summaryrefslogtreecommitdiffstats
path: root/o3d
diff options
context:
space:
mode:
Diffstat (limited to 'o3d')
-rw-r--r--o3d/DEPS193
-rw-r--r--o3d/DEPS_chrome72
-rwxr-xr-xo3d/PRESUBMIT.py109
-rw-r--r--o3d/README4
-rw-r--r--o3d/base/cross/bits.h76
-rw-r--r--o3d/base/cross/bits_test.cc78
-rw-r--r--o3d/base/cross/std_functional.h76
-rw-r--r--o3d/breakpad/breakpad.gyp99
-rw-r--r--o3d/breakpad/linux/breakpad.cc166
-rw-r--r--o3d/breakpad/linux/breakpad.h126
-rw-r--r--o3d/breakpad/win/bluescreen_detector.cc332
-rw-r--r--o3d/breakpad/win/bluescreen_detector.h219
-rw-r--r--o3d/breakpad/win/bluescreen_detector_test.cc322
-rw-r--r--o3d/breakpad/win/breakpad_config.cc78
-rw-r--r--o3d/breakpad/win/breakpad_config.h57
-rw-r--r--o3d/breakpad/win/crash_sender_win32.cc153
-rw-r--r--o3d/breakpad/win/exception_handler_win32.cc210
-rw-r--r--o3d/breakpad/win/exception_handler_win32.h76
-rw-r--r--o3d/build/branding.gypi23
-rw-r--r--o3d/build/cairo.gyp176
-rw-r--r--o3d/build/common.gypi264
-rw-r--r--o3d/build/common_global.gypi58
-rw-r--r--o3d/build/file_exists.py10
-rwxr-xr-xo3d/build/gyp_o3d33
-rw-r--r--o3d/build/is_admin.py59
-rw-r--r--o3d/build/libs.gyp408
-rw-r--r--o3d/build/misc/cairo-features.h10
-rw-r--r--o3d/build/nacl.gyp6
-rw-r--r--o3d/build/o3d.gyp15
-rw-r--r--o3d/build/o3d_all.gyp54
-rw-r--r--o3d/build/o3d_in_chrome.gyp29
-rw-r--r--o3d/build/o3d_minimal.gyp18
-rw-r--r--o3d/build/pixman.gyp103
-rw-r--r--o3d/build/pkg-config.gyp54
-rw-r--r--o3d/build/select_dependencies.py17
-rw-r--r--o3d/build/version.gypi9
-rwxr-xr-xo3d/cg_to_glsl/convert.py284
-rw-r--r--o3d/codereview.settings10
-rw-r--r--o3d/collada_edge/README.collada_edge25
-rw-r--r--o3d/collada_edge/collada_edge.vcproj225
-rw-r--r--o3d/collada_edge/cross/collada_edge.cpp87
-rw-r--r--o3d/collada_edge/cross/conditioner.cpp371
-rw-r--r--o3d/collada_edge/cross/conditioner.h121
-rw-r--r--o3d/collada_edge/cross/precompile.cpp32
-rw-r--r--o3d/collada_edge/cross/precompile.h54
-rw-r--r--o3d/collada_edge/cross/utility.h45
-rw-r--r--o3d/compiler/glsl_validator/Makefile34
-rw-r--r--o3d/compiler/glsl_validator/build.xml89
-rw-r--r--o3d/compiler/glsl_validator/glsl_es/GLSL_ES.g667
-rw-r--r--o3d/compiler/glsl_validator/glsl_es/GLSL_ES.l221
-rw-r--r--o3d/compiler/glsl_validator/glsl_es/GLSL_ES.y607
-rw-r--r--o3d/compiler/glsl_validator/shaders/ambient.frag10
-rw-r--r--o3d/compiler/glsl_validator/shaders/ambient.vert11
-rw-r--r--o3d/compiler/glsl_validator/shaders/diffuse.frag22
-rw-r--r--o3d/compiler/glsl_validator/shaders/diffuse.vert28
-rw-r--r--o3d/compiler/glsl_validator/shaders/many-planets-deep.frag11
-rw-r--r--o3d/compiler/glsl_validator/shaders/many-planets-deep.vert19
-rw-r--r--o3d/compiler/glsl_validator/shaders/nvidia-vertex-buffer-object.frag5
-rw-r--r--o3d/compiler/glsl_validator/shaders/nvidia-vertex-buffer-object.vert48
-rw-r--r--o3d/compiler/glsl_validator/shaders/particles-2d.vert69
-rw-r--r--o3d/compiler/glsl_validator/shaders/particles-3d.vert87
-rw-r--r--o3d/compiler/glsl_validator/shaders/particles.frag17
-rw-r--r--o3d/compiler/glsl_validator/shaders/san-angeles-fade.vert10
-rw-r--r--o3d/compiler/glsl_validator/shaders/san-angeles-flat.frag4
-rw-r--r--o3d/compiler/glsl_validator/shaders/san-angeles-flat.vert8
-rw-r--r--o3d/compiler/glsl_validator/shaders/san-angeles-lit.vert50
-rw-r--r--o3d/compiler/glsl_validator/shaders/shiny-teapot.frag23
-rw-r--r--o3d/compiler/glsl_validator/shaders/shiny-teapot.vert26
-rw-r--r--o3d/compiler/glsl_validator/shaders/spirit-box.frag12
-rw-r--r--o3d/compiler/glsl_validator/shaders/spirit-box.vert18
-rw-r--r--o3d/compiler/glsl_validator/shaders/spore-view.frag12
-rw-r--r--o3d/compiler/glsl_validator/shaders/spore-view.vert19
-rw-r--r--o3d/compiler/glsl_validator/shaders/teapot-per-pixel.frag46
-rw-r--r--o3d/compiler/glsl_validator/shaders/teapot-per-pixel.vert96
-rw-r--r--o3d/compiler/glsl_validator/shaders/teapot-per-vertex.frag11
-rw-r--r--o3d/compiler/glsl_validator/shaders/teapot-per-vertex.vert106
-rw-r--r--o3d/compiler/glsl_validator/shaders/texture_mapping.frag12
-rw-r--r--o3d/compiler/glsl_validator/shaders/texture_mapping.vert18
-rw-r--r--o3d/compiler/glsl_validator/test/Main.java62
-rw-r--r--o3d/compiler/hlsl/HLSL.g1020
-rw-r--r--o3d/compiler/puritan/exp_gen.cc934
-rw-r--r--o3d/compiler/puritan/exp_gen.h331
-rw-r--r--o3d/compiler/puritan/knobs.cc783
-rw-r--r--o3d/compiler/puritan/knobs.h268
-rw-r--r--o3d/compiler/puritan/main.cc129
-rw-r--r--o3d/compiler/puritan/puritan.cc1619
-rw-r--r--o3d/compiler/puritan/puritan.h259
-rw-r--r--o3d/compiler/puritan/puritan_assert.cc51
-rw-r--r--o3d/compiler/puritan/puritan_assert.h83
-rw-r--r--o3d/compiler/puritan/puritan_shared_ptr.h292
-rw-r--r--o3d/compiler/puritan/rand.cc150
-rw-r--r--o3d/compiler/puritan/rand.h73
-rw-r--r--o3d/compiler/puritan/structure_gen.cc328
-rw-r--r--o3d/compiler/puritan/structure_gen.h204
-rw-r--r--o3d/compiler/puritan/test_gen.cc50
-rw-r--r--o3d/compiler/puritan/test_gen.h47
-rw-r--r--o3d/compiler/technique/Technique.g3pl1126
-rw-r--r--o3d/compiler/technique/technique.gyp109
-rw-r--r--o3d/compiler/technique/technique_error.cc283
-rw-r--r--o3d/compiler/technique/technique_error.h60
-rw-r--r--o3d/compiler/technique/technique_parser.cc228
-rw-r--r--o3d/compiler/technique/technique_parser.h130
-rw-r--r--o3d/compiler/technique/technique_parser_test.cc414
-rw-r--r--o3d/compiler/technique/technique_structures.cc87
-rw-r--r--o3d/compiler/technique/technique_structures.h132
-rw-r--r--o3d/compiler/technique/test_data/HLSL_declarations.fx30
-rw-r--r--o3d/compiler/technique/test_data/fur.fx121
-rw-r--r--o3d/compiler/technique/test_data/lambert.fx38
-rw-r--r--o3d/compiler/technique/test_data/noshader.fx8
-rw-r--r--o3d/compiler/technique/test_data/notechnique.fx7
-rw-r--r--o3d/compiler/technique/test_data/sampler_test.fx54
-rw-r--r--o3d/compiler/technique/test_data/shadow_map.fx170
-rw-r--r--o3d/compiler/technique/test_data/simple.fx13
-rw-r--r--o3d/converter/README.converter76
-rw-r--r--o3d/converter/README.verifier32
-rw-r--r--o3d/converter/converter.gyp144
-rw-r--r--o3d/converter/cross/buffer_stub.cc87
-rw-r--r--o3d/converter/cross/buffer_stub.h112
-rw-r--r--o3d/converter/cross/converter.cc576
-rw-r--r--o3d/converter/cross/converter.h127
-rw-r--r--o3d/converter/cross/converter_main.cc181
-rw-r--r--o3d/converter/cross/draw_element_stub.h58
-rw-r--r--o3d/converter/cross/effect_stub.h73
-rw-r--r--o3d/converter/cross/param_cache_stub.h69
-rw-r--r--o3d/converter/cross/primitive_stub.h70
-rw-r--r--o3d/converter/cross/render_surface_stub.h75
-rw-r--r--o3d/converter/cross/renderer_stub.cc214
-rw-r--r--o3d/converter/cross/renderer_stub.h140
-rw-r--r--o3d/converter/cross/sampler_stub.h53
-rw-r--r--o3d/converter/cross/stream_bank_stub.h51
-rw-r--r--o3d/converter/cross/texture_stub.cc51
-rw-r--r--o3d/converter/cross/texture_stub.h161
-rw-r--r--o3d/converter/cross/verifier_main.cc106
-rwxr-xr-xo3d/converter/mac/converter_install_name.sh10
-rw-r--r--o3d/converter/mac/converter_main.mm49
-rw-r--r--o3d/converter_edge/README.converter_edge59
-rw-r--r--o3d/converter_edge/cross/buffer_stub.cc87
-rw-r--r--o3d/converter_edge/cross/buffer_stub.h112
-rw-r--r--o3d/converter_edge/cross/converter.cc639
-rw-r--r--o3d/converter_edge/cross/converter.h139
-rw-r--r--o3d/converter_edge/cross/converter_main.cc180
-rw-r--r--o3d/converter_edge/cross/draw_element_stub.h58
-rw-r--r--o3d/converter_edge/cross/effect_stub.h73
-rw-r--r--o3d/converter_edge/cross/param_cache_stub.h69
-rw-r--r--o3d/converter_edge/cross/primitive_stub.h71
-rw-r--r--o3d/converter_edge/cross/render_surface_stub.h75
-rw-r--r--o3d/converter_edge/cross/renderer_stub.cc204
-rw-r--r--o3d/converter_edge/cross/renderer_stub.h123
-rw-r--r--o3d/converter_edge/cross/sampler_stub.h53
-rw-r--r--o3d/converter_edge/cross/stream_bank_stub.h51
-rw-r--r--o3d/converter_edge/cross/texture_stub.cc51
-rw-r--r--o3d/converter_edge/cross/texture_stub.h174
-rw-r--r--o3d/converter_edge/cross/verifier_main.cc106
-rw-r--r--o3d/converter_edge/mac/converter_main.mm49
-rw-r--r--o3d/core/core.gyp560
-rw-r--r--o3d/core/cross/bitmap.cc567
-rw-r--r--o3d/core/cross/bitmap.h406
-rw-r--r--o3d/core/cross/bitmap_dds.cc512
-rw-r--r--o3d/core/cross/bitmap_jpg.cc276
-rw-r--r--o3d/core/cross/bitmap_png.cc356
-rw-r--r--o3d/core/cross/bitmap_test.cc1247
-rw-r--r--o3d/core/cross/bitmap_tga.cc145
-rw-r--r--o3d/core/cross/bounding_box.cc303
-rw-r--r--o3d/core/cross/bounding_box.h182
-rw-r--r--o3d/core/cross/bounding_box_test.cc243
-rw-r--r--o3d/core/cross/buffer.cc620
-rw-r--r--o3d/core/cross/buffer.h397
-rw-r--r--o3d/core/cross/buffer_test.cc589
-rw-r--r--o3d/core/cross/cairo/install_check.cc42
-rw-r--r--o3d/core/cross/cairo/layer.cc87
-rw-r--r--o3d/core/cross/cairo/layer.h327
-rw-r--r--o3d/core/cross/cairo/pattern.cc166
-rw-r--r--o3d/core/cross/cairo/pattern.h138
-rw-r--r--o3d/core/cross/cairo/renderer_cairo.cc948
-rw-r--r--o3d/core/cross/cairo/renderer_cairo.h285
-rw-r--r--o3d/core/cross/cairo/texture_cairo.cc296
-rw-r--r--o3d/core/cross/cairo/texture_cairo.h128
-rw-r--r--o3d/core/cross/callback.h348
-rw-r--r--o3d/core/cross/canvas.cc277
-rw-r--r--o3d/core/cross/canvas.h204
-rw-r--r--o3d/core/cross/canvas_paint.cc272
-rw-r--r--o3d/core/cross/canvas_paint.h268
-rw-r--r--o3d/core/cross/canvas_shader.cc145
-rw-r--r--o3d/core/cross/canvas_shader.h166
-rw-r--r--o3d/core/cross/canvas_utils.h51
-rw-r--r--o3d/core/cross/class_manager.cc276
-rw-r--r--o3d/core/cross/class_manager.h109
-rw-r--r--o3d/core/cross/class_manager_test.cc140
-rw-r--r--o3d/core/cross/clear_buffer.cc89
-rw-r--r--o3d/core/cross/clear_buffer.h145
-rw-r--r--o3d/core/cross/client.cc662
-rw-r--r--o3d/core/cross/client.h550
-rw-r--r--o3d/core/cross/client_info.cc67
-rw-r--r--o3d/core/cross/client_info.h154
-rw-r--r--o3d/core/cross/client_info_test.cc174
-rw-r--r--o3d/core/cross/client_test.cc555
-rw-r--r--o3d/core/cross/core_metrics.cc52
-rw-r--r--o3d/core/cross/core_metrics.h60
-rw-r--r--o3d/core/cross/counter.cc563
-rw-r--r--o3d/core/cross/counter.h402
-rw-r--r--o3d/core/cross/counter_manager.cc142
-rw-r--r--o3d/core/cross/counter_manager.h126
-rw-r--r--o3d/core/cross/counter_test.cc652
-rw-r--r--o3d/core/cross/cursor.h70
-rw-r--r--o3d/core/cross/curve.cc815
-rw-r--r--o3d/core/cross/curve.h470
-rw-r--r--o3d/core/cross/curve_test.cc886
-rw-r--r--o3d/core/cross/ddsurfacedesc.h231
-rw-r--r--o3d/core/cross/display_mode.h115
-rw-r--r--o3d/core/cross/display_window.h56
-rw-r--r--o3d/core/cross/draw_context.cc69
-rw-r--r--o3d/core/cross/draw_context.h120
-rw-r--r--o3d/core/cross/draw_element.cc81
-rw-r--r--o3d/core/cross/draw_element.h94
-rw-r--r--o3d/core/cross/draw_element_test.cc78
-rw-r--r--o3d/core/cross/draw_list.cc270
-rw-r--r--o3d/core/cross/draw_list.h155
-rw-r--r--o3d/core/cross/draw_list_manager.cc79
-rw-r--r--o3d/core/cross/draw_list_manager.h81
-rw-r--r--o3d/core/cross/draw_list_test.cc82
-rw-r--r--o3d/core/cross/draw_pass.cc67
-rw-r--r--o3d/core/cross/draw_pass.h103
-rw-r--r--o3d/core/cross/draw_pass_test.cc82
-rw-r--r--o3d/core/cross/effect.cc245
-rw-r--r--o3d/core/cross/effect.h279
-rw-r--r--o3d/core/cross/effect_test.cc505
-rw-r--r--o3d/core/cross/element.cc121
-rw-r--r--o3d/core/cross/element.h250
-rw-r--r--o3d/core/cross/element_test.cc327
-rw-r--r--o3d/core/cross/error.h56
-rw-r--r--o3d/core/cross/error_status.cc100
-rw-r--r--o3d/core/cross/error_status.h164
-rw-r--r--o3d/core/cross/error_stream_manager.cc61
-rw-r--r--o3d/core/cross/error_stream_manager.h73
-rw-r--r--o3d/core/cross/evaluation_counter.cc40
-rw-r--r--o3d/core/cross/evaluation_counter.h68
-rw-r--r--o3d/core/cross/event.cc102
-rw-r--r--o3d/core/cross/event.h416
-rw-r--r--o3d/core/cross/event_callback.h48
-rw-r--r--o3d/core/cross/event_manager.cc165
-rw-r--r--o3d/core/cross/event_manager.h108
-rw-r--r--o3d/core/cross/event_manager_test.cc78
-rw-r--r--o3d/core/cross/fake_vertex_source.cc181
-rw-r--r--o3d/core/cross/fake_vertex_source.h122
-rw-r--r--o3d/core/cross/features.cc137
-rw-r--r--o3d/core/cross/features.h122
-rw-r--r--o3d/core/cross/features_test.cc278
-rw-r--r--o3d/core/cross/field.cc618
-rw-r--r--o3d/core/cross/field.h397
-rw-r--r--o3d/core/cross/field_test.cc520
-rw-r--r--o3d/core/cross/file_request.cc64
-rw-r--r--o3d/core/cross/file_request.h180
-rw-r--r--o3d/core/cross/float_n.h212
-rw-r--r--o3d/core/cross/float_n_test.cc47
-rw-r--r--o3d/core/cross/function.cc100
-rw-r--r--o3d/core/cross/function.h172
-rw-r--r--o3d/core/cross/function_test.cc197
-rw-r--r--o3d/core/cross/gl/buffer_gl.cc253
-rw-r--r--o3d/core/cross/gl/buffer_gl.h120
-rw-r--r--o3d/core/cross/gl/draw_element_gl.cc46
-rw-r--r--o3d/core/cross/gl/draw_element_gl.h57
-rw-r--r--o3d/core/cross/gl/effect_gl.cc632
-rw-r--r--o3d/core/cross/gl/effect_gl.h147
-rw-r--r--o3d/core/cross/gl/gl_headers.h43
-rw-r--r--o3d/core/cross/gl/install_check.cc41
-rw-r--r--o3d/core/cross/gl/param_cache_gl.cc762
-rw-r--r--o3d/core/cross/gl/param_cache_gl.h103
-rw-r--r--o3d/core/cross/gl/primitive_gl.cc258
-rw-r--r--o3d/core/cross/gl/primitive_gl.h63
-rw-r--r--o3d/core/cross/gl/render_surface_gl.cc125
-rw-r--r--o3d/core/cross/gl/render_surface_gl.h109
-rw-r--r--o3d/core/cross/gl/renderer_gl.cc1603
-rw-r--r--o3d/core/cross/gl/renderer_gl.h347
-rw-r--r--o3d/core/cross/gl/sampler_gl.cc217
-rw-r--r--o3d/core/cross/gl/sampler_gl.h65
-rw-r--r--o3d/core/cross/gl/stream_bank_gl.cc201
-rw-r--r--o3d/core/cross/gl/stream_bank_gl.h72
-rw-r--r--o3d/core/cross/gl/texture_gl.cc884
-rw-r--r--o3d/core/cross/gl/texture_gl.h243
-rw-r--r--o3d/core/cross/gl/utils_gl-inl.h69
-rw-r--r--o3d/core/cross/gl/utils_gl.cc228
-rw-r--r--o3d/core/cross/gl/utils_gl.h47
-rw-r--r--o3d/core/cross/glcommon/utils_glcommon-inl.h64
-rw-r--r--o3d/core/cross/gles2/buffer_gles2.cc299
-rw-r--r--o3d/core/cross/gles2/buffer_gles2.h136
-rw-r--r--o3d/core/cross/gles2/draw_element_gles2.cc46
-rw-r--r--o3d/core/cross/gles2/draw_element_gles2.h58
-rw-r--r--o3d/core/cross/gles2/effect_gles2.cc453
-rw-r--r--o3d/core/cross/gles2/effect_gles2.h144
-rw-r--r--o3d/core/cross/gles2/gles2_headers.h153
-rw-r--r--o3d/core/cross/gles2/install_check.cc41
-rw-r--r--o3d/core/cross/gles2/param_cache_gles2.cc743
-rw-r--r--o3d/core/cross/gles2/param_cache_gles2.h96
-rw-r--r--o3d/core/cross/gles2/primitive_gles2.cc260
-rw-r--r--o3d/core/cross/gles2/primitive_gles2.h64
-rw-r--r--o3d/core/cross/gles2/render_surface_gles2.cc143
-rw-r--r--o3d/core/cross/gles2/render_surface_gles2.h111
-rw-r--r--o3d/core/cross/gles2/renderer_gles2.cc1795
-rw-r--r--o3d/core/cross/gles2/renderer_gles2.h380
-rw-r--r--o3d/core/cross/gles2/sampler_gles2.cc232
-rw-r--r--o3d/core/cross/gles2/sampler_gles2.h75
-rw-r--r--o3d/core/cross/gles2/stream_bank_gles2.cc225
-rw-r--r--o3d/core/cross/gles2/stream_bank_gles2.h74
-rw-r--r--o3d/core/cross/gles2/texture_gles2.cc943
-rw-r--r--o3d/core/cross/gles2/texture_gles2.h244
-rw-r--r--o3d/core/cross/gles2/utils_gles2-inl.h50
-rw-r--r--o3d/core/cross/gles2/utils_gles2.cc79
-rw-r--r--o3d/core/cross/gles2/utils_gles2.h46
-rw-r--r--o3d/core/cross/gpu2d/arena.h216
-rw-r--r--o3d/core/cross/gpu2d/arena_test.cc147
-rw-r--r--o3d/core/cross/gpu2d/cubic_classifier.cc126
-rw-r--r--o3d/core/cross/gpu2d/cubic_classifier.h108
-rw-r--r--o3d/core/cross/gpu2d/cubic_classifier_test.cc93
-rw-r--r--o3d/core/cross/gpu2d/cubic_math_utils.cc188
-rw-r--r--o3d/core/cross/gpu2d/cubic_math_utils.h115
-rw-r--r--o3d/core/cross/gpu2d/cubic_texture_coords.cc193
-rw-r--r--o3d/core/cross/gpu2d/cubic_texture_coords.h94
-rw-r--r--o3d/core/cross/gpu2d/interval_tree.h283
-rw-r--r--o3d/core/cross/gpu2d/interval_tree_test.cc215
-rw-r--r--o3d/core/cross/gpu2d/local_triangulator.cc302
-rw-r--r--o3d/core/cross/gpu2d/local_triangulator.h255
-rw-r--r--o3d/core/cross/gpu2d/local_triangulator_test.cc134
-rw-r--r--o3d/core/cross/gpu2d/path_cache.cc105
-rw-r--r--o3d/core/cross/gpu2d/path_cache.h120
-rw-r--r--o3d/core/cross/gpu2d/path_processor.cc1370
-rw-r--r--o3d/core/cross/gpu2d/path_processor.h126
-rw-r--r--o3d/core/cross/gpu2d/red_black_tree.h763
-rw-r--r--o3d/core/cross/gpu2d/red_black_tree_test.cc189
-rw-r--r--o3d/core/cross/gpu2d/tree_test_helpers.cc63
-rw-r--r--o3d/core/cross/gpu2d/tree_test_helpers.h60
-rw-r--r--o3d/core/cross/iclass_manager.cc40
-rw-r--r--o3d/core/cross/iclass_manager.h159
-rw-r--r--o3d/core/cross/id_manager.cc43
-rw-r--r--o3d/core/cross/id_manager.h52
-rw-r--r--o3d/core/cross/ierror_status.cc40
-rw-r--r--o3d/core/cross/ierror_status.h99
-rw-r--r--o3d/core/cross/image_utils.cc906
-rw-r--r--o3d/core/cross/image_utils.h288
-rw-r--r--o3d/core/cross/image_utils_test.cc592
-rw-r--r--o3d/core/cross/imain_thread_task_poster.cc40
-rw-r--r--o3d/core/cross/imain_thread_task_poster.h57
-rw-r--r--o3d/core/cross/install_check.h51
-rw-r--r--o3d/core/cross/lost_resource_callback.h45
-rw-r--r--o3d/core/cross/material.cc66
-rw-r--r--o3d/core/cross/material.h127
-rw-r--r--o3d/core/cross/material_test.cc109
-rw-r--r--o3d/core/cross/math_types.h77
-rw-r--r--o3d/core/cross/math_utilities.cc233
-rw-r--r--o3d/core/cross/math_utilities.h85
-rw-r--r--o3d/core/cross/math_utilities_test.cc48
-rw-r--r--o3d/core/cross/matrix4_axis_rotation.cc70
-rw-r--r--o3d/core/cross/matrix4_axis_rotation.h105
-rw-r--r--o3d/core/cross/matrix4_axis_rotation_test.cc83
-rw-r--r--o3d/core/cross/matrix4_composition.cc66
-rw-r--r--o3d/core/cross/matrix4_composition.h95
-rw-r--r--o3d/core/cross/matrix4_composition_test.cc81
-rw-r--r--o3d/core/cross/matrix4_scale.cc66
-rw-r--r--o3d/core/cross/matrix4_scale.h95
-rw-r--r--o3d/core/cross/matrix4_scale_test.cc81
-rw-r--r--o3d/core/cross/matrix4_translation.cc65
-rw-r--r--o3d/core/cross/matrix4_translation.h95
-rw-r--r--o3d/core/cross/matrix4_translation_test.cc81
-rw-r--r--o3d/core/cross/message_commands.cc49
-rw-r--r--o3d/core/cross/message_commands.h430
-rw-r--r--o3d/core/cross/message_commands_test.cc170
-rw-r--r--o3d/core/cross/message_queue.cc891
-rw-r--r--o3d/core/cross/message_queue.h229
-rw-r--r--o3d/core/cross/message_queue_test.cc1310
-rw-r--r--o3d/core/cross/named_object.cc55
-rw-r--r--o3d/core/cross/named_object.h84
-rw-r--r--o3d/core/cross/object_base.cc93
-rw-r--r--o3d/core/cross/object_base.h243
-rw-r--r--o3d/core/cross/object_base_test.cc83
-rw-r--r--o3d/core/cross/object_manager.cc141
-rw-r--r--o3d/core/cross/object_manager.h209
-rw-r--r--o3d/core/cross/pack.cc496
-rw-r--r--o3d/core/cross/pack.h459
-rw-r--r--o3d/core/cross/pack_test.cc181
-rw-r--r--o3d/core/cross/param.cc380
-rw-r--r--o3d/core/cross/param.h706
-rw-r--r--o3d/core/cross/param_array.cc169
-rw-r--r--o3d/core/cross/param_array.h186
-rw-r--r--o3d/core/cross/param_array_test.cc181
-rw-r--r--o3d/core/cross/param_cache.cc128
-rw-r--r--o3d/core/cross/param_cache.h154
-rw-r--r--o3d/core/cross/param_object.cc313
-rw-r--r--o3d/core/cross/param_object.h446
-rw-r--r--o3d/core/cross/param_object_test.cc489
-rw-r--r--o3d/core/cross/param_operation.cc294
-rw-r--r--o3d/core/cross/param_operation.h523
-rw-r--r--o3d/core/cross/param_operation_test.cc479
-rw-r--r--o3d/core/cross/param_test.cc766
-rw-r--r--o3d/core/cross/performance_timer.h100
-rw-r--r--o3d/core/cross/performance_timer_test.cc79
-rw-r--r--o3d/core/cross/pointer_utils.h58
-rw-r--r--o3d/core/cross/precompile.cc32
-rw-r--r--o3d/core/cross/precompile.h50
-rw-r--r--o3d/core/cross/primitive.cc707
-rw-r--r--o3d/core/cross/primitive.h225
-rw-r--r--o3d/core/cross/primitive_test.cc117
-rw-r--r--o3d/core/cross/processed_path.cc159
-rw-r--r--o3d/core/cross/processed_path.h115
-rw-r--r--o3d/core/cross/profiler.cc52
-rw-r--r--o3d/core/cross/profiler.h93
-rw-r--r--o3d/core/cross/ray_intersection_info.cc94
-rw-r--r--o3d/core/cross/ray_intersection_info.h128
-rw-r--r--o3d/core/cross/ray_intersection_info_test.cc130
-rw-r--r--o3d/core/cross/render_context.cc45
-rw-r--r--o3d/core/cross/render_context.h93
-rw-r--r--o3d/core/cross/render_event.h174
-rw-r--r--o3d/core/cross/render_node.cc335
-rw-r--r--o3d/core/cross/render_node.h227
-rw-r--r--o3d/core/cross/render_node_test.cc135
-rw-r--r--o3d/core/cross/render_surface.cc118
-rw-r--r--o3d/core/cross/render_surface.h225
-rw-r--r--o3d/core/cross/render_surface_set.cc112
-rw-r--r--o3d/core/cross/render_surface_set.h114
-rw-r--r--o3d/core/cross/render_surface_test.cc273
-rw-r--r--o3d/core/cross/renderer.cc834
-rw-r--r--o3d/core/cross/renderer.h799
-rw-r--r--o3d/core/cross/renderer_platform.h82
-rw-r--r--o3d/core/cross/renderer_test.cc191
-rw-r--r--o3d/core/cross/sampler.cc127
-rw-r--r--o3d/core/cross/sampler.h207
-rw-r--r--o3d/core/cross/semantic_manager.cc71
-rw-r--r--o3d/core/cross/semantic_manager.h87
-rw-r--r--o3d/core/cross/service_dependency.h83
-rw-r--r--o3d/core/cross/service_implementation.h71
-rw-r--r--o3d/core/cross/service_interface_traits.h64
-rw-r--r--o3d/core/cross/service_locator.cc80
-rw-r--r--o3d/core/cross/service_locator.h131
-rw-r--r--o3d/core/cross/service_locator_test.cc115
-rw-r--r--o3d/core/cross/shape.cc111
-rw-r--r--o3d/core/cross/shape.h118
-rw-r--r--o3d/core/cross/shape_test.cc93
-rw-r--r--o3d/core/cross/skin.cc649
-rw-r--r--o3d/core/cross/skin.h385
-rw-r--r--o3d/core/cross/skin_test.cc720
-rw-r--r--o3d/core/cross/smart_ptr.h173
-rw-r--r--o3d/core/cross/smart_ptr_test.cc167
-rw-r--r--o3d/core/cross/standard_param.cc178
-rw-r--r--o3d/core/cross/standard_param.h174
-rw-r--r--o3d/core/cross/state.cc167
-rw-r--r--o3d/core/cross/state.h214
-rw-r--r--o3d/core/cross/state_set.cc62
-rw-r--r--o3d/core/cross/state_set.h85
-rw-r--r--o3d/core/cross/state_set_test.cc77
-rw-r--r--o3d/core/cross/state_test.cc102
-rw-r--r--o3d/core/cross/stream.cc102
-rw-r--r--o3d/core/cross/stream.h181
-rw-r--r--o3d/core/cross/stream_bank.cc187
-rw-r--r--o3d/core/cross/stream_bank.h185
-rw-r--r--o3d/core/cross/stream_bank_test.cc296
-rw-r--r--o3d/core/cross/stream_test.cc106
-rw-r--r--o3d/core/cross/texture.cc788
-rw-r--r--o3d/core/cross/texture.h459
-rw-r--r--o3d/core/cross/texture_base.cc88
-rw-r--r--o3d/core/cross/texture_base.h203
-rw-r--r--o3d/core/cross/texture_base_test.cc101
-rw-r--r--o3d/core/cross/texture_test.cc201
-rw-r--r--o3d/core/cross/tick_event.h71
-rw-r--r--o3d/core/cross/timer.cc114
-rw-r--r--o3d/core/cross/timer.h84
-rw-r--r--o3d/core/cross/timingtable.h192
-rw-r--r--o3d/core/cross/transform.cc375
-rw-r--r--o3d/core/cross/transform.h331
-rw-r--r--o3d/core/cross/transform_test.cc611
-rw-r--r--o3d/core/cross/transformation_context.cc40
-rw-r--r--o3d/core/cross/transformation_context.h120
-rw-r--r--o3d/core/cross/tree_traversal.cc362
-rw-r--r--o3d/core/cross/tree_traversal.h216
-rw-r--r--o3d/core/cross/tree_traversal_test.cc99
-rw-r--r--o3d/core/cross/types.h148
-rw-r--r--o3d/core/cross/vector_map.h382
-rw-r--r--o3d/core/cross/vector_map_test.cc258
-rw-r--r--o3d/core/cross/vertex_source.cc73
-rw-r--r--o3d/core/cross/vertex_source.h91
-rw-r--r--o3d/core/cross/vertex_source_test.cc294
-rw-r--r--o3d/core/cross/viewport.cc69
-rw-r--r--o3d/core/cross/viewport.h108
-rw-r--r--o3d/core/cross/visitor_base.h154
-rw-r--r--o3d/core/cross/visitor_base_test.cc165
-rw-r--r--o3d/core/cross/weak_ptr.h166
-rw-r--r--o3d/core/cross/weak_ptr_test.cc169
-rw-r--r--o3d/core/linux/display_window_linux.h66
-rw-r--r--o3d/core/linux/performance_timer.cc80
-rw-r--r--o3d/core/mac/display_window_mac.h85
-rw-r--r--o3d/core/mac/performance_timer.cc74
-rw-r--r--o3d/core/win/core_unittests.sln39
-rw-r--r--o3d/core/win/d3d9/buffer_d3d9.cc221
-rw-r--r--o3d/core/win/d3d9/buffer_d3d9.h123
-rw-r--r--o3d/core/win/d3d9/d3d_entry_points.h140
-rw-r--r--o3d/core/win/d3d9/draw_element_d3d9.cc48
-rw-r--r--o3d/core/win/d3d9/draw_element_d3d9.h53
-rw-r--r--o3d/core/win/d3d9/effect_d3d9.cc1224
-rw-r--r--o3d/core/win/d3d9/effect_d3d9.h203
-rw-r--r--o3d/core/win/d3d9/install_check.cc258
-rw-r--r--o3d/core/win/d3d9/param_cache_d3d9.cc83
-rw-r--r--o3d/core/win/d3d9/param_cache_d3d9.h74
-rw-r--r--o3d/core/win/d3d9/primitive_d3d9.cc231
-rw-r--r--o3d/core/win/d3d9/primitive_d3d9.h66
-rw-r--r--o3d/core/win/d3d9/render_surface_d3d9.cc153
-rw-r--r--o3d/core/win/d3d9/render_surface_d3d9.h120
-rw-r--r--o3d/core/win/d3d9/renderer_d3d9.cc1747
-rw-r--r--o3d/core/win/d3d9/renderer_d3d9.h284
-rw-r--r--o3d/core/win/d3d9/sampler_d3d9.cc202
-rw-r--r--o3d/core/win/d3d9/sampler_d3d9.h72
-rw-r--r--o3d/core/win/d3d9/software_renderer_d3d9.h46
-rw-r--r--o3d/core/win/d3d9/stream_bank_d3d9.cc185
-rw-r--r--o3d/core/win/d3d9/stream_bank_d3d9.h81
-rw-r--r--o3d/core/win/d3d9/texture_d3d9.cc997
-rw-r--r--o3d/core/win/d3d9/texture_d3d9.h213
-rw-r--r--o3d/core/win/d3d9/utils_d3d9.cc119
-rw-r--r--o3d/core/win/d3d9/utils_d3d9.h72
-rw-r--r--o3d/core/win/display_window_win.h60
-rw-r--r--o3d/core/win/performance_timer.cc79
-rw-r--r--o3d/documentation/Doxyfile293
-rw-r--r--o3d/documentation/DoxygenLayout.xml182
-rwxr-xr-xo3d/documentation/build_docs.bat33
-rwxr-xr-xo3d/documentation/build_docs.py354
-rw-r--r--o3d/documentation/classtree.bat33
-rw-r--r--o3d/documentation/classtree.py166
-rw-r--r--o3d/documentation/documentation.gyp115
-rw-r--r--o3d/documentation/externs/externs.js1859
-rw-r--r--o3d/documentation/externs/o3d-extra-externs.js55
-rw-r--r--o3d/documentation/ezt_formatter.bat33
-rw-r--r--o3d/documentation/ezt_formatter.py351
-rw-r--r--o3d/documentation/ezt_formatter_test.py197
-rw-r--r--o3d/documentation/ezt_formatter_unittest.bat33
-rw-r--r--o3d/documentation/footer.html10
-rw-r--r--o3d/documentation/get_docs_files.py52
-rw-r--r--o3d/documentation/header.html29
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/annotated.tmpl27
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/class.tmpl419
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/classtree.tmpl15
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/dot.tmpl21
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/exports.tmpl33
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/filelist.tmpl7
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/members.tmpl65
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/namespaces.tmpl26
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/publish.js1255
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/static/footer.html10
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/static/header.html30
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/static/prettify.css34
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/static/prettify.js23
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/static/stylesheet.css246
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/static/tab_b.gifbin35 -> 0 bytes
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/static/tab_l.gifbin706 -> 0 bytes
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/static/tab_r.gifbin2585 -> 0 bytes
-rw-r--r--o3d/documentation/jsdoc-toolkit-templates/static/tabs.css102
-rw-r--r--o3d/google_update/google_update.gyp32
-rw-r--r--o3d/google_update/google_update_idl.idl243
-rw-r--r--o3d/google_update/performondemand.cc546
-rw-r--r--o3d/google_update/performondemand.h193
-rwxr-xr-xo3d/gypbuild40
-rw-r--r--o3d/gypbuild.bat33
-rwxr-xr-xo3d/gypbuild.py292
-rw-r--r--o3d/import/archive.gyp94
-rw-r--r--o3d/import/cross/archive_processor.cc88
-rw-r--r--o3d/import/cross/archive_processor.h97
-rw-r--r--o3d/import/cross/archive_request.cc255
-rw-r--r--o3d/import/cross/archive_request.h208
-rw-r--r--o3d/import/cross/camera_info.cc98
-rw-r--r--o3d/import/cross/camera_info.h221
-rw-r--r--o3d/import/cross/camera_info_test.cc222
-rw-r--r--o3d/import/cross/collada.cc3079
-rw-r--r--o3d/import/cross/collada.h507
-rw-r--r--o3d/import/cross/collada_conditioner.cc578
-rw-r--r--o3d/import/cross/collada_conditioner.h136
-rw-r--r--o3d/import/cross/collada_conditioner_stub.cc90
-rw-r--r--o3d/import/cross/collada_zip_archive.cc80
-rw-r--r--o3d/import/cross/collada_zip_archive.h73
-rw-r--r--o3d/import/cross/destination_buffer.cc79
-rw-r--r--o3d/import/cross/destination_buffer.h83
-rw-r--r--o3d/import/cross/destination_buffer_test.cc104
-rw-r--r--o3d/import/cross/file_output_stream_processor.cc61
-rw-r--r--o3d/import/cross/file_output_stream_processor.h57
-rw-r--r--o3d/import/cross/gz_compressor.cc149
-rw-r--r--o3d/import/cross/gz_compressor.h73
-rw-r--r--o3d/import/cross/gz_compressor_test.cc202
-rw-r--r--o3d/import/cross/gz_decompressor.cc130
-rw-r--r--o3d/import/cross/gz_decompressor.h66
-rw-r--r--o3d/import/cross/gz_decompressor_test.cc171
-rw-r--r--o3d/import/cross/iarchive_generator.h65
-rw-r--r--o3d/import/cross/json_object.cc66
-rw-r--r--o3d/import/cross/json_object.h289
-rw-r--r--o3d/import/cross/json_object_test.cc448
-rw-r--r--o3d/import/cross/main_thread_archive_callback_client.cc138
-rw-r--r--o3d/import/cross/main_thread_archive_callback_client.h85
-rw-r--r--o3d/import/cross/main_thread_archive_callback_client_test.cc219
-rw-r--r--o3d/import/cross/memory_buffer.h78
-rw-r--r--o3d/import/cross/memory_buffer_test.cc98
-rw-r--r--o3d/import/cross/memory_stream.cc401
-rw-r--r--o3d/import/cross/memory_stream.h288
-rw-r--r--o3d/import/cross/memory_stream_test.cc329
-rw-r--r--o3d/import/cross/precompile.cc33
-rw-r--r--o3d/import/cross/precompile.h116
-rw-r--r--o3d/import/cross/raw_data.cc291
-rw-r--r--o3d/import/cross/raw_data.h121
-rw-r--r--o3d/import/cross/raw_data_test.cc285
-rw-r--r--o3d/import/cross/tar_generator.cc242
-rw-r--r--o3d/import/cross/tar_generator.h136
-rw-r--r--o3d/import/cross/tar_generator_test.cc445
-rw-r--r--o3d/import/cross/tar_processor.cc177
-rw-r--r--o3d/import/cross/tar_processor.h97
-rw-r--r--o3d/import/cross/tar_processor_test.cc186
-rw-r--r--o3d/import/cross/targz_generator.cc64
-rw-r--r--o3d/import/cross/targz_generator.h85
-rw-r--r--o3d/import/cross/targz_generator_test.cc199
-rw-r--r--o3d/import/cross/targz_processor.cc69
-rw-r--r--o3d/import/cross/targz_processor.h67
-rw-r--r--o3d/import/cross/targz_processor_test.cc171
-rw-r--r--o3d/import/cross/threaded_stream_processor.cc116
-rw-r--r--o3d/import/cross/threaded_stream_processor.h72
-rw-r--r--o3d/import/cross/threaded_stream_processor_test.cc155
-rw-r--r--o3d/import/cross/zip_archive.cc891
-rw-r--r--o3d/import/cross/zip_archive.h217
-rw-r--r--o3d/import/import.gyp130
-rw-r--r--o3d/import/linux/collada_conditioner_linux.cc120
-rw-r--r--o3d/import/mac/collada_conditioner_mac.mm105
-rw-r--r--o3d/import/test_data/crate.dae239
-rw-r--r--o3d/import/test_data/crate.jpgbin15135 -> 0 bytes
-rw-r--r--o3d/import/test_data/rock01.tgabin262188 -> 0 bytes
-rw-r--r--o3d/import/test_data/rock02.tgabin196652 -> 0 bytes
-rw-r--r--o3d/import/win/collada_conditioner_win.cc154
-rw-r--r--o3d/installer/installer.gyp59
-rw-r--r--o3d/installer/linux/debian.in/changelog.in6
-rw-r--r--o3d/installer/linux/debian.in/compat1
-rw-r--r--o3d/installer/linux/debian.in/control26
-rw-r--r--o3d/installer/linux/debian.in/copyright7
-rw-r--r--o3d/installer/linux/debian.in/debian.gyp100
-rw-r--r--o3d/installer/linux/debian.in/google-o3d.install3
-rw-r--r--o3d/installer/linux/debian.in/google-o3d.links8
-rw-r--r--o3d/installer/linux/debian.in/google-o3d.lintian-overrides21
-rw-r--r--o3d/installer/linux/debian.in/mk_changelog.py55
-rwxr-xr-xo3d/installer/linux/debian.in/rules13
-rwxr-xr-xo3d/installer/linux/generic/setup.sh160
-rwxr-xr-xo3d/installer/linux/generic/uninstall.sh111
-rw-r--r--o3d/installer/linux/installer.gyp21
-rw-r--r--o3d/installer/mac/O3D_Stats/English.lproj/InfoPlist.strings5
-rw-r--r--o3d/installer/mac/O3D_Stats/English.lproj/Localizable.strings3
-rw-r--r--o3d/installer/mac/O3D_Stats/English.lproj/O3D_Stats.xib586
-rw-r--r--o3d/installer/mac/O3D_Stats/Info.plist32
-rw-r--r--o3d/installer/mac/O3D_Stats/InstallerSections.plist16
-rw-r--r--o3d/installer/mac/O3D_Stats/O3D_Stats.xcodeproj/project.pbxproj291
-rw-r--r--o3d/installer/mac/O3D_Stats/O3D_StatsPane.h54
-rw-r--r--o3d/installer/mac/O3D_Stats/O3D_StatsPane.m92
-rw-r--r--o3d/installer/mac/O3D_Stats/O3D_Stats_Prefix.pch7
-rw-r--r--o3d/installer/mac/O3D_Stats/version.plist14
-rw-r--r--o3d/installer/mac/installer.gyp57
-rwxr-xr-xo3d/installer/mac/make_disk_image.sh81
-rwxr-xr-xo3d/installer/mac/make_installer.sh71
-rw-r--r--o3d/installer/win/custom_actions.cc466
-rw-r--r--o3d/installer/win/docs.url4
-rw-r--r--o3d/installer/win/driver_blacklist.txt12
-rw-r--r--o3d/installer/win/installer.gyp328
-rw-r--r--o3d/installer/win/o3d.wxs355
-rw-r--r--o3d/installer/win/o3d_sdk.wxs223
-rw-r--r--o3d/installer/win/o3dextras.wxs120
-rw-r--r--o3d/nbguidgen/win/md5.cc254
-rw-r--r--o3d/nbguidgen/win/md5.h46
-rw-r--r--o3d/nbguidgen/win/nbguidgen.cc166
-rw-r--r--o3d/nbguidgen/win/nbguidgen.exebin155648 -> 0 bytes
-rw-r--r--o3d/plugin/cross/archive_request_static_glue.cc214
-rw-r--r--o3d/plugin/cross/archive_request_static_glue.h66
-rw-r--r--o3d/plugin/cross/async_loading.cc288
-rw-r--r--o3d/plugin/cross/async_loading.h67
-rw-r--r--o3d/plugin/cross/blacklist.cc73
-rw-r--r--o3d/plugin/cross/config.h119
-rw-r--r--o3d/plugin/cross/config_common.cc218
-rw-r--r--o3d/plugin/cross/download_stream.h66
-rw-r--r--o3d/plugin/cross/main.cc460
-rw-r--r--o3d/plugin/cross/main.h171
-rw-r--r--o3d/plugin/cross/main_remote_cb.cc210
-rw-r--r--o3d/plugin/cross/main_thread_task_poster.cc62
-rw-r--r--o3d/plugin/cross/main_thread_task_poster.h57
-rw-r--r--o3d/plugin/cross/marshaling_utils.h129
-rw-r--r--o3d/plugin/cross/np_v8_bridge.cc1578
-rw-r--r--o3d/plugin/cross/np_v8_bridge.h414
-rw-r--r--o3d/plugin/cross/o3d_glue.cc1243
-rw-r--r--o3d/plugin/cross/o3d_glue.h568
-rw-r--r--o3d/plugin/cross/out_of_memory.cc239
-rw-r--r--o3d/plugin/cross/out_of_memory.h43
-rw-r--r--o3d/plugin/cross/plugin_logging.h158
-rw-r--r--o3d/plugin/cross/plugin_logging_test.cc228
-rw-r--r--o3d/plugin/cross/plugin_main.h38
-rw-r--r--o3d/plugin/cross/plugin_metrics.h152
-rw-r--r--o3d/plugin/cross/stream_manager.cc356
-rw-r--r--o3d/plugin/cross/stream_manager.h169
-rw-r--r--o3d/plugin/cross/texture_static_glue.cc606
-rw-r--r--o3d/plugin/cross/whitelist.cc213
-rw-r--r--o3d/plugin/cross/whitelist.h44
-rw-r--r--o3d/plugin/idl/archive_request.idl176
-rw-r--r--o3d/plugin/idl/bitmap.idl112
-rw-r--r--o3d/plugin/idl/bounding_box.idl211
-rw-r--r--o3d/plugin/idl/buffer.idl482
-rw-r--r--o3d/plugin/idl/canvas.idl185
-rw-r--r--o3d/plugin/idl/canvas_paint.idl193
-rw-r--r--o3d/plugin/idl/canvas_shader.idl98
-rw-r--r--o3d/plugin/idl/clear_buffer.idl92
-rw-r--r--o3d/plugin/idl/client.idl695
-rw-r--r--o3d/plugin/idl/codegen.py37
-rw-r--r--o3d/plugin/idl/counter.idl253
-rw-r--r--o3d/plugin/idl/cursor.idl82
-rw-r--r--o3d/plugin/idl/curve.idl330
-rw-r--r--o3d/plugin/idl/display_mode.idl64
-rw-r--r--o3d/plugin/idl/draw_context.idl63
-rw-r--r--o3d/plugin/idl/draw_element.idl77
-rw-r--r--o3d/plugin/idl/draw_list.idl56
-rw-r--r--o3d/plugin/idl/draw_pass.idl55
-rw-r--r--o3d/plugin/idl/effect.idl231
-rw-r--r--o3d/plugin/idl/element.idl185
-rw-r--r--o3d/plugin/idl/event.idl186
-rw-r--r--o3d/plugin/idl/field.idl245
-rw-r--r--o3d/plugin/idl/file_request.idl146
-rw-r--r--o3d/plugin/idl/function.idl93
-rw-r--r--o3d/plugin/idl/get_idl_files.py26
-rw-r--r--o3d/plugin/idl/idl.gyp118
-rw-r--r--o3d/plugin/idl/idl_filenames.py24
-rw-r--r--o3d/plugin/idl/layer.idl128
-rw-r--r--o3d/plugin/idl/material.idl63
-rw-r--r--o3d/plugin/idl/matrix4_axis_rotation.idl72
-rw-r--r--o3d/plugin/idl/matrix4_composition.idl66
-rw-r--r--o3d/plugin/idl/matrix4_scale.idl64
-rw-r--r--o3d/plugin/idl/matrix4_translation.idl64
-rw-r--r--o3d/plugin/idl/named.idl120
-rw-r--r--o3d/plugin/idl/pack.idl337
-rw-r--r--o3d/plugin/idl/param.idl336
-rw-r--r--o3d/plugin/idl/param_array.idl149
-rw-r--r--o3d/plugin/idl/param_object.idl164
-rw-r--r--o3d/plugin/idl/param_operation.idl353
-rw-r--r--o3d/plugin/idl/pattern.idl146
-rw-r--r--o3d/plugin/idl/plugin.idl59
-rw-r--r--o3d/plugin/idl/primitive.idl100
-rw-r--r--o3d/plugin/idl/processed_path.idl119
-rw-r--r--o3d/plugin/idl/raw_data.idl88
-rw-r--r--o3d/plugin/idl/ray_intersection_info.idl64
-rw-r--r--o3d/plugin/idl/render_event.idl106
-rw-r--r--o3d/plugin/idl/render_node.idl140
-rw-r--r--o3d/plugin/idl/render_surface.idl105
-rw-r--r--o3d/plugin/idl/render_surface_set.idl67
-rw-r--r--o3d/plugin/idl/sampler.idl143
-rw-r--r--o3d/plugin/idl/shape.idl89
-rw-r--r--o3d/plugin/idl/skin.idl274
-rw-r--r--o3d/plugin/idl/standard_param.idl200
-rw-r--r--o3d/plugin/idl/state.idl288
-rw-r--r--o3d/plugin/idl/state_set.idl51
-rw-r--r--o3d/plugin/idl/stream.idl118
-rw-r--r--o3d/plugin/idl/stream_bank.idl125
-rw-r--r--o3d/plugin/idl/texture.idl564
-rw-r--r--o3d/plugin/idl/tick_event.idl49
-rw-r--r--o3d/plugin/idl/transform.idl385
-rw-r--r--o3d/plugin/idl/tree_traversal.idl74
-rw-r--r--o3d/plugin/idl/types.idl130
-rw-r--r--o3d/plugin/idl/vector.idl216
-rw-r--r--o3d/plugin/idl/vertex_source.idl70
-rw-r--r--o3d/plugin/idl/viewport.idl72
-rw-r--r--o3d/plugin/idl_list.manifest92
-rw-r--r--o3d/plugin/linux/config.cc66
-rw-r--r--o3d/plugin/linux/envvars.cc84
-rw-r--r--o3d/plugin/linux/envvars.h43
-rw-r--r--o3d/plugin/linux/main_linux.cc971
-rw-r--r--o3d/plugin/mac/Info.plist62
-rw-r--r--o3d/plugin/mac/Resources/English.lproj/InfoPlist.strings10
-rwxr-xr-xo3d/plugin/mac/Tools/fix_install_names.sh21
-rw-r--r--o3d/plugin/mac/config_mac.mm361
-rw-r--r--o3d/plugin/mac/fullscreen_window_mac.h84
-rw-r--r--o3d/plugin/mac/fullscreen_window_mac.mm702
-rw-r--r--o3d/plugin/mac/graphics_utils_mac.h62
-rw-r--r--o3d/plugin/mac/graphics_utils_mac.mm150
-rw-r--r--o3d/plugin/mac/main_mac.mm1347
-rw-r--r--o3d/plugin/mac/o3d_layer.h62
-rw-r--r--o3d/plugin/mac/o3d_layer.mm196
-rw-r--r--o3d/plugin/mac/o3d_plugin.r15
-rw-r--r--o3d/plugin/mac/overlay_window_mac.h62
-rw-r--r--o3d/plugin/mac/overlay_window_mac.mm286
-rwxr-xr-xo3d/plugin/mac/plugin_copy_frameworks.sh20
-rwxr-xr-xo3d/plugin/mac/plugin_fix_install_names.sh10
-rw-r--r--o3d/plugin/mac/plugin_logging-mac.mm242
-rw-r--r--o3d/plugin/mac/plugin_mac.h116
-rw-r--r--o3d/plugin/mac/plugin_mac.mm717
-rw-r--r--o3d/plugin/mac/plugin_metrics-mac.cc85
-rw-r--r--o3d/plugin/npapi_host_control/win/dispatch_proxy.cc325
-rw-r--r--o3d/plugin/npapi_host_control/win/dispatch_proxy.h197
-rw-r--r--o3d/plugin/npapi_host_control/win/host_control.cc620
-rw-r--r--o3d/plugin/npapi_host_control/win/host_control.h275
-rw-r--r--o3d/plugin/npapi_host_control/win/host_control.rgs_template42
-rw-r--r--o3d/plugin/npapi_host_control/win/module.h68
-rw-r--r--o3d/plugin/npapi_host_control/win/np_browser_proxy.cc834
-rw-r--r--o3d/plugin/npapi_host_control/win/np_browser_proxy.h282
-rw-r--r--o3d/plugin/npapi_host_control/win/np_object_proxy.cc518
-rw-r--r--o3d/plugin/npapi_host_control/win/np_object_proxy.h124
-rw-r--r--o3d/plugin/npapi_host_control/win/np_plugin_proxy.cc454
-rw-r--r--o3d/plugin/npapi_host_control/win/np_plugin_proxy.h161
-rw-r--r--o3d/plugin/npapi_host_control/win/npapi_host_control.cc73
-rw-r--r--o3d/plugin/npapi_host_control/win/npapi_host_control.def9
-rw-r--r--o3d/plugin/npapi_host_control/win/npapi_host_control.idl_template92
-rw-r--r--o3d/plugin/npapi_host_control/win/npapi_host_control.rc121
-rw-r--r--o3d/plugin/npapi_host_control/win/npapi_host_control.rgs17
-rw-r--r--o3d/plugin/npapi_host_control/win/precompile.cc33
-rw-r--r--o3d/plugin/npapi_host_control/win/precompile.h83
-rw-r--r--o3d/plugin/npapi_host_control/win/resource.h54
-rw-r--r--o3d/plugin/npapi_host_control/win/stream_operation.cc773
-rw-r--r--o3d/plugin/npapi_host_control/win/stream_operation.h270
-rw-r--r--o3d/plugin/npapi_host_control/win/variant_utils.cc207
-rw-r--r--o3d/plugin/npapi_host_control/win/variant_utils.h65
-rw-r--r--o3d/plugin/o3d_binding.py536
-rw-r--r--o3d/plugin/o3d_iface_generator.py618
-rw-r--r--o3d/plugin/plugin.gyp853
-rw-r--r--o3d/plugin/version_info.py138
-rw-r--r--o3d/plugin/win/config.cc241
-rw-r--r--o3d/plugin/win/logger_main.cc58
-rw-r--r--o3d/plugin/win/main_win.cc956
-rw-r--r--o3d/plugin/win/o3dPlugin.def_template6
-rw-r--r--o3d/plugin/win/o3dPlugin.rc_template106
-rw-r--r--o3d/plugin/win/o3dPlugin.sln92
-rw-r--r--o3d/plugin/win/plugin_logging-win32.cc312
-rw-r--r--o3d/plugin/win/plugin_metrics-win32.cc109
-rw-r--r--o3d/plugin/win/resource.h46
-rw-r--r--o3d/plugin/win/update_lock.cc43
-rw-r--r--o3d/plugin/win/update_lock.h104
-rw-r--r--o3d/samples/2d.html558
-rw-r--r--o3d/samples/GoogleIO-2009/assets/colorbar.pngbin1977 -> 0 bytes
-rw-r--r--o3d/samples/GoogleIO-2009/assets/style.css8
-rw-r--r--o3d/samples/GoogleIO-2009/shaders/checker.shader111
-rw-r--r--o3d/samples/GoogleIO-2009/step01ex.html176
-rw-r--r--o3d/samples/GoogleIO-2009/step02ex.html206
-rw-r--r--o3d/samples/GoogleIO-2009/step03ex.html254
-rw-r--r--o3d/samples/GoogleIO-2009/step04ex.html264
-rw-r--r--o3d/samples/GoogleIO-2009/step05ex.html292
-rw-r--r--o3d/samples/GoogleIO-2009/step06ex.html301
-rw-r--r--o3d/samples/GoogleIO-2009/step07ex.html302
-rw-r--r--o3d/samples/GoogleIO-2009/step08ex.html330
-rw-r--r--o3d/samples/GoogleIO-2009/step09ex.html358
-rw-r--r--o3d/samples/GoogleIO-2009/step10ex.html361
-rw-r--r--o3d/samples/GoogleIO-2009/step11ex.html365
-rw-r--r--o3d/samples/GoogleIO-2009/step12ex.html394
-rw-r--r--o3d/samples/GoogleIO-2009/step13ex.html570
-rw-r--r--o3d/samples/GoogleIO-2009/step14ex.html581
-rw-r--r--o3d/samples/MANIFEST224
-rw-r--r--o3d/samples/animated-scene.html228
-rw-r--r--o3d/samples/animation.html288
-rw-r--r--o3d/samples/archive-textures.html287
-rw-r--r--o3d/samples/assets/android.pngbin11280 -> 0 bytes
-rw-r--r--o3d/samples/assets/archive_textures.o3dtgzbin1019281 -> 0 bytes
-rw-r--r--o3d/samples/assets/block.pngbin4461 -> 0 bytes
-rw-r--r--o3d/samples/assets/brush.pngbin435 -> 0 bytes
-rw-r--r--o3d/samples/assets/egg.pngbin29942 -> 0 bytes
-rw-r--r--o3d/samples/assets/empty.txt0
-rw-r--r--o3d/samples/assets/four_pixel.pngbin169 -> 0 bytes
-rw-r--r--o3d/samples/assets/fullscreen.pngbin988 -> 0 bytes
-rw-r--r--o3d/samples/assets/gauge.pngbin174 -> 0 bytes
-rw-r--r--o3d/samples/assets/gaugeback.pngbin2355 -> 0 bytes
-rw-r--r--o3d/samples/assets/gears_init.js86
-rw-r--r--o3d/samples/assets/google-square.pngbin12051 -> 0 bytes
-rw-r--r--o3d/samples/assets/hi.jpgbin1745 -> 0 bytes
-rw-r--r--o3d/samples/assets/iconback.pngbin2316 -> 0 bytes
-rw-r--r--o3d/samples/assets/normalmap.ddsbin43832 -> 0 bytes
-rw-r--r--o3d/samples/assets/old-school-shadow.pngbin1619 -> 0 bytes
-rw-r--r--o3d/samples/assets/one-pixel-white.pngbin159 -> 0 bytes
-rw-r--r--o3d/samples/assets/one-pixel-white.tgabin48 -> 0 bytes
-rw-r--r--o3d/samples/assets/orange-flower.pngbin11702 -> 0 bytes
-rw-r--r--o3d/samples/assets/particle-anim.pngbin10050 -> 0 bytes
-rw-r--r--o3d/samples/assets/pillar.pngbin7867 -> 0 bytes
-rw-r--r--o3d/samples/assets/poolballs.pngbin109874 -> 0 bytes
-rw-r--r--o3d/samples/assets/purple-flower.pngbin26558 -> 0 bytes
-rw-r--r--o3d/samples/assets/radar.pngbin11122 -> 0 bytes
-rw-r--r--o3d/samples/assets/ripple.pngbin3221 -> 0 bytes
-rw-r--r--o3d/samples/assets/rock_bumps.jpgbin1951243 -> 0 bytes
-rw-r--r--o3d/samples/assets/rock_texture.jpgbin714283 -> 0 bytes
-rw-r--r--o3d/samples/assets/shaving_cream.jpgbin322717 -> 0 bytes
-rw-r--r--o3d/samples/assets/shaving_cream.pngbin496645 -> 0 bytes
-rw-r--r--o3d/samples/assets/shaving_cream_300x300.jpgbin107306 -> 0 bytes
-rw-r--r--o3d/samples/assets/square.pngbin14491 -> 0 bytes
-rw-r--r--o3d/samples/assets/teapot_vertices.js32
-rw-r--r--o3d/samples/assets/texture_b3.jpgbin38230 -> 0 bytes
-rw-r--r--o3d/samples/beachdemo/assets/pe_fire.jpgbin10629 -> 0 bytes
-rw-r--r--o3d/samples/beachdemo/assets/pe_mist.pngbin54013 -> 0 bytes
-rw-r--r--o3d/samples/beachdemo/assets/sky-cubemap.ddsbin786560 -> 0 bytes
-rw-r--r--o3d/samples/beachdemo/beachdemo-glsl.html150
-rw-r--r--o3d/samples/beachdemo/beachdemo-glsl.js2779
-rw-r--r--o3d/samples/beachdemo/beachdemo.html150
-rw-r--r--o3d/samples/beachdemo/beachdemo.js2772
-rw-r--r--o3d/samples/beachdemo/shaders_cg/diffuse.cg79
-rw-r--r--o3d/samples/beachdemo/shaders_cg/diffuse_bump.cg98
-rw-r--r--o3d/samples/beachdemo/shaders_cg/diffuse_bump_2textures.cg103
-rw-r--r--o3d/samples/beachdemo/shaders_cg/diffuse_bump_blend.cg116
-rw-r--r--o3d/samples/beachdemo/shaders_cg/diffuse_bump_blend_underwater.cg115
-rw-r--r--o3d/samples/beachdemo/shaders_cg/diffuse_bump_specular.cg97
-rw-r--r--o3d/samples/beachdemo/shaders_cg/imageshader.cg61
-rw-r--r--o3d/samples/beachdemo/shaders_cg/just_color.cg81
-rw-r--r--o3d/samples/beachdemo/shaders_cg/proxy.cg81
-rw-r--r--o3d/samples/beachdemo/shaders_cg/simpleshader.cg55
-rw-r--r--o3d/samples/beachdemo/shaders_cg/skydomeshader.cg62
-rw-r--r--o3d/samples/beachdemo/shaders_cg/underwatershader.cg80
-rw-r--r--o3d/samples/beachdemo/shaders_cg/watercolorandskyshader.cg131
-rw-r--r--o3d/samples/beachdemo/shaders_cg/waterfallshader.cg80
-rw-r--r--o3d/samples/beachdemo/shaders_cg/watershader.cg157
-rw-r--r--o3d/samples/beachdemo/shaders_cg/waterstyle2.cg73
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/diffuse.glsl221
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/diffuse_bump.glsl268
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/diffuse_bump_2textures.glsl279
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/diffuse_bump_blend.glsl337
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/diffuse_bump_blend_underwater.glsl332
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/diffuse_bump_specular.glsl270
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/imageshader.glsl105
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/just_color.glsl209
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/proxy.glsl209
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/simpleshader.glsl90
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/skydomeshader.glsl116
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/underwatershader.glsl174
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/watercolorandskyshader.glsl236
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/waterfallshader.glsl194
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/watershader.glsl257
-rw-r--r--o3d/samples/beachdemo/shaders_glsl/waterstyle2.glsl85
-rw-r--r--o3d/samples/billboards.html254
-rw-r--r--o3d/samples/bitmap-draw-image.html247
-rw-r--r--o3d/samples/box2d-3d/box2d-3d.html138
-rw-r--r--o3d/samples/box2d-3d/demos/LICENSE.txt14
-rw-r--r--o3d/samples/box2d-3d/demos/README.o3d5
-rw-r--r--o3d/samples/box2d-3d/demos/compound.js71
-rw-r--r--o3d/samples/box2d-3d/demos/crank.js79
-rw-r--r--o3d/samples/box2d-3d/demos/demo_base.js59
-rw-r--r--o3d/samples/box2d-3d/demos/demos.js271
-rw-r--r--o3d/samples/box2d-3d/demos/draw_world.js90
-rw-r--r--o3d/samples/box2d-3d/demos/manager.js210
-rw-r--r--o3d/samples/box2d-3d/demos/pendulum.js25
-rw-r--r--o3d/samples/box2d-3d/demos/stack.js37
-rw-r--r--o3d/samples/box2d-3d/demos/top.js53
-rw-r--r--o3d/samples/box2d-3d/third_party/box2d/LICENSE.txt14
-rw-r--r--o3d/samples/box2d-3d/third_party/box2d/README.o3d5
-rw-r--r--o3d/samples/box2d-3d/third_party/box2d/box2d.js1037
-rw-r--r--o3d/samples/box2d-3d/third_party/prototype-1.6.0.2.js4221
-rw-r--r--o3d/samples/canvas-fonts.html192
-rw-r--r--o3d/samples/canvas-texturedraw.html263
-rw-r--r--o3d/samples/canvas.html339
-rw-r--r--o3d/samples/checkers.html870
-rw-r--r--o3d/samples/convolution.html397
-rw-r--r--o3d/samples/culling.html321
-rw-r--r--o3d/samples/customcamera.html405
-rw-r--r--o3d/samples/debugging.html246
-rw-r--r--o3d/samples/displayfps.html215
-rw-r--r--o3d/samples/error-texture.html263
-rw-r--r--o3d/samples/fullscreen.html367
-rw-r--r--o3d/samples/gadgets/readme.txt11
-rw-r--r--o3d/samples/gadgets/scatter-chart.xml434
-rw-r--r--o3d/samples/generate-texture.html290
-rw-r--r--o3d/samples/gpu2d/Google_Logo.svg134
-rw-r--r--o3d/samples/gpu2d/a.svg72
-rw-r--r--o3d/samples/gpu2d/basic.html229
-rw-r--r--o3d/samples/gpu2d/butterfly.svg17
-rw-r--r--o3d/samples/gpu2d/crescent.svg19
-rw-r--r--o3d/samples/gpu2d/javalogo.svg58
-rw-r--r--o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-1.html51
-rw-r--r--o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-1.svg17
-rw-r--r--o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-2.html51
-rw-r--r--o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-2.svg17
-rw-r--r--o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-3.html51
-rw-r--r--o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-3.svg17
-rw-r--r--o3d/samples/gpu2d/regression-tests/orientation-bug-1.html51
-rw-r--r--o3d/samples/gpu2d/regression-tests/orientation-bug-1.svg72
-rw-r--r--o3d/samples/gpu2d/regression-tests/orientation-bug-2.html51
-rw-r--r--o3d/samples/gpu2d/regression-tests/orientation-bug-2.svg17
-rw-r--r--o3d/samples/gpu2d/regression-tests/orientation-bug-3.html51
-rw-r--r--o3d/samples/gpu2d/regression-tests/orientation-bug-3.svg17
-rw-r--r--o3d/samples/gpu2d/svg_a.html51
-rw-r--r--o3d/samples/gpu2d/svg_butterfly.html52
-rw-r--r--o3d/samples/gpu2d/svg_crescent.html51
-rw-r--r--o3d/samples/gpu2d/svg_google_logo.html51
-rw-r--r--o3d/samples/gpu2d/svg_java_logo.html51
-rw-r--r--o3d/samples/gpu2d/svg_thin_crescent.html51
-rw-r--r--o3d/samples/gpu2d/svgloader.js990
-rw-r--r--o3d/samples/gpu2d/svgsample.js226
-rw-r--r--o3d/samples/gpu2d/thincrescent.svg22
-rw-r--r--o3d/samples/hellocube-colors-glsl.html343
-rw-r--r--o3d/samples/hellocube-colors.html352
-rw-r--r--o3d/samples/hellocube-glsl.html304
-rw-r--r--o3d/samples/hellocube-textures-glsl.html433
-rw-r--r--o3d/samples/hellocube-textures.html445
-rw-r--r--o3d/samples/hellocube.html312
-rw-r--r--o3d/samples/helloworld.html171
-rw-r--r--o3d/samples/home-configurators/assets/empty.txt0
-rw-r--r--o3d/samples/home-configurators/cb_images/cb_item_thumbnails.jpgbin42895 -> 0 bytes
-rw-r--r--o3d/samples/home-configurators/cb_images/toolselector.gifbin344 -> 0 bytes
-rw-r--r--o3d/samples/home-configurators/cb_images/unbranded_bg.pngbin26868 -> 0 bytes
-rw-r--r--o3d/samples/home-configurators/cbassets/empty.txt0
-rw-r--r--o3d/samples/home-configurators/craftsmanassets/craftsman_item_thumbnails.jpgbin34143 -> 0 bytes
-rw-r--r--o3d/samples/home-configurators/deletetool.js88
-rw-r--r--o3d/samples/home-configurators/homedesigner.html171
-rw-r--r--o3d/samples/home-configurators/movetool.js161
-rw-r--r--o3d/samples/home-configurators/orbittool.js94
-rw-r--r--o3d/samples/home-configurators/pantool.js77
-rw-r--r--o3d/samples/home-configurators/rotatetool.js113
-rw-r--r--o3d/samples/home-configurators/searsassets/sears_bg.pngbin65087 -> 0 bytes
-rw-r--r--o3d/samples/home-configurators/searsassets/sears_item_thumbnails.jpgbin45942 -> 0 bytes
-rw-r--r--o3d/samples/home-configurators/viewer.js581
-rw-r--r--o3d/samples/home-configurators/zoomtool.js76
-rw-r--r--o3d/samples/hud-2d-overlay.html491
-rw-r--r--o3d/samples/iframeit.html132
-rw-r--r--o3d/samples/instance-override.html180
-rw-r--r--o3d/samples/instancing.html208
-rw-r--r--o3d/samples/interactive_logic.js576
-rw-r--r--o3d/samples/interactive_sampler_assets/images/bl.gifbin157 -> 0 bytes
-rw-r--r--o3d/samples/interactive_sampler_assets/images/br.gifbin158 -> 0 bytes
-rw-r--r--o3d/samples/interactive_sampler_assets/images/cleardot.gifbin43 -> 0 bytes
-rw-r--r--o3d/samples/interactive_sampler_assets/images/corner.pngbin1140 -> 0 bytes
-rw-r--r--o3d/samples/interactive_sampler_assets/images/db_tl.pngbin126 -> 0 bytes
-rw-r--r--o3d/samples/interactive_sampler_assets/images/db_tr.pngbin124 -> 0 bytes
-rw-r--r--o3d/samples/interactive_sampler_assets/images/google-small.pngbin2445 -> 0 bytes
-rw-r--r--o3d/samples/interactive_sampler_assets/images/lb_tl.pngbin123 -> 0 bytes
-rw-r--r--o3d/samples/interactive_sampler_assets/images/lb_tr.pngbin124 -> 0 bytes
-rw-r--r--o3d/samples/interactive_sampler_assets/images/sprites.gifbin6229 -> 0 bytes
-rw-r--r--o3d/samples/interactive_sampler_assets/images/sprites08132008.pngbin4179 -> 0 bytes
-rw-r--r--o3d/samples/interactive_sampler_assets/images/sprites2.jpgbin1087 -> 0 bytes
-rw-r--r--o3d/samples/interactive_sampler_assets/images/tl.gifbin1185 -> 0 bytes
-rw-r--r--o3d/samples/interactive_sampler_assets/images/tr.gifbin158 -> 0 bytes
-rw-r--r--o3d/samples/interactive_sampler_assets/styles.css278
-rw-r--r--o3d/samples/interactive_sampler_assets/styles_ie.css301
-rw-r--r--o3d/samples/interactive_sampler_assets/utils.js200
-rw-r--r--o3d/samples/interactive_samples.js189
-rw-r--r--o3d/samples/io/README.txt29
-rw-r--r--o3d/samples/io/actors/actor.js144
-rw-r--r--o3d/samples/io/actors/arrow.js94
-rw-r--r--o3d/samples/io/actors/avatar.js67
-rw-r--r--o3d/samples/io/actors/coin.js68
-rw-r--r--o3d/samples/io/actors/horizontalpad.js85
-rw-r--r--o3d/samples/io/actors/mover.js48
-rw-r--r--o3d/samples/io/actors/spikem.js126
-rw-r--r--o3d/samples/io/actors/verticalpad.js84
-rw-r--r--o3d/samples/io/autoincludes.js49
-rw-r--r--o3d/samples/io/cutscenes.js148
-rw-r--r--o3d/samples/io/dynamic_lights.js123
-rw-r--r--o3d/samples/io/editor.html126
-rw-r--r--o3d/samples/io/gamelogic.js578
-rw-r--r--o3d/samples/io/init.js395
-rw-r--r--o3d/samples/io/io.html173
-rw-r--r--o3d/samples/io/levels/all_actors.js383
-rw-r--r--o3d/samples/io/levels/all_actors.skpbin1514934 -> 0 bytes
-rw-r--r--o3d/samples/io/levels/map1.js156
-rw-r--r--o3d/samples/io/levels/map1.skpbin663342 -> 0 bytes
-rw-r--r--o3d/samples/io/levels/starter_level.skpbin557136 -> 0 bytes
-rw-r--r--o3d/samples/io/sound/_MISS.mp3bin627 -> 0 bytes
-rw-r--r--o3d/samples/io/sound/_PUNCH.mp3bin940 -> 0 bytes
-rw-r--r--o3d/samples/io/sound/_SMASH.mp3bin40333 -> 0 bytes
-rw-r--r--o3d/samples/io/sound/_woosh.mp3bin6653 -> 0 bytes
-rw-r--r--o3d/samples/io/sound/ah.mp3bin7549 -> 0 bytes
-rw-r--r--o3d/samples/io/sound/arrow.mp3bin5459 -> 0 bytes
-rw-r--r--o3d/samples/io/sound/coin_3.mp3bin12564 -> 0 bytes
-rw-r--r--o3d/samples/io/sound/music.mp3bin3276800 -> 0 bytes
-rw-r--r--o3d/samples/io/sound/page.mp3bin12146 -> 0 bytes
-rw-r--r--o3d/samples/io/sound/soundplayer.js147
-rw-r--r--o3d/samples/io/sound/soundplayer.swfbin3869 -> 0 bytes
-rw-r--r--o3d/samples/io/sound/step1.mp3bin4623 -> 0 bytes
-rw-r--r--o3d/samples/io/sound/step2.mp3bin5041 -> 0 bytes
-rw-r--r--o3d/samples/io/sound/step3.mp3bin4205 -> 0 bytes
-rw-r--r--o3d/samples/io/sound/ug.mp3bin2951 -> 0 bytes
-rw-r--r--o3d/samples/io/ui/Thumbs.dbbin27648 -> 0 bytes
-rw-r--r--o3d/samples/io/ui/bgtile.jpgbin2495 -> 0 bytes
-rw-r--r--o3d/samples/io/ui/book_capbottom.jpgbin18693 -> 0 bytes
-rw-r--r--o3d/samples/io/ui/book_capleft.jpgbin11719 -> 0 bytes
-rw-r--r--o3d/samples/io/ui/book_capright.jpgbin14239 -> 0 bytes
-rw-r--r--o3d/samples/io/ui/book_captop.jpgbin16493 -> 0 bytes
-rw-r--r--o3d/samples/io/ui/book_cover.jpgbin86247 -> 0 bytes
-rw-r--r--o3d/samples/io/ui/book_innercover.jpgbin25296 -> 0 bytes
-rw-r--r--o3d/samples/io/ui/book_page1.jpgbin97294 -> 0 bytes
-rw-r--r--o3d/samples/io/ui/book_page2.jpgbin95923 -> 0 bytes
-rw-r--r--o3d/samples/io/ui/book_page3.jpgbin75059 -> 0 bytes
-rw-r--r--o3d/samples/io/ui/book_pageblank.jpgbin44635 -> 0 bytes
-rw-r--r--o3d/samples/io/ui/covershadow.pngbin6490 -> 0 bytes
-rw-r--r--o3d/samples/io/ui/io.css181
-rw-r--r--o3d/samples/io/ui/logo.gifbin1577 -> 0 bytes
-rw-r--r--o3d/samples/io/ui/scrollwork.gifbin26553 -> 0 bytes
-rw-r--r--o3d/samples/juggler.html463
-rw-r--r--o3d/samples/julia.html295
-rw-r--r--o3d/samples/manipulators/manipsample.js297
-rw-r--r--o3d/samples/manipulators/rotate1.html85
-rw-r--r--o3d/samples/manipulators/translate1.html76
-rw-r--r--o3d/samples/manipulators/translate2.html76
-rw-r--r--o3d/samples/multiple-clients.html230
-rw-r--r--o3d/samples/multiple-lights.html208
-rw-r--r--o3d/samples/multiple-views.html220
-rw-r--r--o3d/samples/o3d-webgl-samples/2d.html562
-rw-r--r--o3d/samples/o3d-webgl-samples/animation.html343
-rw-r--r--o3d/samples/o3d-webgl-samples/billboards.html257
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/box2d-3d.html147
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/demos/LICENSE.txt14
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/demos/README.o3d5
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/demos/compound.js71
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/demos/crank.js79
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/demos/demo_base.js59
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/demos/demos.js274
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/demos/draw_world.js90
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/demos/manager.js210
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/demos/pendulum.js25
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/demos/stack.js37
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/demos/top.js53
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/third_party/box2d/LICENSE.txt14
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/third_party/box2d/README.o3d5
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/third_party/box2d/box2d.js1037
-rw-r--r--o3d/samples/o3d-webgl-samples/box2d-3d/third_party/prototype-1.6.0.2.js4221
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/blaster/extra/shadow-map.js213
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/blaster/index.html165
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/blaster/js/block.js145
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/blaster/js/bubble-manager.js150
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/blaster/js/bubble.js231
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/blaster/js/camera.js190
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/blaster/js/game.js125
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/blaster/js/level.js154
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/blaster/js/main.js174
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/bubble1.pngbin3139 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/bubble2.pngbin2267 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/bubble3.pngbin1779 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/style.css188
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/bubble.html250
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/css/style.css163
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/cubemap/negx.pngbin8952 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/cubemap/negy.pngbin9353 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/cubemap/negz.pngbin8635 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/cubemap/posx.pngbin8805 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/cubemap/posy.pngbin7478 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/cubemap/posz.pngbin8616 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/js/bubbledemo.js620
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/js/controls.js341
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/js/environment.js61
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/js/iridescence.js223
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/js/main.js270
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/js/modulation.js97
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/js/noise.js210
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/AUTHORS.txt30
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/MIT-LICENSE.txt25
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/README.o3d7
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/css/jquery-ui-1.8.4.custom.css124
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/jquery-1.4.2.min.js154
-rw-r--r--o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/jquery-ui-1.8.4.custom.min.js83
-rw-r--r--o3d/samples/o3d-webgl-samples/checkers.html873
-rw-r--r--o3d/samples/o3d-webgl-samples/convolution.html398
-rw-r--r--o3d/samples/o3d-webgl-samples/culling.html320
-rw-r--r--o3d/samples/o3d-webgl-samples/customcamera.html456
-rw-r--r--o3d/samples/o3d-webgl-samples/debugging.html248
-rw-r--r--o3d/samples/o3d-webgl-samples/error-texture.html265
-rw-r--r--o3d/samples/o3d-webgl-samples/generate-texture.html259
-rw-r--r--o3d/samples/o3d-webgl-samples/hellocube-colors.html343
-rw-r--r--o3d/samples/o3d-webgl-samples/hellocube-textures.html433
-rw-r--r--o3d/samples/o3d-webgl-samples/hellocube-wireframe.html534
-rw-r--r--o3d/samples/o3d-webgl-samples/hellocube.html300
-rw-r--r--o3d/samples/o3d-webgl-samples/helloworld.html177
-rw-r--r--o3d/samples/o3d-webgl-samples/hud-2d-overlay.html493
-rw-r--r--o3d/samples/o3d-webgl-samples/instance-override.html182
-rw-r--r--o3d/samples/o3d-webgl-samples/instancing.html211
-rw-r--r--o3d/samples/o3d-webgl-samples/juggler.html453
-rw-r--r--o3d/samples/o3d-webgl-samples/julia.html285
-rw-r--r--o3d/samples/o3d-webgl-samples/multiple-clients.html229
-rw-r--r--o3d/samples/o3d-webgl-samples/multiple-lights.html209
-rw-r--r--o3d/samples/o3d-webgl-samples/multiple-views.html222
-rw-r--r--o3d/samples/o3d-webgl-samples/old-school-shadows.html277
-rw-r--r--o3d/samples/o3d-webgl-samples/particles.html591
-rw-r--r--o3d/samples/o3d-webgl-samples/phongshading.html345
-rw-r--r--o3d/samples/o3d-webgl-samples/picking-more.html384
-rw-r--r--o3d/samples/o3d-webgl-samples/picking.html345
-rw-r--r--o3d/samples/o3d-webgl-samples/pingpong/instructions.gifbin3439 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/pingpong/logo.gifbin6958 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/pingpong/pingpong.html846
-rw-r--r--o3d/samples/o3d-webgl-samples/pool.html2187
-rw-r--r--o3d/samples/o3d-webgl-samples/primitives.html247
-rw-r--r--o3d/samples/o3d-webgl-samples/procedural-texture.html255
-rw-r--r--o3d/samples/o3d-webgl-samples/render-mode.html287
-rw-r--r--o3d/samples/o3d-webgl-samples/render-targets.html333
-rw-r--r--o3d/samples/o3d-webgl-samples/rotatemodel.html250
-rw-r--r--o3d/samples/o3d-webgl-samples/shader-test.html407
-rw-r--r--o3d/samples/o3d-webgl-samples/shadow-map.html620
-rw-r--r--o3d/samples/o3d-webgl-samples/simpleviewer/simpleviewer.html377
-rw-r--r--o3d/samples/o3d-webgl-samples/skinning.html278
-rw-r--r--o3d/samples/o3d-webgl-samples/sobel.html339
-rw-r--r--o3d/samples/o3d-webgl-samples/texturesamplers.html272
-rw-r--r--o3d/samples/o3d-webgl-samples/trends/assets/clouds.jpgbin107460 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/trends/assets/earth-large-with-ocean-mask.pngbin2367738 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/trends/assets/earth-large.jpgbin586564 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/trends/assets/earth.jpgbin46696 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/trends/assets/energy.pngbin136 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/trends/assets/moon.jpgbin67152 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/trends/assets/night-large.jpgbin313629 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/trends/assets/night.jpgbin86315 -> 0 bytes
-rw-r--r--o3d/samples/o3d-webgl-samples/trends/trends-with-particles.html803
-rw-r--r--o3d/samples/o3d-webgl-samples/trends/trends.html869
-rw-r--r--o3d/samples/o3d-webgl-samples/vertex-shader-animation.html203
-rw-r--r--o3d/samples/o3d-webgl-samples/vertex-shader.html334
-rw-r--r--o3d/samples/o3d-webgl-samples/yuv2rgb.html203
-rw-r--r--o3d/samples/o3d-webgl-samples/zsorting.html203
-rw-r--r--o3d/samples/o3d-webgl/archive_request.js275
-rw-r--r--o3d/samples/o3d-webgl/base.js290
-rw-r--r--o3d/samples/o3d-webgl/bitmap.js201
-rw-r--r--o3d/samples/o3d-webgl/bounding_box.js301
-rw-r--r--o3d/samples/o3d-webgl/buffer.js337
-rw-r--r--o3d/samples/o3d-webgl/clear_buffer.js120
-rw-r--r--o3d/samples/o3d-webgl/client.js1354
-rw-r--r--o3d/samples/o3d-webgl/counter.js814
-rw-r--r--o3d/samples/o3d-webgl/curve.js912
-rw-r--r--o3d/samples/o3d-webgl/draw_context.js66
-rw-r--r--o3d/samples/o3d-webgl/draw_element.js66
-rw-r--r--o3d/samples/o3d-webgl/draw_list.js166
-rw-r--r--o3d/samples/o3d-webgl/draw_pass.js77
-rw-r--r--o3d/samples/o3d-webgl/effect.js646
-rw-r--r--o3d/samples/o3d-webgl/element.js202
-rw-r--r--o3d/samples/o3d-webgl/event.js266
-rw-r--r--o3d/samples/o3d-webgl/field.js144
-rw-r--r--o3d/samples/o3d-webgl/file_request.js216
-rw-r--r--o3d/samples/o3d-webgl/function.js143
-rw-r--r--o3d/samples/o3d-webgl/material.js70
-rw-r--r--o3d/samples/o3d-webgl/named_object.js55
-rw-r--r--o3d/samples/o3d-webgl/named_object_base.js49
-rw-r--r--o3d/samples/o3d-webgl/object_base.js72
-rw-r--r--o3d/samples/o3d-webgl/pack.js403
-rw-r--r--o3d/samples/o3d-webgl/param.js1018
-rw-r--r--o3d/samples/o3d-webgl/param_array.js184
-rw-r--r--o3d/samples/o3d-webgl/param_object.js261
-rw-r--r--o3d/samples/o3d-webgl/param_operation.js513
-rw-r--r--o3d/samples/o3d-webgl/primitive.js594
-rw-r--r--o3d/samples/o3d-webgl/raw_data.js103
-rw-r--r--o3d/samples/o3d-webgl/ray_intersection_info.js84
-rw-r--r--o3d/samples/o3d-webgl/render_node.js217
-rw-r--r--o3d/samples/o3d-webgl/render_surface.js138
-rw-r--r--o3d/samples/o3d-webgl/render_surface_set.js171
-rw-r--r--o3d/samples/o3d-webgl/sampler.js291
-rw-r--r--o3d/samples/o3d-webgl/shape.js191
-rw-r--r--o3d/samples/o3d-webgl/skin.js931
-rw-r--r--o3d/samples/o3d-webgl/state.js700
-rw-r--r--o3d/samples/o3d-webgl/state_set.js70
-rw-r--r--o3d/samples/o3d-webgl/stream.js124
-rw-r--r--o3d/samples/o3d-webgl/stream_bank.js145
-rw-r--r--o3d/samples/o3d-webgl/texture.js965
-rw-r--r--o3d/samples/o3d-webgl/transform.js1370
-rw-r--r--o3d/samples/o3d-webgl/tree_traversal.js112
-rw-r--r--o3d/samples/o3d-webgl/types.js119
-rw-r--r--o3d/samples/o3d-webgl/vertex_source.js115
-rw-r--r--o3d/samples/o3d-webgl/viewport.js96
-rw-r--r--o3d/samples/o3djs/arcball.js162
-rw-r--r--o3d/samples/o3djs/base.js809
-rw-r--r--o3d/samples/o3djs/camera.js364
-rw-r--r--o3d/samples/o3djs/cameracontroller.js396
-rw-r--r--o3d/samples/o3djs/canvas.js438
-rw-r--r--o3d/samples/o3djs/debug.js1031
-rw-r--r--o3d/samples/o3djs/dump.js585
-rw-r--r--o3d/samples/o3djs/effect.js1534
-rw-r--r--o3d/samples/o3djs/element.js212
-rw-r--r--o3d/samples/o3djs/error.js133
-rw-r--r--o3d/samples/o3djs/event.js360
-rw-r--r--o3d/samples/o3djs/fps.js486
-rw-r--r--o3d/samples/o3djs/gpu2d.js800
-rw-r--r--o3d/samples/o3djs/io.js656
-rw-r--r--o3d/samples/o3djs/js_list.manifest63
-rw-r--r--o3d/samples/o3djs/lineprimitives.js396
-rw-r--r--o3d/samples/o3djs/loader.js241
-rw-r--r--o3d/samples/o3djs/manipulators.js1910
-rw-r--r--o3d/samples/o3djs/material.js593
-rw-r--r--o3d/samples/o3djs/math.js3168
-rw-r--r--o3d/samples/o3djs/pack.js71
-rw-r--r--o3d/samples/o3djs/particles.js1510
-rw-r--r--o3d/samples/o3djs/performance.js202
-rw-r--r--o3d/samples/o3djs/picking.js742
-rw-r--r--o3d/samples/o3djs/plugin_math.js2536
-rw-r--r--o3d/samples/o3djs/primitives.js2016
-rw-r--r--o3d/samples/o3djs/quaternions.js520
-rw-r--r--o3d/samples/o3djs/rendergraph.js580
-rw-r--r--o3d/samples/o3djs/scene.js91
-rw-r--r--o3d/samples/o3djs/serialization.js871
-rw-r--r--o3d/samples/o3djs/shape.js140
-rw-r--r--o3d/samples/o3djs/simple.js830
-rw-r--r--o3d/samples/o3djs/test.js342
-rw-r--r--o3d/samples/o3djs/texture.js295
-rw-r--r--o3d/samples/o3djs/util.js1037
-rw-r--r--o3d/samples/o3djs/webgl.js283
-rw-r--r--o3d/samples/old-school-shadows.html274
-rw-r--r--o3d/samples/particles.html593
-rw-r--r--o3d/samples/phongshading.html367
-rw-r--r--o3d/samples/picking.html342
-rw-r--r--o3d/samples/pingpong/instructions.gifbin3439 -> 0 bytes
-rw-r--r--o3d/samples/pingpong/logo.gifbin6958 -> 0 bytes
-rw-r--r--o3d/samples/pingpong/o3dPingPong.html851
-rw-r--r--o3d/samples/primitives.html250
-rw-r--r--o3d/samples/procedural-texture.html258
-rw-r--r--o3d/samples/render-mode.html283
-rw-r--r--o3d/samples/render-targets.html340
-rw-r--r--o3d/samples/rotatemodel.html247
-rw-r--r--o3d/samples/sampler_index.html187
-rw-r--r--o3d/samples/samples.gyp131
-rw-r--r--o3d/samples/samples_gen.py240
-rw-r--r--o3d/samples/scatter-chart.html398
-rw-r--r--o3d/samples/shader-test.html413
-rw-r--r--o3d/samples/shaders/README16
-rw-r--r--o3d/samples/shaders/billboard-glsl.shader67
-rw-r--r--o3d/samples/shaders/billboard.shader80
-rw-r--r--o3d/samples/shaders/binormal-glsl.shader55
-rw-r--r--o3d/samples/shaders/binormal.shader64
-rw-r--r--o3d/samples/shaders/bump-glsl.shader140
-rw-r--r--o3d/samples/shaders/bump.shader137
-rw-r--r--o3d/samples/shaders/checker-glsl.shader107
-rw-r--r--o3d/samples/shaders/checker.shader117
-rw-r--r--o3d/samples/shaders/diffuse-glsl.shader87
-rw-r--r--o3d/samples/shaders/diffuse.shader96
-rw-r--r--o3d/samples/shaders/green-blue-checker.shader110
-rw-r--r--o3d/samples/shaders/imposter-glsl.shader77
-rw-r--r--o3d/samples/shaders/imposter.shader89
-rw-r--r--o3d/samples/shaders/normal-glsl.shader56
-rw-r--r--o3d/samples/shaders/normal.shader64
-rw-r--r--o3d/samples/shaders/one-channel-texture.shader94
-rw-r--r--o3d/samples/shaders/phong-vertex-anim-glsl.shader100
-rw-r--r--o3d/samples/shaders/phong-vertex-anim.shader95
-rw-r--r--o3d/samples/shaders/phong-with-colormult-glsl.shader88
-rw-r--r--o3d/samples/shaders/phong-with-colormult.shader83
-rw-r--r--o3d/samples/shaders/solid-color-glsl.shader62
-rw-r--r--o3d/samples/shaders/solid-color.shader74
-rw-r--r--o3d/samples/shaders/tangent-glsl.shader56
-rw-r--r--o3d/samples/shaders/tangent.shader64
-rw-r--r--o3d/samples/shaders/texture-colormult-glsl.shader67
-rw-r--r--o3d/samples/shaders/texture-colormult.shader74
-rw-r--r--o3d/samples/shaders/texture-only-glsl.shader64
-rw-r--r--o3d/samples/shaders/texture-only.shader71
-rw-r--r--o3d/samples/shaders/toon-glsl.shader89
-rwxr-xr-xo3d/samples/shaders/toon.shader98
-rw-r--r--o3d/samples/shaders/vertex-color-glsl.shader59
-rw-r--r--o3d/samples/shaders/vertex-color.shader75
-rw-r--r--o3d/samples/shaders/yuv2rgb-glsl.shader230
-rw-r--r--o3d/samples/shaders/yuv2rgb.shader235
-rw-r--r--o3d/samples/shadow-map.html628
-rw-r--r--o3d/samples/simple.html108
-rw-r--r--o3d/samples/simpletexture.html169
-rw-r--r--o3d/samples/simpleviewer/assets/empty.txt0
-rw-r--r--o3d/samples/simpleviewer/simpleviewer.html365
-rw-r--r--o3d/samples/siteswap/animation.js198
-rw-r--r--o3d/samples/siteswap/math.js1492
-rw-r--r--o3d/samples/siteswap/siteswap.html323
-rw-r--r--o3d/samples/siteswap/siteswap.js415
-rw-r--r--o3d/samples/skinning.html272
-rw-r--r--o3d/samples/sobel.html342
-rw-r--r--o3d/samples/stencil_example.html439
-rw-r--r--o3d/samples/texturesamplers.html231
-rw-r--r--o3d/samples/third_party/codemirror/LICENSE23
-rw-r--r--o3d/samples/third_party/codemirror/README.o3d5
-rw-r--r--o3d/samples/third_party/codemirror/css/csscolors.css47
-rw-r--r--o3d/samples/third_party/codemirror/css/docs.css38
-rw-r--r--o3d/samples/third_party/codemirror/css/jscolors.css47
-rw-r--r--o3d/samples/third_party/codemirror/css/xmlcolors.css51
-rw-r--r--o3d/samples/third_party/codemirror/js/codemirror.js189
-rw-r--r--o3d/samples/third_party/codemirror/js/editor.js1052
-rw-r--r--o3d/samples/third_party/codemirror/js/mirrorframe.js83
-rw-r--r--o3d/samples/third_party/codemirror/js/parsecss.js155
-rw-r--r--o3d/samples/third_party/codemirror/js/parsehtmlmixed.js66
-rw-r--r--o3d/samples/third_party/codemirror/js/parsejavascript.js322
-rw-r--r--o3d/samples/third_party/codemirror/js/parsesparql.js162
-rw-r--r--o3d/samples/third_party/codemirror/js/parsexml.js292
-rw-r--r--o3d/samples/third_party/codemirror/js/select.js500
-rw-r--r--o3d/samples/third_party/codemirror/js/stringstream.js111
-rw-r--r--o3d/samples/third_party/codemirror/js/tokenize.js57
-rw-r--r--o3d/samples/third_party/codemirror/js/tokenizejavascript.js168
-rw-r--r--o3d/samples/third_party/codemirror/js/undo.js386
-rw-r--r--o3d/samples/third_party/codemirror/js/util.js134
-rw-r--r--o3d/samples/third_party/json/json2-min.js29
-rw-r--r--o3d/samples/third_party/json/json2.js482
-rw-r--r--o3d/samples/third_party/lightbox/LICENSE-lightbox-iframe.txt66
-rw-r--r--o3d/samples/third_party/lightbox/LICENSE-prototype.txt16
-rw-r--r--o3d/samples/third_party/lightbox/lightbox-iframe.js199
-rw-r--r--o3d/samples/third_party/lightbox/lightbox.css74
-rw-r--r--o3d/samples/third_party/lightbox/prototype.js1785
-rw-r--r--o3d/samples/third_party/xmljs/COPYING491
-rw-r--r--o3d/samples/third_party/xmljs/tinyxmlsax.js245
-rw-r--r--o3d/samples/trends/assets/clouds.jpgbin107460 -> 0 bytes
-rw-r--r--o3d/samples/trends/assets/earth-large-with-ocean-mask.pngbin2367738 -> 0 bytes
-rw-r--r--o3d/samples/trends/assets/earth-large.jpgbin586564 -> 0 bytes
-rw-r--r--o3d/samples/trends/assets/earth.jpgbin46696 -> 0 bytes
-rw-r--r--o3d/samples/trends/assets/energy.pngbin136 -> 0 bytes
-rw-r--r--o3d/samples/trends/assets/moon.jpgbin67152 -> 0 bytes
-rw-r--r--o3d/samples/trends/assets/night-large.jpgbin313629 -> 0 bytes
-rw-r--r--o3d/samples/trends/assets/night.jpgbin86315 -> 0 bytes
-rw-r--r--o3d/samples/trends/trends-with-particles.html791
-rw-r--r--o3d/samples/trends/trends.html866
-rw-r--r--o3d/samples/tutorial-primitive.html120
-rw-r--r--o3d/samples/vertex-shader-animation.html201
-rw-r--r--o3d/samples/vertex-shader.html337
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.0.pngbin211905 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.1.pngbin212138 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.10.pngbin211866 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.11.pngbin212161 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.12.pngbin212358 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.13.pngbin212488 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.14.pngbin212369 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.15.pngbin212315 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.16.pngbin211997 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.17.pngbin212105 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.18.pngbin211728 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.19.pngbin211885 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.2.pngbin211780 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.20.pngbin211708 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.21.pngbin211877 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.22.pngbin211941 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.23.pngbin211997 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.24.pngbin211822 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.25.pngbin211683 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.26.pngbin211858 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.27.pngbin211979 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.28.pngbin212254 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.29.pngbin212175 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.3.pngbin212017 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.4.pngbin212107 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.5.pngbin212184 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.6.pngbin212345 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.7.pngbin212017 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.8.pngbin211892 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/deepwater/deepwater.9.pngbin211785 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/empty.txt0
-rw-r--r--o3d/samples/waterdemo/assets/horizon_ramp.pngbin2961 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/horizon_ramp_1.pngbin2961 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/main_rock_normal.ddsbin524416 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/noise.pngbin467149 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/reflectivity_map.pngbin170 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/rock_reflection_new.pngbin24018 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/rock_tile_normal_x.jpgbin5102958 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/rock_tile_rgb.jpgbin3558437 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/sky_compat.pngbin147484 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/sun_compat.pngbin55036 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/sun_ramp.pngbin2950 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/assets/sun_ramp_1.pngbin2950 -> 0 bytes
-rw-r--r--o3d/samples/waterdemo/cameracontrol.js123
-rw-r--r--o3d/samples/waterdemo/uicomponents.js112
-rw-r--r--o3d/samples/waterdemo/waterdemo.html439
-rw-r--r--o3d/samples/waterdemo/waterdemo.js646
-rw-r--r--o3d/samples/yuv2rgb.html196
-rw-r--r--o3d/samples/zsorting.html200
-rw-r--r--o3d/serializer/cross/README.txt67
-rw-r--r--o3d/serializer/cross/serializer.cc948
-rw-r--r--o3d/serializer/cross/serializer.h216
-rw-r--r--o3d/serializer/cross/serializer_binary.cc263
-rw-r--r--o3d/serializer/cross/serializer_binary.h56
-rw-r--r--o3d/serializer/cross/serializer_test.cc1171
-rw-r--r--o3d/serializer/cross/version.h45
-rw-r--r--o3d/serializer/serializer.gyp53
-rw-r--r--o3d/standalone/standalone.cc5
-rw-r--r--o3d/standalone/standalone.gyp144
-rw-r--r--o3d/statsreport/aggregator-mac.h77
-rw-r--r--o3d/statsreport/aggregator-mac.mm152
-rw-r--r--o3d/statsreport/aggregator-posix-inl.h61
-rw-r--r--o3d/statsreport/aggregator-posix.cc193
-rw-r--r--o3d/statsreport/aggregator-posix.h84
-rw-r--r--o3d/statsreport/aggregator-win32.cc172
-rw-r--r--o3d/statsreport/aggregator-win32.h104
-rw-r--r--o3d/statsreport/aggregator-win32_unittest.cc116
-rw-r--r--o3d/statsreport/aggregator-win32_unittest.h78
-rw-r--r--o3d/statsreport/aggregator.cc94
-rw-r--r--o3d/statsreport/aggregator.h77
-rw-r--r--o3d/statsreport/aggregator_unittest.cc140
-rw-r--r--o3d/statsreport/aggregator_unittest.h85
-rw-r--r--o3d/statsreport/common/const_product.h91
-rw-r--r--o3d/statsreport/common/highres_timer-linux.cc59
-rw-r--r--o3d/statsreport/common/highres_timer-linux.h106
-rw-r--r--o3d/statsreport/common/highres_timer-mac.cc70
-rw-r--r--o3d/statsreport/common/highres_timer-mac.h103
-rw-r--r--o3d/statsreport/common/highres_timer-win32.cc72
-rw-r--r--o3d/statsreport/common/highres_timer-win32.h105
-rw-r--r--o3d/statsreport/common/highres_timer.h40
-rw-r--r--o3d/statsreport/common/highres_timer_unittest.cc84
-rw-r--r--o3d/statsreport/const-mac.h52
-rw-r--r--o3d/statsreport/const-mac.mm68
-rw-r--r--o3d/statsreport/const-posix.cc44
-rw-r--r--o3d/statsreport/const-posix.h49
-rw-r--r--o3d/statsreport/const-win32.cc46
-rw-r--r--o3d/statsreport/const-win32.h48
-rw-r--r--o3d/statsreport/const_server.h54
-rw-r--r--o3d/statsreport/formatter.cc93
-rw-r--r--o3d/statsreport/formatter.h79
-rw-r--r--o3d/statsreport/formatter_unittest.cc54
-rw-r--r--o3d/statsreport/lock.h63
-rw-r--r--o3d/statsreport/metrics.cc276
-rw-r--r--o3d/statsreport/metrics.h561
-rw-r--r--o3d/statsreport/metrics_unittest.cc398
-rw-r--r--o3d/statsreport/persistent_iterator-win32.cc163
-rw-r--r--o3d/statsreport/persistent_iterator-win32.h152
-rw-r--r--o3d/statsreport/persistent_iterator-win32_unittest.cc164
-rw-r--r--o3d/statsreport/statsreport.gyp130
-rw-r--r--o3d/statsreport/uploader-mac.mm97
-rw-r--r--o3d/statsreport/uploader-posix.cc76
-rw-r--r--o3d/statsreport/uploader-win32.cc106
-rw-r--r--o3d/statsreport/uploader.h77
-rw-r--r--o3d/statsreport/uploader_aggregation-mac.mm244
-rw-r--r--o3d/statsreport/uploader_aggregation-posix.cc154
-rw-r--r--o3d/statsreport/uploader_aggregation-win32.cc193
-rw-r--r--o3d/statsreport/util-win32.h53
-rw-r--r--o3d/tests/archive_files/BumpReflect.fx99
-rw-r--r--o3d/tests/archive_files/bogus.tar.gz4
-rw-r--r--o3d/tests/archive_files/keyboard.jpgbin37521 -> 0 bytes
-rw-r--r--o3d/tests/archive_files/keyboard.jpg.gzbin29434 -> 0 bytes
-rw-r--r--o3d/tests/archive_files/perc.aifbin155526 -> 0 bytes
-rw-r--r--o3d/tests/archive_files/test1.tarbin6656 -> 0 bytes
-rw-r--r--o3d/tests/archive_files/test1.tar.gzbin248 -> 0 bytes
-rw-r--r--o3d/tests/archive_files/test2.tar.gzbin148746 -> 0 bytes
-rw-r--r--o3d/tests/basic_system_test/basic_system_test.cc340
-rw-r--r--o3d/tests/basic_system_test/reference_frames/frame_capture0.pngbin2454 -> 0 bytes
-rw-r--r--o3d/tests/basic_system_test/reference_frames/frame_capture1.pngbin2738 -> 0 bytes
-rw-r--r--o3d/tests/basic_system_test/reference_frames/frame_capture2.pngbin2735 -> 0 bytes
-rw-r--r--o3d/tests/basic_system_test/reference_frames/frame_capture3.pngbin2719 -> 0 bytes
-rw-r--r--o3d/tests/basic_system_test/reference_frames/frame_capture4.pngbin2764 -> 0 bytes
-rw-r--r--o3d/tests/basic_system_test/reference_stream.csv242
-rw-r--r--o3d/tests/bitmap_test/5kx5k.ddsbin4096 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/5kx5k.jpgbin147286 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/5kx5k.pngbin84347 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/5kx5k.tgabin4096 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/dds-dxt1-256x256-alpha.ddsbin32896 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/dds-dxt1-256x256-mipmap.ddsbin43832 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/dds-dxt1-256x256.ddsbin32896 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/dds-dxt3-256x256-alpha.ddsbin65664 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/dds-dxt3-256x256-mipmap.ddsbin87536 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/dds-dxt5-256x256-alpha.ddsbin65664 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/dds-dxt5-256x256-mipmap.ddsbin87536 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/gif-256x256-interlaced.gifbin35523 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/gif-256x256.gifbin30735 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/jpeg-256x256.jpgbin48355 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/png-20x14-4bit-palette.pngbin267 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/png-256x256-24bit-interlaced.pngbin76052 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/png-256x256-24bit.pngbin52647 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/png-256x256-32bit.pngbin74812 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/png-256x256-8bit-palette-alpha.pngbin18474 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/png-256x256-8bit-palette.pngbin18216 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/png-2x2-24bit-drawimage-src.pngbin100 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/png-4x4-24bit-drawimage-argb8-src.pngbin203 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/png-4x4-24bit-drawimage-src.pngbin98 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/png-8x4-24bit-drawimage-argb8-dest.pngbin180 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/png-8x4-24bit-drawimage-dest.pngbin104 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/png-8x8-24bit-drawimage-src.pngbin102 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/test_source.psdbin1742489 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/tga-256x256-24bit.tgabin196652 -> 0 bytes
-rw-r--r--o3d/tests/bitmap_test/tga-256x256-32bit.tgabin262188 -> 0 bytes
-rw-r--r--o3d/tests/common/cross/main.cc49
-rw-r--r--o3d/tests/common/cross/test_utils.cc68
-rw-r--r--o3d/tests/common/cross/test_utils.h51
-rw-r--r--o3d/tests/common/linux/testing_common.cc171
-rw-r--r--o3d/tests/common/mac/testing_common.mm141
-rw-r--r--o3d/tests/common/win/dxcapture.cc140
-rw-r--r--o3d/tests/common/win/dxcapture.h68
-rw-r--r--o3d/tests/common/win/system_test.h82
-rw-r--r--o3d/tests/common/win/testing_common.cc212
-rw-r--r--o3d/tests/common/win/testing_common.h66
-rw-r--r--o3d/tests/keyboard_info.html126
-rw-r--r--o3d/tests/lab/ChangeResolution/build.bat21
-rw-r--r--o3d/tests/lab/ChangeResolution/change_resolution.cpp123
-rw-r--r--o3d/tests/lab/ChangeResolution/change_resolution.gyp25
-rw-r--r--o3d/tests/lab/__init__.py0
-rw-r--r--o3d/tests/lab/browsers.py216
-rw-r--r--o3d/tests/lab/configure_ie.py303
-rw-r--r--o3d/tests/lab/run_lab_test.py320
-rw-r--r--o3d/tests/lab/runner_constants.py98
-rw-r--r--o3d/tests/lab/runner_util.py165
-rw-r--r--o3d/tests/lab/util.py371
-rwxr-xr-xo3d/tests/mac/unit_tests_install_name.sh10
-rw-r--r--o3d/tests/package_tests.bat37
-rw-r--r--o3d/tests/presubmit_tests.bat35
-rw-r--r--o3d/tests/selenium/__init__.py0
-rw-r--r--o3d/tests/selenium/javascript_unit_test_list.txt103
-rw-r--r--o3d/tests/selenium/javascript_unit_tests.py302
-rw-r--r--o3d/tests/selenium/mac_chrome.sh2
-rw-r--r--o3d/tests/selenium/main.py743
-rw-r--r--o3d/tests/selenium/pdiff_test.py132
-rw-r--r--o3d/tests/selenium/run.bat34
-rw-r--r--o3d/tests/selenium/sample_list.txt148
-rw-r--r--o3d/tests/selenium/samples_tests.py527
-rw-r--r--o3d/tests/selenium/selenium.gyp281
-rw-r--r--o3d/tests/selenium/selenium_constants.py71
-rw-r--r--o3d/tests/selenium/selenium_utilities.py354
-rw-r--r--o3d/tests/selenium/test_runner.py412
-rw-r--r--o3d/tests/selenium/tests/assets/archive.o3dtgzbin308669 -> 0 bytes
-rw-r--r--o3d/tests/selenium/tests/base-test.html89
-rw-r--r--o3d/tests/selenium/tests/culling-zsort-test.html459
-rw-r--r--o3d/tests/selenium/tests/drawshapes.html395
-rw-r--r--o3d/tests/selenium/tests/effect-import-test.html154
-rw-r--r--o3d/tests/selenium/tests/event-test.html284
-rw-r--r--o3d/tests/selenium/tests/features-test.html157
-rw-r--r--o3d/tests/selenium/tests/init-status-test.html117
-rw-r--r--o3d/tests/selenium/tests/math-test.html886
-rw-r--r--o3d/tests/selenium/tests/no-rendergraph.html80
-rw-r--r--o3d/tests/selenium/tests/non-cachable-params.html250
-rw-r--r--o3d/tests/selenium/tests/offscreen-test.html158
-rw-r--r--o3d/tests/selenium/tests/ownership-test.html210
-rw-r--r--o3d/tests/selenium/tests/param-array-test.html307
-rw-r--r--o3d/tests/selenium/tests/pixel-perfection.html337
-rw-r--r--o3d/tests/selenium/tests/quaternion-test.html336
-rw-r--r--o3d/tests/selenium/tests/render-target-clear-test.html156
-rw-r--r--o3d/tests/selenium/tests/render-test.html136
-rw-r--r--o3d/tests/selenium/tests/serialization-test.html1531
-rw-r--r--o3d/tests/selenium/tests/test-test.html368
-rw-r--r--o3d/tests/selenium/tests/texture-set-test.html496
-rw-r--r--o3d/tests/selenium/tests/type-test.html166
-rw-r--r--o3d/tests/selenium/tests/util-test.html111
-rw-r--r--o3d/tests/selenium/tests/v8-test.html784
-rw-r--r--o3d/tests/selenium/tests/version-check-test.html90
-rw-r--r--o3d/tests/selenium/tests/window-overlap-test.html119
-rw-r--r--o3d/tests/selenium/tests/window-overlap-top.html63
-rw-r--r--o3d/tests/selenium/unpack_firefox.py90
-rw-r--r--o3d/tests/test_driver.bat33
-rw-r--r--o3d/tests/test_driver.py433
-rw-r--r--o3d/tests/testing_framework_hardware.PIXExp2
-rw-r--r--o3d/tests/testing_framework_reference.PIXExp2
-rw-r--r--o3d/tests/tests.gyp251
-rw-r--r--o3d/utils/cross/base64.cc218
-rw-r--r--o3d/utils/cross/base64.h92
-rw-r--r--o3d/utils/cross/base64_test.cc170
-rw-r--r--o3d/utils/cross/dataurl.cc113
-rw-r--r--o3d/utils/cross/dataurl.h70
-rw-r--r--o3d/utils/cross/dataurl_test.cc125
-rw-r--r--o3d/utils/cross/file_path_utils.cc222
-rw-r--r--o3d/utils/cross/file_path_utils.h90
-rw-r--r--o3d/utils/cross/file_path_utils_test.cc237
-rw-r--r--o3d/utils/cross/file_text_reader.cc190
-rw-r--r--o3d/utils/cross/file_text_reader.h73
-rw-r--r--o3d/utils/cross/file_text_reader_test.cc266
-rw-r--r--o3d/utils/cross/file_text_writer.cc70
-rw-r--r--o3d/utils/cross/file_text_writer.h70
-rw-r--r--o3d/utils/cross/json_writer.cc246
-rw-r--r--o3d/utils/cross/json_writer.h121
-rw-r--r--o3d/utils/cross/json_writer_test.cc212
-rw-r--r--o3d/utils/cross/math_gtest.cc119
-rw-r--r--o3d/utils/cross/math_gtest.h71
-rw-r--r--o3d/utils/cross/math_gtest_test.cc70
-rw-r--r--o3d/utils/cross/string_reader.cc110
-rw-r--r--o3d/utils/cross/string_reader.h71
-rw-r--r--o3d/utils/cross/string_reader_test.cc200
-rw-r--r--o3d/utils/cross/string_writer.cc55
-rw-r--r--o3d/utils/cross/string_writer.h62
-rw-r--r--o3d/utils/cross/string_writer_test.cc120
-rw-r--r--o3d/utils/cross/structured_writer.h103
-rw-r--r--o3d/utils/cross/temporary_file.cc89
-rw-r--r--o3d/utils/cross/temporary_file.h86
-rw-r--r--o3d/utils/cross/temporary_file_test.cc120
-rw-r--r--o3d/utils/cross/text_reader.cc66
-rw-r--r--o3d/utils/cross/text_reader.h91
-rw-r--r--o3d/utils/cross/text_writer.cc104
-rw-r--r--o3d/utils/cross/text_writer.h95
-rw-r--r--o3d/utils/utils.gyp75
1634 files changed, 0 insertions, 335296 deletions
diff --git a/o3d/DEPS b/o3d/DEPS
deleted file mode 100644
index e616b26..0000000
--- a/o3d/DEPS
+++ /dev/null
@@ -1,193 +0,0 @@
-vars = {
- "chromium_trunk": "http://src.chromium.org/svn/trunk",
- "nixysa_rev": "73",
- # When updating the chromium rev, you must also update the nss and sqlite
- # revs to match the version pulled-in by Chromium's own DEPS in the new rev.
- "chromium_rev": "51794",
- "chromium_breakpad_rev": "50763",
- "o3d_code_rev": "235",
- "skia_rev": "586",
- "gyp_rev": "899",
- "gtest_rev": "408",
- "gflags_rev": "30",
- "breakpad_rev": "604",
- "v8_rev": "5017",
-}
-
-deps = {
- "o3d/o3d_assets":
- "http://o3d.googlecode.com/svn/trunk/googleclient/o3d_assets@" + Var("o3d_code_rev"),
-
- "third_party/antlr3":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/antlr3@" + Var("o3d_code_rev"),
-
- "third_party/cg":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/cg@" + Var("o3d_code_rev"),
-
- "third_party/fcollada":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/fcollada@" + Var("o3d_code_rev"),
-
- "third_party/glew":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/glew@" + Var("o3d_code_rev"),
-
- "third_party/jsdoctoolkit":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/jsdoctoolkit@" + Var("o3d_code_rev"),
-
- "third_party/libevent":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/libevent@" + Var("o3d_code_rev"),
-
- "third_party/makeself":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/makeself@" + Var("o3d_code_rev"),
-
- "third_party/pdiff":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/pdiff@" + Var("o3d_code_rev"),
-
- "third_party/zip_utils":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/zip_utils@" + Var("o3d_code_rev"),
-
- "third_party/selenium_rc":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/selenium_rc@" + Var("o3d_code_rev"),
-
-# Stuff that is O3D specific (from a Chrome point of view).
-
- "o3d/third_party/glu":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/glu@" + Var("o3d_code_rev"),
-
- "o3d/third_party/libtxc_dxtn":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/libtxc_dxtn@" + Var("o3d_code_rev"),
-
- "o3d/third_party/vectormath":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/vectormath@" + Var("o3d_code_rev"),
-
- "o3d/third_party/nixysa":
- "http://nixysa.googlecode.com/svn/trunk/nixysa@" + Var("nixysa_rev"),
-
- "o3d/third_party/npapi":
- "http://nixysa.googlecode.com/svn/trunk/third_party/npapi@" + Var("nixysa_rev"),
-
- "o3d/third_party/ply":
- "http://nixysa.googlecode.com/svn/trunk/third_party/ply-3.1@" + Var("nixysa_rev"),
-
- "o3d/third_party/gflags":
- "http://google-gflags.googlecode.com/svn/trunk@" + Var("gflags_rev"),
-
-# Stuff from the Chromium tree.
-
- "third_party/harfbuzz":
- Var("chromium_trunk") + "/src/third_party/harfbuzz@" + Var("chromium_rev"),
-
- "third_party/icu":
- Var("chromium_trunk") + "/deps/third_party/icu42@" + Var("chromium_rev"),
-
- "third_party/libevent":
- Var("chromium_trunk") + "/src/third_party/libevent@" + Var("chromium_rev"),
-
- "third_party/libjpeg":
- Var("chromium_trunk") + "/src/third_party/libjpeg@" + Var("chromium_rev"),
-
- "third_party/libpng":
- Var("chromium_trunk") + "/src/third_party/libpng@" + Var("chromium_rev"),
-
- "third_party/modp_b64":
- Var("chromium_trunk") + "/src/third_party/modp_b64@" + Var("chromium_rev"),
-
- "chrome/third_party/wtl":
- Var("chromium_trunk") + "/src/third_party/wtl@" + Var("chromium_rev"),
-
- "third_party/zlib":
- Var("chromium_trunk") + "/src/third_party/zlib@" + Var("chromium_rev"),
-
- "third_party/skia":
- "http://skia.googlecode.com/svn/trunk@" + Var("skia_rev"),
-
- "v8":
- "http://v8.googlecode.com/svn/trunk@" + Var("v8_rev"),
-
- "testing":
- Var("chromium_trunk") + "/src/testing@" + Var("chromium_rev"),
-
- "skia":
- Var("chromium_trunk") + "/src/skia@" + Var("chromium_rev"),
-
- "breakpad":
- Var("chromium_trunk") + "/src/breakpad@" + Var("chromium_breakpad_rev"),
-
- "base":
- Var("chromium_trunk") + "/src/base@" + Var("chromium_rev"),
-
- "ipc":
- Var("chromium_trunk") + "/src/ipc@" + Var("chromium_rev"),
-
- "native_client":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/native_client@" + Var("o3d_code_rev"),
-
- "net":
- Var("chromium_trunk") + "/src/net@" + Var("chromium_rev"),
-
- "breakpad/src":
- "http://google-breakpad.googlecode.com/svn/trunk/src@" + Var("breakpad_rev"),
-
- "testing/gtest":
- "http://googletest.googlecode.com/svn/trunk@" + Var("gtest_rev"),
-
- "testing/gmock":
- Var("chromium_trunk") + "/src/testing/gmock@" + Var("chromium_rev"),
-
- # Dependency of chrome base
- "third_party/nss":
- Var("chromium_trunk") + "/deps/third_party/nss@48440",
-
- # Dependency of nss, even though its DEPS fail to mention that.
- "third_party/sqlite":
- Var("chromium_trunk") + "/src/third_party/sqlite@51584",
-
- # Stuff needed for GYP to run
- "build":
- Var("chromium_trunk") + "/src/build@" + Var("chromium_rev"),
-
- "tools/gyp":
- "http://gyp.googlecode.com/svn/trunk@" + Var("gyp_rev"),
-}
-
-deps_os = {
- "win": {
- "third_party/wix_2_0_4221":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/wix_2_0_4221@" + Var("o3d_code_rev"),
-
- "third_party/cygwin":
- "/trunk/deps/third_party/cygwin@11984",
-
- "third_party/python_24":
- Var("chromium_trunk") + "/deps/third_party/python_24@19441",
-
- "third_party/pixman":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/pixman@" + Var("o3d_code_rev"),
-
- "third_party/cairo":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/cairo@" + Var("o3d_code_rev"),
- },
- "mac": {
- "third_party/pixman":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/pixman@" + Var("o3d_code_rev"),
-
- "third_party/pkg-config":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/pkg-config@" + Var("o3d_code_rev"),
-
- "third_party/cairo":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/cairo@" + Var("o3d_code_rev"),
- },
- "unix": {
- # Linux, really.
- "tools/xdisplaycheck":
- Var("chromium_trunk") + "/src/tools/xdisplaycheck@" + Var("chromium_rev"),
- },
-}
-
-hooks = [
- {
- # A change to a .gyp, .gypi, or to GYP itself should run the generator.
- "pattern": "\\.gypi?$|[/\\\\]src[/\\\\]tools[/\\\\]gyp[/\\\\]|[/\\\\]src[/\\\\]o3d[/\\\\]build[/\\\\]gyp_o3d$|MANIFEST$",
- "action": ["python", "o3d/build/gyp_o3d", "o3d/build/o3d.gyp", "o3d/tests/lab/ChangeResolution/change_resolution.gyp"],
- },
-]
-
diff --git a/o3d/DEPS_chrome b/o3d/DEPS_chrome
deleted file mode 100644
index e805e9e..0000000
--- a/o3d/DEPS_chrome
+++ /dev/null
@@ -1,72 +0,0 @@
-vars = {
- "o3d_code_rev": "157",
-}
-
-deps = {
- "src/o3d/o3d_assets":
- "http://o3d.googlecode.com/svn/trunk/googleclient/o3d_assets@" + Var("o3d_code_rev"),
-
- "src/third_party/antlr3":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/antlr3@" + Var("o3d_code_rev"),
-
- "src/third_party/cg":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/cg@" + Var("o3d_code_rev"),
-
- "src/third_party/fcollada":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/fcollada@" + Var("o3d_code_rev"),
-
- "src/third_party/jsdoctoolkit":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/jsdoctoolkit@" + Var("o3d_code_rev"),
-
- "src/third_party/pdiff":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/pdiff@" + Var("o3d_code_rev"),
-
- "src/third_party/zip_utils":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/zip_utils@" + Var("o3d_code_rev"),
-
- "src/third_party/selenium_rc":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/selenium_rc@" + Var("o3d_code_rev"),
-}
-
-deps_os = {
- "win": {
- "src/third_party/wix_2_0_4221":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/wix_2_0_4221@" + Var("o3d_code_rev"),
- },
-}
-vars = {
- "o3d_code_rev": "149",
-}
-
-deps = {
- "src/o3d/o3d_assets":
- "http://o3d.googlecode.com/svn/trunk/googleclient/o3d_assets@" + Var("o3d_code_rev"),
-
- "src/third_party/antlr3":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/antlr3@" + Var("o3d_code_rev"),
-
- "src/third_party/cg":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/cg@" + Var("o3d_code_rev"),
-
- "src/third_party/fcollada":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/fcollada@" + Var("o3d_code_rev"),
-
- "src/third_party/jsdoctoolkit":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/jsdoctoolkit@" + Var("o3d_code_rev"),
-
- "src/third_party/pdiff":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/pdiff@" + Var("o3d_code_rev"),
-
- "src/third_party/zip_utils":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/zip_utils@" + Var("o3d_code_rev"),
-
- "src/third_party/selenium_rc":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/selenium_rc@" + Var("o3d_code_rev"),
-}
-
-deps_os = {
- "win": {
- "src/third_party/wix_2_0_4221":
- "http://o3d.googlecode.com/svn/trunk/googleclient/third_party/wix_2_0_4221@" + Var("o3d_code_rev"),
- },
-} \ No newline at end of file
diff --git a/o3d/PRESUBMIT.py b/o3d/PRESUBMIT.py
deleted file mode 100755
index c80f02e..0000000
--- a/o3d/PRESUBMIT.py
+++ /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.
-
-import os
-import sys
-
-EXCLUDED_PATHS = (
- r"breakpad[\\\/].*",
- r"o3d_assets[\\\/].*",
- r"third_party[\\\/].*",
-)
-
-def FindOnPage(input_api, url, regex):
- """Given a url, download it and find the part matching a regex.
- Arguments:
- input_api: the limited set of input modules allowed in presubmit
- url: url to download
- regex: regex to match on
- Returns:
- A string extracted from the match, or None if no match or error.
- """
- try:
- connection = input_api.urllib2.urlopen(url)
- text = connection.read()
- connection.close()
- match = input_api.re.search(regex, text)
- if match:
- return match.group(1)
- else:
- return None
- except IOError, e:
- print str(e)
- return None
-
-
-def CheckTreeIsOpen(input_api, output_api, url, url_text):
- """Similar to the one in presubmit_canned_checks except it shows an helpful
- status text instead.
- Arguments:
- input_api: the limited set of input modules allowed in presubmit
- output_api: the limited set of output modules allowed in presubmit
- url: url to get numerical tree status from
- url_text: url to get human readable tree status from
- regex: regex to match on
- Returns:
- A list of presubmit warnings.
- """
- assert(input_api.is_committing)
- # Check if tree is open.
- status = FindOnPage(input_api, url, '([0-9]+)')
- if status and int(status):
- return []
- # Try to find out what failed.
- message = FindOnPage(input_api, url_text,
- r'\<div class\="Notice"\>(.*)\<\/div\>')
- if message:
- return [output_api.PresubmitPromptWarning("The tree is closed.",
- long_text=message.strip())]
- # Report unknown reason.
- return [output_api.PresubmitPromptWarning(
- "The tree status can't be checked.")]
-
-
-def CheckChangeOnUpload(input_api, output_api):
- report = []
- black_list = input_api.DEFAULT_BLACK_LIST + EXCLUDED_PATHS
- sources = lambda x: input_api.FilterSourceFile(x, black_list=black_list)
- report.extend(input_api.canned_checks.CheckChangeSvnEolStyle(
- input_api, output_api, sources))
- return report
-
-
-def CheckChangeOnCommit(input_api, output_api):
- report = []
- black_list = input_api.DEFAULT_BLACK_LIST + EXCLUDED_PATHS
- sources = lambda x: input_api.FilterSourceFile(x, black_list=black_list)
- report.extend(input_api.canned_checks.CheckChangeSvnEolStyle(
- input_api, output_api, sources))
- report.extend(CheckTreeIsOpen(
- input_api, output_api,
- 'http://o3d-status.appspot.com/status',
- 'http://o3d-status.appspot.com/current'))
- return report
diff --git a/o3d/README b/o3d/README
deleted file mode 100644
index f0c492a..0000000
--- a/o3d/README
+++ /dev/null
@@ -1,4 +0,0 @@
-This is the Google O3D source code, currently copied from the
-code.google.com repository at http://code.google.com/p/o3d
-
-It is currently not referenced or built as part of the Chrome build. \ No newline at end of file
diff --git a/o3d/base/cross/bits.h b/o3d/base/cross/bits.h
deleted file mode 100644
index 7be7b73..0000000
--- a/o3d/base/cross/bits.h
+++ /dev/null
@@ -1,76 +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 some bit utilities.
-
-#ifndef O3D_BASE_CROSS_BITS_H_
-#define O3D_BASE_CROSS_BITS_H_
-
-#include "base/logging.h"
-
-namespace o3d {
-namespace base {
-namespace bits {
-
-// Returns the integer i such as 2^i <= n < 2^(i+1)
-static inline int Log2Floor(unsigned int n) {
- if (n == 0)
- return -1;
- int log = 0;
- unsigned int value = n;
- for (int i = 4; i >= 0; --i) {
- int shift = (1 << i);
- unsigned int x = value >> shift;
- if (x != 0) {
- value = x;
- log += shift;
- }
- }
- DCHECK_EQ(value, 1u);
- return log;
-}
-
-// Returns the integer i such as 2^(i-1) < n <= 2^i
-static inline int Log2Ceiling(unsigned int n) {
- if (n == 0) {
- return -1;
- } else {
- // Log2Floor returns -1 for 0, so the following works correctly for n=1.
- return 1 + Log2Floor(n - 1);
- }
-}
-
-} // namespace bits
-} // namespace base
-} // namespace o3d
-
-#endif // O3D_BASE_CROSS_BITS_H_
diff --git a/o3d/base/cross/bits_test.cc b/o3d/base/cross/bits_test.cc
deleted file mode 100644
index 4db01a0..0000000
--- a/o3d/base/cross/bits_test.cc
+++ /dev/null
@@ -1,78 +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 unit tests for the bit utilities.
-
-#include "base/cross/bits.h"
-#include "tests/common/win/testing_common.h"
-
-namespace o3d {
-namespace base {
-namespace bits {
-
-TEST(Bits, TestLog2Floor) {
- EXPECT_EQ(-1, Log2Floor(0));
- EXPECT_EQ(0, Log2Floor(1));
- EXPECT_EQ(1, Log2Floor(2));
- EXPECT_EQ(1, Log2Floor(3));
- EXPECT_EQ(2, Log2Floor(4));
- for (unsigned int i = 3; i < 31; ++i) {
- unsigned int value = 1U << i;
- EXPECT_EQ(i, Log2Floor(value));
- EXPECT_EQ(i, Log2Floor(value + 1));
- EXPECT_EQ(i, Log2Floor(value + 2));
- EXPECT_EQ(i - 1, Log2Floor(value - 1));
- EXPECT_EQ(i - 1, Log2Floor(value - 2));
- }
- EXPECT_EQ(31, Log2Floor(0xffffffffU));
-}
-
-TEST(Bits, TestLog2Ceiling) {
- EXPECT_EQ(-1, Log2Ceiling(0));
- EXPECT_EQ(0, Log2Ceiling(1));
- EXPECT_EQ(1, Log2Ceiling(2));
- EXPECT_EQ(2, Log2Ceiling(3));
- EXPECT_EQ(2, Log2Ceiling(4));
- for (unsigned int i = 3; i < 31; ++i) {
- unsigned int value = 1U << i;
- EXPECT_EQ(i, Log2Ceiling(value));
- EXPECT_EQ(i + 1, Log2Ceiling(value + 1));
- EXPECT_EQ(i + 1, Log2Ceiling(value + 2));
- EXPECT_EQ(i, Log2Ceiling(value - 1));
- EXPECT_EQ(i, Log2Ceiling(value - 2));
- }
- EXPECT_EQ(32, Log2Ceiling(0xffffffffU));
-}
-
-} // namespace bits
-} // namespace base
-} // namespace o3d
diff --git a/o3d/base/cross/std_functional.h b/o3d/base/cross/std_functional.h
deleted file mode 100644
index 884028a..0000000
--- a/o3d/base/cross/std_functional.h
+++ /dev/null
@@ -1,76 +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 STL functional classes in a cross-compiler way.
-
-#ifndef O3D_BASE_CROSS_STD_FUNCTIONAL_H_
-#define O3D_BASE_CROSS_STD_FUNCTIONAL_H_
-
-#include <build/build_config.h>
-
-#if defined(COMPILER_GCC)
-#include <ext/functional>
-namespace o3d {
-namespace base {
-using __gnu_cxx::select1st;
-using __gnu_cxx::select2nd;
-} // namespace base
-} // namespace o3d
-#elif defined(COMPILER_MSVC)
-#include <functional>
-#include <utility>
-namespace o3d {
-namespace base {
-
-template <class Pair>
-class select1st : public std::unary_function<Pair, typename Pair::first_type> {
- public:
- const result_type &operator()(const argument_type &value) const {
- return value.first;
- }
-};
-
-template <class Pair>
-class select2nd : public std::unary_function<Pair, typename Pair::second_type> {
- public:
- const result_type &operator()(const argument_type &value) const {
- return value.second;
- }
-};
-
-} // namespace base
-} // namespace o3d
-#else
-#error Unsupported compiler
-#endif
-
-#endif // O3D_BASE_CROSS_STD_FUNCTIONAL_H_
diff --git a/o3d/breakpad/breakpad.gyp b/o3d/breakpad/breakpad.gyp
deleted file mode 100644
index d5cdd907..0000000
--- a/o3d/breakpad/breakpad.gyp
+++ /dev/null
@@ -1,99 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- },
- 'includes': [
- '../build/branding.gypi',
- '../build/common.gypi',
- '../build/version.gypi',
- ],
- 'target_defaults': {
- 'include_dirs': [
- '..',
- '../..',
- '../../breakpad/src',
- ],
- 'defines': [
- 'O3D_PLUGIN_VERSION="<(plugin_version)"',
- 'O3D_PLUGIN_INSTALLDIR_CSIDL=<(plugin_installdir_csidl)',
- 'O3D_PLUGIN_VENDOR_DIRECTORY="<(plugin_vendor_directory)"',
- 'O3D_PLUGIN_PRODUCT_DIRECTORY="<(plugin_product_directory)"',
- ],
- },
- 'conditions': [
- ['OS=="mac"',
- {
- 'targets': [
- {
- 'target_name': 'reporter',
- 'type': 'none',
- },
- ],
- },
- ],
- ['OS=="win"',
- {
- 'targets': [
- {
- 'target_name': 'o3dBreakpad',
- 'type': 'static_library',
- 'dependencies': [
- '../../breakpad/breakpad.gyp:breakpad_sender',
- '../../breakpad/breakpad.gyp:breakpad_handler',
- ],
- 'sources': [
- 'win/exception_handler_win32.cc',
- 'win/breakpad_config.cc',
- 'win/bluescreen_detector.cc',
- ],
- 'direct_dependent_settings': {
- 'include_dirs': [
- '../../breakpad/src',
- ],
- },
- },
- {
- 'target_name': 'reporter',
- 'type': 'executable',
- 'dependencies': [
- 'o3dBreakpad',
- ],
- 'sources': [
- 'win/crash_sender_win32.cc',
- '../../<(breakpaddir)/client/windows/sender/crash_report_sender.cc',
- ],
- },
- ],
- },
- ],
- ['OS=="linux"',
- {
- 'targets': [
- {
- 'target_name': 'o3dBreakpad',
- 'type': 'static_library',
- 'sources': [
- 'linux/breakpad.cc',
- 'linux/breakpad.h',
- ],
- 'direct_dependent_settings': {
- 'include_dirs': [
- '../../breakpad/src',
- ],
- },
- },
- ],
- },
- ],
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/breakpad/linux/breakpad.cc b/o3d/breakpad/linux/breakpad.cc
deleted file mode 100644
index 6fec736..0000000
--- a/o3d/breakpad/linux/breakpad.cc
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright 2010, 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 "breakpad.h"
-
-#if defined(LINUX)
-#include <sys/stat.h>
-#endif // defined(LINUX)
-
-#include <cstring>
-
-namespace o3d {
-#if defined(WIN32)
-static const std::string kBreakpadProduct = "Google_O3D_Plugin";
-#elif defined(OSX)
-static const std::string kBreakpadProduct = "Google_O3D_Plugin_Mac";
-#elif defined(LINUX)
-static const std::string kBreakpadProduct = "Google_O3D_Plugin_Linux";
-#endif
-static const std::string kBreakpadVersion = "unknown";
-static const std::string kBreakpadGUID = "unknown";
-static const std::string kBreakpadEmail = "unknown";
-#ifndef NDEBUG
-static const std::string kBreakpadServer =
- "http://clients2.google.com/cr/staging_report";
-#else
-static const std::string kBreakpadServer =
- "http://clients2.google.com/cr/report";
-#endif
-
-//TODO(zhurunz): Add/use decent path utility functions.
-
-bool Breakpad::Initialize() {
- if (NULL != breakpad_)
- return true;
-
- // Set default configuration.
- set_product(kBreakpadProduct);
- set_version(kBreakpadVersion);
- set_guid(kBreakpadGUID);
- set_email(kBreakpadEmail);
- set_path("/tmp/");
- set_server(kBreakpadServer);
-
- // TODO(zhurunz): consider using HANDLE_CRASHES
- // Setup callback.
- breakpad_ = new
- google_breakpad::ExceptionHandler(path_.c_str(),
- NULL, /* filter callback */
- BreakpadCallback,
- this,
- true /* install handlers */);
-
- return (NULL != breakpad_);
-}
-
-bool Breakpad::Shutdown() {
- delete breakpad_;
- breakpad_ = NULL;
- return true;
-}
-
-#if defined(LINUX)
-bool Breakpad::BuildDumpFilename(char* filename,
- int len,
- const char* dump_path,
- const char* minidump_id) {
- const int dump_path_len = strlen(dump_path);
- const int minidump_id_len = strlen(minidump_id);
- int len_needed = dump_path_len + minidump_id_len +
- 4 /* ".dmp" */ + 1 /* NUL */;
- if (len_needed > len)
- return false;
-
- filename[0] = '\0';
- std::strcat(filename, dump_path);
- std::strcat(filename, minidump_id);
- std::strcat(filename, ".dmp");
-
- return true;
-}
-
-bool Breakpad::SendDumpFile(const char* filename) {
- struct stat st;
- if (stat(filename, &st) != 0 || st.st_size <= 0)
- return false;
-
- google_breakpad::GoogleCrashdumpUploader
- uploader(product_.c_str(),
- version_.c_str(),
- guid_.c_str(),
- ptime_.c_str(),
- ctime_.c_str(),
- email_.c_str(),
- comments_.c_str(),
- filename,
- server_.c_str(),
- proxy_.c_str(),
- passwd_.c_str());
- return uploader.Upload();
-}
-
-bool Breakpad::OnBreakpadCallback(const char* dump_path,
- const char* minidump_id,
- bool succeeded) {
- // WARNING: this code runs in a compromised context. It may not call into
- // libc nor allocate memory normally.
- if (!succeeded)
- return succeeded;
-
- // Build dump filename.
- char filename[256];
- if (!BuildDumpFilename(filename, sizeof(filename),
- dump_path, minidump_id))
- return false;
-
- // TODO(zhurunz): Change in-proc upload to out-proc upload.
- // TODO(zhurunz): Sync with other teams in ChromeOS and figure out if
- // we could have a GC proc to upload all dumps on ChromeOS/Linux.
- bool ret = SendDumpFile(filename);
- unlink(filename);
-
- return ret;
-}
-#endif // defined(LINUX)
-
-bool BreakpadCallback(const char* dump_path,
- const char* minidump_id,
- void* context,
- bool succeeded) {
- Breakpad* breakpad = reinterpret_cast<Breakpad*>(context);
- if (NULL == breakpad)
- return false;
-
- return breakpad->OnBreakpadCallback(dump_path, minidump_id, succeeded);
-}
-
-} // namespace o3d
diff --git a/o3d/breakpad/linux/breakpad.h b/o3d/breakpad/linux/breakpad.h
deleted file mode 100644
index ff133a2..0000000
--- a/o3d/breakpad/linux/breakpad.h
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright 2010, 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_LINUX_BREAKPAD_H_
-#define O3D_LINUX_BREAKPAD_H_
-
-#include <string>
-
-#if defined(LINUX)
-#include "client/linux/handler/exception_handler.h"
-#include "client/linux/minidump_writer/minidump_writer.h"
-#include "common/linux/linux_syscall_support.h"
-#include "common/linux/google_crashdump_uploader.h"
-#endif // defined(LINUX)
-
-namespace o3d {
-class Breakpad {
- public:
- const std::string& product() const { return product_; }
- void set_product(const std::string & product) { product_ = product; }
-
- const std::string& version() const { return version_; }
- void set_version(const std::string & version) { version_ = version; }
-
- const std::string& guid() const { return guid_; }
- void set_guid(const std::string & guid) { guid_ = guid; }
-
- const std::string& email() const { return email_; }
- void set_email(const std::string & email) { email_ = email; }
-
- const std::string& path() const { return path_; }
- void set_path(const std::string & path) { path_ = path; }
-
- const std::string& server() const { return server_; }
- void set_server(const std::string & server) { server_ = server; }
-
- bool Initialize();
- bool Shutdown();
-
- private:
- static bool BuildDumpFilename(char* filename,
- int len,
- const char* dump_path,
- const char* minidump_id);
-
- // This is virtual to allow unittest to overwirte it and not sending
- // out minidump file in test.
- virtual bool SendDumpFile(const char* filename);
-
- // Invoked by friend function BreakpadCallback
- bool OnBreakpadCallback(const char* dump_path,
- const char* minidump_id,
- bool succeeded);
-
- friend bool BreakpadCallback(const char* dump_path,
- const char* minidump_id,
- void* context,
- bool succeeded);
-
- std::string product_;
- std::string version_;
- std::string guid_;
- std::string ptime_;
- std::string ctime_;
- std::string email_;
- std::string comments_;
- std::string path_;
- std::string server_;
- std::string proxy_;
- std::string passwd_;
-
- google_breakpad::ExceptionHandler* breakpad_;
-};
-
-// Breakpad minidump callback
-// A friend function of Breakpad to invoke OnBreakpadCallback.
-bool BreakpadCallback(const char* dump_path,
- const char* minidump_id,
- void* context,
- bool succeeded);
-
-
-#if defined(LINUX)
-// This provides a wrapper around system calls which may be
-// interrupted by a signal and return EINTR. See man 7 signal.
-#define HANDLE_EINTR(x) ({ \
- typeof(x) __eintr_result__; \
- do { \
- __eintr_result__ = x; \
- } while (__eintr_result__ == -1 && errno == EINTR); \
- __eintr_result__;\
-})
-#endif // defined(LINUX)
-
-} // namespace o3d
-
-#endif // O3D_LINUX_BREAKPAD_H_
diff --git a/o3d/breakpad/win/bluescreen_detector.cc b/o3d/breakpad/win/bluescreen_detector.cc
deleted file mode 100644
index 9143fdc..0000000
--- a/o3d/breakpad/win/bluescreen_detector.cc
+++ /dev/null
@@ -1,332 +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.
- */
-
-
-// BluescreenDetector attempts to identify cases where the machine bluescreened
-// and was caused by o3d.
-
-#include "breakpad/win/bluescreen_detector.h"
-#include "plugin/cross/plugin_logging.h"
-#include "plugin/cross/plugin_metrics.h"
-
-#ifdef OS_WIN
-#include <windows.h>
-#include <rpc.h>
-#endif
-
-extern o3d::PluginLogging* g_logger;
-
-namespace o3d {
-
-using std::vector;
-
-#ifdef OS_WIN
-
-const wchar_t *kMarkerFileSuffix = L"_bs";
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-BluescreenDetector::BluescreenDetector()
- : started_(false) {
- time_manager_ = new TimeManager();
- marker_file_manager_ = new MarkerFileManager(time_manager_);
- bluescreen_logger_ = new BluescreenLogger();
-}
-#endif // OS_WIN
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-BluescreenDetector::~BluescreenDetector() {
- if (started_) {
- Stop();
- }
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void BluescreenDetector::Start() {
- // Here we check if any marker files (from a previous session) were not
- // properly cleaned up. If so, then a blue-screen may have been caused
- // by us and we'll log it.
- int num_bluescreens = marker_file_manager_->DetectStrayMarkerFiles();
-
- if (num_bluescreens > 0) {
- bluescreen_logger_->LogBluescreen(num_bluescreens);
- }
-
- // Create a marker file for this session - it will be removed when the plugin
- // unloads (or in the breakpad exception handler). If a blue-screen happens,
- // then this file will not be deleted and we'll hopefully detect it the next
- // time around (in a call to DetectStrayMarkerFiles())
- marker_file_manager_->CreateMarkerFile();
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void BluescreenDetector::Stop() {
- marker_file_manager_->RemoveMarkerFile();
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// MarkerFileManager
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Base implementation shared by mock and actual sub-classes
-int MarkerFileManagerInterface::DetectStrayMarkerFiles() {
- vector<MarkerFileInfo> marker_files;
- GetMarkerFileList(&marker_files);
-
- // Go through all marker files and look for ones which were created before
- // the machine was last booted
- int stray_file_count = 0;
-
- for (vector<MarkerFileInfo>::size_type i = 0;
- i < marker_files.size(); ++i) {
- const MarkerFileInfo &file_info = marker_files[i];
-
- if (time_manager_->IsMarkerFileOld(file_info)) {
- // We've found a marker file which was created before we last re-booted
- // This could signal a blue-screen which we caused
-
- // Clean it up, so we don't continue detecting it again and logging a
- // blue-screen more than once
- DeleteMarkerFile(file_info);
- ++stray_file_count;
- // don't break here, since we need to detect and delete all old ones
- }
- }
-
- return stray_file_count;
-}
-
-#ifdef OS_WIN
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MarkerFileManager::CreateMarkerFile() {
- if (marker_file_) {
- // error
- return;
- }
-
- std::wstring marker_dir = GetMarkerDirectory();
- std::wstring uuid_string = GetUUIDString();
-
- // format a complete file path for the marker file
- wchar_t fullpath[MAX_PATH];
- _snwprintf(fullpath, MAX_PATH, L"%s%s%s",
- marker_dir.c_str(),
- uuid_string.c_str(),
- kMarkerFileSuffix);
-
- marker_file_name_ = fullpath;
-
- // Note that the file is created with the attribute FILE_FLAG_DELETE_ON_CLOSE
- // so even if the process crashes, this file will get cleaned up.
- // It's only if a bluescreen occurs (or plug is pulled out of wall) that the
- // file will not be deleted (in theory)
- marker_file_ = CreateFileW(fullpath,
- GENERIC_WRITE,
- 0,
- NULL,
- CREATE_NEW,
- FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE,
- NULL);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MarkerFileManager::RemoveMarkerFile() {
- if (marker_file_) {
- // Strictly speaking, we don't really need to delete the file here since
- // the system will do it for us since FILE_FLAG_DELETE_ON_CLOSE was used,
- // but let's do it just to be sure...
- CloseHandle(marker_file_);
- marker_file_ = NULL;
- DeleteFile(marker_file_name_.c_str());
- }
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-static MarkerFileInfo GetMarkerFileInfo(const WIN32_FIND_DATA &find_data,
- const std::wstring &marker_dir) {
- std::wstring file_name = find_data.cFileName;
- std::wstring full_pathname_w = marker_dir + file_name;
- String full_pathname = WideToUTF8(full_pathname_w);
- uint64 creation_time =
- TimeManager::FileTimeToUInt64(find_data.ftCreationTime);
-
- MarkerFileInfo file_info(full_pathname, creation_time);
- return file_info;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool MarkerFileManager::GetMarkerFileList(vector<MarkerFileInfo> *file_list) {
- // Search the marker directory for all files ending in kMarkerFileSuffix
- std::wstring marker_dir = GetMarkerDirectory();
- std::wstring search_string = marker_dir + L"*" + kMarkerFileSuffix;
-
- WIN32_FIND_DATA find_data;
- HANDLE h = ::FindFirstFile(search_string.c_str(), &find_data);
-
- if (h != INVALID_HANDLE_VALUE) {
- MarkerFileInfo file_info = GetMarkerFileInfo(find_data, marker_dir);
- file_list->push_back(file_info);
-
- BOOL file_valid = true;
-
- while (file_valid) {
- file_valid = ::FindNextFile(h, &find_data);
- if (file_valid) {
- MarkerFileInfo file_info = GetMarkerFileInfo(find_data, marker_dir);
- file_list->push_back(file_info);
- }
- }
-
- ::FindClose(h);
- } else {
- // This can happen if there are no marker files found
- return true;
- }
-
- return true;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MarkerFileManager::DeleteMarkerFile(const MarkerFileInfo &file_info) {
- std::wstring filename_w = UTF8ToWide(file_info.GetName());
- ::DeleteFileW(filename_w.c_str());
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-const std::wstring MarkerFileManager::GetUUIDString() {
- // now generate a GUID
- UUID guid = {0};
- ::UuidCreate(&guid);
-
- // and format into a wide-string
- wchar_t guid_string[37];
- _snwprintf(
- guid_string, sizeof(guid_string) / sizeof(guid_string[0]),
- L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
- guid.Data1, guid.Data2, guid.Data3,
- guid.Data4[0], guid.Data4[1], guid.Data4[2],
- guid.Data4[3], guid.Data4[4], guid.Data4[5],
- guid.Data4[6], guid.Data4[7]);
-
- return guid_string;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-const std::wstring MarkerFileManager::GetMarkerDirectory() {
- wchar_t temp_path[MAX_PATH];
- if (!::GetTempPathW(MAX_PATH, temp_path)) {
- return L"c:\\windows\\temp\\";
- }
- return temp_path;
-}
-
-#endif // OS_WIN
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// TimeManager
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool TimeManagerInterface::IsMarkerFileOld(const MarkerFileInfo &file_info) {
- uint64 creation_time = file_info.GetCreationTime();
- uint64 current_time = GetCurrentTime();
-
- if (current_time < creation_time) {
- // should never happen, but log error
- return false; // something wrong has happened here
- }
-
- uint64 file_time_since_now = current_time - creation_time;
- uint64 up_time = GetUpTime();
-
- bool is_old = (file_time_since_now > up_time);
- return is_old;
-}
-
-#ifdef OS_WIN
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-uint64 TimeManager::FileTimeToUInt64(FILETIME time) {
- // FILETIME units are 100-nanosecond intervals
- ULARGE_INTEGER li;
- li.LowPart = time.dwLowDateTime;
- li.HighPart = time.dwHighDateTime;
- return li.QuadPart;
-}
-
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-uint64 TimeManager::GetCurrentTime() {
- SYSTEMTIME current_time;
- ::GetSystemTime(&current_time);
-
- FILETIME file_time;
- ::SystemTimeToFileTime(&current_time, &file_time);
-
- // Now convert to uint64...
- return FileTimeToUInt64(file_time);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// in units of 100-nanosecond intervals (FILETIME units)
-uint64 TimeManager::GetUpTime() {
- // NOTE : It would have been easier to simply use GetTickCount(),
- // but it wraps around to zero after 49.7 days! There is a GetTickCount64()
- // function but it's only available on Vista.
- // Using QueryPerformanceCounter() and QueryPerformanceFrequency() appears
- // to be the best alternative.
-
- uint64 tick_count64 = 0;
- LARGE_INTEGER count;
- LARGE_INTEGER frequency;
- if (QueryPerformanceCounter(&count) &&
- QueryPerformanceFrequency(&frequency)) {
- LONGLONG total_seconds = count.QuadPart / frequency.QuadPart;
-
- // convert to 100-nanosecond intervals
- const LONGLONG k100NanosecondIntervalsPerSecond = 1000*1000*10;
- tick_count64 = total_seconds * k100NanosecondIntervalsPerSecond;
- }
-
- return tick_count64;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// BluescreenLogger
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void BluescreenLogger::LogBluescreen(int num_bluescreens) {
- metric_bluescreens_total += num_bluescreens;
- // Make sure we write this out to the registry immediately in case we're
- // about to bluescreen again before the metrics timer fires!
- if (g_logger) g_logger->ProcessMetrics(false, true, false);
-}
-#endif // OS_WIN
-
-} // namespace o3d
diff --git a/o3d/breakpad/win/bluescreen_detector.h b/o3d/breakpad/win/bluescreen_detector.h
deleted file mode 100644
index 16f47a6..0000000
--- a/o3d/breakpad/win/bluescreen_detector.h
+++ /dev/null
@@ -1,219 +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.
- */
-
-
-// BluescreenDetector attempts to identify cases where the machine bluescreened
-// and was caused by o3d.
-
-#ifndef CLIENT3D_BREAKPAD_WIN_BLUESCREENDETECTOR_H_
-#define CLIENT3D_BREAKPAD_WIN_BLUESCREENDETECTOR_H_
-
-#include <string.h>
-#include <stdlib.h>
-#include <vector>
-
-#ifdef OS_WIN
-#include <windows.h>
-#endif
-
-#include "base/basictypes.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class MarkerFileInfo {
- public:
- MarkerFileInfo(const String &name, uint64 creation_time)
- : name_(name), creation_time_(creation_time) { };
-
- MarkerFileInfo() : name_(""), creation_time_(0) { };
-
- // explicit copy constructor
- MarkerFileInfo(const MarkerFileInfo& info)
- : name_(info.name_),
- creation_time_(info.creation_time_) { }
-
- const String &GetName() const { return name_; }
- uint64 GetCreationTime() const { return creation_time_; }
-
- private:
- String name_;
- uint64 creation_time_;
-};
-
-//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// We create interfaces so that we can mock these elements in the unit tests
-
-//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// TimeManagerInterface deals with times:
-// - time since boot
-// - current time
-// - file creation time
-//
-// with this information, it helps determine if marker file is "new" or "old"
-// "old" means the file was created before the last time the machine was booted
-//
-
-class TimeManagerInterface {
- public:
- // times are in units of 100-nanosecond intervals (FILETIME units)
- virtual uint64 GetCurrentTime() = 0;
- virtual uint64 GetUpTime() = 0;
-
- // Returns |true| if the marker file was created before the machine
- // was last re-booted
- bool IsMarkerFileOld(const MarkerFileInfo &file_info);
-};
-
-//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Manages a directory where "marker" files will be written. The presence or
-// absence of a marker file, along with its creation date, current time, and
-// time since boot can be used to help determine if a blue-screen has occurred.
-class MarkerFileManagerInterface {
- public:
- MarkerFileManagerInterface(TimeManagerInterface *time_manager)
- : time_manager_(time_manager) {}
-
- virtual void CreateMarkerFile() = 0;
- virtual void RemoveMarkerFile() = 0;
-
-
- // By looking at the creation date, along with the current time,
- // and the "up time" (time since boot) we can tell if any "marker" files were
- // created before boot time. If found, they will be considered as evidence for
- // a blue-screen event in the past. Returns the number of such files found.
- int DetectStrayMarkerFiles();
-
- protected:
- virtual bool GetMarkerFileList(std::vector<MarkerFileInfo> *file_list) = 0;
- virtual void DeleteMarkerFile(const MarkerFileInfo &file_info) = 0;
-
- TimeManagerInterface *time_manager_;
-};
-
-//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class BluescreenLoggerInterface {
- public:
- virtual void LogBluescreen(int num_bluescreens) = 0;
-};
-
-//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Actual implementation
-
-// We only actually implement the interfaces for Windows, but we can unit test
-// (with mocks) on all platforms
-#ifdef OS_WIN
-
-//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class MarkerFileManager : public MarkerFileManagerInterface {
- public:
- MarkerFileManager(TimeManagerInterface *time_manager)
- : MarkerFileManagerInterface(time_manager), marker_file_(NULL) { };
-
- // "marker" file management. The marker file is used to check for future
- // blue-screens.
- virtual void CreateMarkerFile();
- virtual void RemoveMarkerFile();
-
- private:
- virtual bool GetMarkerFileList(std::vector<MarkerFileInfo> *file_list);
- virtual void DeleteMarkerFile(const MarkerFileInfo &file_info);
-
- const std::wstring GetMarkerDirectory();
- const std::wstring GetUUIDString();
-
- HANDLE marker_file_;
- std::wstring marker_file_name_;
-};
-
-//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class TimeManager : public TimeManagerInterface {
- public:
- virtual uint64 GetCurrentTime();
- virtual uint64 GetUpTime();
-
- static uint64 FileTimeToUInt64(FILETIME time);
-};
-
-
-//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class BluescreenLogger : public BluescreenLoggerInterface {
- public:
- // Sends blue-screen info to Google
- virtual void LogBluescreen(int num_bluescreens);
-};
-
-#endif // OS_WIN
-
-
-//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class BluescreenDetector {
- public:
- // Default constructor for real-world use
- BluescreenDetector();
-
- // For mocking/testing
- BluescreenDetector(TimeManagerInterface *time_manager,
- MarkerFileManagerInterface *marker_file_manager,
- BluescreenLoggerInterface *bluescreen_logger)
- : started_(false),
- time_manager_(time_manager),
- marker_file_manager_(marker_file_manager),
- bluescreen_logger_(bluescreen_logger) { }
-
- virtual ~BluescreenDetector();
-
- // Call Start() to check for blue-screens which may have occured and log them
- // if so. Also, writes out a "marker" to be used to check for future
- // blue-screens.
- //
- // Should be called when the plugin first loads
- void Start();
-
- // Call when the plugin unloads - the marker file is deleted here
- // on Windows it's unnecessary to call Stop() since the file will be
- // automatically deleted by the system when the process exits (or crashes)
- void Stop();
-
- private:
- bool started_;
-
- TimeManagerInterface *time_manager_;
- MarkerFileManagerInterface *marker_file_manager_;
- BluescreenLoggerInterface *bluescreen_logger_;
-
- DISALLOW_COPY_AND_ASSIGN(BluescreenDetector);
-};
-
-} // namespace o3d
-
-#endif // CLIENT3D_BREAKPAD_WIN_BLUESCREENDETECTOR_H_
diff --git a/o3d/breakpad/win/bluescreen_detector_test.cc b/o3d/breakpad/win/bluescreen_detector_test.cc
deleted file mode 100644
index ac279f2..0000000
--- a/o3d/breakpad/win/bluescreen_detector_test.cc
+++ /dev/null
@@ -1,322 +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 functionality of the BluescreenDetector class
-
-#include "core/cross/client.h"
-#include "tests/common/win/testing_common.h"
-#include "core/cross/error.h"
-#include "breakpad/win/bluescreen_detector.h"
-#include "plugin/cross/plugin_logging.h"
-
-// This is defined in "main_win.cc" but not in unit tests
-o3d::PluginLogging *g_logger = NULL;
-
-namespace o3d {
-
-// Test fixture for BluescreenDetector testing.
-class BluescreenDetectorTest : public testing::Test {
-};
-
-using std::vector;
-using o3d::MarkerFileInfo;
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Mock implementation
-
-const uint64 kInitialCurrentTime = 20000;
-const uint64 kInitialUpTime = 10000;
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class TimeManagerMock : public TimeManagerInterface {
- public:
- TimeManagerMock()
- : current_time_(kInitialCurrentTime),
- up_time_(kInitialUpTime) { }
-
- virtual uint64 GetCurrentTime() { return current_time_; }
- virtual uint64 GetUpTime() { return up_time_; }
-
- void AdvanceTime(uint64 n) {
- current_time_ += n;
- up_time_ += n;
- }
-
- void SetCurrentTime(uint64 t) { current_time_ = t; }
- void SetUpTime(uint64 t) { up_time_ = t; }
-
- private:
- uint64 current_time_;
- uint64 up_time_;
-};
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class MarkerFileManagerMock : public MarkerFileManagerInterface {
- public:
- MarkerFileManagerMock(TimeManagerMock *time_manager)
- : MarkerFileManagerInterface(time_manager),
- mock_time_manager_(time_manager),
- created_count_(0),
- removed_count_(0) {
- };
-
- // "marker" file management. The marker file is used to check for future
- // blue-screens.
- virtual void CreateMarkerFile();
- virtual void RemoveMarkerFile();
-
- void AddFileEntry(const String &name, uint64 creation_time) {
- file_list_.push_back(MarkerFileInfo(name, creation_time));
- }
-
- // Each should be 1 after the test is run
- int GetCreatedCount() const {
- return created_count_;
- }
-
- int GetRemovedCount() const {
- return removed_count_;
- }
-
- int GetMarkerFileCount() const {
- return file_list_.size();
- }
-
- private:
- virtual bool GetMarkerFileList(vector<MarkerFileInfo> *file_list);
- virtual void DeleteMarkerFile(const MarkerFileInfo &file_info);
-
- TimeManagerMock *mock_time_manager_;
- vector<MarkerFileInfo> file_list_;
- int created_count_;
- int removed_count_;
-};
-
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class BluescreenLoggerMock : public BluescreenLoggerInterface {
- public:
- BluescreenLoggerMock() : bluescreen_count_(0), log_bluescreen_count_(0) { }
-
- // Pretends to send blue-screen info to Google
- virtual void LogBluescreen(int num_bluescreens) {
- ++log_bluescreen_count_; // counts number of times this method is called
- bluescreen_count_ += num_bluescreens;
- }
-
- // Returns number of bluescreens logged
- int GetBluescreenCount() const {
- return bluescreen_count_;
- }
-
- // Returns total number of times LogBluescreen() was called
- // (it should only be called once)
- int GetLogBluescreenCount() const {
- return log_bluescreen_count_;
- }
-
- private:
- int bluescreen_count_;
- int log_bluescreen_count_;
-};
-
-
-
-const String kOurMarkerFileName("OurMarkerFile");
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MarkerFileManagerMock::CreateMarkerFile() {
- AddFileEntry(kOurMarkerFileName, time_manager_->GetCurrentTime());
- mock_time_manager_->AdvanceTime(1);
- created_count_++;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MarkerFileManagerMock::RemoveMarkerFile() {
- for (int i = 0; i < file_list_.size(); ++i) {
- if (file_list_[i].GetName() == kOurMarkerFileName) {
- file_list_.erase(file_list_.begin() + i);
- removed_count_++;
- break;
- }
- }
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool MarkerFileManagerMock::GetMarkerFileList(
- vector<MarkerFileInfo> *file_list) {
- // Just duplicate our interval file list
- for (int i = 0; i < file_list_.size(); ++i) {
- file_list->push_back(file_list_[i]);
- }
- return true;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MarkerFileManagerMock::DeleteMarkerFile(const MarkerFileInfo &file_info) {
- for (int i = 0; i < file_list_.size(); ++i) {
- if (file_list_[i].GetName() == file_info.GetName()) {
- file_list_.erase(file_list_.begin() + i);
- break;
- }
- }
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-// Make sure marker file is written, then removed...
-// This is also testing the case where there was a regular crash
-// (such as "bus error" or "divide-by-zero") in which case the
-// exception handler will call Stop() on the detector (instead of the plugin
-// shutdown code calling it)
-TEST_F(BluescreenDetectorTest, Basic) {
- TimeManagerMock time_manager;
- MarkerFileManagerMock marker_file_manager(&time_manager);
- BluescreenLoggerMock bluescreen_logger;
-
- BluescreenDetector detector(&time_manager,
- &marker_file_manager,
- &bluescreen_logger);
-
- detector.Start();
-
- // Make sure marker file was created (but not yet removed)
- EXPECT_EQ(1, marker_file_manager.GetCreatedCount());
- EXPECT_EQ(0, marker_file_manager.GetRemovedCount());
-
- detector.Stop();
-
- // Make sure marker file was created then removed
- EXPECT_EQ(1, marker_file_manager.GetCreatedCount());
- EXPECT_EQ(1, marker_file_manager.GetRemovedCount());
-
- // we didn't add any old marker files, so there should be no bluescreens
- EXPECT_EQ(0, bluescreen_logger.GetBluescreenCount());
- EXPECT_EQ(0, bluescreen_logger.GetLogBluescreenCount());
-}
-
-// Let's try simulating a simple blue-screen
-TEST_F(BluescreenDetectorTest, SimulateBluescreen) {
- TimeManagerMock time_manager;
- MarkerFileManagerMock marker_file_manager(&time_manager);
- BluescreenLoggerMock bluescreen_logger;
-
- BluescreenDetector detector(&time_manager,
- &marker_file_manager,
- &bluescreen_logger);
-
- // Let's create a couple of stray marker files :)
- // and say they were created 100 time units before the machine was
- // booted
- uint64 kStrayCreationTime1 = kInitialCurrentTime - kInitialUpTime - 100;
- marker_file_manager.AddFileEntry("Stray1", kStrayCreationTime1);
- marker_file_manager.AddFileEntry("Stray2", kStrayCreationTime1);
-
- // Verify the two we just added
- EXPECT_EQ(2, marker_file_manager.GetMarkerFileCount());
-
- detector.Start();
-
- // Check that two bluescreens were detected (and reported)
- EXPECT_EQ(2, bluescreen_logger.GetBluescreenCount());
-
- // Check that LogBluescreen() was only called once (with two detections)
- EXPECT_EQ(1, bluescreen_logger.GetLogBluescreenCount());
-
- // Make sure the two "stray" marker files were removed
- // (so we won't report bluescreens multiple times)
- // the marker file added by |detector| should still be there
- EXPECT_EQ(1, marker_file_manager.GetMarkerFileCount());
-
- detector.Stop();
-
- // Now make sure the marker file added by |detector|
- // was also removed
- EXPECT_EQ(0, marker_file_manager.GetMarkerFileCount());
-
- // Make sure marker file was created then removed
- EXPECT_EQ(1, marker_file_manager.GetCreatedCount());
- EXPECT_EQ(1, marker_file_manager.GetRemovedCount());
-}
-
-// Let's make sure we don't detect a blue-screen from marker
-// files written since boot time (these marker files may be
-// written by o3d running in other browsers alongside ours)
-TEST_F(BluescreenDetectorTest, OtherBrowsersRunning) {
- TimeManagerMock time_manager;
- MarkerFileManagerMock marker_file_manager(&time_manager);
- BluescreenLoggerMock bluescreen_logger;
-
- BluescreenDetector detector(&time_manager,
- &marker_file_manager,
- &bluescreen_logger);
-
- // Let's create a couple of other marker files :)
- // but this time 100 time units AFTER the machine was
- // booted, simulating other browsers which are still running
- // o3d
- uint64 kStrayCreationTime1 = kInitialCurrentTime - kInitialUpTime + 100;
- marker_file_manager.AddFileEntry("OtherBrowserMarker1", kStrayCreationTime1);
- marker_file_manager.AddFileEntry("OtherBrowserMarker2", kStrayCreationTime1);
-
- // Verify the two we just added
- EXPECT_EQ(2, marker_file_manager.GetMarkerFileCount());
-
- detector.Start();
-
- // Check that NO bluescreens were detected
- EXPECT_EQ(0, bluescreen_logger.GetBluescreenCount());
-
- // Check that NO bluescreen reports were logged/uploaded
- EXPECT_EQ(0, bluescreen_logger.GetLogBluescreenCount());
-
- // Make sure the two other marker files were NOT removed
- // because they were not created before boot time and
- // are owned by a different browser...
- // There should be the two we added, plus the one added
- // by |detector|
- EXPECT_EQ(3, marker_file_manager.GetMarkerFileCount());
-
- detector.Stop();
-
- // Now make sure the marker file added by |detector|
- // was removed, so we're left with the original two
- EXPECT_EQ(2, marker_file_manager.GetMarkerFileCount());
-
- // Make sure marker file was created then removed
- EXPECT_EQ(1, marker_file_manager.GetCreatedCount());
- EXPECT_EQ(1, marker_file_manager.GetRemovedCount());
-}
-
-} // namespace o3d
diff --git a/o3d/breakpad/win/breakpad_config.cc b/o3d/breakpad/win/breakpad_config.cc
deleted file mode 100644
index c182a06..0000000
--- a/o3d/breakpad/win/breakpad_config.cc
+++ /dev/null
@@ -1,78 +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.
- */
-
-//
-// Breakpad configuration constants
-
-// Product-specific constants. MODIFY THESE TO SUIT YOUR PROJECT.
-
-#define _QUOTEME(x) #x
-#define QUOTEME(x) _QUOTEME(x)
-
-#define _MAKE_LONG_STRING(string) L ## string
-#define MAKE_LONG_STRING(string) _MAKE_LONG_STRING(string)
-
-#define PRODUCT_VERSION_STRING MAKE_LONG_STRING(QUOTEME(O3D_PLUGIN_VERSION))
-
-wchar_t *kCrashReportProductName = L"O3D"; // [naming]
-
-wchar_t *kCrashReportProductVersion =
- PRODUCT_VERSION_STRING L" (win32)";
-
-// Crash report uploading configuration (used by reporter.exe)
-
-#ifdef NDEBUG
-// production server
-wchar_t *kCrashReportUrl = L"http://clients2.google.com/cr/report";
-#else
-// staging server
-wchar_t *kCrashReportUrl = L"http://clients2.google.com/cr/staging_report";
-#endif
-
-wchar_t *kCrashReportProductParam = L"prod";
-wchar_t *kCrashReportVersionParam = L"ver";
-
-// Throttling-related constants
-// (we don't want to upload too many crash reports in a row)
-
-bool kCrashReportAlwaysUpload = false; // disables throttling if set to |true|
-
-wchar_t *kCrashReportThrottlingRegKey =
- L"Software\\Google\\Breakpad\\Throttling";
-
-int kCrashReportAttempts = 3;
-int kCrashReportResendPeriodMs = (1 * 60 * 60 * 1000);
-
-// kCrashReportsMaxPerInterval is defined (using #define)
-// in the header file, since the compiler requires it to be a constant
-// (can't be global variable as defined in this file)
-
-int kCrashReportsIntervalSeconds = (24 * 60 * 60);
diff --git a/o3d/breakpad/win/breakpad_config.h b/o3d/breakpad/win/breakpad_config.h
deleted file mode 100644
index 5b28801..0000000
--- a/o3d/breakpad/win/breakpad_config.h
+++ /dev/null
@@ -1,57 +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.
- */
-
-//
-// Breakpad configuration constants
-
-#ifndef O3D_BREAKPAD_WIN_BREAKPAD_CONFIG_H_
-#define O3D_BREAKPAD_WIN_BREAKPAD_CONFIG_H_
-
-extern wchar_t *kCrashReportProductName;
-extern wchar_t *kCrashReportProductVersion;
-
-extern wchar_t *kReporterPath;
-
-// Crash report uploading configuration (used by reporter.exe)
-extern wchar_t *kCrashReportUrl;
-extern wchar_t *kCrashReportStagingUrl;
-extern wchar_t *kCrashReportProductParam;
-extern wchar_t *kCrashReportVersionParam;
-
-// Throttling-related constants
-extern bool kCrashReportAlwaysUpload;
-extern wchar_t *kCrashReportThrottlingRegKey;
-extern int kCrashReportAttempts;
-extern int kCrashReportResendPeriodMs;
-#define kCrashReportsMaxPerInterval 5
-extern int kCrashReportsIntervalSeconds;
-
-#endif // O3D_BREAKPAD_WIN_BREAKPAD_CONFIG_H_
diff --git a/o3d/breakpad/win/crash_sender_win32.cc b/o3d/breakpad/win/crash_sender_win32.cc
deleted file mode 100644
index b5c60c2..0000000
--- a/o3d/breakpad/win/crash_sender_win32.cc
+++ /dev/null
@@ -1,153 +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.
- */
-
-//
-// Breakpad crash report uploader
-// (adapted from code in Gears)
-//
-
-
-#include <map>
-#include <windows.h>
-#include <assert.h>
-#include <shellapi.h>
-#include <tchar.h>
-#include <time.h>
-
-#include "breakpad_config.h"
-#include "client/windows/sender/crash_report_sender.h"
-
-using std::map;
-using std::wstring;
-using google_breakpad::CrashReportSender;
-using google_breakpad::ReportResult;
-
-bool CanSendMinidump(const wchar_t *product_name);
-void SendMinidump(const wchar_t *minidump_filename,
- const wchar_t *product_name,
- const wchar_t *product_version);
-
-
-int _tmain(int argc, _TCHAR* argv[]) {
- SendMinidump(argv[1], argv[2], argv[3]);
- return 0;
-}
-
-bool CanSendMinidump(const wchar_t *product_name) {
- // useful for testing purposes
- if (kCrashReportAlwaysUpload) {
- return true;
- }
-
- bool can_send = false;
-
- time_t current_time;
- time(&current_time);
-
- // For throttling, we remember when the last N minidumps were sent.
-
- time_t past_send_times[kCrashReportsMaxPerInterval];
- DWORD bytes = sizeof(past_send_times);
- memset(&past_send_times, 0, bytes);
-
- HKEY reg_key;
- DWORD create_type;
- if (ERROR_SUCCESS != RegCreateKeyExW(HKEY_CURRENT_USER,
- kCrashReportThrottlingRegKey,
- 0,
- NULL,
- 0,
- KEY_READ | KEY_WRITE, NULL,
- &reg_key, &create_type)) {
- return false; // this should never happen, but just in case
- }
-
- if (ERROR_SUCCESS != RegQueryValueEx(reg_key, product_name, NULL,
- NULL,
- reinterpret_cast<BYTE*>(past_send_times),
- &bytes)) {
- // this product hasn't sent any crash reports yet
- can_send = true;
- } else {
- // find crash reports within the last interval
- int crashes_in_last_interval = 0;
- for (int i = 0; i < kCrashReportsMaxPerInterval; ++i) {
- if (current_time - past_send_times[i] < kCrashReportsIntervalSeconds) {
- ++crashes_in_last_interval;
- }
- }
-
- can_send = crashes_in_last_interval < kCrashReportsMaxPerInterval;
- }
-
- if (can_send) {
- memmove(&past_send_times[1],
- &past_send_times[0],
- sizeof(time_t) * (kCrashReportsMaxPerInterval - 1));
- past_send_times[0] = current_time;
- }
-
- RegSetValueEx(reg_key, product_name, 0, REG_BINARY,
- reinterpret_cast<BYTE*>(past_send_times),
- sizeof(past_send_times));
-
- return can_send;
-}
-
-void SendMinidump(const wchar_t *minidump_filename,
- const wchar_t *product_name,
- const wchar_t *product_version) {
- if (CanSendMinidump(product_name)) {
- map<std::wstring, std::wstring> parameters;
- parameters[kCrashReportProductParam] = product_name;
- parameters[kCrashReportVersionParam] = std::wstring(product_version);
-
- std::wstring minidump_wstr(minidump_filename);
-
- CrashReportSender sender(L"");
-
- for (int i = 0; i < kCrashReportAttempts; ++i) {
- wstring upload_result;
- ReportResult result = sender.SendCrashReport(kCrashReportUrl,
- parameters,
- minidump_wstr,
- &upload_result);
- if (result == google_breakpad::RESULT_FAILED) {
- Sleep(kCrashReportResendPeriodMs);
- } else {
- // RESULT_SUCCEEDED or RESULT_REJECTED
- break;
- }
- }
- }
-
- DeleteFileW(minidump_filename);
-}
diff --git a/o3d/breakpad/win/exception_handler_win32.cc b/o3d/breakpad/win/exception_handler_win32.cc
deleted file mode 100644
index ade738f..0000000
--- a/o3d/breakpad/win/exception_handler_win32.cc
+++ /dev/null
@@ -1,210 +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.
- */
-
-//
-// Wrapper class for using the Breakpad crash reporting system.
-// (adapted from code in Gears)
-//
-
-#include <windows.h>
-#include <assert.h>
-#include <shellapi.h>
-#include <shlobj.h>
-#include <shlwapi.h>
-#include <tchar.h>
-#include <time.h>
-#include <string>
-
-#include "breakpad/win/breakpad_config.h"
-#include "breakpad/win/exception_handler_win32.h"
-#include "client/windows/handler/exception_handler.h"
-
-// We use g_logger to determine if we opt-in/out of crash reporting
-namespace o3d {
- class PluginLogging;
-}
-extern o3d::PluginLogging* g_logger;
-
-// Some simple string typedefs
-#define STRING16(x) reinterpret_cast<const char16*>(x)
-
-typedef wchar_t char16;
-
-namespace std {
-typedef wstring string16;
-}
-
-
-ExceptionManager* ExceptionManager::instance_ = NULL;
-
-
-ExceptionManager::ExceptionManager(bool catch_entire_process)
- : catch_entire_process_(catch_entire_process),
- exception_handler_(NULL) {
- assert(!instance_);
- instance_ = this;
-}
-
-
-ExceptionManager::~ExceptionManager() {
- if (exception_handler_)
- delete exception_handler_;
- assert(instance_ == this);
- instance_ = NULL;
-}
-
-
-static HMODULE GetModuleHandleFromAddress(void *address) {
- MEMORY_BASIC_INFORMATION mbi;
- SIZE_T result = VirtualQuery(address, &mbi, sizeof(mbi));
- return static_cast<HMODULE>(mbi.AllocationBase);
-}
-
-
-// Gets the handle to the currently executing module.
-static HMODULE GetCurrentModuleHandle() {
- // pass a pointer to the current function
- return GetModuleHandleFromAddress(GetCurrentModuleHandle);
-}
-
-
-static bool IsAddressInCurrentModule(void *address) {
- return GetCurrentModuleHandle() == GetModuleHandleFromAddress(address);
-}
-
-
-// Called back when an exception occurs - we can decide here if we
-// want to handle this crash...
-//
-static bool FilterCallback(void *context,
- EXCEPTION_POINTERS *exinfo,
- MDRawAssertionInfo *assertion) {
- // g_logger will be NULL if user opts out of metrics/crash reporting
- if (!g_logger) return false;
-
- ExceptionManager* this_ptr = reinterpret_cast<ExceptionManager*>(context);
-
- if (this_ptr->catch_entire_process())
- return true;
-
- if (!exinfo)
- return true;
-
- return IsAddressInCurrentModule(exinfo->ExceptionRecord->ExceptionAddress);
-}
-
-
-// Is called by Breakpad when an exception occurs and a minidump has been
-// written to disk.
-static bool MinidumpCallback(const wchar_t *minidump_folder,
- const wchar_t *minidump_id,
- void *context,
- EXCEPTION_POINTERS *exinfo,
- MDRawAssertionInfo *assertion,
- bool succeeded) {
- // If this is set to |false| then the exception will be forwarded to
- // Windows and a crash dialog will appear
- bool handled_exception = true;
-
- // get the full path to the minidump
- wchar_t minidump_path[MAX_PATH];
- _snwprintf(minidump_path, sizeof(minidump_path), L"%s\\%s.dmp",
- minidump_folder, minidump_id);
-
-
-
- // determine the full path to "reporter.exe"
- // it will look something like:
- // "c:\Documents and Settings\user\Application Data\Google\O3D\reporter.exe"
- TCHAR reporterPath[MAX_PATH];
-
- HRESULT result = SHGetFolderPath(
- NULL,
- O3D_PLUGIN_INSTALLDIR_CSIDL,
- NULL,
- 0,
- reporterPath);
-
- if (result == 0) {
- PathAppend(reporterPath,
- _T(O3D_PLUGIN_VENDOR_DIRECTORY) _T("\\")
- _T(O3D_PLUGIN_PRODUCT_DIRECTORY) _T("\\reporter.exe"));
- }
-
- if (PathFileExists(reporterPath)) {
- std::string16 command_line;
- command_line += L"\"";
- command_line += reporterPath;
- command_line += L"\" \"";
- command_line += minidump_path;
- command_line += L"\" \"";
- command_line += kCrashReportProductName;
- command_line += L"\" \"";
- command_line += kCrashReportProductVersion;
- command_line += L"\"";
-
- // execute the process
- STARTUPINFO startup_info = {0};
- startup_info.cb = sizeof(startup_info);
- PROCESS_INFORMATION process_info = {0};
- CreateProcessW(NULL, // application name (NULL to get from command line)
- const_cast<char16 *>(command_line.c_str()),
- NULL, // process attributes (NULL means process handle not
- // inheritable)
- NULL, // thread attributes (NULL means thread handle not
- // inheritable)
- FALSE, // inherit handles
- 0, // creation flags
- NULL, // environment block (NULL to use parent's)
- NULL, // starting block (NULL to use parent's)
- &startup_info,
- &process_info);
- CloseHandle(process_info.hProcess);
- CloseHandle(process_info.hThread);
- } else {
- handled_exception = false;
- }
-
- return handled_exception;
-}
-
-
-void ExceptionManager::StartMonitoring() {
- if (exception_handler_) { return; } // don't init more than once
-
- wchar_t temp_path[MAX_PATH];
- if (!GetTempPathW(MAX_PATH, temp_path)) { return; }
-
- exception_handler_ = new google_breakpad::ExceptionHandler(temp_path,
- FilterCallback,
- MinidumpCallback,
- this, true);
-}
diff --git a/o3d/breakpad/win/exception_handler_win32.h b/o3d/breakpad/win/exception_handler_win32.h
deleted file mode 100644
index a7bd045..0000000
--- a/o3d/breakpad/win/exception_handler_win32.h
+++ /dev/null
@@ -1,76 +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.
- */
-
-//
-// Wrapper class for using the Breakpad crash reporting system.
-// (adapted from code in Gears)
-//
-
-#ifndef O3D_BREAKPAD_WIN_EXCEPTION_HANDLER_WIN32_H_
-#define O3D_BREAKPAD_WIN_EXCEPTION_HANDLER_WIN32_H_
-
-namespace google_breakpad {
-class ExceptionHandler;
-};
-
-// Sample usage:
-// int main(void) {
-// static ExceptionManager exception_manager(false);
-// exception_manager.StartMonitoring();
-// ...
-// }
-class ExceptionManager {
- public:
- // If catch_entire_process is true, then all minidumps are captured.
- // Otherwise, only crashes in this module are captured.
- // Use the latter when running inside IE or Firefox.
- // StartMonitoring needs to be called before any minidumps are captured.
- explicit ExceptionManager(bool catch_entire_process);
- ~ExceptionManager();
-
- // Starts monitoring for crashes. When a crash occurs a minidump will
- // automatically be captured and sent.
- void StartMonitoring();
-
- // TODO: Cleanup. The following should not be called
- // directly, ideally these should be private methods.
- bool catch_entire_process() { return catch_entire_process_; }
- static void SendMinidump(const char *minidump_filename);
- static bool CanSendMinidump(); // considers throttling
-
- private:
- static ExceptionManager *instance_;
-
- bool catch_entire_process_;
- google_breakpad::ExceptionHandler *exception_handler_;
-};
-
-#endif // O3D_BREAKPAD_WIN_EXCEPTION_HANDLER_WIN32_H_
diff --git a/o3d/build/branding.gypi b/o3d/build/branding.gypi
deleted file mode 100644
index 4102fb6..0000000
--- a/o3d/build/branding.gypi
+++ /dev/null
@@ -1,23 +0,0 @@
-# Copyright (c) 2010 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- # Default identity. Can be overridden to allow making custom
- # plugins based on O3D, but they will not work with regular O3D apps.
- 'plugin_name%': 'O3D Plugin',
- 'plugin_npapi_filename%': 'npo3dautoplugin',
- 'plugin_npapi_mimetype%': 'application/vnd.o3d.auto',
- 'plugin_activex_hostcontrol_clsid%': '9666A772-407E-4F90-BC37-982E8160EB2D',
- 'plugin_activex_typelib_clsid%': 'D4F6E31C-E952-48FE-9833-6AE308BD79C6',
- 'plugin_activex_hostcontrol_name%': 'o3d_host',
- 'plugin_activex_typelib_name%': 'npapi_host2',
- 'plugin_installdir_csidl%': 'CSIDL_APPDATA',
- 'plugin_vendor_directory%': 'Google',
- 'plugin_product_directory%': 'O3D',
- 'plugin_extras_directory%': 'O3DExtras',
- # You must set this to 1 if changing any of the above.
- 'plugin_rebranded%': '0',
- }
-}
diff --git a/o3d/build/cairo.gyp b/o3d/build/cairo.gyp
deleted file mode 100644
index 92d6ad8..0000000
--- a/o3d/build/cairo.gyp
+++ /dev/null
@@ -1,176 +0,0 @@
-# Copyright (c) 2011 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'cairobuilddir': '<(SHARED_INTERMEDIATE_DIR)/cairo',
- },
- 'includes': [
- 'common.gypi',
- ],
- 'targets': [
- {
- 'target_name': 'cairo',
- 'conditions': [
- ['OS == "mac"',
- {
- 'type': 'none',
- 'dependencies': [
- 'pixman.gyp:pixman',
- 'pkg-config.gyp:pkg-config',
- ],
- 'actions': [
- {
- 'action_name': 'build_cairo',
- 'inputs': [
- # Tragically, GYP/XCode has a limitation on the number of
- # inputs that an action may have, and cairo's 3000+ files is
- # over the limit, so we declare a dependency on only the first
- # 2000 files. This is fine because any update to a newer
- # version of cairo is likely to modify at least one of those
- # files, which is sufficient to re-run the action.
- '<!@(find ../../<(cairodir) -name .svn -prune -o -type f '
- '-print | head -n 2000)',
- ],
- 'inputs': [
- # The cairo build won't actually read this file at all, but
- # it does read the installed pixman headers, so if pixman has
- # been rebuilt then we want cairo to be rebuilt too and it is
- # simpler to just list this file than list all the pixman
- # headers.
- '<(pkgconfigroot)/usr/lib/libpixman-1.a',
- ],
- 'outputs': [
- '<(pkgconfigroot)/usr/lib/libcairo.a',
- # There are other outputs but it is sufficient to just list
- # one.
- ],
- 'action': [
- 'sh',
- '-c',
- # Delete existing build directory, if any.
- 'rm -rf <(cairobuilddir) && '
- # Copy the cairo tree to the build directory.
- 'cp -r ../../<(cairodir) <(cairobuilddir) && '
- # Go there!
- 'cd <(cairobuilddir) && '
- # Put our pkg-config binary into the PATH so cairo's build can
- # find it.
- 'PATH=<(pkgconfigroot)/usr/bin:$PATH && '
- # Configure it.
- 'CFLAGS="-arch <(mac_gcc_arch) <(mac_gcc_debug_flag)" '
- './configure --prefix=<(pkgconfigroot)/usr '
- '--disable-shared '
- # Disable things we don't need that have additional
- # external dependencies.
- '--disable-png --disable-svg --disable-ft && '
- # Build.
- 'make && '
- # "Install" to pkgconfigroot.
- 'make install',
- ],
- },
- ],
- },
- ],
- ['OS == "win"',
- {
- 'type': 'static_library',
- 'defines': [
- 'CAIRO_WIN32_STATIC_BUILD',
- # TODO(gangji): This may hurt perf. Investigate.
- 'DISABLE_SOME_FLOATING_POINT',
- ],
- 'include_dirs': [
- '../../<(cairodir)/src',
- '../../<(pngdir)/',
- '../../<(pixmandir)/pixman',
- '../../<(zlibdir)/',
- 'misc'
- ],
- 'sources': [
- '../../<(cairodir)/src/cairo-analysis-surface.c',
- '../../<(cairodir)/src/cairo-arc.c',
- '../../<(cairodir)/src/cairo-array.c',
- '../../<(cairodir)/src/cairo-atomic.c',
- '../../<(cairodir)/src/cairo-base64-stream.c',
- '../../<(cairodir)/src/cairo-base85-stream.c',
- '../../<(cairodir)/src/cairo-bentley-ottmann.c',
- '../../<(cairodir)/src/cairo-bentley-ottmann-rectangular.c',
- '../../<(cairodir)/src/cairo-bentley-ottmann-rectilinear.c',
- '../../<(cairodir)/src/cairo-botor-scan-converter.c',
- '../../<(cairodir)/src/cairo-boxes.c',
- '../../<(cairodir)/src/cairo.c',
- '../../<(cairodir)/src/cairo-cache.c',
- '../../<(cairodir)/src/cairo-clip.c',
- '../../<(cairodir)/src/cairo-color.c',
- '../../<(cairodir)/src/cairo-composite-rectangles.c',
- '../../<(cairodir)/src/cairo-debug.c',
- '../../<(cairodir)/src/cairo-device.c',
- '../../<(cairodir)/src/cairo-fixed.c',
- '../../<(cairodir)/src/cairo-font-face.c',
- '../../<(cairodir)/src/cairo-font-face-twin.c',
- '../../<(cairodir)/src/cairo-font-face-twin-data.c',
- '../../<(cairodir)/src/cairo-font-options.c',
- '../../<(cairodir)/src/cairo-freelist.c',
- '../../<(cairodir)/src/cairo-freed-pool.c',
- '../../<(cairodir)/src/cairo-gstate.c',
- '../../<(cairodir)/src/cairo-hash.c',
- '../../<(cairodir)/src/cairo-hull.c',
- '../../<(cairodir)/src/cairo-image-info.c',
- '../../<(cairodir)/src/cairo-image-surface.c',
- '../../<(cairodir)/src/cairo-lzw.c',
- '../../<(cairodir)/src/cairo-matrix.c',
- '../../<(cairodir)/src/cairo-recording-surface.c',
- '../../<(cairodir)/src/cairo-misc.c',
- '../../<(cairodir)/src/cairo-mutex.c',
- '../../<(cairodir)/src/cairo-observer.c',
- '../../<(cairodir)/src/cairo-output-stream.c',
- '../../<(cairodir)/src/cairo-paginated-surface.c',
- '../../<(cairodir)/src/cairo-path-bounds.c',
- '../../<(cairodir)/src/cairo-path.c',
- '../../<(cairodir)/src/cairo-path-fill.c',
- '../../<(cairodir)/src/cairo-path-fixed.c',
- '../../<(cairodir)/src/cairo-path-in-fill.c',
- '../../<(cairodir)/src/cairo-path-stroke.c',
- '../../<(cairodir)/src/cairo-pattern.c',
- '../../<(cairodir)/src/cairo-pen.c',
- '../../<(cairodir)/src/cairo-png.c',
- '../../<(cairodir)/src/cairo-polygon.c',
- '../../<(cairodir)/src/cairo-rectangle.c',
- '../../<(cairodir)/src/cairo-rectangular-scan-converter.c',
- '../../<(cairodir)/src/cairo-region.c',
- '../../<(cairodir)/src/cairo-rtree.c',
- '../../<(cairodir)/src/cairo-scaled-font.c',
- '../../<(cairodir)/src/cairo-scaled-font-subsets.c',
- '../../<(cairodir)/src/cairo-slope.c',
- '../../<(cairodir)/src/cairo-spans.c',
- '../../<(cairodir)/src/cairo-spline.c',
- '../../<(cairodir)/src/cairo-stroke-style.c',
- '../../<(cairodir)/src/cairo-surface.c',
- '../../<(cairodir)/src/cairo-surface-fallback.c',
- '../../<(cairodir)/src/cairo-surface-clipper.c',
- '../../<(cairodir)/src/cairo-surface-offset.c',
- '../../<(cairodir)/src/cairo-surface-snapshot.c',
- '../../<(cairodir)/src/cairo-surface-subsurface.c',
- '../../<(cairodir)/src/cairo-surface-wrapper.c',
- '../../<(cairodir)/src/cairo-system.c',
- '../../<(cairodir)/src/cairo-tor-scan-converter.c',
- '../../<(cairodir)/src/cairo-toy-font-face.c',
- '../../<(cairodir)/src/cairo-traps.c',
- '../../<(cairodir)/src/cairo-truetype-subset.c',
- '../../<(cairodir)/src/cairo-unicode.c',
- '../../<(cairodir)/src/cairo-user-font.c',
- '../../<(cairodir)/src/cairo-version.c',
- '../../<(cairodir)/src/cairo-wideint.c',
- '../../<(cairodir)/src/cairo-win32-surface.c',
- '../../<(cairodir)/src/cairo-win32-printing-surface.c',
- '../../<(cairodir)/src/cairo-win32-font.c',
- ],
- },
- ],
- ],
- },
- ],
-}
diff --git a/o3d/build/common.gypi b/o3d/build/common.gypi
deleted file mode 100644
index 77f4a87..0000000
--- a/o3d/build/common.gypi
+++ /dev/null
@@ -1,264 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'antlrdir': 'third_party/antlr3',
- 'breakpaddir': 'breakpad/src',
- 'cairodir': 'third_party/cairo',
- 'fcolladadir': 'third_party/fcollada/files',
- 'glewdir': 'third_party/glew/files',
- 'gtestdir': 'testing/gtest/include',
- 'internaldir':'o3d-internal',
- 'jpegdir': 'third_party/libjpeg',
- 'nacldir': 'third_party/native_client/googleclient',
- 'nixysadir': 'o3d/third_party/nixysa',
- 'npapidir': 'o3d/third_party/npapi',
- 'pdiffdir': 'third_party/pdiff/files',
- 'pixmandir': 'third_party/pixman',
- 'pkgconfigdir': 'third_party/pkg-config',
- 'pngdir': 'third_party/libpng',
- 'screenshotsdir': 'o3d_assets/tests/screenshots',
- 'seleniumdir': 'third_party/selenium_rc/files',
- 'skiadir': 'third_party/skia/include',
- 'txcdir': 'third_party/libtxc_dxtn/files',
- 'zlibdir': 'third_party/zlib',
-
- 'pkgconfigroot': '<(SHARED_INTERMEDIATE_DIR)/pkgconfigroot',
-
- # Hack to ensure that these variables (specifically "renderer") are
- # available later in the file. Long term solution is late
- # evaluation of variables.
- 'variables': {
- # 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 <(DEPTH)/DEPS)',
- 'gles2_backend%': 'desktop_gl',
- 'conditions' : [
- # These have to come first because GYP doesn't like it when
- # they're part of the same conditional as a conditions clause that
- # uses them.
- ['OS == "win"',
- {
- 'cgdir': 'third_party/cg/files/win',
- 'renderer%': 'd3d9',
- 'swiftshaderdir': 'o3d-internal/third_party/swiftshader/files',
- },
- ],
- ['OS == "mac"',
- {
- 'cgdir': 'third_party/cg/files/mac',
- 'renderer%': 'gl',
- 'swiftshaderdir': '',
- },
- ],
- ['OS == "linux"',
- {
- 'cgdir': 'third_party/cg/files/linux',
- 'renderer%': 'gl',
- 'swiftshaderdir': '',
- },
- ],
- ],
- },
- 'o3d_in_chrome%': '<(o3d_in_chrome)',
- 'renderer%': '<(renderer)',
- 'cgdir%': '<(cgdir)',
- 'gles2_backend%': '<(gles2_backend)',
- 'swiftshaderdir%': '<(swiftshaderdir)',
-
- # 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 '
- '<(DEPTH)/o3d/o3d_assets/samples/convert_assets/teapot.zip)',
- 'selenium_screenshots%': 0,
-
- # Add a way to disable FBO support for GL implementations that don't have
- # it.
- 'disable_fbo%': 0,
-
- # Whether to enable the English-only, Win/Mac-only fullscreen message.
- 'plugin_enable_fullscreen_msg%': '1',
- },
- 'target_defaults': {
- 'defines': [
- 'GYP_BUILD', # Needed to make a change in base/types.h conditional.
- ],
- # This needs to be in a target_conditions block in order to successfully
- # override the xcode_settings in ../../build/common.gypi.
- # Something to do with evaluation order.
- 'target_conditions': [
- ['OS=="mac"', {
- 'xcode_settings': {
- 'MACOSX_DEPLOYMENT_TARGET': '10.5',
- # TODO(maf): figure out proper fix for the following.
- # There is only one place in plugin_mac.mm which attempts
- # to use ObjC exception handling.
- 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
- },
- }],
- ],
- 'conditions' : [
- ['renderer == "d3d9"',
- {
- 'defines': [
- 'RENDERER_D3D9',
- ],
- },
- ],
- ['renderer == "gl"',
- {
- 'defines': [
- 'RENDERER_GL',
- ],
- },
- ],
- ['renderer == "gles2"',
- {
- 'defines': [
- 'RENDERER_GLES2',
- ],
- 'conditions': [
- ['gles2_backend == "desktop_gl"',
- {
- 'defines': [
- 'GLES2_BACKEND_DESKTOP_GL',
- ],
- },
- ],
- ['gles2_backend == "native_gles2"',
- {
- 'defines': [
- 'GLES2_BACKEND_NATIVE_GLES2',
- ],
- },
- ],
- ['gles2_backend == "gles2_command_buffers"',
- {
- 'defines': [
- 'GLES2_BACKEND_GLES2_COMMAND_BUFFERS',
- ],
- },
- ],
- ],
- },
- ],
- ['<(plugin_enable_fullscreen_msg) != 0',
- {
- 'defines': [
- 'O3D_PLUGIN_ENABLE_FULLSCREEN_MSG=1',
- ],
- },
- ],
- ],
- },
- 'conditions' : [
- ['OS == "win"',
- {
- 'target_defaults': {
- 'defines': [
- '_CRT_SECURE_NO_WARNINGS',
- 'OS_WIN',
- 'UNICODE',
- 'NACL_WINDOWS',
- '_X86_',
- ],
- # Disable warning: "'this' : used in base member initialization list."
- 'msvs_disabled_warnings': [4355],
- 'msvs_settings': {
- 'VCCLCompilerTool': {
- 'WarnAsError': 'false',
- # Turn off errors for signed/unsigned mismatch from Chromium build/common.gypi.
- 'AdditionalOptions!': ['/we4389'],
- },
- },
- },
- },
- ],
- ['OS == "mac"',
- {
- 'variables': {
- # Ridiculously, it is impossible to define a GYP variable whose value
- # depends on the choice of build configuration, so to get this to be
- # -g only when building Debug we define it as a shell fragment that
- # uses command substitution to evaluate to different things based on
- # the Xcode "CONFIGURATION" environment variable. We further have to
- # use `` instead of $() because GYP/Xcode mangles $().
- 'mac_gcc_debug_flag':
- '`if [ "$CONFIGURATION" = Debug ]; then '
- 'echo -g; '
- 'else '
- 'echo -g0; '
- 'fi`'
- },
- 'conditions': [
- ['target_arch == "ia32"',
- {
- 'variables': {
- 'mac_gcc_arch': 'i386',
- },
- }
- ],
- ['target_arch == "x64"',
- {
- 'variables': {
- 'mac_gcc_arch': 'x86_64',
- },
- }
- ],
- ],
- 'target_defaults': {
- 'defines': [
- 'OS_MACOSX',
- 'UNICODE',
- 'GTEST_NOT_MAC_FRAMEWORK_MODE',
- 'NACL_OSX=1',
- 'MAC_OS_X_VERSION_MIN_REQUIRED=MAC_OS_X_VERSION_10_5',
- 'SK_BUILD_FOR_MAC',
- ],
- 'configurations': {
- 'Debug': {
- 'xcode_settings': {
- 'GCC_DEBUGGING_SYMBOLS': 'full',
- },
- },
- },
- 'xcode_settings': {
- 'GCC_SYMBOLS_PRIVATE_EXTERN': 'NO',
- 'OTHER_CFLAGS': [
- '-fno-eliminate-unused-debug-symbols',
- '-mmacosx-version-min=10.5'],
- 'WARNING_CFLAGS': ['-Wno-deprecated-declarations'],
- 'WARNING_CFLAGS!': ['-Wall', '-Wextra'],
- 'WARNING_CXXFLAGS': ['-Wstrict-aliasing',
- '-Wno-deprecated',],
- },
- },
- },
- ],
- ['OS == "linux"',
- {
- 'target_defaults': {
- 'defines': [
- 'LINUX',
- 'MOZ_X11',
- 'NACL_LINUX=1',
- 'OS_LINUX',
- 'SK_BUILD_FOR_UNIX',
- 'UNICODE',
- 'XP_UNIX',
- ],
- 'cflags': [
- '-fvisibility=hidden',
- '-Wstrict-aliasing',
- # We always want debugging information, even for release builds. It
- # is stripped by the packager into the -dbgsym package, so it
- # doesn't affect what we ship.
- '-g',
- ],
- },
- },
- ],
- ],
-}
diff --git a/o3d/build/common_global.gypi b/o3d/build/common_global.gypi
deleted file mode 100644
index 031f7eb..0000000
--- a/o3d/build/common_global.gypi
+++ /dev/null
@@ -1,58 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# This file contains flags that are specific to o3d, but affect the build as a
-# whole (e.g. build flags that change the ABI).
-# For example, on linux amd64, all the libraries that will be linked into the
-# plugin (skia, v8, ...) need to be compiled with -fPIC but we don't want to do
-# that generally in Chrome (so it can't be lumped into the top-level
-# build/common.gypi).
-{
- 'variables': {
- 'conditions': [
- [ 'OS == "linux"', {
- 'use_system_zlib': 0,
- 'use_system_libjpeg': 0,
- 'nacl_standalone': 1,
- # nacl_standalone=1 is broken because nacl's build/common.gypi
- # insists on building 32-bit. Force target_arch to be defined
- # so that nacl's override isn't used.
- # Note: this variable setting is copied from nacl's
- # build/common.gypi so that it has the exact same semantics.
- 'target_arch%': '<!(uname -m | sed -e "s/i.86/ia32/;s/x86_64/x64/;s/arm.*/arm/")'
- }],
- [ 'OS == "win"', {
- 'nacl_standalone': 1,
- }],
- ],
- },
- 'target_defaults': {
- 'conditions': [
- [ 'OS == "linux" and target_arch=="x64"', {
- 'cflags': [
- '-m64',
- '-fPIC',
- ],
- 'ldflags': [
- '-m64',
- ],
- }],
- [ 'OS == "linux" and target_arch=="arm"', {
- 'cflags': [
- '-fPIC',
- ],
- }],
- [ 'OS == "mac"', {
- 'xcode_settings': {
- 'MACOSX_DEPLOYMENT_TARGET': '10.5',
- 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
- 'OTHER_CFLAGS': ['-mmacosx-version-min=10.5'],
- },
- 'defines': [
- 'MAC_OS_X_VERSION_MIN_REQUIRED=MAC_OS_X_VERSION_10_5',
- ],
- }],
- ],
- },
-}
diff --git a/o3d/build/file_exists.py b/o3d/build/file_exists.py
deleted file mode 100644
index aac99b7..0000000
--- a/o3d/build/file_exists.py
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/usr/bin/env python
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import os.path
-import sys
-
-sys.stdout.write(str(os.path.exists(sys.argv[1])))
-sys.exit(0)
diff --git a/o3d/build/gyp_o3d b/o3d/build/gyp_o3d
deleted file mode 100755
index 6cfcaf3..0000000
--- a/o3d/build/gyp_o3d
+++ /dev/null
@@ -1,33 +0,0 @@
-#!/usr/bin/python
-
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# This script is wrapper for O3D when compiling independently of Chromium.
-# Like in Chromium, the common.gypi include is forced in.
-
-import os
-import sys
-
-chrome_src = os.path.join(os.path.dirname(sys.argv[0]), os.pardir, os.pardir)
-o3d_src = os.path.join(os.path.dirname(sys.argv[0]), os.pardir)
-
-try:
- import gyp
-except ImportError, e:
- sys.path.append(os.path.join(chrome_src, 'tools', 'gyp', 'pylib'))
- import gyp
-
-if __name__ == '__main__':
- args = sys.argv[1:]
-
- # Always include common.gypi
- args += ['--depth', '.',
- '-I', os.path.join(chrome_src, 'build', 'common.gypi'),
- '-I', os.path.join(o3d_src, 'build', 'common_global.gypi'),
- '-D', 'mac_deployment_target=10.4',
- '-D', 'linux_use_tcmalloc=0']
-
- # Off we go...
- sys.exit(gyp.main(args))
diff --git a/o3d/build/is_admin.py b/o3d/build/is_admin.py
deleted file mode 100644
index 33789a4..0000000
--- a/o3d/build/is_admin.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/env python
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-#
-# Checks if the user is running as admin
-
-import os
-import os.path
-import sys
-import subprocess
-import platform
-import re
-
-def IsAdminNT():
- # (1, 4, 0): '95',
- # (1, 4, 10): '98',
- # (1, 4, 90): 'ME',
- # (2, 4, 0): 'NT',
- # (2, 5, 0): '2000',
- # (2, 5, 1): 'XP',
- # (2, 5, 2): '2003',
- v = sys.getwindowsversion()
- v = v[3], v[0], v[1]
- # check that we are in vista or greater so we know that
- # 'whoami.exe' exists.
- if v[0] > 2 or (v[0] == 2 and v[1] >= 6):
- output = subprocess.Popen(['whoami.exe', '/all'],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE).communicate()[0]
- elevated_sid = "S-1-16-12288"
- admin_sid = "S-1-5-32-544"
-
- if re.search(elevated_sid, output) and re.search(admin_sid, output):
- return True
- return False
- else:
- # Where in XP or 2000. For now just assume we are admin.
- return True
-
-def IsAdmin():
- if os.name == 'nt':
- is_admin = IsAdminNT()
- elif platform.system() == 'Darwin':
- is_admin = False
- elif platform.system() == 'Linux':
- is_admin = False
- else:
- is_admin = False
- return is_admin
-
-
-def main(args):
- sys.stdout.write(str(IsAdmin()))
-
-
-if __name__ == "__main__":
- main(sys.argv)
- sys.exit(0)
diff --git a/o3d/build/libs.gyp b/o3d/build/libs.gyp
deleted file mode 100644
index 0386e9f..0000000
--- a/o3d/build/libs.gyp
+++ /dev/null
@@ -1,408 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- 'dx_redist_path':
- '../../o3d-internal/third_party/dx_nov_2007_redist',
- 'dx_redist_exists': '<!(python file_exists.py ../../o3d-internal/third_party/dx_nov_2007_redist/d3dx9_36.dll)',
- 'swiftshader_path':
- '../../o3d-internal/third_party/swiftshader/files/swiftshader_d3d9.dll',
- 'swiftshader_exists':
- '<!(python file_exists.py ../../o3d-internal/third_party/swiftshader/files/swiftshader_d3d9.dll)',
- },
- 'includes': [
- 'common.gypi',
- ],
- 'targets': [
- {
- 'target_name': 'cairo_libs',
- 'type': 'none',
- 'conditions': [
- ['OS=="linux"',
- {
- 'all_dependent_settings': {
- 'cflags': [
- '<!@(pkg-config --cflags cairo)',
- ],
- 'ldflags': [
- '<!@(pkg-config --libs-only-L --libs-only-other cairo)',
- ],
- 'libraries': [
- '<!@(pkg-config --libs-only-l cairo)',
- ],
- },
- },
- ],
- ['OS=="mac"',
- {
- 'dependencies': [
- 'pixman.gyp:pixman',
- 'cairo.gyp:cairo',
- ],
- # Ideally we would just call our pkg-config build here to query the
- # right settings, but there are multiple problems with GYP/Xcode
- # that prevent that from working, so we hard-code the values.
- 'all_dependent_settings': {
- 'include_dirs': [
- '<(pkgconfigroot)/usr/include/cairo',
- '<(pkgconfigroot)/usr/include/pixman-1',
- ],
- # GYP/Xcode also has problems with adding libraries to all
- # dependents, so we have to put them in this target_conditions
- # section to restrict them to just the target types that we care
- # about.
- 'target_conditions': [
- ['_type=="executable" or _type=="shared_library" '
- 'or _type=="loadable_module"',
- {
- 'libraries': [
- '<(pkgconfigroot)/usr/lib/libcairo.a',
- '<(pkgconfigroot)/usr/lib/libpixman-1.a',
- ]
- },
- ],
- ],
- },
- },
- ],
- ['OS=="win"',
- {
- 'all_dependent_settings': {
- 'defines': [
- 'CAIRO_WIN32_STATIC_BUILD'
- ],
- 'include_dirs': [
- '../../<(cairodir)/src',
- '../../<(pixmandir)/pixman',
- '../build/misc',
- ],
- },
- 'dependencies': [
- 'cairo.gyp:cairo',
- 'pixman.gyp:pixman',
- ],
- },
- ],
- ],
- },
- {
- 'target_name': 'gl_libs',
- 'type': 'none',
- 'all_dependent_settings': {
- 'include_dirs': [
- '../../<(glewdir)/include',
- ],
- },
- 'conditions': [
- ['OS=="linux"',
- {
- 'all_dependent_settings': {
- 'defines': [
- 'GL_GLEXT_PROTOTYPES',
- ],
- 'conditions': [
- ['target_arch=="x64"',
- {
- 'variables': { 'libdir': 'lib64' }
- }, {
- 'variables': { 'libdir': 'lib' }
- }
- ],
- ],
- 'ldflags': [
- '-L<(PRODUCT_DIR)',
- '-L<(glewdir)/<(libdir)',
- ],
- 'libraries': [
- '-lGL',
- '-lX11',
- '-l:libGLEW.so.a',
- ],
- },
- },
- ],
- ['OS=="mac"',
- {
- 'direct_dependent_settings': {
- 'libraries': [
- '$(SDKROOT)/System/Library/Frameworks/OpenGL.framework',
- ],
- },
- },
- ],
- ['OS=="win"',
- {
- 'all_dependent_settings': {
- 'libraries': [
- '-lOpenGL32.lib',
- '../../<(glewdir)/lib/glew32.lib',
- ],
- },
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)',
- 'files': [
- "../../<(glewdir)/bin/glew32.dll",
- ]
- },
- ],
- },
- ],
- ],
- },
- {
- 'target_name': 'gles2_libs',
- 'type': 'none',
- 'conditions': [
- ['gles2_backend=="desktop_gl"',
- {
- 'all_dependent_settings': {
- 'include_dirs': [
- '../../<(glewdir)/include',
- ],
- },
- 'conditions': [
- ['OS=="linux"',
- {
- 'all_dependent_settings': {
- 'defines': [
- 'GL_GLEXT_PROTOTYPES',
- ],
- 'conditions': [
- ['target_arch=="x64"',
- {
- 'variables': { 'libdir': 'lib64' }
- }, {
- 'variables': { 'libdir': 'lib' }
- }
- ],
- ],
- 'ldflags': [
- '-L<(PRODUCT_DIR)',
- '-L<(glewdir)/<(libdir)',
- ],
- 'libraries': [
- '-lGL',
- '-lX11',
- '-l:libGLEW.so.a',
- ],
- },
- },
- ],
- ['OS=="mac"',
- {
- 'direct_dependent_settings': {
- 'libraries': [
- '$(SDKROOT)/System/Library/Frameworks/OpenGL.framework',
- ],
- },
- },
- ],
- ['OS=="win"',
- {
- 'all_dependent_settings': {
- 'libraries': [
- '-lOpenGL32.lib',
- '../../<(glewdir)/lib/glew32.lib',
- ],
- },
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)',
- 'files': [
- "../../<(glewdir)/bin/glew32.dll",
- ]
- },
- ],
- },
- ],
- ],
- },
- ],
- #['gles2_backend=="gles2_command_buffers"',
- # {
- # },
- #],
- ['gles2_backend=="native_gles2"',
- {
- 'all_dependent_settings': {
- 'libraries': [
- '-lEGL',
- '-lGLESv2',
- ],
- }
- },
- ],
- ],
- },
- {
- 'target_name': 'cg_libs',
- 'type': 'none',
- 'hard_dependency': 1,
- 'all_dependent_settings': {
- 'include_dirs': [
- '../../<(cgdir)/include',
- ],
- },
- 'conditions': [
- ['OS=="linux"',
- {
- 'all_dependent_settings': {
- 'ldflags': [
- '-L<(PRODUCT_DIR)',
- ],
- 'libraries': [
- "-lCg",
- "-lCgGL",
- ],
- },
- },
- ],
- ['OS=="win"',
- {
- 'all_dependent_settings': {
- 'libraries': [
- "../../<(cgdir)/lib/cg.lib",
- "../../<(cgdir)/lib/cgD3D9.lib",
- "../../<(cgdir)/lib/cgGL.lib",
- "../../<(cgdir)/lib/glut32.lib",
- ],
- },
- },
- ],
- ['OS=="mac"',
- {
- 'direct_dependent_settings': {
- 'mac_framework_dirs': [
- "<(PRODUCT_DIR)/Library/Frameworks",
- ],
- 'libraries': [
- "<(PRODUCT_DIR)/Library/Frameworks/Cg.framework",
- ],
- },
- }
- ],
- ],
- 'copies': [
- {
- 'conditions' : [
- ['OS=="linux"',
- {
- 'destination': '<(PRODUCT_DIR)',
- 'conditions': [
- ['target_arch=="x64"',
- {
- 'variables': { 'libdir': 'lib64' }
- }, {
- 'variables': { 'libdir': 'lib' }
- }
- ],
- ],
- 'files': [
- "../../<(cgdir)/<(libdir)/libCg.so",
- "../../<(cgdir)/<(libdir)/libCgGL.so",
- "../../<(cgdir)/bin/cgc",
- ],
- },
- ],
- ['OS=="win"',
- {
- 'destination': '<(PRODUCT_DIR)',
- 'files': [
- "../../<(cgdir)/bin/cg.dll",
- "../../<(cgdir)/bin/cgD3D9.dll",
- "../../<(cgdir)/bin/cgGL.dll",
- "../../<(cgdir)/bin/cgc.exe",
- "../../<(cgdir)/bin/glut32.dll",
- ],
- },
- ],
- ['OS=="mac"',
- {
- 'destination': '<(PRODUCT_DIR)/Library/Frameworks',
- 'files': [
- "../../<(cgdir)/Cg.framework",
- ]
- }
- ],
- ],
- },
- {
- 'conditions' : [
- ['OS=="linux"',
- {
- 'destination': '<(SHARED_LIB_DIR)',
- 'files': [
- "<(PRODUCT_DIR)/libCg.so",
- "<(PRODUCT_DIR)/libCgGL.so",
- ],
- },
- ],
- ['OS=="mac"',
- {
- # Dummy copy, because the xcode generator in gyp fails when it
- # has an empty copy entry.
- 'destination': 'dummy',
- 'files': [],
- }
- ],
- ]
- }
- ],
- },
- ],
- 'conditions': [
- ['OS=="win"',
- {
- 'targets': [
- {
- 'target_name': 'dx_dll',
- 'type': 'none',
- 'all_dependent_settings': {
- 'msvs_system_include_dirs': [
- '$(DXSDK_DIR)/Include',
- ],
- 'libraries': [
- '"$(DXSDK_DIR)/Lib/x86/d3dx9.lib"',
- ],
- },
- 'conditions' : [
- ['"<(swiftshader_exists)" == "True"', {
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)/O3DExtras',
- 'files': ['<(swiftshader_path)'],
- },
- ],
- }],
- ],
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)',
- 'conditions' : [
- ['"<(dx_redist_exists)" == "True"',
- {
- 'files': ['<(dx_redist_path)/d3dx9_36.dll'],
- },
- {
- 'files': ['$(windir)/system32/d3dx9_36.dll'],
- }
- ],
- ],
- },
- ],
- },
- ],
- },
- ],
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/build/misc/cairo-features.h b/o3d/build/misc/cairo-features.h
deleted file mode 100644
index 496c28e..0000000
--- a/o3d/build/misc/cairo-features.h
+++ /dev/null
@@ -1,10 +0,0 @@
-/* Generated by Makefile.win32. Do not edit. */
-#ifndef CAIRO_FEATURES_H
-#define CAIRO_FEATURES_H 1
-#define CAIRO_HAS_WIN32_SURFACE 1
-#define CAIRO_HAS_WIN32_FONT 1
-#define CAIRO_HAS_PNG_FUNCTIONS 1
-#define CAIRO_HAS_IMAGE_SURFACE 1
-#define CAIRO_HAS_RECORDING_SURFACE 1
-#define CAIRO_HAS_USER_FONT 1
-#endif
diff --git a/o3d/build/nacl.gyp b/o3d/build/nacl.gyp
deleted file mode 100644
index 178e6ee..0000000
--- a/o3d/build/nacl.gyp
+++ /dev/null
@@ -1,6 +0,0 @@
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/build/o3d.gyp b/o3d/build/o3d.gyp
deleted file mode 100644
index 14832d1..0000000
--- a/o3d/build/o3d.gyp
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'targets': [
- {
- 'target_name': 'O3D',
- 'type': 'none',
- 'dependencies': [
- '<!(python select_dependencies.py):*',
- ],
- },
- ],
-}
diff --git a/o3d/build/o3d_all.gyp b/o3d/build/o3d_all.gyp
deleted file mode 100644
index e172ed2..0000000
--- a/o3d/build/o3d_all.gyp
+++ /dev/null
@@ -1,54 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'includes': [
- 'common.gypi',
- ],
- 'targets': [
- {
- 'target_name': 'O3D_All',
- 'type': 'none',
- 'dependencies': [
- '../../<(antlrdir)/antlr.gyp:*',
- '../../<(fcolladadir)/fcollada.gyp:*',
- '../../<(jpegdir)/libjpeg.gyp:*',
- '../../<(pngdir)/libpng.gyp:*',
- '../../<(zlibdir)/zlib.gyp:*',
- '../compiler/technique/technique.gyp:o3dTechnique',
- '../converter/converter.gyp:o3dConverter',
- '../core/core.gyp:o3dCore',
- '../core/core.gyp:o3dCorePlatform',
- '../documentation/documentation.gyp:*',
- '../import/archive.gyp:o3dArchive',
- '../import/import.gyp:o3dImport',
- '../installer/installer.gyp:installer',
- '../plugin/idl/idl.gyp:o3dPluginIdl',
- '../plugin/idl/idl.gyp:o3dNpnApi',
- '../plugin/plugin.gyp:npo3dautoplugin',
- '../samples/samples.gyp:*',
- '../standalone/standalone.gyp:*',
- '../tests/selenium/selenium.gyp:*',
- '../tests/tests.gyp:unit_tests',
- '../utils/utils.gyp:o3dUtils',
- ],
- 'conditions': [
- ['OS=="win"',
- {
- 'dependencies': [
- '../plugin/plugin.gyp:o3d_host',
- ],
- },
- ],
- ['OS=="mac"',
- {
- 'dependencies': [
- '../../breakpad/breakpad.gyp:breakpad',
- ],
- },
- ],
- ],
- },
- ],
-}
diff --git a/o3d/build/o3d_in_chrome.gyp b/o3d/build/o3d_in_chrome.gyp
deleted file mode 100644
index 08f2e59..0000000
--- a/o3d/build/o3d_in_chrome.gyp
+++ /dev/null
@@ -1,29 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'includes': [
- 'common.gypi',
- ],
- 'targets': [
- # Depend on this target to set the O3D_IN_CHROME macro. This also works for
- # indirectly dependent Chromium projects that do not include the O3D
- # common.gypi.
- {
- 'target_name': 'o3d_in_chrome',
- 'type': 'none',
- 'conditions': [
- ['o3d_in_chrome == "True"',
- {
- 'all_dependent_settings': {
- 'defines': [
- 'O3D_IN_CHROME',
- ], # 'defines'
- }, # 'all_dependent_settings'
- },
- ],
- ], # 'conditions'
- },
- ],
-}
diff --git a/o3d/build/o3d_minimal.gyp b/o3d/build/o3d_minimal.gyp
deleted file mode 100644
index 200c9cb..0000000
--- a/o3d/build/o3d_minimal.gyp
+++ /dev/null
@@ -1,18 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'includes': [
- 'common.gypi',
- ],
- 'targets': [
- {
- 'target_name': 'O3D_Minimal',
- 'type': 'none',
- 'dependencies': [
- '../plugin/plugin.gyp:o3dPlugin',
- ],
- },
- ],
-}
diff --git a/o3d/build/pixman.gyp b/o3d/build/pixman.gyp
deleted file mode 100644
index 8811b9d..0000000
--- a/o3d/build/pixman.gyp
+++ /dev/null
@@ -1,103 +0,0 @@
-# Copyright (c) 2011 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'pixmanbuilddir': '<(SHARED_INTERMEDIATE_DIR)/pixman',
- },
- 'includes': [
- 'common.gypi',
- ],
- 'targets': [
- {
- 'target_name': 'pixman',
- 'conditions': [
- ['OS == "mac"',
- {
- 'type': 'none',
- 'actions': [
- {
- 'action_name': 'build_pixman',
- 'inputs': [
- '<!@(find ../../<(pixmandir) -name .svn -prune -o -type f '
- '-print)',
- ],
- 'outputs': [
- '<(pkgconfigroot)/usr/lib/libpixman-1.a',
- # There are other outputs but it is sufficient to just list
- # one.
- ],
- 'action': [
- 'sh',
- '-c',
- # Delete existing build directory, if any.
- 'rm -rf <(pixmanbuilddir) && '
- # Copy the pixman tree to the build directory.
- 'cp -r ../../<(pixmandir) <(pixmanbuilddir) && '
- # Go there!
- 'cd <(pixmanbuilddir) && '
- # Configure it.
- 'CFLAGS="-arch <(mac_gcc_arch) <(mac_gcc_debug_flag)" '
- './configure --prefix=<(pkgconfigroot)/usr '
- '--disable-shared && '
- # Build.
- 'make && '
- # "Install" to pkgconfigroot.
- 'make install',
- ],
- },
- ],
- },
- ],
- ['OS == "win"',
- {
- 'type': 'static_library',
- 'defines': [
- # Build pixman with Windows XP support.
- '_WIN32_WINNT=0x0502',
- 'WINVER=0x0502',
- 'PACKAGE=pixman',
- 'PACKAGE_VERSION=""',
- 'PACKAGE_BUGREPORT=""',
- 'USE_SSE2',
- 'USE_MMX',
- ],
- 'include_dirs': [
- '../../<(pixmandir)/pixman',
- ],
- 'sources': [
- '../../<(pixmandir)/pixman/pixman.c',
- '../../<(pixmandir)/pixman/pixman-access.c',
- '../../<(pixmandir)/pixman/pixman-access-accessors.c',
- '../../<(pixmandir)/pixman/pixman-bits-image.c',
- '../../<(pixmandir)/pixman/pixman-combine32.c',
- '../../<(pixmandir)/pixman/pixman-combine64.c',
- '../../<(pixmandir)/pixman/pixman-conical-gradient.c',
- '../../<(pixmandir)/pixman/pixman-cpu.c',
- '../../<(pixmandir)/pixman/pixman-edge.c',
- '../../<(pixmandir)/pixman/pixman-edge-accessors.c',
- '../../<(pixmandir)/pixman/pixman-fast-path.c',
- '../../<(pixmandir)/pixman/pixman-general.c',
- '../../<(pixmandir)/pixman/pixman-gradient-walker.c',
- '../../<(pixmandir)/pixman/pixman-implementation.c',
- '../../<(pixmandir)/pixman/pixman-image.c',
- '../../<(pixmandir)/pixman/pixman-linear-gradient.c',
- '../../<(pixmandir)/pixman/pixman-matrix.c',
- '../../<(pixmandir)/pixman/pixman-mmx.c',
- '../../<(pixmandir)/pixman/pixman-radial-gradient.c',
- '../../<(pixmandir)/pixman/pixman-region16.c',
- '../../<(pixmandir)/pixman/pixman-region32.c',
- '../../<(pixmandir)/pixman/pixman-solid-fill.c',
- '../../<(pixmandir)/pixman/pixman-sse2.c',
- '../../<(pixmandir)/pixman/pixman-timer.c',
- '../../<(pixmandir)/pixman/pixman-trap.c',
- '../../<(pixmandir)/pixman/pixman-utils.c',
- '../../<(pixmandir)/pixman/pixman-win32-tls.c',
- ],
- },
- ],
- ],
- },
- ],
-}
diff --git a/o3d/build/pkg-config.gyp b/o3d/build/pkg-config.gyp
deleted file mode 100644
index 81fe308..0000000
--- a/o3d/build/pkg-config.gyp
+++ /dev/null
@@ -1,54 +0,0 @@
-# Copyright (c) 2011 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'pkgconfigbuilddir': '<(SHARED_INTERMEDIATE_DIR)/pkg-config',
- },
- 'includes': [
- 'common.gypi',
- ],
- 'targets': [
- {
- 'target_name': 'pkg-config',
- 'type': 'none',
- 'conditions': [
- ['OS == "mac"',
- {
- 'actions': [
- {
- 'action_name': 'build_pkgconfig',
- 'inputs': [
- '<!@(find ../../<(pkgconfigdir) -name .svn -prune -o -type f '
- '-print)',
- ],
- 'outputs': [
- '<(pkgconfigroot)/usr/bin/pkg-config',
- # There are other outputs but it is sufficient to just list
- # one.
- ],
- 'action': [
- 'sh',
- '-c',
- # Delete existing build directory, if any.
- 'rm -rf <(pkgconfigbuilddir) && '
- # Copy the pkg-config tree to the build directory.
- 'cp -r ../../<(pkgconfigdir) <(pkgconfigbuilddir) && '
- # Go there!
- 'cd <(pkgconfigbuilddir) && '
- # Configure it.
- './configure --prefix=<(pkgconfigroot)/usr && '
- # Build.
- 'make && '
- # "Install" to pkgconfigroot.
- 'make install',
- ],
- },
- ],
- },
- ],
- ],
- },
- ],
-}
diff --git a/o3d/build/select_dependencies.py b/o3d/build/select_dependencies.py
deleted file mode 100644
index d9fb546..0000000
--- a/o3d/build/select_dependencies.py
+++ /dev/null
@@ -1,17 +0,0 @@
-#!/usr/bin/env python
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""This file selects which of the sets of dependencies are used
- when Chrome includes o3d.gyp"""
-
-import os.path
-import sys
-
-has_assets = os.path.exists(os.path.join("..", "o3d_assets"))
-if has_assets:
- print "o3d_all.gyp"
-else:
- print "o3d_minimal.gyp"
-sys.exit(0)
diff --git a/o3d/build/version.gypi b/o3d/build/version.gypi
deleted file mode 100644
index dbd5cda..0000000
--- a/o3d/build/version.gypi
+++ /dev/null
@@ -1,9 +0,0 @@
-# Copyright (c) 2010 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'plugin_version': '0.1.43.7',
- }
-}
diff --git a/o3d/cg_to_glsl/convert.py b/o3d/cg_to_glsl/convert.py
deleted file mode 100755
index 44800a1..0000000
--- a/o3d/cg_to_glsl/convert.py
+++ /dev/null
@@ -1,284 +0,0 @@
-#!/usr/bin/python
-import optparse
-import os
-import re
-import subprocess
-import sys
-
-# This script takes an o3d cg shader from standard input and does the following:
-#
-# * it extracts entry points to vertex and fragment shaders as specified by
-# VertexShaderEntryPoint and PixelShaderEntryPoint instructions;
-#
-# * renames NORMAL, TANGENT{,1} and BINORMAL{,1} attributes to ATTR8-12;
-#
-# * runs cgc with glslv and glslf profiles with those entry points;
-#
-# * renames attributes and uniforms back to their orignal names;
-#
-# * changes 'uniform vecN var[N]' to 'uniform matN var';
-#
-# * renames gl_Vertex and gl_MultiTexCoordN to position and texCoordN
-# respectively and adds attribute declarations;
-#
-# * prints the results to standard output, separating them with SplitMarker
-# instruction and keeping the MatrixLoadOrder instruction as is.
-
-# Cygwin lies about the OS name ("posix" instead of "nt"), the line
-# separator, and perhaps other things. For most robust behavior, try
-# to find cgc on disk.
-
-def find_o3d_root():
- path = os.path.abspath(sys.path[0])
- for i in range(5):
- path = os.path.dirname(path)
- if (os.path.isdir(os.path.join(path, 'o3d')) and
- os.path.isdir(os.path.join(path, 'third_party'))):
- return path
- return ''
-
-def default_cgc():
- paths = ['/usr/bin/cgc',
- 'C:/Program Files/NVIDIA Corporation/Cg/bin/cgc.exe',
- 'C:/Program Files (x86)/NVIDIA Corporation/Cg/bin/cgc.exe']
- for path in paths:
- if os.path.exists(path):
- return path
- script_path = os.path.abspath(sys.path[0])
- # Try again looking in the current working directory to match
- # the layout of the prebuilt o3dConverter binaries.
- cur_dir_paths = [os.path.join(script_path, 'cgc'),
- os.path.join(script_path, 'cgc.exe')]
- for path in cur_dir_paths:
- if (os.path.exists(path)):
- return path
-
- # Last fallback is to use the binaries in o3d/third_party/cg/files.
- # Unfortunately, because we can't rely on the OS name, we have to
- # actually try running the cgc executable.
- o3d_root = find_o3d_root();
- cg_root = os.path.join(o3d_root, 'third_party', 'cg', 'files')
- exe_paths = ['linux/bin/cgc',
- 'linux/bin64/cgc',
- 'mac/bin/cgc',
- 'win/bin/cgc.exe']
- for exe_path in exe_paths:
- try:
- exe = os.path.join(cg_root, exe_path)
- return_code = subprocess.call([exe, '-v'],
- stdout=open(os.devnull, 'w'),
- stderr=open(os.devnull, 'w'))
- if return_code == 0 or return_code == 1:
- return exe
- except:
- pass
-
- # We don't know where cgc lives.
- return ''
-
-def check_cgc(cgc_path):
- if not os.path.exists(cgc_path):
- print >>sys.stderr, (cgc_path +
- ' is not found, use --cgc option to specify its')
- print >>sys.stderr, 'location. You may need to install nvidia cg toolkit.'
- sys.exit(1)
-
-# cgc complains about TANGENT1 and BINORMAL1 semantics, so we hack it by
-# replacing standard semantics with ATTR8-ATTR12 and then renaming them back to
-# their original names.
-ATTRIBUTES_TO_SEMANTICS = dict(
- attr8 = 'normal',
- attr9 = 'tangent',
- attr10 = 'binormal',
- attr11 = 'tangent1',
- attr12 = 'binormal1')
-
-MATRIX_UNIFORM_NAMES = [
- 'world',
- 'view',
- 'projection',
- 'worldView',
- 'worldViewProjection',
- 'worldInverse',
- 'viewInverse',
- 'projectionInverse',
- 'worldViewInverse',
- 'viewProjectionInverse',
- 'worldViewProjectionInverse',
- 'worldTranspose',
- 'viewTranspose',
- 'projectionTranspose',
- 'worldViewTranspose',
- 'viewProjectionTranspose',
- 'worldViewProjectionTranspose',
- 'worldInverseTranspose',
- 'viewInverseTranspose',
- 'projectionInverseTranspose',
- 'worldViewInverseTranspose',
- 'viewProjectionInverseTranspose',
- 'worldViewProjectionInverseTranspose'
-]
-
-MATRIX_UNIFORM_NAMES_MAPPING = dict((name.lower(), name)
- for name in MATRIX_UNIFORM_NAMES)
-
-def correct_semantic_case(name):
- lower_name = name.lower()
- return MATRIX_UNIFORM_NAMES_MAPPING.get(lower_name, lower_name)
-
-def get_input_mapping(header):
- ret = dict()
- for l in header.splitlines():
- if not l.startswith('//var'):
- continue
- old_name_and_type, semantic, new_name, _, _ = l.split(' : ')
- if '[' in new_name:
- new_name = new_name[:new_name.index('[')]
- if new_name.startswith('$'):
- new_name = new_name[1:]
- if semantic:
- ret[new_name] = correct_semantic_case(semantic)
- else:
- ret[new_name] = old_name_and_type.split(' ')[2]
- return ret
-
-
-def fix_glsl_body(body, input_mapping):
- # Change uniform names back to original.
- for match in re.findall(r'(?m)^uniform (?:\w+) (\w+)', body):
- body = re.sub(r'\b%s\b' % match, input_mapping[match], body)
-
- # Change attribute names back to original.
- for match in re.findall(r'(?m)^attribute (?:\w+) (\w+)', body):
- attr_name = input_mapping[match]
- assert attr_name.startswith('$vin.')
- orig_name = ATTRIBUTES_TO_SEMANTICS[attr_name[len('$vin.'):]]
- body = re.sub(r'\b%s\b' % match, orig_name, body)
-
- # Change vecN blah[N]; to matN blah;
- body = re.sub(r'(?m)^uniform vec(\d) (\w+)\[\1\];', r'uniform mat\1 \2;',
- body)
-
- attributes = []
- if 'gl_Vertex' in body:
- # Change gl_Vertex to position and add attribute declaration.
- body = re.sub(r'\bgl_Vertex\b', 'position', body)
- attributes.append('attribute vec4 position;')
-
- for n in xrange(8):
- if 'gl_MultiTexCoord%d' % n in body:
- # Change gl_MultiTexCoordN (0<=N<=7) to texCoordN and add attribute
- # declaration.
- body = re.sub(r'\bgl_MultiTexCoord%d\b' % n, 'texCoord%d' % n, body)
- attributes.append('attribute vec4 texCoord%d;' % n)
-
- # ATTRIBUTES_TO_SEMANTICS should have taken care of normals.
- assert 'gl_Normal' not in body
-
- if 'gl_Position' in body:
- # If there is exactly one assignment to gl_Position, modify it similar to
- # how RewriteVertexProgramSource in gl/effect_gl.cc does it. The input is
- # taken from vec4 dx_clipping uniform.
- #
- # If there is more than one gl_Position mentioned in the shader, the
- # converter fails.
- assert len(re.findall('gl_Position', body)) == 1
- attributes.append('vec4 _glPositionTemp;')
- attributes.append('uniform vec4 dx_clipping;')
- body = re.sub(r'\bgl_Position\b([^;]*);',
- r'_glPositionTemp\1; gl_Position = vec4(' +
- r'_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, ' +
- r'dx_clipping.w * ' +
- r'(_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), ' +
- r'_glPositionTemp.z * 2.0 - _glPositionTemp.w, ' +
- r'_glPositionTemp.w);', body)
-
- return '\n'.join(attributes) + '\n\n' + body
-
-
-def fix_glsl(glsl_shader):
- # Hack for Cygwin lying about os.linesep and being POSIX on Windows.
- if '\r\n' in glsl_shader:
- header, body = re.split('\r\n'*2, glsl_shader, 1)
- else:
- header, body = re.split(os.linesep*2, glsl_shader, 1)
-
- for l in header.splitlines():
- assert l.startswith('//')
- input_mapping = get_input_mapping(header)
- return header + '\n\n' + fix_glsl_body(body, input_mapping)
-
-
-def cg_rename_attributes(cg_shader):
- for new, old in ATTRIBUTES_TO_SEMANTICS.iteritems():
- cg_shader = re.sub(r'\b%s\b' % old.upper(), new.upper(), cg_shader)
- return cg_shader
-
-
-def cg_to_glsl(cg_shader, cgc_path):
- cg_shader = cg_rename_attributes(cg_shader)
-
- vertex_entry = re.search(r'#o3d\s+VertexShaderEntryPoint\s+(\w+)',
- cg_shader).group(1)
- p = subprocess.Popen([cgc_path]+('-profile glslv -entry %s' %
- vertex_entry).split(' '),
- stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- glsl_vertex, err_v = p.communicate(cg_shader)
-
- fragment_entry = re.search(r'#o3d\s+PixelShaderEntryPoint\s+(\w+)',
- cg_shader).group(1)
- p = subprocess.Popen([cgc_path]+('-profile glslf -entry %s' %
- fragment_entry).split(' '),
- stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- glsl_fragment, err_f = p.communicate(cg_shader)
-
- log = (
- '// glslv profile log:\n' +
- '\n'.join('// ' + l for l in err_v.splitlines()) + '\n\n'
- '// glslf profile log:\n' +
- '\n'.join('// ' + l for l in err_f.splitlines())) + '\n'
-
- return glsl_vertex, glsl_fragment, log
-
-
-def get_matrixloadorder(cg_shader):
- return re.search(r'(?m)^.*#o3d\s+MatrixLoadOrder\b.*$', cg_shader).group(0)
-
-
-def main(cg_shader, cgc_path):
- matrixloadorder = get_matrixloadorder(cg_shader)
- glsl_vertex, glsl_fragment, log = cg_to_glsl(cg_shader, cgc_path)
-
- print log
- print fix_glsl(glsl_vertex)
- print
- print '// #o3d SplitMarker'
- print get_matrixloadorder(cg_shader).strip()
- print
- print fix_glsl(glsl_fragment)
-
-
-if __name__ == '__main__':
- cgc_path = default_cgc()
- cmdline_parser = optparse.OptionParser()
- cmdline_parser.add_option('-i', dest='file', default=None,
- help='input shader; standard input if omitted')
- cmdline_parser.add_option('--cgc', dest='cgc_path', default=cgc_path,
- help='path to cgc [default: %default]')
- options, args = cmdline_parser.parse_args()
- cgc_path = options.cgc_path
- check_cgc(cgc_path)
-
- try:
- if options.file is None:
- f = sys.stdin
- else:
- f = open(options.file)
- input = f.read()
- except KeyboardInterrupt:
- input = None
-
- if not input:
- cmdline_parser.print_help()
- else:
- main(input, cgc_path)
diff --git a/o3d/codereview.settings b/o3d/codereview.settings
deleted file mode 100644
index dc940b8..0000000
--- a/o3d/codereview.settings
+++ /dev/null
@@ -1,10 +0,0 @@
-# This file is used by gcl to get repository specific information.
-CODE_REVIEW_SERVER: codereview.chromium.org
-CC_LIST: o3d-review@googlegroups.com
-VIEW_VC: http://src.chromium.org/viewvc/chrome?view=rev&revision=
-STATUS: http://o3d-status.appspot.com/status
-TRY_ON_UPLOAD: True
-TRYSERVER_PROJECT: o3d
-# Share the nacl tryserver check-in location.
-TRYSERVER_SVN_URL: svn://svn.chromium.org/chrome-try/try-nacl
-
diff --git a/o3d/collada_edge/README.collada_edge b/o3d/collada_edge/README.collada_edge
deleted file mode 100644
index f2f9a45..0000000
--- a/o3d/collada_edge/README.collada_edge
+++ /dev/null
@@ -1,25 +0,0 @@
-Collada_edge tool is a command line utility that could add additional edges
-to represent the outline of the model based on user's specification.
-This tool is independent from o3d.
-
-It is able to read COLLADA file as DAE text files, and then outputs a DAE
-with a different name specified by the user.
-
-In order to compile and run this tool, you need FCollada and vectormath lib
-installed.
-
-The command line arguments are as follows:
-
-Usage: ColladaEdgeConditioner <infile.dae> <outifle.dae>
- [-sharpEdgeThreshold t]
- [-sharpEdgeColor r,g,b]
-
--sharpEdgeThreshold t : sharp edge threshold defined by dihedral
- angle. Edges with a angle smaller than t
- will be defined as a sharp edge.
--sharpEdgeColor r,g,b : color of addtional edges.
- default value is 1,0,0 .(no space)
-
-ColladaEdgeConditioner checks all polygon edges in <infile.dae> and add
-addtional edges to the model if normal angle of certain edge is larger
-than the pre-defined threshold. \ No newline at end of file
diff --git a/o3d/collada_edge/collada_edge.vcproj b/o3d/collada_edge/collada_edge.vcproj
deleted file mode 100644
index 589c442..0000000
--- a/o3d/collada_edge/collada_edge.vcproj
+++ /dev/null
@@ -1,225 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
- ProjectType="Visual C++"
- Version="9.00"
- Name="ColladaEdgeConditioner"
- ProjectGUID="{F96F6A96-AA54-4D00-BD4F-BE14850D355D}"
- RootNamespace="CheckSharpEdge"
- Keyword="Win32Proj"
- TargetFrameworkVersion="196613"
- >
- <Platforms>
- <Platform
- Name="Win32"
- />
- </Platforms>
- <ToolFiles>
- </ToolFiles>
- <Configurations>
- <Configuration
- Name="Debug|Win32"
- OutputDirectory="$(SolutionDir)$(ConfigurationName)"
- IntermediateDirectory="$(ConfigurationName)"
- ConfigurationType="1"
- CharacterSet="1"
- >
- <Tool
- Name="VCPreBuildEventTool"
- />
- <Tool
- Name="VCCustomBuildTool"
- />
- <Tool
- Name="VCXMLDataGeneratorTool"
- />
- <Tool
- Name="VCWebServiceProxyGeneratorTool"
- />
- <Tool
- Name="VCMIDLTool"
- />
- <Tool
- Name="VCCLCompilerTool"
- Optimization="0"
- AdditionalIncludeDirectories="FCollada\header"
- PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
- MinimalRebuild="true"
- BasicRuntimeChecks="3"
- RuntimeLibrary="3"
- UsePrecompiledHeader="0"
- PrecompiledHeaderThrough=""
- PrecompiledHeaderFile="precompile.h"
- WarningLevel="3"
- DebugInformationFormat="4"
- />
- <Tool
- Name="VCManagedResourceCompilerTool"
- />
- <Tool
- Name="VCResourceCompilerTool"
- />
- <Tool
- Name="VCPreLinkEventTool"
- />
- <Tool
- Name="VCLinkerTool"
- AdditionalDependencies="FColladaU.lib"
- LinkIncremental="2"
- AdditionalLibraryDirectories="FCollada\lib"
- GenerateDebugInformation="true"
- SubSystem="1"
- TargetMachine="1"
- />
- <Tool
- Name="VCALinkTool"
- />
- <Tool
- Name="VCManifestTool"
- />
- <Tool
- Name="VCXDCMakeTool"
- />
- <Tool
- Name="VCBscMakeTool"
- />
- <Tool
- Name="VCFxCopTool"
- />
- <Tool
- Name="VCAppVerifierTool"
- />
- <Tool
- Name="VCPostBuildEventTool"
- />
- </Configuration>
- <Configuration
- Name="Release|Win32"
- OutputDirectory="$(SolutionDir)$(ConfigurationName)"
- IntermediateDirectory="$(ConfigurationName)"
- ConfigurationType="1"
- CharacterSet="1"
- WholeProgramOptimization="1"
- >
- <Tool
- Name="VCPreBuildEventTool"
- />
- <Tool
- Name="VCCustomBuildTool"
- />
- <Tool
- Name="VCXMLDataGeneratorTool"
- />
- <Tool
- Name="VCWebServiceProxyGeneratorTool"
- />
- <Tool
- Name="VCMIDLTool"
- />
- <Tool
- Name="VCCLCompilerTool"
- Optimization="2"
- EnableIntrinsicFunctions="true"
- AdditionalIncludeDirectories="..\FCollada\header"
- PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
- RuntimeLibrary="2"
- EnableFunctionLevelLinking="true"
- UsePrecompiledHeader="2"
- WarningLevel="3"
- DebugInformationFormat="3"
- />
- <Tool
- Name="VCManagedResourceCompilerTool"
- />
- <Tool
- Name="VCResourceCompilerTool"
- />
- <Tool
- Name="VCPreLinkEventTool"
- />
- <Tool
- Name="VCLinkerTool"
- AdditionalDependencies="FColladaU.lib"
- LinkIncremental="1"
- AdditionalLibraryDirectories="..\FCollada\lib"
- GenerateDebugInformation="true"
- SubSystem="1"
- OptimizeReferences="2"
- EnableCOMDATFolding="2"
- TargetMachine="1"
- />
- <Tool
- Name="VCALinkTool"
- />
- <Tool
- Name="VCManifestTool"
- />
- <Tool
- Name="VCXDCMakeTool"
- />
- <Tool
- Name="VCBscMakeTool"
- />
- <Tool
- Name="VCFxCopTool"
- />
- <Tool
- Name="VCAppVerifierTool"
- />
- <Tool
- Name="VCPostBuildEventTool"
- />
- </Configuration>
- </Configurations>
- <References>
- </References>
- <Files>
- <Filter
- Name="Source Files"
- Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
- UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
- >
- <File
- RelativePath=".\cross\collada_edge.cpp"
- >
- </File>
- <File
- RelativePath=".\cross\conditioner.cpp"
- >
- </File>
- <File
- RelativePath=".\cross\precompile.cpp"
- >
- </File>
- </Filter>
- <Filter
- Name="Header Files"
- Filter="h;hpp;hxx;hm;inl;inc;xsd"
- UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
- >
- <File
- RelativePath=".\cross\conditioner.h"
- >
- </File>
- <File
- RelativePath=".\cross\precompile.h"
- >
- </File>
- <File
- RelativePath=".\cross\utility.h"
- >
- </File>
- </Filter>
- <Filter
- Name="Resource Files"
- Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
- UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
- >
- </Filter>
- <File
- RelativePath=".\ReadMe.txt"
- >
- </File>
- </Files>
- <Globals>
- </Globals>
-</VisualStudioProject>
diff --git a/o3d/collada_edge/cross/collada_edge.cpp b/o3d/collada_edge/cross/collada_edge.cpp
deleted file mode 100644
index effb592..0000000
--- a/o3d/collada_edge/cross/collada_edge.cpp
+++ /dev/null
@@ -1,87 +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.
- */
-
-// collada_edge.cpp : Defines the entry point for the console application.
-#include "precompile.h"
-#include "conditioner.h"
-#include <cstdio>
-
-static const char *usage =
-"\nUsage: ColladaEdgeConditioner <infile.dae> <outifle.dae> [ options ]\n\n\
-Options:\n\
- -sharpEdgeThreshold t : sharp edge threshold defined by dihedral \n\
- angle. Edges with a angle smaller than t\n\
- will be defined as a sharp edge.\n\
- -sharpEdgeColor r,g,b : color of addtional edges.\n\
- default value is 1,0,0 .(no space)\n\n\
-ColladaEdgeConditioner checks all polygon edges in <infile.dae> and add\n\
-addtional edges to the model if normal angle of certain edge is larger\n\
-than the pre-defined threshold.\n";
-
-int wmain(int argc, wchar_t **argv) {
- wchar_t* input_file = NULL;
- wchar_t* output_file = NULL;
- Options options;
-
- if (argc < 3) {
- printf("%s", usage);
- return -1;
- }
- int file_count = 0;
- for (int i = 1; i < argc; i++) {
- if (wcscmp(argv[i], L"-sharpEdgeThreshold") == 0) {
- if (++i < argc) {
- options.enable_soften_edge = true;
- options.soften_edge_threshold = static_cast<float>(_wtof(argv[i]));
- }
- } else if (wcscmp(argv[i], L"-sharpEdgeColor") == 0) {
- if (++i < argc) {
- int r, g, b;
- if (swscanf_s(argv[i], L"%d,%d,%d", &r, &g, &b) != 3) {
- printf("Invalid -sharpEdgeColor. Should be -sharpEdgeColor=x,y,z\n");
- return -1;
- }
- options.sharp_edge_color = Vector3(static_cast<float>(r),
- static_cast<float>(g),
- static_cast<float>(b));
- }
- } else if (file_count < 2) {
- ++file_count;
- if (file_count == 1)
- input_file = argv[i];
- else
- output_file = argv[i];
- }
- }
-
- bool result = Condition(input_file, output_file, options);
- return 0;
-}
diff --git a/o3d/collada_edge/cross/conditioner.cpp b/o3d/collada_edge/cross/conditioner.cpp
deleted file mode 100644
index b9efb1a..0000000
--- a/o3d/collada_edge/cross/conditioner.cpp
+++ /dev/null
@@ -1,371 +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 "precompile.h"
-
-#include "conditioner.h"
-
-#include <cstdio>
-#include <map>
-#include <vector>
-
-const float kEpsilon = 0.001f;
-static const float kPi = 3.14159265358979f;
-FCDMaterial* edge_material = NULL;
-FCDEffect* edge_effect = NULL;
-
-// Constructor, make sure points order is unique. If x-coordinate is
-// the same, compare y-coordinate. If y value is also the same, compare z.
-Edge::Edge(Point3 p1, Point3 p2, uint32 i1, uint32 i2) {
- bool isRightOrder = false;
- if (fabs(p1.getX() - p2.getX()) < kEpsilon) {
- if (fabs(p1.getY() - p2.getY()) < kEpsilon) {
- if (p1.getZ() < p2.getZ())
- isRightOrder = true;
- } else {
- if (p1.getY() < p2.getY())
- isRightOrder = true;
- }
- } else {
- if (p1.getX() < p2.getX())
- isRightOrder = true;
- }
- if (isRightOrder) {
- pts.push_back(p1);
- pts.push_back(p2);
- indices.push_back(i1);
- indices.push_back(i2);
- } else {
- pts.push_back(p2);
- pts.push_back(p1);
- indices.push_back(i2);
- indices.push_back(i1);
- }
-}
-
-// Less than operator overload, necessary function for edge-triangle map.
-bool operator<(const Edge& left, const Edge& right) {
- // compare two edges by their actually coordinates.
- if (dist(left.pts[0], right.pts[0]) < kEpsilon) {
- if (fabs(left.pts[1].getX() - right.pts[1].getX()) < kEpsilon) {
- if (fabs(left.pts[1].getY() - right.pts[1].getY()) < kEpsilon) {
- return left.pts[1].getZ() < right.pts[1].getZ();
- }
- return left.pts[1].getY() < right.pts[1].getY();
- }
- return left.pts[1].getX() < right.pts[1].getX();
- } else {
- if (fabs(left.pts[0].getX() - right.pts[0].getX()) < kEpsilon) {
- if (fabs(left.pts[0].getY() - right.pts[0].getY()) < kEpsilon) {
- return left.pts[0].getZ() < right.pts[0].getZ();
- }
- return left.pts[0].getY() < right.pts[0].getY();
- }
- return left.pts[0].getX() < right.pts[0].getX();
- }
-}
-
-// Go through triangles who share this edge. And check whether
-// the max normal angle is larger than the threshold.
-void CheckSharpEdge(const Edge& shared_edge,
- const std::vector<Triangle>& triangle_list,
- std::vector<Edge>* sharp_edges, float threshold) {
- for (size_t i = 0; i < triangle_list.size(); i++)
- for (size_t j = i + 1; j < triangle_list.size(); j++) {
- Triangle t1 = triangle_list[i];
- Triangle t2 = triangle_list[j];
- int same_vertices_count = 0;
- // Same triangle might be stored twice to represent inner and
- // outer faces. Check the order of indices of vertices to not
- // mix inner and outer faces togeter.
- std::vector<int> same_vertices_pos;
- for (int k = 0; k < 3; k++)
- for (int l = 0; l < 3; l++) {
- if (dist(t1.pts[k], t2.pts[l]) < kEpsilon) {
- same_vertices_count++;
- same_vertices_pos.push_back(k);
- same_vertices_pos.push_back(l);
- }
- }
- if (same_vertices_count != 2)
- continue;
- // check the order of positions to make sure triangles are on
- // the same face.
- int i1 = same_vertices_pos[2] - same_vertices_pos[0];
- int i2 = same_vertices_pos[3] - same_vertices_pos[1];
- // if triangles are on different faces.
- if (!(i1 * i2 == -1 || i1 * i2 == 2 || i1 * i2 == -4))
- continue;
-
- Vector3 v12 = t1.pts[1] - t1.pts[0];
- Vector3 v13 = t1.pts[2] - t1.pts[0];
- Vector3 n1 = cross(v12, v13);
- Vector3 v22 = t2.pts[1] - t2.pts[0];
- Vector3 v23 = t2.pts[2] - t2.pts[0];
- Vector3 n2 = cross(v22, v23);
- float iAngle = acos(dot(n1, n2) / (length(n1) * length(n2)));
- iAngle = iAngle * 180 / kPi;
- if (iAngle >= threshold) {
- sharp_edges->push_back(shared_edge);
- return;
- }
- }
-}
-
-// Insert edge-triangle pair to edge triangle map.
-void InsertEdgeTrianglePair(const Edge& edge, const Triangle& triangle,
- std::map<Edge, std::vector<Triangle>>* et_map) {
- std::map<Edge, std::vector<Triangle>>::iterator iter1 =
- et_map->find(edge);
- if (iter1 == et_map->end()) {
- std::vector<Triangle> same_edge_triangle_list;
- same_edge_triangle_list.push_back(triangle);
- et_map->insert(make_pair(edge, same_edge_triangle_list));
- } else {
- iter1->second.push_back(triangle);
- }
-}
-
-NodeInstance* CreateInstanceTree(FCDSceneNode *node) {
- NodeInstance *instance = new NodeInstance(node);
- NodeInstance::NodeInstanceList &children = instance->children();
- for (size_t i = 0; i < node->GetChildrenCount(); ++i) {
- FCDSceneNode *child_node = node->GetChild(i);
- NodeInstance *child_instance = CreateInstanceTree(child_node);
- children.push_back(child_instance);
- }
- return instance;
-}
-
-// Go through all polygons in geom_instance, and add all sharp edges
-// as a new polygon in geom. And also, add material and effect based
-// on the given sharpEdgeColor option.
-void BuildSharpEdge(FCDocument* doc, FCDGeometryInstance* geom_instance,
- const Options& options) {
- FCDGeometry* geom = static_cast<FCDGeometry*>(geom_instance->GetEntity());
- if (!(geom && geom->IsMesh()))
- return;
- FCDGeometryMesh* mesh = geom->GetMesh();
- FCDGeometryPolygonsTools::Triangulate(mesh);
- FCDGeometryPolygonsTools::GenerateUniqueIndices(mesh, NULL, NULL);
-
- size_t num_polygons = mesh->GetPolygonsCount();
- size_t num_indices = mesh->GetFaceVertexCount();
- if (num_polygons <= 0 || num_indices <= 0) return;
- FCDGeometrySource* pos_source =
- mesh->FindSourceByType(FUDaeGeometryInput::POSITION);
- if (pos_source == NULL) return;
- size_t num_vertices = pos_source->GetValueCount();
- float* pos_source_data = pos_source->GetData();
- std::vector<Point3> point_list;
- for (size_t i = 0; i + 2 < num_vertices * 3; i += 3) {
- Point3 point(pos_source_data[i + 0],
- pos_source_data[i + 1],
- pos_source_data[i + 2]);
- point_list.push_back(point);
- }
-
- for (size_t p = 0; p < num_polygons; ++p) {
- FCDGeometryPolygons* polys = mesh->GetPolygons(p);
-
- if (polys->GetPrimitiveType() != FCDGeometryPolygons::POLYGONS)
- continue;
- FCDGeometryPolygonsInput* input = polys->GetInput(0);
- size_t size = input->GetIndexCount();
- if (size == 0) continue;
- // meshed triangle list.
- size_t vertices_per_primitive = 3;
- if (size % vertices_per_primitive != 0) {
- continue;
- }
- uint32* indices = input->GetIndices();
- size_t indexCount = input->GetIndexCount();
- // create triangle list.
- std::vector<Triangle> triangle_list;
- for (size_t i = 0; i + 2 < indexCount; i += 3) {
- Triangle triangle(point_list[indices[i + 0]],
- point_list[indices[i + 1]],
- point_list[indices[i + 2]],
- indices[i + 0],
- indices[i + 1],
- indices[i + 2]);
- triangle_list.push_back(triangle);
- }
- std::map<Edge, std::vector<Triangle>> edge_triangle_map;
- for (size_t i = 0; i < triangle_list.size(); i++) {
- Triangle triangle = triangle_list[i];
- Edge e1(triangle.pts[0], triangle.pts[1],
- triangle.indices[0], triangle.indices[1]);
- Edge e2(triangle.pts[1], triangle.pts[2],
- triangle.indices[1], triangle.indices[2]);
- Edge e3(triangle.pts[0], triangle.pts[2],
- triangle.indices[0], triangle.indices[2]);
- InsertEdgeTrianglePair(e1, triangle, &edge_triangle_map);
- InsertEdgeTrianglePair(e2, triangle, &edge_triangle_map);
- InsertEdgeTrianglePair(e3, triangle, &edge_triangle_map);
- }
- // go through the edge-triangle map.
- std::map<Edge, std::vector<Triangle>>::iterator iter;
- std::vector<Edge> sharp_edges;
- for (iter = edge_triangle_map.begin();
- iter != edge_triangle_map.end(); iter++) {
- if (iter->second.size() < 2)
- continue;
- CheckSharpEdge(iter->first, iter->second, &sharp_edges,
- options.soften_edge_threshold);
- }
- if (sharp_edges.size() > 0) {
- FCDGeometryPolygons* edge_polys = mesh->AddPolygons();
- edge_polys->AddFaceVertexCount(sharp_edges.size() * 2);
- edge_polys->SetPrimitiveType(FCDGeometryPolygons::LINES);
- FCDGeometrySource* vertex_source = mesh->GetVertexSource(0);
- FCDGeometryPolygonsInput* edge_input =
- edge_polys->AddInput(vertex_source, 0);
- FUDaeGeometryInput::Semantic semantic = edge_input->GetSemantic();
- if (edge_input == NULL)
- return;
- FCDGeometrySource* edge_source = edge_input->GetSource();
- if (edge_source == NULL)
- return;
- for (size_t i = 0; i < sharp_edges.size(); i++) {
- edge_input->AddIndex(sharp_edges[i].indices[0]);
- edge_input->AddIndex(sharp_edges[i].indices[1]);
- }
- edge_input->SetIndexCount(sharp_edges.size() * 2);
- edge_input->SetOffset(0);
-
- if (edge_material == NULL) {
- // add material to material lib.
- FCDMaterialLibrary* material_library = doc->GetMaterialLibrary();
- FCDEffectLibrary* effect_library = doc->GetEffectLibrary();
- edge_material =
- static_cast<FCDMaterial*>(material_library->AddEntity());
- edge_material->SetDaeId("o3d_hard_edge_materialID");
- edge_material->SetName(L"o3d_hard_edge_material");
- edge_effect = static_cast<FCDEffect*>(effect_library->AddEntity());
- edge_effect->SetDaeId("o3d_hard_edge_effectID");
- edge_effect->SetName(L"o3d_hard_edge_effect");
- if (edge_effect == NULL || edge_material == NULL)
- return;
- edge_material->SetEffect(edge_effect);
- FCDEffectStandard* edge_effect_profile =
- static_cast<FCDEffectStandard*>(edge_effect->AddProfile(
- FUDaeProfileType::COMMON));
- edge_effect_profile->SetLightingType(FCDEffectStandard::LAMBERT);
- edge_effect_profile->
- SetEmissionColor(FMVector4(options.sharp_edge_color.getX(),
- options.sharp_edge_color.getY(),
- options.sharp_edge_color.getZ(), 1));
- }
- // add material instance to visual scenes lib.
- FCDMaterialInstance* edge_material_instance =
- geom_instance->AddMaterialInstance(edge_material, edge_polys);
- edge_material_instance->SetSemantic(L"o3d_hard_edge_material");
- edge_polys->SetMaterialSemantic(L"o3d_hard_edge_material");
- }
- }
-}
-
-// go through the collada tree and import instance. if found a
-// geometry instance, call BuildSharpEdge function.
-bool ImportTreeInstances(FCDocument* doc,
- NodeInstance *node_instance,
- const Options& options) {
- FCDSceneNode *node = node_instance->node();
- // recursively import the rest of the nodes in the tree
- const NodeInstance::NodeInstanceList &children = node_instance->children();
- for (size_t i = 0; i < children.size(); ++i) {
- if (!ImportTreeInstances(doc, children[i], options)) {
- return false;
- }
- }
- for (size_t i = 0; i < node->GetInstanceCount(); ++i) {
- FCDEntityInstance* instance = node->GetInstance(i);
- FCDCamera* camera(NULL);
- FCDGeometryInstance* geom_instance(NULL);
- FCDMaterialInstance* mat_instance(NULL);
- // Import each node based on what kind of entity it is
- switch (instance->GetEntityType()) {
- case FCDEntity::GEOMETRY: {
- // geometry entity
- geom_instance = static_cast<FCDGeometryInstance*>(instance);
- BuildSharpEdge(doc, geom_instance, options);
- break;
- }
- case FCDEntity::CAMERA:
- case FCDEntity::CONTROLLER:
- default: break;
- }
- }
- return true;
-}
-
-bool ConditionDoc(FCDocument* doc, const Options& options) {
- // The root of the instance node tree.
- NodeInstance* instance_root_;
- bool status = false;
- // Import the scene objects, starting at the root.
- FCDSceneNode* scene = doc->GetVisualSceneInstance();
- if (scene) {
- instance_root_ = CreateInstanceTree(scene);
- if (ImportTreeInstances(doc, instance_root_, options)) {
- status = true;
- }
- delete instance_root_;
- }
- return status;
-}
-
-bool Condition(const wchar_t* in_filename, const wchar_t* out_filename,
- const Options& options) {
- FCollada::Initialize();
- FCDocument* doc = FCollada::NewTopDocument();
- bool retval = false;
- if (doc) {
- // Load and parse the COLLADA file.
- if (FCollada::LoadDocumentFromFile(doc, in_filename)) {
- doc->SetFileUrl(out_filename);
-
- // condition it.
- retval = ConditionDoc(doc, options);
- if (retval) {
- FCollada::SaveDocument(doc, out_filename);
- }
- } else {
- printf("Error: couldn't open the input file.\n");
- }
- doc->Release();
- } else {
- printf("Internal error: Couldn't create FCollada document.\n");
- }
- FCollada::Release();
- return retval;
-}
-
diff --git a/o3d/collada_edge/cross/conditioner.h b/o3d/collada_edge/cross/conditioner.h
deleted file mode 100644
index 57c61fabee..0000000
--- a/o3d/collada_edge/cross/conditioner.h
+++ /dev/null
@@ -1,121 +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_COLLADA_EDGE_CONDITIONER_H_
-#define O3D_COLLADA_EDGE_CONDITIONER_H_
-
-#include <vector>
-#include "utility.h"
-
-struct Options {
- // default constructor.
- Options()
- : enable_soften_edge(false),
- soften_edge_threshold(0),
- sharp_edge_color(1, 0, 0) {}
-
- // Add edges with dihedral angle larger than soften_edge_threshold.
- bool enable_soften_edge;
-
- // The threshold of normal angle of edges, if angle of certain
- // edge is larger than this threshold, it will be added into
- // the output file.
- float soften_edge_threshold;
-
- // Color of extra edges.
- Vector3 sharp_edge_color;
-};
-
-// This takes ownership of its children NodeInstances.
-class NodeInstance {
- public:
- typedef std::vector<NodeInstance *> NodeInstanceList;
-
- explicit NodeInstance(FCDSceneNode *node) : node_(node) {}
- ~NodeInstance() {
- for (unsigned int i = 0; i < children_.size(); ++i) {
- delete children_[i];
- }
- }
-
- // Gets the Collada node associated with this node instance.
- FCDSceneNode *node() const { return node_; }
-
- // Gets the list of this node instance's children.
- NodeInstanceList &children() { return children_; }
-
- // Finds the NodeInstance representing a scene node in the direct
- // children of this NodeInstance.
- NodeInstance *FindNodeShallow(FCDSceneNode *node) {
- for (unsigned int i = 0; i < children_.size(); ++i) {
- NodeInstance *child = children_[i];
- if (child->node() == node) return child;
- }
- return NULL;
- }
-
- // Finds the NodeInstance representing a scene node in the sub-tree
- // starting at this NodeInstance.
- NodeInstance *FindNodeInTree(FCDSceneNode *node);
-
- private:
- FCDSceneNode *node_;
- std::vector<NodeInstance *> children_;
-};
-
-// Edge class is used in detect sharp edge process. It stores two points
-// in a specific order, and it serves as key class in edge-triangle map.
-struct Edge {
- Edge(Point3 p1, Point3 p2, uint32 i1, uint32 i2);
- std::vector<Point3> pts;
- std::vector<uint32> indices;
-};
-
-// Triangle class is used in detect sharp edge process.
-struct Triangle {
- Triangle(Point3 p1, Point3 p2, Point3 p3,
- uint32 i1, uint32 i2, uint32 i3) {
- pts.push_back(p1);
- pts.push_back(p2);
- pts.push_back(p3);
- indices.push_back(i1);
- indices.push_back(i2);
- indices.push_back(i3);
- }
- std::vector<Point3> pts;
- std::vector<uint32> indices;
-};
-
-// Conditions the given file to emphasize the sharp edges.
-// Returns false on failure, and writes the relevant erros to stderr.
-bool Condition(const wchar_t* in_filename, const wchar_t* out_filename,
- const Options& options);
-
-#endif \ No newline at end of file
diff --git a/o3d/collada_edge/cross/precompile.cpp b/o3d/collada_edge/cross/precompile.cpp
deleted file mode 100644
index 258d08b..0000000
--- a/o3d/collada_edge/cross/precompile.cpp
+++ /dev/null
@@ -1,32 +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 "precompile.h" \ No newline at end of file
diff --git a/o3d/collada_edge/cross/precompile.h b/o3d/collada_edge/cross/precompile.h
deleted file mode 100644
index e062271..0000000
--- a/o3d/collada_edge/cross/precompile.h
+++ /dev/null
@@ -1,54 +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_COLLADA_EDGE_PRECOMPILE_H_
-#define O3D_COLLADA_EDGE_PRECOMPILE_H_
-
-#include <stdio.h>
-#include <tchar.h>
-
-#include "FCollada.h"
-#include "FCDocument/FCDocument.h"
-#include "FCDocument/FCDEffect.h"
-#include "FCDocument/FCDEffectStandard.h"
-#include "FCDocument/FCDSceneNode.h"
-#include "FCDocument/FCDGeometry.h"
-#include "FCDocument/FCDGeometryInstance.h"
-#include "FCDocument/FCDGeometryMesh.h"
-#include "FCDocument/FCDGeometryPolygons.h"
-#include "FCDocument/FCDGeometryPolygonsInput.h"
-#include "FCDocument/FCDGeometryPolygonsTools.h"
-#include "FCDocument/FCDGeometrySource.h"
-#include "FCDocument/FCDLibrary.h"
-#include "FCDocument/FCDMaterial.h"
-#include "FCDocument/FCDMaterialInstance.h"
-
-#endif \ No newline at end of file
diff --git a/o3d/collada_edge/cross/utility.h b/o3d/collada_edge/cross/utility.h
deleted file mode 100644
index 6fe1bc7..0000000
--- a/o3d/collada_edge/cross/utility.h
+++ /dev/null
@@ -1,45 +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_COLLADA_EDGE_UTILITY_H_
-#define O3D_COLLADA_EDGE_UTILITY_H_
-
-#include "..\vectormath\vectormathlibrary\include\vectormath\scalar\cpp\vectormath_aos.h" // NOLINT"
-
-// Point
-//
-typedef Vectormath::Aos::Point3 Point3;
-
-// 3d-vector
-//
-typedef Vectormath::Aos::Vector3 Vector3;
-
-#endif \ No newline at end of file
diff --git a/o3d/compiler/glsl_validator/Makefile b/o3d/compiler/glsl_validator/Makefile
deleted file mode 100644
index 60dba47..0000000
--- a/o3d/compiler/glsl_validator/Makefile
+++ /dev/null
@@ -1,34 +0,0 @@
-# Makefile for the Flex/Bison GLSL ES grammar and simple test harness.
-# "make" to build everything.
-# "make clean" to clean the build.
-# "make test" to run tests.
-
-CC=gcc
-BUILD=build
-SRC=glsl_es
-
-LEXER_INPUT=$(SRC)/GLSL_ES.l
-GRAMMAR_INPUT=$(SRC)/GLSL_ES.y
-GRAMMAR_INPUTS=$(LEXER_INPUT) $(GRAMMAR_INPUT)
-LEXER_OUTPUT=$(BUILD)/GLSL_ES.lex.c
-GRAMMAR_OUTPUT=$(BUILD)/GLSL_ES.tab.c
-GRAMMAR_OUTPUTS=$(LEXER_OUTPUT) $(GRAMMAR_OUTPUT)
-
-$(BUILD)/GLSLESParser: $(GRAMMAR_OUTPUTS)
- $(CC) -I$(BUILD) $(GRAMMAR_OUTPUTS) -o $(BUILD)/GLSLESParser
-
-$(GRAMMAR_OUTPUTS): $(GRAMMAR_INPUTS)
- mkdir -p $(BUILD)
- lex -o $(LEXER_OUTPUT) $(LEXER_INPUT)
- bison -o $(GRAMMAR_OUTPUT) -v -d --debug $(GRAMMAR_INPUT)
-
-.PHONY: test
-
-test:
- @for i in $(shell ls shaders/*.vert) $(shell ls shaders/*.frag) ; do \
- echo Parsing $$i ; \
- time $(BUILD)/GLSLESParser < $$i ; \
- done
-
-clean:
- rm $(BUILD)/GLSLESParser $(GRAMMAR_OUTPUTS) $(BUILD)/GLSL_ES.output $(BUILD)/GLSL_ES.tab.h
diff --git a/o3d/compiler/glsl_validator/build.xml b/o3d/compiler/glsl_validator/build.xml
deleted file mode 100644
index ee52a8c..0000000
--- a/o3d/compiler/glsl_validator/build.xml
+++ /dev/null
@@ -1,89 +0,0 @@
-<!--
- - Ant build for the ANTLR GLSL ES grammar and simple test harness.
- - "ant" to compile everything.
- - "ant clean" to clean the build.
- - "ant test" to run tests.
- -->
-
-<project name="GLSL_ES" basedir="." default="all">
- <target name="init">
- <property name="build" value="build" />
- <property name="test" value="test" />
- <path id="antlr.classpath">
- <pathelement location="../../../third_party/antlr3/lib/antlr-3.1.1.jar" />
- </path>
- <path id="antlr.runtime.classpath">
- <pathelement location="../../../third_party/antlr3/lib/antlr-runtime-3.1.1.jar" />
- </path>
- <path id="test.classpath">
- <pathelement location="../../../third_party/antlr3/lib/antlr-runtime-3.1.1.jar" />
- <pathelement location="${build}" />
- </path>
- </target>
-
- <target name="build" depends="init">
- <mkdir dir="${build}" />
- <mkdir dir="${build}/glsl_es" />
- <!-- Run ANTLR on the grammar -->
- <java classname="org.antlr.Tool" failonerror="true">
- <classpath refid="antlr.classpath" />
- <arg value="glsl_es/GLSL_ES.g" />
- <arg value="-fo" />
- <arg value="${build}/glsl_es" />
- </java>
- <!-- Compile the grammar and test cases -->
- <javac srcdir="${build}:${test}"
- destdir="${build}">
- <classpath refid="antlr.runtime.classpath" />
- </javac>
- </target>
-
- <target name="test" depends="init">
- <java classname="test.Main">
- <classpath refid="test.classpath" />
- <arg value="shaders/ambient.vert" />
- <arg value="shaders/ambient.frag" />
- <arg value="shaders/diffuse.vert" />
- <arg value="shaders/diffuse.frag" />
- <arg value="shaders/many-planets-deep.vert" />
- <arg value="shaders/many-planets-deep.frag" />
- <arg value="shaders/nvidia-vertex-buffer-object.vert" />
- <arg value="shaders/nvidia-vertex-buffer-object.frag" />
- <arg value="shaders/texture_mapping.vert" />
- <arg value="shaders/texture_mapping.frag" />
- <arg value="shaders/particles-2d.vert" />
- <arg value="shaders/particles-3d.vert" />
- <arg value="shaders/particles.frag" />
- <arg value="shaders/san-angeles-flat.vert" />
- <arg value="shaders/san-angeles-lit.vert" />
- <arg value="shaders/san-angeles-flat.frag" />
- <arg value="shaders/shiny-teapot.vert" />
- <arg value="shaders/shiny-teapot.frag" />
- <arg value="shaders/spirit-box.vert" />
- <arg value="shaders/spirit-box.frag" />
- <arg value="shaders/spore-view.vert" />
- <arg value="shaders/spore-view.frag" />
- <arg value="shaders/teapot-per-pixel.vert" />
- <arg value="shaders/teapot-per-pixel.frag" />
- <arg value="shaders/teapot-per-vertex.vert" />
- <arg value="shaders/teapot-per-vertex.frag" />
- </java>
- </target>
-
- <target name="testgrammar" depends="init">
- <mkdir dir="${build}" />
- <!-- Run ANTLR on the grammar -->
- <java classname="org.antlr.Tool">
- <classpath refid="antlr.classpath" />
- <arg value="glsl_es/Test.g" />
- <arg value="-fo" />
- <arg value="${build}" />
- </java>
- </target>
-
- <target name="clean" depends="init">
- <delete dir="${build}" />
- </target>
-
- <target name="all" depends="build" />
-</project>
diff --git a/o3d/compiler/glsl_validator/glsl_es/GLSL_ES.g b/o3d/compiler/glsl_validator/glsl_es/GLSL_ES.g
deleted file mode 100644
index e2cf26e..0000000
--- a/o3d/compiler/glsl_validator/glsl_es/GLSL_ES.g
+++ /dev/null
@@ -1,667 +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 ANTLR grammar for parsing GLSL ES into an Abstract
-// Syntax Tree (AST).
-
-grammar GLSL_ES;
-
-options {
- language = Java;
-}
-
-@lexer::header { package glsl_es; }
-@parser::header { package glsl_es; }
-
-/* Main entry point */
-translation_unit
- : ( external_declaration )* EOF
- ;
-
-variable_identifier
- : IDENTIFIER
- ;
-
-primary_expression
- : INTCONSTANT
- | FLOATCONSTANT
- | BOOLCONSTANT
- | variable_identifier
- | LEFT_PAREN expression RIGHT_PAREN
- ;
-
-postfix_expression
- : primary_expression_or_function_call
- ( LEFT_BRACKET integer_expression RIGHT_BRACKET
- | DOT field_selection
- | INC_OP
- | DEC_OP
- )*
- ;
-
-primary_expression_or_function_call
- : ( INTCONSTANT ) => primary_expression
- | ( FLOATCONSTANT ) => primary_expression
- | ( BOOLCONSTANT ) => primary_expression
- | ( LEFT_PAREN ) => primary_expression
- | ( function_call_header ) => function_call
- | primary_expression
- ;
-
-integer_expression
- : expression
- ;
-
-function_call
- : function_call_generic
- ;
-
-function_call_generic
- : function_call_header
- (
- (VOID)?
- | assignment_expression (COMMA assignment_expression)*
- )
- RIGHT_PAREN
- ;
-
-function_call_header
- : function_identifier LEFT_PAREN
- ;
-
-// NOTE: change compared to GLSL ES grammar, because constructor_identifier
-// has IDENTIFIER (=TYPE_NAME) as one of its arms.
-function_identifier
- : constructor_identifier
-// | IDENTIFIER
- ;
-
-// Grammar Note: Constructors look like functions, but lexical analysis recognized most of them as
-// keywords.
-//
-// TODO(kbr): do we need to register declared struct types in a dictionary
-// and look them up in order to be able to handle the TYPE_NAME constructor
-// identifier type?
-
-constructor_identifier
- : FLOAT
- | INT
- | BOOL
- | VEC2
- | VEC3
- | VEC4
- | BVEC2
- | BVEC3
- | BVEC4
- | IVEC2
- | IVEC3
- | IVEC4
- | MAT2
- | MAT3
- | MAT4
-// | TYPE_NAME
- | IDENTIFIER
- ;
-
-unary_expression
- : (INC_OP | DEC_OP | unary_operator)* postfix_expression
- ;
-
-// Grammar Note: No traditional style type casts.
-
-unary_operator
- : PLUS
- | DASH
- | BANG
-//| TILDE // reserved
- ;
-
-// Grammar Note: No '*' or '&' unary ops. Pointers are not supported.
-
-multiplicative_expression
- : unary_expression ((STAR | SLASH) unary_expression)*
-//| multiplicative_expression PERCENT unary_expression // reserved
- ;
-
-additive_expression
- : multiplicative_expression ((PLUS | DASH) multiplicative_expression)*
- ;
-
-shift_expression
- : additive_expression
-//| shift_expression LEFT_OP additive_expression // reserved
-//| shift_expression RIGHT_OP additive_expression // reserved
- ;
-
-relational_expression
- : shift_expression ((LEFT_ANGLE | RIGHT_ANGLE | LE_OP | GE_OP) shift_expression)*
- ;
-
-equality_expression
- : relational_expression ((EQ_OP | NE_OP) relational_expression)*
- ;
-
-and_expression
- : equality_expression
-//| and_expression AMPERSAND equality_expression // reserved
- ;
-
-exclusive_or_expression
- : and_expression
-//| exclusive_or_expression CARET and_expression // reserved
- ;
-
-inclusive_or_expression
- : exclusive_or_expression
-//| inclusive_or_expression VERTICAL_BAR exclusive_or_expression // reserved
- ;
-
-logical_and_expression
- : inclusive_or_expression (AND_OP inclusive_or_expression)*
- ;
-
-logical_xor_expression
- : logical_and_expression (XOR_OP logical_and_expression)*
- ;
-
-logical_or_expression
- : logical_xor_expression (OR_OP logical_xor_expression)*
- ;
-
-conditional_expression
- : logical_or_expression (QUESTION expression COLON assignment_expression)?
- ;
-
-assignment_expression
- : (unary_expression assignment_operator) => unary_expression assignment_operator assignment_expression
- | conditional_expression
- ;
-
-assignment_operator
- : EQUAL
- | MUL_ASSIGN
- | DIV_ASSIGN
-//| MOD_ASSIGN // reserved
- | ADD_ASSIGN
- | SUB_ASSIGN
-//| LEFT_ASSIGN // reserved
-//| RIGHT_ASSIGN // reserved
-//| AND_ASSIGN // reserved
-//| XOR_ASSIGN // reserved
-//| OR_ASSIGN // reserved
- ;
-
-expression
- : assignment_expression (COMMA assignment_expression)*
- ;
-
-constant_expression
- : conditional_expression
- ;
-
-declaration
- : (function_header) => function_prototype SEMICOLON
- | init_declarator_list SEMICOLON
- | PRECISION precision_qualifier type_specifier_no_prec SEMICOLON
- ;
-
-function_prototype
- : function_declarator RIGHT_PAREN
- ;
-
-function_declarator
- : function_header (parameter_declaration (COMMA parameter_declaration)* )?
- ;
-
-function_header
- : fully_specified_type IDENTIFIER LEFT_PAREN
- ;
-
-parameter_declaration
- : (type_qualifier)? (parameter_qualifier)?
- ( type_specifier
- // parameter_declarator
- (IDENTIFIER)?
- // parameter_type_specifier
- (LEFT_BRACKET constant_expression RIGHT_BRACKET)?
- )
- ;
-
-// NOTE: this originally had "empty" as one of the arms in the grammar
-
-parameter_qualifier
- : IN
- | OUT
- | INOUT
- ;
-
-init_declarator_list
- : single_declaration (init_declarator_list_1)*
- ;
-
-init_declarator_list_1
- : COMMA IDENTIFIER (init_declarator_list_2)?
- ;
-
-init_declarator_list_2
- : LEFT_BRACKET constant_expression RIGHT_BRACKET
- | EQUAL initializer
- ;
-
-single_declaration
- : fully_specified_type
- ( IDENTIFIER
- ( LEFT_BRACKET constant_expression RIGHT_BRACKET
- | EQUAL initializer
- ) ?
- ) ?
- | INVARIANT IDENTIFIER // Vertex only.
- ;
-
-// Grammar Note: No 'enum', or 'typedef'.
-
-fully_specified_type
- : type_specifier
- | type_qualifier type_specifier
- ;
-
-type_qualifier
- : CONST
- | ATTRIBUTE // Vertex only.
- | VARYING
- | INVARIANT VARYING
- | UNIFORM
- ;
-
-type_specifier
- : type_specifier_no_prec
- | precision_qualifier type_specifier_no_prec
- ;
-
-type_specifier_no_prec
- : VOID
- | FLOAT
- | INT
- | BOOL
- | VEC2
- | VEC3
- | VEC4
- | BVEC2
- | BVEC3
- | BVEC4
- | IVEC2
- | IVEC3
- | IVEC4
- | MAT2
- | MAT3
- | MAT4
- | SAMPLER2D
- | SAMPLERCUBE
- | struct_specifier
-// | TYPE_NAME
- | IDENTIFIER
- ;
-
-precision_qualifier
- : HIGH_PRECISION
- | MEDIUM_PRECISION
- | LOW_PRECISION
- ;
-
-struct_specifier
- : STRUCT (IDENTIFIER)? LEFT_BRACE struct_declaration_list RIGHT_BRACE
- ;
-
-struct_declaration_list
- : (struct_declaration)+
- ;
-
-struct_declaration
- : type_specifier struct_declarator_list SEMICOLON
- ;
-
-struct_declarator_list
- : struct_declarator (COMMA struct_declarator)*
- ;
-
-struct_declarator
- : IDENTIFIER (LEFT_BRACKET constant_expression RIGHT_BRACKET)?
- ;
-
-initializer
- : assignment_expression
- ;
-
-declaration_statement
- : declaration
- ;
-
-statement_no_new_scope
- : compound_statement_with_scope
- | simple_statement
- ;
-
-simple_statement
-options { backtrack=true; }
- : declaration_statement
- | expression_statement
- | selection_statement
- | iteration_statement
- | jump_statement
- ;
-
-compound_statement_with_scope
- : LEFT_BRACE (statement_list)? RIGHT_BRACE
- ;
-
-statement_with_scope
- : compound_statement_no_new_scope
- | simple_statement
- ;
-
-compound_statement_no_new_scope
- : LEFT_BRACE (statement_list)? RIGHT_BRACE
- ;
-
-statement_list
- : (statement_no_new_scope)+
- ;
-
-expression_statement
- : (expression)? SEMICOLON
- ;
-
-selection_statement
-options { backtrack=true; }
- : IF LEFT_PAREN expression RIGHT_PAREN statement_with_scope ELSE statement_with_scope
- | IF LEFT_PAREN expression RIGHT_PAREN statement_with_scope
- ;
-
-condition
- : expression
- | fully_specified_type IDENTIFIER EQUAL initializer
- ;
-
-iteration_statement
- : WHILE LEFT_PAREN condition RIGHT_PAREN statement_no_new_scope
- | DO statement_with_scope WHILE LEFT_PAREN expression RIGHT_PAREN SEMICOLON
- | FOR LEFT_PAREN for_init_statement for_rest_statement RIGHT_PAREN statement_no_new_scope
- ;
-
-for_init_statement
-options { backtrack=true; }
- : expression_statement
- | declaration_statement
- ;
-
-for_rest_statement
- : (condition)? SEMICOLON (expression)?
- ;
-
-jump_statement
- : CONTINUE SEMICOLON
- | BREAK SEMICOLON
- | RETURN (expression)? SEMICOLON
- | DISCARD SEMICOLON // Fragment shader only.
- ;
-
-external_declaration
- : (function_header) => function_definition
- | declaration
- ;
-
-function_definition
- : function_prototype compound_statement_no_new_scope
- ;
-
-// ----------------------------------------------------------------------
-// Keywords
-
-ATTRIBUTE : 'attribute';
-BOOL : 'bool';
-BREAK : 'break';
-BVEC2 : 'bvec2';
-BVEC3 : 'bvec3';
-BVEC4 : 'bvec4';
-CONST : 'const';
-CONTINUE : 'continue';
-DISCARD : 'discard';
-DO : 'do';
-ELSE : 'else';
-FALSE : 'false';
-FLOAT : 'float';
-FOR : 'for';
-HIGH_PRECISION : 'highp';
-IF : 'if';
-IN : 'in';
-INOUT : 'inout';
-INT : 'int';
-INVARIANT : 'invariant';
-IVEC2 : 'ivec2';
-IVEC3 : 'ivec3';
-IVEC4 : 'ivec4';
-LOW_PRECISION : 'lowp';
-MAT2 : 'mat2';
-MAT3 : 'mat3';
-MAT4 : 'mat4';
-MEDIUM_PRECISION : 'mediump';
-OUT : 'out';
-PRECISION : 'precision';
-RETURN : 'return';
-SAMPLER2D : 'sampler2D';
-SAMPLERCUBE : 'samplerCube';
-STRUCT : 'struct';
-TRUE : 'true';
-UNIFORM : 'uniform';
-VARYING : 'varying';
-VEC2 : 'vec2';
-VEC3 : 'vec3';
-VEC4 : 'vec4';
-VOID : 'void';
-WHILE : 'while';
-
-IDENTIFIER
- : ('a'..'z'|'A'..'Z'|'_')('a'..'z'|'A'..'Z'|'_'|'0'..'9')*
- ;
-
-/*
-// TODO(kbr): it isn't clear whether we need to support the TYPE_NAME
-// token type; that may only be needed if typedef is supported
-TYPE_NAME
- : IDENTIFIER
- ;
-*/
-
-// NOTE difference in handling of leading minus sign compared to HLSL
-// grammar
-
-fragment EXPONENT_PART : ('e'|'E') (PLUS | DASH)? ('0'..'9')+ ;
-
-FLOATCONSTANT
- : ('0'..'9')+ '.' ('0'..'9')* (EXPONENT_PART)?
- | '.' ('0'..'9')+ (EXPONENT_PART)?
- ;
-
-fragment DECIMAL_CONSTANT
- : ('1'..'9')('0'..'9')*
- ;
-
-fragment OCTAL_CONSTANT
- : '0' ('0'..'7')*
- ;
-
-fragment HEXADECIMAL_CONSTANT
- : '0' ('x'|'X') HEXDIGIT+
- ;
-
-fragment HEXDIGIT
- : ('0'..'9'|'a'..'f'|'A'..'F')
- ;
-
-INTCONSTANT
- : DECIMAL_CONSTANT
- | OCTAL_CONSTANT
- | HEXADECIMAL_CONSTANT
- ;
-
-fragment BOOLCONSTANT
- : TRUE
- | FALSE
- ;
-
-// TODO(kbr): this needs much more work
-field_selection
- : IDENTIFIER
- ;
-
-//LEFT_OP : '<<'; - reserved
-//RIGHT_OP : '>>'; - reserved
-
-INC_OP : '++';
-DEC_OP : '--';
-LE_OP : '<=';
-GE_OP : '>=';
-EQ_OP : '==';
-NE_OP : '!=';
-
-AND_OP : '&&';
-OR_OP : '||';
-XOR_OP : '^^';
-MUL_ASSIGN : '*=';
-DIV_ASSIGN : '/=';
-ADD_ASSIGN : '+=';
-MOD_ASSIGN : '%=';
-// LEFT_ASSIGN : '<<='; - reserved
-// RIGHT_ASSIGN : '>>='; - reserved
-// AND_ASSIGN : '&='; - reserved
-// XOR_ASSIGN : '^='; - reserved
-// OR_ASSIGN : '|='; - reserved
-SUB_ASSIGN : '-=';
-
-LEFT_PAREN : '(';
-RIGHT_PAREN : ')';
-LEFT_BRACKET : '[';
-RIGHT_BRACKET : ']';
-LEFT_BRACE : '{';
-RIGHT_BRACE : '}';
-DOT : '.';
-
-COMMA : ',';
-COLON : ':';
-EQUAL : '=';
-SEMICOLON : ';';
-BANG : '!';
-DASH : '-';
-TILDE : '~';
-PLUS : '+';
-STAR : '*';
-SLASH : '/';
-PERCENT : '%';
-
-LEFT_ANGLE : '<';
-RIGHT_ANGLE : '>';
-VERTICAL_BAR : '|';
-CARET : '^';
-AMPERSAND : '&';
-QUESTION : '?';
-
-// ----------------------------------------------------------------------
-// skipped elements
-
-WHITESPACE
- : ( ' ' | '\t' | '\f' | '\r' | '\n' )
- { $channel = HIDDEN; }
- ;
-
-COMMENT
- : '//' (~('\n'|'\r'))*
- { $channel = HIDDEN; }
- ;
-
-MULTILINE_COMMENT
- : '/*' ( options {greedy=false;} : . )* '*/'
- { $channel = HIDDEN; }
- ;
-
-// ----------------------------------------------------------------------
-// Keywords reserved for future use
-
-//RESERVED_KEYWORDS
-// : 'asm'
-// | 'cast'
-// | 'class'
-// | 'default'
-// | 'double'
-// | 'dvec2'
-// | 'dvec3'
-// | 'dvec4'
-// | 'enum'
-// | 'extern'
-// | 'external'
-// | 'fixed'
-// | 'flat'
-// | 'fvec2'
-// | 'fvec3'
-// | 'fvec4'
-// | 'goto'
-// | 'half'
-// | 'hvec2'
-// | 'hvec3'
-// | 'hvec4'
-// | 'inline'
-// | 'input'
-// | 'interface'
-// | 'long'
-// | 'namespace'
-// | 'noinline'
-// | 'output'
-// | 'packed'
-// | 'public'
-// | 'sampler1D'
-// | 'sampler1DShadow'
-// | 'sampler2DRect'
-// | 'sampler2DRectShadow'
-// | 'sampler2DShadow'
-// | 'sampler3D'
-// | 'sampler3DRect'
-// | 'short'
-// | 'sizeof'
-// | 'static'
-// | 'superp'
-// | 'switch'
-// | 'template'
-// | 'this'
-// | 'typedef'
-// | 'union'
-// | 'unsigned'
-// | 'using'
-// | 'volatile'
-// ;
diff --git a/o3d/compiler/glsl_validator/glsl_es/GLSL_ES.l b/o3d/compiler/glsl_validator/glsl_es/GLSL_ES.l
deleted file mode 100644
index 07ab141..0000000
--- a/o3d/compiler/glsl_validator/glsl_es/GLSL_ES.l
+++ /dev/null
@@ -1,221 +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 <stdio.h>
-#define YYSTYPE char *
-#include "GLSL_ES.tab.h"
-%}
-
-EXPONENT_PART [eE][+-]?[0-9]+
-
-DECIMAL_CONSTANT [1-9][0-9]*
-HEXADECIMAL_CONSTANT 0[xX][0-9a-fA-F]+
-OCTAL_CONSTANT 0[0-7]*
-
-%s IN_COMMENT
-%%
-
- /**********************************************************************/
- /* Keywords */
- /**/
-
-attribute return ATTRIBUTE;
-bool return BOOL;
-break return BREAK;
-bvec2 return BVEC2;
-bvec3 return BVEC3;
-bvec4 return BVEC4;
-const return CONST;
-continue return CONTINUE;
-discard return DISCARD;
-do return DO;
-else return ELSE;
-false return FALSE;
-float return FLOAT;
-for return FOR;
-highp return HIGH_PRECISION;
-if return IF;
-in return IN;
-inout return INOUT;
-int return INT;
-invariant return INVARIANT;
-ivec2 return IVEC2;
-ivec3 return IVEC3;
-ivec4 return IVEC4;
-lowp return LOW_PRECISION;
-mat2 return MAT2;
-mat3 return MAT3;
-mat4 return MAT4;
-mediump return MEDIUM_PRECISION;
-out return OUT;
-precision return PRECISION;
-return return RETURN;
-sampler2D return SAMPLER2D;
-samplerCube return SAMPLERCUBE;
-struct return STRUCT;
-true return TRUE;
-uniform return UNIFORM;
-varying return VARYING;
-vec2 return VEC2;
-vec3 return VEC3;
-vec4 return VEC4;
-void return VOID;
-while return WHILE;
-
- /**********************************************************************/
- /* Basic tokens and operators */
- /**/
-
-\/\/.* /* ignore single-line comments */;
-
- /* Ignore C-style multi-line comments */
-<INITIAL>{
-"/*" BEGIN(IN_COMMENT);
-}
-<IN_COMMENT>{
-"*/" BEGIN(INITIAL);
-[^*\n]+ // eat comment in chunks
-"*" // eat the lone star
-\n yylineno++;
-}
-
-DECIMAL_CONSTANT |
-HEXADECIMAL_CONSTANT |
-OCTAL_CONSTANT yylval=strdup(yytext); return INTCONSTANT;
-
-[0-9]+\.[0-9]*{EXPONENT_PART}? |
-\.[0-9]+{EXPONENT_PART}? yylval=strdup(yytext); return FLOATCONSTANT;
-
-\n /* ignore EOL */;
-[ \t\r\f]+ /* ignore whitespace */;
-
-\+\+ return INC_OP;
-\-\- return DEC_OP;
-\<= return LE_OP;
-\>= return GE_OP;
-== return EQ_OP;
-!= return NE_OP;
-
-&& return AND_OP;
-\|\| return OR_OP;
-\^\^ return XOR_OP;
-\*= return MUL_ASSIGN;
-\/= return DIV_ASSIGN;
-\+= return ADD_ASSIGN;
-\%= return MOD_ASSIGN;
--= return SUB_ASSIGN;
-
-\( return LEFT_PAREN;
-\) return RIGHT_PAREN;
-\[ return LEFT_BRACKET;
-\] return RIGHT_BRACKET;
-\{ return LEFT_BRACE;
-\} return RIGHT_BRACE;
-\. return DOT;
-
-, return COMMA;
-: return COLON;
-; return SEMICOLON;
-= return EQUAL;
-! return BANG;
-\- return DASH;
-~ return TILDE;
-\+ return PLUS;
-\* return STAR;
-\/ return SLASH;
-\% return PERCENT;
-
-\< return LEFT_ANGLE;
-\> return RIGHT_ANGLE;
-\| return VERTICAL_BAR;
-\^ return CARET;
-& return AMPERSAND;
-\? return QUESTION;
-
- /* Catch-all for user identifiers */
-[a-zA-Z_][a-zA-Z0-9_]* yylval=strdup(yytext); return IDENTIFIER;
-
- /**********************************************************************/
- /* Keywords reserved for future use */
- /**/
-
- /**************************/
- /* asm | */
- /* cast | */
- /* class | */
- /* default | */
- /* double | */
- /* dvec2 | */
- /* dvec3 | */
- /* dvec4 | */
- /* enum | */
- /* extern | */
- /* external | */
- /* fixed | */
- /* flat | */
- /* fvec2 | */
- /* fvec3 | */
- /* fvec4 | */
- /* goto | */
- /* half | */
- /* hvec2 | */
- /* hvec3 | */
- /* hvec4 | */
- /* inline | */
- /* input | */
- /* interface | */
- /* long | */
- /* namespace | */
- /* noinline | */
- /* output | */
- /* packed | */
- /* public | */
- /* sampler1D | */
- /* sampler1DShadow | */
- /* sampler2DRect | */
- /* sampler2DRectShadow | */
- /* sampler2DShadow | */
- /* sampler3D | */
- /* sampler3DRect | */
- /* short | */
- /* sizeof | */
- /* static | */
- /* superp | */
- /* switch | */
- /* template | */
- /* this | */
- /* typedef | */
- /* union | */
- /* unsigned | */
- /* using | */
- /* volatile | */
-%%
diff --git a/o3d/compiler/glsl_validator/glsl_es/GLSL_ES.y b/o3d/compiler/glsl_validator/glsl_es/GLSL_ES.y
deleted file mode 100644
index 10c9879..0000000
--- a/o3d/compiler/glsl_validator/glsl_es/GLSL_ES.y
+++ /dev/null
@@ -1,607 +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 <stdio.h>
-#include <string.h>
-
-#define YYSTYPE char *
-
-int yydebug=0;
-
-void yyerror(const char *str)
-{
- fprintf(stderr,"error: %s\n",str);
-}
-
-int yywrap()
-{
- return 1;
-}
-
-main()
-{
- yyparse();
-}
-
-%}
-
-%token
- INTCONSTANT FLOATCONSTANT IDENTIFIER
-
- INC_OP DEC_OP LE_OP GE_OP EQ_OP NE_OP AND_OP OR_OP XOR_OP
-
- MUL_ASSIGN DIV_ASSIGN ADD_ASSIGN MOD_ASSIGN SUB_ASSIGN
-
- LEFT_PAREN RIGHT_PAREN LEFT_BRACKET RIGHT_BRACKET LEFT_BRACE RIGHT_BRACE DOT
-
- COMMA COLON SEMICOLON EQUAL BANG DASH TILDE PLUS STAR SLASH PERCENT
-
- LEFT_ANGLE RIGHT_ANGLE VERTICAL_BAR CARET AMPERSAND QUESTION
-
- ATTRIBUTE BOOL BREAK BVEC2 BVEC3
- BVEC4 CONST CONTINUE DISCARD DO
- ELSE FALSE FLOAT FOR HIGH_PRECISION
- IF IN INOUT INT INVARIANT
- IVEC2 IVEC3 IVEC4 LOW_PRECISION MAT2
- MAT3 MAT4 MEDIUM_PRECISION OUT PRECISION
- RETURN SAMPLER2D SAMPLERCUBE STRUCT TRUE
- UNIFORM VARYING VEC2 VEC3 VEC4
- VOID WHILE
-
-%%
-
-/* Main entry point */
-translation_unit
- : external_declaration
- | translation_unit external_declaration
-
-/* TODO(kbr): this requires much more work */
-FIELD_SELECTION
- : IDENTIFIER
- ;
-
-variable_identifier
- : IDENTIFIER
- ;
-
-primary_expression
- : variable_identifier
- | INTCONSTANT
- | FLOATCONSTANT
- | TRUE | FALSE
- | primary_expression_1
- ;
-
-primary_expression_1
- : LEFT_PAREN expression RIGHT_PAREN
- ;
-
-postfix_expression
- : postfix_expression_1
- | postfix_expression postfix_expression_2
- ;
-
-postfix_expression_1
- : primary_expression
- | function_call
- ;
-
-postfix_expression_2
- : LEFT_BRACKET integer_expression RIGHT_BRACKET
- | DOT FIELD_SELECTION
- | INC_OP
- | DEC_OP
- ;
-
-integer_expression
- : expression
- ;
-
-function_call
- : function_call_generic
- ;
-
-function_call_generic
- : function_call_header_with_parameters RIGHT_PAREN
- | function_call_header_no_parameters RIGHT_PAREN
- ;
-
-function_call_header_no_parameters
- : function_call_header VOID
- | function_call_header
- ;
-
-function_call_header_with_parameters
- : function_call_header assignment_expression
- | function_call_header_with_parameters function_call_header_with_parameters_1
- ;
-
-function_call_header_with_parameters_1
- : COMMA assignment_expression
- ;
-
-function_call_header
- : function_identifier LEFT_PAREN
- ;
-
-// NOTE: change compared to GLSL ES grammar, because constructor_identifier
-// has IDENTIFIER (=TYPE_NAME) as one of its arms.
-function_identifier
- : constructor_identifier
- | IDENTIFIER
- ;
-
-// TODO(kbr): do we need to register declared struct types in a dictionary
-// and look them up in order to be able to handle the TYPE_NAME constructor
-// identifier type?
-
-constructor_identifier
- : FLOAT
- | INT
- | BOOL
- | VEC2
- | VEC3
- | VEC4
- | BVEC2
- | BVEC3
- | BVEC4
- | IVEC2
- | IVEC3
- | IVEC4
- | MAT2
- | MAT3
- | MAT4
-// | TYPE_NAME
-// | IDENTIFIER
- ;
-
-unary_expression
- : postfix_expression
- | INC_OP unary_expression
- | DEC_OP unary_expression
- | unary_operator unary_expression
- ;
-
-/* Grammar Note: No traditional style type casts. */
-
-unary_operator
- : PLUS
- | DASH
- | BANG
-/*| TILDE // reserved */
- ;
-
-/* Grammar Note: No '*' or '&' unary ops. Pointers are not supported. */
-
-multiplicative_expression
- : unary_expression
- | multiplicative_expression multiplicative_expression_1
- ;
-
-multiplicative_expression_1
- : STAR unary_expression
- | SLASH unary_expression
-/*| PERCENT unary_expression */
- ;
-
-additive_expression
- : multiplicative_expression
- | additive_expression additive_expression_1
- ;
-
-additive_expression_1
- : PLUS multiplicative_expression
- | DASH multiplicative_expression
- ;
-
-shift_expression
- : additive_expression
-/*| shift_expression LEFT_OP additive_expression // reserved */
-/*| shift_expression RIGHT_OP additive_expression // reserved */
- ;
-
-relational_expression
- : shift_expression
- | relational_expression relational_expression_1
- ;
-
-relational_expression_1
- : LEFT_ANGLE shift_expression
- | RIGHT_ANGLE shift_expression
- | LE_OP shift_expression
- | GE_OP shift_expression
- ;
-
-equality_expression
- : relational_expression
- | equality_expression equality_expression_1
- ;
-
-equality_expression_1
- : EQ_OP relational_expression
- | NE_OP relational_expression
- ;
-
-and_expression
- : equality_expression
-/*| and_expression AMPERSAND equality_expression // reserved */
- ;
-
-exclusive_or_expression
- : and_expression
-/*| exclusive_or_expression CARET and_expression // reserved */
- ;
-
-inclusive_or_expression
- : exclusive_or_expression
-/*| inclusive_or_expression VERTICAL_BAR exclusive_or_expression // reserved */
- ;
-
-logical_and_expression
- : inclusive_or_expression
- | logical_and_expression logical_and_expression_1
- ;
-
-logical_and_expression_1
- : AND_OP inclusive_or_expression
- ;
-
-logical_xor_expression
- : logical_and_expression
- | logical_xor_expression logical_xor_expression_1
- ;
-
-logical_xor_expression_1
- : XOR_OP logical_and_expression
- ;
-
-logical_or_expression
- : logical_xor_expression
- | logical_or_expression logical_or_expression_1
- ;
-
-logical_or_expression_1
- : OR_OP logical_xor_expression
- ;
-
-conditional_expression
- : logical_or_expression
- | logical_or_expression conditional_expression_1
- ;
-
-/* NOTE (TODO(kbr)): difference between Mesa's grammar and GLSL ES spec;
- Mesa uses conditional_expression after the colon, GLSL ES uses assignment_expression */
-conditional_expression_1
- : QUESTION expression COLON assignment_expression
- ;
-
-assignment_expression
- : conditional_expression
- | unary_expression assignment_operator assignment_expression
- ;
-
-assignment_operator
- : EQUAL
- | MUL_ASSIGN
- | DIV_ASSIGN
-/*| MOD_ASSIGN // reserved */
- | ADD_ASSIGN
- | SUB_ASSIGN
-/*| LEFT_ASSIGN // reserved */
-/*| RIGHT_ASSIGN // reserved */
-/*| AND_ASSIGN // reserved */
-/*| XOR_ASSIGN // reserved */
-/*| OR_ASSIGN // reserved */
- ;
-
-expression
- : assignment_expression
- | expression expression_1
- ;
-
-expression_1
- : COMMA assignment_expression
- ;
-
-constant_expression
- : conditional_expression
- ;
-
-declaration
- : function_prototype SEMICOLON
- | init_declarator_list SEMICOLON
- | PRECISION precision_qualifier type_specifier_no_prec SEMICOLON
- ;
-
-function_prototype
- : function_declarator RIGHT_PAREN
- ;
-
-function_declarator
- : function_header
- | function_header_with_parameters
- ;
-
-function_header_with_parameters
- : function_header parameter_declaration
- | function_header_with_parameters function_header_with_parameters_1
- ;
-
-function_header_with_parameters_1
- : COMMA parameter_declaration
- ;
-
-/* NOTE: Mesa grammar differs substantially in handling of types ("space" vs. "non-space") */
-function_header
- : fully_specified_type IDENTIFIER LEFT_PAREN
- ;
-
-parameter_declarator
- : type_specifier IDENTIFIER
- | type_specifier IDENTIFIER LEFT_BRACKET constant_expression RIGHT_BRACKET
- ;
-
-/* NOTE: difference between both Mesa and ANTLR grammars */
-parameter_declaration
- : type_qualifier parameter_qualifier parameter_declarator
- | parameter_qualifier parameter_declarator
- | type_qualifier parameter_qualifier parameter_type_specifier
- | parameter_qualifier parameter_type_specifier
- ;
-
-/* NOTE empty arm at beginning */
-parameter_qualifier
- :
- | IN
- | OUT
- | INOUT
- ;
-
-parameter_type_specifier
- : type_specifier
- | type_specifier LEFT_BRACKET constant_expression RIGHT_BRACKET
- ;
-
-init_declarator_list
- : single_declaration
- | single_declaration init_declarator_list_1
- ;
-
-init_declarator_list_1
- : COMMA IDENTIFIER init_declarator_list_2
- ;
-
-init_declarator_list_2
- : init_declarator_list_3
- | init_declarator_list_4
- | /* empty */
- ;
-
-init_declarator_list_3
- : LEFT_BRACKET constant_expression RIGHT_BRACKET
- ;
-
-init_declarator_list_4
- : EQUAL initializer
- ;
-
-/* NOTE: significant differences between this formulation and Mesa's */
-single_declaration
- : fully_specified_type
- | fully_specified_type IDENTIFIER
- | fully_specified_type IDENTIFIER LEFT_BRACKET constant_expression RIGHT_BRACKET
- | fully_specified_type IDENTIFIER EQUAL initializer
- | INVARIANT IDENTIFIER // Vertex only.
- ;
-
-/* Grammar Note: No 'enum', or 'typedef'. */
-
-fully_specified_type
- : type_specifier
- | type_qualifier type_specifier
- ;
-
-type_qualifier
- : CONST
- | ATTRIBUTE // Vertex only.
- | VARYING
- | INVARIANT VARYING
- | UNIFORM
- ;
-
-type_specifier
- : type_specifier_no_prec
- | precision_qualifier type_specifier_no_prec
- ;
-
-type_specifier_no_prec
- : VOID
- | FLOAT
- | INT
- | BOOL
- | VEC2
- | VEC3
- | VEC4
- | BVEC2
- | BVEC3
- | BVEC4
- | IVEC2
- | IVEC3
- | IVEC4
- | MAT2
- | MAT3
- | MAT4
- | SAMPLER2D
- | SAMPLERCUBE
- | struct_specifier
-// | TYPE_NAME
-// | IDENTIFIER
- ;
-
-precision_qualifier
- : HIGH_PRECISION
- | MEDIUM_PRECISION
- | LOW_PRECISION
- ;
-
-struct_specifier
- : STRUCT IDENTIFIER LEFT_BRACE struct_declaration_list RIGHT_BRACE
- | STRUCT LEFT_BRACE struct_declaration_list RIGHT_BRACE
- ;
-
-struct_declaration_list
- : struct_declaration
- | struct_declaration struct_declaration_list_1
- ;
-
-struct_declaration_list_1
- : struct_declaration struct_declaration_list
- ;
-
-struct_declaration
- : type_specifier struct_declarator_list SEMICOLON
- ;
-
-/* NOTE difference with spec grammar in where recursion occurs */
-struct_declarator_list
- : struct_declarator
- | struct_declarator struct_declarator_list_1
- ;
-
-/* NOTE difference with Mesa grammar */
-struct_declarator_list_1
- : COMMA struct_declarator_list
- ;
-
-struct_declarator
- : IDENTIFIER
- | IDENTIFIER LEFT_BRACKET constant_expression RIGHT_BRACKET
- ;
-
-initializer
- : assignment_expression
- ;
-
-declaration_statement
- : declaration
- ;
-
-statement_no_new_scope
- : compound_statement_with_scope
- | simple_statement
- ;
-
-simple_statement
- : declaration_statement
- | expression_statement
- | selection_statement
- | iteration_statement
- | jump_statement
- ;
-
-compound_statement_with_scope
- : LEFT_BRACE RIGHT_BRACE
- | LEFT_BRACE statement_list RIGHT_BRACE
- ;
-
-statement_with_scope
- : compound_statement_no_new_scope
- | simple_statement
- ;
-
-compound_statement_no_new_scope
- : LEFT_BRACE RIGHT_BRACE
- | LEFT_BRACE statement_list RIGHT_BRACE
- ;
-
-/* TODO(kbr): may need refactoring */
-statement_list
- : statement_no_new_scope
- | statement_list statement_no_new_scope
- ;
-
-expression_statement
- : SEMICOLON
- | expression SEMICOLON
- ;
-
-selection_statement
- : IF LEFT_PAREN expression RIGHT_PAREN selection_rest_statement
- ;
-
-selection_rest_statement
- : statement_with_scope ELSE statement_with_scope
- | statement_with_scope
- ;
-
-condition
- : expression
- | fully_specified_type IDENTIFIER EQUAL initializer
- ;
-
-iteration_statement
- : WHILE LEFT_PAREN condition RIGHT_PAREN statement_no_new_scope
- | DO statement_with_scope WHILE LEFT_PAREN expression RIGHT_PAREN SEMICOLON
- | FOR LEFT_PAREN for_init_statement for_rest_statement RIGHT_PAREN statement_no_new_scope
- ;
-
-for_init_statement
- : expression_statement
- | declaration_statement
- ;
-
-conditionopt
- : condition
- | /* empty */
- ;
-
-for_rest_statement
- : conditionopt SEMICOLON
- | conditionopt SEMICOLON expression
- ;
-
-jump_statement
- : CONTINUE SEMICOLON
- | BREAK SEMICOLON
- | RETURN SEMICOLON
- | RETURN expression SEMICOLON
- | DISCARD SEMICOLON // Fragment shader only.
- ;
-
-external_declaration
- : function_definition
- | declaration
- ;
-
-function_definition
- : function_prototype compound_statement_no_new_scope
- ;
diff --git a/o3d/compiler/glsl_validator/shaders/ambient.frag b/o3d/compiler/glsl_validator/shaders/ambient.frag
deleted file mode 100644
index 1e46e4d..0000000
--- a/o3d/compiler/glsl_validator/shaders/ambient.frag
+++ /dev/null
@@ -1,10 +0,0 @@
-// Modified from shader at
-// http://nehe.gamedev.net/data/articles/article.asp?article=21
-
-uniform vec4 g_Color;
-
-void main()
-{
- // Set each pixel to a constant color
- gl_FragColor = g_Color;
-}
diff --git a/o3d/compiler/glsl_validator/shaders/ambient.vert b/o3d/compiler/glsl_validator/shaders/ambient.vert
deleted file mode 100644
index 88a755e..0000000
--- a/o3d/compiler/glsl_validator/shaders/ambient.vert
+++ /dev/null
@@ -1,11 +0,0 @@
-// Modified from shader at
-// http://nehe.gamedev.net/data/articles/article.asp?article=21
-
-uniform mat4 g_ModelViewProjectionMatrix;
-
-attribute vec4 g_Vertex;
-
-void main()
-{
- gl_Position = g_ModelViewProjectionMatrix * g_Vertex;
-}
diff --git a/o3d/compiler/glsl_validator/shaders/diffuse.frag b/o3d/compiler/glsl_validator/shaders/diffuse.frag
deleted file mode 100644
index c3c91f9..0000000
--- a/o3d/compiler/glsl_validator/shaders/diffuse.frag
+++ /dev/null
@@ -1,22 +0,0 @@
-// Modified from shader at
-// http://nehe.gamedev.net/data/articles/article.asp?article=21
-
-varying vec3 normal;
-varying vec3 vertex_to_light_vector;
-
-void main()
-{
- // Defining The Material Colors
- const vec4 AMBIENT_COLOR = vec4(0.1, 0.0, 0.0, 1.0);
- const vec4 DIFFUSE_COLOR = vec4(1.0, 0.0, 0.0, 1.0);
-
- // Scaling The Input Vector To Length 1
- vec3 normalized_normal = normalize(normal);
- vec3 normalized_vertex_to_light_vector = normalize(vertex_to_light_vector);
-
- // Calculating The Diffuse Term And Clamping It To [0;1]
- float diffuseTerm = clamp(dot(normal, vertex_to_light_vector), 0.0, 1.0);
-
- // Calculating The Final Color
- gl_FragColor = AMBIENT_COLOR + DIFFUSE_COLOR * diffuseTerm;
-}
diff --git a/o3d/compiler/glsl_validator/shaders/diffuse.vert b/o3d/compiler/glsl_validator/shaders/diffuse.vert
deleted file mode 100644
index e155901..0000000
--- a/o3d/compiler/glsl_validator/shaders/diffuse.vert
+++ /dev/null
@@ -1,28 +0,0 @@
-// Modified from shader at
-// http://nehe.gamedev.net/data/articles/article.asp?article=21
-
-uniform mat4 g_ModelViewProjectionMatrix;
-uniform mat4 g_ModelViewMatrix;
-uniform mat4 g_NormalMatrix;
-uniform vec4 g_LightSource0Position;
-
-attribute vec4 g_Vertex;
-attribute vec4 g_Normal;
-
-varying vec3 normal;
-varying vec3 vertex_to_light_vector;
-
-void main()
-{
- // Transforming The Vertex
- gl_Position = g_ModelViewProjectionMatrix * g_Vertex;
-
- // Transforming The Normal To ModelView-Space
- normal = vec3(g_NormalMatrix * g_Normal);
-
- // Transforming The Vertex Position To ModelView-Space
- vec4 vertex_in_modelview_space = g_ModelViewMatrix * g_Vertex;
-
- // Calculating The Vector From The Vertex Position To The Light Position
- vertex_to_light_vector = vec3(g_LightSource0Position - vertex_in_modelview_space);
-}
diff --git a/o3d/compiler/glsl_validator/shaders/many-planets-deep.frag b/o3d/compiler/glsl_validator/shaders/many-planets-deep.frag
deleted file mode 100644
index 64bf5a4..0000000
--- a/o3d/compiler/glsl_validator/shaders/many-planets-deep.frag
+++ /dev/null
@@ -1,11 +0,0 @@
-uniform sampler2D sampler2d;
-
-varying float v_Dot;
-varying vec2 v_texCoord;
-
-void main()
-{
- vec4 color = texture2D(sampler2d,v_texCoord);
- color += vec4(0.1,0.1,0.1,1);
- gl_FragColor = vec4(color.xyz * v_Dot, color.a);
-}
diff --git a/o3d/compiler/glsl_validator/shaders/many-planets-deep.vert b/o3d/compiler/glsl_validator/shaders/many-planets-deep.vert
deleted file mode 100644
index 051a226..0000000
--- a/o3d/compiler/glsl_validator/shaders/many-planets-deep.vert
+++ /dev/null
@@ -1,19 +0,0 @@
-uniform mat4 u_modelViewMatrix;
-uniform mat4 u_modelViewProjMatrix;
-uniform mat4 u_normalMatrix;
-uniform vec3 lightDir;
-
-attribute vec3 vNormal;
-attribute vec4 vTexCoord;
-attribute vec4 vPosition;
-
-varying float v_Dot;
-varying vec2 v_texCoord;
-
-void main()
-{
- gl_Position = u_modelViewProjMatrix * vPosition;
- v_texCoord = vTexCoord.st;
- vec4 transNormal = u_normalMatrix * vec4(vNormal,1);
- v_Dot = max(dot(transNormal.xyz, lightDir), 0.0);
-}
diff --git a/o3d/compiler/glsl_validator/shaders/nvidia-vertex-buffer-object.frag b/o3d/compiler/glsl_validator/shaders/nvidia-vertex-buffer-object.frag
deleted file mode 100644
index 98e8b27..0000000
--- a/o3d/compiler/glsl_validator/shaders/nvidia-vertex-buffer-object.frag
+++ /dev/null
@@ -1,5 +0,0 @@
-varying vec4 v_color;
-
-void main() {
- gl_FragColor = v_color;
-}
diff --git a/o3d/compiler/glsl_validator/shaders/nvidia-vertex-buffer-object.vert b/o3d/compiler/glsl_validator/shaders/nvidia-vertex-buffer-object.vert
deleted file mode 100644
index 60fc084..0000000
--- a/o3d/compiler/glsl_validator/shaders/nvidia-vertex-buffer-object.vert
+++ /dev/null
@@ -1,48 +0,0 @@
-// Per-vertex phong shader
-uniform mat4 worldViewProjection;
-uniform vec3 lightWorldPos;
-uniform vec4 lightColor;
-
-uniform mat4 world;
-uniform mat4 viewInverse;
-uniform mat4 worldInverseTranspose;
-
-uniform vec4 emissiveColor;
-uniform vec4 ambientColor;
-uniform vec4 diffuseColor;
-uniform vec4 specularColor;
-uniform float shininess;
-uniform float specularFactor;
-
-attribute vec3 g_Position;
-attribute vec3 g_Normal;
-
-varying vec4 v_color;
-
-vec4 lit(float n_dot_l, float n_dot_h, float m) {
- return vec4(1.,
- clamp(n_dot_l, 0., 1.),
- // FIXME: approximation to
- // (n_dot_l < 0) || (n_dot_h < 0)
- pow(clamp(n_dot_h, 0., 1.), m),
- 1.);
-}
-
-void main() {
- vec4 position = vec4(g_Position, 1.);
- vec4 worldPosition = world * position;
- vec3 normal = normalize((worldInverseTranspose *
- vec4(g_Normal, 0.)).xyz);
- vec3 surfaceToLight = normalize(lightWorldPos - worldPosition.xyz);
- vec3 surfaceToView = normalize((viewInverse[3] - worldPosition).xyz);
- vec3 halfVector = normalize(surfaceToLight + surfaceToView);
- vec4 litR = lit(dot(normal, surfaceToLight),
- dot(normal, halfVector), shininess);
- v_color =
- vec4((emissiveColor +
- lightColor * (ambientColor * litR.x +
- diffuseColor * litR.y +
- specularColor * litR.z * specularFactor)).rgb,
- diffuseColor.a);
- gl_Position = worldViewProjection * position;
-}
diff --git a/o3d/compiler/glsl_validator/shaders/particles-2d.vert b/o3d/compiler/glsl_validator/shaders/particles-2d.vert
deleted file mode 100644
index 5197941..0000000
--- a/o3d/compiler/glsl_validator/shaders/particles-2d.vert
+++ /dev/null
@@ -1,69 +0,0 @@
-uniform mat4 viewProjection;
-uniform mat4 world;
-uniform mat4 viewInverse;
-uniform vec3 worldVelocity;
-uniform vec3 worldAcceleration;
-uniform float timeRange;
-uniform float time;
-uniform float timeOffset;
-uniform float frameDuration;
-uniform float numFrames;
-
-// Incoming vertex attributes
-attribute vec4 uvLifeTimeFrameStart; // uv, lifeTime, frameStart
-attribute vec4 positionStartTime; // position.xyz, startTime
-attribute vec4 velocityStartSize; // velocity.xyz, startSize
-attribute vec4 accelerationEndSize; // acceleration.xyz, endSize
-attribute vec4 spinStartSpinSpeed; // spinStart.x, spinSpeed.y
-attribute vec4 colorMult; // multiplies color and ramp textures
-
-// Outgoing variables to fragment shader
-varying vec2 outputTexcoord;
-varying float outputPercentLife;
-varying vec4 outputColorMult;
-
-void main() {
- vec2 uv = uvLifeTimeFrameStart.xy;
- float lifeTime = uvLifeTimeFrameStart.z;
- float frameStart = uvLifeTimeFrameStart.w;
- vec3 position = positionStartTime.xyz;
- float startTime = positionStartTime.w;
- vec3 velocity = (world * vec4(velocityStartSize.xyz,
- 0.)).xyz + worldVelocity;
- float startSize = velocityStartSize.w;
- vec3 acceleration = (world * vec4(accelerationEndSize.xyz,
- 0)).xyz + worldAcceleration;
- float endSize = accelerationEndSize.w;
- float spinStart = spinStartSpinSpeed.x;
- float spinSpeed = spinStartSpinSpeed.y;
-
- float localTime = mod((time - timeOffset - startTime), timeRange);
- float percentLife = localTime / lifeTime;
-
- float frame = mod(floor(localTime / frameDuration + frameStart),
- numFrames);
- float uOffset = frame / numFrames;
- float u = uOffset + (uv.x + 0.5) * (1. / numFrames);
-
- outputTexcoord = vec2(u, uv.y + 0.5);
- outputColorMult = colorMult;
-
- vec3 basisX = viewInverse[0].xyz;
- vec3 basisZ = viewInverse[1].xyz;
-
- float size = mix(startSize, endSize, percentLife);
- size = (percentLife < 0. || percentLife > 1.) ? 0. : size;
- float s = sin(spinStart + spinSpeed * localTime);
- float c = cos(spinStart + spinSpeed * localTime);
-
- vec2 rotatedPoint = vec2(uv.x * c + uv.y * s,
- -uv.x * s + uv.y * c);
- vec3 localPosition = vec3(basisX * rotatedPoint.x +
- basisZ * rotatedPoint.y) * size +
- velocity * localTime +
- acceleration * localTime * localTime +
- position;
-
- outputPercentLife = percentLife;
- gl_Position = viewProjection * vec4(localPosition + world[3].xyz, 1.);
-}
diff --git a/o3d/compiler/glsl_validator/shaders/particles-3d.vert b/o3d/compiler/glsl_validator/shaders/particles-3d.vert
deleted file mode 100644
index 7f09de7..0000000
--- a/o3d/compiler/glsl_validator/shaders/particles-3d.vert
+++ /dev/null
@@ -1,87 +0,0 @@
-uniform mat4 worldViewProjection;
-uniform mat4 world;
-uniform vec3 worldVelocity;
-uniform vec3 worldAcceleration;
-uniform float timeRange;
-uniform float time;
-uniform float timeOffset;
-uniform float frameDuration;
-uniform float numFrames;
-
-// Incoming vertex attributes
-attribute vec4 uvLifeTimeFrameStart; // uv, lifeTime, frameStart
-attribute vec4 positionStartTime; // position.xyz, startTime
-attribute vec4 velocityStartSize; // velocity.xyz, startSize
-attribute vec4 accelerationEndSize; // acceleration.xyz, endSize
-attribute vec4 spinStartSpinSpeed; // spinStart.x, spinSpeed.y
-attribute vec4 orientation; // orientation quaternion
-attribute vec4 colorMult; // multiplies color and ramp textures
-
-// Outgoing variables to fragment shader
-varying vec2 outputTexcoord;
-varying float outputPercentLife;
-varying vec4 outputColorMult;
-
-void main() {
- vec2 uv = uvLifeTimeFrameStart.xy;
- float lifeTime = uvLifeTimeFrameStart.z;
- float frameStart = uvLifeTimeFrameStart.w;
- vec3 position = positionStartTime.xyz;
- float startTime = positionStartTime.w;
- vec3 velocity = (world * vec4(velocityStartSize.xyz,
- 0.)).xyz + worldVelocity;
- float startSize = velocityStartSize.w;
- vec3 acceleration = (world * vec4(accelerationEndSize.xyz,
- 0)).xyz + worldAcceleration;
- float endSize = accelerationEndSize.w;
- float spinStart = spinStartSpinSpeed.x;
- float spinSpeed = spinStartSpinSpeed.y;
-
- float localTime = mod((time - timeOffset - startTime), timeRange);
- float percentLife = localTime / lifeTime;
-
- float frame = mod(floor(localTime / frameDuration + frameStart),
- numFrames);
- float uOffset = frame / numFrames;
- float u = uOffset + (uv.x + 0.5) * (1. / numFrames);
-
- outputTexcoord = vec2(u, uv.y + 0.5);
- outputColorMult = colorMult;
-
- float size = mix(startSize, endSize, percentLife);
- size = (percentLife < 0. || percentLife > 1.) ? 0. : size;
- float s = sin(spinStart + spinSpeed * localTime);
- float c = cos(spinStart + spinSpeed * localTime);
-
- vec4 rotatedPoint = vec4((uv.x * c + uv.y * s) * size, 0.,
- (uv.x * s - uv.y * c) * size, 1.);
- vec3 center = velocity * localTime +
- acceleration * localTime * localTime +
- position;
-
- vec4 q2 = orientation + orientation;
- vec4 qx = orientation.xxxw * q2.xyzx;
- vec4 qy = orientation.xyyw * q2.xyzy;
- vec4 qz = orientation.xxzw * q2.xxzz;
-
- mat4 localMatrix = mat4(
- (1.0 - qy.y) - qz.z,
- qx.y + qz.w,
- qx.z - qy.w,
- 0,
-
- qx.y - qz.w,
- (1.0 - qx.x) - qz.z,
- qy.z + qx.w,
- 0,
-
- qx.z + qy.w,
- qy.z - qx.w,
- (1.0 - qx.x) - qy.y,
- 0,
-
- center.x, center.y, center.z, 1);
- rotatedPoint = localMatrix * rotatedPoint;
- outputPercentLife = percentLife;
- gl_Position = worldViewProjection * rotatedPoint;
-}
diff --git a/o3d/compiler/glsl_validator/shaders/particles.frag b/o3d/compiler/glsl_validator/shaders/particles.frag
deleted file mode 100644
index 25fb378..0000000
--- a/o3d/compiler/glsl_validator/shaders/particles.frag
+++ /dev/null
@@ -1,17 +0,0 @@
-uniform sampler2D rampSampler;
-uniform sampler2D colorSampler;
-
-// Incoming variables from vertex shader
-varying vec2 outputTexcoord;
-varying float outputPercentLife;
-varying vec4 outputColorMult;
-
-void main() {
- vec4 colorMult = texture2D(rampSampler,
- vec2(outputPercentLife, 0.5)) *
- outputColorMult;
- gl_FragColor = texture2D(colorSampler, outputTexcoord) * colorMult;
- // For debugging: requires setup of some uniforms and vertex
- // attributes to be commented out to avoid GL errors
- // gl_FragColor = vec4(1., 0., 0., 1.);
-}
diff --git a/o3d/compiler/glsl_validator/shaders/san-angeles-fade.vert b/o3d/compiler/glsl_validator/shaders/san-angeles-fade.vert
deleted file mode 100644
index d2676ee42..0000000
--- a/o3d/compiler/glsl_validator/shaders/san-angeles-fade.vert
+++ /dev/null
@@ -1,10 +0,0 @@
-attribute vec2 pos;
-
-varying vec4 color;
-
-uniform float minFade;
-
-void main() {
- color = vec4(minFade, minFade, minFade, 1.);
- gl_Position = vec4(pos, 0., 1.);
-}
diff --git a/o3d/compiler/glsl_validator/shaders/san-angeles-flat.frag b/o3d/compiler/glsl_validator/shaders/san-angeles-flat.frag
deleted file mode 100644
index 3f2bed8..0000000
--- a/o3d/compiler/glsl_validator/shaders/san-angeles-flat.frag
+++ /dev/null
@@ -1,4 +0,0 @@
-varying vec4 color;
-void main() {
- gl_FragColor = vec4(color.rgb, 1.0);
-}
diff --git a/o3d/compiler/glsl_validator/shaders/san-angeles-flat.vert b/o3d/compiler/glsl_validator/shaders/san-angeles-flat.vert
deleted file mode 100644
index 4583d20..0000000
--- a/o3d/compiler/glsl_validator/shaders/san-angeles-flat.vert
+++ /dev/null
@@ -1,8 +0,0 @@
-attribute vec3 pos;
-attribute vec4 colorIn;
-uniform mat4 mvp;
-varying vec4 color;
-void main() {
- color = colorIn;
- gl_Position = mvp * vec4(pos.xyz, 1.);
-}
diff --git a/o3d/compiler/glsl_validator/shaders/san-angeles-lit.vert b/o3d/compiler/glsl_validator/shaders/san-angeles-lit.vert
deleted file mode 100644
index 022ec5ac..0000000
--- a/o3d/compiler/glsl_validator/shaders/san-angeles-lit.vert
+++ /dev/null
@@ -1,50 +0,0 @@
-attribute vec3 pos;
-attribute vec3 normal;
-attribute vec4 colorIn;
-
-varying vec4 color;
-
-uniform mat4 mvp;
-uniform mat3 normalMatrix;
-uniform vec4 ambient;
-uniform float shininess;
-uniform vec3 light_0_direction;
-uniform vec4 light_0_diffuse;
-uniform vec4 light_0_specular;
-uniform vec3 light_1_direction;
-uniform vec4 light_1_diffuse;
-uniform vec3 light_2_direction;
-uniform vec4 light_2_diffuse;
-
-vec3 worldNormal;
-
-vec4 SpecularLight(vec3 direction,
- vec4 diffuseColor,
- vec4 specularColor) {
- vec3 lightDir = normalize(direction);
- float diffuse = max(0., dot(worldNormal, lightDir));
- float specular = 0.;
- if (diffuse > 0.) {
- vec3 halfv = normalize(lightDir + vec3(0., 0., 1.));
- specular = pow(max(0., dot(halfv, worldNormal)), shininess);
- }
- return diffuse * diffuseColor * colorIn + specular * specularColor;
-}
-
-vec4 DiffuseLight(vec3 direction, vec4 diffuseColor) {
- vec3 lightDir = normalize(direction);
- float diffuse = max(0., dot(worldNormal, lightDir));
- return diffuse * diffuseColor * colorIn;
-}
-
-void main() {
- worldNormal = normalize(normalMatrix * normal);
-
- gl_Position = mvp * vec4(pos, 1.);
-
- color = ambient * colorIn;
- color += SpecularLight(light_0_direction, light_0_diffuse,
- light_0_specular);
- color += DiffuseLight(light_1_direction, light_1_diffuse);
- color += DiffuseLight(light_2_direction, light_2_diffuse);
-}
diff --git a/o3d/compiler/glsl_validator/shaders/shiny-teapot.frag b/o3d/compiler/glsl_validator/shaders/shiny-teapot.frag
deleted file mode 100644
index 7c0667e..0000000
--- a/o3d/compiler/glsl_validator/shaders/shiny-teapot.frag
+++ /dev/null
@@ -1,23 +0,0 @@
-const float bumpHeight = 0.2;
-
-uniform sampler2D normalSampler;
-uniform samplerCube envSampler;
-
-varying vec2 texCoord;
-varying vec3 worldEyeVec;
-varying vec3 worldNormal;
-varying vec3 worldTangent;
-varying vec3 worldBinorm;
-
-void main() {
- vec2 bump = (texture2D(normalSampler, texCoord.xy).xy * 2.0 - 1.0) * bumpHeight;
- vec3 normal = normalize(worldNormal);
- vec3 tangent = normalize(worldTangent);
- vec3 binormal = normalize(worldBinorm);
- vec3 nb = normal + bump.x * tangent + bump.y * binormal;
- nb = normalize(nb);
- vec3 worldEye = normalize(worldEyeVec);
- vec3 lookup = reflect(worldEye, nb);
- vec4 color = textureCube(envSampler, lookup);
- gl_FragColor = color;
-}
diff --git a/o3d/compiler/glsl_validator/shaders/shiny-teapot.vert b/o3d/compiler/glsl_validator/shaders/shiny-teapot.vert
deleted file mode 100644
index e0eef69..0000000
--- a/o3d/compiler/glsl_validator/shaders/shiny-teapot.vert
+++ /dev/null
@@ -1,26 +0,0 @@
-attribute vec3 g_Position;
-attribute vec3 g_TexCoord0;
-attribute vec3 g_Tangent;
-attribute vec3 g_Binormal;
-attribute vec3 g_Normal;
-
-uniform mat4 world;
-uniform mat4 worldInverseTranspose;
-uniform mat4 worldViewProj;
-uniform mat4 viewInverse;
-
-varying vec2 texCoord;
-varying vec3 worldEyeVec;
-varying vec3 worldNormal;
-varying vec3 worldTangent;
-varying vec3 worldBinorm;
-
-void main() {
- gl_Position = worldViewProj * vec4(g_Position.xyz, 1.);
- texCoord.xy = g_TexCoord0.xy;
- worldNormal = (worldInverseTranspose * vec4(g_Normal, 1.)).xyz;
- worldTangent = (worldInverseTranspose * vec4(g_Tangent, 1.)).xyz;
- worldBinorm = (worldInverseTranspose * vec4(g_Binormal, 1.)).xyz;
- vec3 worldPos = (world * vec4(g_Position, 1.)).xyz;
- worldEyeVec = normalize(worldPos - viewInverse[3].xyz);
-}
diff --git a/o3d/compiler/glsl_validator/shaders/spirit-box.frag b/o3d/compiler/glsl_validator/shaders/spirit-box.frag
deleted file mode 100644
index 3013143..0000000
--- a/o3d/compiler/glsl_validator/shaders/spirit-box.frag
+++ /dev/null
@@ -1,12 +0,0 @@
-uniform sampler2D sampler2d;
-
-varying float v_Dot;
-varying vec2 v_texCoord;
-
-void main()
-{
- vec2 texCoord = vec2(v_texCoord.s, 1.0 - v_texCoord.t);
- vec4 color = texture2D(sampler2d, texCoord);
- color += vec4(0.1, 0.1, 0.1, 1);
- gl_FragColor = vec4(color.xyz * v_Dot, color.a);
-}
diff --git a/o3d/compiler/glsl_validator/shaders/spirit-box.vert b/o3d/compiler/glsl_validator/shaders/spirit-box.vert
deleted file mode 100644
index 72f86d7..0000000
--- a/o3d/compiler/glsl_validator/shaders/spirit-box.vert
+++ /dev/null
@@ -1,18 +0,0 @@
-uniform mat4 u_modelViewProjMatrix;
-uniform mat4 u_normalMatrix;
-uniform vec3 lightDir;
-
-attribute vec3 vNormal;
-attribute vec4 vTexCoord;
-attribute vec4 vPosition;
-
-varying float v_Dot;
-varying vec2 v_texCoord;
-
-void main()
-{
- gl_Position = u_modelViewProjMatrix * vPosition;
- v_texCoord = vTexCoord.st;
- vec4 transNormal = u_normalMatrix * vec4(vNormal, 1);
- v_Dot = max(dot(transNormal.xyz, lightDir), 0.0);
-}
diff --git a/o3d/compiler/glsl_validator/shaders/spore-view.frag b/o3d/compiler/glsl_validator/shaders/spore-view.frag
deleted file mode 100644
index 72717bb..0000000
--- a/o3d/compiler/glsl_validator/shaders/spore-view.frag
+++ /dev/null
@@ -1,12 +0,0 @@
-varying vec3 vNormal;
-varying vec3 vViewVec;
-varying vec2 vTexCoord0;
-
-uniform vec4 uColor;
-uniform sampler2D uTexture0;
-
-void main(void) {
- float v = 0.5 * (1.0 + dot(normalize(vViewVec), vNormal));
-
- gl_FragColor = texture2D(uTexture0, vTexCoord0.st);
-}
diff --git a/o3d/compiler/glsl_validator/shaders/spore-view.vert b/o3d/compiler/glsl_validator/shaders/spore-view.vert
deleted file mode 100644
index 8ed64c3..0000000
--- a/o3d/compiler/glsl_validator/shaders/spore-view.vert
+++ /dev/null
@@ -1,19 +0,0 @@
-attribute vec3 aVertex;
-attribute vec3 aNormal;
-attribute vec2 aTexCoord0;
-
-uniform mat4 uPMatrix;
-uniform mat4 uMVMatrix;
-uniform vec4 uViewPosition;
-
-varying vec3 vNormal;
-varying vec3 vViewVec;
-varying vec2 vTexCoord0;
-
-void main(void) {
- gl_Position = uPMatrix * uMVMatrix * vec4(aVertex, 1.0);
-
- vNormal = aNormal;
- vViewVec = uViewPosition.xyz - aVertex.xyz;
- vTexCoord0 = aTexCoord0;
-}
diff --git a/o3d/compiler/glsl_validator/shaders/teapot-per-pixel.frag b/o3d/compiler/glsl_validator/shaders/teapot-per-pixel.frag
deleted file mode 100644
index 9e485f0..0000000
--- a/o3d/compiler/glsl_validator/shaders/teapot-per-pixel.frag
+++ /dev/null
@@ -1,46 +0,0 @@
-struct Light
-{
- vec4 ambient;
- vec4 diffuse;
- vec4 specular;
- vec4 position;
-
- vec3 halfVector;
-};
-
-struct Material
-{
- vec4 emission;
- vec4 ambient;
- vec4 diffuse;
- vec4 specular;
- float shininess;
-};
-
-uniform sampler2D u_sampler2d;
-uniform Light u_light;
-uniform Material u_frontMaterial;
-uniform Material u_backMaterial;
-
-varying vec4 v_diffuse, v_ambient;
-varying vec3 v_normal, v_lightDir;
-varying vec2 v_texCoord;
-
-void main()
-{
- vec4 color = v_diffuse;
-
- vec3 n = normalize(v_normal);
-
- Light light = u_light;
- vec3 lightDir = v_lightDir;
- float nDotL = max(dot(n, lightDir), 0.0);
- if (nDotL > 0.0) {
- color = vec4(color.rgb * nDotL, color.a);
- float nDotHV = max(dot(n, light.halfVector), 0.0);
- vec4 specular = u_frontMaterial.specular * light.specular;
- color += vec4(specular.rgb * pow(nDotHV, u_frontMaterial.shininess), specular.a);
- }
-
- gl_FragColor = color + v_ambient;
-}
diff --git a/o3d/compiler/glsl_validator/shaders/teapot-per-pixel.vert b/o3d/compiler/glsl_validator/shaders/teapot-per-pixel.vert
deleted file mode 100644
index b03e747..0000000
--- a/o3d/compiler/glsl_validator/shaders/teapot-per-pixel.vert
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- Copyright (c) 2008 Seneca College
- Licenced under the MIT License (http://www.c3dl.org/index.php/mit-license/)
-*/
-
-// We need to create our own light structure since we can't access
-// the light() function in the 2.0 context.
-struct Light
-{
- vec4 ambient;
- vec4 diffuse;
- vec4 specular;
- vec4 position;
-
- vec3 halfVector;
-};
-
-struct Material
-{
- vec4 emission;
- vec4 ambient;
- vec4 diffuse;
- vec4 specular;
- float shininess;
-};
-//
-// vertex attributes
-//
-attribute vec4 a_vertex;
-attribute vec3 a_normal;
-attribute vec4 a_texCoord;
-
-// for every model we multiply the projection, view and model matrices
-// once to prevent having to do it for every vertex, however we still need
-// the view matrix to calculate lighting.
-uniform mat4 u_modelViewMatrix;
-
-// we can calculate this once per model to speed up processing done on the js side.
-uniform mat4 u_modelViewProjMatrix;
-
-// matrix to transform the vertex normals
-uniform mat4 u_normalMatrix;
-
-// custom light structures need to be used since we don't have access to
-// light states.
-uniform Light u_light;
-
-// material
-uniform vec4 u_globalAmbientColor;
-uniform Material u_frontMaterial;
-uniform Material u_backMaterial;
-
-// passed to fragment shader
-varying vec4 v_diffuse, v_ambient;
-varying vec3 v_normal, v_lightDir;
-varying vec2 v_texCoord;
-
-/*
- Given a reference to the ambient and diffuse lighting variables,
- this function will calculate how much each component contributes to the scene.
-
- Light light - the light in view space
- vec3 normal -
- vec4 ambient -
- vec4 diffuse -
-*/
-vec3 directionalLight(inout vec4 ambient, inout vec4 diffuse)
-{
- ambient += u_light.ambient;
- diffuse += u_light.diffuse;
- return normalize(vec3(u_light.position));
-}
-
-void main()
-{
- v_normal = normalize(u_normalMatrix * vec4(a_normal, 1)).xyz;
-
- vec4 ambient = vec4(0.0, 0.0, 0.0, 1.0);
- vec4 diffuse = vec4(0.0, 0.0, 0.0, 1.0);
- vec4 specular = vec4(0.0, 0.0, 0.0, 1.0);
-
- // place the current vertex into view space
- // ecPos = eye coordinate position.
- vec4 ecPos4 = u_modelViewMatrix * a_vertex;
-
- // the current vertex in eye coordinate space
- vec3 ecPos = ecPos4.xyz/ecPos4.w;
- v_lightDir = directionalLight(ambient, diffuse);
-
- v_ambient = u_frontMaterial.ambient * ambient;
- v_ambient += u_globalAmbientColor * u_frontMaterial.ambient;
- v_diffuse = u_frontMaterial.diffuse * diffuse;
-
- gl_Position = u_modelViewProjMatrix * a_vertex;
- v_texCoord = a_texCoord.st;
-}
diff --git a/o3d/compiler/glsl_validator/shaders/teapot-per-vertex.frag b/o3d/compiler/glsl_validator/shaders/teapot-per-vertex.frag
deleted file mode 100644
index 973eddb..0000000
--- a/o3d/compiler/glsl_validator/shaders/teapot-per-vertex.frag
+++ /dev/null
@@ -1,11 +0,0 @@
-uniform sampler2D u_sampler2d;
-
-varying vec4 v_diffuse, v_specular;
-varying vec2 v_texCoord;
-
-void main()
-{
- vec4 color = v_diffuse;
-
- gl_FragColor = color + v_specular;
-}
diff --git a/o3d/compiler/glsl_validator/shaders/teapot-per-vertex.vert b/o3d/compiler/glsl_validator/shaders/teapot-per-vertex.vert
deleted file mode 100644
index cfc0d45..0000000
--- a/o3d/compiler/glsl_validator/shaders/teapot-per-vertex.vert
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- Copyright (c) 2008 Seneca College
- Licenced under the MIT License (http://www.c3dl.org/index.php/mit-license/)
-*/
-
-// We need to create our own light structure since we can't access
-// the light() function in the 2.0 context.
-struct Light
-{
- vec4 ambient;
- vec4 diffuse;
- vec4 specular;
- vec4 position;
-
- vec3 halfVector;
-};
-
-struct Material
-{
- vec4 emission;
- vec4 ambient;
- vec4 diffuse;
- vec4 specular;
- float shininess;
-};
-
-//
-// vertex attributes
-//
-attribute vec3 a_normal;
-attribute vec4 a_texCoord;
-attribute vec4 a_vertex;
-
-// for every model we multiply the projection, view and model matrices
-// once to prevent having to do it for every vertex, however we still need
-// the view matrix to calculate lighting.
-uniform mat4 u_modelViewMatrix;
-
-// we can calculate this once per model to speed up processing done on the js side.
-uniform mat4 u_modelViewProjMatrix;
-
-// matrix to transform the vertex normals
-uniform mat4 u_normalMatrix;
-
-// custom light structures need to be used since we don't have access to
-// light states.
-uniform Light u_light;
-
-// material
-uniform vec4 u_globalAmbientColor;
-uniform Material u_frontMaterial;
-uniform Material u_backMaterial;
-
-// passed to fragment shader
-varying vec4 v_diffuse, v_specular;
-varying vec2 v_texCoord;
-
-/*
- Given a reference to the ambient and diffuse lighting variables,
- this function will calculate how much each component contributes to the scene.
-
- Light light - the light in view space
- vec3 normal -
- vec4 ambient -
- vec4 diffuse -
-*/
-void directionalLight(in vec3 normal, inout vec4 ambient, inout vec4 diffuse, inout vec4 specular)
-{
- vec3 lightDir = normalize(vec3(u_light.position));
- ambient += u_light.ambient;
-
- float nDotL = max(dot(normal, lightDir), 0.0);
- if (nDotL > 0.0) {
- diffuse += u_light.diffuse * nDotL;
- float nDotHV = max(dot(normal, u_light.halfVector), 0.0);
- nDotHV += 0.3;
- vec4 specularColor = u_frontMaterial.specular * u_light.specular;
- specular += vec4(specularColor.rgb * pow(nDotHV, u_frontMaterial.shininess), specularColor.a);
- }
-}
-
-void main()
-{
- vec3 normal = normalize(u_normalMatrix * vec4(a_normal, 1)).xyz;
-
- vec4 ambient = vec4(0.0, 0.0, 0.0, 1.0);
- vec4 diffuse = vec4(0.0, 0.0, 0.0, 1.0);
- vec4 specular = vec4(0.0, 0.0, 0.0, 1.0);
-
- // place the current vertex into view space
- // ecPos = eye coordinate position.
- vec4 ecPos4 = u_modelViewMatrix * a_vertex;
-
- // the current vertex in eye coordinate space
- vec3 ecPos = ecPos4.xyz/ecPos4.w;
- directionalLight(normal, ambient, diffuse, specular);
-
- ambient = u_frontMaterial.ambient * ambient;
- ambient += u_globalAmbientColor * u_frontMaterial.ambient;
- diffuse = u_frontMaterial.diffuse * diffuse;
-
- v_diffuse = diffuse;
- v_specular = specular + ambient;
- gl_Position = u_modelViewProjMatrix * a_vertex;
- v_texCoord = a_texCoord.st;
-}
diff --git a/o3d/compiler/glsl_validator/shaders/texture_mapping.frag b/o3d/compiler/glsl_validator/shaders/texture_mapping.frag
deleted file mode 100644
index 49cc9d0..0000000
--- a/o3d/compiler/glsl_validator/shaders/texture_mapping.frag
+++ /dev/null
@@ -1,12 +0,0 @@
-// Modified from shader at
-// http://nehe.gamedev.net/data/articles/article.asp?article=21
-
-uniform sampler2D my_color_texture;
-
-varying vec2 texture_coordinate;
-
-void main()
-{
- // Sampling The Texture And Passing It To The Frame Buffer
- gl_FragColor = texture2D(my_color_texture, texture_coordinate);
-}
diff --git a/o3d/compiler/glsl_validator/shaders/texture_mapping.vert b/o3d/compiler/glsl_validator/shaders/texture_mapping.vert
deleted file mode 100644
index 6e13f4d..0000000
--- a/o3d/compiler/glsl_validator/shaders/texture_mapping.vert
+++ /dev/null
@@ -1,18 +0,0 @@
-// Modified from shader at
-// http://nehe.gamedev.net/data/articles/article.asp?article=21
-
-uniform mat4 g_ModelViewProjectionMatrix;
-
-attribute vec4 g_Vertex;
-attribute vec4 g_MultiTexCoord0;
-
-varying vec2 texture_coordinate;
-
-void main()
-{
- // Transforming The Vertex
- gl_Position = g_ModelViewProjectionMatrix * g_Vertex;
-
- // Passing The Texture Coordinate Of Texture Unit 0 To The Fragment Shader
- texture_coordinate = vec2(g_MultiTexCoord0);
-}
diff --git a/o3d/compiler/glsl_validator/test/Main.java b/o3d/compiler/glsl_validator/test/Main.java
deleted file mode 100644
index e462cba..0000000
--- a/o3d/compiler/glsl_validator/test/Main.java
+++ /dev/null
@@ -1,62 +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.
- */
-
-package test;
-
-import java.io.*;
-import org.antlr.runtime.*;
-import glsl_es.*;
-
-public class Main {
- public static void main(String[] args) {
- for (String str : args) {
- parseFile(str);
- }
- }
-
- private static void parseFile(String f) {
- try {
- long startTime = System.currentTimeMillis();
- GLSL_ESLexer lexer = new GLSL_ESLexer(new ANTLRFileStream(f, "iso8859-1"));
- TokenRewriteStream tokens = new TokenRewriteStream(lexer);
- tokens.LT(1);
- // Create a parser that reads from the scanner
- GLSL_ESParser parser = new GLSL_ESParser(tokens);
- // Parse the translation unit
- parser.translation_unit();
- long endTime = System.currentTimeMillis();
- System.out.println("Parsing " + f + " took " + (endTime - startTime) + " ms");
- } catch (Exception e) {
- System.out.println("While parsing " + f + ":");
- e.printStackTrace();
- }
- }
-}
diff --git a/o3d/compiler/hlsl/HLSL.g b/o3d/compiler/hlsl/HLSL.g
deleted file mode 100644
index 7477b0d..0000000
--- a/o3d/compiler/hlsl/HLSL.g
+++ /dev/null
@@ -1,1020 +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 ANTLR grammar for parsing HLSL into an Abstract
-// Syntax Tree (AST).
-
-grammar HLSL;
-
-options {
- language = Java;
- }
-
-@header
-{
-}
-
-translation_unit
- : ( global_declaration )* (technique)* EOF
- ;
-
-global_declaration
- : (function_storage_class? function_type_specifier ID LPAREN) => function_declaration
- | sampler_declaration
- | texture_declaration
- | struct_definition
- | typedef_definition
- | var_declaration
- ;
-
-// variables -------------------------------------------
-
-var_declaration
- : var_storage_class*
- var_type_modifier?
- var_datatype id_declaration
- semantic?
- annotation_list?
- ('=' initializer)?
- var_packoffset?
- var_register_bind?
- SEMI
- ;
-
-var_storage_class
- : 'extern'
- | 'nointerpolation'
- | 'shared'
- | 'static'
- | 'uniform'
- | 'volatile'
- ;
-
-var_type_modifier
- : ('const'|'row_major'|'column_major');
-
-var_datatype
- : buffer_type_specifier
- | scalar_type_or_string_specifier
- | vector_type_specifier
- | matrix_type_specifier
- | struct_type_specifier
- ;
-
-var_packoffset
- : 'packoffset' LPAREN register_name (DOT vector_subcomponent)? RPAREN
- ;
-
-var_register_bind
- : COLON register_name
- ;
-
-id_declaration
- : ID ( LBRACKET constant_expression RBRACKET )?
- ;
-
-// function --------------------------------------------
-
-function_declaration
- : function_storage_class?
- function_type_specifier ID LPAREN argument_list RPAREN semantic?
- function_body (SEMI)?
- ;
-
-function_storage_class
- : 'inline' // ignoring platform target
- ;
-
-function_type_specifier
- : scalar_type_specifier
- | vector_type_specifier
- | matrix_type_specifier
- | struct_type_specifier
- | 'void'
- ;
-
-semantic
- : COLON semantic_specifier ;
-
-param_type_specifier
- : scalar_type_specifier
- | vector_type_specifier
- | matrix_type_specifier
- | struct_type_specifier
- | string_type_specifier
- ;
-
-// typedef ---------------------------------------
-
-typedef_definition
- : 'typedef'
- ;
-
-// basic datatypes -------------------------------
-
-buffer_type_specifier
- : ('buffer' '<' var_datatype '>' ID)
- ;
-
-scalar_type_specifier
- : 'bool'
- | 'int'
- | 'uint'
- | 'half'
- | 'float'
- | 'double'
- ;
-
-scalar_type_or_string_specifier
- : scalar_type_specifier
- | string_type_specifier
- ;
-
-vector_type_specifier
- : 'bool1'
- | 'bool2'
- | 'bool3'
- | 'bool4'
- | 'int1'
- | 'int2'
- | 'int3'
- | 'int4'
- | 'uint1'
- | 'uint2'
- | 'uint3'
- | 'uint4'
- | 'half1'
- | 'half2'
- | 'half3'
- | 'half4'
- | 'float1'
- | 'float2'
- | 'float3'
- | 'float4'
- | 'double1'
- | 'double2'
- | 'double3'
- | 'double4'
- | 'vector' '<' scalar_type_specifier ',' ('1'|'2'|'3'|'4') '>'
- ;
-
-matrix_type_specifier
- : 'float1x1'
- | 'float1x2'
- | 'float1x3'
- | 'float1x4'
- | 'float2x1'
- | 'float2x2'
- | 'float2x3'
- | 'float2x4'
- | 'float3x1'
- | 'float3x2'
- | 'float3x3'
- | 'float3x4'
- | 'float4x1'
- | 'float4x2'
- | 'float4x3'
- | 'float4x4'
- | 'matrix' '<' scalar_type_specifier ',' ('1'|'2'|'3'|'4') ',' ('1'|'2'|'3'|'4') '>'
- ;
-
-string_type_specifier
- : 'string'
- ;
-
-// Sampler declarations ----------------------------
-
-sampler_declaration
- : SAMPLER ID '=' sampler_type_specifier '{' sampler_state_declaration+ '}' SEMI
- | SAMPLER ID SEMI // GLSL format
- | sampler_type_specifier id_declaration '=' '{' sampler_state_declaration_simple ']' SEMI // DX10 style
- ;
-
-sampler_state_declaration
- : ( ('Texture'|'texture') '=' '<' ID '>' SEMI ) // DX9 must have one of these
- | sampler_state_declaration_simple
- ;
-
-sampler_state_declaration_simple
- : ( sampler_state_specifier '=' initializer SEMI ) // DX10 style
- ;
-
-sampler_type_specifier
- : 'sampler' | 'Sampler'
- | 'sampler1D' | 'Sampler1D' | 'sampler1d'
- | 'sampler2D' | 'Sampler2D' | 'sampler2d'
- | 'sampler3D' | 'Sampler3D' | 'sampler3d'
- | 'samplerCUBE' | 'SamplerCUBE' | 'samplercube'
- | 'sampler_state' | 'samplerstate' | 'SamplerState'
- | 'SamplerComparisonState' | 'samplercomparisonstate' // DX10 only
- ;
-
-sampler_state_specifier
- : 'AddressU' | 'addressu'
- | 'AddressV' | 'addressv'
- | 'AddressW' | 'addressw'
- | 'BorderColor' | 'bordercolor'
- | 'ComparisonFilter' | 'comparisonfilter' // SamplerComparisonState only
- | 'ComparisonFunc' | 'comparisonfunc' // SamplerComparisonState only
- | 'MagFilter' | 'magfilter'
- | 'MaxAnisotropy' | 'maxanisotropy'
- | 'MinFilter' | 'minfilter'
- | 'MipFilter' | 'mipfilter'
- | 'MipMapLODBias' | 'MipMapLodBias' | 'mipmapLODbias' | 'mipmaplodbias'
- ;
-
- // texture declaration ----------------------------
-
-texture_declaration
- : texture_type_specifier ID annotation_list? SEMI
- | texture_type_specifier '<'
- (scalar_type_specifier | vector_type_specifier ) '>' ID SEMI // GLSL syntax.
- ;
-
-texture_type_specifier
- : 'texture'
- | 'texture1D' | 'Texture1D'
- | 'texture2D' | 'Texture2D'
- | 'texture3D' | 'Texture3D'
- | 'textureCUBE' | 'TextureCUBE'
- ;
-
- // struct declaration -----------------------------
-
-struct_type_specifier
- : ID
- | ( STRUCT ( ID )? LCURLY ) => struct_definition
- | STRUCT ID
- ;
-
-annotation_list
- : '<' (annotation)* '>';
-
-annotation
- : scalar_type_or_string_specifier ID '=' constant_expression SEMI ;
-
-initializer
- : constant_expression
- | '{' constant_expression ( ',' constant_expression )* '}'
- ;
-
-register_name
- // registers for VS_3_0
- : 'register' '(' input_register_name | output_register_name ')';
-
-input_register_name
- : (('v'|'r'|'c'|'b'|'i'|'s'|'o') DECIMAL_LITERAL)
- | ('a0'|'aL'|'p0')
- ;
-
-output_register_name
- : 'oD0'|'oD1'|'oFog'|'oPos'|'oPts'
- | 'oT0'|'oT1'|'oT2'|'oT3'|'oT4'|'oT5'|'oT6'|'oT7'
- ;
-
-pack_offset
- : .+ ; // no idea what this field looks like.
-
-argument_list
- : ( param_declaration ( COMMA param_declaration )* )?
- ;
-
-param_declaration
- : param_direction? param_variability? param_type_specifier id_declaration semantic?
- | SAMPLER ID
-// | FUNCTION type_specifier ID
- ;
-
-param_variability
- : CONST
- | UNIFORM
- ;
-
-param_direction
- : IN
- | OUT
- | INOUT
- ;
-
-function_body
- : LCURLY ( decl_or_statement )* RCURLY
- ;
-
-decl_or_statement
- // We copied the following sub-rule here to expedite the parsing time
- // as this is a much more common case than the "Id init_declarator_list"
- // case which would normally spend a lot of time in exception handling.
- : (lvalue_expression assignment_operator ) => assignment_statement
- | ( ( CONST )? vector_type_specifier ) => ( CONST )? vector_type_specifier init_declarator_list SEMI
- | ( ( CONST )? scalar_type_specifier ) => ( CONST )? scalar_type_specifier init_declarator_list SEMI
- | ( STRUCT ( ID )? LCURLY ) => struct_definition ( init_declarator_list )? SEMI
- | STRUCT ID init_declarator_list SEMI
- | ( ID init_declarator_list ) => ID init_declarator_list SEMI
- | statement
- ;
-
-init_declarator_list
- : init_declarator ( COMMA init_declarator )* ;
-
-init_declarator
- : declarator ( ASSIGN initializer )? ;
-
-declarator
- : ID ( LBRACKET ( constant_expression )? RBRACKET )*;
-
-struct_definition
- : STRUCT ( ID )? LCURLY struct_declaration_list RCURLY ID? SEMI;
-
-struct_declaration_list
- // We currently don't support nested structs so the field type
- // can only be either a scalar or a vector.
- : ( struct_interpolation_modifier?
- (scalar_type_specifier|vector_type_specifier) ID
- (COLON semantic_specifier)? SEMI )+
- ;
-
-struct_interpolation_modifier // DX10 only
- : 'linear'
- | 'centroid'
- | 'nointerpolation'
- | 'noperspective'
- ;
-
-semantic_specifier
- : ID ;
-
-statement
- : ( lvalue_expression assignment_operator ) => assignment_statement
- | ( lvalue_expression self_modify_operator ) => post_modify_statement
- | pre_modify_statement
- | expression_statement
- | compound_statement
- | selection_statement
- | iteration_statement
- | jump_statement
- | SEMI
- ;
-
-assignment_statement
- : lvalue_expression assignment_operator expression SEMI ;
-
-pre_modify_statement
- : pre_modify_expression SEMI ;
-
-pre_modify_expression
- : self_modify_operator lvalue_expression ;
-
-post_modify_statement
- : post_modify_expression SEMI ;
-
-post_modify_expression
- : lvalue_expression self_modify_operator ;
-
-self_modify_operator
- : PLUSPLUS | MINUSMINUS ;
-
-expression_statement
- : expression SEMI ;
-
-compound_statement
- : LCURLY (
- ( ID init_declarator_list) => ID init_declarator_list SEMI
- | ( ( CONST )? vector_type_specifier ) => ( CONST )? vector_type_specifier init_declarator_list SEMI
- | ( ( CONST )? scalar_type_specifier ) => ( CONST )? scalar_type_specifier init_declarator_list SEMI
- | ( STRUCT ( ID )? LCURLY ) => struct_definition ( init_declarator_list )? SEMI
- | STRUCT ID init_declarator_list SEMI
- | statement
- )*
- RCURLY
- ;
-
-selection_statement
- : IF LPAREN expression RPAREN statement ( ELSE statement )?
- ;
-
-iteration_statement
- : WHILE LPAREN expression RPAREN statement
- | FOR LPAREN assignment_statement
- equality_expression SEMI modify_expression RPAREN statement
- | DO statement WHILE LPAREN expression RPAREN SEMI
- ;
-
-modify_expression
- : (lvalue_expression assignment_operator ) =>
- lvalue_expression assignment_operator expression
- | pre_modify_expression
- | post_modify_expression
- ;
-
-jump_statement
- : BREAK SEMI
- | CONTINUE
- | RETURN ( expression )? SEMI
- | DISCARD
- ;
-
-expression
- : conditional_expression ;
-
-assignment_operator
- : ASSIGN
- | MUL_ASSIGN
- | DIV_ASSIGN
- | ADD_ASSIGN
- | SUB_ASSIGN
- | BITWISE_AND_ASSIGN
- | BITWISE_OR_ASSIGN
- | BITWISE_XOR_ASSIGN
- | BITWISE_SHIFTL_ASSIGN
- | BITWISE_SHIFTR_ASSIGN
- ;
-
-constant_expression
- : (ID) => variable_expression
- | literal_value ;
-
-conditional_expression
- : logical_or_expression ( QUESTION expression COLON conditional_expression )?
- ;
-
-logical_or_expression
- : exclusive_or_expression ( OR exclusive_or_expression )*
- ;
-
-// We remove the NOT operator from the unary expression and stick it here
-// so that it has a lower precedence than relational operations.
-logical_and_expression
- : ( NOT )? inclusive_or_expression ( AND ( NOT )? inclusive_or_expression )*
- ;
-
-inclusive_or_expression
- : exclusive_or_expression (BITWISE_OR exclusive_or_expression )*
- ;
-
-exclusive_or_expression
- : and_expression ( BITWISE_XOR and_expression )*
- ;
-
-and_expression
- : equality_expression ( BITWISE_AND equality_expression )*
- ;
-
-equality_expression
- : relational_expression ( (EQUAL|NOT_EQUAL) relational_expression )*
- ;
-
-relational_expression
- : shift_expression ( (LT|GT|LTE|GTE) shift_expression )*
- ;
-
-shift_expression
- : additive_expression ( (BITWISE_SHIFTL|BITWISE_SHIFTR) additive_expression )*
- ;
-
-additive_expression
- : multiplicative_expression ( (PLUS|MINUS) multiplicative_expression )*
- ;
-
-multiplicative_expression
- : cast_expression ( (MUL|DIV|MOD) cast_expression )*
- ;
-
-cast_expression
- : LBRACKET param_type_specifier RBRACKET cast_expression
- | unary_expression
- ;
-
-unary_expression
- : (PLUS|MINUS) unary_expression
- | postfix_expression
- ;
-
-postfix_expression
- : primary_expression ( postfix_suffix )? ;
-
-lvalue_expression
- : variable_expression ( postfix_suffix )? ;
-
-postfix_suffix
- // choosing between struct field access or vector swizzling is a semantic choice.
- : ( DOT swizzle )
- | ( DOT primary_expression )+ ;
-
-primary_expression
-// : constructor
- : intrinsic_name LPAREN argument_expression_list RPAREN
- | variable_or_call_expression
- | literal_value
- | LPAREN expression RPAREN
- ;
-
-variable_expression
- : ID ( LBRACKET expression RBRACKET )? ;
-
-// Combine variable expression and call expression here to get rid of the
-// syntactic predicate we used to use in the primary_expression rule. Using
-// predicates results in the parser spending a lot of time in exception
-// handling (when lookahead fails).
-variable_or_call_expression
- : ID
- (
- ( ( LBRACKET expression RBRACKET )? )
- |
- ( LPAREN argument_expression_list RPAREN )
- )
- ;
-
-constructor
- : vector_type_specifier LPAREN expression ( COMMA expression )* RPAREN ;
-
-argument_expression_list
- : ( expression ( COMMA expression )* )? ;
-
-intrinsic_name
- : ABS
- | ACOS
- | ALL
- | ANY
- | ASFLOAT
- | ASIN
- | ASINT
- | ASUINT
- | ATAN
- | ATAN2
- | CEIL
- | CLAMP
- | CLIP
- | COS
- | COSH
- | CROSS
- | DDX
- | DDY
- | DEGREES
- | DETERMINANT
- | DISTANCE
- | DOT
- | EXP
- | EXP2
- | FACEFORWARD
- | FLOOR
- | FMOD
- | FRAC
- | FREXP
- | FWIDTH
- | ISFINITE
- | ISINF
- | ISNAN
- | LDEXP
- | LENGTH
- | LERP
- | LIT
- | LOG
- | LOG10
- | LOG2
- | MAX
- | MIN
- | MODF
- | MUL
- | NOISE
- | NORMALIZE
- | POW
- | RADIANS
- | REFLECT
- | REFRACT
- | ROUND
- | RSQRT
- | SATURATE
- | SIGN
- | SIN
- | SINCOS
- | SINH
- | SMOOTHSTEP
- | SQRT
- | STEP
- | TAN
- | TANH
- | TEX1D
- | TEX1DBIAS
- | TEX1DGRAD
- | TEX1DLOD
- | TEX1DPROJ
- | TEX2D
- | TEX2DBIAS
- | TEX2DGRAD
- | TEX2DLOD
- | TEX2DPROJ
- | TEX3D
- | TEX3DBIAS
- | TEX3DGRAD
- | TEX3DLOD
- | TEX3DPROJ
- | TEXCUBE
- | TEXCUBEBIAS
- | TEXCUBEGRAD
- | TEXCUBELOD
- | TEXCUBEPROJ
- | TRANSPOSE
- | TRUNC
- ;
-
-int_literal
- : DECIMAL_LITERAL
- | OCT_LITERAL
- | HEX_LITERAL
- ;
-literal_value
- : ('"') => string_literal
- | int_literal
- | float_literal
- ;
-
-
-float_literal
- : FLOAT_LITERAL
- ;
-
-string_literal
- : '"' STRING_LITERAL '"'
- ;
-
-vector_subcomponent
- : DOT ('x'|'y'|'z'|'w'|'r'|'g'|'b'|'a')
- ;
-
-swizzle
- : ( s += ('x'|'y'|'z'|'w') )+ { $s.size() <= 4 }?
- | ( s += ('r'|'g'|'b'|'a') )+ { $s.size() <= 4 }?
- ;
-
-// effects ---------------------------------------
-
-technique
- : 'technique' ID? '{' (pass)+ '}' SEMI?
- ;
-
-pass
- : 'pass' (ID)? '{' (state_assignment)* '}' SEMI?
- ;
-
-state_assignment
- : a=ID '=' state_assignment_value SEMI
- { System.out.println("Found stateassignment: " + $a.text); }
- ;
-
-state_assignment_value
- : 'compile' p=ID q=variable_or_call_expression
- { System.out.println("Found compile: " + $p.text + " " + $q.text); }
- | a=expression
- { System.out.println("Found stateassignmentvalue: " + $a.text); }
- | ('true' | 'false')
- ;
-
-// -----------------------------------------------------------------------------
-
-NOT : '!' ;
-NOT_EQUAL : '!=' ;
-AND : '&&' ;
-LPAREN : '(' ;
-RPAREN : ')' ;
-MUL : '*' ;
-MUL_ASSIGN : '*=' ;
-PLUS : '+' ;
-PLUSPLUS : '++' ;
-ADD_ASSIGN : '+=' ;
-COMMA : ',' ;
-MINUS : '-' ;
-MINUSMINUS : '--' ;
-SUB_ASSIGN : '-=' ;
-DIV : '/' ;
-DIV_ASSIGN : '/=' ;
-MOD : '%';
-MOD_ASSIGN : '%=';
-COLON : ':' ;
-SEMI : ';' ;
-LT : '<' ;
-LTE : '<=' ;
-ASSIGN : '=' ;
-EQUAL : '==' ;
-GT : '>' ;
-GTE : '>=' ;
-QUESTION : '?' ;
-LBRACKET : '[' ;
-RBRACKET : ']' ;
-LCURLY : '{' ;
-OR : '||' ;
-RCURLY : '}' ;
-DOT : '.' ;
-BITWISE_NOT : '~';
-BITWISE_SHIFTL : '<<';
-BITWISE_SHIFTR : '>>';
-BITWISE_AND : '&';
-BITWISE_OR : '|';
-BITWISE_XOR : '^';
-BITWISE_SHIFTL_ASSIGN : '<<=';
-BITWISE_SHIFTR_ASSIGN : '>>=';
-BITWISE_AND_ASSIGN : '&=';
-BITWISE_OR_ASSIGN : '|=';
-BITWISE_XOR_ASSIGN : '^=';
-
-// keywords ----------------------------
-
-BREAK : 'break';
-BUFFER : 'buffer';
-CBUFFER : 'cbuffer';
-CONST : 'const';
-CONTINUE : 'continue';
-DISCARD : 'discard';
-DO : 'do';
-ELSE : 'else';
-EXTERN : 'extern';
-FALSE : 'false';
-FOR : 'for';
-IF : 'if';
-IN : 'in';
-INLINE : 'inline';
-INOUT : 'inout';
-MATRIX : 'matrix';
-NAMESPACE : 'namespace';
-NOINTERPOLATION : 'nointerpolation';
-OUT : 'out';
-RETURN : 'return';
-REGISTER : 'register';
-SHARED : 'shared';
-STATEBLOCK : 'stateblock';
-STATEBLOCK_STATE : 'stateblock_state';
-STATIC : 'static';
-STRING : 'string';
-STRUCT : 'struct';
-SWITCH : 'switch';
-TBUFFER : 'tbuffer';
-TEXTURE : 'texture';
-TEXTURE1D : 'texture1d';
-TEXTURE1DARRAY : 'texture1darray';
-TEXTURE2D : 'texture2d';
-TEXTURE2DARRAY : 'texture2darray';
-TEXTURE2DMS : 'texture2dms';
-TEXTURE2DMSARRAY : 'texture2dmsarray';
-TEXTURE3D : 'texture3d';
-TEXTURECUBE : 'texturecube';
-TEXTURECUBEARRAY : 'texturecubearray';
-TRUE : 'true';
-TYPEDEF : 'typedef';
-UNIFORM : 'uniform';
-VOID : 'void';
-VOLATILE : 'volatile';
-WHILE : 'while';
-
-// fx keywords ---------------------
-
-BLENDSTATE : 'blendstate';
-COMPILE : 'compile';
-DEPTHSTENCILSTATE : 'depthstencilstate';
-DEPTHSTENCILVIEW : 'depthstencilview';
-GEOMETRYSHADER : 'geometryshader';
-PASS : 'pass';
-PIXELSHADER : 'pixelshader';
-RASTERIZERSTATE : 'rasterizerstate';
-RENDERTARGETVIEW : 'rendertargetview';
-TECHNIQUE : 'technique';
-TECHNIQUE10 : 'technique10';
-VERTEXSHADER : 'vertexshader';
-
-
-// intrinsic functions --------------------
-ABS : 'abs';
-ACOS : 'acos';
-ALL : 'all';
-ANY : 'any';
-ASFLOAT : 'asfloat';
-ASIN : 'asin';
-ASINT : 'asint';
-ASUINT : 'asuint';
-ATAN : 'atan';
-ATAN2 : 'atan2';
-CEIL : 'ceil';
-CLAMP : 'clamp';
-CLIP : 'clip';
-COS : 'cos';
-COSH : 'cosh';
-CROSS : 'cross';
-DDX : 'ddx';
-DDY : 'ddy';
-DEGREES : 'degrees';
-DETERMINANT : 'determinant';
-DISTANCE : 'distance';
-DOT_PRODUCT : 'dot';
-EXP : 'exp';
-EXP2 : 'exp2';
-FACEFORWARD : 'faceforward';
-FLOOR : 'floor';
-FMOD : 'fmod';
-FRAC : 'frac';
-FREXP : 'frexp';
-FWIDTH : 'fwidth';
-ISFINITE : 'isfinite';
-ISINF : 'isinf';
-ISNAN : 'isnan';
-LDEXP : 'ldexp';
-LENGTH : 'length';
-LERP : 'lerp';
-LIT : 'lit';
-LOG : 'log';
-LOG10 : 'log10';
-LOG2 : 'log2';
-MAX : 'max';
-MIN : 'min';
-MODF : 'modf';
-MUL_FUNC : 'mul';
-NOISE : 'noise';
-NORMALIZE : 'normalize';
-POW : 'pow';
-RADIANS : 'radians';
-REFLECT : 'reflect';
-REFRACT : 'refract';
-ROUND : 'round';
-RSQRT : 'rsqrt';
-SATURATE : 'saturate';
-SIGN : 'sign';
-SIN : 'sin';
-SINCOS : 'sincos';
-SINH : 'sinh';
-SMOOTHSTEP : 'smoothstep';
-SQRT : 'sqrt';
-STEP : 'step';
-TAN : 'tan';
-TANH : 'tanh';
-TEX1D : 'tex1D';
-TEX1DBIAS : 'tex1Dbias';
-TEX1DGRAD : 'tex1Dgrad';
-TEX1DLOD : 'tex1Dlod';
-TEX1DPROJ : 'tex1Dproj';
-TEX2D : 'tex2D';
-TEX2DBIAS : 'tex2Dbias';
-TEX2DGRAD : 'tex2Dgrad';
-TEX2DLOD : 'tex2Dlod';
-TEX2DPROJ : 'tex2Dproj';
-TEX3D : 'tex3D';
-TEX3DBIAS : 'tex3Dbias';
-TEX3DGRAD : 'tex3Dgrad';
-TEX3DLOD : 'tex3Dlod';
-TEX3DPROJ : 'tex3Dproj';
-TEXCUBE : 'texCUBE';
-TEXCUBEBIAS : 'texCUBEbias';
-TEXCUBEGRAD : 'texCUBEgrad';
-TEXCUBELOD : 'texCUBElod';
-TEXCUBEPROJ : 'texCUBEproj';
-TRANSPOSE : 'transpose';
-TRUNC : 'trunc';
-
-
-
-// fundamental tokens ---------------------
-
-fragment HEXDIGIT
- : ('0'..'9'|'a'..'f'|'A'..'F')
- ;
-
-fragment UNICODE_ESCAPE
- : '\\' 'u' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT
- ;
-
-fragment OCTAL_ESCAPE
- : '\\' ('0'..'3') ('0'..'7') ('0'..'7')
- | '\\' ('0'..'7') ('0'..'7')
- | '\\' ('0'..'7')
- ;
-
-fragment ESCAPE_SEQUENCE
- : '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\')
- | UNICODE_ESCAPE
- | OCTAL_ESCAPE
- ;
-
-fragment EXPONENT : ('e'|'E') (PLUS | MINUS)? ('0'..'9')+ ;
-
-fragment FLOATSUFFIX : ('f'|'F'|'h'|'H') ;
-
-ID
- : ('a'..'z'|'A'..'Z'|'_')('a'..'z'|'A'..'Z'|'_'|'0'..'9')*
- {
- // check the length of the identifier before accepting it.
- if (($ID.length() > 96)) {
- RecognitionException();
- }
- }
- ;
-
-DECIMAL_LITERAL
- : ('1'..'9')('0'..'9')+
- ;
-
-OCT_LITERAL
- : ('0'..'3') ('0'..'7') ('0'..'7')
- | ('0'..'7') ('0'..'7')
- | ('0'..'7')
- ;
-
-HEX_LITERAL
- : '0x' HEXDIGIT+
- ;
-
-CHARACTER_LITERAL
- : '\'' ( ESCAPE_SEQUENCE | ~('\''|'\\') ) '\''
- ;
-
-STRING_LITERAL
- : ( ESCAPE_SEQUENCE | ~('\\'|'"') )*
- ;
-
-FLOAT_LITERAL
- : (PLUS | MINUS)? ('0'..'9')+ '.' ('0'..'9')* (EXPONENT)? (FLOATSUFFIX)?
- | (PLUS | MINUS)? '.' ('0'..'9')+ (EXPONENT)? (FLOATSUFFIX)?
- | (PLUS | MINUS)? ('0'..'9')+ (EXPONENT)? (FLOATSUFFIX)?
- ;
-
-// skipped elements -----------------
-
-WHITESPACE
- : ( ' ' | '\t' | '\f' | '\r' )
- { $channel = HIDDEN; }
- ;
-
-COMMENT
- : '//' (~('\n'|'\r'))*
- { $channel = HIDDEN; }
- ;
-
-MULTILINE_COMMENT
- : '/*' ( options {greedy=false;} : . )* '*/'
- { $channel = HIDDEN; }
- ;
-
-//RESERVED_WORDS
-// : 'auto'
-// | 'case'
-// | 'catch'
-// | 'char'
-// | 'class'
-// | 'const_cast'
-// | 'default'
-// | 'delete'
-// | 'dynamic_cast'
-// | 'enum'
-// | 'explicit'
-// | 'friend'
-// | 'goto'
-// | 'long'
-// | 'mutable'
-// | 'new'
-// | 'operator'
-// | 'private'
-// | 'protected'
-// | 'public'
-// | 'reinterpret_cast'
-// | 'short'
-// | 'signed'
-// | 'sizeof'
-// | 'snorm'
-// | 'static_cast'
-// | 'template'
-// | 'this'
-// | 'throw'
-// | 'try'
-// | 'typename'
-// | 'union'
-// | 'unorm'
-// | 'unsigned'
-// | 'using'
-// | 'varying'
-// | 'virtual'
-// { $channel = HIDDEN; }
-// ;
diff --git a/o3d/compiler/puritan/exp_gen.cc b/o3d/compiler/puritan/exp_gen.cc
deleted file mode 100644
index 29c126b..0000000
--- a/o3d/compiler/puritan/exp_gen.cc
+++ /dev/null
@@ -1,934 +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 <iostream>
-#include "puritan_assert.h"
-#include "exp_gen.h"
-#include "structure_gen.h"
-#include "knobs.h"
-
-namespace Salem
-{
-namespace Puritan
-{
-
-
-const char *f2tof_swizzle_names[] =
-{
- "x", "y", 0
-};
-
-StrCoverage f2tof_swizzles ("F2tof Swizzles",
- f2tof_swizzle_names);
-
-const char *f2tof2_swizzle_names[] =
-{
- "xx", "yy", "xy", "yx", 0
-};
-
-StrCoverage f2tof2_swizzles ("F2tof2 Swizzles",
- f2tof2_swizzle_names);
-
-const char *f4tof_swizzle_names[] =
-{
- "x", "y", "z", "w", 0
-};
-
-StrCoverage f4tof_swizzles ("F4tof Swizzles",
- f4tof_swizzle_names);
-
-const char *f4tof2_swizzle_names[] =
-{
- "xx", "xy", "xw", "xz",
- "yy", "yx", "yw", "yz",
- "wx", "wy", "ww", "wz",
- "zx", "zy", "zw", "zz",
- 0
-};
-
-StrCoverage f4tof2_swizzles ("F4tof2 Swizzles",
- f4tof2_swizzle_names);
-
-const char *f4tof4_swizzle_names[] =
-{
- "x", "y", "z", "w", 0
-};
-
-StrCoverage f4tof4_swizzles ("f4tof4 Swizzles",
- f4tof4_swizzle_names);
-
-//////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////
-// This code generates controlled random expressions for Puritan.
-
-// During generation, various knobs and random numbers determine the complexity
-// of the expression and push various operands into a list. Then the code
-// builds an expression tree removing things from the list until there's
-// nothing left.
-//
-
-//////////////////////////////////////////////////////////////////////
-
-// "frac" removed because it can cause discrepant CPU vs GPU results
-// - see ticket #3493
-const char *unfunc_names[] =
-{ "abs", /* "frac", */ "exp2", "log2",
- "rcp", "rsqrt", "sqrt", "!", 0
-};
-
-StrCoverage unfuncs ("Unary functions", unfunc_names);
-
-const char *binfunc_names[] =
-{ "max", "min", "dot", 0 };
-
-StrCoverage binfuncs ("Binary functions", binfunc_names);
-
-const char *trifunc_names[] =
-{ "mad", "opcond", 0};
-
-StrCoverage trifuncs ("Trinary functions", trifunc_names);
-
-const char *unop_names[] =
-{ "-", 0 };
-
-StrCoverage unops ("Unops", unop_names);
-
-const char *binop_names[] =
-{ "*", "/", "+", "-", 0 };
-
-StrCoverage binops ("Binops", binop_names);
-
-// "eq", "ne" removed because these are very sensitive to precision errors
-// and could cause discrepant CPU vs GPU results
-const char *relop_names[] =
-{
- "lt", "le", "gt", "ge",
- /* "eq", "ne", */ "and", "or",
- 0
-};
-
-StrCoverage relops ("Relops", relop_names);
-
-const char *special_names[] =
-{
- "* 2.0", "* 4.0", "* 8.0",
- "/ 2.0", "/ 4.0", "/ 8.0",
- "1.0 -", "1.0-2.0*", 0
-};
-
-StrCoverage special ("Special", special_names);
-
-std::ostream & operator << (std::ostream & out,
- const ENode & x)
-{
- x->print (out);
- return out;
-}
-
-void print_e (const ENode &x)
-{
- std::cerr << x;
-}
-
-std::ostream & operator << (std::ostream & out,
- const EList & x)
-{
- bool need_comma = false;
-
- for (EList::const_iterator i = x.begin (); i != x.end ();
- i++)
- {
- if (need_comma)
- {
- out << ", ";
- }
- out << *i;
- need_comma = true;
- }
- return out;
-}
-
-//////////////////////////////////////////////////////////////////////
-// Generate expressions..
-
-// Remove one operand from the stack of expressions and convert it to the
-// prevailing type.
-
-ENode one_arg (exp_list * exp, Rand * rand, const Type & type, Gen *gen)
-{
- PURITAN_ASSERT (!exp->empty (), "Ran out of expressions");
- ENode arg = exp->back ();
-
- exp->pop_back ();
-
- return ENode (Exp::convert (arg, rand, type, gen));
-}
-
-// Create an expression tree returning with type RETURN_TYPE.
-ENode create_expression (Gen * gen, Type return_type, const Context & ctx)
-{
- Rand *rand = &gen->rand;
- static int depth;
- Type type = return_type;
- const Knobs & knobs = gen->knobs;
- exp_list exp;
-
- depth++;
-
- // We create some things regardless of the complexity settings.
- if (return_type == Float4 && knobs.float4_chance (rand))
- {
- // Make more args - call create_expression out of the arg list
- // because otherwise the expression eval order will be undefined.
- ENode a0 = (create_expression (gen, Float, ctx.deeper ()));
- ENode a1 = (create_expression (gen, Float, ctx.deeper ()));
- ENode a2 = (create_expression (gen, Float, ctx.deeper ()));
- ENode a3 = (create_expression (gen, Float, ctx.deeper ()));
-
- exp.push_back (ENode (new Float4Func (Float4, a0, a1, a2, a3)));
- }
-
- if (return_type == Float2 && knobs.float2_chance (rand))
- {
- ENode a0 = (create_expression (gen, Float, ctx.deeper ()));
- ENode a1 = (create_expression (gen, Float, ctx.deeper ()));
-
- exp.push_back (ENode (new BiIntrinsicFunc (Float2, "float2", a0, a1)));
- }
-
- if (ctx.callees && !ctx.callees->empty ())
- {
- FunctionSPtr target = ctx.callees->front ();
- EList actuals;
-
- ctx.callees->pop_front ();
-
- for (DeclList::iterator ai = target->formals.begin ();
- ai != target->formals.end ();
- ai++)
- {
- switch (ai->scope.scope)
- {
- // input argument can be any expression
- case Argument_IO:
- case Argument_I:
- {
- ENode actual = create_expression (gen, ai->type, ctx.deeper ());
- actuals.push_back (actual);
- break;
- }
- case Argument_O:
- {
- ENode actual (new Variable
- (gen->fetch_decl (ai->type,
- ctx.deeper (),
- Uninitialized,
- Read)));
-
- actuals.push_back (actual);
- break;
- }
-
- default:
- case Uniform:
- case Static:
- case StaticConstArrays:
- case Sampler:
- case NoScope:
- {
- PURITAN_ABORT ("Bad scope" << ai->scope.scope);
- break;
- }
- }
- }
-
- exp.push_back
- (ENode (new FCallTemplate (target->ret_type, target, actuals)));
- }
-
- if (ctx.samplers && !ctx.samplers->empty ())
- {
- // Have to get the arguments in range
- // tex2D (id<n>, <exp> % id<n>_size)
- unsigned sampler = ctx.samplers->front ();
-
- ctx.samplers->pop_front ();
- ENode lhs = create_expression (gen, Float4, ctx.deeper ());
- ENode rhs (new SamplerSizeRef (sampler));
- ENode mod (new BiIntrinsicFunc (Float4, "quick_mod", lhs, rhs));
-
- exp.push_back (ENode (new SamplerRef (sampler, mod)));
- }
-
- // Build as many terms as we were asked for.
- int l = gen->knobs.expression_depth (rand);
-
- // Children functions get fewer nodes.
- if (ctx.func)
- {
- l = l * 4 / 6 + 1;
- }
-
- for (int i = 0; i < l; i++)
- {
- if (knobs.type_change_chance (rand))
- {
- type = gen->random_type ();
- }
-
- if (knobs.array_use (rand))
- {
- Type t = knobs.array_constness (rand)
- ? Float4ConstArray : Float4Array;
-
- Decl decl = gen->gen_array_decl (t, ctx.deeper (), Read);
- ENode v (new Variable (decl));
- ENode idx;
-
- if (knobs.array_index_const (rand) || ctx.loop.get() == NULL)
- {
- idx = ENode (new Constant (Float,
- rand->range (0, array_size)));
- }
- else
- {
- idx = ENode (new Variable (ctx.loop->counter));
- }
-
- ENode id (new Index (v, idx));
- exp.push_back (id);
- }
- else
- {
- if (knobs.uniform_chance (rand) && gen->n_uniforms)
- {
- size_t uni_idx = rand->srange (0, gen->n_uniforms);
- std::vector <std::pair <Type, string> >::iterator uni
- = gen->uniforms.begin () + uni_idx;
- ENode e (new UniformRef (uni->first, uni->second));
- exp.push_back (e);
- }
- else if (ctx.depth > 10 || knobs.constant_use (rand))
- {
- ENode e (new Constant (Float, gen->gen_fconstant ()));
- exp.push_back (e);
- }
- else
- {
- Type t
- = knobs.type_change_chance (rand)
- ? gen->random_type () : type;
-
- Decl decl = gen->fetch_decl (t,
- ctx.deeper (),
- Initialized,
- Read);
- ENode v (new Variable (decl));
-
- exp.push_back (v);
- }
- }
-
- // Stop making nodes if we've gone too far.
- gen->exp_nodes++;
- if (gen->exp_nodes >= knobs.exp_limit.uget ())
- {
- break;
- }
- }
-
- // Now add enough operators to consume all but one of the terms, the final
- // term is the result of the expression.
-
- bool no_more_unarys = false;
-
- while (exp.size () != 1)
- {
- if ((type == Float
- && knobs.relop_chance (rand))
- || (ctx.relop_p
- && exp.size () < 3 && knobs.relop_cond_chance (rand)))
- {
- exp.push_back
- (ENode (new Relop (relops.choose (rand),
- one_arg (&exp, rand, Float, gen),
- one_arg (&exp, rand, Float, gen))));
-
- }
- else if (knobs.special_chance (rand))
- {
- exp.push_back
- (ENode (new SpecialPhrase (type,
- special.choose (rand),
- one_arg (&exp, rand, type, gen))));
- }
- else if (knobs.func_chance (rand))
- {
- if (exp.size () > 2 && knobs.trifunc_chance (rand))
- {
- string name = trifuncs.choose (rand);
-
-
- // name of opcond function changes by type
- if (name == "opcond")
- {
- switch (type.type)
- {
- case Float4:
- name = "opcond4";
- break;
- case Float2:
- name = "opcond2";
- break;
- case Float:
- name = "opcond";
- break;
- case NoType:
- case Int:
- case Int4:
- case SamplerFloat4:
- case SamplerSize:
- case Struct:
- case Float4ConstArray:
- case Float4Array:
- default:
- PURITAN_ABORT ("Illegal type for opcond" << type.type) ;
- break;
- }
- }
-
- exp.push_back
- (ENode (new TriIntrinsicFunc (type,
- name,
- one_arg (&exp, rand, type, gen),
- one_arg (&exp, rand, type, gen),
- one_arg (&exp, rand, type, gen))));
- }
- else if (exp.size () > 1 && knobs.binfunc_chance (rand))
- {
- string f = binfuncs.choose (rand);
- Type ret_type = f == "dot" ? Float : type;
-
- ENode lhs = one_arg (&exp, rand, type, gen);
- ENode rhs = one_arg (&exp, rand, type, gen);
- exp.push_back
- (ENode (new BiIntrinsicFunc (ret_type,
- f,
- lhs,
- rhs)));
- type = ret_type;
- }
- else
- {
- exp.push_back
- (ENode (new UnIntrinsicFunc (type,
- unfuncs.choose (rand),
- one_arg (&exp, rand, type, gen))));
- }
- }
- else if (!no_more_unarys && knobs.unary_chance (rand))
- {
- exp.push_back (ENode (new Unop (type,
- unops.choose (rand),
- one_arg (&exp, rand, type, gen))));
- }
- else if (knobs.swizzle_chance (rand))
- {
- exp.push_back (Exp::convert (one_arg (&exp, rand, type, gen), rand, type, gen));
- }
- else
- {
- exp.push_back
- (ENode (new Binop (type, binops.choose (rand),
- one_arg (&exp, rand, type, gen),
- one_arg (&exp, rand, type, gen))));
- }
- }
-
- return Exp::convert (exp.back (), rand, return_type, gen);
-
-}
-//////////////////////////////////////////////////////////////////////
-/// ENode Template, base class for all expression nodes.
-
-Exp::Exp (Type _type) :type (_type)
-{
-}
-
-Exp::~ Exp ()
-{
-}
-
-bool Exp::is_fconstant () const
-{
- return false;
-}
-
-// Convert a tree from one type to another, return the new tree.
-ENode Exp::convert (ENode from, Rand * rand, Type to, Gen *gen)
-{
- string pre;
- string post;
- unsigned n = 1;
-
- if (from->type == to.type && !gen->knobs.copy_swizzle_chance (rand))
- {
- n = 0;
- }
- else if (from->type == Float && to.type == Float)
- {
-
- }
- else if (from->type == Float2 && to.type == Float2)
- {
- post = f2tof2_swizzles.choose (rand);
- }
- else if (from->type == Float && to.type == Float2)
- {
- n = 1;
- pre = "float2";
- }
- else if (from->type == Float && to.type == Float4)
- {
- n = 1;
- pre = "float4";
- }
- else if (from->type == Float2 && to.type == Float)
- {
- post = f2tof_swizzles.choose (rand);
- }
- else if (from->type == Float2 && to.type == Float4)
- {
- // Can't spread out a float2
- pre = "float4";
- n = 2;
- }
- else if (from->type == Float4 && to.type == Float)
- {
- post = f4tof_swizzles.choose (rand);
- }
- else if (from->type == Float4 && to.type == Float2)
- {
- post = f4tof2_swizzles.choose (rand);
- }
- else if (from->type == Float4 && to.type == Float4)
- {
- for (unsigned i = 0; i < 4; i++)
- post += f4tof4_swizzles.choose (rand);
- }
- else
- {
- PURITAN_ABORT ("Bad args in convert");
- }
-
- if (from->is_fconstant ())
- {
- n = 1;
- }
- return ENode (new Convert (to, from->type, pre, post, n, from));
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Boilerplate
-
-A0::A0 (Type ty) :Exp (ty)
-{
-}
-
-A1::A1 (Type ty, ENode _child) :Exp (ty), child (_child)
-{
-}
-
-A2::A2 (Type ty, ENode _lhs, ENode _rhs) :Exp (ty),
- lhs (_lhs), rhs (_rhs)
-{
-}
-
-A3::A3 (Type ty, ENode _a0, ENode _a1,
- ENode _a2) :Exp (ty), a0 (_a0), a1 (_a1),
- a2 (_a2)
-{
-}
-
-A4::A4 (Type ty, ENode _a0, ENode _a1, ENode _a2,
- ENode _a3) :Exp (ty), a0 (_a0), a1 (_a1),
- a2 (_a2), a3 (_a3)
-{
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Unary operations
-
-Unop::Unop (Type ty, string _name, ENode _child)
- :A1 (ty, _child), name (_name)
-{
-}
-
-void Unop::print (ostream & out) const
-{
- out << " ( " << name << " " << child << ") ";
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Function calls.
-
-FCallTemplate::FCallTemplate (TypeList ty,
- FunctionSPtr _target,
- EList _actuals)
- :Exp (ty.front ()), target (_target), actuals (_actuals)
-{
-}
-
-void FCallTemplate::print (ostream & out) const
-{
- out << "func" << target->idx << " (" << actuals << ")";
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Sampler references.
-
-SamplerRef::SamplerRef (unsigned _n, ENode _child)
- :A1 (Float4, _child), n (_n)
-{
-}
-
-void SamplerRef::print (ostream & out) const
-{
- out << "tex2D (in" << n << ", " << child << ")";
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Sampler references.
-
-SamplerSizeRef::SamplerSizeRef (unsigned _n)
- :A0 (Float4), n (_n)
-{
-}
-
-void SamplerSizeRef::print (ostream & out) const
-{
- out << "in" << n << "_size";
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Uniform references.
-
-UniformRef::UniformRef (Type ty, string v)
- :A0 (ty), name (v)
-{
-}
-
-void UniformRef::print (ostream & out) const
-{
- out << name;
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Constants.
-
-Constant::Constant (Type ty, string _val)
- :A0 (ty), val (_val)
-{
-}
-
-void Constant::print (ostream & out) const
-{
- out << val;
-}
-
-Constant::Constant (Type ty, unsigned _val)
- :A0 (ty)
-{
- ostringstream o;
-
- o << _val;
- val = (o.str ());
-}
-bool Constant::is_fconstant () const
-{
- return true;
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Variables.
-
-Variable::Variable (Decl _d)
- :A0 (_d.type ()), decl (_d)
-{
-}
-
-void Variable::print (ostream & out) const
-{
- out << " " << decl;
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Indexes into arrays.
-
-Index::Index (ENode child, ENode idx)
- :A2 (Float4, child, idx)
-{
-}
-
-void Index::print (ostream & out) const
-{
- out << lhs << "[" << rhs << "]";
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Constant array references.
-
-ConstArrayRef::ConstArrayRef (Decl _d)
- :A0 (Float4), decl (_d)
-{
-}
-
-void ConstArrayRef::print (ostream & out) const
-{
- out << " " << decl;
-}
-
-//////////////////////////////////////////////////////////////////////
-/// lhs swizzles
-
-Swizzle::Swizzle (Type ty, string _name, ENode _child)
- : A1 (ty, _child), name (_name)
-{
-
-}
-
-void Swizzle::print (ostream & out) const
-{
- out << child << "." << name;
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Variables on the LHS of an assignment.
-
-LHSVariable::LHSVariable (Decl _d, bool _swizzled)
- :Exp (_d.type ()), decl (_d), swizzled (_swizzled)
-{
-}
-
-void LHSVariable::print (ostream & out) const
-{
- out << " " << decl;
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Special phrases.
-
-SpecialPhrase::SpecialPhrase (Type t, string _name, ENode _child)
- :A1 (t, _child), name (_name)
-{
-}
-
-void SpecialPhrase::print (ostream & out) const
-{
- if (name[0] == '1')
- {
- out << " " << name << child;
- }
- else
- {
- out << child << " " + name;
- }
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Unary intrinsic
-
-UnIntrinsicFunc::UnIntrinsicFunc (Type ty, string _name,
- ENode _child)
- :A1 (ty, _child),
- name (_name)
-{
-}
-
-void UnIntrinsicFunc::print (ostream & out) const
-{
- if (name == "!")
- {
- out << "(!(" << child << "))";
- }
- else
- {
- out << " " << name << " (" << child << ")";
- }
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Binary intrinsic
-
-BiIntrinsicFunc::BiIntrinsicFunc (Type ty, string _name,
- ENode _lhs, ENode _rhs)
- :A2 (ty, _lhs, _rhs), name (_name)
-{
-}
-
-void BiIntrinsicFunc::print (ostream & out) const
-{
- out << " " << name << " (" << lhs << ", " << rhs << ")";
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Tri intrinsic
-
-TriIntrinsicFunc::TriIntrinsicFunc (Type ty,
- string _name,
- ENode _a1,
- ENode _a2,
- ENode _a3)
- :A3 (ty, _a1, _a2, _a3), name (_name)
-{
-}
-
-void TriIntrinsicFunc::print (ostream & out) const
-{
- out << name << "(" << a0 << ", " << a1 << ", " << a2 << ")";
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Float4
-
-Float4Func::Float4Func (Type ty, ENode _a1, ENode _a2,
- ENode _a3, ENode _a4)
- :A4 (ty, _a1, _a2, _a3, _a4)
-{
-}
-
-void Float4Func::print (ostream & out) const
-{
- out << "float4 (" << a0 << ", " << a1 << ", " << a2 << ", " << a3
- << ")";
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Convert
-
-Convert::Convert (Type to,
- Type _from,
- string _pre, string _post, unsigned _n,
- ENode _child)
- :A1 (to, _child), from (_from), pre (_pre), post (_post), n (_n)
-{
-}
-
-void Convert::print (ostream & out) const
-{
- if (n == 0)
- {
- out << child;
- }
- else
- {
- out << pre << " (";
- for (unsigned i = 0; i < n; i++)
- {
- if (i)
- {
- out << ", ";
- }
- out << child;
- }
- out << ")";
- if (!post.empty ())
- {
- out << "." << post;
- }
- }
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Binop
-
-Binop::Binop (Type ty, string _name, ENode _lhs,
- ENode _rhs)
- :A2 (ty, _lhs, _rhs),
- name (_name)
-{
-}
-
-void Binop::print (ostream & out) const
-{
- out << lhs << " " << name << " " << rhs;
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Relop
-
-Relop::Relop (string _name, ENode _lhs, ENode _rhs)
- :A2 (Float, _lhs, _rhs),
- name (_name)
-{
-}
-
-void Relop::print (ostream & out) const
-{
- out << "op" << name << type.suffix_name() << "(" << lhs << ", " << rhs << ")";
-}
-
-//////////////////////////////////////////////////////////////////////
-/// AssOp
-
-AssOp::AssOp (Type ty, string _name, ENode _lhs, ENode _rhs)
- :A2 (ty, _lhs, _rhs),
- name (_name)
-{
-}
-
-void AssOp::print (ostream & out) const
-{
- out << lhs << " " << name << " " << rhs;
-}
-
-//////////////////////////////////////////////////////////////////////
-/// SelfModOp
-
-SelfModOp::SelfModOp (Type ty, string _name, ENode _child)
- :A1 (ty, _child),
- name (_name)
-{
-}
-
-void SelfModOp::print (ostream & out) const
-{
- out << child << " " << name;
-}
-
-//////////////////////////////////////////////////////////////////////
-///
-
-//////////////////////////////////////////////////////////////////////
-
-}
-}
diff --git a/o3d/compiler/puritan/exp_gen.h b/o3d/compiler/puritan/exp_gen.h
deleted file mode 100644
index 9387d98..0000000
--- a/o3d/compiler/puritan/exp_gen.h
+++ /dev/null
@@ -1,331 +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 PURITAN_EXPGEN_H
-#define PURITAN_EXPGEN_H
-#include "puritan.h"
-
-// Expression trees.
-namespace Salem
-{
-namespace Puritan
-{
-class Exp;
-class Gen;
-class Type;
-class Context;
-typedef ::shared_ptr<Exp> ENode;
-typedef std::vector <ENode> exp_list;
-// Make a tree.
-ENode create_expression (Gen *gen, Type return_type, const Context &ctx);
-
-// Print it out.
-std::ostream & operator<< (std::ostream &out, const ENode &x);
-
-class Exp
-{
-public:
- Type type;
- Exp (Type _type) ;
- virtual ~Exp();
-
- virtual void print (ostream &out) const = 0;
- virtual bool is_fconstant() const;
-
- static ENode convert (ENode from, Rand *rand, Type to, Gen *gen);
-};
-
-class A0 : public Exp
-{
-public:
- A0 (Type ty);
-};
-
-class A1 : public Exp
-{
-public:
- ENode child;
- A1 (Type ty, ENode child);
-};
-
-class A2 : public Exp
-{
-public:
- ENode lhs;
- ENode rhs;
- A2(Type ty,
- ENode lhs,
- ENode rhs);
-};
-
-class A3 : public Exp
-{
-public:
- ENode a0;
- ENode a1;
- ENode a2;
-
- A3(Type ty,
- ENode a0,
- ENode a1,
- ENode a2);
-};
-
-class A4 : public Exp
-{
-public:
- ENode a0;
- ENode a1;
- ENode a2;
- ENode a3;
-
- A4(Type ty,
- ENode a0,
- ENode a1,
- ENode a2,
- ENode a3);
-};
-
-class Unop : public A1
-{
- string name;
-
-public:
- Unop(Type ty, string _name, ENode child) ;
- void print (ostream &out) const;
-};
-
-class FCallTemplate : public Exp
-{
-public:
- FunctionSPtr target;
- EList actuals;
-
- FCallTemplate (TypeList ty, FunctionSPtr f, EList actuals);
- void print (ostream &out) const;
-};
-
-class SamplerRef : public A1
-{
- unsigned n;
-
-public:
- SamplerRef (unsigned _n, ENode _child) ;
- void print (ostream &out) const;
-};
-
-class SamplerSizeRef : public A0
-{
- unsigned n;
-
-public:
- SamplerSizeRef (unsigned _n);
- void print (ostream &out) const;
-};
-
-class UniformRef : public A0
-{
- string name;
-
-public:
- UniformRef (Type ty, string v);
- void print (ostream &out) const;
-};
-
-class Constant : public A0
-{
- string val;
-public:
- Constant (Type ty, string v);
- Constant (Type ty, unsigned v);
- bool is_fconstant() const;
- void print (ostream &out) const;
-};
-
-class Variable : public A0
-{
- Decl decl;
-
-public:
- Variable (Decl _d) ;
- void print (ostream &out) const;
-};
-
-
-class Index : public A2
-{
-public:
- Index (ENode child, ENode index);
- void print (ostream &out) const;
-
-};
-
-class ConstArrayRef : public A0
-{
- Decl decl;
-public:
- ConstArrayRef (Decl _d);
- void print (ostream &out) const;
-};
-
-class LHSVariable : public Exp
-{
- Decl decl;
- bool swizzled;
-
-public:
- LHSVariable (Decl _d, bool _swizzled) ;
-
- void print (ostream &out) const;
-};
-
-class SpecialPhrase : public A1
-{
- string name;
-
-public:
- SpecialPhrase (Type , string name, ENode _child);
-
- void print (ostream &out) const;
-};
-
-class UnIntrinsicFunc : public A1
-{
- string name;
-
-public:
- UnIntrinsicFunc(Type ty, string _name, ENode) ;
-
- void print (ostream &out) const;
-};
-
-class BiIntrinsicFunc : public A2
-{
- string name;
-
-public:
- BiIntrinsicFunc(Type ty, string _name, ENode _lhs, ENode _rhs) ;
-
- void print (ostream &out) const;
-};
-
-class TriIntrinsicFunc : public A3
-{
- string name;
-public:
- TriIntrinsicFunc(Type ty, string _name, ENode _a1, ENode _a2, ENode _a3);
-
- void print (ostream &out) const;
-};
-
-class Float4Func : public A4
-{
-public:
- Float4Func(Type ty, ENode _a1, ENode _a2, ENode _a3, ENode _a4);
-
- void print (ostream &out) const;
-};
-
-class Convert : public A1
-{
- Type from;
- string pre;
- string post;
- unsigned n;
-
-public:
- Convert (Type _to,
- Type _from,
- string pre,
- string post,
- unsigned n,
- ENode _child);
-
- void print (ostream &out) const;
-};
-
-
-class Swizzle : public A1
-{
- string name;
-public:
- Swizzle (Type ty, string _name, ENode _child) ;
-
- void print (ostream &out) const;
-};
-
-class Binop : public A2
-{
- string name;
-
-public:
- Binop(Type ty, string _name, ENode _lhs, ENode _rhs) ;
-
- void print (ostream &out) const;
-};
-
-class Relop : public A2
-{
- string name;
-
-public:
- Relop(string _name, ENode _lhs, ENode _rhs) ;
- void print (ostream &out) const;
-};
-
-class AssOp : public A2
-{
- string name;
-
-public:
- AssOp(Type ty,
- string _name,
- ENode lhs,
- ENode rhs);
-
- void print (ostream &out) const;
-};
-
-class SelfModOp : public A1
-{
- string name;
-
-public:
- SelfModOp(Type ty, string _name, ENode lhs);
- void print (ostream &out) const;
-};
-
-}
-}
-#endif
-
diff --git a/o3d/compiler/puritan/knobs.cc b/o3d/compiler/puritan/knobs.cc
deleted file mode 100644
index d36a89e..0000000
--- a/o3d/compiler/puritan/knobs.cc
+++ /dev/null
@@ -1,783 +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 "knobs.h"
-#include <sstream>
-#include <iomanip>
-#include <iostream>
-#include "rand.h"
-
-#ifdef _MSC_VER
-#define snprintf _snprintf
-#endif
-
-// Knobs control the behavior of Puritan and keep track of what's happened.
-
-namespace Salem
-{
-namespace Puritan
-{
-static Knob *link;
-
-Knobs::Knobs (void)
- :
- top_level_statements
-("--top-level-statements",
- "\t\tNumber of statements at the top level\n",
- 1,
- 3),
-
- for_count
- ("--for-count",
- "\t\tNumber of for loops in code\n",
- 0,
- 2),
-
- while_count
- ("--while-count",
- "\t\tNumber of while loops in code\n",
- 0,
- 2),
-
- do_count
- ("--do-count",
- "\t\tNumber of do loops in code\n",
- 0,
- 1),
-
- if_count
- ("--if-count",
- "\t\tNumber of ifs in code\n",
- 0,
- 5),
-
- block_count
- ("--block-count",
- "\t\tNumber of blocks in code\n",
- 0,
- 3),
-
- code_limit
- ("--code-limit",
- "\t\tMaximum number of code nodes\n",
- 200),
-
- exp_limit
- ("--exp-limit",
- "\t\tMaximum number of expression nodes\n",
- 100),
-
- exp_count
- ("--exp-count",
- "\t\tNumber of expressions in code\n",
- 6,
- 16),
-
- func_count
- ("--func-count",
- "\t\tNumber of functions in code\n",
- 1,
- 9),
-
- func_trim
- ("--func-trim",
- "\t\tSize factor to apply to callee functions\n",
- 0.7),
-
- arg_in_chance
- ("--args-in-chance",
- "\t\tChance argument may be just input\n",
- 0.4),
-
- arg_out_chance
- ("--args-out-chance",
- "\t\tAfter input, chance argument may be just output\n",
- 0.4),
-
- for_nesting
- ("--for-nest",
- "\t\tNumber of for loops inside for loops\n",
- 0,
- 9),
-
- while_nesting
- ("--while-nest",
- "\t\tNumber of while loops inside while loops\n",
- 0,
- 4),
-
- block_nesting
- ("--block-nest",
- "\t\tNumber of blocks inside blocks\n",
- 0,
- 1),
-
- do_nesting
- ("--do-nest",
- "\t\tNumber of do loops inside do loops\n",
- 0,
- 4),
-
- if_nesting
- ("--if-nest",
- "\t\tNumber of ifs inside ifs\n",
- 0,
- 9),
-
- block_length
- ("--block-length",
- "\t\tNumber of statements in a block.\n",
- 2,
- 7),
-
- expression_depth
- ("--exp-depth",
- "\t\tRange of expression complexity\n",
- 1,
- 7),
-
- special_chance
- ("--special-chance",
- "\t\tProbability at each expression point of a special phrase.\n",
- 0.2),
-
- float4_chance
- ("--float4-chance",
- "\t\tProbability that an expression will have a float4 constructor.\n",
- .03),
-
- float4_struct_member_chance
- ("--float4-struct-member-chance",
- "\t\tProbability that an element of the output struct will be float4.\n",
- .90),
-
- float2_chance
- ("--float2-chance",
- "\t\tProbability that an expression will have a float2 constructor.\n",
- 0.03),
-
- func_chance
- ("--func-chance",
- "\t\tAfter special, probability of an intrinsic function.\n",
- 0.1),
-
- term_chance
- ("--terminal-chance",
- "\t\tAfter func, probability a terminal.\n",
- 0.2),
-
- unary_chance
- ("--unary-chance",
- "\t\tAfter terminal, probabaility of a unary op.\n",
- 0.05),
-
- swizzle_chance
- ("--swizzle-chance",
- "\t\tAfter unrary, chance that term will be a swizzle.\n",
- 0.35),
-
- fcall_chance
- ("--fcall-chance",
- "\t\tAfter swizzle, probability of a function call.\n",
- 0.25),
-
- copy_swizzle_chance
- ("--copy-swizzle-chance",
- "\t\tChance a simple non converting copy will be a swizzle.\n",
- 0.3),
-
- noinline_chance
- ("--fnoinline-chance",
- "\t\tProbability a function will be declared noinline.\n",
- 0.25),
-
- lhs_swizzle_chance
- ("--lhs-swizzle-chance",
- "\t\tProbabaility of a swizzle as an lval.\n",
- 1.0),
-
- assop_chance
- ("--assop-chance",
- "\t\tProbability of a fancy assignment operator as assignment.\n",
- 0.1),
-
- selfmod_chance
- ("--selfmod-chance",
- "\t\tProbability that an assignment will really be a selfmodify.\n",
- 0.1),
-
- trifunc_chance
- ("--trifunc-chance",
- "\t\tProbability of a trinary intrinsic.\n",
- 0.2),
-
- binfunc_chance
- ("--binary-chance",
- "\t\tAfter trinary, probabaility of a binary intrinsic instead of unary.\n",
- 0.8),
-
- relop_chance
- ("--relop-chance",
- "\t\tIf there's going to be a binop,"
- "probability that it will be a relation.\n",
- 0.1),
-
- relop_cond_chance
- ("--relop-cond-chance",
- "\t\tNear the end of an expression in a test, "
- "chance that the op will be a compare\n",
- 0.9),
-
- type_change_chance
- ("--type-change-chance",
- "\t\tProbability that the type of a subexpression will be different "
- "to the expression.\n",
- 0.01),
-
- type_float4_chance
- ("--type-float4-chance",
- "\t\tProbability that a subexpression type will be float4.\n",
- 0.9),
-
- type_float2_chance
- ("--type-float2-chance",
- "\t\tAfter float4,"
- "probability that a subexpression type will be float2 instead of float.\n",
- 0.9),
-
- sampler_count
- ("--sampler-count",
- "\t\tNumber of samplers used\n",
- 0,
- 9),
-
- sampler_chance
- ("--sampler-chance",
- "\t\tProbability that an expression will use a sampler\n",
- .4),
-
- uniform_count
- ("--uniform-count",
- "\t\tNumber of unforms used\n",
- 0,
- 9),
-
- uniform_chance
- ("--unform-chance",
- "\t\tProbability that an expression will use a uniform\n",
- .4),
-
- arg_count
- ("--arg-count",
- "\t\tNumber of arguments to functions\n",
- 1,
- 3),
-
- static_initializer_depth
- ("--static-initializer-depth",
- "\t\tRange of static initializer expression complexity\n",
- 1,
- 2),
-
- standalone
- ("--standalone",
- "\t\tIf the output should work outside the framework\n",
- false),
-
- seed
- ("--seed",
- "\t\tSeed for the random number generator\n",
- 0),
-
- variable_reuse
- ("--variable-reuse",
- "\t\tRatio of variables reused to created in expressions\n",
- 0.90),
-
- array_use
- ("--array-use",
- "\t\tRatio of array terms in terms in expressions\n",
- 0.2),
-
- array_reuse
- ("--array-reuse",
- "\t\tRatio of array terms reused to created in expressions\n",
- 0.95),
-
- array_constness
- ("--array-constness",
- "\t\tProportion of array refs which are references to const arrays\n",
- 1.),
-
- array_index_const
- ("--array-index-const",
- "\t\tProportion of array references which have a constant index\n",
- 1.),
-
- array_in_for_use
- ("--array-in-for",
- "\t\tProportion of array references which use a loop index, lhs only.\n",
- 0.),
-
- if_elses
- ("--if-elses",
- "\t\tProportion of ifs which have elses.\n",
- 0.30),
-
- loop_breaks
- ("--loop-breaks",
- "\t\tProportion of loops which have breaks.\n",
- 0.80),
-
- multiple_stmt
- ("--multiple-stmt",
- "\t\tRatio of single statements to blocks.\n",
- 0.30),
-
- constant_use
- ("--constant-use",
- "\t\tRatio of constants to variables in expressions.\n",
- 0.30),
-
- constant_small
- ("--constant-small",
- "\t\tChance a constant will be between 0 and 1.\n",
- 0.90),
-
-// random_names
-// ("--random-names",
-// "\t\tShould names be random or easy on the eyes\n",
-// false),
-
- int_variables
- ("--int-variables",
- "\t\tDeclare integer variables and use them in expressions\n",
- false),
-
- allow_two_negs
- ("--allow-two-negs",
- "\t\tAllow two negs in an expression\n",
- false),
- first (link)
-{
- link = 0;
-}
-
-RangeKnob::RangeKnob (const char *_name,
- const char *_help,
- int _from, int _to)
- :Knob (_name, _help),
- from (_from), to (_to)
-{
-}
-
-IntKnob::IntKnob (const char *_name,
- const char *_help,
- int _val)
- :Knob (_name, _help), val (_val)
-{
-}
-
-BoolKnob::BoolKnob (const char *_name,
- const char *_help,
- bool _x)
- :Knob (_name, _help), val (_x)
-{
-}
-
-ProbKnob::ProbKnob (const char *_name,
- const char *_help,
- double _x)
- :Knob (_name, _help), prob (_x)
-{
-}
-
-void RangeKnob::set (int a, int b)
-{
- from = a;
- to = b;
-}
-
-// link together the members so we can iterate simply through the struct
-// elements.
-
-
-Knob::~Knob ()
-{
-}
-
-Knob::Knob (const char *_name, const char *_help)
- :prev (link),
- name (_name), help (_help)
-{
- link = this;
-}
-
-
-void RangeKnob::to_stream (std::ostream & out) const
-{
- out << name << "=" << from;
- if (from != to)
- out << "," << to;
-}
-
-void IntKnob::to_stream (std::ostream & out) const
-{
- out << name << "=" << val;
-}
-
-void BoolKnob::to_stream (std::ostream & out) const
-{
- out << name << "=" << (val ? "t" : "f") ;
-}
-
-void BoolKnob::usage (std::ostream & out) const
-{
- out << (name) << "=" << "[t|f] ";
- out << (val ? "{t}" : "{f}") << "\n" << help;
-}
-
-void ProbKnob::usage (std::ostream & out) const
-{
- char t[1000];
- sprintf (t, "%s = <0.0 <= x <= 1.0> {%g}\n%s", name, prob, help);
- out << t;
-}
-
-void IntKnob::usage (std::ostream & out) const
-{
- out << (name) << "=" << "<int>";
- out << " {" << val << "}\n" << help;
-}
-
-void RangeKnob::usage (std::ostream & out) const
-{
- out << (name) << "=" << "<int>,<int>";
- out << " {" << from;
- if (from != to)
- out << "," << to;
- out << "}\n" << help;
-}
-
-bool BoolKnob::set_from_argument (const char *arg)
-{
- if (arg[0] == 't' || arg[0] == '1')
- {
- val = true;
- return true;
- }
- if (arg[0] == 'f' || arg[0] == '0')
- {
- val = false;
- return true;
- }
- return false;
-}
-
-bool ProbKnob::set_from_argument (const char *arg)
-{
- char *finish;
- prob = strtod (arg, &finish);
- return (arg != finish);
-}
-
-bool IntKnob::set_from_argument (const char *arg)
-{
- char *finish;
- val = strtol (arg, &finish, 0);
- return (arg != finish);
-}
-
-int IntKnob::get () const
-{
- return val;
-}
-
-unsigned IntKnob::uget () const
-{
- return val;
-}
-
-bool RangeKnob::set_from_argument (const char *val)
-{
- long int a, b;
- char *next;
- a = strtol (val, &next, 0);
-
- if (next == val)
- {
- return false;
- }
-
- if (*next == 0)
- {
- from = a;
- to = a;
- return true;
- }
-
- if (*next != ',')
- {
- return false;
- }
-
- char *next_2;
- next++;
- b = strtol (next, &next_2, 0);
- if (next_2 == next || *next_2 != 0)
- return false;
-
- from = a;
- to = b;
- return true;
-}
-
-bool Knobs::parse_argument (const char *arg)
-{
- for (Knob * l = first; l; l = l->prev)
- {
- if (strncmp (l->name, arg, strlen (l->name)) == 0)
- {
- const char *val = strchr (arg, '=');
- if (val)
- return l->set_from_argument (val + 1);
- }
- }
- return false;
-}
-
-std::ostream & operator << (std::ostream &out, const Knobs& x)
-{
- unsigned j = 0;
- for (Knob * l = x.first; l; l = l->prev)
- {
- std::ostringstream tmp;
- l->to_stream (tmp);
- out << std::setw(30) << tmp.str();
- j++;
- if (j == 3)
- {
- out << "\n";
- j = 0;
- }
- }
-
- return out;
-}
-
-std::string Knobs::usage ()
-{
- std::ostringstream tmp;
- Knobs dummy = Knobs ();
-
- for (Knob * l = dummy.first; l; l = l->prev)
- {
- l->usage (tmp);
- tmp << "\n";
- }
-
- return tmp.str ();
-}
-
-bool BoolKnob::operator () () const
-{
- return val;
-}
-
-void BoolKnob::set (bool x)
-{
- val = x;
-}
-
-bool ProbKnob::operator () (Rand * r) const
-{
- double rnd = r->rnd_flt ();
- return prob > rnd;
-}
-
-void ProbKnob::to_stream (std::ostream & out) const
-{
- char t[1000];
- sprintf (t, "%s=%g", name, prob);
- out << t;
-}
-
-double ProbKnob::get () const
-{
- return prob;
-}
-
-int RangeKnob::operator () (Rand * r) const
-{
- return r->range (from, to);
-}
-
-unsigned RangeKnob::random_uint (Rand * r) const
-{
- return r->range (from, to);
-}
-
-//////////////////////////////////////////////////////////////////////
-//
-// Coverage
-// Used for random selections and maintaining stats.
-
-// pointer to head of choice list, so we can look through choices later and
-// generate stats.
-Coverage * Coverage::head = 0;
-
-Coverage::Coverage (std::string _title)
- :title (_title),
- prev (head)
-{
- head = this;
-}
-
-Coverage:: ~ Coverage ()
-{
-}
-
-void Coverage::increment (size_t idx)
-{
- if (idx >= count.size ())
- {
- count.resize (idx + 1);
-
- }
- count[idx]++;
-}
-
-std::ostream &operator<<(std::ostream &out, const Coverage &thing)
-{
- thing.output_worker (out);
- return out;
-}
-
-StrCoverage:: StrCoverage (const char *_title,
- const char **_selections):Coverage (_title)
-{
- while (*_selections)
- {
- width = std::max (width, strlen (*_selections));
- selections.push_back (*_selections);
- count.push_back (0);
- _selections++;
- }
-// round to tab size
- width = (width + 7) & -8;
-}
-
-std::string StrCoverage::choose (class Rand * r)
-{
- size_t idx = r->srange (0, count.size ());
- increment (idx);
- return selections[idx];
-}
-
-void StrCoverage::output_worker (std::ostream & out) const
-{
- unsigned items = 0;
- out << title << "\n";
- size_t online = 0;
- for (unsigned i = 0; i < count.size (); i++)
- {
- out << " |";
- out.fill (' ');
- out.width (static_cast<int>(width));
- out << selections[i];
- out.fill (' ');
- out.width (6);
- out << count[i];
- out.width (0);
- online += width + 6;
- items++;
- if (items > 4 || online > 60)
- {
- out << " |\n";
- items = 0;
- online = 0;
- }
- }
- if (online)
- {
- out << " |\n";
- }
- if (prev)
- {
- prev->output_worker (out);
- }
-}
-
-IntCoverage::IntCoverage (const char *_title):Coverage (_title)
-{
-}
-
-void IntCoverage::output_worker (std::ostream & out) const
-{
- unsigned items = 0;
- out << title << "\n";
-
- for (unsigned i = 0; i < count.size (); i++)
- {
- out << "|";
- out << std::setw(4) << i ;
-
- if (count[i])
- {
- out << std::setw(6) << count[i];
- }
- else
- {
- out << std::setw(6) << "****";
- }
- items++;
- if (items > 4)
- {
- out << "\n";
- items = 0;
- }
- }
-
- if (items)
- {
- out << "\n";
- }
-
- if (prev)
- {
- prev->output_worker (out);
- }
-}
-
-
-}
-}
diff --git a/o3d/compiler/puritan/knobs.h b/o3d/compiler/puritan/knobs.h
deleted file mode 100644
index 00fa692..0000000
--- a/o3d/compiler/puritan/knobs.h
+++ /dev/null
@@ -1,268 +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 PURITAN_KNOBS_H
-#define PURITAN_KNOBS_H
-
-#include <string>
-#include <list>
-#include <vector>
-
-namespace Salem
-{
-namespace Puritan
-{
-
-class OutputInfo
-{
-public:
- typedef enum
- {
- Float1,
- Float2,
- Float4
- } ArgSize;
-
- unsigned n_samplers;
- std::list <std::pair <ArgSize, std::string> > uniforms;
- std::list <ArgSize> returns;
-};
-
-class Knob
-{
- class Knob *prev;
- const char *name;
- const char *help;
-
- virtual bool set_from_argument (const char *val) = 0;
- bool parse_argument (const char *val);
- virtual void usage (std::ostream &out) const= 0;
-
- friend class Knobs;
- friend class IntKnob;
- friend class RangeKnob;
- friend class BoolKnob;
- friend class ProbKnob;
- friend std::ostream & operator << (std::ostream &out, const class Knobs& x);
-
-public:
- Knob(const char *name, const char *desc);
- virtual ~Knob();
-
- virtual void to_stream (std::ostream &) const = 0;
-
-};
-
-class RangeKnob : public Knob
-{
- int from;
- int to;
-
- bool set_from_argument (const char *val);
- void usage (std::ostream &) const;
-
-public:
- RangeKnob (const char *, const char *,int f, int t);
-
- void set(int, int);
- int operator () (class Rand *) const;
- unsigned int random_uint (class Rand *) const ;
- void to_stream (std::ostream &) const;
-
-};
-
-class IntKnob : public Knob
-{
- int val;
-
- bool set_from_argument (const char *val);
- void usage (std::ostream &) const;
-
-public:
- IntKnob (const char *, const char *,int);
-
- int get() const;
- unsigned uget() const;
- void set(int x) { val = x;}
- void to_stream (std::ostream &) const;
-
-};
-
-class BoolKnob : public Knob
-{
- bool val;
-
- bool set_from_argument (const char *val);
- void usage (std::ostream &) const;
-public:
- BoolKnob (const char *, const char *,bool f);
- void to_stream (std::ostream &) const;
- bool operator () () const;
- void set(bool x);
-};
-
-class ProbKnob : public Knob
-{
- double prob;
-
- bool set_from_argument (const char *val);
- void usage (std::ostream &) const;
-public:
- ProbKnob (const char *, const char *,double d);
- void set (double x) { prob = x; }
- double get() const;
- void to_stream (std::ostream &) const;
- bool operator () (Rand *r) const ;
-};
-
-class Knobs
-{
-public:
- RangeKnob top_level_statements;
- RangeKnob for_count;
- RangeKnob while_count;
- RangeKnob do_count;
- RangeKnob if_count;
- RangeKnob block_count;
- IntKnob code_limit;
- IntKnob exp_limit;
- RangeKnob exp_count;
- RangeKnob func_count;
- ProbKnob func_trim;
- ProbKnob arg_in_chance;
- ProbKnob arg_out_chance;
- RangeKnob for_nesting;
- RangeKnob while_nesting;
- RangeKnob block_nesting;
- RangeKnob do_nesting;
- RangeKnob if_nesting;
- RangeKnob block_length;
- RangeKnob expression_depth;
- ProbKnob special_chance;
- ProbKnob float4_chance;
- ProbKnob float4_struct_member_chance;
- ProbKnob float2_chance;
- ProbKnob func_chance;
- ProbKnob term_chance;
- ProbKnob unary_chance;
- ProbKnob swizzle_chance;
- ProbKnob fcall_chance;
- ProbKnob copy_swizzle_chance;
- ProbKnob noinline_chance;
- ProbKnob lhs_swizzle_chance;
- ProbKnob assop_chance;
- ProbKnob selfmod_chance;
- ProbKnob trifunc_chance;
- ProbKnob binfunc_chance;
- ProbKnob relop_chance;
- ProbKnob relop_cond_chance;
- ProbKnob type_change_chance;
- ProbKnob type_float4_chance;
- ProbKnob type_float2_chance;
- RangeKnob sampler_count;
- ProbKnob sampler_chance;
- RangeKnob uniform_count;
- ProbKnob uniform_chance;
- RangeKnob arg_count;
- RangeKnob static_initializer_depth;
- BoolKnob standalone;
- IntKnob seed;
- ProbKnob variable_reuse;
- ProbKnob array_use;
- ProbKnob array_reuse;
- ProbKnob array_constness;
- ProbKnob array_index_const;
- ProbKnob array_in_for_use;
- ProbKnob if_elses;
- ProbKnob loop_breaks;
- ProbKnob multiple_stmt;
- ProbKnob constant_use;
- ProbKnob constant_small;
- BoolKnob int_variables;
- BoolKnob allow_two_negs;
-
- Knob *first;
- Knobs(void);
- void to_stream (std::ostream &);
- bool parse_argument (const char *arg);
- static std::string usage ();
-};
-
-class Coverage
-{
-private:
- // Next in chain
-
- std::string title;
- std::vector <int> count;
- Coverage *prev;
-
- friend class StrCoverage;
- friend class IntCoverage;
-
-public:
- static Coverage *head;
- virtual void output_worker (std::ostream & out) const = 0;
- Coverage (std::string _title) ;
- virtual ~ Coverage () ;
-
- void increment (size_t idx);
-};
-
-class StrCoverage:Coverage
-{
-private:
- std::vector <std::string> selections;
- size_t width;
- void output_worker (std::ostream & out) const;
-
-public:
- StrCoverage (const char *_title, const char **_selections);
- std::string choose (class Rand * r);
-};
-
-class IntCoverage:public Coverage
-{
-private:
- void output_worker (std::ostream & out) const;
-public:
- IntCoverage (const char *_title);
-};
-
-
-std::ostream & operator << (std::ostream &out, const class Salem::Puritan::Coverage &x);
-std::ostream & operator << (std::ostream &out, const class Salem::Puritan::Knobs &x);
-}
-}
-
-#endif
diff --git a/o3d/compiler/puritan/main.cc b/o3d/compiler/puritan/main.cc
deleted file mode 100644
index cc6570a..0000000
--- a/o3d/compiler/puritan/main.cc
+++ /dev/null
@@ -1,129 +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 program demonstrates how to get test case information out of Puritan.
-
-#include <iostream>
-#include "test_gen.h"
-#include "knobs.h"
-
-static std::string name_of_size(Salem::Puritan::OutputInfo::ArgSize x) {
- switch (x) {
- case Salem::Puritan::OutputInfo::Float1:
- return "float";
- case Salem::Puritan::OutputInfo::Float2:
- return "float2";
- case Salem::Puritan::OutputInfo::Float4:
- return "float4";
- default:
- break;
- }
- return "Impossible";
-}
-
-
-static std::string comma(bool * need_comma) {
- if (*need_comma) {
- return ", ";
- } else {
- *need_comma = true;
- return "";
- }
-}
-
-int main (int argc, char * const argv[]) {
- int j = 0;
- if (argc > 1) {
- sscanf(argv[1], "%d", &j);
- }
-
- Salem::Puritan::Knobs options;
-
- // Set up some options just the way we like
- options.block_count.set(2, 3);
- options.for_count.set(2, 3);
- options.for_nesting.set(2, 3);
- options.array_in_for_use.set(false);
- options.seed.set(j);
-
- Salem::Puritan::OutputInfo info;
-
-
- // Build a test case
- std::string test_case =
- Salem::Puritan::generate(&info, options);
-
- // Dump out the test information
- std::cout << "(Seed " << options.seed.get() << "), "
- << "(Samplers (";
-
- bool need_comma = false;
-
- for (unsigned i = 0; i < info.n_samplers; i++) {
- std::cout << comma(&need_comma) << "in" << i;
- }
-
- std::cout << ")),"
- << "(Uniforms (";
-
- need_comma = false;
-
- for (std::list <
- std::pair <
- Salem::Puritan::OutputInfo::ArgSize,
- std::string > >::const_iterator
- i = info.uniforms.begin();
- i != info.uniforms.end();
- i++) {
- std::cout << comma(&need_comma)
- << name_of_size(i->first)
- << " "
- << i->second;
- }
-
- std::cout << ")), "
- << "(return struct {";
-
- need_comma = false;
- for (std::list <Salem::Puritan::OutputInfo::ArgSize>::const_iterator
- i = info.returns.begin();
- i != info.returns.end();
- i++) {
- std::cout << comma(&need_comma) << name_of_size(*i);
- }
-
- std::cout << "})\n";
- std::cout << test_case;
-
- return 1;
-}
diff --git a/o3d/compiler/puritan/puritan.cc b/o3d/compiler/puritan/puritan.cc
deleted file mode 100644
index 055b814..0000000
--- a/o3d/compiler/puritan/puritan.cc
+++ /dev/null
@@ -1,1619 +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 <sstream>
-#include <iterator>
-#include <iomanip>
-#include "puritan.h"
-#include "knobs.h"
-#include "structure_gen.h"
-#include "exp_gen.h"
-#include "puritan_assert.h"
-
-#ifdef _MSC_VER
-#define snprintf _snprintf
-#endif
-
-namespace Salem
-{
-namespace Puritan
-{
-// Counters for code coverage.
-IntCoverage cfor_count ("for loop count");
-IntCoverage cfor_nesting ("for loop nesting");
-IntCoverage cdo_count ("do loop count");
-IntCoverage cdo_nesting ("do loop nesting");
-IntCoverage cwhile_count ("while loop count");
-IntCoverage cwhile_nesting ("while loop nesting");
-IntCoverage cif_count ("if count");
-IntCoverage cif_nesting ("if nesting");
-IntCoverage cblock_count ("block count");
-IntCoverage cblock_nesting ("block nesting");
-IntCoverage cexp_count ("exp count");
-IntCoverage cfunc_count ("func count");
-IntCoverage csampler_count ("sampler count");
-IntCoverage cuniform_count ("unform count");
-
-const char *assop_names[] = { "*=", "/=", "+=", "-=", 0 };
-StrCoverage assops ("Assops", assop_names);
-
-const char *selfmodops_names[] = { "++", "--", 0 };
-StrCoverage selfmodops ("SelfModOps", selfmodops_names);
-
-const char *lhs_f4tof4_swizzle_names[] =
-{
- "w", "z", "zw", "y",
- "yw", "yz", "yzw", "x",
- "xw", "xz", "xzw", "xy",
- "xyw", "xyz", "xyzw",
- 0
-};
-
-StrCoverage lhs_f4tof4_swizzles ("Lhs f4tof4 Swizzles",
- lhs_f4tof4_swizzle_names);
-
-const char *lhs_f2tof2_swizzle_names[] =
-{
- "xy", "x", "y",
- 0
-};
-
-StrCoverage lhs_f2tof2_swizzles ("lhs_f2tof2_swizzles",
- lhs_f2tof2_swizzle_names);
-
-
-
-
-// Build the control structurte for each function
-//
-// Each function starts off with an empty list of tokens describing what to
-// do. Knobs and random numbers insert things into the list in random places
-// to mark structure. Many things have two items in the list, for example, a
-// for will have For token and a Close token, marking the point that the for
-// scope is opened, and then closed. If something is inserted into the list
-// between the For and the Close, then it becomes nested inside the for when
-// the code is output. If the thing that is inserted is a pair and it has a
-// Close istelf and that straddles the Close of the for, then since the Closes
-// all look alike, it is still the same as being nested, except the scope of
-// the for then stretches out to the end of the new item.
-
-
-void Gen::create_control_structure ()
-{
- // Divide the samplers among the functions, samples_per_func is a list of
- // samplers used in each function.
- std::vector <UList> samples_per_func;
-
- for (unsigned fidx = 0; fidx < max_funcs; fidx++)
- {
- samples_per_func.push_back (UList ());
- }
-
- for (unsigned i = 0; i < n_samplers; i++)
- {
- for (unsigned j = 0; j < rand.urange (1,2); j++)
- {
- samples_per_func[rand.urange (0, max_funcs)].push_back (i);
- }
- }
-
- for (unsigned fidx = 0; fidx < max_funcs; fidx++)
- {
- unsigned for_count
- = coverage (fidx, knobs.for_count, &cfor_count);
- unsigned for_nesting
- = coverage (fidx, knobs.for_nesting, &cfor_nesting);
- unsigned block_count
- = coverage (fidx, knobs.block_count, &cblock_count);
- unsigned block_nesting
- = coverage (fidx, knobs.block_nesting, &cblock_nesting);
- unsigned while_count
- = coverage (fidx, knobs.while_count, &cwhile_count);
- unsigned while_nesting
- = coverage (fidx, knobs.while_nesting, &cwhile_nesting);
- unsigned do_count
- = coverage (fidx, knobs.do_count, &cdo_count);
- unsigned do_nesting
- = coverage (fidx, knobs.do_nesting, &cdo_nesting);
- unsigned if_count
- = coverage (fidx, knobs.if_count, &cif_count);
- unsigned if_nesting
- = coverage (fidx, knobs.if_nesting, &cif_nesting);
- unsigned asn_count
- = coverage (fidx, knobs.exp_count, &cexp_count);
-
- std::vector <BlockSPtr> code_stack;
- std::vector <ForSPtr> for_stack;
-
- TokenVec tokens;
-
- unsigned asn_tmp_count = asn_count;
-
- while (code_nodes < knobs.code_limit.uget()
- && (for_count || block_count || while_count
- || do_count || if_count || asn_tmp_count))
- {
- code_nodes ++;
- for_count = ins_stmts (&tokens,
- for_count, for_nesting,
- TokFor, 1, true);
-
- block_count= ins_stmts (&tokens,
- block_count, block_nesting,
- TokBlock, 1, false);
-
- while_count = ins_stmts (&tokens,
- while_count, while_nesting,
- TokWhile, 1, true);
-
- do_count = ins_stmts (&tokens,
- do_count, do_nesting,
- TokDo, 1, true);
-
- if_count = ins_stmts (&tokens,
- if_count, if_nesting,
- TokIf, 1, false);
-
- if (knobs.selfmod_chance (&rand))
- {
- asn_tmp_count = ins_stmts (&tokens,
- asn_tmp_count, 1,
- TokSelfMod, 0, false);
- }
- else
- {
- asn_tmp_count = ins_stmts (&tokens,
- asn_tmp_count, 1,
- TokAssign, 0, false);
- }
-
- }
-
-
- // The final statement is always a return, we stick it in an assignment
- // slot
-
- tokens.push_back (TokReturn);
-
- asn_count ++;
-
- // Spread the function calls and samplers over a number of assignments,
- // so that there's always at least one of the right thing per function.
- std::vector <UList> sampler_slots;
- std::vector <FunctionList> caller_slots;
-
- for (unsigned i = 0; i < asn_count; i++)
- {
- sampler_slots.push_back (UList ());
- caller_slots.push_back (FunctionList ());
- }
-
- for (UList::const_iterator sampler = samples_per_func[fidx].begin ();
- sampler != samples_per_func[fidx].end ();
- sampler++)
- {
- for (unsigned j = 0; j < rand.urange (1,3); j++)
- {
- sampler_slots[rand.range (0, asn_count)].push_back (*sampler);
- }
- }
-
- for (FunctionList::const_iterator
- i = callees[fidx].begin ();
- i != callees[fidx].end ();
- i++)
- {
- for (unsigned j = 0; j < rand.urange (1,2); j++)
- {
- caller_slots[rand.range (0, asn_count)].push_back (*i);
- }
- }
-
-
- ForSPtr last_for;
-
- asn_count = 0;
-
- FunctionSPtr cur = functions[fidx];
-
- code_stack.push_back (cur);
-
-
- for (TokenVec::iterator t = tokens.begin ();
- t != tokens.end ();
- t++)
- {
- Context ctx (cur->idx,
- last_for,
- &sampler_slots[asn_count],
- &caller_slots[asn_count]);
-
- switch (*t)
- {
- case TokBlock:
- {
- BlockSPtr c (new Block ());
- code_stack.back ()->add_child (c);
- code_stack.push_back (c);
- for_stack.push_back (last_for);
- break;
- }
- case TokFor:
- {
- Decl counter
- = new_uninitialized_variable (Scope (Static, cur->idx),
- Int);
- // mark this variable such that its not assigned anywhere
- counter.noWrites = true;
- ForSPtr
- f (new For (counter,
- rand.range (0,10),
- rand.range (11,20)));
- last_for = f;
- code_stack.back ()->add_child (f);
- code_stack.push_back (f);
- for_stack.push_back (f);
- break;
- }
- case TokIf:
- {
- BlockSPtr
- c (new IfTemplate (create_expression (this,
- Float,
- ctx.relop ()),
- knobs.if_elses (&rand)));
- code_stack.back ()->add_child (c);
- code_stack.push_back (c);
- for_stack.push_back (last_for);
- break;
- }
- case TokWhile:
- {
- Decl counter
- = new_uninitialized_variable (Scope (Static, cur->idx),
- Float);
- // mark this variable such that its not assigned anywhere
- counter.noWrites = true;
- BlockSPtr
- c (new While (create_expression (this,
- Float,
- ctx.relop ()),
- counter,
- rand.range (1,10)));
- code_stack.back ()->add_child (c);
- code_stack.push_back (c);
- for_stack.push_back (last_for);
- break;
- }
- case TokDo:
- {
- Decl counter
- = new_uninitialized_variable (Scope (Static, cur->idx),
- Float);
- // mark this variable such that its not assigned anywhere
- counter.noWrites = true;
- BlockSPtr
- c (new Do (create_expression (this,
- Float,
- ctx.relop ()),
- counter,
- rand.range (1,10)));
- code_stack.back ()->add_child (c);
- code_stack.push_back (c);
- for_stack.push_back (last_for);
- break;
- }
- // End of any kind of block
- case TokClose:
- code_stack.pop_back ();
- last_for = for_stack.back ();
- for_stack.pop_back ();
- break;
- case TokSelfMod:
- {
- Type ty = random_type ();
- Decl d = fetch_decl (ty, ctx, Initialized, ReadWrite);
- ENode lhs = ENode
- (new SelfModOp (ty, selfmodops.choose (&rand),
- ENode (new LHSVariable (d, false))));
- // We can use the assignment template for self mod, since it
- // takes any expression.
- code_stack.back ()->add_child
- (CodeSPtr (new AssignmentTemplate (lhs)));
- }
- break;
- case TokAssign:
- {
- ENode rhs;
- ENode lhs;
- Type type (NoType);
- bool assop = knobs.assop_chance (&rand);
- bool lhs_swizzle = true;
- // Inside a for loop we may want to do array assignments.
- if (ctx.loop.get()
- && knobs.array_in_for_use (&rand)
- && !knobs.array_constness (&rand))
- {
- Decl decl = gen_array_decl (Float4Array, ctx, Read);
- rhs = create_expression (this, Float4, ctx);
- lhs = ENode
- (new Index (ENode (new LHSVariable (decl, false)),
- ENode (new Constant (Float4, "4"))));
- type = Float4;
- }
- else
- {
- type = random_type ();
- rhs = create_expression (this, type, ctx);
- // An assignment operator needs a preinitialized lhs.
- Decl d = fetch_decl (type, ctx,
- assop
- ? Initialized
- : Uninitialized,
- assop
- ? ReadWrite
- : Write);
- if (! d.initializer.get() )
- lhs_swizzle = false;
- lhs = ENode (new LHSVariable (d, false));
- }
-
-
- if (assop)
- {
- rhs = ENode (new AssOp (type, assops.choose (&rand),
- lhs,
- rhs));
- }
- else
- {
- if (lhs_swizzle)
- {
- if (type == Float4 && knobs.lhs_swizzle_chance (&rand))
- {
- lhs = ENode
- (new Swizzle (type,
- lhs_f4tof4_swizzles.choose (&rand),
- lhs));
- }
- else if (type == Float2 && knobs.lhs_swizzle_chance (&rand))
- {
- lhs = ENode
- (new Swizzle (type,
- lhs_f2tof2_swizzles.choose (&rand),
- lhs));
- }
- }
- rhs = ENode (new AssOp (type, "=", lhs, rhs));
- }
-
- code_stack.back ()->add_child
- (CodeSPtr (new AssignmentTemplate (rhs)));
- asn_count ++;
- }
- break;
-
- case TokReturn:
- {
- // Add the returns at the bottom, the main function returns a
- // struct.
-
- if (cur->idx == 0)
- {
- Decl decl = new_variable (Scope (Static, cur->idx),
- cur->ret_type);
- EList v;
- for (TypeList::const_iterator i = cur->ret_type.begin ();
- i != cur->ret_type.end ();
- i++)
- {
- v.push_back (create_expression (this, *i, ctx));
- }
- code_stack.back ()->add_child
- (CodeSPtr (new Return (v, decl)));
- }
- else
- {
- ENode rval1 = create_expression (this,
- cur->ret_type.front (),
- ctx);
- code_stack.back ()->add_child
- (CodeSPtr (new Return (rval1)));
- }
- }
- break;
-
- case TokBreak:
- {
- BreakSPtr
- b (new Break
- (create_expression (this, Float, ctx)));
- code_stack.back ()->add_child (b);
- }
- break;
- default:
- PURITAN_ABORT("Illegal token " << static_cast<int>(*t));
- break;
- }
- }
- }
-}
-
-
-// Create the function template for each function and fill in the argument type
-// and return types.
-
-void Gen::create_call_structure ()
-{
- for (unsigned i = 0; i < max_funcs; i++)
- {
- DeclList formals;
- TypeList ret_type;
-
- if (i == 0)
- {
- // first function is main, always returns a struct and takes just
- // float2
-
- unsigned nrets = rand.urange (1, 5);
- for (unsigned j = 0; j < nrets; j++)
- {
- ret_type.push_back (knobs.float4_struct_member_chance (&rand)
- ? Float4
- : Float);
-
- }
-
- formals.push_back (
- new_uninitialized_variable (Scope (Argument_I, i), Float2));
- }
- else
- {
- switch (rand.range (0,4))
- {
- case 0:
- ret_type.push_back (Float);
- break;
- case 1:
- ret_type.push_back (Float2);
- break;
- default:
- ret_type.push_back (Float4);
- break;
- }
-
- unsigned n = knobs.arg_count.random_uint (&rand);
-
- for (unsigned j = 0; j < n; j++)
- {
- Context ctx (i, ForSPtr (), 0, 0);
- scope_t arg =
- knobs.arg_in_chance(&rand)
- ? Argument_I : knobs.arg_out_chance (&rand)
- ? Argument_O : Argument_IO;
-
- formals.push_back (new_uninitialized_variable (Scope (arg, i),
- random_type ()));
- }
- }
- functions.push_back (FunctionSPtr
- (new Function (this, i, ret_type,
- formals,
- knobs.standalone (),
- knobs.noinline_chance(&rand))));
- }
- // Different call patterns, so far only one.
- switch (int x = rand.range (0,0))
- {
- case 0:
- // Each functions calls the one above, save the last
- for (unsigned i = 0; i < max_funcs; i++)
- {
- FunctionList targets;
- if (i != (max_funcs - 1))
- {
- targets.push_back (functions[i+1]);
- }
- callees.push_back (targets);
- }
- break;
- case 1:
- break;
- default:
- PURITAN_ABORT ("Unexpected case " << x);
- }
-}
-
-// Add any samplers to the symbol table.
-void Gen::declare_samplers ()
-{
- for (unsigned i = 0; i < n_samplers; i++)
- {
- new_uninitialized_variable (Scope (Sampler), SamplerFloat4, i);
- new_uninitialized_variable (Scope (Uniform), SamplerSize, i);
- }
-
- for (unsigned i = 0; i < n_uniforms; i++)
- {
- Decl decl = new_uninitialized_variable (Scope (Uniform), Float4, i);
- ostringstream decl_name;
- decl_name << decl;
- uniforms.push_back
- (std::pair <Type, string> (Float4, decl_name.str()));
- }
-}
-
-// Insert the statement tokens somewhere randomly.
-unsigned Gen::ins_stmts (TokenVec *vec,
- unsigned count,
- unsigned nest,
- Token token,
- unsigned ends,
- bool break_p)
-{
- nest = std::min (std::max(1U, nest), count);
- size_t start_pos = 0;
- size_t limit = vec->size();
- size_t end_pos = limit;
- for (unsigned j = 0; j < nest; j++)
- {
- start_pos = rand.srange (start_pos, end_pos);
- end_pos = start_pos + 1 < end_pos
- ? rand.srange (start_pos + 1, end_pos)
- : end_pos;
-
- PURITAN_ASSERT (start_pos <= end_pos, "Sanity check");
-
- vec->insert (vec->begin () + start_pos, token);
-
- start_pos ++;
- end_pos++;
-
- if (break_p && knobs.loop_breaks (&rand))
- {
- vec->insert (vec->begin () + start_pos, TokBreak);
- start_pos ++;
- end_pos++;
- }
-
- if (ends)
- {
- vec->insert (vec->begin () + start_pos, TokClose);
- start_pos ++;
- end_pos++;
- }
-
- }
- return count - nest;
-}
-
-//////////////////////////////////////////////////////////////////////
-// Class containing the scope of a name.
-Scope::Scope (scope_t x, unsigned i) : scope (x) , fnc_idx (i)
-{
-
-}
-
-bool Scope::visible_in (const Context &ctx,
- Dir d) const
-{
- switch (scope)
- {
- case Argument_IO:
- return fnc_idx == ctx.func && (d == Read || d == Write);
- case Argument_O:
- return fnc_idx == ctx.func && (d == Write);
- case Argument_I:
- return fnc_idx == ctx.func && (d == Read || d == Write);
- case StaticConstArrays:
- case Sampler:
- case Uniform:
- return d == Read;
- case Static:
- return fnc_idx == ctx.func;
- case NoScope:
- default:
- break;
- }
- PURITAN_ABORT ("Illegal scope " << scope);
-}
-
-string Scope::name () const
-{
- switch (scope)
- {
- case Sampler:
- return "sampler ";
- case Uniform:
- return "uniform ";
- case Static:
- case StaticConstArrays:
- return "";
- default:
- case NoScope:
- case Argument_I:
- case Argument_O:
- case Argument_IO:
- PURITAN_ABORT ("Argument error " << scope);
- }
-}
-
-string Scope::short_name () const
-{
- switch (scope)
- {
- case Sampler:
- return "in";
- case Uniform:
- return "u_";
- case Static:
- case StaticConstArrays:
- return "s_";
- case Argument_I:
- return "ai_";
- case Argument_O:
- return "ao_";
- case Argument_IO:
- return "aio_";
- default:
- case NoScope:
- PURITAN_ABORT ("Argument error " << scope);
- }
-}
-
-bool Scope::eq (const Scope &other) const
-{
- return scope == other.scope && fnc_idx == other.fnc_idx;
-}
-
-//////////////////////////////////////////////////////////////////////
-// Generator
-// Main wrapper and support
-// Emit all the declarations at the given scope
-void
-Gen::output_declarations (ostream &out,
- Scope s)
-{
- DeclVec::const_iterator i = symtable.begin ();
- while (i != symtable.end ())
- {
- const Decl & d = *i;
- if (d.scope.eq (s))
- {
- if (d.type () == Float4Array)
- {
- out << "uniform float4 "
- << d
- << "[" << array_size << "];\n";
- }
- else if (d.type () == Float4ConstArray)
- {
- out << "const float4 "
- << d
- << "[" << array_size << "] = {\n";
- for (unsigned i = 0; i < array_size * 4; i++)
- {
- if (i)
- {
- out << ",\n";
- }
-
- out << gen_fconstant ();
- }
- out << "};\n";
- }
- else
- {
- out << d.scope.name ();
-
- if (d.scope.scope != Sampler)
- {
- out << " " << d.type;
- }
-
- out << " " << d;
-
- if (d.initializer.get() )
- {
- out << " = " << d.initializer;
- }
- out << ";\n";
- }
- }
- i++;
- }
-}
-
-// Return a random type.
-Type Gen::random_type ()
-{
- return (knobs.type_float4_chance (&rand))
- ? Float4
- : knobs.type_float2_chance (&rand)
- ? Float2
- : Float;
-}
-
-
-const char *id_char =
-"0123456789" "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-const char *first_char =
-"abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-const char *digit = "012345678";
-
-char Gen::rchar (const char *what)
-{
- return what[ (rand.srange (0, strlen (what)))];
-}
-
-
-// Make a random floating point constant.
-string Gen::gen_fconstant ()
-{
- if (knobs.constant_small (&rand))
- {
- ostringstream out;
- char b[100];
- sprintf (b, "%g", 10.0 / rand.range (1, 10000));
- out << b;
- return out.str ();
- }
- else
- {
- string res;
- unsigned len = rand.range (1, 30);
- unsigned point = rand.range (0,len);
-
- for (unsigned i = 0; i < len; i++)
- {
- res += rchar (digit);
- if (i == point)
- {
- res += ".";
- }
- }
- return res;
- }
-}
-
-ostream & Gen::output_typedefs (ostream &out)
-{
- FunctionSPtr main = functions.front ();
-
- if (knobs.standalone())
- {
- out << "\n\nstruct PS_OUTPUT\n{\n";
- unsigned k = 0;
- for (TypeList::const_iterator i = main->ret_type.begin ();
- i != main->ret_type.end ();
- i++)
- {
- out << *i << " color" << k << " :" << "COLOR" << k << ";\n";
- k++;
- }
- out << "};\n";
- }
-#if 0
- else
- {
- out << "#ifdef STANDALONE_DEFS\n"
- << "#define D_IN(t,name) in t name\n"
- << "#define D_OUT(t,name) out t name\n"
- << "#define D_INOUT(t,name) inout t name\n"
- << "#define D_VPOS : VPOS\n"
- << "#define D_COLOR0 : COLOR0\n"
- << "#define D_COLOR1 : COLOR1\n"
- << "#define D_COLOR2 : COLOR2\n"
- << "#define D_COLOR3 : COLOR3\n"
- "\n\nstruct PS_OUTPUT\n{\n";
-
- unsigned k = 0;
-
- for (TypeList::const_iterator i = main->ret_type.begin ();
- i != main->ret_type.end ();
- i++)
- {
- out << *i << " color" << k << " " << "D_COLOR" << k << ";\n";
- k++;
- }
- out << "};\n"
- << "#endif\n"
- << "#ifdef WRAPPED_DEFS\n"
- << "#define D_IN(t,name) t name\n"
- << "#define D_OUT(t,name) t&name\n"
- << "#define D_INOUT(t,name) t&name\n"
- << "etc etc\n"
- << "#include \"something here\"\n"
- << "#endif\n";
- }
-#endif
-
- return out;
-}
-
-// Create a new and unique name of the right type in the symbol table
-Decl Gen::new_variable (Scope scope,
- Type type,
- Kind k,
- const Context &ctx)
-{
- return k == Initialized
- ? new_initialized_variable (scope, type, ctx)
- : new_uninitialized_variable (scope, type);
-}
-
-Decl Gen::new_variable (Scope scope,
- const TypeList & type)
-{
- Decl newdecl = Decl (scope, Struct);
- // We ignore the type, there's only one struct.
- (void) type;
- symtable.push_back (newdecl);
- return newdecl;
-}
-
-Decl Gen::new_uninitialized_variable (Scope scope,
- Type type,
- unsigned idx)
-{
- Decl newdecl = Decl (scope, type, idx);
- symtable.push_back (newdecl);
- return newdecl;
-}
-
-Decl Gen::new_uninitialized_variable (Scope scope,
- Type type)
-{
- Decl newdecl = Decl (scope, type);
- symtable.push_back (newdecl);
- return newdecl;
-}
-
-Decl Gen::new_initialized_variable (Scope scope,
- Type type,
- const Context &ctx)
-{
- Decl newdecl = Decl (scope, type, create_expression (this, type, ctx));
- symtable.push_back (newdecl);
- return newdecl;
-}
-
-//////////////////////////////////////////////////////////////////////
-// Contexts
-// A context is a structure which describes the conditions under something else
-// is being run. An expression can use the context to work out if it is in a
-// for loop or which function it's in.
-
-Context::Context (unsigned _owner,
- ForSPtr _loop,
- UList *_samplers,
- FunctionList *_callees)
-
- : func (_owner), loop (_loop) , depth (0), relop_p (false),
- samplers (_samplers),
- callees (_callees)
-{
-}
-
-Context Context::deeper () const
-{
- Context res = *this;
- res.depth++;
- return res;
-}
-
-Context Context::relop () const
-{
- Context res =deeper ();
- res.relop_p = true;
- return res;
-}
-
-Decl Gen::gen_array_decl (Type t,
- const Context &ctx,
- Dir d)
-{
- if (knobs.array_reuse (&rand))
- {
- DeclVec::iterator i = existing_decl (t, ctx, d);
- if (i != symtable.end ())
- {
- return *i;
- }
- }
- return new_uninitialized_variable (Scope (Uniform), t);
-}
-
-Decl Gen::fetch_decl (Type t, const Context & ctx, Kind k, Dir dir)
-{
- if (knobs.variable_reuse (&rand))
- {
- DeclVec::iterator i = existing_decl (t, ctx, dir);
- if (i != symtable.end ())
- {
- return *i;
- }
- }
- return new_variable (Scope (Static, ctx.func), t, k, ctx);
-}
-
-//////////////////////////////////////////////////////////////////////
-// Simply reformat the output to make it look pretty.
-
-class Reformat
-{
- string res;
- string pending_line;
- std::vector <unsigned> indent_stack;
- unsigned last_indent;
- bool pending_nl;
- char prev_char;
- char this_char;
- bool had_open_p;
- bool had_eq;
- unsigned raw_line_length;
- string tab ()
- {
- string t;
- unsigned i;
- for (i = 0; i < last_indent; i++)
- {
- t += " ";
- }
- return t;
- }
- void write (string x)
- {
- pending_line += x;
- }
- unsigned pos_on_line ()
- {
- return last_indent + pending_line.size ();
- }
- void flush_pending_line ()
- {
- if (!pending_line.empty ())
- {
- res += tab ();
- res += pending_line;
- res += "\n";
- pending_line = "";
- }
- pending_nl = false;
- had_open_p = false;
- raw_line_length = 0;
- last_indent = indent_stack.back ();
- }
- void tabout_and_writeln (string x)
- {
- tab ();
- write (x);
- write ("\n");
- }
-public:
- Reformat (string src) : res (""),
- pending_line (""),
- last_indent (0),
- pending_nl (false),
- prev_char (' '),
- this_char (' '),
- had_open_p (false),
- had_eq (false),
- raw_line_length (0)
-
- {
- indent_stack.push_back (0);
- prev_char = '\n';
- for (string::iterator p = src.begin (); p != src.end (); p++)
- {
- this_char = *p;
-
- if (raw_line_length == 0)
- {
- raw_line_length = last_indent;
- for (string::iterator q = p;
- q != src.end () && *q != '\n';
- q++)
- {
- raw_line_length++;
- }
- }
-
- switch (this_char)
- {
- case '{':
- flush_pending_line ();
- pending_line = "{";
- flush_pending_line ();
- prev_char = this_char;
- last_indent = indent_stack.back () + 2;
- indent_stack.push_back (last_indent);
- break;
- // fall
- case '(':
- if (raw_line_length > 80 && pos_on_line () > 70)
- {
- flush_pending_line ();
- }
-
- if (pos_on_line () < 30)
- {
- indent_stack.push_back (pos_on_line ());
- }
- else
- {
- indent_stack.push_back (indent_stack.back ()+1);
- }
- pending_line += this_char;
- prev_char = this_char;
-
- break;
-
- case '}':
-
- flush_pending_line ();
- indent_stack.pop_back ();
- pending_line = "}";
- last_indent = indent_stack.back ();
- flush_pending_line ();
-
-
- prev_char = '\n';
- break;
-
- case ')':
- prev_char = this_char;
- indent_stack.pop_back ();
- pending_line += this_char;
- break;
- case '\n':
- pending_nl = false;
- flush_pending_line ();
- prev_char = this_char;
- break;
- case ' ':
- if (prev_char == ' '
- || prev_char == '('
- || prev_char == '\n'
- || prev_char == '{')
- {
- break;
- }
- pending_line += this_char;
- prev_char = this_char;
- break;
-
- case ';':
- pending_line += this_char;
- prev_char = this_char;
- if (had_eq)
- {
- had_eq = false;
- indent_stack.pop_back ();
- }
- break;
-
- case '=':
- pending_line += this_char;
- prev_char = this_char;
- if (!had_eq)
- {
- had_eq = true;
- indent_stack.push_back (indent_stack.back () + 4);
- }
-
- break;
-
- default:
- // no need to break line if we know it will fit
-
- if (raw_line_length > 80) {
- if (prev_char == ' '
- && (!isalpha (this_char))
- && (!isdigit (this_char))
- && pos_on_line () > 60)
- {
- flush_pending_line ();
- }
- else
- if ( (prev_char == ' '
- && pos_on_line () > 100)
- || pending_nl)
- {
- flush_pending_line ();
- }
- }
- if (prev_char == ';')
- {
- pending_line += ' ';
- }
-
- pending_line += this_char;
- prev_char = this_char;
- break;
- }
- }
- flush_pending_line ();
- }
- string str ()
- {
- return res;
- }
-};
-
-ostream &
-Gen::output_boiler_plate (ostream &out) const
-{
- // isnan functions
- out <<
- "float isnan1 (float a)\n"
- "{\n"
- "return ((a<0) && (a>0));"
- "}\n"
- "float2 isnan2 (float2 a)\n"
- "{\n"
- "return ((a<0) && (a>0));"
- "}\n"
- "float4 isnan4 (float4 a)\n"
- "{\n"
- "return ((a<0) && (a>0));"
- "}\n";
-
- out <<
- "float4 quick_mod (float4 a, float4 b)\n"
- "{\n"
- "float4 d = a / b;\n"
- "float4 q = d - frac (d);\n"
- "float4 r = a - q * b;\n"
- "r -= frac(r);\n"
- "return isnan4 (r) ? 0 : r;\n"
- "}\n"
- "float opcond(float x, float y, float z)\n"
- "{\n"
- "return x ? y : z;\n"
- "}\n"
- "float2 opcond2(float2 x, float2 y, float2 z)\n"
- "{\n"
- "return x ? y : z;\n"
- "}\n"
- "float4 opcond4(float4 x, float4 y, float4 z)\n"
- "{\n"
- "return x ? y : z;\n"
- "}\n";
-
- static char * floats[2][4] =
- { { "float", "float2", "float4", 0},
- {"1", "2", "4", 0} };
- static char * ops[2][9] =
- { {"lt", "le", "gt", "ge", "eq", "ne", "and", "or", 0},
- {"<", "<=", ">", ">=", "==", "!=", "&&", "||", 0} };
-
- for (unsigned i = 0; floats[0][i]; i++)
- {
- for (unsigned t = 0; ops[0][t]; t++)
- {
- out << floats[0][i] << " op" << ops[0][t] << floats[1][i]
- << "(" << floats[0][i] << " a, " << floats[0][i] << " b) "
- << "{ return isnan" << floats[1][i] << " (a) ? 0 : (isnan"
- << floats[1][i] << " (b) ? 0 : (a" << ops[1][t] << "b));\n}";
- }
-
- }
- return out;
-}
-
-std::ostream & operator << (std::ostream &out, const FunctionSPtr&x)
-{
- x->output_code (out);
- return out;
-}
-
-std::ostream & operator << (std::ostream &out,
- const Program &functions)
-{
- std::copy (functions.rbegin (),
- functions.rend (),
- std::ostream_iterator<FunctionSPtr> (out,"\n"));
- return out;
-}
-
-std::ostream & operator << (std::ostream &out, gspair x)
-{
- x.first->output_declarations (out, x.second);
- return out;
-}
-
-static OutputInfo::ArgSize translate_type (Type t)
-{
- switch (t.type)
- {
- case Float4:
- return OutputInfo::Float4;
- case Float2:
- return OutputInfo::Float2;
- case Float:
- return OutputInfo::Float1;
- case NoType:
- case Int:
- case Int4:
- case SamplerFloat4:
- case SamplerSize:
- case Struct:
- case Float4ConstArray:
- case Float4Array:
- default:
- PURITAN_ABORT ("Unexpected type " << t.type);
- break;
- }
-}
-
-string Gen::generate (OutputInfo *output_info)
-{
- ostringstream output_stream;
- ostringstream comments;
-
- // Reset the declaration counter so names start at 0 for each new file.
- Decl::reset ();
-
- declare_samplers ();
- create_call_structure ();
- create_control_structure ();
-
- output_typedefs (output_stream);
-
- output_stream << gspair (this, Scope (Sampler))
- << gspair (this, Scope (Uniform))
- << gspair (this, Scope (StaticConstArrays));
-
- output_boiler_plate (output_stream);
-
- output_stream << functions
- << "/* cn=" << code_nodes << " en=" << exp_nodes << "*/\n";
-
- comments << "/*\n" << knobs << "*/\n"
- << "/*\n Coverage to this point\n"
- << *Coverage::head
- << "*/\n";
-
- Reformat reformatted (output_stream.str ());
-
-
- // Fill in the output description with what we've been up to.
- if (output_info)
- {
- output_info->n_samplers = n_samplers;
-
- PURITAN_ASSERT (output_info->uniforms.empty(),"Incorrect start state");
- PURITAN_ASSERT (output_info->returns.empty(), "Incorrect start state");
-
- FunctionSPtr func = functions[0];
-
- for (TypeList::const_iterator i = func->ret_type.begin();
- i != func->ret_type.end();
- i++)
- {
- output_info->returns.push_front (translate_type (*i));
- }
-
- for (std::vector<std::pair <Type, string> >::const_iterator
- i = uniforms.begin();
- i != uniforms.end();
- i++)
- {
- std::pair <OutputInfo::ArgSize, std::string>
- x(translate_type (i->first), i->second);
- output_info->uniforms.push_front (x);
- }
- }
- return comments.str () + reformatted.str ();
-}
-
-Gen::Gen (Knobs & _config)
- :
- rand (_config.seed.get ()),
- knobs (_config),
- exp_nodes (0),
- code_nodes (0),
- max_funcs (coverage (knobs.func_count, &cfunc_count)),
- n_samplers (coverage (knobs.sampler_count, &csampler_count)),
- n_uniforms (coverage (knobs.uniform_count, &cuniform_count))
-{
-
-}
-
-
-// Return iterator pointing to an existing decl with the suggested type and
-// visible in the context. If it's an argument formal make sure that the
-// direction of intended action is ok.
-DeclVec::iterator Gen::existing_decl (Type t,
- const Context &ctx,
- Dir d)
-{
- size_t length = symtable.size ();
- size_t scan_from = rand.srange (0, length);
-
- // Scan from the middle somewhere, and if that doesn't find
- // anything, start again at the start.
-
- DeclVec::iterator starts[2] =
- { symtable.begin () + scan_from, symtable.begin()};
- DeclVec::iterator ends[2] =
- { symtable.end(), symtable.begin() + scan_from };
-
- for (unsigned i = 0; i < 2; i++)
- {
- for (DeclVec::iterator res = starts[i];
- res != ends[i];
- res++)
- {
- // It's usable if we're writing, or it's initialized, or an
- // incoming argument. Also, check if assignments it are allowed, if
- // we are writing.
- if (res->type == t
- && res->scope.visible_in (ctx, d)
- && (res->initializer.get()
- || d == Write
- || res->scope.scope == Argument_I
- || res->scope.scope == Argument_IO)
- && (!res->noWrites || d == Read))
- {
- return res;
- }
- }
- }
- return symtable.end ();
-}
-
-
-unsigned Decl::counter = 0;
-
-Decl::Decl () : scope (NoScope), type (NoType), idx (0), noWrites (false)
-{
-}
-
-Decl::Decl (bool) : scope (NoScope), type (NoType), idx (0), noWrites (false)
-{
-}
-
-Decl::Decl (Scope _scope,
- Type _type)
- : scope (_scope), type (_type), idx (++counter), noWrites (false)
-{
-}
-
-Decl::Decl (Scope _scope,
- Type _type,
- unsigned _idx)
- : scope (_scope), type (_type), idx (_idx), noWrites (false)
-{
-}
-
-
-// Return a number according to the knob range, and increment the coverage
-// counter for it.
-int Gen::coverage (const RangeKnob &knob,
- IntCoverage *marker)
-{
- int r = knob (&rand);
- marker->increment (r);
- return r;
-}
-
-// As above, but the value is scaled so that minor functions get smaller
-// values.
-int Gen::coverage (unsigned fidx,
- const RangeKnob &knob,
- IntCoverage *marker)
-{
- int r = knob (&rand);
- if (fidx > 0)
- {
- r = (static_cast<int> ( (static_cast<double> (r))
- * knobs.func_trim.get ()));
- }
- marker->increment (r);
- return r;
-}
-
-//////////////////////////////////////////////////////////////////////
-// Decl class
-// Knows the scope, type, name and initializer of every variable.
-
-Decl::Decl (Scope _scope,
- Type _type,
- ENode _init)
- : scope (_scope),
- type (_type),
- initializer (_init),
- idx (++counter)
-{
-}
-
-void Decl::reset ()
-{
- Decl::counter = 0;
-}
-
-Scope::Scope (scope_t _scope) : scope (_scope), fnc_idx (0)
-{
-}
-
-std::ostream & operator << (std::ostream &out, const Decl&x)
-{
- if (x.type == SamplerSize)
- {
- out << "in" << x.idx << "_size";
- }
- else
- {
- out << x.scope.short_name () << x.type.short_name () << x.idx;
- }
- return out;
-}
-
-//////////////////////////////////////////////////////////////////////
-// Type
-
-Type::Type () : type (NoType) {}
-Type::Type (enum type _type) : type (_type) {}
-
-enum type Type::operator () () const
-{
- return type;
-}
-
-bool Type::array_p ()
-{
- return type == Float4ConstArray
- || type == Float4Array;
-}
-
-
-std::ostream & operator << (std::ostream &out, Type x)
-{
- const char *w;
- switch (x.type)
- {
- case Int:
- w= "int";
- break;
- case Int4:
- w="int4";
- break;
- case Float:
- w= "float";
- break;
- case Float2:
- w= "float2";
- break;
- case Float4:
- case SamplerSize:
- w= "float4";
- break;
- case Float4ConstArray:
- w ="floatc4x40";
- break;
- case Float4Array:
- w = "floatv4x40";
- break;
- case Struct:
- w = "struct PS_OUTPUT";
- break;
- default:
- case NoType:
- case SamplerFloat4:
- PURITAN_ABORT ("Argument error" << x.type);
- }
- return (out << w);
-
-}
-
-string Type::short_name () const
-{
- switch (type)
- {
- case Int:
- return "i_";
- case Int4:
- return "i4_";
- case Float:
- return "f1_";
- case Float2:
- return "f2_";
- case Float4:
- return "f4_";
- case Float4ConstArray:
- return "carray_";
- case Float4Array:
- return "farray_";
- case SamplerFloat4:
- return "";
- case Struct:
- return "s_";
- default:
- case NoType:
- case SamplerSize:
- PURITAN_ABORT ("Argument error:" << type);
- }
-}
-
-string Type::suffix_name () const
-{
- switch (type)
- {
- case Int:
- return "i";
- case Int4:
- return "i4";
- case Float:
- return "1";
- case Float2:
- return "2";
- case Float4:
- return "4";
- case Float4ConstArray:
- return "c";
- case Float4Array:
- return "f";
- case SamplerFloat4:
- return "";
- case Struct:
- return "s";
- default:
- case NoType:
- case SamplerSize:
- PURITAN_ABORT ("Argument error:" << type);
- }
-}
-
-bool Type::operator != (Type x) const
-{
- return x.type != type;
-}
-
-bool Type::operator == (Type x) const
-{
- return x.type == type;
-}
-
-std::ostream & operator << (std::ostream &out, const TypeList &x)
-{
- PURITAN_ASSERT (x.size () == 1, "Should never be called with a non unary list");
- out << x.front ();
- return out;
-}
-
-
-}
-}
-
diff --git a/o3d/compiler/puritan/puritan.h b/o3d/compiler/puritan/puritan.h
deleted file mode 100644
index a9dc409..0000000
--- a/o3d/compiler/puritan/puritan.h
+++ /dev/null
@@ -1,259 +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 PURITAN_PURITAN_H
-#define PURITAN_PURITAN_H
-
-#include <string>
-#include <sstream>
-#include <vector>
-#include <list>
-#include "puritan_assert.h"
-#include "rand.h"
-
-#include "puritan_shared_ptr.h"
-
-namespace Salem
-{
-namespace Puritan
-{
-
-class Decl;
-class Exp;
-class For;
-class Function;
-class Gen;
-class IntCoverage;
-class RangeKnob;
-class Scope;
-class Type;
-
-typedef ::shared_ptr<Exp> ENode;
-typedef ::shared_ptr<For> ForSPtr;
-typedef ::shared_ptr<Function> FunctionSPtr;
-typedef std::list <Decl> DeclList;
-typedef std::list <ENode> EList;
-typedef std::list <FunctionSPtr> FunctionList;
-typedef std::list <Type> TypeList;
-typedef std::list <unsigned> UList;
-typedef std::ostream ostream;
-typedef std::ostringstream ostringstream;
-typedef std::pair <Gen *, Scope> gspair;
-typedef std::string string;
-typedef std::vector <Decl> DeclVec;
-typedef std::vector <FunctionSPtr> Program;
-
-ostream & operator << (ostream &out, Type x);
-ostream & operator << (ostream &out, const Decl& x);
-ostream & operator << (ostream &out, const TypeList & x) ;
-ostream & operator << (ostream &out, gspair x);
-
-const unsigned int array_size = 3;
-
-enum type
-{
- NoType,
- Int, Int4,
- Float, Float2, Float4,
- SamplerFloat4,
- SamplerSize,
- Struct,
- Float4ConstArray, Float4Array
-};
-
-class Type
-{
-public:
- enum type type;
- string name () const;
- string short_name () const;
- string suffix_name () const;
- bool array_p ();
- enum type operator () () const;
- Type (enum type);
- Type (); // default ctor for use with STL containers
- bool operator == (Type) const;
- bool operator != (Type) const;
- unsigned struct_elements ();
-};
-
-typedef enum
-{
- NoScope,
- StaticConstArrays,
- Sampler,
- Uniform,
- Static,
- Argument_I,
- Argument_O,
- Argument_IO
-} scope_t;
-
-typedef enum
-{
- Initialized,
- Uninitialized
-} Kind;
-
-typedef enum
-{
- Read,
- Write,
- ReadWrite
-} Dir;
-
-// Scope of a name.
-class Scope
-{
-public:
- scope_t scope;
- unsigned fnc_idx;
-
- Scope (scope_t x) ;
- Scope (scope_t x, unsigned fnc_idx) ;
-
- bool eq (const Scope&other) const;
- string name () const;
- string short_name () const;
- bool visible_in (const class Context & ctx, Dir d) const;
-};
-
-// Declarations - scope, type and name.
-class Decl
-{
- static unsigned counter;
-
-public:
- Scope scope;
- Type type;
- ENode initializer;
-
- // use the creation index as the root of the name
- unsigned idx;
-
- // certain variables should be made unavailable for general assignments
- // - for example, loop counters are modified by special
- // increment/decrement statements and should not be modified elsewhere
- bool noWrites;
-
- Decl (Scope, Type type);
- Decl (Scope, Type type, ENode init);
- Decl (Scope, Type type, unsigned idx);
- Decl (bool);
- Decl (); // default ctor for use with STL containers
- bool same ();
- static void reset ();
-};
-
-// A context passes information about what we're doing down through the
-// recursive decent generator
-
-class Context
-{
-public:
- unsigned func;
- ForSPtr loop;
- unsigned depth;
- bool relop_p;
-
- UList *samplers;
- FunctionList *callees;
-
- Context relop () const;
- Context deeper () const;
-
- Context (unsigned _owner,
- ForSPtr _loop,
- UList *samplers,
- FunctionList *callees);
-};
-
-class Gen
-{
-private:
- friend class Exp;
- typedef enum { TokFor, TokWhile, TokDo, TokAssign,
- TokSelfMod, TokReturn, TokIf, TokBlock,
- TokClose, TokBreak } Token;
- typedef std::vector <Token> TokenVec;
- Rand rand;
- class Knobs & knobs;
- std::vector < std::pair < Type, std::string > > uniforms;
- unsigned exp_nodes;
- unsigned code_nodes;
- unsigned max_funcs;
- unsigned n_samplers;
- unsigned n_uniforms;
-
- Program functions;
- std::vector <FunctionList> callees;
- DeclVec symtable;
-
- void create_control_structure ();
- void create_call_structure ();
- void declare_samplers ();
-
-
- Decl gen_array_decl (Type t, const Context &ctx, Dir d);
- Decl fetch_decl (Type t,const Context &ctx, Kind k, Dir d);
- Decl new_variable (Scope scope, Type type, Kind k, const Context &c);
- Decl new_variable (Scope scope, const TypeList & type);
- Decl new_initialized_variable (Scope scope, Type type, const Context &c);
- Decl new_uninitialized_variable (Scope s, Type c, unsigned idx);
- Decl new_uninitialized_variable (Scope s, Type c);
- DeclVec::iterator existing_decl (Type t, const Context &ctx, Dir d);
-
- char rchar (const char *what);
- ostream & output_boiler_plate (ostream &out) const;
- int coverage (const RangeKnob &knob, IntCoverage *marker);
- int coverage (unsigned fidx, const RangeKnob &knob, IntCoverage *marker) ;
- unsigned ins_stmts (TokenVec *v, unsigned c,
- unsigned n, Token t,
- unsigned e, bool break_p);
- void output_code (ostream &out, const Program &functions);
- void output_declarations (ostream &out, Scope s);
- ostream &output_typedefs (ostream &out);
-
- string gen_fconstant ();
- Type random_type ();
-
- friend ostream & operator << (ostream &out, gspair x);
- friend ENode create_expression (Gen *gen, Type rtype, const Context &ctx);
-public:
- Gen (Knobs & _config);
- string generate (class OutputInfo *output);
-};
-
-}
-}
-
-#endif
diff --git a/o3d/compiler/puritan/puritan_assert.cc b/o3d/compiler/puritan/puritan_assert.cc
deleted file mode 100644
index 0b648af..0000000
--- a/o3d/compiler/puritan/puritan_assert.cc
+++ /dev/null
@@ -1,51 +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 "puritan_assert.h"
-#include <iostream>
-#ifdef __GNUC__
-namespace Salem
-{
-namespace Puritan
-{
-#endif
-void puritan_assert_worker (const char *file, const char *func, unsigned line, const std::string &message)
-{
- std::cerr << "Fatal error [" << file << ":" << func << ":" << line << "] " << message << "\n";
- exit (1);
-}
-
-#ifdef __GNUC__
-}
-}
-#endif
-
diff --git a/o3d/compiler/puritan/puritan_assert.h b/o3d/compiler/puritan/puritan_assert.h
deleted file mode 100644
index 0e03e73..0000000
--- a/o3d/compiler/puritan/puritan_assert.h
+++ /dev/null
@@ -1,83 +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 PURITAN_ASSERT_H
-#define PURITAN_ASSERT_H
-
-#include <string>
-#include <sstream>
-
-#ifndef __GNUC__
-
-// MSVC and GCC are different - MSVC needs assert worker to be at the top level
-// for boost to compile. GCC does not. I don't know which is correct
-
-__declspec (noreturn) void puritan_assert_worker (const char *,
- const char *,
- unsigned,
- const std::string &);
-namespace Salem { namespace Puritan {
-#else
-namespace Salem { namespace Puritan {
-
-void puritan_assert_worker (const char *,
- const char *,
- unsigned,
- const std::string &) __attribute__((noreturn));
-
-#endif
-
-
-#define PURITAN_ABORT(message) \
-do { \
- std::ostringstream message_buf; \
- message_buf << message; \
- puritan_assert_worker (__FILE__, \
- __FUNCTION__, \
- __LINE__, \
- message_buf.str()); \
-} while (0)
-
-#define PURITAN_ASSERT(check, message) \
-do { \
- if (!(check)) \
- { \
- PURITAN_ABORT(message); \
- } \
-} while (0)
-
-#undef assert
-#define assert(x) PURITAN_ASSERT(x,"")
-}
-}
-
-#endif
diff --git a/o3d/compiler/puritan/puritan_shared_ptr.h b/o3d/compiler/puritan/puritan_shared_ptr.h
deleted file mode 100644
index ce1fa58..0000000
--- a/o3d/compiler/puritan/puritan_shared_ptr.h
+++ /dev/null
@@ -1,292 +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.
- */
-
-//
-// A simple reference counted pointer implementation. It is a subset
-// of the boost/tr1 shared_ptr class, which is expected to be part of
-// the next C++ standard. See section 20.6.6 [util.smartptr] of the
-// draft standard for a full description of the standard interface.
-//
-// The following standard features have been omitted from this implementation:
-// - no custom deallocators - uses delete
-// - no support for enable_shared_from_this
-// - no support for smart pointer casts
-// - no support for features that rely on variadic templates
-// - not exception-safe
-// - no overloaded comparison operators (e.g. operator<). They're
-// convenient, but they can be explicitly defined outside the class.
-//
-
-#ifndef UTIL_GTL_PURITAN_SHARED_PTR_H__
-#define UTIL_GTL_PURITAN_SHARED_PTR_H__
-
-#include <algorithm> // for swap
-
-template <typename T> class shared_ptr;
-template <typename T> class weak_ptr;
-
-// This class is an internal implementation detail for shared_ptr.
-//
-class SharedPtrControlBlock {
- template <typename T> friend class shared_ptr;
- template <typename T> friend class weak_ptr;
- private:
- SharedPtrControlBlock() : refcount_(1), weak_count_(1) { }
- int refcount_;
- int weak_count_;
-};
-
-template <typename T>
-class shared_ptr {
- template <typename U> friend class weak_ptr;
- public:
- typedef T element_type;
-
- explicit shared_ptr(T* ptr = NULL)
- : ptr_(ptr),
- control_block_(ptr != NULL ? new SharedPtrControlBlock : NULL) {
- }
-
- // Copy constructor: makes this object a copy of ptr
- template <typename U>
- shared_ptr(const shared_ptr<U>& ptr)
- : ptr_(NULL),
- control_block_(NULL) {
- Initialize(ptr);
- }
- // Need non-templated version to prevent the compiler-generated default
- shared_ptr(const shared_ptr<T>& ptr)
- : ptr_(NULL),
- control_block_(NULL) {
- Initialize(ptr);
- }
-
- // Assignment operator. Replaces the existing shared_ptr with ptr.
- template <typename U>
- shared_ptr<T>& operator=(const shared_ptr<U>& ptr) {
- if (ptr_ != ptr.ptr_) {
- shared_ptr<T> me(ptr); // will hold our previous state to be destroyed.
- swap(me);
- }
- return *this;
- }
-
- // Need non-templated version to prevent the compiler-generated default
- shared_ptr<T>& operator=(const shared_ptr<T>& ptr) {
- if (ptr_ != ptr.ptr_) {
- shared_ptr<T> me(ptr); // will hold our previous state to be destroyed.
- swap(me);
- }
- return *this;
- }
-
- ~shared_ptr() {
- if (ptr_ != NULL) {
- if (--control_block_->refcount_ == 0) {
- delete ptr_;
-
- // weak_count_ is defined as the number of weak_ptrs that observe
- // ptr_, plus 1 if refcount_ is nonzero.
- if (--control_block_->weak_count_ == 0) {
- delete control_block_;
- }
- }
- }
- }
-
- // Replaces underlying raw pointer with the one passed in. The reference
- // count is set to one (or zero if the pointer is NULL) for the pointer
- // being passed in and decremented for the one being replaced.
- void reset(T* p = NULL) {
- if (p != ptr_) {
- shared_ptr<T> tmp(p);
- tmp.swap(*this);
- }
- }
-
- // Exchanges the contents of this with the contents of r. This function
- // supports more efficient swapping since it eliminates the need for a
- // temporary shared_ptr object.
- void swap(shared_ptr<T>& r) {
- std::swap(ptr_, r.ptr_);
- std::swap(control_block_, r.control_block_);
- }
-
- // The following function is useful for gaining access to the underlying
- // pointer when a shared_ptr remains in scope so the reference-count is
- // known to be > 0 (e.g. for parameter passing).
- T* get() const {
- return ptr_;
- }
-
- T& operator*() const {
- return *ptr_;
- }
-
- T* operator->() const {
- return ptr_;
- }
-
- long use_count() const {
- return control_block_ ? control_block_->refcount_ : 1;
- }
-
- bool unique() const {
- return use_count() == 1;
- }
-
- private:
- // If r is non-empty, initialize *this to share ownership with r,
- // increasing the underlying reference count.
- // If r is empty, *this remains empty.
- // Requires: this is empty, namely this->ptr_ == NULL.
- template <typename U>
- void Initialize(const shared_ptr<U>& r) {
- if (r.control_block_ != NULL) {
- ++r.control_block_->refcount_;
-
- ptr_ = r.ptr_;
- control_block_ = r.control_block_;
- }
- }
-
- T* ptr_;
- SharedPtrControlBlock* control_block_;
-
- template <typename U>
- friend class shared_ptr;
-};
-
-// Matches the interface of std::swap as an aid to generic programming.
-template <typename T> void swap(shared_ptr<T>& r, shared_ptr<T>& s) {
- r.swap(s);
-}
-
-// See comments at the top of the file for a description of why this
-// class exists, and the draft C++ standard (as of October 2007 the
-// latest draft is N2461) for the detailed specification.
-template <typename T>
-class weak_ptr {
- template <typename U> friend class weak_ptr;
- public:
- typedef T element_type;
-
- // Create an empty (i.e. already expired) weak_ptr.
- weak_ptr() : ptr_(NULL), control_block_(NULL) { }
-
- // Create a weak_ptr that observes the same object that ptr points
- // to. Note that there is no race condition here: we know that the
- // control block can't disappear while we're looking at it because
- // it is owned by at least one shared_ptr, ptr.
- template <typename U> weak_ptr(const shared_ptr<U>& ptr) {
- CopyFrom(ptr.ptr_, ptr.control_block_);
- }
-
- // Copy a weak_ptr. The object it points to might disappear, but we
- // don't care: we're only working with the control block, and it can't
- // disappear while we're looking at because it's owned by at least one
- // weak_ptr, ptr.
- template <typename U> weak_ptr(const weak_ptr<U>& ptr) {
- CopyFrom(ptr.ptr_, ptr.control_block_);
- }
-
- // Need non-templated version to prevent default copy constructor
- weak_ptr(const weak_ptr& ptr) {
- CopyFrom(ptr.ptr_, ptr.control_block_);
- }
-
- // Destroy the weak_ptr. If no shared_ptr owns the control block, and if
- // we are the last weak_ptr to own it, then it can be deleted. Note that
- // weak_count_ is defined as the number of weak_ptrs sharing this control
- // block, plus 1 if there are any shared_ptrs. We therefore know that it's
- // safe to delete the control block when weak_count_ reaches 0, without
- // having to perform any additional tests.
- ~weak_ptr() {
- if (control_block_ != NULL &&
- (--control_block_->weak_count_) == 0) {
- delete control_block_;
- }
- }
-
- weak_ptr& operator=(const weak_ptr& ptr) {
- if (&ptr != this) {
- weak_ptr tmp(ptr);
- tmp.swap(*this);
- }
- return *this;
- }
- template <typename U> weak_ptr& operator=(const weak_ptr<U>& ptr) {
- weak_ptr tmp(ptr);
- tmp.swap(*this);
- return *this;
- }
- template <typename U> weak_ptr& operator=(const shared_ptr<U>& ptr) {
- weak_ptr tmp(ptr);
- tmp.swap(*this);
- return *this;
- }
-
- void swap(weak_ptr& ptr) {
- ::swap(ptr_, ptr.ptr_);
- ::swap(control_block_, ptr.control_block_);
- }
-
- void reset() {
- weak_ptr tmp;
- tmp.swap(*this);
- }
-
- // Return the number of shared_ptrs that own the object we are observing.
- // Note that this number can be 0 (if this pointer has expired).
- long use_count() const {
- return control_block_ != NULL ? control_block_->refcount_ : 0;
- }
-
- bool expired() const { return use_count() == 0; }
-
- private:
- void CopyFrom(T* ptr, SharedPtrControlBlock* control_block) {
- ptr_ = ptr;
- control_block_ = control_block;
- if (control_block_ != NULL)
- ++control_block_->weak_count_;
- }
-
- private:
- element_type* ptr_;
- SharedPtrControlBlock* control_block_;
-};
-
-template <typename T> void swap(weak_ptr<T>& r, weak_ptr<T>& s) {
- r.swap(s);
-}
-
-#endif // UTIL_GTL_PURITAN_SHARED_PTR_H__
diff --git a/o3d/compiler/puritan/rand.cc b/o3d/compiler/puritan/rand.cc
deleted file mode 100644
index 7a4775b..0000000
--- a/o3d/compiler/puritan/rand.cc
+++ /dev/null
@@ -1,150 +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 <cstddef>
-#include <iostream>
-#include "rand.h"
-#include "puritan_assert.h"
-
-namespace Salem
-{
-namespace Puritan
-{
-static const unsigned a = 1103515245 ;
-static const unsigned b = 12345;
-
-// Convention:
-// If seed passed in is zero, this class will use the strong random number
-// generator from crypto API via CryptGenRandom()
-// Otherwise fallback to the linear-congruential generator.
-Rand::Rand (unsigned seed) : y (seed+1231)
-{
- crypt_provider_ = NULL;
- available_ = 0;
- if (seed == 0)
- InitializeProvider();
-}
-
-unsigned Rand::rnd_uint(void)
-{
- unsigned result = 0;
- // If there is no provider, use the LCG.
- if (crypt_provider_ == NULL) {
- y = (a * y + b);
- result = y >> 4;
- }
-#ifdef _WIN32
- // The following code is used for improved random-number generation.
- // TODO: Investigate use of openssl, which may do this on all
- // platforms, but will still require platform-specific seeding.
- else {
- // Maintain a cache of random values by getting a large batch
- // on each call, since calling CryptGenRandom() is expensive.
- // Note: This code is not thread-safe, neither is the original LCG.
- // Use InterlockedDecrement/CompareXchg etc. if that has to change.
- long chosen_index = --available_;
-
- if (chosen_index < 0) {
- // We are out of values, time to replenish the cache.
- ::CryptGenRandom(crypt_provider_, sizeof(cached_numbers_),
- reinterpret_cast<BYTE*>(cached_numbers_));
- available_ = kCacheSize;
- chosen_index = --available_;
- }
-
- result = cached_numbers_[chosen_index];
- }
-#endif
-
- return result;
-}
-
-double Rand::rnd_flt()
-{
- unsigned r = rnd_uint();
- // We don't ask for the full range of random numbers because
- // I see different rounding behavior on different machines at the limit.
- unsigned mask = 0xffffff;
- unsigned div = mask + 1;
- double dr = r & mask;
- double res = dr / div;
- return res;
-}
-
-int Rand::range (int from, int to)
-{
- PURITAN_ASSERT (from <= to, "Range is malformed");
- if (from == to)
- {
- return from;
- }
- double x = (rnd_flt ()) * (to - from) + from;
- int r = static_cast <int>(x);
- return r;
-}
-
-unsigned Rand::urange (unsigned from, unsigned to)
-{
- return range (from, to);
-}
-
-size_t Rand::srange (size_t from, size_t to)
-{
- return range (static_cast <int>(from),
- static_cast <int>(to));
-}
-
-// Return random string from list of strings.
-const char *Rand::from_list (const char **list)
-{
- unsigned int i;
- for (i = 0; list[i]; i++)
- ;
- unsigned rn = range (0, i);
- return list[rn];
-}
-
-bool Rand::InitializeProvider() {
-#ifdef _WIN32
- int result = ::CryptAcquireContext(& crypt_provider_, NULL, NULL,
- PROV_RSA_FULL,
- CRYPT_VERIFYCONTEXT);
- return (result != 0);
-#else
- // If there is no cryptographic PRNG, this is a noop.
- return true;
-#endif
-}
-
-}
-}
diff --git a/o3d/compiler/puritan/rand.h b/o3d/compiler/puritan/rand.h
deleted file mode 100644
index d5804c0..0000000
--- a/o3d/compiler/puritan/rand.h
+++ /dev/null
@@ -1,73 +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 PURITAN_RAND_H
-#define PURITAN_RAND_H
-
-// Use a strong RNG if available.
-// TODO: Investigate using openssl on all platforms.
-#ifdef _WIN32
-#include <windows.h>
-#include <wincrypt.h>
-#else
-typedef void* HCRYPTPROV;
-#endif
-
-
-namespace Salem
-{
-namespace Puritan
-{
-
-class Rand
-{
-public:
- unsigned y;
- unsigned rnd_uint(void) ;
- Rand(unsigned seed);
- double rnd_flt(void);
- int range(int lo, int hi);
- unsigned urange(unsigned lo, unsigned hi);
- size_t srange(size_t lo, size_t hi);
- const char *from_list (const char **);
-
-private:
- bool InitializeProvider();
-
- HCRYPTPROV crypt_provider_;
- static const size_t kCacheSize = 0x1000;
- unsigned int cached_numbers_[kCacheSize];
- long available_;
-};
-}
-}
-#endif
diff --git a/o3d/compiler/puritan/structure_gen.cc b/o3d/compiler/puritan/structure_gen.cc
deleted file mode 100644
index 2be25c7..0000000
--- a/o3d/compiler/puritan/structure_gen.cc
+++ /dev/null
@@ -1,328 +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 <sstream>
-#include "structure_gen.h"
-#include "exp_gen.h"
-namespace Salem
-{
-namespace Puritan
-{
-class Context;
-
-//////////////////////////////////////////////////////////////////////
-// Blocks
-
-void Block::print_code (ostream &out)
-{
- print_code_kids (children, out);
-}
-
-void Block::add_child (CodeSPtr x)
-{
- children.push_back (x);
-}
-
-//////////////////////////////////////////////////////////////////////
-// Functions
-
-Function::Function(Gen *_gen,
- unsigned _idx,
- TypeList _ret_type,
- DeclList _formals,
- bool _standalone,
- bool _noinline)
- : gen (_gen),
- idx (_idx),
- ret_type (_ret_type),
- formals (_formals),
- standalone (_standalone),
- noinline (_noinline)
-{
-
-}
-
-void Function::output_code (ostream &out)
-{
- // main always returns a struct
- if (idx == 0)
- {
- if (standalone)
- {
- out << "struct ";
- }
-
- out << "PS_OUTPUT main (";
- }
- else
- {
- if (noinline)
- {
- out << "noinline ";
-
- }
- out << ret_type << " func" << idx << "(";
- }
- unsigned arg_idx = 0;
-
- for (DeclList::iterator i = formals.begin();
- i != formals.end();
- i++, arg_idx++)
- {
- if (arg_idx != 0)
- {
- out << ", ";
- }
-
- out << (*i).type << " " << (*i);
-
- if (standalone && idx == 0)
- {
- out << ":VPOS";
- }
- }
-
- out << ")\n";
-
-
- ostringstream code;
-
- for (CodeVec::iterator x = children.begin();
- x != children.end();
- x++)
- {
- (*x)->print_code (code);
- }
-
- // emit the declarations at the top of the function and then the guts.
- out << "{"
- << gspair (gen, Scope(Static, idx))
- << code.str()
- << "}";
-}
-
-//////////////////////////////////////////////////////////////////////
-/// For loops
-
-For::For(Decl _counter, int _from, int _to)
- : from (_from), to (_to), counter (_counter)
-{
-
-}
-
-void For::print_code (ostream &out)
-{
- out << "for (" << counter << " = " << from << ";"
- << counter << " < " << to <<"; "
- << counter << "++)\n";
- print_code_kids (children, out);
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Breaks in loops
-
-Break::Break (ENode _cond)
- : cond (_cond)
-{
-}
-
-void Break::print_code (ostream &out)
-{
- out << "if (" << cond << ")\n{ break;}\n";
-}
-
-//////////////////////////////////////////////////////////////////////
-/// While loops
-
-While::While(ENode _cond,
- Decl _index,
- unsigned _limit)
- : cond(_cond),
- counter (_index),
- limit (_limit)
-{
-}
-
-void While::print_code (ostream &out)
-{
- out << counter << " = " << limit << ";\n"
- << "while (" << counter << "> 0 &&"
- << cond << ")\n"
- << "{" << "--" << counter << ";\n";
-
- for (CodeVec::iterator x = children.begin();
- x != children.end();
- x++)
- {
- (*x)->print_code (out);
- }
-
- out << "}";
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Do loops
-
-Do::Do(ENode _cond, Decl _counter, unsigned _limit)
- : cond(_cond),
- counter (_counter),
- limit (_limit)
-{
-}
-
-void Do::print_code (ostream &out)
-{
- out << counter << " = " << limit << ";\n"
- << "do {";
-
- for (CodeVec::iterator x = children.begin();
- x != children.end();
- x++)
- {
- (*x)->print_code (out);
- }
-
- out << "--" << counter << ";\n"
- << "} while (" << counter << "> 0 &&"
- << cond << ");\n";
-}
-
-//////////////////////////////////////////////////////////////////////
-// Ifs
-
-IfTemplate::IfTemplate(ENode _cond, bool _has_else)
- : cond (_cond),
- has_else (_has_else),
- toggle (false)
-{
-}
-
-void IfTemplate::print_code (ostream &out)
-{
- out << "if (" << cond << ")\n";
-
- print_code_kids (children, out);
- if (has_else)
- {
- out << "else\n";
- print_code_kids (other_block, out);
- }
-
-}
-
-void IfTemplate::add_child (CodeSPtr x)
-{
- if (toggle && has_else)
- {
- other_block.push_back (x);
- }
- else
- {
- children.push_back (x);
- }
-
- toggle = ! toggle;
-}
-
-//////////////////////////////////////////////////////////////////////
-// Return
-
-Return::Return(EList _returns, Decl _name)
- : returns (_returns),
- name (_name)
-{
-}
-
-Return::Return(ENode _reta) : name(false)
-{
- returns.push_back (_reta);
-}
-
-void Return::print_code (ostream &out)
-{
- if (name.type != NoType)
- {
- const char *ext[] = {".color0", ".color1", ".color2", ".color3" };
- unsigned k = 0;
- for (EList::const_iterator i = returns.begin();
- i != returns.end();
- i++, k++)
- {
- out << name << ext[k] << " = " << *i << ";\n";
- }
- out << "return " << name << ";\n";
- }
- else
- {
- out << "return " << returns.front() << ";\n";
- }
-}
-
-//////////////////////////////////////////////////////////////////////
-// Assignments
-
-AssignmentTemplate::AssignmentTemplate(ENode _terms)
- : rp (_terms)
-{
-}
-
-void AssignmentTemplate::print_code (ostream &out)
-{
- out << rp << ";\n";
-}
-
-
-//////////////////////////////////////////////////////////////////////
-// Skeleton base class for all above
-Code::Code()
-{
-}
-
-Code::~Code()
-{
-}
-
-void Code::print_code_kids (CodeVec &children, ostream &out)
-{
- out << "{";
- for (CodeVec::iterator x = children.begin();
- x != children.end();
- x++)
- {
- (*x)->print_code (out);
- }
- out << "}";
-}
-
-}
-}
diff --git a/o3d/compiler/puritan/structure_gen.h b/o3d/compiler/puritan/structure_gen.h
deleted file mode 100644
index 04f4820..0000000
--- a/o3d/compiler/puritan/structure_gen.h
+++ /dev/null
@@ -1,204 +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 PURITAN_STRUCTUREGEN_H
-#define PURITAN_STRUCTUREGEN_H
-
-#include "puritan.h"
-
-namespace Salem
-{
-namespace Puritan
-{
-typedef ::shared_ptr<class Block> BlockSPtr;
-typedef ::shared_ptr<class Break> BreakSPtr;
-typedef ::shared_ptr<class Code> CodeSPtr;
-typedef ::shared_ptr<class Exp> ENode;
-typedef ::shared_ptr<class For> ForSPtr;
-typedef ::shared_ptr<class Function> FunctionSPtr;
-typedef std::vector <CodeSPtr> CodeVec;
-typedef std::vector <FunctionSPtr> FunctionVec;
-
-
-class Code
-{
- virtual void print_code (std::ostream &out) = 0;
-
-public:
- Code ();
- virtual ~Code();
-
- void print_code_kids (CodeVec &children, std::ostream &out);
-
- friend class Function;
- friend class While;
- friend class Do;
-};
-
-class Block:public Code
-{
- void print_code (std::ostream &out);
-
-public:
- CodeVec children;
-
- void add_child (CodeSPtr x);
-};
-
-class Function:public Block
-{
-public:
- class Gen *gen;
- unsigned idx;
- TypeList ret_type;
- DeclList formals;
- UList samplers;
- FunctionSPtr calls;
- std::string name;
- bool standalone;
- bool noinline;
-
- Function(Gen *gen, unsigned _idx,
- TypeList ret_type,
- DeclList formals,
- bool standalone,
- bool noinline);
-
- void new_decl (std::string name,
- Scope scope,
- FunctionSPtr func,
- enum type type,
- std::string init);
-
- void output_code (std::ostream &out);
-};
-
-
-
-class For : public Block
-{
-
- int from;
- int to;
-
- friend class Index;
- friend class ConstArrayRef;
-public:
-
- Decl counter;
-
- static unsigned fidx;
- For(Decl counter, int _from, int _to) ;
-
- void print_code (std::ostream &out);
-};
-
-class Break: public Code
-{
-public:
- ::shared_ptr<Exp> cond;
-
- Break (ENode _cond) ;
- void print_code (std::ostream &out);
-}
-;
-
-
-class While: public Block
-{
- ENode cond;
- Decl counter;
- unsigned limit;
-public:
- While(ENode _cond,
- Decl i,
- unsigned limit) ;
-
- void print_code (std::ostream &out);
-};
-
-
-class Do: public Block
-{
- ENode cond;
- Decl counter;
- unsigned limit;
-
-public:
- Do(ENode _cond, Decl counter, unsigned limit) ;
-
- void print_code (std::ostream &out);
-};
-
-class IfTemplate: public Block
-{
- ENode cond;
- bool has_else;
- bool toggle;
- CodeVec other_block;
-
-public:
- IfTemplate(ENode _cond, bool has_else);
-
- void print_code (std::ostream &out);
- void add_child (CodeSPtr x);
-};
-
-
-
-class Return : public Code
-{
-public:
- unsigned struct_elements;
- EList returns;
- Decl name;
-
- Return(ENode _reta) ;
- Return(EList _returns, Decl name) ;
-
- void print_code (std::ostream &out);
-};
-
-
-class AssignmentTemplate : public Code
-{
-public:
- ENode rp;
- AssignmentTemplate(ENode _terms) ;
- void print_code (std::ostream &out);
-};
-
-
-}
-}
-#endif
diff --git a/o3d/compiler/puritan/test_gen.cc b/o3d/compiler/puritan/test_gen.cc
deleted file mode 100644
index 85916a3..0000000
--- a/o3d/compiler/puritan/test_gen.cc
+++ /dev/null
@@ -1,50 +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 "puritan.h"
-#include "test_gen.h"
-#include <string>
-
-namespace Salem
-{
-namespace Puritan
-{
-string generate (class OutputInfo *output, Knobs & knobs)
-{
- class Gen *gen;
- gen = new Gen (knobs);
- std::string res = gen->generate (output);
- delete gen;
- return res;
-}
-}
-}
diff --git a/o3d/compiler/puritan/test_gen.h b/o3d/compiler/puritan/test_gen.h
deleted file mode 100644
index f5c2cf9..0000000
--- a/o3d/compiler/puritan/test_gen.h
+++ /dev/null
@@ -1,47 +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 PURITAN_TESTGEN_H
-#define PURITAN_TESTGEN_H
-
-#include <string>
-#include "knobs.h"
-namespace Salem
-{
-namespace Puritan
-{
-std::string generate(class OutputInfo *info,
- class Knobs &knobs);
-}
-}
-
-#endif
diff --git a/o3d/compiler/technique/Technique.g3pl b/o3d/compiler/technique/Technique.g3pl
deleted file mode 100644
index 9f71db1..0000000
--- a/o3d/compiler/technique/Technique.g3pl
+++ /dev/null
@@ -1,1126 +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.
- */
-
-//
-// Parse HLSL shaders and separate the shader code from the Technique block
-// parse the technique block into shader declarations and stateassignments
-// using a Parser and Lexer generated by Antlr3.0
-//
-// Compile from the command line using:
-//
-// $ set CLASSPATH=%CLASSPATH%;c:\bin\antlr\antlr-3.1.jar
-// $ java org.antlr.Tool Technique.g3pl
-// $ cl *.cc *.c /TP -I c:\bin\antlr\libantlr3c-3.1\include /c /nologo
-// $ link *.obj /LTCG /out:technique.exe c:\bin\antlr\antlr3c.lib \
-// /NODEFAULTLIB:libcmt.lib /nologo
-
-
-grammar Technique;
-
-options {
- language = C;
-}
-
-@lexer::preincludes {
-#include <vector>
-#include "base/logging.h"
-#include "core/cross/types.h"
-
-#ifdef OS_WIN
-// These need to be defined here so that when antlr includes
-// winsock.h, it doesn't barf. For some reason these are undefined by
-// some header (and it appears to be a windows header).
-#define IN
-#define OUT
-#endif
-}
-
-@lexer::postinclude {
- namespace o3d {
- void TechniqueError(pANTLR3_BASE_RECOGNIZER recognizer,
- pANTLR3_UINT8 * tokenNames);
- }
-}
-
-@lexer::apifuncs
-{
- // Install the custom error reporting function.
- RECOGNIZER->displayRecognitionError = o3d::TechniqueError;
-}
-
-@lexer::members {
- static int toInt(const pANTLR3_STRING string) {
- return atoi(reinterpret_cast<const char*>(string->chars));
- }
- static o3d::String toStringL(const pANTLR3_STRING string) {
- return o3d::String(reinterpret_cast<const char*>(string->chars));
- }
- // Removes escape sequences, as well as leading and trailing quotes.
- static ANTLR3_STRING* unescape(const pANTLR3_STRING string) {
- if (!string || !string->factory) return NULL;
- ANTLR3_STRING* s = string->factory->newRaw(string->factory);
- const char *f = reinterpret_cast<const char*>(string->chars);
- if (!f) return s;
- if (*f == '"') f++;
- for (; *f; f++) {
- if (*f == '\\') {
- switch (*++f) {
- case '\0': return s;
- case 'b': s->addc(s, '\b'); break;
- case 't': s->addc(s, '\t'); break;
- case 'n': s->addc(s, '\n'); break;
- case 'f': s->addc(s, '\f'); break;
- case 'r': s->addc(s, '\r'); break;
- default: s->addc(s, *f); break;
- }
- } else if (*f == '"') {
- return s;
- } else {
- s->addc(s, *f);
- }
- }
- return s;
- }
- static void setFilename(pANTLR3_BASE_RECOGNIZER rec,
- const pANTLR3_STRING filename) {
- if (filename) {
- // We store the filename into the "custom" field in the lexer state,
- // which gets copied into each token. If we use the fileName field
- // in the stream itself, when the lexer runs ahead of the parser
- // (which is often), the file name can be incorrect. By storing it
- // in the token itself, the error code can retrieve the filename
- // associated with that token.
- rec->state->custom = unescape(filename);
- }
- }
-}
-
-@parser::preincludes {
-// NOTE: this header must be included before the "antlr.h" header
-// because on Windows it includes <windows.h> which will define <winsock.h>
-// before <winsock2.h>, causing a cascade of struct redefinition errors.
-#ifdef OS_WIN
-// NOTE: disable compiler warning about C function returning a
-// struct. This is caused by the Antlr generated functions being declared
-// extern "C" but being compiled and used as C++.
-#pragma warning( disable: 4190 )
-#endif
-#include <vector>
-#include "base/logging.h"
-#include "base/string_util.h"
-#include "core/cross/types.h"
-#include "compiler/technique/technique_structures.h"
-}
-
-@parser::includes {
-// NOTE: includes that occur after the "antlr3.h" header has been
-// declared which therefore can use the Antlr3 datatypes.
-}
-
-@parser::postinclude {
- namespace o3d {
- void TechniqueError(pANTLR3_BASE_RECOGNIZER recognizer,
- pANTLR3_UINT8 * tokenNames);
- void TechniqueSetErrorString(String* e);
- }
-}
-
-@parser::apifuncs
-{
- // Install the custom error reporting function.
- RECOGNIZER->displayRecognitionError = o3d::TechniqueError;
-}
-
-@parser::members {
- o3d::String *shader_string_;
- o3d::TechniqueDeclarationList *technique_list_;
- o3d::SamplerStateList *sampler_list_;
- o3d::String *error_string_;
- // NOTE: the reinterpret casts below are
- // to cast from Antlr3's internal ANTLR_UINT8 strings to the UTF8
- // char* that O3D uses.
- o3d::String toString(const pANTLR3_STRING string) {
- return o3d::String(reinterpret_cast<const char*>(string->chars));
- }
- void addString(const pANTLR3_STRING string) {
- shader_string_->append(toString(string));
- }
- void addText(const pANTLR3_STRING string) {
- if (string && string->chars) {
- addString(string);
- shader_string_->append("\n");
- }
- }
- void sampler_state_assignment(const pANTLR3_STRING id,
- const pANTLR3_STRING value) {
- const char* idc = reinterpret_cast<const char *>(id->chars);
- if (!base::strcasecmp(idc, "MinFilter")) {
- sampler_list_->back().min_filter = toString(value);
- } else if (!base::strcasecmp(idc, "MagFilter")) {
- sampler_list_->back().mag_filter = toString(value);
- } else if (!base::strcasecmp(idc, "MipFilter")) {
- sampler_list_->back().mip_filter = toString(value);
- } else if (!base::strcasecmp(idc, "AddressU")) {
- sampler_list_->back().address_u = toString(value);
- } else if (!base::strcasecmp(idc, "AddressV")) {
- sampler_list_->back().address_v = toString(value);
- } else if (!base::strcasecmp(idc, "AddressW")) {
- sampler_list_->back().address_w = toString(value);
- } else if (!base::strcasecmp(idc, "BorderColor")) {
- sampler_list_->back().border_color = toString(value);
- } else if (!base::strcasecmp(idc, "MaxAnisotropy")) {
- sampler_list_->back().max_anisotropy = toString(value);
- }
- }
-}
-
-// rules -----------------------------------------------------------------------
-
-// This is the entry rule - zero or more global declarations followed by an
-// end-of-file token.
-translation_unit [o3d::TechniqueDeclarationList *technique_list,
- o3d::SamplerStateList *sampler_list,
- o3d::String *shader_string,
- o3d::String *error_string]
- returns [bool success]
-@init {
- // On entry, reset the list of error strings.
- technique_list_ = technique_list;
- sampler_list_ = sampler_list;
- shader_string_ = shader_string;
- error_string_ = error_string;
- o3d::TechniqueSetErrorString(error_string_);
-}
-@after {
- // On exit, set the return value.
- success = error_string_->length() == 0;
- technique_list_ = NULL;
- sampler_list_ = NULL;
- shader_string_ = NULL;
- error_string_ = NULL;
- o3d::TechniqueSetErrorString(NULL);
-}
- :
- ( noise global_declaration )* EOF
- ;
-
-noise
- :
- ( COMMENT | WHITESPACE | MULTILINE_COMMENT )* { addText($text); }
- | LINE_DIRECTIVE
- ;
-
-global_declaration
- : (function_storage_class? function_type_specifier IDENTIFIER LPAREN) => function_declaration
- { addText($text); }
- | sampler_declaration
- | texture_declaration
- | struct_definition
- { addText($text); }
- | typedef_definition
- { addText($text); }
- | var_declaration
- { addText($text); }
- | technique_definition
- ;
-
-// variables -------------------------------------------
-
-var_declaration
- : var_storage_class*
- var_type_modifier?
- var_datatype id_declaration
- semantic?
- annotation_list?
- ('=' initializer)?
- var_packoffset?
- var_register_bind?
- SEMI
- ;
-
-var_storage_class
- : EXTERN
- | NOINTERPOLATION
- | SHARED
- | STATIC
- | UNIFORM
- | VOLATILE
- ;
-
-var_type_modifier
- : T_CONST
- | ROW_MAJOR
- | COLUMN_MAJOR;
-
-var_datatype
- : buffer_type_specifier
- | scalar_type_or_string_specifier
- | vector_type_specifier
- | matrix_type_specifier
- | struct_type_specifier
- ;
-
-var_packoffset
- : 'packoffset' LPAREN register_name (DOT IDENTIFIER)? RPAREN
- ;
-
-var_register_bind
- : COLON register_name
- ;
-
-id_declaration
- : IDENTIFIER ( LBRACKET constant_expression RBRACKET )?
- ;
-
-// function --------------------------------------------
-
-function_declaration
- : function_storage_class?
- function_type_specifier IDENTIFIER LPAREN argument_list RPAREN semantic?
- function_body (SEMI)?
- ;
-
-function_storage_class
- : INLINE // ignoring platform target
- ;
-
-function_type_specifier
- : scalar_type_specifier
- | vector_type_specifier
- | matrix_type_specifier
- | struct_type_specifier
- | T_VOID
- ;
-
-semantic
- : COLON semantic_specifier ;
-
-param_type_specifier
- : scalar_type_specifier
- | vector_type_specifier
- | matrix_type_specifier
- | struct_type_specifier
- | string_type_specifier
- | sampler_type_specifier
- ;
-
-basic_type_specifier
- : scalar_type_specifier
- | vector_type_specifier
- | matrix_type_specifier
- | string_type_specifier
- ;
-
-// typedef ---------------------------------------
-
-typedef_definition
- : TYPEDEF
- ;
-
-// basic datatypes -------------------------------
-
-buffer_type_specifier
- : (BUFFER '<' var_datatype '>' IDENTIFIER)
- ;
-
-// effects ---------------------------------------------------------------------
-
-technique_definition
-@declarations {
- o3d::TechniqueDeclaration technique_decl;
-}
-@init {
- // clear the technique declaration before use
- technique_decl.clear();
-}
- : TECHNIQUE IDENTIFIER
- {
- technique_decl.name = toString($IDENTIFIER.text);
- }
- annotation_list? '{' ( pass[technique_decl] )+ '}' SEMI?
- {
- technique_list_->push_back(technique_decl);
- }
-
- | TECHNIQUE
- {
- technique_decl.name = "";
- }
- annotation_list? '{' ( pass[technique_decl] )+ '}' SEMI?
- {
- technique_list_->push_back(technique_decl);
- }
- ;
-
-pass [o3d::TechniqueDeclaration& technique_decl]
-@declarations {
- o3d::PassDeclaration pass_decl;
-}
-@after {
- $technique_decl.pass.push_back(pass_decl);
-}
- : PASS IDENTIFIER?
- {
- if ($IDENTIFIER != NULL && $IDENTIFIER.text->chars != NULL) {
- pass_decl.name = toString($IDENTIFIER.text);
- } else {
- *error_string_ += "Bad pass identifier, line ";
- *error_string_ += $PASS.line;
- }
- }
- annotation_list? '{' ( state_assignment[pass_decl] )* '}' SEMI?
- ;
-
-state_assignment [o3d::PassDeclaration& pass]
- : (VERTEXSHADER) =>
- x=VERTEXSHADER '=' 'compile' IDENTIFIER fn=variable_or_call_expression
- {
- $pass.vertex_shader_entry = $fn.identifier;
- $pass.vertex_shader_profile = toString($IDENTIFIER.text);
- $pass.vertex_shader_arguments = $fn.arglist;
- }
- SEMI
- | (FRAGMENTSHADER) =>
- x=FRAGMENTSHADER '=' 'compile' IDENTIFIER fn=variable_or_call_expression
- {
- $pass.fragment_shader_entry = $fn.identifier;
- $pass.fragment_shader_profile = toString($IDENTIFIER.text);
- $pass.fragment_shader_arguments = $fn.arglist;
- }
- SEMI
- | IDENTIFIER '=' val=primary_expression
- {
- if ($IDENTIFIER.text->chars == NULL) {
- *error_string_ += "Bad state assigment identifier, line ";
- *error_string_ += $IDENTIFIER.line;
-
- } else if ($val.text->chars == NULL) {
- *error_string_ = "Bad state assigment value, line ";
- *error_string_ += $IDENTIFIER.line;
- } else {
- o3d::StateAssignment state;
- state.name = toString($IDENTIFIER.text);
- state.value = toString($val.text);
- $pass.state_assignment.push_back(state);
- }
- }
- SEMI
- ;
-
-// data types ------------------------------------------------------------------
-
-scalar_type_specifier
- : 'bool'
- | 'int'
- | 'uint'
- | 'half'
- | FLOAT
- | 'double'
- ;
-
-scalar_type_or_string_specifier
- : scalar_type_specifier
- | string_type_specifier
- ;
-
-vector_type_specifier
- : 'bool1'
- | 'bool2'
- | 'bool3'
- | 'bool4'
- | 'int1'
- | 'int2'
- | 'int3'
- | 'int4'
- | 'uint1'
- | 'uint2'
- | 'uint3'
- | 'uint4'
- | 'half1'
- | 'half2'
- | 'half3'
- | 'half4'
- | 'float1'
- | 'float2'
- | 'float3'
- | 'float4'
- | 'double1'
- | 'double2'
- | 'double3'
- | 'double4'
- | VECTOR '<' scalar_type_specifier ',' DECIMAL_LITERAL '>'
- ;
-
-matrix_type_specifier
- : 'float1x1'
- | 'float1x2'
- | 'float1x3'
- | 'float1x4'
- | 'float2x1'
- | 'float2x2'
- | 'float2x3'
- | 'float2x4'
- | 'float3x1'
- | 'float3x2'
- | 'float3x3'
- | 'float3x4'
- | 'float4x1'
- | 'float4x2'
- | 'float4x3'
- | 'float4x4'
- | MATRIX '<' scalar_type_specifier ','
- DECIMAL_LITERAL ',' DECIMAL_LITERAL '>'
- ;
-
-string_type_specifier
- : STRING
- ;
-
-// Sampler declarations ----------------------------
-
-sampler_declaration
- : sampler_type_specifier id_declaration
- {
- o3d::SamplerState s;
- s.name = toString($id_declaration.text);
- sampler_list_->push_back(s);
- addString($sampler_type_specifier.text);
- shader_string_->append(" ");
- addString($id_declaration.text);
- shader_string_->append(";\n");
- }
- ( '=' 'sampler_state' '{' sampler_state_declaration+ '}' )? SEMI
- ;
-
-sampler_state_declaration
- : TEXTURE '=' '<' IDENTIFIER '>' SEMI
- { sampler_list_->back().texture = toString($IDENTIFIER.text); }
- | TEXTURE '=' '(' IDENTIFIER ')' SEMI
- { sampler_list_->back().texture = toString($IDENTIFIER.text); }
- | IDENTIFIER '=' initializer SEMI
- { sampler_state_assignment($IDENTIFIER.text, $initializer.text); }
- ;
-
-sampler_type_specifier
- : 'sampler'
- | 'sampler1D'
- | 'sampler2D'
- | 'sampler3D'
- | 'samplerCUBE'
- | 'sampler_state'
- | 'SamplerComparisonState' | 'samplercomparisonstate' // DX10 only
- ;
-
- // texture declaration ----------------------------
-
-texture_declaration
- : texture_type_specifier IDENTIFIER semantic? annotation_list? SEMI
- ;
-
-texture_type_specifier
- : TEXTURE
- | TEXTURE1D
- | TEXTURE2D
- | TEXTURE3D
- | TEXTURECUBE
- | TEXTURERECT
- ;
-
- // struct declaration -----------------------------
-
-struct_type_specifier
- : IDENTIFIER
- | ( STRUCT ( IDENTIFIER )? LCURLY ) => struct_definition
- | STRUCT IDENTIFIER
- ;
-
-annotation_list
- : '<' annotation* '>'
- ;
-
-annotation
- : basic_type_specifier IDENTIFIER '=' initializer SEMI
- ;
-
-initializer
- : expression
- | '{' expression ( ',' expression )* '}'
- ;
-
-register_name
- // registers for VS_3_0
- : REGISTER '(' input_register_name | output_register_name ')';
-
-input_register_name
- : IDENTIFIER DECIMAL_LITERAL
- // IDENTIFIER must be v, r, c, b, i, s, o (check semantically)
- | IDENTIFIER
- // IDENTIFIER must be a0 aL p0 (check semantically)
- ;
-
-output_register_name
- : IDENTIFIER
- // must be one of: 'oD0', 'oD1', 'oFog', 'oPos', 'oPts',
- // 'oT0', 'oT1', 'oT2', 'oT3', 'oT4', 'oT5', 'oT6', 'oT7'
- // (check semantically)
- ;
-
-pack_offset
- : .+ ; // no idea what this field looks like.
-
-argument_list
- : ( param_declaration ( COMMA param_declaration )* )?
- ;
-
-param_declaration
- : param_direction? param_variability? param_type_specifier id_declaration semantic?
-// | FUNCTION type_specifier IDENTIFIER
- ;
-
-param_variability
- : T_CONST
- | UNIFORM
- ;
-
-param_direction
- : T_IN
- | T_OUT
- | T_INOUT
- ;
-
-function_body
- : LCURLY ( decl_or_statement )* RCURLY
- ;
-
-decl_or_statement
- // We copied the following sub-rule here to expedite the parsing time
- // as this is a much more common case than the "Id init_declarator_list"
- // case which would normally spend a lot of time in exception handling.
- : (lvalue_expression assignment_operator ) => assignment_statement
- | ( ( T_CONST )? vector_type_specifier ) => ( T_CONST )? vector_type_specifier init_declarator_list SEMI
- | ( ( T_CONST )? scalar_type_specifier ) => ( T_CONST )? scalar_type_specifier init_declarator_list SEMI
- | ( ( T_CONST )? matrix_type_specifier ) => ( T_CONST )? matrix_type_specifier init_declarator_list SEMI
- | ( STRUCT ( IDENTIFIER )? LCURLY ) => struct_definition ( init_declarator_list )? SEMI
- | STRUCT IDENTIFIER init_declarator_list SEMI
- | ( IDENTIFIER init_declarator_list ) => IDENTIFIER init_declarator_list SEMI
- | statement
- ;
-
-init_declarator_list
- : init_declarator ( COMMA init_declarator )* ;
-
-init_declarator
- : declarator ( ASSIGN expression )? ;
-
-declarator
- : IDENTIFIER ( LBRACKET ( constant_expression )? RBRACKET )*
- ;
-
-struct_definition
- : STRUCT ( IDENTIFIER )? LCURLY struct_declaration_list RCURLY IDENTIFIER? SEMI
- ;
-
-struct_declaration_list
- // We currently don't support nested structs so the field type
- // can only be either a scalar or a vector.
- : ( struct_interpolation_modifier?
- (scalar_type_specifier|vector_type_specifier) IDENTIFIER
- (COLON semantic_specifier)? SEMI )+
- ;
-
-struct_interpolation_modifier // DX10 only
- : T_LINEAR
- | CENTROID
- | NOINTERPOLATION
- | NOPERSPECTIVE
- ;
-
-semantic_specifier
- : IDENTIFIER
- ;
-
-statement
- : ( lvalue_expression assignment_operator ) => assignment_statement
- | ( lvalue_expression self_modify_operator ) => post_modify_statement
- | pre_modify_statement
- | expression_statement
- | compound_statement
- | selection_statement
- | iteration_statement
- | jump_statement
- | SEMI
- ;
-
-assignment_statement
- : lvalue_expression assignment_operator expression SEMI
- ;
-
-pre_modify_statement
- : pre_modify_expression SEMI ;
-
-pre_modify_expression
- : self_modify_operator lvalue_expression ;
-
-post_modify_statement
- : post_modify_expression SEMI ;
-
-post_modify_expression
- : lvalue_expression self_modify_operator ;
-
-self_modify_operator
- : PLUS_PLUS | MINUS_MINUS ;
-
-expression_statement
- : expression SEMI ;
-
-compound_statement
- : LCURLY (
- ( IDENTIFIER init_declarator_list) => IDENTIFIER init_declarator_list SEMI
- | ( ( T_CONST )? vector_type_specifier ) => ( T_CONST )? vector_type_specifier init_declarator_list SEMI
- | ( ( T_CONST )? scalar_type_specifier ) => ( T_CONST )? scalar_type_specifier init_declarator_list SEMI
- | ( STRUCT ( IDENTIFIER )? LCURLY ) => struct_definition ( init_declarator_list )? SEMI
- | STRUCT IDENTIFIER init_declarator_list SEMI
- | statement
- )*
- RCURLY
- ;
-
-selection_statement
- : IF LPAREN expression RPAREN statement ( ELSE statement )?
- ;
-
-iteration_statement
- : WHILE LPAREN expression RPAREN statement
- | FOR LPAREN assignment_statement
- equality_expression SEMI modify_expression RPAREN statement
- | DO statement WHILE LPAREN expression RPAREN SEMI
- ;
-
-modify_expression
- : (lvalue_expression assignment_operator ) =>
- lvalue_expression assignment_operator expression
- | pre_modify_expression
- | post_modify_expression
- ;
-
-jump_statement
- : BREAK SEMI
- | CONTINUE
- | RETURN ( expression )? SEMI
- | DISCARD
- ;
-
-expression
- : conditional_expression
- ;
-
-assignment_operator
- : ASSIGN
- | MUL_ASSIGN
- | DIV_ASSIGN
- | ADD_ASSIGN
- | SUB_ASSIGN
- | BITWISE_AND_ASSIGN
- | BITWISE_OR_ASSIGN
- | BITWISE_XOR_ASSIGN
- | BITWISE_SHIFTL_ASSIGN
- | BITWISE_SHIFTR_ASSIGN
- ;
-
-constant_expression
- : (IDENTIFIER) => variable_expression
- | literal_value
- ;
-
-conditional_expression
- : logical_or_expression ( QUESTION expression COLON conditional_expression )?
- ;
-
-logical_or_expression
- : exclusive_or_expression ( OR exclusive_or_expression )*
- ;
-
-// We remove the NOT operator from the unary expression and stick it here
-// so that it has a lower precedence than relational operations.
-logical_and_expression
- : ( NOT )? inclusive_or_expression ( AND ( NOT )? inclusive_or_expression )*
- ;
-
-inclusive_or_expression
- : exclusive_or_expression (BITWISE_OR exclusive_or_expression )*
- ;
-
-exclusive_or_expression
- : and_expression ( BITWISE_XOR and_expression )*
- ;
-
-and_expression
- : equality_expression ( BITWISE_AND equality_expression )*
- ;
-
-equality_expression
- : relational_expression ( (EQUAL|NOT_EQUAL) relational_expression )*
- ;
-
-relational_expression
- : shift_expression ( (LESS|GREATER|LESSEQUAL|GREATEREQUAL) shift_expression )*
- ;
-
-shift_expression
- : additive_expression ( (BITWISE_SHIFTL|BITWISE_SHIFTR) additive_expression )*
- ;
-
-additive_expression
- : multiplicative_expression ( (PLUS|MINUS) multiplicative_expression )*
- ;
-
-multiplicative_expression
- : cast_expression ( (MUL|DIV|MOD) cast_expression )*
- ;
-
-cast_expression
- : LPAREN IDENTIFIER RPAREN postfix_expression
- | LPAREN basic_type_specifier RPAREN postfix_expression
- | unary_expression
- ;
-
-unary_expression
- : (PLUS|MINUS) unary_expression
- | postfix_expression
- ;
-
-postfix_expression
- : primary_expression ( postfix_suffix )?
- ;
-
-lvalue_expression
- : variable_expression ( postfix_suffix )?
- ;
-
-postfix_suffix
- // choosing between struct field access or vector swizzling is a semantic choice.
- : ( DOT primary_expression )+
- ;
-
-primary_expression
- : constructor
- | variable_or_call_expression
- | literal_value
- | LPAREN expression RPAREN
- ;
-
-variable_expression
- : IDENTIFIER ( LBRACKET expression RBRACKET )?
- ;
-
-// Combine variable expression and call expression here to get rid of the
-// syntactic predicate we used to use in the primary_expression rule. Using
-// predicates results in the parser spending a lot of time in exception
-// handling (when lookahead fails).
-variable_or_call_expression
- returns [o3d::String identifier, o3d::String arglist]
- : IDENTIFIER
- (
- ( ( LBRACKET expression RBRACKET )? )
- {
- $identifier = toString($IDENTIFIER.text);
- $arglist = "";
- }
- |
- ( LPAREN argument_expression_list RPAREN )
- {
- $identifier = toString($IDENTIFIER.text);
- if ($argument_expression_list.text->chars) {
- $arglist = toString($argument_expression_list.text);
- } else {
- $arglist = "";
- }
- }
- )
- ;
-
-constructor
- : ( vector_type_specifier | matrix_type_specifier )
- LPAREN expression ( COMMA expression )* RPAREN
- ;
-
-argument_expression_list
- : ( expression ( COMMA expression )* )?
- ;
-
-int_literal
- : DECIMAL_LITERAL
-// | OCT_LITERAL
-// | HEX_LITERAL
- ;
-
-literal_value
- : DECIMAL_LITERAL
- | FLOAT_LITERAL
- | STRING_LITERAL+
- | ( T_FALSE | T_TRUE )
- ;
-
-float_literal
- : FLOAT_LITERAL
- ;
-
-// lexical elements ------------------------------------------------------------
-
-NOT : '!' ;
-NOT_EQUAL : '!=' ;
-AND : '&&' ;
-LPAREN : '(' ;
-RPAREN : ')' ;
-MUL : '*' ;
-MUL_ASSIGN : '*=' ;
-PLUS : '+' ;
-PLUS_PLUS : '++' ;
-ADD_ASSIGN : '+=' ;
-COMMA : ',' ;
-MINUS : '-' ;
-MINUS_MINUS : '--' ;
-SUB_ASSIGN : '-=' ;
-DIV : '/' ;
-DIV_ASSIGN : '/=' ;
-MOD : '%';
-MOD_ASSIGN : '%=';
-COLON : ':' ;
-SEMI : ';' ;
-LESS : '<' ;
-LESSEQUAL : '<=' ;
-ASSIGN : '=' ;
-EQUAL : '==' ;
-GREATER : '>' ;
-GREATEREQUAL : '>=' ;
-QUESTION : '?' ;
-LBRACKET : '[' ;
-RBRACKET : ']' ;
-LCURLY : '{' ;
-OR : '||' ;
-RCURLY : '}' ;
-DOT : '.' ;
-BITWISE_NOT : '~';
-BITWISE_SHIFTL : '<<';
-BITWISE_SHIFTR : '>>';
-BITWISE_AND : '&';
-BITWISE_OR : '|';
-BITWISE_XOR : '^';
-BITWISE_SHIFTL_ASSIGN : '<<=';
-BITWISE_SHIFTR_ASSIGN : '>>=';
-BITWISE_AND_ASSIGN : '&=';
-BITWISE_OR_ASSIGN : '|=';
-BITWISE_XOR_ASSIGN : '^=';
-// keywords ----------------------------
-
-BREAK : 'break';
-BUFFER : 'buffer';
-COLUMN_MAJOR : 'column_major';
-CBUFFER : 'cbuffer';
-CENTROID : 'centroid';
-T_CONST : 'const';
-CONTINUE : 'continue';
-DISCARD : 'discard';
-DO : 'do';
-ELSE : 'else';
-EXTERN : 'extern';
-T_FALSE : 'false';
-FLOAT : (('f'|'F')('l'|'L')('o'|'O')('a'|'A')('t'|'T'));
-FOR : 'for';
-IF : 'if';
-T_IN : 'in';
-INLINE : 'inline';
-T_INOUT : 'inout';
-T_LINEAR : 'linear';
-MATRIX : ('m'|'M')('a'|'A')('t'|'T')('r'|'R')('i'|'I')('x'|'X');
-NAMESPACE : 'namespace';
-NOINTERPOLATION : 'nointerpolation';
-NOPERSPECTIVE : 'noperspective';
-T_OUT : 'out';
-RETURN : 'return';
-REGISTER : 'register';
-ROW_MAJOR : 'row_major';
-SHARED : 'shared';
-STATEBLOCK : 'stateblock';
-STATEBLOCK_STATE : 'stateblock_state';
-STATIC : 'static';
-STRING : ('s'|'S')('t'|'T')('r'|'R')('i'|'I')('n'|'N')('g'|'G');
-STRUCT : 'struct';
-SWITCH : 'switch';
-TBUFFER : 'tbuffer';
-TEXTURE :
- ('t'|'T')('e'|'E')('x'|'X')('t'|'T')('u'|'U')('r'|'R')('e'|'E');
-TEXTURE1D : 'Texture1D';
-TEXTURE1DARRAY : 'Texture1DArray';
-TEXTURE2D : 'Texture2D';
-TEXTURE2DARRAY : 'Texture2DArray';
-TEXTURE2DMS : 'Texture2DMS';
-TEXTURE2DMSARRAY : 'Texture2DMSArray';
-TEXTURE3D : 'Texture3D';
-TEXTURECUBE : 'TextureCUBE';
-TEXTURECUBEARRAY : 'TextureCUBEArray';
-TEXTURERECT : 'TextureRECT';
-T_TRUE : 'true';
-TYPEDEF : 'typedef';
-UNIFORM : 'uniform';
-VECTOR : ('v'|'V')('e'|'E')('c'|'C')('t'|'T')('o'|'O')('r'|'R');
-T_VOID : 'void';
-VOLATILE : 'volatile';
-WHILE : 'while';
-
-// sampler state tokens
-
-PASS : ('p'|'P')('a'|'A')('s'|'S')('s'|'S');
-
-TECHNIQUE : ('t'|'T')('e'|'E')('c'|'C')('h'|'H')
- ('n'|'N')('i'|'I')('q'|'Q')('u'|'U')('e'|'E')
- ;
-
-VERTEXSHADER
- : (('v'|'V')('e'|'E')('r'|'R')('t'|'T')('e'|'E')('x'|'X'))
- ((('s'|'S')('h'|'H')('a'|'A')('d'|'D')('e'|'E')('r'|'R')) |
- (('p'|'P')('r'|'R')('o'|'O')('g'|'G')('r'|'R')('a'|'A')('m'|'M')))
- ;
-
-FRAGMENTSHADER
- : (('f'|'F')('r'|'R')('a'|'A')('g'|'G')('m'|'M')('e'|'E')('n'|'N')('t'|'T')
- ('p'|'P')('r'|'R')('o'|'O')('g'|'G')('r'|'R')('a'|'A')('m'|'M'))
- | (('p'|'P')('i'|'I')('x'|'X')('e'|'E')('l'|'L')
- ('s'|'S')('h'|'H')('a'|'A')('d'|'D')('e'|'E')('r'|'R'))
- ;
-
-RESERVED_WORDS
- : (('a'|'A')('S'|'s')('m'|'M'))
- | 'asm_fragment'
- | 'auto'
- | 'case'
- | 'catch'
- | 'char'
- | 'class'
- | 'const_cast'
- | (('d'|'D')('e'|'E')('c'|'C')('l'|'L'))
- | 'default'
- | 'delete'
- | (('d'|'D')('w'|'W')('o'|'O')('r'|'R')('d'|'D'))
- | 'dynamic_cast'
- | 'emit'
- | 'enum'
- | 'explicit'
- | 'fixed'
- | 'friend'
- | 'get'
- | 'goto'
- | 'interface'
- | 'long'
- | 'mutable'
- | 'new'
- | 'operator'
- | 'packed'
- | (('p'|'P')('i'|'I')('x'|'X')('e'|'E')('l'|'L')
- ('f'|'F')('r'|'R')('a'|'A')('g'|'G')('m'|'M')('e'|'E')('n'|'N')('t'|'T'))
- | 'private'
- | 'protected'
- | 'public'
- | 'reinterpret_cast'
- | 'short'
- | 'signed'
- | 'sizeof'
- | 'snorm'
- | 'static_cast'
- | 'template'
- | 'this'
- | 'throw'
- | 'try'
- | 'typeid'
- | 'typename'
- | 'union'
- | 'unorm'
- | 'unsigned'
- | 'using'
- | (('v'|'V')('e'|'E')('r'|'R')('t'|'T')('e'|'E')('x'|'X')
- ('f'|'F')('r'|'R')('a'|'A')
- ('g'|'G')('m'|'M')('e'|'E')('n'|'N')('t'|'T'))
- | 'virtual'
- ;
-
-IDENTIFIER
- : ('a'..'z'|'A'..'Z'|'_')('a'..'z'|'A'..'Z'|'_'|'0'..'9')*
- ;
-
-DECIMAL_LITERAL
- : ('0'..'9')+
- ;
-
-fragment ESCAPE_SEQUENCE
- : '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\')
- ;
-
-CHARACTER_LITERAL
- : '\'' ( ESCAPE_SEQUENCE | ~('\''|'\\') ) '\''
- ;
-
-STRING_LITERAL
- : '"' ( ESCAPE_SEQUENCE | ~('\\'|'"') )* '"'
- ;
-
-fragment EXPONENT : ('e'|'E') (PLUS | MINUS)? ('0'..'9')+ ;
-
-fragment FLOATSUFFIX : ('f'|'F'|'h'|'H') ;
-
-FLOAT_LITERAL
- : ('0'..'9')+ '.' ('0'..'9')* (EXPONENT)? (FLOATSUFFIX)?
- | '.' ('0'..'9')+ (EXPONENT)? (FLOATSUFFIX)?
- ;
-
-// skipped elements ------------------------------------------------------------
-
-LINE_DIRECTIVE
- : '#line' (' '|'\t')* line_num=DECIMAL_LITERAL '\r'? '\n'
- { INPUT->setLine(INPUT, toInt($line_num.text)); $channel = HIDDEN; }
- | '#line' (' '|'\t')* line_num=DECIMAL_LITERAL
- (' '|'\t')* file=STRING_LITERAL '\r'? '\n'
- { INPUT->setLine(INPUT, toInt($line_num.text)); $channel = HIDDEN;
- setFilename(RECOGNIZER, $file.text); }
- ;
-
-WHITESPACE
- : (' '|'\r'|'\t'|'\u000C'|'\n') { $channel = HIDDEN; }
- ;
-
-COMMENT
- : '//' ~('\n'|'\r')* '\r'? '\n' { $channel = HIDDEN; }
- ;
-
-MULTILINE_COMMENT
- : '/*' ( options {greedy=false;} : . )* '*/' { $channel = HIDDEN; }
- ;
-
-// -----------------------------------------------------------------------------
diff --git a/o3d/compiler/technique/technique.gyp b/o3d/compiler/technique/technique.gyp
deleted file mode 100644
index 04d09e9..0000000
--- a/o3d/compiler/technique/technique.gyp
+++ /dev/null
@@ -1,109 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 0,
- 'technique_out_dir': '<(SHARED_INTERMEDIATE_DIR)/technique',
- },
- 'includes': [
- '../../build/common.gypi',
- ],
- 'targets': [
- {
- 'target_name': 'o3dTechnique',
- 'type': 'static_library',
- 'dependencies': [
- '../../../<(antlrdir)/antlr.gyp:antlr3c',
- '../../../base/base.gyp:base',
- '../../core/core.gyp:o3dCore',
- ],
- 'include_dirs': [
- '<(technique_out_dir)',
- ],
- 'rules': [
- {
- 'rule_name': 'technique_parser',
- 'extension': 'g3pl',
- 'inputs' : [
- '../../../<(antlrdir)/lib/antlr-3.1.1.jar',
- ],
- 'outputs': [
- '<(technique_out_dir)/<(RULE_INPUT_ROOT)Lexer.c',
- '<(technique_out_dir)/<(RULE_INPUT_ROOT)Lexer.h',
- '<(technique_out_dir)/<(RULE_INPUT_ROOT)Parser.c',
- '<(technique_out_dir)/<(RULE_INPUT_ROOT)Parser.h',
- ],
- 'process_outputs_as_sources': 1,
- 'action': [
- 'java',
- '-cp', '../../../<(antlrdir)/lib/antlr-3.1.1.jar',
- 'org.antlr.Tool',
- '<(RULE_INPUT_PATH)',
- '-fo', '<(technique_out_dir)',
- '-Xconversiontimeout', '30000',
- ],
- },
- ],
- 'sources': [
- 'Technique.g3pl',
- 'technique_error.cc',
- 'technique_error.h',
- 'technique_parser.cc',
- 'technique_parser.h',
- 'technique_structures.cc',
- 'technique_structures.h',
- ],
- 'hard_dependency': 1,
- 'direct_dependent_settings': {
- 'include_dirs': [
- '<(technique_out_dir)',
- ],
- },
- 'msvs_settings': {
- 'VCCLCompilerTool': {
- 'CompileAs': '2',
- },
- },
- 'xcode_settings': {
- 'OTHER_CFLAGS': [
- '-x', 'c++',
- ],
- },
- 'conditions': [
- ['OS == "linux"',
- {
- 'cflags': [
- '-x', 'c++',
- ],
- }
- ],
- ],
- },
- {
- 'target_name': 'o3dTechniqueTest',
- 'type': 'none',
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)/unittest_data',
- 'files': [
- 'test_data/fur.fx',
- 'test_data/lambert.fx',
- 'test_data/noshader.fx',
- 'test_data/notechnique.fx',
- 'test_data/sampler_test.fx',
- 'test_data/shadow_map.fx',
- 'test_data/simple.fx',
- ],
- },
- ],
- },
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/compiler/technique/technique_error.cc b/o3d/compiler/technique/technique_error.cc
deleted file mode 100644
index 7545ac5..0000000
--- a/o3d/compiler/technique/technique_error.cc
+++ /dev/null
@@ -1,283 +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.
- */
-
-//
-// Custom error reporting functon for the Technique parser, as described in
-// the Antlr3 documention for the C Runtime at
-// http://www.antlr.org/api/C/using.html
-//
-// NOTE: These error functions are only designed to work with 8-bit
-// token streams.
-
-#include "core/cross/types.h"
-#include "compiler/technique/technique_error.h"
-
-namespace o3d {
-String* error_string;
-
-void TechniqueSetErrorString(String* e) {
- error_string = e;
-}
-
-void TechniqueError(pANTLR3_BASE_RECOGNIZER recognizer,
- pANTLR3_UINT8 * tokenNames) {
- // If the error string pointer has not been set, bail now.
- if (!error_string) return;
-
- pANTLR3_PARSER parser;
- pANTLR3_STRING token_text;
- pANTLR3_EXCEPTION exception;
- pANTLR3_COMMON_TOKEN token;
- pANTLR3_BASE_TREE theBaseTree;
- pANTLR3_COMMON_TREE theCommonTree;
-
- // Retrieve some info for easy reading.
- exception = recognizer->state->exception;
- token_text = NULL;
-
- pANTLR3_COMMON_TOKEN exception_token =
- static_cast<pANTLR3_COMMON_TOKEN>(exception->token);
- if (exception_token && exception_token->custom) {
- // The filename is retrieved from the "custom" field of the token, which
- // was put there by the lexer. The lexer gets it from the #line directives
- // in the pre-processed output.
- pANTLR3_STRING filename =
- static_cast<pANTLR3_STRING>(exception_token->custom);
- *error_string += reinterpret_cast<char*>(filename->chars);
- } else {
- if (exception_token && exception_token->type == ANTLR3_TOKEN_EOF) {
- *error_string += "End of input";
- } else {
- *error_string += "Unknown source";
- }
- }
-
- // Next comes the line number
- char buffer[10];
- base::snprintf(buffer, sizeof(buffer), "%d", exception->line);
- *error_string += "(";
- *error_string += buffer;
- *error_string += ")";
-
- *error_string += ": Error: ";
- *error_string += reinterpret_cast<char*>(exception->message);
-
- // Find out what part of the system raised the error.
- switch (recognizer->type) {
- case ANTLR3_TYPE_PARSER: {
- // This is a normal Parser error. Prepare the information we have
- // available.
- parser = (pANTLR3_PARSER)(recognizer->super);
- token = (pANTLR3_COMMON_TOKEN)(exception->token);
-
- *error_string += ", at offset ";
- base::snprintf(buffer, sizeof(buffer), "%d",
- exception->charPositionInLine);
- *error_string += buffer;
- if (token != NULL) {
- if (token->type == ANTLR3_TOKEN_EOF) {
- ANTLR3_FPRINTF(stderr, ", at <EOF>");
- } else {
- token_text = token->getText(token);
- if (token_text != NULL) {
- *error_string += " near \"";
- *error_string += reinterpret_cast<const char*>(token_text->chars);
- *error_string += "\"";
- }
- }
- }
- break;
- }
- case ANTLR3_TYPE_LEXER: {
- *error_string += "lexer error.";
- break;
- }
- case ANTLR3_TYPE_TREE_PARSER: {
- // Tree parsers not supported. Exit.
- DLOG(FATAL) << "Technique error should never see a Tree Parser.";
- return;
- }
- default: {
- // Parser type was not recognised. Exit.
- DLOG(FATAL) << "Technique error called by an unknown Parser type.";
- return;
- }
- }
-
-#if 0
- // Although this function should generally be provided by the
- // implementation, this one should be as helpful as possible for grammar
- // developers and serve as an example of what you can do with each
- // exception type. In general, when you make up your 'real' handler, you
- // should debug the routine with all possible errors you expect which will
- // then let you be as specific as possible about all circumstances.
- //
- // Note that in the general case, errors thrown by tree parsers indicate a
- // problem with the output of the parser or with the tree grammar
- // itself. The job of the parser is to produce a perfect (in traversal
- // terms) syntactically correct tree, so errors at that stage should
- // really be semantic errors that your own code determines and handles in
- // whatever way is appropriate.
- switch (exception->type) {
- case ANTLR3_UNWANTED_TOKEN_EXCEPTION:
- // Indicates that the recognizer was fed a token which seesm to be
- // spurious input. We can detect this when the token that follows
- // this unwanted token would normally be part of the syntactically
- // correct stream. Then we can see that the token we are looking at
- // is just something that should not be there and throw this exception.
- if (tokenNames == NULL) {
- ANTLR3_FPRINTF(stderr, " : Extraneous input...");
- } else {
- if (exception->expecting == ANTLR3_TOKEN_EOF) {
- ANTLR3_FPRINTF(stderr, " : Extraneous input - expected <EOF>\n");
- } else {
- ANTLR3_FPRINTF(stderr,
- " : Extraneous input - expected %s ...\n",
- tokenNames[exception->expecting]);
- }
- }
- break;
- case ANTLR3_MISSING_TOKEN_EXCEPTION:
- // Indicates that the recognizer detected that the token we just
- // hit would be valid syntactically if preceeded by a particular
- // token. Perhaps a missing ';' at line end or a missing ',' in an
- // expression list, and such like.
- if (tokenNames == NULL) {
- ANTLR3_FPRINTF(stderr,
- " : Missing token (%d)...\n",
- exception->expecting);
- } else {
- if (exception->expecting == ANTLR3_TOKEN_EOF) {
- ANTLR3_FPRINTF(stderr, " : Missing <EOF>\n");
- } else {
- ANTLR3_FPRINTF(stderr,
- " : Missing %s \n",
- tokenNames[exception->expecting]);
- }
- }
- break;
- case ANTLR3_RECOGNITION_EXCEPTION:
- // Indicates that the recognizer received a token
- // in the input that was not predicted. This is the basic exception type
- // from which all others are derived. So we assume it was a syntax error.
- // You may get this if there are not more tokens and more are needed
- // to complete a parse for instance.
- ANTLR3_FPRINTF(stderr, " : syntax error...\n");
- break;
- case ANTLR3_MISMATCHED_TOKEN_EXCEPTION:
- // We were expecting to see one thing and got another. This is the
- // most common error if we coudl not detect a missing or unwanted token.
- // Here you can spend your efforts to
- // derive more useful error messages based on the expected
- // token set and the last token and so on. The error following
- // bitmaps do a good job of reducing the set that we were looking
- // for down to something small. Knowing what you are parsing may be
- // able to allow you to be even more specific about an error.
- if (tokenNames == NULL) {
- ANTLR3_FPRINTF(stderr, " : syntax error...\n");
- } else {
- if (exception->expecting == ANTLR3_TOKEN_EOF) {
- ANTLR3_FPRINTF(stderr, " : expected <EOF>\n");
- } else {
- ANTLR3_FPRINTF(stderr,
- " : expected %s ...\n",
- tokenNames[exception->expecting]);
- }
- }
- break;
- case ANTLR3_NO_VIABLE_ALT_EXCEPTION:
- // We could not pick any alt decision from the input given
- // so god knows what happened - however when you examine your grammar,
- // you should. It means that at the point where the current token occurred
- // that the DFA indicates nowhere to go from here.
- ANTLR3_FPRINTF(stderr, " : cannot match to any predicted input...\n");
- break;
- case ANTLR3_MISMATCHED_SET_EXCEPTION: {
- ANTLR3_UINT32 count;
- ANTLR3_UINT32 bit;
- ANTLR3_UINT32 size;
- ANTLR3_UINT32 numbits;
- pANTLR3_BITSET errBits;
-
- // This means we were able to deal with one of a set of
- // possible tokens at this point, but we did not see any
- // member of that set.
- ANTLR3_FPRINTF(stderr, " : unexpected input...\n expected one of : ");
-
- // What tokens could we have accepted at this point in the
- // parse?
- count = 0;
- errBits = antlr3BitsetLoad(exception->expectingSet);
- numbits = errBits->numBits(errBits);
- size = errBits->size(errBits);
-
- if (size > 0) {
- // However many tokens we could have dealt with here, it is usually
- // not useful to print ALL of the set here. I arbitrarily chose 8
- // here, but you should do whatever makes sense for you of course.
- // No token number 0, so look for bit 1 and on.
- for (bit = 1; bit < numbits && count < 8 && count < size; bit++) {
- // TODO: This doesn't look right - should be asking if the bit is set!
- if (tokenNames[bit]) {
- ANTLR3_FPRINTF(stderr,
- "%%s", count > 0 ? ", " : "",
- tokenNames[bit]);
- count++;
- }
- }
- ANTLR3_FPRINTF(stderr, "\n");
- } else {
- ANTLR3_FPRINTF(stderr,
- "Could not work out which set element was missing.\n");
- }
- break;
- }
- case ANTLR3_EARLY_EXIT_EXCEPTION:
- // We entered a loop requiring a number of token sequences
- // but found a token that ended that sequence earlier than
- // we should have done.
- ANTLR3_FPRINTF(stderr, " : missing elements...\n");
- break;
- default:
- // We don't handle any other exceptions here, but you can
- // if you wish. If we get an exception that hits this point
- // then we are just going to report what we know about the
- // token.
- ANTLR3_FPRINTF(stderr, " : syntax not recognized...\n");
- break;
- }
-#endif // end #if 0
-
- *error_string += "\n";
-
- DLOG(INFO) << "parse error: " << error_string->c_str();
-}
-} // namespace o3d
diff --git a/o3d/compiler/technique/technique_error.h b/o3d/compiler/technique/technique_error.h
deleted file mode 100644
index 260856c..0000000
--- a/o3d/compiler/technique/technique_error.h
+++ /dev/null
@@ -1,60 +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.
- */
-
-//
-// Custom error reporting functions for the Technique parser.
-//
-// NOTE: These error functions assume they are interacting with with
-// 8-bit token streams.
-
-#ifndef O3D_COMPILER_TECHNIQUE_TECHNIQUE_ERROR_H_
-#define O3D_COMPILER_TECHNIQUE_TECHNIQUE_ERROR_H_
-
-#include <build/build_config.h>
-#ifdef OS_WIN
-// NOTE: disable compiler warning about C function returning a
-// struct. This is caused by the Antlr generated functions being declared
-// extern "C" but being compiled and used as C++.
-#pragma warning(disable: 4190)
-#endif
-
-#include <vector>
-#include "TechniqueLexer.h"
-#include "TechniqueParser.h"
-
-namespace o3d {
-
-void TechniqueError(pANTLR3_BASE_RECOGNIZER recognizer,
- pANTLR3_UINT8 * tokenNames);
-
-} // namespace o3d
-
-#endif // O3D_COMPILER_TECHNIQUE_TECHNIQUE_ERROR_H_
diff --git a/o3d/compiler/technique/technique_parser.cc b/o3d/compiler/technique/technique_parser.cc
deleted file mode 100644
index 01a29de..0000000
--- a/o3d/compiler/technique/technique_parser.cc
+++ /dev/null
@@ -1,228 +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.
- */
-
-//
-// Driver function that sets up the Parser and Lexer for the "Technique"
-// grammar and executes the parsing process, returning the results as a
-// string and a Technique structure.
-//
-// Note that the "TechniqueParser.[c|h]" and "TechniqueLexer.[c|h]" files
-// are generated in standard C and compiled under C++, but the code
-// generator declares all functions as having "extern C" linkage. This may
-// lead to compiler warnings about returning "struct" type values from a
-// function - valid in C++, invalid under C.
-
-#include "base/logging.h"
-#include "compiler/technique/technique_parser.h"
-
-namespace o3d {
-
-// functions -------------------------------------------------------------------
-
-// Use the Technique grammar to parse a UTF8 text file from the filesystem.
-bool ParseFxFile(
- const String& filename,
- String *shader_string,
- SamplerStateList *sampler_list,
- TechniqueDeclarationList *technique_list,
- String *error_string) {
- // Create the input stream object from a file of UTF8 held in the filesystem.
- // The antlr3 library requires a non-const pointer to the filename.
- char* temp = const_cast<char*>(filename.c_str());
- pANTLR3_INPUT_STREAM input_stream = antlr3AsciiFileStreamNew(
- reinterpret_cast<pANTLR3_UINT8>(temp));
- if (input_stream == NULL) {
- DLOG(ERROR) << "Technique: Unable to open file" << filename
- << "due to memory allocation failure.";
- return false;
- } else {
- DLOG(INFO) << "Technique: Opened file \"" << filename << "\"";
- }
-
- // Create the language-specific Lexer.
- pTechniqueLexer lexer = TechniqueLexerNew(input_stream);
- if (lexer == NULL) {
- DLOG(ERROR) << "Technique: Unable to create the lexer";
- input_stream->close(input_stream);
- return false;
- } else {
- DLOG(INFO) << "Technique: Created lexer.";
- }
-
- // Create token stream from the Lexer.
- pANTLR3_COMMON_TOKEN_STREAM token_stream =
- antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lexer));
- if (token_stream == NULL) {
- DLOG(ERROR) << "Technique: failed to allocate token stream.";
- lexer->free(lexer);
- input_stream->close(input_stream);
- return false;
- } else {
- DLOG(INFO) << "Technique: Created token stream.";
- }
-
- // Force the token stream to turn off token filtering and pass all
- // whitespace and comments through to the parser.
- token_stream->discardOffChannel = ANTLR3_FALSE;
-
- // Create the language Parser.
- pTechniqueParser parser = TechniqueParserNew(token_stream);
- if (parser == NULL) {
- DLOG(ERROR) << "Technique: Out of memory trying to allocate parser";
- token_stream->free(token_stream);
- lexer->free(lexer);
- input_stream->close(input_stream);
- return false;
- } else {
- DLOG(INFO) << "Technique: Created parser.";
- }
-
- // call the root parsing rule to parse the input stream.
- DLOG(INFO) << "Technique: Parsing...";
- shader_string->clear();
- technique_list->clear();
- sampler_list->clear();
- bool return_value = parser->translation_unit(parser,
- technique_list,
- sampler_list,
- shader_string,
- error_string);
- DLOG(INFO) << "Technique: Finished parsing.";
-
- DLOG(INFO) << "Technique: Shader string = ";
- DLOG(INFO) << *shader_string;
-
- // Free created objects.
- parser->free(parser);
- token_stream->free(token_stream);
- lexer->free(lexer);
- input_stream->close(input_stream);
-
- // Finished
- return return_value;
-}
-
-
-// Use the Technique grammar to parse an FX file from an in-memory,
-// zero-terminted UTF8 string buffer.
-bool ParseFxString(
- const String& fx_string,
- String *shader_string,
- SamplerStateList *sampler_list,
- TechniqueDeclarationList *technique_list,
- String* error_string) {
- // Create a token stream from a zero-terminated memory buffer of uint8.
- ANTLR3_UINT32 fx_string_length =
- static_cast<ANTLR3_UINT32>(fx_string.length());
- if (fx_string_length == 0) {
- DLOG(INFO) << "Technique: fx string has zero length. Skipping.";
- return true;
- }
-
- // Create the input stream from the memory buffer.
- // The antlr3 stream library requires a non-const pointer to the fx_string.
- char* temp_fx_string = const_cast<char*>(fx_string.c_str());
- pANTLR3_INPUT_STREAM input_stream =
- antlr3NewAsciiStringInPlaceStream(
- reinterpret_cast<pANTLR3_UINT8>(temp_fx_string),
- fx_string_length,
- NULL);
- if (input_stream == NULL) {
- DLOG(ERROR) << "Technique: Unable to create input stream from string.";
- return false;
- } else {
- DLOG(INFO) << "Technique: Created input stream from string.";
- }
-
- // Create the language-specific Lexer.
- pTechniqueLexer lexer = TechniqueLexerNew(input_stream);
- if (lexer == NULL) {
- DLOG(ERROR) << "Technique: Unable to create the lexer";
- input_stream->close(input_stream);
- return false;
- } else {
- DLOG(INFO) << "Technique: Created lexer.";
- }
-
- // Create token stream from the Lexer.
- pANTLR3_COMMON_TOKEN_STREAM token_stream =
- antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lexer));
- if (token_stream == NULL) {
- DLOG(ERROR) << "Technique: failed to allocate token stream.";
- lexer->free(lexer);
- input_stream->close(input_stream);
- return false;
- } else {
- DLOG(INFO) << "Technique: Created token stream.";
- }
-
- // Force the token stream to turn off token filtering and pass all
- // whitespace and comments through to the parser.
- token_stream->discardOffChannel = ANTLR3_FALSE;
-
- // Create the language Parser.
- pTechniqueParser parser = TechniqueParserNew(token_stream);
- if (parser == NULL) {
- DLOG(ERROR) << "Technique: Out of memory trying to allocate parser";
- token_stream->free(token_stream);
- lexer->free(lexer);
- input_stream->close(input_stream);
- return false;
- } else {
- DLOG(INFO) << "Technique: Created parser.";
- }
-
- // call the root parsing rule to parse the input stream.
- DLOG(INFO) << "Technique: Parsing...";
- shader_string->clear();
- technique_list->clear();
- sampler_list->clear();
- bool return_value = parser->translation_unit(parser,
- technique_list,
- sampler_list,
- shader_string,
- error_string);
- DLOG(INFO) << "Technique: Finished parsing.";
-
- DLOG(INFO) << "Technique: Shader string = ";
- DLOG(INFO) << *shader_string;
-
- // Free created objects.
- parser->free(parser);
- token_stream->free(token_stream);
- lexer->free(lexer);
- input_stream->close(input_stream);
-
- // Completed
- return return_value;
-}
-
-} // namespace o3d
diff --git a/o3d/compiler/technique/technique_parser.h b/o3d/compiler/technique/technique_parser.h
deleted file mode 100644
index ef6e96e..0000000
--- a/o3d/compiler/technique/technique_parser.h
+++ /dev/null
@@ -1,130 +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.
- */
-
-//
-// Parse an HLSL or Cg ".fx" file and break it into:
-// a) source code for the shader
-// b) structured information from a "technique{}" block, if one exists.
-//
-// Entry functions initialize the Parser and Lexer for the "Technique"
-// grammar and execute the parsing process, returning the results as a
-// string and a Technique object.
-//
-// Note that the two headers "TechniqueLexer.h" and "TechniqueParser.h" are
-// automatically generated using the Antlr compiler-generator from the
-// grammar file "Technique.g3pl"
-//
-// TODO: Note that this is a specialized grammar designed for this
-// purpose alone, and it does no sanity checking on the HLSL source
-// structure or identifiers itself. A more complete HLSL grammar and
-// analyser for this task can be found in the directory
-// "o3d/compiler/hlsl".
-
-#ifndef O3D_COMPILER_TECHNIQUE_TECHNIQUE_PARSER_H_
-#define O3D_COMPILER_TECHNIQUE_TECHNIQUE_PARSER_H_
-
-#include <build/build_config.h>
-#include <vector>
-#include "core/cross/types.h"
-#include "compiler/technique/technique_structures.h"
-#include "compiler/technique/technique_error.h"
-
-#ifdef OS_WIN
-// NOTE: disable compiler warning about C function returning a
-// struct caused by the Antlr generated functions being declared extern"C"
-// but being compiled and used as C++.
-#pragma warning(disable: 4190)
-#endif
-
-// As these headers are automatically generated, their full path has to be
-// passed via the build script as each build target will generate the
-// headers in a different location.
-#include "TechniqueLexer.h"
-#include "TechniqueParser.h"
-
-namespace o3d {
-
-// typedefs --------------------------------------------------------------------
-
-typedef std::vector<TechniqueDeclaration> TechniqueDeclarationList;
-
-
-// functions -------------------------------------------------------------------
-
-
-// Use the Technique grammar to parse a UTF8 text file from the filing system.
-// Inputs:
-// filename - a UTF8 filename to send to the filesystem.
-// shader_string - pointer to a String object that will be cleared.
-// sampler_list - pointer to a vector of SamplerState objects.
-// technique_list - pointer to a vector of TechniqueDeclaration objects.
-// error_string - pointer to a String object that will be cleared.
-// Returns:
-// shader_string - pointer to a String object containing the shader source.
-// sampler_list - pointer to a vector of SamplerState objects, each filled
-// in with fields parsed from the FX file.
-// technique_list - pointer to a vector of TechniqueDeclaration objects, each
-// filled with fields parsed from the FX file.
-// error_string - pointer to a String object containing parse errors,
-// if any.
-bool ParseFxFile(
- const String &filename,
- String *shader_string,
- SamplerStateList *sampler_list,
- TechniqueDeclarationList *technique_list,
- String *error_string);
-
-
-// Use the Technique grammar to parse an in-memory string buffer.
-// Inputs:
-// fx_string - a zero-terminated UTF8 string of the .fx file source.
-// shader_string - pointer to a String object that will be cleared.
-// sampler_list - pointer to a vector of SamplerState objects.
-// technique_list - pointer to a vector of TechniqueDeclaration objects.
-// error_string - pointer to a String object that will be cleared.
-// Returns:
-// shader_string - pointer to a String object containing the shader source.
-// sampler_list - pointer to a vector of SamplerState objects, each filled
-// in with fields parsed from the FX file.
-// technique_list - pointer to a vector of TechniqueDeclaration objects, each
-// filled with fields parsed from the FX file.
-// error_string - pointer to a String object containing parse errors,
-// if any.
-bool ParseFxString(
- const String &fx_string,
- String *shader_string,
- SamplerStateList *sampler_list,
- TechniqueDeclarationList *technique_list,
- String *error_string);
-
-} // namespace o3d
-
-#endif // O3D_COMPILER_TECHNIQUE_TECHNIQUE_PARSER_H_
diff --git a/o3d/compiler/technique/technique_parser_test.cc b/o3d/compiler/technique/technique_parser_test.cc
deleted file mode 100644
index ea2ca0a..0000000
--- a/o3d/compiler/technique/technique_parser_test.cc
+++ /dev/null
@@ -1,414 +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.
- */
-
-//
-// Test program to exercise the Technique Antlr grammar using both files and
-// in-memory string buffers.
-
-#include "tests/common/win/testing_common.h"
-#include "compiler/technique/technique_parser.h"
-
-namespace o3d {
-
-// classes ---------------------------------------------------------------------
-
-class TechniqueParserTest : public testing::Test {
- protected:
- virtual void SetUp();
- virtual void TearDown();
- private:
-};
-
-void TechniqueParserTest::SetUp() {
-}
-
-void TechniqueParserTest::TearDown() {
-}
-
-// globals ---------------------------------------------------------------------
-
-char simple_fx_source[] =
-"float4x4 worldViewProj : WORLDVIEWPROJECTION; \
-void vs(in float4 pos, out float4 opos) { \
- opos = mul(pos, worldViewProj); \
-} \
-float4 fs(): COLOR { \
- return float3(0.33f, 0.57f, 0.10f); \
-} \
-technique t1 { \
- pass p0 { \
- VertexShader = compile vs_2_0 vs(); \
- PixelShader = compile ps_2_0 fs(); \
- } \
-} \
-";
-
-char lambert_fx_source[] =
-"struct a2v { \
- float4 pos : POSITION; \
- float3 normal : NORMAL; \
-}; \
- \
-struct v2f { \
- float4 pos : POSITION; \
- float3 n : TEXCOORD0; \
- float3 l : TEXCOORD1; \
-}; \
- \
-float4x4 worldViewProj : WorldViewProjection; \
-float4x4 world : World; \
-float4x4 worldIT : WorldInverseTranspose; \
-float3 lightWorldPos; \
-float4 lightColor; \
- \
-v2f vsMain(a2v IN) { \
- v2f OUT; \
- OUT.pos = mul(IN.pos, worldViewProj); \
- OUT.n = mul(float4(IN.normal,0), worldIT).xyz; \
- OUT.l = lightWorldPos-mul(IN.pos, world).xyz; \
- return OUT; \
-} \
- \
-float4 fsMain(v2f IN): COLOR { \
- float3 l=normalize(IN.l); \
- float3 n=normalize(IN.n); \
- float4 litR=lit(dot(n,l),0,0); \
- return emissive+lightColor*(ambient+diffuse*litR.y); \
-} \
- \
-technique { \
- pass p0 { \
- VertexShader = compile vs_2_0 vsMain(); \
- PixelShader = compile ps_2_0 fsMain(); \
- } \
-} \
-";
-
-// -----------------------------------------------------------------------------
-
-TEST_F(TechniqueParserTest, ParseSimpleFXFromFile) {
- String shader_source, error_string;
- TechniqueDeclarationList technique_list;
- SamplerStateList sampler_list;
- String filepath = *g_program_path + "/unittest_data/simple.fx";
- EXPECT_TRUE(ParseFxFile(filepath,
- &shader_source,
- &sampler_list,
- &technique_list,
- &error_string));
- EXPECT_LT(0, static_cast<int>(technique_list.size()));
- ASSERT_EQ(1, technique_list.size());
- EXPECT_EQ("t1", technique_list[0].name);
- ASSERT_EQ(0, technique_list[0].annotation.size());
- ASSERT_EQ(1, technique_list[0].pass.size());
- EXPECT_EQ("p0", technique_list[0].pass[0].name);
- ASSERT_EQ(0, technique_list[0].pass[0].annotation.size());
- EXPECT_EQ("vs", technique_list[0].pass[0].vertex_shader_entry);
- EXPECT_EQ("vs_2_0", technique_list[0].pass[0].vertex_shader_profile);
- EXPECT_EQ("", technique_list[0].pass[0].vertex_shader_arguments);
- EXPECT_EQ("fs", technique_list[0].pass[0].fragment_shader_entry);
- EXPECT_EQ("ps_2_0", technique_list[0].pass[0].fragment_shader_profile);
- EXPECT_EQ("", technique_list[0].pass[0].fragment_shader_arguments);
- ASSERT_EQ(0, technique_list[0].pass[0].state_assignment.size());
- EXPECT_EQ(0, sampler_list.size());
-}
-
-TEST_F(TechniqueParserTest, ParseSimpleFXFromString) {
- String shader_source, error_string;
- TechniqueDeclarationList technique_list;
- SamplerStateList sampler_list;
- EXPECT_TRUE(ParseFxString(simple_fx_source,
- &shader_source,
- &sampler_list,
- &technique_list,
- &error_string));
- EXPECT_LT(0, static_cast<int>(technique_list.size()));
- ASSERT_EQ(1, technique_list.size());
- EXPECT_EQ("t1", technique_list[0].name);
- ASSERT_EQ(0, technique_list[0].annotation.size());
- ASSERT_EQ(1, technique_list[0].pass.size());
- EXPECT_EQ("p0", technique_list[0].pass[0].name);
- ASSERT_EQ(0, technique_list[0].pass[0].annotation.size());
- EXPECT_EQ("vs", technique_list[0].pass[0].vertex_shader_entry);
- EXPECT_EQ("vs_2_0", technique_list[0].pass[0].vertex_shader_profile);
- EXPECT_EQ("", technique_list[0].pass[0].vertex_shader_arguments);
- EXPECT_EQ("fs", technique_list[0].pass[0].fragment_shader_entry);
- EXPECT_EQ("ps_2_0", technique_list[0].pass[0].fragment_shader_profile);
- EXPECT_EQ("", technique_list[0].pass[0].fragment_shader_arguments);
- ASSERT_EQ(0, technique_list[0].pass[0].state_assignment.size());
- EXPECT_EQ(0, sampler_list.size());
-}
-
-TEST_F(TechniqueParserTest, ParseLambertFXFromFile) {
- String shader_source, error_string;
- TechniqueDeclarationList technique_list;
- SamplerStateList sampler_list;
- String filepath = *g_program_path + "/unittest_data/lambert.fx";
- EXPECT_TRUE(ParseFxFile(filepath.c_str(),
- &shader_source,
- &sampler_list,
- &technique_list,
- &error_string));
- EXPECT_LT(0, static_cast<int>(technique_list.size()));
- ASSERT_EQ(1, technique_list.size());
- EXPECT_EQ("", technique_list[0].name);
- ASSERT_EQ(0, technique_list[0].annotation.size());
- ASSERT_EQ(1, technique_list[0].pass.size());
- EXPECT_EQ("p0", technique_list[0].pass[0].name);
- ASSERT_EQ(0, technique_list[0].pass[0].annotation.size());
- EXPECT_EQ("vsMain", technique_list[0].pass[0].vertex_shader_entry);
- EXPECT_EQ("vs_2_0", technique_list[0].pass[0].vertex_shader_profile);
- EXPECT_EQ("", technique_list[0].pass[0].vertex_shader_arguments);
- EXPECT_EQ("fsMain", technique_list[0].pass[0].fragment_shader_entry);
- EXPECT_EQ("ps_2_0", technique_list[0].pass[0].fragment_shader_profile);
- EXPECT_EQ("", technique_list[0].pass[0].fragment_shader_arguments);
- ASSERT_EQ(0, technique_list[0].pass[0].state_assignment.size());
- EXPECT_EQ(0, sampler_list.size());
-}
-
-TEST_F(TechniqueParserTest, ParseLambertFXFromString) {
- String shader_source, error_string;
- TechniqueDeclarationList technique_list;
- SamplerStateList sampler_list;
- EXPECT_TRUE(ParseFxString(lambert_fx_source,
- &shader_source,
- &sampler_list,
- &technique_list,
- &error_string));
- EXPECT_LT(0, static_cast<int>(technique_list.size()));
- ASSERT_EQ(1, technique_list.size());
- EXPECT_EQ("", technique_list[0].name);
- ASSERT_EQ(0, technique_list[0].annotation.size());
- ASSERT_EQ(1, technique_list[0].pass.size());
- EXPECT_EQ("p0", technique_list[0].pass[0].name);
- ASSERT_EQ(0, technique_list[0].pass[0].annotation.size());
- EXPECT_EQ("vsMain", technique_list[0].pass[0].vertex_shader_entry);
- EXPECT_EQ("vs_2_0", technique_list[0].pass[0].vertex_shader_profile);
- EXPECT_EQ("", technique_list[0].pass[0].vertex_shader_arguments);
- EXPECT_EQ("fsMain", technique_list[0].pass[0].fragment_shader_entry);
- EXPECT_EQ("ps_2_0", technique_list[0].pass[0].fragment_shader_profile);
- EXPECT_EQ("", technique_list[0].pass[0].fragment_shader_arguments);
- ASSERT_EQ(0, technique_list[0].pass[0].state_assignment.size());
- ASSERT_EQ(0, sampler_list.size());
-}
-
-
-
-// Test the longer shaders from files ------------------------------------------
-
-TEST_F(TechniqueParserTest, ParseNoShaderFXFromFile) {
- String shader_source, error_string;
- TechniqueDeclarationList technique_list;
- SamplerStateList sampler_list;
- String filepath = *g_program_path + "/unittest_data/noshader.fx";
- EXPECT_TRUE(ParseFxFile(filepath,
- &shader_source,
- &sampler_list,
- &technique_list,
- &error_string));
- EXPECT_LT(0, static_cast<int>(technique_list.size()));
- ASSERT_EQ(1, technique_list.size());
- EXPECT_EQ("t1", technique_list[0].name);
- ASSERT_EQ(0, technique_list[0].annotation.size());
- ASSERT_EQ(1, technique_list[0].pass.size());
- EXPECT_EQ("p0", technique_list[0].pass[0].name);
- ASSERT_EQ(0, technique_list[0].pass[0].annotation.size());
- EXPECT_EQ("", technique_list[0].pass[0].vertex_shader_entry);
- EXPECT_EQ("", technique_list[0].pass[0].vertex_shader_profile);
- EXPECT_EQ("", technique_list[0].pass[0].vertex_shader_arguments);
- EXPECT_EQ("", technique_list[0].pass[0].fragment_shader_entry);
- EXPECT_EQ("", technique_list[0].pass[0].fragment_shader_profile);
- EXPECT_EQ("", technique_list[0].pass[0].fragment_shader_arguments);
- ASSERT_EQ(4, technique_list[0].pass[0].state_assignment.size());
- EXPECT_EQ("ZEnable", technique_list[0].pass[0].state_assignment[0].name);
- EXPECT_EQ("true", technique_list[0].pass[0].state_assignment[0].value);
- EXPECT_EQ("ZWriteEnable", technique_list[0].pass[0].state_assignment[1].name);
- EXPECT_EQ("true", technique_list[0].pass[0].state_assignment[1].value);
- EXPECT_EQ("ZFunc", technique_list[0].pass[0].state_assignment[2].name);
- EXPECT_EQ("LessEqual", technique_list[0].pass[0].state_assignment[2].value);
- EXPECT_EQ("CullMode", technique_list[0].pass[0].state_assignment[3].name);
- EXPECT_EQ("None", technique_list[0].pass[0].state_assignment[3].value);
- EXPECT_EQ(0, sampler_list.size());
-}
-
-TEST_F(TechniqueParserTest, ParseNoTechniqueFXFromFile) {
- String shader_source, error_string;
- TechniqueDeclarationList technique_list;
- SamplerStateList sampler_list;
- String filepath = *g_program_path + "/unittest_data/notechnique.fx";
- EXPECT_TRUE(ParseFxFile(filepath,
- &shader_source,
- &sampler_list,
- &technique_list,
- &error_string));
- EXPECT_EQ(0, technique_list.size());
- EXPECT_EQ(0, sampler_list.size());
-}
-
-TEST_F(TechniqueParserTest, ParseFurFXFromFile) {
- String shader_source, error_string;
- TechniqueDeclarationList technique_list;
- SamplerStateList sampler_list;
- String filepath = *g_program_path + "/unittest_data/fur.fx";
- EXPECT_TRUE(ParseFxFile(filepath,
- &shader_source,
- &sampler_list,
- &technique_list,
- &error_string));
- ASSERT_EQ(1, technique_list.size());
- EXPECT_EQ(1, sampler_list.size());
-}
-
-TEST_F(TechniqueParserTest, ParseShadowMapFXFromFile) {
- String shader_source, error_string;
- TechniqueDeclarationList technique_list;
- SamplerStateList sampler_list;
- String filepath = *g_program_path + "/unittest_data/shadow_map.fx";
- EXPECT_TRUE(ParseFxFile(filepath,
- &shader_source,
- &sampler_list,
- &technique_list,
- &error_string));
- ASSERT_EQ(2, technique_list.size());
- EXPECT_EQ(2, sampler_list.size());
-}
-
-
-
-// Tests of error cases --------------------------------------------------------
-
-TEST_F(TechniqueParserTest, ParseEmptyString) {
- String shader_source, error_string;
- TechniqueDeclarationList technique_list;
- SamplerStateList sampler_list;
- String empty_fx_source = "";
- EXPECT_TRUE(ParseFxString(empty_fx_source,
- &shader_source,
- &sampler_list,
- &technique_list,
- &error_string));
- EXPECT_EQ(0, technique_list.size());
- EXPECT_EQ(String(""), shader_source);
- EXPECT_EQ(0, sampler_list.size());
-}
-
-TEST_F(TechniqueParserTest, ParseInvalidString) {
- String shader_source, error_string;
- TechniqueDeclarationList technique_list;
- SamplerStateList sampler_list;
- String invalid_fx_source = "$%^~ This is an invalid shader.";
- EXPECT_FALSE(ParseFxString(invalid_fx_source,
- &shader_source,
- &sampler_list,
- &technique_list,
- &error_string));
- EXPECT_EQ(0, technique_list.size());
- EXPECT_EQ(0, sampler_list.size());
- // TODO: make sure the string was rejected as an invalid HLSL
- // program and test the parser errors.
-}
-
-TEST_F(TechniqueParserTest, ParseInvalidFilename) {
- String shader_source, error_string;
- TechniqueDeclarationList technique_list;
- SamplerStateList sampler_list;
- String filepath = *g_program_path + "/unittest_data/invalid_filename.fx";
- EXPECT_FALSE(ParseFxFile(filepath,
- &shader_source,
- &sampler_list,
- &technique_list,
- &error_string));
- EXPECT_EQ(technique_list.size(), 0);
- EXPECT_EQ(shader_source, String(""));
- EXPECT_EQ(0, sampler_list.size());
-}
-
-TEST_F(TechniqueParserTest, ParseInvalidPassIdentifier) {
- String shader_source, error_string;
- TechniqueDeclarationList technique_list;
- SamplerStateList sampler_list;
- String invalid_pass_identifier_source = "technique { pass pass { } };";
- EXPECT_FALSE(ParseFxString(invalid_pass_identifier_source,
- &shader_source,
- &sampler_list,
- &technique_list,
- &error_string));
- EXPECT_EQ(1, technique_list.size());
- ASSERT_EQ(1, technique_list[0].pass.size());
- EXPECT_EQ("", technique_list[0].pass[0].name);
- EXPECT_EQ(shader_source, String(""));
- EXPECT_EQ(0, sampler_list.size());
-}
-
-TEST_F(TechniqueParserTest, ParseInvalidStateName) {
- String shader_source, error_string;
- TechniqueDeclarationList technique_list;
- SamplerStateList sampler_list;
- // NOTE: "FragmentShader" should read "FragmentProgram" or "PixelShader".
- String invalid_pass_identifier_source =
- "technique { pass { FragmentShader = compile ps_2_0 nothing(); } };";
- EXPECT_FALSE(ParseFxString(invalid_pass_identifier_source,
- &shader_source,
- &sampler_list,
- &technique_list,
- &error_string));
- EXPECT_EQ(1, technique_list.size());
- ASSERT_EQ(1, technique_list[0].pass.size());
- EXPECT_EQ("", technique_list[0].pass[0].name);
- EXPECT_EQ(shader_source, String(""));
- EXPECT_EQ(0, sampler_list.size());
-}
-
-TEST_F(TechniqueParserTest, ParseSampler) {
- String shader_source, error_string;
- TechniqueDeclarationList technique_list;
- SamplerStateList sampler_list;
- String filepath = *g_program_path + "/unittest_data/sampler_test.fx";
- EXPECT_TRUE(ParseFxFile(filepath,
- &shader_source,
- &sampler_list,
- &technique_list,
- &error_string));
- EXPECT_EQ(1, technique_list.size());
- ASSERT_EQ(1, technique_list[0].pass.size());
- ASSERT_EQ(1, sampler_list.size());
- EXPECT_EQ("Tex0", sampler_list[0].texture);
- EXPECT_EQ("Linear", sampler_list[0].min_filter);
- EXPECT_EQ("Point", sampler_list[0].mag_filter);
- EXPECT_EQ("None", sampler_list[0].mip_filter);
- EXPECT_EQ("Mirror", sampler_list[0].address_u);
- EXPECT_EQ("Wrap", sampler_list[0].address_v);
- EXPECT_EQ("Clamp", sampler_list[0].address_w);
- EXPECT_EQ("16", sampler_list[0].max_anisotropy);
- EXPECT_EQ("float4(1.0, 0.0, 0.0, 1.0)", sampler_list[0].border_color);
-}
-
-} // namespace o3d
diff --git a/o3d/compiler/technique/technique_structures.cc b/o3d/compiler/technique/technique_structures.cc
deleted file mode 100644
index f32253d..0000000
--- a/o3d/compiler/technique/technique_structures.cc
+++ /dev/null
@@ -1,87 +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 "base/logging.h"
-#include "base/cross/std_functional.h"
-#include "compiler/technique/technique_structures.h"
-
-namespace o3d {
-
-void TechniqueDeclaration::clear() {
- name.clear();
- annotation.clear();
- pass.clear();
-}
-
-void TechniqueDeclaration::dump() {
- DLOG(INFO) << "Dump of Technique \"" << name << "\"";
- DLOG(INFO) << "Technique Annotation count = " << annotation.size();
- std::for_each(annotation.begin(),
- annotation.end(),
- std::mem_fun_ref(&Annotation::dump));
- DLOG(INFO) << "Pass count = " << pass.size();
- std::for_each(pass.begin(),
- pass.end(),
- std::mem_fun_ref(&PassDeclaration::dump));
-}
-
-void PassDeclaration::dump() {
- DLOG(INFO) << "Pass \"" << name << "\"";
- DLOG(INFO) << "Pass Annotation count = " << annotation.size();
- std::for_each(annotation.begin(),
- annotation.end(),
- std::mem_fun_ref(&Annotation::dump));
- DLOG(INFO) << "Vertex shader \"" << vertex_shader_entry << "\"";
- DLOG(INFO) << "Vertex profile \"" << vertex_shader_profile << "\"";
- DLOG(INFO) << "Vertex args \"" << vertex_shader_arguments << "\"";
- DLOG(INFO) << "Fragment shader \"" << fragment_shader_entry << "\"";
- DLOG(INFO) << "Fragment profile \"" << fragment_shader_profile << "\"";
- DLOG(INFO) << "Fragment args \"" << fragment_shader_arguments << "\"";
- DLOG(INFO) << "State Assignment count = " << state_assignment.size();
- std::for_each(state_assignment.begin(),
- state_assignment.end(),
- std::mem_fun_ref(&StateAssignment::dump));
-}
-
-void StateAssignment::dump() {
- DLOG(INFO) << "State assignment name \"" << name << "\"";
- DLOG(INFO) << "State assignment value \"" << value << "\"";
-}
-
-void Annotation::dump() {
- DLOG(INFO) << "Annotation name \"" << name << "\"";
- DLOG(INFO) << "Annotation type \"" << type << "\"";
- DLOG(INFO) << "Annotation value \"" << value << "\"";
-}
-
-} // namespace o3d
diff --git a/o3d/compiler/technique/technique_structures.h b/o3d/compiler/technique/technique_structures.h
deleted file mode 100644
index ec7607a..0000000
--- a/o3d/compiler/technique/technique_structures.h
+++ /dev/null
@@ -1,132 +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_COMPILER_TECHNIQUE_TECHNIQUE_STRUCTURES_H_
-#define O3D_COMPILER_TECHNIQUE_TECHNIQUE_STRUCTURES_H_
-
-#include <vector>
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// typedefs --------------------------------------------------------------------
-
-class TechniqueDeclaration;
-class SamplerState;
-
-typedef std::vector<TechniqueDeclaration> TechniqueDeclarationList;
-typedef std::vector<SamplerState> SamplerStateList;
-
-// classes ---------------------------------------------------------------------
-
-// A set of simple data classes that hold the structured information
-// uncovered by the Technique parser. All values are public as providing
-// accessors for each member would be pretty pointless. If a field is
-// missing in the parsed FX file the matching field will either hold an
-// empty string or have zero entries in the container.
-//
-// TODO: if it proves necessary, interpret the "value" fields into
-// binary form as opposed to the current model of leaving them as strings.
-
-class Annotation {
- public:
- Annotation() {}
- Annotation(String t, String n, String v) : type(t), name(n), value(v) {}
- ~Annotation() {}
- void dump();
-
- String type;
- String name;
- String value;
-};
-
-class StateAssignment {
- public:
- StateAssignment() {}
- StateAssignment(String n, String v) : name(n), value(v) {}
- ~StateAssignment() {}
- void dump();
-
- String name;
- String value;
-};
-
-class PassDeclaration {
- public:
- PassDeclaration() {}
- explicit PassDeclaration(String n) : name(n) {}
- ~PassDeclaration() {}
- void dump();
-
- String name;
- std::vector<Annotation> annotation;
- String vertex_shader_entry;
- String vertex_shader_profile;
- String vertex_shader_arguments;
- String fragment_shader_entry;
- String fragment_shader_profile;
- String fragment_shader_arguments;
- std::vector<StateAssignment> state_assignment;
-};
-
-class TechniqueDeclaration {
- public:
- TechniqueDeclaration() {}
- ~TechniqueDeclaration() {}
- void clear();
- void dump();
-
- String name;
- std::vector<Annotation> annotation;
- std::vector<PassDeclaration> pass;
-};
-
-class SamplerState {
- public:
- SamplerState() {}
- ~SamplerState() {}
-
- String name;
- String texture;
- String address_u;
- String address_v;
- String address_w;
- String min_filter;
- String mag_filter;
- String mip_filter;
- String border_color;
- String max_anisotropy;
-};
-
-} // namespeace o3d
-
-#endif // O3D_COMPILER_TECHNIQUE_TECHNIQUE_STRUCTURES_H_
diff --git a/o3d/compiler/technique/test_data/HLSL_declarations.fx b/o3d/compiler/technique/test_data/HLSL_declarations.fx
deleted file mode 100644
index 55c927a..0000000
--- a/o3d/compiler/technique/test_data/HLSL_declarations.fx
+++ /dev/null
@@ -1,30 +0,0 @@
-// Variable declarations ----------------------------
-
-extern aa;
-nointerpolation ab;
-shared ac;
-static ad;
-uniform ae;
-volatile af;
-
-static uniform nointerpolation ag;
-shared extern const column_major ah;
-
-extern const ai;
-shared const aj;
-static const ak;
-uniform const al;
-
-static row_major float2x2 am;
-uniform column_major float3x2 an;
-
-
-
-// Geometry Shader ----------------
-
-Buffer<float4> g_Buffer;
-
-float4 geom_fn() {
- float4 bufferdata = g_Buffer.Load(1);
- return bufferdata;
-}
diff --git a/o3d/compiler/technique/test_data/fur.fx b/o3d/compiler/technique/test_data/fur.fx
deleted file mode 100644
index 6c326a6..0000000
--- a/o3d/compiler/technique/test_data/fur.fx
+++ /dev/null
@@ -1,121 +0,0 @@
-/*****************************************************************************/
-/* */
-/* File: fur.fx */
-/* */
-/*****************************************************************************/
-
-// fur.fx
-
-//---------------------------------------------------------------------------//
-
-int shellcount = 20;
-int shellnumber = 0;
-
-float FurScale = 0;
-float FurLength = 0;
-float UVScale = 0;
-
-
-texture FurTexture
-<
- string TextureType = "2D";
->;
-
-
-// transformations
-float4x4 worldViewProj : WORLDVIEWPROJ;
-
-//------------------------------------
-struct vertexInput {
- float3 position : POSITION;
- float3 normal : NORMAL;
- //float4 color : COLOR0;
- float4 texCoordDiffuse : TEXCOORD0;
- float4 tex1 : TEXCOORD1;
-};
-
-struct vertexOutput {
- float4 HPOS : POSITION;
- //float4 color : COLOR;
- float4 T0 : TEXCOORD0;
- float3 normal : TEXCOORD1;
-
-};
-
-
-//------------------------------------
-vertexOutput VS_TransformAndTexture(vertexInput IN)
-{
- vertexOutput OUT;
-
- //float3 P = IN.position.xyz;
- //float3 P = IN.position.xyz + (IN.normal * (FurDistance * (float)shellnumber));
-
- //float3 P = IN.position.xyz + (IN.normal * FurScale * 10.0f) + (IN.normal*FurLength);
- //float3 P = IN.position.xyz + (IN.normal * FurScale * 10.0f) + (IN.normal*FurLength);
-
- float3 P = IN.position.xyz + (IN.normal * FurLength);
-
- //OUT.T0 = IN.texCoordDiffuse * 2.0f;
- //OUT.T0 = IN.tex1 * FurScale;
- OUT.T0 = IN.texCoordDiffuse * UVScale;
- //OUT.T0 = IN.tex1 / 3.0f;
- OUT.HPOS = mul(float4(P, 1.0f), worldViewProj);
- //OUT.color = IN.color;
- OUT.normal = IN.normal;
- return OUT;
-}
-
-
-//------------------------------------
-sampler TextureSampler = sampler_state
-{
- texture = <FurTexture>;
- AddressU = WRAP;
- AddressV = WRAP;
- AddressW = WRAP;
- MIPFILTER = LINEAR;
- MINFILTER = LINEAR;
- MAGFILTER = LINEAR;
-};
-
-
-//-----------------------------------
-float4 PS_Textured( vertexOutput IN): COLOR
-{
- float4 diffuseTexture = tex2D( TextureSampler, IN.T0 );
- //float4 diffuseTexture2 = tex2D( TextureSampler2, IN.T0 );
-
- //return (float4(furColor.xyz, FurStrength) * diffuseTexture);
- return diffuseTexture;
- //return float4(0.0f, 1.0f, 1.0f, 0.3f); //rrggbbaa
-}
-
-//-----------------------------------
-
-technique Fur
-{
- pass Shell
- <
- string script="Draw=Geometry;";
- >
- {
- VertexShader = compile vs_1_1 VS_TransformAndTexture();
- PixelShader = compile ps_1_3 PS_Textured();
- AlphaBlendEnable = true;
- SrcBlend = srcalpha;
- //DestBlend = one;
- DestBlend = invsrcalpha;
- //DestBlend = srccolor;
- //DestBlend = invsrccolor;
- //DestBlend = srcalpha;
- //DestBlend = destalpha;
- //DestBlend = invdestalpha;
- //DestBlend = destcolor;
- //DestBlend = invdestcolor;
-
- //CullMode = None;
- //CullMode = CCW;
- }
-}
-
diff --git a/o3d/compiler/technique/test_data/lambert.fx b/o3d/compiler/technique/test_data/lambert.fx
deleted file mode 100644
index b3f34b0..0000000
--- a/o3d/compiler/technique/test_data/lambert.fx
+++ /dev/null
@@ -1,38 +0,0 @@
-struct a2v {
- float4 pos : POSITION;
- float3 normal : NORMAL;
-};
-
-struct v2f {
- float4 pos : POSITION;
- float3 n : TEXCOORD0;
- float3 l : TEXCOORD1;
-};
-
-float4x4 worldViewProj : WorldViewProjection;
-float4x4 world : World;
-float4x4 worldIT : WorldInverseTranspose;
-float3 lightWorldPos;
-float4 lightColor;
-
-v2f vsMain(a2v IN) {
- v2f OUT;
- OUT.pos = mul(IN.pos, worldViewProj);
- OUT.n = mul(float4(IN.normal,0), worldIT).xyz;
- OUT.l = lightWorldPos-mul(IN.pos, world).xyz;
- return OUT;
-}
-
-float4 fsMain(v2f IN): COLOR {
- float3 l=normalize(IN.l);
- float3 n=normalize(IN.n);
- float4 litR=lit(dot(n,l),0,0);
- return emissive+lightColor*(ambient+diffuse*litR.y);
-}
-
-technique {
- pass p0 {
- VertexShader = compile vs_2_0 vsMain();
- PixelShader = compile ps_2_0 fsMain();
- }
-}
diff --git a/o3d/compiler/technique/test_data/noshader.fx b/o3d/compiler/technique/test_data/noshader.fx
deleted file mode 100644
index 13a4924..0000000
--- a/o3d/compiler/technique/test_data/noshader.fx
+++ /dev/null
@@ -1,8 +0,0 @@
-technique t1 {
- pass p0 {
- ZEnable = true;
- ZWriteEnable = true;
- ZFunc = LessEqual;
- CullMode = None;
- }
-}
diff --git a/o3d/compiler/technique/test_data/notechnique.fx b/o3d/compiler/technique/test_data/notechnique.fx
deleted file mode 100644
index 2201243..0000000
--- a/o3d/compiler/technique/test_data/notechnique.fx
+++ /dev/null
@@ -1,7 +0,0 @@
-float4x4 worldViewProj : WORLDVIEWPROJECTION;
-void vs(in float4 pos, out float4 opos) {
- opos = mul(pos, worldViewProj);
-}
-float4 fs(): COLOR {
- return float3(0.33f, 0.57f, 0.10f);
-}
diff --git a/o3d/compiler/technique/test_data/sampler_test.fx b/o3d/compiler/technique/test_data/sampler_test.fx
deleted file mode 100644
index 12bcc61..0000000
--- a/o3d/compiler/technique/test_data/sampler_test.fx
+++ /dev/null
@@ -1,54 +0,0 @@
-// texture
-texture Tex0 : DiffuseMap <
- string name = "tiger.bmp";
- string UIName = "Base Texture";
- >;
-
-// transformations
-float4x4 worldViewProj : WORLDVIEWPROJECTION;
-
-struct VS_OUTPUT
-{
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0;
-};
-
-VS_OUTPUT VS(VS_OUTPUT IN) {
- VS_OUTPUT Out = (VS_OUTPUT)0;
- Out.position = mul(IN.position, worldViewProj);
- Out.texcoord = IN.texcoord;
- return Out;
-}
-
-sampler Sampler = sampler_state
-{
- Texture = (Tex0);
- MinFilter = Linear;
- MagFilter = Point;
- MipFilter = None;
- AddressU = Mirror;
- AddressV = Wrap;
- AddressW = Clamp;
- MaxAnisotropy = 16;
- BorderColor = float4(1.0, 0.0, 0.0, 1.0);
-};
-
-
-float4 PS(VS_OUTPUT IN) : COLOR
-{
- float4 color = tex2D(Sampler, IN.texcoord);
- return color ;
-}
-
-
-technique DefaultTechnique
-{
- pass P0
- {
- // shaders
- CullMode = None;
- VertexShader = compile vs_2_0 VS();
- PixelShader = compile ps_2_0 PS();
- }
-}
-
diff --git a/o3d/compiler/technique/test_data/shadow_map.fx b/o3d/compiler/technique/test_data/shadow_map.fx
deleted file mode 100644
index b4f1c88..0000000
--- a/o3d/compiler/technique/test_data/shadow_map.fx
+++ /dev/null
@@ -1,170 +0,0 @@
-// Shader from NVidia example documentation:
-// ftp://download.nvidia.com/developer/SDK/Individual_Samples/
-// MEDIA/docPix/docs/FX_Shadowing.pdf
-
-texture CTex : RENDERCOLORTARGET <
- float2 Dimensions = {256,256};
- string Format = "x8b8g8r8" ;
- string UIWidget = "None";
->;
-
-sampler CSamp = sampler_state {
- texture = <CTex>;
- AddressU = CLAMP; AddressV = CLAMP;
- MipFilter = NONE;
- MinFilter = LINEAR;
- MagFilter = LINEAR;
-};
-
-texture DTex : RENDERDEPTHSTENCILTARGET <
- float2 Dimensions = {256,256};
- string format = "D24S8_SHADOWMAP";
- string UIWidget = "None";
->;
-
-sampler DSamp = sampler_state {
- texture = <DTex>;
- AddressU = CLAMP; AddressV = CLAMP;
- MipFilter = NONE;
- MinFilter = LINEAR;
- MagFilter = LINEAR;
-};
-
-float Script : STANDARDSGLOBAL <
- string UIWidget = "none";
- string ScriptClass = "sceneorobject";
- string ScriptOrder = "standard";
- string ScriptOutput = "color";
- string Script = "Tech=Technique?Shadowed:Unshadowed;";
-> = 0.8; // version #
-
-// The following global variables are values to be used
-// when clearing color and/or depth buffers
-float4 ClearColor <
- string UIWidget = "color";
- string UIName = "background";
-> = {0,0,0,0.0};
-
-float ClearDepth <
- string UIWidget = "none";
-> = 1.0;
-
-float4 ShadowClearColor <
- string UIWidget = "none";
-> = {1,1,1,0.0};
-
-void lightingCalc(ShadowingVertexOutput IN,
- out float3 litContrib,
- out float3 ambiContrib) {
- float3 Nn = normalize(IN.WNormal);
- float3 Vn = normalize(IN.WView);
- Nn = faceforward(Nn,-Vn,Nn);
- float falloff = 1.0 / dot(IN.LightVec,IN.LightVec);
- float3 Ln = normalize(IN.LightVec);
- float3 Hn = normalize(Vn + Ln);
- float hdn = dot(Hn,Nn);
- float ldn = dot(Ln,Nn);
- float4 litVec = lit(ldn,hdn,SpecExpon);
- ldn = litVec.y * SpotLightIntensity;
- ambiContrib = SurfColor * AmbiLightColor;
- float3 diffContrib = SurfColor*(Kd * ldn * SpotLightColor);
- float3 specContrib = ((ldn * litVec.z * Ks) * SpotLightColor);
- float3 result = diffContrib + specContrib;
- float cone = tex2Dproj(SpotSamp,IN.LProj);
- litContrib = ((cone*falloff) * result);
-}
-
-float4 useShadowPS(ShadowingVertexOutput IN) : COLOR {
- float3 litPart, ambiPart;
- lightingCalc(IN,litPart,ambiPart);
- float4 shadowed = tex2Dproj(ShadDepthSampler,IN.LProj);
- return float4((shadowed.x*litPart)+ambiPart,1);
-}
-
-float4 unshadowedPS(ShadowingVertexOutput IN) : COLOR {
- float3 litPart, ambiPart;
- lightingCalc(IN,litPart,ambiPart);
-}
-
-technique Unshadowed <
- string Script = "Pass=NoShadow;";
-> {
- pass NoShadow <
- string Script =
- "RenderColorTarget0=;"
- "RenderDepthStencilTarget=;"
- "RenderPort=;"
- "ClearSetColor=ClearColor;"
- "ClearSetDepth=ClearDepth;"
- "ClearDepth=Color;"
- "Clear=Depth;"
- "Draw=geometry;";
- > {
- VertexShader = compile vs_2_0
- shadowUseVS(WorldXf,
- WorldITXf,
- WorldViewProjXf,
- ShadowViewProjXf,
- ViewIXf,
- ShadBiasXf,
- SpotLightPos);
- ZEnable = true;
- ZWriteEnable = true;
- ZFunc = LessEqual;
- CullMode = None;
- PixelShader = compile ps_2_a unshadowedPS();
- }
-}
-
-technique Shadowed <
- string Script = "Pass=MakeShadow;"
- "Pass=UseShadow;";
-> {
- pass MakeShadow <
- string Script =
- "RenderColorTarget0=ColorShadMap;"
- "RenderDepthStencilTarget=ShadDepthTarget;"
- "RenderPort=light0;"
- "ClearSetColor=ShadowClearColor;"
- "ClearSetDepth=ClearDepth;"
- "Clear=Color;"
- "Clear=Depth;"
- "Draw=geometry;";
- > {
- VertexShader = compile vs_2_0
- shadowGenVS(WorldXf,
- WorldITXf,
- ShadowViewProjXf);
- ZEnable = true;
- ZWriteEnable = true;
- ZFunc = LessEqual;
- CullMode = None;
- // no pixel shader needed!
- }
-
- pass UseShadow <
- string Script =
- "RenderColorTarget0=;"
- "RenderDepthStencilTarget=;"
- " RenderPort=;"
- "ClearSetColor=ClearColor;"
- "ClearSetDepth=ClearDepth;"
- "Clear=Color;"
- "Clear=Depth;"
- "Draw=geometry;";
- > {
- VertexShader = compile vs_2_0
- shadowUseVS(WorldXf,
- WorldITXf,
- WorldViewProjXf,
- ShadowViewProjXf,
- ViewIXf,
- ShadBiasXf,
- SpotLightPos);
- ZEnable = true;
- ZWriteEnable = true;
- ZFunc = LessEqual;
- CullMode = None;
- PixelShader = compile ps_2_a useShadowPS();
- }
-}
diff --git a/o3d/compiler/technique/test_data/simple.fx b/o3d/compiler/technique/test_data/simple.fx
deleted file mode 100644
index 5c707429..0000000
--- a/o3d/compiler/technique/test_data/simple.fx
+++ /dev/null
@@ -1,13 +0,0 @@
-float4x4 worldViewProj : WORLDVIEWPROJECTION;
-void vs(in float4 pos, out float4 opos) {
- opos = mul(pos, worldViewProj);
-}
-float4 fs(): COLOR {
- return float3(0.33f, 0.57f, 0.10f);
-}
-technique t1 {
- pass p0 {
- VertexShader = compile vs_2_0 vs();
- PixelShader = compile ps_2_0 fs();
- }
-}
diff --git a/o3d/converter/README.converter b/o3d/converter/README.converter
deleted file mode 100644
index 71fd462..0000000
--- a/o3d/converter/README.converter
+++ /dev/null
@@ -1,76 +0,0 @@
-The converter is a command line utility that will convert from COLLADA
-to the form that the sample JavaScript scene loader (in
-samples/o3djs/serialization.js) can read.
-
-It is able to read COLLADA files as either DAE text files (and
-associated asset files in subdirectories), or as part of a ZIP archive
-(or KMZ file). By default it outputs a gzip-compressed tar archive
-(.tgz) which contains a JSON file and any associated assets (textures,
-shaders, etc.) from the source COLLADA model. By default we don't use
-the .tgz extension, as it can cause problems with some webservers; we
-put .o3dtgz on instead. The converter can optionally output a set of
-flat files into a directory, which is the layout compatible with the
-WebGL implementation of O3D.
-
-In order to run the converter on Windows, you need the DirectX SDK installed.
-Installing it requires administrator privileges. You can get it here:
-http://msdn.microsoft.com/en-us/library/bb219737(VS.85).aspx.
-
-The command line arguments are as follows:
-
-Usage: o3dConverter.exe [--base-path=<path>]
- [--up-axis=x,y,z]
- [--no-condition]
- [--pretty-print]
- [--no-binary]
- [--no-archive]
- [--convert-dds-to-png]
- [--convert-cg-to-glsl]
- <infile.dae> [ <outfile> ]
-
---base-path=<path>: This specifies the path elements to remove from
- the beginning of the filenames placed into the
- .o3dtgz file (to avoid including sensitive paths in
- the .o3dtgz file).
-
---up-axis=x,y,z: This specifies the up-axis for the resulting model,
- if you wish it to be different from the axis in the
- COLLADA file.
-
---pretty-print: This simply formats the JSON file in the resulting
- .o3dtgz file to be human readable, instead of compacted
- into one line.
-
---no-condition: This will prevent conditioning of the shaders from
- COLLADA form to the form expected by O3D. [This is
- useful only for pre-release data conditioned before
- the converter existed.]
-
-The following four command line options are useful when converting
-assets for the WebGL implementation of O3D:
-
---no-binary: Buffers, skins and curves will be written directly into the
- scene.json rather than into separate binary files.
-
---no-archive: Don't make a gzipped tar file, just flat files. Still
- takes the name of an archive file; for archive.o3dtgz,
- creates directory named archive/ and writes files inside.
-
---convert-dds-to-png: Convert all DDS textures to PNGs. For cube map
- textures, writes six separate PNGs with suffixes
- _posx, _negx, etc.
-
---convert-cg-to-glsl: Convert shaders using an external tool. Requires
- python on PATH and either NVIDIA Cg toolkit
- installed or cgc{.exe} in same directory as
- converter.
-
-<infile.dae|infile.zip|infile.kmz>: This is the input file in one of
- ZIP, KMZ, or DAE formats. The
- DAE format expects to find assets
- relative to the .dae file.
-
-<outfile>: An optional argument giving the name of the
- gzip-compressed tar archive output file. By default
- this has the same basename as the input file, and has the extension
- .o3dtgz.
diff --git a/o3d/converter/README.verifier b/o3d/converter/README.verifier
deleted file mode 100644
index af776bf..0000000
--- a/o3d/converter/README.verifier
+++ /dev/null
@@ -1,32 +0,0 @@
-The verifier is a command line utility that will verify shader files.
-
-This utility is used to verify that a shader will compile when given
-to O3D to render. On Windows, it will test-compile the given shader
-with both Cg and HLSL compilers. On Mac and Linux platforms, it will
-only compile using Cg (since DirectX isn't available on those
-platforms). This will help users on Windows verify that their shaders
-will run when displayed on Mac or Linux platforms, and will help
-everyone verify that their shaders compile.
-
-If an output file is specified, it can be used to convert shaders to a
-form that can be used directly in O3D. It strips out unneeded blocks
-(like the technique/pass blocks) and replaces them with the O3D
-comments which describe the shader entry points.
-
-The command line arguments are as follows:
-
-Usage: o3dVerifier.exe [--no-condition] <infile.fx> [ <outfile.fx> ]
-
---no-condition: This will prevent conditioning of the shaders into the
- form expected by O3D. Specifying this causes the
- verifier to ignore any output file specified (since
- that would just be copying the file, and not doing any
- conditioning). This option is useful only for
- verifying pre-conditioned shaders.
-
-<infile.fx>: This is the input filename of the shader to be validated.
-
-<outfile.fx>: An optional argument giving the name of the desired
- output location of the conditioned shader file in the
- form expected by O3D. If you don't specify this, then
- no output is created.
diff --git a/o3d/converter/converter.gyp b/o3d/converter/converter.gyp
deleted file mode 100644
index 2ac286d..0000000
--- a/o3d/converter/converter.gyp
+++ /dev/null
@@ -1,144 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- },
- 'includes': [
- '../build/common.gypi',
- ],
- 'target_defaults': {
- 'include_dirs': [
- '..',
- '../..',
- '../../<(gtestdir)',
- '../<(txcdir)',
- ],
- },
- 'targets': [
- {
- 'target_name': 'o3dConverter',
- 'type': 'executable',
- 'dependencies': [
- '../../<(antlrdir)/antlr.gyp:antlr3c',
- '../../<(fcolladadir)/fcollada.gyp:fcollada',
- '../../<(jpegdir)/libjpeg.gyp:libjpeg',
- '../../<(pngdir)/libpng.gyp:libpng',
- '../../<(zlibdir)/zlib.gyp:zlib',
- '../../base/base.gyp:base',
- '../../skia/skia.gyp:skia',
- '../compiler/technique/technique.gyp:o3dTechnique',
- '../core/core.gyp:o3dCore',
- '../core/core.gyp:o3dCorePlatform',
- '../import/archive.gyp:o3dArchive',
- '../import/import.gyp:o3dImport',
- '../serializer/serializer.gyp:o3dSerializer',
- '../utils/utils.gyp:o3dUtils',
- 'cgToGLSLConverterScript',
- ],
- 'sources': [
- 'cross/buffer_stub.cc',
- 'cross/buffer_stub.h',
- 'cross/converter.cc',
- 'cross/converter.h',
- 'cross/converter_main.cc',
- 'cross/draw_element_stub.h',
- 'cross/effect_stub.h',
- 'cross/param_cache_stub.h',
- 'cross/primitive_stub.h',
- 'cross/render_surface_stub.h',
- 'cross/renderer_stub.cc',
- 'cross/renderer_stub.h',
- 'cross/sampler_stub.h',
- 'cross/stream_bank_stub.h',
- 'cross/texture_stub.cc',
- 'cross/texture_stub.h',
- '../<(txcdir)/txc_fetch_dxtn.cc',
- ],
- 'conditions' : [
- ['renderer == "gl"',
- {
- 'dependencies': [
- '../build/libs.gyp:cg_libs',
- ],
- },
- ],
- ['OS == "mac"',
- {
- 'postbuilds': [
- {
- 'variables': {
- # Define install_name in a variable ending in _path
- # so that gyp understands it's a path and performs proper
- # relativization during dict merging.
- 'install_name_path': 'mac/converter_install_name.sh',
- },
- 'postbuild_name': 'Fix Framework Paths',
- 'action': ['<(install_name_path)'],
- },
- ],
- 'sources': [
- 'mac/converter_main.mm',
- ],
- 'link_settings': {
- 'libraries': [
- '$(SDKROOT)/System/Library/Frameworks/Foundation.framework',
- '$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework',
- '$(SDKROOT)/System/Library/Frameworks/OpenGL.framework',
- ],
- },
- },
- ],
- ['OS == "linux"',
- {
- 'link_settings': {
- 'libraries': [
- '-lGL',
- ],
- },
- },
- ],
- ['OS == "win"',
- {
- 'dependencies': [
- '../build/libs.gyp:dx_dll',
- '../build/libs.gyp:cg_libs',
- ],
- 'link_settings': {
- 'libraries': [
- '-lrpcrt4.lib',
- ],
- },
- 'msvs_settings': {
- 'VCLinkerTool': {
- # Set /SUBSYSTEM:CONSOLE for converter.exe, since
- # it is a console app.
- 'SubSystem': '1',
- },
- },
- },
- ],
- ],
- },
- {
- 'target_name': 'cgToGLSLConverterScript',
- 'type': 'none',
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)',
- 'files': [
- '../cg_to_glsl/convert.py',
- ]
- },
- ]
- },
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/converter/cross/buffer_stub.cc b/o3d/converter/cross/buffer_stub.cc
deleted file mode 100644
index d400ff2..0000000
--- a/o3d/converter/cross/buffer_stub.cc
+++ /dev/null
@@ -1,87 +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 definition of the VertexBufferStub and
-// IndexBufferStub classes.
-
-#include "converter/cross/buffer_stub.h"
-
-namespace o3d {
-
-bool VertexBufferStub::ConcreteAllocate(size_t size_in_bytes) {
- buffer_.reset(new int8[size_in_bytes]);
- return true;
-}
-
-void VertexBufferStub::ConcreteFree() {
- buffer_.reset();
-}
-
-bool VertexBufferStub::ConcreteLock(AccessMode access_mode,
- void** buffer_data) {
- *buffer_data = buffer_.get();
- DCHECK(locked_ == false);
- locked_ = true;
- return (buffer_.get() != NULL);
-}
-
-bool VertexBufferStub::ConcreteUnlock() {
- bool status = locked_;
- DCHECK(locked_ == true);
- locked_ = false;
- return status;
-}
-
-bool IndexBufferStub::ConcreteAllocate(size_t size_in_bytes) {
- buffer_.reset(new int8[size_in_bytes]);
- return true;
-}
-
-void IndexBufferStub::ConcreteFree() {
- buffer_.reset();
-}
-
-bool IndexBufferStub::ConcreteLock(AccessMode access_mode, void** buffer_data) {
- *buffer_data = buffer_.get();
- DCHECK(locked_ == false);
- locked_ = true;
- return (buffer_.get() != NULL);
-}
-
-bool IndexBufferStub::ConcreteUnlock() {
- bool status = locked_;
- DCHECK(locked_ == true);
- locked_ = false;
- return status;
-}
-
-} // end namespace o3d
diff --git a/o3d/converter/cross/buffer_stub.h b/o3d/converter/cross/buffer_stub.h
deleted file mode 100644
index 26c0aad..0000000
--- a/o3d/converter/cross/buffer_stub.h
+++ /dev/null
@@ -1,112 +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 declaration of the platform specific
-// VertexBufferStub and IndexBufferStub objects used by O3D
-
-#ifndef O3D_CONVERTER_CROSS_BUFFER_STUB_H_
-#define O3D_CONVERTER_CROSS_BUFFER_STUB_H_
-
-#include "base/basictypes.h"
-#include "base/scoped_ptr.h"
-#include "core/cross/buffer.h"
-
-namespace o3d {
-
-// VertexBufferStub is a wrapper around an Stub Vertex Buffer Object (VBO).
-// The buffer starts out empty. Calling Allocate() will reserve video memory
-// for the buffer. Buffer contents are are updated by calling Lock() to get a
-// pointer to the memory allocated for the buffer, updating that data in place
-// and calling Unlock() to notify Stub that the edits are done.
-
-class VertexBufferStub : public VertexBuffer {
- public:
- explicit VertexBufferStub(ServiceLocator* service_locator)
- : VertexBuffer(service_locator), locked_(false) {}
- ~VertexBufferStub() {}
-
- protected:
- // Creates a Stub vertex buffer object of the specified size.
- virtual bool ConcreteAllocate(size_t size_in_bytes);
-
- // Frees the buffer.
- virtual void ConcreteFree();
-
- // Returns a pointer to the current contents of the buffer. A matching
- // call to Unlock is necessary to update the contents of the buffer.
- virtual bool ConcreteLock(AccessMode access_mode, void** buffer_data);
-
- // Notifies Stub that the buffer data has been updated. Unlock is only
- // valid if it follows a Lock operation.
- virtual bool ConcreteUnlock();
- private:
- scoped_array<int8> buffer_;
- bool locked_;
-
- DISALLOW_COPY_AND_ASSIGN(VertexBufferStub);
-};
-
-// IndexBufferStub is a wrapper around a Stub Index Buffer Object.
-// The buffer starts out empty. A call to Allocate() will create a stub
-// index buffer of the requested size. Updates the to the contents of the
-// buffer are done via the Lock/Unlock calls.
-class IndexBufferStub : public IndexBuffer {
- public:
- explicit IndexBufferStub(ServiceLocator* service_locator)
- : IndexBuffer(service_locator), locked_(false) {}
- ~IndexBufferStub() {}
-
- protected:
- // Creates a OpenGL index buffer of the specified size.
- virtual bool ConcreteAllocate(size_t size_in_bytes);
-
- // Frees the buffer.
- virtual void ConcreteFree();
-
- // Returns a pointer to the current contents of the buffer. After calling
- // Lock, the contents of the buffer can be updated in place.
- virtual bool ConcreteLock(AccessMode access_mode, void** buffer_data);
-
- // Notifies OpenGL that the buffer data has been updated. Unlock is only
- // valid if it follows a Lock operation.
- virtual bool ConcreteUnlock();
- private:
- scoped_array<int8> buffer_;
- bool locked_;
-
- DISALLOW_COPY_AND_ASSIGN(IndexBufferStub);
-};
-
-} // namespace o3d
-
-
-#endif // O3D_CONVERTER_CROSS_BUFFER_STUB_H_
diff --git a/o3d/converter/cross/converter.cc b/o3d/converter/cross/converter.cc
deleted file mode 100644
index 68969f2..0000000
--- a/o3d/converter/cross/converter.cc
+++ /dev/null
@@ -1,576 +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 logic for converting the scene graph to a
-// JSON-encoded file that is stored in a zip archive.
-#include "converter/cross/converter.h"
-
-#include "base/file_path.h"
-#include "base/file_util.h"
-#include "base/scoped_ptr.h"
-#include "converter/cross/renderer_stub.h"
-#include "core/cross/class_manager.h"
-#include "core/cross/client.h"
-#include "core/cross/client_info.h"
-#include "core/cross/effect.h"
-#include "core/cross/error.h"
-#include "core/cross/features.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/renderer.h"
-#include "core/cross/service_locator.h"
-#include "core/cross/transform.h"
-#include "core/cross/tree_traversal.h"
-#include "core/cross/types.h"
-#include "import/cross/collada.h"
-#include "import/cross/collada_conditioner.h"
-#include "import/cross/file_output_stream_processor.h"
-#include "import/cross/iarchive_generator.h"
-#include "import/cross/targz_generator.h"
-#include "import/cross/archive_request.h"
-#include "serializer/cross/serializer.h"
-#include "utils/cross/file_path_utils.h"
-#include "utils/cross/json_writer.h"
-#include "utils/cross/string_writer.h"
-#include "utils/cross/temporary_file.h"
-
-namespace o3d {
-
-namespace {
-// Writes either to an archive file or to multiple flat files.
-class MultiFileWriter : public IArchiveGenerator {
- public:
- virtual ~MultiFileWriter() {}
-
- // Takes the path of an archive file. If writing multiple flat
- // files, then for archive named archive.o3dtgz, creates directory
- // "archive/" and writes all files within.
- virtual bool OpenTopLevelFile(const FilePath& file_name,
- const char* mode) = 0;
-
- // Closes the top-level file and any currently open sub-file.
- virtual void CloseTopLevelFile(bool success) = 0;
-
- int AddFileBytes(const uint8* data, size_t n);
-
- //----------------------------------------------------------------------
- // IArchiveGenerator
- // It seems these virtual functions need to be re-declared here.
- // (Compiler bugs on Mac OS X?)
-
- // AddFile either adds a file to the archive, or opens a new flat
- // file. If a sub-file is currently open, implicitly closes it.
- virtual bool AddFile(const String& file_name,
- size_t file_size) = 0;
-
- // Writes data to the current sub-file.
- virtual int AddFileBytes(MemoryReadStream* stream, size_t n) = 0;
-
- // Closes the current sub-file.
- virtual void Close(bool success) = 0;
-
- protected:
- MultiFileWriter() {}
-
- private:
- DISALLOW_COPY_AND_ASSIGN(MultiFileWriter);
-};
-
-int MultiFileWriter::AddFileBytes(const uint8* data, size_t n) {
- MemoryReadStream stream(data, n);
- return AddFileBytes(&stream, n);
-}
-
-class TarGzWriter : public MultiFileWriter {
- public:
- TarGzWriter() {}
- virtual ~TarGzWriter();
-
- virtual bool OpenTopLevelFile(const FilePath& file_name,
- const char* mode);
- virtual bool AddFile(const String& file_name,
- size_t file_size);
- virtual int AddFileBytes(MemoryReadStream* stream,
- size_t n);
- virtual void Close(bool success);
- virtual void CloseTopLevelFile(bool success);
-
- private:
- scoped_ptr<FileOutputStreamProcessor> stream_processor_;
- scoped_ptr<TarGzGenerator> archive_generator_;
- DISALLOW_COPY_AND_ASSIGN(TarGzWriter);
-};
-
-TarGzWriter::~TarGzWriter() {
- // Need to reset these in the right order.
- archive_generator_.reset();
- stream_processor_.reset();
-}
-
-bool TarGzWriter::OpenTopLevelFile(const FilePath& file_name,
- const char* mode) {
- FILE* out_file = file_util::OpenFile(file_name, mode);
- if (out_file == NULL) {
- return false;
- }
- stream_processor_.reset(new FileOutputStreamProcessor(out_file));
- archive_generator_.reset(new TarGzGenerator(stream_processor_.get()));
- return true;
-}
-
-bool TarGzWriter::AddFile(const String& file_name,
- size_t file_size) {
- archive_generator_->AddFile(file_name, file_size);
- return true;
-}
-
-int TarGzWriter::AddFileBytes(MemoryReadStream* stream,
- size_t n) {
- return archive_generator_->AddFileBytes(stream, n);
-}
-
-void TarGzWriter::Close(bool success) {
-}
-
-void TarGzWriter::CloseTopLevelFile(bool success) {
- archive_generator_->Close(success);
-}
-
-class FlatFileWriter : public MultiFileWriter {
- public:
- FlatFileWriter() {}
- virtual ~FlatFileWriter();
-
- virtual bool OpenTopLevelFile(const FilePath& file_name,
- const char* mode);
- virtual bool AddFile(const String& file_name,
- size_t file_size);
- virtual int AddFileBytes(MemoryReadStream* stream,
- size_t n);
- virtual void Close(bool success);
- virtual void CloseTopLevelFile(bool success);
-
- private:
- FilePath destination_directory_;
- String mode_;
- scoped_ptr<FileOutputStreamProcessor> stream_processor_;
- DISALLOW_COPY_AND_ASSIGN(FlatFileWriter);
-};
-
-FlatFileWriter::~FlatFileWriter() {
-}
-
-bool FlatFileWriter::OpenTopLevelFile(const FilePath& file_name,
- const char* mode) {
- destination_directory_ = file_name.RemoveExtension();
- if (!file_util::CreateDirectory(destination_directory_)) {
- return false;
- }
- mode_ = String(mode);
- return true;
-}
-
-bool FlatFileWriter::AddFile(const String& file_name,
- size_t file_size) {
- Close(true);
- FilePath path = destination_directory_.Append(UTF8ToFilePath(file_name));
- // We may need to make parent directories.
- FilePath parent_dir = path.DirName();
- if (!file_util::CreateDirectory(parent_dir)) {
- return false;
- }
- FILE* out_file = file_util::OpenFile(path, mode_.c_str());
- // We expect to be able to write the desired file.
- DCHECK_NE(out_file, static_cast<FILE*>(NULL));
- if (out_file == NULL) {
- return false;
- }
- stream_processor_.reset(new FileOutputStreamProcessor(out_file));
- return true;
-}
-
-int FlatFileWriter::AddFileBytes(MemoryReadStream* stream,
- size_t n) {
- if (!stream_processor_.get())
- return 0;
- StreamProcessor::Status status =
- stream_processor_->ProcessBytes(stream, n);
- if (status == StreamProcessor::FAILURE)
- return 0;
- return n;
-}
-
-void FlatFileWriter::Close(bool success) {
- if (stream_processor_.get()) {
- stream_processor_->Close(success);
- stream_processor_.reset();
- }
-}
-
-void FlatFileWriter::CloseTopLevelFile(bool success) {
- Close(success);
-}
-
-void AddBinaryElements(const Collada& collada,
- MultiFileWriter* file_writer) {
- const ColladaDataMap& data_map(collada.original_data_map());
- std::vector<FilePath> paths = data_map.GetOriginalDataFilenames();
- for (std::vector<FilePath>::const_iterator iter = paths.begin();
- iter != paths.end();
- ++iter) {
- const std::string& data = data_map.GetOriginalData(*iter);
-
- file_writer->AddFile(FilePathToUTF8(*iter), data.size());
- file_writer->AddFileBytes(
- reinterpret_cast<const uint8*>(data.c_str()),
- data.length());
- }
-}
-} // end anonymous namespace
-
-namespace converter {
-// Loads the Collada input file and writes it to the zipped JSON output file.
-bool Convert(const FilePath& in_filename,
- const FilePath& out_filename,
- const Options& options,
- String *error_messages) {
- // Create a service locator and renderer.
- ServiceLocator service_locator;
- EvaluationCounter evaluation_counter(&service_locator);
- ClassManager class_manager(&service_locator);
- ClientInfoManager client_info_manager(&service_locator);
- ObjectManager object_manager(&service_locator);
- Profiler profiler(&service_locator);
- ErrorStatus error_status(&service_locator);
- Features features(&service_locator);
-
- Collada::Init(&service_locator);
- features.Init("MaxCapabilities");
-
- // Collect error messages.
- ErrorCollector error_collector(&service_locator);
-
- scoped_ptr<Renderer> renderer(RendererStub::CreateDefault(&service_locator));
- renderer->InitCommon();
-
- Pack::Ref pack(object_manager.CreatePack());
- Transform* root = pack->Create<Transform>();
- root->set_name(String(Serializer::ROOT_PREFIX) + String("root"));
-
- // Setup a ParamFloat to be the source to all animations in this file.
- ParamObject* param_object = pack->Create<ParamObject>();
- // This is some arbitrary name
- param_object->set_name(O3D_STRING_CONSTANT("animSourceOwner"));
- ParamFloat* param_float = param_object->CreateParam<ParamFloat>("animSource");
-
- Collada::Options collada_options;
- collada_options.condition_document = options.condition;
- collada_options.keep_original_data = true;
- collada_options.base_path = options.base_path;
- collada_options.file_paths = options.file_paths;
- collada_options.up_axis = options.up_axis;
- collada_options.convert_dds_to_png = options.convert_dds_to_png;
- collada_options.convert_cg_to_glsl = options.convert_cg_to_glsl;
- collada_options.converter_tool = options.converter_tool;
- Collada collada(pack.Get(), collada_options);
- bool result = collada.ImportFile(in_filename, root, param_float);
- if (!result || !error_collector.errors().empty()) {
- if (error_messages) {
- *error_messages += error_collector.errors();
- }
- return false;
- }
-
- // Remove the animation param_object (and indirectly the param_float)
- // if there is no animation.
- if (param_float->output_connections().empty()) {
- pack->RemoveObject(param_object);
- }
-
- // Mark all Samplers to use tri-linear filtering
- if (!options.keep_filters) {
- std::vector<Sampler*> samplers = pack->GetByClass<Sampler>();
- for (unsigned ii = 0; ii < samplers.size(); ++ii) {
- Sampler* sampler = samplers[ii];
- sampler->set_mag_filter(Sampler::LINEAR);
- sampler->set_min_filter(Sampler::LINEAR);
- sampler->set_mip_filter(Sampler::LINEAR);
- }
- }
-
- // Mark all Materials that are on Primitives that have no normals as constant.
- if (!options.keep_materials) {
- std::vector<Primitive*> primitives = pack->GetByClass<Primitive>();
- for (unsigned ii = 0; ii < primitives.size(); ++ii) {
- Primitive* primitive = primitives[ii];
- StreamBank* stream_bank = primitive->stream_bank();
- if (stream_bank && !stream_bank->GetVertexStream(Stream::NORMAL, 0)) {
- Material* material = primitive->material();
- if (material) {
- ParamString* lighting_param = material->GetParam<ParamString>(
- Collada::kLightingTypeParamName);
- if (lighting_param) {
- // If the lighting type is lambert, blinn, or phong
- // copy the diffuse color to the emissive since that's most likely
- // what the user wants to see.
- if (lighting_param->value().compare(
- Collada::kLightingTypeLambert) == 0 ||
- lighting_param->value().compare(
- Collada::kLightingTypeBlinn) == 0 ||
- lighting_param->value().compare(
- Collada::kLightingTypePhong) == 0) {
- // There's 4 cases: (to bad they are not the same names)
- // 1) Diffuse -> Emissive
- // 2) DiffuseSampler -> Emissive
- // 3) Diffuse -> EmissiveSampler
- // 4) DiffuseSampler -> EmissiveSampler
- ParamFloat4* diffuse_param = material->GetParam<ParamFloat4>(
- Collada::kMaterialParamNameDiffuse);
- ParamFloat4* emissive_param = material->GetParam<ParamFloat4>(
- Collada::kMaterialParamNameEmissive);
- ParamSampler* diffuse_sampler_param =
- material->GetParam<ParamSampler>(
- Collada::kMaterialParamNameDiffuseSampler);
- ParamSampler* emissive_sampler_param =
- material->GetParam<ParamSampler>(
- Collada::kMaterialParamNameEmissive);
- Param* source_param = diffuse_param ?
- static_cast<Param*>(diffuse_param) :
- static_cast<Param*>(diffuse_sampler_param);
- Param* destination_param = emissive_param ?
- static_cast<Param*>(emissive_param) :
- static_cast<Param*>(emissive_sampler_param);
- if (!source_param->IsA(destination_param->GetClass())) {
- // The params do not match type so we need to make the emissive
- // Param the same as the diffuse Param.
- material->RemoveParam(destination_param);
- destination_param = material->CreateParamByClass(
- diffuse_param ? Collada::kMaterialParamNameEmissive :
- Collada::kMaterialParamNameEmissiveSampler,
- source_param->GetClass());
- DCHECK(destination_param);
- }
- destination_param->CopyDataFromParam(source_param);
- }
- lighting_param->set_value(Collada::kLightingTypeConstant);
- }
- }
- }
- }
- }
-
- // Attempt to open the output file.
- scoped_ptr<MultiFileWriter> file_writer;
- if (options.archive) {
- file_writer.reset(new TarGzWriter);
- } else {
- file_writer.reset(new FlatFileWriter);
- }
-
- // Create an archive file or individual flat files and serialize the
- // JSON scene graph and assets to it / them.
- if (!file_writer->OpenTopLevelFile(out_filename, "wb")) {
- O3D_ERROR(&service_locator) << "Could not open output file \""
- << FilePathToUTF8(out_filename).c_str()
- << "\"";
- if (error_messages) {
- *error_messages += error_collector.errors();
- }
- return false;
- }
-
- if (options.archive) {
- file_writer->AddFile(ArchiveRequest::kO3DMarker,
- ArchiveRequest::kO3DMarkerContentLength);
- file_writer->AddFileBytes(
- reinterpret_cast<const uint8*>(ArchiveRequest::kO3DMarkerContent),
- ArchiveRequest::kO3DMarkerContentLength);
- }
-
- // Serialize the created O3D scene graph to JSON.
- StringWriter out_writer(StringWriter::LF);
- JsonWriter json_writer(&out_writer, 2);
- if (!options.pretty_print) {
- json_writer.BeginCompacting();
- }
- Serializer::Options serializer_options(
- options.binary ? Serializer::Options::kBinaryOutputOn :
- Serializer::Options::kBinaryOutputOff);
- Serializer serializer(
- &service_locator, &json_writer, file_writer.get(), serializer_options);
- serializer.SerializePack(pack.Get());
- json_writer.Close();
- out_writer.Close();
- if (!options.pretty_print) {
- json_writer.EndCompacting();
- }
-
- String json = out_writer.ToString();
-
- file_writer->AddFile("scene.json", json.length());
- file_writer->AddFileBytes(reinterpret_cast<const uint8*>(json.c_str()),
- json.length());
-
- // Now add original data (e.g. compressed textures) collected during
- // the loading process.
- AddBinaryElements(collada, file_writer.get());
-
- file_writer->CloseTopLevelFile(true);
-
- pack->Destroy();
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return true;
-}
-
-// Loads the input shader file and validates it.
-bool Verify(const FilePath& in_filename,
- const FilePath& out_filename,
- const Options& options,
- String* error_messages) {
- FilePath source_filename(in_filename);
- // Create a service locator and renderer.
- ServiceLocator service_locator;
- EvaluationCounter evaluation_counter(&service_locator);
- ClassManager class_manager(&service_locator);
- ObjectManager object_manager(&service_locator);
- Profiler profiler(&service_locator);
- ErrorStatus error_status(&service_locator);
-
- // Collect error messages.
- ErrorCollector error_collector(&service_locator);
-
- scoped_ptr<Renderer> renderer(
- RendererStub::CreateDefault(&service_locator));
- renderer->InitCommon();
-
- Pack::Ref pack(object_manager.CreatePack());
- Transform* root = pack->Create<Transform>();
- root->set_name(O3D_STRING_CONSTANT("root"));
-
- Collada::Options collada_options;
- collada_options.condition_document = options.condition;
- collada_options.keep_original_data = false;
- Collada collada(pack.Get(), collada_options);
-
- ColladaConditioner conditioner(&service_locator);
- String vertex_shader_entry_point;
- String fragment_shader_entry_point;
- TemporaryFile temp_file;
- if (options.condition) {
- if (!TemporaryFile::Create(&temp_file)) {
- O3D_ERROR(&service_locator) << "Could not create temporary file";
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return false;
- }
- SamplerStateList state_list;
- if (!conditioner.RewriteShaderFile(NULL,
- in_filename,
- temp_file.path(),
- &state_list,
- &vertex_shader_entry_point,
- &fragment_shader_entry_point)) {
- O3D_ERROR(&service_locator) << "Could not rewrite shader file";
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return false;
- }
- source_filename = temp_file.path();
- } else {
- source_filename = in_filename;
- }
-
- std::string shader_source_in;
- // Load file into memory
- if (!file_util::ReadFileToString(source_filename, &shader_source_in)) {
- O3D_ERROR(&service_locator) << "Could not read shader file "
- << FilePathToUTF8(source_filename).c_str();
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return false;
- }
-
- Effect::MatrixLoadOrder matrix_load_order;
- scoped_ptr<Effect> effect(pack->Create<Effect>());
- if (!effect->ValidateFX(shader_source_in,
- &vertex_shader_entry_point,
- &fragment_shader_entry_point,
- &matrix_load_order)) {
- O3D_ERROR(&service_locator) << "Could not validate shader file";
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return false;
- }
-
- if (!conditioner.CompileHLSL(shader_source_in,
- vertex_shader_entry_point,
- fragment_shader_entry_point)) {
- O3D_ERROR(&service_locator) << "Could not HLSL compile shader file";
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return false;
- }
-
- if (!conditioner.CompileCg(in_filename,
- shader_source_in,
- vertex_shader_entry_point,
- fragment_shader_entry_point)) {
- O3D_ERROR(&service_locator) << "Could not Cg compile shader file";
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return false;
- }
-
- // If we've validated the file, then we write out the conditioned
- // shader to the given output file, if there is one.
- if (options.condition && !out_filename.empty()) {
- if (file_util::WriteFile(out_filename, shader_source_in.c_str(),
- static_cast<int>(shader_source_in.size())) == -1) {
- O3D_ERROR(&service_locator) << "Warning: Could not write to output file '"
- << FilePathToUTF8(in_filename).c_str() << "'";
- }
- }
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return true;
-}
-} // end namespace converter
-} // end namespace o3d
diff --git a/o3d/converter/cross/converter.h b/o3d/converter/cross/converter.h
deleted file mode 100644
index 69e801b..0000000
--- a/o3d/converter/cross/converter.h
+++ /dev/null
@@ -1,127 +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 declarations for the functions in the
-// O3D converter namespace. These functions do most of the actual
-// work of conditioning and packagaging a JSON file for use in
-// O3D.
-
-#ifndef O3D_CONVERTER_CROSS_CONVERTER_H_
-#define O3D_CONVERTER_CROSS_CONVERTER_H_
-
-#include <vector>
-#include "base/file_path.h"
-#include "core/cross/types.h"
-#include "utils/cross/file_path_utils.h"
-
-namespace o3d {
-namespace converter {
-
-// Options struct for passing to the converter.
-struct Options {
- Options()
- : base_path(FilePath::kCurrentDirectory),
- condition(true),
- up_axis(0, 0, 0),
- pretty_print(false),
- keep_filters(false),
- keep_materials(false),
- archive(true),
- convert_dds_to_png(false),
- convert_cg_to_glsl(false),
- converter_tool() {
- }
-
- // A list of paths to search for assets..
- std::vector<FilePath> file_paths;
-
- // The path to the "base" of the model path, from which all paths
- // are made relative. Defaults to the current directory.
- FilePath base_path;
-
- // Indicates if the converter should condition the input shaders or
- // not.
- bool condition;
-
- // The up axis of the output. The input will be converted to a new coordinate
- // system if it indicates a different up axis. Zero means no conversion.
- Vector3 up_axis;
-
- // This indicates whether or not the serialized JSON code should be
- // pretty-printed (formatted with spaces and newlines) or just
- // emitted as one huge one-line string. Defaults to false.
- bool pretty_print;
-
- // Tells the converter not to set all filters to tri-linear.
- bool keep_filters;
-
- // Tells the converter not to change materials to constant if they are used by
- // a mesh that has no normals.
- bool keep_materials;
-
- // Use binary formats for buffers, skin, curve.
- bool binary;
-
- // True means make a gzipped tar file. False means write individual files.
- bool archive;
-
- // True means convert DDS files to PNGs. For cube map textures, this
- // implies writing six separate PNGs.
- bool convert_dds_to_png;
-
- // True means convert CG shaders go GLSL using external cgc tool.
- bool convert_cg_to_glsl;
-
- // Path to shader converter tool.
- FilePath converter_tool;
-};
-
-// Converts the given file for use in O3D. This is done by
-// loading the input file, traversing the scene graph and serializing
-// what is found there.
-bool Convert(const FilePath& in_filename,
- const FilePath& out_filename,
- const Options& options,
- String* error_messages);
-
-// Verifies the given shader file as "valid". Returns true if input
-// shader file contains valid code (code that can be compiled
-// successfully).
-bool Verify(const FilePath& in_filename,
- const FilePath& out_filename,
- const Options& options,
- String* error_messages);
-
-} // namespace converter
-} // namespace o3d
-
-#endif // O3D_CONVERTER_CROSS_CONVERTER_H_
diff --git a/o3d/converter/cross/converter_main.cc b/o3d/converter/cross/converter_main.cc
deleted file mode 100644
index ee819a9..0000000
--- a/o3d/converter/cross/converter_main.cc
+++ /dev/null
@@ -1,181 +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 main routine for the converter that writes
-// out a scene graph as a JSON file.
-
-#include <string>
-#include <iostream>
-#include <vector>
-
-#include "base/at_exit.h"
-#include "base/command_line.h"
-#include "base/file_path.h"
-#include "base/file_util.h"
-#include "base/string_util.h"
-#include "converter/cross/converter.h"
-#include "utils/cross/file_path_utils.h"
-
-using std::string;
-using std::wstring;
-
-#if defined(OS_WIN)
-int wmain(int argc, wchar_t **argv) {
- // On Windows, CommandLine::Init ignores its arguments and uses
- // GetCommandLineW.
- CommandLine::Init(0, NULL);
-#endif
-#if defined(OS_LINUX)
-int main(int argc, char **argv) {
- CommandLine::Init(argc, argv);
-#endif
-#if defined(OS_MACOSX)
-// The "real" main on Mac is in mac/converter_main.mm, so we can get
-// memory pool initialization for Cocoa.
-int CrossMain(int argc, char**argv) {
- CommandLine::Init(argc, argv);
-#endif
- // Create an at_exit_manager so that base singletons will get
- // deleted properly.
- base::AtExitManager at_exit_manager;
- const CommandLine* command_line = CommandLine::ForCurrentProcess();
-
- FilePath in_filename, out_filename;
- // Use the absolute path to the converter tool for the case that we
- // are in the current working directory and "." is not on the PATH.
- FilePath converter_dir = FilePath(argv[0]).DirName();
- file_util::AbsolutePath(&converter_dir);
- const FilePath converter_tool = converter_dir.Append(
- o3d::UTF8ToFilePath("convert.py"));
-
-
- std::vector<std::wstring> values = command_line->GetLooseValues();
- if (values.size() == 1) {
- // If we're only given one argument, then construct the output
- // filename by substituting the extension on the filename (if any)
- // with .o3dtgz.
- in_filename = o3d::WideToFilePath(values[0]);
- out_filename = in_filename.ReplaceExtension(FILE_PATH_LITERAL(".o3dtgz"));
- } else if (values.size()== 2) {
- in_filename = o3d::WideToFilePath(values[0]);
- out_filename = o3d::WideToFilePath(values[1]);
- } else {
- std::cerr << "Usage: " << argv[0]
- << " [ options ] <infile.dae> [ <outfile> ]\n";
- std::cerr
- << "--no-condition\n"
- << " Stops the converter from conditioning shaders.\n"
- << "--base-path=<path>\n"
- << " Sets the path to remove from URIs of external files\n"
- << "--asset-paths=<comma separted list of paths>\n"
- << " Sets the paths for finding textures and other external\n"
- << " files.\n"
- << "--up-axis=x,y,z\n"
- << " Converts the file to have this up axis.\n"
- << "--pretty-print\n"
- << " Makes the exported JSON easier to read.\n"
- << "--keep-filters\n"
- << " Stops the converter from forcing all texture samplers to use\n"
- << " tri-linear filtering.\n"
- << "--keep-materials\n"
- << " Stops the converter from changing materials to <constant> if\n"
- << " they are used by a mesh that has no normals.\n"
- << "--no-binary\n"
- << " Use JSON for buffers, skins, curves instead of binary\n"
- << "--no-archive\n"
- << " Don't make a gzipped tar file, just flat files. Still takes\n"
- << " the name of an archive file; for archive.o3dtgz, creates\n"
- << " directory named archive/ and writes files inside.\n"
- << "--convert-dds-to-png\n"
- << " Convert all DDS textures to PNGs. For cube map textures,\n"
- << " writes six separate PNGs with suffixes _posx, _negx, etc.\n"
- << "--convert-cg-to-glsl\n"
- << " Convert shaders using an external tool.\n"
- << " Requires python on PATH.\n"
- << "--converter-tool=<filename> [default: "
- << converter_tool.value() << "]\n"
- << " Specifies the shader converter tool.\n";
- return EXIT_FAILURE;
- }
-
- o3d::converter::Options options;
- options.condition = !command_line->HasSwitch("no-condition");
- options.pretty_print = command_line->HasSwitch("pretty-print");
- options.binary = !command_line->HasSwitch("no-binary");
- options.archive = !command_line->HasSwitch("no-archive");
- options.convert_dds_to_png = command_line->HasSwitch("convert-dds-to-png");
- options.convert_cg_to_glsl = command_line->HasSwitch("convert-cg-to-glsl");
- options.converter_tool = command_line->HasSwitch("converter-tool") ?
- o3d::WideToFilePath(command_line->GetSwitchValue("converter-tool")) :
- converter_tool;
- if (command_line->HasSwitch("base-path")) {
- options.base_path = o3d::WideToFilePath(
- command_line->GetSwitchValue("base-path"));
- }
- if (command_line->HasSwitch("asset-paths")) {
- std::vector<std::wstring> paths;
- SplitString(command_line->GetSwitchValue("asset-paths"), ',', &paths);
- for (size_t ii = 0; ii < paths.size(); ++ii) {
- options.file_paths.push_back(o3d::WideToFilePath(paths[ii]));
- }
- }
- if (command_line->HasSwitch("up-axis")) {
- wstring up_axis_string = command_line->GetSwitchValue("up-axis");
- int x, y, z;
- if (swscanf(up_axis_string.c_str(), L"%d,%d,%d", &x, &y, &z) != 3) {
- std::cerr << "Invalid --up-axis value. Should be --up-axis=x,y,z\n";
- return EXIT_FAILURE;
- }
- options.up_axis = o3d::Vector3(static_cast<float>(x),
- static_cast<float>(y),
- static_cast<float>(z));
- }
-
- o3d::String error_messages;
- bool result = o3d::converter::Convert(in_filename,
- out_filename,
- options,
- &error_messages);
- if (result) {
- std::cerr << "Converted '" << o3d::FilePathToUTF8(in_filename).c_str()
- << "' to '" << o3d::FilePathToUTF8(out_filename).c_str()
- << "'." << std::endl;
- return EXIT_SUCCESS;
- } else {
- std::cerr << error_messages.c_str() << std::endl;
- std::cerr << "FAILED to convert '"
- << o3d::FilePathToUTF8(in_filename).c_str()
- << "' to '" << o3d::FilePathToUTF8(out_filename).c_str()
- << "'." << std::endl;
- return EXIT_FAILURE;
- }
-}
diff --git a/o3d/converter/cross/draw_element_stub.h b/o3d/converter/cross/draw_element_stub.h
deleted file mode 100644
index 6d92ebc..0000000
--- a/o3d/converter/cross/draw_element_stub.h
+++ /dev/null
@@ -1,58 +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 declaration of the DrawElementGL class.
-
-#ifndef O3D_CONVERTER_CROSS_DRAW_ELEMENT_STUB_H_
-#define O3D_CONVERTER_CROSS_DRAW_ELEMENT_STUB_H_
-
-#include "core/cross/draw_element.h"
-
-namespace o3d {
-
-class ServiceLocator;
-
-// DrawElementStub is the Stub implementation of the DrawElement. It
-// provides a place for the renderer to store platform specific cache
-// information.
-class DrawElementStub : public DrawElement {
- public:
- explicit DrawElementStub(ServiceLocator* service_locator)
- : DrawElement(service_locator) {}
- ~DrawElementStub() {}
-
- private:
- DISALLOW_COPY_AND_ASSIGN(DrawElementStub);
-};
-} // o3d
-
-#endif // O3D_CONVERTER_CROSS_DRAW_ELEMENT_STUB_H_
diff --git a/o3d/converter/cross/effect_stub.h b/o3d/converter/cross/effect_stub.h
deleted file mode 100644
index 7a54a9b..0000000
--- a/o3d/converter/cross/effect_stub.h
+++ /dev/null
@@ -1,73 +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 declaration of the EffectGL class.
-
-#ifndef O3D_CONVERTER_CROSS_EFFECT_STUB_H_
-#define O3D_CONVERTER_CROSS_EFFECT_STUB_H_
-
-#include "core/cross/effect.h"
-
-namespace o3d {
-
-class ServiceLocator;
-
-// EffectStub is an implementation of the Effect object for the
-// converter. It provides the API for setting the vertex and fragment
-// shaders for the Effect using the Cg Runtime.
-class EffectStub : public Effect {
- public:
- explicit EffectStub(ServiceLocator* service_locator)
- : Effect(service_locator) {}
- virtual ~EffectStub() {}
-
- // Reads the vertex and fragment shaders from string in the FX format.
- // It returns true if the shaders were successfully compiled.
- virtual bool LoadFromFXString(const String& effect) { return true; }
-
- // Gets info about the parameters this effect needs.
- // Overriden from Effect.
- virtual void GetParameterInfo(EffectParameterInfoArray* info_array) {}
-
- // Gets info about the varying parameters this effects vertex shader needs.
- // Parameters:
- // info_array: EffectParameterInfoArray to receive info.
- virtual void GetStreamInfo(
- EffectStreamInfoArray* info_array) {
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(EffectStub);
-};
-} // namespace o3d
-
-#endif // O3D_CONVERTER_CROSS_EFFECT_STUB_H_
diff --git a/o3d/converter/cross/param_cache_stub.h b/o3d/converter/cross/param_cache_stub.h
deleted file mode 100644
index 5ae89ee..0000000
--- a/o3d/converter/cross/param_cache_stub.h
+++ /dev/null
@@ -1,69 +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 declaration of the ParamCacheStub class.
-
-#ifndef O3D_CONVERTER_CROSS_PARAM_CACHE_STUB_H_
-#define O3D_CONVERTER_CROSS_PARAM_CACHE_STUB_H_
-
-#include "core/cross/param_cache.h"
-
-namespace o3d {
-
-class Effect;
-class DrawElement;
-class Element;
-class Material;
-class ParamObject;
-
-class ParamCacheStub : public ParamCache {
- public:
- ParamCacheStub() : ParamCache() {}
-
- // Overridden from ParamCache.
- virtual void UpdateCache(Effect* effect,
- DrawElement* draw_element,
- Element* element,
- Material* material,
- ParamObject* override) {}
-
- protected:
- // Overridden from ParamCache
- // Validates platform specific information about the effect.
- virtual bool ValidateEffect(Effect* effect) { return true; }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(ParamCacheStub);
-};
-} // o3d
-
-#endif // O3D_CONVERTER_CROSS_PARAM_CACHE_STUB_H_
diff --git a/o3d/converter/cross/primitive_stub.h b/o3d/converter/cross/primitive_stub.h
deleted file mode 100644
index b17bec0..0000000
--- a/o3d/converter/cross/primitive_stub.h
+++ /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.
- */
-
-
-// This file contains the declaration of the PrimitiveStub class.
-
-#ifndef O3D_CONVERTER_CROSS_PRIMITIVE_STUB_H_
-#define O3D_CONVERTER_CROSS_PRIMITIVE_STUB_H_
-
-#include "core/cross/primitive.h"
-
-namespace o3d {
-
-class DrawElement;
-class Material;
-class ParamCache;
-class ParamObject;
-class Renderer;
-class ServiceLocator;
-
-// PrimitiveStub is the Stub implementation of the Primitive. It provides the
-// necessary interfaces for setting the geometry streams on the Primitive.
-class PrimitiveStub : public Primitive {
- public:
- explicit PrimitiveStub(ServiceLocator* service_locator)
- : Primitive(service_locator) {}
- virtual ~PrimitiveStub() {}
-
- protected:
- // Overridden from Primitive.
- virtual void PlatformSpecificRender(Renderer* renderer,
- DrawElement* draw_element,
- Material* material,
- ParamObject* override,
- ParamCache* param_cache) {}
-
- private:
- DISALLOW_COPY_AND_ASSIGN(PrimitiveStub);
-};
-} // o3d
-
-#endif // O3D_CONVERTER_CROSS_PRIMITIVE_STUB_H_
diff --git a/o3d/converter/cross/render_surface_stub.h b/o3d/converter/cross/render_surface_stub.h
deleted file mode 100644
index 4e68677..0000000
--- a/o3d/converter/cross/render_surface_stub.h
+++ /dev/null
@@ -1,75 +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 declarations for RenderSurfaceGL and
-// RenderDepthStencilSurfaceGL.
-
-#ifndef O3D_CONVERTER_CROSS_RENDER_SURFACE_STUB_H_
-#define O3D_CONVERTER_CROSS_RENDER_SURFACE_STUB_H_
-
-#include "core/cross/render_surface.h"
-#include "core/cross/texture.h"
-
-namespace o3d {
-
-class RenderSurfaceStub : public RenderSurface {
- public:
- typedef SmartPointer<RenderSurfaceStub> Ref;
-
- // Constructs a RenderSurfaceStub instance.
- // Parameters:
- // service_locator: Service locator for the instance.
- RenderSurfaceStub(ServiceLocator *service_locator,
- int width,
- int height)
- : RenderSurface(service_locator, width, height, NULL) {}
- virtual ~RenderSurfaceStub() {}
- private:
- DISALLOW_COPY_AND_ASSIGN(RenderSurfaceStub);
-};
-
-class RenderDepthStencilSurfaceStub : public RenderDepthStencilSurface {
- public:
- typedef SmartPointer<RenderDepthStencilSurfaceStub> Ref;
-
- RenderDepthStencilSurfaceStub(ServiceLocator *service_locator,
- int width,
- int height)
- : RenderDepthStencilSurface(service_locator, width, height) {}
- virtual ~RenderDepthStencilSurfaceStub() {}
- private:
- DISALLOW_COPY_AND_ASSIGN(RenderDepthStencilSurfaceStub);
-};
-
-} // namespace o3d
-
-#endif // O3D_CONVERTER_CROSS_RENDER_SURFACE_STUB_H_
diff --git a/o3d/converter/cross/renderer_stub.cc b/o3d/converter/cross/renderer_stub.cc
deleted file mode 100644
index 0155068..0000000
--- a/o3d/converter/cross/renderer_stub.cc
+++ /dev/null
@@ -1,214 +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 definition of abstract functions in the
-// cross platform API so that we can use it for serialization of the
-// scene graph on all systems without needing graphics.
-
-#include "converter/cross/renderer_stub.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/service_locator.h"
-#include "converter/cross/buffer_stub.h"
-#include "converter/cross/draw_element_stub.h"
-#include "converter/cross/effect_stub.h"
-#include "converter/cross/param_cache_stub.h"
-#include "converter/cross/primitive_stub.h"
-#include "converter/cross/render_surface_stub.h"
-#include "converter/cross/sampler_stub.h"
-#include "converter/cross/stream_bank_stub.h"
-#include "converter/cross/texture_stub.h"
-
-namespace o3d {
-
-Renderer* RendererStub::CreateDefault(ServiceLocator* service_locator) {
- return new RendererStub(service_locator);
-}
-
-RendererStub::RendererStub(ServiceLocator* service_locator)
- : Renderer(service_locator) {
-}
-
-Renderer::InitStatus RendererStub::InitPlatformSpecific(
- const DisplayWindow&, bool) {
- DCHECK(false);
- return SUCCESS;
-}
-
-void RendererStub::InitCommon() {
-}
-
-void RendererStub::UninitCommon() {
-}
-
-void RendererStub::Destroy(void) {
- DCHECK(false);
-}
-
-bool RendererStub::PlatformSpecificBeginDraw(void) {
- DCHECK(false);
- return true;
-}
-
-void RendererStub::PlatformSpecificEndDraw(void) {
- DCHECK(false);
-}
-
-bool RendererStub::PlatformSpecificStartRendering(void) {
- DCHECK(false);
- return true;
-}
-
-void RendererStub::PlatformSpecificFinishRendering(void) {
- DCHECK(false);
-}
-
-void RendererStub::Resize(int, int) {
- DCHECK(false);
-}
-
-void RendererStub::PlatformSpecificClear(
- const Float4 &, bool, float, bool, int, bool) {
- DCHECK(false);
-}
-
-void RendererStub::SetRenderSurfacesPlatformSpecific(
- const RenderSurface* surface,
- const RenderDepthStencilSurface* surface_depth) {
- DCHECK(false);
-}
-
-void RendererStub::SetBackBufferPlatformSpecific() {
- DCHECK(false);
-}
-
-void RendererStub::ApplyDirtyStates() {
- DCHECK(false);
-}
-
-Primitive::Ref RendererStub::CreatePrimitive(void) {
- return Primitive::Ref(new PrimitiveStub(service_locator()));
-}
-
-DrawElement::Ref RendererStub::CreateDrawElement(void) {
- return DrawElement::Ref(new DrawElementStub(service_locator()));
-}
-
-VertexBuffer::Ref RendererStub::CreateVertexBuffer(void) {
- return VertexBuffer::Ref(new VertexBufferStub(service_locator()));
-}
-
-IndexBuffer::Ref RendererStub::CreateIndexBuffer(void) {
- return IndexBuffer::Ref(new IndexBufferStub(service_locator()));
-}
-
-Effect::Ref RendererStub::CreateEffect(void) {
- return Effect::Ref(new EffectStub(service_locator()));
-}
-
-Sampler::Ref RendererStub::CreateSampler(void) {
- return Sampler::Ref(new SamplerStub(service_locator()));
-}
-
-Texture2D::Ref RendererStub::CreatePlatformSpecificTexture2D(
- int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- return Texture2D::Ref(new Texture2DStub(service_locator(),
- width,
- height,
- format,
- levels,
- enable_render_surfaces));
-}
-
-TextureCUBE::Ref RendererStub::CreatePlatformSpecificTextureCUBE(
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- return TextureCUBE::Ref(new TextureCUBEStub(service_locator(),
- edge_length,
- format,
- levels,
- enable_render_surfaces));
-}
-
-RenderDepthStencilSurface::Ref RendererStub::CreateDepthStencilSurface(
- int width,
- int height) {
- return RenderDepthStencilSurface::Ref(
- new RenderDepthStencilSurfaceStub(service_locator(), width, height));
-}
-
-StreamBank::Ref RendererStub::CreateStreamBank() {
- return StreamBank::Ref(new StreamBankStub(service_locator()));
-}
-
-ParamCache *RendererStub::CreatePlatformSpecificParamCache(void) {
- return new ParamCacheStub;
-}
-
-void RendererStub::SetViewportInPixels(int, int, int, int, float, float) {
- DCHECK(false);
-}
-
-bool RendererStub::GoFullscreen(const DisplayWindow& display,
- int mode_id) {
- return false;
-}
-
-bool RendererStub::CancelFullscreen(const DisplayWindow& display,
- int width, int height) {
- return false;
-}
-
-bool RendererStub::fullscreen() const { return false; }
-
-void RendererStub::GetDisplayModes(std::vector<DisplayMode> *modes) {
- modes->clear();
-}
-
-bool RendererStub::GetDisplayMode(int id, DisplayMode *mode) {
- return false;
-}
-
-void RendererStub::PlatformSpecificPresent(void) {
-}
-
-const int* RendererStub::GetRGBAUByteNSwizzleTable() {
- static int swizzle_table[] = { 0, 1, 2, 3, };
- return swizzle_table;
-}
-
-} // namespace o3d
diff --git a/o3d/converter/cross/renderer_stub.h b/o3d/converter/cross/renderer_stub.h
deleted file mode 100644
index 514349d..0000000
--- a/o3d/converter/cross/renderer_stub.h
+++ /dev/null
@@ -1,140 +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 declaration of functions needed to
-// instantiate a renderer from the core cross-platform API so that we
-// can use it for serialization of the scene graph on all systems
-// without needing graphics.
-
-#ifndef O3D_CONVERTER_CROSS_RENDERER_STUB_H_
-#define O3D_CONVERTER_CROSS_RENDERER_STUB_H_
-
-#include "core/cross/renderer.h"
-
-namespace o3d {
-
-// Please see core/cross/renderer.h for documentation of these
-// functions. With the exception of the "Create..." methods, these
-// are mostly just stubbed out here, and don't do anything.
-
-class RendererStub : public Renderer {
- public:
- static Renderer* CreateDefault(ServiceLocator* service_locator);
- virtual InitStatus InitPlatformSpecific(const DisplayWindow& display,
- bool off_screen);
- virtual void InitCommon();
- virtual void UninitCommon();
- virtual void Destroy();
- virtual void Resize(int width, int height);
- virtual Primitive::Ref CreatePrimitive();
- virtual DrawElement::Ref CreateDrawElement();
- virtual VertexBuffer::Ref CreateVertexBuffer();
- virtual IndexBuffer::Ref CreateIndexBuffer();
- virtual Effect::Ref CreateEffect();
- virtual Sampler::Ref CreateSampler();
- virtual RenderDepthStencilSurface::Ref CreateDepthStencilSurface(int width,
- int height);
- virtual StreamBank::Ref CreateStreamBank();
- ParamCache *CreatePlatformSpecificParamCache();
- virtual void SetViewportInPixels(int left,
- int top,
- int width,
- int height,
- float min_z,
- float max_z);
- virtual bool GoFullscreen(const DisplayWindow& display,
- int mode_id);
- virtual bool CancelFullscreen(const DisplayWindow& display,
- int width, int height);
- virtual bool fullscreen() const;
- virtual void GetDisplayModes(std::vector<DisplayMode> *modes);
- virtual bool GetDisplayMode(int id, DisplayMode *mode);
-
- // Overridden from Renderer.
- virtual const int* GetRGBAUByteNSwizzleTable();
-
- protected:
- explicit RendererStub(ServiceLocator* service_locator);
-
- // Overridden from Renderer.
- virtual bool PlatformSpecificBeginDraw();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificEndDraw();
-
- // Overridden from Renderer.
- virtual bool PlatformSpecificStartRendering();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificFinishRendering();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificPresent();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificClear(const Float4 &color,
- bool color_flag,
- float depth,
- bool depth_flag,
- int stencil,
- bool stencil_flag);
-
- // Overridden from Renderer.
- virtual void SetBackBufferPlatformSpecific();
-
- // Overridden from Renderer.
- virtual void ApplyDirtyStates();
-
- // Overridden from Renderer.
- virtual void SetRenderSurfacesPlatformSpecific(
- const RenderSurface* surface,
- const RenderDepthStencilSurface* depth_surface);
-
- // Overridden from Renderer.
- virtual Texture2D::Ref CreatePlatformSpecificTexture2D(
- int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
- // Overridden from Renderer.
- virtual TextureCUBE::Ref CreatePlatformSpecificTextureCUBE(
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-};
-
-} // namespace o3d
-
-#endif // O3D_CONVERTER_CROSS_RENDERER_STUB_H_
diff --git a/o3d/converter/cross/sampler_stub.h b/o3d/converter/cross/sampler_stub.h
deleted file mode 100644
index 61da44b..0000000
--- a/o3d/converter/cross/sampler_stub.h
+++ /dev/null
@@ -1,53 +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 class declaration for SamplerStub.
-
-#ifndef O3D_CONVERTER_CROSS_SAMPLER_STUB_H_
-#define O3D_CONVERTER_CROSS_SAMPLER_STUB_H_
-
-#include "core/cross/sampler.h"
-
-namespace o3d {
-
-// SamplerStub is an implementation of the Sampler object for the converter.
-class SamplerStub : public Sampler {
- public:
- explicit SamplerStub(ServiceLocator* service_locator)
- : Sampler(service_locator) {}
- virtual ~SamplerStub() {}
- private:
- DISALLOW_COPY_AND_ASSIGN(SamplerStub);
-};
-} // namespace o3d
-
-#endif // O3D_CONVERTER_CROSS_SAMPLER_STUB_H_
diff --git a/o3d/converter/cross/stream_bank_stub.h b/o3d/converter/cross/stream_bank_stub.h
deleted file mode 100644
index b137519..0000000
--- a/o3d/converter/cross/stream_bank_stub.h
+++ /dev/null
@@ -1,51 +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 declaration of the StreamBankGL class.
-
-#ifndef O3D_CONVERTER_CROSS_STREAM_BANK_STUB_H_
-#define O3D_CONVERTER_CROSS_STREAM_BANK_STUB_H_
-
-#include "core/cross/stream_bank.h"
-
-namespace o3d {
-
-// StreamBankStub is the Stub implementation of the StreamBank.
-class StreamBankStub : public StreamBank {
- public:
- explicit StreamBankStub(ServiceLocator* service_locator)
- : StreamBank(service_locator) {}
- virtual ~StreamBankStub() {}
-};
-} // o3d
-
-#endif // O3D_CONVERTER_CROSS_STREAM_BANK_STUB_H_
diff --git a/o3d/converter/cross/texture_stub.cc b/o3d/converter/cross/texture_stub.cc
deleted file mode 100644
index 4c91fb5..0000000
--- a/o3d/converter/cross/texture_stub.cc
+++ /dev/null
@@ -1,51 +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 "converter/cross/texture_stub.h"
-
-namespace o3d {
-
-namespace {
-
-Texture::RGBASwizzleIndices g_stub_abgr32f_swizzle_indices = {0, 1, 2, 3};
-
-} // anonymous namespace.
-
-const Texture::RGBASwizzleIndices& Texture2DStub::GetABGR32FSwizzleIndices() {
- return g_stub_abgr32f_swizzle_indices;
-}
-
-const Texture::RGBASwizzleIndices& TextureCUBEStub::GetABGR32FSwizzleIndices() {
- return g_stub_abgr32f_swizzle_indices;
-}
-
-} // namespace o3d
diff --git a/o3d/converter/cross/texture_stub.h b/o3d/converter/cross/texture_stub.h
deleted file mode 100644
index 5cb17d7..0000000
--- a/o3d/converter/cross/texture_stub.h
+++ /dev/null
@@ -1,161 +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 declarations for Texture2DStub and TextureCUBEStub.
-
-#ifndef O3D_CONVERTER_CROSS_TEXTURE_STUB_H_
-#define O3D_CONVERTER_CROSS_TEXTURE_STUB_H_
-
-#include "core/cross/bitmap.h"
-#include "core/cross/texture.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// Texture2DStub implements the stub Texture2D interface for the converter.
-class Texture2DStub : public Texture2D {
- public:
- typedef SmartPointer<Texture2DStub> Ref;
-
- Texture2DStub(ServiceLocator* service_locator,
- int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces)
- : Texture2D(service_locator,
- width,
- height,
- format,
- levels,
- enable_render_surfaces) {}
- virtual ~Texture2DStub() {}
-
- // Overridden from Texture2D
- virtual void SetRect(int level,
- unsigned left,
- unsigned top,
- unsigned width,
- unsigned height,
- const void* src_data,
- int src_pitch) {
- }
-
- // Returns the implementation-specific texture handle for this texture.
- void* GetTextureHandle() const {
- return NULL;
- }
-
- // Gets a RGBASwizzleIndices that contains a mapping from
- // RGBA to the internal format used by the rendering API.
- virtual const RGBASwizzleIndices& GetABGR32FSwizzleIndices();
-
- protected:
- // Overridden from Texture2D
- virtual bool PlatformSpecificLock(
- int level, void** texture_data, int* pitch, AccessMode mode) {
- return false;
- }
-
- // Overridden from Texture2D
- virtual bool PlatformSpecificUnlock(int level) { return true; }
-
- // Overridden from Texture2D
- virtual RenderSurface::Ref PlatformSpecificGetRenderSurface(int mip_level) {
- return RenderSurface::Ref(NULL);
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(Texture2DStub);
-};
-
-
-// TextureCUBEStub implements the TextureCUBE interface for the converter stub.
-class TextureCUBEStub : public TextureCUBE {
- public:
- typedef SmartPointer<TextureCUBEStub> Ref;
- TextureCUBEStub(ServiceLocator* service_locator,
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces)
- : TextureCUBE(service_locator,
- edge_length,
- format,
- levels,
- enable_render_surfaces) {}
- virtual ~TextureCUBEStub() {}
-
- // Overridden from TextureCUBE
- virtual void SetRect(CubeFace face,
- int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned width,
- unsigned height,
- const void* src_data,
- int src_pitch) {
- };
-
- // Returns the implementation-specific texture handle for this texture.
- void* GetTextureHandle() const {
- return NULL;
- }
-
- // Gets a RGBASwizzleIndices that contains a mapping from
- // RGBA to the internal format used by the rendering API.
- virtual const RGBASwizzleIndices& GetABGR32FSwizzleIndices();
-
- protected:
- // Overridden from TextureCUBE
- virtual bool PlatformSpecificLock(
- CubeFace face, int level, void** texture_data, int* pitch,
- AccessMode mode) {
- return false;
- }
-
- // Overridden from TextureCUBE
- virtual bool PlatformSpecificUnlock(CubeFace face, int level) { return true; }
-
- // Overridden from TextureCUBE
- virtual RenderSurface::Ref PlatformSpecificGetRenderSurface(CubeFace face,
- int mip_level) {
- return RenderSurface::Ref(NULL);
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(TextureCUBEStub);
-};
-
-} // namespace o3d
-
-#endif // O3D_CONVERTER_CROSS_TEXTURE_STUB_H_
diff --git a/o3d/converter/cross/verifier_main.cc b/o3d/converter/cross/verifier_main.cc
deleted file mode 100644
index 931fa39..0000000
--- a/o3d/converter/cross/verifier_main.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 the main routine for the converter that writes
-// out a scene graph as a JSON file.
-
-#include <string>
-#include <iostream>
-#include <vector>
-
-#include "base/at_exit.h"
-#include "base/file_path.h"
-#include "base/command_line.h"
-#include "converter/cross/converter.h"
-#include "utils/cross/file_path_utils.h"
-
-using std::string;
-using std::wstring;
-
-#if defined(OS_WIN)
-int wmain(int argc, wchar_t **argv) {
- // On Windows, CommandLine::Init ignores its arguments and uses
- // GetCommandLineW.
- CommandLine::Init(0, NULL);
-#endif
-#if defined(OS_LINUX)
-int main(int argc, char **argv) {
- CommandLine::Init(argc, argv);
-#endif
-#if defined(OS_MACOSX)
-// The "real" main on Mac is in mac/converter_main.mm, so we can get
-// memory pool initialization for Cocoa.
-int CrossMain(int argc, char**argv) {
- CommandLine::Init(argc, argv);
-#endif
- // Create an at_exit_manager so that base singletons will get
- // deleted properly.
- base::AtExitManager at_exit_manager;
- const CommandLine* command_line = CommandLine::ForCurrentProcess();
-
- FilePath in_filename, out_filename;
-
- std::vector<std::wstring> values = command_line->GetLooseValues();
- if (values.size() == 1) {
- in_filename = o3d::WideToFilePath(values[0]);
- } else if (values.size()== 2) {
- in_filename = o3d::WideToFilePath(values[0]);
- out_filename = o3d::WideToFilePath(values[1]);
- } else {
- std::cerr << "Usage: " << FilePath(argv[0]).BaseName().value()
- << " [--no-condition] <infile.fx> [<outfile.fx>]\n";
- return EXIT_FAILURE;
- }
-
- o3d::converter::Options options;
- options.condition = !command_line->HasSwitch("no-condition");
-
- if (!options.condition && !out_filename.empty()) {
- std::cerr << "Warning: Ignoring output filename because conditioning "
- << "has been turned off.\n";
- out_filename = FilePath();
- }
-
- o3d::String errors;
- bool result = o3d::converter::Verify(in_filename, out_filename, options,
- &errors);
- if (result) {
- std::cerr << "Shader in '" << o3d::FilePathToUTF8(in_filename).c_str()
- << "' has been validated." << std::endl;
- return EXIT_SUCCESS;
- } else {
- std::cerr << errors.c_str() << std::endl;
- std::cerr << "Shader in '" << o3d::FilePathToUTF8(in_filename).c_str()
- << "' FAILED to be validated." << std::endl;
- return EXIT_FAILURE;
- }
-}
diff --git a/o3d/converter/mac/converter_install_name.sh b/o3d/converter/mac/converter_install_name.sh
deleted file mode 100755
index d6af0b0..0000000
--- a/o3d/converter/mac/converter_install_name.sh
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/bin/sh
-
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-/usr/bin/install_name_tool -change \
- @executable_path/../Library/Frameworks/Cg.framework/Cg \
- @executable_path/Library/Frameworks/Cg.framework/Cg \
- "${BUILT_PRODUCTS_DIR}/${EXECUTABLE_PATH}"
diff --git a/o3d/converter/mac/converter_main.mm b/o3d/converter/mac/converter_main.mm
deleted file mode 100644
index 4e9a4af..0000000
--- a/o3d/converter/mac/converter_main.mm
+++ /dev/null
@@ -1,49 +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 main routine for the converter that writes
-// out a scene graph as a JSON file. Really, just a shell for the
-// common main routine in cross so we can get memory pool
-// initialization for Cocoa.
-
-#import <Cocoa/Cocoa.h>
-
-// Defined in converter/cross/converter_main.cc
-extern int CrossMain(int argc, char** argv);
-
-int main(int argc, char** argv) {
- // Make a pool to use for any Cocoa objects in the app.
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- int result = CrossMain(argc, argv);
- [pool release];
- return result;
-}
diff --git a/o3d/converter_edge/README.converter_edge b/o3d/converter_edge/README.converter_edge
deleted file mode 100644
index 17edbf4..0000000
--- a/o3d/converter_edge/README.converter_edge
+++ /dev/null
@@ -1,59 +0,0 @@
-The converter is a command line utility that will convert from COLLADA
-to the form that the sample JavaScript scene loader (in
-samples/o3djs/serialization.js) can read.
-
-It is able to read COLLADA files as either DAE text files (and
-associated asset files in subdirectories), or as part of a ZIP archive
-(or KMZ file). It outputs a gzip-compressed tar archive (.tgz) which
-contains a JSON file and any associated assets (textures, shaders,
-etc.) from the source COLLADA model. By default we don't use the .tgz
-extension, as it can cause problems with some webservers; we put .o3dtgz on
-instead.
-
-In order to run the converter on Windows, you need the DirectX SDK installed.
-Installing it requires administrator privileges. You can get it here:
-http://msdn.microsoft.com/en-us/library/bb219737(VS.85).aspx.
-
-The command line arguments are as follows:
-
-Usage: o3dConverter.exe [--base-path=<path>]
- [--up-axis=x,y,z]
- [--no-condition]
- [--pretty-print]
- [--sharp-edge-threshold=<threshold>]
- [--sharp-edge-color=r,g,b]
- <infile.dae> [ <outfile> ]
-
---base-path=<path>: This specifies the path elements to remove from
- the beginning of the filenames placed into the
- .o3dtgz file (to avoid including sensitive paths in
- the .o3dtgz file).
-
---up-axis=x,y,z: This specifies the up-axis for the resulting model,
- if you wish it to be different from the axis in the
- COLLADA file.
-
---pretty-print: This simply formats the JSON file in the resulting
- .o3dtgz file to be human readable, instead of compacted
- into one line.
-
---no-condition: This will prevent conditioning of the shaders from
- COLLADA form to the form expected by O3D. [This is
- useful only for pre-release data conditioned before
- the converter existed.]
-
---sharp-edge-threshold=<threshold>: Adds edges with normal angle
- larger than <threshold>.
-
---sharp-edge-color=r,g,b: Specify color of the additional edges,
- (value 0 to 1).Default value is 1,0,0.
-
-<infile.dae|infile.zip|infile.kmz>: This is the input file in one of
- ZIP, KMZ, or DAE formats. The
- DAE format expects to find assets
- relative to the .dae file.
-
-<outfile>: An optional argument giving the name of the
- gzip-compressed tar archive output file. By default
- this has the same basename as the input file, and has the extension
- .o3dtgz.
diff --git a/o3d/converter_edge/cross/buffer_stub.cc b/o3d/converter_edge/cross/buffer_stub.cc
deleted file mode 100644
index 1549939..0000000
--- a/o3d/converter_edge/cross/buffer_stub.cc
+++ /dev/null
@@ -1,87 +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 definition of the VertexBufferStub and
-// IndexBufferStub classes.
-
-#include "converter_edge/cross/buffer_stub.h"
-
-namespace o3d {
-
-bool VertexBufferStub::ConcreteAllocate(size_t size_in_bytes) {
- buffer_.reset(new int8[size_in_bytes]);
- return true;
-}
-
-void VertexBufferStub::ConcreteFree() {
- buffer_.reset();
-}
-
-bool VertexBufferStub::ConcreteLock(AccessMode access_mode,
- void** buffer_data) {
- *buffer_data = buffer_.get();
- DCHECK(locked_ == false);
- locked_ = true;
- return (buffer_.get() != NULL);
-}
-
-bool VertexBufferStub::ConcreteUnlock() {
- bool status = locked_;
- DCHECK(locked_ == true);
- locked_ = false;
- return status;
-}
-
-bool IndexBufferStub::ConcreteAllocate(size_t size_in_bytes) {
- buffer_.reset(new int8[size_in_bytes]);
- return true;
-}
-
-void IndexBufferStub::ConcreteFree() {
- buffer_.reset();
-}
-
-bool IndexBufferStub::ConcreteLock(AccessMode access_mode, void** buffer_data) {
- *buffer_data = buffer_.get();
- DCHECK(locked_ == false);
- locked_ = true;
- return (buffer_.get() != NULL);
-}
-
-bool IndexBufferStub::ConcreteUnlock() {
- bool status = locked_;
- DCHECK(locked_ == true);
- locked_ = false;
- return status;
-}
-
-} // end namespace o3d
diff --git a/o3d/converter_edge/cross/buffer_stub.h b/o3d/converter_edge/cross/buffer_stub.h
deleted file mode 100644
index d1da197..0000000
--- a/o3d/converter_edge/cross/buffer_stub.h
+++ /dev/null
@@ -1,112 +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 declaration of the platform specific
-// VertexBufferStub and IndexBufferStub objects used by O3D
-
-#ifndef O3D_CONVERTER_EDGE_CROSS_BUFFER_STUB_H_
-#define O3D_CONVERTER_EDGE_CROSS_BUFFER_STUB_H_
-
-#include "base/basictypes.h"
-#include "base/scoped_ptr.h"
-#include "core/cross/buffer.h"
-
-namespace o3d {
-
-// VertexBufferStub is a wrapper around an Stub Vertex Buffer Object (VBO).
-// The buffer starts out empty. Calling Allocate() will reserve video memory
-// for the buffer. Buffer contents are are updated by calling Lock() to get a
-// pointer to the memory allocated for the buffer, updating that data in place
-// and calling Unlock() to notify Stub that the edits are done.
-
-class VertexBufferStub : public VertexBuffer {
- public:
- explicit VertexBufferStub(ServiceLocator* service_locator)
- : VertexBuffer(service_locator), locked_(false) {}
- ~VertexBufferStub() {}
-
- protected:
- // Creates a Stub vertex buffer object of the specified size.
- virtual bool ConcreteAllocate(size_t size_in_bytes);
-
- // Frees the buffer.
- virtual void ConcreteFree();
-
- // Returns a pointer to the current contents of the buffer. A matching
- // call to Unlock is necessary to update the contents of the buffer.
- virtual bool ConcreteLock(AccessMode access_mode, void** buffer_data);
-
- // Notifies Stub that the buffer data has been updated. Unlock is only
- // valid if it follows a Lock operation.
- virtual bool ConcreteUnlock();
- private:
- scoped_array<int8> buffer_;
- bool locked_;
-
- DISALLOW_COPY_AND_ASSIGN(VertexBufferStub);
-};
-
-// IndexBufferStub is a wrapper around a Stub Index Buffer Object.
-// The buffer starts out empty. A call to Allocate() will create a stub
-// index buffer of the requested size. Updates the to the contents of the
-// buffer are done via the Lock/Unlock calls.
-class IndexBufferStub : public IndexBuffer {
- public:
- explicit IndexBufferStub(ServiceLocator* service_locator)
- : IndexBuffer(service_locator), locked_(false) {}
- ~IndexBufferStub() {}
-
- protected:
- // Creates a OpenGL index buffer of the specified size.
- virtual bool ConcreteAllocate(size_t size_in_bytes);
-
- // Frees the buffer.
- virtual void ConcreteFree();
-
- // Returns a pointer to the current contents of the buffer. After calling
- // Lock, the contents of the buffer can be updated in place.
- virtual bool ConcreteLock(AccessMode access_mode, void** buffer_data);
-
- // Notifies OpenGL that the buffer data has been updated. Unlock is only
- // valid if it follows a Lock operation.
- virtual bool ConcreteUnlock();
- private:
- scoped_array<int8> buffer_;
- bool locked_;
-
- DISALLOW_COPY_AND_ASSIGN(IndexBufferStub);
-};
-
-} // namespace o3d
-
-
-#endif // O3D_CONVERTER_EDGE_CROSS_BUFFER_STUB_H_
diff --git a/o3d/converter_edge/cross/converter.cc b/o3d/converter_edge/cross/converter.cc
deleted file mode 100644
index 8936213..0000000
--- a/o3d/converter_edge/cross/converter.cc
+++ /dev/null
@@ -1,639 +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 logic for converting the scene graph to a
-// JSON-encoded file that is stored in a zip archive.
-#include "converter_edge/cross/converter.h"
-
-#include <cmath>
-#include <map>
-#include <utility>
-
-#include "base/file_path.h"
-#include "base/file_util.h"
-#include "base/scoped_ptr.h"
-#include "core/cross/class_manager.h"
-#include "core/cross/client.h"
-#include "core/cross/client_info.h"
-#include "core/cross/effect.h"
-#include "core/cross/error.h"
-#include "core/cross/features.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/renderer.h"
-#include "core/cross/service_locator.h"
-#include "core/cross/transform.h"
-#include "core/cross/tree_traversal.h"
-#include "core/cross/types.h"
-#include "core/cross/primitive.cc"
-#include "import/cross/collada.h"
-#include "import/cross/collada_conditioner.h"
-#include "import/cross/file_output_stream_processor.h"
-#include "import/cross/targz_generator.h"
-#include "import/cross/archive_request.h"
-#include "serializer/cross/serializer.h"
-#include "utils/cross/file_path_utils.h"
-#include "utils/cross/json_writer.h"
-#include "utils/cross/string_writer.h"
-#include "utils/cross/temporary_file.h"
-
-namespace o3d {
-
-namespace {
-static const float kPi = 3.14159265358979f;
-static const float kEpsilon = 0.0001f;
-
-void AddBinaryElements(const Collada& collada,
- TarGzGenerator* archive_generator) {
- const ColladaDataMap& data_map(collada.original_data_map());
- std::vector<FilePath> paths = data_map.GetOriginalDataFilenames();
- for (std::vector<FilePath>::const_iterator iter = paths.begin();
- iter != paths.end();
- ++iter) {
- const std::string& data = data_map.GetOriginalData(*iter);
-
- archive_generator->AddFile(FilePathToUTF8(*iter), data.size());
- archive_generator->AddFileBytes(
- reinterpret_cast<const uint8*>(data.c_str()),
- data.length());
- }
-}
-} // end anonymous namespace
-
-namespace converter {
-// Constructor, make sure points order is unique.
-// If x-coordinates are the same, compare y-coordinate.
-// If y values are also the same, compare z.
-Edge::Edge(Point3 p1, Point3 p2) {
- bool isRightOrder = false;
- if (fabs(p1.getX() - p2.getX()) < kEpsilon) {
- if (fabs(p1.getY() - p2.getY()) < kEpsilon) {
- if (p1.getZ() < p2.getZ())
- isRightOrder = true;
- } else {
- if (p1.getY() < p2.getY())
- isRightOrder = true;
- }
- } else {
- if (p1.getX() < p2.getX())
- isRightOrder = true;
- }
- if (isRightOrder) {
- pts.push_back(p1);
- pts.push_back(p2);
- } else {
- pts.push_back(p2);
- pts.push_back(p1);
- }
-}
-
-// less than operator overload, necessary function for edge-triangle map.
-bool operator<(const Edge& left, const Edge& right) {
- // compare two edges by their actually coordinates, not indices.
- // Beceause two different indices may point to one actually coordinates.
- if (dist(left.pts[0], right.pts[0]) < kEpsilon) {
- if (fabs(left.pts[1].getX() - right.pts[1].getX()) < kEpsilon) {
- if (fabs(left.pts[1].getY() - right.pts[1].getY()) < kEpsilon) {
- return left.pts[1].getZ() < right.pts[1].getZ();
- }
- return left.pts[1].getY() < right.pts[1].getY();
- }
- return left.pts[1].getX() < right.pts[1].getX();
- } else {
- if (fabs(left.pts[0].getX() - right.pts[0].getX()) < kEpsilon) {
- if (fabs(left.pts[0].getY() - right.pts[0].getY()) < kEpsilon) {
- return left.pts[0].getZ() < right.pts[0].getZ();
- }
- return left.pts[0].getY() < right.pts[0].getY();
- }
- return left.pts[0].getX() < right.pts[0].getX();
- }
-}
-
-void CheckSharpEdge(const Edge& shared_edge,
- const std::vector<Triangle>& triangle_list,
- std::vector<Edge>* sharp_edges, float threshold) {
- for (size_t i = 0; i < triangle_list.size(); i++)
- for (size_t j = i + 1; j < triangle_list.size(); j++) {
- Triangle t1 = triangle_list[i];
- Triangle t2 = triangle_list[j];
- int same_vertices_count = 0;
- // Same triangle might be stored twice to represent inner and outer faces.
- // Check the order of indices of vertices to not mix inner and outer faces
- // togeter.
- std::vector<int> same_vertices_pos;
- for (int k = 0; k < 3; k++)
- for (int l = 0; l < 3; l++) {
- if (dist(t1.pts[k], t2.pts[l]) < kEpsilon) {
- same_vertices_count++;
- same_vertices_pos.push_back(k);
- same_vertices_pos.push_back(l);
- }
- }
- if (same_vertices_count != 2)
- continue;
- // check the order of positions to make sure triangles are on
- // the same face.
- int i1 = same_vertices_pos[2] - same_vertices_pos[0];
- int i2 = same_vertices_pos[3] - same_vertices_pos[1];
- // if triangles are on different faces.
- if (!(i1 * i2 == -1 || i1 * i2 == 2 || i1 * i2 == -4))
- continue;
-
- Vector3 v12 = t1.pts[1] - t1.pts[0];
- Vector3 v13 = t1.pts[2] - t1.pts[0];
- Vector3 n1 = cross(v12, v13);
- Vector3 v22 = t2.pts[1] - t2.pts[0];
- Vector3 v23 = t2.pts[2] - t2.pts[0];
- Vector3 n2 = cross(v22, v23);
- float iAngle = acos(dot(n1, n2) / (length(n1) * length(n2)));
- iAngle = iAngle * 180 / kPi;
- if (iAngle >= threshold) {
- sharp_edges->push_back(shared_edge);
- return;
- }
- }
-}
-
-// create a single color material and effect and attach it to
-// sharp edge primitive.
-Material* GetSingleColorMaterial(Pack::Ref pack, const Vector3& edge_color) {
- Material* singleColorMaterial = pack->Create<Material>();
- singleColorMaterial->set_name("singleColorMaterial");
- ParamString* lighting_param = singleColorMaterial->CreateParam<ParamString>(
- Collada::kLightingTypeParamName);
- lighting_param->set_value(Collada::kLightingTypeConstant);
- ParamFloat4* emissive_param = singleColorMaterial->CreateParam<ParamFloat4>(
- Collada::kMaterialParamNameEmissive);
- emissive_param->set_value(Float4(edge_color.getX(), edge_color.getY(),
- edge_color.getZ(), 1));
-
- return singleColorMaterial;
-}
-
-// insert edge-triangle pair to edge triangle map.
-void InsertEdgeTrianglePair(const Edge& edge, const Triangle& triangle,
- std::map<Edge, std::vector<Triangle>>* et_map) {
- std::map<Edge, std::vector<Triangle>>::iterator iter1 =
- et_map->find(edge);
- if (iter1 == et_map->end()) {
- std::vector<Triangle> same_edge_triangle_list;
- same_edge_triangle_list.push_back(triangle);
- et_map->insert(make_pair(edge, same_edge_triangle_list));
- } else {
- iter1->second.push_back(triangle);
- }
-}
-
-// Loads the Collada input file and writes it to the zipped JSON output file.
-bool Convert(const FilePath& in_filename,
- const FilePath& out_filename,
- const Options& options,
- String *error_messages) {
- // Create a service locator and renderer.
- ServiceLocator service_locator;
- EvaluationCounter evaluation_counter(&service_locator);
- ClassManager class_manager(&service_locator);
- ClientInfoManager client_info_manager(&service_locator);
- ObjectManager object_manager(&service_locator);
- Profiler profiler(&service_locator);
- ErrorStatus error_status(&service_locator);
- Features features(&service_locator);
-
- Collada::Init(&service_locator);
- features.Init("MaxCapabilities");
-
- // Collect error messages.
- ErrorCollector error_collector(&service_locator);
-
- scoped_ptr<Renderer> renderer(
- Renderer::CreateDefaultRenderer(&service_locator));
- renderer->InitCommon();
-
- Pack::Ref pack(object_manager.CreatePack());
- Transform* root = pack->Create<Transform>();
- root->set_name(String(Serializer::ROOT_PREFIX) + String("root"));
-
- // Setup a ParamFloat to be the source to all animations in this file.
- ParamObject* param_object = pack->Create<ParamObject>();
- // This is some arbitrary name
- param_object->set_name(O3D_STRING_CONSTANT("animSourceOwner"));
- ParamFloat* param_float = param_object->CreateParam<ParamFloat>("animSource");
-
- Collada::Options collada_options;
- collada_options.condition_document = options.condition;
- collada_options.keep_original_data = true;
- collada_options.base_path = options.base_path;
- collada_options.file_paths = options.file_paths;
- collada_options.up_axis = options.up_axis;
- Collada collada(pack.Get(), collada_options);
- bool result = collada.ImportFile(in_filename, root, param_float);
- if (!result || !error_collector.errors().empty()) {
- if (error_messages) {
- *error_messages += error_collector.errors();
- }
- return false;
- }
-
- // Remove the animation param_object (and indirectly the param_float)
- // if there is no animation.
- if (param_float->output_connections().empty()) {
- pack->RemoveObject(param_object);
- }
-
- // Add edges whose normals angle is larger than predefined threshold.
- if (options.enable_add_sharp_edge) {
- std::vector<Shape*> shapes = pack->GetByClass<Shape>();
- for (unsigned s = 0; s < shapes.size(); ++s) {
- Shape* shape = shapes[s];
- const ElementRefArray& elements = shape->GetElementRefs();
- for (unsigned e = 0; e < elements.size(); ++e) {
- if (elements[e]->IsA(Primitive::GetApparentClass())) {
- Primitive* primitive = down_cast<Primitive*>(elements[e].Get());
- // Get vertices and indices of this primitive.
- if (primitive->primitive_type() != Primitive::TRIANGLELIST)
- continue;
- FieldReadAccessor<Point3> vertices;
- FieldReadAccessorUnsignedInt indices;
- if (!GetVerticesAccessor(primitive, 0, &vertices))
- return false;
-
- unsigned int index_count;
- if (primitive->indexed()) {
- if (!Primitive::GetIndexCount(Primitive::TRIANGLELIST,
- primitive->number_primitives(),
- &index_count))
- continue;
-
- if (!GetIndicesAccessor(primitive, &indices,
- primitive->start_index(), index_count))
- continue;
- index_count = std::min(index_count, indices.max_index());
- } else {
- index_count = primitive->number_vertices();
- indices.InitializeJustCount(primitive->start_index(), index_count);
- }
- // If there are no vertices then exit early.
- if (vertices.max_index() == 0) {
- continue;
- }
- // generate triangle list.
- int prim = 0;
- std::vector<Triangle> triangle_list;
- std::vector<Point3> point_list;
- for (size_t i = 0; i < 48; i++) {
- point_list.push_back(vertices[i]);
- }
- for (unsigned int prim_base = 0; prim_base + 2 < index_count;
- prim_base += 3) {
- Triangle triangle(vertices[indices[prim_base + 0]],
- vertices[indices[prim_base + 1]],
- vertices[indices[prim_base + 2]]);
- triangle_list.push_back(triangle);
- }
- // build edge and triangle map.
- std::map<Edge, std::vector<Triangle>> edge_triangle_map;
- for (size_t i = 0; i < triangle_list.size(); i++) {
- Triangle triangle = triangle_list[i];
- Edge e1(triangle.pts[0], triangle.pts[1]);
- Edge e2(triangle.pts[1], triangle.pts[2]);
- Edge e3(triangle.pts[0], triangle.pts[2]);
- InsertEdgeTrianglePair(e1, triangle, &edge_triangle_map);
- InsertEdgeTrianglePair(e2, triangle, &edge_triangle_map);
- InsertEdgeTrianglePair(e3, triangle, &edge_triangle_map);
- }
- // go through the edge-triangle map.
- std::map<Edge, std::vector<Triangle>>::iterator iter;
- std::vector<Edge> sharp_edges;
- for (iter = edge_triangle_map.begin();
- iter != edge_triangle_map.end(); iter++) {
- if (iter->second.size() < 2)
- continue;
- CheckSharpEdge(iter->first, iter->second, &sharp_edges,
- options.sharp_edge_threshold);
- }
-
- if (sharp_edges.size() > 0) {
- Primitive* sharp_edge_primitive = pack->Create<Primitive>();
- sharp_edge_primitive->SetOwner(shape);
- sharp_edge_primitive->set_name("sharp_edge_primitive");
- StreamBank* stream_bank = pack->Create<StreamBank>();
-
- VertexBuffer* vertex_buffer = pack->Create<VertexBuffer>();
- vertex_buffer->set_name("sharp_edges_vertex_buffer");
- size_t num_vertices = sharp_edges.size() * 2;
-
- Field* field = vertex_buffer->CreateField(
- FloatField::GetApparentClass(), 3);
- if (!vertex_buffer->AllocateElements(static_cast<unsigned int>(
- sharp_edges.size() * 2))) {
- O3D_ERROR(&service_locator) << "Failed to allocate vertex buffer";
- return NULL;
- }
- scoped_array<float> values(new float[num_vertices * 3]);
- for (unsigned int i = 0; i < num_vertices; i++) {
- Point3 currentPoint;
- if (i % 2 == 0)
- currentPoint = sharp_edges[i / 2].pts[0];
- else
- currentPoint = sharp_edges[i / 2].pts[1];
- values[i * 3 + 0] = currentPoint.getX();
- values[i * 3 + 1] = currentPoint.getY();
- values[i * 3 + 2] = currentPoint.getZ();
- }
- field->SetFromFloats(&values[0], 3, 0,
- static_cast<unsigned int>(num_vertices));
- stream_bank->SetVertexStream(Stream::POSITION, 0, field, 0);
- stream_bank->set_name("sharp_edges_stream_bank");
-
- Material* material =
- GetSingleColorMaterial(pack, options.sharp_edge_color);
- sharp_edge_primitive->set_material(material);
- sharp_edge_primitive->set_primitive_type(Primitive::LINELIST);
- sharp_edge_primitive->set_number_vertices(static_cast<int>(
- sharp_edges.size() * 2));
- sharp_edge_primitive->set_number_primitives(static_cast<int>(
- sharp_edges.size()));
- sharp_edge_primitive->set_stream_bank(stream_bank);
- }
- }
- }
- }
- }
- // Mark all Samplers to use tri-linear filtering
- if (!options.keep_filters) {
- std::vector<Sampler*> samplers = pack->GetByClass<Sampler>();
- for (unsigned ii = 0; ii < samplers.size(); ++ii) {
- Sampler* sampler = samplers[ii];
- sampler->set_mag_filter(Sampler::LINEAR);
- sampler->set_min_filter(Sampler::LINEAR);
- sampler->set_mip_filter(Sampler::LINEAR);
- }
- }
-
- // Mark all Materials that are on Primitives that have no normals as constant.
- if (!options.keep_materials) {
- std::vector<Primitive*> primitives = pack->GetByClass<Primitive>();
- for (unsigned ii = 0; ii < primitives.size(); ++ii) {
- Primitive* primitive = primitives[ii];
- StreamBank* stream_bank = primitive->stream_bank();
- if (stream_bank && !stream_bank->GetVertexStream(Stream::NORMAL, 0)) {
- Material* material = primitive->material();
- if (material) {
- ParamString* lighting_param = material->GetParam<ParamString>(
- Collada::kLightingTypeParamName);
- if (lighting_param) {
- // If the lighting type is lambert, blinn, or phong
- // copy the diffuse color to the emissive since that's most likely
- // what the user wants to see.
- if (lighting_param->value().compare(
- Collada::kLightingTypeLambert) == 0 ||
- lighting_param->value().compare(
- Collada::kLightingTypeBlinn) == 0 ||
- lighting_param->value().compare(
- Collada::kLightingTypePhong) == 0) {
- // There's 4 cases: (to bad they are not the same names)
- // 1) Diffuse -> Emissive
- // 2) DiffuseSampler -> Emissive
- // 3) Diffuse -> EmissiveSampler
- // 4) DiffuseSampler -> EmissiveSampler
- ParamFloat4* diffuse_param = material->GetParam<ParamFloat4>(
- Collada::kMaterialParamNameDiffuse);
- ParamFloat4* emissive_param = material->GetParam<ParamFloat4>(
- Collada::kMaterialParamNameEmissive);
- ParamSampler* diffuse_sampler_param =
- material->GetParam<ParamSampler>(
- Collada::kMaterialParamNameDiffuseSampler);
- ParamSampler* emissive_sampler_param =
- material->GetParam<ParamSampler>(
- Collada::kMaterialParamNameEmissive);
- Param* source_param = diffuse_param ?
- static_cast<Param*>(diffuse_param) :
- static_cast<Param*>(diffuse_sampler_param);
- Param* destination_param = emissive_param ?
- static_cast<Param*>(emissive_param) :
- static_cast<Param*>(emissive_sampler_param);
- if (!source_param->IsA(destination_param->GetClass())) {
- // The params do not match type so we need to make the emissive
- // Param the same as the diffuse Param.
- material->RemoveParam(destination_param);
- destination_param = material->CreateParamByClass(
- diffuse_param ? Collada::kMaterialParamNameEmissive :
- Collada::kMaterialParamNameEmissiveSampler,
- source_param->GetClass());
- DCHECK(destination_param);
- }
- destination_param->CopyDataFromParam(source_param);
- }
- lighting_param->set_value(Collada::kLightingTypeConstant);
- }
- }
- }
- }
- }
-
- // Attempt to open the output file.
- FILE* out_file = file_util::OpenFile(out_filename, "wb");
- if (out_file == NULL) {
- O3D_ERROR(&service_locator) << "Could not open output file \""
- << FilePathToUTF8(out_filename).c_str()
- << "\"";
- if (error_messages) {
- *error_messages += error_collector.errors();
- }
- return false;
- }
-
- // Create an archive file and serialize the JSON scene graph and assets to it.
- FileOutputStreamProcessor stream_processor(out_file);
- TarGzGenerator archive_generator(&stream_processor);
-
- archive_generator.AddFile(ArchiveRequest::O3D_MARKER,
- ArchiveRequest::O3D_MARKER_CONTENT_LENGTH);
- archive_generator.AddFileBytes(
- reinterpret_cast<const uint8*>(ArchiveRequest::O3D_MARKER_CONTENT),
- ArchiveRequest::O3D_MARKER_CONTENT_LENGTH);
-
- // Serialize the created O3D scene graph to JSON.
- StringWriter out_writer(StringWriter::LF);
- JsonWriter json_writer(&out_writer, 2);
- if (!options.pretty_print) {
- json_writer.BeginCompacting();
- }
- Serializer serializer(&service_locator, &json_writer, &archive_generator);
- serializer.SerializePack(pack.Get());
- json_writer.Close();
- out_writer.Close();
- if (!options.pretty_print) {
- json_writer.EndCompacting();
- }
-
- String json = out_writer.ToString();
-
- archive_generator.AddFile("scene.json", json.length());
- archive_generator.AddFileBytes(reinterpret_cast<const uint8*>(json.c_str()),
- json.length());
-
- // Now add original data (e.g. compressed textures) collected during
- // the loading process.
- AddBinaryElements(collada, &archive_generator);
-
- archive_generator.Close(true);
-
- pack->Destroy();
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return true;
-}
-
-// Loads the input shader file and validates it.
-bool Verify(const FilePath& in_filename,
- const FilePath& out_filename,
- const Options& options,
- String* error_messages) {
- FilePath source_filename(in_filename);
- // Create a service locator and renderer.
- ServiceLocator service_locator;
- EvaluationCounter evaluation_counter(&service_locator);
- ClassManager class_manager(&service_locator);
- ObjectManager object_manager(&service_locator);
- Profiler profiler(&service_locator);
- ErrorStatus error_status(&service_locator);
-
- // Collect error messages.
- ErrorCollector error_collector(&service_locator);
-
- scoped_ptr<Renderer> renderer(
- Renderer::CreateDefaultRenderer(&service_locator));
- renderer->InitCommon();
-
- Pack::Ref pack(object_manager.CreatePack());
- Transform* root = pack->Create<Transform>();
- root->set_name(O3D_STRING_CONSTANT("root"));
-
- Collada::Options collada_options;
- collada_options.condition_document = options.condition;
- collada_options.keep_original_data = false;
- Collada collada(pack.Get(), collada_options);
-
- ColladaConditioner conditioner(&service_locator);
- String vertex_shader_entry_point;
- String fragment_shader_entry_point;
- TemporaryFile temp_file;
- if (options.condition) {
- if (!TemporaryFile::Create(&temp_file)) {
- O3D_ERROR(&service_locator) << "Could not create temporary file";
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return false;
- }
- SamplerStateList state_list;
- if (!conditioner.RewriteShaderFile(NULL,
- in_filename,
- temp_file.path(),
- &state_list,
- &vertex_shader_entry_point,
- &fragment_shader_entry_point)) {
- O3D_ERROR(&service_locator) << "Could not rewrite shader file";
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return false;
- }
- source_filename = temp_file.path();
- } else {
- source_filename = in_filename;
- }
-
- std::string shader_source_in;
- // Load file into memory
- if (!file_util::ReadFileToString(source_filename, &shader_source_in)) {
- O3D_ERROR(&service_locator) << "Could not read shader file "
- << FilePathToUTF8(source_filename).c_str();
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return false;
- }
-
- Effect::MatrixLoadOrder matrix_load_order;
- scoped_ptr<Effect> effect(pack->Create<Effect>());
- if (!effect->ValidateFX(shader_source_in,
- &vertex_shader_entry_point,
- &fragment_shader_entry_point,
- &matrix_load_order)) {
- O3D_ERROR(&service_locator) << "Could not validate shader file";
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return false;
- }
-
- if (!conditioner.CompileHLSL(shader_source_in,
- vertex_shader_entry_point,
- fragment_shader_entry_point)) {
- O3D_ERROR(&service_locator) << "Could not HLSL compile shader file";
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return false;
- }
-
- if (!conditioner.CompileCg(in_filename,
- shader_source_in,
- vertex_shader_entry_point,
- fragment_shader_entry_point)) {
- O3D_ERROR(&service_locator) << "Could not Cg compile shader file";
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return false;
- }
-
- // If we've validated the file, then we write out the conditioned
- // shader to the given output file, if there is one.
- if (options.condition && !out_filename.empty()) {
- if (file_util::WriteFile(out_filename, shader_source_in.c_str(),
- static_cast<int>(shader_source_in.size())) == -1) {
- O3D_ERROR(&service_locator) << "Warning: Could not write to output file '"
- << FilePathToUTF8(in_filename).c_str() << "'";
- }
- }
- if (error_messages) {
- *error_messages = error_collector.errors();
- }
- return true;
-}
-} // end namespace converter
-} // end namespace o3d
diff --git a/o3d/converter_edge/cross/converter.h b/o3d/converter_edge/cross/converter.h
deleted file mode 100644
index af360e5..0000000
--- a/o3d/converter_edge/cross/converter.h
+++ /dev/null
@@ -1,139 +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 declarations for the functions in the
-// O3D converter namespace. These functions do most of the actual
-// work of conditioning and packagaging a JSON file for use in
-// O3D.
-
-#ifndef O3D_CONVERTER_EDGE_CROSS_CONVERTER_H_
-#define O3D_CONVERTER_EDGE_CROSS_CONVERTER_H_
-
-#include <vector>
-#include <cmath>
-#include "base/file_path.h"
-#include "core/cross/types.h"
-#include "utils/cross/file_path_utils.h"
-
-namespace o3d {
-namespace converter {
-
-// Options struct for passing to the converter.
-struct Options {
- Options()
- : base_path(FilePath::kCurrentDirectory),
- condition(true),
- up_axis(0, 0, 0),
- pretty_print(false),
- keep_filters(false),
- keep_materials(false),
- enable_add_sharp_edge(false),
- sharp_edge_threshold(0),
- sharp_edge_color(1, 0, 0) {
- }
-
- // A list of paths to search for assets..
- std::vector<FilePath> file_paths;
-
- // The path to the "base" of the model path, from which all paths
- // are made relative. Defaults to the current directory.
- FilePath base_path;
-
- // Indicates if the converter should condition the input shaders or
- // not.
- bool condition;
-
- // The up axis of the output. The input will be converted to a new coordinate
- // system if it indicates a different up axis. Zero means no conversion.
- Vector3 up_axis;
-
- // This indicates whether or not the serialized JSON code should be
- // pretty-printed (formatted with spaces and newlines) or just
- // emitted as one huge one-line string. Defaults to false.
- bool pretty_print;
-
- // Tells the converter not to set all filters to tri-linear.
- bool keep_filters;
-
- // Tells the converter not to change materials to constant if they are used by
- // a mesh that has no normals.
- bool keep_materials;
-
- // Add edges with normal angle larger than soften_edge_threshold.
- bool enable_add_sharp_edge;
-
- // The threshold of normal angle of edge, if angle of certain edge is larger
- // than this threshold, it will be added into the output file.
- float sharp_edge_threshold;
-
- // The color of edges been added.
- Vector3 sharp_edge_color;
-};
-
-// Edge class is used in sharp edge detect process.
-// It stores two points in a specific order,
-// and it serves as key class in edge-triangle map.
-struct Edge {
- Edge(Point3 p1, Point3 p2);
- std::vector<Point3> pts;
-};
-
-// Triangle class is used in detect sharp edge process.
-struct Triangle {
- Triangle(Point3 p1, Point3 p2, Point3 p3) {
- pts.push_back(p1);
- pts.push_back(p2);
- pts.push_back(p3);
- }
- std::vector<Point3> pts;
-};
-
-// Converts the given file for use in O3D. This is done by
-// loading the input file, traversing the scene graph and serializing
-// what is found there.
-bool Convert(const FilePath& in_filename,
- const FilePath& out_filename,
- const Options& options,
- String* error_messages);
-
-// Verifies the given shader file as "valid". Returns true if input
-// shader file contains valid code (code that can be compiled
-// successfully).
-bool Verify(const FilePath& in_filename,
- const FilePath& out_filename,
- const Options& options,
- String* error_messages);
-
-} // namespace converter
-} // namespace o3d
-
-#endif // O3D_CONVERTER_EDGE_CROSS_CONVERTER_H_
diff --git a/o3d/converter_edge/cross/converter_main.cc b/o3d/converter_edge/cross/converter_main.cc
deleted file mode 100644
index eef1dec..0000000
--- a/o3d/converter_edge/cross/converter_main.cc
+++ /dev/null
@@ -1,180 +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 main routine for the converter that writes
-// out a scene graph as a JSON file.
-
-#include <string>
-#include <iostream>
-#include <vector>
-
-#include "base/at_exit.h"
-#include "base/command_line.h"
-#include "base/file_path.h"
-#include "base/string_util.h"
-#include "converter_edge/cross/converter.h"
-#include "utils/cross/file_path_utils.h"
-
-using std::string;
-using std::wstring;
-
-#if defined(OS_WIN)
-int wmain(int argc, wchar_t **argv) {
- // On Windows, CommandLine::Init ignores its arguments and uses
- // GetCommandLineW.
- CommandLine::Init(0, NULL);
-#endif
-#if defined(OS_LINUX)
-int main(int argc, char **argv) {
- CommandLine::Init(argc, argv);
-#endif
-#if defined(OS_MACOSX)
-// The "real" main on Mac is in mac/converter_main.mm, so we can get
-// memory pool initialization for Cocoa.
-int CrossMain(int argc, char**argv) {
- CommandLine::Init(argc, argv);
-#endif
- // Create an at_exit_manager so that base singletons will get
- // deleted properly.
- base::AtExitManager at_exit_manager;
- const CommandLine* command_line = CommandLine::ForCurrentProcess();
-
- FilePath in_filename, out_filename;
-
- std::vector<std::wstring> values = command_line->GetLooseValues();
- if (values.size() == 1) {
- // If we're only given one argument, then construct the output
- // filename by substituting the extension on the filename (if any)
- // with .o3dtgz.
- in_filename = o3d::WideToFilePath(values[0]);
- out_filename = in_filename.ReplaceExtension(FILE_PATH_LITERAL(".o3dtgz"));
- } else if (values.size()== 2) {
- in_filename = o3d::WideToFilePath(values[0]);
- out_filename = o3d::WideToFilePath(values[1]);
- } else {
- std::cerr << "Usage: " << argv[0]
- << " [ options ] <infile.dae> [ <outfile> ]\n";
- std::cerr
- << "--no-condition\n"
- << " Stops the converter from conditioning shaders.\n"
- << "--base-path=<path>\n"
- << " Sets the path to remove from URIs of external files\n"
- << "--asset-paths=<comma separted list of paths>\n"
- << " Sets the paths for finding textures and other external\n"
- << " files.\n"
- << "--up-axis=x,y,z\n"
- << " Converts the file to have this up axis.\n"
- << "--pretty-print\n"
- << " Makes the exported JSON easier to read.\n"
- << "--keep-filters\n"
- << " Stops the converter from forcing all texture samplers to use\n"
- << " tri-linear filtering.\n"
- << "--keep-materials\n"
- << " Stops the converter from changing materials to <constant> if\n"
- << " they are used by a mesh that has no normals.\n"
- << "--sharp-edge-threshold=<threshold>\n"
- << " Adds edges with normal angle larger than <threshold>.\n"
- << "--sharp-edge-color=r,g,b\n"
- << " Specify color of the additional edges, (value 0 to 1).\n"
- << " Default value is 1,0,0.\n";
- return EXIT_FAILURE;
- }
-
- o3d::converter::Options options;
- options.condition = !command_line->HasSwitch("no-condition");
- options.pretty_print = command_line->HasSwitch("pretty-print");
- if (command_line->HasSwitch("base-path")) {
- options.base_path = o3d::WideToFilePath(
- command_line->GetSwitchValue("base-path"));
- }
- if (command_line->HasSwitch("asset-paths")) {
- std::vector<std::wstring> paths;
- SplitString(command_line->GetSwitchValue("asset-paths"), ',', &paths);
- for (size_t ii = 0; ii < paths.size(); ++ii) {
- options.file_paths.push_back(o3d::WideToFilePath(paths[ii]));
- }
- }
- if (command_line->HasSwitch("up-axis")) {
- wstring up_axis_string = command_line->GetSwitchValue("up-axis");
- int x, y, z;
- if (swscanf(up_axis_string.c_str(), L"%d,%d,%d", &x, &y, &z) != 3) {
- std::cerr << "Invalid --up-axis value. Should be --up-axis=x,y,z\n";
- return EXIT_FAILURE;
- }
- options.up_axis = o3d::Vector3(static_cast<float>(x),
- static_cast<float>(y),
- static_cast<float>(z));
- }
- if (command_line->HasSwitch("sharp-edge-threshold")) {
- wstring soften_edge_string =
- command_line->GetSwitchValue("sharp-edge-threshold");
- float soft_threshold;
- if (swscanf(soften_edge_string.c_str(), L"%f", &soft_threshold) != 1) {
- std::cerr << "Invalid --sharp-edges-threshold value.\n";
- return EXIT_FAILURE;
- }
- options.enable_add_sharp_edge = true;
- options.sharp_edge_threshold = soft_threshold;
- }
- if (command_line->HasSwitch("sharp-edge-color")) {
- wstring edge_color_str =
- command_line->GetSwitchValue("sharp-edge-color");
- int r, g, b;
- if (swscanf(edge_color_str.c_str(), L"%d,%d,%d", &r, &g, &b) != 3) {
- std::cerr << "Invalid --sharp-edge-color value. Should be "
- << "--sharp-edge-color=r,g,b\n";
- return EXIT_FAILURE;
- }
- options.sharp_edge_color = o3d::Vector3(static_cast<float>(r),
- static_cast<float>(g),
- static_cast<float>(b));
- }
-
- o3d::String error_messages;
- bool result = o3d::converter::Convert(in_filename,
- out_filename,
- options,
- &error_messages);
- if (result) {
- std::cerr << "Converted '" << o3d::FilePathToUTF8(in_filename).c_str()
- << "' to '" << o3d::FilePathToUTF8(out_filename).c_str()
- << "'." << std::endl;
- return EXIT_SUCCESS;
- } else {
- std::cerr << error_messages.c_str() << std::endl;
- std::cerr << "FAILED to convert '"
- << o3d::FilePathToUTF8(in_filename).c_str()
- << "' to '" << o3d::FilePathToUTF8(out_filename).c_str()
- << "'." << std::endl;
- return EXIT_FAILURE;
- }
-}
diff --git a/o3d/converter_edge/cross/draw_element_stub.h b/o3d/converter_edge/cross/draw_element_stub.h
deleted file mode 100644
index 8ed3de6..0000000
--- a/o3d/converter_edge/cross/draw_element_stub.h
+++ /dev/null
@@ -1,58 +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 declaration of the DrawElementGL class.
-
-#ifndef O3D_CONVERTER_EDGE_CROSS_DRAW_ELEMENT_STUB_H_
-#define O3D_CONVERTER_EDGE_CROSS_DRAW_ELEMENT_STUB_H_
-
-#include "core/cross/draw_element.h"
-
-namespace o3d {
-
-class ServiceLocator;
-
-// DrawElementStub is the Stub implementation of the DrawElement. It
-// provides a place for the renderer to store platform specific cache
-// information.
-class DrawElementStub : public DrawElement {
- public:
- explicit DrawElementStub(ServiceLocator* service_locator)
- : DrawElement(service_locator) {}
- ~DrawElementStub() {}
-
- private:
- DISALLOW_COPY_AND_ASSIGN(DrawElementStub);
-};
-} // o3d
-
-#endif // O3D_CONVERTER_EDGE_CROSS_DRAW_ELEMENT_STUB_H_
diff --git a/o3d/converter_edge/cross/effect_stub.h b/o3d/converter_edge/cross/effect_stub.h
deleted file mode 100644
index dfe9a84..0000000
--- a/o3d/converter_edge/cross/effect_stub.h
+++ /dev/null
@@ -1,73 +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 declaration of the EffectGL class.
-
-#ifndef O3D_CONVERTER_EDGE_CROSS_EFFECT_STUB_H_
-#define O3D_CONVERTER_EDGE_CROSS_EFFECT_STUB_H_
-
-#include "core/cross/effect.h"
-
-namespace o3d {
-
-class ServiceLocator;
-
-// EffectStub is an implementation of the Effect object for the
-// converter. It provides the API for setting the vertex and fragment
-// shaders for the Effect using the Cg Runtime.
-class EffectStub : public Effect {
- public:
- explicit EffectStub(ServiceLocator* service_locator)
- : Effect(service_locator) {}
- virtual ~EffectStub() {}
-
- // Reads the vertex and fragment shaders from string in the FX format.
- // It returns true if the shaders were successfully compiled.
- virtual bool LoadFromFXString(const String& effect) { return true; }
-
- // Gets info about the parameters this effect needs.
- // Overriden from Effect.
- virtual void GetParameterInfo(EffectParameterInfoArray* info_array) {}
-
- // Gets info about the varying parameters this effects vertex shader needs.
- // Parameters:
- // info_array: EffectParameterInfoArray to receive info.
- virtual void GetStreamInfo(
- EffectStreamInfoArray* info_array) {
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(EffectStub);
-};
-} // namespace o3d
-
-#endif // O3D_CONVERTER_EDGE_CROSS_EFFECT_STUB_H_
diff --git a/o3d/converter_edge/cross/param_cache_stub.h b/o3d/converter_edge/cross/param_cache_stub.h
deleted file mode 100644
index 38efe6e..0000000
--- a/o3d/converter_edge/cross/param_cache_stub.h
+++ /dev/null
@@ -1,69 +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 declaration of the ParamCacheStub class.
-
-#ifndef O3D_CONVERTER_EDGE_CROSS_PARAM_CACHE_STUB_H_
-#define O3D_CONVERTER_EDGE_CROSS_PARAM_CACHE_STUB_H_
-
-#include "core/cross/param_cache.h"
-
-namespace o3d {
-
-class Effect;
-class DrawElement;
-class Element;
-class Material;
-class ParamObject;
-
-class ParamCacheStub : public ParamCache {
- public:
- ParamCacheStub() : ParamCache() {}
-
- // Overridden from ParamCache.
- virtual void UpdateCache(Effect* effect,
- DrawElement* draw_element,
- Element* element,
- Material* material,
- ParamObject* override) {}
-
- protected:
- // Overridden from ParamCache
- // Validates platform specific information about the effect.
- virtual bool ValidateEffect(Effect* effect) { return true; }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(ParamCacheStub);
-};
-} // o3d
-
-#endif // O3D_CONVERTER_EDGE_CROSS_PARAM_CACHE_STUB_H_
diff --git a/o3d/converter_edge/cross/primitive_stub.h b/o3d/converter_edge/cross/primitive_stub.h
deleted file mode 100644
index 5dd43ac..0000000
--- a/o3d/converter_edge/cross/primitive_stub.h
+++ /dev/null
@@ -1,71 +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 declaration of the PrimitiveStub class.
-
-#ifndef O3D_CONVERTER_EDGE_CROSS_PRIMITIVE_STUB_H_
-#define O3D_CONVERTER_EDGE_CROSS_PRIMITIVE_STUB_H_
-
-#include "core/cross/primitive.h"
-
-namespace o3d {
-
-class DrawElement;
-class Material;
-class ParamCache;
-class ParamObject;
-class Renderer;
-class ServiceLocator;
-
-// PrimitiveStub is the Stub implementation of the Primitive. It provides the
-// necessary interfaces for setting the geometry streams on the Primitive.
-class PrimitiveStub : public Primitive {
- public:
- explicit PrimitiveStub(ServiceLocator* service_locator)
- : Primitive(service_locator) {}
- virtual ~PrimitiveStub() {}
-
- // Overridden from Element
- // Renders this Element using the parameters from override first, followed by
- // the draw_element, followed by params on this Primitive and material.
- virtual void Render(Renderer* renderer,
- DrawElement* draw_element,
- Material* material,
- ParamObject* override,
- ParamCache* param_cache) {}
-
- private:
- DISALLOW_COPY_AND_ASSIGN(PrimitiveStub);
-};
-} // o3d
-
-#endif // O3D_CONVERTER_EDGE_CROSS_PRIMITIVE_STUB_H_
diff --git a/o3d/converter_edge/cross/render_surface_stub.h b/o3d/converter_edge/cross/render_surface_stub.h
deleted file mode 100644
index 8b018b4..0000000
--- a/o3d/converter_edge/cross/render_surface_stub.h
+++ /dev/null
@@ -1,75 +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 declarations for RenderSurfaceGL and
-// RenderDepthStencilSurfaceGL.
-
-#ifndef O3D_CONVERTER_EDGE_CROSS_RENDER_SURFACE_STUB_H_
-#define O3D_CONVERTER_EDGE_CROSS_RENDER_SURFACE_STUB_H_
-
-#include "core/cross/render_surface.h"
-#include "core/cross/texture.h"
-
-namespace o3d {
-
-class RenderSurfaceStub : public RenderSurface {
- public:
- typedef SmartPointer<RenderSurfaceStub> Ref;
-
- // Constructs a RenderSurfaceStub instance.
- // Parameters:
- // service_locator: Service locator for the instance.
- RenderSurfaceStub(ServiceLocator *service_locator,
- int width,
- int height)
- : RenderSurface(service_locator, width, height, NULL) {}
- virtual ~RenderSurfaceStub() {}
- private:
- DISALLOW_COPY_AND_ASSIGN(RenderSurfaceStub);
-};
-
-class RenderDepthStencilSurfaceStub : public RenderDepthStencilSurface {
- public:
- typedef SmartPointer<RenderDepthStencilSurfaceStub> Ref;
-
- RenderDepthStencilSurfaceStub(ServiceLocator *service_locator,
- int width,
- int height)
- : RenderDepthStencilSurface(service_locator, width, height) {}
- virtual ~RenderDepthStencilSurfaceStub() {}
- private:
- DISALLOW_COPY_AND_ASSIGN(RenderDepthStencilSurfaceStub);
-};
-
-} // namespace o3d
-
-#endif // O3D_CONVERTER_EDGE_CROSS_RENDER_SURFACE_STUB_H_
diff --git a/o3d/converter_edge/cross/renderer_stub.cc b/o3d/converter_edge/cross/renderer_stub.cc
deleted file mode 100644
index 1ede3d4..0000000
--- a/o3d/converter_edge/cross/renderer_stub.cc
+++ /dev/null
@@ -1,204 +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 definition of abstract functions in the
-// cross platform API so that we can use it for serialization of the
-// scene graph on all systems without needing graphics.
-
-#include "converter/cross/renderer_stub.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/service_locator.h"
-#include "converter_edge/cross/buffer_stub.h"
-#include "converter_edge/cross/draw_element_stub.h"
-#include "converter_edge/cross/effect_stub.h"
-#include "converter_edge/cross/param_cache_stub.h"
-#include "converter_edge/cross/primitive_stub.h"
-#include "converter_edge/cross/render_surface_stub.h"
-#include "converter_edge/cross/sampler_stub.h"
-#include "converter_edge/cross/stream_bank_stub.h"
-#include "converter_edge/cross/texture_stub.h"
-
-namespace o3d {
-
-Renderer* RendererStub::CreateDefault(ServiceLocator* service_locator) {
- return new RendererStub(service_locator);
-}
-
-RendererStub::RendererStub(ServiceLocator* service_locator)
- : Renderer(service_locator) {
-}
-
-Renderer::InitStatus RendererStub::InitPlatformSpecific(
- const DisplayWindow&, bool) {
- DCHECK(false);
- return SUCCESS;
-}
-
-void RendererStub::InitCommon() {
-}
-
-void RendererStub::UninitCommon() {
-}
-
-void RendererStub::Destroy(void) {
- DCHECK(false);
-}
-
-bool RendererStub::BeginDraw(void) {
- DCHECK(false);
- return true;
-}
-
-void RendererStub::EndDraw(void) {
- DCHECK(false);
-}
-
-bool RendererStub::StartRendering(void) {
- DCHECK(false);
- return true;
-}
-
-void RendererStub::FinishRendering(void) {
- DCHECK(false);
-}
-
-void RendererStub::Resize(int, int) {
- DCHECK(false);
-}
-
-void RendererStub::Clear(const Float4 &, bool, float, bool, int, bool) {
- DCHECK(false);
-}
-
-void RendererStub::RenderElement(Element *,
- DrawElement *,
- Material *,
- ParamObject *,
- ParamCache *) {
- DCHECK(false);
-}
-
-void RendererStub::SetRenderSurfacesPlatformSpecific(
- RenderSurface* surface,
- RenderDepthStencilSurface* surface_depth) {
- DCHECK(false);
-}
-
-void RendererStub::SetBackBufferPlatformSpecific() {
- DCHECK(false);
-}
-
-Primitive::Ref RendererStub::CreatePrimitive(void) {
- return Primitive::Ref(new PrimitiveStub(service_locator()));
-}
-
-DrawElement::Ref RendererStub::CreateDrawElement(void) {
- return DrawElement::Ref(new DrawElementStub(service_locator()));
-}
-
-VertexBuffer::Ref RendererStub::CreateVertexBuffer(void) {
- return VertexBuffer::Ref(new VertexBufferStub(service_locator()));
-}
-
-IndexBuffer::Ref RendererStub::CreateIndexBuffer(void) {
- return IndexBuffer::Ref(new IndexBufferStub(service_locator()));
-}
-
-Effect::Ref RendererStub::CreateEffect(void) {
- return Effect::Ref(new EffectStub(service_locator()));
-}
-
-Sampler::Ref RendererStub::CreateSampler(void) {
- return Sampler::Ref(new SamplerStub(service_locator()));
-}
-
-Texture2D::Ref RendererStub::CreatePlatformSpecificTexture2D(
- int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- return Texture2D::Ref(new Texture2DStub(service_locator(),
- width,
- height,
- format,
- levels,
- enable_render_surfaces));
-}
-
-TextureCUBE::Ref RendererStub::CreatePlatformSpecificTextureCUBE(
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- return TextureCUBE::Ref(new TextureCUBEStub(service_locator(),
- edge_length,
- format,
- levels,
- enable_render_surfaces));
-}
-
-RenderDepthStencilSurface::Ref RendererStub::CreateDepthStencilSurface(
- int width,
- int height) {
- return RenderDepthStencilSurface::Ref(
- new RenderDepthStencilSurfaceStub(service_locator(), width, height));
-}
-
-StreamBank::Ref RendererStub::CreateStreamBank() {
- return StreamBank::Ref(new StreamBankStub(service_locator()));
-}
-
-Bitmap::Ref RendererStub::TakeScreenshot() {
- return Bitmap::Ref();
-}
-
-ParamCache *RendererStub::CreatePlatformSpecificParamCache(void) {
- return new ParamCacheStub;
-}
-
-void RendererStub::SetViewportInPixels(int, int, int, int, float, float) {
- DCHECK(false);
-}
-
-const int* RendererStub::GetRGBAUByteNSwizzleTable() {
- static int swizzle_table[] = { 0, 1, 2, 3, };
- return swizzle_table;
-}
-
-// This is a factory function for creating Renderer objects. Since
-// we're implementing a stub renderer, we only ever return a stub renderer.
-Renderer* Renderer::CreateDefaultRenderer(ServiceLocator* service_locator) {
- return RendererStub::CreateDefault(service_locator);
-}
-
-} // namespace o3d
diff --git a/o3d/converter_edge/cross/renderer_stub.h b/o3d/converter_edge/cross/renderer_stub.h
deleted file mode 100644
index e924cf1..0000000
--- a/o3d/converter_edge/cross/renderer_stub.h
+++ /dev/null
@@ -1,123 +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 declaration of functions needed to
-// instantiate a renderer from the core cross-platform API so that we
-// can use it for serialization of the scene graph on all systems
-// without needing graphics.
-
-#ifndef O3D_CONVERTER_EDGE_CROSS_RENDERER_STUB_H_
-#define O3D_CONVERTER_EDGE_CROSS_RENDERER_STUB_H_
-
-#include "core/cross/renderer.h"
-
-namespace o3d {
-
-// Please see core/cross/renderer.h for documentation of these
-// functions. With the exception of the "Create..." methods, these
-// are mostly just stubbed out here, and don't do anything.
-
-class RendererStub : public Renderer {
- public:
- static Renderer* CreateDefault(ServiceLocator* service_locator);
- virtual InitStatus InitPlatformSpecific(const DisplayWindow& display,
- bool off_screen);
- virtual void InitCommon();
- virtual void UninitCommon();
- virtual void Destroy();
- virtual bool BeginDraw();
- virtual void EndDraw();
- virtual bool StartRendering();
- virtual void FinishRendering();
- virtual void Resize(int width, int height);
- virtual void Clear(const Float4 &color,
- bool color_flag,
- float depth,
- bool depth_flag,
- int stencil,
- bool stencil_flag);
- virtual void RenderElement(Element* element,
- DrawElement* draw_element,
- Material* material,
- ParamObject* override,
- ParamCache* param_cache);
- virtual Primitive::Ref CreatePrimitive();
- virtual DrawElement::Ref CreateDrawElement();
- virtual VertexBuffer::Ref CreateVertexBuffer();
- virtual IndexBuffer::Ref CreateIndexBuffer();
- virtual Effect::Ref CreateEffect();
- virtual Sampler::Ref CreateSampler();
- virtual RenderDepthStencilSurface::Ref CreateDepthStencilSurface(int width,
- int height);
- virtual StreamBank::Ref CreateStreamBank();
- virtual Bitmap::Ref TakeScreenshot();
- ParamCache *CreatePlatformSpecificParamCache();
- virtual void SetViewportInPixels(int left,
- int top,
- int width,
- int height,
- float min_z,
- float max_z);
-
- // Overridden from Renderer.
- virtual const int* GetRGBAUByteNSwizzleTable();
-
- protected:
- explicit RendererStub(ServiceLocator* service_locator);
-
- // Overridden from Renderer.
- virtual void SetBackBufferPlatformSpecific();
-
- // Overridden from Renderer.
- virtual void SetRenderSurfacesPlatformSpecific(
- RenderSurface* surface,
- RenderDepthStencilSurface* depth_surface);
-
- // Overridden from Renderer.
- virtual Texture2D::Ref CreatePlatformSpecificTexture2D(
- int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
- // Overridden from Renderer.
- virtual TextureCUBE::Ref CreatePlatformSpecificTextureCUBE(
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-};
-
-} // namespace o3d
-
-#endif // O3D_CONVERTER_EDGE_CROSS_RENDERER_STUB_H_
diff --git a/o3d/converter_edge/cross/sampler_stub.h b/o3d/converter_edge/cross/sampler_stub.h
deleted file mode 100644
index 1eb3fcc..0000000
--- a/o3d/converter_edge/cross/sampler_stub.h
+++ /dev/null
@@ -1,53 +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 class declaration for SamplerStub.
-
-#ifndef O3D_CONVERTER_EDGE_CROSS_SAMPLER_STUB_H_
-#define O3D_CONVERTER_EDGE_CROSS_SAMPLER_STUB_H_
-
-#include "core/cross/sampler.h"
-
-namespace o3d {
-
-// SamplerStub is an implementation of the Sampler object for the converter.
-class SamplerStub : public Sampler {
- public:
- explicit SamplerStub(ServiceLocator* service_locator)
- : Sampler(service_locator) {}
- virtual ~SamplerStub() {}
- private:
- DISALLOW_COPY_AND_ASSIGN(SamplerStub);
-};
-} // namespace o3d
-
-#endif // O3D_CONVERTER_EDGE_CROSS_SAMPLER_STUB_H_
diff --git a/o3d/converter_edge/cross/stream_bank_stub.h b/o3d/converter_edge/cross/stream_bank_stub.h
deleted file mode 100644
index 3ee9dc5..0000000
--- a/o3d/converter_edge/cross/stream_bank_stub.h
+++ /dev/null
@@ -1,51 +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 declaration of the StreamBankGL class.
-
-#ifndef O3D_CONVERTER_EDGE_CROSS_STREAM_BANK_STUB_H_
-#define O3D_CONVERTER_EDGE_CROSS_STREAM_BANK_STUB_H_
-
-#include "core/cross/stream_bank.h"
-
-namespace o3d {
-
-// StreamBankStub is the Stub implementation of the StreamBank.
-class StreamBankStub : public StreamBank {
- public:
- explicit StreamBankStub(ServiceLocator* service_locator)
- : StreamBank(service_locator) {}
- virtual ~StreamBankStub() {}
-};
-} // o3d
-
-#endif // O3D_CONVERTER_EDGE_CROSS_STREAM_BANK_STUB_H_
diff --git a/o3d/converter_edge/cross/texture_stub.cc b/o3d/converter_edge/cross/texture_stub.cc
deleted file mode 100644
index c287b58..0000000
--- a/o3d/converter_edge/cross/texture_stub.cc
+++ /dev/null
@@ -1,51 +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 "converter_edge/cross/texture_stub.h"
-
-namespace o3d {
-
-namespace {
-
-Texture::RGBASwizzleIndices g_stub_abgr32f_swizzle_indices = {0, 1, 2, 3};
-
-} // anonymous namespace.
-
-const Texture::RGBASwizzleIndices& Texture2DStub::GetABGR32FSwizzleIndices() {
- return g_stub_abgr32f_swizzle_indices;
-}
-
-const Texture::RGBASwizzleIndices& TextureCUBEStub::GetABGR32FSwizzleIndices() {
- return g_stub_abgr32f_swizzle_indices;
-}
-
-} // namespace o3d
diff --git a/o3d/converter_edge/cross/texture_stub.h b/o3d/converter_edge/cross/texture_stub.h
deleted file mode 100644
index 7b31a17..0000000
--- a/o3d/converter_edge/cross/texture_stub.h
+++ /dev/null
@@ -1,174 +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 declarations for Texture2DStub and TextureCUBEStub.
-
-#ifndef O3D_CONVERTER_EDGE_CROSS_TEXTURE_STUB_H_
-#define O3D_CONVERTER_EDGE_CROSS_TEXTURE_STUB_H_
-
-#include "core/cross/bitmap.h"
-#include "core/cross/texture.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// Texture2DStub implements the stub Texture2D interface for the converter.
-class Texture2DStub : public Texture2D {
- public:
- typedef SmartPointer<Texture2DStub> Ref;
-
- Texture2DStub(ServiceLocator* service_locator,
- int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces)
- : Texture2D(service_locator,
- width,
- height,
- format,
- levels,
- enable_render_surfaces) {}
- virtual ~Texture2DStub() {}
-
- // Overridden from Texture2D
- virtual void SetRect(int level,
- unsigned left,
- unsigned top,
- unsigned width,
- unsigned height,
- const void* src_data,
- int src_pitch) {
- }
-
- // Returns a RenderSurface object associated with a mip_level of a texture.
- // Parameters:
- // mip_level: [in] The mip-level of the surface to be returned.
- // pack: [in] The pack in which the surface will reside.
- // Returns:
- // Reference to the RenderSurface object.
- virtual RenderSurface::Ref GetRenderSurface(int mip_level, Pack *pack) {
- return RenderSurface::Ref(NULL);
- }
-
- // Returns the implementation-specific texture handle for this texture.
- void* GetTextureHandle() const {
- return NULL;
- }
-
- // Gets a RGBASwizzleIndices that contains a mapping from
- // RGBA to the internal format used by the rendering API.
- virtual const RGBASwizzleIndices& GetABGR32FSwizzleIndices();
-
- protected:
- // Locks the image buffer of a given mipmap level for writing from main
- // memory.
- virtual bool Lock(int level, void** texture_data, int* pitch) {
- return false;
- }
-
- // Unlocks this texture and returns it to Stub control.
- virtual bool Unlock(int level) { return true; }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(Texture2DStub);
-};
-
-
-// TextureCUBEStub implements the TextureCUBE interface for the converter stub.
-class TextureCUBEStub : public TextureCUBE {
- public:
- typedef SmartPointer<TextureCUBEStub> Ref;
- TextureCUBEStub(ServiceLocator* service_locator,
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces)
- : TextureCUBE(service_locator,
- edge_length,
- format,
- levels,
- enable_render_surfaces) {}
- virtual ~TextureCUBEStub() {}
-
- // Overridden from TextureCUBE
- virtual void SetRect(CubeFace face,
- int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned width,
- unsigned height,
- const void* src_data,
- int src_pitch) {
- };
-
- // Returns a RenderSurface object associated with a given cube face and
- // mip_level of a texture.
- // Parameters:
- // face: [in] The cube face from which to extract the surface.
- // mip_level: [in] The mip-level of the surface to be returned.
- // pack: [in] The pack in which the surface will reside.
- // Returns:
- // Reference to the RenderSurface object.
- virtual RenderSurface::Ref GetRenderSurface(CubeFace face,
- int level,
- Pack* pack) {
- return RenderSurface::Ref(NULL);
- }
-
- // Returns the implementation-specific texture handle for this texture.
- void* GetTextureHandle() const {
- return NULL;
- }
-
- // Gets a RGBASwizzleIndices that contains a mapping from
- // RGBA to the internal format used by the rendering API.
- virtual const RGBASwizzleIndices& GetABGR32FSwizzleIndices();
-
- protected:
- // Locks the image buffer of a given face and mipmap level for loading
- // from main memory.
- virtual bool Lock(
- CubeFace face, int level, void** texture_data, int* pitch) {
- return false;
- }
-
- // Unlocks the image buffer of a given face and mipmap level.
- virtual bool Unlock(CubeFace face, int level) { return true; }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(TextureCUBEStub);
-};
-
-} // namespace o3d
-
-#endif // O3D_CONVERTER_EDGE_CROSS_TEXTURE_STUB_H_
diff --git a/o3d/converter_edge/cross/verifier_main.cc b/o3d/converter_edge/cross/verifier_main.cc
deleted file mode 100644
index c401596..0000000
--- a/o3d/converter_edge/cross/verifier_main.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 the main routine for the converter that writes
-// out a scene graph as a JSON file.
-
-#include <string>
-#include <iostream>
-#include <vector>
-
-#include "base/at_exit.h"
-#include "base/file_path.h"
-#include "base/command_line.h"
-#include "converter_edge/cross/converter.h"
-#include "utils/cross/file_path_utils.h"
-
-using std::string;
-using std::wstring;
-
-#if defined(OS_WIN)
-int wmain(int argc, wchar_t **argv) {
- // On Windows, CommandLine::Init ignores its arguments and uses
- // GetCommandLineW.
- CommandLine::Init(0, NULL);
-#endif
-#if defined(OS_LINUX)
-int main(int argc, char **argv) {
- CommandLine::Init(argc, argv);
-#endif
-#if defined(OS_MACOSX)
-// The "real" main on Mac is in mac/converter_main.mm, so we can get
-// memory pool initialization for Cocoa.
-int CrossMain(int argc, char**argv) {
- CommandLine::Init(argc, argv);
-#endif
- // Create an at_exit_manager so that base singletons will get
- // deleted properly.
- base::AtExitManager at_exit_manager;
- const CommandLine* command_line = CommandLine::ForCurrentProcess();
-
- FilePath in_filename, out_filename;
-
- std::vector<std::wstring> values = command_line->GetLooseValues();
- if (values.size() == 1) {
- in_filename = o3d::WideToFilePath(values[0]);
- } else if (values.size()== 2) {
- in_filename = o3d::WideToFilePath(values[0]);
- out_filename = o3d::WideToFilePath(values[1]);
- } else {
- std::cerr << "Usage: " << FilePath(argv[0]).BaseName().value()
- << " [--no-condition] <infile.fx> [<outfile.fx>]\n";
- return EXIT_FAILURE;
- }
-
- o3d::converter::Options options;
- options.condition = !command_line->HasSwitch("no-condition");
-
- if (!options.condition && !out_filename.empty()) {
- std::cerr << "Warning: Ignoring output filename because conditioning "
- << "has been turned off.\n";
- out_filename = FilePath();
- }
-
- o3d::String errors;
- bool result = o3d::converter::Verify(in_filename, out_filename, options,
- &errors);
- if (result) {
- std::cerr << "Shader in '" << o3d::FilePathToUTF8(in_filename).c_str()
- << "' has been validated." << std::endl;
- return EXIT_SUCCESS;
- } else {
- std::cerr << errors.c_str() << std::endl;
- std::cerr << "Shader in '" << o3d::FilePathToUTF8(in_filename).c_str()
- << "' FAILED to be validated." << std::endl;
- return EXIT_FAILURE;
- }
-}
diff --git a/o3d/converter_edge/mac/converter_main.mm b/o3d/converter_edge/mac/converter_main.mm
deleted file mode 100644
index 4e9a4af..0000000
--- a/o3d/converter_edge/mac/converter_main.mm
+++ /dev/null
@@ -1,49 +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 main routine for the converter that writes
-// out a scene graph as a JSON file. Really, just a shell for the
-// common main routine in cross so we can get memory pool
-// initialization for Cocoa.
-
-#import <Cocoa/Cocoa.h>
-
-// Defined in converter/cross/converter_main.cc
-extern int CrossMain(int argc, char** argv);
-
-int main(int argc, char** argv) {
- // Make a pool to use for any Cocoa objects in the app.
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- int result = CrossMain(argc, argv);
- [pool release];
- return result;
-}
diff --git a/o3d/core/core.gyp b/o3d/core/core.gyp
deleted file mode 100644
index b3e1c9e..0000000
--- a/o3d/core/core.gyp
+++ /dev/null
@@ -1,560 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- },
- 'includes': [
- '../build/branding.gypi',
- '../build/common.gypi',
- '../build/version.gypi',
- ],
- 'target_defaults': {
- 'include_dirs': [
- # The internal dir is first so that headers in internal can replace those
- # in external
- '../../<(internaldir)',
- '..',
- '../..',
- '../../<(gtestdir)',
- '../../<(nacldir)',
- ],
- 'defines': [
- 'O3D_PLUGIN_VERSION="<(plugin_version)"',
- 'O3D_PLUGIN_EXTRAS_DIRECTORY="<(plugin_extras_directory)"',
- ],
- 'conditions': [
- ['OS == "win"',
- {
- 'msvs_settings': {
- 'VCCLCompilerTool': {
- 'ForcedIncludeFiles':
- 'core/cross/precompile.h',
- },
- },
- },
- ],
- ['renderer == "d3d9" and OS == "win"',
- {
- 'msvs_system_include_dirs': [
- '$(DXSDK_DIR)/Include',
- ],
- }
- ],
- ['OS == "linux"',
- {
- 'cflags': [
- '-include',
- 'core/cross/precompile.h',
- ],
- },
- ],
- ['renderer == "gl"',
- {
- 'include_dirs': [
- '../../<(glewdir)/include',
- '../../<(cgdir)/include',
- ],
- },
- ],
- ['renderer == "gles2"',
- {
- 'include_dirs': [
- '../../<(glewdir)/include',
- ],
- },
- ],
- ['disable_fbo == 1', {
- 'defines': [
- 'DISABLE_FBO',
- ],
- }],
- ],
- },
- 'targets': [
- {
- 'target_name': 'o3dCore',
- 'type': 'static_library',
- 'dependencies': [
- '../../<(jpegdir)/libjpeg.gyp:libjpeg',
- '../../<(pngdir)/libpng.gyp:libpng',
- '../../<(zlibdir)/zlib.gyp:zlib',
- '../../skia/skia.gyp:skia',
- '../third_party/glu/libtess.gyp:libtess',
- ],
- 'sources': [
- 'cross/bitmap.cc',
- 'cross/bitmap.h',
- 'cross/bitmap_dds.cc',
- 'cross/bitmap_jpg.cc',
- 'cross/bitmap_png.cc',
- 'cross/bitmap_tga.cc',
- 'cross/bounding_box.cc',
- 'cross/bounding_box.h',
- 'cross/buffer.cc',
- 'cross/buffer.h',
- 'cross/callback.h',
- 'cross/canvas.cc',
- 'cross/canvas.h',
- 'cross/canvas_paint.cc',
- 'cross/canvas_paint.h',
- 'cross/canvas_shader.cc',
- 'cross/canvas_shader.h',
- 'cross/canvas_utils.h',
- 'cross/class_manager.cc',
- 'cross/class_manager.h',
- 'cross/clear_buffer.cc',
- 'cross/clear_buffer.h',
- 'cross/client.cc',
- 'cross/client.h',
- 'cross/client_info.cc',
- 'cross/client_info.h',
- 'cross/core_metrics.cc',
- 'cross/core_metrics.h',
- 'cross/counter.cc',
- 'cross/counter.h',
- 'cross/counter_manager.cc',
- 'cross/counter_manager.h',
- 'cross/cursor.h',
- 'cross/curve.cc',
- 'cross/curve.h',
- 'cross/ddsurfacedesc.h',
- 'cross/display_mode.h',
- 'cross/display_window.h',
- 'cross/draw_context.cc',
- 'cross/draw_context.h',
- 'cross/draw_element.cc',
- 'cross/draw_element.h',
- 'cross/draw_list.cc',
- 'cross/draw_list.h',
- 'cross/draw_list_manager.cc',
- 'cross/draw_list_manager.h',
- 'cross/draw_pass.cc',
- 'cross/draw_pass.h',
- 'cross/effect.cc',
- 'cross/effect.h',
- 'cross/element.cc',
- 'cross/element.h',
- 'cross/error.h',
- 'cross/error_status.cc',
- 'cross/error_status.h',
- 'cross/error_stream_manager.cc',
- 'cross/error_stream_manager.h',
- 'cross/evaluation_counter.cc',
- 'cross/evaluation_counter.h',
- 'cross/event.cc',
- 'cross/event.h',
- 'cross/event_callback.h',
- 'cross/event_manager.cc',
- 'cross/event_manager.h',
- 'cross/fake_vertex_source.cc',
- 'cross/fake_vertex_source.h',
- 'cross/features.cc',
- 'cross/features.h',
- 'cross/field.cc',
- 'cross/field.h',
- 'cross/file_request.cc',
- 'cross/file_request.h',
- 'cross/float_n.h',
- 'cross/function.cc',
- 'cross/function.h',
- 'cross/iclass_manager.cc',
- 'cross/iclass_manager.h',
- 'cross/id_manager.cc',
- 'cross/id_manager.h',
- 'cross/ierror_status.cc',
- 'cross/ierror_status.h',
- 'cross/image_utils.cc',
- 'cross/imain_thread_task_poster.cc',
- 'cross/imain_thread_task_poster.h',
- 'cross/install_check.h',
- 'cross/lost_resource_callback.h',
- 'cross/material.cc',
- 'cross/material.h',
- 'cross/math_types.h',
- 'cross/math_utilities.cc',
- 'cross/math_utilities.h',
- 'cross/matrix4_axis_rotation.cc',
- 'cross/matrix4_axis_rotation.h',
- 'cross/matrix4_composition.cc',
- 'cross/matrix4_composition.h',
- 'cross/matrix4_scale.cc',
- 'cross/matrix4_scale.h',
- 'cross/matrix4_translation.cc',
- 'cross/matrix4_translation.h',
- 'cross/message_commands.cc',
- 'cross/message_commands.h',
- 'cross/message_queue.cc',
- 'cross/message_queue.h',
- 'cross/named_object.cc',
- 'cross/named_object.h',
- 'cross/object_base.cc',
- 'cross/object_base.h',
- 'cross/object_manager.cc',
- 'cross/object_manager.h',
- 'cross/pack.cc',
- 'cross/pack.h',
- 'cross/param.cc',
- 'cross/param.h',
- 'cross/param_array.cc',
- 'cross/param_array.h',
- 'cross/param_cache.cc',
- 'cross/param_cache.h',
- 'cross/param_object.cc',
- 'cross/param_object.h',
- 'cross/param_operation.cc',
- 'cross/param_operation.h',
- 'cross/performance_timer.h',
- 'cross/precompile.cc',
- 'cross/precompile.h',
- 'cross/primitive.cc',
- 'cross/primitive.h',
- 'cross/processed_path.cc',
- 'cross/processed_path.h',
- 'cross/profiler.cc',
- 'cross/profiler.h',
- 'cross/ray_intersection_info.cc',
- 'cross/ray_intersection_info.h',
- 'cross/render_context.cc',
- 'cross/render_context.h',
- 'cross/render_event.h',
- 'cross/render_node.cc',
- 'cross/render_node.h',
- 'cross/render_surface.cc',
- 'cross/render_surface.h',
- 'cross/render_surface_set.cc',
- 'cross/render_surface_set.h',
- 'cross/renderer.cc',
- 'cross/renderer.h',
- 'cross/renderer_platform.h',
- 'cross/sampler.cc',
- 'cross/sampler.h',
- 'cross/semantic_manager.cc',
- 'cross/semantic_manager.h',
- 'cross/service_dependency.h',
- 'cross/service_implementation.h',
- 'cross/service_interface_traits.h',
- 'cross/service_locator.cc',
- 'cross/service_locator.h',
- 'cross/shape.cc',
- 'cross/shape.h',
- 'cross/skin.cc',
- 'cross/skin.h',
- 'cross/smart_ptr.h',
- 'cross/standard_param.cc',
- 'cross/standard_param.h',
- 'cross/state.cc',
- 'cross/state.h',
- 'cross/state_set.cc',
- 'cross/state_set.h',
- 'cross/stream.cc',
- 'cross/stream.h',
- 'cross/stream_bank.cc',
- 'cross/stream_bank.h',
- 'cross/texture.cc',
- 'cross/texture.h',
- 'cross/texture_base.cc',
- 'cross/texture_base.h',
- 'cross/tick_event.h',
- 'cross/timer.cc',
- 'cross/timer.h',
- 'cross/timingtable.h',
- 'cross/transform.cc',
- 'cross/transform.h',
- 'cross/transformation_context.cc',
- 'cross/transformation_context.h',
- 'cross/tree_traversal.cc',
- 'cross/tree_traversal.h',
- 'cross/types.h',
- 'cross/vector_map.h',
- 'cross/vertex_source.cc',
- 'cross/vertex_source.h',
- 'cross/viewport.cc',
- 'cross/viewport.h',
- 'cross/visitor_base.h',
- 'cross/weak_ptr.h',
- 'cross/gpu2d/arena.h',
- 'cross/gpu2d/cubic_classifier.cc',
- 'cross/gpu2d/cubic_classifier.h',
- 'cross/gpu2d/cubic_math_utils.cc',
- 'cross/gpu2d/cubic_math_utils.h',
- 'cross/gpu2d/cubic_texture_coords.cc',
- 'cross/gpu2d/cubic_texture_coords.h',
- 'cross/gpu2d/interval_tree.h',
- 'cross/gpu2d/local_triangulator.cc',
- 'cross/gpu2d/local_triangulator.h',
- 'cross/gpu2d/path_cache.cc',
- 'cross/gpu2d/path_cache.h',
- 'cross/gpu2d/path_processor.cc',
- 'cross/gpu2d/path_processor.h',
- 'cross/gpu2d/red_black_tree.h',
- ],
- 'direct_dependent_settings': {
- 'include_dirs': [
- '..',
- ],
- },
- 'conditions': [
- ['OS == "win"',
- {
- 'sources': [
- 'win/display_window_win.h',
- 'win/performance_timer.cc',
- ],
- 'direct_dependent_settings': {
- 'include_dirs': [
- 'win',
- ],
- },
- },
- ],
- ['renderer == "gl"',
- {
- 'dependencies': [
- '../build/libs.gyp:cg_libs',
- '../build/libs.gyp:gl_libs',
- ],
- },
- ],
- ['renderer == "gles2"',
- {
- 'dependencies': [
- '../build/libs.gyp:gles2_libs',
- ],
- },
- ],
- ['OS == "linux"',
- {
- 'sources': [
- 'linux/display_window_linux.h',
- 'linux/performance_timer.cc',
- ],
- 'direct_dependent_settings': {
- 'include_dirs': [
- 'linux',
- ],
- },
- },
- ],
- ['OS == "mac"',
- {
- 'sources': [
- 'mac/display_window_mac.h',
- 'mac/performance_timer.cc',
- ],
- 'direct_dependent_settings': {
- 'include_dirs': [
- 'mac',
- ],
- },
- 'xcode_settings': {
- 'GCC_PREFIX_HEADER': 'cross/precompile.h',
- 'GCC_PFE_FILE_C_DIALECTS': 'c++',
- },
- },
- ],
- ],
- },
- {
- 'target_name': 'o3dCorePlatform',
- 'type': 'static_library',
- 'dependencies': [
- '../../skia/skia.gyp:skia',
- '../build/libs.gyp:cairo_libs',
- ],
- 'sources': [
- 'cross/cairo/install_check.cc',
- 'cross/cairo/layer.cc',
- 'cross/cairo/layer.h',
- 'cross/cairo/pattern.cc',
- 'cross/cairo/pattern.h',
- 'cross/cairo/renderer_cairo.cc',
- 'cross/cairo/renderer_cairo.h',
- 'cross/cairo/texture_cairo.cc',
- 'cross/cairo/texture_cairo.h',
- ],
- 'conditions': [
- ['OS == "mac"',
- {
- 'xcode_settings': {
- 'GCC_PREFIX_HEADER': 'cross/precompile.h',
- 'GCC_PFE_FILE_C_DIALECTS': 'c++',
- },
- },
- ],
- ['renderer == "gl"',
- {
- 'sources': [
- 'cross/gl/buffer_gl.cc',
- 'cross/gl/buffer_gl.h',
- 'cross/gl/draw_element_gl.cc',
- 'cross/gl/draw_element_gl.h',
- 'cross/gl/effect_gl.cc',
- 'cross/gl/effect_gl.h',
- 'cross/gl/install_check.cc',
- 'cross/gl/param_cache_gl.cc',
- 'cross/gl/param_cache_gl.h',
- 'cross/gl/primitive_gl.cc',
- 'cross/gl/primitive_gl.h',
- 'cross/gl/render_surface_gl.cc',
- 'cross/gl/render_surface_gl.h',
- 'cross/gl/renderer_gl.cc',
- 'cross/gl/renderer_gl.h',
- 'cross/gl/sampler_gl.cc',
- 'cross/gl/sampler_gl.h',
- 'cross/gl/stream_bank_gl.cc',
- 'cross/gl/stream_bank_gl.h',
- 'cross/gl/texture_gl.cc',
- 'cross/gl/texture_gl.h',
- 'cross/gl/utils_gl-inl.h',
- 'cross/gl/utils_gl.cc',
- 'cross/gl/utils_gl.h',
- ],
- 'dependencies': [
- '../build/libs.gyp:gl_libs',
- ],
- },
- ],
- ['renderer == "gles2"',
- {
- 'sources': [
- 'cross/gles2/buffer_gles2.cc',
- 'cross/gles2/buffer_gles2.h',
- 'cross/gles2/draw_element_gles2.cc',
- 'cross/gles2/draw_element_gles2.h',
- 'cross/gles2/effect_gles2.cc',
- 'cross/gles2/effect_gles2.h',
- 'cross/gles2/install_check.cc',
- 'cross/gles2/param_cache_gles2.cc',
- 'cross/gles2/param_cache_gles2.h',
- 'cross/gles2/primitive_gles2.cc',
- 'cross/gles2/primitive_gles2.h',
- 'cross/gles2/render_surface_gles2.cc',
- 'cross/gles2/render_surface_gles2.h',
- 'cross/gles2/renderer_gles2.cc',
- 'cross/gles2/renderer_gles2.h',
- 'cross/gles2/sampler_gles2.cc',
- 'cross/gles2/sampler_gles2.h',
- 'cross/gles2/stream_bank_gles2.cc',
- 'cross/gles2/stream_bank_gles2.h',
- 'cross/gles2/texture_gles2.cc',
- 'cross/gles2/texture_gles2.h',
- 'cross/gles2/utils_gles2-inl.h',
- 'cross/gles2/utils_gles2.cc',
- 'cross/gles2/utils_gles2.h',
- ],
- 'dependencies': [
- '../build/libs.gyp:gles2_libs',
- ],
- },
- ],
- ['renderer == "d3d9" and OS == "win"',
- {
- 'sources': [
- 'win/d3d9/buffer_d3d9.cc',
- 'win/d3d9/buffer_d3d9.h',
- 'win/d3d9/d3d_entry_points.h',
- 'win/d3d9/draw_element_d3d9.cc',
- 'win/d3d9/draw_element_d3d9.h',
- 'win/d3d9/effect_d3d9.cc',
- 'win/d3d9/effect_d3d9.h',
- 'win/d3d9/install_check.cc',
- 'win/d3d9/param_cache_d3d9.cc',
- 'win/d3d9/param_cache_d3d9.h',
- 'win/d3d9/primitive_d3d9.cc',
- 'win/d3d9/primitive_d3d9.h',
- 'win/d3d9/render_surface_d3d9.cc',
- 'win/d3d9/render_surface_d3d9.h',
- 'win/d3d9/renderer_d3d9.cc',
- 'win/d3d9/renderer_d3d9.h',
- 'win/d3d9/sampler_d3d9.cc',
- 'win/d3d9/sampler_d3d9.h',
- 'win/d3d9/stream_bank_d3d9.cc',
- 'win/d3d9/stream_bank_d3d9.h',
- 'win/d3d9/texture_d3d9.cc',
- 'win/d3d9/texture_d3d9.h',
- 'win/d3d9/utils_d3d9.cc',
- 'win/d3d9/utils_d3d9.h',
- ],
- },
- ],
- ],
- },
- {
- 'target_name': 'o3dCoreTest',
- 'type': 'none',
- 'direct_dependent_settings': {
- 'sources': [
- 'cross/bitmap_test.cc',
- 'cross/bounding_box_test.cc',
- 'cross/buffer_test.cc',
- 'cross/class_manager_test.cc',
- 'cross/client_test.cc',
- 'cross/counter_test.cc',
- 'cross/curve_test.cc',
- 'cross/draw_element_test.cc',
- 'cross/draw_list_test.cc',
- 'cross/draw_pass_test.cc',
- 'cross/effect_test.cc',
- 'cross/element_test.cc',
- 'cross/event_manager_test.cc',
- 'cross/features_test.cc',
- 'cross/field_test.cc',
- 'cross/float_n_test.cc',
- 'cross/function_test.cc',
- 'cross/image_utils_test.cc',
- 'cross/material_test.cc',
- 'cross/math_utilities_test.cc',
- 'cross/matrix4_axis_rotation_test.cc',
- 'cross/matrix4_composition_test.cc',
- 'cross/matrix4_scale_test.cc',
- 'cross/matrix4_translation_test.cc',
- 'cross/message_commands_test.cc',
- 'cross/message_queue_test.cc',
- 'cross/object_base_test.cc',
- 'cross/pack_test.cc',
- 'cross/param_array_test.cc',
- 'cross/param_object_test.cc',
- 'cross/param_operation_test.cc',
- 'cross/param_test.cc',
- 'cross/performance_timer_test.cc',
- 'cross/primitive_test.cc',
- 'cross/ray_intersection_info_test.cc',
- 'cross/render_node_test.cc',
- 'cross/renderer_test.cc',
- 'cross/service_locator_test.cc',
- 'cross/shape_test.cc',
- 'cross/skin_test.cc',
- 'cross/smart_ptr_test.cc',
- 'cross/state_set_test.cc',
- 'cross/state_test.cc',
- 'cross/stream_bank_test.cc',
- 'cross/stream_test.cc',
- 'cross/texture_base_test.cc',
- 'cross/texture_test.cc',
- 'cross/transform_test.cc',
- 'cross/tree_traversal_test.cc',
- 'cross/vector_map_test.cc',
- 'cross/vertex_source_test.cc',
- 'cross/visitor_base_test.cc',
- 'cross/weak_ptr_test.cc',
- 'cross/gpu2d/arena_test.cc',
- 'cross/gpu2d/cubic_classifier_test.cc',
- 'cross/gpu2d/interval_tree_test.cc',
- 'cross/gpu2d/local_triangulator_test.cc',
- 'cross/gpu2d/red_black_tree_test.cc',
- 'cross/gpu2d/tree_test_helpers.cc',
- 'cross/gpu2d/tree_test_helpers.h',
- ],
- },
- },
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/core/cross/bitmap.cc b/o3d/core/cross/bitmap.cc
deleted file mode 100644
index 6a62ee2..0000000
--- a/o3d/core/cross/bitmap.cc
+++ /dev/null
@@ -1,567 +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 image file codec operations for OpenGL texture
-// loading. Trying to keep this class as independent from the OpenGL API in
-// case they need retargeting later on.
-
-#include "core/cross/bitmap.h"
-#include <cstring>
-#include <cmath>
-#include <sys/stat.h>
-#include "base/file_path.h"
-#include "base/file_util.h"
-#include "core/cross/error.h"
-#include "core/cross/features.h"
-#include "core/cross/texture.h"
-#include "import/cross/raw_data.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-#include "utils/cross/file_path_utils.h"
-
-using file_util::OpenFile;
-using file_util::CloseFile;
-using file_util::GetFileSize;
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Bitmap, ParamObject);
-
-Bitmap::Bitmap(ServiceLocator* service_locator)
- : ParamObject(service_locator),
- image_data_(NULL),
- format_(Texture::UNKNOWN_FORMAT),
- width_(0),
- height_(0),
- num_mipmaps_(0),
- semantic_(IMAGE) {
-}
-
-size_t Bitmap::GetMipSize(unsigned int level) const {
- unsigned int mip_width = std::max(1U, width() >> level);
- unsigned int mip_height = std::max(1U, height() >> level);
- return image::ComputeMipChainSize(mip_width, mip_height, format(), 1);
-}
-
-size_t Bitmap::ComputeMaxSize(
- unsigned width, unsigned height, Texture::Format format) {
- return image::ComputeMipChainSize(
- width, height, format,
- image::ComputeMipMapCount(width, height));
-}
-
-void Bitmap::SetContents(Texture::Format format,
- unsigned int num_mipmaps,
- unsigned int width,
- unsigned int height,
- Bitmap::Semantic semantic,
- scoped_array<uint8>* image_data) {
- DCHECK(image_data);
- image_data_.reset();
- format_ = format;
- num_mipmaps_ = num_mipmaps;
- width_ = width;
- height_ = height;
- semantic_ = semantic;
- image_data_.swap(*image_data);
-}
-
-void Bitmap::SetFrom(Bitmap *source) {
- DCHECK(source);
- SetContents(source->format(),
- source->num_mipmaps(),
- source->width(),
- source->height(),
- source->semantic(),
- &source->image_data_);
-}
-
-void Bitmap::Allocate(Texture::Format format,
- unsigned int width,
- unsigned int height,
- unsigned int num_mipmaps,
- Bitmap::Semantic semantic) {
- DCHECK(image::CheckImageDimensions(width, height));
- switch (format) {
- case Texture::XRGB8:
- case Texture::ARGB8:
- case Texture::ABGR16F:
- case Texture::R32F:
- case Texture::ABGR32F:
- case Texture::DXT1:
- case Texture::DXT3:
- case Texture::DXT5:
- break;
- default:
- DLOG(FATAL) << "Trying to allocate a bitmap with invalid format";
- break;
- }
- DCHECK_LE(num_mipmaps, image::ComputeMipMapCount(width, height));
- DCHECK_GT(num_mipmaps, 0u);
-
- format_ = format;
- width_ = width;
- height_ = height;
- num_mipmaps_ = num_mipmaps;
- semantic_ = semantic;
- AllocateData();
-}
-
-uint8 *Bitmap::GetMipData(unsigned int level) const {
- DCHECK(level < num_mipmaps_);
- if (!image_data_.get()) return NULL;
- uint8 *data = image_data_.get();
- return data + GetMipChainSize(level);
-}
-
-uint8 *Bitmap::GetPixelData(
- unsigned int level, unsigned int x, unsigned int y) const {
- uint8* data = GetMipData(level);
- if (data) {
- data += GetMipPitch(level) * y + image::ComputePitch(format(), 1) * x;
- }
- return data;
-}
-
-void Bitmap::SetRect(
- int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned src_width,
- unsigned src_height,
- const void* src_data,
- int src_pitch) {
- DCHECK(src_data);
- DCHECK(level < static_cast<int>(num_mipmaps()) && level >= 0);
- unsigned mip_width = image::ComputeMipDimension(level, width());
- unsigned mip_height = image::ComputeMipDimension(level, height());
- DCHECK(dst_left + src_width <= mip_width &&
- dst_top + src_height <= mip_height);
- bool compressed = Texture::IsCompressedFormat(format());
- bool entire_rect = dst_left == 0 && dst_top == 0 &&
- src_width == mip_width && src_height == mip_height;
- DCHECK(!compressed || entire_rect);
-
- uint8* dst = GetPixelData(level, dst_left, dst_top);
-
- const uint8* src = static_cast<const uint8*>(src_data);
- if (!compressed) {
- unsigned bytes_per_line = image::ComputePitch(format(), src_width);
- int dst_pitch = image::ComputePitch(format(), mip_width);
- for (unsigned yy = 0; yy < src_height; ++yy) {
- memcpy(dst, src, bytes_per_line);
- src += src_pitch;
- dst += dst_pitch;
- }
- } else {
- memcpy(dst, src,
- image::ComputeMipChainSize(mip_width, mip_height, format(), 1));
- }
-}
-
-bool Bitmap::LoadFromStream(ServiceLocator* service_locator,
- MemoryReadStream *stream,
- const String &filename,
- image::ImageFileType file_type,
- BitmapRefArray* bitmaps) {
- DCHECK(stream);
- DCHECK(bitmaps);
- BitmapRefArray::size_type first = bitmaps->size();
- bool success = false;
- // If we don't know what type to load, try to detect it based on the file
- // name.
- if (file_type == image::UNKNOWN) {
- file_type = image::GetFileTypeFromFilename(filename.c_str());
- }
-
- switch (file_type) {
- case image::TGA:
- success = LoadFromTGAStream(service_locator, stream, filename, bitmaps);
- break;
- case image::DDS:
- success = LoadFromDDSStream(service_locator, stream, filename, bitmaps);
- break;
- case image::PNG:
- success = LoadFromPNGStream(service_locator, stream, filename, bitmaps);
- break;
- case image::JPEG:
- success = LoadFromJPEGStream(service_locator, stream, filename, bitmaps);
- break;
- case image::UNKNOWN:
- default:
- break;
- }
-
- if (!success) {
- // At this point we either could not detect the filetype, or possibly
- // the file extension was incorrect (eg. a JPEG image with a .png suffix)
- DLOG(INFO) << "Could not detect file type from filename \""
- << filename << "\". Trying all the loaders.";
- // We will try all the loaders, one by one, starting by the ones that can
- // have an early detect based on magic strings. We Seek(0) after each try
- // since each attempt changes the stream read position.
- success = LoadFromDDSStream(service_locator, stream, filename, bitmaps);
- if (!success) {
- stream->Seek(0);
- success = LoadFromPNGStream(service_locator, stream, filename, bitmaps);
- }
-
- if (!success) {
- stream->Seek(0);
- success = LoadFromJPEGStream(service_locator, stream, filename, bitmaps);
- }
-
- if (!success) {
- stream->Seek(0);
- success = LoadFromTGAStream(service_locator, stream, filename, bitmaps);
- }
- }
-
- if (success) {
- Features* features = service_locator->GetService<Features>();
- DCHECK(features);
- if (features->flip_textures()) {
- // Only flip the bitmaps we added.
- for (BitmapRefArray::size_type ii = first; ii < bitmaps->size(); ++ii) {
- Bitmap* bitmap = (*bitmaps)[ii].Get();
- if (bitmap->semantic() == IMAGE) {
- bitmap->FlipVertically();
- }
- }
- }
- } else {
- DLOG(ERROR) << "Failed to load image \"" << filename
- << "\": unknown file type";
- }
- return success;
-}
-
-// Given an arbitrary bitmap file, load it all into memory and then call our
-// stream loader
-bool Bitmap::LoadFromFile(ServiceLocator* service_locator,
- const FilePath &filepath,
- image::ImageFileType file_type,
- BitmapRefArray* bitmaps) {
- DCHECK(bitmaps);
- // Open the file.
- bool result = false;
- String filename = FilePathToUTF8(filepath);
- FILE *file = OpenFile(filepath, "rb");
-
- if (!file) {
- DLOG(ERROR) << "bitmap file not found \"" << filename << "\"";
- } else {
- // Determine the file's length
- int64 file_size64;
- if (!GetFileSize(filepath, &file_size64)) {
- DLOG(ERROR) << "error getting bitmap file size \"" << filename << "\"";
- } else {
- if (file_size64 > 0xffffffffLL) {
- DLOG(ERROR) << "bitmap file is too large \"" << filename << "\"";
- } else {
- size_t file_length = static_cast<size_t>(file_size64);
-
- // Load the compressed image data into memory
- MemoryBuffer<uint8> file_contents(file_length);
- uint8 *p = file_contents;
- if (fread(p, file_length, 1, file) != 1) {
- DLOG(ERROR) << "error reading bitmap file \"" << filename << "\"";
- } else {
- // And create the bitmap from a memory stream
- MemoryReadStream stream(file_contents, file_length);
- result = LoadFromStream(service_locator,
- &stream, filename, file_type, bitmaps);
- }
- }
- }
- CloseFile(file);
- }
-
- return result;
-}
-
-// Given a RawData object containing image data in one of our known formats,
-// decide which image format it is and call the correct loading function.
-bool Bitmap::LoadFromRawData(RawData *raw_data,
- image::ImageFileType file_type,
- BitmapRefArray* bitmaps) {
- DCHECK(raw_data);
- DCHECK(bitmaps);
- String filename = raw_data->uri();
-
- // GetData() returns NULL if it, for example, cannot open the temporary data
- // file. In that case, it invokes the error callback. We just have to be
- // careful not to dereference it.
- const uint8* data = raw_data->GetData();
- if (!data) {
- return false;
- }
-
- MemoryReadStream stream(data, raw_data->GetLength());
-
- return LoadFromStream(raw_data->service_locator(),
- &stream, filename, file_type, bitmaps);
-}
-
-void Bitmap::DrawImage(const Bitmap& src_img,
- int src_level,
- int src_x, int src_y,
- int src_width, int src_height,
- int dst_level,
- int dst_x, int dst_y,
- int dst_width, int dst_height) {
- DCHECK(src_img.image_data());
- DCHECK(image_data());
-
- if (dst_level < 0 || dst_level >= static_cast<int>(num_mipmaps())) {
- O3D_ERROR(service_locator()) << "Destination Mip out of range";
- }
-
- if (src_level < 0 || src_level >= static_cast<int>(src_img.num_mipmaps())) {
- O3D_ERROR(service_locator()) << "Source Mip out of range";
- }
-
- // Clip source and destination rectangles to
- // source and destination bitmaps.
- // if src or dest rectangle is out of boundary,
- // do nothing and return.
- if (!image::AdjustDrawImageBoundary(&src_x, &src_y,
- &src_width, &src_height,
- src_level,
- src_img.width_, src_img.height_,
- &dst_x, &dst_y,
- &dst_width, &dst_height,
- dst_level,
- width_, height_))
- return;
-
- // check formats of source and dest images.
- // format of source and dest should be the same.
- if (src_img.format_ != format_) {
- O3D_ERROR(service_locator()) << "DrawImage does not support "
- << "different formats.";
- return;
- }
- // if src and dest are in the same size and drawImage is copying
- // the entire bitmap on dest image, just perform memcpy.
- if (src_x == 0 && src_y == 0 && dst_x == 0 && dst_y == 0 &&
- src_img.width_ == width_ && src_img.height_ == height_ &&
- src_width == src_img.width_ && src_height == src_img.height_ &&
- dst_width == width_ && dst_height == height_) {
- SetRect(dst_level, 0, 0, dst_width, dst_height,
- src_img.GetMipData(src_level), src_img.GetMipPitch(src_level));
- return;
- }
-
- unsigned int components = image::GetNumComponentsForFormat(format_);
- if (components == 0) {
- O3D_ERROR(service_locator()) << "DrawImage does not support format: "
- << src_img.format_ << " unless src and "
- << "dest images are in the same size and "
- << "copying the entire bitmap";
- return;
- }
-
- int src_pitch = src_img.GetMipPitch(src_level);
- if (image::AdjustForSetRect(&src_y, src_width, src_height, &src_pitch,
- &dst_y, dst_width, &dst_height)) {
- SetRect(dst_level, dst_x, dst_y, dst_width, dst_height,
- src_img.GetPixelData(src_level, src_x, src_y),
- src_pitch);
- return;
- }
-
- // crop part of image from src img, scale it in
- // bilinear interpolation fashion, and paste it
- // on dst img.
- image::LanczosScale(src_img.format_,
- src_img.GetMipData(src_level),
- src_img.GetMipPitch(src_level),
- src_x, src_y,
- src_width, src_height,
- GetMipData(dst_level),
- GetMipPitch(dst_level),
- dst_x, dst_y,
- dst_width, dst_height,
- components);
-}
-
-void Bitmap::GenerateMips(int source_level, int num_levels) {
- if (source_level >= static_cast<int>(num_mipmaps()) || source_level < 0) {
- O3D_ERROR(service_locator()) << "source level out of range.";
- return;
- }
- unsigned int max_mips = image::ComputeMipMapCount(width(), height());
- if (source_level + num_levels >=
- static_cast<int>(max_mips) || num_levels < 0) {
- O3D_ERROR(service_locator()) << "num levels out of range.";
- return;
- }
-
- if (GenerateMipmaps(image::ComputeMipDimension(source_level, width()),
- image::ComputeMipDimension(source_level, height()),
- format(),
- num_levels,
- GetMipData(source_level))) {
- num_mipmaps_ = std::max(
- num_mipmaps_,
- static_cast<unsigned>(source_level + num_levels + 1));
- }
-}
-
-// NOTE: This only works for Bitmap since Bitmap knows the pitch.
-bool Bitmap::GenerateMipmaps(unsigned int base_width,
- unsigned int base_height,
- Texture::Format format,
- unsigned int num_mipmaps,
- uint8 *data) {
- DCHECK(image::CheckImageDimensions(base_width, base_height));
- unsigned int components = image::GetNumComponentsForFormat(format);
- if (components == 0) {
- DLOG(ERROR) << "Mip-map generation not supported for format: " << format;
- return false;
- }
- DCHECK_GE(std::max(base_width, base_height) >> (num_mipmaps - 1), 1u);
- uint8 *mip_data = data;
- unsigned int mip_width = base_width;
- unsigned int mip_height = base_height;
- for (unsigned int level = 1; level < num_mipmaps; ++level) {
- unsigned int prev_width = mip_width;
- unsigned int prev_height = mip_height;
- uint8 *prev_data = mip_data;
- mip_data += components * mip_width * mip_height;
- DCHECK_EQ(mip_data, data + image::ComputeMipChainSize(
- base_width, base_height, format, level));
- mip_width = std::max(1U, mip_width >> 1);
- mip_height = std::max(1U, mip_height >> 1);
- image::GenerateMipmap(
- prev_width, prev_height, format,
- prev_data, image::ComputePitch(format, prev_width),
- mip_data, image::ComputePitch(format, mip_width));
- }
-
- return true;
-}
-
-// Checks that all the alpha values are 1.0
-bool Bitmap::CheckAlphaIsOne() const {
- if (!image_data())
- return false;
-
- switch (format()) {
- case Texture::XRGB8:
- return true;
- case Texture::ARGB8: {
- for (unsigned int level = 0; level < num_mipmaps(); ++level) {
- const uint8* data = GetMipData(level) + 3;
- const uint8* end = data + image::ComputeBufferSize(
- std::max(1U, width() >> level),
- std::max(1U, height() >> level),
- format());
- while (data < end) {
- if (*data != 255) {
- return false;
- }
- data += 4;
- }
- }
- break;
- }
- case Texture::DXT1: {
- for (unsigned int level = 0; level < num_mipmaps(); ++level) {
- const uint8* data = GetMipData(level);
- const uint8* end = data + image::ComputeBufferSize(
- std::max(1U, width() >> level),
- std::max(1U, height() >> level),
- format());
- DCHECK((end - data) % 8 == 0);
- while (data < end) {
- int color0 = static_cast<int>(data[0]) |
- static_cast<int>(data[1]) << 8;
- int color1 = static_cast<int>(data[2]) |
- static_cast<int>(data[3]) << 8;
- if (color0 < color1) {
- return false;
- }
- data += 8;
- }
- }
- break;
- }
- case Texture::DXT3:
- case Texture::DXT5:
- return false;
- case Texture::ABGR16F: {
- for (unsigned int level = 0; level < num_mipmaps(); ++level) {
- const uint8* data = GetMipData(level) + 6;
- const uint8* end = data + image::ComputeBufferSize(
- std::max(1U, width() >> level),
- std::max(1U, height() >> level),
- format());
- while (data < end) {
- if (data[0] != 0x00 || data[1] != 0x3C) {
- return false;
- }
- data += 8;
- }
- }
- break;
- }
- case Texture::R32F:
- return true;
- case Texture::ABGR32F: {
- for (unsigned int level = 0; level < num_mipmaps(); ++level) {
- const uint8* data = GetMipData(level) + 12;
- const uint8* end = data + image::ComputeBufferSize(
- std::max(1U, width() >> level),
- std::max(1U, height() >> level),
- format());
- while (data < end) {
- if (*(reinterpret_cast<const float*>(data)) != 1.0f) {
- return false;
- }
- data += 16;
- }
- }
- break;
- }
- case Texture::UNKNOWN_FORMAT:
- return false;
- }
- return true;
-}
-
-ObjectBase::Ref Bitmap::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new Bitmap(service_locator));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/bitmap.h b/o3d/core/cross/bitmap.h
deleted file mode 100644
index 8af80a5..0000000
--- a/o3d/core/cross/bitmap.h
+++ /dev/null
@@ -1,406 +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 declaration of Bitmap helper class that can load
-// raw 24- and 32-bit bitmaps from popular image formats. The Bitmap class
-// also interprets the file format to record the correct OpenGL buffer format.
-//
-// Trying to keep this class independent from the OpenGL API in case they
-// need retargeting later on.
-
-#ifndef O3D_CORE_CROSS_BITMAP_H_
-#define O3D_CORE_CROSS_BITMAP_H_
-
-#include <stdlib.h>
-#include <vector>
-#include "base/cross/bits.h"
-#include "core/cross/types.h"
-#include "core/cross/texture_base.h"
-#include "core/cross/image_utils.h"
-
-class FilePath;
-
-namespace o3d {
-
-class MemoryReadStream;
-class RawData;
-class Pack;
-
-// Bitmap provides an API for basic image operations on bitmap images,
-// including scale and crop. Bitmaps can be created from a RawData object via
-// LoadFromRawData(), and also can be transfered to mips of a Texure2D or a
-// specific face of TextureCUBE via methods in Texture.
-
-class Bitmap : public ParamObject {
- public:
- typedef SmartPointer<Bitmap> Ref;
- typedef std::vector<Bitmap::Ref> BitmapRefArray;
-
- explicit Bitmap(ServiceLocator* service_locator);
- virtual ~Bitmap() {}
-
- enum Semantic {
- FACE_POSITIVE_X, // NOTE: These must match TextureCUBE::CubeFace
- FACE_NEGATIVE_X,
- FACE_POSITIVE_Y,
- FACE_NEGATIVE_Y,
- FACE_POSITIVE_Z,
- FACE_NEGATIVE_Z,
- IMAGE, // normal 2d image
- SLICE, // a slice of a 3d texture.
- };
-
- // Returns the pitch of the bitmap for a certain level.
- int GetMipPitch(int level) const {
- return image::ComputeMipPitch(format(), level, width());
- }
-
- // Creates a copy of a bitmap, copying the pixels as well.
- // Parameters:
- // source: the source bitmap.
- void CopyDeepFrom(const Bitmap &source) {
- Allocate(source.format_, source.width_, source.height_,
- source.num_mipmaps_, source.semantic_);
- memcpy(image_data(), source.image_data(), GetTotalSize());
- }
-
- // Sets the bitmap parameters from another bitmap, stealing the pixel buffer
- // from the source bitmap.
- // Parameters:
- // source: the source bitmap.
- void SetFrom(Bitmap *source);
-
- // Allocates an uninitialized bitmap with specified parameters.
- // Parameters:
- // format: the format of the pixels.
- // width: the width of the base image.
- // height: the height of the base image.
- // num_mipmaps: the number of mip-maps.
- void Allocate(Texture::Format format,
- unsigned int width,
- unsigned int height,
- unsigned int num_mipmaps,
- Semantic semantic);
-
- // Allocates a bitmap with initialized parameters.
- // data is zero-initialized
- void AllocateData() {
- image_data_.reset(new uint8[GetTotalSize()]);
- memset(image_data_.get(), 0, GetTotalSize());
- }
-
- // Frees the data owned by the bitmap.
- void FreeData() {
- image_data_.reset(NULL);
- }
-
- // Sets a rectangular region of this bitmap.
- // If the bitmap is a DXT format, the only acceptable values
- // for left, top, width and height are 0, 0, bitmap->width, bitmap->height
- //
- // Parameters:
- // level: The mipmap level to modify
- // dst_left: The left edge of the rectangular area to modify.
- // dst_top: The top edge of the rectangular area to modify.
- // width: The width of the rectangular area to modify.
- // height: The of the rectangular area to modify.
- // src_data: The source pixels.
- // src_pitch: If the format is uncompressed this is the number of bytes
- // per row of pixels. If compressed this value is unused.
- void SetRect(int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned width,
- unsigned height,
- const void* src_data,
- int src_pitch);
-
- // Gets the image data for a given mip-map level.
- // Parameters:
- // level: mip level to get.
- uint8 *GetMipData(unsigned int level) const;
-
- // Gets the address of a particular pixel.
- // Parameters:
- // level: mip level to get.
- uint8 *GetPixelData(unsigned int level, unsigned int x, unsigned int y) const;
-
- // Gets the size of mip.
- size_t GetMipSize(unsigned int level) const;
-
- uint8 *image_data() const { return image_data_.get(); }
- Texture::Format format() const { return format_; }
- unsigned int width() const { return width_; }
- unsigned int height() const { return height_; }
- unsigned int num_mipmaps() const { return num_mipmaps_; }
- Semantic semantic() const {
- return semantic_;
- }
-
- // Returns whether or not the dimensions of the bitmap are power-of-two.
- bool IsPOT() const {
- return image::IsPOT(width_, height_);
- }
-
- // Loads a bitmap from a file.
- // Parameters:
- // filename: the name of the file to load.
- // file_type: the type of file to load. If UNKNOWN, the file type will be
- // determined from the filename extension, and if it is not a
- // known extension, all the loaders will be tried.
- // bitmaps: An array to hold references to the loaded bitmaps.
- static bool LoadFromFile(ServiceLocator* service_locator,
- const FilePath &filepath,
- image::ImageFileType file_type,
- BitmapRefArray* bitmaps);
-
- // Loads a bitmap from a RawData object.
- // Parameters:
- // raw_data: contains the bitmap data in one of the known formats
- // file_type: the format of the bitmap data. If UNKNOWN, the file type
- // will be determined from the extension from raw_data's uri
- // and if it is not a known extension, all the loaders will
- // be tried.
- // bitmaps: An array to hold references to the loaded bitmaps.
- static bool LoadFromRawData(RawData *raw_data,
- image::ImageFileType file_type,
- BitmapRefArray* bitmaps);
-
- // Flips a bitmap vertically in place.
- // This is needed instead of just using DrawImage because flipping DXT formats
- // using generic algorithms would be lossy and extremely slow to reconvert
- // from a flippable format back to a DXT format.
- void FlipVertically();
-
- // Returns the contents of the bitmap as a data URL
- // Returns:
- // A data url that represents the content of the bitmap.
- String ToDataURL();
-
- // Checks that the alpha channel for the entire bitmap is 1.0
- bool CheckAlphaIsOne() const;
-
- // Copy pixels from source bitmap. Scales if the width and height of source
- // and dest do not match.
- // Parameters:
- // source_img: source bitmap which would be drawn.
- // source_level: level to draw.
- // source_x: x-coordinate of the starting pixel in the source image.
- // source_x: y-coordinate of the starting pixel in the source image.
- // source_width: width of the source image to draw.
- // source_height: Height of the source image to draw.
- // dest_level: level to target.
- // dest_x: x-coordinate of the starting pixel in the dest image.
- // dest_y: y-coordinate of the starting pixel in the dest image.
- // dest_width: width of the dest image to draw.
- // dest_height: height of the dest image to draw.
- void DrawImage(const Bitmap& source_img, int source_level,
- int source_x, int source_y,
- int source_width, int source_height,
- int dest_level,
- int dest_x, int dest_y,
- int dest_width, int dest_height);
-
- // Gets the size of the buffer containing a mip-map chain, given a number of
- // mip-map levels.
- size_t GetMipChainSize(unsigned int num_mipmaps) const {
- return image::ComputeMipChainSize(width(), height(), format(), num_mipmaps);
- }
-
- // Generates Mips from the source_level for num_levels
- void GenerateMips(int source_level, int num_levels);
-
- bool WriteToPNGStream(std::vector<uint8>* stream);
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // Sets the contents of a Bitmap replacing any previous contents.
- // Parameters:
- // format: Format of the bitmap.
- // num_mipmaps: The number of mipmaps.
- // width: width in pixels.
- // height: height in pixels.
- // semantic: the semantic of the bitmap
- // image_data: The image data. The bitmap will take ownership of this data.
- void SetContents(Texture::Format format,
- unsigned int num_mipmaps,
- unsigned int width,
- unsigned int height,
- Semantic semantic,
- scoped_array<uint8>* image_data);
-
- // Loads bitmaps from a MemoryReadStream.
- // Parameters:
- // stream: a stream for the bitmap data in one of the known formats
- // filename: a filename (or uri) of the original bitmap data
- // (may be an empty string)
- // file_type: the format of the bitmap data. If UNKNOWN, the file type
- // will be determined from the extension of |filename|
- // and if it is not a known extension, all the loaders
- // will be tried.
- // bitmaps: An array to hold references to the loaded bitmaps.
- static bool LoadFromStream(ServiceLocator* service_locator,
- MemoryReadStream *stream,
- const String &filename,
- image::ImageFileType file_type,
- BitmapRefArray* bitmaps);
-
- static bool LoadFromPNGStream(ServiceLocator* service_locator,
- MemoryReadStream *stream,
- const String &filename,
- BitmapRefArray* bitmaps);
-
- static bool LoadFromTGAStream(ServiceLocator* service_locator,
- MemoryReadStream *stream,
- const String &filename,
- BitmapRefArray* bitmaps);
-
- static bool LoadFromDDSStream(ServiceLocator* service_locator,
- MemoryReadStream *stream,
- const String &filename,
- BitmapRefArray* bitmaps);
-
- static bool LoadFromJPEGStream(ServiceLocator* service_locator,
- MemoryReadStream *stream,
- const String &filename,
- BitmapRefArray* bitmaps);
-
- bool GenerateMipmaps(unsigned int base_width,
- unsigned int base_height,
- Texture::Format format,
- unsigned int num_mipmaps,
- uint8 *data);
-
- // Gets the total size of the bitmap data, counting all faces and mip levels.
- size_t GetTotalSize() const {
- return GetMipChainSize(image::ComputeMipMapCount(width_, height_));
- }
-
- static size_t ComputeMaxSize(
- unsigned width, unsigned height, Texture::Format format);
-
- // pointer to the raw bitmap data
- // NOTE: image_data_ is either NULL or it has space for the maximum number
- // of mips for the current size bitmap, even if they are not used.
- scoped_array<uint8> image_data_;
- // format of the texture this is meant to represent.
- Texture::Format format_;
- // width of the bitmap in pixels.
- int width_;
- // height of the bitmap in pixels.
- int height_;
- // number of valid mipmap levels in this bitmap.
- unsigned int num_mipmaps_;
- // The purpose of the bitmap
- Semantic semantic_;
-
- O3D_DECL_CLASS(Bitmap, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(Bitmap);
-};
-
-typedef Bitmap::BitmapRefArray BitmapRefArray;
-
-class BitmapUncompressed : public Bitmap {
- public:
- explicit BitmapUncompressed(ServiceLocator* service_locator);
-};
-
-template <typename T>
-class TypedBitmapUncompressed : public BitmapUncompressed {
- public:
- typedef T ComponentType;
- explicit TypedBitmapUncompressed(ServiceLocator* service_locator)
- : BitmapUncompressed(service_locator) {
- }
-};
-
-class Bitmap8 : public TypedBitmapUncompressed<uint8> {
- public:
- explicit Bitmap8(ServiceLocator* service_locator);
-
- private:
- DISALLOW_COPY_AND_ASSIGN(Bitmap8);
-};
-
-class Bitmap16F : public TypedBitmapUncompressed<uint16> {
- public:
- explicit Bitmap16F(ServiceLocator* service_locator);
-
- private:
- DISALLOW_COPY_AND_ASSIGN(Bitmap16F);
-};
-
-class Bitmap32F : public TypedBitmapUncompressed<float> {
- public:
- explicit Bitmap32F(ServiceLocator* service_locator);
-
- private:
- DISALLOW_COPY_AND_ASSIGN(Bitmap32F);
-};
-
-class BitmapCompressed : public Bitmap {
- public:
- explicit BitmapCompressed(ServiceLocator* service_locator);
-
- private:
- DISALLOW_COPY_AND_ASSIGN(BitmapCompressed);
-};
-
-class BitmapDXT1 : public BitmapCompressed {
- public:
- explicit BitmapDXT1(ServiceLocator* service_locator);
-
- private:
- DISALLOW_COPY_AND_ASSIGN(BitmapDXT1);
-};
-
-class BitmapDXT3 : public BitmapCompressed {
- public:
- explicit BitmapDXT3(ServiceLocator* service_locator);
-
- private:
- DISALLOW_COPY_AND_ASSIGN(BitmapDXT3);
-};
-
-class BitmapDXT5 : public BitmapCompressed {
- public:
- explicit BitmapDXT5(ServiceLocator* service_locator);
-
- private:
- DISALLOW_COPY_AND_ASSIGN(BitmapDXT5);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_BITMAP_H_
diff --git a/o3d/core/cross/bitmap_dds.cc b/o3d/core/cross/bitmap_dds.cc
deleted file mode 100644
index 9b47c30..0000000
--- a/o3d/core/cross/bitmap_dds.cc
+++ /dev/null
@@ -1,512 +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 image codec operations for DDS files.
-
-#include <stdio.h>
-#include "core/cross/bitmap.h"
-#include "core/cross/ddsurfacedesc.h"
-#include "utils/cross/file_path_utils.h"
-#include "base/file_util.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-
-using file_util::OpenFile;
-using file_util::CloseFile;
-
-namespace o3d {
-
-// LoadFromDDSFile -------------------------------------------------------------
-
-// A function that flips a DXTC block.
-typedef void (* FlipBlockFunction)(uint8 *block);
-
-// Flips a full DXT1 block in the y direction.
-static void FlipDXT1BlockFull(uint8 *block) {
- // A DXT1 block layout is:
- // [0-1] color0.
- // [2-3] color1.
- // [4-7] color bitmap, 2 bits per pixel.
- // So each of the 4-7 bytes represents one line, flipping a block is just
- // flipping those bytes.
- uint8 tmp = block[4];
- block[4] = block[7];
- block[7] = tmp;
- tmp = block[5];
- block[5] = block[6];
- block[6] = block[5];
-}
-
-// Flips the first 2 lines of a DXT1 block in the y direction.
-static void FlipDXT1BlockHalf(uint8 *block) {
- // See layout above.
- uint8 tmp = block[4];
- block[4] = block[5];
- block[5] = tmp;
-}
-
-// Flips a full DXT3 block in the y direction.
-static void FlipDXT3BlockFull(uint8 *block) {
- // A DXT3 block layout is:
- // [0-7] alpha bitmap, 4 bits per pixel.
- // [8-15] a DXT1 block.
-
- // We can flip the alpha bits at the byte level (2 bytes per line).
- uint8 tmp = block[0];
- block[0] = block[6];
- block[6] = tmp;
- tmp = block[1];
- block[1] = block[7];
- block[7] = tmp;
- tmp = block[2];
- block[2] = block[4];
- block[4] = tmp;
- tmp = block[3];
- block[3] = block[5];
- block[5] = tmp;
-
- // And flip the DXT1 block using the above function.
- FlipDXT1BlockFull(block + 8);
-}
-
-// Flips the first 2 lines of a DXT3 block in the y direction.
-static void FlipDXT3BlockHalf(uint8 *block) {
- // See layout above.
- uint8 tmp = block[0];
- block[0] = block[2];
- block[2] = tmp;
- tmp = block[1];
- block[1] = block[3];
- block[3] = tmp;
- FlipDXT1BlockHalf(block + 8);
-}
-
-// Flips a full DXT5 block in the y direction.
-static void FlipDXT5BlockFull(uint8 *block) {
- // A DXT5 block layout is:
- // [0] alpha0.
- // [1] alpha1.
- // [2-7] alpha bitmap, 3 bits per pixel.
- // [8-15] a DXT1 block.
-
- // The alpha bitmap doesn't easily map lines to bytes, so we have to
- // interpret it correctly. Extracted from
- // http://www.opengl.org/registry/specs/EXT/texture_compression_s3tc.txt :
- //
- // The 6 "bits" bytes of the block are decoded into one 48-bit integer:
- //
- // bits = bits_0 + 256 * (bits_1 + 256 * (bits_2 + 256 * (bits_3 +
- // 256 * (bits_4 + 256 * bits_5))))
- //
- // bits is a 48-bit unsigned integer, from which a three-bit control code
- // is extracted for a texel at location (x,y) in the block using:
- //
- // code(x,y) = bits[3*(4*y+x)+1..3*(4*y+x)+0]
- //
- // where bit 47 is the most significant and bit 0 is the least
- // significant bit.
- unsigned int line_0_1 = block[2] + 256 * (block[3] + 256 * block[4]);
- unsigned int line_2_3 = block[5] + 256 * (block[6] + 256 * block[7]);
- // swap lines 0 and 1 in line_0_1.
- unsigned int line_1_0 = ((line_0_1 & 0x000fff) << 12) |
- ((line_0_1 & 0xfff000) >> 12);
- // swap lines 2 and 3 in line_2_3.
- unsigned int line_3_2 = ((line_2_3 & 0x000fff) << 12) |
- ((line_2_3 & 0xfff000) >> 12);
- block[2] = line_3_2 & 0xff;
- block[3] = (line_3_2 & 0xff00) >> 8;
- block[4] = (line_3_2 & 0xff0000) >> 8;
- block[5] = line_1_0 & 0xff;
- block[6] = (line_1_0 & 0xff00) >> 8;
- block[7] = (line_1_0 & 0xff0000) >> 8;
-
- // And flip the DXT1 block using the above function.
- FlipDXT1BlockFull(block + 8);
-}
-
-// Flips the first 2 lines of a DXT5 block in the y direction.
-static void FlipDXT5BlockHalf(uint8 *block) {
- // See layout above.
- unsigned int line_0_1 = block[2] + 256 * (block[3] + 256 * block[4]);
- unsigned int line_1_0 = ((line_0_1 & 0x000fff) << 12) |
- ((line_0_1 & 0xfff000) >> 12);
- block[2] = line_1_0 & 0xff;
- block[3] = (line_1_0 & 0xff00) >> 8;
- block[4] = (line_1_0 & 0xff0000) >> 8;
- FlipDXT1BlockHalf(block + 8);
-}
-
-// Flips a DXTC image, by flipping and swapping DXTC blocks as appropriate.
-static void FlipDXTCImage(unsigned int width,
- unsigned int height,
- unsigned int levels,
- Texture::Format format,
- uint8 *data) {
- DCHECK(image::CheckImageDimensions(width, height));
- // Height must be a power-of-two.
- DCHECK_EQ(height & (height - 1), 0u);
- FlipBlockFunction full_block_function = NULL;
- FlipBlockFunction half_block_function = NULL;
- unsigned int block_bytes = 0;
- switch (format) {
- case Texture::DXT1:
- full_block_function = FlipDXT1BlockFull;
- half_block_function = FlipDXT1BlockHalf;
- block_bytes = 8;
- break;
- case Texture::DXT3:
- full_block_function = FlipDXT3BlockFull;
- half_block_function = FlipDXT3BlockHalf;
- block_bytes = 16;
- break;
- case Texture::DXT5:
- full_block_function = FlipDXT5BlockFull;
- half_block_function = FlipDXT5BlockHalf;
- block_bytes = 16;
- break;
- default:
- DLOG(FATAL) << "Not Reached";
- return;
- }
- unsigned int mip_width = width;
- unsigned int mip_height = height;
- for (unsigned int i = 0; i < levels; ++i) {
- unsigned int blocks_per_row = (mip_width + 3) / 4;
- unsigned int blocks_per_col = (mip_height + 3) / 4;
- unsigned int blocks = blocks_per_row * blocks_per_col;
- if (mip_height == 1) {
- // no flip to do, and we're done.
- break;
- } else if (mip_height == 2) {
- // flip the first 2 lines in each block.
- for (unsigned int i = 0; i < blocks_per_row; ++i) {
- half_block_function(data + i * block_bytes);
- }
- } else {
- // flip each block.
- for (unsigned int i = 0; i < blocks; ++i) {
- full_block_function(data + i * block_bytes);
- }
- // swap each block line in the first half of the image with the
- // corresponding one in the second half.
- // note that this is a no-op if mip_height is 4.
- unsigned int row_bytes = block_bytes * blocks_per_row;
- scoped_array<uint8> temp_line(new uint8[row_bytes]);
- for (unsigned int y = 0; y < blocks_per_col / 2; ++y) {
- uint8 *line1 = data + y * row_bytes;
- uint8 *line2 = data + (blocks_per_col - y - 1) * row_bytes;
- memcpy(temp_line.get(), line1, row_bytes);
- memcpy(line1, line2, row_bytes);
- memcpy(line2, temp_line.get(), row_bytes);
- }
- }
- // mip levels are contiguous.
- data += block_bytes * blocks;
- mip_width = std::max(1U, mip_width >> 1);
- mip_height = std::max(1U, mip_height >> 1);
- }
-}
-
-// Flips a BGRA image, by simply swapping pixel rows.
-static void FlipBGRAImage(unsigned int width,
- unsigned int height,
- unsigned int levels,
- Texture::Format format,
- uint8 *data) {
- DCHECK(image::CheckImageDimensions(width, height));
- DCHECK(format != Texture::DXT1 && format != Texture::DXT3 &&
- format != Texture::DXT5);
- size_t pixel_bytes = image::ComputeMipChainSize(1, 1, format, 1);
- unsigned int mip_width = width;
- unsigned int mip_height = height;
- // rows are at most as big as the first one.
- scoped_array<uint8> temp_line(
- new uint8[mip_width * pixel_bytes]);
- for (unsigned int i = 0; i < levels; ++i) {
- unsigned int row_bytes = pixel_bytes * mip_width;
- for (unsigned int y = 0; y < mip_height / 2; ++y) {
- uint8 *line1 = data + y * row_bytes;
- uint8 *line2 = data + (mip_height - y - 1) * row_bytes;
- memcpy(temp_line.get(), line1, row_bytes);
- memcpy(line1, line2, row_bytes);
- memcpy(line2, temp_line.get(), row_bytes);
- }
- // mip levels are contiguous.
- data += row_bytes * mip_height;
- mip_width = std::max(1U, mip_width >> 1);
- mip_height = std::max(1U, mip_height >> 1);
- }
-}
-
-void Bitmap::FlipVertically() {
- if (format() == Texture::DXT1 ||
- format() == Texture::DXT3 ||
- format() == Texture::DXT5) {
- FlipDXTCImage(width(), height(), num_mipmaps(), format(), image_data());
- } else {
- FlipBGRAImage(width(), height(), num_mipmaps(), format(), image_data());
- }
-}
-
-
-// Load the bitmap data as DXTC compressed data from a DDS stream into the
-// Bitmap object. This routine only supports compressed DDS formats DXT1,
-// DXT3 and DXT5.
-bool Bitmap::LoadFromDDSStream(ServiceLocator* service_locator,
- MemoryReadStream *stream,
- const String &filename,
- BitmapRefArray* bitmaps) {
- // Verify the file is a true .dds file
- char magic[4];
- size_t bytes_read = stream->Read(magic, sizeof(magic));
- if (bytes_read != sizeof(magic)) {
- DLOG(ERROR) << "DDS magic header not read \"" << filename << "\"";
- return false;
- }
- if (std::strncmp(magic, "DDS ", 4) != 0) {
- DLOG(ERROR) << "DDS magic header not recognized \"" << filename << "\"";
- return false;
- }
- // Get the DirectDraw Surface Descriptor
- DDSURFACEDESC2 dd_surface_descriptor;
- if (!stream->ReadAs<DDSURFACEDESC2>(&dd_surface_descriptor)) {
- DLOG(ERROR) << "DDS header not read \"" << filename << "\"";
- return false;
- }
- const unsigned int kRequiredFlags =
- DDSD_CAPS |
- DDSD_HEIGHT |
- DDSD_WIDTH |
- DDSD_PIXELFORMAT;
- if ((dd_surface_descriptor.dwFlags & kRequiredFlags) != kRequiredFlags) {
- DLOG(ERROR) << "Required DDS flags are absent in \"" << filename << "\".";
- return false;
- }
- // NOTE: Add permissible flags as appropriate here when supporting new
- // formats.
- const unsigned int kValidFlags = kRequiredFlags |
- DDSD_MIPMAPCOUNT |
- DDSD_LINEARSIZE;
- if (dd_surface_descriptor.dwFlags & ~kValidFlags) {
- DLOG(ERROR) << "Invalid DDS flags combination \"" << filename << "\".";
- return false;
- }
- unsigned int mip_count = (dd_surface_descriptor.dwFlags & DDSD_MIPMAPCOUNT) ?
- dd_surface_descriptor.dwMipMapCount : 1;
- unsigned int dds_width = dd_surface_descriptor.dwWidth;
- unsigned int dds_height = dd_surface_descriptor.dwHeight;
- if (!image::CheckImageDimensions(dds_width, dds_height)) {
- DLOG(ERROR) << "Failed to load " << filename
- << ": dimensions are too large (" << dds_width
- << ", " << dds_height << ").";
- return false;
- }
-
- if (mip_count > image::ComputeMipMapCount(dds_width, dds_height)) {
- DLOG(ERROR) << "Failed to load " << filename
- << ": mip count " << mip_count
- << "is inconsistent with image dimensions ("
- << dds_width<< ", " << dds_height << ").";
- return false;
- }
-
- // Check for cube maps
- bool is_cubemap =
- (dd_surface_descriptor.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP) != 0;
- // Cube maps should have all the face flags set - otherwise the cube map is
- // incomplete.
- if (is_cubemap) {
- if ((dd_surface_descriptor.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) !=
- DDSCAPS2_CUBEMAP_ALLFACES) {
- DLOG(ERROR) << "DDS file \"" << filename
- << "\" is a cube map but doesn't have all the faces.";
- return false;
- }
- if (dds_width != dds_height) {
- DLOG(ERROR) << "DDS file \"" << filename
- << "\" is a cube map but doesn't have square dimensions.";
- return false;
- }
- }
-
- // The size of the buffer needed to hold four-component per pixel
- // image data, including MIPMaps
- unsigned int components_per_pixel = 0;
- bool add_filler_alpha = false;
- bool rgb_to_bgr = false;
-
- Texture::Format format = Texture::UNKNOWN_FORMAT;
- bool is_dxtc = false;
-
- DDPIXELFORMAT &pixel_format = dd_surface_descriptor.ddpfPixelFormat;
-
- if (pixel_format.dwFlags & DDPF_FOURCC) {
- switch (pixel_format.dwFourCC) {
- case FOURCC_DXT1 : {
- format = Texture::DXT1;
- is_dxtc = true;
- break;
- }
- case FOURCC_DXT3 : {
- format = Texture::DXT3;
- is_dxtc = true;
- break;
- }
- case FOURCC_DXT5 : {
- format = Texture::DXT5;
- is_dxtc = true;
- break;
- }
- default : {
- DLOG(ERROR) << "DDS format not DXT1, DXT3 or DXT5. \""
- << filename << "\"";
- return false;
- }
- }
-
- // Check that the advertised size is correct.
- if (dd_surface_descriptor.dwFlags & DDSD_LINEARSIZE) {
- size_t expected_size =
- image::ComputeBufferSize(dds_width, dds_height, format);
- if (expected_size != dd_surface_descriptor.dwLinearSize) {
- DLOG(ERROR) << "Advertised buffer size in \"" << filename
- << "\" differs from expected size.";
- return false;
- }
- }
- if (is_dxtc) {
- // DirectX says the only valid DXT format base sizes are multiple-of-4.
- // OpenGL doesn't care, but we actually do because we need to flip them.
- // (and we can't flip them if they are not multiple-of-4).
- // This restriction actually exists for mip-map levels as well, so in
- // practice we need power-of-two restriction.
- if ((dds_width & (dds_width - 1)) != 0 ||
- (dds_height & (dds_height - 1)) != 0) {
- DLOG(ERROR) << "Invalid dimensions in DXTC file \""
- << filename << "\": must be power-of-two.";
- return false;
- }
- }
- } else if (pixel_format.dwFlags & DDPF_RGB) {
- if (pixel_format.dwFlags & DDPF_ALPHAPIXELS) {
- // Pixel format with alpha. Check that the alpha bits are at the expected
- // place.
- if (pixel_format.dwRGBAlphaBitMask != 0xff000000) {
- DLOG(ERROR) << "unexpected alpha mask in DDS image format \""
- << filename << "\"";
- return false;
- }
- } else {
- add_filler_alpha = true;
- }
- // uncompressed bitmap
- // try to determine the format
- if (pixel_format.dwRBitMask == 0x00ff0000 &&
- pixel_format.dwGBitMask == 0x0000ff00 &&
- pixel_format.dwBBitMask == 0x000000ff) {
- // BGR(A) format.
- } else if (pixel_format.dwRBitMask == 0x000000ff &&
- pixel_format.dwGBitMask == 0x0000ff00 &&
- pixel_format.dwBBitMask == 0x00ff0000) {
- // RGB(A) format. Convert to BGR(A).
- rgb_to_bgr = true;
- } else {
- DLOG(ERROR) << "unknown uncompressed DDS image format \""
- << filename << "\"";
- return false;
- }
- // components per pixel in the file.
- components_per_pixel = add_filler_alpha ? 3 : 4;
- if (components_per_pixel * 8 != pixel_format.dwRGBBitCount) {
- DLOG(ERROR) << "unexpected bit count in DDS image format \""
- << filename << "\"";
- return false;
- }
- format = add_filler_alpha ? Texture::XRGB8 : Texture::ARGB8;
- }
-
- unsigned int num_bitmaps = is_cubemap ? 6 : 1;
- // Bitmap requires we allocate enough memory for all mips even if we don't use
- // them.
- size_t face_size = Bitmap::ComputeMaxSize(dds_width, dds_height, format);
-
- BitmapRefArray temp_bitmaps;
-
- size_t disk_face_size =
- image::ComputeMipChainSize(dds_width, dds_height, format, mip_count);
- if (!is_dxtc) {
- // if reading uncompressed RGB, for example, we shouldn't read alpha channel
- // NOTE: here we assume that RGB data is packed - it may not be true
- // for non-multiple-of-4 widths.
- disk_face_size = components_per_pixel * disk_face_size / 4;
- }
-
- for (unsigned int face = 0; face < num_bitmaps; ++face) {
- // Allocate and load bitmap data.
- scoped_array<uint8> image_data(new uint8[face_size]);
-
- char *data = reinterpret_cast<char*>(image_data.get());
- bytes_read = stream->Read(data, disk_face_size);
- if (bytes_read != disk_face_size) {
- DLOG(ERROR) << "DDS failed to read image data \"" << filename << "\"";
- return false;
- }
-
- // Do pixel conversions on non-DXT images.
- if (!is_dxtc) {
- DCHECK(components_per_pixel == 3 || components_per_pixel == 4);
- unsigned int pixel_count = disk_face_size / components_per_pixel;
- // convert to four components per pixel if necessary
- if (add_filler_alpha) {
- DCHECK_EQ(components_per_pixel, 3u);
- image::XYZToXYZA(image_data.get(), pixel_count);
- } else {
- DCHECK_EQ(components_per_pixel, 4u);
- }
- if (rgb_to_bgr) {
- image::RGBAToBGRA(image_data.get(), pixel_count);
- }
- }
- Semantic semantic = is_cubemap ? static_cast<Semantic>(face) : IMAGE;
-
- Bitmap::Ref bitmap(new Bitmap(service_locator));
- bitmap->SetContents(format, mip_count, dds_width, dds_height, semantic,
- &image_data);
- temp_bitmaps.push_back(bitmap);
- }
-
- // Success.
- bitmaps->insert(bitmaps->end(), temp_bitmaps.begin(), temp_bitmaps.end());
- return true;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/bitmap_jpg.cc b/o3d/core/cross/bitmap_jpg.cc
deleted file mode 100644
index 2c6030f..0000000
--- a/o3d/core/cross/bitmap_jpg.cc
+++ /dev/null
@@ -1,276 +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 image codec operations for JPEG files.
-
-#include <csetjmp>
-#include "core/cross/bitmap.h"
-#include "utils/cross/file_path_utils.h"
-#include "base/file_path.h"
-#include "base/file_util.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-
-using file_util::OpenFile;
-using file_util::CloseFile;
-
-#define XMD_H // Prevent redefinition of UINT32
-#undef FAR // Prevent redefinition of macro "FAR"
-
-extern "C" {
-// NOTE: Some win32 header that is included by DirectX's headers
-// typedefs boolean to a type incompatible with libjpeg's definition. I can't
-// figure out how to disable that header. So scope the 'boolean' definition
-// with a typedef, only in this file.
-#define boolean jpg_boolean
-#include "jpeglib.h"
-#include "jerror.h"
-}
-
-namespace {
-// JPEGMemoryReader acts as a data source for libjpeg
-// Create one of these objects after calling jpeg_create_decompress()
-// and pass a pointer to the jpeg_decompress_struct initialized
-// from that function. |jpeg_data| is a pointer to the JPEG data
-// which is of length |jpeg_data_length| bytes
-//
-// NB: don't add any virtual methods to this class as we depend on
-// the initial memory layout of this object matching a jpeg_source_mgr
-class JPEGMemoryReader : public jpeg_source_mgr {
- public:
- JPEGMemoryReader(j_decompress_ptr cinfo,
- const uint8 *jpeg_data,
- size_t jpeg_data_length) {
- // Store a pointer to ourselves that we'll get in the callbacks
- if (cinfo->src == NULL) {
- cinfo->src = (struct jpeg_source_mgr *)this;
- }
-
- // Setup our custom function callbacks
- init_source = InitSource;
- fill_input_buffer = FillInputBuffer;
- skip_input_data = SkipInputData;
- resync_to_restart = jpeg_resync_to_restart; // default method from libjpeg
- term_source = TermSource;
-
- bytes_in_buffer = jpeg_data_length;
-
- uint8 *p = const_cast<uint8*>(jpeg_data);
- next_input_byte = reinterpret_cast<JOCTET*>(p);
- }
-
- private:
- // Callback functions, most of them do nothing
- METHODDEF(void) InitSource(j_decompress_ptr cinfo) {}; // nop
-
- METHODDEF(boolean) FillInputBuffer(j_decompress_ptr cinfo) {
- // Should not be called because we already have all the data
- ERREXIT(cinfo, JERR_INPUT_EOF);
- return TRUE;
- }
-
- // Here's the one which essentially "reads" from the memory buffer
- METHODDEF(void) SkipInputData(j_decompress_ptr cinfo, long num_bytes) {
- JPEGMemoryReader *This = (JPEGMemoryReader*)cinfo->src;
-
- int i = This->bytes_in_buffer - num_bytes;
- if (i < 0) i = 0;
- This->bytes_in_buffer = i;
- This->next_input_byte += num_bytes;
- }
-
- METHODDEF(void) TermSource(j_decompress_ptr cinfo) {}; // nop
-};
-} // namespace
-
-namespace o3d {
-
-struct my_error_mgr {
- struct jpeg_error_mgr pub; // "public" fields
- jmp_buf setjmp_buffer; // for return to caller
-};
-
-typedef struct my_error_mgr* my_error_ptr;
-
-METHODDEF(void) my_error_exit(j_common_ptr cinfo) {
- // return control to the original error handler.
- my_error_ptr myerr = reinterpret_cast<my_error_ptr>(cinfo->err);
- std::longjmp(myerr->setjmp_buffer, 1);
-}
-
-// Loads the raw RGB bitmap data from a compressed JPEG stream and converts
-// the result to 24- or 32-bit bitmap data.
-bool Bitmap::LoadFromJPEGStream(ServiceLocator* service_locator,
- MemoryReadStream *stream,
- const String &filename,
- BitmapRefArray* bitmaps) {
- // Workspace for libjpeg decompression.
- struct jpeg_decompress_struct cinfo;
- // create our custom error handler.
- struct my_error_mgr jerr;
- JSAMPARRAY buffer; // Output buffer - a row of pixels.
- int row_stride; // Physical row width in output buffer.
-
-
- // Step 1: allocate and initialize JPEG decompression object
-
- // We set up the normal JPEG error routines, then override error_exit.
- cinfo.err = jpeg_std_error(&jerr.pub);
- jerr.pub.error_exit = my_error_exit;
-
- // NOTE: The following smart pointer needs to be declared before the
- // setjmp so that it is properly destroyed if we jump back.
- scoped_array<uint8> image_data;
-
- // Establish the setjmp return context for my_error_exit to use.
- if (setjmp(jerr.setjmp_buffer)) {
- // If control is returned here, an error occurred inside libjpeg.
- // Log the error message.
- char buffer[JMSG_LENGTH_MAX];
- (*cinfo.err->format_message) (reinterpret_cast<j_common_ptr>(&cinfo),
- buffer);
- DLOG(ERROR) << "JPEG load error: " << buffer;
- // Clean up.
- jpeg_destroy_decompress(&cinfo);
- return false;
- }
-
- // Initialize the JPEG decompression object.
- jpeg_create_decompress(&cinfo);
-
- // Creating a JPEGMemoryReader instance modifies some state in |cinfo|
- // in such a way to read JPEG data from memory buffer |jpeg_data| of
- // length |jpeg_data_length|
- size_t jpeg_data_length = stream->GetTotalStreamLength();
- const uint8 *jpeg_data = stream->GetDirectMemoryPointer();
- JPEGMemoryReader(&cinfo, jpeg_data, jpeg_data_length);
-
- // Step 3: read the JPEG header and allocate storage
- jpeg_read_header(&cinfo, TRUE);
-
- // Set the Bitmap member variables from the jpeg_decompress_struct fields.
- unsigned int width = cinfo.image_width;
- unsigned int height = cinfo.image_height;
- if (!image::CheckImageDimensions(width, height)) {
- DLOG(ERROR) << "Failed to load " << filename
- << ": dimensions are too large (" << width
- << ", " << height << ").";
- // Use the jpeg error system to clean up and exit.
- ERREXIT(&cinfo, JERR_QUANT_COMPONENTS);
- }
-
- if (cinfo.num_components != 3) {
- DLOG(ERROR) << "JPEG load error: Bad number of pixel channels ("
- << cinfo.num_components
- << ") in file \"" << filename << "\"";
- // Use the jpeg error system to clean up and exit.
- ERREXIT(&cinfo, JERR_QUANT_COMPONENTS);
- }
- unsigned int image_components = 4;
- Texture::Format format = Texture::XRGB8;
- // Allocate storage for the pixels. Bitmap requires we allocate enough
- // memory for all mips even if we don't use them.
- size_t image_size = Bitmap::ComputeMaxSize(width, height, format);
- image_data.reset(new uint8[image_size]);
- if (image_data.get() == NULL) {
- DLOG(ERROR) << "JPEG memory allocation error \"" << filename << "\"";
- // Invoke the longjmp() error handler.
- ERREXIT(&cinfo, JERR_OUT_OF_MEMORY);
- }
-
- // Step 4: set parameters for decompression
- // Use the default decompression settings.
-
- // Step 5: Start decompressor
- jpeg_start_decompress(&cinfo);
- // These should be equal because we don't use scaling.
- // TODO: use libjpeg scaling for NPOT->POT ?
- DCHECK_EQ(width, cinfo.output_width);
- DCHECK_EQ(height, cinfo.output_height);
-
- // Create an output work buffer of the right size.
- row_stride = cinfo.output_width * cinfo.output_components;
-
- // Make a one-row-high sample array, using the JPEG library memory manager.
- // This buffer will be deallocated when decompression is finished.
- buffer = (*cinfo.mem->alloc_sarray)( reinterpret_cast<j_common_ptr>(&cinfo),
- JPOOL_IMAGE,
- row_stride,
- 1);
-
- // Step 6: while (scan lines remain to be read)
- // jpeg_read_scanlines(...);
-
- // Use the library's state variable cinfo.output_scanline as the
- // loop counter, so that we don't have to keep track ourselves.
- while (cinfo.output_scanline < height) {
- // Initialise the buffer write location.
- uint8 *image_write_ptr = image_data.get() +
- cinfo.output_scanline * width * image_components;
-
- // jpeg_read_scanlines() expects an array of pointers to scanlines.
- // Here we ask for only one scanline to be read into "buffer".
- jpeg_read_scanlines(&cinfo, buffer, 1);
-
- // output_scanline is the numbe of scanlines that have been emitted.
- DCHECK_LE(cinfo.output_scanline, height);
-
- // copy the scanline to its final destination
- for (unsigned int i = 0; i < width; ++i) {
- // RGB -> BGRX
- image_write_ptr[i * image_components + 0] =
- buffer[0][i * cinfo.output_components + 2];
- image_write_ptr[i * image_components + 1] =
- buffer[0][i * cinfo.output_components + 1];
- image_write_ptr[i * image_components + 2] =
- buffer[0][i * cinfo.output_components + 0];
- image_write_ptr[i * image_components + 3] = 0xff;
- }
- }
-
- // Step 7: Finish decompression.
- jpeg_finish_decompress(&cinfo);
-
- // Step 8: Release JPEG decompression object nd free workspace.
- jpeg_destroy_decompress(&cinfo);
-
- // Check for jpeg decompression warnings.
- DLOG(WARNING) << "JPEG decompression warnings: " << jerr.pub.num_warnings;
-
- // Success.
- Bitmap::Ref bitmap(new Bitmap(service_locator));
- bitmap->SetContents(format, 1, width, height, IMAGE, &image_data);
- bitmaps->push_back(bitmap);
- return true;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/bitmap_png.cc b/o3d/core/cross/bitmap_png.cc
deleted file mode 100644
index 686e854..0000000
--- a/o3d/core/cross/bitmap_png.cc
+++ /dev/null
@@ -1,356 +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 image codec operations for PNG files.
-
-#include <fstream>
-#include "core/cross/bitmap.h"
-#include "core/cross/error.h"
-#include "core/cross/types.h"
-#include "utils/cross/file_path_utils.h"
-#include "base/file_path.h"
-#include "base/file_util.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-#include "png.h"
-#include "utils/cross/dataurl.h"
-
-using file_util::OpenFile;
-using file_util::CloseFile;
-
-namespace o3d {
-
-namespace {
-
-// Helper function for LoadFromPNGFile that converts a stream into the
-// necessary abstract byte reading function.
-void StreamReadData(png_structp png_ptr, png_bytep data, png_size_t length) {
- MemoryReadStream *stream =
- static_cast<MemoryReadStream*>(png_get_io_ptr(png_ptr));
- stream->Read(data, length);
-}
-
-// Helper function for ToDataURL that converts a stream into the necessary
-// abstract byte writing function.
-void StreamWriteData(png_structp png_ptr, png_bytep data, png_size_t length) {
- std::vector<uint8>* stream =
- static_cast<std::vector<uint8>*>(png_get_io_ptr(png_ptr));
- stream->insert(stream->end(),
- static_cast<uint8*>(data),
- static_cast<uint8*>(data) + length);
-}
-
-// Because libpng requires a flush function according to the docs.
-void StreamFlush(png_structp png_ptr) {
-}
-
-} // anonymous namespace
-
-// Loads the raw RGB data from a compressed PNG file.
-bool Bitmap::LoadFromPNGStream(ServiceLocator* service_locator,
- MemoryReadStream *stream,
- const String &filename,
- BitmapRefArray* bitmaps) {
- DCHECK(bitmaps);
- // Read the magic header.
- char magic[4];
- size_t bytes_read = stream->Read(magic, sizeof(magic));
- if (bytes_read != sizeof(magic)) {
- DLOG(ERROR) << "PNG file magic header not loaded \"" << filename << "\"";
- return false;
- }
-
- // Match the magic header to check that this is a PNG file.
- if (png_sig_cmp(reinterpret_cast<png_bytep>(magic), 0, sizeof(magic)) != 0) {
- DLOG(ERROR) << "File is not a PNG file \"" << filename << "\"";
- return false;
- }
-
- // Load the rest of the PNG file ----------------
- png_structp png_ptr = NULL;
- png_infop info_ptr = NULL;
-
- // create the PNG structure (not providing user error functions).
- png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
- NULL, // user_error_ptr
- NULL, // user_error_fn
- NULL); // user_warning_fn
- if (png_ptr == NULL)
- return 0;
-
- // Allocate memory for image information
- info_ptr = png_create_info_struct(png_ptr);
- if (info_ptr == NULL) {
- png_destroy_read_struct(&png_ptr, png_infopp_NULL, png_infopp_NULL);
- DLOG(ERROR) << "Cannot allocate working memory for PNG load.";
- return false;
- }
-
- // NOTE: The following smart pointer needs to be declared before the
- // setjmp so that it is properly destroyed if we jump back.
- scoped_array<uint8> image_data;
- png_bytepp row_pointers = NULL;
-
- // Set error handling if you are using the setjmp/longjmp method. If any
- // error happens in the following code, we will return here to handle the
- // error.
- if (setjmp(png_jmpbuf(png_ptr))) {
- // If we reach here, a fatal error occurred so free memory and exit.
- DLOG(ERROR) << "Fatal error reading PNG file \"" << filename << "\"";
- if (row_pointers)
- png_free(png_ptr, row_pointers);
- png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL);
- return false;
- }
-
- // Set up our STL stream input control
- png_set_read_fn(png_ptr, stream, &StreamReadData);
-
- // We have already read some of the signature, advance the pointer.
- png_set_sig_bytes(png_ptr, sizeof(magic));
-
- // Read the PNG header information.
- png_uint_32 png_width = 0;
- png_uint_32 png_height = 0;
- int png_color_type = 0;
- int png_interlace_type = 0;
- int png_bits_per_channel = 0;
- png_read_info(png_ptr, info_ptr);
- png_get_IHDR(png_ptr,
- info_ptr,
- &png_width,
- &png_height,
- &png_bits_per_channel,
- &png_color_type,
- &png_interlace_type,
- NULL,
- NULL);
-
- if (!image::CheckImageDimensions(png_width, png_height)) {
- DLOG(ERROR) << "Failed to load " << filename
- << ": dimensions are too large (" << png_width
- << ", " << png_height << ").";
- // Use the png error system to clean up and exit.
- png_error(png_ptr, "PNG image too large");
- }
-
- // Extract multiple pixels with bit depths of 1, 2, and 4 from a single
- // byte into separate bytes (useful for paletted and grayscale images)
- //
- // png_set_packing(png_ptr);
-
- // Change the order of packed pixels to least significant bit first
- // (not useful if you are using png_set_packing)
- //
- // png_set_packswap(png_ptr);
-
- // Number of components in destination data (going to image_data).
- unsigned int dst_components = 0;
- Texture::Format format = Texture::UNKNOWN_FORMAT;
- // Palette vs non-palette.
- if (png_color_type == PNG_COLOR_TYPE_PALETTE) {
- // Expand paletted colors into RGB{A} triplets
- png_set_palette_to_rgb(png_ptr);
- // Gray vs RGB.
- } else if ((png_color_type & PNG_COLOR_MASK_COLOR) == PNG_COLOR_TYPE_RGB) {
- if (png_bits_per_channel != 8) {
- png_error(png_ptr, "PNG image type not recognized");
- }
- } else {
- if (png_bits_per_channel <= 1 ||
- png_bits_per_channel >= 8 ) {
- png_error(png_ptr, "PNG image type not recognized");
- }
- // Expand grayscale images to the full 8 bits from 2, or 4 bits/pixel
- // TODO(o3d): Do we want to expose L/A/LA texture formats ?
- png_set_gray_1_2_4_to_8(png_ptr);
- png_set_gray_to_rgb(png_ptr);
- }
- // Expand paletted or RGB images with transparency to full alpha channels
- // so the data will be available as RGBA quartets.
- if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
- png_set_tRNS_to_alpha(png_ptr);
- png_color_type |= PNG_COLOR_MASK_ALPHA;
- }
- // 24-bit RGB image or 32-bit RGBA image.
- if (png_color_type & PNG_COLOR_MASK_ALPHA) {
- format = Texture::ARGB8;
- } else {
- format = Texture::XRGB8;
- // Add alpha byte after each RGB triplet
- png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER);
- }
- png_set_bgr(png_ptr);
- dst_components = 4;
-
- // Turn on interlace handling. REQURIED if you are not using
- // png_read_image(). To see how to handle interlacing passes,
- // see the png_read_row() method below:
- png_set_interlace_handling(png_ptr);
-
- // Execute any setup steps for each Transform, i.e. to gamma correct and
- // add the background to the palette and update info structure. REQUIRED
- // if you are expecting libpng to update the palette for you (ie you
- // selected such a transform above).
- png_read_update_info(png_ptr, info_ptr);
-
- // Allocate storage for the pixels. Bitmap requires we allocate enough
- // memory for all mips even if we don't use them.
- size_t png_image_size = Bitmap::ComputeMaxSize(png_width, png_height, format);
- image_data.reset(new uint8[png_image_size]);
- if (image_data.get() == NULL) {
- DLOG(ERROR) << "PNG image memory allocation error \"" << filename << "\"";
- png_error(png_ptr, "Cannot allocate memory for bitmap");
- }
-
- // Create an array of pointers to the beginning of each row. For some
- // hideous reason the PNG library requires this. At least we don't malloc
- // memory for each row as the examples do.
- row_pointers = static_cast<png_bytep *>(
- png_malloc(png_ptr, png_height * sizeof(png_bytep))); // NOLINT
- if (row_pointers == NULL) {
- DLOG(ERROR) << "PNG row memory allocation error \"" << filename << "\"";
- png_error(png_ptr, "Cannot allocate memory for row pointers");
- }
-
- // Fill the row pointer array.
- DCHECK_LE(png_get_rowbytes(png_ptr, info_ptr), png_width * dst_components);
- png_bytep row_ptr = reinterpret_cast<png_bytep>(image_data.get());
- for (unsigned int i = 0; i < png_height; ++i) {
- row_pointers[i] = row_ptr;
- row_ptr += png_width * dst_components;
- }
-
- // Read the image, applying format transforms and de-interlacing as we go.
- png_read_image(png_ptr, row_pointers);
-
- // Do not reading any additional chunks using png_read_end()
-
- // Clean up after the read, and free any memory allocated - REQUIRED
- png_free(png_ptr, row_pointers);
- png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL);
-
- // Success.
- Bitmap::Ref bitmap(new Bitmap(service_locator));
- bitmap->SetContents(format, 1, png_width, png_height, IMAGE, &image_data);
- bitmaps->push_back(bitmap);
- return true;
-}
-
-namespace {
-
-bool CreatePNGInUInt8Vector(const Bitmap& bitmap, std::vector<uint8>* buffer) {
- DCHECK(bitmap.format() == Texture::ARGB8);
- DCHECK(bitmap.num_mipmaps() == 1);
-
- png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL,
- NULL, NULL);
- if (!png_ptr) {
- DLOG(ERROR) << "Could not create PNG structure.";
- return false;
- }
-
- png_infop info_ptr = png_create_info_struct(png_ptr);
- if (!info_ptr) {
- DLOG(ERROR) << "Could not create PNG info structure.";
- png_destroy_write_struct(&png_ptr, png_infopp_NULL);
- return false;
- }
-
- unsigned width = bitmap.width();
- unsigned height = bitmap.height();
- scoped_array<png_bytep> row_pointers(new png_bytep[height]);
- for (unsigned int i = 0; i < height; ++i) {
- row_pointers[height - 1 - i] = bitmap.GetMipData(0) + i * width * 4;
- }
-
- if (setjmp(png_jmpbuf(png_ptr))) {
- // If we get here, we had a problem reading the file.
- DLOG(ERROR) << "Error while getting dataURL.";
- png_destroy_write_struct(&png_ptr, &info_ptr);
- return false;
- }
-
- // Set up our STL stream output.
- png_set_write_fn(png_ptr, buffer, &StreamWriteData, &StreamFlush);
-
- png_set_IHDR(png_ptr, info_ptr, width, height, 8,
- PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
- PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
- png_set_bgr(png_ptr);
- png_set_rows(png_ptr, info_ptr, row_pointers.get());
- png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, png_voidp_NULL);
-
- png_destroy_write_struct(&png_ptr, &info_ptr);
- return true;
-}
-
-} // anonymous namespace
-
-bool Bitmap::WriteToPNGStream(std::vector<uint8>* stream) {
- if (format_ != Texture::ARGB8) {
- O3D_ERROR(service_locator()) << "Can only write ARGB8 images to PNGs.";
- return false;
- }
- if (num_mipmaps_ != 1) {
- O3D_ERROR(service_locator()) <<
- "Can only write 2d images with no mips to PNGs.";
- return false;
- }
-
- if (!CreatePNGInUInt8Vector(*this, stream)) {
- return false;
- }
-
- return true;
-}
-
-String Bitmap::ToDataURL() {
- if (format_ != Texture::ARGB8) {
- O3D_ERROR(service_locator()) << "Can only get data URL from ARGB8 images.";
- return dataurl::kEmptyDataURL;
- }
- if (num_mipmaps_ != 1) {
- O3D_ERROR(service_locator()) <<
- "Can only get data URL from 2d images with no mips.";
- return dataurl::kEmptyDataURL;
- }
-
- std::vector<uint8> stream;
- if (!CreatePNGInUInt8Vector(*this, &stream)) {
- return dataurl::kEmptyDataURL;
- }
-
- return dataurl::ToDataURL("image/png", &stream[0], stream.size());
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/bitmap_test.cc b/o3d/core/cross/bitmap_test.cc
deleted file mode 100644
index bf35e62..0000000
--- a/o3d/core/cross/bitmap_test.cc
+++ /dev/null
@@ -1,1247 +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 "core/cross/client.h"
-#include "core/cross/bitmap.h"
-#include "core/cross/texture.h"
-#include "tests/common/win/testing_common.h"
-#include "base/file_path.h"
-#include "utils/cross/file_path_utils.h"
-
-namespace o3d {
-
-class BitmapTest : public testing::Test {
-};
-
-// The first 128 bytes of tga-256x256-24bit.tga, converted to BGRX format.
-static uint8 ktga256x256_24bit_BGRX[128] = {
- 0x36, 0x87, 0xbc, 0xff, 0x36, 0x87, 0xbc, 0xff,
- 0x35, 0x83, 0xb5, 0xff, 0x34, 0x83, 0xb5, 0xff,
- 0x35, 0x83, 0xb5, 0xff, 0x35, 0x82, 0xb5, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x83, 0xb5, 0xff, 0x37, 0x85, 0xb8, 0xff,
- 0x36, 0x85, 0xb8, 0xff, 0x35, 0x86, 0xb7, 0xff,
- 0x35, 0x87, 0xb7, 0xff, 0x35, 0x88, 0xb7, 0xff,
- 0x35, 0x89, 0xb7, 0xff, 0x34, 0x8a, 0xb7, 0xff,
- 0x34, 0x8b, 0xb7, 0xff, 0x32, 0x8c, 0xb5, 0xff,
- 0x31, 0x8c, 0xb1, 0xff, 0x2f, 0x8d, 0xaf, 0xff,
- 0x1d, 0x8d, 0x96, 0xff, 0x1b, 0x8f, 0x90, 0xff,
-};
-
-static uint8 ktga256x256_32bit_BGRA[128] = {
- 0x36, 0x87, 0xbc, 0x7d, 0x36, 0x87, 0xbc, 0x7c,
- 0x35, 0x83, 0xb5, 0x78, 0x34, 0x83, 0xb5, 0x77,
- 0x35, 0x83, 0xb5, 0x77, 0x35, 0x82, 0xb5, 0x76,
- 0x35, 0x82, 0xb4, 0x76, 0x35, 0x82, 0xb4, 0x76,
- 0x35, 0x82, 0xb4, 0x76, 0x35, 0x82, 0xb4, 0x77,
- 0x35, 0x82, 0xb4, 0x76, 0x35, 0x82, 0xb4, 0x77,
- 0x35, 0x82, 0xb4, 0x76, 0x35, 0x82, 0xb4, 0x76,
- 0x35, 0x82, 0xb4, 0x76, 0x35, 0x82, 0xb4, 0x76,
- 0x35, 0x82, 0xb4, 0x76, 0x35, 0x82, 0xb4, 0x76,
- 0x35, 0x83, 0xb5, 0x77, 0x37, 0x85, 0xb8, 0x7a,
- 0x36, 0x85, 0xb8, 0x7a, 0x35, 0x86, 0xb7, 0x7a,
- 0x35, 0x87, 0xb7, 0x7a, 0x35, 0x88, 0xb7, 0x7c,
- 0x35, 0x89, 0xb7, 0x7c, 0x34, 0x8a, 0xb7, 0x7d,
- 0x34, 0x8b, 0xb7, 0x7e, 0x32, 0x8c, 0xb5, 0x7e,
- 0x31, 0x8c, 0xb1, 0x7d, 0x2f, 0x8d, 0xaf, 0x7c,
- 0x1d, 0x8d, 0x96, 0x75, 0x1b, 0x8f, 0x90, 0x75,
-};
-
-static uint8 kjpg256x256_BGRX[128] = {
- 0x3a, 0x88, 0xbd, 0xff, 0x38, 0x86, 0xbb, 0xff,
- 0x36, 0x85, 0xb8, 0xff, 0x34, 0x83, 0xb6, 0xff,
- 0x36, 0x82, 0xb6, 0xff, 0x35, 0x82, 0xb3, 0xff,
- 0x36, 0x82, 0xb3, 0xff, 0x36, 0x82, 0xb3, 0xff,
- 0x35, 0x81, 0xb5, 0xff, 0x35, 0x81, 0xb5, 0xff,
- 0x35, 0x81, 0xb5, 0xff, 0x35, 0x81, 0xb5, 0xff,
- 0x35, 0x81, 0xb5, 0xff, 0x35, 0x81, 0xb5, 0xff,
- 0x35, 0x81, 0xb5, 0xff, 0x35, 0x81, 0xb5, 0xff,
- 0x34, 0x82, 0xb1, 0xff, 0x35, 0x82, 0xb3, 0xff,
- 0x35, 0x84, 0xb7, 0xff, 0x36, 0x85, 0xb8, 0xff,
- 0x36, 0x85, 0xb8, 0xff, 0x35, 0x87, 0xb7, 0xff,
- 0x35, 0x87, 0xb7, 0xff, 0x36, 0x88, 0xb7, 0xff,
- 0x32, 0x8a, 0xb3, 0xff, 0x34, 0x8c, 0xb5, 0xff,
- 0x35, 0x8b, 0xb5, 0xff, 0x33, 0x8b, 0xb4, 0xff,
- 0x32, 0x8d, 0xb2, 0xff, 0x2b, 0x8f, 0xa8, 0xff,
- 0x21, 0x8d, 0x99, 0xff, 0x1a, 0x8f, 0x8e, 0xff,
-};
-
-static uint8 kpng256x256_24bit_BGRX[128] = {
- 0x36, 0x87, 0xbc, 0xff, 0x36, 0x87, 0xbc, 0xff,
- 0x35, 0x83, 0xb5, 0xff, 0x34, 0x83, 0xb5, 0xff,
- 0x35, 0x83, 0xb5, 0xff, 0x35, 0x82, 0xb5, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x83, 0xb5, 0xff, 0x37, 0x85, 0xb8, 0xff,
- 0x36, 0x85, 0xb8, 0xff, 0x35, 0x86, 0xb7, 0xff,
- 0x35, 0x87, 0xb7, 0xff, 0x35, 0x88, 0xb7, 0xff,
- 0x35, 0x89, 0xb7, 0xff, 0x34, 0x8a, 0xb7, 0xff,
- 0x34, 0x8b, 0xb7, 0xff, 0x32, 0x8c, 0xb5, 0xff,
- 0x31, 0x8c, 0xb1, 0xff, 0x2f, 0x8d, 0xaf, 0xff,
- 0x1d, 0x8d, 0x96, 0xff, 0x1b, 0x8f, 0x90, 0xff,
-};
-
-static uint8 kpng256x256_24bit_interlaced_BGRX[128] = {
- 0x36, 0x87, 0xbc, 0xff, 0x36, 0x87, 0xbc, 0xff,
- 0x35, 0x83, 0xb5, 0xff, 0x34, 0x83, 0xb5, 0xff,
- 0x35, 0x83, 0xb5, 0xff, 0x35, 0x82, 0xb5, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x83, 0xb5, 0xff, 0x37, 0x85, 0xb8, 0xff,
- 0x36, 0x85, 0xb8, 0xff, 0x35, 0x86, 0xb7, 0xff,
- 0x35, 0x87, 0xb7, 0xff, 0x35, 0x88, 0xb7, 0xff,
- 0x35, 0x89, 0xb7, 0xff, 0x34, 0x8a, 0xb7, 0xff,
- 0x34, 0x8b, 0xb7, 0xff, 0x32, 0x8c, 0xb5, 0xff,
- 0x31, 0x8c, 0xb1, 0xff, 0x2f, 0x8d, 0xaf, 0xff,
- 0x1d, 0x8d, 0x96, 0xff, 0x1b, 0x8f, 0x90, 0xff,
-};
-
-static uint8 kpng256x256_32bit_BGRA[128] = {
- 0x36, 0x87, 0xbc, 0xd4, 0x36, 0x87, 0xbc, 0xfa,
- 0x35, 0x83, 0xb5, 0xff, 0x34, 0x83, 0xb5, 0xfe,
- 0x35, 0x83, 0xb5, 0xf3, 0x35, 0x82, 0xb5, 0xcf,
- 0x35, 0x82, 0xb4, 0x9a, 0x35, 0x82, 0xb4, 0x75,
- 0x35, 0x82, 0xb4, 0x67, 0x35, 0x82, 0xb4, 0x7d,
- 0x35, 0x82, 0xb4, 0xa8, 0x35, 0x82, 0xb4, 0xdd,
- 0x35, 0x82, 0xb4, 0xf7, 0x35, 0x82, 0xb4, 0xff,
- 0x35, 0x82, 0xb4, 0xff, 0x35, 0x82, 0xb4, 0xf8,
- 0x35, 0x82, 0xb4, 0xaf, 0x35, 0x82, 0xb4, 0x68,
- 0x35, 0x83, 0xb5, 0x5a, 0x37, 0x85, 0xb8, 0x6a,
- 0x36, 0x85, 0xb8, 0xaf, 0x35, 0x86, 0xb7, 0xf8,
- 0x35, 0x87, 0xb7, 0xff, 0x35, 0x88, 0xb7, 0xff,
- 0x35, 0x89, 0xb7, 0xff, 0x34, 0x8a, 0xb7, 0xff,
- 0x34, 0x8b, 0xb7, 0xff, 0x32, 0x8c, 0xb5, 0xff,
- 0x31, 0x8c, 0xb1, 0xff, 0x2f, 0x8d, 0xaf, 0xff,
- 0x1d, 0x8d, 0x96, 0xff, 0x1b, 0x8f, 0x90, 0xff,
-};
-
-static uint8 kpng256x256_8bit_palette_BGRX[128] = {
- 0x36, 0x89, 0xbb, 0xff, 0x36, 0x89, 0xbb, 0xff,
- 0x35, 0x81, 0xb5, 0xff, 0x32, 0x84, 0xb5, 0xff,
- 0x35, 0x81, 0xb5, 0xff, 0x35, 0x81, 0xb5, 0xff,
- 0x35, 0x81, 0xb5, 0xff, 0x35, 0x81, 0xb5, 0xff,
- 0x35, 0x81, 0xb5, 0xff, 0x35, 0x81, 0xb5, 0xff,
- 0x35, 0x81, 0xb5, 0xff, 0x35, 0x81, 0xb5, 0xff,
- 0x35, 0x81, 0xb5, 0xff, 0x35, 0x81, 0xb5, 0xff,
- 0x35, 0x81, 0xb5, 0xff, 0x35, 0x81, 0xb5, 0xff,
- 0x35, 0x81, 0xb5, 0xff, 0x35, 0x81, 0xb5, 0xff,
- 0x35, 0x81, 0xb5, 0xff, 0x35, 0x85, 0xba, 0xff,
- 0x35, 0x85, 0xba, 0xff, 0x36, 0x86, 0xb6, 0xff,
- 0x36, 0x86, 0xb6, 0xff, 0x36, 0x86, 0xb6, 0xff,
- 0x38, 0x8b, 0xb6, 0xff, 0x38, 0x8b, 0xb6, 0xff,
- 0x38, 0x8b, 0xb6, 0xff, 0x33, 0x8b, 0xb2, 0xff,
- 0x33, 0x8b, 0xb2, 0xff, 0x33, 0x8b, 0xb2, 0xff,
- 0x1f, 0x8d, 0x91, 0xff, 0x1f, 0x8d, 0x91, 0xff,
-};
-
-static uint8 kpng20x14_4bit_palette_BGRX[128] = {
- 0xed, 0xed, 0xed, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xed, 0xed, 0xed, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0x54, 0x54, 0x54, 0xff,
- 0x33, 0x33, 0x33, 0xff, 0x33, 0x33, 0x33, 0xff,
- 0x33, 0x33, 0x33, 0xff, 0x33, 0x33, 0x33, 0xff,
- 0x33, 0x33, 0x33, 0xff, 0x33, 0x33, 0x33, 0xff,
- 0x33, 0x33, 0x33, 0xff, 0x33, 0x33, 0x33, 0xff,
- 0x54, 0x54, 0x54, 0xff, 0x33, 0x33, 0x33, 0xff,
-};
-
-static uint8 kdxt1_256x256[128] = {
- 0x47, 0xbc, 0x06, 0xb4, 0x5a, 0x6a, 0x6a, 0xea,
- 0x27, 0xb4, 0x06, 0xb4, 0x57, 0x57, 0x57, 0x5e,
- 0x06, 0xb4, 0x07, 0xb4, 0xaa, 0xaa, 0xaa, 0xaa,
- 0x06, 0xb4, 0x07, 0xb4, 0xaa, 0xaa, 0xaa, 0xaa,
- 0x46, 0xbc, 0x07, 0xb4, 0xd5, 0xf5, 0xf5, 0xa5,
- 0x46, 0xbc, 0x27, 0xb4, 0xfd, 0xbf, 0xbf, 0xaf,
- 0x47, 0xbc, 0x65, 0xac, 0xaa, 0xea, 0xea, 0x7a,
- 0x46, 0xac, 0x83, 0x8c, 0xf0, 0x7c, 0x7c, 0x5f,
- 0xe3, 0x8c, 0x83, 0x8c, 0x29, 0x0b, 0x0b, 0x02,
- 0x03, 0x8d, 0xe3, 0x8c, 0xfd, 0xfd, 0xfd, 0xfd,
- 0xe3, 0x8c, 0x03, 0x8d, 0x56, 0x5a, 0x5a, 0xaa,
- 0x03, 0x95, 0x23, 0x95, 0x55, 0x55, 0x55, 0x00,
- 0xc4, 0x9c, 0x23, 0x95, 0x55, 0xf5, 0xf5, 0x2f,
- 0x24, 0x9c, 0xe4, 0x94, 0xf5, 0xbd, 0xbd, 0x02,
- 0x25, 0xa4, 0x84, 0x94, 0xa9, 0x2a, 0x2a, 0x00,
- 0x06, 0xb4, 0x45, 0xa4, 0xfd, 0xaf, 0xaf, 0x0a,
-};
-
-static uint8 kdxt1_256x256_alpha[128] = {
- 0x00, 0x00, 0x01, 0x00, 0xff, 0xff, 0xff, 0xff,
- 0x00, 0x00, 0x01, 0x00, 0xff, 0xff, 0xff, 0xff,
- 0x00, 0x00, 0x01, 0x00, 0xff, 0xff, 0xff, 0xff,
- 0x00, 0x00, 0x01, 0x00, 0xff, 0xff, 0xff, 0xff,
- 0x00, 0x00, 0x01, 0x00, 0xff, 0xff, 0xff, 0xff,
- 0x00, 0x00, 0x01, 0x00, 0xff, 0xff, 0xff, 0xff,
- 0x00, 0x00, 0x01, 0x00, 0xff, 0xff, 0xff, 0xff,
- 0x00, 0x00, 0x01, 0x00, 0xff, 0xff, 0xff, 0xff,
- 0x02, 0x85, 0xe3, 0x8c, 0xff, 0x7f, 0x7f, 0x7f,
- 0xe3, 0x8c, 0x03, 0x8d, 0xa8, 0xa8, 0xa8, 0xa8,
- 0xe3, 0x8c, 0x03, 0x8d, 0x56, 0x5a, 0x5a, 0xaa,
- 0x03, 0x95, 0x23, 0x95, 0x55, 0x55, 0x55, 0x00,
- 0xe4, 0x94, 0x23, 0x95, 0x95, 0xa5, 0xa5, 0xca,
- 0xa4, 0x94, 0x04, 0x95, 0xf9, 0xfe, 0xfe, 0xff,
- 0x00, 0x00, 0x01, 0x00, 0xff, 0xff, 0xff, 0xff,
- 0x00, 0x00, 0x01, 0x00, 0xff, 0xff, 0xff, 0xff,
-};
-
-static uint8 kdxt1_256x256_mipmap[128] = {
- 0x47, 0xbc, 0x06, 0xb4, 0x5a, 0x6a, 0x6a, 0xea,
- 0x27, 0xb4, 0x06, 0xb4, 0x57, 0x57, 0x57, 0x5e,
- 0x06, 0xb4, 0x07, 0xb4, 0xaa, 0xaa, 0xaa, 0xaa,
- 0x06, 0xb4, 0x07, 0xb4, 0xaa, 0xaa, 0xaa, 0xaa,
- 0x46, 0xbc, 0x07, 0xb4, 0xd5, 0xf5, 0xf5, 0xa5,
- 0x46, 0xbc, 0x27, 0xb4, 0xfd, 0xbf, 0xbf, 0xaf,
- 0x47, 0xbc, 0x65, 0xac, 0xaa, 0xea, 0xea, 0x7a,
- 0x46, 0xac, 0x83, 0x8c, 0xf0, 0x7c, 0x7c, 0x5f,
- 0xe3, 0x8c, 0x83, 0x8c, 0x29, 0x0b, 0x0b, 0x02,
- 0x03, 0x8d, 0xe3, 0x8c, 0xfd, 0xfd, 0xfd, 0xfd,
- 0xe3, 0x8c, 0x03, 0x8d, 0x56, 0x5a, 0x5a, 0xaa,
- 0x03, 0x95, 0x23, 0x95, 0x55, 0x55, 0x55, 0x00,
- 0xc4, 0x9c, 0x23, 0x95, 0x55, 0xf5, 0xf5, 0x2f,
- 0x24, 0x9c, 0xe4, 0x94, 0xf5, 0xbd, 0xbd, 0x02,
- 0x25, 0xa4, 0x84, 0x94, 0xa9, 0x2a, 0x2a, 0x00,
- 0x06, 0xb4, 0x45, 0xa4, 0xfd, 0xaf, 0xaf, 0x0a,
-};
-
-static uint8 kdxt3_256x256_alpha[128] = {
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x47, 0xbc, 0x06, 0xb4, 0x5a, 0x6a, 0x6a, 0xea,
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x27, 0xb4, 0x06, 0xb4, 0x57, 0x57, 0x57, 0x5e,
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x07, 0xb4, 0x06, 0xb4, 0xaa, 0xaa, 0xaa, 0xaa,
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x07, 0xb4, 0x06, 0xb4, 0xaa, 0xaa, 0xaa, 0xaa,
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x46, 0xbc, 0x07, 0xb4, 0xd5, 0xb5, 0xb5, 0xa5,
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x46, 0xbc, 0x27, 0xb4, 0xfd, 0xbf, 0xbf, 0xaf,
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x47, 0xbc, 0x65, 0xac, 0xaa, 0xea, 0xea, 0x7a,
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x46, 0xac, 0x83, 0x8c, 0xf0, 0x7c, 0x7c, 0x5f,
-};
-
-static uint8 kdxt3_256x256_mipmap[128] = {
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x47, 0xbc, 0x06, 0xb4, 0x5a, 0x6a, 0x6a, 0xea,
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x27, 0xb4, 0x06, 0xb4, 0x57, 0x57, 0x57, 0x5e,
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x07, 0xb4, 0x06, 0xb4, 0xaa, 0xaa, 0xaa, 0xaa,
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x07, 0xb4, 0x06, 0xb4, 0xaa, 0xaa, 0xaa, 0xaa,
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x46, 0xbc, 0x07, 0xb4, 0xd5, 0xb5, 0xb5, 0xa5,
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x46, 0xbc, 0x27, 0xb4, 0xfd, 0xbf, 0xbf, 0xaf,
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x47, 0xbc, 0x65, 0xac, 0xaa, 0xea, 0xea, 0x7a,
- 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77,
- 0x46, 0xac, 0x83, 0x8c, 0xf0, 0x7c, 0x7c, 0x5f,
-};
-
-static uint8 kdxt5_256x256_alpha[128] = {
- 0x7e, 0x77, 0xda, 0x23, 0x00, 0x90, 0x0a, 0x00,
- 0x47, 0xbc, 0x06, 0xb4, 0x5a, 0x6a, 0x6a, 0xea,
- 0x78, 0x76, 0x4e, 0x02, 0x00, 0x70, 0x02, 0x00,
- 0x27, 0xb4, 0x06, 0xb4, 0x57, 0x57, 0x57, 0x5e,
- 0x77, 0x75, 0x86, 0x61, 0x00, 0xb0, 0x6d, 0x00,
- 0x07, 0xb4, 0x06, 0xb4, 0xaa, 0xaa, 0xaa, 0xaa,
- 0x77, 0x76, 0x49, 0x82, 0x00, 0x41, 0x12, 0x00,
- 0x07, 0xb4, 0x06, 0xb4, 0xaa, 0xaa, 0xaa, 0xaa,
- 0x7c, 0x76, 0xc9, 0x77, 0x00, 0xff, 0x60, 0x00,
- 0x46, 0xbc, 0x07, 0xb4, 0xd5, 0xb5, 0xb5, 0xa5,
- 0x7c, 0x7a, 0x49, 0x60, 0x00, 0x36, 0x60, 0x00,
- 0x46, 0xbc, 0x27, 0xb4, 0xfd, 0xbf, 0xbf, 0xaf,
- 0x7e, 0x7c, 0x31, 0x60, 0x00, 0x06, 0x6c, 0x00,
- 0x47, 0xbc, 0x65, 0xac, 0xaa, 0xea, 0xea, 0x7a,
- 0x7d, 0x75, 0x50, 0x82, 0x00, 0x7c, 0x98, 0x00,
- 0x46, 0xac, 0x83, 0x8c, 0xf0, 0x7c, 0x7c, 0x5f,
-};
-
-static uint8 kdxt5_256x256_mipmap[128] = {
- 0x7e, 0x77, 0xda, 0x23, 0x00, 0x90, 0x0a, 0x00,
- 0x47, 0xbc, 0x06, 0xb4, 0x5a, 0x6a, 0x6a, 0xea,
- 0x78, 0x76, 0x4e, 0x02, 0x00, 0x70, 0x02, 0x00,
- 0x27, 0xb4, 0x06, 0xb4, 0x57, 0x57, 0x57, 0x5e,
- 0x77, 0x75, 0x86, 0x61, 0x00, 0xb0, 0x6d, 0x00,
- 0x07, 0xb4, 0x06, 0xb4, 0xaa, 0xaa, 0xaa, 0xaa,
- 0x77, 0x76, 0x49, 0x82, 0x00, 0x41, 0x12, 0x00,
- 0x07, 0xb4, 0x06, 0xb4, 0xaa, 0xaa, 0xaa, 0xaa,
- 0x7c, 0x76, 0xc9, 0x77, 0x00, 0xff, 0x60, 0x00,
- 0x46, 0xbc, 0x07, 0xb4, 0xd5, 0xb5, 0xb5, 0xa5,
- 0x7c, 0x7a, 0x49, 0x60, 0x00, 0x36, 0x60, 0x00,
- 0x46, 0xbc, 0x27, 0xb4, 0xfd, 0xbf, 0xbf, 0xaf,
- 0x7e, 0x7c, 0x31, 0x60, 0x00, 0x06, 0x6c, 0x00,
- 0x47, 0xbc, 0x65, 0xac, 0xaa, 0xea, 0xea, 0x7a,
- 0x7d, 0x75, 0x50, 0x82, 0x00, 0x7c, 0x98, 0x00,
- 0x46, 0xac, 0x83, 0x8c, 0xf0, 0x7c, 0x7c, 0x5f,
-};
-
-// Match the first 128 bytes of a loaded bitmap data againt known values.
-bool TestBitmapData(const Bitmap &bitmap, uint8 reference[128]) {
- if (!bitmap.image_data()) return false;
- return std::memcmp(bitmap.image_data(), reference, sizeof(reference)) == 0;
-}
-
-// Prints the first 128 bytes of a loaded bitmap data. Helper function to
-// generate the known data above.
-bool PrintBitmapData(const Bitmap &bitmap, const char *name) {
- const uint8 *data = bitmap.image_data();
- if (!data) return false;
- printf("static uint8 %s[128] = {\n", name);
- for (int i = 0; i < 16; ++i) {
- printf(" ");
- for (int j = 0; j < 8; ++j) {
- printf(" 0x%02x,", data[i*8+j]);
- }
- printf("\n");
- }
- printf("};\n");
- return true;
-}
-
-
-// -----------------------------------------------------------------------------
-
-TEST_F(BitmapTest, Basic) {
- EXPECT_EQ(static_cast<int>(Bitmap::FACE_NEGATIVE_X),
- static_cast<int>(TextureCUBE::FACE_NEGATIVE_X));
- EXPECT_EQ(static_cast<int>(Bitmap::FACE_NEGATIVE_Y),
- static_cast<int>(TextureCUBE::FACE_NEGATIVE_Y));
- EXPECT_EQ(static_cast<int>(Bitmap::FACE_NEGATIVE_Z),
- static_cast<int>(TextureCUBE::FACE_NEGATIVE_Z));
- EXPECT_EQ(static_cast<int>(Bitmap::FACE_POSITIVE_X),
- static_cast<int>(TextureCUBE::FACE_POSITIVE_X));
- EXPECT_EQ(static_cast<int>(Bitmap::FACE_POSITIVE_Y),
- static_cast<int>(TextureCUBE::FACE_POSITIVE_Y));
- EXPECT_EQ(static_cast<int>(Bitmap::FACE_POSITIVE_Z),
- static_cast<int>(TextureCUBE::FACE_POSITIVE_Z));
- Bitmap::Ref bitmap(new Bitmap(g_service_locator));
- ASSERT_FALSE(bitmap.IsNull());
- EXPECT_TRUE(bitmap->IsA(Bitmap::GetApparentClass()));
- EXPECT_TRUE(bitmap->IsA(ParamObject::GetApparentClass()));
- EXPECT_TRUE(bitmap->image_data() == NULL);
- EXPECT_EQ(Texture::UNKNOWN_FORMAT, bitmap->format());
- EXPECT_EQ(0u, bitmap->width());
- EXPECT_EQ(0u, bitmap->height());
- EXPECT_EQ(0u, bitmap->num_mipmaps());
- EXPECT_EQ(Bitmap::IMAGE, bitmap->semantic());
-}
-
-// Loads a 24 bit TGA file, checks it against the known data.
-TEST_F(BitmapTest, LoadTGAFile24bit) {
- // Load the texture object from a file.
- String filename = *g_program_path + "/bitmap_test/tga-256x256-24bit.tga";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::TGA, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::XRGB8, bitmap->format());
- EXPECT_EQ(256U, bitmap->width());
- EXPECT_EQ(256U, bitmap->height());
- EXPECT_EQ(1U, bitmap->num_mipmaps());
- EXPECT_TRUE(TestBitmapData(*bitmap, ktga256x256_24bit_BGRX));
-}
-
-// Loads a 32 bit TGA file, checks it against the known data.
-TEST_F(BitmapTest, LoadTGAFile32bit) {
- String filename = *g_program_path + "/bitmap_test/tga-256x256-32bit.tga";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::TGA, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::ARGB8, bitmap->format());
- EXPECT_EQ(256U, bitmap->width());
- EXPECT_EQ(256U, bitmap->height());
- EXPECT_EQ(1U, bitmap->num_mipmaps());
- EXPECT_TRUE(TestBitmapData(*bitmap, ktga256x256_32bit_BGRA));
-}
-
-// Tries to load a 5kx5k TGA file, which should fail.
-TEST_F(BitmapTest, LoadTGAFileTooLarge) {
- // NOTE: the 5kx5k.tga file only has the first 4k bytes, to avoid
- // creating a 100MB test file. The code reads the header (first 18 bytes),
- // but bails before reading the actual image bytes.
- String filename = *g_program_path + "/bitmap_test/5kx5k.tga";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_FALSE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::TGA, &bitmaps));
- EXPECT_EQ(0u, bitmaps.size());
-}
-
-// Loads a JPEG file, checks it against the known data.
-TEST_F(BitmapTest, LoadJPEGFile) {
- String filename = *g_program_path + "/bitmap_test/jpeg-256x256.jpg";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::JPEG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::XRGB8, bitmap->format());
- EXPECT_EQ(256U, bitmap->width());
- EXPECT_EQ(256U, bitmap->height());
- EXPECT_EQ(1U, bitmap->num_mipmaps());
- EXPECT_TRUE(TestBitmapData(*bitmap, kjpg256x256_BGRX));
-}
-
-// Tries to load a 5kx5k JPEG file, which should fail.
-TEST_F(BitmapTest, LoadJPEGFileTooLarge) {
- String filename = *g_program_path + "/bitmap_test/5kx5k.jpg";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_FALSE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::JPEG, &bitmaps));
- EXPECT_EQ(0u, bitmaps.size());
-}
-
-// Loads a 24 bit PNG file, checks it against the known data.
-TEST_F(BitmapTest, LoadPNGFile24bit) {
- String filename = *g_program_path + "/bitmap_test/png-256x256-24bit.png";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::XRGB8, bitmap->format());
- EXPECT_EQ(256U, bitmap->width());
- EXPECT_EQ(256U, bitmap->height());
- EXPECT_EQ(1U, bitmap->num_mipmaps());
- EXPECT_TRUE(TestBitmapData(*bitmap, kpng256x256_24bit_BGRX));
-}
-
-// Loads a 24 bit interlaced PNG file, checks it against the known data.
-TEST_F(BitmapTest, LoadPNGFile24bitInterlaced) {
- String filename = *g_program_path +
- "/bitmap_test/png-256x256-24bit-interlaced.png";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::XRGB8, bitmap->format());
- EXPECT_EQ(256U, bitmap->width());
- EXPECT_EQ(256U, bitmap->height());
- EXPECT_EQ(1U, bitmap->num_mipmaps());
- EXPECT_TRUE(TestBitmapData(*bitmap, kpng256x256_24bit_interlaced_BGRX));
-}
-
-TEST_F(BitmapTest, LoadPNGFile32bit) {
- String filename = *g_program_path + "/bitmap_test/png-256x256-32bit.png";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::ARGB8, bitmap->format());
- EXPECT_EQ(256U, bitmap->width());
- EXPECT_EQ(256U, bitmap->height());
- EXPECT_EQ(1U, bitmap->num_mipmaps());
- EXPECT_TRUE(TestBitmapData(*bitmap, kpng256x256_32bit_BGRA));
-}
-
-// Loads a palettized PNG file, checks it against the known data.
-TEST_F(BitmapTest, LoadPNGFile8bitPalette) {
- String filename = *g_program_path +
- "/bitmap_test/png-256x256-8bit-palette.png";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::XRGB8, bitmap->format());
- EXPECT_EQ(256U, bitmap->width());
- EXPECT_EQ(256U, bitmap->height());
- EXPECT_EQ(1U, bitmap->num_mipmaps());
- EXPECT_TRUE(TestBitmapData(*bitmap, kpng256x256_8bit_palette_BGRX));
-}
-
-// Loads a palettized PNG file, checks it against the known data.
-TEST_F(BitmapTest, LoadPNGFile4bitPalette) {
- String filename = *g_program_path +
- "/bitmap_test/png-20x14-4bit-palette.png";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::XRGB8, bitmap->format());
- EXPECT_EQ(20U, bitmap->width());
- EXPECT_EQ(14U, bitmap->height());
- EXPECT_EQ(1U, bitmap->num_mipmaps());
- EXPECT_TRUE(TestBitmapData(*bitmap, kpng20x14_4bit_palette_BGRX));
-}
-
-
-// Tries to load a 5kx5k PNG file, which should fail.
-TEST_F(BitmapTest, LoadPNGFileTooLarge) {
- String filename = *g_program_path + "/bitmap_test/5kx5k.png";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_FALSE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::PNG, &bitmaps));
- EXPECT_EQ(0u, bitmaps.size());
-}
-
-// NOTE: Having trouble recognising the alpha channel in a PNG
-// exported from Photoshop.
-/*
-TEST_F(BitmapTest, LoadPNGFile8bitPaletteAlpha) {
- String filename = *g_program_path +
- "/bitmap_test/png-256x256-8bit-palette-alpha.png";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::ARGB8, bitmap->format());
- EXPECT_EQ(256U, bitmap->width());
- EXPECT_EQ(256U, bitmap->height());
- EXPECT_EQ(1U, bitmap->num_mipmaps());
-}
-*/
-
-// Loads a DXT1 DDS file, checks the format.
-TEST_F(BitmapTest, LoadDDSFileDXT1) {
- String filename = *g_program_path + "/bitmap_test/dds-dxt1-256x256.dds";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::DDS, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::DXT1, bitmap->format());
- EXPECT_EQ(256U, bitmap->width());
- EXPECT_EQ(256U, bitmap->height());
- EXPECT_EQ(1U, bitmap->num_mipmaps());
- EXPECT_TRUE(TestBitmapData(*bitmap, kdxt1_256x256));
-}
-
-// Loads a DXT1 DDS file with alpha, checks the format.
-TEST_F(BitmapTest, LoadDDSFileDXT1Alpha) {
- String filename = *g_program_path +
- "/bitmap_test/dds-dxt1-256x256-alpha.dds";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::DDS, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::DXT1, bitmap->format());
- EXPECT_EQ(256U, bitmap->width());
- EXPECT_EQ(256U, bitmap->height());
- EXPECT_EQ(1U, bitmap->num_mipmaps());
- EXPECT_TRUE(TestBitmapData(*bitmap, kdxt1_256x256_alpha));
-}
-
-// Loads a DXT1 DDS file with mipmaps, checks the format.
-TEST_F(BitmapTest, LoadDDSFileDXT1Mipmap) {
- String filename = *g_program_path +
- "/bitmap_test/dds-dxt1-256x256-mipmap.dds";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::DDS, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::DXT1, bitmap->format());
- EXPECT_EQ(256U, bitmap->width());
- EXPECT_EQ(256U, bitmap->height());
- EXPECT_EQ(9U, bitmap->num_mipmaps());
- for (unsigned int i = 0; i < bitmap->num_mipmaps(); ++i) {
- EXPECT_TRUE(bitmap->GetMipData(i) != NULL);
- }
- EXPECT_TRUE(TestBitmapData(*bitmap, kdxt1_256x256_mipmap));
-}
-
-// Loads a DXT3 DDS file, checks the format.
-TEST_F(BitmapTest, LoadDDSFileDXT3) {
- String filename = *g_program_path +
- "/bitmap_test/dds-dxt3-256x256-alpha.dds";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::DDS, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::DXT3, bitmap->format());
- EXPECT_EQ(256U, bitmap->width());
- EXPECT_EQ(256U, bitmap->height());
- EXPECT_EQ(1U, bitmap->num_mipmaps());
- EXPECT_TRUE(TestBitmapData(*bitmap, kdxt3_256x256_alpha));
-}
-
-// Loads a DXT3 DDS file with mipmaps, checks the format.
-TEST_F(BitmapTest, LoadDDSFileDXT3Mipmap) {
- String filename = *g_program_path +
- "/bitmap_test/dds-dxt3-256x256-mipmap.dds";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::DDS, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::DXT3, bitmap->format());
- EXPECT_EQ(256U, bitmap->width());
- EXPECT_EQ(256U, bitmap->height());
- EXPECT_EQ(9U, bitmap->num_mipmaps());
- for (unsigned int i = 0; i < bitmap->num_mipmaps(); ++i) {
- EXPECT_TRUE(bitmap->GetMipData(i) != NULL);
- }
- EXPECT_TRUE(TestBitmapData(*bitmap, kdxt3_256x256_mipmap));
-}
-
-// Loads a DXT5 DDS file, checks the format.
-TEST_F(BitmapTest, LoadDDSFileDXT5) {
- String filename = *g_program_path +
- "/bitmap_test/dds-dxt5-256x256-alpha.dds";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::DDS, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::DXT5, bitmap->format());
- EXPECT_EQ(256U, bitmap->width());
- EXPECT_EQ(256U, bitmap->height());
- EXPECT_EQ(1U, bitmap->num_mipmaps());
- EXPECT_TRUE(TestBitmapData(*bitmap, kdxt5_256x256_alpha));
-}
-
-// Loads a DXT5 DDS file with mipmaps, checks the format.
-TEST_F(BitmapTest, LoadDDSFileDXT5Mipmap) {
- String filename = *g_program_path +
- "/bitmap_test/dds-dxt5-256x256-mipmap.dds";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::DDS, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap* bitmap = bitmaps[0].Get();
- EXPECT_TRUE(bitmap->image_data() != NULL);
- EXPECT_EQ(Texture::DXT5, bitmap->format());
- EXPECT_EQ(256U, bitmap->width());
- EXPECT_EQ(256U, bitmap->height());
- EXPECT_EQ(9U, bitmap->num_mipmaps());
- for (unsigned int i = 0; i < bitmap->num_mipmaps(); ++i) {
- EXPECT_TRUE(bitmap->GetMipData(i) != NULL);
- }
- EXPECT_TRUE(TestBitmapData(*bitmap, kdxt5_256x256_mipmap));
-}
-
-// Tries to load a 5kx5k DDS file, which should fail.
-TEST_F(BitmapTest, LoadDDSFileTooLarge) {
- // NOTE: the 5kx5k.dds file only has the first 4k bytes, to avoid
- // creating a 100MB test file. The code reads the header (first 128 bytes),
- // but bails before reading the actual image bytes.
- String filename = *g_program_path + "/bitmap_test/5kx5k.dds";
- FilePath filepath = UTF8ToFilePath(filename);
- BitmapRefArray bitmaps;
- EXPECT_FALSE(Bitmap::LoadFromFile(
- g_service_locator, filepath, image::DDS, &bitmaps));
- EXPECT_EQ(0u, bitmaps.size());
-}
-
-static uint8 kpng_8x4_drawImage[128] = {
- // Raw dest image used in drawimage test.
- 0x30, 0x60, 0xc0, 0xff, 0x32, 0x64, 0xc8, 0xff,
- 0x34, 0x68, 0xd0, 0xff, 0x36, 0x6c, 0xd8, 0xff,
- 0x38, 0x70, 0xe0, 0xff, 0x3a, 0x74, 0xe8, 0xff,
- 0x3c, 0x78, 0xf0, 0xff, 0x3e, 0x7c, 0xf8, 0xff,
- 0x20, 0x40, 0x80, 0xff, 0x22, 0x44, 0x88, 0xff,
- 0x24, 0x48, 0x90, 0xff, 0x26, 0x4c, 0x98, 0xff,
- 0x28, 0x50, 0xa0, 0xff, 0x2a, 0x54, 0xa8, 0xff,
- 0x2c, 0x58, 0xb0, 0xff, 0x2e, 0x5c, 0xb8, 0xff,
- 0x10, 0x20, 0x40, 0xff, 0x12, 0x24, 0x48, 0xff,
- 0x14, 0x28, 0x50, 0xff, 0x16, 0x2c, 0x58, 0xff,
- 0x18, 0x30, 0x60, 0xff, 0x1a, 0x34, 0x68, 0xff,
- 0x1c, 0x38, 0x70, 0xff, 0x1e, 0x3c, 0x78, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0x02, 0x04, 0x08, 0xff,
- 0x04, 0x08, 0x10, 0xff, 0x06, 0x0c, 0x18, 0xff,
- 0x08, 0x10, 0x20, 0xff, 0x0a, 0x14, 0x28, 0xff,
- 0x0c, 0x18, 0x30, 0xff, 0x0e, 0x1c, 0x38, 0xff,
-};
-
-static uint8 kpng_8x4_drawImage_top_left[128] = {
- // expected result of drawimage on top left corner of dest image.
- 0x28, 0x28, 0x28, 0xff, 0x29, 0x29, 0x29, 0xff,
- 0x2a, 0x2a, 0x2a, 0xff, 0x36, 0x6c, 0xd8, 0xff,
- 0x38, 0x70, 0xe0, 0xff, 0x3a, 0x74, 0xe8, 0xff,
- 0x3c, 0x78, 0xf0, 0xff, 0x3e, 0x7c, 0xf8, 0xff,
- 0x24, 0x24, 0x24, 0xff, 0x25, 0x25, 0x25, 0xff,
- 0x26, 0x26, 0x26, 0xff, 0x26, 0x4c, 0x98, 0xff,
- 0x28, 0x50, 0xa0, 0xff, 0x2a, 0x54, 0xa8, 0xff,
- 0x2c, 0x58, 0xb0, 0xff, 0x2e, 0x5c, 0xb8, 0xff,
- 0x20, 0x20, 0x20, 0xff, 0x21, 0x21, 0x21, 0xff,
- 0x22, 0x22, 0x22, 0xff, 0x16, 0x2c, 0x58, 0xff,
- 0x18, 0x30, 0x60, 0xff, 0x1a, 0x34, 0x68, 0xff,
- 0x1c, 0x38, 0x70, 0xff, 0x1e, 0x3c, 0x78, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0x02, 0x04, 0x08, 0xff,
- 0x04, 0x08, 0x10, 0xff, 0x06, 0x0c, 0x18, 0xff,
- 0x08, 0x10, 0x20, 0xff, 0x0a, 0x14, 0x28, 0xff,
- 0x0c, 0x18, 0x30, 0xff, 0x0e, 0x1c, 0x38, 0xff,
-};
-
-static uint8 kpng_8x4_drawImage_top[128] = {
- // expected result of drawimage on top bound of dest image.
- 0x30, 0x60, 0xc0, 0xff, 0x32, 0x64, 0xc8, 0xff,
- 0x34, 0x68, 0xd0, 0xff, 0x36, 0x6c, 0xd8, 0xff,
- 0x38, 0x70, 0xe0, 0xff, 0x3a, 0x74, 0xe8, 0xff,
- 0x3c, 0x78, 0xf0, 0xff, 0x3e, 0x7c, 0xf8, 0xff,
- 0x20, 0x40, 0x80, 0xff, 0x22, 0x44, 0x88, 0xff,
- 0x24, 0x48, 0x90, 0xff, 0x26, 0x4c, 0x98, 0xff,
- 0x28, 0x50, 0xa0, 0xff, 0x2a, 0x54, 0xa8, 0xff,
- 0x2c, 0x58, 0xb0, 0xff, 0x2e, 0x5c, 0xb8, 0xff,
- 0x10, 0x20, 0x40, 0xff, 0x12, 0x24, 0x48, 0xff,
- 0x2b, 0x2b, 0x2b, 0xff, 0x2c, 0x2c, 0x2c, 0xff,
- 0x2d, 0x2d, 0x2d, 0xff, 0x2e, 0x2e, 0x2e, 0xff,
- 0x1c, 0x38, 0x70, 0xff, 0x1e, 0x3c, 0x78, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0x02, 0x04, 0x08, 0xff,
- 0x27, 0x27, 0x27, 0xff, 0x28, 0x28, 0x28, 0xff,
- 0x29, 0x29, 0x29, 0xff, 0x2a, 0x2a, 0x2a, 0xff,
- 0x0c, 0x18, 0x30, 0xff, 0x0e, 0x1c, 0x38, 0xff,
-};
-
-static uint8 kpng_8x4_drawImage_top_right[128] = {
- // expected result of drawimage on top right corner of dest image.
- 0x30, 0x60, 0xc0, 0xff, 0x32, 0x64, 0xc8, 0xff,
- 0x34, 0x68, 0xd0, 0xff, 0x36, 0x6c, 0xd8, 0xff,
- 0x38, 0x70, 0xe0, 0xff, 0x3a, 0x74, 0xe8, 0xff,
- 0x3c, 0x78, 0xf0, 0xff, 0x3e, 0x7c, 0xf8, 0xff,
- 0x20, 0x40, 0x80, 0xff, 0x22, 0x44, 0x88, 0xff,
- 0x24, 0x48, 0x90, 0xff, 0x26, 0x4c, 0x98, 0xff,
- 0x28, 0x50, 0xa0, 0xff, 0x2b, 0x2b, 0x2b, 0xff,
- 0x2c, 0x2c, 0x2c, 0xff, 0x2d, 0x2d, 0x2d, 0xff,
- 0x10, 0x20, 0x40, 0xff, 0x12, 0x24, 0x48, 0xff,
- 0x14, 0x28, 0x50, 0xff, 0x16, 0x2c, 0x58, 0xff,
- 0x18, 0x30, 0x60, 0xff, 0x27, 0x27, 0x27, 0xff,
- 0x28, 0x28, 0x28, 0xff, 0x29, 0x29, 0x29, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0x02, 0x04, 0x08, 0xff,
- 0x04, 0x08, 0x10, 0xff, 0x06, 0x0c, 0x18, 0xff,
- 0x08, 0x10, 0x20, 0xff, 0x23, 0x23, 0x23, 0xff,
- 0x24, 0x24, 0x24, 0xff, 0x25, 0x25, 0x25, 0xff,
-};
-
-static uint8 kpng_8x4_drawImage_right[128] = {
- // expected result of drawimage on right bound of dest image.
- 0x30, 0x60, 0xc0, 0xff, 0x32, 0x64, 0xc8, 0xff,
- 0x34, 0x68, 0xd0, 0xff, 0x36, 0x6c, 0xd8, 0xff,
- 0x38, 0x70, 0xe0, 0xff, 0x2b, 0x2b, 0x2b, 0xff,
- 0x2c, 0x2c, 0x2c, 0xff, 0x2d, 0x2d, 0x2d, 0xff,
- 0x20, 0x40, 0x80, 0xff, 0x22, 0x44, 0x88, 0xff,
- 0x24, 0x48, 0x90, 0xff, 0x26, 0x4c, 0x98, 0xff,
- 0x28, 0x50, 0xa0, 0xff, 0x27, 0x27, 0x27, 0xff,
- 0x28, 0x28, 0x28, 0xff, 0x29, 0x29, 0x29, 0xff,
- 0x10, 0x20, 0x40, 0xff, 0x12, 0x24, 0x48, 0xff,
- 0x14, 0x28, 0x50, 0xff, 0x16, 0x2c, 0x58, 0xff,
- 0x18, 0x30, 0x60, 0xff, 0x23, 0x23, 0x23, 0xff,
- 0x24, 0x24, 0x24, 0xff, 0x25, 0x25, 0x25, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0x02, 0x04, 0x08, 0xff,
- 0x04, 0x08, 0x10, 0xff, 0x06, 0x0c, 0x18, 0xff,
- 0x08, 0x10, 0x20, 0xff, 0x1f, 0x1f, 0x1f, 0xff,
- 0x20, 0x20, 0x20, 0xff, 0x21, 0x21, 0x21, 0xff,
-};
-
-static uint8 kpng_8x4_drawImage_bottom_right[128] = {
- // expected result of drawimage on bottom right corner of dest image.
- 0x30, 0x60, 0xc0, 0xff, 0x32, 0x64, 0xc8, 0xff,
- 0x34, 0x68, 0xd0, 0xff, 0x36, 0x6c, 0xd8, 0xff,
- 0x38, 0x70, 0xe0, 0xff, 0x27, 0x27, 0x27, 0xff,
- 0x28, 0x28, 0x28, 0xff, 0x29, 0x29, 0x29, 0xff,
- 0x20, 0x40, 0x80, 0xff, 0x22, 0x44, 0x88, 0xff,
- 0x24, 0x48, 0x90, 0xff, 0x26, 0x4c, 0x98, 0xff,
- 0x28, 0x50, 0xa0, 0xff, 0x23, 0x23, 0x23, 0xff,
- 0x24, 0x24, 0x24, 0xff, 0x25, 0x25, 0x25, 0xff,
- 0x10, 0x20, 0x40, 0xff, 0x12, 0x24, 0x48, 0xff,
- 0x14, 0x28, 0x50, 0xff, 0x16, 0x2c, 0x58, 0xff,
- 0x18, 0x30, 0x60, 0xff, 0x1f, 0x1f, 0x1f, 0xff,
- 0x20, 0x20, 0x20, 0xff, 0x21, 0x21, 0x21, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0x02, 0x04, 0x08, 0xff,
- 0x04, 0x08, 0x10, 0xff, 0x06, 0x0c, 0x18, 0xff,
- 0x08, 0x10, 0x20, 0xff, 0x0a, 0x14, 0x28, 0xff,
- 0x0c, 0x18, 0x30, 0xff, 0x0e, 0x1c, 0x38, 0xff,
-};
-
-static uint8 kpng_8x4_drawImage_bottom[128] = {
- // expected result of drawimage on bottom bound of dest image.
- 0x30, 0x60, 0xc0, 0xff, 0x32, 0x64, 0xc8, 0xff,
- 0x27, 0x27, 0x27, 0xff, 0x28, 0x28, 0x28, 0xff,
- 0x29, 0x29, 0x29, 0xff, 0x2a, 0x2a, 0x2a, 0xff,
- 0x3c, 0x78, 0xf0, 0xff, 0x3e, 0x7c, 0xf8, 0xff,
- 0x20, 0x40, 0x80, 0xff, 0x22, 0x44, 0x88, 0xff,
- 0x23, 0x23, 0x23, 0xff, 0x24, 0x24, 0x24, 0xff,
- 0x25, 0x25, 0x25, 0xff, 0x26, 0x26, 0x26, 0xff,
- 0x2c, 0x58, 0xb0, 0xff, 0x2e, 0x5c, 0xb8, 0xff,
- 0x10, 0x20, 0x40, 0xff, 0x12, 0x24, 0x48, 0xff,
- 0x1f, 0x1f, 0x1f, 0xff, 0x20, 0x20, 0x20, 0xff,
- 0x21, 0x21, 0x21, 0xff, 0x22, 0x22, 0x22, 0xff,
- 0x1c, 0x38, 0x70, 0xff, 0x1e, 0x3c, 0x78, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0x02, 0x04, 0x08, 0xff,
- 0x04, 0x08, 0x10, 0xff, 0x06, 0x0c, 0x18, 0xff,
- 0x08, 0x10, 0x20, 0xff, 0x0a, 0x14, 0x28, 0xff,
- 0x0c, 0x18, 0x30, 0xff, 0x0e, 0x1c, 0x38, 0xff,
-};
-
-static uint8 kpng_8x4_drawImage_bottom_left[128] = {
- // expected result of drawimage on bottom left corner of dest image.
- 0x30, 0x60, 0xc0, 0xff, 0x32, 0x64, 0xc8, 0xff,
- 0x34, 0x68, 0xd0, 0xff, 0x36, 0x6c, 0xd8, 0xff,
- 0x38, 0x70, 0xe0, 0xff, 0x3a, 0x74, 0xe8, 0xff,
- 0x3c, 0x78, 0xf0, 0xff, 0x3e, 0x7c, 0xf8, 0xff,
- 0x2c, 0x2c, 0x2c, 0xff, 0x2d, 0x2d, 0x2d, 0xff,
- 0x2e, 0x2e, 0x2e, 0xff, 0x26, 0x4c, 0x98, 0xff,
- 0x28, 0x50, 0xa0, 0xff, 0x2a, 0x54, 0xa8, 0xff,
- 0x2c, 0x58, 0xb0, 0xff, 0x2e, 0x5c, 0xb8, 0xff,
- 0x28, 0x28, 0x28, 0xff, 0x29, 0x29, 0x29, 0xff,
- 0x2a, 0x2a, 0x2a, 0xff, 0x16, 0x2c, 0x58, 0xff,
- 0x18, 0x30, 0x60, 0xff, 0x1a, 0x34, 0x68, 0xff,
- 0x1c, 0x38, 0x70, 0xff, 0x1e, 0x3c, 0x78, 0xff,
- 0x24, 0x24, 0x24, 0xff, 0x25, 0x25, 0x25, 0xff,
- 0x26, 0x26, 0x26, 0xff, 0x06, 0x0c, 0x18, 0xff,
- 0x08, 0x10, 0x20, 0xff, 0x0a, 0x14, 0x28, 0xff,
- 0x0c, 0x18, 0x30, 0xff, 0x0e, 0x1c, 0x38, 0xff,
-};
-
-static uint8 kpng_8x4_drawImage_left[128] = {
- // expected result of drawimage on left bound of dest image.
- 0x2c, 0x2c, 0x2c, 0xff, 0x2d, 0x2d, 0x2d, 0xff,
- 0x2e, 0x2e, 0x2e, 0xff, 0x36, 0x6c, 0xd8, 0xff,
- 0x38, 0x70, 0xe0, 0xff, 0x3a, 0x74, 0xe8, 0xff,
- 0x3c, 0x78, 0xf0, 0xff, 0x3e, 0x7c, 0xf8, 0xff,
- 0x28, 0x28, 0x28, 0xff, 0x29, 0x29, 0x29, 0xff,
- 0x2a, 0x2a, 0x2a, 0xff, 0x26, 0x4c, 0x98, 0xff,
- 0x28, 0x50, 0xa0, 0xff, 0x2a, 0x54, 0xa8, 0xff,
- 0x2c, 0x58, 0xb0, 0xff, 0x2e, 0x5c, 0xb8, 0xff,
- 0x24, 0x24, 0x24, 0xff, 0x25, 0x25, 0x25, 0xff,
- 0x26, 0x26, 0x26, 0xff, 0x16, 0x2c, 0x58, 0xff,
- 0x18, 0x30, 0x60, 0xff, 0x1a, 0x34, 0x68, 0xff,
- 0x1c, 0x38, 0x70, 0xff, 0x1e, 0x3c, 0x78, 0xff,
- 0x20, 0x20, 0x20, 0xff, 0x21, 0x21, 0x21, 0xff,
- 0x22, 0x22, 0x22, 0xff, 0x06, 0x0c, 0x18, 0xff,
- 0x08, 0x10, 0x20, 0xff, 0x0a, 0x14, 0x28, 0xff,
- 0x0c, 0x18, 0x30, 0xff, 0x0e, 0x1c, 0x38, 0xff,
-};
-
-static uint8 kpng_8x4_drawImage_scale_up[128] = {
- // expected result of scale up from 2x2 to 8x4.
- 0x38, 0x38, 0x38, 0xff, 0x43, 0x43, 0x43, 0xff,
- 0x52, 0x52, 0x52, 0xff, 0x63, 0x63, 0x63, 0xff,
- 0x77, 0x77, 0x77, 0xff, 0x88, 0x88, 0x88, 0xff,
- 0x96, 0x96, 0x96, 0xff, 0x90, 0x90, 0x90, 0xff,
- 0x25, 0x25, 0x25, 0xff, 0x2c, 0x2c, 0x2c, 0xff,
- 0x36, 0x36, 0x36, 0xff, 0x45, 0x45, 0x45, 0xff,
- 0x54, 0x54, 0x54, 0xff, 0x63, 0x63, 0x63, 0xff,
- 0x6e, 0x6e, 0x6e, 0xff, 0x69, 0x69, 0x69, 0xff,
- 0x0b, 0x0b, 0x0b, 0xff, 0x0d, 0x0d, 0x0d, 0xff,
- 0x13, 0x13, 0x13, 0xff, 0x1c, 0x1c, 0x1c, 0xff,
- 0x28, 0x28, 0x28, 0xff, 0x31, 0x31, 0x31, 0xff,
- 0x39, 0x39, 0x39, 0xff, 0x35, 0x35, 0x35, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff,
- 0x05, 0x05, 0x05, 0xff, 0x0c, 0x0c, 0x0c, 0xff,
- 0x11, 0x11, 0x11, 0xff, 0x0e, 0x0e, 0x0e, 0xff,
-};
-
-static uint8 kpng_8x4_drawImage_scale_down[128] = {
- // expected result of scale down from 8x8 to 4x4.
- 0xa0, 0xa0, 0xa0, 0xff, 0xa7, 0xa7, 0xa7, 0xff,
- 0xad, 0xad, 0xad, 0xff, 0xb3, 0xb3, 0xb3, 0xff,
- 0x38, 0x70, 0xe0, 0xff, 0x3a, 0x74, 0xe8, 0xff,
- 0x3c, 0x78, 0xf0, 0xff, 0x3e, 0x7c, 0xf8, 0xff,
- 0x6d, 0x6d, 0x6d, 0xff, 0x74, 0x74, 0x74, 0xff,
- 0x7a, 0x7a, 0x7a, 0xff, 0x80, 0x80, 0x80, 0xff,
- 0x28, 0x50, 0xa0, 0xff, 0x2a, 0x54, 0xa8, 0xff,
- 0x2c, 0x58, 0xb0, 0xff, 0x2e, 0x5c, 0xb8, 0xff,
- 0x3d, 0x3d, 0x3d, 0xff, 0x44, 0x44, 0x44, 0xff,
- 0x4a, 0x4a, 0x4a, 0xff, 0x50, 0x50, 0x50, 0xff,
- 0x18, 0x30, 0x60, 0xff, 0x1a, 0x34, 0x68, 0xff,
- 0x1c, 0x38, 0x70, 0xff, 0x1e, 0x3c, 0x78, 0xff,
- 0x0a, 0x0a, 0x0a, 0xff, 0x11, 0x11, 0x11, 0xff,
- 0x17, 0x17, 0x17, 0xff, 0x1d, 0x1d, 0x1d, 0xff,
- 0x08, 0x10, 0x20, 0xff, 0x0a, 0x14, 0x28, 0xff,
- 0x0c, 0x18, 0x30, 0xff, 0x0e, 0x1c, 0x38, 0xff,
-};
-
-static uint8 kpng_8x4_drawImage_scale_out[128] = {
- // expected result of scale src image larger than dest image.
- 0x7c, 0x7c, 0x7c, 0xff, 0x7e, 0x7e, 0x7e, 0xff,
- 0x80, 0x80, 0x80, 0xff, 0x82, 0x82, 0x82, 0xff,
- 0x85, 0x85, 0x85, 0xff, 0x87, 0x87, 0x87, 0xff,
- 0x89, 0x89, 0x89, 0xff, 0x8b, 0x8b, 0x8b, 0xff,
- 0x70, 0x70, 0x70, 0xff, 0x72, 0x72, 0x72, 0xff,
- 0x74, 0x74, 0x74, 0xff, 0x76, 0x76, 0x76, 0xff,
- 0x79, 0x79, 0x79, 0xff, 0x7b, 0x7b, 0x7b, 0xff,
- 0x7d, 0x7d, 0x7d, 0xff, 0x7f, 0x7f, 0x7f, 0xff,
- 0x56, 0x56, 0x56, 0xff, 0x58, 0x58, 0x58, 0xff,
- 0x5a, 0x5a, 0x5a, 0xff, 0x5c, 0x5c, 0x5c, 0xff,
- 0x5f, 0x5f, 0x5f, 0xff, 0x61, 0x61, 0x61, 0xff,
- 0x63, 0x63, 0x63, 0xff, 0x65, 0x65, 0x65, 0xff,
- 0x4a, 0x4a, 0x4a, 0xff, 0x4c, 0x4c, 0x4c, 0xff,
- 0x4e, 0x4e, 0x4e, 0xff, 0x50, 0x50, 0x50, 0xff,
- 0x53, 0x53, 0x53, 0xff, 0x55, 0x55, 0x55, 0xff,
- 0x57, 0x57, 0x57, 0xff, 0x59, 0x59, 0x59, 0xff,
-};
-
-static uint8 kpng_8x4_drawImage_flip[128] = {
- // expected result of flip src image.
- 0x30, 0x60, 0xc0, 0xff, 0x32, 0x64, 0xc8, 0xff,
- 0x22, 0x22, 0x22, 0xff, 0x21, 0x21, 0x21, 0xff,
- 0x20, 0x20, 0x20, 0xff, 0x1f, 0x1f, 0x1f, 0xff,
- 0x3c, 0x78, 0xf0, 0xff, 0x3e, 0x7c, 0xf8, 0xff,
- 0x20, 0x40, 0x80, 0xff, 0x22, 0x44, 0x88, 0xff,
- 0x26, 0x26, 0x26, 0xff, 0x25, 0x25, 0x25, 0xff,
- 0x24, 0x24, 0x24, 0xff, 0x23, 0x23, 0x23, 0xff,
- 0x2c, 0x58, 0xb0, 0xff, 0x2e, 0x5c, 0xb8, 0xff,
- 0x10, 0x20, 0x40, 0xff, 0x12, 0x24, 0x48, 0xff,
- 0x2a, 0x2a, 0x2a, 0xff, 0x29, 0x29, 0x29, 0xff,
- 0x28, 0x28, 0x28, 0xff, 0x27, 0x27, 0x27, 0xff,
- 0x1c, 0x38, 0x70, 0xff, 0x1e, 0x3c, 0x78, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0x02, 0x04, 0x08, 0xff,
- 0x2e, 0x2e, 0x2e, 0xff, 0x2d, 0x2d, 0x2d, 0xff,
- 0x2c, 0x2c, 0x2c, 0xff, 0x2b, 0x2b, 0x2b, 0xff,
- 0x0c, 0x18, 0x30, 0xff, 0x0e, 0x1c, 0x38, 0xff,
-};
-
-static uint8 kpng_8x4_drawImage_argb8[128] = {
- // expected result of drawimage with rgb8 format.
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0xca, 0xca, 0xca, 0x3e, 0xd7, 0xd7, 0xd7, 0x9a,
- 0x00, 0x00, 0x00, 0xee, 0x00, 0x00, 0x00, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff,
- 0x00, 0x00, 0x00, 0x00, 0xca, 0xca, 0xca, 0x3e,
- 0xe6, 0xe6, 0xe6, 0xdc, 0xfc, 0xfc, 0xfc, 0xfe,
- 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff,
- 0xca, 0xca, 0xca, 0x3e, 0xe6, 0xe6, 0xe6, 0xdc,
- 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff,
- 0xc7, 0xc7, 0xc7, 0x83, 0xf4, 0xf4, 0xf4, 0xfb,
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0x00, 0x00, 0x00, 0xeb, 0x00, 0x00, 0x00, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff,
-};
-
-// DrawImage from another bitmap on different positions,
-// compare with expected results.
-TEST_F(BitmapTest, DrawImage) {
- // path of dest image.
- String fname_dst = *g_program_path +
- "/bitmap_test/png-8x4-24bit-drawimage-dest.png";
- BitmapRefArray bitmaps;
- // load three src bitmaps in different sizes from files.
- String filename_2x2_src = *g_program_path +
- "/bitmap_test/png-2x2-24bit-drawimage-src.png";
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(filename_2x2_src),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_2x2_src(bitmaps[0]);
-
- String filename_4x4_src = *g_program_path +
- "/bitmap_test/png-4x4-24bit-drawimage-src.png";
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(filename_4x4_src),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_4x4_src(bitmaps[0]);
-
- String filename_8x8_src = *g_program_path +
- "/bitmap_test/png-8x8-24bit-drawimage-src.png";
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(filename_8x8_src),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_8x8_src(bitmaps[0]);
-
- // test draw image on top left boundary.
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(fname_dst),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_dest_top_left(bitmaps[0]);
- // test whether the raw image is loaded correctly or not.
- EXPECT_TRUE(bitmap_dest_top_left->image_data() != NULL);
- EXPECT_TRUE(TestBitmapData(*bitmap_dest_top_left, kpng_8x4_drawImage));
- bitmap_dest_top_left->DrawImage(
- *bitmap_4x4_src, 0, 0, 0, 4, 4, 0, -1, -1, 4, 4);
- EXPECT_TRUE(TestBitmapData(*bitmap_dest_top_left,
- kpng_8x4_drawImage_top_left));
-
- // test draw image on top boundary.
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(fname_dst),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_dest_top(bitmaps[0]);
- bitmap_dest_top->DrawImage(*bitmap_4x4_src, 0, 0, 0, 4, 4, 0, 2, -2, 4, 4);
- EXPECT_TRUE(TestBitmapData(*bitmap_dest_top, kpng_8x4_drawImage_top));
-
- // test draw image on top right boundary.
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(fname_dst),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_dest_top_right(bitmaps[0]);
- bitmap_dest_top_right->DrawImage(
- *bitmap_4x4_src, 0, 0, 0, 4, 4, 0, 5, -1, 4, 4);
- EXPECT_TRUE(TestBitmapData(*bitmap_dest_top_right,
- kpng_8x4_drawImage_top_right));
-
- // test draw image on right boundary.
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(fname_dst),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_dest_right(bitmaps[0]);
- bitmap_dest_right->DrawImage(*bitmap_4x4_src, 0, 0, 0, 4, 4, 0, 5, 0, 4, 4);
- EXPECT_TRUE(TestBitmapData(*bitmap_dest_right, kpng_8x4_drawImage_right));
-
- // test draw image on bottom right boundary.
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(fname_dst),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_dest_bottom_right(bitmaps[0]);
- bitmap_dest_bottom_right->DrawImage(
- *bitmap_4x4_src, 0, 0, 0, 4, 4, 0, 5, 1, 4, 4);
- EXPECT_TRUE(TestBitmapData(*bitmap_dest_bottom_right,
- kpng_8x4_drawImage_bottom_right));
-
- // test draw image on bottom boundary.
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(fname_dst),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_dest_bottom(bitmaps[0]);
- bitmap_dest_bottom->DrawImage(
- *bitmap_4x4_src, 0, 0, 0, 4, 4, 0, 2, 1, 4, 4);
- EXPECT_TRUE(TestBitmapData(*bitmap_dest_bottom, kpng_8x4_drawImage_bottom));
-
- // test draw image on bottom left boundary.
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(fname_dst),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_dest_bottom_left(bitmaps[0]);
- bitmap_dest_bottom_left->DrawImage(
- *bitmap_4x4_src, 0, 0, 0, 4, 4, 0, -1, 1, 4, 4);
- EXPECT_TRUE(TestBitmapData(*bitmap_dest_bottom_left,
- kpng_8x4_drawImage_bottom_left));
-
- // test draw image on left boundary.
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(fname_dst),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_dest_left(bitmaps[0]);
- bitmap_dest_left->DrawImage(*bitmap_4x4_src, 0, 0, 0, 4, 4, 0, -1, 0, 4, 4);
- EXPECT_TRUE(TestBitmapData(*bitmap_dest_left, kpng_8x4_drawImage_left));
-
- // test scale up.
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(fname_dst),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_dest_scale_up(bitmaps[0]);
- bitmap_dest_scale_up->DrawImage(
- *bitmap_2x2_src, 0, 0, 0, 2, 2, 0, 0, 0, 8, 4);
- EXPECT_TRUE(TestBitmapData(*bitmap_dest_scale_up,
- kpng_8x4_drawImage_scale_up));
-
- // test scale down.
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(fname_dst),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_dest_scale_down(bitmaps[0]);
- bitmap_dest_scale_down->DrawImage(
- *bitmap_8x8_src, 0, 0, 0, 8, 8, 0, 0, 0, 4, 4);
- EXPECT_TRUE(TestBitmapData(*bitmap_dest_scale_down,
- kpng_8x4_drawImage_scale_down));
-
- // test scale up to a large size.
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(fname_dst),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_dest_scale_out(bitmaps[0]);
- bitmap_dest_scale_out->DrawImage(
- *bitmap_8x8_src, 0, 0, 0, 8, 8, 0, -2, -4, 12, 12);
- EXPECT_TRUE(TestBitmapData(*bitmap_dest_scale_out,
- kpng_8x4_drawImage_scale_out));
-
- // test flip an image on both x and y cooridnates.
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(fname_dst),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_dest_flip(bitmaps[0]);
- bitmap_dest_flip->DrawImage(*bitmap_4x4_src, 0, 0, 0, 4, 4, 0, 5, 3, -4, -4);
- EXPECT_TRUE(TestBitmapData(*bitmap_dest_flip, kpng_8x4_drawImage_flip));
-
- // test draw image on argb8 format.
- String fname_dst_argb8 = *g_program_path +
- "/bitmap_test/" +
- "png-8x4-24bit-drawimage-argb8-dest.png";
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(fname_dst_argb8),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_dest_argb8(bitmaps[0]);
- String fname_src_argb8 = *g_program_path +
- "/bitmap_test/" +
- "png-4x4-24bit-drawimage-argb8-src.png";
- bitmaps.clear();
- EXPECT_TRUE(Bitmap::LoadFromFile(
- g_service_locator, UTF8ToFilePath(fname_src_argb8),
- image::PNG, &bitmaps));
- ASSERT_EQ(1u, bitmaps.size());
- Bitmap::Ref bitmap_src_argb8(bitmaps[0]);
- bitmap_dest_argb8->DrawImage(*bitmap_src_argb8, 0, 0, 0, 4, 4, 0, 0, 0, 4, 4);
- EXPECT_TRUE(TestBitmapData(*bitmap_dest_argb8, kpng_8x4_drawImage_argb8));
-}
-
-TEST_F(BitmapTest, SetRect) {
- Bitmap::Ref bitmap(new Bitmap(g_service_locator));
- const int kWidth = 8;
- const int kHeight = 8;
- const int kLevels = 2;
- const int kDestMip = 1;
- const unsigned kDestX = 1u;
- const unsigned kDestY = 1u;
- bitmap->Allocate(o3d::Texture::R32F, kWidth, kHeight, kLevels, Bitmap::IMAGE);
- const float* pixels =
- reinterpret_cast<const float*>(bitmap->GetMipData(kDestMip));
- static const float kExpected1[] = {
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f,
- };
- EXPECT_EQ(0, memcmp(pixels, kExpected1, sizeof(kExpected1)));
- const int kSrcWidth = 2;
- const int kSrcHeight = 2;
- static const float kSourcePixels[] = {
- 0.123f, 0.456f,
- 0.789f, 123.0f,
- };
- const int kSourcePitch = sizeof(kSourcePixels[0]) * kSrcWidth;
- // normal copy
- bitmap->SetRect(kDestMip, kDestX, kDestY,
- kSrcWidth, kSrcHeight, kSourcePixels, kSourcePitch);
- static const float kExpected2[] = {
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.123f, 0.456f, 0.0f,
- 0.0f, 0.789f, 123.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f,
- };
- EXPECT_EQ(0, memcmp(pixels, kExpected2, sizeof(kExpected2)));
- // flipped copy
- bitmap->SetRect(
- kDestMip, kDestX, kDestY,
- kSrcWidth, kSrcHeight,
- reinterpret_cast<const uint8*>(kSourcePixels) + kSourcePitch,
- -kSourcePitch);
- static const float kExpected3[] = {
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.789f, 123.0f, 0.0f,
- 0.0f, 0.123f, 0.456f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f,
- };
- EXPECT_EQ(0, memcmp(pixels, kExpected3, sizeof(kExpected3)));
-}
-
-} // namespace
diff --git a/o3d/core/cross/bitmap_tga.cc b/o3d/core/cross/bitmap_tga.cc
deleted file mode 100644
index 0404261..0000000
--- a/o3d/core/cross/bitmap_tga.cc
+++ /dev/null
@@ -1,145 +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 image file codec operations for OpenGL texture
-// loading.
-
-#include <stdio.h>
-#include "core/cross/bitmap.h"
-#include "utils/cross/file_path_utils.h"
-#include "base/file_path.h"
-#include "base/file_util.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-
-using file_util::OpenFile;
-using file_util::CloseFile;
-
-namespace o3d {
-
-// Loads the header information and raw RGB{A} data from an uncompressed
-// 24-bit or 32-bit TGA stream into the Bitmap object.
-bool Bitmap::LoadFromTGAStream(ServiceLocator* service_locator,
- MemoryReadStream *stream,
- const String &filename,
- BitmapRefArray* bitmaps) {
- // Read the magic header.
- uint8 file_magic[12];
- if (stream->Read(file_magic, sizeof(file_magic)) != sizeof(file_magic)) {
- DLOG(ERROR) << "Targa file magic not loaded \"" << filename << "\"";
- return false;
- }
- // Match the first few bytes of the TGA header to confirm we can read this
- // format. Multibyte values are stored little endian.
- static const uint8 kTargaMagic[12] = {
- 0, // ID Length (0 = no ID string present)
- 0, // Color Map Type ( 0 = no color map)
- 2, // Image Type (2 = Uncompressed True Color)
- 0, 0, // Color Map: First Entry Index (2 bytes)
- 0, 0, // Color Map: Table Length (2 bytes)
- 0, // Color Map: Entry Size
- 0, 0, // X-origin of image
- 0, 0, // Y-origin of image
- // MATCHED LATER: Image Width (2 bytes)
- // MATCHED LATER: Image Height (2 bytes)
- // MATCHED LATER: Pixel Depth (1 byte)
- // MATCHED LATER: Image Descriptor (1 byte, alpha:4bit, origin:2bit)
- };
-
- // TODO(gman): The most common targa format is compressed! We should support
- // that format or remove targa support completely. If we are keeping targa
- // format we should also support grayscale, 8bit indexed and 16bit formats.
- if (memcmp(kTargaMagic, file_magic, sizeof(kTargaMagic)) != 0) {
- DLOG(ERROR) << "Targa file subtype not recognized \"" << filename << "\"";
- return false;
- }
- // Read the image header.
- uint8 header[6];
- if (stream->Read(header, sizeof(header)) != sizeof(header)) {
- DLOG(ERROR) << "Targa file header not read \"" << filename << "\"";
- return false;
- }
- // Calculate image width and height, stored as little endian.
- unsigned int tga_width = header[1] * 256 + header[0];
- unsigned int tga_height = header[3] * 256 + header[2];
- if (!image::CheckImageDimensions(tga_width, tga_height)) {
- DLOG(ERROR) << "Failed to load " << filename
- << ": dimensions are too large (" << tga_width
- << ", " << tga_height << ").";
- return false;
- }
- unsigned int components = header[4] >> 3;
- // NOTE: Image Descriptor byte is skipped.
- if (components != 3 && components != 4) {
- DLOG(ERROR) << "Targa file \"" << filename
- << "\"has an unsupported number of components";
- return false;
- }
- // pixels contained in the file.
- unsigned int pixel_count = tga_width * tga_height;
- // Allocate storage for the pixels.
- Texture::Format format = components == 3 ? Texture::XRGB8 : Texture::ARGB8;
- // Allocate storage for the pixels. Bitmap requires we allocate enough
- // memory for all mips even if we don't use them.
- size_t image_size = Bitmap::ComputeMaxSize(tga_width, tga_height, format);
- scoped_array<uint8> image_data(new uint8[image_size]);
- if (image_data.get() == NULL) {
- DLOG(ERROR) << "Targa file memory allocation error \"" << filename << "\"";
- return false;
- }
- // Read in the bitmap data.
- size_t bytes_to_read = pixel_count * components;
- if (stream->Read(image_data.get(), bytes_to_read) != bytes_to_read) {
- DLOG(ERROR) << "Targa file read failed \"" << filename << "\"";
- return false;
- }
-
- if (components == 3) {
- // Fixup the image by inserting an alpha value of 1 (BGR->BGRX).
- image::XYZToXYZA(image_data.get(), pixel_count);
- }
-
- // Success.
- Bitmap::Ref bitmap(new Bitmap(service_locator));
- bitmap->SetContents(format, 1, tga_width, tga_height, IMAGE, &image_data);
- bitmaps->push_back(bitmap);
-
- // Targas are generally bottom first in memory so flip it.
- //
- // TODO(gman): In truth a targa can be any orientation. We should check
- // that orientation and flip or not flip accordingly.
- bitmap->FlipVertically();
-
- return true;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/bounding_box.cc b/o3d/core/cross/bounding_box.cc
deleted file mode 100644
index 8fd2cc2..0000000
--- a/o3d/core/cross/bounding_box.cc
+++ /dev/null
@@ -1,303 +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 definition of BoundingBox which is a class that
-// represents an Axis Aligned Bounding Box. It also contains the definition of
-// ParamBoundingBox, a Param that cointains a BoundingBox as well as
-// ParamBindFloat3sToBoundingBox which is a ParamBind that takes 2 Float3s and
-// converts them to a BoundingBox.
-
-#include "core/cross/bounding_box.h"
-#include "core/cross/ray_intersection_info.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(ParamBoundingBox, Param);
-// TODO: change this to a ParamOperation
-// O3D_DEFN_CLASS(ParamBindFloat3sToBoundingBox, ParamBind);
-
-// Adds a box to this box producing a bounding box that contains both.
-void BoundingBox::Add(const BoundingBox& box, BoundingBox* result) const {
- DLOG_ASSERT(result != NULL);
-
- if (valid() && box.valid()) {
- *result = BoundingBox(
- Vectormath::Aos::minPerElem(min_extent(), box.min_extent()),
- Vectormath::Aos::maxPerElem(max_extent(), box.max_extent()));
- } else if (valid()) {
- *result = *this;
- } else if (box.valid()) {
- *result = box;
- } else {
- *result = BoundingBox(); // will be an invalid box.
- }
-}
-
-// Computing the bounding box of this box re-oriented by multiplying by a
-// Matrix4.
-void BoundingBox::Mul(const Matrix4& matrix, BoundingBox* result) const {
- DLOG_ASSERT(result != NULL);
-
- Point3 min_extent((matrix * min_extent_).getXYZ());
- Point3 max_extent(min_extent);
-
- Point3 temp;
- temp = Point3((matrix * max_extent_).getXYZ()),
- min_extent = Vectormath::Aos::minPerElem(temp, min_extent);
- max_extent = Vectormath::Aos::maxPerElem(temp, max_extent);
- temp = Point3((matrix * Point3(min_extent_.getX(),
- max_extent_.getY(),
- min_extent_.getZ())).getXYZ());
- min_extent = Vectormath::Aos::minPerElem(temp, min_extent);
- max_extent = Vectormath::Aos::maxPerElem(temp, max_extent);
- temp = Point3((matrix * Point3(min_extent_.getX(),
- min_extent_.getY(),
- max_extent_.getZ())).getXYZ());
- min_extent = Vectormath::Aos::minPerElem(temp, min_extent);
- max_extent = Vectormath::Aos::maxPerElem(temp, max_extent);
- temp = Point3((matrix * Point3(min_extent_.getX(),
- max_extent_.getY(),
- max_extent_.getZ())).getXYZ());
- min_extent = Vectormath::Aos::minPerElem(temp, min_extent);
- max_extent = Vectormath::Aos::maxPerElem(temp, max_extent);
- temp = Point3((matrix * Point3(max_extent_.getX(),
- min_extent_.getY(),
- min_extent_.getZ())).getXYZ());
- min_extent = Vectormath::Aos::minPerElem(temp, min_extent);
- max_extent = Vectormath::Aos::maxPerElem(temp, max_extent);
- temp = Point3((matrix * Point3(max_extent_.getX(),
- max_extent_.getY(),
- min_extent_.getZ())).getXYZ());
- min_extent = Vectormath::Aos::minPerElem(temp, min_extent);
- max_extent = Vectormath::Aos::maxPerElem(temp, max_extent);
- temp = Point3((matrix * Point3(max_extent_.getX(),
- min_extent_.getY(),
- max_extent_.getZ())).getXYZ());
- min_extent = Vectormath::Aos::minPerElem(temp, min_extent);
- max_extent = Vectormath::Aos::maxPerElem(temp, max_extent);
-
- *result = BoundingBox(min_extent, max_extent);
-}
-
-// Adapted from: Fast Ray-Box Intersection by Andrew Woo from "Graphics Gems",
-// Academic Press, 1990
-void BoundingBox::IntersectRay(const Point3& start,
- const Point3& end,
- RayIntersectionInfo* result) const {
- DLOG_ASSERT(result != NULL);
-
- result->Reset();
- if (valid()) {
- result->set_valid(true);
- result->set_intersected(true); // Assume true.
-
- static const int kNumberOfDimensions = 3;
- static const int kRight = 0;
- static const int kLeft = 1;
- static const int kMiddle = 2;
-
- Vector3 dir(end - start);
- Point3 coord;
- bool inside = true;
- float quadrant[kNumberOfDimensions];
- int which_plane;
- float max_t[kNumberOfDimensions];
- float candidate_plane[kNumberOfDimensions];
-
- // Find candidate planes; this loop can be avoided if rays cast all from the
- // eye (assumes perpsective view).
- for (int i = 0; i < kNumberOfDimensions; ++i) {
- if (start[i] < min_extent_[i]) {
- quadrant[i] = kLeft;
- candidate_plane[i] = min_extent_[i];
- inside = false;
- } else if (start[i] > max_extent_[i]) {
- quadrant[i] = kRight;
- candidate_plane[i] = max_extent_[i];
- inside = false;
- } else {
- quadrant[i] = kMiddle;
- }
- }
-
- // Ray origin inside bounding box.
- if (inside) {
- // TODO: Should this return true? I feel like maybe not. Or
- // maybe ray_intersection_info should have a flag like "inside".
- result->set_position(start);
- } else {
- // Calculate T distances to candidate planes.
- for (int i = 0; i < kNumberOfDimensions; ++i) {
- if (quadrant[i] != kMiddle && dir[i] != 0.0f) {
- max_t[i] = (candidate_plane[i] - start[i]) / dir[i];
- } else {
- max_t[i] = -1.0f;
- }
- }
-
- // Get largest of the max_t's for final choice of intersection.
- which_plane = 0;
- for (int i = 1; i < kNumberOfDimensions; ++i) {
- if (max_t[which_plane] < max_t[i]) {
- which_plane = i;
- }
- }
-
- // Check final candidate actually inside box.
- if (max_t[which_plane] < 0.0f) {
- result->set_intersected(false);
- } else {
- for (int i = 0; i < kNumberOfDimensions; ++i) {
- if (which_plane != i) {
- coord[i] = start[i] + max_t[which_plane] * dir[i];
- if (coord[i] < min_extent_[i] || coord[i] > max_extent_[i]) {
- result->set_intersected(false);
- break;
- }
- } else {
- coord[i] = candidate_plane[i];
- }
- }
-
- // ray hits box.
- result->set_position(coord);
- }
- }
- }
-}
-
-// Returns true if the bounding box is inside the frustum matrix.
-// It checks all 8 corners of the bounding box against the 6 frustum planes
-// and determines whether there's at least one plane for which all 6 points lie
-// on the outside side of it. In that case it reports that the bounding box
-// is outside the frustum. Note that this is a conservative check in that
-// it in certain cases it will report that a box is in the frustum even if it
-// really isn't. However if it reports that the box is outside then it's
-// guaranteed to be outside.
-bool BoundingBox::InFrustum(const Matrix4& matrix) const {
- Point3 box_max = max_extent();
- Point3 box_min = min_extent();
-
- // Compute the 8 corners of the box in local space.
- Vector4 box_points[8] = {
- Vector4(box_min.getX(), box_max.getY(), box_min.getZ(), 1),
- Vector4(box_min.getX(), box_min.getY(), box_max.getZ(), 1),
- Vector4(box_min.getX(), box_max.getY(), box_max.getZ(), 1),
- Vector4(box_max.getX(), box_min.getY(), box_min.getZ(), 1),
- Vector4(box_max.getX(), box_max.getY(), box_min.getZ(), 1),
- Vector4(box_max.getX(), box_min.getY(), box_max.getZ(), 1),
- Vector4(box_max),
- Vector4(box_min)};
-
- // Convert the bounding box corners to screen space and test them against
- // the six planes of the frustum. The results of the tests are stored in six
- // consecutive bits in a bit field. A one denotes that the point is on the
- // outside of a particular frustum plane. The order of the bits is as
- // follows:
- // bit 0: x < -w
- // bit 1: x > w
- // bit 2: y < -w
- // bit 3: y > w
- // bit 4: z < 0
- // bit 5: z > w
- // The generated bitfields are ANDed together. If at the end any of the
- // resulting bits has a value of one then it means that all 8 points lie
- // outside of one of the frustum planes and hence the entire bounding box
- // is outside the frustum.
- unsigned char bb_test = 0xff;
- for (int i = 0; i < 8; i++) {
- // Compute the coordinates of the corner in screen space.
- Vector4 point = matrix * box_points[i];
-
- // Test against all 6 of the frustum planes.
- unsigned char test1 = point.getX() < -point.getW();
- unsigned char test2 = ((point.getX() > point.getW()) << 1);
- unsigned char test3 = ((point.getY() < -point.getW()) << 2);
- unsigned char test4 = ((point.getY() > point.getW()) << 3);
- unsigned char test5 = ((point.getZ() < 0) << 4);
- unsigned char test6 = ((point.getZ() > point.getW()) << 5);
-
- // Put all the results in a single bitfield.
- unsigned char test_bits = test1 | test2 | test3 | test4 | test5 | test6;
-
- // Check if any of the tests match with the results from the other points.
- bb_test &= test_bits;
-
- // Early out. If the points we processed so far there's not a single
- // frustum plane that they are all outside of, then there's no need to
- // continue.
- if (bb_test == 0)
- return true;
- }
-
- return (bb_test == 0);
-}
-
-ObjectBase::Ref ParamBoundingBox::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamBoundingBox(service_locator, false, false));
-}
-
-#if 0 // TODO: change this to a ParamOperation
-const char* ParamBindFloat3sToBoundingBox::kInput1Name = "Input1";
-const char* ParamBindFloat3sToBoundingBox::kInput2Name = "Input2";
-const char* ParamBindFloat3sToBoundingBox::kOutputName = "Output";
-
-ParamBindFloat3sToBoundingBox::ParamBindFloat3sToBoundingBox(const String& name)
- : ParamBind(service_locator) {
- RegisterInputPointer(kInput1Name, &source_bind_connection_1_);
- RegisterInputPointer(kInput2Name, &source_bind_connection_2_);
- RegisterOutputPointer(kOutputName, &destination_bind_connection_);
-}
-
-// Computes the product of the two source Params and stores the result in the
-// destination Param.
-void ParamBindFloat3sToBoundingBox::ComputeDestinationValues() {
- // Update the stored values of the two input Params
- UpdateSourceValues();
-
- Float3 value_1(source_bind_connection_1_->GetParam()->value());
- Float3 value_2(source_bind_connection_2_->GetParam()->value());
- ParamBoundingBox *dest_bounding_box =
- destination_bind_connection_->GetParam();
-
- dest_bounding_box->set_dynamic_value(
- BoundingBox(Point3(value_1[0], value_1[1], value_1[2]),
- Point3(value_2[0], value_2[1], value_2[2])));
-}
-
-ObjectBase::Ref ParamBindFloat3sToBoundingBox::Create(
- ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamBindFloat3sToBoundingBox(service_locator));
-}
-#endif
-
-} // namespace o3d
diff --git a/o3d/core/cross/bounding_box.h b/o3d/core/cross/bounding_box.h
deleted file mode 100644
index d83feb7..0000000
--- a/o3d/core/cross/bounding_box.h
+++ /dev/null
@@ -1,182 +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 declaration of BoundingBox which is a class that
-// represents an Axis Aligned Bounding Box. It also contains the declaration of
-// ParamBoundingBox, a Param that cointains a BoundingBox as well as
-// ParamBindFloat3sToBoundingBox which is a ParamBind that takes 2 Float3s and
-// converts them to a BoundingBox.
-
-#ifndef O3D_CORE_CROSS_BOUNDING_BOX_H_
-#define O3D_CORE_CROSS_BOUNDING_BOX_H_
-
-#include "core/cross/types.h"
-#include "core/cross/param.h"
-
-namespace o3d {
-
-class RayIntersectionInfo;
-
-// Defines a class that represents an Axis Aligned Bounding Box.
-class BoundingBox {
- public:
- // Constructs an uninitialized BoundingBox marking it as non valid.
- BoundingBox() : valid_(false), min_extent_(0, 0, 0), max_extent_(0, 0, 0) { }
-
- // Constructs a BoundingBox.
- // Parameters:
- // min_extent: minimum corner of the box.
- // max_extent: maximum corner of the box.
- BoundingBox(const Point3& min_extent, const Point3& max_extent)
- : valid_(true),
- min_extent_(Vectormath::Aos::minPerElem(min_extent, max_extent)),
- max_extent_(Vectormath::Aos::maxPerElem(min_extent, max_extent)) {
- }
-
- // True if this bounding box has been initialized.
- // Returns:
- // true if this bounding box has been initialized.
- bool valid() const {
- return valid_;
- }
-
- // The min extent of the box.
- // Returns:
- // the min extent of the box. If the box is not valid the return value
- // is undefined.
- const Point3& min_extent() const {
- return min_extent_;
- }
-
- // The max extent of the box.
- // Returns:
- // the max extent of the box. If the box is not valid the return value
- // is undefined.
- const Point3& max_extent() const {
- return max_extent_;
- }
-
- // Computing the bounding box of this box re-oriented by multiplying by a
- // Matrix4.
- // Paramaters:
- // matrix: Matrix4 to multiple by.
- // result: pointer to bounding box to store the result.
- void Mul(const Matrix4& matrix, BoundingBox* result) const;
-
- // Adds a bounding box to this box producing a bounding box that contains
- // both. If one box is invalid the result is the other box. If both boxes are
- // invalid the result will be an invalid box.
- // Parameters:
- // box: bounding box to add to this box.
- // result: pointer to bounding box to store the result.
- void Add(const BoundingBox& box, BoundingBox* result) const;
-
- // Checks if a ray defined in same coordinate system as this box intersects
- // this bounding box.
- // Parameters:
- // start: position of start of ray in local space.
- // end: position of end of ray in local space.
- // result: RayIntersectionInfo structure to fill out with results. If
- // result->valid() is false then something was wrong like using this
- // function with an uninitialized bounding box. If result->intersected()
- // is true then the ray intersected the box and result->position() is
- // the exact point of intersection.
- void IntersectRay(const Point3& start,
- const Point3& end,
- RayIntersectionInfo* result) const;
-
- // Returns true if the bounding box is inside the frustum.
- // Parameter:
- // matrix: Matrix to transform the box from its local space to view frustum
- // space.
- bool InFrustum(const Matrix4& matrix) const;
-
- private:
- bool valid_; // true if this bounding box has been initialized.
- Point3 min_extent_;
- Point3 max_extent_;
-};
-
-// A Param that contains a bounding box.
-class ParamBoundingBox : public TypedParam<BoundingBox> {
- public:
- typedef SmartPointer<ParamBoundingBox> Ref;
-
- protected:
- ParamBoundingBox(ServiceLocator* service_locator,
- bool dynamic,
- bool read_only)
- : TypedParam<BoundingBox>(service_locator, dynamic, read_only) {
- }
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamBoundingBox, Param);
- DISALLOW_COPY_AND_ASSIGN(ParamBoundingBox);
-};
-
-#if 0 // TODO: change this to a ParamOperation
-// A bind operation of 2 Float3s into a bounding box.
-class ParamBindFloat3sToBoundingBox : public ParamBind {
- public:
- typedef SmartPointer<ParamBindFloat3sToBoundingBox> Ref;
-
- static const char* kInput1Name;
- static const char* kInput2Name;
- static const char* kOutputName;
-
- // Creates a BoundingBox from 2 Float3s.
- virtual void ComputeDestinationValues();
-
- private:
- explicit ParamBindFloat3sToBoundingBox(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // The source Params.
- TypedBindConnection<ParamFloat3>* source_bind_connection_1_;
- TypedBindConnection<ParamFloat3>* source_bind_connection_2_;
-
- // The dest Param.
- TypedBindConnection<ParamBoundingBox>* destination_bind_connection_;
-
- O3D_DECL_CLASS(ParamBindFloat3sToBoundingBox, ParamBind)
- DISALLOW_COPY_AND_ASSIGN(ParamBindFloat3sToBoundingBox);
-};
-#endif
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_BOUNDING_BOX_H_
diff --git a/o3d/core/cross/bounding_box_test.cc b/o3d/core/cross/bounding_box_test.cc
deleted file mode 100644
index 62c5eac..0000000
--- a/o3d/core/cross/bounding_box_test.cc
+++ /dev/null
@@ -1,243 +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 implements unit tests for class BoundingBox.
-
-#include "core/cross/client.h"
-#include "tests/common/win/testing_common.h"
-#include "core/cross/bounding_box.h"
-#include "core/cross/math_utilities.h"
-#include "core/cross/ray_intersection_info.h"
-#include "core/cross/transform.h"
-#include "core/cross/renderer.h"
-
-namespace o3d {
-
-class BoundingBoxTest : public testing::Test {
-};
-
-// Tests the creation of a BoundingBox.
-TEST_F(BoundingBoxTest, Basic) {
- // Check that it defaults to invalid.
- EXPECT_FALSE(BoundingBox().valid());
-
- BoundingBox bounding_box(Point3(-1.0f, 2.0f, -3.0f),
- Point3(1.0f, -2.0f, 3.0f));
- // Check it's valid.
- EXPECT_TRUE(bounding_box.valid());
-
- // Check it got set.
- EXPECT_EQ(bounding_box.min_extent().getX(), -1.0f);
- EXPECT_EQ(bounding_box.min_extent().getY(), -2.0f);
- EXPECT_EQ(bounding_box.min_extent().getZ(), -3.0f);
- EXPECT_EQ(bounding_box.max_extent().getX(), 1.0f);
- EXPECT_EQ(bounding_box.max_extent().getY(), 2.0f);
- EXPECT_EQ(bounding_box.max_extent().getZ(), 3.0f);
-}
-
-// Tests BoundingBox::Add
-TEST_F(BoundingBoxTest, Add) {
- BoundingBox box(Point3(-1.0f, -2.0f, -3.0f),
- Point3(1.0f, 2.0f, 3.0f));
- box.Add(BoundingBox(Point3(-4.0f, -1.0f, 9.0f),
- Point3(5.0f, 1.0f, 11.0f)),
- &box);
-
- // Check the results are the sum of both boxes.
- EXPECT_TRUE(box.valid());
- EXPECT_EQ(box.min_extent().getX(), -4.0f);
- EXPECT_EQ(box.min_extent().getY(), -2.0f);
- EXPECT_EQ(box.min_extent().getZ(), -3.0f);
- EXPECT_EQ(box.max_extent().getX(), 5.0f);
- EXPECT_EQ(box.max_extent().getY(), 2.0f);
- EXPECT_EQ(box.max_extent().getZ(), 11.0f);
-
- // Check only the original box is valid.
- box.Add(BoundingBox(),
- &box);
-
- // Check the results are just the first box.
- EXPECT_TRUE(box.valid());
- EXPECT_EQ(box.min_extent().getX(), -4.0f);
- EXPECT_EQ(box.min_extent().getY(), -2.0f);
- EXPECT_EQ(box.min_extent().getZ(), -3.0f);
- EXPECT_EQ(box.max_extent().getX(), 5.0f);
- EXPECT_EQ(box.max_extent().getY(), 2.0f);
- EXPECT_EQ(box.max_extent().getZ(), 11.0f);
-
- // Check only the otherbox is valid.
- box = BoundingBox();
- box.Add(BoundingBox(Point3(-4.0f, -1.0f, 9.0f),
- Point3(5.0f, 1.0f, 11.0f)),
- &box);
-
- // Check the results are just the second box.
- EXPECT_TRUE(box.valid());
- EXPECT_EQ(box.min_extent().getX(), -4.0f);
- EXPECT_EQ(box.min_extent().getY(), -1.0f);
- EXPECT_EQ(box.min_extent().getZ(), 9.0f);
- EXPECT_EQ(box.max_extent().getX(), 5.0f);
- EXPECT_EQ(box.max_extent().getY(), 1.0f);
- EXPECT_EQ(box.max_extent().getZ(), 11.0f);
-
- // Check neither box valid
- box = BoundingBox();
- box.Add(BoundingBox(), &box);
-
- // Check the results are not valid.
- EXPECT_FALSE(box.valid());
-}
-
-static const float kEpsilon = 0.0001f;
-
-// Tests BoundingBox::Mul
-TEST_F(BoundingBoxTest, Mul) {
- BoundingBox bounding_box(Point3(-10.0f, 1.0f, -3.0f),
- Point3(0.0f, 2.0f, 3.0f));
-
- // Rotate around Z 180 degrees and check the values are as expected.
- BoundingBox box;
- bounding_box.Mul(Matrix4::rotationZ(3.14159f), &box);
-
- EXPECT_TRUE(fabsf(box.min_extent().getX() - 0.0f) < kEpsilon);
- EXPECT_TRUE(fabsf(box.min_extent().getY() - -2.0f) < kEpsilon);
- EXPECT_TRUE(fabsf(box.min_extent().getZ() - -3.0f) < kEpsilon);
- EXPECT_TRUE(fabsf(box.max_extent().getX() - 10.0f) < kEpsilon);
- EXPECT_TRUE(fabsf(box.max_extent().getY() - -1.0f) < kEpsilon);
- EXPECT_TRUE(fabsf(box.max_extent().getZ() - 3.0f) < kEpsilon);
-}
-
-// Tests BoundingBox::IntersectRay
-TEST_F(BoundingBoxTest, IntersectRay) {
- BoundingBox bounding_box(Point3(-1.0f, -2.0f, -3.0f),
- Point3(1.0f, 2.0f, 3.0f));
-
- // Check a ray that collides.
- RayIntersectionInfo info;
- bounding_box.IntersectRay(Point3(-2.0f, -4.0f, -6.0f),
- Point3(2.0f, 4.0f, 6.0f),
- &info);
-
- EXPECT_TRUE(info.valid());
- EXPECT_TRUE(info.intersected());
- EXPECT_TRUE(fabsf(info.position().getX() - -1.0f) < kEpsilon);
- EXPECT_TRUE(fabsf(info.position().getY() - -2.0f) < kEpsilon);
- EXPECT_TRUE(fabsf(info.position().getZ() - -3.0f) < kEpsilon);
-
- // Check a ray that misses.
- bounding_box.IntersectRay(Point3(2.0f, 4.0f, 6.0f),
- Point3(12.0f, 14.0f, 16.0f),
- &info);
-
- EXPECT_TRUE(info.valid());
- EXPECT_FALSE(info.intersected());
-
- // Check that an invalid box returns an invalid ray.
- BoundingBox invalid_box;
- invalid_box.IntersectRay(Point3(2.0f, 4.0f, 6.0f),
- Point3(12.0f, 14.0f, 16.0f),
- &info);
- EXPECT_FALSE(info.valid());
-}
-
-// Tests BoundingBox::InFrustum
-TEST_F(BoundingBoxTest, InFrustum) {
- Matrix4 view(Matrix4::lookAt(Point3(0.0f, 0.0f, 0.0f),
- Point3(0.0f, 0.0f, 1.0f),
- Vector3(0.0f, 1.0f, 0.0f)));
- Matrix4 projection(Vectormath::Aos::CreatePerspectiveMatrix(
- 45.0f * 180.0f / 3.14159f,
- 4.0f / 3.0f,
- 1.0,
- 10.0));
- Matrix4 frustum(projection * view);
-
- // Check a box completely inside the frustum.
- EXPECT_TRUE(BoundingBox(Point3(1.0f, 1.0f, 1.0f),
- Point3(2.0f, 2.0f, 2.0f)).InFrustum(frustum));
- // Check a box completely outside the frustum.
- EXPECT_FALSE(BoundingBox(Point3(11.0f, 11.0f, 11.0f),
- Point3(12.0f, 12.0f, 12.0f)).InFrustum(frustum));
- // Check a box crossing the edge of the frustum.
- EXPECT_TRUE(BoundingBox(Point3(1.0f, 1.0f, 0.0f),
- Point3(2.0f, 2.0f, 2.0f)).InFrustum(frustum));
-}
-
-#if 0 // TODO: change this to a ParamOperation
-// Tests ParamBindFloat3sToBoundingBox
-TEST_F(BoundingBoxTest, ParamBindFloat3sToBoundingBox) {
- Client client(g_service_locator);
- client.Init();
-
- Pack* pack = client.CreatePack();
-
- Transform* transform = pack->Create<Transform>();
- ASSERT_TRUE(transform != NULL);
-
- ParamBoundingBox* box_param = transform->CreateParam<ParamBoundingBox>("foo");
- ASSERT_TRUE(box_param != NULL);
-
- ParamBindFloat3sToBoundingBox* bind =
- pack->Create<ParamBindFloat3sToBoundingBox>();
- ASSERT_TRUE(bind != NULL);
-
- ParamFloat3* param1 = transform->CreateParam<ParamFloat3>("f1");
- ParamFloat3* param2 = transform->CreateParam<ParamFloat3>("f2");
- ASSERT_TRUE(param1 != NULL);
- ASSERT_TRUE(param2 != NULL);
-
- // Check that we can bind to the inputs and outputs.
- EXPECT_TRUE(
- bind->BindInput(ParamBindFloat3sToBoundingBox::kInput1Name, param1));
- EXPECT_TRUE(
- bind->BindInput(ParamBindFloat3sToBoundingBox::kInput2Name, param2));
- EXPECT_TRUE(
- bind->BindOutput(ParamBindFloat3sToBoundingBox::kOutputName, box_param));
-
- // Check that if we set the values, the make it through the bind and update
- // our bounding box.
- param1->set_value(Float3(-1.0f, 2.0f, -3.0f));
- param2->set_value(Float3(1.0f, -2.0f, 3.0f));
- BoundingBox box(box_param->value());
-
- EXPECT_EQ(box.min_extent()[0], -1.0f);
- EXPECT_EQ(box.min_extent()[1], -2.0f);
- EXPECT_EQ(box.min_extent()[2], -3.0f);
- EXPECT_EQ(box.max_extent()[0], 1.0f);
- EXPECT_EQ(box.max_extent()[1], 2.0f);
- EXPECT_EQ(box.max_extent()[2], 3.0f);
-
- pack->Destroy();
-}
-#endif
-
-} // namespace o3d
diff --git a/o3d/core/cross/buffer.cc b/o3d/core/cross/buffer.cc
deleted file mode 100644
index d1d075a..0000000
--- a/o3d/core/cross/buffer.cc
+++ /dev/null
@@ -1,620 +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 definitions of Buffer, VertexBuffer and IndexBuffer.
-
-#include "core/cross/buffer.h"
-#include "core/cross/client_info.h"
-#include "core/cross/pointer_utils.h"
-#include "core/cross/renderer.h"
-#include "core/cross/features.h"
-#include "core/cross/error.h"
-#include "import/cross/memory_stream.h"
-#include "import/cross/raw_data.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Buffer, NamedObject);
-O3D_DEFN_CLASS(VertexBufferBase, Buffer);
-O3D_DEFN_CLASS(VertexBuffer, VertexBufferBase);
-O3D_DEFN_CLASS(SourceBuffer, VertexBufferBase);
-O3D_DEFN_CLASS(IndexBuffer, Buffer);
-
-const char *Buffer::kSerializationID = "BUFF";
-
-namespace {
-
-// Copies a field.
-// Parameters:
-// source: address of source data.
-// source_stride: amount to step for each element in the source.
-// field_size: size of field in bytes.
-// num_elements: number of elements to copy.
-// destination: address of destination data.
-// destination_stride: amount to step for each element in the destination.
-void CopyField(const void* source,
- size_t source_stride,
- size_t field_size,
- size_t num_elements,
- void* destination,
- size_t destination_stride) {
- while (num_elements) {
- memcpy(destination, source, field_size);
- source = AddPointerOffset(source, source_stride);
- destination = AddPointerOffset(destination, destination_stride);
- --num_elements;
- }
-}
-
-typedef Field::Ref (*FieldCreatorFunc)(ServiceLocator* service_locator,
- Buffer* buffer,
- unsigned num_components,
- unsigned offset);
-
-struct FieldCreator {
- const ObjectBase::Class* field_type;
- FieldCreatorFunc create_function;
- unsigned required_component_multiple;
-};
-static FieldCreator g_creators[] = {
- { FloatField::GetApparentClass(), FloatField::Create,
- FloatField::kRequiredComponentMultiple, },
- { UInt32Field::GetApparentClass(), UInt32Field::Create,
- UInt32Field::kRequiredComponentMultiple, },
- { UByteNField::GetApparentClass(), UByteNField::Create,
- UByteNField::kRequiredComponentMultiple, },
-};
-
-} // anonymouse namespace.
-
-// Buffer ---------------
-Buffer::Buffer(ServiceLocator* service_locator)
- : NamedObject(service_locator),
- features_(service_locator->GetService<Features>()),
- field_change_count_(0),
- total_components_(0),
- stride_(0),
- num_elements_(0),
- access_mode_(NONE),
- lock_count_(0) {
-}
-
-Buffer::~Buffer() {
- AdjustBufferMemoryInfo(false);
- for (unsigned ii = 0; ii < fields_.size(); ++ii) {
- if (!fields_[ii].IsNull()) {
- fields_[ii]->ClearBuffer();
- }
- }
-}
-
-void Buffer::AdjustBufferMemoryInfo(bool add) {
- // Only count VRAM/hardware buffers.
- if (IsA(VertexBuffer::GetApparentClass()) ||
- IsA(IndexBuffer::GetApparentClass())) {
- size_t size_in_bytes = num_elements_ * stride_;
- ClientInfoManager* client_info_manager =
- service_locator()->GetService<ClientInfoManager>();
- client_info_manager->AdjustBufferMemoryUsed(
- static_cast<int>(size_in_bytes) * (add ? 1 : -1));
- }
-}
-
-bool Buffer::AllocateElements(unsigned num_elements) {
- if (access_mode_ != NONE) {
- O3D_ERROR(service_locator()) << "Attempt to allocate locked Buffer '"
- << name() << "'";
- return false;
- }
-
- if (stride_ == 0) {
- O3D_ERROR(service_locator())
- << "No fields have been set on Buffer '" << name() << "'";
- return false;
- }
-
- if (num_elements > MAX_SMALL_INDEX && !features_->large_geometry()) {
- O3D_ERROR(service_locator())
- << "You can not allocate more then " << MAX_SMALL_INDEX
- << " elements in a buffer unless "
- << "you request support for large geometry when you "
- << "initialize O3D.";
- return false;
- }
-
- if (num_elements > MAX_LARGE_INDEX) {
- O3D_ERROR(service_locator())
- << "The maximum number of elements in a buffer is " << MAX_LARGE_INDEX
- << ".";
- return false;
- }
-
- size_t size_in_bytes = num_elements * stride_;
- // Check for size_t overflow.
- if (size_in_bytes / stride_ != num_elements) {
- O3D_ERROR(service_locator())
- << "Attempt to allocate too many elements for the current set of "
- << "fields on buffer.";
- return false;
- }
-
- if (size_in_bytes == 0) {
- O3D_ERROR(service_locator())
- << "Attempt to allocate zero bytes for Buffer '" << name() << "'";
- return false;
- }
-
- bool success = true;
- if (!ConcreteAllocate(size_in_bytes)) {
- num_elements = 0;
- size_in_bytes = 0;
- success = false;
- }
-
- num_elements_ = num_elements;
-
- AdjustBufferMemoryInfo(true);
-
- return success;
-}
-
-void Buffer::Free() {
- if (num_elements_ > 0) {
- ConcreteFree();
- AdjustBufferMemoryInfo(false);
- num_elements_ = 0;
- }
-}
-
-bool Buffer::ReshuffleBuffer(unsigned int new_stride, Field* field_to_remove) {
- if (new_stride == 0) {
- AdjustBufferMemoryInfo(false);
- ConcreteFree();
- stride_ = 0;
- return true;
- }
- if (num_elements_) {
- size_t size_in_bytes = num_elements_ * new_stride;
- // Check for size_t overflow.
- if (size_in_bytes / new_stride != num_elements_) {
- O3D_ERROR(service_locator())
- << "Attempt to allocate too many elements for the current set of "
- << "fields on buffer.";
- return false;
- }
- std::vector<uint8> temp(size_in_bytes);
-
- // Copy old fields into new buffer.
- {
- BufferLockHelper helper(this);
- void* source = helper.GetData(Buffer::READ_ONLY);
- if (!source) {
- return false;
- }
- unsigned int offset = 0;
- for (unsigned ii = 0; ii < fields_.size(); ++ii) {
- Field* field = fields_[ii].Get();
- if (field != field_to_remove) {
- CopyField(PointerFromVoidPointer<void*>(source, field->offset()),
- stride_,
- field->size(),
- num_elements_,
- PointerFromVoidPointer<void*>(&temp[0], offset),
- new_stride);
- field->set_offset(offset);
- offset += field->size();
- }
- }
- }
- // Copy the reorganized data into a new buffer.
- {
- ConcreteFree();
- AdjustBufferMemoryInfo(false);
- if (!ConcreteAllocate(size_in_bytes)) {
- num_elements_ = 0;
- O3D_ERROR(service_locator())
- << "Couldn't allocate buffer of size: " << size_in_bytes
- << " for Buffer '" << name() << "'";
- return false;
- }
- // stride_ must be set before GetData is called so that the proper size
- // buffer is allocated. We also need to set it after this function is
- // is completed (see CreateField, RemoveField) for when we create a new
- // buffer with no fields yet.
- stride_ = new_stride;
- AdjustBufferMemoryInfo(true);
- BufferLockHelper helper(this);
- void* destination = helper.GetData(Buffer::WRITE_ONLY);
- if (!destination) {
- return false;
- }
- memcpy(destination, &temp[0], size_in_bytes);
- }
- }
- return true;
-}
-
-Field* Buffer::CreateFieldByClassName(const String& field_type,
- unsigned num_components) {
- for (unsigned ii = 0; ii < arraysize(g_creators); ++ii) {
- if (!field_type.compare(g_creators[ii].field_type->name()) ||
- !field_type.compare(g_creators[ii].field_type->unqualified_name())) {
- return CreateField(g_creators[ii].field_type, num_components);
- }
- }
-
- O3D_ERROR(service_locator())
- << "unrecognized field type '" << field_type << "'";
- return NULL;
-}
-
-Field* Buffer::CreateField(const ObjectBase::Class* field_type,
- unsigned num_components) {
- FieldCreator* creator = NULL;
- for (unsigned ii = 0; ii < arraysize(g_creators); ++ii) {
- if (g_creators[ii].field_type == field_type) {
- creator = &g_creators[ii];
- break;
- }
- }
-
- if (!creator) {
- O3D_ERROR(service_locator())
- << "unrecognized field type '"
- << (field_type ? field_type->name() : "NULL") << "'";
- return NULL;
- }
-
- if (num_components == 0) {
- O3D_ERROR(service_locator())
- << "num components must be > 0 for Buffer '" << name() << "'";
- return NULL;
- }
-
- if (num_components % creator->required_component_multiple != 0) {
- O3D_ERROR(service_locator())
- << "num components must be a multiple of "
- << creator->required_component_multiple
- << " for fields of type " << field_type->unqualified_name();
- return NULL;
- }
-
- Field::Ref field = creator->create_function(service_locator(), this,
- num_components, stride_);
- unsigned int new_stride = stride_ + field->size();
- ReshuffleBuffer(new_stride, NULL);
-
- fields_.push_back(field);
- stride_ = new_stride;
- total_components_ += num_components;
- ++field_change_count_;
-
- return field;
-}
-
-void Buffer::RemoveField(Field* field) {
- for (unsigned ii = 0; ii < fields_.size(); ++ii) {
- if (fields_[ii] == field) {
- unsigned int new_stride = stride_ - field->size();
- ReshuffleBuffer(new_stride, field);
- total_components_ -= field->num_components();
- stride_ = new_stride;
- field->ClearBuffer();
- // This erase may remove the last reference to the field so field may
- // be invalid after this line.
- fields_.erase(fields_.begin() + ii);
- ++field_change_count_;
- return;
- }
- }
- O3D_ERROR(service_locator())
- << "Field '" << field->name()
- << "' does not exist on Buffer '" << name() << "'";
-}
-
-bool Buffer::Lock(AccessMode access_mode, void** buffer_data) {
- if (access_mode == NONE) {
- O3D_ERROR(service_locator())
- << "attempt to lock Buffer '" << name()
- << "' with access mode NONE";
- return false;
- }
- if (access_mode_ == NONE || access_mode == access_mode_) {
- if (lock_count_ == 0) {
- if (!ConcreteLock(access_mode, &locked_data_)) {
- return false;
- }
- }
- ++lock_count_;
- *buffer_data = locked_data_;
- return true;
- } else {
- O3D_ERROR(service_locator())
- << "attempt to lock already locked Buffer '" << name()
- << "' with different access mode";
- return false;
- }
-}
-
-bool Buffer::Unlock() {
- if (lock_count_ == 0) {
- O3D_ERROR(service_locator())
- << "attempt to unlock unlocked Buffer '" << name() << "'";
- return false;
- }
- --lock_count_;
- if (lock_count_ == 0) {
- return ConcreteUnlock();
- }
- return true;
-}
-
-bool Buffer::Set(o3d::RawData *raw_data) {
- DCHECK(raw_data);
- return Set(raw_data, 0, raw_data->GetLength());
-}
-
-bool Buffer::Set(o3d::RawData *raw_data,
- size_t offset,
- size_t length) {
- DCHECK(raw_data);
-
- if (!raw_data->IsOffsetLengthValid(offset, length)) {
- O3D_ERROR(service_locator()) << "illegal buffer data offset or size";
- return false;
- }
-
- // GetData() returns NULL if it, for example, cannot open the temporary data
- // file. In that case, it invokes the error callback. We just have to be
- // careful not to dereference it.
- const uint8 *data = raw_data->GetDataAs<uint8>(offset);
- if (!data) {
- return false;
- }
-
- MemoryReadStream stream(data, length);
-
- // Verify we at least have enough data for four-char kSerializationID plus
- // version and num_fields
- if (length < 4 + 2*sizeof(int32)) {
- O3D_ERROR(service_locator())
- << "data object does not contain buffer data";
- return false;
- }
-
- // To insure data integrity we expect four characters kSerializationID
- char id[5];
- stream.Read(id, 4);
- id[4] = 0; // null-terminate
-
- if (strcmp(id, kSerializationID)) {
- O3D_ERROR(service_locator())
- << "data object does not contain buffer data";
- return false;
- }
-
- int32 version = stream.ReadLittleEndianInt32();
- if (version != 1) {
- O3D_ERROR(service_locator()) << "unknown buffer data version";
- return false;
- }
-
- // Delete existing fields.
- // TODO: Since this removes all fields, there is no need to
- // reshuffle (which can be expensive). We could provide a RemoveAllFields
- // and call it here.
- while (fields_.size() > 0) {
- RemoveField(fields_[0]);
- }
-
- // Create fields.
- int32 num_fields = stream.ReadLittleEndianInt32();
- for (int32 ff = 0; ff < num_fields; ++ff) {
- if (stream.GetRemainingByteCount() < 2*sizeof(uint8)) {
- O3D_ERROR(service_locator()) << "unexpected end of buffer data";
- return false;
- }
-
- uint8 field_id = stream.ReadByte();
- uint8 num_components = stream.ReadByte();
-
- const ObjectBase::Class *field_type;
-
- switch (field_id) {
- case Field::FIELDID_FLOAT32:
- field_type = FloatField::GetApparentClass();
- break;
- case Field::FIELDID_UINT32:
- field_type = UInt32Field::GetApparentClass();
- break;
- case Field::FIELDID_BYTE:
- field_type = UByteNField::GetApparentClass();
- break;
-
- case Field::FIELDID_UNKNOWN:
- default:
- O3D_ERROR(service_locator()) << "unknown field_type";
- return false;
- }
-
- Field* field = CreateField(field_type, num_components);
- if (!field) {
- O3D_ERROR(service_locator()) << "couldn't create field";
- return false;
- }
- }
-
- // Read the number of elements and allocate space
- if (stream.GetRemainingByteCount() < sizeof(int32)) {
- O3D_ERROR(service_locator()) << "unexpected end of buffer data";
- return false;
- }
- int32 num_elements = stream.ReadLittleEndianInt32();
- if (!AllocateElements(num_elements)) {
- O3D_ERROR(service_locator()) << "could not allocate buffer elements";
- return false;
- }
-
- {
- // Lock before reading in all the fields to avoid locking/unlocking
- // for each field which would be slower
- o3d::BufferLockHelper helper(this);
- helper.GetData(o3d::Buffer::WRITE_ONLY);
-
- // Read each field
- for (int32 ff = 0; ff < num_fields; ++ff) {
- Field *field = fields()[ff];
- if (!field->SetFromMemoryStream(&stream)) {
- O3D_ERROR(service_locator()) <<
- "unexpected end of buffer field data";
- return false;
- }
- }
- }
-
- // Final integrity check that we consumed exactly the correct amount of data
- if (stream.GetRemainingByteCount() != 0) {
- O3D_ERROR(service_locator()) << "extra buffer data remaining";
- return false;
- }
-
- return true;
-}
-
-VertexBufferBase::VertexBufferBase(ServiceLocator* service_locator)
- : Buffer(service_locator) {
-}
-
-VertexBuffer::VertexBuffer(ServiceLocator* service_locator)
- : VertexBufferBase(service_locator) {
-}
-
-ObjectBase::Ref VertexBuffer::Create(ServiceLocator* service_locator) {
- Renderer* renderer = service_locator->GetService<Renderer>();
- if (NULL == renderer) {
- O3D_ERROR(service_locator) << "No Render Device Available";
- return ObjectBase::Ref();
- }
- return ObjectBase::Ref(renderer->CreateVertexBuffer());
-}
-
-SourceBuffer::SourceBuffer(ServiceLocator* service_locator)
- : VertexBufferBase(service_locator),
- buffer_() {
-}
-
-SourceBuffer::~SourceBuffer() {
- ConcreteFree();
-}
-
-void SourceBuffer::ConcreteFree() {
- buffer_.reset();
-}
-
-bool SourceBuffer::ConcreteAllocate(size_t size_in_bytes) {
- ConcreteFree();
-
- buffer_.reset(new char[size_in_bytes]);
-
- return true;
-}
-
-bool SourceBuffer::ConcreteLock(AccessMode access_mode, void **buffer_data) {
- if (!buffer_.get()) {
- return false;
- }
-
- *buffer_data = reinterpret_cast<void*>(buffer_.get());
- return true;
-}
-
-bool SourceBuffer::ConcreteUnlock() {
- return buffer_.get() != NULL;
-}
-
-ObjectBase::Ref SourceBuffer::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new SourceBuffer(service_locator));
-}
-
-Field* IndexBuffer::index_field() const {
- // TODO: It does not make sense for an IndexBuffer to have more
- // than one field. For example, we do not support any way of rendering a
- // primitive using only one of the fields of an IndexBuffer. The API allows
- // you to create any number of fields for Buffers in general. That may not be
- // the best design. This code verifies that there are not multiple fields
- // on the IndexBuffer. It also checks for the case where there are no fields
- // to prevent a crash. This function can be called from JavaScript. It
- // should never crash. It is okay for an IndexBuffer to temporarily contain
- // no fields. This is is used by Buffer::Set(). I added a DCHECK for debug
- // builds.
- DCHECK(fields().size() == 1);
- return fields().size() == 1 ? fields()[0].Get() : NULL;
-}
-
-IndexBuffer::IndexBuffer(ServiceLocator* service_locator)
- : Buffer(service_locator) {
- CreateField(UInt32Field::GetApparentClass(), 1);
-}
-
-ObjectBase::Ref IndexBuffer::Create(ServiceLocator* service_locator) {
- Renderer* renderer = service_locator->GetService<Renderer>();
- if (NULL == renderer) {
- O3D_ERROR(service_locator) << "No Render Device Available";
- return ObjectBase::Ref();
- }
- return ObjectBase::Ref(renderer->CreateIndexBuffer());
-}
-
-BufferLockHelper::BufferLockHelper(Buffer* buffer)
- : buffer_(buffer),
- data_(NULL),
- locked_(false) {
-}
-
-BufferLockHelper::~BufferLockHelper() {
- if (locked_) {
- buffer_->Unlock();
- }
-}
-
-void* BufferLockHelper::GetData(Buffer::AccessMode access_mode) {
- if (!locked_) {
- locked_ = buffer_->Lock(access_mode, &data_);
- if (!locked_) {
- O3D_ERROR(buffer_->service_locator())
- << "Unable to lock buffer '" << buffer_->name() << "'";
- }
- }
- return data_;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/buffer.h b/o3d/core/cross/buffer.h
deleted file mode 100644
index 79f5b1f..0000000
--- a/o3d/core/cross/buffer.h
+++ /dev/null
@@ -1,397 +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 declaration for the Buffer, VertexBuffer and
-// IndexBuffer classes.
-
-#ifndef O3D_CORE_CROSS_BUFFER_H_
-#define O3D_CORE_CROSS_BUFFER_H_
-
-#include <vector>
-#include "core/cross/field.h"
-#include "core/cross/named_object.h"
-#include "core/cross/types.h"
-#include "base/scoped_ptr.h"
-
-namespace o3d {
-
-class RawData;
-class Features;
-
-// class Buffer -----------------------------
-//
-// DESIGN GOALS:the Buffer object is a low level container for a flat list of
-// floating point or integer values. These are used to define geometry,
-// parameter buffers and to hold animation data.
-//
-// The default implementation of the Buffer doesn't do much. Each render system
-// (e.g. D3D, OGL, etc) should derive its own version of a Buffer that handles
-// the underlying data resources appropriately
-
-// The Buffer object is a low level container for a flat list of
-// floating point or integer values. These are currently used to define
-// geometry. Buffer is an abstract class and only declares the interface for
-// buffer operations. Data storage needs to be allocated by derived classes.
-class Buffer : public NamedObject {
- public:
- typedef SmartPointer<Buffer> Ref;
-
- // Defines how you want to access a buffer when locking.
- enum AccessMode {
- NONE = 0,
- READ_ONLY = 1,
- WRITE_ONLY = 2,
- READ_WRITE = 3,
- };
-
- // Yes, 65534 is the correct number. Specifically the Intel 945 only allows
- // 65534 elements.
- static const unsigned MAX_SMALL_INDEX = 65534;
-
- // Yes, Sadly many modern cards only support 1048575 vertices.
- static const unsigned MAX_LARGE_INDEX = 1048575;
-
- // A four-character identifier used in the binary serialization format
- // (not exposed to Javascript)
- static const char *kSerializationID;
-
- explicit Buffer(ServiceLocator* service_locator);
- ~Buffer();
-
- // Allocates memory for the data to be stored in the buffer
- bool AllocateElements(unsigned int num_elements);
-
- // Frees any data currently allocated for this buffer.
- void Free();
-
- // Creates a field on this buffer
- // Parameters:
- // field_type: type of field.
- // num_components: number of components.
- // Returns:
- // Pointer to created field.
- Field* CreateField(const ObjectBase::Class* field_type,
- unsigned num_components);
-
- // Creates a field on this buffer
- //
- // this is for Javascript
- //
- // Paramters:
- // field_type_name: name of type of field.
- // num_components: number of components.
- // Returns:
- // Pointer to created field.
- Field* CreateFieldByClassName(const String& field_type_name,
- unsigned num_components);
-
- // Removes a field
- // Parameters:
- // field: Field to remove.
- void RemoveField(Field* field);
-
- // Returns the stride of the buffer.
- unsigned int stride() const {
- return stride_;
- }
-
- // Returns the number of components per element. In other words the sum
- // of all the components in all fields.
- unsigned int total_components() const {
- return total_components_;
- }
-
- // Returns the field change count. Anytime a field is added, removed or
- // changed this value is incremented. Streams track it so they know
- // to rebuild vertex declarations based on the buffer changing format.
- unsigned int field_change_count() const {
- return field_change_count_;
- }
-
- // Obtains a pointer to the memory location where the data is stored.
- // This method should get called before data stored in the buffer can be
- // modified. From C++ use LockAs
- // Parameters:
- // access_mode: How you want to access the data.
- // buffer_data: pointer to void pointer to receive pointer to data.
- // Returns:
- // true if the operation succeeds.
- bool Lock(AccessMode access_mode, void** buffer_data);
-
- // Notifies that updates to the buffer data are completed. Once Unlock
- // is called data should not be modified any more.
- bool Unlock();
-
- // Gets the number of elements.
- unsigned int num_elements() const {
- return num_elements_;
- }
-
- // Gets the array of fields.
- const FieldRefArray& fields() const {
- return fields_;
- }
-
- // Returns the size of the buffer in bytes.
- size_t GetSizeInBytes() const {
- return num_elements_ * stride_;
- }
-
- // A typed version of Lock
- template <typename T>
- bool LockAs(AccessMode access_mode, T** buffer_data) {
- return Lock(access_mode, reinterpret_cast<void**>(buffer_data));
- }
-
- // De-serializes the data contained in |raw_data|
- // The entire contents of |raw_data| from start to finish will
- // be used
- bool Set(o3d::RawData *raw_data);
-
- // De-serializes the data contained in |raw_data|
- // starting at byte offset |offset| and using |length|
- // bytes
- bool Set(o3d::RawData *raw_data,
- size_t offset,
- size_t length);
-
- protected:
- // The concrete version of AllocateElements.
- virtual bool ConcreteAllocate(size_t size_in_bytes) = 0;
-
- // The concrete version of Free
- virtual void ConcreteFree() = 0;
-
- // The concrete version of Lock. Platform specific versions of buffers
- // need to override this.
- //
- // Parameters:
- // access_mode: How you want to access the data. buffer_data: pointer to
- // void pointer to receive pointer to data.
- // Returns:
- // true if the operation succeeds.
- virtual bool ConcreteLock(AccessMode access_mode, void** buffer_data) = 0;
-
- // The concrete version of Unlock. Platform specific versions of buffers need
- // to override this.
- virtual bool ConcreteUnlock() = 0;
-
- private:
- // Takes the data currently allocated and copies it to new data of a different
- // stride.
- // Parameters:
- // new_stride: stride of new buffer.
- // field_to_remove: address of field. If NULL no field is removed.
- bool ReshuffleBuffer(unsigned int new_stride, Field* field_to_remove);
-
- void AdjustBufferMemoryInfo(bool add);
-
- Features* features_;
-
- // Fields.
- FieldRefArray fields_;
-
- // The number of times fields have been added or removed. Streams
- // can track this value so they can know if they need to update.
- unsigned int field_change_count_;
-
- // The total number of components in all fields.
- unsigned int total_components_;
-
- // The stride of the buffer.
- unsigned int stride_;
-
- // The current number of elements in the buffer.
- unsigned int num_elements_;
-
- // The mode the buffer is currently being accessed so we can fail if a
- // different mode is requested
- AccessMode access_mode_;
-
- // The number of times this buffer has been locked.
- int lock_count_;
-
- // Pointer to data when it's locked.
- void* locked_data_;
-
- O3D_DECL_CLASS(Buffer, NamedObject);
-};
-
-// VertexBufferBase is just here so VertexBuffer and SourceBuffer can share IDL
-// glue.
-class VertexBufferBase : public Buffer {
- public:
- typedef SmartPointer<VertexBufferBase> Ref;
-
- protected:
- explicit VertexBufferBase(ServiceLocator* service_locator);
-
- private:
- O3D_DECL_CLASS(VertexBufferBase, Buffer);
- DISALLOW_COPY_AND_ASSIGN(VertexBufferBase);
-};
-
-// VertexBuffer is Buffer object used for storing vertex data for geometry
-// (e.g. vertex positions, normals, colors, etc). It is an abstract class
-// declaring the interface only. Each rendering platform should derive its own
-// implementation of the interface.
-//
-// NOTE: You can not READ data from a VertexBuffer.
-class VertexBuffer : public VertexBufferBase {
- public:
- typedef SmartPointer<VertexBuffer> Ref;
-
- protected:
- explicit VertexBuffer(ServiceLocator* service_locator);
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(VertexBuffer, VertexBufferBase);
- DISALLOW_COPY_AND_ASSIGN(VertexBuffer);
-};
-
-// SourceBuffer is a buffer object stored in system memory. It is used as
-// the source for skinning, morph targets, etc.
-class SourceBuffer : public VertexBufferBase {
- public:
- typedef SmartPointer<SourceBuffer> Ref;
-
- ~SourceBuffer();
-
- protected:
- // Overridden from Buffer.
- virtual bool ConcreteAllocate(size_t size_in_bytes);
-
- // Overridden from Buffer.
- virtual bool ConcreteLock(AccessMode access_mode, void **buffer_data);
-
- // Overridden from Buffer.
- virtual bool ConcreteUnlock();
-
- explicit SourceBuffer(ServiceLocator* service_locator);
-
- protected:
- // Frees the buffer if it exists.
- void ConcreteFree();
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- scoped_array<char> buffer_; // The actual data for this buffer.
-
- O3D_DECL_CLASS(SourceBuffer, VertexBufferBase);
- DISALLOW_COPY_AND_ASSIGN(SourceBuffer);
-};
-
-// IndexBuffer is a buffer object used for storing geometry index data (e.g.
-// triangle indices). It is an abstract class declaring the interface only.
-// Each rendering platform should derive its own implementation of the
-// interface.
-//
-// NOTE: You can not READ data from an IndexBuffer.
-class IndexBuffer : public Buffer {
- public:
- typedef SmartPointer<IndexBuffer> Ref;
-
- Field* index_field() const;
-
- // De-serializes the data contained in |raw_data|
- // The entire contents of |raw_data| from start to finish will
- // be used
- bool Set(o3d::RawData *raw_data) {
- return Buffer::Set(raw_data);
- }
-
- // De-serializes the data contained in |raw_data|
- // starting at byte offset |offset| and using |length|
- // bytes
- bool Set(o3d::RawData *raw_data,
- size_t offset,
- size_t length) {
- return Buffer::Set(raw_data, offset, length);
- }
-
- protected:
- explicit IndexBuffer(ServiceLocator* service_locator);
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(IndexBuffer, Buffer);
- DISALLOW_COPY_AND_ASSIGN(IndexBuffer);
-};
-
-// BufferLockHelper can be used to lock a buffer in a safe way in that it will
-// unlock the buffer on destruction so you can use it like this
-//
-// {
-// BufferLockHelper helper(my_buffer);
-// void* data = helper.GetData();
-// if (data) {
-// .. do something with data here ..
-// }
-// }
-//
-// Because there is no need to call Unlock it is much easier to deal with error
-// conditions.
-class BufferLockHelper {
- public:
- explicit BufferLockHelper(Buffer* buffer);
-
- ~BufferLockHelper();
-
- // Gets a pointer to the data of the buffer, locking the buffer if necessary.
- // Returns:
- // Pointer to data in buffer or NULL if there was an error.
- void* GetData(Buffer::AccessMode access_mode);
-
- // Typed version of GetData
- template <typename T>
- T* GetDataAs(Buffer::AccessMode access_mode) {
- return reinterpret_cast<T*>(GetData(access_mode));
- }
-
- private:
- Buffer* buffer_;
- void* data_;
- bool locked_;
-
- DISALLOW_COPY_AND_ASSIGN(BufferLockHelper);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_BUFFER_H_
diff --git a/o3d/core/cross/buffer_test.cc b/o3d/core/cross/buffer_test.cc
deleted file mode 100644
index 7bdddac..0000000
--- a/o3d/core/cross/buffer_test.cc
+++ /dev/null
@@ -1,589 +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 VertexBuffer and IndexBuffer.
-
-#include "core/cross/client.h"
-#include "tests/common/win/testing_common.h"
-#include "core/cross/error_status.h"
-#include "core/cross/buffer.h"
-#include "core/cross/pack.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-#include "import/cross/raw_data.h"
-#include "serializer/cross/serializer_binary.h"
-
-namespace o3d {
-
-namespace {
-
-// Checks if change_count != buffer->field_change_count and updates
-// change_count.
-bool ChangeCountChanged(unsigned int* change_count, Buffer* buffer) {
- bool changed = *change_count != buffer->field_change_count();
- *change_count = buffer->field_change_count();
- return changed;
-}
-
-// Checks if an error has occured on the client then clears the error.
-bool CheckErrorExists(IErrorStatus* error_status) {
- bool have_error = !error_status->GetLastError().empty();
- error_status->ClearLastError();
- return have_error;
-}
-
-// Compares 2 sets of floats. Returns true if they are the same.
-bool CompareElements(const float* floats_1,
- const float* floats_2,
- unsigned num_elements,
- unsigned num_components) {
- for (; num_elements; --num_elements) {
- for (unsigned ii = 0; ii < num_components; ++ii) {
- if (*floats_1 != *floats_2) {
- return false;
- }
- ++floats_1;
- ++floats_2;
- }
- }
- return true;
-}
-
-} // anonymous namespace
-
-class BufferTest : public testing::Test {
- protected:
- BufferTest()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- IErrorStatus* error_status() { return &error_status_; }
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- Pack* pack_;
-};
-
-void BufferTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void BufferTest::TearDown() {
- object_manager_->DestroyPack(pack_);
-}
-
-// Test Buffer.
-TEST_F(BufferTest, TestBasic) {
- Buffer *buffer = pack()->Create<VertexBuffer>();
- const FieldRefArray& fields = buffer->fields();
- // Verify initial state.
- ASSERT_TRUE(buffer->IsA(Buffer::GetApparentClass()));
- EXPECT_EQ(buffer->num_elements(), 0U);
- EXPECT_EQ(fields.size(), 0U);
- EXPECT_EQ(buffer->stride(), 0U);
- EXPECT_EQ(buffer->GetSizeInBytes(), 0U);
-}
-
-// Test create fields and putting something in
-TEST_F(BufferTest, CreateFields) {
- Buffer *buffer = pack()->Create<VertexBuffer>();
- const FieldRefArray& fields = buffer->fields();
- // Verify initial state.
- unsigned int change_count = buffer->field_change_count();
-
- static float in_floats_1[][3] = {
- { 1, 2, 3, },
- { 4, 5, 6, },
- { 10, 11, 12, },
- { 13, 14, 15, },
- };
- const unsigned kNumComponents1 = arraysize(in_floats_1[0]);
- const unsigned kNumElements = arraysize(in_floats_1);
- const unsigned kStride1 = kNumComponents1;
- const size_t kSize1 = sizeof(in_floats_1[0]);
-
- // Add a field
- Field::Ref field_1 = Field::Ref(buffer->CreateField(
- FloatField::GetApparentClass(),
- kNumComponents1));
- EXPECT_EQ(fields.size(), 1U);
- EXPECT_EQ(field_1, fields[0].Get());
- EXPECT_EQ(field_1->offset(), 0U);
- EXPECT_EQ(buffer->stride(), kSize1);
- EXPECT_EQ(buffer->total_components(), kNumComponents1);
- EXPECT_EQ(buffer->GetSizeInBytes(), 0U);
- EXPECT_TRUE(ChangeCountChanged(&change_count, buffer));
-
- // Allocate some elements.
- buffer->AllocateElements(4);
- EXPECT_EQ(buffer->GetSizeInBytes(), kSize1 * kNumElements);
-
- // Put data in.
- field_1->SetFromFloats(&in_floats_1[0][0], kStride1, 0, kNumElements);
-
- // Get Data out
- float out_floats_1[kNumElements][kNumComponents1];
- memset(out_floats_1, 0, sizeof(out_floats_1));
- field_1->GetAsFloats(0, &out_floats_1[0][0], kStride1, kNumElements);
-
- EXPECT_TRUE(CompareElements(&in_floats_1[0][0],
- &out_floats_1[0][0],
- kNumElements,
- kNumComponents1));
-
- // Check offset out of range.
- EXPECT_FALSE(CheckErrorExists(error_status()));
- field_1->SetFromFloats(&in_floats_1[0][0], kStride1, kNumElements, 1);
- EXPECT_TRUE(CheckErrorExists(error_status()));
-
- // Check offset in range, length out of range.
- field_1->SetFromFloats(&in_floats_1[0][0], kStride1, kNumElements - 1, -1);
- EXPECT_TRUE(CheckErrorExists(error_status()));
-
- // Check that we can lock the buffer around SetFromFloats.
- {
- BufferLockHelper helper(buffer);
- void* data = helper.GetData(Buffer::WRITE_ONLY);
- ASSERT_TRUE(data != NULL);
- field_1->SetFromFloats(&in_floats_1[0][0], kStride1, 0, kNumElements);
- }
-
- // Check that we can lock the buffer around GetAsFloats.
- {
- BufferLockHelper helper(buffer);
- void* data = helper.GetData(Buffer::READ_ONLY);
- ASSERT_TRUE(data != NULL);
- field_1->SetFromFloats(&in_floats_1[0][0], kStride1, 0, kNumElements);
- }
-
- // Check that deleting buffer clears the field buffer pointer.
- pack()->RemoveObject(buffer);
- EXPECT_TRUE(field_1->buffer() == NULL);
-}
-
-// Test creating a field, putting data in, then adding another field and
-// removing the original.
-TEST_F(BufferTest, ReshuffleFields) {
- Buffer *buffer = pack()->Create<VertexBuffer>();
- const FieldRefArray& fields = buffer->fields();
- unsigned int change_count = buffer->field_change_count();
-
- static float in_floats_1[][3] = {
- { 1, 2, 3, },
- { 4, 5, 6, },
- { 10, 11, 12, },
- { 13, 14, 15, },
- };
- const unsigned kNumComponents1 = arraysize(in_floats_1[0]);
- const unsigned kNumElements = arraysize(in_floats_1);
- const unsigned kStride1 = kNumComponents1;
- const size_t kSize1 = sizeof(in_floats_1[0]);
-
- // Add a field
- Field::Ref field_1 = Field::Ref(buffer->CreateField(
- FloatField::GetApparentClass(),
- kNumComponents1));
-
- // Allocate some elements.
- buffer->AllocateElements(4);
- EXPECT_EQ(buffer->GetSizeInBytes(), kSize1 * kNumElements);
-
- // Put data in.
- field_1->SetFromFloats(&in_floats_1[0][0], kStride1, 0, kNumElements);
-
- // Get Data out
- float out_floats_1[kNumElements][kNumComponents1];
- memset(out_floats_1, 0, sizeof(out_floats_1));
- field_1->GetAsFloats(0, &out_floats_1[0][0], kStride1, kNumElements);
-
- EXPECT_TRUE(CompareElements(&in_floats_1[0][0],
- &out_floats_1[0][0],
- kNumElements,
- kNumComponents1));
-
- // Check offset out of range.
- EXPECT_FALSE(CheckErrorExists(error_status()));
- field_1->SetFromFloats(&in_floats_1[0][0], kStride1, kNumElements, 1);
- EXPECT_TRUE(CheckErrorExists(error_status()));
-
- // Check offset in range, length out of range.
- field_1->SetFromFloats(&in_floats_1[0][0], kStride1, kNumElements - 1, -1);
- EXPECT_TRUE(CheckErrorExists(error_status()));
-
- static float in_floats_2[kNumElements][1] = {
- { 2, },
- { 4, },
- { 5, },
- { 7, },
- };
- const unsigned kNumComponents2 = arraysize(in_floats_2[0]);
- const unsigned kStride2 = kNumComponents2;
- const size_t kSize2 = sizeof(in_floats_2[0]);
-
- // Check adding a second field.
- Field::Ref field_2 = Field::Ref(buffer->CreateField(
- FloatField::GetApparentClass(),
- kNumComponents2));
- EXPECT_EQ(fields.size(), 2U);
- EXPECT_EQ(field_1, fields[0].Get());
- EXPECT_EQ(field_2, fields[1].Get());
- EXPECT_EQ(field_1->offset(), 0U);
- EXPECT_EQ(field_2->offset(), kSize1);
- EXPECT_EQ(buffer->stride(), kSize1 + kSize2);
- EXPECT_EQ(buffer->total_components(), kNumComponents1 + kNumComponents2);
- EXPECT_EQ(buffer->GetSizeInBytes(), (kSize1 + kSize2) * kNumElements);
- EXPECT_TRUE(ChangeCountChanged(&change_count, buffer));
-
- // Put data in second field.
- field_2->SetFromFloats(&in_floats_2[0][0], kStride2, 0, kNumElements);
-
- // Get Data out of second field
- float out_floats_2[kNumElements][kNumComponents2];
- memset(out_floats_1, 0, sizeof(out_floats_1));
- memset(out_floats_2, 0, sizeof(out_floats_2));
- field_1->GetAsFloats(0, &out_floats_1[0][0], kStride1, kNumElements);
- field_2->GetAsFloats(0, &out_floats_2[0][0], kStride2, kNumElements);
-
- EXPECT_TRUE(CompareElements(&in_floats_1[0][0],
- &out_floats_1[0][0],
- kNumElements,
- kNumComponents1));
- EXPECT_TRUE(CompareElements(&in_floats_2[0][0],
- &out_floats_2[0][0],
- kNumElements,
- kNumComponents2));
-
- // Check deleting a field
- buffer->RemoveField(field_1);
- EXPECT_TRUE(field_1->buffer() == NULL);
- EXPECT_EQ(fields.size(), 1U);
- EXPECT_EQ(field_2, fields[0].Get());
- EXPECT_EQ(field_2->offset(), 0U);
- EXPECT_EQ(buffer->stride(), kSize2);
- EXPECT_EQ(buffer->total_components(), kNumComponents2);
- EXPECT_EQ(buffer->GetSizeInBytes(), kSize2 * kNumElements);
- EXPECT_TRUE(ChangeCountChanged(&change_count, buffer));
-
- // Check that the data got shuffled.
- memset(out_floats_2, 0, sizeof(out_floats_2));
- field_2->GetAsFloats(0, &out_floats_2[0][0], kStride2, kNumElements);
- EXPECT_TRUE(CompareElements(&in_floats_2[0][0],
- &out_floats_2[0][0],
- kNumElements,
- kNumComponents2));
-
- // Check that we can lock the buffer around SetFromFloats.
- {
- BufferLockHelper helper(buffer);
- void* data = helper.GetData(Buffer::WRITE_ONLY);
- ASSERT_TRUE(data != NULL);
- field_2->SetFromFloats(&in_floats_2[0][0], kStride2, 0, kNumElements);
- }
-
- // Check that we can lock the buffer around GetAsFloats.
- {
- BufferLockHelper helper(buffer);
- void* data = helper.GetData(Buffer::READ_ONLY);
- ASSERT_TRUE(data != NULL);
- field_2->GetAsFloats(0, &out_floats_2[0][0], kStride2, kNumElements);
- }
-
- // Check that deleting buffer clears the field buffer pointer.
- pack()->RemoveObject(buffer);
- EXPECT_TRUE(field_2->buffer() == NULL);
-}
-
-// Creates a vertex buffer, tests basic properties, and checks that writing data
-// works.
-TEST_F(BufferTest, VertexBuffer) {
- Buffer *buffer = pack()->Create<VertexBuffer>();
-
- const size_t kSize = 100;
- Field* field = buffer->CreateField(UInt32Field::GetApparentClass(), 1);
- ASSERT_TRUE(field != NULL);
- ASSERT_TRUE(buffer->AllocateElements(kSize));
- EXPECT_EQ(kSize * sizeof(uint32), buffer->GetSizeInBytes()); // NOLINT
-
- // Put some data into the buffer.
- uint32 *data = NULL;
- ASSERT_TRUE(buffer->LockAs(Buffer::WRITE_ONLY, &data));
- ASSERT_TRUE(data != NULL);
- for (uint32 i = 0; i < kSize; ++i) {
- data[i] = i;
- }
- ASSERT_TRUE(buffer->Unlock());
-
- data = NULL;
- // Read the data from the buffer, checks that it's the expected values.
- ASSERT_TRUE(buffer->LockAs(Buffer::READ_ONLY, &data));
- ASSERT_TRUE(data != NULL);
- for (uint32 i = 0; i < kSize; ++i) {
- EXPECT_EQ(i, data[i]);
- }
- ASSERT_TRUE(buffer->Unlock());
-}
-
-// Creates a source buffer, tests basic properties, and checks that writing then
-// reading data works.
-TEST_F(BufferTest, TestSourceBuffer) {
- Buffer *buffer = pack()->Create<SourceBuffer>();
- EXPECT_TRUE(buffer->IsA(SourceBuffer::GetApparentClass()));
- EXPECT_TRUE(buffer->IsA(VertexBufferBase::GetApparentClass()));
- EXPECT_TRUE(buffer->IsA(Buffer::GetApparentClass()));
-
- const size_t kSize = 100;
- Field* field = buffer->CreateField(UInt32Field::GetApparentClass(), 1);
- ASSERT_TRUE(field != NULL);
- ASSERT_TRUE(buffer->AllocateElements(kSize));
- EXPECT_EQ(kSize * sizeof(uint32), buffer->GetSizeInBytes()); // NOLINT
-
- // Put some data into the buffer.
- uint32 *data = NULL;
- ASSERT_TRUE(buffer->LockAs(Buffer::WRITE_ONLY, &data));
- ASSERT_TRUE(data != NULL);
- for (uint32 i = 0; i < kSize; ++i) {
- data[i] = i;
- }
- ASSERT_TRUE(buffer->Unlock());
-
- data = NULL;
- // Read the data from the buffer, checks that it's the expected values.
- ASSERT_TRUE(buffer->LockAs(Buffer::READ_ONLY, &data));
- ASSERT_TRUE(data != NULL);
- for (uint32 i = 0; i < kSize; ++i) {
- EXPECT_EQ(i, data[i]);
- }
- ASSERT_TRUE(buffer->Unlock());
-}
-
-// Creates an index buffer, tests basic properties, and checks that writing
-// data works.
-TEST_F(BufferTest, TestIndexBuffer) {
- IndexBuffer *buffer = pack()->Create<IndexBuffer>();
- EXPECT_TRUE(buffer->IsA(IndexBuffer::GetApparentClass()));
- EXPECT_TRUE(buffer->IsA(Buffer::GetApparentClass()));
-
- EXPECT_TRUE(buffer->index_field()->IsA(UInt32Field::GetApparentClass()));
-
- const size_t kSize = 100;
- ASSERT_TRUE(buffer->AllocateElements(kSize));
- EXPECT_EQ(kSize, buffer->num_elements());
-
- // Put some data into the buffer.
- uint32 *data = NULL;
- ASSERT_TRUE(buffer->LockAs(Buffer::WRITE_ONLY, &data));
- ASSERT_TRUE(data != NULL);
- for (uint32 i = 0; i < kSize; ++i) {
- data[i] = i;
- }
- ASSERT_TRUE(buffer->Unlock());
-
- data = NULL;
- // Read the data from the buffer, checks that it's the expected values.
- ASSERT_TRUE(buffer->LockAs(Buffer::READ_ONLY, &data));
- ASSERT_TRUE(data != NULL);
- for (uint32 i = 0; i < kSize; ++i) {
- EXPECT_EQ(i, data[i]);
- }
- ASSERT_TRUE(buffer->Unlock());
-}
-
-TEST_F(BufferTest, TestIndexFieldIsFirstField) {
- IndexBuffer *buffer = pack()->Create<IndexBuffer>();
- buffer->RemoveField(buffer->fields()[0]);
- Field* field = buffer->CreateField(UInt32Field::GetApparentClass(), 1);
- EXPECT_EQ(field, buffer->index_field());
-}
-
-// Creates a vertex buffer, checks that setting values from a RawData
-// object works.
-TEST_F(BufferTest, TestVertexBufferFromRawData) {
- VertexBuffer *buffer = pack()->Create<VertexBuffer>();
- EXPECT_TRUE(buffer->IsA(VertexBuffer::GetApparentClass()));
- EXPECT_TRUE(buffer->IsA(VertexBufferBase::GetApparentClass()));
- EXPECT_TRUE(buffer->IsA(Buffer::GetApparentClass()));
-
- // Create a field to verify that setting the buffer from raw data deletes it.
- buffer->CreateField(FloatField::GetApparentClass(), 1);
-
- const int kMemBufferSize = 32768; // more than enough for our needs here
- MemoryBuffer<uint8> mem_buffer(kMemBufferSize);
- MemoryWriteStream stream(mem_buffer, kMemBufferSize);
-
- // write out serialization ID
- stream.Write(Buffer::kSerializationID, 4);
-
- // write out version
- stream.WriteLittleEndianInt32(1);
-
- // write out number of fields
- const int kNumFields = 3;
- stream.WriteLittleEndianInt32(kNumFields);
-
- // Write out the specification for the fields
- struct FieldInfo {
- int id;
- int num_components;
- };
-
- const FieldInfo infos[kNumFields] =
- { {Field::FIELDID_FLOAT32, 3},
- {Field::FIELDID_UINT32, 2},
- {Field::FIELDID_BYTE, 4} };
-
- for (int i = 0; i < kNumFields; ++i) {
- const FieldInfo &info = infos[i];
- stream.WriteByte(info.id);
- stream.WriteByte(info.num_components);
- }
-
- // Write out the number of elements
- const int kNumElements = 4;
-
- stream.WriteLittleEndianInt32(kNumElements);
-
- // Make note of stream position at end of header
- stream.GetStreamPosition();
-
- // Write out the data for each field
-
- float float_data[kNumElements * 3] = {
- 1.2f, 2.3f, 4.7f,
- -4.1f, 3.14f, 17.8f,
- 17.3f, -4.7f, -1.1f,
- -0.1f, 0.123f, 5.720f
- };
-
- uint32 int_data[kNumElements * 2] = {
- 1, 2,
- 3, 4,
- 10, 11,
- 12, 13
- };
-
- uint8 byte_data[kNumElements * 4] = {
- 0, 1, 2, 3,
- 17, 16, 10, 11,
- 100, 99, 87, 88,
- 50, 51, 60, 65
- };
-
- // First write out the float data
- for (int j = 0; j < kNumElements; ++j) {
- stream.WriteLittleEndianFloat32(float_data[j * 3]);
- stream.WriteLittleEndianFloat32(float_data[j * 3 + 1]);
- stream.WriteLittleEndianFloat32(float_data[j * 3 + 2]);
- }
-
- // Write out the int data
- for (int j = 0; j < kNumElements; ++j) {
- stream.WriteLittleEndianInt32(int_data[j * 2]);
- stream.WriteLittleEndianInt32(int_data[j * 2 + 1]);
- }
-
- // Write out the byte data
- for (int j = 0; j < kNumElements; ++j) {
- stream.WriteByte(byte_data[j * 4]);
- stream.WriteByte(byte_data[j * 4 + 1]);
- stream.WriteByte(byte_data[j * 4 + 2]);
- stream.WriteByte(byte_data[j * 4 + 3]);
- }
-
- // Make note of exactly how much we've written
- size_t total_length_in_bytes = stream.GetStreamPosition();
-
- // Create RawData object
- String uri("test_filename");
- uint8 *p = mem_buffer;
- RawData::Ref ref = RawData::Create(g_service_locator,
- uri,
- p,
- total_length_in_bytes);
- RawData *raw_data = ref;
-
- bool success = buffer->Set(raw_data); // set values from raw data object
- EXPECT_TRUE(success);
-
- // Check that the field that was originally created to verify that setting
- // the buffer from raw data would remove any existing fields was in fact
- // removed.
- EXPECT_EQ(3U, buffer->fields().size());
-
- float buffer_float_data[kNumElements * 3];
- uint32 buffer_int_data[kNumElements * 2];
- uint8 buffer_byte_data[kNumElements * 4];
-
- buffer->fields()[0].Get()->GetAsFloats(
- 0, &buffer_float_data[0], 3, kNumElements);
- down_cast<UInt32Field*>(buffer->fields()[1].Get())->GetAsUInt32s(
- 0, &buffer_int_data[0], 2, kNumElements);
- down_cast<UByteNField*>(buffer->fields()[2].Get())->GetAsUByteNs(
- 0, &buffer_byte_data[0], 4, kNumElements);
-
- for (int i = 0; i < kNumElements; ++i) {
- // Validate float field
- EXPECT_EQ(buffer_float_data[i * 3 + 0], float_data[i * 3 + 0]);
- EXPECT_EQ(buffer_float_data[i * 3 + 1], float_data[i * 3 + 1]);
- EXPECT_EQ(buffer_float_data[i * 3 + 2], float_data[i * 3 + 2]);
-
- // Validate int field
- EXPECT_EQ(buffer_int_data[i * 2 + 0], int_data[i * 2 + 0]);
- EXPECT_EQ(buffer_int_data[i * 2 + 1], int_data[i * 2 + 1]);
-
- // Validate byte field
- EXPECT_EQ(buffer_byte_data[i * 4 + 0], byte_data[i * 4 + 0]);
- EXPECT_EQ(buffer_byte_data[i * 4 + 1], byte_data[i * 4 + 1]);
- EXPECT_EQ(buffer_byte_data[i * 4 + 2], byte_data[i * 4 + 2]);
- EXPECT_EQ(buffer_byte_data[i * 4 + 3], byte_data[i * 4 + 3]);
- }
-
- // Now, let's try a very nice test to verify that we properly
- // serialize -- this is a round trip test
- MemoryBuffer<uint8> serialized_data;
- SerializeBuffer(*buffer, &serialized_data);
-
- // Make sure serialized data length is identical to what we made
- ASSERT_EQ(total_length_in_bytes, serialized_data.GetLength());
-
- // Make sure the data matches
- uint8 *original = mem_buffer;
- uint8 *serialized = serialized_data;
- EXPECT_EQ(0, memcmp(original, serialized, total_length_in_bytes));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/cairo/install_check.cc b/o3d/core/cross/cairo/install_check.cc
deleted file mode 100644
index 2784c13..0000000
--- a/o3d/core/cross/cairo/install_check.cc
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright 2010, 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 "core/cross/install_check.h"
-
-namespace o3d {
-
-bool RendererInstallCheck(std::string *error) {
- return true;
-}
-
-} // namespace o3d
-
diff --git a/o3d/core/cross/cairo/layer.cc b/o3d/core/cross/cairo/layer.cc
deleted file mode 100644
index 450ad40..0000000
--- a/o3d/core/cross/cairo/layer.cc
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright 2010, 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 "core/cross/cairo/layer.h"
-
-#include "core/cross/error.h"
-#include "core/cross/renderer.h"
-#include "core/cross/cairo/renderer_cairo.h"
-
-namespace o3d {
-
-namespace o2d {
-
-O3D_DEFN_CLASS(Layer, ObjectBase);
-
-Layer::~Layer() {
- Renderer* renderer = service_locator()->GetService<Renderer>();
- RendererCairo* renderer_cairo = down_cast<RendererCairo*>(renderer);
- renderer_cairo->RemoveLayer(this);
-}
-
-Layer::Layer(ServiceLocator* service_locator)
- : ObjectBase(service_locator),
- visible_(true),
- alpha_(0),
- region_(false, 0, 0, 0, 0),
- inner_clip_region_(false, 0, 0, 0, 0),
- outer_clip_region_(false, 0, 0, 0, 0),
- z_(0),
- scale_x_(1.0),
- scale_y_(1.0),
- paint_operator_(BLEND),
- z_dirty_(true),
- region_dirty_(false),
- content_dirty_(true),
- saved_should_paint_(false),
- saved_outer_clip_region_(false, 0, 0, 0, 0) {
- DLOG(INFO) << "Create Layer";
- Renderer* renderer = service_locator->GetService<Renderer>();
- RendererCairo* renderer_cairo = down_cast<RendererCairo*>(renderer);
- renderer_cairo->AddLayer(this);
-}
-
-ObjectBase::Ref Layer::Create(ServiceLocator* service_locator) {
- Renderer* renderer = service_locator->GetService<Renderer>();
- if (NULL == renderer) {
- O3D_ERROR(service_locator) << "No Render Device Available";
- return ObjectBase::Ref();
- }
-
- Layer* layer = new Layer(service_locator);
-
- return ObjectBase::Ref(layer);
-}
-
-} // namespace o2d
-
-} // namespace o3d
diff --git a/o3d/core/cross/cairo/layer.h b/o3d/core/cross/cairo/layer.h
deleted file mode 100644
index 7fc1da8..0000000
--- a/o3d/core/cross/cairo/layer.h
+++ /dev/null
@@ -1,327 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-// A Layer is a rectangular region of the O2D canvas to be filled with a
-// particular Pattern, with automatic clipping based on stacking order.
-
-#ifndef O3D_CORE_CROSS_CAIRO_LAYER_H_
-#define O3D_CORE_CROSS_CAIRO_LAYER_H_
-
-#include <vector>
-
-#include "core/cross/object_base.h"
-#include "core/cross/cairo/pattern.h"
-
-namespace o3d {
-
-class IClassManager;
-
-namespace o2d {
-
-class Layer : public ObjectBase {
- public:
- struct Region {
- Region(bool everywhere, double x, double y, double width, double height)
- : everywhere(everywhere),
- x(x),
- y(y),
- width(width),
- height(height) {
- }
-
- bool everywhere;
- double x;
- double y;
- double width;
- double height;
- };
-
- typedef SmartPointer<Layer> Ref;
-
- enum PaintOperator {
- BLEND,
- BLEND_WITH_TRANSPARENCY,
- COPY,
- COPY_WITH_FADING,
- };
-
- virtual ~Layer();
-
- // Methods exposed to JS.
-
- Pattern* pattern() const {
- return pattern_;
- }
-
- void set_pattern(Pattern* pattern) {
- pattern_ = Pattern::Ref(pattern);
- set_content_dirty(true);
- }
-
- bool visible() const {
- return visible_;
- }
-
- void set_visible(bool visible) {
- visible_ = visible;
- }
-
- bool everywhere() const {
- return region_.everywhere;
- }
-
- void set_everywhere(bool everywhere) {
- region_.everywhere = everywhere;
- set_region_dirty(true);
- }
-
- double alpha() const {
- return alpha_;
- }
-
- void set_alpha(double alpha) {
- alpha_ = alpha;
- set_content_dirty(true);
- }
-
- double x() const {
- return region_.x;
- }
-
- void set_x(double x) {
- region_.x = x;
- set_region_dirty(true);
- }
-
- double y() const {
- return region_.y;
- }
-
- void set_y(double y) {
- region_.y = y;
- set_region_dirty(true);
- }
-
- double z() const {
- return z_;
- }
-
- void set_z(double z) {
- z_ = z;
- set_z_dirty(true);
- set_content_dirty(true);
- }
-
- double width() const {
- return region_.width;
- }
-
- void set_width(double width) {
- region_.width = width;
- set_region_dirty(true);
- }
-
- double height() const {
- return region_.height;
- }
-
- void set_height(double height) {
- region_.height = height;
- set_region_dirty(true);
- }
-
- double scale_x() const {
- return scale_x_;
- }
-
- void set_scale_x(double scale_x) {
- scale_x_ = scale_x;
- set_content_dirty(true);
- }
-
- double scale_y() const {
- return scale_y_;
- }
-
- void set_scale_y(double scale_y) {
- scale_y_ = scale_y;
- set_content_dirty(true);
- }
-
- PaintOperator paint_operator() const {
- return paint_operator_;
- }
-
- void set_paint_operator(PaintOperator paint_operator) {
- paint_operator_ = paint_operator;
- set_content_dirty(true);
- }
-
- // Methods not exposed to JS.
-
- bool z_dirty() const {
- return z_dirty_;
- }
-
- void set_z_dirty(bool z_dirty) {
- z_dirty_ = z_dirty;
- }
-
- bool region_dirty() const {
- return region_dirty_;
- }
-
- void set_region_dirty(bool region_dirty) {
- region_dirty_ = region_dirty;
- }
-
- bool content_dirty() const {
- return content_dirty_;
- }
-
- void set_content_dirty(bool content_dirty) {
- content_dirty_ = content_dirty;
- }
-
- const Region& region() const {
- return region_;
- }
-
- const Region& inner_clip_region() const {
- return inner_clip_region_;
- }
-
- const Region& outer_clip_region() const {
- return outer_clip_region_;
- }
-
- Region& inner_clip_region() {
- return inner_clip_region_;
- }
-
- Region& outer_clip_region() {
- return outer_clip_region_;
- }
-
- // Whether we should currently paint this layer.
- bool ShouldPaint() const {
- return visible() && pattern() != NULL;
- }
-
- // Whether this layer should currently clip content behind it (i.e.,
- // prevent it from being drawn in the first place).
- bool ShouldClip() const {
- // When alpha blending is used we cannot clip the background because our
- // content will be blended with it.
- return ShouldPaint() &&
- (paint_operator() == COPY || paint_operator() == COPY_WITH_FADING);
- }
-
- void SaveShouldPaint() {
- saved_should_paint_ = ShouldPaint();
- }
-
- bool GetSavedShouldPaint() const {
- return saved_should_paint_;
- }
-
- void SaveOuterClipRegion() {
- saved_outer_clip_region_ = outer_clip_region();
- }
-
- const Region& GetSavedOuterClipRegion() const {
- return saved_outer_clip_region_;
- }
-
- private:
- explicit Layer(ServiceLocator* service_locator);
-
- friend class o3d::IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // The pattern used to paint this layer.
- Pattern::Ref pattern_;
-
- // Whether this layer should be visible or not.
- bool visible_;
-
- // The transparency for the BLEND_WITH_TRANSPARENCY operator or the fading for
- // the COPY_WITH_FADING operator.
- double alpha_;
-
- // The region of screen space occupied by this layer.
- Region region_;
-
- // A version of region_ that excludes any fractional pixels.
- Region inner_clip_region_;
-
- // A version of region_ that fully includes any fractional pixels.
- Region outer_clip_region_;
-
- // The z coordinate of the layer (used only to determine stacking order).
- double z_;
-
- // A scaling factor to apply to the pattern's x-axis.
- double scale_x_;
-
- // A scaling factor to apply to the pattern's y-axis.
- double scale_y_;
-
- // The paint operator to use for painting this layer.
- PaintOperator paint_operator_;
-
- // Whether or not this layer's z property has changed since the last frame was
- // rendered.
- bool z_dirty_;
-
- // Whether or not this layer's region properties have changed since the layer
- // was last updated on-screen.
- bool region_dirty_;
-
- // Whether or not this layer's content properties (pattern, alpha, z, scale_x,
- // scale_y, paint_operator) have changed since the layer was last updated
- // on-screen.
- bool content_dirty_;
-
- // The value of ShouldPaint() when the last frame was rendered.
- bool saved_should_paint_;
-
- // The value of outer_clip_region() when the layer was last updated on-screen.
- Region saved_outer_clip_region_;
-
- O3D_DECL_CLASS(Layer, ObjectBase)
-}; // Layer
-
-} // namespace o2d
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_CAIRO_LAYER_H_
diff --git a/o3d/core/cross/cairo/pattern.cc b/o3d/core/cross/cairo/pattern.cc
deleted file mode 100644
index 0488292..0000000
--- a/o3d/core/cross/cairo/pattern.cc
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright 2011, 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 "core/cross/cairo/pattern.h"
-
-#include <cairo.h>
-
-#include "core/cross/pack.h"
-#include "core/cross/cairo/texture_cairo.h"
-
-namespace o3d {
-
-namespace o2d {
-
-O3D_DEFN_CLASS(Pattern, ObjectBase);
-
-// Cairo supports more pattern types than just these three, but we don't expose
-// the others.
-
-Pattern* Pattern::CreateTexturePattern(Pack* pack, Texture* texture) {
- TextureCairo* texture_cairo = down_cast<TextureCairo*>(texture);
- return WrapCairoPattern(
- pack,
- cairo_pattern_create_for_surface(texture_cairo->surface()),
- texture_cairo);
-}
-
-Pattern* Pattern::CreateRgbPattern(Pack* pack,
- double red,
- double green,
- double blue) {
- return WrapCairoPattern(pack,
- cairo_pattern_create_rgb(red, green, blue),
- NULL);
-}
-
-Pattern* Pattern::CreateRgbaPattern(Pack* pack,
- double red,
- double green,
- double blue,
- double alpha) {
- return WrapCairoPattern(pack,
- cairo_pattern_create_rgba(red, green, blue, alpha),
- NULL);
-}
-
-Pattern::~Pattern() {
- cairo_pattern_destroy(pattern_);
-}
-
-void Pattern::SetAffineTransform(double xx,
- double yx,
- double xy,
- double yy,
- double x0,
- double y0) {
- cairo_matrix_t matrix;
- cairo_matrix_init(&matrix, xx, yx, xy, yy, x0, y0);
- cairo_pattern_set_matrix(pattern_, &matrix);
- set_content_dirty(true);
-}
-
-void Pattern::set_extend(ExtendType extend) {
- cairo_extend_t cairo_extend;
- switch (extend) {
- case NONE:
- cairo_extend = CAIRO_EXTEND_NONE;
- break;
- case REPEAT:
- cairo_extend = CAIRO_EXTEND_REPEAT;
- break;
- case REFLECT:
- cairo_extend = CAIRO_EXTEND_REFLECT;
- break;
- case PAD:
- cairo_extend = CAIRO_EXTEND_PAD;
- break;
- default:
- DCHECK(false);
- return;
- }
- cairo_pattern_set_extend(pattern_, cairo_extend);
- set_content_dirty(true);
-}
-
-void Pattern::set_filter(FilterType filter) {
- cairo_filter_t cairo_filter;
- switch (filter) {
- case FAST:
- cairo_filter = CAIRO_FILTER_FAST;
- break;
- case GOOD:
- cairo_filter = CAIRO_FILTER_GOOD;
- break;
- case BEST:
- cairo_filter = CAIRO_FILTER_BEST;
- break;
- case NEAREST:
- cairo_filter = CAIRO_FILTER_NEAREST;
- break;
- case BILINEAR:
- cairo_filter = CAIRO_FILTER_BILINEAR;
- break;
- default:
- DCHECK(false);
- return;
- }
- cairo_pattern_set_filter(pattern_, cairo_filter);
- set_content_dirty(true);
-}
-
-Pattern::Pattern(ServiceLocator* service_locator,
- cairo_pattern_t* pattern,
- TextureCairo* texture)
- : ObjectBase(service_locator),
- pattern_(pattern),
- texture_(texture),
- content_dirty_(false) {
-}
-
-Pattern* Pattern::WrapCairoPattern(Pack* pack,
- cairo_pattern_t* pattern,
- TextureCairo* texture) {
- cairo_status_t status = cairo_pattern_status(pattern);
- if (CAIRO_STATUS_SUCCESS != status) {
- DLOG(ERROR) << "Error creating Cairo pattern: " << status;
- cairo_pattern_destroy(pattern);
- return NULL;
- }
- Pattern* p = new Pattern(pack->service_locator(), pattern, texture);
- pack->RegisterObject(p);
- return p;
-}
-
-} // namespace o2d
-
-} // namespace o3d
diff --git a/o3d/core/cross/cairo/pattern.h b/o3d/core/cross/cairo/pattern.h
deleted file mode 100644
index e28a772..0000000
--- a/o3d/core/cross/cairo/pattern.h
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright 2011, 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.
- */
-
-// A Pattern is a container for pixel content for painting to a Layer.
-
-#ifndef O3D_CORE_CROSS_CAIRO_PATTERN_H_
-#define O3D_CORE_CROSS_CAIRO_PATTERN_H_
-
-#include "core/cross/object_base.h"
-#include "core/cross/cairo/texture_cairo.h"
-
-typedef struct _cairo_pattern cairo_pattern_t;
-
-namespace o3d {
-
-class Pack;
-
-namespace o2d {
-
-class Pattern : public ObjectBase {
- public:
- typedef SmartPointer<Pattern> Ref;
-
- enum ExtendType {
- NONE,
- REPEAT,
- REFLECT,
- PAD
- };
-
- enum FilterType {
- FAST,
- GOOD,
- BEST,
- NEAREST,
- BILINEAR
- };
-
- // Create a pattern that paints the content of a texture.
- static Pattern* CreateTexturePattern(Pack* pack, Texture* texture);
-
- // Create a pattern that paints a solid colour.
- static Pattern* CreateRgbPattern(Pack* pack,
- double red,
- double green,
- double blue);
-
- // Create a pattern that paints a solid colour with transparency.
- static Pattern* CreateRgbaPattern(Pack* pack,
- double red,
- double green,
- double blue,
- double alpha);
-
- virtual ~Pattern();
-
- cairo_pattern_t* pattern() const { return pattern_; }
-
- TextureCairo* texture() const { return texture_; }
-
- bool content_dirty() const {
- return content_dirty_;
- }
-
- void set_content_dirty(bool content_dirty) {
- content_dirty_ = content_dirty;
- }
-
- // Set the affine transformation matrix that maps user space to pattern space.
- // The default matrix is the identity matrix, so that no transformation
- // occurs.
- void SetAffineTransform(double xx,
- double yx,
- double xy,
- double yy,
- double x0,
- double y0);
-
- void set_extend(ExtendType extend);
-
- void set_filter(FilterType filter);
-
- private:
- Pattern(ServiceLocator* service_locator,
- cairo_pattern_t* pattern,
- TextureCairo* texture);
-
- static Pattern* WrapCairoPattern(Pack* pack,
- cairo_pattern_t* pattern,
- TextureCairo* texture);
-
- // The underlying Cairo pattern.
- cairo_pattern_t* pattern_;
-
- // The TextureCairo that wraps the pattern's texture, or NULL if not a texture
- // pattern.
- TextureCairo::Ref texture_;
-
- // Whether or not this pattern's content has changed since it was last updated
- // on-screen.
- bool content_dirty_;
-
- O3D_DECL_CLASS(Pattern, ObjectBase)
-}; // Pattern
-
-} // namespace o2d
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_CAIRO_PATTERN_H_
diff --git a/o3d/core/cross/cairo/renderer_cairo.cc b/o3d/core/cross/cairo/renderer_cairo.cc
deleted file mode 100644
index dee852c..0000000
--- a/o3d/core/cross/cairo/renderer_cairo.cc
+++ /dev/null
@@ -1,948 +0,0 @@
-/*
- * Copyright 2011, 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.
- */
-
-// A 2D renderer that uses the Cairo library.
-
-#include "core/cross/cairo/renderer_cairo.h"
-
-#if defined(OS_LINUX)
-#include <cairo-xlib.h>
-#elif defined(OS_MACOSX)
-#include <cairo-quartz.h>
-#elif defined(OS_WIN)
-#include <cairo-win32-private.h>
-#include <cairo-win32.h>
-#endif
-
-#include <algorithm>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "core/cross/cairo/layer.h"
-#include "core/cross/cairo/texture_cairo.h"
-
-#if defined(OS_MACOSX) || defined(OS_WIN)
-// As of OS X 10.6.4, the Quartz 2D drawing API has hardware acceleration
-// disabled by default, and if you force-enable it then it actually hurts
-// performance instead of improving it (really, go google it). It also turns out
-// that the performance of the software implementation in Pixman is about 12%
-// faster than the OS X software implementation (measured as CPU usage per
-// rendered frame), so we do all compositing with Pixman via an image surface
-// and only use the OS to paint the final frame to the screen.
-
-// On Windows COMPOSITING_TO_IMAGE is also slightly faster than compositing with
-// GDI.
-// TODO(tschmelcher): Profile Windows without COMPOSITING_TO_IMAGE and see if we
-// can make it faster.
-#define COMPOSITING_TO_IMAGE 1
-#endif
-
-namespace o3d {
-
-// This is a factory function for creating 2D Renderer objects.
-Renderer* Renderer::Create2DRenderer(ServiceLocator* service_locator) {
- return o2d::RendererCairo::CreateDefault(service_locator);
-}
-
-namespace o2d {
-
-RendererCairo::RendererCairo(ServiceLocator* service_locator)
- : Renderer(service_locator),
-#if defined(OS_LINUX)
- display_(NULL),
- window_(0),
-#elif defined(OS_MACOSX)
- mac_cg_context_ref_(0),
-#elif defined(OS_WIN)
- hwnd_(NULL),
-#endif
- display_surface_(NULL),
- offscreen_surface_(NULL),
- fullscreen_(false),
- size_dirty_(false) {
- // Don't need to do anything.
-}
-
-RendererCairo::~RendererCairo() {
- Destroy();
-}
-
-RendererCairo* RendererCairo::CreateDefault(ServiceLocator* service_locator) {
- return new RendererCairo(service_locator);
-}
-
-// Released all hardware resources.
-void RendererCairo::Destroy() {
- DLOG(INFO) << "To Destroy";
-
- DestroyOffscreenSurface();
-#if defined(OS_LINUX) || defined(OS_WIN)
- DestroyDisplaySurface();
-#endif
-
-#if defined(OS_LINUX)
- display_ = NULL;
- window_ = 0;
-#elif defined(OS_MACOSX)
- mac_cg_context_ref_ = 0;
-#elif defined(OS_WIN)
- hwnd_ = NULL;
-#endif
-}
-
-// Comparison predicate for STL sort.
-static bool LayerZValueLessThan(const Layer* first, const Layer* second) {
- return first->z() < second->z();
-}
-
-static void AddRectangleRegion(cairo_t* cr, const Layer::Region& region) {
- cairo_rectangle(cr,
- region.x,
- region.y,
- region.width,
- region.height);
-}
-
-typedef double (*rounding_fn)(double);
-
-static void RoundRegion(const Layer::Region& in_region,
- rounding_fn round_x1y1,
- rounding_fn round_x2y2,
- Layer::Region* out_region) {
- out_region->everywhere = in_region.everywhere;
- out_region->x = (*round_x1y1)(in_region.x);
- out_region->y = (*round_x1y1)(in_region.y);
- out_region->width = (*round_x2y2)(in_region.x + in_region.width)
- - out_region->x;
- out_region->height = (*round_x2y2)(in_region.y + in_region.height)
- - out_region->y;
-}
-
-void RendererCairo::Paint() {
-#ifdef OS_MACOSX
- // On OSX we can't persist the display surface across Paint() calls because
- // of issues with unbalanced CGContextSaveGState/RestoreGState calls, so we
- // have to create and destroy the surface for every frame.
- CreateDisplaySurface();
-#endif
-
-#if !defined(COMPOSITING_TO_IMAGE) && defined(OS_LINUX)
- if (!offscreen_surface_) {
- // Have to call this here because strangely it breaks rendering if we call
- // it during InitCommon() on Linux. Possibly the X11 Window underlying the
- // display_surface_ is not fully initialized until sometime after
- // NPP_SetWindow().
- CreateOffscreenSurface();
- }
-#endif
-
- if (!display_surface_ || !offscreen_surface_) {
- DLOG(INFO) << "No target surface(s), cannot paint";
- return;
- }
-
- // TODO(tschmelcher): Don't keep creating and destroying the drawing context.
- cairo_t* cr = cairo_create(offscreen_surface_);
-
- cairo_save(cr);
-
- // Set clip rule for building the initial clip region.
- cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
-
- // If we have been resized then we must redraw everything, since the new
- // offscreen surface will be uninitialized.
- if (size_dirty_) {
- AddDisplayRegion(cr);
- }
-
- // Build an initial clip region for all drawing operations that restricts
- // drawing to only areas of the screen that have changed.
- bool needs_sort = false;
- for (LayerList::const_iterator i = layer_list_.begin();
- i != layer_list_.end(); i++) {
- Layer* layer = *i;
-
- // Aggregate all content dirtiness into the layer's dirtiness property.
- Pattern* pattern = layer->pattern();
- if (pattern) {
- if (pattern->content_dirty()) {
- layer->set_content_dirty(true);
- } else {
- TextureCairo* texture = pattern->texture();
- if (texture && texture->content_dirty()) {
- layer->set_content_dirty(true);
- }
- }
- }
-
- if (!layer->ShouldPaint() && !layer->GetSavedShouldPaint()) {
- // Won't be painted now and wasn't painted on the last frame either, so
- // doesn't need to be redrawn.
- continue;
- }
-
- if (layer->ShouldPaint() && layer->z_dirty()) {
- // If the z-value has changed and it is going to be painted then we need
- // to re-sort.
- needs_sort = true;
- }
-
- if (layer->region_dirty()) {
- // Recompute clip regions.
- RoundRegion(layer->region(), &ceil, &floor, &layer->inner_clip_region());
- RoundRegion(layer->region(), &floor, &ceil, &layer->outer_clip_region());
- }
-
- if (layer->ShouldPaint() && (layer->region_dirty() ||
- layer->content_dirty() ||
- !layer->GetSavedShouldPaint())) {
- // If it is visible and the region, content, or visibility has changed
- // then the current region must be redrawn.
- AddRegion(cr, layer->outer_clip_region());
- }
-
- if (layer->GetSavedShouldPaint() && (layer->region_dirty() ||
- !layer->ShouldPaint())) {
- // If the region or visibility has changed and it was visible before then
- // the old region must be redrawn.
- AddRegion(cr, layer->GetSavedOuterClipRegion());
- }
- }
-
- // Must also redraw the regions of any formerly visible layers.
- for (RegionList::const_iterator i = layer_ghost_list_.begin();
- i != layer_ghost_list_.end(); ++i) {
- AddRegion(cr, *i);
- }
-
- // Clip everything outside the regions defined by the above.
- cairo_clip(cr);
-
- // If any visible layer has had its z-value modified, re-sort the list to get
- // the right draw order.
- if (needs_sort) {
- std::sort(layer_list_.begin(), layer_list_.end(), LayerZValueLessThan);
- }
-
- // Change clip rule for the paint operations.
- cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
-
- // Core process of painting.
- for (LayerList::const_iterator i = layer_list_.begin();
- i != layer_list_.end(); i++) {
- Layer* layer = *i;
- if (!layer->ShouldPaint()) continue;
-
- Pattern* pattern = layer->pattern();
-
- // Save the current drawing state.
- cairo_save(cr);
-
- // Clip the region outside the current Layer.
- if (!layer->everywhere()) {
- // This should really be layer->region(), but there is a bug in cairo with
- // complex unaligned clip regions so we use an aligned one instead. See
- // http://lists.cairographics.org/archives/cairo/2011-March/021827.html
- // This doesn't really matter though because any sensible web app will
- // align everything to pixel boundaries.
- AddRectangleRegion(cr, layer->outer_clip_region());
- cairo_clip(cr);
- }
-
- // Clip the regions within other Layers that will obscure this one.
- LayerList::const_iterator start_mask_it = i;
- start_mask_it++;
- ClipArea(cr, start_mask_it);
-
- // Transform the pattern to fit into the Layer's region.
- cairo_translate(cr, layer->x(), layer->y());
- cairo_scale(cr, layer->scale_x(), layer->scale_y());
-
- // Set source pattern.
- cairo_set_source(cr, pattern->pattern());
-
- // Paint the pattern to the off-screen surface.
- switch (layer->paint_operator()) {
- case Layer::BLEND:
- cairo_paint(cr);
- break;
-
- case Layer::BLEND_WITH_TRANSPARENCY:
- cairo_paint_with_alpha(cr, layer->alpha());
- break;
-
- case Layer::COPY:
- // Set Cairo to copy the pattern's alpha content instead of blending.
- cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
- cairo_paint(cr);
- break;
-
- case Layer::COPY_WITH_FADING:
- // TODO(tschmelcher): This can also be done in a single operation with:
- //
- // cairo_set_operator(cr, CAIRO_OPERATOR_IN);
- // cairo_paint_with_alpha(cr, layer->alpha());
- //
- // but surprisingly that is slightly slower for me. We should figure out
- // why.
- cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
- cairo_paint(cr);
- cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
- cairo_paint_with_alpha(cr, layer->alpha());
- break;
-
- default:
- DCHECK(false);
- }
-
- // Restore to a clean state.
- cairo_restore(cr);
- }
-
- cairo_restore(cr);
-
- // Finish drawing to the offscreen surface.
- cairo_destroy(cr);
-
- // Set up a new context for painting the offscreen surface to the screen.
- cr = cairo_create(display_surface_);
- cairo_set_source_surface(cr, offscreen_surface_, 0, 0);
- // Painting to a Win32 window with the SOURCE operator interacts poorly with
- // window resizing, so on Windows we use the default of OVER.
-#ifndef OS_WIN
- cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
-#endif
-
- // Paint to the screen.
- // TODO(tschmelcher): We can clip here too if we know that the on-screen
- // window hasn't been damaged by another window.
- cairo_paint(cr);
-
- cairo_destroy(cr);
-
- // Clear dirtiness.
-
- size_dirty_ = false;
-
- for (LayerList::const_iterator i = layer_list_.begin();
- i != layer_list_.end(); i++) {
- Layer* layer = *i;
-
- // Clear pattern/texture content dirtiness on all layers, since it has been
- // aggregated into the layer.
- Pattern* pattern = layer->pattern();
- if (pattern) {
- pattern->set_content_dirty(false);
- TextureCairo* texture = pattern->texture();
- if (texture) {
- texture->set_content_dirty(false);
- }
- }
-
- if (needs_sort) {
- // If we sorted the list, clear the z dirty flag for everyone, since even
- // layers that were not updated will have been sorted into the right
- // order.
- layer->set_z_dirty(false);
- }
-
- if (!layer->ShouldPaint() && !layer->GetSavedShouldPaint()) {
- // Was not updated, so any layer dirtiness persists.
- continue;
- }
-
- // Clear layer dirtiness.
- layer->set_region_dirty(false);
- layer->set_content_dirty(false);
-
- // Save current region and paintability for reference on the next frame.
- layer->SaveShouldPaint();
- layer->SaveOuterClipRegion();
- }
-
- layer_ghost_list_.clear();
-
-#ifdef OS_MACOSX
- DestroyDisplaySurface();
-#endif
-}
-
-void RendererCairo::ClipArea(cairo_t* cr, LayerList::const_iterator it) {
- for (LayerList::const_iterator i = it; i != layer_list_.end(); i++) {
- // Preparing and updating the Layer.
- Layer* layer = *i;
- if (!layer->ShouldClip()) continue;
-
- if (!layer->everywhere()) {
- AddDisplayRegion(cr);
- AddRectangleRegion(cr, layer->inner_clip_region());
- }
- cairo_clip(cr);
- }
-}
-
-void RendererCairo::AddLayer(Layer* layer) {
- layer_list_.push_back(layer);
-}
-
-void RendererCairo::RemoveLayer(Layer* layer) {
- LayerList::iterator i = std::find(layer_list_.begin(),
- layer_list_.end(),
- layer);
- if (layer_list_.end() == i) {
- return;
- }
- layer_list_.erase(i);
- if (layer->GetSavedShouldPaint()) {
- // Need to remember this layer's region so we can redraw it on the next
- // frame.
- layer_ghost_list_.push_back(layer->GetSavedOuterClipRegion());
- }
-}
-
-void RendererCairo::InitCommon() {
-#if defined(OS_LINUX) || defined(OS_WIN)
- CreateDisplaySurface();
-#endif
-#if defined(COMPOSITING_TO_IMAGE) || !defined(OS_LINUX)
- CreateOffscreenSurface();
-#endif
-}
-
-void RendererCairo::CreateDisplaySurface() {
-#if defined(OS_LINUX)
- display_surface_ = cairo_xlib_surface_create(display_,
- window_,
- XDefaultVisual(display_, 0),
- display_width(),
- display_height());
-#elif defined(OS_MACOSX)
- if (!mac_cg_context_ref_) {
- // Can't create the surface until we get a valid CGContextRef. If we don't
- // have one it may be because we haven't yet gotten one from
- // HandleCocoaEvent() in main_mac.mm, or we may have initialized with a
- // drawing model other than Core Graphics (in which case we are never going
- // to get one and rendering won't work).
- // TODO(tschmelcher): Support the other drawing models too.
- DLOG(INFO) << "No CGContextRef, cannot initialize yet";
- return;
- }
- // Normally this function requires the caller to transform the CG coordinate
- // space to match Cairo's origin convention, but in NPAPI it happens to
- // already be that way.
- display_surface_ = cairo_quartz_surface_create_for_cg_context(
- mac_cg_context_ref_,
- display_width(),
- display_height());
-#elif defined(OS_WIN)
- HDC hdc = GetDC(hwnd_);
-
- display_surface_ = cairo_win32_surface_create(hdc);
-#endif
-
- if (CAIRO_STATUS_SUCCESS != cairo_surface_status(display_surface_)) {
- DLOG(ERROR) << "Failed to create display surface";
- DestroyDisplaySurface();
- return;
- }
-
-#ifdef OS_WIN
- // Check the surface to make sure it has the correct clip box.
- cairo_win32_surface_t* cairo_surface =
- reinterpret_cast<cairo_win32_surface_t*>(display_surface_);
- if (cairo_surface->extents.width != display_width() ||
- cairo_surface->extents.height != display_height()) {
- // The clip box doesn't have the right info. Need to do the following:
- // 1. Update the surface parameters to the right rectangle.
- // 2. Try to update the DC clip region.
- DLOG(WARNING) << "CreateDisplaySurface updates clip box from (0,0,"
- << cairo_surface->extents.width << ","
- << cairo_surface->extents.height << ") to (0,0,"
- << display_width() << "," << display_height() << ").";
- HRGN hRegion = CreateRectRgn(0, 0, display_width(), display_height());
- int result = SelectClipRgn(hdc, hRegion);
- if (result == ERROR) {
- LOG(ERROR) << "CreateDisplaySurface SelectClipRgn returns ERROR";
- } else if (result == NULLREGION) {
- // This should not happen since the ShowWindow is called.
- LOG(ERROR) << "CreateDisplaySurface SelectClipRgn returns NULLREGION";
- }
- DeleteObject(hRegion);
- cairo_surface->extents.width = display_width();
- cairo_surface->extents.height = display_height();
- }
-
- ReleaseDC(hwnd_, hdc);
-#endif
-}
-
-void RendererCairo::DestroyDisplaySurface() {
- if (display_surface_ != NULL) {
- cairo_surface_destroy(display_surface_);
- display_surface_ = NULL;
- }
-}
-
-void RendererCairo::CreateOffscreenSurface() {
- offscreen_surface_ = CreateSimilarSurface(CAIRO_CONTENT_COLOR,
- display_width(),
- display_height());
- if (!offscreen_surface_) {
- DLOG(ERROR) << "Failed to create offscreen surface";
- }
-}
-
-void RendererCairo::DestroyOffscreenSurface() {
- if (offscreen_surface_) {
- cairo_surface_destroy(offscreen_surface_);
- offscreen_surface_ = NULL;
- }
-}
-
-#if defined(COMPOSITING_TO_IMAGE) || defined(OS_MACOSX)
-static cairo_format_t CairoFormatFromCairoContent(cairo_content_t content) {
- switch (content) {
- case CAIRO_CONTENT_COLOR:
- return CAIRO_FORMAT_RGB24;
- case CAIRO_CONTENT_ALPHA:
- return CAIRO_FORMAT_A8;
- case CAIRO_CONTENT_COLOR_ALPHA:
- return CAIRO_FORMAT_ARGB32;
- default:
- DCHECK(false);
- return CAIRO_FORMAT_ARGB32;
- }
-}
-#endif
-
-cairo_surface_t* RendererCairo::CreateSimilarSurface(cairo_content_t content,
- int width,
- int height) {
- cairo_surface_t* similar;
-#if defined(COMPOSITING_TO_IMAGE)
- similar = cairo_image_surface_create(CairoFormatFromCairoContent(content),
- width,
- height);
-#elif defined(OS_LINUX) || defined(OS_WIN)
- if (!display_surface_) {
- DLOG(INFO) << "No display surface, cannot create similar surface";
- return NULL;
- }
- similar = cairo_surface_create_similar(display_surface_,
- content,
- width,
- height);
-#else // OS_MACOSX
- // On OSX we can't use cairo_surface_create_similar() because display_surface_
- // is only valid during Paint(), so instead hard-code what a
- // cairo_surface_create_similar() call would do. Conveniently the OSX
- // implementation doesn't actually make use of the surface argument.
- // (Note that this code path is not actually taken right now because we use
- // COMPOSITING_TO_IMAGE on OSX.)
- similar = cairo_quartz_surface_create(CairoFormatFromCairoContent(content),
- width,
- height);
-#endif
-
- if (CAIRO_STATUS_SUCCESS != cairo_surface_status(similar)) {
- DLOG(ERROR) << "Failed to create similar surface";
- cairo_surface_destroy(similar);
- similar = NULL;
- }
-
- return similar;
-}
-
-void RendererCairo::AddDisplayRegion(cairo_t* cr) {
- cairo_rectangle(cr, 0, 0, display_width(), display_height());
-}
-
-void RendererCairo::AddRegion(cairo_t* cr, const Layer::Region& region) {
- if (region.everywhere) {
- AddDisplayRegion(cr);
- } else {
- AddRectangleRegion(cr, region);
- }
-}
-
-void RendererCairo::UninitCommon() {
- // Don't need to do anything.
-}
-
-Renderer::InitStatus RendererCairo::InitPlatformSpecific(
- const DisplayWindow& display_window,
- bool off_screen) {
-#if defined(OS_LINUX)
- const DisplayWindowLinux &display_platform =
- static_cast<const DisplayWindowLinux&>(display_window);
- display_ = display_platform.display();
- window_ = display_platform.window();
-#elif defined(OS_MACOSX)
- const DisplayWindowMac &display_platform =
- static_cast<const DisplayWindowMac&>(display_window);
- mac_cg_context_ref_ = display_platform.cg_context_ref();
-#elif defined(OS_WIN)
- const DisplayWindowWindows &display_platform =
- static_cast<const DisplayWindowWindows&>(display_window);
- hwnd_ = display_platform.hwnd();
- if (NULL == hwnd_) {
- return INITIALIZATION_ERROR;
- }
-#endif
-
- return SUCCESS;
-}
-
-#ifdef OS_MACOSX
-bool RendererCairo::ChangeDisplayWindow(const DisplayWindow& display_window) {
- const DisplayWindowMac &display_platform =
- static_cast<const DisplayWindowMac&>(display_window);
- mac_cg_context_ref_ = display_platform.cg_context_ref();
-}
-#endif
-
-// Handles the plugin resize event.
-void RendererCairo::Resize(int width, int height) {
- DLOG(INFO) << "To Resize " << width << " x " << height;
- SetClientSize(width, height);
-
-#if defined(OS_LINUX)
- if (display_surface_) {
- cairo_xlib_surface_set_size(display_surface_, width, height);
- }
-#elif defined(OS_WIN)
- DestroyDisplaySurface();
- CreateDisplaySurface();
-#endif
-
- DestroyOffscreenSurface();
-#if defined(COMPOSITING_TO_IMAGE) || !defined(OS_LINUX)
- CreateOffscreenSurface();
-#endif
-}
-
-// The platform specific part of BeginDraw.
-bool RendererCairo::PlatformSpecificBeginDraw() {
- return true;
-}
-
-// Platform specific version of CreateTexture2D
-Texture2D::Ref RendererCairo::CreatePlatformSpecificTexture2D(
- int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- return Texture2D::Ref(TextureCairo::Create(service_locator(),
- format,
- levels,
- width,
- height,
- enable_render_surfaces));
-}
-
-// The platform specific part of EndDraw.
-void RendererCairo::PlatformSpecificEndDraw() {
- // Don't need to do anything.
-}
-
-// The platform specific part of StartRendering.
-bool RendererCairo::PlatformSpecificStartRendering() {
- return true;
-}
-
-// The platform specific part of EndRendering.
-void RendererCairo::PlatformSpecificFinishRendering() {
- Paint();
-}
-
-// The platform specific part of Present.
-void RendererCairo::PlatformSpecificPresent() {
- // Don't need to do anything.
-}
-
-// TODO(fransiskusx): DO need to implement before shipped.
-// Get a single fullscreen display mode by id.
-// Returns true on success, false on error.
-bool RendererCairo::GetDisplayMode(int id, DisplayMode* mode) {
- NOTIMPLEMENTED();
- return true;
-}
-
-// TODO(fransiskusx): DO need to implement before shipped.
-// Get a vector of the available fullscreen display modes.
-// Clears *modes on error.
-void RendererCairo::GetDisplayModes(std::vector<DisplayMode>* modes) {
- NOTIMPLEMENTED();
-}
-
-// TODO(fransiskusx): DO need to implement before shipped.
-// The platform specific part of Clear.
-void RendererCairo::PlatformSpecificClear(const Float4 &color,
- bool color_flag,
- float depth,
- bool depth_flag,
- int stencil,
- bool stencil_flag) {
- NOTIMPLEMENTED();
-}
-
-// TODO(fransiskusx): DO need to implement before shipped.
-// Sets the viewport. This is the platform specific version.
-void RendererCairo::SetViewportInPixels(int left,
- int top,
- int width,
- int height,
- float min_z,
- float max_z) {
- NOTIMPLEMENTED();
-}
-
-// Turns fullscreen display on.
-// Parameters:
-// display: a platform-specific display identifier
-// mode_id: a mode returned by GetDisplayModes
-// Returns true on success, false on failure.
-bool RendererCairo::GoFullscreen(const DisplayWindow& display,
- int mode_id) {
- if (!fullscreen_) {
- DLOG(INFO) << "RendererCairo entering fullscreen";
-#if defined(OS_LINUX)
- const DisplayWindowLinux &display_platform =
- static_cast<const DisplayWindowLinux&>(display);
- display_ = display_platform.display();
- window_ = display_platform.window();
- XWindowAttributes window_attributes;
- if (XGetWindowAttributes(display_, window_, &window_attributes)) {
- fullscreen_ = true;
- SetClientSize(window_attributes.width, window_attributes.height);
- DestroyDisplaySurface();
- CreateDisplaySurface();
- DestroyOffscreenSurface();
-#ifdef COMPOSITING_TO_IMAGE
- CreateOffscreenSurface();
-#endif
- }
-#elif defined(OS_WIN)
- DEVMODE dev_mode;
- if (hwnd_ != NULL &&
- EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dev_mode)) {
- int width = dev_mode.dmPelsWidth;
- int height = dev_mode.dmPelsHeight;
-
- fullscreen_ = true;
- Resize(width, height);
- }
-#endif
- }
- return fullscreen_;
-}
-
-// Cancels fullscreen display. Restores rendering to windowed mode
-// with the given width and height.
-// Parameters:
-// display: a platform-specific display identifier
-// width: the width to which to restore windowed rendering
-// height: the height to which to restore windowed rendering
-// Returns true on success, false on failure.
-bool RendererCairo::CancelFullscreen(const DisplayWindow& display,
- int width, int height) {
- if (fullscreen_) {
- DLOG(INFO) << "RendererCairo exiting fullscreen";
-#if defined(OS_LINUX)
- const DisplayWindowLinux &display_platform =
- static_cast<const DisplayWindowLinux&>(display);
- display_ = display_platform.display();
- window_ = display_platform.window();
-
- fullscreen_ = false;
- SetClientSize(width, height);
- DestroyDisplaySurface();
- CreateDisplaySurface();
- DestroyOffscreenSurface();
-#ifdef COMPOSITING_TO_IMAGE
- CreateOffscreenSurface();
-#endif
-#elif defined(OS_WIN)
- if (hwnd_ == NULL) {
- // Not initialized.
- return false;
- }
- fullscreen_ = false;
- Resize(width, height);
-#endif
- }
- return true;
-}
-
-// TODO(fransiskusx): Need to implement it later.
-// Tells whether we're currently displayed fullscreen or not.
-bool RendererCairo::fullscreen() const {
- return fullscreen_;
-}
-
-// Sets the client's size. Overridden from Renderer.
-void RendererCairo::SetClientSize(int width, int height) {
- Renderer::SetClientSize(width, height);
- size_dirty_ = true;
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-// Sets rendering to the back buffer.
-void RendererCairo::SetBackBufferPlatformSpecific() {
- // Don't need to do anything.
- NOTIMPLEMENTED();
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-// Applies states that have been modified (marked dirty).
-void RendererCairo::ApplyDirtyStates() {
- // Don't need to do anything.
- NOTIMPLEMENTED();
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-// Creates a platform specific ParamCache.
-ParamCache* RendererCairo::CreatePlatformSpecificParamCache() {
- NOTIMPLEMENTED();
- return NULL;
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-// Platform specific version of CreateTextureCUBE.
-TextureCUBE::Ref RendererCairo::CreatePlatformSpecificTextureCUBE(
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- NOTIMPLEMENTED();
- return TextureCUBE::Ref();
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-void RendererCairo::PushRenderStates(State* state) {
- // Don't need to do anything.;
- NOTIMPLEMENTED();
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-// Sets the render surfaces on a specific platform.
-void RendererCairo::SetRenderSurfacesPlatformSpecific(
- const RenderSurface* surface,
- const RenderDepthStencilSurface* depth_surface) {
- // Don't need to do anything.
- NOTIMPLEMENTED();
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-// Creates a StreamBank, returning a platform specific implementation class.
-StreamBank::Ref RendererCairo::CreateStreamBank() {
- NOTIMPLEMENTED();
- return StreamBank::Ref();
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-// Creates a Primitive, returning a platform specific implementation class.
-Primitive::Ref RendererCairo::CreatePrimitive() {
- NOTIMPLEMENTED();
- return Primitive::Ref();
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-// Creates a DrawElement, returning a platform specific implementation
-// class.
-DrawElement::Ref RendererCairo::CreateDrawElement() {
- NOTIMPLEMENTED();
- return DrawElement::Ref();
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-// Creates and returns a platform specific float buffer
-VertexBuffer::Ref RendererCairo::CreateVertexBuffer() {
- NOTIMPLEMENTED();
- return VertexBuffer::Ref();
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-// Creates and returns a platform specific integer buffer
-IndexBuffer::Ref RendererCairo::CreateIndexBuffer() {
- NOTIMPLEMENTED();
- return IndexBuffer::Ref();
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-// Creates and returns a platform specific effect object
-Effect::Ref RendererCairo::CreateEffect() {
- NOTIMPLEMENTED();
- return Effect::Ref();
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-// Creates and returns a platform specific Sampler object.
-Sampler::Ref RendererCairo::CreateSampler() {
- NOTIMPLEMENTED();
- return Sampler::Ref();
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-// Returns a platform specific 4 element swizzle table for RGBA UByteN fields.
-// The should contain the index of R, G, B, and A in that order for the
-// current platform.
-const int* RendererCairo::GetRGBAUByteNSwizzleTable() {
- static int swizzle_table[] = { 0, 1, 2, 3, };
- NOTIMPLEMENTED();
- return swizzle_table;
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-// Creates and returns a platform-specific RenderDepthStencilSurface object
-// for use as a depth-stencil render target.
-RenderDepthStencilSurface::Ref RendererCairo::CreateDepthStencilSurface(
- int width,
- int height) {
- NOTIMPLEMENTED();
- return RenderDepthStencilSurface::Ref();
-}
-
-// TODO(fransiskusx): This function is not applicable to 2D rendering.
-void RendererCairo::SetState(Renderer* renderer, Param* param) {
- // Don't need to do anything.
- NOTIMPLEMENTED();
-}
-
-void RendererCairo::PopRenderStates() {
- NOTIMPLEMENTED();
-}
-
-} // namespace o2d
-
-} // namespace o3d
diff --git a/o3d/core/cross/cairo/renderer_cairo.h b/o3d/core/cross/cairo/renderer_cairo.h
deleted file mode 100644
index de6bef3..0000000
--- a/o3d/core/cross/cairo/renderer_cairo.h
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-// Renderer that is using 2D Library Cairo.
-
-#ifndef O3D_CORE_CROSS_CAIRO_RENDERER_CAIRO_H_
-#define O3D_CORE_CROSS_CAIRO_RENDERER_CAIRO_H_
-
-#include <cairo.h>
-#include <build/build_config.h>
-#include <list>
-#include <vector>
-
-#include "core/cross/renderer_platform.h"
-#include "core/cross/renderer.h"
-#include "core/cross/cairo/layer.h"
-
-namespace o3d {
-
-namespace o2d {
-
-class RendererCairo : public Renderer {
- public:
- static RendererCairo* CreateDefault(ServiceLocator* service_locator);
-
- virtual ~RendererCairo();
-
- // Initializes stuff that has to happen after Init
- virtual void InitCommon();
-
- virtual void UninitCommon();
-
- // Initialises the renderer for use, claiming hardware resources.
- virtual InitStatus InitPlatformSpecific(const DisplayWindow& display,
- bool off_screen);
-
-#ifdef OS_MACOSX
- virtual bool ChangeDisplayWindow(const DisplayWindow& display);
-
- virtual bool SupportsCoreGraphics() const { return true; }
-#endif
-
- // Released all hardware resources.
- virtual void Destroy();
-
- // Paint the frame to the main view
- void Paint();
-
- // Insert the given Layer to the back of the array.
- void AddLayer(Layer* image);
-
- // Remove the given Layer from the array.
- void RemoveLayer(Layer* image);
-
- // Create a cairo surface with a similar back-end as the display surface.
- cairo_surface_t* CreateSimilarSurface(cairo_content_t content,
- int width,
- int height);
-
- // Handles the plugin resize event.
- virtual void Resize(int width, int height);
-
- // Creates and returns a platform-specific RenderDepthStencilSurface object
- // for use as a depth-stencil render target.
- virtual RenderDepthStencilSurface::Ref CreateDepthStencilSurface(int width,
- int height);
-
- // Turns fullscreen display on.
- // Parameters:
- // display: a platform-specific display identifier
- // mode_id: a mode returned by GetDisplayModes
- // Returns true on success, false on failure.
- virtual bool GoFullscreen(const DisplayWindow& display,
- int mode_id);
-
- // Cancels fullscreen display. Restores rendering to windowed mode
- // with the given width and height.
- // Parameters:
- // display: a platform-specific display identifier
- // width: the width to which to restore windowed rendering
- // height: the height to which to restore windowed rendering
- // Returns true on success, false on failure.
- virtual bool CancelFullscreen(const DisplayWindow& display,
- int width, int height);
-
- // Tells whether we're currently displayed fullscreen or not.
- virtual bool fullscreen() const;
-
- // Get a vector of the available fullscreen display modes.
- // Clears *modes on error.
- virtual void GetDisplayModes(std::vector<DisplayMode> *modes);
-
- // Get a single fullscreen display mode by id.
- // Returns true on success, false on error.
- virtual bool GetDisplayMode(int id, DisplayMode *mode);
-
- // Sets the state to the value of the param.
- // Parameters:
- // renderer: the renderer
- // param: param with state data
- virtual void SetState(Renderer* renderer, Param* param);
-
- // Creates a StreamBank, returning a platform specific implementation class.
- virtual StreamBank::Ref CreateStreamBank();
-
- // Creates a Primitive, returning a platform specific implementation class.
- virtual Primitive::Ref CreatePrimitive();
-
- // Creates a DrawElement, returning a platform specific implementation
- // class.
- virtual DrawElement::Ref CreateDrawElement();
-
- // Creates and returns a platform specific float buffer
- virtual VertexBuffer::Ref CreateVertexBuffer();
-
- // Creates and returns a platform specific integer buffer
- virtual IndexBuffer::Ref CreateIndexBuffer();
-
- // Creates and returns a platform specific effect object
- virtual Effect::Ref CreateEffect();
-
- // Creates and returns a platform specific Sampler object.
- virtual Sampler::Ref CreateSampler();
-
- // Returns a platform specific 4 element swizzle table for RGBA UByteN
- // fields.
- // The should contain the index of R, G, B, and A in that order for the
- // current platform.
- virtual const int* GetRGBAUByteNSwizzleTable();
-
- // Overriden from Renderer
- void PushRenderStates(State* state);
-
- // Overrider from Renderer
- void PopRenderStates();
-
- protected:
- // Keep the constructor protected so only factory methods can create
- // renderers.
- explicit RendererCairo(ServiceLocator* service_locator);
-
- // Sets the client's size. Overridden from Renderer.
- void SetClientSize(int width, int height);
-
- // Sets rendering to the back buffer.
- virtual void SetBackBufferPlatformSpecific();
-
- // Sets the render surfaces on a specific platform.
- virtual void SetRenderSurfacesPlatformSpecific(
- const RenderSurface* surface,
- const RenderDepthStencilSurface* depth_surface);
-
- // Creates a platform specific ParamCache.
- virtual ParamCache* CreatePlatformSpecificParamCache();
-
- // Platform specific version of CreateTexture2D
- virtual Texture2D::Ref CreatePlatformSpecificTexture2D(
- int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
- // Platform specific version of CreateTextureCUBE.
- virtual TextureCUBE::Ref CreatePlatformSpecificTextureCUBE(
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
- // The platform specific part of BeginDraw.
- virtual bool PlatformSpecificBeginDraw();
-
- // The platform specific part of EndDraw.
- virtual void PlatformSpecificEndDraw();
-
- // The platform specific part of StartRendering.
- virtual bool PlatformSpecificStartRendering();
-
- // The platform specific part of EndRendering.
- virtual void PlatformSpecificFinishRendering();
-
- // The platform specific part of Present.
- virtual void PlatformSpecificPresent();
-
- // The platform specific part of Clear.
- virtual void PlatformSpecificClear(const Float4 &color,
- bool color_flag,
- float depth,
- bool depth_flag,
- int stencil,
- bool stencil_flag);
-
- // Applies states that have been modified (marked dirty).
- virtual void ApplyDirtyStates();
-
- // Sets the viewport. This is the platform specific version.
- virtual void SetViewportInPixels(int left,
- int top,
- int width,
- int height,
- float min_z,
- float max_z);
-
- private:
- typedef std::vector<Layer*> LayerList;
- typedef std::vector<Layer::Region> RegionList;
-
- // Clip the area of the current layer that will collide with other images.
- void ClipArea(cairo_t* cr, LayerList::const_iterator it);
-
- void CreateDisplaySurface();
- void DestroyDisplaySurface();
-
- void CreateOffscreenSurface();
- void DestroyOffscreenSurface();
-
- void AddDisplayRegion(cairo_t* cr);
- void AddRegion(cairo_t* cr, const Layer::Region& region);
-
-#if defined(OS_LINUX)
- // Linux Client Display
- Display* display_;
- // Linux Client Window
- Window window_;
-#elif defined(OS_MACOSX)
- CGContextRef mac_cg_context_ref_;
-#elif defined(OS_WIN)
- HWND hwnd_;
-#endif
-
- // The OS-specific cairo surface for our display window.
- cairo_surface_t* display_surface_;
- // An offscreen surface for compositing the frame before drawing to the
- // display surface.
- cairo_surface_t* offscreen_surface_;
-
- // List of all layers.
- LayerList layer_list_;
-
- // Saved regions of formerly visible layers deleted since the previous frame
- // was rendered.
- RegionList layer_ghost_list_;
-
- // Fullscreen mode.
- bool fullscreen_;
-
- // Whether or not the display window has been resized since the last frame was
- // rendered.
- bool size_dirty_;
-};
-
-} // namespace o2d
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_CAIRO_RENDERER_CAIRO_H_
diff --git a/o3d/core/cross/cairo/texture_cairo.cc b/o3d/core/cross/cairo/texture_cairo.cc
deleted file mode 100644
index da77732..0000000
--- a/o3d/core/cross/cairo/texture_cairo.cc
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
- * Copyright 2011, 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.
- */
-
-
-// Implementations of the abstract Texture2D.
-// Texture Class for handling Cairo Rendering Mode.
-
-#include "core/cross/cairo/texture_cairo.h"
-
-#include <string.h>
-
-#include "core/cross/cairo/renderer_cairo.h"
-
-namespace o3d {
-
-namespace {
-
-Texture::RGBASwizzleIndices g_gl_abgr32f_swizzle_indices = {0, 1, 2, 3};
-
-} // anonymous namespace.
-
-namespace o2d {
-
-static const cairo_content_t kCairoContentInvalid =
- static_cast<cairo_content_t>(-1);
-
-static cairo_content_t CairoContentFromO3DFormat(
- Texture::Format format) {
- switch (format) {
- case Texture::ARGB8:
- return CAIRO_CONTENT_COLOR_ALPHA;
- case Texture::XRGB8:
- return CAIRO_CONTENT_COLOR;
- default:
- return kCairoContentInvalid;
- }
- // Cairo also supports a pure-alpha surface, but we don't expose that.
-}
-
-TextureCairo::TextureCairo(ServiceLocator* service_locator,
- cairo_surface_t* surface,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool enable_render_surfaces)
- : Texture2D(service_locator,
- width,
- height,
- format,
- levels,
- enable_render_surfaces),
- surface_(surface),
- content_dirty_(false) {
- DLOG(INFO) << "Texture2D Construct";
- DCHECK_NE(format, Texture::UNKNOWN_FORMAT);
-}
-
-// Creates a new texture object from scratch.
-TextureCairo* TextureCairo::Create(ServiceLocator* service_locator,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool enable_render_surfaces) {
- cairo_content_t content = CairoContentFromO3DFormat(format);
- if (kCairoContentInvalid == content) {
- DLOG(ERROR) << "Texture format " << format << " not supported by Cairo";
- return NULL;
- }
-
- RendererCairo* renderer = static_cast<RendererCairo*>(
- service_locator->GetService<Renderer>());
- // NOTE(tschmelcher): Strangely, on Windows if COMPOSITING_TO_IMAGE is turned
- // off in RendererCairo then we actually get much better performance if we use
- // an image surface for textures rather than using CreateSimilarSurface(). But
- // the performance of COMPOSITING_TO_IMAGE narrowly takes first place.
- cairo_surface_t* surface = renderer->CreateSimilarSurface(
- content,
- width,
- height);
- if (!surface) {
- DLOG(ERROR) << "Failed to create texture surface";
- return NULL;
- }
-
- return new TextureCairo(service_locator,
- surface,
- format,
- levels,
- width,
- height,
- enable_render_surfaces);
-}
-
-// In 2D: is not really used
-const Texture::RGBASwizzleIndices& TextureCairo::GetABGR32FSwizzleIndices() {
- NOTIMPLEMENTED();
- return g_gl_abgr32f_swizzle_indices;
-}
-
-TextureCairo::~TextureCairo() {
- cairo_surface_destroy(surface_);
- DLOG(INFO) << "Texture2DCairo Destruct";
-}
-
-static void CopyNonPremultipliedAlphaToPremultipliedAlpha(
- const unsigned char* src_data,
- int src_pitch,
- unsigned char* dst_data,
- int dst_pitch,
- unsigned width,
- unsigned height) {
- // Cairo supports only premultiplied alpha, but we get images as
- // non-premultiplied alpha, so we have to convert.
- for (unsigned i = 0; i < height; ++i) {
- for (unsigned j = 0; j < width; ++j) {
- // NOTE: This assumes a little-endian architecture (e.g., x86). It
- // works for RGBA or BGRA where alpha is in byte 3.
- // Get alpha.
- uint8 alpha = src_data[3];
- // Convert each colour.
- for (int i = 0; i < 3; i++) {
- dst_data[i] = (src_data[i] * alpha + 128U) / 255U;
- }
- // Copy alpha.
- dst_data[3] = alpha;
- src_data += 4;
- dst_data += 4;
- }
- src_data += src_pitch - width * 4;
- dst_data += dst_pitch - width * 4;
- }
-}
-
-// Set the image data to the renderer
-void TextureCairo::SetRect(int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned src_width,
- unsigned src_height,
- const void* src_data_void,
- int src_pitch) {
- DLOG(INFO) << "Texture2DCairo SetRect";
-
- if (0 != level) {
- // Cairo does not support/need mip-maps.
- return;
- }
-
- unsigned char* src_data =
- reinterpret_cast<unsigned char*>(const_cast<void*>(src_data_void));
-
- if (cairo_surface_get_type(surface_) == CAIRO_SURFACE_TYPE_IMAGE) {
- // Copy directly to the image surface's data buffer.
-
- cairo_surface_flush(surface_);
-
- unsigned char* dst_data = cairo_image_surface_get_data(surface_);
-
- int dst_pitch = cairo_image_surface_get_stride(surface_);
-
- dst_data += dst_top * dst_pitch + dst_left * 4;
-
- if (ARGB8 == format()) {
- CopyNonPremultipliedAlphaToPremultipliedAlpha(src_data,
- src_pitch,
- dst_data,
- dst_pitch,
- src_width,
- src_height);
- } else {
- for (unsigned i = 0; i < src_height; ++i) {
- memcpy(dst_data, src_data, src_width * 4);
- src_data += src_pitch;
- dst_data += dst_pitch;
- }
- }
-
- cairo_surface_mark_dirty(surface_);
- } else {
- // No way to get a pointer to a data buffer for the surface, so we have to
- // update it using cairo operations.
-
- // Create a source surface for the paint operation.
- cairo_surface_t* source_surface;
- if (ARGB8 == format()) {
- // Have to convert to premultiplied alpha, so we need to make a temporary
- // image surface and copy to it.
- source_surface = cairo_image_surface_create(
- CAIRO_FORMAT_ARGB32,
- src_width,
- src_height);
-
- cairo_surface_flush(source_surface);
-
- unsigned char* dst_data = cairo_image_surface_get_data(source_surface);
-
- int dst_pitch = cairo_image_surface_get_stride(source_surface);
-
- CopyNonPremultipliedAlphaToPremultipliedAlpha(src_data,
- src_pitch,
- dst_data,
- dst_pitch,
- src_width,
- src_height);
-
- cairo_surface_mark_dirty(source_surface);
- } else {
- // No conversion needed, so we can paint directly from the input buffer.
- source_surface = cairo_image_surface_create_for_data(
- src_data,
- CAIRO_FORMAT_RGB24,
- src_width,
- src_height,
- src_pitch);
- }
-
- // Now paint it to this texture's surface.
- cairo_t* context = cairo_create(surface_);
- cairo_set_operator(context, CAIRO_OPERATOR_SOURCE);
- cairo_set_source_surface(context, source_surface, dst_left, dst_top);
- cairo_rectangle(context, dst_left, dst_top, src_width, src_height);
- cairo_fill(context);
- cairo_destroy(context);
-
- cairo_surface_destroy(source_surface);
- }
-
- set_content_dirty(true);
-
- TextureUpdated();
-}
-
-// Locks the given mipmap level of this texture for loading from main memory,
-// and returns a pointer to the buffer.
-bool TextureCairo::PlatformSpecificLock(
- int level, void** data, int* pitch, Texture::AccessMode mode) {
- NOTIMPLEMENTED();
- return true;
-}
-
-// In Open GL: Unlocks the given mipmap level of this texture, uploading
-// the main memory data buffer to GL.
-//
-// In 2D: is not really used
-bool TextureCairo::PlatformSpecificUnlock(int level) {
- NOTIMPLEMENTED();
- return true;
-}
-
-// In 2D: is not really used
-RenderSurface::Ref TextureCairo::PlatformSpecificGetRenderSurface(
- int mip_level) {
- DCHECK_LT(mip_level, levels());
- NOTIMPLEMENTED();
- return RenderSurface::Ref(NULL);
-}
-
-// Returns the implementation-specific texture handle for this texture.
-void* TextureCairo::GetTextureHandle() const {
- NOTIMPLEMENTED();
- return reinterpret_cast<void*>(NULL);
-}
-
-} // namespace o2d
-
-} // namespace o3d
diff --git a/o3d/core/cross/cairo/texture_cairo.h b/o3d/core/cross/cairo/texture_cairo.h
deleted file mode 100644
index 70829e7..0000000
--- a/o3d/core/cross/cairo/texture_cairo.h
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright 2011, 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.
- */
-
-
-// Implementations of the abstract Texture2D.
-// Texture Class for handling Cairo Rendering Mode.
-
-#ifndef O3D_CORE_CROSS_CAIRO_TEXTURE_CAIRO_H_
-#define O3D_CORE_CROSS_CAIRO_TEXTURE_CAIRO_H_
-
-#include "core/cross/texture.h"
-
-typedef struct _cairo cairo_t;
-typedef struct _cairo_surface cairo_surface_t;
-
-namespace o3d {
-
-namespace o2d {
-
-class RendererCairo;
-
-// Texture2DCairo implements the Texture2D interface.
-class TextureCairo : public Texture2D {
- public:
- typedef SmartPointer<TextureCairo> Ref;
-
- // Creates a new Texture2DCairo with the given specs. If the texture
- // creation fails then it returns NULL otherwise it returns a pointer to the
- // newly created Texture object.
- static TextureCairo* Create(ServiceLocator* service_locator,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool enable_render_surfaces);
-
- virtual ~TextureCairo();
-
- // Overridden from Texture2D
- virtual void SetRect(int level,
- unsigned left,
- unsigned top,
- unsigned width,
- unsigned height,
- const void* src_data,
- int src_pitch);
-
- // Gets a RGBASwizzleIndices that contains a mapping from
- // RGBA to the internal format used by the rendering API.
- virtual const RGBASwizzleIndices& GetABGR32FSwizzleIndices();
-
- cairo_surface_t* surface() const {
- return surface_;
- }
-
- bool content_dirty() const {
- return content_dirty_;
- }
-
- void set_content_dirty(bool content_dirty) {
- content_dirty_ = content_dirty;
- }
-
- protected:
- // Overridden from Texture2D
- virtual bool PlatformSpecificLock(int level, void** texture_data, int* pitch,
- AccessMode mode);
-
- // Overridden from Texture2D
- virtual bool PlatformSpecificUnlock(int level);
-
- // Overridden from Texture2D
- virtual RenderSurface::Ref PlatformSpecificGetRenderSurface(int mip_level);
-
- // Returns the implementation-specific texture handle for this texture.
- virtual void* GetTextureHandle() const;
-
- private:
- // Initializes the Texture2D.
- TextureCairo(ServiceLocator* service_locator,
- cairo_surface_t* surface,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool enable_render_surfaces);
-
- // The Cairo surface for this texture.
- cairo_surface_t* surface_;
-
- // Whether or not this texture's content has changed since it was last updated
- // on-screen.
- bool content_dirty_;
-};
-
-} // namespace o2d
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_CAIRO_TEXTURE_CAIRO_H_
diff --git a/o3d/core/cross/callback.h b/o3d/core/cross/callback.h
deleted file mode 100644
index bf9d8d2..0000000
--- a/o3d/core/cross/callback.h
+++ /dev/null
@@ -1,348 +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 contain the class declarations related to callbacks in o3d.
-
-#ifndef O3D_CORE_CROSS_CALLBACK_H_
-#define O3D_CORE_CROSS_CALLBACK_H_
-
-#include "core/cross/smart_ptr.h"
-
-namespace o3d {
-
-class Closure {
- public:
- virtual ~Closure() { }
- virtual bool IsRepeatable() const { return false; }
- virtual void CheckIsRepeatable() const { }
- virtual void Run() = 0;
- protected:
- Closure() {}
-};
-
-template <class R>
-class ResultCallback {
- public:
- virtual ~ResultCallback() { }
- virtual bool IsRepeatable() const { return false; }
- virtual void CheckIsRepeatable() const { }
- virtual R Run() = 0;
- protected:
- ResultCallback() {}
-};
-
-
-template <class A1>
-class Callback1 {
- public:
- virtual ~Callback1() { }
- virtual bool IsRepeatable() const { return false; }
- virtual void CheckIsRepeatable() const { }
- virtual void Run(A1) = 0;
- protected:
- Callback1() {}
-};
-
-template <class R, class A1>
-class ResultCallback1 {
- public:
- virtual ~ResultCallback1() { }
- virtual bool IsRepeatable() const { return false; }
- virtual void CheckIsRepeatable() const { }
- virtual R Run(A1) = 0;
- protected:
- ResultCallback1() {}
-};
-
-template <class A1, class A2>
-class Callback2 {
- public:
- virtual ~Callback2() { }
- virtual bool IsRepeatable() const { return false; }
- virtual void CheckIsRepeatable() const { }
- virtual void Run(A1, A2) = 0;
- protected:
- Callback2() {}
-};
-
-template <class R, class A1, class A2>
-class ResultCallback2 {
- public:
- virtual ~ResultCallback2() { }
- virtual bool IsRepeatable() const { return false; }
- virtual void CheckIsRepeatable() const { }
- virtual R Run(A1, A2) = 0;
- protected:
- ResultCallback2() {}
-};
-
-template <class A1, class A2, class A3>
-class Callback3 {
- public:
- virtual ~Callback3() { }
- virtual bool IsRepeatable() const { return false; }
- virtual void CheckIsRepeatable() const { }
- virtual void Run(A1, A2, A3) = 0;
- protected:
- Callback3() {}
-};
-
-template <class R, class A1, class A2, class A3>
-class ResultCallback3 {
- public:
- virtual ~ResultCallback3() { }
- virtual bool IsRepeatable() const { return false; }
- virtual void CheckIsRepeatable() const { }
- virtual R Run(A1, A2, A3) = 0;
- protected:
- ResultCallback3() {}
-};
-
-template <class A1, class A2, class A3, class A4>
-class Callback4 {
- public:
- virtual ~Callback4() { }
- virtual bool IsRepeatable() const { return false; }
- virtual void CheckIsRepeatable() const { }
- virtual void Run(A1, A2, A3, A4) = 0;
- protected:
- Callback4() {}
-};
-
-template <class R, class A1, class A2, class A3, class A4>
-class ResultCallback4 {
- public:
- virtual ~ResultCallback4() { }
- virtual bool IsRepeatable() const { return false; }
- virtual void CheckIsRepeatable() const { }
- virtual R Run(A1, A2, A3, A4) = 0;
- protected:
- ResultCallback4() {}
-};
-
-
-// Manages a callback so it can not be called recursively. The manager takes
-// ownership of the callback. Calling Set a second time, calling Clear or
-// destroying the manager deletes any callback that was previously set.
-template <typename T>
-class NonRecursiveCallback1Manager {
- public:
- typedef T ArgumentType;
- typedef Callback1<ArgumentType> CallbackType;
- NonRecursiveCallback1Manager()
- : callback_(NULL),
- called_(false) {
- }
- ~NonRecursiveCallback1Manager() {
- Clear();
- }
-
- // Check if the callback is currently set to call something
- // Returns:
- // true if the closuer is set.
- bool IsSet() const {
- return callback_ != NULL;
- }
-
- // Sets the callback. Note that the manager owns any callback set and will
- // delete that callback if Set or Clear is called or if the manager is
- // destroyed.
- // Paramaters:
- // callback: The callback to be called when Run is called.
- void Set(CallbackType* callback) {
- Clear();
- callback_ = callback;
- }
-
- // Clear the callback. Note that the manager owns any callback set and will
- // delete that callback if Set or Clear is called or if the manager is
- // destroyed.
- void Clear() {
- if (callback_) {
- delete callback_;
- callback_ = NULL;
- }
- }
-
- // Runs the callback if one is currently set and if it is not already inside a
- // previous call.
- // Parameter:
- // argument: the argument for the callback.
- void Run(ArgumentType argument) const {
- if (callback_ && !called_) {
- called_ = true;
- callback_->Run(argument);
- called_ = false;
- }
- }
-
- // Exchanges the callback with a new callback, returning the old
- // callback.
- // Parameters:
- // callback: The new callback.
- CallbackType* Exchange(CallbackType* callback) {
- CallbackType* old = callback_;
- callback_ = callback;
- return old;
- }
-
- // True if we're currently running the callback.
- bool called() const { return called_; }
-
- private:
- CallbackType* callback_;
- mutable bool called_;
- DISALLOW_COPY_AND_ASSIGN(NonRecursiveCallback1Manager);
-};
-
-// Manages a closure so it can not be called recursively. The manager takes
-// ownership of the closure. Calling Set a second time, calling Clear or
-// destroying the manager deletes any closure that was previously set.
-class NonRecursiveClosureManager {
- public:
- typedef Closure ClosureType;
-
- NonRecursiveClosureManager()
- : closure_(NULL),
- called_(false) {
- }
-
- ~NonRecursiveClosureManager() {
- Clear();
- }
-
- // Check if the closure is currently set to call something
- // Returns:
- // true if the closuer is set.
- bool IsSet() const {
- return closure_ != NULL;
- }
-
- // Sets the closure. Note that the manager owns any closure set and will
- // delete that closure if Set or Clear is called or if the manager is
- // destroyed.
- // Paramaters:
- // closure: The closure to be called when Run is called.
- void Set(ClosureType* closure) {
- Clear();
- closure_ = closure;
- }
-
- // Clear the closure. Note that the manager owns any closure set and will
- // delete that closure if Set or Clear is called or if the manager is
- // destroyed.
- void Clear() {
- if (closure_) {
- delete closure_;
- closure_ = NULL;
- }
- }
-
- // Runs the closure if one is currently set and if it is not already inside a
- // previous call.
- void Run() const {
- if (closure_ && !called_) {
- called_ = true;
- closure_->Run();
- called_ = false;
- }
- }
-
- private:
- ClosureType* closure_;
- mutable bool called_;
- DISALLOW_COPY_AND_ASSIGN(NonRecursiveClosureManager);
-};
-
-// Manages a closure so it can not be called recursively. The manager takes
-// ownership of the closure. Calling Set a second time, calling Clear or
-// destroying the manager deletes any closure that was previously set.
-class RefCountedNonRecursiveClosureManager : public RefCounted {
- public:
- typedef SmartPointer<RefCountedNonRecursiveClosureManager> Ref;
- typedef Closure ClosureType;
-
- RefCountedNonRecursiveClosureManager()
- : closure_(NULL),
- called_(false) {
- }
-
- ~RefCountedNonRecursiveClosureManager() {
- Clear();
- }
-
- // Check if the closure is currently set to call something
- // Returns:
- // true if the closuer is set.
- bool IsSet() const {
- return closure_ != NULL;
- }
-
- // Sets the closure. Note that the manager owns any closure set and will
- // delete that closure if Set or Clear is called or if the manager is
- // destroyed.
- // Paramaters:
- // closure: The closure to be called when Run is called.
- void Set(ClosureType* closure) {
- Clear();
- closure_ = closure;
- }
-
- // Clear the closure. Note that the manager owns any closure set and will
- // delete that closure if Set or Clear is called or if the manager is
- // destroyed.
- void Clear() {
- if (closure_) {
- delete closure_;
- closure_ = NULL;
- }
- }
-
- // Runs the closure if one is currently set and if it is not already inside a
- // previous call.
- void Run() const {
- if (closure_ && !called_) {
- called_ = true;
- closure_->Run();
- called_ = false;
- }
- }
-
- private:
- ClosureType* closure_;
- mutable bool called_;
- DISALLOW_COPY_AND_ASSIGN(RefCountedNonRecursiveClosureManager);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_CALLBACK_H_
diff --git a/o3d/core/cross/canvas.cc b/o3d/core/cross/canvas.cc
deleted file mode 100644
index c955a14..0000000
--- a/o3d/core/cross/canvas.cc
+++ /dev/null
@@ -1,277 +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 Canvas class.
-
-#include "core/cross/canvas.h"
-#include "core/cross/canvas_paint.h"
-#include "core/cross/canvas_utils.h"
-#include "core/cross/client.h"
-#include "core/cross/error.h"
-#include "core/cross/features.h"
-
-#include "SkPath.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Canvas, ParamObject);
-
-Canvas::Canvas(ServiceLocator* service_locator)
- : ParamObject(service_locator),
- width_(0),
- height_(0) {
- Features* features = service_locator->GetService<Features>();
- DCHECK(features);
- flip_ = features->flip_textures();
-
- // Initialize a 0x0 bitmap
- sk_bitmap_.setConfig(SkBitmap::kARGB_8888_Config, 0, 0);
- sk_canvas_.setBitmapDevice(sk_bitmap_);
-}
-
-Canvas::~Canvas() {
-}
-
-bool Canvas::SetSize(int width, int height) {
- width_ = width;
- height_ = height;
-
- sk_bitmap_.setConfig(SkBitmap::kARGB_8888_Config, width, height);
- if (!sk_bitmap_.allocPixels()) {
- DLOG(ERROR) << "Failed to allocate Skia bitmap";
- return false;
- }
- sk_canvas_.setBitmapDevice(sk_bitmap_);
-
- if (flip_) {
- // Translate and flip our canvas to change from o3d coordinates
- // (where the lower left is (0,0)) to skia coordinates (where the
- // upper left is (0,0))
- sk_canvas_.translate(0, SkIntToScalar(sk_bitmap_.height()));
- sk_canvas_.scale(SK_Scalar1, -SK_Scalar1);
- }
-
- return true;
-}
-
-void Canvas::Clear(float red, float green, float blue, float alpha) {
- sk_bitmap_.eraseColor(Float4ToSkColor(Float4(red, green, blue, alpha)));
-}
-
-void Canvas::DrawRect(float left,
- float top,
- float right,
- float bottom,
- CanvasPaint* paint) {
- sk_canvas_.drawRectCoords(SkFloatToScalar(left),
- SkFloatToScalar(top),
- SkFloatToScalar(right),
- SkFloatToScalar(bottom),
- paint->GetNativePaint());
-}
-
-void Canvas::DrawText(const String& text,
- float x,
- float y,
- CanvasPaint* paint) {
- sk_canvas_.drawText(text.c_str(),
- text.length(),
- SkFloatToScalar(x),
- SkFloatToScalar(y),
- paint->GetNativePaint());
-}
-
-void Canvas::DrawTextOnPath(const String& text,
- std::vector<Float2> positions,
- float horizontal_offset,
- float vertical_offset,
- CanvasPaint* paint) {
- unsigned int size = positions.size();
- if (size < 2) {
- O3D_ERROR(service_locator()) << "Must provide at least two positions"
- << " for drawTextOnPath!";
- return;
- }
-
- SkPath path;
-
- path.moveTo(SkFloatToScalar(positions[0].getX()),
- SkFloatToScalar(positions[0].getY()));
- for (unsigned int i = 1; i < size; i++) {
- path.lineTo(SkFloatToScalar(positions[i].getX()),
- SkFloatToScalar(positions[i].getY()));
- }
- SkPaint nativePaint = paint->GetNativePaint();
-
- sk_canvas_.drawTextOnPathHV(text.c_str(),
- text.length(),
- path,
- SkFloatToScalar(horizontal_offset),
- SkFloatToScalar(vertical_offset),
- nativePaint);
-}
-
-void Canvas::DrawBitmap(Texture2D* texture2d,
- float left,
- float bottom) {
- if (!texture2d)
- return;
-
- if (texture2d->format() != Texture2D::ARGB8 &&
- texture2d->format() != Texture2D::XRGB8) {
- O3D_ERROR(service_locator()) <<
- "Texture format must be ARGB8 or XRGB8 for drawBitmap";
- return;
- }
-
- Texture2D::LockHelper lock_helper(texture2d, 0, Texture::kReadOnly);
- uint8* texture_data = lock_helper.GetDataAs<uint8>();
- if (!texture_data) {
- return;
- }
-
- int height = texture2d->height();
- int width = texture2d->width();
-
- // Create a temporary bitmap to copy the texture data into.
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, width, height);
-
- // Allocate enough space to copy the pixels over to the bitmap.
- if (!bitmap.allocPixels()) {
- O3D_ERROR(service_locator()) << "Unable to allocate bitmap";
- return;
- }
-
- unsigned char* bitmap_data = static_cast<unsigned char*>(
- bitmap.getPixels());
-
- for (int yy = 0; yy < height; ++yy) {
- memcpy(bitmap_data + yy * width * 4,
- texture_data + yy * lock_helper.pitch(),
- width * 4);
- }
-
- if (texture2d->format() == Texture2D::XRGB8) {
- // Set the alpha to 1
- for (int ii = 0; ii < width * height; ii++) {
- bitmap_data[3] = 0xff;
- bitmap_data += 4;
- }
- } else {
- // Pre-multiply (i.e. multiply the color by alpha) the color since the
- // Skia bitmap expects it in that format.
- for (int ii = 0; ii < width * height; ii++) {
- unsigned char* b = (bitmap_data + 0);
- unsigned char* g = (bitmap_data + 1);
- unsigned char* r = (bitmap_data + 2);
- unsigned char a = bitmap_data[3];
-
- *r = SkMulDiv255Round(*r, a);
- *g = SkMulDiv255Round(*g, a);
- *b = SkMulDiv255Round(*b, a);
- bitmap_data += 4;
- }
- }
-
- // Now copy from the temporary bitmap to the canvas bitmap.
- SaveMatrix();
- if (flip_) {
- Scale(1, -1);
- bottom = -bottom;
- }
- sk_canvas_.drawBitmap(bitmap,
- SkFloatToScalar(left),
- SkFloatToScalar(bottom),
- NULL);
- RestoreMatrix();
-}
-
-void Canvas::Rotate(float degrees) {
- sk_canvas_.rotate(SkFloatToScalar(degrees));
-}
-
-void Canvas::Scale(float sx, float sy) {
- sk_canvas_.scale(SkFloatToScalar(sx), SkFloatToScalar(sy));
-}
-
-void Canvas::Translate(float dx, float dy) {
- sk_canvas_.translate(SkFloatToScalar(dx), SkFloatToScalar(dy));
-}
-
-// Copy the contents of the local bitmap to a Texture object.
-bool Canvas::CopyToTexture(Texture2D* texture_2d) const {
- DCHECK(texture_2d);
-
- if (texture_2d->width() != sk_bitmap_.width() ||
- texture_2d->height() != sk_bitmap_.height() ||
- (texture_2d->format() != Texture2D::ARGB8 &&
- texture_2d->format() != Texture2D::XRGB8)) {
- O3D_ERROR(service_locator())
- << "Texture format and size doesn't match Canvas";
- return false;
- }
-
- int width = sk_bitmap_.width();
- int height = sk_bitmap_.height();
- texture_2d->SetRect(0, 0, 0, width, height,
- sk_bitmap_.getPixels(), width * 4);
-
- // Fill in all the mipmap levels of the texture by drawing scaled down
- // versions of the canvas bitmap contents.
- SkBitmap bitmap;
- int levels = texture_2d->levels();
-
- for (int i = 1; (!levels && width > 1 && height > 1) || i < levels; i++) {
- width = std::max(1, width >> 1);
- height = std::max(1, height >> 1);
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, width, height);
-
- scoped_array<uint8> buffer(new uint8[width * height * 4]);
- bitmap.setPixels(buffer.get());
- SkCanvas canvas(bitmap);
- SkScalar scaleFactor = SkScalarDiv(SK_Scalar1, SkIntToScalar(1 << i));
- canvas.scale(scaleFactor, scaleFactor);
- canvas.drawBitmap(sk_bitmap_, 0, 0);
- texture_2d->SetRect(i, 0, 0, width, height, bitmap.getPixels(), width * 4);
- }
-
- return true;
-}
-
-ObjectBase::Ref Canvas::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new Canvas(service_locator));
-}
-
-
-
-} // namespace o3d
diff --git a/o3d/core/cross/canvas.h b/o3d/core/cross/canvas.h
deleted file mode 100644
index 44691fb..0000000
--- a/o3d/core/cross/canvas.h
+++ /dev/null
@@ -1,204 +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 declaration for the Canvas class.
-
-#ifndef O3D_CORE_CROSS_CANVAS_H_
-#define O3D_CORE_CROSS_CANVAS_H_
-
-#include <vector>
-
-#include "core/cross/param_object.h"
-#include "core/cross/param.h"
-#include "core/cross/texture.h"
-
-#include "SkBitmap.h"
-#include "SkCanvas.h"
-
-namespace o3d {
-
-class CanvasPaint;
-
-// The Canvas class provides an API for drawing text and 2D primitives onto
-// a 2D bitmap surface whose contents can be transfered to a compatible
-// Texture2D object via the CopyToTexture() method. Each Canvas object
-// maintains a stack of 2D transformation matrices which allow fine control over
-// the placement of drawable elements. Both geometry and drawing coordinates
-// provided to every draw call are transformed by the concatenation of
-// all matrices in the stack.
-class Canvas : public ParamObject {
- public:
- typedef SmartPointer<Canvas> Ref;
-
- virtual ~Canvas();
-
- // Sets the size of the bitmap surface this Canvas object will use.
- bool SetSize(int width, int height);
-
- // Initializes the bitmap's pixels with the specified color.
- // Parameters:
- // red: Red color value (between 0 and 1.0)
- // green: Green color value (between 0 and 1.0)
- // blue: Blue color value (between 0 and 1.0)
- // alpha: Transparency value (0 = transparent, 1 = opaque)
- void Clear(float red, float green, float blue, float alpha);
-
- // Draws a rectangle using the specified coordinates. The rectangle will be
- // filled based on the color and shader of the specified paint.
- // Parameters:
- // left The left side of the rectangle to be drawn
- // top The top side of the rectangle to be drawn
- // right The right side of the rectangle to be drawn
- // bottom The bottom side of the rectangle to be drawn
- // paint The CanvasPaint object used to draw the rectangle.
- void DrawRect(float left,
- float top,
- float right,
- float bottom,
- CanvasPaint* paint);
-
- // Draws the text, with origin at (x,y), using the specified paint. The origin
- // is interpreted based on the textAlign property in the paint.
- // Parameters:
- // text: String of text to be drawn
- // x: The x coordinate for the text origin
- // y: The y coordinate for the text origin
- // paint: The CanvasPaint object that specifies the text style, size, etc
- void DrawText(const String& text, float x, float y, CanvasPaint* paint);
-
- // Draws the text with its baseline along the
- // specified path. The paint's textAlign property determines where along the
- // path to start the text. The path must contain at least two positions.
- // Parameters:
- // text: String of text to be drawn
- // positions: An array of x,y positions making up the path.
- // horizonal_offset: The distance along the path to add to the text starting
- // position.
- // vertical_offset: The distance above(-) or below(+) the path to position
- // the text.
- // paint: The CanvasPaint object that specifies the text style, size, etc.
- void DrawTextOnPath(const String& text,
- std::vector<Float2> positions,
- float horizontal_offset,
- float vertical_offset,
- CanvasPaint* paint);
-
- // Draws the contents of the specified texture onto the canvas surface.
- // The bottom left corner of the bitmap will be at (x, y) and transformed by
- // the current matrix.
- // DEPRECATED
- // Parameters:
- // texture: Pointer to Texture2D object where the bitmap is extracted from
- // left: The position of the left side of the bitmap.
- // bottom: The position of the bottom side of the bitmap.
- void DrawBitmap(Texture2D* texture,
- float left,
- float bottom);
-
- // This call saves the current matrix information, and pushes a copy onto a
- // private stack. Subsequent calls to translate, scale, rotate, all operate on
- // this copy. When the balancing call to RestoreState() is made, this copy is
- // deleted and the previous matrix is restored.
- void SaveMatrix() { sk_canvas_.save(); }
-
- // This call balances a previous call to SaveMatrix(), and is used to remove
- // all modifications to the matrix since the last SaveMatrix call.
- void RestoreMatrix() { sk_canvas_.restore(); }
-
- // Preconcats the current canvas matrix with the specified rotation.
- // Parameters:
- // degrees: The amount to rotate, in degrees
- void Rotate(float degrees);
-
- // Preconcats the current canvas matrix with the specified scale.
- // Parameters:
- // sx: The amount to scale in x
- // sy: The amount to scale in y
- void Scale(float sx, float sy);
-
- // Preconcats the current canvas matrix with the specified translation.
- // Parameters:
- // dx: The amount to translate in x
- // dy: The amount to translate in y
- void Translate(float dx, float dy);
-
- // Copies the contents of the Canvas bitmap to a Texture2D object. The
- // texture object must have the same size as the canvas and a ARGB8 or XRGB8
- // format. All mip levels of the the texture will be filled.
- // DEPRECATED
- // Parameters:
- // texture_2d: The texture object to copy the bitmap to.
- bool CopyToTexture(Texture2D* texture_2d) const;
-
- // Returns the width of the canvas bitmap.
- int width() const { return width_; }
-
- // Returns the height of the canvas bitmap.
- int height() const { return height_; }
-
- // Returns the actual pixels of the canvas
- const uint8* GetPixelData(int x, int y) const {
- return static_cast<const uint8*>(sk_bitmap_.getPixels()) +
- y * GetPitch() + x * 4;
- }
-
- // Returns the pitch of the pixel data
- int GetPitch() const {
- return width_ * 4;
- }
-
- protected:
- explicit Canvas(ServiceLocator* service_locator);
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // Local area in memory to perform drawing operations.
- SkBitmap sk_bitmap_;
- SkCanvas sk_canvas_;
-
- // bitmap width and height.
- int width_;
- int height_;
-
- // For backward compatibility. Whether to flip the bitmap.
- bool flip_;
-
- O3D_DECL_CLASS(Canvas, ParamObject)
- DISALLOW_COPY_AND_ASSIGN(Canvas);
-};
-
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_CANVAS_H_
diff --git a/o3d/core/cross/canvas_paint.cc b/o3d/core/cross/canvas_paint.cc
deleted file mode 100644
index d4545b7..0000000
--- a/o3d/core/cross/canvas_paint.cc
+++ /dev/null
@@ -1,272 +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 for the CanvasPaint class.
-
-#include "core/cross/canvas_paint.h"
-#include "core/cross/canvas_utils.h"
-#include "core/cross/client.h"
-
-#include "SkCanvas.h"
-#include "SkColor.h"
-#include "SkDrawLooper.h"
-#include "SkPaint.h"
-#include "SkTypeface.h"
-#include "SkBlurDrawLooper.h"
-
-namespace o3d {
-
-namespace {
-
-/** StrokeDrawLooper This class draws an outline of the
-* object, and then draws the original object in its original
-* position.
-*/
-class StrokeDrawLooper : public SkDrawLooper {
- public:
- StrokeDrawLooper(SkScalar radius, SkColor color);
- virtual ~StrokeDrawLooper() {}
- virtual void init(SkCanvas* canvas, SkPaint* paint);
- virtual bool next();
- virtual void restore();
-
- protected:
- virtual Factory getFactory() { return CreateProc; }
- void flatten(SkFlattenableWriteBuffer& buffer);
- StrokeDrawLooper(SkFlattenableReadBuffer& buffer);
-
- private:
- SkCanvas* fCanvas;
- SkPaint* fPaint;
-
- // These are to save the state attributes that we want to change so
- // we can restore them after we draw the stroke.
- SkPaint::Style fSavedStyle;
- SkScalar fSavedStrokeWidth;
- SkColor fSavedColor;
-
- // These are the attribues of the stroke.
- SkScalar fRadius;
- SkColor fColor;
-
- // Possible machine states for this object.
- enum State {
- kBeforeEdge,
- kAfterEdge,
- kDone,
- };
- State fState;
-
- // Factory method for ressurecting a StrokeDrawLooper.
- static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) {
- return SkNEW_ARGS(StrokeDrawLooper, (buffer)); }
-
- typedef SkDrawLooper INHERITED;
-};
-
-StrokeDrawLooper::StrokeDrawLooper(SkScalar radius, SkColor color)
- : fRadius(radius), fColor(color) {
-}
-
-void StrokeDrawLooper::init(SkCanvas* canvas, SkPaint* paint) {
- fState = kBeforeEdge;
- fCanvas = canvas;
- fPaint = paint;
-}
-
-bool StrokeDrawLooper::next() {
- switch (fState) {
- case kBeforeEdge:
- // Save the original values.
- fSavedStyle = fPaint->getStyle();
- fSavedStrokeWidth = fPaint->getStrokeWidth();
- fSavedColor = fPaint->getColor();
-
- // Override with stroke values.
- fPaint->setColor(fColor);
- fPaint->setStrokeWidth(fRadius);
- fPaint->setStyle(SkPaint::kStroke_Style);
-
- // Change states.
- fState = kAfterEdge;
- return true;
- case kAfterEdge:
- // Restore original values.
- fPaint->setColor(fSavedColor);
- fPaint->setStrokeWidth(fSavedStrokeWidth);
- fPaint->setStyle(fSavedStyle);
-
- // Now we're done.
- fState = kDone;
- return true;
- default:
- SkASSERT(kDone == fState);
- return false;
- }
-}
-
-void StrokeDrawLooper::restore() {
- if (kAfterEdge == fState) {
- fPaint->setColor(fSavedColor);
- fPaint->setStrokeWidth(fSavedStrokeWidth);
- fPaint->setStyle(fSavedStyle);
- fState = kDone;
- }
-}
-
-void StrokeDrawLooper::flatten(SkFlattenableWriteBuffer& buffer) {
- buffer.writeScalar(fRadius);
- buffer.write32(fColor);
-}
-
-StrokeDrawLooper::StrokeDrawLooper(SkFlattenableReadBuffer& buffer) {
- fRadius = buffer.readScalar();
- fColor = buffer.readU32();
-}
-
-} // end anonymous namespace
-
-O3D_DEFN_CLASS(CanvasPaint, ParamObject);
-
-static SkPaint::Align ToSKAlign(CanvasPaint::TextAlign align) {
- switch (align) {
- case CanvasPaint::LEFT:
- return SkPaint::kLeft_Align;
- case CanvasPaint::CENTER:
- return SkPaint::kCenter_Align;
- case CanvasPaint::RIGHT:
- return SkPaint::kRight_Align;
- default:
- return SkPaint::kLeft_Align;
- }
-}
-
-CanvasPaint::CanvasPaint(ServiceLocator* service_locator)
- : ParamObject(service_locator),
- shader_(NULL),
- needs_update_(true),
- text_align_(LEFT),
- color_(Float4(0, 0, 0, 1)),
- text_size_(10),
- text_typeface_(""),
- text_style_(NORMAL),
- outline_radius_(0),
- outline_color_(Float4(0, 0, 0, 1)),
- shadow_radius_(0),
- shadow_offset_x_(0),
- shadow_offset_y_(0),
- shadow_color_(Float4(0, 0, 0, 1)) {
- sk_paint_.setAntiAlias(true);
-}
-
-CanvasPaint::~CanvasPaint() {
-}
-
-// Updates the native paint object with the current values of all the settings.
-void CanvasPaint::UpdateNativePaint() {
- if (needs_update_) {
- sk_paint_.setColor(Float4ToSkColor(color_));
-
- // Note that shadow and ouline cannot both be active at the same time.
- if (outline_radius_ != 0.0) {
- SkDrawLooper* l = new StrokeDrawLooper(SkFloatToScalar(outline_radius_),
- Float4ToSkColor(outline_color_));
- sk_paint_.setLooper(l);
- l->unref();
- } else if (shadow_radius_ != 0.0) {
- SkBlurDrawLooper* l = new SkBlurDrawLooper(
- SkFloatToScalar(shadow_radius_),
- SkFloatToScalar(shadow_offset_x_),
- SkFloatToScalar(shadow_offset_y_),
- Float4ToSkColor(shadow_color_));
- sk_paint_.setLooper(l);
- l->unref();
- } else {
- sk_paint_.setLooper(NULL);
- }
-
- sk_paint_.setTextSize(SkFloatToScalar(text_size_));
-
- // TODO: Verify that there's visual parity between fonts on all
- // platforms. If not, come up with a list of typefaces and their
- // correspondances across platforms. The long term solution will be to
- // allow inclusion of Free Type fonts (Skia allows that) in the file format
- // so that we're guaranteed that text looks identical on all platforms.
- SkTypeface* tf = SkTypeface::CreateFromName(
- text_typeface_.c_str(),
- static_cast<SkTypeface::Style>(text_style_));
- if (tf) {
- sk_paint_.setTypeface(tf);
- tf->unref();
- }
-
- if (shader_) {
- sk_paint_.setShader(shader_->GetNativeShader());
- } else {
- sk_paint_.setShader(NULL);
- }
-
- sk_paint_.setTextAlign(ToSKAlign(text_align_));
-
- needs_update_ = false;
- }
-}
-
-CanvasFontMetrics CanvasPaint::GetFontMetrics() {
- CanvasFontMetrics ret;
-
- SkPaint::FontMetrics metrics;
- GetNativePaint().getFontMetrics(&metrics);
-
- ret.set_ascent(metrics.fAscent);
- ret.set_bottom(metrics.fBottom);
- ret.set_descent(metrics.fDescent);
- ret.set_leading(metrics.fLeading);
- ret.set_top(metrics.fTop);
-
- return ret;
-}
-
-Float4 CanvasPaint::MeasureText(const String& text) {
- SkRect bounds;
- GetNativePaint().measureText(text.c_str(), text.size(), &bounds);
-
- return Float4(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom);
-}
-
-ObjectBase::Ref CanvasPaint::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new CanvasPaint(service_locator));
-}
-
-
-
-} // namespace o3d
diff --git a/o3d/core/cross/canvas_paint.h b/o3d/core/cross/canvas_paint.h
deleted file mode 100644
index 8475f93..0000000
--- a/o3d/core/cross/canvas_paint.h
+++ /dev/null
@@ -1,268 +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 declaration for the Paint class.
-
-#ifndef O3D_CORE_CROSS_CANVAS_PAINT_H_
-#define O3D_CORE_CROSS_CANVAS_PAINT_H_
-
-#include "core/cross/param_object.h"
-#include "core/cross/param.h"
-#include "core/cross/canvas_shader.h"
-
-#include "SkPaint.h"
-
-namespace o3d {
-
-class Float4;
-
-// Class containing the metrics describing properties of a font used by the
-// paint object.
-class CanvasFontMetrics {
- public:
- float top() const { return top_; }
- void set_top(float top) { top_ = top; }
- float ascent() const { return ascent_; }
- void set_ascent(float ascent) { ascent_ = ascent; }
- float descent() const { return descent_; }
- void set_descent(float descent) { descent_ = descent; }
- float bottom() const { return bottom_; }
- void set_bottom(float bottom) { bottom_ = bottom; }
- float leading() const { return leading_; }
- void set_leading(float leading) { leading_ = leading; }
-
- private:
- // The greatest distance above the baseline for any glyph (will be <= 0)
- float top_;
- // The recommended distance above the baseline (will be <= 0)
- float ascent_;
- // The recommended distance below the baseline (will be >= 0)
- float descent_;
- // The greatest distance below the baseline for any glyph (will be >= 0)
- float bottom_;
- // The recommended distance to add between lines of text (will be >= 0)
- float leading_;
-};
-
-
-// The Paint class is used for specifying how to draw to
-// a canvas
-class CanvasPaint : public ParamObject {
- public:
- enum Style {
- NORMAL,
- BOLD,
- ITALIC,
- BOLD_ITALIC
- };
-
- enum TextAlign {
- LEFT,
- CENTER,
- RIGHT
- };
-
- typedef SmartPointer<CanvasPaint> Ref;
-
- virtual ~CanvasPaint();
-
- // Returns the color used for the drawing operations using this paint.
- Float4 color() { return color_; }
-
- // Sets the color.
- void set_color(const Float4& color) {
- color_ = color;
- needs_update_ = true;
- }
-
- // Sets the color and radius of an outline around the text. Setting the
- // radius to 0 cancels the outline effect.
- // Parameters:
- // radius: The radius of the outline effect in pixels.
- // color: The color used for outlining (in RGBA)
- void SetOutline(float radius, const Float4& color) {
- outline_radius_ = radius;
- outline_color_ = color;
- if (outline_radius_ != 0)
- shadow_radius_ = 0;
- needs_update_ = true;
- }
-
- // Sets a shadow effect around text. Setting the radius to 0 cancels the
- // shadow effect.
- // Parameters:
- // radius: The radius of shadow effect in pixels
- // offset_x: The offset of the shadow in the x coordinate.
- // offset_y: The offset of the shadow in the y coordinate.
- // color: The color used for the shadow (in RGBA)
- void SetShadow(float radius,
- float offset_x,
- float offset_y,
- const Float4& color) {
- shadow_radius_ = radius;
- shadow_offset_x_ = offset_x;
- shadow_offset_y_ = offset_y;
- shadow_color_ = color;
- if (shadow_radius_ != 0) {
- outline_radius_ = 0;
- }
- needs_update_ = true;
- }
-
- // Returns the font metrics for the current font being used by the paint.
- CanvasFontMetrics GetFontMetrics();
-
- // Returns the bounds of the given text string when rendered with this paint.
- // The bounds are returned as a Float4 containing [left, top, right, bottom]
- // values relative to (0, 0).
- Float4 MeasureText(const String& text);
-
- // Sets the size of the font used for text drawing.
- // Parameters:
- // text_size: The size of the text
- void set_text_size(float text_size) {
- text_size_ = text_size;
- needs_update_ = true;
- }
-
- // Returns the current font size used for drawing text.
- float text_size() { return text_size_; }
-
- // Sets the typeface of the font used for rendering text.
- // Parameters:
- // font: typeface to use.
- void set_text_typeface(const String& typeface) {
- text_typeface_ = typeface;
- needs_update_ = true;
- }
-
- // Returns the typeface used for text drawing.
- String text_typeface() {
- return text_typeface_;
- }
-
- // Sets the style parameter for the text (e.g. italic, bold, etc)
- void set_text_style(Style style) {
- text_style_ = style;
- needs_update_ = true;
- }
-
- // Returns the style used for drawing text.
- Style text_style() {
- return text_style_;
- }
-
- // Sets the pointer to the CanvasShader object used by this paint. The
- // CanvasShader specifies in detail how paint gets applied (e.g. with a
- // linear gradient, etc)
- void set_shader(CanvasShader* shader) {
- shader_ = CanvasShader::Ref(shader);
- needs_update_ = true;
- }
-
- // Returns the current shader used by the paint.
- CanvasShader* shader() {
- return shader_.Get();
- }
-
- // Sets the alignment mode for renderered text. This is the setting that's
- // used by the canvas text drawing methods.
- void set_text_align(TextAlign text_align) {
- text_align_ = text_align;
- needs_update_ = true;
- }
-
- // Returns the text alingment setting.
- TextAlign text_align() { return text_align_; }
-
- protected:
- explicit CanvasPaint(ServiceLocator* service_locator);
-
- private:
- friend class Canvas;
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // Updates the internal skia paint object using the current parameter values.
- void UpdateNativePaint();
-
- const SkPaint& GetNativePaint() {
- UpdateNativePaint();
- return sk_paint_;
- }
-
- // CanvasShader object used by this paint.
- CanvasShader::Ref shader_;
-
- // Skia paint object.
- SkPaint sk_paint_;
-
- // This flag is set to true when one of the paint parameters is changed. When
- // the GetNativePaint() method is called, if this flag is set it will force
- // a rebuild of the native SkPaint object.
- bool needs_update_;
-
- // Alignment mode used for drawing text.
- TextAlign text_align_;
-
- // Color used for text and drawing operations (RGBA)
- Float4 color_;
-
- // Size of font used for drawing text.
- float text_size_;
-
- // Typeface of font used for text drawing.
- String text_typeface_;
-
- // Style of text used for rendering (e.g. bold, italic, etc)
- Style text_style_;
-
- // Radius (in pixels) of outline around text
- float outline_radius_;
-
- // Color used for outlining text.
- Float4 outline_color_;
-
- // Parameters for shadow effect around text.
- float shadow_radius_;
- float shadow_offset_x_;
- float shadow_offset_y_;
- Float4 shadow_color_;
-
- O3D_DECL_CLASS(CanvasPaint, ParamObject)
- DISALLOW_COPY_AND_ASSIGN(CanvasPaint);
-};
-
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_CANVAS_PAINT_H_
diff --git a/o3d/core/cross/canvas_shader.cc b/o3d/core/cross/canvas_shader.cc
deleted file mode 100644
index 7f55fcb..0000000
--- a/o3d/core/cross/canvas_shader.cc
+++ /dev/null
@@ -1,145 +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 for the CanvasShader class.
-
-#include "core/cross/canvas_shader.h"
-#include "base/scoped_ptr.h"
-#include "core/cross/canvas_utils.h"
-#include "core/cross/error.h"
-
-#include "SkShader.h"
-#include "SkGradientShader.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(CanvasShader, ParamObject);
-O3D_DEFN_CLASS(CanvasLinearGradient, CanvasShader);
-
-static SkShader::TileMode ToSKTileMode(CanvasShader::TileMode mode) {
- switch (mode) {
- case CanvasShader::CLAMP:
- return SkShader::kClamp_TileMode;
- case CanvasShader::MIRROR:
- return SkShader::kMirror_TileMode;
- case CanvasShader::REPEAT:
- return SkShader::kRepeat_TileMode;
- default:
- return SkShader::kRepeat_TileMode;
- }
-}
-
-CanvasShader::CanvasShader(ServiceLocator* service_locator)
- : ParamObject(service_locator),
- native_shader_(NULL) {
-}
-
-CanvasShader::~CanvasShader() {
- if (native_shader_)
- native_shader_->unref();
-}
-
-SkShader* CanvasShader::GetNativeShader() {
- if (needs_update_) {
- needs_update_ = false;
- if (native_shader_)
- native_shader_->unref();
- native_shader_ = MakeNativeShader();
- }
- return native_shader_;
-}
-
-CanvasLinearGradient::CanvasLinearGradient(ServiceLocator* service_locator)
- : CanvasShader(service_locator),
- start_point_(Float2(0, 0)),
- end_point_(Float2(0, 0)),
- tile_mode_(REPEAT) {
- colors_.push_back(Float4(0, 0, 0, 1));
- colors_.push_back(Float4(0, 0, 0, 1));
- positions_.clear();
-}
-
-CanvasLinearGradient::~CanvasLinearGradient() {
-}
-
-SkShader* CanvasLinearGradient::MakeNativeShader() {
- SkPoint start_to_end[2];
- start_to_end[0].set(SkFloatToScalar(start_point_.getX()),
- SkFloatToScalar(start_point_.getY()));
- start_to_end[1].set(SkFloatToScalar(end_point_.getX()),
- SkFloatToScalar(end_point_.getY()));
-
- if (colors_.size() < 2) {
- O3D_ERROR(service_locator()) << "Must provide at least two colors for"
- << " CanvasLinearGradient!";
- return NULL;
- }
- scoped_array<SkColor> colors(new SkColor[colors_.size()]);
- for (std::vector<Float4>::size_type ii = 0; ii < colors_.size(); ii++) {
- (colors.get())[ii] = Float4ToSkColor(colors_[ii]);
- }
- scoped_ptr<SkScalar> positions;
- if (positions_.size()) {
- if (positions_.size() != colors_.size()) {
- O3D_ERROR(service_locator()) << "The number of positions must match "
- << "the number of colors for"
- << " CanvasLinearGradient.";
- return NULL;
- }
- positions.reset(new SkScalar[positions_.size()]);
- for (std::vector<float>::size_type ii = 0; ii < positions_.size(); ii++) {
- (positions.get())[ii] = SkFloatToScalar(positions_[ii]);
- }
- } else {
- positions.reset(NULL);
- }
-
- SkShader* shader = SkGradientShader::CreateLinear(
- start_to_end,
- colors.get(),
- positions.get(),
- colors_.size(),
- ToSKTileMode(tile_mode_));
-
- if (shader == NULL) {
- DLOG(ERROR) << "Failed to create SkGradientShader (linear)";
- }
-
- return shader;
-}
-
-
-ObjectBase::Ref CanvasLinearGradient::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new CanvasLinearGradient(service_locator));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/canvas_shader.h b/o3d/core/cross/canvas_shader.h
deleted file mode 100644
index fbc689e..0000000
--- a/o3d/core/cross/canvas_shader.h
+++ /dev/null
@@ -1,166 +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 declaration for the CanvasShader class.
-
-#ifndef O3D_CORE_CROSS_CANVAS_SHADER_H_
-#define O3D_CORE_CROSS_CANVAS_SHADER_H_
-
-#include <vector>
-
-#include "core/cross/param_object.h"
-#include "core/cross/param.h"
-
-#include "SkColor.h"
-#include "SkPoint.h"
-
-class SkShader;
-
-namespace o3d {
-
-// This is the base class for 2D gradient shaders that can be applied to a
-// CanvasPaint. The shaders affect both text and primitive drawing in the
-// canvas.
-class CanvasShader : public ParamObject {
- public:
- enum TileMode {
- CLAMP, /* copy the edge color if the shader draws outside of its bounds */
- REPEAT, /* repeat horizontally and vertically outside its bounds */
- MIRROR /* same, alternating mirror images */
- };
- typedef SmartPointer<CanvasShader> Ref;
-
- explicit CanvasShader(ServiceLocator* service_locator);
- virtual ~CanvasShader();
-
- // Returns a pointer to the native (SKIA) shader object.
- SkShader* GetNativeShader();
-
- protected:
- // Creates a new native (SKIA) shader object using the parameter values
- // stored in the object.
- virtual SkShader* MakeNativeShader() = 0;
- SkShader* native_shader_;
- bool needs_update_;
-
- private:
- O3D_DECL_CLASS(CanvasShader, ParamObject)
- DISALLOW_COPY_AND_ASSIGN(CanvasShader);
-};
-
-// A shader that generates a linear gradient between two specified points.
-// Two or more colors need to be specified for the gradient.
-class CanvasLinearGradient : public CanvasShader {
- public:
- typedef SmartPointer<CanvasLinearGradient> Ref;
- virtual ~CanvasLinearGradient();
-
- // Sets the start point of the gradient.
- void set_start_point(Float2 start_point) {
- start_point_ = start_point;
- }
-
- // Returns the start point of the gradient.
- Float2 start_point() {
- return start_point_;
- }
-
- // Sets the end point of the gradient.
- void set_end_point(Float2 end_point) {
- end_point_ = end_point;
- }
-
- // Returns the end point of the gradient.
- Float2 end_point() {
- return end_point_;
- }
-
- // Sets the relative positions corresponding to the colors in the color array.
- // If the positions list is empty then the colors will be spread evenly.
- // Otherwise, position values should start with 0 and end with 1.0 and their
- // count should be equal to the length of the colors_ array.
- void set_positions(std::vector<float> positions) {
- positions_ = positions;
- needs_update_ = true;
- }
-
- std::vector<float> positions() {
- return positions_;
- }
-
- // Sets the array of colors used by the gradient.
- void set_colors(std::vector<Float4> colors) {
- colors_ = colors;
- needs_update_ = true;
- }
-
- // Returns the color array.
- std::vector<Float4> colors() {
- return colors_;
- }
-
- // Sets the tiling mode for the gradient which specifies how the shader
- // repeats for values beyond the start and end points.
- void set_tile_mode(CanvasShader::TileMode tile_mode) {
- tile_mode_ = tile_mode;
- needs_update_ = true;
- }
-
- // Returns the tile mode.
- TileMode tile_mode() { return tile_mode_; }
-
- protected:
- explicit CanvasLinearGradient(ServiceLocator* service_locator);
- virtual SkShader* MakeNativeShader();
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // Start and end points for the gradient.
- Float2 start_point_;
- Float2 end_point_;
-
- // Array of colors.
- std::vector<Float4> colors_;
-
- // Array of positions corresponding to colors.
- std::vector<float> positions_;
-
- CanvasShader::TileMode tile_mode_;
-
- O3D_DECL_CLASS(CanvasLinearGradient, CanvasShader)
- DISALLOW_COPY_AND_ASSIGN(CanvasLinearGradient);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_CANVAS_SHADER_H_
diff --git a/o3d/core/cross/canvas_utils.h b/o3d/core/cross/canvas_utils.h
deleted file mode 100644
index c43d1ea..0000000
--- a/o3d/core/cross/canvas_utils.h
+++ /dev/null
@@ -1,51 +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_CORE_CROSS_CANVAS_UTILS_H_
-#define O3D_CORE_CROSS_CANVAS_UTILS_H_
-
-#include "core/cross/float_n.h"
-#include "SkColor.h"
-
-// Helper function to convert from Float4 to an SkColor
-static SkColor Float4ToSkColor(const o3d::Float4& color) {
- unsigned char red = static_cast<unsigned char>(color[0] * 255.0f);
- unsigned char green = static_cast<unsigned char>(color[1] * 255.0f);
- unsigned char blue = static_cast<unsigned char>(color[2] * 255.0f);
- unsigned char alpha = static_cast<unsigned char>(color[3] * 255.0f);
- return SkColorSetARGB(static_cast<U8CPU>(alpha),
- static_cast<U8CPU>(red),
- static_cast<U8CPU>(green),
- static_cast<U8CPU>(blue));
-}
-
-#endif // O3D_CORE_CROSS_CANVAS_UTILS_H_
diff --git a/o3d/core/cross/class_manager.cc b/o3d/core/cross/class_manager.cc
deleted file mode 100644
index ace172e..0000000
--- a/o3d/core/cross/class_manager.cc
+++ /dev/null
@@ -1,276 +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 implements class ClassManager.
-
-#include "core/cross/bitmap.h"
-#include "core/cross/bounding_box.h"
-#include "core/cross/buffer.h"
-#include "core/cross/canvas.h"
-#include "core/cross/canvas_paint.h"
-#include "core/cross/canvas_shader.h"
-#include "core/cross/class_manager.h"
-#include "core/cross/clear_buffer.h"
-#include "core/cross/counter.h"
-#include "core/cross/curve.h"
-#include "core/cross/draw_context.h"
-#include "core/cross/draw_pass.h"
-#include "core/cross/effect.h"
-#include "core/cross/function.h"
-#include "core/cross/material.h"
-#include "core/cross/matrix4_axis_rotation.h"
-#include "core/cross/matrix4_composition.h"
-#include "core/cross/matrix4_scale.h"
-#include "core/cross/matrix4_translation.h"
-#include "core/cross/param_array.h"
-#include "core/cross/param_operation.h"
-#include "core/cross/primitive.h"
-#include "core/cross/processed_path.h"
-#include "core/cross/render_surface_set.h"
-#include "core/cross/sampler.h"
-#include "core/cross/shape.h"
-#include "core/cross/skin.h"
-#include "core/cross/standard_param.h"
-#include "core/cross/state_set.h"
-#include "core/cross/stream.h"
-#include "core/cross/stream_bank.h"
-#include "core/cross/transform.h"
-#include "core/cross/tree_traversal.h"
-#include "core/cross/viewport.h"
-#include "core/cross/cairo/layer.h"
-
-namespace o3d {
-
-ClassManager::ClassManager(ServiceLocator* service_locator)
- : service_locator_(service_locator),
- service_(service_locator_, this) {
- // Params
- AddTypedClass<ParamBoolean>();
- AddTypedClass<ParamBoundingBox>();
- AddTypedClass<ParamDrawContext>();
- AddTypedClass<ParamDrawList>();
- AddTypedClass<ParamEffect>();
- AddTypedClass<ParamFloat>();
- AddTypedClass<ParamFloat2>();
- AddTypedClass<ParamFloat3>();
- AddTypedClass<ParamFloat4>();
- AddTypedClass<ParamFunction>();
- AddTypedClass<ParamInteger>();
- AddTypedClass<ParamMaterial>();
- AddTypedClass<ParamMatrix4>();
- AddTypedClass<ParamParamArray>();
- AddTypedClass<ParamRenderSurface>();
- AddTypedClass<ParamRenderDepthStencilSurface>();
- AddTypedClass<ParamSampler>();
- AddTypedClass<ParamSkin>();
- AddTypedClass<ParamState>();
- AddTypedClass<ParamStreamBank>();
- AddTypedClass<ParamString>();
- AddTypedClass<ParamTexture>();
- AddTypedClass<ParamTransform>();
-
- // Param operations.
- AddTypedClass<Matrix4AxisRotation>();
- AddTypedClass<Matrix4Composition>();
- AddTypedClass<Matrix4Scale>();
- AddTypedClass<Matrix4Translation>();
- AddTypedClass<ParamOp2FloatsToFloat2>();
- AddTypedClass<ParamOp3FloatsToFloat3>();
- AddTypedClass<ParamOp4FloatsToFloat4>();
- AddTypedClass<ParamOp16FloatsToMatrix4>();
- AddTypedClass<TRSToMatrix4>();
-
- // SAS Params
- AddTypedClass<WorldParamMatrix4>();
- AddTypedClass<WorldInverseParamMatrix4>();
- AddTypedClass<WorldTransposeParamMatrix4>();
- AddTypedClass<WorldInverseTransposeParamMatrix4>();
-
- AddTypedClass<ViewParamMatrix4>();
- AddTypedClass<ViewInverseParamMatrix4>();
- AddTypedClass<ViewTransposeParamMatrix4>();
- AddTypedClass<ViewInverseTransposeParamMatrix4>();
-
- AddTypedClass<ProjectionParamMatrix4>();
- AddTypedClass<ProjectionInverseParamMatrix4>();
- AddTypedClass<ProjectionTransposeParamMatrix4>();
- AddTypedClass<ProjectionInverseTransposeParamMatrix4>();
-
- AddTypedClass<WorldViewParamMatrix4>();
- AddTypedClass<WorldViewInverseParamMatrix4>();
- AddTypedClass<WorldViewTransposeParamMatrix4>();
- AddTypedClass<WorldViewInverseTransposeParamMatrix4>();
-
- AddTypedClass<ViewProjectionParamMatrix4>();
- AddTypedClass<ViewProjectionInverseParamMatrix4>();
- AddTypedClass<ViewProjectionTransposeParamMatrix4>();
- AddTypedClass<ViewProjectionInverseTransposeParamMatrix4>();
-
- AddTypedClass<WorldViewProjectionParamMatrix4>();
- AddTypedClass<WorldViewProjectionInverseParamMatrix4>();
- AddTypedClass<WorldViewProjectionTransposeParamMatrix4>();
- AddTypedClass<WorldViewProjectionInverseTransposeParamMatrix4>();
-
- // Other Objects.
- AddTypedClass<Bitmap>();
- AddTypedClass<Canvas>();
- AddTypedClass<CanvasLinearGradient>();
- AddTypedClass<CanvasPaint>();
- AddTypedClass<ClearBuffer>();
- AddTypedClass<Counter>();
- AddTypedClass<Curve>();
- AddTypedClass<DrawContext>();
- AddTypedClass<DrawElement>();
- AddTypedClass<DrawList>();
- AddTypedClass<DrawPass>();
- AddTypedClass<Effect>();
- AddTypedClass<FunctionEval>();
- AddTypedClass<IndexBuffer>();
- AddTypedClass<Material>();
- AddTypedClass<ParamArray>();
- AddTypedClass<ParamObject>();
- AddTypedClass<Primitive>();
- AddTypedClass<ProcessedPath>();
- AddTypedClass<RenderFrameCounter>();
- AddTypedClass<RenderNode>();
- AddTypedClass<RenderSurfaceSet>();
- AddTypedClass<Sampler>();
- AddTypedClass<SecondCounter>();
- AddTypedClass<Shape>();
- AddTypedClass<Skin>();
- AddTypedClass<SkinEval>();
- AddTypedClass<SourceBuffer>();
- AddTypedClass<State>();
- AddTypedClass<StateSet>();
- AddTypedClass<StreamBank>();
- AddTypedClass<Texture2D>();
- AddTypedClass<TextureCUBE>();
- AddTypedClass<TickCounter>();
- AddTypedClass<Transform>();
- AddTypedClass<TreeTraversal>();
- AddTypedClass<VertexBuffer>();
- AddTypedClass<Viewport>();
-
- // Specific Objects for Cairo
- AddTypedClass<o2d::Layer>();
-}
-
-void ClassManager::AddClass(const ObjectBase::Class* object_class,
- ObjectCreateFunc function) {
- DLOG_ASSERT(object_class_info_name_map_.find(object_class->name()) ==
- object_class_info_name_map_.end())
- << "attempt to register duplicate class name";
- object_class_info_name_map_.insert(
- std::make_pair(object_class->name(),
- ObjectClassInfo(object_class, function)));
- DLOG_ASSERT(object_creator_class_map_.find(object_class) ==
- object_creator_class_map_.end())
- << "attempt to register duplicate class";
- object_creator_class_map_.insert(std::make_pair(object_class,
- function));
-}
-
-void ClassManager::RemoveClass(const ObjectBase::Class* object_class) {
- ObjectClassInfoNameMap::size_type ii = object_class_info_name_map_.erase(
- object_class->name());
- DLOG_ASSERT(ii == 1) << "attempt to unregister non-existant class name";
- ObjectCreatorClassMap::size_type jj = object_creator_class_map_.erase(
- object_class);
- DLOG_ASSERT(jj == 1) << "attempt to unregister non-existant class";
-}
-
-const ObjectBase::Class* ClassManager::GetClassByClassName(
- const String& class_name) const {
- ObjectClassInfoNameMap::const_iterator iter =
- object_class_info_name_map_.find(class_name);
-
- if (iter == object_class_info_name_map_.end()) {
- // Try adding the o3d namespace prefix
- String prefixed_class_name(O3D_STRING_CONSTANT("") + class_name);
- iter = object_class_info_name_map_.find(prefixed_class_name);
- }
-
- return (iter != object_class_info_name_map_.end()) ?
- iter->second.class_type() : NULL;
-}
-
-bool ClassManager::ClassNameIsAClass(
- const String& derived_class_name,
- const ObjectBase::Class* base_class) const {
- const ObjectBase::Class* derived_class = GetClassByClassName(
- derived_class_name);
- return derived_class && ObjectBase::ClassIsA(derived_class, base_class);
-}
-
-// Factory method to create a new object by class name.
-
-ObjectBase::Ref ClassManager::CreateObject(const String& type_name) {
- ObjectClassInfoNameMap::const_iterator iter =
- object_class_info_name_map_.find(type_name);
- if (iter == object_class_info_name_map_.end()) {
- // Try adding the o3d namespace prefix
- String prefixed_type_name(O3D_STRING_CONSTANT("") + type_name);
- iter = object_class_info_name_map_.find(prefixed_type_name);
- }
-
- if (iter != object_class_info_name_map_.end()) {
- return ObjectBase::Ref(iter->second.creation_func()(service_locator_));
- }
-
- return ObjectBase::Ref();
-}
-
-// Factory method to create a new object by class.
-
-ObjectBase::Ref ClassManager::CreateObjectByClass(
- const ObjectBase::Class* object_class) {
- ObjectCreatorClassMap::const_iterator iter =
- object_creator_class_map_.find(object_class);
-
- if (iter != object_creator_class_map_.end()) {
- return ObjectBase::Ref(iter->second(service_locator_));
- }
-
- return ObjectBase::Ref();
-}
-
-std::vector<const ObjectBase::Class*> ClassManager::GetAllClasses() const {
- std::vector<const ObjectBase::Class*> classes;
- for (ObjectClassInfoNameMap::const_iterator it =
- object_class_info_name_map_.begin();
- it != object_class_info_name_map_.end(); ++it) {
- classes.push_back(it->second.class_type());
- }
- return classes;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/class_manager.h b/o3d/core/cross/class_manager.h
deleted file mode 100644
index 0a3f922..0000000
--- a/o3d/core/cross/class_manager.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_CORE_CROSS_CLASS_MANAGER_H_
-#define O3D_CORE_CROSS_CLASS_MANAGER_H_
-
-#include <map>
-#include <vector>
-
-#include "core/cross/service_implementation.h"
-#include "core/cross/iclass_manager.h"
-
-namespace o3d {
-
-// Maintains a collection of Class objects. Allows Classes to be retreived
-// by name and objects of those Classes to be created.
-class ClassManager : public IClassManager {
- public:
- explicit ClassManager(ServiceLocator* service_locator);
-
- virtual void AddClass(const ObjectBase::Class* class_type,
- ObjectCreateFunc function);
-
- virtual void RemoveClass(const ObjectBase::Class* class_type);
-
- virtual const ObjectBase::Class* GetClassByClassName(
- const String& class_name) const;
-
- virtual bool ClassNameIsAClass(const String& derived_class_name,
- const ObjectBase::Class* base_class) const;
-
- virtual ObjectBase::Ref CreateObjectByClass(
- const ObjectBase::Class* object_class);
-
- virtual ObjectBase::Ref CreateObject(const String& type_name);
-
- std::vector<const ObjectBase::Class*> GetAllClasses() const;
-
- private:
- ServiceLocator* service_locator_;
- ServiceImplementation<IClassManager> service_;
-
- // A class to hold data about a class in the ObjectClassInfoNameMap;
-
- class ObjectClassInfo {
- public:
-
- ObjectClassInfo(const ObjectBase::Class* class_type,
- ObjectCreateFunc func)
- : class_type_(class_type),
- creation_func_(func) { }
-
- const ObjectBase::Class* class_type() const {
- return class_type_;
- }
-
- ObjectCreateFunc creation_func() const {
- return creation_func_;
- }
-
- private:
- const ObjectBase::Class* class_type_;
- const ObjectCreateFunc creation_func_;
- };
-
- // A map by string of ObjectClassInfos.
- typedef std::map<const String, ObjectClassInfo> ObjectClassInfoNameMap;
- // A map by ObjectBase::Class of Object creations functions.
- typedef std::map<const ObjectBase::Class*,
- ObjectCreateFunc> ObjectCreatorClassMap;
-
- // ObjectClassInfo by name.
- ObjectClassInfoNameMap object_class_info_name_map_;
-
- // ObjectClassInfo by class.
- ObjectCreatorClassMap object_creator_class_map_;
-};
-}
-
-#endif // O3D_CORE_CROSS_CLASS_MANAGER_H_
diff --git a/o3d/core/cross/class_manager_test.cc b/o3d/core/cross/class_manager_test.cc
deleted file mode 100644
index c48a3f4..0000000
--- a/o3d/core/cross/class_manager_test.cc
+++ /dev/null
@@ -1,140 +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 implements unit tests for class ClassManager.
-
-#include <algorithm>
-
-#include "core/cross/class_manager.h"
-#include "core/cross/object_manager.h"
-#include "tests/common/win/testing_common.h"
-
-namespace o3d {
-
-namespace {
-class CreatableClass : public ObjectBase {
- public:
- explicit CreatableClass(ServiceLocator* service_locator)
- : ObjectBase(service_locator) {
- }
- static ObjectBase::Ref Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new CreatableClass(service_locator));
- }
- O3D_DECL_CLASS(CreatableClass, ObjectBase)
-};
-O3D_DEFN_CLASS(CreatableClass, ObjectBase);
-
-class NonCreatableClass : public ObjectBase {
- public:
- explicit NonCreatableClass(ServiceLocator* service_locator)
- : ObjectBase(service_locator) {
- }
- static ObjectBase::Ref Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref();
- }
- O3D_DECL_CLASS(NonCreatableClass, ObjectBase)
-};
-O3D_DEFN_CLASS(NonCreatableClass, ObjectBase);
-}
-
-class ClassManagerTest : public testing::Test {
- protected:
-
- virtual void SetUp() {
- service_locator_ = new ServiceLocator;
- object_manager_ = new ObjectManager(service_locator_);
- class_manager_ = new ClassManager(service_locator_);
- class_manager_->AddTypedClass<CreatableClass>();
- class_manager_->AddTypedClass<NonCreatableClass>();
- }
-
- virtual void TearDown() {
- delete class_manager_;
- delete object_manager_;
- delete service_locator_;
- }
-
- ServiceLocator* service_locator_;
- ObjectManager* object_manager_;
- ClassManager* class_manager_;
-};
-
-TEST_F(ClassManagerTest, ShouldNotBeAbleToFindClassWithNameThatIsNotAdded) {
- EXPECT_EQ(NULL, class_manager_->GetClassByClassName(
- "o3d.NonexistentClass"));
-}
-
-TEST_F(ClassManagerTest, ShouldGetCreatableClassByName) {
- EXPECT_EQ(CreatableClass::GetApparentClass(),
- class_manager_->GetClassByClassName("o3d.CreatableClass"));
-}
-
-TEST_F(ClassManagerTest, ShouldCreateCreatableClass) {
- ObjectBase::Ref object = class_manager_->CreateObject(
- "o3d.CreatableClass");
- EXPECT_FALSE(object.IsNull());
-}
-
-TEST_F(ClassManagerTest, ShouldGetNonCreatableClassByName) {
- EXPECT_EQ(NonCreatableClass::GetApparentClass(),
- class_manager_->GetClassByClassName("o3d.NonCreatableClass"));
-}
-
-TEST_F(ClassManagerTest, ShouldNotCreateNonCreatableClass) {
- ObjectBase::Ref object = class_manager_->CreateObject(
- "o3d.NonCreatableClass");
- EXPECT_TRUE(object.IsNull());
-}
-
-TEST_F(ClassManagerTest, ClassShouldDeriveFromObjectBase) {
- EXPECT_TRUE(class_manager_->ClassNameIsAClass(
- "o3d.NonCreatableClass",
- ObjectBase::GetApparentClass()));
-}
-
-TEST_F(ClassManagerTest, ClassShouldDeriveFromItself) {
- EXPECT_TRUE(class_manager_->ClassNameIsAClass(
- "o3d.NonCreatableClass",
- NonCreatableClass::GetApparentClass()));
-}
-
-TEST_F(ClassManagerTest, ShouldGetAllClasses) {
- std::vector<const ObjectBase::Class*> classes =
- class_manager_->GetAllClasses();
- ASSERT_FALSE(classes.end() == std::find(
- classes.begin(), classes.end(),
- CreatableClass::GetApparentClass()));
- ASSERT_FALSE(classes.end() == std::find(
- classes.begin(), classes.end(),
- NonCreatableClass::GetApparentClass()));
-}
-} // namespace o3d
diff --git a/o3d/core/cross/clear_buffer.cc b/o3d/core/cross/clear_buffer.cc
deleted file mode 100644
index a733a4e..0000000
--- a/o3d/core/cross/clear_buffer.cc
+++ /dev/null
@@ -1,89 +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 ClearBuffer render node implementation
-
-#include "core/cross/clear_buffer.h"
-#include "core/cross/renderer.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(ClearBuffer, RenderNode)
-
-const char* ClearBuffer::kClearColorParamName =
- O3D_STRING_CONSTANT("clearColor");
-const char* ClearBuffer::kClearColorFlagParamName =
- O3D_STRING_CONSTANT("clearColorFlag");
-const char* ClearBuffer::kClearDepthParamName =
- O3D_STRING_CONSTANT("clearDepth");
-const char* ClearBuffer::kClearDepthFlagParamName =
- O3D_STRING_CONSTANT("clearDepthFlag");
-const char* ClearBuffer::kClearStencilParamName =
- O3D_STRING_CONSTANT("clearStencil");
-const char* ClearBuffer::kClearStencilFlagParamName =
- O3D_STRING_CONSTANT("clearStencilFlag");
-
-ClearBuffer::ClearBuffer(ServiceLocator* service_locator)
- : RenderNode(service_locator) {
- RegisterParamRef(kClearColorParamName, &color_param_ref_);
- RegisterParamRef(kClearColorFlagParamName, &color_flag_param_ref_);
- RegisterParamRef(kClearDepthParamName, &depth_param_ref_);
- RegisterParamRef(kClearDepthFlagParamName, &depth_flag_param_ref_);
- RegisterParamRef(kClearStencilParamName, &stencil_param_ref_);
- RegisterParamRef(kClearStencilFlagParamName, &stencil_flag_param_ref_);
-
- set_clear_color(Float4(0.0, 0.0f, 0.0f, 1.0f));
- set_clear_color_flag(true);
- set_clear_depth(1.0f);
- set_clear_depth_flag(true);
- set_clear_stencil(0);
- set_clear_stencil_flag(true);
-}
-
-ClearBuffer::~ClearBuffer() {
-}
-
-ObjectBase::Ref ClearBuffer::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ClearBuffer(service_locator));
-}
-
-void ClearBuffer::Render(RenderContext* render_context) {
- render_context->renderer()->Clear(
- clear_color(),
- clear_color_flag(),
- clear_depth(),
- clear_depth_flag(),
- clear_stencil(),
- clear_stencil_flag());
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/clear_buffer.h b/o3d/core/cross/clear_buffer.h
deleted file mode 100644
index 1da8b11..0000000
--- a/o3d/core/cross/clear_buffer.h
+++ /dev/null
@@ -1,145 +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 ClearBuffer render node declaration.
-
-#ifndef O3D_CORE_CROSS_CLEAR_BUFFER_H_
-#define O3D_CORE_CROSS_CLEAR_BUFFER_H_
-
-#include "core/cross/render_node.h"
-
-namespace o3d {
-
-// A ClearBuffer is a render node that clears the color buffer, zbuffer and/or
-// stencil buffer of the current render target.
-class ClearBuffer : public RenderNode {
- public:
- typedef SmartPointer<ClearBuffer> Ref;
-
- virtual ~ClearBuffer();
-
- // Gets the clear color.
- const Float4 clear_color() const {
- return color_param_ref_->value();
- }
-
- // Sets the clear color.
- void set_clear_color(const Float4& value) {
- color_param_ref_->set_value(value);
- }
-
- // Gets the clear color flag.
- bool clear_color_flag() const {
- return color_flag_param_ref_->value();
- }
-
- // Sets the clear color flag.
- void set_clear_color_flag(bool value) {
- color_flag_param_ref_->set_value(value);
- }
-
- // Gets the depth.
- float clear_depth() const {
- return depth_param_ref_->value();
- }
-
- // Sets the depth.
- void set_clear_depth(float value) {
- depth_param_ref_->set_value(value);
- }
-
- // Gets the clear depth flag.
- bool clear_depth_flag() const {
- return depth_flag_param_ref_->value();
- }
-
- // Sets the clear depth flag.
- void set_clear_depth_flag(bool value) {
- depth_flag_param_ref_->set_value(value);
- }
-
- // Gets the stencil clear value..
- int clear_stencil() const {
- return stencil_param_ref_->value();
- }
-
- // Sets the stencil clear value..
- void set_clear_stencil(int value) {
- stencil_param_ref_->set_value(value);
- }
-
- // Gets the clear stencil flag.
- bool clear_stencil_flag() const {
- return stencil_flag_param_ref_->value();
- }
-
- // Sets the clear stencil flag.
- void set_clear_stencil_flag(bool value) {
- stencil_flag_param_ref_->set_value(value);
- }
-
- // Names of ClearBuffer Params.
- static const char* kClearColorParamName;
- static const char* kClearColorFlagParamName;
- static const char* kClearDepthParamName;
- static const char* kClearDepthFlagParamName;
- static const char* kClearStencilParamName;
- static const char* kClearStencilFlagParamName;
-
- // Overridden from RenderNode. Renders with the specifed Effect, State and
- // params
- virtual void Render(RenderContext* render_context);
-
- private:
- explicit ClearBuffer(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamFloat4::Ref color_param_ref_; // Color to clear buffer.
- ParamBoolean::Ref color_flag_param_ref_; // True = clear color.
- ParamFloat::Ref depth_param_ref_; // Value to set depth buffer.
- ParamBoolean::Ref depth_flag_param_ref_; // True = clear depth buffer.
- ParamInteger::Ref stencil_param_ref_; // Value to set stencil.
- ParamBoolean::Ref stencil_flag_param_ref_; // True = clear stencil buffer.
-
- O3D_DECL_CLASS(ClearBuffer, RenderNode);
- DISALLOW_COPY_AND_ASSIGN(ClearBuffer);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_CLEAR_BUFFER_H_
-
-
-
-
diff --git a/o3d/core/cross/client.cc b/o3d/core/cross/client.cc
deleted file mode 100644
index 2d4a644..0000000
--- a/o3d/core/cross/client.cc
+++ /dev/null
@@ -1,662 +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 for the Client class.
-
-#include "core/cross/client.h"
-#include "core/cross/draw_context.h"
-#include "core/cross/effect.h"
-#include "core/cross/message_queue.h"
-#include "core/cross/pack.h"
-#include "core/cross/shape.h"
-#include "core/cross/transform.h"
-#include "core/cross/material.h"
-#include "core/cross/renderer.h"
-#include "core/cross/viewport.h"
-#include "core/cross/clear_buffer.h"
-#include "core/cross/state_set.h"
-#include "core/cross/tree_traversal.h"
-#include "core/cross/draw_pass.h"
-#include "core/cross/bounding_box.h"
-#include "core/cross/bitmap.h"
-#include "core/cross/error.h"
-#include "core/cross/evaluation_counter.h"
-#include "core/cross/id_manager.h"
-#include "core/cross/profiler.h"
-#include "utils/cross/string_writer.h"
-#include "utils/cross/json_writer.h"
-#include "utils/cross/dataurl.h"
-
-#ifdef OS_WIN
-#include "core/cross/core_metrics.h"
-#endif
-
-using std::map;
-using std::vector;
-using std::make_pair;
-
-namespace o3d {
-// If Renderer::max_fps has been set, rendering is driven by incoming new
-// textures. We draw on each new texture as long as not exceeding max_fps.
-//
-// If we are in RENDERMODE_ON_DEMAND mode, Client::Render() can still set dirty
-// specifically.
-//
-// If we are in RENDERMODE_CONTINUOUS mode, we do NOT set dirty on each tick any
-// more (since it is already driven by new textures.).
-// There is one problem here: what if new texture don't come in for some reason?
-// If that happened, no rendering callback will be invoked and this can cause
-// problem sometimes. For example, some UI may depend on the rendering callback
-// to work correctly.
-// So, in RENDERMODE_CONTINUOUS mode, if we have set max_fps but haven't
-// received any new texture for a while, we draw anyway to trigger the rendering
-// callback.
-// This value defines the minimum number of draws per seconds in
-// RENDERMODE_CONTINUOUS mode.
-static const float kContinuousModeMinDrawPerSecond = 15;
-// TODO(zhurunz) Tuning this value.
-
-// We don't want to handle too much MOUSEMOVE events for perf reasons.
-// This is used for limiting one MOUSEMOVE event per N ticks.
-//
-// Notes:
-// Don't limit MOUSEMOVE event on new texture since that don't always come.
-// Don't limit MOUSEMOVE event on rendering since RENDERMODE_ON_DEMAND might
-// depends on MOUSEMOVE first.
-static const int kTicksPerMouseMoveEvent = 4;
-
-// Client constructor. Creates the default root node for the scenegraph
-Client::Client(ServiceLocator* service_locator)
- : service_locator_(service_locator),
- object_manager_(service_locator),
- error_status_(service_locator),
- draw_list_manager_(service_locator),
- counter_manager_(service_locator),
- transformation_context_(service_locator),
- semantic_manager_(service_locator),
- profiler_(service_locator),
- renderer_(service_locator),
- evaluation_counter_(service_locator),
- render_tree_called_(false),
- render_mode_(RENDERMODE_CONTINUOUS),
- texture_on_hold_(false),
- event_manager_(),
- is_ticking_(false),
- last_tick_time_(0),
- tick_count_(0),
- root_(NULL),
-#ifdef OS_WIN
- calls_(0),
-#endif
- rendergraph_root_(NULL),
- id_(IdManager::CreateId()) {
- // Create and initialize the message queue to allow external code to
- // communicate with the Client via RPC calls.
- message_queue_.reset(new MessageQueue(service_locator_));
-
- if (!message_queue_->Initialize()) {
- LOG(ERROR) << "Client failed to initialize the message queue";
- message_queue_.reset(NULL);
- }
-}
-
-// Frees up all the resources allocated by the Client factory methods but
-// does not destroy the "renderer_" object.
-Client::~Client() {
- root_.Reset();
- rendergraph_root_.Reset();
-
- object_manager_->DestroyAllPacks();
-
- // Unmap the client from the renderer on exit.
- if (renderer_.IsAvailable()) {
- renderer_->UninitCommon();
- }
-}
-
-// Assigns a Renderer to the Client, and also assigns the Client
-// to the Renderer and sets up the default render graph
-void Client::Init() {
- if (!renderer_.IsAvailable())
- return;
-
- // Create the root node for the scenegraph. Note that the root lives
- // outside of a pack object. The root's lifetime is directly bound to that
- // of the client.
- root_ = Transform::Ref(new Transform(service_locator_));
- root_->set_name(O3D_STRING_CONSTANT("root"));
-
- // Creates the root for the render graph.
- rendergraph_root_ = RenderNode::Ref(new RenderNode(service_locator_));
- rendergraph_root_->set_name(O3D_STRING_CONSTANT("root"));
-
- // Let the renderer Init a few common things.
- renderer_->InitCommon();
-}
-
-void Client::Cleanup() {
- ClearRenderCallback();
- ClearPostRenderCallback();
- ClearTickCallback();
- event_manager_.ClearAll();
- counter_manager_.ClearAllCallbacks();
-
- // Disable continuous rendering because there is nothing to render after
- // Cleanup is called. This speeds up the the process of unloading the page.
- // It also preserves the last rendered frame so long as it does not become
- // invalid.
- render_mode_ = RENDERMODE_ON_DEMAND;
-
- // Destroy the packs here if possible. If there are a lot of objects it takes
- // a long time and seems to make Chrome timeout if it happens in NPP_Destroy.
- root_.Reset();
- rendergraph_root_.Reset();
- object_manager_->DestroyAllPacks();
-}
-
-Pack* Client::CreatePack() {
- if (!renderer_.IsAvailable()) {
- O3D_ERROR(service_locator_)
- << "No Renderer available, Pack creation not allowed.";
- return NULL;
- }
-
- return object_manager_->CreatePack();
-}
-
-// Tick Methods ----------------------------------------------------------------
-
-void Client::SetTickCallback(
- TickCallback* tick_callback) {
- tick_callback_manager_.Set(tick_callback);
-}
-
-void Client::ClearTickCallback() {
- tick_callback_manager_.Clear();
-}
-
-bool Client::Tick() {
- is_ticking_ = true;
- ElapsedTimeTimer timer;
- float seconds_elapsed = tick_elapsed_time_timer_.GetElapsedTimeAndReset();
- tick_event_.set_elapsed_time(seconds_elapsed);
- profiler_->ProfileStart("Tick callback");
- tick_callback_manager_.Run(tick_event_);
- profiler_->ProfileStop("Tick callback");
-
- evaluation_counter_->InvalidateAllParameters();
-
- counter_manager_.AdvanceCounters(1.0f, seconds_elapsed);
-
- // Processes any incoming message found in the message queue. Note that this
- // call does not block if no new messages are found.
- bool message_check_ok = true;
- bool has_new_texture = false;
-
- if (message_queue_.get()) {
- profiler_->ProfileStart("CheckForNewMessages");
- message_check_ok = message_queue_->CheckForNewMessages(&has_new_texture);
- profiler_->ProfileStop("CheckForNewMessages");
- }
-
- event_manager_.ProcessQueue();
- event_manager_.ProcessQueue();
- event_manager_.ProcessQueue();
- event_manager_.ProcessQueue();
-
- last_tick_time_ = timer.GetElapsedTimeAndReset();
-
- texture_on_hold_ |= has_new_texture;
- if (texture_on_hold_ && renderer_.IsAvailable()) {
- int max_fps = renderer_->max_fps();
- if (max_fps > 0 &&
- render_mode() == RENDERMODE_ON_DEMAND &&
- render_elapsed_time_timer_.GetElapsedTimeWithoutClearing()
- > 1.0/max_fps) {
- renderer_->set_need_to_render(true);
- texture_on_hold_ = false;
- }
- }
-
- is_ticking_ = false;
- tick_count_++;
- return message_check_ok;
-}
-
-// Render Methods --------------------------------------------------------------
-
-void Client::SetLostResourcesCallback(LostResourcesCallback* callback) {
- if (!renderer_.IsAvailable()) {
- O3D_ERROR(service_locator_) << "No Renderer";
- } else {
- renderer_->SetLostResourcesCallback(callback);
- }
-}
-
-void Client::ClearLostResourcesCallback() {
- if (renderer_.IsAvailable()) {
- renderer_->ClearLostResourcesCallback();
- }
-}
-
-void Client::RenderClientInner(bool present, bool send_callback) {
- ElapsedTimeTimer timer;
- render_tree_called_ = false;
- total_time_to_render_ = 0.0f;
-
- if (!renderer_.IsAvailable())
- return;
-
- if (renderer_->StartRendering()) {
- counter_manager_.AdvanceRenderFrameCounters(1.0f);
-
- profiler_->ProfileStart("Render callback");
- if (send_callback)
- render_callback_manager_.Run(render_event_);
-
- // Calling back to JavaScript may have caused the plugin to be
- // torn down. Guard carefully against this.
- if (!profiler_.IsAvailable()) {
- if (renderer_.IsAvailable()) {
- renderer_->FinishRendering();
- }
- return;
- }
-
- profiler_->ProfileStop("Render callback");
-
- if (!render_tree_called_) {
- RenderNode* rendergraph_root = render_graph_root();
- // If nothing was rendered and there are no render graph nodes then
- // clear the client area.
- if (!rendergraph_root || rendergraph_root->children().empty()) {
- renderer_->Clear(Float4(0.4f, 0.3f, 0.3f, 1.0f),
- true, 1.0, true, 0, true);
- } else if (rendergraph_root) {
- RenderTree(rendergraph_root);
- }
- }
-
- renderer_->FinishRendering();
- if (present) {
- renderer_->Present();
- // This has to be called before the POST render callback because
- // the post render callback may call Client::Render.
- renderer_->set_need_to_render(false);
- }
-
- // Call post render callback.
- profiler_->ProfileStart("Post-render callback");
- post_render_callback_manager_.Run(render_event_);
- profiler_->ProfileStop("Post-render callback");
-
- // Update Render stats.
- render_event_.set_elapsed_time(
- render_elapsed_time_timer_.GetElapsedTimeAndReset());
- render_event_.set_render_time(total_time_to_render_);
- render_event_.set_transforms_culled(renderer_->transforms_culled());
- render_event_.set_transforms_processed(renderer_->transforms_processed());
- render_event_.set_draw_elements_culled(renderer_->draw_elements_culled());
- render_event_.set_draw_elements_processed(
- renderer_->draw_elements_processed());
- render_event_.set_draw_elements_rendered(
- renderer_->draw_elements_rendered());
-
- render_event_.set_primitives_rendered(renderer_->primitives_rendered());
-
- render_event_.set_active_time(
- timer.GetElapsedTimeAndReset() + last_tick_time_);
- last_tick_time_ = 0.0f;
-
-#ifdef OS_WIN
- // Update render metrics
- metric_render_elapsed_time.AddSample( // Convert to ms.
- static_cast<int>(1000 * render_event_.elapsed_time()));
- metric_render_time_seconds += static_cast<uint64>(
- render_event_.render_time());
- metric_render_xforms_culled.AddSample(render_event_.transforms_culled());
- metric_render_xforms_processed.AddSample(
- render_event_.transforms_processed());
- metric_render_draw_elts_culled.AddSample(
- render_event_.draw_elements_culled());
- metric_render_draw_elts_processed.AddSample(
- render_event_.draw_elements_processed());
- metric_render_draw_elts_rendered.AddSample(
- render_event_.draw_elements_rendered());
- metric_render_prims_rendered.AddSample(render_event_.primitives_rendered());
-#endif // OS_WIN
- }
-}
-
-void Client::RenderClient(bool send_callback) {
- if (!renderer_.IsAvailable())
- return;
-
- bool have_offscreen_surfaces =
- !(offscreen_render_surface_.IsNull() ||
- offscreen_depth_render_surface_.IsNull());
-
- if (have_offscreen_surfaces) {
- if (!renderer_->StartRendering()) {
- return;
- }
- renderer_->SetRenderSurfaces(offscreen_render_surface_,
- offscreen_depth_render_surface_,
- true);
- }
-
- RenderClientInner(!have_offscreen_surfaces, send_callback);
-
- if (have_offscreen_surfaces) {
- renderer_->SetRenderSurfaces(NULL, NULL, false);
- renderer_->FinishRendering();
- }
-}
-
-bool Client::IsRendering() {
- return (renderer_.IsAvailable() && renderer_->rendering());
-}
-
-bool Client::NeedsRender() {
- return NeedsContinuousRender() || renderer_->need_to_render();
-}
-
-bool Client::NeedsContinuousRender() {
- bool needRender = false;
- // Only may happen in RENDERMODE_CONTINUOUS mode.
- if (render_mode() == RENDERMODE_CONTINUOUS) {
- // Always need a draw in normal RENDERMODE_CONTINUOUS mode.
- needRender = true;
-
- if (renderer_.IsAvailable()) {
- // If max_fps has been set, only need a draw when "long time no draw".
- int max_fps = renderer_->max_fps();
- if (max_fps > 0 &&
- render_elapsed_time_timer_.GetElapsedTimeWithoutClearing() <
- 1.0/kContinuousModeMinDrawPerSecond)
- {
- needRender = false;
- }
- }
- }
- return needRender;
-}
-
-// Executes draw calls for all visible shapes in a subtree
-void Client::RenderTree(RenderNode *tree_root) {
- if (!renderer_.IsAvailable())
- return;
-
- if (!renderer_->rendering()) {
- // Render tree can not be called if we are not rendering because all calls
- // to RenderTree must happen inside renderer->StartRendering() /
- // renderer->FinishRendering() calls.
- O3D_ERROR(service_locator_)
- << "RenderTree must not be called outside of rendering.";
- return;
- }
-
- render_tree_called_ = true;
-
- // Only render the shapes if BeginDraw() succeeds
- profiler_->ProfileStart("RenderTree");
- ElapsedTimeTimer time_to_render_timer;
- if (renderer_->BeginDraw()) {
- RenderContext render_context(renderer_.Get());
-
- if (tree_root) {
- tree_root->RenderTree(&render_context);
- }
-
- draw_list_manager_.Reset();
-
- // Finish up.
- renderer_->EndDraw();
- }
- total_time_to_render_ += time_to_render_timer.GetElapsedTimeAndReset();
- profiler_->ProfileStop("RenderTree");
-}
-
-void Client::SetRenderCallback(RenderCallback* render_callback) {
- render_callback_manager_.Set(render_callback);
-}
-
-void Client::ClearRenderCallback() {
- render_callback_manager_.Clear();
-}
-
-void Client::SetEventCallback(Event::Type type,
- EventCallback* event_callback) {
- event_manager_.SetEventCallback(type, event_callback);
-}
-
-void Client::SetEventCallback(String type_name,
- EventCallback* event_callback) {
- Event::Type type = Event::TypeFromString(type_name.c_str());
- if (!Event::ValidType(type)) {
- O3D_ERROR(service_locator_) << "Invalid event type: '" <<
- type_name << "'.";
- } else {
- event_manager_.SetEventCallback(type, event_callback);
- }
-}
-
-void Client::ClearEventCallback(Event::Type type) {
- event_manager_.ClearEventCallback(type);
-}
-
-void Client::ClearEventCallback(String type_name) {
- Event::Type type = Event::TypeFromString(type_name.c_str());
- if (!Event::ValidType(type)) {
- O3D_ERROR(service_locator_) << "Invalid event type: '" <<
- type_name << "'.";
- } else {
- event_manager_.ClearEventCallback(type);
- }
-}
-
-void Client::AddEventToQueue(const Event& event) {
- // Limit one MOUSEMOVE event per N ticks.
- if (event.type() == Event::TYPE_MOUSEMOVE) {
- if (tick_count_ <= kTicksPerMouseMoveEvent) {
- return;
- } else {
- tick_count_ = 0;
- }
- }
- event_manager_.AddEventToQueue(event);
-}
-
-void Client::SendResizeEvent(int width, int height, bool fullscreen) {
- Event event(Event::TYPE_RESIZE);
- event.set_size(width, height, fullscreen);
- AddEventToQueue(event);
-}
-
-void Client::set_render_mode(RenderMode render_mode) {
- render_mode_ = render_mode;
-}
-
-void Client::SetPostRenderCallback(RenderCallback* post_render_callback) {
- post_render_callback_manager_.Set(post_render_callback);
-}
-
-void Client::ClearPostRenderCallback() {
- post_render_callback_manager_.Clear();
-}
-
-void Client::Render() {
- if (render_mode() == RENDERMODE_ON_DEMAND) {
- if (renderer_.IsAvailable()) {
- renderer_->set_need_to_render(true);
- }
- }
-}
-
-void Client::SetErrorTexture(Texture* texture) {
- renderer_->SetErrorTexture(texture);
-}
-
-void Client::InvalidateAllParameters() {
- evaluation_counter_->InvalidateAllParameters();
-}
-
-String Client::GetScreenshotAsDataURL() {
- // To take a screenshot we create a render target and render into it
- // then get a bitmap from that.
- int pot_width =
- static_cast<int>(image::ComputePOTSize(renderer_->display_width()));
- int pot_height =
- static_cast<int>(image::ComputePOTSize(renderer_->display_height()));
- if (pot_width == 0 || pot_height == 0) {
- return dataurl::kEmptyDataURL;
- }
- Texture2D::Ref texture = renderer_->CreateTexture2D(
- pot_width,
- pot_height,
- Texture::ARGB8,
- 1,
- true);
- if (texture.IsNull()) {
- return dataurl::kEmptyDataURL;
- }
- RenderSurface::Ref surface(texture->GetRenderSurface(0));
- if (surface.IsNull()) {
- return dataurl::kEmptyDataURL;
- }
- RenderDepthStencilSurface::Ref depth(renderer_->CreateDepthStencilSurface(
- pot_width,
- pot_height));
- if (depth.IsNull()) {
- return dataurl::kEmptyDataURL;
- }
- surface->SetClipSize(renderer_->display_width(), renderer_->display_height());
- depth->SetClipSize(renderer_->display_width(), renderer_->display_height());
-
- const RenderSurface* old_render_surface_;
- const RenderDepthStencilSurface* old_depth_surface_;
- bool is_back_buffer;
-
- renderer_->GetRenderSurfaces(&old_render_surface_, &old_depth_surface_,
- &is_back_buffer);
- renderer_->SetRenderSurfaces(surface, depth, true);
-
- RenderClientInner(false, true);
-
- renderer_->SetRenderSurfaces(old_render_surface_, old_depth_surface_,
- is_back_buffer);
-
- Bitmap::Ref bitmap(surface->GetBitmap());
- if (bitmap.IsNull()) {
- return dataurl::kEmptyDataURL;
- } else {
- bitmap->FlipVertically();
- return bitmap->ToDataURL();
- }
-}
-
-String Client::ToDataURL() {
- if (!renderer_.IsAvailable()) {
- O3D_ERROR(service_locator_) << "No Render Device Available";
- return dataurl::kEmptyDataURL;
- }
-
- if (renderer_->rendering()) {
- O3D_ERROR(service_locator_)
- << "Can not take a screenshot while rendering";
- return dataurl::kEmptyDataURL;
- }
-
- if (!renderer_->StartRendering()) {
- return dataurl::kEmptyDataURL;
- }
-
- String data_url(GetScreenshotAsDataURL());
- renderer_->FinishRendering();
-
- return data_url;
-}
-
-String Client::GetMessageQueueAddress() const {
- if (message_queue_.get()) {
- return message_queue_->GetSocketAddress();
- } else {
- O3D_ERROR(service_locator_) << "Message queue not initialized";
- return String("");
- }
-}
-
-void Client::SetOffscreenRenderingSurfaces(
- RenderSurface::Ref surface,
- RenderDepthStencilSurface::Ref depth_surface) {
- offscreen_render_surface_ = surface;
- offscreen_depth_render_surface_ = depth_surface;
-}
-
-// Error Related methods -------------------------------------------------------
-
-void Client::SetErrorCallback(ErrorCallback* callback) {
- error_status_.SetErrorCallback(callback);
-}
-
-void Client::ClearErrorCallback() {
- error_status_.ClearErrorCallback();
-}
-
-const String& Client::GetLastError() const {
- return error_status_.GetLastError();
-}
-
-void Client::ClearLastError() {
- error_status_.ClearLastError();
-}
-
-void Client::ProfileStart(const std::string& key) {
- profiler_->ProfileStart(key);
-}
-
-void Client::ProfileStop(const std::string& key) {
- profiler_->ProfileStop(key);
-}
-
-void Client::ProfileReset() {
- profiler_->ProfileReset();
-}
-
-String Client::ProfileToString() {
- StringWriter string_writer(StringWriter::LF);
- JsonWriter json_writer(&string_writer, 2);
- profiler_->Write(&json_writer);
- json_writer.Close();
- return string_writer.ToString();
-}
-} // namespace o3d
diff --git a/o3d/core/cross/client.h b/o3d/core/cross/client.h
deleted file mode 100644
index 19cc45e..0000000
--- a/o3d/core/cross/client.h
+++ /dev/null
@@ -1,550 +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 class definition of the o3d::Client,
-// the main entry point to O3D.
-
-#ifndef O3D_CORE_CROSS_CLIENT_H_
-#define O3D_CORE_CROSS_CLIENT_H_
-
-#include <build/build_config.h>
-#include <map>
-#include <ostream>
-#include <sstream>
-#include <string>
-#include <vector>
-
-#include "base/logging.h"
-#include "base/scoped_ptr.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/error_status.h"
-#include "core/cross/draw_list_manager.h"
-#include "core/cross/counter_manager.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/semantic_manager.h"
-#include "core/cross/transformation_context.h"
-#include "core/cross/render_node.h"
-#include "core/cross/callback.h"
-#include "core/cross/event.h"
-#include "core/cross/event_callback.h"
-#include "core/cross/event_manager.h"
-#include "core/cross/lost_resource_callback.h"
-#include "core/cross/render_event.h"
-#include "core/cross/render_surface.h"
-#include "core/cross/tick_event.h"
-#include "core/cross/timer.h"
-#include "core/cross/timingtable.h"
-#include "core/cross/transform.h"
-
-namespace o3d {
-class MessageQueue;
-class Profiler;
-class State;
-class Pack;
-
-// The Client class is the main point of entry to O3D. It defines methods
-// for creating and deleting packs and internal use only methods for creating
-// most objects. Each new object created by the Client is assigned a unique ID
-// which can be used to efficiently retrieve the object using the appropriate
-// Get*ById() method.
-//
-// The Client has a root transform for the transform graph and a root render
-// node for the render graph.
-class Client {
- friend class ObjectBase;
- friend class ParamObject;
-
- public:
-
- explicit Client(ServiceLocator* service_locator);
- ~Client();
-
- typedef NonRecursiveCallback1Manager<const RenderEvent&>
- RenderCallbackManager;
- typedef RenderCallbackManager::CallbackType RenderCallback;
-
- // Name of the default pack that the default rendergraph rendernodes belong
- // to.
- static const char* kDefaultPackName;
-
- Id id() const {
- return id_;
- }
-
- // Sets the renderer to be used for all platform-specific graphics
- // methods and sets up the default rendergraph
- void Init();
-
- // Cleansup certain things in preparation for unloading the plugin.
- // This is for Javascript because there are certain conditions, the Render
- // callback for example, which can cause a javascript error in the browser
- // while the page is being unloaded. This function, if called during
- // window.onunload, handles those cases.
- void Cleanup();
-
- // Pack methods --------------------------
-
- // Creates a pack object, and registers it within the Client's internal
- // dictionary strutures. Note that multiple packs may share the same name.
- // The system does not enforce pack name uniqueness.
- // Returns:
- // A smart-pointer reference to the newly created pack object.
- Pack* CreatePack();
-
- // Node methods --------------------------
-
- // Returns the transform graph root transform
- // Parameters:
- // None
- // Returns:
- // A pointer to the transform graph root Transform
- inline Transform* root() const {
- return root_.Get();
- }
-
- // RenderNode methods --------------------------
-
- enum RenderMode {
- RENDERMODE_CONTINUOUS, // Draw as often as possible up to refresh rate.
- RENDERMODE_ON_DEMAND, // Draw once, then only when the OS requests it
- // (like uncovering part of a window.)
- };
-
- RenderMode render_mode() const {
- return render_mode_;
- }
-
- void set_render_mode(RenderMode render_mode);
-
- // Returns the rendergraph root render node.
- // Parameters:
- // None.
- // Returns:
- // A pointer to the rendergraph root rendernode.
- inline RenderNode* render_graph_root() const {
- return rendergraph_root_;
- }
-
- // Searches the entire Client's rendernode dictionary for rendernodes that
- // match the given name. It will find rendernodes created by the Client
- // regardless of whether or not they are part of the rendergraph.
- // Parameters:
- // name: Node name to look for.
- // render_nodes: RenderNodeArray to receive list of nodes. It anything is in
- // the array will be cleared.
- void GetRenderNodesFast(const String& name,
- RenderNodeArray* render_nodes) const;
-
- // Renders a subtree of the rendergraph.
- // Parameters:
- // tree_root: The root of the subtree to be drawn.
- // Returns:
- // Nothing
- void RenderTree(RenderNode *tree_root);
-
- // Sets the render callback.
- // NOTE: The client takes ownership of the RenderCallback you pass in. It will
- // be deleted if you call SetRenderCallback a second time or if you call
- // ClearRenderCallback
- //
- // Parameters:
- // render_callback: RenderCallback to call each frame.
- void SetRenderCallback(RenderCallback* render_callback);
-
- // Clears the render callback
- // NOTE: The client takes ownership of the RenderCallback you pass in to
- // SetRenderCallback. It will be deleted if you call SetRenderCallback a
- // second time or if you call ClearRenderCallback
- void ClearRenderCallback();
-
- // Sets the callback for a events of a supplied type.
- // NOTE: The client takes ownership of the EventCallback you pass in. It will
- // be deleted if you call SetEventCallback a second time for the same event
- // type or if you call ClearEventCallback for that type.
- //
- // Parameters:
- // event_callback: EventCallback to call each time an event of the right
- // type occurs.
- // type: Type of event this callback handles.
- void SetEventCallback(Event::Type type, EventCallback* render_callback);
- void SetEventCallback(String type_name, EventCallback* render_callback);
-
- // Clears the callback for events of a given type.
- void ClearEventCallback(Event::Type type);
- void ClearEventCallback(String type_name);
-
- // Automatically drops some events to throttle event bandwidth.
- void AddEventToQueue(const Event& event);
- // Adds a resize event to the queue.
- void SendResizeEvent(int width, int height, bool fullscreen);
-
- // Sets the lost resources callback.
- // NOTE: The client takes ownership of the LostResourcesCallback you pass in.
- // It will be deleted if you call SetLostResourcesCallback a second time or if
- // you call ClearLostResourcesCallback
- //
- // Parameters:
- // callback: LostResourcesCallback to call each frame.
- void SetLostResourcesCallback(LostResourcesCallback* callback);
-
- // Clears the lost resources callback
- // NOTE: The client takes ownership of the LostResourcesCallback you pass in
- // to SetLostResourcesCallback. It will be deleted if you call
- // SetLostResourcesCallback a second time or if you call
- // ClearLostResourcesCallback.
- void ClearLostResourcesCallback();
-
- // Forces a render of the current scene if the current render mode is
- // RENDERMODE_ON_DEMAND.
- void Render();
-
- // Sets the post render callback.
- // NOTE: The client takes ownership of the RenderCallback you pass in. It will
- // be deleted if you call SetPostRenderCallback a second time or if you call
- // ClearPostRenderCallback
- //
- // Parameters:
- // post_render_callback: RenderCallback to call at the end of
- // the render cycle in each frame.
- void SetPostRenderCallback(RenderCallback* post_render_callback);
-
- // Clears the post render callback
- // NOTE: The client takes ownership of the RenderCallback you pass in to
- // SetPostRenderCallback. It will be deleted if you call post
- // SetRenderCallback a second time or if you call ClearRenderCallback.
- void ClearPostRenderCallback();
-
- // Updates the current state of the objects handled by the Client and
- // processes any messages found in the message queue then renders the client.
- // This is the function anything hosting the client, like a plugin, should
- // call to render.
- // Parameters:
- // send_callback : whether to make the javascript render callback.
- // Generally you want to pass true, but if the render is happening
- // in non-windowed mode (eg on a Mac) and is in response to an update
- // event rather than a timer, it can be useful to pass false to prevent
- // the javascript code triggering another update and causing an infinite
- // calback loop. Case in point is the custom camera example, which
- // modifies some HTML form text fields on render callback, which on
- // Firefox causes a plugin invalidation and round and round we would
- // go.
- void RenderClient(bool send_callback);
-
- // In some situations (on Mac OS X at least) calling the user's
- // render callback can cause OS events to be dispatched which cause
- // the plugin to become reentrant. Detect this at a higher level.
- bool IsRendering();
-
- // Needs either ONDEMAND or CONTINOUS render.
- bool NeedsRender();
-
- // If Renderer::max_fps has been set in RENDERMODE_CONTINUOUS mode, we don't
- // draw on each tick but just let new textures drive the rendering. There is
- // only one exception: if we haven't received any new textures for a while, we
- // still need to draw in order to trigger rendering callback. Since there
- // might be some UI depends on rendering callback.
- // This function determines if this has happened and if we need a draw.
- bool NeedsContinuousRender();
-
- // Sets the texture to use when a Texture or Sampler is missing while
- // rendering. If you set it to NULL you'll get an error if you try to render
- // something that is missing a needed Texture, Sampler or ParamSampler
- // Parameters:
- // texture: texture to use for missing texture or NULL.
- void SetErrorTexture(Texture* texture);
-
- // Tick Methods ----------------------------
-
- typedef NonRecursiveCallback1Manager<const o3d::TickEvent&>
- TickCallbackManager;
- typedef TickCallbackManager::CallbackType TickCallback;
-
- // Sets the tick callback.
- // NOTE: The client takes ownership of the TickCallback you pass in. It will
- // be deleted if you call SetTickCallback a second time or if you call
- // ClearTickCallback.
- //
- // Parameters:
- // tick_callback: TickCallback to call each time the client processes a
- // tick.
- void SetTickCallback(TickCallback* tick_callback);
-
- // Clears the tick callback NOTE: The client takes ownership of the
- // TickCallback you pass in to SetTickCallback. It will be deleted if you call
- // SetTickCallback a second time or if you call ClearTickCallback.
- void ClearTickCallback();
-
- // Tick the client. This method is called by the plugin to give the client
- // a chance to process NaCl messages and update animation.
- // Returns:
- // true if message check was ok.
- bool Tick();
-
- // Indicates whether a call to Tick() is in progress. This is needed
- // to avoid reentrancy problems on some platforms.
- bool IsTicking() const {
- return is_ticking_;
- }
-
- // Searches in the Client for an object by its id. This function is for
- // Javascript.
- // Parameters:
- // id: id of object to look for.
- // Returns:
- // Pointer to the object or NULL if not found.
- ObjectBase* GetObjectById(Id id) const {
- return object_manager_->GetObjectById(id);
- }
-
- // Searches the Client for objects of a particular name and type.
- // This function is for Javascript.
- // Parameters:
- // name: name of object to look for.
- // type_name: name of class to look for.
- // Returns:
- // Array of raw pointers to the found objects.
- ObjectBaseArray GetObjects(const String& name,
- const String& type_name) const {
- return object_manager_->GetObjects(name, type_name);
- }
-
- // Searches by id for an Object created by the Client. To search
- // for an object regardless of type use:
- // Client::GetById<ObjectBase>(obj_id)
- // To search for an object of a specific type use:
- // Client::GetById<Type>(obj_id)
- // for example, to search for Transform use:
- // Client::GetById<Transform>(transform_id)
- // Parameters:
- // id: Unique id of the object to search for
- // Returns:
- // Pointer to the object with matching id or NULL if no object is found
- template<class T> T* GetById(Id id) const {
- return object_manager_->GetById<T>(id);
- }
-
- // Search the client for all objects of a certain class
- // Returns:
- // Array of Pointers to the requested class.
- template<typename T>
- std::vector<T*> GetByClass() const {
- return object_manager_->GetByClass<T>();
- }
-
- // Search the client for all objects of a certain class
- // Parameters:
- // class_type_name: the Class of the object. It is okay to pass base types
- // for example Node::GetApparentClass()->name will return
- // both Transforms and Shapes.
- // Returns:
- // Array of Object Pointers.
- ObjectBaseArray GetObjectsByClassName(const String& class_type_name) const {
- return object_manager_->GetObjectsByClassName(class_type_name);
- }
-
- // Returns the socket address of the IMC message queue associated with the
- // Client.
- String GetMessageQueueAddress() const;
-
- // Error Methods ----------------
-
- typedef Callback1<const String&> ErrorCallback;
-
- // Sets the error callback. NOTE: The client takes ownership of the
- // ErrorCallback you pass in. It will be deleted if you call SetErrorCallback
- // a second time or if you call ClearErrorCallback.
- //
- // Parameters:
- // error_callback: ErrorCallback to call each time the client gets
- // an error.
- void SetErrorCallback(ErrorCallback* error_callback);
-
- // Clears the Error callback NOTE: The client takes ownership of the
- // ErrorCallback you pass in to SetErrorCallback. It will be deleted if you
- // call SetErrorCallback a second time or if you call ClearErrorCallback.
- void ClearErrorCallback();
-
- // Gets the last reported error.
- const String& GetLastError() const;
-
- // Clears the stored last error.
- void ClearLastError();
-
- // Parameter methods ------------------
-
- // Marks all parameters as so they will get re-evaluated
- void InvalidateAllParameters();
-
- // Profiling methods -------------------
-
- // Starts the timer ticking for the code range identified by key.
- void ProfileStart(const std::string& key);
-
- // Stops the timer for the code range identified by key.
- void ProfileStop(const std::string& key);
-
- // Resets the profiler, clearing out all data.
- void ProfileReset();
-
- // Dumps all profiler state to a string.
- String ProfileToString();
-
- // Reutrns a data: URL of the client area in png format.
- String ToDataURL();
-
- // This class is intended to be used on the stack, such that the variable gets
- // incremented on scope entry and decremented on scope exit. It's currently
- // used in WindowProc to determine if we're reentrant or not, but may be
- // needed on other platforms as well.
- class ScopedIncrement {
- public:
- explicit ScopedIncrement(Client *client) {
- DCHECK(client);
- client_ = client;
- ++client_->calls_;
- DCHECK_GT(client_->calls_, 0);
- }
- int get() {
- DCHECK(client_); // Don't call this after decrement!
- return client_->calls_;
- }
- void decrement() {
- if (client_) {
- DCHECK_GT(client_->calls_, 0);
- --client_->calls_;
- client_ = NULL;
- }
- }
- ~ScopedIncrement() {
- decrement();
- }
- private:
- Client *client_;
- DISALLOW_COPY_AND_ASSIGN(ScopedIncrement);
- };
-
- // Offscreen rendering methods -------------------
-
- // Sets up this Client so that RenderClient will cause the rendering
- // results to go into the given surfaces.
- void SetOffscreenRenderingSurfaces(
- RenderSurface::Ref surface,
- RenderDepthStencilSurface::Ref depth_surface);
-
- private:
- // Renders the client.
- void RenderClientInner(bool present, bool send_callback);
-
- // Gets a screenshot.
- String GetScreenshotAsDataURL();
-
- // MessageQueue that allows external code to communicate with the Client.
- scoped_ptr<MessageQueue> message_queue_;
-
- ServiceLocator* service_locator_;
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- DrawListManager draw_list_manager_;
- CounterManager counter_manager_;
- TransformationContext transformation_context_;
- SemanticManager semantic_manager_;
- ServiceDependency<Profiler> profiler_;
- ServiceDependency<Renderer> renderer_;
- ServiceDependency<EvaluationCounter> evaluation_counter_;
-
- // RenderTree was called.
- bool render_tree_called_;
-
- // Render mode.
- RenderMode render_mode_;
-
- // Used for rendering control
- bool texture_on_hold_;
-
- // Render Callbacks.
- RenderCallbackManager render_callback_manager_;
-
- RenderCallbackManager post_render_callback_manager_;
-
- // Render Event to pass to the render callback.
- RenderEvent render_event_;
-
- // This class holds on to all the handlers and the event queue for standard
- // JavaScript IO events.
- EventManager event_manager_;
-
- // Timer for getting the elapsed time between render updates.
- ElapsedTimeTimer render_elapsed_time_timer_;
-
- // Tick Callback.
- TickCallbackManager tick_callback_manager_;
-
- // Tick Event to pass to the tick callback.
- TickEvent tick_event_;
-
- // Timer for getting the elapsed time between tick updates.
- ElapsedTimeTimer tick_elapsed_time_timer_;
-
- // Whether a call to Tick() is currently active.
- bool is_ticking_;
-
- // Used to gather render time from mulitple RenderTree calls.
- float total_time_to_render_;
-
- // Time used for tick and message processing.
- float last_tick_time_;
-
- // Number of ticks since last reset.
- int tick_count_;
-
- // Reference to global transform graph root for Client.
- Transform::Ref root_;
-
- // Global Render Graph root for Client.
- RenderNode::Ref rendergraph_root_;
-
- ParamObject::Ref sas_param_object_;
-
- // The id of the client.
- Id id_;
-
- int calls_; // Used to check reentrancy along with ScopedIncrement.
-
- RenderSurface::Ref offscreen_render_surface_;
- RenderDepthStencilSurface::Ref offscreen_depth_render_surface_;
-
- DISALLOW_COPY_AND_ASSIGN(Client);
-}; // Client
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_CLIENT_H_
diff --git a/o3d/core/cross/client_info.cc b/o3d/core/cross/client_info.cc
deleted file mode 100644
index b927e8e..0000000
--- a/o3d/core/cross/client_info.cc
+++ /dev/null
@@ -1,67 +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 ClientInfoManager implementation
-
-#include "core/cross/client_info.h"
-#include <vector>
-#include "base/string_util.h"
-#include "core/cross/types.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/object_manager.h"
-
-namespace o3d {
-
-ClientInfo::ClientInfo()
- : num_objects_(0),
- texture_memory_used_(0),
- buffer_memory_used_(0),
- software_renderer_(false),
- non_power_of_two_textures_(false),
- render_2d_(false),
- version_(O3D_PLUGIN_VERSION) {
-}
-
-const InterfaceId ClientInfoManager::kInterfaceId =
- InterfaceTraits<ClientInfoManager>::kInterfaceId;
-
-ClientInfoManager::ClientInfoManager(ServiceLocator* service_locator)
- : service_(service_locator, this) {
-}
-
-const ClientInfo& ClientInfoManager::client_info() {
- ServiceDependency<ObjectManager> object_manager_(service_.service_locator());
- client_info_.num_objects_ = object_manager_->GetNumObjects();
- return client_info_;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/client_info.h b/o3d/core/cross/client_info.h
deleted file mode 100644
index 7e828c7..0000000
--- a/o3d/core/cross/client_info.h
+++ /dev/null
@@ -1,154 +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 ClientInfo class.
-
-#ifndef O3D_CORE_CROSS_CLIENT_INFO_H_
-#define O3D_CORE_CROSS_CLIENT_INFO_H_
-
-#include "core/cross/types.h"
-#include "core/cross/service_locator.h"
-#include "core/cross/service_implementation.h"
-
-namespace o3d {
-
-// This class is used to report infomation about the client.
-class ClientInfo {
- public:
- ClientInfo();
-
- // The number of objects the client is currently tracking.
- int num_objects() const {
- return num_objects_;
- }
-
- // The amount of texture memory used.
- int texture_memory_used() const {
- return texture_memory_used_;
- };
-
- // The amount of texture memory used.
- int buffer_memory_used() const {
- return buffer_memory_used_;
- }
-
- // Whether or not we are using the software renderer.
- bool software_renderer() const {
- return software_renderer_;
- }
-
- // Whether or not shaders are GLSL.
- bool glsl() const {
-#if defined(RENDERER_GLES2)
- return true;
-#else
- return false;
-#endif
- }
-
- // Whether render in 2d Mode
- bool render_2d() const {
- return render_2d_;
- }
-
- // Whether or not the underlying GPU supports non power of 2 textures.
- // NOTE: O3D always supports non power of 2 textures from a public API
- // point of view and massages the data underneath to make this work.
- // The point of this flag is mostly that if you are doing any kind of
- // dynamic texture updating, like video, then you might want to use a
- // power of two texture so O3D doesn't have to do extra work of converting
- // your NPOT texture into a POT texture behind the scenes.
- bool non_power_of_two_textures() const {
- return non_power_of_two_textures_;
- }
-
- // Gets the O3D version.
- const String& version() const {
- return version_;
- }
-
- private:
- friend class ClientInfoManager;
-
- int num_objects_;
- int texture_memory_used_;
- int buffer_memory_used_;
- bool software_renderer_;
- bool non_power_of_two_textures_;
- bool render_2d_;
- String version_;
-};
-
-// A class to manage the client info so other classes can easily look it up.
-class ClientInfoManager {
- public:
- static const InterfaceId kInterfaceId;
-
- explicit ClientInfoManager(ServiceLocator* service_locator);
-
- const ClientInfo& client_info();
-
- // Adds or subtracts from the amount of texture memory used.
- void AdjustTextureMemoryUsed(int amount) {
- client_info_.texture_memory_used_ += amount;
- DCHECK(client_info_.texture_memory_used_ >= 0);
- }
-
- // Adds or subtracts from the amount of texture memory used.
- void AdjustBufferMemoryUsed(int amount) {
- client_info_.buffer_memory_used_ += amount;
- DCHECK(client_info_.buffer_memory_used_ >= 0);
- }
-
- void SetSoftwareRenderer(bool used) {
- client_info_.software_renderer_ = used;
- }
-
- void SetNonPowerOfTwoTextures(bool npot) {
- client_info_.non_power_of_two_textures_ = npot;
- }
-
- void SetRender2d(bool render2d) {
- client_info_.render_2d_ = render2d;
- }
-
-private:
- ServiceImplementation<ClientInfoManager> service_;
-
- ClientInfo client_info_;
-
- DISALLOW_COPY_AND_ASSIGN(ClientInfoManager);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_CLIENT_INFO_H_
diff --git a/o3d/core/cross/client_info_test.cc b/o3d/core/cross/client_info_test.cc
deleted file mode 100644
index 6fb4722..0000000
--- a/o3d/core/cross/client_info_test.cc
+++ /dev/null
@@ -1,174 +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 implements unit tests for class ClientInfoManager.
-
-#include "core/cross/client.h"
-#include "tests/common/win/testing_common.h"
-#include "core/cross/client_info.h"
-
-namespace o3d {
-
-class ClientInfoManagerTest : public testing::Test {
- public:
- ServiceLocator* service_locator() {
- return service_locator_;
- }
-
- ObjectManager* object_manager() {
- return object_manager_;
- }
-
- protected:
- ClientInfoManagerTest() { }
-
- virtual void SetUp() {
- // We need to create a new SerivceLocator because the global one
- // already has a global ClientInfoManager object registered on it.
- service_locator_ = new ServiceLocator;
- object_manager_ = new ObjectManager(service_locator_);
- }
-
- virtual void TearDown() {
- delete object_manager_;
- delete service_locator_;
- }
-
- ServiceLocator* service_locator_;
- ObjectManager* object_manager_;
-};
-
-TEST_F(ClientInfoManagerTest, Basic) {
- ClientInfoManager* client_info_manager =
- new ClientInfoManager(service_locator());
- ASSERT_TRUE(client_info_manager != NULL);
-
- // Check that the client_info_manager start off correctly.
- EXPECT_EQ(0, client_info_manager->client_info().texture_memory_used());
- EXPECT_EQ(0, client_info_manager->client_info().buffer_memory_used());
- EXPECT_EQ(0, client_info_manager->client_info().num_objects());
- EXPECT_FALSE(client_info_manager->client_info().software_renderer());
- EXPECT_FALSE(client_info_manager->client_info().non_power_of_two_textures());
-
- int version[4] = { -1, -1, -1, -1 };
- sscanf(client_info_manager->client_info().version().c_str(),
- "%d.%d.%d.%d", &version[0], &version[1], &version[2], &version[3]);
- EXPECT_NE(-1, version[0]);
- EXPECT_NE(-1, version[1]);
- EXPECT_NE(-1, version[2]);
- EXPECT_NE(-1, version[3]);
-
- delete client_info_manager;
-}
-
-TEST_F(ClientInfoManagerTest, AdjustTextureMemoryUsed) {
- ClientInfoManager* client_info_manager =
- new ClientInfoManager(service_locator());
- ASSERT_TRUE(client_info_manager != NULL);
-
- client_info_manager->AdjustTextureMemoryUsed(10);
- EXPECT_EQ(10, client_info_manager->client_info().texture_memory_used());
- client_info_manager->AdjustTextureMemoryUsed(10);
- EXPECT_EQ(20, client_info_manager->client_info().texture_memory_used());
- client_info_manager->AdjustTextureMemoryUsed(-10);
- EXPECT_EQ(10, client_info_manager->client_info().texture_memory_used());
- client_info_manager->AdjustTextureMemoryUsed(-10);
- EXPECT_EQ(0, client_info_manager->client_info().texture_memory_used());
-
- delete client_info_manager;
-}
-
-TEST_F(ClientInfoManagerTest, AdjustBufferMemoryUsed) {
- ClientInfoManager* client_info_manager =
- new ClientInfoManager(service_locator());
- ASSERT_TRUE(client_info_manager != NULL);
-
- client_info_manager->AdjustBufferMemoryUsed(10);
- EXPECT_EQ(10, client_info_manager->client_info().buffer_memory_used());
- client_info_manager->AdjustBufferMemoryUsed(10);
- EXPECT_EQ(20, client_info_manager->client_info().buffer_memory_used());
- client_info_manager->AdjustBufferMemoryUsed(-10);
- EXPECT_EQ(10, client_info_manager->client_info().buffer_memory_used());
- client_info_manager->AdjustBufferMemoryUsed(-10);
- EXPECT_EQ(0, client_info_manager->client_info().buffer_memory_used());
-
- delete client_info_manager;
-}
-
-TEST_F(ClientInfoManagerTest, SetNumObjects) {
- ClientInfoManager* client_info_manager =
- new ClientInfoManager(service_locator());
- ASSERT_TRUE(client_info_manager != NULL);
-
- ObjectBase* object_1 = new ObjectBase(service_locator());
- ASSERT_TRUE(object_1 != NULL);
- EXPECT_EQ(1, client_info_manager->client_info().num_objects());
-
- ObjectBase* object_2 = new ObjectBase(service_locator());
- ASSERT_TRUE(object_2 != NULL);
- EXPECT_EQ(2, client_info_manager->client_info().num_objects());
-
- delete object_1;
- EXPECT_EQ(1, client_info_manager->client_info().num_objects());
- delete object_2;
- EXPECT_EQ(0, client_info_manager->client_info().num_objects());
-
- delete client_info_manager;
-}
-
-TEST_F(ClientInfoManagerTest, SetSoftwareRenderer) {
- ClientInfoManager* client_info_manager =
- new ClientInfoManager(service_locator());
- ASSERT_TRUE(client_info_manager != NULL);
-
- client_info_manager->SetSoftwareRenderer(true);
- EXPECT_TRUE(client_info_manager->client_info().software_renderer());
- client_info_manager->SetSoftwareRenderer(false);
- EXPECT_FALSE(client_info_manager->client_info().software_renderer());
-
- delete client_info_manager;
-}
-
-TEST_F(ClientInfoManagerTest, SetNonPowerOfTwoTextures) {
- ClientInfoManager* client_info_manager =
- new ClientInfoManager(service_locator());
- ASSERT_TRUE(client_info_manager != NULL);
-
- client_info_manager->SetNonPowerOfTwoTextures(true);
- EXPECT_TRUE(client_info_manager->client_info().non_power_of_two_textures());
- client_info_manager->SetNonPowerOfTwoTextures(false);
- EXPECT_FALSE(client_info_manager->client_info().non_power_of_two_textures());
-
- delete client_info_manager;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/client_test.cc b/o3d/core/cross/client_test.cc
deleted file mode 100644
index 49c5d85..0000000
--- a/o3d/core/cross/client_test.cc
+++ /dev/null
@@ -1,555 +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 "core/cross/client.h"
-#include "tests/common/win/testing_common.h"
-#include "core/cross/pack.h"
-#include "core/cross/buffer.h"
-
-namespace o3d {
-
-using Vectormath::Aos::Vector4;
-using Vectormath::Aos::Matrix4;
-
-// Basic test fixture. Simply creates a Client object
-// before each test and deletes it after
-class ClientBasic : public testing::Test {
- protected:
-
- ClientBasic()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
-
- virtual void TearDown();
-
- Client* client() { return client_; }
- Pack* pack() { return pack_; }
-
- void DestroyPack();
-
- ServiceDependency<ObjectManager> object_manager_;
-
- private:
- Client *client_;
- Pack* pack_;
-};
-
-void ClientBasic::SetUp() {
- client_ = new Client(g_service_locator);
- client_->Init();
- pack_ = object_manager_->CreatePack();
-}
-
-void ClientBasic::TearDown() {
- DestroyPack();
- delete client_;
-}
-
-void ClientBasic::DestroyPack() {
- if (pack_) {
- object_manager_->DestroyPack(pack_);
- pack_ = NULL;
- }
-}
-
-// Tests that the Client always has a root
-TEST_F(ClientBasic, GetRoot) {
- EXPECT_TRUE((client()->root() != NULL));
-}
-
-TEST_F(ClientBasic, CreatePack) {
- const String kPackName("CreatePack pack");
- Pack* pack = object_manager_->CreatePack();
- pack->set_name(kPackName);
- ASSERT_FALSE(pack == NULL);
-
- EXPECT_TRUE(object_manager_->GetById<Pack>(pack->id()) == pack);
- object_manager_->DestroyPack(pack);
-}
-
-// Tests Transform creation
-TEST_F(ClientBasic, CreateTransform) {
- Transform* t = pack()->Create<Transform>();
- ASSERT_FALSE(t == NULL);
-
- EXPECT_TRUE(t->IsA(Transform::GetApparentClass()));
-
- EXPECT_TRUE(object_manager_->GetById<Transform>(t->id()) == t);
-
- // Make sure the node has no parent
- EXPECT_TRUE(t->parent() == NULL);
-}
-
-// Tests shape creation
-TEST_F(ClientBasic, CreateShape) {
- Shape* s = pack()->Create<Shape>();
- ASSERT_FALSE(s == NULL);
-
- EXPECT_TRUE(s->IsA(Shape::GetApparentClass()));
-
- EXPECT_TRUE(object_manager_->GetById<Shape>(s->id()) == s);
-}
-
-// Buffer ----------------------------------------------------------------------
-
-// Tests buffer creation
-TEST_F(ClientBasic, CreateBuffer) {
- Buffer* b1(pack()->Create<IndexBuffer>());
- EXPECT_FALSE(b1 == NULL);
- Buffer* b2(pack()->Create<VertexBuffer>());
- EXPECT_FALSE(b2 == NULL);
-}
-
-// Tests GetBuffers
-TEST_F(ClientBasic, GetBuffers) {
- Buffer* b1 = pack()->Create<IndexBuffer>();
- b1->set_name("buffer1");
- Buffer* b2 = pack()->Create<VertexBuffer>();
- b2->set_name("buffer1");
- Buffer* b3 = pack()->Create<VertexBuffer>();
- b3->set_name("buffer3");
-
- std::vector<Buffer*> buffers = object_manager_->Get<Buffer>("buffer1");
- EXPECT_EQ(2U, buffers.size());
- std::vector<Buffer*>::const_iterator pos;
- EXPECT_TRUE((pos = find(buffers.begin(), buffers.end(), b1)) !=
- buffers.end());
- EXPECT_TRUE((pos = find(buffers.begin(), buffers.end(), b2)) !=
- buffers.end());
-}
-
-// Tests GetBufferById
-TEST_F(ClientBasic, GetBufferById) {
- Buffer* b1 = pack()->Create<IndexBuffer>();
- Buffer* b2 = pack()->Create<VertexBuffer>();
- ASSERT_TRUE(b1 != NULL);
- ASSERT_TRUE(b2 != NULL);
-
- o3d::Id id1 = b1->id();
- o3d::Id id2 = b2->id();
-
- EXPECT_TRUE(object_manager_->GetById<Buffer>(id1) == b1);
- EXPECT_TRUE(object_manager_->GetById<Buffer>(id2) == b2);
-}
-
-// Effect ----------------------------------------------------------------------
-
-// Tests Effect creation
-TEST_F(ClientBasic, CreateEffect) {
- Effect* e1 = pack()->Create<Effect>();
- EXPECT_FALSE(e1 == NULL);
- Effect* e2 = pack()->Create<Effect>();
- EXPECT_FALSE(e2 == NULL);
-}
-
-// Tests GetEffects
-TEST_F(ClientBasic, GetEffects) {
- Effect* e1 = pack()->Create<Effect>();
- e1->set_name("effect1");
- Effect* e2 = pack()->Create<Effect>();
- e2->set_name("effect1");
- Effect* e3 = pack()->Create<Effect>();
- e3->set_name("effect3");
-
- EffectArray effects = object_manager_->Get<Effect>("effect1");
- EXPECT_EQ(2U, effects.size());
- EffectArray::const_iterator pos;
- EXPECT_TRUE((pos = find(effects.begin(), effects.end(), e1)) !=
- effects.end());
- EXPECT_TRUE((pos = find(effects.begin(), effects.end(), e2)) !=
- effects.end());
-}
-
-// Tests GetEffectById
-TEST_F(ClientBasic, GetEffectById) {
- Effect* e1 = pack()->Create<Effect>();
- Effect* e2 = pack()->Create<Effect>();
- ASSERT_TRUE(e1 != NULL);
- ASSERT_TRUE(e2 != NULL);
-
- o3d::Id id1 = e1->id();
- o3d::Id id2 = e2->id();
-
- EXPECT_TRUE(object_manager_->GetById<Effect>(id1) == e1);
- EXPECT_TRUE(object_manager_->GetById<Effect>(id2) == e2);
-}
-
-// Scenegraph tree -------------------------------------------------------------
-
-// Scenegraph tree test fixture. Creates a Client object and
-// a simple hierarchy in it
-class ClientTree : public testing::Test {
- protected:
-
- ClientTree()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
-
- virtual void TearDown();
-
- Client* client() { return client_; }
- Pack* pack() { return pack_; }
- void DestroyPack();
-
- Transform *t1_, *t2_, *t3_, *t4_;
- Shape *s1_, *s2_, *s3_;
- o3d::Id id_t1_, id_t2_, id_t3_, id_t4_, id_s1_, id_s2_, id_s3_;
-
- ServiceDependency<ObjectManager> object_manager_;
-
- private:
- Client *client_;
- Pack* pack_;
-};
-
-void ClientTree::SetUp() {
- client_ = new Client(g_service_locator);
- client_->Init();
-
- pack_ = object_manager_->CreatePack();
-
- t1_ = pack_->Create<Transform>();
- t1_->set_name("t1");
- t2_ = pack_->Create<Transform>();
- t2_->set_name("t2");
- t3_ = pack_->Create<Transform>();
- t3_->set_name("t3");
- t4_ = pack_->Create<Transform>();
- t4_->set_name("t4");
-
- s1_ = pack_->Create<Shape>();
- ASSERT_TRUE(s1_ != NULL);
- s2_ = pack_->Create<Shape>();
- ASSERT_TRUE(s2_ != NULL);
- s3_ = pack_->Create<Shape>();
- ASSERT_TRUE(s3_ != NULL);
-
- Transform *root = client_->root();
- t1_->SetParent(root);
- t2_->SetParent(root);
- t3_->SetParent(t2_);
- t4_->SetParent(t2_);
-
- t2_->AddShape(s1_);
- t3_->AddShape(s2_);
- t4_->AddShape(s3_);
-
- id_t1_ = t1_->id();
- id_t2_ = t2_->id();
- id_t3_ = t3_->id();
- id_t4_ = t4_->id();
-
- id_s1_ = s1_->id();
- id_s2_ = s2_->id();
- id_s3_ = s3_->id();
-}
-
-void ClientTree::TearDown() {
- DestroyPack();
- delete client_;
-}
-
-void ClientTree::DestroyPack() {
- if (pack_) {
- object_manager_->DestroyPack(pack_);
- pack_ = NULL;
- }
-}
-
-// Tests GetById
-TEST_F(ClientTree, GetById) {
- EXPECT_TRUE(object_manager_->GetById<Shape>(id_s2_) == s2_);
-}
-
-// Tests GetByName
-TEST_F(ClientTree, GetByName) {
- TransformArray transforms = object_manager_->Get<Transform>("t3");
- EXPECT_EQ(1U, transforms.size());
- EXPECT_TRUE(transforms[0] == t3_);
-
- transforms = object_manager_->Get<Transform>("t5");
- EXPECT_EQ(0U, transforms.size());
-
- // Add one more transform with the name "t3"
- Transform* t3_new = pack()->Create<Transform>();
- t3_new->set_name("t3");
- transforms = object_manager_->Get<Transform>("t3");
- EXPECT_EQ(2U, transforms.size());
- TransformArray::const_iterator pos;
- EXPECT_TRUE((pos = find(transforms.begin(),
- transforms.end(),
- t3_)) != transforms.end());
- EXPECT_TRUE((pos = find(transforms.begin(),
- transforms.end(),
- t3_new)) != transforms.end());
-}
-
-// NaCl interface --------------------------------------------------------------
-
-#if 0 // TODO: Understand and fix this stuff
-// Native client interface test fixture
-class NaClInterface : public testing::Test {
- protected:
- virtual void SetUp();
-
- virtual void TearDown();
-
- Client* client() { return client_; }
- Pack* pack() { return pack_; }
-
- Transform *t1_, *t2_, *t3_, *t4_;
- Shape *s1_, *s2_, *s3_;
- Primitive *p1_, *p2_, *p3_;
- o3d::Id id_t1_, id_t2_, id_t3_, id_t4_, id_s1_, id_s2_, id_s3_;
- int vertex_buffer_size_;
- int index_buffer_size_;
- scoped_array<float> cube_vertices1_;
- scoped_array<float> cube_vertices2_;
-
- private:
- Client *client_;
- Pack* pack_;
-};
-
-void NaClInterface::SetUp() {
- client_ = new Client;
- client_->Init(g_renderer);
-
- pack_ = object_manager_->CreatePack();
-
- t1_ = pack_->Create<Transform>("t1");
- t2_ = pack_->Create<Transform>("t2");
- t3_ = pack_->Create<Transform>("t3");
- t4_ = pack_->Create<Transform>("t4");
-
- s1_ = pack_->Create<Shape>("s1");
- p1_ = pack_->Create<Primitive>("p1");
- ASSERT_TRUE(s1_ != NULL);
- ASSERT_TRUE(p1_ != NULL);
- s2_ = pack_->Create<Shape>("s2");
- p2_ = pack_->Create<Primitive>("p2");
- ASSERT_TRUE(s2_ != NULL);
- ASSERT_TRUE(p2_ != NULL);
- s3_ = pack_->Create<Shape>("s3");
- p3_ = pack_->Create<Primitive>("p3");
- ASSERT_TRUE(s3_ != NULL);
- ASSERT_TRUE(p3_ != NULL);
-
- Transform *root = client()->root();
- t1_->SetParent(root);
- t2_->SetParent(root);
- t3_->SetParent(t2_);
- t4_->SetParent(t2_);
-
- t2_->AddShape(s1_);
- t3_->AddShape(s2_);
- t4_->AddShape(s3_);
-
- s1_->AddPrimitive(p1_);
- s2_->AddPrimitive(p2_);
- s3_->AddPrimitive(p3_);
-
- const unsigned int kCubeIndicies[] = {
- 0, 1, 2, 1, 3, 2, // Quad 0
- 4, 5, 6, 5, 7, 6, // Quad 1
- 4, 6, 0, 6, 1, 0, // Quad 2
- 5, 2, 7, 2, 3, 7, // Quad 3
- 1, 6, 3, 6, 7, 3, // Quad 4
- 0, 2, 4, 2, 5, 4 // Quad 5
- };
-
- cube_vertices1_.reset(new float[8*3]);
- cube_vertices2_.reset(new float[8*3]);
-
- for (int ii = 0;ii < 8*3;ii++) {
- cube_vertices1_[ii] = static_cast<float>(ii+100);
- cube_vertices2_[ii] = static_cast<float>(ii+200);
- }
-
-
- // Create and fill the vertex buffer
- VertexBuffer* vert_buffer = pack()->Create<VertexBuffer>("CubeVerts");
- ASSERT_TRUE(vert_buffer != NULL);
- vertex_buffer_size_ = 8*3*sizeof(cube_vertices1_[0]);
- vert_buffer->Allocate(vertex_buffer_size_);
- void *vertices = NULL;
- vert_buffer->Lock(&vertices);
- memcpy(vertices, cube_vertices1_.get(), vertex_buffer_size_);
- vert_buffer->Unlock();
-
- // Create and fill the vertex buffer
- VertexBuffer* vert_buffer2 = pack()->Create<VertexBuffer>("CubeVerts2");
- ASSERT_TRUE(vert_buffer2 != NULL);
- vert_buffer2->Allocate(vertex_buffer_size_);
- void *vertices2 = NULL;
- vert_buffer2->Lock(&vertices2);
- memcpy(vertices2, cube_vertices2_.get(), vertex_buffer_size_);
- vert_buffer2->Unlock();
-
- // Create and fill the index buffer
- IndexBuffer* index_buffer = pack()->Create<IndexBuffer>("CubeIndices");
- ASSERT_TRUE(index_buffer != NULL);
- index_buffer->Allocate(6*6*sizeof(kCubeIndicies[0]));
- unsigned int *indices = NULL;
- void *indices_void = static_cast<void*>(indices);
- index_buffer->Lock(&indices_void);
- memcpy(indices_void, kCubeIndicies, sizeof(kCubeIndicies));
- index_buffer->Unlock();
- index_buffer_size_ = 6*6*sizeof(kCubeIndicies[0]);
-
- p1_->SetVertexStream(Stream::POSITION,
- 0,
- Stream::FLOAT3,
- vert_buffer,
- 0,
- sizeof(cube_vertices1_[0]) * 3);
- p1_->SetIndexStream(index_buffer, 0);
-
- p2_->SetVertexStream(Stream::POSITION,
- 0,
- Stream::FLOAT3,
- vert_buffer2,
- 0,
- sizeof(cube_vertices2_[0]) * 3);
- p2_->SetIndexStream(index_buffer, 0);
-
- id_t1_ = t1_->id();
- id_t2_ = t2_->id();
- id_t3_ = t3_->id();
- id_t4_ = t4_->id();
-
- id_s1_ = s1_->id();
- id_s2_ = s2_->id();
- id_s3_ = s3_->id();
-}
-
-void NaClInterface::TearDown() {
- object_manager_->DestroyPack(pack_);
- delete client_;
-}
-
-TEST_F(NaClInterface, GetPropertyBufferSize) {
- // Fail when an id is not found
- IdArray ids;
- ids.push_back(100);
- EXPECT_EQ(-1,
- client()->GetPropertyBufferSize(ids, Client::PROP_WORLD_MATRIX));
-
- // Fail when the property is not available in one of the nodes
- // (Shapes don't have a world matrix property)
- ids.clear();
- ids.push_back(id_s1_);
- ids.push_back(id_t1_);
- EXPECT_EQ(-1,
- client()->GetPropertyBufferSize(ids, Client::PROP_WORLD_MATRIX));
-
- ids.clear();
- ids.push_back(id_t1_);
- ids.push_back(id_t2_);
- ids.push_back(id_t3_);
- int expected_size = 3*4*sizeof(float)*3; // NOLINT
- EXPECT_EQ(expected_size,
- client()->GetPropertyBufferSize(ids, Client::PROP_WORLD_MATRIX));
-
- ids.clear();
- ids.push_back(id_s1_);
- ids.push_back(id_s2_);
- expected_size = 2*vertex_buffer_size_;
- EXPECT_EQ(
- expected_size,
- client()->GetPropertyBufferSize(ids, Client::PROP_VERTEX_POSITIONS));
-}
-
-TEST_F(NaClInterface, GetPropertyToBuffer) {
- IdArray ids;
- ids.push_back(id_s1_);
- ids.push_back(id_s2_);
- int sz = client()->GetPropertyBufferSize(ids, Client::PROP_VERTEX_POSITIONS);
- float *buff = static_cast<float*>(malloc(sz));
- EXPECT_TRUE(client()->GetPropertyToBuffer(buff,
- sz,
- ids,
- Client::PROP_VERTEX_POSITIONS));
- EXPECT_TRUE(buff[0] == cube_vertices1_[0]);
- EXPECT_TRUE(buff[5] == cube_vertices1_[5]);
- EXPECT_TRUE(buff[10] == cube_vertices1_[10]);
-
- EXPECT_TRUE(buff[24+0] == cube_vertices2_[0]);
- EXPECT_TRUE(buff[24+4] == cube_vertices2_[4]);
- EXPECT_TRUE(buff[24+10] == cube_vertices2_[10]);
-}
-
-TEST_F(NaClInterface, SetPropertyFromBuffer) {
- IdArray ids;
- ids.push_back(id_s1_);
- ids.push_back(id_s2_);
- int sz = client()->GetPropertyBufferSize(ids, Client::PROP_VERTEX_POSITIONS);
- int float_count = sz/sizeof(float); // NOLINT
- float *buff = new float[float_count];
- for (int ii = 0;ii < float_count;ii++)
- buff[ii] = static_cast<float>(ii);
-
- EXPECT_TRUE(client()->SetPropertyFromBuffer(buff,
- sz,
- ids,
- Client::PROP_VERTEX_POSITIONS));
-
- // Check that the values made it to the first shape
- Stream stream = p1_->GetVertexStream(Stream::POSITION, 0);
- Buffer *buffer = stream.buffer();
- void *buffer_data = NULL;
- buffer->Lock(&buffer_data);
- float *f_data = static_cast<float*>(buffer_data);
- int ii;
- for (ii = 0;ii < float_count/2;ii++)
- EXPECT_TRUE(f_data[ii] == buff[ii]);
- buffer->Unlock();
-
- // Check that the values made it to the second shape
- stream = p2_->GetVertexStream(Stream::POSITION, 0);
- buffer = stream.buffer();
- buffer_data = NULL;
- buffer->Lock(&buffer_data);
- f_data = static_cast<float*>(buffer_data);
- for (ii = 0;ii < float_count/2;ii++)
- EXPECT_TRUE(f_data[ii] == buff[ii + float_count/2]);
- buffer->Unlock();
-
- delete [] buff;
-}
-#endif
-
-} // namespace o3d
diff --git a/o3d/core/cross/core_metrics.cc b/o3d/core/cross/core_metrics.cc
deleted file mode 100644
index b1aabd5..0000000
--- a/o3d/core/cross/core_metrics.cc
+++ /dev/null
@@ -1,52 +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 "statsreport/metrics.h"
-
-namespace o3d {
-// Shader Instruction counts
-DEFINE_METRIC_timing(vertex_shader_instruction_count);
-DEFINE_METRIC_timing(pixel_shader_instruction_count);
-
-// Render Events
-DEFINE_METRIC_timing(render_elapsed_time);
-DEFINE_METRIC_count(render_time_seconds);
-DEFINE_METRIC_timing(render_xforms_culled);
-DEFINE_METRIC_timing(render_xforms_processed);
-DEFINE_METRIC_timing(render_draw_elts_culled);
-DEFINE_METRIC_timing(render_draw_elts_processed);
-DEFINE_METRIC_timing(render_draw_elts_rendered);
-DEFINE_METRIC_timing(render_prims_rendered);
-
-// Messages
-DEFINE_METRIC_bool(imc_hello_msg);
-} // namespace o3d
diff --git a/o3d/core/cross/core_metrics.h b/o3d/core/cross/core_metrics.h
deleted file mode 100644
index 96b3bd0..0000000
--- a/o3d/core/cross/core_metrics.h
+++ /dev/null
@@ -1,60 +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.
- */
-
-
-// Declares the system metrics used by the plugin.
-
-#ifndef O3D_CORE_CROSS_CORE_METRICS_H_
-#define O3D_CORE_CROSS_CORE_METRICS_H_
-
-#include "statsreport/metrics.h"
-
-namespace o3d {
-// Shader Instruction counts
-DECLARE_METRIC_timing(vertex_shader_instruction_count);
-DECLARE_METRIC_timing(pixel_shader_instruction_count);
-
-// Render Events
-DECLARE_METRIC_timing(render_elapsed_time);
-DECLARE_METRIC_count(render_time_seconds);
-DECLARE_METRIC_timing(render_xforms_culled);
-DECLARE_METRIC_timing(render_xforms_processed);
-DECLARE_METRIC_timing(render_draw_elts_culled);
-DECLARE_METRIC_timing(render_draw_elts_processed);
-DECLARE_METRIC_timing(render_draw_elts_rendered);
-DECLARE_METRIC_timing(render_prims_rendered);
-
-// Messages
-DECLARE_METRIC_bool(imc_hello_msg);
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_CORE_METRICS_H_
diff --git a/o3d/core/cross/counter.cc b/o3d/core/cross/counter.cc
deleted file mode 100644
index dcf84e7..0000000
--- a/o3d/core/cross/counter.cc
+++ /dev/null
@@ -1,563 +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 definitions of Counter related classes
-
-#include "core/cross/counter.h"
-#include "core/cross/counter_manager.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Counter, ParamObject);
-O3D_DEFN_CLASS(SecondCounter, Counter);
-O3D_DEFN_CLASS(RenderFrameCounter, Counter);
-O3D_DEFN_CLASS(TickCounter, Counter);
-
-const char* Counter::kRunningParamName =
- O3D_STRING_CONSTANT("running");
-const char* Counter::kForwardParamName =
- O3D_STRING_CONSTANT("forward");
-const char* Counter::kStartParamName =
- O3D_STRING_CONSTANT("start");
-const char* Counter::kEndParamName =
- O3D_STRING_CONSTANT("end");
-const char* Counter::kCountModeParamName =
- O3D_STRING_CONSTANT("countMode");
-const char* Counter::kCountParamName =
- O3D_STRING_CONSTANT("count");
-const char* Counter::kMultiplierParamName =
- O3D_STRING_CONSTANT("multiplier");
-
-Counter::Counter(ServiceLocator* service_locator)
- : ParamObject(service_locator),
- next_callback_valid_(false),
- prev_callback_valid_(false),
- last_call_callbacks_end_count_(0.0f) {
- RegisterParamRef(kRunningParamName, &running_param_);
- RegisterParamRef(kForwardParamName, &forward_param_);
- RegisterParamRef(kCountModeParamName, &count_mode_param_);
- RegisterParamRef(kStartParamName, &start_param_);
- RegisterParamRef(kEndParamName, &end_param_);
- RegisterParamRef(kCountParamName, &count_param_);
- RegisterParamRef(kMultiplierParamName, &multiplier_param_);
- set_multiplier(1.0f);
- set_forward(true);
- set_running(true);
- set_count_mode(Counter::CONTINUOUS);
-}
-
-Counter::~Counter() {
- // We have to call this manually to make sure all the callback managers
- // unregister themselves before callback_managers_ is destoryed.
- callbacks_.clear();
-}
-
-void Counter::Reset() {
- SetCount(forward() ? start() : end());
-}
-
-void Counter::SetCount(float value) {
- set_count(value);
- next_callback_valid_ = false;
- prev_callback_valid_ = false;
-}
-
-void Counter::Advance(float advance_amount, CounterCallbackQueue* queue) {
- DCHECK(queue != NULL);
-
- float old_count = count_param_->value();
-
- // Update the count.
- if (count_param_->input_connection() != NULL) {
- float new_count = count_param_->value();
- CallCallbacks(old_count, new_count, queue);
- } else {
- bool direction = forward();
- float start_count = start();
- float end_count = end();
- float delta = (direction ? advance_amount : -advance_amount) * multiplier();
- float period = end_count - start_count;
-
- CountMode mode = count_mode();
- if (period >= 0.0f) {
- // end > start
- float new_count = old_count + delta;
- if (delta >= 0.0f) {
- switch (mode) {
- case Counter::ONCE: {
- if (new_count >= end_count) {
- new_count = end_count;
- set_running(false);
- }
- break;
- }
- case Counter::CYCLE: {
- while (new_count >= end_count) {
- CallCallbacks(old_count, end_count, queue);
- if (period == 0.0f) {
- break;
- }
- old_count = start_count;
- new_count -= period;
- }
- break;
- }
- case Counter::OSCILLATE: {
- while (delta > 0.0f) {
- new_count = old_count + delta;
- if (new_count < end_count) {
- break;
- }
- CallCallbacks(old_count, end_count, queue);
- direction = !direction;
- float amount = end_count - old_count;
- delta -= amount;
- old_count = end_count;
- new_count = end_count;
- if (delta <= 0.0f || period == 0.0f) {
- break;
- }
- new_count -= delta;
- if (new_count > start_count) {
- break;
- }
- CallCallbacks(old_count, start_count, queue);
- direction = !direction;
- amount = old_count - start_count;
- delta -= amount;
- old_count = start_count;
- new_count = start_count;
- }
- set_forward(direction);
- break;
- }
- case Counter::CONTINUOUS:
- default:
- break;
- }
- CallCallbacks(old_count, new_count, queue);
- set_count(new_count);
- } else if (delta < 0.0f) {
- switch (mode) {
- case Counter::ONCE: {
- if (new_count <= start_count) {
- new_count = start_count;
- set_running(false);
- }
- break;
- }
- case Counter::CYCLE: {
- while (new_count <= start_count) {
- CallCallbacks(old_count, start_count, queue);
- if (period == 0.0f) {
- break;
- }
- old_count = end_count;
- new_count += period;
- }
- break;
- }
- case Counter::OSCILLATE: {
- while (delta < 0.0f) {
- new_count = old_count + delta;
- if (new_count > start_count) {
- break;
- }
- CallCallbacks(old_count, start_count, queue);
- direction = !direction;
- float amount = old_count - start_count;
- delta += amount;
- old_count = start_count;
- new_count = start_count;
- if (delta >= 0.0f || period == 0.0f) {
- break;
- }
- new_count -= delta;
- if (new_count < end_count) {
- break;
- }
- CallCallbacks(old_count, end_count, queue);
- direction = !direction;
- amount = end_count - old_count;
- delta += amount;
- old_count = end_count;
- new_count = end_count;
- }
- set_forward(direction);
- break;
- }
- case Counter::CONTINUOUS:
- default:
- break;
- }
- CallCallbacks(old_count, new_count, queue);
- set_count(new_count);
- }
- } else if (period < 0.0f) {
- // start > end
- period = -period;
- float new_count = old_count - delta;
- if (delta > 0.0f) {
- switch (mode) {
- case Counter::ONCE: {
- if (new_count <= end_count) {
- new_count = end_count;
- set_running(false);
- }
- break;
- }
- case Counter::CYCLE: {
- while (new_count <= end_count) {
- CallCallbacks(old_count, end_count, queue);
- old_count = start_count;
- new_count += period;
- }
- break;
- }
- case Counter::OSCILLATE: {
- while (delta > 0.0f) {
- new_count = old_count - delta;
- if (new_count > end_count) {
- break;
- }
- CallCallbacks(old_count, end_count, queue);
- direction = !direction;
- float amount = old_count - end_count;
- delta -= amount;
- old_count = end_count;
- new_count = end_count;
- if (delta <= 0.0f) {
- break;
- }
- new_count += delta;
- if (new_count < start_count) {
- break;
- }
- CallCallbacks(old_count, start_count, queue);
- direction = !direction;
- amount = start_count - old_count;
- delta -= amount;
- old_count = start_count;
- new_count = start_count;
- }
- set_forward(direction);
- break;
- }
- case Counter::CONTINUOUS:
- default:
- break;
- }
- CallCallbacks(old_count, new_count, queue);
- set_count(new_count);
- } else if (delta < 0.0f) {
- switch (mode) {
- case Counter::ONCE: {
- if (new_count >= start_count) {
- new_count = start_count;
- set_running(false);
- }
- break;
- }
- case Counter::CYCLE: {
- while (new_count >= start_count) {
- CallCallbacks(old_count, start_count, queue);
- old_count = end_count;
- new_count -= period;
- }
- break;
- }
- case Counter::OSCILLATE: {
- while (delta < 0.0f) {
- new_count = old_count - delta;
- if (new_count < start_count) {
- break;
- }
- CallCallbacks(old_count, start_count, queue);
- direction = !direction;
- float amount = start_count - old_count;
- delta += amount;
- old_count = start_count;
- new_count = start_count;
- if (delta >= 0.0f) {
- break;
- }
- new_count += delta;
- if (new_count > end_count) {
- break;
- }
- CallCallbacks(old_count, end_count, queue);
- direction = !direction;
- amount = old_count - end_count;
- delta += amount;
- old_count = end_count;
- new_count = end_count;
- }
- set_forward(direction);
- break;
- }
- case Counter::CONTINUOUS:
- default:
- break;
- }
- CallCallbacks(old_count, new_count, queue);
- set_count(new_count);
- }
- }
- }
-}
-
-void Counter::CallCallbacks(float start_count,
- float end_count,
- CounterCallbackQueue* queue) {
- DCHECK(queue != NULL);
-
- if (end_count > start_count) {
- // Going forward.
- // If next_callback is not valid, find the first possible callback.
- if (!next_callback_valid_ ||
- start_count != last_call_callbacks_end_count_) {
- next_callback_ = callbacks_.begin();
- while (next_callback_ != callbacks_.end() &&
- next_callback_->count() < start_count) {
- ++next_callback_;
- }
- }
-
- // add callbacks until we get to some callback past end_count.
- while (next_callback_ != callbacks_.end()) {
- if (next_callback_->count() > end_count) {
- break;
- }
- queue->QueueCounterCallback(next_callback_->callback_manager());
- ++next_callback_;
- }
- next_callback_valid_ = true;
- prev_callback_valid_ = false;
- last_call_callbacks_end_count_ = end_count;
- } else if (end_count < start_count) {
- // Going backward.
- // If prev_callback is not valid, find the first possible callback.
- if (!prev_callback_valid_ ||
- start_count != last_call_callbacks_end_count_) {
- prev_callback_ = callbacks_.rbegin();
- while (prev_callback_ != callbacks_.rend() &&
- prev_callback_->count() > start_count) {
- ++prev_callback_;
- }
- }
-
- // add callbacks until we get to some callback past end_count.
- while (prev_callback_ != callbacks_.rend()) {
- if (prev_callback_->count() < end_count) {
- break;
- }
- queue->QueueCounterCallback(prev_callback_->callback_manager());
- ++prev_callback_;
- }
-
- prev_callback_valid_ = true;
- next_callback_valid_ = false;
- last_call_callbacks_end_count_ = end_count;
- }
-}
-
-void Counter::AddCallback(float count, CounterCallback* callback) {
- next_callback_valid_ = false;
- prev_callback_valid_ = false;
- CounterCallbackManager* manager;
-
- {
- CallbackManagerMap::iterator iter = callback_managers_.find(callback);
- if (iter != callback_managers_.end()) {
- manager = iter->second;
- } else {
- manager = new CounterCallbackManager(this, callback);
- }
- }
-
- {
- CounterCallbackInfoArray::iterator end(callbacks_.end());
- CounterCallbackInfoArray::iterator iter(callbacks_.begin());
- while (iter != end) {
- if (iter->count() == count) {
- iter->set_callback_manager(manager);
- return;
- } else if (iter->count() > count) {
- break;
- }
- ++iter;
- }
- callbacks_.insert(iter, CounterCallbackInfo(count, manager));
- }
-}
-
-bool Counter::RemoveCallback(float count) {
- CounterCallbackInfoArray::iterator end(callbacks_.end());
- for (CounterCallbackInfoArray::iterator iter(callbacks_.begin());
- iter != end;
- ++iter) {
- if (iter->count() == count) {
- next_callback_valid_ = false;
- prev_callback_valid_ = false;
- callbacks_.erase(iter);
- return true;
- }
- }
- return false;
-}
-
-void Counter::RemoveAllCallbacks() {
- callbacks_.clear();
- next_callback_valid_ = false;
- prev_callback_valid_ = false;
-}
-
-void Counter::RegisterCallbackManager(
- Counter::CounterCallbackManager* manager) {
- DCHECK(callback_managers_.find(manager->callback()) ==
- callback_managers_.end());
- callback_managers_.insert(std::make_pair(manager->callback(), manager));
-}
-
-void Counter::UnregisterCallbackManager(
- Counter::CounterCallbackManager* manager) {
- CallbackManagerMap::iterator iter = callback_managers_.find(
- manager->callback());
- DCHECK(iter != callback_managers_.end());
- callback_managers_.erase(iter);
-}
-
-ObjectBase::Ref Counter::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new Counter(service_locator));
-}
-
-void Counter::CounterCallbackQueue::CallCounterCallbacks() {
- // call all the queued callbacks.
- for (unsigned ii = 0; ii < counter_callbacks_.size(); ++ii) {
- counter_callbacks_[ii]->Run();
- }
- counter_callbacks_.clear();
-}
-
-void Counter::CounterCallbackQueue::QueueCounterCallback(
- CounterCallbackManager* callback_manager) {
- counter_callbacks_.push_back(CounterCallbackManager::Ref(callback_manager));
-}
-
-Counter::CounterCallbackManager::CounterCallbackManager(Counter* counter,
- ClosureType* closure)
- : counter_(counter),
- closure_(closure),
- called_(false) {
- DCHECK(counter != NULL);
- DCHECK(closure != NULL);
- counter_->RegisterCallbackManager(this);
-}
-
-Counter::CounterCallbackManager::~CounterCallbackManager() {
- counter_->UnregisterCallbackManager(this);
- delete closure_;
-}
-
-// Runs the closure if one is currently set and if it is not already inside a
-// previous call.
-void Counter::CounterCallbackManager::Run() const {
- if (!called_) {
- called_ = true;
- closure_->Run();
- called_ = false;
- }
-}
-
-// Second Counter ------------------------
-
-SecondCounter::SecondCounter(ServiceLocator* service_locator)
- : Counter(service_locator) {
- CounterManager* counter_manager =
- service_locator->GetService<CounterManager>();
- DCHECK(counter_manager);
- counter_manager->RegisterSecondCounter(this);
-}
-
-SecondCounter::~SecondCounter() {
- CounterManager* counter_manager =
- service_locator()->GetService<CounterManager>();
- DCHECK(counter_manager);
- counter_manager->UnregisterSecondCounter(this);
-}
-
-ObjectBase::Ref SecondCounter::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new SecondCounter(service_locator));
-}
-
-// Render Frame Counter ------------------------
-
-RenderFrameCounter::RenderFrameCounter(ServiceLocator* service_locator)
- : Counter(service_locator) {
- CounterManager* counter_manager =
- service_locator->GetService<CounterManager>();
- DCHECK(counter_manager);
- counter_manager->RegisterRenderFrameCounter(this);
-}
-
-RenderFrameCounter::~RenderFrameCounter() {
- CounterManager* counter_manager =
- service_locator()->GetService<CounterManager>();
- DCHECK(counter_manager);
- counter_manager->UnregisterRenderFrameCounter(this);
-}
-
-ObjectBase::Ref RenderFrameCounter::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new RenderFrameCounter(service_locator));
-}
-
-// Tick Counter ------------------------
-
-TickCounter::TickCounter(ServiceLocator* service_locator)
- : Counter(service_locator) {
- CounterManager* counter_manager =
- service_locator->GetService<CounterManager>();
- DCHECK(counter_manager);
- counter_manager->RegisterTickCounter(this);
-}
-
-TickCounter::~TickCounter() {
- CounterManager* counter_manager =
- service_locator()->GetService<CounterManager>();
- DCHECK(counter_manager);
- counter_manager->UnregisterTickCounter(this);
-}
-
-ObjectBase::Ref TickCounter::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new TickCounter(service_locator));
-}
-} // namespace o3d
diff --git a/o3d/core/cross/counter.h b/o3d/core/cross/counter.h
deleted file mode 100644
index 9faea11..0000000
--- a/o3d/core/cross/counter.h
+++ /dev/null
@@ -1,402 +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 declarations of Counter related classes
-
-#ifndef O3D_CORE_CROSS_COUNTER_H_
-#define O3D_CORE_CROSS_COUNTER_H_
-
-#include <map>
-#include <vector>
-#include "core/cross/callback.h"
-#include "core/cross/param_object.h"
-#include "core/cross/pack.h"
-
-namespace o3d {
-
-class Counter : public ParamObject {
- public:
- virtual ~Counter();
-
- // Manages a closure so it can not be called recursively. The manager takes
- // ownership of the closure.
- class CounterCallbackManager : public RefCounted {
- public:
- typedef SmartPointer<CounterCallbackManager> Ref;
- typedef Closure ClosureType;
-
- CounterCallbackManager(Counter* counter, ClosureType* closure);
- ~CounterCallbackManager();
-
- // Runs the closure if it is not already inside a previous call.
- void Run() const;
-
- ClosureType* callback() const {
- return closure_;
- }
-
- private:
- Counter* counter_;
- ClosureType* closure_;
- mutable bool called_;
- };
-
- typedef CounterCallbackManager::ClosureType CounterCallback;
-
- // A class to associate a count with a callback.
- class CounterCallbackInfo {
- public:
- CounterCallbackInfo(float count, CounterCallbackManager* manager)
- : count_(count),
- callback_manager_(CounterCallbackManager::Ref(manager)) {
- }
-
- inline float count() const {
- return count_;
- }
-
- inline CounterCallbackManager* callback_manager() const {
- return callback_manager_;
- }
-
- inline void set_callback_manager(CounterCallbackManager* manager) {
- callback_manager_ = CounterCallbackManager::Ref(manager);
- }
-
- private:
- float count_;
- CounterCallbackManager::Ref callback_manager_;
- };
-
- typedef std::vector<CounterCallbackInfo> CounterCallbackInfoArray;
-
- // A class for queuing counter callbacks and then calling them.
- class CounterCallbackQueue {
- public:
- CounterCallbackQueue() { }
-
- // Queue a counter callback. This is an internal function only called by
- // class Counter. Because a callback could effect structures in the client
- // we must not call them while walking any of those structures so Counter
- // adds all the callbacks that need calling through this method and the
- // client calls them all at the appropriate time.
- // Parameters:
- // callback_manager: callback manager to queue.
- void QueueCounterCallback(CounterCallbackManager* callback_manager);
-
- // Calls all the queue callbacks and clears the queue. This is an internal
- // function.
- void CallCounterCallbacks();
-
- private:
- // Counter callback managers.
- typedef std::vector<CounterCallbackManager::Ref>
- CounterCallbackManagerArray;
- CounterCallbackManagerArray counter_callbacks_;
-
- DISALLOW_COPY_AND_ASSIGN(CounterCallbackQueue);
- };
-
- static const char* kRunningParamName;
- static const char* kForwardParamName;
- static const char* kCountModeParamName;
- static const char* kStartParamName;
- static const char* kEndParamName;
- static const char* kCountParamName;
- static const char* kMultiplierParamName;
-
- enum CountMode {
- CONTINUOUS, // Keep running the counter forever.
- ONCE, // Stop at start or end depending on the time.
- CYCLE, // When at end, jump back to start.
- OSCILLATE, // Go from start to end back to start.
- };
-
- // Updates the counter. This is an internal function called by the client.
- // Parameters:
- // advance_amount: How much to advance the counter. For a SecondCounter
- // this will be the number of seconds since the last call to Advance,
- // For a RenderFrameCounter or TickCounter this will always be 1.0
- // queue: queue to hold any callbacks that need to be called because of
- // advance.
- void Advance(float advance_amount, CounterCallbackQueue* queue);
-
- // Resets the counter to start or end depending on the current direction. Note
- // that resetting a counter does not Stop it. If you want to both reset and
- // stop an counter call Stop() then call Reset().
- void Reset();
-
- // Gets the running state.
- bool running() {
- return running_param_->value();
- }
-
- // Sets the running state.
- void set_running(bool running) {
- running_param_->set_value(running);
- }
-
- // Gets the forward setting. Whether the counter is counting forward or back.
- bool forward() {
- return forward_param_->value();
- }
-
- // Sets the forward setting.
- void set_forward(bool forward) {
- forward_param_->set_value(forward);
- }
-
- // Gets the count_mode.
- CountMode count_mode() {
- return static_cast<CountMode>(count_mode_param_->value());
- }
-
- // Sets the count_mode.
- void set_count_mode(CountMode count_mode) {
- count_mode_param_->set_value(count_mode);
- }
-
- // Gets the current count.
- float count() const {
- return count_param_->value();
- }
-
- // Sets the current count value for this counter as well as resetting the
- // state of the callbacks.
- //
- // In other words. Assume start = 1, end = 5, count = 1, and you have a
- // callback at 3.
- //
- // myCounter->set_start(1.0f);
- // myCounter->set_end(5.0f);
- // myCounter->AddCallback(3.0f, myCallback);
- // myCounter->Reset();
- //
- // myCounter->Advance(2.0f, &queue); // count is now 3, myCallback is queued.
- // myCounter->Advance(2.0f, &queue); // count is now 5
- //
- // vs.
- //
- // myCounter->set_start(1.f);
- // myCounter->set_end(5.f);
- // myCounter->AddCallback(3.f, myCallback);
- // myCounter->Reset();
- //
- // myCounter->Advance(2.f, &queue); // count is now 3, myCallback is queued.
- // myCounter->SetCount(3.f); // count is now 3, callback state has been reset.
- // myCounter->advance(2.f, &queue); // count is now 5, myCallback is queued.
- //
- // In the second case myCallback was queued twice.
- //
- // Parameters:
- // count: Value to set the count to.
- void SetCount(float value);
-
- // Gets the start count.
- float start() const {
- return start_param_->value();
- }
-
- // Sets the start count.
- void set_start(float start) {
- start_param_->set_value(start);
- }
-
- // Gets the end count.
- float end() const {
- return end_param_->value();
- }
-
- // Sets the end count.
- void set_end(float end) {
- end_param_->set_value(end);
- }
-
- // Gets the multiplier
- float multiplier() {
- return multiplier_param_->value();
- }
-
- // Sets the multiplier.
- void set_multiplier(float multiplier) {
- multiplier_param_->set_value(multiplier);
- }
-
- // Adds a callback that will be called when the counter
- // reaches a certain count. If a callback is already registered for that
- // particular count it will be removed.
- //
- // NOTE: A callback at start will only get called when counting backward, a
- // callback at end will only get called counting forward.
- //
- // NOTE: The client takes ownership of the Callback you pass in. It will be
- // deleted if you call AddCallback for the same count or RemoveCallback for
- // the same count.
- //
- // Parameters:
- // count: count at which callback will be called.
- // callback: callback to call.
- void AddCallback(float count, CounterCallback* callback);
-
- // Removes a callback at a particular count.
- // Parameters:
- // count: count to remove callback at.
- // Returns:
- // true of there was a callback at that count to remove.
- bool RemoveCallback(float count);
-
- // Removes all the callbacks on this counter.
- void RemoveAllCallbacks();
-
- // Returns the callbacks.
- const CounterCallbackInfoArray& GetCallbacks() const {
- return callbacks_;
- }
-
- protected:
- explicit Counter(ServiceLocator* service_locator);
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // Calls the callbacks in the range start_count to end_count. start_count is
- // NOT included in callback check, end_count is.
- // Parameters:
- // start_count: non-inclusive start count.
- // end_count: inclusive end count.
- // queue: queue to hold any callbacks that need to be called.
- void CallCallbacks(float start_count,
- float end_count,
- CounterCallbackQueue* queue);
-
- // Finds a callback by count.
- // Parameters:
- // count: count to find.
- // Returns:
- // Iterator to callbackInfo
- CounterCallbackInfoArray::iterator FindCallback(float count);
-
- // Registers a callback manager. This is an internal function called only
- // by CounterCallbackManager's constructor.
- // Parameters:
- // manager: manager to register.
- void RegisterCallbackManager(CounterCallbackManager* manager);
-
- // Unregisters a callback manager. This is an internal function called only by
- // CounterCallbackManager's constructor.
- // Parameters:
- // manager: manager to unregister.
- void UnregisterCallbackManager(CounterCallbackManager* manager);
-
- // Sets the current count directly, not changing any thing but the count.
- void set_count(float count) {
- count_param_->set_value(count);
- }
-
- ParamBoolean::Ref running_param_;
- ParamBoolean::Ref forward_param_;
- ParamInteger::Ref count_mode_param_;
- ParamFloat::Ref start_param_;
- ParamFloat::Ref end_param_;
- ParamFloat::Ref count_param_;
- ParamFloat::Ref multiplier_param_;
-
- // Points to the next callback in the current direction for this counter.
- // In other words if there are callbacks at times 10, 27 and 34 and the count
- // is at 21 and this counter is going forward then this would be pointing to
- // the callback at 27.
- CounterCallbackInfoArray::iterator next_callback_;
- CounterCallbackInfoArray::reverse_iterator prev_callback_;
-
- // false if the next_callback_ is valid (points to something real)
- bool next_callback_valid_;
-
- // false if the prev_callback_ is valid (points to something real)
- bool prev_callback_valid_;
-
- // last end count passed to CallCallbacks.
- float last_call_callbacks_end_count_;
-
- // Array of counts to callbacks.
- CounterCallbackInfoArray callbacks_;
-
- // Map fo callbacks to callback managers.
- typedef std::map<CounterCallback*,
- CounterCallbackManager*> CallbackManagerMap;
- CallbackManagerMap callback_managers_;
-
- O3D_DECL_CLASS(Counter, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(Counter);
-};
-
-// A Second counter counts by elasped time.
-class SecondCounter : public Counter {
- public:
- explicit SecondCounter(ServiceLocator* service_locator);
- virtual ~SecondCounter();
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(SecondCounter, Counter);
- DISALLOW_COPY_AND_ASSIGN(SecondCounter);
-};
-
-// A Render Frame counter counts by render frames.
-class RenderFrameCounter : public Counter {
- public:
- explicit RenderFrameCounter(ServiceLocator* service_locator);
- virtual ~RenderFrameCounter();
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(RenderFrameCounter, Counter);
- DISALLOW_COPY_AND_ASSIGN(RenderFrameCounter);
-};
-
-// A tick counter counts by ticks.
-class TickCounter : public Counter {
- public:
- explicit TickCounter(ServiceLocator* service_locator);
- virtual ~TickCounter();
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(TickCounter, Counter);
- DISALLOW_COPY_AND_ASSIGN(TickCounter);
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_COUNTER_H_
diff --git a/o3d/core/cross/counter_manager.cc b/o3d/core/cross/counter_manager.cc
deleted file mode 100644
index 6bfe400..0000000
--- a/o3d/core/cross/counter_manager.cc
+++ /dev/null
@@ -1,142 +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 "core/cross/counter_manager.h"
-#include "core/cross/counter.h"
-
-namespace o3d {
-
-const InterfaceId CounterManager::kInterfaceId =
- InterfaceTraits<CounterManager>::kInterfaceId;
-
-CounterManager::CounterManager(ServiceLocator* service_locator)
- : service_(service_locator, this),
- profiler_(service_locator) {
-}
-
-void CounterManager::RegisterSecondCounter(SecondCounter* counter) {
- DCHECK(std::find(second_counters_.begin(),
- second_counters_.end(),
- counter) == second_counters_.end());
- second_counters_.push_back(counter);
-}
-
-void CounterManager::UnregisterSecondCounter(SecondCounter* counter) {
- SecondCounterArray::iterator last = std::remove(second_counters_.begin(),
- second_counters_.end(),
- counter);
- DCHECK(last != second_counters_.end());
- second_counters_.erase(last, second_counters_.end());
-}
-
-void CounterManager::RegisterTickCounter(TickCounter* counter) {
- DCHECK(std::find(tick_counters_.begin(),
- tick_counters_.end(),
- counter) == tick_counters_.end());
- tick_counters_.push_back(counter);
-}
-
-void CounterManager::UnregisterTickCounter(TickCounter* counter) {
- TickCounterArray::iterator last = std::remove(tick_counters_.begin(),
- tick_counters_.end(),
- counter);
- DCHECK(last != tick_counters_.end());
- tick_counters_.erase(last, tick_counters_.end());
-}
-
-void CounterManager::RegisterRenderFrameCounter(RenderFrameCounter* counter) {
- DCHECK(std::find(render_frame_counters_.begin(),
- render_frame_counters_.end(),
- counter) == render_frame_counters_.end());
- render_frame_counters_.push_back(counter);
-}
-
-void CounterManager::UnregisterRenderFrameCounter(RenderFrameCounter* counter) {
- RenderFrameCounterArray::iterator last =
- std::remove(render_frame_counters_.begin(),
- render_frame_counters_.end(),
- counter);
- DCHECK(last != render_frame_counters_.end());
- render_frame_counters_.erase(last, render_frame_counters_.end());
-}
-
-void CounterManager::AdvanceCounters(float advance_amount,
- float seconds_elapsed) {
- Counter::CounterCallbackQueue queue;
-
- // Update any tick counters.
- for (unsigned ii = 0; ii < tick_counters_.size(); ++ii) {
- if (tick_counters_[ii]->running()) {
- tick_counters_[ii]->Advance(advance_amount, &queue);
- }
- }
-
- // Update any second counters.
- for (unsigned ii = 0; ii < second_counters_.size(); ++ii) {
- if (second_counters_[ii]->running()) {
- second_counters_[ii]->Advance(seconds_elapsed, &queue);
- }
- }
-
- profiler_->ProfileStart("Tick Counter callbacks");
- queue.CallCounterCallbacks();
- profiler_->ProfileStop("Tick Counter callbacks");
-}
-
-void CounterManager::AdvanceRenderFrameCounters(float advance_amnount) {
- Counter::CounterCallbackQueue queue;
-
- // Update any render frame counters.
- for (unsigned ii = 0; ii < render_frame_counters_.size(); ++ii) {
- if (render_frame_counters_[ii]->running()) {
- render_frame_counters_[ii]->Advance(advance_amnount, &queue);
- }
- }
-
- profiler_->ProfileStart("PrepareForFrame Counter callbacks");
- queue.CallCounterCallbacks();
- profiler_->ProfileStop("PrepareForFrame Counter callbacks");
-}
-
-void CounterManager::ClearAllCallbacks() {
- for (unsigned ii = 0; ii < tick_counters_.size(); ++ii) {
- tick_counters_[ii]->RemoveAllCallbacks();
- }
- for (unsigned ii = 0; ii < render_frame_counters_.size(); ++ii) {
- render_frame_counters_[ii]->RemoveAllCallbacks();
- }
- for (unsigned ii = 0; ii < second_counters_.size(); ++ii) {
- second_counters_[ii]->RemoveAllCallbacks();
- }
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/counter_manager.h b/o3d/core/cross/counter_manager.h
deleted file mode 100644
index eb38f1d..0000000
--- a/o3d/core/cross/counter_manager.h
+++ /dev/null
@@ -1,126 +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_CORE_CROSS_COUNTER_MANAGER_H_
-#define O3D_CORE_CROSS_COUNTER_MANAGER_H_
-
-#include <vector>
-
-#include "base/basictypes.h"
-#include "core/cross/profiler.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/service_implementation.h"
-
-namespace o3d {
-
-class SecondCounter;
-class TickCounter;
-class RenderFrameCounter;
-
-// Registry for the various kinds of Counter. Can register and unregister
-// counters and advance all registered counters.
-class CounterManager {
- public:
- static const InterfaceId kInterfaceId;
-
- explicit CounterManager(ServiceLocator* service_locator);
-
- // Registers a second counter with the client. This is an internal function
- // only called by SecondCounter's constructor.
- // Parameters:
- // counter: The SecondCounter to register.
- void RegisterSecondCounter(SecondCounter* counter);
-
- // Unregisters a second counter with the client. This is an internal function
- // only called by SecondCounter's destructor.
- // Parameters:
- // counter: The SecondCounter to unregister.
- void UnregisterSecondCounter(SecondCounter* counter);
-
- // Registers a tick counter with the client. This is an internal function
- // only called by TickCounter's constructor.
- // Parameters:
- // counter: The TickCounter to register.
- void RegisterTickCounter(TickCounter* counter);
-
- // Unregisters a tick counter with the client. This is an internal function
- // only called by TickCounter's destructor.
- // Parameters:
- // counter: The TickCounter to unregister.
- void UnregisterTickCounter(TickCounter* counter);
-
- // Registers a render frame counter with the client. This is an internal
- // function only called by RenderFrameCounter's constructor.
- // Parameters:
- // counter: The RenderFrameCounter to register.
- void RegisterRenderFrameCounter(RenderFrameCounter* counter);
-
- // Unregisters a render frame counter with the client. This is an internal
- // function only called by RenderFrameCounter's destructor.
- // Parameters:
- // counter: The RenderFrameCounter to unregister.
- void UnregisterRenderFrameCounter(RenderFrameCounter* counter);
-
- // Advance the registered TickCounters by advance_amount and the
- // SecondCounters by seconds_elapsed, invoking their Advance functions
- // and any callbacks they enqueue as they run.
- void AdvanceCounters(float advance_amount, float seconds_elapsed);
-
- // Advance the RenderFrameCounters by the advance_amount, invoking their
- // Advance functions and any callbacks they enqueue.
- void AdvanceRenderFrameCounters(float advance_amount);
-
- // Clears the callbacks on all counters registered in the
- // CallbackManager. This needs to be called by Client::Cleanup
- // so that these callbacks do not get called after the page
- // has unloaded.
- void ClearAllCallbacks();
-
- private:
- ServiceImplementation<CounterManager> service_;
- ServiceDependency<Profiler> profiler_;
-
- // Render frame counters registed with this client.
- typedef std::vector<RenderFrameCounter*> RenderFrameCounterArray;
- RenderFrameCounterArray render_frame_counters_;
-
- // Second counters registed with this client.
- typedef std::vector<SecondCounter*> SecondCounterArray;
- SecondCounterArray second_counters_;
-
- // Tick counters registed with this client.
- typedef std::vector<TickCounter*> TickCounterArray;
- TickCounterArray tick_counters_;
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_COUNTER_MANAGER_H_
diff --git a/o3d/core/cross/counter_test.cc b/o3d/core/cross/counter_test.cc
deleted file mode 100644
index 814328a..0000000
--- a/o3d/core/cross/counter_test.cc
+++ /dev/null
@@ -1,652 +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 implements unit tests for class Counter.
-
-#include "core/cross/client.h"
-#include "tests/common/win/testing_common.h"
-#include "core/cross/counter.h"
-#include "core/cross/timer.h"
-
-namespace o3d {
-
-class CounterTest : public testing::Test {
- protected:
-
- CounterTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- CounterManager* counter_manager() { return counter_manager_; }
- Pack* pack() { return pack_; }
-
- private:
-
- ServiceDependency<ObjectManager> object_manager_;
- CounterManager *counter_manager_;
- Pack* pack_;
-};
-
-void CounterTest::SetUp() {
- counter_manager_ = new CounterManager(g_service_locator);
- pack_ = object_manager_->CreatePack();
-}
-
-void CounterTest::TearDown() {
- pack_->Destroy();
- delete counter_manager_;
-}
-
-// Tests the creation of a Counter.
-TEST_F(CounterTest, Basic) {
- Counter* counter = pack()->Create<Counter>();
- ASSERT_TRUE(counter != NULL);
-
- // Check that its default params got created.
- EXPECT_TRUE(
- counter->GetParam<ParamBoolean>(Counter::kRunningParamName) != NULL);
- EXPECT_TRUE(
- counter->GetParam<ParamBoolean>(Counter::kForwardParamName) != NULL);
- EXPECT_TRUE(
- counter->GetParam<ParamInteger>(Counter::kCountModeParamName) != NULL);
- EXPECT_TRUE(
- counter->GetParam<ParamFloat>(Counter::kStartParamName) != NULL);
- EXPECT_TRUE(
- counter->GetParam<ParamFloat>(Counter::kEndParamName) != NULL);
- EXPECT_TRUE(
- counter->GetParam<ParamFloat>(Counter::kCountParamName) != NULL);
- EXPECT_TRUE(
- counter->GetParam<ParamFloat>(Counter::kMultiplierParamName) != NULL);
-
- // Check that the defaults are correct
- EXPECT_EQ(counter->forward(), true);
- EXPECT_EQ(counter->running(), true);
- EXPECT_EQ(counter->count_mode(), Counter::CONTINUOUS);
- EXPECT_EQ(counter->count(), 0.0f);
- EXPECT_EQ(counter->start(), 0.0f);
- EXPECT_EQ(counter->end(), 0.0f);
- EXPECT_EQ(counter->multiplier(), 1.0f);
-}
-
-// Tests Counter::Advance
-TEST_F(CounterTest, Advance) {
- Counter* counter = pack()->Create<Counter>();
- ASSERT_TRUE(counter != NULL);
- Counter::CounterCallbackQueue queue;
-
- counter->set_start(1.0f);
- counter->set_end(5.0f);
- counter->Reset();
-
- // See that it advances.
- EXPECT_EQ(counter->count(), 1.0f);
- counter->Advance(1.0f, &queue);
- EXPECT_EQ(counter->count(), 2.0f);
-
- // See that forward works.
- counter->set_forward(false);
- counter->Advance(1.0f, &queue);
- EXPECT_EQ(counter->count(), 1.0f);
- counter->set_forward(true);
-
- // Check that CONTINUOUS works.
- counter->Advance(10.0f, &queue);
- EXPECT_EQ(counter->count(), 11.0f);
- // Check backward as well.
- counter->Advance(-20.0f, &queue);
- EXPECT_EQ(counter->count(), -9.0f);
-
- // Check that ONCE works.
- counter->Reset();
- counter->set_running(true);
- counter->set_count_mode(Counter::ONCE);
- counter->Advance(10.0f, &queue);
- EXPECT_EQ(counter->count(), counter->end());
- EXPECT_EQ(counter->running(), false);
- // Check backward as well.
- counter->set_running(true);
- counter->Advance(-10.0f, &queue);
- EXPECT_EQ(counter->count(), counter->start());
- EXPECT_EQ(counter->running(), false);
- // Check bounds end.
- counter->SetCount(counter->end());
- counter->set_running(true);
- counter->Advance(1.0f, &queue);
- EXPECT_EQ(counter->count(), counter->end());
- EXPECT_EQ(counter->running(), false);
- // Check bounds start
- counter->SetCount(counter->start());
- counter->set_running(true);
- counter->Advance(-1.0f, &queue);
- EXPECT_EQ(counter->count(), counter->start());
- EXPECT_EQ(counter->running(), false);
-
- // Check that CYCLE works.
- counter->Reset();
- counter->set_count_mode(Counter::CYCLE);
- counter->Advance(4.0f, &queue);
- EXPECT_EQ(counter->count(), counter->start());
- counter->Advance(5.0f, &queue);
- EXPECT_EQ(counter->count(), counter->start() + 1.0f);
- counter->Advance(-4.0f, &queue);
- EXPECT_EQ(counter->count(), counter->start() + 1.0f);
-
- // Check that OSCILLATE works.
- counter->Reset();
- counter->set_count_mode(Counter::OSCILLATE);
- counter->Advance(5.0f, &queue);
- EXPECT_EQ(counter->count(), counter->start() + 3.0f);
- EXPECT_EQ(counter->forward(), false);
- counter->Advance(4.0f, &queue);
- EXPECT_EQ(counter->count(), counter->start() + 1.0f);
- EXPECT_EQ(counter->forward(), true);
- counter->Advance(-3.0f, &queue);
- EXPECT_EQ(counter->count(), counter->start() + 2.0f);
- EXPECT_EQ(counter->forward(), false);
- counter->Advance(-4.0f, &queue);
- EXPECT_EQ(counter->count(), counter->start() + 2.0f);
- EXPECT_EQ(counter->forward(), true);
-}
-
-// Tests Counter::Reset
-TEST_F(CounterTest, Reset) {
- Counter* counter = pack()->Create<SecondCounter>();
- ASSERT_TRUE(counter != NULL);
-
- counter->set_start(20.0f);
- counter->set_end(40.0f);
- EXPECT_EQ(counter->count(), 0.0f);
- counter->Reset();
- EXPECT_EQ(counter->count(), 20.0f);
- counter->set_forward(false);
- counter->Reset();
- EXPECT_EQ(counter->count(), 40.0f);
-}
-
-namespace {
-
-// A CounterCallback that tracks how many times it has been called
-// and whether or not it has been deleted.
-class TestCounterCallback : public Counter::CounterCallback {
- public:
- explicit TestCounterCallback(bool* deleted)
- : call_count_(0),
- deleted_(deleted) {
- *deleted_ = false;
- }
-
- ~TestCounterCallback() {
- *deleted_ = true;
- }
-
- virtual void Run() {
- ++call_count_;
- }
-
- int call_count() {
- return call_count_;
- }
-
- void Reset() {
- call_count_ = 0;
- }
-
- private:
- int call_count_; // number of times this callback was called.
- bool* deleted_; // pointer to bool to get set to true when deleted.
-
- DISALLOW_COPY_AND_ASSIGN(TestCounterCallback);
-};
-
-} // anonymous namespace
-
-// Tests Counter::AddCallback/RemoveCallback
-TEST_F(CounterTest, AddRemoveGetCallback) {
- Counter* counter = pack()->Create<Counter>();
- ASSERT_TRUE(counter != NULL);
-
- const Counter::CounterCallbackInfoArray& counters = counter->GetCallbacks();
- Counter::CounterCallbackInfoArray::const_iterator iter;
-
- bool test1_deleted;
- bool test2_deleted;
- TestCounterCallback* test1 = new TestCounterCallback(&test1_deleted);
- TestCounterCallback* test2 = new TestCounterCallback(&test2_deleted);
- ASSERT_TRUE(test1 != NULL);
- ASSERT_TRUE(test2 != NULL);
- ASSERT_FALSE(test1_deleted);
- ASSERT_FALSE(test2_deleted);
-
- // Testing Adding
- counter->AddCallback(2.0f, test2);
- counter->AddCallback(1.0f, test1);
- // Check that both got added.
- ASSERT_EQ(counters.size(), 2U);
- iter = counters.begin();
- EXPECT_EQ(iter->count(), 1.0f);
- ++iter;
- EXPECT_EQ(iter->count(), 2.0f);
-
- // Check that adding one at the same time removes the other
- counter->AddCallback(2.0f, test1);
- EXPECT_TRUE(test2_deleted);
- ASSERT_EQ(counters.size(), 2U);
-
- // Check that removing a non-existant callback fails.
- EXPECT_FALSE(counter->RemoveCallback(3.0f));
-
- // Check that removing one of the duplicated callbacks does not remove the
- // other.
- EXPECT_TRUE(counter->RemoveCallback(1.0f));
- ASSERT_EQ(counters.size(), 1U);
- EXPECT_FALSE(test1_deleted);
-
- // Check that removing final callback deletes the callback.
- EXPECT_TRUE(counter->RemoveCallback(2.0f));
- ASSERT_EQ(counters.size(), 0U);
- EXPECT_TRUE(test1_deleted);
- EXPECT_FALSE(counter->RemoveCallback(2.0f));
-
- // Check that callbacks get called correct number of times.
- test1 = new TestCounterCallback(&test1_deleted);
- test2 = new TestCounterCallback(&test2_deleted);
- bool test3_deleted;
- bool test4_deleted;
- bool test5_deleted;
- TestCounterCallback* test3 = new TestCounterCallback(&test3_deleted);
- TestCounterCallback* test4 = new TestCounterCallback(&test4_deleted);
- TestCounterCallback* test5 = new TestCounterCallback(&test5_deleted);
- ASSERT_TRUE(test1 != NULL);
- ASSERT_TRUE(test2 != NULL);
- ASSERT_FALSE(test1_deleted);
- ASSERT_FALSE(test2_deleted);
- counter->set_start(1.0f);
- counter->set_end(5.0f);
- counter->AddCallback(0.0f, test1); // before start
- counter->AddCallback(1.0f, test2); // at start
- counter->AddCallback(2.0f, test3); // in between
- counter->AddCallback(5.0f, test4); // end end
- counter->AddCallback(6.0f, test5); // after end.
-
- Counter::CounterCallbackQueue queue;
-
- // Test CONTINUOUS
- counter->Reset();
- counter->Advance(0.0f, &queue); // At 1
- EXPECT_EQ(counter->count(), 1.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 0);
- EXPECT_EQ(test3->call_count(), 0);
- EXPECT_EQ(test4->call_count(), 0);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(1.0f, &queue); // At 2
- EXPECT_EQ(counter->count(), 2.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 1);
- EXPECT_EQ(test3->call_count(), 1);
- EXPECT_EQ(test4->call_count(), 0);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(3.0f, &queue); // At 5
- EXPECT_EQ(counter->count(), 5.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 1);
- EXPECT_EQ(test3->call_count(), 1);
- EXPECT_EQ(test4->call_count(), 1);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(3.0f, &queue); // At 8
- EXPECT_EQ(counter->count(), 8.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 1);
- EXPECT_EQ(test3->call_count(), 1);
- EXPECT_EQ(test4->call_count(), 1);
- EXPECT_EQ(test5->call_count(), 1);
- counter->Advance(-3.0f, &queue); // At 5
- EXPECT_EQ(counter->count(), 5.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 1);
- EXPECT_EQ(test3->call_count(), 1);
- EXPECT_EQ(test4->call_count(), 2);
- EXPECT_EQ(test5->call_count(), 2);
- counter->Advance(-3.0f, &queue); // At 2
- EXPECT_EQ(counter->count(), 2.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 1);
- EXPECT_EQ(test3->call_count(), 2);
- EXPECT_EQ(test4->call_count(), 2);
- EXPECT_EQ(test5->call_count(), 2);
- counter->Advance(-2.0f, &queue); // At 0
- EXPECT_EQ(counter->count(), 0.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 1);
- EXPECT_EQ(test2->call_count(), 2);
- EXPECT_EQ(test3->call_count(), 2);
- EXPECT_EQ(test4->call_count(), 2);
- EXPECT_EQ(test5->call_count(), 2);
-
- // Test ONCE
- test1->Reset();
- test2->Reset();
- test3->Reset();
- test4->Reset();
- test5->Reset();
- counter->Reset();
- counter->set_count_mode(Counter::ONCE);
- counter->Advance(0.0f, &queue); // At 1
- EXPECT_EQ(counter->count(), 1.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 0);
- EXPECT_EQ(test3->call_count(), 0);
- EXPECT_EQ(test4->call_count(), 0);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(10.0f, &queue); // At 5
- EXPECT_EQ(counter->count(), 5.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 1);
- EXPECT_EQ(test3->call_count(), 1);
- EXPECT_EQ(test4->call_count(), 1);
- EXPECT_EQ(test5->call_count(), 0);
- counter->set_forward(false);
- counter->Advance(10.0f, &queue); // At 1
- EXPECT_EQ(counter->count(), 1.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 2);
- EXPECT_EQ(test3->call_count(), 2);
- EXPECT_EQ(test4->call_count(), 2);
- EXPECT_EQ(test5->call_count(), 0);
-
- // Test CYCLE
- test1->Reset();
- test2->Reset();
- test3->Reset();
- test4->Reset();
- test5->Reset();
- counter->set_forward(true);
- counter->Reset();
- counter->set_count_mode(Counter::CYCLE);
- counter->Advance(4.0f, &queue); // At 1.0 (1 cycle)
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 1);
- EXPECT_EQ(test3->call_count(), 1);
- EXPECT_EQ(test4->call_count(), 1);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(22.0f, &queue); // At 3.0 (5 cycles + 2)
- EXPECT_EQ(counter->count(), 3.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 7);
- EXPECT_EQ(test3->call_count(), 7);
- EXPECT_EQ(test4->call_count(), 6);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(-21.0f, &queue); // At 2.0 (5 cycles + 1)
- EXPECT_EQ(counter->count(), 2.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 12);
- EXPECT_EQ(test3->call_count(), 13);
- EXPECT_EQ(test4->call_count(), 11);
- EXPECT_EQ(test5->call_count(), 0);
-
- // Test OSCILLATE
- test1->Reset();
- test2->Reset();
- test3->Reset();
- test4->Reset();
- test5->Reset();
- counter->Reset();
- counter->set_forward(true);
- counter->set_count_mode(Counter::OSCILLATE);
- counter->Advance(22.0f, &queue); // At 3.0 (5 cycles)
- EXPECT_EQ(counter->count(), 3.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 5);
- EXPECT_EQ(test3->call_count(), 5);
- EXPECT_EQ(test4->call_count(), 6);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(-21.0f, &queue); // At 2.0 (5 cycles)
- EXPECT_EQ(counter->count(), 2.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 9);
- EXPECT_EQ(test3->call_count(), 10);
- EXPECT_EQ(test4->call_count(), 12);
- EXPECT_EQ(test5->call_count(), 0);
-
- // Check start < end case ----------------------------
-
- counter->set_start(5.0f);
- counter->set_end(1.0f);
-
- // Test CONTINUOUS
- test1->Reset();
- test2->Reset();
- test3->Reset();
- test4->Reset();
- test5->Reset();
- counter->set_count_mode(Counter::CONTINUOUS);
- counter->Reset();
- counter->Advance(0.0f, &queue); // At 5
- EXPECT_EQ(counter->count(), 5.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 0);
- EXPECT_EQ(test3->call_count(), 0);
- EXPECT_EQ(test4->call_count(), 0);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(1.0f, &queue); // At 4
- EXPECT_EQ(counter->count(), 4.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 0);
- EXPECT_EQ(test3->call_count(), 0);
- EXPECT_EQ(test4->call_count(), 1);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(3.0f, &queue); // At 1
- EXPECT_EQ(counter->count(), 1.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 1);
- EXPECT_EQ(test3->call_count(), 1);
- EXPECT_EQ(test4->call_count(), 1);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(3.0f, &queue); // At -2
- EXPECT_EQ(counter->count(), -2.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 1);
- EXPECT_EQ(test2->call_count(), 1);
- EXPECT_EQ(test3->call_count(), 1);
- EXPECT_EQ(test4->call_count(), 1);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(-3.0f, &queue); // At 1
- EXPECT_EQ(counter->count(), 1.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 2);
- EXPECT_EQ(test2->call_count(), 2);
- EXPECT_EQ(test3->call_count(), 1);
- EXPECT_EQ(test4->call_count(), 1);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(-3.0f, &queue); // At 4
- EXPECT_EQ(counter->count(), 4.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 2);
- EXPECT_EQ(test2->call_count(), 2);
- EXPECT_EQ(test3->call_count(), 2);
- EXPECT_EQ(test4->call_count(), 1);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(-2.0f, &queue); // At 6
- EXPECT_EQ(counter->count(), 6.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 2);
- EXPECT_EQ(test2->call_count(), 2);
- EXPECT_EQ(test3->call_count(), 2);
- EXPECT_EQ(test4->call_count(), 2);
- EXPECT_EQ(test5->call_count(), 1);
-
- // Test ONCE
- test1->Reset();
- test2->Reset();
- test3->Reset();
- test4->Reset();
- test5->Reset();
- counter->Reset();
- counter->set_count_mode(Counter::ONCE);
- counter->Advance(0.0f, &queue); // At 5
- EXPECT_EQ(counter->count(), 5.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 0);
- EXPECT_EQ(test3->call_count(), 0);
- EXPECT_EQ(test4->call_count(), 0);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(10.0f, &queue); // At 1
- EXPECT_EQ(counter->count(), 1.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 1);
- EXPECT_EQ(test3->call_count(), 1);
- EXPECT_EQ(test4->call_count(), 1);
- EXPECT_EQ(test5->call_count(), 0);
- counter->set_forward(false);
- counter->Advance(10.0f, &queue); // At 5
- EXPECT_EQ(counter->count(), 5.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 2);
- EXPECT_EQ(test3->call_count(), 2);
- EXPECT_EQ(test4->call_count(), 2);
- EXPECT_EQ(test5->call_count(), 0);
-
- // Test CYCLE
- test1->Reset();
- test2->Reset();
- test3->Reset();
- test4->Reset();
- test5->Reset();
- counter->Reset();
- counter->set_forward(true);
- counter->set_count_mode(Counter::CYCLE);
- counter->Advance(22.0f, &queue); // At 3.0 (5 cycles + 2)
- EXPECT_EQ(counter->count(), 3.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 5);
- EXPECT_EQ(test3->call_count(), 5);
- EXPECT_EQ(test4->call_count(), 6);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(-21.0f, &queue); // At 4.0 (5 cycles + 1)
- EXPECT_EQ(counter->count(), 4.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 10);
- EXPECT_EQ(test3->call_count(), 10);
- EXPECT_EQ(test4->call_count(), 11);
- EXPECT_EQ(test5->call_count(), 0);
-
- // Test OSCILLATE
- test1->Reset();
- test2->Reset();
- test3->Reset();
- test4->Reset();
- test5->Reset();
- counter->Reset();
- counter->set_forward(true);
- counter->set_count_mode(Counter::OSCILLATE);
- counter->Advance(22.0f, &queue); // At 3.0 (5 cycles)
- EXPECT_EQ(counter->count(), 3.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 6);
- EXPECT_EQ(test3->call_count(), 6);
- EXPECT_EQ(test4->call_count(), 5);
- EXPECT_EQ(test5->call_count(), 0);
- counter->Advance(-21.0f, &queue); // At 4.0 (5 cycles)
- EXPECT_EQ(counter->count(), 4.0f);
- queue.CallCounterCallbacks();
- EXPECT_EQ(test1->call_count(), 0);
- EXPECT_EQ(test2->call_count(), 12);
- EXPECT_EQ(test3->call_count(), 12);
- EXPECT_EQ(test4->call_count(), 9);
- EXPECT_EQ(test5->call_count(), 0);
-
- // Check RemoveAllCallbacks.
- counter->RemoveAllCallbacks();
- EXPECT_EQ(counters.size(), 0U);
- EXPECT_TRUE(test1_deleted);
- EXPECT_TRUE(test2_deleted);
- EXPECT_TRUE(test3_deleted);
- EXPECT_TRUE(test4_deleted);
- EXPECT_TRUE(test5_deleted);
-}
-
-// Tests SecondCounter.
-TEST_F(CounterTest, SecondCounter) {
- SecondCounter* counter = pack()->Create<SecondCounter>();
- ASSERT_TRUE(counter != NULL);
-
- EXPECT_EQ(0.0f, counter->count());
- counter_manager()->AdvanceCounters(2.0f, 1.0f);
- EXPECT_EQ(1.0f, counter->count());
-}
-
-// Tests RenderFrameCounter.
-TEST_F(CounterTest, RenderFrameCounter) {
- RenderFrameCounter* counter = pack()->Create<RenderFrameCounter>();
- ASSERT_TRUE(counter != NULL);
-
- EXPECT_EQ(0.0f, counter->count());
- counter_manager()->AdvanceRenderFrameCounters(1.0f);
- EXPECT_EQ(1.0f, counter->count());
-}
-
-// Tests TickCounter.
-TEST_F(CounterTest, TickCounter) {
- TickCounter* counter = pack()->Create<TickCounter>();
- ASSERT_TRUE(counter != NULL);
-
- EXPECT_EQ(0.0f, counter->count());
- counter_manager()->AdvanceCounters(1.0f, 2.0f);
- EXPECT_EQ(1.0f, counter->count());
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/cursor.h b/o3d/core/cross/cursor.h
deleted file mode 100644
index fc0e4f8..0000000
--- a/o3d/core/cross/cursor.h
+++ /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.
- */
-
-
-// This file contains the declaration of the CursorType enumeration.
-
-#ifndef O3D_CORE_CROSS_CURSOR_H_
-#define O3D_CORE_CROSS_CURSOR_H_
-
-namespace o3d {
-
-namespace Cursor {
-
-// Defines the cursor tyoes.
-enum CursorType {
- DEFAULT,
- NONE,
- CROSSHAIR,
- POINTER,
- E_RESIZE,
- NE_RESIZE,
- NW_RESIZE,
- N_RESIZE,
- SE_RESIZE,
- SW_RESIZE,
- S_RESIZE,
- W_RESIZE,
- MOVE,
- TEXT,
- WAIT,
- PROGRESS,
- HELP,
-
- NUM_CURSORS, // This is not a valid Cursor Type. It is the number of cursor
- // types.
-};
-
-} // namespace Cursor
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_CURSOR_H_
diff --git a/o3d/core/cross/curve.cc b/o3d/core/cross/curve.cc
deleted file mode 100644
index 82be3c9..0000000
--- a/o3d/core/cross/curve.cc
+++ /dev/null
@@ -1,815 +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 Curve.
-// This code is heavily influenced by code from FCollada.
-
-#include "core/cross/curve.h"
-#include "core/cross/error.h"
-#include "import/cross/memory_stream.h"
-#include "import/cross/raw_data.h"
-
-#undef min
-#undef max
-
-namespace o3d {
-
-O3D_DEFN_CLASS(CurveKey, ObjectBase);
-O3D_DEFN_CLASS(StepCurveKey, CurveKey);
-O3D_DEFN_CLASS(LinearCurveKey, CurveKey);
-O3D_DEFN_CLASS(BezierCurveKey, CurveKey);
-O3D_DEFN_CLASS(CurveFunctionContext, FunctionContext);
-O3D_DEFN_CLASS(Curve, Function);
-
-const char *Curve::kSerializationID = "CURV";
-
-namespace {
-
-const float kEpsilon = 0.00001f;
-
-float Clamp(float value, float min_value, float max_value) {
- return value > max_value ? max_value :
- (value < min_value ? min_value : value);
-}
-
-// Uses iterative method to accurately pin-point the 't' of the Bezier
-// equation that corresponds to the current time.
-float FindT(float control_point_0_x,
- float control_point_1_x,
- float control_point_2_x,
- float control_point_3_x,
- float input,
- float initial_guess) {
- float local_tolerance = 0.001f;
- float high_t = 1.0f;
- float low_t = 0.0f;
-
- // TODO: Optimize here, start with a more intuitive value than 0.5
- // (comment left over from original code)
- float mid_t = 0.5f;
- if (initial_guess <= 0.1) {
- mid_t = 0.1f; // clamp to 10% or 90%, because if miss, the cost is
- // too high.
- } else if (initial_guess >= 0.9) {
- mid_t = 0.9f;
- } else {
- mid_t = initial_guess;
- }
- bool once = true;
- while ((high_t-low_t) > local_tolerance) {
- if (once) {
- once = false;
- } else {
- mid_t = (high_t - low_t) / 2.0f + low_t;
- }
- float ti = 1.0f - mid_t; // (1 - t)
- float calculated_time = control_point_0_x * ti * ti * ti +
- 3 * control_point_1_x * mid_t * ti * ti +
- 3 * control_point_2_x * mid_t * mid_t * ti +
- control_point_3_x * mid_t * mid_t * mid_t;
- if (fabsf(calculated_time - input) <= local_tolerance) {
- break; // If we 'fall' very close, we like it and break.
- }
- if (calculated_time > input) {
- high_t = mid_t;
- } else {
- low_t = mid_t;
- }
- }
- return mid_t;
-}
-
-typedef CurveKey::Ref (*KeyCreatorFunc)(ServiceLocator* service_locator,
- Curve* onwer);
-struct KeyCreator {
- const ObjectBase::Class* key_type;
- KeyCreatorFunc create_function;
-};
-static KeyCreator g_creators[] = {
- { StepCurveKey::GetApparentClass(), StepCurveKey::Create, },
- { LinearCurveKey::GetApparentClass(), LinearCurveKey::Create, },
- { BezierCurveKey::GetApparentClass(), BezierCurveKey::Create, },
-};
-
-} // anonymous namespace
-
-CurveKey::CurveKey(ServiceLocator* service_locator, Curve* owner)
- : ObjectBase(service_locator),
- owner_(owner),
- input_(0.0f),
- output_(0.0f) {
-}
-
-void CurveKey::Destroy() {
- owner_->RemoveKey(this);
-}
-
-void CurveKey::SetInput(float new_input) {
- if (new_input != input_) {
- input_ = new_input;
- owner_->MarkAsUnsorted();
- }
-}
-
-void CurveKey::SetOutput(float new_output) {
- if (new_output != output_) {
- output_ = new_output;
- owner_->InvalidateCache();
- }
-}
-
-// StepCurveKey ------------------------------------------------------------
-
-StepCurveKey::StepCurveKey(ServiceLocator* service_locator, Curve* owner)
- : CurveKey(service_locator, owner) {
-}
-
-CurveKey::Ref StepCurveKey::Create(ServiceLocator* service_locator,
- Curve* owner) {
- return CurveKey::Ref(new StepCurveKey(service_locator, owner));
-}
-
-float StepCurveKey::GetOutputAtOffset(float offset, unsigned key_index) const {
- return output();
-}
-
-// LinearCurveKey ----------------------------------------------------------
-
-LinearCurveKey::LinearCurveKey(ServiceLocator* service_locator, Curve* owner)
- : CurveKey(service_locator, owner) {
-}
-
-CurveKey::Ref LinearCurveKey::Create(ServiceLocator* service_locator,
- Curve* owner) {
- return CurveKey::Ref(new LinearCurveKey(service_locator, owner));
-}
-
-float LinearCurveKey::GetOutputAtOffset(float offset,
- unsigned key_index) const {
- const CurveKey* next_key(owner()->GetKey(key_index + 1));
- DCHECK(next_key);
-
- float input_span = next_key->input() - input();
- float output_span = next_key->output() - output();
- return output() + offset / input_span * output_span;
-}
-
-// BezierCurveKey ----------------------------------------------------------
-
-BezierCurveKey::BezierCurveKey(ServiceLocator* service_locator, Curve* owner)
- : CurveKey(service_locator, owner),
- in_tangent_(0, 0),
- out_tangent_(0, 0) {
-}
-
-CurveKey::Ref BezierCurveKey::Create(ServiceLocator* service_locator,
- Curve* owner) {
- return CurveKey::Ref(new BezierCurveKey(service_locator, owner));
-}
-
-void BezierCurveKey::SetInTangent(const Float2& value) {
- in_tangent_ = value;
- owner()->InvalidateCache();
-}
-
-void BezierCurveKey::SetOutTangent(const Float2& value) {
- out_tangent_ = value;
- owner()->InvalidateCache();
-}
-
-float BezierCurveKey::GetOutputAtOffset(float offset,
- unsigned key_index) const {
- const CurveKey* next_key(owner()->GetKey(key_index + 1));
- DCHECK(next_key);
-
- float input_span = next_key->input() - input();
- float output_span = next_key->output() - output();
- Float2 in_tangent;
-
- // We check bezier first because it's the most likely match for another
- // bezier key.
- if (next_key->GetClass() == BezierCurveKey::GetApparentClass()) {
- in_tangent = (down_cast<const BezierCurveKey*>(next_key)->in_tangent());
- } else if (next_key->GetClass() == LinearCurveKey::GetApparentClass() ||
- next_key->GetClass() == StepCurveKey::GetApparentClass()) {
- in_tangent.setX(next_key->input() - input_span / 3.0f);
- in_tangent.setY(next_key->output() - output_span / 3.0f);
- } else {
- DCHECK(false); // Bad Key.
- return output();
- }
-
- // Do a bezier calculation.
- float t = offset / input_span;
- t = FindT(input(),
- out_tangent_.getX(),
- in_tangent.getX(),
- next_key->input(),
- input() + offset,
- t);
- float b = out_tangent_.getY();
- float c = in_tangent.getY();
- float ti = 1.0f - t;
- float br = 3.0f;
- float cr = 3.0f;
- return output() * ti * ti * ti + br * b * ti * ti * t +
- cr * c * ti * t * t + next_key->output() * t * t * t;
-}
-
-// CurveFunctionContext ------------------------------------------------
-
-CurveFunctionContext::CurveFunctionContext(ServiceLocator* service_locator)
- : FunctionContext(service_locator),
- last_key_index_(0) {
-}
-
-// Curve --------------------------------------------------------------
-
-const float Curve::kDefaultSampleRate = 1.0f / 30.0f; // 30hz
-const float Curve::kMinimumSampleRate = 1.0f / 240.0f; // 240hz
-
-Curve::Curve(ServiceLocator* service_locator)
- : Function(service_locator),
- pre_infinity_(CONSTANT),
- post_infinity_(CONSTANT),
- sorted_(true),
- use_cache_(true),
- sample_rate_(kDefaultSampleRate),
- cache_valid_(false),
- check_discontinuity_(false),
- discontinuous_(false),
- num_step_keys_(0),
- last_key_index_(0) {
-}
-
-Curve::~Curve() {
-}
-
-const ObjectBase::Class* Curve::GetFunctionContextClass() const {
- return CurveFunctionContext::GetApparentClass();
-}
-
-FunctionContext* Curve::CreateFunctionContext() const {
- return new CurveFunctionContext(service_locator());
-}
-
-void Curve::AddKey(CurveKey::Ref key) {
- keys_.push_back(key);
- MarkAsUnsorted();
- if (key->IsA(StepCurveKey::GetApparentClass())) {
- ++num_step_keys_;
- }
-}
-
-CurveKey* Curve::CreateKeyByClass(const ObjectBase::Class* key_type) {
- for (unsigned ii = 0; ii < arraysize(g_creators); ++ii) {
- if (g_creators[ii].key_type == key_type) {
- CurveKey::Ref key(g_creators[ii].create_function(
- service_locator(),
- this));
- AddKey(key);
- return key.Get();
- }
- }
-
- O3D_ERROR(service_locator())
- << "unrecognized key type '" << (key_type ? key_type->name() : "NULL")
- << "'";
- return NULL;
-}
-
-CurveKey* Curve::CreateKeyByClassName(const String& key_type) {
- for (unsigned ii = 0; ii < arraysize(g_creators); ++ii) {
- if (!key_type.compare(g_creators[ii].key_type->name()) ||
- !key_type.compare(g_creators[ii].key_type->unqualified_name())) {
- CurveKey::Ref key(g_creators[ii].create_function(
- service_locator(),
- this));
- AddKey(key);
- return key.Get();
- }
- }
-
- O3D_ERROR(service_locator())
- << "unrecognized key type '" << key_type << "'";
- return NULL;
-}
-
-void Curve::RemoveKey(CurveKey* key) {
- // keep a reference to the key so it doesn't get deleted early.
- CurveKey::Ref temp(key);
- CurveKeyRefArray::iterator end = std::remove(keys_.begin(),
- keys_.end(),
- CurveKey::Ref(key));
-
- // key should never be in the key array more than once.
- DLOG_ASSERT(std::distance(end, keys_.end()) <= 1);
-
- // The key was never found.
- DCHECK(end != keys_.end());
-
- if (key->IsA(StepCurveKey::GetApparentClass())) {
- --num_step_keys_;
- }
-
- // Actually remove the key from the key array
- keys_.erase(end, keys_.end());
-
- InvalidateCache();
-
- // The key will get destroyed here since the last reference to
- // it, temp, will be released.
-}
-
-void Curve::SetSampleRate(float rate) {
- if (rate < kMinimumSampleRate) {
- // TODO: should we just silently set it to the minimum?
- O3D_ERROR(service_locator())
- << "attempt to set sample rate to " << rate
- << " which is lower than the minimum of "
- << kMinimumSampleRate;
- } else if (rate != sample_rate_) {
- sample_rate_ = rate;
- InvalidateCache();
- }
-}
-
-void Curve::MarkAsUnsorted() const {
- sorted_ = false;
-}
-
-void Curve::InvalidateCache() const {
- cache_valid_ = false;
- check_discontinuity_ = true;
-}
-
-bool Curve::IsDiscontinuous() const {
- UpdateCurveInfo();
- return discontinuous_;
-}
-
-inline static bool CompareByInput(const CurveKey::Ref& lhs,
- const CurveKey::Ref& rhs) {
- return lhs->input() < rhs->input();
-}
-
-void Curve::ResortKeys() const {
- std::sort(keys_.begin(), keys_.end(), CompareByInput);
- sorted_ = true;
- InvalidateCache();
-}
-
-void Curve::CheckDiscontinuity() const {
- // Mark the curve as discontinuous if any 2 keys share the same input and
- // if their outputs are different.
- check_discontinuity_ = false;
- discontinuous_ = num_step_keys_ > 0 && num_step_keys_ != keys_.size();
- if (!discontinuous_ && keys_.size() > 1) {
- for (unsigned ii = 0; ii < keys_.size() - 1; ++ii) {
- if (keys_[ii]->input() == keys_[ii + 1]->input() &&
- keys_[ii]->output() != keys_[ii + 1]->output()) {
- discontinuous_ = true;
- break;
- }
- }
- }
-}
-
-void Curve::CreateCache() const {
- float start_input = keys_.front()->input();
- float end_input = keys_.back()->input();
- float input_span = end_input - start_input;
-
- unsigned samples =
- static_cast<unsigned>(ceilf(input_span / sample_rate_) + 1);
- cache_samples_.clear();
- cache_samples_.resize(samples, 0.0f);
-
- FunctionContext::Ref context = FunctionContext::Ref(CreateFunctionContext());
-
- for (unsigned ii = 0; ii < samples; ++ii) {
- cache_samples_[ii] = GetOutputInSpan(
- start_input + sample_rate_ * static_cast<float>(ii),
- down_cast<CurveFunctionContext*>(context.Get()));
- }
-
- cache_valid_ = true;
-}
-
-float Curve::GetOutputInSpan(float input, CurveFunctionContext* context) const {
- DCHECK(input >= keys_.front()->input());
-
- if (input >= keys_.back()->input()) {
- return keys_.back()->output();
- }
-
- // use the keys directly.
- unsigned start = 0;
- unsigned end = keys_.size();
- unsigned key_index;
- bool found = false;
-
- static const unsigned kKeysToSearch = 3U;
-
- // See if the context already has a index to the correct key.
- if (context) {
- key_index = context->last_key_index();
- // is that index in range.
- if (key_index < end - 1) {
- // Are we between these keys.
- if (keys_[key_index]->input() <= input &&
- keys_[key_index + 1]->input() > input) {
- // Yes!
- found = true;
- } else {
- // No, so check which way we need to go.
- if (input > keys_[key_index]->input()) {
- // search forward a few keys. If it's not within a few keys give up.
- unsigned check_end = std::max(key_index + kKeysToSearch, end);
- for (++key_index; key_index < check_end; ++key_index) {
- if (keys_[key_index]->input() <= input &&
- keys_[key_index + 1]->input() > input) {
- // Yes!
- found = true;
- break;
- }
- }
- } else if (key_index > 0) {
- // search backward a few keys. If it's not within a few keys give up.
- unsigned check_end = std::min(key_index - kKeysToSearch, 0U);
- for (--key_index; key_index >= check_end; --key_index) {
- if (keys_[key_index]->input() <= input &&
- keys_[key_index + 1]->input() > input) {
- // Yes!
- found = true;
- break;
- }
- }
- }
- }
- }
- }
-
- if (!found) {
- // TODO: If we assume the most common case is sampled keys and
- // constant intervals we can make a quick guess where that key is.
-
- // Find the current the keys that cover our input.
- while (start <= end) {
- unsigned mid = (start + end) / 2;
- if (input > keys_[mid]->input()) {
- start = mid + 1;
- } else {
- if (mid == 0) {
- break;
- }
- end = mid - 1;
- }
- }
-
- end = keys_.size();
- while (start < end) {
- if (keys_[start]->input() > input) {
- break;
- }
- ++start;
- }
-
- DCHECK(start > 0);
- DCHECK(start < end);
-
- key_index = start - 1;
- }
-
- const CurveKey* key = keys_[key_index];
- if (context) {
- context->set_last_key_index(key_index);
- }
- return key->GetOutputAtOffset(input - key->input(), key_index);
-}
-
-float Curve::Evaluate(float input, FunctionContext* context) const {
- if (context && !context->IsA(CurveFunctionContext::GetApparentClass())) {
- O3D_ERROR(service_locator())
- << "function context '" << context->GetClassName()
- << "' is wrong type for Curve";
- context = NULL;
- }
-
- if (keys_.empty()) {
- return 0.0f;
- }
-
- if (keys_.size() == 1) {
- return keys_.front()->output();
- }
-
- UpdateCurveInfo();
-
- float start_input = keys_.front()->input();
- float end_input = keys_.back()->input();
- float input_span = end_input - start_input;
- float start_output = keys_.front()->output();
- float end_output = keys_.back()->output();
- float output_delta = end_output - start_output;
-
- float output_offset = 0.0f;
- // check for pre-infinity
- if (input < start_input) {
- if (input_span <= 0.0f) {
- return start_output;
- }
- float pre_infinity_offset = start_input - input;
- switch (pre_infinity_) {
- case CONSTANT:
- return start_output;
- case LINEAR: {
- const CurveKey* second_key = keys_[1];
- float input_delta = second_key->input() - start_input;
- if (input_delta > kEpsilon) {
- return start_output - pre_infinity_offset *
- (second_key->output() - start_output) / input_delta;
- } else {
- return start_output;
- }
- }
- case CYCLE: {
- float cycle_count = ceilf(pre_infinity_offset / input_span);
- input += cycle_count * input_span;
- input = start_input + fmodf(input - start_input, input_span);
- break;
- }
- case CYCLE_RELATIVE: {
- float cycle_count = ceilf(pre_infinity_offset / input_span);
- input += cycle_count * input_span;
- input = start_input + fmodf(input - start_input, input_span);
- output_offset -= cycle_count * output_delta;
- break;
- }
- case OSCILLATE: {
- float cycle_count = ceilf(pre_infinity_offset / (2.0f * input_span));
- input += cycle_count * 2.0f * input_span;
- input = end_input - fabsf(input - end_input);
- break;
- }
- default:
- O3D_ERROR(service_locator()) << "invalid value for pre-infinity";
- return start_output;
- }
- } else if (input >= end_input) {
- // check for post-infinity
- if (input_span <= 0.0f) {
- return end_output;
- }
- float post_infinity_offset = input - end_input;
- switch (post_infinity_) {
- case CONSTANT:
- return end_output;
- case LINEAR: {
- const CurveKey* next_to_last_key = keys_[keys_.size() - 2];
- float input_delta = end_input - next_to_last_key->input();
- if (input_delta > kEpsilon) {
- return end_output + post_infinity_offset *
- (end_output - next_to_last_key->output()) /
- input_delta;
- } else {
- return end_output;
- }
- }
- case CYCLE: {
- float cycle_count = ceilf(post_infinity_offset / input_span);
- input -= cycle_count * input_span;
- input = start_input + fmodf(input - start_input, input_span);
- break;
- }
- case CYCLE_RELATIVE: {
- float cycle_count = floorf((input - start_input) / input_span);
- input -= cycle_count * input_span;
- input = start_input + fmodf(input - start_input, input_span);
- output_offset += cycle_count * output_delta;
- break;
- }
- case OSCILLATE: {
- float cycle_count = ceilf(post_infinity_offset / (2.0f *
- input_span));
- input -= cycle_count * 2.0f * input_span;
- input = start_input + fabsf(input - start_input);
- break;
- }
- default:
- O3D_ERROR(service_locator()) << "invalid value for post-infinity";
- return end_output;
- }
- }
-
- // At this point input should be between start_input and end_input
- // inclusive.
-
- // If we are at end_input then just return end_output since we can't
- // interpolate end_input to anything past it.
- if (input >= end_input) {
- return end_output + output_offset;
- }
-
- if (!discontinuous_ && use_cache_) {
- // use the cache. The cache is implemented as a sampling of outputs at
- // specific intervals (sample_rate_). Linear interpolation is used between
- // samples. The is significantly faster than using the real keys but it
- // takes a lot more memory and it can't handle discontinuous animation like
- // camera cuts.
- if (!cache_valid_) {
- CreateCache();
- }
- float span_input = input - start_input;
- unsigned sample = static_cast<unsigned>(span_input / sample_rate_);
-
- DCHECK(sample < cache_samples_.size() - 1);
-
- float current_sample = cache_samples_[sample];
- if (num_step_keys_ == keys_.size()) {
- // It's all step keys so don't interpolate.
- return current_sample + output_offset;
- } else {
- float offset = fmodf(span_input, sample_rate_);
- float next_sample = cache_samples_[sample + 1];
- return current_sample + (next_sample - current_sample) *
- offset / sample_rate_ + output_offset;
- }
- } else {
- return GetOutputInSpan(
- input, down_cast<CurveFunctionContext*>(context)) + output_offset;
- }
-}
-
-ObjectBase::Ref Curve::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new Curve(service_locator));
-}
-
-
-static Float2 ReadFloat2(MemoryReadStream *stream) {
- float v1 = stream->ReadLittleEndianFloat32();
- float v2 = stream->ReadLittleEndianFloat32();
- Float2 value;
- value.setX(v1);
- value.setY(v2);
- return value;
-}
-
-// Some constants for error checking
-const size_t kFloat2Size = 2 * sizeof(float);
-const size_t kStepDataSize = 2 * sizeof(float);
-const size_t kLinearDataSize = 2 * sizeof(float);
-
-// not using sizeof(Float2) just in case this class adds ivars
-// we're being more explicit here
-const size_t kBezierDataSize = 2 * sizeof(float) + 2 * kFloat2Size;
-
-bool Curve::LoadFromBinaryData(MemoryReadStream *stream) {
- // Make sure we have enough data for serialization ID and version
- if (stream->GetRemainingByteCount() < 4 + sizeof(int32)) {
- O3D_ERROR(service_locator()) << "invalid empty curve data";
- return false;
- }
-
- // To insure data integrity we expect four characters kSerializationID
- uint8 id[4];
- stream->Read(id, 4);
-
- if (memcmp(id, kSerializationID, 4)) {
- O3D_ERROR(service_locator())
- << "data object does not contain curve data";
- return false;
- }
-
- int32 version = stream->ReadLittleEndianInt32();
- if (version != 1) {
- O3D_ERROR(service_locator()) << "unknown version for curve data";
- return false;
- }
-
- while (!stream->EndOfStream()) {
- // switch on types of keys
- CurveKey::KeyType key_type =
- static_cast<CurveKey::KeyType>(stream->ReadByte());
- size_t available_bytes = stream->GetRemainingByteCount();
-
- switch (key_type) {
- case CurveKey::TYPE_STEP: {
- if (available_bytes < kStepDataSize) {
- FreeAll(); // This must be called before O3D_ERROR.
- O3D_ERROR(service_locator()) << "unexpected end of curve data";
- return false;
- }
- float input = stream->ReadLittleEndianFloat32();
- float output = stream->ReadLittleEndianFloat32();
- StepCurveKey* key = Create<StepCurveKey>();
- key->SetInput(input);
- key->SetOutput(output);
- break;
- }
- case CurveKey::TYPE_LINEAR: {
- if (available_bytes < kLinearDataSize) {
- FreeAll(); // This must be called before O3D_ERROR.
- O3D_ERROR(service_locator()) << "unexpected end of curve data";
- return false;
- }
- float input = stream->ReadLittleEndianFloat32();
- float output = stream->ReadLittleEndianFloat32();
- LinearCurveKey* key = Create<LinearCurveKey>();
- key->SetInput(input);
- key->SetOutput(output);
- break;
- }
- case CurveKey::TYPE_BEZIER: {
- if (available_bytes < kBezierDataSize) {
- FreeAll(); // This must be called before O3D_ERROR.
- O3D_ERROR(service_locator()) << "unexpected end of curve data";
- return false;
- }
- float input = stream->ReadLittleEndianFloat32();
- float output = stream->ReadLittleEndianFloat32();
- Float2 in_tangent = ReadFloat2(stream);
- Float2 out_tangent = ReadFloat2(stream);
- BezierCurveKey* key = Create<BezierCurveKey>();
- key->SetInput(input);
- key->SetOutput(output);
- key->SetInTangent(in_tangent);
- key->SetOutTangent(out_tangent);
- break;
- }
- default: {
- FreeAll(); // This must be called before O3D_ERROR.
- O3D_ERROR(service_locator()) << "invalid curve data";
- return false; // unknown key type
- }
- }
- }
- return true;
-}
-
-void Curve::FreeAll() {
- while (!keys_.empty()) {
- keys_[0]->Destroy();
- }
-}
-
-bool Curve::Set(o3d::RawData *raw_data) {
- if (!raw_data) {
- O3D_ERROR(service_locator()) << "data object is null";
- return false;
- }
- return Set(raw_data, 0, raw_data->GetLength());
-}
-
-bool Curve::Set(o3d::RawData *raw_data,
- size_t offset,
- size_t length) {
- if (!raw_data) {
- O3D_ERROR(service_locator()) << "data object is null";
- return false;
- }
-
- if (!raw_data->IsOffsetLengthValid(offset, length)) {
- O3D_ERROR(service_locator()) << "illegal curve data offset or size";
- return false;
- }
-
- const uint8 *data = raw_data->GetDataAs<uint8>(offset);
- if (!data) {
- return false;
- }
-
- MemoryReadStream stream(data, length);
- return LoadFromBinaryData(&stream);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/curve.h b/o3d/core/cross/curve.h
deleted file mode 100644
index 855b42c..0000000
--- a/o3d/core/cross/curve.h
+++ /dev/null
@@ -1,470 +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 Curve declaration.
-
-#ifndef O3D_CORE_CROSS_CURVE_H_
-#define O3D_CORE_CROSS_CURVE_H_
-
-#include <vector>
-#include "core/cross/param_object.h"
-#include "core/cross/function.h"
-
-namespace o3d {
-
-class Curve;
-class MemoryReadStream;
-class RawData;
-
-// CurveKey is the abstract base class for all types of CurveKeys.
-// Each Concrete CurveKey is responsible for computing outputs between it
-// and the next type of key.
-class CurveKey : public ObjectBase {
- public:
- typedef SmartPointer<CurveKey> Ref;
-
- // These enum values are only used for binary serialization/deserialization
- // and are not exposed through Javascript
- enum KeyType {
- TYPE_UNKNOWN = 0,
- TYPE_STEP = 1,
- TYPE_LINEAR = 2,
- TYPE_BEZIER = 3,
- };
-
- virtual ~CurveKey() { }
-
- // Destroy's this Key (removing it from its owner).
- void Destroy();
-
- // Gets the input of this key.
- inline float input() const {
- return input_;
- }
-
- // Sets the input of this key. This has the side effect of telling the
- // Curve this key belongs to resort the keys.
- // Parameters:
- // new_input: new input for key.
- void SetInput(float new_input);
-
- // Gets the output of the key.
- inline float output() const {
- return output_;
- }
-
- // Sets the output of the key.
- void SetOutput(float new_output);
-
- // Gets the Curve that owns this key.
- Curve* owner() const {
- return owner_;
- }
-
- // Given an offset from this key's input to the next key (key_index + 1)
- // returns a output between this key and the next key.
- // Parameters:
- // offset: Offset to next key.
- // key_index: Index of this key. There must be a key at key_index + 1!!!
- virtual float GetOutputAtOffset(float offset, unsigned key_index) const = 0;
-
- protected:
- CurveKey(ServiceLocator* service_locator, Curve* owner);
-
- private:
- // Curve we are owned by.
- Curve* owner_;
-
- // Input of key
- float input_;
-
- // Output of key at input.
- float output_;
-
- O3D_DECL_CLASS(CurveKey, ObjectBase);
- DISALLOW_COPY_AND_ASSIGN(CurveKey);
-};
-
-typedef std::vector<CurveKey::Ref> CurveKeyRefArray;
-typedef std::vector<CurveKey*> CurveKeyArray;
-
-// An CurveKey that holds its output (is not interpolated between this key
-// and the next.)
-class StepCurveKey : public CurveKey {
- public:
- typedef SmartPointer<StepCurveKey> Ref;
-
- StepCurveKey(ServiceLocator* service_locator, Curve* owner);
-
- // Overridden from CurveKey
- virtual float GetOutputAtOffset(float offset, unsigned key_index) const;
-
- static CurveKey::Ref Create(ServiceLocator* service_locator, Curve* owner);
-
- private:
- O3D_DECL_CLASS(StepCurveKey, CurveKey);
- DISALLOW_COPY_AND_ASSIGN(StepCurveKey);
-};
-
-// An CurveKey that linearly interpolates between this key and the next key.
-class LinearCurveKey : public CurveKey {
- public:
- typedef SmartPointer<LinearCurveKey> Ref;
-
- LinearCurveKey(ServiceLocator* service_locator, Curve* owner);
-
- // Overridden from CurveKey
- virtual float GetOutputAtOffset(float offset, unsigned key_index) const;
-
- static CurveKey::Ref Create(ServiceLocator* service_locator, Curve* owner);
-
- private:
- O3D_DECL_CLASS(LinearCurveKey, CurveKey);
- DISALLOW_COPY_AND_ASSIGN(LinearCurveKey);
-};
-
-// An CurveKey that uses a bezier curve for interpolation between this key
-// and the next.
-class BezierCurveKey : public CurveKey {
- public:
- typedef SmartPointer<BezierCurveKey> Ref;
-
- BezierCurveKey(ServiceLocator* service_locator, Curve* owner);
-
- // Overridden from CurveKey
- virtual float GetOutputAtOffset(float offset, unsigned key_index) const;
-
- inline const Float2& in_tangent() const {
- return in_tangent_;
- }
-
- // Sets the in tanget of the key.
- void SetInTangent(const Float2& value);
-
- inline const Float2& out_tangent() const {
- return out_tangent_;
- }
-
- // Sets the out tanget of the key.
- void SetOutTangent(const Float2& value);
-
- static CurveKey::Ref Create(ServiceLocator* service_locator, Curve* owner);
-
- private:
- Float2 in_tangent_;
- Float2 out_tangent_;
-
- O3D_DECL_CLASS(BezierCurveKey, CurveKey);
- DISALLOW_COPY_AND_ASSIGN(BezierCurveKey);
-};
-
-// A CurveFunctionContext is used by Curve to help with evaluation.
-// In the case of Curve it holds the index to the last key so that
-// the next time the curve is evaluated we can usually avoid looking for the
-// correct key pair.
-class CurveFunctionContext : public FunctionContext {
- public:
- typedef SmartPointer<CurveFunctionContext> Ref;
-
- explicit CurveFunctionContext(ServiceLocator* service_locator);
-
- unsigned last_key_index() const {
- return last_key_index_;
- }
-
- void set_last_key_index(unsigned index) {
- last_key_index_ = index;
- }
-
- private:
- unsigned last_key_index_;
-
- O3D_DECL_CLASS(CurveFunctionContext, FunctionContext);
- DISALLOW_COPY_AND_ASSIGN(CurveFunctionContext);
-};
-
-// An Curve stores a bunch of spline keys and given a value
-// representing a point on the spline returns the value of the spline for that
-// point. Curve is a data only. It is use by 1 or more
-// AnimationChannels.
-class Curve : public Function {
- public:
- typedef SmartPointer<Curve> Ref;
-
- // Animations that are cached default to using this sample rate.
- static const float kDefaultSampleRate;
- static const float kMinimumSampleRate;
-
- // A four-character identifier used in the binary serialization format
- // (not exposed to Javascript)
- static const char *kSerializationID;
-
-
- enum Infinity {
- CONSTANT, // Uses the output value of the first or last animation
- // key.
- //
- LINEAR, // Takes the distance between the closest animation key
- // input value and the evaluation time. Multiplies this
- // distance against the instant slope at the closest
- // animation key and offsets the result with the closest
- // animation key output value.
- //
- CYCLE, // Cycles over the first and last keys using
- // input = (input - first) % (last - first) + first;
- // Note that in CYCLE mode you can never get the end value
- // because a cycle goes from start to end exclusive of end.
- //
- CYCLE_RELATIVE, // Same as cycle except
- // value = (last.value - first.value) *
- // (input - first) / (last - first)
- //
- OSCILLATE, // Ping Pongs between the first and last keys.
- // input = (input - first) % ((last - first) * 2)
- // if (input > (last - first)) {
- // input = (last - first) * 2 - input;
- // }
- // input += first;
- };
-
- ~Curve();
-
- Infinity pre_infinity() const {
- return pre_infinity_;
- }
-
- void set_pre_infinity(Infinity infinity) {
- pre_infinity_ = infinity;
- }
-
- Infinity post_infinity() const {
- return post_infinity_;
- }
-
- void set_post_infinity(Infinity infinity) {
- post_infinity_ = infinity;
- }
-
- bool use_cache() const {
- return use_cache_;
- }
-
- // Sets whether or not to use the cache.
- void set_use_cache(bool use_cache) {
- use_cache_ = use_cache;
- }
-
- // The sample rate for the cache.
- float sample_rate() const {
- return sample_rate_;
- }
-
- // Sets the sample rate used for the cache. By default Animation data is
- // cached so that using the animation is fast. To do this the keys that
- // represent the animation are sampled. The higher the frequency of the
- // samples the closer the cache will match the actual keys.
- // The default is 1/30 (30hz). You can set it anywhere from 1/240th (240hz) to
- // any larger value. Note: Setting the sample rate has the side effect of
- // invalidating the cache thereby causing it to get rebuilt.
- // Parameters:
- // rate: sample rate. Must be 1/240 or greater. Default = 1/30.
- void SetSampleRate(float rate);
-
-
- // Returns whether or not the curve is discontinuous. A discontinuous curve
- // takes more time to evaluate.
- bool IsDiscontinuous() const;
-
- // Overriden from Function.
- // Gets a value for this curve at the given input on the curve.
- // Parameters:
- // input: input to function.
- // context: A CurveFunctionContext. May be null.
- // Returns:
- // The output for the given input.
- float Evaluate(float input, FunctionContext* context) const;
-
- // Overriden from Function.
- virtual FunctionContext* CreateFunctionContext() const;
-
- // Overriden from Function.
- virtual const ObjectBase::Class* GetFunctionContextClass() const;
-
- // Creates a new Key. Do not use this directly, Use the Create template below.
- // Parameters:
- // key_type: class of key to create.
- // Returns:
- // pointer to created key.
- CurveKey* CreateKeyByClass(const ObjectBase::Class* key_type);
-
- // Creates a new Key for this curve. Use like this.
- //
- // StepCurveKey* key = curve->Create<StepCurveKey>();
- template<typename T>
- T* Create() {
- T* key = down_cast<T*>(CreateKeyByClass(T::GetApparentClass()));
- DCHECK(key);
- return key;
- }
-
- // Creates a new key for this curve. This function is for Javascript.
- // Parameters:
- // key_type: class name of key to create.
- // Returns:
- // pointer to created key.
- CurveKey* CreateKeyByClassName(const String& key_type);
-
- // This is an internal function. It is only called by CurveKey::Remove
- void RemoveKey(CurveKey* key);
-
- // Returns the array of keys for this curve.
- const CurveKeyRefArray& keys() {
- return keys_;
- }
-
- // Gets a particular key by index, returns NULL if the index is out of range.
- CurveKey* GetKey(unsigned key_index) const {
- return key_index < keys_.size() ? keys_[key_index].Get() : NULL;
- }
-
- // Invalidates the cache (internal use only)
- void InvalidateCache() const;
-
- // Marks the cache as unsorted (internal use only)
- void MarkAsUnsorted() const;
-
- // De-serializes the data contained in |raw_data|
- // The entire contents of |raw_data| from start to finish will
- // be used
- bool Set(o3d::RawData *raw_data);
-
- // De-serializes the data contained in |raw_data|
- // starting at byte offset |offset| and using |length|
- // bytes
- bool Set(o3d::RawData *raw_data,
- size_t offset,
- size_t length);
-
- // de-serializes from a memory stream
- bool LoadFromBinaryData(MemoryReadStream *stream);
-
- private:
- explicit Curve(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // Adds a key to the keys that belong to this curve.
- void AddKey(CurveKey::Ref key);
-
- // Checks if the keys represent a discontinuous curve.
- void CheckDiscontinuity() const;
-
- // Resorts the keys by input. Requires that keys that have the same
- // input remain in the same relative order. In otherwords, if key1 comes
- // before key2 and both have the same input then resorting keeps key1
- // before key2.
- void ResortKeys() const;
-
- // Returns a output for the given input. Input must be greater than or
- // equal to the input of the first key and any input >= the input of
- // the last key will return the output of the last key.
- float GetOutputInSpan(float input, CurveFunctionContext* context) const;
-
- // Caches the animation in an evaluation friendly format.
- void CreateCache() const;
-
- // Updates information about the curve such as sorting the keys
- // and checking for discontinuity.
- inline void UpdateCurveInfo() const {
- if (!sorted_) {
- ResortKeys();
- }
- if (check_discontinuity_) {
- CheckDiscontinuity();
- }
- }
-
- // Removes all the keys.
- void FreeAll();
-
- // What to do for inputs before the first key
- Infinity pre_infinity_;
-
- // What to do for inputs past the last key.
- Infinity post_infinity_;
-
- // true if the keys are sorted.
- mutable bool sorted_;
-
- // Animation keys. These keys are kept sorted by input at all times.
- mutable CurveKeyRefArray keys_;
-
- // -- Cache related fields --
-
- // true if we should use the cache vs recomputing from the curve each time.
- // Default is true. The only reason to set this to false is either that
- // it uses less memory not to cache or because the sampling is not
- // accurate enough.
- bool use_cache_;
-
- // how often to sample for the cache. Default = 1/30
- float sample_rate_;
-
- // true if the cache is valid.
- mutable bool cache_valid_;
-
- // true if we need to check whether or not the curve is discontinous
- mutable bool check_discontinuity_;
-
- // true if there are 2 keys at the same input with different outputs.
- mutable bool discontinuous_;
-
- // The number of keys at are Step keys. If all keys are all step keys we can
- // use the cache but must not interpolate. If there are one or more step keys
- // but all the keys are not step keys then the curve will be marked as
- // discontinous.
- mutable unsigned num_step_keys_;
-
- // The last key we used during evaluate.
- mutable unsigned last_key_index_;
-
- // Samples used for cache.
- mutable std::vector<float> cache_samples_;
-
- O3D_DECL_CLASS(Curve, Function);
- DISALLOW_COPY_AND_ASSIGN(Curve);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_CURVE_H_
diff --git a/o3d/core/cross/curve_test.cc b/o3d/core/cross/curve_test.cc
deleted file mode 100644
index ab8c47a..0000000
--- a/o3d/core/cross/curve_test.cc
+++ /dev/null
@@ -1,886 +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 implements unit tests for class Curve.
-
-#include <algorithm>
-#include "tests/common/win/testing_common.h"
-#include "core/cross/curve.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/error_status.h"
-#include "core/cross/object_manager.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-#include "serializer/cross/serializer_binary.h"
-
-namespace o3d {
-
-class CurveTest : public testing::Test {
- protected:
-
- CurveTest()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
-
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- Pack* pack_;
-};
-
-void CurveTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void CurveTest::TearDown() {
- pack_->Destroy();
-}
-
-namespace {
-
-const float kEpsilon = 0.001f;
-const float kEpsilon2 = 0.1f;
-
-// Returns true of key is in keys.
-bool KeyInKeys(CurveKey* key, const CurveKeyRefArray& keys) {
- return std::find(keys.begin(), keys.end(), CurveKey::Ref(key)) !=
- keys.end();
-}
-
-// Checks that a output on a curve is close to the expected output.
-bool CheckCurve(Curve* curve,
- float input,
- float expected_output) {
- float output = curve->Evaluate(input, NULL);
- return fabsf(output - expected_output) < kEpsilon;
-}
-
-// Checks that a output on a curve is close to the expected output.
-bool CheckCurveWithContext(Curve* curve,
- float input,
- float expected_output,
- FunctionContext* context) {
- float output = curve->Evaluate(input, context);
- return fabsf(output - expected_output) < kEpsilon2;
-}
-
-} // anonymous namespace.
-
-// Tests Curve.
-TEST_F(CurveTest, Basic) {
- Curve* curve = pack()->Create<Curve>();
- // Check that it got created.
- EXPECT_TRUE(curve != NULL);
- // Check that it derives from NamedObject
- EXPECT_TRUE(curve->IsA(NamedObject::GetApparentClass()));
-}
-
-// Tests CreateFunctionContext.
-TEST_F(CurveTest, CreateFunctionContext) {
- Curve* curve = pack()->Create<Curve>();
- ASSERT_TRUE(curve != NULL);
-
- FunctionContext* context = curve->CreateFunctionContext();
- ASSERT_TRUE(context != NULL);
- EXPECT_TRUE(context->IsA(CurveFunctionContext::GetApparentClass()));
-
- delete context;
-}
-
-// Tests GetFunctionContextClass.
-TEST_F(CurveTest, GetFunctionContextClass) {
- Curve* curve = pack()->Create<Curve>();
- ASSERT_TRUE(curve != NULL);
-
- EXPECT_EQ(curve->GetFunctionContextClass(),
- CurveFunctionContext::GetApparentClass());
-}
-
-// Tests CreateKey and RemoveKey.
-TEST_F(CurveTest, CreateKeyRemoveKey) {
- // Create one of each kind of key.
- Curve* curve = pack()->Create<Curve>();
- ASSERT_TRUE(curve != NULL);
-
- StepCurveKey::Ref step_key(curve->Create<StepCurveKey>());
- LinearCurveKey::Ref linear_key(curve->Create<LinearCurveKey>());
- BezierCurveKey::Ref bezier_key(curve->Create<BezierCurveKey>());
-
- ASSERT_TRUE(step_key != NULL);
- ASSERT_TRUE(linear_key != NULL);
- ASSERT_TRUE(bezier_key != NULL);
-
- const CurveKeyRefArray& keys = curve->keys();
- EXPECT_EQ(keys.size(), 3U);
- EXPECT_TRUE(KeyInKeys(step_key, keys));
- EXPECT_TRUE(KeyInKeys(linear_key, keys));
- EXPECT_TRUE(KeyInKeys(bezier_key, keys));
-
- step_key->Destroy();
- EXPECT_EQ(keys.size(), 2U);
- EXPECT_FALSE(KeyInKeys(step_key, keys));
- EXPECT_TRUE(KeyInKeys(linear_key, keys));
- EXPECT_TRUE(KeyInKeys(bezier_key, keys));
-
- bezier_key->Destroy();
- EXPECT_EQ(keys.size(), 1U);
- EXPECT_TRUE(KeyInKeys(linear_key, keys));
- EXPECT_FALSE(KeyInKeys(bezier_key, keys));
-
- linear_key->Destroy();
- EXPECT_EQ(keys.size(), 0U);
-}
-
-// Tests ResortKeys and IsDiscontinuous
-TEST_F(CurveTest, ResortKeysDiscontinuous) {
- Curve* curve = pack()->Create<Curve>();
- ASSERT_TRUE(curve != NULL);
-
- // No reason to rebuild the cache everytime
- // since we are not checking outputs.
- curve->set_use_cache(false);
-
- CurveKey* key1 = curve->Create<LinearCurveKey>();
- CurveKey* key2 = curve->Create<LinearCurveKey>();
- CurveKey* key3 = curve->Create<LinearCurveKey>();
- CurveKey* key4 = curve->Create<LinearCurveKey>();
-
- ASSERT_TRUE(key1 != NULL);
- ASSERT_TRUE(key2 != NULL);
- ASSERT_TRUE(key3 != NULL);
- ASSERT_TRUE(key4 != NULL);
-
- const CurveKeyRefArray& keys = curve->keys();
- EXPECT_EQ(keys.size(), 4U);
-
- key1->SetInput(1.0f);
- key2->SetInput(2.0f);
- key3->SetInput(3.0f);
- key4->SetInput(4.0f);
- EXPECT_FALSE(curve->IsDiscontinuous()); // causes keys to be re-sorted.
-
- EXPECT_EQ(keys.size(), 4U);
- EXPECT_EQ(keys[0], key1);
- EXPECT_EQ(keys[1], key2);
- EXPECT_EQ(keys[2], key3);
- EXPECT_EQ(keys[3], key4);
-
- key4->SetInput(0.0f);
- EXPECT_FALSE(curve->IsDiscontinuous()); // causes keys to be re-sorted.
-
- EXPECT_EQ(keys.size(), 4U);
- EXPECT_EQ(keys[0], key4);
- EXPECT_EQ(keys[1], key1);
- EXPECT_EQ(keys[2], key2);
- EXPECT_EQ(keys[3], key3);
-
- key4->SetInput(2.5f);
- EXPECT_FALSE(curve->IsDiscontinuous()); // causes keys to be re-sorted.
-
- EXPECT_EQ(keys.size(), 4U);
- EXPECT_EQ(keys[0], key1);
- EXPECT_EQ(keys[1], key2);
- EXPECT_EQ(keys[2], key4);
- EXPECT_EQ(keys[3], key3);
-
- key4->SetOutput(1.0f);
- EXPECT_FALSE(curve->IsDiscontinuous()); // causes keys to be re-sorted.
-
- key4->SetInput(2.0f);
- EXPECT_TRUE(curve->IsDiscontinuous()); // causes keys to be re-sorted.
- EXPECT_EQ(keys.size(), 4U);
- EXPECT_EQ(keys[0], key1);
- EXPECT_EQ(keys[1], key2);
- EXPECT_EQ(keys[2], key4);
- EXPECT_EQ(keys[3], key3);
-
- key4->SetInput(1.5f); // should move it before key2
- EXPECT_FALSE(curve->IsDiscontinuous()); // causes keys to be re-sorted.
- EXPECT_EQ(keys.size(), 4U);
- EXPECT_EQ(keys[0], key1);
- EXPECT_EQ(keys[1], key4);
- EXPECT_EQ(keys[2], key2);
- EXPECT_EQ(keys[3], key3);
-
- key4->SetInput(2.0f); // should still be before key2.
- EXPECT_TRUE(curve->IsDiscontinuous()); // causes keys to be re-sorted.
- EXPECT_EQ(keys.size(), 4U);
- EXPECT_EQ(keys[0], key1);
- EXPECT_EQ(keys[1], key4);
- EXPECT_EQ(keys[2], key2);
- EXPECT_EQ(keys[3], key3);
-
- CurveKey* key5 = curve->Create<LinearCurveKey>();
- CurveKey* key6 = curve->Create<LinearCurveKey>();
- EXPECT_TRUE(curve->IsDiscontinuous()); // causes keys to be re-sorted.
- EXPECT_EQ(keys.size(), 6U);
- EXPECT_EQ(keys[0], key5);
- EXPECT_EQ(keys[1], key6);
- EXPECT_EQ(keys[2], key1);
- EXPECT_EQ(keys[3], key4);
- EXPECT_EQ(keys[4], key2);
- EXPECT_EQ(keys[5], key3);
-
- // Move 2 keys together. They should still be in the same order relative to
- // each other.
- key5->SetInput(5.0f);
- key6->SetInput(5.0f);
- EXPECT_TRUE(curve->IsDiscontinuous()); // causes keys to be re-sorted.
- EXPECT_EQ(keys.size(), 6U);
- EXPECT_EQ(keys[0], key1);
- EXPECT_EQ(keys[1], key4);
- EXPECT_EQ(keys[2], key2);
- EXPECT_EQ(keys[3], key3);
- EXPECT_EQ(keys[4], key5);
- EXPECT_EQ(keys[5], key6);
-
- // Add a StepKey
- key1->SetInput(1.0f);
- key2->SetInput(2.0f);
- key3->SetInput(3.0f);
- key4->SetInput(4.0f);
- EXPECT_FALSE(curve->IsDiscontinuous()); // causes keys to be re-sorted.
- curve->Create<StepCurveKey>();
- EXPECT_TRUE(curve->IsDiscontinuous()); // causes keys to be re-sorted.
-
- // Try all step keys.
- curve->Create<StepCurveKey>();
- key1->Destroy();
- key2->Destroy();
- key3->Destroy();
- key4->Destroy();
- key5->Destroy();
- key6->Destroy();
- EXPECT_FALSE(curve->IsDiscontinuous()); // causes keys to be re-sorted.
-}
-
-// Tests Evaluate for StepCurveKey.
-TEST_F(CurveTest, EvaluateStepCurveKey) {
- Curve* curve = pack()->Create<Curve>();
- ASSERT_TRUE(curve != NULL);
-
- // No cache since we want to evaluate the actual curves.
- curve->set_use_cache(false);
-
- // Try no key
- EXPECT_EQ(curve->Evaluate(0.0f, NULL), 0.0f);
-
- // Try 1 key
- CurveKey* key1 = curve->Create<StepCurveKey>();
- ASSERT_TRUE(key1 != NULL);
- key1->SetOutput(1.0f);
-
- EXPECT_EQ(curve->Evaluate(0.0f, NULL), 1.0f);
- EXPECT_EQ(curve->Evaluate(1.0f, NULL), 1.0f);
- EXPECT_EQ(curve->Evaluate(2.0f, NULL), 1.0f);
-
- // Try 2 keys
- CurveKey* key2 = curve->Create<StepCurveKey>();
- ASSERT_TRUE(key2 != NULL);
- key2->SetOutput(2.0f);
-
- // Because the keys are both at input 0 everything should be 2.0 from zero
- // on.
- EXPECT_EQ(curve->Evaluate(-1.0f, NULL), 1.0f);
- EXPECT_EQ(curve->Evaluate(0.0f, NULL), 2.0f);
- EXPECT_EQ(curve->Evaluate(1.0f, NULL), 2.0f);
- EXPECT_EQ(curve->Evaluate(2.0f, NULL), 2.0f);
-
- // Move key 2
- key2->SetInput(1.0f);
- EXPECT_EQ(curve->Evaluate(-1.0f, NULL), 1.0f);
- EXPECT_EQ(curve->Evaluate(0.0f, NULL), 1.0f);
- EXPECT_EQ(curve->Evaluate(1.0f, NULL), 2.0f);
- EXPECT_EQ(curve->Evaluate(2.0f, NULL), 2.0f);
-}
-//
-// Tests Evaluate for LinearCurveKey.
-TEST_F(CurveTest, EvaluateLinearCurveKey) {
- Curve* curve = pack()->Create<Curve>();
- ASSERT_TRUE(curve != NULL);
-
- // No cache since we want to evaluate the actual curves.
- curve->set_use_cache(false);
-
- // Try 2 keys
- CurveKey* key1 = curve->Create<LinearCurveKey>();
- CurveKey* key2 = curve->Create<LinearCurveKey>();
- ASSERT_TRUE(key1 != NULL);
- ASSERT_TRUE(key2 != NULL);
-
- const float kStartInput = 1.0f;
- const float kStartOutput = 1.0f;
- const float kEndInput = 2.0f;
- const float kEndOutput = 5.0f;
- const float kOutputRange = kEndOutput - kStartOutput;
-
- key1->SetOutput(kStartOutput);
- key1->SetInput(kStartInput);
- key2->SetOutput(kEndOutput);
- key2->SetInput(kEndInput);
-
- curve->set_use_cache(false);
- for (int ii = 0; ii < 2; ++ii) {
- EXPECT_TRUE(CheckCurve(curve, 1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 1.2f, kStartOutput + kOutputRange * 0.2f));
- EXPECT_TRUE(CheckCurve(curve, 1.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, 1.7f, kStartOutput + kOutputRange * 0.7f));
- EXPECT_TRUE(CheckCurve(curve, 2.0f, kEndOutput));
- curve->set_use_cache(true);
- }
-}
-
-// Tests Evaluate for Pre/Post Infintiy.
-TEST_F(CurveTest, EvaluateInfinity) {
- Curve* curve = pack()->Create<Curve>();
- ASSERT_TRUE(curve != NULL);
-
- // Try 2 keys
- CurveKey* key1 = curve->Create<LinearCurveKey>();
- CurveKey* key2 = curve->Create<LinearCurveKey>();
- ASSERT_TRUE(key1 != NULL);
- ASSERT_TRUE(key2 != NULL);
-
- const float kStartInput = 1.0f;
- const float kStartOutput = 1.0f;
- const float kEndInput = 2.0f;
- const float kEndOutput = 5.0f;
- const float kOutputRange = kEndOutput - kStartOutput;
-
- key1->SetOutput(kStartOutput);
- key1->SetInput(kStartInput);
- key2->SetOutput(kEndOutput);
- key2->SetInput(kEndInput);
-
- EXPECT_TRUE(CheckCurve(curve, -1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 0.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 1.2f, kStartOutput + kOutputRange * 0.2f));
- EXPECT_TRUE(CheckCurve(curve, 1.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, 1.7f, kStartOutput + kOutputRange * 0.7f));
- EXPECT_TRUE(CheckCurve(curve, 2.0f, kEndOutput));
- EXPECT_TRUE(CheckCurve(curve, 3.0f, kEndOutput));
-
- // Change Pre-Infinity to LINEAR
- curve->set_pre_infinity(Curve::LINEAR);
- EXPECT_TRUE(CheckCurve(curve, -1.5f, kStartOutput - kOutputRange * 2.5f));
- EXPECT_TRUE(CheckCurve(curve, -1.0f, kStartOutput - kOutputRange * 2.0f));
- EXPECT_TRUE(CheckCurve(curve, 0.0f, kStartOutput - kOutputRange));
- EXPECT_TRUE(CheckCurve(curve, 1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 1.2f, kStartOutput + kOutputRange * 0.2f));
- EXPECT_TRUE(CheckCurve(curve, 1.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, 1.7f, kStartOutput + kOutputRange * 0.7f));
- EXPECT_TRUE(CheckCurve(curve, 2.0f, kEndOutput));
- EXPECT_TRUE(CheckCurve(curve, 3.0f, kEndOutput));
-
- // Change Post-Infinity to LINEAR
- curve->set_post_infinity(Curve::LINEAR);
- EXPECT_TRUE(CheckCurve(curve, -1.5f, kStartOutput - kOutputRange * 2.5f));
- EXPECT_TRUE(CheckCurve(curve, -1.0f, kStartOutput - kOutputRange * 2.0f));
- EXPECT_TRUE(CheckCurve(curve, 0.0f, kStartOutput - kOutputRange));
- EXPECT_TRUE(CheckCurve(curve, 1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 1.2f, kStartOutput + kOutputRange * 0.2f));
- EXPECT_TRUE(CheckCurve(curve, 1.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, 1.7f, kStartOutput + kOutputRange * 0.7f));
- EXPECT_TRUE(CheckCurve(curve, 2.0f, kEndOutput));
- EXPECT_TRUE(CheckCurve(curve, 3.0f, kEndOutput + kOutputRange));
- EXPECT_TRUE(CheckCurve(curve, 4.0f, kEndOutput + kOutputRange * 2.0f));
- EXPECT_TRUE(CheckCurve(curve, 4.5f, kEndOutput + kOutputRange * 2.5f));
-
- // Change Pre-Infinity to CYCLE
- curve->set_pre_infinity(Curve::CYCLE);
- EXPECT_TRUE(CheckCurve(curve, -1.2f, kStartOutput + kOutputRange * 0.8f));
- EXPECT_TRUE(CheckCurve(curve, -1.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, -1.7f, kStartOutput + kOutputRange * 0.3f));
- EXPECT_TRUE(CheckCurve(curve, -1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 0.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 1.2f, kStartOutput + kOutputRange * 0.2f));
- EXPECT_TRUE(CheckCurve(curve, 1.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, 1.7f, kStartOutput + kOutputRange * 0.7f));
- EXPECT_TRUE(CheckCurve(curve, 2.0f, kEndOutput));
- EXPECT_TRUE(CheckCurve(curve, 3.0f, kEndOutput + kOutputRange));
- EXPECT_TRUE(CheckCurve(curve, 4.0f, kEndOutput + kOutputRange * 2.0f));
- EXPECT_TRUE(CheckCurve(curve, 4.5f, kEndOutput + kOutputRange * 2.5f));
-
- // Change Post-Infinity to CYCLE
- curve->set_post_infinity(Curve::CYCLE);
- EXPECT_TRUE(CheckCurve(curve, -1.2f, kStartOutput + kOutputRange * 0.8f));
- EXPECT_TRUE(CheckCurve(curve, -1.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, -1.7f, kStartOutput + kOutputRange * 0.3f));
- EXPECT_TRUE(CheckCurve(curve, -1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 0.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 1.2f, kStartOutput + kOutputRange * 0.2f));
- EXPECT_TRUE(CheckCurve(curve, 1.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, 1.7f, kStartOutput + kOutputRange * 0.7f));
- EXPECT_TRUE(CheckCurve(curve, 2.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 3.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 4.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 4.2f, kStartOutput + kOutputRange * 0.2f));
- EXPECT_TRUE(CheckCurve(curve, 4.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, 4.7f, kStartOutput + kOutputRange * 0.7f));
-
- // Change Pre-Infinity to OSCILLATE
- curve->set_pre_infinity(Curve::OSCILLATE);
- EXPECT_TRUE(CheckCurve(curve, -1.7f, kStartOutput + kOutputRange * 0.7f));
- EXPECT_TRUE(CheckCurve(curve, -1.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, -1.2f, kStartOutput + kOutputRange * 0.2f));
- EXPECT_TRUE(CheckCurve(curve, -1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, -0.7f, kStartOutput + kOutputRange * 0.3f));
- EXPECT_TRUE(CheckCurve(curve, -0.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, -0.2f, kStartOutput + kOutputRange * 0.8f));
- EXPECT_TRUE(CheckCurve(curve, 0.0f, kEndOutput));
- EXPECT_TRUE(CheckCurve(curve, 1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 1.2f, kStartOutput + kOutputRange * 0.2f));
- EXPECT_TRUE(CheckCurve(curve, 1.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, 1.7f, kStartOutput + kOutputRange * 0.7f));
- EXPECT_TRUE(CheckCurve(curve, 2.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 3.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 4.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 4.2f, kStartOutput + kOutputRange * 0.2f));
- EXPECT_TRUE(CheckCurve(curve, 4.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, 4.7f, kStartOutput + kOutputRange * 0.7f));
-
- // Change Post-Infinity to OSCILLATE
- curve->set_post_infinity(Curve::OSCILLATE);
- EXPECT_TRUE(CheckCurve(curve, -1.7f, kStartOutput + kOutputRange * 0.7f));
- EXPECT_TRUE(CheckCurve(curve, -1.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, -1.2f, kStartOutput + kOutputRange * 0.2f));
- EXPECT_TRUE(CheckCurve(curve, -1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, -0.7f, kStartOutput + kOutputRange * 0.3f));
- EXPECT_TRUE(CheckCurve(curve, -0.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, -0.2f, kStartOutput + kOutputRange * 0.8f));
- EXPECT_TRUE(CheckCurve(curve, 0.0f, kEndOutput));
- EXPECT_TRUE(CheckCurve(curve, 1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 1.2f, kStartOutput + kOutputRange * 0.2f));
- EXPECT_TRUE(CheckCurve(curve, 1.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, 1.7f, kStartOutput + kOutputRange * 0.7f));
- EXPECT_TRUE(CheckCurve(curve, 2.0f, kEndOutput));
- EXPECT_TRUE(CheckCurve(curve, 3.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, 3.2f, kStartOutput + kOutputRange * 0.2f));
- EXPECT_TRUE(CheckCurve(curve, 3.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, 3.7f, kStartOutput + kOutputRange * 0.7f));
- EXPECT_TRUE(CheckCurve(curve, 4.0f, kEndOutput));
- EXPECT_TRUE(CheckCurve(curve, 4.2f, kStartOutput + kOutputRange * 0.8f));
- EXPECT_TRUE(CheckCurve(curve, 4.5f, kStartOutput + kOutputRange * 0.5f));
- EXPECT_TRUE(CheckCurve(curve, 4.7f, kStartOutput + kOutputRange * 0.3f));
-
- // Check Discontinuous Curves.
- CurveKey* key3 = curve->Create<LinearCurveKey>();
- CurveKey* key4 = curve->Create<LinearCurveKey>();
- ASSERT_TRUE(key3 != NULL);
- ASSERT_TRUE(key4 != NULL);
-
- const float kMidInput = 1.5f;
- const float kPreMidOutput = 3.0f;
- const float kPostMidOutput = 0.0f;
- const float kMidStartRange = kPreMidOutput - kStartOutput;
- const float kMidEndRange = kEndOutput - kPostMidOutput;
-
- // 5| E
- // 4| /
- // 3| PRE /
- // 2| / | /
- // 1| S |/
- // 0| POST
- // -+-----------
- // 1 0.5 2
-
- key3->SetOutput(kPreMidOutput);
- key3->SetInput(kMidInput);
- key4->SetOutput(kPostMidOutput);
- key4->SetInput(kMidInput);
-
- const float O2Output = kStartOutput + kMidStartRange * 0.2f * 2.0f;
- const float O3Output = kStartOutput + kMidStartRange * 0.3f * 2.0f;
- const float O49Output = kStartOutput + kMidStartRange * 0.49999f * 2.0f;
- const float O7Output = kPostMidOutput + kMidEndRange * 0.2f * 2.0f;
- const float O8Output = kPostMidOutput + kMidEndRange * 0.3f * 2.0f;
-
- EXPECT_TRUE(CheckCurve(curve, 1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.2f, O2Output));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.3f, O3Output));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.49999f, O49Output));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.5f, kPostMidOutput));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.7f, O7Output));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.8f, O8Output));
- EXPECT_TRUE(CheckCurve(curve, 2.0f, kEndOutput));
-
- // Check Pre-Infinity CYCLE_RELATIVE.
- curve->set_pre_infinity(Curve::CYCLE_RELATIVE);
- EXPECT_TRUE(CheckCurve(curve, -2.0f + 0.2f, O2Output - kOutputRange * 3.0f));
- EXPECT_TRUE(CheckCurve(curve, -2.0f + 0.3f, O3Output - kOutputRange * 3.0f));
- EXPECT_TRUE(CheckCurve(curve,
- -2.0f + 0.49999f,
- O49Output - kOutputRange * 3.0f));
- EXPECT_TRUE(CheckCurve(curve,
- -2.0f + 0.5f,
- kPostMidOutput - kOutputRange * 3.0f));
- EXPECT_TRUE(CheckCurve(curve, -2.0f + 0.7f, O7Output - kOutputRange * 3.0f));
- EXPECT_TRUE(CheckCurve(curve, -2.0f + 0.8f, O8Output - kOutputRange * 3.0f));
- EXPECT_TRUE(CheckCurve(curve, -1.0f, kStartOutput - kOutputRange * 2.0f));
- EXPECT_TRUE(CheckCurve(curve, 0.0f, kStartOutput - kOutputRange * 1.0f));
- EXPECT_TRUE(CheckCurve(curve, 1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.2f, O2Output));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.3f, O3Output));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.49999f, O49Output));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.5f, kPostMidOutput));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.7f, O7Output));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.8f, O8Output));
- EXPECT_TRUE(CheckCurve(curve, 2.0f, kEndOutput));
- EXPECT_TRUE(CheckCurve(curve, 3.0f, kStartOutput));
- // still oscillate..
- EXPECT_TRUE(CheckCurve(curve, 3.2f, O2Output));
- EXPECT_TRUE(CheckCurve(curve, 3.5f, kPostMidOutput));
- EXPECT_TRUE(CheckCurve(curve, 3.7f, O7Output));
- EXPECT_TRUE(CheckCurve(curve, 4.0f, kEndOutput));
- EXPECT_TRUE(CheckCurve(curve, 4.2f, O8Output));
- EXPECT_TRUE(CheckCurve(curve, 4.5f, kPostMidOutput));
- EXPECT_TRUE(CheckCurve(curve, 4.7f, O3Output));
-
- // Check Post-Infinity CYCLE_RELATIVE.
- curve->set_post_infinity(Curve::CYCLE_RELATIVE);
- EXPECT_TRUE(CheckCurve(curve, -2.0f + 0.2f, O2Output - kOutputRange * 3.0f));
- EXPECT_TRUE(CheckCurve(curve, -2.0f + 0.3f, O3Output - kOutputRange * 3.0f));
- EXPECT_TRUE(CheckCurve(curve,
- -2.0f + 0.49999f,
- O49Output - kOutputRange * 3.0f));
- EXPECT_TRUE(CheckCurve(curve,
- -2.0f + 0.5f,
- kPostMidOutput - kOutputRange * 3.0f));
- EXPECT_TRUE(CheckCurve(curve, -2.0f + 0.7f, O7Output - kOutputRange * 3.0f));
- EXPECT_TRUE(CheckCurve(curve, -2.0f + 0.8f, O8Output - kOutputRange * 3.0f));
- EXPECT_TRUE(CheckCurve(curve, -1.0f, kStartOutput - kOutputRange * 2.0f));
- EXPECT_TRUE(CheckCurve(curve, 0.0f, kStartOutput - kOutputRange * 1.0f));
- EXPECT_TRUE(CheckCurve(curve, 1.0f, kStartOutput));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.2f, O2Output));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.3f, O3Output));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.49999f, O49Output));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.5f, kPostMidOutput));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.7f, O7Output));
- EXPECT_TRUE(CheckCurve(curve, kStartInput + 0.8f, O8Output));
- EXPECT_TRUE(CheckCurve(curve, 2.0f, kEndOutput));
- EXPECT_TRUE(CheckCurve(curve, 3.0f, kEndOutput + kOutputRange * 1.0f));
- EXPECT_TRUE(CheckCurve(curve, 4.0f, kEndOutput + kOutputRange * 2.0f));
- EXPECT_TRUE(CheckCurve(curve, 4.0f + 0.2f, O2Output + kOutputRange * 3.0f));
- EXPECT_TRUE(CheckCurve(curve, 5.0f + 0.2f, O2Output + kOutputRange * 4.0f));
- EXPECT_TRUE(CheckCurve(curve, 5.0f + 0.3f, O3Output + kOutputRange * 4.0f));
- EXPECT_TRUE(CheckCurve(curve,
- 5.0f + 0.49999f,
- O49Output + kOutputRange * 4.0f));
- EXPECT_TRUE(CheckCurve(curve,
- 5.0f + 0.5f,
- kPostMidOutput + kOutputRange * 4.0f));
- EXPECT_TRUE(CheckCurve(curve, 5.0f + 0.7f, O7Output + kOutputRange * 4.0f));
- EXPECT_TRUE(CheckCurve(curve, 5.0f + 0.8f, O8Output + kOutputRange * 4.0f));
-}
-
-namespace {
-struct BezierKey {
- float input;
- float output;
- float in_tangent_x;
- float in_tangent_y;
- float out_tangent_x;
- float out_tangent_y;
-};
-
-struct ExpectedResult {
- float input; // in 24hz frames
- float output;
- float maya_output;
-};
-
-struct KeyInfo {
- unsigned num_keys;
- const BezierKey* keys;
- unsigned num_tests;
- const ExpectedResult* expected_results;
-};
-} // anonymous namespace
-
-static const BezierKey bezier_data_0[] = {
- { 0.083333f, 3, 0.013888f, -2.66667f, 0.152778f, 8.66667f, },
- { 0.291667f, 20, 0.222222f, -9.22377f, 0.388889f, 60.9133f, },
- { 0.583333f, -5, 0.486111f, 3.33333f, 0.680556f, -13.3333f, }
-};
-
-static const BezierKey bezier_data_1[] = {
- { 0.083333f, 3, 0.013888f, -2.66667f, 0.152778f, 8.66667f, },
- { 0.291667f, 20, 0.222222f, -9.22377f, 0.740598f, 19.9773f, },
- { 0.583333f, -5, 0.486111f, 3.33333f, 0.680556f, -13.3333f, },
-};
-
-static const ExpectedResult expected_results_0[] = {
- { 2.00f, 3.0524368f, 3.000000f, },
- { 3.00f, 4.1385164f, 4.139000f, },
- { 4.00f, 3.0155535f, 3.016000f, },
- { 5.00f, 3.0233288f, 3.023000f, },
- { 6.00f, 7.5540328f, 7.554000f, },
- { 7.00f, 19.727404f, 20.00000f, },
- { 8.00f, 31.934761f, 31.93500f, },
- { 9.00f, 34.393578f, 34.39400f, },
- { 10.0f, 29.960693f, 29.96100f, },
- { 11.0f, 21.220503f, 21.22100f, },
- { 12.0f, 10.757395f, 10.75700f, },
- { 13.0f, 1.1557499f, 1.156000f, },
- { 14.0f, -5.000000f, -5.00000f, },
-};
-
-static const ExpectedResult expected_results_1[] = {
- { 2.00f, 3.0524368f, 3.000000f, },
- { 3.00f, 4.1385164f, 4.139000f, },
- { 4.00f, 3.0155535f, 3.016000f, },
- { 5.00f, 3.0233288f, 3.023000f, },
- { 6.00f, 7.5540328f, 7.554000f, },
- { 7.00f, 19.727404f, 20.00000f, },
- { 8.00f, 19.946407f, 19.92800f, },
- { 9.00f, 19.764795f, 19.68200f, },
- { 10.0f, 19.417355f, 19.18900f, },
- { 11.0f, 18.804613f, 18.29900f, }, // TODO: fix so these match.
- { 12.0f, 17.725473f, 16.63900f, }, // notice these numbers don't match maya
- { 13.0f, 15.654317f, 12.23100f, }, // notice these numbers don't match maya
- { 14.0f, -5.000000f, -5.00000f, },
-};
-
-TEST_F(CurveTest, EvaluateBezierCurveKey) {
- const float kFrameRate = 24.0f;
-
- static const KeyInfo key_infos[] = {
- { arraysize(bezier_data_0), bezier_data_0,
- arraysize(expected_results_0), expected_results_0, },
- { arraysize(bezier_data_1), bezier_data_1,
- arraysize(expected_results_1), expected_results_1, },
- };
-
- for (unsigned tt = 0; tt < arraysize(key_infos); ++tt) {
- Curve* curve = pack()->Create<Curve>();
- ASSERT_TRUE(curve != NULL);
-
- // No cache since we want to evaluate the actual curves.
- curve->set_use_cache(false);
-
- const KeyInfo& key_info = key_infos[tt];
-
- for (unsigned ii = 0; ii < key_info.num_keys; ++ii) {
- const BezierKey& bezier_key = key_info.keys[ii];
- BezierCurveKey* key = curve->Create<BezierCurveKey>();
- key->SetInput(bezier_key.input);
- key->SetOutput(bezier_key.output);
- key->SetInTangent(Float2(bezier_key.in_tangent_x,
- bezier_key.in_tangent_y));
- key->SetOutTangent(Float2(bezier_key.out_tangent_x,
- bezier_key.out_tangent_y));
- }
-
- for (unsigned ii = 0; ii < key_info.num_tests; ++ii) {
- const ExpectedResult& expected_result = key_info.expected_results[ii];
- EXPECT_TRUE(CheckCurve(curve,
- expected_result.input / kFrameRate,
- expected_result.output));
- }
- }
-}
-
-// Tests the CurveFunctionContext in use.
-TEST_F(CurveTest, CurveFunctionContext) {
- Curve* curve = pack()->Create<Curve>();
- ASSERT_TRUE(curve != NULL);
-
- FunctionContext* context = curve->CreateFunctionContext();
- ASSERT_TRUE(context != NULL);
-
- // Create keys
- for (unsigned ii = 0; ii < 20; ++ii) {
- CurveKey* key = curve->Create<LinearCurveKey>();
- ASSERT_TRUE(key != NULL);
- key->SetInput(static_cast<float>(ii));
- key->SetOutput(static_cast<float>(ii * 2));
- }
-
- // Check the curve with linear access.
- for (unsigned ii = 0; ii < 39; ++ii) {
- EXPECT_TRUE(CheckCurveWithContext(curve,
- static_cast<float>(ii) * 0.5f,
- static_cast<float>(ii * 2) * 0.5f,
- context));
- }
-
- // Check the curve with semi random access.
- unsigned jj = 0;
- for (unsigned ii = 0; ii < 50; ++ii) {
- jj = (jj + 17) % 39;
- EXPECT_TRUE(CheckCurveWithContext(curve,
- static_cast<float>(jj) * 0.5f,
- static_cast<float>(jj * 2) * 0.5f,
- context));
- }
-
- delete context;
-}
-
-
-// Tests loading Curve from binary data
-
-// Sanity check on empty data
-TEST_F(CurveTest, CurveRawDataEmpty) {
- Curve* curve = pack()->Create<Curve>();
- ASSERT_TRUE(curve != NULL);
-
- uint8 p[2];
- MemoryReadStream read_stream(p, 0); // empty stream
-
- bool success = curve->LoadFromBinaryData(&read_stream);
-
- // Make sure we don't like to load from empty data
- EXPECT_FALSE(success);
-}
-
-// Sanity check on corrupt data
-TEST_F(CurveTest, CurveRawDataCorrupt) {
- Curve* curve = pack()->Create<Curve>();
- ASSERT_TRUE(curve != NULL);
-
- const int kDataLength = 256;
- uint8 p[kDataLength];
- for (int i = 0; i < kDataLength; ++i) p[i] = i; // not valid curve data
-
- MemoryReadStream read_stream(p, kDataLength);
-
- bool success = curve->LoadFromBinaryData(&read_stream);
-
- // Make sure we don't like to load from corrupt data
- EXPECT_FALSE(success);
-}
-
-// Sanity check on incomplete data
-TEST_F(CurveTest, CurveRawDataIncomplete) {
- Curve* curve = pack()->Create<Curve>();
- ASSERT_TRUE(curve != NULL);
-
- const int kDataLength = 512; // enough storage for test
- MemoryBuffer<uint8> buffer(kDataLength);
- MemoryWriteStream write_stream(buffer, kDataLength);
- write_stream.WriteLittleEndianInt32(1); // version 1
- write_stream.WriteByte(3); // bezier
- write_stream.WriteLittleEndianFloat32(3.4f);
- write_stream.WriteLittleEndianFloat32(1.7f);
- // but DON'T write the tangent data
-
- // make note of amount we've written
- size_t data_size = write_stream.GetStreamPosition();
-
- // try to load what we just created
- MemoryReadStream read_stream(buffer, data_size);
- bool success = curve->LoadFromBinaryData(&read_stream);
-
- // Make sure we don't like to load from incomplete data
- EXPECT_FALSE(success);
-}
-
-// Check that valid curve data loads OK
-TEST_F(CurveTest, CurveRawDataValid) {
- Curve* curve = pack()->Create<Curve>();
- ASSERT_TRUE(curve != NULL);
-
- // No cache since we want to evaluate the actual curves.
- curve->set_use_cache(false);
-
- const int kDataLength = 512; // enough storage for test
- MemoryBuffer<uint8> buffer(kDataLength);
- MemoryWriteStream write_stream(buffer, kDataLength);
-
- // write out serialization ID
- write_stream.Write(Curve::kSerializationID, 4);
-
- // write out version
- write_stream.WriteLittleEndianInt32(1);
-
- // Write out some bezier data (one that we tested above)
- size_t n = arraysize(bezier_data_0);
-
- for (size_t i = 0; i < n; ++i) {
- const BezierKey &key = bezier_data_0[i];
-
- write_stream.WriteByte(3); // bezier
- write_stream.WriteLittleEndianFloat32(key.input);
- write_stream.WriteLittleEndianFloat32(key.output);
- write_stream.WriteLittleEndianFloat32(key.in_tangent_x);
- write_stream.WriteLittleEndianFloat32(key.in_tangent_y);
- write_stream.WriteLittleEndianFloat32(key.out_tangent_x);
- write_stream.WriteLittleEndianFloat32(key.out_tangent_y);
- }
-
- // Make note of amount we've written
- size_t data_size = write_stream.GetStreamPosition();
-
- // Try to load what we just created
- MemoryReadStream read_stream(buffer, data_size);
- bool success = curve->LoadFromBinaryData(&read_stream);
-
- // Make sure curve data was accepted
- EXPECT_TRUE(success);
-
- // Validate some test points on curve
- size_t num_tests = arraysize(expected_results_0);
- const float kFrameRate = 24.0f;
- for (unsigned ii = 0; ii < num_tests; ++ii) {
- const ExpectedResult& expected_result = expected_results_0[ii];
- EXPECT_TRUE(CheckCurve(curve,
- expected_result.input / kFrameRate,
- expected_result.output));
- }
-
- // Now, let's try a very nice test to verify that we properly
- // serialize -- this is a round trip test
- MemoryBuffer<uint8> serialized_data;
- SerializeCurve(*curve, &serialized_data);
-
- // Make sure serialized data length is identical to what we made
- ASSERT_EQ(data_size, serialized_data.GetLength());
-
- // Make sure the data matches
- uint8 *original = buffer;
- uint8 *serialized = serialized_data;
- EXPECT_EQ(0, memcmp(original, serialized, data_size));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/ddsurfacedesc.h b/o3d/core/cross/ddsurfacedesc.h
deleted file mode 100644
index adc8ffd..0000000
--- a/o3d/core/cross/ddsurfacedesc.h
+++ /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.
- */
-
-
-// This file contains the structure definintions necessary for loading a DDS
-// image file (DirectDrawSurface). Using ths definition will prevent apps
-// from having to including "ddraw.h" from the DirectX SDK.
-
-#ifndef O3D_CORE_CROSS_GL_DDSURFACEDESC_H_
-#define O3D_CORE_CROSS_GL_DDSURFACEDESC_H_
-
-#include <build/build_config.h>
-
-#ifndef OS_WIN
-typedef uint16 WORD;
-typedef uint32 DWORD;
-typedef int8 BYTE;
-typedef int32 LONG;
-typedef void* LPVOID;
-#endif
-
-#define MAKEFOURCC(ch0, ch1, ch2, ch3) \
- ((DWORD)(BYTE)(ch0) | ((DWORD)(BYTE)(ch1) << 8) | \
- ((DWORD)(BYTE)(ch2) << 16) | ((DWORD)(BYTE)(ch3) << 24 ))
-
-#define FOURCC_DXT1 (MAKEFOURCC('D', 'X', 'T', '1'))
-#define FOURCC_DXT2 (MAKEFOURCC('D', 'X', 'T', '2'))
-#define FOURCC_DXT3 (MAKEFOURCC('D', 'X', 'T', '3'))
-#define FOURCC_DXT4 (MAKEFOURCC('D', 'X', 'T', '4'))
-#define FOURCC_DXT5 (MAKEFOURCC('D', 'X', 'T', '5'))
-
-/*
- * The surface will accept pixel data in the format specified
- * and compress it during the write.
- */
-#define DDPF_ALPHAPIXELS 0x00000001l
-#define DDPF_FOURCC 0x00000004L
-#define DDPF_RGB 0x00000040L
-#define DDPF_COMPRESSED 0x00000080L
-#define DDSCAPS_COMPLEX 0x00000008L
-#define DDSCAPS_MIPMAP 0x00400000L
-#define DDSCAPS_TEXTURE 0x00001000L
-#define DDSCAPS2_CUBEMAP 0x00000200L
-
-/*
- * These flags preform two functions:
- * - At CreateSurface time, they define which of the six cube faces are
- * required by the application.
- * - After creation, each face in the cubemap will have exactly one of these
- * bits set.
- */
-#define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400L
-#define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800L
-#define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000L
-#define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000L
-#define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000L
-#define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000L
-
-/*
- * This macro may be used to specify all faces of a cube map at
- * CreateSurface time.
- */
-#define DDSCAPS2_CUBEMAP_ALLFACES (DDSCAPS2_CUBEMAP_POSITIVEX | \
- DDSCAPS2_CUBEMAP_NEGATIVEX | \
- DDSCAPS2_CUBEMAP_POSITIVEY | \
- DDSCAPS2_CUBEMAP_NEGATIVEY | \
- DDSCAPS2_CUBEMAP_POSITIVEZ | \
- DDSCAPS2_CUBEMAP_NEGATIVEZ)
-
-namespace o3d {
-
-enum DDSD_FLAGS {
- DDSD_CAPS = 0x00000001l,
- DDSD_HEIGHT = 0x00000002l,
- DDSD_WIDTH = 0x00000004l,
- DDSD_PITCH = 0x00000008l,
- DDSD_BACKBUFFERCOUNT = 0x00000020l,
- DDSD_ZBUFFERBITDEPTH = 0x00000040l,
- DDSD_ALPHABITDEPTH = 0x00000080l,
- DDSD_LPSURFACE = 0x00000800l,
- DDSD_PIXELFORMAT = 0x00001000l,
- DDSD_CKDESTOVERLAY = 0x00002000l,
- DDSD_CKDESTBLT = 0x00004000l,
- DDSD_CKSRCOVERLAY = 0x00008000l,
- DDSD_CKSRCBLT = 0x00010000l,
- DDSD_MIPMAPCOUNT = 0x00020000l,
- DDSD_REFRESHRATE = 0x00040000l,
- DDSD_LINEARSIZE = 0x00080000l,
- DDSD_TEXTURESTAGE = 0x00100000l,
- DDSD_FVF = 0x00200000l,
- DDSD_SRCVBHANDLE = 0x00400000l,
- DDSD_DEPTH = 0x00800000l,
-};
-
-struct DDCOLORKEY {
- DWORD dwColorSpaceLowValue; // low boundary of Color Key, inclusive
- DWORD dwColorSpaceHighValue; // high boundary of Color Key, inclusive
-};
-
-struct DDPIXELFORMAT {
- DWORD dwSize; // size of structure
- DWORD dwFlags; // pixel format flags
- DWORD dwFourCC; // (FOURCC code)
- union {
- DWORD dwRGBBitCount; // how many bits per pixel
- DWORD dwYUVBitCount; // how many bits per pixel
- DWORD dwZBufferBitDepth; // how many total bits/pixel in z buffer
- // (including any stencil bits)
- DWORD dwAlphaBitDepth; // how many bits for alpha channels
- DWORD dwLuminanceBitCount; // how many bits per pixel
- DWORD dwBumpBitCount; // how many bits per "buxel", total
- DWORD dwPrivateFormatBitCount; // Bits per pixel of private driver formats.
- // Only valid in texture format list and if
- // DDPF_D3DFORMAT is set.
- };
- union {
- DWORD dwRBitMask; // mask for red bit
- DWORD dwYBitMask; // mask for Y bits
- DWORD dwStencilBitDepth; // how many stencil bits
- // (note:dwZBufferBitDepth-dwStencilBitDepth is
- // total Z-only bits)
- DWORD dwLuminanceBitMask; // mask for luminance bits
- DWORD dwBumpDuBitMask; // mask for bump map U delta bits
- DWORD dwOperations; // DDPF_D3DFORMAT Operations
- };
- union {
- DWORD dwGBitMask; // mask for green bits
- DWORD dwUBitMask; // mask for U bits
- DWORD dwZBitMask; // mask for Z bits
- DWORD dwBumpDvBitMask; // mask for bump map V delta bits
- struct {
- WORD wFlipMSTypes; // Multisample methods supported via flip for
- // this D3DFORMAT
- WORD wBltMSTypes; // Multisample methods supported via blt for
- // this D3DFORMAT
- } MultiSampleCaps;
- };
- union {
- DWORD dwBBitMask; // mask for blue bits
- DWORD dwVBitMask; // mask for V bits
- DWORD dwStencilBitMask; // mask for stencil bits
- DWORD dwBumpLuminanceBitMask; // mask for luminance in bump map
- };
- union {
- DWORD dwRGBAlphaBitMask; // mask for alpha channel
- DWORD dwYUVAlphaBitMask; // mask for alpha channel
- DWORD dwLuminanceAlphaBitMask; // mask for alpha channel
- DWORD dwRGBZBitMask; // mask for Z channel
- DWORD dwYUVZBitMask; // mask for Z channel
- };
-};
-
-struct DDSCAPS2 {
- DWORD dwCaps; // capabilities of surface wanted
- DWORD dwCaps2;
- DWORD dwCaps3;
- union {
- DWORD dwCaps4;
- DWORD dwVolumeDepth;
- };
-};
-
-struct DDSURFACEDESC2 {
- DWORD dwSize; // size of the DDSURFACEDESC structure
- DWORD dwFlags; // determines what fields are valid
- DWORD dwHeight; // height of surface to be created
- DWORD dwWidth; // width of input surface
- union {
- LONG lPitch; // distance to start of next line (return value only)
- DWORD dwLinearSize; // Formless late-allocated optimized surface size
- };
- union {
- DWORD dwBackBufferCount; // number of back buffers requested
- DWORD dwDepth; // the depth if this is a volume texture
- };
- union {
- DWORD dwMipMapCount; // number of mip-map levels requested
- // dwZBufferBitDepth removed, use ddpfPixelFormat
- // one instead
- DWORD dwRefreshRate; // refresh rate (used when display mode is described)
- DWORD dwSrcVBHandle; // The source used in VB::Optimize
- };
- DWORD dwAlphaBitDepth; // depth of alpha buffer requested
- DWORD dwReserved; // reserved
- DWORD lpSurface; // pointer to the associated surface memory
- union {
- DDCOLORKEY ddckCKDestOverlay; // color key for destination overlay
- DWORD dwEmptyFaceColor; // color for empty cubemap faces
- };
- DDCOLORKEY ddckCKDestBlt; // color key for destination blt use
- DDCOLORKEY ddckCKSrcOverlay; // color key for source overlay use
- DDCOLORKEY ddckCKSrcBlt; // color key for source blt use
- union {
- DDPIXELFORMAT ddpfPixelFormat; // format of the surface
- DWORD dwFVF; // format of vertex buffers
- };
- DDSCAPS2 ddsCaps; // direct draw surface capabilities
- DWORD dwTextureStage; // stage in multitexture cascade
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GL_DDSURFACEDESC_H_
diff --git a/o3d/core/cross/display_mode.h b/o3d/core/cross/display_mode.h
deleted file mode 100644
index 623f7a6..0000000
--- a/o3d/core/cross/display_mode.h
+++ /dev/null
@@ -1,115 +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 declaration of DisplayMode.
-
-#ifndef O3D_CORE_CROSS_DISPLAY_MODE_H_
-#define O3D_CORE_CROSS_DISPLAY_MODE_H_
-
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// A DisplayMode describes the size and refresh rate of a display mode; it's
-// usually used in [or when transitioning into] fullscreen mode. The id is a
-// platform-specific opaque identifier used to identify the mode when
-// requesting a fullscreen transition.
-class DisplayMode {
- public:
- DisplayMode()
- : width_(0),
- height_(0),
- refresh_rate_(0),
- id_(-1), // Since this is platform-specific, -1 may well be valid.
- valid_(false) {
- }
- void Set(int w, int h, int r, int i) {
- width_ = w;
- height_ = h;
- refresh_rate_ = r;
- id_ = i;
- valid_ = true;
- }
- DisplayMode(int w, int h, int r, int i) {
- Set(w, h, r, i);
- }
- DisplayMode(const DisplayMode& mode) {
- if (mode.valid()) {
- Set(mode.width(), mode.height(), mode.refresh_rate(), mode.id());
- } else {
- valid_ = false;
- }
- }
- DisplayMode& operator=(const DisplayMode& mode) {
- if (&mode != this) {
- if (mode.valid()) {
- Set(mode.width(), mode.height(), mode.refresh_rate(), mode.id());
- } else {
- valid_ = false;
- }
- }
- return *this;
- }
-
- int width() const {
- DCHECK(valid_);
- return width_;
- }
- int height() const {
- DCHECK(valid_);
- return height_;
- }
- int refresh_rate() const {
- DCHECK(valid_);
- return refresh_rate_;
- }
- int id() const {
- DCHECK(valid_);
- return id_;
- }
- bool valid() const { return valid_; }
-
- private:
- int width_;
- int height_;
- int refresh_rate_;
- int id_;
- bool valid_;
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_DISPLAY_MODE_H_
-
-
-
-
diff --git a/o3d/core/cross/display_window.h b/o3d/core/cross/display_window.h
deleted file mode 100644
index 834283c..0000000
--- a/o3d/core/cross/display_window.h
+++ /dev/null
@@ -1,56 +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.
- */
-
-
-// The DisplayWindow class is a platform-independent base class of a
-// platform's display window.
-
-#ifndef O3D_CORE_CROSS_DISPLAY_WINDOW_H_
-#define O3D_CORE_CROSS_DISPLAY_WINDOW_H_
-
-#include "base/basictypes.h"
-
-namespace o3d {
-class DisplayWindow {
- public:
- // Only subclasses can be instantiated.
- virtual ~DisplayWindow() = 0;
- protected:
- DisplayWindow() {}
- private:
- DISALLOW_COPY_AND_ASSIGN(DisplayWindow);
-};
-
-inline DisplayWindow::~DisplayWindow() {}
-
-} // end namespace o3d
-
-#endif // O3D_CORE_CROSS_DISPLAY_WINDOW_H_
diff --git a/o3d/core/cross/draw_context.cc b/o3d/core/cross/draw_context.cc
deleted file mode 100644
index 08e8f3a..0000000
--- a/o3d/core/cross/draw_context.cc
+++ /dev/null
@@ -1,69 +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 the DrawContext class. This class
-// contains two pre-defined Parameters: o3d.view, for the viewing
-// matrix, and o3d.projection, for the projection matrix. There
-// are convenience funtions for accessing these without looking them up
-// by name. These matrices are used by StandardParamMatrix4s, to implement
-// the SAS transform semantics. In addition, any user-defined
-// parameters added to the DrawContext will be made "global", ie.,
-// linked to all Shapes containing parameters of the same name, by
-// Node::GenerateRenderTreeGroup().
-
-#include "core/cross/draw_context.h"
-
-namespace o3d {
-
-const char* DrawContext::kViewParamName =
- O3D_STRING_CONSTANT("view");
-const char* DrawContext::kProjectionParamName =
- O3D_STRING_CONSTANT("projection");
-
-O3D_DEFN_CLASS(DrawContext, ParamObject);
-O3D_DEFN_CLASS(ParamDrawContext, RefParamBase);
-
-DrawContext::DrawContext(ServiceLocator* service_locator)
- : ParamObject(service_locator),
- weak_pointer_manager_(this) {
- RegisterParamRef(kViewParamName, &view_param_);
- RegisterParamRef(kProjectionParamName, &projection_param_);
-}
-
-ObjectBase::Ref DrawContext::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new DrawContext(service_locator));
-}
-
-ObjectBase::Ref ParamDrawContext::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamDrawContext(service_locator, false, false));
-}
-} // namespace o3d
diff --git a/o3d/core/cross/draw_context.h b/o3d/core/cross/draw_context.h
deleted file mode 100644
index ed29c6b..0000000
--- a/o3d/core/cross/draw_context.h
+++ /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 declarations for the DrawContext class. This class
-// contains two pre-defined Parameters: o3d.view, for the viewing
-// matrix, and o3d.projection, for the projection matrix. There
-// are convenience funtions for accessing these without looking them up
-// by name. These matrices are used by StandardParamMatrix4s, to implement
-// the SAS transform semantics. In addition, any user-defined
-// parameters added to the DrawContext will be made "global", ie.,
-// linked to all Shapes containing parameters of the same name, by
-// Node::GenerateRenderTreeGroup().
-
-#ifndef O3D_CORE_CROSS_DRAW_CONTEXT_H_
-#define O3D_CORE_CROSS_DRAW_CONTEXT_H_
-
-#include "core/cross/param_object.h"
-
-namespace o3d {
-
-class DrawContext : public ParamObject {
- public:
- typedef SmartPointer<DrawContext> Ref;
- typedef WeakPointer<DrawContext> WeakPointerType;
-
- static const char* kViewParamName;
- static const char* kProjectionParamName;
-
- // Gets the view matrix.
- const Matrix4 view() const {
- return view_param_->value();
- }
-
- // Sets the view matrix.
- void set_view(const Matrix4& value) {
- view_param_->set_value(value);
- }
-
- // Gets the projection matrix.
- const Matrix4 projection() const {
- return projection_param_->value();
- }
-
- // Sets the projection matrix.
- void set_projection(const Matrix4& value) {
- projection_param_->set_value(value);
- }
-
- // Gets a weak pointer to us.
- WeakPointerType GetWeakPointer() const {
- return weak_pointer_manager_.GetWeakPointer();
- }
-
- private:
- explicit DrawContext(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // Predefined view matrix parameter.
- ParamMatrix4::Ref view_param_;
-
- // Predefined projection matrix parameter.
- ParamMatrix4::Ref projection_param_;
-
- // Manager for weak pointers to us.
- WeakPointerType::WeakPointerManager weak_pointer_manager_;
-
- O3D_DECL_CLASS(DrawContext, ParamObject)
- DISALLOW_COPY_AND_ASSIGN(DrawContext);
-};
-
-class ParamDrawContext : public TypedRefParam<DrawContext> {
- public:
- typedef SmartPointer<ParamDrawContext> Ref;
-
- ParamDrawContext(ServiceLocator* service_locator,
- bool dynamic,
- bool read_only)
- : TypedRefParam<DrawContext>(service_locator, dynamic, read_only) {}
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamDrawContext, RefParamBase)
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_DRAW_CONTEXT_H_
diff --git a/o3d/core/cross/draw_element.cc b/o3d/core/cross/draw_element.cc
deleted file mode 100644
index 9d66c69..0000000
--- a/o3d/core/cross/draw_element.cc
+++ /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 contains the definition of DrawElement.
-
-#include "core/cross/draw_element.h"
-#include "core/cross/renderer.h"
-#include "core/cross/error.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(DrawElement, ParamObject);
-
-const char* DrawElement::kMaterialParamName =
- O3D_STRING_CONSTANT("material");
-
-ObjectBase::Ref DrawElement::Create(ServiceLocator* service_locator) {
- Renderer* renderer = service_locator->GetService<Renderer>();
- if (NULL == renderer) {
- O3D_ERROR(service_locator) << "No Render Device Available";
- return ObjectBase::Ref();
- }
-
- return ObjectBase::Ref(renderer->CreateDrawElement());
-}
-
-DrawElement::DrawElement(ServiceLocator* service_locator)
- : ParamObject(service_locator),
- owner_(NULL) {
- RegisterParamRef(kMaterialParamName, &material_param_ref_);
-}
-
-DrawElement::~DrawElement() {
-}
-
-void DrawElement::SetOwner(Element* new_owner) {
- // Hold a ref to ourselves so we make sure we don't get deleted while
- // as we remove ourself from our current owner.
- DrawElement::Ref temp(this);
-
- if (owner_ != NULL) {
- bool removed = owner_->RemoveDrawElement(this);
- DLOG_ASSERT(removed);
- }
-
- owner_ = new_owner;
-
- if (new_owner) {
- new_owner->AddDrawElement(this);
- }
-}
-} // namespace o3d
diff --git a/o3d/core/cross/draw_element.h b/o3d/core/cross/draw_element.h
deleted file mode 100644
index 69c6923..0000000
--- a/o3d/core/cross/draw_element.h
+++ /dev/null
@@ -1,94 +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 cotnains the declaration of DrawElement.
-
-#ifndef O3D_CORE_CROSS_DRAW_ELEMENT_H_
-#define O3D_CORE_CROSS_DRAW_ELEMENT_H_
-
-#include <vector>
-#include "core/cross/param_object.h"
-#include "core/cross/material.h"
-
-namespace o3d {
-
-class Element;
-
-// A DrawElement is what is actually "Drawn". It sits below a Element
-// and draws that Element with a different material. You can also override that
-// material/effect's params with params directly on the DrawElement.
-class DrawElement : public ParamObject {
- public:
- typedef SmartPointer<DrawElement> Ref;
-
- static const char* kMaterialParamName;
-
- explicit DrawElement(ServiceLocator* service_locator);
- virtual ~DrawElement();
-
- // Returns the Material object bound to the DrawElement.
- Material* material() const {
- return material_param_ref_->value();
- }
-
- // Binds an Material object to the Material.
- void set_material(Material* material) {
- material_param_ref_->set_value(material);
- }
-
- // Sets the owner for this DrawElement.
- // Parameters:
- // new_owner: Element to be our new owner. Pass in null to stop being owned.
- void SetOwner(Element* new_owner);
-
- Element* owner() const {
- return owner_;
- }
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamMaterial::Ref material_param_ref_; // Material to render with.
-
- Element* owner_; // our current owner.
-
- O3D_DECL_CLASS(DrawElement, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(DrawElement);
-};
-
-typedef std::vector<DrawElement*> DrawElementArray;
-typedef std::vector<DrawElement::Ref> DrawElementRefArray;
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_DRAW_ELEMENT_H_
diff --git a/o3d/core/cross/draw_element_test.cc b/o3d/core/cross/draw_element_test.cc
deleted file mode 100644
index 535bce6..0000000
--- a/o3d/core/cross/draw_element_test.cc
+++ /dev/null
@@ -1,78 +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 implements unit tests for class DrawElement.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/draw_element.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-
-namespace o3d {
-
-class DrawElementTest : public testing::Test {
- protected:
-
- DrawElementTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
-
- ServiceDependency<ObjectManager> object_manager_;
- Pack* pack_;
-};
-
-void DrawElementTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void DrawElementTest::TearDown() {
- pack_->Destroy();
-}
-
-TEST_F(DrawElementTest, Basic) {
- DrawElement* draw_element = pack()->Create<DrawElement>();
- // Check that draw_pass got created.
- EXPECT_TRUE(draw_element != NULL);
-
- // Check that the default parameters got created.
- EXPECT_TRUE(draw_element->GetParam<ParamMaterial>(
- DrawElement::kMaterialParamName) != NULL);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/draw_list.cc b/o3d/core/cross/draw_list.cc
deleted file mode 100644
index d4a9cd8..0000000
--- a/o3d/core/cross/draw_list.cc
+++ /dev/null
@@ -1,270 +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 definition of DrawList.
-
-#include "core/cross/draw_list.h"
-#include "core/cross/transformation_context.h"
-#include "core/cross/draw_list_manager.h"
-#include "core/cross/renderer.h"
-#include "core/cross/material.h"
-#include "core/cross/element.h"
-#include "core/cross/draw_element.h"
-#include "core/cross/render_context.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(DrawList, NamedObject);
-O3D_DEFN_CLASS(ParamDrawList, RefParamBase);
-
-// A DrawElementInfo is used to render an individual DrawElement
-// with a particular set of matrices.
-class DrawElementInfo {
- public:
- DrawElementInfo()
- : element_(NULL),
- draw_element_(NULL),
- material_(NULL),
- override_(NULL) {
- }
-
- void Set(const Matrix4& world,
- const Matrix4& world_view_projection,
- DrawElement* draw_element,
- Element* element,
- Material* material,
- ParamObject* override,
- ParamCache* param_cache) {
- world_ = world;
- world_view_projection_ = world_view_projection;
- draw_element_ = draw_element;
- element_ = element;
- material_ = material;
- override_ = override;
- param_cache_ = param_cache;
- priority_ = element->priority();
- effect_ = material->effect();
- state_ = material->state();
- // TODO: Since I'm pulling effect and state out here it would be
- // a small optmization to use these values in rendering since it's
- // possible they were pulled from a param chain. Still, it's unlikely
- // effect or state will have a complicted chain.
- }
- inline float priority() const {
- return priority_;
- }
- inline float z_value() const {
- return z_value_;
- }
- inline Effect* effect() const {
- return effect_;
- }
- inline State* state() const {
- return state_;
- }
- void ComputeZValue(TransformationContext* transformation_context) {
- if (element_->ParamsUsedByZSortHaveInputConnetions()) {
- transformation_context->set_world(world_);
- transformation_context->set_world_view_projection(world_view_projection_);
- }
- Float3 z_sort_point = element_->z_sort_point();
- z_value_ = (world_view_projection_ * Point3(z_sort_point[0],
- z_sort_point[1],
- z_sort_point[2])).getZ();
- }
- void Render(RenderContext* render_context,
- TransformationContext* transformation_context) {
- transformation_context->set_world(world_);
- transformation_context->set_world_view_projection(world_view_projection_);
- render_context->renderer()->RenderElement(element_,
- draw_element_,
- material_,
- override_,
- param_cache_);
- }
-
- private:
- Matrix4 world_;
- Matrix4 world_view_projection_;
- Element* element_;
- DrawElement* draw_element_;
- Material* material_;
- ParamObject* override_;
- ParamCache* param_cache_;
- float priority_; // pulled out for sorting
- float z_value_; // pulled out for sorting
- Effect* effect_; // pulled out for sorting
- State* state_; // pulled out for sorting
-};
-
-
-DrawList::DrawList(ServiceLocator* service_locator)
- : NamedObject(service_locator),
- transformation_context_(service_locator->
- GetService<TransformationContext>()),
- view_(Matrix4::identity()),
- projection_(Matrix4::identity()),
- top_draw_element_info_(0),
- global_index_(0),
- weak_pointer_manager_(this) {
- DrawListManager* draw_list_manager =
- service_locator->GetService<DrawListManager>();
- DCHECK(draw_list_manager);
- global_index_ = draw_list_manager->RegisterDrawList(this);
-}
-
-DrawList::~DrawList() {
- // delete all pass elements.
- DrawElementInfoArray::iterator end(draw_element_infos_.end());
- for (DrawElementInfoArray::iterator it(draw_element_infos_.begin());
- it != end;
- ++it) {
- delete (*it);
- }
-
- // Free our global index.
- DrawListManager* draw_list_manager =
- service_locator()->GetService<DrawListManager>();
- DCHECK(draw_list_manager);
- draw_list_manager->UnregisterDrawList(this);
-}
-
-ObjectBase::Ref DrawList::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new DrawList(service_locator));
-}
-
-void DrawList::Reset(const Matrix4& view, const Matrix4& projection) {
- view_ = view;
- projection_ = projection;
- top_draw_element_info_ = 0;
-}
-
-void DrawList::AddDrawElement(DrawElement* draw_element,
- Element* element,
- Material* material,
- ParamObject* override,
- ParamCache* param_cache,
- const Matrix4& world,
- const Matrix4& world_view_projection) {
- // DrawElementInfos only get created once and then reused forever. Then never
- // get freed until the DrawList gets destroyed. This saves lots of
- // allocations/deallocation that would otherwise happen every frame.
-
- // If I instead used size() then I would have to clear() draw_element_infos_
- // each frame which in turn would mean I'd need to keep a separate container
- // of DrawElementInfos to keep track of the pass elements I'm keeping around
- // and pulling them out of that container and putting them in this one.
-
- // Instead I just keep using the ones in this container and use
- // top_draw_element_info_ to track the highest used DrawElementInfo.
- while (top_draw_element_info_ >= draw_element_infos_.size()) {
- draw_element_infos_.push_back(new DrawElementInfo());
- }
- DrawElementInfo* pass_element =
- draw_element_infos_[top_draw_element_info_++];
- pass_element->Set(world,
- world_view_projection,
- draw_element,
- element,
- material,
- override,
- param_cache);
-}
-
-inline static bool CompareByPriority(const DrawElementInfo* lhs,
- const DrawElementInfo* rhs) {
- return lhs->priority() < rhs->priority();
-}
-
-inline static bool CompareByZValue(const DrawElementInfo* lhs,
- const DrawElementInfo* rhs) {
- return lhs->z_value() > rhs->z_value();
-}
-
-inline static bool CompareByPerformance(const DrawElementInfo* lhs,
- const DrawElementInfo* rhs) {
- int effectDif = lhs->effect() - rhs->effect();
-
- if (effectDif != 0) {
- return effectDif < 0;
- }
-
- return (lhs->state() - rhs->state()) < 0;
-}
-
-void DrawList::Render(RenderContext* render_context,
- SortMethod sort_method) {
- if (top_draw_element_info_ > 0) {
- // Set the view and projection to what they where when these draw elements
- // were put on this draw list.
- transformation_context_->set_view(view_);
- transformation_context_->set_projection(projection_);
- transformation_context_->set_view_projection(
- transformation_context_->projection() *
- transformation_context_->view());
-
- switch (sort_method) {
- case BY_Z_ORDER: {
- // Compute a Z value for each entry
- for (unsigned ii = 0; ii < top_draw_element_info_; ++ii) {
- draw_element_infos_[ii]->ComputeZValue(transformation_context_);
- }
- std::sort(draw_element_infos_.begin(),
- draw_element_infos_.begin() + top_draw_element_info_,
- CompareByZValue);
- break;
- }
- case BY_PRIORITY:
- std::sort(draw_element_infos_.begin(),
- draw_element_infos_.begin() + top_draw_element_info_,
- CompareByPriority);
- break;
- default: // BY_PERFORMANCE
- std::sort(draw_element_infos_.begin(),
- draw_element_infos_.begin() + top_draw_element_info_,
- CompareByPerformance);
- break;
- }
-
- // TODO: Since the ViewProjection never changes for this entire
- // list we could optmize by storing it in the client and changing
- // the SAS stuff to use that one.
- for (unsigned ii = 0; ii < top_draw_element_info_; ++ii) {
- draw_element_infos_[ii]->Render(render_context, transformation_context_);
- }
- }
-}
-
-ObjectBase::Ref ParamDrawList::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamDrawList(service_locator, false, false));
-}
-} // namespace o3d
diff --git a/o3d/core/cross/draw_list.h b/o3d/core/cross/draw_list.h
deleted file mode 100644
index e532426..0000000
--- a/o3d/core/cross/draw_list.h
+++ /dev/null
@@ -1,155 +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 declaration of DrawList.
-
-#ifndef O3D_CORE_CROSS_DRAW_LIST_H_
-#define O3D_CORE_CROSS_DRAW_LIST_H_
-
-#include <vector>
-#include "core/cross/param.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-class TransformationContext;
-class DrawElement;
-class DrawElementInfo;
-class Element;
-class Material;
-class ParamObject;
-class ParamCache;
-class RenderContext;
-
-// A DrawList is a list of things to render. It is filled out by a TreeTraversal
-// and is rendered by a DrawPass. A single DrawList can be filled out / added to
-// by multiple TreeTraversals. It can also be rendered by multiple DrawPasses.
-class DrawList : public NamedObject {
- public:
- typedef SmartPointer<DrawList> Ref;
- typedef WeakPointer<DrawList> WeakPointerType;
-
- ~DrawList();
-
- enum SortMethod {
- BY_PERFORMANCE = 0,
- BY_Z_ORDER = 1,
- BY_PRIORITY = 2,
- };
-
- // Resets the DrawList to have no elements.
- // Parameters:
- // view: View Matrix to use when drawing this list.
- // projection: Projection Matrix to use when drawing this list.
- void Reset(const Matrix4& view, const Matrix4& projection);
-
- // Adds a DrawElement to this DrawList.
- // Parameters:
- // draw_element: DrawElement for this DrawElement.
- // primitive: Primitive for this DrawElement.
- // material: Material to render this DrawElement.
- // override: ParamObject to override parameters for this DrawElement.
- // world: World Matrix to render this DrawElement.
- // world_view_projection: World View Projection Matrix to render this
- // DrawElement.
- void AddDrawElement(DrawElement* draw_element,
- Element* element,
- Material* material,
- ParamObject* override,
- ParamCache* param_cache,
- const Matrix4& world,
- const Matrix4& world_view_projection);
-
- // Render the elements of this DrawList.
- void Render(RenderContext* render_context, SortMethod sort_method);
-
- // Return the global index for this DrawList.
- unsigned int global_index() {
- return global_index_;
- }
-
- // Gets a weak pointer to us.
- WeakPointerType GetWeakPointer() const {
- return weak_pointer_manager_.GetWeakPointer();
- }
-
- private:
- explicit DrawList(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // We store draw element infos by pointer so they are easy to sort.
- typedef std::vector<DrawElementInfo*> DrawElementInfoArray;
-
- TransformationContext* transformation_context_;
-
- // The view matrix that was used when this list was filled out.
- Matrix4 view_;
-
- // The projection matrix that was used when this list was filled out.
- Matrix4 projection_;
-
- // Array to hold draw elements.
- DrawElementInfoArray draw_element_infos_;
-
- // The top (next to be used) draw element ifno.
- unsigned int top_draw_element_info_;
-
- // Index of this draw list in the client for quick lookup.
- unsigned int global_index_;
-
- // Manager for weak pointers to us.
- WeakPointerType::WeakPointerManager weak_pointer_manager_;
-
- O3D_DECL_CLASS(DrawList, NamedObject);
- DISALLOW_COPY_AND_ASSIGN(DrawList);
-};
-
-class ParamDrawList : public TypedRefParam<DrawList> {
- public:
- typedef SmartPointer<ParamDrawList> Ref;
-
- ParamDrawList(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedRefParam<DrawList>(service_locator, dynamic, read_only) {
- }
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamDrawList, RefParamBase);
- DISALLOW_COPY_AND_ASSIGN(ParamDrawList);
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_DRAW_LIST_H_
diff --git a/o3d/core/cross/draw_list_manager.cc b/o3d/core/cross/draw_list_manager.cc
deleted file mode 100644
index 44a02a4..0000000
--- a/o3d/core/cross/draw_list_manager.cc
+++ /dev/null
@@ -1,79 +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 "core/cross/draw_list_manager.h"
-#include "core/cross/draw_list.h"
-
-namespace o3d {
-
-const InterfaceId DrawListManager::kInterfaceId =
- InterfaceTraits<DrawListManager>::kInterfaceId;
-
-DrawListManager::DrawListManager(ServiceLocator* service_locator)
- : service_(service_locator, this) {}
-
-unsigned int DrawListManager::RegisterDrawList(DrawList* draw_list) {
- // Find a free global id.
- unsigned int index = 0;
- DrawListIndexMap::iterator end(draw_list_map_.end());
- for (DrawListIndexMap::iterator iter(draw_list_map_.begin());
- iter != end;
- ++iter) {
- if (iter->first != index) {
- break;
- }
- ++index;
- }
-
- // Save the global id so we know it's used.
- draw_list_map_.insert(std::make_pair(index, draw_list));
-
- return index;
-}
-
-void DrawListManager::UnregisterDrawList(DrawList* draw_list) {
- // Remove it from the client's Pass List map.
- DrawListIndexMap::iterator iter = draw_list_map_.find(
- draw_list->global_index());
- DLOG_ASSERT(iter != draw_list_map_.end());
- draw_list_map_.erase(iter);
-}
-
-void DrawListManager::Reset() {
- DrawListIndexMap::iterator end(draw_list_map_.end());
- for (DrawListIndexMap::iterator iter(draw_list_map_.begin());
- iter != end;
- ++iter) {
- iter->second->Reset(Matrix4::identity(), Matrix4::identity());
- }
-}
-} // namespace o3d
diff --git a/o3d/core/cross/draw_list_manager.h b/o3d/core/cross/draw_list_manager.h
deleted file mode 100644
index 33e0873..0000000
--- a/o3d/core/cross/draw_list_manager.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.
- */
-
-
-#ifndef O3D_CORE_CROSS_DRAW_LIST_MANAGER_H_
-#define O3D_CORE_CROSS_DRAW_LIST_MANAGER_H_
-
-#include <map>
-
-#include "core/cross/service_implementation.h"
-
-namespace o3d {
-
-class DrawList;
-
-class DrawListManager {
- public:
- static const InterfaceId kInterfaceId;
-
- explicit DrawListManager(ServiceLocator* service_locator);
-
- // Gets the lowest numbered unused DrawList index and adds it to the list of
- // used indices. These indices are used as an optimization at render time.
- // Then it registers the DrawList in the client's DrawList DB.
- // This is an internal function.
- // Parameters:
- // draw_list: Pass list to register.
- // Returns:
- // a global pass list index.
- unsigned int RegisterDrawList(DrawList* draw_list);
-
- // Removes the DrawList from the client's DrawList DB and frees its global
- // pass index that is no longer being used.
- // This is an internal function
- // Parameters:
- // draw_list: Pass list to register.
- void UnregisterDrawList(DrawList* draw_list);
-
- // Clear all the pass lists so they don't hold pointers across frames.
- void Reset();
-
- private:
- ServiceImplementation<DrawListManager> service_;
-
- // Keep a map of DrawLists to indices for optimizaion and so we can clear them
- // each frame. A raw pointer is safe because the constructor/destructor for
- // DrawList keeps this array valid.
- typedef std::map<unsigned int, DrawList*> DrawListIndexMap;
- DrawListIndexMap draw_list_map_;
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_DRAW_LIST_MANAGER_H_
diff --git a/o3d/core/cross/draw_list_test.cc b/o3d/core/cross/draw_list_test.cc
deleted file mode 100644
index 36ab6e3..0000000
--- a/o3d/core/cross/draw_list_test.cc
+++ /dev/null
@@ -1,82 +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 implements unit tests for class DrawList.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/draw_list.h"
-#include "core/cross/draw_list_manager.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/transformation_context.h"
-
-namespace o3d {
-
-class DrawListTest : public testing::Test {
- protected:
-
- DrawListTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
-
- ServiceDependency<ObjectManager> object_manager_;
- DrawListManager* draw_list_manager_;
- TransformationContext* transformation_context_;
- Pack* pack_;
-};
-
-void DrawListTest::SetUp() {
- draw_list_manager_ = new DrawListManager(g_service_locator);
- transformation_context_ = new TransformationContext(g_service_locator);
- pack_ = object_manager_->CreatePack();
-}
-
-void DrawListTest::TearDown() {
- pack_->Destroy();
- delete transformation_context_;
- delete draw_list_manager_;
-}
-
-TEST_F(DrawListTest, Basic) {
- DrawList* draw_list = pack()->Create<DrawList>();
- // Check that draw_list got created.
- EXPECT_TRUE(draw_list != NULL);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/draw_pass.cc b/o3d/core/cross/draw_pass.cc
deleted file mode 100644
index dd40f8a..0000000
--- a/o3d/core/cross/draw_pass.cc
+++ /dev/null
@@ -1,67 +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 definition of DrawPass.
-
-#include "core/cross/draw_pass.h"
-#include "core/cross/draw_list.h"
-#include "core/cross/transformation_context.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(DrawPass, RenderNode);
-
-const char* DrawPass::kDrawListParamName =
- O3D_STRING_CONSTANT("drawList");
-const char* DrawPass::kSortMethodParamName =
- O3D_STRING_CONSTANT("sortMethod");
-
-DrawPass::DrawPass(ServiceLocator* service_locator)
- : RenderNode(service_locator) {
- RegisterParamRef(kDrawListParamName, &draw_list_param_);
- RegisterParamRef(kSortMethodParamName, &sort_method_param_);
-}
-
-void DrawPass::Render(RenderContext* render_context) {
- DrawList* drawlist = draw_list();
- if (!drawlist) {
- return;
- }
-
- // Draw the elements of this list.
- drawlist->Render(render_context, sort_method());
-}
-
-ObjectBase::Ref DrawPass::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new DrawPass(service_locator));
-}
-} // namespace o3d
diff --git a/o3d/core/cross/draw_pass.h b/o3d/core/cross/draw_pass.h
deleted file mode 100644
index 60bb8e9..0000000
--- a/o3d/core/cross/draw_pass.h
+++ /dev/null
@@ -1,103 +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 declaration of DrawPass.
-
-#ifndef O3D_CORE_CROSS_DRAW_PASS_H_
-#define O3D_CORE_CROSS_DRAW_PASS_H_
-
-#include "core/cross/draw_context.h"
-#include "core/cross/draw_list.h"
-#include "core/cross/render_node.h"
-
-namespace o3d {
-
-class TransformationContext;
-class DrawList;
-class RenderContext;
-
-// A DrawPass is a RenderNode that renders a DrawList with a specific
-// DrawContext.
-class DrawPass : public RenderNode {
- public:
- typedef SmartPointer<DrawPass> Ref;
-
- static const char* kDrawListParamName;
- static const char* kSortMethodParamName;
-
- // Gets the draw list.
- DrawList* draw_list() const {
- return draw_list_param_->value();
- }
-
- // Sets the draw list.
- void set_draw_list(DrawList* value) {
- draw_list_param_->set_value(value);
- }
-
- // Gets the sort method.
- DrawList::SortMethod sort_method() const {
- return static_cast<DrawList::SortMethod>(sort_method_param_->value());
- }
-
- // Sets the sort method.
- void set_sort_method(DrawList::SortMethod value) {
- sort_method_param_->set_value(value);
- }
-
- // Renders this DrawPass.
- void Render(RenderContext* render_context);
-
- private:
- explicit DrawPass(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- TransformationContext* transformation_context_;
-
- // Predefined draw context parameter.
- ParamDrawContext::Ref draw_context_param_;
- ParamDrawList::Ref draw_list_param_; // DrawList we will render.
- ParamInteger::Ref sort_method_param_; // The order we will sort the DrawList.
-
- O3D_DECL_CLASS(DrawPass, RenderNode);
- DISALLOW_COPY_AND_ASSIGN(DrawPass);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_DRAW_PASS_H_
-
-
-
-
diff --git a/o3d/core/cross/draw_pass_test.cc b/o3d/core/cross/draw_pass_test.cc
deleted file mode 100644
index a82a39c..0000000
--- a/o3d/core/cross/draw_pass_test.cc
+++ /dev/null
@@ -1,82 +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 implements unit tests for class DrawPass.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/draw_pass.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/transformation_context.h"
-#include "core/cross/pack.h"
-
-namespace o3d {
-
-class DrawPassTest : public testing::Test {
- protected:
-
- DrawPassTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- TransformationContext* transformation_context_;
- Pack *pack_;
-};
-
-void DrawPassTest::SetUp() {
- transformation_context_ = new TransformationContext(g_service_locator);
- pack_ = object_manager_->CreatePack();
-}
-
-void DrawPassTest::TearDown() {
- object_manager_->DestroyPack(pack_);
- delete transformation_context_;
-}
-
-TEST_F(DrawPassTest, Basic) {
- DrawPass* draw_pass = pack()->Create<DrawPass>();
- // Check that draw_pass got created.
- EXPECT_TRUE(draw_pass != NULL);
-
- // Check that the default parameters got created.
- EXPECT_TRUE(draw_pass->GetParam<ParamDrawList>(
- DrawPass::kDrawListParamName) != NULL);
- EXPECT_TRUE(draw_pass->GetParam<ParamInteger>(
- DrawPass::kSortMethodParamName) != NULL);
-}
-} // namespace o3d
diff --git a/o3d/core/cross/effect.cc b/o3d/core/cross/effect.cc
deleted file mode 100644
index 152b03b..0000000
--- a/o3d/core/cross/effect.cc
+++ /dev/null
@@ -1,245 +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 definition of the Effect class.
-
-#include <cctype>
-#include <algorithm>
-#include "core/cross/effect.h"
-#include "core/cross/param_array.h"
-#include "core/cross/renderer.h"
-#include "core/cross/types.h"
-#include "core/cross/error.h"
-
-namespace o3d {
-
-namespace {
-struct EffectToUpper {
- char operator() (char c) const { return std::toupper(c); }
-};
-}
-
-EffectParameterInfo::EffectParameterInfo(
- const String& name,
- const ObjectBase::Class* class_type,
- int num_elements,
- const String& semantic,
- const ObjectBase::Class* sas_class_type)
- : name_(name),
- class_type_(class_type),
- num_elements_(num_elements),
- semantic_(semantic),
- sas_class_type_(sas_class_type) {
- // Apparently CG uppercases the semantics so we need to do the same
- // in D3D.
- std::transform(semantic_.begin(),
- semantic_.end(),
- semantic_.begin(),
- EffectToUpper());
-}
-
-O3D_DEFN_CLASS(Effect, ParamObject);
-O3D_DEFN_CLASS(ParamEffect, RefParamBase);
-
-const char* Effect::kVertexShaderEntryPointPrefix =
- "// #o3d VertexShaderEntryPoint ";
-const char* Effect::kFragmentShaderEntryPointPrefix =
- "// #o3d PixelShaderEntryPoint ";
-const char* Effect::kMatrixLoadOrderPrefix =
- "// #o3d MatrixLoadOrder ";
-
-Effect::Effect(ServiceLocator* service_locator)
- : ParamObject(service_locator),
- weak_pointer_manager_(this),
- matrix_load_order_(ROW_MAJOR) {
-}
-
-void Effect::CreateUniformParameters(ParamObject* param_object) {
- CreateSpecifiedParameters(param_object, false);
-}
-
-void Effect::CreateSASParameters(ParamObject* param_object) {
- CreateSpecifiedParameters(param_object, true);
-}
-
-// Creates parameters on a ParamObject corresponding to the internal effect
-// parameters.
-void Effect::CreateSpecifiedParameters(ParamObject* param_object, bool sas) {
- String errors;
- EffectParameterInfoArray param_infos;
- GetParameterInfo(&param_infos);
- for (unsigned ii = 0; ii < param_infos.size(); ++ii) {
- const EffectParameterInfo& param_info = param_infos[ii];
- if ((param_info.sas_class_type() != NULL) == sas) {
- Param* param = param_object->GetUntypedParam(param_info.name());
- if (param) {
- // Param exists. Is the the correct type?
- if (!param->IsA(param_info.class_type())) {
- // Remove it
- if (!param_object->RemoveParam(param)) {
- errors += "Could not remove param '" + param->name() +
- "' type '" + param->GetClassName() +
- "' on '" + param_object->name() +
- "' while trying to replace it with param of type '" +
- param_info.class_type()->name() + "' for Effect '" +
- name() + "'";
- } else {
- param = NULL;
- }
- }
- }
- if (!param) {
- const ObjectBase::Class* type = param_info.class_type();
- if (param_info.num_elements() == 0) {
- // Non-array type
- param = param_object->CreateParamByClass(
- param_info.name(),
- param_info.sas_class_type() ? param_info.sas_class_type() :
- param_info.class_type());
- } else {
- // Array type
- param =
- param_object->CreateParam<ParamParamArray>(param_info.name());
- }
- if (!param) {
- errors += String(errors.empty() ? "" : "\n") +
- String("Could not create Param '") + param_info.name() +
- String("' type '") + String(type->name()) +
- String(" for Effect '") + name() + "'";
- }
- }
- }
- }
- if (errors.length()) {
- O3D_ERROR(service_locator()) << errors;
- }
-}
-
-namespace {
-
-String::size_type GetEndOfIdentifier(const String& original,
- String::size_type start) {
- if (start < original.size()) {
- // check that first character is alpha or '_'
- if (isalpha(original[start]) || original[start] == '_') {
- String::size_type end = original.size();
- String::size_type position = start;
- while (position < end) {
- char c = original[position];
- if (!isalnum(c) && c != '_') {
- break;
- }
- ++position;
- }
- return position;
- }
- }
- return String::npos;
-}
-
-bool GetIdentifierAfterString(const String& original,
- const String& phrase,
- String* word) {
- String::size_type position = original.find(phrase);
- if (position == String::npos) {
- return false;
- }
-
- // Find end of identifier
- String::size_type start = position + phrase.size();
- String::size_type end = GetEndOfIdentifier(original, start);
- if (end != start && end != String::npos) {
- *word = String(original, start, end - start);
- return true;
- }
- return false;
-}
-
-} // anonymous namespace
-
-// TODO(gman): Replace this with the runtime shader parser.
-// For now it's very stupid. It requires the word "techinque" not appear
-// anywhere inside the file. Then it searches for
-//
-// // #o3d VertexShaderEntryPoint name
-// // #o3d PixelShaderEntryPoint name
-//
-// with that exact syntax. No extra whitespace.
-// If it doesn't find both it's a fails.
-bool Effect::ValidateFX(const String& effect,
- String* vertex_shader_entry_point,
- String* fragment_shader_entry_point,
- MatrixLoadOrder* matrix_load_order) {
- if (!GetIdentifierAfterString(effect,
- kVertexShaderEntryPointPrefix,
- vertex_shader_entry_point)) {
- O3D_ERROR(service_locator()) << "Failed to find \""
- << kVertexShaderEntryPointPrefix
- << "\" in Effect:" << effect;
- return false;
- }
- if (!GetIdentifierAfterString(effect,
- kFragmentShaderEntryPointPrefix,
- fragment_shader_entry_point)) {
- O3D_ERROR(service_locator()) << "Failed to find \""
- << kFragmentShaderEntryPointPrefix
- << "\" in Effect";
- return false;
- }
- String matrix_load_order_str;
- if (!GetIdentifierAfterString(effect,
- kMatrixLoadOrderPrefix,
- &matrix_load_order_str)) {
- O3D_ERROR(service_locator()) << "Failed to find \""
- << kMatrixLoadOrderPrefix
- << "\" in Effect";
- return false;
- }
- bool column_major = !strcmp(matrix_load_order_str.c_str(), "ColumnMajor");
- *matrix_load_order = column_major ? COLUMN_MAJOR : ROW_MAJOR;
-
- return true;
-}
-
-ObjectBase::Ref Effect::Create(ServiceLocator* service_locator) {
- Renderer* renderer = service_locator->GetService<Renderer>();
- if (NULL == renderer) {
- O3D_ERROR(service_locator) << "No Render Device Available";
- return ObjectBase::Ref();
- }
- return ObjectBase::Ref(renderer->CreateEffect());
-}
-
-ObjectBase::Ref ParamEffect::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamEffect(service_locator, false, false));
-}
-} // namespace o3d
diff --git a/o3d/core/cross/effect.h b/o3d/core/cross/effect.h
deleted file mode 100644
index 9336dc6..0000000
--- a/o3d/core/cross/effect.h
+++ /dev/null
@@ -1,279 +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 declaration to the Effect class.
-
-#ifndef O3D_CORE_CROSS_EFFECT_H_
-#define O3D_CORE_CROSS_EFFECT_H_
-
-#include <vector>
-#include "core/cross/param_object.h"
-#include "core/cross/param.h"
-#include "core/cross/stream.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-class Texture;
-class Transform;
-class ParamObject;
-
-// Used to return info about a parameter an effect needs.
-class EffectParameterInfo {
- public:
- EffectParameterInfo() : class_type_(NULL), sas_class_type_(NULL) {
- }
-
- // Parameters:
- // name: name of parameter.
- // class_type: type of parameter
- // num_elements: number of elements. Non-zero for array types, zero
- // for non-array types.
- // semantic: semantic.
- // sas_class_type: type of standard parameter to use for this param.
- EffectParameterInfo(const String& name,
- const ObjectBase::Class* class_type,
- int num_elements,
- const String& semantic,
- const ObjectBase::Class* sas_class_type);
-
- // Name of parameter.
- const String& name() const {
- return name_;
- }
-
- // Type of parameter.
- const ObjectBase::Class* class_type() const {
- return class_type_;
- }
-
- // Number of elements.
- int num_elements() const {
- return num_elements_;
- }
-
- // The semantic is always in upper case.
- const String& semantic() const {
- return semantic_;
- }
-
- // If this is a Standard Parameter (SAS) this will be a class.
- // Otherwise it will be NULL.
- const ObjectBase::Class* sas_class_type () const {
- return sas_class_type_;
- }
-
- private:
- String name_;
- const ObjectBase::Class* class_type_;
- int num_elements_;
- String semantic_;
- const ObjectBase::Class* sas_class_type_;
-};
-
-typedef std::vector<EffectParameterInfo> EffectParameterInfoArray;
-
-// Used to return info about a Stream an effect needs.
-class EffectStreamInfo {
- public:
- EffectStreamInfo()
- : semantic_(Stream::UNKNOWN_SEMANTIC),
- semantic_index_(0) {
- }
-
- EffectStreamInfo(Stream::Semantic semantic,
- int semantic_index)
- : semantic_(semantic),
- semantic_index_(semantic_index) {
- }
-
- // Get the semantic associated with the Stream.
- Stream::Semantic semantic() const {
- return semantic_;
- }
-
- // Get the semantic index associated with the Stream.
- int semantic_index() const {
- return semantic_index_;
- }
-
- private:
- Stream::Semantic semantic_;
- int semantic_index_;
-};
-
-typedef std::vector<EffectStreamInfo> EffectStreamInfoArray;
-
-// An Effect object carries all the settings needed to
-// completely specify a full graphics pipeline, from culling at the
-// beginning to blending at the end. An Effect contains the vertex and fragment
-// shader.
-class Effect : public ParamObject {
- public:
- typedef SmartPointer<Effect> Ref;
- typedef WeakPointer<Effect> WeakPointerType;
-
- // The MatrixLoadOrder is the order in which Matrix parameters are
- // loaded to the GPU.
- // ROW_MAJOR means matrix[0] represents the first row of the matrix. This
- // format is used when doing matrix/vector multiplication as mul(v, M).
- // COLUMN_MAJOR means matrix[0] represents the first column of the matrix.
- // This format is used when doing matrix/vector multiplication as mul(M, v),
- // and usually requires the Matrix parameter to be transposed on load.
- enum MatrixLoadOrder {
- ROW_MAJOR,
- COLUMN_MAJOR,
- };
-
- static const char* kVertexShaderEntryPointPrefix;
- static const char* kFragmentShaderEntryPointPrefix;
- static const char* kMatrixLoadOrderPrefix;
-
- // Accessor for effect source.
- const String& source() {
- return source_;
- }
-
- // Loads the vertex and fragment shader programs from an string containing
- // a DirectX FX description.
- virtual bool LoadFromFXString(const String& effect) = 0;
-
- // For each of the effect's uniform parameters, creates corresponding
- // parameters on the given ParamObject. Skips SAS Parameters.
- // Parameters:
- // param_object: object that will hold the created params
- void CreateUniformParameters(ParamObject* param_object);
-
- // For each of the effect's uniform parameters, if it is a SAS parameter
- // creates corresponding StandardParamMatrix4 parameters on the given
- // ParamObject.
- // Parameters:
- // param_object: object that will hold the created params
- void CreateSASParameters(ParamObject* param_object);
-
- // Gets a weak pointer to us.
- WeakPointerType GetWeakPointer() const {
- return weak_pointer_manager_.GetWeakPointer();
- }
- // Gets info about the parameters this effect needs.
- // Parameters:
- // info_array: EffectParameterInfoArray to receive info.
- virtual void GetParameterInfo(EffectParameterInfoArray* info_array) = 0;
-
- // Gets info about the varying parameters this effects vertex shader needs.
- // Parameters:
- // info_array: EffectParameterInfoArray to receive info.
- virtual void GetStreamInfo(EffectStreamInfoArray* info_array) = 0;
-
- // Sets the order that matrices will be loaded to the GPU for this effect
- // (row major or column major).
- // Parameters:
- // matrix_load_order: ROW_MAJOR or COLUMN_MAJOR
- void set_matrix_load_order(MatrixLoadOrder matrix_load_order) {
- matrix_load_order_ = matrix_load_order;
- }
-
- // Gets the order that matrices will be loaded to the GPU for this effect
- // (row major or column major).
- MatrixLoadOrder matrix_load_order() const {
- return matrix_load_order_;
- }
-
- // Validates an effect meaning parse the effect and verify it does not
- // break any o3d rules. For example it must NOT have any technique
- // or render states or texture generation or sampler statements etc and it
- // must have the o3d entry point specification.
- // Parameters:
- // effect: Effect string in o3d format.
- // vertex_shader_entry_point: String to receive name of vertex shader entry
- // point.
- // fragment_shader_entry_point: String to receive name of fragment
- // shader entry point.
- // Returns:
- // true if effect was valid.
- bool ValidateFX(const String& effect,
- String* vertex_shader_entry_point,
- String* fragment_shader_entry_point,
- MatrixLoadOrder* matrix_load_order);
-
- protected:
- explicit Effect(ServiceLocator* service_locator);
-
- // Accessor for source.
- void set_source(const String& source) {
- source_ = source;
- }
-
- // For each of the effect's uniform parameters, creates corresponding
- // parameters on the given ParamObject. Creates SAS or non-SAS only
- // depending on the sas argument.
- // Parameters:
- // param_object: object that will hold the created params.
- // sas: true means create only SAS params. false means create only non-SAS
- // params.
- void CreateSpecifiedParameters(ParamObject* param_object, bool sas);
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // Manager for weak pointers to us.
- WeakPointerType::WeakPointerManager weak_pointer_manager_;
- MatrixLoadOrder matrix_load_order_;
-
- // The source for the shaders on this effect.
- String source_;
-
- O3D_DECL_CLASS(Effect, NamedObject);
- DISALLOW_COPY_AND_ASSIGN(Effect);
-}; // Effect
-
-// Array container for Effect pointers
-typedef std::vector<Effect*> EffectArray;
-
-class ParamEffect : public TypedRefParam<Effect> {
- public:
- typedef SmartPointer<ParamEffect> Ref;
-
- ParamEffect(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedRefParam<Effect>(service_locator, dynamic, read_only) {}
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamEffect, RefParamBase);
- DISALLOW_COPY_AND_ASSIGN(ParamEffect);
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_EFFECT_H_
diff --git a/o3d/core/cross/effect_test.cc b/o3d/core/cross/effect_test.cc
deleted file mode 100644
index f301b61..0000000
--- a/o3d/core/cross/effect_test.cc
+++ /dev/null
@@ -1,505 +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 "tests/common/win/testing_common.h"
-#include "core/cross/client.h"
-#include "core/cross/effect.h"
-#include "core/cross/image_utils.h"
-#include "core/cross/pack.h"
-#include "core/cross/param_array.h"
-#include "core/cross/primitive.h"
-#include "core/cross/sampler.h"
-#include "core/cross/standard_param.h"
-#include "core/cross/stream.h"
-#include "core/cross/texture_base.h"
-
-namespace o3d {
-
-class EffectTest : public testing::Test {
- protected:
-
- EffectTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- ObjectManager* object_manager() { return object_manager_.Get(); }
- Client* client() { return client_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- Client *client_;
-};
-
-void EffectTest::SetUp() {
- client_ = new Client(g_service_locator);
- client_->Init();
-}
-
-void EffectTest::TearDown() {
- delete client_;
-}
-
-// ----------------------------------------------------------------------------
-
-namespace {
-
-#if defined(RENDERER_GLES2)
-
-char kLambertEffect[] =
- "attribute vec4 position; // : POSITION; \n"
- "attribute vec3 normal; // : NORMAL; \n"
- "attribute vec2 texcoord1; // : TEXCOORD1; \n"
- " \n"
- "uniform mat4 worldViewProjection; // : WorldViewProjection; \n"
- "uniform mat4 world; // : World; \n"
- "uniform mat4 worldInverseTranspose; // : WorldInverseTranspose; \n"
- "uniform vec3 lightWorldPos; \n"
- " \n"
- "varying vec3 v_n; // : TEXCOORD1; \n"
- "varying vec3 v_l; // : TEXCOORD2; \n"
- "varying vec2 v_diffuseUV; // : TEXCOORD0; \n"
- " \n"
- "void main() { \n"
- " gl_Position = worldViewProjection * position; \n"
- " v_n = (worldInverseTranspose * vec4(normal, 0)).xyz; \n"
- " v_l = lightWorldPos - (world * position).xyz; \n"
- " v_diffuseUV = texcoord1; \n"
- "} \n"
- " \n"
- "// This hack is here for now since O3D only allows one string \n"
- "// to be passed to Effect::loadFromFXString \n"
- "// #o3d SplitMarker \n"
- " \n"
- "uniform vec4 lightColor; \n"
- "uniform vec4 emissive; \n"
- "uniform vec4 ambient; \n"
- "uniform sampler2D diffuseSampler; \n"
- " \n"
- "varying vec3 v_n; // : TEXCOORD1; \n"
- "varying vec3 v_l; // : TEXCOORD2; \n"
- "varying vec2 v_diffuseUV; // : TEXCOORD0; \n"
- " \n"
- "void main() { \n"
- " vec4 diffuse = texture2D(diffuseSampler, v_diffuseUV); \n"
- " vec3 l = normalize(v_l); \n"
- " vec3 n = normalize(v_n); \n"
- " vec4 litR = vec4(dot(n,l),0,0,0); // fixme hack! \n"
- " gl_FragColor = emissive+lightColor*(ambient+diffuse*litR.y); \n"
- "} \n"
- "// #o3d MatrixLoadOrder RowMajor \n"
- "";
-
-#else
-
-char kLambertEffect[] =
- "struct a2v { \n"
- "float4 pos : POSITION; \n"
- "float3 normal : NORMAL; \n"
- "float2 diffuseUV : TEXCOORD1; \n"
- "}; \n"
- "struct v2f { \n"
- "float4 pos : POSITION; \n"
- "float3 n : TEXCOORD1; \n"
- "float3 l : TEXCOORD2; \n"
- "float2 diffuseUV : TEXCOORD0; \n"
- "}; \n"
- "float4x4 worldViewProj : WorldViewProjection; \n"
- "float4x4 world : World; \n"
- "float4x4 worldIT : WorldInverseTranspose; \n"
- "float3 lightWorldPos; \n"
- "float4 lightColor; \n"
- "uniform float4 emissive; \n"
- "uniform float4 ambient; \n"
- "uniform float array[8]; \n"
- "uniform extern texture diffuseTexture; \n"
- "sampler2D diffuseSampler = sampler_state { \n"
- " Texture = <diffuseTexture>; \n"
- "}; \n"
- "v2f vsMain(a2v IN) { \n"
- " v2f OUT; \n"
- " OUT.pos = mul(IN.pos, worldViewProj); \n"
- " OUT.n = mul(float4(IN.normal, 0), worldIT).xyz; \n"
- " OUT.l = lightWorldPos - mul(IN.pos, world).xyz; \n"
- " OUT.diffuseUV = IN.diffuseUV; \n"
- " return OUT; \n"
- "} \n"
- "float4 fsMain(v2f IN): COLOR { \n"
- " float4 diffuse = tex2D(diffuseSampler, IN.diffuseUV); \n"
- " float3 l = normalize(IN.l); \n"
- " float3 n = normalize(IN.n); \n"
- " float4 litR = lit(dot(n,l),0,0); \n"
- " return emissive+lightColor*(ambient+diffuse*litR.y); \n"
- "} \n"
- "// #o3d VertexShaderEntryPoint vsMain \n"
- "// #o3d PixelShaderEntryPoint fsMain \n"
- "// #o3d MatrixLoadOrder RowMajor \n"
- "";
-
-#endif
-
-struct ParamInfo {
- const char* name;
- const ObjectBase::Class* type;
- int num_elements;
- const char* semantic;
- const ObjectBase::Class* sas_type;
-};
-
-#if defined(RENDERER_GLES2)
-ParamInfo expected_params[] = {
- { "lightWorldPos", ParamFloat3::GetApparentClass(), 0, "", NULL, },
- { "lightColor", ParamFloat4::GetApparentClass(), 0, "", NULL, },
- { "emissive", ParamFloat4::GetApparentClass(), 0, "", NULL, },
- { "ambient", ParamFloat4::GetApparentClass(), 0, "", NULL, },
- { "diffuseSampler", ParamSampler::GetApparentClass(), 0, "", NULL, },
- { "worldViewProjection", ParamMatrix4::GetApparentClass(), 0,
- "WORLDVIEWPROJECTION",
- WorldViewProjectionParamMatrix4::GetApparentClass(), },
- { "world", ParamMatrix4::GetApparentClass(), 0,
- "WORLD", WorldParamMatrix4::GetApparentClass(), },
- { "worldInverseTranspose", ParamMatrix4::GetApparentClass(), 0,
- "WORLDINVERSETRANSPOSE",
- WorldInverseTransposeParamMatrix4::GetApparentClass(), },
-};
-#else
-ParamInfo expected_params[] = {
- { "lightWorldPos", ParamFloat3::GetApparentClass(), 0, "", NULL, },
- { "lightColor", ParamFloat4::GetApparentClass(), 0, "", NULL, },
- { "emissive", ParamFloat4::GetApparentClass(), 0, "", NULL, },
- { "ambient", ParamFloat4::GetApparentClass(), 0, "", NULL, },
- { "array", ParamFloat::GetApparentClass(), 8, "", NULL, },
- { "diffuseTexture", ParamTexture::GetApparentClass(), 0, "", NULL, },
- { "diffuseSampler", ParamSampler::GetApparentClass(), 0, "", NULL, },
- { "worldViewProj", ParamMatrix4::GetApparentClass(), 0, "WORLDVIEWPROJECTION",
- WorldViewProjectionParamMatrix4::GetApparentClass(), },
- { "world", ParamMatrix4::GetApparentClass(), 0, "WORLD",
- WorldParamMatrix4::GetApparentClass(), },
- { "worldIT", ParamMatrix4::GetApparentClass(), 0, "WORLDINVERSETRANSPOSE",
- WorldInverseTransposeParamMatrix4::GetApparentClass(), },
-};
-#endif
-
-EffectStreamInfo expected_streams[] = {
- EffectStreamInfo(Stream::POSITION, 0),
- EffectStreamInfo(Stream::NORMAL, 0),
- EffectStreamInfo(Stream::TEXCOORD, 1)
-};
-
-float kVertexBlock[][4] = {
- { -1, 1, 0, 1, },
- { 1, 1, 0, 1, },
- { -1, -1, 0, 1, },
- { 1, -1, 0, 1, },
-};
-
-float kColorBlock[][3] = {
- { 1, 0, 0, },
- { 1, 1, 0, },
- { 0, 1, 0, },
- { 0, 0, 1, },
-};
-
-uint32 kIndexBlock[4] = {
- 0, 1, 2, 3
-};
-
-bool IsExpectedParamInfo(const EffectParameterInfo& info) {
- for (unsigned ii = 0; ii < arraysize(expected_params); ++ii) {
- const ParamInfo& expected_info = expected_params[ii];
- if (info.name().compare(expected_info.name) == 0) {
- return info.class_type() == expected_info.type &&
- info.semantic().compare(expected_info.semantic) == 0 &&
- info.sas_class_type() == expected_info.sas_type;
- }
- }
- return false;
-}
-
-bool IsExpectedStream(const EffectStreamInfo& info) {
- for (unsigned ii = 0; ii < arraysize(expected_streams); ++ii) {
- const EffectStreamInfo& expected_info = expected_streams[ii];
- if (info.semantic() == expected_info.semantic() &&
- info.semantic_index() == expected_info.semantic_index()) {
- return true;
- }
- }
- return false;
-}
-
-} // anonymous namespace.
-
-TEST_F(EffectTest, LogOpenGLCalls) {
- // TODO(o3d): Find a way to implement a Mocklog object under
- // Googleclient. The code would be of the usual form:
- //
- // ScopedMockLog log;
- // EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
- // EXPECT_CALL(log, LOG(INFO, _, StartsWith("EffectGL created:"));
- //
- // In the mean time, work directly on the actual log file itself:
-
- Pack* pack = object_manager()->CreatePack();
-
- Shape* shape = pack->Create<Shape>();
- ASSERT_TRUE(shape != NULL);
- client()->root()->AddShape(shape);
- Primitive* primitive = pack->Create<Primitive>();
- ASSERT_TRUE(primitive != NULL);
- primitive->SetOwner(shape);
-
- // Load the vertex and fragment shaders.
- Effect *fx = pack->Create<Effect>();
- ASSERT_TRUE(fx != NULL);
- EXPECT_TRUE(fx->LoadFromFXString(String(kLambertEffect)));
- EXPECT_TRUE(!fx->source().compare(kLambertEffect));
- Material* material = pack->Create<Material>();
- ASSERT_TRUE(material);
- material->set_effect(fx);
- primitive->set_material(material);
-
- // TODO(o3d): Test the log file.
-
- // Clean up.
- object_manager()->DestroyPack(pack);
-}
-
-TEST_F(EffectTest, CreateAndDestroyEffect) {
- Pack* pack = object_manager()->CreatePack();
-
- Shape* shape = pack->Create<Shape>();
- ASSERT_TRUE(shape != NULL);
- client()->root()->AddShape(shape);
- Primitive* primitive = pack->Create<Primitive>();
- ASSERT_TRUE(primitive != NULL);
- primitive->SetOwner(shape);
-
- // load an effect
- Effect *fx = pack->Create<Effect>();
- ASSERT_TRUE(fx != NULL);
- EXPECT_TRUE(fx->LoadFromFXString(String(kLambertEffect)));
- Material* material = pack->Create<Material>();
- ASSERT_TRUE(material);
- material->set_effect(fx);
- primitive->set_material(material);
- StreamBank* stream_bank = pack->Create<StreamBank>();
- ASSERT_TRUE(stream_bank != NULL);
- primitive->set_stream_bank(stream_bank);
-
- VertexBuffer* verts = pack->Create<VertexBuffer>();
- VertexBuffer* color = pack->Create<VertexBuffer>();
- IndexBuffer* index = pack->Create<IndexBuffer>();
-
- ASSERT_TRUE(verts != NULL);
- ASSERT_TRUE(color != NULL);
- ASSERT_TRUE(index != NULL);
-
- Field* vertex_field = verts->CreateField(FloatField::GetApparentClass(),
- arraysize(kVertexBlock[0]));
- ASSERT_TRUE(vertex_field != NULL);
- ASSERT_TRUE(verts->AllocateElements(arraysize(kVertexBlock)));
- vertex_field->SetFromFloats(&kVertexBlock[0][0], arraysize(kVertexBlock[0]),
- 0, arraysize(kVertexBlock));
-
- Field* color_field = color->CreateField(FloatField::GetApparentClass(),
- arraysize(kColorBlock[0]));
- ASSERT_TRUE(color_field != NULL);
- ASSERT_TRUE(color->AllocateElements(arraysize(kColorBlock)));
- color_field->SetFromFloats(&kColorBlock[0][0], arraysize(kColorBlock[0]), 0,
- arraysize(kColorBlock));
-
- EXPECT_TRUE(index->AllocateElements(arraysize(kIndexBlock)));
- index->index_field()->SetFromUInt32s(&kIndexBlock[0], 1, 0,
- arraysize(kIndexBlock));
-
- EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION,
- 0,
- vertex_field,
- 0));
- EXPECT_TRUE(stream_bank->SetVertexStream(Stream::COLOR,
- 0,
- color_field,
- 0));
- primitive->set_index_buffer(index);
-
- // Create effect parameters.
-
- ParamFloat3 *lightpos =
- shape->CreateParam<ParamFloat3>("lightworldPos");
- EXPECT_TRUE(lightpos != NULL);
- lightpos->set_value(Float3(0.2f, 10.5f, -3.14f));
-
- ParamFloat4 *lightcolor =
- shape->CreateParam<ParamFloat4>("lightColor");
- EXPECT_TRUE(lightcolor != NULL);
- lightcolor->set_value(Float4(0.8f, 0.2f, 0.655f, 1.0f));
-
- ParamFloat4 *emissive =
- shape->CreateParam<ParamFloat4>("emissive");
- EXPECT_TRUE(emissive != NULL);
- emissive->set_value(Float4(0.0f, 0.0f, 0.0f, 1.0f));
-
- ParamFloat4 *ambient =
- shape->CreateParam<ParamFloat4>("ambient");
- EXPECT_TRUE(ambient != NULL);
- ambient->set_value(Float4(0.25f, 0.25f, 0.35f, 1.0f));
-
- String filepath = *g_program_path + "/unittest_data/rock01.tga";
- Texture *texture = pack->CreateTextureFromFile(filepath,
- filepath,
- image::TGA,
- true);
- EXPECT_TRUE(texture != NULL);
-
- ParamTexture * diffuse_texture =
- shape->CreateParam<ParamTexture>("diffuseTexture");
- EXPECT_TRUE(diffuse_texture != NULL);
- diffuse_texture->set_value(texture);
-
- // Clean up.
- object_manager()->DestroyPack(pack);
-}
-
-TEST_F(EffectTest, GetEffectParameters) {
- Pack* pack = object_manager()->CreatePack();
- ASSERT_TRUE(pack != NULL);
-
- // load an effect
- Effect *fx = pack->Create<Effect>();
- ASSERT_TRUE(fx != NULL);
- EXPECT_TRUE(fx->LoadFromFXString(String(kLambertEffect)));
-
- // Check that we get the correct params
- EffectParameterInfoArray info;
- fx->GetParameterInfo(&info);
- EXPECT_EQ(arraysize(expected_params), info.size());
-
- for (EffectParameterInfoArray::size_type ii = 0; ii < info.size(); ++ii) {
- EXPECT_TRUE(IsExpectedParamInfo(info[ii]));
- }
-
- // Clean up.
- object_manager()->DestroyPack(pack);
-}
-
-TEST_F(EffectTest, CreateUniformParameters) {
- Pack* pack = object_manager()->CreatePack();
- ASSERT_TRUE(pack != NULL);
-
- // load an effect
- Effect *fx = pack->Create<Effect>();
- ASSERT_TRUE(fx != NULL);
- EXPECT_TRUE(fx->LoadFromFXString(String(kLambertEffect)));
-
- ParamObject* param_object = pack->Create<ParamObject>();
- ASSERT_TRUE(param_object != NULL);
-
- // Check that we get the correct params
- fx->CreateUniformParameters(param_object);
-
- for (unsigned ii = 0; ii < arraysize(expected_params); ++ii) {
- const ParamInfo& expected_info = expected_params[ii];
- Param* param = param_object->GetUntypedParam(expected_info.name);
- if (expected_info.sas_type) {
- ASSERT_TRUE(param == NULL);
- } else {
- ASSERT_TRUE(param != NULL);
- if (expected_info.num_elements > 0) {
- EXPECT_TRUE(param->IsA(ParamParamArray::GetApparentClass()));
- } else {
- EXPECT_TRUE(param->IsA(expected_info.type));
- }
- }
- }
-
- // Clean up.
- object_manager()->DestroyPack(pack);
-}
-
-TEST_F(EffectTest, CreateSASParameters) {
- Pack* pack = object_manager()->CreatePack();
- ASSERT_TRUE(pack != NULL);
-
- // load an effect
- Effect *fx = pack->Create<Effect>();
- ASSERT_TRUE(fx != NULL);
- EXPECT_TRUE(fx->LoadFromFXString(String(kLambertEffect)));
-
- ParamObject* param_object = pack->Create<ParamObject>();
- ASSERT_TRUE(param_object != NULL);
-
- // Check that we get the correct params
- fx->CreateSASParameters(param_object);
-
- for (unsigned ii = 0; ii < arraysize(expected_params); ++ii) {
- const ParamInfo& expected_info = expected_params[ii];
- Param* param = param_object->GetUntypedParam(expected_info.name);
- if (expected_info.sas_type) {
- ASSERT_TRUE(param != NULL);
- if (expected_info.num_elements > 0) {
- ASSERT_TRUE(param->IsA(ParamParamArray::GetApparentClass()));
- } else {
- EXPECT_TRUE(param->IsA(expected_info.sas_type));
- }
- } else {
- ASSERT_TRUE(param == NULL);
- }
- }
-
- // Clean up.
- object_manager()->DestroyPack(pack);
-}
-
-TEST_F(EffectTest, GetEffectStreams) {
- Pack* pack = object_manager()->CreatePack();
- ASSERT_TRUE(pack != NULL);
-
- // load an effect
- Effect *fx = pack->Create<Effect>();
- ASSERT_TRUE(fx != NULL);
- EXPECT_TRUE(fx->LoadFromFXString(String(kLambertEffect)));
-
- // Check that we get the correct params
- EffectStreamInfoArray info;
- fx->GetStreamInfo(&info);
- EXPECT_EQ(arraysize(expected_streams), info.size());
-
- for (EffectStreamInfoArray::size_type ii = 0; ii < info.size(); ++ii) {
- EXPECT_TRUE(IsExpectedStream(info[ii]));
- }
-
- // Clean up.
- object_manager()->DestroyPack(pack);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/element.cc b/o3d/core/cross/element.cc
deleted file mode 100644
index a9a0bd0..0000000
--- a/o3d/core/cross/element.cc
+++ /dev/null
@@ -1,121 +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 definition of Element.
-
-#include "core/cross/element.h"
-#include "core/cross/error.h"
-#include "core/cross/pack.h"
-#include "core/cross/shape.h"
-
-namespace o3d {
-
-const char* Element::kMaterialParamName =
- O3D_STRING_CONSTANT("material");
-const char* Element::kBoundingBoxParamName =
- O3D_STRING_CONSTANT("boundingBox");
-const char* Element::kPriorityParamName =
- O3D_STRING_CONSTANT("priority");
-const char* Element::kZSortPointParamName =
- O3D_STRING_CONSTANT("zSortPoint");
-const char* Element::kCullParamName =
- O3D_STRING_CONSTANT("cull");
-
-O3D_DEFN_CLASS(Element, ParamObject);
-
-Element::Element(ServiceLocator* service_locator)
- : ParamObject(service_locator),
- owner_(NULL) {
- RegisterParamRef(kMaterialParamName, &material_param_ref_);
- RegisterParamRef(kBoundingBoxParamName, &bounding_box_param_ref_);
- RegisterParamRef(kPriorityParamName, &priority_param_ref_);
- RegisterParamRef(kZSortPointParamName, &z_sort_point_param_ref_);
- RegisterParamRef(kCullParamName, &cull_param_ref_);
-}
-
-Element::~Element() {
-}
-
-void Element::SetOwner(Shape* new_owner) {
- // Hold a ref to ourselves so we make sure we don't get deleted while
- // as we remove ourself from our current owner.
- Element::Ref temp(this);
-
- if (owner_ != NULL) {
- bool removed = owner_->RemoveElement(this);
- DLOG_ASSERT(removed);
- }
-
- owner_ = new_owner;
-
- if (new_owner) {
- new_owner->AddElement(this);
- }
-}
-
-// Adds a DrawElement to this Element and associates it to a group name.
-
-void Element::AddDrawElement(DrawElement* draw_element) {
- DCHECK(draw_element);
- draw_elements_.push_back(DrawElement::Ref(draw_element));
-}
-
-// Removes a DrawElement from this Element by group name.
-bool Element::RemoveDrawElement(DrawElement* draw_element) {
- DrawElementRefArray::iterator iter = std::find(
- draw_elements_.begin(),
- draw_elements_.end(),
- DrawElement::Ref(draw_element));
- if (iter != draw_elements_.end()) {
- draw_elements_.erase(iter);
- return true;
- }
- return false;
-}
-
-// Gets all the DrawPrimtives under this Element.
-DrawElementArray Element::GetDrawElements() const {
- DrawElementArray draw_elements;
- draw_elements.reserve(draw_elements_.size());
- std::copy(draw_elements_.begin(),
- draw_elements_.end(),
- std::back_inserter(draw_elements));
- return draw_elements;
-}
-
-DrawElement* Element::CreateDrawElement(Pack* pack, Material* material) {
- DrawElement* draw_element = pack->Create<DrawElement>();
- draw_element->set_material(material);
- draw_element->SetOwner(this);
- return draw_element;
-}
-} // namespace o3d
diff --git a/o3d/core/cross/element.h b/o3d/core/cross/element.h
deleted file mode 100644
index ab4ee60..0000000
--- a/o3d/core/cross/element.h
+++ /dev/null
@@ -1,250 +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 cotnains the declaration of Element.
-
-#ifndef O3D_CORE_CROSS_ELEMENT_H_
-#define O3D_CORE_CROSS_ELEMENT_H_
-
-#include <vector>
-#include "core/cross/param_object.h"
-#include "core/cross/bounding_box.h"
-#include "core/cross/ray_intersection_info.h"
-#include "core/cross/material.h"
-#include "core/cross/draw_element.h"
-#include "core/cross/state.h"
-
-namespace o3d {
-
-class RenderContext;
-class Renderer;
-class Pack;
-class Shape;
-class RayIntersectionInfo;
-class BoundingBox;
-class ParamCache;
-
-typedef std::vector<String> StringArray;
-typedef std::vector<DrawElement::Ref> DrawElementRefArray;
-
-// The Element is an abstract base class. It's purpose is to manage
-// DrawElements for things inherited from Element.
-class Element : public ParamObject {
- public:
- typedef SmartPointer<Element> Ref;
-
- virtual ~Element();
-
- static const char* kMaterialParamName;
- static const char* kBoundingBoxParamName;
- static const char* kZSortPointParamName;
- static const char* kPriorityParamName;
- static const char* kCullParamName;
-
- // Returns true if any params used during tree traversal have input
- // connections.
- inline bool ParamsUsedByTreeTraversalHaveInputConnections() {
- return cull_param_ref_->input_connection() != NULL ||
- bounding_box_param_ref_->input_connection() != NULL;
- }
-
- // Returns true if any params used for z sort have input connections.
- inline bool ParamsUsedByZSortHaveInputConnetions() {
- return z_sort_point_param_ref_->input_connection() != NULL;
- }
-
- // Returns the Material object bound to the Element.
- Material* material() const {
- return material_param_ref_->value();
- }
-
- // Binds an Material object to the Material.
- void set_material(Material* material) {
- material_param_ref_->set_value(material);
- }
-
- // Returns the BoundingBox of this Element.
- BoundingBox bounding_box() const {
- return bounding_box_param_ref_->value();
- }
-
- // Sets the BoundingBox used to cull this Element.
- void set_bounding_box(const BoundingBox& bounding_box) {
- bounding_box_param_ref_->set_value(bounding_box);
- }
-
- // Returns the z sort point of this Element.
- Float3 z_sort_point() const {
- return z_sort_point_param_ref_->value();
- }
-
- // Sets the point used to zsort this Element if the DrawPass is set to sort by
- // z order.
- void set_z_sort_point(const Float3& z_sort_point) {
- z_sort_point_param_ref_->set_value(z_sort_point);
- }
-
- // Returns the priority of this Element
- float priority() const {
- return priority_param_ref_->value();
- }
-
- // Sets the priority used to sort this Element if the DrawPass is set to sort
- // by priority.
- void set_priority(float priority) {
- priority_param_ref_->set_value(priority);
- }
-
- // Returns the cull setting of this Element. true = attempt to cull by
- // bounding box, false = do not attempt to cull.
- bool cull() const {
- return cull_param_ref_->value();
- }
-
- // Sets the cull setting for this Element. true = attempt to cull by
- // bounding box, false = do not attempt to cull
- void set_cull(bool cull) {
- cull_param_ref_->set_value(cull);
- }
-
- // Sets the owner of this Element. Passing in NULL will remove this
- // element from having an owner.
- // Parameters:
- // shape: Shape that will own this Element.
- void SetOwner(Shape* shape);
-
- // Gets the current owner of this Element.
- // Returns:
- // A pointer to the owner of this element.
- Shape* owner() {
- return owner_;
- }
-
- // Render this Element.
- virtual void Render(Renderer* renderer,
- DrawElement* draw_element,
- Material* material,
- ParamObject* param_object,
- ParamCache* param_cache) = 0;
-
- // Adds a DrawElement to this Element.
- // This is an internal function. Use DrawElement::SetOwner.
- // Parameter:
- // draw_element: DrawElement to add.
- void AddDrawElement(DrawElement* draw_element);
-
- // Removes a DrawElement from this Element.
- // This is an internal function. Use DrawElement::SetOwner.
- // Parameters:
- // draw_element: DrawElement to remove.
- // Returns:
- // True if removed. False if there this draw element was not on this
- // Element.
- bool RemoveDrawElement(DrawElement* draw_element);
-
- // Gets all the DrawElements under this Element.
- // Returns:
- // Array of raw pointers to DrawElements.
- DrawElementArray GetDrawElements() const;
-
- // for this Element. Note that unlike Shape::CreateDrawElements and
- // Transform::CreateDrawElements this one will create more than one element
- // for the same material.
- // Parameters:
- // pack: pack used to manage created DrawElements.
- // material: material to use for the created DrawElement. If you pass NULL
- // it will use the material on this Element. This allows you to easily
- // setup the default (just draw as is) by passing NULL or setup a shadow
- // pass by passing in a shadow material.
- // Returns:
- // The DrawElement created.
- DrawElement* CreateDrawElement(Pack* pack, Material* material);
-
- // Gets a direct const reference to all the DrawPrimtives under this
- // Element.
- // Returns:
- // Array of refs to DrawElements.
- const DrawElementRefArray& GetDrawElementRefs() const {
- return draw_elements_;
- }
-
- // Computes the intersection of a ray in the same coordinate system as
- // the specified POSITION stream.
- // Parameters:
- // position_stream_index: Index of POSITION stream.
- // cull: which side of the triangles to ignore.
- // start: position of start of ray in local space. end: position of end of
- // ray. in local space. result: pointer to ray intersection info to store
- // the result. If result->valid() is false then something was wrong.
- // Check IErrorStatus::GetLastError(). If result->intersected() is true
- // then the ray intersected a something. result->position() is the exact
- // point of intersection.
- virtual void IntersectRay(int position_stream_index,
- State::Cull cull,
- const Point3& start,
- const Point3& end,
- RayIntersectionInfo* result) const = 0;
-
- // Computes the bounding box in same coordinate system as the specified
- // POSITION stream.
- // Parameters:
- // position_stream_index: Index of POSITION stream.
- // result: A pointer to boundingbox to store the result.
- virtual void GetBoundingBox(int position_stream_index,
- BoundingBox* result) const = 0;
-
- protected:
- explicit Element(ServiceLocator* service_locator);
-
- private:
- ParamMaterial::Ref material_param_ref_; // Material to render with.
- ParamFloat3::Ref z_sort_point_param_ref_; // Point to zsort by.
- ParamFloat::Ref priority_param_ref_; // Point to priority sort by.
- ParamBoundingBox::Ref bounding_box_param_ref_; // Bounding box to cull by.
- ParamBoolean::Ref cull_param_ref_; // Culling on or off.
-
- // Draw elements under this Element.
- DrawElementRefArray draw_elements_;
-
- // The Shape we are currnetly owned by.
- Shape* owner_;
-
- O3D_DECL_CLASS(Element, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(Element);
-};
-
-typedef std::vector<Element*> ElementArray;
-typedef std::vector<Element::Ref> ElementRefArray;
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_ELEMENT_H_
diff --git a/o3d/core/cross/element_test.cc b/o3d/core/cross/element_test.cc
deleted file mode 100644
index fc66b15..0000000
--- a/o3d/core/cross/element_test.cc
+++ /dev/null
@@ -1,327 +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 implements unit tests for class Element.
-
-#include <algorithm>
-#include "tests/common/win/testing_common.h"
-#include "core/cross/element.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/primitive.h"
-
-namespace o3d {
-
-class ElementTest : public testing::Test {
- protected:
-
- ElementTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- Pack *pack_;
-};
-
-void ElementTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void ElementTest::TearDown() {
- pack_->Destroy();
-}
-
-TEST_F(ElementTest, Basic) {
- Element* element = pack()->Create<Primitive>();
-
- // Check that element got created.
- ASSERT_TRUE(element != NULL);
-
- // Check that its material is not set.
- EXPECT_TRUE(element->material() == NULL);
-
- // Check that the default params got created.
- EXPECT_TRUE(
- element->GetParam<ParamMaterial>(Element::kMaterialParamName) != NULL);
- EXPECT_TRUE(
- element->GetParam<ParamBoundingBox>(
- Element::kBoundingBoxParamName) != NULL);
- EXPECT_TRUE(
- element->GetParam<ParamFloat3>(Element::kZSortPointParamName) != NULL);
- EXPECT_TRUE(
- element->GetParam<ParamFloat>(Element::kPriorityParamName) != NULL);
- EXPECT_TRUE(
- element->GetParam<ParamBoolean>(Element::kCullParamName) != NULL);
-
- // Check that it has no owner.
- EXPECT_TRUE(element->owner() == NULL);
-}
-
-TEST_F(ElementTest, Owner) {
- Shape* shape1 = pack()->Create<Shape>();
- Shape* shape2 = pack()->Create<Shape>();
- Element* element = pack()->Create<Primitive>();
-
- ASSERT_TRUE(shape1 != NULL);
- ASSERT_TRUE(shape2 != NULL);
- ASSERT_TRUE(element != NULL);
-
- element->SetOwner(shape1);
-
- // Check that we are owned by shape1
- EXPECT_TRUE(element->owner() == shape1);
-
- // Check that shape1 owns us.
- const ElementRefArray& elements1 = shape1->GetElementRefs();
- EXPECT_TRUE(std::find(elements1.begin(),
- elements1.end(),
- Element::Ref(element)) !=
- elements1.end());
-
- // Check switching owners
- element->SetOwner(shape2);
-
- // Check that we are owned by shape2
- EXPECT_TRUE(element->owner() == shape2);
-
- // Check that shape1 no longer owns us.
- EXPECT_TRUE(std::find(elements1.begin(),
- elements1.end(),
- Element::Ref(element)) ==
- elements1.end());
-
- // Check that shape2 owns us.
- const ElementRefArray& elements2 = shape2->GetElementRefs();
- EXPECT_TRUE(std::find(elements2.begin(),
- elements2.end(),
- Element::Ref(element)) !=
- elements2.end());
-}
-
-TEST_F(ElementTest, DrawElement) {
- Element* element = pack()->Create<Primitive>();
- DrawElement* draw_element1 = pack()->Create<DrawElement>();
- DrawElement* draw_element2 = pack()->Create<DrawElement>();
-
- ASSERT_TRUE(element != NULL);
- ASSERT_TRUE(draw_element1 != NULL);
- ASSERT_TRUE(draw_element2 != NULL);
-
- // Check there are no draw elements.
- EXPECT_EQ(element->GetDrawElementRefs().size(), 0U);
-
- element->AddDrawElement(draw_element1);
-
- // Check it's been added.
- EXPECT_EQ(element->GetDrawElementRefs().size(), 1U);
- EXPECT_EQ(element->GetDrawElements()[0], draw_element1);
-
- // Check removing something else fails
- EXPECT_FALSE(element->RemoveDrawElement(draw_element2));
-
- // Remove it.
- EXPECT_TRUE(element->RemoveDrawElement(draw_element1));
-
- // Check it's been removed.
- EXPECT_EQ(element->GetDrawElementRefs().size(), 0U);
-
- // Check removing it twice fails.
- EXPECT_FALSE(element->RemoveDrawElement(draw_element1));
-}
-
-static void CreateCube(Pack* pack, Primitive** primitive_pointer) {
- static float cube_vertices[][3] = {
- { 1000, 1000, 1000 }, // dummy vertex
- { -1.0f, -1.0f, 1.0f, }, // vertex v0
- { +1.0f, -1.0f, 1.0f, }, // vertex v1
- { +1.0f, -1.0f, -1.0f, }, // vertex v2
- { -1.0f, -1.0f, -1.0f, }, // vertex v3
- { -1.0f, 1.0f, 1.0f, }, // vertex v4
- { +1.0f, 1.0f, 1.0f, }, // vertex v5
- { +1.0f, 1.0f, -1.0f, }, // vertex v6
- { -1.0f, 1.0f, -1.0f, }, // vertex v7
- };
-
- static uint32 cube_indices[] = {
- 0, // dummy index
- 0, 1, 4, // triangle v0,v1,v4
- 1, 5, 4, // triangle v1,v5,v4
- 1, 2, 5, // triangle v1,v2,v5
- 2, 6, 5, // triangle v2,v6,v5
- 2, 3, 6, // triangle v2,v3,v6
- 3, 7, 6, // triangle v3,v7,v6
- 3, 0, 7, // triangle v3,v0,v7
- 0, 4, 7, // triangle v0,v4,v7
- 4, 5, 7, // triangle v4,v5,v7
- 5, 6, 7, // triangle v5,v6,v7
- 3, 2, 0, // triangle v3,v2,v0
- 2, 1, 0 // triangle v2,v1,v0
- };
- Primitive* primitive = pack->Create<Primitive>();
- StreamBank* stream_bank = pack->Create<StreamBank>();
- ASSERT_TRUE(primitive != NULL);
- ASSERT_TRUE(stream_bank != NULL);
- primitive->set_stream_bank(stream_bank);
-
- // Check Setting Vertex Streams.
- VertexBuffer* vertex_buffer = pack->Create<VertexBuffer>();
- ASSERT_TRUE(vertex_buffer != NULL);
- Field* position_field = vertex_buffer->CreateField(
- FloatField::GetApparentClass(), arraysize(cube_vertices[0]));
- ASSERT_TRUE(position_field != NULL);
- ASSERT_TRUE(vertex_buffer->AllocateElements(arraysize(cube_vertices)));
- position_field->SetFromFloats(&cube_vertices[0][0],
- arraysize(cube_vertices[0]), 0,
- arraysize(cube_vertices));
- EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION,
- 0,
- position_field,
- 1));
- // Check Setting Index Streams.
- IndexBuffer* index_buffer = pack->Create<IndexBuffer>();
- ASSERT_TRUE(index_buffer != NULL);
- ASSERT_TRUE(index_buffer->AllocateElements(arraysize(cube_indices)));
- index_buffer->index_field()->SetFromUInt32s(cube_indices, 1, 0,
- arraysize(cube_indices));
-
- primitive->set_index_buffer(index_buffer);
-
- primitive->set_primitive_type(o3d::Primitive::TRIANGLELIST);
- primitive->set_start_index(1);
- primitive->set_number_primitives(12);
- primitive->set_number_vertices(8);
-
- EXPECT_EQ(primitive->primitive_type(), o3d::Primitive::TRIANGLELIST);
- EXPECT_EQ(primitive->number_primitives(), 12U);
- EXPECT_EQ(primitive->number_vertices(), 8U);
-
- *primitive_pointer = primitive;
-}
-
-static const float kEpsilon = 0.00001f;
-
-TEST_F(ElementTest, IntersectRay) {
- Element* element = pack()->Create<Primitive>();
-
- ASSERT_TRUE(element != NULL);
-
- RayIntersectionInfo info;
- element->IntersectRay(0,
- State::CULL_NONE,
- Point3(0, 0, 0),
- Point3(1.0f, 1.0f, 1.0f),
- &info);
-
- // Check that it's invalid (there are no streams)
- EXPECT_FALSE(info.valid());
-
- Primitive* primitive;
- CreateCube(pack(), &primitive);
- Element* element2 = primitive;
-
- element2->IntersectRay(0,
- State::CULL_NONE,
- Point3(-2.0f, -2.0f, -2.0f),
- Point3(2.0f, 2.0f, 2.0f),
- &info);
-
- // Check that it intersected.
- EXPECT_TRUE(info.valid());
- EXPECT_TRUE(info.intersected());
- EXPECT_TRUE(fabsf(info.position().getX() - -1.0f) < kEpsilon);
- EXPECT_TRUE(fabsf(info.position().getY() - -1.0f) < kEpsilon);
- EXPECT_TRUE(fabsf(info.position().getZ() - -1.0f) < kEpsilon);
-
- // Check when culling counter clockwise
- element2->IntersectRay(0,
- State::CULL_CCW,
- Point3(-2.0f, -2.0f, -2.0f),
- Point3(0.0f, 0.0f, 0.0f),
- &info);
-
- // Check that it intersected.
- EXPECT_TRUE(info.valid());
- EXPECT_TRUE(info.intersected());
-
- // Check when culling clockwise
- element2->IntersectRay(0,
- State::CULL_CW,
- Point3(-2.0f, -2.0f, -2.0f),
- Point3(0.0f, 0.0f, 0.0f),
- &info);
-
- // Check that it did NOT intersect.
- EXPECT_TRUE(info.valid());
- EXPECT_FALSE(info.intersected());
-
- element2->IntersectRay(0,
- State::CULL_NONE,
- Point3(2.0f, 2.0f, 2.0f),
- Point3(3.0f, 3.0f, 3.0f),
- &info);
-
- // Check that it didn't intersect
- EXPECT_TRUE(info.valid());
- EXPECT_FALSE(info.intersected());
-} // namespace o3d
-
-TEST_F(ElementTest, GetBoundingBox) {
- Element* element = pack()->Create<Primitive>();
-
- ASSERT_TRUE(element != NULL);
-
- BoundingBox box;
- element->GetBoundingBox(0, &box);
-
- // Check that it's invalid (there are no streams)
- EXPECT_FALSE(box.valid());
-
- Primitive* primitive;
- CreateCube(pack(), &primitive);
- Element* element2 = primitive;
- element2->GetBoundingBox(0, &box);
- EXPECT_TRUE(box.valid());
- EXPECT_TRUE(fabsf(box.min_extent().getX() - -1.0f) < kEpsilon);
- EXPECT_TRUE(fabsf(box.min_extent().getY() - -1.0f) < kEpsilon);
- EXPECT_TRUE(fabsf(box.min_extent().getZ() - -1.0f) < kEpsilon);
- EXPECT_TRUE(fabsf(box.max_extent().getX() - 1.0f) < kEpsilon);
- EXPECT_TRUE(fabsf(box.max_extent().getY() - 1.0f) < kEpsilon);
- EXPECT_TRUE(fabsf(box.max_extent().getZ() - 1.0f) < kEpsilon);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/error.h b/o3d/core/cross/error.h
deleted file mode 100644
index 3946e70..0000000
--- a/o3d/core/cross/error.h
+++ /dev/null
@@ -1,56 +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_CORE_CROSS_ERROR_H_
-#define O3D_CORE_CROSS_ERROR_H_
-
-#include "core/cross/error_stream_manager.h"
-#include "core/cross/service_locator.h"
-#include "core/cross/ierror_status.h"
-
-// This macro reports and error to the client. It is used like the logging
-// macros ie O3D_ERROR(status) << "you had an error in " << name;
-// Parameters:
-// status: pointer to the IErrorStatus object.
-#ifdef NDEBUG
-
-#define O3D_ERROR(service_locator) \
- o3d::ErrorStreamManager(service_locator).stream()
-
-#else
-
-#define O3D_ERROR(service_locator) \
- o3d::ErrorStreamManager(service_locator, __FILE__, __LINE__).stream()
-
-#endif
-
-#endif // O3D_CORE_CROSS_ERROR_H_
diff --git a/o3d/core/cross/error_status.cc b/o3d/core/cross/error_status.cc
deleted file mode 100644
index 6a9ceee..0000000
--- a/o3d/core/cross/error_status.cc
+++ /dev/null
@@ -1,100 +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 "core/cross/error_status.h"
-
-namespace o3d {
-
-ErrorStatus::ErrorStatus(ServiceLocator* service_locator)
- : service_(service_locator, this), log_to_file_(true) {}
-
-void ErrorStatus::SetErrorCallback(ErrorCallback* error_callback) {
- error_callback_manager_.Set(error_callback);
-}
-
-void ErrorStatus::ClearErrorCallback() {
- error_callback_manager_.Clear();
-}
-
-IErrorStatus::ErrorCallback* ErrorStatus::Exchange(ErrorCallback* callback) {
- return error_callback_manager_.Exchange(callback);
-}
-
-#ifndef NDEBUG
-void ErrorStatus::SetLastError(const String& error, const char *file,
- int line) {
- if (log_to_file_) {
- logging::LogMessage(file, line, ERROR).stream() << error;
- }
- SetLastError(error);
-}
-#endif
-
-void ErrorStatus::SetLastError(const String& error) {
- error_string_ = error;
- error_callback_manager_.Run(error_string_);
-}
-
-const String& ErrorStatus::GetLastError() const {
- return error_string_;
-}
-
-void ErrorStatus::ClearLastError() {
- error_string_.clear();
-}
-
-ErrorCollector::ErrorCollector(ServiceLocator* service_locator)
- : error_status_(service_locator->GetService<IErrorStatus>()) {
- old_callback_ = error_status_->Exchange(this);
-}
-
-ErrorCollector::~ErrorCollector() {
- error_status_->Exchange(old_callback_);
-}
-
-void ErrorCollector::Run(const String& error) {
- errors_ += (errors_.empty() ? String("") : String("\n")) + error;
-}
-
-ErrorSuppressor::ErrorSuppressor(ServiceLocator* service_locator)
- : error_status_(service_locator->GetService<IErrorStatus>()) {
- old_callback_ = error_status_->Exchange(this);
- old_file_logging_ = error_status_->IsFileLoggingActive();
- error_status_->SetFileLoggingActive(false);
-}
-
-ErrorSuppressor::~ErrorSuppressor() {
- error_status_->Exchange(old_callback_);
- error_status_->SetFileLoggingActive(old_file_logging_);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/error_status.h b/o3d/core/cross/error_status.h
deleted file mode 100644
index 2f4084b..0000000
--- a/o3d/core/cross/error_status.h
+++ /dev/null
@@ -1,164 +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_CORE_CROSS_ERROR_STATUS_H_
-#define O3D_CORE_CROSS_ERROR_STATUS_H_
-
-#include "core/cross/service_implementation.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/ierror_status.h"
-
-namespace o3d {
-
-// Records the last reported error. Allows a callback to be invoked when an
-// error is reported.
-class ErrorStatus : public IErrorStatus {
- public:
- explicit ErrorStatus(ServiceLocator* service_locator_);
-
- // Sets the error callback. NOTE: The client takes ownership of the
- // ErrorCallback you pass in. It will be deleted if you call SetErrorCallback
- // a second time or if you call ClearErrorCallback.
- //
- // Parameters:
- // error_callback: ErrorCallback to call each time the client gets
- // an error.
- void SetErrorCallback(ErrorCallback* error_callback);
-
- // Clears the Error callback NOTE: The client takes ownership of the
- // ErrorCallback you pass in to SetErrorCallback. It will be deleted if you
- // call SetErrorCallback a second time or if you call ClearErrorCallback.
- virtual void ClearErrorCallback();
-
- // Sets the last error. This is pretty much only called by ErrorStreamManager.
- virtual void SetLastError(const String& error);
-
-#ifndef NDEBUG
- // For debug builds, we display where in the code the error came from.
- virtual void SetLastError(const String& error, const char *file, int line);
-#endif
-
- // Gets the last reported error.
- virtual const String& GetLastError() const;
-
- // Clears the stored last error.
- virtual void ClearLastError();
-
- // File logging is only ever done in a debug build.
- void SetFileLoggingActive(bool should_log) {
- log_to_file_ = should_log;
- }
- bool IsFileLoggingActive() const {
- return log_to_file_;
- }
-
- protected:
- // Exchanges a new callback with the current callback, returing the old
- // one.
- // Parameters:
- // callback: ErrorCallback to exchange.
- virtual ErrorCallback* Exchange(ErrorCallback* callback);
-
- private:
- typedef NonRecursiveCallback1Manager<const o3d::String&>
- ErrorCallbackManager;
-
- ServiceImplementation<IErrorStatus> service_;
- ErrorCallbackManager error_callback_manager_;
- String error_string_;
- bool log_to_file_;
-};
-
-// This class temporarily replaces the error callback on the ErrorStatus
-// service. It restores it when destroyed.
-// It should be used like this.
-//
-// { // some scope
-// ErrorCollector error_collector(service_locator);
-//
-// .. call some stuff that might generate an error.
-//
-// String errors = error_collector.errors();
-//
-// } // end of scope, old callback has been restored.
-class ErrorCollector : public IErrorStatus::ErrorCallback {
- public:
- explicit ErrorCollector(ServiceLocator* service_locator);
- ~ErrorCollector();
-
- // Appends the error to the errors being collected.
- virtual void Run(const String& error);
-
- // Gets the collectd errors.
- const String& errors() const {
- return errors_;
- }
-
- private:
- IErrorStatus* error_status_;
- IErrorStatus::ErrorCallback* old_callback_;
- String errors_;
-
- DISALLOW_COPY_AND_ASSIGN(ErrorCollector);
-};
-
-// This class temporarily replaces the error callback on the ErrorStatus
-// service. It restores it when destroyed. It's similar to the ErrorCollector,
-// but it throws away all errors instead of collecting them. It also suppresses
-// debugging log output temporarily.
-//
-// It should be used like this.
-//
-// { // some scope
-// ErrorSuppressor error_suppressor(service_locator);
-//
-// .. call some stuff that might generate an error.
-//
-// } // end of scope, old callback has been restored.
-class ErrorSuppressor : public IErrorStatus::ErrorCallback {
- public:
- explicit ErrorSuppressor(ServiceLocator* service_locator);
- ~ErrorSuppressor();
-
- virtual void Run(const String& error) {}
-
- private:
- IErrorStatus* error_status_;
- IErrorStatus::ErrorCallback* old_callback_;
- bool old_file_logging_;
-
- DISALLOW_COPY_AND_ASSIGN(ErrorSuppressor);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_ERROR_STATUS_H_
diff --git a/o3d/core/cross/error_stream_manager.cc b/o3d/core/cross/error_stream_manager.cc
deleted file mode 100644
index e49e755..0000000
--- a/o3d/core/cross/error_stream_manager.cc
+++ /dev/null
@@ -1,61 +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 "core/cross/error_stream_manager.h"
-#include "base/logging.h"
-
-namespace o3d {
-
-#ifdef NDEBUG
-ErrorStreamManager::ErrorStreamManager(ServiceLocator* service_locator) {
-#else
-ErrorStreamManager::ErrorStreamManager(ServiceLocator* service_locator,
- const char* file,
- int line)
- : file_(file),
- line_(line) {
-#endif
- if (service_locator->IsAvailable<IErrorStatus>())
- error_status_ = service_locator->GetService<o3d::IErrorStatus>();
- else
- error_status_ = NULL;
-}
-
-ErrorStreamManager::~ErrorStreamManager() {
- if (error_status_ != NULL)
-#ifdef NDEBUG
- error_status_->SetLastError(String(stream_.str()));
-#else
- error_status_->SetLastError(String(stream_.str()), file_, line_);
-#endif
-}
-} // namespace o3d
diff --git a/o3d/core/cross/error_stream_manager.h b/o3d/core/cross/error_stream_manager.h
deleted file mode 100644
index 90fa7a1..0000000
--- a/o3d/core/cross/error_stream_manager.h
+++ /dev/null
@@ -1,73 +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_CORE_CROSS_ERROR_STREAM_MANAGER_H_
-#define O3D_CORE_CROSS_ERROR_STREAM_MANAGER_H_
-
-#include <sstream>
-
-#include "core/cross/ierror_status.h"
-
-namespace o3d {
-
-// We create a new ErrorStreamManager with each instantiation of the
-// O3D_ERROR macro. That way we can call stuff based on the destruction
-// of the manager.
-class ErrorStreamManager {
- public:
- // Constructs an ErrorStreamManager which on destruction will copy the
- // contents of the stream to the client's error_string.
- // Parameters:
- // client: The client whose error message to set.
-#ifdef NDEBUG
- explicit ErrorStreamManager(ServiceLocator *service_locator);
-#else
- ErrorStreamManager(ServiceLocator* service_locator,
- const char* file,
- int line);
-#endif
- ~ErrorStreamManager();
-
- std::ostream& stream() {
- return stream_;
- }
- private:
- std::ostringstream stream_;
- IErrorStatus* error_status_;
-#ifndef NDEBUG
- const char* file_;
- int line_;
-#endif
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_ERROR_STREAM_MANAGER_H_
diff --git a/o3d/core/cross/evaluation_counter.cc b/o3d/core/cross/evaluation_counter.cc
deleted file mode 100644
index 3f8d054..0000000
--- a/o3d/core/cross/evaluation_counter.cc
+++ /dev/null
@@ -1,40 +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 "core/cross/evaluation_counter.h"
-
-namespace o3d {
-
-const InterfaceId EvaluationCounter::kInterfaceId =
- InterfaceTraits<EvaluationCounter>::kInterfaceId;
-
-} // namespace o3d
diff --git a/o3d/core/cross/evaluation_counter.h b/o3d/core/cross/evaluation_counter.h
deleted file mode 100644
index 3aaaab14..0000000
--- a/o3d/core/cross/evaluation_counter.h
+++ /dev/null
@@ -1,68 +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_CORE_CROSS_EVALUATION_COUNTER_H_
-#define O3D_CORE_CROSS_EVALUATION_COUNTER_H_
-
-#include "core/cross/service_implementation.h"
-
-namespace o3d {
-
-// Keeps track of the current evaluation count, used to determine whether a
-// parameter's state is valid or needs to be computed.
-class EvaluationCounter {
- public:
- static const InterfaceId kInterfaceId;
-
- explicit EvaluationCounter(ServiceLocator* service_locator)
- : service_(service_locator, this),
- evaluation_count_(0) {}
-
- // Marks all parameters as so they will get re-evaluated
- void InvalidateAllParameters() {
- ++evaluation_count_;
- }
-
- // Gets the current global evaluation count.
- int evaluation_count() {
- return evaluation_count_;
- }
-
- private:
- ServiceImplementation<EvaluationCounter> service_;
-
- // The global evaluation count;
- int evaluation_count_;
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_EVALUATION_COUNTER_H_
diff --git a/o3d/core/cross/event.cc b/o3d/core/cross/event.cc
deleted file mode 100644
index efc7f76..0000000
--- a/o3d/core/cross/event.cc
+++ /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 contains the implementation of Event.
-
-#include "core/cross/event.h"
-
-namespace o3d {
-
-bool Event::operator==(const Event& e) const {
- CHECK(valid() && e.valid());
- if (type_ != e.type_) {
- return false;
- }
- if (button_valid_ != e.button_valid_) {
- return false;
- }
- if (button_valid_ && (button_ != e.button_)) {
- return false;
- }
- if (modifier_state_valid_ != e.modifier_state_valid_) {
- return false;
- }
- if (modifier_state_valid_ && (modifier_state_ != e.modifier_state_)) {
- return false;
- }
- if (key_code_valid_ != e.key_code_valid_) {
- return false;
- }
- if (key_code_valid_ && (key_code_ != e.key_code_)) {
- return false;
- }
- if (char_code_valid_ != e.char_code_valid_) {
- return false;
- }
- if (char_code_valid_ && (char_code_ != e.char_code_)) {
- return false;
- }
- if (position_valid_ != e.position_valid_) {
- return false;
- }
- if (position_valid_) {
- if (x_ != e.x_) {
- return false;
- }
- if (y_ != e.y_) {
- return false;
- }
- if (screen_x_ != e.screen_x_) {
- return false;
- }
- if (screen_y_ != e.screen_y_) {
- return false;
- }
- if (in_plugin_ != e.in_plugin_) {
- return false;
- }
- }
- if (delta_valid_ != e.delta_valid_) {
- return false;
- }
- if (delta_valid_) {
- if (delta_x_ != e.delta_x_) {
- return false;
- }
- if (delta_y_ != e.delta_y_) {
- return false;
- }
- }
- return true;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/event.h b/o3d/core/cross/event.h
deleted file mode 100644
index b33f127..0000000
--- a/o3d/core/cross/event.h
+++ /dev/null
@@ -1,416 +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 declaration of Event.
-
-#ifndef O3D_CORE_CROSS_EVENT_H_
-#define O3D_CORE_CROSS_EVENT_H_
-
-#include <deque>
-
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// This Event class is used to pass information to JavaScript event handlers.
-// It's the single argument passed to JavaScript for any event that we catch
-// and forward through.
-// See http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html
-// for what we're trying to emulate. However, some of the fields are hard to
-// produce, so we skip them for now or make up the different in JavaScript.
-class Event {
- public:
- // TODO: Figure out what events to add here; stuff like onmouseout is
- // probably handled by the browser. For a decent list of HTML5 events, see:
- // http://www.w3schools.com/tags/html5_ref_eventattributes.asp
- enum Type { // When you add to this, don't forget to add to StringFromType!
- TYPE_INVALID,
- TYPE_CLICK,
- TYPE_DBLCLICK,
- TYPE_MOUSEDOWN,
- TYPE_MOUSEMOVE,
- TYPE_MOUSEUP,
- TYPE_WHEEL,
- TYPE_KEYDOWN,
- TYPE_KEYPRESS,
- TYPE_KEYUP,
- TYPE_RESIZE, // This we also trigger on the fullscreen transition.
- TYPE_CONTEXTMENU,
- NUM_TYPES
- };
- enum Button {
- BUTTON_LEFT = 0,
- BUTTON_MIDDLE = 1,
- BUTTON_RIGHT = 2,
- BUTTON_4 = 3,
- BUTTON_5 = 4,
- NUM_BUTTONS,
- };
- enum Modifier {
- MODIFIER_ALT = 1,
- MODIFIER_CTRL = 2,
- MODIFIER_SHIFT = 4,
- MODIFIER_META = 8, // Command on OSX
- MODIFIER_MAX = MODIFIER_META, // Must update this if you add a modifier.
- MODIFIER_MASK = (MODIFIER_MAX << 1) - 1
- };
-
- static const char *StringFromType(Type type) {
- switch (type) {
- case TYPE_CLICK:
- return "click";
- case TYPE_DBLCLICK:
- return "dblclick";
- case TYPE_KEYDOWN:
- return "keydown";
- case TYPE_KEYPRESS:
- return "keypress";
- case TYPE_KEYUP:
- return "keyup";
- case TYPE_MOUSEDOWN:
- return "mousedown";
- case TYPE_MOUSEMOVE:
- return "mousemove";
- case TYPE_MOUSEUP:
- return "mouseup";
- case TYPE_WHEEL:
- return "wheel";
- case TYPE_RESIZE:
- return "resize";
- case TYPE_CONTEXTMENU:
- return "contextmenu";
- case TYPE_INVALID:
- default:
- DCHECK(false);
- return "invalid";
- }
- }
-
- static Type TypeFromString(const char *type_string) {
- for (int i = TYPE_INVALID + 1; i < NUM_TYPES; ++i) {
- if (!strcmp(type_string, StringFromType(static_cast<Type>(i)))) {
- return static_cast<Type>(i);
- }
- }
- return TYPE_INVALID;
- }
-
- static bool ValidType(Type type) {
- return TYPE_INVALID < type && type < NUM_TYPES;
- }
-
- Event() :
- type_(TYPE_INVALID),
- button_valid_(false),
- modifier_state_valid_(false),
- key_code_valid_(false),
- char_code_valid_(false),
- position_valid_(false),
- delta_valid_(false),
- size_valid_(false),
- valid_(false) { }
- explicit Event(Type type) :
- type_(type),
- button_valid_(false),
- modifier_state_valid_(false),
- key_code_valid_(false),
- char_code_valid_(false),
- position_valid_(false),
- delta_valid_(false),
- size_valid_(false),
- valid_(true) { }
- Event(const Event& event) {
- if (event.valid()) {
- Copy(event);
- } else {
- valid_ = false;
- }
- }
- Event& operator=(const Event& event) {
- if (event.valid()) {
- Copy(event);
- } else {
- valid_ = false;
- }
- return *this;
- }
- bool operator==(const Event& e) const;
- bool operator!=(const Event& e) const {
- return !(*this == e);
- }
-
-
- Type type() const {
- DCHECK(valid_);
- return type_;
- }
- // This is generally used only for overriding a type on a copied event [to
- // create a click from a mouseup, for example].
- void set_type(Type type) {
- DCHECK(valid_);
- type_ = type;
- }
- const char *type_string() const {
- return StringFromType(type());
- }
-
- // Button is valid on mousedown, mouseup, click, and dblclick.
- // It indicates which button actually caused the event.
- int button() const {
- DCHECK(valid_);
- return button_valid_ ? button_ : 0;
- }
- void set_button(int button) {
- DCHECK(valid_);
- DCHECK(button >= 0 && button < NUM_BUTTONS);
- button_valid_ = true;
- button_ = button;
- }
- bool button_valid() const { return button_valid_; }
- void clear_button() { button_valid_ = false; }
-
- int modifier_state() const {
- DCHECK(valid_);
- return modifier_state_valid_ ? modifier_state_ : 0;
- }
- void set_modifier_state(int state) {
- DCHECK(valid_);
- DCHECK(!(state & ~MODIFIER_MASK));
- modifier_state_valid_ = true;
- modifier_state_ = state;
- }
- bool modifier_state_valid() const { return modifier_state_valid_; }
- void clear_modifier_state() { modifier_state_valid_ = false; }
-
- bool ctrl_key() const {
- DCHECK(valid_);
- return modifier_state_valid_ ?
- (modifier_state_ & MODIFIER_CTRL) != 0 : false;
- }
- bool alt_key() const {
- DCHECK(valid_);
- return modifier_state_valid_ ?
- (modifier_state_ & MODIFIER_ALT) != 0 : false;
- }
- bool shift_key() const {
- DCHECK(valid_);
- return modifier_state_valid_ ?
- (modifier_state_ & MODIFIER_SHIFT) != 0 : false;
- }
- bool meta_key() const {
- DCHECK(valid_);
- return modifier_state_valid_ ?
- (modifier_state_ & MODIFIER_META) != 0 : false;
- }
-
- // Key code is valid on keydown and keyup events only.
- int key_code() const {
- DCHECK(valid_);
- return key_code_valid_ ? key_code_ : 0;
- }
- void set_key_code(int key_code) {
- DCHECK(valid_);
- key_code_valid_ = true;
- key_code_ = key_code;
- }
- bool key_code_valid() const { return key_code_valid_; }
- void clear_key_code() { key_code_valid_ = false; }
-
- // Key char is valid on keypress events only.
- void set_char_code(int char_code) {
- DCHECK(valid_);
- char_code_valid_ = true;
- char_code_ = char_code;
- }
- int char_code() const {
- DCHECK(valid_);
- return char_code_valid_ ? char_code_ : 0;
- }
- bool char_code_valid() const { return char_code_valid_; }
- void clear_char_code() { char_code_valid_ = false; }
-
- // Position is valid on mouse events only.
- int x() const {
- DCHECK(valid_);
- return position_valid_ ? x_ : 0;
- }
- int y() const {
- DCHECK(valid_);
- return position_valid_ ? y_ : 0;
- }
- int screen_x() const {
- DCHECK(valid_);
- return position_valid_ ? screen_x_ : 0;
- }
- int screen_y() const {
- DCHECK(valid_);
- return position_valid_ ? screen_y_ : 0;
- }
-
- // This tells whether or not the position was within the plugin region at the
- // time of the event. This is used to determine when to synthesize a click
- // event, which only happens when both a mousedown and its corresponding
- // mouseup both occur within the plugin region [regardless of the location
- // intervening mousemove events]. Technically we only absolutely need this
- // for mousedown and mouseup, but the interface is simpler to require it on
- // all positioned events, and it might be useful.
- bool in_plugin() const {
- DCHECK(valid_);
- return position_valid_ ? in_plugin_ : false;
- }
- void set_position(int x, int y, int screen_x, int screen_y, bool inPlugin) {
- DCHECK(valid_);
- position_valid_ = true;
- x_ = x;
- y_ = y;
- screen_x_ = screen_x;
- screen_y_ = screen_y;
- in_plugin_ = inPlugin;
- }
- bool position_valid() const { return position_valid_; }
- void clear_position() { position_valid_ = false; }
-
- // These are used for mouse scroll events only. Currently one of the two will
- // always be zero, as some platforms can only detect one axis at a time.
- // We'll want to add a z axis at some point.
- int delta_x() const {
- DCHECK(valid_);
- return delta_valid_ ? delta_x_ : 0;
- }
- int delta_y() const {
- DCHECK(valid_);
- return delta_valid_ ? delta_y_ : 0;
- }
- void set_delta(int delta_x, int delta_y) {
- DCHECK(valid_);
- DCHECK(!delta_x || !delta_y);
- delta_valid_ = true;
- delta_x_ = delta_x;
- delta_y_ = delta_y;
- }
- bool delta_valid() const { return delta_valid_; }
- void clear_delta() { delta_valid_ = false; }
-
- // Width, height, and fullscreen are valid on resize events only.
- int width() const {
- DCHECK(valid_);
- return size_valid_ ? width_ : 0;
- }
- int height() const {
- DCHECK(valid_);
- return size_valid_ ? height_ : 0;
- }
- bool fullscreen() const {
- DCHECK(valid_);
- return size_valid_ ? fullscreen_ : false;
- }
- void set_size(int width, int height, bool fullscreen) {
- DCHECK(valid_);
- size_valid_ = true;
- width_ = width;
- height_ = height;
- fullscreen_ = fullscreen;
- }
- bool size_valid() const { return size_valid_; }
- void clear_size() { size_valid_ = false; }
-
- bool valid() const { return valid_; }
-
- protected:
- void Copy(const Event& event) {
- valid_ = true;
- type_ = event.type();
- if (event.button_valid()) {
- set_button(event.button());
- } else {
- button_valid_ = false;
- }
- if (event.modifier_state_valid()) {
- set_modifier_state(event.modifier_state());
- } else {
- modifier_state_valid_ = false;
- }
- if (event.key_code_valid()) {
- set_key_code(event.key_code());
- } else {
- key_code_valid_ = false;
- }
- if (event.char_code_valid()) {
- set_char_code(event.char_code());
- } else {
- char_code_valid_ = false;
- }
- if (event.position_valid()) {
- set_position(event.x(), event.y(), event.screen_x(), event.screen_y(),
- event.in_plugin());
- } else {
- position_valid_ = false;
- }
- if (event.delta_valid()) {
- set_delta(event.delta_x(), event.delta_y());
- } else {
- delta_valid_ = false;
- }
- if (event.size_valid()) {
- set_size(event.width(), event.height(), event.fullscreen());
- } else {
- size_valid_ = false;
- }
- }
-
- private:
- Type type_;
- int button_;
- bool button_valid_;
- int modifier_state_;
- bool modifier_state_valid_;
- int key_code_;
- bool key_code_valid_;
- int char_code_;
- bool char_code_valid_;
- int x_, y_;
- int screen_x_, screen_y_;
- bool in_plugin_;
- bool position_valid_;
- int delta_x_, delta_y_;
- bool delta_valid_;
- int width_, height_;
- bool fullscreen_;
- bool size_valid_;
- bool valid_;
-};
-
-typedef std::deque<Event> EventQueue;
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_EVENT_H_
diff --git a/o3d/core/cross/event_callback.h b/o3d/core/cross/event_callback.h
deleted file mode 100644
index 49f899c..0000000
--- a/o3d/core/cross/event_callback.h
+++ /dev/null
@@ -1,48 +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 definition of the callback for JavaScript IO events.
-
-#ifndef O3D_CORE_CROSS_EVENT_CALLBACK_H_
-#define O3D_CORE_CROSS_EVENT_CALLBACK_H_
-
-#include "core/cross/callback.h"
-#include "core/cross/event.h"
-
-namespace o3d {
-
-typedef NonRecursiveCallback1Manager<const Event&> EventCallbackManager;
-typedef EventCallbackManager::CallbackType EventCallback;
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_EVENT_CALLBACK_H_
diff --git a/o3d/core/cross/event_manager.cc b/o3d/core/cross/event_manager.cc
deleted file mode 100644
index 8033579..0000000
--- a/o3d/core/cross/event_manager.cc
+++ /dev/null
@@ -1,165 +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 for the EventManager class.
-
-#include "core/cross/event_manager.h"
-
-#include "core/cross/client.h"
-#include "core/cross/error.h"
-
-namespace o3d {
-
-void EventManager::ProcessQueue() {
- // Process up to one event per frame.
- // If we've removed all callbacks by clearing event_callbacks_, we're shutting
- // down, so we can't process any late-added events.
- if (valid_ && !event_queue_.empty()) {
-#ifndef NDEBUG
- DCHECK(!processing_event_queue_);
- processing_event_queue_ = true;
-#endif
- Event event = event_queue_.front();
-
- // Pop the event before invoking the callback; the callback might invoke
- // Client::CleanUp, which empties the event queue. This can happen in Chrome
- // if it invokes the unload handler when control enters JavaScript.
- event_queue_.pop_front();
-
- event_callbacks_[event.type()].Run(event);
-#ifndef NDEBUG
- processing_event_queue_ = false;
-#endif
- }
-}
-
-void EventManager::SetEventCallback(Event::Type type,
- EventCallback* event_callback) {
- DCHECK(Event::ValidType(type));
- if (valid_)
- event_callbacks_[type].Set(event_callback);
-}
-
-void EventManager::ClearEventCallback(Event::Type type) {
- DCHECK(Event::ValidType(type));
- if (valid_)
- event_callbacks_[type].Clear();
-}
-
-void EventManager::AddEventToQueue(const Event& event) {
- // If we're shutting down or there's no callback registered to handle
- // this event type, we drop it.
- // NOTE:If we have a callback registered for the click event then we allow
- // MOUSEDOWN and MOUSEUP events through.
- if (valid_ && (event_callbacks_[event.type()].IsSet() ||
- (event_callbacks_[Event::TYPE_CLICK].IsSet() &&
- (event.type() == Event::TYPE_MOUSEDOWN ||
- event.type() == Event::TYPE_MOUSEUP)))) {
- if (!event_queue_.empty()) {
- switch (event.type()) {
- case Event::TYPE_MOUSEMOVE:
- if (event_queue_.back().type() == Event::TYPE_MOUSEMOVE) {
- // Just keep the last MOUSEMOVE; there's no need to queue up lots
- // of them.
- event_queue_.back() = event;
- return;
- }
- break;
- case Event::TYPE_KEYPRESS:
- // If we're backed up with keydowns and keypresses [which alternate
- // on key repeat], just throw away the new ones. Throwing them away
- // one at a time could lead to aliased repeat patterns in which we
- // throw away more keydowns than keypresses, so we have to detect the
- // pair together and throw them both away. This means that we won't
- // start chucking stuff until there are at least 4 events backed up [3
- // in the queue plus the new one], but that'll keep us from getting
- // more than a few frames behind.
- if (event_queue_.size() >= 3) {
- EventQueue::reverse_iterator iter = event_queue_.rbegin();
- const Event& event3 = *iter;
- if (event3.type() != Event::TYPE_KEYDOWN) {
- break;
- }
- const Event& event2 = *++iter;
- if (event2 != event) {
- break;
- }
- const Event& event1 = *++iter;
- if (event1 != event3) {
- break;
- }
- event_queue_.pop_back(); // Throw away the keydown.
- return; // Throw away the keypress.
- }
- break;
- default:
- break;
- }
- }
- if (event.type() == Event::TYPE_MOUSEDOWN) {
- if (event.in_plugin()) {
- mousedown_in_plugin_ = true;
- } else {
- mousedown_in_plugin_ = false;
- return; // Why did we even get this event?
- }
- }
-
- if (event_callbacks_[event.type()].IsSet())
- event_queue_.push_back(event);
-
- if (event.type() == Event::TYPE_MOUSEUP) {
- if (mousedown_in_plugin_ && event.in_plugin()) {
- Event temp = event;
- temp.set_type(Event::TYPE_CLICK);
- event_queue_.push_back(temp);
- if (temp.button() == Event::BUTTON_RIGHT) {
- temp.set_type(Event::TYPE_CONTEXTMENU);
- temp.clear_modifier_state();
- temp.clear_button();
- event_queue_.push_back(temp);
- }
- }
- mousedown_in_plugin_ = false;
- }
- }
-}
-
-void EventManager::ClearAll() {
- valid_ = false;
- for (unsigned int i = 0; i < arraysize(event_callbacks_); ++i) {
- event_callbacks_[i].Clear();
- }
- event_queue_.clear();
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/event_manager.h b/o3d/core/cross/event_manager.h
deleted file mode 100644
index a32908c..0000000
--- a/o3d/core/cross/event_manager.h
+++ /dev/null
@@ -1,108 +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 declaration of the EventManager class.
-
-#ifndef O3D_CORE_CROSS_EVENT_MANAGER_H_
-#define O3D_CORE_CROSS_EVENT_MANAGER_H_
-
-#include <vector>
-#include "core/cross/event.h"
-#include "core/cross/event_callback.h"
-
-namespace o3d {
-
-class Client;
-
-// This class manages the queue of events that need to get forwarded through to
-// JavaScript handlers. It deals with synthesizing any events that need
-// synthesis in the same way across platforms, and does throttling on mousemove
-// events.
-class EventManager {
- public:
-
- explicit EventManager() :
- mousedown_in_plugin_(false),
-#ifndef NDEBUG
- processing_event_queue_(false),
-#endif
- valid_(true) { }
-
- // Do per-timer-tick queue processing.
- void ProcessQueue();
-
- // Sets the callback for a events of a supplied type.
- // NOTE: The client takes ownership of the EventCallback you pass in. It will
- // be deleted if you call SetEventCallback a second time for the same event
- // type or if you call ClearEventCallback for that type.
- //
- // Parameters:
- // event_callback: EventCallback to call each time an event of the right
- // type occurs.
- // type: Type of event this callback handles.
- void SetEventCallback(Event::Type type, EventCallback* event_callback);
-
- // Clears the callback for events of a given type.
- void ClearEventCallback(Event::Type type);
-
- // Automatically drops some mousemove events to throttle event bandwidth.
- void AddEventToQueue(const Event& event);
-
- // Deletes all callbacks and events. May optionally be used before deletion,
- // as it accomplishes what the destructor does, but is safe to use twice or
- // not at all. After this is called, no events will be processed, although
- // all functions are still safe to call.
- void ClearAll();
-
- private:
- // One EventCallbackManager for each type of event that we might have to pass
- // through to the user.
- EventCallbackManager event_callbacks_[Event::NUM_TYPES];
- // Queue of events that have come in and need to get sent to the user's
- // handler(s). We throttle the rate at which events get handled by sending
- // out a fixed number [currently one] per timer tick. The ticks [and thus the
- // events] still happen even if rendering on-demand.
- EventQueue event_queue_;
- bool mousedown_in_plugin_;
-
-#ifndef NDEBUG
- // Test flag used to guarantee nonreentrance.
- bool processing_event_queue_;
-#endif
- bool valid_;
-
- DISALLOW_COPY_AND_ASSIGN(EventManager);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_EVENT_MANAGER_H_
diff --git a/o3d/core/cross/event_manager_test.cc b/o3d/core/cross/event_manager_test.cc
deleted file mode 100644
index c603965..0000000
--- a/o3d/core/cross/event_manager_test.cc
+++ /dev/null
@@ -1,78 +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 implements unit tests for class EventManager.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/event_manager.h"
-
-namespace o3d {
-
-class EventManagerTest : public testing::Test {
- protected:
- EventManagerTest() {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- EventManager event_manager_;
-};
-
-void EventManagerTest::SetUp() {
-}
-
-void EventManagerTest::TearDown() {
- event_manager_.ClearAll();
-}
-
-TEST_F(EventManagerTest, CanClearAllFromEventCallback) {
- class ClearAllEventCallback : public EventCallback {
- public:
- explicit ClearAllEventCallback(EventManager* event_manager)
- : event_manager_(event_manager) {
- }
- virtual void Run(const Event& event) {
- event_manager_->ClearAll();
- }
- private:
- EventManager* event_manager_;
- };
-
- event_manager_.SetEventCallback(
- Event::TYPE_CLICK,
- new ClearAllEventCallback(&event_manager_));
- Event event(Event::TYPE_CLICK);
- event_manager_.AddEventToQueue(event);
- event_manager_.ProcessQueue();
-}
-} // namespace o3d
diff --git a/o3d/core/cross/fake_vertex_source.cc b/o3d/core/cross/fake_vertex_source.cc
deleted file mode 100644
index 2796609..0000000
--- a/o3d/core/cross/fake_vertex_source.cc
+++ /dev/null
@@ -1,181 +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 definition of FakeVertexSource. It is only used in
-// unit testing and should not be compiled in with the plugin.
-
-#include "core/cross/fake_vertex_source.h"
-#include "core/cross/pointer_utils.h"
-#include "core/cross/buffer.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(FakeVertexSource, VertexSource);
-
-bool FakeVertexSource::SetVertexStream(Stream::Semantic semantic,
- int semantic_index,
- Field* field,
- unsigned int start_index) {
- Buffer* buffer = field->buffer();
- if (!buffer || !buffer->IsA(SourceBuffer::GetApparentClass())) {
- return false;
- }
-
- Stream::Ref stream(new Stream(service_locator(),
- field,
- start_index,
- semantic,
- semantic_index));
-
- // If a stream with the same semantic has already been set then remove it.
- RemoveVertexStream(semantic, semantic_index);
-
- ParamVertexBufferStream::Ref stream_param(new SlaveParamVertexBufferStream(
- service_locator(), this, stream));
- vertex_stream_params_.push_back(stream_param);
-
- return true;
-}
-
-bool FakeVertexSource::RemoveVertexStream(Stream::Semantic stream_semantic,
- int semantic_index) {
- StreamParamVector::iterator iter, end = vertex_stream_params_.end();
- for (iter = vertex_stream_params_.begin(); iter != end; ++iter) {
- const Stream& stream = (*iter)->stream();
- if (stream.semantic() == stream_semantic &&
- stream.semantic_index() == semantic_index) {
- vertex_stream_params_.erase(iter);
- return true;
- }
- }
- return false;
-}
-
-const Stream* FakeVertexSource::GetVertexStream(
- Stream::Semantic stream_semantic,
- int semantic_index) const {
- ParamVertexBufferStream* param = GetVertexStreamParam(stream_semantic,
- semantic_index);
- return param ? &param->stream() : NULL;
-}
-
-ParamVertexBufferStream* FakeVertexSource::GetVertexStreamParam(
- Stream::Semantic semantic,
- int semantic_index) const {
- StreamParamVector::const_iterator iter, end = vertex_stream_params_.end();
- for (iter = vertex_stream_params_.begin(); iter != end; ++iter) {
- const Stream& stream = (*iter)->stream();
- if (stream.semantic() == semantic &&
- stream.semantic_index() == semantic_index) {
- return *iter;
- }
- }
- return NULL;
-}
-
-void FakeVertexSource::UpdateStreams() {
- for (unsigned ii = 0; ii < vertex_stream_params_.size(); ++ii) {
- vertex_stream_params_[ii]->UpdateStream();
- }
-}
-
-void FakeVertexSource::UpdateOutputs() {
- ++update_outputs_call_count_;
-
- // Now copy our streams to their outputs.
- for (unsigned ii = 0; ii < vertex_stream_params_.size(); ++ii) {
- ParamVertexBufferStream* source_param = vertex_stream_params_[ii];
-
- // Make sure our upstream streams are ready
- ParamVertexBufferStream* input = down_cast<ParamVertexBufferStream*>(
- source_param->input_connection());
- if (input) {
- input->UpdateStream(); // Will automatically mark us as valid.
- } else {
- // Mark us as valid so we don't evaluate a second time.
- source_param->ValidateStream();
- }
-
- const Stream& source_stream = source_param->stream();
- const Field& source_field = source_stream.field();
- unsigned num_components = source_field.num_components();
- Buffer* source_buffer = source_field.buffer();
- if (source_buffer) {
- const ParamVector& outputs = source_param->output_connections();
- BufferLockHelper source_helper(source_buffer);
- void* source_data = source_helper.GetData(Buffer::READ_ONLY);
- if (source_data) {
- unsigned source_num_vertices = source_stream.GetMaxVertices();
- unsigned source_stride = source_buffer->stride();
- for (unsigned jj = 0; jj < outputs.size(); ++jj) {
- ParamVertexBufferStream* destination_param =
- down_cast<ParamVertexBufferStream*>(outputs[jj]);
- // TODO: Make calling this automatic so that each concrete
- // VertexSource does not have to manually call it.
- destination_param->ValidateStream();
- const Stream& destination_stream = destination_param->stream();
- const Field& destination_field = destination_stream.field();
- Buffer* destination_buffer = destination_field.buffer();
- if (destination_buffer) {
- BufferLockHelper destination_helper(destination_buffer);
- void* destination_data =
- destination_helper.GetData(Buffer::WRITE_ONLY);
- if (destination_data) {
- unsigned num_vertices = std::min(
- destination_stream.GetMaxVertices(),
- source_num_vertices);
- if (num_vertices < UINT_MAX) {
- unsigned destination_stride = destination_buffer->stride();
- float* source = PointerFromVoidPointer<float*>(
- source_data, source_field.offset());
- float* destination = PointerFromVoidPointer<float*>(
- destination_data, destination_field.offset());
- while (num_vertices) {
- for (unsigned jj = 0; jj < num_components; ++jj) {
- destination[jj] =
- source[jj] * (destination_stream.semantic_index() + 2);
- }
- destination = AddPointerOffset(destination,
- destination_stride);
- source = AddPointerOffset(source, source_stride);
- --num_vertices;
- }
- }
- }
- }
- }
- }
- }
- }
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/fake_vertex_source.h b/o3d/core/cross/fake_vertex_source.h
deleted file mode 100644
index 2a24358..0000000
--- a/o3d/core/cross/fake_vertex_source.h
+++ /dev/null
@@ -1,122 +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 declaration of FakeVertexSource. It is only used in
-// unit testing and is not compiled in with the plugin.
-
-#ifndef O3D_CORE_CROSS_FAKE_VERTEX_SOURCE_H_
-#define O3D_CORE_CROSS_FAKE_VERTEX_SOURCE_H_
-
-#include <vector>
-#include "core/cross/param_object.h"
-#include "core/cross/vertex_source.h"
-
-namespace o3d {
-
-// This class is here to test that a primitive has its vertices updated from a
-// VertexSource through binding. It copies its source vertices, multiplying each
-// one by 2 + the semantic index of the destination stream.
-class FakeVertexSource : public VertexSource {
- public:
- explicit FakeVertexSource(ServiceLocator* service_locator)
- : VertexSource(service_locator),
- update_outputs_call_count_() {
- }
-
- // Binds a SourceBuffer and defines how the data in the buffer should be
- // accessed and interpreted.
- bool SetVertexStream(Stream::Semantic semantic,
- int semantic_index,
- Field* field,
- unsigned int start_index);
-
- // Removes a vertex stream from this primitive.
- // Returns true if the specified stream existed.
- bool RemoveVertexStream(Stream::Semantic stream_semantic,
- int semantic_index);
-
- // Searches the vertex streams bound to the shape for one with the given
- // stream semantic. If a stream is not found then it returns NULL.
- const Stream* GetVertexStream(Stream::Semantic stream_semantic,
- int semantic_index) const;
-
- // Updates all the VertexBuffers bound to streams on this VertexSource.
- void UpdateStreams();
-
- // Updates the VertexBuffers bound to streams on this VertexSource.
- void UpdateOutputs();
-
- // For testing.
- unsigned update_outputs_call_count() {
- return update_outputs_call_count_;
- }
-
- // Overriden from
- virtual ParamVertexBufferStream* GetVertexStreamParam(
- Stream::Semantic semantic,
- int semantic_index) const;
-
- private:
- class SlaveParamVertexBufferStream : public ParamVertexBufferStream {
- public:
- SlaveParamVertexBufferStream(ServiceLocator* service_locator,
- FakeVertexSource* master,
- Stream* stream)
- : ParamVertexBufferStream(service_locator, stream, true, false),
- master_(master) {
- }
-
- virtual void ComputeValue() {
- master_->UpdateOutputs();
- }
-
- private:
- FakeVertexSource* master_;
- DISALLOW_COPY_AND_ASSIGN(SlaveParamVertexBufferStream);
- };
-
- typedef std::vector<SlaveParamVertexBufferStream::Ref> StreamParamVector;
-
- unsigned update_outputs_call_count_;
- StreamParamVector vertex_stream_params_;
-
- O3D_DECL_CLASS(FakeVertexSource, VertexSource);
- DISALLOW_COPY_AND_ASSIGN(FakeVertexSource);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_FAKE_VERTEX_SOURCE_H_
-
-
-
-
diff --git a/o3d/core/cross/features.cc b/o3d/core/cross/features.cc
deleted file mode 100644
index 4e1fc85..0000000
--- a/o3d/core/cross/features.cc
+++ /dev/null
@@ -1,137 +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 Features implementation
-
-#include "core/cross/features.h"
-#include <vector>
-#include "base/string_util.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-const InterfaceId Features::kInterfaceId =
- InterfaceTraits<Features>::kInterfaceId;
-
-Features::Features(ServiceLocator* service_locator)
- : service_(service_locator, this),
- floating_point_textures_(true),
- large_geometry_(true),
- windowless_(false),
- not_anti_aliased_(false),
- flip_textures_(true),
- init_status_(Renderer::SUCCESS),
- render_mode_(Renderer::RENDER_MODE_3D) {
- // NOTE: For backward compatibility floating_point_textures and
- // large_geometry default to true. o3djs.util.makeClients before 0.1.35.0
- // does not set the o3d_features plugin parameters and therefore
- // Features::Init is not called. o3djs,util.makeClients after and
- // including 0.1.35.0 do set o3d_features and therefore Init is called
- // which sets those to false to start.
-}
-
-void Features::ParseFeatures(const std::vector<std::string>& features,
- bool version_pass) {
- for (size_t jj = 0; jj < features.size(); ++jj) {
- const std::string& feature_string = features[jj];
- std::vector<std::string> arguments;
- SplitString(feature_string, '=', &arguments);
- const std::string feature(arguments.front());
- arguments.erase(arguments.begin());
- if (version_pass) {
- if (feature.compare("APIVersion") == 0 && !arguments.empty()) {
- int version[4] = { 0, };
- std::vector<std::string> parts;
- SplitString(arguments[0], '.', &parts);
- size_t num_parts = std::min(parts.size(), arraysize(version));
- for (size_t ii = 0; ii < num_parts; ++ii) {
- StringToInt(parts[ii], &version[ii]);
- }
- if (version[0] >= 0 && version[1] >= 1 && version[2] >= 40) {
- flip_textures_ = false;
- }
- }
- } else {
- if (feature.compare("FloatingPointTextures") == 0) {
- floating_point_textures_ = true;
- } else if (feature.compare("LargeGeometry") == 0) {
- large_geometry_ = true;
- } else if (feature.compare("Windowless") == 0) {
- windowless_ = true;
- } else if (feature.compare("NotAntiAliased") == 0) {
- not_anti_aliased_ = true;
- } else if (feature.compare("FlipTextures") == 0) {
- flip_textures_ = true;
- } else if (feature.compare("MaxCapabilities") == 0) {
- large_geometry_ = true;
- floating_point_textures_ = true;
- } else if (feature.compare("InitStatus") == 0 &&
- !arguments.empty()) {
- int value;
- StringToInt(arguments[0], &value);
- init_status_ = static_cast<Renderer::InitStatus>(value);
- } else if (feature.compare("RenderMode") == 0 &&
- arguments.size() == 1) {
- std::string render_mode_str;
- const char* override;
- if (arguments[0].compare("Auto") == 0 &&
- (override = getenv("O3D_OVERRIDE_RENDER_MODE_AUTO"))) {
- // For testing purposes, allow developers to override RenderMode=Auto
- // with an environment variable. This is useful for testing 2D mode
- // without having to alter the web app.
- render_mode_str = override;
- } else {
- render_mode_str = arguments[0];
- }
- if (render_mode_str.compare("Auto") == 0) {
- render_mode_ = Renderer::RENDER_MODE_AUTO;
- } else if (render_mode_str.compare("3D") == 0) {
- render_mode_ = Renderer::RENDER_MODE_3D;
- } else if (render_mode_str.compare("2D") == 0) {
- render_mode_ = Renderer::RENDER_MODE_2D;
- }
- }
- }
- }
-}
-
-void Features::Init(const String& requested_features) {
- large_geometry_ = false;
- floating_point_textures_ = false;
-
- std::vector<std::string> features;
- SplitString(requested_features, ',', &features);
- ParseFeatures(features, true);
- ParseFeatures(features, false);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/features.h b/o3d/core/cross/features.h
deleted file mode 100644
index 133eb3a..0000000
--- a/o3d/core/cross/features.h
+++ /dev/null
@@ -1,122 +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 Features declaration.
-
-#ifndef O3D_CORE_CROSS_FEATURES_H_
-#define O3D_CORE_CROSS_FEATURES_H_
-
-#include <string>
-#include <vector>
-#include "core/cross/types.h"
-#include "core/cross/service_locator.h"
-#include "core/cross/service_implementation.h"
-#include "core/cross/renderer.h"
-
-namespace o3d {
-
-// Features is a class that represents features requested by the user
-// for the O3D.
-class Features {
- public:
- static const InterfaceId kInterfaceId;
-
- explicit Features(ServiceLocator* service_locator);
-
- // Initalizes the Features with the user requested features.
- // Parameters:
- // requested_features: A comma separate string of features.
- void Init(const String& requested_features);
-
- bool floating_point_textures() const {
- return floating_point_textures_;
- }
-
- bool large_geometry() const {
- return large_geometry_;
- }
-
- bool windowless() const {
- return windowless_;
- }
-
- bool not_anti_aliased() const {
- return not_anti_aliased_;
- }
-
- bool flip_textures() const {
- return flip_textures_;
- }
-
- // This can be used to force the renderer to fail for testing.
- Renderer::InitStatus init_status() const {
- return init_status_;
- }
-
- Renderer::RenderMode render_mode() const {
- return render_mode_;
- }
-
- // For use by SuppressRenderModeAuto() in main_mac.mm.
- void set_render_mode(Renderer::RenderMode render_mode) {
- render_mode_ = render_mode;
- }
-
- private:
- // Parses the features strings.
- // Parameters:
- // features: vector of feature strings.
- // version_pass: True = only check for APIVersion, false = check everything
- // but APIVersion.
- void ParseFeatures(const std::vector<std::string>& features,
- bool version_pass);
-
- ServiceImplementation<Features> service_;
-
- bool floating_point_textures_;
- bool large_geometry_;
- bool windowless_;
- bool not_anti_aliased_;
- bool flip_textures_;
- Renderer::InitStatus init_status_;
- Renderer::RenderMode render_mode_;
-
- DISALLOW_COPY_AND_ASSIGN(Features);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_FEATURES_H_
-
-
-
-
diff --git a/o3d/core/cross/features_test.cc b/o3d/core/cross/features_test.cc
deleted file mode 100644
index e844e5f..0000000
--- a/o3d/core/cross/features_test.cc
+++ /dev/null
@@ -1,278 +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 implements unit tests for class Features.
-
-#include "core/cross/client.h"
-#include "tests/common/win/testing_common.h"
-#include "core/cross/features.h"
-
-namespace o3d {
-
-class FeaturesTest : public testing::Test {
- public:
- ServiceLocator* service_locator() {
- return service_locator_;
- }
-
- protected:
- FeaturesTest() { }
-
- virtual void SetUp() {
- // We need to create a new SerivceLocator because the global one
- // already has a global Features object registered on it.
- service_locator_ = new ServiceLocator;
- }
-
- virtual void TearDown() {
- delete service_locator_;
- }
-
- ServiceLocator* service_locator_;
-};
-
-TEST_F(FeaturesTest, Basic) {
- Features* features = new Features(service_locator());
-
- // Check that the features start off correctly.
- //
- // NOTE: For backward compatibility floating_point_textures and
- // large_geometry default to true. o3djs.util.makeClients before 0.1.35.0
- // does not set the o3d_features plugin parameters and therefore
- // Features::Init is not called. o3djs,util.makeClients after and
- // including 0.1.35.0 do set o3d_features and therefore Init is called
- // which sets those to false to start.
- //
- // NOTE: pre 0.1.40.0 flip_textures defaults to true. After it defaults to
- // false.
-
- EXPECT_TRUE(features->floating_point_textures());
- EXPECT_TRUE(features->large_geometry());
- EXPECT_FALSE(features->windowless());
- EXPECT_FALSE(features->not_anti_aliased());
- EXPECT_TRUE(features->flip_textures());
- EXPECT_EQ(features->init_status(), Renderer::SUCCESS);
-
- delete features;
-}
-
-TEST_F(FeaturesTest, Empty) {
- Features* features = new Features(service_locator());
-
- features->Init("");
-
- // Check that the features start off as false.
- EXPECT_FALSE(features->floating_point_textures());
- EXPECT_FALSE(features->large_geometry());
- EXPECT_FALSE(features->windowless());
- EXPECT_FALSE(features->not_anti_aliased());
- EXPECT_TRUE(features->flip_textures());
- EXPECT_EQ(features->init_status(), Renderer::SUCCESS);
-
- delete features;
-}
-
-TEST_F(FeaturesTest, APIVersion0_1_38_0) {
- Features* features = new Features(service_locator());
-
- features->Init("APIVersion=0.1.38.0");
-
- // Check that the features start off as false.
- EXPECT_FALSE(features->floating_point_textures());
- EXPECT_FALSE(features->large_geometry());
- EXPECT_FALSE(features->windowless());
- EXPECT_FALSE(features->not_anti_aliased());
- EXPECT_TRUE(features->flip_textures());
- EXPECT_EQ(features->init_status(), Renderer::SUCCESS);
-
- delete features;
-}
-
-TEST_F(FeaturesTest, APIVersion0_1_40_0) {
- Features* features = new Features(service_locator());
-
- features->Init("APIVersion=0.1.40.0");
-
- // Check that the features start off as false.
- EXPECT_FALSE(features->floating_point_textures());
- EXPECT_FALSE(features->large_geometry());
- EXPECT_FALSE(features->windowless());
- EXPECT_FALSE(features->not_anti_aliased());
- EXPECT_FALSE(features->flip_textures());
- EXPECT_EQ(features->init_status(), Renderer::SUCCESS);
-
- delete features;
-}
-
-TEST_F(FeaturesTest, FloatingPointTextures) {
- Features* features = new Features(service_locator());
-
- features->Init("FloatingPointTextures");
-
- EXPECT_TRUE(features->floating_point_textures());
- EXPECT_FALSE(features->large_geometry());
- EXPECT_FALSE(features->windowless());
- EXPECT_FALSE(features->not_anti_aliased());
- EXPECT_TRUE(features->flip_textures());
- EXPECT_EQ(features->init_status(), Renderer::SUCCESS);
-
- delete features;
-}
-
-TEST_F(FeaturesTest, LargeGeometry) {
- Features* features = new Features(service_locator());
-
- features->Init("LargeGeometry");
-
- EXPECT_FALSE(features->floating_point_textures());
- EXPECT_TRUE(features->large_geometry());
- EXPECT_FALSE(features->windowless());
- EXPECT_FALSE(features->not_anti_aliased());
- EXPECT_TRUE(features->flip_textures());
- EXPECT_EQ(features->init_status(), Renderer::SUCCESS);
-
- delete features;
-}
-
-TEST_F(FeaturesTest, Windowless) {
- Features* features = new Features(service_locator());
-
- features->Init("Windowless");
-
- EXPECT_FALSE(features->floating_point_textures());
- EXPECT_FALSE(features->large_geometry());
- EXPECT_TRUE(features->windowless());
- EXPECT_FALSE(features->not_anti_aliased());
- EXPECT_TRUE(features->flip_textures());
- EXPECT_EQ(features->init_status(), Renderer::SUCCESS);
-
- delete features;
-}
-
-TEST_F(FeaturesTest, NotAntiAliased) {
- Features* features = new Features(service_locator());
-
- features->Init("NotAntiAliased");
-
- EXPECT_FALSE(features->floating_point_textures());
- EXPECT_FALSE(features->large_geometry());
- EXPECT_FALSE(features->windowless());
- EXPECT_TRUE(features->not_anti_aliased());
- EXPECT_TRUE(features->flip_textures());
- EXPECT_EQ(features->init_status(), Renderer::SUCCESS);
-
- delete features;
-}
-
-TEST_F(FeaturesTest, FlipTextures) {
- Features* features = new Features(service_locator());
-
- features->Init("FlipTextures,APIVersion=0.1.40.0");
-
- EXPECT_FALSE(features->floating_point_textures());
- EXPECT_FALSE(features->large_geometry());
- EXPECT_FALSE(features->windowless());
- EXPECT_FALSE(features->not_anti_aliased());
- EXPECT_TRUE(features->flip_textures());
- EXPECT_EQ(features->init_status(), Renderer::SUCCESS);
-
- delete features;
-}
-
-TEST_F(FeaturesTest, InitStatus) {
- static Renderer::InitStatus statuses[] = {
- Renderer::OUT_OF_RESOURCES,
- Renderer::GPU_NOT_UP_TO_SPEC,
- Renderer::INITIALIZATION_ERROR,
- };
- for (unsigned ii = 0; ii < arraysize(statuses); ++ii) {
- Features* features = new Features(service_locator());
- std::string s(StringPrintf("InitStatus=%d", statuses[ii]));
- features->Init(s);
-
- EXPECT_FALSE(features->floating_point_textures());
- EXPECT_FALSE(features->large_geometry());
- EXPECT_FALSE(features->windowless());
- EXPECT_FALSE(features->not_anti_aliased());
- EXPECT_TRUE(features->flip_textures());
- EXPECT_EQ(features->init_status(), statuses[ii]);
-
- delete features;
- }
-}
-
-TEST_F(FeaturesTest, BadInput) {
- Features* features = new Features(service_locator());
-
- features->Init(",abcd,,efe,FloatingPointT,");
-
- EXPECT_FALSE(features->floating_point_textures());
- EXPECT_FALSE(features->large_geometry());
- EXPECT_FALSE(features->windowless());
- EXPECT_FALSE(features->not_anti_aliased());
- EXPECT_TRUE(features->flip_textures());
- EXPECT_EQ(features->init_status(), Renderer::SUCCESS);
-
- delete features;
-}
-
-TEST_F(FeaturesTest, MultipleFeatures) {
- Features* features = new Features(service_locator());
-
- features->Init("FloatingPointTextures,Windowless");
-
- EXPECT_TRUE(features->floating_point_textures());
- EXPECT_FALSE(features->large_geometry());
- EXPECT_TRUE(features->windowless());
- EXPECT_FALSE(features->not_anti_aliased());
- EXPECT_TRUE(features->flip_textures());
- EXPECT_EQ(features->init_status(), Renderer::SUCCESS);
-
- delete features;
-}
-
-TEST_F(FeaturesTest, MaxCapabilities) {
- Features* features = new Features(service_locator());
-
- features->Init("MaxCapabilities");
-
- EXPECT_TRUE(features->floating_point_textures());
- EXPECT_TRUE(features->large_geometry());
- EXPECT_FALSE(features->windowless());
- EXPECT_FALSE(features->not_anti_aliased());
- EXPECT_TRUE(features->flip_textures());
- EXPECT_EQ(features->init_status(), Renderer::SUCCESS);
-
- delete features;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/field.cc b/o3d/core/cross/field.cc
deleted file mode 100644
index 0a31eff..0000000
--- a/o3d/core/cross/field.cc
+++ /dev/null
@@ -1,618 +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 definitions for the Buffer, VertexBuffer and
-// IndexBuffer.
-
-#include <vector>
-#include "core/cross/field.h"
-#include "core/cross/error.h"
-#include "core/cross/buffer.h"
-#include "core/cross/pointer_utils.h"
-#include "core/cross/types.h"
-#include "core/cross/renderer.h"
-#include "import/cross/memory_stream.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Field, NamedObject);
-O3D_DEFN_CLASS(FloatField, Field);
-O3D_DEFN_CLASS(UInt32Field, Field);
-O3D_DEFN_CLASS(UByteNField, Field);
-
-namespace {
-
-// Sets a field from a specific type of source converting through a
-// convertFunction.
-template <typename SourceType,
- typename DestinationType,
- DestinationType convert_function(SourceType value)>
-void SetFrom(const SourceType* source,
- unsigned source_stride,
- Field* field,
- unsigned destination_start_index,
- unsigned num_elements) {
- if (!field->RangeValid(destination_start_index, num_elements)) {
- return;
- }
-
- Buffer* buffer = field->buffer();
- o3d::BufferLockHelper helper(buffer);
- void* buffer_data = helper.GetData(o3d::Buffer::WRITE_ONLY);
- if (!buffer_data) {
- O3D_ERROR(field->service_locator())
- << "could not lock buffer for field '" << field->name() << "'";
- return;
- }
- unsigned destination_stride = buffer->stride();
- unsigned num_components = field->num_components();
- DestinationType* destination =
- PointerFromVoidPointer<DestinationType*>(
- buffer_data,
- destination_start_index * destination_stride + field->offset());
- for (; num_elements; --num_elements) {
- for (unsigned cc = 0; cc < num_components; ++cc) {
- destination[cc] = convert_function(source[cc]);
- }
- source += source_stride;
- destination = AddPointerOffset(destination, destination_stride);
- }
-}
-
-template <typename SourceType,
- typename DestinationType,
- DestinationType convert_function(SourceType value)>
-void SetFromWithSwizzle(const SourceType* source,
- unsigned source_stride,
- Field* field,
- unsigned destination_start_index,
- unsigned num_elements,
- const int* swizzle_table) {
- if (!field->RangeValid(destination_start_index, num_elements)) {
- return;
- }
-
- Buffer* buffer = field->buffer();
- o3d::BufferLockHelper helper(buffer);
- void* buffer_data = helper.GetData(o3d::Buffer::WRITE_ONLY);
- if (!buffer_data) {
- O3D_ERROR(field->service_locator())
- << "could not lock buffer for field '" << field->name() << "'";
- return;
- }
- unsigned destination_stride = buffer->stride();
- unsigned num_components = field->num_components();
- DestinationType* destination =
- PointerFromVoidPointer<DestinationType*>(
- buffer_data,
- destination_start_index * destination_stride + field->offset());
- for (; num_elements; --num_elements) {
- for (unsigned cc = 0; cc < num_components; ++cc) {
- destination[swizzle_table[cc]] = convert_function(source[cc]);
- }
- source += source_stride;
- destination = AddPointerOffset(destination, destination_stride);
- }
-}
-
-// Gets a field copying into a specific type of destination converting through a
-// convertFunction.
-template <typename SourceType,
- typename DestinationType,
- DestinationType convert_function(SourceType value)>
-void GetAs(const Field* field_c,
- unsigned source_start_index,
- DestinationType* destination,
- unsigned destination_stride,
- unsigned num_elements) {
- Field* field = const_cast<Field*>(field_c);
- if (!field->RangeValid(source_start_index, num_elements)) {
- return;
- }
-
- Buffer* buffer = field->buffer();
- o3d::BufferLockHelper helper(buffer);
- void* buffer_data = helper.GetData(o3d::Buffer::READ_ONLY);
- if (!buffer_data) {
- O3D_ERROR(field->service_locator())
- << "could not lock buffer for field '" << field->name() << "'";
- return;
- }
- unsigned source_stride = buffer->stride();
- unsigned num_components = field->num_components();
- SourceType* source = PointerFromVoidPointer<SourceType*>(
- buffer_data,
- source_start_index * source_stride + field->offset());
- for (; num_elements; --num_elements) {
- for (unsigned cc = 0; cc < num_components; ++cc) {
- destination[cc] = convert_function(source[cc]);
- }
- source = AddPointerOffset(source, source_stride);
- destination += destination_stride;
- }
-}
-
-
-// Gets a field copying into a specific type of destination converting through a
-// convertFunction.
-template <typename SourceType,
- typename DestinationType,
- DestinationType convert_function(SourceType value)>
-void GetAsWithSwizzle(const Field* field_c,
- unsigned source_start_index,
- DestinationType* destination,
- unsigned destination_stride,
- unsigned num_elements,
- const int* swizzle_table) {
- Field* field = const_cast<Field*>(field_c);
- if (!field->RangeValid(source_start_index, num_elements)) {
- return;
- }
-
- Buffer* buffer = field->buffer();
- o3d::BufferLockHelper helper(buffer);
- void* buffer_data = helper.GetData(o3d::Buffer::READ_ONLY);
- if (!buffer_data) {
- O3D_ERROR(field->service_locator())
- << "could not lock buffer for field '" << field->name() << "'";
- return;
- }
- unsigned source_stride = buffer->stride();
- unsigned num_components = field->num_components();
- SourceType* source = PointerFromVoidPointer<SourceType*>(
- buffer_data,
- source_start_index * source_stride + field->offset());
- for (; num_elements; --num_elements) {
- for (unsigned cc = 0; cc < num_components; ++cc) {
- destination[cc] = convert_function(source[swizzle_table[cc]]);
- }
- source = AddPointerOffset(source, source_stride);
- destination += destination_stride;
- }
-}
-
-inline float ConvertFloatToFloat(float value) {
- return value;
-}
-
-// Note that |value| is an int here since we want to avoid loading
-// an incorrectly swapped value into a float register
-inline float ConvertLittleEndianFloatToFloat(uint32 value) {
- union UInt32FloatUnion {
- uint32 i;
- float f;
- };
- UInt32FloatUnion u;
- u.i = MemoryReadStream::GetLittleEndianUInt32(
- reinterpret_cast<uint32*>(&value));
- return u.f;
-}
-
-inline uint32 ConvertLittleEndianUInt32ToUInt32(uint32 value) {
- return MemoryReadStream::GetLittleEndianUInt32(
- reinterpret_cast<uint32*>(&value));
-}
-
-inline float ConvertUInt32ToFloat(uint32 value) {
- return static_cast<float>(value);
-}
-
-inline float ConvertUByteNToFloat(uint8 value) {
- return static_cast<float>(value) / 255.0f;
-}
-
-inline uint32 ConvertFloatToUInt32(float value) {
- return static_cast<uint32>(std::max(0.0f, value));
-}
-
-inline uint32 ConvertUInt32ToUInt32(uint32 value) {
- return value;
-}
-
-inline uint32 ConvertUByteNToUInt32(uint8 value) {
- return static_cast<uint32>(value > 0);
-}
-
-inline uint8 ConvertFloatToUByteN(float value) {
- return static_cast<uint8>(floorf(
- std::min(1.0f, std::max(0.0f, value)) * 255.0f + 0.5f));
-}
-
-inline uint8 ConvertUInt32ToUByteN(uint32 value) {
- return static_cast<uint8>(std::min<unsigned>(255, value));
-}
-
-inline uint8 ConvertUByteNToUByteN(uint8 value) {
- return value;
-}
-
-} // anonymous namespace.
-
-Field::Field(ServiceLocator* service_locator,
- Buffer* buffer,
- unsigned num_components,
- unsigned offset)
- : NamedObject(service_locator),
- buffer_(buffer),
- num_components_(num_components),
- offset_(offset) {
- DCHECK(num_components > 0);
-}
-
-bool Field::RangeValid(unsigned int start_index, unsigned int num_elements) {
- if (!buffer_) {
- O3D_ERROR(service_locator())
- << "The buffer for field '" << name() << "' no longer exists";
- return false;
- }
- if (start_index + num_elements > buffer_->num_elements() ||
- start_index + num_elements < start_index) {
- O3D_ERROR(service_locator())
- << "Range is not valid for Buffer '"<< buffer_->name()
- << "' on Field '" << name() << "'";
- return false;
- }
- return true;
-}
-
-void Field::Copy(const Field& source) {
- if (!source.IsA(GetClass())) {
- O3D_ERROR(service_locator())
- << "source field of type " << source.GetClassName()
- << " is not compatible with field of type " << GetClassName();
- return;
- }
- if (!source.buffer()) {
- O3D_ERROR(service_locator()) << "source buffer is null";
- return;
- }
- if (!buffer()) {
- O3D_ERROR(service_locator()) << "destination buffer is null";
- return;
- }
- ConcreteCopy(source);
-}
-
-// FloatField -------------------
-
-FloatField::FloatField(ServiceLocator* service_locator,
- Buffer* buffer,
- unsigned num_components,
- unsigned offset)
- : Field(service_locator, buffer, num_components, offset) {
-}
-
-size_t FloatField::GetFieldComponentSize() const {
- return sizeof(float); // NOLINT
-}
-
-void FloatField::SetFromFloats(const float* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements) {
- SetFrom<const float, float, ConvertFloatToFloat>(
- source, source_stride, this, destination_start_index, num_elements);
-}
-
-void FloatField::SetFromUInt32s(const uint32* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements) {
- SetFrom<const uint32, float, ConvertUInt32ToFloat>(
- source, source_stride, this, destination_start_index, num_elements);
-}
-
-void FloatField::SetFromUByteNs(const uint8* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements) {
- SetFrom<const uint8, float, ConvertUByteNToFloat>(
- source, source_stride, this, destination_start_index, num_elements);
-}
-
-bool FloatField::SetFromMemoryStream(MemoryReadStream* stream) {
- if (!buffer()) {
- O3D_ERROR(service_locator())
- << "The buffer for field '" << name() << "' no longer exists";
- return false;
- }
-
- size_t num_elements = buffer()->num_elements();
-
- // sanity check that the stream has enough data
- if (stream->GetRemainingByteCount() < num_elements * size()) {
- return false;
- }
-
- // Note that we're interpreting the source as uint32 since that's
- // what ConvertLittleEndianFloatToFloat wants (byte swapping for
- // float32 and uint32 are the same). Interpreting floating point
- // values before they're byte-swapped can cause problems...
- const uint32 *source = stream->GetDirectMemoryPointerAs<const uint32>();
-
- stream->Skip(num_elements * size());
-
- SetFrom<const uint32, float, ConvertLittleEndianFloatToFloat>(
- source, num_components(), this, 0, num_elements);
-
- return true;
-}
-
-void FloatField::GetAsFloats(unsigned source_start_index,
- float* destination,
- unsigned destination_stride,
- unsigned num_elements) const {
- GetAs<const float, float, ConvertFloatToFloat>(
- this,
- source_start_index,
- destination,
- destination_stride,
- num_elements);
-}
-
-void FloatField::ConcreteCopy(const Field& source) {
- DCHECK(source.IsA(GetClass()));
- DCHECK(source.buffer());
- unsigned num_components = source.num_components();
- unsigned num_elements = source.buffer()->num_elements();
- scoped_array<float> temp(new float[num_components * num_elements]);
- source.GetAsFloats(0, temp.get(), num_components, num_elements);
- SetFromFloats(temp.get(), num_components, 0, num_elements);
-}
-
-Field::Ref FloatField::Create(ServiceLocator* service_locator,
- Buffer* buffer,
- unsigned num_components,
- unsigned offset) {
- return Field::Ref(
- new FloatField(service_locator, buffer, num_components, offset));
-}
-
-// UInt32Field -------------------
-
-UInt32Field::UInt32Field(ServiceLocator* service_locator,
- Buffer* buffer,
- unsigned num_components,
- unsigned offset)
- : Field(service_locator, buffer, num_components, offset) {
-}
-
-size_t UInt32Field::GetFieldComponentSize() const {
- return sizeof(uint32); // NOLINT
-}
-
-void UInt32Field::SetFromFloats(const float* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements) {
- SetFrom<const float, uint32, ConvertFloatToUInt32>(
- source, source_stride, this, destination_start_index, num_elements);
-}
-
-void UInt32Field::SetFromUInt32s(const uint32* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements) {
- SetFrom<const uint32, uint32, ConvertUInt32ToUInt32>(
- source, source_stride, this, destination_start_index, num_elements);
-}
-
-void UInt32Field::SetFromUByteNs(const uint8* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements) {
- SetFrom<const uint8, uint32, ConvertUByteNToUInt32>(
- source, source_stride, this, destination_start_index, num_elements);
-}
-
-bool UInt32Field::SetFromMemoryStream(MemoryReadStream* stream) {
- if (!buffer()) {
- O3D_ERROR(service_locator())
- << "The buffer for field '" << name() << "' no longer exists";
- return false;
- }
-
- size_t num_elements = buffer()->num_elements();
-
- // sanity check that the stream has enough data
- if (stream->GetRemainingByteCount() < num_elements * size()) {
- return false;
- }
-
- const uint32 *source = stream->GetDirectMemoryPointerAs<const uint32>();
-
- stream->Skip(num_elements * size());
-
- SetFrom<const uint32, uint32, ConvertLittleEndianUInt32ToUInt32>(
- source, num_components(), this, 0, num_elements);
-
- return true;
-}
-
-void UInt32Field::GetAsFloats(unsigned source_start_index,
- float* destination,
- unsigned destination_stride,
- unsigned num_elements) const {
- GetAs<const uint32, float, ConvertUInt32ToFloat>(
- this,
- source_start_index,
- destination,
- destination_stride,
- num_elements);
-}
-
-void UInt32Field::GetAsUInt32s(unsigned source_start_index,
- uint32* destination,
- unsigned destination_stride,
- unsigned num_elements) const {
- GetAs<const uint32, uint32, ConvertUInt32ToUInt32>(
- this,
- source_start_index,
- destination,
- destination_stride,
- num_elements);
-}
-
-void UInt32Field::ConcreteCopy(const Field& source) {
- DCHECK(source.IsA(GetClass()));
- DCHECK(source.buffer());
- unsigned num_components = source.num_components();
- unsigned num_elements = source.buffer()->num_elements();
- scoped_array<uint32> temp(new uint32[num_components * num_elements]);
- down_cast<const UInt32Field*>(&source)->GetAsUInt32s(
- 0, temp.get(), num_components, num_elements);
- SetFromUInt32s(temp.get(), num_components, 0, num_elements);
-}
-
-Field::Ref UInt32Field::Create(ServiceLocator* service_locator,
- Buffer* buffer,
- unsigned num_components,
- unsigned offset) {
- return Field::Ref(
- new UInt32Field(service_locator, buffer, num_components, offset));
-}
-
-// UByteNField -------------------
-
-UByteNField::UByteNField(ServiceLocator* service_locator,
- Buffer* buffer,
- unsigned num_components,
- unsigned offset)
- : Field(service_locator, buffer, num_components, offset) {
- Renderer* renderer = service_locator->GetService<Renderer>();
- DCHECK(renderer);
- DCHECK(num_components % 4 == 0);
-
- swizzle_table_ = renderer->GetRGBAUByteNSwizzleTable();
-}
-
-size_t UByteNField::GetFieldComponentSize() const {
- return sizeof(uint8); // NOLINT
-}
-
-void UByteNField::SetFromFloats(const float* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements) {
- SetFromWithSwizzle<const float, uint8, ConvertFloatToUByteN>(
- source, source_stride, this, destination_start_index, num_elements,
- swizzle_table_);
-}
-
-void UByteNField::SetFromUInt32s(const uint32* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements) {
- SetFromWithSwizzle<const uint32, uint8, ConvertUInt32ToUByteN>(
- source, source_stride, this, destination_start_index, num_elements,
- swizzle_table_);
-}
-
-void UByteNField::SetFromUByteNs(const uint8* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements) {
- SetFromWithSwizzle<const uint8, uint8, ConvertUByteNToUByteN>(
- source, source_stride, this, destination_start_index, num_elements,
- swizzle_table_);
-}
-
-bool UByteNField::SetFromMemoryStream(MemoryReadStream* stream) {
- if (!buffer()) {
- O3D_ERROR(service_locator())
- << "The buffer for field '" << name() << "' no longer exists";
- return false;
- }
-
- size_t num_elements = buffer()->num_elements();
-
- // sanity check that the stream has enough data
- if (stream->GetRemainingByteCount() < num_elements * size()) {
- return false;
- }
-
- const uint8 *source = stream->GetDirectMemoryPointerAs<const uint8>();
- stream->Skip(num_elements * size());
-
- SetFromWithSwizzle<const uint8, uint8, ConvertUByteNToUByteN>(
- source, num_components(), this, 0, num_elements, swizzle_table_);
-
- return true;
-}
-
-void UByteNField::GetAsFloats(unsigned source_start_index,
- float* destination,
- unsigned destination_stride,
- unsigned num_elements) const {
- GetAsWithSwizzle<const uint8, float, ConvertUByteNToFloat>(
- this,
- source_start_index,
- destination,
- destination_stride,
- num_elements,
- swizzle_table_);
-}
-
-void UByteNField::GetAsUByteNs(unsigned source_start_index,
- uint8* destination,
- unsigned destination_stride,
- unsigned num_elements) const {
- GetAsWithSwizzle<const uint8, uint8, ConvertUByteNToUByteN>(
- this,
- source_start_index,
- destination,
- destination_stride,
- num_elements,
- swizzle_table_);
-}
-
-void UByteNField::ConcreteCopy(const Field& source) {
- DCHECK(source.IsA(GetClass()));
- DCHECK(source.buffer());
- unsigned num_components = source.num_components();
- unsigned num_elements = source.buffer()->num_elements();
- scoped_array<uint8> temp(new uint8[num_components * num_elements]);
- down_cast<const UByteNField*>(&source)->GetAsUByteNs(
- 0, temp.get(), num_components, num_elements);
- SetFromUByteNs(temp.get(), num_components, 0, num_elements);
-}
-
-
-Field::Ref UByteNField::Create(ServiceLocator* service_locator,
- Buffer* buffer,
- unsigned num_components,
- unsigned offset) {
- return Field::Ref(
- new UByteNField(service_locator, buffer, num_components, offset));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/field.h b/o3d/core/cross/field.h
deleted file mode 100644
index 2a64098..0000000
--- a/o3d/core/cross/field.h
+++ /dev/null
@@ -1,397 +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 declaration for the Field, FloatField, UInt32Field and
-// UByteNField classes.
-
-#ifndef O3D_CORE_CROSS_FIELD_H_
-#define O3D_CORE_CROSS_FIELD_H_
-
-#include <vector>
-#include "core/cross/named_object.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-class Buffer;
-class MemoryReadStream;
-
-// A Field is an abstract base class that manages a set of components in a
-// buffer of a specific type. Fields are managed by Buffers and can not be
-// directly created. When a Buffer is destroyed or if a Field is removed from a
-// Buffer the Field's buffer pointer will be set to NULL.
-class Field : public NamedObject {
- public:
- typedef SmartPointer<Field> Ref;
-
- // These IDs are used for serialization and are not exposed to
- // Javascript.
- enum FieldID {
- FIELDID_UNKNOWN = 0,
- FIELDID_FLOAT32 = 1,
- FIELDID_UINT32 = 2,
- FIELDID_BYTE = 3
- };
-
- Field(ServiceLocator* service_locator,
- Buffer* buffer,
- unsigned num_components,
- unsigned offset);
-
- // The number of components in this field.
- unsigned num_components() const {
- return num_components_;
- }
-
- // The offset for this field.
- unsigned offset() const {
- return offset_;
- }
-
- // The size of this field in bytes.
- size_t size() const {
- return num_components_ * GetFieldComponentSize();
- }
-
- // The buffer this field belongs to. Can be NULL if the buffer has been
- // deleted.
- Buffer* buffer() const {
- return buffer_;
- }
-
- // Returns the size of a field type in bytes.
- virtual size_t GetFieldComponentSize() const = 0;
-
- // Sets this field from source floats
- //
- // This function copies elements from the source array to the field.
- // It assumes that there are a multiple of N components in the source where N
- // is the number of components in the field. In other words, if the field has
- // 3 components then passing a num_elements of 2 would copy 2 elements, each 3
- // components.
- //
- // Parameters:
- // source: pointer to first element in array.
- // source_stride: stride between elements in source where an element
- // equals the number of components this field uses. This is in source
- // units not in bytes.
- // destination_start_index: element in the destination to start.
- // num_elements: The number of elements to copy.
- virtual void SetFromFloats(const float* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements) = 0;
-
- // This function is the same as SetFromFloats except takes UInt32s as input.
- virtual void SetFromUInt32s(const uint32* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements) = 0;
-
- // This function is the same as SetFromFloats except takes UByteNs as input.
- virtual void SetFromUByteNs(const uint8* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements) = 0;
-
- // Sets all the elements for this field given the memory stream
- virtual bool SetFromMemoryStream(MemoryReadStream* stream) = 0;
-
- // Gets this field as floats.
- //
- // This function copies elements from the the field to the destination array.
- // It assumes that there are a multiple of N components in the destination
- // where N is the number of components in the field. In other words, if the
- // field has 3 components then passing a num_elements of 2 would copy 2
- // elements, each 3 components.
- //
- // Parameters:
- // source_start_index: element in the source to start.
- // destination: pointer to first element in destination array.
- // destination_stride: stride between elements in the destination in
- // destination units.
- // num_elements: The number of elements to copy.
- virtual void GetAsFloats(unsigned source_start_index,
- float* destination,
- unsigned destination_stride,
- unsigned num_elements) const = 0;
-
- // Checks if the start_index and num_elements would reference something
- // outside the buffer associated with this field.
- bool RangeValid(unsigned int start_index, unsigned int num_elements);
-
- // Copies a field. The field must be of the same type.
- // Paremeters:
- // source: field to copy from.
- void Copy(const Field& source);
-
- protected:
- // The concrete version of Copy. Copy calls this function to do the actual
- // copying after it has verified the types are compatible and the buffers
- // exist. ConcreteCopy does NOT have to check for those errors.
- // Paremeters:
- // source: field to copy from.
- virtual void ConcreteCopy(const Field& source) = 0;
-
- private:
- friend class Buffer;
- void set_offset(unsigned offset) {
- offset_ = offset;
- }
-
- void ClearBuffer() {
- buffer_ = NULL;
- }
-
- Buffer* buffer_;
- unsigned num_components_;
- unsigned offset_;
-
- O3D_DECL_CLASS(Field, NamedObject);
- DISALLOW_COPY_AND_ASSIGN(Field);
-};
-
-typedef std::vector<Field*> FieldArray;
-typedef std::vector<Field::Ref> FieldRefArray;
-
-// A field the hold floats.
-class FloatField : public Field {
- public:
- // When requesting a field of this type the number of componets must be a
- // multiple of this.
- static const unsigned kRequiredComponentMultiple = 1;
-
- // Overridden from Field.
- virtual size_t GetFieldComponentSize() const;
-
- static Field::Ref Create(ServiceLocator* service_locator,
- Buffer* buffer,
- unsigned num_components,
- unsigned offset);
-
- // Overridden from Field.
- virtual void SetFromFloats(const float* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements);
-
- // Overridden from Field.
- virtual void SetFromUInt32s(const uint32* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements);
-
- // Overridden from Field.
- virtual void SetFromUByteNs(const uint8* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements);
-
- // Overridden from Field.
- virtual bool SetFromMemoryStream(MemoryReadStream* stream);
-
- // Overridden from Field.
- virtual void GetAsFloats(unsigned source_start_index,
- float* destination,
- unsigned destination_stride,
- unsigned num_elements) const;
-
- protected:
- // Overridden from Field.
- virtual void ConcreteCopy(const Field& source);
-
- private:
- FloatField(ServiceLocator* service_locator,
- Buffer* buffer,
- unsigned num_components,
- unsigned offset);
-
- O3D_DECL_CLASS(FloatField, Field);
- DISALLOW_COPY_AND_ASSIGN(FloatField);
-};
-
-// A field the hold uint32s.
-class UInt32Field : public Field {
- public:
- // When requesting a field of this type the number of componets must be a
- // multiple of this.
- static const unsigned kRequiredComponentMultiple = 1;
-
- // Overridden from Field.
- virtual size_t GetFieldComponentSize() const;
-
- static Field::Ref Create(ServiceLocator* service_locator,
- Buffer* buffer,
- unsigned num_components,
- unsigned offset);
-
- // Overridden from Field.
- virtual void SetFromFloats(const float* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements);
-
- // Overridden from Field.
- virtual void SetFromUInt32s(const uint32* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements);
-
- // Overridden from Field.
- virtual void SetFromUByteNs(const uint8* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements);
-
- // Overridden from Field.
- virtual bool SetFromMemoryStream(MemoryReadStream* stream);
-
- // Overridden from Field.
- virtual void GetAsFloats(unsigned source_start_index,
- float* destination,
- unsigned destination_stride,
- unsigned num_elements) const;
-
- // Gets this field as uint32s.
- //
- // This function copies elements from the the field to the destination array.
- // It assumes that there are a multiple of N components in the destination
- // where N is the number of components in the field. In other words, if the
- // field has 3 components then passing a num_elements of 2 would copy 2
- // elements, each 3 components.
- //
- // Parameters:
- // source_start_index: element in the source to start.
- // destination: pointer to first element in destination array.
- // destination_stride: stride between elements in the destination in
- // destination units.
- // num_elements: The number of elements to copy.
- void GetAsUInt32s(unsigned source_start_index,
- uint32* destination,
- unsigned destination_stride,
- unsigned num_elements) const;
-
- protected:
- // Overridden from Field.
- virtual void ConcreteCopy(const Field& source);
-
- private:
- UInt32Field(ServiceLocator* service_locator,
- Buffer* buffer,
- unsigned num_components,
- unsigned offset);
-
- O3D_DECL_CLASS(UInt32Field, Field);
- DISALLOW_COPY_AND_ASSIGN(UInt32Field);
-};
-
-// A field the hold UByteNs where a UByteN is an uint8 that represents a value
-// from 0.0 to 1.0.
-class UByteNField : public Field {
- public:
- // When requesting a field of this type the number of componets must be a
- // multiple of this.
- static const unsigned kRequiredComponentMultiple = 4;
-
- // Overridden from Field.
- virtual size_t GetFieldComponentSize() const;
-
- static Field::Ref Create(ServiceLocator* service_locator,
- Buffer* buffer,
- unsigned num_components,
- unsigned offset);
-
- // Overridden from Field.
- virtual void SetFromFloats(const float* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements);
-
- // Overridden from Field.
- virtual void SetFromUInt32s(const uint32* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements);
-
- // Overridden from Field.
- virtual void SetFromUByteNs(const uint8* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements);
-
- // Overridden from Field.
- virtual bool SetFromMemoryStream(MemoryReadStream* stream);
-
- // Overridden from Field.
- virtual void GetAsFloats(unsigned source_start_index,
- float* destination,
- unsigned destination_stride,
- unsigned num_elements) const;
-
- // Gets this field as ubyten data.
- //
- // This function copies elements from the the field to the destination array.
- // It assumes that there are a multiple of N components in the destination
- // where N is the number of components in the field. In other words, if the
- // field has 3 components then passing a num_elements of 2 would copy 2
- // elements, each 3 components.
- //
- // Parameters:
- // source_start_index: element in the source to start.
- // destination: pointer to first element in destination array.
- // destination_stride: stride between elements in the destination in
- // destination units.
- // num_elements: The number of elements to copy.
- void GetAsUByteNs(unsigned source_start_index,
- uint8* destination,
- unsigned destination_stride,
- unsigned num_elements) const;
-
- protected:
- // Overridden from Field.
- virtual void ConcreteCopy(const Field& source);
-
- private:
- UByteNField(ServiceLocator* service_locator,
- Buffer* buffer,
- unsigned num_components,
- unsigned offset);
-
- const int* swizzle_table_;
-
- O3D_DECL_CLASS(UByteNField, Field);
- DISALLOW_COPY_AND_ASSIGN(UByteNField);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_FIELD_H_
diff --git a/o3d/core/cross/field_test.cc b/o3d/core/cross/field_test.cc
deleted file mode 100644
index 6b37426..0000000
--- a/o3d/core/cross/field_test.cc
+++ /dev/null
@@ -1,520 +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 Field, FloatField, UInt32Field, UByteNField.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/error_status.h"
-#include "core/cross/field.h"
-#include "core/cross/buffer.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-
-namespace o3d {
-
-namespace {
-
-static const float kInFloats[][4] = {
- { 1.0f, 2.0f, 3.0f, 3.5f, },
- { 4.0f, 5.0f, 6.0f, 7.0f, },
- { 10.0f, 11.0f, 12.0f, 13.0f, },
- { 0.3f, 0.4f, 0.5f, -1.3f, },
-};
-const unsigned kFloatsNumComponents = arraysize(kInFloats[0]);
-const unsigned kFloatsNumElements = arraysize(kInFloats);
-const unsigned kFloatsStride = kFloatsNumComponents;
-
-static const uint32 kInUInt32s[][4] = {
- { 1234, 67, 160000, 667, },
- { 0, 342353, 13443, 13, },
-};
-
-const unsigned kUInt32sNumComponents = arraysize(kInUInt32s[0]);
-const unsigned kUInt32sNumElements = arraysize(kInUInt32s);
-const unsigned kUInt32sStride = kUInt32sNumComponents;
-
-static const uint8 kInUByteNs[][4] = {
- { 64, 255, 128, 254, },
- { 192, 0, 32, 1, },
-};
-
-const unsigned kUByteNsNumComponents = arraysize(kInUByteNs[0]);
-const unsigned kUByteNsNumElements = arraysize(kInUByteNs);
-const unsigned kUByteNsStride = kUByteNsNumComponents;
-
-// Checks if an error has occured on the client then clears the error.
-bool CheckErrorExists(IErrorStatus* error_status) {
- bool have_error = !error_status->GetLastError().empty();
- error_status->ClearLastError();
- return have_error;
-}
-
-// Compares 2 sets of floats. Returns true if they are the same.
-bool CompareElements(const float* floats_1,
- const float* floats_2,
- unsigned num_elements,
- unsigned num_components) {
- for (; num_elements; --num_elements) {
- for (unsigned ii = 0; ii < num_components; ++ii) {
- if (*floats_1 != *floats_2) {
- return false;
- }
- ++floats_1;
- ++floats_2;
- }
- }
- return true;
-}
-
-bool CompareUInt32sAsFloat(const uint32* uint32s,
- const float* floats,
- unsigned num_elements,
- unsigned num_components) {
- for (; num_elements; --num_elements) {
- for (unsigned ii = 0; ii < num_components; ++ii) {
- float check = static_cast<float>(*uint32s);
- if (check != *floats) {
- return false;
- }
- ++uint32s;
- ++floats;
- }
- }
- return true;
-}
-
-bool CompareUByteNsAsFloat(const uint8* uint8s,
- const float* floats,
- unsigned num_elements,
- unsigned num_components) {
- for (; num_elements; --num_elements) {
- for (unsigned ii = 0; ii < num_components; ++ii) {
- float check = static_cast<float>(*uint8s) / 255.0f;
- // The following EXPECT_EQ is in there to get around a bug with gcc
- // on linux where, most likely due to overly aggressive optimization, the
- // check != *floats test fails even though the values are identical.
- EXPECT_EQ(check, check);
- if (check != *floats) {
- return false;
- }
- ++uint8s;
- ++floats;
- }
- }
- return true;
-}
-
-} // anonymous namespace
-
-class FieldTest : public testing::Test {
- protected:
- FieldTest()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- IErrorStatus* error_status() { return &error_status_; }
- Pack* pack() { return pack_; }
- Buffer* buffer() { return buffer_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- Pack* pack_;
- Buffer* buffer_;
-};
-
-void FieldTest::SetUp() {
- pack_ = object_manager_->CreatePack();
- buffer_ = pack()->Create<SourceBuffer>();
-}
-
-void FieldTest::TearDown() {
- object_manager_->DestroyPack(pack_);
-}
-
-// Test Field.
-TEST_F(FieldTest, TestBasic) {
- const unsigned kNumComponents = 3;
- const unsigned kNumElements = 4;
- Field::Ref field_1_ref = Field::Ref(
- buffer()->CreateField(FloatField::GetApparentClass(), kNumComponents));
- ASSERT_FALSE(field_1_ref.IsNull());
- Field* field_1 = field_1_ref.Get();
-
- // Check things are as expected.
- EXPECT_EQ(field_1->num_components(), kNumComponents);
- EXPECT_EQ(field_1->offset(), 0U);
- EXPECT_EQ(field_1->size(),
- field_1->num_components() * field_1->GetFieldComponentSize());
- EXPECT_EQ(field_1->buffer(), buffer());
-
- // Put some elements in the buffer.
- ASSERT_TRUE(buffer()->AllocateElements(kNumElements));
- EXPECT_EQ(buffer()->num_elements(), kNumElements);
-
- // Check various ranges
- EXPECT_TRUE(field_1->RangeValid(0, kNumElements));
- EXPECT_FALSE(field_1->RangeValid(0, kNumElements + 1));
- EXPECT_FALSE(field_1->RangeValid(kNumElements + 1, 0));
- EXPECT_FALSE(field_1->RangeValid(kNumElements - 1, -1));
-
- // Check if we create another field it's offset is correct.
- Field::Ref field_2_ref = Field::Ref(
- buffer()->CreateField(FloatField::GetApparentClass(), kNumComponents));
- ASSERT_FALSE(field_2_ref.IsNull());
- Field* field_2 = field_2_ref.Get();
- EXPECT_EQ(field_1->offset(), 0U);
- EXPECT_EQ(field_2->offset(), field_1->size());
- EXPECT_EQ(field_2->buffer(), buffer());
- EXPECT_EQ(buffer()->num_elements(), kNumElements);
-
- // Check if we remove the first field the second field gets updated correctly.
- buffer()->RemoveField(field_1);
- EXPECT_TRUE(field_1->buffer() == NULL);
- EXPECT_EQ(field_2->offset(), 0U);
-
- // Check we can't create a field of 0 components.
- EXPECT_TRUE(buffer()->CreateField(FloatField::GetApparentClass(), 0) ==
- NULL);
-}
-
-class FloatFieldTest : public testing::Test {
- protected:
- FloatFieldTest()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- IErrorStatus* error_status() { return &error_status_; }
- Pack* pack() { return pack_; }
- Buffer* buffer() { return buffer_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- Pack* pack_;
- Buffer* buffer_;
-};
-
-void FloatFieldTest::SetUp() {
- pack_ = object_manager_->CreatePack();
- buffer_ = pack()->Create<SourceBuffer>();
-}
-
-void FloatFieldTest::TearDown() {
- object_manager_->DestroyPack(pack_);
-}
-
-// Test FloatField.
-TEST_F(FloatFieldTest, TestBasic) {
- Field* field = buffer()->CreateField(FloatField::GetApparentClass(),
- kFloatsNumComponents);
- ASSERT_TRUE(field != NULL);
- ASSERT_TRUE(field->IsA(FloatField::GetApparentClass()));
- ASSERT_TRUE(field->IsA(Field::GetApparentClass()));
-
- EXPECT_EQ(field->GetFieldComponentSize(), sizeof(float)); // NOLINT
-
- ASSERT_TRUE(buffer()->AllocateElements(kFloatsNumElements));
- field->SetFromFloats(&kInFloats[0][0], kFloatsStride, 0, kFloatsNumElements);
-
- float out_floats[kFloatsNumElements][kFloatsNumComponents];
- memset(&out_floats, 0, sizeof(out_floats));
- field->GetAsFloats(0, &out_floats[0][0], kFloatsStride, kFloatsNumElements);
-
- EXPECT_TRUE(CompareElements(&kInFloats[0][0],
- &out_floats[0][0],
- kFloatsNumElements,
- kFloatsNumComponents));
-
- Field* new_field = buffer()->CreateField(FloatField::GetApparentClass(),
- kFloatsNumComponents);
- ASSERT_TRUE(new_field != NULL);
- new_field->Copy(*field);
- memset(&out_floats, 0, sizeof(out_floats));
- new_field->GetAsFloats(0, &out_floats[0][0], kFloatsStride,
- kFloatsNumElements);
-
- EXPECT_TRUE(CompareElements(&kInFloats[0][0],
- &out_floats[0][0],
- kFloatsNumElements,
- kFloatsNumComponents));
-
- field->SetFromUInt32s(&kInUInt32s[0][0], kUInt32sStride, 0,
- kUInt32sNumElements);
-
- memset(&out_floats, 0, sizeof(out_floats));
- field->GetAsFloats(0, &out_floats[0][0], kFloatsStride, kUInt32sNumElements);
-
- EXPECT_TRUE(CompareUInt32sAsFloat(&kInUInt32s[0][0],
- &out_floats[0][0],
- kUInt32sNumElements,
- kUInt32sNumComponents));
-
- field->SetFromUByteNs(&kInUByteNs[0][0], kUByteNsStride, 0,
- kUByteNsNumElements);
-
- memset(&out_floats, 0, sizeof(out_floats));
- field->GetAsFloats(0, &out_floats[0][0], kFloatsStride, kUByteNsNumElements);
-
- EXPECT_TRUE(CompareUByteNsAsFloat(&kInUByteNs[0][0],
- &out_floats[0][0],
- kUByteNsNumElements,
- kUByteNsNumComponents));
-}
-
-class UInt32FieldTest : public testing::Test {
- protected:
- UInt32FieldTest()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- IErrorStatus* error_status() { return &error_status_; }
- Pack* pack() { return pack_; }
- Buffer* buffer() { return buffer_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- Pack* pack_;
- Buffer* buffer_;
-};
-
-void UInt32FieldTest::SetUp() {
- pack_ = object_manager_->CreatePack();
- buffer_ = pack()->Create<SourceBuffer>();
-}
-
-void UInt32FieldTest::TearDown() {
- object_manager_->DestroyPack(pack_);
-}
-
-// Test UInt32Field.
-TEST_F(UInt32FieldTest, TestBasic) {
- Field* field = buffer()->CreateField(UInt32Field::GetApparentClass(),
- kFloatsNumComponents);
- ASSERT_TRUE(field != NULL);
- ASSERT_TRUE(field->IsA(UInt32Field::GetApparentClass()));
- ASSERT_TRUE(field->IsA(Field::GetApparentClass()));
-
- EXPECT_EQ(field->GetFieldComponentSize(), sizeof(float)); // NOLINT
-
- ASSERT_TRUE(buffer()->AllocateElements(kFloatsNumElements));
- field->SetFromFloats(&kInFloats[0][0], kFloatsStride, 0, kFloatsNumElements);
-
- float out_floats[kFloatsNumElements][kFloatsNumComponents];
-
- memset(&out_floats, 0, sizeof(out_floats));
- field->GetAsFloats(0, &out_floats[0][0], kFloatsStride, kFloatsNumElements);
-
- for (unsigned jj = 0; jj < kFloatsNumElements; ++jj) {
- for (unsigned ii = 0; ii < kFloatsNumComponents; ++ii) {
- uint32 in_value = static_cast<uint32>(std::max(0.f, kInFloats[jj][ii]));
- uint32 out_value = static_cast<uint32>(std::max(0.f, out_floats[jj][ii]));
- EXPECT_EQ(in_value, out_value);
- }
- }
-
- field->SetFromUInt32s(&kInUInt32s[0][0], kUInt32sStride, 0,
- kUInt32sNumElements);
-
- uint32 out_uint32s[kUInt32sNumElements][kUInt32sNumComponents];
- memset(&out_uint32s, 0, sizeof(out_uint32s));
- UInt32Field* uint32_field = down_cast<UInt32Field*>(field);
- uint32_field->GetAsUInt32s(0, &out_uint32s[0][0], kUInt32sStride,
- kUInt32sNumElements);
-
- for (unsigned jj = 0; jj < kUInt32sNumElements; ++jj) {
- for (unsigned ii = 0; ii < kUInt32sNumComponents; ++ii) {
- EXPECT_EQ(kInUInt32s[jj][ii], out_uint32s[jj][ii]);
- }
- }
-
- Field* new_field = buffer()->CreateField(UInt32Field::GetApparentClass(),
- kUInt32sNumComponents);
- ASSERT_TRUE(new_field != NULL);
- new_field->Copy(*field);
- memset(&out_uint32s, 0, sizeof(out_uint32s));
- down_cast<UInt32Field*>(new_field)->GetAsUInt32s(
- 0, &out_uint32s[0][0], kUInt32sStride, kUInt32sNumElements);
-
- for (unsigned jj = 0; jj < kUInt32sNumElements; ++jj) {
- for (unsigned ii = 0; ii < kUInt32sNumComponents; ++ii) {
- EXPECT_EQ(kInUInt32s[jj][ii], out_uint32s[jj][ii]);
- }
- }
-
- memset(&out_floats, 0, sizeof(out_floats));
- field->GetAsFloats(0, &out_floats[0][0], kFloatsStride, kUInt32sNumElements);
-
- EXPECT_TRUE(CompareUInt32sAsFloat(&kInUInt32s[0][0],
- &out_floats[0][0],
- kUInt32sNumElements,
- kUInt32sNumComponents));
-
- field->SetFromUByteNs(&kInUByteNs[0][0], kUByteNsStride, 0,
- kUByteNsNumElements);
-
- memset(&out_floats, 0, sizeof(out_floats));
- field->GetAsFloats(0, &out_floats[0][0], kFloatsStride, kUByteNsNumElements);
-
- for (unsigned jj = 0; jj < kUByteNsNumElements; ++jj) {
- for (unsigned ii = 0; ii < kUByteNsNumComponents; ++ii) {
- EXPECT_EQ((kInUByteNs[jj][ii] > 0 ? 1.0f : 0.0f), out_floats[jj][ii]);
- }
- }
-}
-
-class UByteNFieldTest : public testing::Test {
- protected:
- UByteNFieldTest()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- IErrorStatus* error_status() { return &error_status_; }
- Pack* pack() { return pack_; }
- Buffer* buffer() { return buffer_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- Pack* pack_;
- Buffer* buffer_;
-};
-
-void UByteNFieldTest::SetUp() {
- pack_ = object_manager_->CreatePack();
- buffer_ = pack()->Create<SourceBuffer>();
-}
-
-void UByteNFieldTest::TearDown() {
- object_manager_->DestroyPack(pack_);
-}
-
-// Test UByteNField.
-TEST_F(UByteNFieldTest, TestBasic) {
- Field* field = buffer()->CreateField(UByteNField::GetApparentClass(),
- kFloatsNumComponents);
- ASSERT_TRUE(field != NULL);
- ASSERT_TRUE(field->IsA(UByteNField::GetApparentClass()));
- ASSERT_TRUE(field->IsA(Field::GetApparentClass()));
-
- EXPECT_EQ(field->GetFieldComponentSize(), sizeof(uint8)); // NOLINT
-
- ASSERT_TRUE(buffer()->AllocateElements(kFloatsNumElements));
- field->SetFromFloats(&kInFloats[0][0], kFloatsStride, 0, kFloatsNumElements);
-
- float out_floats[kFloatsNumElements][kFloatsNumComponents];
-
- memset(&out_floats, 0, sizeof(out_floats));
- field->GetAsFloats(0, &out_floats[0][0], kFloatsStride, kFloatsNumElements);
-
- static const float kEpsilon = 0.002f;
-
- for (unsigned jj = 0; jj < kFloatsNumElements; ++jj) {
- for (unsigned ii = 0; ii < kFloatsNumComponents; ++ii) {
- float expect = std::max(std::min(1.0f, kInFloats[jj][ii]), 0.0f);
- float difference = fabsf(expect - out_floats[jj][ii]);
- EXPECT_TRUE(difference < kEpsilon);
- }
- }
-
- field->SetFromUInt32s(&kInUInt32s[0][0], kUInt32sStride, 0,
- kUInt32sNumElements);
-
- memset(&out_floats, 0, sizeof(out_floats));
- field->GetAsFloats(0, &out_floats[0][0], kFloatsStride, kUInt32sNumElements);
-
- for (unsigned jj = 0; jj < kUInt32sNumElements; ++jj) {
- for (unsigned ii = 0; ii < kUByteNsNumComponents; ++ii) {
- float check =
- static_cast<float>(std::min<uint32>(255, kInUInt32s[jj][ii])) /
- 255.0f;
- EXPECT_EQ(check, out_floats[jj][ii]);
- }
- }
-
- field->SetFromUByteNs(&kInUByteNs[0][0], kUByteNsStride, 0,
- kUByteNsNumElements);
- uint8 out_ubytens[kUByteNsNumElements][kUByteNsNumComponents];
- memset(&out_ubytens, 0, sizeof(out_ubytens));
- down_cast<UByteNField*>(field)->GetAsUByteNs(
- 0, &out_ubytens[0][0], kUByteNsStride, kUByteNsNumElements);
-
- for (unsigned jj = 0; jj < kUByteNsNumElements; ++jj) {
- for (unsigned ii = 0; ii < kUByteNsNumComponents; ++ii) {
- EXPECT_EQ(kInUByteNs[jj][ii], out_ubytens[jj][ii]);
- }
- }
-
- Field* new_field = buffer()->CreateField(UByteNField::GetApparentClass(),
- kUByteNsNumComponents);
- ASSERT_TRUE(new_field != NULL);
- new_field->Copy(*field);
-
- memset(&out_ubytens, 0, sizeof(out_ubytens));
- down_cast<UByteNField*>(new_field)->GetAsUByteNs(
- 0, &out_ubytens[0][0], kUByteNsStride, kUByteNsNumElements);
-
- for (unsigned jj = 0; jj < kUByteNsNumElements; ++jj) {
- for (unsigned ii = 0; ii < kUByteNsNumComponents; ++ii) {
- EXPECT_EQ(kInUByteNs[jj][ii], out_ubytens[jj][ii]);
- }
- }
-
-
- // Test that we can't make a UByteN field that is not multiple of 4
- EXPECT_TRUE(buffer()->CreateField(UByteNField::GetApparentClass(), 1) ==
- NULL);
- EXPECT_TRUE(buffer()->CreateField(UByteNField::GetApparentClass(), 2) ==
- NULL);
- EXPECT_TRUE(buffer()->CreateField(UByteNField::GetApparentClass(), 3) ==
- NULL);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/file_request.cc b/o3d/core/cross/file_request.cc
deleted file mode 100644
index b3c4247..0000000
--- a/o3d/core/cross/file_request.cc
+++ /dev/null
@@ -1,64 +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 definition of the FileRequest class.
-
-#include "core/cross/file_request.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(FileRequest, ObjectBase);
-
-FileRequest::FileRequest(ServiceLocator* service_locator,
- Pack *pack,
- Type type)
- : ObjectBase(service_locator),
- pack_(pack),
- type_(type),
- generate_mipmaps_(true),
- done_(false),
- success_(false),
- ready_state_(0) {
-}
-
-FileRequest *FileRequest::Create(ServiceLocator* service_locator,
- Pack *pack,
- Type type) {
- FileRequest *request = NULL;
-
- if (IsValidType(type)) {
- request = new FileRequest(service_locator, pack, type);
- }
-
- return request;
-}
-} // namespace o3d
diff --git a/o3d/core/cross/file_request.h b/o3d/core/cross/file_request.h
deleted file mode 100644
index 11e695d9..0000000
--- a/o3d/core/cross/file_request.h
+++ /dev/null
@@ -1,180 +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 declaration of the FileRequest class.
-
-#ifndef O3D_CORE_CROSS_FILE_REQUEST_H_
-#define O3D_CORE_CROSS_FILE_REQUEST_H_
-
-#include <algorithm>
-#include <string>
-
-#include "base/scoped_ptr.h"
-#include "core/cross/callback.h"
-#include "core/cross/object_base.h"
-#include "core/cross/pack.h"
-#include "import/cross/raw_data.h"
-
-namespace o3d {
-
-typedef Closure FileRequestCallback;
-
-// A FileRequest object is used to carry out an asynchronous request for a file
-// to be loaded.
-class FileRequest : public ObjectBase {
- public:
- enum Type {
- TYPE_INVALID,
- TYPE_TEXTURE,
- TYPE_RAWDATA,
- TYPE_MAX = TYPE_RAWDATA,
- };
-
- enum ReadyState { // These are copied from XMLHttpRequest.
- STATE_INIT = 0,
- STATE_OPEN = 1,
- STATE_SENT = 2,
- STATE_RECEIVING = 3,
- STATE_LOADED = 4,
- };
-
- public:
- typedef SmartPointer<FileRequest> Ref;
-
- virtual ~FileRequest() { }
-
- static FileRequest *Create(ServiceLocator* service_locator,
- Pack *pack,
- Type type);
-
- static Type TypeFromString(String type) {
- std::transform(type.begin(),
- type.end(),
- type.begin(),
- ::tolower);
- if (type == "texture") {
- return TYPE_TEXTURE;
- }
- if (type == "rawdata") {
- return TYPE_RAWDATA;
- }
- return TYPE_INVALID;
- }
-
- static bool IsValidType(Type type) {
- return type > TYPE_INVALID && type <= TYPE_MAX;
- }
- Pack *pack() const {
- return pack_.Get(); // Set at creation time and never changed.
- }
- FileRequestCallback *onreadystatechange() const {
- return onreadystatechange_.get();
- }
- void set_onreadystatechange(FileRequestCallback *onreadystatechange) {
- onreadystatechange_.reset(onreadystatechange);
- }
- const String& uri() const {
- return uri_;
- }
- void set_uri(const String& uri) {
- uri_ = uri;
- }
- Type type() const {
- return type_; // Set at creation time and never changed.
- }
- Texture *texture() const {
- return texture_.Get();
- }
- RawData *data() const {
- return data_.Get();
- }
- bool generate_mipmaps() const { return generate_mipmaps_; }
- void set_generate_mipmaps(bool value) {
- generate_mipmaps_ = value;
- }
- void set_texture(Texture *texture) {
- CHECK(type_ == TYPE_TEXTURE);
- texture_ = Texture::Ref(texture);
- }
- void set_data(RawData *data) {
- CHECK(type_ == TYPE_RAWDATA);
- data_ = RawData::Ref(data);
- }
- bool done() const {
- return done_;
- }
- bool success() const {
- return success_;
- }
- void set_success(bool success) {
- success_ = success;
- done_ = true;
- pack_.Reset(); // Removes pack reference, allowing pack garbage collection.
- }
- int ready_state() const {
- return ready_state_;
- }
- void set_ready_state(int state) {
- ready_state_ = state;
- }
- const String& error() const {
- return error_;
- }
- void set_error(const String& error) {
- error_ = error;
- }
-
- O3D_DECL_CLASS(FileRequest, ObjectBase);
-
- private:
- FileRequest(ServiceLocator* service_locator,
- Pack *pack,
- Type type);
-
- Pack::Ref pack_;
- scoped_ptr<FileRequestCallback> onreadystatechange_;
- String uri_;
- Type type_;
- Texture::Ref texture_; // Only used on a successful texture load.
- RawData::Ref data_; // Only used on a successful RawData load.
- bool generate_mipmaps_;
- bool done_; // Set after completion/failure to indicate success_ is valid.
- bool success_; // Set after completion/failure to indicate which it is.
- int ready_state_; // Like the XMLHttpRequest variable of the same name.
- String error_;
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(FileRequest);
-}; // FileRequest
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_FILE_REQUEST_H_
diff --git a/o3d/core/cross/float_n.h b/o3d/core/cross/float_n.h
deleted file mode 100644
index 90fb06c..0000000
--- a/o3d/core/cross/float_n.h
+++ /dev/null
@@ -1,212 +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 definition and (inline) implementation of Float2,
-// Float3 and Float4.
-// Note: Although these classes look like a good candidate for templating,
-// we cannot template them as they each require a constructor taking a different
-// number of arguments.
-
-#ifndef O3D_CORE_CROSS_FLOAT_N_H_
-#define O3D_CORE_CROSS_FLOAT_N_H_
-
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// Class for storing and accessing two consecutive floats.
-class Float2 {
- public:
- // Default constructor does not initialize the data in any way.
- Float2() {}
-
- // Creates a Float2 out of two floats
- Float2(float v0, float v1) {
- data_[0] = v0;
- data_[1] = v1;
- }
-
- Float2(const Float2& v) { CopyFrom(v); }
-
- float operator[](int index) const { return data_[index]; }
- float& operator[](int index) { return data_[index]; }
-
- // Returns a pointer to the start of the internal data storage.
- const float* GetFloatArray() const { return &data_[0]; }
-
- Float2& operator= (const Float2& v) {
- CopyFrom(v);
- return *this;
- }
-
- float getX() const { return data_[0]; }
- void setX(float v) { data_[0] = v; }
- float getY() const { return data_[1]; }
- void setY(float v) { data_[1] = v; }
-
- private:
- // Copies the values from another Float2.
- void CopyFrom(const Float2& v) {
- data_[0] = v[0];
- data_[1] = v[1];
- }
- // Data storage.
- float data_[2];
-};
-
-// Class for storing and accessing three consecutive floats.
-class Float3 {
- public:
- // Default constructor does not initialize the data in any way
- Float3() {}
-
- // Creates a Float3 out of three floats
- Float3(float v0, float v1, float v2) {
- data_[0] = v0;
- data_[1] = v1;
- data_[2] = v2;
- }
-
- Float3(const Float3& v) { CopyFrom(v); }
- explicit Float3(const Vector3& v) {
- data_[0] = v.getX();
- data_[1] = v.getY();
- data_[2] = v.getZ();
- }
- explicit Float3(const Point3& v) {
- data_[0] = v.getX();
- data_[1] = v.getY();
- data_[2] = v.getZ();
- }
-
- float operator[](int index) const { return data_[index]; }
- float& operator[](int index) { return data_[index]; }
-
- // Returns a pointer to the start of the internal data storage.
- const float* GetFloatArray() const { return &data_[0]; }
-
- Float3& operator= (const Float3& v) {
- CopyFrom(v);
- return *this;
- }
-
- float getX() const { return data_[0]; }
- void setX(float v) { data_[0] = v; }
- float getY() const { return data_[1]; }
- void setY(float v) { data_[1] = v; }
- float getZ() const { return data_[2]; }
- void setZ(float v) { data_[2] = v; }
-
- private:
- // Copies the values from another Float2.
- void CopyFrom(const Float3& v) {
- data_[0] = v[0];
- data_[1] = v[1];
- data_[2] = v[2];
- }
-
- // Data storage.
- float data_[3];
-};
-
-inline Vector3 Float3ToVector3(const Float3& v) {
- return Vector3(v.getX(), v.getY(), v.getZ());
-}
-
-inline Point3 Float3ToPoint3(const Float3& v) {
- return Point3(v.getX(), v.getY(), v.getZ());
-}
-
-// Class for storing and accessing four consecutive floats.
-class Float4 {
- public:
- // Default constructor does not initialize the data in any way
- Float4() {}
-
- // Creates a Float4 out of four floats
- Float4(float v0, float v1, float v2, float v3) {
- data_[0] = v0;
- data_[1] = v1;
- data_[2] = v2;
- data_[3] = v3;
- }
-
- Float4(const Float4& v) { CopyFrom(v); }
- explicit Float4(const Vector4& v) {
- data_[0] = v.getX();
- data_[1] = v.getY();
- data_[2] = v.getZ();
- data_[3] = v.getW();
- }
- explicit Float4(const Quaternion& v) {
- data_[0] = v.getX();
- data_[1] = v.getY();
- data_[2] = v.getZ();
- data_[3] = v.getW();
- }
-
- float operator[](int index) const { return data_[index]; }
- float& operator[](int index) { return data_[index]; }
-
- // Returns a pointer to the start of the internal data storage.
- const float* GetFloatArray() const { return &data_[0]; }
-
- Float4& operator= (const Float4& v) {
- CopyFrom(v);
- return *this;
- }
-
- float getX() const { return data_[0]; }
- void setX(float v) { data_[0] = v; }
- float getY() const { return data_[1]; }
- void setY(float v) { data_[1] = v; }
- float getZ() const { return data_[2]; }
- void setZ(float v) { data_[2] = v; }
- float getW() const { return data_[3]; }
- void setW(float v) { data_[3] = v; }
-
- private:
- // Copies the values from another Float2.
- void CopyFrom(const Float4& v) {
- data_[0] = v[0];
- data_[1] = v[1];
- data_[2] = v[2];
- data_[3] = v[3];
- }
-
- // Data storage.
- float data_[4];
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_FLOAT_N_H_
diff --git a/o3d/core/cross/float_n_test.cc b/o3d/core/cross/float_n_test.cc
deleted file mode 100644
index 338ae46..0000000
--- a/o3d/core/cross/float_n_test.cc
+++ /dev/null
@@ -1,47 +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 "tests/common/win/testing_common.h"
-#include "core/cross/float_n.h"
-
-namespace o3d {
-
-TEST(FloatNTest, Float3ToVector3) {
- Vector3 v = Float3ToVector3(Float3(1, 2, 3));
- ASSERT_NEAR(0.0f, length(v - Vector3(1, 2, 3)), 0.001f);
-}
-
-TEST(FloatNTest, Float3ToPoint3) {
- Point3 v = Float3ToPoint3(Float3(1, 2, 3));
- ASSERT_NEAR(0.0f, length(v - Point3(1, 2, 3)), 0.001f);
-}
-} // namespace o3d
diff --git a/o3d/core/cross/function.cc b/o3d/core/cross/function.cc
deleted file mode 100644
index 3c08434..0000000
--- a/o3d/core/cross/function.cc
+++ /dev/null
@@ -1,100 +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 Function.
-
-#include "core/cross/function.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(FunctionContext, ObjectBase);
-O3D_DEFN_CLASS(Function, NamedObject);
-O3D_DEFN_CLASS(ParamFunction, RefParamBase);
-O3D_DEFN_CLASS(FunctionEval, ParamObject);
-
-FunctionContext::FunctionContext(ServiceLocator* service_locator)
- : ObjectBase(service_locator) {
-}
-
-Function::Function(ServiceLocator* service_locator)
- : NamedObject(service_locator),
- weak_pointer_manager_(this) {
-}
-
-const char* FunctionEval::kInputParamName =
- O3D_STRING_CONSTANT("input");
-const char* FunctionEval::kFunctionObjectParamName =
- O3D_STRING_CONSTANT("functionObject");
-const char* FunctionEval::kOutputParamName =
- O3D_STRING_CONSTANT("output");
-
-FunctionEval::FunctionEval(ServiceLocator* service_locator)
- : ParamObject(service_locator),
- function_context_(NULL) {
- RegisterParamRef(kInputParamName, &input_param_);
- RegisterParamRef(kFunctionObjectParamName, &function_object_param_);
- SlaveParamFloat::RegisterParamRef(kOutputParamName,
- &output_param_,
- this);
-}
-
-void FunctionEval::UpdateOutputs() {
- if (output_param_->input_connection() == NULL) {
- Function* function = function_object_param_->value();
- if (function) {
- // If we don't have a function context or if the one we have is the wrong
- // type then get a new one.
- if (!function_context_ ||
- !function_context_->IsA(function->GetFunctionContextClass())) {
- function_context_.Reset();
- function_context_ = FunctionContext::Ref(
- function->CreateFunctionContext());
- }
- output_param_->set_dynamic_value(
- function->Evaluate(input_param_->value(), function_context_.Get()));
- } else {
- output_param_->set_dynamic_value(input_param_->value());
- }
- }
-}
-
-ObjectBase::Ref FunctionEval::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new FunctionEval(service_locator));
-}
-
-ObjectBase::Ref ParamFunction::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamFunction(service_locator, false, false));
-}
-
-} // namespace o3d
-
-
diff --git a/o3d/core/cross/function.h b/o3d/core/cross/function.h
deleted file mode 100644
index 13d8705..0000000
--- a/o3d/core/cross/function.h
+++ /dev/null
@@ -1,172 +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 Function declaration.
-
-#ifndef O3D_CORE_CROSS_FUNCTION_H_
-#define O3D_CORE_CROSS_FUNCTION_H_
-
-#include "core/cross/param_object.h"
-
-namespace o3d {
-
-// An FunctionContext is passed to a Function to allow caching and other
-// performance enhancements. FunctionContext is abstract. To get an
-// FunctionContext that is compatible with a particular function call
-// Function::CreateFunctionContext
-class FunctionContext : public ObjectBase {
- public:
- typedef SmartPointer<FunctionContext> Ref;
-
- protected:
- explicit FunctionContext(ServiceLocator* service_locator);
-
- private:
- O3D_DECL_CLASS(FunctionContext, ObjectBase);
- DISALLOW_COPY_AND_ASSIGN(FunctionContext);
-};
-
-// A Function is a class that has an Evaluate method. Evaluate takes 1 input and
-// returns 1 output.
-class Function : public NamedObject {
- public:
- typedef SmartPointer<Function> Ref;
- typedef WeakPointer<Function> WeakPointerType;
-
- // Gets a output for this function for the given input.
- // Parameters:
- // input: input to function.
- // context: FunctionContext compatible with function. May be null.
- // Returns:
- // The output for the given input.
- virtual float Evaluate(float input, FunctionContext* context) const = 0;
-
- // Creates an evaluation context that can be used for this Function.
- // Returns:
- // An evaluation context compatible with this Function.
- virtual FunctionContext* CreateFunctionContext() const = 0;
-
- // Gets the class of the FunctionObject this Function needs.
- // Returns:
- // the class of the FunctionObject this Function needs.
- virtual const ObjectBase::Class* GetFunctionContextClass() const = 0;
-
- // Gets a weak pointer to us.
- WeakPointerType GetWeakPointer() const {
- return weak_pointer_manager_.GetWeakPointer();
- }
-
- protected:
- explicit Function(ServiceLocator* service_locator);
-
- private:
- // Manager for weak pointers to us.
- WeakPointerType::WeakPointerManager weak_pointer_manager_;
-
- O3D_DECL_CLASS(Function, NamedObject);
- DISALLOW_COPY_AND_ASSIGN(Function);
-};
-
-// A param that holds a weak pointer to a Function.
-class ParamFunction : public TypedRefParam<Function> {
- public:
- typedef SmartPointer<ParamFunction> Ref;
-
- ParamFunction(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedRefParam<Function>(service_locator, dynamic, read_only) {
- }
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamFunction, RefParamBase);
- DISALLOW_COPY_AND_ASSIGN(ParamFunction);
-};
-
-// A class that evaluates a Function through parameters.
-class FunctionEval : public ParamObject {
- public:
- typedef SmartPointer<FunctionEval> Ref;
-
- // Names of Params.
- static const char* kInputParamName;
- static const char* kFunctionObjectParamName;
- static const char* kOutputParamName;
-
- float input() const {
- return input_param_->value();
- }
-
- void set_input(float value) {
- input_param_->set_value(value);
- }
-
- Function* function_object() const {
- return function_object_param_->value();
- }
-
- void set_function_object(Function* function) {
- function_object_param_->set_value(function);
- }
-
- float output() const {
- return output_param_->value();
- }
-
- // Updates the output param.
- void UpdateOutputs();
-
- private:
- typedef SlaveParam<ParamFloat, FunctionEval> SlaveParamFloat;
-
- explicit FunctionEval(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamFloat::Ref input_param_;
- ParamFunction::Ref function_object_param_;
- SlaveParamFloat::Ref output_param_;
- FunctionContext::Ref function_context_;
-
- O3D_DECL_CLASS(FunctionEval, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(FunctionEval);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_FUNCTION_H_
-
-
-
-
diff --git a/o3d/core/cross/function_test.cc b/o3d/core/cross/function_test.cc
deleted file mode 100644
index 5407324..0000000
--- a/o3d/core/cross/function_test.cc
+++ /dev/null
@@ -1,197 +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 implements unit tests for class Function and FunctionEval.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/error_status.h"
-#include "core/cross/function.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-
-namespace o3d {
-
-class FunctionTest : public testing::Test {
- protected:
-
- FunctionTest()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
-
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- Pack* pack_;
-};
-
-void FunctionTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void FunctionTest::TearDown() {
- pack_->Destroy();
-}
-
-namespace {
-
-// Just multiplies the input by 2.0f
-class TestFunction : public Function {
- public:
- explicit TestFunction(ServiceLocator* service_locator)
- : Function(service_locator) {
- }
-
- // overridden from Function
- virtual float Evaluate(float input, FunctionContext* context) const {
- return input * 2.0f;
- }
-
- // overridden from Function
- virtual FunctionContext* CreateFunctionContext() const {
- return NULL;
- }
-
- // overridden from Function
- virtual const ObjectBase::Class* GetFunctionContextClass() const {
- return NULL;
- }
-
- private:
- O3D_DECL_CLASS(TestFunction, Function);
- DISALLOW_COPY_AND_ASSIGN(TestFunction);
-};
-
-O3D_DEFN_CLASS(TestFunction, Function);
-
-} // anonymous namespace.
-
-// Tests Function.
-TEST_F(FunctionTest, Basic) {
- Function::Ref function = Function::Ref(new TestFunction(g_service_locator));
- // Check that it got created.
- ASSERT_FALSE(function.IsNull());
- // Check that it derives from NamedObject
- EXPECT_TRUE(function->IsA(NamedObject::GetApparentClass()));
-}
-
-// Tests Evaluate.
-TEST_F(FunctionTest, Evaluate) {
- Function::Ref function = Function::Ref(new TestFunction(g_service_locator));
- // Check that it got created.
- ASSERT_FALSE(function.IsNull());
-
- EXPECT_EQ(function->Evaluate(2.0f, NULL), 2.0f * 2.0f);
- EXPECT_EQ(function->Evaluate(4.0f, NULL), 4.0f * 2.0f);
- EXPECT_EQ(function->Evaluate(-4.0f, NULL), -4.0f * 2.0f);
-}
-
-class FunctionEvalTest : public testing::Test {
- protected:
-
- FunctionEvalTest()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
-
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- Pack* pack_;
-};
-
-void FunctionEvalTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void FunctionEvalTest::TearDown() {
- pack_->Destroy();
-}
-
-// Tests FunctionEval.
-TEST_F(FunctionEvalTest, Basic) {
- FunctionEval* function_eval = pack()->Create<FunctionEval>();
- // Check that it got created.
- ASSERT_TRUE(function_eval != NULL);
- // Check that it derives from ParamObject
- EXPECT_TRUE(function_eval->IsA(ParamObject::GetApparentClass()));
-}
-
-// Tests UpdateOutputs (indirectly)
-TEST_F(FunctionEvalTest, Evaluate) {
- FunctionEval* function_eval = pack()->Create<FunctionEval>();
- // Check that it got created.
- ASSERT_TRUE(function_eval != NULL);
-
- // Check that the correct params got created.
- EXPECT_TRUE(function_eval->GetParam<ParamFloat>(
- FunctionEval::kInputParamName) != NULL);
- EXPECT_TRUE(function_eval->GetParam<ParamFunction>(
- FunctionEval::kFunctionObjectParamName) != NULL);
- EXPECT_TRUE(function_eval->GetParam<ParamFloat>(
- FunctionEval::kOutputParamName) != NULL);
-
- // Check that with no function the input just gets passed through.
- function_eval->set_input(2.0f);
- EXPECT_EQ(function_eval->input(), 2.0f);
- EXPECT_EQ(function_eval->output(), 2.0f);
- function_eval->set_input(4.0f);
- EXPECT_EQ(function_eval->input(), 4.0f);
- EXPECT_EQ(function_eval->output(), 4.0f);
-
- // Attach a function
- Function::Ref function = Function::Ref(new TestFunction(g_service_locator));
- // Check that it got created.
- ASSERT_FALSE(function.IsNull());
-
- function_eval->set_function_object(function);
- EXPECT_EQ(function_eval->function_object(), function);
-
- function_eval->set_input(2.0f);
- EXPECT_EQ(function_eval->output(), 4.0f);
- function_eval->set_input(4.0f);
- EXPECT_EQ(function_eval->output(), 8.0f);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/gl/buffer_gl.cc b/o3d/core/cross/gl/buffer_gl.cc
deleted file mode 100644
index 6d6b677..0000000
--- a/o3d/core/cross/gl/buffer_gl.cc
+++ /dev/null
@@ -1,253 +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 implementatinos of VertexBufferGL and
-// IndexBufferGL, used to implement O3D using OpenGL.
-//
-// To force the vertex and index buffers to be created by Cg Runtime
-// control, define the compile flag "USE_CG_BUFFERS". This option is off by
-// default and buffers are created, locked and managed using the OpenGL
-// "ARB_vertex_buffer_object" extension.
-
-#include "core/cross/error.h"
-#include "core/cross/gl/buffer_gl.h"
-#include "core/cross/gl/renderer_gl.h"
-#include "core/cross/gl/utils_gl.h"
-#include "core/cross/gl/utils_gl-inl.h"
-
-namespace o3d {
-
-namespace {
-
-GLenum BufferAccessModeToGLenum(Buffer::AccessMode access_mode) {
- switch (access_mode) {
- case Buffer::READ_ONLY:
- return GL_READ_ONLY_ARB;
- case Buffer::WRITE_ONLY:
- return GL_WRITE_ONLY_ARB;
- case Buffer::READ_WRITE:
- return GL_READ_WRITE_ARB;
- case Buffer::NONE:
- break;
- }
- DCHECK(false);
- return GL_READ_WRITE_ARB;
-}
-
-} // anonymous namespace
-
-// Vertex Buffers --------------------------------------------------------------
-
-// Initializes the O3D VertexBuffer object but does not allocate an
-// OpenGL vertex buffer object yet.
-VertexBufferGL::VertexBufferGL(ServiceLocator* service_locator)
- : VertexBuffer(service_locator),
- renderer_(static_cast<RendererGL*>(
- service_locator->GetService<Renderer>())),
- gl_buffer_(0) {
- DLOG(INFO) << "VertexBufferGL Construct";
-}
-
-// Destructor releases the OpenGL VBO.
-VertexBufferGL::~VertexBufferGL() {
- DLOG(INFO) << "VertexBufferGL Destruct \"" << name() << "\"";
- ConcreteFree();
-}
-
-// Creates a OpenGL vertex buffer of the requested size.
-bool VertexBufferGL::ConcreteAllocate(size_t size_in_bytes) {
- DLOG(INFO) << "VertexBufferGL Allocate \"" << name() << "\"";
- renderer_->MakeCurrentLazy();
- ConcreteFree();
- // Create a new VBO.
- glGenBuffersARB(1, &gl_buffer_);
-
- if (!gl_buffer_) return false;
-
- // Give the VBO a size, but no data, and set the hint to "STATIC_DRAW"
- // to mark the buffer as set up once then used often.
- glBindBufferARB(GL_ARRAY_BUFFER_ARB, gl_buffer_);
- glBufferDataARB(GL_ARRAY_BUFFER_ARB,
- size_in_bytes,
- NULL,
- GL_STATIC_DRAW_ARB);
- CHECK_GL_ERROR();
- return true;
-}
-
-void VertexBufferGL::ConcreteFree() {
- if (gl_buffer_) {
- renderer_->MakeCurrentLazy();
- glDeleteBuffersARB(1, &gl_buffer_);
- gl_buffer_ = 0;
- CHECK_GL_ERROR();
- }
-}
-
-// Calls Lock on the OpenGL buffer to get the address in memory of where the
-// buffer data is currently stored.
-bool VertexBufferGL::ConcreteLock(Buffer::AccessMode access_mode,
- void **buffer_data) {
- DLOG(INFO) << "VertexBufferGL Lock \"" << name() << "\"";
- renderer_->MakeCurrentLazy();
- glBindBufferARB(GL_ARRAY_BUFFER_ARB, gl_buffer_);
- *buffer_data = glMapBufferARB(GL_ARRAY_BUFFER_ARB,
- BufferAccessModeToGLenum(access_mode));
- if (*buffer_data == NULL) {
- GLenum error = glGetError();
- if (error == GL_OUT_OF_MEMORY) {
- O3D_ERROR(service_locator()) << "Out of memory for buffer lock.";
- } else {
- O3D_ERROR(service_locator()) << "Unable to lock a GL Array Buffer";
- }
- return false;
- }
- CHECK_GL_ERROR();
- return true;
-}
-
-// Calls Unlock on the OpenGL buffer to notify that the contents of the buffer
-// are now ready for use.
-bool VertexBufferGL::ConcreteUnlock() {
- DLOG(INFO) << "VertexBufferGL Unlock \"" << name() << "\"";
- renderer_->MakeCurrentLazy();
- glBindBufferARB(GL_ARRAY_BUFFER_ARB, gl_buffer_);
- if (!glUnmapBufferARB(GL_ARRAY_BUFFER)) {
- GLenum error = glGetError();
- if (error == GL_INVALID_OPERATION) {
- O3D_ERROR(service_locator()) <<
- "Buffer was unlocked without first being locked.";
- } else {
- O3D_ERROR(
- service_locator()) << "Unable to unlock a GL Element Array Buffer";
- }
- return false;
- }
- CHECK_GL_ERROR();
- return true;
-}
-
-
-// Index Buffers ---------------------------------------------------------------
-
-// Initializes the O3D IndexBuffer object but does not create a OpenGL
-// buffer yet.
-
-IndexBufferGL::IndexBufferGL(ServiceLocator* service_locator)
- : IndexBuffer(service_locator),
- renderer_(static_cast<RendererGL*>(
- service_locator->GetService<Renderer>())),
- gl_buffer_(0) {
- DLOG(INFO) << "IndexBufferGL Construct";
-}
-
-// Destructor releases the OpenGL index buffer.
-IndexBufferGL::~IndexBufferGL() {
- DLOG(INFO) << "IndexBufferGL Destruct \"" << name() << "\"";
- ConcreteFree();
-}
-
-// Creates a OpenGL index buffer of the requested size.
-bool IndexBufferGL::ConcreteAllocate(size_t size_in_bytes) {
- DLOG(INFO) << "IndexBufferGL Allocate \"" << name() << "\"";
- renderer_->MakeCurrentLazy();
- ConcreteFree();
- // Create a new VBO.
- glGenBuffersARB(1, &gl_buffer_);
- if (!gl_buffer_) return false;
- // Give the VBO a size, but no data, and set the hint to "STATIC_DRAW"
- // to mark the buffer as set up once then used often.
- glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, gl_buffer_);
- glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB,
- size_in_bytes,
- NULL,
- GL_STATIC_DRAW_ARB);
- CHECK_GL_ERROR();
- return true;
-}
-
-void IndexBufferGL::ConcreteFree() {
- if (gl_buffer_) {
- renderer_->MakeCurrentLazy();
- glDeleteBuffersARB(1, &gl_buffer_);
- gl_buffer_ = 0;
- CHECK_GL_ERROR();
- }
-}
-
-// Maps the OpenGL buffer to get the address in memory of the buffer data.
-bool IndexBufferGL::ConcreteLock(Buffer::AccessMode access_mode,
- void **buffer_data) {
- DLOG(INFO) << "IndexBufferGL Lock \"" << name() << "\"";
- renderer_->MakeCurrentLazy();
- glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, gl_buffer_);
- if (!num_elements())
- return true;
- *buffer_data = glMapBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB,
- BufferAccessModeToGLenum(access_mode));
- if (*buffer_data == NULL) {
- GLenum error = glGetError();
- if (error == GL_OUT_OF_MEMORY) {
- O3D_ERROR(service_locator()) << "Out of memory for buffer lock.";
- } else {
- O3D_ERROR(
- service_locator()) << "Unable to lock a GL Element Array Buffer";
- }
- return false;
- }
- CHECK_GL_ERROR();
- return true;
-}
-
-// Calls Unlock on the OpenGL buffer to notify that the contents of the buffer
-// are now ready for use.
-bool IndexBufferGL::ConcreteUnlock() {
- DLOG(INFO) << "IndexBufferGL Unlock \"" << name() << "\"";
- renderer_->MakeCurrentLazy();
- if (!num_elements())
- return true;
- glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, gl_buffer_);
- if (!glUnmapBufferARB(GL_ELEMENT_ARRAY_BUFFER)) {
- GLenum error = glGetError();
- if (error == GL_INVALID_OPERATION) {
- O3D_ERROR(service_locator()) <<
- "Buffer was unlocked without first being locked.";
- } else {
- O3D_ERROR(
- service_locator()) << "Unable to unlock a GL Element Array Buffer";
- }
- return false;
- }
- CHECK_GL_ERROR();
- return true;
-}
-} // namespace o3d
diff --git a/o3d/core/cross/gl/buffer_gl.h b/o3d/core/cross/gl/buffer_gl.h
deleted file mode 100644
index 69d34a1..0000000
--- a/o3d/core/cross/gl/buffer_gl.h
+++ /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 declaration of the platform specific
-// VertexBufferGL and IndexBufferGL objects used by O3D
-
-#ifndef O3D_CORE_CROSS_GL_BUFFER_GL_H_
-#define O3D_CORE_CROSS_GL_BUFFER_GL_H_
-
-#include "core/cross/buffer.h"
-#include "core/cross/gl/gl_headers.h"
-
-namespace o3d {
-
-class RendererGL;
-
-// VertexBufferGL is a wrapper around an OpenGL Vertex Buffer Object (VBO).
-// The buffer starts out empty. Calling Allocate() will reserve video memory
-// for the buffer. Buffer contents are are updated by calling Lock() to get a
-// pointer to the memory allocated for the buffer, updating that data in place
-// and calling Unlock() to notify OpenGL that the edits are done.
-//
-// To force the vertex and index buffers to be created by Cg Runtime
-// control, define the compile flag "USE_CG_BUFFERS". This option is off by
-// default and buffers are created, locked and managed using the OpenGL
-// "ARB_vertex_buffer_object" extension.
-
-class VertexBufferGL : public VertexBuffer {
- public:
- explicit VertexBufferGL(ServiceLocator* service_locator);
- ~VertexBufferGL();
-
- // Returns the OpenGL vertex buffer Object handle.
- GLuint gl_buffer() const { return gl_buffer_; }
-
- protected:
- // Creates a OpenGL vertex buffer object of the specified size.
- virtual bool ConcreteAllocate(size_t size_in_bytes);
-
- // Frees the OpenGL vertex buffer object.
- virtual void ConcreteFree();
-
- // Returns a pointer to the current contents of the buffer. A matching
- // call to Unlock is necessary to update the contents of the buffer.
- virtual bool ConcreteLock(AccessMode access_mode, void** buffer_data);
-
- // Notifies OpenGL that the buffer data has been updated. Unlock is only
- // valid if it follows a Lock operation.
- virtual bool ConcreteUnlock();
-
- private:
- RendererGL* renderer_;
- GLuint gl_buffer_;
-};
-
-// IndexBufferGL is a wrapper around an OpenGL Index Buffer Object (VBO).
-// The buffer starts out empty. A call to Allocate() will create an OpenGL
-// index buffer of the requested size. Updates the to the contents of the
-// buffer are done via the Lock/Unlock calls.
-class IndexBufferGL : public IndexBuffer {
- public:
- explicit IndexBufferGL(ServiceLocator* service_locator);
- ~IndexBufferGL();
-
- // Returns the OpenGL vertex buffer Object handle.
- GLuint gl_buffer() const { return gl_buffer_; }
-
- protected:
- // Creates a OpenGL index buffer of the specified size.
- virtual bool ConcreteAllocate(size_t size_in_bytes);
-
- // Frees the OpenGL vertex buffer object.
- virtual void ConcreteFree();
-
- // Returns a pointer to the current contents of the buffer. After calling
- // Lock, the contents of the buffer can be updated in place.
- virtual bool ConcreteLock(AccessMode access_mode, void** buffer_data);
-
- // Notifies OpenGL that the buffer data has been updated. Unlock is only
- // valid if it follows a Lock operation.
- virtual bool ConcreteUnlock();
-
- private:
- RendererGL* renderer_;
- GLuint gl_buffer_;
-};
-
-} // namespace o3d
-
-
-#endif // O3D_CORE_CROSS_GL_BUFFER_GL_H_
diff --git a/o3d/core/cross/gl/draw_element_gl.cc b/o3d/core/cross/gl/draw_element_gl.cc
deleted file mode 100644
index 3e09856..0000000
--- a/o3d/core/cross/gl/draw_element_gl.cc
+++ /dev/null
@@ -1,46 +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 definition of the DrawElementGL class.
-
-#include "core/cross/gl/draw_element_gl.h"
-
-namespace o3d {
-
-DrawElementGL::DrawElementGL(ServiceLocator* service_locator)
- : DrawElement(service_locator) {
-}
-
-DrawElementGL::~DrawElementGL() {
-}
-} // namespace o3d
-
diff --git a/o3d/core/cross/gl/draw_element_gl.h b/o3d/core/cross/gl/draw_element_gl.h
deleted file mode 100644
index 76ccc0c..0000000
--- a/o3d/core/cross/gl/draw_element_gl.h
+++ /dev/null
@@ -1,57 +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 declaration of the DrawElementGL class.
-
-#ifndef O3D_CORE_CROSS_GL_DRAW_ELEMENT_GL_H_
-#define O3D_CORE_CROSS_GL_DRAW_ELEMENT_GL_H_
-
-#include <map>
-#include "core/cross/draw_element.h"
-
-namespace o3d {
-
-class Element;
-
-// DrawElementGL is the OpenGL implementation of the DrawElement. It
-// provides a place for the renderer to store platform specific cache
-// information.
-class DrawElementGL : public DrawElement {
- public:
- explicit DrawElementGL(ServiceLocator* service_locator);
- ~DrawElementGL();
-
- private:
-};
-} // o3d
-
-#endif // O3D_CORE_CROSS_GL_DRAW_ELEMENT_GL_H_
diff --git a/o3d/core/cross/gl/effect_gl.cc b/o3d/core/cross/gl/effect_gl.cc
deleted file mode 100644
index 755d80a..0000000
--- a/o3d/core/cross/gl/effect_gl.cc
+++ /dev/null
@@ -1,632 +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 definition of EffectGL, the OpenGL implementation
-// of the abstract O3D class Effect.
-
-
-// Disable pointer casting warning for openGL calls that require a void* to
-// be cast to a GLuint
-#if defined(OS_WIN)
-#pragma warning(disable : 4312)
-#pragma warning(disable : 4311)
-#endif
-
-#include <sstream>
-#include "base/cross/std_functional.h"
-#include "core/cross/semantic_manager.h"
-#include "core/cross/error.h"
-#include "core/cross/standard_param.h"
-#include "core/cross/gl/effect_gl.h"
-#include "core/cross/gl/renderer_gl.h"
-#include "core/cross/gl/primitive_gl.h"
-#include "core/cross/gl/draw_element_gl.h"
-#include "core/cross/gl/texture_gl.h"
-#include "core/cross/gl/utils_gl.h"
-#include "core/cross/gl/utils_gl-inl.h"
-
-#if defined(OS_WIN)
-#include "core/cross/core_metrics.h"
-#endif
-
-namespace o3d {
-
-// Number of repeating events to log before giving up, e.g. setup frame,
-// draw polygons, etc.
-const int kNumLoggedEvents = 5;
-
-// Convert a CGparameter data type into a Param type. Note that
-// Param::BOOLEAN is never generated by the Cg compiler.
-static const ObjectBase::Class* CgTypeToParamType(CGtype cg_type) {
- switch (cg_type) {
- case CG_FLOAT :
- case CG_FLOAT1 : return ParamFloat::GetApparentClass();
- case CG_FLOAT2 : return ParamFloat2::GetApparentClass();
- case CG_FLOAT3 : return ParamFloat3::GetApparentClass();
- case CG_FLOAT4 : return ParamFloat4::GetApparentClass();
- case CG_INT : return ParamInteger::GetApparentClass();
- case CG_INT1 : return ParamInteger::GetApparentClass();
- case CG_FLOAT4x4 : return ParamMatrix4::GetApparentClass();
- case CG_BOOL :
- case CG_BOOL1 : return ParamBoolean::GetApparentClass();
- case CG_SAMPLER :
- case CG_SAMPLER1D :
- case CG_SAMPLER2D :
- case CG_SAMPLER3D :
- case CG_SAMPLERCUBE : return ParamSampler::GetApparentClass();
- default : {
- DLOG(ERROR) << "Cannot convert CGtype "
- << cgGetTypeString(cg_type)
- << " to a Param type.";
- return NULL;
- }
- }
-}
-
-// -----------------------------------------------------------------------------
-
-EffectGL::EffectGL(ServiceLocator* service_locator, CGcontext cg_context)
- : Effect(service_locator),
- semantic_manager_(service_locator->GetService<SemanticManager>()),
- renderer_(static_cast<RendererGL*>(
- service_locator->GetService<Renderer>())),
- cg_context_(cg_context),
- cg_vertex_(NULL),
- cg_fragment_(NULL) {
- DLOG(INFO) << "EffectGL Construct";
-}
-
-// Destructor releases vertex and fragment shaders and their correspoding
-// constants tables.
-EffectGL::~EffectGL() {
- DLOG(INFO) << "EffectGL Destruct \"" << name() << "\"";
- if (cg_vertex_) {
- cgDestroyProgram(cg_vertex_);
- }
- if (cg_fragment_) {
- cgDestroyProgram(cg_fragment_);
- }
-}
-
-// Rewrites vertex program assembly code to match GL semantics for clipping.
-// This parses the source, breaking it down into pieces:
-// - declaration ("!!ARBvp1.0")
-// - comments (that contain the parameter information)
-// - instructions
-// - "END" token.
-// Then it rewrites the instructions so that 'result.position' doesn't get
-// written directly, instead it is written to a temporary variable. Then a
-// transformation is done on that variable before outputing to
-// 'result.position':
-// - offset x and y by half a pixel (times w).
-// - remap z from [0..w] to [-w..w].
-// - invert y, if render targets are active.
-//
-// Note that for the 1/2 pixel offset, we need a parameter that depends on the
-// current viewport. This is done through 'program.env[0]' which is shared
-// across all programs (so we only have to update it once when we change the
-// viewport), because Cg won't use them currently (it uses 'program.local'
-// instead).
-static bool RewriteVertexProgramSource(String *source) {
- String::size_type pos = source->find('\n');
- if (pos == String::npos) {
- DLOG(ERROR) << "could not find program declaration";
- return false;
- }
- String decl(*source, 0, pos + 1);
- String::size_type start_comments = pos + 1;
- // skip the comments that contain the parameters etc.
- for (; pos < source->size(); pos = source->find('\n', pos)) {
- ++pos;
- if (pos >= source->size())
- break;
- if ((*source)[pos] != '#')
- break;
- }
- if (pos >= source->size()) {
- // we only found comments.
- return false;
- }
- String comments(*source, start_comments, pos - start_comments);
-
- String::size_type end_token = source->find("\nEND", pos + 1);
- if (end_token == String::npos) {
- DLOG(ERROR) << "Compiled shader doesn't have an END token";
- return false;
- }
- String instructions(*source, pos, end_token + 1 - pos);
-
- // Replace accesses to 'result.position' by accesses to our temp variable
- // '$O3D_HPOS'.
- // '$' is a valid symbol for identifiers, but Cg doesn't seem to be using
- // it, so we can use it to ensure we don't have name conflicts.
- static const char kOutPositionRegister[] = "result.position";
- for (String::size_type i = instructions.find(kOutPositionRegister);
- i < String::npos; i = instructions.find(kOutPositionRegister, i)) {
- instructions.replace(i, strlen(kOutPositionRegister), "$O3D_HPOS");
- }
-
- *source = decl +
- comments +
- // .x = 1/viewport.width; .y = -1/viewport.height; .z = 2.0; w = +/-1.0;
- "PARAM $O3D_HELPER = program.env[0];\n"
- "TEMP $O3D_HPOS;\n" +
- instructions +
- // hpos.x <- hpos.x + hpos.w / viewport.width;
- // hpos.y <- hpos.y - hpos.w / viewport.height;
- "MAD $O3D_HPOS.xy, $O3D_HELPER.xyyy, $O3D_HPOS.w, $O3D_HPOS.xyyy;\n"
- // Invert y, based on the w component of the helper arg.
- "MUL $O3D_HPOS.y, $O3D_HELPER.w, $O3D_HPOS.y;\n"
- // hpos.z <- hpos.z * 2 - hpos.w
- "MAD $O3D_HPOS.z, $O3D_HPOS.z, $O3D_HELPER.z, -$O3D_HPOS.w;\n"
- "MOV result.position, $O3D_HPOS;\n"
- "END\n";
- return true;
-}
-
-// Initializes the Effect object using the shaders found in an FX formatted
-// string.
-bool EffectGL::LoadFromFXString(const String& effect) {
- DLOG(INFO) << "EffectGL LoadFromFXString";
- renderer_->MakeCurrentLazy();
-
- set_source("");
-
- String vertex_shader_entry_point;
- String fragment_shader_entry_point;
- MatrixLoadOrder matrix_load_order;
- // TODO(gman): Check for failure once shader parser is in.
- if (!ValidateFX(effect,
- &vertex_shader_entry_point,
- &fragment_shader_entry_point,
- &matrix_load_order)) {
- return false;
- }
-
- set_matrix_load_order(matrix_load_order);
-
- // Compile the original vertex program once, to get the ARBVP1 assembly code.
- CGprogram original_vp = cgCreateProgram(cg_context_, CG_SOURCE,
- effect.c_str(), CG_PROFILE_ARBVP1,
- vertex_shader_entry_point.c_str(),
- NULL);
- const char* listing = cgGetLastListing(cg_context_);
- if (original_vp == NULL) {
- O3D_ERROR(service_locator()) << "Effect Compile Error: "
- << cgGetErrorString(cgGetError()) << " : "
- << listing;
- return false;
- }
-
- if (listing && listing[0] != 0) {
- DLOG(WARNING) << "Effect Compile Warnings: " << listing;
- }
-
- String vp_assembly = cgGetProgramString(original_vp, CG_COMPILED_PROGRAM);
- cgDestroyProgram(original_vp);
- if (!RewriteVertexProgramSource(&vp_assembly)) {
- return false;
- }
- cg_vertex_ = cgCreateProgram(cg_context_, CG_OBJECT, vp_assembly.c_str(),
- CG_PROFILE_ARBVP1,
- vertex_shader_entry_point.c_str(), NULL);
- listing = cgGetLastListing(cg_context_);
- if (cg_vertex_ == NULL) {
- O3D_ERROR(service_locator()) << "Effect post-rewrite Compile Error: "
- << cgGetErrorString(cgGetError()) << " : "
- << listing;
- return false;
- }
-
-#ifdef OS_WIN
- // Get metrics for length of the vertex shader
- const char* shader_data = cgGetProgramString(cg_vertex_, CG_COMPILED_PROGRAM);
- metric_vertex_shader_instruction_count.AddSample(strlen(shader_data));
-#endif
-
- if (listing && listing[0] != 0) {
- DLOG(WARNING) << "Effect post-rewrite compile warnings: " << listing;
- }
-
- // If the program rewrite introduced some syntax or semantic errors, we won't
- // know it until we load the program (through a GL error).
- // So flush all GL errors first...
- FlushGlErrors();
-
- // ... Then load the program ...
- cgGLLoadProgram(cg_vertex_);
-
- // ... And check for GL errors.
- if (glGetError() != GL_NO_ERROR) {
- O3D_ERROR(service_locator())
- << "Effect post-rewrite GL Error: "
- << glGetString(GL_PROGRAM_ERROR_STRING_ARB)
- << "\nSource: \n"
- << vp_assembly;
- return false;
- }
-
- cg_fragment_ = cgCreateProgram(cg_context_, CG_SOURCE, effect.c_str(),
- CG_PROFILE_ARBFP1,
- fragment_shader_entry_point.c_str(), NULL);
- listing = cgGetLastListing(cg_context_);
- if (cg_fragment_ == NULL) {
- O3D_ERROR(service_locator()) << "Effect Compile Error: "
- << cgGetErrorString(cgGetError()) << " : "
- << listing;
- return false;
- }
-
-#ifdef OS_WIN
- // Get metrics for length of the fragment shader
- shader_data = cgGetProgramString(cg_fragment_, CG_COMPILED_PROGRAM);
- metric_pixel_shader_instruction_count.AddSample(strlen(shader_data));
-#endif
-
- if (listing && listing[0] != 0) {
- DLOG(WARNING) << "Effect Compile Warnings: " << listing;
- }
-
- cgGLLoadProgram(cg_fragment_);
-
- // Also check for GL errors, in case Cg managed to compile, but generated a
- // bad program.
- if (glGetError() != GL_NO_ERROR) {
- O3D_ERROR(service_locator())
- << "Effect GL Error: "
- << glGetString(GL_PROGRAM_ERROR_STRING_ARB);
- return false;
- }
-
- // TODO(o3d): remove this (OLD path for textures).
- FillSamplerToTextureMap(effect);
-
- CHECK_GL_ERROR();
-
- set_source(effect);
- return true;
-}
-
-// Fills the sampler->texture map. This needs to compile the source as an
-// effect because the state assignments get lost when compiled as a
-// shader.
-// Note that we compile the raw effect, which shouldn't have any
-// technique/pass, so we don't actually create programs, just parse the
-// uniforms and state assignments.
-void EffectGL::FillSamplerToTextureMap(const String &effect) {
- CGeffect cg_effect = cgCreateEffect(cg_context_, effect.c_str(), NULL);
- if (!cg_effect) {
- DLOG(ERROR) << "Could not compile the effect to find "
- << "Sampler->Texture associations";
- return;
- }
- for (CGparameter param = cgGetFirstEffectParameter(cg_effect);
- param; param = cgGetNextLeafParameter(param)) {
- CGtype cg_type = cgGetParameterType(param);
- switch (cg_type) {
- case CG_SAMPLER:
- case CG_SAMPLER1D:
- case CG_SAMPLER2D:
- case CG_SAMPLER3D:
- case CG_SAMPLERCUBE:
- break;
- default:
- continue;
- }
- CGstateassignment state_assignment =
- cgGetNamedSamplerStateAssignment(param, "Texture");
- if (!state_assignment)
- continue;
- CGparameter texture_param =
- cgGetTextureStateAssignmentValue(state_assignment);
- if (!texture_param)
- continue;
- DCHECK((cgGetParameterType(texture_param) == CG_TEXTURE));
- sampler_to_texture_map_[cgGetParameterName(param)] =
- cgGetParameterName(texture_param);
- }
- cgDestroyEffect(cg_effect);
-}
-
-// TODO(o3d): remove this (OLD path for textures).
-String EffectGL::GetTextureNameFromSamplerParamName(
- const String &sampler_name) {
- std::map<String, String>::iterator it =
- sampler_to_texture_map_.find(sampler_name);
- if (it != sampler_to_texture_map_.end()) {
- return it->second;
- } else {
- return "";
- }
-}
-
-// Given a CG_SAMPLER parameter, find the corresponding CG_TEXTURE
-// parameter. From this CG_TEXTURE, find a matching Param by name.
-ParamTexture* EffectGL::GetTextureParamFromCgSampler(
- CGparameter cg_sampler,
- const std::vector<ParamObject*> &param_objects) {
- DLOG(INFO) << "EffectGL GetTextureParamFromCgSampler";
- DLOG_ASSERT(cgGetParameterType(cg_sampler) != CG_SAMPLER);
- String sampler_name = cgGetParameterName(cg_sampler);
- String param_name = GetTextureNameFromSamplerParamName(sampler_name);
- if (param_name.empty()) {
- // Sampler has no texture associated with it.
- return NULL;
- }
- // Find a matching Param with the same name as the CG_TEXTURE.
- for (unsigned int i = 0; i < param_objects.size(); ++i) {
- Param* param = param_objects[i]->GetUntypedParam(param_name);
- if (param && param->IsA(ParamTexture::GetApparentClass())) {
- // Success.
- DLOG(INFO) << "EffectGL Matched CG_SAMPLER \""
- << sampler_name
- << "\" To Param \""
- << param_name << "\"";
- return down_cast<ParamTexture*>(param);
- }
- }
- DLOG(INFO) << "No matching Param for CG_TEXTURE \""
- << param_name
- << "\" used by CG_SAMPLER \""
- << sampler_name << "\"";
- return NULL;
-}
-
-void EffectGL::GetShaderParamInfo(
- CGprogram program,
- CGenum name_space,
- std::map<String, EffectParameterInfo>* info_map) {
- DCHECK(info_map);
-
- // Loop over all parameters, visiting only CGparameters that have
- // had storage allocated to them.
- CGparameter cg_param = cgGetFirstParameter(program, name_space);
- for (; cg_param != NULL; cg_param = cgGetNextParameter(cg_param)) {
- CGenum variability = cgGetParameterVariability(cg_param);
- if (variability != CG_UNIFORM)
- continue;
- CGenum direction = cgGetParameterDirection(cg_param);
- if (direction != CG_IN)
- continue;
- String name = cgGetParameterName(cg_param);
- CGtype cg_type = cgGetParameterType(cg_param);
- // Texture parameters need special handling as the c3cImport system
- // records a handle to the CG_TEXTURE param, not the CG_SAMPLER
- // param. D3D sets textures by binding a bitmap to the Texture
- // param, Cg binds bitmaps to the Sampler parameter. We solve this
- // by keeping an internal collection of Texture-Sampler mappings
- // that is built here, so we can later to do the reverse lookup.
- //
- // TODO(o3d): This will not solve the one-to-many problem of one
- // Texture being used by many Sampler params, but it's enough to get
- // us up and running.
- //
- // TODO(o3d): Once we start using samplers exclusively, this special
- // treatment of textures should go away. For the time being though, we do
- // end up creating a texture param on the param_object.
- if (cg_type == CG_SAMPLER1D ||
- cg_type == CG_SAMPLER2D ||
- cg_type == CG_SAMPLER3D ||
- cg_type == CG_SAMPLERCUBE) {
- // rename the parameter to have the name of the texture.
- String texture_param_name = GetTextureNameFromSamplerParamName(name);
- if (texture_param_name.size() != 0) {
- (*info_map)[texture_param_name] = EffectParameterInfo(
- texture_param_name,
- ParamTexture::GetApparentClass(),
- 0,
- "",
- false);
- }
- } else if (cg_type == CG_TEXTURE) {
- continue;
- }
- int num_elements;
- if (cg_type == CG_ARRAY) {
- num_elements = cgGetArraySize(cg_param, 0);
- // Substitute the first element's type for our type.
- cg_type = cgGetParameterType(cgGetArrayParameter(cg_param, 0));
- } else {
- num_elements = 0;
- }
- const ObjectBase::Class *param_class = CgTypeToParamType(cg_type);
- if (!param_class)
- continue;
- const char* cg_semantic = cgGetParameterSemantic(cg_param);
- const ObjectBase::Class *sem_class = NULL;
- if (cg_semantic != NULL && cg_semantic[0] != '\0') {
- // NOTE: this semantic is not the regularised profile semantic output
- // from the CGC compiler but the actual user supplied semantic from
- // the shader source code, so this match is valid.
- sem_class = semantic_manager_->LookupSemantic(cg_semantic);
- }
- (*info_map)[name] = EffectParameterInfo(
- name,
- param_class,
- num_elements,
- (cg_semantic != NULL) ? cg_semantic : "",
- sem_class);
- }
-}
-
-void EffectGL::GetParameterInfo(EffectParameterInfoArray* info_array) {
- DCHECK(info_array);
- std::map<String, EffectParameterInfo> info_map;
- renderer_->MakeCurrentLazy();
- if (cg_vertex_) {
- GetShaderParamInfo(cg_vertex_, CG_PROGRAM, &info_map);
- GetShaderParamInfo(cg_vertex_, CG_GLOBAL, &info_map);
- }
- if (cg_fragment_) {
- // create Param objects based on the parameters found in the fragment
- // program.
- GetShaderParamInfo(cg_fragment_, CG_PROGRAM, &info_map);
- GetShaderParamInfo(cg_fragment_, CG_GLOBAL, &info_map);
- }
- info_array->clear();
- info_array->reserve(info_map.size());
- std::transform(
- info_map.begin(),
- info_map.end(),
- std::back_inserter(*info_array),
- base::select2nd<std::map<String, EffectParameterInfo>::value_type>());
-}
-
-void EffectGL::GetVaryingVertexShaderParamInfo(
- CGprogram program,
- CGenum name_space,
- std::vector<EffectStreamInfo>* info_array) {
- CGparameter cg_param = cgGetFirstLeafParameter(cg_vertex_, name_space);
- for (; cg_param != NULL; cg_param = cgGetNextLeafParameter(cg_param)) {
- CGenum variability = cgGetParameterVariability(cg_param);
- if (variability != CG_VARYING)
- continue;
- CGenum direction = cgGetParameterDirection(cg_param);
- if (direction != CG_IN)
- continue;
-
- const char* cg_semantic = cgGetParameterSemantic(cg_param);
- if (cg_semantic == NULL)
- continue;
-
- int attr = SemanticNameToGLVertexAttribute(cg_semantic);
- if (attr < 0)
- continue;
-
- int semantic_index = 0;
- Stream::Semantic semantic = GLVertexAttributeToStream(attr,
- &semantic_index);
- if (semantic == Stream::UNKNOWN_SEMANTIC)
- continue;
-
- info_array->push_back(EffectStreamInfo(semantic,
- semantic_index));
- }
-}
-
-void EffectGL::GetStreamInfo(
- EffectStreamInfoArray* info_array) {
- DCHECK(info_array);
- renderer_->MakeCurrentLazy();
- info_array->clear();
- GetVaryingVertexShaderParamInfo(cg_vertex_, CG_PROGRAM, info_array);
- GetVaryingVertexShaderParamInfo(cg_vertex_, CG_GLOBAL, info_array);
-}
-
-
-// private functions -----------------------------------------------------------
-
-// Loop over all the CG_SAMPLER objects and attach the GLuint handle for the
-// GL texture object that we discovered earlier. Then execute the
-// CGstateassignments in the sampler_state to set up the texture unit.
-// TODO(o3d): remove this (OLD path for textures).
-void EffectGL::SetTexturesFromEffect(ParamCacheGL* param_cache_gl) {
- DLOG_FIRST_N(INFO, kNumLoggedEvents) << "EffectGL EnableTexturesFromEffect";
- ParamCacheGL::SamplerParameterMap& map = param_cache_gl->sampler_map();
- ParamCacheGL::SamplerParameterMap::iterator i;
- for (i = map.begin(); i != map.end(); ++i) {
- CGparameter cg_param = i->first;
- ParamTexture *param = i->second;
- if (param != NULL) {
- Texture *t = param->value();
- if (t) {
- GLuint handle = static_cast<GLuint>(reinterpret_cast<intptr_t>(
- t->GetTextureHandle()));
- cgGLSetTextureParameter(cg_param, handle);
- cgGLEnableTextureParameter(cg_param);
- }
- }
- }
- CHECK_GL_ERROR();
-}
-
-// Loop through all the uniform CGparameters on the effect and set their
-// values from their corresponding Params on the various ParamObject (as stored
-// in the ParamCacheGL).
-void EffectGL::UpdateShaderUniformsFromEffect(ParamCacheGL* param_cache_gl) {
- DLOG_FIRST_N(INFO, kNumLoggedEvents)
- << "EffectGL UpdateShaderUniformsFromEffect";
- ParamCacheGL::UniformParameterMap& map = param_cache_gl->uniform_map();
- ParamCacheGL::UniformParameterMap::iterator i;
- for (i = map.begin(); i != map.end(); ++i) {
- CGparameter cg_param = i->first;
- i->second->SetEffectParam(renderer_, cg_param);
- }
- CHECK_GL_ERROR();
-}
-
-// Loop through all the uniform CGparameters on the effect and reset their
-// values. For now, this unbinds textures contained in sampler parameters.
-void EffectGL::ResetShaderUniforms(ParamCacheGL* param_cache_gl) {
- DLOG_FIRST_N(INFO, kNumLoggedEvents) << "EffectGL ResetShaderUniforms";
- ParamCacheGL::UniformParameterMap& map = param_cache_gl->uniform_map();
- ParamCacheGL::UniformParameterMap::iterator i;
- for (i = map.begin(); i != map.end(); ++i) {
- CGparameter cg_param = i->first;
- i->second->ResetEffectParam(renderer_, cg_param);
- }
- CHECK_GL_ERROR();
-}
-
-// Updates the values of the vertex and fragment shader parameters using the
-// current values in the param/cgparam caches.
-void EffectGL::PrepareForDraw(ParamCacheGL* param_cache_gl) {
- DLOG_FIRST_N(INFO, kNumLoggedEvents) << "EffectGL PrepareForDraw \""
- << name()
- << "\"";
- DCHECK(renderer_->IsCurrent());
- if (cg_vertex_ && cg_fragment_) {
- // Initialise the render states for this pass, this includes the shaders.
- cgGLBindProgram(cg_vertex_);
- cgGLBindProgram(cg_fragment_);
- UpdateShaderUniformsFromEffect(param_cache_gl);
-
- // TODO(o3d): remove this (OLD path for textures).
- SetTexturesFromEffect(param_cache_gl);
- } else {
- DLOG_FIRST_N(ERROR, kNumLoggedEvents)
- << "No valid CGeffect found "
- << "in Effect \"" << name() << "\"";
- }
- CHECK_GL_ERROR();
-}
-
-// Resets the render states back to their default value.
-void EffectGL::PostDraw(ParamCacheGL* param_cache_gl) {
- DLOG_FIRST_N(INFO, kNumLoggedEvents)
- << "EffectGL PostDraw \"" << name() << "\"";
- DCHECK(renderer_->IsCurrent());
- ResetShaderUniforms(param_cache_gl);
- CHECK_GL_ERROR();
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/gl/effect_gl.h b/o3d/core/cross/gl/effect_gl.h
deleted file mode 100644
index 1d9b81f..0000000
--- a/o3d/core/cross/gl/effect_gl.h
+++ /dev/null
@@ -1,147 +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 declaration of the EffectGL class.
-
-#ifndef O3D_CORE_CROSS_GL_EFFECT_GL_H_
-#define O3D_CORE_CROSS_GL_EFFECT_GL_H_
-
-// Disable compiler warning for openGL calls that require a void* to
-// be cast to a GLuint
-#if defined(OS_WIN)
-#pragma warning(disable : 4312)
-#pragma warning(disable : 4311)
-#endif
-
-#include <utility>
-#include <vector>
-#include <map>
-#include "core/cross/gl/gl_headers.h"
-#include "core/cross/effect.h"
-#include "core/cross/gl/utils_gl.h"
-
-namespace o3d {
-
-class DrawElementGL;
-class ParamCacheGL;
-class ParamObject;
-class Param;
-class ParamTexture;
-class RendererGL;
-class SemanticManager;
-
-// A class to set an effect parameter from an O3D parameter.
-class EffectParamHandlerGL : public RefCounted {
- public:
- typedef SmartPointer<EffectParamHandlerGL> Ref;
- virtual ~EffectParamHandlerGL() { }
-
- // Sets a GL/Cg Effect Parameter by an O3D Param.
- virtual void SetEffectParam(RendererGL* renderer, CGparameter cg_param) = 0;
-
- // Resets a GL/Cg Effect parameter to default (currently only
- // unbinds textures contained in Sampler params).
- virtual void ResetEffectParam(RendererGL* renderer, CGparameter cg_param) {}
-};
-
-// EffectGL is an implementation of the Effect object for OpenGL. It
-// provides the API for setting the vertex and framgent shaders for the
-// Effect using the Cg Runtime. Currently the two shaders can either be
-// provided separately as shader code or together in an FX file.
-class EffectGL : public Effect {
- public:
- EffectGL(ServiceLocator* service_locator, CGcontext cg_context);
- virtual ~EffectGL();
-
- // Reads the vertex and fragment shaders from string in the FX format.
- // It returns true if the shaders were successfully compiled.
- virtual bool LoadFromFXString(const String& effect);
-
- // Binds the shaders to the device and sets up all the shader parameters using
- // the values from the matching Param's of the param_object.
- void PrepareForDraw(ParamCacheGL* param_cache_gl);
-
- // Removes any pipeline state-changes installed during a draw.
- void PostDraw(ParamCacheGL* param_cache_gl);
-
- // Gets info about the parameters this effect needs.
- // Overriden from Effect.
- virtual void GetParameterInfo(EffectParameterInfoArray* info_array);
-
- // Gets info about the streams this effect needs.
- // Overriden from Effect.
- virtual void GetStreamInfo(
- EffectStreamInfoArray* info_array);
-
- // Given a CG_SAMPLER parameter, find the corresponding CG_TEXTURE
- // parameterand from this CG_TEXTURE, find a matching Param by name in a list
- // of ParamObject.
- // TODO: remove this (OLD path for textures).
- ParamTexture* GetTextureParamFromCgSampler(
- CGparameter cg_sampler,
- const std::vector<ParamObject*> &param_objects);
-
- CGprogram cg_vertex_program() { return cg_vertex_; }
- CGprogram cg_fragment_program() { return cg_fragment_; }
-
- private:
- // Loops through all the parameters in the ShapeDataGL and updates the
- // corresponding parameter EffectGL object
- void UpdateShaderUniformsFromEffect(ParamCacheGL* param_cache_gl);
- // Undoes the effect of the above. For now, this unbinds textures.
- void ResetShaderUniforms(ParamCacheGL* param_cache_gl);
- void GetShaderParamInfo(CGprogram program,
- CGenum name_space,
- std::map<String, EffectParameterInfo>* info_map);
- void GetVaryingVertexShaderParamInfo(
- CGprogram program,
- CGenum name_space,
- std::vector<EffectStreamInfo>* info_array);
-
- // TODO: remove these (OLD path for textures).
- void SetTexturesFromEffect(ParamCacheGL* param_cache_gl);
- void FillSamplerToTextureMap(const String &effect);
- String GetTextureNameFromSamplerParamName(const String &sampler_name);
-
- SemanticManager* semantic_manager_;
- RendererGL* renderer_;
-
- CGcontext cg_context_;
- CGprogram cg_vertex_;
- CGprogram cg_fragment_;
-
- // TODO: remove this (OLD path for textures).
- std::map<String, String> sampler_to_texture_map_;
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GL_EFFECT_GL_H_
diff --git a/o3d/core/cross/gl/gl_headers.h b/o3d/core/cross/gl/gl_headers.h
deleted file mode 100644
index 4716c54..0000000
--- a/o3d/core/cross/gl/gl_headers.h
+++ /dev/null
@@ -1,43 +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_CORE_CROSS_GL_GL_HEADERS_H_
-#define O3D_CORE_CROSS_GL_GL_HEADERS_H_
-
-#include <GL/glew.h>
-#if defined(OS_WIN)
-#include <GL/wglew.h>
-#endif
-#include <Cg/cg.h>
-#include <Cg/cgGL.h>
-
-#endif // O3D_CORE_CROSS_GL_GL_HEADERS_H_
-
diff --git a/o3d/core/cross/gl/install_check.cc b/o3d/core/cross/gl/install_check.cc
deleted file mode 100644
index 9ae59dd..0000000
--- a/o3d/core/cross/gl/install_check.cc
+++ /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.
- */
-
-
-#include "core/cross/install_check.h"
-
-namespace o3d {
-
-bool RendererInstallCheck(std::string *error) {
- return true;
-}
-
-} // o3d
diff --git a/o3d/core/cross/gl/param_cache_gl.cc b/o3d/core/cross/gl/param_cache_gl.cc
deleted file mode 100644
index aae2acd..0000000
--- a/o3d/core/cross/gl/param_cache_gl.cc
+++ /dev/null
@@ -1,762 +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 definition of the ParamCacheGL class.
-
-#include "core/cross/error.h"
-#include "core/cross/param_array.h"
-#include "core/cross/renderer.h"
-#include "core/cross/semantic_manager.h"
-#include "core/cross/gl/param_cache_gl.h"
-#include "core/cross/gl/effect_gl.h"
-#include "core/cross/gl/sampler_gl.h"
-#include "core/cross/gl/renderer_gl.h"
-#include "core/cross/element.h"
-#include "core/cross/draw_element.h"
-
-namespace o3d {
-
-typedef std::vector<ParamObject *> ParamObjectList;
-
-ParamCacheGL::ParamCacheGL(SemanticManager* semantic_manager,
- Renderer* renderer)
- : semantic_manager_(semantic_manager),
- renderer_(renderer),
- last_vertex_program_(0),
- last_fragment_program_(0) {
-}
-
-bool ParamCacheGL::ValidateEffect(Effect* effect) {
- DLOG_ASSERT(effect);
-
- EffectGL* effect_gl = down_cast<EffectGL*>(effect);
- return (effect_gl->cg_vertex_program() == last_vertex_program_ ||
- effect_gl->cg_fragment_program() == last_fragment_program_);
-}
-
-void ParamCacheGL::UpdateCache(Effect* effect,
- DrawElement* draw_element,
- Element* element,
- Material* material,
- ParamObject* override) {
- DLOG_ASSERT(effect);
- EffectGL* effect_gl = down_cast<EffectGL*>(effect);
-
- ScanCgEffectParameters(effect_gl->cg_vertex_program(),
- effect_gl->cg_fragment_program(),
- draw_element,
- element,
- material,
- override);
-
- last_vertex_program_ = effect_gl->cg_vertex_program();
- last_fragment_program_ = effect_gl->cg_fragment_program();
-}
-
-template <typename T>
-class TypedEffectParamHandlerGL : public EffectParamHandlerGL {
- public:
- explicit TypedEffectParamHandlerGL(T* param)
- : param_(param) {
- }
- virtual void SetEffectParam(RendererGL* renderer, CGparameter cg_param);
- private:
- T* param_;
-};
-
-class EffectParamHandlerGLMatrixRows : public EffectParamHandlerGL {
- public:
- explicit EffectParamHandlerGLMatrixRows(ParamMatrix4* param)
- : param_(param) {
- }
- virtual void SetEffectParam(RendererGL* renderer, CGparameter cg_param) {
- // set the data as floats in row major order.
- Matrix4 mat = param_->value();
- cgSetMatrixParameterfr(cg_param, &mat[0][0]);
- }
- private:
- ParamMatrix4* param_;
-};
-
-class EffectParamHandlerGLMatrixColumns : public EffectParamHandlerGL {
- public:
- explicit EffectParamHandlerGLMatrixColumns(ParamMatrix4* param)
- : param_(param) {
- }
- virtual void SetEffectParam(RendererGL* renderer, CGparameter cg_param) {
- // set the data as floats in column major order.
- Matrix4 mat = param_->value();
- cgSetMatrixParameterfc(cg_param, &mat[0][0]);
- }
- private:
- ParamMatrix4* param_;
-};
-
-template <>
-void TypedEffectParamHandlerGL<ParamFloat>::SetEffectParam(
- RendererGL* renderer,
- CGparameter cg_param) {
- Float f = param_->value();
- cgSetParameter1f(cg_param, f);
-};
-
-template <>
-void TypedEffectParamHandlerGL<ParamFloat2>::SetEffectParam(
- RendererGL* renderer,
- CGparameter cg_param) {
- Float2 f = param_->value();
- cgSetParameter2fv(cg_param, f.GetFloatArray());
-};
-
-template <>
-void TypedEffectParamHandlerGL<ParamFloat3>::SetEffectParam(
- RendererGL* renderer,
- CGparameter cg_param) {
- Float3 f = param_->value();
- cgSetParameter3fv(cg_param, f.GetFloatArray());
-};
-
-template <>
-void TypedEffectParamHandlerGL<ParamFloat4>::SetEffectParam(
- RendererGL* renderer,
- CGparameter cg_param) {
- Float4 f = param_->value();
- cgSetParameter4fv(cg_param, f.GetFloatArray());
-};
-
-template <>
-void TypedEffectParamHandlerGL<ParamInteger>::SetEffectParam(
- RendererGL* renderer,
- CGparameter cg_param) {
- int i = param_->value();
- cgSetParameter1i(cg_param, i);
-};
-
-template <>
-void TypedEffectParamHandlerGL<ParamBoolean>::SetEffectParam(
- RendererGL* renderer,
- CGparameter cg_param) {
- int i = param_->value();
- cgSetParameter1i(cg_param, i);
-};
-
-class EffectParamHandlerForSamplersGL : public EffectParamHandlerGL {
- public:
- explicit EffectParamHandlerForSamplersGL(ParamSampler* param)
- : param_(param) {
- }
- virtual void SetEffectParam(RendererGL* renderer, CGparameter cg_param) {
- SamplerGL* sampler_gl = down_cast<SamplerGL*>(param_->value());
- if (!sampler_gl) {
- // Use the error sampler.
- sampler_gl = down_cast<SamplerGL*>(renderer->error_sampler());
- // If no error texture is set then generate an error.
- if (!renderer->error_texture()) {
- O3D_ERROR(param_->service_locator())
- << "Missing Sampler for ParamSampler " << param_->name();
- }
- }
- sampler_gl->SetTextureAndStates(cg_param);
- }
- virtual void ResetEffectParam(RendererGL* renderer, CGparameter cg_param) {
- SamplerGL* sampler_gl = down_cast<SamplerGL*>(param_->value());
- if (!sampler_gl) {
- sampler_gl = down_cast<SamplerGL*>(renderer->error_sampler());
- }
- sampler_gl->ResetTexture(cg_param);
- }
- private:
- ParamSampler* param_;
-};
-
-template <typename T>
-class EffectParamArrayHandlerGL : public EffectParamHandlerGL {
- public:
- explicit EffectParamArrayHandlerGL(ParamParamArray* param)
- : param_(param) {
- }
- virtual void SetEffectParam(RendererGL* renderer, CGparameter cg_param) {
- ParamArray* param = param_->value();
- if (param) {
- int size = cgGetArraySize(cg_param, 0);
- if (size != static_cast<int>(param->size())) {
- O3D_ERROR(param->service_locator())
- << "number of params in ParamArray does not match number of params "
- << "needed by shader array";
- } else {
- for (int i = 0; i < size; ++i) {
- Param* untyped_element = param->GetUntypedParam(i);
- // TODO(gman): Make this check happen when building the param cache.
- // To do that would require that ParamParamArray mark it's owner
- // as changed if a Param in it's ParamArray changes.
- if (untyped_element->IsA(T::GetApparentClass())) {
- CGparameter cg_element = cgGetArrayParameter(cg_param, i);
- SetElement(cg_element, down_cast<T*>(untyped_element));
- } else {
- O3D_ERROR(param->service_locator())
- << "Param in ParamArray at index " << i << " is not a "
- << T::GetApparentClassName();
- }
- }
- }
- }
- }
- void SetElement(CGparameter cg_element, T* param);
-
- private:
- ParamParamArray* param_;
-};
-
-template <bool column_major>
-class EffectParamArrayMatrix4HandlerGL : public EffectParamHandlerGL {
- public:
- explicit EffectParamArrayMatrix4HandlerGL(ParamParamArray* param)
- : param_(param) {
- }
- virtual void SetEffectParam(RendererGL* renderer, CGparameter cg_param) {
- ParamArray* param = param_->value();
- if (param) {
- int size = cgGetArraySize(cg_param, 0);
- if (size != static_cast<int>(param->size())) {
- O3D_ERROR(param->service_locator())
- << "number of params in ParamArray does not match number of params "
- << "needed by shader array";
- } else {
- for (int i = 0; i < size; ++i) {
- Param* untyped_element = param->GetUntypedParam(i);
- // TODO(gman): Make this check happen when building the param cache.
- // To do that would require that ParamParamArray mark it's owner
- // as changed if a Param in it's ParamArray changes.
- if (untyped_element->IsA(ParamMatrix4::GetApparentClass())) {
- CGparameter cg_element = cgGetArrayParameter(cg_param, i);
- SetElement(cg_element, down_cast<ParamMatrix4*>(untyped_element));
- } else {
- O3D_ERROR(param->service_locator())
- << "Param in ParamArray at index " << i
- << " is not a ParamMatrix4";
- }
- }
- }
- }
- }
- void SetElement(CGparameter cg_element, ParamMatrix4* param);
-
- private:
- ParamParamArray* param_;
-};
-
-class EffectParamArraySamplerHandlerGL : public EffectParamHandlerGL {
- public:
- explicit EffectParamArraySamplerHandlerGL(ParamParamArray* param)
- : param_(param) {
- }
- virtual void SetEffectParam(RendererGL* renderer, CGparameter cg_param) {
- ParamArray* param = param_->value();
- if (param) {
- int size = cgGetArraySize(cg_param, 0);
- if (size != static_cast<int>(param->size())) {
- O3D_ERROR(param->service_locator())
- << "number of params in ParamArray does not match number of params "
- << "needed by shader array";
- } else {
- for (int i = 0; i < size; ++i) {
- Param* untyped_element = param->GetUntypedParam(i);
- // TODO(gman): Make this check happen when building the param cache.
- // To do that would require that ParamParamArray mark it's owner
- // as changed if a Param in it's ParamArray changes.
- if (untyped_element->IsA(ParamSampler::GetApparentClass())) {
- CGparameter cg_element = cgGetArrayParameter(cg_param, i);
- ParamSampler* element = down_cast<ParamSampler*>(untyped_element);
- SamplerGL* sampler_gl = down_cast<SamplerGL*>(element->value());
- if (!sampler_gl) {
- // Use the error sampler.
- sampler_gl = down_cast<SamplerGL*>(renderer->error_sampler());
- // If no error texture is set then generate an error.
- if (!renderer->error_texture()) {
- O3D_ERROR(param_->service_locator())
- << "Missing Sampler for ParamSampler '" << param_->name()
- << "' index " << i;
- }
- }
- sampler_gl->SetTextureAndStates(cg_element);
- } else {
- O3D_ERROR(param->service_locator())
- << "Param in ParamArray at index " << i
- << " is not a ParamSampler";
- }
- }
- }
- }
- }
- virtual void ResetEffectParam(RendererGL* renderer, CGparameter cg_param) {
- ParamArray* param = param_->value();
- if (param) {
- int size = cgGetArraySize(cg_param, 0);
- if (size == static_cast<int>(param->size())) {
- for (int i = 0; i < size; ++i) {
- Param* untyped_element = param->GetUntypedParam(i);
- if (untyped_element->IsA(ParamSampler::GetApparentClass())) {
- CGparameter cg_element = cgGetArrayParameter(cg_param, i);
- ParamSampler* element = down_cast<ParamSampler*>(untyped_element);
- SamplerGL* sampler_gl = down_cast<SamplerGL*>(element->value());
- if (!sampler_gl) {
- sampler_gl = down_cast<SamplerGL*>(renderer->error_sampler());
- }
- sampler_gl->ResetTexture(cg_element);
- }
- }
- }
- }
- }
-
- private:
- ParamParamArray* param_;
-};
-
-template<>
-void EffectParamArrayHandlerGL<ParamFloat>::SetElement(
- CGparameter cg_element,
- ParamFloat* param) {
- cgSetParameter1f(cg_element, param->value());
-}
-
-template<>
-void EffectParamArrayHandlerGL<ParamFloat2>::SetElement(
- CGparameter cg_element,
- ParamFloat2* param) {
- Float2 f = param->value();
- cgSetParameter2fv(cg_element, f.GetFloatArray());
-}
-
-template<>
-void EffectParamArrayHandlerGL<ParamFloat3>::SetElement(
- CGparameter cg_element,
- ParamFloat3* param) {
- Float3 f = param->value();
- cgSetParameter3fv(cg_element, f.GetFloatArray());
-}
-
-template<>
-void EffectParamArrayHandlerGL<ParamFloat4>::SetElement(
- CGparameter cg_element,
- ParamFloat4* param) {
- Float4 f = param->value();
- cgSetParameter4fv(cg_element, f.GetFloatArray());
-}
-
-template<>
-void EffectParamArrayMatrix4HandlerGL<false>::SetElement(
- CGparameter cg_element,
- ParamMatrix4* param) {
- // set the data as floats in row major order.
- Matrix4 mat = param->value();
- cgSetMatrixParameterfr(cg_element, &mat[0][0]);
-}
-
-template<>
-void EffectParamArrayMatrix4HandlerGL<true>::SetElement(
- CGparameter cg_element,
- ParamMatrix4* param) {
- // set the data as floats in column major order.
- Matrix4 mat = param->value();
- cgSetMatrixParameterfc(cg_element, &mat[0][0]);
-}
-
-template<>
-void EffectParamArrayHandlerGL<ParamInteger>::SetElement(
- CGparameter cg_element,
- ParamInteger* param) {
- cgSetParameter1i(cg_element, param->value());
-}
-
-template<>
-void EffectParamArrayHandlerGL<ParamBoolean>::SetElement(
- CGparameter cg_element,
- ParamBoolean* param) {
- cgSetParameter1i(cg_element, param->value());
-}
-
-static EffectParamHandlerGL::Ref GetHandlerFromParamAndCgType(
- EffectGL* effect_gl,
- Param *param,
- CGtype cg_type) {
- EffectParamHandlerGL::Ref handler;
- if (param->IsA(ParamParamArray::GetApparentClass())) {
- ParamParamArray* param_param_array = down_cast<ParamParamArray*>(param);
- switch (cg_type) {
- case CG_FLOAT:
- case CG_FLOAT1:
- handler = EffectParamHandlerGL::Ref(
- new EffectParamArrayHandlerGL<ParamFloat>(param_param_array));
- break;
- case CG_FLOAT2:
- handler = EffectParamHandlerGL::Ref(
- new EffectParamArrayHandlerGL<ParamFloat2>(param_param_array));
- break;
- case CG_FLOAT3:
- handler = EffectParamHandlerGL::Ref(
- new EffectParamArrayHandlerGL<ParamFloat3>(param_param_array));
- break;
- case CG_FLOAT4:
- handler = EffectParamHandlerGL::Ref(
- new EffectParamArrayHandlerGL<ParamFloat4>(param_param_array));
- break;
- case CG_FLOAT4x4:
- if (effect_gl->matrix_load_order() == Effect::COLUMN_MAJOR) {
- handler = EffectParamHandlerGL::Ref(
- new EffectParamArrayMatrix4HandlerGL<true>(param_param_array));
- } else {
- handler = EffectParamHandlerGL::Ref(
- new EffectParamArrayMatrix4HandlerGL<false>(param_param_array));
- }
- break;
- case CG_INT:
- case CG_INT1:
- handler = EffectParamHandlerGL::Ref(
- new EffectParamArrayHandlerGL<ParamInteger>(param_param_array));
- break;
- case CG_BOOL:
- case CG_BOOL1:
- handler = EffectParamHandlerGL::Ref(
- new EffectParamArrayHandlerGL<ParamBoolean>(param_param_array));
- break;
- case CG_SAMPLER:
- case CG_SAMPLER1D:
- case CG_SAMPLER2D:
- case CG_SAMPLER3D:
- case CG_SAMPLERCUBE:
- handler = EffectParamHandlerGL::Ref(
- new EffectParamArraySamplerHandlerGL(param_param_array));
- break;
- default:
- break;
- }
- } else if (param->IsA(ParamMatrix4::GetApparentClass())) {
- if (cg_type == CG_FLOAT4x4) {
- if (effect_gl->matrix_load_order() == Effect::COLUMN_MAJOR) {
- // set the data as floats in column major order.
- handler = EffectParamHandlerGL::Ref(
- new EffectParamHandlerGLMatrixColumns(
- down_cast<ParamMatrix4*>(param)));
- } else {
- // set the data as floats in row major order.
- handler = EffectParamHandlerGL::Ref(
- new EffectParamHandlerGLMatrixRows(
- down_cast<ParamMatrix4*>(param)));
- }
- }
- } else if (param->IsA(ParamFloat::GetApparentClass())) {
- if (cg_type == CG_FLOAT ||
- cg_type == CG_FLOAT1) {
- handler = EffectParamHandlerGL::Ref(
- new TypedEffectParamHandlerGL<ParamFloat>(
- down_cast<ParamFloat*>(param)));
- }
- } else if (param->IsA(ParamFloat2::GetApparentClass())) {
- if (cg_type == CG_FLOAT2) {
- handler = EffectParamHandlerGL::Ref(
- new TypedEffectParamHandlerGL<ParamFloat2>(
- down_cast<ParamFloat2*>(param)));
- }
- } else if (param->IsA(ParamFloat3::GetApparentClass())) {
- if (cg_type == CG_FLOAT3) {
- handler = EffectParamHandlerGL::Ref(
- new TypedEffectParamHandlerGL<ParamFloat3>(
- down_cast<ParamFloat3*>(param)));
- }
- } else if (param->IsA(ParamFloat4::GetApparentClass())) {
- if (cg_type == CG_FLOAT4) {
- handler = EffectParamHandlerGL::Ref(
- new TypedEffectParamHandlerGL<ParamFloat4>(
- down_cast<ParamFloat4*>(param)));
- }
- } else if (param->IsA(ParamInteger::GetApparentClass())) {
- if (cg_type == CG_INT || cg_type == CG_INT1) {
- handler = EffectParamHandlerGL::Ref(
- new TypedEffectParamHandlerGL<ParamInteger>(
- down_cast<ParamInteger*>(param)));
- }
- } else if (param->IsA(ParamBoolean::GetApparentClass())) {
- if (cg_type == CG_BOOL || cg_type == CG_BOOL1) {
- handler = EffectParamHandlerGL::Ref(
- new TypedEffectParamHandlerGL<ParamBoolean>(
- down_cast<ParamBoolean*>(param)));
- }
- } else if (param->IsA(ParamSampler::GetApparentClass())) {
- if (cg_type == CG_SAMPLER ||
- cg_type == CG_SAMPLER1D ||
- cg_type == CG_SAMPLER2D ||
- cg_type == CG_SAMPLER3D ||
- cg_type == CG_SAMPLERCUBE) {
- handler = EffectParamHandlerGL::Ref(
- new EffectParamHandlerForSamplersGL(
- down_cast<ParamSampler*>(param)));
- }
- }
- return handler;
-}
-
-// Local helper function for scanning varying Cg parameters of a
-// program or effect and recording their entries into the varying map.
-static void ScanVaryingParameters(CGprogram program,
- CGenum name_space,
- ParamCacheGL* param_cache_gl) {
- CGparameter cg_param = cgGetFirstLeafParameter(program, name_space);
- for (; cg_param; cg_param = cgGetNextLeafParameter(cg_param)) {
- if (!cgIsParameterReferenced(cg_param))
- continue;
- CGenum variability = cgGetParameterVariability(cg_param);
- CGenum direction = cgGetParameterDirection(cg_param);
- if (variability == CG_VARYING && direction == CG_IN) {
- // Add a link between the parameter and no stream (index -1)
- // NOTE: Stream indexes will be set later in
- // InsertMissingVertexStreams().
- if (param_cache_gl->varying_map().find(cg_param) ==
- param_cache_gl->varying_map().end()) {
- const char* cg_name = cgGetParameterName(cg_param);
- param_cache_gl->varying_map().insert(std::make_pair(cg_param, -1));
- DLOG(INFO) << "ElementGL Found CG_VARYING \""
- << cg_name << " : "
- << cgGetParameterSemantic(cg_param) << "\"";
- }
- }
- }
-}
-
-// Local helper function for scanning uniform Cg parameters of a
-// program or effect and recording their entries into the parameter maps.
-static void ScanUniformParameters(SemanticManager* semantic_manager,
- Renderer* renderer,
- CGprogram program,
- CGenum name_space,
- ParamCacheGL* param_cache_gl,
- const ParamObjectList& param_objects,
- EffectGL* effect_gl) {
- CGparameter cg_param = cgGetFirstParameter(program, name_space);
- for (; cg_param; cg_param = cgGetNextParameter(cg_param)) {
- if (!cgIsParameterReferenced(cg_param))
- continue;
- CGenum direction = cgGetParameterDirection(cg_param);
- if (direction != CG_IN)
- continue;
- CGtype cg_type = cgGetParameterType(cg_param);
- CGenum variability = cgGetParameterVariability(cg_param);
- const char* cg_name = cgGetParameterName(cg_param);
-
- if (variability == CG_UNIFORM) {
- // We have a CGparameter to add, find a Param that matches it by name.
- if (cg_type == CG_TEXTURE) {
- // CG_TEXTURE objects are handled by CG_SAMPLER objects.
- continue;
- }
-
- // TODO(o3d): The following code block should be removed once we start
- // creating sampler params for all effects coming in via the importer. For
- // the time being, we keep an extra ParamTexture that does the job it used
- // to do. If we are using a ParamSampler on the object then the
- // ParamTexture will have no value and therefore its handler will have no
- // side-effects.
- if (cg_type == CG_SAMPLER ||
- cg_type == CG_SAMPLER1D ||
- cg_type == CG_SAMPLER2D ||
- cg_type == CG_SAMPLER3D ||
- cg_type == CG_SAMPLERCUBE) {
- // Uniform is a Sampler object. Find the CG_TEXTURE object
- // assigned to the CG_SAMPLER, then find a Param object with the
- // same name as the CG_TEXTURE. This is the tricky bit!
- if (param_cache_gl->sampler_map().find(cg_param) ==
- param_cache_gl->sampler_map().end()) {
- ParamTexture* param =
- effect_gl->GetTextureParamFromCgSampler(cg_param,
- param_objects);
- if (param) {
- param_cache_gl->sampler_map().insert(std::make_pair(cg_param,
- param));
- }
- }
- }
-
- // Find a Param of the same name, and record the link.
- if (param_cache_gl->uniform_map().find(cg_param) ==
- param_cache_gl->uniform_map().end()) {
- const ObjectBase::Class *sem_class = NULL;
- // Try looking by SAS class name.
- const char* cg_semantic = cgGetParameterSemantic(cg_param);
- if (cg_semantic != NULL && cg_semantic[0] != '\0') {
- // NOTE: this semantic is not the regularised profile semantic
- // output from the CGC compiler but the actual user supplied
- // semantic from the shader source code, so this match is valid.
- sem_class = semantic_manager->LookupSemantic(cg_semantic);
- }
- EffectParamHandlerGL::Ref handler;
- // Look through all the param objects to find a matching param.
- unsigned last = param_objects.size() - 1;
- for (unsigned int i = 0; i < param_objects.size(); ++i) {
- ParamObject *param_object = param_objects[i];
- Param *param = param_object->GetUntypedParam(cg_name);
- if (!param && sem_class) {
- param = param_object->GetUntypedParam(sem_class->name());
- }
- if (!param) {
- // If this is the last param object and we didn't find a matching
- // param then if it's a sampler use the error sampler
- if (i == last) {
- if (cg_type == CG_SAMPLER ||
- cg_type == CG_SAMPLER1D ||
- cg_type == CG_SAMPLER2D ||
- cg_type == CG_SAMPLER3D ||
- cg_type == CG_SAMPLERCUBE) {
- param =
- renderer->error_param_sampler();
- }
- }
- if (!param) {
- continue;
- }
- }
- if (cg_type == CG_ARRAY) {
- // Substitute the first element's type for our type.
- cg_type = cgGetParameterType(cgGetArrayParameter(cg_param, 0));
- }
- handler = GetHandlerFromParamAndCgType(effect_gl, param, cg_type);
- if (!handler.IsNull()) {
- param_cache_gl->uniform_map().insert(
- std::make_pair(cg_param, handler));
- DLOG(INFO) << "ElementGL Matched CG_PARAMETER \""
- << cg_name << "\" to Param \""
- << param->name() << "\" from \""
- << param_object->name() << "\"";
- break;
- } else {
- // We found a param, but it didn't match the type. keep looking.
- DLOG(ERROR) << "ElementGL Param \""
- << param->name() << "\" type \""
- << param->GetClassName() << "\" from \""
- << param_object->name()
- << "\" does not match CG_PARAMETER \""
- << cg_name << "\"";
- }
- }
- if (handler.IsNull()) {
- DLOG(ERROR) << "No matching Param for CG_PARAMETER \""
- << cg_name << "\"";
- }
- }
- }
- }
-}
-
-static void DoScanCgEffectParameters(SemanticManager* semantic_manager,
- Renderer* renderer,
- ParamCacheGL* param_cache_gl,
- CGprogram cg_vertex,
- CGprogram cg_fragment,
- EffectGL* effect_gl,
- const ParamObjectList& param_objects) {
- ScanVaryingParameters(cg_vertex, CG_PROGRAM, param_cache_gl);
- ScanVaryingParameters(cg_vertex, CG_GLOBAL, param_cache_gl);
- ScanUniformParameters(semantic_manager,
- renderer,
- cg_vertex,
- CG_PROGRAM,
- param_cache_gl,
- param_objects,
- effect_gl);
- ScanUniformParameters(semantic_manager,
- renderer,
- cg_vertex,
- CG_GLOBAL,
- param_cache_gl,
- param_objects,
- effect_gl);
- // Do not record varying inputs for a fragment program
- ScanUniformParameters(semantic_manager,
- renderer,
- cg_fragment,
- CG_PROGRAM,
- param_cache_gl,
- param_objects,
- effect_gl);
- ScanUniformParameters(semantic_manager,
- renderer,
- cg_fragment,
- CG_GLOBAL,
- param_cache_gl,
- param_objects,
- effect_gl);
-}
-
-// Search the leaf parameters of a CGeffect and it's shaders for parameters
-// using cgGetFirstEffectParameter() / cgGetFirstLeafParameter() /
-// cgGetNextLeafParameter(). Add the CGparameters found to the parameter
-// maps on the DrawElement.
-void ParamCacheGL::ScanCgEffectParameters(CGprogram cg_vertex,
- CGprogram cg_fragment,
- ParamObject* draw_element,
- ParamObject* element,
- Material* material,
- ParamObject* override) {
- DLOG(INFO) << "DrawElementGL ScanCgEffectParameters";
- DLOG_ASSERT(material);
- DLOG_ASSERT(draw_element);
- DLOG_ASSERT(element);
- EffectGL* effect_gl = static_cast<EffectGL*>(material->effect());
- DLOG_ASSERT(effect_gl);
- if (cg_vertex == NULL) {
- DLOG(ERROR) << "Can't scan an empty Vertex Program for Cg Parameters.";
- return;
- }
- if (cg_fragment == NULL) {
- DLOG(ERROR) << "Can't scan an empty Fragment Program for Cg Parameters.";
- return;
- }
-
- uniform_map_.clear();
- varying_map_.clear();
- sampler_map_.clear();
- ParamObjectList param_object_list;
- param_object_list.push_back(override);
- param_object_list.push_back(draw_element);
- param_object_list.push_back(element);
- param_object_list.push_back(material);
- param_object_list.push_back(effect_gl);
- param_object_list.push_back(semantic_manager_->sas_param_object());
- DoScanCgEffectParameters(semantic_manager_,
- renderer_,
- this,
- cg_vertex,
- cg_fragment,
- effect_gl,
- param_object_list);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/gl/param_cache_gl.h b/o3d/core/cross/gl/param_cache_gl.h
deleted file mode 100644
index 52731cd..0000000
--- a/o3d/core/cross/gl/param_cache_gl.h
+++ /dev/null
@@ -1,103 +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 declaration of the ParamCacheGL class.
-
-#ifndef O3D_CORE_CROSS_GL_PARAM_CACHE_GL_H_
-#define O3D_CORE_CROSS_GL_PARAM_CACHE_GL_H_
-
-#include <map>
-#include "core/cross/gl/gl_headers.h"
-#include "core/cross/param_cache.h"
-#include "core/cross/gl/effect_gl.h"
-
-namespace o3d {
-
-class ParamTexture;
-class SemanticManager;
-
-class ParamCacheGL : public ParamCache {
- public:
- ParamCacheGL(SemanticManager* semantic_manager, Renderer* renderer);
-
- typedef std::map<CGparameter, int> VaryingParameterMap;
- typedef std::map<CGparameter, EffectParamHandlerGL::Ref> UniformParameterMap;
- typedef std::map<CGparameter, ParamTexture*> SamplerParameterMap;
-
- // Overridden from ParamCache.
- virtual void UpdateCache(Effect* effect,
- DrawElement* draw_element,
- Element* element,
- Material* material,
- ParamObject* override);
-
- VaryingParameterMap& varying_map() { return varying_map_; }
- UniformParameterMap& uniform_map() { return uniform_map_; }
- SamplerParameterMap& sampler_map() { return sampler_map_; }
-
- protected:
- // Overridden from ParamCache
- // Validates platform specific information about the effect.
- virtual bool ValidateEffect(Effect* effect);
-
- private:
-
- SemanticManager* semantic_manager_;
- Renderer* renderer_;
-
- // Records the last two shaders used on this cache, allowing us to rescan the
- // shader parameters if the user changes the shader on an active cache.
- CGprogram last_vertex_program_;
- CGprogram last_fragment_program_;
-
- // Search the leaf parameters of a CGeffect and it's shaders for
- // parameters using cgGetFirstEffectParameter() /
- // cgGetFirstLeafParameter() / cgGetNextLeafParameter(). Add the
- // CGparameters found to the parameter maps on the DrawElement.
- void ScanCgEffectParameters(CGprogram cg_vertex,
- CGprogram fragment,
- ParamObject* draw_element,
- ParamObject* element,
- Material* material,
- ParamObject* override);
-
- // A map of varying CGparameter to Stream index.
- VaryingParameterMap varying_map_;
- // A map of uniform CGparameter to Param objects.
- UniformParameterMap uniform_map_;
- // A map of uniform CG_SAMPLER CGparameters to ParamTexture objects.
- // TODO: remove this (OLD path for textures).
- SamplerParameterMap sampler_map_;
-};
-} // o3d
-
-#endif // O3D_CORE_CROSS_GL_PARAM_CACHE_GL_H_
diff --git a/o3d/core/cross/gl/primitive_gl.cc b/o3d/core/cross/gl/primitive_gl.cc
deleted file mode 100644
index 5c7eb73..0000000
--- a/o3d/core/cross/gl/primitive_gl.cc
+++ /dev/null
@@ -1,258 +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 definition of PrimitiveGL.
-
-#include <algorithm>
-
-#include "core/cross/stream.h"
-#include "core/cross/error.h"
-#include "core/cross/gl/buffer_gl.h"
-#include "core/cross/gl/effect_gl.h"
-#include "core/cross/gl/primitive_gl.h"
-#include "core/cross/gl/renderer_gl.h"
-#include "core/cross/gl/draw_element_gl.h"
-#include "core/cross/gl/stream_bank_gl.h"
-#include "core/cross/gl/utils_gl-inl.h"
-#include "Cg/cgGL.h"
-
-// Someone defines min, conflicting with std::min
-#ifdef min
-#undef min
-#endif
-
-namespace o3d {
-
-// Number of times to log a repeated event before giving up.
-const int kNumLoggedEvents = 5;
-
-// PrimitiveGL functions -------------------------------------------------------
-
-PrimitiveGL::PrimitiveGL(ServiceLocator* service_locator)
- : Primitive(service_locator) {
- DLOG(INFO) << "PrimitiveGL Construct";
-}
-
-PrimitiveGL::~PrimitiveGL() {
- DLOG(INFO) << "PrimitiveGL Destruct";
-}
-
-// Binds the vertex and index streams required to draw the shape. If the
-// vertex or fragment programs have changed since the last time this method
-// was called (or it's the first time it's getting called) then it forces
-// an update of the mapping between the Shape Param's and the shader parameters
-// and also fills in for any missing streams.
-void PrimitiveGL::PlatformSpecificRender(Renderer* renderer,
- DrawElement* draw_element,
- Material* material,
- ParamObject* override,
- ParamCache* param_cache) {
- DLOG_ASSERT(material);
- DLOG_ASSERT(draw_element);
- DLOG_ASSERT(param_cache);
- DLOG_FIRST_N(INFO, kNumLoggedEvents) << "PrimitiveGL Draw \""
- << draw_element->name() << "\"";
- DrawElementGL* draw_element_gl = down_cast<DrawElementGL*>(draw_element);
- EffectGL* effect_gl = down_cast<EffectGL*>(material->effect());
- DLOG_ASSERT(effect_gl);
- StreamBankGL* stream_bank_gl = down_cast<StreamBankGL*>(stream_bank());
- DLOG_ASSERT(stream_bank_gl);
-
- ParamCacheGL* param_cache_gl = down_cast<ParamCacheGL*>(param_cache);
- ParamCacheGL::VaryingParameterMap& varying_map =
- param_cache_gl->varying_map();
-
- // If this PrimitiveGL has an effect we haven't seen before (or it's the first
- // time through), initalize the parameter lists before drawing with it.
- if (effect_gl->cg_vertex_program() && effect_gl->cg_fragment_program()) {
- // Set up the current CGeffect.
- if (!param_cache_gl->ValidateAndCacheParams(effect_gl,
- draw_element_gl,
- this,
- stream_bank_gl,
- material,
- override)) {
- Stream::Semantic missing_semantic;
- int missing_semnatic_index;
- if (!stream_bank_gl->CheckForMissingVertexStreams(
- varying_map,
- &missing_semantic,
- &missing_semnatic_index)) {
- param_cache_gl->ClearParamCache();
- O3D_ERROR(service_locator())
- << "Required Stream "
- << Stream::GetSemanticDescription(missing_semantic) << ":"
- << missing_semnatic_index << " missing on Primitive '" << name()
- << "' using Material '" << material->name()
- << "' with Effect '" << effect_gl->name() << "'";
- return;
- }
- }
- } else {
- O3D_ERROR(service_locator())
- << "No CG effect provided in Effect \""
- << effect_gl->name() << "\" used by Material \""
- << material->name() << "\" in Shape \""
- << draw_element_gl->name() << "\". Drawing nothing.";
- return;
- }
-
- // Make sure our streams are up to date (skinned, etc..)
- stream_bank_gl->UpdateStreams();
-
- unsigned int max_vertices;
- if (!stream_bank_gl->BindStreamsForRendering(varying_map, &max_vertices)) {
- return;
- }
-
- // TODO: move these checks at 'set' time instead of draw time.
-
- bool draw = true;
- if (number_vertices_ > max_vertices) {
- O3D_ERROR(service_locator())
- << "Trying to draw with " << number_vertices_
- << " vertices when there are only " << max_vertices
- << " available in the buffers. Skipping primitive.";
- draw = false;
- }
-
- unsigned int index_count;
-
- if (!Primitive::GetIndexCount(primitive_type_,
- number_primitives_,
- &index_count)) {
- O3D_ERROR(service_locator())
- << "Unknown Primitive Type in GetIndexCount: "
- << primitive_type_ << ". Skipping primitive "
- << name();
- draw = false;
- }
-
- if (indexed()) {
- // Re-bind the index buffer for this shape
- IndexBufferGL *ibuffer = down_cast<IndexBufferGL*>(index_buffer());
-
- unsigned int max_indices = ibuffer->num_elements();
-
- if (index_count > max_indices) {
- O3D_ERROR(service_locator())
- << "Trying to draw with " << index_count
- << " indices when only " << max_indices
- << " are available in the buffer. Skipping shape.";
- draw = false;
- }
-
- // TODO: Also check that indices in the index buffer are less than
- // max_vertices_. Needs support from the index buffer (scan indices on
- // Unlock).
-
- glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, ibuffer->gl_buffer());
- }
-
- // Set up the shaders in this drawcall from the Effect.
- effect_gl->PrepareForDraw(param_cache_gl);
-
- // Do the drawcall.
- GLenum gl_primitive_type = GL_NONE;
- switch (primitive_type_) {
- case Primitive::POINTLIST : {
- if (indexed()) {
- O3D_ERROR(service_locator())
- << "POINTLIST unsupported for indexed primitives for primitive "
- << name();
- draw = false;
- } else {
- gl_primitive_type = GL_POINTS;
- }
- break;
- }
- case Primitive::LINELIST : {
- DLOG_FIRST_N(INFO, kNumLoggedEvents)
- << "Draw " << number_primitives_ << " GL_LINES";
- gl_primitive_type = GL_LINES;
- break;
- }
- case Primitive::LINESTRIP : {
- DLOG_FIRST_N(INFO, kNumLoggedEvents)
- << "Draw " << number_primitives_ << " GL_LINE_STRIP";
- gl_primitive_type = GL_LINE_STRIP;
- break;
- }
- case Primitive::TRIANGLELIST : {
- DLOG_FIRST_N(INFO, kNumLoggedEvents)
- << "Draw " << number_primitives_ << " GL_TRIANGLES";
- gl_primitive_type = GL_TRIANGLES;
- break;
- }
- case Primitive::TRIANGLESTRIP : {
- DLOG_FIRST_N(INFO, kNumLoggedEvents)
- << "Draw " << number_primitives_ << " GL_TRIANGLE_STRIP";
- gl_primitive_type = GL_TRIANGLE_STRIP;
- break;
- }
- case Primitive::TRIANGLEFAN : {
- DLOG_FIRST_N(INFO, kNumLoggedEvents)
- << "Draw " << number_primitives_ << " GL_TRIANGLE_FAN";
- gl_primitive_type = GL_TRIANGLE_FAN;
- break;
- }
- default : {
- DLOG(ERROR) << "Unknown Primitive Type in Primitive: "
- << primitive_type_;
- draw = false;
- }
- }
- if (draw) {
- DCHECK_NE(gl_primitive_type, static_cast<unsigned int>(GL_NONE));
- renderer->AddPrimitivesRendered(number_primitives_);
- if (indexed())
- glDrawElements(gl_primitive_type,
- index_count,
- GL_UNSIGNED_INT,
- BUFFER_OFFSET(start_index() * sizeof(uint32))); // NOLINT
- else
- glDrawArrays(gl_primitive_type, start_index(), index_count);
- }
-
- // Clean up the shaders.
- effect_gl->PostDraw(param_cache_gl);
-
- // Disable the vertex attribute states set earlier.
- for (ParamCacheGL::VaryingParameterMap::iterator i = varying_map.begin();
- i != varying_map.end();
- ++i) {
- cgGLDisableClientState(i->first);
- }
- CHECK_GL_ERROR();
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/gl/primitive_gl.h b/o3d/core/cross/gl/primitive_gl.h
deleted file mode 100644
index eadf8f8..0000000
--- a/o3d/core/cross/gl/primitive_gl.h
+++ /dev/null
@@ -1,63 +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 declaration of the PrimitiveGL class.
-
-#ifndef O3D_CORE_CROSS_GL_PRIMITIVE_GL_H_
-#define O3D_CORE_CROSS_GL_PRIMITIVE_GL_H_
-
-#include <map>
-#include "core/cross/primitive.h"
-#include "core/cross/gl/param_cache_gl.h"
-
-namespace o3d {
-
-// PrimitiveGL is the OpenGL implementation of the Primitive. It provides the
-// necessary interfaces for setting the geometry streams on the Primitive.
-class PrimitiveGL : public Primitive {
- public:
- explicit PrimitiveGL(ServiceLocator* service_locator);
- virtual ~PrimitiveGL();
-
- protected:
- // Overridden from Primitive.
- virtual void PlatformSpecificRender(Renderer* renderer,
- DrawElement* draw_element,
- Material* material,
- ParamObject* override,
- ParamCache* param_cache);
-
- private:
-};
-} // o3d
-
-#endif // O3D_CORE_CROSS_GL_PRIMITIVE_GL_H_
diff --git a/o3d/core/cross/gl/render_surface_gl.cc b/o3d/core/cross/gl/render_surface_gl.cc
deleted file mode 100644
index f12718c..0000000
--- a/o3d/core/cross/gl/render_surface_gl.cc
+++ /dev/null
@@ -1,125 +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 RenderSurfaceGL and
-// RenderDepthStencilSurfaceGL.
-
-#include "core/cross/gl/render_surface_gl.h"
-#include "core/cross/gl/utils_gl-inl.h"
-#include "core/cross/renderer.h"
-
-namespace o3d {
-
-RenderSurfaceGL::RenderSurfaceGL(ServiceLocator *service_locator,
- int width,
- int height,
- GLenum cube_face,
- int mip_level,
- Texture *texture)
- : RenderSurface(service_locator, width, height, texture),
- cube_face_(cube_face),
- mip_level_(mip_level) {
- DCHECK(texture);
-}
-
-RenderSurfaceGL::~RenderSurfaceGL() {
-}
-
-bool RenderSurfaceGL::PlatformSpecificGetIntoBitmap(Bitmap::Ref bitmap) const {
- Renderer* renderer = service_locator()->GetService<Renderer>();
- DCHECK(renderer);
- DCHECK(bitmap->width() == static_cast<unsigned int>(clip_width()) &&
- bitmap->height() == static_cast<unsigned int>(clip_height()) &&
- bitmap->num_mipmaps() == 1 &&
- bitmap->format() == Texture::ARGB8);
-
- const RenderSurface* old_render_surface;
- const RenderDepthStencilSurface* old_depth_surface;
- bool old_is_back_buffer;
-
- renderer->GetRenderSurfaces(&old_render_surface, &old_depth_surface,
- &old_is_back_buffer);
- renderer->SetRenderSurfaces(this, NULL, false);
-
- ::glReadPixels(0, 0, clip_width(), clip_height(), GL_BGRA, GL_UNSIGNED_BYTE,
- bitmap->image_data());
-
- renderer->SetRenderSurfaces(old_render_surface, old_depth_surface,
- old_is_back_buffer);
-
- return true;
-}
-
-RenderDepthStencilSurfaceGL::RenderDepthStencilSurfaceGL(
- ServiceLocator *service_locator,
- int width,
- int height)
- : RenderDepthStencilSurface(service_locator, width, height) {
-
- // If packed depth stencil is supported, create only one buffer for both
- // depth and stencil.
- if (GLEW_EXT_packed_depth_stencil) {
- glGenRenderbuffersEXT(1, render_buffers_);
- glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, render_buffers_[0]);
- glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT,
- GL_DEPTH24_STENCIL8_EXT,
- width,
- height);
- CHECK_GL_ERROR();
- render_buffers_[1] = render_buffers_[0];
- } else {
- glGenRenderbuffersEXT(2, render_buffers_);
- glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, render_buffers_[0]);
- glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT,
- GL_DEPTH_COMPONENT24,
- width,
- height);
- CHECK_GL_ERROR();
-
- glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, render_buffers_[1]);
- glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT,
- GL_STENCIL_INDEX8_EXT,
- width,
- height);
- CHECK_GL_ERROR();
- }
-}
-
-RenderDepthStencilSurfaceGL::~RenderDepthStencilSurfaceGL() {
- if (GLEW_EXT_packed_depth_stencil) {
- glDeleteRenderbuffersEXT(1, render_buffers_);
- } else {
- glDeleteRenderbuffersEXT(2, render_buffers_);
- }
-}
-
-} // end namespace o3d
diff --git a/o3d/core/cross/gl/render_surface_gl.h b/o3d/core/cross/gl/render_surface_gl.h
deleted file mode 100644
index 254a142..0000000
--- a/o3d/core/cross/gl/render_surface_gl.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.
- */
-
-
-// This file contains the declarations for RenderSurfaceGL and
-// RenderDepthStencilSurfaceGL.
-
-#ifndef O3D_CORE_CROSS_GL_RENDER_SURFACE_GL_H_
-#define O3D_CORE_CROSS_GL_RENDER_SURFACE_GL_H_
-
-#include "core/cross/gl/gl_headers.h"
-#include "core/cross/render_surface.h"
-#include "core/cross/texture.h"
-
-namespace o3d {
-
-class RenderSurfaceGL : public RenderSurface {
- public:
- typedef SmartPointer<RenderSurfaceGL> Ref;
-
- // Constructs a RenderSurfaceGL instance associated with the texture argument.
- // Parameters:
- // service_locator: Service locator for the instance.
- // width: The width of the surface, in pixels.
- // height: The height of the surface, in pixels.
- // cube_face: The face of the cube texture to which the surface is to be
- // associated. NOTE: If the texture is a 2d texture, then the value of
- // this argument is irrelevent.
- // mip_level: The mip-level of the texture to associate with the surface.
- // texture: The texture to associate with the surface.
- RenderSurfaceGL(ServiceLocator *service_locator,
- int width,
- int height,
- GLenum cube_face,
- int mip_level,
- Texture *texture);
- virtual ~RenderSurfaceGL();
-
- GLenum cube_face() const {
- return cube_face_;
- }
-
- int mip_level() const {
- return mip_level_;
- }
-
- protected:
- // The platform specific part of GetIntoBitmap.
- virtual bool PlatformSpecificGetIntoBitmap(Bitmap::Ref bitmap) const;
-
- private:
- GLenum cube_face_;
- int mip_level_;
- DISALLOW_COPY_AND_ASSIGN(RenderSurfaceGL);
-};
-
-class RenderDepthStencilSurfaceGL : public RenderDepthStencilSurface {
- public:
- typedef SmartPointer<RenderDepthStencilSurfaceGL> Ref;
-
- RenderDepthStencilSurfaceGL(ServiceLocator *service_locator,
- int width,
- int height);
- virtual ~RenderDepthStencilSurfaceGL();
-
- GLuint depth_buffer() const {
- return render_buffers_[0];
- }
-
- GLuint stencil_buffer() const {
- return render_buffers_[1];
- }
- private:
- // Handles to the depth and stencil render-buffers, respectively.
- GLuint render_buffers_[2];
- DISALLOW_COPY_AND_ASSIGN(RenderDepthStencilSurfaceGL);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GL_RENDER_SURFACE_GL_H_
diff --git a/o3d/core/cross/gl/renderer_gl.cc b/o3d/core/cross/gl/renderer_gl.cc
deleted file mode 100644
index 8c42b2a..0000000
--- a/o3d/core/cross/gl/renderer_gl.cc
+++ /dev/null
@@ -1,1603 +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 definition of the RendererGL class that
-// implements the abstract Renderer API using OpenGL and the Cg
-// Runtime.
-
-
-#include "core/cross/gl/renderer_gl.h"
-
-#include "core/cross/client_info.h"
-#include "core/cross/error.h"
-#include "core/cross/gl/buffer_gl.h"
-#include "core/cross/gl/draw_element_gl.h"
-#include "core/cross/gl/effect_gl.h"
-#include "core/cross/gl/param_cache_gl.h"
-#include "core/cross/gl/primitive_gl.h"
-#include "core/cross/gl/render_surface_gl.h"
-#include "core/cross/gl/sampler_gl.h"
-#include "core/cross/gl/stream_bank_gl.h"
-#include "core/cross/gl/texture_gl.h"
-#include "core/cross/gl/utils_gl-inl.h"
-#include "core/cross/gl/utils_gl.h"
-#include "core/cross/material.h"
-#include "core/cross/semantic_manager.h"
-#include "core/cross/features.h"
-#include "core/cross/shape.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-namespace {
-
-GLenum ConvertCmpFunc(State::Comparison cmp) {
- switch (cmp) {
- case State::CMP_ALWAYS:
- return GL_ALWAYS;
- case State::CMP_NEVER:
- return GL_NEVER;
- case State::CMP_LESS:
- return GL_LESS;
- case State::CMP_GREATER:
- return GL_GREATER;
- case State::CMP_LEQUAL:
- return GL_LEQUAL;
- case State::CMP_GEQUAL:
- return GL_GEQUAL;
- case State::CMP_EQUAL:
- return GL_EQUAL;
- case State::CMP_NOTEQUAL:
- return GL_NOTEQUAL;
- default:
- break;
- }
- return GL_ALWAYS;
-}
-
-GLenum ConvertFillMode(State::Fill mode) {
- switch (mode) {
- case State::POINT:
- return GL_POINT;
- case State::WIREFRAME:
- return GL_LINE;
- case State::SOLID:
- return GL_FILL;
- default:
- break;
- }
- return GL_FILL;
-}
-
-GLenum ConvertBlendFunc(State::BlendingFunction blend_func) {
- switch (blend_func) {
- case State::BLENDFUNC_ZERO:
- return GL_ZERO;
- case State::BLENDFUNC_ONE:
- return GL_ONE;
- case State::BLENDFUNC_SOURCE_COLOR:
- return GL_SRC_COLOR;
- case State::BLENDFUNC_INVERSE_SOURCE_COLOR:
- return GL_ONE_MINUS_SRC_COLOR;
- case State::BLENDFUNC_SOURCE_ALPHA:
- return GL_SRC_ALPHA;
- case State::BLENDFUNC_INVERSE_SOURCE_ALPHA:
- return GL_ONE_MINUS_SRC_ALPHA;
- case State::BLENDFUNC_DESTINATION_ALPHA:
- return GL_DST_ALPHA;
- case State::BLENDFUNC_INVERSE_DESTINATION_ALPHA:
- return GL_ONE_MINUS_DST_ALPHA;
- case State::BLENDFUNC_DESTINATION_COLOR:
- return GL_DST_COLOR;
- case State::BLENDFUNC_INVERSE_DESTINATION_COLOR:
- return GL_ONE_MINUS_DST_COLOR;
- case State::BLENDFUNC_SOURCE_ALPHA_SATUTRATE:
- return GL_SRC_ALPHA_SATURATE;
- default:
- break;
- }
- return GL_ONE;
-}
-
-GLenum ConvertBlendEquation(State::BlendingEquation blend_equation) {
- switch (blend_equation) {
- case State::BLEND_ADD:
- return GL_FUNC_ADD;
- case State::BLEND_SUBTRACT:
- return GL_FUNC_SUBTRACT;
- case State::BLEND_REVERSE_SUBTRACT:
- return GL_FUNC_REVERSE_SUBTRACT;
- case State::BLEND_MIN:
- return GL_MIN;
- case State::BLEND_MAX:
- return GL_MAX;
- default:
- break;
- }
- return GL_FUNC_ADD;
-}
-
-GLenum ConvertStencilOp(State::StencilOperation stencil_func) {
- switch (stencil_func) {
- case State::STENCIL_KEEP:
- return GL_KEEP;
- case State::STENCIL_ZERO:
- return GL_ZERO;
- case State::STENCIL_REPLACE:
- return GL_REPLACE;
- case State::STENCIL_INCREMENT_SATURATE:
- return GL_INCR;
- case State::STENCIL_DECREMENT_SATURATE:
- return GL_DECR;
- case State::STENCIL_INVERT:
- return GL_INVERT;
- case State::STENCIL_INCREMENT:
- return GL_INCR_WRAP;
- case State::STENCIL_DECREMENT:
- return GL_DECR_WRAP;
- default:
- break;
- }
- return GL_KEEP;
-}
-
-// Helper routine that will bind the surfaces stored in the RenderSurface and
-// RenderDepthStencilSurface arguments to the current OpenGL context.
-// Returns true upon success.
-// Note: This routine assumes that a frambuffer object is presently bound
-// to the context.
-bool InstallFramebufferObjects(const RenderSurface* surface,
- const RenderDepthStencilSurface* surface_depth) {
-#ifndef NDEBUG
- GLint bound_framebuffer;
- ::glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, &bound_framebuffer);
- DCHECK(bound_framebuffer != 0);
-#endif
-
- // Reset the bound attachments to the current framebuffer object.
- ::glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT,
- GL_COLOR_ATTACHMENT0_EXT,
- GL_RENDERBUFFER_EXT,
- 0);
-
- ::glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT,
- GL_DEPTH_ATTACHMENT_EXT,
- GL_RENDERBUFFER_EXT,
- 0);
-
- ::glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT,
- GL_STENCIL_ATTACHMENT_EXT,
- GL_RENDERBUFFER_EXT,
- 0);
-
- if (surface) {
- const RenderSurfaceGL *gl_surface =
- down_cast<const RenderSurfaceGL*>(surface);
- Texture *texture = gl_surface->texture();
- GLuint handle = static_cast<GLuint>(reinterpret_cast<intptr_t>(
- texture->GetTextureHandle()));
- if (texture->IsA(Texture2D::GetApparentClass())) {
- ::glFramebufferTexture2DEXT(
- GL_FRAMEBUFFER_EXT,
- GL_COLOR_ATTACHMENT0_EXT,
- GL_TEXTURE_2D,
- handle,
- gl_surface->mip_level());
- } else if (texture->IsA(TextureCUBE::GetApparentClass())) {
- ::glFramebufferTexture2DEXT(
- GL_FRAMEBUFFER_EXT,
- GL_COLOR_ATTACHMENT0_EXT,
- gl_surface->cube_face(),
- handle,
- gl_surface->mip_level());
- }
- }
-
- if (surface_depth) {
- // Bind both the depth and stencil attachments.
- const RenderDepthStencilSurfaceGL* gl_surface =
- down_cast<const RenderDepthStencilSurfaceGL*>(surface_depth);
- ::glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT,
- GL_DEPTH_ATTACHMENT_EXT,
- GL_RENDERBUFFER_EXT,
- gl_surface->depth_buffer());
- ::glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT,
- GL_STENCIL_ATTACHMENT_EXT,
- GL_RENDERBUFFER_EXT,
- gl_surface->stencil_buffer());
- }
- GLenum framebuffer_status = ::glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
- if (GL_FRAMEBUFFER_COMPLETE_EXT != framebuffer_status) {
- return false;
- }
-
- CHECK_GL_ERROR();
- return true;
-}
-
-// Helper routine that returns a pointer to the non-NULL entry in the renderer's
-// stack of bound surfaces.
-const RenderSurfaceBase* GetValidRenderSurface(
- const std::pair<RenderSurface*, RenderDepthStencilSurface*> &stack_entry) {
- if (stack_entry.first) {
- return stack_entry.first;
- } else {
- return stack_entry.second;
- }
-}
-
-} // unnamed namespace
-
-// This class wraps StateHandler to make it typesafe.
-template <typename T>
-class TypedStateHandler : public RendererGL::StateHandler {
- public:
- // Override this function to set a specific state.
- // Parameters:
- // renderer: The platform specific renderer.
- // param: A concrete param with state data.
- virtual void SetStateFromTypedParam(RendererGL* renderer, T* param) const = 0;
-
- // Gets Class of State's Parameter
- virtual const ObjectBase::Class* GetClass() const {
- return T::GetApparentClass();
- }
-
- private:
- // Calls SetStateFromTypedParam if the Param type is the correct type.
- // Parameters:
- // renderer: The platform specific renderer.
- // param: A param with state data.
- virtual void SetState(Renderer* renderer, Param* param) const {
- RendererGL *renderer_gl = down_cast<RendererGL *>(renderer);
- // This is safe because State guarntees Params match by type.
- DCHECK(param->IsA(T::GetApparentClass()));
- SetStateFromTypedParam(renderer_gl, down_cast<T*>(param));
- }
-};
-
-// A template the generates a handler for enable/disable states.
-// Parameters:
-// state_constant: GLenum of state we want to enable/disable
-template <GLenum state_constant>
-class StateEnableHandler : public TypedStateHandler<ParamBoolean> {
- public:
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamBoolean* param) const {
- if (param->value()) {
- ::glEnable(state_constant);
- } else {
- ::glDisable(state_constant);
- }
- }
-};
-
-class BoolHandler : public TypedStateHandler<ParamBoolean> {
- public:
- explicit BoolHandler(bool* var, bool* changed_var)
- : var_(*var),
- changed_var_(*changed_var) {
- }
- virtual void SetStateFromTypedParam(RendererGL *renderer,
- ParamBoolean *param) const {
- var_ = param->value();
- }
- private:
- bool& var_;
- bool& changed_var_;
-};
-
-class ZWriteEnableHandler : public TypedStateHandler<ParamBoolean> {
- public:
- virtual void SetStateFromTypedParam(RendererGL *renderer,
- ParamBoolean *param) const {
- ::glDepthMask(param->value());
- }
-};
-
-class AlphaReferenceHandler : public TypedStateHandler<ParamFloat> {
- public:
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamFloat* param) const {
- float refFloat = param->value();
-
- // cap the float to the required range
- if (refFloat < 0.0f) {
- refFloat = 0.0f;
- } else if (refFloat > 1.0f) {
- refFloat = 1.0f;
- }
-
- renderer->alpha_function_ref_changed_ = true;
- renderer->alpha_ref_ = refFloat;
- }
-};
-
-class CullModeHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamInteger* param) const {
- State::Cull cull = static_cast<State::Cull>(param->value());
- switch (cull) {
- case State::CULL_CW:
- ::glEnable(GL_CULL_FACE);
- ::glCullFace(GL_BACK);
- break;
- case State::CULL_CCW:
- ::glEnable(GL_CULL_FACE);
- ::glCullFace(GL_FRONT);
- break;
- default:
- ::glDisable(GL_CULL_FACE);
- break;
- }
- }
-};
-
-class PolygonOffset1Handler : public TypedStateHandler<ParamFloat> {
- public:
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamFloat* param) const {
- renderer->polygon_offset_factor_ = param->value();
- renderer->polygon_offset_changed_ = true;
- }
-};
-
-class PolygonOffset2Handler : public TypedStateHandler<ParamFloat> {
- public:
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamFloat* param) const {
- renderer->polygon_offset_bias_ = param->value();
- renderer->polygon_offset_changed_ = true;
- }
-};
-
-class FillModeHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamInteger* param) const {
- ::glPolygonMode(GL_FRONT_AND_BACK,
- ConvertFillMode(static_cast<State::Fill>(param->value())));
- }
-};
-
-class ZFunctionHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamInteger* param) const {
- ::glDepthFunc(
- ConvertCmpFunc(static_cast<State::Comparison>(param->value())));
- }
-};
-
-class BlendEquationHandler : public TypedStateHandler<ParamInteger> {
- public:
- explicit BlendEquationHandler(GLenum* var)
- : var_(*var) {
- }
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamInteger* param) const {
- renderer->alpha_blend_settings_changed_ = true;
- var_ = ConvertBlendEquation(
- static_cast<State::BlendingEquation>(param->value()));
- }
- private:
- GLenum& var_;
-};
-
-class BlendFunctionHandler : public TypedStateHandler<ParamInteger> {
- public:
- explicit BlendFunctionHandler(GLenum* var)
- : var_(*var) {
- }
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamInteger* param) const {
- renderer->alpha_blend_settings_changed_ = true;
- var_ = ConvertBlendFunc(
- static_cast<State::BlendingFunction>(param->value()));
- }
- private:
- GLenum& var_;
-};
-
-
-class StencilOperationHandler : public TypedStateHandler<ParamInteger> {
- public:
- StencilOperationHandler(int face, int condition)
- : face_(face) ,
- condition_(condition) {
- }
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamInteger* param) const {
- renderer->stencil_settings_changed_ = true;
- renderer->stencil_settings_[face_].op_[condition_] = ConvertStencilOp(
- static_cast<State::StencilOperation>(param->value()));
- }
- private:
- int face_;
- int condition_;
-};
-
-class ComparisonFunctionHandler : public TypedStateHandler<ParamInteger> {
- public:
- ComparisonFunctionHandler(GLenum* var, bool* changed_var)
- : var_(*var),
- changed_var_(*changed_var) {
- }
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamInteger* param) const {
- changed_var_ = true;
- var_ = ConvertCmpFunc(static_cast<State::Comparison>(param->value()));
- }
- private:
- GLenum& var_;
- bool& changed_var_;
-};
-
-class StencilRefHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamInteger* param) const {
- renderer->stencil_settings_changed_ = true;
- renderer->stencil_ref_ = param->value();
- }
-};
-
-class StencilMaskHandler : public TypedStateHandler<ParamInteger> {
- public:
- explicit StencilMaskHandler(int mask_index)
- : mask_index_(mask_index) {
- }
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamInteger* param) const {
- renderer->stencil_settings_changed_ = true;
- renderer->stencil_mask_[mask_index_] = param->value();
- }
- private:
- int mask_index_;
-};
-
-class ColorWriteEnableHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamInteger* param) const {
- int mask = param->value();
- ::glColorMask((mask & 0x1) != 0,
- (mask & 0x2) != 0,
- (mask & 0x4) != 0,
- (mask & 0x8) != 0);
- renderer->SetWriteMask(mask);
- }
-};
-
-class PointSpriteEnableHandler : public TypedStateHandler<ParamBoolean> {
- public:
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamBoolean* param) const {
- if (param->value()) {
- ::glEnable(GL_POINT_SPRITE);
- // TODO: It's not clear from D3D docs that point sprites affect
- // TEXCOORD0, but that's my guess. Check that.
- ::glActiveTextureARB(GL_TEXTURE0);
- ::glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
- } else {
- ::glActiveTextureARB(GL_TEXTURE0);
- ::glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_FALSE);
- ::glDisable(GL_POINT_SPRITE);
- }
- }
-};
-
-class PointSizeHandler : public TypedStateHandler<ParamFloat> {
- public:
- virtual void SetStateFromTypedParam(RendererGL* renderer,
- ParamFloat* param) const {
- ::glPointSize(param->value());
- }
-};
-
-RendererGL* RendererGL::CreateDefault(ServiceLocator* service_locator) {
- return new RendererGL(service_locator);
-}
-
-RendererGL::RendererGL(ServiceLocator* service_locator)
- : Renderer(service_locator),
- semantic_manager_(service_locator),
-#ifdef OS_WIN
- gl_context_(NULL),
-#endif
- fullscreen_(0),
-#ifdef OS_LINUX
- display_(NULL),
- window_(0),
- context_(0),
-#endif
-#ifdef OS_MACOSX
- mac_agl_context_(0),
- mac_cgl_context_(0),
-#endif
- render_surface_framebuffer_(0),
- cg_context_(NULL),
- alpha_function_ref_changed_(true),
- alpha_function_(GL_ALWAYS),
- alpha_ref_(0.f),
- alpha_blend_settings_changed_(true),
- separate_alpha_blend_enable_(false),
- stencil_settings_changed_(true),
- separate_stencil_settings_enable_(false),
- stencil_ref_(0),
- polygon_offset_changed_(true),
- polygon_offset_factor_(0.f),
- polygon_offset_bias_(0.f),
- must_reset_context_(false) {
- DLOG(INFO) << "RendererGL Construct";
-
- // Setup default state values.
- for (int ii = 0; ii < 2; ++ii) {
- stencil_settings_[ii].func_ = GL_ALWAYS;
- stencil_settings_[ii].op_[StencilStates::FAIL_OP] = GL_KEEP;
- stencil_settings_[ii].op_[StencilStates::ZFAIL_OP] = GL_KEEP;
- stencil_settings_[ii].op_[StencilStates::PASS_OP] = GL_KEEP;
- stencil_mask_[ii] = -1;
- blend_function_[ii][FRONT] = GL_ONE;
- blend_function_[ii][BACK] = GL_ZERO;
- blend_equation_[ii] = GL_FUNC_ADD;
- }
-
- // Setup state handlers
- AddStateHandler(State::kAlphaTestEnableParamName,
- new StateEnableHandler<GL_ALPHA_TEST>);
- AddStateHandler(State::kAlphaReferenceParamName,
- new AlphaReferenceHandler);
- AddStateHandler(State::kAlphaComparisonFunctionParamName,
- new ComparisonFunctionHandler(&alpha_function_,
- &alpha_function_ref_changed_));
- AddStateHandler(State::kCullModeParamName,
- new CullModeHandler);
- AddStateHandler(State::kDitherEnableParamName,
- new StateEnableHandler<GL_DITHER>);
- AddStateHandler(State::kLineSmoothEnableParamName,
- new StateEnableHandler<GL_LINE_SMOOTH>);
- AddStateHandler(State::kPointSpriteEnableParamName,
- new PointSpriteEnableHandler);
- AddStateHandler(State::kPointSizeParamName,
- new PointSizeHandler);
- AddStateHandler(State::kPolygonOffset1ParamName,
- new PolygonOffset1Handler);
- AddStateHandler(State::kPolygonOffset2ParamName,
- new PolygonOffset2Handler);
- AddStateHandler(State::kFillModeParamName,
- new FillModeHandler);
- AddStateHandler(State::kZEnableParamName,
- new StateEnableHandler<GL_DEPTH_TEST>);
- AddStateHandler(State::kZWriteEnableParamName,
- new ZWriteEnableHandler);
- AddStateHandler(State::kZComparisonFunctionParamName,
- new ZFunctionHandler);
- AddStateHandler(State::kAlphaBlendEnableParamName,
- new StateEnableHandler<GL_BLEND>);
- AddStateHandler(State::kSourceBlendFunctionParamName,
- new BlendFunctionHandler(&blend_function_[SRC][RGB]));
- AddStateHandler(State::kDestinationBlendFunctionParamName,
- new BlendFunctionHandler(&blend_function_[DST][RGB]));
- AddStateHandler(State::kStencilEnableParamName,
- new StateEnableHandler<GL_STENCIL_TEST>);
- AddStateHandler(State::kStencilFailOperationParamName,
- new StencilOperationHandler(FRONT, StencilStates::FAIL_OP));
- AddStateHandler(State::kStencilZFailOperationParamName,
- new StencilOperationHandler(FRONT, StencilStates::ZFAIL_OP));
- AddStateHandler(State::kStencilPassOperationParamName,
- new StencilOperationHandler(FRONT, StencilStates::PASS_OP));
- AddStateHandler(State::kStencilComparisonFunctionParamName,
- new ComparisonFunctionHandler(
- &stencil_settings_[FRONT].func_,
- &stencil_settings_changed_));
- AddStateHandler(State::kStencilReferenceParamName,
- new StencilRefHandler);
- AddStateHandler(State::kStencilMaskParamName,
- new StencilMaskHandler(READ_MASK));
- AddStateHandler(State::kStencilWriteMaskParamName,
- new StencilMaskHandler(WRITE_MASK));
- AddStateHandler(State::kColorWriteEnableParamName,
- new ColorWriteEnableHandler);
- AddStateHandler(State::kBlendEquationParamName,
- new BlendEquationHandler(&blend_equation_[RGB]));
- AddStateHandler(State::kTwoSidedStencilEnableParamName,
- new BoolHandler(&separate_stencil_settings_enable_,
- &stencil_settings_changed_));
- AddStateHandler(State::kCCWStencilFailOperationParamName,
- new StencilOperationHandler(BACK, StencilStates::FAIL_OP));
- AddStateHandler(State::kCCWStencilZFailOperationParamName,
- new StencilOperationHandler(BACK, StencilStates::ZFAIL_OP));
- AddStateHandler(State::kCCWStencilPassOperationParamName,
- new StencilOperationHandler(BACK, StencilStates::PASS_OP));
- AddStateHandler(State::kCCWStencilComparisonFunctionParamName,
- new ComparisonFunctionHandler(
- &stencil_settings_[BACK].func_,
- &stencil_settings_changed_));
- AddStateHandler(State::kSeparateAlphaBlendEnableParamName,
- new BoolHandler(&separate_alpha_blend_enable_,
- &alpha_blend_settings_changed_));
- AddStateHandler(State::kSourceBlendAlphaFunctionParamName,
- new BlendFunctionHandler(&blend_function_[SRC][ALPHA]));
- AddStateHandler(State::kDestinationBlendAlphaFunctionParamName,
- new BlendFunctionHandler(&blend_function_[DST][ALPHA]));
- AddStateHandler(State::kBlendAlphaEquationParamName,
- new BlendEquationHandler(&blend_equation_[ALPHA]));
-}
-
-RendererGL::~RendererGL() {
- Destroy();
-}
-
-// platform neutral initialization code
-//
-Renderer::InitStatus RendererGL::InitCommonGL() {
- GLenum glew_error = glewInit();
- if (glew_error != GLEW_OK) {
- DLOG(ERROR) << "Unable to initialise GLEW : "
- << ::glewGetErrorString(glew_error);
- return INITIALIZATION_ERROR;
- }
-
- // Check to see that we can use the OpenGL vertex attribute APIs
- // TODO: We should return false if this check fails, but because some
- // Intel hardware does not support OpenGL 2.0, yet does support all of the
- // extensions we require, we only log an error. A future CL should change
- // this check to ensure that all of the extension strings we require are
- // present.
- if (!GLEW_VERSION_2_0) {
- DLOG(ERROR) << "GL drivers do not have OpenGL 2.0 functionality.";
- }
-
- if (!GLEW_ARB_vertex_buffer_object) {
- // NOTE: Linux NVidia drivers claim to support OpenGL 2.0 when using
- // indirect rendering (e.g. remote X), but it is actually lying. The
- // ARB_vertex_buffer_object functions silently no-op (!) when using
- // indirect rendering, leading to crashes. Fortunately, in that case, the
- // driver claims to not support ARB_vertex_buffer_object, so fail in that
- // case.
- DLOG(ERROR) << "GL drivers do not support vertex buffer objects.";
- return GPU_NOT_UP_TO_SPEC;
- }
-
- if (!GLEW_EXT_framebuffer_object) {
- DLOG(ERROR) << "GL drivers do not support framebuffer objects.";
- return GPU_NOT_UP_TO_SPEC;
- }
-
- SetSupportsNPOT(GLEW_ARB_texture_non_power_of_two != 0);
-
-#ifdef OS_MACOSX
- // The Radeon X1600 says it supports NPOT, but in most situations it doesn't.
- if (supports_npot() &&
- !strcmp("ATI Radeon X1600 OpenGL Engine",
- reinterpret_cast<const char*>(::glGetString(GL_RENDERER))))
- SetSupportsNPOT(false);
-#endif
-
- // Check for necessary extensions
- if (!GLEW_VERSION_2_0 && !GLEW_EXT_stencil_two_side) {
- DLOG(ERROR) << "Two sided stencil extension missing.";
- }
- if (!GLEW_VERSION_1_4 && !GLEW_EXT_blend_func_separate) {
- DLOG(ERROR) << "Separate blend func extension missing.";
- }
- if (!GLEW_VERSION_2_0 && !GLEW_EXT_blend_equation_separate) {
- DLOG(ERROR) << "Separate blend function extension missing.";
- }
- // create a Cg Runtime.
- cg_context_ = cgCreateContext();
- DLOG_CG_ERROR("Creating Cg context");
- SetupCgAndOpenGLContext();
-
- ::glGenFramebuffersEXT(1, &render_surface_framebuffer_);
- CHECK_GL_ERROR();
-
- return SUCCESS;
-}
-
-// platform neutral destruction code
-void RendererGL::DestroyCommonGL() {
- MakeCurrentLazy();
- if (render_surface_framebuffer_) {
- ::glDeleteFramebuffersEXT(1, &render_surface_framebuffer_);
- }
-
- if (cg_context_) {
- cgDestroyContext(cg_context_);
- cg_context_ = NULL;
- }
-}
-
-#ifdef OS_WIN
-
-namespace {
-
-PIXELFORMATDESCRIPTOR kPixelFormatDescriptor = {
- sizeof(kPixelFormatDescriptor), // Size of structure.
- 1, // Default version.
- PFD_DRAW_TO_WINDOW | // Window drawing support.
- PFD_SUPPORT_OPENGL | // OpenGL support.
- PFD_DOUBLEBUFFER, // Double buffering support (not stereo).
- PFD_TYPE_RGBA, // RGBA color mode (not indexed).
- 24, // 24 bit color mode.
- 0, 0, 0, 0, 0, 0, // Don't set RGB bits & shifts.
- 8, 0, // 8 bit alpha
- 0, // No accumulation buffer.
- 0, 0, 0, 0, // Ignore accumulation bits.
- 24, // 24 bit z-buffer size.
- 8, // 8-bit stencil buffer.
- 0, // No aux buffer.
- PFD_MAIN_PLANE, // Main drawing plane (not overlay).
- 0, // Reserved.
- 0, 0, 0, // Layer masks ignored.
-};
-
-LRESULT CALLBACK IntermediateWindowProc(HWND window,
- UINT message,
- WPARAM w_param,
- LPARAM l_param) {
- return ::DefWindowProc(window, message, w_param, l_param);
-}
-
-// Helper routine that returns the highest quality pixel format supported on
-// the current platform. Returns true upon success.
-Renderer::InitStatus GetWindowsPixelFormat(HWND window,
- Features* features,
- int* pixel_format) {
- // We must initialize a GL context before we can determine the multi-sampling
- // supported on the current hardware, so we create an intermediate window
- // and context here.
- HINSTANCE module_handle;
- if (!::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
- GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
- reinterpret_cast<wchar_t*>(IntermediateWindowProc),
- &module_handle)) {
- return Renderer::INITIALIZATION_ERROR;
- }
-
- WNDCLASS intermediate_class;
- intermediate_class.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
- intermediate_class.lpfnWndProc = IntermediateWindowProc;
- intermediate_class.cbClsExtra = 0;
- intermediate_class.cbWndExtra = 0;
- intermediate_class.hInstance = module_handle;
- intermediate_class.hIcon = LoadIcon(NULL, IDI_APPLICATION);
- intermediate_class.hCursor = LoadCursor(NULL, IDC_ARROW);
- intermediate_class.hbrBackground = NULL;
- intermediate_class.lpszMenuName = NULL;
- intermediate_class.lpszClassName = L"Intermediate GL Window";
-
- ATOM class_registration = ::RegisterClass(&intermediate_class);
- if (!class_registration) {
- return Renderer::INITIALIZATION_ERROR;
- }
-
- HWND intermediate_window = ::CreateWindow(
- reinterpret_cast<wchar_t*>(class_registration),
- L"",
- WS_OVERLAPPEDWINDOW,
- 0, 0,
- CW_USEDEFAULT, CW_USEDEFAULT,
- NULL,
- NULL,
- NULL,
- NULL);
-
- if (!intermediate_window) {
- ::UnregisterClass(reinterpret_cast<wchar_t*>(class_registration),
- module_handle);
- return Renderer::INITIALIZATION_ERROR;
- }
-
- HDC intermediate_dc = ::GetDC(intermediate_window);
- int format_index = ::ChoosePixelFormat(intermediate_dc,
- &kPixelFormatDescriptor);
- if (format_index == 0) {
- DLOG(ERROR) << "Unable to get the pixel format for GL context.";
- ::ReleaseDC(intermediate_window, intermediate_dc);
- ::DestroyWindow(intermediate_window);
- ::UnregisterClass(reinterpret_cast<wchar_t*>(class_registration),
- module_handle);
- return Renderer::INITIALIZATION_ERROR;
- }
- if (!::SetPixelFormat(intermediate_dc, format_index,
- &kPixelFormatDescriptor)) {
- DLOG(ERROR) << "Unable to set the pixel format for GL context.";
- ::ReleaseDC(intermediate_window, intermediate_dc);
- ::DestroyWindow(intermediate_window);
- ::UnregisterClass(reinterpret_cast<wchar_t*>(class_registration),
- module_handle);
- return Renderer::INITIALIZATION_ERROR;
- }
-
- // Store the pixel format without multisampling.
- *pixel_format = format_index;
- HGLRC gl_context = ::wglCreateContext(intermediate_dc);
- if (::wglMakeCurrent(intermediate_dc, gl_context)) {
- // GL context was successfully created and applied to the window's DC.
- // Startup GLEW, the GL extensions wrangler.
- GLenum glew_error = ::glewInit();
- if (glew_error == GLEW_OK) {
- DLOG(INFO) << "Initialized GLEW " << ::glewGetString(GLEW_VERSION);
- } else {
- DLOG(ERROR) << "Unable to initialise GLEW : "
- << ::glewGetErrorString(glew_error);
- ::wglMakeCurrent(intermediate_dc, NULL);
- ::wglDeleteContext(gl_context);
- ::ReleaseDC(intermediate_window, intermediate_dc);
- ::DestroyWindow(intermediate_window);
- ::UnregisterClass(reinterpret_cast<wchar_t*>(class_registration),
- module_handle);
- return Renderer::INITIALIZATION_ERROR;
- }
-
- // If the multi-sample extensions are present, query the api to determine
- // the pixel format.
- if (!features->not_anti_aliased() &&
- WGLEW_ARB_pixel_format && WGLEW_ARB_multisample) {
- int pixel_attributes[] = {
- WGL_SAMPLES_ARB, 4,
- WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
- WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
- WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
- WGL_COLOR_BITS_ARB, 24,
- WGL_ALPHA_BITS_ARB, 8,
- WGL_DEPTH_BITS_ARB, 24,
- WGL_STENCIL_BITS_ARB, 8,
- WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
- WGL_SAMPLE_BUFFERS_ARB, GL_TRUE,
- 0, 0};
-
- float pixel_attributes_f[] = {0, 0};
- int msaa_pixel_format;
- unsigned int num_formats;
-
- // Query for the highest sampling rate supported, starting at 4x.
- static const int kSampleCount[] = {4, 2};
- static const int kNumSamples = 2;
- for (int sample = 0; sample < kNumSamples; ++sample) {
- pixel_attributes[1] = kSampleCount[sample];
- if (GL_TRUE == ::wglChoosePixelFormatARB(intermediate_dc,
- pixel_attributes,
- pixel_attributes_f,
- 1,
- &msaa_pixel_format,
- &num_formats)) {
- *pixel_format = msaa_pixel_format;
- break;
- }
- }
- }
- }
-
- ::wglMakeCurrent(intermediate_dc, NULL);
- ::wglDeleteContext(gl_context);
- ::ReleaseDC(intermediate_window, intermediate_dc);
- ::DestroyWindow(intermediate_window);
- ::UnregisterClass(reinterpret_cast<wchar_t*>(class_registration),
- module_handle);
- return Renderer::SUCCESS;
-}
-
-} // unnamed namespace
-
-Renderer::InitStatus RendererGL::InitPlatformSpecific(
- const DisplayWindow& display,
- bool off_screen) {
- const DisplayWindowWindows &display_platform =
- static_cast<const DisplayWindowWindows&>(display);
-
- DLOG(INFO) << "RendererGL Init";
-
- // TODO: Add support for off-screen rendering using OpenGL.
- if (off_screen) {
- return INITIALIZATION_ERROR;
- }
-
- int pixel_format;
- InitStatus init_status;
-
- init_status = GetWindowsPixelFormat(display_platform.hwnd(),
- features(),
- &pixel_format);
- if (init_status != SUCCESS) {
- return init_status;
- }
-
- window_ = display_platform.hwnd();
- device_context_ = ::GetDC(window_);
- if (!::SetPixelFormat(device_context_, pixel_format,
- &kPixelFormatDescriptor)) {
- DLOG(ERROR) << "Unable to set the pixel format for GL context.";
- return INITIALIZATION_ERROR;
- }
-
- gl_context_ = ::wglCreateContext(device_context_);
- if (MakeCurrent()) {
- // Ensure that glew has been initialized for the created rendering context.
- init_status = InitCommonGL();
- if (init_status != SUCCESS) {
- DLOG(ERROR) << "Failed to initialize GL rendering context.";
- return init_status;
- }
- if (WGLEW_ARB_multisample) {
- ::glEnable(GL_MULTISAMPLE_ARB);
- }
- } else {
- DLOG(ERROR) << "Failed to create the GL Context.";
- return INITIALIZATION_ERROR;
- }
- CHECK_GL_ERROR();
- return SUCCESS;
-}
-
-// Releases the Cg Context and deletes the GL device.
-void RendererGL::Destroy() {
- DLOG(INFO) << "Destroy RendererGL";
- DestroyCommonGL();
- if (device_context_) {
- CHECK_GL_ERROR();
- // Release the OpenGL rendering context.
- ::wglMakeCurrent(device_context_, NULL);
- if (gl_context_) {
- ::wglDeleteContext(gl_context_);
- gl_context_ = NULL;
- }
- // release the hDC obtained through GetDC().
- ::ReleaseDC(window_, device_context_);
- device_context_ = NULL;
- window_ = NULL;
- }
- DLOG(INFO) << "Renderer destroyed.";
-}
-
-#endif // OS_WIN
-
-#ifdef OS_MACOSX
-
-Renderer::InitStatus RendererGL::InitPlatformSpecific(
- const DisplayWindow& display,
- bool /*off_screen*/) {
- const DisplayWindowMac &display_platform =
- static_cast<const DisplayWindowMac&>(display);
- // TODO: Add support for off screen rendering on the Mac.
- mac_agl_context_ = display_platform.agl_context();
- mac_cgl_context_ = display_platform.cgl_context();
-
- return InitCommonGL();
-}
-
-void RendererGL::Destroy() {
- DestroyCommonGL();
- // We only have to destroy agl contexts,
- // cgl contexts are not owned by us.
- if (mac_agl_context_) {
- ::aglDestroyContext(mac_agl_context_);
- mac_agl_context_ = NULL;
- }
-}
-
-#endif // OS_MACOSX
-
-#ifdef OS_LINUX
-Renderer::InitStatus RendererGL::InitPlatformSpecific(
- const DisplayWindow& display_window,
- bool off_screen) {
- const DisplayWindowLinux &display_platform =
- static_cast<const DisplayWindowLinux&>(display_window);
- Display *display = display_platform.display();
- Window window = display_platform.window();
- XWindowAttributes attributes;
- ::XGetWindowAttributes(display, window, &attributes);
- XVisualInfo visual_info_template;
- visual_info_template.visualid = ::XVisualIDFromVisual(attributes.visual);
- int visual_info_count = 0;
- XVisualInfo *visual_info_list = ::XGetVisualInfo(display, VisualIDMask,
- &visual_info_template,
- &visual_info_count);
- DCHECK(visual_info_list);
- DCHECK_GT(visual_info_count, 0);
- context_ = 0;
- for (int i = 0; i < visual_info_count; ++i) {
- context_ = ::glXCreateContext(display, visual_info_list + i, 0,
- True);
- if (context_) break;
- }
- ::XFree(visual_info_list);
- if (!context_) {
- DLOG(ERROR) << "Couldn't create GL context.";
- return INITIALIZATION_ERROR;
- }
- display_ = display;
- window_ = window;
- if (!MakeCurrent()) {
- ::glXDestroyContext(display, context_);
- context_ = 0;
- display_ = NULL;
- window_ = 0;
- DLOG(ERROR) << "Couldn't create GL context.";
- return INITIALIZATION_ERROR;
- }
-
- InitStatus init_status = InitCommonGL();
- if (init_status != SUCCESS) {
- ::glXDestroyContext(display, context_);
- context_ = 0;
- display_ = NULL;
- window_ = 0;
- } else if (strcmp("Software Rasterizer",
- reinterpret_cast<const char*>(::glGetString(
- GL_RENDERER))) == 0) {
- ClientInfoManager* client_info_manager =
- service_locator()->GetService<ClientInfoManager>();
- client_info_manager->SetSoftwareRenderer(true);
- }
- return init_status;
-}
-
-void RendererGL::Destroy() {
- DestroyCommonGL();
- if (display_) {
- ::glXMakeCurrent(display_, 0, 0);
- if (context_) {
- ::glXDestroyContext(display_, context_);
- context_ = 0;
- }
- display_ = NULL;
- window_ = 0;
- }
-}
-
-#endif
-
-bool RendererGL::MakeCurrent() {
-#ifdef OS_WIN
- if (!device_context_ || !gl_context_) return false;
- bool result = ::wglMakeCurrent(device_context_, gl_context_) != 0;
- return result;
-#endif
-#ifdef OS_MACOSX
- if (mac_cgl_context_ != NULL) {
- ::CGLSetCurrentContext(mac_cgl_context_);
- return true;
- } else if (mac_agl_context_ != NULL) {
- ::aglSetCurrentContext(mac_agl_context_);
- return true;
- } else {
- return false;
- }
-#endif
-#ifdef OS_LINUX
- if (context_ != NULL) {
- bool result = ::glXMakeCurrent(display_, window_, context_) == True;
- return result;
- } else {
- return false;
- }
-#endif
-}
-
-void RendererGL::PlatformSpecificClear(const Float4 &color,
- bool color_flag,
- float depth,
- bool depth_flag,
- int stencil,
- bool stencil_flag) {
- MakeCurrentLazy();
- ::glClearColor(color[0], color[1], color[2], color[3]);
- ::glClearDepth(depth);
- ::glClearStencil(stencil);
-
- ::glClear((color_flag ? GL_COLOR_BUFFER_BIT : 0) |
- (depth_flag ? GL_DEPTH_BUFFER_BIT : 0) |
- (stencil_flag ? GL_STENCIL_BUFFER_BIT : 0));
- CHECK_GL_ERROR();
-}
-
-// Updates the helper constant used for the D3D -> GL remapping.
-// See effect_gl.cc for details.
-void RendererGL::UpdateHelperConstant(float width, float height) {
- MakeCurrentLazy();
- // If render-targets are active, pass -1 to invert the Y axis. OpenGL uses
- // a different viewport orientation than DX. Without the inversion, the
- // output of render-target rendering will be upside down.
- if (RenderSurfaceActive()) {
- ::glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB,
- 0,
- 1.0f / width,
- -1.0f / height,
- 2.0f,
- -1.0f);
- } else {
- // Only apply the origin offset when rendering to the client area.
- ::glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB,
- 0,
- (1.0f + (2.0f * -dest_x_offset())) / width,
- (-1.0f + (2.0f * dest_y_offset())) / height,
- 2.0f,
- 1.0f);
- }
- CHECK_GL_ERROR();
-}
-
-void RendererGL::SetViewportInPixels(int left,
- int top,
- int width,
- int height,
- float min_z,
- float max_z) {
- MakeCurrentLazy();
- int vieport_top =
- RenderSurfaceActive() ? top : display_height() - top - height;
- ::glViewport(left, vieport_top, width, height);
- UpdateHelperConstant(static_cast<float>(width), static_cast<float>(height));
-
- // If it's the full client area turn off scissor test for speed.
- if (left == 0 &&
- top == 0 &&
- width == display_width() &&
- height == display_height()) {
- ::glDisable(GL_SCISSOR_TEST);
- } else {
- ::glScissor(left, vieport_top, width, height);
- ::glEnable(GL_SCISSOR_TEST);
- }
- ::glDepthRange(min_z, max_z);
-}
-
-// Resizes the viewport.
-void RendererGL::Resize(int width, int height) {
- MakeCurrentLazy();
- SetClientSize(width, height);
- CHECK_GL_ERROR();
-}
-
-bool RendererGL::GoFullscreen(const DisplayWindow& display,
- int mode_id) {
-#ifdef OS_LINUX
- // This actually just switches the GLX context to the new window. The real
- // work is in main_linux.cc.
- const DisplayWindowLinux &display_platform =
- static_cast<const DisplayWindowLinux&>(display);
- display_ = display_platform.display();
- window_ = display_platform.window();
- if (!MakeCurrent()) {
- return false;
- }
-#endif
- fullscreen_ = true;
- return true;
-}
-
-bool RendererGL::CancelFullscreen(const DisplayWindow& display,
- int width, int height) {
-#ifdef OS_LINUX
- // This actually just switches the GLX context to the old window. The real
- // work is in main_linux.cc.
- const DisplayWindowLinux &display_platform =
- static_cast<const DisplayWindowLinux&>(display);
- display_ = display_platform.display();
- window_ = display_platform.window();
- if (!MakeCurrent()) {
- return false;
- }
-#endif
- fullscreen_ = false;
- return true;
-}
-
-void RendererGL::GetDisplayModes(std::vector<DisplayMode> *modes) {
-#ifdef OS_MACOSX
- // Mac is supposed to call a different function in plugin_mac.mm instead.
- DLOG(FATAL) << "Not supposed to be called";
-#endif
- // On all other platforms this is unimplemented. Linux only supports
- // DISPLAY_MODE_DEFAULT for now.
- modes->clear();
-}
-
-bool RendererGL::GetDisplayMode(int id, DisplayMode *mode) {
-#ifdef OS_MACOSX
- // Mac is supposed to call a different function in plugin_mac.mm instead.
- DLOG(FATAL) << "Not supposed to be called";
- return false;
-#elif defined(OS_LINUX)
- if (id == DISPLAY_MODE_DEFAULT) {
- // Don't need to know any of this on Linux.
- mode->Set(0, 0, 0, id);
- return true;
- } else {
- // There are no other valid ids until we implement GetDisplayModes() and
- // mode switching.
- return false;
- }
-#else
- return false;
-#endif
-}
-
-bool RendererGL::PlatformSpecificStartRendering() {
- DLOG_FIRST_N(INFO, 10) << "RendererGL StartRendering";
- MakeCurrentLazy();
-
- if (must_reset_context_) {
- SetupCgAndOpenGLContext();
- }
-
- // Currently always returns true.
- // Should be modified if current behavior changes.
- CHECK_GL_ERROR();
- return true;
-}
-
-// Clears the color, depth and stncil buffers and prepares GL for rendering
-// the frame.
-// Returns true on success.
-bool RendererGL::PlatformSpecificBeginDraw() {
- DLOG_FIRST_N(INFO, 10) << "RendererGL BeginDraw";
-
- MakeCurrentLazy();
-
- // Currently always returns true.
- // Should be modified if current behavior changes.
- CHECK_GL_ERROR();
- return true;
-}
-
-// Assign the surface arguments to the renderer, and update the stack
-// of pushed surfaces.
-void RendererGL::SetRenderSurfacesPlatformSpecific(
- const RenderSurface* surface,
- const RenderDepthStencilSurface* surface_depth) {
- // TODO: This routine re-uses a single global framebuffer object for
- // all RenderSurface rendering. Because of the validation checks performed
- // at attachment-change time, it may be more performant to create a pool
- // of framebuffer objects with different attachment characterists and
- // switch between them here.
- MakeCurrentLazy();
- ::glBindFramebufferEXT(GL_FRAMEBUFFER, render_surface_framebuffer_);
- if (!InstallFramebufferObjects(surface, surface_depth)) {
- O3D_ERROR(service_locator())
- << "Failed to bind OpenGL render target objects:"
- << (surface ? surface->name() : "(no surface)") << ", "
- << (surface_depth ? surface_depth->name() : "(no depth surface)");
- }
- // RenderSurface rendering is performed with an inverted Y, so the front
- // face winding must be changed to clock-wise. See comments for
- // UpdateHelperConstant.
- glFrontFace(GL_CW);
-}
-
-void RendererGL::SetBackBufferPlatformSpecific() {
- MakeCurrentLazy();
- // Bind the default context, and restore the default front-face winding.
- ::glBindFramebufferEXT(GL_FRAMEBUFFER, 0);
- glFrontFace(GL_CCW);
-}
-
-// Executes a post rendering step
-void RendererGL::PlatformSpecificEndDraw() {
- DLOG_FIRST_N(INFO, 10) << "RendererGL EndDraw";
- DCHECK(IsCurrent());
-}
-
-// Swaps the buffers.
-void RendererGL::PlatformSpecificFinishRendering() {
- DLOG_FIRST_N(INFO, 10) << "RendererGL FinishRendering";
- DCHECK(IsCurrent());
- ::glFlush();
- CHECK_GL_ERROR();
-}
-
-void RendererGL::PlatformSpecificPresent() {
- DLOG_FIRST_N(INFO, 10) << "RendererGL Present";
- DCHECK(IsCurrent());
-#ifdef OS_WIN
- ::SwapBuffers(device_context_);
-#endif
-#ifdef OS_MACOSX
-#ifdef USE_AGL_DOUBLE_BUFFER
- if (mac_agl_context_) {
- ::aglSwapBuffers(mac_agl_context_);
- }
-#endif
-#endif
-#ifdef OS_LINUX
- ::glXSwapBuffers(display_, window_);
-#endif
-}
-
-StreamBank::Ref RendererGL::CreateStreamBank() {
- return StreamBank::Ref(new StreamBankGL(service_locator()));
-}
-
-Primitive::Ref RendererGL::CreatePrimitive() {
- return Primitive::Ref(new PrimitiveGL(service_locator()));
-}
-
-DrawElement::Ref RendererGL::CreateDrawElement() {
- return DrawElement::Ref(new DrawElementGL(service_locator()));
-}
-
-void RendererGL::SetStencilStates(GLenum face,
- const StencilStates& stencil_state) {
- DCHECK(IsCurrent());
- if (face == GL_FRONT_AND_BACK) {
- ::glStencilFunc(stencil_state.func_,
- stencil_ref_,
- stencil_mask_[READ_MASK]);
- ::glStencilOp(stencil_state.op_[StencilStates::FAIL_OP],
- stencil_state.op_[StencilStates::ZFAIL_OP],
- stencil_state.op_[StencilStates::PASS_OP]);
- ::glStencilMask(stencil_mask_[WRITE_MASK]);
- } else if (GLEW_VERSION_2_0) {
- ::glStencilFuncSeparate(face,
- stencil_state.func_,
- stencil_ref_,
- stencil_mask_[READ_MASK]);
- ::glStencilOpSeparate(face,
- stencil_state.op_[StencilStates::FAIL_OP],
- stencil_state.op_[StencilStates::ZFAIL_OP],
- stencil_state.op_[StencilStates::PASS_OP]);
- ::glStencilMaskSeparate(face,
- stencil_mask_[WRITE_MASK]);
- } else if (GLEW_EXT_stencil_two_side) {
- ::glEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);
- ::glActiveStencilFaceEXT(face);
- ::glStencilFunc(stencil_state.func_,
- stencil_ref_,
- stencil_mask_[READ_MASK]);
- ::glStencilOp(stencil_state.op_[StencilStates::FAIL_OP],
- stencil_state.op_[StencilStates::ZFAIL_OP],
- stencil_state.op_[StencilStates::PASS_OP]);
- ::glStencilMask(stencil_mask_[WRITE_MASK]);
- ::glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
- }
- CHECK_GL_ERROR();
-}
-
-void RendererGL::ApplyDirtyStates() {
- MakeCurrentLazy();
- DCHECK(IsCurrent());
- // Set blend settings.
- if (alpha_blend_settings_changed_) {
- if (separate_alpha_blend_enable_) {
- if (GLEW_VERSION_1_4) {
- ::glBlendFuncSeparate(blend_function_[SRC][RGB],
- blend_function_[DST][RGB],
- blend_function_[SRC][ALPHA],
- blend_function_[DST][ALPHA]);
- } else if (GLEW_EXT_blend_func_separate) {
- ::glBlendFuncSeparateEXT(blend_function_[SRC][RGB],
- blend_function_[DST][RGB],
- blend_function_[SRC][ALPHA],
- blend_function_[DST][ALPHA]);
- }
- if (GLEW_VERSION_2_0) {
- ::glBlendEquationSeparate(blend_equation_[RGB],
- blend_equation_[ALPHA]);
- } else if (GLEW_EXT_blend_equation_separate) {
- ::glBlendEquationSeparateEXT(blend_equation_[RGB],
- blend_equation_[ALPHA]);
- }
- } else {
- ::glBlendFunc(blend_function_[SRC][RGB],
- blend_function_[DST][RGB]);
- if (::glBlendEquation != NULL)
- ::glBlendEquation(blend_equation_[RGB]);
- }
- alpha_blend_settings_changed_ = false;
- }
-
- // Set alpha settings.
- if (alpha_function_ref_changed_) {
- ::glAlphaFunc(alpha_function_, alpha_ref_);
- alpha_function_ref_changed_ = false;
- }
-
- // Set stencil settings.
- if (stencil_settings_changed_) {
- if (separate_stencil_settings_enable_) {
- SetStencilStates(GL_FRONT, stencil_settings_[FRONT]);
- SetStencilStates(GL_BACK, stencil_settings_[BACK]);
- } else {
- SetStencilStates(GL_FRONT_AND_BACK, stencil_settings_[FRONT]);
- }
- stencil_settings_changed_ = false;
- }
-
- if (polygon_offset_changed_) {
- bool enable = (polygon_offset_factor_ != 0.f) ||
- (polygon_offset_bias_ != 0.f);
- if (enable) {
- ::glEnable(GL_POLYGON_OFFSET_POINT);
- ::glEnable(GL_POLYGON_OFFSET_LINE);
- ::glEnable(GL_POLYGON_OFFSET_FILL);
- ::glPolygonOffset(polygon_offset_factor_, polygon_offset_bias_);
- } else {
- ::glDisable(GL_POLYGON_OFFSET_POINT);
- ::glDisable(GL_POLYGON_OFFSET_LINE);
- ::glDisable(GL_POLYGON_OFFSET_FILL);
- }
- polygon_offset_changed_ = false;
- }
- CHECK_GL_ERROR();
-}
-
-VertexBuffer::Ref RendererGL::CreateVertexBuffer() {
- DLOG(INFO) << "RendererGL CreateVertexBuffer";
- MakeCurrentLazy();
- return VertexBuffer::Ref(new VertexBufferGL(service_locator()));
-}
-
-IndexBuffer::Ref RendererGL::CreateIndexBuffer() {
- DLOG(INFO) << "RendererGL CreateIndexBuffer";
- MakeCurrentLazy();
- return IndexBuffer::Ref(new IndexBufferGL(service_locator()));
-}
-
-Effect::Ref RendererGL::CreateEffect() {
- DLOG(INFO) << "RendererGL CreateEffect";
- MakeCurrentLazy();
- return Effect::Ref(new EffectGL(service_locator(), cg_context_));
-}
-
-Sampler::Ref RendererGL::CreateSampler() {
- return Sampler::Ref(new SamplerGL(service_locator()));
-}
-
-ParamCache* RendererGL::CreatePlatformSpecificParamCache() {
- return new ParamCacheGL(semantic_manager_.Get(), this);
-}
-
-
-Texture2D::Ref RendererGL::CreatePlatformSpecificTexture2D(
- int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- DLOG(INFO) << "RendererGL CreateTexture2D";
- MakeCurrentLazy();
- return Texture2D::Ref(Texture2DGL::Create(service_locator(),
- format,
- levels,
- width,
- height,
- enable_render_surfaces));
-}
-
-TextureCUBE::Ref RendererGL::CreatePlatformSpecificTextureCUBE(
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- DLOG(INFO) << "RendererGL CreateTextureCUBE";
- MakeCurrentLazy();
- return TextureCUBE::Ref(TextureCUBEGL::Create(service_locator(),
- format,
- levels,
- edge_length,
- enable_render_surfaces));
-}
-
-RenderDepthStencilSurface::Ref RendererGL::CreateDepthStencilSurface(
- int width,
- int height) {
- return RenderDepthStencilSurface::Ref(
- new RenderDepthStencilSurfaceGL(service_locator(),
- width,
- height));
-}
-
-const int* RendererGL::GetRGBAUByteNSwizzleTable() {
- static int swizzle_table[] = { 0, 1, 2, 3, };
- return swizzle_table;
-}
-
-// This is a factory function for creating Renderer objects. Since
-// we're implementing GL, we only ever return a GL renderer.
-Renderer* Renderer::CreateDefaultRenderer(ServiceLocator* service_locator) {
- return RendererGL::CreateDefault(service_locator);
-}
-
-#ifdef OS_MACOSX
-void RendererGL::set_mac_cgl_context(CGLContextObj obj) {
- bool changed = (mac_cgl_context_ != obj);
- mac_cgl_context_ = obj;
- if (changed) {
- // We need to reset all of the OpenGL state when the context changes.
- alpha_function_ref_changed_ = true;
- alpha_blend_settings_changed_ = true;
- stencil_settings_changed_ = true;
- polygon_offset_changed_ = true;
- must_reset_context_ = true;
- }
-}
-#endif
-
-void RendererGL::SetupCgAndOpenGLContext() {
- // NOTE: the first CGerror number after the recreation of a
- // CGcontext (the second time through) seems to be trashed. Please
- // ignore any "CG ERROR: Invalid context handle." message on this
- // function - Invalid context handle isn't one of therror states of
- // cgCreateContext().
- DLOG(INFO) << "OpenGL Vendor: " << ::glGetString(GL_VENDOR);
- DLOG(INFO) << "OpenGL Renderer: " << ::glGetString(GL_RENDERER);
- DLOG(INFO) << "OpenGL Version: " << ::glGetString(GL_VERSION);
- DLOG(INFO) << "Cg Version: " << cgGetString(CG_VERSION);
- cg_vertex_profile_ = cgGLGetLatestProfile(CG_GL_VERTEX);
- cgGLSetOptimalOptions(cg_vertex_profile_);
- DLOG(INFO) << "Best Cg vertex profile = "
- << cgGetProfileString(cg_vertex_profile_);
- cg_fragment_profile_ = cgGLGetLatestProfile(CG_GL_FRAGMENT);
- cgGLSetOptimalOptions(cg_fragment_profile_);
- DLOG(INFO) << "Best Cg fragment profile = "
- << cgGetProfileString(cg_fragment_profile_);
- // Set up all Cg State Assignments for OpenGL.
- cgGLRegisterStates(cg_context_);
- DLOG_CG_ERROR("Registering GL StateAssignments");
- cgGLSetDebugMode(CG_FALSE);
- // Enable the profiles we use.
- cgGLEnableProfile(CG_PROFILE_ARBVP1);
- cgGLEnableProfile(CG_PROFILE_ARBFP1);
- // get some limits for this profile.
- GLint max_vertex_attribs = 0;
- ::glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attribs);
- DLOG(INFO) << "Max Vertex Attribs = " << max_vertex_attribs;
- // Initialize global GL settings.
- // Tell GL that texture buffers can be single-byte aligned.
- ::glPixelStorei(GL_PACK_ALIGNMENT, 1);
- ::glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
- ::glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
- ::glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
- CHECK_GL_ERROR();
-
- GLint viewport[4];
- ::glGetIntegerv(GL_VIEWPORT, &viewport[0]);
- SetClientSize(viewport[2], viewport[3]);
- CHECK_GL_ERROR();
-
- // We need to initialize the front face definition in each context.
- SetBackBufferPlatformSpecific();
-
- if (must_reset_context_) {
- // Apply the initial rendering states to the newly set context.
- SetInitialStates();
- }
-
- must_reset_context_ = false;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/gl/renderer_gl.h b/o3d/core/cross/gl/renderer_gl.h
deleted file mode 100644
index 84b9715..0000000
--- a/o3d/core/cross/gl/renderer_gl.h
+++ /dev/null
@@ -1,347 +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 definition of the RendererGL class that provides
-// low-level access for O3D to graphics hardware using the OpenGL API
-// and Cg Runtime.
-
-#ifndef O3D_CORE_CROSS_GL_RENDERER_GL_H_
-#define O3D_CORE_CROSS_GL_RENDERER_GL_H_
-
-#include "core/cross/gl/gl_headers.h"
-#include <build/build_config.h>
-#include "core/cross/renderer.h"
-#include "core/cross/renderer_platform.h"
-#include "core/cross/types.h"
-#include "core/cross/state.h"
-
-namespace o3d {
-
-class Material;
-class Effect;
-class DrawEffect;
-class SemanticManager;
-
-// Implements the genereric Renderer interface using OpenGL and the Cg Runtime.
-class RendererGL : public Renderer {
- public:
- // Creates a default Renderer.
- static RendererGL* CreateDefault(ServiceLocator* service_locator);
- virtual ~RendererGL();
-
- // Initialises the renderer for use, claiming hardware resources.
- virtual InitStatus InitPlatformSpecific(const DisplayWindow& display,
- bool off_screen);
-
- // Released all hardware resources.
- virtual void Destroy();
-
- // Overridden from Renderer.
- virtual bool GoFullscreen(const DisplayWindow& display,
- int mode_id);
-
- // Overridden from Renderer.
- virtual bool CancelFullscreen(const DisplayWindow& display,
- int width, int height);
-
- // Tells whether we're currently displayed fullscreen or not.
- virtual bool fullscreen() const {
- return fullscreen_;
- }
-
- // Get a vector of the available fullscreen display modes.
- // Clears *modes on error.
- virtual void GetDisplayModes(std::vector<DisplayMode> *modes);
-
- // Get a single fullscreen display mode by id.
- // Returns true on success, false on error.
- virtual bool GetDisplayMode(int id, DisplayMode *mode);
-
- // Resizes the viewport in OpenGL.
- virtual void Resize(int width, int height);
-
- // Creates a StreamBank, returning a platform specific implementation class.
- virtual StreamBank::Ref CreateStreamBank();
-
- // Creates a Primitive, returning a platform specific implementation class.
- virtual Primitive::Ref CreatePrimitive();
-
- // Creates a DrawElement, returning a platform specific implementation
- // class.
- virtual DrawElement::Ref CreateDrawElement();
-
- // Creates and returns a GL specific float buffer.
- virtual VertexBuffer::Ref CreateVertexBuffer();
-
- // Creates and returns a GL specific integer buffer.
- virtual IndexBuffer::Ref CreateIndexBuffer();
-
- // Creates and returns a GL specific Effect object.
- virtual Effect::Ref CreateEffect();
-
- // Creates and returns a GL specific Sampler object.
- virtual Sampler::Ref CreateSampler();
-
- // Creates and returns a platform-specific RenderDepthStencilSurface object
- // for use as a depth-stencil render target.
- virtual RenderDepthStencilSurface::Ref CreateDepthStencilSurface(
- int width,
- int height);
-
- // Overridden from Renderer.
- virtual const int* GetRGBAUByteNSwizzleTable();
-
- // Makes this renderer active on the current thread if it is not active
- // already.
- void MakeCurrentLazy() {
- if (!IsCurrent())
- MakeCurrent();
- }
-
- // Returns whether or not this renderer is active on the current thread.
- // Don't worry, the "get" calls are el cheapo.
- bool IsCurrent() {
-#if defined(OS_MACOSX)
- if ((mac_agl_context_ != NULL) &&
- (mac_agl_context_ == aglGetCurrentContext())) {
- return true;
- } else if ((mac_cgl_context_ != NULL) &&
- (mac_cgl_context_ == CGLGetCurrentContext())) {
- return true;
- }
-#elif defined(OS_WIN)
- if ((gl_context_ != NULL) &&
- (gl_context_ == wglGetCurrentContext())) {
- return true;
- }
-#elif defined(OS_LINUX)
- if ((context_ != NULL) &&
- (context_ == glXGetCurrentContext())) {
- return true;
- }
-#else
- Error: must port RendererGL::IsCurrent() to your platform.
-#endif
- return false;
- }
-
- // Makes this renderer active on the current thread.
- bool MakeCurrent();
-
- inline CGcontext cg_context() const { return cg_context_; }
- inline CGprofile cg_vertex_profile() const { return cg_vertex_profile_; }
- inline CGprofile cg_fragment_profile() const { return cg_fragment_profile_; }
-
-#ifdef OS_MACOSX
- // We need to be able to reset the CGLContextObj when we go into and
- // out of full-screen mode.
- void set_mac_cgl_context(CGLContextObj obj);
-#endif
-
- protected:
- // Keep the constructor protected so only factory methods can create
- // renderers.
- explicit RendererGL(ServiceLocator* service_locator);
-
- // Overridden from Renderer.
- virtual bool PlatformSpecificBeginDraw();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificEndDraw();
-
- // Overridden from Renderer.
- virtual bool PlatformSpecificStartRendering();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificFinishRendering();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificPresent();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificClear(const Float4 &color,
- bool color_flag,
- float depth,
- bool depth_flag,
- int stencil,
- bool stencil_flag);
-
- // Overridden from Renderer.
- virtual ParamCache* CreatePlatformSpecificParamCache();
-
- // Sets the viewport. This is the platform specific version.
- void SetViewportInPixels(int left,
- int top,
- int width,
- int height,
- float min_z,
- float max_z);
-
- // Overridden from Renderer.
- virtual void SetBackBufferPlatformSpecific();
-
- // Overridden from Renderer.
- virtual void SetRenderSurfacesPlatformSpecific(
- const RenderSurface* surface,
- const RenderDepthStencilSurface* depth_surface);
-
- // Overridden from Renderer.
- virtual Texture2D::Ref CreatePlatformSpecificTexture2D(
- int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
- // Overridden from Renderer.
- virtual TextureCUBE::Ref CreatePlatformSpecificTextureCUBE(
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
- // Overridden from Renderer.
- virtual void ApplyDirtyStates();
-
- private:
- // Platform-independent GL initialization
- InitStatus InitCommonGL();
-
- // Platform-independent GL destruction
- void DestroyCommonGL();
-
- // Per-OpenGL context initialization
- void SetupCgAndOpenGLContext();
-
- // Updates the helper constant used to remap D3D clip coordinates to GL ones.
- void UpdateHelperConstant(float width, float height);
-
- ServiceDependency<SemanticManager> semantic_manager_;
-
- // Indicates we're rendering fullscreen rather than in the plugin region.
- bool fullscreen_;
-
-
-#ifdef OS_WIN
- // Handle to the GL device.
- HWND window_;
- HDC device_context_;
- HGLRC gl_context_;
-#endif
-
-#ifdef OS_MACOSX
- AGLContext mac_agl_context_;
- CGLContextObj mac_cgl_context_;
-#endif
-
-#ifdef OS_LINUX
- Display *display_;
- Window window_;
- GLXContext context_;
-#endif
-
- // Handle to the framebuffer-object used while rendering to off-screen
- // targets.
- GLuint render_surface_framebuffer_;
-
- // Cg Runtime variables.
- CGcontext cg_context_;
- CGprofile cg_vertex_profile_;
- CGprofile cg_fragment_profile_;
-
- friend class AlphaReferenceHandler;
- bool alpha_function_ref_changed_;
- GLenum alpha_function_;
- GLclampf alpha_ref_;
-
- friend class BlendFunctionHandler;
- friend class BlendEquationHandler;
- bool alpha_blend_settings_changed_;
- bool separate_alpha_blend_enable_;
- enum {
- RGB,
- ALPHA,
- };
- enum {
- SRC,
- DST,
- };
- GLenum blend_function_[2][2]; // SRC/DST, RGB/ALPHA
- GLenum blend_equation_[2]; // RGB/ALPHA
-
- bool stencil_settings_changed_;
- bool separate_stencil_settings_enable_;
-
- // States for Stencils
- friend class StencilOperationHandler;
- friend class StencilRefHandler;
- friend class StencilMaskHandler;
- struct StencilStates {
- GLenum func_;
- enum {
- FAIL_OP,
- ZFAIL_OP,
- PASS_OP,
- };
- int op_[3];
- };
-
- enum {
- FRONT,
- BACK,
- };
- StencilStates stencil_settings_[2];
-
- enum {
- READ_MASK,
- WRITE_MASK,
- };
- int stencil_mask_[2];
- int stencil_ref_;
-
- // States for PolygonOffset
- friend class PolygonOffset1Handler;
- friend class PolygonOffset2Handler;
- bool polygon_offset_changed_;
- float polygon_offset_factor_;
- float polygon_offset_bias_;
-
- // Dirty flag indicating portions of context state need to be reset.
- bool must_reset_context_;
-
- // Sets the stencils states for either front, back or both facing polys.
- void SetStencilStates(GLenum face, const StencilStates& stencil_states);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GL_RENDERER_GL_H_
diff --git a/o3d/core/cross/gl/sampler_gl.cc b/o3d/core/cross/gl/sampler_gl.cc
deleted file mode 100644
index 6c72d64..0000000
--- a/o3d/core/cross/gl/sampler_gl.cc
+++ /dev/null
@@ -1,217 +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 for SamplerGL.
-
-#include "core/cross/gl/gl_headers.h"
-#include "core/cross/error.h"
-#include "core/cross/gl/renderer_gl.h"
-#include "core/cross/gl/sampler_gl.h"
-
-namespace o3d {
-
-SamplerGL::SamplerGL(ServiceLocator* service_locator)
- : Sampler(service_locator),
- renderer_(static_cast<RendererGL*>(
- service_locator->GetService<Renderer>())) {
-}
-
-SamplerGL::~SamplerGL() {
-}
-
-namespace {
-
-unsigned int GLAddressMode(Sampler::AddressMode o3d_mode,
- unsigned int default_mode) {
- unsigned int gl_mode = default_mode;
- switch (o3d_mode) {
- case Sampler::WRAP:
- gl_mode = GL_REPEAT;
- break;
- case Sampler::MIRROR:
- gl_mode = GL_MIRRORED_REPEAT;
- break;
- case Sampler::CLAMP:
- gl_mode = GL_CLAMP_TO_EDGE;
- break;
- case Sampler::BORDER:
- gl_mode = GL_CLAMP_TO_BORDER;
- break;
- default:
- DLOG(ERROR) << "Unknown Address mode " << static_cast<int>(o3d_mode);
- break;
- }
- return gl_mode;
-}
-
-unsigned int GLMinFilter(Sampler::FilterType o3d_filter,
- Sampler::FilterType mip_filter) {
- switch (o3d_filter) {
- case Sampler::NONE:
- return GL_NEAREST;
- case Sampler::POINT:
- if (mip_filter == Sampler::NONE)
- return GL_NEAREST;
- else if (mip_filter == Sampler::POINT)
- return GL_NEAREST_MIPMAP_NEAREST;
- else if (mip_filter == Sampler::LINEAR)
- return GL_NEAREST_MIPMAP_LINEAR;
- else if (mip_filter == Sampler::ANISOTROPIC)
- return GL_NEAREST_MIPMAP_LINEAR;
- case Sampler::ANISOTROPIC: // Anisotropy is handled in SetTextureAndStates
- case Sampler::LINEAR:
- if (mip_filter == Sampler::NONE)
- return GL_LINEAR;
- else if (mip_filter == Sampler::POINT)
- return GL_LINEAR_MIPMAP_NEAREST;
- else if (mip_filter == Sampler::LINEAR)
- return GL_LINEAR_MIPMAP_LINEAR;
- else if (mip_filter == Sampler::ANISOTROPIC)
- return GL_LINEAR_MIPMAP_LINEAR;
- }
- // fall through
- DLOG(ERROR) << "Unknown filter " << static_cast<int>(o3d_filter);
- DCHECK(false);
- return GL_NONE;
-}
-
-unsigned int GLMagFilter(Sampler::FilterType o3d_filter) {
- switch (o3d_filter) {
- case Sampler::NONE:
- case Sampler::POINT:
- return GL_NEAREST;
- case Sampler::LINEAR:
- case Sampler::ANISOTROPIC:
- return GL_LINEAR;
- default:
- DLOG(ERROR) << "Unknown filter " << static_cast<int>(o3d_filter);
- return GL_LINEAR;
- }
-}
-
-GLenum GLTextureTarget(Texture* texture) {
- if (texture->IsA(Texture2D::GetApparentClass())) {
- return GL_TEXTURE_2D;
- } else if (texture->IsA(TextureCUBE::GetApparentClass())) {
- return GL_TEXTURE_CUBE_MAP;
- } else {
- DLOG(ERROR) << "Unknown texture target";
- return 0;
- }
-}
-
-} // namespace
-
-void SamplerGL::SetTextureAndStates(CGparameter cg_param) {
- // Get the texture object associated with this sampler.
- Texture* texture_object = texture();
-
- if (!texture_object) {
- texture_object = renderer_->error_texture();
- if (!texture_object) {
- O3D_ERROR(service_locator())
- << "Missing texture for sampler " << name();
- texture_object = renderer_->fallback_error_texture();
- }
- }
-
- if (!renderer_->SafeToBindTexture(texture_object)) {
- O3D_ERROR(renderer_->service_locator())
- << "Attempt to bind texture, " << texture_object->name()
- << " when drawing to same texture as a RenderSurface";
- texture_object = renderer_->error_texture();
- }
-
- GLuint handle = static_cast<GLuint>(reinterpret_cast<intptr_t>(
- texture_object->GetTextureHandle()));
- if (handle) {
- cgGLSetTextureParameter(cg_param, handle);
- cgGLEnableTextureParameter(cg_param);
- } else {
- cgGLSetTextureParameter(cg_param, 0);
- cgGLDisableTextureParameter(cg_param);
- return;
- }
-
- // TODO: this is a slow check and needs to be moved to initialization
- // time.
- GLenum target = GLTextureTarget(texture_object);
-
- if (target) {
- GLenum texture_unit = cgGLGetTextureEnum(cg_param);
- ::glActiveTextureARB(texture_unit);
- glBindTexture(target, handle);
- glTexParameteri(target,
- GL_TEXTURE_WRAP_S,
- GLAddressMode(address_mode_u(), GL_REPEAT));
- glTexParameteri(target,
- GL_TEXTURE_WRAP_T,
- GLAddressMode(address_mode_v(), GL_REPEAT));
- if (texture_object->IsA(TextureCUBE::GetApparentClass())) {
- glTexParameteri(target,
- GL_TEXTURE_WRAP_R,
- GLAddressMode(address_mode_w(), GL_REPEAT));
- }
- glTexParameteri(target,
- GL_TEXTURE_MIN_FILTER,
- GLMinFilter(min_filter(), mip_filter()));
- glTexParameteri(target,
- GL_TEXTURE_MAG_FILTER,
- GLMagFilter(mag_filter()));
-
- Float4 color = border_color();
- GLfloat gl_color[4] = {color[0], color[1], color[2], color[3]};
- glTexParameterfv(target, GL_TEXTURE_BORDER_COLOR, gl_color);
-
- // Check for anisotropic texture filtering.
- if (GLEW_EXT_texture_filter_anisotropic) {
- int gl_max_anisotropy =
- (min_filter() == ANISOTROPIC) ? max_anisotropy() : 1;
- glTexParameteri(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, gl_max_anisotropy);
- }
- }
-}
-
-void SamplerGL::ResetTexture(CGparameter cg_param) {
- Texture* the_texture = texture();
- if (the_texture) {
- // TODO: this is a slow check and needs to be moved to initialization
- // time.
- GLenum target = GLTextureTarget(the_texture);
- if (target) {
- GLenum texture_unit = cgGLGetTextureEnum(cg_param);
- glActiveTextureARB(texture_unit);
- glBindTexture(target, 0);
- }
- }
-}
-} // namespace o3d
diff --git a/o3d/core/cross/gl/sampler_gl.h b/o3d/core/cross/gl/sampler_gl.h
deleted file mode 100644
index 3ec6a28..0000000
--- a/o3d/core/cross/gl/sampler_gl.h
+++ /dev/null
@@ -1,65 +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 class declaration for SamplerGL.
-
-#ifndef O3D_CORE_CROSS_GL_SAMPLER_GL_H_
-#define O3D_CORE_CROSS_GL_SAMPLER_GL_H_
-
-#include "core/cross/sampler.h"
-
-namespace o3d {
-
-class RendererGL;
-
-// SamplerGL is an implementation of the Sampler object for GL.
-class SamplerGL : public Sampler {
- public:
- explicit SamplerGL(ServiceLocator* service_locator);
- virtual ~SamplerGL();
-
- // Sets the gl texture and sampler states.
- void SetTextureAndStates(CGparameter cg_param);
-
- // Unbinds the GL texture.
- void ResetTexture(CGparameter cg_param);
-
- private:
-
- RendererGL* renderer_;
-
- DISALLOW_COPY_AND_ASSIGN(SamplerGL);
-};
-} // namespace o3d
-
-
-#endif // O3D_CORE_CROSS_GL_SAMPLER_GL_H_
diff --git a/o3d/core/cross/gl/stream_bank_gl.cc b/o3d/core/cross/gl/stream_bank_gl.cc
deleted file mode 100644
index 72b93fa..0000000
--- a/o3d/core/cross/gl/stream_bank_gl.cc
+++ /dev/null
@@ -1,201 +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 definition of StreamBankGL.
-
-#include <algorithm>
-
-#include "core/cross/stream.h"
-#include "core/cross/error.h"
-#include "core/cross/gl/buffer_gl.h"
-#include "core/cross/gl/effect_gl.h"
-#include "core/cross/gl/stream_bank_gl.h"
-#include "core/cross/gl/renderer_gl.h"
-#include "core/cross/gl/draw_element_gl.h"
-#include "core/cross/gl/utils_gl-inl.h"
-#include "Cg/cgGL.h"
-
-// Someone defines min, conflicting with std::min
-#ifdef min
-#undef min
-#endif
-
-namespace o3d {
-
-namespace {
-
-// Converts from a Field datatype to a suitable GL type
-GLenum GLDataType(const Field& field) {
- if (field.IsA(FloatField::GetApparentClass())) {
- return GL_FLOAT;
- } else if (field.IsA(UByteNField::GetApparentClass())) {
- switch (field.num_components()) {
- case 4:
- return GL_UNSIGNED_BYTE;
- }
- }
- DLOG(ERROR) << "Unknown Stream DataType";
- return GL_INVALID_ENUM;
-}
-
-} // anonymous namespace
-
-// Number of times to log a repeated event before giving up.
-const int kNumLoggedEvents = 5;
-
-// StreamBankGL functions ------------------------------------------------------
-
-StreamBankGL::StreamBankGL(ServiceLocator* service_locator)
- : StreamBank(service_locator) {
- DLOG(INFO) << "StreamBankGL Construct";
-}
-
-StreamBankGL::~StreamBankGL() {
- DLOG(INFO) << "StreamBankGL Destruct";
-}
-
-bool StreamBankGL::CheckForMissingVertexStreams(
- ParamCacheGL::VaryingParameterMap& varying_map,
- Stream::Semantic* missing_semantic,
- int* missing_semantic_index) {
- DCHECK(missing_semantic);
- DCHECK(missing_semantic_index);
- DLOG(INFO) << "StreamBankGL InsertMissingVertexStreams";
- // Match CG_VARYING parameters to Buffers with the matching semantics.
- ParamCacheGL::VaryingParameterMap::iterator i;
- for (i = varying_map.begin(); i != varying_map.end(); ++i) {
- CGparameter cg_param = i->first;
- const char* semantic_string = cgGetParameterSemantic(cg_param);
- int attr = SemanticNameToGLVertexAttribute(semantic_string);
- int index = 0;
- Stream::Semantic semantic = GLVertexAttributeToStream(attr, &index);
- int stream_index = FindVertexStream(semantic, index);
- if (stream_index >= 0) {
- // record the matched stream into the varying parameter map for later
- // use by StreamBankGL::Draw().
- i->second = stream_index;
- DLOG(INFO)
- << "StreamBankGL Matched CG_PARAMETER \""
- << cgGetParameterName(cg_param) << " : "
- << semantic_string << "\" to stream "
- << stream_index << " \""
- << vertex_stream_params_.at(
- stream_index)->stream().field().buffer()->name()
- << "\"";
- } else {
- // no matching stream was found.
- *missing_semantic = semantic;
- *missing_semantic_index = index;
- return false;
- }
- }
- CHECK_GL_ERROR();
- return true;
-}
-
-bool StreamBankGL::BindStreamsForRendering(
- const ParamCacheGL::VaryingParameterMap& varying_map,
- unsigned int* max_vertices) {
- *max_vertices = UINT_MAX;
- // Loop over varying params setting up the streams.
- ParamCacheGL::VaryingParameterMap::const_iterator i;
- for (i = varying_map.begin(); i != varying_map.end(); ++i) {
- const Stream& stream = vertex_stream_params_.at(i->second)->stream();
- const Field& field = stream.field();
- GLenum type = GLDataType(field);
- if (type == GL_INVALID_ENUM) {
- // TODO: support other kinds of buffers.
- O3D_ERROR(service_locator())
- << "unsupported field of type '" << field.GetClassName()
- << "' on StreamBank '" << name() << "'";
- return false;
- }
- VertexBufferGL *vbuffer = down_cast<VertexBufferGL*>(field.buffer());
- if (!vbuffer) {
- O3D_ERROR(service_locator())
- << "stream has no buffer in StreamBank '" << name() << "'";
- return false;
- }
- // TODO support all data types and packings here. Currently it
- // only supports GL_FLOAT buffers, but buffers of GL_HALF and GL_INT are
- // also possible as streamed parameter inputs.
- GLint element_count = field.num_components();
- if (element_count > 4) {
- element_count = 0;
- DLOG_FIRST_N(ERROR, kNumLoggedEvents)
- << "Unable to find stream for CGparameter: "
- << cgGetParameterName(i->first);
- }
-
- // In the num_elements = 1 case we want to do the D3D stride = 0 thing.
- // but see below.
- if (vbuffer->num_elements() == 1) {
- // TODO: passing a stride of 0 has a different meaning in GL
- // (compute a stride as if it was packed) than in DX (re-use the vertex
- // over and over again). The equivalent of the DX behavior is by
- // disabling the vertex array, and setting a constant value. Currently,
- // this just avoids de-referencing outside of the vertex buffer, but it
- // doesn't set the proper value: we'd need to map the buffer, get the
- // value, and unmap it (slow !!). A better solution is to disallow 0
- // stride at the API level, and instead maybe provide a way to pss a
- // constant value - but the DX version relies on being able to pass a 0
- // stride, so the whole thing needs a bit of rewrite.
- cgGLDisableClientState(i->first);
- } else {
- glBindBufferARB(GL_ARRAY_BUFFER, vbuffer->gl_buffer());
- cgGLSetParameterPointer(i->first,
- element_count,
- GLDataType(field),
- vbuffer->stride(),
- BUFFER_OFFSET(field.offset()));
- cgGLEnableClientState(i->first);
- *max_vertices = std::min(*max_vertices, stream.GetMaxVertices());
- }
- }
- return true;
-}
-
-// private member functions ----------------------------------------------------
-
-// Searches the array of streams and returns the index of the stream that
-// matches the semantic and index pair. if no match was found, return "-1"
-int StreamBankGL::FindVertexStream(Stream::Semantic semantic, int index) {
- for (unsigned ii = 0; ii < vertex_stream_params_.size(); ++ii) {
- const Stream& stream = vertex_stream_params_[ii]->stream();
- if (stream.semantic() == semantic && stream.semantic_index() == index) {
- return static_cast<int>(ii);
- }
- }
- return -1;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/gl/stream_bank_gl.h b/o3d/core/cross/gl/stream_bank_gl.h
deleted file mode 100644
index 802a88b..0000000
--- a/o3d/core/cross/gl/stream_bank_gl.h
+++ /dev/null
@@ -1,72 +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 declaration of the StreamBankGL class.
-
-#ifndef O3D_CORE_CROSS_GL_STREAM_BANK_GL_H_
-#define O3D_CORE_CROSS_GL_STREAM_BANK_GL_H_
-
-#include <map>
-#include "core/cross/stream_bank.h"
-#include "core/cross/gl/param_cache_gl.h"
-
-namespace o3d {
-
-// StreamBankGL is the OpenGL implementation of the StreamBank.
-class StreamBankGL : public StreamBank {
- public:
- explicit StreamBankGL(ServiceLocator* service_locator);
- virtual ~StreamBankGL();
-
- // Sets the streams for rendering.
- // Parameter:
- // varying_map: Map of streams.
- // max_vertrices: pointer to variable to receive the maximum vertices
- // the streams can render.
- // Returns:
- // true if all streams were bound.
- bool BindStreamsForRendering(
- const ParamCacheGL::VaryingParameterMap& varying_map,
- unsigned int* max_vertices);
-
- // Checks for all required streams before rendering.
- bool CheckForMissingVertexStreams(
- ParamCacheGL::VaryingParameterMap& varying_map,
- Stream::Semantic* missing_semantic,
- int* missing_semantic_index);
-
- private:
- int FindVertexStream(Stream::Semantic semantic, int index);
-};
-} // o3d
-
-#endif // O3D_CORE_CROSS_GL_STREAM_BANK_GL_H_
diff --git a/o3d/core/cross/gl/texture_gl.cc b/o3d/core/cross/gl/texture_gl.cc
deleted file mode 100644
index 7626e8e..0000000
--- a/o3d/core/cross/gl/texture_gl.cc
+++ /dev/null
@@ -1,884 +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.
- */
-
-
-// Implementations of the abstract Texture2D and TextureCUBE classes using
-// the OpenGL graphics API.
-
-#include "core/cross/gl/gl_headers.h"
-#include "core/cross/error.h"
-#include "core/cross/types.h"
-#include "core/cross/pointer_utils.h"
-#include "core/cross/gl/renderer_gl.h"
-#include "core/cross/gl/render_surface_gl.h"
-#include "core/cross/gl/texture_gl.h"
-#include "core/cross/gl/utils_gl.h"
-#include "core/cross/gl/utils_gl-inl.h"
-
-namespace o3d {
-
-namespace {
-
-Texture::RGBASwizzleIndices g_gl_abgr32f_swizzle_indices = {0, 1, 2, 3};
-
-} // anonymous namespace.
-
-// Converts an O3D texture format to a GL texture format.
-// Input is 'format'.
-// GL has 2 notions of the format:
-// - the internal format which describes how the format should be stored on the
-// GPU
-// - the (format, type) pair which describes how the input data to glTexImage2D
-// is laid out. If format is 0, the data is compressed and needs to be passed
-// to glCompressedTexImage2D.
-// The internal format is returned in internal_format.
-// The format is the return value of the function.
-// The type is returned in data_type.
-static GLenum GLFormatFromO3DFormat(Texture::Format format,
- GLenum *internal_format,
- GLenum *data_type) {
- switch (format) {
- case Texture::XRGB8: {
- *internal_format = GL_RGB;
- *data_type = GL_UNSIGNED_BYTE;
- return GL_BGRA;
- }
- case Texture::ARGB8: {
- *internal_format = GL_RGBA;
- *data_type = GL_UNSIGNED_BYTE;
- return GL_BGRA;
- }
- case Texture::ABGR16F: {
- *internal_format = GL_RGBA16F_ARB;
- *data_type = GL_HALF_FLOAT_ARB;
- return GL_RGBA;
- }
- case Texture::R32F: {
- *internal_format = GL_LUMINANCE32F_ARB;
- *data_type = GL_FLOAT;
- return GL_LUMINANCE;
- }
- case Texture::ABGR32F: {
- *internal_format = GL_RGBA32F_ARB;
- *data_type = GL_FLOAT;
- return GL_BGRA;
- }
- case Texture::DXT1: {
- if (GL_EXT_texture_compression_s3tc) {
- *internal_format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
- *data_type = 0;
- return 0;
- } else {
- // TODO: we need to convert DXT1 -> RGBA8 but keep around the
- // pixels so that we can read them back (we won't try to convert back
- // to DXTC).
- LOG(ERROR) << "DXT1 compressed textures not supported yet.";
- *internal_format = 0;
- *data_type = GL_BYTE;
- return 0;
- }
- }
- case Texture::DXT3: {
- if (GL_EXT_texture_compression_s3tc) {
- *internal_format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
- *data_type = 0;
- return 0;
- } else {
- // TODO: we need to convert DXT3 -> RGBA8 but keep around the
- // pixels so that we can read them back (we won't try to convert back
- // to DXTC).
- LOG(ERROR) << "DXT3 compressed textures not supported yet.";
- *internal_format = 0;
- *data_type = GL_BYTE;
- return 0;
- }
- }
- case Texture::DXT5: {
- if (GL_EXT_texture_compression_s3tc) {
- *internal_format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
- *data_type = 0;
- return 0;
- } else {
- // TODO: we need to convert DXT3 -> RGBA8 but keep around the
- // pixels so that we can read them back (we won't try to convert back
- // to DXTC).
- LOG(ERROR) << "DXT5 compressed textures not supported yet.";
- *internal_format = 0;
- *data_type = GL_BYTE;
- return 0;
- }
- }
- case Texture::UNKNOWN_FORMAT:
- break;
- }
- // failed to find a matching format
- LOG(ERROR) << "Unrecognized Texture format type.";
- *internal_format = 0;
- *data_type = 0;
- return 0;
-}
-
-// Updates a GL image from a bitmap, rescaling if necessary.
-static bool UpdateGLImageFromBitmap(GLenum target,
- unsigned int level,
- TextureCUBE::CubeFace face,
- const Bitmap &bitmap,
- bool resize_to_pot) {
- DCHECK(bitmap.image_data());
- unsigned int mip_width = std::max(1U, bitmap.width() >> level);
- unsigned int mip_height = std::max(1U, bitmap.height() >> level);
- const uint8 *mip_data = bitmap.GetMipData(level);
- size_t mip_size =
- image::ComputeBufferSize(mip_width, mip_height, bitmap.format());
- scoped_array<uint8> temp_data;
- if (resize_to_pot) {
- DCHECK(!Texture::IsCompressedFormat(bitmap.format()));
- unsigned int pot_width =
- std::max(1U, image::ComputePOTSize(bitmap.width()) >> level);
- unsigned int pot_height =
- std::max(1U, image::ComputePOTSize(bitmap.height()) >> level);
- size_t pot_size = image::ComputeBufferSize(pot_width, pot_height,
- bitmap.format());
- temp_data.reset(new uint8[pot_size]);
- image::Scale(mip_width, mip_height, bitmap.format(), mip_data,
- pot_width, pot_height, temp_data.get(),
- image::ComputePitch(bitmap.format(), pot_width));
- mip_width = pot_width;
- mip_height = pot_height;
- mip_size = pot_size;
- mip_data = temp_data.get();
- }
- GLenum gl_internal_format = 0;
- GLenum gl_data_type = 0;
- GLenum gl_format = GLFormatFromO3DFormat(bitmap.format(), &gl_internal_format,
- &gl_data_type);
- FlushGlErrors();
- if (gl_format) {
- glTexSubImage2D(target, level, 0, 0, mip_width, mip_height,
- gl_format, gl_data_type, mip_data);
- } else {
- glCompressedTexSubImage2D(target, level, 0, 0, mip_width, mip_height,
- gl_internal_format, mip_size, mip_data);
- }
- return glGetError() == GL_NO_ERROR;
-}
-
-// Creates the array of GL images for a particular face and upload the pixel
-// data from the bitmap.
-static bool CreateGLImages(GLenum target,
- GLenum internal_format,
- GLenum gl_format,
- GLenum type,
- TextureCUBE::CubeFace face,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool resize_to_pot) {
- unsigned int mip_width = width;
- unsigned int mip_height = height;
- if (resize_to_pot) {
- mip_width = image::ComputePOTSize(mip_width);
- mip_height = image::ComputePOTSize(mip_height);
- }
- // glCompressedTexImage2D does't accept NULL as a parameter, so we need
- // to pass in some data. If we can pass in the original pixel data, we'll
- // do that, otherwise we'll pass an empty buffer. In that case, prepare it
- // here once for all.
- scoped_array<uint8> temp_data;
- size_t size = image::ComputeBufferSize(mip_width, mip_height, format);
- temp_data.reset(new uint8[size]);
- memset(temp_data.get(), 0, size);
-
- for (int i = 0; i < levels; ++i) {
- FlushGlErrors();
- if (gl_format) {
- glTexImage2D(target, i, internal_format, mip_width, mip_height,
- 0, gl_format, type, temp_data.get());
- if (glGetError() != GL_NO_ERROR) {
- DLOG(ERROR) << "glTexImage2D failed";
- return false;
- }
- } else {
- size_t mip_size = image::ComputeBufferSize(mip_width, mip_height, format);
- glCompressedTexImage2DARB(target, i, internal_format, mip_width,
- mip_height, 0, mip_size, temp_data.get());
- if (glGetError() != GL_NO_ERROR) {
- DLOG(ERROR) << "glCompressedTexImage2D failed";
- return false;
- }
- }
- mip_width = std::max(1U, mip_width >> 1);
- mip_height = std::max(1U, mip_height >> 1);
- }
- return true;
-}
-
-// Texture2DGL -----------------------------------------------------------------
-
-// Constructs a 2D texture object from an existing OpenGL 2D texture.
-// NOTE: the Texture2DGL now owns the GL texture and will destroy it on exit.
-Texture2DGL::Texture2DGL(ServiceLocator* service_locator,
- GLint texture,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool resize_to_pot,
- bool enable_render_surfaces)
- : Texture2D(service_locator,
- width,
- height,
- format,
- levels,
- enable_render_surfaces),
- resize_to_pot_(resize_to_pot),
- renderer_(static_cast<RendererGL*>(
- service_locator->GetService<Renderer>())),
- gl_texture_(texture),
- backing_bitmap_(Bitmap::Ref(new Bitmap(service_locator))),
- has_levels_(0),
- locked_levels_(0) {
- DLOG(INFO) << "Texture2DGL Construct from GLint";
- DCHECK_NE(format, Texture::UNKNOWN_FORMAT);
-}
-
-// Creates a new texture object from scratch.
-Texture2DGL* Texture2DGL::Create(ServiceLocator* service_locator,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool enable_render_surfaces) {
- DLOG(INFO) << "Texture2DGL Create";
- DCHECK_NE(format, Texture::UNKNOWN_FORMAT);
- DCHECK_GE(levels, 0);
- RendererGL *renderer = static_cast<RendererGL *>(
- service_locator->GetService<Renderer>());
- renderer->MakeCurrentLazy();
- GLenum gl_internal_format = 0;
- GLenum gl_data_type = 0;
- GLenum gl_format = GLFormatFromO3DFormat(format,
- &gl_internal_format,
- &gl_data_type);
- if (gl_internal_format == 0) {
- DLOG(ERROR) << "Unsupported format in Texture2DGL::Create.";
- return NULL;
- }
-
- bool resize_to_pot = !renderer->supports_npot() &&
- !image::IsPOT(width, height);
-
- // Creates the OpenGL texture object, with all the required mip levels.
- GLuint gl_texture = 0;
- glGenTextures(1, &gl_texture);
- glBindTexture(GL_TEXTURE_2D, gl_texture);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL,
- levels - 1);
-
- if (!CreateGLImages(GL_TEXTURE_2D, gl_internal_format, gl_format,
- gl_data_type, TextureCUBE::FACE_POSITIVE_X,
- format, levels, width, height, resize_to_pot)) {
- DLOG(ERROR) << "Failed to create texture images.";
- glDeleteTextures(1, &gl_texture);
- return NULL;
- }
- glTexParameteri(GL_TEXTURE_2D,
- GL_TEXTURE_MIN_FILTER,
- GL_NEAREST_MIPMAP_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
-
- GLint gl_width;
- GLint gl_height;
- glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &gl_width);
- glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &gl_height);
-
- DLOG(INFO) << "Created 2D texture (size=" << gl_width << "x" << gl_height
- << ", GLuint=" << gl_texture << ")";
- Texture2DGL *texture = new Texture2DGL(service_locator,
- gl_texture,
- format,
- levels,
- width,
- height,
- resize_to_pot,
- enable_render_surfaces);
-
- // If the hardware does not support npot textures, allocate a 0-initialized
- // mip-chain here for use during Texture2DGL::Lock.
- if (resize_to_pot) {
- texture->backing_bitmap_->Allocate(format, width, height, levels,
- Bitmap::IMAGE);
- texture->has_levels_ = (1 << levels) - 1;
- }
- CHECK_GL_ERROR();
- return texture;
-}
-
-void Texture2DGL::UpdateBackedMipLevel(unsigned int level) {
- DCHECK_LT(static_cast<int>(level), levels());
- DCHECK(backing_bitmap_->image_data());
- DCHECK_EQ(backing_bitmap_->width(), static_cast<unsigned int>(width()));
- DCHECK_EQ(backing_bitmap_->height(), static_cast<unsigned int>(height()));
- DCHECK_EQ(backing_bitmap_->format(), format());
- renderer_->MakeCurrentLazy();
- glBindTexture(GL_TEXTURE_2D, gl_texture_);
- UpdateGLImageFromBitmap(GL_TEXTURE_2D, level, TextureCUBE::FACE_POSITIVE_X,
- *backing_bitmap_.Get(), resize_to_pot_);
-}
-
-Texture2DGL::~Texture2DGL() {
- DLOG(INFO) << "Texture2DGL Destruct";
- if (gl_texture_) {
- renderer_->MakeCurrentLazy();
- glDeleteTextures(1, &gl_texture_);
- gl_texture_ = 0;
- }
- CHECK_GL_ERROR();
-}
-
-void Texture2DGL::SetRect(int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned src_width,
- unsigned src_height,
- const void* src_data,
- int src_pitch) {
- if (level >= levels() || level < 0) {
- O3D_ERROR(service_locator())
- << "Trying to SetRect on non-existent level " << level
- << " on Texture \"" << name() << "\"";
- return;
- }
- if (render_surfaces_enabled()) {
- O3D_ERROR(service_locator())
- << "Attempting to SetRect a render-target texture: " << name();
- return;
- }
-
- unsigned mip_width = image::ComputeMipDimension(level, width());
- unsigned mip_height = image::ComputeMipDimension(level, height());
-
- if (dst_left + src_width > mip_width ||
- dst_top + src_height > mip_height) {
- O3D_ERROR(service_locator())
- << "SetRect(" << level << ", " << dst_left << ", " << dst_top << ", "
- << src_width << ", " << src_height << ") out of range for texture << \""
- << name() << "\"";
- return;
- }
-
- bool entire_rect = dst_left == 0 && dst_top == 0 &&
- src_width == mip_width && src_height == mip_height;
- bool compressed = IsCompressed();
-
- if (compressed && !entire_rect) {
- O3D_ERROR(service_locator())
- << "SetRect must be full rectangle for compressed textures";
- return;
- }
-
- if (resize_to_pot_) {
- DCHECK(backing_bitmap_->image_data());
- DCHECK(!compressed);
- // We need to update the backing mipmap and then use that to update the
- // texture.
- backing_bitmap_->SetRect(
- level, dst_left, dst_top, src_width, src_height, src_data, src_pitch);
- UpdateBackedMipLevel(level);
- } else {
- renderer_->MakeCurrentLazy();
- glBindTexture(GL_TEXTURE_2D, gl_texture_);
- GLenum gl_internal_format = 0;
- GLenum gl_data_type = 0;
- GLenum gl_format = GLFormatFromO3DFormat(format(), &gl_internal_format,
- &gl_data_type);
- if (gl_format) {
- if (src_pitch == image::ComputePitch(format(), src_width)) {
- glTexSubImage2D(GL_TEXTURE_2D, level,
- dst_left, dst_top,
- src_width, src_height,
- gl_format,
- gl_data_type,
- src_data);
- } else {
- int limit = src_height;
- for (int yy = 0; yy < limit; ++yy) {
- glTexSubImage2D(GL_TEXTURE_2D, level,
- dst_left, dst_top + yy,
- src_width, 1,
- gl_format,
- gl_data_type,
- src_data);
- src_data = AddPointerOffset<const void*>(src_data, src_pitch);
- }
- }
- } else {
- glCompressedTexSubImage2D(
- GL_TEXTURE_2D, level, 0, 0, src_width, src_height,
- gl_internal_format,
- image::ComputeMipChainSize(src_width, src_height, format(), 1),
- src_data);
- }
- }
- if (level == 0) {
- TextureUpdated();
- }
-}
-
-// Locks the given mipmap level of this texture for loading from main memory,
-// and returns a pointer to the buffer.
-bool Texture2DGL::PlatformSpecificLock(
- int level, void** data, int* pitch, Texture::AccessMode mode) {
- DLOG(INFO) << "Texture2DGL Lock";
- DCHECK(data);
- DCHECK(pitch);
- DCHECK_GE(level, 0);
- DCHECK_LT(level, levels());
- renderer_->MakeCurrentLazy();
- if (!backing_bitmap_->image_data()) {
- DCHECK_EQ(has_levels_, 0u);
- backing_bitmap_->Allocate(format(), width(), height(), levels(),
- Bitmap::IMAGE);
- }
- *data = backing_bitmap_->GetMipData(level);
- unsigned int mip_width = image::ComputeMipDimension(level, width());
- if (!IsCompressed()) {
- *pitch = image::ComputePitch(format(), mip_width);
- } else {
- unsigned blocks_across = (mip_width + 3) / 4;
- unsigned bytes_per_block = format() == Texture::DXT1 ? 8 : 16;
- unsigned bytes_per_row = bytes_per_block * blocks_across;
- *pitch = bytes_per_row;
- }
- if (mode != kWriteOnly && !HasLevel(level)) {
- DCHECK(!resize_to_pot_);
- GLenum gl_internal_format = 0;
- GLenum gl_data_type = 0;
- GLenum gl_format = GLFormatFromO3DFormat(format(),
- &gl_internal_format,
- &gl_data_type);
- glBindTexture(GL_TEXTURE_2D, gl_texture_);
- glGetTexImage(GL_TEXTURE_2D, level, gl_format, gl_data_type, *data);
- has_levels_ |= 1 << level;
- }
- locked_levels_ |= 1 << level;
- CHECK_GL_ERROR();
- return true;
-}
-
-// Unlocks the given mipmap level of this texture, uploading the main memory
-// data buffer to GL.
-bool Texture2DGL::PlatformSpecificUnlock(int level) {
- DLOG(INFO) << "Texture2DGL Unlock";
- DCHECK_GE(level, 0);
- DCHECK_LT(level, levels());
- if (LockedMode(level) != kReadOnly) {
- renderer_->MakeCurrentLazy();
- UpdateBackedMipLevel(level);
- }
- locked_levels_ &= ~(1 << level);
- if (!resize_to_pot_ && (locked_levels_ == 0)) {
- backing_bitmap_->FreeData();
- has_levels_ = 0;
- }
- CHECK_GL_ERROR();
- return true;
-}
-
-RenderSurface::Ref Texture2DGL::PlatformSpecificGetRenderSurface(
- int mip_level) {
- DCHECK_LT(mip_level, levels());
- if (!render_surfaces_enabled()) {
- O3D_ERROR(service_locator())
- << "Attempting to get RenderSurface from non-render-surface-enabled"
- << " Texture: " << name();
- return RenderSurface::Ref(NULL);
- }
-
- if (mip_level >= levels() || mip_level < 0) {
- O3D_ERROR(service_locator())
- << "Attempting to access non-existent mip_level " << mip_level
- << " in render-target texture \"" << name() << "\".";
- return RenderSurface::Ref(NULL);
- }
-
- return RenderSurface::Ref(new RenderSurfaceGL(
- service_locator(),
- width()>> mip_level,
- height() >> mip_level,
- 0,
- mip_level,
- this));
-}
-
-const Texture::RGBASwizzleIndices& Texture2DGL::GetABGR32FSwizzleIndices() {
- return g_gl_abgr32f_swizzle_indices;
-}
-
-// TextureCUBEGL ---------------------------------------------------------------
-
-// Creates a texture from a pre-existing GL texture object.
-TextureCUBEGL::TextureCUBEGL(ServiceLocator* service_locator,
- GLint texture,
- Texture::Format format,
- int levels,
- int edge_length,
- bool resize_to_pot,
- bool enable_render_surfaces)
- : TextureCUBE(service_locator,
- edge_length,
- format,
- levels,
- enable_render_surfaces),
- resize_to_pot_(resize_to_pot),
- renderer_(static_cast<RendererGL*>(
- service_locator->GetService<Renderer>())),
- gl_texture_(texture) {
- DLOG(INFO) << "TextureCUBEGL Construct";
- for (int ii = 0; ii < static_cast<int>(NUMBER_OF_FACES); ++ii) {
- backing_bitmaps_[ii] = Bitmap::Ref(new Bitmap(service_locator));
- has_levels_[ii] = 0;
- locked_levels_[ii] = 0;
- }
-}
-
-TextureCUBEGL::~TextureCUBEGL() {
- DLOG(INFO) << "TextureCUBEGL Destruct";
- if (gl_texture_) {
- renderer_->MakeCurrentLazy();
- glDeleteTextures(1, &gl_texture_);
- gl_texture_ = 0;
- }
- CHECK_GL_ERROR();
-}
-
-static const int kCubemapFaceList[] = {
- GL_TEXTURE_CUBE_MAP_POSITIVE_X,
- GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
- GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
- GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
- GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
- GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
-};
-
-// Create a new Cube texture from scratch.
-TextureCUBEGL* TextureCUBEGL::Create(ServiceLocator* service_locator,
- Texture::Format format,
- int levels,
- int edge_length,
- bool enable_render_surfaces) {
- DLOG(INFO) << "TextureCUBEGL Create";
- CHECK_GL_ERROR();
- RendererGL *renderer = static_cast<RendererGL *>(
- service_locator->GetService<Renderer>());
- renderer->MakeCurrentLazy();
-
- bool resize_to_pot = !renderer->supports_npot() &&
- !image::IsPOT(edge_length, edge_length);
-
- // Get gl formats
- GLenum gl_internal_format = 0;
- GLenum gl_data_type = 0;
- GLenum gl_format = GLFormatFromO3DFormat(format,
- &gl_internal_format,
- &gl_data_type);
- if (gl_internal_format == 0) {
- DLOG(ERROR) << "Unsupported format in TextureCUBEGL::Create.";
- return NULL;
- }
-
- // Creates the OpenGL texture object, with all the required mip levels.
- GLuint gl_texture = 0;
- glGenTextures(1, &gl_texture);
- glBindTexture(GL_TEXTURE_CUBE_MAP, gl_texture);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL,
- levels - 1);
-
- for (int face = 0; face < static_cast<int>(NUMBER_OF_FACES); ++face) {
- CreateGLImages(kCubemapFaceList[face], gl_internal_format,
- gl_format, gl_data_type,
- static_cast<CubeFace>(face),
- format, levels, edge_length, edge_length,
- resize_to_pot);
- }
- glTexParameteri(GL_TEXTURE_CUBE_MAP,
- GL_TEXTURE_MIN_FILTER,
- GL_NEAREST_MIPMAP_LINEAR);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-
- // Create a new texture object, which initializes the base Texture class
- // from the Bitmap information.
- TextureCUBEGL* texture = new TextureCUBEGL(service_locator,
- gl_texture,
- format,
- levels,
- edge_length,
- resize_to_pot,
- enable_render_surfaces);
- // If the hardware does not support npot textures, allocate a 0-initialized
- // mip-chain here for use during TextureCUBEGL::Lock.
- if (resize_to_pot) {
- for (int face = 0; face < static_cast<int>(NUMBER_OF_FACES); ++face) {
- texture->backing_bitmaps_[face]->Allocate(
- format, edge_length, edge_length, levels, Bitmap::IMAGE);
- texture->has_levels_[face] = (1 << levels) - 1;
- }
- }
- CHECK_GL_ERROR();
- DLOG(INFO) << "Created cube map texture (GLuint=" << gl_texture << ")";
- return texture;
-}
-
-void TextureCUBEGL::UpdateBackedMipLevel(unsigned int level,
- TextureCUBE::CubeFace face) {
- Bitmap* backing_bitmap = backing_bitmaps_[face].Get();
- DCHECK_LT(static_cast<int>(level), levels());
- DCHECK(backing_bitmap->image_data());
- DCHECK_EQ(backing_bitmap->width(), static_cast<unsigned int>(edge_length()));
- DCHECK_EQ(backing_bitmap->height(), static_cast<unsigned int>(edge_length()));
- DCHECK_EQ(backing_bitmap->format(), format());
- renderer_->MakeCurrentLazy();
- glBindTexture(GL_TEXTURE_2D, gl_texture_);
- UpdateGLImageFromBitmap(kCubemapFaceList[face], level, face,
- *backing_bitmap,
- resize_to_pot_);
-}
-
-RenderSurface::Ref TextureCUBEGL::PlatformSpecificGetRenderSurface(
- TextureCUBE::CubeFace face,
- int mip_level) {
- DCHECK_LT(mip_level, levels());
- if (!render_surfaces_enabled()) {
- O3D_ERROR(service_locator())
- << "Attempting to get RenderSurface from non-render-surface-enabled"
- << " Texture: " << name();
- return RenderSurface::Ref(NULL);
- }
-
- if (mip_level >= levels() || mip_level < 0) {
- O3D_ERROR(service_locator())
- << "Attempting to access non-existent mip_level " << mip_level
- << " in render-target texture \"" << name() << "\".";
- return RenderSurface::Ref(NULL);
- }
-
- return RenderSurface::Ref(new RenderSurfaceGL(
- service_locator(),
- edge_length() >> mip_level,
- edge_length() >> mip_level,
- kCubemapFaceList[face],
- mip_level,
- this));
-}
-
-void TextureCUBEGL::SetRect(TextureCUBE::CubeFace face,
- int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned src_width,
- unsigned src_height,
- const void* src_data,
- int src_pitch) {
- if (level >= levels() || level < 0) {
- O3D_ERROR(service_locator())
- << "Trying to SetRect non-existent level " << level
- << " on Texture \"" << name() << "\"";
- return;
- }
- if (render_surfaces_enabled()) {
- O3D_ERROR(service_locator())
- << "Attempting to SetRect a render-target texture: " << name();
- return;
- }
-
- unsigned mip_width = image::ComputeMipDimension(level, edge_length());
- unsigned mip_height = mip_width;
-
- if (dst_left + src_width > mip_width ||
- dst_top + src_height > mip_height) {
- O3D_ERROR(service_locator())
- << "SetRect(" << level << ", " << dst_left << ", " << dst_top << ", "
- << src_width << ", " << src_height << ") out of range for texture << \""
- << name() << "\"";
- return;
- }
-
- bool entire_rect = dst_left == 0 && dst_top == 0 &&
- src_width == mip_width && src_height == mip_height;
- bool compressed = IsCompressed();
-
- if (compressed && !entire_rect) {
- O3D_ERROR(service_locator())
- << "SetRect must be full rectangle for compressed textures";
- return;
- }
-
- if (resize_to_pot_) {
- Bitmap* backing_bitmap = backing_bitmaps_[face].Get();
- DCHECK(backing_bitmap->image_data());
- DCHECK(!compressed);
- // We need to update the backing mipmap and then use that to update the
- // texture.
- backing_bitmap->SetRect(
- level, dst_left, dst_top, src_width, src_height, src_data, src_pitch);
- UpdateBackedMipLevel(level, face);
- } else {
- // TODO(gman): Should this bind be using a FACE id?
- renderer_->MakeCurrentLazy();
- glBindTexture(GL_TEXTURE_2D, gl_texture_);
- GLenum gl_internal_format = 0;
- GLenum gl_data_type = 0;
- GLenum gl_format = GLFormatFromO3DFormat(format(), &gl_internal_format,
- &gl_data_type);
- int gl_face = kCubemapFaceList[face];
- if (gl_format) {
- if (src_pitch == image::ComputePitch(format(), src_width)) {
- glTexSubImage2D(gl_face, level,
- dst_left, dst_top,
- src_width, src_height,
- gl_format,
- gl_data_type,
- src_data);
- } else {
- int limit = src_height;
- for (int yy = 0; yy < limit; ++yy) {
- glTexSubImage2D(gl_face, level,
- dst_left, dst_top + yy,
- src_width, 1,
- gl_format,
- gl_data_type,
- src_data);
- src_data = AddPointerOffset<const void*>(src_data, src_pitch);
- }
- }
- } else {
- glCompressedTexSubImage2D(
- gl_face, level, 0, 0, src_width, src_height,
- gl_internal_format,
- image::ComputeMipChainSize(src_width, src_height, format(), 1),
- src_data);
- }
- }
- if (level == 0) {
- TextureUpdated();
- }
-}
-
-// Locks the given face and mipmap level of this texture for loading from
-// main memory, and returns a pointer to the buffer.
-bool TextureCUBEGL::PlatformSpecificLock(
- CubeFace face, int level, void** data, int* pitch,
- Texture::AccessMode mode) {
- DLOG(INFO) << "TextureCUBEGL Lock";
- DCHECK_GE(level, 0);
- DCHECK_LT(level, levels());
- renderer_->MakeCurrentLazy();
- Bitmap* backing_bitmap = backing_bitmaps_[face].Get();
- if (!backing_bitmap->image_data()) {
- for (int i = 0; i < static_cast<int>(NUMBER_OF_FACES); ++i) {
- DCHECK_EQ(has_levels_[i], 0u);
- }
- backing_bitmap->Allocate(format(), edge_length(), edge_length(), levels(),
- Bitmap::IMAGE);
- }
- *data = backing_bitmap->GetMipData(level);
- unsigned int mip_width = image::ComputeMipDimension(level, edge_length());
- if (!IsCompressed()) {
- *pitch = image::ComputePitch(format(), mip_width);
- } else {
- unsigned blocks_across = (mip_width + 3) / 4;
- unsigned bytes_per_block = format() == Texture::DXT1 ? 8 : 16;
- unsigned bytes_per_row = bytes_per_block * blocks_across;
- *pitch = bytes_per_row;
- }
- GLenum gl_target = kCubemapFaceList[face];
- if (mode != kWriteOnly && !HasLevel(face, level)) {
- // TODO: add some API so we don't have to copy back the data if we
- // will rewrite it all.
- DCHECK(!resize_to_pot_);
- GLenum gl_internal_format = 0;
- GLenum gl_data_type = 0;
- GLenum gl_format = GLFormatFromO3DFormat(format(),
- &gl_internal_format,
- &gl_data_type);
- glBindTexture(GL_TEXTURE_CUBE_MAP, gl_texture_);
- glGetTexImage(gl_target, level, gl_format, gl_data_type, *data);
- has_levels_[face] |= 1 << level;
- }
- CHECK_GL_ERROR();
-
- locked_levels_[face] |= 1 << level;
-
- return false;
-}
-
-// Unlocks the given face and mipmap level of this texture.
-bool TextureCUBEGL::PlatformSpecificUnlock(CubeFace face, int level) {
- DLOG(INFO) << "TextureCUBEGL Unlock";
- DCHECK_GE(level, 0);
- DCHECK_LT(level, levels());
- if (LockedMode(face, level) != kReadOnly) {
- renderer_->MakeCurrentLazy();
- UpdateBackedMipLevel(level, face);
- }
- locked_levels_[face] &= ~(1 << level);
-
- if (!resize_to_pot_) {
- // See if we can throw away the backing bitmap.
- Bitmap* backing_bitmap = backing_bitmaps_[face].Get();
- bool has_locked_level = false;
- for (int i = 0; i < static_cast<int>(NUMBER_OF_FACES); ++i) {
- if (locked_levels_[i]) {
- has_locked_level = true;
- break;
- }
- }
- if (!has_locked_level) {
- backing_bitmap->FreeData();
- for (int i = 0; i < static_cast<int>(NUMBER_OF_FACES); ++i) {
- has_levels_[i] = 0;
- }
- }
- }
- CHECK_GL_ERROR();
- return false;
-}
-
-const Texture::RGBASwizzleIndices& TextureCUBEGL::GetABGR32FSwizzleIndices() {
- return g_gl_abgr32f_swizzle_indices;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/gl/texture_gl.h b/o3d/core/cross/gl/texture_gl.h
deleted file mode 100644
index 579dc07..0000000
--- a/o3d/core/cross/gl/texture_gl.h
+++ /dev/null
@@ -1,243 +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 declarations for Texture2DGL and TextureCUBEGL.
-
-#ifndef O3D_CORE_CROSS_GL_TEXTURE_GL_H_
-#define O3D_CORE_CROSS_GL_TEXTURE_GL_H_
-
-// Precompiled header comes before everything else.
-
-// Disable compiler warning for openGL calls that require a void* to
-// be cast to a GLuint
-#if defined(OS_WIN)
-#pragma warning(disable : 4312)
-#pragma warning(disable : 4311)
-#endif
-
-#include "core/cross/bitmap.h"
-#include "core/cross/texture.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-class RendererGL;
-
-// Texture2DGL -----------------------------------------------------------------
-
-// Texture2DGL implements the Texture2D interface with OpenGL.
-class Texture2DGL : public Texture2D {
- public:
- typedef SmartPointer<Texture2DGL> Ref;
-
- virtual ~Texture2DGL();
-
- // Overridden from Texture2D
- virtual void SetRect(int level,
- unsigned left,
- unsigned top,
- unsigned width,
- unsigned height,
- const void* src_data,
- int src_pitch);
-
- // Creates a new Texture2DGL with the given specs. If the GL texture
- // creation fails then it returns NULL otherwise it returns a pointer to the
- // newly created Texture object.
- // The created texture takes ownership of the bitmap data.
- static Texture2DGL* Create(ServiceLocator* service_locator,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool enable_render_surfaces);
-
- // Returns the implementation-specific texture handle for this texture.
- void* GetTextureHandle() const {
- return reinterpret_cast<void*>(gl_texture_);
- }
-
- // Gets the GL texture handle.
- GLuint gl_texture() const { return gl_texture_; }
-
- // Gets a RGBASwizzleIndices that contains a mapping from
- // RGBA to the internal format used by the rendering API.
- virtual const RGBASwizzleIndices& GetABGR32FSwizzleIndices();
-
- protected:
- // Overridden from Texture2D
- virtual bool PlatformSpecificLock(
- int level, void** texture_data, int* pitch, AccessMode mode);
-
- // Overridden from Texture2D
- virtual bool PlatformSpecificUnlock(int level);
-
- // Overridden from Texture2D
- virtual RenderSurface::Ref PlatformSpecificGetRenderSurface(int mip_level);
-
- private:
- // Initializes the Texture2DGL from a preexisting OpenGL texture handle
- // and raw Bitmap data.
- // The texture takes ownership of the bitmap data.
- Texture2DGL(ServiceLocator* service_locator,
- GLint texture,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool resize_npot,
- bool enable_render_surfaces);
-
- // Updates a mip level, sending it from the backing bitmap to GL, rescaling
- // it if resize_to_pot_ is set.
- void UpdateBackedMipLevel(unsigned int level);
-
- // Returns true if the backing bitmap has the data for the level.
- bool HasLevel(unsigned int level) const {
- DCHECK_LT(static_cast<int>(level), levels());
- return (has_levels_ & (1 << level)) != 0;
- }
-
- // Whether or not this texture needs to be resized from NPOT to pot behind
- // the scenes.
- bool resize_to_pot_;
-
- RendererGL* renderer_;
-
- // The handle of the OpenGL texture object.
- GLuint gl_texture_;
-
- // A bitmap used to back the NPOT textures on POT-only hardware, and to back
- // the pixel buffer for Lock().
- Bitmap::Ref backing_bitmap_;
-
- // Bitfield that indicates mip levels that are currently stored in the
- // backing bitmap.
- unsigned int has_levels_;
-
- // Bitfield that indicates which levels are currently locked.
- unsigned int locked_levels_;
-};
-
-
-// TextureCUBEGL ---------------------------------------------------------------
-
-// TextureCUBEGL implements the TextureCUBE interface with OpenGL.
-class TextureCUBEGL : public TextureCUBE {
- public:
- typedef SmartPointer<TextureCUBEGL> Ref;
- virtual ~TextureCUBEGL();
-
- // Create a new Cube texture from scratch.
- static TextureCUBEGL* Create(ServiceLocator* service_locator,
- Texture::Format format,
- int levels,
- int edge_length,
- bool enable_render_surfaces);
-
- // Overridden from TextureCUBE
- virtual void SetRect(CubeFace face,
- int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned width,
- unsigned height,
- const void* src_data,
- int src_pitch);
-
- // Returns the implementation-specific texture handle for this texture.
- virtual void* GetTextureHandle() const {
- return reinterpret_cast<void*>(gl_texture_);
- }
-
- // Gets the GL texture handle.
- GLuint gl_texture() const { return gl_texture_; }
-
- // Gets a RGBASwizzleIndices that contains a mapping from
- // RGBA to the internal format used by the rendering API.
- virtual const RGBASwizzleIndices& GetABGR32FSwizzleIndices();
-
- protected:
- // Overridden from TextureCUBE
- virtual bool PlatformSpecificLock(
- CubeFace face, int level, void** texture_data, int* pitch,
- AccessMode mode);
-
- // Overridden from TextureCUBE
- virtual bool PlatformSpecificUnlock(CubeFace face, int level);
-
- // Overridden from TextureCUBE.
- virtual RenderSurface::Ref PlatformSpecificGetRenderSurface(CubeFace face,
- int level);
- private:
- // Creates a texture from a pre-existing GL texture object.
- TextureCUBEGL(ServiceLocator* service_locator,
- GLint texture,
- Texture::Format format,
- int levels,
- int edge_length,
- bool resize_to_pot,
- bool enable_render_surfaces);
-
- // Updates a mip level, sending it from the backing bitmap to GL, rescaling
- // it if resize_to_pot_ is set.
- void UpdateBackedMipLevel(unsigned int level, CubeFace face);
-
- // Returns true if the backing bitmap has the data for the level.
- bool HasLevel(CubeFace face, unsigned int level) const {
- DCHECK_LT(static_cast<int>(level), levels());
- return (has_levels_[face] & (1 << level)) != 0;
- }
-
- // Whether or not this texture needs to be resized from NPOT to pot behind
- // the scenes.
- bool resize_to_pot_;
-
- RendererGL* renderer_;
-
- // The handle of the OpenGL texture object.
- GLuint gl_texture_;
-
- // Bitmaps used to back the NPOT textures on POT-only hardware.
- Bitmap::Ref backing_bitmaps_[NUMBER_OF_FACES];
-
- // Bitfields that indicates mip levels that are currently stored in the
- // backing bitmap, one per face.
- unsigned int has_levels_[NUMBER_OF_FACES];
-
- // Bitfields that indicates which levels are currently locked, one per face.
- unsigned int locked_levels_[NUMBER_OF_FACES];
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GL_TEXTURE_GL_H_
diff --git a/o3d/core/cross/gl/utils_gl-inl.h b/o3d/core/cross/gl/utils_gl-inl.h
deleted file mode 100644
index b6ca8d4..0000000
--- a/o3d/core/cross/gl/utils_gl-inl.h
+++ /dev/null
@@ -1,69 +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_CORE_CROSS_GL_UTILS_GL_INL_H_
-#define O3D_CORE_CROSS_GL_UTILS_GL_INL_H_
-
-#include "core/cross/glcommon/utils_glcommon-inl.h"
-
-namespace o3d {
-
-// convert a byte offset into a Vertex Buffer Object into a GLvoid* for
-// use with glVertexPointer(), glNormalPointer(), glVertexAttribPointer(),
-// etc. after having used a glBindBuffer().
-#define BUFFER_OFFSET(i) (reinterpret_cast<char *>(NULL)+(i))
-
-// Writes any Cg errors to the log with a descriptive message.
-// NOTE: macros used to make sure the LOG calls note the correct
-// line number and source file.
-#define DLOG_CG_ERROR(message) { \
- CGerror error = cgGetError(); \
- DLOG_IF(INFO, error != CG_NO_ERROR) \
- << message << " : " \
- << cgGetErrorString(error); \
-}
-
-// Writes any Cg errors to the log with a descriptive message, along with
-// the error messages from the CGC compiler.
-#define DLOG_CG_COMPILER_ERROR(message, cg_context) { \
- CGerror error = cgGetError(); \
- DLOG_IF(ERROR, error == CG_NO_ERROR) \
- << message << " : " << cgGetErrorString(error); \
- if (error == CG_COMPILER_ERROR) { \
- DLOG(ERROR) << "CGC compiler output :\n" \
- << cgGetLastListing(cg_context); \
- } \
-}
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GL_UTILS_GL_INL_H_
diff --git a/o3d/core/cross/gl/utils_gl.cc b/o3d/core/cross/gl/utils_gl.cc
deleted file mode 100644
index f75abc6..0000000
--- a/o3d/core/cross/gl/utils_gl.cc
+++ /dev/null
@@ -1,228 +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 "core/cross/stream.h"
-#include "core/cross/types.h"
-#include "core/cross/gl/utils_gl.h"
-#include "core/cross/gl/gl_headers.h"
-
-// Required OpenGL extensions:
-// GL_ARB_vertex_buffer_object
-// GL_ARB_vertex_program
-// GL_ARB_texture_compression
-// GL_EXT_texture_compression_dxt1
-
-namespace o3d {
-
-typedef std::pair<String, int> SemanticMapElement;
-typedef std::map<String, int> SemanticMap;
-
-// The map batween the semantics on vertex program varying parameters names
-// and vertex attribute indices under the VP_30 profile.
-SemanticMapElement semantic_map_vp_30[] = {
- SemanticMapElement("POSITION", 0),
- SemanticMapElement("ATTR0", 0),
- SemanticMapElement("BLENDWEIGHT", 1),
- SemanticMapElement("ATTR1", 1),
- SemanticMapElement("NORMAL", 2),
- SemanticMapElement("ATTR2", 2),
- SemanticMapElement("COLOR0", 3),
- SemanticMapElement("DIFFUSE", 3),
- SemanticMapElement("ATTR3", 3),
- SemanticMapElement("COLOR1", 4),
- SemanticMapElement("SPECULAR", 4),
- SemanticMapElement("ATTR4", 4),
- SemanticMapElement("TESSFACTOR", 5),
- SemanticMapElement("FOGCOORD", 5),
- SemanticMapElement("ATTR5", 5),
- SemanticMapElement("PSIZE", 6),
- SemanticMapElement("ATTR6", 6),
- SemanticMapElement("BLENDINDICES", 7),
- SemanticMapElement("ATTR7", 7),
- SemanticMapElement("TEXCOORD0", 8),
- SemanticMapElement("ATTR8", 8),
- SemanticMapElement("TEXCOORD1", 9),
- SemanticMapElement("ATTR9", 9),
- SemanticMapElement("TEXCOORD2", 10),
- SemanticMapElement("ATTR10", 10),
- SemanticMapElement("TEXCOORD3", 11),
- SemanticMapElement("ATTR11", 11),
- SemanticMapElement("TEXCOORD4", 12),
- SemanticMapElement("ATTR12", 12),
- SemanticMapElement("TEXCOORD5", 13),
- SemanticMapElement("ATTR13", 13),
- SemanticMapElement("TEXCOORD6", 14),
- SemanticMapElement("TANGENT", 14),
- SemanticMapElement("ATTR14", 14),
- SemanticMapElement("TEXCOORD7", 15),
- SemanticMapElement("BINORMAL", 15),
- SemanticMapElement("ATTR15", 15),
-};
-
-// The map batween the semantics on vertex program varying parameters names
-// and vertex attribute indices under the VP_40 profile.
-SemanticMapElement semantic_map_vp_40[] = {
- SemanticMapElement("POSITION", 0),
- SemanticMapElement("POSITION0", 0),
- SemanticMapElement("ATTR0", 0),
- SemanticMapElement("BLENDWEIGHT", 1),
- SemanticMapElement("BLENDWEIGHT0", 1),
- SemanticMapElement("ATTR1", 1),
- SemanticMapElement("NORMAL", 2),
- SemanticMapElement("NORMAL0", 2),
- SemanticMapElement("ATTR2", 2),
- SemanticMapElement("COLOR", 3),
- SemanticMapElement("COLOR0", 3),
- SemanticMapElement("DIFFUSE", 3),
- SemanticMapElement("ATTR3", 3),
- SemanticMapElement("COLOR1", 4),
- SemanticMapElement("SPECULAR", 4),
- SemanticMapElement("ATTR4", 4),
- SemanticMapElement("TESSFACTOR", 5),
- SemanticMapElement("FOGCOORD", 5),
- SemanticMapElement("TESSFACTOR0", 5),
- SemanticMapElement("FOGCOORD0", 5),
- SemanticMapElement("ATTR5", 5),
- SemanticMapElement("PSIZE", 6),
- SemanticMapElement("PSIZE0", 6),
- SemanticMapElement("ATTR6", 6),
- SemanticMapElement("BLENDINDICES", 7),
- SemanticMapElement("BLENDINDICES0", 7),
- SemanticMapElement("ATTR7", 7),
- SemanticMapElement("TEXCOORD", 8),
- SemanticMapElement("TEXCOORD0", 8),
- SemanticMapElement("ATTR8", 8),
- SemanticMapElement("TEXCOORD1", 9),
- SemanticMapElement("ATTR9", 9),
- SemanticMapElement("TEXCOORD2", 10),
- SemanticMapElement("ATTR10", 10),
- SemanticMapElement("TEXCOORD3", 11),
- SemanticMapElement("ATTR11", 11),
- SemanticMapElement("TEXCOORD4", 12),
- SemanticMapElement("ATTR12", 12),
- SemanticMapElement("TEXCOORD5", 13),
- SemanticMapElement("ATTR13", 13),
- SemanticMapElement("TANGENT", 14),
- SemanticMapElement("TANGENT0", 14),
- SemanticMapElement("TEXCOORD6", 14),
- SemanticMapElement("ATTR14", 14),
- SemanticMapElement("BINORMAL", 15),
- SemanticMapElement("BINORMAL0", 15),
- SemanticMapElement("TEXCOORD7", 15),
- SemanticMapElement("ATTR15", 15),
-};
-
-// The map batween OpenGL Vertex Attribute indexes under the VP_40 profile
-// to Stream::Semantic identifiers (with index offsets).
-struct AttrMapElement {
- AttrMapElement(Stream::Semantic s, int i) : semantic(s), index(i) {}
- Stream::Semantic semantic;
- int index;
-};
-AttrMapElement attr_map_vp_40[] = {
- AttrMapElement(Stream::POSITION, 0),
- AttrMapElement(Stream::UNKNOWN_SEMANTIC, 0),
- AttrMapElement(Stream::NORMAL, 0),
- AttrMapElement(Stream::COLOR, 0),
- AttrMapElement(Stream::COLOR, 1),
- AttrMapElement(Stream::UNKNOWN_SEMANTIC, 0),
- AttrMapElement(Stream::UNKNOWN_SEMANTIC, 0),
- AttrMapElement(Stream::UNKNOWN_SEMANTIC, 0),
- AttrMapElement(Stream::TEXCOORD, 0),
- AttrMapElement(Stream::TEXCOORD, 1),
- AttrMapElement(Stream::TEXCOORD, 2),
- AttrMapElement(Stream::TEXCOORD, 3),
- AttrMapElement(Stream::TEXCOORD, 4),
- AttrMapElement(Stream::TEXCOORD, 5),
- AttrMapElement(Stream::TANGENT, 0),
- AttrMapElement(Stream::BINORMAL, 0),
-};
-
-// TODO: make this choice a runtime decision in RendererGL
-// initialisation.
-static SemanticMap semantic_map(semantic_map_vp_40,
- semantic_map_vp_40 +
- sizeof(semantic_map_vp_40) /
- sizeof(SemanticMapElement) );
-
-// Converts a semantic string to an OpenGL vertex attribute number using the
-// standard VP_40 shader semantic mappings. If the semantic is not
-// recognised, it returns an index of -1.
-int SemanticNameToGLVertexAttribute(const char* semantic) {
- SemanticMap::const_iterator i = semantic_map.find(semantic);
- if (i == semantic_map.end()) {
- return -1;
- }
- return i->second;
-}
-
-// Given a vertex attribute stream, convert it to a Stream::Semantic number
-// and index. This is an imprecise operation.
-Stream::Semantic GLVertexAttributeToStream(const unsigned int attr,
- int *index) {
- // kMaxAttrIndex is available from:
- // glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attribs);
- //
- // TODO: make this a runtime provided value discovered during
- // Renderer creation.
- const unsigned int kMaxAttrIndex = 15u;
- if (attr > kMaxAttrIndex) {
- //TODO: Figure out how to get errors out of here to the client.
- DLOG(ERROR) << "Invalid vertex attribute index.";
- *index = 0;
- return Stream::UNKNOWN_SEMANTIC;
- }
- *index = attr_map_vp_40[attr].index;
- return attr_map_vp_40[attr].semantic;
-}
-
-#ifdef OS_WIN
-
-// Given a CGcontext object, check to see if any errors have occurred since
-// the last Cg API call, and report the message and any compiler errors (if
-// necessary).
-inline void CheckForCgError(const String& logmessage, CGcontext cg_context) {
- CGerror error = CG_NO_ERROR;
- const char *error_string = cgGetLastErrorString(&error);
- if (error == CG_NO_ERROR) {
- return;
- } else {
- DLOG(ERROR) << logmessage << ": " << error_string;
- if (error == CG_COMPILER_ERROR) {
- DLOG(ERROR) << "Compiler message:\n" << cgGetLastListing(cg_context);
- }
- }
-}
-
-#endif
-
-} // namespace o3d
diff --git a/o3d/core/cross/gl/utils_gl.h b/o3d/core/cross/gl/utils_gl.h
deleted file mode 100644
index a7af934..0000000
--- a/o3d/core/cross/gl/utils_gl.h
+++ /dev/null
@@ -1,47 +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_CORE_CROSS_GL_UTILS_GL_H_
-#define O3D_CORE_CROSS_GL_UTILS_GL_H_
-
-#include "base/basictypes.h"
-#include "core/cross/stream.h"
-
-namespace o3d {
-
-bool GetGLProcedures();
-int SemanticNameToGLVertexAttribute(const char* semantic);
-Stream::Semantic GLVertexAttributeToStream(const unsigned int attr, int *index);
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GL_UTILS_GL_H_
diff --git a/o3d/core/cross/glcommon/utils_glcommon-inl.h b/o3d/core/cross/glcommon/utils_glcommon-inl.h
deleted file mode 100644
index a675239..0000000
--- a/o3d/core/cross/glcommon/utils_glcommon-inl.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright 2010, 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_CORE_CROSS_GLCOMMON_UTILS_GLCOMMON_INL_H_
-#define O3D_CORE_CROSS_GLCOMMON_UTILS_GLCOMMON_INL_H_
-
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// Define this to debug GL errors. This has a significant performance hit.
-// #define GL_ERROR_DEBUGGING
-
-#ifdef GL_ERROR_DEBUGGING
-#define CHECK_GL_ERROR() do { \
- GLenum gl_error = glGetError(); \
- LOG_IF(ERROR, gl_error != GL_NO_ERROR) << "GL Error: " << gl_error; \
-} while(0)
-#define LOG_FLUSHED_GL_ERROR(gl_error) \
- LOG(ERROR) << "Flushing unreaped GL error: " << gl_error;
-#else // GL_ERROR_DEBUGGING
-#define CHECK_GL_ERROR() void(0)
-#define LOG_FLUSHED_GL_ERROR(gl_error) void(0)
-#endif // GL_ERROR_DEBUGGING
-
-inline static void FlushGlErrors() {
- GLenum gl_error;
- while ((gl_error = glGetError()) != GL_NO_ERROR) {
- LOG_FLUSHED_GL_ERROR(gl_error);
- }
-}
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GLCOMMON_UTILS_GLCOMMON_INL_H_
diff --git a/o3d/core/cross/gles2/buffer_gles2.cc b/o3d/core/cross/gles2/buffer_gles2.cc
deleted file mode 100644
index 8cd7838..0000000
--- a/o3d/core/cross/gles2/buffer_gles2.cc
+++ /dev/null
@@ -1,299 +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 implementatinos of VertexBufferGLES2 and
-// IndexBufferGLES2, used to implement O3D using OpenGLES2.
-//
-// To force the vertex and index buffers to be created by Cg Runtime
-// control, define the compile flag "USE_CG_BUFFERS". This option is off by
-// default and buffers are created, locked and managed using the OpenGLES2
-// "ARB_vertex_buffer_object" extension.
-
-#include "core/cross/error.h"
-#include "core/cross/gles2/buffer_gles2.h"
-#include "core/cross/gles2/renderer_gles2.h"
-#include "core/cross/gles2/utils_gles2.h"
-#include "core/cross/gles2/utils_gles2-inl.h"
-
-namespace o3d {
-
-namespace {
-
-#if defined(GLES2_BACKEND_DESKTOP_GL)
-GLenum BufferAccessModeToGLenum(Buffer::AccessMode access_mode) {
- switch (access_mode) {
- case Buffer::READ_ONLY:
- return GL_READ_ONLY_ARB;
- case Buffer::WRITE_ONLY:
- return GL_WRITE_ONLY_ARB;
- case Buffer::READ_WRITE:
- return GL_READ_WRITE_ARB;
- case Buffer::NONE:
- break;
- }
- DCHECK(false);
- return GL_READ_WRITE_ARB;
-}
-#endif
-
-} // anonymous namespace
-
-// Vertex Buffers --------------------------------------------------------------
-
-// Initializes the O3D VertexBuffer object but does not allocate an
-// OpenGLES2 vertex buffer object yet.
-VertexBufferGLES2::VertexBufferGLES2(ServiceLocator* service_locator)
- : VertexBuffer(service_locator),
- renderer_(static_cast<RendererGLES2*>(
- service_locator->GetService<Renderer>())),
-#if !defined(GLES2_BACKEND_DESKTOP_GL)
- shadow_(NULL),
- read_only_(true),
-#endif
- gl_buffer_(0) {
- DLOG(INFO) << "VertexBufferGLES2 Construct";
-}
-
-// Destructor releases the OpenGLES2 VBO.
-VertexBufferGLES2::~VertexBufferGLES2() {
- DLOG(INFO) << "VertexBufferGLES2 Destruct \"" << name() << "\"";
- ConcreteFree();
-}
-
-// Creates a OpenGLES2 vertex buffer of the requested size.
-bool VertexBufferGLES2::ConcreteAllocate(size_t size_in_bytes) {
- DLOG(INFO) << "VertexBufferGLES2 Allocate \"" << name() << "\"";
- renderer_->MakeCurrentLazy();
- ConcreteFree();
- // Create a new VBO.
- glGenBuffersARB(1, &gl_buffer_);
-
- if (!gl_buffer_) return false;
-
- // Give the VBO a size, but no data, and set the hint to "STATIC_DRAW"
- // to mark the buffer as set up once then used often.
- glBindBufferARB(GL_ARRAY_BUFFER, gl_buffer_);
- glBufferDataARB(GL_ARRAY_BUFFER,
- size_in_bytes,
- NULL,
- GL_STATIC_DRAW);
-
-#if !defined(GLES2_BACKEND_DESKTOP_GL)
- shadow_.reset(new char[size_in_bytes]);
-#endif
- CHECK_GL_ERROR();
- return true;
-}
-
-void VertexBufferGLES2::ConcreteFree() {
- if (gl_buffer_) {
- renderer_->MakeCurrentLazy();
- glDeleteBuffersARB(1, &gl_buffer_);
- gl_buffer_ = 0;
- CHECK_GL_ERROR();
- }
-#if !defined(GLES2_BACKEND_DESKTOP_GL)
- shadow_.reset(NULL);
-#endif
-}
-
-// Calls Lock on the OpenGLES2 buffer to get the address in memory of where the
-// buffer data is currently stored.
-bool VertexBufferGLES2::ConcreteLock(Buffer::AccessMode access_mode,
- void **buffer_data) {
- DLOG(INFO) << "VertexBufferGLES2 Lock \"" << name() << "\"";
- renderer_->MakeCurrentLazy();
- glBindBufferARB(GL_ARRAY_BUFFER, gl_buffer_);
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- *buffer_data = glMapBufferARB(GL_ARRAY_BUFFER,
- BufferAccessModeToGLenum(access_mode));
- if (*buffer_data == NULL) {
- GLenum error = glGetError();
- if (error == GL_OUT_OF_MEMORY) {
- O3D_ERROR(service_locator()) << "Out of memory for buffer lock.";
- } else {
- O3D_ERROR(service_locator()) << "Unable to lock a GLES2 Array Buffer";
- }
- return false;
- }
-#else
- *buffer_data = shadow_.get();
- read_only_ = (access_mode == READ_ONLY);
-#endif
- CHECK_GL_ERROR();
- return true;
-}
-
-// Calls Unlock on the OpenGLES2 buffer to notify that the contents of the
-// buffer are now ready for use.
-bool VertexBufferGLES2::ConcreteUnlock() {
- DLOG(INFO) << "VertexBufferGLES2 Unlock \"" << name() << "\"";
- renderer_->MakeCurrentLazy();
- glBindBufferARB(GL_ARRAY_BUFFER, gl_buffer_);
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- if (!glUnmapBufferARB(GL_ARRAY_BUFFER)) {
- GLenum error = glGetError();
- if (error == GL_INVALID_OPERATION) {
- O3D_ERROR(service_locator()) <<
- "Buffer was unlocked without first being locked.";
- } else {
- O3D_ERROR(
- service_locator()) << "Unable to unlock a GLES2 Element Array Buffer";
- }
- return false;
- }
-#else
- if (!read_only_) {
- glBufferSubData(GL_ARRAY_BUFFER, 0, GetSizeInBytes(), shadow_.get());
- }
-#endif
- CHECK_GL_ERROR();
- return true;
-}
-
-
-// Index Buffers ---------------------------------------------------------------
-
-// Initializes the O3D IndexBuffer object but does not create a OpenGLES2
-// buffer yet.
-
-IndexBufferGLES2::IndexBufferGLES2(ServiceLocator* service_locator)
- : IndexBuffer(service_locator),
- renderer_(static_cast<RendererGLES2*>(
- service_locator->GetService<Renderer>())),
-#if !defined(GLES2_BACKEND_DESKTOP_GL)
- shadow_(NULL),
- read_only_(true),
-#endif
- gl_buffer_(0) {
- DLOG(INFO) << "IndexBufferGLES2 Construct";
-}
-
-// Destructor releases the OpenGLES2 index buffer.
-IndexBufferGLES2::~IndexBufferGLES2() {
- DLOG(INFO) << "IndexBufferGLES2 Destruct \"" << name() << "\"";
- ConcreteFree();
-}
-
-// Creates a OpenGLES2 index buffer of the requested size.
-bool IndexBufferGLES2::ConcreteAllocate(size_t size_in_bytes) {
- DLOG(INFO) << "IndexBufferGLES2 Allocate \"" << name() << "\"";
- renderer_->MakeCurrentLazy();
- ConcreteFree();
- // Create a new VBO.
- glGenBuffersARB(1, &gl_buffer_);
- if (!gl_buffer_) return false;
- // Give the VBO a size, but no data, and set the hint to "STATIC_DRAW"
- // to mark the buffer as set up once then used often.
- glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, gl_buffer_);
- glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER,
- size_in_bytes,
- NULL,
- GL_STATIC_DRAW);
-#if !defined(GLES2_BACKEND_DESKTOP_GL)
- shadow_.reset(new char[size_in_bytes]);
-#endif
- CHECK_GL_ERROR();
- return true;
-}
-
-void IndexBufferGLES2::ConcreteFree() {
- if (gl_buffer_) {
- renderer_->MakeCurrentLazy();
- glDeleteBuffersARB(1, &gl_buffer_);
- gl_buffer_ = 0;
- CHECK_GL_ERROR();
- }
-#if !defined(GLES2_BACKEND_DESKTOP_GL)
- shadow_.reset(NULL);
-#endif
-}
-
-// Maps the OpenGLES2 buffer to get the address in memory of the buffer data.
-bool IndexBufferGLES2::ConcreteLock(Buffer::AccessMode access_mode,
- void **buffer_data) {
- DLOG(INFO) << "IndexBufferGLES2 Lock \"" << name() << "\"";
- renderer_->MakeCurrentLazy();
- glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, gl_buffer_);
- if (!num_elements())
- return true;
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- *buffer_data = glMapBufferARB(GL_ELEMENT_ARRAY_BUFFER,
- BufferAccessModeToGLenum(access_mode));
- if (*buffer_data == NULL) {
- GLenum error = glGetError();
- if (error == GL_OUT_OF_MEMORY) {
- O3D_ERROR(service_locator()) << "Out of memory for buffer lock.";
- } else {
- O3D_ERROR(
- service_locator()) << "Unable to lock a GLES2 Element Array Buffer";
- }
- return false;
- }
-#else
- *buffer_data = shadow_.get();
- read_only_ = (access_mode == READ_ONLY);
-#endif
- CHECK_GL_ERROR();
- return true;
-}
-
-// Calls Unlock on the OpenGLES2 buffer to notify that the contents of the
-// buffer are now ready for use.
-bool IndexBufferGLES2::ConcreteUnlock() {
- DLOG(INFO) << "IndexBufferGLES2 Unlock \"" << name() << "\"";
- renderer_->MakeCurrentLazy();
- if (!num_elements())
- return true;
- glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, gl_buffer_);
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- if (!glUnmapBufferARB(GL_ELEMENT_ARRAY_BUFFER)) {
- GLenum error = glGetError();
- if (error == GL_INVALID_OPERATION) {
- O3D_ERROR(service_locator()) <<
- "Buffer was unlocked without first being locked.";
- } else {
- O3D_ERROR(
- service_locator()) << "Unable to unlock a GLES2 Element Array Buffer";
- }
- return false;
- }
-#else
- if (!read_only_) {
- glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, GetSizeInBytes(),
- shadow_.get());
- }
-#endif
- CHECK_GL_ERROR();
- return true;
-}
-} // namespace o3d
diff --git a/o3d/core/cross/gles2/buffer_gles2.h b/o3d/core/cross/gles2/buffer_gles2.h
deleted file mode 100644
index b1956f8..0000000
--- a/o3d/core/cross/gles2/buffer_gles2.h
+++ /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 contains the declaration of the platform specific
-// VertexBufferGLES2 and IndexBufferGLES2 objects used by O3D
-
-#ifndef O3D_CORE_CROSS_GLES2_BUFFER_GLES2_H_
-#define O3D_CORE_CROSS_GLES2_BUFFER_GLES2_H_
-
-#include "base/scoped_ptr.h"
-#include "core/cross/buffer.h"
-#include "core/cross/gles2/gles2_headers.h"
-
-namespace o3d {
-
-class RendererGLES2;
-
-// VertexBufferGLES2 is a wrapper around an OpenGLES2
-// Vertex Buffer Object (VBO). The buffer starts out empty. Calling Allocate()
-// will reserve video memory for the buffer. Buffer contents are are updated by
-// calling Lock() to get a pointer to the memory allocated for the buffer,
-// updating that data in place and calling Unlock() to notify OpenGLES2 that the
-// edits are done.
-//
-// To force the vertex and index buffers to be created by Cg Runtime
-// control, define the compile flag "USE_CG_BUFFERS". This option is off by
-// default and buffers are created, locked and managed using the OpenGLES2
-// "ARB_vertex_buffer_object" extension.
-
-class VertexBufferGLES2 : public VertexBuffer {
- public:
- explicit VertexBufferGLES2(ServiceLocator* service_locator);
- ~VertexBufferGLES2();
-
- // Returns the OpenGLES2 vertex buffer Object handle.
- GLuint gl_buffer() const { return gl_buffer_; }
-
- protected:
- // Creates a OpenGLES2 vertex buffer object of the specified size.
- virtual bool ConcreteAllocate(size_t size_in_bytes);
-
- // Frees the OpenGLES2 vertex buffer object.
- virtual void ConcreteFree();
-
- // Returns a pointer to the current contents of the buffer. A matching
- // call to Unlock is necessary to update the contents of the buffer.
- virtual bool ConcreteLock(AccessMode access_mode, void** buffer_data);
-
- // Notifies OpenGLES2 that the buffer data has been updated. Unlock is only
- // valid if it follows a Lock operation.
- virtual bool ConcreteUnlock();
-
- private:
- RendererGLES2* renderer_;
-#if !defined(GLES2_BACKEND_DESKTOP_GL)
- // GLES doesn't support glMapBuffers (only WRITE_ONLY if an extension is
- // present), or even glGetBufferSubData, so we need to keep a shadow of the
- // data.
- scoped_array<char> shadow_;
- bool read_only_;
-#endif
- GLuint gl_buffer_;
-};
-
-// IndexBufferGLES2 is a wrapper around an OpenGLES2 Index Buffer Object (VBO).
-// The buffer starts out empty. A call to Allocate() will create an OpenGLES2
-// index buffer of the requested size. Updates the to the contents of the
-// buffer are done via the Lock/Unlock calls.
-class IndexBufferGLES2 : public IndexBuffer {
- public:
- explicit IndexBufferGLES2(ServiceLocator* service_locator);
- ~IndexBufferGLES2();
-
- // Returns the OpenGLES2 vertex buffer Object handle.
- GLuint gl_buffer() const { return gl_buffer_; }
-
- protected:
- // Creates a OpenGLES2 index buffer of the specified size.
- virtual bool ConcreteAllocate(size_t size_in_bytes);
-
- // Frees the OpenGLES2 vertex buffer object.
- virtual void ConcreteFree();
-
- // Returns a pointer to the current contents of the buffer. After calling
- // Lock, the contents of the buffer can be updated in place.
- virtual bool ConcreteLock(AccessMode access_mode, void** buffer_data);
-
- // Notifies OpenGLES2 that the buffer data has been updated. Unlock is only
- // valid if it follows a Lock operation.
- virtual bool ConcreteUnlock();
-
- private:
- RendererGLES2* renderer_;
-#if !defined(GLES2_BACKEND_DESKTOP_GL)
- // GLES doesn't support glMapBuffers (only WRITE_ONLY if an extension is
- // present), or even glGetBufferSubData, so we need to keep a shadow of the
- // data.
- scoped_array<char> shadow_;
- bool read_only_;
-#endif
- GLuint gl_buffer_;
-};
-
-} // namespace o3d
-
-
-#endif // O3D_CORE_CROSS_GLES2_BUFFER_GLES2_H_
diff --git a/o3d/core/cross/gles2/draw_element_gles2.cc b/o3d/core/cross/gles2/draw_element_gles2.cc
deleted file mode 100644
index 825ebb4..0000000
--- a/o3d/core/cross/gles2/draw_element_gles2.cc
+++ /dev/null
@@ -1,46 +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 definition of the DrawElementGLES2 class.
-
-#include "core/cross/gles2/draw_element_gles2.h"
-
-namespace o3d {
-
-DrawElementGLES2::DrawElementGLES2(ServiceLocator* service_locator)
- : DrawElement(service_locator) {
-}
-
-DrawElementGLES2::~DrawElementGLES2() {
-}
-} // namespace o3d
-
diff --git a/o3d/core/cross/gles2/draw_element_gles2.h b/o3d/core/cross/gles2/draw_element_gles2.h
deleted file mode 100644
index ca026d2..0000000
--- a/o3d/core/cross/gles2/draw_element_gles2.h
+++ /dev/null
@@ -1,58 +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 declaration of the DrawElementGLES2 class.
-
-#ifndef O3D_CORE_CROSS_GLES2_DRAW_ELEMENT_GLES2_H_
-#define O3D_CORE_CROSS_GLES2_DRAW_ELEMENT_GLES2_H_
-
-#include <map>
-#include "core/cross/draw_element.h"
-
-namespace o3d {
-
-class Element;
-
-// DrawElementGLES2 is the OpenGLES2 implementation of the DrawElement. It
-// provides a place for the renderer to store platform specific cache
-// information.
-class DrawElementGLES2 : public DrawElement {
- public:
- explicit DrawElementGLES2(ServiceLocator* service_locator);
- ~DrawElementGLES2();
-
- private:
-};
-} // o3d
-
-#endif // O3D_CORE_CROSS_GLES2_DRAW_ELEMENT_GLES2_H_
-
diff --git a/o3d/core/cross/gles2/effect_gles2.cc b/o3d/core/cross/gles2/effect_gles2.cc
deleted file mode 100644
index 88157b0..0000000
--- a/o3d/core/cross/gles2/effect_gles2.cc
+++ /dev/null
@@ -1,453 +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 definition of EffectGLES2, the OpenGLES2
-// implementation of the abstract O3D class Effect.
-
-// Disable pointer casting warning for OpenGLES2 calls that require a void* to
-// be cast to a GLuint
-#if defined(OS_WIN)
-#pragma warning(disable : 4312)
-#pragma warning(disable : 4311)
-#endif
-
-#include <sstream>
-#include "base/cross/std_functional.h"
-#include "core/cross/semantic_manager.h"
-#include "core/cross/error.h"
-#include "core/cross/standard_param.h"
-#include "core/cross/gles2/effect_gles2.h"
-#include "core/cross/gles2/renderer_gles2.h"
-#include "core/cross/gles2/primitive_gles2.h"
-#include "core/cross/gles2/draw_element_gles2.h"
-#include "core/cross/gles2/texture_gles2.h"
-#include "core/cross/gles2/utils_gles2.h"
-#include "core/cross/gles2/utils_gles2-inl.h"
-
-#if defined(OS_WIN)
-#include "core/cross/core_metrics.h"
-#endif
-
-namespace o3d {
-
-// Number of repeating events to log before giving up, e.g. setup frame,
-// draw polygons, etc.
-const int kNumLoggedEvents = 5;
-
-// Convert a GLunum data type into a Param type.
-static const ObjectBase::Class* GLTypeToParamType(GLenum gl_type) {
- switch (gl_type) {
- case GL_FLOAT:
- return ParamFloat::GetApparentClass();
- case GL_FLOAT_VEC2:
- return ParamFloat2::GetApparentClass();
- case GL_FLOAT_VEC3:
- return ParamFloat3::GetApparentClass();
- case GL_FLOAT_VEC4:
- return ParamFloat4::GetApparentClass();
- case GL_INT:
- return ParamInteger::GetApparentClass();
- case GL_INT_VEC2:
- return NULL;
- case GL_INT_VEC3:
- return NULL;
- case GL_INT_VEC4:
- return NULL;
- case GL_BOOL:
- return ParamBoolean::GetApparentClass();
- case GL_BOOL_VEC2:
- return NULL;
- case GL_BOOL_VEC3:
- return NULL;
- case GL_BOOL_VEC4:
- return NULL;
- case GL_FLOAT_MAT2:
- return NULL;
- case GL_FLOAT_MAT3:
- return NULL;
- case GL_FLOAT_MAT4:
- return ParamMatrix4::GetApparentClass();
- case GL_SAMPLER_2D:
- return ParamSampler::GetApparentClass();
- case GL_SAMPLER_CUBE:
- return ParamSampler::GetApparentClass();
- default : {
- DLOG(ERROR) << "Cannot convert GLtype "
- << gl_type
- << " to a Param type.";
- return NULL;
- }
- }
-}
-
-// -----------------------------------------------------------------------------
-
-EffectGLES2::EffectGLES2(ServiceLocator* service_locator)
- : Effect(service_locator),
- semantic_manager_(service_locator->GetService<SemanticManager>()),
- renderer_(static_cast<RendererGLES2*>(
- service_locator->GetService<Renderer>())),
- gl_program_(0),
- compile_count_(-1) {
- DLOG(INFO) << "EffectGLES2 Construct";
-}
-
-// Destructor releases vertex and fragment shaders and their correspoding
-// constants tables.
-EffectGLES2::~EffectGLES2() {
- DLOG(INFO) << "EffectGLES2 Destruct \"" << name() << "\"";
- ClearProgram();
-}
-
-void EffectGLES2::ClearProgram() {
- if (gl_program_) {
- glDeleteProgram(gl_program_);
- gl_program_ = 0;
- }
- set_source("");
-}
-
-GLuint EffectGLES2::LoadShader(GLenum type, const char* shader_src) {
- GLuint shader = glCreateShader(type);
- if (shader == 0) {
- return 0;
- }
-
- // Load the shader source
- glShaderSource(shader, 1, &shader_src, NULL);
- // Compile the shader
- glCompileShader(shader);
- // Check the compile status
- GLint value;
- glGetShaderiv(shader, GL_COMPILE_STATUS, &value);
- if (value == 0) {
- GLint error_length;
- glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &error_length);
- scoped_array<char> buffer(new char[error_length + 1]);
- GLsizei length;
- glGetShaderInfoLog(shader, error_length + 1, &length, buffer.get());
- O3D_ERROR(service_locator()) << "Effect Compile Error: " << buffer.get();
- DLOG(ERROR) << "Error compiling shader:" << buffer.get();
- glDeleteShader(shader);
- return 0;
- }
- return shader;
-}
-
-namespace {
-
-String::size_type GetEndOfIdentifier(const String& original,
- String::size_type start) {
- if (start < original.size()) {
- // check that first character is alpha or '_'
- if (isalpha(original[start]) || original[start] == '_') {
- String::size_type end = original.size();
- String::size_type position = start;
- while (position < end) {
- char c = original[position];
- if (!isalnum(c) && c != '_') {
- break;
- }
- ++position;
- }
- return position;
- }
- }
- return String::npos;
-}
-
-bool GetIdentifierAfterString(const String& original,
- const String& phrase,
- String* word) {
- String::size_type position = original.find(phrase);
- if (position == String::npos) {
- return false;
- }
-
- // Find end of identifier
- String::size_type start = position + phrase.size();
- String::size_type end = GetEndOfIdentifier(original, start);
- if (end != start && end != String::npos) {
- *word = String(original, start, end - start);
- return true;
- }
- return false;
-}
-
-#ifdef GLES2_BACKEND_DESKTOP_GL
-const char kVertexHeader[] = "";
-const char kFragmentHeader[] = "// ";
-#else
-const char kVertexHeader[] = "precision highp float; precision highp int;\n";
-const char kFragmentHeader[] =
- "precision mediump float; precision mediump int;\n// ";
-#endif
-
-} // anonymous namespace
-
-// Initializes the Effect object using the shaders found in an FX formatted
-// string.
-bool EffectGLES2::LoadFromFXString(const String& effect) {
- DLOG(INFO) << "EffectGLES2 LoadFromFXString";
- renderer_->MakeCurrentLazy();
-
- ++compile_count_;
- ClearProgram();
-
- String matrix_load_order_str;
- if (!GetIdentifierAfterString(effect,
- kMatrixLoadOrderPrefix,
- &matrix_load_order_str)) {
- O3D_ERROR(service_locator()) << "Failed to find \""
- << kMatrixLoadOrderPrefix
- << "\" in Effect";
- return false;
- }
- bool column_major = matrix_load_order_str == "ColumnMajor";
- MatrixLoadOrder matrix_load_order = column_major ? COLUMN_MAJOR : ROW_MAJOR;
-
- // Split the effect
- const char* kSplitMarker = "// #o3d SplitMarker";
- String::size_type split_pos = effect.find(kSplitMarker);
- if (split_pos == String::npos) {
- O3D_ERROR(service_locator()) << "Missing '" << kSplitMarker
- << "' in shader: " << effect;
- return false;
- }
-
- String vertex_shader(kVertexHeader + effect.substr(0, split_pos));
- String fragment_shader(kFragmentHeader + effect.substr(split_pos));
-
- set_matrix_load_order(matrix_load_order);
-
- GLuint gl_vertex_shader =
- LoadShader(GL_VERTEX_SHADER, vertex_shader.c_str());
- if (!gl_vertex_shader) {
- return false;
- }
- GLuint gl_fragment_shader =
- LoadShader(GL_FRAGMENT_SHADER, fragment_shader.c_str());
- if (!gl_fragment_shader) {
- glDeleteShader(gl_vertex_shader);
- return false;
- }
- gl_program_ = glCreateProgram();
- if (!gl_program_) {
- glDeleteShader(gl_fragment_shader);
- glDeleteShader(gl_vertex_shader);
- return false;
- }
- glAttachShader(gl_program_, gl_vertex_shader);
- glAttachShader(gl_program_, gl_fragment_shader);
- glLinkProgram(gl_program_);
- glDeleteShader(gl_vertex_shader);
- glDeleteShader(gl_fragment_shader);
- // Check the compile status
- GLint value;
- glGetProgramiv(gl_program_, GL_LINK_STATUS, &value);
- if (value == 0) {
- GLint error_length;
- glGetProgramiv(gl_program_, GL_INFO_LOG_LENGTH, &error_length);
- scoped_array<char> buffer(new char[error_length + 1]);
- GLsizei length;
- glGetProgramInfoLog(gl_program_, error_length + 1, &length, buffer.get());
- O3D_ERROR(service_locator()) << "Effect Link Error: " << buffer.get();
- DLOG(ERROR) << "Error linking programr:" << buffer.get();
- glDeleteProgram(gl_program_);
- return false;
- }
-
- CHECK_GL_ERROR();
-
- set_source(effect);
- return true;
-}
-
-void EffectGLES2::GetShaderParamInfo(
- GLuint program,
- std::map<String, EffectParameterInfo>* info_map) {
- DCHECK(info_map);
- if (!program) {
- return;
- }
-
- GLint num_uniforms = 0;
- GLint max_len = 0;
- glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &num_uniforms);
- glGetProgramiv(program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max_len);
- // TODO(gman): Should we check for error?
- scoped_array<char> name_buffer(new char[max_len + 1]);
- // Loop over all parameters.
- for (GLint ii = 0; ii < num_uniforms; ++ii) {
- GLsizei length;
- GLsizei size;
- GLenum type;
- glGetActiveUniform(
- program, ii, max_len + 1, &length, &size, &type, name_buffer.get());
- String name(name_buffer.get());
- // TODO(gman): Should we check for error?
- // TODO(gman): Should we skip uniforms that start with "gl_"?
- int num_elements = 0;
- if (size > 1) {
- // It's an array.
- num_elements = size;
- }
- const ObjectBase::Class *param_class = GLTypeToParamType(type);
- if (!param_class)
- continue;
- const ObjectBase::Class *sem_class = NULL;
- // Since there is no SAS for GLSL let's just use reserved names.
- sem_class = semantic_manager_->LookupSemantic(name);
- (*info_map)[name] = EffectParameterInfo(
- name,
- param_class,
- num_elements,
- sem_class != NULL ? name : "",
- sem_class);
- }
-}
-
-void EffectGLES2::GetParameterInfo(EffectParameterInfoArray* info_array) {
- DCHECK(info_array);
- std::map<String, EffectParameterInfo> info_map;
- renderer_->MakeCurrentLazy();
- if (gl_program_) {
- GetShaderParamInfo(gl_program_, &info_map);
- }
- info_array->clear();
- info_array->reserve(info_map.size());
- std::transform(
- info_map.begin(),
- info_map.end(),
- std::back_inserter(*info_array),
- base::select2nd<std::map<String, EffectParameterInfo>::value_type>());
-}
-
-void EffectGLES2::GetVaryingVertexShaderParamInfo(
- GLuint program,
- std::vector<EffectStreamInfo>* info_array) {
- GLint num_attribs = 0;
- GLint max_len = 0;
- glGetProgramiv(program, GL_ACTIVE_ATTRIBUTES, &num_attribs);
- glGetProgramiv(program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &max_len);
- // TODO(gman): Should we check for error?
- scoped_array<char> name_buffer(new char[max_len + 1]);
- for (GLint ii = 0; ii < num_attribs; ++ii) {
- GLsizei length;
- GLsizei size;
- GLenum type;
- glGetActiveAttrib(
- program, ii, max_len + 1, &length, &size, &type, name_buffer.get());
- // TODO(gman): Should we check for error?
- String name(name_buffer.get());
- // Since GLSL has no semantics just go by name.
- Stream::Semantic semantic;
- int semantic_index;
- if (!SemanticNameToSemantic(name, &semantic, &semantic_index)) {
- continue;
- }
-
- info_array->push_back(EffectStreamInfo(semantic, semantic_index));
- }
-}
-
-void EffectGLES2::GetStreamInfo(
- EffectStreamInfoArray* info_array) {
- DCHECK(info_array);
- renderer_->MakeCurrentLazy();
- info_array->clear();
- GetVaryingVertexShaderParamInfo(gl_program_, info_array);
-}
-
-// private functions -----------------------------------------------------------
-
-// Loop through all the uniform parameters on the effect and set their values
-// from their corresponding Params on the various ParamObject (as stored in the
-// ParamCacheGLES2).
-void EffectGLES2::UpdateShaderUniformsFromEffect(
- ParamCacheGLES2* param_cache_gl) {
- DLOG_FIRST_N(INFO, kNumLoggedEvents)
- << "EffectGLES2 UpdateShaderUniformsFromEffect";
- renderer_->ResetTextureGroupSetCount();
- ParamCacheGLES2::UniformParameterMap& map = param_cache_gl->uniform_map();
- ParamCacheGLES2::UniformParameterMap::iterator i;
- for (i = map.begin(); i != map.end(); ++i) {
- GLES2Parameter gl_param = i->first;
- i->second->SetEffectParam(renderer_, gl_param);
- }
- renderer_->UpdateDxClippingUniform(
- glGetUniformLocation(gl_program_, "dx_clipping"));
- CHECK_GL_ERROR();
-}
-
-// Loop through all the uniform parameters on the effect and reset their values.
-// For now, this unbinds textures contained in sampler parameters.
-void EffectGLES2::ResetShaderUniforms(ParamCacheGLES2* param_cache_gles2) {
- DLOG_FIRST_N(INFO, kNumLoggedEvents) << "EffectGLES2 ResetShaderUniforms";
- ParamCacheGLES2::UniformParameterMap& map = param_cache_gles2->uniform_map();
- ParamCacheGLES2::UniformParameterMap::iterator i;
- for (i = map.begin(); i != map.end(); ++i) {
- GLES2Parameter gl_param = i->first;
- i->second->ResetEffectParam(renderer_, gl_param);
- }
- CHECK_GL_ERROR();
-}
-
-// Updates the values of the vertex and fragment shader parameters using the
-// current values in the param/glparam caches.
-void EffectGLES2::PrepareForDraw(ParamCacheGLES2* param_cache_gles2) {
- DLOG_FIRST_N(INFO, kNumLoggedEvents) << "EffectGLES2 PrepareForDraw \""
- << name()
- << "\"";
- DCHECK(renderer_->IsCurrent());
- if (gl_program_) {
- // Initialise the render states for this pass, this includes the shaders.
- glUseProgram(gl_program_);
- UpdateShaderUniformsFromEffect(param_cache_gles2);
- } else {
- DLOG_FIRST_N(ERROR, kNumLoggedEvents)
- << "No valid GLES2effect found "
- << "in Effect \"" << name() << "\"";
- }
- CHECK_GL_ERROR();
-}
-
-// Resets the render states back to their default value.
-void EffectGLES2::PostDraw(ParamCacheGLES2* param_cache_gles2) {
- DLOG_FIRST_N(INFO, kNumLoggedEvents)
- << "EffectGLES2 PostDraw \"" << name() << "\"";
- DCHECK(renderer_->IsCurrent());
- ResetShaderUniforms(param_cache_gles2);
- CHECK_GL_ERROR();
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/gles2/effect_gles2.h b/o3d/core/cross/gles2/effect_gles2.h
deleted file mode 100644
index e9655ae..0000000
--- a/o3d/core/cross/gles2/effect_gles2.h
+++ /dev/null
@@ -1,144 +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 declaration of the EffectGLES2 class.
-
-#ifndef O3D_CORE_CROSS_GLES2_EFFECT_GLES2_H_
-#define O3D_CORE_CROSS_GLES2_EFFECT_GLES2_H_
-
-// Disable compiler warning for openGLES2 calls that require a void* to
-// be cast to a GLuint
-#if defined(OS_WIN)
-#pragma warning(disable : 4312)
-#pragma warning(disable : 4311)
-#endif
-
-#include <utility>
-#include <vector>
-#include <map>
-#include "core/cross/gles2/gles2_headers.h"
-#include "core/cross/effect.h"
-#include "core/cross/gles2/utils_gles2.h"
-
-namespace o3d {
-
-class DrawElementGLES2;
-class ParamCacheGLES2;
-class ParamObject;
-class Param;
-class ParamTexture;
-class RendererGLES2;
-class SemanticManager;
-
-// TODO(gman): Replace.
-typedef GLuint GLES2Parameter;
-
-// A class to set an effect parameter from an O3D parameter.
-class EffectParamHandlerGLES2 : public RefCounted {
- public:
- typedef SmartPointer<EffectParamHandlerGLES2> Ref;
- virtual ~EffectParamHandlerGLES2() { }
-
- // Sets a GLES2 Effect Parameter by an O3D Param.
- virtual void SetEffectParam(
- RendererGLES2* renderer, GLES2Parameter param) = 0;
-
- // Resets a GLES2 Effect parameter to default (currently only unbinds textures
- // contained in Sampler params).
- virtual void ResetEffectParam(
- RendererGLES2* renderer, GLES2Parameter param) {}
-};
-
-// EffectGLES2 is an implementation of the Effect object for OpenGLES2. It
-// provides the API for setting the vertex and framgent shaders for the
-// Effect using the Cg Runtime. Currently the two shaders can either be
-// provided separately as shader code or together in an FX file.
-class EffectGLES2 : public Effect {
- public:
- explicit EffectGLES2(ServiceLocator* service_locator);
- virtual ~EffectGLES2();
-
- // Reads the vertex and fragment shaders from string in the FX format.
- // It returns true if the shaders were successfully compiled.
- virtual bool LoadFromFXString(const String& effect);
-
- // Binds the shaders to the device and sets up all the shader parameters using
- // the values from the matching Param's of the param_object.
- void PrepareForDraw(ParamCacheGLES2* param_cache_gl);
-
- // Removes any pipeline state-changes installed during a draw.
- void PostDraw(ParamCacheGLES2* param_cache_gl);
-
- // Gets info about the parameters this effect needs.
- // Overriden from Effect.
- virtual void GetParameterInfo(EffectParameterInfoArray* info_array);
-
- // Gets info about the streams this effect needs.
- // Overriden from Effect.
- virtual void GetStreamInfo(
- EffectStreamInfoArray* info_array);
-
- GLuint gl_program() { return gl_program_; }
- int compile_count() { return compile_count_; }
-
- private:
- // Loops through all the parameters in the ShapeDataGLES2 and updates the
- // corresponding parameter EffectGLES2 object
- void UpdateShaderUniformsFromEffect(ParamCacheGLES2* param_cache_gl);
- // Undoes the effect of the above. For now, this unbinds textures.
- void ResetShaderUniforms(ParamCacheGLES2* param_cache_gl);
- void GetShaderParamInfo(GLuint program,
- std::map<String, EffectParameterInfo>* info_map);
- void GetVaryingVertexShaderParamInfo(
- GLuint program,
- std::vector<EffectStreamInfo>* info_array);
- void ClearProgram();
- GLuint LoadShader(GLenum type, const char* shader_src);
-
- // TODO(o3d): remove these (OLD path for textures).
- void SetTexturesFromEffect(ParamCacheGLES2* param_cache_gl);
- void FillSamplerToTextureMap(const String &effect);
- String GetTextureNameFromSamplerParamName(const String &sampler_name);
-
- SemanticManager* semantic_manager_;
- RendererGLES2* renderer_;
-
- GLuint gl_program_;
- int compile_count_;
-
- // TODO(o3d): remove this (OLD path for textures).
- std::map<String, String> sampler_to_texture_map_;
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GLES2_EFFECT_GLES2_H_
-
diff --git a/o3d/core/cross/gles2/gles2_headers.h b/o3d/core/cross/gles2/gles2_headers.h
deleted file mode 100644
index f21317b..0000000
--- a/o3d/core/cross/gles2/gles2_headers.h
+++ /dev/null
@@ -1,153 +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_CORE_CROSS_GLES2_GL_HEADERS_H_
-#define O3D_CORE_CROSS_GLES2_GL_HEADERS_H_
-
-#if defined(GLES2_BACKEND_DESKTOP_GL)
-
-#include <GL/glew.h>
-#if defined(OS_WIN)
-#include <GL/wglew.h>
-#elif defined(OS_LINUX)
-#include <GL/glx.h>
-#endif
-
-// Use ARB_shader_object / ARB_vertex_shader functions to work when GL2 isn't
-// present but the extensions are.
-// Note that several GL2 functions are defined into the same ARB function (e.g.
-// glDeleteProgram and glDeleteShader into glDeleteObjectARB). That's expected.
-#undef glAttachShader
-#define glAttachShader glAttachObjectARB
-#undef glCompileShader
-#define glCompileShader glCompileShaderARB
-#undef glCreateProgram
-#define glCreateProgram glCreateProgramObjectARB
-#undef glCreateShader
-#define glCreateShader glCreateShaderObjectARB
-#undef glDeleteProgram
-#define glDeleteProgram glDeleteObjectARB
-#undef glDeleteShader
-#define glDeleteShader glDeleteObjectARB
-#undef glDisableVertexAttribArray
-#define glDisableVertexAttribArray glDisableVertexAttribArrayARB
-#undef glEnableVertexAttribArray
-#define glEnableVertexAttribArray glEnableVertexAttribArrayARB
-#undef glGetActiveAttrib
-#define glGetActiveAttrib glGetActiveAttribARB
-#undef glGetActiveUniform
-#define glGetActiveUniform glGetActiveUniformARB
-#undef glGetAttribLocation
-#define glGetAttribLocation glGetAttribLocationARB
-#undef glGetProgramInfoLog
-#define glGetProgramInfoLog glGetInfoLogARB
-#undef glGetProgramiv
-#define glGetProgramiv glGetObjectParameterivARB
-#undef glGetShaderInfoLog
-#define glGetShaderInfoLog glGetInfoLogARB
-#undef glGetShaderiv
-#define glGetShaderiv glGetObjectParameterivARB
-#undef glGetUniformLocation
-#define glGetUniformLocation glGetUniformLocationARB
-#undef glLinkProgram
-#define glLinkProgram glLinkProgramARB
-#undef glShaderSource
-#define glShaderSource glShaderSourceARB
-#undef glUniform1f
-#define glUniform1f glUniform1fARB
-#undef glUniform1fv
-#define glUniform1fv glUniform1fvARB
-#undef glUniform1i
-#define glUniform1i glUniform1iARB
-#undef glUniform1iv
-#define glUniform1iv glUniform1ivARB
-#undef glUniform2fv
-#define glUniform2fv glUniform2fvARB
-#undef glUniform3fv
-#define glUniform3fv glUniform3fvARB
-#undef glUniform4fv
-#define glUniform4fv glUniform4fvARB
-#undef glUniformMatrix4fv
-#define glUniformMatrix4fv glUniformMatrix4fvARB
-#undef glUseProgram
-#define glUseProgram glUseProgramObjectARB
-#undef glVertexAttribPointer
-#define glVertexAttribPointer glVertexAttribPointerARB
-
-#elif defined(GLES2_BACKEND_NATIVE_GLES2)
-
-#include <EGL/egl.h>
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
-
-#define glClearDepth glClearDepthf
-#define glDepthRange glDepthRangef
-
-// Buffer Objects
-#define glBindBufferARB glBindBuffer
-#define glBufferDataARB glBufferData
-#define glBufferSubDataARB glBufferSubData
-#define glDeleteBuffersARB glDeleteBuffers
-#define glGenBuffersARB glGenBuffers
-
-// Framebuffer Objects
-#define glBindFramebufferEXT glBindFramebuffer
-#define glBindRenderbufferEXT glBindRenderbuffer
-#define glCheckFramebufferStatusEXT glCheckFramebufferStatus
-#define glDeleteRenderbuffersEXT glDeleteRenderbuffers
-#define glDeleteFramebuffersEXT glDeleteFramebuffers
-#define glFramebufferRenderbufferEXT glFramebufferRenderbuffer
-#define glFramebufferTexture2DEXT glFramebufferTexture2D
-#define glGenFramebuffersEXT glGenFramebuffers
-#define glGenRenderbuffersEXT glGenRenderbuffers
-#define glRenderbufferStorageEXT glRenderbufferStorage
-
-#define GLEW_VERSION_2_0 true
-#define GLEW_VERSION_1_4 true
-
-// TODO(piman): handle gracefully the case where GL_EXT_bgra isn't present.
-#define GL_BGRA 0x80E1
-
-// TODO(piman): handle gracefully the case where GL_OES_half_float isn't
-// present.
-#define GL_HALF_FLOAT_ARB GL_HALF_FLOAT_OES
-
-#elif defined(GLES2_BACKEND_GLES2_COMMAND_BUFFERS)
-
-#include <GLES2/gl2.h>
-
-#else // GLES2_BACKEND_xxx not defined
-
-#error "GLES2_BACKEND_xxx not defined"
-
-#endif // GLES2_BACKEND_xxx
-
-#endif // O3D_CORE_CROSS_GLES2_GL_HEADERS_H_
diff --git a/o3d/core/cross/gles2/install_check.cc b/o3d/core/cross/gles2/install_check.cc
deleted file mode 100644
index 9ae59dd..0000000
--- a/o3d/core/cross/gles2/install_check.cc
+++ /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.
- */
-
-
-#include "core/cross/install_check.h"
-
-namespace o3d {
-
-bool RendererInstallCheck(std::string *error) {
- return true;
-}
-
-} // o3d
diff --git a/o3d/core/cross/gles2/param_cache_gles2.cc b/o3d/core/cross/gles2/param_cache_gles2.cc
deleted file mode 100644
index 4dc4d50..0000000
--- a/o3d/core/cross/gles2/param_cache_gles2.cc
+++ /dev/null
@@ -1,743 +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 definition of the ParamCacheGLES2 class.
-
-#include "core/cross/error.h"
-#include "core/cross/param_array.h"
-#include "core/cross/renderer.h"
-#include "core/cross/semantic_manager.h"
-#include "core/cross/gles2/param_cache_gles2.h"
-#include "core/cross/gles2/effect_gles2.h"
-#include "core/cross/gles2/sampler_gles2.h"
-#include "core/cross/gles2/renderer_gles2.h"
-#include "core/cross/element.h"
-#include "core/cross/draw_element.h"
-
-namespace o3d {
-
-namespace {
-
-String GetUniformSemantic(GLES2Parameter gl_param, const String& name) {
- return name;
-}
-
-} // anonymous namespace
-
-typedef std::vector<ParamObject *> ParamObjectList;
-
-ParamCacheGLES2::ParamCacheGLES2(SemanticManager* semantic_manager,
- Renderer* renderer)
- : semantic_manager_(semantic_manager),
- renderer_(renderer),
- last_compile_count_(0) {
-}
-
-bool ParamCacheGLES2::ValidateEffect(Effect* effect) {
- DLOG_ASSERT(effect);
-
- EffectGLES2* effect_gles2 = down_cast<EffectGLES2*>(effect);
- return (effect_gles2->compile_count() == last_compile_count_);
-}
-
-void ParamCacheGLES2::UpdateCache(Effect* effect,
- DrawElement* draw_element,
- Element* element,
- Material* material,
- ParamObject* override) {
- DLOG_ASSERT(effect);
- EffectGLES2* effect_gl = down_cast<EffectGLES2*>(effect);
-
- ScanGLEffectParameters(effect_gl->gl_program(),
- draw_element,
- element,
- material,
- override);
-
- last_compile_count_ = effect_gl->compile_count();
-}
-
-template <typename T>
-class TypedEffectParamHandlerGLES2 : public EffectParamHandlerGLES2 {
- public:
- explicit TypedEffectParamHandlerGLES2(T* param)
- : param_(param) {
- }
- virtual void SetEffectParam(RendererGLES2* renderer, GLES2Parameter gl_param);
- private:
- T* param_;
-};
-
-class EffectParamHandlerGLMatrixRows : public EffectParamHandlerGLES2 {
- public:
- explicit EffectParamHandlerGLMatrixRows(ParamMatrix4* param)
- : param_(param) {
- }
- virtual void SetEffectParam(RendererGLES2* renderer,
- GLES2Parameter gl_param) {
- // set the data as floats in row major order.
- Matrix4 mat = param_->value();
- glUniformMatrix4fv(gl_param, 1, GL_FALSE, &mat[0][0]);
- }
- private:
- ParamMatrix4* param_;
-};
-
-class EffectParamHandlerGLMatrixColumns : public EffectParamHandlerGLES2 {
- public:
- explicit EffectParamHandlerGLMatrixColumns(ParamMatrix4* param)
- : param_(param) {
- }
- virtual void SetEffectParam(
- RendererGLES2* renderer, GLES2Parameter gl_param) {
- // set the data as floats in column major order.
- Matrix4 mat = transpose(param_->value());
- glUniformMatrix4fv(gl_param, 1, GL_FALSE, &mat[0][0]);
- }
- private:
- ParamMatrix4* param_;
-};
-
-template <>
-void TypedEffectParamHandlerGLES2<ParamFloat>::SetEffectParam(
- RendererGLES2* renderer,
- GLES2Parameter gl_param) {
- Float f = param_->value();
- glUniform1f(gl_param, f);
-};
-
-template <>
-void TypedEffectParamHandlerGLES2<ParamFloat2>::SetEffectParam(
- RendererGLES2* renderer,
- GLES2Parameter gl_param) {
- Float2 f = param_->value();
- glUniform2fv(gl_param, 1, f.GetFloatArray());
-};
-
-template <>
-void TypedEffectParamHandlerGLES2<ParamFloat3>::SetEffectParam(
- RendererGLES2* renderer,
- GLES2Parameter gl_param) {
- Float3 f = param_->value();
- glUniform3fv(gl_param, 1, f.GetFloatArray());
-};
-
-template <>
-void TypedEffectParamHandlerGLES2<ParamFloat4>::SetEffectParam(
- RendererGLES2* renderer,
- GLES2Parameter gl_param) {
- Float4 f = param_->value();
- glUniform4fv(gl_param, 1, f.GetFloatArray());
-};
-
-template <>
-void TypedEffectParamHandlerGLES2<ParamInteger>::SetEffectParam(
- RendererGLES2* renderer,
- GLES2Parameter gl_param) {
- int i = param_->value();
- glUniform1i(gl_param, i);
-};
-
-template <>
-void TypedEffectParamHandlerGLES2<ParamBoolean>::SetEffectParam(
- RendererGLES2* renderer,
- GLES2Parameter gl_param) {
- int i = param_->value();
- glUniform1i(gl_param, i);
-};
-
-class EffectParamHandlerForSamplersGLES2 : public EffectParamHandlerGLES2 {
- public:
- explicit EffectParamHandlerForSamplersGLES2(ParamSampler* param)
- : param_(param) {
- }
- virtual void SetEffectParam(
- RendererGLES2* renderer, GLES2Parameter gl_param) {
- SamplerGLES2* sampler_gl = down_cast<SamplerGLES2*>(param_->value());
- if (!sampler_gl) {
- // Use the error sampler.
- sampler_gl = down_cast<SamplerGLES2*>(renderer->error_sampler());
- // If no error texture is set then generate an error.
- if (!renderer->error_texture()) {
- O3D_ERROR(param_->service_locator())
- << "Missing Sampler for ParamSampler " << param_->name();
- }
- }
- GLint handle = sampler_gl->SetTextureAndStates(gl_param);
- glUniform1iv(gl_param, 1, &handle);
- }
- virtual void ResetEffectParam(
- RendererGLES2* renderer, GLES2Parameter gl_param) {
- SamplerGLES2* sampler_gl = down_cast<SamplerGLES2*>(param_->value());
- if (!sampler_gl) {
- sampler_gl = down_cast<SamplerGLES2*>(renderer->error_sampler());
- }
- sampler_gl->ResetTexture(gl_param);
- }
- private:
- ParamSampler* param_;
-};
-
-template <typename T>
-class EffectParamArrayHandlerGLES2 : public EffectParamHandlerGLES2 {
- public:
- typedef typename T::DataType DataType;
- EffectParamArrayHandlerGLES2(ParamParamArray* param, GLsizei size)
- : param_(param),
- size_(size) {
- values_.reset(new DataType[size]);
- }
- virtual void SetEffectParam(
- RendererGLES2* renderer, GLES2Parameter gl_param) {
- ParamArray* param = param_->value();
- if (param) {
- if (size_ != static_cast<int>(param->size())) {
- O3D_ERROR(param->service_locator())
- << "number of params in ParamArray does not match number of params "
- << "needed by shader array";
- } else {
- for (int i = 0; i < size_; ++i) {
- Param* untyped_element = param->GetUntypedParam(i);
- // TODO(gman): Make this check happen when building the param cache.
- // To do that would require that ParamParamArray mark it's owner
- // as changed if a Param in it's ParamArray changes.
- if (untyped_element->IsA(T::GetApparentClass())) {
- SetElement(down_cast<T*>(untyped_element), &values_[i]);
- } else {
- O3D_ERROR(param->service_locator())
- << "Param in ParamArray at index " << i << " is not a "
- << T::GetApparentClassName();
- }
- }
- SetElements(gl_param, size_, values_.get());
- }
- }
- }
- void SetElement(T* param, DataType* value);
- void SetElements(GLES2Parameter gl_param, GLsizei size,
- const DataType* values);
-
- private:
- ParamParamArray* param_;
- scoped_array<DataType> values_;
- GLsizei size_;
-};
-
-class EffectParamArraySamplerHandlerGLES2 : public EffectParamHandlerGLES2 {
- public:
- explicit EffectParamArraySamplerHandlerGLES2(ParamParamArray* param,
- GLsizei size)
- : param_(param),
- size_(size) {
- values_.reset(new GLint[size]);
- }
- virtual void SetEffectParam(RendererGLES2* renderer,
- GLES2Parameter gl_param) {
- ParamArray* param = param_->value();
- if (param) {
- if (size_ != static_cast<int>(param->size())) {
- O3D_ERROR(param->service_locator())
- << "number of params in ParamArray does not match number of params "
- << "needed by shader array";
- } else {
- for (int i = 0; i < size_; ++i) {
- GLint handle = 0;
- Param* untyped_element = param->GetUntypedParam(i);
- // TODO(gman): Make this check happen when building the param cache.
- // To do that would require that ParamParamArray mark it's owner
- // as changed if a Param in it's ParamArray changes.
- if (untyped_element->IsA(ParamSampler::GetApparentClass())) {
- ParamSampler* element = down_cast<ParamSampler*>(untyped_element);
- SamplerGLES2* sampler_gl =
- down_cast<SamplerGLES2*>(element->value());
- if (!sampler_gl) {
- // Use the error sampler.
- sampler_gl = down_cast<SamplerGLES2*>(renderer->error_sampler());
- // If no error texture is set then generate an error.
- if (!renderer->error_texture()) {
- O3D_ERROR(param_->service_locator())
- << "Missing Sampler for ParamSampler '" << param_->name()
- << "' index " << i;
- }
- }
- handle = sampler_gl->SetTextureAndStates(gl_param);
- } else {
- O3D_ERROR(param->service_locator())
- << "Param in ParamArray at index " << i
- << " is not a ParamSampler";
- }
- values_[i] = handle;
- }
- glUniform1iv(gl_param, size_, values_.get());
- }
- }
- }
- virtual void ResetEffectParam(RendererGLES2* renderer,
- GLES2Parameter gl_param) {
- ParamArray* param = param_->value();
- if (param) {
- if (size_ == static_cast<int>(param->size())) {
- for (int i = 0; i < size_; ++i) {
- Param* untyped_element = param->GetUntypedParam(i);
- if (untyped_element->IsA(ParamSampler::GetApparentClass())) {
- ParamSampler* element = down_cast<ParamSampler*>(untyped_element);
- SamplerGLES2* sampler_gl =
- down_cast<SamplerGLES2*>(element->value());
- if (!sampler_gl) {
- sampler_gl = down_cast<SamplerGLES2*>(renderer->error_sampler());
- }
- sampler_gl->ResetTexture(gl_param);
- }
- }
- }
- }
- }
-
- private:
- ParamParamArray* param_;
- scoped_array<GLint> values_;
- GLsizei size_;
-};
-
-template<>
-void EffectParamArrayHandlerGLES2<ParamFloat>::SetElement(
- ParamFloat* param,
- float* value) {
- *value = param->value();
-}
-
-template<>
-void EffectParamArrayHandlerGLES2<ParamFloat>::SetElements(
- GLES2Parameter gl_param,
- GLsizei count,
- const float* values) {
- glUniform1fv(gl_param, count, values);
-}
-
-template<>
-void EffectParamArrayHandlerGLES2<ParamFloat2>::SetElement(
- ParamFloat2* param,
- Float2* value) {
- *value = param->value();
-}
-
-template<>
-void EffectParamArrayHandlerGLES2<ParamFloat2>::SetElements(
- GLES2Parameter gl_param,
- GLsizei count,
- const Float2* values) {
- glUniform2fv(gl_param, count, values[0].GetFloatArray());
-}
-
-template<>
-void EffectParamArrayHandlerGLES2<ParamFloat3>::SetElement(
- ParamFloat3* param,
- Float3* value) {
- *value = param->value();
-}
-
-template<>
-void EffectParamArrayHandlerGLES2<ParamFloat3>::SetElements(
- GLES2Parameter gl_param,
- GLsizei count,
- const Float3* values) {
- glUniform3fv(gl_param, count, values[0].GetFloatArray());
-}
-
-template<>
-void EffectParamArrayHandlerGLES2<ParamFloat4>::SetElement(
- ParamFloat4* param,
- Float4* value) {
- *value = param->value();
-}
-
-template<>
-void EffectParamArrayHandlerGLES2<ParamFloat4>::SetElements(
- GLES2Parameter gl_param,
- GLsizei count,
- const Float4* values) {
- glUniform4fv(gl_param, count, values[0].GetFloatArray());
-}
-
-class ColumnMajorParamMatrix4 : public ParamMatrix4 {
-};
-
-class RowMajorParamMatrix4 : public ParamMatrix4 {
-};
-
-template<>
-void EffectParamArrayHandlerGLES2<RowMajorParamMatrix4>::SetElement(
- RowMajorParamMatrix4* param,
- Matrix4* value) {
- // set the data as floats in row major order.
- *value = param->value();
-}
-
-template<>
-void EffectParamArrayHandlerGLES2<RowMajorParamMatrix4>::SetElements(
- GLES2Parameter gl_param,
- GLsizei count,
- const Matrix4* values) {
- glUniformMatrix4fv(gl_param, count, GL_FALSE,
- reinterpret_cast<const GLfloat*>(values_.get()));
-}
-
-template<>
-void EffectParamArrayHandlerGLES2<ColumnMajorParamMatrix4>::SetElement(
- ColumnMajorParamMatrix4* param,
- Matrix4* value) {
- // set the data as floats in row major order.
- *value = transpose(param->value());
-}
-
-template<>
-void EffectParamArrayHandlerGLES2<ColumnMajorParamMatrix4>::SetElements(
- GLES2Parameter gl_param,
- GLsizei count,
- const Matrix4* values) {
- // NOTE: The transpose happens in the function above because GLES2 requires
- // the transpose argument to this function to be GL_FALSE.
- glUniformMatrix4fv(gl_param, count, GL_FALSE,
- reinterpret_cast<const GLfloat*>(values_.get()));
-}
-
-template<>
-void EffectParamArrayHandlerGLES2<ParamBoolean>::SetElement(
- ParamBoolean* param,
- bool* value) {
- *value = param->value();
-}
-
-template<>
-void EffectParamArrayHandlerGLES2<ParamBoolean>::SetElements(
- GLES2Parameter gl_param,
- GLsizei count,
- const bool* values) {
- scoped_array<GLint> local(new GLint[count]);
- for (GLsizei ii = 0; ii < count; ++ii) {
- local[ii] = values[ii];
- }
- glUniform1iv(gl_param, count, local.get());
-}
-
-template<>
-void EffectParamArrayHandlerGLES2<ParamInteger>::SetElement(
- ParamInteger* param,
- int* value) {
- *value = param->value();
-}
-
-template<>
-void EffectParamArrayHandlerGLES2<ParamInteger>::SetElements(
- GLES2Parameter gl_param,
- GLsizei count,
- const int* values) {
- glUniform1iv(gl_param, count, values);
-}
-
-static EffectParamHandlerGLES2::Ref GetHandlerFromParamAndGLType(
- EffectGLES2* effect_gl,
- Param *param,
- GLenum gl_type,
- GLsizei size) {
- EffectParamHandlerGLES2::Ref handler;
- if (param->IsA(ParamParamArray::GetApparentClass())) {
- ParamParamArray* param_param_array = down_cast<ParamParamArray*>(param);
- switch (gl_type) {
- case GL_FLOAT:
- handler = EffectParamHandlerGLES2::Ref(
- new EffectParamArrayHandlerGLES2<ParamFloat>(param_param_array,
- size));
- break;
- case GL_FLOAT_VEC2:
- handler = EffectParamHandlerGLES2::Ref(
- new EffectParamArrayHandlerGLES2<ParamFloat2>(param_param_array,
- size));
- break;
- case GL_FLOAT_VEC3:
- handler = EffectParamHandlerGLES2::Ref(
- new EffectParamArrayHandlerGLES2<ParamFloat3>(param_param_array,
- size));
- break;
- case GL_FLOAT_VEC4:
- handler = EffectParamHandlerGLES2::Ref(
- new EffectParamArrayHandlerGLES2<ParamFloat4>(param_param_array,
- size));
- break;
- case GL_FLOAT_MAT4:
- if (effect_gl->matrix_load_order() == Effect::COLUMN_MAJOR) {
- handler = EffectParamHandlerGLES2::Ref(
- new EffectParamArrayHandlerGLES2<ColumnMajorParamMatrix4>(
- param_param_array, size));
- } else {
- handler = EffectParamHandlerGLES2::Ref(
- new EffectParamArrayHandlerGLES2<RowMajorParamMatrix4>(
- param_param_array, size));
- }
- break;
- case GL_INT:
- handler = EffectParamHandlerGLES2::Ref(
- new EffectParamArrayHandlerGLES2<ParamInteger>(param_param_array,
- size));
- break;
- case GL_BOOL:
- handler = EffectParamHandlerGLES2::Ref(
- new EffectParamArrayHandlerGLES2<ParamBoolean>(param_param_array,
- size));
- break;
- case GL_SAMPLER_2D:
- case GL_SAMPLER_CUBE:
- handler = EffectParamHandlerGLES2::Ref(
- new EffectParamArraySamplerHandlerGLES2(param_param_array, size));
- break;
- default:
- break;
- }
- } else if (param->IsA(ParamMatrix4::GetApparentClass())) {
- if (gl_type == GL_FLOAT_MAT4) {
- if (effect_gl->matrix_load_order() == Effect::COLUMN_MAJOR) {
- // set the data as floats in column major order.
- handler = EffectParamHandlerGLES2::Ref(
- new EffectParamHandlerGLMatrixColumns(
- down_cast<ParamMatrix4*>(param)));
- } else {
- // set the data as floats in row major order.
- handler = EffectParamHandlerGLES2::Ref(
- new EffectParamHandlerGLMatrixRows(
- down_cast<ParamMatrix4*>(param)));
- }
- }
- } else if (param->IsA(ParamFloat::GetApparentClass())) {
- if (gl_type == GL_FLOAT) {
- handler = EffectParamHandlerGLES2::Ref(
- new TypedEffectParamHandlerGLES2<ParamFloat>(
- down_cast<ParamFloat*>(param)));
- }
- } else if (param->IsA(ParamFloat2::GetApparentClass())) {
- if (gl_type == GL_FLOAT_VEC2) {
- handler = EffectParamHandlerGLES2::Ref(
- new TypedEffectParamHandlerGLES2<ParamFloat2>(
- down_cast<ParamFloat2*>(param)));
- }
- } else if (param->IsA(ParamFloat3::GetApparentClass())) {
- if (gl_type == GL_FLOAT_VEC3) {
- handler = EffectParamHandlerGLES2::Ref(
- new TypedEffectParamHandlerGLES2<ParamFloat3>(
- down_cast<ParamFloat3*>(param)));
- }
- } else if (param->IsA(ParamFloat4::GetApparentClass())) {
- if (gl_type == GL_FLOAT_VEC4) {
- handler = EffectParamHandlerGLES2::Ref(
- new TypedEffectParamHandlerGLES2<ParamFloat4>(
- down_cast<ParamFloat4*>(param)));
- }
- } else if (param->IsA(ParamInteger::GetApparentClass())) {
- if (gl_type == GL_INT) {
- handler = EffectParamHandlerGLES2::Ref(
- new TypedEffectParamHandlerGLES2<ParamInteger>(
- down_cast<ParamInteger*>(param)));
- }
- } else if (param->IsA(ParamBoolean::GetApparentClass())) {
- if (gl_type == GL_BOOL) {
- handler = EffectParamHandlerGLES2::Ref(
- new TypedEffectParamHandlerGLES2<ParamBoolean>(
- down_cast<ParamBoolean*>(param)));
- }
- } else if (param->IsA(ParamSampler::GetApparentClass())) {
- if (gl_type == GL_SAMPLER_2D ||
- gl_type == GL_SAMPLER_CUBE) {
- handler = EffectParamHandlerGLES2::Ref(
- new EffectParamHandlerForSamplersGLES2(
- down_cast<ParamSampler*>(param)));
- }
- }
- return handler;
-}
-
-// Local helper function for scanning varying Cg parameters of a
-// program or effect and recording their entries into the varying map.
-static void ScanVaryingParameters(GLuint gl_program,
- ParamCacheGLES2* param_cache_gl) {
- GLint num_attribs = 0;
- GLint max_len = 0;
- glGetProgramiv(gl_program, GL_ACTIVE_ATTRIBUTES, &num_attribs);
- glGetProgramiv(gl_program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &max_len);
- // TODO(gman): Should we check for error?
- scoped_array<char> name_buffer(new char[max_len + 1]);
- for (GLint ii = 0; ii < num_attribs; ++ii) {
- GLsizei length;
- GLsizei size;
- GLenum type;
- glGetActiveAttrib(
- gl_program, ii, max_len + 1, &length, &size, &type, name_buffer.get());
- // TODO(gman): Should we check for error?
- GLint location = glGetAttribLocation(gl_program, name_buffer.get());
- if (location != -1)
- param_cache_gl->varying_map().insert(std::make_pair(location, ii));
- }
-}
-
-// Local helper function for scanning uniform Cg parameters of a
-// program or effect and recording their entries into the parameter maps.
-static void ScanUniformParameters(SemanticManager* semantic_manager,
- Renderer* renderer,
- GLuint gl_program,
- ParamCacheGLES2* param_cache_gl,
- const ParamObjectList& param_objects,
- EffectGLES2* effect_gl) {
- GLint num_uniforms = 0;
- GLint max_len = 0;
- glGetProgramiv(gl_program, GL_ACTIVE_UNIFORMS, &num_uniforms);
- glGetProgramiv(gl_program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max_len);
- // TODO(gman): Should we check for error?
- scoped_array<char> name_buffer(new char[max_len + 1]);
- for (GLint ii = 0; ii < num_uniforms; ++ii) {
- GLsizei length;
- GLsizei size;
- GLenum gl_type;
- glGetActiveUniform(
- gl_program, ii,
- max_len + 1, &length, &size, &gl_type, name_buffer.get());
- // TODO(gman): Should we check for error?
- GLint location = glGetUniformLocation(gl_program, name_buffer.get());
- String name(name_buffer.get(), length);
-
- // Find a Param of the same name, and record the link.
- if (param_cache_gl->uniform_map().find(ii) ==
- param_cache_gl->uniform_map().end()) {
- const ObjectBase::Class *sem_class = NULL;
- // Try looking by SAS class name.
- String semantic = GetUniformSemantic(ii, name);
- if (!semantic.empty()) {
- sem_class = semantic_manager->LookupSemantic(semantic);
- }
- EffectParamHandlerGLES2::Ref handler;
- // Look through all the param objects to find a matching param.
- unsigned last = param_objects.size() - 1;
- for (unsigned int i = 0; i < param_objects.size(); ++i) {
- ParamObject *param_object = param_objects[i];
- Param *param = param_object->GetUntypedParam(name);
- if (!param && sem_class) {
- param = param_object->GetUntypedParam(sem_class->name());
- }
- if (!param) {
- // If this is the last param object and we didn't find a matching
- // param then if it's a sampler use the error sampler
- if (i == last) {
- if (gl_type == GL_SAMPLER_2D || gl_type == GL_SAMPLER_CUBE) {
- param = renderer->error_param_sampler();
- }
- }
- if (!param) {
- continue;
- }
- }
- handler = GetHandlerFromParamAndGLType(effect_gl, param, gl_type, size);
- if (!handler.IsNull()) {
- param_cache_gl->uniform_map().insert(
- std::make_pair(location, handler));
- DLOG(INFO) << "ElementGLES2 Matched gl_paramETER \""
- << name << "\" to Param \""
- << param->name() << "\" from \""
- << param_object->name() << "\"";
- break;
- } else {
- // We found a param, but it didn't match the type. keep looking.
- DLOG(ERROR) << "ElementGLES2 Param \""
- << param->name() << "\" type \""
- << param->GetClassName() << "\" from \""
- << param_object->name()
- << "\" does not match gl_paramETER \""
- << name << "\"";
- }
- }
- if (handler.IsNull()) {
- DLOG(ERROR) << "No matching Param for gl_paramETER \""
- << name << "\"";
- }
- }
- }
-}
-
-static void DoScanGLEffectParameters(SemanticManager* semantic_manager,
- Renderer* renderer,
- ParamCacheGLES2* param_cache_gl,
- GLuint gl_program,
- EffectGLES2* effect_gl,
- const ParamObjectList& param_objects) {
- ScanVaryingParameters(gl_program, param_cache_gl);
- ScanUniformParameters(semantic_manager,
- renderer,
- gl_program,
- param_cache_gl,
- param_objects,
- effect_gl);
-}
-
-// Search the leaf parameters of a CGeffect and it's shaders for parameters
-// using cgGetFirstEffectParameter() / cgGetFirstLeafParameter() /
-// cgGetNextLeafParameter(). Add the GLES2Parameters found to the parameter
-// maps on the DrawElement.
-void ParamCacheGLES2::ScanGLEffectParameters(GLuint gl_program,
- ParamObject* draw_element,
- ParamObject* element,
- Material* material,
- ParamObject* override) {
- DLOG(INFO) << "DrawElementGLES2 ScanGLEffectParameters";
- DLOG_ASSERT(material);
- DLOG_ASSERT(draw_element);
- DLOG_ASSERT(element);
- EffectGLES2* effect_gl = static_cast<EffectGLES2*>(material->effect());
- DLOG_ASSERT(effect_gl);
- if (gl_program == 0) {
- DLOG(ERROR) << "Can't scan an empty Program for Parameters.";
- return;
- }
- uniform_map_.clear();
- varying_map_.clear();
- ParamObjectList param_object_list;
- param_object_list.push_back(override);
- param_object_list.push_back(draw_element);
- param_object_list.push_back(element);
- param_object_list.push_back(material);
- param_object_list.push_back(effect_gl);
- param_object_list.push_back(semantic_manager_->sas_param_object());
- DoScanGLEffectParameters(semantic_manager_,
- renderer_,
- this,
- gl_program,
- effect_gl,
- param_object_list);
-}
-
-} // namespace o3d
-
diff --git a/o3d/core/cross/gles2/param_cache_gles2.h b/o3d/core/cross/gles2/param_cache_gles2.h
deleted file mode 100644
index f3c193e..0000000
--- a/o3d/core/cross/gles2/param_cache_gles2.h
+++ /dev/null
@@ -1,96 +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 declaration of the ParamCacheGLES2 class.
-
-#ifndef O3D_CORE_CROSS_GLES2_PARAM_CACHE_GLES2_H_
-#define O3D_CORE_CROSS_GLES2_PARAM_CACHE_GLES2_H_
-
-#include <map>
-#include "core/cross/gles2/gles2_headers.h"
-#include "core/cross/param_cache.h"
-#include "core/cross/gles2/effect_gles2.h"
-
-namespace o3d {
-
-class ParamTexture;
-class SemanticManager;
-
-class ParamCacheGLES2 : public ParamCache {
- public:
- ParamCacheGLES2(SemanticManager* semantic_manager, Renderer* renderer);
-
- typedef std::map<GLES2Parameter, int> VaryingParameterMap;
- typedef std::map<GLES2Parameter,
- EffectParamHandlerGLES2::Ref> UniformParameterMap;
- typedef std::map<GLES2Parameter, ParamTexture*> SamplerParameterMap;
-
- // Overridden from ParamCache.
- virtual void UpdateCache(Effect* effect,
- DrawElement* draw_element,
- Element* element,
- Material* material,
- ParamObject* override);
-
- VaryingParameterMap& varying_map() { return varying_map_; }
- UniformParameterMap& uniform_map() { return uniform_map_; }
-
- protected:
- // Overridden from ParamCache
- // Validates platform specific information about the effect.
- virtual bool ValidateEffect(Effect* effect);
-
- private:
- SemanticManager* semantic_manager_;
- Renderer* renderer_;
-
- // Used to track if the shader on the Effect has changed and
- // therefore we need to rebuild our cache.
- int last_compile_count_;
-
- // Search the leaf parameters of a GLSL program for parameters and add the
- // parameters found to the parameter maps on the DrawElement.
- void ScanGLEffectParameters(GLuint gl_program,
- ParamObject* draw_element,
- ParamObject* element,
- Material* material,
- ParamObject* override);
-
- // A map of varying GLES2Parameter to Stream index.
- VaryingParameterMap varying_map_;
- // A map of uniform GLES2Parameter to Param objects.
- UniformParameterMap uniform_map_;
-};
-} // o3d
-
-#endif // O3D_CORE_CROSS_GLES2_PARAM_CACHE_GLES2_H_
-
diff --git a/o3d/core/cross/gles2/primitive_gles2.cc b/o3d/core/cross/gles2/primitive_gles2.cc
deleted file mode 100644
index e229833..0000000
--- a/o3d/core/cross/gles2/primitive_gles2.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.
- */
-
-
-// This file contains the definition of PrimitiveGLES2.
-
-#include <algorithm>
-
-#include "core/cross/stream.h"
-#include "core/cross/error.h"
-#include "core/cross/gles2/buffer_gles2.h"
-#include "core/cross/gles2/effect_gles2.h"
-#include "core/cross/gles2/primitive_gles2.h"
-#include "core/cross/gles2/renderer_gles2.h"
-#include "core/cross/gles2/draw_element_gles2.h"
-#include "core/cross/gles2/stream_bank_gles2.h"
-#include "core/cross/gles2/utils_gles2-inl.h"
-
-// Someone defines min, conflicting with std::min
-#ifdef min
-#undef min
-#endif
-
-namespace o3d {
-
-// Number of times to log a repeated event before giving up.
-const int kNumLoggedEvents = 5;
-
-// PrimitiveGLES2 functions ----------------------------------------------------
-
-PrimitiveGLES2::PrimitiveGLES2(ServiceLocator* service_locator)
- : Primitive(service_locator) {
- DLOG(INFO) << "PrimitiveGLES2 Construct";
-}
-
-PrimitiveGLES2::~PrimitiveGLES2() {
- DLOG(INFO) << "PrimitiveGLES2 Destruct";
-}
-
-// Binds the vertex and index streams required to draw the shape. If the
-// vertex or fragment programs have changed since the last time this method
-// was called (or it's the first time it's getting called) then it forces
-// an update of the mapping between the Shape Param's and the shader parameters
-// and also fills in for any missing streams.
-void PrimitiveGLES2::PlatformSpecificRender(Renderer* renderer,
- DrawElement* draw_element,
- Material* material,
- ParamObject* override,
- ParamCache* param_cache) {
- DLOG_ASSERT(material);
- DLOG_ASSERT(draw_element);
- DLOG_ASSERT(param_cache);
- DLOG_FIRST_N(INFO, kNumLoggedEvents) << "PrimitiveGLES2 Draw \""
- << draw_element->name() << "\"";
- DrawElementGLES2* draw_element_gl =
- down_cast<DrawElementGLES2*>(draw_element);
- EffectGLES2* effect_gl = down_cast<EffectGLES2*>(material->effect());
- DLOG_ASSERT(effect_gl);
- StreamBankGLES2* stream_bank_gl = down_cast<StreamBankGLES2*>(stream_bank());
- DLOG_ASSERT(stream_bank_gl);
-
- ParamCacheGLES2* param_cache_gl = down_cast<ParamCacheGLES2*>(param_cache);
- ParamCacheGLES2::VaryingParameterMap& varying_map =
- param_cache_gl->varying_map();
-
- // If this PrimitiveGLES2 has an effect we haven't seen before (or it's the
- // first time through), initalize the parameter lists before drawing with it.
- if (effect_gl->gl_program()) {
- // Set up the current CGeffect.
- if (!param_cache_gl->ValidateAndCacheParams(effect_gl,
- draw_element_gl,
- this,
- stream_bank_gl,
- material,
- override)) {
- String missing_stream;
- if (!stream_bank_gl->CheckForMissingVertexStreams(
- varying_map,
- effect_gl->gl_program(),
- &missing_stream)) {
- param_cache_gl->ClearParamCache();
- O3D_ERROR(service_locator())
- << "Required Stream "
- << missing_stream << " missing on Primitive '" << name()
- << "' using Material '" << material->name()
- << "' with Effect '" << effect_gl->name() << "'";
- return;
- }
- }
- } else {
- O3D_ERROR(service_locator())
- << "No CG effect provided in Effect \""
- << effect_gl->name() << "\" used by Material \""
- << material->name() << "\" in Shape \""
- << draw_element_gl->name() << "\". Drawing nothing.";
- return;
- }
-
- // Make sure our streams are up to date (skinned, etc..)
- stream_bank_gl->UpdateStreams();
-
- unsigned int max_vertices;
- if (!stream_bank_gl->BindStreamsForRendering(varying_map,
- effect_gl->gl_program(),
- &max_vertices)) {
- return;
- }
-
- // TODO(o3d): move these checks at 'set' time instead of draw time.
-
- bool draw = true;
- if (number_vertices_ > max_vertices) {
- O3D_ERROR(service_locator())
- << "Trying to draw with " << number_vertices_
- << " vertices when there are only " << max_vertices
- << " available in the buffers. Skipping primitive.";
- draw = false;
- }
-
- unsigned int index_count;
-
- if (!Primitive::GetIndexCount(primitive_type_,
- number_primitives_,
- &index_count)) {
- O3D_ERROR(service_locator())
- << "Unknown Primitive Type in GetIndexCount: "
- << primitive_type_ << ". Skipping primitive "
- << name();
- draw = false;
- }
-
- if (indexed()) {
- // Re-bind the index buffer for this shape
- IndexBufferGLES2 *ibuffer = down_cast<IndexBufferGLES2*>(index_buffer());
-
- unsigned int max_indices = ibuffer->num_elements();
-
- if (index_count > max_indices) {
- O3D_ERROR(service_locator())
- << "Trying to draw with " << index_count
- << " indices when only " << max_indices
- << " are available in the buffer. Skipping shape.";
- draw = false;
- }
-
- // TODO(o3d): Also check that indices in the index buffer are less than
- // max_vertices_. Needs support from the index buffer (scan indices on
- // Unlock).
-
- glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, ibuffer->gl_buffer());
- }
-
- // Set up the shaders in this drawcall from the Effect.
- effect_gl->PrepareForDraw(param_cache_gl);
-
- // Do the drawcall.
- GLenum gl_primitive_type = GL_NONE;
- switch (primitive_type_) {
- case Primitive::POINTLIST : {
- if (indexed()) {
- O3D_ERROR(service_locator())
- << "POINTLIST unsupported for indexed primitives for primitive "
- << name();
- draw = false;
- } else {
- gl_primitive_type = GL_POINTS;
- }
- break;
- }
- case Primitive::LINELIST : {
- DLOG_FIRST_N(INFO, kNumLoggedEvents)
- << "Draw " << number_primitives_ << " GL_LINES";
- gl_primitive_type = GL_LINES;
- break;
- }
- case Primitive::LINESTRIP : {
- DLOG_FIRST_N(INFO, kNumLoggedEvents)
- << "Draw " << number_primitives_ << " GL_LINE_STRIP";
- gl_primitive_type = GL_LINE_STRIP;
- break;
- }
- case Primitive::TRIANGLELIST : {
- DLOG_FIRST_N(INFO, kNumLoggedEvents)
- << "Draw " << number_primitives_ << " GL_TRIANGLES";
- gl_primitive_type = GL_TRIANGLES;
- break;
- }
- case Primitive::TRIANGLESTRIP : {
- DLOG_FIRST_N(INFO, kNumLoggedEvents)
- << "Draw " << number_primitives_ << " GL_TRIANGLE_STRIP";
- gl_primitive_type = GL_TRIANGLE_STRIP;
- break;
- }
- case Primitive::TRIANGLEFAN : {
- DLOG_FIRST_N(INFO, kNumLoggedEvents)
- << "Draw " << number_primitives_ << " GL_TRIANGLE_FAN";
- gl_primitive_type = GL_TRIANGLE_FAN;
- break;
- }
- default : {
- DLOG(ERROR) << "Unknown Primitive Type in Primitive: "
- << primitive_type_;
- draw = false;
- }
- }
- if (draw) {
- DCHECK_NE(gl_primitive_type, static_cast<unsigned int>(GL_NONE));
- renderer->AddPrimitivesRendered(number_primitives_);
- if (indexed()) {
- glDrawElements(gl_primitive_type,
- index_count,
- GL_UNSIGNED_INT,
- BufferOffset(start_index() * sizeof(uint32))); // NOLINT
- } else {
- glDrawArrays(gl_primitive_type, start_index(), index_count);
- }
- }
-
- // Clean up the shaders.
- effect_gl->PostDraw(param_cache_gl);
-
- // Disable the vertex attribute states set earlier.
- for (ParamCacheGLES2::VaryingParameterMap::iterator i = varying_map.begin();
- i != varying_map.end();
- ++i) {
- glDisableVertexAttribArray(i->first);
- }
- CHECK_GL_ERROR();
-}
-
-} // namespace o3d
-
diff --git a/o3d/core/cross/gles2/primitive_gles2.h b/o3d/core/cross/gles2/primitive_gles2.h
deleted file mode 100644
index 2191033..0000000
--- a/o3d/core/cross/gles2/primitive_gles2.h
+++ /dev/null
@@ -1,64 +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 declaration of the PrimitiveGLES2 class.
-
-#ifndef O3D_CORE_CROSS_GLES2_PRIMITIVE_GLES2_H_
-#define O3D_CORE_CROSS_GLES2_PRIMITIVE_GLES2_H_
-
-#include <map>
-#include "core/cross/primitive.h"
-#include "core/cross/gles2/param_cache_gles2.h"
-
-namespace o3d {
-
-// PrimitiveGLES2 is the OpenGLES2 implementation of the Primitive. It provides
-// the necessary interfaces for setting the geometry streams on the Primitive.
-class PrimitiveGLES2 : public Primitive {
- public:
- explicit PrimitiveGLES2(ServiceLocator* service_locator);
- virtual ~PrimitiveGLES2();
-
- protected:
- // Overridden from Primitive.
- virtual void PlatformSpecificRender(Renderer* renderer,
- DrawElement* draw_element,
- Material* material,
- ParamObject* override,
- ParamCache* param_cache);
-
- private:
-};
-} // o3d
-
-#endif // O3D_CORE_CROSS_GLES2_PRIMITIVE_GLES2_H_
-
diff --git a/o3d/core/cross/gles2/render_surface_gles2.cc b/o3d/core/cross/gles2/render_surface_gles2.cc
deleted file mode 100644
index 02b2ee3..0000000
--- a/o3d/core/cross/gles2/render_surface_gles2.cc
+++ /dev/null
@@ -1,143 +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 RenderSurfaceGLES2 and
-// RenderDepthStencilSurfaceGLES2.
-
-#include "core/cross/gles2/render_surface_gles2.h"
-#include "core/cross/gles2/utils_gles2-inl.h"
-#include "core/cross/renderer.h"
-
-namespace o3d {
-
-RenderSurfaceGLES2::RenderSurfaceGLES2(ServiceLocator *service_locator,
- int width,
- int height,
- GLenum cube_face,
- int mip_level,
- Texture *texture)
- : RenderSurface(service_locator, width, height, texture),
- cube_face_(cube_face),
- mip_level_(mip_level) {
- DCHECK(texture);
-}
-
-RenderSurfaceGLES2::~RenderSurfaceGLES2() {
-}
-
-bool RenderSurfaceGLES2::PlatformSpecificGetIntoBitmap(
- Bitmap::Ref bitmap) const {
- Renderer* renderer = service_locator()->GetService<Renderer>();
- DCHECK(renderer);
- DCHECK(bitmap->width() == static_cast<unsigned int>(clip_width()) &&
- bitmap->height() == static_cast<unsigned int>(clip_height()) &&
- bitmap->num_mipmaps() == 1 &&
- bitmap->format() == Texture::ARGB8);
-
- const RenderSurface* old_render_surface;
- const RenderDepthStencilSurface* old_depth_surface;
- bool old_is_back_buffer;
-
- renderer->GetRenderSurfaces(&old_render_surface, &old_depth_surface,
- &old_is_back_buffer);
- renderer->SetRenderSurfaces(this, NULL, false);
-
- ::glReadPixels(0, 0, clip_width(), clip_height(), GL_BGRA, GL_UNSIGNED_BYTE,
- bitmap->image_data());
-
- renderer->SetRenderSurfaces(old_render_surface, old_depth_surface,
- old_is_back_buffer);
-
- return true;
-}
-
-RenderDepthStencilSurfaceGLES2::RenderDepthStencilSurfaceGLES2(
- ServiceLocator *service_locator,
- int width,
- int height)
- : RenderDepthStencilSurface(service_locator, width, height) {
-
-#ifndef DISABLE_FBO
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- // If packed depth stencil is supported, create only one buffer for both
- // depth and stencil.
- // TODO(piman): on GLES, test GL_OES_packed_depth_stencil
- if (GLEW_EXT_packed_depth_stencil) {
- glGenRenderbuffersEXT(1, render_buffers_);
- glBindRenderbufferEXT(GL_RENDERBUFFER, render_buffers_[0]);
- glRenderbufferStorageEXT(GL_RENDERBUFFER,
- GL_DEPTH24_STENCIL8_EXT,
- width,
- height);
- CHECK_GL_ERROR();
- render_buffers_[1] = render_buffers_[0];
- return;
- }
-#endif
- glGenRenderbuffersEXT(2, render_buffers_);
- glBindRenderbufferEXT(GL_RENDERBUFFER, render_buffers_[0]);
- glRenderbufferStorageEXT(GL_RENDERBUFFER,
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- GL_DEPTH_COMPONENT24,
-#else
- // On GLES, only 16bit depth is available by default.
- // TODO(piman): test for GL_OES_depth24 or 32 and
- // use those.
- GL_DEPTH_COMPONENT16,
-#endif
- width,
- height);
- CHECK_GL_ERROR();
-
- glBindRenderbufferEXT(GL_RENDERBUFFER, render_buffers_[1]);
- glRenderbufferStorageEXT(GL_RENDERBUFFER,
- GL_STENCIL_INDEX8,
- width,
- height);
- CHECK_GL_ERROR();
-#endif
-}
-
-RenderDepthStencilSurfaceGLES2::~RenderDepthStencilSurfaceGLES2() {
-#ifndef DISABLE_FBO
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- // TODO(piman): on GLES, test GL_OES_packed_depth_stencil
- if (GLEW_EXT_packed_depth_stencil) {
- glDeleteRenderbuffersEXT(1, render_buffers_);
- return;
- }
-#endif
- glDeleteRenderbuffersEXT(2, render_buffers_);
-#endif
-}
-
-} // end namespace o3d
diff --git a/o3d/core/cross/gles2/render_surface_gles2.h b/o3d/core/cross/gles2/render_surface_gles2.h
deleted file mode 100644
index df5825b..0000000
--- a/o3d/core/cross/gles2/render_surface_gles2.h
+++ /dev/null
@@ -1,111 +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 declarations for RenderSurfaceGLES2 and
-// RenderDepthStencilSurfaceGLES2.
-
-#ifndef O3D_CORE_CROSS_GLES2_RENDER_SURFACE_GLES2_H_
-#define O3D_CORE_CROSS_GLES2_RENDER_SURFACE_GLES2_H_
-
-#include "core/cross/gles2/gles2_headers.h"
-#include "core/cross/render_surface.h"
-#include "core/cross/texture.h"
-
-namespace o3d {
-
-class RenderSurfaceGLES2 : public RenderSurface {
- public:
- typedef SmartPointer<RenderSurfaceGLES2> Ref;
-
- // Constructs a RenderSurfaceGLES2 instance associated with the texture
- // argument.
- // Parameters:
- // service_locator: Service locator for the instance.
- // width: The width of the surface, in pixels.
- // height: The height of the surface, in pixels.
- // cube_face: The face of the cube texture to which the surface is to be
- // associated. NOTE: If the texture is a 2d texture, then the value of
- // this argument is irrelevent.
- // mip_level: The mip-level of the texture to associate with the surface.
- // texture: The texture to associate with the surface.
- RenderSurfaceGLES2(ServiceLocator *service_locator,
- int width,
- int height,
- GLenum cube_face,
- int mip_level,
- Texture *texture);
- virtual ~RenderSurfaceGLES2();
-
- GLenum cube_face() const {
- return cube_face_;
- }
-
- int mip_level() const {
- return mip_level_;
- }
-
- protected:
- // The platform specific part of GetIntoBitmap.
- virtual bool PlatformSpecificGetIntoBitmap(Bitmap::Ref bitmap) const;
-
- private:
- GLenum cube_face_;
- int mip_level_;
- DISALLOW_COPY_AND_ASSIGN(RenderSurfaceGLES2);
-};
-
-class RenderDepthStencilSurfaceGLES2 : public RenderDepthStencilSurface {
- public:
- typedef SmartPointer<RenderDepthStencilSurfaceGLES2> Ref;
-
- RenderDepthStencilSurfaceGLES2(ServiceLocator *service_locator,
- int width,
- int height);
- virtual ~RenderDepthStencilSurfaceGLES2();
-
- GLuint depth_buffer() const {
- return render_buffers_[0];
- }
-
- GLuint stencil_buffer() const {
- return render_buffers_[1];
- }
- private:
- // Handles to the depth and stencil render-buffers, respectively.
- GLuint render_buffers_[2];
- DISALLOW_COPY_AND_ASSIGN(RenderDepthStencilSurfaceGLES2);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GLES2_RENDER_SURFACE_GLES2_H_
-
diff --git a/o3d/core/cross/gles2/renderer_gles2.cc b/o3d/core/cross/gles2/renderer_gles2.cc
deleted file mode 100644
index 47939c5..0000000
--- a/o3d/core/cross/gles2/renderer_gles2.cc
+++ /dev/null
@@ -1,1795 +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 definition of the RendererGLES2 class that
-// implements the abstract Renderer API using OpenGLES2.
-
-#include "core/cross/gles2/renderer_gles2.h"
-
-#include "core/cross/error.h"
-#include "core/cross/gles2/buffer_gles2.h"
-#include "core/cross/gles2/draw_element_gles2.h"
-#include "core/cross/gles2/effect_gles2.h"
-#include "core/cross/gles2/param_cache_gles2.h"
-#include "core/cross/gles2/primitive_gles2.h"
-#include "core/cross/gles2/render_surface_gles2.h"
-#include "core/cross/gles2/sampler_gles2.h"
-#include "core/cross/gles2/stream_bank_gles2.h"
-#include "core/cross/gles2/texture_gles2.h"
-#include "core/cross/gles2/utils_gles2-inl.h"
-#include "core/cross/gles2/utils_gles2.h"
-#include "core/cross/material.h"
-#include "core/cross/semantic_manager.h"
-#include "core/cross/features.h"
-#include "core/cross/shape.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-namespace {
-
-GLenum ConvertCmpFunc(State::Comparison cmp) {
- switch (cmp) {
- case State::CMP_ALWAYS:
- return GL_ALWAYS;
- case State::CMP_NEVER:
- return GL_NEVER;
- case State::CMP_LESS:
- return GL_LESS;
- case State::CMP_GREATER:
- return GL_GREATER;
- case State::CMP_LEQUAL:
- return GL_LEQUAL;
- case State::CMP_GEQUAL:
- return GL_GEQUAL;
- case State::CMP_EQUAL:
- return GL_EQUAL;
- case State::CMP_NOTEQUAL:
- return GL_NOTEQUAL;
- default:
- break;
- }
- return GL_ALWAYS;
-}
-
-#if defined(GLES2_BACKEND_DESKTOP_GL)
-GLenum ConvertFillMode(State::Fill mode) {
- switch (mode) {
- case State::POINT:
- return GL_POINT;
- case State::WIREFRAME:
- return GL_LINE;
- case State::SOLID:
- return GL_FILL;
- default:
- break;
- }
- return GL_FILL;
-}
-#endif
-
-GLenum ConvertBlendFunc(State::BlendingFunction blend_func) {
- switch (blend_func) {
- case State::BLENDFUNC_ZERO:
- return GL_ZERO;
- case State::BLENDFUNC_ONE:
- return GL_ONE;
- case State::BLENDFUNC_SOURCE_COLOR:
- return GL_SRC_COLOR;
- case State::BLENDFUNC_INVERSE_SOURCE_COLOR:
- return GL_ONE_MINUS_SRC_COLOR;
- case State::BLENDFUNC_SOURCE_ALPHA:
- return GL_SRC_ALPHA;
- case State::BLENDFUNC_INVERSE_SOURCE_ALPHA:
- return GL_ONE_MINUS_SRC_ALPHA;
- case State::BLENDFUNC_DESTINATION_ALPHA:
- return GL_DST_ALPHA;
- case State::BLENDFUNC_INVERSE_DESTINATION_ALPHA:
- return GL_ONE_MINUS_DST_ALPHA;
- case State::BLENDFUNC_DESTINATION_COLOR:
- return GL_DST_COLOR;
- case State::BLENDFUNC_INVERSE_DESTINATION_COLOR:
- return GL_ONE_MINUS_DST_COLOR;
- case State::BLENDFUNC_SOURCE_ALPHA_SATUTRATE:
- return GL_SRC_ALPHA_SATURATE;
- default:
- break;
- }
- return GL_ONE;
-}
-
-GLenum ConvertBlendEquation(State::BlendingEquation blend_equation) {
- switch (blend_equation) {
- case State::BLEND_ADD:
- return GL_FUNC_ADD;
- case State::BLEND_SUBTRACT:
- return GL_FUNC_SUBTRACT;
- case State::BLEND_REVERSE_SUBTRACT:
- return GL_FUNC_REVERSE_SUBTRACT;
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- case State::BLEND_MIN:
- return GL_MIN;
- case State::BLEND_MAX:
- return GL_MAX;
-#else
- case State::BLEND_MIN:
- case State::BLEND_MAX:
- NOTIMPLEMENTED() << "MIN/MAX blend equation";
- break;
-#endif
- default:
- break;
- }
- return GL_FUNC_ADD;
-}
-
-GLenum ConvertStencilOp(State::StencilOperation stencil_func) {
- switch (stencil_func) {
- case State::STENCIL_KEEP:
- return GL_KEEP;
- case State::STENCIL_ZERO:
- return GL_ZERO;
- case State::STENCIL_REPLACE:
- return GL_REPLACE;
- case State::STENCIL_INCREMENT_SATURATE:
- return GL_INCR;
- case State::STENCIL_DECREMENT_SATURATE:
- return GL_DECR;
- case State::STENCIL_INVERT:
- return GL_INVERT;
- case State::STENCIL_INCREMENT:
- return GL_INCR_WRAP;
- case State::STENCIL_DECREMENT:
- return GL_DECR_WRAP;
- default:
- break;
- }
- return GL_KEEP;
-}
-
-#ifndef DISABLE_FBO
-// Helper routine that will bind the surfaces stored in the RenderSurface and
-// RenderDepthStencilSurface arguments to the current OpenGLES2 context.
-// Returns true upon success.
-// Note: This routine assumes that a frambuffer object is presently bound
-// to the context.
-bool InstallFramebufferObjects(const RenderSurface* surface,
- const RenderDepthStencilSurface* surface_depth) {
-#ifndef NDEBUG
- GLint bound_framebuffer;
- ::glGetIntegerv(GL_FRAMEBUFFER_BINDING, &bound_framebuffer);
- DCHECK(bound_framebuffer != 0);
-#endif
-
- // Reset the bound attachments to the current framebuffer object.
- ::glFramebufferRenderbufferEXT(GL_FRAMEBUFFER,
- GL_COLOR_ATTACHMENT0,
- GL_RENDERBUFFER,
- 0);
-
- ::glFramebufferRenderbufferEXT(GL_FRAMEBUFFER,
- GL_DEPTH_ATTACHMENT,
- GL_RENDERBUFFER,
- 0);
-
- ::glFramebufferRenderbufferEXT(GL_FRAMEBUFFER,
- GL_STENCIL_ATTACHMENT,
- GL_RENDERBUFFER,
- 0);
-
- if (surface) {
- const RenderSurfaceGLES2 *gl_surface =
- down_cast<const RenderSurfaceGLES2*>(surface);
- Texture *texture = gl_surface->texture();
- GLuint handle = static_cast<GLuint>(reinterpret_cast<intptr_t>(
- texture->GetTextureHandle()));
- if (texture->IsA(Texture2D::GetApparentClass())) {
- ::glFramebufferTexture2DEXT(
- GL_FRAMEBUFFER,
- GL_COLOR_ATTACHMENT0,
- GL_TEXTURE_2D,
- handle,
- gl_surface->mip_level());
- } else if (texture->IsA(TextureCUBE::GetApparentClass())) {
- ::glFramebufferTexture2DEXT(
- GL_FRAMEBUFFER,
- GL_COLOR_ATTACHMENT0,
- gl_surface->cube_face(),
- handle,
- gl_surface->mip_level());
- }
- }
-
- if (surface_depth) {
- // Bind both the depth and stencil attachments.
- const RenderDepthStencilSurfaceGLES2* gl_surface =
- down_cast<const RenderDepthStencilSurfaceGLES2*>(surface_depth);
- ::glFramebufferRenderbufferEXT(GL_FRAMEBUFFER,
- GL_DEPTH_ATTACHMENT,
- GL_RENDERBUFFER,
- gl_surface->depth_buffer());
- ::glFramebufferRenderbufferEXT(GL_FRAMEBUFFER,
- GL_STENCIL_ATTACHMENT,
- GL_RENDERBUFFER,
- gl_surface->stencil_buffer());
- }
- GLenum framebuffer_status = ::glCheckFramebufferStatusEXT(GL_FRAMEBUFFER);
- if (GL_FRAMEBUFFER_COMPLETE != framebuffer_status) {
- return false;
- }
-
- CHECK_GL_ERROR();
- return true;
-}
-#endif
-
-// Helper routine that returns a pointer to the non-NULL entry in the renderer's
-// stack of bound surfaces.
-const RenderSurfaceBase* GetValidRenderSurface(
- const std::pair<RenderSurface*, RenderDepthStencilSurface*> &stack_entry) {
- if (stack_entry.first) {
- return stack_entry.first;
- } else {
- return stack_entry.second;
- }
-}
-
-} // unnamed namespace
-
-// This class wraps StateHandler to make it typesafe.
-template <typename T>
-class TypedStateHandler : public RendererGLES2::StateHandler {
- public:
- // Override this function to set a specific state.
- // Parameters:
- // renderer: The platform specific renderer.
- // param: A concrete param with state data.
- virtual void SetStateFromTypedParam(
- RendererGLES2* renderer, T* param) const = 0;
-
- // Gets Class of State's Parameter
- virtual const ObjectBase::Class* GetClass() const {
- return T::GetApparentClass();
- }
-
- private:
- // Calls SetStateFromTypedParam if the Param type is the correct type.
- // Parameters:
- // renderer: The platform specific renderer.
- // param: A param with state data.
- virtual void SetState(Renderer* renderer, Param* param) const {
- RendererGLES2 *renderer_gl = down_cast<RendererGLES2 *>(renderer);
- // This is safe because State guarntees Params match by type.
- DCHECK(param->IsA(T::GetApparentClass()));
- SetStateFromTypedParam(renderer_gl, down_cast<T*>(param));
- }
-};
-
-template <class T>
-class NoOpHandler : public TypedStateHandler<T> {
- public:
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- T* param) const {
- }
-};
-
-
-// A template the generates a handler for enable/disable states.
-// Parameters:
-// state_constant: GLenum of state we want to enable/disable
-template <GLenum state_constant>
-class StateEnableHandler : public TypedStateHandler<ParamBoolean> {
- public:
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamBoolean* param) const {
- if (param->value()) {
- ::glEnable(state_constant);
- } else {
- ::glDisable(state_constant);
- }
- }
-};
-
-class BoolHandler : public TypedStateHandler<ParamBoolean> {
- public:
- explicit BoolHandler(bool* var, bool* changed_var)
- : var_(*var),
- changed_var_(*changed_var) {
- }
- virtual void SetStateFromTypedParam(RendererGLES2 *renderer,
- ParamBoolean *param) const {
- var_ = param->value();
- }
- private:
- bool& var_;
- bool& changed_var_;
-};
-
-class ZWriteEnableHandler : public TypedStateHandler<ParamBoolean> {
- public:
- virtual void SetStateFromTypedParam(RendererGLES2 *renderer,
- ParamBoolean *param) const {
- ::glDepthMask(param->value());
- }
-};
-
-class AlphaReferenceHandler : public TypedStateHandler<ParamFloat> {
- public:
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamFloat* param) const {
- float refFloat = param->value();
-
- // cap the float to the required range
- if (refFloat < 0.0f) {
- refFloat = 0.0f;
- } else if (refFloat > 1.0f) {
- refFloat = 1.0f;
- }
-
- renderer->alpha_function_ref_changed_ = true;
- renderer->alpha_ref_ = refFloat;
- }
-};
-
-class CullModeHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamInteger* param) const {
- State::Cull cull = static_cast<State::Cull>(param->value());
- switch (cull) {
- case State::CULL_CW:
- ::glEnable(GL_CULL_FACE);
- ::glCullFace(GL_BACK);
- break;
- case State::CULL_CCW:
- ::glEnable(GL_CULL_FACE);
- ::glCullFace(GL_FRONT);
- break;
- default:
- ::glDisable(GL_CULL_FACE);
- break;
- }
- }
-};
-
-class PolygonOffset1Handler : public TypedStateHandler<ParamFloat> {
- public:
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamFloat* param) const {
- renderer->polygon_offset_factor_ = param->value();
- renderer->polygon_offset_changed_ = true;
- }
-};
-
-class PolygonOffset2Handler : public TypedStateHandler<ParamFloat> {
- public:
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamFloat* param) const {
- renderer->polygon_offset_bias_ = param->value();
- renderer->polygon_offset_changed_ = true;
- }
-};
-
-class FillModeHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamInteger* param) const {
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- ::glPolygonMode(GL_FRONT_AND_BACK,
- ConvertFillMode(static_cast<State::Fill>(param->value())));
-#else
- NOTIMPLEMENTED() << "Fill mode";
-#endif
- }
-};
-
-class ZFunctionHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamInteger* param) const {
- ::glDepthFunc(
- ConvertCmpFunc(static_cast<State::Comparison>(param->value())));
- }
-};
-
-class BlendEquationHandler : public TypedStateHandler<ParamInteger> {
- public:
- explicit BlendEquationHandler(GLenum* var)
- : var_(*var) {
- }
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamInteger* param) const {
- renderer->alpha_blend_settings_changed_ = true;
- var_ = ConvertBlendEquation(
- static_cast<State::BlendingEquation>(param->value()));
- }
- private:
- GLenum& var_;
-};
-
-class BlendFunctionHandler : public TypedStateHandler<ParamInteger> {
- public:
- explicit BlendFunctionHandler(GLenum* var)
- : var_(*var) {
- }
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamInteger* param) const {
- renderer->alpha_blend_settings_changed_ = true;
- var_ = ConvertBlendFunc(
- static_cast<State::BlendingFunction>(param->value()));
- }
- private:
- GLenum& var_;
-};
-
-
-class StencilOperationHandler : public TypedStateHandler<ParamInteger> {
- public:
- StencilOperationHandler(int face, int condition)
- : face_(face) ,
- condition_(condition) {
- }
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamInteger* param) const {
- renderer->stencil_settings_changed_ = true;
- renderer->stencil_settings_[face_].op_[condition_] = ConvertStencilOp(
- static_cast<State::StencilOperation>(param->value()));
- }
- private:
- int face_;
- int condition_;
-};
-
-class ComparisonFunctionHandler : public TypedStateHandler<ParamInteger> {
- public:
- ComparisonFunctionHandler(GLenum* var, bool* changed_var)
- : var_(*var),
- changed_var_(*changed_var) {
- }
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamInteger* param) const {
- changed_var_ = true;
- var_ = ConvertCmpFunc(static_cast<State::Comparison>(param->value()));
- }
- private:
- GLenum& var_;
- bool& changed_var_;
-};
-
-class StencilRefHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamInteger* param) const {
- renderer->stencil_settings_changed_ = true;
- renderer->stencil_ref_ = param->value();
- }
-};
-
-class StencilMaskHandler : public TypedStateHandler<ParamInteger> {
- public:
- explicit StencilMaskHandler(int mask_index)
- : mask_index_(mask_index) {
- }
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamInteger* param) const {
- renderer->stencil_settings_changed_ = true;
- renderer->stencil_mask_[mask_index_] = param->value();
- }
- private:
- int mask_index_;
-};
-
-class ColorWriteEnableHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamInteger* param) const {
- int mask = param->value();
- ::glColorMask((mask & 0x1) != 0,
- (mask & 0x2) != 0,
- (mask & 0x4) != 0,
- (mask & 0x8) != 0);
- renderer->SetWriteMask(mask);
- }
-};
-
-class PointSpriteEnableHandler : public TypedStateHandler<ParamBoolean> {
- public:
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamBoolean* param) const {
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- if (param->value()) {
- ::glEnable(GL_POINT_SPRITE);
- // TODO(o3d): It's not clear from D3D docs that point sprites affect
- // TEXCOORD0, but that's my guess. Check that.
- ::glActiveTextureARB(GL_TEXTURE0);
- ::glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
- } else {
- ::glActiveTextureARB(GL_TEXTURE0);
- ::glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_FALSE);
- ::glDisable(GL_POINT_SPRITE);
- }
-#else
- NOTIMPLEMENTED() << "Point Sprites";
-#endif
- }
-};
-
-class PointSizeHandler : public TypedStateHandler<ParamFloat> {
- public:
- virtual void SetStateFromTypedParam(RendererGLES2* renderer,
- ParamFloat* param) const {
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- ::glPointSize(param->value());
-#else
- NOTIMPLEMENTED() << "Point Size";
-#endif
- }
-};
-
-RendererGLES2* RendererGLES2::CreateDefault(ServiceLocator* service_locator) {
- return new RendererGLES2(service_locator);
-}
-
-RendererGLES2::RendererGLES2(ServiceLocator* service_locator)
- : Renderer(service_locator),
- semantic_manager_(service_locator),
-#ifdef OS_WIN
- gl_context_(NULL),
-#endif
- fullscreen_(0),
-#ifdef OS_LINUX
- display_(NULL),
- window_(0),
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- context_(0),
-#elif defined(GLES2_BACKEND_NATIVE_GLES2)
- egl_display_(NULL),
- egl_surface_(NULL),
- egl_context_(NULL),
-#endif // GLES_BACKEND_xxx
-#endif // OS_LINUX
-#ifdef OS_MACOSX
- mac_agl_context_(0),
- mac_cgl_context_(0),
-#endif
- render_surface_framebuffer_(0),
- alpha_function_ref_changed_(true),
- alpha_function_(GL_ALWAYS),
- alpha_ref_(0.f),
- alpha_blend_settings_changed_(true),
- separate_alpha_blend_enable_(false),
- stencil_settings_changed_(true),
- separate_stencil_settings_enable_(false),
- stencil_ref_(0),
- polygon_offset_changed_(true),
- polygon_offset_factor_(0.f),
- polygon_offset_bias_(0.f) {
- DLOG(INFO) << "RendererGLES2 Construct";
-
- // Setup default state values.
- for (int ii = 0; ii < 2; ++ii) {
- stencil_settings_[ii].func_ = GL_ALWAYS;
- stencil_settings_[ii].op_[StencilStates::FAIL_OP] = GL_KEEP;
- stencil_settings_[ii].op_[StencilStates::ZFAIL_OP] = GL_KEEP;
- stencil_settings_[ii].op_[StencilStates::PASS_OP] = GL_KEEP;
- stencil_mask_[ii] = -1;
- blend_function_[ii][FRONT] = GL_ONE;
- blend_function_[ii][BACK] = GL_ZERO;
- blend_equation_[ii] = GL_FUNC_ADD;
- }
-
- // Setup state handlers
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- AddStateHandler(State::kAlphaTestEnableParamName,
- new StateEnableHandler<GL_ALPHA_TEST>);
-#else
- // TODO(piman): Alpha test isn't supported in GLES2, because it can be done
- // in a shader. Solution here would be to add instructions to the shader...
- AddStateHandler(State::kAlphaTestEnableParamName,
- new NoOpHandler<ParamBoolean>);
-#endif
- AddStateHandler(State::kAlphaReferenceParamName,
- new AlphaReferenceHandler);
- AddStateHandler(State::kAlphaComparisonFunctionParamName,
- new ComparisonFunctionHandler(&alpha_function_,
- &alpha_function_ref_changed_));
- AddStateHandler(State::kCullModeParamName,
- new CullModeHandler);
- AddStateHandler(State::kDitherEnableParamName,
- new StateEnableHandler<GL_DITHER>);
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- AddStateHandler(State::kLineSmoothEnableParamName,
- new StateEnableHandler<GL_LINE_SMOOTH>);
-#else
- AddStateHandler(State::kLineSmoothEnableParamName,
- new NoOpHandler<ParamBoolean>);
-#endif
- AddStateHandler(State::kPointSpriteEnableParamName,
- new PointSpriteEnableHandler);
- AddStateHandler(State::kPointSizeParamName,
- new PointSizeHandler);
- AddStateHandler(State::kPolygonOffset1ParamName,
- new PolygonOffset1Handler);
- AddStateHandler(State::kPolygonOffset2ParamName,
- new PolygonOffset2Handler);
- AddStateHandler(State::kFillModeParamName,
- new FillModeHandler);
- AddStateHandler(State::kZEnableParamName,
- new StateEnableHandler<GL_DEPTH_TEST>);
- AddStateHandler(State::kZWriteEnableParamName,
- new ZWriteEnableHandler);
- AddStateHandler(State::kZComparisonFunctionParamName,
- new ZFunctionHandler);
- AddStateHandler(State::kAlphaBlendEnableParamName,
- new StateEnableHandler<GL_BLEND>);
- AddStateHandler(State::kSourceBlendFunctionParamName,
- new BlendFunctionHandler(&blend_function_[SRC][RGB]));
- AddStateHandler(State::kDestinationBlendFunctionParamName,
- new BlendFunctionHandler(&blend_function_[DST][RGB]));
- AddStateHandler(State::kStencilEnableParamName,
- new StateEnableHandler<GL_STENCIL_TEST>);
- AddStateHandler(State::kStencilFailOperationParamName,
- new StencilOperationHandler(FRONT, StencilStates::FAIL_OP));
- AddStateHandler(State::kStencilZFailOperationParamName,
- new StencilOperationHandler(FRONT, StencilStates::ZFAIL_OP));
- AddStateHandler(State::kStencilPassOperationParamName,
- new StencilOperationHandler(FRONT, StencilStates::PASS_OP));
- AddStateHandler(State::kStencilComparisonFunctionParamName,
- new ComparisonFunctionHandler(
- &stencil_settings_[FRONT].func_,
- &stencil_settings_changed_));
- AddStateHandler(State::kStencilReferenceParamName,
- new StencilRefHandler);
- AddStateHandler(State::kStencilMaskParamName,
- new StencilMaskHandler(READ_MASK));
- AddStateHandler(State::kStencilWriteMaskParamName,
- new StencilMaskHandler(WRITE_MASK));
- AddStateHandler(State::kColorWriteEnableParamName,
- new ColorWriteEnableHandler);
- AddStateHandler(State::kBlendEquationParamName,
- new BlendEquationHandler(&blend_equation_[RGB]));
- AddStateHandler(State::kTwoSidedStencilEnableParamName,
- new BoolHandler(&separate_stencil_settings_enable_,
- &stencil_settings_changed_));
- AddStateHandler(State::kCCWStencilFailOperationParamName,
- new StencilOperationHandler(BACK, StencilStates::FAIL_OP));
- AddStateHandler(State::kCCWStencilZFailOperationParamName,
- new StencilOperationHandler(BACK, StencilStates::ZFAIL_OP));
- AddStateHandler(State::kCCWStencilPassOperationParamName,
- new StencilOperationHandler(BACK, StencilStates::PASS_OP));
- AddStateHandler(State::kCCWStencilComparisonFunctionParamName,
- new ComparisonFunctionHandler(
- &stencil_settings_[BACK].func_,
- &stencil_settings_changed_));
- AddStateHandler(State::kSeparateAlphaBlendEnableParamName,
- new BoolHandler(&separate_alpha_blend_enable_,
- &alpha_blend_settings_changed_));
- AddStateHandler(State::kSourceBlendAlphaFunctionParamName,
- new BlendFunctionHandler(&blend_function_[SRC][ALPHA]));
- AddStateHandler(State::kDestinationBlendAlphaFunctionParamName,
- new BlendFunctionHandler(&blend_function_[DST][ALPHA]));
- AddStateHandler(State::kBlendAlphaEquationParamName,
- new BlendEquationHandler(&blend_equation_[ALPHA]));
-}
-
-RendererGLES2::~RendererGLES2() {
- Destroy();
-}
-
-// platform neutral initialization code
-//
-Renderer::InitStatus RendererGLES2::InitCommonGLES2() {
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- GLenum glew_error = glewInit();
- if (glew_error != GLEW_OK) {
- DLOG(ERROR) << "Unable to initialise GLEW : "
- << ::glewGetErrorString(glew_error);
- return INITIALIZATION_ERROR;
- }
-
- // Check to see that we can use the OpenGLES2 vertex attribute APIs
- // TODO(o3d): We should return false if this check fails, but because some
- // Intel hardware does not support OpenGLES2 2.0, yet does support all of the
- // extensions we require, we only log an error. A future CL should change
- // this check to ensure that all of the extension strings we require are
- // present.
- if (!GLEW_VERSION_2_0) {
- DLOG(ERROR) << "GLES2 drivers do not have OpenGLES2 2.0 functionality.";
- }
-
- if (!GLEW_ARB_vertex_buffer_object) {
- // NOTE: Linux NVidia drivers claim to support OpenGLES2 2.0 when using
- // indirect rendering (e.g. remote X), but it is actually lying. The
- // ARB_vertex_buffer_object functions silently no-op (!) when using
- // indirect rendering, leading to crashes. Fortunately, in that case, the
- // driver claims to not support ARB_vertex_buffer_object, so fail in that
- // case.
- DLOG(ERROR) << "GLES2 drivers do not support vertex buffer objects.";
- return GPU_NOT_UP_TO_SPEC;
- }
-
-#ifndef DISABLE_FBO
- if (!GLEW_EXT_framebuffer_object) {
- DLOG(ERROR) << "GLES2 drivers do not support framebuffer objects.";
- return GPU_NOT_UP_TO_SPEC;
- }
-#endif
-
- SetSupportsNPOT(GLEW_ARB_texture_non_power_of_two != 0);
-
-#ifdef OS_MACOSX
- // The Radeon X1600 says it supports NPOT, but in most situations it doesn't.
- if (supports_npot() &&
- !strcmp("ATI Radeon X1600 OpenGLES2 Engine",
- reinterpret_cast<const char*>(::glGetString(GL_RENDERER))))
- SetSupportsNPOT(false);
-#endif
-
- // Check for necessary extensions
- if (!GLEW_VERSION_2_0 && !GLEW_EXT_stencil_two_side) {
- DLOG(ERROR) << "Two sided stencil extension missing.";
- }
- if (!GLEW_VERSION_1_4 && !GLEW_EXT_blend_func_separate) {
- DLOG(ERROR) << "Separate blend func extension missing.";
- }
- if (!GLEW_VERSION_2_0 && !GLEW_EXT_blend_equation_separate) {
- DLOG(ERROR) << "Separate blend function extension missing.";
- }
-#elif defined(GLES2_BACKEND_NATIVE_GLES2)
- // GLES specific initialization ?
-#endif // GLES2_BACKEND
- DLOG(INFO) << "OpenGLES2 Vendor: " << ::glGetString(GL_VENDOR);
- DLOG(INFO) << "OpenGLES2 Renderer: " << ::glGetString(GL_RENDERER);
- DLOG(INFO) << "OpenGLES2 Version: " << ::glGetString(GL_VERSION);
- DLOG(INFO) << "OpenGLES2 Extensions: " << ::glGetString(GL_EXTENSIONS);
- // get some limits for this profile.
- GLint max_vertex_attribs = 0;
- ::glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attribs);
- DLOG(INFO) << "Max Vertex Attribs = " << max_vertex_attribs;
- // Initialize global GLES2 settings.
- // Tell GLES2 that texture buffers can be single-byte aligned.
- ::glPixelStorei(GL_PACK_ALIGNMENT, 1);
- ::glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- ::glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
- ::glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
-#endif
- CHECK_GL_ERROR();
- // TODO(piman): by default, GLES2 has some minimal support for NPOT. Is it
- // enough for what we use ?
- SetSupportsNPOT(true);
-
- GLint viewport[4];
- ::glGetIntegerv(GL_VIEWPORT, &viewport[0]);
- SetClientSize(viewport[2], viewport[3]);
- CHECK_GL_ERROR();
-
-#ifndef DISABLE_FBO
- ::glGenFramebuffersEXT(1, &render_surface_framebuffer_);
- CHECK_GL_ERROR();
-#endif
-
- return SUCCESS;
-}
-
-// platform neutral destruction code
-void RendererGLES2::DestroyCommonGLES2() {
- MakeCurrentLazy();
-#ifndef DISABLE_FBO
- if (render_surface_framebuffer_) {
- ::glDeleteFramebuffersEXT(1, &render_surface_framebuffer_);
- }
-#endif
-}
-
-#ifdef OS_WIN
-
-namespace {
-
-PIXELFORMATDESCRIPTOR kPixelFormatDescriptor = {
- sizeof(kPixelFormatDescriptor), // Size of structure.
- 1, // Default version.
- PFD_DRAW_TO_WINDOW | // Window drawing support.
- PFD_SUPPORT_OPENGL | // OpenGL support.
- PFD_DOUBLEBUFFER, // Double buffering support (not stereo).
- PFD_TYPE_RGBA, // RGBA color mode (not indexed).
- 24, // 24 bit color mode.
- 0, 0, 0, 0, 0, 0, // Don't set RGB bits & shifts.
- 8, 0, // 8 bit alpha
- 0, // No accumulation buffer.
- 0, 0, 0, 0, // Ignore accumulation bits.
- 24, // 24 bit z-buffer size.
- 8, // 8-bit stencil buffer.
- 0, // No aux buffer.
- PFD_MAIN_PLANE, // Main drawing plane (not overlay).
- 0, // Reserved.
- 0, 0, 0, // Layer masks ignored.
-};
-
-LRESULT CALLBACK IntermediateWindowProc(HWND window,
- UINT message,
- WPARAM w_param,
- LPARAM l_param) {
- return ::DefWindowProc(window, message, w_param, l_param);
-}
-
-// Helper routine that returns the highest quality pixel format supported on
-// the current platform. Returns true upon success.
-Renderer::InitStatus GetWindowsPixelFormat(HWND window,
- Features* features,
- int* pixel_format) {
- // We must initialize a GLES2 context before we can determine the
- // multi-sampling supported on the current hardware, so we create an
- // intermediate window and context here.
- HINSTANCE module_handle;
- if (!::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
- GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
- reinterpret_cast<wchar_t*>(IntermediateWindowProc),
- &module_handle)) {
- return Renderer::INITIALIZATION_ERROR;
- }
-
- WNDCLASS intermediate_class;
- intermediate_class.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
- intermediate_class.lpfnWndProc = IntermediateWindowProc;
- intermediate_class.cbClsExtra = 0;
- intermediate_class.cbWndExtra = 0;
- intermediate_class.hInstance = module_handle;
- intermediate_class.hIcon = LoadIcon(NULL, IDI_APPLICATION);
- intermediate_class.hCursor = LoadCursor(NULL, IDC_ARROW);
- intermediate_class.hbrBackground = NULL;
- intermediate_class.lpszMenuName = NULL;
- intermediate_class.lpszClassName = L"Intermediate GLES2 Window";
-
- ATOM class_registration = ::RegisterClass(&intermediate_class);
- if (!class_registration) {
- return Renderer::INITIALIZATION_ERROR;
- }
-
- HWND intermediate_window = ::CreateWindow(
- reinterpret_cast<wchar_t*>(class_registration),
- L"",
- WS_OVERLAPPEDWINDOW,
- 0, 0,
- CW_USEDEFAULT, CW_USEDEFAULT,
- NULL,
- NULL,
- NULL,
- NULL);
-
- if (!intermediate_window) {
- ::UnregisterClass(reinterpret_cast<wchar_t*>(class_registration),
- module_handle);
- return Renderer::INITIALIZATION_ERROR;
- }
-
- HDC intermediate_dc = ::GetDC(intermediate_window);
- int format_index = ::ChoosePixelFormat(intermediate_dc,
- &kPixelFormatDescriptor);
- if (format_index == 0) {
- DLOG(ERROR) << "Unable to get the pixel format for GLES2 context.";
- ::ReleaseDC(intermediate_window, intermediate_dc);
- ::DestroyWindow(intermediate_window);
- ::UnregisterClass(reinterpret_cast<wchar_t*>(class_registration),
- module_handle);
- return Renderer::INITIALIZATION_ERROR;
- }
- if (!::SetPixelFormat(intermediate_dc, format_index,
- &kPixelFormatDescriptor)) {
- DLOG(ERROR) << "Unable to set the pixel format for GLES2 context.";
- ::ReleaseDC(intermediate_window, intermediate_dc);
- ::DestroyWindow(intermediate_window);
- ::UnregisterClass(reinterpret_cast<wchar_t*>(class_registration),
- module_handle);
- return Renderer::INITIALIZATION_ERROR;
- }
-
- // Store the pixel format without multisampling.
- *pixel_format = format_index;
- HGLRC gl_context = ::wglCreateContext(intermediate_dc);
- if (::wglMakeCurrent(intermediate_dc, gl_context)) {
- // GLES2 context was successfully created and applied to the window's DC.
- // Startup GLEW, the GLES2 extensions wrangler.
- GLenum glew_error = ::glewInit();
- if (glew_error == GLEW_OK) {
- DLOG(INFO) << "Initialized GLEW " << ::glewGetString(GLEW_VERSION);
- } else {
- DLOG(ERROR) << "Unable to initialise GLEW : "
- << ::glewGetErrorString(glew_error);
- ::wglMakeCurrent(intermediate_dc, NULL);
- ::wglDeleteContext(gl_context);
- ::ReleaseDC(intermediate_window, intermediate_dc);
- ::DestroyWindow(intermediate_window);
- ::UnregisterClass(reinterpret_cast<wchar_t*>(class_registration),
- module_handle);
- return Renderer::INITIALIZATION_ERROR;
- }
-
- // If the multi-sample extensions are present, query the api to determine
- // the pixel format.
- if (!features->not_anti_aliased() &&
- WGLEW_ARB_pixel_format && WGLEW_ARB_multisample) {
- int pixel_attributes[] = {
- WGL_SAMPLES_ARB, 4,
- WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
- WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
- WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
- WGL_COLOR_BITS_ARB, 24,
- WGL_ALPHA_BITS_ARB, 8,
- WGL_DEPTH_BITS_ARB, 24,
- WGL_STENCIL_BITS_ARB, 8,
- WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
- WGL_SAMPLE_BUFFERS_ARB, GL_TRUE,
- 0, 0};
-
- float pixel_attributes_f[] = {0, 0};
- int msaa_pixel_format;
- unsigned int num_formats;
-
- // Query for the highest sampling rate supported, starting at 4x.
- static const int kSampleCount[] = {4, 2};
- static const int kNumSamples = 2;
- for (int sample = 0; sample < kNumSamples; ++sample) {
- pixel_attributes[1] = kSampleCount[sample];
- if (GL_TRUE == ::wglChoosePixelFormatARB(intermediate_dc,
- pixel_attributes,
- pixel_attributes_f,
- 1,
- &msaa_pixel_format,
- &num_formats)) {
- *pixel_format = msaa_pixel_format;
- break;
- }
- }
- }
- }
-
- ::wglMakeCurrent(intermediate_dc, NULL);
- ::wglDeleteContext(gl_context);
- ::ReleaseDC(intermediate_window, intermediate_dc);
- ::DestroyWindow(intermediate_window);
- ::UnregisterClass(reinterpret_cast<wchar_t*>(class_registration),
- module_handle);
- return Renderer::SUCCESS;
-}
-
-} // unnamed namespace
-
-Renderer::InitStatus RendererGLES2::InitPlatformSpecific(
- const DisplayWindow& display,
- bool off_screen) {
- const DisplayWindowWindows &display_platform =
- static_cast<const DisplayWindowWindows&>(display);
-
- DLOG(INFO) << "RendererGLES2 Init";
-
- // TODO(o3d): Add support for off-screen rendering using OpenGLES2.
- if (off_screen) {
- return INITIALIZATION_ERROR;
- }
-
- int pixel_format;
- InitStatus init_status;
-
- init_status = GetWindowsPixelFormat(display_platform.hwnd(),
- features(),
- &pixel_format);
- if (init_status != SUCCESS) {
- return init_status;
- }
-
- window_ = display_platform.hwnd();
- device_context_ = ::GetDC(window_);
- if (!::SetPixelFormat(device_context_, pixel_format,
- &kPixelFormatDescriptor)) {
- DLOG(ERROR) << "Unable to set the pixel format for GLES2 context.";
- return INITIALIZATION_ERROR;
- }
-
- gl_context_ = ::wglCreateContext(device_context_);
- if (MakeCurrent()) {
- // Ensure that glew has been initialized for the created rendering context.
- init_status = InitCommonGLES2();
- if (init_status != SUCCESS) {
- DLOG(ERROR) << "Failed to initialize GLES2 rendering context.";
- return init_status;
- }
- if (WGLEW_ARB_multisample) {
- ::glEnable(GL_MULTISAMPLE_ARB);
- }
- } else {
- DLOG(ERROR) << "Failed to create the GLES2 Context.";
- return INITIALIZATION_ERROR;
- }
- CHECK_GL_ERROR();
- return SUCCESS;
-}
-
-// Deletes the GLES2 device.
-void RendererGLES2::Destroy() {
- DLOG(INFO) << "Destroy RendererGLES2";
- DestroyCommonGLES2();
- if (device_context_) {
- CHECK_GL_ERROR();
- // Release the OpenGLES2 rendering context.
- ::wglMakeCurrent(device_context_, NULL);
- if (gl_context_) {
- ::wglDeleteContext(gl_context_);
- gl_context_ = NULL;
- }
- // release the hDC obtained through GetDC().
- ::ReleaseDC(window_, device_context_);
- device_context_ = NULL;
- window_ = NULL;
- }
- DLOG(INFO) << "Renderer destroyed.";
-}
-
-#endif // OS_WIN
-
-#ifdef OS_MACOSX
-
-Renderer::InitStatus RendererGLES2::InitPlatformSpecific(
- const DisplayWindow& display,
- bool /*off_screen*/) {
- const DisplayWindowMac &display_platform =
- static_cast<const DisplayWindowMac&>(display);
- // TODO(o3d): Add support for off screen rendering on the Mac.
- mac_agl_context_ = display_platform.agl_context();
- mac_cgl_context_ = display_platform.cgl_context();
-
- return InitCommonGLES2();
-}
-
-void RendererGLES2::Destroy() {
- DestroyCommonGLES2();
- // We only have to destroy agl contexts,
- // cgl contexts are not owned by us.
- if (mac_agl_context_) {
- ::aglDestroyContext(mac_agl_context_);
- mac_agl_context_ = NULL;
- }
-}
-
-#endif // OS_MACOSX
-
-#ifdef OS_LINUX
-Renderer::InitStatus RendererGLES2::InitPlatformSpecific(
- const DisplayWindow& display_window,
- bool off_screen) {
- const DisplayWindowLinux &display_platform =
- static_cast<const DisplayWindowLinux&>(display_window);
- Display *display = display_platform.display();
- Window window = display_platform.window();
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- XWindowAttributes attributes;
- ::XGetWindowAttributes(display, window, &attributes);
- XVisualInfo visual_info_template;
- visual_info_template.visualid = ::XVisualIDFromVisual(attributes.visual);
- int visual_info_count = 0;
- XVisualInfo *visual_info_list = ::XGetVisualInfo(display, VisualIDMask,
- &visual_info_template,
- &visual_info_count);
- DCHECK(visual_info_list);
- DCHECK_GT(visual_info_count, 0);
- context_ = 0;
- for (int i = 0; i < visual_info_count; ++i) {
- context_ = ::glXCreateContext(display, visual_info_list + i, 0,
- True);
- if (context_) break;
- }
- ::XFree(visual_info_list);
- if (!context_) {
- DLOG(ERROR) << "Couldn't create GLES2 context.";
- return INITIALIZATION_ERROR;
- }
- display_ = display;
- window_ = window;
- if (!MakeCurrent()) {
- ::glXDestroyContext(display, context_);
- context_ = 0;
- display_ = NULL;
- window_ = 0;
- DLOG(ERROR) << "Couldn't create GLES2 context.";
- return INITIALIZATION_ERROR;
- }
-
- InitStatus init_status = InitCommonGLES2();
- if (init_status != SUCCESS) {
- ::glXDestroyContext(display, context_);
- context_ = 0;
- display_ = NULL;
- window_ = 0;
- }
- return init_status;
-#elif defined(GLES2_BACKEND_NATIVE_GLES2)
- EGLDisplay egl_display = eglGetDisplay(display);
- if (eglGetError() != EGL_SUCCESS) {
- DLOG(ERROR) << "eglGetDisplay failed.";
- return INITIALIZATION_ERROR;
- }
-
- EGLint major;
- EGLint minor;
- // TODO(piman): is it ok to do this several times ?
- if (!eglInitialize(egl_display, &major, &minor)) {
- DLOG(ERROR) << "eglInitialize failed.";
- return INITIALIZATION_ERROR;
- }
- DLOG(INFO) << "EGL vendor:" << eglQueryString(egl_display, EGL_VENDOR);
- DLOG(INFO) << "EGL version:" << eglQueryString(egl_display, EGL_VERSION);
- DLOG(INFO) << "EGL extensions:"
- << eglQueryString(egl_display, EGL_EXTENSIONS);
- DLOG(INFO) << "EGL client apis:"
- << eglQueryString(egl_display, EGL_CLIENT_APIS);
-
- EGLint attribs[] = {
-#if 0
- // On some platforms X is started in 16-bit mode, and making a 32-bit
- // framebuffer causes tons of problems.
- // TODO(piman): fix this.
- EGL_RED_SIZE, 8,
- EGL_GREEN_SIZE, 8,
- EGL_BLUE_SIZE, 8,
- EGL_ALPHA_SIZE, 8,
- EGL_DEPTH_SIZE, 24,
- EGL_STENCIL_SIZE, 8,
-#else
- EGL_RED_SIZE, 5,
- EGL_GREEN_SIZE, 6,
- EGL_BLUE_SIZE, 5,
- EGL_DEPTH_SIZE, 16,
- EGL_STENCIL_SIZE, 0,
-#endif
- EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
- EGL_NONE
- };
-
- EGLint num_configs = -1;
- if (!eglGetConfigs(egl_display, NULL, 0, &num_configs)) {
- DLOG(ERROR) << "eglGetConfigs failed.";
- return INITIALIZATION_ERROR;
- }
-
- EGLConfig config;
- if (!eglChooseConfig(egl_display, attribs, &config, 1, &num_configs)) {
- DLOG(ERROR) << "eglChooseConfig failed.";
- return INITIALIZATION_ERROR;
- }
-
- EGLint red_size, green_size, blue_size, alpha_size, depth_size, stencil_size;
- eglGetConfigAttrib(egl_display, config, EGL_RED_SIZE, &red_size);
- eglGetConfigAttrib(egl_display, config, EGL_GREEN_SIZE, &green_size);
- eglGetConfigAttrib(egl_display, config, EGL_BLUE_SIZE, &blue_size);
- eglGetConfigAttrib(egl_display, config, EGL_ALPHA_SIZE, &alpha_size);
- eglGetConfigAttrib(egl_display, config, EGL_DEPTH_SIZE, &depth_size);
- eglGetConfigAttrib(egl_display, config, EGL_STENCIL_SIZE, &stencil_size);
- DLOG(INFO) << "R,G,B,A: " << red_size << "," << green_size
- << "," << blue_size << "," << alpha_size << " bits";
- DLOG(INFO) << "Depth: " << depth_size << " bits, Stencil:" << stencil_size
- << "bits";
-
- EGLSurface egl_surface = eglCreateWindowSurface(egl_display, config,
- window, NULL);
- if (!egl_surface) {
- DLOG(ERROR) << "eglCreateWindowSurface failed.";
- return INITIALIZATION_ERROR;
- }
-
- static const EGLint egl_context_attributes[] = {
- EGL_CONTEXT_CLIENT_VERSION, 2,
- EGL_NONE
- };
-
- EGLContext egl_context = eglCreateContext(egl_display, config, NULL,
- egl_context_attributes);
- if (!egl_context) {
- DLOG(ERROR) << "eglCreateContext failed.";
- eglDestroySurface(egl_display, egl_surface);
- return INITIALIZATION_ERROR;
- }
-
- display_ = display;
- window_ = window;
- egl_display_ = egl_display;
- egl_surface_ = egl_surface;
- egl_context_ = egl_context;
- if (!MakeCurrent()) {
- eglDestroyContext(egl_display, egl_context);
- eglDestroySurface(egl_display, egl_surface);
- display_ = NULL;
- window_ = 0;
- egl_display_ = NULL;
- egl_surface_ = NULL;
- egl_context_ = NULL;
- return INITIALIZATION_ERROR;
- }
-
- EGLint width;
- EGLint height;
- eglQuerySurface(egl_display, egl_surface, EGL_WIDTH, &width);
- eglQuerySurface(egl_display, egl_surface, EGL_HEIGHT, &height);
- glViewport(0, 0, width, height);
-
- InitStatus init_status = InitCommonGLES2();
- if (init_status != SUCCESS) {
- Destroy();
- return INITIALIZATION_ERROR;
- }
- return init_status;
-#else
-#error Not Implemented
-#endif
-}
-
-void RendererGLES2::Destroy() {
- DestroyCommonGLES2();
- if (display_) {
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- ::glXMakeCurrent(display_, 0, 0);
- if (context_) {
- ::glXDestroyContext(display_, context_);
- context_ = 0;
- }
-#elif defined(GLES2_BACKEND_NATIVE_GLES2)
- if (egl_display_) {
- eglMakeCurrent(egl_display_, EGL_NO_SURFACE, EGL_NO_SURFACE,
- EGL_NO_CONTEXT);
- if (egl_context_) {
- eglDestroyContext(egl_display_, egl_context_);
- egl_context_ = NULL;
- }
- if (egl_surface_) {
- eglDestroySurface(egl_display_, egl_surface_);
- egl_surface_ = NULL;
- }
- // TODO(piman): is it ok to do this if we have multiple clients ?
- eglTerminate(egl_display_);
- egl_display_ = NULL;
- }
-#else
-#error Not Implemented
-#endif
- display_ = NULL;
- window_ = 0;
- }
-}
-
-#endif
-
-bool RendererGLES2::MakeCurrent() {
-#ifdef OS_WIN
- if (!device_context_ || !gl_context_) return false;
- bool result = ::wglMakeCurrent(device_context_, gl_context_) != 0;
- return result;
-#endif
-#ifdef OS_MACOSX
- if (mac_cgl_context_ != NULL) {
- ::CGLSetCurrentContext(mac_cgl_context_);
- return true;
- } else if (mac_agl_context_ != NULL) {
- ::aglSetCurrentContext(mac_agl_context_);
- return true;
- } else {
- return false;
- }
-#endif
-#ifdef OS_LINUX
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- if (context_ != NULL) {
- bool result = ::glXMakeCurrent(display_, window_, context_) == True;
- return result;
- } else {
- return false;
- }
-#elif defined(GLES2_BACKEND_NATIVE_GLES2)
- if (egl_context_ != NULL) {
- EGLBoolean result = eglMakeCurrent(egl_display_, egl_surface_,
- egl_surface_, egl_context_);
- return result == EGL_TRUE;
- } else {
- return false;
- }
-#else
-#error Not Implemented
-#endif
-#endif
-}
-
-void RendererGLES2::PlatformSpecificClear(const Float4 &color,
- bool color_flag,
- float depth,
- bool depth_flag,
- int stencil,
- bool stencil_flag) {
- MakeCurrentLazy();
- ::glClearColor(color[0], color[1], color[2], color[3]);
- ::glClearDepth(depth);
- ::glClearStencil(stencil);
-
- ::glClear((color_flag ? GL_COLOR_BUFFER_BIT : 0) |
- (depth_flag ? GL_DEPTH_BUFFER_BIT : 0) |
- (stencil_flag ? GL_STENCIL_BUFFER_BIT : 0));
- CHECK_GL_ERROR();
-}
-
-// Updates the helper constant used for the D3D -> GLES2 remapping.
-// See effect_gles2.cc for details.
-void RendererGLES2::UpdateHelperConstant(float width, float height) {
- MakeCurrentLazy();
- // If render-targets are active, pass -1 to invert the Y axis. OpenGLES2 uses
- // a different viewport orientation than DX. Without the inversion, the
- // output of render-target rendering will be upside down.
- CHECK_GL_ERROR();
-
- if (RenderSurfaceActive()) {
- dx_clipping_[0] = 1.f / width;
- dx_clipping_[1] = -1.f / height;
- dx_clipping_[2] = 2.f;
- dx_clipping_[3] = -1.f;
- } else {
- dx_clipping_[0] = (1.0f + 2.0f * (-dest_x_offset())) / width;
- dx_clipping_[1] = (-1.0f + 2.0f * dest_y_offset()) / height;
- dx_clipping_[2] = 2.0f;
- dx_clipping_[3] = 1.0f;
- }
-}
-
-// Programs the helper constants into the hardware.
-void RendererGLES2::UpdateDxClippingUniform(GLint location) {
- // For some reason, if location is -1 an error is signalled, despite the spec
- // saying it is OK.
- if (location != -1)
- glUniform4fv(location, 1, dx_clipping_);
- CHECK_GL_ERROR();
-}
-
-#if defined(OS_MACOSX) && defined(GLES2_BACKEND_DESKTOP_GL)
-void RendererGLES2::set_mac_cgl_context(CGLContextObj obj) {
- bool changed = (mac_cgl_context_ != obj);
- mac_cgl_context_ = obj;
- if (changed) {
- // We need to reset all of the OpenGL state when the context changes.
- alpha_function_ref_changed_ = true;
- alpha_blend_settings_changed_ = true;
- stencil_settings_changed_ = true;
- polygon_offset_changed_ = true;
- // TODO(kbr): properly wire up full-screen support in this configuration.
- // must_reset_context_ = true;
- }
-}
-#endif
-
-void RendererGLES2::SetViewportInPixels(int left,
- int top,
- int width,
- int height,
- float min_z,
- float max_z) {
- MakeCurrentLazy();
- int vieport_top =
- RenderSurfaceActive() ? top : display_height() - top - height;
- ::glViewport(left, vieport_top, width, height);
- UpdateHelperConstant(static_cast<float>(width), static_cast<float>(height));
-
- // If it's the full client area turn off scissor test for speed.
- if (left == 0 &&
- top == 0 &&
- width == display_width() &&
- height == display_height()) {
- ::glDisable(GL_SCISSOR_TEST);
- } else {
- ::glScissor(left, vieport_top, width, height);
- ::glEnable(GL_SCISSOR_TEST);
- }
- ::glDepthRange(min_z, max_z);
-}
-
-// Resizes the viewport.
-void RendererGLES2::Resize(int width, int height) {
- MakeCurrentLazy();
- SetClientSize(width, height);
- CHECK_GL_ERROR();
-}
-
-bool RendererGLES2::GoFullscreen(const DisplayWindow& display,
- int mode_id) {
-#ifdef OS_LINUX
- // This actually just switches the GLX context to the new window. The real
- // work is in main_linux.cc.
- const DisplayWindowLinux &display_platform =
- static_cast<const DisplayWindowLinux&>(display);
- display_ = display_platform.display();
- window_ = display_platform.window();
- if (!MakeCurrent()) {
- return false;
- }
-#endif
- fullscreen_ = true;
- return true;
-}
-
-bool RendererGLES2::CancelFullscreen(const DisplayWindow& display,
- int width, int height) {
-#ifdef OS_LINUX
- // This actually just switches the GLX context to the old window. The real
- // work is in main_linux.cc.
- const DisplayWindowLinux &display_platform =
- static_cast<const DisplayWindowLinux&>(display);
- display_ = display_platform.display();
- window_ = display_platform.window();
- if (!MakeCurrent()) {
- return false;
- }
-#endif
- fullscreen_ = false;
- return true;
-}
-
-void RendererGLES2::GetDisplayModes(std::vector<DisplayMode> *modes) {
-#ifdef OS_MACOSX
- // Mac is supposed to call a different function in plugin_mac.mm instead.
- DLOG(FATAL) << "Not supposed to be called";
-#endif
- // On all other platforms this is unimplemented. Linux only supports
- // DISPLAY_MODE_DEFAULT for now.
- modes->clear();
-}
-
-bool RendererGLES2::GetDisplayMode(int id, DisplayMode *mode) {
-#ifdef OS_MACOSX
- // Mac is supposed to call a different function in plugin_mac.mm instead.
- DLOG(FATAL) << "Not supposed to be called";
- return false;
-#elif defined(OS_LINUX)
- if (id == DISPLAY_MODE_DEFAULT) {
- // Don't need to know any of this on Linux.
- mode->Set(0, 0, 0, id);
- return true;
- } else {
- // There are no other valid ids until we implement GetDisplayModes() and
- // mode switching.
- return false;
- }
-#else
- return false;
-#endif
-}
-
-bool RendererGLES2::PlatformSpecificStartRendering() {
- DLOG_FIRST_N(INFO, 10) << "RendererGLES2 StartRendering";
- MakeCurrentLazy();
-
- // Currently always returns true.
- // Should be modified if current behavior changes.
- CHECK_GL_ERROR();
- return true;
-}
-
-// Clears the color, depth and stncil buffers and prepares GLES2 for rendering
-// the frame.
-// Returns true on success.
-bool RendererGLES2::PlatformSpecificBeginDraw() {
- DLOG_FIRST_N(INFO, 10) << "RendererGLES2 BeginDraw";
-
- MakeCurrentLazy();
-
- // Currently always returns true.
- // Should be modified if current behavior changes.
- CHECK_GL_ERROR();
- return true;
-}
-
-// Assign the surface arguments to the renderer, and update the stack
-// of pushed surfaces.
-void RendererGLES2::SetRenderSurfacesPlatformSpecific(
- const RenderSurface* surface,
- const RenderDepthStencilSurface* surface_depth) {
- // TODO(o3d): This routine re-uses a single global framebuffer object for
- // all RenderSurface rendering. Because of the validation checks performed
- // at attachment-change time, it may be more performant to create a pool
- // of framebuffer objects with different attachment characterists and
- // switch between them here.
- MakeCurrentLazy();
-#ifndef DISABLE_FBO
- ::glBindFramebufferEXT(GL_FRAMEBUFFER, render_surface_framebuffer_);
- if (!InstallFramebufferObjects(surface, surface_depth)) {
- O3D_ERROR(service_locator())
- << "Failed to bind OpenGLES2 render target objects:"
- << surface->name() <<", "<< surface_depth->name();
- }
-#endif
- // RenderSurface rendering is performed with an inverted Y, so the front
- // face winding must be changed to clock-wise. See comments for
- // UpdateHelperConstant.
- glFrontFace(GL_CW);
-}
-
-void RendererGLES2::SetBackBufferPlatformSpecific() {
- MakeCurrentLazy();
-#ifndef DISABLE_FBO
- // Bind the default context, and restore the default front-face winding.
- ::glBindFramebufferEXT(GL_FRAMEBUFFER, 0);
-#endif
- glFrontFace(GL_CCW);
-}
-
-// Executes a post rendering step
-void RendererGLES2::PlatformSpecificEndDraw() {
- DLOG_FIRST_N(INFO, 10) << "RendererGLES2 EndDraw";
- DCHECK(IsCurrent());
-}
-
-// Swaps the buffers.
-void RendererGLES2::PlatformSpecificFinishRendering() {
- DLOG_FIRST_N(INFO, 10) << "RendererGLES2 FinishRendering";
- DCHECK(IsCurrent());
- ::glFlush();
- CHECK_GL_ERROR();
-}
-
-void RendererGLES2::PlatformSpecificPresent() {
- DLOG_FIRST_N(INFO, 10) << "RendererGLES2 Present";
- DCHECK(IsCurrent());
-#ifdef OS_WIN
- ::SwapBuffers(device_context_);
-#endif
-#ifdef OS_MACOSX
-#ifdef USE_AGL_DOUBLE_BUFFER
- if (mac_agl_context_) {
- ::aglSwapBuffers(mac_agl_context_);
- }
-#endif
-#endif
-#ifdef OS_LINUX
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- ::glXSwapBuffers(display_, window_);
-#elif defined(GLES2_BACKEND_NATIVE_GLES2)
- eglSwapBuffers(egl_display_, egl_surface_);
-#else
-#error Not Implemented
-#endif // GLES2_BACKEND_xxx
-#endif
-}
-
-StreamBank::Ref RendererGLES2::CreateStreamBank() {
- return StreamBank::Ref(new StreamBankGLES2(service_locator()));
-}
-
-Primitive::Ref RendererGLES2::CreatePrimitive() {
- return Primitive::Ref(new PrimitiveGLES2(service_locator()));
-}
-
-DrawElement::Ref RendererGLES2::CreateDrawElement() {
- return DrawElement::Ref(new DrawElementGLES2(service_locator()));
-}
-
-void RendererGLES2::SetStencilStates(GLenum face,
- const StencilStates& stencil_state) {
- DCHECK(IsCurrent());
- if (face == GL_FRONT_AND_BACK) {
- ::glStencilFunc(stencil_state.func_,
- stencil_ref_,
- stencil_mask_[READ_MASK]);
- ::glStencilOp(stencil_state.op_[StencilStates::FAIL_OP],
- stencil_state.op_[StencilStates::ZFAIL_OP],
- stencil_state.op_[StencilStates::PASS_OP]);
- ::glStencilMask(stencil_mask_[WRITE_MASK]);
- } else if (GLEW_VERSION_2_0) {
- ::glStencilFuncSeparate(face,
- stencil_state.func_,
- stencil_ref_,
- stencil_mask_[READ_MASK]);
- ::glStencilOpSeparate(face,
- stencil_state.op_[StencilStates::FAIL_OP],
- stencil_state.op_[StencilStates::ZFAIL_OP],
- stencil_state.op_[StencilStates::PASS_OP]);
- ::glStencilMaskSeparate(face,
- stencil_mask_[WRITE_MASK]);
- }
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- else if (GLEW_EXT_stencil_two_side) {
- ::glEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);
- ::glActiveStencilFaceEXT(face);
- ::glStencilFunc(stencil_state.func_,
- stencil_ref_,
- stencil_mask_[READ_MASK]);
- ::glStencilOp(stencil_state.op_[StencilStates::FAIL_OP],
- stencil_state.op_[StencilStates::ZFAIL_OP],
- stencil_state.op_[StencilStates::PASS_OP]);
- ::glStencilMask(stencil_mask_[WRITE_MASK]);
- ::glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
- }
-#endif
- CHECK_GL_ERROR();
-}
-
-void RendererGLES2::ApplyDirtyStates() {
- MakeCurrentLazy();
- DCHECK(IsCurrent());
- // Set blend settings.
- if (alpha_blend_settings_changed_) {
- if (separate_alpha_blend_enable_) {
- if (GLEW_VERSION_1_4) {
- ::glBlendFuncSeparate(blend_function_[SRC][RGB],
- blend_function_[DST][RGB],
- blend_function_[SRC][ALPHA],
- blend_function_[DST][ALPHA]);
- }
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- else if (GLEW_EXT_blend_func_separate) {
- ::glBlendFuncSeparateEXT(blend_function_[SRC][RGB],
- blend_function_[DST][RGB],
- blend_function_[SRC][ALPHA],
- blend_function_[DST][ALPHA]);
- }
-#endif
- if (GLEW_VERSION_2_0) {
- ::glBlendEquationSeparate(blend_equation_[RGB],
- blend_equation_[ALPHA]);
- }
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- else if (GLEW_EXT_blend_equation_separate) {
- ::glBlendEquationSeparateEXT(blend_equation_[RGB],
- blend_equation_[ALPHA]);
- }
-#endif
- } else {
- ::glBlendFunc(blend_function_[SRC][RGB],
- blend_function_[DST][RGB]);
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- if (::glBlendEquation != NULL)
-#endif
- ::glBlendEquation(blend_equation_[RGB]);
- }
- alpha_blend_settings_changed_ = false;
- }
-
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- // Set alpha settings.
- if (alpha_function_ref_changed_) {
- ::glAlphaFunc(alpha_function_, alpha_ref_);
- alpha_function_ref_changed_ = false;
- }
-#endif
-
- // Set stencil settings.
- if (stencil_settings_changed_) {
- if (separate_stencil_settings_enable_) {
- SetStencilStates(GL_FRONT, stencil_settings_[FRONT]);
- SetStencilStates(GL_BACK, stencil_settings_[BACK]);
- } else {
- SetStencilStates(GL_FRONT_AND_BACK, stencil_settings_[FRONT]);
- }
- stencil_settings_changed_ = false;
- }
-
- if (polygon_offset_changed_) {
- bool enable = (polygon_offset_factor_ != 0.f) ||
- (polygon_offset_bias_ != 0.f);
- if (enable) {
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- ::glEnable(GL_POLYGON_OFFSET_POINT);
- ::glEnable(GL_POLYGON_OFFSET_LINE);
-#endif
- ::glEnable(GL_POLYGON_OFFSET_FILL);
- ::glPolygonOffset(polygon_offset_factor_, polygon_offset_bias_);
- } else {
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- ::glDisable(GL_POLYGON_OFFSET_POINT);
- ::glDisable(GL_POLYGON_OFFSET_LINE);
-#endif
- ::glDisable(GL_POLYGON_OFFSET_FILL);
- }
- polygon_offset_changed_ = false;
- }
- CHECK_GL_ERROR();
-}
-
-VertexBuffer::Ref RendererGLES2::CreateVertexBuffer() {
- DLOG(INFO) << "RendererGLES2 CreateVertexBuffer";
- MakeCurrentLazy();
- return VertexBuffer::Ref(new VertexBufferGLES2(service_locator()));
-}
-
-IndexBuffer::Ref RendererGLES2::CreateIndexBuffer() {
- DLOG(INFO) << "RendererGLES2 CreateIndexBuffer";
- MakeCurrentLazy();
- return IndexBuffer::Ref(new IndexBufferGLES2(service_locator()));
-}
-
-Effect::Ref RendererGLES2::CreateEffect() {
- DLOG(INFO) << "RendererGLES2 CreateEffect";
- MakeCurrentLazy();
- return Effect::Ref(new EffectGLES2(service_locator()));
-}
-
-Sampler::Ref RendererGLES2::CreateSampler() {
- return Sampler::Ref(new SamplerGLES2(service_locator()));
-}
-
-ParamCache* RendererGLES2::CreatePlatformSpecificParamCache() {
- return new ParamCacheGLES2(semantic_manager_.Get(), this);
-}
-
-
-Texture2D::Ref RendererGLES2::CreatePlatformSpecificTexture2D(
- int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- DLOG(INFO) << "RendererGLES2 CreateTexture2D";
- MakeCurrentLazy();
- return Texture2D::Ref(Texture2DGLES2::Create(service_locator(),
- format,
- levels,
- width,
- height,
- enable_render_surfaces));
-}
-
-TextureCUBE::Ref RendererGLES2::CreatePlatformSpecificTextureCUBE(
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- DLOG(INFO) << "RendererGLES2 CreateTextureCUBE";
- MakeCurrentLazy();
- return TextureCUBE::Ref(TextureCUBEGLES2::Create(service_locator(),
- format,
- levels,
- edge_length,
- enable_render_surfaces));
-}
-
-RenderDepthStencilSurface::Ref RendererGLES2::CreateDepthStencilSurface(
- int width,
- int height) {
- return RenderDepthStencilSurface::Ref(
- new RenderDepthStencilSurfaceGLES2(service_locator(),
- width,
- height));
-}
-
-const int* RendererGLES2::GetRGBAUByteNSwizzleTable() {
- static int swizzle_table[] = { 0, 1, 2, 3, };
- return swizzle_table;
-}
-
-// This is a factory function for creating Renderer objects. Since
-// we're implementing GLES2, we only ever return a GLES2 renderer.
-Renderer* Renderer::CreateDefaultRenderer(ServiceLocator* service_locator) {
- return RendererGLES2::CreateDefault(service_locator);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/gles2/renderer_gles2.h b/o3d/core/cross/gles2/renderer_gles2.h
deleted file mode 100644
index 6ddfbf4..0000000
--- a/o3d/core/cross/gles2/renderer_gles2.h
+++ /dev/null
@@ -1,380 +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 definition of the RendererGLES2 class that provides
-// low-level access for O3D to graphics hardware using the OpenGLES2 API.
-
-#ifndef O3D_CORE_CROSS_GLES2_RENDERER_GLES2_H_
-#define O3D_CORE_CROSS_GLES2_RENDERER_GLES2_H_
-
-#include "core/cross/gles2/gles2_headers.h"
-#include <build/build_config.h>
-#include "core/cross/renderer.h"
-#include "core/cross/renderer_platform.h"
-#include "core/cross/types.h"
-#include "core/cross/state.h"
-
-namespace o3d {
-
-class Material;
-class Effect;
-class DrawEffect;
-class SemanticManager;
-
-// Implements the genereric Renderer interface using OpenGLES2.
-class RendererGLES2 : public Renderer {
- public:
- // Creates a default Renderer.
- static RendererGLES2* CreateDefault(ServiceLocator* service_locator);
- virtual ~RendererGLES2();
-
- // Initialises the renderer for use, claiming hardware resources.
- virtual InitStatus InitPlatformSpecific(const DisplayWindow& display,
- bool off_screen);
-
- // Released all hardware resources.
- virtual void Destroy();
-
- // Overridden from Renderer.
- virtual bool GoFullscreen(const DisplayWindow& display,
- int mode_id);
-
- // Overridden from Renderer.
- virtual bool CancelFullscreen(const DisplayWindow& display,
- int width, int height);
-
- // Tells whether we're currently displayed fullscreen or not.
- virtual bool fullscreen() const {
- return fullscreen_;
- }
-
- // Get a vector of the available fullscreen display modes.
- // Clears *modes on error.
- virtual void GetDisplayModes(std::vector<DisplayMode> *modes);
-
- // Get a single fullscreen display mode by id.
- // Returns true on success, false on error.
- virtual bool GetDisplayMode(int id, DisplayMode *mode);
-
- // Resizes the viewport in OpenGLES2.
- virtual void Resize(int width, int height);
-
- // Creates a StreamBank, returning a platform specific implementation class.
- virtual StreamBank::Ref CreateStreamBank();
-
- // Creates a Primitive, returning a platform specific implementation class.
- virtual Primitive::Ref CreatePrimitive();
-
- // Creates a DrawElement, returning a platform specific implementation
- // class.
- virtual DrawElement::Ref CreateDrawElement();
-
- // Creates and returns a GLES2 specific float buffer.
- virtual VertexBuffer::Ref CreateVertexBuffer();
-
- // Creates and returns a GLES2 specific integer buffer.
- virtual IndexBuffer::Ref CreateIndexBuffer();
-
- // Creates and returns a GLES2 specific Effect object.
- virtual Effect::Ref CreateEffect();
-
- // Creates and returns a GLES2 specific Sampler object.
- virtual Sampler::Ref CreateSampler();
-
- // Creates and returns a platform-specific RenderDepthStencilSurface object
- // for use as a depth-stencil render target.
- virtual RenderDepthStencilSurface::Ref CreateDepthStencilSurface(
- int width,
- int height);
-
- // Overridden from Renderer.
- virtual const int* GetRGBAUByteNSwizzleTable();
-
- // Makes this renderer active on the current thread if it is not active
- // already.
- void MakeCurrentLazy() {
- if (!IsCurrent())
- MakeCurrent();
- }
-
- // Returns whether or not this renderer is active on the current thread.
- // Don't worry, the "get" calls are el cheapo.
- bool IsCurrent() {
-#if defined(OS_MACOSX)
- if ((mac_agl_context_ != NULL) &&
- (mac_agl_context_ == aglGetCurrentContext())) {
- return true;
- } else if ((mac_cgl_context_ != NULL) &&
- (mac_cgl_context_ == CGLGetCurrentContext())) {
- return true;
- }
-#elif defined(OS_WIN)
- if ((gl_context_ != NULL) &&
- (gl_context_ == wglGetCurrentContext())) {
- return true;
- }
-#elif defined(OS_LINUX)
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- if ((context_ != NULL) &&
- (context_ == glXGetCurrentContext())) {
- return true;
- }
-#elif defined(GLES2_BACKEND_NATIVE_GLES2)
- if (egl_context_ && egl_context_ == eglGetCurrentContext()) {
- return true;
- }
-#elif defined(GLES2_BACKEND_GLES2_COMMAND_BUFFERS)
-#error RendererGLES2::IsCurrent() Not implemented.
-#endif
-#else
- Error: must port RendererGLES2::IsCurrent() to your platform.
-#endif
- return false;
- }
-
- // Makes this renderer active on the current thread.
- bool MakeCurrent();
-
- // Called by EffectGLES2::PrepareForDraw before setting any parameters.
- void ResetTextureGroupSetCount() {
- ++texture_unit_group_set_count_;
- next_texture_unit_ = 0;
- }
-
- int GetTextureGroupSetCount() {
- return texture_unit_group_set_count_;
- }
-
- // Samplers call this if their texture group set count is out of date.
- GLenum GetNextTextureUnit() {
- return next_texture_unit_++;
- }
-
- // Programs the helper constants into the hardware.
- void UpdateDxClippingUniform(GLint location);
-
-#if defined(GLES2_BACKEND_DESKTOP_GL)
-#if defined(OS_LINUX)
- inline GLXContext glx_context() const { return context_; }
-#endif
-#if defined(OS_MACOSX)
- // We need to be able to reset the CGLContextObj when we go into and
- // out of full-screen mode.
- void set_mac_cgl_context(CGLContextObj obj);
-#endif
-#elif defined(GLES2_BACKEND_NATIVE_GLES2)
- inline EGLContext egl_context() const { return egl_context_; }
-#endif
-
- protected:
- // Keep the constructor protected so only factory methods can create
- // renderers.
- explicit RendererGLES2(ServiceLocator* service_locator);
-
- // Overridden from Renderer.
- virtual bool PlatformSpecificBeginDraw();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificEndDraw();
-
- // Overridden from Renderer.
- virtual bool PlatformSpecificStartRendering();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificFinishRendering();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificPresent();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificClear(const Float4 &color,
- bool color_flag,
- float depth,
- bool depth_flag,
- int stencil,
- bool stencil_flag);
-
- // Overridden from Renderer.
- virtual ParamCache* CreatePlatformSpecificParamCache();
-
- // Sets the viewport. This is the platform specific version.
- void SetViewportInPixels(int left,
- int top,
- int width,
- int height,
- float min_z,
- float max_z);
-
- // Overridden from Renderer.
- virtual void SetBackBufferPlatformSpecific();
-
- // Overridden from Renderer.
- virtual void SetRenderSurfacesPlatformSpecific(
- const RenderSurface* surface,
- const RenderDepthStencilSurface* depth_surface);
-
- // Overridden from Renderer.
- virtual Texture2D::Ref CreatePlatformSpecificTexture2D(
- int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
- // Overridden from Renderer.
- virtual TextureCUBE::Ref CreatePlatformSpecificTextureCUBE(
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
- // Overridden from Renderer.
- virtual void ApplyDirtyStates();
-
- private:
- // Platform-independent GLES2 initialization
- InitStatus InitCommonGLES2();
-
- // Platform-independent GLES2 destruction
- void DestroyCommonGLES2();
-
- // Updates the helper constant used to remap D3D clip coordinates to GLES2
- // ones.
- void UpdateHelperConstant(float width, float height);
-
- ServiceDependency<SemanticManager> semantic_manager_;
-
- // Indicates we're rendering fullscreen rather than in the plugin region.
- bool fullscreen_;
-
-#ifdef OS_WIN
- // Handle to the GLES2 device.
- HWND window_;
- HDC device_context_;
- HGLRC gl_context_;
-#endif
-
-#ifdef OS_MACOSX
- AGLContext mac_agl_context_;
- CGLContextObj mac_cgl_context_;
-#endif
-
-#ifdef OS_LINUX
- Display *display_;
- Window window_;
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- GLXContext context_;
-#elif defined(GLES2_BACKEND_NATIVE_GLES2)
- EGLDisplay egl_display_;
- EGLSurface egl_surface_;
- EGLContext egl_context_;
-#endif
-#endif
-
- // Handle to the framebuffer-object used while rendering to off-screen
- // targets.
- GLuint render_surface_framebuffer_;
-
- friend class AlphaReferenceHandler;
- bool alpha_function_ref_changed_;
- GLenum alpha_function_;
- GLclampf alpha_ref_;
-
- friend class BlendFunctionHandler;
- friend class BlendEquationHandler;
- bool alpha_blend_settings_changed_;
- bool separate_alpha_blend_enable_;
- enum {
- RGB,
- ALPHA,
- };
- enum {
- SRC,
- DST,
- };
- GLenum blend_function_[2][2]; // SRC/DST, RGB/ALPHA
- GLenum blend_equation_[2]; // RGB/ALPHA
-
- bool stencil_settings_changed_;
- bool separate_stencil_settings_enable_;
-
- // States for Stencils
- friend class StencilOperationHandler;
- friend class StencilRefHandler;
- friend class StencilMaskHandler;
- struct StencilStates {
- GLenum func_;
- enum {
- FAIL_OP,
- ZFAIL_OP,
- PASS_OP,
- };
- int op_[3];
- };
-
- enum {
- FRONT,
- BACK,
- };
- StencilStates stencil_settings_[2];
-
- enum {
- READ_MASK,
- WRITE_MASK,
- };
- int stencil_mask_[2];
- int stencil_ref_;
-
- // States for PolygonOffset
- friend class PolygonOffset1Handler;
- friend class PolygonOffset2Handler;
- bool polygon_offset_changed_;
- float polygon_offset_factor_;
- float polygon_offset_bias_;
-
- // Sets the stencils states for either front, back or both facing polys.
- void SetStencilStates(GLenum face, const StencilStates& stencil_states);
-
- // Sampler test against this to see if their cached texture unit is valid.
- int texture_unit_group_set_count_;
-
- // The next texture unit to use. This is reset with ResetTextureUnit
- // and retrieved with GetNextTextureUnit.
- GLenum next_texture_unit_;
-
- // Transform matrix coefficients to match DX clipping rules.
- GLfloat dx_clipping_[4];
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GLES2_RENDERER_GLES2_H_
diff --git a/o3d/core/cross/gles2/sampler_gles2.cc b/o3d/core/cross/gles2/sampler_gles2.cc
deleted file mode 100644
index 6f4769b..0000000
--- a/o3d/core/cross/gles2/sampler_gles2.cc
+++ /dev/null
@@ -1,232 +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 for SamplerGLES2.
-
-#include "core/cross/gles2/gles2_headers.h"
-#include "core/cross/error.h"
-#include "core/cross/gles2/renderer_gles2.h"
-#include "core/cross/gles2/sampler_gles2.h"
-
-namespace o3d {
-
-SamplerGLES2::SamplerGLES2(ServiceLocator* service_locator)
- : Sampler(service_locator),
- renderer_(static_cast<RendererGLES2*>(
- service_locator->GetService<Renderer>())),
- texture_unit_group_set_count_(renderer_->GetTextureGroupSetCount() - 1),
- texture_unit_(0) {
-}
-
-SamplerGLES2::~SamplerGLES2() {
-}
-
-namespace {
-
-unsigned int GLAddressMode(Sampler::AddressMode o3d_mode,
- unsigned int default_mode) {
- unsigned int gl_mode = default_mode;
- switch (o3d_mode) {
- case Sampler::WRAP:
- gl_mode = GL_REPEAT;
- break;
- case Sampler::MIRROR:
- gl_mode = GL_MIRRORED_REPEAT;
- break;
- case Sampler::CLAMP:
- gl_mode = GL_CLAMP_TO_EDGE;
- break;
- case Sampler::BORDER:
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- gl_mode = GL_CLAMP_TO_BORDER;
-#else
- NOTIMPLEMENTED() << "Sampler::BORDER";
- gl_mode = GL_CLAMP_TO_EDGE;
-#endif
- break;
- default:
- DLOG(ERROR) << "Unknown Address mode " << static_cast<int>(o3d_mode);
- break;
- }
- return gl_mode;
-}
-
-unsigned int GLMinFilter(Sampler::FilterType o3d_filter,
- Sampler::FilterType mip_filter) {
- switch (o3d_filter) {
- case Sampler::NONE:
- return GL_NEAREST;
- case Sampler::POINT:
- if (mip_filter == Sampler::NONE)
- return GL_NEAREST;
- else if (mip_filter == Sampler::POINT)
- return GL_NEAREST_MIPMAP_NEAREST;
- else if (mip_filter == Sampler::LINEAR)
- return GL_NEAREST_MIPMAP_LINEAR;
- else if (mip_filter == Sampler::ANISOTROPIC)
- return GL_NEAREST_MIPMAP_LINEAR;
- case Sampler::ANISOTROPIC: // Anisotropy is handled in SetTextureAndStates
- case Sampler::LINEAR:
- if (mip_filter == Sampler::NONE)
- return GL_LINEAR;
- else if (mip_filter == Sampler::POINT)
- return GL_LINEAR_MIPMAP_NEAREST;
- else if (mip_filter == Sampler::LINEAR)
- return GL_LINEAR_MIPMAP_LINEAR;
- else if (mip_filter == Sampler::ANISOTROPIC)
- return GL_LINEAR_MIPMAP_LINEAR;
- }
- // fall through
- DLOG(ERROR) << "Unknown filter " << static_cast<int>(o3d_filter);
- DCHECK(false);
- return GL_NONE;
-}
-
-unsigned int GLMagFilter(Sampler::FilterType o3d_filter) {
- switch (o3d_filter) {
- case Sampler::NONE:
- case Sampler::POINT:
- return GL_NEAREST;
- case Sampler::LINEAR:
- case Sampler::ANISOTROPIC:
- return GL_LINEAR;
- default:
- DLOG(ERROR) << "Unknown filter " << static_cast<int>(o3d_filter);
- return GL_LINEAR;
- }
-}
-
-GLenum GLTextureTarget(Texture* texture) {
- if (texture->IsA(Texture2D::GetApparentClass())) {
- return GL_TEXTURE_2D;
- } else if (texture->IsA(TextureCUBE::GetApparentClass())) {
- return GL_TEXTURE_CUBE_MAP;
- } else {
- DLOG(ERROR) << "Unknown texture target";
- return 0;
- }
-}
-
-} // namespace
-
-GLint SamplerGLES2::SetTextureAndStates(GLES2Parameter gl_param) {
- // Get the texture object associated with this sampler.
- Texture* texture_object = texture();
-
- if (!texture_object) {
- texture_object = renderer_->error_texture();
- if (!texture_object) {
- O3D_ERROR(service_locator())
- << "Missing texture for sampler " << name();
- texture_object = renderer_->fallback_error_texture();
- }
- }
-
- if (!renderer_->SafeToBindTexture(texture_object)) {
- O3D_ERROR(renderer_->service_locator())
- << "Attempt to bind texture, " << texture_object->name()
- << " when drawing to same texture as a RenderSurface";
- texture_object = renderer_->error_texture();
- }
-
- GLint handle = static_cast<GLint>(reinterpret_cast<intptr_t>(
- texture_object->GetTextureHandle()));
- if (handle) {
- // TODO(o3d): this is a slow check and needs to be moved to initialization
- // time.
- GLenum target = GLTextureTarget(texture_object);
- if (target) {
- int renderer_texture_unit_group_set_count =
- renderer_->GetTextureGroupSetCount();
- if (renderer_texture_unit_group_set_count !=
- texture_unit_group_set_count_) {
- texture_unit_group_set_count_ = renderer_texture_unit_group_set_count;
- texture_unit_ = renderer_->GetNextTextureUnit();
- }
- ::glActiveTexture(GL_TEXTURE0 + texture_unit_);
- glBindTexture(target, handle);
- glTexParameteri(target,
- GL_TEXTURE_WRAP_S,
- GLAddressMode(address_mode_u(), GL_REPEAT));
- glTexParameteri(target,
- GL_TEXTURE_WRAP_T,
- GLAddressMode(address_mode_v(), GL_REPEAT));
- // disable mipmapping if we have only one level.
- FilterType clamped_mip_filter =
- texture_object->levels() == 1 ? NONE : mip_filter();
- glTexParameteri(target,
- GL_TEXTURE_MIN_FILTER,
- GLMinFilter(min_filter(), clamped_mip_filter));
- glTexParameteri(target,
- GL_TEXTURE_MAG_FILTER,
- GLMagFilter(mag_filter()));
-
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- Float4 color = border_color();
- GLfloat gl_color[4] = {color[0], color[1], color[2], color[3]};
- glTexParameterfv(target, GL_TEXTURE_BORDER_COLOR, gl_color);
-#else
- // Not implemented
-#endif
-
-
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- // Check for anisotropic texture filtering.
- if (GLEW_EXT_texture_filter_anisotropic) {
- int gl_max_anisotropy =
- (min_filter() == ANISOTROPIC) ? max_anisotropy() : 1;
- glTexParameteri(target, GL_TEXTURE_MAX_ANISOTROPY_EXT,
- gl_max_anisotropy);
- }
-#else
- // TODO(piman): test for GL_EXT_texture_filter_anisotropic and implement
- // as above.
-#endif
- }
- }
-
- return texture_unit_;
-}
-
-void SamplerGLES2::ResetTexture(GLES2Parameter gl_param) {
- Texture* the_texture = texture();
- if (the_texture) {
- // TODO(o3d): this is a slow check and needs to be moved to initialization
- // time.
- GLenum target = GLTextureTarget(the_texture);
- if (target) {
- glActiveTexture(GL_TEXTURE0 + texture_unit_);
- glBindTexture(target, 0);
- }
- }
-}
-} // namespace o3d
diff --git a/o3d/core/cross/gles2/sampler_gles2.h b/o3d/core/cross/gles2/sampler_gles2.h
deleted file mode 100644
index 1562c8c..0000000
--- a/o3d/core/cross/gles2/sampler_gles2.h
+++ /dev/null
@@ -1,75 +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 class declaration for SamplerGLES2.
-
-#ifndef O3D_CORE_CROSS_GLES2_SAMPLER_GLES2_H_
-#define O3D_CORE_CROSS_GLES2_SAMPLER_GLES2_H_
-
-#include "core/cross/sampler.h"
-
-namespace o3d {
-
-class RendererGLES2;
-
-// TODO(gman): Replace.
-typedef GLuint GLES2Parameter;
-
-// SamplerGLES2 is an implementation of the Sampler object for GLES2.
-class SamplerGLES2 : public Sampler {
- public:
- explicit SamplerGLES2(ServiceLocator* service_locator);
- virtual ~SamplerGLES2();
-
- // Sets the gl texture and sampler states.
- // Returns the handle to the texture.
- GLint SetTextureAndStates(GLES2Parameter gl_param);
-
- // Unbinds the GLES2 texture.
- void ResetTexture(GLES2Parameter gl_param);
-
- private:
- RendererGLES2* renderer_;
-
- // We compare this to RendererGLES2::GetTextureGroupSetCount to see
- // if we need to update our texture unit
- int texture_unit_group_set_count_;
-
- GLenum texture_unit_;
-
- DISALLOW_COPY_AND_ASSIGN(SamplerGLES2);
-};
-} // namespace o3d
-
-
-#endif // O3D_CORE_CROSS_GLES2_SAMPLER_GLES2_H_
-
diff --git a/o3d/core/cross/gles2/stream_bank_gles2.cc b/o3d/core/cross/gles2/stream_bank_gles2.cc
deleted file mode 100644
index d8d36be..0000000
--- a/o3d/core/cross/gles2/stream_bank_gles2.cc
+++ /dev/null
@@ -1,225 +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 definition of StreamBankGLES2.
-
-#include <algorithm>
-
-#include "core/cross/stream.h"
-#include "core/cross/error.h"
-#include "core/cross/gles2/buffer_gles2.h"
-#include "core/cross/gles2/effect_gles2.h"
-#include "core/cross/gles2/stream_bank_gles2.h"
-#include "core/cross/gles2/renderer_gles2.h"
-#include "core/cross/gles2/draw_element_gles2.h"
-#include "core/cross/gles2/utils_gles2-inl.h"
-
-// Someone defines min, conflicting with std::min
-#ifdef min
-#undef min
-#endif
-
-namespace o3d {
-
-namespace {
-
-// Converts from a Field datatype to a suitable GLES2 type
-GLenum GLDataType(const Field& field) {
- if (field.IsA(FloatField::GetApparentClass())) {
- return GL_FLOAT;
- } else if (field.IsA(UByteNField::GetApparentClass())) {
- switch (field.num_components()) {
- case 4:
- return GL_UNSIGNED_BYTE;
- }
- }
- DLOG(ERROR) << "Unknown Stream DataType";
- return GL_INVALID_ENUM;
-}
-
-String GetAttribName(GLuint gl_program, GLuint attrib_index) {
- char buffer[1024];
- GLsizei name_len;
- GLint size;
- GLenum type;
- glGetActiveAttrib(gl_program,
- attrib_index,
- sizeof(buffer),
- &name_len,
- &size,
- &type,
- &buffer[0]);
- if (name_len == 0) {
- return String("**NO INFO FOR ATTRIB**");
- }
- return String(&buffer[0], name_len);
-}
-
-String GetAttribSemantic(GLuint gl_program, GLuint attrib_index) {
- // GLES doesn't have semantics so for now we just return the names.
- return GetAttribName(gl_program, attrib_index);
-}
-
-} // anonymous namespace
-
-// Number of times to log a repeated event before giving up.
-const int kNumLoggedEvents = 5;
-
-// StreamBankGLES2 functions ---------------------------------------------------
-
-StreamBankGLES2::StreamBankGLES2(ServiceLocator* service_locator)
- : StreamBank(service_locator) {
- DLOG(INFO) << "StreamBankGLES2 Construct";
-}
-
-StreamBankGLES2::~StreamBankGLES2() {
- DLOG(INFO) << "StreamBankGLES2 Destruct";
-}
-
-bool StreamBankGLES2::CheckForMissingVertexStreams(
- ParamCacheGLES2::VaryingParameterMap& varying_map,
- GLuint gl_program,
- String* missing_stream) {
- DCHECK(missing_stream);
- DLOG(INFO) << "StreamBankGLES2 InsertMissingVertexStreams";
- // Match VARYING parameters to Buffers with the matching semantics.
- ParamCacheGLES2::VaryingParameterMap::iterator i;
- for (i = varying_map.begin(); i != varying_map.end(); ++i) {
- GLuint attribute_index = i->second;
- String semantic_string(GetAttribSemantic(gl_program, attribute_index));
- Stream::Semantic semantic;
- int semantic_index;
- if (!SemanticNameToSemantic(semantic_string, &semantic, &semantic_index)) {
- *missing_stream = semantic_string;
- }
- int stream_index = FindVertexStream(semantic, semantic_index);
- if (stream_index >= 0) {
- // record the matched stream into the varying parameter map for later
- // use by StreamBankGLES2::Draw().
- i->second = stream_index;
- DLOG(INFO)
- << "StreamBankGLES2 Matched PARAMETER \""
- << GetAttribName(gl_program, attribute_index) << " : "
- << semantic_string << "\" to stream "
- << stream_index << " \""
- << vertex_stream_params_.at(
- stream_index)->stream().field().buffer()->name()
- << "\"";
- } else {
- // no matching stream was found.
- *missing_stream = semantic_string;
- return false;
- }
- }
- CHECK_GL_ERROR();
- return true;
-}
-
-bool StreamBankGLES2::BindStreamsForRendering(
- const ParamCacheGLES2::VaryingParameterMap& varying_map,
- GLuint gl_program,
- unsigned int* max_vertices) {
- *max_vertices = UINT_MAX;
- // Loop over varying params setting up the streams.
- ParamCacheGLES2::VaryingParameterMap::const_iterator i;
- for (i = varying_map.begin(); i != varying_map.end(); ++i) {
- const Stream& stream = vertex_stream_params_.at(i->second)->stream();
- const Field& field = stream.field();
- GLenum type = GLDataType(field);
- if (type == GL_INVALID_ENUM) {
- // TODO(o3d): support other kinds of buffers.
- O3D_ERROR(service_locator())
- << "unsupported field of type '" << field.GetClassName()
- << "' on StreamBank '" << name() << "'";
- return false;
- }
- VertexBufferGLES2 *vbuffer = down_cast<VertexBufferGLES2*>(field.buffer());
- if (!vbuffer) {
- O3D_ERROR(service_locator())
- << "stream has no buffer in StreamBank '" << name() << "'";
- return false;
- }
- // TODO support all data types and packings here. Currently it
- // only supports GL_FLOAT buffers, but buffers of GL_HALF and GL_INT are
- // also possible as streamed parameter inputs.
- GLint element_count = field.num_components();
- if (element_count > 4) {
- element_count = 0;
- DLOG_FIRST_N(ERROR, kNumLoggedEvents)
- << "Unable to find stream for attrib: "
- << GetAttribName(gl_program, i->first);
- }
-
- // In the num_elements = 1 case we want to do the D3D stride = 0 thing.
- // but see below.
- if (vbuffer->num_elements() == 1) {
- // TODO(o3d): passing a stride of 0 has a different meaning in GLES2
- // (compute a stride as if it was packed) than in DX (re-use the vertex
- // over and over again). The equivalent of the DX behavior is by
- // disabling the vertex array, and setting a constant value. Currently,
- // this just avoids de-referencing outside of the vertex buffer, but it
- // doesn't set the proper value: we'd need to map the buffer, get the
- // value, and unmap it (slow !!). A better solution is to disallow 0
- // stride at the API level, and instead maybe provide a way to pss a
- // constant value - but the DX version relies on being able to pass a 0
- // stride, so the whole thing needs a bit of rewrite.
- glDisableVertexAttribArray(i->first);
- } else {
- glBindBufferARB(GL_ARRAY_BUFFER, vbuffer->gl_buffer());
- glVertexAttribPointer(i->first,
- element_count,
- GLDataType(field),
- false,
- vbuffer->stride(),
- BufferOffset(field.offset()));
- glEnableVertexAttribArray(i->first);
- *max_vertices = std::min(*max_vertices, stream.GetMaxVertices());
- }
- }
- return true;
-}
-
-// private member functions ----------------------------------------------------
-
-// Searches the array of streams and returns the index of the stream that
-// matches the semantic and index pair. if no match was found, return "-1"
-int StreamBankGLES2::FindVertexStream(Stream::Semantic semantic, int index) {
- for (unsigned ii = 0; ii < vertex_stream_params_.size(); ++ii) {
- const Stream& stream = vertex_stream_params_[ii]->stream();
- if (stream.semantic() == semantic && stream.semantic_index() == index) {
- return static_cast<int>(ii);
- }
- }
- return -1;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/gles2/stream_bank_gles2.h b/o3d/core/cross/gles2/stream_bank_gles2.h
deleted file mode 100644
index 3582069..0000000
--- a/o3d/core/cross/gles2/stream_bank_gles2.h
+++ /dev/null
@@ -1,74 +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 declaration of the StreamBankGLES2 class.
-
-#ifndef O3D_CORE_CROSS_GLES2_STREAM_BANK_GLES2_H_
-#define O3D_CORE_CROSS_GLES2_STREAM_BANK_GLES2_H_
-
-#include <map>
-#include "core/cross/stream_bank.h"
-#include "core/cross/gles2/param_cache_gles2.h"
-
-namespace o3d {
-
-// StreamBankGLES2 is the OpenGLES2 implementation of the StreamBank.
-class StreamBankGLES2 : public StreamBank {
- public:
- explicit StreamBankGLES2(ServiceLocator* service_locator);
- virtual ~StreamBankGLES2();
-
- // Sets the streams for rendering.
- // Parameter:
- // varying_map: Map of streams.
- // max_vertrices: pointer to variable to receive the maximum vertices
- // the streams can render.
- // Returns:
- // true if all streams were bound.
- bool BindStreamsForRendering(
- const ParamCacheGLES2::VaryingParameterMap& varying_map,
- GLuint gl_program,
- unsigned int* max_vertices);
-
- // Checks for all required streams before rendering.
- bool CheckForMissingVertexStreams(
- ParamCacheGLES2::VaryingParameterMap& varying_map,
- GLuint gl_program,
- String* missing_stream);
-
- private:
- int FindVertexStream(Stream::Semantic semantic, int index);
-};
-} // o3d
-
-#endif // O3D_CORE_CROSS_GLES2_STREAM_BANK_GLES2_H_
-
diff --git a/o3d/core/cross/gles2/texture_gles2.cc b/o3d/core/cross/gles2/texture_gles2.cc
deleted file mode 100644
index 09dc269..0000000
--- a/o3d/core/cross/gles2/texture_gles2.cc
+++ /dev/null
@@ -1,943 +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.
- */
-
-
-// Implementations of the abstract Texture2D and TextureCUBE classes using
-// the OpenGLES2 graphics API.
-
-#include "core/cross/gles2/gles2_headers.h"
-#include "core/cross/error.h"
-#include "core/cross/types.h"
-#include "core/cross/pointer_utils.h"
-#include "core/cross/gles2/renderer_gles2.h"
-#include "core/cross/gles2/render_surface_gles2.h"
-#include "core/cross/gles2/texture_gles2.h"
-#include "core/cross/gles2/utils_gles2.h"
-#include "core/cross/gles2/utils_gles2-inl.h"
-
-namespace o3d {
-
-namespace {
-
-Texture::RGBASwizzleIndices g_gl_abgr32f_swizzle_indices = {0, 1, 2, 3};
-
-} // anonymous namespace.
-
-// Converts an O3D texture format to a GLES2 texture format.
-// Input is 'format'.
-// GLES2 has 2 notions of the format:
-// - the internal format which describes how the format should be stored on the
-// GPU
-// - the (format, type) pair which describes how the input data to glTexImage2D
-// is laid out. If format is 0, the data is compressed and needs to be passed
-// to glCompressedTexImage2D.
-// The internal format is returned in internal_format.
-// The format is the return value of the function.
-// The type is returned in data_type.
-static GLenum GLFormatFromO3DFormat(Texture::Format format,
- GLenum *internal_format,
- GLenum *data_type) {
- switch (format) {
- case Texture::XRGB8: {
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- *internal_format = GL_RGB;
-#else
- // On GLES, the internal_format must match format.
- *internal_format = GL_BGRA;
-#endif
- *data_type = GL_UNSIGNED_BYTE;
- return GL_BGRA;
- }
- case Texture::ARGB8: {
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- *internal_format = GL_RGBA;
-#else
- *internal_format = GL_BGRA;
-#endif
- *data_type = GL_UNSIGNED_BYTE;
- return GL_BGRA;
- }
- case Texture::ABGR16F: {
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- *internal_format = GL_RGBA16F_ARB;
-#else
- *internal_format = GL_RGBA;
-#endif
- *data_type = GL_HALF_FLOAT_ARB;
- return GL_RGBA;
- }
- case Texture::R32F: {
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- *internal_format = GL_LUMINANCE32F_ARB;
-#else
- *internal_format = GL_LUMINANCE;
-#endif
- *data_type = GL_FLOAT;
- return GL_LUMINANCE;
- }
- case Texture::ABGR32F: {
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- *internal_format = GL_RGBA32F_ARB;
-#else
- *internal_format = GL_BGRA;
-#endif
- *data_type = GL_FLOAT;
- return GL_BGRA;
- }
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- case Texture::DXT1: {
- if (GL_EXT_texture_compression_s3tc) {
- *internal_format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
- *data_type = 0;
- return 0;
- } else {
- // TODO(o3d): we need to convert DXT1 -> RGBA8 but keep around the
- // pixels so that we can read them back (we won't try to convert back
- // to DXTC).
- LOG(ERROR) << "DXT1 compressed textures not supported yet.";
- *internal_format = 0;
- *data_type = GL_BYTE;
- return 0;
- }
- }
- case Texture::DXT3: {
- if (GL_EXT_texture_compression_s3tc) {
- *internal_format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
- *data_type = 0;
- return 0;
- } else {
- // TODO(o3d): we need to convert DXT3 -> RGBA8 but keep around the
- // pixels so that we can read them back (we won't try to convert back
- // to DXTC).
- LOG(ERROR) << "DXT3 compressed textures not supported yet.";
- *internal_format = 0;
- *data_type = GL_BYTE;
- return 0;
- }
- }
- case Texture::DXT5: {
- if (GL_EXT_texture_compression_s3tc) {
- *internal_format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
- *data_type = 0;
- return 0;
- } else {
- // TODO(o3d): we need to convert DXT3 -> RGBA8 but keep around the
- // pixels so that we can read them back (we won't try to convert back
- // to DXTC).
- LOG(ERROR) << "DXT5 compressed textures not supported yet.";
- *internal_format = 0;
- *data_type = GL_BYTE;
- return 0;
- }
- }
-#else
- case Texture::DXT1:
- case Texture::DXT3:
- case Texture::DXT5:
- NOTIMPLEMENTED() << "DXT textures";
- *internal_format = 0;
- *data_type = GL_BYTE;
- return 0;
-#endif
- case Texture::UNKNOWN_FORMAT:
- break;
- }
- // failed to find a matching format
- LOG(ERROR) << "Unrecognized Texture format type.";
- *internal_format = 0;
- *data_type = 0;
- return 0;
-}
-
-// Updates a GLES2 image from a bitmap, rescaling if necessary.
-static bool UpdateGLImageFromBitmap(GLenum target,
- unsigned int level,
- TextureCUBE::CubeFace face,
- const Bitmap &bitmap,
- bool resize_to_pot) {
- DCHECK(bitmap.image_data());
- unsigned int mip_width = std::max(1U, bitmap.width() >> level);
- unsigned int mip_height = std::max(1U, bitmap.height() >> level);
- const uint8 *mip_data = bitmap.GetMipData(level);
- size_t mip_size =
- image::ComputeBufferSize(mip_width, mip_height, bitmap.format());
- scoped_array<uint8> temp_data;
- if (resize_to_pot) {
- DCHECK(!Texture::IsCompressedFormat(bitmap.format()));
- unsigned int pot_width =
- std::max(1U, image::ComputePOTSize(bitmap.width()) >> level);
- unsigned int pot_height =
- std::max(1U, image::ComputePOTSize(bitmap.height()) >> level);
- size_t pot_size = image::ComputeBufferSize(pot_width, pot_height,
- bitmap.format());
- temp_data.reset(new uint8[pot_size]);
- image::Scale(mip_width, mip_height, bitmap.format(), mip_data,
- pot_width, pot_height, temp_data.get(),
- image::ComputePitch(bitmap.format(), pot_width));
- mip_width = pot_width;
- mip_height = pot_height;
- mip_size = pot_size;
- mip_data = temp_data.get();
- }
- GLenum gl_internal_format = 0;
- GLenum gl_data_type = 0;
- GLenum gl_format = GLFormatFromO3DFormat(bitmap.format(), &gl_internal_format,
- &gl_data_type);
- FlushGlErrors();
- if (gl_format) {
- glTexSubImage2D(target, level, 0, 0, mip_width, mip_height,
- gl_format, gl_data_type, mip_data);
- } else {
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- glCompressedTexSubImage2D(target, level, 0, 0, mip_width, mip_height,
- gl_internal_format, mip_size, mip_data);
-#else
- NOTIMPLEMENTED() << "DXT textures";
-#endif
- }
- return glGetError() == GL_NO_ERROR;
-}
-
-// Creates the array of GLES2 images for a particular face and upload the pixel
-// data from the bitmap.
-static bool CreateGLImages(GLenum target,
- GLenum internal_format,
- GLenum gl_format,
- GLenum type,
- TextureCUBE::CubeFace face,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool resize_to_pot) {
- unsigned int mip_width = width;
- unsigned int mip_height = height;
- if (resize_to_pot) {
- mip_width = image::ComputePOTSize(mip_width);
- mip_height = image::ComputePOTSize(mip_height);
- }
- // glCompressedTexImage2D does't accept NULL as a parameter, so we need
- // to pass in some data. If we can pass in the original pixel data, we'll
- // do that, otherwise we'll pass an empty buffer. In that case, prepare it
- // here once for all.
- scoped_array<uint8> temp_data;
- size_t size = image::ComputeBufferSize(mip_width, mip_height, format);
- temp_data.reset(new uint8[size]);
- memset(temp_data.get(), 0, size);
-
- for (int i = 0; i < levels; ++i) {
- FlushGlErrors();
- if (gl_format) {
- glTexImage2D(target, i, internal_format, mip_width, mip_height,
- 0, gl_format, type, temp_data.get());
- if (glGetError() != GL_NO_ERROR) {
- DLOG(ERROR) << "glTexImage2D failed";
- return false;
- }
- } else {
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- size_t mip_size = image::ComputeBufferSize(mip_width, mip_height, format);
- glCompressedTexImage2DARB(target, i, internal_format, mip_width,
- mip_height, 0, mip_size, temp_data.get());
- if (glGetError() != GL_NO_ERROR) {
- DLOG(ERROR) << "glCompressedTexImage2D failed";
- return false;
- }
-#else
- NOTIMPLEMENTED() << "DXT textures";
- return false;
-#endif
- }
- mip_width = std::max(1U, mip_width >> 1);
- mip_height = std::max(1U, mip_height >> 1);
- }
- return true;
-}
-
-// Texture2DGLES2 --------------------------------------------------------------
-
-// Constructs a 2D texture object from an existing OpenGLES2 2D texture.
-// NOTE: the Texture2DGLES2 now owns the GLES2 texture and will destroy it on
-// exit.
-Texture2DGLES2::Texture2DGLES2(ServiceLocator* service_locator,
- GLint texture,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool resize_to_pot,
- bool enable_render_surfaces)
- : Texture2D(service_locator,
- width,
- height,
- format,
- levels,
- enable_render_surfaces),
- resize_to_pot_(resize_to_pot),
- renderer_(static_cast<RendererGLES2*>(
- service_locator->GetService<Renderer>())),
- gl_texture_(texture),
- backing_bitmap_(Bitmap::Ref(new Bitmap(service_locator))),
- has_levels_(0),
- locked_levels_(0) {
- DLOG(INFO) << "Texture2DGLES2 Construct from GLint";
- DCHECK_NE(format, Texture::UNKNOWN_FORMAT);
-}
-
-// Creates a new texture object from scratch.
-Texture2DGLES2* Texture2DGLES2::Create(ServiceLocator* service_locator,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool enable_render_surfaces) {
- DLOG(INFO) << "Texture2DGLES2 Create";
- DCHECK_NE(format, Texture::UNKNOWN_FORMAT);
- DCHECK_GE(levels, 0);
- RendererGLES2 *renderer = static_cast<RendererGLES2 *>(
- service_locator->GetService<Renderer>());
- renderer->MakeCurrentLazy();
- GLenum gl_internal_format = 0;
- GLenum gl_data_type = 0;
- GLenum gl_format = GLFormatFromO3DFormat(format,
- &gl_internal_format,
- &gl_data_type);
- if (gl_internal_format == 0) {
- DLOG(ERROR) << "Unsupported format in Texture2DGLES2::Create.";
- return NULL;
- }
-
- bool resize_to_pot = !renderer->supports_npot() &&
- !image::IsPOT(width, height);
-
- // Creates the OpenGLES2 texture object, with all the required mip levels.
- GLuint gl_texture = 0;
- glGenTextures(1, &gl_texture);
- glBindTexture(GL_TEXTURE_2D, gl_texture);
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL,
- levels - 1);
-#else
- // On GLES2, we can't specify GL_TEXTURE_MAX_LEVEL, so we either allocate
- // only the base image, and clamp the min filter, or we allocate all of them.
- if (levels > 1) {
- levels = image::ComputeMipMapCount(width, height);
- }
-#endif
-
- if (!CreateGLImages(GL_TEXTURE_2D, gl_internal_format, gl_format,
- gl_data_type, TextureCUBE::FACE_POSITIVE_X,
- format, levels, width, height, resize_to_pot)) {
- DLOG(ERROR) << "Failed to create texture images.";
- glDeleteTextures(1, &gl_texture);
- return NULL;
- }
- glTexParameteri(GL_TEXTURE_2D,
- GL_TEXTURE_MIN_FILTER,
- GL_NEAREST_MIPMAP_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
-
- Texture2DGLES2 *texture = new Texture2DGLES2(service_locator,
- gl_texture,
- format,
- levels,
- width,
- height,
- resize_to_pot,
- enable_render_surfaces);
-
- // If the hardware does not support npot textures, allocate a 0-initialized
- // mip-chain here for use during Texture2DGLES2::Lock.
- if (resize_to_pot) {
- texture->backing_bitmap_->Allocate(format, width, height, levels,
- Bitmap::IMAGE);
- texture->has_levels_ = (1 << levels) - 1;
- }
- CHECK_GL_ERROR();
- return texture;
-}
-
-void Texture2DGLES2::UpdateBackedMipLevel(unsigned int level) {
- DCHECK_LT(static_cast<int>(level), levels());
- DCHECK(backing_bitmap_->image_data());
- DCHECK_EQ(backing_bitmap_->width(), static_cast<unsigned int>(width()));
- DCHECK_EQ(backing_bitmap_->height(), static_cast<unsigned int>(height()));
- DCHECK_EQ(backing_bitmap_->format(), format());
- renderer_->MakeCurrentLazy();
- glBindTexture(GL_TEXTURE_2D, gl_texture_);
- UpdateGLImageFromBitmap(GL_TEXTURE_2D, level, TextureCUBE::FACE_POSITIVE_X,
- *backing_bitmap_.Get(), resize_to_pot_);
-}
-
-Texture2DGLES2::~Texture2DGLES2() {
- DLOG(INFO) << "Texture2DGLES2 Destruct";
- if (gl_texture_) {
- renderer_->MakeCurrentLazy();
- glDeleteTextures(1, &gl_texture_);
- gl_texture_ = 0;
- }
- CHECK_GL_ERROR();
-}
-
-void Texture2DGLES2::SetRect(int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned src_width,
- unsigned src_height,
- const void* src_data,
- int src_pitch) {
- if (level >= levels() || level < 0) {
- O3D_ERROR(service_locator())
- << "Trying to SetRect on non-existent level " << level
- << " on Texture \"" << name() << "\"";
- return;
- }
- if (render_surfaces_enabled()) {
- O3D_ERROR(service_locator())
- << "Attempting to SetRect a render-target texture: " << name();
- return;
- }
-
- unsigned mip_width = image::ComputeMipDimension(level, width());
- unsigned mip_height = image::ComputeMipDimension(level, height());
-
- if (dst_left + src_width > mip_width ||
- dst_top + src_height > mip_height) {
- O3D_ERROR(service_locator())
- << "SetRect(" << level << ", " << dst_left << ", " << dst_top << ", "
- << src_width << ", " << src_height << ") out of range for texture << \""
- << name() << "\"";
- return;
- }
-
- bool entire_rect = dst_left == 0 && dst_top == 0 &&
- src_width == mip_width && src_height == mip_height;
- bool compressed = IsCompressed();
-
- if (compressed && !entire_rect) {
- O3D_ERROR(service_locator())
- << "SetRect must be full rectangle for compressed textures";
- return;
- }
-
- if (resize_to_pot_) {
- DCHECK(backing_bitmap_->image_data());
- DCHECK(!compressed);
- // We need to update the backing mipmap and then use that to update the
- // texture.
- backing_bitmap_->SetRect(
- level, dst_left, dst_top, src_width, src_height, src_data, src_pitch);
- UpdateBackedMipLevel(level);
- } else {
- renderer_->MakeCurrentLazy();
- glBindTexture(GL_TEXTURE_2D, gl_texture_);
- GLenum gl_internal_format = 0;
- GLenum gl_data_type = 0;
- GLenum gl_format = GLFormatFromO3DFormat(format(), &gl_internal_format,
- &gl_data_type);
- if (gl_format) {
- if (src_pitch == image::ComputePitch(format(), src_width)) {
- glTexSubImage2D(GL_TEXTURE_2D, level,
- dst_left, dst_top,
- src_width, src_height,
- gl_format,
- gl_data_type,
- src_data);
- } else {
- int limit = src_height;
- for (int yy = 0; yy < limit; ++yy) {
- glTexSubImage2D(GL_TEXTURE_2D, level,
- dst_left, dst_top + yy,
- src_width, 1,
- gl_format,
- gl_data_type,
- src_data);
- src_data = AddPointerOffset<const void*>(src_data, src_pitch);
- }
- }
- } else {
- glCompressedTexSubImage2D(
- GL_TEXTURE_2D, level, 0, 0, src_width, src_height,
- gl_internal_format,
- image::ComputeMipChainSize(src_width, src_height, format(), 1),
- src_data);
- }
- }
- if (level == 0) {
- TextureUpdated();
- }
-}
-
-// Locks the given mipmap level of this texture for loading from main memory,
-// and returns a pointer to the buffer.
-bool Texture2DGLES2::PlatformSpecificLock(
- int level, void** data, int* pitch, Texture::AccessMode mode) {
- DLOG(INFO) << "Texture2DGLES2 Lock";
- DCHECK(data);
- DCHECK(pitch);
- DCHECK_GE(level, 0);
- DCHECK_LT(level, levels());
- renderer_->MakeCurrentLazy();
- if (!backing_bitmap_->image_data()) {
- DCHECK_EQ(has_levels_, 0u);
- backing_bitmap_->Allocate(format(), width(), height(), levels(),
- Bitmap::IMAGE);
- }
- *data = backing_bitmap_->GetMipData(level);
- unsigned int mip_width = image::ComputeMipDimension(level, width());
- if (!IsCompressed()) {
- *pitch = image::ComputePitch(format(), mip_width);
- } else {
- unsigned blocks_across = (mip_width + 3) / 4;
- unsigned bytes_per_block = format() == Texture::DXT1 ? 8 : 16;
- unsigned bytes_per_row = bytes_per_block * blocks_across;
- *pitch = bytes_per_row;
- }
- if (mode != kWriteOnly && !HasLevel(level)) {
- DCHECK(!resize_to_pot_);
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- GLenum gl_internal_format = 0;
- GLenum gl_data_type = 0;
- GLenum gl_format = GLFormatFromO3DFormat(format(),
- &gl_internal_format,
- &gl_data_type);
- glBindTexture(GL_TEXTURE_2D, gl_texture_);
- glGetTexImage(GL_TEXTURE_2D, level, gl_format, gl_data_type, *data);
-#else
- NOTIMPLEMENTED() << "Texture read back";
-#endif
- has_levels_ |= 1 << level;
- }
- locked_levels_ |= 1 << level;
- CHECK_GL_ERROR();
- return true;
-}
-
-// Unlocks the given mipmap level of this texture, uploading the main memory
-// data buffer to GLES2.
-bool Texture2DGLES2::PlatformSpecificUnlock(int level) {
- DLOG(INFO) << "Texture2DGLES2 Unlock";
- DCHECK_GE(level, 0);
- DCHECK_LT(level, levels());
- if (LockedMode(level) != kReadOnly) {
- renderer_->MakeCurrentLazy();
- UpdateBackedMipLevel(level);
- }
- locked_levels_ &= ~(1 << level);
- if (!resize_to_pot_ && (locked_levels_ == 0)) {
- backing_bitmap_->FreeData();
- has_levels_ = 0;
- }
- CHECK_GL_ERROR();
- return true;
-}
-
-RenderSurface::Ref Texture2DGLES2::PlatformSpecificGetRenderSurface(
- int mip_level) {
- DCHECK_LT(mip_level, levels());
- if (!render_surfaces_enabled()) {
- O3D_ERROR(service_locator())
- << "Attempting to get RenderSurface from non-render-surface-enabled"
- << " Texture: " << name();
- return RenderSurface::Ref(NULL);
- }
-
- if (mip_level >= levels() || mip_level < 0) {
- O3D_ERROR(service_locator())
- << "Attempting to access non-existent mip_level " << mip_level
- << " in render-target texture \"" << name() << "\".";
- return RenderSurface::Ref(NULL);
- }
-
- return RenderSurface::Ref(new RenderSurfaceGLES2(
- service_locator(),
- width()>> mip_level,
- height() >> mip_level,
- 0,
- mip_level,
- this));
-}
-
-const Texture::RGBASwizzleIndices& Texture2DGLES2::GetABGR32FSwizzleIndices() {
- return g_gl_abgr32f_swizzle_indices;
-}
-
-// TextureCUBEGLES2 ------------------------------------------------------------
-
-// Creates a texture from a pre-existing GLES2 texture object.
-TextureCUBEGLES2::TextureCUBEGLES2(ServiceLocator* service_locator,
- GLint texture,
- Texture::Format format,
- int levels,
- int edge_length,
- bool resize_to_pot,
- bool enable_render_surfaces)
- : TextureCUBE(service_locator,
- edge_length,
- format,
- levels,
- enable_render_surfaces),
- resize_to_pot_(resize_to_pot),
- renderer_(static_cast<RendererGLES2*>(
- service_locator->GetService<Renderer>())),
- gl_texture_(texture) {
- DLOG(INFO) << "TextureCUBEGLES2 Construct";
- for (int ii = 0; ii < static_cast<int>(NUMBER_OF_FACES); ++ii) {
- backing_bitmaps_[ii] = Bitmap::Ref(new Bitmap(service_locator));
- has_levels_[ii] = 0;
- locked_levels_[ii] = 0;
- }
-}
-
-TextureCUBEGLES2::~TextureCUBEGLES2() {
- DLOG(INFO) << "TextureCUBEGLES2 Destruct";
- if (gl_texture_) {
- renderer_->MakeCurrentLazy();
- glDeleteTextures(1, &gl_texture_);
- gl_texture_ = 0;
- }
- CHECK_GL_ERROR();
-}
-
-static const int kCubemapFaceList[] = {
- GL_TEXTURE_CUBE_MAP_POSITIVE_X,
- GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
- GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
- GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
- GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
- GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
-};
-
-// Create a new Cube texture from scratch.
-TextureCUBEGLES2* TextureCUBEGLES2::Create(ServiceLocator* service_locator,
- Texture::Format format,
- int levels,
- int edge_length,
- bool enable_render_surfaces) {
- DLOG(INFO) << "TextureCUBEGLES2 Create";
- CHECK_GL_ERROR();
- RendererGLES2 *renderer = static_cast<RendererGLES2 *>(
- service_locator->GetService<Renderer>());
- renderer->MakeCurrentLazy();
-
- bool resize_to_pot = !renderer->supports_npot() &&
- !image::IsPOT(edge_length, edge_length);
-
- // Get gl formats
- GLenum gl_internal_format = 0;
- GLenum gl_data_type = 0;
- GLenum gl_format = GLFormatFromO3DFormat(format,
- &gl_internal_format,
- &gl_data_type);
- if (gl_internal_format == 0) {
- DLOG(ERROR) << "Unsupported format in TextureCUBEGLES2::Create.";
- return NULL;
- }
-
- // Creates the OpenGLES2 texture object, with all the required mip levels.
- GLuint gl_texture = 0;
- glGenTextures(1, &gl_texture);
- glBindTexture(GL_TEXTURE_CUBE_MAP, gl_texture);
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL,
- levels - 1);
-#else
- // On GLES2, we can't specify GL_TEXTURE_MAX_LEVEL, so we either allocate
- // only the base image, and clamp the min filter, or we allocate all of them.
- if (levels > 1) {
- levels = image::ComputeMipMapCount(edge_length, edge_length);
- }
-#endif
-
- for (int face = 0; face < static_cast<int>(NUMBER_OF_FACES); ++face) {
- CreateGLImages(kCubemapFaceList[face], gl_internal_format,
- gl_format, gl_data_type,
- static_cast<CubeFace>(face),
- format, levels, edge_length, edge_length,
- resize_to_pot);
- }
- glTexParameteri(GL_TEXTURE_CUBE_MAP,
- GL_TEXTURE_MIN_FILTER,
- GL_NEAREST_MIPMAP_LINEAR);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-
- // Create a new texture object, which initializes the base Texture class
- // from the Bitmap information.
- TextureCUBEGLES2* texture = new TextureCUBEGLES2(service_locator,
- gl_texture,
- format,
- levels,
- edge_length,
- resize_to_pot,
- enable_render_surfaces);
- // If the hardware does not support npot textures, allocate a 0-initialized
- // mip-chain here for use during TextureCUBEGLES2::Lock.
- if (resize_to_pot) {
- for (int face = 0; face < static_cast<int>(NUMBER_OF_FACES); ++face) {
- texture->backing_bitmaps_[face]->Allocate(
- format, edge_length, edge_length, levels, Bitmap::IMAGE);
- texture->has_levels_[face] = (1 << levels) - 1;
- }
- }
- CHECK_GL_ERROR();
- DLOG(INFO) << "Created cube map texture (GLuint=" << gl_texture << ")";
- return texture;
-}
-
-void TextureCUBEGLES2::UpdateBackedMipLevel(unsigned int level,
- TextureCUBE::CubeFace face) {
- Bitmap* backing_bitmap = backing_bitmaps_[face].Get();
- DCHECK_LT(static_cast<int>(level), levels());
- DCHECK(backing_bitmap->image_data());
- DCHECK_EQ(backing_bitmap->width(), static_cast<unsigned int>(edge_length()));
- DCHECK_EQ(backing_bitmap->height(), static_cast<unsigned int>(edge_length()));
- DCHECK_EQ(backing_bitmap->format(), format());
- renderer_->MakeCurrentLazy();
- glBindTexture(GL_TEXTURE_2D, gl_texture_);
- UpdateGLImageFromBitmap(kCubemapFaceList[face], level, face,
- *backing_bitmap,
- resize_to_pot_);
-}
-
-RenderSurface::Ref TextureCUBEGLES2::PlatformSpecificGetRenderSurface(
- TextureCUBE::CubeFace face,
- int mip_level) {
- DCHECK_LT(mip_level, levels());
- if (!render_surfaces_enabled()) {
- O3D_ERROR(service_locator())
- << "Attempting to get RenderSurface from non-render-surface-enabled"
- << " Texture: " << name();
- return RenderSurface::Ref(NULL);
- }
-
- if (mip_level >= levels() || mip_level < 0) {
- O3D_ERROR(service_locator())
- << "Attempting to access non-existent mip_level " << mip_level
- << " in render-target texture \"" << name() << "\".";
- return RenderSurface::Ref(NULL);
- }
-
- return RenderSurface::Ref(new RenderSurfaceGLES2(
- service_locator(),
- edge_length() >> mip_level,
- edge_length() >> mip_level,
- kCubemapFaceList[face],
- mip_level,
- this));
-}
-
-void TextureCUBEGLES2::SetRect(TextureCUBE::CubeFace face,
- int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned src_width,
- unsigned src_height,
- const void* src_data,
- int src_pitch) {
- if (level >= levels() || level < 0) {
- O3D_ERROR(service_locator())
- << "Trying to SetRect non-existent level " << level
- << " on Texture \"" << name() << "\"";
- return;
- }
- if (render_surfaces_enabled()) {
- O3D_ERROR(service_locator())
- << "Attempting to SetRect a render-target texture: " << name();
- return;
- }
-
- unsigned mip_width = image::ComputeMipDimension(level, edge_length());
- unsigned mip_height = mip_width;
-
- if (dst_left + src_width > mip_width ||
- dst_top + src_height > mip_height) {
- O3D_ERROR(service_locator())
- << "SetRect(" << level << ", " << dst_left << ", " << dst_top << ", "
- << src_width << ", " << src_height << ") out of range for texture << \""
- << name() << "\"";
- return;
- }
-
- bool entire_rect = dst_left == 0 && dst_top == 0 &&
- src_width == mip_width && src_height == mip_height;
- bool compressed = IsCompressed();
-
- if (compressed && !entire_rect) {
- O3D_ERROR(service_locator())
- << "SetRect must be full rectangle for compressed textures";
- return;
- }
-
- if (resize_to_pot_) {
- Bitmap* backing_bitmap = backing_bitmaps_[face].Get();
- DCHECK(backing_bitmap->image_data());
- DCHECK(!compressed);
- // We need to update the backing mipmap and then use that to update the
- // texture.
- backing_bitmap->SetRect(
- level, dst_left, dst_top, src_width, src_height, src_data, src_pitch);
- UpdateBackedMipLevel(level, face);
- } else {
- // TODO(gman): Should this bind be using a FACE id?
- renderer_->MakeCurrentLazy();
- glBindTexture(GL_TEXTURE_CUBE_MAP, gl_texture_);
- GLenum gl_internal_format = 0;
- GLenum gl_data_type = 0;
- GLenum gl_format = GLFormatFromO3DFormat(format(), &gl_internal_format,
- &gl_data_type);
- int gl_face = kCubemapFaceList[face];
- if (gl_format) {
- if (src_pitch == image::ComputePitch(format(), src_width)) {
- glTexSubImage2D(gl_face, level,
- dst_left, dst_top,
- src_width, src_height,
- gl_format,
- gl_data_type,
- src_data);
- } else {
- int limit = src_height;
- for (int yy = 0; yy < limit; ++yy) {
- glTexSubImage2D(gl_face, level,
- dst_left, dst_top + yy,
- src_width, 1,
- gl_format,
- gl_data_type,
- src_data);
- src_data = AddPointerOffset<const void*>(src_data, src_pitch);
- }
- }
- } else {
- glCompressedTexSubImage2D(
- gl_face, level, 0, 0, src_width, src_height,
- gl_internal_format,
- image::ComputeMipChainSize(src_width, src_height, format(), 1),
- src_data);
- }
- }
- if (level == 0) {
- TextureUpdated();
- }
-}
-
-// Locks the given face and mipmap level of this texture for loading from
-// main memory, and returns a pointer to the buffer.
-bool TextureCUBEGLES2::PlatformSpecificLock(
- CubeFace face, int level, void** data, int* pitch,
- Texture::AccessMode mode) {
- DLOG(INFO) << "TextureCUBEGLES2 Lock";
- DCHECK_GE(level, 0);
- DCHECK_LT(level, levels());
- renderer_->MakeCurrentLazy();
- Bitmap* backing_bitmap = backing_bitmaps_[face].Get();
- if (!backing_bitmap->image_data()) {
- for (int i = 0; i < static_cast<int>(NUMBER_OF_FACES); ++i) {
- DCHECK_EQ(has_levels_[i], 0u);
- }
- backing_bitmap->Allocate(format(), edge_length(), edge_length(), levels(),
- Bitmap::IMAGE);
- }
- *data = backing_bitmap->GetMipData(level);
- unsigned int mip_width = image::ComputeMipDimension(level, edge_length());
- if (!IsCompressed()) {
- *pitch = image::ComputePitch(format(), mip_width);
- } else {
- unsigned blocks_across = (mip_width + 3) / 4;
- unsigned bytes_per_block = format() == Texture::DXT1 ? 8 : 16;
- unsigned bytes_per_row = bytes_per_block * blocks_across;
- *pitch = bytes_per_row;
- }
- if (mode != kWriteOnly && !HasLevel(face, level)) {
- // TODO(o3d): add some API so we don't have to copy back the data if we
- // will rewrite it all.
- DCHECK(!resize_to_pot_);
-#if defined(GLES2_BACKEND_DESKTOP_GL)
- GLenum gl_internal_format = 0;
- GLenum gl_data_type = 0;
- GLenum gl_format = GLFormatFromO3DFormat(format(),
- &gl_internal_format,
- &gl_data_type);
- glBindTexture(GL_TEXTURE_CUBE_MAP, gl_texture_);
- GLenum gl_target = kCubemapFaceList[face];
- glGetTexImage(gl_target, level, gl_format, gl_data_type, *data);
-#else
- NOTIMPLEMENTED() << "Texture read back";
-#endif
- has_levels_[face] |= 1 << level;
- }
- CHECK_GL_ERROR();
-
- locked_levels_[face] |= 1 << level;
-
- return false;
-}
-
-// Unlocks the given face and mipmap level of this texture.
-bool TextureCUBEGLES2::PlatformSpecificUnlock(CubeFace face, int level) {
- DLOG(INFO) << "TextureCUBEGLES2 Unlock";
- DCHECK_GE(level, 0);
- DCHECK_LT(level, levels());
- if (LockedMode(face, level) != kReadOnly) {
- renderer_->MakeCurrentLazy();
- UpdateBackedMipLevel(level, face);
- }
- locked_levels_[face] &= ~(1 << level);
-
- if (!resize_to_pot_) {
- // See if we can throw away the backing bitmap.
- Bitmap* backing_bitmap = backing_bitmaps_[face].Get();
- bool has_locked_level = false;
- for (int i = 0; i < static_cast<int>(NUMBER_OF_FACES); ++i) {
- if (locked_levels_[i]) {
- has_locked_level = true;
- break;
- }
- }
- if (!has_locked_level) {
- backing_bitmap->FreeData();
- for (int i = 0; i < static_cast<int>(NUMBER_OF_FACES); ++i) {
- has_levels_[i] = 0;
- }
- }
- }
- CHECK_GL_ERROR();
- return false;
-}
-
-const Texture::RGBASwizzleIndices&
- TextureCUBEGLES2::GetABGR32FSwizzleIndices() {
- return g_gl_abgr32f_swizzle_indices;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/gles2/texture_gles2.h b/o3d/core/cross/gles2/texture_gles2.h
deleted file mode 100644
index 660bd5a..0000000
--- a/o3d/core/cross/gles2/texture_gles2.h
+++ /dev/null
@@ -1,244 +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 declarations for Texture2DGLES2 and TextureCUBEGLES2.
-
-#ifndef O3D_CORE_CROSS_GLES2_TEXTURE_GLES2_H_
-#define O3D_CORE_CROSS_GLES2_TEXTURE_GLES2_H_
-
-// Precompiled header comes before everything else.
-
-// Disable compiler warning for OpenGLES2 calls that require a void* to be cast
-// to a GLuint
-#if defined(OS_WIN)
-#pragma warning(disable : 4312)
-#pragma warning(disable : 4311)
-#endif
-
-#include "core/cross/bitmap.h"
-#include "core/cross/texture.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-class RendererGLES2;
-
-// Texture2DGLES2 --------------------------------------------------------------
-
-// Texture2DGLES2 implements the Texture2D interface with OpenGLES2.
-class Texture2DGLES2 : public Texture2D {
- public:
- typedef SmartPointer<Texture2DGLES2> Ref;
-
- virtual ~Texture2DGLES2();
-
- // Overridden from Texture2D
- virtual void SetRect(int level,
- unsigned left,
- unsigned top,
- unsigned width,
- unsigned height,
- const void* src_data,
- int src_pitch);
-
- // Creates a new Texture2DGLES2 with the given specs. If the GLES2 texture
- // creation fails then it returns NULL otherwise it returns a pointer to the
- // newly created Texture object.
- // The created texture takes ownership of the bitmap data.
- static Texture2DGLES2* Create(ServiceLocator* service_locator,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool enable_render_surfaces);
-
- // Returns the implementation-specific texture handle for this texture.
- void* GetTextureHandle() const {
- return reinterpret_cast<void*>(gl_texture_);
- }
-
- // Gets the GLES2 texture handle.
- GLuint gl_texture() const { return gl_texture_; }
-
- // Gets a RGBASwizzleIndices that contains a mapping from
- // RGBA to the internal format used by the rendering API.
- virtual const RGBASwizzleIndices& GetABGR32FSwizzleIndices();
-
- protected:
- // Overridden from Texture2D
- virtual bool PlatformSpecificLock(
- int level, void** texture_data, int* pitch, AccessMode mode);
-
- // Overridden from Texture2D
- virtual bool PlatformSpecificUnlock(int level);
-
- // Overridden from Texture2D
- virtual RenderSurface::Ref PlatformSpecificGetRenderSurface(int mip_level);
-
- private:
- // Initializes the Texture2DGLES2 from a preexisting OpenGLES2 texture handle
- // and raw Bitmap data.
- // The texture takes ownership of the bitmap data.
- Texture2DGLES2(ServiceLocator* service_locator,
- GLint texture,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool resize_npot,
- bool enable_render_surfaces);
-
- // Updates a mip level, sending it from the backing bitmap to GLES2, rescaling
- // it if resize_to_pot_ is set.
- void UpdateBackedMipLevel(unsigned int level);
-
- // Returns true if the backing bitmap has the data for the level.
- bool HasLevel(unsigned int level) const {
- DCHECK_LT(static_cast<int>(level), levels());
- return (has_levels_ & (1 << level)) != 0;
- }
-
- // Whether or not this texture needs to be resized from NPOT to pot behind
- // the scenes.
- bool resize_to_pot_;
-
- RendererGLES2* renderer_;
-
- // The handle of the OpenGLES2 texture object.
- GLuint gl_texture_;
-
- // A bitmap used to back the NPOT textures on POT-only hardware, and to back
- // the pixel buffer for Lock().
- Bitmap::Ref backing_bitmap_;
-
- // Bitfield that indicates mip levels that are currently stored in the
- // backing bitmap.
- unsigned int has_levels_;
-
- // Bitfield that indicates which levels are currently locked.
- unsigned int locked_levels_;
-};
-
-
-// TextureCUBEGLES2 ------------------------------------------------------------
-
-// TextureCUBEGLES2 implements the TextureCUBE interface with OpenGLES2.
-class TextureCUBEGLES2 : public TextureCUBE {
- public:
- typedef SmartPointer<TextureCUBEGLES2> Ref;
- virtual ~TextureCUBEGLES2();
-
- // Create a new Cube texture from scratch.
- static TextureCUBEGLES2* Create(ServiceLocator* service_locator,
- Texture::Format format,
- int levels,
- int edge_length,
- bool enable_render_surfaces);
-
- // Overridden from TextureCUBE
- virtual void SetRect(CubeFace face,
- int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned width,
- unsigned height,
- const void* src_data,
- int src_pitch);
-
- // Returns the implementation-specific texture handle for this texture.
- virtual void* GetTextureHandle() const {
- return reinterpret_cast<void*>(gl_texture_);
- }
-
- // Gets the GLES2 texture handle.
- GLuint gl_texture() const { return gl_texture_; }
-
- // Gets a RGBASwizzleIndices that contains a mapping from
- // RGBA to the internal format used by the rendering API.
- virtual const RGBASwizzleIndices& GetABGR32FSwizzleIndices();
-
- protected:
- // Overridden from TextureCUBE
- virtual bool PlatformSpecificLock(
- CubeFace face, int level, void** texture_data, int* pitch,
- AccessMode mode);
-
- // Overridden from TextureCUBE
- virtual bool PlatformSpecificUnlock(CubeFace face, int level);
-
- // Overridden from TextureCUBE.
- virtual RenderSurface::Ref PlatformSpecificGetRenderSurface(CubeFace face,
- int level);
- private:
- // Creates a texture from a pre-existing GLES2 texture object.
- TextureCUBEGLES2(ServiceLocator* service_locator,
- GLint texture,
- Texture::Format format,
- int levels,
- int edge_length,
- bool resize_to_pot,
- bool enable_render_surfaces);
-
- // Updates a mip level, sending it from the backing bitmap to GLES2, rescaling
- // it if resize_to_pot_ is set.
- void UpdateBackedMipLevel(unsigned int level, CubeFace face);
-
- // Returns true if the backing bitmap has the data for the level.
- bool HasLevel(CubeFace face, unsigned int level) const {
- DCHECK_LT(static_cast<int>(level), levels());
- return (has_levels_[face] & (1 << level)) != 0;
- }
-
- // Whether or not this texture needs to be resized from NPOT to pot behind
- // the scenes.
- bool resize_to_pot_;
-
- RendererGLES2* renderer_;
-
- // The handle of the OpenGLES2 texture object.
- GLuint gl_texture_;
-
- // Bitmaps used to back the NPOT textures on POT-only hardware.
- Bitmap::Ref backing_bitmaps_[NUMBER_OF_FACES];
-
- // Bitfields that indicates mip levels that are currently stored in the
- // backing bitmap, one per face.
- unsigned int has_levels_[NUMBER_OF_FACES];
-
- // Bitfields that indicates which levels are currently locked, one per face.
- unsigned int locked_levels_[NUMBER_OF_FACES];
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GLES2_TEXTURE_GLES2_H_
-
diff --git a/o3d/core/cross/gles2/utils_gles2-inl.h b/o3d/core/cross/gles2/utils_gles2-inl.h
deleted file mode 100644
index 8ca0d48..0000000
--- a/o3d/core/cross/gles2/utils_gles2-inl.h
+++ /dev/null
@@ -1,50 +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_CORE_CROSS_GLES2_UTILS_GLES2_INL_H_
-#define O3D_CORE_CROSS_GLES2_UTILS_GLES2_INL_H_
-
-#include "core/cross/glcommon/utils_glcommon-inl.h"
-
-namespace o3d {
-
-// convert a byte offset into a Vertex Buffer Object into a GLvoid* for
-// use with glVertexPointer(), glNormalPointer(), glVertexAttribPointer(),
-// etc. after having used a glBindBuffer().
-inline GLvoid* BufferOffset(unsigned i) {
- return static_cast<int8 *>(NULL)+(i);
-}
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GLES2_UTILS_GLES2_INL_H_
-
diff --git a/o3d/core/cross/gles2/utils_gles2.cc b/o3d/core/cross/gles2/utils_gles2.cc
deleted file mode 100644
index 4d07e1c..0000000
--- a/o3d/core/cross/gles2/utils_gles2.cc
+++ /dev/null
@@ -1,79 +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 "base/string_util.h"
-#include "core/cross/stream.h"
-#include "core/cross/types.h"
-#include "core/cross/gles2/utils_gles2.h"
-#include "core/cross/gles2/gles2_headers.h"
-
-// Required OpenGLES2 extensions:
-// GL_ARB_vertex_buffer_object
-// GL_ARB_vertex_program
-// GL_ARB_texture_compression
-// GL_EXT_texture_compression_dxt1
-
-namespace o3d {
-
-bool SemanticNameToSemantic(
- const String& name, Stream::Semantic* semantic, int* semantic_index) {
- struct NameToSemantic {
- const char* const name;
- size_t length;
- const Stream::Semantic semantic;
- };
- static const char kPosition[] = "POSITION";
- static const char kNormal[] = "NORMAL";
- static const char kTangent[] = "TANGENT";
- static const char kBinormal[] = "BINORMAL";
- static const char kColor[] = "COLOR";
- static const char kTexcoord[] = "TEXCOORD";
-
- static const NameToSemantic lookup[] = {
- { kPosition, sizeof(kPosition) - 1, Stream::POSITION, },
- { kNormal, sizeof(kNormal) - 1, Stream::NORMAL, },
- { kTangent, sizeof(kTangent) - 1, Stream::TANGENT, },
- { kBinormal, sizeof(kBinormal) - 1, Stream::BINORMAL, },
- { kColor, sizeof(kColor) - 1, Stream::COLOR, },
- { kTexcoord, sizeof(kTexcoord) - 1, Stream::TEXCOORD, },
- };
- for (unsigned ii = 0; ii < ARRAYSIZE_UNSAFE(lookup); ++ii) {
- const NameToSemantic& info = lookup[ii];
- if (!base::strncasecmp(info.name, name.c_str(), info.length)) {
- *semantic = info.semantic;
- *semantic_index = atoi(name.c_str() + info.length);
- return true;
- }
- }
- return false;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/gles2/utils_gles2.h b/o3d/core/cross/gles2/utils_gles2.h
deleted file mode 100644
index 113b857..0000000
--- a/o3d/core/cross/gles2/utils_gles2.h
+++ /dev/null
@@ -1,46 +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_CORE_CROSS_GLES2_UTILS_GLES2_H_
-#define O3D_CORE_CROSS_GLES2_UTILS_GLES2_H_
-
-#include "base/basictypes.h"
-#include "core/cross/stream.h"
-
-namespace o3d {
-
-bool SemanticNameToSemantic(
- const String& name, Stream::Semantic* semantic, int* semantic_index);
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GLES2_UTILS_GLES2_H_
diff --git a/o3d/core/cross/gpu2d/arena.h b/o3d/core/cross/gpu2d/arena.h
deleted file mode 100644
index 486eedf..0000000
--- a/o3d/core/cross/gpu2d/arena.h
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-// An arena allocates large chunks of memory internally and allocates
-// individual objects out of those chunks. Objects are not freed
-// individually; their storage is reclaimed all at once when the arena
-// is destroyed. The arena calls the constructors of the objects
-// allocated within, but NOT their destructors.
-
-#ifndef O3D_CORE_CROSS_GPU2D_ARENA_H_
-#define O3D_CORE_CROSS_GPU2D_ARENA_H_
-
-#include <stddef.h>
-
-#include <algorithm>
-#include <list>
-
-#include "core/cross/types.h"
-
-namespace o3d {
-namespace gpu2d {
-
-class Arena {
- public:
- // The arena is configured with an allocator, which is responsible
- // for allocating and freeing chunks of memory at a time.
- class Allocator {
- public:
- virtual ~Allocator() {}
- virtual void* Allocate(size_t size) = 0;
- virtual void Free(void* ptr) = 0;
- protected:
- Allocator() {}
- DISALLOW_COPY_AND_ASSIGN(Allocator);
- };
-
- // The Arena's default allocator, which uses malloc and free to
- // allocate chunks of storage.
- class MallocAllocator : public Allocator {
- public:
- virtual void* Allocate(size_t size) {
- return ::malloc(size);
- }
-
- virtual void Free(void* ptr) {
- ::free(ptr);
- }
- };
-
- // Creates a new Arena configured with a MallocAllocator, which is
- // deleted when the arena is.
- Arena()
- : allocator_(new MallocAllocator),
- should_delete_allocator_(true),
- current_(NULL),
- current_chunk_size_(kDefaultChunkSize) {
- }
-
- // Creates a new Arena configured with the given Allocator. The
- // Allocator is not deleted when the arena is.
- explicit Arena(Allocator* allocator)
- : allocator_(allocator),
- should_delete_allocator_(false),
- current_(NULL),
- current_chunk_size_(kDefaultChunkSize) {
- }
-
- // Deletes this arena.
- ~Arena() {
- for_each(chunks_.begin(), chunks_.end(), &Arena::DeleteChunk);
- if (should_delete_allocator_) {
- delete allocator_;
- }
- }
-
- // Allocates an object from the arena.
- template<class T>
- T* Alloc() {
- void* ptr = NULL;
- size_t rounded_size = RoundUp(sizeof(T), MinAlignment());
- if (current_ != NULL)
- ptr = current_->Allocate(rounded_size);
-
- if (ptr == NULL) {
- if (rounded_size > current_chunk_size_)
- current_chunk_size_ = rounded_size;
- current_ = new Chunk(allocator_, current_chunk_size_);
- chunks_.push_back(current_);
- ptr = current_->Allocate(rounded_size);
- }
-
- if (ptr != NULL) {
- // Allocate a T at this spot
- new(ptr) T();
- }
-
- return static_cast<T*>(ptr);
- }
-
- private:
- enum {
- kDefaultChunkSize = 16384
- };
-
- // The following two structures are intended to automatically
- // determine the platform's alignment constraint for structures.
- struct AlignmentInner {
- int64 x;
- };
- struct AlignmentStruct {
- char f1;
- AlignmentInner f2;
- };
-
- // Returns the alignment requirement for classes and structs on the
- // current platform.
- static size_t MinAlignment() {
- return offsetof(AlignmentStruct, f2);
- }
-
- // Rounds up the given allocation size to the specified alignment.
- size_t RoundUp(size_t size, size_t alignment) {
- DCHECK(alignment % 2 == 0);
- return (size + alignment - 1) & ~(alignment - 1);
- }
-
- Allocator* allocator_;
- bool should_delete_allocator_;
-
- // Manages a chunk of memory and individual allocations out of it.
- class Chunk {
- public:
- // Allocates a block of memory of the given size from the passed
- // Allocator.
- Chunk(Allocator* allocator, size_t size)
- : allocator_(allocator),
- size_(size) {
- base_ = static_cast<uint8*>(allocator_->Allocate(size));
- current_offset_ = 0;
- }
-
- // Frees the memory allocated from the Allocator in the
- // constructor.
- ~Chunk() {
- allocator_->Free(base_);
- }
-
- // Returns a pointer to "size" bytes of storage, or NULL if this
- // Chunk could not satisfy the allocation.
- void* Allocate(size_t size) {
- // Check for overflow
- if (current_offset_ + size < current_offset_) {
- return NULL;
- }
-
- if (current_offset_ + size > size_) {
- return NULL;
- }
- void* result = base_ + current_offset_;
- current_offset_ += size;
- return result;
- }
-
- private:
- Allocator* allocator_;
- uint8* base_;
- size_t size_;
- size_t current_offset_;
- DISALLOW_COPY_AND_ASSIGN(Chunk);
- };
-
- // Callback used to delete an individual chunk.
- static void DeleteChunk(Chunk* chunk) {
- delete chunk;
- }
-
- Chunk* current_;
- std::list<Chunk*> chunks_;
- size_t current_chunk_size_;
-
- DISALLOW_COPY_AND_ASSIGN(Arena);
-};
-
-} // namespace gpu2d
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GPU2D_ARENA_H_
-
diff --git a/o3d/core/cross/gpu2d/arena_test.cc b/o3d/core/cross/gpu2d/arena_test.cc
deleted file mode 100644
index 0c34bbf..0000000
--- a/o3d/core/cross/gpu2d/arena_test.cc
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright 2010, 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 arena.
-
-#include <algorithm>
-#include <vector>
-
-#include "base/scoped_ptr.h"
-#include "core/cross/gpu2d/arena.h"
-#include "gtest/gtest.h"
-
-namespace o3d {
-namespace gpu2d {
-
-namespace {
-
-// A base allocator for the Arena which tracks the regions
-// which have been allocated.
-class TrackedMallocAllocator : public Arena::Allocator {
- public:
- TrackedMallocAllocator() {
- }
-
- virtual void* Allocate(size_t size) {
- void* res = ::malloc(size);
- allocated_regions_.push_back(res);
- return res;
- }
-
- virtual void Free(void* ptr) {
- std::vector<void*>::iterator slot = std::find(allocated_regions_.begin(),
- allocated_regions_.end(),
- ptr);
- ASSERT_TRUE(slot != allocated_regions_.end());
- allocated_regions_.erase(slot);
- ::free(ptr);
- }
-
- bool IsEmpty() {
- return NumRegions() == 0;
- }
-
- int NumRegions() {
- return allocated_regions_.size();
- }
-
- private:
- std::vector<void*> allocated_regions_;
- DISALLOW_COPY_AND_ASSIGN(TrackedMallocAllocator);
-};
-
-// A couple of simple structs to allocate.
-struct TestClass1 {
- TestClass1()
- : x(0), y(0), z(0), w(1) {
- }
-
- float x, y, z, w;
-};
-
-struct TestClass2 {
- TestClass2()
- : a(1), b(2), c(3), d(4) {
- }
-
- float a, b, c, d;
-};
-
-} // anonymous namespace
-
-class ArenaTest : public testing::Test {
-};
-
-// Make sure the arena can successfully allocate from more than one
-// region.
-TEST_F(ArenaTest, CanAllocateFromMoreThanOneRegion) {
- TrackedMallocAllocator base_allocator;
- Arena arena(&base_allocator);
- for (int i = 0; i < 10000; i++) {
- arena.Alloc<TestClass1>();
- }
- EXPECT_GT(base_allocator.NumRegions(), 1);
-}
-
-// Make sure the arena frees all allocated regions during destruction.
-TEST_F(ArenaTest, FreesAllAllocatedRegions) {
- scoped_ptr<TrackedMallocAllocator> base_allocator(
- new TrackedMallocAllocator());
- {
- scoped_ptr<Arena> arena(new Arena(base_allocator.get()));
- for (int i = 0; i < 3; i++) {
- arena->Alloc<TestClass1>();
- }
- EXPECT_GT(base_allocator->NumRegions(), 0);
- }
- EXPECT_TRUE(base_allocator->IsEmpty());
-}
-
-// Make sure the arena runs constructors of the objects allocated within.
-TEST_F(ArenaTest, RunsConstructors) {
- Arena arena;
- for (int i = 0; i < 10000; i++) {
- TestClass1* tc1 = arena.Alloc<TestClass1>();
- EXPECT_EQ(0, tc1->x);
- EXPECT_EQ(0, tc1->y);
- EXPECT_EQ(0, tc1->z);
- EXPECT_EQ(1, tc1->w);
- TestClass2* tc2 = arena.Alloc<TestClass2>();
- EXPECT_EQ(1, tc2->a);
- EXPECT_EQ(2, tc2->b);
- EXPECT_EQ(3, tc2->c);
- EXPECT_EQ(4, tc2->d);
- }
-}
-
-} // namespace gpu2d
-} // namespace o3d
-
diff --git a/o3d/core/cross/gpu2d/cubic_classifier.cc b/o3d/core/cross/gpu2d/cubic_classifier.cc
deleted file mode 100644
index 725fec6..0000000
--- a/o3d/core/cross/gpu2d/cubic_classifier.cc
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright 2010, 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 "core/cross/gpu2d/cubic_classifier.h"
-
-#include "core/cross/math_types.h"
-#include "core/cross/gpu2d/cubic_math_utils.h"
-
-namespace o3d {
-namespace gpu2d {
-
-using cubic::ApproxEqual;
-using cubic::RoundToZero;
-
-CubicClassifier::Result CubicClassifier::Classify(float b0x, float b0y,
- float b1x, float b1y,
- float b2x, float b2y,
- float b3x, float b3y) {
- Vector3 b0(b0x, b0y, 1);
- Vector3 b1(b1x, b1y, 1);
- Vector3 b2(b2x, b2y, 1);
- Vector3 b3(b3x, b3y, 1);
-
- // Compute a1..a3
- float a1 = dot(b0, cross(b3, b2));
- float a2 = dot(b1, cross(b0, b3));
- float a3 = dot(b2, cross(b1, b0));
-
- // Compute d1..d3
- float d1 = a1 - 2 * a2 + 3 * a3;
- float d2 = -a2 + 3 * a3;
- float d3 = 3 * a3;
-
- // Experimentation has shown that the texture coordinates computed
- // from these values quickly become huge, leading to roundoff errors
- // and artifacts in the shader. It turns out that if we normalize
- // the vector defined by (d1, d2, d3), this fixes the problem of the
- // texture coordinates getting too large without affecting the
- // classification results.
- Vector3 nd = normalize(Vector3(d1, d2, d3));
- d1 = nd.getX();
- d2 = nd.getY();
- d3 = nd.getZ();
-
- // Compute the discriminant.
- // term0 is a common term in the computation which helps decide
- // which way to classify the cusp case: as serpentine or loop.
- float term0 = (3 * d2 * d2 - 4 * d1 * d3);
- float discr = d1 * d1 * term0;
-
- // Experimentation has also shown that when the classification is
- // near the boundary between one curve type and another, the shader
- // becomes numerically unstable, particularly with the cusp case.
- // Correct for this by rounding d1..d3 and the discriminant to zero
- // when they get near it.
- d1 = RoundToZero(d1);
- d2 = RoundToZero(d2);
- d3 = RoundToZero(d3);
- discr = RoundToZero(discr);
-
- // Do the classification
- if (ApproxEqual(b0, b1) &&
- ApproxEqual(b0, b2) &&
- ApproxEqual(b0, b3)) {
- return Result(kPoint, d1, d2, d3);
- }
-
- if (discr == 0) {
- if (d1 == 0 && d2 == 0) {
- if (d3 == 0)
- return Result(kLine, d1, d2, d3);
- return Result(kQuadratic, d1, d2, d3);
- }
-
- if (d1 == 0)
- return Result(kCusp, d1, d2, d3);
-
- // This is the boundary case described in Loop and Blinn's
- // SIGGRAPH '05 paper of a cusp with inflection at infinity.
- // Because term0 might not be exactly 0, we decide between using
- // the serpentine and loop cases depending on its sign to avoid
- // taking the square root of a negative number when computing the
- // cubic texture coordinates.
- if (term0 < 0)
- return Result(kLoop, d1, d2, d3);
-
- return Result(kSerpentine, d1, d2, d3);
- } else if (discr > 0) {
- return Result(kSerpentine, d1, d2, d3);
- } else {
- // discr < 0
- return Result(kLoop, d1, d2, d3);
- }
-}
-
-} // namespace gpu2d
-} // namespace o3d
-
diff --git a/o3d/core/cross/gpu2d/cubic_classifier.h b/o3d/core/cross/gpu2d/cubic_classifier.h
deleted file mode 100644
index 8b3c03a..0000000
--- a/o3d/core/cross/gpu2d/cubic_classifier.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-// Cubic curve classification algorithm from "Rendering Vector Art on
-// the GPU" by Loop and Blinn, GPU Gems 3, Chapter 25.
-
-#ifndef O3D_CORE_CROSS_GPU2D_CUBIC_CLASSIFIER_H_
-#define O3D_CORE_CROSS_GPU2D_CUBIC_CLASSIFIER_H_
-
-#include "base/basictypes.h"
-
-namespace o3d {
-namespace gpu2d {
-
-// Classifies cubic curves into specific types.
-class CubicClassifier {
- public:
- // The types of cubic curves.
- enum CurveType {
- kSerpentine,
- kCusp,
- kLoop,
- kQuadratic,
- kLine,
- kPoint
- };
-
- // The result of the classifier.
- class Result {
- public:
- Result(CurveType curve_type,
- float d1, float d2, float d3)
- : curve_type_(curve_type),
- d1_(d1),
- d2_(d2),
- d3_(d3) {
- }
-
- CurveType curve_type() const {
- return curve_type_;
- }
-
- float d1() const {
- return d1_;
- }
-
- float d2() const {
- return d2_;
- }
-
- float d3() const {
- return d3_;
- }
-
- private:
- CurveType curve_type_;
- float d1_;
- float d2_;
- float d3_;
- };
-
- // Classifies the given cubic bezier curve starting at (b0x, b0y),
- // ending at (b3x, b3y), and affected by control points (b1x, b1y)
- // and (b2x, b2y).
- static Result Classify(float b0x, float b0y,
- float b1x, float b1y,
- float b2x, float b2y,
- float b3x, float b3y);
-
- private:
- // This class does not need to be instantiated.
- CubicClassifier() {}
- DISALLOW_COPY_AND_ASSIGN(CubicClassifier);
-};
-
-} // namespace gpu2d
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GPU2D_CUBIC_CLASSIFIER_H_
-
diff --git a/o3d/core/cross/gpu2d/cubic_classifier_test.cc b/o3d/core/cross/gpu2d/cubic_classifier_test.cc
deleted file mode 100644
index a0ef475..0000000
--- a/o3d/core/cross/gpu2d/cubic_classifier_test.cc
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright 2010, 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 cubic classifier.
-
-#include "core/cross/gpu2d/cubic_classifier.h"
-#include "gtest/gtest.h"
-
-namespace o3d {
-namespace gpu2d {
-
-// The data points in the following tests were determined by hand in
-// an interactive program.
-
-TEST(CubicClassifierTest, TestSerpentine) {
- CubicClassifier::Result result =
- CubicClassifier::Classify(100, 100,
- 125, 175,
- 200, 100,
- 200, 200);
- EXPECT_EQ(CubicClassifier::kSerpentine, result.curve_type());
-}
-
-TEST(CubicClassifierTest, TestCusp) {
- CubicClassifier::Result result =
- CubicClassifier::Classify(100, 400,
- 200, 200,
- 300, 300,
- 400, 400);
- EXPECT_EQ(CubicClassifier::kCusp, result.curve_type());
-}
-
-TEST(CubicClassifierTest, TestLoop) {
- CubicClassifier::Result result =
- CubicClassifier::Classify(200, 200,
- 400, 100,
- 100, 100,
- 300, 200);
- EXPECT_EQ(CubicClassifier::kLoop, result.curve_type());
-}
-
-TEST(CubicClassifierTest, TestQuadratic) {
- CubicClassifier::Result result =
- CubicClassifier::Classify(100, 100,
- 166.66667f, 166.66667f,
- 233.33333f, 166.66667f,
- 300, 100);
- EXPECT_EQ(CubicClassifier::kQuadratic, result.curve_type());
-}
-
-// Can't figure out how to get the classifier to return kLine.
-
-TEST(CubicClassifierTest, TestPoint) {
- CubicClassifier::Result result =
- CubicClassifier::Classify(100, 100,
- 100, 100,
- 100, 100,
- 100, 100);
- EXPECT_EQ(CubicClassifier::kPoint, result.curve_type());
-}
-
-
-} // namespace gpu2d
-} // namespace o3d
-
diff --git a/o3d/core/cross/gpu2d/cubic_math_utils.cc b/o3d/core/cross/gpu2d/cubic_math_utils.cc
deleted file mode 100644
index 023ce6c..0000000
--- a/o3d/core/cross/gpu2d/cubic_math_utils.cc
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * Copyright 2010, 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 "core/cross/gpu2d/cubic_math_utils.h"
-
-namespace o3d {
-namespace gpu2d {
-namespace cubic {
-
-namespace {
-
-// Utility functions local to this file
-
-int Orientation(float x1, float y1,
- float x2, float y2,
- float x3, float y3) {
- // p1 = (x1, y1)
- // p2 = (x2, y2)
- // p3 = (x3, y3)
- float cross_product = (y2 - y1) * (x3 - x2) - (y3 - y2) * (x2 - x1);
- return (cross_product < 0.0f) ? -1 : ((cross_product > 0.0f) ? 1 : 0);
-}
-
-bool EdgeEdgeTest(float ax, float ay,
- float v0x, float v0y,
- float u0x, float u0y,
- float u1x, float u1y) {
- // This edge to edge test is based on Franlin Antonio's gem: "Faster
- // Line Segment Intersection", in Graphics Gems III, pp. 199-202.
- float bx = u0x - u1x;
- float by = u0y - u1y;
- float cx = v0x - u0x;
- float cy = v0y - u0y;
- float f = ay * bx - ax * by;
- float d = by * cx - bx * cy;
- if ((f > 0 && d >= 0 && d <= f) || (f < 0 && d <= 0 && d >= f)) {
- float e = ax * cy - ay * cx;
-
- // This additional test avoids reporting coincident edges, which
- // is the behavior we want.
- if (ApproxEqual(e, 0) || ApproxEqual(f, 0) || ApproxEqual(e, f)) {
- return false;
- }
-
- if (f > 0) {
- return e >= 0 && e <= f;
- } else {
- return e <= 0 && e >= f;
- }
- }
- return false;
-}
-
-bool EdgeAgainstTriEdges(float v0x, float v0y,
- float v1x, float v1y,
- float u0x, float u0y,
- float u1x, float u1y,
- float u2x, float u2y) {
- float ax, ay;
- ax = v1x - v0x;
- ay = v1y - v0y;
- // Test edge u0, u1 against v0, v1.
- if (EdgeEdgeTest(ax, ay, v0x, v0y, u0x, u0y, u1x, u1y)) {
- return true;
- }
- // Test edge u1, u2 against v0, v1.
- if (EdgeEdgeTest(ax, ay, v0x, v0y, u1x, u1y, u2x, u2y)) {
- return true;
- }
- // Test edge u2, u1 against v0, v1.
- if (EdgeEdgeTest(ax, ay, v0x, v0y, u2x, u2y, u0x, u0y)) {
- return true;
- }
- return false;
-}
-
-} // anonymous namespace
-
-bool LinesIntersect(float p1x, float p1y,
- float q1x, float q1y,
- float p2x, float p2y,
- float q2x, float q2y) {
- return ((Orientation(p1x, p1y, q1x, q1y, p2x, p2y) !=
- Orientation(p1x, p1y, q1x, q1y, q2x, q2y)) &&
- (Orientation(p2x, p2y, q2x, q2y, p1x, p1y) !=
- Orientation(p2x, p2y, q2x, q2y, q1x, q1y)));
-}
-
-bool PointInTriangle(float px, float py,
- float ax, float ay,
- float bx, float by,
- float cx, float cy) {
- // Algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html
- float x0 = cx - ax;
- float y0 = cy - ay;
- float x1 = bx - ax;
- float y1 = by - ay;
- float x2 = px - ax;
- float y2 = py - ay;
-
- float dot00 = x0 * x0 + y0 * y0;
- float dot01 = x0 * x1 + y0 * y1;
- float dot02 = x0 * x2 + y0 * y2;
- float dot11 = x1 * x1 + y1 * y1;
- float dot12 = x1 * x2 + y1 * y2;
- float denom = dot00 * dot11 - dot01 * dot01;
- if (denom == 0.0f) {
- // Triangle is zero-area. Treat query point as not being inside.
- return false;
- }
- // Compute
- float invDenom = 1.0f / denom;
- float u = (dot11 * dot02 - dot01 * dot12) * invDenom;
- float v = (dot00 * dot12 - dot01 * dot02) * invDenom;
-
- return (u > 0.0f) && (v > 0.0f) && (u + v < 1.0f);
-}
-
-bool TrianglesOverlap(float a1x, float a1y,
- float b1x, float b1y,
- float c1x, float c1y,
- float a2x, float a2y,
- float b2x, float b2y,
- float c2x, float c2y) {
- // Derived from coplanar_tri_tri() at
- // http://jgt.akpeters.com/papers/ShenHengTang03/tri_tri.html ,
- // simplified for the 2D case and modified so that overlapping edges
- // do not report overlapping triangles.
-
- // Test all edges of triangle 1 against the edges of triangle 2.
- if (EdgeAgainstTriEdges(a1x, a1y, b1x, b1y, a2x, a2y, b2x, b2y, c2x, c2y))
- return true;
- if (EdgeAgainstTriEdges(b1x, b1y, c1x, c1y, a2x, a2y, b2x, b2y, c2x, c2y))
- return true;
- if (EdgeAgainstTriEdges(c1x, c1y, a1x, a1y, a2x, a2y, b2x, b2y, c2x, c2y))
- return true;
- // Finally, test if tri1 is totally contained in tri2 or vice versa.
- if (PointInTriangle(a1x, a1y, a2x, a2y, b2x, b2y, c2x, c2y))
- return true;
- if (PointInTriangle(a2x, a2y, a1x, a1y, b1x, b1y, c1x, c1y))
- return true;
-
- // Because we define that triangles sharing a vertex or edge don't
- // overlap, we must perform additional point-in-triangle tests to
- // see whether one triangle is contained in the other.
- if (PointInTriangle(b1x, b1y, a2x, a2y, b2x, b2y, c2x, c2y))
- return true;
- if (PointInTriangle(c1x, c1y, a2x, a2y, b2x, b2y, c2x, c2y))
- return true;
- if (PointInTriangle(b2x, b2y, a1x, a1y, b1x, b1y, c1x, c1y))
- return true;
- if (PointInTriangle(c2x, c2y, a1x, a1y, b1x, b1y, c1x, c1y))
- return true;
- return false;
-}
-
-} // namespace cubic
-} // namespace gpu2d
-} // namespace o3d
-
diff --git a/o3d/core/cross/gpu2d/cubic_math_utils.h b/o3d/core/cross/gpu2d/cubic_math_utils.h
deleted file mode 100644
index 1051bb3..0000000
--- a/o3d/core/cross/gpu2d/cubic_math_utils.h
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright 2010, 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_CORE_CROSS_GPU2D_CUBIC_MATH_UTILS_H_
-#define O3D_CORE_CROSS_GPU2D_CUBIC_MATH_UTILS_H_
-
-#include <math.h>
-
-#include "core/cross/math_types.h"
-
-namespace o3d {
-namespace gpu2d {
-namespace cubic {
-
-// A roundoff factor in the cubic classification and texture
-// coordinate generation algorithms. This primarily determines the
-// handling of corner cases during the classification process. Be
-// careful when adjusting this; it has been determined emprically to
-// work well.
-const float kEpsilon = 5.0e-4f;
-
-// Returns zero if value is within +/-kEpsilon of zero.
-inline float RoundToZero(float val) {
- if (val < kEpsilon && val > -kEpsilon)
- return 0;
- return val;
-}
-
-// Returns distance between two points in the 2D plane.
-inline float Distance(float x0, float y0,
- float x1, float y1) {
- float xd = x1 - x0;
- float yd = y1 - y0;
- return sqrtf(xd * xd + yd * yd);
-}
-
-// Returns true if the given points are within kEpsilon distance of
-// each other.
-inline bool ApproxEqual(const Vector3& v0, const Vector3& v1) {
- return lengthSqr(v0 - v1) < kEpsilon * kEpsilon;
-}
-
-// Returns true if the given 2D points are within kEpsilon distance of
-// each other.
-inline bool ApproxEqual(float x0, float y0,
- float x1, float y1) {
- return Distance(x0, y0, x1, y1) < kEpsilon;
-}
-
-// Returns true if the given scalar values are within kEpsilon of each other.
-inline bool ApproxEqual(float f0, float f1) {
- return fabsf(f0 - f1) < kEpsilon;
-}
-
-// Determines whether the line segment between (p1, q1) intersects
-// that between (p2, q2).
-bool LinesIntersect(float p1x, float p1y,
- float q1x, float q1y,
- float p2x, float p2y,
- float q2x, float q2y);
-
-// Determines whether the 2D point defined by (px, py) is inside the
-// 2D triangle defined by vertices (ax, ay), (bx, by), and (cx, cy).
-// This test defines that points exactly on an edge are not considered
-// to be inside the triangle.
-bool PointInTriangle(float px, float py,
- float ax, float ay,
- float bx, float by,
- float cx, float cy);
-
-// Determines whether the triangles defined by the points (a1, b1, c1)
-// and (a2, b2, c2) overlap. The definition of this function is that
-// if the two triangles only share an adjacent edge or vertex, they
-// are not considered to overlap.
-bool TrianglesOverlap(float a1x, float a1y,
- float b1x, float b1y,
- float c1x, float c1y,
- float a2x, float a2y,
- float b2x, float b2y,
- float c2x, float c2y);
-
-} // namespace cubic
-} // namespace gpu2d
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GPU2D_CUBIC_MATH_UTILS_H_
-
diff --git a/o3d/core/cross/gpu2d/cubic_texture_coords.cc b/o3d/core/cross/gpu2d/cubic_texture_coords.cc
deleted file mode 100644
index f797b87..0000000
--- a/o3d/core/cross/gpu2d/cubic_texture_coords.cc
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * Copyright 2010, 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>
-
-#include "base/logging.h"
-#include "core/cross/gpu2d/cubic_math_utils.h"
-#include "core/cross/gpu2d/cubic_texture_coords.h"
-
-namespace o3d {
-namespace gpu2d {
-
-void CubicTextureCoords::Compute(const CubicClassifier::Result& c,
- bool fill_right_side,
- CubicTextureCoords::Result* result) {
- // Loop and Blinn's formulation states that the right side of the
- // curve is defined to be the inside (filled region), but for some
- // reason it looks like with the default orientation parameters we
- // are filling the left side of the curve. Regardless, because we
- // can receive arbitrarily oriented curves as input, we might have
- // to reverse the orientation of the cubic texture coordinates even
- // in cases where the paper doen't say it is necessary.
- bool reverse_orientation = false;
- const float kOneThird = 1.0f / 3.0f;
- const float kTwoThirds = 2.0f / 3.0f;
- CubicClassifier::CurveType curve_type = c.curve_type();
-
- result->is_line_or_point = false;
- result->has_rendering_artifact = false;
- result->subdivision_parameter_value = 0.0f;
-
- switch (curve_type) {
- case CubicClassifier::kSerpentine: {
- float t1 = sqrtf(9.0f * c.d2() * c.d2() - 12 * c.d1() * c.d3());
- float ls = 3.0f * c.d2() - t1;
- float lt = 6.0f * c.d1();
- float ms = 3.0f * c.d2() + t1;
- float mt = lt;
- float ltmls = lt - ls;
- float mtmms = mt - ms;
- result->coords[0] = Vector3(ls * ms,
- ls * ls * ls,
- ms * ms * ms);
- result->coords[1] = Vector3(kOneThird * (3.0f * ls * ms -
- ls * mt -
- lt * ms),
- ls * ls * (ls - lt),
- ms * ms * (ms - mt));
- result->coords[2] = Vector3(kOneThird * (lt * (mt - 2.0f * ms) +
- ls * (3.0f * ms - 2.0f * mt)),
- ltmls * ltmls * ls,
- mtmms * mtmms * ms);
- result->coords[3] = Vector3(ltmls * mtmms,
- -(ltmls * ltmls * ltmls),
- -(mtmms * mtmms * mtmms));
- if (c.d1() < 0.0f)
- reverse_orientation = true;
- break;
- }
-
- case CubicClassifier::kLoop: {
- float t1 = sqrtf(4.0f * c.d1() * c.d3() - 3.0f * c.d2() * c.d2());
- float ls = c.d2() - t1;
- float lt = 2.0f * c.d1();
- float ms = c.d2() + t1;
- float mt = lt;
-
- // Figure out whether there is a rendering artifact requiring
- // the curve to be subdivided by the caller.
- float ql = ls / lt;
- float qm = ms / mt;
- if (0.0f < ql && ql < 1.0f) {
- result->has_rendering_artifact = true;
- result->subdivision_parameter_value = ql;
- // TODO(kbr): may require more work?
- break;
- }
-
- if (0.0f < qm && qm < 1.0f) {
- result->has_rendering_artifact = true;
- result->subdivision_parameter_value = qm;
- // TODO(kbr): may require more work?
- break;
- }
-
- float ltmls = lt - ls;
- float mtmms = mt - ms;
- result->coords[0] = Vector3(ls * ms,
- ls * ls * ms,
- ls * ms * ms);
- result->coords[1] =
- Vector3(kOneThird * (-ls * mt - lt * ms + 3.0f * ls * ms),
- -kOneThird * ls * (ls * (mt - 3.0f * ms) + 2.0f * lt * ms),
- -kOneThird * ms * (ls * (2.0f * mt - 3.0f * ms) + lt * ms));
- result->coords[2] =
- Vector3(kOneThird * (lt * (mt - 2.0f * ms) +
- ls * (3.0f * ms - 2.0f * mt)),
- kOneThird * (lt - ls) * (ls * (2.0f * mt - 3.0f * ms) +
- lt * ms),
- kOneThird * (mt - ms) * (ls * (mt - 3.0f * ms) +
- 2.0f * lt * ms));
- result->coords[3] =
- Vector3(ltmls * mtmms,
- -(ltmls * ltmls) * mtmms,
- -ltmls * mtmms * mtmms);
- reverse_orientation =
- ((c.d1() > 0.0f && result->coords[0].getX() < 0.0f) ||
- (c.d1() < 0.0f && result->coords[0].getX() > 0.0f));
- break;
- }
-
- case CubicClassifier::kCusp: {
- float ls = c.d3();
- float lt = 3.0f * c.d2();
- float lsmlt = ls - lt;
- result->coords[0] = Vector3(ls,
- ls * ls * ls,
- 1.0f);
- result->coords[1] = Vector3(ls - kOneThird * lt,
- ls * ls * lsmlt,
- 1.0f);
- result->coords[2] = Vector3(ls - kTwoThirds * lt,
- lsmlt * lsmlt * ls,
- 1.0f);
- result->coords[3] = Vector3(lsmlt,
- lsmlt * lsmlt * lsmlt,
- 1.0f);
- break;
- }
-
- case CubicClassifier::kQuadratic: {
- result->coords[0] = Vector3(0.0f, 0.0f, 0.0f);
- result->coords[1] = Vector3(kOneThird, 0, kOneThird);
- result->coords[2] = Vector3(kTwoThirds, kOneThird, kTwoThirds);
- result->coords[3] = Vector3(1.0f, 1.0f, 1.0f);
- if (c.d3() < 0.0f)
- reverse_orientation = true;
- break;
- }
-
- case CubicClassifier::kLine:
- case CubicClassifier::kPoint:
- result->is_line_or_point = true;
- break;
-
- default:
- NOTREACHED();
- break;
- }
-
- if (fill_right_side) {
- reverse_orientation = !reverse_orientation;
- }
-
- if (reverse_orientation) {
- for (int i = 0; i < 4; i++) {
- result->coords[i].setX(-result->coords[i].getX());
- result->coords[i].setY(-result->coords[i].getY());
- }
- }
-}
-
-} // namespace gpu2d
-} // namespace o3d
-
diff --git a/o3d/core/cross/gpu2d/cubic_texture_coords.h b/o3d/core/cross/gpu2d/cubic_texture_coords.h
deleted file mode 100644
index 7dab7c5..0000000
--- a/o3d/core/cross/gpu2d/cubic_texture_coords.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-// Computes three-dimensional texture coordinates for the control
-// points of a cubic curve for rendering via the shader in "Rendering
-// Vector Art on the GPU" by Loop and Blinn, GPU Gems 3, Chapter 25.
-
-#ifndef O3D_CORE_CROSS_GPU2D_CUBIC_TEXTURE_COORDS_H_
-#define O3D_CORE_CROSS_GPU2D_CUBIC_TEXTURE_COORDS_H_
-
-#include "base/basictypes.h"
-#include "core/cross/math_types.h"
-#include "core/cross/gpu2d/cubic_classifier.h"
-
-namespace o3d {
-namespace gpu2d {
-
-// Computes texture coordinates for rendering cubic curves on the GPU.
-class CubicTextureCoords {
- public:
- // Container for the cubic texture coordinates and other associated
- // information.
- struct Result {
- Result()
- : is_line_or_point(false),
- has_rendering_artifact(false),
- subdivision_parameter_value(0.0f) {
- }
-
- // The 3D texture coordinates that are to be associated with the
- // four control points of the cubic curve.
- Vector3 coords[4];
-
- // Indicates whether the curve is a line or a point, in which case
- // we do not need to add its triangles to the mesh.
- bool is_line_or_point;
-
- // For the loop case, indicates whether a rendering artifact was
- // detected, in which case the curve needs to be further
- // subdivided.
- bool has_rendering_artifact;
-
- // If a rendering artifact will occur for the given loop curve,
- // this is the parameter value (0 <= value <= 1) at which the
- // curve needs to be subdivided to fix the artifact.
- float subdivision_parameter_value;
- };
-
- // Computes the texture coordinates for a cubic curve segment's
- // control points, given the classification of the curve as well as
- // an indication of which side is to be filled.
- static void Compute(const CubicClassifier::Result& classification,
- bool fill_right_side,
- Result* result);
-
- private:
- // This class does not need to be instantiated.
- CubicTextureCoords() {}
- DISALLOW_COPY_AND_ASSIGN(CubicTextureCoords);
-};
-
-} // namespace gpu2d
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GPU2D_CUBIC_TEXTURE_COORDS_H_
-
diff --git a/o3d/core/cross/gpu2d/interval_tree.h b/o3d/core/cross/gpu2d/interval_tree.h
deleted file mode 100644
index ec4bb2a..0000000
--- a/o3d/core/cross/gpu2d/interval_tree.h
+++ /dev/null
@@ -1,283 +0,0 @@
-/*
- * Copyright 2010, 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_CORE_CROSS_GPU2D_INTERVAL_TREE_H_
-#define O3D_CORE_CROSS_GPU2D_INTERVAL_TREE_H_
-
-#include <vector>
-
-#include "base/logging.h"
-#include "core/cross/gpu2d/arena.h"
-#include "core/cross/gpu2d/red_black_tree.h"
-
-namespace o3d {
-namespace gpu2d {
-
-// Class representing a closed interval which can hold an arbitrary
-// type as its endpoints and a piece of user data. An important
-// characteristic for the algorithms we use is that if two intervals
-// have identical endpoints but different user data, they are not
-// considered to be equal. This situation can arise when representing
-// the vertical extents of bounding boxes of overlapping triangles,
-// where the pointer to the triangle is the user data of the interval.
-//
-// The following constructors and operators must be implemented on
-// type T:
-//
-// - Copy constructor (if user data is desired)
-// - operator<
-// - operator==
-// - operator=
-//
-// If the UserData type is specified, it must support a copy
-// constructor and assignment operator.
-//
-// *Note* that the destructors of type T and UserData will *not* be
-// called by this class. They must not allocate any memory in their
-// constructors.
-//
-// Note that this class requires a copy constructor and assignment
-// operator in order to be stored in the red-black tree.
-template<class T, class UserData = void*>
-class Interval {
- public:
- // Constructor from endpoints. This constructor only works when the
- // UserData type is a pointer or other type which can be initialized
- // with NULL.
- Interval(const T& low, const T& high)
- : low_(low),
- high_(high),
- data_(NULL),
- max_high_(high) {
- }
-
- // Constructor from two endpoints plus explicit user data.
- Interval(const T& low, const T& high, const UserData data)
- : low_(low),
- high_(high),
- data_(data),
- max_high_(high) {
- }
-
- const T& low() const {
- return low_;
- }
-
- const T& high() const {
- return high_;
- }
-
- const UserData& data() const {
- return data_;
- }
-
- // Returns true if this interval overlaps that specified by the
- // given low and high endpoints.
- bool Overlaps(const T& low, const T& high) const {
- if (this->high() < low)
- return false;
- if (high < this->low())
- return false;
- return true;
- }
-
- // Returns true if this interval overlaps the other.
- bool Overlaps(const Interval& other) const {
- return Overlaps(other.low(), other.high());
- }
-
- // Returns true if this interval is "less" than the other. The
- // comparison is performed on the low endpoints of the intervals.
- bool operator<(const Interval& other) const {
- return low() < other.low();
- }
-
- // Returns true if this interval is strictly equal to the other,
- // including comparison of the user data.
- bool operator==(const Interval& other) const {
- return (low() == other.low() &&
- high() == other.high() &&
- data() == other.data());
- }
-
- // Summary information needed for efficient queries.
- const T& max_high() const {
- return max_high_;
- }
-
- // Updates the cache of the summary information for this interval.
- // It is not really const, but it does not affect the user-level
- // state, and must be declared const to obey the contract in the
- // RedBlackTree that Node::data() returns a const reference.
- void set_max_high(const T& max_high) const {
- max_high_ = max_high;
- }
-
- private:
- T low_;
- T high_;
- UserData data_;
- // See the documentation for set_max_high() for an explanation of
- // why this must be mutable.
- mutable T max_high_;
-};
-
-// Suppport for logging Intervals.
-template<class T, class UserData>
-std::ostream& operator<<(std::ostream& ostr, // NOLINT
- const Interval<T, UserData>& arg) {
- ostr << "[Interval (" << arg.low()
- << ", " << arg.high()
- << "), data " << arg.data() << "]";
- return ostr;
-}
-
-// An interval tree, which is a form of augmented red-black tree. It
-// supports efficient (O(lg n)) insertion, removal and querying of
-// intervals in the tree.
-template<class T, class UserData = void*>
-class IntervalTree : public RedBlackTree<Interval<T, UserData> > {
- public:
- // Typedef to reduce typing when declaring intervals to be stored in
- // this tree.
- typedef Interval<T, UserData> IntervalType;
-
- IntervalTree()
- : RedBlackTree<IntervalType>() {
- Init();
- }
-
- explicit IntervalTree(Arena* arena)
- : RedBlackTree<IntervalType>(arena) {
- Init();
- }
-
- // Returns all intervals in the tree which overlap the given query
- // interval. The returned intervals are sorted by increasing low
- // endpoint.
- std::vector<IntervalType> AllOverlaps(const IntervalType& interval) {
- std::vector<IntervalType> result;
- AllOverlaps(interval, result);
- return result;
- }
-
- // Returns all intervals in the tree which overlap the given query
- // interval. The returned intervals are sorted by increasing low
- // endpoint.
- void AllOverlaps(const IntervalType& interval,
- std::vector<IntervalType>& result) {
- // gcc requires explicit dereference of "this" here
- SearchForOverlapsFrom(this->root(), interval, result);
- }
-
- // Helper to create interval objects.
- static IntervalType MakeInterval(const T& low,
- const T& high,
- const UserData data = NULL) {
- return IntervalType(low, high, data);
- }
-
- private:
- typedef typename RedBlackTree<IntervalType>::Node IntervalNode;
-
- // Initializes the tree.
- void Init() {
- // gcc requires explicit dereference of "this" here
- this->set_needs_full_ordering_comparisons(true);
- }
-
- // Starting from the given node, adds all overlaps with the given
- // interval to the result vector. The intervals are sorted by
- // increasing low endpoint.
- void SearchForOverlapsFrom(IntervalNode* node,
- const IntervalType& interval,
- std::vector<IntervalType>& res) {
- if (node == NULL)
- return;
-
- // Because the intervals are sorted by left endpoint, inorder
- // traversal produces results sorted as desired.
-
- // See whether we need to traverse the left subtree.
- IntervalNode* left = node->left();
- if (left != NULL &&
- // This is equivalent to:
- // interval.low() <= left->data().max_high()
- !(left->data().max_high() < interval.low())) {
- SearchForOverlapsFrom(left, interval, res);
- }
-
- // Check for overlap with current node.
- if (node->data().Overlaps(interval)) {
- res.push_back(node->data());
- }
-
- // See whether we need to traverse the right subtree.
- // This is equivalent to:
- // node->data().low() <= interval.high()
- if (!(interval.high() < node->data().low())) {
- SearchForOverlapsFrom(node->right(), interval, res);
- }
- }
-
- virtual bool UpdateNode(IntervalNode* node) {
- // Would use const T&, but need to reassign this reference in this
- // function.
- const T* cur_max = &node->data().high();
- IntervalNode* left = node->left();
- if (left != NULL) {
- if (*cur_max < left->data().max_high()) {
- cur_max = &left->data().max_high();
- }
- }
- IntervalNode* right = node->right();
- if (right != NULL) {
- if (*cur_max < right->data().max_high()) {
- cur_max = &right->data().max_high();
- }
- }
- // This is phrased like this to avoid needing operator!= on type T.
- if (!(*cur_max == node->data().max_high())) {
- node->data().set_max_high(*cur_max);
- return true;
- }
- return false;
- }
-
- DISALLOW_COPY_AND_ASSIGN(IntervalTree);
-};
-
-} // namespace gpu2d
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GPU2D_INTERVAL_TREE_H_
-
diff --git a/o3d/core/cross/gpu2d/interval_tree_test.cc b/o3d/core/cross/gpu2d/interval_tree_test.cc
deleted file mode 100644
index 95b48d0..0000000
--- a/o3d/core/cross/gpu2d/interval_tree_test.cc
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * Copyright 2010, 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 interval tree class.
-
-#include "core/cross/gpu2d/interval_tree.h"
-#include "core/cross/gpu2d/tree_test_helpers.h"
-#include "gtest/gtest.h"
-
-namespace o3d {
-namespace gpu2d {
-
-TEST(IntervalTreeTest, TestInsertion) {
- IntervalTree<float> tree;
- tree.Insert(Interval<float>(2, 4));
- ASSERT_TRUE(tree.Verify());
-}
-
-TEST(IntervalTreeTest, TestInsertionAndQuery) {
- IntervalTree<float> tree;
- tree.Insert(Interval<float>(2, 4));
- ASSERT_TRUE(tree.Verify());
- std::vector<Interval<float> > res =
- tree.AllOverlaps(Interval<float>(1, 3));
- EXPECT_EQ(1U, res.size());
- EXPECT_EQ(2, res[0].low());
- EXPECT_EQ(4, res[0].high());
-}
-
-TEST(IntervalTreeTest, TestQueryAgainstZeroSizeInterval) {
- IntervalTree<float> tree;
- tree.Insert(Interval<float>(1, 2.5));
- tree.Insert(Interval<float>(3.5, 5));
- tree.Insert(Interval<float>(2, 4));
- ASSERT_TRUE(tree.Verify());
- std::vector<Interval<float> > res =
- tree.AllOverlaps(Interval<float>(3, 3));
- EXPECT_EQ(1U, res.size());
- EXPECT_EQ(2, res[0].low());
- EXPECT_EQ(4, res[0].high());
-}
-
-TEST(IntervalTreeTest, TestDuplicateElementInsertion) {
- IntervalTree<float, int*> tree;
- int tmp1 = 1;
- int tmp2 = 2;
- typedef IntervalTree<float, int*>::IntervalType IntervalType;
- IntervalType interval1(1, 3, &tmp1);
- IntervalType interval2(1, 3, &tmp2);
- tree.Insert(interval1);
- tree.Insert(interval2);
- ASSERT_TRUE(tree.Verify());
- EXPECT_TRUE(tree.Contains(interval1));
- EXPECT_TRUE(tree.Contains(interval2));
- EXPECT_TRUE(tree.Delete(interval1));
- EXPECT_TRUE(tree.Contains(interval2));
- EXPECT_FALSE(tree.Contains(interval1));
- EXPECT_TRUE(tree.Delete(interval2));
- EXPECT_EQ(0, tree.NumElements());
-}
-
-namespace {
-struct UserData1 {
- public:
- UserData1() : a(0), b(1) {
- }
-
- float a;
- int b;
-};
-} // anonymous namespace
-
-TEST(IntervalTreeTest, TestInsertionOfComplexUserData) {
- IntervalTree<float, UserData1> tree;
- UserData1 data1;
- data1.a = 5;
- data1.b = 6;
- tree.Insert(tree.MakeInterval(2, 4, data1));
- ASSERT_TRUE(tree.Verify());
-}
-
-TEST(IntervalTreeTest, TestQueryingOfComplexUserData) {
- IntervalTree<float, UserData1> tree;
- UserData1 data1;
- data1.a = 5;
- data1.b = 6;
- tree.Insert(tree.MakeInterval(2, 4, data1));
- ASSERT_TRUE(tree.Verify());
- std::vector<Interval<float, UserData1> > overlaps =
- tree.AllOverlaps(tree.MakeInterval(3, 5, data1));
- EXPECT_EQ(1U, overlaps.size());
- EXPECT_EQ(5, overlaps[0].data().a);
- EXPECT_EQ(6, overlaps[0].data().b);
-}
-
-namespace {
-class EndpointType1 {
- public:
- explicit EndpointType1(int val) : val_(val) {
- }
-
- bool operator<(const EndpointType1& other) const {
- return val_ < other.val_;
- }
-
- bool operator==(const EndpointType1& other) const {
- return val_ == other.val_;
- }
-
- private:
- int val_;
- // These operators should not be required by the interval tree.
- bool operator>(const EndpointType1& other);
- bool operator<=(const EndpointType1& other);
- bool operator>=(const EndpointType1& other);
- bool operator!=(const EndpointType1& other);
-};
-} // anonymous namespace
-
-TEST(IntervalTreeTest, TestTreeDoesNotRequireMostOperators) {
- IntervalTree<EndpointType1> tree;
- tree.Insert(tree.MakeInterval(EndpointType1(1), EndpointType1(2)));
- ASSERT_TRUE(tree.Verify());
-}
-
-static void
-InsertionAndDeletionTest(unsigned seed, int tree_size) {
- InitRandom(seed);
- int max_val = tree_size;
- // Build the tree
- IntervalTree<int> tree;
- std::vector<Interval<int> > added_elements;
- std::vector<Interval<int> > removed_elements;
- for (int i = 0; i < tree_size; i++) {
- int left = NextRandom(max_val);
- int len = NextRandom(max_val);
- Interval<int> interval(left, left + len);
- tree.Insert(interval);
- added_elements.push_back(interval);
- }
- // Churn the tree's contents.
- // First remove half of the elements in random order.
- for (int i = 0; i < tree_size / 2; i++) {
- int idx = NextRandom(added_elements.size());
- tree.Insert(added_elements[idx]);
- EXPECT_TRUE(tree.Verify()) << "Test failed for seed " << seed;
- added_elements.erase(added_elements.begin() + idx);
- }
- // Now randomly add or remove elements.
- for (int i = 0; i < 2 * tree_size; i++) {
- bool add = false;
- if (added_elements.empty()) {
- add = true;
- } else if (removed_elements.empty()) {
- add = false;
- } else {
- add = (NextRandom(2) == 1);
- }
- if (add) {
- int idx = NextRandom(removed_elements.size());
- tree.Insert(removed_elements[idx]);
- added_elements.push_back(removed_elements[idx]);
- removed_elements.erase(removed_elements.begin() + idx);
- } else {
- int idx = NextRandom(added_elements.size());
- EXPECT_TRUE(tree.Contains(added_elements[idx]))
- << "Test failed for seed " << seed;
- EXPECT_TRUE(tree.Delete(added_elements[idx]))
- << "Test failed for seed " << seed;
- removed_elements.push_back(added_elements[idx]);
- added_elements.erase(added_elements.begin() + idx);
- }
- EXPECT_TRUE(tree.Verify()) << "Test failed for seed " << seed;
- }
-}
-
-TEST(IntervalTreeTest, RandomDeletionAndInsertionRegressionTest1) {
- InsertionAndDeletionTest((unsigned) 13972, 100);
-}
-
-TEST(IntervalTreeTest, TestRandomDeletionAndInsertion) {
- InsertionAndDeletionTest((unsigned) GenerateSeed(), 1000);
-}
-
-} // namespace gpu2d
-} // namespace o3d
-
diff --git a/o3d/core/cross/gpu2d/local_triangulator.cc b/o3d/core/cross/gpu2d/local_triangulator.cc
deleted file mode 100644
index 00f33d9..0000000
--- a/o3d/core/cross/gpu2d/local_triangulator.cc
+++ /dev/null
@@ -1,302 +0,0 @@
-/*
- * Copyright 2010, 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 "core/cross/gpu2d/local_triangulator.h"
-
-#include <algorithm>
-
-#include "core/cross/gpu2d/cubic_math_utils.h"
-
-namespace o3d {
-namespace gpu2d {
-
-using cubic::ApproxEqual;
-using cubic::Distance;
-using cubic::LinesIntersect;
-using cubic::PointInTriangle;
-
-bool LocalTriangulator::Triangle::Contains(LocalTriangulator::Vertex* v) {
- for (int i = 0; i < 3; i++) {
- if (v_[i] == v)
- return true;
- }
- return false;
-}
-
-LocalTriangulator::Vertex* LocalTriangulator::Triangle::NextVertex(
- LocalTriangulator::Vertex* cur,
- bool ccw) {
- int idx = IndexForVertex(cur);
- DCHECK(idx >= 0);
- if (ccw) {
- ++idx;
- } else {
- --idx;
- }
- if (idx < 0) {
- idx += 3;
- } else {
- idx = idx % 3;
- }
- return v_[idx];
-}
-
-int LocalTriangulator::Triangle::IndexForVertex(
- LocalTriangulator::Vertex* vertex) {
- for (int i = 0; i < 3; i++) {
- if (v_[i] == vertex)
- return i;
- }
- return -1;
-}
-
-void LocalTriangulator::Triangle::MakeCCW() {
- // Possibly swaps two vertices so that the triangle's vertices are
- // always specified in counterclockwise order. This orders the
- // vertices canonically when walking the interior edges from the
- // start to the end vertex.
- Vector3 vec0(v_[0]->x(), v_[0]->y(), 0.0f);
- Vector3 vec1(v_[1]->x(), v_[1]->y(), 0.0f);
- Vector3 vec2(v_[2]->x(), v_[2]->y(), 0.0f);
- Vector3 diff1 = vec1 - vec0;
- Vector3 diff2 = vec2 - vec0;
- Vector3 cp = cross(diff1, diff2);
- if (cp.getZ() < 0.0f) {
- std::swap(v_[1], v_[2]);
- }
-}
-
-LocalTriangulator::LocalTriangulator() {
- Reset();
-}
-
-void LocalTriangulator::Reset() {
- num_triangles_ = 0;
- num_interior_vertices_ = 0;
- for (int i = 0; i < 4; i++) {
- interior_vertices_[i] = NULL;
- vertices_[i].ResetFlags();
- }
-}
-
-void LocalTriangulator::Triangulate(bool compute_interior_vertices,
- bool fill_right_side) {
- Reset();
-
- bool done = false;
-
- vertices_[3].set_end(true);
-
- // First test for degenerate cases.
- for (int i = 0; i < 4 && !done; i++) {
- for (int j = i + 1; j < 4 && !done; j++) {
- if (ApproxEqual(vertices_[i].x(), vertices_[i].y(),
- vertices_[j].x(), vertices_[j].y())) {
- // Two of the vertices are coincident, so we can eliminate at
- // least one triangle. We might be able to eliminate the other
- // as well, but this seems sufficient to avoid degenerate
- // triangulations.
- int indices[3] = { 0 };
- int index = 0;
- for (int k = 0; k < 4; k++) {
- if (k != j)
- indices[index++] = k;
- }
- AddTriangle(&vertices_[indices[0]],
- &vertices_[indices[1]],
- &vertices_[indices[2]]);
- done = true;
- }
- }
- }
-
- if (!done) {
- // See whether any of the points are fully contained in the
- // triangle defined by the other three.
- for (int i = 0; i < 4 && !done; i++) {
- int indices[3] = { 0 };
- int index = 0;
- for (int j = 0; j < 4; j++) {
- if (i != j)
- indices[index++] = j;
- }
- if (PointInTriangle(
- vertices_[i].x(), vertices_[i].y(),
- vertices_[indices[0]].x(), vertices_[indices[0]].y(),
- vertices_[indices[1]].x(), vertices_[indices[1]].y(),
- vertices_[indices[2]].x(), vertices_[indices[2]].y())) {
- // Produce three triangles surrounding this interior vertex.
- for (int j = 0; j < 3; j++) {
- AddTriangle(&vertices_[indices[j % 3]],
- &vertices_[indices[(j + 1) % 3]],
- &vertices_[i]);
- }
- // Mark the interior vertex so we ignore it if trying to trace
- // the interior edge.
- vertices_[i].set_interior(true);
- done = true;
- }
- }
- }
-
- if (!done) {
- // There are only a few permutations of the vertices, ignoring
- // rotations, which are irrelevant:
- //
- // 0--3 0--2 0--3 0--1 0--2 0--1
- // | | | | | | | | | | | |
- // | | | | | | | | | | | |
- // 1--2 1--3 2--1 2--3 3--1 3--2
- //
- // Note that three of these are reflections of each other.
- // Therefore there are only three possible triangulations:
- //
- // 0--3 0--2 0--3
- // |\ | |\ | |\ |
- // | \| | \| | \|
- // 1--2 1--3 2--1
- //
- // From which we can choose by seeing which of the potential
- // diagonals intersect. Note that we choose the shortest diagonal
- // to split the quad.
- if (LinesIntersect(vertices_[0].x(), vertices_[0].y(),
- vertices_[2].x(), vertices_[2].y(),
- vertices_[1].x(), vertices_[1].y(),
- vertices_[3].x(), vertices_[3].y())) {
- if (Distance(vertices_[0].x(), vertices_[0].y(),
- vertices_[2].x(), vertices_[2].y()) <
- Distance(vertices_[1].x(), vertices_[1].y(),
- vertices_[3].x(), vertices_[3].y())) {
- AddTriangle(&vertices_[0], &vertices_[1], &vertices_[2]);
- AddTriangle(&vertices_[0], &vertices_[2], &vertices_[3]);
- } else {
- AddTriangle(&vertices_[0], &vertices_[1], &vertices_[3]);
- AddTriangle(&vertices_[1], &vertices_[2], &vertices_[3]);
- }
- } else if (LinesIntersect(
- vertices_[0].x(), vertices_[0].y(),
- vertices_[3].x(), vertices_[3].y(),
- vertices_[1].x(), vertices_[1].y(),
- vertices_[2].x(), vertices_[2].y())) {
- if (Distance(vertices_[0].x(), vertices_[0].y(),
- vertices_[3].x(), vertices_[3].y()) <
- Distance(vertices_[1].x(), vertices_[1].y(),
- vertices_[2].x(), vertices_[2].y())) {
- AddTriangle(&vertices_[0], &vertices_[1], &vertices_[3]);
- AddTriangle(&vertices_[0], &vertices_[3], &vertices_[2]);
- } else {
- AddTriangle(&vertices_[0], &vertices_[1], &vertices_[2]);
- AddTriangle(&vertices_[2], &vertices_[1], &vertices_[3]);
- }
- } else {
- // Lines (0->1), (2->3) intersect -- or should, modulo numerical
- // precision issues
- if (Distance(vertices_[0].x(), vertices_[0].y(),
- vertices_[1].x(), vertices_[1].y()) <
- Distance(vertices_[2].x(), vertices_[2].y(),
- vertices_[3].x(), vertices_[3].y())) {
- AddTriangle(&vertices_[0], &vertices_[2], &vertices_[1]);
- AddTriangle(&vertices_[0], &vertices_[1], &vertices_[3]);
- } else {
- AddTriangle(&vertices_[0], &vertices_[2], &vertices_[3]);
- AddTriangle(&vertices_[3], &vertices_[2], &vertices_[1]);
- }
- }
- }
-
- if (compute_interior_vertices) {
- // We need to compute which vertices describe the path along the
- // interior portion of the shape, to feed these vertices to the
- // more general tessellation algorithm. It is possible that we
- // could determine this directly while producing triangles above.
- // Here we try to do it generally just by examining the triangles
- // that have already been produced. We walk around them in a
- // specific direction determined by which side of the curve is
- // being filled. We ignore the interior vertex unless it is also
- // the ending vertex, and skip the edges shared between two
- // triangles.
- Vertex* v = &vertices_[0];
- AddInteriorVertex(v);
- int num_steps = 0;
- while (!v->end() && num_steps < 4) {
- // Find the next vertex according to the above rules
- bool got_next = false;
- for (int i = 0; i < num_triangles() && !got_next; i++) {
- Triangle* tri = get_triangle(i);
- if (tri->Contains(v)) {
- Vertex* next = tri->NextVertex(v, fill_right_side);
- if (!next->marked() &&
- !IsSharedEdge(v, next) &&
- (!next->interior() || next->end())) {
- AddInteriorVertex(next);
- v = next;
- // Break out of for loop
- got_next = true;
- }
- }
- }
- ++num_steps;
- }
- if (!v->end()) {
- // Something went wrong with the above algorithm; add the last
- // vertex to the interior vertices anyway.
- AddInteriorVertex(&vertices_[3]);
- }
- }
-}
-
-void LocalTriangulator::AddTriangle(Vertex* v0, Vertex* v1, Vertex* v2) {
- DCHECK(num_triangles_ < 3);
- triangles_[num_triangles_++].SetVertices(v0, v1, v2);
-}
-
-void LocalTriangulator::AddInteriorVertex(Vertex* v) {
- DCHECK(num_interior_vertices_ < 4);
- interior_vertices_[num_interior_vertices_++] = v;
- v->set_marked(true);
-}
-
-bool LocalTriangulator::IsSharedEdge(Vertex* v0, Vertex* v1) {
- bool haveEdge01 = false;
- bool haveEdge10 = false;
- for (int i = 0; i < num_triangles(); i++) {
- Triangle* tri = get_triangle(i);
- if (tri->Contains(v0) && tri->NextVertex(v0, true) == v1)
- haveEdge01 = true;
- if (tri->Contains(v1) && tri->NextVertex(v1, true) == v0)
- haveEdge10 = true;
- }
- return haveEdge01 && haveEdge10;
-}
-
-} // namespace gpu2d
-} // namespace o3d
-
diff --git a/o3d/core/cross/gpu2d/local_triangulator.h b/o3d/core/cross/gpu2d/local_triangulator.h
deleted file mode 100644
index f268515..0000000
--- a/o3d/core/cross/gpu2d/local_triangulator.h
+++ /dev/null
@@ -1,255 +0,0 @@
-/*
- * Copyright 2010, 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_CORE_CROSS_GPU2D_LOCAL_TRIANGULATOR_H_
-#define O3D_CORE_CROSS_GPU2D_LOCAL_TRIANGULATOR_H_
-
-#include "base/basictypes.h"
-#include "base/logging.h"
-
-namespace o3d {
-namespace gpu2d {
-
-// Performs a localized triangulation of the triangle mesh
-// corresponding to the four control point vertices of a cubic curve
-// segment.
-class LocalTriangulator {
- public:
- // The vertices that the triangulator operates upon, containing both
- // the position information as well as the cubic texture
- // coordinates.
- class Vertex {
- public:
- Vertex() {
- }
-
- float x() { return x_; }
- float y() { return y_; }
-
- float k() { return k_; }
- float l() { return l_; }
- float m() { return m_; }
-
- // Sets the position and texture coordinates of the vertex.
- void Set(float x, float y,
- float k, float l, float m) {
- x_ = x;
- y_ = y;
- k_ = k;
- l_ = l;
- m_ = m;
- }
-
- // Flags for walking from the start vertex to the end vertex.
- bool end() {
- return end_;
- }
-
- void set_end(bool end) {
- end_ = end;
- }
-
- bool marked() {
- return marked_;
- }
-
- void set_marked(bool marked) {
- marked_ = marked;
- }
-
- bool interior() {
- return interior_;
- }
-
- void set_interior(bool interior) {
- interior_ = interior;
- }
-
- void ResetFlags() {
- end_ = false;
- marked_ = false;
- interior_ = false;
- }
-
- private:
- // 2D coordinates of the vertex in the plane.
- float x_;
- float y_;
- // Cubic texture coordinates for rendering the curve.
- float k_, l_, m_;
-
- // Flags for walking from the start vertex to the end vertex.
- bool end_;
- bool marked_;
- bool interior_;
- DISALLOW_COPY_AND_ASSIGN(Vertex);
- };
-
- // The triangles the Triangulator produces.
- class Triangle {
- public:
- Triangle() {
- v_[0] = NULL;
- v_[1] = NULL;
- v_[2] = NULL;
- }
-
- // Gets the vertex at the given index, 0 <= index < 3.
- Vertex* get_vertex(int index) {
- DCHECK(index >= 0 && index < 3);
- return v_[index];
- }
-
- // Returns true if this triangle contains the given vertex (by
- // identity, not geometrically).
- bool Contains(Vertex* v);
-
- // Returns the vertex following the current one in the specified
- // direction, counterclockwise or clockwise.
- Vertex* NextVertex(Vertex* cur, bool ccw);
-
- // Sets the vertices of this triangle, potentially reordering them
- // to produce a canonical orientation.
- void SetVertices(Vertex* v0,
- Vertex* v1,
- Vertex* v2) {
- v_[0] = v0;
- v_[1] = v1;
- v_[2] = v2;
- MakeCCW();
- }
-
- private:
- // Returns the index [0..2] associated with the given vertex, or
- // -1 if not found.
- int IndexForVertex(Vertex* vertex);
-
- // Reorders the vertices in this triangle to make them
- // counterclockwise when viewed in the 2D plane, in order to
- // achieve a canonical ordering.
- void MakeCCW();
-
- Vertex* v_[3];
-
- DISALLOW_COPY_AND_ASSIGN(Triangle);
- };
-
- LocalTriangulator();
-
- // Resets the triangulator's state. After each triangulation and
- // before the next, call this to re-initialize the internal
- // vertices' state.
- void Reset();
-
- // Returns a mutable vertex stored in the triangulator. Use this to
- // set up the vertices before a triangulation.
- Vertex* get_vertex(int index) {
- DCHECK(index >= 0 && index < 4);
- return &vertices_[index];
- }
-
- // Once the vertices' contents have been set up, call Triangulate()
- // to recompute the triangles.
- //
- // If compute_inside_edges is true, then fill_right_side will be
- // used to determine which side of the cubic curve defined by the
- // four control points is to be filled.
- //
- // The triangulation obeys the following guarantees:
- // - If the convex hull is a quadrilateral, then the shortest edge
- // will be chosen for the cut into two triangles.
- // - If one of the vertices is contained in the triangle spanned
- // by the other three, three triangles will be produced.
- void Triangulate(bool compute_inside_edges,
- bool fill_right_side);
-
- // Number of triangles computed by Triangulate().
- int num_triangles() const {
- return num_triangles_;
- }
-
- // Returns the computed triangle at index, 0 <= index <
- // num_triangles().
- Triangle* get_triangle(int index) {
- DCHECK(index >= 0 && index < num_triangles_);
- return &triangles_[index];
- }
-
- // Number of vertices facing the inside of the shape, if
- // compute_inside_edges was true when Triangulate() was called.
- int num_interior_vertices() const {
- return num_interior_vertices_;
- }
-
- // Fetches the given interior vertex, 0 <= index <
- // num_interior_vertices(). Returns NULL if index is out of range.
- Vertex* get_interior_vertex(int index) {
- DCHECK(index >= 0 && index < num_interior_vertices_);
- return interior_vertices_[index];
- }
-
- private:
- // Adds a triangle to the triangulation.
- void AddTriangle(Vertex* v0, Vertex* v1, Vertex* v2);
-
- // Adds a vertex to the list of interior vertices.
- void AddInteriorVertex(Vertex* v);
-
- // Indicates whether the edge between vertex v0 and v1 is shared
- // between two or more triangles.
- bool IsSharedEdge(Vertex* v0, Vertex* v1);
-
- // The vertices being triangulated.
- Vertex vertices_[4];
-
- // The vertices corresponding to the edges facing the inside of the
- // shape, in order from the start vertex to the end vertex. The more
- // general triangulation algorithm tessellates this interior region.
- Vertex* interior_vertices_[4];
- // The number of interior vertices that are valid for the current
- // triangulation.
- int num_interior_vertices_;
-
- // There can be at most three triangles computed by this local
- // algorithm, which occurs when one of the vertices is contained in
- // the triangle spanned by the other three. Most of the time the
- // algorithm computes two triangles.
- Triangle triangles_[3];
- int num_triangles_;
-
- DISALLOW_COPY_AND_ASSIGN(LocalTriangulator);
-};
-
-} // namespace gpu2d
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GPU2D_LOCAL_TRIANGULATOR_H_
-
diff --git a/o3d/core/cross/gpu2d/local_triangulator_test.cc b/o3d/core/cross/gpu2d/local_triangulator_test.cc
deleted file mode 100644
index 4ceba99..0000000
--- a/o3d/core/cross/gpu2d/local_triangulator_test.cc
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright 2010, 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 local triangulator.
-
-#include "core/cross/gpu2d/cubic_math_utils.h"
-#include "core/cross/gpu2d/local_triangulator.h"
-#include "gtest/gtest.h"
-
-namespace o3d {
-namespace gpu2d {
-
-using cubic::ApproxEqual;
-
-namespace {
-
-// Sets up control point vertices for (approximately) a serpentine
-// curve.
-void SetupSerpentineVertices(LocalTriangulator* triangulator) {
- triangulator->get_vertex(0)->Set(0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
- triangulator->get_vertex(1)->Set(75.0f, 25.0f, 0.0f, 0.0f, 0.0f);
- triangulator->get_vertex(2)->Set(25.0f, 75.0f, 0.0f, 0.0f, 0.0f);
- triangulator->get_vertex(3)->Set(100.0f, 100.0f, 0.0f, 0.0f, 0.0f);
-}
-
-} // anonymous namespace
-
-TEST(LocalTriangulatorTest, TestShortestEdgeGuarantee) {
- LocalTriangulator triangulator;
- SetupSerpentineVertices(&triangulator);
- triangulator.Triangulate(false, false);
- EXPECT_EQ(triangulator.num_triangles(), 2);
- // It would be an error if the edge from (0, 0) to (100, 100) was
- // contained in either of the two triangles.
- for (int i = 0; i < triangulator.num_triangles(); i++) {
- LocalTriangulator::Triangle* triangle = triangulator.get_triangle(i);
- bool has_0_0 = false;
- bool has_100_100 = false;
- for (int j = 0; j < 3; j++) {
- LocalTriangulator::Vertex* vertex = triangle->get_vertex(j);
- if (ApproxEqual(vertex->x(), 0) && ApproxEqual(vertex->y(), 0)) {
- has_0_0 = true;
- }
- if (ApproxEqual(vertex->x(), 100) && ApproxEqual(vertex->y(), 100)) {
- has_100_100 = true;
- }
- }
- EXPECT_FALSE(has_0_0 && has_100_100);
- }
-}
-
-TEST(LocalTriangulatorTest, TestInteriorVertexGuarantee) {
- LocalTriangulator triangulator;
- triangulator.get_vertex(0)->Set(0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
- triangulator.get_vertex(1)->Set(100.0f, 0.0f, 0.0f, 0.0f, 0.0f);
- triangulator.get_vertex(2)->Set(50.0f, 50.0f, 0.0f, 0.0f, 0.0f);
- triangulator.get_vertex(3)->Set(50.0f, 100.0f, 0.0f, 0.0f, 0.0f);
- triangulator.Triangulate(false, false);
- EXPECT_EQ(triangulator.num_triangles(), 3);
-}
-
-TEST(LocalTriangulatorTest, TestInteriorVertexComputationFillingRightSide) {
- LocalTriangulator triangulator;
- SetupSerpentineVertices(&triangulator);
- triangulator.Triangulate(true, true);
- EXPECT_EQ(triangulator.num_triangles(), 2);
- // In this configuration, vertex (75, 25) should be among the
- // interior vertices, and vertex (25, 75) should not.
- bool found_correct_interior_vertex = false;
- for (int i = 0; i < triangulator.num_interior_vertices(); i++) {
- LocalTriangulator::Vertex* vertex = triangulator.get_interior_vertex(i);
- if (ApproxEqual(vertex->x(), 75) && ApproxEqual(vertex->y(), 25)) {
- found_correct_interior_vertex = true;
- }
- }
- EXPECT_TRUE(found_correct_interior_vertex);
- for (int i = 0; i < triangulator.num_interior_vertices(); i++) {
- LocalTriangulator::Vertex* vertex = triangulator.get_interior_vertex(i);
- EXPECT_FALSE(ApproxEqual(vertex->x(), 25) && ApproxEqual(vertex->y(), 75));
- }
-}
-
-TEST(LocalTriangulatorTest, TestInteriorVertexComputationFillingLeftSide) {
- LocalTriangulator triangulator;
- SetupSerpentineVertices(&triangulator);
- triangulator.Triangulate(true, false);
- EXPECT_EQ(triangulator.num_triangles(), 2);
- // In this configuration, vertex (25, 75) should be among the
- // interior vertices, and vertex (75, 25) should not.
- bool found_correct_interior_vertex = false;
- for (int i = 0; i < triangulator.num_interior_vertices(); i++) {
- LocalTriangulator::Vertex* vertex = triangulator.get_interior_vertex(i);
- if (ApproxEqual(vertex->x(), 25) && ApproxEqual(vertex->y(), 75)) {
- found_correct_interior_vertex = true;
- }
- }
- EXPECT_TRUE(found_correct_interior_vertex);
- for (int i = 0; i < triangulator.num_interior_vertices(); i++) {
- LocalTriangulator::Vertex* vertex = triangulator.get_interior_vertex(i);
- EXPECT_FALSE(ApproxEqual(vertex->x(), 75) && ApproxEqual(vertex->y(), 25));
- }
-}
-
-} // namespace gpu2d
-} // namespace o3d
-
diff --git a/o3d/core/cross/gpu2d/path_cache.cc b/o3d/core/cross/gpu2d/path_cache.cc
deleted file mode 100644
index 9dec156..0000000
--- a/o3d/core/cross/gpu2d/path_cache.cc
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright 2010, 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 "core/cross/gpu2d/path_cache.h"
-
-namespace o3d {
-namespace gpu2d {
-
-unsigned int PathCache::num_vertices() const {
- return vertices_.size() / 2;
-}
-
-const float* PathCache::vertices() const {
- if (num_vertices() == 0)
- return NULL;
- return &vertices_.front();
-}
-
-const float* PathCache::texcoords() const {
- if (num_vertices() == 0)
- return NULL;
- return &texcoords_.front();
-}
-
-void PathCache::AddVertex(float x, float y,
- float k, float l, float m) {
- vertices_.push_back(x);
- vertices_.push_back(y);
- texcoords_.push_back(k);
- texcoords_.push_back(l);
- texcoords_.push_back(m);
-}
-
-void PathCache::Clear() {
- vertices_.clear();
- texcoords_.clear();
- interior_vertices_.clear();
-#ifdef O3D_CORE_CROSS_GPU2D_PATH_CACHE_DEBUG_INTERIOR_EDGES
- interior_edge_vertices_.clear();
-#endif // O3D_CORE_CROSS_GPU2D_PATH_CACHE_DEBUG_INTERIOR_EDGES
-}
-
-unsigned int PathCache::num_interior_vertices() const {
- return interior_vertices_.size() / 2;
-}
-
-const float* PathCache::interior_vertices() const {
- if (num_interior_vertices() == 0)
- return NULL;
- return &interior_vertices_.front();
-}
-
-void PathCache::AddInteriorVertex(float x, float y) {
- interior_vertices_.push_back(x);
- interior_vertices_.push_back(y);
-}
-
-#ifdef O3D_CORE_CROSS_GPU2D_PATH_CACHE_DEBUG_INTERIOR_EDGES
-unsigned int PathCache::num_interior_edge_vertices() const {
- return interior_edge_vertices_.size() / 2;
-}
-
-const float* PathCache::interior_edge_vertices() const {
- if (num_interior_edge_vertices() == 0)
- return NULL;
- return &interior_edge_vertices_.front();
-}
-
-void PathCache::AddInteriorEdgeVertex(float x, float y) {
- interior_edge_vertices_.push_back(x);
- interior_edge_vertices_.push_back(y);
-}
-#endif // O3D_CORE_CROSS_GPU2D_PATH_CACHE_DEBUG_INTERIOR_EDGES
-
-} // namespace gpu2d
-} // namespace o3d
-
diff --git a/o3d/core/cross/gpu2d/path_cache.h b/o3d/core/cross/gpu2d/path_cache.h
deleted file mode 100644
index 93ba86c0..0000000
--- a/o3d/core/cross/gpu2d/path_cache.h
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright 2010, 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_CORE_CROSS_GPU2D_PATH_CACHE_H_
-#define O3D_CORE_CROSS_GPU2D_PATH_CACHE_H_
-
-#include <vector>
-
-#include "base/basictypes.h"
-
-namespace o3d {
-namespace gpu2d {
-
-// A cache of the processed triangle mesh for a given path. Because
-// these might be expensive to allocate (using malloc/free
-// internally), it is recommended to try to reuse them when possible.
-
-// Uncomment the following to obtain debugging information for the edges facing
-// the interior region of the mesh.
-// #define O3D_CORE_CROSS_GPU2D_PATH_CACHE_DEBUG_INTERIOR_EDGES
-
-class PathCache {
- public:
- PathCache() {
- }
-
- // The number of vertices in the mesh.
- unsigned int num_vertices() const;
-
- // Get the base pointer to the vertex information. There are two
- // coordinates per vertex. This pointer is valid until the cache is
- // cleared or another vertex is added. Returns NULL if there are no
- // vertices in the mesh.
- const float* vertices() const;
-
- // Get the base pointer to the texture coordinate information. There
- // are three coordinates per vertex. This pointer is valid until the
- // cache is cleared or another vertex is added. Returns NULL if
- // there are no vertices in the mesh.
- const float* texcoords() const;
-
- // Adds a vertex's information to the cache. The first two arguments
- // are the x and y coordinates of the vertex on the plane; the last
- // three arguments are the cubic texture coordinates associated with
- // this vertex.
- void AddVertex(float x, float y,
- float k, float l, float m);
-
- // The number of interior vertices.
- unsigned int num_interior_vertices() const;
- // Base pointer to the interior vertices; two coordinates per
- // vertex, which can be drawn as GL_TRIANGLES. Returns NULL if there
- // are no interior vertices in the mesh.
- const float* interior_vertices() const;
- // Adds an interior vertex to the cache.
- void AddInteriorVertex(float x, float y);
-
- // Clears all of the stored vertex information in this cache.
- void Clear();
-
-#ifdef O3D_CORE_CROSS_GPU2D_PATH_CACHE_DEBUG_INTERIOR_EDGES
- // The number of interior edge vertices
- unsigned int num_interior_edge_vertices() const;
- // Base pointer to the interior vertices; two coordinates per
- // vertex, which can be drawn as GL_LINES. Returns NULL if there are
- // no interior edge vertices in the mesh.
- const float* interior_edge_vertices() const;
- void AddInteriorEdgeVertex(float x, float y);
-#endif // O3D_CORE_CROSS_GPU2D_PATH_CACHE_DEBUG_INTERIOR_EDGES
-
- private:
- // The two-dimensional vertices of the triangle mesh.
- std::vector<float> vertices_;
-
- // The three-dimensional cubic texture coordinates.
- std::vector<float> texcoords_;
-
- std::vector<float> interior_vertices_;
-
-#ifdef O3D_CORE_CROSS_GPU2D_PATH_CACHE_DEBUG_INTERIOR_EDGES
- // The following is only for debugging
- std::vector<float> interior_edge_vertices_;
-#endif // O3D_CORE_CROSS_GPU2D_PATH_CACHE_DEBUG_INTERIOR_EDGES
-
- DISALLOW_COPY_AND_ASSIGN(PathCache);
-};
-
-} // namespace gpu2d
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GPU2D_PATH_CACHE_H_
-
diff --git a/o3d/core/cross/gpu2d/path_processor.cc b/o3d/core/cross/gpu2d/path_processor.cc
deleted file mode 100644
index 6e50e9e..0000000
--- a/o3d/core/cross/gpu2d/path_processor.cc
+++ /dev/null
@@ -1,1370 +0,0 @@
-/*
- * Copyright 2010, 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 "core/cross/gpu2d/path_processor.h"
-
-#include <algorithm>
-
-#include "base/logging.h"
-#include "core/cross/gpu2d/arena.h"
-#include "core/cross/gpu2d/cubic_classifier.h"
-#include "core/cross/gpu2d/cubic_math_utils.h"
-#include "core/cross/gpu2d/cubic_texture_coords.h"
-#include "core/cross/gpu2d/interval_tree.h"
-#include "core/cross/gpu2d/local_triangulator.h"
-#include "core/cross/gpu2d/path_cache.h"
-#include "third_party/skia/include/core/SkGeometry.h"
-#include "third_party/skia/include/core/SkPath.h"
-#include "third_party/skia/include/core/SkScalar.h"
-#include "third_party/glu/internal_glu.h"
-
-namespace o3d {
-namespace gpu2d {
-
-class Contour;
-
-//----------------------------------------------------------------------
-// min / max helpers
-//
-
-template <typename T>
-T min2(const T& v1, const T& v2) {
- return std::min(v1, v2);
-}
-
-template <typename T>
-T max2(const T& v1, const T& v2) {
- return std::max(v1, v2);
-}
-
-template <typename T>
-T min3(const T& v1, const T& v2, const T& v3) {
- return min2(min2(v1, v2), v3);
-}
-
-template <typename T>
-T max3(const T& v1, const T& v2, const T& v3) {
- return max2(max2(v1, v2), v3);
-}
-
-template <typename T>
-T min4(const T& v1, const T& v2, const T& v3, const T& v4) {
- return min2(min2(v1, v2), min2(v3, v4));
-}
-
-template <typename T>
-T max4(const T& v1, const T& v2, const T& v3, const T& v4) {
- return max2(max2(v1, v2), max2(v3, v4));
-}
-
-//----------------------------------------------------------------------
-// BBox
-//
-
-// Extremely simple bounding box class for Segments and Contours.
-class BBox {
- public:
- BBox()
- : min_x_(0),
- min_y_(0),
- max_x_(0),
- max_y_(0) {
- }
-
- // Initializes the parameters of the bounding box.
- void Setup(float min_x,
- float min_y,
- float max_x,
- float max_y) {
- min_x_ = min_x;
- min_y_ = min_y;
- max_x_ = max_x;
- max_y_ = max_y;
- }
-
- // Initializes the bounding box to surround the given triangle.
- void Setup(LocalTriangulator::Triangle* triangle) {
- Setup(min3(triangle->get_vertex(0)->x(),
- triangle->get_vertex(1)->x(),
- triangle->get_vertex(2)->x()),
- min3(triangle->get_vertex(0)->y(),
- triangle->get_vertex(1)->y(),
- triangle->get_vertex(2)->y()),
- max3(triangle->get_vertex(0)->x(),
- triangle->get_vertex(1)->x(),
- triangle->get_vertex(2)->x()),
- max3(triangle->get_vertex(0)->y(),
- triangle->get_vertex(1)->y(),
- triangle->get_vertex(2)->y()));
- }
-
- // Initializes this bounding box to the contents of the other.
- void Setup(const BBox& bbox) {
- min_x_ = bbox.min_x();
- min_y_ = bbox.min_y();
- max_x_ = bbox.max_x();
- max_y_ = bbox.max_y();
- }
-
- // Extends this bounding box to surround itself and the other.
- void Extend(const BBox& other) {
- Setup(min2(min_x(), other.min_x()),
- min2(min_y(), other.min_y()),
- max2(max_x(), other.max_x()),
- max2(max_y(), other.max_y()));
- }
-
- float min_x() const { return min_x_; }
- float min_y() const { return min_y_; }
- float max_x() const { return max_x_; }
- float max_y() const { return max_y_; }
-
- private:
- float min_x_;
- float min_y_;
- float max_x_;
- float max_y_;
- DISALLOW_COPY_AND_ASSIGN(BBox);
-};
-
-// Suppport for logging BBoxes.
-std::ostream& operator<<(std::ostream& ostr, // NOLINT
- const BBox& arg) {
- ostr << "[BBox min_x=" << arg.min_x()
- << " min_y=" << arg.min_y()
- << " max_x=" << arg.max_x()
- << " max_y=" << arg.max_y()
- << "]";
- return ostr;
-}
-
-//----------------------------------------------------------------------
-// Segment
-//
-
-// Describes a segment of the path: either a cubic or a line segment.
-// These are stored in a doubly linked list to speed up curve
-// subdivision, which occurs due to either rendering artifacts in the
-// loop case or due to overlapping triangles.
-class Segment {
- public:
- // The kind of segment: cubic or line.
- enum Kind {
- kCubic,
- kLine
- };
-
- // No-argument constructor allows construction by the Arena class.
- Segment()
- : arena_(NULL),
- kind_(kCubic),
- prev_(NULL),
- next_(NULL),
- contour_(NULL),
- triangulator_(NULL),
- marked_for_subdivision_(false) {
- }
-
- // Initializer for cubic curve segments.
- void Setup(Arena* arena,
- Contour* contour,
- SkPoint cp0,
- SkPoint cp1,
- SkPoint cp2,
- SkPoint cp3) {
- arena_ = arena;
- contour_ = contour;
- kind_ = kCubic;
- points_[0] = cp0;
- points_[1] = cp1;
- points_[2] = cp2;
- points_[3] = cp3;
- ComputeBoundingBox();
- }
-
- // Initializer for line segments.
- void Setup(Arena* arena,
- Contour* contour,
- SkPoint p0,
- SkPoint p1) {
- arena_ = arena;
- contour_ = contour;
- kind_ = kLine;
- points_[0] = p0;
- points_[1] = p1;
- ComputeBoundingBox();
- }
-
- // Returns the kind of segment.
- Kind kind() const {
- return kind_;
- }
-
- // Returns the i'th control point, 0 <= i < 4.
- const SkPoint& get_point(int i) {
- DCHECK(i >= 0 && i < 4);
- return points_[i];
- }
-
- // Returns the next segment in the contour.
- Segment* next() const { return next_; }
-
- // Returns the previous segment in the contour.
- Segment* prev() const { return prev_; }
-
- // Sets the next segment in the contour.
- void set_next(Segment* next) { next_ = next; }
-
- // Sets the previous segment in the contour.
- void set_prev(Segment* prev) { prev_ = prev; }
-
- // The contour this segment belongs to.
- Contour* contour() const { return contour_; }
-
- // Subdivides the current segment at the given parameter value (0 <=
- // t <= 1) and replaces it with the two newly created Segments in
- // the linked list, if possible. Returns a pointer to the leftmost
- // Segment.
- Segment* Subdivide(float param) {
- SkPoint dst[7];
- SkChopCubicAt(points_, dst, param);
- Segment* left = arena_->Alloc<Segment>();
- Segment* right = arena_->Alloc<Segment>();
- left->Setup(arena_, contour_, dst[0], dst[1], dst[2], dst[3]);
- right->Setup(arena_, contour_, dst[3], dst[4], dst[5], dst[6]);
- left->set_next(right);
- right->set_prev(left);
- // Try to set up a link between "this->prev()" and "left".
- if (prev() != NULL) {
- left->set_prev(prev());
- prev()->set_next(left);
- }
- // Try to set up a link between "this->next()" and "right".
- Segment* n = next();
- if (n != NULL) {
- right->set_next(n);
- n->set_prev(right);
- }
- // Set up a link between "this" and "left"; this is only to
- // provide a certain amount of continuity during forward iteration.
- set_next(left);
- return left;
- }
-
- // Subdivides the current segment at the halfway point and replaces
- // it with the two newly created Segments in the linked list, if
- // possible. Returns a pointer to the leftmost Segment.
- Segment* Subdivide() {
- return Subdivide(0.5f);
- }
-
- // Returns the bounding box of this segment.
- const BBox& bbox() const {
- return bbox_;
- }
-
- // Computes the number of times a query line starting at the given
- // point and extending to x=+infinity crosses this segment. Outgoing
- // "ambiguous" argument indicates whether the query intersected an
- // endpoint or tangent point of the segment, indicating that another
- // query point is preferred.
- int NumCrossingsForXRay(SkPoint pt, bool* ambiguous) const {
- if (kind_ == kCubic) {
- // Should consider caching the monotonic cubics.
- return SkNumXRayCrossingsForCubic(pt, points_, ambiguous);
- } else {
- return SkXRayCrossesLine(pt, points_, ambiguous) ? 1 : 0;
- }
- }
-
- // Performs a local triangulation of the control points in this
- // segment. This operation only makes sense for cubic type segments.
- void Triangulate(bool compute_inside_edges,
- CubicTextureCoords::Result* tex_coords);
-
- // Returns the number of control point triangles associated with
- // this segment.
- int num_triangles() const {
- if (!triangulator_)
- return 0;
- return triangulator_->num_triangles();
- }
-
- // Fetches the given control point triangle for this segment.
- LocalTriangulator::Triangle* get_triangle(int index) {
- DCHECK(triangulator_);
- return triangulator_->get_triangle(index);
- }
-
- // Number of vertices along the inside edge of this segment. This
- // can be called either for line or cubic type segments.
- int num_interior_vertices() const {
- if (kind_ == kCubic) {
- if (triangulator_) {
- return triangulator_->num_interior_vertices();
- } else {
- return 0;
- }
- }
-
- return 2;
- }
-
- // Returns the given interior vertex, 0 <= index < num_interior_vertices().
- SkPoint get_interior_vertex(int index) const {
- DCHECK(index >= 0 && index < num_interior_vertices());
- if (kind_ == kCubic) {
- SkPoint res = { 0 };
- if (triangulator_) {
- LocalTriangulator::Vertex* vertex =
- triangulator_->get_interior_vertex(index);
- if (vertex)
- res.set(SkFloatToScalar(vertex->x()),
- SkFloatToScalar(vertex->y()));
- }
- return res;
- }
-
- return points_[index];
- }
-
- // State to assist with curve subdivision.
- bool marked_for_subdivision() {
- return marked_for_subdivision_;
- }
-
- // State to assist with curve subdivision.
- void set_marked_for_subdivision(bool marked_for_subdivision) {
- marked_for_subdivision_ = marked_for_subdivision;
- }
-
- private:
- // Computes the bounding box of this Segment.
- void ComputeBoundingBox() {
- switch (kind_) {
- case kCubic:
- bbox_.Setup(SkScalarToFloat(min4(points_[0].fX,
- points_[1].fX,
- points_[2].fX,
- points_[3].fX)),
- SkScalarToFloat(min4(points_[0].fY,
- points_[1].fY,
- points_[2].fY,
- points_[3].fY)),
- SkScalarToFloat(max4(points_[0].fX,
- points_[1].fX,
- points_[2].fX,
- points_[3].fX)),
- SkScalarToFloat(max4(points_[0].fY,
- points_[1].fY,
- points_[2].fY,
- points_[3].fY)));
- break;
-
- case kLine:
- bbox_.Setup(SkScalarToFloat(min2(points_[0].fX,
- points_[1].fX)),
- SkScalarToFloat(min2(points_[0].fY,
- points_[1].fY)),
- SkScalarToFloat(max2(points_[0].fX,
- points_[1].fX)),
- SkScalarToFloat(max2(points_[0].fY,
- points_[1].fY)));
- break;
-
- default:
- NOTREACHED();
- break;
- }
- }
-
- Arena* arena_;
- Kind kind_;
- SkPoint points_[4];
- Segment* prev_;
- Segment* next_;
- Contour* contour_;
- BBox bbox_;
- LocalTriangulator* triangulator_;
- bool marked_for_subdivision_;
-
- DISALLOW_COPY_AND_ASSIGN(Segment);
-};
-
-// Suppport for logging Segments.
-std::ostream& operator<<(std::ostream& ostr, // NOLINT
- const Segment& arg) {
- ostr << "[Segment kind=";
- if (arg.kind() == Segment::kLine) {
- ostr << "line";
- } else {
- ostr << "cubic";
- }
- ostr << " bbox=" << arg.bbox() << "]";
- return ostr;
-}
-
-//----------------------------------------------------------------------
-// Contour
-//
-
-// Describes a closed contour of the path.
-class Contour {
- public:
- Contour() {
- first_ = &sentinel_;
- first_->set_next(first_);
- first_->set_prev(first_);
- ccw_ = true;
- bbox_dirty_ = false;
- fill_right_side_ = true;
- }
-
- // Adds a segment to this contour.
- void Add(Segment* segment) {
- if (first_ == &sentinel_) {
- // First element is the sentinel. Replace it with the incoming
- // segment.
- segment->set_next(first_);
- segment->set_prev(first_);
- first_->set_next(segment);
- first_->set_prev(segment);
- first_ = segment;
- } else {
- // first_->prev() is the sentinel.
- Segment* sentinel = first_->prev();
- Segment* last = sentinel->prev();
- last->set_next(segment);
- segment->set_prev(last);
- segment->set_next(sentinel);
- sentinel->set_prev(segment);
- }
- bbox_dirty_ = true;
- }
-
- // Subdivides the given segment at the given parametric value.
- // Returns a pointer to the first of the two portions of the
- // subdivided segment.
- Segment* Subdivide(Segment* segment, float param) {
- Segment* left = segment->Subdivide(param);
- if (first_ == segment)
- first_ = left;
- return left;
- }
-
- // Subdivides the given segment at the halfway point. Returns a
- // pointer to the first of the two portions of the subdivided
- // segment.
- Segment* Subdivide(Segment* segment) {
- Segment* left = segment->Subdivide();
- if (first_ == segment)
- first_ = left;
- return left;
- }
-
- // Returns the first segment in the contour for iteration.
- Segment* begin() const {
- return first_;
- }
-
- // Returns the last segment in the contour for iteration. Callers
- // should not iterate over this segment. In other words:
- // for (Segment* cur = contour->begin();
- // cur != contour->end();
- // cur = cur->next()) {
- // // .. process cur ...
- // }
- Segment* end() const {
- return first_->prev();
- }
-
- // Returns whether this contour is oriented counterclockwise.
- bool ccw() const {
- return ccw_;
- }
-
- void set_ccw(bool ccw) {
- ccw_ = ccw;
- }
-
- // Returns the bounding box of this contour.
- const BBox& bbox() const {
- if (bbox_dirty_) {
- bool first = true;
- for (Segment* cur = begin(); cur != end(); cur = cur->next()) {
- if (first) {
- bbox_.Setup(cur->bbox());
- } else {
- bbox_.Extend(cur->bbox());
- }
- first = false;
- }
-
- bbox_dirty_ = false;
- }
- return bbox_;
- }
-
- // Returns whether the right side of this contour is filled.
- bool fill_right_side() const { return fill_right_side_; }
-
- void set_fill_right_side(bool fill_right_side) {
- fill_right_side_ = fill_right_side;
- }
-
- private:
- // The start of the segment chain. The segments are kept in a
- // circular doubly linked list for rapid access to the beginning and
- // end.
- Segment* first_;
-
- // The sentinel element at the end of the chain, needed for
- // reasonable iteration semantics.
- Segment sentinel_;
-
- // Whether this contour is oriented counterclockwise.
- bool ccw_;
-
- // This contour's bounding box.
- mutable BBox bbox_;
-
- // Whether this contour's bounding box is dirty.
- mutable bool bbox_dirty_;
-
- // Whether we should fill the right (or left) side of this contour.
- bool fill_right_side_;
-
- DISALLOW_COPY_AND_ASSIGN(Contour);
-};
-
-//----------------------------------------------------------------------
-// Segment
-//
-
-// Definition of Segment::Triangulate(), which must come after
-// declaration of Contour.
-void Segment::Triangulate(bool compute_inside_edges,
- CubicTextureCoords::Result* tex_coords) {
- DCHECK(kind_ == kCubic);
- if (triangulator_ == NULL) {
- triangulator_ = arena_->Alloc<LocalTriangulator>();
- }
- triangulator_->Reset();
- for (int i = 0; i < 4; i++) {
- LocalTriangulator::Vertex* vertex = triangulator_->get_vertex(i);
- if (tex_coords) {
- vertex->Set(get_point(i).fX,
- get_point(i).fY,
- tex_coords->coords[i].getX(),
- tex_coords->coords[i].getY(),
- tex_coords->coords[i].getZ());
- } else {
- vertex->Set(get_point(i).fX,
- get_point(i).fY,
- // No texture coordinates yet
- 0, 0, 0);
- }
- }
- triangulator_->Triangulate(compute_inside_edges,
- contour()->fill_right_side());
-}
-
-//----------------------------------------------------------------------
-// PathProcessor
-//
-
-PathProcessor::PathProcessor()
- : arena_(new Arena()),
- should_delete_arena_(true),
- verbose_logging_(false) {
-}
-
-PathProcessor::PathProcessor(Arena* arena)
- : arena_(arena),
- should_delete_arena_(false),
- verbose_logging_(false) {
-}
-
-PathProcessor::~PathProcessor() {
- if (should_delete_arena_) {
- delete arena_;
- }
-}
-
-void PathProcessor::Process(const SkPath& path, PathCache* cache) {
- BuildContours(path);
-
- // Run plane-sweep algorithm to determine overlaps of control point
- // curves and subdivide curves appropriately.
- SubdivideCurves();
-
- // Determine orientations of countours. Based on orientation and the
- // number of curve crossings at a random point on the contour,
- // determine whether to fill the left or right side of the contour.
- DetermineSidesToFill();
-
- // Classify curves, compute texture coordinates and subdivide as
- // necessary to eliminate rendering artifacts. Do the final
- // triangulation of the curve segments, determining the path along
- // the interior of the shape.
- for (std::vector<Contour*>::iterator iter = contours_.begin();
- iter != contours_.end();
- iter++) {
- Contour* cur = *iter;
- for (Segment* seg = cur->begin(); seg != cur->end(); seg = seg->next()) {
- if (seg->kind() == Segment::kCubic) {
- CubicClassifier::Result classification =
- CubicClassifier::Classify(seg->get_point(0).fX,
- seg->get_point(0).fY,
- seg->get_point(1).fX,
- seg->get_point(1).fY,
- seg->get_point(2).fX,
- seg->get_point(2).fY,
- seg->get_point(3).fX,
- seg->get_point(3).fY);
- DLOG_IF(INFO, verbose_logging_) << "Classification:"
- << classification.curve_type();
- CubicTextureCoords::Result tex_coords;
- CubicTextureCoords::Compute(classification,
- cur->fill_right_side(),
- &tex_coords);
- if (tex_coords.has_rendering_artifact) {
- // TODO(kbr): split at the subdivision parameter value
- cur->Subdivide(seg);
- // Next iteration will handle the newly subdivided halves
- } else {
- if (!tex_coords.is_line_or_point) {
- seg->Triangulate(true, &tex_coords);
- for (int i = 0; i < seg->num_triangles(); i++) {
- LocalTriangulator::Triangle* triangle =
- seg->get_triangle(i);
- for (int j = 0; j < 3; j++) {
- LocalTriangulator::Vertex* vert =
- triangle->get_vertex(j);
- cache->AddVertex(vert->x(),
- vert->y(),
- vert->k(),
- vert->l(),
- vert->m());
- }
- }
-#ifdef O3D_CORE_CROSS_GPU2D_PATH_CACHE_DEBUG_INTERIOR_EDGES
- // Show the end user the interior edges as well
- for (int i = 1; i < seg->num_interior_vertices(); i++) {
- SkPoint vert = seg->get_interior_vertex(i);
- // Duplicate previous vertex to be able to draw GL_LINES
- SkPoint prev = seg->get_interior_vertex(i - 1);
- cache->AddInteriorEdgeVertex(prev.fX, prev.fY);
- cache->AddInteriorEdgeVertex(vert.fX, vert.fY);
- }
-#endif // O3D_CORE_CROSS_GPU2D_PATH_CACHE_DEBUG_INTERIOR_EDGES
- }
- }
- }
- }
- }
-
- // Run the interior paths through a tessellation algorithm
- // supporting multiple contours.
- TessellateInterior(cache);
-}
-
-void PathProcessor::BuildContours(const SkPath& path) {
- // Clear out the contours
- contours_.clear();
- SkPath::Iter iter(path, false);
- SkPoint pts[4];
- SkPath::Verb verb;
- Contour* contour = NULL;
- SkPoint cur_pt = { 0 };
- SkPoint move_to_pt = { 0 };
- do {
- verb = iter.next(pts);
- if (verb != SkPath::kMove_Verb) {
- if (contour == NULL) {
- contour = arena_->Alloc<Contour>();
- contours_.push_back(contour);
- }
- }
- switch (verb) {
- case SkPath::kMove_Verb: {
- contour = arena_->Alloc<Contour>();
- contours_.push_back(contour);
- cur_pt = pts[0];
- move_to_pt = pts[0];
- DLOG_IF(INFO, verbose_logging_) << "MoveTo (" << pts[0].fX
- << ", " << pts[0].fY << ")";
- break;
- }
- case SkPath::kLine_Verb: {
- Segment* segment = arena_->Alloc<Segment>();
- if (iter.isCloseLine()) {
- segment->Setup(arena_, contour, cur_pt, pts[1]);
- DLOG_IF(INFO, verbose_logging_) << "CloseLineTo (" << cur_pt.fX
- << ", " << cur_pt.fY
- << "), (" << pts[1].fX
- << ", " << pts[1].fY << ")";
- contour->Add(segment);
- contour = NULL;
- } else {
- segment->Setup(arena_, contour, pts[0], pts[1]);
- DLOG_IF(INFO, verbose_logging_) << "LineTo (" << pts[0].fX
- << ", " << pts[0].fY
- << "), (" << pts[1].fX
- << ", " << pts[1].fY << ")";
- contour->Add(segment);
- cur_pt = pts[1];
- }
- break;
- }
- case SkPath::kQuad_Verb: {
- // Need to degree elevate the quadratic into a cubic
- SkPoint cubic[4];
- SkConvertQuadToCubic(pts, cubic);
- Segment* segment = arena_->Alloc<Segment>();
- segment->Setup(arena_, contour,
- cubic[0], cubic[1], cubic[2], cubic[3]);
- DLOG_IF(INFO, verbose_logging_) << "Quad->CubicTo (" << cubic[0].fX
- << ", " << cubic[0].fY
- << "), (" << cubic[1].fX
- << ", " << cubic[1].fY
- << "), (" << cubic[2].fX
- << ", " << cubic[2].fY
- << "), (" << cubic[3].fX
- << ", " << cubic[3].fY << ")";
- contour->Add(segment);
- cur_pt = cubic[3];
- break;
- }
- case SkPath::kCubic_Verb: {
- Segment* segment = arena_->Alloc<Segment>();
- segment->Setup(arena_, contour, pts[0], pts[1], pts[2], pts[3]);
- DLOG_IF(INFO, verbose_logging_) << "CubicTo (" << pts[0].fX
- << ", " << pts[0].fY
- << "), (" << pts[1].fX
- << ", " << pts[1].fY
- << "), (" << pts[2].fX
- << ", " << pts[2].fY
- << "), (" << pts[3].fX
- << ", " << pts[3].fY << ")";
- contour->Add(segment);
- cur_pt = pts[3];
- break;
- }
- case SkPath::kClose_Verb: {
- Segment* segment = arena_->Alloc<Segment>();
- segment->Setup(arena_, contour, cur_pt, move_to_pt);
- DLOG_IF(INFO, verbose_logging_) << "Close (" << cur_pt.fX
- << ", " << cur_pt.fY
- << ") -> (" << move_to_pt.fX
- << ", " << move_to_pt.fY << ")";
- contour->Add(segment);
- contour = NULL;
- }
- default:
- break;
- }
- } while (verb != SkPath::kDone_Verb);
-}
-
-std::vector<Segment*> PathProcessor::AllSegmentsOverlappingY(float y) {
- std::vector<Segment*> res;
- for (std::vector<Contour*>::iterator iter = contours_.begin();
- iter != contours_.end();
- iter++) {
- Contour* cur = *iter;
- for (Segment* seg = cur->begin(); seg != cur->end(); seg = seg->next()) {
- const BBox& bbox = seg->bbox();
- if (bbox.min_y() <= y && y <= bbox.max_y()) {
- res.push_back(seg);
- }
- }
- }
- return res;
-}
-
-// Uncomment this to debug the orientation computation
-// #define O3D_CORE_CROSS_GPU2D_PATH_PROCESSOR_DEBUG_ORIENTATION
-
-void PathProcessor::DetermineSidesToFill() {
- // Loop and Blinn's algorithm can only easily emulate the even/odd
- // fill rule, and only for non-intersecting curves. We can determine
- // which side of each curve segment to fill based on its
- // clockwise/counterclockwise orientation and how many other
- // contours surround it.
-
- // To optimize the query of all curve segments intersecting a
- // horizontal line going to x=+infinity, we build up an interval
- // tree whose keys are the y extents of the segments.
- IntervalTree<float, Segment*> tree(arena_);
- typedef IntervalTree<float, Segment*>::IntervalType IntervalType;
-
- for (std::vector<Contour*>::iterator iter = contours_.begin();
- iter != contours_.end();
- iter++) {
- Contour* cur = *iter;
- DetermineOrientation(cur);
- for (Segment* seg = cur->begin(); seg != cur->end(); seg = seg->next()) {
- const BBox& bbox = seg->bbox();
- tree.Insert(tree.MakeInterval(bbox.min_y(), bbox.max_y(), seg));
- }
- }
-
- // Now iterate through the contours and pick a random segment (in
- // this case we use the first) and a random point on that segment.
- // Find all segments from other contours which intersect this one
- // and count the number of crossings a horizontal line to
- // x=+infinity makes with those contours. This combined with the
- // orientation of the curve tells us which side to fill -- again,
- // assuming an even/odd fill rule, which is all we can easily
- // handle.
- for (std::vector<Contour*>::iterator iter = contours_.begin();
- iter != contours_.end();
- iter++) {
- Contour* cur = *iter;
-
- bool ambiguous = true;
- int num_crossings = 0;
-
- // For each contour, attempt to find a point on the contour which,
- // when we cast an XRay, does not intersect the other contours at
- // an ambiguous point (the junction between two curves or at a
- // tangent point). Ambiguous points make the determination of
- // whether this contour is contained within another fragile. Note
- // that this loop is only an approximation to the selection of a
- // good casting point. We could as well evaluate a segment to
- // determine a point upon it.
- for (Segment* seg = cur->begin();
- ambiguous && seg != cur->end();
- seg = seg->next()) {
- num_crossings = 0;
- // We use a zero-sized vertical interval for the query.
- std::vector<IntervalType> overlaps =
- tree.AllOverlaps(IntervalType(SkScalarToFloat(seg->get_point(0).fY),
- SkScalarToFloat(seg->get_point(0).fY),
- NULL));
-#if !defined(O3D_CORE_CROSS_GPU2D_PATH_PROCESSOR_DEBUG_ORIENTATION)
- for (std::vector<IntervalType>::iterator iter = overlaps.begin();
- iter != overlaps.end();
- iter++) {
- const IntervalType& interval = *iter;
- Segment* query_seg = interval.data();
- // Ignore segments coming from the same contour.
- if (query_seg->contour() != cur) {
- // Only perform queries that can affect the computation.
- const BBox& bbox = query_seg->contour()->bbox();
- if (seg->get_point(0).fX >= bbox.min_x() &&
- seg->get_point(0).fX <= bbox.max_x()) {
- num_crossings += query_seg->NumCrossingsForXRay(seg->get_point(0),
- &ambiguous);
- if (ambiguous) {
- DLOG(INFO) << "Ambiguous intersection query at point ("
- << seg->get_point(0).fX << ", "
- << seg->get_point(0).fY << ")";
- DLOG(INFO) << "Query segment: " << *query_seg;
- break; // Abort iteration over overlaps.
- }
- }
- }
- }
-#endif // !defined(O3D_CORE_CROSS_GPU2D_PATH_PROCESSOR_DEBUG_ORIENTATION)
-
-#ifdef O3D_CORE_CROSS_GPU2D_PATH_PROCESSOR_DEBUG_ORIENTATION
- // For debugging
- std::vector<Segment*> slow_overlaps =
- AllSegmentsOverlappingY(seg->get_point(0).fY);
- if (overlaps.size() != slow_overlaps.size()) {
- DLOG(ERROR) << "for query point " << seg->get_point(0).fY << ":";
- DLOG(ERROR) << " overlaps:";
- for (size_t i = 0; i < overlaps.size(); i++) {
- DLOG(ERROR) << " " << (i+1) << ": " << *overlaps[i].data();
- }
- DLOG(ERROR) << " slow_overlaps:";
- for (size_t i = 0; i < slow_overlaps.size(); i++) {
- DLOG(ERROR) << " " << (i+1) << ": " << *slow_overlaps[i];
- }
- }
- DCHECK(overlaps.size() == slow_overlaps.size());
- for (std::vector<Segment*>::iterator iter = slow_overlaps.begin();
- iter != slow_overlaps.end();
- iter++) {
- Segment* query_seg = *iter;
- // Ignore segments coming from the same contour.
- if (query_seg->contour() != cur) {
- // Only perform queries that can affect the computation.
- const BBox& bbox = query_seg->contour()->bbox();
- if (seg->get_point(0).fX >= bbox.min_x() &&
- seg->get_point(0).fX <= bbox.max_x()) {
- num_crossings += query_seg->NumCrossingsForXRay(seg->get_point(0),
- &ambiguous);
- if (ambiguous) {
- DLOG(INFO) << "Ambiguous intersection query at point ("
- << seg->get_point(0).fX << ", "
- << seg->get_point(0).fY << ")";
- DLOG(INFO) << "Query segment: " << *query_seg;
- break; // Abort iteration over overlaps.
- }
- }
- }
- }
-#endif // O3D_CORE_CROSS_GPU2D_PATH_PROCESSOR_DEBUG_ORIENTATION
- } // for (Segment* seg = cur->begin(); ...
-
- if (cur->ccw()) {
- if (num_crossings & 1) {
- cur->set_fill_right_side(true);
- } else {
- cur->set_fill_right_side(false);
- }
- } else {
- if (num_crossings & 1) {
- cur->set_fill_right_side(false);
- } else {
- cur->set_fill_right_side(true);
- }
- }
- }
-}
-
-void PathProcessor::DetermineOrientation(Contour* contour) {
- // Determine signed area of the polygon represented by the points
- // along the segments. Consider this an approximation to the true
- // orientation of the polygon; it probably won't handle
- // self-intersecting curves correctly.
- //
- // There is also a pretty basic assumption here that the contour is
- // closed.
- float signed_area = 0;
- for (Segment* seg = contour->begin();
- seg != contour->end();
- seg = seg->next()) {
- int limit = (seg->kind() == Segment::kCubic) ? 4 : 2;
- for (int i = 1; i < limit; i++) {
- const SkPoint& prev_point = seg->get_point(i - 1);
- const SkPoint& point = seg->get_point(i);
- float cur_area = prev_point.fX * point.fY - prev_point.fY * point.fX;
- DLOG_IF(INFO, verbose_logging_) << "Adding to signed area ("
- << prev_point.fX << ", "
- << prev_point.fY << ") -> ("
- << point.fX << ", "
- << point.fY << ") = "
- << cur_area;
- signed_area += cur_area;
- }
- }
-
- if (signed_area > 0)
- contour->set_ccw(true);
- else
- contour->set_ccw(false);
-}
-
-//----------------------------------------------------------------------
-// Classes and typedefs needed for curve subdivision.
-// Unfortunately it appears we can't scope these within the
-// SubdivideCurves() method itself, because templates then fail to
-// instantiate.
-
-// The user data which is placed in the IntervalTree.
-struct SweepData {
- SweepData()
- : triangle(NULL),
- segment(NULL) {
- }
-
- // The triangle this interval is associated with
- LocalTriangulator::Triangle* triangle;
- // The segment the triangle is associated with
- Segment* segment;
-};
-
-typedef IntervalTree<float, SweepData*> SweepTree;
-typedef SweepTree::IntervalType SweepInterval;
-
-// The entry / exit events which occur at the minimum and maximum x
-// coordinates of the control point triangles' bounding boxes.
-//
-// Note that this class requires its copy constructor and assignment
-// operator since it needs to be stored in a std::vector.
-class SweepEvent {
- public:
- SweepEvent()
- : x_(0),
- entry_(false),
- interval_(0, 0, NULL) {
- }
-
- // Initializes the SweepEvent.
- void Setup(float x, bool entry, SweepInterval interval) {
- x_ = x;
- entry_ = entry;
- interval_ = interval;
- }
-
- float x() const { return x_; }
- bool entry() const { return entry_; }
- const SweepInterval& interval() const { return interval_; }
-
- bool operator<(const SweepEvent& other) const {
- return x_ < other.x_;
- }
-
- private:
- float x_;
- bool entry_;
- SweepInterval interval_;
-};
-
-namespace {
-
-bool TrianglesOverlap(LocalTriangulator::Triangle* t0,
- LocalTriangulator::Triangle* t1) {
- LocalTriangulator::Vertex* t0v0 = t0->get_vertex(0);
- LocalTriangulator::Vertex* t0v1 = t0->get_vertex(1);
- LocalTriangulator::Vertex* t0v2 = t0->get_vertex(2);
- LocalTriangulator::Vertex* t1v0 = t1->get_vertex(0);
- LocalTriangulator::Vertex* t1v1 = t1->get_vertex(1);
- LocalTriangulator::Vertex* t1v2 = t1->get_vertex(2);
- return cubic::TrianglesOverlap(t0v0->x(), t0v0->y(),
- t0v1->x(), t0v1->y(),
- t0v2->x(), t0v2->y(),
- t1v0->x(), t1v0->y(),
- t1v1->x(), t1v1->y(),
- t1v2->x(), t1v2->y());
-}
-
-} // anonymous namespace
-
-void PathProcessor::SubdivideCurves() {
- // We need to determine all overlaps of all control point triangles
- // (from different segments, not the same segment) and, if any
- // exist, subdivide the associated curves.
- //
- // The plane-sweep algorithm determines all overlaps of a set of
- // rectangles in the 2D plane. Our problem maps very well to this
- // algorithm and significantly reduces the complexity compared to a
- // naive implementation.
- //
- // Each bounding box of a control point triangle is converted into
- // an "entry" event at its smallest X coordinate and an "exit" event
- // at its largest X coordinate. Each event has an associated
- // one-dimensional interval representing the Y span of the bounding
- // box. We sort these events by increasing X coordinate. We then
- // iterate through them. For each entry event we add the interval to
- // a side interval tree, and query this tree for overlapping
- // intervals. Any overlapping interval corresponds to an overlapping
- // bounding box. For each exit event we remove the associated
- // interval from the interval tree.
-
- std::vector<Segment*> cur_segments;
- std::vector<Segment*> next_segments;
-
- // Start things off by considering all of the segments
- for (std::vector<Contour*>::iterator iter = contours_.begin();
- iter != contours_.end();
- iter++) {
- Contour* cur = *iter;
- for (Segment* seg = cur->begin(); seg != cur->end(); seg = seg->next()) {
- if (seg->kind() == Segment::kCubic) {
- seg->Triangulate(false, NULL);
- cur_segments.push_back(seg);
- }
- }
- }
-
- // Subdivide curves at most this many times
- const int kMaxIter = 5;
- std::vector<SweepInterval> overlaps;
-
- for (int cur_iter = 0; cur_iter < kMaxIter; ++cur_iter) {
- if (cur_segments.empty()) {
- // Done
- break;
- }
-
- std::vector<SweepEvent> events;
- SweepTree tree(arena_);
- for (std::vector<Segment*>::iterator iter = cur_segments.begin();
- iter != cur_segments.end();
- iter++) {
- Segment* seg = *iter;
- if (seg->kind() == Segment::kCubic) {
- for (int i = 0; i < seg->num_triangles(); i++) {
- LocalTriangulator::Triangle* triangle = seg->get_triangle(i);
- BBox bbox;
- bbox.Setup(triangle);
- // Ignore zero-width triangles to avoid issues with
- // coincident entry and exit events for the same triangle
- if (bbox.max_x() > bbox.min_x()) {
- SweepData* data = arena_->Alloc<SweepData>();
- data->triangle = triangle;
- data->segment = seg;
- SweepInterval interval =
- tree.MakeInterval(bbox.min_y(), bbox.max_y(), data);
- // Add entry and exit events
- SweepEvent event;
- event.Setup(bbox.min_x(), true, interval);
- events.push_back(event);
- event.Setup(bbox.max_x(), false, interval);
- events.push_back(event);
- }
- }
- }
- }
-
- // Sort events by increasing X coordinate
- std::sort(events.begin(), events.end());
-
- // Now iterate through the events
- for (std::vector<SweepEvent>::iterator iter = events.begin();
- iter != events.end();
- iter++) {
- SweepEvent event = *iter;
- if (event.entry()) {
- // Add this interval into the tree
- tree.Insert(event.interval());
- // See whether the associated segment has been subdivided yet
- if (!event.interval().data()->segment->marked_for_subdivision()) {
- // Query the tree
- overlaps.clear();
- tree.AllOverlaps(event.interval(), overlaps);
- // Now see exactly which triangles overlap this one
- for (std::vector<SweepInterval>::iterator iter = overlaps.begin();
- iter != overlaps.end();
- iter++) {
- SweepInterval overlap = *iter;
- // Only pay attention to overlaps from a different Segment
- if (event.interval().data()->segment != overlap.data()->segment) {
- // See whether the triangles actually overlap
- if (TrianglesOverlap(event.interval().data()->triangle,
- overlap.data()->triangle)) {
- // Actually subdivide the segments.
- // Each one might already have been subdivided.
- Segment* seg = event.interval().data()->segment;
- ConditionallySubdivide(seg, &next_segments);
- seg = overlap.data()->segment;
- ConditionallySubdivide(seg, &next_segments);
- }
- }
- }
- }
- } else {
- // Remove this interval from the tree
- tree.Delete(event.interval());
- }
- }
-
- cur_segments = next_segments;
- next_segments.clear();
- }
-}
-
-void PathProcessor::ConditionallySubdivide(
- Segment* seg, std::vector<Segment*>* next_segments) {
- if (!seg->marked_for_subdivision()) {
- seg->set_marked_for_subdivision(true);
- Segment* next = seg->contour()->Subdivide(seg);
- // Triangulate the newly subdivided segments.
- next->Triangulate(false, NULL);
- next->next()->Triangulate(false, NULL);
- // Add them for the next iteration.
- next_segments->push_back(next);
- next_segments->push_back(next->next());
- }
-}
-
-void PathProcessor::SubdivideCurvesSlow() {
- // Alternate, significantly slower algorithm for curve subdivision
- // for use in debugging.
- std::vector<Segment*> cur_segments;
- std::vector<Segment*> next_segments;
-
- // Start things off by considering all of the segments
- for (std::vector<Contour*>::iterator iter = contours_.begin();
- iter != contours_.end();
- iter++) {
- Contour* cur = *iter;
- for (Segment* seg = cur->begin(); seg != cur->end(); seg = seg->next()) {
- if (seg->kind() == Segment::kCubic) {
- seg->Triangulate(false, NULL);
- cur_segments.push_back(seg);
- }
- }
- }
-
- // Subdivide curves at most this many times
- const int kMaxIter = 5;
-
- for (int cur_iter = 0; cur_iter < kMaxIter; ++cur_iter) {
- if (cur_segments.empty()) {
- // Done
- break;
- }
-
- for (std::vector<Segment*>::iterator iter = cur_segments.begin();
- iter != cur_segments.end();
- iter++) {
- Segment* seg = *iter;
- if (seg->kind() == Segment::kCubic) {
- for (std::vector<Segment*>::iterator iter2 = cur_segments.begin();
- iter2 != cur_segments.end();
- iter2++) {
- Segment* seg2 = *iter2;
- if (seg2->kind() == Segment::kCubic &&
- seg != seg2) {
- for (int i = 0; i < seg->num_triangles(); i++) {
- LocalTriangulator::Triangle* triangle = seg->get_triangle(i);
- for (int j = 0; j < seg2->num_triangles(); j++) {
- LocalTriangulator::Triangle* triangle2 = seg2->get_triangle(j);
- if (TrianglesOverlap(triangle, triangle2)) {
- ConditionallySubdivide(seg, &next_segments);
- ConditionallySubdivide(seg2, &next_segments);
- }
- }
- }
- }
- }
- }
- }
-
- cur_segments = next_segments;
- next_segments.clear();
- }
-}
-
-//----------------------------------------------------------------------
-// Structures and callbacks for tessellation of the interior region of
-// the contours.
-
-// The user data for the GLU tessellator.
-struct TessellationState {
- PathCache* cache;
- std::vector<void*> allocated_pointers;
-};
-
-namespace {
-
-void VertexCallback(void* vertex_data, void* data) {
- TessellationState* state = static_cast<TessellationState*>(data);
- PathCache* cache = state->cache;
- GLdouble* location = static_cast<GLdouble*>(vertex_data);
- cache->AddInteriorVertex(static_cast<float>(location[0]),
- static_cast<float>(location[1]));
-}
-
-void CombineCallback(GLdouble coords[3], void* vertex_data[4],
- GLfloat weight[4], void** out_data,
- void* polygon_data) {
- TessellationState* state = static_cast<TessellationState*>(polygon_data);
- GLdouble* out_vertex = static_cast<GLdouble*>(malloc(3 * sizeof(GLdouble)));
- state->allocated_pointers.push_back(out_vertex);
- out_vertex[0] = coords[0];
- out_vertex[1] = coords[1];
- out_vertex[2] = coords[2];
- *out_data = out_vertex;
-}
-
-void EdgeFlagCallback(GLboolean flag) {
- // No-op just to prevent triangle strips and fans from being passed
- // to us
-}
-
-} // anonymous namespace
-
-void PathProcessor::TessellateInterior(PathCache* cache) {
- // Because the GLU tessellator requires its input in
- // double-precision format, we need to make a separate copy of the
- // data.
- std::vector<GLdouble> vertex_data;
- std::vector<size_t> contour_endings;
- // For avoiding adding coincident vertices.
- float cur_x = 0, cur_y = 0;
- for (std::vector<Contour*>::iterator iter = contours_.begin();
- iter != contours_.end();
- iter++) {
- Contour* cur = *iter;
- bool first = true;
- for (Segment* seg = cur->begin(); seg != cur->end(); seg = seg->next()) {
- int num_interior_vertices = seg->num_interior_vertices();
- for (int i = 0; i < num_interior_vertices - 1; i++) {
- SkPoint point = seg->get_interior_vertex(i);
- if (first) {
- first = false;
- vertex_data.push_back(point.fX);
- vertex_data.push_back(point.fY);
- vertex_data.push_back(0);
- cur_x = point.fX;
- cur_y = point.fY;
- } else if (point.fX != cur_x || point.fY != cur_y) {
- vertex_data.push_back(point.fX);
- vertex_data.push_back(point.fY);
- vertex_data.push_back(0);
- cur_x = point.fX;
- cur_y = point.fY;
- }
- }
- }
- contour_endings.push_back(vertex_data.size());
- }
- // Now that we have all of the vertex data in a stable location in
- // memory, call the tessellator.
- GLUtesselator* tess = internal_gluNewTess();
- TessellationState state;
- state.cache = cache;
- internal_gluTessCallback(tess, GLU_TESS_VERTEX_DATA,
- reinterpret_cast<GLvoid (*)()>(VertexCallback));
- internal_gluTessCallback(tess, GLU_TESS_COMBINE_DATA,
- reinterpret_cast<GLvoid (*)()>(CombineCallback));
- internal_gluTessCallback(tess, GLU_TESS_EDGE_FLAG,
- reinterpret_cast<GLvoid (*)()>(EdgeFlagCallback));
- internal_gluTessBeginPolygon(tess, &state);
- internal_gluTessBeginContour(tess);
- GLdouble* base = &vertex_data.front();
- int contour_idx = 0;
- for (size_t i = 0; i < vertex_data.size(); i += 3) {
- if (i == contour_endings[contour_idx]) {
- internal_gluTessEndContour(tess);
- internal_gluTessBeginContour(tess);
- ++contour_idx;
- }
- internal_gluTessVertex(tess, &base[i], &base[i]);
- }
- internal_gluTessEndContour(tess);
- internal_gluTessEndPolygon(tess);
- for (size_t i = 0; i < state.allocated_pointers.size(); i++) {
- free(state.allocated_pointers[i]);
- }
- internal_gluDeleteTess(tess);
-}
-
-} // namespace gpu2d
-} // namespace o3d
-
diff --git a/o3d/core/cross/gpu2d/path_processor.h b/o3d/core/cross/gpu2d/path_processor.h
deleted file mode 100644
index f1af232..0000000
--- a/o3d/core/cross/gpu2d/path_processor.h
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-// The main entry point for Loop and Blinn's GPU accelerated curve
-// rendering algorithm.
-
-#ifndef O3D_CORE_CROSS_GPU2D_PATH_PROCESSOR_H_
-#define O3D_CORE_CROSS_GPU2D_PATH_PROCESSOR_H_
-
-#include <vector>
-
-#include "base/basictypes.h"
-
-class SkPath;
-
-namespace o3d {
-namespace gpu2d {
-
-class Arena;
-class Contour;
-class PathCache;
-class Segment;
-
-// The PathProcessor turns an SkPath (assumed to contain one or more
-// closed regions) into a set of exterior and interior triangles,
-// stored in the PathCache. The exterior triangles have associated 3D
-// texture coordinates which are used to evaluate the curve's
-// inside/outside function on a per-pixel basis. The interior
-// triangles are filled with 100% opacity.
-//
-// Note that the fill style and management of multiple layers are
-// separate concerns, handled at a higher level with shaders and
-// polygon offsets.
-class PathProcessor {
- public:
- PathProcessor();
- explicit PathProcessor(Arena* arena);
- ~PathProcessor();
-
- // Transforms the given path into a triangle mesh for rendering
- // using Loop and Blinn's shader, placing the result into the given
- // PathCache.
- void Process(const SkPath& path, PathCache* cache);
-
- // Enables or disables verbose logging in debug mode.
- void set_verbose_logging(bool on_or_off);
-
- private:
- // Builds a list of contours for the given path.
- void BuildContours(const SkPath& path);
-
- // Determines whether the left or right side of each contour should
- // be filled.
- void DetermineSidesToFill();
-
- // Determines whether the given (closed) contour is oriented
- // clockwise or counterclockwise.
- void DetermineOrientation(Contour* contour);
-
- // Subdivides the curves so that there are no overlaps of the
- // triangles associated with the curves' control points.
- void SubdivideCurves();
-
- // Helper function used during curve subdivision.
- void ConditionallySubdivide(Segment* seg,
- std::vector<Segment*>* next_segments);
-
- // Tessellates the interior regions of the contours.
- void TessellateInterior(PathCache* cache);
-
- // For debugging the orientation computation. Returns all of the
- // segments overlapping the given Y coordinate.
- std::vector<Segment*> AllSegmentsOverlappingY(float y);
-
- // For debugging the curve subdivision algorithm. Subdivides the
- // curves using an alternate, slow (O(n^3)) algorithm.
- void SubdivideCurvesSlow();
-
- // Arena from which to allocate temporary objects.
- Arena* arena_;
-
- // Whether to delete the arena upon deletion of the PathProcessor.
- bool should_delete_arena_;
-
- // The contours described by the path.
- std::vector<Contour*> contours_;
-
- // Whether or not to perform verbose logging in debug mode.
- bool verbose_logging_;
-
- DISALLOW_COPY_AND_ASSIGN(PathProcessor);
-};
-
-} // namespace gpu2d
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GPU2D_PATH_PROCESSOR_H_
-
diff --git a/o3d/core/cross/gpu2d/red_black_tree.h b/o3d/core/cross/gpu2d/red_black_tree.h
deleted file mode 100644
index e9ba092..0000000
--- a/o3d/core/cross/gpu2d/red_black_tree.h
+++ /dev/null
@@ -1,763 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-// A red-black tree, which is a form of a balanced binary tree. It
-// supports efficient insertion, deletion and queries of comparable
-// elements. The same element may be inserted multiple times. The
-// algorithmic complexity of common operations is:
-//
-// Insertion: O(lg(n))
-// Deletion: O(lg(n))
-// Querying: O(lg(n))
-//
-// The data type that is stored in this red-black tree must support
-// the default constructor, the copy constructor, and the "<" and "=="
-// operators. It must _not_ rely on having its destructor called. This
-// implementation internally allocates storage in large chunks and
-// does not call the destructor on each object.
-//
-// Note that when complex types are stored in this red/black tree, it
-// is possible that single invocations of the "<" and "==" operators
-// will be insufficient to describe the ordering of elements in the
-// tree during queries. As a concrete example, consider the case where
-// intervals are stored in the tree sorted by low endpoint. The "<"
-// operator on the Interval class only compares the low endpoint, but
-// the "==" operator takes into account the high endpoint as well.
-// This makes the necessary logic for querying and deletion somewhat
-// more complex. In order to properly handle such situations, the
-// property "needs_full_ordering_comparisons" must be set to true on
-// the tree.
-//
-// This red-black tree is designed to be _augmented_; subclasses can
-// add additional and summary information to each node to efficiently
-// store and index more complex data structures. A concrete example is
-// the IntervalTree, which extends each node with a summary statistic
-// to efficiently store one-dimensional intervals.
-//
-// The design of this red-black tree comes from Cormen, Leiserson,
-// and Rivest, _Introduction to Algorithms_, MIT Press, 1990.
-
-#ifndef O3D_CORE_CROSS_GPU2D_RED_BLACK_TREE_H_
-#define O3D_CORE_CROSS_GPU2D_RED_BLACK_TREE_H_
-
-#include <string>
-
-#include "base/logging.h"
-#include "core/cross/gpu2d/arena.h"
-
-namespace o3d {
-namespace gpu2d {
-
-template<class T>
-class RedBlackTree {
- public:
- // Visitor interface for walking all of the tree's elements.
- class Visitor {
- public:
- virtual ~Visitor() {}
- virtual void Visit(const T& data) = 0;
- };
-
- // Constructs a new red-black tree, allocating temporary objects
- // from a newly constructed Arena.
- RedBlackTree()
- : arena_(new Arena()),
- should_delete_arena_(true),
- root_(NULL),
- needs_full_ordering_comparisons_(false),
- verbose_debugging_(false) {
- }
-
- // Constructs a new red-black tree, allocating temporary objects
- // from the given Arena. The Arena is not destroyed when this tree
- // is.
- explicit RedBlackTree(Arena* arena)
- : arena_(arena),
- should_delete_arena_(false),
- root_(NULL),
- needs_full_ordering_comparisons_(false),
- verbose_debugging_(false) {
- }
-
- // Destructor deletes the internal Arena if it was not explicitly
- // passed to the constructor.
- virtual ~RedBlackTree() {
- if (should_delete_arena_) {
- delete arena_;
- }
- }
-
- // Inserts a datum into the tree.
- void Insert(const T& data) {
- Node* node = new Node(data);
- InsertNode(node);
- }
-
- // Deletes the given datum from the tree. Returns true if the datum
- // was found in the tree.
- bool Delete(const T& data) {
- Node* node = TreeSearch(data);
- if (node != NULL) {
- DeleteNode(node);
- return true;
- }
- return false;
- }
-
- // Returns true if the tree contains the given datum.
- bool Contains(const T& data) {
- return TreeSearch(data) != NULL;
- }
-
- // Visits the nodes of this tree in order, calling the visitor on
- // each one.
- void VisitInorder(Visitor* visitor) {
- if (root_ != NULL) {
- VisitInorderImpl(root_, visitor);
- }
- }
-
- // Returns the number of elements in the tree.
- int NumElements() {
- Counter counter;
- VisitInorder(&counter);
- return counter.count();
- }
-
- // Returns true if the tree's invariants are preserved.
- bool Verify() {
- int black_count;
- return VerifyFromNode(root_, &black_count);
- }
-
- // Dumps the tree's contents to the logging info stream for
- // debugging purposes.
- void Dump() {
- DumpFromNode(root_, 0);
- }
-
- // Sets whether this tree requires full ordering comparisons; see
- // the class documentation for an explanation of this property.
- void set_needs_full_ordering_comparisons(
- bool needs_full_ordering_comparisons) {
- needs_full_ordering_comparisons_ = needs_full_ordering_comparisons;
- }
-
- // Turns on or off verbose debugging of the tree, causing many
- // messages to be logged during insertion and other operations in
- // debug mode.
- void set_verbose_debugging(bool on_or_off) {
- verbose_debugging_ = on_or_off;
- }
-
- protected:
- enum Color {
- kRed = 1,
- kBlack
- };
-
- // The base Node class which is stored in the tree. Nodes are only
- // an internal concept; users of the tree deal only with the data
- // they store in it.
- class Node {
- public:
- // Constructor. Newly-created nodes are colored red.
- explicit Node(const T& data)
- : left_(NULL),
- right_(NULL),
- parent_(NULL),
- color_(kRed),
- data_(data) {
- }
-
- virtual ~Node() {
- }
-
- Color color() const {
- return color_;
- }
-
- void set_color(Color color) {
- color_ = color;
- }
-
- // Fetches the user data.
- const T& data() const {
- return data_;
- }
-
- // Copies all user-level fields from the source node, but not
- // internal fields. For example, the base implementation of this
- // method copies the "data_" field, but not the child or parent
- // fields. Any augmentation information also does not need to be
- // copied, as it will be recomputed. Subclasses must call the
- // superclass implementation.
- virtual void CopyFrom(Node* src) {
- data_ = src->data();
- }
-
- Node* left() const {
- return left_;
- }
-
- void set_left(Node* node) {
- left_ = node;
- }
-
- Node* right() const {
- return right_;
- }
-
- void set_right(Node* node) {
- right_ = node;
- }
-
- Node* parent() const {
- return parent_;
- }
-
- void set_parent(Node* node) {
- parent_ = node;
- }
-
- private:
- Node* left_;
- Node* right_;
- Node* parent_;
- Color color_;
- T data_;
- DISALLOW_COPY_AND_ASSIGN(Node);
- };
-
- // Returns the root of the tree, which is needed by some subclasses.
- Node* root() const {
- return root_;
- }
-
- private:
- // This virtual method is the hook that subclasses should use when
- // augmenting the red-black tree with additional per-node summary
- // information. For example, in the case of an interval tree, this
- // is used to compute the maximum endpoint of the subtree below the
- // given node based on the values in the left and right children. It
- // is guaranteed that this will be called in the correct order to
- // properly update such summary information based only on the values
- // in the left and right children. This method should return true if
- // the node's summary information changed.
- virtual bool UpdateNode(Node* node) {
- return false;
- }
-
- //----------------------------------------------------------------------
- // Generic binary search tree operations
- //
-
- // Searches the tree for the given datum.
- Node* TreeSearch(const T& data) {
- if (needs_full_ordering_comparisons_) {
- return TreeSearchFullComparisons(root_, data);
- } else {
- return TreeSearchNormal(root_, data);
- }
- }
-
- // Searches the tree using the normal comparison operations,
- // suitable for simple data types such as numbers.
- Node* TreeSearchNormal(Node* current, const T& data) {
- while (current != NULL) {
- if (current->data() == data) {
- return current;
- }
- if (data < current->data()) {
- current = current->left();
- } else {
- current = current->right();
- }
- }
- return NULL;
- }
-
- // Searches the tree using multiple comparison operations, required
- // for data types with more complex behavior such as intervals.
- Node* TreeSearchFullComparisons(Node* current, const T& data) {
- if (current == NULL) {
- return NULL;
- }
- if (data < current->data()) {
- return TreeSearchFullComparisons(current->left(), data);
- } else if (current->data() < data) {
- return TreeSearchFullComparisons(current->right(), data);
- } else {
- if (data == current->data()) {
- return current;
- } else {
- // We may need to traverse both the left and right subtrees.
- Node* result = TreeSearchFullComparisons(current->left(), data);
- if (result == NULL) {
- result = TreeSearchFullComparisons(current->right(), data);
- }
- return result;
- }
- }
- }
-
- // Inserts the given node into the tree.
- void TreeInsert(Node* z) {
- Node* y = NULL;
- Node* x = root_;
- while (x != NULL) {
- y = x;
- if (z->data() < x->data())
- x = x->left();
- else
- x = x->right();
- }
- z->set_parent(y);
- if (y == NULL) {
- root_ = z;
- } else {
- if (z->data() < y->data()) {
- y->set_left(z);
- } else {
- y->set_right(z);
- }
- }
- }
-
- // Finds the node following the given one in sequential ordering of
- // their data, or NULL if none exists.
- Node* TreeSuccessor(Node* x) {
- if (x->right() != NULL)
- return TreeMinimum(x->right());
- Node* y = x->parent();
- while (y != NULL && x == y->right()) {
- x = y;
- y = y->parent();
- }
- return y;
- }
-
- // Finds the minimum element in the sub-tree rooted at the given
- // node.
- Node* TreeMinimum(Node* x) {
- while (x->left() != NULL) {
- x = x->left();
- }
- return x;
- }
-
- // Helper for maintaining the augmented red-black tree.
- void PropagateUpdates(Node* start) {
- bool should_continue = true;
- while (start != NULL && should_continue) {
- should_continue = UpdateNode(start);
- start = start->parent();
- }
- }
-
- //----------------------------------------------------------------------
- // Red-Black tree operations
- //
-
- // Left-rotates the subtree rooted at x.
- void LeftRotate(Node* x) {
- // Set y.
- Node* y = x->right();
- // Turn y's left subtree into x's right subtree.
- x->set_right(y->left());
- if (y->left() != NULL) {
- y->left()->set_parent(x);
- }
- // Link x's parent to y.
- y->set_parent(x->parent());
- if (x->parent() == NULL) {
- root_ = y;
- } else {
- if (x == x->parent()->left()) {
- x->parent()->set_left(y);
- } else {
- x->parent()->set_right(y);
- }
- }
- // Put x on y's left.
- y->set_left(x);
- x->set_parent(y);
- // Update nodes lowest to highest.
- UpdateNode(x);
- UpdateNode(y);
- }
-
- // Right-rotates the subtree rooted at y.
- void RightRotate(Node* y) {
- // Set x.
- Node* x = y->left();
- // Turn x's right subtree into y's left subtree.
- y->set_left(x->right());
- if (x->right() != NULL) {
- x->right()->set_parent(y);
- }
- // Link y's parent to x.
- x->set_parent(y->parent());
- if (y->parent() == NULL) {
- root_ = x;
- } else {
- if (y == y->parent()->left()) {
- y->parent()->set_left(x);
- } else {
- y->parent()->set_right(x);
- }
- }
- // Put y on x's right.
- x->set_right(y);
- y->set_parent(x);
- // Update nodes lowest to highest.
- UpdateNode(y);
- UpdateNode(x);
- }
-
- // Inserts the given node into the tree.
- void InsertNode(Node* x) {
- TreeInsert(x);
- x->set_color(kRed);
- UpdateNode(x);
-
- DLOG_IF(INFO, verbose_debugging_) << " RedBlackTree::InsertNode";
-
- // The node from which to start propagating updates upwards.
- Node* update_start = x->parent();
-
- while (x != root_ && x->parent()->color() == kRed) {
- if (x->parent() == x->parent()->parent()->left()) {
- Node* y = x->parent()->parent()->right();
- if (y != NULL && y->color() == kRed) {
- // Case 1
- DLOG_IF(INFO, verbose_debugging_) << " Case 1/1";
- x->parent()->set_color(kBlack);
- y->set_color(kBlack);
- x->parent()->parent()->set_color(kRed);
- UpdateNode(x->parent());
- x = x->parent()->parent();
- UpdateNode(x);
- update_start = x->parent();
- } else {
- if (x == x->parent()->right()) {
- DLOG_IF(INFO, verbose_debugging_) << " Case 1/2";
- // Case 2
- x = x->parent();
- LeftRotate(x);
- }
- // Case 3
- DLOG_IF(INFO, verbose_debugging_) << " Case 1/3";
- x->parent()->set_color(kBlack);
- x->parent()->parent()->set_color(kRed);
- RightRotate(x->parent()->parent());
- update_start = x->parent()->parent();
- }
- } else {
- // Same as "then" clause with "right" and "left" exchanged.
- Node* y = x->parent()->parent()->left();
- if (y != NULL && y->color() == kRed) {
- // Case 1
- DLOG_IF(INFO, verbose_debugging_) << " Case 2/1";
- x->parent()->set_color(kBlack);
- y->set_color(kBlack);
- x->parent()->parent()->set_color(kRed);
- UpdateNode(x->parent());
- x = x->parent()->parent();
- UpdateNode(x);
- update_start = x->parent();
- } else {
- if (x == x->parent()->left()) {
- // Case 2
- DLOG_IF(INFO, verbose_debugging_) << " Case 2/2";
- x = x->parent();
- RightRotate(x);
- }
- // Case 3
- DLOG_IF(INFO, verbose_debugging_) << " Case 2/3";
- x->parent()->set_color(kBlack);
- x->parent()->parent()->set_color(kRed);
- LeftRotate(x->parent()->parent());
- update_start = x->parent()->parent();
- }
- }
- }
-
- PropagateUpdates(update_start);
-
- root_->set_color(kBlack);
- }
-
- // Restores the red-black property to the tree after splicing out
- // a node. Note that x may be NULL, which is why x_parent must be
- // supplied.
- void DeleteFixup(Node* x, Node* x_parent) {
- while (x != root_ && (x == NULL || x->color() == kBlack)) {
- if (x == x_parent->left()) {
- // Note: the text points out that w can not be NULL.
- // The reason is not obvious from simply looking at
- // the code; it comes about from the properties of the
- // red-black tree.
- Node* w = x_parent->right();
- DCHECK(w != NULL) << "x's sibling should not be null.";
- if (w->color() == kRed) {
- // Case 1
- w->set_color(kBlack);
- x_parent->set_color(kRed);
- LeftRotate(x_parent);
- w = x_parent->right();
- }
- if ((w->left() == NULL || w->left()->color() == kBlack) &&
- (w->right() == NULL || w->right()->color() == kBlack)) {
- // Case 2
- w->set_color(kRed);
- x = x_parent;
- x_parent = x->parent();
- } else {
- if (w->right() == NULL || w->right()->color() == kBlack) {
- // Case 3
- w->left()->set_color(kBlack);
- w->set_color(kRed);
- RightRotate(w);
- w = x_parent->right();
- }
- // Case 4
- w->set_color(x_parent->color());
- x_parent->set_color(kBlack);
- if (w->right() != NULL) {
- w->right()->set_color(kBlack);
- }
- LeftRotate(x_parent);
- x = root_;
- x_parent = x->parent();
- }
- } else {
- // Same as "then" clause with "right" and "left"
- // exchanged.
-
- // Note: the text points out that w can not be NULL.
- // The reason is not obvious from simply looking at
- // the code; it comes about from the properties of the
- // red-black tree.
- Node* w = x_parent->left();
- DCHECK(w != NULL) << "x's sibling should not be null.";
- if (w->color() == kRed) {
- // Case 1
- w->set_color(kBlack);
- x_parent->set_color(kRed);
- RightRotate(x_parent);
- w = x_parent->left();
- }
- if ((w->right() == NULL || w->right()->color() == kBlack) &&
- (w->left() == NULL || w->left()->color() == kBlack)) {
- // Case 2
- w->set_color(kRed);
- x = x_parent;
- x_parent = x->parent();
- } else {
- if (w->left() == NULL || w->left()->color() == kBlack) {
- // Case 3
- w->right()->set_color(kBlack);
- w->set_color(kRed);
- LeftRotate(w);
- w = x_parent->left();
- }
- // Case 4
- w->set_color(x_parent->color());
- x_parent->set_color(kBlack);
- if (w->left() != NULL) {
- w->left()->set_color(kBlack);
- }
- RightRotate(x_parent);
- x = root_;
- x_parent = x->parent();
- }
- }
- }
- if (x != NULL) {
- x->set_color(kBlack);
- }
- }
-
- // Deletes the given node from the tree. Note that this
- // particular node may not actually be removed from the tree;
- // instead, another node might be removed and its contents
- // copied into z.
- void DeleteNode(Node* z) {
- // Y is the node to be unlinked from the tree.
- Node* y;
- if (z->left() == NULL || z->right() == NULL) {
- y = z;
- } else {
- y = TreeSuccessor(z);
- }
- // Y is guaranteed to be non-NULL at this point.
- Node* x;
- if (y->left() != NULL) {
- x = y->left();
- } else {
- x = y->right();
- }
- // X is the child of y which might potentially replace y in
- // the tree. X might be NULL at this point.
- Node* x_parent;
- if (x != NULL) {
- x->set_parent(y->parent());
- x_parent = x->parent();
- } else {
- x_parent = y->parent();
- }
- if (y->parent() == NULL) {
- root_ = x;
- } else {
- if (y == y->parent()->left()) {
- y->parent()->set_left(x);
- } else {
- y->parent()->set_right(x);
- }
- }
- // It has been found empirically that both of these upward
- // propagations are necessary.
- if (y != z) {
- z->CopyFrom(y);
- PropagateUpdates(z);
- }
- if (x_parent != NULL) {
- PropagateUpdates(x_parent);
- }
- if (y->color() == kBlack) {
- DeleteFixup(x, x_parent);
- }
- }
-
- // Visits the subtree rooted at the given node in order.
- void VisitInorderImpl(Node* node, Visitor* visitor) {
- if (node->left() != NULL)
- VisitInorderImpl(node->left(), visitor);
- visitor->Visit(node->data());
- if (node->right() != NULL)
- VisitInorderImpl(node->right(), visitor);
- }
-
- //----------------------------------------------------------------------
- // Helper class for NumElements()
-
- // A Visitor which simply counts the number of visited elements.
- class Counter : public Visitor {
- public:
- Counter() : count_(0) {}
-
- virtual void Visit(const T& data) {
- ++count_;
- }
-
- int count() {
- return count_;
- }
-
- private:
- int count_;
- DISALLOW_COPY_AND_ASSIGN(Counter);
- };
-
- //----------------------------------------------------------------------
- // Verification and debugging routines
- //
-
- // Returns true if verification succeeded. Returns in the
- // "black_count" parameter the number of black children along all
- // paths to all leaves of the given node.
- bool VerifyFromNode(Node* node, int* black_count) {
- // Base case is a leaf node.
- if (node == NULL) {
- *black_count = 1;
- return true;
- }
-
- // Each node is either red or black.
- if (!(node->color() == kRed || node->color() == kBlack))
- return false;
-
- // Every leaf (or NULL) is black.
-
- if (node->color() == kRed) {
- // Both of its children are black.
- if (!((node->left() == NULL || node->left()->color() == kBlack)))
- return false;
- if (!((node->right() == NULL || node->right()->color() == kBlack)))
- return false;
- }
-
- // Every simple path to a leaf node contains the same number of
- // black nodes.
- int left_count = 0, right_count = 0;
- bool left_valid = VerifyFromNode(node->left(), &left_count);
- bool right_valid = VerifyFromNode(node->right(), &right_count);
- if (!left_valid || !right_valid)
- return false;
- *black_count = left_count + (node->color() == kBlack ? 1 : 0);
- return left_count == right_count;
- }
-
- // Dumps the subtree rooted at the given node.
- void DumpFromNode(Node* node, int indentation) {
- std::string prefix;
- for (int i = 0; i < indentation; i++) {
- prefix += " ";
- }
- prefix += "-";
- if (node == NULL) {
- DLOG(INFO) << prefix;
- return;
- }
- DLOG(INFO) << prefix << " " << node->data()
- << ((node->color() == kBlack) ? " (black)" : " (red)");
- DumpFromNode(node->left(), indentation + 2);
- DumpFromNode(node->right(), indentation + 2);
- }
-
- //----------------------------------------------------------------------
- // Data members
-
- Arena* arena_;
- bool should_delete_arena_;
- Node* root_;
- bool needs_full_ordering_comparisons_;
- bool verbose_debugging_;
-
- DISALLOW_COPY_AND_ASSIGN(RedBlackTree);
-};
-
-} // namespace gpu2d
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GPU2D_RED_BLACK_TREE_H_
-
diff --git a/o3d/core/cross/gpu2d/red_black_tree_test.cc b/o3d/core/cross/gpu2d/red_black_tree_test.cc
deleted file mode 100644
index cada4ef..0000000
--- a/o3d/core/cross/gpu2d/red_black_tree_test.cc
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Copyright 2010, 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 red-black tree class.
-
-#include <vector>
-
-#include "core/cross/gpu2d/red_black_tree.h"
-#include "core/cross/gpu2d/tree_test_helpers.h"
-#include "gtest/gtest.h"
-
-namespace o3d {
-namespace gpu2d {
-
-TEST(RedBlackTreeTest, TestSingleElementInsertion) {
- RedBlackTree<int> tree;
- tree.Insert(5);
- ASSERT_TRUE(tree.Verify());
- EXPECT_TRUE(tree.Contains(5));
-}
-
-TEST(RedBlackTreeTest, TestMultipleElementInsertion) {
- RedBlackTree<int> tree;
- tree.Insert(4);
- ASSERT_TRUE(tree.Verify());
- EXPECT_TRUE(tree.Contains(4));
- tree.Insert(3);
- ASSERT_TRUE(tree.Verify());
- EXPECT_TRUE(tree.Contains(3));
- tree.Insert(5);
- ASSERT_TRUE(tree.Verify());
- EXPECT_TRUE(tree.Contains(5));
- EXPECT_TRUE(tree.Contains(4));
- EXPECT_TRUE(tree.Contains(3));
-}
-
-TEST(RedBlackTreeTest, TestDuplicateElementInsertion) {
- RedBlackTree<int> tree;
- tree.Insert(3);
- ASSERT_TRUE(tree.Verify());
- tree.Insert(3);
- ASSERT_TRUE(tree.Verify());
- tree.Insert(3);
- ASSERT_TRUE(tree.Verify());
- EXPECT_EQ(3, tree.NumElements());
- EXPECT_TRUE(tree.Contains(3));
-}
-
-TEST(RedBlackTreeTest, TestSingleElementInsertionAndDeletion) {
- RedBlackTree<int> tree;
- tree.Insert(5);
- ASSERT_TRUE(tree.Verify());
- EXPECT_TRUE(tree.Contains(5));
- tree.Delete(5);
- ASSERT_TRUE(tree.Verify());
- EXPECT_FALSE(tree.Contains(5));
-}
-
-TEST(RedBlackTreeTest, TestMultipleElementInsertionAndDeletion) {
- RedBlackTree<int> tree;
- tree.Insert(4);
- ASSERT_TRUE(tree.Verify());
- EXPECT_TRUE(tree.Contains(4));
- tree.Insert(3);
- ASSERT_TRUE(tree.Verify());
- EXPECT_TRUE(tree.Contains(3));
- tree.Insert(5);
- ASSERT_TRUE(tree.Verify());
- EXPECT_TRUE(tree.Contains(5));
- EXPECT_TRUE(tree.Contains(4));
- EXPECT_TRUE(tree.Contains(3));
- tree.Delete(4);
- ASSERT_TRUE(tree.Verify());
- EXPECT_TRUE(tree.Contains(3));
- EXPECT_FALSE(tree.Contains(4));
- EXPECT_TRUE(tree.Contains(5));
- tree.Delete(5);
- ASSERT_TRUE(tree.Verify());
- EXPECT_TRUE(tree.Contains(3));
- EXPECT_FALSE(tree.Contains(4));
- EXPECT_FALSE(tree.Contains(5));
- EXPECT_EQ(1, tree.NumElements());
-}
-
-TEST(RedBlackTreeTest, TestDuplicateElementInsertionAndDeletion) {
- RedBlackTree<int> tree;
- tree.Insert(3);
- ASSERT_TRUE(tree.Verify());
- tree.Insert(3);
- ASSERT_TRUE(tree.Verify());
- tree.Insert(3);
- ASSERT_TRUE(tree.Verify());
- EXPECT_EQ(3, tree.NumElements());
- EXPECT_TRUE(tree.Contains(3));
- tree.Delete(3);
- ASSERT_TRUE(tree.Verify());
- tree.Delete(3);
- ASSERT_TRUE(tree.Verify());
- EXPECT_EQ(1, tree.NumElements());
- EXPECT_TRUE(tree.Contains(3));
- tree.Delete(3);
- ASSERT_TRUE(tree.Verify());
- EXPECT_EQ(0, tree.NumElements());
- EXPECT_FALSE(tree.Contains(3));
-}
-
-TEST(RedBlackTreeTest, FailingInsertionRegressionTest1) {
- RedBlackTree<int> tree;
- tree.Insert(5113);
- ASSERT_TRUE(tree.Verify());
- tree.Insert(4517);
- ASSERT_TRUE(tree.Verify());
- tree.Insert(3373);
- ASSERT_TRUE(tree.Verify());
- tree.Insert(9307);
- ASSERT_TRUE(tree.Verify());
- tree.Insert(7077);
- ASSERT_TRUE(tree.Verify());
-}
-
-namespace {
-void InsertionAndDeletionTest(const int32 seed, const int tree_size) {
- InitRandom(seed);
- const int max_val = tree_size;
- // Build the tree.
- RedBlackTree<int> tree;
- std::vector<int> values;
- for (int i = 0; i < tree_size; i++) {
- int val = NextRandom(max_val);
- tree.Insert(val);
- EXPECT_TRUE(tree.Verify()) << "Test failed for seed " << seed;
- values.push_back(val);
- }
- // Churn the tree's contents.
- for (int i = 0; i < tree_size; i++) {
- // Pick a random value to remove.
- int idx = NextRandom(tree_size);
- int val = values[idx];
- // Remove this value.
- tree.Delete(val);
- EXPECT_TRUE(tree.Verify()) << "Test failed for seed " << seed;
- // Replace it with a new one.
- val = NextRandom(max_val);
- values[idx] = val;
- tree.Insert(val);
- EXPECT_TRUE(tree.Verify()) << "Test failed for seed " << seed;
- }
-}
-} // anonymous namespace
-
-TEST(RedBlackTreeTest, RandomDeletionAndInsertionRegressionTest1) {
- InsertionAndDeletionTest(12311, 100);
-}
-
-TEST(RedBlackTreeTest, TestRandomDeletionAndInsertion) {
- InsertionAndDeletionTest(GenerateSeed(), 100);
-}
-
-} // namespace gpu2d
-} // namespace o3d
-
diff --git a/o3d/core/cross/gpu2d/tree_test_helpers.cc b/o3d/core/cross/gpu2d/tree_test_helpers.cc
deleted file mode 100644
index 337d7d1..0000000
--- a/o3d/core/cross/gpu2d/tree_test_helpers.cc
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright 2010, 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 "core/cross/gpu2d/tree_test_helpers.h"
-
-#include <cstdlib>
-
-#include "base/rand_util.h"
-
-namespace o3d {
-namespace gpu2d {
-
-int32 GenerateSeed() {
- // A seed of 1 has the special behavior of resetting the random
- // number generator. Assume that if we call this routine that we
- // don't want this behavior.
- int seed;
- do {
- seed = base::RandInt(0, 2 << 15);
- } while (seed <= 1);
- return seed;
-}
-
-void InitRandom(const int32 seed) {
- srand(seed);
-}
-
-int32 NextRandom(const int32 max_val) {
- // rand_r is not available on Windows
- return rand() % max_val; // NOLINT
-}
-
-} // namespace gpu2d
-} // namespace o3d
-
diff --git a/o3d/core/cross/gpu2d/tree_test_helpers.h b/o3d/core/cross/gpu2d/tree_test_helpers.h
deleted file mode 100644
index 39c74b7..0000000
--- a/o3d/core/cross/gpu2d/tree_test_helpers.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-// Simple pseudorandom number generator helper functions, used by the
-// red-black and interval tree tests.
-//
-// These are **not** thread safe!
-
-#ifndef O3D_CORE_CROSS_GPU2D_TREE_TEST_HELPERS_H_
-#define O3D_CORE_CROSS_GPU2D_TREE_TEST_HELPERS_H_
-
-#include "base/basictypes.h"
-
-namespace o3d {
-namespace gpu2d {
-
-// Generates a seed value to be passed to InitRandom().
-int32 GenerateSeed();
-
-// Initializes the pseudo-random number generator with a specific seed.
-void InitRandom(const int32 seed);
-
-// Produces the next pseudo-random number in the sequence, in the
-// range from [0..max_val). Negative numbers are not allowed and will
-// produce undefined results.
-int32 NextRandom(const int32 max_val);
-
-} // namespace gpu2d
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_GPU2D_TREE_TEST_HELPERS_H_
-
diff --git a/o3d/core/cross/iclass_manager.cc b/o3d/core/cross/iclass_manager.cc
deleted file mode 100644
index e3961eb..0000000
--- a/o3d/core/cross/iclass_manager.cc
+++ /dev/null
@@ -1,40 +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 "core/cross/iclass_manager.h"
-
-namespace o3d {
-
-const InterfaceId IClassManager::kInterfaceId =
- InterfaceTraits<IClassManager>::kInterfaceId;
-
-} // namespace o3d
diff --git a/o3d/core/cross/iclass_manager.h b/o3d/core/cross/iclass_manager.h
deleted file mode 100644
index e7b7a42..0000000
--- a/o3d/core/cross/iclass_manager.h
+++ /dev/null
@@ -1,159 +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_CORE_CROSS_ICLASS_MANAGER_H_
-#define O3D_CORE_CROSS_ICLASS_MANAGER_H_
-
-#include <vector>
-
-#include "core/cross/service_locator.h"
-#include "core/cross/object_base.h"
-
-namespace o3d {
-
-class ServiceLocator;
-
-// A pointer to a function that creates an object derived from NamedObject.
-typedef ObjectBase::Ref (*ObjectCreateFunc)(ServiceLocator* service_locator);
-
-// Maintains a collection of Class objects. Allows Classes to be retreived
-// by name and objects of those Classes to be created.
-class IClassManager {
- public:
- static const InterfaceId kInterfaceId;
-
- IClassManager() {}
- virtual ~IClassManager() {}
-
- // Registers a new Object creation function by string so that CreateObject can
- // create this new type.
- // Paramters:
- // class_type: Class of type as provided by ObjectBase::GetClass.
- // function: A function that creates an object of that type.
- virtual void AddClass(const ObjectBase::Class* class_type,
- ObjectCreateFunc function) = 0;
-
- // A typesafe version of AddClass. It guarantees that the creator and
- // class match. (Seems like this would be better as a macro since there would
- // be no code generation).
- template <typename T>
- void AddTypedClass() {
- AddClass(T::GetApparentClass(), T::Create);
- }
-
- // Removes a registered class.
- // Paramters:
- // class_type: Class of type as provided by ObjectBase::GetClass.
- virtual void RemoveClass(const ObjectBase::Class* class_type) = 0;
-
- // A typesafe version of RemoveClass.
- template <typename T>
- void RemoveTypedClass() {
- RemoveClass(T::GetApparentClass());
- }
-
- // Returns the ObjectBase::Class for a particular class name. It only works
- // for classes that have been registered through AddClass.
- // Parameters:
- // class_name: name of the class to look for.
- // Returns:
- // ObjectBase::Class* for the given class name or NULL if there is no match.
- virtual const ObjectBase::Class* GetClassByClassName(
- const String& class_name) const = 0;
-
- // Returns true if class_name is or is derived from base_class_type. It only
- // works for classes that have been registered through AddClass.
- // Parameters:
- // derived_class_name: Class name of derived class.
- // base_class: Class of type to check for.
- // Returns:
- // true if derived_class_name is or is derived from base_class.
- virtual bool ClassNameIsAClass(
- const String& derived_class_name,
- const ObjectBase::Class* base_class) const = 0;
-
- // Creates an Object by Class. This is an internal function. Do not use
- // directly.
- // Parameters:
- // object_class: ObjectBase::Class* to type of class to create.
- // Returns:
- // ObjectBase::Ref to created object.
- virtual ObjectBase::Ref CreateObjectByClass(
- const ObjectBase::Class* object_class) = 0;
-
- // Creates a Object based on the type. This is a type safe version of
- // CreateObjectByClass for C++.
- // Returns:
- // pointer to new object if successful.
- template<typename T>
- typename T::Ref Create() {
- return typename T::Ref(down_cast<T*>(
- CreateObjectByClass(T::GetApparentClass()).Get()));
- }
-
- // Creates an Object by Class name. This is an internal function. Do not use
- // directly.
- // Parameters:
- // type_name: Name of the Class to create.
- // Returns:
- // ObjectBase::Ref to created object.
- virtual ObjectBase::Ref CreateObject(const String& type_name) = 0;
-
- // Get all the classes registered in the class manager.
- virtual std::vector<const ObjectBase::Class*>
- GetAllClasses() const = 0;
-
- // This class registers a class with a class manager and removes it on
- // destruction.
- template <typename T>
- class Register {
- public:
- explicit Register(ServiceLocator* service_locator)
- : class_manager_(service_locator->GetService<IClassManager>()) {
- class_manager_->AddTypedClass<T>();
- }
- ~Register() {
- class_manager_->RemoveTypedClass<T>();
- }
-
- private:
- IClassManager* class_manager_;
- DISALLOW_COPY_AND_ASSIGN(Register);
- };
-
- private:
- DISALLOW_COPY_AND_ASSIGN(IClassManager);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_ICLASS_MANAGER_H_
diff --git a/o3d/core/cross/id_manager.cc b/o3d/core/cross/id_manager.cc
deleted file mode 100644
index f7c7085..0000000
--- a/o3d/core/cross/id_manager.cc
+++ /dev/null
@@ -1,43 +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 "core/cross/id_manager.h"
-
-namespace o3d {
-
-// Initialize the first unique id
-Id IdManager::next_unique_id_ = 0;
-
-Id IdManager::CreateId() {
- return next_unique_id_++;
-}
-} // namespace o3d
diff --git a/o3d/core/cross/id_manager.h b/o3d/core/cross/id_manager.h
deleted file mode 100644
index fa1651cfc..0000000
--- a/o3d/core/cross/id_manager.h
+++ /dev/null
@@ -1,52 +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_CORE_CROSS_ID_MANAGER_H_
-#define O3D_CORE_CROSS_ID_MANAGER_H_
-
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// Assigns unique ids.
-class IdManager {
- public:
- // Get next unused id.
- static Id CreateId();
-
- private:
- // Current largest unique id
- static Id next_unique_id_;
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_ID_MANAGER_H_
diff --git a/o3d/core/cross/ierror_status.cc b/o3d/core/cross/ierror_status.cc
deleted file mode 100644
index e50b375..0000000
--- a/o3d/core/cross/ierror_status.cc
+++ /dev/null
@@ -1,40 +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 "core/cross/ierror_status.h"
-
-namespace o3d {
-
-const InterfaceId IErrorStatus::kInterfaceId =
- InterfaceTraits<IErrorStatus>::kInterfaceId;
-
-} // namespace o3d
diff --git a/o3d/core/cross/ierror_status.h b/o3d/core/cross/ierror_status.h
deleted file mode 100644
index 7e9b070..0000000
--- a/o3d/core/cross/ierror_status.h
+++ /dev/null
@@ -1,99 +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_CORE_CROSS_IERROR_STATUS_H_
-#define O3D_CORE_CROSS_IERROR_STATUS_H_
-
-#include "core/cross/service_locator.h"
-#include "core/cross/callback.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// Records the last reported error. Allows a callback to be invoked when an
-// error is reported.
-class IErrorStatus {
- public:
- static const InterfaceId kInterfaceId;
-
- typedef Callback1<const String&> ErrorCallback;
-
- virtual ~IErrorStatus() {}
-
- // Sets the error callback. NOTE: The client takes ownership of the
- // ErrorCallback you pass in. It will be deleted if you call SetErrorCallback
- // a second time or if you call ClearErrorCallback.
- //
- // Parameters:
- // error_callback: ErrorCallback to call each time the client gets
- // an error.
- virtual void SetErrorCallback(ErrorCallback* error_callback) = 0;
-
- // Clears the Error callback NOTE: The client takes own ership of the
- // ErrorCallback you pass in to SetErrorCallback. It will be deleted if you
- // call SetErrorCallback a second time or if you call ClearErrorCallback.
- virtual void ClearErrorCallback() = 0;
-
- // Sets the last error. This is pretty much only called by ErrorStreamManager.
- virtual void SetLastError(const String& error) = 0;
-
-#ifndef NDEBUG
- // For debug builds, we display where in the code the error came from.
- virtual void SetLastError(const String& error, const char *file,
- int line) = 0;
-#endif
-
- // Gets the last reported error.
- virtual const String& GetLastError() const = 0;
-
- // Clears the stored last error.
- virtual void ClearLastError() = 0;
-
- // File logging is only ever done in a debug build, but can be turned off
- // there at will.
- virtual void SetFileLoggingActive(bool should_log) = 0;
- virtual bool IsFileLoggingActive() const = 0;
-
- protected:
- // Exchanges a new callback with the current callback, returing the old
- // one.
- // Parameters:
- // callback: ErrorCallback to exchange.
- virtual ErrorCallback* Exchange(ErrorCallback* callback) = 0;
-
- private:
- friend class ErrorCollector;
- friend class ErrorSuppressor;
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_IERROR_STATUS_H_
diff --git a/o3d/core/cross/image_utils.cc b/o3d/core/cross/image_utils.cc
deleted file mode 100644
index 4a94aad..0000000
--- a/o3d/core/cross/image_utils.cc
+++ /dev/null
@@ -1,906 +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 functions to help with images.
-
-// The precompiled header must appear before anything else.
-#include "core/cross/precompile.h"
-
-#include "core/cross/image_utils.h"
-#include "core/cross/pointer_utils.h"
-#include "core/cross/math_utilities.h"
-
-namespace o3d {
-namespace image {
-
-// Computes the size of the buffer containing a an image, given its width,
-// height and format.
-size_t ComputeBufferSize(unsigned int width,
- unsigned int height,
- Texture::Format format) {
- DCHECK(CheckImageDimensions(width, height));
- unsigned int pixels = width * height;
- switch (format) {
- case Texture::XRGB8:
- case Texture::ARGB8:
- return 4 * sizeof(uint8) * pixels; // NOLINT
- case Texture::ABGR16F:
- return 4 * sizeof(uint16) * pixels; // NOLINT
- case Texture::R32F:
- return sizeof(float) * pixels; // NOLINT
- case Texture::ABGR32F:
- return 4 * sizeof(float) * pixels; // NOLINT
- case Texture::DXT1:
- case Texture::DXT3:
- case Texture::DXT5: {
- unsigned int blocks = ((width + 3) / 4) * ((height + 3) / 4);
- unsigned int bytes_per_block = format == Texture::DXT1 ? 8 : 16;
- return blocks * bytes_per_block;
- }
- case Texture::UNKNOWN_FORMAT:
- break;
- }
- // failed to find a matching format
- LOG(ERROR) << "Unrecognized Texture format type.";
- return 0;
-}
-
-// Gets the size of the buffer containing a mip-map chain, given its base
-// width, height, format and number of mip-map levels.
-size_t ComputeMipChainSize(unsigned int base_width,
- unsigned int base_height,
- Texture::Format format,
- unsigned int num_mipmaps) {
- DCHECK(CheckImageDimensions(base_width, base_height));
- size_t total_size = 0;
- unsigned int mip_width = base_width;
- unsigned int mip_height = base_height;
- for (unsigned int i = 0; i < num_mipmaps; ++i) {
- total_size += ComputeBufferSize(mip_width, mip_height, format);
- mip_width = std::max(1U, mip_width >> 1);
- mip_height = std::max(1U, mip_height >> 1);
- }
- return total_size;
-}
-
-// Scales the image using basic point filtering.
-bool ScaleUpToPOT(unsigned int width,
- unsigned int height,
- Texture::Format format,
- const void *src,
- void *dst,
- int dst_pitch) {
- DCHECK(CheckImageDimensions(width, height));
- switch (format) {
- case Texture::XRGB8:
- case Texture::ARGB8:
- case Texture::ABGR16F:
- case Texture::R32F:
- case Texture::ABGR32F:
- break;
- case Texture::DXT1:
- case Texture::DXT3:
- case Texture::DXT5:
- case Texture::UNKNOWN_FORMAT:
- DCHECK(false);
- return false;
- }
- unsigned int pot_width = ComputePOTSize(width);
- unsigned int pot_height = ComputePOTSize(height);
- if (pot_width == width && pot_height == height && src == dst)
- return true;
- return Scale(
- width, height, format, src, pot_width, pot_height, dst, dst_pitch);
-}
-
-unsigned int GetNumComponentsForFormat(o3d::Texture::Format format) {
- switch (format) {
- case o3d::Texture::XRGB8:
- case o3d::Texture::ARGB8:
- case o3d::Texture::ABGR16F:
- case o3d::Texture::ABGR32F:
- return 4;
- case o3d::Texture::R32F:
- return 1;
- case o3d::Texture::DXT1:
- case o3d::Texture::DXT3:
- case o3d::Texture::DXT5:
- case o3d::Texture::UNKNOWN_FORMAT:
- break;
- }
- return 0;
-}
-
-bool CanMakeMips(o3d::Texture::Format format) {
- return GetNumComponentsForFormat(format) != 0;
-}
-
-namespace {
-
-static const float kEpsilon = 0.0001f;
-static const float kPi = 3.14159265358979f;
-static const int kFilterSize = 3;
-
-// utility function, round float numbers into 0 to 255 integers.
-uint8 Safe8Round(float f) {
- f += 0.5f;
- if (f < 0.0f) {
- return 0;
- } else if (!(f < 255.0f)) {
- return 255;
- }
- return static_cast<uint8>(f);
-}
-
-template <typename T>
-void PointScale(
- unsigned components,
- const void* src,
- unsigned src_width,
- unsigned src_height,
- void* dst,
- int dst_pitch,
- unsigned dst_width,
- unsigned dst_height) {
- const T* use_src = reinterpret_cast<const T*>(src);
- T* use_dst = reinterpret_cast<T*>(dst);
- int pitch = dst_pitch / sizeof(*use_src) / components;
- // Start from the end to be able to do it in place.
- for (unsigned int y = dst_height - 1; y < dst_height; --y) {
- // max value for y is dst_height - 1, which makes :
- // base_y = (2*dst_height - 1) * src_height / (2 * dst_height)
- // which is < src_height.
- unsigned int base_y = ((y * 2 + 1) * src_height) / (dst_height * 2);
- DCHECK_LT(base_y, src_height);
- for (unsigned int x = dst_width - 1; x < dst_width; --x) {
- unsigned int base_x = ((x * 2 + 1) * src_width) / (dst_width * 2);
- DCHECK_LT(base_x, src_width);
- for (unsigned int c = 0; c < components; ++c) {
- use_dst[(y * pitch + x) * components + c] =
- use_src[(base_y * src_width + base_x) * components + c];
- }
- }
- }
-}
-
-} // anonymous namespace
-
-// Scales the image using basic point filtering.
-bool Scale(unsigned int src_width,
- unsigned int src_height,
- Texture::Format format,
- const void *src,
- unsigned int dst_width,
- unsigned int dst_height,
- void *dst,
- int dst_pitch) {
- DCHECK(CheckImageDimensions(src_width, src_height));
- DCHECK(CheckImageDimensions(dst_width, dst_height));
- switch (format) {
- case Texture::XRGB8:
- case Texture::ARGB8: {
- PointScale<uint8>(4, src, src_width, src_height,
- dst, dst_pitch, dst_width, dst_height);
- break;
- }
- case Texture::ABGR16F: {
- PointScale<uint16>(4, src, src_width, src_height,
- dst, dst_pitch, dst_width, dst_height);
- break;
- }
- case Texture::R32F:
- case Texture::ABGR32F: {
- PointScale<float>(format == Texture::R32F ? 1 : 4,
- src, src_width, src_height,
- dst, dst_pitch, dst_width, dst_height);
- break;
- }
- case Texture::DXT1:
- case Texture::DXT3:
- case Texture::DXT5:
- case Texture::UNKNOWN_FORMAT:
- DCHECK(false);
- return false;
- }
- return true;
-}
-
-
-namespace {
-
-// utility function called in AdjustDrawImageBoundary.
-// help to adjust a specific dimension,
-// if start point or ending point is out of boundary.
-bool AdjustDrawImageBoundHelper(int* src_a, int* dest_a,
- int* src_length, int* dest_length,
- int src_bmp_length) {
- if (*src_length == 0 || *dest_length == 0) {
- return false;
- }
-
- // check if start point is out of boundary.
- // if src_a < 0, src_length must be positive.
- if (*src_a < 0) {
- int src_length_delta = 0 - *src_a;
- *dest_a = *dest_a + (*dest_length) * src_length_delta / (*src_length);
- *dest_length = *dest_length - (*dest_length) *
- src_length_delta / (*src_length);
- *src_length = *src_length - src_length_delta;
- *src_a = 0;
- }
- // if src_a >= src_bmp_width, src_length must be negative.
- if (*src_a >= src_bmp_length) {
- int src_length_delta = *src_a - (src_bmp_length - 1);
- *dest_a = *dest_a - (*dest_length) * src_length_delta / (*src_length);
- *dest_length = *dest_length - (*dest_length) *
- src_length_delta / *src_length;
- *src_length = *src_length - src_length_delta;
- *src_a = src_bmp_length - 1;
- }
-
- if (*src_length == 0 || *dest_length == 0) {
- return false;
- }
- // check whether start point + related length is out of boundary.
- // if src_a + src_length > src_bmp_length, src_length must be positive.
- if (*src_a + *src_length > src_bmp_length) {
- int src_length_delta = *src_length - (src_bmp_length - *src_a);
- *dest_length = *dest_length - (*dest_length) *
- src_length_delta / (*src_length);
- *src_length = *src_length - src_length_delta;
- }
- // if src_a + src_length < -1, src_length must be negative.
- if (*src_a + *src_length < -1) {
- int src_length_delta = 0 - (*src_a + *src_length);
- *dest_length = *dest_length + (*dest_length) *
- src_length_delta / (*src_length);
- *src_length = *src_length + src_length_delta;
- }
-
- return true;
-}
-
-template <typename OriginalType,
- float convert_to_float(OriginalType value),
- OriginalType convert_to_original(float)>
-void LanczosResize1D(const void* src_data, int src_pitch,
- int src_x, int src_y,
- int width, int height,
- void* dest_data, int dest_pitch,
- int dest_x, int dest_y,
- int nwidth,
- bool is_width, int components) {
- // calculate scale factor and init the weight array for lanczos filter.
- float scale = fabs(static_cast<float>(width) / nwidth);
- float support = kFilterSize * scale;
- scoped_array<float> weight(new float[static_cast<int>(support * 2) + 4]);
- // we assume width is the dimension we are scaling, and height stays
- // the same.
- for (int i = 0; i < abs(nwidth); ++i) {
- // center is the corresponding coordinate of i in original img.
- float center = (i + 0.5f) * scale;
- // boundary of weight array in original img.
- int xmin = static_cast<int>(floorf(center - support));
- if (xmin < 0) {
- xmin = 0;
- }
- int xmax = static_cast<int>(ceilf(center + support));
- if (xmax >= abs(width)) {
- xmax = abs(width) - 1;
- }
-
- // fill up weight array by lanczos filter.
- float wsum = 0.0;
- for (int ox = xmin; ox <= xmax; ++ox) {
- float wtemp;
- float dx = ox + 0.5f - center;
- // lanczos filter
- if (dx <= -kFilterSize || dx >= kFilterSize) {
- wtemp = 0.0;
- } else if (dx == 0.0) {
- wtemp = 1.0f;
- } else {
- wtemp = kFilterSize * sinf(kPi * dx) * sinf(kPi / kFilterSize * dx) /
- (kPi * kPi * dx * dx);
- }
-
- weight[ox - xmin] = wtemp;
- wsum += wtemp;
- }
- int wcount = xmax - xmin + 1;
-
- // Normalize the weights.
- if (fabs(wsum) > kEpsilon) {
- for (int k = 0; k < wcount; ++k) {
- weight[k] /= wsum;
- }
- }
- // Now that we've computed the filter weights for this x-position
- // of the image, we can apply that filter to all pixels in that
- // column.
- // calculate coordinate in new img.
- int x = nwidth >= 0 ? i : -i;
- // lower bound of coordinate in original img.
- if (width < 0) {
- xmin = -1 * xmin;
- }
- for (int j = 0; j < abs(height); ++j) {
- // coordinate in height, same in src and dest img.
- int base_y = height >= 0 ? j : -j;
- // TODO(yux): fix the vertical flip problem and merge this if-else
- // statement coz at that time, there would be no need to check
- // which measure we are scaling.
- if (is_width) {
- const OriginalType* inrow = PointerFromVoidPointer<const OriginalType*>(
- src_data, (src_y + base_y) * src_pitch) +
- (src_x + xmin) * components;
- OriginalType* outpix = PointerFromVoidPointer<OriginalType*>(
- dest_data, (dest_y + base_y) * dest_pitch) +
- (dest_x + x) * components;
- int step = width >= 0 ? components : -components;
- for (int b = 0; b < components; ++b) {
- float sum = 0.0;
- for (int k = 0, xk = b; k < wcount; ++k, xk += step) {
- sum += weight[k] * convert_to_float(inrow[xk]);
- }
- outpix[b] = convert_to_original(sum);
- }
- } else {
- const OriginalType* inrow = PointerFromVoidPointer<const OriginalType*>(
- src_data,
- (src_y + xmin) * src_pitch) +
- (src_x + base_y) * components;
- OriginalType* outpix = PointerFromVoidPointer<OriginalType*>(
- dest_data,
- (dest_y + x) * dest_pitch) +
- (dest_x + base_y) * components;
- int step = width >= 0 ? src_pitch : -src_pitch;
- for (int b = 0; b < components; ++b) {
- float sum = 0.0;
- const OriginalType* work = inrow + b;
- for (int k = 0; k < wcount; ++k) {
- sum += weight[k] * convert_to_float(*work);
- work = AddPointerOffset<const OriginalType*>(work, step);
- }
- outpix[b] = convert_to_original(sum);
- }
- }
- }
- }
-}
-
-template <typename OriginalType,
- float convert_to_float(OriginalType value),
- OriginalType convert_to_original(float)>
-void TypedLanczosScale(const void* src, int src_pitch,
- int src_x, int src_y,
- int src_width, int src_height,
- void* dest, int dest_pitch,
- int dest_x, int dest_y,
- int dest_width, int dest_height,
- int components) {
- // Scale the image horizontally to a temp buffer.
- int temp_img_width = abs(dest_width);
- int temp_img_height = abs(src_height);
- int temp_width = dest_width;
- int temp_height = src_height;
- int temp_x = 0, temp_y = 0;
- if (temp_width < 0)
- temp_x = abs(temp_width) - 1;
- if (temp_height < 0)
- temp_y = abs(temp_height) - 1;
-
- scoped_array<OriginalType> temp(
- new OriginalType[temp_img_width * temp_img_height * components]);
-
- LanczosResize1D<OriginalType, convert_to_float, convert_to_original>(
- src, src_pitch, src_x, src_y, src_width, src_height,
- temp.get(), temp_img_width * components * sizeof(OriginalType),
- temp_x, temp_y, temp_width,
- true, components);
-
- // Scale the temp buffer vertically to get the final result.
- LanczosResize1D<OriginalType, convert_to_float, convert_to_original>(
- temp.get(), temp_img_width * components * sizeof(OriginalType),
- temp_x, temp_y, temp_height, temp_width,
- dest, dest_pitch,
- dest_x, dest_y, dest_height,
- false, components);
-}
-
-// Compute a texel, filtered from several source texels. This function assumes
-// minification.
-// Parameters:
-// x: x-coordinate of the destination texel in the destination image
-// y: y-coordinate of the destination texel in the destination image
-// dst_width: width of the destination image
-// dst_height: height of the destination image
-// dst_data: address of the destination image data
-// dst_pitch: the number of bytes per row of the destination.
-// src_width: width of the source image
-// src_height: height of the source image
-// src_data: address of the source image data
-// src_pitch: the number of bytes per row of the source.
-// components: number of components in the image.
-template <typename OriginalType,
- typename WorkType,
- WorkType convert_to_work(OriginalType value),
- OriginalType convert_to_original(WorkType)>
-void FilterTexel(unsigned int x,
- unsigned int y,
- unsigned int dst_width,
- unsigned int dst_height,
- void *dst_data,
- int dst_pitch,
- unsigned int src_width,
- unsigned int src_height,
- const void *src_data,
- int src_pitch,
- unsigned int components) {
- DCHECK(image::CheckImageDimensions(src_width, src_height));
- DCHECK(image::CheckImageDimensions(dst_width, dst_height));
- DCHECK_LE(dst_width, src_width);
- DCHECK_LE(dst_height, src_height);
- DCHECK_LE(x, dst_width);
- DCHECK_LE(y, dst_height);
- DCHECK_LE(static_cast<int>(src_width), src_pitch);
- DCHECK_LE(static_cast<int>(dst_width), dst_pitch);
-
- // the texel at (x, y) represents the square of texture coordinates
- // [x/dst_w, (x+1)/dst_w) x [y/dst_h, (y+1)/dst_h).
- // This takes contributions from the texels:
- // [floor(x*src_w/dst_w), ceil((x+1)*src_w/dst_w)-1]
- // x
- // [floor(y*src_h/dst_h), ceil((y+1)*src_h/dst_h)-1]
- // from the previous level.
- unsigned int src_min_x = (x * src_width) / dst_width;
- unsigned int src_max_x =
- ((x + 1) * src_width + dst_width - 1) / dst_width - 1;
- unsigned int src_min_y = (y * src_height) / dst_height;
- unsigned int src_max_y =
- ((y + 1) * src_height + dst_height - 1) / dst_height - 1;
-
- // Find the contribution of source each texel, by computing the coverage of
- // the destination texel on the source texel. We do all the computations in
- // fixed point, at a src_height*src_width factor to be able to use ints,
- // but keep all the precision.
- // Accumulators need to be 64 bits though, because src_height*src_width can
- // be 24 bits for a 4kx4k base, to which we need to multiply the component
- // value which is another 8 bits (and we need to accumulate several of them).
-
- // NOTE: all of our formats use at most 4 components per pixel.
- // Instead of dynamically allocating a buffer for each pixel on the heap,
- // just allocate the worst case on the stack.
- DCHECK_LE(components, 4u);
- WorkType accum[4] = {0};
- for (unsigned int src_x = src_min_x; src_x <= src_max_x; ++src_x) {
- for (unsigned int src_y = src_min_y; src_y <= src_max_y; ++src_y) {
- // The contribution of a fully covered texel is 1/(m_x*m_y) where m_x is
- // the x-dimension minification factor (src_width/dst_width) and m_y is
- // the y-dimenstion minification factor (src_height/dst_height).
- // If the texel is partially covered (on a border), the contribution is
- // proportional to the covered area. We compute it as the product of the
- // covered x-length by the covered y-length.
-
- unsigned int x_contrib = dst_width;
- if (src_x * dst_width < x * src_width) {
- // source texel is across the left border of the footprint of the
- // destination texel.
- x_contrib = (src_x + 1) * dst_width - x * src_width;
- } else if ((src_x + 1) * dst_width > (x + 1) * src_width) {
- // source texel is across the right border of the footprint of the
- // destination texel.
- x_contrib = (x+1) * src_width - src_x * dst_width;
- }
- DCHECK(x_contrib > 0);
- DCHECK(x_contrib <= dst_width);
- unsigned int y_contrib = dst_height;
- if (src_y * dst_height < y * src_height) {
- // source texel is across the top border of the footprint of the
- // destination texel.
- y_contrib = (src_y + 1) * dst_height - y * src_height;
- } else if ((src_y + 1) * dst_height > (y + 1) * src_height) {
- // source texel is across the bottom border of the footprint of the
- // destination texel.
- y_contrib = (y + 1) * src_height - src_y * dst_height;
- }
- DCHECK(y_contrib > 0);
- DCHECK(y_contrib <= dst_height);
- WorkType contrib = static_cast<WorkType>(x_contrib * y_contrib);
- const OriginalType* src = PointerFromVoidPointer<const OriginalType*>(
- src_data, src_y * src_pitch);
- for (unsigned int c = 0; c < components; ++c) {
- accum[c] += contrib *
- convert_to_work(src[src_x * components + c]);
- }
- }
- }
- OriginalType* dst = PointerFromVoidPointer<OriginalType*>(
- dst_data, y * dst_pitch);
- for (unsigned int c = 0; c < components; ++c) {
- WorkType value = accum[c] / static_cast<WorkType>(src_height * src_width);
- dst[x * components + c] = convert_to_original(value);
- }
-}
-
-template <typename OriginalType,
- typename WorkType,
- typename FilterType,
- WorkType convert_to_work(OriginalType value),
- OriginalType convert_from_work(WorkType),
- FilterType convert_to_filter(OriginalType value),
- OriginalType convert_from_filter(FilterType)>
-void GenerateMip(unsigned int components,
- unsigned int src_width,
- unsigned int src_height,
- const void *src_data,
- int src_pitch,
- void *dst_data,
- int dst_pitch) {
- unsigned int mip_width = std::max(1U, src_width >> 1);
- unsigned int mip_height = std::max(1U, src_height >> 1);
-
- if (mip_width * 2 == src_width && mip_height * 2 == src_height) {
- // Easy case: every texel maps to exactly 4 texels in the previous level.
- for (unsigned int y = 0; y < mip_height; ++y) {
- const OriginalType* src0 = PointerFromVoidPointer<const OriginalType*>(
- src_data, y * 2 * src_pitch);
- const OriginalType* src1 =
- AddPointerOffset<const OriginalType*>(src0, src_pitch);
- OriginalType* dst = PointerFromVoidPointer<OriginalType*>(
- dst_data, y * dst_pitch);
- for (unsigned int x = 0; x < mip_width; ++x) {
- for (unsigned int c = 0; c < components; ++c) {
- // Average the 4 texels.
- unsigned int offset = x * 2 * components + c;
- WorkType value = convert_to_work(src0[offset]); // (2x, 2y)
- value += convert_to_work(src0[offset + components]); // (2x+1, 2y)
- value += convert_to_work(src1[offset]); // (2x, 2y+1)
- value += convert_to_work(src1[offset + components]); // (2x+1, 2y+1)
- dst[x * components + c] =
- convert_from_work(value / static_cast<WorkType>(4));
- }
- }
- }
- } else {
- for (unsigned int y = 0; y < mip_height; ++y) {
- for (unsigned int x = 0; x < mip_width; ++x) {
- FilterTexel<OriginalType,
- FilterType,
- convert_to_filter,
- convert_from_filter>(
- x, y, mip_width, mip_height, dst_data, dst_pitch,
- src_width, src_height, src_data, src_pitch, components);
- }
- }
- }
-}
-
-uint32 UInt8ToUInt32(uint8 value) {
- return static_cast<uint32>(value);
-};
-
-uint8 UInt32ToUInt8(uint32 value) {
- return static_cast<uint8>(value);
-};
-
-uint64 UInt8ToUInt64(uint8 value) {
- return static_cast<uint64>(value);
-};
-
-uint8 UInt64ToUInt8(uint64 value) {
- return static_cast<uint8>(value);
-};
-
-float UInt8ToFloat(uint8 value) {
- return static_cast<float>(value);
-};
-
-float FloatToFloat(float value) {
- return value;
-}
-
-double FloatToDouble(float value) {
- return static_cast<double>(value);
-}
-
-float DoubleToFloat(double value) {
- return static_cast<float>(value);
-}
-
-float HalfToFloat(uint16 value) {
- return Vectormath::Aos::HalfToFloat(value);
-}
-
-uint16 FloatToHalf(float value) {
- return Vectormath::Aos::FloatToHalf(value);
-}
-
-double HalfToDouble(uint16 value) {
- return static_cast<double>(Vectormath::Aos::HalfToFloat(value));
-}
-
-uint16 DoubleToHalf(double value) {
- return Vectormath::Aos::FloatToHalf(static_cast<float>(value));
-}
-
-} // anonymous namespace
-
-bool AdjustForSetRect(int* src_y,
- int src_width,
- int src_height,
- int* src_pitch,
- int* dst_y,
- int dst_width,
- int* dst_height) {
- if (src_width != dst_width || abs(src_height) != abs(*dst_height) ||
- src_width < 0) {
- return false;
- }
-
- if (*dst_height < 0) {
- *dst_y = *dst_y + *dst_height + 1;
- *dst_height = -*dst_height;
- if (src_height < 0) {
- *src_y = *src_y + src_height + 1;
- } else {
- *src_y = *src_y + src_height - 1;
- *src_pitch = -*src_pitch;
- }
- } else {
- if (src_height < 0) {
- *src_pitch = -*src_pitch;
- }
- }
-
- return true;
-}
-
-// Adjust boundaries when using DrawImage function in bitmap or texture.
-bool AdjustDrawImageBoundary(int* src_x, int* src_y,
- int* src_width, int* src_height,
- int src_bmp_level,
- int src_bmp_width, int src_bmp_height,
- int* dest_x, int* dest_y,
- int* dest_width, int* dest_height,
- int dest_bmp_level,
- int dest_bmp_width, int dest_bmp_height) {
- // if src or dest rectangle is out of boundaries, do nothing.
- if ((*src_x < 0 && *src_x + *src_width <= 0) ||
- (*src_y < 0 && *src_y + *src_height <= 0) ||
- (*dest_x < 0 && *dest_x + *dest_width <= 0) ||
- (*dest_y < 0 && *dest_y + *dest_height <= 0) ||
- (*src_x >= src_bmp_width &&
- *src_x + *src_width >= src_bmp_width - 1) ||
- (*src_y >= src_bmp_height &&
- *src_y + *src_height >= src_bmp_height - 1) ||
- (*dest_x >= dest_bmp_width &&
- *dest_x + *dest_width >= dest_bmp_width - 1) ||
- (*dest_y >= dest_bmp_height &&
- *dest_y + *dest_height >= dest_bmp_height - 1) ||
- (src_bmp_level < 0) || (dest_bmp_level < 0))
- return false;
-
- int src_mip_width = static_cast<int>(
- image::ComputeMipDimension(src_bmp_level, src_bmp_width));
- int src_mip_height = static_cast<int>(
- image::ComputeMipDimension(src_bmp_level, src_bmp_height));
- int dest_mip_width = static_cast<int>(
- image::ComputeMipDimension(dest_bmp_level, dest_bmp_width));
- int dest_mip_height = static_cast<int>(
- image::ComputeMipDimension(dest_bmp_level, dest_bmp_height));
-
- // if start points are negative.
- // check whether src_x is negative.
- if (!AdjustDrawImageBoundHelper(src_x, dest_x,
- src_width, dest_width, src_mip_width))
- return false;
- // check whether dest_x is negative.
- if (!AdjustDrawImageBoundHelper(dest_x, src_x,
- dest_width, src_width, dest_mip_width))
- return false;
- // check whether src_y is negative.
- if (!AdjustDrawImageBoundHelper(src_y, dest_y,
- src_height, dest_height, src_mip_height))
- return false;
- // check whether dest_y is negative.
- if (!AdjustDrawImageBoundHelper(dest_y, src_y,
- dest_height, src_height, dest_mip_height))
- return false;
-
- // check any width or height becomes negative after adjustment.
- if (*src_width == 0 || *src_height == 0 ||
- *dest_width == 0 || *dest_height == 0) {
- return false;
- }
-
- return true;
-}
-
-void LanczosScale(Texture::Format format, const void* src, int src_pitch,
- int src_x, int src_y,
- int src_width, int src_height,
- void* dest, int dest_pitch,
- int dest_x, int dest_y,
- int dest_width, int dest_height,
- int components) {
- switch (format) {
- case Texture::ARGB8:
- case Texture::XRGB8:
- TypedLanczosScale<uint8, UInt8ToFloat, Safe8Round>(
- src, src_pitch, src_x, src_y, src_width, src_height,
- dest, dest_pitch, dest_x, dest_y, dest_width, dest_height,
- components);
- break;
- case Texture::ABGR16F:
- TypedLanczosScale<uint16, HalfToFloat, FloatToHalf>(
- src, src_pitch, src_x, src_y, src_width, src_height,
- dest, dest_pitch, dest_x, dest_y, dest_width, dest_height,
- components);
- break;
- case Texture::ABGR32F:
- case Texture::R32F:
- TypedLanczosScale<float, FloatToFloat, FloatToFloat>(
- src, src_pitch, src_x, src_y, src_width, src_height,
- dest, dest_pitch, dest_x, dest_y, dest_width, dest_height,
- components);
- break;
- default:
- DLOG(ERROR) << "Mip-map generation not supported for format: " << format;
- return;
- }
-}
-
-bool GenerateMipmap(unsigned int src_width,
- unsigned int src_height,
- Texture::Format format,
- const void *src_data,
- int src_pitch,
- void *dst_data,
- int dst_pitch) {
- unsigned int components = GetNumComponentsForFormat(format);
- if (components == 0) {
- DLOG(ERROR) << "Mip-map generation not supported for format: " << format;
- return false;
- }
-
- switch (format) {
- case Texture::ARGB8:
- case Texture::XRGB8:
- GenerateMip<uint8, uint32, uint64,
- UInt8ToUInt32, UInt32ToUInt8,
- UInt8ToUInt64, UInt64ToUInt8>(
- components, src_width, src_height, src_data, src_pitch,
- dst_data, dst_pitch);
- break;
- case Texture::ABGR16F:
- GenerateMip<uint16, float, double,
- HalfToFloat, FloatToHalf,
- HalfToDouble, DoubleToHalf>(
- components, src_width, src_height, src_data, src_pitch,
- dst_data, dst_pitch);
- break;
- case Texture::ABGR32F:
- case Texture::R32F:
- GenerateMip<float, float, double,
- FloatToFloat, FloatToFloat,
- FloatToDouble, DoubleToFloat>(
- components, src_width, src_height, src_data, src_pitch,
- dst_data, dst_pitch);
- break;
- default:
- DLOG(ERROR) << "Mip-map generation not supported for format: " << format;
- return false;
- }
- return true;
-}
-
-ImageFileType GetFileTypeFromFilename(const char *filename) {
- // Convert the filename to lower case for matching.
- // NOTE: Surprisingly, "tolower" is not in the std namespace.
- String name(filename);
- std::transform(name.begin(), name.end(), name.begin(), ::tolower);
-
- // Dispatch loading functions based on filename extensions.
- String::size_type i = name.rfind(".");
- if (i == String::npos) {
- DLOG(INFO) << "Could not detect file type for image \""
- << filename << "\": no extension.";
- return UNKNOWN;
- }
-
- String extension = name.substr(i);
- if (extension == ".tga") {
- DLOG(INFO) << "Bitmap Found a TGA file : " << filename;
- return TGA;
- } else if (extension == ".dds") {
- DLOG(INFO) << "Bitmap Found a DDS file : " << filename;
- return DDS;
- } else if (extension == ".png") {
- DLOG(INFO) << "Bitmap Found a PNG file : " << filename;
- return PNG;
- } else if (extension == ".jpg" ||
- extension == ".jpeg" ||
- extension == ".jpe") {
- DLOG(INFO) << "Bitmap Found a JPEG file : " << filename;
- return JPEG;
- } else {
- return UNKNOWN;
- }
-}
-
-namespace {
-
-struct MimeTypeToFileType {
- const char *mime_type;
- ImageFileType file_type;
-};
-
-const MimeTypeToFileType mime_type_map[] = {
- {"image/png", PNG},
- {"image/jpeg", JPEG},
- // No official MIME type for TGA or DDS.
-};
-
-} // anonymous namespace
-
-ImageFileType GetFileTypeFromMimeType(const char *mime_type) {
- for (unsigned int i = 0u; i < arraysize(mime_type_map); ++i) {
- if (!strcmp(mime_type, mime_type_map[i].mime_type))
- return mime_type_map[i].file_type;
- }
- return UNKNOWN;
-}
-
-void XYZToXYZA(uint8 *image_data, int pixel_count) {
- // We do this pixel by pixel, starting from the end to avoid overlapping
- // problems.
- for (int i = pixel_count - 1; i >= 0; --i) {
- image_data[i * 4 + 3] = 0xff;
- image_data[i * 4 + 2] = image_data[i * 3 + 2];
- image_data[i * 4 + 1] = image_data[i * 3 + 1];
- image_data[i * 4 + 0] = image_data[i * 3 + 0];
- }
-}
-
-void RGBAToBGRA(uint8 *image_data, int pixel_count) {
- for (int i = 0; i < pixel_count; ++i) {
- uint8 c = image_data[i * 4 + 0];
- image_data[i * 4 + 0] = image_data[i * 4 + 2];
- image_data[i * 4 + 2] = c;
- }
-}
-
-} // namespace image
-} // namespace o3d
-
-
diff --git a/o3d/core/cross/image_utils.h b/o3d/core/cross/image_utils.h
deleted file mode 100644
index 28e8b34..0000000
--- a/o3d/core/cross/image_utils.h
+++ /dev/null
@@ -1,288 +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 declaration of functions to help with images.
-
-#ifndef O3D_CORE_CROSS_IMAGE_UTILS_H_
-#define O3D_CORE_CROSS_IMAGE_UTILS_H_
-
-#include "base/cross/bits.h"
-#include "core/cross/types.h"
-#include "core/cross/texture_base.h"
-
-namespace o3d {
-namespace image {
-
-// We will fail to load images that are bigger than 4kx4k to avoid security
-// risks. GPUs don't usually support bigger sizes anyway.
-// The biggest bitmap buffer size with these dimensions is:
-// 4k x 4k x 4xsizeof(float) x6 x4/3 (x6 for cube maps, x4/3 for mipmaps)
-// That makes 2GB, representable in an unsigned int, so we will avoid wraps.
-const unsigned int kMaxImageDimension = 4096u;
-
-enum ImageFileType {
- UNKNOWN,
- TGA,
- JPEG,
- PNG,
- DDS,
-};
-
-unsigned int GetNumComponentsForFormat(Texture::Format format);
-
-inline bool IsPOT(unsigned width, unsigned height) {
- return ((width & (width - 1)) == 0) && ((height & (height - 1)) == 0);
-}
-
-inline bool CheckImageDimensions(unsigned int width, unsigned int height) {
- return width <= kMaxImageDimension && height <= kMaxImageDimension;
-}
-
-// Returns whether or not we can make mips.
-bool CanMakeMips(Texture::Format format);
-
-// Gets the number of mip-maps required for a full chain starting at
-// width x height.
-inline unsigned int ComputeMipMapCount(
- unsigned int width, unsigned int height) {
- return 1 + base::bits::Log2Floor(std::max(width, height));
-}
-
-// Gets the smallest power-of-two value that is at least as high as
-// dimension. This is the POT dimension used in ScaleUpToPOT.
-inline unsigned int ComputePOTSize(unsigned int dimension) {
- return (dimension == 0) ? 0 : 1 << base::bits::Log2Ceiling(dimension);
-}
-
-// Computes one dimension of a mip.
-inline unsigned ComputeMipDimension(int level, unsigned dimension) {
- unsigned v = dimension >> level;
- return v > 0 ? v : 1u;
-}
-
-// Computes the size of the buffer containing a mip-map chain, given its base
-// width, height, format and number of mip-map levels.
-size_t ComputeMipChainSize(unsigned int base_width,
- unsigned int base_height,
- Texture::Format format,
- unsigned int num_mipmaps);
-
-inline int ComputePitch(Texture::Format format, unsigned width) {
- if (Texture::IsCompressedFormat(format)) {
- unsigned blocks_across = (width + 3u) / 4u;
- unsigned bytes_per_block = format == Texture::DXT1 ? 8u : 16u;
- return bytes_per_block * blocks_across;
- } else {
- return static_cast<int>(ComputeMipChainSize(width, 1u, format, 1u));
- }
-}
-
-// Computes the pitch for a bitmap.
-// NOTE: For textures you must get the pitch from the OS.
-inline int ComputeMipPitch(Texture::Format format,
- int level,
- unsigned width) {
- return ComputePitch(format, ComputeMipDimension(level, width));
-}
-
-// Computes the number of bytes of a bitmap pixel buffer.
-size_t ComputeBufferSize(unsigned int width,
- unsigned int height,
- Texture::Format format);
-
-// Crop part of an image from src, scale it to an arbitrary size
-// and paste in dest image. Utility function for all DrawImage
-// function in bitmap and textures. Scale operation is based on
-// Lanczos resampling.
-// Note: this doesn't work for DXTC.
-//
-// Parameters:
-// format: The format of the images.
-// src: source image which would be copied from.
-// src_pitch: The number of bytes per row in the src image.
-// src_x: x-coordinate of the starting pixel in the src image.
-// src_y: y-coordinate of the starting pixel in the src image.
-// src_width: width of the part in src image to be croped.
-// src_height: height of the part in src image to be croped.
-// dest: dest image which would be copied to.
-// dest_pitch: The number of bytes per row in the dest image.
-// dest_x: x-coordinate of the starting pixel in the dest image.
-// dest_y: y-coordinate of the starting pixel in the dest image.
-// dest_width: width of the part in dest image to be pasted to.
-// dest_height: height of the part in dest image to be pasted to.
-// components: number of components per pixel.
-void LanczosScale(Texture::Format format,
- const void* src, int src_pitch,
- int src_x, int src_y,
- int src_width, int src_height,
- void* dest, int dest_pitch,
- int dest_x, int dest_y,
- int dest_width, int dest_height,
- int components);
-
-// Detects the type of image file based on the filename.
-ImageFileType GetFileTypeFromFilename(const char *filename);
-//
-// Detects the type of image file based on the mime-type.
-ImageFileType GetFileTypeFromMimeType(const char *mime_type);
-
-// Adds filler alpha byte (0xff) after every pixel. Assumes buffer was
-// allocated with enough storage)
-// can convert RGB -> RGBA, BGR -> BGRA, etc.
-void XYZToXYZA(uint8 *image_data, int pixel_count);
-
-// Swaps Red and Blue components in the image.
-void RGBAToBGRA(uint8 *image_data, int pixel_count);
-
-// Generates a mip-map for 1 level.
-// NOTE: this doesn't work for DXTC images.
-//
-// Parameters:
-// src_width: the width of the source image.
-// src_height: the height of the source image.
-// format: the format of the data.
-// src_data: the data containing the src image.
-// src_pitch: If the format is uncompressed this is the number of bytes
-// per row of pixels. If compressed this value is unused.
-// dst_data: memory for a mip one level smaller then the source.
-// dst_pitch: If the format is uncompressed this is the number of bytes
-// per row of pixels. If compressed this value is unused.
-bool GenerateMipmap(unsigned int src_width,
- unsigned int src_height,
- Texture::Format format,
- const void *src_data,
- int src_pitch,
- void *dst_data,
- int dst_pitch);
-
-// Scales an image up to power-of-two textures, using point filtering.
-// NOTE: this doesn't work for DXTC images.
-//
-// Parameters:
-// width: the non-power-of-two width of the original image.
-// height: the non-power-of-two height of the original image.
-// format: the format of the data.
-// src: the data containing the source data of the original image.
-// dst: a buffer with enough space for the power-of-two version. Pixels are
-// written from the end to the beginning so dst can be the same buffer
-// as src.
-// dst_pitch: Number of bytes across 1 row of pixels.
-bool ScaleUpToPOT(unsigned int width,
- unsigned int height,
- Texture::Format format,
- const void *src,
- void *dst,
- int dst_pitch);
-
-// Scales an image to an arbitrary size, using point filtering.
-// NOTE: this doesn't work for DXTC images.
-//
-// Parameters:
-// src_width: the width of the original image.
-// src_height: the height of the original image.
-// format: the format of the data.
-// src: the data containing the source data of the original image.
-// dst_width: the width of the target image.
-// dst_height: the height of the target image.
-// dst: a buffer with enough space for the target version. Pixels are
-// written from the end to the beginning so dst can be the same buffer
-// as src if the transformation is an upscaling.
-// dst_pitch: Number of bytes across 1 row of pixels.
-bool Scale(unsigned int src_width,
- unsigned int src_height,
- Texture::Format format,
- const void *src,
- unsigned int dst_width,
- unsigned int dst_height,
- void *dst,
- int dst_pitch);
-
-// adjust start points and boundaries when using DrawImage data
-// in bitmap and textures.
-// Parameters:
-// src_x: x-coordinate of the starting pixel in the source image.
-// src_y: y-coordinate of the starting pixel in the source image.
-// src_width: width of the source image to draw.
-// src_height: height of the source image to draw.
-// src_bmp_level: which mip in source.
-// src_bmp_width: original width of source bitmap.
-// src_bmp_height: original height of source bitmap.
-// dest_x: x-coordinate of the starting pixel in the dest image.
-// dest_y: y-coordinate of the starting pixel in the dest image.
-// dest_width: width of the dest image to draw.
-// dest_height: height of the dest image to draw.
-// dest_bmp_level: which mip in dest.
-// dest_bmp_width: original width of dest bitmap.
-// dest_bmp_height: original height of dest bitmap.
-// Returns:
-// false if src or dest rectangle is out of boundaries.
-bool AdjustDrawImageBoundary(int* src_x, int* src_y,
- int* src_width, int* src_height,
- int src_level,
- int src_bmp_width, int src_bmp_height,
- int* dest_x, int* dest_y,
- int* dest_width, int* dest_height,
- int dest_level,
- int dest_bmp_width, int dest_bmp_height);
-
-// Checks whether or not we can call SetRect and adjust the inputs
-// accordingly so SetRect will work.
-//
-// Assumes that both the source and destination rectangles are within the
-// bounds of their respective images.
-//
-// Parameters:
-// src_y: A pointer to an int holding the Y position of the source
-// rect. Will be adjusted if SetRect can be called.
-// src_width: The width of the source rect.
-// src_height: The height of the source rect.
-// src_pitch: A pointer to an int holding the pitch of the source. Will be
-// adjusted if SetRect can be called.
-// dst_y: A pointer to an int holding the Y position of the dest rect. Will be
-// adjusted if SetRect can be called.
-// dst_width: The width of the dest rect.
-// dst_height: A pointer to an int holding the height of the dest rect. Will
-// adjusted if SetRect can be called.
-// Returns:
-// True if SetRect can be called.
-bool AdjustForSetRect(int* src_y,
- int src_width,
- int src_height,
- int* src_pitch,
- int* dst_y,
- int dst_width,
- int* dst_height);
-
-} // namespace image
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_IMAGE_UTILS_H_
-
diff --git a/o3d/core/cross/image_utils_test.cc b/o3d/core/cross/image_utils_test.cc
deleted file mode 100644
index 49a8723..0000000
--- a/o3d/core/cross/image_utils_test.cc
+++ /dev/null
@@ -1,592 +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 "core/cross/client.h"
-#include "core/cross/image_utils.h"
-#include "tests/common/win/testing_common.h"
-#include "base/file_path.h"
-#include "utils/cross/file_path_utils.h"
-#include "core/cross/math_utilities.h"
-
-namespace o3d {
-
-namespace {
-
-void ConvertToHalf(const float* src, size_t count, uint16* dst) {
- for (; count != 0; --count) {
- *dst++ = Vectormath::Aos::FloatToHalf(*src++);
- }
-}
-
-bool CompareFloats(const float* src_1, const float* src_2, size_t num_floats) {
- const float kEpsilon = 0.000001f;
- for (; num_floats != 0; --num_floats) {
- if (fabs(*src_1 - *src_2) > kEpsilon) {
- return false;
- }
- ++src_1;
- ++src_2;
- }
- return true;
-}
-
-bool CompareHalfs(const uint16* src_1, const uint16* src_2, size_t num_floats) {
- const float kEpsilon = 0.001f;
- for (; num_floats != 0; --num_floats) {
- float s1 = Vectormath::Aos::HalfToFloat(*src_1);
- float s2 = Vectormath::Aos::HalfToFloat(*src_2);
- if (fabs(s1 - s2) > kEpsilon) {
- return false;
- }
- ++src_1;
- ++src_2;
- }
- return true;
-}
-
-} // anonymous namespace.
-
-class ImageTest : public testing::Test {
-};
-
-TEST_F(ImageTest, GetNumComponentsForFormat) {
- EXPECT_EQ(4u, image::GetNumComponentsForFormat(Texture::XRGB8));
- EXPECT_EQ(4u, image::GetNumComponentsForFormat(Texture::ARGB8));
- EXPECT_EQ(4u, image::GetNumComponentsForFormat(Texture::ABGR16F));
- EXPECT_EQ(4u, image::GetNumComponentsForFormat(Texture::ABGR32F));
- EXPECT_EQ(1u, image::GetNumComponentsForFormat(Texture::R32F));
- EXPECT_EQ(0u, image::GetNumComponentsForFormat(Texture::DXT1));
- EXPECT_EQ(0u, image::GetNumComponentsForFormat(Texture::DXT3));
- EXPECT_EQ(0u, image::GetNumComponentsForFormat(Texture::DXT5));
-}
-
-TEST_F(ImageTest, IsPOT) {
- EXPECT_TRUE(image::IsPOT(2, 2));
- EXPECT_FALSE(image::IsPOT(3, 2));
- EXPECT_FALSE(image::IsPOT(2, 3));
-}
-
-TEST_F(ImageTest, CheckImageDimensions) {
- EXPECT_TRUE(image::CheckImageDimensions(1u, 1u));
- EXPECT_TRUE(image::CheckImageDimensions(image::kMaxImageDimension,
- image::kMaxImageDimension));
- EXPECT_FALSE(image::CheckImageDimensions(0u, image::kMaxImageDimension + 1));
- EXPECT_FALSE(image::CheckImageDimensions(image::kMaxImageDimension + 1, 0u));
-}
-
-TEST_F(ImageTest, ComputeMipMapCount) {
- EXPECT_EQ(image::ComputeMipMapCount(1, 1), 1u);
- EXPECT_EQ(image::ComputeMipMapCount(2, 2), 2u);
- EXPECT_EQ(image::ComputeMipMapCount(2, 1), 2u);
- EXPECT_EQ(image::ComputeMipMapCount(256, 1), 9u);
- EXPECT_EQ(image::ComputeMipMapCount(256, 256), 9u);
-}
-
-TEST_F(ImageTest, ComputePOTSize) {
- EXPECT_EQ(image::ComputePOTSize(1), 1u);
- EXPECT_EQ(image::ComputePOTSize(2), 2u);
- EXPECT_EQ(image::ComputePOTSize(3), 4u);
- EXPECT_EQ(image::ComputePOTSize(4), 4u);
- EXPECT_EQ(image::ComputePOTSize(5), 8u);
- EXPECT_EQ(image::ComputePOTSize(7), 8u);
- EXPECT_EQ(image::ComputePOTSize(8), 8u);
- EXPECT_EQ(image::ComputePOTSize(9), 16u);
- EXPECT_EQ(image::ComputePOTSize(128), 128u);
- EXPECT_EQ(image::ComputePOTSize(129), 256u);
- EXPECT_EQ(image::ComputePOTSize(255), 256u);
- EXPECT_EQ(image::ComputePOTSize(4096), 4096u);
-}
-
-TEST_F(ImageTest, CanMakeMips) {
- EXPECT_TRUE(image::CanMakeMips(Texture::XRGB8));
- EXPECT_TRUE(image::CanMakeMips(Texture::ARGB8));
- EXPECT_TRUE(image::CanMakeMips(Texture::ABGR16F));
- EXPECT_TRUE(image::CanMakeMips(Texture::R32F));
- EXPECT_TRUE(image::CanMakeMips(Texture::ABGR32F));
- EXPECT_FALSE(image::CanMakeMips(Texture::DXT1));
- EXPECT_FALSE(image::CanMakeMips(Texture::DXT3));
- EXPECT_FALSE(image::CanMakeMips(Texture::DXT5));
-};
-
-static const uint8 kScaleUPDataNPOT[] = {
- // This is a 3x3 image.
- 0x75, 0x58, 0x7b, 0x76,
- 0x8a, 0x54, 0x85, 0x6f,
- 0x93, 0x56, 0x74, 0x7d,
-
- 0x3f, 0x58, 0x7a, 0x64,
- 0x7a, 0x90, 0x75, 0x8f,
- 0xb4, 0x7c, 0x71, 0x6b,
-
- 0x84, 0x84, 0x85, 0x6c,
- 0xb1, 0x73, 0x4f, 0x7c,
- 0x97, 0x87, 0x78, 0xa2,
-};
-
-static const uint8 kScaleUPDataPOT[] = {
- // This is the 4x4 scaled-up version of the above.
- 0x75, 0x58, 0x7b, 0x76,
- 0x8a, 0x54, 0x85, 0x6f,
- 0x8a, 0x54, 0x85, 0x6f,
- 0x93, 0x56, 0x74, 0x7d,
-
- 0x3f, 0x58, 0x7a, 0x64,
- 0x7a, 0x90, 0x75, 0x8f,
- 0x7a, 0x90, 0x75, 0x8f,
- 0xb4, 0x7c, 0x71, 0x6b,
-
- 0x3f, 0x58, 0x7a, 0x64,
- 0x7a, 0x90, 0x75, 0x8f,
- 0x7a, 0x90, 0x75, 0x8f,
- 0xb4, 0x7c, 0x71, 0x6b,
-
- 0x84, 0x84, 0x85, 0x6c,
- 0xb1, 0x73, 0x4f, 0x7c,
- 0xb1, 0x73, 0x4f, 0x7c,
- 0x97, 0x87, 0x78, 0xa2,
-};
-
-// Scales up a NPOT texture, compare with expected results.
-TEST_F(ImageTest, ScaleUpToPOT) {
- const unsigned int kWidth = 3;
- const unsigned int kHeight = 3;
- const unsigned int kPOTWidth = image::ComputePOTSize(kWidth);
- ASSERT_EQ(kPOTWidth, 4u);
- const unsigned int kPOTHeight = image::ComputePOTSize(kHeight);
- ASSERT_EQ(kPOTHeight, 4u);
- const Texture::Format format = Texture::ARGB8;
- size_t src_size = image::ComputeBufferSize(kWidth, kHeight, format);
- ASSERT_EQ(sizeof(kScaleUPDataNPOT), src_size);
- size_t dst_size = image::ComputeBufferSize(kPOTWidth, kPOTHeight, format);
- ASSERT_EQ(sizeof(kScaleUPDataPOT), dst_size);
- scoped_array<uint8> data(new uint8[dst_size]);
- ASSERT_TRUE(data.get() != NULL);
- // Check that scaling works when source and destination don't alias
- image::ScaleUpToPOT(kWidth, kHeight, format, kScaleUPDataNPOT, data.get(),
- 4 * 4);
- EXPECT_EQ(0, memcmp(data.get(), kScaleUPDataPOT, dst_size));
-
- // Check that scaling works when source and destination do alias
- memset(data.get(), 0, dst_size);
- memcpy(data.get(), kScaleUPDataNPOT, src_size);
- image::ScaleUpToPOT(kWidth, kHeight, format, data.get(), data.get(), 4 * 4);
- EXPECT_EQ(0, memcmp(data.get(), kScaleUPDataPOT, dst_size));
-}
-
-// NOTE: untested ffile types are:
-// png grayscale textures
-// dds cube maps
-// dds mipmapped cube maps
-// dds 1D textures
-// dds 3D textures
-
-
-static const uint8 kMipmapDataPOT[] = {
- // This is a 4x4 image
- 0x7D, 0xE4, 0x0F, 0xff, 0x71, 0x7B, 0x9C, 0xff,
- 0xDD, 0xF0, 0x9D, 0xff, 0xFA, 0x08, 0x49, 0xff,
- 0xEA, 0x28, 0xF6, 0xff, 0x73, 0x10, 0x64, 0xff,
- 0x8B, 0x36, 0x58, 0xff, 0x7A, 0x3E, 0x21, 0xff,
- 0x64, 0xCE, 0xB1, 0xff, 0x36, 0x4D, 0xC5, 0xff,
- 0xF3, 0x99, 0x7E, 0xff, 0x5C, 0x56, 0x1E, 0xff,
- 0x59, 0x8C, 0x41, 0xff, 0x39, 0x24, 0x1B, 0xff,
- 0x5D, 0x4D, 0x96, 0xff, 0x5E, 0xF8, 0x8B, 0xff,
- // Followed by its 2x2 mip level
- 0x92, 0x65, 0x81, 0xff, 0xb7, 0x5b, 0x57, 0xff,
- 0x4b, 0x72, 0x74, 0xff, 0x82, 0x8d, 0x6f, 0xff,
- // Followed by its 1x1 mip level
- 0x85, 0x6f, 0x6e, 0xff,
-};
-
-// Generates mip-maps from a known power-of-two image, compare with expected
-// results.
-TEST_F(ImageTest, GenerateMipmapsPOTUInt8) {
- const unsigned int kWidth = 4;
- const unsigned int kHeight = 4;
- const Texture::Format format = Texture::ARGB8;
- unsigned int mipmaps = image::ComputeMipMapCount(kWidth, kHeight);
- EXPECT_EQ(3u, mipmaps);
- size_t size = image::ComputeMipChainSize(kWidth, kHeight, format, mipmaps);
- ASSERT_EQ(sizeof(kMipmapDataPOT), size);
- scoped_array<uint8> data(new uint8[size]);
- ASSERT_TRUE(data.get() != NULL);
- // Copy first level into the buffer.
- size_t base_size = image::ComputeMipChainSize(kWidth, kHeight, format, 1);
- memcpy(data.get(), kMipmapDataPOT, base_size);
- image::GenerateMipmap(
- kWidth, kHeight, format,
- data.get(), image::ComputeMipPitch(format, 0, kWidth),
- data.get() + image::ComputeMipChainSize(kWidth, kHeight, format, 1),
- image::ComputeMipPitch(format, 1, kWidth));
- image::GenerateMipmap(
- image::ComputeMipDimension(1, kWidth),
- image::ComputeMipDimension(1, kHeight),
- format,
- data.get() + image::ComputeMipChainSize(kWidth, kHeight, format, 1),
- image::ComputeMipPitch(format, 1, kWidth),
- data.get() + image::ComputeMipChainSize(kWidth, kHeight, format, 2),
- image::ComputeMipPitch(format, 2, kWidth));
- // Check the result.
- EXPECT_EQ(0, memcmp(data.get(), kMipmapDataPOT, size));
-}
-
-TEST_F(ImageTest, GenerateMipmapsPOTFloat) {
- static const float original[] = { 0.0f, 2.0f, 3.0f, 5.0f, };
- static const float expected_mip1[] = { 1.0f, 4.0f, };
- static const float expected_mip2[] = { 2.5f, };
-
- const unsigned int kWidth = 4;
- const unsigned int kHeight = 1;
- const Texture::Format kFormat = Texture::R32F;
- unsigned int mipmaps = image::ComputeMipMapCount(kWidth, kHeight);
- EXPECT_EQ(3u, mipmaps);
- float mip1[2 + 1];
- float mip2[1 + 1];
- // Put sentinels at the ends
- const float kSentinel = 123.12345f;
- mip1[2] = kSentinel;
- mip2[1] = kSentinel;
- image::GenerateMipmap(
- kWidth, kHeight, kFormat,
- original, image::ComputeMipPitch(kFormat, 0, kWidth),
- mip1,
- image::ComputeMipPitch(kFormat, 1, kWidth));
- image::GenerateMipmap(
- image::ComputeMipDimension(1, kWidth),
- image::ComputeMipDimension(1, kHeight),
- kFormat,
- mip1,
- image::ComputeMipPitch(kFormat, 1, kWidth),
- mip2,
- image::ComputeMipPitch(kFormat, 2, kWidth));
- // Check the result.
- EXPECT_TRUE(CompareFloats(mip1, expected_mip1, arraysize(expected_mip1)));
- EXPECT_TRUE(CompareFloats(mip2, expected_mip2, arraysize(expected_mip2)));
- EXPECT_EQ(mip1[2], kSentinel);
- EXPECT_EQ(mip2[1], kSentinel);
-}
-
-TEST_F(ImageTest, GenerateMipmapsPOTHalf) {
- static const float original_f[] = {
- 0.0f, 0.0f, 0.0f, 0.0f,
- 2.0f, 2.0f, 2.0f, 2.0f,
- 3.0f, 3.0f, 3.0f, 3.0f,
- 5.0f, 5.0f, 5.0f, 5.0f,
- };
- static const float expected_mip1_f[] = {
- 1.0f, 1.0f, 1.0f, 1.0f,
- 4.0f, 4.0f, 4.0f, 4.0f,
- };
- static const float expected_mip2_f[] = {
- 2.5f, 2.5f, 2.5f, 2.5f,
- };
-
- uint16 original[arraysize(original_f)];
- uint16 expected_mip1[arraysize(expected_mip1_f)];
- uint16 expected_mip2[arraysize(expected_mip2_f)];
-
- ConvertToHalf(original_f, arraysize(original_f), original);
- ConvertToHalf(expected_mip1_f, arraysize(expected_mip1_f), expected_mip1);
- ConvertToHalf(expected_mip2_f, arraysize(expected_mip2_f), expected_mip2);
-
- const unsigned int kWidth = 4;
- const unsigned int kHeight = 1;
- const Texture::Format kFormat = Texture::ABGR16F;
- unsigned int mipmaps = image::ComputeMipMapCount(kWidth, kHeight);
- EXPECT_EQ(3u, mipmaps);
- uint16 mip1[2 * 4 + 1];
- uint16 mip2[1 * 4 + 1];
- // Put sentinels at the ends
- const float kSentinel = 123.12345f;
- uint16 sentinel = Vectormath::Aos::FloatToHalf(kSentinel);
- mip1[2 * 4] = sentinel;
- mip2[1 * 4] = sentinel;
- image::GenerateMipmap(
- kWidth, kHeight, kFormat,
- original, image::ComputeMipPitch(kFormat, 0, kWidth),
- mip1,
- image::ComputeMipPitch(kFormat, 1, kWidth));
- image::GenerateMipmap(
- image::ComputeMipDimension(1, kWidth),
- image::ComputeMipDimension(1, kHeight),
- kFormat,
- mip1,
- image::ComputeMipPitch(kFormat, 1, kWidth),
- mip2,
- image::ComputeMipPitch(kFormat, 2, kWidth));
- // Check the result.
- EXPECT_TRUE(CompareHalfs(mip1, expected_mip1, arraysize(expected_mip1)));
- EXPECT_TRUE(CompareHalfs(mip2, expected_mip2, arraysize(expected_mip2)));
- EXPECT_EQ(mip1[2 * 4], sentinel);
- EXPECT_EQ(mip2[1 * 4], sentinel);
-}
-
-static const uint8 kMipmapDataNPOT[] = {
- // This is a 7x7 image
- 0x0d, 0x16, 0x68, 0x1b, 0xe6, 0x09, 0x89, 0x55,
- 0xda, 0x28, 0x56, 0x55, 0x3e, 0x00, 0x6f, 0x16,
- 0x98, 0x11, 0x50, 0x72, 0xe7, 0x17, 0x24, 0xca,
- 0x05, 0xe9, 0x92, 0x43, 0xd6, 0xc4, 0x57, 0xcd,
- 0x34, 0x9b, 0x86, 0xcf, 0x50, 0x65, 0xc4, 0x83,
- 0xaf, 0xa3, 0xaa, 0xe3, 0x7c, 0xab, 0x5f, 0x08,
- 0xc1, 0x2e, 0xd1, 0xe9, 0xa8, 0x2b, 0x56, 0x64,
- 0x12, 0x74, 0x92, 0x56, 0x30, 0x16, 0xa0, 0x03,
- 0x5a, 0x3a, 0x88, 0xb9, 0xe8, 0xa3, 0xfd, 0xf6,
- 0xa1, 0x3b, 0x7b, 0x2d, 0xfd, 0x71, 0xc0, 0x0b,
- 0x22, 0x31, 0x41, 0x5a, 0x45, 0x6f, 0x6b, 0x1b,
- 0x10, 0x5a, 0x16, 0x6e, 0x02, 0x89, 0x12, 0xb1,
- 0x67, 0xfc, 0x43, 0x78, 0xc0, 0x55, 0x59, 0xa3,
- 0xf8, 0xe2, 0x6b, 0xb7, 0xad, 0x5f, 0x3c, 0x14,
- 0xe1, 0x0e, 0x84, 0x89, 0x25, 0xa7, 0xea, 0xc6,
- 0x63, 0x20, 0xf9, 0x84, 0xa1, 0xcd, 0x62, 0x0f,
- 0x22, 0xab, 0x59, 0xde, 0xbd, 0xfa, 0xab, 0x4d,
- 0xca, 0x07, 0x85, 0xdf, 0x83, 0x23, 0x80, 0x8b,
- 0x5e, 0xe4, 0x57, 0x45, 0x81, 0x34, 0x52, 0x65,
- 0xf0, 0x14, 0x32, 0x33, 0xfe, 0xe4, 0x31, 0x90,
- 0x15, 0x51, 0x57, 0x89, 0xed, 0xcf, 0x88, 0xc9,
- 0x7b, 0xbb, 0xc6, 0x41, 0xd5, 0x93, 0x7c, 0x65,
- 0x39, 0x80, 0x20, 0xa2, 0xe5, 0xca, 0x9b, 0x7e,
- 0xb2, 0x1f, 0x0d, 0xdc, 0x5c, 0xab, 0x6b, 0x5b,
- 0xc5, 0x57, 0xc0, 0xd2,
- // Followed by its 3x3 mip level
- 0x75, 0x58, 0x7b, 0x76, 0x8a, 0x54, 0x85, 0x6f,
- 0x93, 0x56, 0x74, 0x7d, 0x3f, 0x58, 0x7a, 0x64,
- 0x7a, 0x90, 0x75, 0x8f, 0xb4, 0x7c, 0x71, 0x6b,
- 0x84, 0x84, 0x85, 0x6c, 0xb1, 0x73, 0x4f, 0x7c,
- 0x97, 0x87, 0x78, 0xa2,
- // Followed by its 1x1 mip level
- 0x88, 0x6e, 0x75, 0x7a,
-};
-
-// Generates mip-maps from a known non-power-of-two image, compare with expected
-// results.
-TEST_F(ImageTest, GenerateMipmapsNPOT) {
- const unsigned int kWidth = 7;
- const unsigned int kHeight = 7;
- const Texture::Format format = Texture::ARGB8;
- unsigned int mipmaps = image::ComputeMipMapCount(kWidth, kHeight);
- EXPECT_EQ(3u, mipmaps);
- size_t size = image::ComputeMipChainSize(kWidth, kHeight, format, mipmaps);
- ASSERT_EQ(sizeof(kMipmapDataNPOT), size);
- scoped_array<uint8> data(new uint8[size]);
- ASSERT_TRUE(data.get() != NULL);
- // Copy first level into the buffer.
- size_t base_size = image::ComputeMipChainSize(kWidth, kHeight, format, 1);
- memcpy(data.get(), kMipmapDataNPOT, base_size);
- image::GenerateMipmap(
- kWidth, kHeight, format,
- data.get(), image::ComputeMipPitch(format, 0, kWidth),
- data.get() + image::ComputeMipChainSize(kWidth, kHeight, format, 1),
- image::ComputeMipPitch(format, 1, kWidth));
- image::GenerateMipmap(
- image::ComputeMipDimension(1, kWidth),
- image::ComputeMipDimension(1, kHeight),
- format,
- data.get() + image::ComputeMipChainSize(kWidth, kHeight, format, 1),
- image::ComputeMipPitch(format, 1, kWidth),
- data.get() + image::ComputeMipChainSize(kWidth, kHeight, format, 2),
- image::ComputeMipPitch(format, 2, kWidth));
- // Check the result.
- EXPECT_EQ(0, memcmp(data.get(), kMipmapDataNPOT, size));
-}
-
-// Checks that filenames are detected as the correct type.
-TEST_F(ImageTest, GetFileTypeFromFilename) {
- EXPECT_EQ(image::TGA, image::GetFileTypeFromFilename("foo.tga"));
- EXPECT_EQ(image::TGA, image::GetFileTypeFromFilename("BAR.TGA"));
- EXPECT_EQ(image::PNG, image::GetFileTypeFromFilename("foo.png"));
- EXPECT_EQ(image::PNG, image::GetFileTypeFromFilename("BAR.PNG"));
- EXPECT_EQ(image::JPEG, image::GetFileTypeFromFilename("foo.jpeg"));
- EXPECT_EQ(image::JPEG, image::GetFileTypeFromFilename("BAR.JPEG"));
- EXPECT_EQ(image::JPEG, image::GetFileTypeFromFilename("foo.jpg"));
- EXPECT_EQ(image::JPEG, image::GetFileTypeFromFilename("BAR.JPG"));
- EXPECT_EQ(image::JPEG, image::GetFileTypeFromFilename("foo.jpe"));
- EXPECT_EQ(image::JPEG, image::GetFileTypeFromFilename("BAR.JPE"));
- EXPECT_EQ(image::DDS, image::GetFileTypeFromFilename("foo.dds"));
- EXPECT_EQ(image::DDS, image::GetFileTypeFromFilename("BAR.DDS"));
- EXPECT_EQ(image::UNKNOWN, image::GetFileTypeFromFilename("foo.bar"));
- EXPECT_EQ(image::UNKNOWN, image::GetFileTypeFromFilename("FOO.BAR"));
-}
-
-// Checks that mime types are detected as the correct type.
-TEST_F(ImageTest, GetFileTypeFromMimeType) {
- EXPECT_EQ(image::PNG, image::GetFileTypeFromMimeType("image/png"));
- EXPECT_EQ(image::JPEG, image::GetFileTypeFromMimeType("image/jpeg"));
- EXPECT_EQ(image::UNKNOWN, image::GetFileTypeFromFilename("text/plain"));
- EXPECT_EQ(image::UNKNOWN,
- image::GetFileTypeFromFilename("application/x-123"));
-}
-
-TEST_F(ImageTest, LanczosScaleFloat) {
- static const float original[] = { 0.0f, 2.0f, 3.0f, 5.0f, };
- static const float expected_mip1[] = { 0.84352076f, 4.1564794f, };
- static const float expected_mip2[] = { 2.5f, };
-
- const unsigned int kWidth = 4;
- const unsigned int kHeight = 1;
- const Texture::Format kFormat = Texture::R32F;
- unsigned int mipmaps = image::ComputeMipMapCount(kWidth, kHeight);
- EXPECT_EQ(3u, mipmaps);
- float mip1[2 + 1];
- float mip2[1 + 1];
- // Put sentinels at the ends
- const float kSentinel = 123.12345f;
- mip1[2] = kSentinel;
- mip2[1] = kSentinel;
- image::LanczosScale(
- kFormat,
- original, image::ComputeMipPitch(kFormat, 0, kWidth),
- 0, 0, 4, 1,
- mip1, image::ComputeMipPitch(kFormat, 1, kWidth),
- 0, 0, 2, 1,
- 1);
- image::LanczosScale(
- kFormat,
- mip1,
- image::ComputeMipPitch(kFormat, 1, kWidth),
- 0, 0, 2, 1,
- mip2, image::ComputeMipPitch(kFormat, 2, kWidth),
- 0, 0, 1, 1,
- 1);
- // Check the result.
- EXPECT_TRUE(CompareFloats(mip1, expected_mip1, arraysize(expected_mip1)));
- EXPECT_TRUE(CompareFloats(mip2, expected_mip2, arraysize(expected_mip2)));
- EXPECT_EQ(mip1[2], kSentinel);
- EXPECT_EQ(mip2[1], kSentinel);
-}
-
-TEST_F(ImageTest, LanczosScaleHalf) {
- static const uint16 original[] = {
- 0x0000, 0x0000, 0x0000, 0x0000,
- 0x4000, 0x4000, 0x4000, 0x4000,
- 0x4200, 0x4200, 0x4200, 0x4200,
- 0x4500, 0x4500, 0x4500, 0x4500,
- };
- static const uint16 expected_mip1[] = {
- 0x3abf, 0x3abf, 0x3abf, 0x3abf,
- 0x4428, 0x4428, 0x4428, 0x4428,
- };
- static const uint16 expected_mip2[] = {
- 0x40ff, 0x40ff, 0x40ff, 0x40ff,
- };
-
- const unsigned int kWidth = 4;
- const unsigned int kHeight = 1;
- const Texture::Format kFormat = Texture::ABGR16F;
- unsigned int mipmaps = image::ComputeMipMapCount(kWidth, kHeight);
- EXPECT_EQ(3u, mipmaps);
- uint16 mip1[2 * 4 + 1];
- uint16 mip2[1 * 4 + 1];
- // Put sentinels at the ends
- const float kSentinel = 123.12345f;
- uint16 sentinel = Vectormath::Aos::FloatToHalf(kSentinel);
- mip1[2 * 4] = sentinel;
- mip2[1 * 4] = sentinel;
- image::LanczosScale(
- kFormat,
- original, image::ComputeMipPitch(kFormat, 0, kWidth),
- 0, 0, 4, 1,
- mip1, image::ComputeMipPitch(kFormat, 1, kWidth),
- 0, 0, 2, 1,
- 4);
- image::LanczosScale(
- kFormat,
- mip1,
- image::ComputeMipPitch(kFormat, 1, kWidth),
- 0, 0, 2, 1,
- mip2, image::ComputeMipPitch(kFormat, 2, kWidth),
- 0, 0, 1, 1,
- 4);
- // Check the result.
- EXPECT_TRUE(CompareHalfs(mip1, expected_mip1, arraysize(expected_mip1)));
- EXPECT_TRUE(CompareHalfs(mip2, expected_mip2, arraysize(expected_mip2)));
- EXPECT_EQ(mip1[2 * 4], sentinel);
- EXPECT_EQ(mip2[1 * 4], sentinel);
-}
-
-TEST_F(ImageTest, AdjustForSetRect) {
- int src_y = 1;
- int src_pitch = 2;
- int dst_y = 3;
- int dst_height = 10;
- // Different widths
- EXPECT_FALSE(image::AdjustForSetRect(&src_y, 10, 10, &src_pitch,
- &dst_y, 11, &dst_height));
- // Different heights
- EXPECT_FALSE(image::AdjustForSetRect(&src_y, 10, 11, &src_pitch,
- &dst_y, 10, &dst_height));
- // width < 0
- EXPECT_FALSE(image::AdjustForSetRect(&src_y, -10, 10, &src_pitch,
- &dst_y, -10, &dst_height));
- // SH > 0, DH > 0
- EXPECT_TRUE(image::AdjustForSetRect(&src_y, 10, 10, &src_pitch,
- &dst_y, 10, &dst_height));
- EXPECT_EQ(1, src_y);
- EXPECT_EQ(2, src_pitch);
- EXPECT_EQ(3, dst_y);
- EXPECT_EQ(10, dst_height);
- // SH > 0, DH < 0
- dst_y = 9;
- dst_height = -10;
- EXPECT_TRUE(image::AdjustForSetRect(&src_y, 10, 10, &src_pitch,
- &dst_y, 10, &dst_height));
- EXPECT_EQ(10, src_y);
- EXPECT_EQ(-2, src_pitch);
- EXPECT_EQ(0, dst_y);
- EXPECT_EQ(10, dst_height);
- // SH < 0, DH < 0
- src_y = 10;
- src_pitch = 2;
- dst_y = 15;
- dst_height = -10;
- EXPECT_TRUE(image::AdjustForSetRect(&src_y, 10, -10, &src_pitch,
- &dst_y, 10, &dst_height));
- EXPECT_EQ(1, src_y);
- EXPECT_EQ(2, src_pitch);
- EXPECT_EQ(6, dst_y);
- EXPECT_EQ(10, dst_height);
- // SH < 0, DH > 0
- src_y = 10;
- src_pitch = 2;
- dst_y = 3;
- dst_height = 10;
- EXPECT_TRUE(image::AdjustForSetRect(&src_y, 10, -10, &src_pitch,
- &dst_y, 10, &dst_height));
- EXPECT_EQ(10, src_y);
- EXPECT_EQ(-2, src_pitch);
- EXPECT_EQ(3, dst_y);
- EXPECT_EQ(10, dst_height);
-}
-
-} // namespace
-
-
diff --git a/o3d/core/cross/imain_thread_task_poster.cc b/o3d/core/cross/imain_thread_task_poster.cc
deleted file mode 100644
index 5ee8b5e..0000000
--- a/o3d/core/cross/imain_thread_task_poster.cc
+++ /dev/null
@@ -1,40 +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 "core/cross/imain_thread_task_poster.h"
-
-namespace o3d {
-
-const InterfaceId IMainThreadTaskPoster::kInterfaceId =
- InterfaceTraits<IMainThreadTaskPoster>::kInterfaceId;
-
-} // namespace o3d
diff --git a/o3d/core/cross/imain_thread_task_poster.h b/o3d/core/cross/imain_thread_task_poster.h
deleted file mode 100644
index cd3d26e..0000000
--- a/o3d/core/cross/imain_thread_task_poster.h
+++ /dev/null
@@ -1,57 +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_CORE_CROSS_IMAIN_THREAD_TASK_POSTER_H_
-#define O3D_CORE_CROSS_IMAIN_THREAD_TASK_POSTER_H_
-
-#include "base/task.h"
-#include "core/cross/service_locator.h"
-
-namespace o3d {
-
-// Allows tasks to be posted from one thread to the main thread.
-class IMainThreadTaskPoster {
- public:
- static const InterfaceId kInterfaceId;
-
- IMainThreadTaskPoster() {}
- virtual ~IMainThreadTaskPoster() {}
-
- virtual bool IsSupported() = 0;
- virtual void PostTask(Task* task) = 0;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(IMainThreadTaskPoster);
-};
-}
-
-#endif // O3D_CORE_CROSS_IMAIN_THREAD_TASK_POSTER_H_
diff --git a/o3d/core/cross/install_check.h b/o3d/core/cross/install_check.h
deleted file mode 100644
index 2cca68a..0000000
--- a/o3d/core/cross/install_check.h
+++ /dev/null
@@ -1,51 +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 declarations for platform- and renderer-specific startup
-// and check code.
-
-#ifndef O3D_CORE_CROSS_INSTALL_CHECK_H_
-#define O3D_CORE_CROSS_INSTALL_CHECK_H_
-
-#include <string>
-
-namespace o3d {
-
-/**
- * Checks to see if all libraries needed by the renderer are installed, and does
- * any platform- and renderer-specific initialization needed to to that check.
- */
-bool RendererInstallCheck(std::string *error);
-
-} // o3d
-
-#endif // O3D_CORE_CROSS_INSTALL_CHECK_H_
diff --git a/o3d/core/cross/lost_resource_callback.h b/o3d/core/cross/lost_resource_callback.h
deleted file mode 100644
index afb5ec3..0000000
--- a/o3d/core/cross/lost_resource_callback.h
+++ /dev/null
@@ -1,45 +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 definition of the callback for lost resources.
-
-#ifndef O3D_CORE_CROSS_LOST_RESOURCE_CALLBACK_H_
-#define O3D_CORE_CROSS_LOST_RESOURCE_CALLBACK_H_
-
-namespace o3d {
-
-typedef NonRecursiveClosureManager LostResourcesCallbackManager;
-typedef LostResourcesCallbackManager::ClosureType LostResourcesCallback;
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_LOST_RESOURCE_CALLBACK_H_
diff --git a/o3d/core/cross/material.cc b/o3d/core/cross/material.cc
deleted file mode 100644
index 64d8ce0..0000000
--- a/o3d/core/cross/material.cc
+++ /dev/null
@@ -1,66 +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 definition of Material.
-
-#include "core/cross/material.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Material, ParamObject);
-O3D_DEFN_CLASS(ParamMaterial, RefParamBase);
-
-const char* Material::kStateParamName =
- O3D_STRING_CONSTANT("state");
-const char* Material::kEffectParamName =
- O3D_STRING_CONSTANT("effect");
-const char* Material::kDrawListParamName =
- O3D_STRING_CONSTANT("drawList");
-
-Material::Material(ServiceLocator* service_locator)
- : ParamObject(service_locator),
- weak_pointer_manager_(this) {
- RegisterParamRef(kStateParamName, &state_param_ref_);
- RegisterParamRef(kEffectParamName, &effect_param_ref_);
- RegisterParamRef(kDrawListParamName, &draw_list_param_);
-}
-
-ObjectBase::Ref Material::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new Material(service_locator));
-}
-
-ObjectBase::Ref ParamMaterial::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamMaterial(service_locator, false, false));
-}
-
-} // namespace o3d
-
diff --git a/o3d/core/cross/material.h b/o3d/core/cross/material.h
deleted file mode 100644
index d2760b8..0000000
--- a/o3d/core/cross/material.h
+++ /dev/null
@@ -1,127 +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 Material declaration.
-
-#ifndef O3D_CORE_CROSS_MATERIAL_H_
-#define O3D_CORE_CROSS_MATERIAL_H_
-
-#include "core/cross/param_object.h"
-#include "core/cross/state.h"
-#include "core/cross/effect.h"
-#include "core/cross/draw_list.h"
-
-namespace o3d {
-
-// A Material represents an Effect with a specific set of parameters. For
-// example a Lambert effect with a "diffuseColor" set to blue vs a Lambert
-// effect with "diffuseColor" set to red. Note that a material MUST have its
-// draw_list set in order for objects using it to render.
-class Material : public ParamObject {
- public:
- typedef SmartPointer<Material> Ref;
- typedef WeakPointer<Material> WeakPointerType;
-
- // Names of Material Params.
- static const char* kEffectParamName;
- static const char* kStateParamName;
- static const char* kDrawListParamName;
-
- // Returns the Effect object bound to the Material.
- Effect* effect() const {
- return effect_param_ref_->value();
- }
-
- // Binds an Effect object to the Material.
- void set_effect(Effect *effect) {
- effect_param_ref_->set_value(effect);
- }
-
- // Returns the State object bound to the Material.
- State* state() const {
- return state_param_ref_->value();
- }
-
- // Binds a State object to the Material.
- void set_state(State *state) {
- state_param_ref_->set_value(state);
- }
-
- // Gets the pass list.
- DrawList* draw_list() const {
- return draw_list_param_->value();
- }
-
- // Sets the pass list.
- void set_draw_list(DrawList* value) {
- draw_list_param_->set_value(value);
- }
-
- // Gets a weak pointer to us.
- WeakPointerType GetWeakPointer() const {
- return weak_pointer_manager_.GetWeakPointer();
- }
-
- private:
- explicit Material(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamState::Ref state_param_ref_; // State for material.
- ParamEffect::Ref effect_param_ref_; // Effect for material.
- ParamDrawList::Ref draw_list_param_; // DrawList we will go on.
-
- // Manager for weak pointers to us.
- WeakPointerType::WeakPointerManager weak_pointer_manager_;
-
- O3D_DECL_CLASS(Material, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(Material);
-};
-
-class ParamMaterial : public TypedRefParam<Material> {
- public:
- typedef SmartPointer<ParamMaterial> Ref;
-
- ParamMaterial(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedRefParam<Material>(service_locator, dynamic, read_only) {
- }
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamMaterial, RefParamBase)
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_MATERIAL_H_
diff --git a/o3d/core/cross/material_test.cc b/o3d/core/cross/material_test.cc
deleted file mode 100644
index 24d7a57..0000000
--- a/o3d/core/cross/material_test.cc
+++ /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.
- */
-
-
-// This file implements unit tests for class Material.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/material.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/semantic_manager.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/transformation_context.h"
-
-namespace o3d {
-
-class MaterialTest : public testing::Test {
- protected:
-
- MaterialTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- TransformationContext* transformation_context_;
- SemanticManager* semantic_manager_;
- Pack *pack_;
-};
-
-void MaterialTest::SetUp() {
- transformation_context_ = new TransformationContext(g_service_locator);
- semantic_manager_ = new SemanticManager(g_service_locator);
- pack_ = object_manager_->CreatePack();
-}
-
-void MaterialTest::TearDown() {
- pack_->Destroy();
- delete semantic_manager_;
- delete transformation_context_;
-}
-
-// Test the basic operations of class Material.
-TEST_F(MaterialTest, Basic) {
- Material* material = pack()->Create<Material>();
- // Check that material got created.
- EXPECT_TRUE(material != NULL);
-
- // Check that its state and effect are not set.
- EXPECT_TRUE(material->effect() == NULL);
- EXPECT_TRUE(material->state() == NULL);
-
- // Check that the default params got created.
- Param* effect_param = material->GetParam<ParamEffect>(
- Material::kEffectParamName);
- Param* state_param = material->GetParam<ParamState>(
- Material::kStateParamName);
- EXPECT_TRUE(effect_param != NULL);
- EXPECT_TRUE(state_param != NULL);
-
- // Check that if we set one by accessor the param is effected
- State* state = pack()->Create<State>();
- ASSERT_TRUE(state != NULL);
- ParamState* typed_state_param = down_cast<ParamState*>(state_param);
- material->set_state(state);
- EXPECT_EQ(state, typed_state_param->value());
-
- // Check that if we set one by param the accessor is effected
- Effect* effect = pack()->Create<Effect>();
- ASSERT_TRUE(effect != NULL);
- ParamEffect* typed_effect_param = down_cast<ParamEffect*>(effect_param);
- ASSERT_TRUE(typed_effect_param != NULL);
- typed_effect_param->set_value(effect);
- EXPECT_EQ(effect, material->effect());
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/math_types.h b/o3d/core/cross/math_types.h
deleted file mode 100644
index c0c01bf..0000000
--- a/o3d/core/cross/math_types.h
+++ /dev/null
@@ -1,77 +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 of various math types.
-
-#ifndef O3D_CORE_CROSS_MATH_TYPES_H_
-#define O3D_CORE_CROSS_MATH_TYPES_H_
-
-#include "third_party/vectormath/files/vectormathlibrary/include/vectormath/scalar/cpp/vectormath_aos.h" // NOLINT
-
-namespace o3d {
-
-// 3d-vector
-//
-typedef Vectormath::Aos::Vector3 Vector3;
-
-// 4d-vector
-//
-typedef Vectormath::Aos::Vector4 Vector4;
-
-// Point
-//
-typedef Vectormath::Aos::Point3 Point3;
-
-// Quaternion
-//
-typedef Vectormath::Aos::Quat Quaternion;
-
-// 3x3 rotation matrix
-//
-typedef Vectormath::Aos::Matrix3 Matrix3;
-
-// 4x4 matrix
-//
-typedef Vectormath::Aos::Matrix4 Matrix4;
-
-// Homogeneous transformation matrix
-//
-typedef Vectormath::Aos::Transform3 Transform3;
-
-// Data types for passing data around in the scenegraph
-typedef float Float;
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_MATH_TYPES_H_
-
-
diff --git a/o3d/core/cross/math_utilities.cc b/o3d/core/cross/math_utilities.cc
deleted file mode 100644
index fd3f498..0000000
--- a/o3d/core/cross/math_utilities.cc
+++ /dev/null
@@ -1,233 +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.
- */
-
-
-// The file contains defintions of various math related functions.
-
-#include <math.h>
-#include "core/cross/math_utilities.h"
-
-static const float kEpsilon = 0.00001f;
-
-namespace Vectormath {
-namespace Aos {
-
-// Creates a perspective projection matrix.
-Matrix4 CreatePerspectiveMatrix(float vertical_field_of_view_radians,
- float aspect,
- float z_near,
- float z_far) {
- float dz = z_near - z_far;
- if (aspect > kEpsilon && fabsf(dz) > kEpsilon) {
- float vertical_scale = 1.0f / tanf(vertical_field_of_view_radians / 2.0f);
- float horizontal_scale = vertical_scale / aspect;
- return Matrix4(Vector4(horizontal_scale, 0.0f, 0.0f, 0.0f),
- Vector4(0.0f, vertical_scale, 0.0f, 0.0f),
- Vector4(0.0f, 0.0f, z_far / dz, -1.0f),
- Vector4(0.0f, 0.0f, z_near * z_far / dz, 0.0f));
- }
- return Matrix4::identity();
-}
-
-// Creates an arbitrary frustum projection matrix.
-Matrix4 CreateFrustumMatrix(float left,
- float right,
- float bottom,
- float top,
- float z_near,
- float z_far) {
- float dx = (right - left);
- float dy = (top - bottom);
- float dz = (z_near - z_far);
-
- if (fabsf(dx) > kEpsilon && fabsf(dy) > kEpsilon && fabsf(dz) > kEpsilon) {
- return Matrix4(
- Vector4(2.0f * z_near / dx, 0.0f, 0.0f, 0.0f),
- Vector4(0.0f, 2.0f * z_near / dy, 0.0f, 0.0f),
- Vector4((left + right) / dx, (top + bottom) / dy, z_far / dz, -1.0f),
- Vector4(0.0f, 0.0f, z_near * z_far / dz, 0.0f));
- }
- return Matrix4::identity();
-}
-
-// Creates an orthographic projection matrix.
-Matrix4 CreateOrthographicMatrix(float left,
- float right,
- float bottom,
- float top,
- float z_near,
- float z_far) {
- if (fabsf(left - right) > kEpsilon &&
- fabsf(top - bottom) > kEpsilon &&
- fabsf(z_near - z_far) > kEpsilon) {
- return Matrix4(
- Vector4(2.0f / (right - left), 0.0f, 0.0f, 0.0f),
- Vector4(0.0f, 2.0f / (top - bottom), 0.0f, 0.0f),
- Vector4(0.0f, 0.0f, 1.0f / (z_near - z_far), 0.0f),
- Vector4((left + right) / (left - right),
- (top + bottom) / (bottom - top),
- z_near / (z_near - z_far),
- 1.0f));
- }
- return Matrix4::identity();
-}
-
-namespace {
-
-// -15 stored using a single precision bias of 127
-const unsigned kHalfFloatMinBiasedExpAsSingleFpExponent = 0x38000000u;
-// max exponent value in single precision that will be converted
-// to Inf or Nan when stored as a half-float
-const unsigned kHalfFloatMaxBiasedExpAsSingleFpExponent = 0x47800000u;
-// 255 is the max exponent biased value
-const unsigned kFloatMaxBiasedExponent = (0xFFu << 23);
-const unsigned kHalfFloatMaxBiasedExponent = (0x1Fu << 10);
-
-} // anonymous namespace
-
-uint16 FloatToHalf(float value) {
- union FloatAndUInt {
- float f;
- unsigned u;
- } temp;
- temp.f = value;
- unsigned v = temp.u;
- unsigned sign = static_cast<uint16>(v >> 31);
- unsigned mantissa;
- unsigned exponent;
- uint16 half;
-
- // get mantissa
- mantissa = v & ((1 << 23) - 1);
- // get exponent bits
- exponent = v & kFloatMaxBiasedExponent;
- if (exponent >= kHalfFloatMaxBiasedExpAsSingleFpExponent) {
- // check if the original single precision float number is a NaN
- if (mantissa && (exponent == kFloatMaxBiasedExponent)) {
- // we have a single precision NaN
- mantissa = (1 << 23) - 1;
- } else {
- // 16-bit half-float representation stores number as Inf
- mantissa = 0;
- }
- half = (static_cast<uint16>(sign) << 15) |
- static_cast<uint16>(kHalfFloatMaxBiasedExponent) |
- static_cast<uint16>(mantissa >> 13);
- // check if exponent is <= -15
- } else if (exponent <= kHalfFloatMinBiasedExpAsSingleFpExponent) {
- // store a denorm half-float value or zero
- exponent = (kHalfFloatMinBiasedExpAsSingleFpExponent -
- exponent) >> 23;
- mantissa >>= (14 + exponent);
-
- half = (static_cast<uint16>(sign) << 15) |
- static_cast<uint16>(mantissa);
- } else {
- half =
- (static_cast<uint16>(sign) << 15) |
- static_cast<uint16>(
- (exponent - kHalfFloatMinBiasedExpAsSingleFpExponent) >> 13) |
- static_cast<uint16>(mantissa >> 13);
- }
- return half;
-}
-
-float HalfToFloat(uint16 half) {
- unsigned int sign = static_cast<unsigned int>(half >> 15);
- unsigned int mantissa = static_cast<unsigned int>(half & ((1 << 10) - 1));
- unsigned int exponent = static_cast<unsigned int>(
- half & kHalfFloatMaxBiasedExponent);
-
- if (exponent == kHalfFloatMaxBiasedExponent) {
- // we have a half-float NaN or Inf
- // half-float NaNs will be converted to a single precision NaN
- // half-float Infs will be converted to a single precision Inf
- exponent = kFloatMaxBiasedExponent;
- if (mantissa)
- mantissa = (1 << 23) - 1; // set all bits to indicate a NaN
- } else if (exponent == 0x0) {
- // convert half-float zero/denorm to single precision value
- if (mantissa) {
- mantissa <<= 1;
- exponent = kHalfFloatMinBiasedExpAsSingleFpExponent;
- // check for leading 1 in denorm mantissa
- while ((mantissa & (1 << 10)) == 0) {
- // for every leading 0, decrement single precision exponent by 1
- // and shift half-float mantissa value to the left
- mantissa <<= 1;
- exponent -= (1 << 23);
- }
- // clamp the mantissa to 10-bits
- mantissa &= ((1 << 10) - 1);
- // shift left to generate single-precision mantissa of 23-bits
- mantissa <<= 13;
- }
- } else {
- // shift left to generate single-precision mantissa of 23-bits
- mantissa <<= 13;
- // generate single precision biased exponent value
- exponent = (exponent << 13) + kHalfFloatMinBiasedExpAsSingleFpExponent;
- }
-
- union {
- unsigned int int_value;
- float float_value;
- } value;
- value.int_value = (sign << 31) | exponent | mantissa;
- return value.float_value;
-}
-
-} // namespace Vectormath
-} // namespace Aos
-
-namespace o3d {
-float FrobeniusNorm(const Matrix3& matrix) {
- Matrix3 elementsSquared = mulPerElem(matrix, matrix);
- Vector3 ones(1, 1, 1);
- float sumOfElementsSquared = 0.0f;
- for (int i = 0; i < 3; ++i) {
- sumOfElementsSquared += dot(ones, elementsSquared.getCol(i));
- }
- return sqrtf(sumOfElementsSquared);
-}
-
-float FrobeniusNorm(const Matrix4& matrix) {
- Matrix4 elementsSquared = mulPerElem(matrix, matrix);
- Vector4 ones(1, 1, 1, 1);
- float sumOfElementsSquared = 0.0f;
- for (int i = 0; i < 4; ++i) {
- sumOfElementsSquared += dot(ones, elementsSquared.getCol(i));
- }
- return sqrtf(sumOfElementsSquared);
-}
-
-const float kPi = ::acosf(-1.0f);
-} // namespace o3d
diff --git a/o3d/core/cross/math_utilities.h b/o3d/core/cross/math_utilities.h
deleted file mode 100644
index 4ba556e..0000000
--- a/o3d/core/cross/math_utilities.h
+++ /dev/null
@@ -1,85 +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 declarations of various math functions.
-//
-
-#ifndef O3D_CORE_CROSS_MATH_UTILITIES_H_
-#define O3D_CORE_CROSS_MATH_UTILITIES_H_
-
-#include "core/cross/types.h"
-
-namespace Vectormath {
-namespace Aos {
-
-// Creates a perspective projection matrix.
-Matrix4 CreatePerspectiveMatrix(float vertical_field_of_view_radians,
- float aspect,
- float z_near,
- float z_far);
-
-// Creates a frustum projection matrix.
-Matrix4 CreateFrustumMatrix(float left,
- float right,
- float bottom,
- float top,
- float z_near,
- float z_far);
-
-// Creates an orthographic projection matrix.
-Matrix4 CreateOrthographicMatrix(float left,
- float right,
- float bottom,
- float top,
- float z_near,
- float z_far);
-
-// Converts a 32 bit float to a 16 bit float.
-uint16 FloatToHalf(float value);
-// Converts a 16 bit float to a 32 bit float.
-float HalfToFloat(uint16 value);
-} // namespace Vectormath
-} // namespace Aos
-
-namespace o3d {
-// Calculates the Frobenius norm of a 3x3 matrix.
-// See http://en.wikipedia.org/wiki/Matrix_norm
-float FrobeniusNorm(const Matrix3& matrix);
-
-// Calculates the Frobenius norm of a 4x4 matrix.
-// See http://en.wikipedia.org/wiki/Matrix_norm
-float FrobeniusNorm(const Matrix4& matrix);
-
-extern const float kPi;
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_MATH_UTILITIES_H_
diff --git a/o3d/core/cross/math_utilities_test.cc b/o3d/core/cross/math_utilities_test.cc
deleted file mode 100644
index ad57dd3..0000000
--- a/o3d/core/cross/math_utilities_test.cc
+++ /dev/null
@@ -1,48 +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 "tests/common/win/testing_common.h"
-#include "core/cross/math_utilities.h"
-
-namespace o3d {
-
-TEST(TestFrobeniusNormTest, OfMatrix3) {
- Matrix3 matrix(Vector3(1, 2, 3), Vector3(4, 5, 6), Vector3(7, 8, 9));
- ASSERT_NEAR(16.882f, FrobeniusNorm(matrix), 0.001f);
-}
-
-TEST(FrobeniusNormTest, OfMatrix4) {
- Matrix4 matrix(Vector4(1, 2, 3, 4), Vector4(5, 6, 7, 8),
- Vector4(9, 10, 11, 12), Vector4(13, 14, 15, 16));
- ASSERT_NEAR(38.678f, FrobeniusNorm(matrix), 0.001f);
-}
-} // namespace o3d
diff --git a/o3d/core/cross/matrix4_axis_rotation.cc b/o3d/core/cross/matrix4_axis_rotation.cc
deleted file mode 100644
index 062329c..0000000
--- a/o3d/core/cross/matrix4_axis_rotation.cc
+++ /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.
- */
-
-
-// This file contains the definition of class Matrix4AxisRotation.
-
-#include "core/cross/matrix4_axis_rotation.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Matrix4AxisRotation, ParamObject);
-
-const char* Matrix4AxisRotation::kInputMatrixParamName =
- O3D_STRING_CONSTANT("inputMatrix");
-const char* Matrix4AxisRotation::kAxisParamName =
- O3D_STRING_CONSTANT("axis");
-const char* Matrix4AxisRotation::kAngleParamName =
- O3D_STRING_CONSTANT("angle");
-const char* Matrix4AxisRotation::kOutputMatrixParamName =
- O3D_STRING_CONSTANT("outputMatrix");
-
-Matrix4AxisRotation::Matrix4AxisRotation(ServiceLocator* service_locator)
- : ParamObject(service_locator) {
- RegisterParamRef(kInputMatrixParamName, &input_matrix_param_);
- RegisterParamRef(kAxisParamName, &axis_param_);
- RegisterParamRef(kAngleParamName, &angle_param_);
- SlaveParamMatrix4::RegisterParamRef(kOutputMatrixParamName,
- &output_matrix_param_,
- this);
-}
-
-void Matrix4AxisRotation::UpdateOutputs() {
- Matrix4 matrix = input_matrix() * Matrix4::rotation(
- angle_param_->value(),
- Float3ToVector3(axis_param_->value()));
- output_matrix_param_->set_dynamic_value(matrix);
-}
-
-ObjectBase::Ref Matrix4AxisRotation::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new Matrix4AxisRotation(service_locator));
-}
-} // namespace o3d
diff --git a/o3d/core/cross/matrix4_axis_rotation.h b/o3d/core/cross/matrix4_axis_rotation.h
deleted file mode 100644
index 7ac00b2..0000000
--- a/o3d/core/cross/matrix4_axis_rotation.h
+++ /dev/null
@@ -1,105 +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 declaration of class Matrix4AxisRotation.
-
-#ifndef O3D_CORE_CROSS_MATRIX4_AXIS_ROTATION_H_
-#define O3D_CORE_CROSS_MATRIX4_AXIS_ROTATION_H_
-
-#include "core/cross/param_object.h"
-#include "core/cross/param.h"
-#include "core/cross/param_cache.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// Operation to build a rotation matrix from an axis vector and an angle and (if
-// bound) compose it with an input transformation matrix.
-class Matrix4AxisRotation : public ParamObject {
- public:
- typedef SmartPointer<Matrix4AxisRotation> Ref;
- typedef WeakPointer<Matrix4AxisRotation> WeakPointerType;
-
- static const char* kInputMatrixParamName;
- static const char* kAxisParamName;
- static const char* kAngleParamName;
- static const char* kOutputMatrixParamName;
-
- Matrix4 input_matrix() const {
- return input_matrix_param_->value();
- }
-
- void set_input_matrix(const Matrix4& input_matrix) {
- input_matrix_param_->set_value(input_matrix);
- }
-
- Float3 axis() const {
- return axis_param_->value();
- }
-
- void set_axis(const Float3& axis) {
- axis_param_->set_value(axis);
- }
-
- float angle() const {
- return angle_param_->value();
- }
-
- void set_angle(float angle) {
- angle_param_->set_value(angle);
- }
-
- Matrix4 output_matrix() const {
- return output_matrix_param_->value();
- }
-
- void UpdateOutputs();
-
- private:
- typedef SlaveParam<ParamMatrix4, Matrix4AxisRotation> SlaveParamMatrix4;
-
- explicit Matrix4AxisRotation(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamMatrix4::Ref input_matrix_param_;
- ParamFloat3::Ref axis_param_;
- ParamFloat::Ref angle_param_;
- SlaveParamMatrix4::Ref output_matrix_param_;
-
- O3D_DECL_CLASS(Matrix4AxisRotation, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(Matrix4AxisRotation);
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_MATRIX4_AXIS_ROTATION_H_
diff --git a/o3d/core/cross/matrix4_axis_rotation_test.cc b/o3d/core/cross/matrix4_axis_rotation_test.cc
deleted file mode 100644
index 350db64..0000000
--- a/o3d/core/cross/matrix4_axis_rotation_test.cc
+++ /dev/null
@@ -1,83 +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 "tests/common/win/testing_common.h"
-#include "core/cross/math_utilities.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/matrix4_axis_rotation.h"
-#include "core/cross/service_dependency.h"
-
-namespace o3d {
-
-class Matrix4AxisRotationTest : public testing::Test {
- protected:
- Matrix4AxisRotationTest()
- : object_manager_(g_service_locator),
- pack_(NULL),
- rotation_(NULL) {
- }
-
- virtual void SetUp() {
- pack_ = object_manager_->CreatePack();
- rotation_ = pack_->Create<Matrix4AxisRotation>();
- }
-
- virtual void TearDown() {
- pack_->Destroy();
- }
-
- protected:
- ServiceDependency<ObjectManager> object_manager_;
- Pack* pack_;
- Matrix4AxisRotation* rotation_;
-};
-
-TEST_F(Matrix4AxisRotationTest, OutputsInputRotationAsMatrixIfNoParent) {
- rotation_->set_axis(Float3(0, 0, 1));
- rotation_->set_angle(kPi * 0.5f);
- Matrix4 output_matrix = rotation_->output_matrix();
- Matrix4 expected(Vector4(0, 1, 0, 0), Vector4(-1, 0, 0, 0),
- Vector4(0, 0, 1, 0), Vector4(0, 0, 0, 1));
- ASSERT_NEAR(0.0f, FrobeniusNorm(expected - output_matrix), 0.001f);
-}
-
-TEST_F(Matrix4AxisRotationTest, ComposesInputRotationWithParentMatrix) {
- rotation_->set_axis(Float3(0, 0, 1));
- rotation_->set_angle(kPi * 0.5f);
- Matrix4 parent = Matrix4::rotation(kPi * 0.5f, Vector3(0, 0, 1));
- rotation_->set_input_matrix(parent);
- Matrix4 output_matrix = rotation_->output_matrix();
- Matrix4 expected = Matrix4::rotation(kPi, Vector3(0, 0, 1));
- ASSERT_NEAR(0.0f, FrobeniusNorm(expected - output_matrix), 0.001f);
-}
-} // namespace o3d
diff --git a/o3d/core/cross/matrix4_composition.cc b/o3d/core/cross/matrix4_composition.cc
deleted file mode 100644
index 6dc10ed..0000000
--- a/o3d/core/cross/matrix4_composition.cc
+++ /dev/null
@@ -1,66 +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 definition of class Matrix4Composition.
-
-#include "core/cross/matrix4_composition.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Matrix4Composition, ParamObject);
-
-const char* Matrix4Composition::kInputMatrixParamName =
- O3D_STRING_CONSTANT("inputMatrix");
-const char* Matrix4Composition::kLocalMatrixParamName =
- O3D_STRING_CONSTANT("localMatrix");
-const char* Matrix4Composition::kOutputMatrixParamName =
- O3D_STRING_CONSTANT("outputMatrix");
-
-Matrix4Composition::Matrix4Composition(
- ServiceLocator* service_locator)
- : ParamObject(service_locator) {
- RegisterParamRef(kInputMatrixParamName, &input_matrix_param_);
- RegisterParamRef(kLocalMatrixParamName, &local_matrix_param_);
- SlaveParamMatrix4::RegisterParamRef(kOutputMatrixParamName,
- &output_matrix_param_, this);
-}
-
-void Matrix4Composition::UpdateOutputs() {
- Matrix4 output_matrix = input_matrix_param_->value() *
- local_matrix_param_->value();
- output_matrix_param_->set_dynamic_value(output_matrix);
-}
-
-ObjectBase::Ref Matrix4Composition::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new Matrix4Composition(service_locator));
-}
-} // namespace o3d
diff --git a/o3d/core/cross/matrix4_composition.h b/o3d/core/cross/matrix4_composition.h
deleted file mode 100644
index 8d329eb..0000000
--- a/o3d/core/cross/matrix4_composition.h
+++ /dev/null
@@ -1,95 +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 declaration of class Matrix4Composition.
-
-#ifndef O3D_CORE_CROSS_MATRIX4_COMPOSITION_H_
-#define O3D_CORE_CROSS_MATRIX4_COMPOSITION_H_
-
-#include "core/cross/param_object.h"
-#include "core/cross/param.h"
-#include "core/cross/param_cache.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// Operation to hold a local transformation matrix and (if bound) compose it
-// with its parent transformation matrix.
-class Matrix4Composition : public ParamObject {
- public:
- typedef SmartPointer<Matrix4Composition> Ref;
- typedef WeakPointer<Matrix4Composition> WeakPointerType;
-
- static const char* kInputMatrixParamName;
- static const char* kLocalMatrixParamName;
- static const char* kOutputMatrixParamName;
-
- Matrix4 input_matrix() const {
- return input_matrix_param_->value();
- }
-
- void set_input_matrix(const Matrix4& input_matrix) {
- input_matrix_param_->set_value(input_matrix);
- }
-
- Matrix4 local_matrix() const {
- return local_matrix_param_->value();
- }
-
- void set_local_matrix(const Matrix4& axis) {
- local_matrix_param_->set_value(axis);
- }
-
- Matrix4 output_matrix() const {
- return output_matrix_param_->value();
- }
-
- void UpdateOutputs();
-
- private:
- typedef SlaveParam<ParamMatrix4, Matrix4Composition> SlaveParamMatrix4;
-
- explicit Matrix4Composition(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamMatrix4::Ref input_matrix_param_;
- ParamMatrix4::Ref local_matrix_param_;
- SlaveParamMatrix4::Ref output_matrix_param_;
-
- O3D_DECL_CLASS(Matrix4Composition, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(Matrix4Composition);
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_MATRIX4_COMPOSITION_H_
diff --git a/o3d/core/cross/matrix4_composition_test.cc b/o3d/core/cross/matrix4_composition_test.cc
deleted file mode 100644
index 232d72f..0000000
--- a/o3d/core/cross/matrix4_composition_test.cc
+++ /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.
- */
-
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/matrix4_composition.h"
-#include "core/cross/math_utilities.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-
-namespace o3d {
-
-class Matrix4CompositionTest : public testing::Test {
- protected:
- Matrix4CompositionTest()
- : object_manager_(g_service_locator),
- pack_(NULL),
- composition_(NULL) {
- }
-
- virtual void SetUp() {
- pack_ = object_manager_->CreatePack();
- composition_ = pack_->Create<Matrix4Composition>();
- }
-
- virtual void TearDown() {
- pack_->Destroy();
- }
-
- protected:
- ServiceDependency<ObjectManager> object_manager_;
- Pack* pack_;
- Matrix4Composition* composition_;
-};
-
-TEST_F(Matrix4CompositionTest, OutputsInputMatrixIfNoParent) {
- Matrix4 input = Matrix4::scale(Vector3(2, 3, 4));
- composition_->set_local_matrix(input);
- Matrix4 output_matrix = composition_->output_matrix();
- ASSERT_NEAR(0.0f, FrobeniusNorm(input - output_matrix), 0.001f);
-}
-
-TEST_F(Matrix4CompositionTest, ComposesInputMatrixWithParentMatrix) {
- Matrix4 input = Matrix4::scale(Vector3(2, 3, 4));
- composition_->set_local_matrix(input);
- Matrix4 parent = Matrix4::scale(Vector3(3, 4, 5));
- composition_->set_input_matrix(parent);
- Matrix4 output_matrix = composition_->output_matrix();
- Matrix4 expected = Matrix4::scale(Vector3(6, 12, 20));
- ASSERT_NEAR(0.0f, FrobeniusNorm(expected - output_matrix), 0.001f);
-}
-} // namespace o3d
diff --git a/o3d/core/cross/matrix4_scale.cc b/o3d/core/cross/matrix4_scale.cc
deleted file mode 100644
index d08702a..0000000
--- a/o3d/core/cross/matrix4_scale.cc
+++ /dev/null
@@ -1,66 +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 definition of class Matrix4Scale.
-
-#include "core/cross/matrix4_scale.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Matrix4Scale, ParamObject);
-
-const char* Matrix4Scale::kInputMatrixParamName =
- O3D_STRING_CONSTANT("inputMatrix");
-const char* Matrix4Scale::kScaleParamName =
- O3D_STRING_CONSTANT("scale");
-const char* Matrix4Scale::kOutputMatrixParamName =
- O3D_STRING_CONSTANT("outputMatrix");
-
-Matrix4Scale::Matrix4Scale(
- ServiceLocator* service_locator)
- : ParamObject(service_locator) {
- RegisterParamRef(kInputMatrixParamName, &input_matrix_param_);
- RegisterParamRef(kScaleParamName, &scale_param_);
- SlaveParamMatrix4::RegisterParamRef(kOutputMatrixParamName,
- &output_matrix_param_, this);
-}
-
-void Matrix4Scale::UpdateOutputs() {
- Matrix4 matrix = input_matrix() * Matrix4::scale(
- Float3ToVector3(scale_param_->value()));
- output_matrix_param_->set_dynamic_value(matrix);
-}
-
-ObjectBase::Ref Matrix4Scale::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new Matrix4Scale(service_locator));
-}
-} // namespace o3d
diff --git a/o3d/core/cross/matrix4_scale.h b/o3d/core/cross/matrix4_scale.h
deleted file mode 100644
index d67ef95..0000000
--- a/o3d/core/cross/matrix4_scale.h
+++ /dev/null
@@ -1,95 +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 declaration of class Matrix4Scale.
-
-#ifndef O3D_CORE_CROSS_MATRIX4_SCALE_H_
-#define O3D_CORE_CROSS_MATRIX4_SCALE_H_
-
-#include "core/cross/param_object.h"
-#include "core/cross/param.h"
-#include "core/cross/param_cache.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// Operation to build a rotation matrix from an axis vector and a rotation
-// around that axis and an input transformation matrix.
-class Matrix4Scale : public ParamObject {
- public:
- typedef SmartPointer<Matrix4Scale> Ref;
- typedef WeakPointer<Matrix4Scale> WeakPointerType;
-
- static const char* kInputMatrixParamName;
- static const char* kScaleParamName;
- static const char* kOutputMatrixParamName;
-
- Matrix4 input_matrix() const {
- return input_matrix_param_->value();
- }
-
- void set_input_matrix(const Matrix4& input_matrix) {
- input_matrix_param_->set_value(input_matrix);
- }
-
- Float3 scale() const {
- return scale_param_->value();
- }
-
- void set_scale(const Float3& axis) {
- scale_param_->set_value(axis);
- }
-
- Matrix4 output_matrix() const {
- return output_matrix_param_->value();
- }
-
- void UpdateOutputs();
-
- private:
- typedef SlaveParam<ParamMatrix4, Matrix4Scale> SlaveParamMatrix4;
-
- explicit Matrix4Scale(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamMatrix4::Ref input_matrix_param_;
- ParamFloat3::Ref scale_param_;
- SlaveParamMatrix4::Ref output_matrix_param_;
-
- O3D_DECL_CLASS(Matrix4Scale, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(Matrix4Scale);
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_MATRIX4_SCALE_H_
diff --git a/o3d/core/cross/matrix4_scale_test.cc b/o3d/core/cross/matrix4_scale_test.cc
deleted file mode 100644
index b103a52..0000000
--- a/o3d/core/cross/matrix4_scale_test.cc
+++ /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.
- */
-
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/math_utilities.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/matrix4_scale.h"
-#include "core/cross/service_dependency.h"
-
-namespace o3d {
-
-class Matrix4ScaleTest : public testing::Test {
- protected:
- Matrix4ScaleTest()
- : object_manager_(g_service_locator),
- pack_(NULL),
- scale_(NULL) {
- }
-
- virtual void SetUp() {
- pack_ = object_manager_->CreatePack();
- scale_ = pack_->Create<Matrix4Scale>();
- }
-
- virtual void TearDown() {
- pack_->Destroy();
- }
-
- protected:
- ServiceDependency<ObjectManager> object_manager_;
- Pack* pack_;
- Matrix4Scale* scale_;
-};
-
-TEST_F(Matrix4ScaleTest, OutputsInputScaleAsMatrixIfNoParent) {
- scale_->set_scale(Float3(1, 2, 3));
- Matrix4 output_matrix = scale_->output_matrix();
- Matrix4 expected(Vector4(1, 0, 0, 0), Vector4(0, 2, 0, 0),
- Vector4(0, 0, 3, 0), Vector4(0, 0, 0, 1));
- ASSERT_NEAR(0.0f, FrobeniusNorm(expected - output_matrix), 0.001f);
-}
-
-TEST_F(Matrix4ScaleTest, ComposesInputScaleWithParentMatrix) {
- scale_->set_scale(Float3(1, 2, 3));
- Matrix4 parent = Matrix4::scale(Vector3(3, 4, 5));
- scale_->set_input_matrix(parent);
- Matrix4 output_matrix = scale_->output_matrix();
- Matrix4 expected = Matrix4::scale(Vector3(3, 8, 15));
- ASSERT_NEAR(0.0f, FrobeniusNorm(expected - output_matrix), 0.001f);
-}
-} // namespace o3d
diff --git a/o3d/core/cross/matrix4_translation.cc b/o3d/core/cross/matrix4_translation.cc
deleted file mode 100644
index 488b5f4..0000000
--- a/o3d/core/cross/matrix4_translation.cc
+++ /dev/null
@@ -1,65 +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 definition of class Matrix4Translation.
-
-#include "core/cross/matrix4_translation.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Matrix4Translation, ParamObject);
-
-const char* Matrix4Translation::kInputMatrixParamName =
- O3D_STRING_CONSTANT("inputMatrix");
-const char* Matrix4Translation::kTranslationParamName =
- O3D_STRING_CONSTANT("translation");
-const char* Matrix4Translation::kOutputMatrixParamName =
- O3D_STRING_CONSTANT("outputMatrix");
-
-Matrix4Translation::Matrix4Translation(ServiceLocator* service_locator)
- : ParamObject(service_locator) {
- RegisterParamRef(kInputMatrixParamName, &input_matrix_param_);
- RegisterParamRef(kTranslationParamName, &translation_param_);
- SlaveParamMatrix4::RegisterParamRef(kOutputMatrixParamName,
- &output_matrix_param_, this);
-}
-
-void Matrix4Translation::UpdateOutputs() {
- Matrix4 matrix = input_matrix_param_->value() * Matrix4::translation(
- Float3ToVector3(translation_param_->value()));
- output_matrix_param_->set_dynamic_value(matrix);
-}
-
-ObjectBase::Ref Matrix4Translation::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new Matrix4Translation(service_locator));
-}
-} // namespace o3d
diff --git a/o3d/core/cross/matrix4_translation.h b/o3d/core/cross/matrix4_translation.h
deleted file mode 100644
index 0a35768f52..0000000
--- a/o3d/core/cross/matrix4_translation.h
+++ /dev/null
@@ -1,95 +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 declaration of class Matrix4Translation.
-
-#ifndef O3D_CORE_CROSS_MATRIX4_TRANSLATION_H_
-#define O3D_CORE_CROSS_MATRIX4_TRANSLATION_H_
-
-#include "core/cross/param_object.h"
-#include "core/cross/param.h"
-#include "core/cross/param_cache.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// Operation to build a translation matrix from a translation vector and (if
-// bound) compose it with an input transformation matrix.
-class Matrix4Translation : public ParamObject {
- public:
- typedef SmartPointer<Matrix4Translation> Ref;
- typedef WeakPointer<Matrix4Translation> WeakPointerType;
-
- static const char* kInputMatrixParamName;
- static const char* kTranslationParamName;
- static const char* kOutputMatrixParamName;
-
- Matrix4 input_matrix() const {
- return input_matrix_param_->value();
- }
-
- void set_input_matrix(const Matrix4& input_matrix) {
- input_matrix_param_->set_value(input_matrix);
- }
-
- Float3 translation() const {
- return translation_param_->value();
- }
-
- void set_translation(const Float3& axis) {
- translation_param_->set_value(axis);
- }
-
- Matrix4 output_matrix() const {
- return output_matrix_param_->value();
- }
-
- void UpdateOutputs();
-
- private:
- typedef SlaveParam<ParamMatrix4, Matrix4Translation> SlaveParamMatrix4;
-
- explicit Matrix4Translation(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamMatrix4::Ref input_matrix_param_;
- ParamFloat3::Ref translation_param_;
- SlaveParamMatrix4::Ref output_matrix_param_;
-
- O3D_DECL_CLASS(Matrix4Translation, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(Matrix4Translation);
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_MATRIX4_TRANSLATION_H_
diff --git a/o3d/core/cross/matrix4_translation_test.cc b/o3d/core/cross/matrix4_translation_test.cc
deleted file mode 100644
index f9129e8..0000000
--- a/o3d/core/cross/matrix4_translation_test.cc
+++ /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.
- */
-
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/math_utilities.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/matrix4_translation.h"
-
-namespace o3d {
-
-class TranslationTest : public testing::Test {
- protected:
- TranslationTest()
- : object_manager_(g_service_locator),
- pack_(NULL),
- translation_(NULL) {
- }
-
- virtual void SetUp() {
- pack_ = object_manager_->CreatePack();
- translation_ = pack_->Create<Matrix4Translation>();
- }
-
- virtual void TearDown() {
- pack_->Destroy();
- }
-
- protected:
- ServiceDependency<ObjectManager> object_manager_;
- Pack* pack_;
- Matrix4Translation* translation_;
-};
-
-TEST_F(TranslationTest, OutputsInputTranslationAsMatrixIfNoParent) {
- translation_->set_translation(Float3(1, 2, 3));
- Matrix4 output_matrix = translation_->output_matrix();
- Matrix4 expected(Vector4(1, 0, 0, 0), Vector4(0, 1, 0, 0),
- Vector4(0, 0, 1, 0), Vector4(1, 2, 3, 1));
- ASSERT_NEAR(0.0f, FrobeniusNorm(expected - output_matrix), 0.001f);
-}
-
-TEST_F(TranslationTest, ComposesInputTranslationWithParentMatrix) {
- translation_->set_translation(Float3(1, 2, 3));
- Matrix4 parent = Matrix4::translation(Vector3(3, 4, 5));
- translation_->set_input_matrix(parent);
- Matrix4 output_matrix = translation_->output_matrix();
- Matrix4 expected = Matrix4::translation(Vector3(4, 6, 8));
- ASSERT_NEAR(0.0f, FrobeniusNorm(expected - output_matrix), 0.001f);
-}
-} // namespace o3d
diff --git a/o3d/core/cross/message_commands.cc b/o3d/core/cross/message_commands.cc
deleted file mode 100644
index f7c0f7e..0000000
--- a/o3d/core/cross/message_commands.cc
+++ /dev/null
@@ -1,49 +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 string descriptions of various IMC messages for O3D.
-
-#include "core/cross/message_commands.h"
-
-namespace o3d {
-namespace imc {
-const char* GetMessageDescription(MessageId id) {
- static const char* const message_descriptions[] = {
- #define O3D_IMC_MESSAGE_OP(id, class_name) #id,
- O3D_IMC_MESSAGE_LIST(O3D_IMC_MESSAGE_OP)
- #undef O3D_IMC_MESSAGE_OP
- };
- return message_descriptions[id];
-}
-} // namespace imc
-} // namespace o3d
-
-
diff --git a/o3d/core/cross/message_commands.h b/o3d/core/cross/message_commands.h
deleted file mode 100644
index 1eeabc2..0000000
--- a/o3d/core/cross/message_commands.h
+++ /dev/null
@@ -1,430 +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 declarations of various IMC messages for O3D.
-
-#ifndef O3D_CORE_CROSS_MESSAGE_COMMANDS_H_
-#define O3D_CORE_CROSS_MESSAGE_COMMANDS_H_
-
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// Max length of the string storing the version of O3D as returned by the
-// GET_VERSION message
-#define MAX_VERSION_STRING_LENGTH 128
-
-// Make sure the compiler does not add extra padding to any of the message
-// structures.
-#pragma pack(push, 1)
-
-// This macro is used to safely and convienently expand the list of possible IMC
-// messages in to various lists and never have them get out of sync. To add a
-// new message add a this list, the first argument is the enum Id, the second
-// argument is the name of the structure that describes the message. Once you've
-// added it to this list, create the structure below and then add a function in
-// message_queue.cc called ProcessMessageStructureName where
-// MessageStructureName is the name of your message structure.
-//
-// NOTE: THE ORDER OF THESE MUST NOT CHANGE (their id is derived by order)
-#define O3D_IMC_MESSAGE_LIST(OP) \
- OP(INVALID_ID, MessageInvalidId) \
- OP(HELLO, MessageHello) \
- OP(ALLOCATE_SHARED_MEMORY, MessageAllocateSharedMemory) \
- OP(UPDATE_TEXTURE2D, MessageUpdateTexture2D) \
- OP(REGISTER_SHARED_MEMORY, MessageRegisterSharedMemory) \
- OP(UNREGISTER_SHARED_MEMORY, MessageUnregisterSharedMemory) \
- OP(UPDATE_TEXTURE2D_RECT, MessageUpdateTexture2DRect) \
- OP(RENDER, MessageRender) \
- OP(GET_VERSION, MessageGetVersion) \
- OP(SET_MAX_FPS, MessageSetMaxFPS) \
-
-
-namespace imc {
-enum MessageId {
- #define O3D_IMC_MESSAGE_OP(id, class_name) id,
- O3D_IMC_MESSAGE_LIST(O3D_IMC_MESSAGE_OP)
- #undef O3D_IMC_MESSAGE_OP
-
- MAX_NUM_IDS,
-
- ID_FORCE_DWORD = 0x7fffffff // Forces a 32-bit size enum
-};
-
-// Returns a string by message ID.
-const char* GetMessageDescription(MessageId id);
-};
-
-// An invalid message. This is mostly a place holder for id 0.
-struct MessageInvalidId {
- // Message Content.
- struct Msg {
- static const imc::MessageId kMessageId = imc::INVALID_ID;
-
- imc::MessageId message_id;
- };
-
- MessageInvalidId() {
- msg.message_id = Msg::kMessageId;
- }
-
- Msg msg;
-};
-
-// The first message you send.
-struct MessageHello {
- // Message Content.
- struct Msg {
- static const imc::MessageId kMessageId = imc::HELLO;
-
- imc::MessageId message_id;
- };
-
- MessageHello() {
- msg.message_id = Msg::kMessageId;
- }
-
- Msg msg;
-};
-
-// A message to allocate shared memory
-struct MessageAllocateSharedMemory {
- // Message Content.
- struct Msg {
- static const imc::MessageId kMessageId = imc::ALLOCATE_SHARED_MEMORY;
- static const int32 kMaxSharedMemSize = 1024 * 1024 * 128; // 128MB
-
- imc::MessageId message_id;
-
- // The amount of memory to allocate.
- int32 mem_size;
- };
-
- // The response data.
- struct ResponseData {
- int32 buffer_id;
- };
-
- // A wrapper to manage the response data.
- struct Response {
- public:
- Response(int32 buffer_id) {
- data.buffer_id = buffer_id;
- }
-
- ResponseData data;
- };
-
- MessageAllocateSharedMemory() {
- msg.message_id = Msg::kMessageId;
- }
-
- // Parameters:
- // mem_size: The number of bytes to allocate.
- explicit MessageAllocateSharedMemory(int32 mem_size) {
- msg.message_id = Msg::kMessageId;
- msg.mem_size = mem_size;
- }
-
- Msg msg;
-};
-
-// A message to update the entire contents of a 2D texture. The number
-// of bytes MUST equal the size of the entire texture to be updated including
-// all mips.
-struct MessageUpdateTexture2D {
- // Message Content.
- struct Msg {
- static const imc::MessageId kMessageId = imc::UPDATE_TEXTURE2D;
-
- imc::MessageId message_id;
-
- // The id of the texture to set.
- Id texture_id;
-
- // The mip level of the texture to set.
- int32 level;
-
- // The id of the shared memory the contains the data to use to set the
- // texture.
- int32 shared_memory_id;
-
- // The offset inside the shared memory where the texture data starts.
- int32 offset;
-
- // The number of bytes to get out of shared memory.
- // NOTE: this number MUST match the size of the texture. For example for an
- // ARGB texture it must be mip_width * mip_height * 4 * sizeof(uint8)
- int32 number_of_bytes;
- };
-
- MessageUpdateTexture2D() {
- msg.message_id = Msg::kMessageId;
- }
-
- // Parameters:
- // texture_id: The id of the texture to set.
- // level: The mip level of the texture to set.
- // shared_memory_id: The id of the shared memory the contains the data
- // to use to set the texture.
- // offset: The offset inside the shared memory where the texture data
- // starts.
- // number_of_bytes: The number of bytes to get out of shared memory.
- // NOTE: this number MUST match the size of the texture. For example for
- // an ARGB texture it must be mip_width * mip_height * 4 * sizeof(uint8)
- MessageUpdateTexture2D(Id texture_id,
- int32 level,
- int32 shared_memory_id,
- int32 offset,
- int32 number_of_bytes) {
- msg.message_id = Msg::kMessageId;
- msg.texture_id = texture_id;
- msg.level = level;
- msg.shared_memory_id = shared_memory_id;
- msg.offset = offset;
- msg.number_of_bytes = number_of_bytes;
- }
-
- Msg msg;
-};
-
-// A message to register shared memory.
-struct MessageRegisterSharedMemory {
- // Message Content.
- struct Msg {
- static const imc::MessageId kMessageId = imc::REGISTER_SHARED_MEMORY;
- static const int32 kMaxSharedMemSize = 1024 * 1024 * 128; // 128MB
-
- imc::MessageId message_id;
- int32 mem_size;
- };
-
- MessageRegisterSharedMemory() {
- msg.message_id = Msg::kMessageId;
- }
-
- explicit MessageRegisterSharedMemory(int32 mem_size) {
- msg.message_id = Msg::kMessageId;
- msg.mem_size = mem_size;
- }
-
- Msg msg;
-};
-
-// A message to unregister shared memory.
-struct MessageUnregisterSharedMemory {
- // Message Content.
- struct Msg {
- static const imc::MessageId kMessageId = imc::UNREGISTER_SHARED_MEMORY;
-
- imc::MessageId message_id;
- int32 buffer_id;
- };
-
- MessageUnregisterSharedMemory() {
- msg.message_id = Msg::kMessageId;
- }
-
- // Parameters:
- // buffer_id: The id of the buffer to unregister.
- explicit MessageUnregisterSharedMemory(int32 buffer_id) {
- msg.message_id = Msg::kMessageId;
- msg.buffer_id = buffer_id;
- }
-
- Msg msg;
-};
-
-// A message to update a portion of a 2D texture. The number of bytes MUST equal
-// the size of the portion of the texture to be updated.
-struct MessageUpdateTexture2DRect {
- // Message Content.
- struct Msg {
- static const imc::MessageId kMessageId = imc::UPDATE_TEXTURE2D_RECT;
-
- imc::MessageId message_id;
-
- // The id of the texture to set.
- Id texture_id;
-
- // The mip level of the texture to set.
- int32 level;
-
- // The left edge of the rectangle to update in the texture.
- int32 x;
-
- // The top edge of the rectangle to update in the texture.
- int32 y;
-
- // The width of the rectangle to update in the texture.
- int32 width;
-
- // The height of the rectangle to update in the texture.
- int32 height;
-
- // The id of the shared memory the contains the data to use to set the
- // texture.
- int32 shared_memory_id;
-
- // The offset inside the shared memory where the texture data starts.
- int32 offset;
-
- // The number of bytes bytes across 1 row in the source data.
- int32 pitch;
- };
-
- MessageUpdateTexture2DRect() {
- msg.message_id = Msg::kMessageId;
- }
-
- // Parameters:
- // texture_id: The id of the texture to set.
- // level: The mip level of the texture to set.
- // x: The left edge of the rectangle to update in the texture.
- // y: The top edge of the rectangle to update in the texture.
- // width: The width of the rectangle to update in the texture.
- // height: The height of the rectangle to update in the texture.
- // shared_memory_id: The id of the shared memory the contains the data to
- // use to set the texture.
- // offset: The offset inside the shared memory where the texture data
- // starts.
- // pitch: The number of bytes bytes across 1 row in the source data.
- MessageUpdateTexture2DRect(Id texture_id,
- int32 level,
- int32 x,
- int32 y,
- int32 width,
- int32 height,
- int32 shared_memory_id,
- int32 offset,
- int32 pitch) {
- msg.message_id = Msg::kMessageId;
- msg.texture_id = texture_id;
- msg.level = level;
- msg.x = x;
- msg.y = y;
- msg.width = width;
- msg.height = height;
- msg.shared_memory_id = shared_memory_id;
- msg.offset = offset;
- msg.pitch = pitch;
- }
-
- Msg msg;
-};
-
-// Tell O3D to render. This is generally used when O3D is in Render on demand
-// mode.
-struct MessageRender {
- // Message Content.
- struct Msg {
- static const imc::MessageId kMessageId = imc::RENDER;
-
- imc::MessageId message_id;
- };
-
- MessageRender() {
- msg.message_id = Msg::kMessageId;
- }
-
- Msg msg;
-};
-
-// Tell O3D to render on every new texture as long as not exceeding max_fps.
-// This is only used when O3D is in Render on demand mode.
-struct MessageSetMaxFPS {
- // Message Content.
- struct Msg {
- static const imc::MessageId kMessageId = imc::SET_MAX_FPS;
-
- imc::MessageId message_id;
-
- // Maximum frames per second
- int32 max_fps;
- };
-
- MessageSetMaxFPS() {
- msg.message_id = Msg::kMessageId;
- }
-
- // Parameters:
- // max_fps: The maximum frames per second
- explicit MessageSetMaxFPS(int32 max_fps) {
- msg.message_id = Msg::kMessageId;
- msg.max_fps = max_fps;
- }
-
- Msg msg;
-};
-
-// Get the O3D version.
-struct MessageGetVersion {
- // Message Content.
- struct Msg {
- static const imc::MessageId kMessageId = imc::GET_VERSION;
-
- imc::MessageId message_id;
- };
-
- // The response data.
- struct ResponseData {
- // a null terminated version string in the format "x.x.x.x" where x is an
- // integer number. Note: There may be other data after the last digit which
- // is currently undefined.
- char version[MAX_VERSION_STRING_LENGTH];
- };
-
- // A wrapper to manage the response data.
- struct Response {
- public:
- Response(const char* version) {
- strncpy(data.version, version,
- std::min(strlen(version) + 1, sizeof(data.version)));
- data.version[sizeof(data.version) - 1] = '\0';
- }
-
- ResponseData data;
- };
-
-
- MessageGetVersion() {
- msg.message_id = Msg::kMessageId;
- }
-
- Msg msg;
-};
-
-#pragma pack(pop)
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_MESSAGE_COMMANDS_H_
-
diff --git a/o3d/core/cross/message_commands_test.cc b/o3d/core/cross/message_commands_test.cc
deleted file mode 100644
index 8bdecfb..0000000
--- a/o3d/core/cross/message_commands_test.cc
+++ /dev/null
@@ -1,170 +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 <stddef.h>
-#include "core/cross/message_commands.h"
-#include "tests/common/win/testing_common.h"
-
-namespace o3d {
-
-class MessageCommandsTest : public testing::Test {
-};
-
-TEST_F(MessageCommandsTest, GetMessageDescription) {
- EXPECT_STREQ(imc::GetMessageDescription(
- imc::ALLOCATE_SHARED_MEMORY), "ALLOCATE_SHARED_MEMORY");
-}
-
-TEST_F(MessageCommandsTest, MessageInvalidIdTest) {
- EXPECT_EQ(static_cast<int>(imc::INVALID_ID), 0);
- EXPECT_EQ(0u, offsetof(MessageInvalidId::Msg, message_id));
- MessageInvalidId msg;
- EXPECT_EQ(imc::INVALID_ID, msg.msg.message_id);
- EXPECT_EQ(4u, sizeof msg.msg);
-}
-
-TEST_F(MessageCommandsTest, MessageHelloTest) {
- EXPECT_EQ(static_cast<int>(imc::HELLO), 1);
- EXPECT_EQ(0u, offsetof(MessageHello::Msg, message_id));
- MessageHello msg;
- EXPECT_EQ(imc::HELLO, msg.msg.message_id);
- EXPECT_EQ(4u, sizeof msg.msg);
-}
-
-TEST_F(MessageCommandsTest, MessageAllocateSharedMemoryTest) {
- EXPECT_EQ(static_cast<int>(imc::ALLOCATE_SHARED_MEMORY), 2);
- EXPECT_EQ(0u, offsetof(MessageAllocateSharedMemory::Msg, message_id));
- EXPECT_EQ(4u, offsetof(MessageAllocateSharedMemory::Msg, mem_size));
- MessageAllocateSharedMemory msg;
- EXPECT_EQ(imc::ALLOCATE_SHARED_MEMORY, msg.msg.message_id);
- EXPECT_EQ(8u, sizeof msg.msg);
- MessageAllocateSharedMemory msg2(3);
- EXPECT_EQ(imc::ALLOCATE_SHARED_MEMORY, msg2.msg.message_id);
- EXPECT_EQ(3, msg2.msg.mem_size);
-}
-
-TEST_F(MessageCommandsTest, MessageUpdateTexture2D) {
- EXPECT_EQ(static_cast<int>(imc::UPDATE_TEXTURE2D), 3);
- EXPECT_EQ(0u, offsetof(MessageUpdateTexture2D::Msg, message_id));
- EXPECT_EQ(4u, offsetof(MessageUpdateTexture2D::Msg, texture_id));
- EXPECT_EQ(8u, offsetof(MessageUpdateTexture2D::Msg, level));
- EXPECT_EQ(12u, offsetof(MessageUpdateTexture2D::Msg, shared_memory_id));
- EXPECT_EQ(16u, offsetof(MessageUpdateTexture2D::Msg, offset));
- EXPECT_EQ(20u, offsetof(MessageUpdateTexture2D::Msg, number_of_bytes));
- MessageUpdateTexture2D msg;
- EXPECT_EQ(imc::UPDATE_TEXTURE2D, msg.msg.message_id);
- EXPECT_EQ(24u, sizeof msg.msg);
- MessageUpdateTexture2D msg2(2, 3, 4, 5, 6);
- EXPECT_EQ(imc::UPDATE_TEXTURE2D, msg2.msg.message_id);
- EXPECT_EQ(2u, msg2.msg.texture_id);
- EXPECT_EQ(3, msg2.msg.level);
- EXPECT_EQ(4, msg2.msg.shared_memory_id);
- EXPECT_EQ(5, msg2.msg.offset);
- EXPECT_EQ(6, msg2.msg.number_of_bytes);
-}
-
-TEST_F(MessageCommandsTest, MessageRegisterSharedMemory) {
- EXPECT_EQ(static_cast<int>(imc::REGISTER_SHARED_MEMORY), 4);
- EXPECT_EQ(0u, offsetof(MessageRegisterSharedMemory::Msg, message_id));
- EXPECT_EQ(4u, offsetof(MessageRegisterSharedMemory::Msg, mem_size));
- MessageRegisterSharedMemory msg;
- EXPECT_EQ(imc::REGISTER_SHARED_MEMORY, msg.msg.message_id);
- EXPECT_EQ(8u, sizeof msg.msg);
- MessageRegisterSharedMemory msg2(123);
- EXPECT_EQ(imc::REGISTER_SHARED_MEMORY, msg2.msg.message_id);
- EXPECT_EQ(123, msg2.msg.mem_size);
-}
-
-TEST_F(MessageCommandsTest, MessageUnregisterSharedMemory) {
- EXPECT_EQ(static_cast<int>(imc::UNREGISTER_SHARED_MEMORY), 5);
- EXPECT_EQ(0u, offsetof(MessageUnregisterSharedMemory::Msg, message_id));
- EXPECT_EQ(4u, offsetof(MessageUnregisterSharedMemory::Msg, buffer_id));
- MessageUnregisterSharedMemory msg;
- EXPECT_EQ(imc::UNREGISTER_SHARED_MEMORY, msg.msg.message_id);
- EXPECT_EQ(8u, sizeof msg.msg);
- MessageUnregisterSharedMemory msg2(2);
- EXPECT_EQ(imc::UNREGISTER_SHARED_MEMORY, msg2.msg.message_id);
- EXPECT_EQ(2, msg2.msg.buffer_id);
-}
-
-TEST_F(MessageCommandsTest, MessageUpdateTexture2DRect) {
- EXPECT_EQ(static_cast<int>(imc::UPDATE_TEXTURE2D_RECT), 6);
- EXPECT_EQ(0u, offsetof(MessageUpdateTexture2DRect::Msg, message_id));
- EXPECT_EQ(4u, offsetof(MessageUpdateTexture2DRect::Msg, texture_id));
- EXPECT_EQ(8u, offsetof(MessageUpdateTexture2DRect::Msg, level));
- EXPECT_EQ(12u, offsetof(MessageUpdateTexture2DRect::Msg, x));
- EXPECT_EQ(16u, offsetof(MessageUpdateTexture2DRect::Msg, y));
- EXPECT_EQ(20u, offsetof(MessageUpdateTexture2DRect::Msg, width));
- EXPECT_EQ(24u, offsetof(MessageUpdateTexture2DRect::Msg, height));
- EXPECT_EQ(28u, offsetof(MessageUpdateTexture2DRect::Msg, shared_memory_id));
- EXPECT_EQ(32u, offsetof(MessageUpdateTexture2DRect::Msg, offset));
- EXPECT_EQ(36u, offsetof(MessageUpdateTexture2DRect::Msg, pitch));
- MessageUpdateTexture2DRect msg;
- EXPECT_EQ(imc::UPDATE_TEXTURE2D_RECT, msg.msg.message_id);
- EXPECT_EQ(40u, sizeof msg.msg);
- MessageUpdateTexture2DRect msg2(2, 3, 4, 5, 6, 7, 8, 9, 10);
- EXPECT_EQ(imc::UPDATE_TEXTURE2D_RECT, msg2.msg.message_id);
- EXPECT_EQ(2u, msg2.msg.texture_id);
- EXPECT_EQ(3, msg2.msg.level);
- EXPECT_EQ(4, msg2.msg.x);
- EXPECT_EQ(5, msg2.msg.y);
- EXPECT_EQ(6, msg2.msg.width);
- EXPECT_EQ(7, msg2.msg.height);
- EXPECT_EQ(8, msg2.msg.shared_memory_id);
- EXPECT_EQ(9, msg2.msg.offset);
- EXPECT_EQ(10, msg2.msg.pitch);
-}
-
-TEST_F(MessageCommandsTest, MessageRender) {
- EXPECT_EQ(static_cast<int>(imc::RENDER), 7);
- EXPECT_EQ(0u, offsetof(MessageRender::Msg, message_id));
- MessageRender msg;
- EXPECT_EQ(imc::RENDER, msg.msg.message_id);
- EXPECT_EQ(4u, sizeof msg.msg);
-}
-
-TEST_F(MessageCommandsTest, MessageGetVersion) {
- EXPECT_EQ(static_cast<int>(imc::GET_VERSION), 8);
- EXPECT_EQ(0u, offsetof(MessageGetVersion::Msg, message_id));
- MessageGetVersion msg;
- EXPECT_EQ(imc::GET_VERSION, msg.msg.message_id);
- EXPECT_EQ(4u, sizeof msg.msg);
- const char* kVersion = "0.1.2.3";
- MessageGetVersion::Response response(kVersion);
- EXPECT_EQ(0u, offsetof(MessageGetVersion::ResponseData, version));
- EXPECT_EQ(128u, sizeof(MessageGetVersion::ResponseData)); // NOLINT
- EXPECT_STREQ(kVersion, response.data.version);
-}
-
-
-} // namespace o3d
-
-
diff --git a/o3d/core/cross/message_queue.cc b/o3d/core/cross/message_queue.cc
deleted file mode 100644
index 617fde6..0000000
--- a/o3d/core/cross/message_queue.cc
+++ /dev/null
@@ -1,891 +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 definition of the MessageQueue, the class that handles
-// the communication of external code (clients) with O3D (server) via the
-// NativeClient IMC library.
-
-#if defined(OS_MACOSX) | defined(OS_LINUX)
-#include <sys/types.h>
-#include <unistd.h>
-#endif
-#include "core/cross/message_queue.h"
-#include "core/cross/client_info.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/bitmap.h"
-#include "core/cross/texture.h"
-#include "core/cross/error.h"
-#include "core/cross/pointer_utils.h"
-#include "core/cross/renderer.h"
-
-#ifdef OS_WIN
-#include "core/cross/core_metrics.h"
-#endif
-
-namespace o3d {
-
-volatile ::base::subtle::Atomic32 MessageQueue::last_message_queue_id_ = -1;
-
-// Prefix used to name all server socket addresses for O3D.
-const char kServerSocketAddressPrefix[] = "o3d";
-
-// Writes any nacl IMC errors to the log with a descriptive message.
-// NOTE: macros used to make sure the LOG calls note the
-// correct line number and source file.
-#define LOG_IMC_ERROR(message) { \
- char buffer[256]; \
- if (nacl::GetLastErrorString(buffer, sizeof(buffer)) == 0) { \
- LOG(ERROR) << message << " : " << buffer; \
- } else { \
- LOG(ERROR) << message; \
- } \
-}
-
-ConnectedClient::ConnectedClient(nacl::Handle handle) : client_handle_(handle) {
-}
-
-ConnectedClient::~ConnectedClient() {
- std::vector<SharedMemoryInfo>::const_iterator iter;
-
- // Unmap and close shared memory.
- for (iter = shared_memory_array_.begin(); iter < shared_memory_array_.end();
- ++iter) {
- nacl::Unmap(iter->mapped_address, iter->size);
- nacl::Close(iter->shared_memory_handle);
- }
-}
-
-// Registers a newly created shared memory buffer with the
-// ConnectedClient by adding the buffer info into the
-// shared_memory_array_.
-void ConnectedClient::RegisterSharedMemory(int32 buffer_id,
- nacl::Handle handle,
- void *address,
- int32 size) {
- SharedMemoryInfo shared_mem;
- shared_mem.buffer_id = buffer_id;
- shared_mem.shared_memory_handle = handle;
- shared_mem.mapped_address = address;
- shared_mem.size = size;
-
- shared_memory_array_.push_back(shared_mem);
-}
-
-// Unregisters a shared memory buffer for a given client-allocated
-// memory region, unmapping and closing it in the process.
-bool ConnectedClient::UnregisterSharedMemory(int32 buffer_id) {
- std::vector<SharedMemoryInfo>::iterator iter;
- for (iter = shared_memory_array_.begin(); iter < shared_memory_array_.end();
- ++iter) {
- if (iter->buffer_id == buffer_id) {
- nacl::Unmap(iter->mapped_address, iter->size);
- nacl::Close(iter->shared_memory_handle);
- shared_memory_array_.erase(iter);
- return true;
- }
- }
- return false;
-}
-
-// Returns the SharedMemoryInfo corresponding to the given shared
-// memory buffer id. The buffer must first be created by the
-// MessageQueue on behalf of this ConnectedClient.
-const SharedMemoryInfo* ConnectedClient::GetSharedMemoryInfo(int32 id) const {
- std::vector<SharedMemoryInfo>::const_iterator iter;
- for (iter = shared_memory_array_.begin(); iter < shared_memory_array_.end();
- ++iter) {
- if (iter->buffer_id == id) {
- return &(*iter);
- }
- }
- return NULL;
-}
-
-
-MessageQueue::MessageQueue(ServiceLocator* service_locator)
- : service_locator_(service_locator),
- object_manager_(service_locator->GetService<ObjectManager>()),
- server_socket_handle_(nacl::kInvalidHandle),
- next_shared_memory_id_(0) {
-#if defined(OS_WIN)
- DWORD proc_id = GetCurrentProcessId();
-#endif
-#if defined(OS_MACOSX) | defined(OS_LINUX)
- pid_t proc_id = getpid();
-#endif
-
- int id = ::base::subtle::NoBarrier_AtomicIncrement(&last_message_queue_id_,
- 1);
-
- // Create a unique name for the socket used by the message queue.
- // We use part of the process id to distinguish between different
- // browsers running o3d at the same time as well as a count to
- // distinguish between multiple instances of o3d running in the same
- // browser.
- ::base::snprintf(server_socket_address_.path,
- sizeof(server_socket_address_.path),
- "%s%u-%d",
- kServerSocketAddressPrefix,
- static_cast<unsigned int>(proc_id),
- id);
-}
-
-MessageQueue::~MessageQueue() {
- // Clean up the ConnectedClient array.
- std::vector<ConnectedClient*>::const_iterator iter;
- for (iter = connected_clients_.begin(); iter != connected_clients_.end();
- ++iter) {
- nacl::Close((*iter)->client_handle());
- delete *iter;
- }
-
- // Close the socket.
- nacl::Close(server_socket_handle_);
-}
-
-// Creates a bound socket that corresponds to the communcation channel
-// for this Client.
-bool MessageQueue::Initialize() {
- server_socket_handle_ = nacl::BoundSocket(&server_socket_address_);
-
- if (server_socket_handle_ == nacl::kInvalidHandle) {
- LOG_IMC_ERROR("Failed to create a bound socket for the MessageQueue");
- return false;
- }
-
- return true;
-}
-
-String MessageQueue::GetSocketAddress() const {
- return &server_socket_address_.path[0];
-}
-
-
-// Checks the message queue for an incoming message. If one is found
-// then it processes it, otherwise it just returns.
-bool MessageQueue::CheckForNewMessages(bool* has_new_texture) {
- // The flag will be set to true if we receive a new texture in
- // ProcessMessageUpdateTexture2DRect() or
- // ProcessMessageUpdateTexture2D()
- has_new_texture_ = false;
-
- // NOTE: This code uses reasonable defaults for the max
- // sizes of the received messages. If a message uses more memory or
- // transmits more data handles then it will appear as truncated. If
- // we find that there are valid messages with size larger than
- // what's defined here we should adjust the constants accordingly.
- const int kBufferLength = 1024; // max 1K of memory transfered per message
-
- // max handles transfered per message
- const int kMaxNumHandles = nacl::kHandleCountMax;
-
- char message_buffer[kBufferLength];
- nacl::Handle handles[kMaxNumHandles];
-
- // All received messages are read as containing a single buffer for data
- // a number of handles.
- nacl::IOVec io_vec[1];
- io_vec[0].base = message_buffer;
- io_vec[0].length = kBufferLength;
-
- nacl::MessageHeader header;
- header.iov = io_vec;
- header.iov_length = 1;
- header.handles = handles;
- header.handle_count = kMaxNumHandles;
- header.flags = 0;
-
- // First check for a message in the server socket. The only
- // messages that we should be receiving here are the HELLO messages
- // received from clients that want to connect. Note that
- // ReceiveMessageFromSocket also returns true if there are no
- // messages in the queue in which case message_length will be equal
- // to -1.
- imc::MessageId message_id;
- int message_length = 0;
- if (ReceiveMessageFromSocket(server_socket_handle_,
- &header,
- &message_id,
- &message_length)) {
- if (message_id == imc::HELLO) {
- ProcessHelloMessage(&header, handles);
-#ifdef OS_WIN
- metric_imc_hello_msg.Set(true);
-#endif
- } else if (message_length != -1) {
- DLOG(INFO) << "Received a non-HELLO message from server queue";
- }
- }
-
- // Check all the sockets of the connected clients to see if they contain any
- // messages.
- std::vector<ConnectedClient*>::iterator iter;
- for (iter = connected_clients_.begin(); iter < connected_clients_.end();) {
- // Must reset the available buffer length and number of handles each time
- // so NaCl's IMC knows how much space is available for reading
- io_vec[0].length = kBufferLength;
- header.handle_count = kMaxNumHandles;
- if (ReceiveMessageFromSocket((*iter)->client_handle(),
- &header,
- &message_id,
- &message_length)) {
- if (message_length == 0) {
- // Message length of 0 means EOF (i.e., client closed its handle).
- nacl::Close((*iter)->client_handle());
- delete *iter;
- iter = connected_clients_.erase(iter); // Advances the iterator too.
- continue;
- }
- if (message_length != -1) { // Else no message waiting
- ProcessClientRequest(*iter,
- message_length,
- message_id,
- &header,
- handles);
- }
- }
- ++iter;
- }
-
- *has_new_texture = has_new_texture_;
- return true;
-}
-
-
-// Checks the socket for messages. If none are found then it returns
-// right away. If a message is found, it checks to make sure that the
-// first 4 bytes contain a valid message ID. If they do, then it
-// return the ID in message_id.
-bool MessageQueue::ReceiveMessageFromSocket(nacl::Handle socket,
- nacl::MessageHeader* header,
- imc::MessageId* message_id,
- int* length) {
- *message_id = imc::INVALID_ID;
-
- // Check if there's a new message but don't block waiting for it.
- int message_length = nacl::ReceiveDatagram(socket,
- header,
- nacl::kDontWait);
-
- // If result==-1 then either there are no messages in the queue in
- // which case we can just return, or the message read failed in
- // which case we need to log the failure.
- if (message_length == -1) {
- if (nacl::WouldBlock()) {
- *length = message_length;
- return true;
-#if defined(OS_WIN)
- } else if (GetLastError() == ERROR_BROKEN_PIPE) {
- // On Windows, the NACL library treats EOF as a failure with this failure
- // code. We convert it to the traditional format of a successful read that
- // returns zero bytes to match the Mac & Linux case below.
- *length = 0;
- return true;
-#endif
- } else {
- LOG_IMC_ERROR("nacl::ReceiveMessage failed");
- return false;
- }
- }
-
-#if defined(OS_MACOSX) | defined(OS_LINUX)
- if (message_length == 0) { // EOF
- *length = 0;
- return true;
- }
-#endif
-
- // Valid messages must always contain at least the ID of the message
- if (message_length >= static_cast<int>(sizeof(*message_id))) {
- // Check if the incoming message requires more space than we have
- // currently allocated.
- if (header->flags & nacl::kMessageTruncated) {
- LOG(ERROR) << "Incoming message was truncated";
- return false;
- }
-
- // Extract the ID of the message just received.
- imc::MessageId id_found =
- *(reinterpret_cast<imc::MessageId*>(header->iov[0].base));
- if (id_found <= imc::INVALID_ID ||
- id_found >= imc::MAX_NUM_IDS) {
- LOG(ERROR) << "Unknown ID found in message :" << id_found;
- }
- *message_id = id_found;
- *length = message_length;
- return true;
- } else {
- LOG(ERROR) << "Incoming message too short (length:" << message_length
- << ")";
- return false;
- }
-}
-
-bool MessageQueue::ProcessClientRequest(ConnectedClient* client,
- int message_length,
- imc::MessageId message_id,
- nacl::MessageHeader* header,
- nacl::Handle* handles) {
- static int expected_message_lengths[] = {
- #define O3D_IMC_MESSAGE_OP(id, class_name) sizeof(class_name::Msg),
- O3D_IMC_MESSAGE_LIST(O3D_IMC_MESSAGE_OP)
- #undef O3D_IMC_MESSAGE_OP
- };
-
- if (message_id == imc::INVALID_ID ||
- static_cast<unsigned>(message_id) >=
- arraysize(expected_message_lengths)) {
- LOG(ERROR) << "Unrecognized message id " << message_id;
- return false;
- }
-
- if (message_length != expected_message_lengths[message_id]) {
- LOG(ERROR) << "Bad message length for "
- << imc::GetMessageDescription(message_id);
- return false;
- }
-
- switch (message_id) {
- #define O3D_IMC_MESSAGE_OP(id, class_name) \
- case imc::id: return Process ## class_name( \
- client, message_length, header, handles, \
- *static_cast<const class_name::Msg*>(header->iov[0].base));
- O3D_IMC_MESSAGE_LIST(O3D_IMC_MESSAGE_OP)
- #undef O3D_IMC_MESSAGE_OP
- default:
- return false;
- }
-
- return true;
-}
-
-bool MessageQueue::SendBooleanResponse(nacl::Handle client_handle, bool value) {
- int response = (value ? 1 : 0);
- nacl::IOVec vec;
- vec.base = &response;
- vec.length = sizeof(response);
-
- nacl::MessageHeader header;
- header.iov = &vec;
- header.iov_length = 1;
- header.handles = NULL;
- header.handle_count = 0;
- int result = nacl::SendDatagram(client_handle, &header, 0);
-
- if (result != sizeof(response)) {
- LOG_IMC_ERROR("Failed to send boolean response to client handle");
- return false;
- }
-
- return true;
-}
-
-// Processes a HELLO message received from a client. If everything goes well
-// it adds the client to the ConnectedClient list and sends back a positive
-// response.
-bool MessageQueue::ProcessHelloMessage(nacl::MessageHeader *header,
- nacl::Handle *handles) {
- // HELLO is the first message that should be send by a client. It should
- // contain a single handle corresponding to the client's socket.
- if (header->handle_count == 1) {
- nacl::Handle client_handle = header->handles[0];
- // Make sure the handle is not already being used (i.e. only allow
- // a single HELLO message from a client)
- // TODO : please check correctness of this line
- std::vector<ConnectedClient*>::const_iterator find_iter = find(
- connected_clients_.begin(), connected_clients_.end(),
- reinterpret_cast<ConnectedClient*>(client_handle));
- if (find_iter != connected_clients_.end()) {
- LOG(WARNING) << "Received HELLO from client that's already connected";
-
- // Tell the client that the handshake failed.
- SendBooleanResponse(client_handle, false);
- return true;
- }
-
- // Send an acknowledgement back to the client that the handshake succeeded.
- if (!SendBooleanResponse(client_handle, true))
- return false;
-
- // TODO Is there any way to verify that the handle we got
- // passed here actually corresponds to the socket handle of the client?
- ConnectedClient* new_client = new ConnectedClient(client_handle);
-
- // Add the new client to the list.
- connected_clients_.push_back(new_client);
- return true;
- }
- return false;
-}
-
-// All emums need a Process function.
-bool MessageQueue::ProcessMessageInvalidId(
- ConnectedClient* client,
- int message_length,
- nacl::MessageHeader* header,
- nacl::Handle* handles,
- const MessageInvalidId::Msg& message) {
- return false;
-}
-
-bool MessageQueue::ProcessMessageHello(
- ConnectedClient* client,
- int message_length,
- nacl::MessageHeader* header,
- nacl::Handle* handles,
- const MessageHello::Msg& message) {
- // Hello is handled special.
- return false;
-}
-
-// Processes a request to allocate a shared memory buffer on behalf of a
-// connected client. Parses the arguments of the message to determine how
-// much space is requested, it creates the shared memory buffer, maps it in
-// the local address space and sends a message back to the client with the
-// newly created memory handle.
-bool MessageQueue::ProcessMessageAllocateSharedMemory(
- ConnectedClient* client,
- int message_length,
- nacl::MessageHeader* header,
- nacl::Handle* handles,
- const MessageAllocateSharedMemory::Msg& message) {
-
- if (header->iov_length != 1 ||
- header->handle_count != 0) {
- LOG(ERROR) << "Malformed message for ALLOCATE_SHARED_MEMORY";
- return false;
- }
-
- int32 mem_size = message.mem_size;
- if (mem_size <= 0 ||
- mem_size > MessageAllocateSharedMemory::Msg::kMaxSharedMemSize) {
- LOG(ERROR) << "Invalid mem size requested: " << mem_size
- << "(max size = "
- << MessageAllocateSharedMemory::Msg::kMaxSharedMemSize << ")";
- return false;
- }
-
- // Create the shared memory object.
- nacl::Handle shared_memory = nacl::CreateMemoryObject(mem_size);
- if (shared_memory == nacl::kInvalidHandle) {
- LOG_IMC_ERROR("Failed to create shared memory object");
- return false;
- }
-
- // Map it in local address space.
- void* shared_region = nacl::Map(0,
- mem_size,
- nacl::kProtRead | nacl::kProtWrite,
- nacl::kMapShared,
- shared_memory,
- 0);
-
- if (shared_region == nacl::kMapFailed) {
- LOG_IMC_ERROR("Failed to map shared memory");
- nacl::Close(shared_memory);
- return false;
- }
-
- // Create a unique id for the shared memory buffer.
- MessageAllocateSharedMemory::Response response(next_shared_memory_id_++);
-
- // Send the shared memory handle and the buffer id back to the client.
- nacl::MessageHeader response_header;
- nacl::IOVec id_vec;
- id_vec.base = &response.data;
- id_vec.length = sizeof(response.data);
-
- response_header.iov = &id_vec;
- response_header.iov_length = 1;
- response_header.handles = &shared_memory;
- response_header.handle_count = 1;
- int result = nacl::SendDatagram(client->client_handle(), &response_header, 0);
-
- if (result != sizeof(response.data)) {
- LOG_IMC_ERROR("Failed to send shared memory handle back to the client");
- nacl::Unmap(shared_region, mem_size);
- nacl::Close(shared_memory);
- return false;
- }
-
- // Register the newly created shared memory with the connected client.
- client->RegisterSharedMemory(response.data.buffer_id,
- shared_memory,
- shared_region,
- mem_size);
-
- return true;
-}
-
-// Processes a request by a client to update the contents of a Texture object
-// bitmap using data stored in a shared memory region. The client sends the
-// id of the shared memory region, an offset in that region, the id of the
-// Texture object, the level to be modified and the number of bytes to copy.
-// This is essentially asynchronous as the client will not receive a response
-// back from the server
-bool MessageQueue::ProcessMessageUpdateTexture2D(
- ConnectedClient* client,
- int message_length,
- nacl::MessageHeader* header,
- nacl::Handle* handles,
- const MessageUpdateTexture2D::Msg& message) {
- // Check the length of the message to make sure it contains the size of
- // the requested buffer.
- if (header->iov_length != 1 ||
- header->handle_count != 0) {
- LOG(ERROR) << "Malformed message for UPDATE_TEXTURE2D";
- SendBooleanResponse(client->client_handle(), false);
- return false;
- }
-
- // Check that this client did actually allocate the shared memory
- // corresponding to this handle.
- const SharedMemoryInfo* info =
- client->GetSharedMemoryInfo(message.shared_memory_id);
- if (info == NULL) {
- O3D_ERROR(service_locator_)
- << "shared memory id " << message.shared_memory_id << " not found";
- SendBooleanResponse(client->client_handle(), false);
- return false;
- }
-
- // Check that the Id passed in actually corresponds to a texture.
- Texture2D* texture_object =
- object_manager_->GetById<Texture2D>(message.texture_id);
-
- if (texture_object == NULL) {
- O3D_ERROR(service_locator_)
- << "Texture with id " << message.texture_id << " not found";
- SendBooleanResponse(client->client_handle(), false);
- return false;
- }
-
- // Check that we will not be reading past the end of the allocated shared
- // memory.
- if (message.offset + message.number_of_bytes > info->size ||
- message.offset + message.number_of_bytes < message.offset) {
- O3D_ERROR(service_locator_)
- << "Offset + texture size exceeds allocated shared memory size ("
- << message.offset << " + " << message.number_of_bytes << " > "
- << info->size;
- SendBooleanResponse(client->client_handle(), false);
- return false;
- }
-
- unsigned int mip_width =
- image::ComputeMipDimension(message.level, texture_object->width());
-
- void *target_address =
- PointerFromVoidPointer<void*>(info->mapped_address, message.offset);
-
- int pitch = image::ComputePitch(texture_object->format(), mip_width);
- int rows = message.number_of_bytes / pitch;
-
- texture_object->SetRect(
- message.level, 0, 0, mip_width, rows, target_address, pitch);
-
- int remain = message.number_of_bytes % pitch;
- if (remain) {
- int width = remain / image::ComputePitch(texture_object->format(), 1);
- texture_object->SetRect(
- message.level, 0, rows, width, 1,
- AddPointerOffset<void*>(target_address, rows * pitch), pitch);
- }
-
- SendBooleanResponse(client->client_handle(), true);
- has_new_texture_ = true;
- return true;
-}
-
-bool MessageQueue::ProcessMessageUpdateTexture2DRect(
- ConnectedClient* client,
- int message_length,
- nacl::MessageHeader* header,
- nacl::Handle* handles,
- const MessageUpdateTexture2DRect::Msg& message) {
- // Check the length of the message to make sure it contains the size of
- // the requested buffer.
- if (header->iov_length != 1 ||
- header->handle_count != 0) {
- LOG(ERROR) << "Malformed message for UPDATE_TEXTURE2D_RECT";
- SendBooleanResponse(client->client_handle(), false);
- return false;
- }
-
- // Check that this client did actually allocate the shared memory
- // corresponding to this handle.
- const SharedMemoryInfo* info =
- client->GetSharedMemoryInfo(message.shared_memory_id);
- if (info == NULL) {
- O3D_ERROR(service_locator_)
- << "shared memory id " << message.shared_memory_id << " not found";
- SendBooleanResponse(client->client_handle(), false);
- return false;
- }
-
- // Check that the Id passed in actually corresponds to a texture.
- Texture2D* texture_object =
- object_manager_->GetById<Texture2D>(message.texture_id);
-
- if (texture_object == NULL) {
- O3D_ERROR(service_locator_)
- << "Texture with id " << message.texture_id << " not found";
- SendBooleanResponse(client->client_handle(), false);
- return false;
- }
-
- // Check that we will not be reading past the end of the allocated shared
- // memory.
- int32 number_of_bytes =
- (message.height - 1) * message.pitch +
- image::ComputePitch(texture_object->format(), message.width);
- if (message.offset + number_of_bytes > info->size ||
- message.offset + number_of_bytes < message.offset) {
- O3D_ERROR(service_locator_)
- << "Offset + size as computed by width, height and pitch"
- << " exceeds allocated shared memory size ("
- << message.offset << " + " << number_of_bytes << " > "
- << info->size;
- SendBooleanResponse(client->client_handle(), false);
- return false;
- }
-
- int mip_width =
- image::ComputeMipDimension(message.level, texture_object->width());
- int mip_height =
- image::ComputeMipDimension(message.level, texture_object->height());
-
- if (message.x < 0 || message.width < 0 ||
- message.y < 0 || message.height < 0 ||
- message.x + message.width > mip_width ||
- message.y + message.height > mip_height) {
- O3D_ERROR(service_locator_)
- << "rect out of range ("
- << message.x << ", " << message.y << ", " << message.width
- << message.height << ")";
- SendBooleanResponse(client->client_handle(), false);
- return false;
- }
-
- void *target_address =
- PointerFromVoidPointer<void*>(info->mapped_address, message.offset);
- texture_object->SetRect(
- message.level, message.x, message.y,
- message.width, message.height,
- target_address,
- message.pitch);
-
- SendBooleanResponse(client->client_handle(), true);
- has_new_texture_ = true;
- return true;
-}
-
-// Processes a request to register a client-allocated shared memory
-// buffer on behalf of a connected client. Parses the arguments of
-// the message to determine how much space is being passed. It maps
-// the shared memory buffer into the local address space and sends a
-// message back to the client with the newly allocated shared memory
-// ID.
-bool MessageQueue::ProcessMessageRegisterSharedMemory(
- ConnectedClient* client,
- int message_length,
- nacl::MessageHeader* header,
- nacl::Handle* handles,
- const MessageRegisterSharedMemory::Msg& message) {
- if (header->iov_length != 1 ||
- header->handle_count != 1) {
- LOG(ERROR) << "Malformed message for REGISTER_SHARED_MEMORY";
- return false;
- }
-
- int32 mem_size = message.mem_size;
- if (mem_size <= 0 ||
- mem_size > MessageRegisterSharedMemory::Msg::kMaxSharedMemSize) {
- LOG(ERROR) << "Invalid mem size sent: " << mem_size
- << "(max size = "
- << MessageRegisterSharedMemory::Msg::kMaxSharedMemSize << ")";
- return false;
- }
-
- // Fetch the handle to the preexisting shared memory object.
- nacl::Handle shared_memory = header->handles[0];
- if (shared_memory == nacl::kInvalidHandle) {
- LOG_IMC_ERROR("Invalid shared memory object registered");
- return false;
- }
-
- // Map it in local address space.
- void* shared_region = nacl::Map(0,
- mem_size,
- nacl::kProtRead | nacl::kProtWrite,
- nacl::kMapShared,
- shared_memory,
- 0);
- if (shared_region == nacl::kMapFailed) {
- LOG_IMC_ERROR("Failed to map shared memory");
- nacl::Close(shared_memory);
- return false;
- }
-
- // Create a unique id for the shared memory buffer.
- int32 buffer_id = next_shared_memory_id_++;
-
- // Send the buffer id back to the client.
- nacl::MessageHeader response_header;
- nacl::IOVec id_vec;
- id_vec.base = &buffer_id;
- id_vec.length = sizeof(buffer_id);
-
- response_header.iov = &id_vec;
- response_header.iov_length = 1;
- response_header.handles = NULL;
- response_header.handle_count = 0;
- int result = nacl::SendDatagram(client->client_handle(), &response_header, 0);
-
- if (result != sizeof(buffer_id)) {
- LOG_IMC_ERROR("Failed to send shared memory ID back to the client");
- nacl::Unmap(shared_region, mem_size);
- nacl::Close(shared_memory);
- return false;
- }
-
- // Register the newly mapped shared memory with the connected client.
- client->RegisterSharedMemory(buffer_id,
- shared_memory,
- shared_region,
- mem_size);
-
- return true;
-}
-
-// Processes a request to unregister a client-allocated shared memory
-// buffer, referenced by ID.
-bool MessageQueue::ProcessMessageUnregisterSharedMemory(
- ConnectedClient* client,
- int message_length,
- nacl::MessageHeader* header,
- nacl::Handle* handles,
- const MessageUnregisterSharedMemory::Msg& message) {
- if (header->iov_length != 1 ||
- header->handle_count != 0) {
- LOG(ERROR) << "Malformed message for UNREGISTER_SHARED_MEMORY";
- return false;
- }
-
- bool res = client->UnregisterSharedMemory(message.buffer_id);
- SendBooleanResponse(client->client_handle(), res);
- return res;
-}
-
-// Processes a request to Render.
-bool MessageQueue::ProcessMessageRender(
- ConnectedClient* client,
- int message_length,
- nacl::MessageHeader* header,
- nacl::Handle* handles,
- const MessageRender::Msg& message) {
- if (header->iov_length != 1 ||
- header->handle_count != 0) {
- LOG(ERROR) << "Malformed message for RENDER";
- return false;
- }
-
- Renderer* renderer(service_locator_->GetService<Renderer>());
- if (renderer) {
- renderer->set_need_to_render(true);
- }
- return true;
-}
-
-// Processes a request to SetMaxFPS.
-bool MessageQueue::ProcessMessageSetMaxFPS(
- ConnectedClient* client,
- int message_length,
- nacl::MessageHeader* header,
- nacl::Handle* handles,
- const MessageSetMaxFPS::Msg& message) {
- if (header->iov_length != 1 ||
- header->handle_count != 0) {
- LOG(ERROR) << "Malformed message for SET_MAX_FPS";
- return false;
- }
-
- Renderer* renderer(service_locator_->GetService<Renderer>());
- if (renderer) {
- renderer->set_max_fps(message.max_fps);
- }
-
- SendBooleanResponse(client->client_handle(), true);
- return true;
-}
-
-// Processes a request to get the O3D version.
-bool MessageQueue::ProcessMessageGetVersion(
- ConnectedClient* client,
- int message_length,
- nacl::MessageHeader* header,
- nacl::Handle* handles,
- const MessageGetVersion::Msg& message) {
- if (header->iov_length != 1 ||
- header->handle_count != 0) {
- LOG(ERROR) << "Malformed message for GET_VERSION";
- return false;
- }
-
- ClientInfoManager* manager(service_locator_->GetService<ClientInfoManager>());
- static const char* const kNullString = "";
- const char* version = kNullString;
- if (manager) {
- version = manager->client_info().version().c_str();
- }
-
- // Send the version string.
- DCHECK_LT(strlen(version), static_cast<size_t>(MAX_VERSION_STRING_LENGTH));
- MessageGetVersion::Response response(version);
-
- nacl::MessageHeader response_header;
- nacl::IOVec id_vec;
- id_vec.base = &response.data;
- id_vec.length = sizeof(response.data);
-
- response_header.iov = &id_vec;
- response_header.iov_length = 1;
- response_header.handles = NULL;
- response_header.handle_count = 0;
- nacl::SendDatagram(client->client_handle(), &response_header, 0);
-
- return true;
-}
-
-
-
-} // namespace o3d
diff --git a/o3d/core/cross/message_queue.h b/o3d/core/cross/message_queue.h
deleted file mode 100644
index 42924e7..0000000
--- a/o3d/core/cross/message_queue.h
+++ /dev/null
@@ -1,229 +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 declaration of the MessageQueue, the class which
-// allows external code (clients) to connect via the IMC library to O3D
-// (server) and issue calls to it.
-
-#ifndef O3D_CORE_CROSS_MESSAGE_QUEUE_H_
-#define O3D_CORE_CROSS_MESSAGE_QUEUE_H_
-
-#include <vector>
-
-#include "base/atomicops.h"
-#include "core/cross/types.h"
-#include "core/cross/message_commands.h"
-#include "native_client/src/shared/imc/nacl_imc.h"
-
-namespace o3d {
-
-class ServiceLocator;
-class ObjectManager;
-
-// Structure keeping information about shared memory regions created on the
-// request of a client connection.
-struct SharedMemoryInfo {
- // Unique (to the MessageQueue object that created it) id of the shared
- // memory buffer.
- int buffer_id;
- // Handle to the shared memory.
- nacl::Handle shared_memory_handle;
- // Address to which it maps in the local memory space.
- void* mapped_address;
- // Size in bytes
- int32 size;
-};
-
-// The ConnectedClient class holds information about clients that have made
-// contact with the this instance of the server.
-class ConnectedClient {
- public:
- explicit ConnectedClient(nacl::Handle handle);
-
- ~ConnectedClient();
-
- // Registers a newly created shared memory buffer with the client.
- // Parameters:
- // id - the unique id of the shared memory buffer.
- // handle - the nacl handle to the shared memory.
- // address - the beginning of the buffer in the local address space.
- // size - the size of the buffer in bytes.
- void RegisterSharedMemory(int id,
- nacl::Handle handle,
- void *address,
- int32 size);
-
- // Unregisters a client-allocated shared memory segment, referenced by ID.
- // Parameters:
- // id - the unique id of the shared memory buffer.
- // Returns:
- // true if the ID was valid, false otherwise
- bool UnregisterSharedMemory(int id);
-
- // Returns the socket handle the client uses to talk to the server.
- nacl::Handle client_handle() { return client_handle_; }
-
- // Returns the shared memory record that matches the given buffer id.
- const SharedMemoryInfo* GetSharedMemoryInfo(int buffer_id) const;
-
- private:
- // Handle of the socket the client uses.
- nacl::Handle client_handle_;
-
- std::vector<SharedMemoryInfo> shared_memory_array_;
-
- DISALLOW_COPY_AND_ASSIGN(ConnectedClient);
-};
-
-// The MessageQueue class handles the communcation between external code and
-// O3D. It provides methods for initializing the communcation channel
-// as well as reading data from and writing data to it. It is currently using
-// the NativeClient Inter-Module Communication (IMC) library.
-class MessageQueue {
- public:
- // Creates a MessageQueue that is able to receive messages and execute calls
- // to the given Client object.
- explicit MessageQueue(ServiceLocator* service_locator);
-
- ~MessageQueue();
-
- // Initializes the communcation channel.
- // Returns:
- // true if the channel was initialized successfully, false otherwise.
- bool Initialize();
-
- // Checks for new messages on the queue. If messages are found then it
- // it processes them, otherwise it simply returns.
- // Parameters:
- // has_new_texture - [out] If a new texture has been received.
- // Returns:
- // true if there were no new messages or new messages were succesfully
- // received.
- bool CheckForNewMessages(bool* has_new_texture);
-
- // Returns the socket address used by the message queue.
- String GetSocketAddress() const;
-
- private:
- // Processes a request from an already connected client. It parses the
- // parameters provided in the message and executes the appropriate action.
- // Parameters:
- // client - pointer to the ConnectedClient the request came from.
- // message_length - length of the received message in bytes.
- // message_id - id of the request received by the message
- // header - message header containing information about the received
- // message.
- // handles - the array of handles referenced by the header.
- // Returns:
- // true if the message is properly formed and is succesfully handled by the
- // Client.
- bool ProcessClientRequest(ConnectedClient* client,
- int message_length,
- imc::MessageId message_id,
- nacl::MessageHeader* header,
- nacl::Handle* handles);
-
- // Processes the HELLO message, which initiates a new connection with a
- // client.
- // Parameters:
- // header - message header containing information about the received
- // message.
- // handles - the array of handles referenced by the header.
- // Returns:
- // true if the new client connected successfully.
- bool ProcessHelloMessage(nacl::MessageHeader* header, nacl::Handle* handles);
-
- // Declare all the message processing functions. For each type of message
- // will declare a function called Process<MessageName>.
- #define O3D_IMC_MESSAGE_OP(id, class_name) \
- bool Process ## class_name( \
- ConnectedClient* client, \
- int message_length, \
- nacl::MessageHeader* header, \
- nacl::Handle* handles, \
- const class_name::Msg& message);
- O3D_IMC_MESSAGE_LIST(O3D_IMC_MESSAGE_OP)
- #undef O3D_IMC_MESSAGE_OP
-
- // Sends a true of false (1 or 0) message using the given socket handle.
- // Parameters:
- // client_handle - handle of socket to send the response to.
- // value - value to send.
- // Returns:
- // true on success.
- bool SendBooleanResponse(nacl::Handle client_handle, bool value);
-
- // Checks a socket for a message without blocking waiting for one. If a
- // valid message is found then it returns the message id.
- // Parameters:
- // socket - socket to check for messages.
- // header - pointer to the message header used for receiving the message.
- // message_id [out] - the ID of the message received.
- // message_length [out] - the length of the message received.
- // Returns:
- // true if a message with a valid ID is found. true if no message is found.
- // false in every other case.
- bool ReceiveMessageFromSocket(nacl::Handle socket,
- nacl::MessageHeader* header,
- imc::MessageId* message_id,
- int* message_length);
-
- ServiceLocator* service_locator_;
- ObjectManager* object_manager_;
-
- // A list of clients that are communicating via the message queue.
- std::vector<ConnectedClient*> connected_clients_;
-
- // Handle of server (i.e. O3D) bound socket.
- nacl::Handle server_socket_handle_;
-
- // Address of the server socket used by this MessageQueue.
- nacl::SocketAddress server_socket_address_;
-
- // Stores the next available unique id that can be assigned to a newly
- // created shared memory buffer.
- int32 next_shared_memory_id_;
-
- // Stores the last used unique id for message queues. This allows us to
- // create multiple instances of the MessageQueue, each with a unique address.
- static volatile ::base::subtle::Atomic32 last_message_queue_id_;
-
- bool has_new_texture_;
-
- DISALLOW_COPY_AND_ASSIGN(MessageQueue);
-};
-
-
-} // namespace o3d
-
-
-#endif // O3D_CORE_CROSS_MESSAGE_QUEUE_H_
diff --git a/o3d/core/cross/message_queue_test.cc b/o3d/core/cross/message_queue_test.cc
deleted file mode 100644
index c94eb52..0000000
--- a/o3d/core/cross/message_queue_test.cc
+++ /dev/null
@@ -1,1310 +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 the functionality defined in MessageQueue.cc/h
-
-#include "core/cross/message_queue.h"
-#include "core/cross/client_info.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/error_status.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/texture.h"
-#include "core/cross/types.h"
-#include "core/cross/renderer.h"
-#include "tests/common/win/testing_common.h"
-#include "base/condition_variable.h"
-#include "base/lock.h"
-#include "base/platform_thread.h"
-#include "base/time.h"
-
-using ::base::Time;
-using ::base::TimeDelta;
-
-namespace o3d {
-
-//----------------------------------------------------------------------
-// These are helper classes for the little multithreaded test harness
-// below.
-
-class TimeSource {
- public:
- virtual ~TimeSource() {}
- virtual TimeDelta TimeSinceConstruction() = 0;
-};
-
-class WallClockTimeSource : public TimeSource {
- private:
- Time construction_time_;
-
- public:
- WallClockTimeSource() {
- construction_time_ = Time::Now();
- }
-
- virtual TimeDelta TimeSinceConstruction() {
- return Time::Now() - construction_time_;
- }
-};
-
-// The TestWatchdog expects to be signalled a certain number of times
-// within a certain period of time. If it is not signalled this number
-// of times, this indicates one failure mode of the test.
-class TestWatchdog {
- private:
- Lock lock_;
- ConditionVariable condition_;
- int expected_num_signals_;
- TimeDelta time_to_run_;
- TimeSource* time_source_;
-
- public:
- TestWatchdog(int expected_num_signals,
- TimeDelta time_to_run,
- TimeSource* time_source)
- : lock_(),
- condition_(&lock_),
- expected_num_signals_(expected_num_signals),
- time_to_run_(time_to_run),
- time_source_(time_source) {}
-
- void Signal() {
- AutoLock locker(lock_);
- ASSERT_GE(expected_num_signals_, 0);
- --expected_num_signals_;
- condition_.Broadcast();
- }
-
- // Pause the current thread briefly waiting for a signal so we don't
- // consume all CPU
- void WaitBrieflyForSignal() {
- AutoLock locker(lock_);
- condition_.TimedWait(TimeDelta::FromMilliseconds(5));
- }
-
- bool Expired() {
- return time_source_->TimeSinceConstruction() > time_to_run_;
- }
-
- bool Succeeded() {
- return expected_num_signals_ == 0;
- }
-
- bool Done() {
- return Succeeded() || Expired();
- }
-};
-
-// This is the base class for the multithreaded tests which are
-// executed via MessageQueueTest::RunTests(). Each instance is run in
-// its own thread. Override the Run() method with the body of the
-// test.
-class PerThreadConnectedTest : public PlatformThread::Delegate {
- private:
- MessageQueue* queue_;
- nacl::Handle socket_handle_;
- TestWatchdog* watchdog_;
- volatile bool completed_;
- volatile bool passed_;
- String file_;
- int line_;
- String failure_message_;
-
- protected:
- void Pass() {
- completed_ = true;
- passed_ = true;
- watchdog_->Signal();
- }
-
- void Fail(String file,
- int line,
- String failure_message) {
- completed_ = true;
- passed_ = false;
- file_ = file;
- line_ = line;
- failure_message_ = failure_message;
- watchdog_->Signal();
- }
-
- public:
- PerThreadConnectedTest()
- : queue_(NULL),
- socket_handle_(nacl::kInvalidHandle),
- watchdog_(NULL),
- completed_(false),
- passed_(false),
- line_(0) {}
-
- // Override this with the particular test's functionality
- virtual void Run(MessageQueue* queue,
- nacl::Handle socket_handle) = 0;
-
- void Configure(MessageQueue* queue,
- nacl::Handle socket_handle,
- TestWatchdog* watchdog) {
- queue_ = queue;
- watchdog_ = watchdog;
- socket_handle_ = socket_handle;
- }
-
- // Indicates whether or not the PerThreadTest should be deleted;
- // if it is hanging then to avoid crashes we do not delete it
- bool Completed() {
- return completed_;
- }
-
- bool Passed() {
- return passed_;
- }
-
- const String FailureMessage() {
- std::ostringstream oss;
- oss << file_ << ", line " << line_ << ": " + failure_message_;
- return oss.str();
- }
-
- // This overrides the functionality in PlatformThread::Delegate;
- // don't override this in subclasses.
- virtual void ThreadMain() {
- Run(queue_, socket_handle_);
- }
-};
-
-#define FAIL_TEST(message) Fail(__FILE__, __LINE__, message); return
-
-class TestProvider {
- public:
- virtual ~TestProvider() {}
- virtual PerThreadConnectedTest* CreateTest() = 0;
-};
-
-//----------------------------------------------------------------------
-// This is a helper class that handles connecting to the MessageQueue
-// and issuing commands to it.
-class TextureUpdateHelper {
- public:
- TextureUpdateHelper() : o3d_handle_(nacl::kInvalidHandle) {}
-
- // Connects to the MessageQueue.
- bool ConnectToO3D(const char* o3d_address,
- nacl::Handle my_socket_handle);
-
- // Makes a request for a shared memory buffer.
- bool RequestSharedMemory(size_t requested_size,
- int* shared_mem_id,
- void** shared_mem_address);
-
- // Makes a request to update a texture.
- bool RequestTextureUpdate(unsigned int texture_id,
- int level,
- int shared_memory_id,
- size_t offset,
- size_t number_of_bytes);
-
- // Makes a request to update a portion of a texture.
- bool RequestTextureRectUpdate(unsigned int texture_id,
- int level,
- int x,
- int y,
- int width,
- int height,
- int shared_memory_id,
- size_t offset,
- size_t number_of_bytes);
-
- // Registers a client-allocated shared memory segment with O3D,
- // returning O3D's shared memory ID for later updating. Returns -1
- // upon failure.
- int RegisterSharedMemory(nacl::Handle shared_memory,
- size_t shared_memory_size);
-
- // Unregisters a previously-registered client-allocated shared
- // memory segment.
- bool UnregisterSharedMemory(int shared_memory_id);
-
- // Tells the renderer to render.
- bool Render();
-
- // Gets the version
- bool GetVersion();
-
- private:
- // Handle of the socket that's connected to o3d.
- nacl::Handle o3d_handle_;
-
- bool ReceiveBooleanResponse();
-}; // TextureUpdateHelper
-
-// Waits for a message with a single integer value. If the value is 0 it
-// returns false otherwise returns true.
-bool TextureUpdateHelper::ReceiveBooleanResponse() {
- int response = 0;
- nacl::IOVec vec;
- vec.base = &response;
- vec.length = sizeof(response);
-
- nacl::MessageHeader header;
- header.iov = &vec;
- header.iov_length = 1;
- header.handles = 0;
- header.handle_count = 0;
-
- int result = nacl::ReceiveDatagram(o3d_handle_, &header, 0);
-
- EXPECT_EQ(sizeof(response), static_cast<unsigned>(result));
- if (result != sizeof(response)) {
- return false;
- }
-
- return (response ? true : false);
-}
-
-
-// Send the initial handshake message to O3D.
-bool TextureUpdateHelper::ConnectToO3D(const char* o3d_address,
- nacl::Handle my_socket_handle) {
- nacl::Handle pair[2];
-
- if (nacl::SocketPair(pair) != 0) {
- return false;
- }
-
- MessageHello msg;
- nacl::MessageHeader header;
- nacl::IOVec vec;
- vec.base = &msg.msg;
- vec.length = sizeof(msg.msg);
-
- nacl::SocketAddress socket_address;
- ::base::snprintf(socket_address.path,
- sizeof(socket_address.path),
- "%s", o3d_address);
-
- header.iov = &vec;
- header.iov_length = 1;
- header.handles = &pair[1];
- header.handle_count = 1;
- int result = nacl::SendDatagramTo(my_socket_handle,
- &header,
- 0,
- &socket_address);
-
- EXPECT_EQ(sizeof(msg.msg), static_cast<size_t>(result));
- if (static_cast<size_t>(result) != sizeof(msg.msg)) {
- return false;
- }
-
- // The socket handle we established the connection with o3d with.
- o3d_handle_ = pair[0];
-
- bool response = ReceiveBooleanResponse();
-
- EXPECT_TRUE(response);
-
- // We don't need to have that handle open anymore since the server has it now.
- result = nacl::Close(pair[1]);
-
- return response;
-}
-
-// Sends the server a request to allocate shared memory. It received back
-// from the server a shared memory handle which it then uses to map the shared
-// memory into this process' address space. The server also returns a unique
-// id for the shared memory which can be used to identify the buffer in
-// subsequent communcations with the server.
-bool TextureUpdateHelper::RequestSharedMemory(size_t requested_size,
- int* shared_mem_id,
- void** shared_mem_address) {
- if (o3d_handle_ == nacl::kInvalidHandle) {
- return false;
- }
-
- MessageAllocateSharedMemory msg(requested_size);
- nacl::MessageHeader header;
- nacl::IOVec vec;
-
- vec.base = &msg.msg;
- vec.length = sizeof(msg.msg);
-
- header.iov = &vec;
- header.iov_length = 1;
- header.handles = NULL;
- header.handle_count = 0;
-
- // Send message.
- int result = nacl::SendDatagram(o3d_handle_, &header, 0);
- EXPECT_EQ(vec.length, static_cast<unsigned>(result));
- if (static_cast<unsigned>(result) != vec.length) {
- return false;
- }
-
- // Wait for a message back from the server containing the handle to the
- // shared memory object.
- nacl::Handle shared_memory;
- int shared_memory_id = -1;
- nacl::IOVec shared_memory_vec;
- shared_memory_vec.base = &shared_memory_id;
- shared_memory_vec.length = sizeof(shared_memory_id);
- header.iov = &shared_memory_vec;
- header.iov_length = 1;
- header.handles = &shared_memory;
- header.handle_count = 1;
- result = nacl::ReceiveDatagram(o3d_handle_, &header, 0);
-
- EXPECT_LT(0, result);
- EXPECT_EQ(0, header.flags & nacl::kMessageTruncated);
- EXPECT_EQ(1U, header.handle_count);
- EXPECT_EQ(1U, header.iov_length);
-
- if (result < 0 ||
- header.flags & nacl::kMessageTruncated ||
- header.handle_count != 1 ||
- header.iov_length != 1) {
- return false;
- }
-
- // Map the shared memory object to our address space.
- void* shared_region = nacl::Map(0,
- requested_size,
- nacl::kProtRead | nacl::kProtWrite,
- nacl::kMapShared,
- shared_memory,
- 0);
-
- EXPECT_TRUE(shared_region != NULL);
-
- if (shared_region == NULL) {
- return false;
- }
-
- *shared_mem_address = shared_region;
- *shared_mem_id = shared_memory_id;
-
- return true;
-}
-
-// Sends a message to O3D to update the contents of the texture bitmap
-// using the data stored in shared memory. We pass in the shared memory handle
-// returned by the server as well as an offset from the start of the shared
-// memory buffer where the new texture data is.
-bool TextureUpdateHelper::RequestTextureUpdate(unsigned int texture_id,
- int level,
- int shared_memory_id,
- size_t offset,
- size_t number_of_bytes) {
- MessageUpdateTexture2D msg(
- texture_id, level, shared_memory_id, offset, number_of_bytes);
-
- nacl::MessageHeader header;
- nacl::IOVec vec;
-
- vec.base = &msg.msg;
- vec.length = sizeof(msg.msg);
-
- header.iov = &vec;
- header.iov_length = 1;
- header.handles = NULL;
- header.handle_count = 0;
-
- // Send message.
- int result = nacl::SendDatagram(o3d_handle_, &header, 0);
-
- EXPECT_EQ(vec.length, static_cast<unsigned>(result));
-
- if (static_cast<unsigned>(result) != vec.length) {
- return false;
- }
-
- // Wait for a response from the server. If the server returns true then
- // the texture update was successfully procesed.
- bool texture_updated = ReceiveBooleanResponse();
-
- EXPECT_TRUE(texture_updated);
-
- return texture_updated;
-}
-
-// Sends a message to O3D to update the a potion of the contents of a texture
-// using the data stored in shared memory.
-bool TextureUpdateHelper::RequestTextureRectUpdate(unsigned int texture_id,
- int level,
- int x,
- int y,
- int width,
- int height,
- int shared_memory_id,
- size_t offset,
- size_t number_of_bytes) {
- MessageUpdateTexture2DRect msg(
- texture_id, level, x, y, width, height,
- shared_memory_id, offset, number_of_bytes);
-
- nacl::MessageHeader header;
- nacl::IOVec vec;
-
- vec.base = &msg.msg;
- vec.length = sizeof(msg.msg);
-
- header.iov = &vec;
- header.iov_length = 1;
- header.handles = NULL;
- header.handle_count = 0;
-
- // Send message.
- int result = nacl::SendDatagram(o3d_handle_, &header, 0);
-
- EXPECT_EQ(vec.length, static_cast<unsigned>(result));
-
- if (static_cast<unsigned>(result) != vec.length) {
- return false;
- }
-
- // Wait for a response from the server. If the server returns true then
- // the texture update was successfully procesed.
- bool texture_updated = ReceiveBooleanResponse();
-
- EXPECT_TRUE(texture_updated);
-
- return texture_updated;
-}
-
-// Registers a client-allocated shared memory segment with O3D. It
-// receives back a shared memory ID for later texture updating.
-// Returns -1 upon failure.
-int TextureUpdateHelper::RegisterSharedMemory(nacl::Handle shared_memory,
- size_t shared_memory_size) {
- if (o3d_handle_ == nacl::kInvalidHandle) {
- return false;
- }
-
- MessageRegisterSharedMemory msg(static_cast<int32>(shared_memory_size));
-
- nacl::MessageHeader header;
- nacl::IOVec vec;
-
- vec.base = &msg.msg;
- vec.length = sizeof(msg.msg);
-
- header.iov = &vec;
- header.iov_length = 1;
- header.handles = &shared_memory;
- header.handle_count = 1;
-
- // Send message.
- int result = nacl::SendDatagram(o3d_handle_, &header, 0);
- EXPECT_EQ(vec.length, static_cast<unsigned>(result));
- if (static_cast<unsigned>(result) != vec.length) {
- return -1;
- }
-
- // Wait for a message back from the server containing the ID of the
- // shared memory object.
- nacl::MessageHeader reply_header;
- int shared_memory_id = -1;
- nacl::IOVec shared_memory_vec;
- shared_memory_vec.base = &shared_memory_id;
- shared_memory_vec.length = sizeof(shared_memory_id);
- reply_header.iov = &shared_memory_vec;
- reply_header.iov_length = 1;
- reply_header.handles = NULL;
- reply_header.handle_count = 0;
-
- result = nacl::ReceiveDatagram(o3d_handle_, &reply_header, 0);
- EXPECT_EQ(shared_memory_vec.length, static_cast<unsigned>(result));
- EXPECT_EQ(0, reply_header.flags & nacl::kMessageTruncated);
- EXPECT_EQ(0U, reply_header.handle_count);
- EXPECT_EQ(1U, reply_header.iov_length);
-
- return shared_memory_id;
-}
-
-// Unregisters a previously-registered client-allocated shared
-// memory segment.
-bool TextureUpdateHelper::UnregisterSharedMemory(int shared_memory_id) {
- MessageUnregisterSharedMemory msg(shared_memory_id);
- nacl::MessageHeader header;
- nacl::IOVec vec;
-
- vec.base = &msg.msg;
- vec.length = sizeof(msg.msg);
- header.iov = &vec;
- header.iov_length = 1;
- header.handles = NULL;
- header.handle_count = 0;
-
- // Send message.
- int result = nacl::SendDatagram(o3d_handle_, &header, 0);
- EXPECT_EQ(static_cast<int>(vec.length), result);
- // Read back the boolean reply from the O3D plugin
- bool reply = ReceiveBooleanResponse();
- EXPECT_TRUE(reply);
- return reply;
-}
-
-// Tells the renderer to render..
-bool TextureUpdateHelper::Render() {
- MessageRender msg;
- nacl::MessageHeader header;
- nacl::IOVec vec;
-
- vec.base = &msg.msg;
- vec.length = sizeof(msg.msg);
- header.iov = &vec;
- header.iov_length = 1;
- header.handles = NULL;
- header.handle_count = 0;
-
- // Send message.
- int result = nacl::SendDatagram(o3d_handle_, &header, 0);
- EXPECT_EQ(static_cast<int>(vec.length), result);
- return true;
-}
-
-bool TextureUpdateHelper::GetVersion() {
- MessageGetVersion msg;
- nacl::MessageHeader header;
- nacl::IOVec vec;
-
- vec.base = &msg.msg;
- vec.length = sizeof(msg.msg);
- header.iov = &vec;
- header.iov_length = 1;
- header.handles = NULL;
- header.handle_count = 0;
-
- // Send message.
- int result = nacl::SendDatagram(o3d_handle_, &header, 0);
- EXPECT_EQ(static_cast<int>(vec.length), result);
-
- // Wait for a message back from the server containing the version of O3D.
- MessageGetVersion::ResponseData response;
- nacl::MessageHeader reply_header;
- nacl::IOVec version_vec;
- version_vec.base = &response;
- version_vec.length = sizeof(response);
- reply_header.iov = &version_vec;
- reply_header.iov_length = 1;
- reply_header.handles = NULL;
- reply_header.handle_count = 0;
-
- result = nacl::ReceiveDatagram(o3d_handle_, &reply_header, 0);
- EXPECT_EQ(version_vec.length, static_cast<unsigned>(result));
- EXPECT_EQ(0, reply_header.flags & nacl::kMessageTruncated);
- EXPECT_EQ(0U, reply_header.handle_count);
- EXPECT_EQ(1U, reply_header.iov_length);
-
- ClientInfoManager* manager(
- g_service_locator->GetService<ClientInfoManager>());
- EXPECT_TRUE(manager != NULL);
- if (manager) {
- EXPECT_EQ(0, manager->client_info().version().compare(response.version));
- }
-
- return true;
-}
-
-//----------------------------------------------------------------------
-// This is the main class containing all of the other ones. It knows
-// how to run multiple concurrent PerThreadConnectedTests.
-class MessageQueueTest : public testing::Test {
- protected:
- MessageQueueTest()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator),
- socket_handles_(NULL),
- num_socket_handles_(0) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- // This is the entry point for test cases that need to be run in one
- // or more threads.
- void RunTests(int num_threads,
- TimeDelta timeout,
- TestProvider* test_provider);
-
- Pack* pack() { return pack_; }
-
- // Checks if an error has occured on the client then clears the error.
- bool CheckErrorExists() {
- bool have_error = !error_status_.GetLastError().empty();
- error_status_.ClearLastError();
- return have_error;
- }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- Pack *pack_;
- nacl::Handle* socket_handles_;
- int num_socket_handles_;
-
- // This can't be part of SetUp since it needs to be called from each
- // individual test.
- void ConfigureSockets(int number_of_clients);
-
- nacl::Handle GetSocketHandle(int i) {
- // We would use ASSERT_ here, but that doesn't seem to work from
- // within methods that have non-void return types.
- EXPECT_TRUE(socket_handles_ != NULL);
- EXPECT_LT(i, num_socket_handles_);
- return socket_handles_[i];
- }
-};
-
-void MessageQueueTest::SetUp() {
- pack_ = object_manager_->CreatePack();
- pack_->set_name("MessageQueueTest pack");
-}
-
-void MessageQueueTest::ConfigureSockets(int number_of_clients) {
- ASSERT_GT(number_of_clients, 0);
- num_socket_handles_ = number_of_clients;
- socket_handles_ = new nacl::Handle[num_socket_handles_];
- ASSERT_TRUE(socket_handles_ != NULL);
- for (int i = 0; i < num_socket_handles_; i++) {
- nacl::SocketAddress socket_address;
- ::base::snprintf(socket_address.path,
- sizeof(socket_address.path),
- "%s%d",
- "test-client",
- i);
- socket_handles_[i] = nacl::BoundSocket(&socket_address);
- ASSERT_NE(nacl::kInvalidHandle, socket_handles_[i]);
- }
-}
-
-void MessageQueueTest::TearDown() {
- if (socket_handles_ != NULL) {
- for (int i = 0; i < num_socket_handles_; i++) {
- nacl::Close(socket_handles_[i]);
- }
- delete[] socket_handles_;
- socket_handles_ = NULL;
- num_socket_handles_ = 0;
- }
-
- object_manager_->DestroyPack(pack_);
-}
-
-void MessageQueueTest::RunTests(int num_threads,
- TimeDelta timeout,
- TestProvider* provider) {
- MessageQueue* message_queue = new MessageQueue(g_service_locator);
- message_queue->Initialize();
-
- TimeSource* time_source = new WallClockTimeSource();
- TestWatchdog* watchdog = new TestWatchdog(num_threads,
- timeout,
- time_source);
- PerThreadConnectedTest** tests = new PerThreadConnectedTest*[num_threads];
- ASSERT_TRUE(tests != NULL);
- PlatformThreadHandle* thread_handles = new PlatformThreadHandle[num_threads];
- ASSERT_TRUE(thread_handles != NULL);
- ConfigureSockets(num_threads);
- for (int i = 0; i < num_threads; i++) {
- tests[i] = provider->CreateTest();
- ASSERT_TRUE(tests[i] != NULL);
- tests[i]->Configure(message_queue, GetSocketHandle(i), watchdog);
- }
- // Now that all tests are created, start them up
- for (int i = 0; i < num_threads; i++) {
- ASSERT_TRUE(PlatformThread::Create(0, tests[i], &thread_handles[i]));
- }
- // Wait for completion
- while (!watchdog->Done()) {
- bool has_new_texture = false;
- ASSERT_TRUE(message_queue->CheckForNewMessages(&has_new_texture));
- watchdog->WaitBrieflyForSignal();
- }
- ASSERT_FALSE(watchdog->Expired());
- ASSERT_TRUE(watchdog->Succeeded());
- for (int i = 0; i < num_threads; i++) {
- PerThreadConnectedTest* test = tests[i];
- ASSERT_TRUE(test->Passed()) << test->FailureMessage();
- // Only join the thread and delete the test if it completed
- if (test->Completed()) {
- PlatformThread::Join(thread_handles[i]);
- delete test;
- }
- }
- delete[] thread_handles;
- delete[] tests;
- delete watchdog;
- delete time_source;
- delete message_queue;
-}
-
-//----------------------------------------------------------------------
-// Test cases follow.
-
-// Tests that the message queue socket is properly initialized.
-TEST_F(MessageQueueTest, Initialize) {
- MessageQueue* message_queue = new MessageQueue(g_service_locator);
-
- EXPECT_TRUE(message_queue->Initialize());
-
- String socket_addr = message_queue->GetSocketAddress();
-
- // Make sure the name starts with the expected value
- EXPECT_EQ(0U, socket_addr.find("o3d"));
-
- delete message_queue;
- EXPECT_FALSE(CheckErrorExists());
-}
-
-// Tests that the a client can actually establish a connection to the
-// MessageQueue.
-TEST_F(MessageQueueTest, TestConnection) {
- class ConnectionTest : public PerThreadConnectedTest {
- public:
- void Run(MessageQueue* queue,
- nacl::Handle socket_handle) {
- String socket_addr = queue->GetSocketAddress();
- TextureUpdateHelper helper;
- if (helper.ConnectToO3D(socket_addr.c_str(),
- socket_handle)) {
- Pass();
- } else {
- FAIL_TEST("Failed to connect to O3D");
- }
- }
- };
-
- class Provider : public TestProvider {
- public:
- virtual PerThreadConnectedTest* CreateTest() {
- return new ConnectionTest();
- }
- };
-
- Provider provider;
- RunTests(1, TimeDelta::FromSeconds(1), &provider);
- EXPECT_FALSE(CheckErrorExists());
-}
-
-// Tests a request for shared memory.
-TEST_F(MessageQueueTest, GetSharedMemory) {
- class SharedMemoryTest : public PerThreadConnectedTest {
- public:
- void Run(MessageQueue* queue,
- nacl::Handle socket_handle) {
- String socket_addr = queue->GetSocketAddress();
- TextureUpdateHelper helper;
- if (!helper.ConnectToO3D(socket_addr.c_str(),
- socket_handle)) {
- FAIL_TEST("Failed to connect to O3D");
- }
-
- void *shared_mem_address = NULL;
- int shared_mem_id = -1;
- bool memory_ok = helper.RequestSharedMemory(65536,
- &shared_mem_id,
- &shared_mem_address);
- if (shared_mem_id == -1) {
- FAIL_TEST("Shared memory id was -1");
- }
-
- if (shared_mem_address == NULL) {
- FAIL_TEST("Shared memory address was NULL");
- }
-
- if (!memory_ok) {
- FAIL_TEST("Memory request failed");
- }
-
- Pass();
- }
- };
-
- class Provider : public TestProvider {
- public:
- virtual PerThreadConnectedTest* CreateTest() {
- return new SharedMemoryTest();
- }
- };
-
- Provider provider;
- RunTests(1, TimeDelta::FromSeconds(1), &provider);
-}
-
-// Tests a request to update a texture.
-TEST_F(MessageQueueTest, UpdateTexture2D) {
- class UpdateTexture2DTest : public PerThreadConnectedTest {
- public:
- UpdateTexture2DTest(int texture_id, int buffer_size)
- : texture_id_(texture_id),
- buffer_size_(buffer_size) {
- }
-
- void Run(MessageQueue* queue,
- nacl::Handle socket_handle) {
- String socket_addr = queue->GetSocketAddress();
- TextureUpdateHelper helper;
- if (!helper.ConnectToO3D(socket_addr.c_str(),
- socket_handle)) {
- FAIL_TEST("Failed to connect to O3D");
- }
-
- void *shared_mem_address = NULL;
- int shared_mem_id = -1;
- bool memory_ok = helper.RequestSharedMemory(65536,
- &shared_mem_id,
- &shared_mem_address);
- if (shared_mem_id == -1) {
- FAIL_TEST("Shared memory id was -1");
- }
-
- if (shared_mem_address == NULL) {
- FAIL_TEST("Shared memory address was NULL");
- }
-
- if (!memory_ok) {
- FAIL_TEST("Memory request failed");
- }
-
- if (!helper.RequestTextureUpdate(texture_id_,
- 0,
- shared_mem_id,
- 0,
- buffer_size_)) {
- FAIL_TEST("RequestTextureUpdate failed");
- }
-
- Pass();
- }
-
- private:
- int texture_id_;
- int buffer_size_;
- };
-
- class Provider : public TestProvider {
- public:
- Provider(int texture_id, int buffer_size)
- : texture_id_(texture_id),
- buffer_size_(buffer_size) {
- }
-
- virtual PerThreadConnectedTest* CreateTest() {
- return new UpdateTexture2DTest(texture_id_, buffer_size_);
- }
-
- private:
- int texture_id_;
- int buffer_size_;
- };
-
- Texture2D* texture = pack()->CreateTexture2D(128,
- 128,
- Texture::ARGB8,
- 0,
- false);
-
- ASSERT_TRUE(texture != NULL);
-
- Provider provider(texture->id(), 128 * 128 * 4);
- RunTests(1, TimeDelta::FromSeconds(1), &provider);
- EXPECT_FALSE(CheckErrorExists());
-}
-
-// Tests a request to update a partial texture.
-TEST_F(MessageQueueTest, UpdateTexture2DPartial) {
- class UpdateTexture2DTest : public PerThreadConnectedTest {
- public:
- UpdateTexture2DTest(int texture_id, int buffer_size)
- : texture_id_(texture_id),
- buffer_size_(buffer_size) {
- }
-
- void Run(MessageQueue* queue,
- nacl::Handle socket_handle) {
- String socket_addr = queue->GetSocketAddress();
- TextureUpdateHelper helper;
- if (!helper.ConnectToO3D(socket_addr.c_str(),
- socket_handle)) {
- FAIL_TEST("Failed to connect to O3D");
- }
-
- void *shared_mem_address = NULL;
- int shared_mem_id = -1;
- bool memory_ok = helper.RequestSharedMemory(65536,
- &shared_mem_id,
- &shared_mem_address);
- if (shared_mem_id == -1) {
- FAIL_TEST("Shared memory id was -1");
- }
-
- if (shared_mem_address == NULL) {
- FAIL_TEST("Shared memory address was NULL");
- }
-
- if (!memory_ok) {
- FAIL_TEST("Memory request failed");
- }
-
- if (!helper.RequestTextureUpdate(texture_id_,
- 0,
- shared_mem_id,
- 0,
- buffer_size_)) {
- FAIL_TEST("RequestTextureUpdate failed");
- }
-
- Pass();
- }
-
- private:
- int texture_id_;
- int buffer_size_;
- };
-
- class Provider : public TestProvider {
- public:
- Provider(int texture_id, int buffer_size)
- : texture_id_(texture_id),
- buffer_size_(buffer_size) {
- }
-
- virtual PerThreadConnectedTest* CreateTest() {
- return new UpdateTexture2DTest(texture_id_, buffer_size_);
- }
-
- private:
- int texture_id_;
- int buffer_size_;
- };
-
- // Check updating a partial texture.
- // Because we pass in 8 * 127 * 4 + 4 that means we'll update
- // 127 rows and 1 pixel in the last row.
- Texture2D* texture = pack()->CreateTexture2D(8,
- 128,
- Texture::ARGB8,
- 0,
- false);
-
- ASSERT_TRUE(texture != NULL);
-
- Provider provider(texture->id(), 8 * 127 * 4 + 4);
- RunTests(1, TimeDelta::FromSeconds(1), &provider);
- EXPECT_FALSE(CheckErrorExists());
-}
-
-// Tests a request to update a texture.
-TEST_F(MessageQueueTest, UpdateTexture2DRect) {
- class UpdateTexture2DRectTest : public PerThreadConnectedTest {
- private:
- int texture_id_;
-
- public:
- explicit UpdateTexture2DRectTest(int texture_id) {
- texture_id_ = texture_id;
- }
-
- void Run(MessageQueue* queue,
- nacl::Handle socket_handle) {
- String socket_addr = queue->GetSocketAddress();
- TextureUpdateHelper helper;
- if (!helper.ConnectToO3D(socket_addr.c_str(),
- socket_handle)) {
- FAIL_TEST("Failed to connect to O3D");
- }
-
- void *shared_mem_address = NULL;
- int shared_mem_id = -1;
- bool memory_ok = helper.RequestSharedMemory(65536,
- &shared_mem_id,
- &shared_mem_address);
- if (shared_mem_id == -1) {
- FAIL_TEST("Shared memory id was -1");
- }
-
- if (shared_mem_address == NULL) {
- FAIL_TEST("Shared memory address was NULL");
- }
-
- if (!memory_ok) {
- FAIL_TEST("Memory request failed");
- }
-
- const int kLevel = 0;
- const int kX = 10;
- const int kY = 11;
- const int kWidth = 12;
- const int kHeight = 13;
- const int kTextureRectSize = kWidth * kHeight * 4;
-
- if (!helper.RequestTextureRectUpdate(texture_id_,
- kLevel,
- kX,
- kY,
- kWidth,
- kHeight,
- shared_mem_id,
- 0,
- kTextureRectSize)) {
- FAIL_TEST("RequestTextureRectUpdate failed");
- }
-
- Pass();
- }
- };
-
- class Provider : public TestProvider {
- private:
- int texture_id_;
-
- public:
- explicit Provider(int texture_id) : texture_id_(texture_id) {}
-
- virtual PerThreadConnectedTest* CreateTest() {
- return new UpdateTexture2DRectTest(texture_id_);
- }
- };
-
- Texture2D* texture = pack()->CreateTexture2D(128,
- 128,
- Texture::ARGB8,
- 0,
- false);
-
- ASSERT_TRUE(texture != NULL);
-
- Provider provider(texture->id());
- RunTests(1, TimeDelta::FromSeconds(1), &provider);
- EXPECT_FALSE(CheckErrorExists());
-}
-
-namespace {
-
-// This helper class is used for both single-threaded and concurrent
-// shared memory registration / unregistration tests.
-class SharedMemoryRegisterUnregisterTest : public PerThreadConnectedTest {
- private:
- int num_iterations_;
-
- public:
- explicit SharedMemoryRegisterUnregisterTest(int num_iterations) {
- num_iterations_ = num_iterations;
- }
-
- void Run(MessageQueue* queue,
- nacl::Handle socket_handle) {
- String socket_addr = queue->GetSocketAddress();
- TextureUpdateHelper helper;
- if (!helper.ConnectToO3D(socket_addr.c_str(),
- socket_handle)) {
- FAIL_TEST("Failed to connect to O3D");
- }
-
- // Allocate a shared memory segment
- size_t mem_size = nacl::kMapPageSize;
- nacl::Handle shared_memory = nacl::CreateMemoryObject(mem_size);
- if (shared_memory == nacl::kInvalidHandle) {
- FAIL_TEST("Failed to allocate shared memory object");
- }
-
- // Note that we don't actually have to map it in our process in
- // order to test the failure mode (corrupted messages) this test
- // exercises
-
- for (int i = 0; i < num_iterations_; i++) {
- int shared_mem_id =
- helper.RegisterSharedMemory(shared_memory, mem_size);
- if (shared_mem_id < 0) {
- FAIL_TEST("Failed to register shared memory with server");
- }
- bool result = helper.UnregisterSharedMemory(shared_mem_id);
- if (!result) {
- FAIL_TEST("Failed to unregister shared memory from server");
- }
- }
-
- nacl::Close(shared_memory);
-
- Pass();
- }
-};
-
-} // anonymous namespace.
-
-// Tests that a simple shared memory registration and unregistration
-// pair appear to work.
-TEST_F(MessageQueueTest, RegisterAndUnregisterSharedMemory) {
- class Provider : public TestProvider {
- public:
- virtual PerThreadConnectedTest* CreateTest() {
- return new SharedMemoryRegisterUnregisterTest(1);
- }
- };
-
- Provider provider;
- RunTests(1, TimeDelta::FromSeconds(1), &provider);
- EXPECT_FALSE(CheckErrorExists());
-}
-
-// Tests that multiple concurrent clients of the MessageQueue don't
-// break its deserialization operations.
-TEST_F(MessageQueueTest, ConcurrentSharedMemoryOperations) {
- class Provider : public TestProvider {
- public:
- virtual PerThreadConnectedTest* CreateTest() {
- return new SharedMemoryRegisterUnregisterTest(100);
- }
- };
-
- Provider provider;
- RunTests(2, TimeDelta::FromSeconds(6), &provider);
- EXPECT_FALSE(CheckErrorExists());
-}
-
-namespace {
-
-// This is a helper class for Render test.
-class RenderTest : public PerThreadConnectedTest {
- private:
- int num_iterations_;
-
- public:
- explicit RenderTest(int num_iterations) {
- num_iterations_ = num_iterations;
- }
-
- void Run(MessageQueue* queue,
- nacl::Handle socket_handle) {
- String socket_addr = queue->GetSocketAddress();
- TextureUpdateHelper helper;
- if (!helper.ConnectToO3D(socket_addr.c_str(),
- socket_handle)) {
- FAIL_TEST("Failed to connect to O3D");
- }
-
- // Allocate a shared memory segment
- size_t mem_size = nacl::kMapPageSize;
- nacl::Handle shared_memory = nacl::CreateMemoryObject(mem_size);
- if (shared_memory == nacl::kInvalidHandle) {
- FAIL_TEST("Failed to allocate shared memory object");
- }
-
- for (int i = 0; i < num_iterations_; i++) {
- bool result = helper.Render();
- if (!result) {
- FAIL_TEST("Failed to request a render");
- }
- // Because Render has no result we run a few more messages the do
- // to make sure Render was processed.
- int shared_mem_id =
- helper.RegisterSharedMemory(shared_memory, mem_size);
- if (shared_mem_id < 0) {
- FAIL_TEST("Failed to register shared memory with server");
- }
- result = helper.UnregisterSharedMemory(shared_mem_id);
- if (!result) {
- FAIL_TEST("Failed to unregister shared memory from server");
- }
- }
-
- Pass();
- }
-};
-
-} // anonymous namespace.
-
-// Tests requesting a render.
-TEST_F(MessageQueueTest, Render) {
- class Provider : public TestProvider {
- public:
- virtual PerThreadConnectedTest* CreateTest() {
- return new RenderTest(1);
- }
- };
-
- Renderer* renderer(g_service_locator->GetService<Renderer>());
- ASSERT_TRUE(renderer != NULL);
- renderer->set_need_to_render(false);
-
- Provider provider;
- RunTests(1, TimeDelta::FromSeconds(1), &provider);
- EXPECT_FALSE(CheckErrorExists());
- EXPECT_TRUE(renderer->need_to_render());
-}
-
-namespace {
-
-// This is a helper class for GetVersion test.
-class GetVersionTest : public PerThreadConnectedTest {
- private:
- int num_iterations_;
-
- public:
- explicit GetVersionTest(int num_iterations) {
- num_iterations_ = num_iterations;
- }
-
- void Run(MessageQueue* queue, nacl::Handle socket_handle) {
- String socket_addr = queue->GetSocketAddress();
- TextureUpdateHelper helper;
- if (!helper.ConnectToO3D(socket_addr.c_str(), socket_handle)) {
- FAIL_TEST("Failed to connect to O3D");
- }
-
- for (int i = 0; i < num_iterations_; i++) {
- bool result = helper.GetVersion();
- if (!result) {
- FAIL_TEST("Failed to request a GetVersion");
- }
- }
-
- Pass();
- }
-};
-
-} // anonymous namespace.
-
-// Tests requesting a GetVersion.
-TEST_F(MessageQueueTest, GetVersion) {
- class Provider : public TestProvider {
- public:
- virtual PerThreadConnectedTest* CreateTest() {
- return new GetVersionTest(1);
- }
- };
-
- Provider provider;
- RunTests(1, TimeDelta::FromSeconds(1), &provider);
- EXPECT_FALSE(CheckErrorExists());
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/named_object.cc b/o3d/core/cross/named_object.cc
deleted file mode 100644
index 2c8e3b7..0000000
--- a/o3d/core/cross/named_object.cc
+++ /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.
- */
-
-
-// This file contains the definition of the NamedObject class.
-
-#include "core/cross/named_object.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(NamedObjectBase, ObjectBase);
-O3D_DEFN_CLASS(NamedObject, NamedObjectBase);
-
-NamedObjectBase::NamedObjectBase(ServiceLocator *service_locator)
- : ObjectBase(service_locator) {
-}
-
-const String& NamedObject::name() const {
- return name_;
-}
-
-NamedObject::NamedObject(ServiceLocator *service_locator)
- : NamedObjectBase(service_locator) {
-}
-
-
-} // namespace o3d
diff --git a/o3d/core/cross/named_object.h b/o3d/core/cross/named_object.h
deleted file mode 100644
index 0ff7524..0000000
--- a/o3d/core/cross/named_object.h
+++ /dev/null
@@ -1,84 +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 declaration of NamedObject.
-
-#ifndef O3D_CORE_CROSS_NAMED_OBJECT_H_
-#define O3D_CORE_CROSS_NAMED_OBJECT_H_
-
-#include "core/cross/object_base.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-class ServiceLocator;
-
-// Base class of all objects that are identifiable by a name.
-class NamedObjectBase: public ObjectBase {
- public:
- typedef SmartPointer<NamedObjectBase> Ref;
-
- explicit NamedObjectBase(ServiceLocator *service_locator);
-
- // \brief Returns the object's name
- virtual const String& name() const = 0;
-
- private:
- O3D_DECL_CLASS(NamedObjectBase, ObjectBase);
- DISALLOW_COPY_AND_ASSIGN(NamedObjectBase);
-};
-
-// A class of all objects that are identifiable by a name where the name is
-// settable at any time. This as opposed to Param where the name is only
-// settable once.
-class NamedObject: public NamedObjectBase {
- public:
- typedef SmartPointer<NamedObject> Ref;
-
- explicit NamedObject(ServiceLocator *service_locator);
-
- // \brief Returns the object's name
- virtual const String& name() const;
-
- void set_name(const String& new_name) {
- name_ = new_name;
- }
-
- private:
- String name_;
- O3D_DECL_CLASS(NamedObject, NamedObjectBase);
- DISALLOW_COPY_AND_ASSIGN(NamedObject);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_NAMED_OBJECT_H_
diff --git a/o3d/core/cross/object_base.cc b/o3d/core/cross/object_base.cc
deleted file mode 100644
index c998da0..0000000
--- a/o3d/core/cross/object_base.cc
+++ /dev/null
@@ -1,93 +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 definition of the ObjectBase class.
-
-#include "core/cross/object_base.h"
-#include "core/cross/service_locator.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/id_manager.h"
-
-namespace o3d {
-
-ObjectBase::Class ObjectBase::class_ = {
- O3D_STRING_CONSTANT("ObjectBase"), NULL
-};
-
-const char* ObjectBase::Class::unqualified_name() const {
- if (strncmp(
- name_,
- O3D_NAMESPACE O3D_NAMESPACE_SEPARATOR,
- sizeof(O3D_NAMESPACE) + sizeof(O3D_NAMESPACE_SEPARATOR) - 2) == 0) {
- return name_ + sizeof(O3D_NAMESPACE) + sizeof(O3D_NAMESPACE_SEPARATOR) - 2;
- }
- return name_;
-}
-
-ObjectBase::ObjectBase(ServiceLocator *service_locator)
- : id_(IdManager::CreateId()),
- service_locator_(service_locator) {
- // Upon object construction, register this object with the object manager
- // to allow for central lookup.
- ObjectManager* object_manager = service_locator_->GetService<ObjectManager>();
- if (object_manager) {
- object_manager->RegisterObject(this);
- }
-}
-
-ObjectBase::~ObjectBase() {
- // Upon destruction, unregister this object from the owning client.
- ObjectManager* object_manager = service_locator_->GetService<ObjectManager>();
- if (object_manager) {
- object_manager->UnregisterObject(this);
- }
-}
-
-bool ObjectBase::ClassIsA(const Class *derived, const Class *base) {
- // find base in the hierarchy of derived
- for (; derived; derived = derived->parent()) {
- if (derived == base) return true;
- }
- return false;
-}
-
-bool ObjectBase::ClassIsAClassName(const Class *derived, const String& name) {
- // find base in the hierarchy of derived
- for (; derived; derived = derived->parent()) {
- if (name.compare(derived->name()) == 0) {
- return true;
- }
- }
- return false;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/object_base.h b/o3d/core/cross/object_base.h
deleted file mode 100644
index b4939c1..0000000
--- a/o3d/core/cross/object_base.h
+++ /dev/null
@@ -1,243 +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 declaration of the ObjectBase class and definitions
-// for the macros used to define the O3D object classes.
-
-#ifndef O3D_CORE_CROSS_OBJECT_BASE_H_
-#define O3D_CORE_CROSS_OBJECT_BASE_H_
-
-#include <vector>
-
-#include "core/cross/types.h"
-#include "core/cross/smart_ptr.h"
-
-#define O3D_NAMESPACE "o3d"
-#define O3D_NAMESPACE_SEPARATOR "."
-
-// Macro to provide a uniform prefix for all string constants created by
-// o3d. We reserve this prefix so that we never overwrite a user
-// created Transform, RenderNode, Param, Effect, State etc.
-#define O3D_STRING_CONSTANT(value) \
- (O3D_NAMESPACE O3D_NAMESPACE_SEPARATOR value)
-
-
-// This macro declares the necessary functions for the type mechanism to work.
-// It needs to be used in each of the definition of any class that derives from
-// ObjectBase.
-// CLASS is the class being defined, BASE is its base class.
-#define O3D_OBJECT_BASE_DECL_CLASS(CLASS, BASE) \
- public: \
- static const ObjectBase::Class *GetApparentClass() { return &class_; } \
- static const String GetApparentClassName() { \
- return class_.name(); \
- } \
- virtual const ObjectBase::Class *GetClass() const { \
- return GetApparentClass(); \
- } \
- virtual String GetClassName() const { \
- return GetApparentClass()->name(); \
- } \
- private: \
- static ObjectBase::Class class_;
-
-// This macro defines the class descriptor for the type mechanism. It needs to
-// be used once in the definition file of any class that derives from
-// ObjectBase.
-// CLASSNAME is the name to use to identify the class.
-// CLASS is the class being defined.
-// BASE is its base class.
-#define O3D_OBJECT_BASE_DEFN_CLASS(CLASSNAME, CLASS, BASE) \
- ObjectBase::Class CLASS::class_ = { CLASSNAME, BASE::GetApparentClass() };
-
-// This macro declares the necessary functions for the type mechanism to work.
-// It needs to be used in each of the definition of any class that derives from
-// ObjectBase.
-// CLASS is the class being defined, BASE is its base class.
-#define O3D_DECL_CLASS(CLASS, BASE) O3D_OBJECT_BASE_DECL_CLASS(CLASS, BASE)
-
-// This macro defines the class descriptor for the type mechanism. It needs to
-// be used once in the definition file of any class that derives from
-// ObjectBase.
-// CLASS is the class being defined, BASE is its base class.
-#define O3D_DEFN_CLASS(CLASS, BASE) \
- O3D_OBJECT_BASE_DEFN_CLASS(O3D_STRING_CONSTANT(#CLASS), CLASS, BASE)
-
-namespace o3d {
-
-class ServiceLocator;
-
-// class ObjectBase: base of O3D run-time objects.
-// This class provides the basic functionality for all O3D objects, in
-// particular so that the JavaScript interface is functional and safe:
-// - unique id, as a safe reference to the instance. The id -> instance mapping
-// is handled by the Client.
-// - simple run-time typeinformation mechanism. For this to work, the
-// O3D_DECL_CLASS and O3D_DEFN_CLASS need to be used in each class
-// deriving from ObjectBase.
-//
-// The type mechanism works as following. Say you have two classes:
-//
-// class A: public ObjectBase {
-// O3D_DECL_CLASS(A, ObjectBase)
-// };
-//
-// class B: public A {
-// O3D_DECL_CLASS(B, A)
-// };
-//
-// And then you have:
-//
-// A *a = new A();
-// B *b = new B();
-// A *c = new B();
-// ObjectBase::Class *a_class = A::GetApparentClass();
-// ObjectBase::Class *b_class = B::GetApparentClass();
-//
-// Then:
-//
-// a->GetClass() will return a_class - meaning 'a' is a 'A'
-// b->GetClass() will return b_class - meaning 'b' is a 'B'
-// c->GetClass() will return b_class - meaning 'c' is a 'B', even though the
-// apparent type of 'c' is 'A *'.
-// a->IsA(a_class) is true.
-// a->IsA(b_class) is false.
-// b->IsA(a_class) is true ('b' is a 'B' that derives from 'A')
-// c->IsA(b_class) is true ('c' is a 'B', even though its apparent type is
-// 'A *')
-//
-// You can also test types descriptors themselves:
-//
-// ObjectBase::ClassIsA(a_class, b_class) is false ('A' doesn't derive from 'B')
-// ObjectBase::ClassIsA(b_class, a_class) is true ('B' derives from 'A')
-class ObjectBase : public RefCounted {
- public:
- typedef SmartPointer<ObjectBase> Ref;
-
- // Structure describing the class. A single instance of this struct exists for
- // each class deriving from ObjectBase. Note: This is a struct with all public
- // members because we need to be able to statically define them but we have
- // accessors because we want it treated like a class by the code.
- struct Class {
- public:
- const Class* parent() const {
- return parent_;
- }
-
- const char* name() const {
- return name_;
- }
-
- const char* unqualified_name() const;
-
- public:
- // The name of the class.
- const char *name_;
- // The base class descriptor.
- const Class *parent_;
- };
-
- explicit ObjectBase(ServiceLocator* service_locator);
- virtual ~ObjectBase();
-
- // Return the owning client for this object.
- ServiceLocator* service_locator() const {
- return service_locator_;
- }
-
- // Returns the unique id of the instance.
- const Id id() const {
- return id_;
- }
-
- // Returns the class descriptor for this class.
- static const Class *GetApparentClass() {
- return &class_;
- }
-
- // Returns whether a class derives from a base class.
- static bool ClassIsA(const Class *derived, const Class *base);
-
- // Returns whether a class derives from a base class by class name
- static bool ClassIsAClassName(const Class* derived,
- const String& class_name);
-
- // Returns the class descriptor for this instance.
- virtual const Class *GetClass() const {
- return GetApparentClass();
- }
-
- // Returns the class name for this instance.
- virtual String GetClassName() const {
- return GetApparentClass()->name();
- }
-
- // Returns whether this instance "is a" another type (its class derives from
- // the other class).
- bool IsA(const Class *base) const {
- return ClassIsA(GetClass(), base);
- }
-
- // Returns whether this instance "is a" another type by class name (its class
- // derives from the other class).
- bool IsAClassName(const String& class_name) {
- return ClassIsAClassName(GetClass(), class_name);
- }
-
- // A dynamic_cast for types derived from ObjectBase. Like dynamic_cast it will
- // return NULL if the cast fails. Also like dynamic_cast it's slow! Note:
- // Unlike dynamic_cast you don't specify a pointer as the type so
- //
- // Derived* d = ObjectBase::rtti_dynamic_cast<Derived>(base); // correct
- // Derived* d = ObjectBase::rtti_dynamic_cast<Derived*>(base); // wrong!
- template <typename T>
- static T* rtti_dynamic_cast(ObjectBase* object) {
- return (object && object->IsA(T::GetApparentClass())) ?
- static_cast<T*>(object) : 0;
- }
-
- private:
- Id id_;
- ServiceLocator* service_locator_;
- static Class class_;
-};
-
-inline Id GetObjectId(const ObjectBase* object) {
- return object == NULL ? 0 : object->id();
-}
-
-// Array container for ObjectBase pointers
-typedef std::vector<ObjectBase*> ObjectBaseArray;
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_OBJECT_BASE_H_
diff --git a/o3d/core/cross/object_base_test.cc b/o3d/core/cross/object_base_test.cc
deleted file mode 100644
index 00edb75..0000000
--- a/o3d/core/cross/object_base_test.cc
+++ /dev/null
@@ -1,83 +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 ObjectBase.
-
-#include "core/cross/object_base.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-#include "tests/common/win/testing_common.h"
-
-namespace o3d {
-
-class ObjectBaseTest : public testing::Test {
- protected:
- ObjectBaseTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- protected:
- ServiceDependency<ObjectManager> object_manager_;
- Pack* pack_;
-};
-
-void ObjectBaseTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void ObjectBaseTest::TearDown() {
- object_manager_->DestroyPack(pack_);
-}
-
-TEST_F(ObjectBaseTest, ObjectIdOfNullIsZero) {
- ASSERT_EQ(0U, GetObjectId(NULL));
-}
-
-TEST_F(ObjectBaseTest, ObjectIdOfObjectIsReturned) {
- ASSERT_EQ(pack_->id(), GetObjectId(pack_));
-}
-
-TEST_F(ObjectBaseTest, ObjectClassName) {
- ASSERT_EQ(0,
- strcmp(ObjectBase::GetApparentClass()->name(),
- "o3d.ObjectBase"));
- ASSERT_EQ(0,
- strcmp(ObjectBase::GetApparentClass()->unqualified_name(),
- "ObjectBase"));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/object_manager.cc b/o3d/core/cross/object_manager.cc
deleted file mode 100644
index cf13cb6..0000000
--- a/o3d/core/cross/object_manager.cc
+++ /dev/null
@@ -1,141 +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 "core/cross/object_manager.h"
-#include "core/cross/named_object.h"
-#include "core/cross/pack.h"
-#include "core/cross/client.h"
-
-namespace o3d {
-
-const InterfaceId ObjectManager::kInterfaceId =
- InterfaceTraits<ObjectManager>::kInterfaceId;
-
-ObjectManager::ObjectManager(ServiceLocator* service_locator)
- : service_locator_(service_locator),
- service_(service_locator_, this) {
-}
-
-ObjectManager::~ObjectManager() {
- // Free all the packs.
- pack_array_.clear();
-
- DLOG_ASSERT(object_map_.empty()) << "Client node leak.";
-}
-
-std::vector<ObjectBase*> ObjectManager::GetObjects(
- const String& name,
- const String& class_type_name) const {
- ObjectBaseArray objects;
- ObjectMap::const_iterator end(object_map_.end());
- for (ObjectMap::const_iterator iter(object_map_.begin());
- iter != end;
- ++iter) {
- if (iter->second->IsAClassName(class_type_name) &&
- iter->second->IsA(NamedObjectBase::GetApparentClass()) &&
- down_cast<NamedObjectBase*>(iter->second)->name().compare(name) == 0) {
- objects.push_back(iter->second);
- }
- }
- return objects;
-}
-
-std::vector<ObjectBase*> ObjectManager::GetObjectsByClassName(
- const String& class_type_name) const {
- ObjectBaseArray objects;
- ObjectMap::const_iterator end(object_map_.end());
- for (ObjectMap::const_iterator iter(object_map_.begin());
- iter != end;
- ++iter) {
- if (iter->second->IsAClassName(class_type_name)) {
- objects.push_back(iter->second);
- }
- }
- return objects;
-}
-
-ObjectBase *ObjectManager::GetObjectBaseById(
- Id id,
- const ObjectBase::Class *type) const {
- ObjectMap::const_iterator object_find(object_map_.find(id));
- ObjectBase* object = NULL;
- if (object_find != object_map_.end()) {
- object = object_find->second;
- }
-
- if (object && !object->IsA(type)) {
- object = NULL;
- }
-
- return object;
-}
-
-void ObjectManager::RegisterObject(ObjectBase *object) {
- DLOG_ASSERT(object_map_.find(object->id()) == object_map_.end())
- << "attempt to register duplicate id in client";
- object_map_.insert(std::make_pair(object->id(), object));
-}
-
-void ObjectManager::UnregisterObject(ObjectBase *object) {
- ObjectMap::iterator object_find(object_map_.find(object->id()));
- DLOG_ASSERT(object_find != object_map_.end())
- << "Unregistering an unknown object.";
-
- if (object_find != object_map_.end()) {
- object_map_.erase(object_find);
- }
-}
-
-bool ObjectManager::DestroyPack(Pack* pack) {
- PackRefArray::iterator iter = find(pack_array_.begin(),
- pack_array_.end(),
- pack);
- DLOG_ASSERT(iter != pack_array_.end()) << "Destruction of unknown pack.";
- if (iter != pack_array_.end()) {
- pack_array_.erase(iter);
- return true;
- }
- return false;
-}
-
-Pack* ObjectManager::CreatePack() {
- Pack::Ref pack(new Pack(service_locator_));
- if (pack) {
- pack_array_.push_back(pack);
- }
- return pack;
-}
-
-void ObjectManager::DestroyAllPacks() {
- pack_array_.clear();
-}
-} // namespace o3d
diff --git a/o3d/core/cross/object_manager.h b/o3d/core/cross/object_manager.h
deleted file mode 100644
index fea7d62..0000000
--- a/o3d/core/cross/object_manager.h
+++ /dev/null
@@ -1,209 +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_CORE_CROSS_OBJECT_MANAGER_H_
-#define O3D_CORE_CROSS_OBJECT_MANAGER_H_
-
-#include <map>
-#include <vector>
-
-#include "core/cross/object_base.h"
-#include "core/cross/named_object.h"
-#include "core/cross/service_implementation.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/types.h"
-#include "core/cross/error.h"
-
-namespace o3d {
-
-class Pack;
-
-// Maintains a collection of all objects deriving from ObjectBase. Objects and
-// lists of objects can be found based on various criteria.
-class ObjectManager {
- public:
- static const InterfaceId kInterfaceId;
-
- explicit ObjectManager(ServiceLocator* service_locator);
- ~ObjectManager();
-
- // Disallows pack creation.
- void DisallowPackCreation();
-
- // Searches in the Client for a base object by its id. If the dynamic type
- // of the object matches the requested type, then a pointer to the instance
- // is returned.
- // This is an internal function. You should use GetById from C++.
- // Parameters:
- // id: The id of the ObjectBase to search for type: The class instance
- // specifier used to filter the return value.
- // Returns:
- // A pointer to the ObjectBase instance if found and of the matching
- // dynamic type or NULL otherwise.
- ObjectBase *GetObjectBaseById(Id id, const ObjectBase::Class *type) const;
-
- // Searches in the Client for an object by its id. This function is for
- // Javascript.
- // Parameters:
- // id: id of object to look for.
- // Returns:
- // Pointer to the object or NULL if not found.
- ObjectBase* GetObjectById(Id id) const {
- return GetObjectBaseById(id, ObjectBase::GetApparentClass());
- }
-
- // Searches by id for an Object created by the Client. To search
- // for an object regardless of type use:
- // Client::GetById<ObjectBase>(obj_id)
- // To search for an object of a specific type use:
- // Client::GetById<Type>(obj_id)
- // for example, to search for Transform use:
- // Client::GetById<Transform>(transform_id)
- // Parameters:
- // id: Unique id of the object to search for
- // Returns:
- // Pointer to the object with matching id or NULL if no object is found
- template<class T> T* GetById(Id id) const {
- return static_cast<T *>(GetObjectBaseById(id, T::GetApparentClass()));
- }
-
- // Get an object by name typesafe. This function is for C++
- // Example:
- // Buffer* buffer = client->Get<Buffer>("name");
- // Parameters:
- // name: name of object to search for.
- // Returns:
- // std::vector of pointers to type of the objects that matched by name.
- template<typename T>
- std::vector<T*> Get(const String& name) const {
- std::vector<T*> objects;
- if (ObjectBase::ClassIsA(T::GetApparentClass(),
- NamedObject::GetApparentClass())) {
- ObjectMap::const_iterator end(object_map_.end());
- for (ObjectMap::const_iterator iter(object_map_.begin());
- iter != end;
- ++iter) {
- if (iter->second->IsA(T::GetApparentClass())) {
- if (static_cast<NamedObject*>(
- iter->second)->name().compare(name) == 0) {
- objects.push_back(static_cast<T*>(iter->second));
- }
- }
- }
- }
- return objects;
- }
- // Searches the Client for objects of a particular name and type.
- // This function is for Javascript.
- // Parameters:
- // name: name of object to look for.
- // type_name: name of class to look for.
- // Returns:
- // Array of raw pointers to the found objects.
- std::vector<ObjectBase*> GetObjects(const String& name,
- const String& type_name) const;
-
- // Search the client for all objects of a certain class
- // Parameters:
- // class_type_name: the Class of the object. It is okay to pass base types
- // for example Node::GetApparentClass()->name will return
- // both Transforms and Shapes.
- // Returns:
- // Array of Object Pointers.
- std::vector<ObjectBase*> GetObjectsByClassName(
- const String& class_type_name) const;
-
- // Search the client for all objects of a certain class
- // Returns:
- // Array of Pointers to the requested class.
- template<typename T>
- std::vector<T*> GetByClass() const {
- std::vector<T*> objects;
- ObjectMap::const_iterator end(object_map_.end());
- for (ObjectMap::const_iterator iter(object_map_.begin());
- iter != end;
- ++iter) {
- if (iter->second->IsA(T::GetApparentClass())) {
- objects.push_back(static_cast<T*>(iter->second));
- }
- }
- return objects;
- }
-
- void RegisterObject(ObjectBase *object);
- void UnregisterObject(ObjectBase *object);
-
- // Pack methods --------------------------
-
- // Removes all internal references to the Pack from the client.
- // The pack, and all objects contained in it are permitted to be destroyed
- // after the packs destruction. Nodes will only be destoryed after all
- // references to them have been removed.
- // This is an internal function not to be exposed to the external world.
- // Returns:
- // True if the pack was successfully deleted.
- bool DestroyPack(Pack* pack);
-
- // Creates a pack object, and registers it within the Client's internal
- // dictionary strutures. Note that multiple packs may share the same name.
- // The system does not enforce pack name uniqueness.
- // Returns:
- // A smart-pointer reference to the newly created pack object.
- Pack* CreatePack();
-
- // Destroys all registered packs.
- void DestroyAllPacks();
-
- size_t GetNumObjects() const {
- return object_map_.size();
- }
-
- private:
- typedef std::vector<SmartPointer<Pack> > PackRefArray;
-
- // Dictionary of Objects indexed by their unique ID
- typedef std::map<Id, ObjectBase*> ObjectMap;
-
- ServiceLocator* service_locator_;
- ServiceImplementation<ObjectManager> service_;
-
- // Map of objects to Ids
- ObjectMap object_map_;
-
- // Array required to maintain references to the currently live pack objects.
- PackRefArray pack_array_;
-
- DISALLOW_COPY_AND_ASSIGN(ObjectManager);
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_OBJECT_MANAGER_H_
diff --git a/o3d/core/cross/pack.cc b/o3d/core/cross/pack.cc
deleted file mode 100644
index ce6bfdc..0000000
--- a/o3d/core/cross/pack.cc
+++ /dev/null
@@ -1,496 +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.
- */
-
-
-// Pack file.
-
-#include "base/file_path.h"
-#include "core/cross/pack.h"
-#include "core/cross/bitmap.h"
-#include "core/cross/draw_context.h"
-#include "import/cross/archive_request.h"
-#include "import/cross/raw_data.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-#include "core/cross/file_request.h"
-#include "core/cross/image_utils.h"
-#include "core/cross/render_node.h"
-#include "core/cross/iclass_manager.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/renderer.h"
-#include "core/cross/error.h"
-#include "utils/cross/file_path_utils.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Pack, NamedObject)
-
-Pack::Pack(ServiceLocator* service_locator)
- : NamedObject(service_locator),
- class_manager_(service_locator->GetService<IClassManager>()),
- object_manager_(service_locator->GetService<ObjectManager>()),
- renderer_(service_locator->GetService<Renderer>()) {
-}
-
-Pack::~Pack() {
- DLOG(INFO) << owned_objects_.size()
- << " objects still in Pack at time of deletion";
-}
-
-bool Pack::Destroy() {
- return object_manager_->DestroyPack(this);
-}
-
-bool Pack::RemoveObject(ObjectBase* object) {
- return UnregisterObject(object);
-}
-
-Transform* Pack::root() const {
- return root_.Get();
-}
-
-void Pack::set_root(Transform *root) {
- root_ = Transform::Ref(root);
-}
-
-ObjectBase* Pack::CreateObject(const String& type_name) {
- ObjectBase::Ref new_object(class_manager_->CreateObject(type_name));
- if (new_object.Get() != NULL) {
- RegisterObject(new_object);
- return new_object.Get();
- }
- return NULL;
-}
-
-ObjectBase* Pack::CreateObjectByClass(const ObjectBase::Class* type) {
- ObjectBase::Ref new_object(class_manager_->CreateObjectByClass(type));
- if (new_object.Get() != NULL) {
- RegisterObject(new_object);
- return new_object.Get();
- }
- return NULL;
-}
-
-// Creates a new FileRequest object.
-FileRequest *Pack::CreateFileRequest(const String& type) {
- FileRequest *request = FileRequest::Create(service_locator(),
- this,
- FileRequest::TypeFromString(type));
- if (request) {
- RegisterObject(request);
- }
- return request;
-}
-
-// Creates a new ArchiveRequest object.
-ArchiveRequest *Pack::CreateArchiveRequest() {
- ArchiveRequest *request = ArchiveRequest::Create(service_locator(),
- this);
- if (request) {
- RegisterObject(request);
- }
- return request;
-}
-
-// Creates a Texture object from a file in the current render context format.
-Texture* Pack::CreateTextureFromFile(const String& uri,
- const FilePath& filepath,
- image::ImageFileType file_type,
- bool generate_mipmaps) {
- String filename = FilePathToUTF8(filepath);
-
- DLOG(INFO) << "CreateTextureFromFile(uri='" << uri
- << "', filename='" << filename << "')";
-
- // TODO(gman): Add support for volume texture when we have code to load them.
- BitmapRefArray bitmaps;
- if (!Bitmap::LoadFromFile(service_locator(), filepath, file_type, &bitmaps)) {
- O3D_ERROR(service_locator())
- << "Failed to load bitmap file \"" << uri << "\"";
- return NULL;
- }
-
- return CreateTextureFromBitmaps(bitmaps, uri, generate_mipmaps);
-}
-
-// Creates a Texture object from a file in the current render context format.
-// This version takes a String |filename| argument instead of the preferred
-// FilePath argument. The use of this method should be phased out
-Texture* Pack::CreateTextureFromFile(const String& uri,
- const String& filename,
- image::ImageFileType file_type,
- bool generate_mipmaps) {
- FilePath filepath = UTF8ToFilePath(filename);
- return CreateTextureFromFile(uri,
- filepath,
- file_type,
- generate_mipmaps);
-}
-
-// Creates a Texture object from a bitmap in the current render context format.
-Texture* Pack::CreateTextureFromBitmaps(
- const BitmapRefArray& bitmaps, const String& uri, bool generate_mipmaps) {
- if (bitmaps.empty()) {
- return NULL;
- }
- unsigned width = bitmaps[0]->width();
- unsigned height = bitmaps[0]->height();
-
- BitmapRefArray temp_bitmaps;
- for (BitmapRefArray::size_type ii = 0; ii < bitmaps.size(); ++ii) {
- temp_bitmaps.push_back(bitmaps[ii]);
- Bitmap* bitmap = temp_bitmaps[ii].Get();
- if (bitmap->width() > static_cast<unsigned int>(Texture::kMaxDimension) ||
- bitmap->height() > static_cast<unsigned int>(Texture::kMaxDimension)) {
- O3D_ERROR(service_locator())
- << "Bitmap (uri='" << uri
- << "', size=" << bitmap->width() << "x" << bitmap->height()
- << ", mips=" << bitmap->num_mipmaps()<< ") is larger than the "
- << "maximum texture size which is (" << Texture::kMaxDimension
- << "x" << Texture::kMaxDimension << ")";
- return NULL;
- }
- if (bitmap->width() != width || bitmap->height() != height) {
- O3D_ERROR(service_locator()) << "Bitmaps are not all the same dimensions";
- return NULL;
- }
- if (generate_mipmaps && image::CanMakeMips(bitmap->format())) {
- unsigned total_mips = image::ComputeMipMapCount(
- bitmap->width(), bitmap->height());
- // If we don't already have mips and we could use them then make them.
- if (bitmap->num_mipmaps() == 1 && total_mips > 1) {
- // Create a new Bitmap with mips
- Bitmap::Ref new_bitmap(new Bitmap(service_locator()));
- new_bitmap->Allocate(bitmap->format(),
- bitmap->width(),
- bitmap->height(),
- total_mips,
- bitmap->semantic());
- new_bitmap->SetRect(0, 0, 0, bitmap->width(), bitmap->height(),
- bitmap->GetMipData(0), bitmap->GetMipPitch(0));
- new_bitmap->GenerateMips(0, total_mips - 1);
- temp_bitmaps[ii] = new_bitmap;
- }
- }
- }
-
- // Figure out what kind of texture to make.
- // TODO(gman): Refactor to check semantics to distinguish between CUBE and
- // VOLUME textures.
- Texture::Ref texture;
- if (temp_bitmaps.size() == 1) {
- Bitmap* bitmap = temp_bitmaps[0].Get();
- Texture2D::Ref texture_2d = renderer_->CreateTexture2D(
- bitmap->width(),
- bitmap->height(),
- bitmap->format(),
- bitmap->num_mipmaps(),
- false);
- if (!texture_2d.IsNull()) {
- texture = Texture::Ref(texture_2d.Get());
- texture_2d->SetFromBitmap(*bitmap);
- }
- } else if (temp_bitmaps.size() == 6) {
- Bitmap* bitmap = temp_bitmaps[0].Get();
- TextureCUBE::Ref texture_cube = renderer_->CreateTextureCUBE(
- bitmap->width(),
- bitmap->format(),
- bitmap->num_mipmaps(),
- false);
- if (!texture_cube.IsNull()) {
- texture = Texture::Ref(texture_cube.Get());
- for (unsigned ii = 0; ii < 6; ++ii) {
- texture_cube->SetFromBitmap(static_cast<TextureCUBE::CubeFace>(ii),
- *temp_bitmaps[ii].Get());
- }
- }
- }
-
- if (!texture.IsNull()) {
- // TODO(gman): remove this. Maybe set the name? or make uri an offical
- // Texture param.
- ParamString* param = texture->CreateParam<ParamString>(
- O3D_STRING_CONSTANT("uri"));
- DCHECK(param != NULL);
- param->set_value(uri);
-
- RegisterObject(texture);
- } else {
- O3D_ERROR(service_locator())
- << "Unable to create texture (uri='" << uri
- << "', size=" << width << "x" << height
- << ", mips=" << temp_bitmaps[0]->num_mipmaps() << ")";
- }
-
- return texture.Get();
-}
-
-// Creates a Texture object from RawData and allocates
-// the necessary resources for it.
-Texture* Pack::CreateTextureFromRawData(RawData *raw_data,
- bool generate_mips) {
- if (!renderer_) {
- O3D_ERROR(service_locator()) << "No Render Device Available";
- return NULL;
- }
-
- const String uri = raw_data->uri();
-
- DLOG(INFO) << "CreateTextureFromRawData(uri='" << uri << "')";
-
- BitmapRefArray bitmap_refs;
- if (!Bitmap::LoadFromRawData(raw_data, image::UNKNOWN, &bitmap_refs)) {
- O3D_ERROR(service_locator())
- << "Failed to load bitmap from raw data \"" << uri << "\"";
- return NULL;
- }
-
- return CreateTextureFromBitmaps(bitmap_refs, uri, generate_mips);
-}
-
-// Create a bitmap object.
-Bitmap* Pack::CreateBitmap(int width, int height, Texture::Format format) {
- DCHECK(image::CheckImageDimensions(width, height));
-
- Bitmap::Ref bitmap(new Bitmap(service_locator()));
- if (bitmap.IsNull()) {
- O3D_ERROR(service_locator())
- << "Failed to create bitmap object.";
- return NULL;
- }
- bitmap->Allocate(format, width, height, 1, Bitmap::IMAGE);
- if (!bitmap->image_data()) {
- O3D_ERROR(service_locator())
- << "Failed to allocate memory for bitmap.";
- return NULL;
- }
- RegisterObject(bitmap);
- return bitmap.Get();
-}
-
-// Create a new bitmap object from rawdata.
-std::vector<Bitmap*> Pack::CreateBitmapsFromRawData(RawData* raw_data) {
- BitmapRefArray bitmap_refs;
- if (!Bitmap::LoadFromRawData(raw_data, image::UNKNOWN, &bitmap_refs)) {
- O3D_ERROR(service_locator())
- << "Failed to load bitmap from raw data.";
- }
- std::vector<Bitmap*> bitmaps(bitmap_refs.size(), NULL);
- for (BitmapRefArray::size_type ii = 0; ii < bitmap_refs.size(); ++ii) {
- RegisterObject(bitmap_refs[ii]);
- bitmaps[ii] = bitmap_refs[ii].Get();
- }
- return bitmaps;
-}
-
-// Creates a new RawData from a data URL.
-RawData* Pack::CreateRawDataFromDataURL(const String& data_url) {
- RawData::Ref raw_data = RawData::CreateFromDataURL(service_locator(),
- data_url);
-
- if (!raw_data.IsNull()) {
- RegisterObject(raw_data);
- }
- return raw_data.Get();
-}
-
-// Creates a Texture2D object and allocates the necessary resources for it.
-Texture2D* Pack::CreateTexture2D(int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- if (!renderer_) {
- O3D_ERROR(service_locator()) << "No Render Device Available";
- return NULL;
- }
-
- if (width > Texture::kMaxDimension ||
- height > Texture::kMaxDimension) {
- O3D_ERROR(service_locator())
- << "Maximum texture size is (" << Texture::kMaxDimension << "x"
- << Texture::kMaxDimension << ")";
- return NULL;
- }
-
- if (enable_render_surfaces) {
- if (image::ComputePOTSize(width) != static_cast<unsigned int>(width) ||
- image::ComputePOTSize(height) != static_cast<unsigned int>(height)) {
- O3D_ERROR(service_locator()) <<
- "Textures with RenderSurfaces enabled must have power-of-two "
- "dimensions.";
- return NULL;
- }
- }
-
- Texture2D::Ref texture = renderer_->CreateTexture2D(
- width,
- height,
- format,
- (levels == 0) ? image::ComputeMipMapCount(width, height) : levels,
- enable_render_surfaces);
- if (!texture.IsNull()) {
- RegisterObject(texture);
- }
-
- return texture.Get();
-}
-
-// Creates a TextureCUBE object and allocates the necessary resources for it.
-TextureCUBE* Pack::CreateTextureCUBE(int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- if (!renderer_) {
- O3D_ERROR(service_locator()) << "No Render Device Available";
- return NULL;
- }
-
- if (edge_length > Texture::kMaxDimension) {
- O3D_ERROR(service_locator())
- << "Maximum edge_length is " << Texture::kMaxDimension;
- return NULL;
- }
-
-
- if (enable_render_surfaces) {
- if (image::ComputePOTSize(edge_length) !=
- static_cast<unsigned int>(edge_length)) {
- O3D_ERROR(service_locator()) <<
- "Textures with RenderSurfaces enabled must have power-of-two "
- "dimensions.";
- return NULL;
- }
- }
-
- TextureCUBE::Ref texture = renderer_->CreateTextureCUBE(
- edge_length,
- format,
- (levels == 0) ? image::ComputeMipMapCount(edge_length,
- edge_length) : levels,
- enable_render_surfaces);
- if (!texture.IsNull()) {
- RegisterObject(texture);
- }
-
- return texture.Get();
-}
-
-RenderDepthStencilSurface* Pack::CreateDepthStencilSurface(int width,
- int height) {
- if (!renderer_) {
- O3D_ERROR(service_locator()) << "No Render Device Available";
- return NULL;
- }
-
- if (width > Texture::kMaxDimension ||
- height > Texture::kMaxDimension) {
- O3D_ERROR(service_locator())
- << "Maximum texture size is (" << Texture::kMaxDimension << "x"
- << Texture::kMaxDimension << ")";
- return NULL;
- }
-
- if (image::ComputePOTSize(width) != static_cast<unsigned int>(width) ||
- image::ComputePOTSize(height) != static_cast<unsigned int>(height)) {
- O3D_ERROR(service_locator()) <<
- "Depth-stencil RenderSurfaces must have power-of-two dimensions.";
- return NULL;
- }
-
- RenderDepthStencilSurface::Ref surface =
- renderer_->CreateDepthStencilSurface(width, height);
-
- if (!surface.IsNull()) {
- RegisterObject(surface);
- }
- return surface.Get();
-}
-
-ObjectBase* Pack::GetObjectBaseById(Id id,
- const ObjectBase::Class* class_type) {
- ObjectBase::Ref object(object_manager_->GetObjectBaseById(id, class_type));
- if (!object.IsNull() &&
- owned_objects_.find(object) == owned_objects_.end()) {
- object.Reset();
- }
- return object.Get();
-}
-
-ObjectBaseArray Pack::GetObjects(const String& name,
- const String& class_type_name) const {
- ObjectBaseArray objects;
- ObjectSet::const_iterator end(owned_objects_.end());
- for (ObjectSet::const_iterator iter(owned_objects_.begin());
- iter != end;
- ++iter) {
- ObjectBase* object = iter->Get();
- if (object->IsAClassName(class_type_name)) {
- if (object->IsA(NamedObjectBase::GetApparentClass())) {
- if (name.compare(down_cast<NamedObjectBase*>(object)->name()) == 0) {
- objects.push_back(object);
- }
- }
- }
- }
- return objects;
-}
-
-ObjectBaseArray Pack::GetObjectsByClassName(
- const String& class_type_name) const {
- ObjectBaseArray objects;
- ObjectSet::const_iterator end(owned_objects_.end());
- for (ObjectSet::const_iterator iter(owned_objects_.begin());
- iter != end;
- ++iter) {
- if (iter->Get()->IsAClassName(class_type_name)) {
- objects.push_back(iter->Get());
- }
- }
- return objects;
-}
-
-void Pack::RegisterObject(ObjectBase *object) {
- ObjectBase::Ref temp(object);
- DLOG_ASSERT(owned_objects_.find(temp) == owned_objects_.end())
- << "attempt to register duplicate object in pack.";
- owned_objects_.insert(temp);
-}
-
-bool Pack::UnregisterObject(ObjectBase *object) {
- ObjectSet::iterator find(owned_objects_.find(ObjectBase::Ref(object)));
- if (find == owned_objects_.end())
- return false;
-
- owned_objects_.erase(find);
- return true;
-}
-} // namespace o3d
diff --git a/o3d/core/cross/pack.h b/o3d/core/cross/pack.h
deleted file mode 100644
index 3a9f0ed..0000000
--- a/o3d/core/cross/pack.h
+++ /dev/null
@@ -1,459 +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.
- */
-
-
-// File containing the declaration for the Pack object used to explicitly
-// control O3D object lifetimes..
-
-#ifndef O3D_CORE_CROSS_PACK_H_
-#define O3D_CORE_CROSS_PACK_H_
-
-#include <vector>
-#include <set>
-
-#include "core/cross/named_object.h"
-#include "core/cross/smart_ptr.h"
-#include "core/cross/transform.h"
-#include "core/cross/types.h"
-#include "core/cross/image_utils.h"
-#include "core/cross/bitmap.h"
-
-class FilePath;
-
-namespace o3d {
-
-class Bitmap;
-class ArchiveRequest;
-class RawData;
-class Texture;
-class Texture2D;
-class TextureCUBE;
-class FileRequest;
-class DrawContext;
-class IClassManager;
-class ObjectManager;
-class RenderDepthStencilSurface;
-
-// Type definitions ------------------------
-
-// Array of object id's
-typedef std::vector<Id> IdArray;
-// Array of Bitmaps.
-typedef std::vector<Bitmap*> BitmapArray;
-
-// A Pack object functions as a container for O3D objects. All objects
-// inheriting from ObjectBase must be constructed and assigned a pack. The Pack
-// is used to control the lifetime scope of a collection of objects in bulk. The
-// Pack object achieves this by simply storing a set of references to its
-// contained objects, which ensures that the ref-counts for those objects never
-// reach zero while the pack is alive.
-//
-// The standard usage model is the following:
-// Pack::Ref pack(client->CreatePack());
-// Transform* transform(pack.Get()->Create<Transform>();
-// ==> Construct multiple nodes and the transform graph.
-// pack.Get()->Destroy();
-// ==> All nodes not referenced by the SceneGraph, or other nodes in live
-// packs are destroyed.
-class Pack : public NamedObject {
- friend class ObjectManager;
- friend class ParamObject;
- friend class SmartPointer<Pack>;
-
- // Forward declaration of private helper class used in std::set typedef below.
- class IdObjectComparator;
- public:
- typedef SmartPointer<Pack> Ref;
-
- // Set of references to named objects.
- typedef std::set<ObjectBase::Ref, IdObjectComparator> ObjectSet;
-
- // Removes all internal references to the Pack from the client.
- // The pack, and all objects contained in it are permitted to be destroyed
- // after the packs destruction. Nodes will only be destoryed after all
- // references to them have been removed.
- // Returns:
- // True if the pack was successfully deleted.
- bool Destroy();
-
- // Removes an object from the pack. The lifetime of the object is no longer
- // bound to the lifetime of the pack. Any object created from a pack.CreateXXX
- // function can be removed.
- // Parameters:
- // object: Pointer to object to remove.
- // Returns:
- // true if the object was successfully removed. false if the object is not
- // part of this pack.
- bool RemoveObject(ObjectBase* object);
-
- // Creates an Object based on the type_name. This function is for Javascript.
- // Paramaters:
- // type_name: type name of object type you want created.
- // Returns:
- // pointer to new object if successful.
- ObjectBase* CreateObject(const String& type_name);
-
- // Creates an Object based on the type.
- // Parameters:
- // type: ObjectBase::Class* of the type you want created.
- // Returns:
- // pointer to new object if successful.
- ObjectBase* CreateObjectByClass(const ObjectBase::Class* type);
-
- // Creates a Object based on the type. This is a type safe version of
- // CreateObjectByClass for C++.
- // Returns:
- // pointer to new object if successful.
- template<typename T>
- T* Create() {
- return down_cast<T*>(CreateObjectByClass(T::GetApparentClass()));
- }
-
- // Creates an Object based on the type_name. This function is for Javascript.
- // Paramaters:
- // type_name: type name of object type you want created.
- // Returns:
- // pointer to new object if successful.
- ObjectBase* CreateUnnamedObject(const String& type_name);
-
- // Creates an Object based on the type.
- // Parameters:
- // type: ObjectBase::Class* of the type you want created.
- // Returns:
- // pointer to new object if successful.
- ObjectBase* CreateUnnamedObjectByClass(const ObjectBase::Class* type);
-
- // Creates a Object based on the type. This is a type safe version of
- // CreateObjectByClass for C++.
- // Returns:
- // pointer to new object if successful.
- template<typename T>
- T* CreateUnnamed() {
- return down_cast<T*>(CreateUnnamedObjectByClass(T::GetApparentClass()));
- }
-
- // Transform methods ----
-
- // Returns the root transform of the pack. Typically used on import to
- // specify entry into the loaded contents.
- // Returns:
- // A pointer to the transform assigned as the root. May be NULL if no root
- // transform has been assigned.
- Transform* root() const;
-
- // Assigns the root-transform for the pack. If a root-transform has previously
- // been assigned, it is overwritten with the new value.
- // Parameters:
- // root: Pointer to transform to assign as the root transform.
- void set_root(Transform* root);
-
- // Creates a new FileRequest object. The object is owned by the Client.
- // Parameters:
- // type: what type of file load will occur after download
- // Returns:
- // A pointer to the newly created FileRequest, or NULL if creation failed.
- FileRequest* CreateFileRequest(const String& type);
-
- // Creates a new ArchiveRequest object. The object is owned by the Client.
- // Returns:
- // A pointer to the newly created ArchiveRequest, or NULL if creation failed.
- ArchiveRequest* CreateArchiveRequest();
-
- // Creates a new Texture object from a local file. If the file doesn't exist,
- // or won't load, NULL is returned. The file formats supported are JPEG, PNG,
- // TGA and DDS. If the file contains a cube map, it will be created as an
- // instance of TextureCUBE, otherwise it will be a Texture2D.
- // This function is for internal use only.
- // Parameters:
- // uri: URI that file was requested from. This is purely for user information
- // and is not used for loading.
- // filepath: The local path to the texture file to load
- // file_type: The file type of the image. If UNKNOWN, it wil be detected
- // from the extension, or by trying all the possible loaders.
- // generate_mipmaps: Whether to generate mip-maps or not.
- // Returns:
- // A pointer to the texture or NULL if it did not load
- Texture* CreateTextureFromFile(const String& uri,
- const FilePath& filepath,
- image::ImageFileType file_type,
- bool generate_mipmaps);
-
- // This version takes a String |filename| argument instead of the preferred
- // FilePath argument. The use of this method should be phased out.
- Texture* CreateTextureFromFile(const String& uri,
- const String& filename,
- image::ImageFileType file_type,
- bool generate_mipmaps);
-
- // Creates a new Texture object given a "raw-data" object which must contain
- // binary data in a known image file format (such as JPG or PNG)
- Texture* CreateTextureFromRawData(RawData* raw_data,
- bool generate_mips);
-
- // Creates a new Bitmap object of the specified size and format and
- // reserves the necessary resources for it.
- // Paramters:
- // width: The width of the bitmap in pixel.
- // height: The height of the bitmap in pixel.
- // format: The format of the bitmap.
- // Returns:
- // A pointer to the bitmap obejct.
- Bitmap* CreateBitmap(int width, int height, Texture::Format format);
-
- // Creates a new Bitmaps from RawData.
- // Parameters:
- // raw_data: contains the bitmap data in one of the know formats.
- // Returns:
- // bitmaps: A vector of pointers to bitmaps. If empty there was an error.
- std::vector<Bitmap*> CreateBitmapsFromRawData(RawData* raw_data);
-
- // Creates a new RawData from a String containing a data URL.
- // Parameters:
- // data_url: Contains the data URL that is to be decoded.
- // Returns:
- // A pointer to the RawData that contains the data URL's data.
- RawData* CreateRawDataFromDataURL(const String& data_url);
-
- // Creates a new Texture2D object of the specified size and format and
- // reserves the necessary resources for it.
- // Parameters:
- // width: The width of the texture area in texels
- // height: The height of the texture area in texels
- // format: The memory format of each texel
- // levels: The number of mipmap levels. Use zero to create the compelete
- // mipmap chain.
- // enable_render_surfaces: If true, the texture object will expose
- // RenderSurface objects through
- // GetRenderSurface(...).
- // Returns:
- // A pointer to the Texture2D object.
- // Note: If enable_render_surfaces is true, then the dimensions of the
- // must be a power of two.
- Texture2D* CreateTexture2D(int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
-
- // Creates a new TextureCUBE object of the specified size and format and
- // reserves the necessary resources for it.
- // Parameters:
- // edge_length: The edge of the texture area in texels
- // format: The memory format of each texel
- // levels: The number of mipmap levels. Use zero to create the compelete
- // mipmap chain.
- // enable_render_surfaces: If true, the texture object will expose
- // RenderSurface objects through
- // GetRenderSurface(...).
- // Returns:
- // A pointer to the TextureCUBE object.
- // Note: If enable_render_surfaces is true, then the dimensions of the
- // must be a power of two.
- TextureCUBE* CreateTextureCUBE(int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
- // Creates a new RenderDepthStencilSurface object of D24_S8 format, suitable
- // for use as a depth-stencil render target.
- // Parameters:
- // width: The width of the surface area in pixels
- // height: The height of the surface area in pixels
- // Returns:
- // A pointer to the RenderSurface object.
- // Note: The dimensions of the RenderDepthStencilSurface must be a power of
- // two.
- RenderDepthStencilSurface* CreateDepthStencilSurface(int width,
- int height);
-
- // Searches in the Pack for a base object by its id. If the dynamic type
- // of the object matches the requested type, then a pointer to the instance
- // is returned.
- // Parameters:
- // id: The id of the ObjectBase to search for.
- // class_type: The class instance specifier used to filter the return value.
- // Returns:
- // A pointer to the ObjectBase instance if found and of the matching
- // dynamic type or NULL otherwise.
- ObjectBase* GetObjectBaseById(Id Id, const ObjectBase::Class* class_type);
-
- // Searches in the Pack for a base object by its id. Does not check type.
- // This is for Javascript.
- // Parameters:
- // id: The id of the ObjectBase to search for.
- // Returns:
- // A pointer to the ObjectBase instance if found NULL otherwise.
- ObjectBase* GetObjectById(Id Id);
-
- // Searches in the Pack for a base object by its id. If the dynamic type
- // of the object matches the requested type, then a pointer to the instance
- // is returned.
- // Parameters:
- // id: The id of the ObjectBase to search for.
- // class_type: The class instance specifier used to filter the return value.
- // Returns:
- // A pointer to the ObjectBase instance if found and of the matching
- // dynamic type or NULL otherwise.
- template<typename T>
- T* GetById(Id id) {
- return down_cast<T*>(GetObjectBaseById(id, T::GetApparentClass()));
- }
-
- // Search the pack for all objects of a certain class
- // Returns:
- // Array of Pointers to the requested class.
- template<typename T>
- std::vector<T*> GetByClass() const {
- std::vector<T*> objects;
- ObjectSet::const_iterator end(owned_objects_.end());
- for (ObjectSet::const_iterator iter(owned_objects_.begin());
- iter != end;
- ++iter) {
- if (iter->Get()->IsA(T::GetApparentClass())) {
- objects.push_back(down_cast<T*>(iter->Get()));
- }
- }
- return objects;
- }
-
- // Get an object by name typesafe. This function is for C++
- // Example:
- // Buffer* buffer = pack->Get<Buffer>("name");
- // Parameters:
- // name: name of object to search for.
- // Returns:
- // std::vector of pointers to type of the objects that matched by name.
- template<typename T>
- std::vector<T*> Get(const String& name) const {
- std::vector<T*> objects;
- if (ObjectBase::ClassIsA(T::GetApparentClass(),
- NamedObject::GetApparentClass())) {
- ObjectSet::const_iterator end(owned_objects_.end());
- for (ObjectSet::const_iterator iter(owned_objects_.begin());
- iter != end;
- ++iter) {
- if (iter->Get()->IsA(T::GetApparentClass())) {
- if (down_cast<NamedObject*>(
- iter->Get())->name().compare(name) == 0) {
- objects.push_back(down_cast<T*>(iter->Get()));
- }
- }
- }
- }
- return objects;
- }
-
- // Search the pack for all objects of a certain class with a certain name.
- //
- // This function is for Javascript. Parameters:
- // name: The name to search for.
- // class_type_name: the Class of the object. It is okay to pass base types
- // for example Node::GetApparentClass()->name will return
- // both Transforms and Shapes.
- // Returns:
- // Array of Object Pointers.
- ObjectBaseArray GetObjects(const String& name,
- const String& class_type_name) const;
-
- // Search the pack for all objects of a certain class.
- // This function is for Javascript.
- // Parameters:
- // class_type_name: the Class of the object. It is okay to pass base types
- // for example Node::GetApparentClass()->name will return
- // both Transforms and Shapes.
- // Returns:
- // Array of Object Pointers.
- ObjectBaseArray GetObjectsByClassName(const String& class_type_name) const;
-
- // Register the given object with the Pack. The pack will add a reference
- // to the object, guaranteeing its existence as long as the pack has not
- // been destroyed. This is public so that it can be called by static
- // factory methods.
- // Parameters:
- // object: Pointer to a ObjectBase to register within the pack
- void RegisterObject(ObjectBase *object);
-
- private:
- // Texture objects function as factories for RenderSurface objects.
- // Constructed RenderSurfaces are registered with the pack associated with
- // the texture, so Texture is befriended to Pack for access to the
- // RegisterObject routine below.
- friend class Texture;
-
- explicit Pack(ServiceLocator* service_locator);
-
- virtual ~Pack();
-
- // Unregister a registered object from the pack. If this is the last reference
- // to the object it will be destroyed.
- // Parameters:
- // object: Pointer to ObjectBase to unregister.
- // Returns:
- // false if the object was not in the pack.
- bool UnregisterObject(ObjectBase *object);
-
- // Helper class used as less-than comparator for ordered container classes.
- class IdObjectComparator {
- public:
- // Performs a less than operation on the contents of the left and right
- // smart pointers.
- bool operator()(const ObjectBase::Ref& lhs, const ObjectBase::Ref& rhs)
- const {
- return lhs->id() < rhs->id();
- }
- };
-
- IClassManager* class_manager_;
- ObjectManager* object_manager_;
- Renderer* renderer_;
-
- // helper function
- Texture* CreateTextureFromBitmaps(
- const BitmapRefArray& bitmaps, const String& uri, bool generate_mips);
-
- // The set of objects owned by the pack. This container contains all of the
- // references that force the lifespan of the contained objects to match
- // or exceed that of the pack.
- ObjectSet owned_objects_;
-
- Transform::Ref root_;
-
- O3D_DECL_CLASS(Pack, NamedObject);
- DISALLOW_COPY_AND_ASSIGN(Pack);
-};
-
-// Array container for Pack pointers.
-typedef std::vector<Pack*> PackArray;
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_PACK_H_
diff --git a/o3d/core/cross/pack_test.cc b/o3d/core/cross/pack_test.cc
deleted file mode 100644
index 0b637ec..0000000
--- a/o3d/core/cross/pack_test.cc
+++ /dev/null
@@ -1,181 +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 functionality in pack.cc/.h.
-
-#include "core/cross/pack.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/error_status.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/transform.h"
-#include "tests/common/win/testing_common.h"
-
-namespace o3d {
-
-class PackTest : public testing::Test {
- public:
-
- PackTest()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator) {
- }
-
- ObjectManager* object_manager() { return object_manager_.Get(); }
-
- // Checks if an error has occured on the client then clears the error.
- bool CheckErrorExists() {
- bool have_error = !error_status_.GetLastError().empty();
- error_status_.ClearLastError();
- return have_error;
- }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
-};
-
-// Test basic Pack creation and destruction.
-TEST_F(PackTest, Basic) {
- Pack* pack = object_manager()->CreatePack();
- pack->set_name("PackTest Basic");
- ASSERT_FALSE(pack == NULL);
-
- EXPECT_EQ(pack->name(), "PackTest Basic");
- EXPECT_TRUE(pack->Destroy());
-}
-
-// Test Pack object look-up by name and Id.
-TEST_F(PackTest, ClientLookUp) {
- Pack* pack = object_manager()->CreatePack();
- pack->set_name("PackTest Basic");
- EXPECT_TRUE(object_manager()->GetById<Pack>(pack->id()) == pack);
- EXPECT_TRUE(pack->Destroy());
-}
-
-// Validate the lifetime behaviour for obects in a single pack.
-TEST_F(PackTest, BasicLifetimeScope) {
- Pack* pack = object_manager()->CreatePack();
- Transform* transform1 = pack->Create<Transform>();
- Transform* transform2 = pack->Create<Transform>();
- Id id1 = transform1->id();
- Id id2 = transform2->id();
-
- // Remove all references to the pack.
- ASSERT_TRUE(pack->Destroy());
-
- // Upon removal of all references, the transforms should be destroyed.
- EXPECT_TRUE(object_manager()->GetById<Transform>(id1) == NULL);
- EXPECT_TRUE(object_manager()->GetById<Transform>(id2) == NULL);
-}
-
-// Validate the Pack object look-up routines.
-TEST_F(PackTest, PackLookup) {
- Pack* pack1 = object_manager()->CreatePack();
- Pack* pack2 = object_manager()->CreatePack();
- Transform* transform1 = pack1->Create<Transform>();
- transform1->set_name("Transform1");
- Transform* transform2 = pack2->Create<Transform>();
- transform2->set_name("Transform2");
-
- EXPECT_TRUE(pack1->Get<Transform>("Transform1")[0] == transform1);
- EXPECT_TRUE(pack2->Get<Transform>("Transform2")[0] == transform2);
-
- // Validate that Pack look-ups are confined to the contents of the Pack.
- EXPECT_TRUE(pack1->Get<Transform>("Transform2").empty());
- EXPECT_TRUE(pack2->Get<Transform>("Transform1").empty());
-
- EXPECT_TRUE(pack1->GetById<Transform>(transform1->id()) == transform1);
- EXPECT_TRUE(pack2->GetById<Transform>(transform2->id()) == transform2);
-
- EXPECT_TRUE(pack1->GetById<Transform>(transform2->id()) == NULL);
- EXPECT_TRUE(pack2->GetById<Transform>(transform1->id()) == NULL);
-
- EXPECT_TRUE(pack1->Destroy());
- EXPECT_TRUE(pack2->Destroy());
-}
-
-// Validate the semantics of removal of objects from a Pack.
-TEST_F(PackTest, RemoveObject) {
- Pack* pack = object_manager()->CreatePack();
- ASSERT_TRUE(pack != NULL);
- Transform* transform = pack->Create<Transform>();
- ASSERT_TRUE(transform != NULL);
- transform->set_name("Transform");
- Transform* transform2 = pack->Create<Transform>();
- ASSERT_TRUE(transform2 != NULL);
-
- const String transform_name(transform->name());
- const Id id(transform->id());
-
- pack->RemoveObject(transform);
-
- // The removed transform should not be accessible through the pack.
- EXPECT_TRUE(pack->GetById<Transform>(id) == NULL);
- EXPECT_TRUE(pack->Get<Transform>(transform_name).empty());
-
- // Existing transforms should remain untouched.
- EXPECT_TRUE(pack->GetById<Transform>(
- transform2->id()) == transform2);
- EXPECT_TRUE(pack->Get<Transform>(
- transform2->name())[0] == transform2);
-
- Pack* pack2 = object_manager()->CreatePack();
- ASSERT_TRUE(pack2 != NULL);
- Transform* transform3 = pack2->Create<Transform>();
- ASSERT_TRUE(transform3 != NULL);
-
- // Check that trying to remove something not in the pack returns false but
- // does NOT generate an error.
- EXPECT_FALSE(pack->RemoveObject(transform3));
- EXPECT_FALSE(CheckErrorExists());
-
- EXPECT_TRUE(pack2->Destroy());
- EXPECT_TRUE(pack->Destroy());
-}
-
-TEST_F(PackTest, CreateRawDataFromDataURL) {
- Pack* pack = object_manager()->CreatePack();
- RawData* raw_data = pack->CreateRawDataFromDataURL("data:;base64,YWJj");
-
- EXPECT_FALSE(raw_data == NULL);
- EXPECT_FALSE(CheckErrorExists());
-}
-
-TEST_F(PackTest, CreateRawDataFromDataURLFail) {
- Pack* pack = object_manager()->CreatePack();
- RawData* raw_data = pack->CreateRawDataFromDataURL("data:;base64,Y");
-
- EXPECT_TRUE(raw_data == NULL);
- EXPECT_TRUE(CheckErrorExists());
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/param.cc b/o3d/core/cross/param.cc
deleted file mode 100644
index 4150e60..0000000
--- a/o3d/core/cross/param.cc
+++ /dev/null
@@ -1,380 +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 the Param class and the ones derived from
-// it for each type of data (ParamFloat, ParamFloat2, ParamFloat3,
-// ParamMatrix, ParamBoolean, ParamString, ParamInteger, ParamTexture).
-
-#include "core/cross/param.h"
-#include "core/cross/param_object.h"
-#include "core/cross/error.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Param, NamedObjectBase);
-O3D_DEFN_CLASS(RefParamBase, Param);
-O3D_DEFN_CLASS(ParamFloat, Param);
-O3D_DEFN_CLASS(ParamFloat2, Param);
-O3D_DEFN_CLASS(ParamFloat3, Param);
-O3D_DEFN_CLASS(ParamFloat4, Param);
-O3D_DEFN_CLASS(ParamInteger, Param);
-O3D_DEFN_CLASS(ParamBoolean, Param);
-O3D_DEFN_CLASS(ParamString, Param);
-O3D_DEFN_CLASS(ParamMatrix4, Param);
-
-// Base constructor that sets the Param type, resets input connection
-// and handle.
-Param::Param(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : NamedObjectBase(service_locator),
- evaluation_counter_(service_locator->GetService<EvaluationCounter>()),
- input_connection_(NULL),
- not_cachable_count_(0),
- dynamic_(dynamic),
- read_only_(read_only),
- handle_(NULL),
- owner_(NULL),
- last_evaluation_count_(evaluation_counter_->evaluation_count() - 1),
- update_input_(true) {
-}
-
-Param::~Param() {
- // There can't be any output connections since they'd have a reference to us.
- DCHECK(output_connections_.empty());
- UnbindInput();
- DCHECK(input_connection_ == NULL);
-}
-
-const String& Param::name() const {
- return name_;
-}
-
-void Param::SetName(const String& name) {
- DCHECK(!name.empty());
- DCHECK(name_.empty());
- name_ = name;
-}
-
-// Updates the contents of data_ by recursively traversing the input connections
-// and evaluating them.
-void Param::ComputeValue() {
- if (input_connection_) {
- if (update_input_) {
- input_connection_->UpdateValue();
- }
- CopyDataFromParam(input_connection_);
- }
-}
-
-void Param::MarkAsReadOnly() {
- DCHECK(input_connection_ == NULL);
- read_only_ = true;
-}
-
-// Adds an output connection to the Param by just inserting
-// it in the array.
-void Param::AddOutputConnection(Param* param) {
- output_connections_.push_back(param);
-}
-
-bool Param::UnbindOutput(Param* param) {
- ParamVector::iterator pos = std::find(output_connections_.begin(),
- output_connections_.end(),
- param);
- if (pos != output_connections_.end()) {
- output_connections_.erase(pos);
- param->ResetInputConnection();
- return true;
- }
- return false;
-}
-
-void Param::ResetInputConnection() {
- // Keep a temporary reference to the input_connection
- // so it does not get deleted when we input_connection_.Reset()
- // before we get a chance to call
- // DecrementNotCachableCountOnParamChainForInput.
- Param::Ref temp(input_connection_);
- input_connection_.Reset();
- // This is called after input_connection_.Reset() for symmetry
- // with the way DecrementNotCachableCountOnParamChainForInput
- // is called.
- DecrementNotCachableCountOnParamChainForInput(temp);
- OnAfterUnbindInput(temp.Get());
-}
-
-void Param::set_owner(ParamObject* owner) {
- DCHECK((owner_ == NULL && owner != NULL) ||
- (owner_ != NULL && owner == NULL));
- owner_ = owner;
-}
-
-namespace {
-
-// Check if a param is in the given param array
-// Parameters:
-// param: param to search for.
-// params: ParamVector to search.
-// Returns:
-// true if param is in params.
-bool ParamInParams(Param* param, const ParamVector* params) {
- return std::find(params->begin(), params->end(), param) != params->end();
-}
-
-} // anonymous namespace
-
-void Param::AddInputsRecursive(const Param* original,
- ParamVector* params) const {
- if (owner_) {
- ParamVector owner_params;
- owner_->GetInputsForParam(this, &owner_params);
- for (unsigned ii = 0; ii < owner_params.size(); ++ii) {
- Param* param = owner_params[ii];
- if (param != original && !ParamInParams(param, params)) {
- params->push_back(param);
- param->AddInputsRecursive(original, params);
- }
- }
- }
- if (input_connection_ &&
- input_connection_ != original &&
- !ParamInParams(input_connection_, params)) {
- params->push_back(input_connection_);
- input_connection_->AddInputsRecursive(original, params);
- }
-}
-
-void Param::AddOutputsRecursive(const Param* original,
- ParamVector* params) const {
- if (owner_) {
- ParamVector owner_params;
- owner_->GetOutputsForParam(this, &owner_params);
- for (unsigned ii = 0; ii < owner_params.size(); ++ii) {
- Param* param = owner_params[ii];
- if (param != original && !ParamInParams(param, params)) {
- params->push_back(param);
- param->AddOutputsRecursive(original, params);
- }
- }
- }
- for (unsigned ii = 0; ii < output_connections_.size(); ++ii) {
- Param* param = output_connections_[ii];
- if (param != original && !ParamInParams(param, params)) {
- params->push_back(param);
- param->AddOutputsRecursive(original, params);
- }
- }
-}
-
-void Param::GetInputs(ParamVector* params) const {
- DCHECK(params);
- params->clear();
- AddInputsRecursive(this, params);
-}
-
-void Param::GetOutputs(ParamVector* params) const {
- DCHECK(params);
- params->clear();
- AddOutputsRecursive(this, params);
-}
-
-void Param::InvalidateAllOutputs() const {
- ParamVector params;
- GetOutputs(&params);
- for (unsigned ii = 0; ii < params.size(); ++ii) {
- params[ii]->Invalidate();
- }
-}
-
-void Param::InvalidateAllInputs() {
- ParamVector params;
- GetInputs(&params);
- for (unsigned ii = 0; ii < params.size(); ++ii) {
- params[ii]->Invalidate();
- }
- Invalidate();
-}
-
-void Param::InvalidateAllParameters() {
- evaluation_counter_->InvalidateAllParameters();
-}
-
-void Param::SetNotCachable() {
- DCHECK(not_cachable_count_ == 0);
- not_cachable_count_ = 1;
-}
-
-void Param::IncrementNotCachableCountOnParamChainForInput(Param* input) {
- if (input && !input->cachable()) {
- ++not_cachable_count_;
- ParamVector params;
- GetOutputs(&params);
- for (ParamVector::size_type ii = 0; ii < params.size(); ++ii) {
- ++params[ii]->not_cachable_count_;
- }
- }
-}
-
-void Param::DecrementNotCachableCountOnParamChainForInput(Param* input) {
- if (input && !input->cachable()) {
- --not_cachable_count_;
- ParamVector params;
- GetOutputs(&params);
- for (ParamVector::size_type ii = 0; ii < params.size(); ++ii) {
- --params[ii]->not_cachable_count_;
- }
- }
-}
-
-// Connects two Params using a direct connection or unbinds the input if NULL
-// is specified as the source Param.
-bool Param::Bind(Param *source_param) {
- if (!source_param) {
- UnbindInput();
- return true;
- }
-
- // When we clear a previous input connection our ref count could go to zero if
- // we don't hold this reference.
- Param::Ref temp(this);
-
- if (read_only_) {
- O3D_ERROR(service_locator()) << "attempt to bind source param '"
- << source_param->name()
- << "' to read only param '" << name() << "'";
- return false;
- }
-
- // Check to make sure the two Params are of the same type
- if (!source_param->IsA(GetClass())) {
- O3D_ERROR(service_locator())
- << "attempt to bind incompatible source param '"
- << source_param->name() << "' of type '"
- << source_param->GetClassName()
- << "' to read only param '" << name()
- << "' of type '" << GetClassName() << "'";
- return false;
- }
-
- // Check if we are connecting the same thing. It's either this or holding
- // a temp reference to the source becuase when we clear input_connection_
- // the ref count of source_param could go to zero and get freed.
- if (source_param == input_connection_) {
- return true;
- }
-
- // if we already had an input connection, disconnect it.
- if (input_connection_) {
- // UnbindOutput will clear input_connection_.
- bool result = input_connection_->UnbindOutput(this);
- DCHECK(result);
- }
-
- DCHECK(input_connection_ == NULL);
-
- // If our input is not cachable we need to increment the not_cachable_count
- // for ourselves and all the outputs further down the chain.
- IncrementNotCachableCountOnParamChainForInput(source_param);
-
- // Everything checks out, bind these params.
- input_connection_ = Param::Ref(source_param);
- source_param->AddOutputConnection(this);
- evaluation_counter_->InvalidateAllParameters();
- OnAfterBindInput();
- return true;
-}
-
-// Breaks any input connection.
-void Param::UnbindInput() {
- Param *source_param = input_connection();
- if (source_param != NULL) {
- bool success = source_param->UnbindOutput(this);
- DLOG_ASSERT(success);
- DCHECK(input_connection_ == NULL);
- }
-}
-
-// Breaks all output connections on the given param.
-void Param::UnbindOutputs() {
- // We need to keep a ref to ourselves because as inputs get cleared
- // they could release the last reference to us.
- Param::Ref temp(this);
-
- const ParamVector& params(output_connections());
-
- while (!params.empty()) {
- Param* param = params.front();
- param->UnbindInput();
- }
-}
-
-void Param::ReportReadOnlyError() {
- O3D_ERROR(service_locator()) << "attempt to set read only param '"
- << name() << "'";
-}
-
-void Param::ReportDynamicSetError() {
- O3D_ERROR(service_locator()) << "attempt to set dynamic param '"
- << name() << "'";
-}
-
-ObjectBase::Ref ParamFloat::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamFloat(service_locator, false, false));
-}
-
-ObjectBase::Ref ParamFloat2::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamFloat2(service_locator, false, false));
-}
-
-ObjectBase::Ref ParamFloat3::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamFloat3(service_locator, false, false));
-}
-
-ObjectBase::Ref ParamFloat4::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamFloat4(service_locator, false, false));
-}
-
-ObjectBase::Ref ParamInteger::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamInteger(service_locator, false, false));
-}
-
-ObjectBase::Ref ParamBoolean::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamBoolean(service_locator, false, false));
-}
-
-ObjectBase::Ref ParamString::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamString(service_locator, false, false));
-}
-
-ObjectBase::Ref ParamMatrix4::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamMatrix4(service_locator, false, false));
-}
-} // namespace o3d
diff --git a/o3d/core/cross/param.h b/o3d/core/cross/param.h
deleted file mode 100644
index ee0a0ec..0000000
--- a/o3d/core/cross/param.h
+++ /dev/null
@@ -1,706 +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.
- */
-
-
-// Contains declarations for Param and TypedParam classes.
-
-#ifndef O3D_CORE_CROSS_PARAM_H_
-#define O3D_CORE_CROSS_PARAM_H_
-
-#include <vector>
-#include "base/scoped_ptr.h"
-#include "core/cross/named_object.h"
-#include "core/cross/types.h"
-#include "core/cross/weak_ptr.h"
-#include "core/cross/service_locator.h"
-#include "core/cross/evaluation_counter.h"
-
-namespace o3d {
-
-class Param;
-class ParamObject;
-class ServiceLocator;
-
-#define PARAM_VALUE_CONST
-
-// Type used to store and return an array of Param pointers.
-typedef std::vector<Param*> ParamVector;
-
-// Iterators for ParamVector.
-typedef ParamVector::const_iterator ParamVectorConstIterator;
-typedef ParamVector::iterator ParamVectorIterator;
-
-// Param elements store user defined name/value pairs on nodes
-// and other O3D objects. Each element has a name, a type and a value
-// that can be set and queried. One of their uses is to hold
-// "uniform constants" used to parameterize shaders. Param elements
-// can be connected in a source/destination fashion such that the target Param
-// gets its value from the source param.
-class Param : public NamedObjectBase {
- friend class IClassManager;
- public:
- typedef SmartPointer<Param> Ref;
-
- virtual ~Param();
-
- // Copies data from another Param.
- virtual void CopyDataFromParam(Param* source_param) = 0;
-
- // Gets the name of the Param.
- virtual const String& name() const;
-
- // Gets the parameter handle (opaque).
- const void* handle() const {
- return handle_;
- }
-
- // Sets the parameter handle (opaque).
- void set_handle(const void* handle) {
- handle_ = handle;
- }
-
- // Gets whether or not this param is read only
- inline bool read_only() const {
- return read_only_;
- }
-
- // Gets whether or not this param is dyamically updated (not by bind but by
- // the Param itself. The SAS params are dynamic for example.)
- inline bool dynamic() const {
- return dynamic_;
- }
-
- // The only point of this is to allow the user to make cycles in param chains
- // predictable. If param_A gets its value from param_B and param_B gets its
- // value from param_A the last_evaluation_count_ will prevent an infinite
- // cycle BUT there is no way to specify who gets evaluated first.
- // If you go param_A->value(), param_B will evaluate then copy to param_A.
- // If you go param_B->value(), param_A will evaluate then copy to param_B.
- // If you set param_B->set_update_input(false), then:
- // If you go param_A->value(), param_B will evaluate then copy to param_A.
- // If you go param_B->value(), param_B just copy param_A. param_A will NOT
- // evaluate when param_B asks for its value.
- bool update_input() const {
- return update_input_;
- }
-
- void set_update_input(bool value) {
- update_input_ = value;
- }
-
- inline bool cachable() const {
- return not_cachable_count_ == 0;
- }
-
- // Returns an input Param connection to this element or NULL if there is none.
- Param* input_connection() const {
- return input_connection_;
- }
-
- // Returns a reference to the internal array of output references.
- const ParamVector& output_connections() {
- return output_connections_;
- }
-
- // Gets ALL the params that affect this Param.
- // Parameters:
- // params: ParamVector to fill out with array of inputs. The array will
- // be cleared.
- void GetInputs(ParamVector* params) const;
-
- // Returns ALL the params this Param affects.
- // Parameters:
- // params: ParamVector to fill out with array of outputs. The array will
- // be cleared.
- void GetOutputs(ParamVector* params) const;
-
- // Directly binds two Param elements such that the this parameter gets its
- // value from the source parameter. The source parameters
- // must be a compatible type to this param or NULL to unbind. Note: The
- // routine will fail if the bind would introduce a cycle in the Param graph.
- // Parameters:
- // source_param: The parameter that the value originates from or NULL
- // Returns:
- // True if the bind succeeds
- bool Bind(Param *source_param);
-
- // Breaks any input connection coming into this Param
- void UnbindInput();
-
- // Breaks a specific param-bind output connection on this param.
- // Parameters:
- // destination_param: param to unbind.
- // Returns:
- // True if the param was a destination param and was unbound.
- bool UnbindOutput(Param* destination_param);
-
- // Breaks all param-bind output connections on this param.
- void UnbindOutputs();
-
- // If input is not cachable will increment the not cachable count for this
- // param and its outputs.
- //
- // Note: This function must be called by classes derived from ParamObject when
- // implicit connections between parameters are changed such that a new
- // relationship is established. For example when one Transform is parented to
- // another there is an implicit relationship between parent.worldMatrix and
- // child.worldMatrix.
- //
- // Parameters:
- // input: Param that is about to be made an input to this param.
- void IncrementNotCachableCountOnParamChainForInput(Param* input);
-
- // If input is not cachable will decrement the not cachable count for this
- // param and its outputs.
- //
- // Note: This function must be called by classes derived from ParamObject when
- // implicit connections between parameters are changed such that an old
- // relationship is broken. For example when one Transform is un-parented from
- // another there is an implicit relationship between parent.worldMatrix and
- // child.worldMatrix that is being broken.
- //
- // Parameters:
- // input: Param that was an input to this param but is no longer.
- void DecrementNotCachableCountOnParamChainForInput(Param* input);
-
- // Safely gets a TypedParam from a param.
- // Paramaters:
- // param: Pointer to base param you want down_cast to your TypedParam.
- // Returns:
- // Pointer to TypedParam if success, NULL if failure.
- template <typename T>
- T* GetParam() {
- return ObjectBase::rtti_dynamic_cast<T>(this);
- }
-
- // Safely gets a TypedParam from a param.
- // The safety comes for the fact that you don't give it a type it derives the
- // type so you can't accidentally give it the wrong type.
- // Paramaters:
- // typed_param_pointer_pointer: Pointer to a pointer to TypedParam
- // (eg, ParamFloat, ParamFloat4) which will be
- // set by this function. Will be NULL on
- // failure.
- // Returns:
- // True if successful.
- template <typename T>
- bool GetParamPointer(T** typed_param_pointer_pointer) {
- *typed_param_pointer_pointer = GetParam<T>();
- return *typed_param_pointer_pointer != NULL;
- }
-
- // Sets this parameter to be read only. This is an internal function and is
- // currently only used by ParamObject::RegisterReadOnlyParamRef
- void MarkAsReadOnly();
-
- // Get the ParamObject owning this Param.
- ParamObject* owner() const { return owner_; }
-
- // Sets this Param's owner. This should really probably be passed in
- // the constructor but that's a HUGE change.
- void set_owner(ParamObject* owner);
-
- // Sets the name of the param. This is called by ParamObject::AddParam.
- // The name can only be set once.
- void SetName(const String& name);
-
- protected:
- Param(ServiceLocator* service_locator, bool dynamic, bool read_only);
-
- // Compute or update a value from an input connection.
- // This method may be is overridden in derived classes to compute a new value.
- // The default implementation gets its value from an input connection if one
- // exists.
- virtual void ComputeValue();
-
- // Sets the client's error to an error message about read only. The sole
- // purpose of this function is so that client does not have to be defined
- // in param.h.
- void ReportReadOnlyError();
-
- // Sets the client's error to an error message about trying to set a dynamic
- // param. The sole purpose of this function is so that client does not have to
- // be defined in param.h.
- void ReportDynamicSetError();
-
- // Makes sure the data_ value is up to date, evaluating the input connection
- // if necessary.
- inline void UpdateValue() {
- if ((dynamic_ || !input_connection_.IsNull()) && !IsValid()) {
- ComputeValue();
- Validate();
- }
- }
-
- // Makes sure this param re-evaluates its value
- inline void Invalidate() {
- last_evaluation_count_ = evaluation_counter_->evaluation_count() - 1;
- }
-
- // Marks the param as valid so that it will not update its value.
- inline void Validate() {
- last_evaluation_count_ = evaluation_counter_->evaluation_count();
- }
-
- // Returns true if the param is valid.
- inline bool IsValid() {
- return last_evaluation_count_ == evaluation_counter_->evaluation_count() &&
- not_cachable_count_ == 0;
- }
-
- // This is a glue function for Client::InvalidateAllParameters so we
- // don't have to define client in this file.
- void InvalidateAllParameters();
-
- // Invalidates all the params that depend on this param
- void InvalidateAllOutputs() const;
-
- // Invalidates all the params that we depend. (also Invalidates ourself)
- void InvalidateAllInputs();
-
- // Marks this param non-cachable. Used during initialization only to mark a
- // param as not cachable.
- void SetNotCachable();
-
- // Called after a Param is bound to another. You can override this in a
- // derived class.
- virtual void OnAfterBindInput() { }
-
- // Called after a Param is unbound from another. You can override this in a
- // derived class.
- // Parameters:
- // old_source: The Param that used to be bound.
- virtual void OnAfterUnbindInput(Param* old_source) { }
-
- private:
- // Adds ALL the params that affect this Param to the ParamVector.
- // Parameters:
- // original: the original param we started from. We'll stop if we see this
- // again since that's a cycle.
- // params: ParamVector to add inputs Params to
- void AddInputsRecursive(const Param* original, ParamVector* params) const;
-
- // Returns ALL the params this Param affects to the ParamVector.
- // Parameters:
- // original: the original param we started from. We'll stop if we see this
- // again since that's a cycle.
- // params: ParamVector to add outputs Params to
- void AddOutputsRecursive(const Param* original, ParamVector* params) const;
-
- // Adds a Param to the list of Params using this Param as source.
- void AddOutputConnection(Param* param);
-
- // Removes any existing input connection from the Param.
- void ResetInputConnection();
-
- void IncrementNotCachableCountForThisParamAndAllItsOuputs();
- void DecrementNotCachableCountForThisParamAndAllItsOuputs();
-
- // Array of references to Params.
- typedef std::vector<Param::Ref> ParamRefArray;
-
- // Name of the Param.
- String name_;
-
- EvaluationCounter* evaluation_counter_;
-
- // Pointer to an input connection, if one exists.
- Param::Ref input_connection_;
-
- // List of output connections.
- ParamVector output_connections_;
-
- // Value is cachable. If this is not zero we must call UpdateValue. Cachable
- // is zero by default execpt for Standard Params. Anytime a Param is bound the
- // Param Chain is checked and this flag will be cleared if any input in that
- // chain is not cachable. When the param is unbound the flag will be set
- // again.
- int not_cachable_count_;
-
- // Flag that value is dynamic and therefore ComputeValue needs to be called
- bool dynamic_;
-
- // Flag that value is read only so set_value and bind should fail
- bool read_only_;
-
- // Handle to an implementation specific object corresponding to the Param.
- const void *handle_;
-
- // ParamObject we are owned by.
- ParamObject* owner_;
-
- // last evaluation count. If this value doesn't match the global count
- // then our value is out of date.
- int last_evaluation_count_;
-
- // if true we update our input connection before we evaluate. default = true.
- // See set_update_input() for details.
- bool update_input_;
-
- O3D_DECL_CLASS(Param, NamedObjectBase);
- DISALLOW_COPY_AND_ASSIGN(Param);
-};
-
-// A template for value based param types except it does not implement
-// CopyDataFromParam.
-template<class T>
-class TypedParamBase : public Param {
- public:
- typedef T DataType;
- TypedParamBase(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : Param(service_locator, dynamic, read_only) {}
- virtual ~TypedParamBase() {}
-
- // Sets the value stored in the Param.
- void set_value(const DataType& value) {
- if (!dynamic() && input_connection() == NULL) {
- // This check is not good enough because for example, setting localMatrix
- // affects worldMatrix but that relationship is not expressed.
- //
- // TODO: add flag to mark params like local matrix as having output
- // so we can check that flag here.
- //
- // if (!output_connections_.empty()) {
- // InvalidateAllParameters();
- // }
- InvalidateAllParameters();
- set_dynamic_value(value);
- } else {
- ReportDynamicSetError();
- }
- }
-
- // Sets the value stored in the Param without checking if it's dynamic.
- // ParamBinds should use this function.
- void set_dynamic_value(const DataType& value) {
- if (!read_only()) {
- value_ = value;
- Validate();
- } else {
- ReportReadOnlyError();
- }
- }
-
- // Sets the value for a read only param because there needs to be some way
- // to set it. This is an internal only function.
- void set_read_only_value(const DataType& value) {
- value_ = value;
- }
-
- // Returns the current value stored in the Param.
- DataType value() PARAM_VALUE_CONST {
- UpdateValue();
- return value_;
- }
-
- protected:
- // Because gcc complains that I can't set value_ directly from TypedParam
- void set_value_private(DataType value) {
- value_ = value;
- }
-
- // The value stored in the Param.
- DataType value_;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(TypedParamBase);
-};
-
-template<class T>
-class TypedParam : public TypedParamBase<T> {
- public:
- typedef T DataType;
- TypedParam(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedParamBase<T>(service_locator, dynamic, read_only) {}
- virtual ~TypedParam() {}
-
- // Copies the data from another Param.
- virtual void CopyDataFromParam(Param* source_param) {
- set_value_private((down_cast<TypedParam*>(source_param))->value_);
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(TypedParam);
-};
-
-// Abstract base class of all reference params.
-class RefParamBase : public Param {
- public:
- RefParamBase(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : Param(service_locator, dynamic, read_only) {}
- virtual ~RefParamBase() {}
-
- virtual ObjectBase* value() PARAM_VALUE_CONST = 0;
-
- private:
- O3D_DECL_CLASS(RefParamBase, Param);
- DISALLOW_COPY_AND_ASSIGN(RefParamBase);
-};
-
-// Abstract base class for Specialized TypedParam for SmartPtr objects that have
-// a GetWeakPointer method. Implements all needed methods except
-// CopyDataFromParam.
-template<typename T>
-class TypedRefParamBase : public RefParamBase {
- public:
- typedef WeakPointer<T> WeakPointerType;
-
- TypedRefParamBase(ServiceLocator* service_locator,
- bool dynamic,
- bool read_only)
- : RefParamBase(service_locator, dynamic, read_only) {}
- virtual ~TypedRefParamBase() {}
-
- // Set the value stored in the param if it is not dynmaically updated. If the
- // user attempts to set the value and the value happens to be driven by a bind
- // they'll get an error telling them what they just tried is not going to
- // work.
- void set_value(T* const value) {
- if (!dynamic() && input_connection() == NULL) {
- // This check is not good enough because for example, setting localMatrix
- // affects worldMatrix but that relationship is not expressed.
- //
- // TODO: add flag to mark params like local matrix as having output
- // so we can check that flag here.
- //
- // if (!output_connections_.empty()) {
- // InvalidateAllParameters();
- // }
- InvalidateAllParameters();
- set_dynamic_value(value);
- } else {
- ReportDynamicSetError();
- }
- }
-
- // Sets the value stored in the Param without checking if it's dynamic.
- // ParamBinds should use this function.
- void set_dynamic_value(T* const value) {
- if (!read_only()) {
- value_ = value ? value->GetWeakPointer() : WeakPointerType();
- Validate();
- } else {
- ReportReadOnlyError();
- }
- }
-
- // Sets the value for a read only param because there needs to be some way
- // to set it.
- void set_read_only_value(T* const value) {
- value_ = value ? value->GetWeakPointer() : WeakPointerType();
- }
-
- // Returns the current value stored in the Param.
- T* value() PARAM_VALUE_CONST {
- UpdateValue();
- return value_.Get();
- }
-
- protected:
- // Because gcc complains that I can't set value_ directly from TypedRefParam.
- void set_value_private(WeakPointerType value) {
- value_ = value;
- }
-
- // The value stored in the Param.
- WeakPointerType value_;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(TypedRefParamBase);
-};
-
-// Fully specialize TypedParam for SmartPtr objects that have a GetWeakPointer
-// method.
-template<typename T>
-class TypedRefParam : public TypedRefParamBase<T> {
- public:
- typedef WeakPointer<T> WeakPointerType;
-
- TypedRefParam(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedRefParamBase<T>(service_locator, dynamic, read_only) {
- }
- virtual ~TypedRefParam() {}
-
- // Copies the data from another Param.
- virtual void CopyDataFromParam(Param* source_param) {
- T* value = down_cast<TypedRefParam*>(source_param)->value_.Get();
- set_value_private(value ? value->GetWeakPointer() : WeakPointerType());
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(TypedRefParam);
-};
-
-// The following are type defines for Param types used by the Param system.
-// We use an inheritance model so that these names may be forward declared.
-class ParamFloat : public TypedParam<Float> {
- public:
- typedef SmartPointer<ParamFloat> Ref;
-
- protected:
- ParamFloat(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedParam<Float>(service_locator, dynamic, read_only) {
- set_read_only_value(0.0f);
- }
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamFloat, Param);
- DISALLOW_COPY_AND_ASSIGN(ParamFloat);
-};
-
-class ParamFloat2 : public TypedParam<Float2> {
- public:
- typedef SmartPointer<ParamFloat2> Ref;
-
- protected:
- ParamFloat2(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedParam<Float2>(service_locator, dynamic, read_only) {
- set_read_only_value(Float2(0.0f, 0.0f));
- }
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamFloat2, Param);
- DISALLOW_COPY_AND_ASSIGN(ParamFloat2);
-};
-
-class ParamFloat3 : public TypedParam<Float3> {
- public:
- typedef SmartPointer<ParamFloat3> Ref;
-
- protected:
- ParamFloat3(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedParam<Float3>(service_locator, dynamic, read_only) {
- set_read_only_value(Float3(0.0f, 0.0f, 0.0f));
- }
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamFloat3, Param);
- DISALLOW_COPY_AND_ASSIGN(ParamFloat3);
-};
-
-class ParamFloat4 : public TypedParam<Float4> {
- public:
- typedef SmartPointer<ParamFloat4> Ref;
-
- protected:
- ParamFloat4(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedParam<Float4>(service_locator, dynamic, read_only) {
- set_read_only_value(Float4(0.0f, 0.0f, 0.0f, 0.0f));
- }
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamFloat4, Param);
- DISALLOW_COPY_AND_ASSIGN(ParamFloat4);
-};
-
-class ParamInteger : public TypedParam<int> {
- public:
- typedef SmartPointer<ParamInteger> Ref;
-
- protected:
- ParamInteger(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedParam<int>(service_locator, dynamic, read_only) {
- set_read_only_value(0);
- }
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamInteger, Param);
- DISALLOW_COPY_AND_ASSIGN(ParamInteger);
-};
-
-class ParamBoolean : public TypedParam<bool> {
- public:
- typedef SmartPointer<ParamBoolean> Ref;
-
- protected:
- ParamBoolean(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedParam<bool>(service_locator, dynamic, read_only) {
- set_read_only_value(false);
- }
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamBoolean, Param);
- DISALLOW_COPY_AND_ASSIGN(ParamBoolean);
-};
-
-class ParamString : public TypedParam<String> {
- public:
- typedef SmartPointer<ParamString> Ref;
-
- protected:
- ParamString(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedParam<String>(service_locator, dynamic, read_only) {}
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamString, Param);
-};
-
-class ParamMatrix4 : public TypedParam<Matrix4> {
- public:
- typedef SmartPointer<ParamMatrix4> Ref;
-
- protected:
- ParamMatrix4(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedParam<Matrix4>(service_locator, dynamic, read_only) {
- set_read_only_value(Vectormath::Aos::Matrix4::identity());
- }
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamMatrix4, Param);
- DISALLOW_COPY_AND_ASSIGN(ParamMatrix4);
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_PARAM_H_
diff --git a/o3d/core/cross/param_array.cc b/o3d/core/cross/param_array.cc
deleted file mode 100644
index e6c168b..0000000
--- a/o3d/core/cross/param_array.cc
+++ /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 contains the implementation of class ParamArray.
-
-#include "core/cross/param_array.h"
-#include "core/cross/error.h"
-#include "core/cross/iclass_manager.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(ParamArray, NamedObject);
-O3D_DEFN_CLASS(ParamParamArray, RefParamBase);
-
-ParamArray::ParamArray(ServiceLocator* service_locator)
- : NamedObject(service_locator),
- class_manager_(service_locator->GetService<IClassManager>()),
- weak_pointer_manager_(this) {
-}
-
-ParamArray::~ParamArray() {
- // Tell each Param to Unbind so that other things will let go of it.
- {
- ParamRefVector::iterator end(params_.end());
- for (ParamRefVector::iterator iter(params_.begin());
- iter != end;
- ++iter) {
- Param* param = (*iter).Get();
- if (param) {
- param->UnbindInput();
- param->UnbindOutputs();
- }
- }
- }
-}
-
-Param* ParamArray::CreateParamByClass(unsigned index,
- const ObjectBase::Class* type) {
- if (!ObjectBase::ClassIsA(type, Param::GetApparentClass())) {
- O3D_ERROR(service_locator()) << type->name()
- << " is not a type of Param";
- } else {
- // Create and insert Params until creating this new Param will not be
- // out of range.
- if (params_.size() <= index) {
- params_.reserve(index + 1);
- while (params_.size() <= index) {
- Param::Ref param(down_cast<Param*>(
- class_manager_->CreateObjectByClass(type).Get()));
- if (param.IsNull()) {
- O3D_ERROR(service_locator())
- << "could not create param at index " << params_.size();
- }
- params_.push_back(param);
- }
- }
-
- // Create our new Param.
- {
- Param::Ref param(down_cast<Param*>(
- class_manager_->CreateObjectByClass(type).Get()));
-
- if (!param.IsNull()) {
- params_[index]->UnbindInput();
- params_[index]->UnbindOutputs();
- params_[index] = param;
- return param.Get();
- }
- }
- }
- return NULL;
-}
-
-Param* ParamArray::CreateParamByClassName(unsigned index,
- const String& class_type_name) {
- const ObjectBase::Class* class_type = class_manager_->GetClassByClassName(
- class_type_name);
- if (!class_type) {
- O3D_ERROR(service_locator()) << class_type_name
- << " is not a type of Param";
- return NULL;
- }
-
- return CreateParamByClass(index, class_type);
-}
-
-void ParamArray::ResizeByClass(unsigned num_params,
- const ObjectBase::Class* type) {
- if (num_params > params_.size()) {
- CreateParamByClass(num_params - 1, type);
- } else if (num_params < params_.size()) {
- RemoveParams(num_params, params_.size() - num_params);
- }
-}
-
-void ParamArray::ResizeByClassName(unsigned num_params,
- const String& class_type_name) {
- const ObjectBase::Class* class_type = class_manager_->GetClassByClassName(
- class_type_name);
- if (!class_type) {
- O3D_ERROR(service_locator()) << class_type_name
- << " is not a type of Param";
- return;
- }
-
- ResizeByClass(num_params, class_type);
-}
-
-void ParamArray::RemoveParams(unsigned start_index, unsigned num_to_remove) {
- if (start_index < params_.size() && num_to_remove > 0) {
- unsigned end_index = start_index + num_to_remove;
- if (end_index > params_.size()) {
- end_index = params_.size();
- }
- for (unsigned ii = start_index; ii < end_index; ++ii) {
- params_[ii]->UnbindInput();
- params_[ii]->UnbindOutputs();
- }
- params_.erase(params_.begin() + start_index, params_.begin() + end_index);
- }
-}
-
-bool ParamArray::ParamInArray(const Param* param) const {
- for (unsigned ii = 0; ii < params_.size(); ++ii) {
- if (params_[ii] == param) {
- return true;
- }
- }
- return false;
-}
-
-ObjectBase::Ref ParamArray::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamArray(service_locator));
-}
-
-ObjectBase::Ref ParamParamArray::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamParamArray(service_locator, false, false));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/param_array.h b/o3d/core/cross/param_array.h
deleted file mode 100644
index 32cf71c..0000000
--- a/o3d/core/cross/param_array.h
+++ /dev/null
@@ -1,186 +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 declaration of class ParamArray and ParamParamArray.
-
-#ifndef O3D_CORE_CROSS_PARAM_ARRAY_H_
-#define O3D_CORE_CROSS_PARAM_ARRAY_H_
-
-#include <vector>
-#include "core/cross/named_object.h"
-#include "core/cross/param.h"
-
-namespace o3d {
-
-class IClassManager;
-
-// ParamArray is an array of a Params that can be accessed by index. Two common
-// uses are all the matrices needed for skinning can be stored in a ParamArray.
-// Another is for texture animation, the textures can be stored in a ParamArray.
-class ParamArray : public NamedObject {
- public:
- typedef SmartPointer<ParamArray> Ref;
- typedef WeakPointer<ParamArray> WeakPointerType;
- typedef std::vector<Param::Ref> ParamRefVector;
-
- ~ParamArray();
-
- // Creates a Param of the given type at the index requested. If a Param
- // already exists at that index the new param will replace that it. If the
- // index is past the end of the current array params of the requested type
- // will be created to fill out the array to the requested index.
- //
- // From C++ use the template CreateParam<ParamType>.
- //
- // Parameters:
- // index: index at which to create new param.
- // class_type: type of param to create.
- // Returns:
- // Param created at index or NULL if failure.
- Param* CreateParamByClass(unsigned index,
- const ObjectBase::Class* class_type);
-
- // Same as CreateParamByClass except takes a class name for Javascript.
- // Parameters:
- // index: index at which to create new param.
- // class_name: class name of param to create.
- // Returns:
- // index to Param created at index or NULL if failure.
- Param* CreateParamByClassName(unsigned index,
- const String& class_name);
-
- // Resizes the array of params.
- // Parameters:
- // num_param: number of params to put in array.
- // class_type: type of param to create if params need to be created.
- void ResizeByClass(unsigned num_param, const ObjectBase::Class* class_type);
-
- // Same as ResizeByClass except takes a class name for Javascript.
- // Parameters:
- // index: index at which to create new param.
- // class_name: class name of param to create.
- void ResizeByClassName(unsigned num_param, const String& class_name);
-
- // Returns the number of params. Note: In javascript this is called "length".
- unsigned size() const {
- return static_cast<unsigned>(params_.size());
- }
-
- // Returns a const reference to the actual array of params.
- const ParamRefVector& params() const {
- return params_;
- }
-
- // Removes a range of params
- void RemoveParams(unsigned start_index, unsigned num_to_remove);
-
- // A typesafe version of CreateParamByClass for C++. Example usage
- // ParamFloat4* param = param_vector->CreateParam<ParamFloat4>(index);
- template <typename T>
- T* CreateParam(unsigned index) {
- return down_cast<T*>(CreateParamByClass(index, T::GetApparentClass()));
- }
-
- // Gets a Param from the ParamArray by index. From C++ use GetParam.
- // Parameters:
- // index: index of param to get.
- // Returns:
- // The address of the Param or NULL if the index is out of range.
- Param* GetUntypedParam(unsigned index) const {
- return index < params_.size() ? params_[index].Get() : NULL;
- }
-
- // A typesafe version of GetUntypedParam for C++. Example usage
- // ParamFloat4* param = array->GetParam<ParamFloat4>(index);
- // Parameters:
- // index: index of param to get.
- // Returns:
- // The address of the Param or NULL if the index is out of range or the type
- // is incompatible.
- template <typename T>
- T* GetParam(unsigned index) const {
- Param* param = GetUntypedParam(index);
- return (param && param->IsA(T::GetApparentClass())) ?
- down_cast<T*>(param) : NULL;
- }
-
- // Checks if a param is in this ParamArray
- // Parameters:
- // param: param to check for.
- // Returns:
- // True if the param is in the array.
- bool ParamInArray(const Param* param) const;
-
- // Gets a weak pointer to us.
- WeakPointerType GetWeakPointer() const {
- return weak_pointer_manager_.GetWeakPointer();
- }
-
- private:
- explicit ParamArray(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- IClassManager* class_manager_;
-
- // The array of params.
- ParamRefVector params_;
-
- // Manager for weak pointers to us.
- WeakPointerType::WeakPointerManager weak_pointer_manager_;
-
- O3D_DECL_CLASS(ParamArray, NamedObject);
- DISALLOW_COPY_AND_ASSIGN(ParamArray);
-};
-
-// A Param that holds a weak pointer to a ParamArray.
-class ParamParamArray : public TypedRefParam<ParamArray> {
- public:
- typedef SmartPointer<ParamParamArray> Ref;
-
- ParamParamArray(ServiceLocator* service_locator,
- bool dynamic,
- bool read_only)
- : TypedRefParam<ParamArray>(service_locator, dynamic, read_only) {
- }
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamParamArray, RefParamBase);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_PARAM_ARRAY_H_
diff --git a/o3d/core/cross/param_array_test.cc b/o3d/core/cross/param_array_test.cc
deleted file mode 100644
index 8ffa04f..0000000
--- a/o3d/core/cross/param_array_test.cc
+++ /dev/null
@@ -1,181 +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 functionality of the ParamArray class
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/id_manager.h"
-#include "core/cross/error.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/param_array.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/standard_param.h"
-#include "core/cross/transformation_context.h"
-
-namespace o3d {
-
-// Test fixture for ParamArray testing. Creates a pack before each test and
-// deletes it after.
-class ParamArrayTest : public testing::Test {
- protected:
-
- ParamArrayTest()
- : object_manager_(g_service_locator),
- transformation_context_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- ServiceDependency<ObjectManager> object_manager_;
- TransformationContext transformation_context_;
-
- private:
- Pack* pack_;
-};
-
-void ParamArrayTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void ParamArrayTest::TearDown() {
- pack_->Destroy();
-}
-
-// Test ParamArray
-TEST_F(ParamArrayTest, Basic) {
- ParamArray* param_array = pack()->Create<ParamArray>();
- // Check that it got created.
- ASSERT_TRUE(param_array != NULL);
-
- // Check that it inherits from what we expect it to.
- EXPECT_TRUE(param_array->IsA(NamedObject::GetApparentClass()));
-
- // Check that it's size is zero.
- EXPECT_EQ(param_array->size(), 0U);
-}
-
-// Test ParamArray::CreateParam
-TEST_F(ParamArrayTest, CreateParam) {
- ParamArray* param_array = pack()->Create<ParamArray>();
- // Check that it got created.
- ASSERT_TRUE(param_array != NULL);
-
- // Check we can add a param.
- ParamFloat* param_0 = param_array->CreateParam<ParamFloat>(0);
- ASSERT_TRUE(param_0 != NULL);
-
- // Check the length.
- EXPECT_EQ(param_array->size(), 1U);
-
- // Add some more.
- ParamFloat* param_5 = param_array->CreateParam<ParamFloat>(5);
- ASSERT_TRUE(param_5 != NULL);
-
- // Check that the params in between got created.
- EXPECT_EQ(param_array->size(), 6U);
- EXPECT_EQ(param_array->GetParam<ParamFloat>(0), param_0);
- EXPECT_TRUE(param_array->GetParam<ParamFloat>(1) != NULL);
- EXPECT_TRUE(param_array->GetParam<ParamFloat>(2) != NULL);
- EXPECT_TRUE(param_array->GetParam<ParamFloat>(3) != NULL);
- EXPECT_TRUE(param_array->GetParam<ParamFloat>(4) != NULL);
- EXPECT_EQ(param_array->GetParam<ParamFloat>(5), param_5);
-
- // Check that out of range params don't exit.
- EXPECT_TRUE(param_array->GetParam<ParamFloat>(6) == NULL);
-
- // Check replacing a param.
- ParamFloat* new_param_5 = param_array->CreateParam<ParamFloat>(5);
- ASSERT_TRUE(new_param_5 != NULL);
-
- EXPECT_EQ(param_array->size(), 6U);
- EXPECT_EQ(param_array->GetParam<ParamFloat>(0), param_0);
- EXPECT_TRUE(param_array->GetParam<ParamFloat>(1) != NULL);
- EXPECT_TRUE(param_array->GetParam<ParamFloat>(2) != NULL);
- EXPECT_TRUE(param_array->GetParam<ParamFloat>(3) != NULL);
- EXPECT_TRUE(param_array->GetParam<ParamFloat>(4) != NULL);
- EXPECT_EQ(param_array->GetParam<ParamFloat>(5), new_param_5);
-
- // Check using ParamInArray.
- EXPECT_TRUE(param_array->ParamInArray(new_param_5));
- EXPECT_FALSE(param_array->ParamInArray(param_5));
-}
-
-// Test ParamArray::RemoveParams
-TEST_F(ParamArrayTest, RemoveParam) {
- ParamArray* param_array = pack()->Create<ParamArray>();
- // Check that it got created.
- ASSERT_TRUE(param_array != NULL);
-
- // Check we can add params.
- ParamFloat* param_0 = param_array->CreateParam<ParamFloat>(6);
- ASSERT_TRUE(param_0 != NULL);
-
- // Check the length.
- EXPECT_EQ(param_array->size(), 7U);
-
- // Get the last param so we can see that it moves.
- ParamFloat* param;
- param = param_array->GetParam<ParamFloat>(6);
- ASSERT_TRUE(param != NULL);
-
- // Remove a single param.
- param_array->RemoveParams(1, 1);
-
- EXPECT_EQ(param_array->size(), 6U);
- EXPECT_EQ(param_array->GetParam<ParamFloat>(5), param);
-
- // Remove a range
- param_array->RemoveParams(1, 3);
- EXPECT_EQ(param_array->size(), 3U);
- EXPECT_EQ(param_array->GetParam<ParamFloat>(2), param);
-
- // Remove the first param.
- param_array->RemoveParams(0, 1);
- EXPECT_EQ(param_array->size(), 2U);
- EXPECT_EQ(param_array->GetParam<ParamFloat>(1), param);
-
- // Remove the end param
- param_array->RemoveParams(1, 1);
- EXPECT_EQ(param_array->size(), 1U);
- EXPECT_NE(param_array->GetParam<ParamFloat>(0), param);
-
- // Remove the remaining param.
- param_array->RemoveParams(0, 1);
- EXPECT_EQ(param_array->size(), 0U);
- EXPECT_TRUE(param_array->GetParam<ParamFloat>(0) == NULL);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/param_cache.cc b/o3d/core/cross/param_cache.cc
deleted file mode 100644
index cee5759..0000000
--- a/o3d/core/cross/param_cache.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 contains the definition of DrawElement.
-
-#include "core/cross/param_cache.h"
-#include "core/cross/effect.h"
-#include "core/cross/element.h"
-#include "core/cross/draw_element.h"
-#include "core/cross/material.h"
-#include "core/cross/renderer.h"
-
-namespace o3d {
-
-void ParamCache::ClearParamCache() {
- rebuild_cache_ = true;
-}
-
-bool ParamCache::ValidateAndCacheParams(Effect* effect,
- DrawElement* draw_element,
- Element* element,
- StreamBank* stream_bank,
- Material* material,
- ParamObject* override) {
- if (rebuild_cache_ ||
- draw_element_tracker_.NeedToUpdate(draw_element) ||
- element_tracker_.NeedToUpdate(element) ||
- material_tracker_.NeedToUpdate(material) ||
- effect_tracker_.NeedToUpdate(effect) ||
- stream_bank_tracker_.NeedToUpdate(stream_bank) ||
- override_tracker_.NeedToUpdate(override) ||
- !ValidateEffect(effect)) {
- UpdateCache(effect, draw_element, element, material, override);
- draw_element_tracker_.Update(draw_element);
- element_tracker_.Update(element);
- material_tracker_.Update(material);
- effect_tracker_.Update(effect);
- stream_bank_tracker_.Update(stream_bank);
- override_tracker_.Update(override);
- rebuild_cache_ = false;
- return false;
- }
- return true;
-}
-
-ParamCacheManager::ParamCacheManager(Renderer* renderer)
- : top_cache_index_(0),
- last_render_count_(renderer->render_frame_count() - 1) {
-}
-
-ParamCacheManager::~ParamCacheManager() {
- for (unsigned ii = 0; ii < param_caches_.size(); ++ii) {
- delete param_caches_[ii];
- }
-}
-
-ParamCache* ParamCacheManager::GetNextCache(Renderer* renderer) {
- // If this is the first time we've been asked for a cache this frame
- // reset to start using the first cache.
- if (renderer->render_frame_count() != last_render_count_) {
- last_render_count_ = renderer->render_frame_count();
- // remove any un-needed caches.
- for (unsigned ii = top_cache_index_; ii < param_caches_.size(); ++ii) {
- renderer->FreeParamCache(param_caches_[ii]);
- param_caches_[ii] = NULL;
- }
-
- // Reset to first cache.
- top_cache_index_ = 0;
- }
-
- // ParamCaches only get created once and then reused. This saves lots of
- // allocations/deallocation that would otherwise happen every frame.
-
- // If I instead used size() then I would have to clear() param_caches_ each
- // frame which in turn would mean I'd need to keep a separate container of
- // ParamCaches to keep track of the ParamCaches I'm keeping around and pulling
- // them out of that container and putting them in this one.
-
- // Instead I just keep using the ones in this container and use
- // top_cache_index_ to track the highest used ParamCache.
- if (top_cache_index_ >= param_caches_.size()) {
- param_caches_.push_back(NULL);
- }
- ParamCache* param_cache = param_caches_[top_cache_index_];
- if (!param_cache) {
- param_cache = renderer->CreateParamCache();
- param_caches_[top_cache_index_] = param_cache;
- }
- ++top_cache_index_;
- return param_cache;
-}
-
-} // namespace o3d
-
-
-
-
-
diff --git a/o3d/core/cross/param_cache.h b/o3d/core/cross/param_cache.h
deleted file mode 100644
index 947bdca..0000000
--- a/o3d/core/cross/param_cache.h
+++ /dev/null
@@ -1,154 +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 declaration of ParamCache.
-
-#ifndef O3D_CORE_CROSS_PARAM_CACHE_H_
-#define O3D_CORE_CROSS_PARAM_CACHE_H_
-
-#include <vector>
-#include "core/cross/param_object.h"
-#include "core/cross/stream_bank.h"
-
-namespace o3d {
-
-class Element;
-class Renderer;
-class Material;
-class DrawElement;
-class Effect;
-
-// A ParamCache holds on to a specific set of Platform specific shader params
-// to O3D param cached map to make rendering faster.
-class ParamCache {
- public:
- ParamCache() : rebuild_cache_(true) {}
- virtual ~ParamCache() {}
-
- // Clears any internal Param to Shader Parameter cache.
- void ClearParamCache();
-
- // Checks if the cache of Params to Effect parameters is valid and if it is
- // not rebuilds the cache.
- // Returns true if the cache was valid, false if it was rebuilt.
- bool ValidateAndCacheParams(Effect* effect,
- DrawElement* draw_element,
- Element* element,
- StreamBank* stream_bank,
- Material* material,
- ParamObject* override);
-
- // Update the cache of params.
- virtual void UpdateCache(Effect* effect,
- DrawElement* draw_element,
- Element* element,
- Material* material,
- ParamObject* override) = 0;
- protected:
- // Validates platform specific information about the effect.
- // Returns:
- // True if effect and cache are valid.
- virtual bool ValidateEffect(Effect* effect) = 0;
-
- private:
- // If true we need to rebuild the cache of Params to Shader Parameters.
- bool rebuild_cache_;
-
- // A class to track the change of an object and its parameters.
- template <typename T, typename TPOINTER>
- class ChangeTracker {
- public:
- ChangeTracker()
- : last_object_(NULL),
- last_change_count_(0) {
- }
-
- inline bool NeedToUpdate(TPOINTER object) {
- return object != last_object_ ||
- (object != NULL &&
- object->change_count() != last_change_count_);
- }
-
- inline void Update(TPOINTER object) {
- last_object_ = T(object);
- last_change_count_ = object->change_count();
- }
-
- private:
- T last_object_;
- int last_change_count_;
- };
-
- // These fields track whether this cache matches a certain set of inputs.
- ChangeTracker<ParamObject::Ref, ParamObject*> draw_element_tracker_;
- ChangeTracker<ParamObject::Ref, ParamObject*> element_tracker_;
- ChangeTracker<ParamObject::Ref, ParamObject*> material_tracker_;
- ChangeTracker<ParamObject::Ref, ParamObject*> effect_tracker_;
- ChangeTracker<StreamBank::Ref, StreamBank*> stream_bank_tracker_;
- ChangeTracker<ParamObject*, ParamObject*> override_tracker_;
-
- // NOTE: override_tracker_ has to be a pointer, not a Ref because the cache is
- // stored inside a Transform and ends up referencing itself making it
- // unfreeable. Is okay that it's a pointer though because a cache is always
- // used for by a transform for itself so there is no chance that the
- // override_tracker's pointer will point to something that was freed.
-
- DISALLOW_COPY_AND_ASSIGN(ParamCache);
-};
-
-// A ParamCacheManager manages an array of ParamCaches.
-class ParamCacheManager {
- public:
- explicit ParamCacheManager(Renderer* renderer);
- ~ParamCacheManager();
-
- // Returns the next ParamCache
- // Returns:
- // The next ParamCache
- ParamCache* GetNextCache(Renderer* renderer);
-
- private:
- typedef std::vector<ParamCache*> ParamCacheArray;
- ParamCacheArray param_caches_;
-
- unsigned top_cache_index_;
-
- // If this does not match the current render count we need to reset
- // the top cache.
- int last_render_count_;
-
- DISALLOW_COPY_AND_ASSIGN(ParamCacheManager);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_PARAM_CACHE_H_
diff --git a/o3d/core/cross/param_object.cc b/o3d/core/cross/param_object.cc
deleted file mode 100644
index 7127738..0000000
--- a/o3d/core/cross/param_object.cc
+++ /dev/null
@@ -1,313 +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 ParamObject, the base class for all
-// objects that can have Params.
-
-#include "core/cross/param_object.h"
-#include "base/cross/std_functional.h"
-#include "core/cross/draw_context.h"
-#include "core/cross/param.h"
-#include "core/cross/standard_param.h"
-#include "core/cross/iclass_manager.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(ParamObject, NamedObject);
-
-ParamObject::ParamObject(ServiceLocator* service_locator)
- : NamedObject(service_locator),
- class_manager_(service_locator->GetService<IClassManager>()),
- change_count_(1) {
-}
-
-ParamObject::~ParamObject() {
- // Tell each Param to Unbind so that other things will let go of it.
- {
- NamedParamRefMap::iterator end(params_.end());
- for (NamedParamRefMap::iterator iter(params_.begin());
- iter != end;
- ++iter) {
- iter->second->UnbindInput();
- iter->second->UnbindOutputs();
- }
- }
-
- // Delete all helpers contained in the map.
- {
- ParamRefHelperMultiMapIterator it, end = param_ref_helper_map_.end();
- for (it = param_ref_helper_map_.begin(); it != end; ++it) {
- delete it->second;
- }
- }
-}
-
-ObjectBase::Ref ParamObject::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamObject(service_locator));
-}
-
-// Factory method for Param objects. Creates a new Param on the object.
-Param* ParamObject::CreateParamByClass(const String& param_name,
- const ObjectBase::Class* type) {
- if (ObjectBase::ClassIsA(type, Param::GetApparentClass())) {
- Param::Ref param(down_cast<Param*>(
- class_manager_->CreateObjectByClass(type).Get()));
-
- // Tell the param to add the Param to its list.
- if (!param.IsNull())
- if (!AddParam(param_name, param.Get())) {
- // No need to delete the param. It's held by ref which will go zero
- // on return.
- return NULL;
- }
-
- return param.Get();
- }
- return NULL;
-}
-
-// Factory method for Param objects. Creates a new Param on the object.
-Param* ParamObject::CreateParamByClassName(const String& param_name,
- const String& class_type_name) {
- if (class_manager_->ClassNameIsAClass(class_type_name,
- Param::GetApparentClass())) {
- Param::Ref param(down_cast<Param*>(
- class_manager_->CreateObject(class_type_name).Get()));
-
- // Tell the param to add the Param to its list.
- if (!param.IsNull())
- if (!AddParam(param_name, param.Get())) {
- // No need to delete the param. It's held by ref which will go zero
- // on return.
- return NULL;
- }
-
- return param.Get();
- }
- return NULL;
-}
-
-// Looks in the param_map for a Param with the given name.
-Param* ParamObject::GetUntypedParam(const String& name) const {
- NamedParamRefMap::const_iterator iter = params_.find(name);
- if (iter == params_.end()) {
- // Try adding the o3d namespace prefix
- String prefixed_name(O3D_STRING_CONSTANT("") + name);
- iter = params_.find(prefixed_name);
- if (iter == params_.end()) {
- return NULL;
- }
- }
-
- return iter->second.Get();
-}
-
-// Looks up the given Param name in the param_map, and returns it if
-// it is of the correct type. If it is of the wrong type, NULL is
-// returned. If the param does not exist, it is created with the
-// given type.
-Param* ParamObject::GetOrCreateParamByClass(const String& param_name,
- const ObjectBase::Class* type) {
- Param* param = GetUntypedParam(param_name);
- if (param) {
- if (param->GetClass() != type) {
- return NULL;
- }
- } else {
- param = CreateParamByClass(param_name, type);
- }
- return param;
-}
-
-// Copies all the params from a the given source_param_object.
-// Does not replace any currently existing params with the same
-// name.
-void ParamObject::CopyParams(ParamObject* source_param_object) {
- const NamedParamRefMap& source_params = source_param_object->params();
- NamedParamRefMap::const_iterator end(source_params.end());
- for (NamedParamRefMap::const_iterator iter(source_params.begin());
- iter != end;
- ++iter) {
- Param* source_param = iter->second;
- Param* dest_param = GetUntypedParam(source_param->name());
- if (!dest_param) {
- // it doesn't exist so duplicate it
- dest_param = CreateParamByClass(source_param->name(),
- source_param->GetClass());
- }
-
- if (dest_param) {
- if (source_param->IsA(dest_param->GetClass())) {
- // copy the value from the source
- dest_param->CopyDataFromParam(source_param);
- }
- }
- }
-}
-
-
-void ParamObject::GetParamsFast(ParamVector* param_array) const {
- param_array->clear();
- param_array->reserve(params().size());
- std::transform(params().begin(),
- params().end(),
- std::back_inserter(*param_array),
- base::select2nd<NamedParamRefMap::value_type>());
-}
-
-ParamVector ParamObject::GetParams() const {
- ParamVector param_array;
- GetParamsFast(&param_array);
- return param_array;
-}
-
-// Inserts the Param in the ParamObject's map of Params (indexed by name)
-bool ParamObject::AddParam(const String& param_name, Param *param) {
- // Makes sure the param lasts through this function.
- Param::Ref temp(param);
-
- param->SetName(param_name);
-
- if (!OnBeforeAddParam(param)) {
- return false;
- }
-
- // Inserts new Param in the map so that it can be found by name fast.
- std::pair<NamedParamRefMap::iterator, bool> result = params_.insert(
- std::make_pair(param->name(), Param::Ref(param)));
- if (!result.second) {
- return false;
- }
-
- param->set_owner(this);
-
- // Also update any refs to params by this name.
- ParamRefHelperMultiMapRange range =
- param_ref_helper_map_.equal_range(param->name());
- for (ParamRefHelperMultiMapIterator iter(range.first);
- iter != range.second;
- ++iter) {
- iter->second->UpdateParamRef(param);
- }
-
- ++change_count_;
- OnAfterAddParam(param);
-
- return true;
-}
-
-bool ParamObject::RemoveParam(Param *param) {
- if (!OnBeforeRemoveParam(param)) {
- return false;
- }
-
- // Removes new Param in the map.
- NamedParamRefMap::iterator end(params_.end());
- for (NamedParamRefMap::iterator iter(params_.begin());
- iter != end;
- ++iter) {
- if (iter->second == param) {
- param->set_owner(NULL);
- params_.erase(iter);
- ++change_count_;
- OnAfterRemoveParam(param);
- return true;
- }
- }
- return false;
-}
-
-bool ParamObject::IsAddedParam(Param* param) {
- if (param->owner() != this)
- return false;
- for (ParamRefHelperMultiMap::const_iterator it =
- param_ref_helper_map_.begin();
- it != param_ref_helper_map_.end(); ++it) {
- ParamRefHelperBase* helper = it->second;
- if (helper->IsParam(param))
- return false;
- }
- return true;
-}
-
-namespace {
-
-// Check if a Param is from the given ParamObject.
-//
-// Parameters:
-// param: param to check for. param_object: param_object to check on.
-// Returns:
-// true if param is a Param on param_object Return
-bool CheckParamIsFromParamObject(const Param* param,
- const ParamObject* param_object) {
- const NamedParamRefMap& params = param_object->params();
- NamedParamRefMap::const_iterator end(params.end());
- for (NamedParamRefMap::const_iterator iter(params.begin());
- iter != end;
- ++iter) {
- if (param == iter->second) {
- return true;
- }
- }
- return false;
-}
-
-} // anonymous namespace
-
-void ParamObject::GetInputsForParam(const Param* param,
- ParamVector* inputs) const {
- DCHECK(param);
- DCHECK(inputs);
- DCHECK(CheckParamIsFromParamObject(param, this));
- inputs->clear();
- ConcreteGetInputsForParam(param, inputs);
-}
-
-void ParamObject::GetOutputsForParam(const Param* param,
- ParamVector* outputs) const {
- DCHECK(param);
- DCHECK(outputs);
- DCHECK(CheckParamIsFromParamObject(param, this));
- outputs->clear();
- ConcreteGetOutputsForParam(param, outputs);
-}
-
-void ParamObject::ConcreteGetInputsForParam(const Param* param,
- ParamVector* inputs) const {
- // The default does nothing.
-}
-
-void ParamObject::ConcreteGetOutputsForParam(const Param* param,
- ParamVector* outputs) const {
- // The default does nothing.
-}
-} // namespace o3d
diff --git a/o3d/core/cross/param_object.h b/o3d/core/cross/param_object.h
deleted file mode 100644
index 455e54f..0000000
--- a/o3d/core/cross/param_object.h
+++ /dev/null
@@ -1,446 +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.
- */
-
-
-// Contains the declaration for ParamObject, the base class for all objects that
-// can have Params.
-
-#ifndef O3D_CORE_CROSS_PARAM_OBJECT_H_
-#define O3D_CORE_CROSS_PARAM_OBJECT_H_
-
-#include <map>
-#include <vector>
-#include <utility>
-#include "core/cross/named_object.h"
-#include "core/cross/param.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-class DrawContext;
-class IClassManager;
-class Transform;
-
-// Dictionary of Param objects indexed by name.
-typedef std::map<String, Param::Ref> NamedParamRefMap;
-
-// Base class of all objects that can contain Param elements.
-// Defines methods to add and remove params, search for params, etc.
-class ParamObject : public NamedObject {
- public:
- typedef SmartPointer<ParamObject> Ref;
-
- // Constructor takes a pointer to the Client object that owns the
- // the ParamObject.
- explicit ParamObject(ServiceLocator* service_locator);
- virtual ~ParamObject();
-
- // You can check this value, if it has changed since the last time you checked
- // it Params have been added or removed.
- // Returns:
- // The parameter change count.
- int change_count() const {
- return change_count_;
- }
-
- // Creates a Param with the given name and Class type on the ParamObject.
- // Where possible it is recommended to use the CreateParam
- // Parameters:
- // param_name: Name of the param which must be unique from other params on
- // this object.
- // class_type: Class of parameter
- // Returns:
- // Newly created parameter.
- Param* CreateParamByClass(const String& param_name,
- const ObjectBase::Class* class_type);
-
- // Creates a Param with the given name and class name.
- // Parameters:
- // param_name: Name of the param which must be unique from other params on
- // this object.
- // class_type_name: class type name of the desired parameter type. Valid type
- // names are:
- // 'o3d.ParamFloat',
- // 'o3d.ParamFloat2',
- // 'o3d.ParamFloat3',
- // 'o3d.ParamFloat4',
- // 'o3d.ParamMatrix4',
- // 'o3d.ParamInteger',
- // 'o3d.ParamBoolean',
- // 'o3d.ParamString',
- // 'o3d.ParamTexture'
- // Returns:
- // Newly created parameter.
- Param* CreateParamByClassName(const String& param_name,
- const String& class_type_name);
-
- // Creates a Param based on the type passed in. This is a type safe version of
- // CreateParam for C++. You give it the name and a pointer to a typed param
- // and it will create a param of that type.
- // Paramaters:
- // param_name: Name of the param which must be unique from other params on
- // this object.
- // Returns:
- // pointer to new param if successful.
- template<typename T>
- T* CreateParam(const String& param_name) {
- return down_cast<T*>(CreateParamByClass(param_name,
- T::GetApparentClass()));
- }
-
- // Creates a Param based on the type passed in. This is a type safe version of
- // CreateParam for C++. You give it the name and a pointer to a typed param
- // and it will create a param of that type.
- // Paramaters:
- // param_name: Name of the param which must be unique from other params on
- // this object.
- // typed_param_pointer_pointer: Pointer to a pointer to TypedParam
- // (eg, ParamFloat, ParamFloat4) which will be
- // set by this function. Will be NULL on
- // failure.
- // Returns:
- // True if successful.
- template<typename T>
- bool CreateParamPointer(const String& param_name,
- T** typed_param_pointer_pointer) {
- *typed_param_pointer_pointer = CreateParam<T>(param_name);
- return *typed_param_pointer_pointer != NULL;
- }
-
- // Gets a Param in a typesafe way
- // param_name: Name of the param.
- // Returns:
- // Pointer to typed param if successful, NULL if failure.
- template<typename T>
- T* GetParam(const String& param_name) const {
- Param* param = GetUntypedParam(param_name);
- return (param && param->GetClass() == T::GetApparentClass()) ?
- down_cast<T*>(param) : NULL;
- }
-
- // Gets a param by name, or creates it if it doesn't exist.
- // Returns the param, or NULL if it doesn't match the requested type
- Param* GetOrCreateParamByClass(const String& param_name,
- const ObjectBase::Class* param_type);
-
- // Gets a param by name, or creates it if it doesn't exist.
- // Returns the param, or NULL if it doesn't match the requested type
- template <typename T>
- T* GetOrCreateParam(const String& param_name) {
- return down_cast<T*>(GetOrCreateParamByClass(param_name,
- T::GetApparentClass()));
- }
-
- // Searches by name for a Param defined in the object. Prefer GetParam where
- // possible.
- // Parameter:
- // param_name: name of param to get.
- Param* GetUntypedParam(const String& param_name) const;
-
- // Adds a newly created param to the local Param map. Fails if a param by the
- // same name already exists.
- // Parameters:
- // param_name: Name to assign Param
- // param: Param to add.
- // Returns:
- // true if successful.
- bool AddParam(const String& param_name, Param* param);
-
- // Removes the given Param from the object.
- // Parameters:
- // param: Param to remove.
- // Returns:
- // true if successful.
- bool RemoveParam(Param* param);
-
- // Determines whether a param was added to an object after it was originally
- // constructed.
- bool IsAddedParam(Param* param);
-
- // Called before a Param is added. You can override this method and return
- // false if you want to prevent the add from succeeding. Be sure to call the
- // base and return it's result to give it a chance to refuse addition.
- // Parameter:
- // param: Param about to be added.
- // Return:
- // true if okay to add Param.
- virtual bool OnBeforeAddParam(Param* param) {
- return true;
- }
-
- // Called after a Param has been added. Override if you need to know when a
- // Param is added. Be sure to call the base.
- // Parameter:
- // param: Param that was just added.
- virtual void OnAfterAddParam(Param* param) { }
-
- // Called before a Param is about to be removed. You can override this
- // function and return false if you want to prevent a Param from being
- // removed. Be sure to call the base and return it's result to give it a
- // chance to refuse removal.
- // Parameter:
- // param: Param about to be removed.
- // Return:
- // true if okay to remove Param.
- virtual bool OnBeforeRemoveParam(Param* param) {
- return true;
- }
-
- // Called after a Param has been removed. Override if you need to know when a
- // Param has been removed. Be sure to call the base.
- // Parameter:
- // param: Param that was just added.
- virtual void OnAfterRemoveParam(Param* param) { }
-
- // Copies all the params from a the given source_param_object does not replace
- // any currently existing params with the same name.
- void CopyParams(ParamObject* source_param_object);
-
- // Return the parameter map for this object.
- const NamedParamRefMap& params() const { return params_; }
-
- // Gets all the params.
- // Paramaters:
- // param_array: ParamVector to fill in with params. Will be cleared.
- void GetParamsFast(ParamVector* param_array) const;
-
- // Gets all params.
- //
- // This is a slower version for javascript. If you are using C++ prefer the
- // version above. This one creates the array on the stack and passes it back
- // by value which means the entire array will get copied 2 twice and in making
- // the copies memory is allocated and deallocated twice.
- ParamVector GetParams() const;
-
- // This function is for internal use only. It is only called by
- // Param::AddInputsRecursive and therefore the Param will always be
- // owned by this ParamObject.
- //
- // For the given Param, returns all the inputs that affect that param through
- // this ParamObject. For example, given a Transform's worldMatrix this would
- // return both this Transform's localMatrix and its parent's worldMatrix.
- //
- // Parameters:
- // param: Param to get inputs for. Note that param MUST be a Param on this
- // ParamObject.
- // inputs: ParamVector to fill out with array of inputs. The array will be
- // cleared.
- void GetInputsForParam(const Param* param,
- ParamVector* inputs) const;
-
- // This function is for internal use only. It is only called by
- // Param::AddOutputsRecursive and therefore the Param will always be owned by
- // this ParamObject.
- //
- // For the given Param, returns all the outputs that the given param will
- // affect through this ParamObject. For example, given a Transform's
- // localMatrix it will only return this Transform's worldMatrix. For a
- // transform's worldMatrix it will return all its chilren's worldMatrices.
- //
- // Parameters:
- // param: Param to get outputs for. Note that param MUST be a Param on this
- // ParamObject.
- // outputs: ParamVector to fill out with array of outputs. The array will be
- // cleared.
- void GetOutputsForParam(const Param* param,
- ParamVector* outputs) const;
-
- // Registers a pointer to a reference to a parameter. If the parameter
- // does not exist it will be created. The reference will be set to refer
- // to the parameter.
- // Parameters:
- // param_name: name of parameter
- // typed_param_ref_pointer: address of param ref
- template<typename T>
- void RegisterParamRef(const String& param_name,
- T* typed_param_ref_pointer) {
- typename T::Pointer param =
- GetOrCreateParam<typename T::ClassType>(param_name);
- LOG_ASSERT(param);
- *typed_param_ref_pointer = T(param);
- param_ref_helper_map_.insert(
- std::make_pair(param_name,
- new ParamRefHelper<T>(typed_param_ref_pointer)));
- }
-
- // Registers a pointer to a reference to a read only parameter. If the
- // parameter does not exist it will be created. The reference will be set to
- // refer to the parameter.
- // Parameters:
- // param_name: name of parameter
- // typed_param_ref_pointer: address of param ref
- template<typename T>
- void RegisterReadOnlyParamRef(const String& param_name,
- T* typed_param_ref_pointer) {
- RegisterParamRef<T>(param_name, typed_param_ref_pointer);
- (*typed_param_ref_pointer)->MarkAsReadOnly();
- }
-
- protected:
- // This is the concrete version of GetInputsForParam for a specific class. See
- // GetInputsForParam for details. You should override this function in your
- // derived class. You do not need to clear the inputs nor do you need to check
- // that Param is valid. That is handled in GetInputsForParam.
- //
- // Parameters:
- // param: Param to get inputs for.
- // inputs: ParamVector to append inputs.
- virtual void ConcreteGetInputsForParam(const Param* param,
- ParamVector* inputs) const;
-
- // This is the concrete version of GetOutputsForParam for a specific class.
- // See GetOutputsForParam for details. You should override this function in
- // your derived class. You do not need to clear the outputs nor do you need to
- // check that Param is valid. That is handled in GetOutputsForParam.
- //
- // Parameters:
- // param: Param to get inputs for.
- // outputs: ParamVector to append outputs.
- virtual void ConcreteGetOutputsForParam(const Param* param,
- ParamVector* outputs) const;
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // This class enables us to put multiple types of Params refs in the same
- // map.
- class ParamRefHelperBase {
- public:
- virtual ~ParamRefHelperBase() { } // Because we are a base class.
-
- // Gets overridden for each typedparam.
- virtual void UpdateParamRef(Param* param) = 0;
-
- // Returns whether this is a helper for the given Param.
- virtual bool IsParam(Param* param) const = 0;
- };
-
- // Template to generate concrete ParamRefHelper.
- // Parameters:
- // typed_param_ref_pointer: Pointer to reference to a param.
- template<typename T>
- class ParamRefHelper : public ParamRefHelperBase {
- public:
- explicit ParamRefHelper(T* typed_param_ref_pointer)
- : typed_param_ref_pointer_(typed_param_ref_pointer) {
- LOG_ASSERT(typed_param_ref_pointer);
- }
-
- // Attempt to update the ref to typed param to point to a new param. If the
- // param is the correct type the ref will be updated. If it is not the
- // correct type the ref will remain pointing to the old param.
- // Parameters:
- // param: Param to update references for.
- virtual void UpdateParamRef(Param* param) {
- if (param && param->IsA(T::ClassType::GetApparentClass())) {
- *typed_param_ref_pointer_ = T(down_cast<typename T::Pointer>(param));
- }
- }
-
- // Returns whether this is a helper for the given Param.
- virtual bool IsParam(Param* param) const {
- return param == *typed_param_ref_pointer_;
- }
-
- private:
- // Pointer to pointer to typed param.
- T* typed_param_ref_pointer_;
- };
-
- typedef std::multimap<String, ParamRefHelperBase*>
- ParamRefHelperMultiMap;
- typedef ParamRefHelperMultiMap::iterator ParamRefHelperMultiMapIterator;
- typedef std::pair<ParamRefHelperMultiMapIterator,
- ParamRefHelperMultiMapIterator> ParamRefHelperMultiMapRange;
-
- IClassManager* class_manager_;
-
- // Map of all the typed paramater pointers we are managing.
- ParamRefHelperMultiMap param_ref_helper_map_;
-
- NamedParamRefMap params_; // Stores Params defined on the ParamObject.
-
- // This is incremented every time a param is added or removed so other classes
- // can know when they need to update any pointers to params on this object
- // they may be holding.
- int change_count_;
-
- O3D_DECL_CLASS(ParamObject, NamedObject);
- DISALLOW_COPY_AND_ASSIGN(ParamObject);
-};
-
-// This template helps create Params whose values are set by the class that owns
-// them. For example Transform has a param, "worldMatrix", that is set by the
-// transform. When the Param's value is asked for it will call its master's
-// UpdateOutputs() function which it expects will update its value.
-template <typename ParamType, typename MasterType>
-class SlaveParam : public ParamType {
- public:
- // Overriden from Param.
- virtual void ComputeValue() {
- // TODO: Check here if we really need to call UpdateOutput.
- // The issue here is in param_object_test.cc is an example of a
- // ParamObject that has 2 outputs. Currently asking for the value
- // of either output will end up triggering a call to UpdateOutputs.
- // What we want to happen is if one or the other is called that
- // keep some kind of record in the ParamObject so that the next
- // call to UpdateOuputs is not called or is marked as invalid or
- // something like that. But, Currently, except for that example in
- // param_object_test.cc there are no ParamObjects that have more than 1
- // output.
- if (ParamType::input_connection()) {
- ParamType::ComputeValue();
- } else {
- master_->UpdateOutputs();
- }
- }
-
- static void RegisterParamRef(const String& param_name,
- typename ParamType::Ref* typed_param_ref_pointer,
- MasterType* master) {
- typename ParamType::Ref param = typename ParamType::Ref(new SlaveParam(
- master->service_locator(), master));
- master->AddParam(param_name, param);
- master->RegisterParamRef(param_name, typed_param_ref_pointer);
- }
- private:
- SlaveParam(ServiceLocator* service_locator, MasterType* master)
- : ParamType(service_locator, true, false),
- master_(master) {
- }
-
- MasterType* master_;
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_PARAM_OBJECT_H_
diff --git a/o3d/core/cross/param_object_test.cc b/o3d/core/cross/param_object_test.cc
deleted file mode 100644
index c302877..0000000
--- a/o3d/core/cross/param_object_test.cc
+++ /dev/null
@@ -1,489 +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 functionality of the ParamObject class
-
-#include <algorithm>
-#include "core/cross/param_object.h"
-#include "tests/common/win/testing_common.h"
-#include "core/cross/error.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-
-namespace o3d {
-
-// Test fixture for ParamObject testing. Creates a Client object
-// and a ParamObject before each test and deletes it after
-class ParamObjectTest : public testing::Test {
- protected:
-
- ParamObjectTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
- ParamObject* param_obj() { return param_obj_; }
-
- ServiceDependency<ObjectManager> object_manager_;
-
- private:
- Pack* pack_;
- ParamObject* param_obj_;
-};
-
-void ParamObjectTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-
- param_obj_ = pack()->Create<Transform>();
-}
-
-void ParamObjectTest::TearDown() {
- pack_->Destroy();
-}
-
-namespace {
-
-class FakeParam : public Param {
- public:
- explicit FakeParam(ServiceLocator* service_locator)
- : Param(service_locator, false, false) {
- }
-
- virtual void CopyDataFromParam(Param* source_param) {
- // Do nothing. We are fake.
- }
-};
-
-class FakeDivModParamOperation : public ParamObject {
- public:
- typedef SmartPointer<FakeDivModParamOperation> Ref;
-
- static const char* kInput1Name;
- static const char* kInput2Name;
- static const char* kOutput1Name;
- static const char* kOutput2Name;
-
- explicit FakeDivModParamOperation(ServiceLocator* service_locator);
-
- void UpdateOutputs();
-
- int input1() const {
- return input1_param_->value();
- }
-
- void set_input1(int value) {
- input1_param_->set_value(value);
- }
-
- int input2() const {
- return input2_param_->value();
- }
-
- void set_input2(int value) {
- input2_param_->set_value(value);
- }
-
- int output1() const {
- return output1_param_->value();
- }
-
- int output2() const {
- return output2_param_->value();
- }
-
- unsigned NumberOfCallsToUpdateOutputs() const {
- return update_outputs_call_count_;
- }
-
- protected:
- // Overridden from ParamObject
- // For the given Param, returns all the inputs that affect that param through
- // this ParamObject.
- virtual void ConcreteGetInputsForParam(const Param* param,
- ParamVector* inputs) const;
-
- // Overridden from ParamObject
- // For the given Param, returns all the outputs that the given param will
- // affect through this ParamObject.
- virtual void ConcreteGetOutputsForParam(const Param* param,
- ParamVector* outputs) const;
-
- private:
- typedef SlaveParam<ParamInteger, FakeDivModParamOperation> SlaveParamInteger;
-
- ParamInteger::Ref input1_param_;
- ParamInteger::Ref input2_param_;
- SlaveParamInteger::Ref output1_param_;
- SlaveParamInteger::Ref output2_param_;
-
- unsigned update_outputs_call_count_;
-
- O3D_DECL_CLASS(FakeDivModParamOperation, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(FakeDivModParamOperation);
-};
-
-O3D_DEFN_CLASS(FakeDivModParamOperation, ParamObject);
-
-const char* FakeDivModParamOperation::kInput1Name = "input1";
-const char* FakeDivModParamOperation::kInput2Name = "input2";
-const char* FakeDivModParamOperation::kOutput1Name = "output1";
-const char* FakeDivModParamOperation::kOutput2Name = "output2";
-
-FakeDivModParamOperation::FakeDivModParamOperation(
- ServiceLocator* service_locator)
- : ParamObject(service_locator),
- update_outputs_call_count_(0) {
- RegisterParamRef(kInput1Name, &input1_param_);
- RegisterParamRef(kInput2Name, &input2_param_);
- SlaveParamInteger::RegisterParamRef(kOutput1Name, &output1_param_, this);
- SlaveParamInteger::RegisterParamRef(kOutput2Name, &output2_param_, this);
-}
-
-void FakeDivModParamOperation::ConcreteGetInputsForParam(
- const Param* param,
- ParamVector* inputs) const {
- if ((param == output1_param_ &&
- output1_param_->input_connection() == NULL) ||
- (param == output2_param_ &&
- output2_param_->input_connection() == NULL)) {
- inputs->push_back(input1_param_);
- inputs->push_back(input2_param_);
- }
-}
-
-void FakeDivModParamOperation::ConcreteGetOutputsForParam(
- const Param* param,
- ParamVector* outputs) const {
- if (param == input1_param_ || param == input2_param_) {
- if (output1_param_->input_connection() == NULL) {
- outputs->push_back(output1_param_);
- }
- if (output2_param_->input_connection() == NULL) {
- outputs->push_back(output2_param_);
- }
- }
-}
-
-void FakeDivModParamOperation::UpdateOutputs() {
- ++update_outputs_call_count_;
-
- int input1 = input1_param_->value();
- int input2 = input2_param_->value();
-
- if (input2 != 0) {
- output1_param_->set_dynamic_value(input1 / input2);
- output2_param_->set_dynamic_value(input1 % input2);
- } else {
- O3D_ERROR(g_service_locator) << "divide by zero in '" << name() << "'";
- }
-}
-
-// Check if a param is in the given param array
-// Parameters:
-// param: param to search for.
-// params: ParamVector to search.
-// Returns:
-// true if param is in params.
-bool ParamInParams(Param* param, const ParamVector& params) {
- return std::find(params.begin(), params.end(), param) != params.end();
-}
-
-} // anonymous namespace
-
-// Test ParamObject::AddParam().
-TEST_F(ParamObjectTest, AddParam) {
- using o3d::NamedParamRefMap;
-
- Param* param = new FakeParam(g_service_locator);
- Param* param2 = new FakeParam(g_service_locator);
- param_obj()->AddParam("param", param);
-
- // Make sure the param ends up in the Param obj's Param Map.
- const NamedParamRefMap& param_map = param_obj()->params();
- NamedParamRefMap::const_iterator pos = param_map.find("param");
- EXPECT_TRUE(pos != param_map.end());
-
- // Make sure the param ends up in the client as well.
- EXPECT_TRUE(object_manager_->GetById<Param>(param->id()) == param);
-
- // Make sure if we add another of the same name it fails.
- EXPECT_FALSE(param_obj()->AddParam("param", param2));
-
- // Make sure the old param was uneffected.
- pos = param_map.find("param");
- EXPECT_TRUE(pos != param_map.end());
- EXPECT_EQ(param, param_obj()->GetUntypedParam("param"));
-
- // Note: Param is owned by the ParamObject now so we don't delete it here.
-}
-
-// Test ParamObject::RemoveParam().
-TEST_F(ParamObjectTest, RemoveParam) {
- Param::Ref param(param_obj()->CreateParam<ParamFloat>("param"));
- ASSERT_FALSE(param.IsNull());
-
- // Should be able to remove it
- EXPECT_TRUE(param_obj()->RemoveParam(param));
- // Should not be able to remove it twice.
- EXPECT_FALSE(param_obj()->RemoveParam(param));
-}
-
-// Test ParamObject::CreateParam().
-TEST_F(ParamObjectTest, CreateParam) {
- using o3d::NamedParamRefMap;
-
- Param *param = param_obj()->CreateParam<ParamFloat>("param");
-
- // Make sure the param ends up in the Param obj's Param Map.
- NamedParamRefMap param_map = param_obj()->params();
- NamedParamRefMap::const_iterator pos = param_map.find("param");
- EXPECT_TRUE(pos != param_map.end());
-
- // Make sure the param ends up in the client as well.
- EXPECT_TRUE(object_manager_->GetById<Param>(param->id()) == param);
-
- // Note: Param is owned by the ParamObject now so we don't delete it here.
-}
-
-// Test ParamObject::CreateParam().
-TEST_F(ParamObjectTest, GetOrCreateParam) {
- using o3d::NamedParamRefMap;
-
- Param *param = param_obj()->GetOrCreateParam<ParamMatrix4>("param1");
-
- EXPECT_TRUE(param != NULL);
- EXPECT_EQ(ParamMatrix4::GetApparentClass(), param->GetClass());
- EXPECT_EQ("param1", param->name());
- size_t size = param_obj()->params().size();
-
- // Create an already-existing param, check that it returns the same one and
- // doesn't add anything else to the node.
- Param *param2 = param_obj()->GetOrCreateParam<ParamMatrix4>("param1");
- EXPECT_EQ(param, param2);
- EXPECT_EQ(size, param_obj()->params().size());
- EXPECT_EQ(param2, param_obj()->GetUntypedParam("param1"));
-
- // Note: Param is owned by the ParamObject now so we don't delete it here.
-}
-
-// Tests GetInputsForParam and GetOutputsForParam
-TEST_F(ParamObjectTest, GetInputsForParamGetOutputsForParam) {
- FakeDivModParamOperation::Ref operation = FakeDivModParamOperation::Ref(
- new FakeDivModParamOperation(g_service_locator));
- ASSERT_FALSE(operation.IsNull());
-
- // Verify that FakeDivModParamOperationWorks.
- operation->set_input1(19);
- operation->set_input2(5);
- EXPECT_EQ(operation->NumberOfCallsToUpdateOutputs(), 0U);
- EXPECT_EQ(operation->output1(), 3);
- EXPECT_EQ(operation->NumberOfCallsToUpdateOutputs(), 1U);
- EXPECT_EQ(operation->output2(), 4);
- // This should be 1 because calling operation->output1() should
- // have updated output2().
- EXPECT_EQ(operation->NumberOfCallsToUpdateOutputs(), 1U);
-
- // Now check GetInputs
- Param* input1 = operation->GetUntypedParam(
- FakeDivModParamOperation::kInput1Name);
- Param* input2 = operation->GetUntypedParam(
- FakeDivModParamOperation::kInput2Name);
- Param* output1 = operation->GetUntypedParam(
- FakeDivModParamOperation::kOutput1Name);
- Param* output2 = operation->GetUntypedParam(
- FakeDivModParamOperation::kOutput2Name);
- ASSERT_TRUE(input1 != NULL);
- ASSERT_TRUE(input2 != NULL);
- ASSERT_TRUE(output1 != NULL);
- ASSERT_TRUE(output2 != NULL);
-
- ParamVector params;
- // There should be no params on the params
- operation->GetInputsForParam(input1, &params);
- EXPECT_EQ(params.size(), 0U);
- operation->GetInputsForParam(input2, &params);
- EXPECT_EQ(params.size(), 0U);
- // There should be two params for each output.
- operation->GetInputsForParam(output1, &params);
- EXPECT_EQ(params.size(), 2U);
- EXPECT_TRUE(ParamInParams(input1, params));
- EXPECT_TRUE(ParamInParams(input2, params));
- params.clear(); // make sure we are not just getting the same result.
- operation->GetInputsForParam(output2, &params);
- EXPECT_EQ(params.size(), 2U);
- EXPECT_TRUE(ParamInParams(input1, params));
- EXPECT_TRUE(ParamInParams(input2, params));
- // Make sure we don't just add more params.
- operation->GetInputsForParam(output2, &params);
- EXPECT_EQ(params.size(), 2U);
-
- // Check GetOutputs
- operation->GetOutputsForParam(input1, &params);
- EXPECT_EQ(params.size(), 2U);
- EXPECT_TRUE(ParamInParams(output1, params));
- EXPECT_TRUE(ParamInParams(output2, params));
- operation->GetOutputsForParam(input2, &params);
- EXPECT_EQ(params.size(), 2U);
- EXPECT_TRUE(ParamInParams(output1, params));
- EXPECT_TRUE(ParamInParams(output2, params));
- operation->GetOutputsForParam(output1, &params);
- EXPECT_EQ(params.size(), 0U);
- operation->GetOutputsForParam(output2, &params);
- EXPECT_EQ(params.size(), 0U);
-
- // If we bind the output we should not get it as an input or an output.
- Param* other = operation->CreateParam<ParamInteger>("other");
- ASSERT_TRUE(other != NULL);
- ASSERT_TRUE(output2->Bind(other));
-
- // There should be two inputs for output1 but none for output2 since it is
- // bound.
- operation->GetInputsForParam(output1, &params);
- EXPECT_EQ(params.size(), 2U);
- operation->GetInputsForParam(output2, &params);
- EXPECT_EQ(params.size(), 0U);
-
- // There should only be 1 output for each of the inputs since output2 is
- // no longer effected by the inputs.
- operation->GetOutputsForParam(input1, &params);
- EXPECT_EQ(params.size(), 1U);
- EXPECT_TRUE(ParamInParams(output1, params));
- operation->GetOutputsForParam(input2, &params);
- EXPECT_EQ(params.size(), 1U);
- EXPECT_TRUE(ParamInParams(output1, params));
-}
-
-// Tests Implicit Cycles
-TEST_F(ParamObjectTest, ImplicitCycles) {
- FakeDivModParamOperation::Ref operation_a = FakeDivModParamOperation::Ref(
- new FakeDivModParamOperation(g_service_locator));
- FakeDivModParamOperation::Ref operation_b = FakeDivModParamOperation::Ref(
- new FakeDivModParamOperation(g_service_locator));
- ASSERT_FALSE(operation_a.IsNull());
- ASSERT_FALSE(operation_b.IsNull());
-
- // Now check GetInputs
- Param* input_a_1 = operation_a->GetUntypedParam(
- FakeDivModParamOperation::kInput1Name);
- Param* input_a_2 = operation_a->GetUntypedParam(
- FakeDivModParamOperation::kInput2Name);
- Param* output_a_1 = operation_a->GetUntypedParam(
- FakeDivModParamOperation::kOutput1Name);
- Param* output_a_2 = operation_a->GetUntypedParam(
- FakeDivModParamOperation::kOutput2Name);
-
- Param* input_b_1 = operation_b->GetUntypedParam(
- FakeDivModParamOperation::kInput1Name);
- Param* input_b_2 = operation_b->GetUntypedParam(
- FakeDivModParamOperation::kInput2Name);
- Param* output_b_1 = operation_b->GetUntypedParam(
- FakeDivModParamOperation::kOutput1Name);
- Param* output_b_2 = operation_b->GetUntypedParam(
- FakeDivModParamOperation::kOutput2Name);
-
- ASSERT_TRUE(input_a_1 != NULL);
- ASSERT_TRUE(input_a_2 != NULL);
- ASSERT_TRUE(output_a_1 != NULL);
- ASSERT_TRUE(output_a_2 != NULL);
-
- ASSERT_TRUE(input_b_1 != NULL);
- ASSERT_TRUE(input_b_2 != NULL);
- ASSERT_TRUE(output_b_1 != NULL);
- ASSERT_TRUE(output_b_2 != NULL);
-
- ParamVector params;
- // Test with cycle in operation 2
- EXPECT_TRUE(input_b_1->Bind(output_a_1));
- EXPECT_TRUE(input_b_2->Bind(output_b_1));
-
- // IA1 OA1--->IB1 OB1--+
- // [OPA] [OPB] |
- // IA2 OA2 +->IB2 OB2 |
- // | |
- // +-------------+
-
- input_a_1->GetOutputs(&params);
- EXPECT_EQ(params.size(), 6U);
- EXPECT_TRUE(ParamInParams(output_a_1, params));
- EXPECT_TRUE(ParamInParams(output_a_2, params));
- EXPECT_TRUE(ParamInParams(output_b_1, params));
- EXPECT_TRUE(ParamInParams(output_b_2, params));
- EXPECT_TRUE(ParamInParams(input_b_1, params));
- EXPECT_TRUE(ParamInParams(input_b_2, params));
-
- // Test with cycle in operation 1
- output_b_1->UnbindInput();
- input_a_1->Bind(output_a_1);
-
- // +------------+
- // | |
- // +->IA1 OA1-+->IB1 OB1
- // [OPA] [OPB]
- // IA2 OA2 IB2 OB2
-
- output_b_1->GetInputs(&params);
- EXPECT_EQ(params.size(), 5U);
- EXPECT_TRUE(ParamInParams(input_a_1, params));
- EXPECT_TRUE(ParamInParams(input_a_2, params));
- EXPECT_TRUE(ParamInParams(input_b_1, params));
- EXPECT_TRUE(ParamInParams(input_b_2, params));
- EXPECT_TRUE(ParamInParams(output_a_1, params));
-}
-
-TEST_F(ParamObjectTest,
- ParametersRegisteredAtConstructionTimeAreNotRegardedAsAdded) {
- FakeDivModParamOperation::Ref operation = FakeDivModParamOperation::Ref(
- new FakeDivModParamOperation(g_service_locator));
- Param* input1 = operation->GetUntypedParam(
- FakeDivModParamOperation::kInput1Name);
- EXPECT_FALSE(operation->IsAddedParam(input1));
-}
-
-TEST_F(ParamObjectTest, ParametersAfterConstructionTimeAreRegardedAsAdded) {
- FakeDivModParamOperation::Ref operation = FakeDivModParamOperation::Ref(
- new FakeDivModParamOperation(g_service_locator));
- ParamFloat* param = operation->CreateParam<ParamFloat>("param");
- EXPECT_TRUE(operation->IsAddedParam(param));
-}
-
-TEST_F(ParamObjectTest, ParametersOwnedByOtherObjectsAreNotRegardedAsAdded) {
- FakeDivModParamOperation::Ref operation1 = FakeDivModParamOperation::Ref(
- new FakeDivModParamOperation(g_service_locator));
- ParamFloat* param = operation1->CreateParam<ParamFloat>("param");
- FakeDivModParamOperation::Ref operation2 = FakeDivModParamOperation::Ref(
- new FakeDivModParamOperation(g_service_locator));
- EXPECT_FALSE(operation2->IsAddedParam(param));
-}
-} // namespace o3d
diff --git a/o3d/core/cross/param_operation.cc b/o3d/core/cross/param_operation.cc
deleted file mode 100644
index d4ed08f..0000000
--- a/o3d/core/cross/param_operation.cc
+++ /dev/null
@@ -1,294 +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 various Parameter Operations.
-
-#include "core/cross/param_operation.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(ParamOp2FloatsToFloat2, ParamObject);
-O3D_DEFN_CLASS(ParamOp3FloatsToFloat3, ParamObject);
-O3D_DEFN_CLASS(ParamOp4FloatsToFloat4, ParamObject);
-O3D_DEFN_CLASS(ParamOp16FloatsToMatrix4, ParamObject);
-O3D_DEFN_CLASS(TRSToMatrix4, ParamObject);
-
-const char* ParamOp2FloatsToFloat2::kInput0ParamName =
- O3D_STRING_CONSTANT("input0");
-const char* ParamOp2FloatsToFloat2::kInput1ParamName =
- O3D_STRING_CONSTANT("input1");
-const char* ParamOp2FloatsToFloat2::kOutputParamName =
- O3D_STRING_CONSTANT("output");
-
-ParamOp2FloatsToFloat2::ParamOp2FloatsToFloat2(ServiceLocator* service_locator)
- : ParamObject(service_locator) {
- RegisterParamRef(kInput0ParamName, &input_0_param_);
- RegisterParamRef(kInput1ParamName, &input_1_param_);
- SlaveParamFloat2::RegisterParamRef(kOutputParamName,
- &output_param_,
- this);
-}
-
-void ParamOp2FloatsToFloat2::UpdateOutputs() {
- if (output_param_->input_connection() == NULL) {
- output_param_->set_dynamic_value(Float2(input_0_param_->value(),
- input_1_param_->value()));
- }
-}
-
-ObjectBase::Ref ParamOp2FloatsToFloat2::Create(
- ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamOp2FloatsToFloat2(service_locator));
-}
-
-const char* ParamOp3FloatsToFloat3::kInput0ParamName =
- O3D_STRING_CONSTANT("input0");
-const char* ParamOp3FloatsToFloat3::kInput1ParamName =
- O3D_STRING_CONSTANT("input1");
-const char* ParamOp3FloatsToFloat3::kInput2ParamName =
- O3D_STRING_CONSTANT("input2");
-const char* ParamOp3FloatsToFloat3::kOutputParamName =
- O3D_STRING_CONSTANT("output");
-
-ParamOp3FloatsToFloat3::ParamOp3FloatsToFloat3(ServiceLocator* service_locator)
- : ParamObject(service_locator) {
- RegisterParamRef(kInput0ParamName, &input_0_param_);
- RegisterParamRef(kInput1ParamName, &input_1_param_);
- RegisterParamRef(kInput2ParamName, &input_2_param_);
- SlaveParamFloat3::RegisterParamRef(kOutputParamName,
- &output_param_,
- this);
-}
-
-void ParamOp3FloatsToFloat3::UpdateOutputs() {
- if (output_param_->input_connection() == NULL) {
- output_param_->set_dynamic_value(Float3(input_0_param_->value(),
- input_1_param_->value(),
- input_2_param_->value()));
- }
-}
-
-ObjectBase::Ref ParamOp3FloatsToFloat3::Create(
- ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamOp3FloatsToFloat3(service_locator));
-}
-
-const char* ParamOp4FloatsToFloat4::kInput0ParamName =
- O3D_STRING_CONSTANT("input0");
-const char* ParamOp4FloatsToFloat4::kInput1ParamName =
- O3D_STRING_CONSTANT("input1");
-const char* ParamOp4FloatsToFloat4::kInput2ParamName =
- O3D_STRING_CONSTANT("input2");
-const char* ParamOp4FloatsToFloat4::kInput3ParamName =
- O3D_STRING_CONSTANT("input3");
-const char* ParamOp4FloatsToFloat4::kOutputParamName =
- O3D_STRING_CONSTANT("output");
-
-ParamOp4FloatsToFloat4::ParamOp4FloatsToFloat4(ServiceLocator* service_locator)
- : ParamObject(service_locator) {
- RegisterParamRef(kInput0ParamName, &input_0_param_);
- RegisterParamRef(kInput1ParamName, &input_1_param_);
- RegisterParamRef(kInput2ParamName, &input_2_param_);
- RegisterParamRef(kInput3ParamName, &input_3_param_);
- SlaveParamFloat4::RegisterParamRef(kOutputParamName,
- &output_param_,
- this);
-}
-
-void ParamOp4FloatsToFloat4::UpdateOutputs() {
- if (output_param_->input_connection() == NULL) {
- output_param_->set_dynamic_value(Float4(input_0_param_->value(),
- input_1_param_->value(),
- input_2_param_->value(),
- input_3_param_->value()));
- }
-}
-
-ObjectBase::Ref ParamOp4FloatsToFloat4::Create(
- ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamOp4FloatsToFloat4(service_locator));
-}
-
-const char* ParamOp16FloatsToMatrix4::kInput0ParamName =
- O3D_STRING_CONSTANT("input0");
-const char* ParamOp16FloatsToMatrix4::kInput1ParamName =
- O3D_STRING_CONSTANT("input1");
-const char* ParamOp16FloatsToMatrix4::kInput2ParamName =
- O3D_STRING_CONSTANT("input2");
-const char* ParamOp16FloatsToMatrix4::kInput3ParamName =
- O3D_STRING_CONSTANT("input3");
-const char* ParamOp16FloatsToMatrix4::kInput4ParamName =
- O3D_STRING_CONSTANT("input4");
-const char* ParamOp16FloatsToMatrix4::kInput5ParamName =
- O3D_STRING_CONSTANT("input5");
-const char* ParamOp16FloatsToMatrix4::kInput6ParamName =
- O3D_STRING_CONSTANT("input6");
-const char* ParamOp16FloatsToMatrix4::kInput7ParamName =
- O3D_STRING_CONSTANT("input7");
-const char* ParamOp16FloatsToMatrix4::kInput8ParamName =
- O3D_STRING_CONSTANT("input8");
-const char* ParamOp16FloatsToMatrix4::kInput9ParamName =
- O3D_STRING_CONSTANT("input9");
-const char* ParamOp16FloatsToMatrix4::kInput10ParamName =
- O3D_STRING_CONSTANT("input10");
-const char* ParamOp16FloatsToMatrix4::kInput11ParamName =
- O3D_STRING_CONSTANT("input11");
-const char* ParamOp16FloatsToMatrix4::kInput12ParamName =
- O3D_STRING_CONSTANT("input12");
-const char* ParamOp16FloatsToMatrix4::kInput13ParamName =
- O3D_STRING_CONSTANT("input13");
-const char* ParamOp16FloatsToMatrix4::kInput14ParamName =
- O3D_STRING_CONSTANT("input14");
-const char* ParamOp16FloatsToMatrix4::kInput15ParamName =
- O3D_STRING_CONSTANT("input15");
-const char* ParamOp16FloatsToMatrix4::kOutputParamName =
- O3D_STRING_CONSTANT("output");
-
-ParamOp16FloatsToMatrix4::ParamOp16FloatsToMatrix4(
- ServiceLocator* service_locator)
- : ParamObject(service_locator) {
- RegisterParamRef(kInput0ParamName, &input_0_param_);
- RegisterParamRef(kInput1ParamName, &input_1_param_);
- RegisterParamRef(kInput2ParamName, &input_2_param_);
- RegisterParamRef(kInput3ParamName, &input_3_param_);
- RegisterParamRef(kInput4ParamName, &input_4_param_);
- RegisterParamRef(kInput5ParamName, &input_5_param_);
- RegisterParamRef(kInput6ParamName, &input_6_param_);
- RegisterParamRef(kInput7ParamName, &input_7_param_);
- RegisterParamRef(kInput8ParamName, &input_8_param_);
- RegisterParamRef(kInput9ParamName, &input_9_param_);
- RegisterParamRef(kInput10ParamName, &input_10_param_);
- RegisterParamRef(kInput11ParamName, &input_11_param_);
- RegisterParamRef(kInput12ParamName, &input_12_param_);
- RegisterParamRef(kInput13ParamName, &input_13_param_);
- RegisterParamRef(kInput14ParamName, &input_14_param_);
- RegisterParamRef(kInput15ParamName, &input_15_param_);
- SlaveParamMatrix4::RegisterParamRef(kOutputParamName,
- &output_param_,
- this);
- // Make it the identity matrix by default.
- set_input_0(1.0f);
- set_input_5(1.0f);
- set_input_10(1.0f);
- set_input_15(1.0f);
-}
-
-void ParamOp16FloatsToMatrix4::UpdateOutputs() {
- if (output_param_->input_connection() == NULL) {
- output_param_->set_dynamic_value(
- Matrix4(Vector4(input_0_param_->value(),
- input_1_param_->value(),
- input_2_param_->value(),
- input_3_param_->value()),
- Vector4(input_4_param_->value(),
- input_5_param_->value(),
- input_6_param_->value(),
- input_7_param_->value()),
- Vector4(input_8_param_->value(),
- input_9_param_->value(),
- input_10_param_->value(),
- input_11_param_->value()),
- Vector4(input_12_param_->value(),
- input_13_param_->value(),
- input_14_param_->value(),
- input_15_param_->value())));
- }
-}
-
-ObjectBase::Ref ParamOp16FloatsToMatrix4::Create(
- ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamOp16FloatsToMatrix4(service_locator));
-}
-
-const char* TRSToMatrix4::kTranslateXParamName =
- O3D_STRING_CONSTANT("translateX");
-const char* TRSToMatrix4::kTranslateYParamName =
- O3D_STRING_CONSTANT("translateY");
-const char* TRSToMatrix4::kTranslateZParamName =
- O3D_STRING_CONSTANT("translateZ");
-const char* TRSToMatrix4::kRotateXParamName =
- O3D_STRING_CONSTANT("rotateX");
-const char* TRSToMatrix4::kRotateYParamName =
- O3D_STRING_CONSTANT("rotateY");
-const char* TRSToMatrix4::kRotateZParamName =
- O3D_STRING_CONSTANT("rotateZ");
-const char* TRSToMatrix4::kScaleXParamName =
- O3D_STRING_CONSTANT("scaleX");
-const char* TRSToMatrix4::kScaleYParamName =
- O3D_STRING_CONSTANT("scaleY");
-const char* TRSToMatrix4::kScaleZParamName =
- O3D_STRING_CONSTANT("scaleZ");
-const char* TRSToMatrix4::kOutputParamName =
- O3D_STRING_CONSTANT("output");
-
-TRSToMatrix4::TRSToMatrix4(ServiceLocator* service_locator)
- : ParamObject(service_locator) {
- RegisterParamRef(kTranslateXParamName, &translate_x_param_);
- RegisterParamRef(kTranslateYParamName, &translate_y_param_);
- RegisterParamRef(kTranslateZParamName, &translate_z_param_);
- RegisterParamRef(kRotateXParamName, &rotate_x_param_);
- RegisterParamRef(kRotateYParamName, &rotate_y_param_);
- RegisterParamRef(kRotateZParamName, &rotate_z_param_);
- RegisterParamRef(kScaleXParamName, &scale_x_param_);
- RegisterParamRef(kScaleYParamName, &scale_y_param_);
- RegisterParamRef(kScaleZParamName, &scale_z_param_);
- SlaveParamMatrix4::RegisterParamRef(kOutputParamName,
- &output_param_,
- this);
- // Make it the identity matrix by default.
- set_scale_x(1.0f);
- set_scale_y(1.0f);
- set_scale_z(1.0f);
-}
-
-void TRSToMatrix4::UpdateOutputs() {
- if (output_param_->input_connection() == NULL) {
- output_param_->set_dynamic_value(
- Matrix4::translation(Vector3(translate_x_param_->value(),
- translate_y_param_->value(),
- translate_z_param_->value())) *
- Matrix4::rotationZYX(Vector3(rotate_x_param_->value(),
- rotate_y_param_->value(),
- rotate_z_param_->value())) *
- Matrix4::scale(Vector3(scale_x_param_->value(),
- scale_y_param_->value(),
- scale_z_param_->value())));
- }
-}
-
-ObjectBase::Ref TRSToMatrix4::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new TRSToMatrix4(service_locator));
-}
-
-} // namespace o3d
-
-
diff --git a/o3d/core/cross/param_operation.h b/o3d/core/cross/param_operation.h
deleted file mode 100644
index f026421..0000000
--- a/o3d/core/cross/param_operation.h
+++ /dev/null
@@ -1,523 +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 declaration of various Parameter Operations.
-
-#ifndef O3D_CORE_CROSS_PARAM_OPERATION_H_
-#define O3D_CORE_CROSS_PARAM_OPERATION_H_
-
-#include "core/cross/param_object.h"
-
-namespace o3d {
-
-// A Param operation that takes 2 floats to produce a Float2.
-class ParamOp2FloatsToFloat2 : public ParamObject {
- public:
- static const char* kInput0ParamName;
- static const char* kInput1ParamName;
- static const char* kOutputParamName;
-
- float input_0() const {
- return input_0_param_->value();
- }
-
- void set_input_0(float value) {
- input_0_param_->set_value(value);
- }
-
- float input_1() const {
- return input_1_param_->value();
- }
-
- void set_input_1(float value) {
- input_1_param_->set_value(value);
- }
-
- Float2 output() const {
- return output_param_->value();
- }
-
- // Updates the output param.
- void UpdateOutputs();
-
- private:
- typedef SlaveParam<ParamFloat2, ParamOp2FloatsToFloat2> SlaveParamFloat2;
-
- explicit ParamOp2FloatsToFloat2(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamFloat::Ref input_0_param_;
- ParamFloat::Ref input_1_param_;
- SlaveParamFloat2::Ref output_param_;
-
- O3D_DECL_CLASS(ParamOp2FloatsToFloat2, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(ParamOp2FloatsToFloat2);
-};
-
-// A Param operation that takes 3 floats to produce a Float3.
-class ParamOp3FloatsToFloat3 : public ParamObject {
- public:
- static const char* kInput0ParamName;
- static const char* kInput1ParamName;
- static const char* kInput2ParamName;
- static const char* kOutputParamName;
-
- float input_0() const {
- return input_0_param_->value();
- }
-
- void set_input_0(float value) {
- input_0_param_->set_value(value);
- }
-
- float input_1() const {
- return input_1_param_->value();
- }
-
- void set_input_1(float value) {
- input_1_param_->set_value(value);
- }
-
- float input_2() const {
- return input_2_param_->value();
- }
-
- void set_input_2(float value) {
- input_2_param_->set_value(value);
- }
-
- Float3 output() const {
- return output_param_->value();
- }
-
- // Updates the output param.
- void UpdateOutputs();
-
- private:
- typedef SlaveParam<ParamFloat3, ParamOp3FloatsToFloat3> SlaveParamFloat3;
-
- explicit ParamOp3FloatsToFloat3(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamFloat::Ref input_0_param_;
- ParamFloat::Ref input_1_param_;
- ParamFloat::Ref input_2_param_;
- SlaveParamFloat3::Ref output_param_;
-
- O3D_DECL_CLASS(ParamOp3FloatsToFloat3, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(ParamOp3FloatsToFloat3);
-};
-
-// A Param operation that takes 4 floats to produce a Float4.
-class ParamOp4FloatsToFloat4 : public ParamObject {
- public:
- static const char* kInput0ParamName;
- static const char* kInput1ParamName;
- static const char* kInput2ParamName;
- static const char* kInput3ParamName;
- static const char* kOutputParamName;
-
- float input_0() const {
- return input_0_param_->value();
- }
-
- void set_input_0(float value) {
- input_0_param_->set_value(value);
- }
-
- float input_1() const {
- return input_1_param_->value();
- }
-
- void set_input_1(float value) {
- input_1_param_->set_value(value);
- }
-
- float input_2() const {
- return input_2_param_->value();
- }
-
- void set_input_2(float value) {
- input_2_param_->set_value(value);
- }
-
- float input_3() const {
- return input_3_param_->value();
- }
-
- void set_input_3(float value) {
- input_3_param_->set_value(value);
- }
-
- Float4 output() const {
- return output_param_->value();
- }
-
- // Updates the output param.
- void UpdateOutputs();
-
- private:
- typedef SlaveParam<ParamFloat4, ParamOp4FloatsToFloat4> SlaveParamFloat4;
-
- explicit ParamOp4FloatsToFloat4(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamFloat::Ref input_0_param_;
- ParamFloat::Ref input_1_param_;
- ParamFloat::Ref input_2_param_;
- ParamFloat::Ref input_3_param_;
- SlaveParamFloat4::Ref output_param_;
-
- O3D_DECL_CLASS(ParamOp4FloatsToFloat4, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(ParamOp4FloatsToFloat4);
-};
-
-// A Param operation that takes 16 floats to produce a Matrix4.
-class ParamOp16FloatsToMatrix4 : public ParamObject {
- public:
- static const char* kInput0ParamName;
- static const char* kInput1ParamName;
- static const char* kInput2ParamName;
- static const char* kInput3ParamName;
- static const char* kInput4ParamName;
- static const char* kInput5ParamName;
- static const char* kInput6ParamName;
- static const char* kInput7ParamName;
- static const char* kInput8ParamName;
- static const char* kInput9ParamName;
- static const char* kInput10ParamName;
- static const char* kInput11ParamName;
- static const char* kInput12ParamName;
- static const char* kInput13ParamName;
- static const char* kInput14ParamName;
- static const char* kInput15ParamName;
- static const char* kOutputParamName;
-
- float input_0() const {
- return input_0_param_->value();
- }
-
- void set_input_0(float value) {
- input_0_param_->set_value(value);
- }
-
- float input_1() const {
- return input_1_param_->value();
- }
-
- void set_input_1(float value) {
- input_1_param_->set_value(value);
- }
-
- float input_2() const {
- return input_2_param_->value();
- }
-
- void set_input_2(float value) {
- input_2_param_->set_value(value);
- }
-
- float input_3() const {
- return input_3_param_->value();
- }
-
- void set_input_3(float value) {
- input_3_param_->set_value(value);
- }
-
- float input_4() const {
- return input_4_param_->value();
- }
-
- void set_input_4(float value) {
- input_4_param_->set_value(value);
- }
-
- float input_5() const {
- return input_5_param_->value();
- }
-
- void set_input_5(float value) {
- input_5_param_->set_value(value);
- }
-
- float input_6() const {
- return input_6_param_->value();
- }
-
- void set_input_6(float value) {
- input_6_param_->set_value(value);
- }
-
- float input_7() const {
- return input_7_param_->value();
- }
-
- void set_input_7(float value) {
- input_7_param_->set_value(value);
- }
-
- float input_8() const {
- return input_8_param_->value();
- }
-
- void set_input_8(float value) {
- input_8_param_->set_value(value);
- }
-
- float input_9() const {
- return input_9_param_->value();
- }
-
- void set_input_9(float value) {
- input_9_param_->set_value(value);
- }
-
- float input_10() const {
- return input_10_param_->value();
- }
-
- void set_input_10(float value) {
- input_10_param_->set_value(value);
- }
-
- float input_11() const {
- return input_11_param_->value();
- }
-
- void set_input_11(float value) {
- input_11_param_->set_value(value);
- }
-
- float input_12() const {
- return input_12_param_->value();
- }
-
- void set_input_12(float value) {
- input_12_param_->set_value(value);
- }
-
- float input_13() const {
- return input_13_param_->value();
- }
-
- void set_input_13(float value) {
- input_13_param_->set_value(value);
- }
-
- float input_14() const {
- return input_14_param_->value();
- }
-
- void set_input_14(float value) {
- input_14_param_->set_value(value);
- }
-
- float input_15() const {
- return input_15_param_->value();
- }
-
- void set_input_15(float value) {
- input_15_param_->set_value(value);
- }
-
- Matrix4 output() const {
- return output_param_->value();
- }
-
- // Updates the output param.
- void UpdateOutputs();
-
- private:
- typedef SlaveParam<ParamMatrix4, ParamOp16FloatsToMatrix4> SlaveParamMatrix4;
-
- explicit ParamOp16FloatsToMatrix4(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamFloat::Ref input_0_param_;
- ParamFloat::Ref input_1_param_;
- ParamFloat::Ref input_2_param_;
- ParamFloat::Ref input_3_param_;
- ParamFloat::Ref input_4_param_;
- ParamFloat::Ref input_5_param_;
- ParamFloat::Ref input_6_param_;
- ParamFloat::Ref input_7_param_;
- ParamFloat::Ref input_8_param_;
- ParamFloat::Ref input_9_param_;
- ParamFloat::Ref input_10_param_;
- ParamFloat::Ref input_11_param_;
- ParamFloat::Ref input_12_param_;
- ParamFloat::Ref input_13_param_;
- ParamFloat::Ref input_14_param_;
- ParamFloat::Ref input_15_param_;
- SlaveParamMatrix4::Ref output_param_;
-
- O3D_DECL_CLASS(ParamOp16FloatsToMatrix4, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(ParamOp16FloatsToMatrix4);
-};
-
-// A Param operation that takes 9 floats to produce a Matrix4.
-// It is effectively this:
-//
-// output = Matrix4::translation(translateX, translateY, translateZ) *
-// Matrix4::rotationXYZ(rotateX, rotateY, rotateZ) *
-// Matrix4::scale(scaleX, scaleY, scaleZ);
-class TRSToMatrix4 : public ParamObject {
- public:
- static const char* kTranslateXParamName;
- static const char* kTranslateYParamName;
- static const char* kTranslateZParamName;
- static const char* kRotateXParamName;
- static const char* kRotateYParamName;
- static const char* kRotateZParamName;
- static const char* kScaleXParamName;
- static const char* kScaleYParamName;
- static const char* kScaleZParamName;
- static const char* kOutputParamName;
-
- float translate_x() const {
- return translate_x_param_->value();
- }
-
- void set_translate_x(float value) {
- translate_x_param_->set_value(value);
- }
-
- float translate_y() const {
- return translate_y_param_->value();
- }
-
- void set_translate_y(float value) {
- translate_y_param_->set_value(value);
- }
-
- float translate_z() const {
- return translate_z_param_->value();
- }
-
- void set_translate_z(float value) {
- translate_z_param_->set_value(value);
- }
-
- float rotate_x() const {
- return rotate_x_param_->value();
- }
-
- void set_rotate_x(float value) {
- rotate_x_param_->set_value(value);
- }
-
- float rotate_y() const {
- return rotate_y_param_->value();
- }
-
- void set_rotate_y(float value) {
- rotate_y_param_->set_value(value);
- }
-
- float rotate_z() const {
- return rotate_z_param_->value();
- }
-
- void set_rotate_z(float value) {
- rotate_z_param_->set_value(value);
- }
-
- float scale_x() const {
- return scale_x_param_->value();
- }
-
- void set_scale_x(float value) {
- scale_x_param_->set_value(value);
- }
-
- float scale_y() const {
- return scale_y_param_->value();
- }
-
- void set_scale_y(float value) {
- scale_y_param_->set_value(value);
- }
-
- float scale_z() const {
- return scale_z_param_->value();
- }
-
- void set_scale_z(float value) {
- scale_z_param_->set_value(value);
- }
-
- Matrix4 output() const {
- return output_param_->value();
- }
-
- // Updates the output param.
- void UpdateOutputs();
-
- private:
- typedef SlaveParam<ParamMatrix4, TRSToMatrix4> SlaveParamMatrix4;
-
- explicit TRSToMatrix4(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamFloat::Ref translate_x_param_;
- ParamFloat::Ref translate_y_param_;
- ParamFloat::Ref translate_z_param_;
- ParamFloat::Ref rotate_x_param_;
- ParamFloat::Ref rotate_y_param_;
- ParamFloat::Ref rotate_z_param_;
- ParamFloat::Ref scale_x_param_;
- ParamFloat::Ref scale_y_param_;
- ParamFloat::Ref scale_z_param_;
- SlaveParamMatrix4::Ref output_param_;
-
- O3D_DECL_CLASS(TRSToMatrix4, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(TRSToMatrix4);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_PARAM_OPERATION_H_
-
-
-
-
diff --git a/o3d/core/cross/param_operation_test.cc b/o3d/core/cross/param_operation_test.cc
deleted file mode 100644
index 7906c35..0000000
--- a/o3d/core/cross/param_operation_test.cc
+++ /dev/null
@@ -1,479 +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 implements unit tests for various Param operations.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/param_operation.h"
-#include "core/cross/error_status.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-
-namespace o3d {
-
-class ParamOp2FloatsToFloat2Test : public testing::Test {
- protected:
-
- ParamOp2FloatsToFloat2Test()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
-
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- Pack* pack_;
-};
-
-void ParamOp2FloatsToFloat2Test::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void ParamOp2FloatsToFloat2Test::TearDown() {
- pack_->Destroy();
-}
-
-// Tests ParamOp2FloatsToFloat2.
-TEST_F(ParamOp2FloatsToFloat2Test, Basic) {
- ParamOp2FloatsToFloat2* operation = pack()->Create<ParamOp2FloatsToFloat2>();
-
- // Check that it got created.
- ASSERT_TRUE(operation != NULL);
-
- // Check that the correct params got created.
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp2FloatsToFloat2::kInput0ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp2FloatsToFloat2::kInput1ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat2>(
- ParamOp2FloatsToFloat2::kOutputParamName) != NULL);
-
- // Check that it evaluates correctly.
- operation->set_input_0(5.0f);
- operation->set_input_1(6.0f);
- EXPECT_EQ(operation->input_0(), 5.0f);
- EXPECT_EQ(operation->input_1(), 6.0f);
- Float2 output(operation->output());
- EXPECT_EQ(output[0], 5.0f);
- EXPECT_EQ(output[1], 6.0f);
-}
-
-class ParamOp3FloatsToFloat3Test : public testing::Test {
- protected:
-
- ParamOp3FloatsToFloat3Test()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
-
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- Pack* pack_;
-};
-
-void ParamOp3FloatsToFloat3Test::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void ParamOp3FloatsToFloat3Test::TearDown() {
- pack_->Destroy();
-}
-
-// Tests ParamOp3FloatsToFloat3.
-TEST_F(ParamOp3FloatsToFloat3Test, Basic) {
- ParamOp3FloatsToFloat3* operation = pack()->Create<ParamOp3FloatsToFloat3>();
-
- // Check that it got created.
- ASSERT_TRUE(operation != NULL);
-
- // Check that the correct params got created.
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp3FloatsToFloat3::kInput0ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp3FloatsToFloat3::kInput1ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp3FloatsToFloat3::kInput2ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat3>(
- ParamOp3FloatsToFloat3::kOutputParamName) != NULL);
-
- // Check that it evaluates correctly.
- operation->set_input_0(5.0f);
- operation->set_input_1(6.0f);
- operation->set_input_2(7.0f);
- EXPECT_EQ(operation->input_0(), 5.0f);
- EXPECT_EQ(operation->input_1(), 6.0f);
- EXPECT_EQ(operation->input_2(), 7.0f);
- Float3 output(operation->output());
- EXPECT_EQ(output[0], 5.0f);
- EXPECT_EQ(output[1], 6.0f);
- EXPECT_EQ(output[2], 7.0f);
-}
-
-class ParamOp4FloatsToFloat4Test : public testing::Test {
- protected:
-
- ParamOp4FloatsToFloat4Test()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
-
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- Pack* pack_;
-};
-
-void ParamOp4FloatsToFloat4Test::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void ParamOp4FloatsToFloat4Test::TearDown() {
- pack_->Destroy();
-}
-
-// Tests ParamOp4FloatsToFloat4.
-TEST_F(ParamOp4FloatsToFloat4Test, Basic) {
- ParamOp4FloatsToFloat4* operation = pack()->Create<ParamOp4FloatsToFloat4>();
-
- // Check that it got created.
- ASSERT_TRUE(operation != NULL);
-
- // Check that the correct params got created.
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp4FloatsToFloat4::kInput0ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp4FloatsToFloat4::kInput1ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp4FloatsToFloat4::kInput2ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp4FloatsToFloat4::kInput3ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat4>(
- ParamOp4FloatsToFloat4::kOutputParamName) != NULL);
-
- // Check that it evaluates correctly.
- operation->set_input_0(5.0f);
- operation->set_input_1(6.0f);
- operation->set_input_2(7.0f);
- operation->set_input_3(8.0f);
- EXPECT_EQ(operation->input_0(), 5.0f);
- EXPECT_EQ(operation->input_1(), 6.0f);
- EXPECT_EQ(operation->input_2(), 7.0f);
- EXPECT_EQ(operation->input_3(), 8.0f);
- Float4 output(operation->output());
- EXPECT_EQ(output[0], 5.0f);
- EXPECT_EQ(output[1], 6.0f);
- EXPECT_EQ(output[2], 7.0f);
- EXPECT_EQ(output[3], 8.0f);
-}
-
-class ParamOp16FloatsToMatrix4Test : public testing::Test {
- protected:
-
- ParamOp16FloatsToMatrix4Test()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
-
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- Pack* pack_;
-};
-
-void ParamOp16FloatsToMatrix4Test::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void ParamOp16FloatsToMatrix4Test::TearDown() {
- pack_->Destroy();
-}
-
-// Tests ParamOp16FloatsToMatrix4.
-TEST_F(ParamOp16FloatsToMatrix4Test, Basic) {
- ParamOp16FloatsToMatrix4* operation =
- pack()->Create<ParamOp16FloatsToMatrix4>();
-
- // Check that it got created.
- ASSERT_TRUE(operation != NULL);
-
- // Check that the correct params got created.
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput0ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput1ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput2ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput3ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput4ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput5ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput6ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput7ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput8ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput9ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput10ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput11ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput12ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput13ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput14ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- ParamOp16FloatsToMatrix4::kInput15ParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamMatrix4>(
- ParamOp16FloatsToMatrix4::kOutputParamName) != NULL);
-
- // Check that it defaults to the identity.
- Matrix4 output(operation->output());
- EXPECT_EQ(output[0][0], 1.0f);
- EXPECT_EQ(output[0][1], 0.0f);
- EXPECT_EQ(output[0][2], 0.0f);
- EXPECT_EQ(output[0][3], 0.0f);
- EXPECT_EQ(output[1][0], 0.0f);
- EXPECT_EQ(output[1][1], 1.0f);
- EXPECT_EQ(output[1][2], 0.0f);
- EXPECT_EQ(output[1][3], 0.0f);
- EXPECT_EQ(output[2][0], 0.0f);
- EXPECT_EQ(output[2][1], 0.0f);
- EXPECT_EQ(output[2][2], 1.0f);
- EXPECT_EQ(output[2][3], 0.0f);
- EXPECT_EQ(output[3][0], 0.0f);
- EXPECT_EQ(output[3][1], 0.0f);
- EXPECT_EQ(output[3][2], 0.0f);
- EXPECT_EQ(output[3][3], 1.0f);
-
- // Check that it evaluates correctly.
- operation->set_input_0(0.1f);
- operation->set_input_1(1.0f);
- operation->set_input_2(2.0f);
- operation->set_input_3(3.0f);
- operation->set_input_4(4.0f);
- operation->set_input_5(5.0f);
- operation->set_input_6(6.0f);
- operation->set_input_7(7.0f);
- operation->set_input_8(8.0f);
- operation->set_input_9(9.0f);
- operation->set_input_10(10.0f);
- operation->set_input_11(11.0f);
- operation->set_input_12(12.0f);
- operation->set_input_13(13.0f);
- operation->set_input_14(14.0f);
- operation->set_input_15(15.0f);
- EXPECT_EQ(operation->input_0(), 0.1f);
- EXPECT_EQ(operation->input_1(), 1.0f);
- EXPECT_EQ(operation->input_2(), 2.0f);
- EXPECT_EQ(operation->input_3(), 3.0f);
- EXPECT_EQ(operation->input_4(), 4.0f);
- EXPECT_EQ(operation->input_5(), 5.0f);
- EXPECT_EQ(operation->input_6(), 6.0f);
- EXPECT_EQ(operation->input_7(), 7.0f);
- EXPECT_EQ(operation->input_8(), 8.0f);
- EXPECT_EQ(operation->input_9(), 9.0f);
- EXPECT_EQ(operation->input_10(), 10.0f);
- EXPECT_EQ(operation->input_11(), 11.0f);
- EXPECT_EQ(operation->input_12(), 12.0f);
- EXPECT_EQ(operation->input_13(), 13.0f);
- EXPECT_EQ(operation->input_14(), 14.0f);
- EXPECT_EQ(operation->input_15(), 15.0f);
- output = operation->output();
- EXPECT_EQ(output[0][0], 0.1f);
- EXPECT_EQ(output[0][1], 1.0f);
- EXPECT_EQ(output[0][2], 2.0f);
- EXPECT_EQ(output[0][3], 3.0f);
- EXPECT_EQ(output[1][0], 4.0f);
- EXPECT_EQ(output[1][1], 5.0f);
- EXPECT_EQ(output[1][2], 6.0f);
- EXPECT_EQ(output[1][3], 7.0f);
- EXPECT_EQ(output[2][0], 8.0f);
- EXPECT_EQ(output[2][1], 9.0f);
- EXPECT_EQ(output[2][2], 10.0f);
- EXPECT_EQ(output[2][3], 11.0f);
- EXPECT_EQ(output[3][0], 12.0f);
- EXPECT_EQ(output[3][1], 13.0f);
- EXPECT_EQ(output[3][2], 14.0f);
- EXPECT_EQ(output[3][3], 15.0f);
-}
-
-class TRSToMatrix4Test : public testing::Test {
- protected:
-
- TRSToMatrix4Test()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
-
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- Pack* pack_;
-};
-
-void TRSToMatrix4Test::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void TRSToMatrix4Test::TearDown() {
- pack_->Destroy();
-}
-
-// Tests TRSToMatrix4.
-TEST_F(TRSToMatrix4Test, Basic) {
- TRSToMatrix4* operation = pack()->Create<TRSToMatrix4>();
-
- // Check that it got created.
- ASSERT_TRUE(operation != NULL);
-
- // Check that the correct params got created.
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- TRSToMatrix4::kTranslateXParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- TRSToMatrix4::kTranslateYParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- TRSToMatrix4::kTranslateZParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- TRSToMatrix4::kRotateXParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- TRSToMatrix4::kRotateYParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- TRSToMatrix4::kRotateZParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- TRSToMatrix4::kScaleXParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- TRSToMatrix4::kScaleYParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamFloat>(
- TRSToMatrix4::kScaleZParamName) != NULL);
- EXPECT_TRUE(operation->GetParam<ParamMatrix4>(
- TRSToMatrix4::kOutputParamName) != NULL);
-
- // Check that it defaults to the identity.
- Matrix4 output(operation->output());
- EXPECT_EQ(output[0][0], 1.0f);
- EXPECT_EQ(output[0][1], 0.0f);
- EXPECT_EQ(output[0][2], 0.0f);
- EXPECT_EQ(output[0][3], 0.0f);
- EXPECT_EQ(output[1][0], 0.0f);
- EXPECT_EQ(output[1][1], 1.0f);
- EXPECT_EQ(output[1][2], 0.0f);
- EXPECT_EQ(output[1][3], 0.0f);
- EXPECT_EQ(output[2][0], 0.0f);
- EXPECT_EQ(output[2][1], 0.0f);
- EXPECT_EQ(output[2][2], 1.0f);
- EXPECT_EQ(output[2][3], 0.0f);
- EXPECT_EQ(output[3][0], 0.0f);
- EXPECT_EQ(output[3][1], 0.0f);
- EXPECT_EQ(output[3][2], 0.0f);
- EXPECT_EQ(output[3][3], 1.0f);
-
- // Check that it evaluates correctly.
- operation->set_translate_x(1.0f);
- operation->set_translate_y(2.0f);
- operation->set_translate_z(3.0f);
- operation->set_rotate_x(4.0f);
- operation->set_rotate_y(5.0f);
- operation->set_rotate_z(6.0f);
- operation->set_scale_x(7.0f);
- operation->set_scale_y(8.0f);
- operation->set_scale_z(9.0f);
- EXPECT_EQ(operation->translate_x(), 1.0f);
- EXPECT_EQ(operation->translate_y(), 2.0f);
- EXPECT_EQ(operation->translate_z(), 3.0f);
- EXPECT_EQ(operation->rotate_x(), 4.0f);
- EXPECT_EQ(operation->rotate_y(), 5.0f);
- EXPECT_EQ(operation->rotate_z(), 6.0f);
- EXPECT_EQ(operation->scale_x(), 7.0f);
- EXPECT_EQ(operation->scale_y(), 8.0f);
- EXPECT_EQ(operation->scale_z(), 9.0f);
- output = operation->output();
- Matrix4 expected(
- Matrix4::translation(Vector3(1.0f, 2.0f, 3.0f)) *
- Matrix4::rotationZYX(Vector3(4.0f, 5.0f, 6.0f)) *
- Matrix4::scale(Vector3(7.0f, 8.0f, 9.0f)));
- EXPECT_EQ(output[0][0], expected[0][0]);
- EXPECT_EQ(output[0][1], expected[0][1]);
- EXPECT_EQ(output[0][2], expected[0][2]);
- EXPECT_EQ(output[0][3], expected[0][3]);
- EXPECT_EQ(output[1][0], expected[1][0]);
- EXPECT_EQ(output[1][1], expected[1][1]);
- EXPECT_EQ(output[1][2], expected[1][2]);
- EXPECT_EQ(output[1][3], expected[1][3]);
- EXPECT_EQ(output[2][0], expected[2][0]);
- EXPECT_EQ(output[2][1], expected[2][1]);
- EXPECT_EQ(output[2][2], expected[2][2]);
- EXPECT_EQ(output[2][3], expected[2][3]);
- EXPECT_EQ(output[3][0], expected[3][0]);
- EXPECT_EQ(output[3][1], expected[3][1]);
- EXPECT_EQ(output[3][2], expected[3][2]);
- EXPECT_EQ(output[3][3], expected[3][3]);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/param_test.cc b/o3d/core/cross/param_test.cc
deleted file mode 100644
index f4e7299..0000000
--- a/o3d/core/cross/param_test.cc
+++ /dev/null
@@ -1,766 +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 functionality of the Param class and its derived classes defined in
-// param.cc
-
-#include <algorithm>
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/error_status.h"
-#include "core/cross/pack.h"
-#include "core/cross/param_array.h"
-#include "core/cross/render_surface.h"
-#include "core/cross/sampler.h"
-#include "core/cross/texture.h"
-#include "core/cross/transform.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-namespace {
-// TestTexture derives from o3d::Texture and provides dummy implementations
-// for Texture's virtual methods. It is used in this file instead of Texture
-// which is an abstract class and cannot be instantiated
-class TestTexture : public Texture {
- public:
- explicit TestTexture(ServiceLocator* service_locator)
- : Texture(service_locator, UNKNOWN_FORMAT, 1, false) { }
- void* GetTextureHandle() const { return NULL; }
- virtual const RGBASwizzleIndices& GetABGR32FSwizzleIndices();
- virtual void SetFromBitmap(const Bitmap& bitmap) {
- DCHECK(false);
- }
- virtual void GenerateMips(int source_level, int last_target_level) {
- DCHECK(false);
- }
-};
-
-const Texture::RGBASwizzleIndices& TestTexture::GetABGR32FSwizzleIndices() {
- static Texture::RGBASwizzleIndices swizzle_indices = {2, 1, 0, 3};
- return swizzle_indices;
-};
-
-// TestRenderSurface derives from o3d::RenderSurface, and provides dummy
-// implementations of the abstract virtual functions of RenderSurface.
-class TestRenderSurface : public RenderSurface {
- public:
- explicit TestRenderSurface(ServiceLocator* service_locator)
- : RenderSurface(service_locator, 1, 1, NULL) {}
- void* GetSurfaceHandle() const { return NULL; }
- bool PlatformSpecificGetIntoBitmap(Bitmap::Ref bitmap) const { return true; }
-};
-
-// TestSampler derives from o3d::Sampler and provides a public
-// implementation of the constructor.
-class TestSampler : public Sampler {
- public:
- explicit TestSampler(ServiceLocator* service_locator)
- : Sampler(service_locator) {}
-};
-
-} // anonymous namespace
-
-// Basic test fixture.
-class ParamBasic : public testing::Test {
- protected:
-
- ParamBasic()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
- Transform *transform() { return transform_; }
-
- ServiceDependency<ObjectManager> object_manager_;
-
- Pack* pack() { return pack_; }
-
- private:
- ErrorStatus* error_status_;
- Transform* transform_;
- Pack* pack_;
-};
-
-void ParamBasic::SetUp() {
- error_status_ = new ErrorStatus(g_service_locator);
- pack_ = object_manager_->CreatePack();
- transform_ = pack_->Create<Transform>();
-}
-
-void ParamBasic::TearDown() {
- pack_->Destroy();
- delete error_status_;
-}
-
-namespace {
-
-// Check if a param is in the given param array
-// Parameters:
-// param: param to search for.
-// params: ParamVector to search.
-// Returns:
-// true if param is in params.
-bool ParamInParams(Param* param, const ParamVector& params) {
- return std::find(params.begin(), params.end(), param) != params.end();
-}
-
-// A non-cachable Param.
-class ParamCounter : public ParamFloat {
- public:
- explicit ParamCounter(ServiceLocator* service_locator)
- : ParamFloat(service_locator, true, true),
- count_(0) {
- SetNotCachable();
- }
- private:
- virtual void ComputeValue() {
- count_ += 1.0f;
- set_read_only_value(count_);
- }
-
- float count_;
-};
-
-} // anonymous namespace
-
-// Set/Get Float Params
-TEST_F(ParamBasic, TestFloat) {
- ParamFloat *param = transform()->CreateParam<ParamFloat>("floatParam");
- EXPECT_EQ(ParamFloat::GetApparentClass(), param->GetClass());
- Float in_val = 10.0f;
- param->set_value(in_val);
- Float out_val = param->value();
- EXPECT_FLOAT_EQ(in_val, out_val);
-}
-
-// Set/Get Float2 Params
-TEST_F(ParamBasic, TestFloat2) {
- ParamFloat2 *param = transform()->CreateParam<ParamFloat2>(
- "floatParam2");
- EXPECT_EQ(ParamFloat2::GetApparentClass(), param->GetClass());
- Float2 in_val(10.0f, 20.0f);
- param->set_value(in_val);
- Float2 out_val = param->value();
- EXPECT_FLOAT_EQ(in_val[0], out_val[0]);
- EXPECT_FLOAT_EQ(in_val[1], out_val[1]);
-}
-
-// Set/Get Float3 Params
-TEST_F(ParamBasic, TestFloat3) {
- ParamFloat3 *param = transform()->CreateParam<ParamFloat3>(
- "floatParam3");
- EXPECT_EQ(ParamFloat3::GetApparentClass(), param->GetClass());
- Float3 in_val(10.0f, 20.0f, 30.0f);
- param->set_value(in_val);
- Float3 out_val = param->value();
- EXPECT_FLOAT_EQ(in_val[0], out_val[0]);
- EXPECT_FLOAT_EQ(in_val[1], out_val[1]);
- EXPECT_FLOAT_EQ(in_val[2], out_val[2]);
-}
-
-// Set/Get Float4 Params
-TEST_F(ParamBasic, TestFloat4) {
- ParamFloat4 *param = transform()->CreateParam<ParamFloat4>(
- "floatParam4");
- EXPECT_EQ(ParamFloat4::GetApparentClass(), param->GetClass());
- Float4 in_val(10.0f, 20.0f, 30.0f, 40.f);
- param->set_value(in_val);
- Float4 out_val = param->value();
- EXPECT_FLOAT_EQ(in_val[0], out_val[0]);
- EXPECT_FLOAT_EQ(in_val[1], out_val[1]);
- EXPECT_FLOAT_EQ(in_val[2], out_val[2]);
- EXPECT_FLOAT_EQ(in_val[3], out_val[3]);
-}
-
-// Set/Get Integer param
-TEST_F(ParamBasic, TestInt) {
- ParamInteger *param = transform()->CreateParam<ParamInteger>("IntParam");
- EXPECT_EQ(ParamInteger::GetApparentClass(), param->GetClass());
- int in_val = 10;
- param->set_value(in_val);
- int out_val = param->value();
- EXPECT_EQ(in_val, out_val);
-}
-
-// Set/Get Boolean param
-TEST_F(ParamBasic, TestBoolean) {
- ParamBoolean *param = transform()->CreateParam<ParamBoolean>(
- "BoolParam");
- EXPECT_EQ(ParamBoolean::GetApparentClass(), param->GetClass());
- bool in_val = true;
- param->set_value(in_val);
- bool out_val = param->value();
- EXPECT_TRUE(out_val);
-}
-
-// Set/Get String param
-TEST_F(ParamBasic, TestString) {
- ParamString *param = transform()->CreateParam<ParamString>(
- "StringParam");
- EXPECT_EQ(ParamString::GetApparentClass(), param->GetClass());
- String kInputString = "Test my\tstring\n";
- param->set_value(kInputString);
- String kOutputString = param->value();
- EXPECT_EQ(kInputString, kOutputString);
-}
-
-// Set/Get Matrix4 param
-TEST_F(ParamBasic, TestMatrix4) {
- ParamMatrix4 *param = transform()->CreateParam<ParamMatrix4>(
- "MatrixParam");
- EXPECT_EQ(ParamMatrix4::GetApparentClass(), param->GetClass());
- Matrix4 in_val = Matrix4::rotationZYX(Vector3(10, 20, 30));
- in_val.setTranslation(Vector3(1, 2, 3));
- param->set_value(in_val);
- Matrix4 out_val = param->value();
-
- for (int i = 0; i < 4; i++)
- for (int j = 0; j < 4; j++)
- EXPECT_FLOAT_EQ(in_val[i][j], out_val[i][j]);
-}
-
-// Set/Get Texture param
-TEST_F(ParamBasic, TestTexture) {
- ParamTexture *param =
- transform()->CreateParam<ParamTexture>("TextureParam");
- EXPECT_EQ(ParamTexture::GetApparentClass(), param->GetClass());
- TestTexture::Ref in_texture(new TestTexture(g_service_locator));
- param->set_value(in_texture);
- Texture *out_texture = param->value();
- EXPECT_EQ(in_texture, out_texture);
- in_texture.Reset();
-}
-
-TEST_F(ParamBasic, TestRenderSurface) {
- ParamRenderSurface *param =
- transform()->CreateParam<ParamRenderSurface>("RenderSurfaceParam");
- EXPECT_EQ(ParamRenderSurface::GetApparentClass(), param->GetClass());
-
- TestRenderSurface::Ref in_surface(new TestRenderSurface(
- g_service_locator));
- param->set_value(in_surface);
- RenderSurface *out_surface = param->value();
- EXPECT_EQ(in_surface, out_surface);
- in_surface.Reset();
-}
-
-// Set/Get Sampler param
-TEST_F(ParamBasic, TestSampler) {
- ParamSampler *param =
- transform()->CreateParam<ParamSampler>("SamplerParam");
- EXPECT_EQ(ParamSampler::GetApparentClass(), param->GetClass());
- TestSampler::Ref in_sampler(new TestSampler(g_service_locator));
- param->set_value(in_sampler);
- Sampler *out_sampler = param->value();
- EXPECT_EQ(in_sampler, out_sampler);
- in_sampler.Reset();
-}
-
-// Output connection logic
-TEST_F(ParamBasic, OutputConnections) {
- Param *param1 = transform()->CreateParam<ParamFloat>("FloatParam1");
- Param *param2 = transform()->CreateParam<ParamFloat>("FloatParam2");
- Param *param3 = transform()->CreateParam<ParamFloat>("FloatParam3");
- Param *param4 = transform()->CreateParam<ParamFloat>("FloatParam4");
-
- EXPECT_TRUE(param2->Bind(param1));
- EXPECT_TRUE(param3->Bind(param1));
- EXPECT_TRUE(param4->Bind(param1));
-
- ParamVector out_connections = param1->output_connections();
- EXPECT_EQ(3U, out_connections.size());
-
- EXPECT_EQ(param2->input_connection(), param1);
- EXPECT_EQ(param3->input_connection(), param1);
- EXPECT_EQ(param4->input_connection(), param1);
-
- // Check that all three are listed as output connections for param1
- ParamVector::const_iterator pos;
- EXPECT_TRUE(find(out_connections.begin(), out_connections.end(), param2) !=
- out_connections.end());
- EXPECT_TRUE(find(out_connections.begin(), out_connections.end(), param3) !=
- out_connections.end());
- EXPECT_TRUE(find(out_connections.begin(), out_connections.end(), param4) !=
- out_connections.end());
-
- // Remove one and check again
- EXPECT_TRUE(param1->UnbindOutput(param3));
- out_connections = param1->output_connections();
- EXPECT_EQ(2U, out_connections.size());
- EXPECT_TRUE(find(out_connections.begin(), out_connections.end(), param2) !=
- out_connections.end());
- EXPECT_FALSE(find(out_connections.begin(), out_connections.end(), param3) !=
- out_connections.end());
- EXPECT_TRUE(find(out_connections.begin(), out_connections.end(), param4) !=
- out_connections.end());
- EXPECT_TRUE(param3->input_connection() == NULL);
-
- EXPECT_TRUE(param4->input_connection() != NULL);
- param4->UnbindInput();
-
- // Check that input_connection is gone
- EXPECT_TRUE(param4->input_connection() == NULL);
-
- // and that output connections are updated
- out_connections = param1->output_connections();
- EXPECT_EQ(1U, out_connections.size());
- EXPECT_TRUE(find(out_connections.begin(), out_connections.end(), param2) !=
- out_connections.end());
- EXPECT_FALSE(find(out_connections.begin(), out_connections.end(), param3) !=
- out_connections.end());
- EXPECT_FALSE(find(out_connections.begin(), out_connections.end(), param4) !=
- out_connections.end());
-}
-
-// UnbindInput on a Param
-TEST_F(ParamBasic, UnbindInput) {
- Param *param1 = transform()->CreateParam<ParamFloat>("Param1");
- Param *param2 = transform()->CreateParam<ParamFloat>("Param2");
-
- EXPECT_TRUE(param2->Bind(param1));
-
- Param *source = param2->input_connection();
-
- EXPECT_TRUE(source != NULL);
-
- param2->UnbindInput();
-
- EXPECT_TRUE(param2->input_connection() == NULL);
-}
-
-TEST_F(ParamBasic, BindToNullUnbindsInput) {
- Param *param1 = transform()->CreateParam<ParamFloat>("Param1");
- Param *param2 = transform()->CreateParam<ParamFloat>("Param2");
- EXPECT_TRUE(param2->Bind(param1));
- EXPECT_TRUE(param2->input_connection() == param1);
-
- param2->Bind(NULL);
- EXPECT_TRUE(param2->input_connection() == NULL);
-}
-
-// CopyDataFromParam for a FLOAT Param
-TEST_F(ParamBasic, CopyDataFromParamFloat) {
- ParamFloat *param1 = transform()->CreateParam<ParamFloat>("Param1");
- ParamFloat *param2 = transform()->CreateParam<ParamFloat>("Param2");
-
- param1->set_value(10.0f);
- param2->CopyDataFromParam(param1);
- Float val = param2->value();
- EXPECT_FLOAT_EQ(10.0f, val);
-}
-
-// CopyDataFromParam for a Float2 Param
-TEST_F(ParamBasic, CopyDataFromParamFloat2) {
- ParamFloat2 *param1 = transform()->CreateParam<ParamFloat2>("Param1");
- ParamFloat2 *param2 = transform()->CreateParam<ParamFloat2>("Param2");
- Float2 in_val(10.0f, 20.0f);
- param1->set_value(in_val);
- param2->CopyDataFromParam(param1);
- Float2 out_val = param2->value();
- EXPECT_FLOAT_EQ(in_val[0], out_val[0]);
- EXPECT_FLOAT_EQ(in_val[1], out_val[1]);
-}
-
-// CopyDataFromParam for a Float3 Param
-TEST_F(ParamBasic, CopyDataFromParamFloat3) {
- ParamFloat3 *param1 = transform()->CreateParam<ParamFloat3>("Param1");
- ParamFloat3 *param2 = transform()->CreateParam<ParamFloat3>("Param2");
- Float3 in_val(10.0f, 20.0f, 30.0f);
- param1->set_value(in_val);
- param2->CopyDataFromParam(param1);
- Float3 out_val = param2->value();
- EXPECT_FLOAT_EQ(in_val[0], out_val[0]);
- EXPECT_FLOAT_EQ(in_val[1], out_val[1]);
- EXPECT_FLOAT_EQ(in_val[2], out_val[2]);
-}
-
-// CopyDataFromParam for a Float4 Param
-TEST_F(ParamBasic, CopyDataFromParamFloat4) {
- ParamFloat4 *param1 = transform()->CreateParam<ParamFloat4>("Param1");
- ParamFloat4 *param2 = transform()->CreateParam<ParamFloat4>("Param2");
- Float4 in_val(10.0f, 20.0f, 30.0f, 40.0f);
- param1->set_value(in_val);
- param2->CopyDataFromParam(param1);
- Float4 out_val = param2->value();
- EXPECT_FLOAT_EQ(in_val[0], out_val[0]);
- EXPECT_FLOAT_EQ(in_val[1], out_val[1]);
- EXPECT_FLOAT_EQ(in_val[2], out_val[2]);
- EXPECT_FLOAT_EQ(in_val[3], out_val[3]);
-}
-
-// CopyDataFromParam for a INTEGER Param
-TEST_F(ParamBasic, CopyDataFromParamInt) {
- ParamInteger *param1 = transform()->CreateParam<ParamInteger>("Param1");
- ParamInteger *param2 = transform()->CreateParam<ParamInteger>("Param2");
-
- param1->set_value(10);
- param2->CopyDataFromParam(param1);
- int val = param2->value();
- EXPECT_EQ(10, val);
-}
-
-// CopyDataFromParam for a BOOLEAN Param
-TEST_F(ParamBasic, CopyDataFromParamBool) {
- ParamBoolean *param1 = transform()->CreateParam<ParamBoolean>("Param1");
- ParamBoolean *param2 = transform()->CreateParam<ParamBoolean>("Param2");
-
- param1->set_value(true);
- param2->CopyDataFromParam(param1);
- bool val = param2->value();
- EXPECT_TRUE(val);
-}
-
-// CopyDataFromParam for a STRING Param
-TEST_F(ParamBasic, CopyDataFromParamString) {
- ParamString *param1 = transform()->CreateParam<ParamString>("Param1");
- ParamString *param2 = transform()->CreateParam<ParamString>("Param2");
-
- String kInputString = "Test my cr\\azy\ts\ntring";
- param1->set_value(kInputString);
- param2->CopyDataFromParam(param1);
- String kOutputString = param2->value();
- EXPECT_EQ(kInputString, kOutputString);
-}
-
-// CopyDataFromParam for a MATRIX_4 Param
-TEST_F(ParamBasic, CopyDataFromParamMatrix4) {
- ParamMatrix4 *param1 = transform()->CreateParam<ParamMatrix4>("Param1");
- ParamMatrix4 *param2 = transform()->CreateParam<ParamMatrix4>("Param2");
- Matrix4 in_val = Matrix4::rotationZYX(Vector3(10, 20, 30));
- in_val.setTranslation(Vector3(1, 2, 3));
-
- param1->set_value(in_val);
- param2->CopyDataFromParam(param1);
- Matrix4 out_val = param2->value();
-
- for (int i = 0;i < 4;i++)
- for (int j = 0;j < 4;j++)
- EXPECT_FLOAT_EQ(in_val[i][j], out_val[i][j]);
-}
-
-// CopyDataFromParam for a TEXTURE Param
-TEST_F(ParamBasic, CopyDataFromParamTexture) {
- ParamTexture *param1 = transform()->CreateParam<ParamTexture>("Param1");
- ParamTexture *param2 = transform()->CreateParam<ParamTexture>("Param2");
-
- TestTexture::Ref in_texture(new TestTexture(g_service_locator));
- param1->set_value(in_texture);
- param2->CopyDataFromParam(param1);
- Texture *out_texture = param2->value();
- EXPECT_TRUE(in_texture == out_texture);
-
- // Remove all references to the created texture to localize the test case.
- in_texture.Reset();
- param1->set_value(Texture::Ref(NULL));
-}
-
-// CopyDataFromParam for a RenderSurface Param
-TEST_F(ParamBasic, CopyDataFromParamRenderSurface) {
- ParamRenderSurface *param1 =
- transform()->CreateParam<ParamRenderSurface>("Param1");
- ParamRenderSurface *param2 =
- transform()->CreateParam<ParamRenderSurface>("Param2");
-
- TestRenderSurface::Ref in_render_surface(new TestRenderSurface(
- g_service_locator));
- param1->set_value(in_render_surface);
- param2->CopyDataFromParam(param1);
- RenderSurface *out_render_surface = param2->value();
- EXPECT_TRUE(in_render_surface == out_render_surface);
-
- // Remove all references to the created texture to localize the test case.
- in_render_surface.Reset();
- param1->set_value(RenderSurface::Ref(NULL));
-}
-
-
-TEST_F(ParamBasic, TestReadOnly) {
- ParamMatrix4 *param = transform()->CreateParam<ParamMatrix4>("world");
- param->MarkAsReadOnly();
- EXPECT_EQ(ParamMatrix4::GetApparentClass(), param->GetClass());
- IErrorStatus* error_status = g_service_locator->GetService<IErrorStatus>();
- error_status->ClearLastError();
- param->set_value(Matrix4::identity());
- String error(error_status->GetLastError());
- EXPECT_TRUE(!error.empty());
-}
-
-// Tests ParamParamArray
-TEST_F(ParamBasic, ParamParamArray) {
- ParamParamArray *array_param =
- transform()->CreateParam<ParamParamArray>("param_array");
- ASSERT_TRUE(array_param != NULL);
- EXPECT_TRUE(array_param->value() == NULL);
- ParamArray *array = pack()->Create<ParamArray>();
- ASSERT_TRUE(array != NULL);
- array_param->set_value(array);
- ASSERT_TRUE(array_param->value() == array);
-
- // Check we can add a param.
- ParamFloat* param_0 = array_param->value()->CreateParam<ParamFloat>(0);
- ASSERT_TRUE(param_0 != NULL);
- param_0->set_value(3.0f);
- EXPECT_TRUE(array_param->value()->GetParam<ParamFloat>(0) == param_0);
- EXPECT_TRUE(array_param->value()->GetParam<ParamFloat>(0)->value() == 3.0f);
-}
-
-// A Param bind test fixture
-class ParamBindTest : public testing::Test {
- protected:
-
- ParamBindTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
-
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- ParamFloat *float_param_1_, *float_param_2_, *float_param_3_;
- ParamFloat4 *float4_param_1_, *float4_param_2_;
- ParamMatrix4 *matrix_param_1_, *matrix_param_2_, *matrix_param_3_;
-
- ServiceDependency<ObjectManager> object_manager_;
-
- private:
- Pack* pack_;
-};
-
-void ParamBindTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-
- Transform *t1 = pack_->Create<Transform>();
- Transform *t2 = pack_->Create<Transform>();
-
- float_param_1_ = t1->CreateParam<ParamFloat>("floatParam1");
- float_param_2_ = t2->CreateParam<ParamFloat>("floatParam2");
- float_param_3_ = t2->CreateParam<ParamFloat>("floatParam3");
-
- float4_param_1_ = t1->CreateParam<ParamFloat4>("float4Param1");
- float4_param_2_ = t2->CreateParam<ParamFloat4>("float4Param2");
-
- matrix_param_1_ = t1->CreateParam<ParamMatrix4>("matrixParam1");
- matrix_param_2_ = t2->CreateParam<ParamMatrix4>("matrixParam2");
- matrix_param_3_ = t2->CreateParam<ParamMatrix4>("matrixParam3");
-}
-
-void ParamBindTest::TearDown() {
- object_manager_->DestroyPack(pack_);
-}
-
-// Tests straight param bind
-TEST_F(ParamBindTest, BindParams) {
- float_param_1_->set_value(10.0f);
-
- // Bind float_param_2_ to float_param_1_
- EXPECT_TRUE(float_param_2_->Bind(float_param_1_));
-
- // Read the value of float_param_2_ and make sure it's the same as
- // the value set to float_param_1_
- float val = float_param_2_->value();
- EXPECT_EQ(10.0f, val);
-}
-
-// Makes sure that binding two Params of different types fails
-TEST_F(ParamBindTest, BindParamDifferentType) {
- EXPECT_FALSE(float_param_2_->Bind(matrix_param_1_));
-}
-
-// Tests UnbindInput on a direct bind
-TEST_F(ParamBindTest, UnbindInputDirect) {
- float_param_2_->Bind(float_param_1_);
-
- // Break the connection
- float_param_2_->UnbindInput();
-
- // Make sure that the input connection is gone
- float_param_2_->set_value(123.0f);
- float_param_1_->set_value(456.0f);
- EXPECT_EQ(123.0, float_param_2_->value());
-}
-
-// Tests GetParamById
-TEST_F(ParamBindTest, GetParamById) {
- EXPECT_TRUE(matrix_param_3_ == object_manager_->GetById<ParamMatrix4>(
- matrix_param_3_->id()));
- EXPECT_TRUE(float_param_2_ == object_manager_->GetById<ParamFloat>(
- float_param_2_->id()));
-}
-
-// Tests GetInputs and GetOutputs
-TEST_F(ParamBindTest, GetInputsGetOuputs) {
- EXPECT_TRUE(float_param_1_->Bind(float_param_2_));
- EXPECT_TRUE(float_param_2_->Bind(float_param_3_));
-
- // 3->2->1
-
- ParamVector params;
- float_param_1_->GetInputs(&params);
- EXPECT_EQ(params.size(), 2U);
- EXPECT_TRUE(ParamInParams(float_param_2_, params));
- EXPECT_TRUE(ParamInParams(float_param_3_, params));
-
- float_param_1_->GetOutputs(&params);
- EXPECT_EQ(params.size(), 0U);
-
- float_param_2_->GetInputs(&params);
- EXPECT_EQ(params.size(), 1U);
- EXPECT_TRUE(ParamInParams(float_param_3_, params));
-
- float_param_2_->GetOutputs(&params);
- EXPECT_EQ(params.size(), 1U);
- EXPECT_TRUE(ParamInParams(float_param_1_, params));
-
- float_param_3_->GetInputs(&params);
- EXPECT_EQ(params.size(), 0U);
-
- float_param_3_->GetOutputs(&params);
- EXPECT_EQ(params.size(), 2U);
- EXPECT_TRUE(ParamInParams(float_param_1_, params));
- EXPECT_TRUE(ParamInParams(float_param_2_, params));
-
- // Check with cycles.
- EXPECT_TRUE(float_param_3_->Bind(float_param_1_));
-
- // 3->2->1->3
-
- float_param_1_->GetInputs(&params);
- EXPECT_EQ(params.size(), 2U);
- EXPECT_TRUE(ParamInParams(float_param_2_, params));
- EXPECT_TRUE(ParamInParams(float_param_3_, params));
-
- float_param_1_->GetOutputs(&params);
- EXPECT_EQ(params.size(), 2U);
- EXPECT_TRUE(ParamInParams(float_param_2_, params));
- EXPECT_TRUE(ParamInParams(float_param_3_, params));
-
- float_param_2_->GetInputs(&params);
- EXPECT_EQ(params.size(), 2U);
- EXPECT_TRUE(ParamInParams(float_param_1_, params));
- EXPECT_TRUE(ParamInParams(float_param_3_, params));
-
- float_param_2_->GetOutputs(&params);
- EXPECT_EQ(params.size(), 2U);
- EXPECT_TRUE(ParamInParams(float_param_1_, params));
- EXPECT_TRUE(ParamInParams(float_param_3_, params));
-
- float_param_3_->GetInputs(&params);
- EXPECT_EQ(params.size(), 2U);
- EXPECT_TRUE(ParamInParams(float_param_1_, params));
- EXPECT_TRUE(ParamInParams(float_param_2_, params));
-
- float_param_3_->GetOutputs(&params);
- EXPECT_EQ(params.size(), 2U);
- EXPECT_TRUE(ParamInParams(float_param_1_, params));
- EXPECT_TRUE(ParamInParams(float_param_2_, params));
-
- // Check with up stream cycle (up stream from 1).
- float_param_3_->UnbindInput(); // 3->2->1
- EXPECT_TRUE(float_param_3_->Bind(float_param_2_));
-
- // 3--->2-+->1
- // |
- // +->3
-
- float_param_3_->GetOutputs(&params);
- EXPECT_EQ(params.size(), 2U);
- EXPECT_TRUE(ParamInParams(float_param_1_, params));
- EXPECT_TRUE(ParamInParams(float_param_2_, params));
-
- float_param_1_->GetInputs(&params);
- EXPECT_EQ(params.size(), 2U);
- EXPECT_TRUE(ParamInParams(float_param_2_, params));
- EXPECT_TRUE(ParamInParams(float_param_3_, params));
-}
-
-// Tests update input
-TEST_F(ParamBindTest, UpdateInput) {
- EXPECT_TRUE(float_param_3_->Bind(float_param_2_));
- EXPECT_TRUE(float_param_2_->Bind(float_param_1_));
-
- // 1->2->3
-
- // Check that the value comes through.
- float_param_1_->set_value(1.0f);
- EXPECT_EQ(float_param_3_->value(), 1.0f);
-
- // Check that if we set update_input it just gets the current value. (it's not
- // going to ask float_param_2_ to update.)
- float_param_3_->set_update_input(false);
- float_param_1_->set_value(3.0f);
- EXPECT_EQ(float_param_3_->value(), 1.0f);
-
- // Check it is actually getting the float_param_2_'s value.
- float_param_1_->set_value(5.0f);
- float value = float_param_2_->value();
- EXPECT_EQ(float_param_3_->value(), value);
-}
-
-// Tests non cachable params
-TEST_F(ParamBindTest, NonCachable) {
- Param::Ref param = Param::Ref(new ParamCounter(g_service_locator));
- ASSERT_FALSE(param.IsNull());
-
- // Check that if we bind to a non-cachable param we are also not cachable
- EXPECT_TRUE(float_param_1_->Bind(param));
- EXPECT_FALSE(float_param_1_->cachable());
-
- // Check that if we unbind it goes back to cachable.
- float_param_1_->UnbindInput();
- EXPECT_TRUE(float_param_1_->cachable());
-
- // Check that it if we bind to a chain both get marked as non cachable.
- EXPECT_TRUE(float_param_2_->Bind(float_param_1_));
- EXPECT_TRUE(float_param_1_->Bind(param));
- EXPECT_FALSE(float_param_2_->cachable());
- EXPECT_FALSE(float_param_1_->cachable());
-
- // Check that if we unbind the change they get marked as uncachable.
- float_param_1_->UnbindInput();
- EXPECT_TRUE(float_param_2_->cachable());
- EXPECT_TRUE(float_param_1_->cachable());
-
- // Check that each time we ask for a value we get a different one.
- EXPECT_TRUE(float_param_1_->Bind(param));
- float value1 = float_param_2_->value();
- float value2 = float_param_2_->value();
- EXPECT_EQ(value1 + 1.0f, value2);
-
- // Check that unbinding from the other side things get marked as cachable.
- param->UnbindOutputs();
- EXPECT_TRUE(float_param_2_->cachable());
- EXPECT_TRUE(float_param_1_->cachable());
-}
-} // namespace o3d
diff --git a/o3d/core/cross/performance_timer.h b/o3d/core/cross/performance_timer.h
deleted file mode 100644
index 34e8dc9..0000000
--- a/o3d/core/cross/performance_timer.h
+++ /dev/null
@@ -1,100 +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 declarations for the PerformanceTimer class, which
-// is used to measure o3d performance using the highest resolution
-// timers available on a given platform. This should be a cross-platform
-// header: actual implementation of the timer is platform-specific, and
-// should reside in the platform-specific directory (eg.,
-// win/performance_timer.cc).
-
-#ifndef O3D_IMPORT_CROSS_PERFORMANCE_TIMER_H_
-#define O3D_IMPORT_CROSS_PERFORMANCE_TIMER_H_
-
-#include <build/build_config.h>
-#ifdef OS_MACOSX
-#include <Carbon/Carbon.h>
-#endif
-#include <string>
-#include "base/basictypes.h"
-
-namespace o3d {
-
-#ifdef OS_MACOSX
-typedef AbsoluteTime PerformanceTimeStamp;
-#else
-typedef uint64 PerformanceTimeStamp;
-#endif
-
-// PerformanceTimer is designed to accurately track wallclock time
-// for performance profiling. Between Start() and Stop(), a
-// "stopwatch" accumulates elapsed time into accum_time_. Print() will
-// print a short string to the logger containing the name of the timer,
-// and its elapsed time.
-
-class PerformanceTimer {
- public:
- explicit PerformanceTimer(const char *name);
-
- // Starts the timer.
- void Start();
-
- // Stops the timer.
- void Stop();
-
- // Prints the name and currently elapsed timer value to the logger.
- void Print();
-
- // Stops and prints the timer.
- void StopAndPrint();
-
- // Returns the timer's elapsed time, as of the last Stop(), in seconds.
- double GetElapsedTime();
-
- // Returns the name of the timer.
- const char* name() { return name_.c_str(); }
- private:
-
- // Name of the timer.
- std::string name_;
-
- // Time the timer was last started, in internal units.
- PerformanceTimeStamp start_time_;
-
- // Accumulated elapsed time, in internal units. Computed only on Stop().
- PerformanceTimeStamp accum_time_;
-
- DISALLOW_COPY_AND_ASSIGN(PerformanceTimer);
-};
-} // end namespace o3d
-
-#endif // O3D_IMPORT_CROSS_PERFORMANCE_TIMER_H_
diff --git a/o3d/core/cross/performance_timer_test.cc b/o3d/core/cross/performance_timer_test.cc
deleted file mode 100644
index 3628843..0000000
--- a/o3d/core/cross/performance_timer_test.cc
+++ /dev/null
@@ -1,79 +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 unit tests for the performance timer.
-
-
-#include "core/cross/performance_timer.h"
-#include "tests/common/win/testing_common.h"
-
-namespace o3d {
-
-const char* kTimerName = "MyGroovyTimer";
-
-class PerformanceTimerTest : public testing::Test {
- protected:
- virtual void SetUp();
- virtual void TearDown();
- PerformanceTimer* timer() { return timer_; }
-
- private:
- PerformanceTimer* timer_;
-};
-
-void PerformanceTimerTest::SetUp() {
- timer_ = new PerformanceTimer(kTimerName);
-}
-
-void PerformanceTimerTest::TearDown() {
- delete timer_;
-}
-
-TEST_F(PerformanceTimerTest, Name) {
- EXPECT_TRUE(!strcmp(timer()->name(), kTimerName));
-}
-
-TEST_F(PerformanceTimerTest, StartStop) {
- ASSERT_TRUE(timer() != NULL);
- EXPECT_TRUE(timer()->GetElapsedTime() < 0.00001);
- timer()->Start();
- timer()->Stop();
- EXPECT_TRUE(timer()->GetElapsedTime() < 1.0);
- volatile float a = 0.0f;
- timer()->Start();
- for (int i = 0; i < 1000000; ++i) {
- a += 1;
- }
- timer()->StopAndPrint();
- EXPECT_TRUE(timer()->GetElapsedTime() > 0.0);
-}
-};
diff --git a/o3d/core/cross/pointer_utils.h b/o3d/core/cross/pointer_utils.h
deleted file mode 100644
index b94bff9..0000000
--- a/o3d/core/cross/pointer_utils.h
+++ /dev/null
@@ -1,58 +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 declaration for a few templated function to help with
-// pointers.
-
-#ifndef O3D_CORE_CROSS_POINTER_UTILS_H_
-#define O3D_CORE_CROSS_POINTER_UTILS_H_
-
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// Adds an arbitrary byte offset to a typed pointer.
-template <typename T>
-T AddPointerOffset(T pointer, int offset) {
- return reinterpret_cast<T>(
- const_cast<uint8*>(reinterpret_cast<const uint8*>(pointer) + offset));
-}
-
-// Creates a typed pointer from a void pointer and an offset.
-template <typename T>
-T PointerFromVoidPointer(const void* pointer, int offset) {
- return reinterpret_cast<T>(
- const_cast<uint8*>(reinterpret_cast<const uint8*>(pointer) + offset));
-}
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_POINTER_UTILS_H_
diff --git a/o3d/core/cross/precompile.cc b/o3d/core/cross/precompile.cc
deleted file mode 100644
index 3598338..0000000
--- a/o3d/core/cross/precompile.cc
+++ /dev/null
@@ -1,32 +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 "core/cross/precompile.h"
diff --git a/o3d/core/cross/precompile.h b/o3d/core/cross/precompile.h
deleted file mode 100644
index 8a99389..0000000
--- a/o3d/core/cross/precompile.h
+++ /dev/null
@@ -1,50 +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 includes for common headers used by O3D files. It
-// is used for pre-compiled header support.
-
-#ifndef O3D_CORE_CROSS_PRECOMPILE_H_
-#define O3D_CORE_CROSS_PRECOMPILE_H_
-
-#include <build/build_config.h>
-
-#if defined(OS_WIN)
-#include <windows.h>
-#endif // defined(OS_WIN)
-
-#include <assert.h>
-#include <algorithm>
-#include <map>
-#include <vector>
-
-#endif // O3D_CORE_CROSS_PRECOMPILE_H_
diff --git a/o3d/core/cross/primitive.cc b/o3d/core/cross/primitive.cc
deleted file mode 100644
index 876fa71b..0000000
--- a/o3d/core/cross/primitive.cc
+++ /dev/null
@@ -1,707 +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 definition of Primitive.
-
-#include "core/cross/primitive.h"
-#include "core/cross/renderer.h"
-#include "core/cross/error.h"
-#include "core/cross/stream_bank.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Primitive, Element);
-
-const char* Primitive::kStreamBankParamName =
- O3D_STRING_CONSTANT("streamBank");
-
-bool Primitive::GetIndexCount(PrimitiveType primitive_type,
- unsigned int primitive_count,
- unsigned int* index_count) {
- switch (primitive_type) {
- case Primitive::POINTLIST:
- *index_count = primitive_count;
- return true;
- case Primitive::LINELIST:
- *index_count = primitive_count * 2;
- return true;
- case Primitive::LINESTRIP:
- *index_count = primitive_count + 1;
- return true;
- case Primitive::TRIANGLELIST:
- *index_count = primitive_count * 3;
- return true;
- case Primitive::TRIANGLESTRIP:
- *index_count = primitive_count + 2;
- return true;
- case Primitive::TRIANGLEFAN:
- *index_count = primitive_count + 2;
- return true;
- default:
- return false;
- }
-}
-
-ObjectBase::Ref Primitive::Create(ServiceLocator* service_locator) {
- Renderer* renderer = service_locator->GetService<Renderer>();
- if (NULL == renderer) {
- O3D_ERROR(service_locator) << "No Render Device Available";
- return ObjectBase::Ref();
- }
-
- return ObjectBase::Ref(renderer->CreatePrimitive());
-}
-
-Primitive::Primitive(ServiceLocator* service_locator)
- : Element(service_locator),
- primitive_type_(Primitive::TRIANGLELIST),
- number_vertices_(0),
- number_primitives_(0),
- start_index_(0) {
- RegisterParamRef(kStreamBankParamName, &stream_bank_ref_);
-}
-
-Primitive::~Primitive() {
-}
-
-void Primitive::Render(Renderer* renderer,
- DrawElement* draw_element,
- Material* material,
- ParamObject* override,
- ParamCache* param_cache) {
- DLOG_ASSERT(draw_element);
- DLOG_ASSERT(param_cache);
- // If there's no material attached to this Shape.
- if (!material) {
- O3D_ERROR(service_locator()) << "No Material attached to Shape \""
- << draw_element->name() << "\"";
- return;
- }
-
- Effect* effect = material->effect();
- if (!effect) {
- O3D_ERROR(service_locator()) << "No Effect attached to Material '"
- << material->name() << "' in Shape '"
- << draw_element->name() << "'";
- return;
- }
-
- StreamBank* bank = stream_bank();
- if (!bank) {
- O3D_ERROR(service_locator())
- << "No StreambBank attached to Primitive '"
- << material->name() << "' in Shape '"
- << draw_element->name() << "'";
- return;
- }
-
- if (!bank->renderable()) {
- O3D_ERROR(service_locator())
- << "StreamBank has non-renderable buffers '"
- << bank->name() << "'";
- return;
- }
-
- PlatformSpecificRender(renderer, draw_element, material, override,
- param_cache);
-}
-
-namespace {
-
-// A class to make it easy to access floats from a buffer given a stream.
-template<typename T>
-class FieldReadAccessor {
- public:
- FieldReadAccessor()
- : initialized_(false),
- buffer_(NULL),
- locked_(false),
- data_(NULL),
- offset_(0),
- stride_(0),
- real_start_index_(0),
- translated_end_index_(0) { }
- explicit FieldReadAccessor(const Stream& stream)
- : initialized_(true),
- buffer_(stream.field().buffer()),
- locked_(false),
- data_(NULL),
- offset_(stream.field().offset()),
- stride_(stream.field().buffer()->stride()),
- real_start_index_(stream.start_index()),
- translated_end_index_(stream.GetMaxVertices() - stream.start_index()) {
- if (real_start_index_ > translated_end_index_) {
- initialized_ = false;
- return;
- }
- if (buffer_) {
- locked_ = buffer_->Lock(Buffer::READ_ONLY, &data_);
- }
- }
- virtual ~FieldReadAccessor() {
- if (initialized_ && locked_) {
- buffer_->Unlock();
- }
- }
- virtual T& operator[](unsigned int translated_index) {
- if (translated_index >= translated_end_index_) {
- O3D_ERROR(buffer_->service_locator())
- << "Index " << real_start_index_ + translated_index
- << " into buffer '" << buffer_->name() << "' is out of range.";
- translated_index = 0;
- }
- return *reinterpret_cast<T*>(reinterpret_cast<char*>(data_) + offset_ +
- stride_ * (translated_index + real_start_index_));
- }
- virtual void Initialize(const Field& field, unsigned int start_index,
- unsigned int length) {
- buffer_ = field.buffer();
- locked_ = false;
- data_ = NULL;
- offset_ = field.offset();
- stride_ = buffer_->stride();
- real_start_index_ = start_index;
- unsigned int max_index = std::min(length, buffer_->num_elements());
- translated_end_index_ = max_index - start_index;
- // Check for unsigned wrap.
- if (translated_end_index_ > max_index) {
- translated_end_index_ = 0;
- }
- if (start_index > translated_end_index_) {
- return; // It will not be valid in this case.
- }
- if (buffer_) {
- locked_ = buffer_->Lock(Buffer::READ_ONLY, &data_);
- }
- initialized_ = true;
- }
- bool Valid() {
- return initialized_ && locked_;
- }
-
- unsigned max_index() const {
- return translated_end_index_ - real_start_index_;
- }
-
- protected:
- bool initialized_;
- Buffer* buffer_;
- bool locked_;
- void* data_;
- unsigned int offset_;
- unsigned int stride_;
- unsigned int real_start_index_;
- unsigned int translated_end_index_;
-
- DISALLOW_COPY_AND_ASSIGN(FieldReadAccessor);
-};
-
-// Specialization which pads out the fetched coordinates with zeros,
-// to be able to handle 2D Position streams.
-class FieldReadAccessorPoint3 : public FieldReadAccessor<Point3> {
- public:
- FieldReadAccessorPoint3()
- : FieldReadAccessor<Point3>(),
- num_components_(0),
- cache_index_(0) { }
-
- virtual void Initialize(const Field& field, unsigned int start_index,
- unsigned int length) {
- FieldReadAccessor<Point3>::Initialize(field, start_index, length);
- num_components_ = field.num_components();
- }
-
- virtual Point3& operator[](unsigned int translated_index) {
- Point3& tmp = FieldReadAccessor<Point3>::operator[](translated_index);
- Point3& cur = cache_[cache_index_];
- cache_index_ = (cache_index_ + 1) % 3;
- for (unsigned int i = 0; i < num_components_; i++) {
- cur[i] = tmp[i];
- }
- for (unsigned int i = num_components_; i < 3; i++) {
- cur[i] = 0;
- }
- return cur;
- }
-
- protected:
- unsigned int num_components_;
- // We need a cache of the three most recently fetched vertices to
- // match the usage elsewhere in this file
- int cache_index_;
- Point3 cache_[3];
-};
-
-class FieldReadAccessorUnsignedInt : public FieldReadAccessor<unsigned int> {
- public:
- FieldReadAccessorUnsignedInt()
- : FieldReadAccessor<unsigned int>(),
- just_count_(false) { }
- void InitializeJustCount(unsigned int start_index, unsigned int length) {
- initialized_ = true;
- real_start_index_ = start_index;
- translated_end_index_ = length;
- locked_ = false;
- just_count_ = true;
- }
- virtual unsigned int& operator[](unsigned int translated_index) {
- if (translated_index >= translated_end_index_) {
- O3D_ERROR(buffer_->service_locator())
- << "Index " << real_start_index_ + translated_index
- << " into buffer '" << buffer_->name() << "' is out of range.";
- translated_index = 0;
- }
- if (just_count_) {
- counter_ = real_start_index_ + translated_index;
- return counter_;
- } else {
- return FieldReadAccessor<unsigned int>::operator[](translated_index);
- }
- }
- protected:
- unsigned int counter_;
- bool just_count_;
-};
-
-// Attempts to initialize a FieldReadAccessor for the stream of vertices of
-// the primitive. Returns newly allocated accessor which must be deleted
-// by caller, or NULL upon failure.
-FieldReadAccessor<Point3>* GetVerticesAccessor(const Primitive* primitive,
- int position_stream_index) {
- if (!primitive)
- return NULL;
-
- const StreamBank* stream_bank = primitive->stream_bank();
- if (!stream_bank) {
- O3D_ERROR(primitive->service_locator())
- << "No stream bank on Primitive '" << primitive->name() << "'";
- return NULL;
- }
-
- const Stream* vertex_stream = stream_bank->GetVertexStream(
- Stream::POSITION,
- position_stream_index);
-
- if (!vertex_stream) {
- O3D_ERROR(primitive->service_locator())
- << "No POSITION stream index "
- << position_stream_index;
- return NULL;
- }
-
- const Field& field = vertex_stream->field();
-
- if (!field.buffer()) {
- O3D_ERROR(primitive->service_locator()) << "Vertex Buffer not set";
- return NULL;
- }
-
- if (!field.IsA(FloatField::GetApparentClass())) {
- O3D_ERROR(primitive->service_locator()) << "POSITION stream index "
- << position_stream_index
- << " is not a FLOAT stream";
- return NULL;
- }
-
- // Don't even try to lock fields that don't have any data
- if (vertex_stream->GetMaxVertices() == 0) {
- return NULL;
- }
-
- FieldReadAccessor<Point3>* accessor;
- if (field.num_components() == 3) {
- accessor = new FieldReadAccessor<Point3>();
- } else {
- accessor = new FieldReadAccessorPoint3();
- }
-
- accessor->Initialize(field, vertex_stream->start_index(),
- vertex_stream->GetMaxVertices());
-
- if (!accessor->Valid()) {
- O3D_ERROR(primitive->service_locator())
- << "Could not lock vertex buffer";
- delete accessor;
- return NULL;
- }
-
- return accessor;
-}
-
-// Attempts to initialize a FieldReadAccessor for the stream of indices of
-// the primitive. Returns success.
-bool GetIndicesAccessor(const Primitive* primitive,
- FieldReadAccessor<unsigned int>* accessor,
- unsigned start_index,
- unsigned index_count) {
- if (!(accessor && primitive))
- return false;
-
- const IndexBuffer* buffer = primitive->index_buffer();
- DCHECK(buffer);
- if (!buffer->index_field())
- return false;
-
- accessor->Initialize(*buffer->index_field(), start_index, index_count);
-
- if (!accessor->Valid()) {
- O3D_ERROR(primitive->service_locator())
- << "Could not lock index buffer";
- return false;
- }
-
- return true;
-}
-
-} // anonymous namespace
-
-bool Primitive::WalkPolygons(
- int position_stream_index,
- PolygonFunctor* polygon_functor) const {
- DLOG_ASSERT(polygon_functor);
-
- FieldReadAccessorUnsignedInt indices;
- scoped_ptr<FieldReadAccessor<Point3> > vertices_pointer(
- GetVerticesAccessor(this, position_stream_index));
- if (vertices_pointer.get() == NULL)
- return false;
- FieldReadAccessor<Point3>& vertices = *vertices_pointer;
-
- unsigned int index_count;
- if (indexed()) {
- if (!Primitive::GetIndexCount(primitive_type(),
- number_primitives(),
- &index_count)) {
- O3D_ERROR(service_locator())
- << "Unknown Primitive Type in GetIndexCount: " << primitive_type_;
- return false;
- }
-
- if (!GetIndicesAccessor(this, &indices, start_index_, index_count)) {
- return false;
- }
-
- index_count = std::min(index_count, indices.max_index());
- } else {
- index_count = number_vertices();
- indices.InitializeJustCount(start_index_, index_count);
- }
-
- // If there are no vertices then exit early.
- if (vertices.max_index() == 0) {
- if (indices.max_index() > 0) {
- O3D_ERROR(service_locator())
- << "Indices on primitive '" << name() << "' reference a vertexbuffer"
- << "with 0 elements.";
- }
- return indices.max_index() == 0;
- }
-
- switch (primitive_type()) {
- case Primitive::TRIANGLELIST: {
- int prim = 0;
- for (unsigned int prim_base = 0;
- prim_base + 2 < index_count;
- prim_base += 3) {
- polygon_functor->ProcessTriangle(
- prim,
- vertices[indices[prim_base + 0]],
- vertices[indices[prim_base + 1]],
- vertices[indices[prim_base + 2]]);
- ++prim;
- }
- break;
- }
- case Primitive::TRIANGLESTRIP: {
- if (index_count > 2) {
- int prim = 0;
- unsigned local_indices[3];
- local_indices[0] = indices[0];
- local_indices[1] = indices[1];
- for (unsigned int prim_base = 2;
- prim_base < index_count;
- ++prim_base) {
- local_indices[2] = indices[prim_base];
- // flip ordering passed to ProcessTriangle since triangle strips flip
- // ordering.
- if ((prim & 1) == 0) {
- polygon_functor->ProcessTriangle(
- prim,
- vertices[local_indices[0]],
- vertices[local_indices[1]],
- vertices[local_indices[2]]);
- } else {
- polygon_functor->ProcessTriangle(
- prim,
- vertices[local_indices[0]],
- vertices[local_indices[2]],
- vertices[local_indices[1]]);
- }
- local_indices[0] = local_indices[1];
- local_indices[1] = local_indices[2];
- ++prim;
- }
- }
- break;
- }
- case Primitive::TRIANGLEFAN: {
- if (index_count > 2) {
- int prim = 0;
- unsigned local_indices[3];
- local_indices[0] = indices[0];
- local_indices[1] = indices[1];
- for (unsigned int prim_base = 2;
- prim_base < index_count;
- ++prim_base) {
- local_indices[2] = indices[prim_base];
- polygon_functor->ProcessTriangle(
- prim,
- vertices[local_indices[0]],
- vertices[local_indices[1]],
- vertices[local_indices[2]]);
- local_indices[1] = local_indices[2];
- ++prim;
- }
- }
- break;
- }
- case Primitive::LINELIST: {
- int prim = 0;
- for (unsigned int prim_base = 0;
- prim_base + 1 < index_count;
- prim_base += 2) {
- polygon_functor->ProcessLine(
- prim,
- vertices[indices[prim_base + 0]],
- vertices[indices[prim_base + 1]]);
- ++prim;
- }
- break;
- }
- case Primitive::LINESTRIP: {
- if (index_count > 1) {
- int prim = 0;
- unsigned local_indices[2];
- local_indices[0] = indices[0];
- for (unsigned int prim_base = 1;
- prim_base < index_count;
- ++prim_base) {
- local_indices[1] = indices[prim_base];
- polygon_functor->ProcessLine(
- prim,
- vertices[local_indices[0]],
- vertices[local_indices[1]]);
- local_indices[0] = local_indices[1];
- ++prim;
- }
- }
- break;
- }
- case Primitive::POINTLIST: {
- int prim = 0;
- for (unsigned int prim_base = 0; prim_base < index_count; ++prim_base) {
- polygon_functor->ProcessPoint(prim, vertices[indices[prim_base]]);
- ++prim;
- }
- break;
- }
- }
-
- return true;
-}
-
-namespace {
-
-class IntersectRayHelper : public Primitive::PolygonFunctor {
- public:
- IntersectRayHelper(State::Cull cull,
- const Point3& start,
- const Point3& end,
- RayIntersectionInfo* result)
- : cull_(cull),
- start_(start),
- end_(end),
- result_(result),
- closest_distance_squared_(0) {
- }
-
- virtual void ProcessTriangle(unsigned primitive_index,
- const Point3& p0,
- const Point3& p1,
- const Point3& p2) {
- Point3 intersection_point;
- bool intersected = false;
- if (cull_ == State::CULL_NONE || cull_ == State::CULL_CCW) {
- intersected = RayIntersectionInfo::IntersectTriangle(
- start_,
- end_,
- p0,
- p1,
- p2,
- &intersection_point);
- }
- if (!intersected &&
- (cull_ == State::CULL_NONE || cull_ == State::CULL_CW)) {
- intersected = RayIntersectionInfo::IntersectTriangle(
- start_,
- end_,
- p0,
- p2,
- p1,
- &intersection_point);
- }
- if (intersected) {
- // intersection
- bool update = false;
- float distance_squared;
- if (!result_->intersected()) {
- update = true;
- result_->set_intersected(true);
- distance_squared = lengthSqr(intersection_point - start_);
- } else {
- distance_squared = lengthSqr(intersection_point - start_);
- if (distance_squared < closest_distance_squared_) {
- update = true;
- }
- }
- if (update) {
- closest_distance_squared_ = distance_squared;
- result_->set_position(intersection_point);
- result_->set_primitive_index(primitive_index);
- }
- }
- }
-
- virtual void ProcessLine(unsigned primitive_index,
- const Point3& p0,
- const Point3& p1) {
- // For now, lines are not intersected
- }
- virtual void ProcessPoint(unsigned primitive_index,
- const Point3& p) {
- // For now, points are not intersected
- }
- private:
- State::Cull cull_;
- const Point3& start_;
- const Point3& end_;
- RayIntersectionInfo* result_;
- float closest_distance_squared_;
-};
-
-class BoundingBoxHelper : public Primitive::PolygonFunctor {
- public:
- BoundingBoxHelper()
- : first_(true) {
- }
- virtual void ProcessTriangle(unsigned primitive_index,
- const Point3& p0,
- const Point3& p1,
- const Point3& p2) {
- if (first_) {
- first_ = false;
- min_extent_ = p0;
- max_extent_ = p0;
- }
- min_extent_ = minPerElem(min_extent_, p0);
- max_extent_ = maxPerElem(max_extent_, p0);
- min_extent_ = minPerElem(min_extent_, p1);
- max_extent_ = maxPerElem(max_extent_, p1);
- min_extent_ = minPerElem(min_extent_, p2);
- max_extent_ = maxPerElem(max_extent_, p2);
- }
- virtual void ProcessLine(unsigned primitive_index,
- const Point3& p0,
- const Point3& p1) {
- if (first_) {
- first_ = false;
- min_extent_ = p0;
- max_extent_ = p0;
- }
- min_extent_ = minPerElem(min_extent_, p0);
- max_extent_ = maxPerElem(max_extent_, p0);
- min_extent_ = minPerElem(min_extent_, p1);
- max_extent_ = maxPerElem(max_extent_, p1);
- }
- virtual void ProcessPoint(unsigned primitive_index,
- const Point3& p) {
- if (first_) {
- first_ = false;
- min_extent_ = p;
- max_extent_ = p;
- }
- min_extent_ = minPerElem(min_extent_, p);
- max_extent_ = maxPerElem(max_extent_, p);
- }
- void GetBoundingBox(BoundingBox* result) {
- DLOG_ASSERT(result);
- *result = BoundingBox(min_extent_, max_extent_);
- }
- private:
- bool first_;
- Point3 min_extent_;
- Point3 max_extent_;
-};
-
-} // anonymouse namespace.
-
-void Primitive::IntersectRay(int position_stream_index,
- State::Cull cull,
- const Point3& start,
- const Point3& end,
- RayIntersectionInfo* result) const {
- if (!result) {
- DLOG_ASSERT(false);
- return;
- }
- result->Reset();
- IntersectRayHelper helper(cull, start, end, result);
- if (WalkPolygons(position_stream_index, &helper)) {
- result->set_valid(true);
- }
-}
-
-void Primitive::GetBoundingBox(int position_stream_index,
- BoundingBox* result) const {
- if (!result) {
- DLOG_ASSERT(false);
- return;
- }
-
- BoundingBoxHelper helper;
- if (WalkPolygons(position_stream_index, &helper)) {
- helper.GetBoundingBox(result);
- } else {
- *result = BoundingBox();
- }
-}
-} // namespace o3d
diff --git a/o3d/core/cross/primitive.h b/o3d/core/cross/primitive.h
deleted file mode 100644
index 6941657..0000000
--- a/o3d/core/cross/primitive.h
+++ /dev/null
@@ -1,225 +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 cotnains the declaration of Primitive.
-
-#ifndef O3D_CORE_CROSS_PRIMITIVE_H_
-#define O3D_CORE_CROSS_PRIMITIVE_H_
-
-#include <vector>
-#include <map>
-#include "core/cross/element.h"
-#include "core/cross/stream_bank.h"
-#include "core/cross/buffer.h"
-
-namespace o3d {
-
-class RenderContext;
-class Pack;
-class Material;
-class ParamCache;
-
-// The Primitive contains the geometry streams, vertex and index streams and a
-// reference to a material. It represents a piece of a Shape that uses a single
-// material. For example a cube with 6 faces where each face uses a different
-// material would be represented as 1 Shape with 6 Primitives.
-class Primitive : public Element {
- public:
- typedef SmartPointer<Primitive> Ref;
-
- // Param names for Primitive.
- static const char* kStreamBankParamName;
-
- virtual ~Primitive();
-
- // Types of geometric primitives used by Primitive.
- enum PrimitiveType {
- POINTLIST = 1, /* Point list */
- LINELIST = 2, /* Line list */
- LINESTRIP = 3, /* Line Strip */
- TRIANGLELIST = 4, /* Triangle List */
- TRIANGLESTRIP = 5, /* Triangle Strip */
- TRIANGLEFAN = 6, /* Triangle fan */
- };
-
- // Gets the StreamBank this Primitive is using.
- StreamBank* stream_bank() const {
- return stream_bank_ref_->value();
- }
-
- // Sets the StreamBank this Primitive is using.
- void set_stream_bank(StreamBank* stream_bank) {
- stream_bank_ref_->set_value(stream_bank);
- }
-
- // Computes the number of indices a given set of primitives will use,
- // depending on the primitive type. Returns false if
- static bool GetIndexCount(PrimitiveType primitive_type,
- unsigned int primitive_count,
- unsigned int* index_count);
-
- // Binds an index buffer to the primitive.
- void set_index_buffer(IndexBuffer* buffer) {
- index_buffer_ = IndexBuffer::Ref(buffer);
- }
-
- // Returns the index buffer bound to the primitive or NULL if non has been
- // bound.
- IndexBuffer* index_buffer() const {
- return index_buffer_;
- }
-
- // Sets the type of geometric primitives used by the shape.
- void set_primitive_type(PrimitiveType type) {
- primitive_type_ = type;
- }
-
- // Returns the types of geometric primitives used by the shape.
- PrimitiveType primitive_type() const {
- return primitive_type_;
- }
-
- // Sets the number of vertices used by the draw calls.
- void set_number_vertices(unsigned int number_vertices) {
- number_vertices_ = number_vertices;
- }
-
- // Returns the number of vertices used by the draw calls.
- unsigned int number_vertices() const {
- return number_vertices_;
- }
-
- // Sets the number of primitives used by the draw calls.
- void set_number_primitives(unsigned int number_primitives) {
- number_primitives_ = number_primitives;
- }
-
- // Returns the number of primitives used by the draw calls.
- unsigned int number_primitives() const {
- return number_primitives_;
- }
-
- // Sets the index of the first vertex to render.
- void set_start_index(unsigned int start_index) {
- start_index_ = start_index;
- }
-
- // Gets the index of the first vertex to render.
- unsigned int start_index() const {
- return start_index_;
- }
-
- // Returns whether the geometry should be assumed to be indexed.
- // If there are no indices given, we assume non-indexed geometry.
- bool indexed() const {
- return !index_buffer_.IsNull();
- }
-
- // Render this Primitive.
- void Render(Renderer* renderer,
- DrawElement* draw_element,
- Material* material,
- ParamObject* param_object,
- ParamCache* param_cache);
-
- // Overridden from Element (see element.h)
- // Computes the intersection of a ray in the same coordinate system as
- // the specified POSITION stream.
- virtual void IntersectRay(int position_stream_index,
- State::Cull cull,
- const Point3& start,
- const Point3& end,
- RayIntersectionInfo* result) const;
-
- // Overridden from Element (see element.h)
- // Computes the bounding box in same coordinate system as the specified
- // POSITION stream.
- virtual void GetBoundingBox(int position_stream_index,
- BoundingBox* result) const;
-
-
- // A class for visiting each triangle in this primitive.
- class PolygonFunctor {
- public:
- virtual ~PolygonFunctor() { }
- virtual void ProcessTriangle(unsigned primitive_index,
- const Point3& p0,
- const Point3& p1,
- const Point3& p2) = 0;
- virtual void ProcessLine(unsigned primitive_index,
- const Point3& p0,
- const Point3& p1) = 0;
- virtual void ProcessPoint(unsigned primitive_index,
- const Point3& p) = 0;
- };
-
- // Walks all the polygons in this primitive, calling the PolygonFunctor's
- // ProcessTriangle function for each one.
- bool WalkPolygons(int position_stream_index,
- PolygonFunctor* geometry_functor) const;
-
- protected:
- explicit Primitive(ServiceLocator* service_locator);
-
- virtual void PlatformSpecificRender(Renderer* renderer,
- DrawElement* draw_element,
- Material* material,
- ParamObject* param_object,
- ParamCache* param_cache) = 0;
-
- PrimitiveType primitive_type_;
- unsigned int number_vertices_;
- unsigned int number_primitives_;
- unsigned int start_index_;
-
- ParamStreamBank::Ref stream_bank_ref_;
- IndexBuffer::Ref index_buffer_;
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(Primitive, Element);
- DISALLOW_COPY_AND_ASSIGN(Primitive);
-};
-
-typedef std::vector<Primitive*> PrimitiveArray;
-typedef std::vector<Primitive::Ref> PrimitiveRefArray;
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_PRIMITIVE_H_
-
-
-
-
-
diff --git a/o3d/core/cross/primitive_test.cc b/o3d/core/cross/primitive_test.cc
deleted file mode 100644
index 84765f2..0000000
--- a/o3d/core/cross/primitive_test.cc
+++ /dev/null
@@ -1,117 +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 implements unit tests for class Primitive.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/primitive.h"
-#include "core/cross/fake_vertex_source.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-
-namespace o3d {
-
-class PrimitiveTest : public testing::Test {
- protected:
-
- PrimitiveTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- Pack *pack_;
-};
-
-void PrimitiveTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void PrimitiveTest::TearDown() {
- pack_->Destroy();
-}
-
-TEST_F(PrimitiveTest, Basic) {
- static uint32 cube_indices[] = {
- 0, 1, 4, // triangle v0,v1,v4
- 1, 5, 4, // triangle v1,v5,v4
- 1, 2, 5, // triangle v1,v2,v5
- 2, 6, 5, // triangle v2,v6,v5
- 2, 3, 6, // triangle v2,v3,v6
- 3, 7, 6, // triangle v3,v7,v6
- 3, 0, 7, // triangle v3,v0,v7
- 0, 4, 7, // triangle v0,v4,v7
- 4, 5, 7, // triangle v4,v5,v7
- 5, 6, 7, // triangle v5,v6,v7
- 3, 2, 0, // triangle v3,v2,v0
- 2, 1, 0 // triangle v2,v1,v0
- };
-
- Primitive* primitive = pack()->Create<Primitive>();
- StreamBank* stream_bank = pack()->Create<StreamBank>();
- // Check that primitive and StreamBank got created.
- ASSERT_TRUE(primitive != NULL);
- ASSERT_TRUE(stream_bank != NULL);
- primitive->set_stream_bank(stream_bank);
- EXPECT_EQ(primitive->stream_bank(), stream_bank);
-
- // Check Setting Index Streams.
- IndexBuffer* index_buffer = pack()->Create<IndexBuffer>();
-
- ASSERT_TRUE(index_buffer->AllocateElements(arraysize(cube_indices)));
- ASSERT_TRUE(index_buffer != NULL);
- index_buffer->index_field()->SetFromUInt32s(cube_indices, 1, 0,
- arraysize(cube_indices));
- primitive->set_index_buffer(index_buffer);
- primitive->set_primitive_type(o3d::Primitive::TRIANGLELIST);
- primitive->set_number_primitives(12);
- primitive->set_number_vertices(8);
-
- EXPECT_EQ(primitive->primitive_type(), o3d::Primitive::TRIANGLELIST);
- EXPECT_EQ(primitive->number_primitives(), 12U);
- EXPECT_EQ(primitive->number_vertices(), 8U);
-
- // Check getting the index buffer.
- EXPECT_EQ(primitive->index_buffer(), index_buffer);
-
- // Check removing the index buffer.
- EXPECT_TRUE(primitive->indexed());
- primitive->set_index_buffer(NULL);
- EXPECT_FALSE(primitive->indexed());
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/processed_path.cc b/o3d/core/cross/processed_path.cc
deleted file mode 100644
index ef5ab4e..0000000
--- a/o3d/core/cross/processed_path.cc
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright 2010, 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 definition of ProcessedPath.
-
-#include "core/cross/processed_path.h"
-
-#include "core/cross/buffer.h"
-#include "core/cross/field.h"
-#include "core/cross/gpu2d/path_processor.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(ProcessedPath, ObjectBase);
-
-ProcessedPath::ProcessedPath(ServiceLocator* service_locator)
- : ObjectBase(service_locator) {
-}
-
-ObjectBase::Ref ProcessedPath::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(
- ProcessedPath::Ref(new ProcessedPath(service_locator)));
-}
-
-ProcessedPath::~ProcessedPath() {
-}
-
-void ProcessedPath::Clear() {
- path.reset();
-}
-
-void ProcessedPath::MoveTo(float x, float y) {
- path.moveTo(SkFloatToScalar(x), SkFloatToScalar(y));
-}
-
-void ProcessedPath::LineTo(float x, float y) {
- path.lineTo(SkFloatToScalar(x), SkFloatToScalar(y));
-}
-
-void ProcessedPath::QuadraticTo(float cx, float cy, float x, float y) {
- path.quadTo(SkFloatToScalar(cx),
- SkFloatToScalar(cy),
- SkFloatToScalar(x),
- SkFloatToScalar(y));
-}
-
-void ProcessedPath::CubicTo(float c0x, float c0y,
- float c1x, float c1y,
- float x, float y) {
- path.cubicTo(SkFloatToScalar(c0x),
- SkFloatToScalar(c0y),
- SkFloatToScalar(c1x),
- SkFloatToScalar(c1y),
- SkFloatToScalar(x),
- SkFloatToScalar(y));
-}
-
-void ProcessedPath::Close() {
- path.close();
-}
-
-void ProcessedPath::CreateMesh(Field* exterior_positions,
- Field* exterior_texture_coordinates,
- Field* interior_positions) {
- gpu2d::PathProcessor processor;
- cache.Clear();
- processor.Process(path, &cache);
- // Copy the exterior vertices and texture coordinates into the
- // fields for the exterior triangles.
- SetFields(cache.vertices(), exterior_positions,
- cache.texcoords(), exterior_texture_coordinates,
- cache.num_vertices());
- // Copy the interior vertices into the field for the interior
- // triangles.
- SetFields(cache.interior_vertices(), interior_positions,
- NULL, NULL,
- cache.num_interior_vertices());
-}
-
-void ProcessedPath::SetFields(const float* positions,
- Field* position_field,
- const float* texture_coordinates,
- Field* texture_coordinate_field,
- unsigned int num_vertices) {
- // It may happen that there were no exterior or interior triangles.
- // In this case we allocate a single vertex in the fields to
- // indicate this to JavaScript since we can not allocate a
- // zero-sized buffer.
- DCHECK_NE(num_vertices, 1u);
- if (num_vertices == 0) {
- DCHECK_EQ(positions, static_cast<const float*>(NULL));
- DCHECK_EQ(texture_coordinates, static_cast<const float*>(NULL));
- num_vertices = 1;
- }
- Buffer* buffer = position_field->buffer();
- if (!buffer)
- return;
- if (buffer->num_elements() != num_vertices) {
- if (!buffer->AllocateElements(num_vertices)) {
- return;
- }
- }
- if (num_vertices == 1) {
- float tmp[2] = { 0 };
- position_field->SetFromFloats(tmp, 2, 0, 1);
- } else {
- position_field->SetFromFloats(positions, 2, 0, num_vertices);
- }
-
- // The texture coordinates are NULL for the interior triangles.
- if (texture_coordinate_field != NULL) {
- buffer = texture_coordinate_field->buffer();
- if (!buffer)
- return;
- if (buffer->num_elements() != num_vertices) {
- if (!buffer->AllocateElements(num_vertices)) {
- return;
- }
- }
- if (num_vertices == 1) {
- float tmp[3] = { 0 };
- texture_coordinate_field->SetFromFloats(tmp, 3, 0, 1);
- } else {
- texture_coordinate_field->SetFromFloats(texture_coordinates,
- 3, 0, num_vertices);
- }
- }
-}
-
-} // namespace o3d
-
diff --git a/o3d/core/cross/processed_path.h b/o3d/core/cross/processed_path.h
deleted file mode 100644
index 68233f2..0000000
--- a/o3d/core/cross/processed_path.h
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright 2010, 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_CORE_CROSS_PROCESSED_PATH_H_
-#define O3D_CORE_CROSS_PROCESSED_PATH_H_
-
-#include "core/cross/object_base.h"
-#include "core/cross/gpu2d/path_cache.h"
-#include "third_party/skia/include/core/SkPath.h"
-
-namespace o3d {
-
-class Field;
-
-// This class is the link between the generic curve processing code in
-// this directory and O3D. It runs the PathProcessor on a set of
-// curves and returns the resulting triangles' vertices and texture
-// coordinates in Fields which can be incorporated into primitives in
-// the scene graph.
-class ProcessedPath : public ObjectBase {
- public:
- typedef SmartPointer<ProcessedPath> Ref;
-
- virtual ~ProcessedPath();
-
- // Clears out all of the curve segments that have been added to this
- // path.
- void Clear();
-
- // Moves the pen to the given absolute X,Y coordinates. If a contour
- // isn't currently open on this path, one is opened.
- void MoveTo(float x, float y);
-
- // Draws a line from the current coordinates to the given absolute
- // X,Y coordinates.
- void LineTo(float x, float y);
-
- // Draws a quadratic curve from the current coordinates through the
- // given control point and end point, specified in absolute
- // coordinates.
- void QuadraticTo(float cx, float cy, float x, float y);
-
- // Draws a cubic curve from the current coordinates through the
- // given control points and end point, specified in absolute
- // coordinates.
- void CubicTo(float c0x, float c0y,
- float c1x, float c1y,
- float x, float y);
-
- // Closes the currently open contour on this path.
- void Close();
-
- // Creates the triangle mesh which will render the given curve
- // segments. There are two regions: exterior and interior. The
- // exterior region covers the portions containing the curve
- // segments. It has two associated fields: a 2D floating point field
- // for the positions, and a 3D floating point field for the
- // Loop/Blinn texture coordinates. The interior region has one 2D
- // floating point field for the positions. The contents of the
- // fields are organized for rendering as non-indexed triangles.
- void CreateMesh(Field* exterior_positions,
- Field* exterior_texture_coordinates,
- Field* interior_positions);
-
- private:
- explicit ProcessedPath(ServiceLocator* service_locator);
-
- void SetFields(const float* positions,
- Field* position_field,
- const float* texture_coordinates,
- Field* texture_coordinate_field,
- unsigned int num_vertices);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- SkPath path;
- gpu2d::PathCache cache;
-
- O3D_DECL_CLASS(ProcessedPath, ObjectBase);
- DISALLOW_COPY_AND_ASSIGN(ProcessedPath);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_PROCESSED_PATH_H_
-
diff --git a/o3d/core/cross/profiler.cc b/o3d/core/cross/profiler.cc
deleted file mode 100644
index 6b8fda2..0000000
--- a/o3d/core/cross/profiler.cc
+++ /dev/null
@@ -1,52 +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 "core/cross/profiler.h"
-
-namespace o3d {
-
-const InterfaceId Profiler::kInterfaceId =
- InterfaceTraits<Profiler>::kInterfaceId;
-
-Profiler::Profiler(ServiceLocator* service_locator)
- : service_(service_locator, this) {
-}
-
-#ifdef PROFILE_CLIENT
-
-void Profiler::Write(StructuredWriter* writer) {
- timing_table_.Write(writer);
-}
-
-#endif // PROFILE_CLIENT
-
-} // namespace o3d
diff --git a/o3d/core/cross/profiler.h b/o3d/core/cross/profiler.h
deleted file mode 100644
index 165e526..0000000
--- a/o3d/core/cross/profiler.h
+++ /dev/null
@@ -1,93 +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_CORE_CROSS_PROFILER_H_
-#define O3D_CORE_CROSS_PROFILER_H_
-
-#include <string>
-
-#include "core/cross/service_implementation.h"
-#include "core/cross/timingtable.h"
-
-namespace o3d {
-
-class StructuredWriter;
-
-// Provides support for profiling sections of code.
-class Profiler {
- public:
- static const InterfaceId kInterfaceId;
-
- explicit Profiler(ServiceLocator* service_locator);
-
-#ifdef PROFILE_CLIENT
- // Starts the timer ticking for the code range identified by key.
- inline void ProfileStart(const std::string& key) {
- timing_table_.Start(key);
- }
-
- // Stops the timer for the code range identified by key.
- inline void ProfileStop(const std::string& key) {
- timing_table_.Stop(key);
- }
-
- // Resets the profiler, clearing out all data.
- inline void ProfileReset() {
- timing_table_.Reset();
- }
-
- // Dumps all profiler state to a string.
- void Write(StructuredWriter* writer);
-
-#else // PROFILE_CLIENT
- inline void ProfileStart(const std::string& key) { }
-
- inline void ProfileStop(const std::string& key) { }
-
- inline void ProfileReset() { }
-
- inline void Write(StructuredWriter* writer) {
- }
-#endif // PROFILE_CLIENT
-
- private:
- ServiceImplementation<Profiler> service_;
-
-#ifdef PROFILE_CLIENT
- TimingTable timing_table_;
-#endif // PROFILE_CLIENT
-
- DISALLOW_COPY_AND_ASSIGN(Profiler);
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_PROFILER_H_
diff --git a/o3d/core/cross/ray_intersection_info.cc b/o3d/core/cross/ray_intersection_info.cc
deleted file mode 100644
index cefbef1..0000000
--- a/o3d/core/cross/ray_intersection_info.cc
+++ /dev/null
@@ -1,94 +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 definition for class RayIntersectionInfo.
-
-#include "core/cross/ray_intersection_info.h"
-
-namespace o3d {
-
-static const float kEpsilon = 0.000001f;
-
-// TODO: Someone who is better at math, please optimize this.
-bool RayIntersectionInfo::IntersectTriangle(const Point3& start,
- const Point3& end,
- const Point3& vert0,
- const Point3& vert1,
- const Point3& vert2,
- Point3* intersectionPoint) {
- Vector3 ab(vert1 - vert0);
- Vector3 ac(vert2 - vert0);
- Vector3 qp(start - end);
-
- Vector3 n(cross(ab, ac));
-
- float d = dot(qp, n);
- if (d <= 0.0f) {
- return false;
- }
-
- Vector3 ap(start - vert0);
- float t = dot(ap, n);
- if (t < 0.0f) {
- return false;
- }
- if (t > d) {
- return false;
- }
-
- Vector3 e(cross(qp, ap));
- float v = dot(ac, e);
- if (v < 0.0f || v > d) {
- return false;
- }
-
- float w = -dot(ab, e);
- if (w < 0.0f || v + w > d) {
- return false;
- }
-
- float ood = 1.0f / d;
- t *= ood;
- v *= ood;
- w *= ood;
- float u = 1.0f - v -w;
-
- *intersectionPoint = Point3(
- Vector3(vert0) * u + Vector3(vert1) * v + Vector3(vert2) * w);
-
- return true;
-}
-
-} // namespace o3d
-
-
-
diff --git a/o3d/core/cross/ray_intersection_info.h b/o3d/core/cross/ray_intersection_info.h
deleted file mode 100644
index 7fa6679..0000000
--- a/o3d/core/cross/ray_intersection_info.h
+++ /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 contains the declaration of RayIntersectionInfo
-
-#ifndef O3D_CORE_CROSS_RAY_INTERSECTION_INFO_H_
-#define O3D_CORE_CROSS_RAY_INTERSECTION_INFO_H_
-
-#include "core/cross/types.h"
-
-namespace o3d {
-
-// A RayIntersectionInfo is used to return the results of ray intersection
-// tests.
-class RayIntersectionInfo {
- public:
- RayIntersectionInfo()
- : valid_(false),
- intersected_(false),
- primitive_index_(-1) {
- }
-
- // Puts this info in the default, unset state.
- void Reset() {
- set_valid(false);
- set_intersected(false);
- set_primitive_index(-1);
- }
-
- // True if this ray intersection info is valid. For example if you call
- // element->IntersectRay on an element that has no vertex buffers the result
- // will be invalid.
- bool valid() const {
- return valid_;
- }
-
- void set_valid(bool valid) {
- valid_ = valid;
- }
-
- // True if this ray intersection intersected something.
- bool intersected() const {
- return intersected_;
- }
-
- void set_intersected(bool intersected) {
- intersected_ = intersected;
- }
-
- // The position the ray intersected something.
- const Point3& position() const {
- return position_;
- }
-
- void set_position(const Point3& position) {
- position_ = position;
- }
-
- // The index of the primitive that was intersected.
- int primitive_index() const {
- return primitive_index_;
- }
-
- void set_primitive_index(int index) {
- primitive_index_ = index;
- }
-
- // Intersects a ray with a trianagle.
- // Parameters:
- // start: position of start of ray in local space.
- // end: position of end of ray in local space.
- // vert0: first vertex of triangle.
- // vert1: second vertex of triangle.
- // vert2: third vertex of triangle.
- // intersectionPoint: pointer to Point3 to receive the position of
- // intersection.
- // Returns:
- // true if triangle was intersected by ray.
- static bool IntersectTriangle(const Point3& start,
- const Point3& end,
- const Point3& vert0,
- const Point3& vert1,
- const Point3& vert2,
- Point3* intersectionPoint);
-
- private:
- bool valid_;
- bool intersected_;
- Point3 position_;
- int primitive_index_;
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_RAY_INTERSECTION_INFO_H_
-
-
-
-
diff --git a/o3d/core/cross/ray_intersection_info_test.cc b/o3d/core/cross/ray_intersection_info_test.cc
deleted file mode 100644
index 2b6955a..0000000
--- a/o3d/core/cross/ray_intersection_info_test.cc
+++ /dev/null
@@ -1,130 +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 implements unit tests for class RayIntersectionInfo.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/ray_intersection_info.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-
-namespace o3d {
-
-class RayIntersectionInfoTest : public testing::Test {
- protected:
-
- RayIntersectionInfoTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- Pack *pack_;
-};
-
-void RayIntersectionInfoTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void RayIntersectionInfoTest::TearDown() {
- pack_->Destroy();
-}
-
-TEST_F(RayIntersectionInfoTest, Basic) {
- RayIntersectionInfo ray_intersection_info;
-
- // Check that it defaults to NOT valid.
- EXPECT_FALSE(ray_intersection_info.valid());
-
- // Check that it defaults to NOT intersected.
- EXPECT_FALSE(ray_intersection_info.intersected());
-}
-
-TEST_F(RayIntersectionInfoTest, IntersectTriangle) {
- RayIntersectionInfo ray_intersection_info;
-
- Point3 point1(0.0f, 0.0f, 0.0f);
- Point3 point2(0.0f, 1.0f, 0.0f);
- Point3 point3(1.0f, 0.0f, 0.0f);
-
- // Check that a ray intersects a triangle.
- Point3 result;
- EXPECT_TRUE(RayIntersectionInfo::IntersectTriangle(
- Point3(0.25f, 0.25f, -1.0f),
- Point3(0.25f, 0.25f, 1.0f),
- point1,
- point2,
- point3,
- &result));
- EXPECT_EQ(result.getX(), 0.25f);
- EXPECT_EQ(result.getY(), 0.25f);
- EXPECT_EQ(result.getZ(), 0.0f);
-
- // Check that a ray does NOT intersects a triangle.
- EXPECT_FALSE(RayIntersectionInfo::IntersectTriangle(
- Point3(1.25f, 0.25f, -1.0f),
- Point3(1.25f, 0.25f, 1.0f),
- point1,
- point2,
- point3,
- &result));
-
- // Check opposite winding of points.
-
- // Check that a ray intersects a triangle.
- EXPECT_FALSE(RayIntersectionInfo::IntersectTriangle(
- Point3(0.25f, 0.25f, -1.0f),
- Point3(0.25f, 0.25f, 1.0f),
- point1,
- point3,
- point2,
- &result));
- EXPECT_EQ(result.getX(), 0.25f);
- EXPECT_EQ(result.getY(), 0.25f);
- EXPECT_EQ(result.getZ(), 0.0f);
-
- // Check that a ray does NOT intersects a triangle.
- EXPECT_FALSE(RayIntersectionInfo::IntersectTriangle(
- Point3(1.25f, 0.25f, -1.0f),
- Point3(1.25f, 0.25f, 1.0f),
- point1,
- point3,
- point2,
- &result));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/render_context.cc b/o3d/core/cross/render_context.cc
deleted file mode 100644
index 324ac6e..0000000
--- a/o3d/core/cross/render_context.cc
+++ /dev/null
@@ -1,45 +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 implementation of RenderContext.
-
-#include "core/cross/render_context.h"
-
-namespace o3d {
-
-RenderContext::RenderContext(Renderer* renderer)
- : render_list_(NULL),
- renderer_(renderer) {
-}
-
-} // namespace o3d
-
diff --git a/o3d/core/cross/render_context.h b/o3d/core/cross/render_context.h
deleted file mode 100644
index 0e8788a..0000000
--- a/o3d/core/cross/render_context.h
+++ /dev/null
@@ -1,93 +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 declaration of the RenderContext class.
-
-#ifndef O3D_CORE_CROSS_RENDER_CONTEXT_H_
-#define O3D_CORE_CROSS_RENDER_CONTEXT_H_
-
-#include <vector>
-
-namespace o3d {
-
-class RenderNode;
-class Renderer;
-
-// Array container for RenderNodes.
-typedef std::vector<RenderNode*> RenderNodeArray;
-
-// Iterators for RenderNodeArray
-typedef RenderNodeArray::const_iterator RenderNodeArrayConstIterator;
-typedef RenderNodeArray::iterator RenderNodeArrayIterator;
-
-// The RenderContext class passed down the render graph
-// as the render graph is walked to hold state information
-// and other context needed while walking the render graph.
-class RenderContext {
- public:
- explicit RenderContext(Renderer* renderer);
-
- // Adds a Render Node to the current render list.
- void AddToRenderList(RenderNode* render_node);
-
- // Sets the renderlist that will be used when AddToRenderList is called.
- void set_render_list(RenderNodeArray* render_list);
-
- Renderer* renderer();
-
- private:
- // The current list used by AddToRenderList.
- RenderNodeArray* render_list_;
- Renderer* renderer_;
-};
-
-inline Renderer* RenderContext::renderer() {
- return renderer_;
-}
-
-inline void RenderContext::AddToRenderList(RenderNode* render_node) {
- if (render_list_) {
- render_list_->push_back(render_node);
- }
-}
-
-inline void RenderContext::set_render_list(RenderNodeArray* render_list) {
- render_list_ = render_list;
-}
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_RENDER_CONTEXT_H_
-
-
-
-
diff --git a/o3d/core/cross/render_event.h b/o3d/core/cross/render_event.h
deleted file mode 100644
index 3ced1d5..0000000
--- a/o3d/core/cross/render_event.h
+++ /dev/null
@@ -1,174 +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 RenderEvent class.
-
-#ifndef O3D_CORE_CROSS_RENDER_EVENT_H_
-#define O3D_CORE_CROSS_RENDER_EVENT_H_
-
-namespace o3d {
-
-// This class is used to pass infomation to a registered onrender callback.
-class RenderEvent {
- public:
- RenderEvent()
- : elapsed_time_(0.0f),
- render_time_(0.0f),
- active_time_(0.0f),
- transforms_processed_(0),
- transforms_culled_(0),
- draw_elements_processed_(0),
- draw_elements_culled_(0),
- draw_elements_rendered_(0),
- primitives_rendered_(0) {
- }
-
- // Use this function to get elapsed time since the last render event in
- // seconds.
- float elapsed_time() const {
- return elapsed_time_;
- }
-
- // The client will use this function to set the elapsed time. You should never
- // call this function.
- void set_elapsed_time(float time) {
- elapsed_time_ = time;
- }
-
- // Use this function to get the time it took to render the last frame.
- float render_time() const {
- return render_time_;
- }
-
- // The client will use this function to set the render time. You should never
- // call this function.
- void set_render_time(float time) {
- render_time_ = time;
- }
-
- // Use this function to get the time it took to both render the last frame.
- // and call the tick, counter and render callbacks.
- float active_time() const {
- return active_time_;
- }
-
- // The client will use this function to set the active time. You should never
- // call this function.
- void set_active_time(float time) {
- active_time_ = time;
- }
-
- // The number of transforms processed last frame.
- int transforms_processed() const {
- return transforms_processed_;
- }
-
- // The client uses this function to set this value
- void set_transforms_processed(int value) {
- transforms_processed_ = value;
- }
-
- // The number of transforms culled last frame.
- int transforms_culled() const {
- return transforms_culled_;
- }
-
- // The client uses this function to set this value
- void set_transforms_culled(int value) {
- transforms_culled_ = value;
- }
-
- // The number of draw elements processed last frame.
- int draw_elements_processed() const {
- return draw_elements_processed_;
- }
-
- // The client uses this function to set this value
- void set_draw_elements_processed(int value) {
- draw_elements_processed_ = value;
- }
-
- // The number of draw elements culled last frame.
- int draw_elements_culled() const {
- return draw_elements_culled_;
- }
-
- // The client uses this function to set this value
- void set_draw_elements_culled(int value) {
- draw_elements_culled_ = value;
- }
-
- // The number of draw elements rendered last frame. Note: a draw element can
- // be rendered more than once per frame based on how many transforms it is
- // under and how many DrawPasses use the DrawLists it is put on.
- int draw_elements_rendered() const {
- return draw_elements_rendered_;
- }
-
- // The client uses this function to set this value
- void set_draw_elements_rendered(int value) {
- draw_elements_rendered_ = value;
- }
-
- // The number of low-level primitives rendered last frame. This is the sum of
- // the number primitives (triangles, lines) submitted to the renderer.
- int primitives_rendered() const {
- return primitives_rendered_;
- }
-
- // The client uses this function to set this value
- void set_primitives_rendered(int value) {
- primitives_rendered_ = value;
- }
- private:
- // This is the elapsed time in seconds since the last render event.
- float elapsed_time_;
-
- // This is the time it took to render or rather, the time it took to submit
- // everything to D3D9 or GL and flip buffers.
- float render_time_;
-
- // The time it took to both render the last frame. and call the tick, counter
- // and render callbacks.
- float active_time_;
-
- int transforms_processed_;
- int transforms_culled_;
- int draw_elements_processed_;
- int draw_elements_culled_;
- int draw_elements_rendered_;
- int primitives_rendered_;
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_RENDER_EVENT_H_
diff --git a/o3d/core/cross/render_node.cc b/o3d/core/cross/render_node.cc
deleted file mode 100644
index 335edb0..0000000
--- a/o3d/core/cross/render_node.cc
+++ /dev/null
@@ -1,335 +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 "core/cross/render_node.h"
-#include "core/cross/error.h"
-
-namespace o3d {
-
-namespace {
-
-// Returns true if parenting parent to child introduces a cycle in the
-// rendergraph hierarchy.
-// Note: Assumes that the graph is acyclic. Will infinite loop if cycles
-// are present.
-bool ParentingIntroducesCycle(
- const RenderNode* parent,
- const RenderNode* child) {
- if (child == parent)
- return true;
-
- // Ensure that the parent node is not reachable from any of the descendents
- // of the child node.
- const RenderNodeArray& children(child->GetChildren());
- RenderNodeArray::const_iterator iter(children.begin()), end(children.end());
- for (; iter != end; ++iter) {
- if (ParentingIntroducesCycle(parent, *iter)) {
- return true;
- }
- }
-
- return false;
-}
-
-bool CompareByPriority(const RenderNode* lhs, const RenderNode* rhs) {
- return lhs->priority() < rhs->priority();
-}
-
-} // end unnamed namespace
-
-O3D_DEFN_CLASS(RenderNode, ParamObject);
-
-const char* RenderNode::kPriorityParamName =
- O3D_STRING_CONSTANT("priority");
-const char* RenderNode::kActiveParamName =
- O3D_STRING_CONSTANT("active");
-
-RenderNode::RenderNode(ServiceLocator* service_locator)
- : ParamObject(service_locator),
- parent_(NULL) {
- RegisterParamRef(kPriorityParamName, &priority_param_);
- RegisterParamRef(kActiveParamName, &active_param_);
-
- priority_param_->set_value(0.0f);
- active_param_->set_value(true);
-}
-
-RenderNode::~RenderNode() {
- // Sets any children to have no parent.
- //
- // We can not use child_array_ directly because as each child has
- // SetParent(NULL) called on it it will remove itself from child_array_.
- RenderNodeArray children(GetChildren());
- RenderNodeArray::iterator end(children.end());
- for (RenderNodeArray::iterator iter(children.begin());
- iter != end;
- ++iter) {
- (*iter)->SetParent(NULL);
- }
-}
-
-void RenderNode::RenderTree(RenderContext* render_context) {
- if (active()) {
- Render(render_context);
- if (!child_array_.empty()) {
- RenderChildren(render_context);
- }
- PostRender(render_context);
- }
-}
-
-void RenderNode::RenderChildren(RenderContext* render_context) {
- std::sort(child_array_.begin(), child_array_.end(), CompareByPriority);
- RenderNodeRefArray::const_iterator child_end(child_array_.end());
- for (RenderNodeRefArray::const_iterator child_iter(child_array_.begin());
- child_iter != child_end;
- ++child_iter) {
- RenderNode* child = child_iter->Get();
- child->RenderTree(render_context);
- }
-}
-
-// Returns a array of immediate children for the rendernode.
-RenderNodeArray RenderNode::GetChildren() const {
- RenderNodeArray children_array;
- children_array.reserve(child_array_.size());
- RenderNodeRefArray::const_iterator child_end(child_array_.end());
- for (RenderNodeRefArray::const_iterator child_iter(child_array_.begin());
- child_iter != child_end;
- ++child_iter) {
- children_array.push_back(child_iter->Get());
- }
-
- return children_array;
-}
-
-void RenderNode::SetParent(RenderNode* parent_render_node) {
- // Explicitly disallow parenting that generates a cycle.
- if (ParentingIntroducesCycle(parent_render_node, this)) {
- O3D_ERROR(service_locator())
- << "Cannot set parent as it creates a cycle";
- return;
- }
-
- // Creates a temporary reference to ourselves because if our current parent
- // holds the only reference to us then we'll get deleted the moment we call
- // RemoveChild. This temporary reference will let go automatically when
- // the function exits.
- RenderNode::Ref temp_reference(this);
-
- // Checks if the rendernode already has a parent. If it does then remove it
- // from its current parent first.
- if (parent_ != NULL) {
- bool removed = parent_->RemoveChild(this);
-
- DLOG_ASSERT(removed);
-
- if (!removed)
- return;
- }
-
- // If we are just unparenting the node then we are done.
- if (parent_render_node == NULL) {
- parent_ = NULL;
- return;
- }
-
- // Adds the rendernode as a child of its new parent.
- parent_ = parent_render_node;
-
- bool added = parent_render_node->AddChild(this);
-
- DLOG_ASSERT(added);
-
- // If we failed to add the child to the parent then we leave the child node
- // an orphan in order to avoid any inconsistencies in the rendergraph.
- if (!added)
- parent_ = NULL;
-}
-
-// Removes a child node from the child_array_. Returns true if the operation
-// succeeds.
-bool RenderNode::RemoveChild(RenderNode *child_node) {
- RenderNodeRefArrayIterator end = std::remove(child_array_.begin(),
- child_array_.end(),
- RenderNode::Ref(child_node));
-
- // Child_node should never be in the child array more than once.
- DLOG_ASSERT(child_array_.end() - end <= 1);
-
- // The child was never found.
- if (end == child_array_.end())
- return true;
-
- // This test will tell us if the child_node was found.
- if (child_array_.end() - end != 1)
- return false;
-
- // Actually removes the child_node from the child array.
- child_array_.erase(end, child_array_.end());
- return true;
-}
-
-bool RenderNode::AddChild(RenderNode *child_node) {
- child_array_.push_back(RenderNode::Ref(child_node));
- return true;
-};
-
-// Returns the rendernodes in a subtree starting with this rendernode
-void RenderNode::GetRenderNodesInTreeFast(RenderNodeArray* render_nodes) const {
- render_nodes->clear();
-
- // First push this rendernode into the array.
- render_nodes->push_back(const_cast<RenderNode*>(this));
-
- // Iterate through all the elements of the array and append all the child
- // rendernodes at the end.
- for (unsigned int index = 0;index < render_nodes->size();index++) {
- RenderNode* render_node = (*render_nodes)[index];
- copy(render_node->child_array_.begin(),
- render_node->child_array_.end(),
- back_inserter(*render_nodes));
- }
-}
-
-// Slower version of function above for Javascript.
-RenderNodeArray RenderNode::GetRenderNodesInTree() const {
- RenderNodeArray render_node_array;
- GetRenderNodesInTreeFast(&render_node_array);
- return render_node_array;
-};
-
-// Functor object for comparing render node names.
-namespace {
-class CompareRenderNodeName {
- public:
- explicit CompareRenderNodeName(const String& n) : test_name_(n) {}
- bool operator()(RenderNode*& render_node) {
- return render_node->name() == test_name_;
- }
- private:
- String test_name_;
-};
-}
-
-// Search for render nodes by name in the subtree below this rendernode.
-void RenderNode::GetRenderNodesByNameInTreeFast(
- const String& name,
- RenderNodeArray* matching_nodes) const {
- matching_nodes->clear();
-
- // Get all the render nodes in the subtree.
- GetRenderNodesInTreeFast(matching_nodes);
-
- // Partition the container into two sections depending on whether the render
- // node name matches the desired name.
- RenderNodeArray::iterator i =
- std::partition(matching_nodes->begin(),
- matching_nodes->end(),
- CompareRenderNodeName(name));
-}
-
-// Slower version of function above for Javascript.
-RenderNodeArray RenderNode::GetRenderNodesByNameInTree(
- const String& name) const {
- RenderNodeArray matching_nodes;
- GetRenderNodesByNameInTreeFast(name, &matching_nodes);
- return matching_nodes;
-}
-
-// Functor object for comparing render node classes.
-namespace {
-class CompareRenderNodeClass {
- public:
- explicit CompareRenderNodeClass(const ObjectBase::Class* class_type)
- : class_type_(class_type) {
- }
- bool operator()(RenderNode*& render_node) {
- return render_node->IsA(class_type_);
- }
- private:
- const ObjectBase::Class* class_type_;
-};
-}
-
-// Search for rendernodes by class in the subtree below this rendernode
-RenderNodeArray RenderNode::GetRenderNodesByClassInTree(
- const ObjectBase::Class* class_type) const {
- // Get all the render nodes in the subtree
- RenderNodeArray nodes = GetRenderNodesInTree();
- // Partition the container into two sections depending on whether the render
- // node matches the desired class.
- RenderNodeArray::iterator i =
- std::partition(nodes.begin(),
- nodes.end(),
- CompareRenderNodeClass(class_type));
- // delete the nodes that don't match the name.
- nodes.erase(i, nodes.end());
- return nodes;
-}
-
-// Functor object for comparing render node class names.
-namespace {
-class CompareRenderNodeClassName {
- public:
- explicit CompareRenderNodeClassName(const String& class_type_name)
- : class_type_name_(class_type_name) {
- }
- bool operator()(RenderNode*& render_node) {
- return render_node->IsAClassName(class_type_name_);
- }
- private:
- const String& class_type_name_;
-};
-}
-
-// Search for render nodes by class name in the subtree below this render node
-RenderNodeArray RenderNode::GetRenderNodesByClassNameInTree(
- const String& class_type_name) const {
- // Get all the render nodes in the subtree
- RenderNodeArray nodes = GetRenderNodesInTree();
- // Partition the container into two sections depending on whether the render
- // node class name matches the desired class name.
- RenderNodeArray::iterator i =
- std::partition(nodes.begin(),
- nodes.end(),
- CompareRenderNodeClassName(class_type_name));
- // delete the nodes that don't match the name.
- nodes.erase(i, nodes.end());
- return nodes;
-}
-
-ObjectBase::Ref RenderNode::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new RenderNode(service_locator));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/render_node.h b/o3d/core/cross/render_node.h
deleted file mode 100644
index bbb1004..0000000
--- a/o3d/core/cross/render_node.h
+++ /dev/null
@@ -1,227 +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 declaration of the RenderNode class.
-
-#ifndef O3D_CORE_CROSS_RENDER_NODE_H_
-#define O3D_CORE_CROSS_RENDER_NODE_H_
-
-#include <vector>
-#include "core/cross/param_object.h"
-#include "core/cross/render_context.h"
-
-namespace o3d {
-
-class Effect;
-class State;
-
-// The base class for all nodes that live in the render graph It sorts all its
-// children by priority (lower priority first) and renders them in that order.
-class RenderNode : public ParamObject {
- friend class Client;
- public:
- typedef SmartPointer<RenderNode> Ref;
-
- typedef std::vector<RenderNode::Ref> RenderNodeRefArray;
-
- static const char* kPriorityParamName;
- static const char* kActiveParamName;
-
- virtual ~RenderNode();
-
- // Renders ourself when called and our children if active.
- virtual void Render(RenderContext* render_context) { }
-
- // Renders this render node and all children.
- virtual void RenderTree(RenderContext* render_context);
-
- // Called after render and rendering children.
- virtual void PostRender(RenderContext* render_context) { }
-
- // Gets the priority.
- float priority() const {
- return priority_param_->value();
- }
-
- // Sets the priority.
- void set_priority(float value) {
- priority_param_->set_value(value);
- }
-
- // Gets the draw context.
- bool active() const {
- return active_param_->value();
- }
-
- // Sets the draw context.
- void set_active(bool value) {
- active_param_->set_value(value);
- }
-
- // The actual array of children.
- const RenderNodeRefArray& children() const {
- return child_array_;
- }
-
- // Sets the parent of the render node by re-parenting the node under
- // parent_render_node. Setting parent_render_node to NULL removes the
- // render node and the entire subtree below it from the render graph.
- // The routine will fail if assigning the parent creates a cycle in the
- // parent-child RenderNode graph.
- //
- // NOTE!: When setting the parent to NULL, if results in there being no more
- // references to this render node then this render node will be deleted.
- //
- // Paremeters:
- // parent_render_node: The new parent for the render node or NULL to
- // un-parent the render node.
- void SetParent(RenderNode *parent_render_node);
-
- // Returns the render node's parent.
- // Parameters:
- // None.
- // Returns
- // Pointer to the parent of the rende rnode.
- inline RenderNode* parent() const;
-
- // Returns the immediate children of the render node.
- RenderNodeArray GetChildren() const;
-
- // Returns all the rendernodes in a subtree.
- // Returns this rendernode and all its descendants. Note that this rendernode
- // does not have to be in the rendergraph.
- // Parameters:
- // RenderNodeArray to receive list of nodes. If anything is in
- // the array it will be cleared.
- void GetRenderNodesInTreeFast(RenderNodeArray* render_nodes) const;
-
- // Returns all the rendernodes in a subtree.
- // Returns this rendernode and all its descendants. Note that this
- // rendernode does not have to be in the rendergraph.
- //
- // This is a slower version for javascript. If you are using C++ prefer the
- // version above. This one creates the array on the stack and passes it back
- // by value which means the entire array will get copied twice and in making
- // the copies memory is allocated and deallocated twice.
- //
- // Returns:
- // An array containing pointers to the rendernodes of the subtree.
- RenderNodeArray GetRenderNodesInTree() const;
-
- // Searches for rendernodes that match the given name in the hierarchy under
- // and including this node. Since there can be more than one rendernode with a
- // given name the results are returned in an array.
- // Parameters:
- // name: Rendernode name to look for.
- // render_nodes: RenderNodeArray to receive list of nodes. If anything is in
- // the array it will be cleared.
- void GetRenderNodesByNameInTreeFast(const String& name,
- RenderNodeArray* render_nodes) const;
-
- // Searches for rendernodes that match the given name in the hierarchy under
- // and including this render node. Since there can be more than one rendernode
- // with a given name, results are returned in an array.
- //
- // This is a slower version for javascript. If you are using C++ prefer the
- // version above. This one creates the array on the stack and passes it back
- // by value which means the entire array will get copied twice and in making
- // the copies memory is allocated and deallocated twice.
- //
- // Parameters:
- // name: Rendernode name to look for.
- // Returns:
- // An array of pointers to render nodes matching the given name.
- RenderNodeArray GetRenderNodesByNameInTree(const String& name) const;
-
- // Searches for render nodes that match the given class in the hierarchy under
- // and including this render node.
- // Parameters:
- // class_type: class to look for.
- // Returns:
- // An array of pointers to render nodes matching the given class
- RenderNodeArray GetRenderNodesByClassInTree(
- const ObjectBase::Class* class_type) const;
-
- // Searches for render nodes that match the given class name in the hierarchy
- // under and including this render node.
- // Parameters:
- // class_type_name: name of class to look for
- // Returns:
- // An array of pointers to render nodes matching the given class name
- RenderNodeArray GetRenderNodesByClassNameInTree(
- const String& class_type_name) const;
-
- protected:
- explicit RenderNode(ServiceLocator* service_locator);
-
- // Removes a child render node from the rendernode child list. It does not
- // update the parent of child_node. Note this method is protected and not
- // exposed to the external API as it should not be used to change
- // parent-child relationships. The proper way to re-parent a node is to call
- // RenderNode::SetParent().
- virtual bool RemoveChild(RenderNode *child_node);
-
- // Adds a child render node to the rendernode child list. It does not update
- // the parent of the child. This method is not exposed to the external API and
- // should not be used to change parent-child relationships. The proper way to
- // re-parent a node is to call RenderNode::SetParent().
- virtual bool AddChild(RenderNode *child_node);
-
- private:
- // Renders the children of this render node.
- void RenderChildren(RenderContext* render_context);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamFloat::Ref priority_param_; // For priority sorting.
- ParamBoolean::Ref active_param_; // Should this RenderNode be processed.
-
- RenderNodeRefArray child_array_; // Array of children.
- RenderNode* parent_;
-
- O3D_DECL_CLASS(RenderNode, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(RenderNode);
-};
-
-inline RenderNode* RenderNode::parent() const {
- return parent_;
-}
-
-typedef RenderNode::RenderNodeRefArray RenderNodeRefArray;
-
-typedef RenderNodeRefArray::const_iterator RenderNodeRefArrayConstIterator;
-typedef RenderNodeRefArray::iterator RenderNodeRefArrayIterator;
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_RENDER_NODE_H_
diff --git a/o3d/core/cross/render_node_test.cc b/o3d/core/cross/render_node_test.cc
deleted file mode 100644
index c0ea865..0000000
--- a/o3d/core/cross/render_node_test.cc
+++ /dev/null
@@ -1,135 +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 functionality defined in render_node.cc/h
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/render_node.h"
-#include "core/cross/error_status.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-
-namespace o3d {
-
-// Basic test fixture. Simply creates a Client object
-// before each test and deletes it after
-class RenderNodeBasicTest : public testing::Test {
- protected:
-
- RenderNodeBasicTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus* error_status_;
- Pack *pack_;
-};
-
-void RenderNodeBasicTest::SetUp() {
- error_status_ = new ErrorStatus(g_service_locator);
- pack_ = object_manager_->CreatePack();
-}
-
-void RenderNodeBasicTest::TearDown() {
- object_manager_->DestroyPack(pack_);
- delete error_status_;
-}
-
-// A class deriving from RenderNode with trivial implementations of the pure
-// virtual methods of the RenderNode
-class FakeRenderNode : public RenderNode {
- public:
- explicit FakeRenderNode(ServiceLocator* service_locator)
- : RenderNode(service_locator) {
- }
-
- const String& type() {
- static String kFakeRenderNodeType("FakeRenderNodeType");
- return kFakeRenderNodeType;
- }
-
- void Render(RenderContext *render_context) { }
-};
-
-// Tests RenderNode::SetParent()
-TEST_F(RenderNodeBasicTest, SetParent) {
- // Note: This test assumes that an id of -1 will not alias with ids of nodes
- // created internally by the client.
- FakeRenderNode::Ref render_node(new FakeRenderNode(g_service_locator));
-
- EXPECT_TRUE(NULL == render_node->parent());
-
- RenderNode *parent = pack_->Create<RenderNode>();
- render_node->SetParent(parent);
-
- // Check that the parent pointer was set properly
- EXPECT_EQ(parent, render_node->parent());
-
- // Check that the node was added as a child to the parent transform
- const RenderNodeArray children = parent->GetChildren();
- EXPECT_EQ(1U, children.size());
- EXPECT_EQ(render_node, children[0]);
-
- // Check that SetParent(NULL) works properly too
- render_node->SetParent(NULL);
- EXPECT_EQ(0U, parent->GetChildren().size());
-}
-
-TEST_F(RenderNodeBasicTest, SetParentCyclic) {
- // Note: This test assumes that an id of -1 will not alias with ids of nodes
- // created internally by the client.
- FakeRenderNode::Ref render_node(new FakeRenderNode(g_service_locator));
-
- // Parenting a node to itself must fail.
- error_status_->ClearLastError();
- render_node->SetParent(render_node);
- EXPECT_NE(String(), error_status_->GetLastError());
-
- // Parenting a node creating a cycle containing one or more nodes must fail.
- RenderNode *parent1 = pack_->Create<RenderNode>();
- error_status_->ClearLastError();
- render_node->SetParent(parent1);
- EXPECT_EQ(String(), error_status_->GetLastError());
- parent1->SetParent(render_node);
- EXPECT_NE(String(), error_status_->GetLastError());
-
- RenderNode *parent2 = pack_->Create<RenderNode>();
- error_status_->ClearLastError();
- parent1->SetParent(parent2);
- EXPECT_EQ(String(), error_status_->GetLastError());
- parent2->SetParent(render_node);
- EXPECT_NE(String(), error_status_->GetLastError());
-}
-}
diff --git a/o3d/core/cross/render_surface.cc b/o3d/core/cross/render_surface.cc
deleted file mode 100644
index 8db8f01..0000000
--- a/o3d/core/cross/render_surface.cc
+++ /dev/null
@@ -1,118 +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 "core/cross/render_surface.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(RenderSurfaceBase, ParamObject);
-O3D_DEFN_CLASS(RenderSurface, RenderSurfaceBase);
-O3D_DEFN_CLASS(RenderDepthStencilSurface, RenderSurfaceBase);
-O3D_DEFN_CLASS(ParamRenderSurface, RefParamBase);
-O3D_DEFN_CLASS(ParamRenderDepthStencilSurface, RefParamBase);
-
-const char* RenderSurfaceBase::kWidthParamName =
- O3D_STRING_CONSTANT("width");
-const char* RenderSurfaceBase::kHeightParamName =
- O3D_STRING_CONSTANT("height");
-const char* RenderSurface::kTextureParamName =
- O3D_STRING_CONSTANT("texture");
-
-RenderSurfaceBase::RenderSurfaceBase(ServiceLocator* service_locator,
- int width,
- int height)
- : ParamObject(service_locator),
- clip_width_(width),
- clip_height_(height) {
- RegisterReadOnlyParamRef(kWidthParamName, &width_param_);
- RegisterReadOnlyParamRef(kHeightParamName, &height_param_);
-
- width_param_->set_read_only_value(width);
- height_param_->set_read_only_value(height);
-}
-
-RenderSurface::RenderSurface(ServiceLocator* service_locator,
- int width,
- int height,
- Texture* texture)
- : RenderSurfaceBase(service_locator, width, height),
- weak_pointer_manager_(this) {
- RegisterReadOnlyParamRef(kTextureParamName, &texture_param_);
-
- texture_param_->set_read_only_value(texture);
-}
-
-Bitmap::Ref RenderSurface::GetBitmap() const {
- Bitmap::Ref bitmap = Bitmap::Ref(new Bitmap(service_locator()));
- bitmap->Allocate(Texture::ARGB8,
- clip_width(),
- clip_height(),
- 1,
- Bitmap::IMAGE);
- if (!GetIntoBitmap(bitmap)) {
- Bitmap::Ref empty;
- return empty;
- }
- return bitmap;
-}
-
-bool RenderSurface::GetIntoBitmap(Bitmap::Ref bitmap) const {
- if (bitmap.IsNull() ||
- bitmap->width() != static_cast<unsigned int>(clip_width()) ||
- bitmap->height() != static_cast<unsigned int>(clip_height()) ||
- bitmap->num_mipmaps() != 1 ||
- bitmap->format() != Texture::ARGB8) {
- return false;
- }
-
- return PlatformSpecificGetIntoBitmap(bitmap);
-}
-
-RenderDepthStencilSurface::RenderDepthStencilSurface(
- ServiceLocator* service_locator,
- int width,
- int height)
- : RenderSurfaceBase(service_locator, width, height),
- weak_pointer_manager_(this) {
-}
-
-ObjectBase::Ref ParamRenderSurface::Create(ServiceLocator* client) {
- return ObjectBase::Ref(new ParamRenderSurface(client, false, false));
-}
-
-ObjectBase::Ref ParamRenderDepthStencilSurface::Create(ServiceLocator* client) {
- return ObjectBase::Ref(new ParamRenderDepthStencilSurface(client,
- false,
- false));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/render_surface.h b/o3d/core/cross/render_surface.h
deleted file mode 100644
index 8ee3f01..0000000
--- a/o3d/core/cross/render_surface.h
+++ /dev/null
@@ -1,225 +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 declaration of the RenderSurface render node.
-
-#ifndef O3D_CORE_CROSS_RENDER_SURFACE_H_
-#define O3D_CORE_CROSS_RENDER_SURFACE_H_
-
-#include "core/cross/param.h"
-#include "core/cross/param_object.h"
-#include "core/cross/texture_base.h"
-#include "core/cross/bitmap.h"
-
-namespace o3d {
-
-// RenderSurfaceBase is the base class for RenderSurface and
-// RenderDepthStencilSurface.
-class RenderSurfaceBase : public ParamObject {
- public:
- typedef SmartPointer<RenderSurfaceBase> Ref;
-
- RenderSurfaceBase(ServiceLocator *service_locator,
- int width,
- int height);
-
- // Names of the RenderSurface Params.
- static const char *kWidthParamName;
- static const char *kHeightParamName;
-
- // Returns the width of the surface, in pixels.
- // Note that this is a read-only parameter.
- int width() const {
- return width_param_->value();
- }
-
- // Returns the height of the surface, in pixels.
- // Note that this is a read-only parameter.
- int height() const {
- return height_param_->value();
- }
-
- // Set the clip size, the area of the render target that is actually
- // rendered to.
- // NOTE: This function is not meant to be called by anything except the
- // o3d Client. It is used for rendering screenshots and for windowless
- // mode.
- void SetClipSize(int clip_width, int clip_height) {
- DCHECK_LE(clip_width, width());
- DCHECK_LE(clip_height, height());
- clip_width_ = clip_width;
- clip_height_ = clip_height;
- }
-
- // Returns the used width of the render target. Used for setting the viewport.
- int clip_width() const {
- return clip_width_;
- }
-
- // Returns the used height of the render target. Used for setting the
- // viewport.
- int clip_height() const {
- return clip_height_;
- }
-
- private:
- // The width of the surface, in pixels.
- ParamInteger::Ref width_param_;
-
- // The height of the surface, in pixels.
- ParamInteger::Ref height_param_;
-
- // The part of the render target that is actually used.
- int clip_width_;
- int clip_height_;
-
- O3D_DECL_CLASS(RenderSurfaceBase, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(RenderSurfaceBase);
-};
-
-// A RenderSurface class encapsulates the notion of a renderable surface.
-// When used in conjunction with a RenderSurfaceSet node in the render graph,
-// the API allows for rendering of primitives to the given surface.
-// RenderSurface objects are not constructable through the Pack API, they may
-// only be accessed through the texture GetRenderSurface(...) interfaces.
-class RenderSurface : public RenderSurfaceBase {
- public:
- typedef SmartPointer<RenderSurface> Ref;
- typedef WeakPointer<RenderSurface> WeakPointerType;
-
- RenderSurface(ServiceLocator *service_locator,
- int width,
- int height,
- Texture *texture);
-
- // Names of the RenderSurface Params.
- static const char *kTextureParamName;
-
- // Returns the texture object containing this render surface.
- Texture* texture() const {
- return texture_param_->value();
- }
-
- // Gets a weak pointer to us.
- WeakPointerType GetWeakPointer() const {
- return weak_pointer_manager_.GetWeakPointer();
- }
-
- // Gets a copy of the contents of the render surface as a Bitmap.
- // Only gets the clip_width/clip_height area.
- Bitmap::Ref GetBitmap() const;
-
- // Gets a copy of the contents of the render surface into the given
- // Bitmap. Only gets the clip_width/clip_height area. Returns true
- // if the bitmap was appropriately sized, false if not or if an
- // error occurred.
- bool GetIntoBitmap(Bitmap::Ref bitmap) const;
-
- protected:
- // The platform specific part of GetIntoBitmap.
- virtual bool PlatformSpecificGetIntoBitmap(
- Bitmap::Ref bitmap) const = 0;
-
- private:
- // Texture parameter of the texture in which this render surface is contained.
- ParamTexture::Ref texture_param_;
-
- // Manager for weak pointers to us.
- WeakPointerType::WeakPointerManager weak_pointer_manager_;
-
- O3D_DECL_CLASS(RenderSurface, RenderSurfaceBase);
- DISALLOW_COPY_AND_ASSIGN(RenderSurface);
-};
-
-// A RenderDepthStencilSurface represents a depth stencil render target.
-class RenderDepthStencilSurface : public RenderSurfaceBase {
- public:
- typedef SmartPointer<RenderDepthStencilSurface> Ref;
- typedef WeakPointer<RenderDepthStencilSurface> WeakPointerType;
-
- RenderDepthStencilSurface(ServiceLocator *service_locator,
- int width,
- int height);
-
- // Gets a weak pointer to us.
- WeakPointerType GetWeakPointer() const {
- return weak_pointer_manager_.GetWeakPointer();
- }
-
- private:
- // Manager for weak pointers to us.
- WeakPointerType::WeakPointerManager weak_pointer_manager_;
-
- O3D_DECL_CLASS(RenderDepthStencilSurface, RenderSurfaceBase);
- DISALLOW_COPY_AND_ASSIGN(RenderDepthStencilSurface);
-};
-
-class ParamRenderSurface : public TypedRefParam<RenderSurface> {
- public:
- typedef SmartPointer<ParamRenderSurface> Ref;
-
- ParamRenderSurface(ServiceLocator *service_locator,
- bool dynamic,
- bool read_only)
- : TypedRefParam<RenderSurface>(service_locator, dynamic,
- read_only) {}
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator *service_locator);
-
- O3D_DECL_CLASS(ParamRenderSurface, RefParamBase);
- DISALLOW_COPY_AND_ASSIGN(ParamRenderSurface);
-};
-
-class ParamRenderDepthStencilSurface
- : public TypedRefParam<RenderDepthStencilSurface> {
- public:
- typedef SmartPointer<ParamRenderDepthStencilSurface> Ref;
-
- ParamRenderDepthStencilSurface(ServiceLocator *service_locator,
- bool dynamic,
- bool read_only)
- : TypedRefParam<RenderDepthStencilSurface>(service_locator, dynamic,
- read_only) {}
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator *service_locator);
-
- O3D_DECL_CLASS(ParamRenderDepthStencilSurface, RefParamBase);
- DISALLOW_COPY_AND_ASSIGN(ParamRenderDepthStencilSurface);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_RENDER_SURFACE_H_
diff --git a/o3d/core/cross/render_surface_set.cc b/o3d/core/cross/render_surface_set.cc
deleted file mode 100644
index 7ea058a..0000000
--- a/o3d/core/cross/render_surface_set.cc
+++ /dev/null
@@ -1,112 +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 "core/cross/render_surface_set.h"
-
-#include "core/cross/error.h"
-#include "core/cross/renderer.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(RenderSurfaceSet, RenderNode);
-
-const char* RenderSurfaceSet::kRenderSurfaceParamName =
- O3D_STRING_CONSTANT("renderSurface");
-const char* RenderSurfaceSet::kRenderDepthStencilSurfaceParamName =
- O3D_STRING_CONSTANT("renderDepthStencilSurface");
-
-RenderSurfaceSet::RenderSurfaceSet(ServiceLocator* service_locator)
- : RenderNode(service_locator),
- old_render_surface_(NULL),
- old_depth_stencil_surface_(NULL) {
- RegisterParamRef(kRenderSurfaceParamName, &render_surface_param_);
- RegisterParamRef(kRenderDepthStencilSurfaceParamName,
- &render_depth_stencil_surface_param_);
-}
-
-ObjectBase::Ref RenderSurfaceSet::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new RenderSurfaceSet(service_locator));
-}
-
-bool RenderSurfaceSet::ValidateBoundSurfaces() const {
- RenderSurface *surface = render_surface();
- RenderDepthStencilSurface *depth_stencil_surface =
- render_depth_stencil_surface();
-
- // Validate that at least one surface is assigned.
- if (!(surface || depth_stencil_surface)) {
- O3D_ERROR(service_locator())
- << "RenderSurfaceSet '" << name()
- << "' has neither a surface nor a depth stencil surface. "
- << "It must have at least one.";
- return false;
- }
-
- // If both surfaces are bound, validate that they share the same dimensions.
- if (surface && depth_stencil_surface) {
- if (surface->width() != depth_stencil_surface->width() ||
- surface->height() != depth_stencil_surface->height()) {
- O3D_ERROR(service_locator())
- << "RenderSurfaceSet '" << name()
- << "' has a surface and a depth stencil surface that do not match"
- << " dimensions.";
- return false;
- }
- }
-
- return true;
-}
-
-void RenderSurfaceSet::Render(RenderContext* render_context) {
- if (!ValidateBoundSurfaces()) {
- return;
- }
- render_context->renderer()->GetRenderSurfaces(
- &old_render_surface_,
- &old_depth_stencil_surface_,
- &old_is_back_buffer_);
- render_context->renderer()->SetRenderSurfaces(
- render_surface(),
- render_depth_stencil_surface(),
- false);
-}
-
-void RenderSurfaceSet::PostRender(RenderContext* render_context) {
- if (!ValidateBoundSurfaces()) {
- return;
- }
- render_context->renderer()->SetRenderSurfaces(old_render_surface_,
- old_depth_stencil_surface_,
- old_is_back_buffer_);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/render_surface_set.h b/o3d/core/cross/render_surface_set.h
deleted file mode 100644
index d843df0..0000000
--- a/o3d/core/cross/render_surface_set.h
+++ /dev/null
@@ -1,114 +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 declaration of the RenderSurfaceSet class.
-
-#ifndef O3D_CORE_CROSS_RENDER_SURFACE_SET_H_
-#define O3D_CORE_CROSS_RENDER_SURFACE_SET_H_
-
-#include "core/cross/render_node.h"
-#include "core/cross/render_surface.h"
-
-namespace o3d {
-
-// A RenderSurfaceSet node will bind depth and color RenderSurface nodes
-// to the current rendering context. All RenderNodes descending
-// from the given RenderSurfaceSet node will operate on the contents of
-// the bound depth and color buffers.
-// Note the following usage constraints of this node:
-// 1) The surface bound to render_surface must not be of a depth format.
-// 2) The surface bound to render_depth_surface must be of a depth format.
-// 3) If both a color and depth surface is bound, then they must be of matching
-// dimensions.
-// 4) At least one of render_surface and render_depth_surface must be non-NULL.
-class RenderSurfaceSet : public RenderNode {
- public:
- typedef SmartPointer<RenderSurfaceSet> Ref;
-
- // The names of the RenderSurfaceSet parameters.
- static const char* kRenderSurfaceParamName;
- static const char* kRenderDepthStencilSurfaceParamName;
-
- RenderSurface* render_surface() const {
- return render_surface_param_->value();
- }
-
- // Assigns a render surface to be bound to the color buffer of the active
- // renderer.
- void set_render_surface(RenderSurface* value) {
- render_surface_param_->set_value(value);
- }
-
- RenderDepthStencilSurface* render_depth_stencil_surface() const {
- return render_depth_stencil_surface_param_->value();
- }
-
- // Assigns a render surface to be bound to the depth buffer of the active
- // renderer.
- void set_render_depth_stencil_surface(RenderDepthStencilSurface* value) {
- render_depth_stencil_surface_param_->set_value(value);
- }
-
- // Validates that the surfaces assigned to the depth and color parameters
- // meet the constraints specified above. Returns true if the constraints
- // are satisfied.
- bool ValidateBoundSurfaces() const;
-
- // Overridden from RenderNode. Binds the RenderSurfaces attached to the
- // parameters to the active renderer.
- virtual void Render(RenderContext* render_context);
-
- // Overridden from RenderNode. Restores the depth and color RenderSurfaces
- // associated with the active renderer to their state before the most recent
- // call to RenderSurfaceSet::Render.
- virtual void PostRender(RenderContext* render_context);
-
- private:
- explicit RenderSurfaceSet(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- const RenderSurface* old_render_surface_;
- const RenderDepthStencilSurface* old_depth_stencil_surface_;
- bool old_is_back_buffer_;
-
- ParamRenderSurface::Ref render_surface_param_;
- ParamRenderDepthStencilSurface::Ref render_depth_stencil_surface_param_;
-
- O3D_DECL_CLASS(RenderSurfaceSet, RenderNode)
- DISALLOW_COPY_AND_ASSIGN(RenderSurfaceSet);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_RENDER_SURFACE_SET_H_
diff --git a/o3d/core/cross/render_surface_test.cc b/o3d/core/cross/render_surface_test.cc
deleted file mode 100644
index 5e51e62..0000000
--- a/o3d/core/cross/render_surface_test.cc
+++ /dev/null
@@ -1,273 +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 "core/cross/precompile.h"
-#include "tests/common/win/testing_common.h"
-#include "core/cross/client.h"
-#include "core/cross/pack.h"
-#include "core/cross/renderer.h"
-#include "core/cross/bitmap.h"
-#include "core/cross/features.h"
-#include "core/cross/texture.h"
-#include "core/cross/render_surface.h"
-#include "core/cross/render_surface_set.h"
-#include "core/cross/renderer_platform.h"
-#include "core/cross/error_status.h"
-
-// Defined in testing_common.cc, for each platform.
-extern o3d::DisplayWindow *g_display_window;
-
-namespace o3d {
-
-// A mock render which pushes commands to the renderer so that
-// actual rendering calls that maintain state can be handled by a
-// variable rather than actually rendering.
-class MockRenderer {
- public:
- // Creates a forwarding render class that pushes functionality to be tested
- // to the desired renderer and handles other functionality on its own.
- explicit MockRenderer(Renderer *renderer) : renderer_(renderer) {}
-
- virtual ~MockRenderer() {}
-
- // Rather than actually rendering, this just sets the state in the renderer.
- void StartRendering() {
- renderer_->set_rendering(true);
- }
-
- // This resets the state in the renderer.
- void FinishRendering() {
- renderer_->set_rendering(false);
- }
-
- // Pushes SetRenderSurfaces to the renderer.
- void SetRenderSurfaces(const RenderSurface *surface,
- const RenderDepthStencilSurface *depth_surface,
- bool is_back_buffer) {
- renderer_->SetRenderSurfaces(surface, depth_surface, is_back_buffer);
- }
-
- // Pushes GetRenderSurfaces to the renderer.
- void GetRenderSurfaces(const RenderSurface **surface,
- const RenderDepthStencilSurface **depth_surface,
- bool *is_back_buffer) {
- renderer_->GetRenderSurfaces(surface, depth_surface, is_back_buffer);
- }
- private:
- Renderer *renderer_;
-};
-
-// Class for testing render surfaces and associated functionality.
-class RenderSurfaceTest : public testing::Test {
- public:
- RenderSurfaceTest()
- : object_manager_(g_service_locator),
- error_status_(g_service_locator) {}
-
- protected:
- virtual void SetUp() {
- service_locator_ = new ServiceLocator;
- features_ = new Features(service_locator_);
- pack_ = object_manager_->CreatePack();
- renderer_ = new MockRenderer(g_renderer);
- renderer_->StartRendering();
- }
-
- virtual void TearDown() {
- renderer_->FinishRendering();
- pack_->Destroy();
- error_status_.ClearLastError();
- delete features_;
- delete service_locator_;
- delete renderer_;
- }
-
- ServiceLocator* service_locator() const {
- return service_locator_;
- }
-
- MockRenderer* renderer() const {
- return renderer_;
- }
-
- Pack* pack() const {
- return pack_;
- }
-
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus error_status_;
- ServiceLocator *service_locator_;
- Features *features_;
- Pack *pack_;
- MockRenderer *renderer_;
-};
-
-// Tests that non PoT textures can't make render surfaces.
-TEST_F(RenderSurfaceTest, NonPowerOfTwoRenderSurfaceEnabled) {
- Texture2D *texture = pack()->CreateTexture2D(20, 32, Texture::ARGB8, 2, true);
- ASSERT_TRUE(NULL == texture);
-}
-
-// Tests that a render surface can be created from a texture 2d.
-TEST_F(RenderSurfaceTest, CreateRenderSurfaceFromTexture2D) {
- Texture2D *texture = pack()->CreateTexture2D(16, 32, Texture::ARGB8, 2, true);
- ASSERT_TRUE(NULL != texture);
-
- RenderSurface::Ref render_surface = texture->GetRenderSurface(0);
- ASSERT_TRUE(NULL != render_surface);
- ASSERT_TRUE(NULL != render_surface->texture());
- ASSERT_EQ(render_surface->width(), 16);
- ASSERT_EQ(render_surface->height(), 32);
-}
-
-// Tests that a render surface can be created from a cube texture.
-TEST_F(RenderSurfaceTest, CreateRenderSurfaceFromTextureCUBE) {
- TextureCUBE *texture = pack()->CreateTextureCUBE(16, Texture::ARGB8, 2, true);
- ASSERT_TRUE(NULL != texture);
-
- RenderSurface::Ref render_surface = texture->GetRenderSurface(
- TextureCUBE::FACE_POSITIVE_X, 0);
- ASSERT_TRUE(NULL != render_surface);
- ASSERT_TRUE(NULL != render_surface->texture());
- ASSERT_EQ(render_surface->width(), 16);
- ASSERT_EQ(render_surface->height(), 16);
-}
-
-// Tests the renderer's functionality to swap render surfaces and that
-// the correct render surfaces are set.
-TEST_F(RenderSurfaceTest, SwapRenderSurfaces) {
- Texture2D *texture = pack()->CreateTexture2D(16, 32, Texture::ARGB8, 2, true);
- ASSERT_TRUE(NULL != texture);
-
- RenderSurface::Ref render_surface = texture->GetRenderSurface(0);
- ASSERT_TRUE(NULL != render_surface);
- ASSERT_TRUE(texture == render_surface->texture());
-
- RenderDepthStencilSurface *depth_surface =
- pack()->CreateDepthStencilSurface(16, 32);
-
- // Now swap surfaces.
- renderer()->SetRenderSurfaces(render_surface, depth_surface, false);
- const RenderSurface *test_render_surface = NULL;
- const RenderDepthStencilSurface *test_depth_surface = NULL;
- bool test_is_back_buffer;
- renderer()->GetRenderSurfaces(&test_render_surface, &test_depth_surface,
- &test_is_back_buffer);
- ASSERT_TRUE(test_render_surface == render_surface);
- ASSERT_TRUE(test_depth_surface == depth_surface);
- ASSERT_FALSE(test_is_back_buffer);
-}
-
-// Tests the renderer's functionality to swap render surfaces and return
-// the old one to the main rendering surface.
-TEST_F(RenderSurfaceTest, SetBackSurfaces) {
- Texture2D *texture = pack()->CreateTexture2D(16, 32, Texture::ARGB8, 2, true);
- ASSERT_TRUE(NULL != texture);
-
- RenderSurface::Ref render_surface = texture->GetRenderSurface(0);
- ASSERT_TRUE(NULL != render_surface);
- ASSERT_TRUE(texture == render_surface->texture());
-
- RenderDepthStencilSurface *depth_surface =
- pack()->CreateDepthStencilSurface(16, 32);
-
- // Save the original surfaces for comparison.
- const RenderSurface *original_render_surface = NULL;
- const RenderDepthStencilSurface *original_depth_surface = NULL;
- bool original_is_back_buffer;
- renderer()->GetRenderSurfaces(&original_render_surface,
- &original_depth_surface,
- &original_is_back_buffer);
- // Now swap surfaces.
- renderer()->SetRenderSurfaces(render_surface, depth_surface, false);
- // Return the back buffers
- renderer()->SetRenderSurfaces(NULL, NULL, true);
- // Get the original surfaces again for comparison.
- const RenderSurface *restored_render_surface = NULL;
- const RenderDepthStencilSurface *restored_depth_surface = NULL;
- bool restored_is_back_buffer;
- renderer()->GetRenderSurfaces(&original_render_surface,
- &original_depth_surface,
- &restored_is_back_buffer);
- ASSERT_TRUE(original_render_surface == restored_render_surface);
- ASSERT_TRUE(original_depth_surface == restored_depth_surface);
- ASSERT_TRUE(restored_is_back_buffer);
-}
-
-// Tests the render surfaces interaction as part of a render surface set
-// which is how they are commonly used in practice.
-TEST_F(RenderSurfaceTest, RenderSurfaceSetTest) {
- Texture2D *texture = pack()->CreateTexture2D(16, 32, Texture::ARGB8, 2, true);
- ASSERT_TRUE(NULL != texture);
-
- RenderSurface::Ref render_surface = texture->GetRenderSurface(0);
- ASSERT_TRUE(NULL != render_surface);
- ASSERT_TRUE(texture == render_surface->texture());
-
- RenderDepthStencilSurface *depth_surface =
- pack()->CreateDepthStencilSurface(16, 32);
- ASSERT_TRUE(depth_surface != NULL);
-
- RenderSurfaceSet *render_surface_set = pack()->Create<RenderSurfaceSet>();
- ASSERT_TRUE(render_surface_set != NULL);
- render_surface_set->set_render_surface(render_surface);
- render_surface_set->set_render_depth_stencil_surface(depth_surface);
- ASSERT_TRUE(render_surface_set->ValidateBoundSurfaces());
-
- RenderContext render_context(g_renderer);
-
- const RenderSurface *old_render_surface = NULL;
- const RenderDepthStencilSurface *old_depth_surface = NULL;
- bool old_is_back_buffer = false;
- renderer()->GetRenderSurfaces(&old_render_surface, &old_depth_surface,
- &old_is_back_buffer);
-
- render_surface_set->Render(&render_context);
- const RenderSurface *test_render_surface = NULL;
- const RenderDepthStencilSurface *test_depth_surface = NULL;
- bool test_is_back_buffer = false;
- renderer()->GetRenderSurfaces(&test_render_surface, &test_depth_surface,
- &test_is_back_buffer);
- ASSERT_TRUE(test_render_surface == render_surface);
- ASSERT_TRUE(test_depth_surface == depth_surface);
- ASSERT_FALSE(test_is_back_buffer);
-
- render_surface_set->PostRender(&render_context);
- renderer()->GetRenderSurfaces(&test_render_surface, &test_depth_surface,
- &test_is_back_buffer);
- ASSERT_TRUE(test_render_surface == old_render_surface);
- ASSERT_TRUE(test_depth_surface == old_depth_surface);
- ASSERT_TRUE(test_is_back_buffer == old_is_back_buffer);
-}
-
-} // namespace o3d
-
diff --git a/o3d/core/cross/renderer.cc b/o3d/core/cross/renderer.cc
deleted file mode 100644
index a1d50f1..0000000
--- a/o3d/core/cross/renderer.cc
+++ /dev/null
@@ -1,834 +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.
- */
-
-
-// Define the CreateRenderer() factory function for o3d::Renderer that
-// creates and returns platform specific implementation for the abstract
-// Renderer class.
-
-
-#include "core/cross/renderer.h"
-
-#include "core/cross/client_info.h"
-#include "core/cross/display_window.h"
-#include "core/cross/error.h"
-#include "core/cross/features.h"
-#include "core/cross/param_cache.h"
-#include "core/cross/state.h"
-
-namespace o3d {
-
-const InterfaceId Renderer::kInterfaceId =
- InterfaceTraits<Renderer>::kInterfaceId;
-
-namespace {
-
-class ParamErrorSampler : public ParamSampler {
- public:
- explicit ParamErrorSampler(ServiceLocator* service_locator)
- : ParamSampler(service_locator, true, false),
- renderer_(service_locator->GetService<Renderer>()) {
- }
- // This is only called by the renderer and the user can never gain
- // access to a ParamErrorSampler. The only place it is used is it is put in a
- // ParamCache if a matching sampler is not found so that we can easily supply
- // an error texture.
- // If it's called and error_texture on the client is NULL then generate an
- // error.
- virtual void ComputeValue() {
- if (!renderer_->error_texture()) {
- O3D_ERROR(service_locator()) << "Missing ParamSampler";
- }
- }
-
- private:
- Renderer* renderer_;
-};
-
-// Checks if a texture format is supported. If not generates an error.
-// Returns true if the texture is supported.
-bool IsSupportedTextureFormat(Texture::Format format,
- Features* features,
- ServiceLocator* service_locator) {
- if ((format == Texture::R32F ||
- format == Texture::ABGR16F ||
- format == Texture::ABGR32F) &&
- !features->floating_point_textures()) {
- O3D_ERROR(service_locator)
- << "You can not create a floating point texture unless you request "
- << "support for floating point textures when you initialize O3D.";
- return false;
- }
- return true;
-}
-
-} // anonymous namespace
-
-// Returns whether to Force the Software Renderer by checking for the existence
-// of the environment variable O3D_FORCE_SOFTWARE_RENDERER.
-bool Renderer::IsForceSoftwareRenderer() {
- return getenv("O3D_FORCE_SOFTWARE_RENDERER") != NULL;
-}
-
-Renderer::Renderer(ServiceLocator* service_locator)
- : service_locator_(service_locator),
- service_(service_locator, this),
- features_(service_locator),
- current_render_surface_(NULL),
- current_depth_surface_(NULL),
- current_render_surface_is_back_buffer_(true),
- viewport_(0.0f, 0.0f, 1.0f, 1.0f),
- depth_range_(0.0f, 1.0f),
- write_mask_(0xf),
- render_frame_count_(0),
- transforms_processed_(0),
- transforms_culled_(0),
- draw_elements_processed_(0),
- draw_elements_culled_(0),
- draw_elements_rendered_(0),
- primitives_rendered_(0),
- start_depth_(0),
- clear_client_(true),
- need_to_render_(true),
- rendering_(false),
- drawing_(false),
- width_(0),
- height_(0),
- display_width_(0),
- display_height_(0),
- dest_x_offset_(0),
- dest_y_offset_(0),
- supports_npot_(false),
- back_buffer_cleared_(false),
- presented_once_(false),
- max_fps_(0) {
-}
-
-Renderer::~Renderer() {
- // Delete all the state handlers.
- while (!state_handler_map_.empty()) {
- delete state_handler_map_.begin()->second;
- state_handler_map_.erase(state_handler_map_.begin());
- }
-}
-
-Renderer::InitStatus Renderer::Init(
- const DisplayWindow& display,
- bool off_screen) {
- if (features_->init_status() != Renderer::SUCCESS) {
- return features_->init_status();
- }
-
- return InitPlatformSpecific(display, off_screen);
-}
-
-bool Renderer::ChangeDisplayWindow(const DisplayWindow& display) {
- return false;
-}
-
-void Renderer::InitCommon() {
- AddDefaultStates();
- SetInitialStates();
- error_object_ = ParamObject::Ref(new ParamObject(service_locator_));
- error_sampler_ = CreateSampler();
- Texture2D::Ref texture = CreateTexture2D(8, 8, Texture::XRGB8, 1, false);
- DCHECK(!error_object_.IsNull());
- error_object_->set_name(O3D_STRING_CONSTANT("errorObject"));
- DCHECK(!error_sampler_.IsNull());
- error_sampler_->set_name(O3D_STRING_CONSTANT("errorSampler"));
-
- DCHECK(!texture.IsNull());
- texture->set_name(O3D_STRING_CONSTANT("errorTexture"));
- texture->set_alpha_is_one(true);
- static unsigned char error_texture_data[] = {
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00,
- 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00,
- 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00,
- 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00,
- 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00,
- };
- texture->SetRect(0, 0, 0, 8, 8, error_texture_data, 8 * 4);
-
- error_sampler_->set_mag_filter(Sampler::POINT);
- error_sampler_->set_min_filter(Sampler::POINT);
- error_sampler_->set_mip_filter(Sampler::POINT);
- error_param_sampler_ = ParamSampler::Ref(new ParamErrorSampler(
- service_locator_));
- DCHECK(!error_param_sampler_.IsNull());
- error_object_->AddParam(O3D_STRING_CONSTANT("errorSampler"),
- error_param_sampler_);
- error_param_sampler_->set_dynamic_value(error_sampler_);
- SetErrorTexture(texture);
- fallback_error_texture_ = Texture::Ref(texture.Get());
-}
-
-void Renderer::UninitCommon() {
- error_param_sampler_.Reset();
- error_sampler_.Reset();
- error_texture_.Reset();
- error_object_.Reset();
- fallback_error_texture_.Reset();
- RemoveDefaultStates();
-}
-
-void Renderer::SetSupportsNPOT(bool supports_npot) {
- supports_npot_ = supports_npot;
- ClientInfoManager* client_info_manager =
- service_locator()->GetService<ClientInfoManager>();
- client_info_manager->SetNonPowerOfTwoTextures(supports_npot);
-}
-
-void Renderer::SetLostResourcesCallback(LostResourcesCallback* callback) {
- lost_resources_callback_manager_.Set(callback);
-}
-
-void Renderer::ClearLostResourcesCallback() {
- lost_resources_callback_manager_.Clear();
-}
-
-void Renderer::SetErrorTexture(Texture* texture) {
- error_texture_ = Texture::Ref(texture);
- error_sampler_->set_texture(
- texture ? texture : fallback_error_texture_.Get());
-}
-
-void Renderer::SetClientSize(int width, int height) {
- width_ = width;
- height_ = height;
- display_width_ = width;
- display_height_ = height;
- clear_client_ = true;
-}
-
-bool Renderer::StartRendering() {
- DCHECK_GE(start_depth_, 0);
- bool result = true;
- if (start_depth_ == 0) {
- ++render_frame_count_;
- rendering_ = true;
- transforms_culled_ = 0;
- transforms_processed_ = 0;
- draw_elements_culled_ = 0;
- draw_elements_processed_ = 0;
- draw_elements_rendered_ = 0;
- primitives_rendered_ = 0;
- back_buffer_cleared_ = 0;
- current_render_surface_ = NULL;
- current_depth_surface_ = NULL;
- current_render_surface_is_back_buffer_ = true;
-
- result = PlatformSpecificStartRendering();
- if (result) {
- set_need_to_render(true);
- // Clear the client if we need to.
- if (clear_client_) {
- clear_client_ = false;
- Clear(Float4(0.5f, 0.5f, 0.5f, 1.0f), true, 1.0f, true, 0, true);
- }
- }
- }
- if (result) {
- ++start_depth_;
- }
- return result;
-}
-
-bool Renderer::BeginDraw() {
- DCHECK(rendering_);
- DCHECK(!drawing_);
- bool result = PlatformSpecificBeginDraw();
- if (result) {
- drawing_ = true;
- // Reset the viewport.
- SetViewport(Float4(0.0f, 0.0f, 1.0f, 1.0f), Float2(0.0f, 1.0f));
- }
- return result;
-}
-
-void Renderer::EndDraw() {
- DCHECK(rendering_);
- DCHECK(drawing_);
- ApplyDirtyStates();
- PlatformSpecificEndDraw();
- drawing_ = false;
-}
-
-void Renderer::FinishRendering() {
- DCHECK(rendering_);
- DCHECK(!drawing_);
- DCHECK_GT(start_depth_, 0);
- --start_depth_;
- if (start_depth_ == 0) {
- ApplyDirtyStates();
- PlatformSpecificFinishRendering();
- // Don't hold pointers to these when we are finished rendering.
- current_render_surface_ = NULL;
- current_depth_surface_ = NULL;
- rendering_ = false;
- }
-}
-
-void Renderer::Present() {
- DCHECK(!rendering_);
- DCHECK(!drawing_);
- PlatformSpecificPresent();
- presented_once_ = true;
-}
-
-void Renderer::Clear(const Float4 &color,
- bool color_flag,
- float depth,
- bool depth_flag,
- int stencil,
- bool stencil_flag) {
- // If we are currently rendering to the backbuffer and it has not been cleared
- // AND if we are not about to clear it entirely then clear it.
- bool covers_everything = false;
- if (!back_buffer_cleared_ && current_render_surface_is_back_buffer_) {
- covers_everything =
- !(viewport_[0] != 0.0f || viewport_[1] != 0.0f ||
- viewport_[2] != 1.0f || viewport_[3] != 1.0f ||
- depth_range_[0] != 0.0f || depth_range_[1] != 1.0f) &&
- color_flag && depth_flag && stencil_flag && write_mask_ == 0xF;
- if (!covers_everything) {
- ClearBackBuffer();
- }
- }
-
- ApplyDirtyStates();
- PlatformSpecificClear(
- color, color_flag, depth, depth_flag, stencil, stencil_flag);
-
- // If we are currently rendering to the backbuffer and it has not been cleared
- // and we just cleared everything then mark it as cleared.
- if (!back_buffer_cleared_ && current_render_surface_is_back_buffer_ &&
- covers_everything) {
- back_buffer_cleared_ = true;
- }
-}
-
-void Renderer::ClearBackBuffer() {
- DCHECK(rendering_);
- DCHECK(!back_buffer_cleared_);
- DCHECK(current_render_surface_is_back_buffer_);
-
- // Save all states that would effect clear the back buffer.
- Float4 old_viewport;
- Float2 old_depth_range;
- GetViewport(&old_viewport, &old_depth_range);
-
- // Set the states needed to clear the entire backbuffer.
- SetViewport(Float4(0.0f, 0.0f, 1.0f, 1.0f), Float2(0.0f, 1.0f));
- PushRenderStates(clear_back_buffer_state_);
- ApplyDirtyStates();
-
- // Clear the backbuffer.
- PlatformSpecificClear(
- Float4(0.5f, 0.5f, 0.5f, 1.0f), true,
- 0.0f, true,
- 0, true);
- back_buffer_cleared_ = true;
-
- // restore the states.
- SetViewport(old_viewport, old_depth_range);
- PopRenderStates();
-}
-
-void Renderer::GetViewport(Float4* viewport, Float2* depth_range) {
- DCHECK(viewport);
- DCHECK(depth_range);
- *viewport = viewport_;
- *depth_range = depth_range_;
-}
-
-void Renderer::SetViewport(const Float4& rectangle, const Float2& depth_range) {
- viewport_ = rectangle;
- depth_range_ = depth_range;
- int width = display_width();
- int height = display_height();
- float float_width = static_cast<float>(width);
- float float_height = static_cast<float>(height);
-
- int viewport_left = static_cast<int>(float_width * rectangle[0] + 0.5f);
- int viewport_top = static_cast<int>(float_height * rectangle[1] + 0.5f);
- int viewport_width = static_cast<int>(float_width * rectangle[2] + 0.5f);
- int viewport_height = static_cast<int>(float_height * rectangle[3] + 0.5f);
-
- if (viewport_width < 0) {
- O3D_ERROR(service_locator()) << "attempt to set viewport width < 0";
- viewport_width = 0;
- }
-
- if (viewport_height < 0) {
- O3D_ERROR(service_locator()) << "attempt to set viewport height < 0";
- viewport_height = 0;
- }
-
- if (viewport_left < 0) {
- O3D_ERROR(service_locator()) << "attempt to set viewport left < 0";
- viewport_left = 0;
- }
-
- if (viewport_top < 0) {
- O3D_ERROR(service_locator()) << "attempt to set viewport top < 0";
- viewport_top = 0;
- }
-
- int viewport_right = viewport_left + viewport_width;
- if (viewport_right > width) {
- O3D_ERROR(service_locator()) <<
- "attempt to set viewport left + width to value > 1";
- viewport_width -= viewport_right - width;
- if (viewport_left > width) {
- viewport_left = width;
- viewport_width = 0;
- }
- }
-
- int viewport_bottom = viewport_top + viewport_height;
- if (viewport_bottom > height) {
- O3D_ERROR(service_locator()) <<
- "attempt to set viewport top + height to value > 1";
- viewport_height -= viewport_bottom - height;
- if (viewport_top > height) {
- viewport_top = height;
- viewport_height = 0;
- }
- }
-
- SetViewportInPixels(viewport_left,
- viewport_top,
- viewport_width,
- viewport_height,
- depth_range[0],
- depth_range[1]);
-}
-
-Texture2D::Ref Renderer::CreateTexture2D(int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- if (!IsSupportedTextureFormat(format,
- features_.Get(),
- service_locator())) {
- return Texture2D::Ref(NULL);
- }
- return CreatePlatformSpecificTexture2D(width,
- height,
- format,
- levels,
- enable_render_surfaces);
-}
-
-TextureCUBE::Ref Renderer::CreateTextureCUBE(int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- if (!IsSupportedTextureFormat(format,
- features_.Get(),
- service_locator())) {
- return TextureCUBE::Ref(NULL);
- }
- return CreatePlatformSpecificTextureCUBE(edge_length,
- format,
- levels,
- enable_render_surfaces);
-}
-
-// Creates and returns a ParamCache object
-ParamCache* Renderer::CreateParamCache() {
- // TODO: keep a list of free ParamCache objects to avoid allocations.
- return CreatePlatformSpecificParamCache();
-}
-
-// Frees a Param Cache.
-void Renderer::FreeParamCache(ParamCache* param_cache) {
- // TODO: keep a list of free ParamCache objects to avoid allocations.
- // Note that in order for that to work there must be a ParamCache::Clear()
- // function so that an unused ParamCache releases its references to
- // assets.
- delete param_cache;
-}
-
-void Renderer::AddStateHandler(const String& state_name,
- StateHandler* state_handler) {
- DLOG_ASSERT(state_handler_map_.find(state_name) == state_handler_map_.end())
- << "attempt to add duplicate state handler";
- state_handler->set_index(static_cast<int>(state_handler_map_.size()));
- state_handler_map_.insert(std::make_pair(state_name, state_handler));
- state_param_stacks_.push_back(ParamVector());
-}
-
-const ObjectBase::Class* Renderer::GetStateParamType(
- const String& state_name) const {
- StateHandlerMap::const_iterator iter = state_handler_map_.find(state_name);
- return iter != state_handler_map_.end() ? iter->second->GetClass() : NULL;
-}
-
-// Set initial render states on device creation/reset.
-void Renderer::SetInitialStates() {
- for (StateHandlerMap::iterator it = state_handler_map_.begin();
- it != state_handler_map_.end(); ++it) {
- StateHandler *state_handler = it->second;
- ParamVector& param_stack = state_param_stacks_[state_handler->index()];
- DCHECK_EQ(param_stack.size(), 1u);
- state_handler->SetState(this, param_stack[0]);
- }
-}
-
-template <class ParamType>
-void CreateStateParam(State *state,
- const String &name,
- const typename ParamType::DataType &value) {
- ParamType *param = state->GetStateParam<ParamType>(name);
- DCHECK(param);
- param->set_value(value);
-}
-
-void Renderer::AddDefaultStates() {
- // TODO(gman): It's possible for the user to get these out of the client
- // and then change them which could lead to inconsistent results.
- default_state_ = State::Ref(new State(service_locator_, this));
- default_state_->set_name(O3D_STRING_CONSTANT("defaultState"));
- clear_back_buffer_state_ = State::Ref(new State(service_locator_, this));
- clear_back_buffer_state_->set_name(O3D_STRING_CONSTANT("clearState"));
-
- CreateStateParam<ParamBoolean>(default_state_,
- State::kAlphaTestEnableParamName,
- false);
- CreateStateParam<ParamFloat>(default_state_,
- State::kAlphaReferenceParamName,
- 0.f);
- CreateStateParam<ParamInteger>(default_state_,
- State::kAlphaComparisonFunctionParamName,
- State::CMP_ALWAYS);
- CreateStateParam<ParamInteger>(default_state_,
- State::kCullModeParamName,
- State::CULL_CW);
- CreateStateParam<ParamBoolean>(default_state_,
- State::kDitherEnableParamName,
- false);
- CreateStateParam<ParamBoolean>(default_state_,
- State::kLineSmoothEnableParamName,
- false);
- CreateStateParam<ParamBoolean>(default_state_,
- State::kPointSpriteEnableParamName,
- false);
- CreateStateParam<ParamFloat>(default_state_,
- State::kPointSizeParamName,
- 1.f);
- CreateStateParam<ParamFloat>(default_state_,
- State::kPolygonOffset1ParamName,
- 0.f);
- CreateStateParam<ParamFloat>(default_state_,
- State::kPolygonOffset2ParamName,
- 0.f);
- CreateStateParam<ParamInteger>(default_state_,
- State::kFillModeParamName,
- State::SOLID);
- CreateStateParam<ParamBoolean>(default_state_,
- State::kZEnableParamName,
- true);
- CreateStateParam<ParamBoolean>(default_state_,
- State::kZWriteEnableParamName,
- true);
- CreateStateParam<ParamInteger>(default_state_,
- State::kZComparisonFunctionParamName,
- State::CMP_LESS);
- CreateStateParam<ParamBoolean>(default_state_,
- State::kAlphaBlendEnableParamName,
- false);
- CreateStateParam<ParamBoolean>(default_state_,
- State::kSeparateAlphaBlendEnableParamName,
- false);
- CreateStateParam<ParamInteger>(default_state_,
- State::kSourceBlendFunctionParamName,
- State::BLENDFUNC_ONE);
- CreateStateParam<ParamInteger>(default_state_,
- State::kDestinationBlendFunctionParamName,
- State::BLENDFUNC_ZERO);
- CreateStateParam<ParamInteger>(default_state_,
- State::kBlendEquationParamName,
- State::BLEND_ADD);
- CreateStateParam<ParamInteger>(default_state_,
- State::kSourceBlendAlphaFunctionParamName,
- State::BLENDFUNC_ONE);
- CreateStateParam<ParamInteger>(default_state_,
- State::kDestinationBlendAlphaFunctionParamName,
- State::BLENDFUNC_ZERO);
- CreateStateParam<ParamInteger>(default_state_,
- State::kBlendAlphaEquationParamName,
- State::BLEND_ADD);
- CreateStateParam<ParamBoolean>(default_state_,
- State::kStencilEnableParamName,
- false);
- CreateStateParam<ParamBoolean>(default_state_,
- State::kTwoSidedStencilEnableParamName,
- false);
- CreateStateParam<ParamInteger>(default_state_,
- State::kStencilReferenceParamName,
- 0);
- CreateStateParam<ParamInteger>(default_state_,
- State::kStencilMaskParamName,
- -1);
- CreateStateParam<ParamInteger>(default_state_,
- State::kStencilWriteMaskParamName,
- -1);
- CreateStateParam<ParamInteger>(default_state_,
- State::kStencilFailOperationParamName,
- State::STENCIL_KEEP);
- CreateStateParam<ParamInteger>(default_state_,
- State::kStencilZFailOperationParamName,
- State::STENCIL_KEEP);
- CreateStateParam<ParamInteger>(default_state_,
- State::kStencilPassOperationParamName,
- State::STENCIL_KEEP);
- CreateStateParam<ParamInteger>(default_state_,
- State::kStencilComparisonFunctionParamName,
- State::CMP_ALWAYS);
- CreateStateParam<ParamInteger>(default_state_,
- State::kCCWStencilFailOperationParamName,
- State::STENCIL_KEEP);
- CreateStateParam<ParamInteger>(default_state_,
- State::kCCWStencilZFailOperationParamName,
- State::STENCIL_KEEP);
- CreateStateParam<ParamInteger>(default_state_,
- State::kCCWStencilPassOperationParamName,
- State::STENCIL_KEEP);
- CreateStateParam<ParamInteger>(default_state_,
- State::kCCWStencilComparisonFunctionParamName,
- State::CMP_ALWAYS);
- CreateStateParam<ParamInteger>(default_state_,
- State::kColorWriteEnableParamName,
- 0xf);
- // Check that we have set every state.
- DCHECK_EQ(default_state_->params().size(), state_param_stacks_.size());
-
- // Push the default state on the stack, and every handler on their respective
- // handler stack.
- DCHECK(state_stack_.empty());
- state_stack_.push_back(default_state_);
- const NamedParamRefMap& param_map = default_state_->params();
- NamedParamRefMap::const_iterator end(param_map.end());
- for (NamedParamRefMap::const_iterator iter(param_map.begin());
- iter != end;
- ++iter) {
- Param* param = iter->second.Get();
- const StateHandler* state_handler = GetStateHandler(param);
- DCHECK(state_handler);
- ParamVector& param_stack = state_param_stacks_[state_handler->index()];
- DCHECK(param_stack.empty());
- param_stack.push_back(param);
- }
-
- CreateStateParam<ParamInteger>(clear_back_buffer_state_,
- State::kColorWriteEnableParamName,
- 0xf);
-}
-
-void Renderer::RemoveDefaultStates() {
- DCHECK_EQ(state_stack_.size(), 1u);
- DCHECK(state_stack_[0] == default_state_);
- state_stack_.clear();
- const NamedParamRefMap& param_map = default_state_->params();
- NamedParamRefMap::const_iterator end(param_map.end());
- for (NamedParamRefMap::const_iterator iter(param_map.begin());
- iter != end;
- ++iter) {
- Param* param = iter->second.Get();
- const StateHandler* state_handler = GetStateHandler(param);
- DCHECK(state_handler);
- ParamVector& param_stack = state_param_stacks_[state_handler->index()];
- DCHECK_EQ(param_stack.size(), 1u);
- DCHECK(param_stack[0] == param);
- param_stack.clear();
- }
- default_state_.Reset();
-}
-
-const Renderer::StateHandler* Renderer::GetStateHandler(Param* param) const {
- if (param->handle()) {
- return static_cast<const StateHandler *>((param->handle()));
- } else {
- StateHandlerMap::const_iterator state_handler_map_iter =
- state_handler_map_.find(param->name());
- if (state_handler_map_iter != state_handler_map_.end()) {
- StateHandler* state_handler = state_handler_map_iter->second;
- param->set_handle(state_handler);
- return state_handler;
- }
- }
- return NULL;
-}
-
-void Renderer::RenderElement(Element* element,
- DrawElement* draw_element,
- Material* material,
- ParamObject* override,
- ParamCache* param_cache) {
- ClearBackBufferIfNotCleared();
- IncrementDrawElementsRendered();
- State *current_state = material ? material->state() : NULL;
- PushRenderStates(current_state);
- ApplyDirtyStates();
- element->Render(this, draw_element, material, override, param_cache);
- PopRenderStates();
-}
-
-// Pushes rendering states.
-void Renderer::PushRenderStates(State *state) {
- DCHECK(!state_stack_.empty());
- if (state && (state_stack_.back() != state)) {
- const NamedParamRefMap& param_map = state->params();
- NamedParamRefMap::const_iterator end(param_map.end());
- for (NamedParamRefMap::const_iterator iter(param_map.begin());
- iter != end;
- ++iter) {
- Param* param = iter->second.Get();
- const StateHandler* state_handler = GetStateHandler(param);
- if (state_handler) {
- state_handler->SetState(this, param);
- state_param_stacks_[state_handler->index()].push_back(param);
- }
- }
- }
- // If the state is null, push top state since that's that state
- // that represents our current situation.
- if (!state) {
- state = state_stack_.back();
- }
- state_stack_.push_back(state);
-}
-
-// Pops rendering states to back to their previous settings.
-void Renderer::PopRenderStates() {
- DCHECK_GT(state_stack_.size(), 1u);
- if (state_stack_.back() != state_stack_[state_stack_.size() - 2]) {
- State* state = state_stack_.back();
- // restore the states the top state object set.
- const NamedParamRefMap& param_map = state->params();
- NamedParamRefMap::const_iterator end(param_map.end());
- for (NamedParamRefMap::const_iterator iter(param_map.begin());
- iter != end;
- ++iter) {
- Param* param = iter->second.Get();
- const StateHandler* state_handler = GetStateHandler(param);
- if (state_handler) {
- ParamVector& param_stack = state_param_stacks_[state_handler->index()];
- DCHECK(param_stack.back() == param);
- param_stack.pop_back();
- DCHECK(!param_stack.empty());
- state_handler->SetState(this, param_stack.back());
- }
- }
- }
- state_stack_.pop_back();
-}
-
-void Renderer::SetRenderSurfaces(
- const RenderSurface* surface,
- const RenderDepthStencilSurface* depth_surface,
- bool is_back_buffer) {
- DCHECK(rendering_);
- current_render_surface_is_back_buffer_ = is_back_buffer;
- if (surface != NULL || depth_surface != NULL) {
- SetRenderSurfacesPlatformSpecific(surface, depth_surface);
- current_render_surface_ = surface;
- current_depth_surface_ = depth_surface;
- if (surface) {
- display_width_ = surface->clip_width();
- display_height_ = surface->clip_height();
- } else {
- display_width_ = depth_surface->clip_width();
- display_height_ = depth_surface->clip_height();
- }
- } else {
- SetBackBufferPlatformSpecific();
- current_render_surface_ = NULL;
- current_depth_surface_ = NULL;
- display_width_ = width();
- display_height_ = height();
- }
- // We must reset the viewport after each change in surfaces.
- SetViewport(viewport_, depth_range_);
-}
-
-void Renderer::GetRenderSurfaces(
- const RenderSurface** surface,
- const RenderDepthStencilSurface** depth_surface,
- bool* is_back_buffer) {
- DCHECK(rendering_);
- DCHECK(surface);
- DCHECK(depth_surface);
- DCHECK(is_back_buffer);
- *surface = current_render_surface_;
- *depth_surface = current_depth_surface_;
- *is_back_buffer = current_render_surface_is_back_buffer_;
-}
-
-bool Renderer::SafeToBindTexture(Texture* texture) const {
- if (current_render_surface_ &&
- current_render_surface_->texture() == texture) {
- return false;
- }
-
- return true;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/renderer.h b/o3d/core/cross/renderer.h
deleted file mode 100644
index 1970833..0000000
--- a/o3d/core/cross/renderer.h
+++ /dev/null
@@ -1,799 +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 declaration for the Renderer class.
-
-#ifndef O3D_CORE_CROSS_RENDERER_H_
-#define O3D_CORE_CROSS_RENDERER_H_
-
-#include <utility>
-#include <vector>
-
-#include "core/cross/bitmap.h"
-#include "core/cross/buffer.h"
-#include "core/cross/callback.h"
-#include "core/cross/display_mode.h"
-#include "core/cross/display_window.h"
-#include "core/cross/draw_element.h"
-#include "core/cross/effect.h"
-#include "core/cross/lost_resource_callback.h"
-#include "core/cross/primitive.h"
-#include "core/cross/sampler.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/service_implementation.h"
-#include "core/cross/shape.h"
-#include "core/cross/state.h"
-#include "core/cross/texture.h"
-#include "core/cross/types.h"
-#include "core/cross/vector_map.h"
-
-namespace o3d {
-
-class Material;
-class RenderSurface;
-class Features;
-
-// The Renderer class provides the abstract interface for the draw calls
-// that need to be implemented for each platform. Renderer objects can be
-// created independently of the Client object that uses them.
-//
-// The creation and deletion order of an o3d::Client using a
-// o3d::Renderer object should be:
-//
-// renderer = Renderer::CreateDefaultRenderer(&service_locator_);
-//
-// // PlatformInit isn't a Renderer API -- You define a function
-// // for your platform to return an appropriate display window.
-// DisplayWindow* display = PlatformInit();
-//
-// if (renderer->Init(display, true)) {
-// client = new Client();
-// client->Init();
-//
-// ...
-//
-// delete client; // unbinds renderer from client
-// renderer->Destroy(); // deletes graphics contexts
-// delete renderer;
-// }
-
-class Renderer {
- public:
- static const InterfaceId kInterfaceId;
-
- // These are in order of best to worst except for UNINITIALIZED which is
- // zero on purpose.
- //
- // Note: Do not change the values of these constants as they can be hard coded
- // in javascript. You can update them in o3djs/util.js but if you change them
- // you'll potentially break any app that is not using o3djs/util.js.
- enum InitStatus {
- UNINITIALIZED,
- SUCCESS,
- OUT_OF_RESOURCES,
- GPU_NOT_UP_TO_SPEC,
- INITIALIZATION_ERROR,
- };
-
- // This is exposed to JavaScript, but as long as users always refer to it
- // symbolically, it should be possible to change it without breaking anyone.
- // NOTE: windows d3d display modes are internally implemented via adding 1 to
- // their normal values of [0, NUM) so as not to collide with this value.
- enum DisplayModes {
- DISPLAY_MODE_DEFAULT = 0
- };
-
- enum RenderMode {
- RENDER_MODE_AUTO,
- RENDER_MODE_3D,
- RENDER_MODE_2D,
- };
-
- // A StateHandler takes a param and sets or resets a render state.
- class StateHandler {
- public:
- StateHandler() : index_(-1) { }
- virtual ~StateHandler() { } // Needed because we are a base class.
-
- // Gets Class of State's Parameter
- virtual const ObjectBase::Class* GetClass() const = 0;
-
- // Sets the state to the value of the param.
- // Parameters:
- // renderer: the renderer
- // param: param with state data
- virtual void SetState(Renderer* renderer, Param* param) const = 0;
-
- // Returns the index of this state handler.
- int index() const {
- return index_;
- }
-
- // Sets the index of this state handler.
- void set_index(int index) {
- DLOG_ASSERT(index_ < 0); // Can only be set once.
- index_ = index;
- }
-
- private:
- int index_;
- };
-
- virtual ~Renderer();
-
- // Creates a 'default' renderer, choosing the correct implementation type.
- static Renderer* CreateDefaultRenderer(ServiceLocator* service_locator);
-
- // Creates a 2D renderer. This can be used instead of CreateDefaultRenderer
- // when 3D is not supported by the underlying system, and is not strictly
- // needed by the application.
- static Renderer* Create2DRenderer(ServiceLocator* service_locator);
-
- // Gets whether or not the renderer should attempt to use the software
- // renderer.
- static bool IsForceSoftwareRenderer();
-
- // Initialises the renderer for use, claiming hardware resources.
- InitStatus Init(const DisplayWindow& display, bool off_screen);
-
- // Switch rendering to a different window after initialization (if supported
- // by the implementation).
- virtual bool ChangeDisplayWindow(const DisplayWindow& display);
-
- // Initializes stuff that has to happen after Init
- virtual void InitCommon();
-
- // Frees anything related to the client and clears the client.
- virtual void UninitCommon();
-
- // Releases all hardware resources. This should be called before destroying
- // the window used for rendering. It will be called automatically from the
- // destructor.
- // Destroy() should be called before Init() is called again.
- virtual void Destroy() = 0;
-
- // Prepares the rendering device for subsequent draw calls.
- // This is called during a RenderTree and can be called mutliple times
- // during a single frame.
- // NOTE: See StartRendering!
- bool BeginDraw();
-
- // This is called during a RenderTree and can be called mutliple times during
- // a single frame. It gives the renderer a chance to flush state before
- // returning to JavaScript if JavaScript is calling RenderTree directly.
- // NOTE: See StartRendering!
- void EndDraw();
-
- // Does any pre-rendering preparation.
- // The order of operations is
- // StartRendering()
- // BeginDraw();
- // EndDraw()
- // BeginDraw();
- // EndDraw()
- // BeginDraw();
- // EndDraw()
- // FinishRendering(); // <- Presents the results.
- bool StartRendering();
-
- // Presents the results of the draw calls for this frame.
- void FinishRendering();
-
- // Copy the contents of the backbuffer to the window.
- void Present();
-
- // Returns whether a render is required.
- bool need_to_render() const {
- return need_to_render_;
- }
-
- // Invalidate the last rendered frame.
- void set_need_to_render(bool need_to_render) {
- need_to_render_ = need_to_render;
- }
-
- // When max_fps is set to positive value, we render on every new texture as
- // long as not exceeding max_fps.
-
- // Get max_fps
- int max_fps() const {
- return max_fps_;
- }
-
- // Set max_fps
- void set_max_fps(int max_fps) {
- max_fps_ = max_fps;
- }
-
- // Handles the plugin resize event.
- virtual void Resize(int width, int height) = 0;
-
- // Turns fullscreen display on.
- // Parameters:
- // display: a platform-specific display identifier
- // mode_id: a mode returned by GetDisplayModes
- // Returns true on success, false on failure.
- virtual bool GoFullscreen(const DisplayWindow& display,
- int mode_id) = 0;
-
- // Cancels fullscreen display. Restores rendering to windowed mode
- // with the given width and height.
- // Parameters:
- // display: a platform-specific display identifier
- // width: the width to which to restore windowed rendering
- // height: the height to which to restore windowed rendering
- // Returns true on success, false on failure.
- virtual bool CancelFullscreen(const DisplayWindow& display,
- int width, int height) = 0;
-
- // Tells whether we're currently displayed fullscreen or not.
- virtual bool fullscreen() const = 0;
-
- // Get a vector of the available fullscreen display modes.
- // Clears *modes on error.
- virtual void GetDisplayModes(std::vector<DisplayMode> *modes) = 0;
-
- // Get a single fullscreen display mode by id.
- // Returns true on success, false on error.
- virtual bool GetDisplayMode(int id, DisplayMode *mode) = 0;
-
- // Gets the viewport.
- void GetViewport(Float4* rectangle, Float2* depth_range);
-
- // Sets the viewport.
- // Parameters:
- // rectangle: The position and size to set the viewport in
- // Float4(left, top, width, height) format. The default values are (0.0,
- // 0.0, 1.0, 1.0). In other words, the full area. The viewport provides
- // the mapping of the clip space coordinates into normalized screen
- // coordinates.
- // depth_range:
- // The min Z and max Z depth range in Float2(min Z, max Z) format. The
- // default values are (0.0, 1.0). The depth range provides the mapping of
- // the clip space coordinates into normalized z buffer coordinates.
- //
- // Note: The rectangle values must describe a rectangle that is 100% inside
- // the client area. In other words, (0.5, 0.0, 1.0, 1.0) would describe an
- // area that is 1/2 off right side of the screen. That is an invalid value and
- // will be clipped to (0.5, 0.0, 0.5, 1.0).
- void SetViewport(const Float4& rectangle, const Float2& depth_range);
-
- // Clears the current buffers.
- void Clear(const Float4 &color,
- bool color_flag,
- float depth,
- bool depth_flag,
- int stencil,
- bool stencil_flag);
-
- // Renders this Element using the parameters from override first, followed by
- // the draw_element, followed by params on this Primitive and material.
- // Parameters:
- // element: Element to draw
- // draw_element: DrawElement to override params with.
- // material: Material to render with.
- // override: Override to render with.
- void RenderElement(Element* element,
- DrawElement* draw_element,
- Material* material,
- ParamObject* override,
- ParamCache* param_cache);
-
- // Pushes rendering states.
- virtual void PushRenderStates(State *state);
-
- // Pops rendering states to back to their previous settings.
- virtual void PopRenderStates();
-
- // Binds the passed surfaces to the color and depth buffers of the
- // renderer.
- // Parameters:
- // surface: RenderSurface to bind to the color buffer.
- // depth_surface: RenderDepthStencilSurface to bind to the depth/stencil
- // buffer.
- // is_back_buffer: True if the render surface being set should be considered
- // the backbuffer.
- void SetRenderSurfaces(const RenderSurface* surface,
- const RenderDepthStencilSurface* depth_surface,
- bool is_back_buffer);
-
- // Gets the current render surfaces.
- // Parameters:
- // surface: pointer to variable to hold RenderSurface to bind to the color
- // buffer.
- // depth_surface: pointer to variable to hold RenderDepthStencilSurface to
- // bind to the depth/stencil buffer.
- // is_back_buffer: pointer to variable to hold whether or not the surface
- // returned is the back buffer.
- void GetRenderSurfaces(const RenderSurface** surface,
- const RenderDepthStencilSurface** depth_surface,
- bool* is_back_buffer);
-
- // Creates a StreamBank, returning a platform specific implementation class.
- virtual StreamBank::Ref CreateStreamBank() = 0;
-
- // Creates a Primitive, returning a platform specific implementation class.
- virtual Primitive::Ref CreatePrimitive() = 0;
-
- // Creates a DrawElement, returning a platform specific implementation
- // class.
- virtual DrawElement::Ref CreateDrawElement() = 0;
-
- // Creates and returns a platform specific float buffer
- virtual VertexBuffer::Ref CreateVertexBuffer() = 0;
-
- // Creates and returns a platform specific integer buffer
- virtual IndexBuffer::Ref CreateIndexBuffer() = 0;
-
- // Creates and returns a platform specific effect object
- virtual Effect::Ref CreateEffect() = 0;
-
- // Creates and returns a platform specific Sampler object.
- virtual Sampler::Ref CreateSampler() = 0;
-
- // Creates and returns a ParamCache object
- ParamCache* CreateParamCache();
-
- // Frees a Param Cache.
- void FreeParamCache(ParamCache* param_cache);
-
- // Creates and returns a platform specific Texture2D object. It allocates
- // the necessary resources to store texture data for the given image size
- // and format.
- Texture2D::Ref CreateTexture2D(int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
- // Creates and returns a platform specific TextureCUBE object. It allocates
- // the necessary resources to store texture data for the given image size
- // and format.
- TextureCUBE::Ref CreateTextureCUBE(int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
- // Sets the lost resources callback.
- // NOTE: The client takes ownership of the LostResourcesCallback you pass in.
- // It will be deleted if you call SetLostResourcesCallback a second time or if
- // you call ClearLostResourcesCallback
- //
- // Parameters:
- // callback: LostResourcesCallback to call each frame.
- void SetLostResourcesCallback(LostResourcesCallback* callback);
-
- // Clears the lost resources callback
- // NOTE: The client takes ownership of the LostResourcesCallback you pass in
- // to SetLostResourcesCallback. It will be deleted if you call
- // SetLostResourcesCallback a second time or if you call
- // ClearLostResourcesCallback.
- void ClearLostResourcesCallback();
-
- // Creates and returns a platform-specific RenderDepthStencilSurface object
- // for use as a depth-stencil render target.
- virtual RenderDepthStencilSurface::Ref CreateDepthStencilSurface(
- int width,
- int height) = 0;
-
-#ifdef OS_MACOSX
- virtual bool SupportsCoreGraphics() const { return false; }
-#endif
-
- ServiceLocator* service_locator() const { return service_locator_; }
-
- // Returns the type of Param needed for a particular state.
- const ObjectBase::Class* GetStateParamType(const String& state_name) const;
-
- // Whether we are currently rendering (between StartRendering /
- // FinishRendering calls).
- // NOTE: See StartRendering!
- bool rendering() const {
- return rendering_;
- }
-
- // Whether we are currently drawing (between BeginDraw / EndDraw calls).
- // NOTE: See StartRendering!
- bool drawing() const {
- return drawing_;
- }
-
- // Get the client area's width.
- int width() const {
- return width_;
- }
-
- // Get the client area's height.
- int height() const {
- return height_;
- }
-
- // Get the width of the buffer to which the renderer is drawing.
- int display_width() const {
- return display_width_;
- }
-
- // Get the height of the buffer to which the renderer is drawing.
- int display_height() const {
- return display_height_;
- }
-
- // Whether or not the underlying API (D3D or OpenGL) supports
- // non-power-of-two textures.
- bool supports_npot() const {
- return supports_npot_;
- }
-
- // Gets the number of times we've rendered a frame.
- int render_frame_count() const {
- return render_frame_count_;
- }
-
- int transforms_processed() const {
- return transforms_processed_;
- }
-
- int transforms_culled() const {
- return transforms_culled_;
- }
-
- int draw_elements_processed() const {
- return draw_elements_processed_;
- }
-
- int draw_elements_culled() const {
- return draw_elements_culled_;
- }
-
- int draw_elements_rendered() const {
- return draw_elements_rendered_;
- }
-
- int primitives_rendered() const {
- return primitives_rendered_;
- }
-
- void IncrementTransformsProcessed() {
- ++transforms_processed_;
- }
-
- void IncrementTransformsCulled() {
- ++transforms_culled_;
- }
-
- void IncrementDrawElementsProcessed() {
- ++draw_elements_processed_;
- }
-
- void IncrementDrawElementsCulled() {
- ++draw_elements_culled_;
- }
-
- void IncrementDrawElementsRendered() {
- ++draw_elements_rendered_;
- }
-
- void AddPrimitivesRendered(int amount_to_add) {
- primitives_rendered_ += amount_to_add;
- }
-
- Sampler* error_sampler() const {
- return error_sampler_.Get();
- }
-
- Texture* error_texture() const {
- return error_texture_.Get();
- }
-
- Texture* fallback_error_texture() const {
- return fallback_error_texture_.Get();
- }
-
- ParamSampler* error_param_sampler() const {
- return error_param_sampler_.Get();
- }
-
- // Sets the texture use when a texture is missing. May be NULL.
- void SetErrorTexture(Texture* texture);
-
- // Determine if the Texture argument is safe to use in an effect.
- // If a RenderSurface contained within the texture is currently bound to the
- // renderer, then it is not safe to bind the texture.
- bool SafeToBindTexture(Texture* texture) const;
-
- // When rendering only part of the view because of scrolling or the window
- // being smaller than the client size, etc, this lets us adjust the origin of
- // the top left of the drawing within our area, effectively allowing us to
- // scroll within that area. Vars dest_x_offset_ and dest_y_offset_ will be 0
- // in the unclipped case, positive numbers if we are clipping the left or the
- // top respectively. Only currently used on Mac, only currently respected by
- // the GL renderer.
- void SetClientOriginOffset(int x, int y) {
- dest_x_offset_ = x;
- dest_y_offset_ = y;
- }
-
- // Returns a platform specific 4 element swizzle table for RGBA UByteN fields.
- // The should contain the index of R, G, B, and A in that order for the
- // current platform.
- virtual const int* GetRGBAUByteNSwizzleTable() = 0;
-
- // Used only for unit testing purposes. Should not be used elsewhere.
- void set_rendering(bool rendering) {
- rendering_ = rendering;
- }
-
- // Used only by the ColorWriteEnable state handlers. Should not be used
- // elsewhere.
- // Sets the write mask. This must be called by platform specific renderers
- // when the color write mask is changed.
- void SetWriteMask(int mask) {
- write_mask_ = mask & 0xF;
- }
-
- // Indicates whether this Renderer has yet presented to the screen.
- bool presented_once() {
- return presented_once_;
- }
-
- protected:
- typedef vector_map<String, StateHandler*> StateHandlerMap;
- typedef std::vector<ParamVector> ParamVectorArray;
- typedef std::vector<State*> StateArray;
-
- // Make the constructor protected so that users can only create one
- // using the CreateDefaultRenderer factory method.
- explicit Renderer(ServiceLocator* service_locator);
-
- // Sets whether or not the renderer supports non-power of 2 textures.
- void SetSupportsNPOT(bool supports_npot);
-
- // Adds a state handler to the state handler map
- // Parameters:
- // state_name: Name of the state.
- // state_handler: a concrete state handler.
- void AddStateHandler(const String& state_name, StateHandler* state_handler);
-
- // Gets a state handler based on a Param
- // Parameters:
- // param: Param who's name matches a state.
- // Returns:
- // StateHandler of matching state.
- const StateHandler* GetStateHandler(Param* param) const;
-
- // Resets all states to their defaults.
- void SetInitialStates();
-
- // Returns true if the renderer is presently drawing to a RenderSurface,
- // false if the renderer is drawing to the client area.
- bool RenderSurfaceActive() const {
- return current_render_surface_ != NULL;
- }
-
- // Sets rendering to the back buffer.
- virtual void SetBackBufferPlatformSpecific() = 0;
-
- // Sets the render surfaces on a specific platform.
- virtual void SetRenderSurfacesPlatformSpecific(
- const RenderSurface* surface,
- const RenderDepthStencilSurface* depth_surface) = 0;
-
- // Creates a platform specific ParamCache.
- virtual ParamCache* CreatePlatformSpecificParamCache() = 0;
-
- // Platform specific version of CreateTexture2D
- virtual Texture2D::Ref CreatePlatformSpecificTexture2D(
- int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) = 0;
-
- // Platform specific version of CreateTextureCUBE.
- virtual TextureCUBE::Ref CreatePlatformSpecificTextureCUBE(
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) = 0;
-
- // The platform specific part of BeginDraw.
- virtual bool PlatformSpecificBeginDraw() = 0;
-
- // The platform specific part of EndDraw.
- virtual void PlatformSpecificEndDraw() = 0;
-
- // The platform specific part of StartRendering.
- virtual bool PlatformSpecificStartRendering() = 0;
-
- // The platform specific part of EndRendering.
- virtual void PlatformSpecificFinishRendering() = 0;
-
- // The platform specific part of Present.
- virtual void PlatformSpecificPresent() = 0;
-
- // The platform specific part of Clear.
- virtual void PlatformSpecificClear(const Float4 &color,
- bool color_flag,
- float depth,
- bool depth_flag,
- int stencil,
- bool stencil_flag) = 0;
-
- // Applies states that have been modified (marked dirty).
- virtual void ApplyDirtyStates() = 0;
-
- // Sets the viewport. This is the platform specific version.
- virtual void SetViewportInPixels(int left,
- int top,
- int width,
- int height,
- float min_z,
- float max_z) = 0;
-
- // Sets the client's size. Derived classes must call this on Init and Resize.
- void SetClientSize(int width, int height);
-
- // Calls any registered lost resources callback.
- void CallLostResourcesCallback() const {
- lost_resources_callback_manager_.Run();
- }
-
- int dest_x_offset() const {
- return dest_x_offset_;
- }
-
- int dest_y_offset() const {
- return dest_y_offset_;
- }
-
- Features* features() const {
- return features_.Get();
- }
-
- private:
- // The platform specific part of initalization.
- virtual InitStatus InitPlatformSpecific(const DisplayWindow& display,
- bool off_screen) = 0;
-
- // Adds the default states to their respective stacks.
- void AddDefaultStates();
-
- // Removes the default states from their respective stacks.
- void RemoveDefaultStates();
-
- // Clears the backbuffer.
- void ClearBackBuffer();
-
- // Clears the backbuffer if it has not been cleared.
- void ClearBackBufferIfNotCleared() {
- if (!back_buffer_cleared_ && current_render_surface_is_back_buffer_) {
- ClearBackBuffer();
- }
- }
-
- ServiceLocator* service_locator_;
- ServiceImplementation<Renderer> service_;
- ServiceDependency<Features> features_;
-
- // The current render surfaces. NULL = no surface.
- const RenderSurface* current_render_surface_;
- const RenderDepthStencilSurface* current_depth_surface_;
- bool current_render_surface_is_back_buffer_;
-
- Sampler::Ref error_sampler_; // sampler used when one is missing.
- Texture::Ref error_texture_; // texture used when one is missing.
- Texture::Ref fallback_error_texture_; // texture used when error_texture is
- // null.
- ParamObject::Ref error_object_; // holds params used for missing textures.
- ParamSampler::Ref error_param_sampler_; // A Param for the error sampler.
-
- // Map of State Handlers.
- StateHandlerMap state_handler_map_;
-
- // Stack of state params
- ParamVectorArray state_param_stacks_;
-
- // Stack of state objects.
- StateArray state_stack_;
-
- // State object holding the default state settings.
- State::Ref default_state_;
-
- // A State object holding the settings required to be able to clear the
- // back buffer.
- State::Ref clear_back_buffer_state_;
-
- // Lost Resources Callbacks.
- LostResourcesCallbackManager lost_resources_callback_manager_;
-
- // Current viewport setting.
- Float4 viewport_;
-
- // Current depth range.
- Float2 depth_range_;
-
- // Current write mask.
- int write_mask_;
-
- int render_frame_count_; // count of times we've rendered frame.
- int transforms_processed_; // count of transforms processed this frame.
- int transforms_culled_; // count of transforms culled this frame.
- int draw_elements_processed_; // count of draw elements processed this frame.
- int draw_elements_culled_; // count of draw elements culled this frame.
- int draw_elements_rendered_; // count of draw elements culled this frame.
- int primitives_rendered_; // count of primitives (tris, lines)
- // rendered this frame.
-
- // The depth of times we've called StartRendering/FinishRenderering.
- int start_depth_;
-
- // Whether we need to clear the entire client area next render.
- bool clear_client_;
-
- // Whether a render is required.
- bool need_to_render_;
-
- // Whether we are currently rendering (between StartRendering /
- // FinishRendering calls)
- bool rendering_;
-
- // Whether or not we are drawing (between BeingDraw/EndDraw calls)
- bool drawing_;
-
- int width_; // width of the client area in pixels
- int height_; // height of the client area in pixels
-
- int display_width_; // width of the thing we are rendering to.
- int display_height_; // height of the thing we are rendering to.
-
- // X and Y offsets for destination rectangle.
- int dest_x_offset_;
- int dest_y_offset_;
-
- // Whether or not the underlying API supports non-power-of-two textures.
- bool supports_npot_;
-
- // Whether the backbuffer has been cleared this frame.
- bool back_buffer_cleared_;
-
- // Whether we have ever completed a call to Present().
- bool presented_once_;
-
- // Maximum frames per second.
- int max_fps_;
-
- DISALLOW_COPY_AND_ASSIGN(Renderer);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_RENDERER_H_
diff --git a/o3d/core/cross/renderer_platform.h b/o3d/core/cross/renderer_platform.h
deleted file mode 100644
index ba85fb9..0000000
--- a/o3d/core/cross/renderer_platform.h
+++ /dev/null
@@ -1,82 +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 include determines which renderer to include, based on the
-// compile options, so that this is the only place that needs to know
-// what all the choices are.
-
-#ifndef O3D_CORE_CROSS_RENDERER_PLATFORM_H_
-#define O3D_CORE_CROSS_RENDERER_PLATFORM_H_
-
-#include <build/build_config.h>
-#if defined(OS_MACOSX)
-#include "core/cross/gl/gl_headers.h"
-#include <OpenGL/OpenGL.h>
-#include <AGL/agl.h>
-#elif defined(OS_LINUX)
-#if defined(RENDERER_GL)
-#include "core/cross/gl/gl_headers.h"
-#include <GL/glx.h>
-#elif defined(RENDERER_GLES2)
-#include "core/cross/gles2/gles2_headers.h"
-#endif
-#elif defined(OS_WIN) && defined(RENDERER_GL)
-#include "core/cross/gl/gl_headers.h"
-#include <gl/GL.h>
-#elif defined(OS_WIN) && defined(RENDERER_GLES2)
-#include "core/cross/gles2/gles2_headers.h"
-#include <gl/GL.h>
-#endif
-
-#if defined(OS_WIN)
-#include "core/win/display_window_win.h"
-#elif defined(OS_MACOSX)
-#include "core/mac/display_window_mac.h"
-#elif defined(OS_LINUX)
-#include "core/linux/display_window_linux.h"
-#else
-#error Platform not recognized.
-#endif
-
-#include "core/cross/cairo/renderer_cairo.h"
-
-#if defined(RENDERER_D3D9) && defined(OS_WIN)
-#include "core/win/d3d9/renderer_d3d9.h"
-#elif defined(RENDERER_GL)
-#include "core/cross/gl/renderer_gl.h"
-#elif defined(RENDERER_GLES2)
-#include "core/cross/gles2/renderer_gles2.h"
-#else
-#error Renderer not recognized.
-#endif
-
-#endif // O3D_CORE_CROSS_RENDERER_PLATFORM_H_
diff --git a/o3d/core/cross/renderer_test.cc b/o3d/core/cross/renderer_test.cc
deleted file mode 100644
index 9eb0942..0000000
--- a/o3d/core/cross/renderer_test.cc
+++ /dev/null
@@ -1,191 +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 "tests/common/win/testing_common.h"
-#include "core/cross/client.h"
-#include "core/cross/client_info.h"
-#include "core/cross/renderer.h"
-#include "core/cross/bitmap.h"
-#include "core/cross/features.h"
-#include "core/cross/texture.h"
-#include "core/cross/renderer_platform.h"
-
-// Defined in testing_common.cc, for each platform.
-extern o3d::DisplayWindow* g_display_window;
-
-namespace o3d {
-
-class RendererTest : public testing::Test {
- public:
- ServiceLocator* service_locator() {
- return service_locator_;
- }
-
- protected:
- virtual void SetUp() {
- service_locator_ = new ServiceLocator;
- features_ = new Features(service_locator_);
- client_info_manager_ = new ClientInfoManager(service_locator_);
- }
-
- virtual void TearDown() {
- delete client_info_manager_;
- delete features_;
- delete service_locator_;
- }
-
- ServiceLocator* service_locator_;
- Features* features_;
- ClientInfoManager* client_info_manager_;
-};
-
-// This tests that a default Renderer can be created.
-TEST_F(RendererTest, CreateDefaultRenderer) {
- scoped_ptr<Renderer> renderer(
- Renderer::CreateDefaultRenderer(service_locator()));
- EXPECT_TRUE(renderer != NULL);
-}
-
-
-
-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.
- scoped_ptr<Renderer> renderer(
- Renderer::CreateDefaultRenderer(service_locator()));
- EXPECT_TRUE(renderer->Init(*g_display_window, false));
-#if defined(RENDERER_D3D9)
- // test that the d3d_device was correctly created
- RendererD3D9* d3d_renderer = down_cast<RendererD3D9*>(renderer.get());
- EXPECT_TRUE(d3d_renderer->d3d_device() != NULL);
-#elif defined(RENDERER_GL)
- // test that the Cg Context was correctly created
- RendererGL* gl_renderer = down_cast<RendererGL*>(renderer.get());
- EXPECT_TRUE(gl_renderer->cg_context() != NULL);
-#elif defined(RENDERER_GLES2)
- RendererGLES2* gles2_renderer = down_cast<RendererGLES2*>(renderer.get());
-#endif
- // destroy the renderer
- renderer->Destroy();
-
-#if defined(RENDERER_D3D9)
- // check that the renderer no longer had the D3D device.
- EXPECT_FALSE(d3d_renderer->d3d_device() != NULL);
-#elif defined(RENDERER_GL)
- // check that the renderer no longer has a Cg Context.
- EXPECT_FALSE(gl_renderer->cg_context() != NULL);
-#elif defined(RENDERER_GLES2)
-#if defined(GLES2_BACKEND_DESKTOP_GL)
-#if defined(OS_LINUX)
- EXPECT_FALSE(gles2_renderer->glx_context() != NULL);
-#endif
-#elif defined(GLES2_BACKEND_NATIVE_GLES2)
- EXPECT_FALSE(gles2_renderer->egl_context() != NULL);
-#endif
-#endif
-}
-
-// Offscreen is only supported on D3D currently
-#if defined(RENDERER_D3D9)
-// Tests that creating an off-screen renderer works correctly.
-TEST_F(RendererTest, OffScreen) {
- scoped_ptr<Renderer> renderer(
- Renderer::CreateDefaultRenderer(service_locator()));
- EXPECT_TRUE(renderer->Init(*g_display_window, true));
-
- RendererD3D9 *d3d_renderer = down_cast<RendererD3D9*>(renderer.get());
- EXPECT_TRUE(d3d_renderer->d3d_device() != NULL);
-
- renderer->Destroy();
-
- EXPECT_FALSE(d3d_renderer->d3d_device() != NULL);
-}
-#endif
-
-// Tests SetViewport
-TEST_F(RendererTest, SetViewport) {
- ErrorStatus error_status(g_service_locator);
-
- // Test that we can call it.
- EXPECT_TRUE(error_status.GetLastError().empty());
- g_renderer->SetViewport(Float4(0.0f, 0.0f, 1.0f, 1.0f), Float2(0.0f, 1.0f));
- EXPECT_TRUE(error_status.GetLastError().empty());
-
- // Test zero width
- g_renderer->SetViewport(Float4(0.0f, 0.0f, 0.0f, 0.0f), Float2(0.0f, 1.0f));
- EXPECT_TRUE(error_status.GetLastError().empty());
-
- // Test that it fails with invalid values
- error_status.ClearLastError();
- // width off right
- g_renderer->SetViewport(Float4(0.5f, 0.0f, 1.0f, 1.0f), Float2(0.0f, 1.0f));
- EXPECT_FALSE(error_status.GetLastError().empty());
-
- // height off bottom
- error_status.ClearLastError();
- g_renderer->SetViewport(Float4(0.0f, 0.5f, 1.0f, 1.0f), Float2(0.0f, 1.0f));
- EXPECT_FALSE(error_status.GetLastError().empty());
-
- // left off right
- error_status.ClearLastError();
- g_renderer->SetViewport(Float4(2.0f, 0.0f, 1.0f, 1.0f), Float2(0.0f, 1.0f));
- EXPECT_FALSE(error_status.GetLastError().empty());
-
- // top off bottom
- error_status.ClearLastError();
- g_renderer->SetViewport(Float4(0.0f, 2.0f, 1.0f, 1.0f), Float2(0.0f, 1.0f));
- EXPECT_FALSE(error_status.GetLastError().empty());
-
- // negative width
- error_status.ClearLastError();
- g_renderer->SetViewport(Float4(0.0f, 0.0f, -1.0f, 1.0f), Float2(0.0f, 1.0f));
- EXPECT_FALSE(error_status.GetLastError().empty());
-
- // negative height
- error_status.ClearLastError();
- g_renderer->SetViewport(Float4(0.0f, 0.0f, 1.0f, -1.0f), Float2(0.0f, 1.0f));
- EXPECT_FALSE(error_status.GetLastError().empty());
-
- // left off left
- error_status.ClearLastError();
- g_renderer->SetViewport(Float4(-0.1f, 0.0f, 1.0f, 1.0f), Float2(0.0f, 1.0f));
- EXPECT_FALSE(error_status.GetLastError().empty());
-
- // top off top
- error_status.ClearLastError();
- g_renderer->SetViewport(Float4(0.0f, -0.1f, 1.0f, 1.0f), Float2(0.0f, 1.0f));
- EXPECT_FALSE(error_status.GetLastError().empty());
-}
-
-} // namespace o3d
-
diff --git a/o3d/core/cross/sampler.cc b/o3d/core/cross/sampler.cc
deleted file mode 100644
index 178218a..0000000
--- a/o3d/core/cross/sampler.cc
+++ /dev/null
@@ -1,127 +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 Sampler class.
-
-#include "core/cross/param.h"
-#include "core/cross/renderer.h"
-#include "core/cross/sampler.h"
-#include "core/cross/types.h"
-#include "core/cross/error.h"
-
-
-namespace o3d {
-
-// Names of Params that get created for every Sampler.
-const char* Sampler::kAddressUModeParamName =
- O3D_STRING_CONSTANT("addressModeU");
-const char* Sampler::kAddressVModeParamName =
- O3D_STRING_CONSTANT("addressModeV");
-const char* Sampler::kAddressWModeParamName =
- O3D_STRING_CONSTANT("addressModeW");
-const char* Sampler::kMagFilterParamName =
- O3D_STRING_CONSTANT("magFilter");
-const char* Sampler::kMinFilterParamName =
- O3D_STRING_CONSTANT("minFilter");
-const char* Sampler::kMipFilterParamName =
- O3D_STRING_CONSTANT("mipFilter");
-const char* Sampler::kBorderColorParamName =
- O3D_STRING_CONSTANT("borderColor");
-const char* Sampler::kMaxAnisotropyParamName =
- O3D_STRING_CONSTANT("maxAnisotropy");
-
-const char* Sampler::kTextureParamName =
- O3D_STRING_CONSTANT("texture");
-
-O3D_DEFN_CLASS(Sampler, ParamObject);
-O3D_DEFN_CLASS(ParamSampler, RefParamBase);
-
-
-Sampler::Sampler(ServiceLocator* service_locator)
- : ParamObject(service_locator),
- weak_pointer_manager_(this) {
- // Create all the Params for the Sampler, register them and set their initial
- // values to their defaults.
- RegisterAndSetParam(kAddressUModeParamName,
- WRAP,
- &address_mode_u_param_ref_);
- RegisterAndSetParam(kAddressVModeParamName,
- WRAP,
- &address_mode_v_param_ref_);
- RegisterAndSetParam(kAddressWModeParamName,
- WRAP,
- &address_mode_w_param_ref_);
- RegisterAndSetParam(kMagFilterParamName,
- LINEAR,
- &mag_filter_param_ref_);
- RegisterAndSetParam(kMinFilterParamName,
- LINEAR,
- &min_filter_param_ref_);
- RegisterAndSetParam(kMipFilterParamName,
- LINEAR,
- &mip_filter_param_ref_);
-
- RegisterParamRef(kBorderColorParamName, &border_color_param_ref_);
- border_color_param_ref_.Get()->set_value(Float4(0, 0, 0, 0));
-
- RegisterAndSetParam(kMaxAnisotropyParamName, 1, &max_anisotropy_param_ref_);
-
- RegisterParamRef(kTextureParamName, &texture_param_ref_);
- texture_param_ref_.Get()->set_value(NULL);
-}
-
-// Creates (if it doesn't already exist) and registers a Param in the
-// ParamObject and sets its value to the default_value.
-template<typename T>
-void Sampler::RegisterAndSetParam(const String& param_name,
- unsigned int default_value,
- T* typed_param_ref_pointer) {
- RegisterParamRef(param_name, typed_param_ref_pointer);
- typed_param_ref_pointer->Get()->set_value(default_value);
-}
-
-
-ObjectBase::Ref Sampler::Create(ServiceLocator* service_locator) {
- Renderer* renderer = service_locator->GetService<Renderer>();
- if (NULL == renderer) {
- O3D_ERROR(service_locator) << "No Render Device Available";
- return ObjectBase::Ref();
- }
- return ObjectBase::Ref(renderer->CreateSampler());
-}
-
-
-ObjectBase::Ref ParamSampler::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamSampler(service_locator, false, false));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/sampler.h b/o3d/core/cross/sampler.h
deleted file mode 100644
index c6dcf54..0000000
--- a/o3d/core/cross/sampler.h
+++ /dev/null
@@ -1,207 +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 declaration for the Sampler class.
-
-#ifndef O3D_CORE_CROSS_SAMPLER_H_
-#define O3D_CORE_CROSS_SAMPLER_H_
-
-#include "core/cross/param_object.h"
-#include "core/cross/param.h"
-#include "core/cross/texture.h"
-
-namespace o3d {
-
-// A Sampler is the base class for texture sampler objects. Texture Samplers
-// encapsulate a Texture object reference with states that determine how the
-// texture gets used. Samplers keep a reference to the texture object associated
-// to them via a param.
-class Sampler : public ParamObject {
- public:
- typedef SmartPointer<Sampler> Ref;
- typedef WeakPointer<Sampler> WeakPointerType;
-
- // Address Modes.
- enum AddressMode {
- WRAP,
- MIRROR,
- CLAMP,
- BORDER
- };
-
- // Filter types.
- enum FilterType {
- NONE,
- POINT,
- LINEAR,
- ANISOTROPIC
- };
-
- // Name of Param defining the Texture object used by the Sampler.
- static const char* kTextureParamName;
- // Names of Params that get created for every Sampler.
- static const char* kAddressUModeParamName;
- static const char* kAddressVModeParamName;
- static const char* kAddressWModeParamName;
- static const char* kMagFilterParamName;
- static const char* kMinFilterParamName;
- static const char* kMipFilterParamName;
- static const char* kBorderColorParamName;
- static const char* kMaxAnisotropyParamName;
-
- explicit Sampler(ServiceLocator* service_locator);
-
- // Returns the Texture object bound to the Sampler.
- Texture* texture() const {
- return texture_param_ref_->value();
- }
-
- // Binds a Texture object to the Sampler.
- void set_texture(Texture *texture) {
- texture_param_ref_->set_value(texture);
- }
-
- AddressMode address_mode_u() const {
- return static_cast<AddressMode>(address_mode_u_param_ref_->value());
- }
- AddressMode address_mode_v() const {
- return static_cast<AddressMode>(address_mode_v_param_ref_->value());
- }
- AddressMode address_mode_w() const {
- return static_cast<AddressMode>(address_mode_w_param_ref_->value());
- }
-
- FilterType mag_filter() const {
- return static_cast<FilterType>(mag_filter_param_ref_->value());
- }
- FilterType min_filter() const {
- return static_cast<FilterType>(min_filter_param_ref_->value());
- }
- FilterType mip_filter() const {
- return static_cast<FilterType>(mip_filter_param_ref_->value());
- }
-
- Float4 border_color() const {
- return border_color_param_ref_->value();
- }
-
- int max_anisotropy() const {
- return max_anisotropy_param_ref_->value();
- }
-
- void set_address_mode_u(AddressMode mode) {
- address_mode_u_param_ref_->set_value(mode);
- }
- void set_address_mode_v(AddressMode mode) {
- address_mode_v_param_ref_->set_value(mode);
- }
- void set_address_mode_w(AddressMode mode) {
- address_mode_w_param_ref_->set_value(mode);
- }
-
- void set_mag_filter(FilterType type) {
- mag_filter_param_ref_->set_value(type);
- }
- void set_min_filter(FilterType type) {
- min_filter_param_ref_->set_value(type);
- }
- void set_mip_filter(FilterType type) {
- mip_filter_param_ref_->set_value(type);
- }
-
- void set_border_color(const Float4& color) {
- border_color_param_ref_->set_value(color);
- }
-
- void set_max_anisotropy(int max_anisotropy) {
- max_anisotropy_param_ref_->set_value(max_anisotropy);
- }
-
- // Gets a weak pointer to us.
- WeakPointerType GetWeakPointer() const {
- return weak_pointer_manager_.GetWeakPointer();
- }
-
- protected:
- // Creates (if it doesn't already exist) and registers a Param in the
- // Sampler and sets its value to the default_value.
- // Parameters:
- // param_name: name of the Param to create and register.
- // default_value: value to set to the Param after it gets created.
- // typed_param_ref_pointer: pointer to the param reference to be set.
- template<typename T>
- void RegisterAndSetParam(const String& param_name,
- unsigned int default_value,
- T* typed_param_ref_pointer);
-
- // References to all the default Params created for Samplers.
- ParamInteger::Ref address_mode_u_param_ref_;
- ParamInteger::Ref address_mode_v_param_ref_;
- ParamInteger::Ref address_mode_w_param_ref_;
- ParamInteger::Ref mag_filter_param_ref_;
- ParamInteger::Ref min_filter_param_ref_;
- ParamInteger::Ref mip_filter_param_ref_;
- ParamFloat4::Ref border_color_param_ref_;
- ParamInteger::Ref max_anisotropy_param_ref_;
-
- ParamTexture::Ref texture_param_ref_;
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // Manager for weak pointers to us.
- WeakPointerType::WeakPointerManager weak_pointer_manager_;
-
- O3D_DECL_CLASS(Sampler, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(Sampler);
-};
-
-class ParamSampler : public TypedRefParam<Sampler> {
- public:
- typedef SmartPointer<ParamSampler> Ref;
-
- ParamSampler(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedRefParam<Sampler>(service_locator, dynamic, read_only) {}
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamSampler, RefParamBase);
- DISALLOW_COPY_AND_ASSIGN(ParamSampler);
-};
-
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_SAMPLER_H_
diff --git a/o3d/core/cross/semantic_manager.cc b/o3d/core/cross/semantic_manager.cc
deleted file mode 100644
index 756f641..0000000
--- a/o3d/core/cross/semantic_manager.cc
+++ /dev/null
@@ -1,71 +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 "core/cross/semantic_manager.h"
-#include "core/cross/standard_param.h"
-
-namespace o3d {
-
-const InterfaceId SemanticManager::kInterfaceId =
- InterfaceTraits<SemanticManager>::kInterfaceId;
-
-SemanticManager::SemanticManager(ServiceLocator* service_locator)
- : service_(service_locator, this) {
- // Create an object to hold one of each type of sas param.
- sas_param_object_ = ParamObject::Ref(new ParamObject(service_locator));
- sas_param_object_->set_name(O3D_STRING_CONSTANT("sasParamObject"));
-
- // Initializes the static map between SAS parameter names and the
- // corresponding StandardParamMatrix4 type and adds one of each SAS
- // param type of the sas_param_object_ by class name.
-#undef O3D_STANDARD_ANNOTATION_ENTRY
-#define O3D_STANDARD_ANNOTATION_ENTRY(enum_name, class_name) \
- sas_map_[#class_name] = class_name ## ParamMatrix4::GetApparentClass(); \
- sas_param_object_->CreateParamByClass( \
- class_name ## ParamMatrix4::GetApparentClass()->name(), \
- class_name ## ParamMatrix4::GetApparentClass());
-
- // Create the standard annotations (this uses the above ENTRY macro).
- O3D_STANDARD_ANNOTATIONS;
-}
-
-SemanticManager::~SemanticManager() {
- sas_param_object_.Reset();
-}
-
-// Looks up an SAS transform semantic by name, and returns the Semantic enum.
-const ObjectBase::Class* SemanticManager::LookupSemantic(
- const String& semantic) const {
- SasMap::const_iterator iter = sas_map_.find(semantic);
- return (iter != sas_map_.end()) ? iter->second : NULL;
-}
-} // namespace o3d
diff --git a/o3d/core/cross/semantic_manager.h b/o3d/core/cross/semantic_manager.h
deleted file mode 100644
index f5be134..0000000
--- a/o3d/core/cross/semantic_manager.h
+++ /dev/null
@@ -1,87 +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_CORE_CROSS_SEMANTIC_MANAGER_H_
-#define O3D_CORE_CROSS_SEMANTIC_MANAGER_H_
-
-#include <build/build_config.h>
-#include <map>
-
-#include "core/cross/types.h"
-#include "core/cross/service_implementation.h"
-#include "core/cross/object_base.h"
-#include "core/cross/param_object.h"
-
-namespace o3d {
-
-// Provides Classes associated with semantic names.
-class SemanticManager {
- public:
- static const InterfaceId kInterfaceId;
-
- explicit SemanticManager(ServiceLocator* service_locator);
- ~SemanticManager();
-
- // Gets the SAS param object.
- ParamObject* sas_param_object() {
- return sas_param_object_.Get();
- }
-
- // Looks up an SAS transform semantic by name, and returns the class type.
- const ObjectBase::Class* LookupSemantic(const String& semantic_name) const;
-
- private:
- ServiceImplementation<SemanticManager> service_;
-
- // A case-insensitive string comparator.
- struct lesscasecmp {
- bool operator() (const String& a, const String& b) const {
- // TODO : This is doing ASCII compare - not UTF8!
-#ifdef OS_WIN
- return(_stricmp(a.c_str(), b.c_str()) < 0);
-#else
- return(strcasecmp(a.c_str(), b.c_str()) < 0);
-#endif
- }
- };
-
- // Object to hold one of each Sas param to make it easy
- // to cache them without adding them to any other param object.
- ParamObject::Ref sas_param_object_;
-
- // This is a a case-insensitive map between strings and Param semantics.
- typedef std::map<String, const ObjectBase::Class*, lesscasecmp> SasMap;
- SasMap sas_map_;
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_SEMANTIC_MANAGER_H_
diff --git a/o3d/core/cross/service_dependency.h b/o3d/core/cross/service_dependency.h
deleted file mode 100644
index bb378a7..0000000
--- a/o3d/core/cross/service_dependency.h
+++ /dev/null
@@ -1,83 +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_CORE_CROSS_SERVICE_DEPENDENCY_H_
-#define O3D_CORE_CROSS_SERVICE_DEPENDENCY_H_
-
-#include "base/basictypes.h"
-#include "base/logging.h"
-#include "core/cross/service_locator.h"
-
-namespace o3d {
-
-// Locates and provides access to a service through an interface class.
-// The dependency is located from a ServiceLocator, either immediately or as
-// soon as it is added to the ServiceLocator.
-template <typename Interface>
-class ServiceDependency : public IServiceDependency {
- public:
- explicit ServiceDependency(ServiceLocator* service_locator)
- : service_locator_(service_locator),
- service_(NULL) {
- service_locator_->AddDependency(Interface::kInterfaceId, this);
- }
-
- ~ServiceDependency() {
- service_locator_->RemoveDependency(Interface::kInterfaceId, this);
- }
-
- Interface* Get() const {
- DCHECK(NULL != service_);
- return service_;
- }
-
- Interface* operator->() const {
- DCHECK(NULL != service_);
- return service_;
- }
-
- bool IsAvailable() const {
- return service_ != NULL;
- }
-
- private:
- virtual void Update(void* newService) {
- service_ = static_cast<Interface*>(newService);
- }
-
- ServiceLocator* service_locator_;
- Interface* service_;
- DISALLOW_COPY_AND_ASSIGN(ServiceDependency);
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_SERVICE_DEPENDENCY_H_
diff --git a/o3d/core/cross/service_implementation.h b/o3d/core/cross/service_implementation.h
deleted file mode 100644
index c4a5b8d..0000000
--- a/o3d/core/cross/service_implementation.h
+++ /dev/null
@@ -1,71 +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_CORE_CROSS_SERVICE_IMPLEMENTATION_H_
-#define O3D_CORE_CROSS_SERVICE_IMPLEMENTATION_H_
-
-#include <vector>
-
-#include "base/basictypes.h"
-#include "core/cross/service_locator.h"
-
-namespace o3d {
-
-// Adds a service class to a ServiceLocator. The service is available through
-// the ServiceLocator for as long as the ServiceImplementation is instantiated
-// A service implementing multiple interfaces may be registered with multiple
-// ServiceImplementation objects.
-template <typename Interface>
-class ServiceImplementation {
- public:
- ServiceImplementation(ServiceLocator* service_locator, Interface* service)
- : service_locator_(service_locator),
- service_(service) {
- service_locator_->AddService(Interface::kInterfaceId, service_);
- }
-
- ~ServiceImplementation() {
- service_locator_->RemoveService(Interface::kInterfaceId, service_);
- }
-
- ServiceLocator* service_locator() const {
- return service_locator_;
- }
-
- private:
- ServiceLocator* service_locator_;
- Interface* service_;
- DISALLOW_COPY_AND_ASSIGN(ServiceImplementation);
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_SERVICE_IMPLEMENTATION_H_
diff --git a/o3d/core/cross/service_interface_traits.h b/o3d/core/cross/service_interface_traits.h
deleted file mode 100644
index 9db2e0a..0000000
--- a/o3d/core/cross/service_interface_traits.h
+++ /dev/null
@@ -1,64 +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_CORE_CROSS_SERVICE_INTERFACE_TRAITS_H_
-#define O3D_CORE_CROSS_SERVICE_INTERFACE_TRAITS_H_
-
-namespace o3d {
-
-typedef const void* InterfaceId;
-
-// Provides information (currently only the interface ID) about a service
-// interface.
-template <typename Interface>
-class InterfaceTraits {
- public:
- // The interface ID for the service interface.
- static const InterfaceId kInterfaceId;
-
- private:
- static char unique_;
-
- InterfaceTraits();
- DISALLOW_COPY_AND_ASSIGN(InterfaceTraits);
-};
-
-template <typename Interface>
-const void* const InterfaceTraits<Interface>::kInterfaceId =
- &InterfaceTraits<Interface>::unique_;
-
-template <typename Interface>
-char InterfaceTraits<Interface>::unique_ = 0;
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_SERVICE_INTERFACE_TRAITS_H_
diff --git a/o3d/core/cross/service_locator.cc b/o3d/core/cross/service_locator.cc
deleted file mode 100644
index 83b7e7f..0000000
--- a/o3d/core/cross/service_locator.cc
+++ /dev/null
@@ -1,80 +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 "base/logging.h"
-#include "core/cross/service_locator.h"
-
-namespace o3d {
-
-void ServiceLocator::AddService(InterfaceId interfaceId, void* service) {
- // Check service with this interface is not already installed first.
- DCHECK(services_.end() == services_.find(interfaceId));
- services_.insert(ServiceMap::value_type(interfaceId, service));
-
- DependencyList& existingDependencies = dependencies_[interfaceId];
- for (DependencyList::iterator it = existingDependencies.begin();
- it != existingDependencies.end(); ++it) {
- (*it)->Update(service);
- }
-}
-
-void ServiceLocator::RemoveService(InterfaceId interfaceId, void* service) {
- // Remove the existing service, verifying that the caller identified
- // one that is currently active.
- ServiceMap::iterator serviceIt = services_.find(interfaceId);
- DCHECK_EQ(service, serviceIt->second);
- services_.erase(serviceIt);
-
- DependencyList& existingDependencies = dependencies_[interfaceId];
- for (DependencyList::iterator it = existingDependencies.begin();
- it != existingDependencies.end(); ++it) {
- (*it)->Update(NULL);
- }
-}
-
-void ServiceLocator::AddDependency(InterfaceId interfaceId,
- IServiceDependency* dependency) {
- dependencies_[interfaceId].push_back(dependency);
-
- ServiceMap::const_iterator serviceIt = services_.find(interfaceId);
- if (serviceIt != services_.end())
- dependency->Update(serviceIt->second);
- else
- dependency->Update(NULL);
-}
-
-void ServiceLocator::RemoveDependency(InterfaceId interfaceId,
- IServiceDependency* dependency) {
- dependencies_[interfaceId].remove(dependency);
- dependency->Update(NULL);
-}
-} // namespace o3d
diff --git a/o3d/core/cross/service_locator.h b/o3d/core/cross/service_locator.h
deleted file mode 100644
index bc619a1..0000000
--- a/o3d/core/cross/service_locator.h
+++ /dev/null
@@ -1,131 +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_CORE_CROSS_SERVICE_LOCATOR_H_
-#define O3D_CORE_CROSS_SERVICE_LOCATOR_H_
-
-#include <list>
-#include <map>
-
-#include "base/logging.h"
-#include "base/basictypes.h"
-#include "core/cross/service_interface_traits.h"
-
-namespace o3d {
-
-template <typename Interface>
-class ServiceImplementation;
-
-template <typename Interface>
-class ServiceDependency;
-
-// No virtual destructor for IServiceDependency because it is never destroyed
-// through this class and because if forces the destructor in derived template
-// classes to be instantiated early, causing a compilation error in some cases.
-class IServiceDependency {
- friend class ServiceLocator;
- private:
- virtual void Update(void* newService) = 0;
-};
-
-// A ServiceLocator tracks a number of services and connects them together
-// through their ServiceDependencies. When a service is constucted, one or
-// more ServiceImplementation member variables cause the service to be
-// registered for each implemented service interface. Then zero or more
-// ServiceDependency member variables register themselves as needing references
-// to other services. When these services become available, the dependencies
-// are updated to reference them. When these services are not available, the
-// dependencies report their reference as NULL.
-class ServiceLocator {
- template <typename Interface>
- friend class ServiceImplementation;
-
- template <typename Interface>
- friend class ServiceDependency;
-
- typedef std::list<IServiceDependency*> DependencyList;
- typedef std::map<InterfaceId, DependencyList> DependencyMap;
- typedef std::map<InterfaceId, void*> ServiceMap;
-
- public:
- ServiceLocator() {}
-
- // Returns whether a given service is available.
- template <typename Interface>
- bool IsAvailable() const {
- ServiceMap::const_iterator it = services_.find(Interface::kInterfaceId);
- return it != services_.end();
- }
- // Get a pointer to a service added to the service locator. Consider using a
- // ServiceDependency instead.
- template <typename Interface>
- Interface* GetService() const {
- ServiceMap::const_iterator it = services_.find(Interface::kInterfaceId);
- if (it != services_.end()) {
- return static_cast<Interface*>(it->second);
- } else {
- DCHECK(false);
- return NULL;
- }
- }
-
- private:
- // Add service to list of those available through the service locator
- // For any services previously added that are dependent on this one, update
- // their dependency pointer to point here. This cannot be invoked directly.
- // Use ServiceImplementation class.
- void AddService(InterfaceId interfaceId, void* service);
-
- // Remove an existing service from the service locator. Update any existing
- // dependencies referencing this service to NULL. This cannot be invoked
- // directly. Use ServiceImplementation class.
- void RemoveService(InterfaceId interfaceId, void* service);
-
- // Add a service dependency to the service locator. If the service has already
- // been added then just modify the dependency parameter to reference the
- // known service. Otherwise, set the dependency to NULL and add it to a list
- // of those that will be resolved as soon as the necessary service is added.
- // This cannot be invoked directly. Use ServiceDependency class.
- void AddDependency(InterfaceId interfaceId, IServiceDependency* dependency);
-
- // Remove a service dependency from the service locator.
- // This cannot be invoked directly. Use ServiceDependency class.
- void RemoveDependency(InterfaceId interfaceId,
- IServiceDependency* dependency);
-
- DependencyMap dependencies_;
- ServiceMap services_;
- DISALLOW_COPY_AND_ASSIGN(ServiceLocator);
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_SERVICE_LOCATOR_H_
diff --git a/o3d/core/cross/service_locator_test.cc b/o3d/core/cross/service_locator_test.cc
deleted file mode 100644
index 3b00a67..0000000
--- a/o3d/core/cross/service_locator_test.cc
+++ /dev/null
@@ -1,115 +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 "core/cross/service_dependency.h"
-#include "core/cross/service_implementation.h"
-#include "tests/common/win/testing_common.h"
-
-namespace o3d {
-
-namespace {
-
-class IService1 {
- public:
- static const InterfaceId kInterfaceId;
-};
-
-const InterfaceId IService1::kInterfaceId =
- InterfaceTraits<IService1>::kInterfaceId;
-
-// A service implementing one interface with no dependencies.
-class CService1 : public IService1 {
- public:
- explicit CService1(ServiceLocator* service_locator)
- : service_(service_locator, this) {
- }
-
- ServiceImplementation<IService1> service_;
-};
-
-class IService2 {
- public:
- static const InterfaceId kInterfaceId;
-};
-
-const InterfaceId IService2::kInterfaceId =
- InterfaceTraits<IService2>::kInterfaceId;
-
-// A service implementing one interface with one dependency.
-class DependentService2 : public IService2 {
- public:
- explicit DependentService2(ServiceLocator* service_locator)
- : service_(service_locator, this),
- dependency_(service_locator) {
- }
-
- ServiceImplementation<IService2> service_;
- ServiceDependency<IService1> dependency_;
-};
-}
-
-class ServiceLocatorTest : public testing::Test {
- protected:
- ServiceLocator locator_;
-};
-
-TEST_F(ServiceLocatorTest, ServiceNotAvailableIfNotAdded) {
- EXPECT_FALSE(locator_.IsAvailable<IService1>());
-}
-
-TEST_F(ServiceLocatorTest, CanRetreiveServiceImplementingSingleInterface) {
- CService1 service1(&locator_);
- EXPECT_TRUE(locator_.IsAvailable<IService1>());
- EXPECT_EQ(&service1, locator_.GetService<IService1>());
-}
-
-TEST_F(ServiceLocatorTest, CanRetreiveServiceImplementingExplicitInterface) {
- CService1 service1(&locator_);
- EXPECT_EQ(&service1, locator_.GetService<IService1>());
-}
-
-TEST_F(ServiceLocatorTest,
- CanAddAndRetreiveServiceWithDependenciesWhenDepencenciesAlreadyExist) {
- CService1 service1(&locator_);
- DependentService2 service2(&locator_);
- EXPECT_EQ(&service2, locator_.GetService<IService2>());
- EXPECT_EQ(&service1, service2.dependency_.Get());
-}
-
-TEST_F(ServiceLocatorTest,
- CanAddAndRetreiveServiceWithDependenciesWhenDepencenciesDontYetExist) {
- DependentService2 service2(&locator_);
- CService1 service1(&locator_);
- EXPECT_EQ(&service2, locator_.GetService<IService2>());
- EXPECT_EQ(&service1, service2.dependency_.Get());
-}
-}
diff --git a/o3d/core/cross/shape.cc b/o3d/core/cross/shape.cc
deleted file mode 100644
index cf42655..0000000
--- a/o3d/core/cross/shape.cc
+++ /dev/null
@@ -1,111 +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 definition of the Shape class.
-
-#include "core/cross/shape.h"
-#include "core/cross/param_object.h"
-#include "core/cross/render_node.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Shape, ParamObject)
-
-Shape::Shape(ServiceLocator* service_locator)
- : ParamObject(service_locator) {
-}
-
-ObjectBase::Ref Shape::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new Shape(service_locator));
-}
-
-// Adds a element do this shape.
-void Shape::AddElement(Element* element) {
- elements_.push_back(Element::Ref(element));
-}
-
-// Removes a element from this Shape.
-bool Shape::RemoveElement(Element* element) {
- ElementRefArray::iterator iter = std::find(elements_.begin(),
- elements_.end(),
- Element::Ref(element));
- if (iter != elements_.end()) {
- elements_.erase(iter);
- return true;
- }
- return false;
-}
-
-// Gets an Array of elements in this shape.
-ElementArray Shape::GetElements() const {
- ElementArray elements;
- elements.reserve(elements_.size());
- std::copy(elements_.begin(),
- elements_.end(),
- std::back_inserter(elements));
- return elements;
-}
-
-void Shape::SetElements(const ElementArray& elements) {
- elements_.resize(elements.size());
- for (unsigned int i = 0; i != elements.size(); ++i) {
- elements_[i] = Element::Ref(elements[i]);
- }
-}
-
-namespace {
-class FindByMaterial {
- public:
- explicit FindByMaterial(Material* material) : material_(material) { }
-
- bool operator() (const DrawElement* draw_element) {
- return draw_element->material() == material_;
- }
- private:
- Material* material_;
-};
-}
-
-void Shape::CreateDrawElements(Pack* pack,
- Material* material) {
- for (unsigned pp = 0; pp < elements_.size(); ++pp) {
- Element* element = elements_[pp].Get();
- const DrawElementRefArray& draw_elements = element->GetDrawElementRefs();
- if (std::find_if(draw_elements.begin(),
- draw_elements.end(),
- FindByMaterial(material)) == draw_elements.end()) {
- elements_[pp]->CreateDrawElement(pack, material);
- }
- }
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/shape.h b/o3d/core/cross/shape.h
deleted file mode 100644
index 84b6310..0000000
--- a/o3d/core/cross/shape.h
+++ /dev/null
@@ -1,118 +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 declarations for the Shape class.
-
-#ifndef O3D_CORE_CROSS_SHAPE_H_
-#define O3D_CORE_CROSS_SHAPE_H_
-
-#include <vector>
-#include "core/cross/material.h"
-#include "core/cross/element.h"
-
-namespace o3d {
-
-class Pack;
-
-// TODO: A Shape is something made of Primitives. What would a HeightMap
-// be made of? It seems like Shape should be based on something like class
-// Drawable that is a little more abstract/virtual so that we can easily add
-// things later like SkinnedShape or NurbsSurface etc..
-
-// The Shape represents a collection of Elements. The typical example is a
-// cube with 6 faces where each face uses a different material would be
-// represented as 1 Shape with 6 Elements, one for each material.
-class Shape : public ParamObject {
- public:
- typedef SmartPointer<Shape> Ref;
-
- // Gets an Array of Elements in this shape.
- // Returns:
- // ElementArray of elements in this shape.
- ElementArray GetElements() const;
-
- void SetElements(const ElementArray& elements);
-
- // Gets a direct const reference to the elements owned by this shape.
- // Returns:
- // const reference to the elements in this shape.
- const ElementRefArray& GetElementRefs() const {
- return elements_;
- }
-
- // Creates DrawElements for each Element owned by this Shape. If an Element
- // already has a DrawElement that uses material a new DrawElement will not be
- // created.
- // Parameters:
- // pack: pack used to manage created DrawElements. material: material to use
- // for each DrawElement. If you pass NULL it
- // will use the material on the element to which a draw element is being
- // added. In other words, a DrawPrimtive will use the material of the
- // corresponidng Element if material is NULL. This allows you to easily
- // setup the default (just draw as is) by passing NULL or setup a shadow
- // pass by passing in a shadow material.
- void CreateDrawElements(Pack* pack,
- Material* material);
-
- // Adds an Element to this shape. This is an internal function and should not
- // be called directly. use Element::SetOwner
- // Parameters:
- // element: Element to add.
- void AddElement(Element* element);
-
- // Removes an element from this Shape. This is an internal function and should
- // not be called directly. use Element::SetOwner
- // Parameters:
- // element: Element to remove.
- // Returns:
- // true if successful, false if element was not owned by this shape.
- bool RemoveElement(Element* element);
-
- private:
- explicit Shape(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // The elements of this Shape.
- ElementRefArray elements_;
-
- O3D_DECL_CLASS(Shape, ParamObject)
- DISALLOW_COPY_AND_ASSIGN(Shape);
-}; // Shape
-
-typedef std::vector<Shape*> ShapeArray;
-typedef std::vector<Shape::Ref> ShapeRefArray;
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_SHAPE_H_
diff --git a/o3d/core/cross/shape_test.cc b/o3d/core/cross/shape_test.cc
deleted file mode 100644
index 08d14c3..0000000
--- a/o3d/core/cross/shape_test.cc
+++ /dev/null
@@ -1,93 +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 implements unit tests for class Shape.
-
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/primitive.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/shape.h"
-#include "utils/cross/json_writer.h"
-#include "utils/cross/string_writer.h"
-#include "tests/common/win/testing_common.h"
-
-namespace o3d {
-
-class ShapeTest : public testing::Test {
- protected:
-
- ShapeTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- ServiceDependency<ObjectManager> object_manager_;
- Pack *pack_;
-};
-
-void ShapeTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void ShapeTest::TearDown() {
- pack_->Destroy();
-}
-
-TEST_F(ShapeTest, ElementsAccessorShouldReturnAllElements) {
- Shape* shape = pack_->Create<Shape>();
-
- Element* element = pack_->Create<Primitive>();
- shape->AddElement(element);
- ElementArray elements = shape->GetElements();
-
- EXPECT_EQ(1U, elements.size());
- EXPECT_EQ(element, elements[0]);
-}
-
-TEST_F(ShapeTest, ElementsAccessorShouldReplaceAllElements) {
- Shape* shape = pack_->Create<Shape>();
-
- Element* element1 = pack_->Create<Primitive>();
- shape->AddElement(element1);
-
- Element* element2 = pack_->Create<Primitive>();
- ElementArray elements;
- elements.push_back(element2);
- shape->SetElements(elements);
- elements = shape->GetElements();
-
- EXPECT_EQ(1U, elements.size());
- EXPECT_EQ(element2, elements[0]);
-}
-} // namespace o3d
diff --git a/o3d/core/cross/skin.cc b/o3d/core/cross/skin.cc
deleted file mode 100644
index 3c438c6..0000000
--- a/o3d/core/cross/skin.cc
+++ /dev/null
@@ -1,649 +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 class Skin.
-
-#include "core/cross/skin.h"
-#include "core/cross/error.h"
-#include "core/cross/pointer_utils.h"
-#include "import/cross/memory_stream.h"
-#include "import/cross/raw_data.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Skin, NamedObject);
-O3D_DEFN_CLASS(ParamSkin, RefParamBase);
-O3D_DEFN_CLASS(SkinEval, VertexSource);
-
-const char *Skin::kSerializationID = "SKIN";
-
-Skin::Skin(ServiceLocator* service_locator)
- : NamedObject(service_locator),
- highest_matrix_index_(0),
- highest_influences_(0),
- info_valid_(false),
- weak_pointer_manager_(this) {
-}
-
-const Skin::Influences* Skin::GetVertexInfluences(unsigned vertex_index) const {
- return (vertex_index < influences_array_.size()) ?
- &influences_array_[vertex_index] : NULL;
-}
-
-void Skin::SetVertexInfluences(unsigned vertex_index,
- const Skin::Influences& influences) {
- if (influences_array_.size() <= vertex_index) {
- influences_array_.resize(vertex_index + 1);
- }
-
- // Should we normalize the influences? I think no. The user can always
- // normalize them and if they don't maybe that's the way they wanted them to
- // achieve some effect.
- influences_array_[vertex_index] = influences;
-
- info_valid_ = false;
-}
-
-void Skin::UpdateInfo() const {
- if (!info_valid_) {
- info_valid_ = true;
- highest_matrix_index_ = 0;
- highest_influences_ = 0;
- for (unsigned ii = 0; ii < influences_array_.size(); ++ii) {
- const Influences& influences = influences_array_[ii];
- if (influences.size() > highest_influences_) {
- highest_influences_ = influences.size();
- }
- for (unsigned jj = 0; jj < influences.size(); ++jj) {
- if (influences[jj].matrix_index > highest_matrix_index_) {
- highest_matrix_index_ = influences[jj].matrix_index;
- }
- }
- }
- }
-}
-
-unsigned Skin::GetHighestMatrixIndex() const {
- UpdateInfo();
- return highest_matrix_index_;
-}
-
-unsigned Skin::GetHighestInfluences() const {
- UpdateInfo();
- return highest_influences_;
-}
-
-void Skin::SetInverseBindPoseMatrix(unsigned index, const Matrix4& matrix) {
- if (inverse_bind_pose_matrices_.size() <= index) {
- inverse_bind_pose_matrices_.resize(index + 1, Matrix4::identity());
- }
- inverse_bind_pose_matrices_[index] = matrix;
-}
-
-ObjectBase::Ref Skin::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new Skin(service_locator));
-}
-
-SkinEval::StreamInfo::StreamInfo()
- : compute_function_(NULL),
- copy_function_(NULL),
- data_(NULL),
- buffer_(NULL),
- values_(NULL),
- stride_(0) {
-}
-
-namespace {
-
-void ComputeFloat3AsVector3(float* destination,
- const float* source,
- const Matrix4& matrix) {
- Vector4 result(matrix * Vector3(source[0], source[1], source[2]));
- destination[0] = result.getElem(0);
- destination[1] = result.getElem(1);
- destination[2] = result.getElem(2);
-}
-
-void ComputeFloat3AsPoint3(float* destination,
- const float* source,
- const Matrix4& matrix) {
- Vector4 result(matrix * Point3(source[0], source[1], source[2]));
- destination[0] = result.getElem(0);
- destination[1] = result.getElem(1);
- destination[2] = result.getElem(2);
-}
-
-void ComputeFloat4AsVector4(float* destination,
- const float* source,
- const Matrix4& matrix) {
- Vector4 result(matrix * Vector4(source[0], source[1], source[2], source[3]));
- destination[0] = result.getElem(0);
- destination[1] = result.getElem(1);
- destination[2] = result.getElem(2);
- destination[3] = result.getElem(3);
-}
-
-void CopyFloat3(float* destination,
- const float* source) {
- destination[0] = source[0];
- destination[1] = source[1];
- destination[2] = source[2];
-}
-
-void CopyFloat4(float* destination,
- const float* source) {
- destination[0] = source[0];
- destination[1] = source[1];
- destination[2] = source[2];
- destination[3] = source[3];
-}
-
-} // anonymous namespace
-
-bool SkinEval::StreamInfo::Init(const Stream& stream,
- Buffer::AccessMode access_mode) {
- DCHECK(data_ == NULL);
- DCHECK(buffer_ == NULL);
- const Field& field = stream.field();
- Buffer* buffer = field.buffer();
- if (!buffer || !field.IsA(FloatField::GetApparentClass())) {
- // TODO: Figure out a way to return a better error.
- return false;
- }
- switch (field.num_components()) {
- case 3:
- copy_function_ = CopyFloat3;
- compute_function_ = (stream.semantic() == Stream::POSITION) ?
- ComputeFloat3AsPoint3 : ComputeFloat3AsVector3;
- break;
- case 4:
- compute_function_ = ComputeFloat4AsVector4;
- copy_function_ = CopyFloat4;
- break;
- default:
- // TODO: Figure out a way to return a better error.
- return false;
- }
-
- bool success = buffer->Lock(access_mode, &data_);
- if (success) {
- values_ = PointerFromVoidPointer<float*>(data_, field.offset());
- stride_ = buffer->stride();
- buffer_ = buffer;
- }
- return success;
-}
-
-void SkinEval::StreamInfo::Uninit() {
- if (data_) {
- DCHECK(buffer_);
- buffer_->Unlock();
- data_ = NULL;
- buffer_ = NULL;
- }
-}
-
-const char* SkinEval::kMatricesParamName = O3D_STRING_CONSTANT("matrices");
-const char* SkinEval::kSkinParamName = O3D_STRING_CONSTANT("skin");
-const char* SkinEval::kBaseParamName = O3D_STRING_CONSTANT("base");
-
-SkinEval::SkinEval(ServiceLocator* service_locator)
- : VertexSource(service_locator) {
- RegisterParamRef(kMatricesParamName, &matrices_param_);
- RegisterParamRef(kSkinParamName, &skin_param_);
- RegisterParamRef(kBaseParamName, &base_param_);
-}
-
-bool SkinEval::SetVertexStream(Stream::Semantic semantic,
- int semantic_index,
- Field* field,
- unsigned int start_index) {
- Buffer* buffer = field->buffer();
- if (!buffer) {
- O3D_ERROR(service_locator()) << "No buffer on field";
- return false;
- }
- if (!buffer->IsA(SourceBuffer::GetApparentClass())) {
- O3D_ERROR(service_locator()) << "Buffer is not a SourceBuffer";
- return false;
- }
-
- Stream::Ref stream(new Stream(service_locator(),
- field,
- start_index,
- semantic,
- semantic_index));
-
- // If a stream with the same semantic has already been set then remove it.
- RemoveVertexStream(semantic, semantic_index);
-
- ParamVertexBufferStream::Ref stream_param(new SlaveParamVertexBufferStream(
- service_locator(), this, stream));
- vertex_stream_params_.push_back(stream_param);
-
- return true;
-}
-
-bool SkinEval::RemoveVertexStream(Stream::Semantic stream_semantic,
- int semantic_index) {
- StreamParamVector::iterator iter, end = vertex_stream_params_.end();
- for (iter = vertex_stream_params_.begin(); iter != end; ++iter) {
- const Stream& stream = (*iter)->stream();
- if (stream.semantic() == stream_semantic &&
- stream.semantic_index() == semantic_index) {
- vertex_stream_params_.erase(iter);
- return true;
- }
- }
- return false;
-}
-
-const Stream* SkinEval::GetVertexStream(
- Stream::Semantic stream_semantic,
- int semantic_index) const {
- ParamVertexBufferStream* param = GetVertexStreamParam(stream_semantic,
- semantic_index);
- return param ? &param->stream() : NULL;
-}
-
-ParamVertexBufferStream* SkinEval::GetVertexStreamParam(
- Stream::Semantic semantic,
- int semantic_index) const {
- StreamParamVector::const_iterator iter, end = vertex_stream_params_.end();
- for (iter = vertex_stream_params_.begin(); iter != end; ++iter) {
- const Stream& stream = (*iter)->stream();
- if (stream.semantic() == semantic &&
- stream.semantic_index() == semantic_index) {
- return *iter;
- }
- }
- return NULL;
-}
-
-void SkinEval::UpdateStreams() {
- for (unsigned ii = 0; ii < vertex_stream_params_.size(); ++ii) {
- vertex_stream_params_[ii]->UpdateStream();
- }
-}
-
-void SkinEval::DoSkinning(Skin* skin) {
- const Skin::InfluencesArray& influences_array = skin->influences();
- unsigned num_streams = vertex_stream_params_.size();
-
- if (input_stream_infos_.size() != num_streams) {
- input_stream_infos_.resize(num_streams);
- output_stream_infos_.resize(num_streams);
- }
-
- unsigned num_vertices = influences_array.size();
- // Update our inputs, lock all the inputs and outputs and check that we have
- // the same number of vertices as vertex influences.
- for (unsigned ii = 0; ii < num_streams; ++ii) {
- ParamVertexBufferStream* source_param = vertex_stream_params_[ii];
-
- // Make sure our upstream streams are ready
- ParamVertexBufferStream* input = down_cast<ParamVertexBufferStream*>(
- source_param->input_connection());
- if (input) {
- input->UpdateStream(); // will automatically mark us as valid.
- } else {
- // Mark us as valid so we don't evaluate a second time.
- source_param->ValidateStream();
- }
-
- const Stream& source_stream = source_param->stream();
- if (source_stream.GetMaxVertices() != num_vertices) {
- // TODO: Change semantic below to semantic_name.
- O3D_ERROR(service_locator())
- << "stream " << source_stream.semantic() << " index "
- << source_stream.semantic_index() << " in SkinEval '" << name()
- << " does not have the same number of vertices as Skin '"
- << skin->name() << "'";
- return;
- }
-
- // Lock this input.
- if (!input_stream_infos_[ii].Init(source_stream, Buffer::READ_ONLY)) {
- String buffer_name;
- if (source_stream.field().buffer()) {
- buffer_name = source_stream.field().buffer()->name();
- }
- O3D_ERROR(service_locator())
- << "unable to lock buffer '" << buffer_name
- << " used by stream " << source_stream.semantic() << " index "
- << source_stream.semantic_index() << " in SkinEval '" << name()
- << "'";
- return;
- }
-
- // Lock the outputs to this input.
- const ParamVector& outputs = source_param->output_connections();
- if (output_stream_infos_[ii].size() != outputs.size()) {
- output_stream_infos_[ii].resize(outputs.size());
- }
- for (unsigned jj = 0; jj < outputs.size(); ++jj) {
- ParamVertexBufferStream* destination_param =
- down_cast<ParamVertexBufferStream*>(outputs[jj]);
- destination_param->ValidateStream();
- const Stream& destination_stream = destination_param->stream();
- if (destination_stream.GetMaxVertices() != num_vertices) {
- O3D_ERROR(service_locator())
- << "stream " << destination_stream.semantic() << " index "
- << destination_stream.semantic_index() << " targeted by SkinEval '"
- << name() << " does not have the same number of vertices as Skin '"
- << skin->name() << "'";
- return;
- }
-
- if (!output_stream_infos_[ii][jj].Init(destination_stream,
- Buffer::WRITE_ONLY)) {
- String buffer_name;
- if (destination_stream.field().buffer()) {
- buffer_name = destination_stream.field().buffer()->name();
- }
- O3D_ERROR(service_locator())
- << "unable to lock buffer '" << buffer_name
- << " used by stream " << destination_stream.semantic() << " index "
- << destination_stream.semantic_index() << " targeted by SkinEval '"
- << name() << "'";
- return;
- }
- }
- }
-
- // At this point, all our streams have been locked and everything has been
- // verified so we can skin without checking for errors.
-
- // TODO: Optimizations:
- // It would be relatively easy to optimize for a few special cases.
- //
- // * If there are no more than say 4 influences per bone, pretty common for
- // games, we could cache the Skin data in format better suited
- // to an SSE hardcoded loop.
- //
- // * If all the streams are FLOAT4 we could do an SSE pass
- //
- // * If all the streams are from the same buffer (interleved) we
- // could special case 1 pointer instead of 1 per stream.
- //
- // * If there is only one output stream per input stream use a
- // code path that assumes that.
-
- // skin.
- for (unsigned ii = 0; ii < num_vertices; ++ii) {
- const Skin::Influences& influences = influences_array[ii];
- if (!influences.empty()) {
- // Get the first matrix.
- unsigned matrix_index = influences[0].matrix_index;
-
- // combine the matrixes for this vertex.
- Matrix4 accumulated_matrix(bones_[matrix_index] * influences[0].weight);
- unsigned num_influences = influences.size();
- for (unsigned jj = 1; jj < num_influences; ++jj) {
- const Skin::Influence& influence = influences[jj];
- accumulated_matrix += bones_[influence.matrix_index] *
- influence.weight;
- }
-
- // for each source, compute and copy to destination.
- for (unsigned jj = 0; jj < num_streams; ++jj) {
- StreamInfo& input_stream_info = input_stream_infos_[jj];
- input_stream_info.Compute(accumulated_matrix);
- StreamInfoVector& output_streams = output_stream_infos_[jj];
- unsigned num_output_streams = output_streams.size();
- for (unsigned ll = 0; ll < num_output_streams; ++ll) {
- output_streams[ll].Copy(input_stream_info);
- }
- }
- }
- }
-}
-
-void SkinEval::UpdateOutputs() {
- // Get our matrices.
- ParamArray* param_array = matrices();
- if (!param_array) {
- O3D_ERROR(service_locator()) << "no matrices for SkinEval '"
- << name() << "'";
- return;
- }
-
- Skin* the_skin = skin();
- if (!the_skin) {
- O3D_ERROR(service_locator()) << "no skin specified in SkinEval '"
- << name() << "'";
- return;
- }
-
- // Make sure the bone indcies are in range.
- if (the_skin->GetHighestMatrixIndex() >= param_array->size()) {
- O3D_ERROR(service_locator())
- << "skin '" << the_skin->name() << " specified in SkinEval '"
- << name()
- << "' references matrices outside the valid range in ParamArray '"
- << param_array->name() << "'";
- return;
- }
-
- // Make sure the bind pose array size matches the matrices
- const Skin::MatrixArray& inverse_bind_pose_array =
- the_skin->inverse_bind_pose_matrices();
- if (inverse_bind_pose_array.size() != param_array->size()) {
- O3D_ERROR(service_locator())
- << "skin '" << the_skin->name() << " specified in SkinEval '"
- << name() << "' and the ParamArray '"
- << param_array->name() << "' do not have the same number of matrices.";
- return;
- }
-
- // Get all the bones
- if (bones_.size() < param_array->size()) {
- bones_.resize(param_array->size());
- }
-
- // Get the inverse of our base to remove from the bones.
- Matrix4 inverse_base(inverse(base()));
-
- for (unsigned ii = 0; ii < param_array->size(); ++ii) {
- ParamMatrix4* param = param_array->GetParam<ParamMatrix4>(ii);
- if (!param) {
- O3D_ERROR(service_locator())
- << "In SkinEval '" << name() << "' param at index " << ii
- << " in ParamArray '" << param_array->name()
- << " is not a ParamMatrix4";
- return;
- }
- bones_[ii] = inverse_base * param->value() * inverse_bind_pose_array[ii];
- }
-
- DoSkinning(the_skin);
-
- // Unlock any buffers that were locked during skinning
- for (unsigned ii = 0; ii < input_stream_infos_.size(); ++ii) {
- input_stream_infos_[ii].Uninit();
- }
- for (unsigned ii = 0; ii < output_stream_infos_.size(); ++ii) {
- StreamInfoVector& output_streams = output_stream_infos_[ii];
- for (unsigned jj = 0; jj < output_streams.size(); ++jj) {
- output_streams[jj].Uninit();
- }
- }
-}
-
-bool SkinEval::ParamIsStreamParam(const Param* param) const {
- for (unsigned ii = 0; ii < vertex_stream_params_.size(); ++ii) {
- if (vertex_stream_params_[ii].Get() == param) {
- return true;
- }
- }
- return false;
-}
-
-void SkinEval::ConcreteGetInputsForParam(const Param* param,
- ParamVector* inputs) const {
- // If it's a stream param then it's effected by all the other params.
- if (ParamIsStreamParam(param)) {
- inputs->push_back(base_param_);
- inputs->push_back(matrices_param_);
- inputs->push_back(skin_param_);
- ParamArray* param_array = matrices();
- if (param_array) {
- unsigned size = param_array->size();
- for (unsigned ii = 0; ii < size; ++ii) {
- Param* matrix_param = param_array->GetUntypedParam(ii);
- if (matrix_param) {
- inputs->push_back(matrix_param);
- }
- }
- }
- }
-}
-
-void SkinEval::ConcreteGetOutputsForParam(const Param* param,
- ParamVector* outputs) const {
- ParamArray* param_array = matrices();
- // If it's anything but a stream param it's outputs are all the stream params.
- if (param == base_param_ ||
- param == matrices_param_ ||
- param == skin_param_ ||
- (param_array && param_array->ParamInArray(param))) {
- for (unsigned ii = 0; ii < vertex_stream_params_.size(); ++ii) {
- outputs->push_back(vertex_stream_params_[ii]);
- }
- }
-}
-
-ObjectBase::Ref SkinEval::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new SkinEval(service_locator));
-}
-
-ObjectBase::Ref ParamSkin::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamSkin(service_locator, false, false));
-}
-
-bool Skin::LoadFromBinaryData(MemoryReadStream *stream) {
- // Make sure we have enough data for serialization ID and version
- if (stream->GetRemainingByteCount() < 4 + sizeof(int32)) {
- O3D_ERROR(service_locator()) << "invalid empty skin data";
- return false;
- }
-
- // To insure data integrity we expect four characters kSerializationID
- uint8 id[4];
- stream->Read(id, 4);
-
- if (memcmp(id, kSerializationID, 4)) {
- O3D_ERROR(service_locator())
- << "data object does not contain skin data";
- return false;
- }
-
- int32 version = stream->ReadLittleEndianInt32();
- if (version != 1) {
- O3D_ERROR(service_locator()) << "unknown skin data version";
- return false;
- }
-
- int vertex_index = 0; // start at vertex zero.
-
- while (!stream->EndOfStream()) {
- // Make sure stream has a uint32 to read (for num_influences)
- if (stream->GetRemainingByteCount() < sizeof(uint32)) {
- FreeAll(); // We have to call this before O3D_ERROR.
- O3D_ERROR(service_locator()) << "unexpected end of skin data";
- return false;
- }
-
- uint32 num_influences = stream->ReadLittleEndianInt32();
-
- // Make sure the stream actually has num_influences data to read
- const size_t kInfluenceSize = sizeof(uint32) + sizeof(float);
- size_t data_size = num_influences * kInfluenceSize;
- if (stream->GetRemainingByteCount() < data_size) {
- FreeAll(); // We have to call this before O3D_ERROR.
- O3D_ERROR(service_locator()) << "unexpected end of skin data";
- return false;
- }
-
- if (num_influences > 0) {
- Skin::Influences influences(num_influences);
- for (Skin::Influences::size_type i = 0; i < num_influences; ++i) {
- uint32 matrix_index = stream->ReadLittleEndianInt32();
- float weight = stream->ReadLittleEndianFloat32();
- influences[i] = Skin::Influence(matrix_index, weight);
- }
- SetVertexInfluences(vertex_index, influences);
- }
-
- ++vertex_index;
- }
-
- return true;
-}
-
-void Skin::FreeAll() {
- influences_array_.clear();
- inverse_bind_pose_matrices_.clear();
- info_valid_ = false;
-}
-
-bool Skin::Set(o3d::RawData *raw_data) {
- if (!raw_data) {
- O3D_ERROR(service_locator()) << "data object is null";
- return false;
- }
- return Set(raw_data, 0, raw_data->GetLength());
-}
-
-bool Skin::Set(o3d::RawData *raw_data,
- size_t offset,
- size_t length) {
- if (!raw_data) {
- O3D_ERROR(service_locator()) << "data object is null";
- return false;
- }
-
- if (!raw_data->IsOffsetLengthValid(offset, length)) {
- O3D_ERROR(service_locator()) << "illegal skin data offset or size";
- return false;
- }
-
- const uint8 *data = raw_data->GetDataAs<uint8>(offset);
- if (!data) {
- return false;
- }
-
- MemoryReadStream stream(data, length);
- return LoadFromBinaryData(&stream);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/skin.h b/o3d/core/cross/skin.h
deleted file mode 100644
index 70193db..0000000
--- a/o3d/core/cross/skin.h
+++ /dev/null
@@ -1,385 +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 declaration of class Skin.
-
-#ifndef O3D_CORE_CROSS_SKIN_H_
-#define O3D_CORE_CROSS_SKIN_H_
-
-#include <vector>
-#include "core/cross/buffer.h"
-#include "core/cross/param_object.h"
-#include "core/cross/vertex_source.h"
-#include "core/cross/param_array.h"
-
-namespace o3d {
-
-class MemoryReadStream;
-class RawData;
-
-// A Skin holds an array of matrix indices and influences for vertices in a skin
-// as well as the inverse bind pose matrices for each bone.
-class Skin : public NamedObject {
- public:
- typedef SmartPointer<Skin> Ref;
- typedef WeakPointer<Skin> WeakPointerType;
-
- // A four-character identifier used in the binary serialization format
- // (not exposed to Javascript)
- static const char *kSerializationID;
-
- // One matrix-weight pair.
- struct Influence {
- Influence()
- : matrix_index(0),
- weight(0) {
- }
- Influence(unsigned index, float weight)
- : matrix_index(index),
- weight(weight) {
- }
- unsigned matrix_index;
- float weight;
- };
-
- typedef std::vector<Influence> Influences;
- typedef std::vector<Influences> InfluencesArray;
-
- typedef std::vector<Matrix4> MatrixArray;
-
- const InfluencesArray& influences() const {
- return influences_array_;
- }
-
- // Sets the data for an individual vertex.
- // Parameters:
- // vertex_index: Index of vertex to set.
- // influences: The matrix-weight pairs.
- void SetVertexInfluences(unsigned vertex_index,
- const Influences& influences);
-
- // Gets the data for an individual vertex.
- // Parameters:
- // vertex_index: Index of vertex to set.
- // Returns:
- // The influence data for the requested vertex or NULL if the index is out
- // of range.
- const Influences* GetVertexInfluences(unsigned vertex_index) const;
-
- // Gets the highest matrix index referenced by the influences.
- // Returns:
- // The highest matrix index referenced by the influences.
- unsigned GetHighestMatrixIndex() const;
-
- // Gets the highest number of influences on any vertex.
- // Returns:
- // The highest number of influences on any vertex.
- unsigned GetHighestInfluences() const;
-
- // Sets the inverse bind pose matrix for a particular joint/bone/transform.
- // Parameters:
- // index: index of bone/joint/transform
- // matrix: Inverse bind pose matrix for that joint.
- void SetInverseBindPoseMatrix(unsigned index, const Matrix4& matrix);
-
- // Gets the vector of inverse bind pose matrices.
- // Returns:
- // the vector of inverse bind pose matrices.
- const MatrixArray& inverse_bind_pose_matrices() const {
- return inverse_bind_pose_matrices_;
- }
-
- // Sete the vector of inverse bind pose matrices.
- void set_inverse_bind_pose_matrices(const MatrixArray& matrices) {
- inverse_bind_pose_matrices_ = matrices;
- }
-
- // Gets a weak pointer to us.
- WeakPointerType GetWeakPointer() const {
- return weak_pointer_manager_.GetWeakPointer();
- }
-
- // De-serializes the data contained in |raw_data|
- // The entire contents of |raw_data| from start to finish will
- // be used
- bool Set(o3d::RawData *raw_data);
-
- // De-serializes the data contained in |raw_data|
- // starting at byte offset |offset| and using |length|
- // bytes
- bool Set(o3d::RawData *raw_data,
- size_t offset,
- size_t length);
-
- // De-serializes a skin from its persistent binary representation
- bool LoadFromBinaryData(MemoryReadStream *stream);
-
- private:
- explicit Skin(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // Update the highest influences and highest matrix index.
- void UpdateInfo() const;
-
- // Frees all the influences and matrices.
- void FreeAll();
-
- // The vertex influences.
- InfluencesArray influences_array_;
-
- // The inverse bind poses.
- MatrixArray inverse_bind_pose_matrices_;
-
- // The highest matrix index.
- mutable unsigned highest_matrix_index_;
-
- // The highest number of influences.
- mutable unsigned highest_influences_;
-
- // True of the highest matrix index and highest influences is valid.
- mutable bool info_valid_;
-
- // Manager for weak pointers to us.
- WeakPointerType::WeakPointerManager weak_pointer_manager_;
-
- O3D_DECL_CLASS(Skin, NamedObject);
- DISALLOW_COPY_AND_ASSIGN(Skin);
-};
-
-// A Param that holds a weak reference to a Skin.
-class ParamSkin : public TypedRefParam<Skin> {
- public:
- typedef SmartPointer<ParamSkin> Ref;
-
- ParamSkin(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedRefParam<Skin>(service_locator, dynamic, read_only) {}
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamSkin, RefParamBase);
-};
-
-// A SkinEval is a VertexSource that takes its Streams, a ParamArray of Matrix4s
-// and a Skin and skins the vertices in its streams storing the results in bound
-// output streams.
-class SkinEval : public VertexSource {
- public:
- static const char* kMatricesParamName;
- static const char* kSkinParamName;
- static const char* kBaseParamName;
-
- Skin* skin() const {
- return skin_param_->value();
- }
-
- void set_skin(Skin* skin) {
- skin_param_->set_value(skin);
- }
-
- ParamArray* matrices() const {
- return matrices_param_->value();
- }
-
- void set_matrices(ParamArray* matrices) {
- matrices_param_->set_value(matrices);
- }
-
- Matrix4 base() const {
- return base_param_->value();
- }
-
- void set_base(const Matrix4& base) {
- base_param_->set_value(base);
- }
-
- // Binds the field of SourceBuffer and defines how the data in the buffer
- // should be accessed and interpreted.
- bool SetVertexStream(Stream::Semantic semantic,
- int semantic_index,
- Field* field,
- unsigned int start_index);
-
- // Removes a vertex stream from this primitive.
- // Returns true if the specified stream existed.
- bool RemoveVertexStream(Stream::Semantic stream_semantic,
- int semantic_index);
-
- // Searches the vertex streams bound to the shape for one with the given
- // stream semantic. If a stream is not found then it returns NULL.
- const Stream* GetVertexStream(Stream::Semantic stream_semantic,
- int semantic_index) const;
-
- // Updates all the VertexBuffers bound to streams on this VertexSource.
- void UpdateStreams();
-
- // Updates the VertexBuffers bound to streams on this VertexSource.
- void UpdateOutputs();
-
- // Overriden from VertexSource.
- virtual ParamVertexBufferStream* GetVertexStreamParam(
- Stream::Semantic semantic,
- int semantic_index) const;
-
- const StreamParamVector& vertex_stream_params() const {
- return vertex_stream_params_;
- }
-
- protected:
- // Overridden from ParamObject
- // For the given Param, returns all the inputs that affect that param through
- // this ParamObject.
- virtual void ConcreteGetInputsForParam(const Param* param,
- ParamVector* inputs) const;
-
- // Overridden from ParamCollection
- // For the given Param, returns all the outputs that the given param will
- // affect through this ParamObject.
- virtual void ConcreteGetOutputsForParam(const Param* param,
- ParamVector* outputs) const;
-
- private:
- class SlaveParamVertexBufferStream : public ParamVertexBufferStream {
- public:
- SlaveParamVertexBufferStream(ServiceLocator* service_locator,
- SkinEval* master,
- Stream* stream)
- : ParamVertexBufferStream(service_locator, stream, true, false),
- master_(master) {
- set_owner(master);
- }
-
- virtual void ComputeValue() {
- master_->UpdateOutputs();
- }
-
- private:
- SkinEval* master_;
- DISALLOW_COPY_AND_ASSIGN(SlaveParamVertexBufferStream);
- };
-
- typedef std::vector<Matrix4> Matrix4Vector;
-
- explicit SkinEval(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // Returns true if param is one of the Stream params on this SkinEval.
- bool ParamIsStreamParam(const Param* param) const;
-
- void DoSkinning(Skin* skin);
-
- // The streams on this SkinEval
- StreamParamVector vertex_stream_params_;
-
- // The array of bone matrices
- ParamParamArray::Ref matrices_param_;
-
- // The base matrix that will be used to keep the vertices in object space.
- ParamMatrix4::Ref base_param_;
-
- // The skin
- ParamSkin::Ref skin_param_;
-
- // A place to store the bone calulations. We keep this in the struct
- // so we don't have to allocate it every time.
- Matrix4Vector bones_;
-
- // This class helps manage each stream. Because allocating memory is slow
- // we keep these around across calls and reuse them in place by calling
- // Init.
- class StreamInfo {
- public:
- StreamInfo();
-
- // Locks the stream.
- bool Init(const Stream& stream, Buffer::AccessMode access_mode);
-
- // Unlocks the stream.
- void Uninit();
-
- // Multiplies the current value by the matrix and stores it in result and
- // advances to the next value.
- void Compute(const Matrix4& matrix) {
- compute_function_(&result_[0], values_, matrix);
- Advance();
- }
-
- // Copies the result from source and advances to the next value.
- void Copy(const StreamInfo& source) {
- copy_function_(values_, &source.result_[0]);
- Advance();
- }
-
- private:
- // Advances the internal counter to the next set.
- void Advance() {
- values_ = reinterpret_cast<float*>(reinterpret_cast<char*>(
- values_) + stride_);
- }
-
- // A pointer to function the multipies the source by the matrix and stores
- // the result in destination.
- typedef void (*ComputeFunction)(float* destination,
- const float* source,
- const Matrix4& matrix);
-
- // A pointer to a function that copies a 3 or 4 floats from the source to
- // the destination.
- typedef void (*CopyFunction)(float* destination, const float* source);
-
- ComputeFunction compute_function_;
- CopyFunction copy_function_;
- void* data_;
- Buffer* buffer_;
- float* values_;
- unsigned stride_;
- float result_[4];
- };
-
- typedef std::vector<StreamInfo> StreamInfoVector;
- typedef std::vector<StreamInfoVector> StreamInfoVectorVector;
-
- StreamInfoVector input_stream_infos_;
- StreamInfoVectorVector output_stream_infos_;
-
- O3D_DECL_CLASS(SkinEval, VertexSource);
- DISALLOW_COPY_AND_ASSIGN(SkinEval);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_SKIN_H_
diff --git a/o3d/core/cross/skin_test.cc b/o3d/core/cross/skin_test.cc
deleted file mode 100644
index 3060b1a..0000000
--- a/o3d/core/cross/skin_test.cc
+++ /dev/null
@@ -1,720 +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 functionality of the Skin class
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/error.h"
-#include "core/cross/error_status.h"
-#include "core/cross/skin.h"
-#include "core/cross/pointer_utils.h"
-#include "core/cross/primitive.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-#include "serializer/cross/serializer_binary.h"
-
-namespace o3d {
-
-namespace {
-
-bool CompareInfluences(const Skin::Influences& lhs,
- const Skin::Influences& rhs) {
- if (lhs.size() != rhs.size()) {
- return false;
- }
- for (unsigned ii = 0; ii < lhs.size(); ++ii) {
- if (lhs[ii].matrix_index != rhs[ii].matrix_index ||
- lhs[ii].weight != rhs[ii].weight) {
- return false;
- }
- }
- return true;
-}
-
-const float kEpsilon = 0.00001f;
-
-// Compares two Vector4's for equality.
-bool CompareVector4s(const Vector4& v1, const Vector4& v2) {
- return fabs(v1.getElem(0) - v2.getElem(0)) < kEpsilon &&
- fabs(v1.getElem(1) - v2.getElem(1)) < kEpsilon &&
- fabs(v1.getElem(2) - v2.getElem(2)) < kEpsilon &&
- fabs(v1.getElem(3) - v2.getElem(3)) < kEpsilon;
-}
-
-// Compares two Matrix4's for equality.
-bool CompareMatrix4s(const Matrix4& m1, const Matrix4& m2) {
- return CompareVector4s(m1.getCol0(), m2.getCol0()) &&
- CompareVector4s(m1.getCol1(), m2.getCol1()) &&
- CompareVector4s(m1.getCol2(), m2.getCol2()) &&
- CompareVector4s(m1.getCol3(), m2.getCol3());
-}
-
-bool CompareVertices(StreamBank* source,
- Stream::Semantic semantic,
- int semantic_index,
- const float* values) {
- const Stream* stream = source->GetVertexStream(semantic, semantic_index);
- if (!stream) {
- return false;
- }
-
- const Field& field = stream->field();
- Buffer* buffer = field.buffer();
- if (!buffer) {
- return false;
- }
- BufferLockHelper helper(buffer);
- void* data = helper.GetData(Buffer::READ_ONLY);
- if (!data) {
- return false;
- }
-
- unsigned num_vertices = stream->GetMaxVertices();
- unsigned stride = buffer->stride();
- unsigned num_components = field.num_components();
-
- const float* source_values = PointerFromVoidPointer<const float*>(
- data, field.offset());
- while (num_vertices) {
- for (unsigned jj = 0; jj < num_components; ++jj) {
- float difference = fabsf(source_values[jj] - values[jj]);
- if (difference > kEpsilon) {
- return false;
- }
- }
- values = AddPointerOffset(values, stride);
- source_values = AddPointerOffset(source_values, stride);
- --num_vertices;
- }
- return true;
-}
-
-// TODO: Remove the need for this.
-void InvalidateAllParameters(Pack* pack) {
- EvaluationCounter* evaluation_counter(
- pack->service_locator()->GetService<EvaluationCounter>());
- evaluation_counter->InvalidateAllParameters();
-}
-
-} // anonymous namespace.
-
-// Test fixture for Skin testing.
-class SkinTest : public testing::Test {
- protected:
- SkinTest()
- : object_manager_(g_service_locator) { }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- ServiceDependency<ObjectManager> object_manager_;
-
- private:
- Pack* pack_;
-};
-
-void SkinTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void SkinTest::TearDown() {
- pack_->Destroy();
-}
-
-// Test Skin
-TEST_F(SkinTest, Basic) {
- Skin* skin = pack()->Create<Skin>();
- // Check that it got created.
- ASSERT_TRUE(skin != NULL);
-
- // Check that it inherits from what we expect it to.
- EXPECT_TRUE(skin->IsA(NamedObject::GetApparentClass()));
-}
-
-// Test GetVertexInfluences, SetVertexInfluences, GetHighestMatrixIndex,
-// GetHighestInfluences
-TEST_F(SkinTest, GetSetVertexInfluence) {
- Skin* skin = pack()->Create<Skin>();
- // Check that it got created.
- ASSERT_TRUE(skin != NULL);
-
- // Check Highests are 0
- const Skin::InfluencesArray& influences = skin->influences();
- ASSERT_EQ(influences.size(), 0U);
- EXPECT_EQ(skin->GetHighestMatrixIndex(), 0U);
- EXPECT_EQ(skin->GetHighestInfluences(), 0U);
-
- // Add some influences.
- Skin::Influences no_influences;
- Skin::Influences influences_0;
- influences_0.push_back(Skin::Influence(1, 123.0f));
- influences_0.push_back(Skin::Influence(2, 456.0f));
- Skin::Influences influences_4;
- influences_4.push_back(Skin::Influence(4, 23.0f));
- influences_4.push_back(Skin::Influence(3, 56.0f));
-
- skin->SetVertexInfluences(0, influences_0);
- skin->SetVertexInfluences(4, influences_4);
-
- // Check they got set.
- ASSERT_EQ(influences.size(), 5U);
- EXPECT_TRUE(CompareInfluences(influences[0], influences_0));
- EXPECT_TRUE(CompareInfluences(influences[1], no_influences));
- EXPECT_TRUE(CompareInfluences(influences[2], no_influences));
- EXPECT_TRUE(CompareInfluences(influences[3], no_influences));
- EXPECT_TRUE(CompareInfluences(influences[4], influences_4));
-
- // Check the limits
- EXPECT_EQ(skin->GetHighestMatrixIndex(), 4U);
- EXPECT_EQ(skin->GetHighestInfluences(), 2U);
-
- // Add a new influence.
- Skin::Influences influences_2;
- influences_2.push_back(Skin::Influence(9, 1.0f));
- influences_2.push_back(Skin::Influence(2, 2.0f));
- influences_2.push_back(Skin::Influence(3, 3.0f));
-
- // Check they got set.
- skin->SetVertexInfluences(2, influences_2);
- ASSERT_EQ(influences.size(), 5U);
- EXPECT_TRUE(CompareInfluences(influences[0], influences_0));
- EXPECT_TRUE(CompareInfluences(influences[1], no_influences));
- EXPECT_TRUE(CompareInfluences(influences[2], influences_2));
- EXPECT_TRUE(CompareInfluences(influences[3], no_influences));
- EXPECT_TRUE(CompareInfluences(influences[4], influences_4));
-
- // Check the limits
- EXPECT_EQ(skin->GetHighestMatrixIndex(), 9U);
- EXPECT_EQ(skin->GetHighestInfluences(), 3U);
-
- // Add one past the end.
- skin->SetVertexInfluences(6, influences_4);
- ASSERT_EQ(influences.size(), 7U);
- EXPECT_TRUE(CompareInfluences(influences[0], influences_0));
- EXPECT_TRUE(CompareInfluences(influences[1], no_influences));
- EXPECT_TRUE(CompareInfluences(influences[2], influences_2));
- EXPECT_TRUE(CompareInfluences(influences[3], no_influences));
- EXPECT_TRUE(CompareInfluences(influences[4], influences_4));
- EXPECT_TRUE(CompareInfluences(influences[5], no_influences));
- EXPECT_TRUE(CompareInfluences(influences[6], influences_4));
-
- // Check the limits
- EXPECT_EQ(skin->GetHighestMatrixIndex(), 9U);
- EXPECT_EQ(skin->GetHighestInfluences(), 3U);
-}
-
-TEST_F(SkinTest, GetSetInverseBindPoseMatrices) {
- Skin* skin = pack()->Create<Skin>();
- // Check that it got created.
- ASSERT_TRUE(skin != NULL);
-
- const Skin::MatrixArray& matrices = skin->inverse_bind_pose_matrices();
- EXPECT_EQ(matrices.size(), 0U);
-
- Matrix4 matrix_2(Vector4(1.0f, 2.0f, 3.0f, 4.0f),
- Vector4(2.0f, 3.0f, 4.0f, 6.0f),
- Vector4(3.0f, 4.0f, 5.0f, 7.0f),
- Vector4(4.0f, 5.0f, 6.0f, 8.0f));
- Matrix4 matrix_4(Vector4(1.0f, 2.0f, 3.0f, 4.0f),
- Vector4(2.0f, 3.0f, 4.0f, 6.0f),
- Vector4(3.0f, 4.0f, 5.0f, 7.0f),
- Vector4(4.0f, 5.0f, 6.0f, 8.0f));
-
- skin->SetInverseBindPoseMatrix(2, matrix_2);
- EXPECT_EQ(matrices.size(), 3U);
- EXPECT_TRUE(CompareMatrix4s(matrices[0], Matrix4::identity()));
- EXPECT_TRUE(CompareMatrix4s(matrices[1], Matrix4::identity()));
- EXPECT_TRUE(CompareMatrix4s(matrices[2], matrix_2));
-
- skin->SetInverseBindPoseMatrix(4, matrix_4);
- EXPECT_EQ(matrices.size(), 5U);
- EXPECT_TRUE(CompareMatrix4s(matrices[0], Matrix4::identity()));
- EXPECT_TRUE(CompareMatrix4s(matrices[1], Matrix4::identity()));
- EXPECT_TRUE(CompareMatrix4s(matrices[2], matrix_2));
- EXPECT_TRUE(CompareMatrix4s(matrices[3], Matrix4::identity()));
- EXPECT_TRUE(CompareMatrix4s(matrices[4], matrix_4));
-}
-
-// Test fixture for SkinEval testing.
-class SkinEvalTest : public testing::Test {
- protected:
- SkinEvalTest()
- : object_manager_(g_service_locator) { }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- ServiceDependency<ObjectManager> object_manager_;
- ErrorStatus* error_status_;
-
- private:
- Pack* pack_;
-};
-
-void SkinEvalTest::SetUp() {
- error_status_ = new ErrorStatus(g_service_locator);
- pack_ = object_manager_->CreatePack();
-}
-
-void SkinEvalTest::TearDown() {
- pack_->Destroy();
- delete error_status_;
-}
-
-// Test SkinEval
-TEST_F(SkinEvalTest, Basic) {
- SkinEval* skin_eval = pack()->Create<SkinEval>();
- // Check that it got created.
- ASSERT_TRUE(skin_eval != NULL);
-
- // Check that it inherits from what we expect it to.
- EXPECT_TRUE(skin_eval->IsA(VertexSource::GetApparentClass()));
-
- // Check our params exist.
- EXPECT_TRUE(skin_eval->GetParam<ParamSkin>(
- SkinEval::kSkinParamName) != NULL);
- EXPECT_TRUE(skin_eval->GetParam<ParamParamArray>(
- SkinEval::kMatricesParamName) != NULL);
- EXPECT_TRUE(skin_eval->GetParam<ParamMatrix4>(
- SkinEval::kBaseParamName) != NULL);
-
- // Check our accessors
- EXPECT_TRUE(skin_eval->skin() == NULL);
- EXPECT_TRUE(skin_eval->matrices() == NULL);
- EXPECT_TRUE(CompareMatrix4s(skin_eval->base(), Matrix4::identity()));
-
- Skin* skin = pack()->Create<Skin>();
- ASSERT_TRUE(skin != NULL);
- skin_eval->set_skin(skin);
- ParamArray* param_array = pack()->Create<ParamArray>();
- ASSERT_TRUE(param_array != NULL);
- skin_eval->set_matrices(param_array);
- Matrix4 matrix(Vector4(1.0f, 2.0f, 3.0f, 4.0f),
- Vector4(2.0f, 3.0f, 4.0f, 6.0f),
- Vector4(3.0f, 4.0f, 5.0f, 7.0f),
- Vector4(4.0f, 5.0f, 6.0f, 8.0f));
- skin_eval->set_base(matrix);
-
- EXPECT_EQ(skin_eval->skin(), skin);
- EXPECT_EQ(skin_eval->matrices(), param_array);
- EXPECT_TRUE(CompareMatrix4s(skin_eval->base(), matrix));
-}
-
-// Tests Binding Streams on a Skin.
-TEST_F(SkinEvalTest, BindStreams) {
- SkinEval* skin_eval = pack()->Create<SkinEval>();
- Skin* skin = pack()->Create<Skin>();
- ParamArray* matrices = pack()->Create<ParamArray>();
- StreamBank* stream_bank = pack()->Create<StreamBank>();
- VertexBuffer* vertex_buffer = pack()->Create<VertexBuffer>();
- SourceBuffer* source_buffer = pack()->Create<SourceBuffer>();
-
- ASSERT_TRUE(skin_eval != NULL);
- ASSERT_TRUE(skin != NULL);
- ASSERT_TRUE(matrices != NULL);
- ASSERT_TRUE(stream_bank != NULL);
-
- Field* vertex_position_field = vertex_buffer->CreateField(
- FloatField::GetApparentClass(), 3);
- Field* vertex_normal_field = vertex_buffer->CreateField(
- FloatField::GetApparentClass(), 3);
- Field* vertex_texcoord_field = vertex_buffer->CreateField(
- FloatField::GetApparentClass(), 4);
- Field* source_position_field = source_buffer->CreateField(
- FloatField::GetApparentClass(), 3);
- Field* source_normal_field = source_buffer->CreateField(
- FloatField::GetApparentClass(), 3);
- Field* source_texcoord_field = source_buffer->CreateField(
- FloatField::GetApparentClass(), 4);
-
- ASSERT_TRUE(vertex_position_field != NULL);
- ASSERT_TRUE(vertex_normal_field != NULL);
- ASSERT_TRUE(vertex_texcoord_field != NULL);
- ASSERT_TRUE(source_position_field != NULL);
- ASSERT_TRUE(source_normal_field != NULL);
- ASSERT_TRUE(source_texcoord_field != NULL);
-
- skin_eval->set_skin(skin);
- skin_eval->set_matrices(matrices);
-
- static float vertices[] = {
- 1.0f, 2.0f, 3.0f,
- 1.0f, 0.0f, 0.0f,
- 0.5f, 1.0f, 1.5f, 1.0f,
-
- 4.0f, 5.0f, 6.0f,
- 0.0f, 1.0f, 0.0f,
- 0.5f, 2.0f, 1.5f, 1.0f,
-
- 7.0f, 8.0f, 9.0f,
- 0.0f, 0.0f, 1.0f,
- 0.5f, 3.0f, 1.5f, 1.0f,
- };
-
- static float expected_vertices[] = {
- 1.0f * 2.0f, 2.0f * 2.0f, 3.0f * 2.0f,
- 1.0f * 2.0f, 0.0f * 2.0f, 0.0f * 2.0f,
- 0.5f * 2.0f, 1.0f * 2.0f, 1.5f * 2.0f, 1.0f,
-
- (4.0f * 2.0f + 4.0f + 1.0f) / 2.0f,
- (5.0f * 2.0f + 5.0f + 2.0f) / 2.0f,
- (6.0f * 2.0f + 6.0f + 3.0f) / 2.0f,
-
- (0.0f * 2.0f + 0.0f) / 2.0f,
- (1.0f * 2.0f + 1.0f) / 2.0f,
- (0.0f * 2.0f + 0.0f) / 2.0f,
-
- (0.5f * 2.0f + 0.5f + 1.0f) / 2.0f,
- (2.0f * 2.0f + 2.0f + 2.0f) / 2.0f,
- (1.5f * 2.0f + 1.5f + 3.0f) / 2.0f,
- (1.0f * 1.0f + 1.0f + 0.0f) / 2.0f,
-
- 7.0f + 4.0f, 8.0f + 5.0f, 9.0f + 6.0f,
- 0.0f, 0.0f, 1.0f,
- 0.5f + 4.0f, 3.0f + 5.0f, 1.5f + 6.0f, 1.0f,
- };
-
- const unsigned kNumElements = 3;
-
- // Create the buffers.
-
- ASSERT_TRUE(vertex_buffer->AllocateElements(kNumElements));
- ASSERT_TRUE(source_buffer->AllocateElements(kNumElements));
- float* data;
- ASSERT_TRUE(source_buffer->LockAs(Buffer::WRITE_ONLY, &data));
- memcpy(data, &vertices, sizeof(vertices));
- ASSERT_TRUE(source_buffer->Unlock());
-
- // Setup the streams.
- ASSERT_TRUE(stream_bank->SetVertexStream(Stream::POSITION,
- 0,
- vertex_position_field,
- 0));
- ASSERT_TRUE(stream_bank->SetVertexStream(Stream::NORMAL,
- 0,
- vertex_normal_field,
- 0));
- ASSERT_TRUE(stream_bank->SetVertexStream(Stream::TEXCOORD,
- 0,
- vertex_texcoord_field,
- 0));
-
- ASSERT_TRUE(skin_eval->SetVertexStream(Stream::POSITION,
- 0,
- source_position_field,
- 0));
- ASSERT_TRUE(skin_eval->SetVertexStream(Stream::NORMAL,
- 0,
- source_normal_field,
- 0));
- ASSERT_TRUE(skin_eval->SetVertexStream(Stream::TEXCOORD,
- 0,
- source_texcoord_field,
- 0));
-
- // Bind the streams
- ASSERT_TRUE(stream_bank->BindStream(skin_eval, Stream::POSITION, 0));
- ASSERT_TRUE(stream_bank->BindStream(skin_eval, Stream::NORMAL, 0));
- ASSERT_TRUE(stream_bank->BindStream(skin_eval, Stream::TEXCOORD, 0));
-
- // Create the matrices
- ParamMatrix4* params[3];
- matrices->CreateParam<ParamMatrix4>(2);
- for (unsigned ii = 0; ii < 3; ++ii) {
- params[ii] = matrices->GetParam<ParamMatrix4>(ii);
- ASSERT_TRUE(params[ii] != NULL);
- }
-
- // Set the influences.
- Skin::Influences influences_0;
- influences_0.push_back(Skin::Influence(0, 1.0f));
- Skin::Influences influences_1;
- influences_1.push_back(Skin::Influence(0, 0.5f));
- influences_1.push_back(Skin::Influence(1, 0.5f));
- Skin::Influences influences_2;
- influences_2.push_back(Skin::Influence(1, 0.0f));
- influences_2.push_back(Skin::Influence(2, 1.0f));
-
- skin->SetVertexInfluences(0, influences_0);
- skin->SetVertexInfluences(1, influences_1);
- skin->SetVertexInfluences(2, influences_2);
-
- // Set the inverse bind pose matrices
- skin->SetInverseBindPoseMatrix(0, Matrix4::identity());
- skin->SetInverseBindPoseMatrix(1, Matrix4::identity());
- skin->SetInverseBindPoseMatrix(2, Matrix4::identity());
-
- // Cause the vertices to get updated.
- stream_bank->UpdateStreams();
-
- // Test that vertices get updated.
- EXPECT_TRUE(CompareVertices(stream_bank,
- Stream::POSITION,
- 0,
- vertices));
- EXPECT_TRUE(CompareVertices(stream_bank,
- Stream::NORMAL,
- 0,
- &vertices[3]));
- EXPECT_TRUE(CompareVertices(stream_bank,
- Stream::TEXCOORD,
- 0,
- &vertices[6]));
-
- // Move the matrixes and check again.
- params[0]->set_value(Matrix4(Vector4(2.0f, 0.0f, 0.0f, 0.0f),
- Vector4(0.0f, 2.0f, 0.0f, 0.0f),
- Vector4(0.0f, 0.0f, 2.0f, 0.0f),
- Vector4(0.0f, 0.0f, 0.0f, 1.0f)));
- params[1]->set_value(Matrix4(Vector4(1.0f, 0.0f, 0.0f, 0.0f),
- Vector4(0.0f, 1.0f, 0.0f, 0.0f),
- Vector4(0.0f, 0.0f, 1.0f, 0.0f),
- Vector4(1.0f, 2.0f, 3.0f, 1.0f)));
- params[2]->set_value(Matrix4(Vector4(1.0f, 0.0f, 0.0f, 0.0f),
- Vector4(0.0f, 1.0f, 0.0f, 0.0f),
- Vector4(0.0f, 0.0f, 1.0f, 0.0f),
- Vector4(4.0f, 5.0f, 6.0f, 1.0f)));
-
- // Cause the vertices to get updated.
- InvalidateAllParameters(pack());
- stream_bank->UpdateStreams();
-
- // Test that vertices are correct.
- EXPECT_TRUE(CompareVertices(stream_bank,
- Stream::POSITION,
- 0,
- expected_vertices));
- EXPECT_TRUE(CompareVertices(stream_bank,
- Stream::NORMAL,
- 0,
- &expected_vertices[3]));
- EXPECT_TRUE(CompareVertices(stream_bank,
- Stream::TEXCOORD,
- 0,
- &expected_vertices[6]));
-
- // check if skin references something outside matrices
- influences_2.push_back(Skin::Influence(3, 1.0f));
- skin->SetVertexInfluences(2, influences_2);
-
- // Cause the vertices to get updated.
- InvalidateAllParameters(pack());
- EXPECT_TRUE(error_status_->GetLastError().empty());
- stream_bank->UpdateStreams();
- EXPECT_FALSE(error_status_->GetLastError().empty());
-
- // put it back
- influences_2.pop_back();
- skin->SetVertexInfluences(2, influences_2);
-
- error_status_->ClearLastError();
- InvalidateAllParameters(pack());
- EXPECT_TRUE(error_status_->GetLastError().empty());
- stream_bank->UpdateStreams();
- EXPECT_TRUE(error_status_->GetLastError().empty());
-
- // check if buffers are not the same size.
- ASSERT_TRUE(vertex_buffer->AllocateElements(kNumElements * 2));
-
- // Cause the vertices to get updated.
- error_status_->ClearLastError();
- InvalidateAllParameters(pack());
- EXPECT_TRUE(error_status_->GetLastError().empty());
- stream_bank->UpdateStreams();
- EXPECT_FALSE(error_status_->GetLastError().empty());
-
- // put it back
- ASSERT_TRUE(vertex_buffer->AllocateElements(kNumElements));
-
- // Cause the vertices to get updated.
- error_status_->ClearLastError();
- InvalidateAllParameters(pack());
- EXPECT_TRUE(error_status_->GetLastError().empty());
- stream_bank->UpdateStreams();
- EXPECT_TRUE(error_status_->GetLastError().empty());
-
- // check if skin # vertex doesn't match stream
- skin->SetVertexInfluences(3, influences_2);
-
- // Cause the vertices to get updated.
- error_status_->ClearLastError();
- InvalidateAllParameters(pack());
- EXPECT_TRUE(error_status_->GetLastError().empty());
- stream_bank->UpdateStreams();
- EXPECT_FALSE(error_status_->GetLastError().empty());
-}
-
-
-// Sanity check on empty data
-TEST_F(SkinTest, SkinRawDataEmpty) {
- Skin* skin = pack()->Create<Skin>();
- ASSERT_TRUE(skin != NULL);
-
- uint8 p[2];
- MemoryReadStream read_stream(p, 0); // empty stream
-
- bool success = skin->LoadFromBinaryData(&read_stream);
-
- // Make sure we don't like to load from empty data
- EXPECT_FALSE(success);
-}
-
-// Sanity check on corrupt data
-TEST_F(SkinTest, SkinRawDataCorrupt) {
- Skin* skin = pack()->Create<Skin>();
- ASSERT_TRUE(skin != NULL);
-
- const int kDataLength = 512; // enough storage for test
- MemoryBuffer<uint8> buffer(kDataLength);
- MemoryWriteStream write_stream(buffer, kDataLength);
-
- // write out serialization ID
- write_stream.Write(Skin::kSerializationID, 4);
-
- // write out version 5 (which is illegal version!)
- write_stream.WriteLittleEndianInt32(5);
-
-
- // make note of amount we've written
- size_t data_size = write_stream.GetStreamPosition();
-
- // try to load what we just created
- MemoryReadStream read_stream(buffer, data_size);
- bool success = skin->LoadFromBinaryData(&read_stream);
-
- // Make sure we don't like to load from empty data
- EXPECT_FALSE(success);
-}
-
-// Sanity check on incomplete data
-TEST_F(SkinTest, SkinRawDataIncomplete) {
- Skin* skin = pack()->Create<Skin>();
- ASSERT_TRUE(skin != NULL);
-
- const int kDataLength = 512; // enough storage for test
- MemoryBuffer<uint8> buffer(kDataLength);
- MemoryWriteStream write_stream(buffer, kDataLength);
-
- // write out serialization ID
- write_stream.Write(Skin::kSerializationID, 4);
-
- // write out version
- write_stream.WriteLittleEndianInt32(1);
-
- write_stream.WriteByte(3); // bezier
- write_stream.WriteLittleEndianInt32(5);
- // but DON'T write the actual influences!
-
- // make note of amount we've written
- size_t data_size = write_stream.GetStreamPosition();
-
- // try to load what we just created
- MemoryReadStream read_stream(buffer, data_size);
- bool success = skin->LoadFromBinaryData(&read_stream);
-
- // Make sure we don't like to load from incomplete data
- EXPECT_FALSE(success);
-}
-
-
-// Check that valid skin data loads OK
-TEST_F(SkinTest, SkinRawDataValid) {
- Skin* skin = pack()->Create<Skin>();
- ASSERT_TRUE(skin != NULL);
-
- const int kDataLength = 512; // enough storage for test
- MemoryBuffer<uint8> buffer(kDataLength);
- MemoryWriteStream write_stream(buffer, kDataLength);
-
- // write out serialization ID
- write_stream.Write(Skin::kSerializationID, 4);
-
- // write out version
- write_stream.WriteLittleEndianInt32(1);
-
-
- // Write out some influence data
- const int kNumInfluences = 32;
- write_stream.WriteLittleEndianInt32(kNumInfluences);
-
- for (int i = 0; i < kNumInfluences; ++i) {
- write_stream.WriteLittleEndianInt32(i);
- write_stream.WriteLittleEndianFloat32(1.0f + 0.2f * static_cast<float>(i));
- }
-
- // Make note of amount we've written
- size_t data_size = write_stream.GetStreamPosition();
-
- // Try to load what we just created
- MemoryReadStream read_stream(buffer, data_size);
- bool success = skin->LoadFromBinaryData(&read_stream);
-
- // Make sure skin data was accepted
- EXPECT_TRUE(success);
-
- // Validate the influences
- const Skin::InfluencesArray& influences_array = skin->influences();
- EXPECT_EQ(1U, influences_array.size());
-
- const Skin::Influences& influences = influences_array[0];
- unsigned expected_count = kNumInfluences;
- EXPECT_EQ(expected_count, influences.size());
-
- for (Skin::Influences::size_type i = 0; i < influences.size(); ++i) {
- const Skin::Influence &influence = influences[i];
- EXPECT_EQ(i, influence.matrix_index);
- float expected_weight = 1.0f + 0.2f * static_cast<float>(i);
- EXPECT_EQ(expected_weight, influence.weight);
- }
-
- // Now, let's try a very nice test to verify that we properly
- // serialize -- this is a round trip test
- MemoryBuffer<uint8> serialized_data;
- SerializeSkin(*skin, &serialized_data);
-
- // Make sure serialized data length is identical to what we made
- ASSERT_EQ(data_size, serialized_data.GetLength());
-
- // Make sure the data matches
- uint8 *original = buffer;
- uint8 *serialized = serialized_data;
- EXPECT_EQ(0, memcmp(original, serialized, data_size));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/smart_ptr.h b/o3d/core/cross/smart_ptr.h
deleted file mode 100644
index a032ca4..0000000
--- a/o3d/core/cross/smart_ptr.h
+++ /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.
- */
-
-
-// Yet another implementation of a basic, intrusive reference-counting system.
-
-#ifndef O3D_CORE_CROSS_SMART_PTR_H_
-#define O3D_CORE_CROSS_SMART_PTR_H_
-
-#include "base/basictypes.h"
-
-namespace o3d {
-
-// The intrusive part of the reference counting mechanism. All objects to
-// be used within the reference-counting system must inherit from RefCounted.
-// The class contains the reference count.
-class RefCounted {
- template <class C>
- friend class SmartPointer;
- protected:
- RefCounted() : reference_count_(0) {
- }
-
- // Call when a new reference is made to the object.
- void AddRef() const {
- ++reference_count_;
- }
-
- // Call when a reference to the object is no longer needed.
- int Release() const {
- return --reference_count_;
- }
-
- private:
- mutable int reference_count_;
- DISALLOW_COPY_AND_ASSIGN(RefCounted);
-};
-
-
-// Template wrapper class that controls the lifetime of heap-constructed
-// objects.
-template <class C>
-class SmartPointer {
- public:
- typedef C* Pointer;
- typedef C& Reference;
- typedef C ClassType;
-
- // SmartPointer objects initialize to NULL on construction.
- SmartPointer() : data_(NULL) {
- }
-
- // This copy constructor is not marked explicit on purpose, so that
- // we can copy smart pointers implicitly.
- SmartPointer(const SmartPointer<C>& pointer) // NOLINT
- : data_(pointer.Get()) {
- AddRef();
- }
-
- explicit SmartPointer(Pointer data) : data_(data) {
- AddRef();
- }
-
- ~SmartPointer() {
- Release();
- }
-
- SmartPointer<C>& operator=(const SmartPointer<C>& rhs);
-
- // Operators to return a reference and pointer to the data, respectively.
- // Note that the constness of the operators obeys normal C++ pointer
- // semantics: If the pointer is const, the data is not const.
- Reference operator*() const {
- return *data_;
- }
- Pointer operator->() const {
- return data_;
- }
-
- // Casting opertor needed by the plug-in generator code.
- // TODO: Remove this method so that all conversions between smart-
- // pointers and raw-pointers are explicit.
- operator Pointer() const {
- return data_;
- }
-
- Pointer Get() const {
- return data_;
- }
-
- bool IsNull() const {
- return data_ == NULL;
- }
-
- void Reset() {
- *this = SmartPointer<C>(NULL);
- }
-
- private:
- // Helper function to conditionally add a reference to the pointed-to-data.
- void AddRef() {
- if (data_) {
- data_->AddRef();
- }
- }
-
- // Helper function to decrement the reference count of the pointed-to-data.
- // If the reference count is zero after the decrement, then the object is
- // deleted, and the pointer assigned to NULL.
- void Release();
-
- Pointer data_;
-};
-
-// Provide a convenience equality test operator on SmartPointer objects.
-template <class C>
-inline bool operator==(const SmartPointer<C>& lhs, const SmartPointer<C>& rhs) {
- return lhs.Get() == rhs.Get();
-}
-
-template <class C>
-inline SmartPointer<C>& SmartPointer<C>::operator=(const SmartPointer<C>& rhs) {
- if (this == &rhs) {
- return *this;
- }
-
- Release();
- data_ = rhs.data_;
- AddRef();
- return *this;
-}
-
-template <class C>
-void SmartPointer<C>::Release() {
- if (data_) {
- if (data_->Release() == 0) {
- delete data_;
- }
- data_ = NULL;
- }
-}
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_SMART_PTR_H_
diff --git a/o3d/core/cross/smart_ptr_test.cc b/o3d/core/cross/smart_ptr_test.cc
deleted file mode 100644
index feb45f7..0000000
--- a/o3d/core/cross/smart_ptr_test.cc
+++ /dev/null
@@ -1,167 +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 "core/cross/smart_ptr.h"
-#include "tests/common/win/testing_common.h"
-
-namespace o3d {
-
-// A simple testing helper class that tracks the number of live instances of
-// itself.
-class InstanceCount : public RefCounted {
- public:
- // Use construction & destruction to inc/dec a static instance counter.
- InstanceCount() { ++instance_count_; }
- ~InstanceCount() { --instance_count_; }
-
- static int instance_count() {
- return instance_count_;
- }
-
- private:
- static int instance_count_;
-};
-
-int InstanceCount::instance_count_ = 0;
-
-// Test case for the smart pointer class
-class SmartPtrTest : public testing::Test {
-};
-
-TEST_F(SmartPtrTest, Construct) {
- SmartPointer<InstanceCount> smart_ptr;
- ASSERT_TRUE(smart_ptr.Get() == NULL);
- ASSERT_TRUE(static_cast<InstanceCount*>(smart_ptr) == NULL);
-}
-
-// Test the behaviour of a single smart pointer without aliasing.
-TEST_F(SmartPtrTest, SingleReference) {
- InstanceCount* raw_pointer = new InstanceCount();
- SmartPointer<InstanceCount> smart_ptr(raw_pointer);
-
- // Validate that a single instance was created, and that the pointer
- // points to the correct instance.
- EXPECT_TRUE(smart_ptr.Get() == raw_pointer);
- EXPECT_TRUE(static_cast<InstanceCount*>(smart_ptr) == raw_pointer);
- EXPECT_EQ(InstanceCount::instance_count(), 1);
-
- // Validate the release mechanism when the ref-count reaches 0.
- smart_ptr.Reset();
- EXPECT_EQ(InstanceCount::instance_count(), 0);
- EXPECT_TRUE(smart_ptr.Get() == NULL);
- EXPECT_TRUE(static_cast<InstanceCount*>(smart_ptr) == NULL);
-}
-
-// Validate the behaviour of multiple smart pointers aliasing each other.
-TEST_F(SmartPtrTest, MultipleReferences) {
- SmartPointer<InstanceCount> smart_ptr(new InstanceCount());
- SmartPointer<InstanceCount> second_ref(smart_ptr);
- InstanceCount* raw_ptr = smart_ptr.Get();
-
- // Validate that only a single instance was created.
- EXPECT_EQ(InstanceCount::instance_count(), 1);
- EXPECT_TRUE(smart_ptr.Get() == second_ref.Get());
-
- // Ensure that removal of a single reference does not destroy the instance.
- smart_ptr.Reset();
- EXPECT_TRUE(smart_ptr.Get() == NULL);
- EXPECT_TRUE(second_ref.Get() == raw_ptr);
- EXPECT_EQ(InstanceCount::instance_count(), 1);
-
- // Validate the behaviour of the removal of the last reference.
- second_ref.Reset();
- EXPECT_TRUE(second_ref.Get() == NULL);
- EXPECT_EQ(InstanceCount::instance_count(), 0);
-}
-
-// Validate the relase behaviour of the smart pointer assignment operator.
-TEST_F(SmartPtrTest, AssignmentRelease) {
- SmartPointer<InstanceCount> smart_ptr1(new InstanceCount());
- SmartPointer<InstanceCount> smart_ptr2(new InstanceCount());
- InstanceCount *raw_ptr1 = smart_ptr1.Get();
- EXPECT_TRUE(raw_ptr1 != NULL);
- InstanceCount *raw_ptr2 = smart_ptr2.Get();
- EXPECT_TRUE(raw_ptr2 != NULL);
-
- // Validate that assignment destroys the previous instance.
- smart_ptr2 = smart_ptr1;
- EXPECT_EQ(InstanceCount::instance_count(), 1);
- EXPECT_TRUE(smart_ptr2.Get() == smart_ptr1.Get());
-
- // Validate that assignment of one of the ptrs to NULL does not delete
- // the instance.
- smart_ptr2 = SmartPointer<InstanceCount>(NULL);
- EXPECT_EQ(InstanceCount::instance_count(), 1);
-
- // Assignment of the last instance to NULL should delete the instance.
- smart_ptr1 = smart_ptr2;
- EXPECT_EQ(InstanceCount::instance_count(), 0);
-}
-
-// Validate the behaviour of self-assignment edge-case.
-TEST_F(SmartPtrTest, SelfAssignment) {
- SmartPointer<InstanceCount> smart_ptr1(new InstanceCount());
- smart_ptr1 = smart_ptr1;
- EXPECT_EQ(InstanceCount::instance_count(), 1);
-}
-
-TEST_F(SmartPtrTest, EqualityTest) {
- SmartPointer<InstanceCount> smart_ptr1(new InstanceCount());
- SmartPointer<InstanceCount> smart_ptr2(smart_ptr1);
- EXPECT_TRUE(smart_ptr1 == smart_ptr2);
-}
-
-// A testing helper class that exposes the add-ref and release methods of the
-// RefCounted class.
-class RefCountedHelper : public RefCounted {
- public:
- using RefCounted::AddRef;
- using RefCounted::Release;
-};
-
-class RefCountedTest : public testing::Test {
-};
-
-// Validate the behaviour of the reference-counting mechanism.
-TEST_F(RefCountedTest, Basic) {
- RefCountedHelper instance;
- instance.AddRef();
- EXPECT_EQ(instance.Release(), 0);
-
- instance.AddRef();
- instance.AddRef();
- instance.AddRef();
- instance.AddRef();
- EXPECT_EQ(instance.Release(), 3);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/standard_param.cc b/o3d/core/cross/standard_param.cc
deleted file mode 100644
index e542ee2..0000000
--- a/o3d/core/cross/standard_param.cc
+++ /dev/null
@@ -1,178 +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 declarations for StandardParamMatrix4.
-
-#include "core/cross/transformation_context.h"
-#include "core/cross/standard_param.h"
-#include "core/cross/transform.h"
-
-namespace o3d {
-// create class defintions for RTTI
-#undef O3D_STANDARD_ANNOTATION_ENTRY
-#define O3D_STANDARD_ANNOTATION_ENTRY(enum_name, class_name) \
- O3D_DEFN_CLASS(class_name ## ParamMatrix4, ParamMatrix4);
-
-O3D_STANDARD_ANNOTATIONS;
-
-
-template <>
-void StandardParamMatrix4<WORLD>::ComputeValue() {
- set_read_only_value(transformation_context_->world());
-}
-
-template <>
-void StandardParamMatrix4<WORLD_INVERSE>::ComputeValue() {
- set_read_only_value(inverse(transformation_context_->world()));
-}
-
-template <>
-void StandardParamMatrix4<WORLD_TRANSPOSE>::ComputeValue() {
- set_read_only_value(transpose(transformation_context_->world()));
-}
-
-template <>
-void StandardParamMatrix4<WORLD_INVERSE_TRANSPOSE>::ComputeValue() {
- set_read_only_value(transpose(inverse(transformation_context_->world())));
-}
-
-template <>
-void StandardParamMatrix4<VIEW>::ComputeValue() {
- set_read_only_value(transformation_context_->view());
-}
-
-template <>
-void StandardParamMatrix4<VIEW_INVERSE>::ComputeValue() {
- set_read_only_value(inverse(transformation_context_->view()));
-}
-
-template <>
-void StandardParamMatrix4<VIEW_TRANSPOSE>::ComputeValue() {
- set_read_only_value(transpose(transformation_context_->view()));
-}
-
-template <>
-void StandardParamMatrix4<VIEW_INVERSE_TRANSPOSE>::ComputeValue() {
- set_read_only_value(transpose(inverse(transformation_context_->view())));
-}
-
-template <>
-void StandardParamMatrix4<PROJECTION>::ComputeValue() {
- set_read_only_value(transformation_context_->projection());
-}
-
-template <>
-void StandardParamMatrix4<PROJECTION_INVERSE>::ComputeValue() {
- set_read_only_value(inverse(transformation_context_->projection()));
-}
-
-template <>
-void StandardParamMatrix4<PROJECTION_TRANSPOSE>::ComputeValue() {
- set_read_only_value(transpose(transformation_context_->projection()));
-}
-
-template <>
-void StandardParamMatrix4<PROJECTION_INVERSE_TRANSPOSE>::ComputeValue() {
- set_read_only_value(
- transpose(inverse(transformation_context_->projection())));
-}
-
-template <>
-void StandardParamMatrix4<WORLD_VIEW>::ComputeValue() {
- set_read_only_value(transformation_context_->view() *
- transformation_context_->world());
-}
-
-template <>
-void StandardParamMatrix4<WORLD_VIEW_INVERSE>::ComputeValue() {
- set_read_only_value(inverse(transformation_context_->view() *
- transformation_context_->world()));
-}
-
-template <>
-void StandardParamMatrix4<WORLD_VIEW_TRANSPOSE>::ComputeValue() {
- set_read_only_value(transpose(transformation_context_->view() *
- transformation_context_->world()));
-}
-
-template <>
-void StandardParamMatrix4<WORLD_VIEW_INVERSE_TRANSPOSE>::ComputeValue() {
- set_read_only_value(transpose(inverse(transformation_context_->view() *
- transformation_context_->world())));
-}
-
-template <>
-void StandardParamMatrix4<VIEW_PROJECTION>::ComputeValue() {
- set_read_only_value(transformation_context_->view_projection());
-}
-
-template <>
-void StandardParamMatrix4<VIEW_PROJECTION_INVERSE>::ComputeValue() {
- set_read_only_value(inverse(transformation_context_->view_projection()));
-}
-
-template <>
-void StandardParamMatrix4<VIEW_PROJECTION_TRANSPOSE>::ComputeValue() {
- set_read_only_value(transpose(transformation_context_->view_projection()));
-}
-
-template <>
-void StandardParamMatrix4<VIEW_PROJECTION_INVERSE_TRANSPOSE>::ComputeValue() {
- set_read_only_value(transpose(inverse(
- transformation_context_->view_projection())));
-}
-
-template <>
-void StandardParamMatrix4<WORLD_VIEW_PROJECTION>::ComputeValue() {
- set_read_only_value(transformation_context_->world_view_projection());
-}
-
-template <>
-void StandardParamMatrix4<WORLD_VIEW_PROJECTION_INVERSE>::ComputeValue() {
- set_read_only_value(inverse(transformation_context_->
- world_view_projection()));
-}
-
-template <>
-void StandardParamMatrix4<WORLD_VIEW_PROJECTION_TRANSPOSE>::ComputeValue() {
- set_read_only_value(transpose(
- transformation_context_->world_view_projection()));
-}
-
-template <>
-void StandardParamMatrix4<WORLD_VIEW_PROJECTION_INVERSE_TRANSPOSE>::
- ComputeValue() {
- set_read_only_value(transpose(inverse(
- transformation_context_->world_view_projection())));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/standard_param.h b/o3d/core/cross/standard_param.h
deleted file mode 100644
index aebb8f3..0000000
--- a/o3d/core/cross/standard_param.h
+++ /dev/null
@@ -1,174 +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 declarations for the StandardParamMatrix4 template,
-// and typedefs for the 24 instantiations.
-
-#ifndef O3D_CORE_CROSS_STANDARD_PARAM_H_
-#define O3D_CORE_CROSS_STANDARD_PARAM_H_
-
-#include "core/cross/param.h"
-#include "core/cross/transformation_context.h"
-
-namespace o3d {
-
-// The StandardParamMatrix4 class provides matrices computed from the 24
-// standard values: 6 combinations of the world, view and projection matrices
-// retrieved from the Context on the Client, and their inverse, transpose,
-// and inverse transpose (24 in all).
-
-// Predefined matrix semantics for Params. These correspond to the
-// Standard Annotations and Semantics (SAS) that O3D
-// understands. See http://developer.nvidia.com/object/using_sas.html.
-// See also Effect::GetParameterSemantic().
-
-// Here we create a list of macros so we can expand the list different ways
-// multiple times. This makes it MUCH easier to maintain. Instead of editing
-// in 144 places to edit something we only need to edit in 1.
-#undef O3D_STANDARD_ANNOTATION_ENTRY
-#define O3D_STANDARD_ANNOTATIONS \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- WORLD, \
- World) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- WORLD_INVERSE, \
- WorldInverse) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- WORLD_TRANSPOSE, \
- WorldTranspose) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- WORLD_INVERSE_TRANSPOSE, \
- WorldInverseTranspose) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- VIEW, \
- View) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- VIEW_INVERSE, \
- ViewInverse) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- VIEW_TRANSPOSE, \
- ViewTranspose) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- VIEW_INVERSE_TRANSPOSE, \
- ViewInverseTranspose) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- PROJECTION, \
- Projection) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- PROJECTION_INVERSE, \
- ProjectionInverse) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- PROJECTION_TRANSPOSE, \
- ProjectionTranspose) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- PROJECTION_INVERSE_TRANSPOSE, \
- ProjectionInverseTranspose) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- WORLD_VIEW, \
- WorldView) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- WORLD_VIEW_INVERSE, \
- WorldViewInverse) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- WORLD_VIEW_TRANSPOSE, \
- WorldViewTranspose) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- WORLD_VIEW_INVERSE_TRANSPOSE, \
- WorldViewInverseTranspose) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- VIEW_PROJECTION, \
- ViewProjection) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- VIEW_PROJECTION_INVERSE, \
- ViewProjectionInverse) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- VIEW_PROJECTION_TRANSPOSE, \
- ViewProjectionTranspose) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- VIEW_PROJECTION_INVERSE_TRANSPOSE, \
- ViewProjectionInverseTranspose) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- WORLD_VIEW_PROJECTION, \
- WorldViewProjection) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- WORLD_VIEW_PROJECTION_INVERSE, \
- WorldViewProjectionInverse) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- WORLD_VIEW_PROJECTION_TRANSPOSE, \
- WorldViewProjectionTranspose) \
- O3D_STANDARD_ANNOTATION_ENTRY( \
- WORLD_VIEW_PROJECTION_INVERSE_TRANSPOSE, \
- WorldViewProjectionInverseTranspose)
-
-#undef O3D_STANDARD_ANNOTATION_ENTRY
-#define O3D_STANDARD_ANNOTATION_ENTRY(enum_name, class_name) enum_name,
-
-enum Semantic {
- INVALID_SEMANTIC,
- O3D_STANDARD_ANNOTATIONS
-};
-
-template <Semantic S> class StandardParamMatrix4 : public ParamMatrix4 {
- public:
- explicit StandardParamMatrix4(ServiceLocator* service_locator)
- : ParamMatrix4(service_locator, true, true),
- transformation_context_(service_locator->
- GetService<TransformationContext>()) {
- SetNotCachable();
- }
-
- virtual void ComputeValue();
-
- private:
- TransformationContext* transformation_context_;
- DISALLOW_COPY_AND_ASSIGN(StandardParamMatrix4<S>);
-};
-
-#undef O3D_STANDARD_ANNOTATION_ENTRY
-#define O3D_STANDARD_ANNOTATION_ENTRY(enum_name, class_name) \
-class class_name ## ParamMatrix4 : public StandardParamMatrix4<enum_name> { \
- public: \
- /* Factory Create method. */ \
- static ObjectBase::Ref Create(ServiceLocator* service_locator) { \
- return ObjectBase::Ref(new class_name ## ParamMatrix4(service_locator)); \
- } \
- private: \
- class_name ## ParamMatrix4(ServiceLocator* service_locator) \
- : StandardParamMatrix4<enum_name>(service_locator) { \
- } \
- O3D_DECL_CLASS(class_name ## ParamMatrix4, ParamMatrix4); \
-};
-
-O3D_STANDARD_ANNOTATIONS;
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_STANDARD_PARAM_H_
diff --git a/o3d/core/cross/state.cc b/o3d/core/cross/state.cc
deleted file mode 100644
index 0f039cd..0000000
--- a/o3d/core/cross/state.cc
+++ /dev/null
@@ -1,167 +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 definition of the State class
-
-#include "core/cross/state.h"
-#include "core/cross/types.h"
-#include "core/cross/renderer.h"
-#include "core/cross/error.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(State, NamedObject);
-O3D_DEFN_CLASS(ParamState, RefParamBase);
-
-State::State(ServiceLocator* service_locator, Renderer *renderer)
- : ParamObject(service_locator) ,
- renderer_(renderer),
- weak_pointer_manager_(this) {
-}
-
-Param* State::GetUntypedStateParam(const String& state_name) {
- Param* param = GetUntypedParam(state_name);
- if (!param) {
- String name(state_name);
- const ObjectBase::Class* param_type =
- renderer_->GetStateParamType(name);
- if (!param_type) {
- // Try adding the o3d namespace prefix
- name = String(O3D_STRING_CONSTANT("") + state_name);
- param_type = renderer_->GetStateParamType(name);
- }
- if (param_type) {
- param = CreateParamByClass(name, param_type);
- }
- }
- return param;
-}
-
-// Before a Param is added, verify that if its name matches a state name
-// that its type also matches.
-bool State::OnBeforeAddParam(Param* param) {
- const ObjectBase::Class* param_type =
- renderer_->GetStateParamType(param->name());
- if (param_type) {
- return param->IsA(param_type);
- }
- return true;
-}
-
-const char* State::kAlphaTestEnableParamName =
- O3D_STRING_CONSTANT("AlphaTestEnable");
-const char* State::kAlphaReferenceParamName =
- O3D_STRING_CONSTANT("AlphaReference");
-const char* State::kAlphaComparisonFunctionParamName =
- O3D_STRING_CONSTANT("AlphaComparisonFunction");
-const char* State::kCullModeParamName =
- O3D_STRING_CONSTANT("CullMode");
-const char* State::kDitherEnableParamName =
- O3D_STRING_CONSTANT("DitherEnable");
-const char* State::kLineSmoothEnableParamName =
- O3D_STRING_CONSTANT("LineSmoothEnable");
-const char* State::kPointSpriteEnableParamName =
- O3D_STRING_CONSTANT("PointSpriteEnable");
-const char* State::kPointSizeParamName =
- O3D_STRING_CONSTANT("PointSize");
-const char* State::kPolygonOffset1ParamName =
- O3D_STRING_CONSTANT("PolygonOffset1");
-const char* State::kPolygonOffset2ParamName =
- O3D_STRING_CONSTANT("PolygonOffset2");
-const char* State::kFillModeParamName =
- O3D_STRING_CONSTANT("FillMode");
-const char* State::kZEnableParamName =
- O3D_STRING_CONSTANT("ZEnable");
-const char* State::kZWriteEnableParamName =
- O3D_STRING_CONSTANT("ZWriteEnable");
-const char* State::kZComparisonFunctionParamName =
- O3D_STRING_CONSTANT("ZComparisonFunction");
-const char* State::kAlphaBlendEnableParamName =
- O3D_STRING_CONSTANT("AlphaBlendEnable");
-const char* State::kSourceBlendFunctionParamName =
- O3D_STRING_CONSTANT("SourceBlendFunction");
-const char* State::kDestinationBlendFunctionParamName =
- O3D_STRING_CONSTANT("DestinationBlendFunction");
-const char* State::kStencilEnableParamName =
- O3D_STRING_CONSTANT("StencilEnable");
-const char* State::kStencilFailOperationParamName =
- O3D_STRING_CONSTANT("StencilFailOperation");
-const char* State::kStencilZFailOperationParamName =
- O3D_STRING_CONSTANT("StencilZFailOperation");
-const char* State::kStencilPassOperationParamName =
- O3D_STRING_CONSTANT("StencilPassOperation");
-const char* State::kStencilComparisonFunctionParamName =
- O3D_STRING_CONSTANT("StencilComparisonFunction");
-const char* State::kStencilReferenceParamName =
- O3D_STRING_CONSTANT("StencilReference");
-const char* State::kStencilMaskParamName =
- O3D_STRING_CONSTANT("StencilMask");
-const char* State::kStencilWriteMaskParamName =
- O3D_STRING_CONSTANT("StencilWriteMask");
-const char* State::kColorWriteEnableParamName =
- O3D_STRING_CONSTANT("ColorWriteEnable");
-const char* State::kBlendEquationParamName =
- O3D_STRING_CONSTANT("BlendEquation");
-const char* State::kTwoSidedStencilEnableParamName =
- O3D_STRING_CONSTANT("TwoSidedStencilEnable");
-const char* State::kCCWStencilFailOperationParamName =
- O3D_STRING_CONSTANT("CCWStencilFailOperation");
-const char* State::kCCWStencilZFailOperationParamName =
- O3D_STRING_CONSTANT("CCWStencilZFailOperation");
-const char* State::kCCWStencilPassOperationParamName =
- O3D_STRING_CONSTANT("CCWStencilPassOperation");
-const char* State::kCCWStencilComparisonFunctionParamName =
- O3D_STRING_CONSTANT("CCWStencilComparisonFunction");
-const char* State::kSeparateAlphaBlendEnableParamName =
- O3D_STRING_CONSTANT("SeparateAlphaBlendEnable");
-const char* State::kSourceBlendAlphaFunctionParamName =
- O3D_STRING_CONSTANT("SourceBlendAlphaFunction");
-const char* State::kDestinationBlendAlphaFunctionParamName =
- O3D_STRING_CONSTANT("DestinationBlendAlphaFunction");
-const char* State::kBlendAlphaEquationParamName =
- O3D_STRING_CONSTANT("BlendAlphaEquation");
-
-
-ObjectBase::Ref State::Create(ServiceLocator* service_locator) {
- Renderer* renderer = service_locator->GetService<Renderer>();
- if (NULL == renderer) {
- O3D_ERROR(service_locator) << "No Render Device Available";
- return ObjectBase::Ref();
- }
- return ObjectBase::Ref(new State(service_locator, renderer));
-}
-
-ObjectBase::Ref ParamState::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamState(service_locator, false, false));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/state.h b/o3d/core/cross/state.h
deleted file mode 100644
index dfa912e..0000000
--- a/o3d/core/cross/state.h
+++ /dev/null
@@ -1,214 +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 declaration to the State class.
-
-#ifndef O3D_CORE_CROSS_STATE_H_
-#define O3D_CORE_CROSS_STATE_H_
-
-#include "core/cross/param_object.h"
-#include "core/cross/param.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-
-class Texture;
-class Renderer;
-
-// A State handles setting render states for rendering (eg. polygon offset,
-// alpha). State settings are set using Params. This allows a State to set as
-// few params as possible and also makes it easy to query and expand as needed.
-class State : public ParamObject {
- public:
- typedef SmartPointer<State> Ref;
- typedef WeakPointer<State> WeakPointerType;
-
- State(ServiceLocator* service_locator,
- Renderer* renderer);
-
- static const char* kAlphaTestEnableParamName;
- static const char* kAlphaReferenceParamName;
- static const char* kAlphaComparisonFunctionParamName;
- static const char* kCullModeParamName;
- static const char* kDitherEnableParamName;
- static const char* kLineSmoothEnableParamName;
- static const char* kPointSpriteEnableParamName;
- static const char* kPointSizeParamName;
- static const char* kPolygonOffset1ParamName;
- static const char* kPolygonOffset2ParamName;
- static const char* kFillModeParamName;
- static const char* kZEnableParamName;
- static const char* kZWriteEnableParamName;
- static const char* kZComparisonFunctionParamName;
- static const char* kAlphaBlendEnableParamName;
- static const char* kSourceBlendFunctionParamName;
- static const char* kDestinationBlendFunctionParamName;
- static const char* kStencilEnableParamName;
- static const char* kStencilFailOperationParamName;
- static const char* kStencilZFailOperationParamName;
- static const char* kStencilPassOperationParamName;
- static const char* kStencilComparisonFunctionParamName;
- static const char* kStencilReferenceParamName;
- static const char* kStencilMaskParamName;
- static const char* kStencilWriteMaskParamName;
- static const char* kColorWriteEnableParamName;
- static const char* kBlendEquationParamName;
- static const char* kTwoSidedStencilEnableParamName;
- static const char* kCCWStencilFailOperationParamName;
- static const char* kCCWStencilZFailOperationParamName;
- static const char* kCCWStencilPassOperationParamName;
- static const char* kCCWStencilComparisonFunctionParamName;
- static const char* kSeparateAlphaBlendEnableParamName;
- static const char* kSourceBlendAlphaFunctionParamName;
- static const char* kDestinationBlendAlphaFunctionParamName;
- static const char* kBlendAlphaEquationParamName;
-
- // Comparison Operations Enumeration
- enum Comparison {
- CMP_NEVER, /* Never */
- CMP_LESS, /* Less Than */
- CMP_EQUAL, /* Equal To */
- CMP_LEQUAL, /* Less Than or Equal To */
- CMP_GREATER, /* Greater Than */
- CMP_NOTEQUAL, /* Not Equal To */
- CMP_GEQUAL, /* Greater Than or Equal To */
- CMP_ALWAYS, /* Always */
- };
-
- // Culling Operations Enumeration
- enum Cull {
- CULL_NONE, /* Don't cull */
- CULL_CW, /* Cull clock-wise faces*/
- CULL_CCW, /* Cull counter clock-wise */
- };
-
- // Fill Mode Enumeration
- enum Fill {
- POINT, /* Points only */
- WIREFRAME, /* Wireframe */
- SOLID, /* Solid fill */
- };
-
- // Blending Functions
- enum BlendingFunction {
- BLENDFUNC_ZERO,
- BLENDFUNC_ONE,
- BLENDFUNC_SOURCE_COLOR,
- BLENDFUNC_INVERSE_SOURCE_COLOR,
- BLENDFUNC_SOURCE_ALPHA,
- BLENDFUNC_INVERSE_SOURCE_ALPHA,
- BLENDFUNC_DESTINATION_ALPHA,
- BLENDFUNC_INVERSE_DESTINATION_ALPHA,
- BLENDFUNC_DESTINATION_COLOR,
- BLENDFUNC_INVERSE_DESTINATION_COLOR,
- BLENDFUNC_SOURCE_ALPHA_SATUTRATE,
- };
-
- enum BlendingEquation {
- BLEND_ADD,
- BLEND_SUBTRACT,
- BLEND_REVERSE_SUBTRACT,
- BLEND_MIN,
- BLEND_MAX,
- };
-
- enum StencilOperation {
- STENCIL_KEEP,
- STENCIL_ZERO,
- STENCIL_REPLACE,
- STENCIL_INCREMENT_SATURATE,
- STENCIL_DECREMENT_SATURATE,
- STENCIL_INVERT,
- STENCIL_INCREMENT,
- STENCIL_DECREMENT,
- };
-
- // Returns a Param for a given state. If the param does not already exist it
- // will be created. If the state_name is invalid it will return NULL
- // Parameters:
- // state_name: name of the state
- // Returns:
- // Pointer to param or NULL if no matching state.
- Param* GetUntypedStateParam(const String& state_name);
-
- // Returns a Param for a given state. If the param does not already exist it
- // will be created. If the state_name is invalid it will return NULL. If
- // the template parameter is incorrect for the given state, it will return
- // NULL
- // Parameters:
- // T: the type of the state
- // state_name: name of the state
- // Returns:
- // Pointer to param or NULL if no matching state.
- template<class T>
- T* GetStateParam(const String& state_name) {
- return ObjectBase::rtti_dynamic_cast<T>(GetUntypedStateParam(state_name));
- }
-
- // Overridden from ParamObject. We don't allow mis-matched params
- // to get created.
- virtual bool OnBeforeAddParam(Param* param);
-
- // Gets a weak pointer to us.
- WeakPointerType GetWeakPointer() const {
- return weak_pointer_manager_.GetWeakPointer();
- }
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- Renderer* renderer_;
-
- // Manager for weak pointers to us.
- WeakPointerType::WeakPointerManager weak_pointer_manager_;
-
- O3D_DECL_CLASS(State, NamedObject);
- DISALLOW_COPY_AND_ASSIGN(State);
-}; // State
-
-class ParamState : public TypedRefParam<State> {
- public:
- typedef SmartPointer<ParamState> Ref;
-
- ParamState(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedRefParam<State>(service_locator, dynamic, read_only) {}
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamState, RefParamBase)
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_STATE_H_
diff --git a/o3d/core/cross/state_set.cc b/o3d/core/cross/state_set.cc
deleted file mode 100644
index 154464b..0000000
--- a/o3d/core/cross/state_set.cc
+++ /dev/null
@@ -1,62 +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 StateSet render node implementation
-
-#include "core/cross/state_set.h"
-#include "core/cross/renderer.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(StateSet, RenderNode);
-
-const char* StateSet::kStateParamName =
- O3D_STRING_CONSTANT("state");
-
-StateSet::StateSet(ServiceLocator* service_locator)
- : RenderNode(service_locator) {
- RegisterParamRef(kStateParamName, &state_param_);
-}
-
-ObjectBase::Ref StateSet::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new StateSet(service_locator));
-}
-
-void StateSet::Render(RenderContext* render_context) {
- render_context->renderer()->PushRenderStates(state());
-}
-
-void StateSet::PostRender(RenderContext* render_context) {
- render_context->renderer()->PopRenderStates();
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/state_set.h b/o3d/core/cross/state_set.h
deleted file mode 100644
index 1881bec..0000000
--- a/o3d/core/cross/state_set.h
+++ /dev/null
@@ -1,85 +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 StateSet render node declaration.
-
-#ifndef O3D_CORE_CROSS_STATE_SET_H_
-#define O3D_CORE_CROSS_STATE_SET_H_
-
-#include "core/cross/render_node.h"
-#include "core/cross/state.h"
-
-namespace o3d {
-
-// A StateSet is a render node that sets render states for all of its children.
-class StateSet : public RenderNode {
- public:
- typedef SmartPointer<StateSet> Ref;
-
- // Names of StateSet Params.
- static const char* kStateParamName;
-
- // Gets the state.
- State* state() const {
- return state_param_->value();
- }
-
- // Sets the state.
- void set_state(State* value) {
- state_param_->set_value(value);
- }
-
- // Overridden from RenderNode. Sets the state.
- virtual void Render(RenderContext* render_context);
-
- // Overridden from RenderNode. Restores the state.
- virtual void PostRender(RenderContext* render_context);
-
- private:
- explicit StateSet(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamState::Ref state_param_; // state
-
- O3D_DECL_CLASS(StateSet, RenderNode);
- DISALLOW_COPY_AND_ASSIGN(StateSet);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_STATE_SET_H_
-
-
-
-
diff --git a/o3d/core/cross/state_set_test.cc b/o3d/core/cross/state_set_test.cc
deleted file mode 100644
index 6d784e5..0000000
--- a/o3d/core/cross/state_set_test.cc
+++ /dev/null
@@ -1,77 +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 implements unit tests for class StateSet.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/state_set.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-
-namespace o3d {
-
-class StateSetTest : public testing::Test {
- protected:
-
- StateSetTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- Pack *pack_;
-};
-
-void StateSetTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void StateSetTest::TearDown() {
- pack_->Destroy();
-}
-
-TEST_F(StateSetTest, Basic) {
- StateSet* state_set = pack()->Create<StateSet>();
- // Check that state_set got created.
- EXPECT_TRUE(state_set != NULL);
-
- // Check that the state param got created.
- EXPECT_TRUE(
- state_set->GetParam<ParamState>(StateSet::kStateParamName) != NULL);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/state_test.cc b/o3d/core/cross/state_test.cc
deleted file mode 100644
index 5b7faef..0000000
--- a/o3d/core/cross/state_test.cc
+++ /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 implements unit tests for class State.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/state.h"
-
-namespace o3d {
-
-class StateTest : public testing::Test {
- protected:
-
- StateTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- Pack *pack_;
-};
-
-void StateTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void StateTest::TearDown() {
- pack_->Destroy();
-}
-
-TEST_F(StateTest, Basic) {
- State* state = pack()->Create<State>();
- // Check that state_set got created.
- ASSERT_TRUE(state != NULL);
-
- // Check that we can't create a param of the wrong type.
- EXPECT_TRUE(
- state->CreateParam<ParamMatrix4>(State::kFillModeParamName) == NULL);
-}
-
-TEST_F(StateTest, GetStateParam) {
- State* state = pack()->Create<State>();
- // Check that state_set got created.
- ASSERT_TRUE(state != NULL);
-
- // Check that we can get a state param by name.
- ParamBoolean* alpha_param = state->GetStateParam<ParamBoolean>(
- State::kAlphaBlendEnableParamName);
- EXPECT_TRUE(alpha_param != NULL);
-
- // Check that a name of a state that does not exist fails.
- EXPECT_TRUE(state->GetStateParam<ParamBoolean>("foobar") == NULL);
-
- // Check that a mis-matched state fails.
- EXPECT_TRUE(state->GetStateParam<ParamFloat>(
- State::kAlphaComparisonFunctionParamName) == NULL);
-
- // Check that if we create one by hand GetStateParam gets the same one.
- ParamBoolean* z_param = state->CreateParam<ParamBoolean>(
- State::kZEnableParamName);
- EXPECT_TRUE(z_param != NULL);
- EXPECT_EQ(z_param, state->GetStateParam<ParamBoolean>(
- State::kZEnableParamName));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/stream.cc b/o3d/core/cross/stream.cc
deleted file mode 100644
index b75aa17..0000000
--- a/o3d/core/cross/stream.cc
+++ /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 contains the definition of the Stream class.
-
-#include "core/cross/stream.h"
-#include "core/cross/buffer.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Stream, ObjectBase);
-O3D_DEFN_CLASS(ParamVertexBufferStream, RefParamBase);
-
-Stream::Stream(ServiceLocator* service_locator,
- Field *field,
- unsigned int start_index,
- Semantic semantic,
- int semantic_index)
- : ObjectBase(service_locator),
- field_(field),
- last_field_change_count_(0),
- start_index_(start_index),
- semantic_(semantic),
- semantic_index_(semantic_index) {
- DCHECK(field);
-}
-
-unsigned Stream::GetMaxVertices() const {
- Buffer* buffer = field_->buffer();
-
- if (!field_->buffer()) {
- return 0;
- }
-
- unsigned int num_elements = buffer->num_elements();
- if (start_index_ > num_elements) {
- return 0;
- }
-
- // TODO: If the number of elements is 1 we assume we want to repeat the
- // value (ie, use a stride of 0). We can't do this yet because it's hard to
- // implement in GL.
- // if (num_elements == 1) {
- // return UINT_MAX;
- // }
-
- return num_elements - start_index_;
-}
-
-const char* Stream::GetSemanticDescription(Stream::Semantic semantic) {
- switch (semantic) {
- case POSITION:
- return "POSITION";
- case NORMAL:
- return "NORMAL";
- case TANGENT:
- return "TANGENT";
- case BINORMAL:
- return "BINORMAL";
- case COLOR:
- return "COLOR";
- case TEXCOORD:
- return "TEXCOORD";
- default:
- return "UNKNOWN";
- }
-}
-
-void ParamVertexBufferStream::CopyDataFromParam(Param *source_param) {
- DCHECK(false); // this should never get called.
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/stream.h b/o3d/core/cross/stream.h
deleted file mode 100644
index 15830bd..0000000
--- a/o3d/core/cross/stream.h
+++ /dev/null
@@ -1,181 +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 declarations for the Stream class.
-
-#ifndef O3D_CORE_CROSS_STREAM_H_
-#define O3D_CORE_CROSS_STREAM_H_
-
-#include <vector>
-#include "core/cross/field.h"
-#include "core/cross/param.h"
-
-namespace o3d {
-
-class ServiceLocator;
-
-// A stream object defines how Field data is interpreted by a Shape. It contains
-// a reference to a Field the semantic associated with it.
-class Stream : public ObjectBase {
- public:
- typedef SmartPointer<Stream> Ref;
-
- // Semantics used when binding buffers to the shape. They determine how
- // the Stream links up to the shader inputs.
- // TODO: replace the Stream::Semantic types with proper semantic
- // strings and maps that allow aliasing of semantics.
- enum Semantic {
- UNKNOWN_SEMANTIC = 0,
- POSITION, // Position
- NORMAL, // Normal
- TANGENT, // Tangent
- BINORMAL, // Binormal
- COLOR, // Color
- TEXCOORD, // Texture Coordinate
- };
-
- Stream(ServiceLocator* service_locator,
- Field *field,
- unsigned int start_index,
- Semantic semantic,
- int semantic_index);
-
- // Returns a pointer to the associated Field object.
- Field& field() const {
- // This is guaranteed to be not NULL.
- return *field_.Get();
- }
-
- // Returns the semantic specified for the Stream.
- Semantic semantic() const { return semantic_; }
-
- // Returns the semantic index specified for the Stream
- // (eg., TEXCOORD1 = 1, BINORMAL7 = 7, etc).
- int semantic_index() const { return semantic_index_; }
-
- // Returns the start index for the specified Stream.
- unsigned int start_index() const { return start_index_; }
-
- // Returns the maximum vertices available given the stream's settings
- // and its buffer.
- unsigned GetMaxVertices() const;
-
- // Gets the last field change count.
- unsigned int last_field_change_count() const {
- return last_field_change_count_;
- }
-
- // Sets the last field change count.
- void set_last_field_change_count(unsigned int count) const {
- last_field_change_count_ = count;
- }
-
- static const char* GetSemanticDescription(Semantic);
-
- private:
- Field::Ref field_;
-
- // which field in the buffer this stream is using
- unsigned int field_id_;
-
- // Used to track if the field has changed offsets.
- mutable unsigned int last_field_change_count_;
-
- unsigned int start_index_;
- Semantic semantic_;
- int semantic_index_;
-
- O3D_DECL_CLASS(Stream, ObjectBase);
- DISALLOW_COPY_AND_ASSIGN(Stream);
-};
-
-// Defines a type for an array Stream objects.
-typedef std::vector<Stream::Ref> StreamRefVector;
-
-// A Param that can modify the contents of a vertex buffer.
-// NOTE: This param behaves like no other param and therefore seems a little
-// fishy. It feels like ParamChar (if there was such a thing) where you can do
-// things like:
-//
-// param->set_value(value);
-// value = param->value();
-// param->bind(otherParamVertexBufferStream);
-//
-// But, the difference is when you call param->value(), if the param is bound to
-// another stream we don't copy the stream or reference to the stream like other
-// params. Using SlaveParamVertexBufferStream which is derived from this class
-// a call to value() will call UpdateValue() which will call a virtual
-// ComputeValue() which will update the vertex buffers in the destination stream
-// using whatever means the owner of the Slave param specifies.
-class ParamVertexBufferStream : public TypedParamBase<char> {
- public:
- typedef SmartPointer<ParamVertexBufferStream> Ref;
-
- ParamVertexBufferStream(ServiceLocator* service_locator,
- Stream* stream,
- bool dynamic,
- bool read_only)
- : TypedParamBase<char>(service_locator, dynamic, read_only),
- stream_(stream) {
- DCHECK(stream);
- }
-
- virtual void CopyDataFromParam(Param *source_param);
-
- const Stream& stream() {
- // We guarantee there will always be a stream.
- return *stream_.Get();
- }
-
- // Marks the stream as valid so that it will not be updated again until
- // invalid.
- void ValidateStream() {
- Validate();
- }
-
- // Updates the stream if its bound to anything.
- void UpdateStream() {
- UpdateValue();
- }
-
- private:
- Stream::Ref stream_;
-
- O3D_DECL_CLASS(ParamVertexBufferStream, Param);
- DISALLOW_COPY_AND_ASSIGN(ParamVertexBufferStream);
-};
-
-typedef std::vector<ParamVertexBufferStream::Ref> StreamParamVector;
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_STREAM_H_
diff --git a/o3d/core/cross/stream_bank.cc b/o3d/core/cross/stream_bank.cc
deleted file mode 100644
index 82105b9..0000000
--- a/o3d/core/cross/stream_bank.cc
+++ /dev/null
@@ -1,187 +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 definition of StreamBank.
-
-#include "core/cross/stream_bank.h"
-#include "core/cross/renderer.h"
-#include "core/cross/error.h"
-#include "core/cross/vertex_source.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(StreamBank, VertexSource);
-O3D_DEFN_CLASS(ParamStreamBank, RefParamBase);
-
-ObjectBase::Ref StreamBank::Create(ServiceLocator* service_locator) {
- Renderer* renderer = service_locator->GetService<Renderer>();
- if (NULL == renderer) {
- O3D_ERROR(service_locator) << "No Render Device Available";
- return ObjectBase::Ref();
- }
-
- return ObjectBase::Ref(renderer->CreateStreamBank());
-}
-
-StreamBank::StreamBank(ServiceLocator* service_locator)
- : VertexSource(service_locator),
- number_binds_(0),
- change_count_(1),
- renderable_(true),
- weak_pointer_manager_(this) {
-}
-
-StreamBank::~StreamBank() {
-}
-
-unsigned StreamBank::GetMaxVertices() const {
- unsigned int max_vertices = UINT_MAX;
- StreamParamVector::const_iterator stream_iter;
- for (stream_iter = vertex_stream_params_.begin();
- stream_iter != vertex_stream_params_.end();
- ++stream_iter) {
- const Stream& stream = (*stream_iter)->stream();
- max_vertices = std::min(max_vertices, stream.GetMaxVertices());
- }
- return max_vertices;
-}
-
-void StreamBank::UpdateRenderable() {
- StreamParamVector::const_iterator stream_iter;
- for (stream_iter = vertex_stream_params_.begin();
- stream_iter != vertex_stream_params_.end();
- ++stream_iter) {
- const Stream& stream = (*stream_iter)->stream();
- Buffer* buffer = stream.field().buffer();
- if (!buffer || !buffer->IsA(VertexBuffer::GetApparentClass())) {
- renderable_ = false;
- return;
- }
- }
- renderable_ = true;
-}
-
-// Adds a new vertex Stream to the StreamBank. If a Stream with the same
-// semantic is already bound to the StreamBank then it removes it before adding
-// the new one. Otherwise, it creates a new stream with the information supplied
-// in the parameters and adds it to the array of streams referenced by the
-// StreamBank.
-bool StreamBank::SetVertexStream(Stream::Semantic stream_semantic,
- int semantic_index,
- Field* field,
- unsigned int start_index) {
- Buffer* buffer = field->buffer();
- if (!buffer) {
- O3D_ERROR(service_locator()) << "No buffer on field";
- return false;
- }
-
- ++change_count_;
-
- Stream::Ref stream(new Stream(service_locator(),
- field,
- start_index,
- stream_semantic,
- semantic_index));
-
- // If a stream with the same semantic has already been set then remove it.
- RemoveVertexStream(stream_semantic, semantic_index);
-
- ParamVertexBufferStream::Ref stream_param(
- new SlaveParamVertexBufferStream(service_locator(), this, stream));
- vertex_stream_params_.push_back(stream_param);
-
- UpdateRenderable();
- OnUpdateStreams();
-
- return true;
-}
-
-// Looks for a vertex stream with the given semantic in the array of vertex
-// streams stored in the StreamBank. Right now it does a simple linear pass
-// through all the streams.
-const Stream* StreamBank::GetVertexStream(Stream::Semantic stream_semantic,
- int semantic_index) const {
- ParamVertexBufferStream* param = GetVertexStreamParam(stream_semantic,
- semantic_index);
- return param ? &param->stream() : NULL;
-}
-
-ParamVertexBufferStream* StreamBank::GetVertexStreamParam(
- Stream::Semantic semantic,
- int semantic_index) const {
- StreamParamVector::const_iterator iter, end = vertex_stream_params_.end();
- for (iter = vertex_stream_params_.begin(); iter != end; ++iter) {
- const Stream& stream = (*iter)->stream();
- if (stream.semantic() == semantic &&
- stream.semantic_index() == semantic_index) {
- return *iter;
- }
- }
- return NULL;
-}
-
-bool StreamBank::RemoveVertexStream(Stream::Semantic stream_semantic,
- int semantic_index) {
- StreamParamVector::iterator iter, end = vertex_stream_params_.end();
- for (iter = vertex_stream_params_.begin(); iter != end; ++iter) {
- const Stream& stream = (*iter)->stream();
- if (stream.semantic() == stream_semantic &&
- stream.semantic_index() == semantic_index) {
- ++change_count_;
- vertex_stream_params_.erase(iter);
- UpdateRenderable();
- OnUpdateStreams();
- return true;
- }
- }
- return false;
-}
-
-void StreamBank::UpdateStreams() {
- if (number_binds_) {
- // TODO: Although a second call to UpdateStream on these streams
- // should do nothing, is there any way to void the loop the second time
- // through? Short of checking that each stream param is valid which is a
- // loop, I'm not sure what we could do but because this loop is only called
- // for things that are bound it's unlikely it will be here often.
- for (unsigned ii = 0; ii < vertex_stream_params_.size(); ++ii) {
- vertex_stream_params_[ii]->UpdateStream(); // Triggers updating.
- }
- }
-}
-
-ObjectBase::Ref ParamStreamBank::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamStreamBank(service_locator, false, false));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/stream_bank.h b/o3d/core/cross/stream_bank.h
deleted file mode 100644
index c5d6bd9..0000000
--- a/o3d/core/cross/stream_bank.h
+++ /dev/null
@@ -1,185 +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 cotnains the declaration of StreamBank.
-
-#ifndef O3D_CORE_CROSS_STREAM_BANK_H_
-#define O3D_CORE_CROSS_STREAM_BANK_H_
-
-#include <vector>
-#include <map>
-#include "core/cross/element.h"
-#include "core/cross/stream.h"
-#include "core/cross/vertex_source.h"
-
-namespace o3d {
-
-// A StreamBank collects streams so they can be shared amoung StreamBanks. It
-// also handles platform specific things like vertex declarations..
-class StreamBank : public VertexSource {
- public:
- typedef SmartPointer<StreamBank> Ref;
- typedef WeakPointer<StreamBank> WeakPointerType;
-
- virtual ~StreamBank();
-
- // The number of times streams have been added or removed from this stream
- // bank. Can be used for caching.
- int change_count() const {
- return change_count_;
- }
-
- // True if all the streams on this streambank are renderable.
- bool renderable() const {
- return renderable_;
- }
-
- // Binds a field of a vertex buffer to the streambank and defines how the data
- // in the buffer should be accessed and interpreted. The buffer of the field
- // must be of a compatible type otherwise the binding fails and the function
- // returns false.
- virtual bool SetVertexStream(Stream::Semantic semantic,
- int semantic_index,
- Field* field,
- unsigned int start_index);
-
- // Searches the vertex streams bound to the shape for one with the given
- // stream semantic. If a stream is not found then it returns NULL.
- const Stream* GetVertexStream(Stream::Semantic stream_semantic,
- int semantic_index) const;
-
- // Removes a vertex stream from this primitive.
- // Returns true if the specified stream existed.
- bool RemoveVertexStream(Stream::Semantic stream_semantic,
- int semantic_index);
-
- // Returns the maximum vertices available given the streams currently
- // set on this StreamBank.
- unsigned GetMaxVertices() const;
-
- // Overriden from VertexSource.
- virtual ParamVertexBufferStream* GetVertexStreamParam(
- Stream::Semantic semantic,
- int semantic_index) const;
-
- const StreamParamVector& vertex_stream_params() const {
- return vertex_stream_params_;
- }
-
- // If the streams are bound to other streams, update them.
- void UpdateStreams();
-
- // Gets a weak pointer to us.
- WeakPointerType GetWeakPointer() const {
- return weak_pointer_manager_.GetWeakPointer();
- }
-
- protected:
- explicit StreamBank(ServiceLocator* service_locator);
-
- class SlaveParamVertexBufferStream : public ParamVertexBufferStream {
- public:
- typedef SmartPointer<SlaveParamVertexBufferStream> Ref;
- SlaveParamVertexBufferStream(ServiceLocator* service_locator,
- StreamBank* master,
- Stream* stream)
- : ParamVertexBufferStream(service_locator, stream, true, false),
- master_(master) {
- }
-
- virtual void CopyDataFromParam(Param* source_param) {
- // do nothing.
- }
-
- virtual void OnAfterBindInput() {
- ++master_->number_binds_;
- }
-
- virtual void OnAfterUnbindInput(Param* old_source) {
- --master_->number_binds_;
- }
-
- private:
- StreamBank* master_;
- DISALLOW_COPY_AND_ASSIGN(SlaveParamVertexBufferStream);
- };
-
- // Called after the a stream as been added or removed.
- // Overridden in derived classes that need to know when a stream has been
- // added or removed.
- virtual void OnUpdateStreams() { }
-
- StreamParamVector vertex_stream_params_;
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // Updates the renderable flag.
- void UpdateRenderable();
-
- // the number of streams that are bound to a VertexSource.
- // Used as a shortcut. If zero no need to do expensive checking.
- unsigned int number_binds_;
-
- // The number of times a stream has been added or removed.
- int change_count_;
-
- // True if all the streams on this streambank are renderable.
- bool renderable_;
-
- // Manager for weak pointers to us.
- WeakPointerType::WeakPointerManager weak_pointer_manager_;
-
- O3D_DECL_CLASS(StreamBank, NamedObject);
- DISALLOW_COPY_AND_ASSIGN(StreamBank);
-};
-
-class ParamStreamBank : public TypedRefParam<StreamBank> {
- public:
- typedef SmartPointer<ParamStreamBank> Ref;
-
- ParamStreamBank(ServiceLocator* service_locator,
- bool dynamic,
- bool read_only)
- : TypedRefParam<StreamBank>(service_locator, dynamic, read_only) {}
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamStreamBank, RefParamBase)
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_STREAM_BANK_H_
diff --git a/o3d/core/cross/stream_bank_test.cc b/o3d/core/cross/stream_bank_test.cc
deleted file mode 100644
index 2c962f9..0000000
--- a/o3d/core/cross/stream_bank_test.cc
+++ /dev/null
@@ -1,296 +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 implements unit tests for class StreamBank.
-
-#include "core/cross/skin.h"
-#include "core/cross/stream_bank.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/pointer_utils.h"
-#include "core/cross/fake_vertex_source.h"
-#include "tests/common/win/testing_common.h"
-
-namespace o3d {
-
-namespace {
-
-static const float kEpsilon = 0.0000001f;
-
-bool CompareVertices(StreamBank* source,
- Stream::Semantic semantic,
- int semantic_index,
- const float* values,
- float multiplier) {
- const Stream* stream = source->GetVertexStream(semantic, semantic_index);
- if (!stream) {
- return false;
- }
-
- const Field& field = stream->field();
- Buffer* buffer = field.buffer();
- if (!buffer) {
- return false;
- }
- BufferLockHelper helper(buffer);
- void* data = helper.GetData(Buffer::READ_ONLY);
- if (!data) {
- return false;
- }
-
- unsigned num_vertices = stream->GetMaxVertices();
- unsigned stride = buffer->stride();
-
- const float* source_values = PointerFromVoidPointer<const float*>(
- data, field.offset());
- while (num_vertices) {
- for (unsigned jj = 0; jj < 3; ++jj) {
- float difference = fabsf(source_values[jj] - values[jj] * multiplier);
- if (difference > kEpsilon) {
- return false;
- }
- }
- values += 3;
- source_values = AddPointerOffset(source_values, stride);
- --num_vertices;
- }
- return true;
-}
-
-} // anonymous namespace
-
-class StreamBankTest : public testing::Test {
- protected:
-
- StreamBankTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- Pack *pack_;
-};
-
-void StreamBankTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void StreamBankTest::TearDown() {
- pack_->Destroy();
-}
-
-TEST_F(StreamBankTest, Basic) {
- static float cube_vertices[][3] = {
- { -1.0f, -1.0f, 1.0f, }, // vertex v0
- { +1.0f, -1.0f, 1.0f, }, // vertex v1
- { +1.0f, -1.0f, -1.0f, }, // vertex v2
- { -1.0f, -1.0f, -1.0f, }, // vertex v3
- { -1.0f, 1.0f, 1.0f, }, // vertex v4
- { +1.0f, 1.0f, 1.0f, }, // vertex v5
- { +1.0f, 1.0f, -1.0f, }, // vertex v6
- { -1.0f, 1.0f, -1.0f, }, // vertex v7
- };
- const unsigned kNumVertices = arraysize(cube_vertices);
- const unsigned kNumComponents = arraysize(cube_vertices[0]);
-
- StreamBank* stream_bank = pack()->Create<StreamBank>();
- // Check that StreamBank got created.
- ASSERT_TRUE(stream_bank != NULL);
- EXPECT_TRUE(stream_bank->IsA(StreamBank::GetApparentClass()));
- EXPECT_TRUE(stream_bank->IsA(VertexSource::GetApparentClass()));
- EXPECT_TRUE(stream_bank->renderable());
-
- // Check Setting Vertex Streams.
- VertexBuffer* vertex_buffer = pack()->Create<VertexBuffer>();
- ASSERT_TRUE(vertex_buffer != NULL);
-
- Field* field = vertex_buffer->CreateField(FloatField::GetApparentClass(),
- kNumComponents);
- ASSERT_TRUE(field != NULL);
- ASSERT_TRUE(vertex_buffer->AllocateElements(kNumVertices));
- field->SetFromFloats(&cube_vertices[0][0], kNumComponents, 0, kNumVertices);
-
- EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION,
- 0,
- field,
- 0));
- // Check getting a stream.
- const Stream* vertex_stream = stream_bank->GetVertexStream(Stream::POSITION,
- 0);
- ASSERT_TRUE(vertex_stream != NULL);
- EXPECT_EQ(&vertex_stream->field(), field);
- EXPECT_EQ(vertex_stream->semantic(), Stream::POSITION);
- EXPECT_EQ(vertex_stream->semantic_index(), 0);
-
- // Check removing the streams.
- EXPECT_FALSE(stream_bank->RemoveVertexStream(Stream::POSITION, 1));
- EXPECT_FALSE(stream_bank->RemoveVertexStream(Stream::BINORMAL, 0));
- EXPECT_TRUE(stream_bank->RemoveVertexStream(Stream::POSITION, 0));
- EXPECT_FALSE(stream_bank->RemoveVertexStream(Stream::POSITION, 0));
-}
-
-TEST_F(StreamBankTest, Renderable) {
- StreamBank* stream_bank = pack()->Create<StreamBank>();
- ASSERT_TRUE(stream_bank != NULL);
-
- VertexBuffer* vertex_buffer = pack()->Create<VertexBuffer>();
- ASSERT_TRUE(vertex_buffer != NULL);
- SourceBuffer* source_buffer = pack()->Create<SourceBuffer>();
- ASSERT_TRUE(source_buffer != NULL);
-
- Field* field1 = vertex_buffer->CreateField(FloatField::GetApparentClass(), 1);
- Field* field2 = source_buffer->CreateField(FloatField::GetApparentClass(), 1);
- ASSERT_TRUE(field1 != NULL);
- ASSERT_TRUE(field2 != NULL);
-
- EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION, 0, field1, 0));
- EXPECT_TRUE(stream_bank->renderable());
- EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION, 1, field2, 0));
- EXPECT_FALSE(stream_bank->renderable());
- EXPECT_TRUE(stream_bank->RemoveVertexStream(Stream::POSITION, 1));
- EXPECT_TRUE(stream_bank->renderable());
- EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION, 0, field2, 0));
- EXPECT_FALSE(stream_bank->renderable());
- EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION, 0, field1, 0));
- EXPECT_TRUE(stream_bank->renderable());
- EXPECT_FALSE(stream_bank->RemoveVertexStream(Stream::POSITION, 1));
- EXPECT_FALSE(stream_bank->RemoveVertexStream(Stream::BINORMAL, 0));
- EXPECT_TRUE(stream_bank->RemoveVertexStream(Stream::POSITION, 0));
- EXPECT_FALSE(stream_bank->RemoveVertexStream(Stream::POSITION, 0));
-}
-
-TEST_F(StreamBankTest, BindStream) {
- static float some_vertices[][3] = {
- { 1.0f, 2.0f, 3.0f, },
- { 7.0f, 8.0f, 9.0f, },
- { 4.0f, 5.0f, 6.0f, },
- };
- const unsigned kNumVertices = arraysize(some_vertices);
- const unsigned kNumComponents = arraysize(some_vertices[0]);
-
- StreamBank* stream_bank = pack()->Create<StreamBank>();
- ASSERT_TRUE(stream_bank != NULL);
-
- // Create 2 Vertex Buffers.
- VertexBuffer* vertex_buffer_1 = pack()->Create<VertexBuffer>();
- VertexBuffer* vertex_buffer_2 = pack()->Create<VertexBuffer>();
- ASSERT_TRUE(vertex_buffer_1 != NULL);
- ASSERT_TRUE(vertex_buffer_2 != NULL);
-
- // Create a field on each buffer.
- Field* vertex_field_1 = vertex_buffer_1->CreateField(
- FloatField::GetApparentClass(), kNumComponents);
- Field* vertex_field_2 = vertex_buffer_2->CreateField(
- FloatField::GetApparentClass(), kNumComponents);
- ASSERT_TRUE(vertex_field_1 != NULL);
- ASSERT_TRUE(vertex_field_2 != NULL);
- ASSERT_TRUE(vertex_buffer_1->AllocateElements(kNumVertices));
- ASSERT_TRUE(vertex_buffer_2->AllocateElements(kNumVertices));
-
- // Set up streams on StreamBank.
- EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION,
- 0,
- vertex_field_1,
- 0));
- EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION,
- 1,
- vertex_field_2,
- 0));
-
- // Create 2 source buffers.
- SourceBuffer* source_buffer_1 = pack()->Create<SourceBuffer>();
- SourceBuffer* source_buffer_2 = pack()->Create<SourceBuffer>();
- ASSERT_TRUE(source_buffer_1 != NULL);
- ASSERT_TRUE(source_buffer_2 != NULL);
-
- // Create a field on each buffer.
- Field* source_field_1 = source_buffer_1->CreateField(
- FloatField::GetApparentClass(), kNumComponents);
- Field* source_field_2 = source_buffer_2->CreateField(
- FloatField::GetApparentClass(), kNumComponents);
- ASSERT_TRUE(source_field_1 != NULL);
- ASSERT_TRUE(source_field_2 != NULL);
-
- // Put some vertices in the source streams.
- ASSERT_TRUE(source_buffer_1->AllocateElements(kNumVertices));
- source_field_1->SetFromFloats(&some_vertices[0][0], kNumComponents, 0,
- kNumVertices);
- ASSERT_TRUE(source_buffer_2->AllocateElements(kNumVertices));
- source_field_2->SetFromFloats(&some_vertices[0][0], kNumComponents, 0,
- kNumVertices);
-
- scoped_ptr<FakeVertexSource> source(new FakeVertexSource(
- pack()->service_locator()));
- ASSERT_TRUE(source != NULL);
-
- // Set up streams on source
- EXPECT_TRUE(source->SetVertexStream(Stream::POSITION,
- 0,
- source_field_1,
- 0));
- EXPECT_TRUE(source->SetVertexStream(Stream::POSITION,
- 1,
- source_field_2,
- 0));
-
- // Bind the vertices to both dest streams.
- EXPECT_TRUE(stream_bank->BindStream(source.get(), Stream::POSITION, 0));
- EXPECT_TRUE(stream_bank->BindStream(source.get(), Stream::POSITION, 1));
- // Non-existant streams should fail.
- EXPECT_FALSE(stream_bank->BindStream(source.get(), Stream::POSITION, 2));
- EXPECT_FALSE(stream_bank->BindStream(source.get(), Stream::COLOR, 10));
-
- // Cause the vertices to get updated.
- stream_bank->UpdateStreams();
-
- // Test that vertices get updated.
- EXPECT_TRUE(CompareVertices(stream_bank,
- Stream::POSITION,
- 0,
- &some_vertices[0][0],
- 2.0f));
- EXPECT_TRUE(CompareVertices(stream_bank,
- Stream::POSITION,
- 1,
- &some_vertices[0][0],
- 3.0f));
-
- // Check that UpdateOutputs only got called once.
- EXPECT_EQ(source->update_outputs_call_count(), 1U);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/stream_test.cc b/o3d/core/cross/stream_test.cc
deleted file mode 100644
index 7f1a7de..0000000
--- a/o3d/core/cross/stream_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.
- */
-
-
-// Tests the functionality of the Stream class.
-
-#include "core/cross/stream.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/buffer.h"
-#include "tests/common/win/testing_common.h"
-#include "core/cross/object_manager.h"
-
-namespace o3d {
-
-namespace {
-
-// A class derived from Buffer that trivially defines the virtual methods.
-class FieldTest : public Field {
- public:
- FieldTest() : Field(g_service_locator, NULL, 3, 4) {}
-
- virtual size_t GetFieldComponentSize() const { return 1; }
-
- virtual void SetFromFloats(const float* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements) { }
-
- virtual void SetFromUInt32s(const uint32* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements) { }
-
- virtual void SetFromUByteNs(const uint8* source,
- unsigned source_stride,
- unsigned destination_start_index,
- unsigned num_elements) { }
-
- virtual void GetAsFloats(unsigned source_start_index,
- float* destination,
- unsigned destination_stride,
- unsigned num_elements) const { }
-
- virtual bool SetFromMemoryStream(MemoryReadStream* stream) { return true; }
-
- virtual void ConcreteCopy(const Field& source) { }
-};
-
-} // end unnamed namespace
-
-// Basic test fixture for the Stream class. Nothing gets created during SetUp.
-class StreamBasic : public testing::Test {
- protected:
- StreamBasic()
- : object_manager_(g_service_locator) { }
-
- ServiceDependency<ObjectManager> object_manager_;
-};
-
-// Tests the Stream constructor to make sure that all the arguments are set
-// properly.
-TEST_F(StreamBasic, Constructor) {
- FieldTest::Ref field(new FieldTest());
-
- unsigned start_index = 1;
- int semantic_index = 2;
- Stream::Semantic semantic = Stream::BINORMAL;
-
- Stream stream(g_service_locator,
- field, start_index, semantic, semantic_index);
-
- EXPECT_EQ(field, &stream.field());
- EXPECT_EQ(start_index, stream.start_index());
- EXPECT_EQ(semantic, stream.semantic());
- EXPECT_EQ(semantic_index, stream.semantic_index());
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/texture.cc b/o3d/core/cross/texture.cc
deleted file mode 100644
index c07e99e..0000000
--- a/o3d/core/cross/texture.cc
+++ /dev/null
@@ -1,788 +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 definition of the Texture2D and TextureCUBE classes.
-
-#include <cmath>
-#include "core/cross/texture.h"
-#include "core/cross/bitmap.h"
-#include "core/cross/canvas.h"
-#include "core/cross/renderer.h"
-#include "core/cross/client_info.h"
-#include "core/cross/error.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Texture2D, Texture);
-O3D_DEFN_CLASS(TextureCUBE, Texture);
-
-const char* Texture2D::kWidthParamName =
- O3D_STRING_CONSTANT("width");
-const char* Texture2D::kHeightParamName =
- O3D_STRING_CONSTANT("height");
-const char* TextureCUBE::kEdgeLengthParamName =
- O3D_STRING_CONSTANT("edgeLength");
-
-Texture2D::Texture2D(ServiceLocator* service_locator,
- int width,
- int height,
- Format format,
- int levels,
- bool enable_render_surfaces)
- : Texture(service_locator, format, levels, enable_render_surfaces),
- surface_map_(levels) {
- RegisterReadOnlyParamRef(kWidthParamName, &width_param_);
- RegisterReadOnlyParamRef(kHeightParamName, &height_param_);
- width_param_->set_read_only_value(width);
- height_param_->set_read_only_value(height);
-
- for (int ii = 0; ii < kMaxLevels; ++ii) {
- locked_levels_[ii] = kNone;
- }
-
- ClientInfoManager* client_info_manager =
- service_locator->GetService<ClientInfoManager>();
- client_info_manager->AdjustTextureMemoryUsed(
- static_cast<int>(image::ComputeMipChainSize(
- width, height, format, levels)));
-}
-
-Texture2D::~Texture2D() {
- bool reported = false;
- for (int ii = 0; ii < levels(); ++ii) {
- if (IsLocked(ii)) {
- if (!reported) {
- reported = true;
- O3D_ERROR(service_locator())
- << "Texture2D \"" << name()
- << "\" was never unlocked before being destroyed.";
- }
- Unlock(ii);
- }
- }
-
- ClientInfoManager* client_info_manager =
- service_locator()->GetService<ClientInfoManager>();
- client_info_manager->AdjustTextureMemoryUsed(
- -static_cast<int>(image::ComputeMipChainSize(width(),
- height(),
- format(),
- levels())));
-}
-
-void Texture2D::DrawImage(const Bitmap& src_img,
- int src_mip,
- int src_x, int src_y,
- int src_width, int src_height,
- int dst_mip,
- int dst_x, int dst_y,
- int dst_width, int dst_height) {
- DCHECK(src_img.image_data());
-
- if (dst_mip < 0 || dst_mip >= levels()) {
- O3D_ERROR(service_locator()) << "Mip out of range";
- }
-
- if (src_mip < 0 || src_mip >= static_cast<int>(src_img.num_mipmaps())) {
- O3D_ERROR(service_locator()) << "Source Mip out of range";
- }
-
- // Clip source and destination rectangles to
- // source and destination bitmaps.
- // if src or dest rectangle is out of boundary,
- // do nothing and return.
- if (!image::AdjustDrawImageBoundary(&src_x, &src_y,
- &src_width, &src_height,
- src_mip,
- src_img.width(), src_img.height(),
- &dst_x, &dst_y,
- &dst_width, &dst_height,
- dst_mip,
- width(), height())) {
- return;
- }
-
- // check formats of source and dest images.
- // format of source and dest should be the same.
- if (src_img.format() != format()) {
- O3D_ERROR(service_locator()) << "formats must be the same.";
- return;
- }
-
- unsigned int mip_width = image::ComputeMipDimension(dst_mip, width());
- unsigned int mip_height = image::ComputeMipDimension(dst_mip, height());
-
- // if src and dest are in the same size and drawImage is copying
- // the entire bitmap on dest image, just perform memcpy.
- if (src_x == 0 && src_y == 0 && dst_x == 0 && dst_y == 0 &&
- src_img.width() == mip_width && src_img.height() == mip_height &&
- static_cast<unsigned int>(src_width) == src_img.width() &&
- static_cast<unsigned int>(src_height) == src_img.height() &&
- static_cast<unsigned int>(dst_width) == mip_width &&
- static_cast<unsigned int>(dst_height) == mip_height) {
- SetRect(dst_mip, 0, 0, mip_width, mip_height,
- src_img.GetMipData(src_mip),
- src_img.GetMipPitch(src_mip));
- return;
- }
-
- unsigned int components = image::GetNumComponentsForFormat(format());
- if (components == 0) {
- O3D_ERROR(service_locator()) << "DrawImage does not support format: "
- << src_img.format() << " unless src and "
- << "dest images are in the same size and "
- << "copying the entire bitmap";
- return;
- }
-
- int src_pitch = src_img.GetMipPitch(src_mip);
- if (image::AdjustForSetRect(&src_y, src_width, src_height, &src_pitch,
- &dst_y, dst_width, &dst_height)) {
- SetRect(dst_mip, dst_x, dst_y, dst_width, dst_height,
- src_img.GetPixelData(src_mip, src_x, src_y),
- src_pitch);
- return;
- }
-
- LockHelper helper(this, dst_mip, kReadWrite);
- uint8* mip_data = helper.GetDataAs<uint8>();
- if (!mip_data) {
- return;
- }
-
- image::LanczosScale(src_img.format(),
- src_img.GetMipData(src_mip),
- src_img.GetMipPitch(src_mip),
- src_x, src_y,
- src_width, src_height,
- mip_data, helper.pitch(),
- dst_x, dst_y,
- dst_width, dst_height,
- components);
-}
-
-void Texture2D::DrawImage(const Canvas& src_img,
- int src_x, int src_y,
- int src_width, int src_height,
- int dst_mip,
- int dst_x, int dst_y,
- int dst_width, int dst_height) {
- if (dst_mip < 0 || dst_mip >= levels()) {
- O3D_ERROR(service_locator()) << "Mip out of range";
- }
-
- // Clip source and destination rectangles to
- // source and destination bitmaps.
- // if src or dest rectangle is out of boundary,
- // do nothing and return.
- if (!image::AdjustDrawImageBoundary(&src_x, &src_y,
- &src_width, &src_height,
- 0,
- src_img.width(), src_img.height(),
- &dst_x, &dst_y,
- &dst_width, &dst_height,
- dst_mip,
- width(), height())) {
- return;
- }
-
- // check formats of source and dest images.
- // format of source and dest should be the same.
- if (format() != Texture::ARGB8 && format() != Texture::XRGB8) {
- O3D_ERROR(service_locator()) << "format must be ARGB8 or XRGB8.";
- return;
- }
-
- unsigned int mip_width = image::ComputeMipDimension(dst_mip, width());
- DCHECK(mip_width > 0);
-
- unsigned int mip_height = image::ComputeMipDimension(dst_mip, height());
- DCHECK(mip_height > 0);
-
- unsigned int components = image::GetNumComponentsForFormat(format());
- DCHECK(components > 0);
-
- int src_pitch = src_img.GetPitch();
- if (image::AdjustForSetRect(&src_y, src_width, src_height, &src_pitch,
- &dst_y, dst_width, &dst_height)) {
- SetRect(dst_mip, dst_x, dst_y, dst_width, dst_height,
- src_img.GetPixelData(src_x, src_y),
- src_pitch);
- return;
- }
-
- LockHelper helper(this, dst_mip, kReadWrite);
- uint8* mip_data = helper.GetDataAs<uint8>();
- if (!mip_data) {
- return;
- }
-
- image::LanczosScale(format(),
- src_img.GetPixelData(0, 0),
- src_img.GetPitch(),
- src_x, src_y,
- src_width, src_height,
- mip_data, helper.pitch(),
- dst_x, dst_y,
- dst_width, dst_height,
- components);
-}
-
-void Texture2D::SetFromBitmap(const Bitmap& bitmap) {
- DCHECK(bitmap.image_data());
- if (bitmap.width() != static_cast<unsigned>(width()) ||
- bitmap.height() != static_cast<unsigned>(height()) ||
- bitmap.format() != format()) {
- O3D_ERROR(service_locator())
- << "bitmap must be the same format and dimensions as texture";
- return;
- }
-
- int last_level = std::min<int>(bitmap.num_mipmaps(), levels());
- for (int level = 0; level < last_level; ++level) {
- SetRect(level, 0, 0,
- image::ComputeMipDimension(level, width()),
- image::ComputeMipDimension(level, height()),
- bitmap.GetMipData(level),
- bitmap.GetMipPitch(level));
- }
-}
-
-void Texture2D::GenerateMips(int source_level, int num_levels) {
- if (source_level < 0 || source_level >= levels()) {
- O3D_ERROR(service_locator()) << "source level out of range";
- return;
- }
- if (source_level + num_levels >= levels()) {
- O3D_ERROR(service_locator()) << "num levels out of range";
- return;
- }
-
- for (int ii = 0; ii < num_levels; ++ii) {
- int level = source_level + ii;
- Texture2D::LockHelper src_helper(this, level, kReadOnly);
- Texture2D::LockHelper dst_helper(this, level + 1, kWriteOnly);
- const uint8* src_data = src_helper.GetDataAs<const uint8>();
- if (!src_data) {
- O3D_ERROR(service_locator())
- << "could not lock source texture.";
- return;
- }
- uint8* dst_data = dst_helper.GetDataAs<uint8>();
- if (!dst_data) {
- O3D_ERROR(service_locator())
- << "could not lock destination texture.";
- return;
- }
-
- unsigned int src_width = image::ComputeMipDimension(level, width());
- unsigned int src_height = image::ComputeMipDimension(level, height());
- image::GenerateMipmap(src_width, src_height, format(),
- src_data, src_helper.pitch(),
- dst_data, dst_helper.pitch());
- }
-}
-
-bool Texture2D::Lock(
- int level, void** texture_data, int* pitch, AccessMode mode) {
- DCHECK(texture_data);
- DCHECK(pitch);
- if (level >= levels() || level < 0) {
- O3D_ERROR(service_locator())
- << "Trying to lock inexistent level " << level << " on Texture \""
- << name() << "\"";
- return false;
- }
- if (IsLocked(level)) {
- O3D_ERROR(service_locator())
- << "Level " << level << " of texture \"" << name()
- << "\" is already locked.";
- return false;
- }
- if (render_surfaces_enabled()) {
- O3D_ERROR(service_locator())
- << "Attempting to lock a render-target texture: " << name();
- return false;
- }
- bool success = PlatformSpecificLock(level, texture_data, pitch, mode);
- if (success) {
- locked_levels_[level] = mode;
- } else {
- O3D_ERROR(service_locator()) << "Failed to Lock Texture2D";
- }
- return success;
-}
-
-// Unlocks the given mipmap level of this texture.
-bool Texture2D::Unlock(int level) {
- if (level >= levels() || level < 0) {
- O3D_ERROR(service_locator())
- << "Trying to unlock inexistent level " << level << " on Texture \""
- << name() << "\"";
- return false;
- }
- if (!IsLocked(level)) {
- O3D_ERROR(service_locator())
- << "Level " << level << " of texture \"" << name()
- << "\" is not locked.";
- return false;
- }
- bool result = PlatformSpecificUnlock(level);
- if (result) {
- locked_levels_[level] = kNone;
- } else {
- O3D_ERROR(service_locator()) << "Failed to Unlock Texture2D";
- }
- return result;
-}
-
-ObjectBase::Ref Texture2D::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref();
-}
-
-RenderSurface::Ref Texture2D::GetRenderSurface(int mip_level) {
- if (mip_level < 0 || mip_level >= levels()) {
- O3D_ERROR(service_locator()) << "mip level out of range";
- return RenderSurface::Ref(NULL);
- }
- if (surface_map_[mip_level].IsNull()) {
- surface_map_[mip_level] = RenderSurface::Ref(
- PlatformSpecificGetRenderSurface(mip_level));
- }
- return surface_map_[mip_level];
-}
-
-Texture2D::LockHelper::LockHelper(
- Texture2D* texture, int level, Texture::AccessMode mode)
- : mode_(mode),
- texture_(texture),
- level_(level),
- data_(NULL),
- locked_(false) {
-}
-
-Texture2D::LockHelper::~LockHelper() {
- if (locked_) {
- texture_->Unlock(level_);
- }
-}
-
-void* Texture2D::LockHelper::GetData() {
- if (!locked_) {
- locked_ = texture_->Lock(level_, &data_, &pitch_, mode_);
- if (!locked_) {
- O3D_ERROR(texture_->service_locator())
- << "Unable to lock buffer '" << texture_->name() << "'";
- }
- }
- return data_;
-}
-
-TextureCUBE::TextureCUBE(ServiceLocator* service_locator,
- int edge_length,
- Format format,
- int levels,
- bool enable_render_surfaces)
- : Texture(service_locator, format, levels, enable_render_surfaces) {
- for (int f = 0; f < static_cast<int>(NUMBER_OF_FACES); ++f) {
- for (int ii = 0; ii < kMaxLevels; ++ii) {
- locked_levels_[f][ii] = kNone;
- }
- surface_maps_[f].resize(levels);
- }
- RegisterReadOnlyParamRef(kEdgeLengthParamName, &edge_length_param_);
- edge_length_param_->set_read_only_value(edge_length);
-
- ClientInfoManager* client_info_manager =
- service_locator->GetService<ClientInfoManager>();
- client_info_manager->AdjustTextureMemoryUsed(
- static_cast<int>(image::ComputeMipChainSize(
- edge_length,
- edge_length,
- format,
- levels)) * static_cast<int>(NUMBER_OF_FACES));
-}
-
-TextureCUBE::~TextureCUBE() {
- bool reported = false;
- for (int f = 0; f < static_cast<int>(NUMBER_OF_FACES); ++f) {
- for (int i = 0; i < levels(); ++i) {
- if (IsLocked(static_cast<CubeFace>(f), i)) {
- if (!reported) {
- // No need to report it more than once.
- reported = true;
- O3D_ERROR(service_locator())
- << "TextureCUBE \"" << name() << "\" was never unlocked before"
- << "being destroyed.";
- }
- Unlock(static_cast<CubeFace>(f), i);
- }
- }
- }
-
- ClientInfoManager* client_info_manager =
- service_locator()->GetService<ClientInfoManager>();
- client_info_manager->AdjustTextureMemoryUsed(
- -static_cast<int>(image::ComputeMipChainSize(edge_length(),
- edge_length(),
- format(),
- levels()) * 6));
-}
-
-ObjectBase::Ref TextureCUBE::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref();
-}
-
-RenderSurface::Ref TextureCUBE::GetRenderSurface(CubeFace face, int mip_level) {
- if (mip_level < 0 || mip_level >= levels()) {
- O3D_ERROR(service_locator()) << "mip level out of range";
- return RenderSurface::Ref(NULL);
- }
- if (surface_maps_[face][mip_level].IsNull()) {
- surface_maps_[face][mip_level] = RenderSurface::Ref(
- PlatformSpecificGetRenderSurface(face, mip_level));
- }
- return surface_maps_[face][mip_level];
-}
-
-void TextureCUBE::DrawImage(const Bitmap& src_img, int src_mip,
- int src_x, int src_y,
- int src_width, int src_height,
- CubeFace dest_face, int dest_mip,
- int dst_x, int dst_y,
- int dst_width, int dst_height) {
- DCHECK(src_img.image_data());
-
- if (dest_face >= NUMBER_OF_FACES) {
- O3D_ERROR(service_locator()) << "Invalid face specification";
- return;
- }
-
- if (dest_mip < 0 || dest_mip >= levels()) {
- O3D_ERROR(service_locator()) << "Destination Mip out of range";
- }
-
- if (src_mip < 0 || src_mip >= static_cast<int>(src_img.num_mipmaps())) {
- O3D_ERROR(service_locator()) << "Source Mip out of range";
- }
-
- // Clip source and destination rectangles to
- // source and destination bitmaps.
- // if src or dest rectangle is out of boundary,
- // do nothing and return true.
- if (!image::AdjustDrawImageBoundary(&src_x, &src_y,
- &src_width, &src_height,
- src_mip,
- src_img.width(), src_img.height(),
- &dst_x, &dst_y,
- &dst_width, &dst_height,
- dest_mip,
- edge_length(), edge_length())) {
- return;
- }
-
- // check formats of source and dest images.
- // format of source and dest should be the same.
- if (src_img.format() != format()) {
- O3D_ERROR(service_locator()) << "DrawImage does not support "
- << "different formats.";
- return;
- }
-
- unsigned int mip_length = image::ComputeMipDimension(dest_mip, edge_length());
-
- // if src and dest are in the same size and drawImage is copying
- // the entire bitmap on dest image, just perform memcpy.
- if (src_x == 0 && src_y == 0 && dst_x == 0 && dst_y == 0 &&
- src_img.width() == mip_length && src_img.height() == mip_length &&
- static_cast<unsigned int>(src_width) == src_img.width() &&
- static_cast<unsigned int>(src_height) == src_img.height() &&
- static_cast<unsigned int>(dst_width) == mip_length &&
- static_cast<unsigned int>(dst_height) == mip_length) {
- SetRect(dest_face, dest_mip, 0, 0, mip_length, mip_length,
- src_img.image_data(),
- src_img.GetMipPitch(src_mip));
- return;
- }
-
- unsigned int components = image::GetNumComponentsForFormat(format());
- if (components == 0) {
- O3D_ERROR(service_locator()) << "DrawImage does not support format: "
- << src_img.format() << " unless src and "
- << "dest images are in the same size and "
- << "copying the entire bitmap";
- return;
- }
-
- int src_pitch = src_img.GetMipPitch(src_mip);
- if (image::AdjustForSetRect(&src_y, src_width, src_height, &src_pitch,
- &dst_y, dst_width, &dst_height)) {
- SetRect(dest_face, dest_mip, dst_x, dst_y, dst_width, dst_height,
- src_img.GetPixelData(src_mip, src_x, src_y),
- src_pitch);
- }
-
- LockHelper helper(this, dest_face, dest_mip, kReadWrite);
- uint8* mip_data = helper.GetDataAs<uint8>();
- if (!mip_data) {
- return;
- }
-
- image::LanczosScale(src_img.format(), src_img.GetMipData(src_mip),
- src_img.GetMipPitch(src_mip),
- src_x, src_y,
- src_width, src_height,
- mip_data, helper.pitch(),
- dst_x, dst_y,
- dst_width, dst_height,
- components);
-}
-
-void TextureCUBE::DrawImage(const Canvas& src_img,
- int src_x, int src_y,
- int src_width, int src_height,
- CubeFace dest_face, int dest_mip,
- int dst_x, int dst_y,
- int dst_width, int dst_height) {
- if (dest_face >= NUMBER_OF_FACES) {
- O3D_ERROR(service_locator()) << "Invalid face specification";
- return;
- }
-
- if (dest_mip < 0 || dest_mip >= levels()) {
- O3D_ERROR(service_locator()) << "Destination Mip out of range";
- }
-
- // Clip source and destination rectangles to
- // source and destination bitmaps.
- // if src or dest rectangle is out of boundary,
- // do nothing and return true.
- if (!image::AdjustDrawImageBoundary(&src_x, &src_y,
- &src_width, &src_height,
- 0,
- src_img.width(), src_img.height(),
- &dst_x, &dst_y,
- &dst_width, &dst_height,
- dest_mip,
- edge_length(), edge_length())) {
- return;
- }
-
- // check formats of source and dest images.
- // format of source and dest should be the same.
- if (format() != Texture::ARGB8 && format() != Texture::XRGB8) {
- O3D_ERROR(service_locator()) << "format must be ARGB8 or XRGB8.";
- return;
- }
-
- unsigned int mip_length = image::ComputeMipDimension(dest_mip, edge_length());
- DCHECK(mip_length > 0u);
-
- unsigned int components = image::GetNumComponentsForFormat(format());
- DCHECK(components > 0);
-
- int src_pitch = src_img.GetPitch();
- if (image::AdjustForSetRect(&src_y, src_width, src_height, &src_pitch,
- &dst_y, dst_width, &dst_height)) {
- SetRect(dest_face, dest_mip, dst_x, dst_y, dst_width, dst_height,
- src_img.GetPixelData(src_x, src_y),
- src_pitch);
- return;
- }
-
- LockHelper helper(this, dest_face, dest_mip, kReadWrite);
- uint8* mip_data = helper.GetDataAs<uint8>();
- if (!mip_data) {
- return;
- }
-
- image::LanczosScale(format(),
- src_img.GetPixelData(0, 0),
- src_img.GetPitch(),
- src_x, src_y,
- src_width, src_height,
- mip_data, helper.pitch(),
- dst_x, dst_y,
- dst_width, dst_height,
- components);
-}
-
-void TextureCUBE::SetFromBitmap(CubeFace face, const Bitmap& bitmap) {
- DCHECK(bitmap.image_data());
- if (bitmap.width() != static_cast<unsigned>(edge_length()) ||
- bitmap.height() != static_cast<unsigned>(edge_length()) ||
- bitmap.format() != format()) {
- O3D_ERROR(service_locator())
- << "bitmap must be the same format and dimensions as texture";
- return;
- }
-
- int last_level = std::min<int>(bitmap.num_mipmaps(), levels());
- for (int level = 0; level < last_level; ++level) {
- SetRect(face, level, 0, 0,
- image::ComputeMipDimension(level, edge_length()),
- image::ComputeMipDimension(level, edge_length()),
- bitmap.GetMipData(level),
- bitmap.GetMipPitch(level));
- }
-}
-
-void TextureCUBE::GenerateMips(int source_level, int num_levels) {
- if (source_level < 0 || source_level >= levels()) {
- O3D_ERROR(service_locator()) << "source level out of range";
- return;
- }
- if (source_level + num_levels >= levels()) {
- O3D_ERROR(service_locator()) << "num levels out of range";
- return;
- }
-
- for (int face = FACE_POSITIVE_X; face < NUMBER_OF_FACES; ++face) {
- for (int ii = 0; ii < num_levels; ++ii) {
- int level = source_level + ii;
- TextureCUBE::LockHelper src_helper(
- this, static_cast<TextureCUBE::CubeFace>(face), level, kReadOnly);
- TextureCUBE::LockHelper dst_helper(
- this, static_cast<TextureCUBE::CubeFace>(face), level + 1,
- kWriteOnly);
- const uint8* src_data = src_helper.GetDataAs<const uint8>();
- if (!src_data) {
- O3D_ERROR(service_locator())
- << "could not lock source texture.";
- return;
- }
- uint8* dst_data = dst_helper.GetDataAs<uint8>();
- if (!dst_data) {
- O3D_ERROR(service_locator())
- << "could not lock destination texture.";
- return;
- }
-
- unsigned int src_edge_length =
- std::max<unsigned int>(1U, edge_length() >> level);
-
- image::GenerateMipmap(
- src_edge_length, src_edge_length, format(),
- src_data, src_helper.pitch(),
- dst_data, dst_helper.pitch());
- }
- }
-}
-
-// Locks the given face and mipmap level of this texture for loading from
-// main memory, and returns a pointer to the buffer.
-bool TextureCUBE::Lock(
- CubeFace face, int level, void** texture_data, int* pitch,
- AccessMode mode) {
- DCHECK(texture_data);
- DCHECK(pitch);
- if (level >= levels() || level < 0) {
- O3D_ERROR(service_locator())
- << "Trying to lock inexistent level " << level << " on Texture \""
- << name();
- return false;
- }
- if (IsLocked(face, level)) {
- O3D_ERROR(service_locator())
- << "Level " << level << " Face " << face << " of texture \"" << name()
- << "\" is already locked.";
- return false;
- }
- if (render_surfaces_enabled()) {
- O3D_ERROR(service_locator())
- << "Attempting to lock a render-target texture: " << name();
- return false;
- }
-
- bool success = PlatformSpecificLock(face, level, texture_data, pitch, mode);
- if (success) {
- locked_levels_[face][level] = mode;
- } else {
- O3D_ERROR(service_locator()) << "Failed to Lock TextureCUBE";
- }
- return success;
-}
-
-// Unlocks the given face and mipmap level of this texture.
-bool TextureCUBE::Unlock(CubeFace face, int level) {
- if (level >= levels() || level < 0) {
- O3D_ERROR(service_locator())
- << "Trying to unlock inexistent level " << level << " on Texture \""
- << name();
- return false;
- }
- if (!IsLocked(face, level)) {
- O3D_ERROR(service_locator())
- << "Level " << level << " of texture \"" << name()
- << "\" is not locked.";
- return false;
- }
- bool result = PlatformSpecificUnlock(face, level);
- if (result) {
- locked_levels_[face][level] = kNone;
- } else {
- O3D_ERROR(service_locator()) << "Failed to Unlock TextureCUBE";
- }
- return result;
-}
-
-TextureCUBE::LockHelper::LockHelper(
- TextureCUBE* texture,
- CubeFace face,
- int level,
- Texture::AccessMode mode)
- : mode_(mode),
- texture_(texture),
- face_(face),
- level_(level),
- data_(NULL),
- locked_(false) {
-}
-
-TextureCUBE::LockHelper::~LockHelper() {
- if (locked_) {
- texture_->Unlock(face_, level_);
- }
-}
-
-void* TextureCUBE::LockHelper::GetData() {
- if (!locked_) {
- locked_ = texture_->Lock(face_, level_, &data_, &pitch_, mode_);
- if (!locked_) {
- O3D_ERROR(texture_->service_locator())
- << "Unable to lock buffer '" << texture_->name() << "'";
- }
- }
- return data_;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/texture.h b/o3d/core/cross/texture.h
deleted file mode 100644
index f25a162..0000000
--- a/o3d/core/cross/texture.h
+++ /dev/null
@@ -1,459 +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_CORE_CROSS_TEXTURE_H_
-#define O3D_CORE_CROSS_TEXTURE_H_
-
-#include <vector>
-
-#include "core/cross/render_surface.h"
-#include "core/cross/texture_base.h"
-
-namespace o3d {
-
-class Pack;
-class Bitmap;
-class Canvas;
-
-// An abstract class for 2D textures that defines the interface for getting
-// the dimensions of the texture and number of mipmap levels.
-// Concrete implementations should implement the Lock and Unlock methods.
-class Texture2D : public Texture {
- public:
- typedef SmartPointer<Texture2D> Ref;
-
- // Class to help lock Texture2D. Automatically unlocks texture in destructor.
- class LockHelper {
- public:
- explicit LockHelper(Texture2D* texture, int level, AccessMode mode);
- ~LockHelper();
-
- int pitch() const {
- return pitch_;
- }
-
- // Gets a pointer to the data of the buffer, locking the buffer if
- // necessary.
- // Returns:
- // Pointer to data in buffer or NULL if there was an error.
- void* GetData();
-
- // Typed version of GetData
- template <typename T>
- T* GetDataAs() {
- return reinterpret_cast<T*>(GetData());
- }
-
- private:
- AccessMode mode_;
- Texture2D* texture_;
- int level_;
- int pitch_;
- void* data_;
- bool locked_;
-
- DISALLOW_COPY_AND_ASSIGN(LockHelper);
- };
-
-
- Texture2D(ServiceLocator* service_locator,
- int width,
- int height,
- Format format,
- int levels,
- bool enable_render_surfaces);
- virtual ~Texture2D();
-
- static const char* kWidthParamName;
- static const char* kHeightParamName;
-
- inline int width() const {
- return width_param_->value();
- }
-
- inline int height() const {
- return height_param_->value();
- }
-
- // level: The mipmap level to modify
- // dst_left: The left edge of the rectangular area to modify.
- // dst_top: The top edge of the rectangular area to modify.
- // width: The width of the rectangular area to modify.
- // height: The of the rectangular area to modify.
- // src_data: The source pixels.
- // src_pitch: If the format is uncompressed this is the number of bytes
- // per row of pixels. If compressed this value is unused.
- virtual void SetRect(int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned width,
- unsigned height,
- const void* src_data,
- int src_pitch) = 0;
-
- // Returns a RenderSurface object associated with a mip_level of a texture.
- // Parameters:
- // mip_level: [in] The mip-level of the surface to be returned.
- // Returns:
- // Reference to the RenderSurface object.
- RenderSurface::Ref GetRenderSurface(int mip_level);
-
- // Copy pixels from source bitmap to certain mip level.
- // Scales if the width and height of source and dest do not match.
- // Parameters:
- // source_img: source bitmap which would be drawn.
- // source_mip: source mip to draw.
- // source_x: x-coordinate of the starting pixel in the source image.
- // source_y: y-coordinate of the starting pixel in the source image.
- // source_width: width of the source image to draw.
- // source_height: Height of the source image to draw.
- // dest_mip: on which mip level the sourceImg would be drawn.
- // dest_x: x-coordinate of the starting pixel in the dest image.
- // dest_y: y-coordinate of the starting pixel in the dest image.
- // dest_width: width of the dest image.
- // dest_height: height of the dest image.
- void DrawImage(const Bitmap& source_img, int src_mip,
- int source_x, int source_y,
- int source_width, int source_height,
- int dest_mip,
- int dest_x, int dest_y,
- int dest_width, int dest_height);
-
- // Copy pixels from source bitmap to certain mip level.
- // Scales if the width and height of source and dest do not match.
- // Parameters:
- // source_img: source canvas to draw.
- // source_x: x-coordinate of the starting pixel in the source image.
- // source_y: y-coordinate of the starting pixel in the source image.
- // source_width: width of the source image to draw.
- // source_height: Height of the source image to draw.
- // dest_mip: the dest mip to draw to.
- // dest_x: x-coordinate of the starting pixel in the dest image.
- // dest_y: y-coordinate of the starting pixel in the dest image.
- // dest_width: width of the dest image.
- // dest_height: height of the dest image.
- void DrawImage(const Canvas& source_img,
- int source_x, int source_y,
- int source_width, int source_height,
- int dest_mip,
- int dest_x, int dest_y,
- int dest_width, int dest_height);
-
-
- // Sets the contents of the texture from a Bitmap.
- void SetFromBitmap(const Bitmap& bitmap);
-
- // Overridden from Texture.
- virtual void GenerateMips(int source_level, int num_levels);
-
- protected:
- // Returns a pointer to the internal texture data for the given mipmap level.
- // Lock must be called before the texture data can be modified.
- // Parameters:
- // level: [in] the mipmap level to be modified
- // texture_data: [out] a pointer to the current texture data
- // pitch: bytes across 1 row of pixels if uncompressed format. bytes across 1
- // row of blocks if compressed format.
- // mode: The access mode.
- // Returns:
- // true if the operation succeeds
- bool Lock(int level, void** texture_data, int* pitch, AccessMode mode);
-
- // Notifies the texture object that the internal texture data has been
- // been modified. Unlock must be called in conjunction with Lock. Modifying
- // the contents of the texture after Unlock has been called could lead to
- // unpredictable behavior.
- // Parameters:
- // level: [in] the mipmap level that was modified
- // Returns:
- // true if the operation succeeds
- bool Unlock(int level);
-
- // The platform specific part of Lock.
- virtual bool PlatformSpecificLock(int level, void** texture_data, int* pitch,
- AccessMode mode) = 0;
-
- // The platform specific part of Unlock.
- virtual bool PlatformSpecificUnlock(int level) = 0;
-
- // The platform specific part of GetRenderSurface.
- virtual RenderSurface::Ref PlatformSpecificGetRenderSurface(
- int mip_level) = 0;
-
- // Returns the current locked mode.
- AccessMode LockedMode(unsigned int level) {
- DCHECK_LT(static_cast<int>(level), levels());
- return locked_levels_[level];
- }
-
- // Returns true if the mip-map level has been locked.
- bool IsLocked(unsigned int level) {
- return LockedMode(level) != kNone;
- }
-
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- typedef std::vector<RenderSurface::Ref> MipToRenderSurfaceMap;
-
- MipToRenderSurfaceMap surface_map_;
-
- // The width of the texture, in texels.
- ParamInteger::Ref width_param_;
- // The height of the texture, in texels.
- ParamInteger::Ref height_param_;
-
- // Access mode for each level.
- AccessMode locked_levels_[kMaxLevels];
-
- O3D_DECL_CLASS(Texture2D, Texture);
- DISALLOW_COPY_AND_ASSIGN(Texture2D);
-};
-
-class TextureCUBE : public Texture {
- public:
- typedef SmartPointer<TextureCUBE> Ref;
- // Cross-platform enumeration of faces of the cube texture.
- enum CubeFace {
- FACE_POSITIVE_X,
- FACE_NEGATIVE_X,
- FACE_POSITIVE_Y,
- FACE_NEGATIVE_Y,
- FACE_POSITIVE_Z,
- FACE_NEGATIVE_Z,
- NUMBER_OF_FACES,
- };
-
- // Class to help lock TextureCUBE.
- // Automatically unlocks texture in destructor.
- class LockHelper {
- public:
- explicit LockHelper(TextureCUBE* texture, CubeFace face, int level,
- AccessMode mode);
- ~LockHelper();
-
- int pitch() const {
- return pitch_;
- }
-
- // Gets a pointer to the data of the buffer, locking the buffer if
- // necessary.
- // Returns:
- // Pointer to data in buffer or NULL if there was an error.
- void* GetData();
-
- // Typed version of GetData
- template <typename T>
- T* GetDataAs() {
- return reinterpret_cast<T*>(GetData());
- }
-
- private:
- AccessMode mode_;
- TextureCUBE* texture_;
- CubeFace face_;
- int level_;
- int pitch_;
- void* data_;
- bool locked_;
-
- DISALLOW_COPY_AND_ASSIGN(LockHelper);
- };
-
- static const char* kEdgeLengthParamName;
-
- TextureCUBE(ServiceLocator* service_locator,
- int edge_length,
- Format format,
- int levels,
- bool enable_render_surfaces);
-
- virtual ~TextureCUBE();
- inline int edge_length() const {
- return edge_length_param_->value();
- }
-
- // Sets a rectangular region of this texture.
- // If the texture is a DXT format, the only acceptable values
- // for left, top, width and height are 0, 0, texture->width, texture->height
- //
- // Parameters:
- // face: The face of the cube to modify.
- // level: The mipmap level to modify
- // dst_left: The left edge of the rectangular area to modify.
- // dst_top: The top edge of the rectangular area to modify.
- // width: The width of the rectangular area to modify.
- // height: The of the rectangular area to modify.
- // src_data: buffer to get pixels from.
- // src_pitch: If the format is uncompressed this is the number of bytes
- // per row of pixels. If compressed this value is unused.
- virtual void SetRect(CubeFace face,
- int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned width,
- unsigned height,
- const void* src_data,
- int src_pitch) = 0;
-
- // Returns a RenderSurface object associated with a given cube face and
- // mip_level of a texture.
- // Parameters:
- // face: [in] The cube face from which to extract the surface.
- // mip_level: [in] The mip-level of the surface to be returned.
- // Returns:
- // Reference to the RenderSurface object.
- RenderSurface::Ref GetRenderSurface(CubeFace face, int level);
-
- // Copy pixels from source bitmap to certain mip level.
- // Scales if the width and height of source and dest do not match.
- // Parameters:
- // source_img: source bitmap.
- // source_mip: source mip to draw.
- // source_x: x-coordinate of the starting pixel in the source image.
- // source_y: y-coordinate of the starting pixel in the source image.
- // source_width: width of the source image to draw.
- // source_height: Height of the source image to draw.
- // face: face to draw to.
- // dest_mip: mip to draw to.
- // dest_x: x-coordinate of the starting pixel in the dest image.
- // dest_y: y-coordinate of the starting pixel in the dest image.
- // dest_width: width of the dest image.
- // dest_height: height of the dest image.
- void DrawImage(const Bitmap& source_img, int source_mip,
- int source_x, int source_y,
- int source_width, int source_height,
- CubeFace face, int dest_mip,
- int dest_x, int dest_y, int dest_width,
- int dest_height);
-
- // Copy pixels from source canvas to certain mip level.
- // Scales if the width and height of source and dest do not match.
- // Parameters:
- // source_img: source canvas.
- // source_x: x-coordinate of the starting pixel in the source image.
- // source_y: y-coordinate of the starting pixel in the source image.
- // source_width: width of the source image to draw.
- // source_height: Height of the source image to draw.
- // face: face to draw to.
- // dest_mip: mip to draw to.
- // dest_x: x-coordinate of the starting pixel in the dest image.
- // dest_y: y-coordinate of the starting pixel in the dest image.
- // dest_width: width of the dest image.
- // dest_height: height of the dest image.
- void DrawImage(const Canvas& source_img,
- int source_x, int source_y,
- int source_width, int source_height,
- CubeFace face, int dest_mip,
- int dest_x, int dest_y, int dest_width,
- int dest_height);
-
- // Sets the contents of the texture from a Bitmap.
- void SetFromBitmap(CubeFace face, const Bitmap& bitmap);
-
- // Overridden from Texture.
- virtual void GenerateMips(int source_level, int num_levels);
-
- protected:
- // Returns a pointer to the internal texture data for the given face and
- // mipmap level.
- // Lock must be called before the texture data can be modified.
- // Parameters:
- // face: [in] the index of the cube face to be modified
- // level: [in] the mipmap level to be modified
- // texture_data: [out] a pointer to the current texture data
- // pitch: bytes across 1 row of pixels if uncompressed format. bytes across 1
- // row of blocks if compressed format.
- // mode: The access mode.
- // Returns:
- // true if the operation succeeds
- bool Lock(
- CubeFace face, int level, void** texture_data, int* pitch,
- AccessMode mode);
-
- // Notifies the texture object that the internal texture data has been
- // been modified. Unlock must be called in conjunction with Lock.
- // Modifying the contents of the texture after Unlock has been called could
- // lead to unpredictable behavior.
- // Parameters:
- // face: [in] the index of the cube face that was modified
- // level: [in] the mipmap level that was modified
- // Returns:
- // true if the operation succeeds
- bool Unlock(CubeFace face, int level);
-
- // The platform specific part of Lock.
- virtual bool PlatformSpecificLock(
- CubeFace face, int level, void** texture_data, int* pitch,
- AccessMode mode) = 0;
-
- // The platform specific part of Unlock.
- virtual bool PlatformSpecificUnlock(CubeFace face, int level) = 0;
-
- // The platform specific part of GetRenderSurface.
- virtual RenderSurface::Ref PlatformSpecificGetRenderSurface(
- CubeFace face, int level) = 0;
-
- // Returns the locked mode for a level
- AccessMode LockedMode(CubeFace face, unsigned int level) {
- DCHECK_LT(static_cast<int>(level), levels());
- return locked_levels_[face][level];
- }
-
- // Returns true if the mip-map level has been locked.
- bool IsLocked(CubeFace face, unsigned int level) {
- return LockedMode(face, level) != kNone;
- }
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- typedef std::vector<RenderSurface::Ref> MipToRenderSurfaceMap;
-
- MipToRenderSurfaceMap surface_maps_[NUMBER_OF_FACES];
-
- // The length of each edge of the cube, in texels.
- ParamInteger::Ref edge_length_param_;
-
- // AccessMode for each level on each face.
- AccessMode locked_levels_[NUMBER_OF_FACES][kMaxLevels];
-
- O3D_DECL_CLASS(TextureCUBE, Texture);
- DISALLOW_COPY_AND_ASSIGN(TextureCUBE);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_TEXTURE_H_
diff --git a/o3d/core/cross/texture_base.cc b/o3d/core/cross/texture_base.cc
deleted file mode 100644
index 3c633a8..0000000
--- a/o3d/core/cross/texture_base.cc
+++ /dev/null
@@ -1,88 +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 definition of the Texture class.
-
-#include "core/cross/texture_base.h"
-
-#include "core/cross/bitmap.h"
-#include "core/cross/pack.h"
-#include "core/cross/renderer.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Texture, ParamObject);
-O3D_DEFN_CLASS(ParamTexture, RefParamBase);
-
-const char* Texture::kLevelsParamName =
- O3D_STRING_CONSTANT("levels");
-
-Texture::Texture(ServiceLocator* service_locator,
- Format format,
- int levels,
- bool enable_render_surfaces)
- : ParamObject(service_locator),
- renderer_(service_locator->GetService<Renderer>()),
- alpha_is_one_(false),
- format_(format),
- weak_pointer_manager_(this),
- render_surfaces_enabled_(enable_render_surfaces),
- has_unrendered_update_(false),
- last_render_frame_count_(0),
- update_count_(0),
- render_count_(0) {
- RegisterReadOnlyParamRef(kLevelsParamName, &levels_param_);
- levels_param_->set_read_only_value(levels);
-}
-
-void Texture::TextureUpdated() {
- CheckLastTextureUpdateRendered();
- last_render_frame_count_ = renderer_->render_frame_count();
- update_count_++;
- has_unrendered_update_ = true;
-}
-
-void Texture::CheckLastTextureUpdateRendered() {
- if (has_unrendered_update_ &&
- renderer_->render_frame_count() != last_render_frame_count_) {
- // Then a new frame has been rendered to the screen since we last
- // updated this texture, so that update has been rendered to the screen.
- render_count_++;
- has_unrendered_update_ = false;
- }
-}
-
-ObjectBase::Ref ParamTexture::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamTexture(service_locator, false, false));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/texture_base.h b/o3d/core/cross/texture_base.h
deleted file mode 100644
index 8adf8e1..0000000
--- a/o3d/core/cross/texture_base.h
+++ /dev/null
@@ -1,203 +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.
- */
-
-
-// File containing a base class for texture objects.
-
-#ifndef O3D_CORE_CROSS_TEXTURE_BASE_H_
-#define O3D_CORE_CROSS_TEXTURE_BASE_H_
-
-#include "core/cross/param.h"
-#include "core/cross/param_object.h"
-
-namespace o3d {
-
-class Bitmap;
-class Pack;
-class Renderer;
-class RenderSurface;
-
-// The Texture class is a base class for image data used in texture
-// mapping. It is an abstract class. Concrete implementations should
-// implement the GetTextureHandle() member function.
-class Texture : public ParamObject {
- public:
- typedef SmartPointer<Texture> Ref;
- typedef WeakPointer<Texture> WeakPointerType;
-
- enum Format {
- UNKNOWN_FORMAT,
- XRGB8, // actual format in memory is B G R X
- ARGB8, // actual format in memory is B G R A
- ABGR16F,
- R32F,
- ABGR32F,
- DXT1,
- DXT3,
- DXT5
- };
-
- // Defines how you want to access a texture when locking.
- enum AccessMode {
- kNone = 0,
- kReadOnly = 1,
- kWriteOnly = 2,
- kReadWrite = 3,
- };
-
- typedef unsigned RGBASwizzleIndices[4];
-
- // This is the maximum texture size we allow and hence the largest
- // render target and depth stencil as well. This is because it's the limit of
- // some low-end machines that are still pretty common.
- //
- // NOTE: class Bitmap supports a larger size. The plan is to expose Bitmap
- // to Javascript so you can download larger images, scale them, then put
- // them in a texture.
- static const int kMaxDimension = 2048;
- static const int kMaxLevels = 12;
-
- Texture(ServiceLocator* service_locator,
- Format format,
- int levels,
- bool enable_render_surfaces);
- virtual ~Texture() {}
-
- static const char* kLevelsParamName;
-
- // Returns the implementation-specific texture handle.
- virtual void* GetTextureHandle() const = 0;
-
- static bool IsCompressedFormat(Format format) {
- return format == DXT1 || format == DXT3 || format == DXT5;
- }
-
- bool IsCompressed() const {
- return IsCompressedFormat(format_);
- }
-
- bool alpha_is_one() const { return alpha_is_one_; }
- void set_alpha_is_one(bool value) { alpha_is_one_ = value; }
-
- // Gets the levels.
- int levels() const {
- return levels_param_->value();
- }
-
- // Gets the format of the texture resource.
- Format format() const {
- return format_;
- }
-
- int update_count() {
- return update_count_;
- }
-
- int render_count() {
- CheckLastTextureUpdateRendered();
- return render_count_;
- }
-
- bool render_surfaces_enabled() const {
- return render_surfaces_enabled_;
- }
-
- // Generates mips.
- virtual void GenerateMips(int source_level, int num_levels) = 0;
-
- // Gets a RGBASwizzleIndices that contains a mapping from
- // RGBA to the internal format used by the graphics API.
- virtual const RGBASwizzleIndices& GetABGR32FSwizzleIndices() = 0;
-
- // Gets a weak pointer to us.
- WeakPointerType GetWeakPointer() const {
- return weak_pointer_manager_.GetWeakPointer();
- }
-
- protected:
- void set_levels(int levels) {
- levels_param_->set_read_only_value(levels);
- }
-
- void set_format(Format format) {
- format_ = format;
- }
-
- void TextureUpdated();
-
- Renderer* renderer_;
-
- private:
- void CheckLastTextureUpdateRendered();
-
- // The number of mipmap levels contained in this texture.
- ParamInteger::Ref levels_param_;
-
- // true if all the alpha values in this texture are 1.0.
- bool alpha_is_one_;
-
- // The data format of each pixel.
- Format format_;
-
- // Manager for weak pointers to us.
- WeakPointerType::WeakPointerManager weak_pointer_manager_;
-
- bool render_surfaces_enabled_;
-
- // Counting of frames, to allow the page to determine the framerate of dynamic
- // textures.
- bool has_unrendered_update_;
- int last_render_frame_count_;
- int update_count_;
- int render_count_;
-
- O3D_DECL_CLASS(Texture, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(Texture);
-};
-
-class ParamTexture : public TypedRefParam<Texture> {
- public:
- typedef SmartPointer<ParamTexture> Ref;
-
- ParamTexture(ServiceLocator* service_locator, bool dynamic, bool read_only)
- : TypedRefParam<Texture>(service_locator, dynamic, read_only) {}
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamTexture, RefParamBase);
- DISALLOW_COPY_AND_ASSIGN(ParamTexture);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_TEXTURE_BASE_H_
diff --git a/o3d/core/cross/texture_base_test.cc b/o3d/core/cross/texture_base_test.cc
deleted file mode 100644
index c52bfbc..0000000
--- a/o3d/core/cross/texture_base_test.cc
+++ /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 implements unit tests for class Texture.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/texture_base.h"
-#include "core/cross/object_manager.h"
-
-namespace o3d {
-
-namespace {
-
-Texture::RGBASwizzleIndices swizzle;
-
-class MockTexture : public Texture {
- public:
- typedef SmartPointer<MockTexture> Ref;
-
- MockTexture(ServiceLocator* service_locator,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces)
- : Texture(service_locator, format, levels, enable_render_surfaces) {
- }
-
- virtual const RGBASwizzleIndices& GetABGR32FSwizzleIndices() {
- return swizzle;
- }
-
- virtual void* GetTextureHandle() const {
- return NULL;
- }
-
- virtual void SetFromBitmap(const Bitmap& bitmap) {
- }
-
- virtual void GenerateMips(int source_level, int num_levels) {
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(MockTexture);
-};
-
-} // anonymous namespace
-
-class TextureTest : public testing::Test {
- protected:
-
- TextureTest()
- : object_manager_(g_service_locator) {
- }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
-};
-
-TEST_F(TextureTest, Basic) {
- MockTexture::Ref texture(new MockTexture(
- g_service_locator,
- Texture::XRGB8,
- 1,
- false));
- ASSERT_TRUE(texture != NULL);
- EXPECT_EQ(texture->format(), Texture::XRGB8);
- EXPECT_EQ(texture->levels(), 1);
- EXPECT_FALSE(texture->alpha_is_one());
- EXPECT_FALSE(texture->render_surfaces_enabled());
-}
-
-} // namespace o3d
-
diff --git a/o3d/core/cross/texture_test.cc b/o3d/core/cross/texture_test.cc
deleted file mode 100644
index d8de84f..0000000
--- a/o3d/core/cross/texture_test.cc
+++ /dev/null
@@ -1,201 +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 implements unit tests for class Texture.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/texture.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-
-namespace o3d {
-
-namespace {
-
-bool CompareTexture(Texture2D* texture, int level, const uint8* expected) {
- Texture2D::LockHelper helper(texture, level, Texture::kReadOnly);
- const uint8* data = helper.GetDataAs<const uint8>();
- unsigned mip_width = image::ComputeMipDimension(level, texture->width());
- unsigned mip_height = image::ComputeMipDimension(level, texture->height());
-
- int bytes_per_row = image::ComputePitch(texture->format(), mip_width);
- for (unsigned yy = 0; yy < mip_height; ++yy) {
- if (memcmp(data, expected, bytes_per_row) != 0) {
- return false;
- }
- expected += bytes_per_row;
- data += helper.pitch();
- }
- return true;
-}
-
-} // anonymous namespace.
-
-class Texture2DTest : public testing::Test {
- protected:
- Texture2DTest()
- : object_manager_(g_service_locator) {
- }
-
- virtual void SetUp() {
- pack_ = object_manager_->CreatePack();
- }
-
- virtual void TearDown() {
- pack_->Destroy();
- }
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- Pack* pack_;
-};
-
-TEST_F(Texture2DTest, Basic) {
- Texture2D* texture = pack()->CreateTexture2D(8, 8, Texture::ARGB8, 1, false);
- ASSERT_TRUE(texture != NULL);
- EXPECT_TRUE(texture->IsA(Texture2D::GetApparentClass()));
- EXPECT_TRUE(texture->IsA(Texture::GetApparentClass()));
- EXPECT_TRUE(texture->IsA(ParamObject::GetApparentClass()));
- EXPECT_EQ(texture->format(), Texture::ARGB8);
- EXPECT_EQ(texture->levels(), 1);
- EXPECT_FALSE(texture->render_surfaces_enabled());
- EXPECT_EQ(0, Texture::kMaxDimension >> Texture::kMaxLevels);
- EXPECT_EQ(1, Texture::kMaxDimension >> (Texture::kMaxLevels - 1));
-}
-
-TEST_F(Texture2DTest, SetRect) {
- const int kWidth = 8;
- const int kHeight = 8;
- const int kLevels = 2;
- const int kDestMip = 1;
- const unsigned kDestX = 1u;
- const unsigned kDestY = 1u;
- Texture2D* texture = pack()->CreateTexture2D(
- kWidth, kHeight, Texture::ARGB8, kLevels, false);
- ASSERT_TRUE(texture != NULL);
- static const uint8 kExpected1[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- };
- EXPECT_TRUE(CompareTexture(texture, 1, kExpected1));
- const int kSrcWidth = 2;
- const int kSrcHeight = 2;
- static const uint8 kSourcePixels[] = {
- 0x01, 0x01, 0x01, 0x02, 0x03, 0x03, 0x03, 0x04,
- 0x05, 0x05, 0x05, 0x06, 0x07, 0x07, 0x07, 0x08,
- };
- const int kSourcePitch = sizeof(kSourcePixels[0]) * kSrcWidth * 4;
- // normal copy
- texture->SetRect(kDestMip, kDestX, kDestY,
- kSrcWidth, kSrcHeight, kSourcePixels, kSourcePitch);
- static const uint8 kExpected2[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-
- 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x02,
- 0x03, 0x03, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00,
-
- 0x00, 0x00, 0x00, 0x00, 0x05, 0x05, 0x05, 0x06,
- 0x07, 0x07, 0x07, 0x08, 0x00, 0x00, 0x00, 0x00,
-
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- };
- EXPECT_TRUE(CompareTexture(texture, 1, kExpected2));
- // flipped copy
- texture->SetRect(
- kDestMip, kDestX, kDestY,
- kSrcWidth, kSrcHeight,
- kSourcePixels + kSourcePitch,
- -kSourcePitch);
- static const uint8 kExpected3[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-
- 0x00, 0x00, 0x00, 0x00, 0x05, 0x05, 0x05, 0x06,
- 0x07, 0x07, 0x07, 0x08, 0x00, 0x00, 0x00, 0x00,
-
- 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x02,
- 0x03, 0x03, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00,
-
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- };
- EXPECT_TRUE(CompareTexture(texture, 1, kExpected3));
-}
-
-class TextureCUBETest : public testing::Test {
- protected:
- TextureCUBETest()
- : object_manager_(g_service_locator) {
- }
-
- virtual void SetUp() {
- pack_ = object_manager_->CreatePack();
- }
-
- virtual void TearDown() {
- pack_->Destroy();
- }
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- Pack* pack_;
-};
-
-TEST_F(TextureCUBETest, Basic) {
- TextureCUBE* texture =
- pack()->CreateTextureCUBE(8, Texture::ARGB8, 1, false);
- ASSERT_TRUE(texture != NULL);
- EXPECT_TRUE(texture->IsA(TextureCUBE::GetApparentClass()));
- EXPECT_TRUE(texture->IsA(Texture::GetApparentClass()));
- EXPECT_TRUE(texture->IsA(ParamObject::GetApparentClass()));
- EXPECT_EQ(texture->format(), Texture::ARGB8);
- EXPECT_EQ(texture->levels(), 1);
- EXPECT_FALSE(texture->render_surfaces_enabled());
-}
-
-} // namespace o3d
-
diff --git a/o3d/core/cross/tick_event.h b/o3d/core/cross/tick_event.h
deleted file mode 100644
index 402ee44..0000000
--- a/o3d/core/cross/tick_event.h
+++ /dev/null
@@ -1,71 +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 TickEvent class.
-
-#ifndef O3D_CORE_CROSS_TICK_EVENT_H_
-#define O3D_CORE_CROSS_TICK_EVENT_H_
-
-namespace o3d {
-
-// This class is used to pass infomation to a registered ontick callback.
-class TickEvent {
- public:
- TickEvent()
- : elapsed_time_(0.0f) {
- }
-
- // Use this function to get elapsed time since the last tick event in
- // seconds.
- float elapsed_time() const;
-
- // The ticker will use this function to set the elapsed time. You should
- // never call this function.
- void set_elapsed_time(float time);
-
- private:
-
- // This is the elapsed time in seconds since the last tick event.
- float elapsed_time_;
-};
-
-inline void TickEvent::set_elapsed_time(float time) {
- elapsed_time_ = time;
-}
-
-inline float TickEvent::elapsed_time() const {
- return elapsed_time_;
-}
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_TICK_EVENT_H_
diff --git a/o3d/core/cross/timer.cc b/o3d/core/cross/timer.cc
deleted file mode 100644
index 35d21e7..0000000
--- a/o3d/core/cross/timer.cc
+++ /dev/null
@@ -1,114 +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 definitions of Timer related classes
-
-#include <build/build_config.h>
-#ifdef OS_LINUX
-#include <sys/time.h>
-#include <time.h>
-#endif
-#include "core/cross/timer.h"
-
-namespace o3d {
-
-#ifdef OS_LINUX
-static uint64_t GetCurrentTime() {
- struct timeval tv;
- gettimeofday(&tv, NULL);
- return tv.tv_sec*1000000ULL + tv.tv_usec;
-}
-#endif
-
-ElapsedTimeTimer::ElapsedTimeTimer() {
-#if defined(OS_WIN)
- // Get the frequency of the windows performance clock.
- QueryPerformanceFrequency(&windows_timer_frequency_);
-
- // Initialize the last_time_ value with the current time.
- QueryPerformanceCounter(&last_time_);
-#endif
-
-#if defined(OS_MACOSX)
- last_time_ = UpTime();
-#endif
-#if defined(OS_LINUX)
- last_time_ = GetCurrentTime();
-#endif
-}
-
-float ElapsedTimeTimer::GetElapsedTimeHelper(bool reset) {
- float elapsedTime = 0.0f;
- // Get current performance timer value.
- TimeStamp current_time;
-
-#ifdef OS_WIN
- QueryPerformanceCounter(&current_time);
-
- // Compute elapsed time since the last call.
- elapsedTime = static_cast<float>(
- static_cast<double>(current_time.QuadPart - last_time_.QuadPart) /
- static_cast<double>(windows_timer_frequency_.QuadPart));
-#endif
-
-#ifdef OS_MACOSX
- current_time = UpTime();
- AbsoluteTime elapsed_ticks = SubAbsoluteFromAbsolute(current_time,
- last_time_);
- Nanoseconds elapsedInNanos = AbsoluteToNanoseconds(elapsed_ticks);
- uint64 ns64 = UnsignedWideToUInt64(elapsedInNanos);
- double elapsedInSeconds = static_cast<double>(ns64) * 0.000000001;
- elapsedTime = elapsedInSeconds;
-#endif
-
-#ifdef OS_LINUX
- current_time = GetCurrentTime();
- elapsedTime = static_cast<float>((current_time - last_time_) * 1.e-6);
-#endif
-
- if (reset) {
- // Save the current time for the next time we ask.
- last_time_ = current_time;
- }
-
- return elapsedTime;
-}
-
-float ElapsedTimeTimer::GetElapsedTimeWithoutClearing() {
- return GetElapsedTimeHelper(false);
-}
-
-float ElapsedTimeTimer::GetElapsedTimeAndReset() {
- return GetElapsedTimeHelper(true);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/timer.h b/o3d/core/cross/timer.h
deleted file mode 100644
index 3529cb5..0000000
--- a/o3d/core/cross/timer.h
+++ /dev/null
@@ -1,84 +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 declarations of Timer related classes
-
-#ifndef O3D_CORE_CROSS_TIMER_H_
-#define O3D_CORE_CROSS_TIMER_H_
-
-#include <build/build_config.h>
-#ifdef OS_MACOSX
-#include <Carbon/Carbon.h>
-#endif
-
-#include "core/cross/types.h"
-
-namespace o3d {
-
-class ElapsedTimeTimer {
- public:
- ElapsedTimeTimer();
- // Gets the elapsed time in seconds since the last time the timer was reset,
- // then reset the stored time to restart the interval.
- float GetElapsedTimeAndReset();
- // Gets the elapsed time in seconds since the last time the timer was reset,
- // but doesn't reset the stored time. Use this to keep track of cumulative
- // time rather than each interval.
- float GetElapsedTimeWithoutClearing();
-
- private:
- float GetElapsedTimeHelper(bool reset);
-
-#ifdef OS_MACOSX
- typedef AbsoluteTime TimeStamp;
-#endif
-
-#ifdef OS_LINUX
- typedef uint64_t TimeStamp;
-#endif
-
-#ifdef OS_WIN
- typedef LARGE_INTEGER TimeStamp;
-#endif
-
-#ifdef OS_WIN
- // The frequency of the windows performance counter in ticks per second.
- TimeStamp windows_timer_frequency_;
-#endif
-
- // The value of the tick count from the windows performance counter from the
- // last time GetElapsedTime was called.
- TimeStamp last_time_;
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_TIMER_H_
diff --git a/o3d/core/cross/timingtable.h b/o3d/core/cross/timingtable.h
deleted file mode 100644
index d0c934b..0000000
--- a/o3d/core/cross/timingtable.h
+++ /dev/null
@@ -1,192 +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 class definitions for TimingTable and TimingRecord,
-// which together make up a quick-and-dirty profiling tool for hand-instrumented
-// code.
-
-#ifndef O3D_CORE_CROSS_TIMINGTABLE_H_
-#define O3D_CORE_CROSS_TIMINGTABLE_H_
-
-#ifdef PROFILE_CLIENT
-
-#include <map>
-#include <string>
-
-#include "core/cross/timer.h"
-#include "utils/cross/structured_writer.h"
-
-// A record for keeping track of timing stats for a single section of code,
-// identified by a string. TimingRecord stores enough info to tell you the max,
-// min, and mean time that the code segment took, and the number of times it was
-// called. It also reports unfinished and unbegun calls, which are cases in
-// which you told it to start or finish recording data, but that call failed to
-// have a corresponding finish or start. Unfinished calls usually mean that you
-// failed to instrument a branch exiting the block early. Unstarted calls are
-// probably more serious bugs.
-class TimingRecord {
- public:
- TimingRecord() :
- started_(false),
- unfinished_(0),
- unbegun_(0),
- calls_(0),
- time_(0),
- min_time_(LONG_MAX),
- max_time_(0) {
- }
-
- void Start() {
- if (started_) {
- ++unfinished_;
- }
- started_ = true;
- timer_.GetElapsedTimeAndReset(); // This is how you reset the timer.
- }
-
- void Stop() {
- if (started_) {
- started_= false;
- ++calls_;
- float time = timer_.GetElapsedTimeAndReset();
- if (time > max_time_) {
- max_time_ = time;
- }
- if (time < min_time_) {
- min_time_ = time;
- }
- time_ += time;
- } else {
- ++unbegun_;
- }
- }
-
- int UnfinishedCount() const {
- return unfinished_;
- }
- int UnbegunCount() const {
- return unbegun_;
- }
- int CallCount() const {
- return calls_;
- }
- float TimeSpent() const {
- return time_;
- }
- float MinTime() const {
- return min_time_;
- }
- float MaxTime() const {
- return max_time_;
- }
- void Write(o3d::StructuredWriter* writer) const {
- writer->OpenObject();
- writer->WritePropertyName("max");
- writer->WriteFloat(max_time_);
- writer->WritePropertyName("min");
- writer->WriteFloat(min_time_);
- writer->WritePropertyName("mean");
- writer->WriteFloat(calls_ ? time_ / calls_ : 0);
- writer->WritePropertyName("total");
- writer->WriteFloat(time_);
- writer->WritePropertyName("calls");
- writer->WriteInt(calls_);
- if (unfinished_) {
- writer->WritePropertyName("unfinished");
- writer->WriteInt(unfinished_);
- }
- if (unbegun_) {
- writer->WritePropertyName("unbegun");
- writer->WriteInt(unbegun_);
- }
- writer->CloseObject();
- }
-
- private:
- bool started_;
- int unfinished_;
- int unbegun_;
- int calls_;
- float time_;
- float min_time_;
- float max_time_;
- o3d::ElapsedTimeTimer timer_;
-};
-
-// The TimingTable is a quick-and-dirty profiler for hand-instrumented code.
-// Don't call its functions directly; wrap them in macros so that they can be
-// compiled in optionally. Currently we use GLUE_PROFILE_START/STOP/etc. in the
-// glue code [defined in common.h] and PROFILE_START/STOP/etc. elsewhere
-// in the plugin [defined below].
-class TimingTable {
- public:
- TimingTable() {
- }
-
- virtual public ~TimingTable() {}
-
- virtual void Reset() {
- table_.clear();
- }
-
- virtual void Start(const o3d::String& key) {
- table_[key].Start();
- }
-
- virtual void Stop(const o3d::String& key) {
- table_[key].Stop();
- }
-
- virtual void Write(o3d::StructuredWriter* writer) {
- std::map<o3d::String, TimingRecord>::iterator iter;
- writer->OpenArray();
- for (iter = table_.begin(); iter != table_.end(); ++iter) {
- const TimingRecord& record = iter->second;
- if (record.CallCount() || record.UnfinishedCount() ||
- record.UnbegunCount()) {
- writer->OpenObject();
- writer->WritePropertyName(iter->first);
- iter->second.Write(writer);
- writer->CloseObject();
- }
- }
- writer->CloseArray();
- writer->Close();
- }
-
- private:
- std::map<o3d::String, TimingRecord> table_;
-};
-
-#endif // PROFILE_CLIENT
-
-#endif // O3D_CORE_CROSS_TIMINGTABLE_H_
diff --git a/o3d/core/cross/transform.cc b/o3d/core/cross/transform.cc
deleted file mode 100644
index a9cf707..0000000
--- a/o3d/core/cross/transform.cc
+++ /dev/null
@@ -1,375 +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 definition of the Transform class.
-
-#include "core/cross/transform.h"
-#include "core/cross/renderer.h"
-#include "core/cross/error.h"
-
-namespace o3d {
-
-namespace {
-
-// Returns true if the child transform is already an ancestor of the
-// parent_transform argument.
-// Note: Routine will infinite loop if cycles exist in the Transform graph.
-bool ParentingIntroducesCycle(Transform* child_transform,
- Transform* parent_transform) {
- if (!parent_transform || !child_transform) {
- return false;
- }
-
- // Break the recursion if the parent and child are the same transform.
- if (child_transform == parent_transform) {
- return true;
- }
-
- // Otherwise, recurse on each of the children of the child_transform.
- const TransformRefArray& children(child_transform->GetChildrenRefs());
- TransformRefArray::const_iterator children_iter(children.begin()),
- end(children.end());
- for (; children_iter != end; ++children_iter) {
- if (ParentingIntroducesCycle(*children_iter, parent_transform)) {
- return true;
- }
- }
-
- return false;
-}
-
-void GetTransformsInTreeRecursive(const Transform* tree_root,
- TransformArray* children) {
- children->push_back(const_cast<Transform*>(tree_root));
- const TransformRefArray& children_array = tree_root->GetChildrenRefs();
- TransformRefArray::const_iterator children_iter(children_array.begin()),
- children_end(children_array.end());
- for (; children_iter != children_end; ++children_iter) {
- GetTransformsInTreeRecursive(*children_iter, children);
- }
-}
-
-} // end unnamed namespace
-
-O3D_DEFN_CLASS(Transform, ParamObject);
-O3D_DEFN_CLASS(ParamTransform, RefParamBase);
-
-const char* Transform::kLocalMatrixParamName =
- O3D_STRING_CONSTANT("localMatrix");
-const char* Transform::kWorldMatrixParamName =
- O3D_STRING_CONSTANT("worldMatrix");
-const char* Transform::kVisibleParamName =
- O3D_STRING_CONSTANT("visible");
-const char* Transform::kBoundingBoxParamName =
- O3D_STRING_CONSTANT("boundingBox");
-const char* Transform::kCullParamName =
- O3D_STRING_CONSTANT("cull");
-
-Transform::Transform(ServiceLocator* service_locator)
- : ParamObject(service_locator),
- parent_(NULL),
- param_cache_manager_(service_locator->GetService<Renderer>()),
- weak_pointer_manager_(this) {
- RegisterParamRef(kLocalMatrixParamName, &local_matrix_param_ref_);
- SlaveParamMatrix4::RegisterParamRef(kWorldMatrixParamName,
- &world_matrix_param_ref_,
- this);
- RegisterParamRef(kVisibleParamName, &visible_param_ref_);
- RegisterParamRef(kBoundingBoxParamName, &bounding_box_param_ref_);
- RegisterParamRef(kCullParamName, &cull_param_ref_);
-
- set_visible(true);
-}
-
-Transform::~Transform() {
- // Sets any children to have no parent.
- TransformArray children(GetChildren());
- TransformArray::iterator end(children.end());
- for (TransformArray::iterator iter(children.begin());
- iter != end;
- ++iter) {
- (*iter)->SetParent(NULL);
- }
-}
-
-void Transform::UpdateOutputs() {
- Matrix4 world_matrix;
- if (world_matrix_param_ref_->input_connection() == NULL) {
- if (parent_) {
- world_matrix_param_ref_->set_dynamic_value(parent_->world_matrix() *
- local_matrix());
- } else {
- world_matrix_param_ref_->set_dynamic_value(local_matrix());
- }
- }
-}
-
-ObjectBase::Ref Transform::Create(ServiceLocator* service_locator) {
- Renderer* renderer = service_locator->GetService<Renderer>();
- if (NULL == renderer) {
- O3D_ERROR(service_locator) << "No Render Device Available";
- return ObjectBase::Ref();
- }
- return ObjectBase::Ref(new Transform(service_locator));
-}
-
-// Returns a (read-only) array of immediate children for that transform.
-TransformArray Transform::GetChildren() const {
- // TODO: Unify the system behaviour when working with arrays of refs and
- // raw pointers to avoid costly conversions.
- TransformArray children_array;
- children_array.reserve(child_array_.size());
- TransformRefArray::const_iterator child_iter(child_array_.begin()),
- child_end(child_array_.end());
- for (; child_iter != child_end; ++child_iter) {
- children_array.push_back(child_iter->Get());
- }
-
- return children_array;
-}
-
-// Removes a child transform from the child_array_. Returns true if the
-// operation succeeds.
-bool Transform::RemoveChild(Transform *child) {
- TransformRefArray::iterator end = remove(child_array_.begin(),
- child_array_.end(),
- Transform::Ref(child));
-
- // child should never be in the child array more than once.
- DLOG_ASSERT(std::distance(end, child_array_.end()) <= 1);
-
- // The child was never found.
- if (end == child_array_.end())
- return false;
-
- // We need to do this before erasing the child since the child may get
- // destroyed when we erase its reference below.
- child->world_matrix_param_ref_->DecrementNotCachableCountOnParamChainForInput(
- world_matrix_param_ref_);
-
- // Actually remove the child from the child array.
- child_array_.erase(end, child_array_.end());
-
- return true;
-}
-
-// Adds a child to the transform. Always returns true.
-bool Transform::AddChild(Transform* child) {
- child->world_matrix_param_ref_->IncrementNotCachableCountOnParamChainForInput(
- world_matrix_param_ref_);
- child_array_.push_back(Transform::Ref(child));
- return true;
-}
-
-// Return the transforms in a given subtree. This method performs a depth-first
-// traversal of the tree to get the results
-TransformArray Transform::GetTransformsInTree() const {
- TransformArray tree_transforms;
- GetTransformsInTreeRecursive(this, &tree_transforms);
- return tree_transforms;
-}
-
-// Functor object for comparing Transform names.
-namespace {
-class CompareTransformName {
- public:
- explicit CompareTransformName(const String& n) : test_name_(n) {}
- bool operator()(Transform*& transform) {
- return transform->name() == test_name_;
- }
- private:
- String test_name_;
-};
-}
-
-// Search for transforms by name in the subtree below this transform including
-// this transform.
-TransformArray Transform::GetTransformsByNameInTree(const String& name) const {
- // Get all the transforms in the subtree
- TransformArray transforms = GetTransformsInTree();
- // Partition the container into two sections depending on whether the
- // transform name matches the desired name.
- TransformArray::iterator i =
- std::partition(transforms.begin(),
- transforms.end(),
- CompareTransformName(name));
- // delete the transforms that don't match the name.
- transforms.erase(i, transforms.end());
- return transforms;
-}
-
-// Sets the parent of a transform. Calling "transform->SetParent(NULL)"
-// disconnects the parent-child relationship if one already exists, and does
-// nothing if the transform has no parent.
-void Transform::SetParent(Transform *new_parent) {
- // Ensure that this parent assignment does not create a cycle in the
- // transform graph.
- if (ParentingIntroducesCycle(this, new_parent)) {
- O3D_ERROR(service_locator())
- << "Cannot set parent as it creates a cycle";
- return;
- }
-
- // Creates a temporary reference to ourselves because if our current parent
- // holds the only reference to us then we'll get deleted the moment we call
- // RemoveChild. This temporary reference will let go automatically when
- // the function exits.
- Transform::Ref temp_reference(this);
-
- // First check if the transform already has a parent. If it does then
- // remove it from its current parent first.
- if (parent_ != NULL) {
- bool removed = parent_->RemoveChild(this);
- DLOG_ASSERT(removed);
- if (!removed)
- return;
- }
-
- // If we are just unparenting the transform then we are done.
- if (new_parent == NULL) {
- parent_ = NULL;
- return;
- }
-
- // Add the transform as a child of its new parent.
- parent_ = new_parent;
- bool added = new_parent->AddChild(this);
- DLOG_ASSERT(added);
-
- // If we failed to add the child to the parent then leave the child transform
- // an orphan in order to avoid any inconsistencies in the scenegraph
- if (!added)
- parent_ = NULL;
-}
-
-// Explicitly calculates and returns the world matrix. The world matrix
-// is computed as the product of the parent world matrix and the local matrix
-// unless there's an input bind to the WorldMatrix param in which case
-// we return the value from the bind.
-Matrix4 Transform::GetUpdatedWorldMatrix() {
- if (world_matrix_param_ref_->input_connection() != NULL) {
- return world_matrix_param_ref_->value();
- } else {
- Matrix4 world_matrix;
- if (parent()) {
- world_matrix = parent()->GetUpdatedWorldMatrix() * local_matrix();
- } else {
- world_matrix = local_matrix();
- }
- world_matrix_param_ref_->set_dynamic_value(world_matrix);
- return world_matrix;
- }
-}
-
-// Adds a shape do this transform.
-void Transform::AddShape(Shape* shape) {
- shape_array_.push_back(Shape::Ref(shape));
-}
-
-// Removes a shape from this transform.
-bool Transform::RemoveShape(Shape* shape) {
- ShapeRefArray::iterator iter = std::find(shape_array_.begin(),
- shape_array_.end(),
- Shape::Ref(shape));
- if (iter != shape_array_.end()) {
- shape_array_.erase(iter);
- return true;
- }
- return false;
-}
-
-// Gets an Array of shapes in this transform.
-ShapeArray Transform::GetShapes() const {
- ShapeArray shapes;
- shapes.reserve(shape_array_.size());
- std::copy(shape_array_.begin(),
- shape_array_.end(),
- std::back_inserter(shapes));
- return shapes;
-}
-
-void Transform::SetShapes(const ShapeArray& shapes) {
- shape_array_.resize(shapes.size());
- for (unsigned int i = 0; i != shapes.size(); ++i) {
- shape_array_[i] = Shape::Ref(shapes[i]);
- }
-}
-
-void Transform::CreateDrawElements(Pack* pack, Material* material) {
- for (unsigned cc = 0; cc < child_array_.size(); ++cc) {
- child_array_[cc]->CreateDrawElements(pack, material);
- }
- for (unsigned ss = 0; ss < shape_array_.size(); ++ss) {
- shape_array_[ss]->CreateDrawElements(pack, material);
- }
-}
-
-void Transform::ConcreteGetInputsForParam(const Param* param,
- ParamVector* inputs) const {
- // If it's the world matrix it's affected by our local matrix and our parent
- // unless the world matrix has an input_connection.
- if (param == world_matrix_param_ref_) {
- if (world_matrix_param_ref_->input_connection() == NULL) {
- inputs->push_back(local_matrix_param_ref_);
- if (parent()) {
- inputs->push_back(parent()->world_matrix_param_ref_);
- }
- }
- }
-}
-
-void Transform::ConcreteGetOutputsForParam(const Param* param,
- ParamVector* outputs) const {
- // If it's the local matrix then it affects the world matrix unless the world
- // matrix has an input_connection.
- if (param == local_matrix_param_ref_) {
- if (world_matrix_param_ref_->input_connection() == NULL) {
- outputs->push_back(world_matrix_param_ref_);
- }
- } else if (param == world_matrix_param_ref_) {
- // If it's the world matrix it affects all the children's world matrices
- // unless they have an input connection.
- for (unsigned ii = 0; ii < child_array_.size(); ++ii) {
- Transform* child = child_array_[ii];
- Param* param = child->world_matrix_param_ref_;
- if (param->input_connection() == NULL) {
- outputs->push_back(param);
- }
- }
- }
-}
-
-ObjectBase::Ref ParamTransform::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new ParamTransform(service_locator, false, false));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/transform.h b/o3d/core/cross/transform.h
deleted file mode 100644
index 02f2b5f..0000000
--- a/o3d/core/cross/transform.h
+++ /dev/null
@@ -1,331 +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 declarations for TransformParamMatrix4 and Transform.
-
-#ifndef O3D_CORE_CROSS_TRANSFORM_H_
-#define O3D_CORE_CROSS_TRANSFORM_H_
-
-#include <vector>
-#include "core/cross/param_object.h"
-#include "core/cross/param.h"
-#include "core/cross/types.h"
-#include "core/cross/shape.h"
-#include "core/cross/param_cache.h"
-#include "core/cross/bounding_box.h"
-
-namespace o3d {
-
-class Transform;
-class Client;
-class Pack;
-
-// Array container for Transform pointers.
-typedef std::vector<Transform*> TransformArray;
-
-// Iterators for TransformArray.
-typedef TransformArray::const_iterator TransformArrayConstIterator;
-typedef TransformArray::iterator TransformArrayIterator;
-
-// The Transform defines a single 4x4 matrix transformational element. A
-// Transform can have one or no parents and an arbitrary number of children.
-// The Transform stores two transformation matrices, the local_matrix matrix
-// and the world_matrix which caches the the transformation between the local
-// coordinate system and the world (root) coordinate system when the Transform
-// belongs to the scenegraph.
-class Transform : public ParamObject {
- friend class Client;
- public:
- typedef SmartPointer<Transform> Ref;
- typedef WeakPointer<Transform> WeakPointerType;
-
- // Array for Transform references.
- typedef std::vector<Transform::Ref> TransformRefArray;
-
- // Names of Transform Params.
- static const char* kLocalMatrixParamName;
- static const char* kWorldMatrixParamName;
- static const char* kVisibleParamName;
- static const char* kBoundingBoxParamName;
- static const char* kCullParamName;
-
- ~Transform();
-
- // Returns true if any params used during tree traversal have input
- // connections.
- inline bool ParamsUsedByTreeTraversalHaveInputConnections() {
- return cull_param_ref_->input_connection() != NULL ||
- bounding_box_param_ref_->input_connection() != NULL;
- }
-
- // Sets the parent of the Transform by re-parenting the Transform under
- // parent. Setting parent to NULL removes the Transform and the entire subtree
- // below it from the scenegraph. The operation will fail if the parenting
- // operation will produce a cycle in the scenegraph.
- //
- // NOTE!: If in setting the parent to NULL the transform is no longer
- // referenced by any other transforms and is not referenced by any packs it
- // will be deleted
- //
- // Paremeters:
- // parent: the new parent or NULL to un-parent the transform
- void SetParent(Transform *parent);
-
- // Returns the Transform's parent
- // Parameters:
- // None
- // Returns:
- // Pointer to the parent Transform of this Transform.
- inline Transform* parent() const {
- return parent_;
- }
-
- // Returns the visibility for this Transform.
- bool visible() const {
- return visible_param_ref_->value();
- }
-
- // Sets the visibility for this Transform.
- void set_visible(bool value) {
- visible_param_ref_->set_value(value);
- }
-
- // Returns the BoundingBox of this Transform.
- BoundingBox bounding_box() const {
- return bounding_box_param_ref_->value();
- }
-
- // Sets the BoundingBox used to cull this Transform.
- void set_bounding_box(const BoundingBox& bounding_box) {
- bounding_box_param_ref_->set_value(bounding_box);
- }
-
- // Returns the cull setting of this Transform. true = attempt to cull by
- // bounding box, false = do not attempt to cull.
- bool cull() const {
- return cull_param_ref_->value();
- }
-
- // Sets the cull setting for this Transform. true = attempt to cull by
- // bounding box, false = do not attempt to cull
- void set_cull(bool cull) {
- cull_param_ref_->set_value(cull);
- }
-
- // Returns the local transform matrix.
- Matrix4 local_matrix() const {
- return local_matrix_param_ref_->value();
- }
-
- // Sets the local transform matrix.
- void set_local_matrix(const Matrix4& local_matrix) {
- local_matrix_param_ref_->set_value(local_matrix);
- }
-
- // Returns the world transform matrix. The world transformation matrix
- // gets updated each frame by the client if there's a direct path from the
- // scenegraph root to the Transform.
- Matrix4 world_matrix() const {
- return world_matrix_param_ref_->value();
- }
-
- // Evaluates and returns the current world matrix.
- // The world transform matrix returned is always valid for all transforms
- // which have a path to the scene root.
- // Returns:
- // World Matrix.
- Matrix4 GetUpdatedWorldMatrix();
-
- // Returns the immediate children of the Transform. Note that the returned
- // array consists of raw pointers and is a copy of the internal array.
- TransformArray GetChildren() const;
-
- // Returns the immediate children of the Transform as an array of refs.
- const TransformRefArray& GetChildrenRefs() const {
- return child_array_;
- }
-
- // Returns all the transforms in a subtree.
- // Returns this transform and all its descendants. Note that this does not
- // have to be in the transform graph.
- // Returns:
- // An array containing pointers to the transforms of the subtree
- TransformArray GetTransformsInTree() const;
-
- // Searches for transforms that match the given name in the hierarchy under
- // and including this transform. Since there can be more than one transform
- // with a given name, results are returned in an array.
- // Parameters:
- // name: transform name to look for
- // Returns:
- // An array of pointers to transforms matching the given name
- TransformArray GetTransformsByNameInTree(const String& name) const;
-
- // Adds a shape do this transform.
- // Parameters:
- // shape: Shape to add.
- void AddShape(Shape* shape);
-
- // Removes a shape from this transform.
- // Parameters:
- // shape: Shape to remove.
- // Returns:
- // true if successful, false if shape was not in this transform.
- bool RemoveShape(Shape* shape);
-
- // Gets an Array of shapes in this transform.
- // Returns:
- // ShapeArray of shapes in this transform.
- ShapeArray GetShapes() const;
-
- // Sets the array of shapes for this transform.
- void SetShapes(const ShapeArray& shapes);
-
- // Gets a direct const reference to the shapes in this transform.
- // Returns:
- // const reference to the shapes in this transform.
- const ShapeRefArray& GetShapeRefs() const {
- return shape_array_;
- }
-
- // Walks the tree of transforms starting with this transform and creates
- // draw elements. If an Element already has a DrawElement that uses material a
- // new DrawElement will not be created.
- // Parameters:
- // pack: pack used to manage created elements.
- // material: material to use for each element. If you pass NULL it will use
- // the material on the element to which a draw element is being added.
- // In other words, a DrawElement will use the material of the
- // corresponidng Element if material is NULL. This allows you to easily
- // setup the default (just draw as is) by passing NULL or setup a shadow
- // pass by passing in a shadow material.
- void CreateDrawElements(Pack* pack,
- Material* material);
-
- // Gets the ParamCacheManager for this transform.
- inline ParamCacheManager& param_cache_manager() {
- return param_cache_manager_;
- }
-
- // Gets a weak pointer to us.
- WeakPointerType GetWeakPointer() const {
- return weak_pointer_manager_.GetWeakPointer();
- }
-
- // Update the world Matrix.
- void UpdateOutputs();
-
- protected:
- // Removes a child transform from the child array. Does not change the child
- // transform's parent.
- virtual bool RemoveChild(Transform* child);
-
- // Adds a child transform to the child array. Does not change the child
- // transform's parent.
- virtual bool AddChild(Transform* child);
-
- // Overridden from ParamObject
- // For the given Param, returns all the inputs that affect that param through
- // this ParamObject.
- virtual void ConcreteGetInputsForParam(const Param* param,
- ParamVector* inputs) const;
-
- // Overridden from ParamObject
- // For the given Param, returns all the outputs that the given param will
- // affect through this ParamObject.
- virtual void ConcreteGetOutputsForParam(const Param* param,
- ParamVector* outputs) const;
-
- private:
- typedef SlaveParam<ParamMatrix4, Transform> SlaveParamMatrix4;
-
- explicit Transform(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // Every transform in the transform graph hierarchy has a Transform as a
- // parent. If parent_ is NULL then the transform is not in the hierarchy,
- Transform *parent_;
-
- // World (model) matrix which takes into account the entire transformation
- // hierarchy above the transform.
- SlaveParamMatrix4::Ref world_matrix_param_ref_;
-
- // Local transformation matrix.
- ParamMatrix4::Ref local_matrix_param_ref_;
-
- // Visible param.
- ParamBoolean::Ref visible_param_ref_;
-
- // Bounding box to cull by.
- ParamBoundingBox::Ref bounding_box_param_ref_;
-
- // Culling on or off.
- ParamBoolean::Ref cull_param_ref_;
-
- // Array of refs to children Transforms for this transform.
- TransformRefArray child_array_;
-
- // Array of refs to Shapes under this transform
- ShapeRefArray shape_array_;
-
- // Caches of Params for rendering.
- ParamCacheManager param_cache_manager_;
-
- // Manager for weak pointers to us.
- WeakPointerType::WeakPointerManager weak_pointer_manager_;
-
- O3D_DECL_CLASS(Transform, ParamObject)
-}; // Transform
-
-class ParamTransform : public TypedRefParam<Transform> {
- public:
- typedef SmartPointer<ParamTransform> Ref;
-
- ParamTransform(ServiceLocator* service_locator,
- bool dynamic,
- bool read_only)
- : TypedRefParam<Transform>(service_locator, dynamic, read_only) {}
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- O3D_DECL_CLASS(ParamTransform, RefParamBase)
-};
-
-typedef std::vector<Transform::Ref> TransformRefArray;
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_TRANSFORM_H_
diff --git a/o3d/core/cross/transform_test.cc b/o3d/core/cross/transform_test.cc
deleted file mode 100644
index c6fa213..0000000
--- a/o3d/core/cross/transform_test.cc
+++ /dev/null
@@ -1,611 +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 functionality defined in transform.cc/h
-
-#include <algorithm>
-
-#include "core/cross/transform.h"
-#include "core/cross/shape.h"
-#include "core/cross/primitive.h"
-#include "core/cross/material.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-#include "tests/common/win/testing_common.h"
-
-namespace o3d {
-
-// Use a looser bound on floating point compares - 8 units in the last
-// place, allowing a loss of 3 bits of accuracy on a 23-bit mantissa.
-#define EXPECT_FLOAT_EQ_O3D(expected, actual) \
- EXPECT_TRUE(AlmostEqual32BitFloat((expected), (actual), 8))
-
-// ----------------------------------------------------------------------------
-
-namespace {
-
-union FloatAndInt {
- float float_value;
- int int_value;
-};
-
-// Bit casts a float into an int.
-inline int FloatAsInt(float value) {
- FloatAndInt float_and_int;
- float_and_int.float_value = value;
- return float_and_int.int_value;
-}
-
-// Compares 32-bit floating point values by converting them into integers
-// using a "type pun" and subtracting them to see how different they are as
-// bit patterns, with a necessary fudge for the IEEE754 +0/-0 area.
-// For more see:
-// http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
-bool AlmostEqual32BitFloat(float first, float second, int max_ulps) {
- // Make sure max_ulps is non-negative and small enough to force NaN to not
- // compare as ordered.
- LOG_ASSERT(max_ulps > 0 && max_ulps < 4*1024*1024);
- int first_int = FloatAsInt(first);
- // Make first_int lexicographically ordered in twos-compliment.
- if (first_int < 0) first_int = 0x80000000 - first_int;
- // Make second_int lexicographically ordered in twos-complement
- int second_int = FloatAsInt(second);
- if (second_int < 0) second_int = 0x80000000 - second_int;
- int difference = abs(first_int - second_int);
- if (difference <= max_ulps) return true;
- return false;
-}
-
-// Compares two Vector3's for equality
-void CompareVector3s(const Vector3& v1, const Vector3& v2) {
- EXPECT_FLOAT_EQ_O3D(v1.getX(), v2.getX());
- EXPECT_FLOAT_EQ_O3D(v1.getY(), v2.getY());
- EXPECT_FLOAT_EQ_O3D(v1.getZ(), v2.getZ());
-}
-
-// Compares two Vector4's for equality
-void CompareVector4s(const Vector4& v1, const Vector4& v2) {
- EXPECT_FLOAT_EQ_O3D(v1.getX(), v2.getX());
- EXPECT_FLOAT_EQ_O3D(v1.getY(), v2.getY());
- EXPECT_FLOAT_EQ_O3D(v1.getZ(), v2.getZ());
- EXPECT_FLOAT_EQ_O3D(v1.getW(), v2.getW());
-}
-
-// Compares two Matrix4's for equality
-void CompareMatrix4s(const Matrix4& m1, const Matrix4& m2) {
- CompareVector4s(m1.getCol0(), m2.getCol0());
- CompareVector4s(m1.getCol1(), m2.getCol1());
- CompareVector4s(m1.getCol2(), m2.getCol2());
- CompareVector4s(m1.getCol3(), m2.getCol3());
-}
-
-bool MatricesAreSame(const Matrix4& m1, const Matrix4& m2) {
- for (int ii = 0; ii < 4; ++ii) {
- const Vector4& vec1 = m1[ii];
- const Vector4& vec2 = m2[ii];
- for (int jj = 0; jj < 4; ++jj) {
- if (!AlmostEqual32BitFloat(vec1[jj], vec2[jj], 8)) {
- return false;
- }
- }
- }
- return true;
-}
-
-// Check if a param is in the given param array
-// Parameters:
-// param: param to search for.
-// params: ParamVector to search.
-// Returns:
-// true if param is in params.
-bool ParamInParams(Param* param, const ParamVector& params) {
- return std::find(params.begin(), params.end(), param) != params.end();
-}
-
-// A non-cachable Param.
-class ParamCounter : public ParamMatrix4 {
- public:
- explicit ParamCounter(ServiceLocator* service_locator)
- : ParamMatrix4(service_locator, true, true),
- count_(0) {
- SetNotCachable();
- }
- private:
- virtual void ComputeValue() {
- count_ += 1.0f;
- set_read_only_value(Matrix4(Vector4(count_, count_, count_, count_),
- Vector4(count_, count_, count_, count_),
- Vector4(count_, count_, count_, count_),
- Vector4(count_, count_, count_, count_)));
- }
-
- float count_;
-};
-
-} // end unnamed namespace
-
-// Basic test fixture. Simply creates a Client object
-// before each test and deletes it after
-class TransformBasic : public testing::Test {
- protected:
- TransformBasic()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
-
- virtual void TearDown();
-
- // Creates a simple Transform hierarchy for testing world matrix updates
- void SetupSimpleTree();
-
- Pack* pack() { return pack_; }
-
- Transform* transform_;
- Transform* transform2_;
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- Pack* pack_;
-};
-
-void TransformBasic::SetUp() {
- pack_ = object_manager_->CreatePack();
- transform_ = pack()->Create<Transform>();
- transform2_ = pack()->Create<Transform>();
-}
-
-void TransformBasic::TearDown() {
- pack_->Destroy();
-}
-
-// Make sure the Transform is initialized properly
-TEST_F(TransformBasic, Type) {
- // Check the type
- EXPECT_EQ(Transform::GetApparentClass(), transform_->GetClass());
-
- // Check that the local_matrix is identity
- CompareMatrix4s(Matrix4::identity(), transform_->local_matrix());
-
- // Check that the default params got created
- EXPECT_TRUE(
- transform_->GetParam<ParamBoolean>(Transform::kVisibleParamName) != NULL);
- EXPECT_TRUE(
- transform_->GetParam<ParamBoolean>(Transform::kCullParamName) != NULL);
- EXPECT_TRUE(
- transform_->GetParam<ParamBoundingBox>(
- Transform::kBoundingBoxParamName) != NULL);
-
- // Check that visibility defaults to true
- EXPECT_EQ(transform_->visible(), true);
-}
-
-// Test set_local_matrix() / local_matrix() {
-TEST_F(TransformBasic, SetLocalMatrix) {
- Matrix4 t(Vector4(0, 1, 2, 3),
- Vector4(4, 5, 6, 7),
- Vector4(8, 9, 8, 7),
- Vector4(6, 5, 4, 3));
- transform_->set_local_matrix(t);
-
- CompareMatrix4s(t, transform_->local_matrix());
-}
-
-// Create an additional Transform and parent transform_ under it
-void TransformBasic::SetupSimpleTree() {
- transform2_->set_name("t2");
-
- // Make the transform_ a child of t2
- transform_->SetParent(transform2_);
-
- // Set t2's local matrix
- Vector3 translate(10, 20, 30);
- Vector3 rotate(1, 2, 3);
- Vector3 scale(5, 6, 7);
-
- Matrix4 mat(Matrix4::identity());
- mat *= Matrix4::translation(translate);
- mat *= Matrix4::rotationZYX(rotate);
- mat *= Matrix4::scale(scale);
-
- transform2_->set_local_matrix(mat);
-
- // Set transform_'s local matrix
- Vector3 translate2(30, 40, 50);
- Vector3 rotate2(3, 4, 5);
- Vector3 scale2(4, 5, 12);
-
- mat = Matrix4::identity();
- mat *= Matrix4::translation(translate2);
- mat *= Matrix4::rotationZYX(rotate2);
- mat *= Matrix4::scale(scale2);
-
- transform_->set_local_matrix(mat);
-}
-
-
-// Tests GetUpdatedWorldMatrix()
-TEST_F(TransformBasic, GetUpdatedWorldMatrix) {
- // Create a basic hierarchy
- SetupSimpleTree();
-
- Matrix4 t_transform = transform_->local_matrix();
- Matrix4 t2_transform = transform2_->local_matrix();
-
- // Expected world matrix for transform_
- Matrix4 expected_transform = t2_transform * t_transform;
-
- CompareMatrix4s(expected_transform, transform_->GetUpdatedWorldMatrix());
-
- // Now bind something to the world_matrix of t2 and make sure that the
- // value we get is the value from the bind and not from the product
- // of the local matrix with the parent matrix.
- ParamMatrix4* matrix_param =
- transform_->CreateParam<ParamMatrix4>("matrixParam");
- Matrix4 matrix = Matrix4::translation(Vector3(10, 0, 10)) *
- Matrix4::rotationZYX(Vector3(2, 1, 2)) *
- Matrix4::scale(Vector3(1, 2, 3));
- matrix_param->set_value(matrix);
-
- ParamMatrix4* t_world_matrix =
- transform_->GetParam<ParamMatrix4>(Transform::kWorldMatrixParamName);
- ASSERT_TRUE(t_world_matrix != NULL);
- ASSERT_TRUE(t_world_matrix->Bind(matrix_param));
-
- CompareMatrix4s(matrix, transform_->GetUpdatedWorldMatrix());
-}
-
-// Tests GetChildren()
-TEST_F(TransformBasic, GetChildren) {
- Transform* t2 = pack()->Create<Transform>();
- Transform* t3 = pack()->Create<Transform>();
-
- EXPECT_EQ(0U, transform_->GetChildren().size());
-
- t2->SetParent(transform_);
- EXPECT_EQ(1U, transform_->GetChildren().size());
-
- t3->SetParent(transform_);
- EXPECT_EQ(2U, transform_->GetChildren().size());
-
- TransformArray children = transform_->GetChildren();
- TransformArrayConstIterator pos = find(children.begin(), children.end(), t2);
- EXPECT_TRUE(pos != children.end());
-
- pos = find(children.begin(), children.end(), t3);
- EXPECT_TRUE(pos != children.end());
-}
-
-// Tests WorldMatrix on Transform
-TEST_F(TransformBasic, WorldMatrix) {
- // Setup a basic hierarchy
- SetupSimpleTree();
-
- // Compute expected world matrix for transform_
- Matrix4 t_transform = transform_->local_matrix();
- Matrix4 t2_transform = transform2_->local_matrix();
- Matrix4 expected_world_matrix = t2_transform * t_transform;
-
- // Force an update of the world_matrix for transform_
- transform_->GetUpdatedWorldMatrix();
-
- // Get current worldMatrix
- Matrix4 world_matrix_val(transform_->world_matrix());
-
- CompareMatrix4s(Matrix4(expected_world_matrix), world_matrix_val);
-}
-
-// Tests GetTransformsInTree
-TEST_F(TransformBasic, GetTransformsInTree) {
- // Setup a basic hierarchy
- SetupSimpleTree();
-
- Transform* t3 = pack()->Create<Transform>();
- Transform* t4 = pack()->Create<Transform>();
- t3->SetParent(transform_);
- t4->SetParent(t3);
-
- TransformArray transforms_in_tree(transform2_->GetTransformsInTree());
-
- // Check that all of them are in the tree.
- EXPECT_EQ(transforms_in_tree.size(), 4U);
- EXPECT_TRUE(std::find(transforms_in_tree.begin(),
- transforms_in_tree.end(),
- transform_) != transforms_in_tree.end());
- EXPECT_TRUE(std::find(transforms_in_tree.begin(),
- transforms_in_tree.end(),
- transform2_) != transforms_in_tree.end());
- EXPECT_TRUE(std::find(transforms_in_tree.begin(),
- transforms_in_tree.end(),
- t3) != transforms_in_tree.end());
- EXPECT_TRUE(std::find(transforms_in_tree.begin(),
- transforms_in_tree.end(),
- t4) != transforms_in_tree.end());
-
- // Check if we remove one it it's still correct.
- t3->SetParent(NULL);
-
- transforms_in_tree = transform2_->GetTransformsInTree();
- EXPECT_EQ(transforms_in_tree.size(), 2U);
- EXPECT_TRUE(std::find(transforms_in_tree.begin(),
- transforms_in_tree.end(),
- transform_) != transforms_in_tree.end());
- EXPECT_TRUE(std::find(transforms_in_tree.begin(),
- transforms_in_tree.end(),
- transform2_) != transforms_in_tree.end());
- EXPECT_FALSE(std::find(transforms_in_tree.begin(),
- transforms_in_tree.end(),
- t3) != transforms_in_tree.end());
- EXPECT_FALSE(std::find(transforms_in_tree.begin(),
- transforms_in_tree.end(),
- t4) != transforms_in_tree.end());
-}
-
-// Tests GetTransformsByNameInTree
-TEST_F(TransformBasic, GetTransformsByNameInTree) {
- // Setup a basic hierarchy
- SetupSimpleTree();
-
- // Check that a transform is in there.
- EXPECT_EQ(transform2_->GetTransformsByNameInTree("t2").size(), 1U);
- // Check that another transform is not in there.
- EXPECT_EQ(transform2_->GetTransformsByNameInTree("t3").size(), 0U);
-}
-
-// Tests AddShape, RemoveShape, GetShapes.
-TEST_F(TransformBasic, AddShapeRemoveShapeGetShapes) {
- Shape* shape1 = pack()->Create<Shape>();
- Shape* shape2 = pack()->Create<Shape>();
- ASSERT_TRUE(shape1 != NULL);
- ASSERT_TRUE(shape2 != NULL);
-
- transform_->AddShape(shape1);
- transform_->AddShape(shape2);
-
- // Check that they actually got added.
- {
- const ShapeRefArray& shapes = transform_->GetShapeRefs();
- EXPECT_EQ(shapes.size(), 2U);
- EXPECT_TRUE(std::find(shapes.begin(),
- shapes.end(),
- Shape::Ref(shape1)) != shapes.end());
- EXPECT_TRUE(std::find(shapes.begin(),
- shapes.end(),
- Shape::Ref(shape2)) != shapes.end());
- }
-
- // Add a second copy of shape1.
- transform_->AddShape(shape1);
-
- {
- // check it got added.
- ShapeArray shapes = transform_->GetShapes();
- EXPECT_EQ(shapes.size(), 3U);
- EXPECT_TRUE(std::find(shapes.begin(),
- shapes.end(),
- Shape::Ref(shape1)) != shapes.end());
- EXPECT_TRUE(std::find(shapes.begin(),
- shapes.end(),
- Shape::Ref(shape2)) != shapes.end());
- }
-
- // Check that they can be removed.
- EXPECT_TRUE(transform_->RemoveShape(shape1));
- EXPECT_TRUE(transform_->RemoveShape(shape1));
- EXPECT_FALSE(transform_->RemoveShape(shape1));
- EXPECT_TRUE(transform_->RemoveShape(shape2));
- EXPECT_FALSE(transform_->RemoveShape(shape1));
-}
-
-TEST_F(TransformBasic,
- ShouldReplaceShapeArrayWithThoseInArrayPassedToSetShapes) {
- Shape* shape1 = pack()->Create<Shape>();
- Shape* shape2 = pack()->Create<Shape>();
- transform_->AddShape(shape1);
-
- ShapeArray shape_array;
- shape_array.push_back(shape2);
-
- transform_->SetShapes(shape_array);
- shape_array = transform_->GetShapes();
-
- EXPECT_EQ(1U, shape_array.size());
- EXPECT_EQ(shape2, shape_array[0]);
-}
-
-TEST_F(TransformBasic, CreateGroupDrawElements) {
- // Setup a basic hierarchy
- SetupSimpleTree();
-
- Shape* shape1 = pack()->Create<Shape>();
- Shape* shape2 = pack()->Create<Shape>();
- Primitive* primitive1 = pack()->Create<Primitive>();
- Primitive* primitive2 = pack()->Create<Primitive>();
- Material* material = pack()->Create<Material>();
- ASSERT_TRUE(shape1 != NULL);
- ASSERT_TRUE(shape2 != NULL);
- ASSERT_TRUE(material != NULL);
- ASSERT_TRUE(primitive1 != NULL);
- ASSERT_TRUE(primitive2 != NULL);
-
- transform_->AddShape(shape1);
- transform2_->AddShape(shape2);
- primitive1->SetOwner(shape1);
- primitive2->SetOwner(shape2);
-
- transform2_->CreateDrawElements(pack(), NULL);
- transform2_->CreateDrawElements(pack(), material);
-
- // Check that they got created correctly.
- EXPECT_EQ(primitive1->GetDrawElementRefs().size(), 2U);
- EXPECT_EQ(primitive2->GetDrawElementRefs().size(), 2U);
-}
-
-TEST_F(TransformBasic, GetConcreteInputsForParamGetConcreteOutputsForParam) {
- // Setup a basic hierarchy
- SetupSimpleTree();
-
- Transform* t3 = pack()->Create<Transform>();
- Transform* t4 = pack()->Create<Transform>();
- transform2_->SetParent(t3);
- t3->SetParent(t4);
-
- // t4->t3->transform2_->transform_
-
- Param* t1_local_matrix = transform_->GetUntypedParam(
- Transform::kLocalMatrixParamName);
- Param* t2_local_matrix = transform2_->GetUntypedParam(
- Transform::kLocalMatrixParamName);
- Param* t3_local_matrix = t3->GetUntypedParam(
- Transform::kLocalMatrixParamName);
- Param* t4_local_matrix = t4->GetUntypedParam(
- Transform::kLocalMatrixParamName);
- Param* t1_world_matrix = transform_->GetUntypedParam(
- Transform::kWorldMatrixParamName);
- Param* t2_world_matrix = transform2_->GetUntypedParam(
- Transform::kWorldMatrixParamName);
- Param* t3_world_matrix = t3->GetUntypedParam(
- Transform::kWorldMatrixParamName);
- Param* t4_world_matrix = t4->GetUntypedParam(
- Transform::kWorldMatrixParamName);
-
- ParamVector params;
-
- // Tests GetConcreteInputsForParam (because GetInputsForParam calles
- // GetConcreteInputsForParam)
- t1_world_matrix->GetInputs(&params);
- EXPECT_EQ(params.size(), 7U);
- EXPECT_TRUE(ParamInParams(t1_local_matrix, params));
- EXPECT_TRUE(ParamInParams(t2_world_matrix, params));
- EXPECT_TRUE(ParamInParams(t2_local_matrix, params));
- EXPECT_TRUE(ParamInParams(t3_world_matrix, params));
- EXPECT_TRUE(ParamInParams(t3_local_matrix, params));
- EXPECT_TRUE(ParamInParams(t4_world_matrix, params));
- EXPECT_TRUE(ParamInParams(t4_local_matrix, params));
-
- t1_local_matrix->GetInputs(&params);
- EXPECT_EQ(params.size(), 0U);
-
- // Tests GetConcreteOutputsForParam (because GetOutputsForParam calles
- // GetConcreteOutputsForParam)
- t4_local_matrix->GetOutputs(&params);
- EXPECT_EQ(params.size(), 4U);
- EXPECT_TRUE(ParamInParams(t1_world_matrix, params));
- EXPECT_TRUE(ParamInParams(t2_world_matrix, params));
- EXPECT_TRUE(ParamInParams(t3_world_matrix, params));
- EXPECT_TRUE(ParamInParams(t4_world_matrix, params));
-
- t4_world_matrix->GetOutputs(&params);
- EXPECT_EQ(params.size(), 3U);
- EXPECT_TRUE(ParamInParams(t1_world_matrix, params));
- EXPECT_TRUE(ParamInParams(t2_world_matrix, params));
- EXPECT_TRUE(ParamInParams(t3_world_matrix, params));
-}
-
-// Tests the param system handles implicit parameter relationships.
-TEST_F(TransformBasic, ImplicitInputs) {
- // Setup a basic hierarchy
- SetupSimpleTree();
-
- Transform* t3 = pack()->Create<Transform>();
- Transform* t4 = pack()->Create<Transform>();
- transform2_->SetParent(t3);
- t3->SetParent(t4);
-
- Param::Ref source_param = Param::Ref(new ParamCounter(g_service_locator));
- ASSERT_FALSE(source_param.IsNull());
-
- // t4->t3->transform2_->transform_
-
- Param* t1_local_matrix = transform_->GetUntypedParam(
- Transform::kLocalMatrixParamName);
- EXPECT_TRUE(t1_local_matrix != NULL);
- Param* t2_local_matrix = transform2_->GetUntypedParam(
- Transform::kLocalMatrixParamName);
- EXPECT_TRUE(t2_local_matrix != NULL);
- Param* t3_local_matrix = t3->GetUntypedParam(
- Transform::kLocalMatrixParamName);
- Param* t4_local_matrix = t4->GetUntypedParam(
- Transform::kLocalMatrixParamName);
- EXPECT_TRUE(t4_local_matrix != NULL);
- ParamMatrix4* t1_world_matrix = transform_->GetParam<ParamMatrix4>(
- Transform::kWorldMatrixParamName);
- Param* t2_world_matrix = transform2_->GetUntypedParam(
- Transform::kWorldMatrixParamName);
- Param* t3_world_matrix = t3->GetUntypedParam(
- Transform::kWorldMatrixParamName);
- Param* t4_world_matrix = t4->GetUntypedParam(
- Transform::kWorldMatrixParamName);
-
- // Check that they start as cachable.
- EXPECT_TRUE(t4_world_matrix->cachable());
- EXPECT_TRUE(t3_world_matrix->cachable());
- EXPECT_TRUE(t2_world_matrix->cachable());
- EXPECT_TRUE(t1_world_matrix->cachable());
-
- // check that all implicitly related params get marked as non-cachable if
- // the source is not cachacble.
- EXPECT_TRUE(t4_world_matrix->Bind(source_param));
- EXPECT_FALSE(t4_world_matrix->cachable());
- EXPECT_FALSE(t3_world_matrix->cachable());
- EXPECT_FALSE(t2_world_matrix->cachable());
- EXPECT_FALSE(t1_world_matrix->cachable());
-
- // Check that each time we ask for the value it changes.
- Matrix4 value1(t1_world_matrix->value());
- Matrix4 value2(t1_world_matrix->value());
- EXPECT_FALSE(MatricesAreSame(value1, value2));
-
- // Check that if we disconnect in the middle some of them become cachable.
- transform2_->SetParent(NULL);
- EXPECT_FALSE(t4_world_matrix->cachable());
- EXPECT_FALSE(t3_world_matrix->cachable());
- EXPECT_TRUE(t2_world_matrix->cachable());
- EXPECT_TRUE(t1_world_matrix->cachable());
-
- // Check if we disconnect the bottom the rest become cachable.
- source_param->UnbindOutputs();
- EXPECT_TRUE(t4_world_matrix->cachable());
- EXPECT_TRUE(t3_world_matrix->cachable());
- EXPECT_TRUE(t2_world_matrix->cachable());
- EXPECT_TRUE(t1_world_matrix->cachable());
-
- // Check if we connect to a middle one the correct ones become cachable.
- transform2_->SetParent(t3);
- EXPECT_TRUE(t3_local_matrix->Bind(source_param));
- EXPECT_TRUE(t4_world_matrix->cachable());
- EXPECT_FALSE(t3_world_matrix->cachable());
- EXPECT_FALSE(t2_world_matrix->cachable());
- EXPECT_FALSE(t1_world_matrix->cachable());
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/transformation_context.cc b/o3d/core/cross/transformation_context.cc
deleted file mode 100644
index c3cc1ca..0000000
--- a/o3d/core/cross/transformation_context.cc
+++ /dev/null
@@ -1,40 +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 "core/cross/transformation_context.h"
-
-namespace o3d {
-
-const InterfaceId TransformationContext::kInterfaceId =
- InterfaceTraits<TransformationContext>::kInterfaceId;
-
-} // namespace o3d
diff --git a/o3d/core/cross/transformation_context.h b/o3d/core/cross/transformation_context.h
deleted file mode 100644
index 18d7f6b..0000000
--- a/o3d/core/cross/transformation_context.h
+++ /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.
- */
-
-
-#ifndef O3D_CORE_CROSS_TRANSFORMATION_CONTEXT_H_
-#define O3D_CORE_CROSS_TRANSFORMATION_CONTEXT_H_
-
-#include "core/cross/service_implementation.h"
-#include "core/cross/math_types.h"
-
-namespace o3d {
-
-// Holds the current transformation state, including the world, view and
-// projection matrices. TODO: it would be nice if this wasn't global state.
-class TransformationContext {
- public:
- static const InterfaceId kInterfaceId;
-
- explicit TransformationContext(ServiceLocator* service_locator)
- : service_(service_locator, this) {}
-
- // Retrieves the current world matrix.
- const Matrix4& world() const {
- return world_;
- }
-
- // Retrieves the current view matrix.
- const Matrix4& view() const {
- return view_;
- }
-
- // Retrieves the current projection matrix.
- const Matrix4& projection() const {
- return projection_;
- }
-
- // Retrieves the current view_projection matrix.
- const Matrix4& view_projection() const {
- return view_projection_;
- }
-
- // Retrieves the current world_view_projection matrix.
- const Matrix4& world_view_projection() const {
- return world_view_projection_;
- }
-
- // Sets the current world matrix.
- void set_world(const Matrix4& world) {
- world_ = world;
- }
-
- // Sets the current view matrix.
- void set_view(const Matrix4& view) {
- view_ = view;
- }
-
- // Sets the current projection matrix.
- void set_projection(const Matrix4& projection) {
- projection_ = projection;
- }
-
- // Sets the current view projection matrix.
- void set_view_projection(const Matrix4& view_projection) {
- view_projection_ = view_projection;
- }
-
- // Sets the current world view projection matrix.
- void set_world_view_projection(const Matrix4& world_view_projection) {
- world_view_projection_ = world_view_projection;
- }
-
- private:
- ServiceImplementation<TransformationContext> service_;
-
- // The following five matrices represent the transformation hierarchy during
- // drawing of the scene. These are set in the draw code prior to rendering,
- // so that StandardParamMatrix4s evaluate correctly.
-
- // The current world matrix.
- Matrix4 world_;
- // The current view matrix.
- Matrix4 view_;
- // The current projection matrix.
- Matrix4 projection_;
- // The current view_projection matrix.
- Matrix4 view_projection_;
- // The current world_view_projection matrix.
- Matrix4 world_view_projection_;
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_TRANSFORMATION_CONTEXT_H_
diff --git a/o3d/core/cross/tree_traversal.cc b/o3d/core/cross/tree_traversal.cc
deleted file mode 100644
index 5a08637..0000000
--- a/o3d/core/cross/tree_traversal.cc
+++ /dev/null
@@ -1,362 +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 definition of TreeTraveral.
-
-#include "core/cross/tree_traversal.h"
-#include "core/cross/shape.h"
-#include "core/cross/draw_list.h"
-#include "core/cross/transformation_context.h"
-#include "core/cross/renderer.h"
-#include "core/cross/error.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(TreeTraversal, RenderNode);
-
-const char* TreeTraversal::kTransformParamName =
- O3D_STRING_CONSTANT("transform");
-
-ObjectBase::Ref TreeTraversal::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new TreeTraversal(service_locator));
-}
-
-TreeTraversal::TreeTraversal(ServiceLocator* service_locator)
- : RenderNode(service_locator),
- transformation_context_(service_locator->
- GetService<TransformationContext>()) {
- RegisterParamRef(kTransformParamName, &transform_param_);
-}
-
-void TreeTraversal::RegisterDrawList(
- DrawList* draw_list,
- DrawContext* draw_context,
- bool reset) {
- DCHECK(draw_list);
- DCHECK(draw_context);
-
- draw_list_draw_context_info_map_[DrawList::Ref(draw_list)] =
- DrawContextInfo(draw_context, reset);
-}
-
-bool TreeTraversal::UnregisterDrawList(DrawList* draw_list) {
- return draw_list_draw_context_info_map_.erase(DrawList::Ref(draw_list)) > 0;
-}
-
-void TreeTraversal::Render(RenderContext* render_context) {
- // Reset the draw context infos array so we can rebuild it.
- draw_context_infos_by_draw_list_global_index_.clear();
-
- // Reset any DrawLists that need resetting and set the pass list flags.
- DrawListDrawContextInfoMap::iterator end(
- draw_list_draw_context_info_map_.end());
- for (DrawListDrawContextInfoMap::iterator iter(
- draw_list_draw_context_info_map_.begin());
- iter != end;
- ++iter) {
- DrawContextInfo& draw_context_info = iter->second;
- draw_context_info.ResetCullDepth();
-
- // Update the view projection matrix so we don't have to compute it more
- // than once later.
- draw_context_info.UpdateViewProjection();
-
- // If we are supposed to reset the DrawList reset it.
- DrawList* draw_list = iter->first;
- if (draw_context_info.reset()) {
- draw_list->Reset(draw_context_info.view(),
- draw_context_info.projection());
- }
-
- // Add it to draw_context_infos_by_draw_list_global_index_ array.
- unsigned global_index = draw_list->global_index();
- if (global_index >= draw_context_infos_by_draw_list_global_index_.size()) {
- draw_context_infos_by_draw_list_global_index_.insert(
- draw_context_infos_by_draw_list_global_index_.end(),
- global_index - draw_context_infos_by_draw_list_global_index_.size() + 1,
- NULL);
- }
- draw_context_infos_by_draw_list_global_index_[global_index] =
- &draw_context_info;
- }
-
- // At this point draw_context_infos_by_draw_list_global_index_ is big enough
- // to so that there is a directly accessable entry for each DrawList that this
- // TreeTraveral is filling out. In other words. If
- // draw_context_infos_by_draw_list_global_index_[
- // material->draw_list()->global_index()]
- // is non NULL then we want the DrawElement using that material.
-
- // Only after clearing any DrawLists do we bail out if there is no transform.
- Transform* transform1 = transform();
- if (!transform1) {
- return;
- }
-
- // Return if this transform is not visible.
- if (!transform1->visible()) {
- return;
- }
-
- // Now walk ourselves and all our children.
- WalkTransform(render_context,
- transform1,
- 0,
- static_cast<int>(draw_list_draw_context_info_map_.size()));
-}
-
-void TreeTraversal::SetStandardParameters(const Matrix4& world,
- const Matrix4& world_view_projection,
- DrawContextInfo* draw_context_info) {
- transformation_context_->set_world(world);
- transformation_context_->set_view(draw_context_info->view());
- transformation_context_->set_projection(draw_context_info->projection());
- transformation_context_->set_view_projection(
- draw_context_info->view_projection());
- transformation_context_->set_world_view_projection(world_view_projection);
-}
-
-void TreeTraversal::WalkTransform(RenderContext* render_context,
- Transform* transform,
- int depth,
- int num_non_culled_draw_contexts) {
- Renderer* renderer = render_context->renderer();
- Matrix4 world = transform->world_matrix();
- Matrix4 world_view_projection;
- bool cull_depth_was_set = false;
-
- renderer->IncrementTransformsProcessed();
-
- // Attempt to cull this transform for each draw_context
- DrawListDrawContextInfoMap::iterator end(
- draw_list_draw_context_info_map_.end());
- for (DrawListDrawContextInfoMap::iterator iter(
- draw_list_draw_context_info_map_.begin());
- iter != end;
- ++iter) {
- DrawList* draw_list = iter->first;
- bool have_world_view_projection = false;
-
- DrawContextInfo* draw_context_info =
- draw_context_infos_by_draw_list_global_index_[
- draw_list->global_index()];
- DLOG_ASSERT(draw_context_info);
-
- // Before we cull, if the cull or bounding box params have input
- // connections we need to setup the standard params.
- if (transform->ParamsUsedByTreeTraversalHaveInputConnections()) {
- Matrix4 world_view_projection =
- draw_context_info->view_projection() * world;
- have_world_view_projection = true;
- SetStandardParameters(world, world_view_projection, draw_context_info);
- }
-
- if (transform->cull()) {
- // Are we still processing this draw_context?
- //
- // The way this works is, draw_context_info->cull_depth is set to (-1) for
- // each DrawContextInfo at the start. As we descend the tree, assuming
- // transform->cull is true for a given transform, then if the cull_depth
- // is still (-1) we need to check this transform to see if its boundingbox
- // makes it culled. If that's true then we set the cull_depth to the depth
- // in the tree at which it was culled. That means at any time
- // draw_context_infos_by_draw_list_global_index[draw_list_global_index]->
- // cull_depth() >= 0 means that draw list has already been completely
- // culled.
- //
- // Each time we set a cull_depth we decrement
- // num_non_culled_draw_contexts. If it goes to zero then there is no point
- // going any deeper. The entire sub tree is culled for all draw_contexts.
- //
- // On the way back out IF the depth we are at matches a cull_depth then we
- // can clear it back to -1. To help this process we keep a flag that
- // whether or not we set 1 or more cull_depths in (cull_depth_was_set)
- if (!draw_context_info->IsCulled()) {
- if (!have_world_view_projection) {
- world_view_projection = draw_context_info->view_projection() * world;
- }
- // NOTE: Computing the world view projection matrix this way means
- // that no matter what, we only cull to that worldViewProjection.
- // In other words the user can not supply is own funky
- // worldViewProjection for culling using param binds where as he
- // can supply one for rendering.
- if (!transform->bounding_box().InFrustum(world_view_projection)) {
- renderer->IncrementTransformsCulled();
- --num_non_culled_draw_contexts;
- draw_context_info->set_cull_depth(depth);
- cull_depth_was_set = true;
- }
- }
- }
- }
-
- if (num_non_culled_draw_contexts > 0) {
- // Process Shapes
- {
- const ShapeRefArray& shapes = transform->GetShapeRefs();
- ShapeRefArray::size_type size = shapes.size();
- for (ShapeRefArray::size_type ii = 0; ii < size; ++ii) {
- AddInstance(render_context, shapes[ii], transform, world);
- }
- }
-
- // Process all the children
- {
- int children_depth = depth + 1;
- const TransformRefArray& children = transform->GetChildrenRefs();
- TransformRefArray::size_type size = children.size();
- for (TransformRefArray::size_type ii = 0; ii < size; ++ii) {
- if (children[ii]->visible()) {
- WalkTransform(render_context,
- children[ii],
- children_depth,
- num_non_culled_draw_contexts);
- }
- }
- }
- }
-
- // Reset any cull_depths at our depth
- if (cull_depth_was_set) {
- DrawListDrawContextInfoMap::iterator end(
- draw_list_draw_context_info_map_.end());
- for (DrawListDrawContextInfoMap::iterator iter(
- draw_list_draw_context_info_map_.begin());
- iter != end;
- ++iter) {
- DrawList* draw_list = iter->first;
-
- DrawContextInfo* draw_context_info =
- draw_context_infos_by_draw_list_global_index_[
- draw_list->global_index()];
- DLOG_ASSERT(draw_context_info);
-
- if (draw_context_info->cull_depth() == depth) {
- draw_context_info->ResetCullDepth();
- ++num_non_culled_draw_contexts;
- }
- }
- }
-}
-
-void TreeTraversal::AddInstance(RenderContext* render_context,
- Shape* shape,
- Transform* override,
- const Matrix4& world) {
- Renderer* renderer = render_context->renderer();
- const ElementRefArray& elements = shape->GetElementRefs();
- ElementRefArray::size_type num_elements = elements.size();
- for (ElementRefArray::size_type ii = 0; ii < num_elements; ++ii) {
- Element* element = elements[ii];
- const DrawElementRefArray& draw_elements =
- element->GetDrawElementRefs();
- DrawElementRefArray::const_iterator end(draw_elements.end());
- for (DrawElementRefArray::const_iterator iter(draw_elements.begin());
- iter != end;
- ++iter) {
- renderer->IncrementDrawElementsProcessed();
- DrawElement* draw_element = iter->Get();
-
- // We MUST get the cache BEFORE culling so that we usually get the same
- // cache for the same draw element.
- ParamCache* param_cache =
- override->param_cache_manager().GetNextCache(
- render_context->renderer());
-
- Material* material = draw_element->material();
- if (!material) {
- material = element->material();
- }
-
- if (!material) {
- continue;
- }
-
- if (!material->effect()) {
- continue;
- }
-
- DrawList* draw_list = material->draw_list();
- if (!draw_list) {
- continue;
- }
-
- // Is this pass list something we want?
- if (draw_list->global_index() >=
- draw_context_infos_by_draw_list_global_index_.size()) {
- continue;
- }
-
- DrawContextInfo* draw_context_info =
- draw_context_infos_by_draw_list_global_index_[
- draw_list->global_index()];
- if (draw_context_info && !draw_context_info->IsCulled()) {
- Matrix4 world_view_projection(
- draw_context_info->view_projection() * world);
- // Yes it is. Should we attempt to cull it?
- // Before we cull, if the cull or bounding box params have input
- // connections we need to setup the standard params.
- if (element->ParamsUsedByTreeTraversalHaveInputConnections()) {
- SetStandardParameters(world,
- world_view_projection,
- draw_context_info);
- }
-
- if (element->cull()) {
- // NOTE: Computing the world view projection matrix this way means
- // that no matter what, we only cull to that worldViewProjection.
- // In other words the user can not supply is own funky
- // worldViewProjection for culling using param binds.
- if (!element->bounding_box().InFrustum(world_view_projection)) {
- renderer->IncrementDrawElementsCulled();
- continue;
- }
- }
- draw_list->AddDrawElement(draw_element,
- element,
- material,
- override,
- param_cache,
- world,
- world_view_projection);
- }
- }
- }
-}
-
-void TreeTraversal::DrawContextInfo::UpdateViewProjection() {
- view_ = draw_context_->view();
- projection_ = draw_context_->projection();
- view_projection_ = projection_ * view_;
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/tree_traversal.h b/o3d/core/cross/tree_traversal.h
deleted file mode 100644
index 202c107..0000000
--- a/o3d/core/cross/tree_traversal.h
+++ /dev/null
@@ -1,216 +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 declaration of TreeTraversal.
-
-#ifndef O3D_CORE_CROSS_TREE_TRAVERSAL_H_
-#define O3D_CORE_CROSS_TREE_TRAVERSAL_H_
-
-#include <map>
-#include <vector>
-#include "core/cross/transform.h"
-#include "core/cross/render_node.h"
-#include "core/cross/draw_context.h"
-
-namespace o3d {
-
-class TransformationContext;
-class Shape;
-
-// A TreeTraversal has multiple DrawLists registered with it. Each DrawList has
-// a DrawContext registered with it. At render time the TreeTraversal walks the
-// transform tree from the transform it's pointing at and for each drawable it
-// finds who's matertial matches one of its registered DrawLists it adds that
-// drawable to that DrawList.
-class TreeTraversal : public RenderNode {
- public:
- typedef SmartPointer<TreeTraversal> Ref;
-
- // Names of TreeTraversal Params.
- static const char* kTransformParamName;
-
- // Returns the Transform the TreeTraversal will start traversing from.
- Transform* transform() const {
- return transform_param_->value();
- }
-
- // Set the Transform the TreeTraversal will start traversing from.
- void set_transform(Transform *transform) {
- transform_param_->set_value(transform);
- }
-
- virtual void Render(RenderContext *render_context);
-
- // Registers a DrawList with this TreeTraversal so that when this
- // TreeTraversal traverses its tree materials that use this DrawList will be
- // added though possibly culled by the view frustum of the DrawContext.
- // Note: passing in the same passlist more than once will override the
- // previous drawContext/reset settings for that passlist.
- // Parameters:
- // draw_list: DrawList to register.
- // draw_context: DrawContext to use with the DrawList.
- // reset: true if you want the pass list reset before traversing.
- void RegisterDrawList(DrawList* draw_list,
- DrawContext* draw_context,
- bool reset);
-
- // Unregisters a DrawList with this TreeTraversal.
- // Parameters:
- // draw_list: DrawList to unregister.
- // Returns:
- // true if unregistered. false if this draw_list was not registered.
- bool UnregisterDrawList(DrawList* draw_list);
-
- private:
- explicit TreeTraversal(ServiceLocator* service_locator);
-
- // DrawContextInfo is used to keep track of some info we need per draw context
- // registered with this TreeTraversal.
- class DrawContextInfo {
- public:
- // This has to exist so std::map operator[] can work but an uninitialized
- // DrawContextInfo is never direcly accessed.
- DrawContextInfo() { }
-
- DrawContextInfo(DrawContext* draw_context, bool reset)
- : draw_context_(DrawContext::Ref(draw_context)),
- reset_(reset) {
- }
-
- DrawContext* draw_context() const {
- return draw_context_;
- }
-
- bool reset() const {
- return reset_;
- }
-
- const Matrix4& view() const {
- return view_;
- }
-
- const Matrix4& projection() const {
- return projection_;
- }
-
- const Matrix4& view_projection() const {
- return view_projection_;
- }
-
- int cull_depth() const {
- return cull_depth_;
- }
-
- void set_cull_depth(int depth) {
- cull_depth_ = depth;
- }
-
- void ResetCullDepth() {
- cull_depth_ = -1;
- }
-
- bool IsCulled() {
- return cull_depth_ >= 0;
- }
-
- // Updates the view, projection and viewProjection based on the DrawContext.
- void UpdateViewProjection();
-
- private:
- DrawContext::Ref draw_context_;
- bool reset_;
- int cull_depth_;
- Matrix4 view_;
- Matrix4 projection_;
- Matrix4 view_projection_;
- };
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // Adds an instance of a Shape to the DrawList it's material requests if
- // we are gathering stuff for that DrawList.
- // Parameters:
- // render_context: Rendering info.
- // shape: Shape to add to list.
- // override: Transform used to override params and store param cache.
- // world_matrix: The worldMatrix for this Shape.
- void AddInstance(RenderContext* render_context,
- Shape* shape,
- Transform* override,
- const Matrix4& world_matrix);
-
- // Walks a transform, optionally attempts to cull it. If not culled, walks its
- // children and attempts to add its Shapes to the corresponding registered
- // DrawLists.
- // Parameters:
- // render_context: Rendering info.
- // transform: Transform to walk.
- // depth: depth we've walked so far.
- // num_non_culled_draw_contexts: How many contexts we have left to process.
- void WalkTransform(RenderContext* render_context,
- Transform* transform,
- int depth,
- int num_non_culled_draw_contexts);
-
- // Sets the standard parameters on the client so that Param chains might
- // get valid values.
- void SetStandardParameters(const Matrix4& world,
- const Matrix4& world_view_projection,
- DrawContextInfo* draw_context_info);
-
- // The Transform that we start to traverse.
- ParamTransform::Ref transform_param_;
-
- // The DrawList we will use when traversing and which context to apply to
- // them while traversing.
- typedef std::map<DrawList::Ref, DrawContextInfo> DrawListDrawContextInfoMap;
- DrawListDrawContextInfoMap draw_list_draw_context_info_map_;
-
- // An Array of pointers to DrawContextInfos indexed by DrawList::global_index
- // both for quick lookup AND the corresponding entry is NULL then we are not
- // processing that DrawList.
- typedef std::vector<DrawContextInfo*> DrawContextInfoArray;
- DrawContextInfoArray draw_context_infos_by_draw_list_global_index_;
-
- TransformationContext* transformation_context_;
-
- bool standard_params_have_been_set_; // true if standard params
- // have been set.
-
- O3D_DECL_CLASS(TreeTraversal, RenderNode);
- DISALLOW_COPY_AND_ASSIGN(TreeTraversal);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_TREE_TRAVERSAL_H_
diff --git a/o3d/core/cross/tree_traversal_test.cc b/o3d/core/cross/tree_traversal_test.cc
deleted file mode 100644
index 1cb1f8b..0000000
--- a/o3d/core/cross/tree_traversal_test.cc
+++ /dev/null
@@ -1,99 +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 implements unit tests for class TreeTraveral.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/tree_traversal.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/transformation_context.h"
-#include "core/cross/draw_list_manager.h"
-
-namespace o3d {
-
-class TreeTraversalTest : public testing::Test {
- protected:
- TreeTraversalTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- TransformationContext* transformation_context_;
- DrawListManager* draw_list_manager_;
- Pack *pack_;
-};
-
-void TreeTraversalTest::SetUp() {
- transformation_context_ = new TransformationContext(g_service_locator);
- draw_list_manager_ = new DrawListManager(g_service_locator);
- pack_ = object_manager_->CreatePack();
-}
-
-void TreeTraversalTest::TearDown() {
- pack_->Destroy();
- delete draw_list_manager_;
- delete transformation_context_;
-}
-
-TEST_F(TreeTraversalTest, Basic) {
- TreeTraversal* tree_traversal = pack()->Create<TreeTraversal>();
- // Check that tree_traversal got created.
- ASSERT_TRUE(tree_traversal != NULL);
-
- DrawList* draw_list1 = pack()->Create<DrawList>();
- DrawList* draw_list2 = pack()->Create<DrawList>();
- DrawList* draw_list3 = pack()->Create<DrawList>();
- DrawContext* draw_context = pack()->Create<DrawContext>();
- ASSERT_TRUE(draw_list1 != NULL);
- ASSERT_TRUE(draw_list2 != NULL);
- ASSERT_TRUE(draw_list3 != NULL);
- ASSERT_TRUE(draw_context != NULL);
-
- // Check that we can add and remove them
- tree_traversal->RegisterDrawList(draw_list1, draw_context, true);
- tree_traversal->RegisterDrawList(draw_list2, draw_context, true);
-
- EXPECT_FALSE(tree_traversal->UnregisterDrawList(draw_list3));
- EXPECT_TRUE(tree_traversal->UnregisterDrawList(draw_list1));
- EXPECT_FALSE(tree_traversal->UnregisterDrawList(draw_list1));
- EXPECT_TRUE(tree_traversal->UnregisterDrawList(draw_list2));
- EXPECT_FALSE(tree_traversal->UnregisterDrawList(draw_list3));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/types.h b/o3d/core/cross/types.h
deleted file mode 100644
index 791410c..0000000
--- a/o3d/core/cross/types.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 of common data types and conversion
-// methods used by the O3D codebase.
-
-#ifndef O3D_CORE_CROSS_TYPES_H_
-#define O3D_CORE_CROSS_TYPES_H_
-
-#include <assert.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <build/build_config.h>
-#ifdef OS_WIN
-#include <windows.h>
-#endif
-
-#include <string>
-
-#include "base/basictypes.h"
-#include "base/logging.h"
-#include "base/string_util.h"
-#include "base/utf_string_conversions.h"
-#include "core/cross/math_types.h"
-#include "core/cross/float_n.h"
-
-// Defines ---------------------------------
-#ifndef NDEBUG
-#define O3D_ASSERT(x) assert((x))
-#else
-#define O3D_ASSERT(x)
-#endif
-// Add debug logging for the first N occurrences.
-// Add debug logging for every N occurrences.
-// TODO: delete this when logging.h is updated to include this
-// functionality.
-#ifdef NDEBUG
-#define DONT_LOG while (false) NDEBUG_EAT_STREAM_PARAMETERS
-#define DLOG_FIRST_N(severity, n) DONT_LOG
-
-#define DLOG_EVERY_N(severity, n) DONT_LOG
-#else // NDEBUG
-#define LOG_OCCURRENCES occurrences_ ## __LINE__
-#define LOG_OCCURRENCES_MOD_N occurrences_mod_n_ ## __LINE__
-// WARNING: DO NOT USE THIS IN A CONDITIONAL STATEMENT WITHOUT BRACES AROUND
-// DLOG_FIRST_N AND ITS PARAMETERS (INCLUDING THE COMMENT STREAM)
-// "severity.stream()" must be the last item in the macro in order to actually
-// log the stream properly. Hence, the reason it must also be included in
-// the braces as noted above.
-#define SOME_KIND_OF_LOG_FIRST_N(severity, n) \
- static int LOG_OCCURRENCES = 0; \
- if (LOG_OCCURRENCES <= n) \
- ++LOG_OCCURRENCES; \
- if (LOG_OCCURRENCES <= n) \
- COMPACT_GOOGLE_LOG_ ## severity.stream()
-
-#define SOME_KIND_OF_LOG_EVERY_N(severity, n) \
- static int LOG_OCCURRENCES = 0; \
- static int LOG_OCCURRENCES_MOD_N = 0; \
- ++LOG_OCCURRENCES; \
- if (++LOG_OCCURRENCES_MOD_N > n) \
- LOG_OCCURRENCES_MOD_N -= n; \
- if (LOG_OCCURRENCES_MOD_N == 1) \
- COMPACT_GOOGLE_LOG_ ## severity.stream()
-
-#define DLOG_FIRST_N(severity, n) \
- SOME_KIND_OF_LOG_FIRST_N(severity, (n))
-
-#define DLOG_EVERY_N(severity, n) \
- SOME_KIND_OF_LOG_EVERY_N(severity, (n))
-#endif // NDEBUG
-
-// Endian-ness for machine architecture
-// Either IS_LITTLE_ENDIAN or IS_BIG_ENDIAN should be defined
-
-// For now we build for x86 Win/Mac/Linux
-// We can add more sophisticated per-platform #defines as necessary here
-#define IS_LITTLE_ENDIAN 1
-
-// When you upcast (that is, cast a pointer from type Foo to type
-// SuperclassOfFoo), it's fine to use implicit_cast<>, since upcasts
-// always succeed. When you downcast (that is, cast a pointer from
-// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
-// how do you know the pointer is really of type SubclassOfFoo? It
-// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, when
-// you downcast, you should use this template.
-//
-// NOTE: We used to do a dynamic_cast in debug mode to make sure it
-// was the right type, but now that RTTI is completely turned off, we
-// just do the implicit_cast compile-time check.
-//
-// Use it like this: down_cast<T*>(foo);
-
-template<typename To, typename From>
-inline To down_cast(From* f) { // Defined as From* so we only accept pointers.
- // Ensures that To is a sub-type of From *. This test is here only
- // for compile-time type checking, and has no overhead in an
- // optimized build at run-time, as it will be optimized away
- // completely.
- if (false) {
- implicit_cast<From*, To>(0);
- }
-
- return static_cast<To>(f);
-}
-
-namespace o3d {
-
-// String
-//
-typedef std::string String;
-
-// ID used to uniquely identify objects
-//
-typedef unsigned int Id;
-
-}; // namespace o3d
-
-#endif // O3D_CORE_CROSS_TYPES_H_
diff --git a/o3d/core/cross/vector_map.h b/o3d/core/cross/vector_map.h
deleted file mode 100644
index 7e3a228..0000000
--- a/o3d/core/cross/vector_map.h
+++ /dev/null
@@ -1,382 +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 definition of vector_map, a replacement of std::map
-// that is faster for certain workloads.
-
-#ifndef O3D_CORE_CROSS_VECTOR_MAP_H_
-#define O3D_CORE_CROSS_VECTOR_MAP_H_
-
-#include <algorithm>
-#include <vector>
-#include <utility>
-#include "base/cross/std_functional.h"
-
-namespace o3d {
-
-// Implementation of a map, but with a sorted std::vector storage instead of a
-// RB tree. It makes insertions O(n) but iterations over the data faster than a
-// map (O(n) but smaller constant than std::map). Look-ups are O(log(n)),
-// comparable to std::map. It's also a lot less memory intensive.
-
-// NOTE: since this is meant to be a drop-in replacement for std::map, it uses
-// the STL naming conventions.
-
-// NOTE: The Key needs to be Assignable so that value_type can be a
-// pair<Key, Data> instead of a pair<const Key, Data> so that it can be put in a
-// vector. std::map doesn't have that restriction. This is somewhat important
-// because that means iterators return a pair where the key is mutable,
-// but assigning the key could mess up the sorting of the vector. So don't do
-// that (the compiler won't protect you like it would in a std::map).
-// TODO: see if that could be made safer without adding extra copies.
-template <typename Key, typename Data, typename Compare = std::less<Key> >
-class vector_map {
- public:
- typedef Key key_type;
- typedef Data data_type;
- typedef Compare key_compare;
-
- typedef std::pair<key_type, data_type> value_type;
-
- class value_compare {
- public:
- explicit value_compare(const key_compare &compare) : compare_(compare) {}
- bool operator()(const value_type &left, const value_type &right) {
- return compare_(left.first, right.first);
- }
- private:
- key_compare compare_;
- };
-
- typedef std::vector<value_type> VectorType;
- typedef typename VectorType::size_type size_type;
-
- class const_iterator;
-
- class iterator {
- public:
- typedef typename VectorType::iterator::iterator_category iterator_category;
- typedef typename VectorType::iterator::value_type value_type;
- typedef typename VectorType::iterator::difference_type difference_type;
- typedef typename VectorType::iterator::pointer pointer;
- typedef typename VectorType::iterator::reference reference;
-
- iterator() : vector_iterator_() {}
- iterator(const iterator &other)
- : vector_iterator_(other.vector_iterator_) {}
-
- iterator& operator++() {
- ++vector_iterator_;
- return *this;
- }
-
- iterator operator++(int unused) {
- iterator old = *this;
- ++*this;
- return old;
- }
-
- value_type* operator->() const {
- return vector_iterator_.operator->();
- }
-
- value_type& operator*() const {
- return *vector_iterator_;
- }
-
- bool operator==(const iterator& other) const {
- return vector_iterator_ == other.vector_iterator_;
- }
-
- bool operator!=(const iterator& other) const {
- return !(*this == other);
- }
-
- bool operator==(const const_iterator& other) const;
- bool operator!=(const const_iterator& other) const;
-
- private:
- friend class vector_map;
- friend class const_iterator;
- explicit iterator(const typename VectorType::iterator &it)
- : vector_iterator_(it) {}
-
- typename VectorType::iterator vector_iterator_;
- };
-
- class const_iterator {
- public:
- typedef typename VectorType::const_iterator::iterator_category
- iterator_category;
- typedef typename VectorType::const_iterator::value_type value_type;
- typedef typename VectorType::const_iterator::difference_type
- difference_type;
- typedef typename VectorType::const_iterator::pointer pointer;
- typedef typename VectorType::const_iterator::reference reference;
-
- const_iterator() : vector_iterator_() {}
-
- const_iterator(const const_iterator &other)
- : vector_iterator_(other.vector_iterator_) {}
-
- const_iterator(const iterator &other) // NOLINT - we want the implicit cast
- : vector_iterator_(other.vector_iterator_) {}
-
- const_iterator& operator++() {
- ++vector_iterator_;
- return *this;
- }
-
- const_iterator operator++(int unused) {
- const_iterator old = *this;
- ++*this;
- return old;
- }
-
- const value_type* operator->() const {
- return vector_iterator_.operator->();
- }
-
- const value_type& operator*() const {
- return *vector_iterator_;
- }
-
- bool operator==(const const_iterator& other) const {
- return vector_iterator_ == other.vector_iterator_;
- }
-
- bool operator!=(const const_iterator& other) const {
- return !(*this == other);
- }
-
- private:
- friend class vector_map;
- explicit const_iterator(const typename VectorType::const_iterator &it)
- : vector_iterator_(it) {}
-
- typename VectorType::const_iterator vector_iterator_;
- };
- // TODO: add reverse iterators.
-
- vector_map() {}
-
- explicit vector_map(const key_compare &compare)
- : compare_(compare) {}
-
- vector_map(const vector_map &other)
- : vector_(other.vector_),
- compare_(other.compare_) {}
-
- template <class InputIterator>
- vector_map(InputIterator f, InputIterator l) {
- insert(f, l);
- }
-
- template <class InputIterator>
- vector_map(InputIterator f, InputIterator l, const key_compare &compare)
- : compare_(compare) {
- insert(f, l);
- }
-
- vector_map &operator=(const vector_map &other) {
- vector_ = other.vector_;
- compare_ = other.compare_;
- return *this;
- }
-
- void swap(vector_map &other) {
- vector_.swap(other.vector_);
- compare_.swap(other.compare_);
- }
-
- key_compare key_comp() const { return compare_; }
- value_compare value_comp() const { return value_compare(key_comp()); }
-
- iterator begin() { return iterator(vector_.begin()); }
- const_iterator begin() const { return const_iterator(vector_.begin()); }
- iterator end() { return iterator(vector_.end()); }
- const_iterator end() const { return const_iterator(vector_.end()); }
-
- size_type size() const { return vector_.size(); }
- size_type max_size() const { return vector_.max_size(); }
- bool empty() const { return vector_.empty(); }
-
- std::pair<iterator, bool> insert(const value_type& x) {
- typename VectorType::iterator it =
- std::lower_bound(vector_.begin(), vector_.end(), x, value_comp());
- if ((it == vector_.end()) || (x.first != it->first)) {
- // Didn't find the key. Insert an element.
- return std::make_pair(iterator(vector_.insert(it, x)), true);
- } else {
- // Found the key.
- return std::make_pair(iterator(it), false);
- }
- }
-
- iterator insert(iterator pos, const value_type& x) {
- // TODO: take pos into account.
- return insert(x).first;
- }
-
- template <class InputIterator>
- void insert(InputIterator f, InputIterator l) {
- if (empty()) {
- // If the vector is empty, we can add all elements and then sort in the
- // end. It should be faster.
- vector_.insert(vector_.begin(), f, l);
- std::sort(vector_.begin(), vector_.end(), value_comp());
- } else {
- for (; f != l; ++f) {
- insert(*f);
- }
- }
- }
-
- void erase(iterator pos) {
- vector_.erase(pos.vector_iterator_);
- }
-
- size_type erase(const key_type& k) {
- iterator it = find(k);
- if (it != end()) {
- erase(it);
- return 1;
- } else {
- return 0;
- }
- }
-
- void erase(iterator first, iterator last) {
- vector_.erase(first.vector_iterator_, last.vector_iterator_);
- }
-
- void clear() {
- vector_.clear();
- }
-
- iterator find(const key_type& k) {
- iterator it = lower_bound(k);
- if ((it == end()) || (k != it->first)) {
- return end();
- } else {
- return it;
- }
- }
-
- const_iterator find(const key_type& k) const {
- const_iterator it = lower_bound(k);
- if ((it == end()) || (k != it->first)) {
- return end();
- } else {
- return it;
- }
- }
-
- const size_type count(const key_type& k) const {
- return (find(k) == end()) ? 0 : 1;
- }
-
- iterator lower_bound(const key_type& k) {
- // TODO: Is it possible to use lower_bound without having to
- // construct a data_type ?
- value_type x(k, data_type());
- typename VectorType::iterator it =
- std::lower_bound(vector_.begin(), vector_.end(), x, value_comp());
- return iterator(it);
- }
-
- const_iterator lower_bound(const key_type& k) const {
- // TODO: Is it possible to use lower_bound without having to
- // construct a data_type ?
- value_type x(k, data_type());
- typename VectorType::const_iterator it =
- std::lower_bound(vector_.begin(), vector_.end(), x, value_comp());
- return const_iterator(it);
- }
-
- iterator upper_bound(const key_type& k) {
- // TODO: Is it possible to use upper_bound without having to
- // construct a data_type ?
- value_type x(k, data_type());
- typename VectorType::iterator it =
- std::upper_bound(vector_.begin(), vector_.end(), x, value_comp());
- return iterator(it);
- }
-
- const_iterator upper_bound(const key_type& k) const {
- // TODO: Is it possible to use upper_bound without having to
- // construct a data_type ?
- value_type x(k, data_type());
- typename VectorType::const_iterator it =
- std::upper_bound(vector_.begin(), vector_.end(), x, value_comp());
- return const_iterator(it);
- }
-
- std::pair<iterator, iterator> equal_range(const key_type& k) {
- iterator low = lower_bound(k);
- iterator up = low;
- // We have at most 1 element.
- if (up != end() && up->first == k)
- ++up;
- return std::make_pair(low, up);
- }
-
- std::pair<const_iterator, const_iterator> equal_range(
- const key_type& k) const {
- const_iterator low = lower_bound(k);
- const_iterator up = low;
- // We have at most 1 element.
- if (up != end() && up->first == k)
- ++up;
- return std::make_pair(low, up);
- }
-
- data_type &operator[](const key_type &k) {
- std::pair<iterator, bool> pos = insert(value_type(k, data_type()));
- return pos.first->second;
- }
-
- bool operator==(const vector_map &other) const {
- return vector_ == other.vector_;
- }
-
- bool operator<(const vector_map &other) const {
- return vector_ < other.vector_;
- }
- private:
- VectorType vector_;
- key_compare compare_;
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_VECTOR_MAP_H_
diff --git a/o3d/core/cross/vector_map_test.cc b/o3d/core/cross/vector_map_test.cc
deleted file mode 100644
index 7316a9c..0000000
--- a/o3d/core/cross/vector_map_test.cc
+++ /dev/null
@@ -1,258 +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 tests for vector_map.
-
-#include <map>
-#include "tests/common/win/testing_common.h"
-#include "core/cross/vector_map.h"
-
-namespace o3d {
-
-// Tests basic map behavior.
-TEST(VectorMapTest, General) {
- vector_map<int, int> the_map;
-
- EXPECT_TRUE(the_map.empty());
-
- the_map[0] = 5;
-
- EXPECT_FALSE(the_map.empty());
- EXPECT_EQ(the_map.size(), 1U);
-
- the_map[9] = 2;
-
- EXPECT_FALSE(the_map.empty());
- EXPECT_EQ(the_map.size(), 2U);
-
- EXPECT_EQ(the_map[9], 2);
- EXPECT_EQ(the_map[0], 5);
-
- vector_map<int, int>::iterator iter(the_map.begin());
- ASSERT_TRUE(iter != the_map.end());
- EXPECT_EQ(iter->first, 0);
- EXPECT_EQ(iter->second, 5);
- ++iter;
- ASSERT_TRUE(iter != the_map.end());
- EXPECT_EQ((*iter).first, 9);
- EXPECT_EQ((*iter).second, 2);
- ++iter;
- EXPECT_TRUE(iter == the_map.end());
-
- the_map[8] = 23;
- the_map[1234] = 90;
- the_map[-5] = 6;
-
- EXPECT_EQ(the_map[ 9], 2);
- EXPECT_EQ(the_map[ 0], 5);
- EXPECT_EQ(the_map[1234], 90);
- EXPECT_EQ(the_map[ 8], 23);
- EXPECT_EQ(the_map[ -5], 6);
- EXPECT_EQ(the_map.size(), 5U);
- EXPECT_FALSE(the_map.empty());
-
- iter = the_map.begin();
- for (int i = 0; i < 5; i++) {
- EXPECT_TRUE(iter != the_map.end());
- ++iter;
- }
- EXPECT_TRUE(iter == the_map.end());
-
- const vector_map<int, int>& ref = the_map;
- EXPECT_TRUE(ref.find(1234) != the_map.end());
- EXPECT_TRUE(ref.find(5678) == the_map.end());
-}
-
-// Tests various insertion cases.
-TEST(VectorMapTest, Insert) {
- vector_map<int, int> the_map;
-
- for (int i = 1; i <= 10; ++i) {
- // insert an element
- std::pair<vector_map<int, int>::iterator, bool> ret;
- ret = the_map.insert(std::make_pair(i, 100*i));
- EXPECT_TRUE(ret.second);
- EXPECT_TRUE(ret.first == the_map.find(i));
- EXPECT_EQ(ret.first->first, i);
- EXPECT_EQ(ret.first->second, 100*i);
-
- // try to insert it again with different value, fails, but we still get an
- // iterator back with the original value.
- ret = the_map.insert(std::make_pair(i, -i));
- EXPECT_FALSE(ret.second);
- EXPECT_TRUE(ret.first == the_map.find(i));
- EXPECT_EQ(ret.first->first, i);
- EXPECT_EQ(ret.first->second, 100*i);
-
- // check the state of the map.
- for (int j = 1; j <= i; ++j) {
- vector_map<int, int>::iterator it = the_map.find(j);
- EXPECT_TRUE(it != the_map.end());
- EXPECT_EQ(it->first, j);
- EXPECT_EQ(it->second, j * 100);
- }
- EXPECT_EQ(static_cast<int>(the_map.size()), i);
- EXPECT_FALSE(the_map.empty());
- }
-}
-
-// Tests insertion of a range of values.
-TEST(VectorMapTest, InsertRange) {
- for (int elements = 0; elements <= 10; ++elements) {
- std::map<int, int> normal_map;
- for (int i = 1; i <= elements; ++i) {
- normal_map.insert(std::make_pair(i, 100*i));
- }
-
- vector_map<int, int> the_map;
- the_map.insert(normal_map.begin(), normal_map.end());
- EXPECT_EQ(normal_map.size(), the_map.size());
- for (int i = 1; i <= elements; ++i) {
- EXPECT_TRUE(the_map.find(i) != the_map.end());
- EXPECT_EQ(the_map.find(i)->first, i);
- EXPECT_EQ(the_map.find(i)->second, 100*i);
- }
- }
-}
-
-// Insert a new key and value into a map or hash_map.
-// If the key is not present in the map the key and value are
-// inserted, otherwise nothing happens. True indicates that an insert
-// took place, false indicates the key was already present.
-template <class Collection, class Key, class Value>
-bool InsertIfNotPresent(Collection * const collection,
- const Key& key, const Value& value) {
- std::pair<typename Collection::iterator, bool> ret =
- collection->insert(typename Collection::value_type(key, value));
- return ret.second;
-}
-
-// Tests InsertIfNotPresent map utility function.
-TEST(VectorMapTest, InsertIfNotPresent) {
- vector_map<int, int> the_map;
-
- for (int i = 1; i <= 10; ++i) {
- EXPECT_TRUE(InsertIfNotPresent(&the_map, i, 100*i));
- EXPECT_FALSE(InsertIfNotPresent(&the_map, i, -i));
-
- // check the state of the map.
- for (int j = 1; j <= i; ++j) {
- vector_map<int, int>::iterator it = the_map.find(j);
- ASSERT_TRUE(it != the_map.end());
- EXPECT_EQ(it->first, j);
- EXPECT_EQ(it->second, j * 100);
- }
- EXPECT_EQ(static_cast<int>(the_map.size()), i);
- EXPECT_FALSE(the_map.empty());
- }
-}
-
-// Tests various erase cases.
-TEST(VectorMapTest, Erase) {
- vector_map<std::string, int> the_map;
- vector_map<std::string, int>::iterator iter, iter1, iter2;
-
- the_map["monday"] = 1;
- the_map["tuesday"] = 2;
- the_map["wednesday"] = 3;
-
- EXPECT_EQ(the_map["monday" ], 1);
- EXPECT_EQ(the_map["tuesday" ], 2);
- EXPECT_EQ(the_map["wednesday"], 3);
- EXPECT_EQ(the_map.count("tuesday"), 1U);
-
- iter = the_map.begin();
- ASSERT_TRUE(iter != the_map.end());
- EXPECT_EQ(iter->first, "monday");
- EXPECT_EQ(iter->second, 1);
- // Use the occasion to check that post-increment works correctly.
- iter1 = iter;
- iter2 = iter++;
- EXPECT_TRUE(iter1 == iter2);
- ASSERT_TRUE(iter != the_map.end());
- EXPECT_EQ(iter->first, "tuesday");
- EXPECT_EQ(iter->second, 2);
- iter1 = iter;
- iter2 = iter++;
- EXPECT_TRUE(iter1 == iter2);
- ASSERT_TRUE(iter != the_map.end());
- EXPECT_EQ(iter->first, "wednesday");
- EXPECT_EQ(iter->second, 3);
- iter1 = iter;
- iter2 = iter++;
- EXPECT_TRUE(iter1 == iter2);
- EXPECT_TRUE(iter == the_map.end());
-
- EXPECT_EQ(the_map.erase("tuesday"), 1U);
-
- EXPECT_EQ(the_map["monday" ], 1);
- EXPECT_EQ(the_map["wednesday"], 3);
- EXPECT_EQ(the_map.count("tuesday"), 0U);
- EXPECT_EQ(the_map.erase("tuesday"), 0U);
-
- iter = the_map.begin();
- ASSERT_TRUE(iter != the_map.end());
- EXPECT_EQ(iter->first, "monday");
- EXPECT_EQ(iter->second, 1);
- ++iter;
- ASSERT_TRUE(iter != the_map.end());
- EXPECT_EQ(iter->first, "wednesday");
- EXPECT_EQ(iter->second, 3);
- iter1 = iter;
- iter2 = iter++;
- EXPECT_TRUE(iter1 == iter2);
- EXPECT_TRUE(iter == the_map.end());
-
- the_map["thursday"] = 4;
- the_map["friday"] = 5;
- EXPECT_EQ(the_map.size(), 4U);
- EXPECT_FALSE(the_map.empty());
-
- the_map["saturday"] = 6;
-
- EXPECT_EQ(the_map.count("friday"), 1U);
- EXPECT_EQ(the_map.erase("friday"), 1U);
- EXPECT_EQ(the_map.count("friday"), 0U);
- EXPECT_EQ(the_map.erase("friday"), 0U);
-
- EXPECT_EQ(the_map.size(), 4U);
- EXPECT_FALSE(the_map.empty());
- EXPECT_EQ(the_map.erase("monday"), 1U);
- EXPECT_EQ(the_map.size(), 3U);
- EXPECT_FALSE(the_map.empty());
-
- the_map.clear();
- EXPECT_EQ(the_map.size(), 0U);
- EXPECT_TRUE(the_map.empty());
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/vertex_source.cc b/o3d/core/cross/vertex_source.cc
deleted file mode 100644
index 5fe28d1..0000000
--- a/o3d/core/cross/vertex_source.cc
+++ /dev/null
@@ -1,73 +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 definition of VertexSource.
-
-#include "core/cross/vertex_source.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(VertexSource, ParamObject);
-
-bool VertexSource::BindStream(VertexSource* source,
- Stream::Semantic semantic,
- int semantic_index) {
- if (source) {
- ParamVertexBufferStream* source_param = source->GetVertexStreamParam(
- semantic, semantic_index);
- ParamVertexBufferStream* dest_param = GetVertexStreamParam(
- semantic, semantic_index);
- if (source_param && dest_param &&
- source_param->stream().field().IsA(
- dest_param->stream().field().GetClass()) &&
- source_param->stream().field().num_components() ==
- dest_param->stream().field().num_components()) {
- return dest_param->Bind(source_param);
- }
- }
-
- return false;
-}
-
-bool VertexSource::UnbindStream(Stream::Semantic semantic, int semantic_index) {
- ParamVertexBufferStream* dest_param = GetVertexStreamParam(
- semantic, semantic_index);
- if (dest_param && dest_param->input_connection() != NULL) {
- dest_param->UnbindInput();
- return true;
- }
- return false;
-}
-
-} // namespace o3d
-
-
diff --git a/o3d/core/cross/vertex_source.h b/o3d/core/cross/vertex_source.h
deleted file mode 100644
index 74222cd6..0000000
--- a/o3d/core/cross/vertex_source.h
+++ /dev/null
@@ -1,91 +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 declaration of VertexSource.
-
-#ifndef O3D_CORE_CROSS_VERTEX_SOURCE_H_
-#define O3D_CORE_CROSS_VERTEX_SOURCE_H_
-
-#include "core/cross/param_object.h"
-#include "core/cross/stream.h"
-
-namespace o3d {
-
-// A VertexSource is an abstract base class for classes that allow binding
-// Streams such that the VertexSource updates the Buffers of the Streams that
-// have been bound to it. Example of concrete VertexSource objects would be
-// SkinEval, BlendShapeEval, TerrainEval
-class VertexSource : public ParamObject {
- public:
- explicit VertexSource(ServiceLocator* service_locator)
- : ParamObject(service_locator) {
- }
-
- // Used by BindStream. Each derived class must provide this function.
- // Returns the ParamVertexBufferStream that manages the given stream. as an
- // output param for this VertexSource.
- virtual ParamVertexBufferStream* GetVertexStreamParam(
- Stream::Semantic semantic,
- int semantic_index) const = 0;
-
- // Bind the source stream to the corresponding stream in this VertexSource.
- // Parameters:
- // source: Source to get vertices from.
- // semantic: The semantic of the vertices to get
- // semantic_index: The semantic index of the vertices to get.
- // Returns:
- // True if success. False if failure. If the requested semantic or semantic
- // index do not exist on the source or this source the bind will fail.
- bool BindStream(VertexSource* source,
- Stream::Semantic semantic,
- int semantic_index);
-
- // Unbinds the requested stream.
- // Parameters:
- // semantic: The semantic of the vertices to unbind
- // semantic_index: The semantic index of the vertices to unbind.
- // Returns:
- // True if unbound. False those vertices do not exist or were not bound.
- bool UnbindStream(Stream::Semantic semantic, int semantic_index);
-
- private:
- O3D_DECL_CLASS(VertexSource, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(VertexSource);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_VERTEX_SOURCE_H_
-
-
-
-
diff --git a/o3d/core/cross/vertex_source_test.cc b/o3d/core/cross/vertex_source_test.cc
deleted file mode 100644
index ad0cdeb..0000000
--- a/o3d/core/cross/vertex_source_test.cc
+++ /dev/null
@@ -1,294 +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 implements unit tests for class VertexSource.
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/vertex_source.h"
-#include "core/cross/error_status.h"
-#include "core/cross/evaluation_counter.h"
-#include "core/cross/fake_vertex_source.h"
-#include "core/cross/pointer_utils.h"
-#include "core/cross/buffer.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-
-namespace o3d {
-
-namespace {
-
-static const float kEpsilon = 0.0000001f;
-
-bool CompareVertices(FakeVertexSource* source,
- Stream::Semantic semantic,
- int semantic_index,
- const float* values,
- float multiplier) {
- const Stream* stream = source->GetVertexStream(semantic, semantic_index);
- if (!stream) {
- return false;
- }
-
- const Field& field = stream->field();
- Buffer* buffer = field.buffer();
- if (!buffer) {
- return false;
- }
-
- BufferLockHelper helper(buffer);
- void* data = helper.GetData(Buffer::READ_ONLY);
- if (!data) {
- return false;
- }
-
- unsigned num_vertices = stream->GetMaxVertices();
- unsigned stride = buffer->stride();
-
- const float* source_values = PointerFromVoidPointer<const float*>(
- data, field.offset());
- while (num_vertices) {
- for (unsigned jj = 0; jj < 3; ++jj) {
- float difference = fabsf(source_values[jj] - values[jj] * multiplier);
- if (difference > kEpsilon) {
- return false;
- }
- }
- values += 3;
- source_values = AddPointerOffset(source_values, stride);
- --num_vertices;
- }
- return true;
-}
-
-// TODO: Remove the need for this.
-void InvalidateAllParameters(Pack* pack) {
- EvaluationCounter* evaluation_counter(
- pack->service_locator()->GetService<EvaluationCounter>());
- evaluation_counter->InvalidateAllParameters();
-}
-
-} // anonymous namespace
-
-class VertexSourceTest : public testing::Test {
- protected:
-
- VertexSourceTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- Pack *pack_;
- ErrorStatus* error_status_;
-};
-
-void VertexSourceTest::SetUp() {
- error_status_ = new ErrorStatus(g_service_locator);
- pack_ = object_manager_->CreatePack();
-}
-
-void VertexSourceTest::TearDown() {
- pack_->Destroy();
- delete error_status_;
-}
-
-TEST_F(VertexSourceTest, BindStream) {
- static float some_vertices[][3] = {
- { 1.0f, 2.0f, 3.0f, },
- { 7.0f, 8.0f, 9.0f, },
- { 4.0f, 5.0f, 6.0f, },
- };
- const unsigned kNumVertices = arraysize(some_vertices);
- const unsigned kNumComponents = arraysize(some_vertices[0]);
-
- scoped_ptr<FakeVertexSource> destination(new FakeVertexSource(
- pack()->service_locator()));
- ASSERT_TRUE(destination != NULL);
-
- // Create 2 Buffers.
- SourceBuffer* destination_buffer_1 = pack()->Create<SourceBuffer>();
- SourceBuffer* destination_buffer_2 = pack()->Create<SourceBuffer>();
- ASSERT_TRUE(destination_buffer_1 != NULL);
- ASSERT_TRUE(destination_buffer_2 != NULL);
-
- // Create a field for each buffer.
- Field* destination_field_1 = destination_buffer_1->CreateField(
- FloatField::GetApparentClass(), kNumComponents);
- Field* destination_field_2 = destination_buffer_2->CreateField(
- FloatField::GetApparentClass(), kNumComponents);
- ASSERT_TRUE(destination_field_1 != NULL);
- ASSERT_TRUE(destination_field_2 != NULL);
- ASSERT_TRUE(destination_buffer_1->AllocateElements(kNumVertices));
- ASSERT_TRUE(destination_buffer_2->AllocateElements(kNumVertices));
-
- // Set up streams on primitive.
- EXPECT_TRUE(destination->SetVertexStream(Stream::POSITION,
- 0,
- destination_field_1,
- 0));
- EXPECT_TRUE(destination->SetVertexStream(Stream::POSITION,
- 1,
- destination_field_2,
- 0));
-
- // Create 2 source buffers.
- SourceBuffer* source_buffer_1 = pack()->Create<SourceBuffer>();
- SourceBuffer* source_buffer_2 = pack()->Create<SourceBuffer>();
- ASSERT_TRUE(source_buffer_1 != NULL);
- ASSERT_TRUE(source_buffer_2 != NULL);
-
- // Create a field for each buffer.
- Field* source_field_1 = source_buffer_1->CreateField(
- FloatField::GetApparentClass(), kNumComponents);
- Field* source_field_2 = source_buffer_2->CreateField(
- FloatField::GetApparentClass(), kNumComponents);
- ASSERT_TRUE(source_field_1 != NULL);
- ASSERT_TRUE(source_field_2 != NULL);
- ASSERT_TRUE(source_buffer_1->AllocateElements(kNumVertices));
- ASSERT_TRUE(source_buffer_2->AllocateElements(kNumVertices));
-
-
- // Put some vertices in the source streams.
- ASSERT_TRUE(source_buffer_1->AllocateElements(kNumVertices));
- source_field_1->SetFromFloats(&some_vertices[0][0], kNumComponents, 0,
- kNumVertices);
- ASSERT_TRUE(source_buffer_2->AllocateElements(kNumVertices));
- source_field_2->SetFromFloats(&some_vertices[0][0], kNumComponents, 0,
- kNumVertices);
-
- scoped_ptr<FakeVertexSource>source(new FakeVertexSource(
- pack()->service_locator()));
- ASSERT_TRUE(source != NULL);
-
- // Set up streams on source
- EXPECT_TRUE(source->SetVertexStream(Stream::POSITION,
- 0,
- source_field_1,
- 0));
- EXPECT_TRUE(source->SetVertexStream(Stream::POSITION,
- 1,
- source_field_2,
- 0));
-
-
- // Bind the vertices to both dest streams.
- EXPECT_TRUE(destination->BindStream(source.get(), Stream::POSITION, 0));
- EXPECT_TRUE(destination->BindStream(source.get(), Stream::POSITION, 1));
- // Non-existant streams should fail.
- EXPECT_FALSE(destination->BindStream(source.get(), Stream::POSITION, 2));
- EXPECT_FALSE(destination->BindStream(source.get(), Stream::COLOR, 10));
-
- // Cause the vertices to get updated.
- destination->UpdateStreams();
-
- // Test that vertices get updated.
- EXPECT_TRUE(CompareVertices(destination.get(),
- Stream::POSITION,
- 0,
- &some_vertices[0][0],
- 2.0f));
- EXPECT_TRUE(CompareVertices(destination.get(),
- Stream::POSITION,
- 1,
- &some_vertices[0][0],
- 3.0f));
-
- // Check that UpdateOutputs only got called once.
- EXPECT_EQ(destination->update_outputs_call_count(), 1U);
- EXPECT_EQ(source->update_outputs_call_count(), 1U);
-
- // Test that if we chain another VertexSource UpdateOutputs only gets called
- // once.
- SourceBuffer* source_buffer_1b = pack()->Create<SourceBuffer>();
- ASSERT_TRUE(source_buffer_1b != NULL);
- Field* source_field_1b = source_buffer_1b->CreateField(
- FloatField::GetApparentClass(), kNumComponents);
- ASSERT_TRUE(source_field_1b != NULL);
-
- // Put some vertices in the source streams.
- ASSERT_TRUE(source_buffer_1b->AllocateElements(kNumVertices));
- source_field_1b->SetFromFloats(&some_vertices[0][0], kNumComponents, 0,
- kNumVertices);
-
- scoped_ptr<FakeVertexSource>source_b(new FakeVertexSource(
- pack()->service_locator()));
- ASSERT_TRUE(source_b != NULL);
-
- // Set up streams on source
- EXPECT_TRUE(source_b->SetVertexStream(Stream::POSITION,
- 0,
- source_field_1b,
- 0));
-
- // Bind the vertices to streams.
- EXPECT_TRUE(source->BindStream(source_b.get(), Stream::POSITION, 0));
-
- // Cause the vertices to get updated.
- InvalidateAllParameters(pack());
- destination->UpdateStreams();
-
- // Test that vertices get updated.
- EXPECT_TRUE(CompareVertices(destination.get(),
- Stream::POSITION,
- 0,
- &some_vertices[0][0],
- 4.0f));
- // Test that these vertices stayed the same.
- EXPECT_TRUE(CompareVertices(destination.get(),
- Stream::POSITION,
- 1,
- &some_vertices[0][0],
- 3.0f));
-
- // Check that UpdateOutputs only got called once.
- EXPECT_EQ(destination->update_outputs_call_count(), 2U);
- EXPECT_EQ(source->update_outputs_call_count(), 2U);
- EXPECT_EQ(source_b->update_outputs_call_count(), 1U);
-
- // Test that if we ask again UpdateOutputs does not get called.
- destination->UpdateStreams();
- EXPECT_EQ(destination->update_outputs_call_count(), 2U);
- EXPECT_EQ(source->update_outputs_call_count(), 2U);
- EXPECT_EQ(source_b->update_outputs_call_count(), 1U);
-
- // Test that we can unbind.
- EXPECT_TRUE(source->UnbindStream(Stream::POSITION, 0));
- // Test that unbinding fails if we try a stream that does not exist.
- EXPECT_FALSE(source->UnbindStream(Stream::POSITION, 0));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/viewport.cc b/o3d/core/cross/viewport.cc
deleted file mode 100644
index e9abfe6..0000000
--- a/o3d/core/cross/viewport.cc
+++ /dev/null
@@ -1,69 +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 Viewport render node implementation
-
-#include "core/cross/viewport.h"
-#include "core/cross/renderer.h"
-
-namespace o3d {
-
-O3D_DEFN_CLASS(Viewport, RenderNode);
-
-const char* Viewport::kViewportParamName =
- O3D_STRING_CONSTANT("viewport");
-const char* Viewport::kDepthRangeParamName =
- O3D_STRING_CONSTANT("depthRange");
-
-Viewport::Viewport(ServiceLocator* service_locator)
- : RenderNode(service_locator) {
- RegisterParamRef(kViewportParamName, &viewport_param_);
- RegisterParamRef(kDepthRangeParamName, &depth_range_param_);
-
- set_viewport(Float4(0.0, 0.0f, 1.0f, 1.0f));
- set_depth_range(Float2(0.0, 1.0f));
-}
-
-ObjectBase::Ref Viewport::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new Viewport(service_locator));
-}
-
-void Viewport::Render(RenderContext* render_context) {
- render_context->renderer()->GetViewport(&old_viewport_, &old_depth_range_);
- render_context->renderer()->SetViewport(viewport(), depth_range());
-}
-
-void Viewport::PostRender(RenderContext* render_context) {
- render_context->renderer()->SetViewport(old_viewport_, old_depth_range_);
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/viewport.h b/o3d/core/cross/viewport.h
deleted file mode 100644
index b6d185c..0000000
--- a/o3d/core/cross/viewport.h
+++ /dev/null
@@ -1,108 +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 Viewport render node declaration.
-
-#ifndef O3D_CORE_CROSS_VIEWPORT_H_
-#define O3D_CORE_CROSS_VIEWPORT_H_
-
-#include "core/cross/render_node.h"
-
-namespace o3d {
-
-// A Viewport is a render node that sets the render viewport and depth range.
-// It uses a Float4 in the format (left, top, width, height) where left, top,
-// width and height are in a 0.0 to 1.0 range that represent positions and
-// dimensions relative to the size of the client's rendering area. The depth
-// range is represented by a Float2 in the format (min Z, max Z)
-//
-// Note: The viewport values must describe a rectangle that is 100% inside the
-// client area. In other words, (0.5, 0.0, 1.0, 1.0) would describe an area that
-// is 1/2 off right side of the screen. That is an invalid value and will be
-// clipped to (0.5, 0.0, 0.5, 1.0).
-class Viewport : public RenderNode {
- public:
- typedef SmartPointer<Viewport> Ref;
-
- // Gets the viewport.
- const Float4 viewport() const {
- return viewport_param_->value();
- }
-
- // Sets the viewport.
- void set_viewport(const Float4& value) {
- viewport_param_->set_value(value);
- }
-
- // Gets the depth range.
- const Float2 depth_range() const {
- return depth_range_param_->value();
- }
-
- // Sets the depth range.
- void set_depth_range(const Float2& value) {
- depth_range_param_->set_value(value);
- }
-
- // Names of Viewport Params.
- static const char* kViewportParamName;
- static const char* kDepthRangeParamName;
-
- // Overridden from RenderNode. Sets the viewport.
- virtual void Render(RenderContext* render_context);
-
- // Overridden from RenderNode. Restores the viewport.
- virtual void PostRender(RenderContext* render_context);
-
- private:
- explicit Viewport(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- ParamFloat4::Ref viewport_param_; // viewport (left, top, width, height)
- ParamFloat2::Ref depth_range_param_; // minZ (def. 0.0), maxZ (def. 1.0)
-
- Float4 old_viewport_;
- Float2 old_depth_range_;
-
- O3D_DECL_CLASS(Viewport, RenderNode);
- DISALLOW_COPY_AND_ASSIGN(Viewport);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_VIEWPORT_H_
-
-
-
-
diff --git a/o3d/core/cross/visitor_base.h b/o3d/core/cross/visitor_base.h
deleted file mode 100644
index 6168a3f..0000000
--- a/o3d/core/cross/visitor_base.h
+++ /dev/null
@@ -1,154 +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 declaration of class VisitorBase.
-
-#ifndef O3D_CORE_CROSS_VISITOR_BASE_H_
-#define O3D_CORE_CROSS_VISITOR_BASE_H_
-
-#include <map>
-
-#include "base/basictypes.h"
-#include "core/cross/object_base.h"
-
-namespace o3d {
-
-// Interface implemented by all visitor classes.
-class IVisitor {
- public:
- IVisitor() {
- }
-
- virtual ~IVisitor() {
- }
-
- // Calls the appropriate visitor function enabled for the runtime
- // type of visited object.
- virtual void Accept(ObjectBase* visited) = 0;
-
- // Returns whether a visitor function has been registered for the
- // given class.
- virtual bool IsHandled(const ObjectBase::Class* clazz) = 0;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(IVisitor);
-};
-
-// Immediate base class of all visitor classes. The type of the derived
-// class must be specified as the Visitor template parameter. Used like:
-//
-// class MyVisitor : public VisitorBase<MyVisitor> {
-// }
-template <typename Visitor>
-class VisitorBase : public IVisitor {
- struct ForwarderBase {
- virtual void Forward(VisitorBase<Visitor>* visitor,
- ObjectBase* visited) = 0;
- virtual ~ForwarderBase() {
- }
- };
-
- template <typename VisitedClass>
- struct Forwarder : ForwarderBase {
- explicit Forwarder(void (Visitor::*function)(VisitedClass* visited))
- : function_(function) {
- }
- virtual void Forward(VisitorBase<Visitor>* visitor,
- ObjectBase* visited) {
- (static_cast<Visitor*>(visitor)->*function_)(
- static_cast<VisitedClass*>(visited));
- }
- void (Visitor::*function_)(VisitedClass* visited);
- };
-
- typedef typename std::map<const ObjectBase::Class*, ForwarderBase*>
- ForwarderMap;
-
- public:
- VisitorBase() {
- }
-
- virtual ~VisitorBase() {
- for (typename ForwarderMap::iterator it = forwarders_.begin();
- it != forwarders_.end(); ++it) {
- delete it->second;
- }
- }
-
- // Enables the given function to be called for class VisitedClass.
- template <typename VisitedClass>
- void Enable(void (Visitor::*function)(VisitedClass* visited)) {
- forwarders_.insert(typename ForwarderMap::value_type(
- VisitedClass::GetApparentClass(),
- new Forwarder<VisitedClass>(function)));
- }
-
- // Calls the appropriate visitor function enabled for the runtime
- // type of visited object.
- virtual void Accept(ObjectBase* visited) {
- if (visited == NULL)
- return;
-
- const ObjectBase::Class* current_class = visited->GetClass();
- typename ForwarderMap::iterator it;
- while (current_class != NULL) {
- it = forwarders_.find(current_class);
- if (it != forwarders_.end()) {
- it->second->Forward(this, visited);
- break;
- }
- current_class = current_class->parent();
- }
- }
-
- // Returns whether a visitor function has been registered for the
- // given class.
- virtual bool IsHandled(const ObjectBase::Class* clazz) {
- const ObjectBase::Class* current_class = clazz;
- typename ForwarderMap::iterator it;
- while (current_class != NULL) {
- it = forwarders_.find(current_class);
- if (it != forwarders_.end()) {
- return true;
- }
- current_class = current_class->parent();
- }
- return false;
- }
-
- private:
- ForwarderMap forwarders_;
- DISALLOW_COPY_AND_ASSIGN(VisitorBase<Visitor>);
-};
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_VISITOR_BASE_H_
diff --git a/o3d/core/cross/visitor_base_test.cc b/o3d/core/cross/visitor_base_test.cc
deleted file mode 100644
index 8985dcb..0000000
--- a/o3d/core/cross/visitor_base_test.cc
+++ /dev/null
@@ -1,165 +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 tests for class VisitorBase.
-
-#include "core/cross/class_manager.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/service_locator.h"
-#include "core/cross/visitor_base.h"
-#include "tests/common/win/testing_common.h"
-
-namespace o3d {
-
-class TestClass : public ObjectBase {
- public:
- explicit TestClass(ServiceLocator* service_locator)
- : ObjectBase(service_locator) {
- }
- static ObjectBase::Ref Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new TestClass(service_locator));
- }
- O3D_DECL_CLASS(TestClass, ObjectBase);
-};
-O3D_DEFN_CLASS(TestClass, ObjectBase);
-
-class TestVisitor : public VisitorBase<TestVisitor> {
- public:
- TestVisitor()
- : visit_object_base_calls_(0),
- visit_object_base_param_(NULL),
- visit_test_class_calls_(0),
- visit_test_class_param_(NULL) {
- }
-
- void VisitObjectBase(ObjectBase* param) {
- ++visit_object_base_calls_;
- visit_object_base_param_ = param;
- }
-
- void VisitTestClass(TestClass* param) {
- ++visit_test_class_calls_;
- visit_test_class_param_ = param;
- }
-
- int visit_object_base_calls_;
- ObjectBase* visit_object_base_param_;
-
- int visit_test_class_calls_;
- TestClass* visit_test_class_param_;
-};
-
-class VisitorBaseTest : public testing::Test {
- protected:
- virtual void SetUp() {
- service_locator_ = new ServiceLocator;
- class_manager_ = new ClassManager(service_locator_);
- class_manager_->AddTypedClass<TestClass>();
- object_manager_ = new ObjectManager(service_locator_);
- }
-
- virtual void TearDown() {
- delete object_manager_;
- delete class_manager_;
- delete service_locator_;
- }
-
- ServiceLocator* service_locator_;
- ObjectManager* object_manager_;
- ClassManager* class_manager_;
- Pack* pack_;
- TestVisitor visitor_;
-};
-
-TEST_F(VisitorBaseTest, AcceptShouldForwardToRegisteredFunction) {
- visitor_.Enable(&TestVisitor::VisitTestClass);
- ObjectBase::Ref object(class_manager_->CreateObjectByClass(
- TestClass::GetApparentClass()));
- visitor_.Accept(object);
- EXPECT_EQ(1, visitor_.visit_test_class_calls_);
- EXPECT_EQ(object.Get(), visitor_.visit_test_class_param_);
- EXPECT_EQ(0, visitor_.visit_object_base_calls_);
-}
-
-TEST_F(VisitorBaseTest, AcceptShouldDoNothingIfNoFunctionIsRegisteredForClass) {
- ObjectBase::Ref object(class_manager_->CreateObjectByClass(
- TestClass::GetApparentClass()));
- visitor_.Accept(object);
- EXPECT_EQ(0, visitor_.visit_test_class_calls_);
- EXPECT_EQ(0, visitor_.visit_object_base_calls_);
-}
-
-TEST_F(VisitorBaseTest,
- AcceptShouldForwardToRegisteredFunctionForParentIfClassNotRegistered) {
- visitor_.Enable(&TestVisitor::VisitObjectBase);
- ObjectBase::Ref object(class_manager_->CreateObjectByClass(
- TestClass::GetApparentClass()));
- visitor_.Accept(object);
- EXPECT_EQ(1, visitor_.visit_object_base_calls_);
- EXPECT_EQ(object.Get(), visitor_.visit_object_base_param_);
- EXPECT_EQ(0, visitor_.visit_test_class_calls_);
-}
-
-TEST_F(VisitorBaseTest, AcceptShouldDoNothingForNull) {
- visitor_.Accept(NULL);
- EXPECT_EQ(0, visitor_.visit_test_class_calls_);
- EXPECT_EQ(0, visitor_.visit_object_base_calls_);
-}
-
-TEST_F(VisitorBaseTest,
- VisitorBaseAcceptShouldForwardToRegisteredFunctionOnceForEachAccept) {
- visitor_.Enable(&TestVisitor::VisitTestClass);
- ObjectBase::Ref object(class_manager_->CreateObjectByClass(
- TestClass::GetApparentClass()));
- visitor_.Accept(object);
- visitor_.Accept(object);
- EXPECT_EQ(2, visitor_.visit_test_class_calls_);
- EXPECT_EQ(object.Get(), visitor_.visit_test_class_param_);
- EXPECT_EQ(0, visitor_.visit_object_base_calls_);
-}
-
-TEST_F(VisitorBaseTest, IsHandledReturnsTrueIfAFunctionIsRegistered) {
- visitor_.Enable(&TestVisitor::VisitTestClass);
- EXPECT_TRUE(visitor_.IsHandled(TestClass::GetApparentClass()));
-}
-
-TEST_F(VisitorBaseTest,
- IsHandledReturnsTrueIfAFunctionIsRegisteredForABaseClass) {
- visitor_.Enable(&TestVisitor::VisitObjectBase);
- EXPECT_TRUE(visitor_.IsHandled(TestClass::GetApparentClass()));
-}
-
-TEST_F(VisitorBaseTest, IsHandledReturnsFalseIfNoFunctionIsRegistered) {
- EXPECT_FALSE(visitor_.IsHandled(TestClass::GetApparentClass()));
-}
-
-} // namespace o3d
diff --git a/o3d/core/cross/weak_ptr.h b/o3d/core/cross/weak_ptr.h
deleted file mode 100644
index fc2dbfb..0000000
--- a/o3d/core/cross/weak_ptr.h
+++ /dev/null
@@ -1,166 +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.
- */
-
-
-// An intrusive weak pointer implementation.
-
-#ifndef O3D_CORE_CROSS_WEAK_PTR_H_
-#define O3D_CORE_CROSS_WEAK_PTR_H_
-
-#include "base/logging.h"
-#include "core/cross/smart_ptr.h"
-
-namespace o3d {
-
-// A WeakPointer is a pointer that could go NULL if the object it is pointing
-// to is freed/destroyed/released. That means every time you want to access the
-// think the WeakPointer is pointing to you must call Get() and check for NULL.
-//
-// To use this WeakPointer, first, in the class you want it to point to add a
-// WeakPointerManager field and initialize it in your constructor. Then provide
-// a function GetWeakPointer() to get a WeakPointer to your class. Example.
-//
-// class MyClass {
-// public:
-// typedef WeakPointer<MyClass> WeakPointerType;
-//
-// MyClass() : weak_pointer_manager_(this) {
-// }
-//
-// WeakPointerType GetWeakPointer() const {
-// weak_pointer_manager_.GetWeakPointer();
-// }
-//
-// private:
-// WeakPointerType::WeakPointerManager weak_pointer_manager_;
-// };
-template <class C>
-class WeakPointer {
- public:
- typedef C* Pointer;
- typedef C& Reference;
- typedef C ClassType;
-
- WeakPointer() : handle_(typename WeakPointerHandle::Ref(NULL)) {
- }
-
- // This copy constructor is not marked explicit on purpose, so that
- // we can copy weak pointers implicitly.
- WeakPointer(const WeakPointer<C>& source) // NOLINT
- : handle_(source.handle_) {
- }
-
- WeakPointer<C>& operator=(const WeakPointer<C>& rhs) {
- if (this != &rhs) {
- handle_ = rhs.handle_;
- }
- return *this;
- }
-
- // Gets the object this weak pointer is pointing to.
- Pointer Get() const {
- return handle_.IsNull() ? NULL : handle_->GetRaw();
- }
-
- // This class manages a WeakPointer for the object the WeakPointer is pointing
- // to. If you forget to call Init you'll get an assert on destruction. It also
- // enforces calling Reset on the weak pointer handle at destruction.
- class WeakPointerManager {
- public:
- typedef C* Pointer;
- typedef C& Reference;
- typedef C ClassType;
- typedef WeakPointer<C> WeakPointerType;
- typedef typename WeakPointerType::WeakPointerHandle HandleType;
-
- explicit WeakPointerManager(Pointer data)
- : handle_(typename HandleType::Ref(new HandleType(data))) {
- }
-
- ~WeakPointerManager() {
- handle_->Reset();
- }
-
- WeakPointerType GetWeakPointer() const {
- return handle_->GetWeakPointer();
- }
-
- private:
- typename HandleType::Ref handle_;
- };
-
- private:
- // This class holds the pointer to the actual object all weak pointers
- // are pointing to. It is ref counted so when the last weak pointer
- // goes away this handle will go away.
- class WeakPointerHandle : public RefCounted {
- public:
- typedef SmartPointer<WeakPointerHandle> Ref;
-
- explicit WeakPointerHandle(Pointer data)
- : data_(data) {
- }
-
- void Reset() {
- data_ = NULL;
- }
-
- Pointer GetRaw() const {
- return data_;
- }
-
- WeakPointer<C> GetWeakPointer() const {
- return WeakPointer<C>(this);
- }
-
- private:
- Pointer data_;
-
- DISALLOW_COPY_AND_ASSIGN(WeakPointerHandle);
- };
-
- explicit WeakPointer(const WeakPointerHandle* handle)
- : handle_(typename WeakPointerHandle::Ref(
- const_cast<WeakPointerHandle*>(handle))) {
- }
-
- typename WeakPointerHandle::Ref handle_;
-};
-
-// Provide a convenience equality test operator on SmartPointer objects.
-template <class C>
-inline bool operator==(const WeakPointer<C>& lhs, const WeakPointer<C>& rhs) {
- return lhs.Get() == rhs.Get();
-}
-
-} // namespace o3d
-
-#endif // O3D_CORE_CROSS_WEAK_PTR_H_
diff --git a/o3d/core/cross/weak_ptr_test.cc b/o3d/core/cross/weak_ptr_test.cc
deleted file mode 100644
index 8494331..0000000
--- a/o3d/core/cross/weak_ptr_test.cc
+++ /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.
- */
-
-
-#include "core/cross/weak_ptr.h"
-#include "tests/common/win/testing_common.h"
-
-namespace o3d {
-
-namespace {
-
-// A simple testing helper class that tracks the number of live instances of
-// itself.
-class InstanceCount : public RefCounted {
- public:
- typedef SmartPointer<InstanceCount> Ref;
- typedef WeakPointer<InstanceCount> WeakPointerType;
-
- // Use construction & destruction to inc/dec a static instance counter.
- InstanceCount() : weak_pointer_manager_(this) {
- ++instance_count_;
- }
-
- ~InstanceCount() {
- --instance_count_;
- }
-
- // Gets a weak pointer to us.
- WeakPointerType GetWeakPointer() const {
- return weak_pointer_manager_.GetWeakPointer();
- }
-
- static int instance_count() {
- return instance_count_;
- }
-
- private:
- // Manager for weak pointers to us.
- WeakPointerType::WeakPointerManager weak_pointer_manager_;
-
- static int instance_count_;
-};
-
-int InstanceCount::instance_count_ = 0;
-
-} // anonymous namespace.
-
-// Test case for the Weak pointer class
-class WeakPtrTest : public testing::Test {
-};
-
-TEST_F(WeakPtrTest, Construct) {
- WeakPointer<InstanceCount> weak_ptr;
- ASSERT_TRUE(weak_ptr.Get() == NULL);
-}
-
-// Test the behaviour of a single weak pointer.
-TEST_F(WeakPtrTest, SingleReference) {
- InstanceCount* raw_pointer = new InstanceCount();
- WeakPointer<InstanceCount> weak_ptr(raw_pointer->GetWeakPointer());
-
- // Validate that a single instance was created, and that the pointer
- // points to the correct instance.
- EXPECT_TRUE(weak_ptr.Get() == raw_pointer);
- EXPECT_EQ(InstanceCount::instance_count(), 1);
-
- // Validate we can release it and the weak pointer goes to NULL.
- delete raw_pointer;
- EXPECT_EQ(InstanceCount::instance_count(), 0);
- EXPECT_TRUE(weak_ptr.Get() == NULL);
-}
-
-// Validate the behaviour of multiple weak pointers.
-TEST_F(WeakPtrTest, MultipleReferences) {
- InstanceCount* raw_ptr = new InstanceCount();
- WeakPointer<InstanceCount> weak_ptr1(raw_ptr->GetWeakPointer());
- WeakPointer<InstanceCount> weak_ptr2(raw_ptr->GetWeakPointer());
-
- // Validate that only a single instance was created.
- EXPECT_EQ(InstanceCount::instance_count(), 1);
- EXPECT_TRUE(weak_ptr1.Get() == raw_ptr);
- EXPECT_TRUE(weak_ptr1.Get() == weak_ptr2.Get());
-
- // Check that if we delete the object both weak pointers go NULL.
- delete raw_ptr;
- EXPECT_TRUE(weak_ptr1.Get() == NULL);
- EXPECT_TRUE(weak_ptr2.Get() == NULL);
- EXPECT_EQ(InstanceCount::instance_count(), 0);
-}
-
-// Check that assignment works..
-TEST_F(WeakPtrTest, Assignment) {
- InstanceCount* raw_ptr = new InstanceCount();
- WeakPointer<InstanceCount> weak_ptr1;
- WeakPointer<InstanceCount> weak_ptr2;
-
- EXPECT_TRUE(weak_ptr1.Get() == NULL);
- EXPECT_TRUE(weak_ptr2.Get() == NULL);
- weak_ptr1 = raw_ptr->GetWeakPointer();
- weak_ptr2 = weak_ptr1;
-
- EXPECT_TRUE(weak_ptr1.Get() == raw_ptr);
- EXPECT_TRUE(weak_ptr1.Get() == weak_ptr2.Get());
-
- // Check that if we delete the object both weak pointers go NULL.
- delete raw_ptr;
- EXPECT_TRUE(weak_ptr1.Get() == NULL);
- EXPECT_TRUE(weak_ptr2.Get() == NULL);
- EXPECT_EQ(InstanceCount::instance_count(), 0);
-}
-
-// Validate the behaviour of self-assignment edge-case.
-TEST_F(WeakPtrTest, SelfAssignment) {
- InstanceCount* raw_ptr = new InstanceCount();
- WeakPointer<InstanceCount> weak_ptr1(raw_ptr->GetWeakPointer());
-
- EXPECT_TRUE(weak_ptr1.Get() == raw_ptr);
- weak_ptr1 = weak_ptr1;
- EXPECT_TRUE(weak_ptr1.Get() == raw_ptr);
- delete raw_ptr;
- EXPECT_TRUE(weak_ptr1.Get() == NULL);
-}
-
-TEST_F(WeakPtrTest, EqualityTest) {
- InstanceCount* raw_ptr = new InstanceCount();
- WeakPointer<InstanceCount> weak_ptr1(raw_ptr->GetWeakPointer());
- WeakPointer<InstanceCount> weak_ptr2(raw_ptr->GetWeakPointer());
-
- // Validate that only a single instance was created.
- EXPECT_EQ(InstanceCount::instance_count(), 1);
- EXPECT_TRUE(weak_ptr1.Get() == raw_ptr);
- EXPECT_TRUE(weak_ptr1.Get() == weak_ptr2.Get());
-
- EXPECT_TRUE(weak_ptr1 == weak_ptr2);
-
- // Check that if we delete the object both weak pointers go NULL.
- delete raw_ptr;
- EXPECT_TRUE(weak_ptr1 == weak_ptr2);
-}
-
-} // namespace o3d
diff --git a/o3d/core/linux/display_window_linux.h b/o3d/core/linux/display_window_linux.h
deleted file mode 100644
index c78b915..0000000
--- a/o3d/core/linux/display_window_linux.h
+++ /dev/null
@@ -1,66 +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_CORE_LINUX_DISPLAY_WINDOW_LINUX_H_
-#define O3D_CORE_LINUX_DISPLAY_WINDOW_LINUX_H_
-
-#include <X11/Xlib.h>
-
-#include "core/cross/display_window.h"
-
-namespace o3d {
-
-/**
- * The DisplayWindowLinux class is a platform-specific representation
- * of a platform's display window. This implements the Linux subclass
- * of the DisplayWindow.
- */
-
-class DisplayWindowLinux : public DisplayWindow {
- public:
- DisplayWindowLinux() : display_(NULL), window_(0) {}
- virtual ~DisplayWindowLinux() {}
-
- Display* display() const { return display_; }
- Window window() const { return window_; }
- void set_window(Window window) { window_ = window; }
- void set_display(Display* display) { display_ = display; }
-
- private:
- Display* display_;
- Window window_;
-
- DISALLOW_COPY_AND_ASSIGN(DisplayWindowLinux);
-};
-} // end namespace o3d
-
-#endif // O3D_CORE_LINUX_DISPLAY_WINDOW_LINUX_H_
diff --git a/o3d/core/linux/performance_timer.cc b/o3d/core/linux/performance_timer.cc
deleted file mode 100644
index 9929a48..0000000
--- a/o3d/core/linux/performance_timer.cc
+++ /dev/null
@@ -1,80 +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.
- */
-
-
-// The PerformanceTimer class measures elapsed time between Start and
-// Stop (using the highest resolution timer available on the
-// platform).
-
-#include "core/cross/precompile.h"
-
-#include "core/cross/performance_timer.h"
-
-#include <sys/time.h>
-#include <time.h>
-
-#include "base/logging.h"
-
-namespace o3d {
-
-static uint64_t GetCurrentTime() {
- struct timeval tv;
- gettimeofday(&tv, NULL);
- return tv.tv_sec*1000000ULL + tv.tv_usec;
-}
-
-PerformanceTimer::PerformanceTimer(const char *name)
- : name_(name),
- start_time_(0),
- accum_time_(0) {
-}
-
-void PerformanceTimer::Start() {
- start_time_ = GetCurrentTime();
-}
-
-void PerformanceTimer::Stop() {
- accum_time_ += GetCurrentTime() - start_time_;
-}
-
-double PerformanceTimer::GetElapsedTime() {
- return static_cast<double>(accum_time_) / 1.E6;
-}
-
-void PerformanceTimer::Print() {
- LOG(INFO) << name_.c_str() << " " << GetElapsedTime() << " seconds";
-}
-
-void PerformanceTimer::StopAndPrint() {
- Stop();
- Print();
-}
-}
diff --git a/o3d/core/mac/display_window_mac.h b/o3d/core/mac/display_window_mac.h
deleted file mode 100644
index 6390617..0000000
--- a/o3d/core/mac/display_window_mac.h
+++ /dev/null
@@ -1,85 +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_CORE_MAC_DISPLAY_WINDOW_MAC_H_
-#define O3D_CORE_MAC_DISPLAY_WINDOW_MAC_H_
-
-#include <OpenGL/OpenGL.h>
-#include <AGL/agl.h>
-#include <CoreGraphics/CGContext.h>
-
-#include "core/cross/display_window.h"
-
-namespace o3d {
-
-/**
- * The DisplayWindowMac class is a platform-specific representation of
- * a platform's display window. This implements the Macintosh OS X
- * subclass of the DisplayWindow.
- */
-
-class DisplayWindowMac : public DisplayWindow {
- public:
- DisplayWindowMac()
- : agl_context_(NULL),
- cgl_context_(NULL),
- cg_context_ref_(NULL) {
- }
-
- virtual ~DisplayWindowMac() {}
-
- AGLContext agl_context() const { return agl_context_; }
- CGLContextObj cgl_context() const { return cgl_context_; }
- CGContextRef cg_context_ref() const { return cg_context_ref_; }
-
- void set_agl_context(const AGLContext& agl_context) {
- agl_context_ = agl_context;
- }
-
- void set_cgl_context(const CGLContextObj& cgl_context) {
- cgl_context_ = cgl_context;
- }
-
- void set_cg_context_ref(const CGContextRef& cg_context_ref) {
- cg_context_ref_ = cg_context_ref;
- }
-
- private:
- AGLContext agl_context_;
- CGLContextObj cgl_context_;
- CGContextRef cg_context_ref_;
-
- DISALLOW_COPY_AND_ASSIGN(DisplayWindowMac);
-};
-} // end namespace o3d
-
-#endif // O3D_CORE_MAC_DISPLAY_WINDOW_MAC_H_
diff --git a/o3d/core/mac/performance_timer.cc b/o3d/core/mac/performance_timer.cc
deleted file mode 100644
index 1a1fddf..0000000
--- a/o3d/core/mac/performance_timer.cc
+++ /dev/null
@@ -1,74 +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.
- */
-
-
-// The PerformanceTimer class measures elapsed time between Start and
-// Stop (using the highest resolution timer available on the
-// platform).
-
-#include "core/cross/performance_timer.h"
-
-#include "base/logging.h"
-
-namespace o3d {
-
-PerformanceTimer::PerformanceTimer(const char *name)
- : name_(name) {
- start_time_.lo = start_time_.hi = 0;
- accum_time_.lo = accum_time_.hi = 0;
-}
-
-void PerformanceTimer::Start() {
- start_time_ = UpTime();
-}
-
-void PerformanceTimer::Stop() {
- AbsoluteTime time = UpTime();
- AbsoluteTime deltaTime = SubAbsoluteFromAbsolute(time, start_time_);
- accum_time_ = AddAbsoluteToAbsolute(accum_time_, deltaTime);
-}
-
-double PerformanceTimer::GetElapsedTime() {
- Nanoseconds ns = AbsoluteToNanoseconds(accum_time_);
- uint64 ns64 = UnsignedWideToUInt64(ns);
-
- return static_cast<double>(ns64) * 0.000000001;
-}
-
-void PerformanceTimer::Print() {
- LOG(INFO) << name_.c_str() << " " << GetElapsedTime() << " seconds";
-}
-
-void PerformanceTimer::StopAndPrint() {
- Stop();
- Print();
-}
-}
diff --git a/o3d/core/win/core_unittests.sln b/o3d/core/win/core_unittests.sln
deleted file mode 100644
index d72ca8d6..0000000
--- a/o3d/core/win/core_unittests.sln
+++ /dev/null
@@ -1,39 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 9.00
-# Visual Studio 2005
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "core_unittests", "core_unittests.vcproj", "{A330B4F2-1340-41F9-AE61-BF5471772624}"
- ProjectSection(ProjectDependencies) = postProject
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B} = {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}
- EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "o3dCore", "core_win.vcproj", "{B57C4010-AE66-47A2-8B1F-F839B6E6A67B}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- DebugD3D9|Win32 = DebugD3D9|Win32
- DebugGL|Win32 = DebugGL|Win32
- ReleaseD3D9|Win32 = ReleaseD3D9|Win32
- ReleaseGL|Win32 = ReleaseGL|Win32
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {A330B4F2-1340-41F9-AE61-BF5471772624}.DebugD3D9|Win32.ActiveCfg = DebugD3D9|Win32
- {A330B4F2-1340-41F9-AE61-BF5471772624}.DebugD3D9|Win32.Build.0 = DebugD3D9|Win32
- {A330B4F2-1340-41F9-AE61-BF5471772624}.DebugGL|Win32.ActiveCfg = DebugGL|Win32
- {A330B4F2-1340-41F9-AE61-BF5471772624}.DebugGL|Win32.Build.0 = DebugGL|Win32
- {A330B4F2-1340-41F9-AE61-BF5471772624}.ReleaseD3D9|Win32.ActiveCfg = ReleaseD3D9|Win32
- {A330B4F2-1340-41F9-AE61-BF5471772624}.ReleaseD3D9|Win32.Build.0 = ReleaseD3D9|Win32
- {A330B4F2-1340-41F9-AE61-BF5471772624}.ReleaseGL|Win32.ActiveCfg = ReleaseGL|Win32
- {A330B4F2-1340-41F9-AE61-BF5471772624}.ReleaseGL|Win32.Build.0 = ReleaseGL|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.DebugD3D9|Win32.ActiveCfg = DebugD3D9|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.DebugD3D9|Win32.Build.0 = DebugD3D9|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.DebugGL|Win32.ActiveCfg = DebugGL|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.DebugGL|Win32.Build.0 = DebugGL|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.ReleaseD3D9|Win32.ActiveCfg = ReleaseD3D9|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.ReleaseD3D9|Win32.Build.0 = ReleaseD3D9|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.ReleaseGL|Win32.ActiveCfg = ReleaseGL|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.ReleaseGL|Win32.Build.0 = ReleaseGL|Win32
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
-EndGlobal
diff --git a/o3d/core/win/d3d9/buffer_d3d9.cc b/o3d/core/win/d3d9/buffer_d3d9.cc
deleted file mode 100644
index 0633208..0000000
--- a/o3d/core/win/d3d9/buffer_d3d9.cc
+++ /dev/null
@@ -1,221 +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 definitions of VertexBufferD3D9 and IndexBufferD3D9.
-
-#include "core/cross/precompile.h"
-#include "core/win/d3d9/buffer_d3d9.h"
-#include "core/win/d3d9/utils_d3d9.h"
-
-namespace o3d {
-
-namespace {
-
-DWORD BufferAccessModeToD3DLock(Buffer::AccessMode access_mode) {
- switch (access_mode) {
- case Buffer::READ_ONLY:
- return D3DLOCK_READONLY;
- break;
- case Buffer::WRITE_ONLY:
- return 0;
- case Buffer::READ_WRITE:
- return 0;
- }
- DCHECK(false);
- return 0;
-}
-
-} // anonymous namespace
-
-// Initializes the O3D VertexBuffer object but does not create a DX9 buffer
-// yet.
-VertexBufferD3D9::VertexBufferD3D9(ServiceLocator* service_locator,
- LPDIRECT3DDEVICE9 d3d_device)
- : VertexBuffer(service_locator),
- d3d_device_(d3d_device) {
- DCHECK(d3d_device);
-}
-
-VertexBufferD3D9::~VertexBufferD3D9() {
-}
-
-// Creates a DX9 vertex buffer of the requested size.
-bool VertexBufferD3D9::ConcreteAllocate(unsigned int size_in_bytes) {
- d3d_buffer_ = NULL;
- return HR(d3d_device_->CreateVertexBuffer(
- size_in_bytes,
- 0,
- 0,
- D3DPOOL_MANAGED,
- &d3d_buffer_,
- NULL));
-}
-
-void VertexBufferD3D9::ConcreteFree() {
- d3d_buffer_ = NULL;
-}
-
-// Calls Lock on the DX9 buffer to get the address in memory of where the
-// buffer data is currently stored.
-bool VertexBufferD3D9::ConcreteLock(AccessMode access_mode,
- void **buffer_data) {
- *buffer_data = NULL;
-
- if (GetSizeInBytes() == 0)
- return true;
-
- if (!d3d_buffer_)
- return false;
-
- if (!HR(d3d_buffer_->Lock(0, GetSizeInBytes(), buffer_data,
- BufferAccessModeToD3DLock(access_mode)))) {
- return false;
- }
-
- // Yes, this really happens sometimes.
- if (NULL == *buffer_data) {
- HR(d3d_buffer_->Unlock());
- return false;
- }
-
- return true;
-}
-
-// Calls Unlock on the DX9 buffer to notify that the contents of the buffer
-// are now ready for use.
-bool VertexBufferD3D9::ConcreteUnlock() {
- if (!d3d_buffer_) return false;
- return HR(d3d_buffer_->Unlock());
-}
-
-// Initializes the O3D IndexBuffer object but does not create a DX9 buffer
-// yet.
-IndexBufferD3D9::IndexBufferD3D9(ServiceLocator* service_locator,
- LPDIRECT3DDEVICE9 d3d_device,
- bool small_buffer)
- : IndexBuffer(service_locator),
- d3d_device_(d3d_device),
- shadow_buffer_(NULL),
- dirty_(false),
- small_(small_buffer) {
- DCHECK(d3d_device);
-}
-
-IndexBufferD3D9::~IndexBufferD3D9() {
-}
-
-// Creates a DX9 index buffer of the requested size.
-bool IndexBufferD3D9::ConcreteAllocate(unsigned int size_in_bytes) {
- d3d_buffer_ = NULL;
- if (small_) {
- shadow_buffer_.reset(new uint8[size_in_bytes]);
- }
- return HR(d3d_device_->CreateIndexBuffer(
- size_in_bytes / (small_ ? 2 : 1),
- 0,
- small_ ? D3DFMT_INDEX16 : D3DFMT_INDEX32,
- D3DPOOL_MANAGED,
- &d3d_buffer_,
- NULL));
-}
-
-void IndexBufferD3D9::ConcreteFree() {
- d3d_buffer_ = NULL;
- shadow_buffer_.reset();
-}
-
-// Calls Lock on the DX9 buffer to get the address in memory of where the
-// buffer data is currently stored.
-bool IndexBufferD3D9::ConcreteLock(AccessMode access_mode, void **buffer_data) {
- *buffer_data = NULL;
-
- if (GetSizeInBytes() == 0)
- return true;
-
- if (!d3d_buffer_)
- return false;
-
- if (small_) {
- *buffer_data = shadow_buffer_.get();
- if (access_mode == Buffer::READ_WRITE ||
- access_mode == Buffer::WRITE_ONLY) {
- dirty_ = true;
- }
- return true;
- }
-
- if (!HR(d3d_buffer_->Lock(0, GetSizeInBytes(), buffer_data,
- BufferAccessModeToD3DLock(access_mode)))) {
- return false;
- }
-
- // Yes, this really happens sometimes.
- // WTF is this? If this fails the app fails!
- if (NULL == *buffer_data) {
- HR(d3d_buffer_->Unlock());
- return false;
- }
-
- return true;
-}
-
-// Calls Unlock on the DX9 buffer to notify that the contents of the buffer
-// are now ready for use.
-bool IndexBufferD3D9::ConcreteUnlock() {
- if (GetSizeInBytes() == 0) return true;
- if (!d3d_buffer_) return false;
- if (small_) {
- // TODO: Move this to just before rendering.
- if (dirty_) {
- void* data;
- bool locked = HR(d3d_buffer_->Lock(0, GetSizeInBytes() / 2, &data,
- Buffer::WRITE_ONLY));
- if (locked) {
- uint16* destination = reinterpret_cast<uint16*>(data);
- uint32* source = reinterpret_cast<uint32*>(shadow_buffer_.get());
- uint32* end = source + num_elements();
- for (; source < end; ++source, ++destination) {
- *destination = *source;
- }
- d3d_buffer_->Unlock();
- dirty_ = false;
- return true;
- }
- return false;
- }
- return true;
- } else {
- return HR(d3d_buffer_->Unlock());
- }
-}
-
-} // namespace o3d
diff --git a/o3d/core/win/d3d9/buffer_d3d9.h b/o3d/core/win/d3d9/buffer_d3d9.h
deleted file mode 100644
index 89c499e..0000000
--- a/o3d/core/win/d3d9/buffer_d3d9.h
+++ /dev/null
@@ -1,123 +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 declaration of VertexBufferD3D9 and IndexBufferD3D9.
-
-#ifndef O3D_CORE_WIN_D3D9_BUFFER_D3D9_H_
-#define O3D_CORE_WIN_D3D9_BUFFER_D3D9_H_
-
-#include <d3d9.h>
-#include <atlbase.h>
-#include "base/scoped_ptr.h"
-#include "core/cross/buffer.h"
-
-namespace o3d {
-
-// VertexBufferD3D9 is a wrapper around the DX9 vertex buffer.
-// The buffer starts out empty. Calling Allocate will reserve video memory
-// for the buffer. Buffer contents are are updated by calling Lock() to get a
-// pointer to the memory allocated for the buffer, updating that data in place
-// and calling Unlock() to notify DX that the edits are done.
-class VertexBufferD3D9 : public VertexBuffer {
- public:
- VertexBufferD3D9(ServiceLocator* service_locator,
- IDirect3DDevice9* d3d_device);
- ~VertexBufferD3D9();
-
- // Returns the DX9 vertex buffer handle.
- LPDIRECT3DVERTEXBUFFER9 d3d_buffer() const { return d3d_buffer_; }
-
- protected:
- // Creates a DX9 vertex buffer of the specified size.
- virtual bool ConcreteAllocate(size_t size_in_bytes);
-
- // Frees the buffer.
- virtual void ConcreteFree();
-
- // Returns a pointer to the current contents of the buffer. A matching
- // call to Unlock is necessary to update the contents of the buffer.
- virtual bool ConcreteLock(AccessMode access_mode, void** buffer_data);
-
- // Notifies DX9 that the buffer data has been updated. Unlock is only valid
- // if it follows a Lock operation.
- virtual bool ConcreteUnlock();
-
- private:
- // The D3D Device interface used to create this object.
- CComPtr<IDirect3DDevice9> d3d_device_;
- // Pointer to the internal D3D9 Vertex Buffer object.
- CComPtr<IDirect3DVertexBuffer9> d3d_buffer_;
-};
-
-// IndexBufferD3D9 is a wrapper around the DX9 index buffer object. The buffer
-// starts out empty. A call to Allocate will create a DX9 index buffer of the
-// requested size. Updates the to the contents of the buffer are done via
-// the Lock/Unlock calls.
-class IndexBufferD3D9 : public IndexBuffer {
- public:
- IndexBufferD3D9(ServiceLocator* service_locator,
- IDirect3DDevice9* d3d_device,
- bool small_buffer);
- ~IndexBufferD3D9();
-
- // Returns the DX9 index buffer handle.
- inline LPDIRECT3DINDEXBUFFER9 d3d_buffer() const { return d3d_buffer_; }
-
- protected:
- // Creates a DX9 index buffer of the specified size.
- virtual bool ConcreteAllocate(size_t size_in_bytes);
-
- // Frees the buffer.
- virtual void ConcreteFree();
-
- // Returns a pointer to the current contents of the buffer. After calling
- // Lock, the contents of the buffer can be updated in place.
- virtual bool ConcreteLock(AccessMode access_mode, void** buffer_data);
-
- // Notifies DX9 that the buffer data has been updated. Unlock is only
- // valid if it follows a Lock operation.
- virtual bool ConcreteUnlock();
-
- private:
- bool dirty_;
- bool small_; // 16 or 32 bit. True = 16bit.
- scoped_array<uint8> shadow_buffer_; // shadow buffer if this buffer is small
- // The D3D Device interface used to create this object.
- CComPtr<IDirect3DDevice9> d3d_device_;
- // Pointer to the internal D3D9 Index Buffer object.
- CComPtr<IDirect3DIndexBuffer9> d3d_buffer_;
-};
-
-} // namespace o3d
-
-
-#endif // O3D_CORE_WIN_D3D9_BUFFER_D3D9_H_
diff --git a/o3d/core/win/d3d9/d3d_entry_points.h b/o3d/core/win/d3d9/d3d_entry_points.h
deleted file mode 100644
index 2153ceb..0000000
--- a/o3d/core/win/d3d9/d3d_entry_points.h
+++ /dev/null
@@ -1,140 +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_CORE_WIN_D3D9_D3D_ENTRY_POINTS_H_
-#define O3D_CORE_WIN_D3D9_D3D_ENTRY_POINTS_H_
-
-#include <Windows.h>
-#include <d3d9.h>
-#include <d3dx9.h>
-
-namespace o3d {
-typedef HRESULT (__stdcall *D3DXCreateEffect_Ptr)(
- LPDIRECT3DDEVICE9,
- LPCVOID,
- UINT,
- CONST D3DXMACRO *,
- LPD3DXINCLUDE,
- DWORD,
- LPD3DXEFFECTPOOL,
- LPD3DXEFFECT *,
- LPD3DXBUFFER *);
-
-typedef HRESULT (__stdcall *D3DXGetShaderInputSemantics_Ptr)(
- CONST DWORD *,
- D3DXSEMANTIC *,
- UINT* pCount);
-
-typedef HRESULT (__stdcall *D3DXCreateEffectCompilerFromFileA_Ptr)(
- LPCSTR,
- CONST D3DXMACRO*,
- LPD3DXINCLUDE,
- DWORD,
- LPD3DXEFFECTCOMPILER*,
- LPD3DXBUFFER*);
-
-typedef HRESULT (__stdcall *D3DXCreateEffectCompilerFromFileW_Ptr)(
- LPCWSTR,
- CONST D3DXMACRO*,
- LPD3DXINCLUDE,
- DWORD,
- LPD3DXEFFECTCOMPILER*,
- LPD3DXBUFFER*);
-
-typedef HRESULT (__stdcall *D3DXSaveSurfaceToFileA_Ptr)(
- LPCSTR,
- D3DXIMAGE_FILEFORMAT,
- LPDIRECT3DSURFACE9,
- CONST PALETTEENTRY*,
- CONST RECT*);
-
-typedef HRESULT (__stdcall *D3DXSaveSurfaceToFileW_Ptr)(
- LPCWSTR,
- D3DXIMAGE_FILEFORMAT,
- LPDIRECT3DSURFACE9,
- CONST PALETTEENTRY*,
- CONST RECT*);
-
-typedef HRESULT (__stdcall *D3DXGetShaderConstantTable_Ptr)(
- CONST DWORD*,
- LPD3DXCONSTANTTABLE*);
-
-typedef HRESULT (__stdcall *D3DXCreateFontW_Ptr)(
- LPDIRECT3DDEVICE9 pDevice,
- INT Height,
- UINT Width,
- UINT Weight,
- UINT MipLevels,
- BOOL Italic,
- DWORD CharSet,
- DWORD OutputPrecision,
- DWORD Quality,
- DWORD PitchAndFamily,
- LPCTSTR pFacename,
- LPD3DXFONT * ppFont);
-
-typedef HRESULT (__stdcall *D3DXCreateFontA_Ptr)(
- LPDIRECT3DDEVICE9 pDevice,
- INT Height,
- UINT Width,
- UINT Weight,
- UINT MipLevels,
- BOOL Italic,
- DWORD CharSet,
- DWORD OutputPrecision,
- DWORD Quality,
- DWORD PitchAndFamily,
- LPCTSTR pFacename,
- LPD3DXFONT * ppFont);
-
-typedef HRESULT (__stdcall *D3DXCreateLine_Ptr)(
- LPDIRECT3DDEVICE9 pDevice,
- LPD3DXLINE * ppLine);
-
-typedef IDirect3D9* (__stdcall *Direct3DCreate9_Ptr)(
- UINT SDKVersion);
-
-extern D3DXCreateEffect_Ptr D3DXCreateEffect;
-extern D3DXGetShaderInputSemantics_Ptr D3DXGetShaderInputSemantics;
-extern D3DXCreateEffectCompilerFromFileW_Ptr D3DXCreateEffectCompilerFromFileW;
-extern D3DXCreateEffectCompilerFromFileA_Ptr D3DXCreateEffectCompilerFromFileA;
-extern D3DXSaveSurfaceToFileW_Ptr D3DXSaveSurfaceToFileW;
-extern D3DXSaveSurfaceToFileA_Ptr D3DXSaveSurfaceToFileA;
-extern D3DXGetShaderConstantTable_Ptr D3DXGetShaderConstantTable;
-extern D3DXCreateFontW_Ptr D3DXCreateFontW;
-extern D3DXCreateFontA_Ptr D3DXCreateFontA;
-extern D3DXCreateLine_Ptr D3DXCreateLine;
-extern Direct3DCreate9_Ptr Direct3DCreate9Software;
-
-} // namespace o3d
-
-#endif // O3D_CORE_WIN_D3D9_D3D_ENTRY_POINTS_H_
diff --git a/o3d/core/win/d3d9/draw_element_d3d9.cc b/o3d/core/win/d3d9/draw_element_d3d9.cc
deleted file mode 100644
index 709fbaa..0000000
--- a/o3d/core/win/d3d9/draw_element_d3d9.cc
+++ /dev/null
@@ -1,48 +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 definition of the DrawElementD3D9 class.
-
-#include "core/cross/precompile.h"
-#include "core/win/d3d9/draw_element_d3d9.h"
-
-namespace o3d {
-
-DrawElementD3D9::DrawElementD3D9(ServiceLocator* service_locator)
- : DrawElement(service_locator) {
-}
-
-DrawElementD3D9::~DrawElementD3D9() {
-}
-
-} // namespace o3d
-
diff --git a/o3d/core/win/d3d9/draw_element_d3d9.h b/o3d/core/win/d3d9/draw_element_d3d9.h
deleted file mode 100644
index 2d8a295..0000000
--- a/o3d/core/win/d3d9/draw_element_d3d9.h
+++ /dev/null
@@ -1,53 +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 declaration of the DrawElementD3D9 class.
-
-#ifndef O3D_CORE_WIN_D3D9_DRAW_ELEMENT_D3D9_H_
-#define O3D_CORE_WIN_D3D9_DRAW_ELEMENT_D3D9_H_
-
-#include "core/cross/draw_element.h"
-
-namespace o3d {
-
-// DrawElementD3D9 is the DX9 implementation of the DrawElement. It provides
-// a place for the renderer to store platform specific cache information.
-class DrawElementD3D9 : public DrawElement {
- public:
- explicit DrawElementD3D9(ServiceLocator* service_locator);
- ~DrawElementD3D9();
-
- private:
-};
-} // o3d
-
-#endif // O3D_CORE_WIN_D3D9_DRAW_ELEMENT_D3D9_H_
diff --git a/o3d/core/win/d3d9/effect_d3d9.cc b/o3d/core/win/d3d9/effect_d3d9.cc
deleted file mode 100644
index 057c55e..0000000
--- a/o3d/core/win/d3d9/effect_d3d9.cc
+++ /dev/null
@@ -1,1224 +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 definition of EffectD3D9.
-
-// TODO(gman): Most of the D3DXHANDLE lookup could be cached.
-
-#include "core/cross/precompile.h"
-
-#include "core/win/d3d9/effect_d3d9.h"
-
-#include "base/scoped_ptr.h"
-#include "core/cross/core_metrics.h"
-#include "core/cross/error.h"
-#include "core/cross/material.h"
-#include "core/cross/renderer_platform.h"
-#include "core/cross/semantic_manager.h"
-#include "core/cross/standard_param.h"
-#include "core/cross/transform.h"
-#include "core/win/d3d9/d3d_entry_points.h"
-#include "core/win/d3d9/primitive_d3d9.h"
-#include "core/win/d3d9/sampler_d3d9.h"
-#include "core/win/d3d9/texture_d3d9.h"
-#include "core/win/d3d9/utils_d3d9.h"
-#include "core/cross/param_array.h"
-
-namespace o3d {
-
-namespace {
-
-inline bool IsSamplerType(D3DXPARAMETER_TYPE type) {
- return type == D3DXPT_SAMPLER ||
- type == D3DXPT_SAMPLER1D ||
- type == D3DXPT_SAMPLER2D ||
- type == D3DXPT_SAMPLER3D ||
- type == D3DXPT_SAMPLERCUBE;
-}
-
-} // anonymous namespace
-
-// A 'mostly' typesafe class to set an effect parameter from an O3D
-// Param. The phandle must match the type of Param to be typesafe. That is
-// handled when these are created.
-template<typename ParamType, D3DXPARAMETER_CLASS d3d_parameter_class>
-class TypedEffectParamHandlerD3D9 : public EffectParamHandlerD3D9 {
- public:
- TypedEffectParamHandlerD3D9(ParamType* param, D3DXHANDLE phandle)
- : param_(param),
- phandle_(phandle) {
- }
- virtual void SetEffectParam(RendererD3D9* renderer, ID3DXEffect* d3d_effect);
- private:
- ParamType* param_;
- D3DXHANDLE phandle_;
-};
-
-template <typename T>
-class EffectParamArrayHandlerD3D9 : public EffectParamHandlerD3D9 {
- public:
- EffectParamArrayHandlerD3D9(ParamParamArray* param,
- D3DXHANDLE phandle,
- unsigned num_elements)
- : param_(param),
- phandle_(phandle),
- num_elements_(num_elements) {
- }
- virtual void SetEffectParam(RendererD3D9* renderer, ID3DXEffect* d3d_effect) {
- ParamArray* param = param_->value();
- if (param) {
- int size = param->size();
- if (size != num_elements_) {
- O3D_ERROR(param->service_locator())
- << "number of params in ParamArray does not match number of params "
- << "needed by shader array";
- } else {
- for (int i = 0; i < size; ++i) {
- Param* untyped_element = param->GetUntypedParam(i);
- // TODO(gman): Make this check happen when building the param cache.
- // To do that would require that ParamParamArray mark it's owner
- // as changed if a Param in it's ParamArray changes.
- if (untyped_element->IsA(T::GetApparentClass())) {
- D3DXHANDLE dx_element =
- d3d_effect->GetParameterElement(phandle_, i);
- SetElement(d3d_effect, dx_element, down_cast<T*>(untyped_element));
- } else {
- O3D_ERROR(param->service_locator())
- << "Param in ParamArray at index " << i << " is not a "
- << T::GetApparentClassName();
- }
- }
- }
- }
- }
- void SetElement(ID3DXEffect* d3dx_effect,
- D3DXHANDLE dx_element,
- T* element);
-
- private:
- ParamParamArray* param_;
- D3DXHANDLE phandle_;
- unsigned num_elements_;
-};
-
-// Number of h/w sampler units in the same shader using a single sampler.
-// Eight should be enough!
-static const int kMaxUnitsPerSampler = 8;
-
-template <bool column_major>
-class EffectParamMatrix4ArrayHandlerD3D9 : public EffectParamHandlerD3D9 {
- public:
- EffectParamMatrix4ArrayHandlerD3D9(ParamParamArray* param,
- D3DXHANDLE phandle,
- unsigned num_elements)
- : param_(param),
- phandle_(phandle),
- num_elements_(num_elements) {
- }
- virtual void SetEffectParam(RendererD3D9* renderer, ID3DXEffect* d3d_effect) {
- ParamArray* param = param_->value();
- if (param) {
- int size = param->size();
- if (size != num_elements_) {
- O3D_ERROR(param->service_locator())
- << "number of params in ParamArray does not match number of params "
- << "needed by shader array";
- } else {
- for (int i = 0; i < size; ++i) {
- Param* untyped_element = param->GetUntypedParam(i);
- // TODO(gman): Make this check happen when building the param cache.
- // To do that would require that ParamParamArray mark it's owner
- // as changed if a Param in it's ParamArray changes.
- if (untyped_element->IsA(ParamMatrix4::GetApparentClass())) {
- D3DXHANDLE dx_element =
- d3d_effect->GetParameterElement(phandle_, i);
- SetElement(d3d_effect,
- dx_element,
- down_cast<ParamMatrix4*>(untyped_element));
- } else {
- O3D_ERROR(param->service_locator())
- << "Param in ParamArray at index " << i << " is not a "
- << ParamMatrix4::GetApparentClassName();
- }
- }
- }
- }
- }
- void SetElement(ID3DXEffect* d3dx_effect,
- D3DXHANDLE dx_element,
- ParamMatrix4* element);
-
- private:
- ParamParamArray* param_;
- D3DXHANDLE phandle_;
- unsigned num_elements_;
-};
-
-// A class for setting the the appropriate d3d sampler states from an array of
-// o3d Sampler object.
-class EffectParamSamplerArrayHandlerD3D9 : public EffectParamHandlerD3D9 {
- public:
- EffectParamSamplerArrayHandlerD3D9(ParamParamArray* param,
- D3DXHANDLE phandle,
- const D3DXPARAMETER_DESC& pdesc,
- LPD3DXCONSTANTTABLE fs_constant_table,
- LPDIRECT3DDEVICE9 d3d_device)
- : param_(param),
- phandle_(phandle),
- sampler_unit_index_arrays_(pdesc.Elements) {
- if (!fs_constant_table) {
- DLOG(ERROR) << "Fragment shader constant table is NULL";
- return;
- }
- D3DXHANDLE sampler_array_handle = fs_constant_table->GetConstantByName(
- NULL,
- pdesc.Name);
- if (!sampler_array_handle) {
- DLOG(ERROR) << "Sampler " << pdesc.Name <<
- " not found in fragment shader";
- return;
- }
- for (unsigned ii = 0; ii < pdesc.Elements; ++ii) {
- D3DXHANDLE sampler_handle = fs_constant_table->GetConstantElement(
- sampler_array_handle,
- ii);
- if (!sampler_handle) {
- DLOG(ERROR) << "Sampler " << pdesc.Name << " index " << ii
- << " not found in fragment shader";
- } else {
- D3DXCONSTANT_DESC desc_array[kMaxUnitsPerSampler];
- UINT num_desc = kMaxUnitsPerSampler;
- fs_constant_table->GetConstantDesc(
- sampler_handle, desc_array, &num_desc);
- // We have no good way of querying how many descriptions would really be
- // returned as we're capping the number to kMaxUnitsPerSampler (which
- // should be more than sufficient). If however we do end up with the
- // max number there's a chance that there were actually more so let's
- // log it.
- if (num_desc == kMaxUnitsPerSampler) {
- DLOG(WARNING) << "Number of constant descriptions might have "
- << "exceeded the maximum of " << kMaxUnitsPerSampler;
- }
- SamplerUnitIndexArray& index_array = sampler_unit_index_arrays_[ii];
-
- for (UINT desc_index = 0; desc_index < num_desc; desc_index++) {
- D3DXCONSTANT_DESC constant_desc = desc_array[desc_index];
- if (constant_desc.Class == D3DXPC_OBJECT &&
- IsSamplerType(constant_desc.Type)) {
- index_array.push_back(constant_desc.RegisterIndex);
- }
- }
- if (index_array.empty()) {
- DLOG(ERROR) << "No matching sampler units found for " <<
- pdesc.Name;
- }
- }
- }
- }
-
- virtual void SetEffectParam(RendererD3D9* renderer, ID3DXEffect* d3d_effect) {
- ParamArray* param = param_->value();
- if (param) {
- unsigned size = param->size();
- if (size != sampler_unit_index_arrays_.size()) {
- O3D_ERROR(param->service_locator())
- << "number of params in ParamArray does not match number of params "
- << "needed by shader array";
- } else {
- for (unsigned i = 0; i < size; ++i) {
- SamplerUnitIndexArray& index_array = sampler_unit_index_arrays_[i];
- Param* untyped_element = param->GetUntypedParam(i);
- // TODO(gman): Make this check happen when building the param cache.
- // To do that would require that ParamParamArray mark it's owner
- // as changed if a Param in it's ParamArray changes.
- if (untyped_element->IsA(ParamSampler::GetApparentClass())) {
- D3DXHANDLE dx_element =
- d3d_effect->GetParameterElement(phandle_, i);
- // Find the texture associated with the sampler first.
- Sampler* sampler =
- down_cast<ParamSampler*>(untyped_element)->value();
- if (!sampler) {
- sampler = renderer->error_sampler();
- if (!renderer->error_texture()) {
- O3D_ERROR(param->service_locator())
- << "Missing Sampler for ParamSampler "
- << param->name();
- }
- }
-
- SamplerD3D9* d3d_sampler = down_cast<SamplerD3D9*>(sampler);
- for (unsigned stage = 0; stage < index_array.size(); stage++) {
- d3d_sampler->SetTextureAndStates(index_array[stage]);
- }
- } else {
- O3D_ERROR(param->service_locator())
- << "Param in ParamArray at index " << i << " is not a "
- << ParamSampler::GetApparentClassName();
- }
- }
- }
- }
- }
-
- // Resets the value of the parameter to default. Currently this is used
- // to unbind textures contained in Sampler params.
- virtual void ResetEffectParam(RendererD3D9* renderer,
- ID3DXEffect* d3d_effect) {
- ParamArray* param = param_->value();
- if (param) {
- unsigned size = param->size();
- if (size == sampler_unit_index_arrays_.size()) {
- for (unsigned i = 0; i < size; ++i) {
- SamplerUnitIndexArray& index_array = sampler_unit_index_arrays_[i];
- Param* untyped_element = param->GetUntypedParam(i);
- // TODO(gman): Make this check happen when building the param cache.
- // To do that would require that ParamParamArray mark it's owner
- // as changed if a Param in it's ParamArray changes.
- if (untyped_element->IsA(ParamSampler::GetApparentClass())) {
- D3DXHANDLE dx_element =
- d3d_effect->GetParameterElement(phandle_, i);
- // Find the texture associated with the sampler first.
- Sampler* sampler =
- down_cast<ParamSampler*>(untyped_element)->value();
- if (!sampler) {
- sampler = renderer->error_sampler();
- }
-
- SamplerD3D9* d3d_sampler = down_cast<SamplerD3D9*>(sampler);
- for (unsigned stage = 0; stage < index_array.size(); stage++) {
- d3d_sampler->ResetTexture(index_array[stage]);
- }
- }
- }
- }
- }
- }
-
- private:
- typedef std::vector<int> SamplerUnitIndexArray;
- typedef std::vector<SamplerUnitIndexArray> SamplerIndexArrayArray;
-
- ParamParamArray* param_;
- D3DXHANDLE phandle_;
- // An array of arrays of sampler unit indices.
- SamplerIndexArrayArray sampler_unit_index_arrays_;
-};
-
-template<>
-void EffectParamArrayHandlerD3D9<ParamFloat>::SetElement(
- ID3DXEffect* d3dx_effect,
- D3DXHANDLE dx_element,
- ParamFloat* element) {
- d3dx_effect->SetFloat(dx_element, element->value());
-}
-
-template<>
-void EffectParamArrayHandlerD3D9<ParamFloat2>::SetElement(
- ID3DXEffect* d3dx_effect,
- D3DXHANDLE dx_element,
- ParamFloat2* element) {
- Float2 float2 = element->value();
- HR(d3dx_effect->SetFloatArray(dx_element, float2.GetFloatArray(), 2));
-}
-
-template<>
-void EffectParamArrayHandlerD3D9<ParamFloat3>::SetElement(
- ID3DXEffect* d3dx_effect,
- D3DXHANDLE dx_element,
- ParamFloat3* element) {
- Float3 float3 = element->value();
- HR(d3dx_effect->SetFloatArray(dx_element, float3.GetFloatArray(), 3));
-}
-
-template<>
-void EffectParamArrayHandlerD3D9<ParamFloat4>::SetElement(
- ID3DXEffect* d3dx_effect,
- D3DXHANDLE dx_element,
- ParamFloat4* element) {
- Float4 float4 = element->value();
- HR(d3dx_effect->SetFloatArray(dx_element, float4.GetFloatArray(), 4));
-}
-
-template<>
-void EffectParamArrayHandlerD3D9<ParamBoolean>::SetElement(
- ID3DXEffect* d3dx_effect,
- D3DXHANDLE dx_element,
- ParamBoolean* element) {
- HR(d3dx_effect->SetBool(dx_element, element->value()));
-}
-
-template<>
-void EffectParamArrayHandlerD3D9<ParamInteger>::SetElement(
- ID3DXEffect* d3dx_effect,
- D3DXHANDLE dx_element,
- ParamInteger* element) {
- HR(d3dx_effect->SetInt(dx_element, element->value()));
-}
-
-template<>
-void EffectParamMatrix4ArrayHandlerD3D9<false>::SetElement(
- ID3DXEffect* d3dx_effect,
- D3DXHANDLE dx_element,
- ParamMatrix4* element) {
- Matrix4 param_matrix = element->value();
- HR(d3dx_effect->SetMatrix(
- dx_element,
- reinterpret_cast<D3DXMATRIX*>(&param_matrix[0][0])));
-}
-
-template<>
-void EffectParamMatrix4ArrayHandlerD3D9<true>::SetElement(
- ID3DXEffect* d3dx_effect,
- D3DXHANDLE dx_element,
- ParamMatrix4* element) {
- Matrix4 param_matrix = transpose(element->value());
- HR(d3dx_effect->SetMatrix(
- dx_element,
- reinterpret_cast<D3DXMATRIX*>(&param_matrix[0][0])));
-}
-
-// A class for setting the the appropriate d3d sampler states from a
-// o3d Sampler object.
-class EffectParamHandlerForSamplersD3D9 : public EffectParamHandlerD3D9 {
- public:
- EffectParamHandlerForSamplersD3D9(ParamSampler* sampler_param,
- const D3DXPARAMETER_DESC& pdesc,
- LPD3DXCONSTANTTABLE fs_constant_table,
- LPDIRECT3DDEVICE9 d3d_device);
-
- virtual void SetEffectParam(RendererD3D9* renderer, ID3DXEffect* d3d_effect);
-
- // Resets the value of the parameter to default. Currently this is used
- // to unbind textures contained in Sampler params.
- virtual void ResetEffectParam(RendererD3D9* renderer,
- ID3DXEffect* d3d_effect);
- private:
- ParamSampler* sampler_param_;
- // The number of sampler units using this sampler parameter.
- int number_sampler_units_;
- // An array of sampler unit indices.
- int sampler_unit_index_array_[kMaxUnitsPerSampler];
-};
-
-// Converts a given D3DX parameter description to an O3D Param type,
-// or Param::INVALID if no corresponding type is found.
-static const ObjectBase::Class* D3DXPDescToParamType(
- const D3DXPARAMETER_DESC& pdesc) {
- // Matrix4 Param
- if (pdesc.Type == D3DXPT_FLOAT &&
- pdesc.Columns == 4 &&
- pdesc.Rows == 4) {
- return ParamMatrix4::GetApparentClass();
- // Float Param
- } else if (pdesc.Type == D3DXPT_FLOAT &&
- pdesc.Class == D3DXPC_SCALAR) {
- return ParamFloat::GetApparentClass();
- // Float2 Param
- } else if (pdesc.Type == D3DXPT_FLOAT &&
- pdesc.Class == D3DXPC_VECTOR) {
- if (pdesc.Columns == 1) {
- return ParamFloat::GetApparentClass();
- } else if (pdesc.Columns == 2) {
- return ParamFloat2::GetApparentClass();
- } else if (pdesc.Columns == 3) {
- return ParamFloat3::GetApparentClass();
- } else if (pdesc.Columns == 4) {
- return ParamFloat4::GetApparentClass();
- }
- // Integer param
- } else if (pdesc.Type == D3DXPT_INT &&
- pdesc.Class == D3DXPC_SCALAR &&
- pdesc.Columns == 1) {
- return ParamInteger::GetApparentClass();
- // Boolean param
- } else if (pdesc.Type == D3DXPT_BOOL &&
- pdesc.Class == D3DXPC_SCALAR &&
- pdesc.Columns == 1) {
- return ParamBoolean::GetApparentClass();
- // Texture param
- // TODO(o3d): Texture params should be removed once we switch over to
- // using samplers only.
- } else if (pdesc.Type == D3DXPT_TEXTURE &&
- pdesc.Class == D3DXPC_OBJECT) {
- return ParamTexture::GetApparentClass();
- // Sampler param
- } else if (pdesc.Class == D3DXPC_OBJECT && IsSamplerType(pdesc.Type)) {
- return ParamSampler::GetApparentClass();
- }
- return NULL;
-}
-
-EffectD3D9::EffectD3D9(ServiceLocator* service_locator,
- IDirect3DDevice9* d3d_device)
- : Effect(service_locator),
- semantic_manager_(service_locator->GetService<SemanticManager>()),
- renderer_(static_cast<RendererD3D9*>(
- service_locator->GetService<Renderer>())),
- d3d_device_(d3d_device) {
- DCHECK(d3d_device);
-}
-
-EffectD3D9::~EffectD3D9() {
-}
-
-bool EffectD3D9::PrepareFX(const String& effect,
- String* prepared_effect) {
- String vertex_shader_entry_point;
- String fragment_shader_entry_point;
- MatrixLoadOrder matrix_load_order;
-
- // TODO(o3d): Temporary fix to make GL and D3D match until the shader parser
- // is written.
- if (!ValidateFX(effect,
- &vertex_shader_entry_point,
- &fragment_shader_entry_point,
- &matrix_load_order)) {
- // TODO(o3d): Remove this but for now just let bad ones pass so collada
- // importer works.
- *prepared_effect = effect;
- return false;
- }
-
- *prepared_effect = effect +
- "\n"
- "technique Shaders { "
- " pass p0 { "
- " VertexShader = compile vs_2_0 " + vertex_shader_entry_point + "();"
- " PixelShader = compile ps_2_0 " + fragment_shader_entry_point + "();"
- " }"
- "};";
-
- set_matrix_load_order(matrix_load_order);
-
- return true;
-}
-
-void EffectD3D9::ClearD3D9Effect() {
- set_source("");
- d3d_vertex_shader_ = NULL;
- d3d_fragment_shader_ = NULL;
- fs_constant_table_ = NULL;
- d3dx_effect_ = NULL;
-}
-
-// Initializes the Effect object using the shaders found in an FX formatted
-// string.
-bool EffectD3D9::LoadFromFXString(const String& effect) {
- ClearD3D9Effect();
-
- LPD3DXBUFFER error_buffer;
-
- String prepared_effect;
- // TODO(o3d): Check for failure once shader parser is in.
- PrepareFX(effect, &prepared_effect);
-
- if (!HR(o3d::D3DXCreateEffect(d3d_device_,
- prepared_effect.c_str(),
- (UINT)prepared_effect.size(),
- NULL,
- NULL,
- D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY,
- NULL,
- &d3dx_effect_,
- &error_buffer))) {
- DisplayFXError("FX from String", error_buffer);
- return false;
- }
- if (!InitializeFX()) {
- return false;
- }
-
- // Get metrics for the length of the shader
- UINT data_size = 0;
- if (d3d_vertex_shader_) {
- d3d_vertex_shader_->GetFunction(NULL, &data_size);
- metric_vertex_shader_instruction_count.AddSample(data_size);
- }
- if (d3d_fragment_shader_) {
- d3d_fragment_shader_->GetFunction(NULL, &data_size);
- metric_pixel_shader_instruction_count.AddSample(data_size);
- }
-
- set_source(effect);
- return true;
-}
-
-// Parses a DX9 error buffer and displays a nicely formatted error string
-// in a MessageBox.
-void EffectD3D9::DisplayFXError(const String &header,
- LPD3DXBUFFER error_buffer) {
- String compile_errors_string;
- if (error_buffer) {
- LPVOID compile_errors = error_buffer->GetBufferPointer();
- compile_errors_string = (reinterpret_cast<char*>(compile_errors));
- } else {
- HLOCAL hLocal = NULL;
- FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_ALLOCATE_BUFFER,
- NULL,
- GetLastError(),
- 0,
- reinterpret_cast<wchar_t*>(&hLocal),
- 0,
- NULL);
- wchar_t* msg = reinterpret_cast<wchar_t*>(LocalLock(hLocal));
- std::wstring msg_utf16(msg);
- String msg_utf8 = WideToUTF8(msg_utf16);
-
- compile_errors_string = header + ": " + msg_utf8.c_str();
- LocalFree(hLocal);
- }
- O3D_ERROR(service_locator()) << "Effect Compile Error::"
- << compile_errors_string.c_str();
-}
-
-// Creates the vertex and fragment shaders based on the programs found in the
-// DX9 effect.
-bool EffectD3D9::InitializeFX() {
- bool rc = false;
-
- // we only handle the first technique, for now
- D3DXHANDLE technique = d3dx_effect_->GetTechnique(0);
- if (!technique) {
- DLOG(ERROR) << "Failed to get technique";
- return false;
- }
-
- D3DXTECHNIQUE_DESC desc;
- if (!HR(d3dx_effect_->GetTechniqueDesc(technique, &desc))) {
- DLOG(ERROR) << "Failed to get technique description";
- return false;
- }
-
- if (desc.Passes != 1) {
- O3D_ERROR(service_locator())
- << "Effect Compile Error: "
- << "Multi-pass shaders are unsupported.";
- return false;
- }
-
- D3DXHANDLE pass = d3dx_effect_->GetPass(technique, 0);
- if (!pass) {
- DLOG(ERROR) << "Failed to get pass";
- return false;
- }
-
- D3DXPASS_DESC pass_desc;
- if (!HR(d3dx_effect_->GetPassDesc(pass, &pass_desc))) {
- DLOG(ERROR) << "Failed to get pass description";
- return false;
- }
-
- if (!HR(d3d_device_->CreateVertexShader(
- pass_desc.pVertexShaderFunction, &d3d_vertex_shader_))) {
- DLOG(ERROR) << "Failed to create vertex shader";
- return false;
- }
-
- if (!HR(d3d_device_->CreatePixelShader(
- pass_desc.pPixelShaderFunction, &d3d_fragment_shader_))) {
- DLOG(ERROR) << "Failed to create pixel shader";
- return false;
- }
-
- // Get the Fragment Shader constant table.
- if (!HR(o3d::D3DXGetShaderConstantTable(
- pass_desc.pPixelShaderFunction,
- &fs_constant_table_))) {
- DLOG(ERROR) << "Failed to get fragment shader constant table";
- return false;
- }
-
- return true;
-}
-
-// Adds a Parameter Mapping from an O3D param to a d3d parameter if they
-// match in type.
-// Parameters:
-// param: Param we are attempting to map.
-// pdesc: d3d parameter description.
-// phandle: Handle to d3d parameter.
-// effect_param_cache: Cache to add mapping to.
-// Returns:
-// true if a mapping was added.
-bool EffectD3D9::AddParameterMapping(
- Param* param,
- const D3DXPARAMETER_DESC& pdesc,
- D3DXHANDLE phandle,
- EffectParamHandlerCacheD3D9* effect_param_cache) {
- // Array param
- if (param->IsA(ParamParamArray::GetApparentClass()) && pdesc.Elements > 0) {
- ParamParamArray* param_param_array = down_cast<ParamParamArray*>(param);
- if (pdesc.Class == D3DXPC_SCALAR &&
- pdesc.Type == D3DXPT_FLOAT) {
- effect_param_cache->AddElement(
- new EffectParamArrayHandlerD3D9<ParamFloat>(
- param_param_array, phandle, pdesc.Elements));
- } else if (pdesc.Class == D3DXPC_VECTOR &&
- pdesc.Type == D3DXPT_FLOAT &&
- pdesc.Columns == 2) {
- effect_param_cache->AddElement(
- new EffectParamArrayHandlerD3D9<ParamFloat2>(
- param_param_array, phandle, pdesc.Elements));
- } else if (pdesc.Class == D3DXPC_VECTOR &&
- pdesc.Type == D3DXPT_FLOAT &&
- pdesc.Columns == 3) {
- effect_param_cache->AddElement(
- new EffectParamArrayHandlerD3D9<ParamFloat3>(
- param_param_array, phandle, pdesc.Elements));
- } else if (pdesc.Class == D3DXPC_VECTOR &&
- pdesc.Type == D3DXPT_FLOAT &&
- pdesc.Columns == 4) {
- effect_param_cache->AddElement(
- new EffectParamArrayHandlerD3D9<ParamFloat4>(
- param_param_array, phandle, pdesc.Elements));
- } else if (pdesc.Class == D3DXPC_SCALAR &&
- pdesc.Type == D3DXPT_INT &&
- pdesc.Columns == 1) {
- effect_param_cache->AddElement(
- new EffectParamArrayHandlerD3D9<ParamInteger>(
- param_param_array, phandle, pdesc.Elements));
- } else if (pdesc.Class == D3DXPC_SCALAR &&
- pdesc.Type == D3DXPT_BOOL &&
- pdesc.Columns == 1) {
- effect_param_cache->AddElement(
- new EffectParamArrayHandlerD3D9<ParamBoolean>(
- param_param_array, phandle, pdesc.Elements));
- } else if (pdesc.Class == D3DXPC_MATRIX_COLUMNS) {
- effect_param_cache->AddElement(
- new EffectParamMatrix4ArrayHandlerD3D9<true>(
- param_param_array, phandle, pdesc.Elements));
- } else if (pdesc.Class == D3DXPC_MATRIX_ROWS) {
- if (matrix_load_order() == COLUMN_MAJOR) {
- // D3D has already created a uniform of type MATRIX_ROWS, but the
- // effect wants column major matrices, so we create a handler
- // for MATRIX_COLUMNS. This will cause the matrix to be transposed
- // on load.
- effect_param_cache->AddElement(
- new EffectParamMatrix4ArrayHandlerD3D9<true>(
- param_param_array, phandle, pdesc.Elements));
- } else {
- effect_param_cache->AddElement(
- new EffectParamMatrix4ArrayHandlerD3D9<false>(
- param_param_array, phandle, pdesc.Elements));
- }
- } else if (pdesc.Class == D3DXPC_OBJECT && IsSamplerType(pdesc.Type)) {
- effect_param_cache->AddElement(
- new EffectParamSamplerArrayHandlerD3D9(
- param_param_array,
- phandle,
- pdesc,
- fs_constant_table_,
- d3d_device_));
- }
- // Matrix4 Param
- } else if (param->IsA(ParamMatrix4::GetApparentClass()) &&
- pdesc.Class == D3DXPC_MATRIX_COLUMNS) {
- effect_param_cache->AddElement(
- new TypedEffectParamHandlerD3D9<ParamMatrix4,
- D3DXPC_MATRIX_COLUMNS>(
- down_cast<ParamMatrix4*>(param), phandle));
- } else if (param->IsA(ParamMatrix4::GetApparentClass()) &&
- pdesc.Class == D3DXPC_MATRIX_ROWS) {
- if (matrix_load_order() == COLUMN_MAJOR) {
- // D3D has already created a uniform of type MATRIX_ROWS, but the
- // effect wants column major matrices, so we create a handler
- // for MATRIX_COLUMNS. This will cause the matrix to be transposed
- // on load.
- effect_param_cache->AddElement(
- new TypedEffectParamHandlerD3D9<ParamMatrix4,
- D3DXPC_MATRIX_COLUMNS>(
- down_cast<ParamMatrix4*>(param), phandle));
- } else {
- effect_param_cache->AddElement(
- new TypedEffectParamHandlerD3D9<ParamMatrix4,
- D3DXPC_MATRIX_ROWS>(
- down_cast<ParamMatrix4*>(param), phandle));
- }
- // Float Param
- } else if (param->IsA(ParamFloat::GetApparentClass()) &&
- pdesc.Class == D3DXPC_SCALAR &&
- pdesc.Type == D3DXPT_FLOAT) {
- effect_param_cache->AddElement(
- new TypedEffectParamHandlerD3D9<ParamFloat,
- D3DXPC_SCALAR>(
- down_cast<ParamFloat*>(param), phandle));
- // Float2 Param
- } else if (param->IsA(ParamFloat2::GetApparentClass()) &&
- pdesc.Class == D3DXPC_VECTOR &&
- pdesc.Type == D3DXPT_FLOAT &&
- pdesc.Columns == 2) {
- effect_param_cache->AddElement(
- new TypedEffectParamHandlerD3D9<ParamFloat2,
- D3DXPC_VECTOR>(
- down_cast<ParamFloat2*>(param), phandle));
- // Float3 Param
- } else if (param->IsA(ParamFloat3::GetApparentClass()) &&
- pdesc.Class == D3DXPC_VECTOR &&
- pdesc.Type == D3DXPT_FLOAT &&
- pdesc.Columns == 3) {
- effect_param_cache->AddElement(
- new TypedEffectParamHandlerD3D9<ParamFloat3,
- D3DXPC_VECTOR>(
- down_cast<ParamFloat3*>(param), phandle));
- // Float4 Param
- } else if (param->IsA(ParamFloat4::GetApparentClass()) &&
- pdesc.Class == D3DXPC_VECTOR &&
- pdesc.Type == D3DXPT_FLOAT &&
- pdesc.Columns == 4) {
- effect_param_cache->AddElement(
- new TypedEffectParamHandlerD3D9<ParamFloat4,
- D3DXPC_VECTOR>(
- down_cast<ParamFloat4*>(param), phandle));
- // Integer param
- } else if (param->IsA(ParamInteger::GetApparentClass()) &&
- pdesc.Class == D3DXPC_SCALAR &&
- pdesc.Type == D3DXPT_INT &&
- pdesc.Columns == 1) {
- effect_param_cache->AddElement(
- new TypedEffectParamHandlerD3D9<ParamInteger,
- D3DXPC_SCALAR>(
- down_cast<ParamInteger*>(param), phandle));
- // Boolean param
- } else if (param->IsA(ParamBoolean::GetApparentClass()) &&
- pdesc.Class == D3DXPC_SCALAR &&
- pdesc.Type == D3DXPT_BOOL &&
- pdesc.Columns == 1) {
- effect_param_cache->AddElement(
- new TypedEffectParamHandlerD3D9<ParamBoolean,
- D3DXPC_SCALAR>(
- down_cast<ParamBoolean*>(param), phandle));
- // Texture param
- // TODO(o3d): The texture param block should be removed once we start
- // using samplers only. In the meantime, we need to create a texture param
- // to be able to handle collada files referencing external fx .
- } else if (param->IsA(ParamTexture::GetApparentClass()) &&
- pdesc.Class == D3DXPC_OBJECT &&
- pdesc.Type == D3DXPT_TEXTURE) {
- effect_param_cache->AddElement(
- new TypedEffectParamHandlerD3D9<ParamTexture,
- D3DXPC_OBJECT>(
- down_cast<ParamTexture*>(param), phandle));
- // Sampler param
- } else if (param->IsA(ParamSampler::GetApparentClass()) &&
- pdesc.Class == D3DXPC_OBJECT && IsSamplerType(pdesc.Type)) {
- effect_param_cache->AddElement(
- new EffectParamHandlerForSamplersD3D9(down_cast<ParamSampler*>(param),
- pdesc,
- fs_constant_table_,
- d3d_device_));
- } else {
- return false;
- }
- return true;
-}
-
-// Loops through all the parameters in the d3dx effect and tries to
-// find matches (by name and type) first in the Transform (param_object1)
-// DrawPrimitive Params (param_object2), then in the Primitive Param
-// (param_object3) then in the Material params and finally in the Effect params.
-// If there exists a Param with the same name as the d3dx effect parameter and a
-// compatible type then a handler is created to update the d3d parameter with
-// the Param.
-void EffectD3D9::UpdateParameterMappings(
- const std::vector<ParamObject*>& param_object_list,
- EffectParamHandlerCacheD3D9* effect_param_cache) {
- // Clear the old ones.
- effect_param_cache->Clear();
- if (d3dx_effect_) {
- // Update all the parameter handles from the effect desc
- D3DXEFFECT_DESC desc;
- d3dx_effect_->GetDesc(&desc);
- for (UINT i = 0; i < desc.Parameters; ++i) {
- D3DXPARAMETER_DESC pdesc;
- D3DXHANDLE phandle = d3dx_effect_->GetParameter(NULL, i);
- d3dx_effect_->GetParameterDesc(phandle, &pdesc);
- Param *param;
- String constant_name(pdesc.Name);
- const ObjectBase::Class* sem_type = NULL;
- if (pdesc.Semantic) {
- sem_type = semantic_manager_->LookupSemantic(pdesc.Semantic);
- }
- bool mapped = false;
- for (unsigned ii = 0; !mapped && ii < param_object_list.size(); ++ii) {
- ParamObject* param_object = param_object_list[ii];
- param = param_object->GetUntypedParam(constant_name);
- if (!param && sem_type) {
- param = param_object->GetUntypedParam(sem_type->name());
- }
- if (param) {
- mapped = AddParameterMapping(param,
- pdesc,
- phandle,
- effect_param_cache);
- }
- }
-
- // If it's still not mapped attempt to map it to the error sampler param.
- // It will fail if it's not a sampler.
- if (!mapped) {
- param = renderer_->error_param_sampler();
- mapped = AddParameterMapping(param,
- pdesc,
- phandle,
- effect_param_cache);
- }
- }
- }
-}
-
-void EffectD3D9::GetParameterInfo(EffectParameterInfoArray* info_array) {
- DCHECK(info_array);
- info_array->clear();
- if (d3dx_effect_) {
- // Add parameters to the Shape for all parameters in the effect
- D3DXEFFECT_DESC desc;
- d3dx_effect_->GetDesc(&desc);
- for (UINT i = 0; i < desc.Parameters; ++i) {
- D3DXPARAMETER_DESC pdesc;
- D3DXHANDLE phandle = d3dx_effect_->GetParameter(NULL, i);
- const ObjectBase::Class* sas_class_type = NULL;
- if (d3dx_effect_->GetParameterDesc(phandle, &pdesc) == S_OK) {
- const ObjectBase::Class* type = D3DXPDescToParamType(pdesc);
- if (type != NULL) {
- if (pdesc.Semantic != NULL &&
- type == ParamMatrix4::GetApparentClass()) {
- sas_class_type = semantic_manager_->LookupSemantic(pdesc.Semantic);
- }
- String semantic((pdesc.Semantic != NULL) ? pdesc.Semantic : "");
- info_array->push_back(EffectParameterInfo(
- pdesc.Name,
- type,
- pdesc.Elements,
- semantic,
- sas_class_type));
- }
- }
- }
- }
-}
-
-void EffectD3D9::GetStreamInfo(EffectStreamInfoArray* info_array) {
- DCHECK(info_array);
- info_array->clear();
- if (d3d_vertex_shader_) {
- UINT size;
- d3d_vertex_shader_->GetFunction(NULL, &size);
- scoped_array<DWORD> function(new DWORD[size]);
- d3d_vertex_shader_->GetFunction(function.get(), &size);
-
- UINT num_semantics;
- HR(o3d::D3DXGetShaderInputSemantics(function.get(),
- NULL,
- &num_semantics));
- scoped_array<D3DXSEMANTIC> semantics(new D3DXSEMANTIC[num_semantics]);
- HR(o3d::D3DXGetShaderInputSemantics(function.get(),
- semantics.get(),
- &num_semantics));
-
- info_array->resize(num_semantics);
- for (UINT i = 0; i < num_semantics; ++i) {
- (*info_array)[i] = EffectStreamInfo(
- SemanticFromDX9UsageType(static_cast<D3DDECLUSAGE>(
- semantics[i].Usage)),
- static_cast<int>(semantics[i].UsageIndex));
- }
- }
-}
-
-template<>
-void TypedEffectParamHandlerD3D9<ParamMatrix4,
- D3DXPC_MATRIX_COLUMNS>::SetEffectParam(
- RendererD3D9* renderer,
- ID3DXEffect* d3dx_effect) {
- Matrix4 param_matrix = transpose(param_->value());
- HR(d3dx_effect->SetMatrix(
- phandle_,
- reinterpret_cast<D3DXMATRIX*>(&param_matrix[0][0])));
-}
-
-template<>
-void TypedEffectParamHandlerD3D9<ParamMatrix4,
- D3DXPC_MATRIX_ROWS>::SetEffectParam(
- RendererD3D9* renderer,
- ID3DXEffect* d3dx_effect) {
- Matrix4 param_matrix = param_->value();
- HR(d3dx_effect->SetMatrix(
- phandle_,
- reinterpret_cast<D3DXMATRIX*>(&param_matrix[0][0])));
-}
-
-template<>
-void TypedEffectParamHandlerD3D9<ParamFloat,
- D3DXPC_SCALAR>::SetEffectParam(
- RendererD3D9* renderer,
- ID3DXEffect* d3dx_effect) {
- HR(d3dx_effect->SetFloat(phandle_, param_->value()));
-}
-
-template<>
-void TypedEffectParamHandlerD3D9<ParamFloat2,
- D3DXPC_VECTOR>::SetEffectParam(
- RendererD3D9* renderer,
- ID3DXEffect* d3dx_effect) {
- Float2 param_float2 = param_->value();
- HR(d3dx_effect->SetFloatArray(
- phandle_,
- param_float2.GetFloatArray(),
- 2));
-}
-
-template<>
-void TypedEffectParamHandlerD3D9<ParamFloat3,
- D3DXPC_VECTOR>::SetEffectParam(
- RendererD3D9* renderer,
- ID3DXEffect* d3dx_effect) {
- Float3 param_float3 = param_->value();
- HR(d3dx_effect->SetFloatArray(
- phandle_,
- param_float3.GetFloatArray(),
- 3));
-}
-
-template<>
-void TypedEffectParamHandlerD3D9<ParamFloat4,
- D3DXPC_VECTOR>::SetEffectParam(
- RendererD3D9* renderer,
- ID3DXEffect* d3dx_effect) {
- Float4 param_float4 = param_->value();
- HR(d3dx_effect->SetFloatArray(
- phandle_,
- param_float4.GetFloatArray(),
- 4));
-}
-
-template<>
-void TypedEffectParamHandlerD3D9<ParamInteger,
- D3DXPC_SCALAR>::SetEffectParam(
- RendererD3D9* renderer,
- ID3DXEffect* d3dx_effect) {
- HR(d3dx_effect->SetInt(phandle_, param_->value()));
-}
-
-template<>
-void TypedEffectParamHandlerD3D9<ParamBoolean,
- D3DXPC_SCALAR>::SetEffectParam(
- RendererD3D9* renderer,
- ID3DXEffect* d3dx_effect) {
- HR(d3dx_effect->SetBool(phandle_, param_->value()));
-}
-
-// TODO(o3d): The following handler should be removed once we switch to
-// using Samplers exclusively.
-template<>
-void TypedEffectParamHandlerD3D9<ParamTexture,
- D3DXPC_OBJECT>::SetEffectParam(
- RendererD3D9* renderer,
- ID3DXEffect* d3dx_effect) {
- Texture* texture = param_->value();
- // TODO(o3d): If texture is NULL then we don't set the texture on the
- // effect to avoid clobbering texture set by the corresponding sampler in
- // the cases where we use samplers. The side-effect of this is that if
- // the texture is not set, we could end up using whatever texture was used
- // by the unit before (instead of black). This handler will be removed
- // once we add support for ColladaFX and samplers so it should be ok.
- if (texture != NULL) {
- IDirect3DBaseTexture9 *d3d_texture = NULL;
- if (!renderer->SafeToBindTexture(texture)) {
- O3D_ERROR(renderer->service_locator())
- << "Attempt to bind texture, " << texture->name() << " when drawing "
- << "to an owned RenderSurface";
- d3d_texture = static_cast<IDirect3DBaseTexture9*>(
- renderer->error_texture()->GetTextureHandle());
- } else {
- d3d_texture =
- static_cast<IDirect3DBaseTexture9*>(texture->GetTextureHandle());
- }
- HR(d3dx_effect->SetTexture(phandle_, d3d_texture));
- }
-}
-
-void EffectParamHandlerForSamplersD3D9::SetEffectParam(
- RendererD3D9* renderer,
- ID3DXEffect* d3dx_effect) {
- // Find the texture associated with the sampler first.
- Sampler* sampler = sampler_param_->value();
- if (!sampler) {
- sampler = renderer->error_sampler();
- if (!renderer->error_texture()) {
- O3D_ERROR(sampler_param_->service_locator())
- << "Missing Sampler for ParamSampler " << sampler_param_->name();
- }
- }
-
- SamplerD3D9* d3d_sampler = down_cast<SamplerD3D9*>(sampler);
- for (int stage = 0; stage < number_sampler_units_; stage++) {
- d3d_sampler->SetTextureAndStates(sampler_unit_index_array_[stage]);
- }
-}
-
-void EffectParamHandlerForSamplersD3D9::ResetEffectParam(
- RendererD3D9* renderer,
- ID3DXEffect* d3dx_effect) {
- Sampler* sampler = sampler_param_->value();
- if (!sampler) {
- sampler = renderer->error_sampler();
- }
-
- SamplerD3D9* d3d_sampler = down_cast<SamplerD3D9*>(sampler);
- for (int stage = 0; stage < number_sampler_units_; stage++) {
- d3d_sampler->ResetTexture(sampler_unit_index_array_[stage]);
- }
-}
-
-// Creates a handler for setting up the d3d9 sampler states based on the values
-// on Sampler object pointed to by the sampler_param. It does a lookup
-// (by name) in the fragment shader constants to determine the index of the
-// texture stage the sampler has been mapped to in hardware. This index
-// will be used when making calls to set the texture and various sampler
-// states at render time.
-EffectParamHandlerForSamplersD3D9::EffectParamHandlerForSamplersD3D9(
- ParamSampler* sampler_param,
- const D3DXPARAMETER_DESC& pdesc,
- LPD3DXCONSTANTTABLE fs_constant_table,
- LPDIRECT3DDEVICE9 d3d_device)
- : sampler_param_(sampler_param),
- number_sampler_units_(0) {
- if (!fs_constant_table) {
- DLOG(ERROR) << "Fragment shader constant table is NULL";
- return;
- }
- D3DXHANDLE sampler_handle = fs_constant_table->GetConstantByName(
- NULL,
- pdesc.Name);
- if (!sampler_handle) {
- DLOG(ERROR) << "Sampler " << pdesc.Name <<
- " not found in fragment shader";
- return;
- }
- D3DXCONSTANT_DESC desc_array[kMaxUnitsPerSampler];
- UINT num_desc = kMaxUnitsPerSampler;
- fs_constant_table->GetConstantDesc(sampler_handle, desc_array, &num_desc);
- // We have no good way of querying how many descriptions would really be
- // returned as we're capping the number to kMaxUnitsPerSampler (which should
- // be more than sufficient). If however we do end up with the max number
- // there's a chance that there were actually more so let's log it.
- if (num_desc == kMaxUnitsPerSampler) {
- DLOG(WARNING) << "Number of constant descriptions might have exceeded "
- << "the maximum of " << kMaxUnitsPerSampler;
- }
- for (UINT desc_index = 0; desc_index < num_desc; desc_index++) {
- D3DXCONSTANT_DESC constant_desc = desc_array[desc_index];
- if (constant_desc.Class == D3DXPC_OBJECT &&
- IsSamplerType(constant_desc.Type)) {
- sampler_unit_index_array_[number_sampler_units_++] =
- constant_desc.RegisterIndex;
- }
- }
- if (number_sampler_units_ == 0) {
- DLOG(ERROR) << "No matching sampler units found for " <<
- pdesc.Name;
- }
-}
-
-// Loops through all the parameters needed by the effect and updates the
-// corresponding uniforms in the d3d Effect
-void EffectD3D9::UpdateShaderConstantsFromEffect(
- const EffectParamHandlerCacheD3D9& effect_param_cache) {
-
- const EffectParamHandlerCacheD3D9::ElementArray& effect_params =
- effect_param_cache.GetElements();
-
- EffectParamHandlerCacheD3D9::ElementArray::size_type end =
- effect_params.size();
- for (EffectParamHandlerCacheD3D9::ElementArray::size_type ii = 0;
- ii != end;
- ++ii) {
- effect_params[ii]->SetEffectParam(renderer_, d3dx_effect_);
- }
-}
-
-// Updates the values of the vertex and fragment shader parameters using the
-// current values of the corresponding Shape Param's and sets the various
-// render states if they are different from the default value.
-void EffectD3D9::PrepareForDraw(
- const EffectParamHandlerCacheD3D9& effect_param_cache) {
- // Patch in the vertex and fragment shader constants using
- // values from the matching Params of the Shape
- if (d3dx_effect_) {
- UpdateShaderConstantsFromEffect(effect_param_cache);
- UINT numpasses;
- d3dx_effect_->SetTechnique(d3dx_effect_->GetTechnique(0));
- HR(d3dx_effect_->Begin(&numpasses, 0));
- HR(d3dx_effect_->BeginPass(0));
- }
-}
-
-// Resets the render states back to their default value.
-void EffectD3D9::PostDraw(
- ParamObject* param_object,
- const EffectParamHandlerCacheD3D9& effect_param_cache) {
- if (d3dx_effect_) {
- HR(d3dx_effect_->EndPass());
- HR(d3dx_effect_->End());
-
- const EffectParamHandlerCacheD3D9::ElementArray& effect_params =
- effect_param_cache.GetElements();
-
- EffectParamHandlerCacheD3D9::ElementArray::size_type end =
- effect_params.size();
- for (EffectParamHandlerCacheD3D9::ElementArray::size_type ii = 0;
- ii != end;
- ++ii) {
- effect_params[ii]->ResetEffectParam(renderer_, d3dx_effect_);
- }
- }
-}
-
-// Handler for lost device. This invalidates the effect for a device reset.
-// Returns true on success.
-bool EffectD3D9::OnLostDevice() {
- if (d3dx_effect_)
- return HR(d3dx_effect_->OnLostDevice());
- else
- return true;
-}
-
-// Handler for reset device. This restores the effect after a device reset.
-// Returns true on success.
-bool EffectD3D9::OnResetDevice() {
- if (d3dx_effect_)
- return HR(d3dx_effect_->OnResetDevice());
- else
- return true;
-}
-
-} // namespace o3d
diff --git a/o3d/core/win/d3d9/effect_d3d9.h b/o3d/core/win/d3d9/effect_d3d9.h
deleted file mode 100644
index 46d1bbc..0000000
--- a/o3d/core/win/d3d9/effect_d3d9.h
+++ /dev/null
@@ -1,203 +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 declaration of the EffectD3D9 class.
-
-#ifndef O3D_CORE_WIN_D3D9_EFFECT_D3D9_H_
-#define O3D_CORE_WIN_D3D9_EFFECT_D3D9_H_
-
-#include <d3d9.h>
-#include <d3dx9.h>
-#include <atlbase.h>
-#include <vector>
-#include "core/cross/effect.h"
-
-interface ID3DXEffect;
-
-namespace o3d {
-
-class Material;
-class ParamObject;
-class RendererD3D9;
-class SemanticManager;
-class ShapeDataD3D9;
-
-// A class to set an effect parameter from an O3D parameter.
-class EffectParamHandlerD3D9 {
- public:
- virtual ~EffectParamHandlerD3D9() { }
-
- // Sets a D3D9 Effect Parameter by an O3D Param.
- virtual void SetEffectParam(RendererD3D9* renderer,
- ID3DXEffect* d3d_effect) = 0;
-
- // Resets a D3D9 Effect parameter to default value. This is currently
- // used to unbind textures contained in Sampler parameters.
- virtual void ResetEffectParam(RendererD3D9* renderer,
- ID3DXEffect* d3d_effect) {}
-};
-
-// This class creates a use limited array of pointers to instances of a certain
-// class. It will destroy this instances when Clear() is called or on
-// destruction. You can only add to the array and clear it. No other operations
-// are supported.
-template <typename T>
-class ClassPointerArray {
- public:
- // Public declaration of the type used to store the array.
- typedef std::vector<T*> ElementArray;
-
- ~ClassPointerArray() {
- Clear();
- }
-
- // Clears the array and delete all the elements it points to.
- void Clear() {
- for (ElementArray::size_type ii = 0; ii < elements_.size(); ++ii) {
- delete elements_[ii];
- }
- elements_.clear();
- }
-
- // Adds an element to the array.
- // Parameters:
- // element: Element to add.
- void AddElement(T* element) {
- elements_.push_back(element);
- }
-
- // Gets a const reference to the elements currently in the array
- // as a const stl::vector& so you can use the array with standard stl
- // operations.
- // Returns:
- // const references to the elements.
- const ElementArray& GetElements() const {
- return elements_;
- }
- private:
- ElementArray elements_;
-};
-
-typedef ClassPointerArray<EffectParamHandlerD3D9> EffectParamHandlerCacheD3D9;
-
-// EffectD3D9 is an implementation of the Effect object for DX9. It provides
-// the API for setting the vertex and framgent shaders for the Effect in HLSL.
-// Currently the two shaders can either be provided separately as HLSL code
-// or together in the DX9 FX format.
-class EffectD3D9 : public Effect {
- public:
- EffectD3D9(ServiceLocator* service_locator, IDirect3DDevice9* d3d_device);
- ~EffectD3D9();
-
- // Reads the vertex and fragment shaders from string in the DX9 FX format.
- // It returns true if the shaders were successfully compiled.
- bool LoadFromFXString(const String& effect);
-
- // Binds the shaders to the device and sets up all the shader parameters using
- // the values from the matching Param's of the ParamObject.
- void PrepareForDraw(const EffectParamHandlerCacheD3D9& effect_param_cache);
-
- // Removes any pipeline state-changes installed during a draw.
- void PostDraw(ParamObject* param_object,
- const EffectParamHandlerCacheD3D9& effect_param_cache);
-
- // Gets info about the parameters this effect needs.
- // Overriden from Effect.
- virtual void GetParameterInfo(EffectParameterInfoArray* info_array);
-
- // Gets info about the parameters this effect needs.
- // Overriden from Effect.
- virtual void GetStreamInfo(EffectStreamInfoArray* info_array);
-
- // Returns a pointer to the DX9 vertex shader.
- IDirect3DVertexShader9* d3d_vertex_shader() const {
- return d3d_vertex_shader_;
- }
-
- // Returns a pointer to the DX9 fragment shader.
- IDirect3DPixelShader9* d3d_fragment_shader() const {
- return d3d_fragment_shader_;
- }
-
- // Updates the binds between the params in the list of param objecst and the
- // shader parameters. The two are matched using their names.
- void UpdateParameterMappings(
- const std::vector<ParamObject*>& param_object_list,
- EffectParamHandlerCacheD3D9* effect_param_cache);
-
- // Handler for lost device. This invalidates the effect for a device reset.
- bool OnLostDevice();
-
- // Handler for reset device. This restores the effect after a device reset.
- bool OnResetDevice();
-
- private:
- void UpdateShaderConstantsFromEffect(
- const EffectParamHandlerCacheD3D9& effect_param_cache);
-
- // Adds a Parameter Mapping from an O3D param to a d3d parameter if they
- // match in type.
- // Parameters:
- // param: Param we are attempting to map.
- // pdesc: d3d parameter description.
- // phandle: Handle to d3d parameter.
- // effect_param_cache: Cache to add mapping to.
- // Returns:
- // true if a mapping was added.
- bool AddParameterMapping(Param* param,
- const D3DXPARAMETER_DESC& pdesc,
- D3DXHANDLE phandle,
- EffectParamHandlerCacheD3D9* effect_param_cache);
-
- bool InitializeFX();
- void DisplayFXError(const String &header, LPD3DXBUFFER error_buffer);
-
- // Prepares o3d effect string by converting to platform specific effect
- // string.
- bool PrepareFX(const String& effect, String* prepared_effect);
-
- // Clears, Frees the D3D9 parts of this effect.
- void ClearD3D9Effect();
-
- SemanticManager* semantic_manager_;
- RendererD3D9* renderer_;
-
- CComPtr<IDirect3DVertexShader9> d3d_vertex_shader_;
- CComPtr<IDirect3DPixelShader9> d3d_fragment_shader_;
- CComPtr<ID3DXConstantTable> fs_constant_table_;
- CComPtr<IDirect3DDevice9> d3d_device_;
- CComPtr<ID3DXEffect> d3dx_effect_;
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_WIN_D3D9_EFFECT_D3D9_H_
diff --git a/o3d/core/win/d3d9/install_check.cc b/o3d/core/win/d3d9/install_check.cc
deleted file mode 100644
index dce002e..0000000
--- a/o3d/core/win/d3d9/install_check.cc
+++ /dev/null
@@ -1,258 +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.
- */
-
-
-// The precompiled header must appear before anything else.
-#include "core/cross/precompile.h"
-
-#include "core/cross/install_check.h"
-
-#include <Windows.h>
-#include <Shlwapi.h>
-#include <tchar.h>
-
-#include <sstream>
-
-#include "base/scoped_ptr.h"
-#include "core/win/d3d9/d3d_entry_points.h"
-
-EXTERN_C IMAGE_DOS_HEADER __ImageBase;
-namespace o3d {
-
-D3DXCreateEffect_Ptr D3DXCreateEffect = NULL;
-D3DXGetShaderInputSemantics_Ptr D3DXGetShaderInputSemantics = NULL;
-D3DXCreateEffectCompilerFromFileW_Ptr D3DXCreateEffectCompilerFromFileW = NULL;
-D3DXCreateEffectCompilerFromFileA_Ptr D3DXCreateEffectCompilerFromFileA = NULL;
-D3DXSaveSurfaceToFileW_Ptr D3DXSaveSurfaceToFileW = NULL;
-D3DXSaveSurfaceToFileA_Ptr D3DXSaveSurfaceToFileA = NULL;
-D3DXGetShaderConstantTable_Ptr D3DXGetShaderConstantTable = NULL;
-D3DXCreateFontA_Ptr D3DXCreateFontA = NULL;
-D3DXCreateFontW_Ptr D3DXCreateFontW = NULL;
-D3DXCreateLine_Ptr D3DXCreateLine = NULL;
-Direct3DCreate9_Ptr Direct3DCreate9Software = NULL;
-
-static HINSTANCE g_d3dx = NULL;
-static HINSTANCE g_d3d9_software = NULL;
-
-namespace {
-
-void RendererCleanupAllVariables() {
- D3DXCreateEffect = NULL;
- D3DXGetShaderInputSemantics = NULL;
- D3DXCreateEffectCompilerFromFileW = NULL;
- D3DXCreateEffectCompilerFromFileA = NULL;
- D3DXSaveSurfaceToFileW = NULL;
- D3DXSaveSurfaceToFileA = NULL;
- D3DXGetShaderConstantTable = NULL;
- D3DXCreateFontW = NULL;
- D3DXCreateFontA = NULL;
- D3DXCreateLine = NULL;
-
- if (g_d3dx) {
- FreeLibrary(g_d3dx);
- g_d3dx = NULL;
- }
-
- if (g_d3d9_software) {
- FreeLibrary(g_d3d9_software);
- g_d3d9_software = NULL;
- }
-}
-
-bool GetModuleDirectory(TCHAR* path, std::string* error) {
- ::GetModuleFileName((HINSTANCE)&__ImageBase, path, _MAX_PATH);
- // Trim off the module filename, leaving the path to the directory containing
- // the module.
- if (!PathRemoveFileSpec(path)) {
- *error = "Failed to compute plugin directory base.";
- return false;
- }
-
- return true;
-}
-
-bool D3DX9InstallCheck(std::string* error) {
- scoped_array<TCHAR> dll_path(new TCHAR[_MAX_PATH]);
- if (!GetModuleDirectory(dll_path.get(), error)) {
- return false;
- }
-
- if (!PathAppend(dll_path.get(),
- _T(O3D_PLUGIN_EXTRAS_DIRECTORY) _T("\\d3dx9_36.dll"))) {
- *error = "Failed to compute location of d3dx9_36.dll.";
- return false;
- }
- g_d3dx = LoadLibrary(dll_path.get());
- if (!g_d3dx) { // Last-ditch "Is this anywhere?" check.
- g_d3dx = LoadLibrary(_T("d3dx9_36.dll"));
- }
- if (!g_d3dx) {
- std::stringstream error_code_str;
- error_code_str << GetLastError();
- *error = "Got error " + error_code_str.str() + " loading d3dx9 library.";
- return false;
- }
-
- D3DXCreateEffect = reinterpret_cast<D3DXCreateEffect_Ptr>(
- GetProcAddress(g_d3dx, "D3DXCreateEffect"));
- if (D3DXCreateEffect == NULL) {
- RendererCleanupAllVariables();
- *error = "Failed to load D3DXCreateEffect.";
- return false;
- }
-
- D3DXGetShaderInputSemantics =
- reinterpret_cast<D3DXGetShaderInputSemantics_Ptr>(
- GetProcAddress(g_d3dx, "D3DXGetShaderInputSemantics"));
- if (D3DXGetShaderInputSemantics == NULL) {
- RendererCleanupAllVariables();
- *error = "Failed to load D3DXGetShaderInputSemantics.";
- return false;
- }
-
- D3DXCreateEffectCompilerFromFileW =
- reinterpret_cast<D3DXCreateEffectCompilerFromFileW_Ptr>(
- GetProcAddress(g_d3dx, "D3DXCreateEffectCompilerFromFileW"));
- if (D3DXCreateEffectCompilerFromFileW == NULL) {
- RendererCleanupAllVariables();
- *error = "Failed to load D3DXCreateEffectCompilerFromFileW.";
- return false;
- }
-
- D3DXCreateEffectCompilerFromFileA =
- reinterpret_cast<D3DXCreateEffectCompilerFromFileA_Ptr>(
- GetProcAddress(g_d3dx, "D3DXCreateEffectCompilerFromFileA"));
- if (D3DXCreateEffectCompilerFromFileA == NULL) {
- RendererCleanupAllVariables();
- *error = "Failed to load D3DXCreateEffectCompilerFromFileA.";
- return false;
- }
-
- D3DXSaveSurfaceToFileW =
- reinterpret_cast<D3DXSaveSurfaceToFileW_Ptr>(
- GetProcAddress(g_d3dx, "D3DXSaveSurfaceToFileW"));
- if (D3DXSaveSurfaceToFileW == NULL) {
- RendererCleanupAllVariables();
- *error = "Failed to load D3DXSaveSurfaceToFileW.";
- return false;
- }
-
- D3DXSaveSurfaceToFileA =
- reinterpret_cast<D3DXSaveSurfaceToFileA_Ptr>(
- GetProcAddress(g_d3dx, "D3DXSaveSurfaceToFileA"));
- if (D3DXSaveSurfaceToFileA == NULL) {
- RendererCleanupAllVariables();
- *error = "Failed to load D3DXSaveSurfaceToFileA.";
- return false;
- }
-
- D3DXGetShaderConstantTable =
- reinterpret_cast<D3DXGetShaderConstantTable_Ptr>(
- GetProcAddress(g_d3dx, "D3DXGetShaderConstantTable"));
- if (D3DXGetShaderConstantTable == NULL) {
- RendererCleanupAllVariables();
- *error = "Failed to load D3DXGetShaderConstantTable.";
- return false;
- }
-
- D3DXCreateFontW = reinterpret_cast<D3DXCreateFontW_Ptr>(
- GetProcAddress(g_d3dx, "D3DXCreateFontW"));
- if (D3DXCreateFontW == NULL) {
- RendererCleanupAllVariables();
- *error = "Failed to load D3DXCreateFontW.";
- return false;
- }
-
- D3DXCreateFontA = reinterpret_cast<D3DXCreateFontW_Ptr>(
- GetProcAddress(g_d3dx, "D3DXCreateFontA"));
- if (D3DXCreateFontA == NULL) {
- RendererCleanupAllVariables();
- *error = "Failed to load D3DXCreateFontA.";
- return false;
- }
-
- D3DXCreateLine = reinterpret_cast<D3DXCreateLine_Ptr>(
- GetProcAddress(g_d3dx, "D3DXCreateLine"));
- if (D3DXCreateLine == NULL) {
- RendererCleanupAllVariables();
- *error = "Failed to load D3DXCreateLine.";
- return false;
- }
-
- return true;
-}
-
-bool D3D9SoftwareInstallCheck(std::string* error) {
- scoped_array<TCHAR> dll_path(new TCHAR[_MAX_PATH]);
- if (!GetModuleDirectory(dll_path.get(), error)) {
- return false;
- }
-
- if (!PathAppend(dll_path.get(),
- _T(O3D_PLUGIN_EXTRAS_DIRECTORY)
- _T("\\swiftshader_d3d9.dll"))) {
- *error = "Failed to compute new software renderer location.";
- return false;
- }
-
- g_d3d9_software = LoadLibrary(dll_path.get());
- if (!g_d3d9_software) {
- *error = "Failed to load software renderer.";
- return false;
- }
-
- Direct3DCreate9Software = reinterpret_cast<Direct3DCreate9_Ptr>(
- GetProcAddress(g_d3d9_software, "Direct3DCreate9"));
- if (Direct3DCreate9Software == NULL) {
- *error = "Failed to locate Direct3DCreate9 in software renderer.";
- return false;
- }
-
- return true;
-}
-
-} // namespace anonymous
-
-bool RendererInstallCheck(std::string *error) {
- if (g_d3dx) {
- return true; // Already done.
- }
- if (!D3DX9InstallCheck(error)) {
- return false;
- }
-
- // Failure to find the software renderer is not an error at this point.
- D3D9SoftwareInstallCheck(error);
-
- return true;
-}
-
-} // namespace o3d
diff --git a/o3d/core/win/d3d9/param_cache_d3d9.cc b/o3d/core/win/d3d9/param_cache_d3d9.cc
deleted file mode 100644
index 2610a02..0000000
--- a/o3d/core/win/d3d9/param_cache_d3d9.cc
+++ /dev/null
@@ -1,83 +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 definition of the ParamCacheD3D9 class.
-
-#include "core/cross/precompile.h"
-#include "core/win/d3d9/param_cache_d3d9.h"
-#include "core/win/d3d9/effect_d3d9.h"
-#include "core/cross/element.h"
-#include "core/cross/draw_element.h"
-
-namespace o3d {
-
-ParamCacheD3D9::ParamCacheD3D9(ServiceLocator* service_locator)
- : semantic_manager_(service_locator->GetService<SemanticManager>()),
- last_vertex_shader_(NULL),
- last_fragment_shader_(NULL) {
-}
-
-bool ParamCacheD3D9::ValidateEffect(Effect* effect) {
- DLOG_ASSERT(effect);
-
- EffectD3D9* effect_d3d9 = down_cast<EffectD3D9*>(effect);
- IDirect3DVertexShader9* vertex_shader = effect_d3d9->d3d_vertex_shader();
- IDirect3DPixelShader9* fragment_shader = effect_d3d9->d3d_fragment_shader();
-
- return (last_fragment_shader_ == fragment_shader ||
- last_vertex_shader_ == vertex_shader);
-}
-
-void ParamCacheD3D9::UpdateCache(Effect* effect,
- DrawElement* draw_element,
- Element* element,
- Material* material,
- ParamObject* override) {
- DLOG_ASSERT(effect);
- EffectD3D9* effect_d3d9 = down_cast<EffectD3D9*>(effect);
-
- std::vector<ParamObject*> param_object_list;
- param_object_list.push_back(override);
- param_object_list.push_back(draw_element);
- param_object_list.push_back(element);
- param_object_list.push_back(material);
- param_object_list.push_back(effect);
- param_object_list.push_back(semantic_manager_->sas_param_object());
-
- effect_d3d9->UpdateParameterMappings(param_object_list,
- &cached_effect_params_);
-
- last_vertex_shader_ = effect_d3d9->d3d_vertex_shader();
- last_fragment_shader_ = effect_d3d9->d3d_fragment_shader();}
-
-} // namespace o3d
-
diff --git a/o3d/core/win/d3d9/param_cache_d3d9.h b/o3d/core/win/d3d9/param_cache_d3d9.h
deleted file mode 100644
index d1e710d..0000000
--- a/o3d/core/win/d3d9/param_cache_d3d9.h
+++ /dev/null
@@ -1,74 +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 declaration of the ParamCacheD3D9 class.
-
-#ifndef O3D_CORE_WIN_D3D9_PARAM_CACHE_D3D9_H_
-#define O3D_CORE_WIN_D3D9_PARAM_CACHE_D3D9_H_
-
-#include <d3d9.h>
-#include <atlbase.h>
-#include "core/cross/param_cache.h"
-#include "core/win/d3d9/effect_d3d9.h"
-#include "core/cross/semantic_manager.h"
-
-namespace o3d {
-
-class ParamCacheD3D9 : public ParamCache {
- public:
- explicit ParamCacheD3D9(ServiceLocator* service_locator);
-
- // Overridden from ParamCache.
- virtual void UpdateCache(Effect* effect,
- DrawElement* draw_element,
- Element* element,
- Material* material,
- ParamObject* override);
-
- const EffectParamHandlerCacheD3D9& cached_effect_params() {
- return cached_effect_params_;
- };
- protected:
- // Overridden from ParamCache
- // Validates platform specific information about the effect.
- virtual bool ValidateEffect(Effect* effect);
-
- private:
- EffectParamHandlerCacheD3D9 cached_effect_params_;
- SemanticManager* semantic_manager_;
-
- CComPtr<IDirect3DVertexShader9> last_vertex_shader_;
- CComPtr<IDirect3DPixelShader9> last_fragment_shader_;
-};
-} // o3d
-
-#endif // O3D_CORE_WIN_D3D9_PARAM_CACHE_D3D9_H_
diff --git a/o3d/core/win/d3d9/primitive_d3d9.cc b/o3d/core/win/d3d9/primitive_d3d9.cc
deleted file mode 100644
index a9492c7..0000000
--- a/o3d/core/win/d3d9/primitive_d3d9.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.
- */
-
-
-// This file contains the definition of PrimitiveD3D9.
-
-#include "core/cross/precompile.h"
-
-#include "core/win/d3d9/primitive_d3d9.h"
-
-#include "core/cross/buffer.h"
-#include "core/cross/param_cache.h"
-#include "core/cross/renderer.h"
-#include "core/cross/error.h"
-#include "core/win/d3d9/buffer_d3d9.h"
-#include "core/win/d3d9/d3d_entry_points.h"
-#include "core/win/d3d9/draw_element_d3d9.h"
-#include "core/win/d3d9/effect_d3d9.h"
-#include "core/win/d3d9/param_cache_d3d9.h"
-#include "core/win/d3d9/stream_bank_d3d9.h"
-#include "core/win/d3d9/utils_d3d9.h"
-
-// Someone defines min, conflicting with std::min
-#ifdef min
-#undef min
-#endif
-
-namespace o3d {
-
-PrimitiveD3D9::PrimitiveD3D9(ServiceLocator* service_locator,
- IDirect3DDevice9* d3d_device)
- : Primitive(service_locator),
- d3d_device_(d3d_device) {
- DCHECK(d3d_device);
-}
-
-PrimitiveD3D9::~PrimitiveD3D9() {
-}
-
-// Binds the vertex and index streams required to draw the shape. If the
-// vertex or fragment programs have changed since the last time this method
-// was called (or it's the first time it's getting called) then it forces
-// an update of the mapping between the Material's Params and the shader
-// parameters and also fills in for any missing streams.
-void PrimitiveD3D9::PlatformSpecificRender(Renderer* renderer,
- DrawElement* draw_element,
- Material* material,
- ParamObject* override,
- ParamCache* param_cache) {
- DLOG_ASSERT(param_cache != NULL);
- DLOG_ASSERT(material != NULL);
- ParamCacheD3D9* param_cache_d3d9 = down_cast<ParamCacheD3D9*>(param_cache);
-
- if (!material) {
- O3D_ERROR(service_locator())
- << "No material on Primitive '" << name() << "'";
- return;
- }
-
- EffectD3D9* effect_d3d9 = down_cast<EffectD3D9*>(material->effect());
- DLOG_ASSERT(effect_d3d9);
- StreamBankD3D9* stream_bank_d3d9 = down_cast<StreamBankD3D9*>(stream_bank());
- DLOG_ASSERT(stream_bank_d3d9);
-
- DrawElementD3D9* draw_element_d3d9 = down_cast<DrawElementD3D9*>(
- draw_element);
-
- IDirect3DVertexShader9* vshader = effect_d3d9->d3d_vertex_shader();
- IDirect3DPixelShader9* fshader = effect_d3d9->d3d_fragment_shader();
-
- if (!param_cache_d3d9->ValidateAndCacheParams(effect_d3d9,
- draw_element_d3d9,
- this,
- stream_bank_d3d9,
- material,
- override)) {
- Stream::Semantic missing_semantic;
- int missing_semnatic_index;
- if (!stream_bank_d3d9->CheckForMissingVertexStreams(
- effect_d3d9,
- &missing_semantic,
- &missing_semnatic_index)) {
- param_cache_d3d9->ClearParamCache();
- O3D_ERROR(service_locator())
- << "Required Stream "
- << Stream::GetSemanticDescription(missing_semantic) << ":"
- << missing_semnatic_index << " missing on Primitive '" << name()
- << "' using Material '" << material->name()
- << "' with Effect '" << effect_d3d9->name() << "'";
- return;
- }
- }
-
- if (indexed()) {
- // Set the index stream
- IndexBufferD3D9* index_buffer_d3d9 =
- down_cast<IndexBufferD3D9*>(index_buffer());
- unsigned int max_indices = index_buffer_d3d9->num_elements();
- unsigned int index_count;
-
- if (!Primitive::GetIndexCount(primitive_type_,
- number_primitives_,
- &index_count)) {
- O3D_ERROR(service_locator())
- << "Unknown Primitive Type in GetIndexCount: "
- << primitive_type_ << ". Skipping primitive "
- << name();
- return;
- }
- if (index_count > max_indices) {
- O3D_ERROR(service_locator())
- << "Trying to draw with " << index_count
- << " indices when only " << max_indices
- << " are available in the buffer. Skipping primitive " << name();
- return;
- }
- // TODO: Also check that indices in the index buffer are less than
- // max_vertices_. Needs support from the index buffer (scan indices on
- // Unlock).
- HR(d3d_device_->SetIndices(index_buffer_d3d9->d3d_buffer()));
- }
-
- // Make sure our streams are up to date (skinned, etc..)
- stream_bank_d3d9->UpdateStreams();
-
- // Get all the vertex streams associated with the shape
- unsigned int max_vertices;
- if (!stream_bank_d3d9->BindStreamsForRendering(&max_vertices)) {
- return;
- }
-
- // TODO: move these checks at 'set' time instead of draw time.
-
- // Check the max number of vertices. Do this after InsertMissingVertexStreams
- // happenned because it may modify the list of streams, thus max_vertices_.
- if (number_vertices_ > max_vertices) {
- O3D_ERROR(service_locator())
- << "Trying to draw with " << number_vertices_
- << " vertices when there are only " << max_vertices
- << " available in the buffers. Skipping primitive " << name();
- return;
- }
-
- // Setup the shaders in the effect
- if (effect_d3d9) {
- effect_d3d9->PrepareForDraw(param_cache_d3d9->cached_effect_params());
- }
-
- // Draw the appropriate primitive
- D3DPRIMITIVETYPE d3d_primitive_type;
- switch (primitive_type()) {
- case Primitive::POINTLIST:
- if (indexed()) {
- O3D_ERROR(service_locator())
- << "POINTLIST unsupported for indexed primitives for primitive "
- << name();
- return;
- } else {
- d3d_primitive_type = D3DPT_POINTLIST;
- break;
- }
- case Primitive::LINELIST:
- d3d_primitive_type = D3DPT_LINELIST;
- break;
- case Primitive::LINESTRIP:
- d3d_primitive_type = D3DPT_LINESTRIP;
- break;
- case Primitive::TRIANGLELIST:
- d3d_primitive_type = D3DPT_TRIANGLELIST;
- break;
- case Primitive::TRIANGLESTRIP:
- d3d_primitive_type = D3DPT_TRIANGLESTRIP;
- break;
- case Primitive::TRIANGLEFAN:
- d3d_primitive_type = D3DPT_TRIANGLEFAN;
- break;
- default:
- O3D_ERROR(service_locator())
- << "Unknown Primitive Type in Primitive: "
- << primitive_type() << " for primitive "
- << name();
- return;
- }
- renderer->AddPrimitivesRendered(number_primitives_);
-
- if (indexed()) {
- d3d_device_->DrawIndexedPrimitive(d3d_primitive_type,
- 0,
- 0,
- number_vertices_,
- start_index_,
- number_primitives_);
- } else {
- d3d_device_->DrawPrimitive(
- d3d_primitive_type, start_index_, number_primitives_);
- }
-
- if (effect_d3d9) {
- effect_d3d9->PostDraw(this, param_cache_d3d9->cached_effect_params());
- }
-}
-
-} // namespace o3d
diff --git a/o3d/core/win/d3d9/primitive_d3d9.h b/o3d/core/win/d3d9/primitive_d3d9.h
deleted file mode 100644
index 7a97d84..0000000
--- a/o3d/core/win/d3d9/primitive_d3d9.h
+++ /dev/null
@@ -1,66 +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 declaration of the PrimitiveD3D9 class.
-
-#ifndef O3D_CORE_WIN_D3D9_PRIMITIVE_D3D9_H_
-#define O3D_CORE_WIN_D3D9_PRIMITIVE_D3D9_H_
-
-#include <d3d9.h>
-#include <atlbase.h>
-#include "core/cross/primitive.h"
-#include "core/win/d3d9/effect_d3d9.h"
-
-namespace o3d {
-
-// PrimitiveD3D9 is the DX9 implementation of the Primitive. It provides the
-// necessary interfaces for setting the geometry streams on the Primitive.
-class PrimitiveD3D9 : public Primitive {
- public:
- explicit PrimitiveD3D9(ServiceLocator* service_locator,
- IDirect3DDevice9* d3d_device);
- ~PrimitiveD3D9();
-
- protected:
- // Overridden from Primitive.
- virtual void PlatformSpecificRender(Renderer* renderer,
- DrawElement* draw_element,
- Material* material,
- ParamObject* override,
- ParamCache* param_cache);
-
- private:
- CComPtr<IDirect3DDevice9> d3d_device_;
-};
-} // o3d
-
-#endif // O3D_CORE_WIN_D3D9_PRIMITIVE_D3D9_H_
diff --git a/o3d/core/win/d3d9/render_surface_d3d9.cc b/o3d/core/win/d3d9/render_surface_d3d9.cc
deleted file mode 100644
index c291887..0000000
--- a/o3d/core/win/d3d9/render_surface_d3d9.cc
+++ /dev/null
@@ -1,153 +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 "core/cross/precompile.h"
-#include "core/win/d3d9/render_surface_d3d9.h"
-#include "core/win/d3d9/utils_d3d9.h"
-#include "core/win/d3d9/renderer_d3d9.h"
-#include "core/cross/error.h"
-
-namespace o3d {
-
-RenderSurfaceD3D9::RenderSurfaceD3D9(ServiceLocator *service_locator,
- int width,
- int height,
- Texture *texture,
- SurfaceConstructor *surface_constructor)
- : RenderSurface(service_locator, width, height, texture),
- direct3d_surface_(NULL),
- surface_constructor_(surface_constructor) {
- DCHECK(surface_constructor);
- DCHECK(texture);
- // TODO: Won't this crash if it can not create the surface?
- HR(surface_constructor_->ConstructSurface(&direct3d_surface_));
- Clear();
-}
-
-bool RenderSurfaceD3D9::OnLostDevice() {
- direct3d_surface_ = NULL;
- return true;
-}
-
-bool RenderSurfaceD3D9::OnResetDevice() {
- // Reconstruct the surface from the construction object provided by the
- // owning texture.
- HR(surface_constructor_->ConstructSurface(&direct3d_surface_));
- Clear();
- return direct3d_surface_ != NULL;
-}
-
-void RenderSurfaceD3D9::Clear() {
- RendererD3D9* renderer =
- down_cast<RendererD3D9*>(service_locator()->GetService<Renderer>());
- if (direct3d_surface_) {
- renderer->d3d_device()->ColorFill(
- direct3d_surface_, NULL, D3DCOLOR_RGBA(0, 0, 0, 0));
- }
-}
-
-bool RenderSurfaceD3D9::PlatformSpecificGetIntoBitmap(
- Bitmap::Ref bitmap) const {
- DCHECK(bitmap->width() == static_cast<unsigned int>(clip_width()) &&
- bitmap->height() == static_cast<unsigned int>(clip_height()) &&
- bitmap->num_mipmaps() == 1 &&
- bitmap->format() == Texture::ARGB8);
-
- if (!direct3d_surface_) {
- return false;
- }
-
- RendererD3D9* renderer =
- down_cast<RendererD3D9*>(service_locator()->GetService<Renderer>());
- LPDIRECT3DDEVICE9 device = renderer->d3d_device();
- CComPtr<IDirect3DSurface9> system_surface;
-
- D3DSURFACE_DESC surface_description;
- if (!HR(direct3d_surface_->GetDesc(&surface_description))) {
- return false;
- }
-
- if (!HR(device->CreateOffscreenPlainSurface(surface_description.Width,
- surface_description.Height,
- surface_description.Format,
- D3DPOOL_SYSTEMMEM,
- &system_surface,
- NULL))) {
- return false;
- }
-
- if (!HR(device->GetRenderTargetData(direct3d_surface_, system_surface)))
- return false;
-
- RECT rect = { 0, 0, clip_width(), clip_height() };
- D3DLOCKED_RECT out_rect = {0};
- if (!HR(system_surface->LockRect(&out_rect, &rect, D3DLOCK_READONLY))) {
- O3D_ERROR(service_locator()) << "Failed to Lock Surface (D3D9)";
- return false;
- }
-
- bitmap->SetRect(0, 0, 0,
- clip_width(),
- clip_height(),
- out_rect.pBits,
- out_rect.Pitch);
-
- system_surface->UnlockRect();
-
- return true;
-}
-
-RenderDepthStencilSurfaceD3D9::RenderDepthStencilSurfaceD3D9(
- ServiceLocator *service_locator,
- int width,
- int height,
- SurfaceConstructor *surface_constructor)
- : RenderDepthStencilSurface(service_locator, width, height),
- direct3d_surface_(NULL),
- surface_constructor_(surface_constructor) {
- DCHECK(surface_constructor);
- HR(surface_constructor_->ConstructSurface(&direct3d_surface_));
-}
-
-bool RenderDepthStencilSurfaceD3D9::OnLostDevice() {
- direct3d_surface_ = NULL;
- return true;
-}
-
-bool RenderDepthStencilSurfaceD3D9::OnResetDevice() {
- // Reconstruct the surface from the construction object provided by the
- // owning texture.
- HR(surface_constructor_->ConstructSurface(&direct3d_surface_));
- return direct3d_surface_ != NULL;
-}
-
-} // namespace o3d
diff --git a/o3d/core/win/d3d9/render_surface_d3d9.h b/o3d/core/win/d3d9/render_surface_d3d9.h
deleted file mode 100644
index f541e6f..0000000
--- a/o3d/core/win/d3d9/render_surface_d3d9.h
+++ /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.
- */
-
-
-#ifndef O3D_CORE_WIN_D3D9_RENDER_SURFACE_D3D9_H_
-#define O3D_CORE_WIN_D3D9_RENDER_SURFACE_D3D9_H_
-
-#include <d3d9.h>
-#include <atlbase.h>
-#include "core/cross/render_surface.h"
-
-namespace o3d {
-
-// A memento class that is capable of constructing and returning
-// a DirectX surface. It maintains all of the parameters relevant to the
-// construction internally.
-class SurfaceConstructor {
- public:
- SurfaceConstructor() {}
- virtual ~SurfaceConstructor() {}
- virtual HRESULT ConstructSurface(IDirect3DSurface9** surface) = 0;
- private:
- DISALLOW_COPY_AND_ASSIGN(SurfaceConstructor);
-};
-
-class RenderSurfaceD3D9 : public RenderSurface {
- public:
- typedef SmartPointer<RenderSurfaceD3D9> Ref;
-
- RenderSurfaceD3D9(ServiceLocator *service_locator,
- int width,
- int height,
- Texture *texture,
- SurfaceConstructor *surface_constructor);
-
- IDirect3DSurface9* GetSurfaceHandle() const {
- return direct3d_surface_;
- }
-
- // Handler for lost device. This invalidates the render surface for a
- // device reset.
- bool OnLostDevice();
-
- // Handler for reset device. This restores the render surface after a
- // device reset.
- bool OnResetDevice();
-
- // Clears the surface to 0, 0, 0, 0.
- // TODO: Move this to texture, expose it to JavaScript and let
- // the user supply an RGBA color.
- void Clear();
-
- protected:
- // The platform specific part of GetIntoBitmap.
- virtual bool PlatformSpecificGetIntoBitmap(Bitmap::Ref bitmap) const;
-
- private:
- CComPtr<IDirect3DSurface9> direct3d_surface_;
- scoped_ptr<SurfaceConstructor> surface_constructor_;
- DISALLOW_COPY_AND_ASSIGN(RenderSurfaceD3D9);
-};
-
-class RenderDepthStencilSurfaceD3D9 : public RenderDepthStencilSurface {
- public:
- typedef SmartPointer<RenderDepthStencilSurfaceD3D9> Ref;
-
- RenderDepthStencilSurfaceD3D9(ServiceLocator *service_locator,
- int width,
- int height,
- SurfaceConstructor *surface_constructor);
-
- IDirect3DSurface9* GetSurfaceHandle() const {
- return direct3d_surface_;
- }
-
- // Handler for lost device. This invalidates the render surface for a
- // device reset.
- bool OnLostDevice();
-
- // Handler for reset device. This restores the render surface after a
- // device reset.
- bool OnResetDevice();
-
- private:
- CComPtr<IDirect3DSurface9> direct3d_surface_;
- scoped_ptr<SurfaceConstructor> surface_constructor_;
- DISALLOW_COPY_AND_ASSIGN(RenderDepthStencilSurfaceD3D9);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_WIN_D3D9_RENDER_SURFACE_D3D9_H_
diff --git a/o3d/core/win/d3d9/renderer_d3d9.cc b/o3d/core/win/d3d9/renderer_d3d9.cc
deleted file mode 100644
index c0a56af..0000000
--- a/o3d/core/win/d3d9/renderer_d3d9.cc
+++ /dev/null
@@ -1,1747 +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 definition of the RendererD3D9 class.
-
-#include "core/cross/precompile.h"
-#include "core/win/d3d9/renderer_d3d9.h"
-
-#include <vector>
-#include <d3dx9core.h>
-
-#include "core/cross/ierror_status.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/renderer_platform.h"
-#include "core/cross/semantic_manager.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/client_info.h"
-#include "core/cross/shape.h"
-#include "core/cross/features.h"
-#include "core/cross/types.h"
-#include "core/win/d3d9/buffer_d3d9.h"
-#include "core/win/d3d9/d3d_entry_points.h"
-#include "core/win/d3d9/draw_element_d3d9.h"
-#include "core/win/d3d9/effect_d3d9.h"
-#include "core/win/d3d9/param_cache_d3d9.h"
-#include "core/win/d3d9/primitive_d3d9.h"
-#include "core/win/d3d9/render_surface_d3d9.h"
-#include "core/win/d3d9/sampler_d3d9.h"
-#include "core/win/d3d9/software_renderer_d3d9.h"
-#include "core/win/d3d9/stream_bank_d3d9.h"
-#include "core/win/d3d9/texture_d3d9.h"
-#include "core/win/d3d9/utils_d3d9.h"
-
-namespace o3d {
-
-typedef std::vector<Effect*> EffectArray;
-typedef std::vector<RenderSurfaceBase*> RenderSurfaceBaseArray;
-typedef std::vector<State*> StateArray;
-typedef std::vector<Texture*> TextureArray;
-
-namespace {
-
-D3DCMPFUNC ConvertCmpFunc(State::Comparison cmp) {
- switch (cmp) {
- case State::CMP_ALWAYS:
- return D3DCMP_ALWAYS;
- case State::CMP_NEVER:
- return D3DCMP_NEVER;
- case State::CMP_LESS:
- return D3DCMP_LESS;
- case State::CMP_GREATER:
- return D3DCMP_GREATER;
- case State::CMP_LEQUAL:
- return D3DCMP_LESSEQUAL;
- case State::CMP_GEQUAL:
- return D3DCMP_GREATEREQUAL;
- case State::CMP_EQUAL:
- return D3DCMP_EQUAL;
- case State::CMP_NOTEQUAL:
- return D3DCMP_NOTEQUAL;
- default:
- break;
- }
- return D3DCMP_ALWAYS;
-}
-
-D3DFILLMODE ConvertFillMode(State::Fill mode) {
- switch (mode) {
- case State::POINT:
- return D3DFILL_POINT;
- case State::WIREFRAME:
- return D3DFILL_WIREFRAME;
- case State::SOLID:
- return D3DFILL_SOLID;
- default:
- break;
- }
- return D3DFILL_SOLID;
-}
-
-D3DBLEND ConvertBlendFunc(State::BlendingFunction blend_func) {
- switch (blend_func) {
- case State::BLENDFUNC_ZERO:
- return D3DBLEND_ZERO;
- case State::BLENDFUNC_ONE:
- return D3DBLEND_ONE;
- case State::BLENDFUNC_SOURCE_COLOR:
- return D3DBLEND_SRCCOLOR;
- case State::BLENDFUNC_INVERSE_SOURCE_COLOR:
- return D3DBLEND_INVSRCCOLOR;
- case State::BLENDFUNC_SOURCE_ALPHA:
- return D3DBLEND_SRCALPHA;
- case State::BLENDFUNC_INVERSE_SOURCE_ALPHA:
- return D3DBLEND_INVSRCALPHA;
- case State::BLENDFUNC_DESTINATION_ALPHA:
- return D3DBLEND_DESTALPHA;
- case State::BLENDFUNC_INVERSE_DESTINATION_ALPHA:
- return D3DBLEND_INVDESTALPHA;
- case State::BLENDFUNC_DESTINATION_COLOR:
- return D3DBLEND_DESTCOLOR;
- case State::BLENDFUNC_INVERSE_DESTINATION_COLOR:
- return D3DBLEND_INVDESTCOLOR;
- case State::BLENDFUNC_SOURCE_ALPHA_SATUTRATE:
- return D3DBLEND_SRCALPHASAT;
- default:
- break;
- }
- return D3DBLEND_ONE;
-}
-
-D3DBLENDOP ConvertBlendEquation(State::BlendingEquation blend_equation) {
- switch (blend_equation) {
- case State::BLEND_ADD:
- return D3DBLENDOP_ADD;
- case State::BLEND_SUBTRACT:
- return D3DBLENDOP_SUBTRACT;
- case State::BLEND_REVERSE_SUBTRACT:
- return D3DBLENDOP_REVSUBTRACT;
- case State::BLEND_MIN:
- return D3DBLENDOP_MIN;
- case State::BLEND_MAX:
- return D3DBLENDOP_MAX;
- default:
- break;
- }
- return D3DBLENDOP_ADD;
-}
-
-D3DSTENCILOP ConvertStencilOp(State::StencilOperation stencil_func) {
- switch (stencil_func) {
- case State::STENCIL_KEEP:
- return D3DSTENCILOP_KEEP;
- case State::STENCIL_ZERO:
- return D3DSTENCILOP_ZERO;
- case State::STENCIL_REPLACE:
- return D3DSTENCILOP_REPLACE;
- case State::STENCIL_INCREMENT_SATURATE:
- return D3DSTENCILOP_INCRSAT;
- case State::STENCIL_DECREMENT_SATURATE:
- return D3DSTENCILOP_DECRSAT;
- case State::STENCIL_INVERT:
- return D3DSTENCILOP_INVERT;
- case State::STENCIL_INCREMENT:
- return D3DSTENCILOP_INCR;
- case State::STENCIL_DECREMENT:
- return D3DSTENCILOP_DECR;
- default:
- break;
- }
- return D3DSTENCILOP_KEEP;
-}
-
-// Checks that a device will be able to support the given texture formats.
-bool CheckTextureFormatsSupported(LPDIRECT3D9 d3d,
- UINT adapter,
- D3DFORMAT display_format,
- const D3DFORMAT* formats,
- int num_formats) {
- for (int i = 0; i < num_formats; ++i) {
- if (!SUCCEEDED(d3d->CheckDeviceFormat(adapter,
- D3DDEVTYPE_HAL,
- display_format,
- 0,
- D3DRTYPE_TEXTURE,
- formats[i]))) {
- LOG(ERROR) << "Device does not support all required texture formats.";
- return false;
- }
- }
-
- return true;
-}
-
-// Checks that the graphics device meets the necessary minimum requirements.
-// Note that in the current implementation we're being very lenient with the
-// capabilities we require.
-bool CheckDeviceCaps(LPDIRECT3D9 d3d,
- UINT adapter,
- Features* features,
- D3DDISPLAYMODE* d3d_display_mode) {
- D3DCAPS9 d3d_caps;
- if (!HR(d3d->GetDeviceCaps(adapter, D3DDEVTYPE_HAL, &d3d_caps))) {
- LOG(ERROR) << "Failed to get device capabilities.";
- return false;
- }
-
- // Check the version of the pixel and vertex shader programs supported.
- DWORD pixel_shader_version = d3d_caps.PixelShaderVersion;
- if (pixel_shader_version < D3DPS_VERSION(2, 0)) {
- LOG(ERROR) << "Device only supports up to pixel shader version "
- << D3DSHADER_VERSION_MAJOR(pixel_shader_version) << "."
- << D3DSHADER_VERSION_MINOR(pixel_shader_version)
- << ". Version 2.0 is required.";
- return false;
- }
-
- // Check that the device can support textures that are at least 2048x2048.
- DWORD max_texture_height = d3d_caps.MaxTextureHeight;
- DWORD max_texture_width = d3d_caps.MaxTextureWidth;
- DWORD required_texture_size = 2048;
- if (max_texture_height < required_texture_size ||
- max_texture_width < required_texture_size) {
- LOG(ERROR)
- << "Device only supports up to " << max_texture_height << "x"
- << max_texture_width << " textures. " << required_texture_size << "x"
- << required_texture_size << " is required.";
- return false;
- }
-
- if (!HR(d3d->GetAdapterDisplayMode(adapter, d3d_display_mode)))
- return false;
-
- // Check that the device supports all the texture formats needed.
- static D3DFORMAT texture_formats[] = {
- D3DFMT_X8R8G8B8, D3DFMT_A8R8G8B8, D3DFMT_DXT1,
- D3DFMT_DXT3, D3DFMT_DXT5
- };
- if (!CheckTextureFormatsSupported(
- d3d,
- adapter,
- d3d_display_mode->Format,
- texture_formats,
- arraysize(texture_formats))) {
- return false;
- }
- if (features->floating_point_textures()) {
- static D3DFORMAT float_texture_formats[] = {
- D3DFMT_R32F, D3DFMT_A16B16G16R16F, D3DFMT_A32B32G32R32F
- };
- if (!CheckTextureFormatsSupported(
- d3d,
- adapter,
- d3d_display_mode->Format,
- float_texture_formats,
- arraysize(float_texture_formats))) {
- return false;
- }
- }
-
- // Check the device supports the needed indices
- if (features->large_geometry()) {
- if (d3d_caps.MaxVertexIndex < Buffer::MAX_LARGE_INDEX) {
- return false;
- }
- }
-
- // Check render target formats.
- D3DFORMAT render_target_formats[] = { D3DFMT_X8R8G8B8, D3DFMT_A8R8G8B8 };
- const int kNumRenderTargetFormats = arraysize(render_target_formats);
- for (int i = 0; i < kNumRenderTargetFormats; ++i) {
- if (!SUCCEEDED(d3d->CheckDeviceFormat(adapter,
- D3DDEVTYPE_HAL,
- d3d_display_mode->Format,
- D3DUSAGE_RENDERTARGET,
- D3DRTYPE_TEXTURE,
- render_target_formats[i]))) {
- LOG(ERROR) << "Device does not support all required texture formats"
- << " for render targets.";
- return false;
- }
- }
-
- // Check depth stencil formats.
- D3DFORMAT depth_stencil_formats[] = { D3DFMT_D24S8 };
- const int kNumDepthStencilFormats = arraysize(depth_stencil_formats);
- bool success = false;
- for (int i = 0; i < kNumDepthStencilFormats; ++i) {
- if (!SUCCEEDED(d3d->CheckDeviceFormat(adapter,
- D3DDEVTYPE_HAL,
- d3d_display_mode->Format,
- D3DUSAGE_DEPTHSTENCIL,
- D3DRTYPE_SURFACE,
- depth_stencil_formats[i]))) {
- LOG(ERROR) << "Device does not support all required texture formats"
- << " for depth/stencil buffers.";
- return false;
- }
- // Now check that it's compatible with the given backbuffer format.
- if (!SUCCEEDED(d3d->CheckDepthStencilMatch(
- adapter,
- D3DDEVTYPE_HAL,
- d3d_display_mode->Format,
- D3DFMT_A8R8G8B8,
- D3DFMT_D24S8))) {
- LOG(ERROR) << "Device does not support all required texture formats"
- << " for depth/stencil buffers.";
- return false;
- }
- }
-
- return true;
-}
-
-// Find the adapter related to the given monitor.
-// Return true on success, false on error.
-bool GetAdapterFromMonitor(LPDIRECT3D9 d3d,
- HMONITOR monitor,
- UINT* adapter) {
- UINT num_adapters = d3d->GetAdapterCount();
- for (UINT i = 0; i < num_adapters; ++i) {
- HMONITOR adapter_monitor = d3d->GetAdapterMonitor(i);
- if (monitor == adapter_monitor) {
- *adapter = i;
- return true;
- }
- }
- return false;
-}
-
-// Attempt to create a Direct3D9 object supporting the required caps. Return
-// NULL if the object cannot be created or if it does not support the caps.
-Renderer::InitStatus CreateDirect3D(Direct3DCreate9_Ptr d3d_create_function,
- LPDIRECT3D9* d3d,
- HWND window,
- HMONITOR* monitor,
- UINT* adapter,
- Features* features,
- D3DDISPLAYMODE* d3d_display_mode) {
- if (!d3d_create_function) {
- return Renderer::INITIALIZATION_ERROR;
- }
-
- *d3d = d3d_create_function(D3D_SDK_VERSION);
- if (NULL == *d3d) {
- return Renderer::INITIALIZATION_ERROR;
- }
-
- // Get the current monitor and adapter.
- *monitor = MonitorFromWindow(window, MONITOR_DEFAULTTOPRIMARY);
- if (!GetAdapterFromMonitor(*d3d, *monitor, adapter)) {
- DLOG(WARNING) << "Failed to get adapter, use the default one";
- *adapter = D3DADAPTER_DEFAULT;
- }
-
- // Check that the graphics device meets the minimum capabilities.
- if (!CheckDeviceCaps(*d3d, *adapter, features, d3d_display_mode)) {
- (*d3d)->Release();
- *d3d = NULL;
- return Renderer::GPU_NOT_UP_TO_SPEC;
- }
-
- return Renderer::SUCCESS;
-}
-
-// For certain GPU drivers we need to force anti-aliasing off to avoid a
-// a huge performance hit when certain types of windows are used on the same
-// desktop as O3D. This function returns true if O3D is running on one
-// of these GPUs/Drivers.
-bool ForceAntiAliasingOff(LPDIRECT3D9* d3d,
- UINT adapter) {
- D3DADAPTER_IDENTIFIER9 identifier;
- HRESULT hr = (*d3d)->GetAdapterIdentifier(adapter, 0, &identifier);
-
- unsigned int vendor_id = identifier.VendorId;
- unsigned int device_id = identifier.DeviceId;
- unsigned int product = HIWORD(identifier.DriverVersion.HighPart);
- unsigned int version = LOWORD(identifier.DriverVersion.HighPart);
- unsigned int subversion = HIWORD(identifier.DriverVersion.LowPart);
- unsigned int build = LOWORD(identifier.DriverVersion.LowPart);
-
- // Disable ATI drivers 6.14.10.x where x is 6800 or lower.
- if (vendor_id == 4098 && // ATI
- product == 6 &&
- version == 14 &&
- subversion == 10 &&
- build <= 6800) {
- return true;
- }
-
- return false;
-}
-
-// Helper function that gets the D3D Interface, checks the available
-// multisampling modes and selects the most advanced one available to create
-// a D3D Device with a back buffer containing depth and stencil buffers that
-// match the current display device.
-Renderer::InitStatus InitializeD3D9Context(
- HWND window,
- LPDIRECT3D9* d3d,
- LPDIRECT3DDEVICE9* d3d_device,
- D3DPRESENT_PARAMETERS* d3d_present_parameters,
- D3DDISPLAYMODE* d3d_display_mode,
- HMONITOR* monitor,
- UINT* adapter,
- bool fullscreen,
- Features* features,
- ServiceLocator* service_locator,
- int* out_width,
- int* out_height) {
- // Check registry to see if the developer has opted to force the software
- // renderer.
- Renderer::InitStatus status_hardware;
- if (Renderer::IsForceSoftwareRenderer()) {
- // Simulate GPU not up to spec.
- status_hardware = Renderer::GPU_NOT_UP_TO_SPEC;
- } else {
- // Create a hardware device.
- status_hardware = CreateDirect3D(
- Direct3DCreate9,
- d3d,
- window,
- monitor,
- adapter,
- features,
- d3d_display_mode);
- }
-
- if (status_hardware != Renderer::SUCCESS) {
- Renderer::InitStatus status_software = CreateDirect3D(
- Direct3DCreate9Software,
- d3d,
- window,
- monitor,
- adapter,
- features,
- d3d_display_mode);
-
- // We should not be requiring caps that are not supported by the software
- // renderer.
- DCHECK(status_software != Renderer::GPU_NOT_UP_TO_SPEC);
-
- if (status_software != Renderer::SUCCESS) {
- // Report the hardware error. An error with the software renderer should
- // only mean that it is not available, which is normal.
- if (status_hardware == Renderer::INITIALIZATION_ERROR) {
- LOG(ERROR) << "Failed to create the initial D3D9 Interface";
- }
- return status_hardware;
- }
-
- SetupSoftwareRenderer(*d3d);
-
- ClientInfoManager* client_info_manager =
- service_locator->GetService<ClientInfoManager>();
- client_info_manager->SetSoftwareRenderer(true);
- }
-
- // Note: SwapEffect=DISCARD is req. for multisample to function
- ZeroMemory(d3d_present_parameters, sizeof(*d3d_present_parameters));
- d3d_present_parameters->Windowed = !fullscreen;
- d3d_present_parameters->hDeviceWindow = window;
- d3d_present_parameters->SwapEffect = D3DSWAPEFFECT_DISCARD;
- d3d_present_parameters->BackBufferFormat = D3DFMT_A8R8G8B8;
- d3d_present_parameters->EnableAutoDepthStencil = FALSE;
- d3d_present_parameters->AutoDepthStencilFormat = D3DFMT_D24S8;
- d3d_present_parameters->EnableAutoDepthStencil = TRUE;
- // wait for vsync
- d3d_present_parameters->PresentationInterval = D3DPRESENT_INTERVAL_ONE;
-
- if (features->not_anti_aliased() || ForceAntiAliasingOff(d3d, *adapter)) {
- d3d_present_parameters->MultiSampleType = D3DMULTISAMPLE_NONE;
- d3d_present_parameters->MultiSampleQuality = 0;
- } else {
- // query multisampling
- static D3DMULTISAMPLE_TYPE multisample_types[] = {
- D3DMULTISAMPLE_5_SAMPLES,
- D3DMULTISAMPLE_4_SAMPLES,
- D3DMULTISAMPLE_2_SAMPLES,
- D3DMULTISAMPLE_NONE
- };
-
- DWORD multisample_quality = 0;
- for (int i = 0; i < arraysize(multisample_types); ++i) {
- // check back-buffer for multisampling at level "i";
- // back buffer = 32-bit ARGB
- if (SUCCEEDED((*d3d)->CheckDeviceMultiSampleType(
- *adapter,
- D3DDEVTYPE_HAL,
- D3DFMT_A8R8G8B8,
- true, // result is windowed
- multisample_types[i],
- &multisample_quality))) {
- // back buffer succeeded, now check depth-buffer
- // depth buffer = 24-bit, stencil = 8-bit
- // NOTE: 8-bit not 16-bit like the D3DPRESENT_PARAMETERS
- if (SUCCEEDED((*d3d)->CheckDeviceMultiSampleType(
- *adapter,
- D3DDEVTYPE_HAL,
- D3DFMT_D24S8,
- true, // result is windowed
- multisample_types[i],
- &multisample_quality))) {
- d3d_present_parameters->MultiSampleType = multisample_types[i];
- d3d_present_parameters->MultiSampleQuality = multisample_quality - 1;
- break;
- }
- }
- }
- }
-
- // Check if the window size is zero. Some drivers will fail because of that
- // so we'll force a small size in that case.
- {
- RECT windowRect;
- ::GetWindowRect(window, &windowRect);
- int width = windowRect.right - windowRect.left;
- int height = windowRect.bottom - windowRect.top;
-
- *out_width = width;
- *out_height = height;
-
- if (width == 0 || height == 0) {
- d3d_present_parameters->BackBufferWidth = 16;
- d3d_present_parameters->BackBufferHeight = 16;
- *out_width = 16;
- *out_height = 16;
- }
- }
-
- // create the D3D device
- DWORD d3d_behavior_flags = 0;
-
- // Check the device capabilities.
- D3DCAPS9 d3d_caps;
- HRESULT caps_result = (*d3d)->GetDeviceCaps(*adapter,
- D3DDEVTYPE_HAL,
- &d3d_caps);
- if (!HR(caps_result)) {
- return Renderer::INITIALIZATION_ERROR;
- }
-
- // Check if the device supports HW vertex processing.
- if (d3d_caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
- d3d_behavior_flags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
- else
- d3d_behavior_flags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
-
- // D3DCREATE_FPU_PRESERVE is there because Firefox 3 relies on specific FPU
- // flags for its UI rendering. Apparently Firefox 2 is not, though we don't
- // currently propagate that info.
- // TODO: check if FPU_PRESERVE has a significant perf hit, in which
- // case find out if we can disable it for Firefox 2/other browsers, and/or if
- // it makes sense to switch FPU flags before/after every DX call.
- d3d_behavior_flags |= D3DCREATE_FPU_PRESERVE;
- if (!HR((*d3d)->CreateDevice(*adapter,
- D3DDEVTYPE_HAL,
- window,
- d3d_behavior_flags,
- d3d_present_parameters,
- d3d_device))) {
- return Renderer::OUT_OF_RESOURCES;
- }
-
- return Renderer::SUCCESS;
-}
-
-// Helper function that constructs an off-screen surface based on the
-// current state of the d3d_device argument.
-Renderer::InitStatus InitOffscreenSurface(
- LPDIRECT3DDEVICE9 d3d_device,
- IDirect3DSurface9** off_screen_surface) {
- CComPtr<IDirect3DSurface9> current_surface;
- if (!HR(d3d_device->GetRenderTarget(0, &current_surface))) {
- DLOG(ERROR) << "Failed to get offscreen render target.";
- return Renderer::OUT_OF_RESOURCES;
- }
-
- D3DSURFACE_DESC surface_description;
- if (!HR(current_surface->GetDesc(&surface_description))) {
- DLOG(ERROR) << "Failed to get offscreen surface description.";
- return Renderer::INITIALIZATION_ERROR;
- }
-
- CComPtr<IDirect3DSurface9> depth_stencil_surface;
- if (!HR(d3d_device->GetDepthStencilSurface(&depth_stencil_surface)))
- return Renderer::OUT_OF_RESOURCES;
-
- D3DSURFACE_DESC depth_stencil_description;
- if (!HR(depth_stencil_surface->GetDesc(
- &depth_stencil_description))) {
- DLOG(ERROR) << "Failed to get offscreen depth stencil.";
- return Renderer::INITIALIZATION_ERROR;
- }
-
- // create our surface as render target
- if (!HR(d3d_device->CreateRenderTarget(
- surface_description.Width,
- surface_description.Height,
- surface_description.Format,
- surface_description.MultiSampleType,
- surface_description.MultiSampleQuality,
- false,
- off_screen_surface,
- NULL))) {
- DLOG(ERROR) << "Failed to create offscreen renderer.";
- return Renderer::OUT_OF_RESOURCES;
- }
-
- return Renderer::SUCCESS;
-}
-
-namespace {
-template <typename T>
-T LocalMinMax(T value, T min_value, T max_value) {
- return (value < min_value) ? min_value :
- ((value > max_value) ? max_value : value);
-}
-} // namespace anonymous
-
-// Callback class used to construct depth-stencil RenderSurface objects during
-// lost device events. See usage in CreateDepthStencilSurface(...).
-class DepthStencilSurfaceConstructor : public SurfaceConstructor {
- public:
- DepthStencilSurfaceConstructor(ServiceLocator* service_locator,
- int width,
- int height)
- : width_(width),
- height_(height),
- renderer_(service_locator) {}
-
- virtual HRESULT ConstructSurface(IDirect3DSurface9** surface) {
- if (!renderer_.IsAvailable()) {
- return E_FAIL;
- }
-
- RendererD3D9* renderer_d3d9 = static_cast<RendererD3D9*>(renderer_.Get());
- return renderer_d3d9->d3d_device()->CreateDepthStencilSurface(
- width_,
- height_,
- D3DFMT_D24S8,
- D3DMULTISAMPLE_NONE,
- 0,
- FALSE,
- surface,
- NULL);
- }
-
- private:
- // The width and height of the surface to create, respectively.
- int width_;
- int height_;
-
- ServiceDependency<Renderer> renderer_;
- DISALLOW_COPY_AND_ASSIGN(DepthStencilSurfaceConstructor);
-};
-
-} // unnamed namespace
-
-// This class wraps StateHandler to make it typesafe.
-template <typename T>
-class TypedStateHandler : public RendererD3D9::StateHandler {
- public:
- typedef typename T ParamType;
- // Override this function to set a specific state.
- // Parameters:
- // renderer: The platform specific renderer.
- // param: A concrete param with state data.
- virtual void SetStateFromTypedParam(
- RendererD3D9* renderer, T* param) const = 0;
-
- // Gets Class of State's Parameter
- virtual const ObjectBase::Class* GetClass() const {
- return T::GetApparentClass();
- }
-
- private:
- // Calls SetStateFromTypedParam after casting the param to the correct type.
- // The State object guarntees that bad mis-matches do not happe,.
- // Parameters:
- // renderer: The platform specific renderer.
- // param: A param with state data.
- virtual void SetState(Renderer* renderer, Param* param) const {
- RendererD3D9 *renderer_d3d = down_cast<RendererD3D9 *>(renderer);
- // This is safe because State guarntees Params match by type.
- DCHECK(param->IsA(T::GetApparentClass()));
- SetStateFromTypedParam(renderer_d3d, down_cast<T*>(param));
- }
-};
-
-// A template the generates a handler for enable/disable states.
-// Parameters:
-// state_constant: D3DRENDERSTATETYPE of state we want to enable/disable
-template <D3DRENDERSTATETYPE state_constant>
-class StateEnableHandler : public TypedStateHandler<ParamBoolean> {
- public:
- virtual void SetStateFromTypedParam(RendererD3D9* renderer,
- ParamBoolean* param) const {
- HR(renderer->d3d_device()->SetRenderState(state_constant,
- param->value()));
- }
-};
-
-// A template that generates a handler for stencil operation states.
-// Parameters:
-// state_constant: D3DRENDERSTATETYPE of state we want to set.
-template <D3DRENDERSTATETYPE state_constant>
-class StencilOperationHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererD3D9* renderer,
- ParamInteger* param) const {
- HR(renderer->d3d_device()->SetRenderState(
- state_constant,
- ConvertStencilOp(static_cast<State::StencilOperation>(
- param->value()))));
- }
-};
-
-// A template that generates a handler for blend function states.
-// Parameters:
-// state_constant: D3DRENDERSTATETYPE of state we want to set.
-template <D3DRENDERSTATETYPE state_constant>
-class BlendFunctionHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererD3D9* renderer,
- ParamInteger* param) const {
- HR(renderer->d3d_device()->SetRenderState(
- state_constant,
- ConvertBlendFunc(static_cast<State::BlendingFunction>(
- param->value()))));
- }
-};
-
-// A template that generates a handler for blend equation states.
-// Parameters:
-// state_constant: D3DRENDERSTATETYPE of state we want to set.
-template <D3DRENDERSTATETYPE state_constant>
-class BlendEquationHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererD3D9* renderer,
- ParamInteger* param) const {
- HR(renderer->d3d_device()->SetRenderState(
- state_constant,
- ConvertBlendEquation(
- static_cast<State::BlendingEquation>(param->value()))));
- }
-};
-
-// A template that generates a handler for comparison function states.
-// Parameters:
-// state_constant: D3DRENDERSTATETYPE of state we want to set.
-template <D3DRENDERSTATETYPE state_constant>
-class ComparisonFunctionHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererD3D9* renderer,
- ParamInteger* param) const {
- HR(renderer->d3d_device()->SetRenderState(
- state_constant,
- ConvertCmpFunc(static_cast<State::Comparison>(param->value()))));
- }
-};
-
-// A template that generates a handler for integer function states.
-// Parameters:
-// state_constant: D3DRENDERSTATETYPE of state we want to set.
-template <D3DRENDERSTATETYPE state_constant>
-class IntegerStateHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererD3D9* renderer,
- ParamInteger* param) const {
- HR(renderer->d3d_device()->SetRenderState(state_constant,
- param->value()));
- }
-};
-
-class ColorWriteStateHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererD3D9* renderer,
- ParamInteger* param) const {
- int mask = param->value();
- HR(renderer->d3d_device()->SetRenderState(D3DRS_COLORWRITEENABLE, mask));
- renderer->SetWriteMask(mask);
- }
-};
-
-class AlphaReferenceHandler : public TypedStateHandler<ParamFloat> {
- public:
- virtual void SetStateFromTypedParam(RendererD3D9* renderer,
- ParamFloat* param) const {
- float refFloat = LocalMinMax(param->value(), 0.0f, 1.0f);
- int ref = static_cast<int>(refFloat * 255.0f);
-
- HR(renderer->d3d_device()->SetRenderState(D3DRS_ALPHAREF, ref));
- }
-};
-
-class CullModeHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererD3D9* renderer,
- ParamInteger* param) const {
- State::Cull cull = static_cast<State::Cull>(param->value());
- switch (cull) {
- case State::CULL_NONE:
- HR(renderer->d3d_device()->SetRenderState(D3DRS_CULLMODE,
- D3DCULL_NONE));
- break;
- case State::CULL_CW:
- HR(renderer->d3d_device()->SetRenderState(D3DRS_CULLMODE,
- D3DCULL_CW));
- break;
- case State::CULL_CCW:
- HR(renderer->d3d_device()->SetRenderState(D3DRS_CULLMODE,
- D3DCULL_CCW));
- break;
- }
- }
-};
-
-class PointSizeHandler : public TypedStateHandler<ParamFloat> {
- public:
- virtual void SetStateFromTypedParam(RendererD3D9* renderer,
- ParamFloat* param) const {
- Float2DWord offset;
- offset.my_float = param->value();
-
- HR(renderer->d3d_device()->SetRenderState(D3DRS_POINTSIZE,
- offset.my_dword));
- }
-};
-
-class PolygonOffset1Handler : public TypedStateHandler<ParamFloat> {
- public:
- virtual void SetStateFromTypedParam(RendererD3D9* renderer,
- ParamFloat* param) const {
- Float2DWord offset;
- offset.my_float = param->value();
-
- HR(renderer->d3d_device()->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS,
- offset.my_dword));
- }
-};
-
-class PolygonOffset2Handler : public TypedStateHandler<ParamFloat> {
- public:
- virtual void SetStateFromTypedParam(RendererD3D9* renderer,
- ParamFloat* param) const {
- // TODO: this value is hard-coded currently because we only create a
- // 24-bit depth buffer. Move this to a member of RendererD3D9 if it changes.
- const float kUnitScale = 1.f / (1 << 24);
- Float2DWord offset;
- offset.my_float = param->value() * kUnitScale;
-
- HR(renderer->d3d_device()->SetRenderState(D3DRS_DEPTHBIAS,
- offset.my_dword));
- }
-};
-
-class FillModeHandler : public TypedStateHandler<ParamInteger> {
- public:
- virtual void SetStateFromTypedParam(RendererD3D9* renderer,
- ParamInteger* param) const {
- HR(renderer->d3d_device()->SetRenderState(
- D3DRS_FILLMODE,
- ConvertFillMode(static_cast<State::Fill>(param->value()))));
- }
-};
-
-RendererD3D9* RendererD3D9::CreateDefault(ServiceLocator* service_locator) {
- return new RendererD3D9(service_locator);
-}
-
-RendererD3D9::RendererD3D9(ServiceLocator* service_locator)
- : Renderer(service_locator),
- object_manager_(service_locator),
- semantic_manager_(service_locator),
- d3d_(NULL),
- d3d_device_(NULL),
- use_small_index_buffers_(false),
- off_screen_surface_(NULL),
- back_buffer_surface_(NULL),
- back_buffer_depth_surface_(NULL),
- current_d3d_surface_(NULL),
- current_d3d_depth_surface_(NULL),
- have_device_(false),
- fullscreen_(false)
-#ifdef O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
- ,
- fullscreen_message_font_(NULL),
- fullscreen_message_line_(NULL),
- showing_fullscreen_message_(false)
-#endif
-{
- // Setup state handlers
- AddStateHandler(State::kAlphaTestEnableParamName,
- new StateEnableHandler<D3DRS_ALPHATESTENABLE>);
- AddStateHandler(State::kAlphaReferenceParamName,
- new AlphaReferenceHandler);
- AddStateHandler(State::kAlphaComparisonFunctionParamName,
- new ComparisonFunctionHandler<D3DRS_ALPHAFUNC>);
- AddStateHandler(State::kCullModeParamName,
- new CullModeHandler);
- AddStateHandler(State::kDitherEnableParamName,
- new StateEnableHandler<D3DRS_DITHERENABLE>);
- AddStateHandler(State::kLineSmoothEnableParamName,
- new StateEnableHandler<D3DRS_ANTIALIASEDLINEENABLE>);
- AddStateHandler(State::kPointSpriteEnableParamName,
- new StateEnableHandler<D3DRS_POINTSPRITEENABLE>);
- AddStateHandler(State::kPointSizeParamName,
- new PointSizeHandler);
- AddStateHandler(State::kPolygonOffset1ParamName,
- new PolygonOffset1Handler);
- AddStateHandler(State::kPolygonOffset2ParamName,
- new PolygonOffset2Handler);
- AddStateHandler(State::kFillModeParamName,
- new FillModeHandler);
- AddStateHandler(State::kZEnableParamName,
- new StateEnableHandler<D3DRS_ZENABLE>);
- AddStateHandler(State::kZWriteEnableParamName,
- new StateEnableHandler<D3DRS_ZWRITEENABLE>);
- AddStateHandler(State::kZComparisonFunctionParamName,
- new ComparisonFunctionHandler<D3DRS_ZFUNC>);
- AddStateHandler(State::kAlphaBlendEnableParamName,
- new StateEnableHandler<D3DRS_ALPHABLENDENABLE>);
- AddStateHandler(State::kSourceBlendFunctionParamName,
- new BlendFunctionHandler<D3DRS_SRCBLEND>);
- AddStateHandler(State::kDestinationBlendFunctionParamName,
- new BlendFunctionHandler<D3DRS_DESTBLEND>);
- AddStateHandler(State::kStencilEnableParamName,
- new StateEnableHandler<D3DRS_STENCILENABLE>);
- AddStateHandler(State::kStencilFailOperationParamName,
- new StencilOperationHandler<D3DRS_STENCILFAIL>);
- AddStateHandler(State::kStencilZFailOperationParamName,
- new StencilOperationHandler<D3DRS_STENCILZFAIL>);
- AddStateHandler(State::kStencilPassOperationParamName,
- new StencilOperationHandler<D3DRS_STENCILPASS>);
- AddStateHandler(State::kStencilComparisonFunctionParamName,
- new ComparisonFunctionHandler<D3DRS_STENCILFUNC>);
- AddStateHandler(State::kStencilReferenceParamName,
- new IntegerStateHandler<D3DRS_STENCILREF>);
- AddStateHandler(State::kStencilMaskParamName,
- new IntegerStateHandler<D3DRS_STENCILMASK>);
- AddStateHandler(State::kStencilWriteMaskParamName,
- new IntegerStateHandler<D3DRS_STENCILWRITEMASK>);
- AddStateHandler(State::kColorWriteEnableParamName,
- new ColorWriteStateHandler);
- AddStateHandler(State::kBlendEquationParamName,
- new BlendEquationHandler<D3DRS_BLENDOP>);
- AddStateHandler(State::kTwoSidedStencilEnableParamName,
- new StateEnableHandler<D3DRS_TWOSIDEDSTENCILMODE>);
- AddStateHandler(State::kCCWStencilFailOperationParamName,
- new StencilOperationHandler<D3DRS_CCW_STENCILFAIL>);
- AddStateHandler(State::kCCWStencilZFailOperationParamName,
- new StencilOperationHandler<D3DRS_CCW_STENCILZFAIL>);
- AddStateHandler(State::kCCWStencilPassOperationParamName,
- new StencilOperationHandler<D3DRS_CCW_STENCILPASS>);
- AddStateHandler(State::kCCWStencilComparisonFunctionParamName,
- new ComparisonFunctionHandler<D3DRS_CCW_STENCILFUNC>);
- AddStateHandler(State::kSeparateAlphaBlendEnableParamName,
- new StateEnableHandler<D3DRS_SEPARATEALPHABLENDENABLE>);
- AddStateHandler(State::kSourceBlendAlphaFunctionParamName,
- new BlendFunctionHandler<D3DRS_SRCBLENDALPHA>);
- AddStateHandler(State::kDestinationBlendAlphaFunctionParamName,
- new BlendFunctionHandler<D3DRS_DESTBLENDALPHA>);
- AddStateHandler(State::kBlendAlphaEquationParamName,
- new BlendEquationHandler<D3DRS_BLENDOPALPHA>);
-}
-
-RendererD3D9::~RendererD3D9() {
- Destroy();
-}
-
-Renderer::InitStatus RendererD3D9::InitPlatformSpecific(
- const DisplayWindow& display,
- bool off_screen) {
- const DisplayWindowWindows& platform_display =
- static_cast<const DisplayWindowWindows&>(display);
- HWND window = platform_display.hwnd();
- int width;
- int height;
- d3d_ = NULL;
- d3d_device_ = NULL;
- InitStatus init_status = InitializeD3D9Context(
- window,
- &d3d_,
- &d3d_device_,
- &d3d_present_parameters_,
- &d3d_display_mode_,
- &current_monitor_,
- &current_adapter_,
- fullscreen_,
- features(),
- service_locator(),
- &width,
- &height);
- if (init_status != SUCCESS) {
- DLOG(ERROR) << "Failed to initialize D3D9.";
- return init_status;
- }
-
- D3DCAPS9 d3d_caps;
- if (!HR(d3d_->GetDeviceCaps(current_adapter_, D3DDEVTYPE_HAL, &d3d_caps))) {
- DLOG(ERROR) << "Failed to get device capabilities.";
- return INITIALIZATION_ERROR;
- }
-
- // Do we require small index buffers?
- use_small_index_buffers_ = d3d_caps.MaxVertexIndex < 0x10000;
- DCHECK(!use_small_index_buffers_ || !features()->large_geometry());
-
- const unsigned int kNpotFlags =
- D3DPTEXTURECAPS_POW2 | D3DPTEXTURECAPS_CUBEMAP_POW2;
- SetSupportsNPOT((d3d_caps.TextureCaps & kNpotFlags) == 0);
-
- SetClientSize(width, height);
- have_device_ = true;
-
- if (!HR(d3d_->CheckDeviceFormat(current_adapter_,
- D3DDEVTYPE_HAL,
- d3d_display_mode_.Format,
- D3DUSAGE_DEPTHSTENCIL,
- D3DRTYPE_SURFACE,
- D3DFMT_D24S8))) {
- DLOG(ERROR) << "Failed to find compatible depth surface format.";
- Destroy();
- return GPU_NOT_UP_TO_SPEC;
- }
-
- if (off_screen) {
- init_status = InitOffscreenSurface(d3d_device_, &off_screen_surface_);
- if (init_status != SUCCESS) {
- Destroy();
- return init_status;
- }
- }
-
-#ifdef O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
- if (S_OK !=
- D3DXCreateFont(d3d_device_,
- 27 /* font_height */,
- 0 /* font width--0 appears to be "don't care" */,
- FW_BOLD,
- 1 /* MIP levels */,
- FALSE,
- DEFAULT_CHARSET,
- OUT_TT_PRECIS,
- PROOF_QUALITY,
- DEFAULT_PITCH | FF_DONTCARE /* pitch and font family */,
- L"Arial",
- &fullscreen_message_font_)) {
- DLOG(ERROR) << "Failed to initialize font.";
- return INITIALIZATION_ERROR;
- }
-
- if (S_OK !=
- D3DXCreateLine(d3d_device_,
- &fullscreen_message_line_)) {
- DLOG(ERROR) << "Failed to initialize line for message background.";
- return INITIALIZATION_ERROR;
- }
-#endif
-
- return SUCCESS;
-}
-
-// Deletes the D3D9 Device and releases the D3D interface.
-void RendererD3D9::Destroy() {
- off_screen_surface_ = NULL;
- d3d_device_ = NULL;
- d3d_ = NULL;
-}
-
-void RendererD3D9::PlatformSpecificClear(const Float4 &color,
- bool color_flag,
- float depth,
- bool depth_flag,
- int stencil,
- bool stencil_flag) {
- // Conditionally clear the properties of the current render target or back
- // buffer based on the argument flags, and the existence of currently bound
- // buffers.
- if (!HR(d3d_device_->Clear(
- 0,
- NULL,
- ((current_d3d_surface_ && color_flag) ? D3DCLEAR_TARGET : 0) |
- ((current_d3d_depth_surface_ && depth_flag) ? D3DCLEAR_ZBUFFER : 0) |
- ((current_d3d_depth_surface_ && stencil_flag ? D3DCLEAR_STENCIL : 0)),
- D3DCOLOR_COLORVALUE(color[0],
- color[1],
- color[2],
- color[3]),
- depth,
- stencil))) {
- DLOG(ERROR) << "Clear Failed.";
- }
-}
-
-void RendererD3D9::SetViewportInPixels(int left,
- int top,
- int width,
- int height,
- float min_z,
- float max_z) {
- D3DVIEWPORT9 viewport;
-
- viewport.X = left;
- viewport.Y = top;
- viewport.Width = width;
- viewport.Height = height;
- viewport.MinZ = min_z;
- viewport.MaxZ = max_z;
-
- HR(d3d_device_->SetViewport(&viewport));
-}
-
-// Resource allocation methods ------------------------------------------------
-
-// Invalidates all resources which are in D3DPOOL_DEFAULT.
-// Used before we try to reset the device, when the device is lost.
-// (ie when suspending the computer, locking it, etc.)
-// Returns true on success and false on failure.
-bool RendererD3D9::InvalidateDeviceObjects() {
- back_buffer_surface_ = NULL;
- back_buffer_depth_surface_ = NULL;
-
- // Invalidate all effect objects.
- const EffectArray effect_array(object_manager_->GetByClass<Effect>());
- EffectArray::const_iterator p, end(effect_array.end());
- for (p = effect_array.begin(); p != end; ++p) {
- EffectD3D9* effect = down_cast<EffectD3D9*>(*p);
- if (!HR(effect->OnLostDevice()))
- return false;
- }
-
- // Invalidate all Texture and RenderSurface objects.
- const RenderSurfaceBaseArray surface_array(
- object_manager_->GetByClass<RenderSurfaceBase>());
- RenderSurfaceBaseArray::const_iterator surface_iter(surface_array.begin()),
- surface_end(surface_array.end());
- for (;surface_iter != surface_end; ++surface_iter) {
- if ((*surface_iter)->IsA(RenderSurface::GetApparentClass())) {
- RenderSurfaceD3D9* render_surface_d3d9 =
- down_cast<RenderSurfaceD3D9*>(*surface_iter);
- if (!HR(render_surface_d3d9 ->OnLostDevice())) {
- return false;
- }
- } else if ((*surface_iter)->IsA(
- RenderDepthStencilSurface::GetApparentClass())) {
- RenderDepthStencilSurfaceD3D9* render_depth_surface_d3d9 =
- down_cast<RenderDepthStencilSurfaceD3D9*>(*surface_iter);
- if (!HR(render_depth_surface_d3d9 ->OnLostDevice())) {
- return false;
- }
- }
- }
-
- const TextureArray texture_array(object_manager_->GetByClass<Texture>());
- TextureArray::const_iterator texture_iter(texture_array.begin()),
- texture_end(texture_array.end());
- for (;texture_iter != texture_end; ++texture_iter) {
- if ((*texture_iter)->IsA(Texture2D::GetApparentClass())) {
- Texture2DD3D9* texture2d_d3d9 = down_cast<Texture2DD3D9*>(*texture_iter);
- if (!HR(texture2d_d3d9->OnLostDevice())) {
- return false;
- }
- } else if ((*texture_iter)->IsA(TextureCUBE::GetApparentClass())) {
- TextureCUBED3D9* texture_cube_d3d9 =
- down_cast<TextureCUBED3D9*>(*texture_iter);
- if (!HR(texture_cube_d3d9->OnLostDevice())) {
- return false;
- }
- }
- }
-
-#ifdef O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
- if (fullscreen_message_font_ &&
- S_OK != fullscreen_message_font_->OnLostDevice()) {
- return false;
- }
- if (fullscreen_message_line_ &&
- S_OK != fullscreen_message_line_->OnLostDevice()) {
- return false;
- }
-#endif
-
- return true;
-}
-
-// Restore all resources which are in D3DPOOL_DEFAULT.
-// Used after we reset the direct3d device to restore these resources.
-// Returns true on success and false on failure.
-bool RendererD3D9::RestoreDeviceObjects() {
- // Restore all Effect objects.
- const EffectArray effect_array(object_manager_->GetByClass<Effect>());
- EffectArray::const_iterator p, end(effect_array.end());
- for (p = effect_array.begin(); p != end; ++p) {
- EffectD3D9* effect = down_cast<EffectD3D9*>(*p);
- if (!HR(effect->OnResetDevice()))
- return false;
- }
-
- // Restore all Texture objects.
- const TextureArray texture_array(object_manager_->GetByClass<Texture>());
- TextureArray::const_iterator texture_iter(texture_array.begin()),
- texture_end(texture_array.end());
- for (;texture_iter != texture_end; ++texture_iter) {
- if ((*texture_iter)->IsA(Texture2D::GetApparentClass())) {
- Texture2DD3D9* texture2d_d3d9 = down_cast<Texture2DD3D9*>(*texture_iter);
- if (!HR(texture2d_d3d9->OnResetDevice())) {
- return false;
- }
- } else if ((*texture_iter)->IsA(TextureCUBE::GetApparentClass())) {
- TextureCUBED3D9* texture_cube_d3d9 =
- down_cast<TextureCUBED3D9*>(*texture_iter);
- if (!HR(texture_cube_d3d9->OnResetDevice())) {
- return false;
- }
- }
- }
-
- // Restore all RenderSurface objects. Note that this pass must happen
- // after the Textures have been restored.
- RenderSurfaceBaseArray surface_array(
- object_manager_->GetByClass<RenderSurfaceBase>());
- RenderSurfaceBaseArray::const_iterator surface_iter(surface_array.begin()),
- surface_end(surface_array.end());
- for (; surface_iter != surface_end; ++surface_iter) {
- if ((*surface_iter)->IsA(RenderSurface::GetApparentClass())) {
- RenderSurfaceD3D9* render_surface_d3d9 =
- down_cast<RenderSurfaceD3D9*>(*surface_iter);
- if (!HR(render_surface_d3d9->OnResetDevice())) {
- return false;
- }
- } else if ((*surface_iter)->IsA(
- RenderDepthStencilSurface::GetApparentClass())) {
- RenderDepthStencilSurfaceD3D9* render_depth_stencil_surface_d3d9 =
- down_cast<RenderDepthStencilSurfaceD3D9*>(*surface_iter);
- if (!HR(render_depth_stencil_surface_d3d9->OnResetDevice())) {
- return false;
- }
- }
- }
-
-#ifdef O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
- if (fullscreen_message_font_ &&
- S_OK != fullscreen_message_font_->OnResetDevice()) {
- return false;
- }
- if (fullscreen_message_line_ &&
- S_OK != fullscreen_message_line_->OnResetDevice()) {
- return false;
- }
-#endif
-
- return true;
-}
-
-// Resets the d3d device properly and returns true on success.
-bool RendererD3D9::ResetDevice() {
- // First update the flag if it hasn't been set yet.
- have_device_ = false;
- set_need_to_render(true);
-
- // Try to release all resources
- if (!InvalidateDeviceObjects())
- return false;
-
- // Attempt to reset the device
- if (!HR(d3d_device_->Reset(&d3d_present_parameters_)))
- return false;
-
- // Now try to restore our resources
- if (!RestoreDeviceObjects())
- return false;
-
- // If everything goes well, reset render states.
- SetInitialStates();
-
- // successful
- have_device_ = true;
- return true;
-}
-
-// This function tests if the device is lost and sets the have_device_ flag
-// appropriately.
-// It attempts to reset the device if it is lost.
-void RendererD3D9::TestLostDevice() {
- HRESULT hr = 0;
-
- // We poll for the state of the device using TestCooperativeLevel().
- hr = d3d_device_->TestCooperativeLevel();
-
- // When hr == D3DERR_DEVICELOST, it means that we have lost the device
- // ie. a screensaver, or the computer is locked etc.
- // and there is nothing we can do to get back the device,
- // and display stuff normally.
- // In this case, we set the have_device_ flag to false to disable
- // all render calls and calls involving the device.
-
- // When hr == D3DERR_DEVICENOTRESET, we have lost the device BUT we can
- // reset it and restore our original display.
- // (ie. user has come out of his screensaver)
- // In this case, we attempt to invalidate all resources in D3DPOOL_DEFAULT,
- // reset the device, and then restore the resources.
- // This should succeed and we set the have_device_ flag to true.
- // If it fails, we do not set the flag to true.
-
- if (hr == D3DERR_DEVICELOST) {
- // We've lost the device, update the flag so that render calls don't
- // get called.
- have_device_ = false;
- set_need_to_render(true);
- return;
- } else if (hr == D3DERR_DEVICENOTRESET) {
- // Direct3d tells us it is possible to reset the device now..
- // So let's attempt a reset!
- if (ResetDevice()) {
- CallLostResourcesCallback();
- }
- }
-}
-
-// The window has been resized; change the size of our back buffer
-// and do a reset.
-void RendererD3D9::Resize(int width, int height) {
- if (width > 0 && height > 0) {
- // New size of back buffer
- d3d_present_parameters_.BackBufferWidth = width;
- d3d_present_parameters_.BackBufferHeight = height;
-
- // Attempt to do a reset if possible
- HRESULT hr = d3d_device_->TestCooperativeLevel();
- if (hr == D3DERR_DEVICENOTRESET || hr == D3D_OK) {
- // Reset device
- ResetDevice();
- }
-
- // Save this off.
- SetClientSize(width, height);
- }
-}
-
-void RendererD3D9::GetDisplayModes(std::vector<DisplayMode> *modes) {
- int num_modes =
- d3d_->GetAdapterModeCount(current_adapter_, D3DFMT_X8R8G8B8);
- std::vector<DisplayMode> modes_found;
- for (int i = 0; i < num_modes; ++i) {
- D3DDISPLAYMODE mode;
- if (FAILED(d3d_->EnumAdapterModes(current_adapter_,
- D3DFMT_X8R8G8B8,
- i,
- &mode))) {
- LOG(ERROR) << "Failed to enumerate adapter display modes.";
- } else {
- DCHECK(mode.Format == D3DFMT_X8R8G8B8);
- // Display mode IDs are one higher than D3D display modes.
- modes_found.push_back(
- DisplayMode(mode.Width, mode.Height, mode.RefreshRate, i + 1));
- }
- }
- modes->swap(modes_found);
-}
-
-bool RendererD3D9::GetDisplayMode(int id, DisplayMode *mode) {
- D3DDISPLAYMODE d3d_mode;
- bool success = false;
- if (id == DISPLAY_MODE_DEFAULT) {
- success = SUCCEEDED(d3d_->GetAdapterDisplayMode(current_adapter_,
- &d3d_mode));
- } else {
- // Display mode IDs are one higher than D3D display modes.
- success = SUCCEEDED(d3d_->EnumAdapterModes(current_adapter_,
- D3DFMT_X8R8G8B8,
- id - 1,
- &d3d_mode));
- }
- if (success) {
- mode->Set(d3d_mode.Width, d3d_mode.Height, d3d_mode.RefreshRate, id);
- }
- return success;
-}
-
-bool RendererD3D9::GoFullscreen(const DisplayWindow& display,
- int mode_id) {
- if (!fullscreen_) {
- if (d3d_device_) { // Have we been initialized yet?
- const DisplayWindowWindows& platform_display =
- static_cast<const DisplayWindowWindows&>(display);
- HWND window = platform_display.hwnd();
- int refresh_rate = 0;
- bool windowed = true;
-
- // With software renderer, always use DISPLAY_MODE_DEFAULT.
- // This is due to a bug in software renderer that only the primary
- // monitor/adapter is recognized.
- ClientInfoManager* client_info_manager =
- service_locator()->GetService<ClientInfoManager>();
- if (client_info_manager->client_info().software_renderer())
- mode_id = DISPLAY_MODE_DEFAULT;
-
- // Look up the refresh rate, width and height.
- DisplayMode mode;
- if (!GetDisplayMode(mode_id, &mode)) {
- LOG(ERROR) << "Failed to GetDisplayMode";
- return false;
- }
-
- int width = mode.width();
- int height = mode.height();
-
- // If fullscreen is requested but the mode is set to
- // DISPLAY_MODE_DEFAULT then create a non-full-screen window at the
- // current display resolution. If any other mode is chosen then the
- // windows will change mode and create a true full-screen window.
- if (mode_id != DISPLAY_MODE_DEFAULT) {
- refresh_rate = mode.refresh_rate();
- windowed = false;
- }
-
-#ifdef O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
- showing_fullscreen_message_ = true;
- fullscreen_message_timer_.GetElapsedTimeAndReset(); // Reset the timer.
-#endif
-
- d3d_present_parameters_.FullScreen_RefreshRateInHz = refresh_rate;
- d3d_present_parameters_.hDeviceWindow = window;
- d3d_present_parameters_.Windowed = windowed;
-
- // Check if the window size is zero. Some drivers will fail because of
- // that so we'll force a small size in that case.
- if (width == 0 || height == 0) {
- width = 16;
- height = 16;
- }
- fullscreen_ = true;
- Resize(width, height);
- }
- }
- return true;
-}
-
-bool RendererD3D9::CancelFullscreen(const DisplayWindow& display,
- int width,
- int height) {
- if (fullscreen_) {
- if (d3d_device_) { // Have we been initialized yet?
- const DisplayWindowWindows& platform_display =
- static_cast<const DisplayWindowWindows&>(display);
- HWND window = platform_display.hwnd();
-#ifdef O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
- showing_fullscreen_message_ = false;
-#endif
- d3d_present_parameters_.FullScreen_RefreshRateInHz = 0;
- d3d_present_parameters_.hDeviceWindow = window;
- d3d_present_parameters_.Windowed = true;
-
- // Check if the window size is zero. Some drivers will fail because of
- // that so we'll force a small size in that case.
- if (width == 0 || height == 0) {
- width = 16;
- height = 16;
- }
- fullscreen_ = false;
- Resize(width, height);
- }
- }
- return true;
-}
-
-// Resets the rendering stats and
-bool RendererD3D9::PlatformSpecificStartRendering() {
- // Determine whether the device is lost, resetting if possible.
- TestLostDevice();
-
- bool result = have_device_;
- if (result) {
- bool got_render_target =
- HR(d3d_device_->GetRenderTarget(0, &back_buffer_surface_));
- bool got_depth_surface =
- HR(d3d_device_->GetDepthStencilSurface(&back_buffer_depth_surface_));
- result = got_render_target && got_depth_surface;
- }
-
- if (!result) {
- back_buffer_surface_ = NULL;
- back_buffer_depth_surface_ = NULL;
- }
-
- current_d3d_surface_ = back_buffer_surface_;
- current_d3d_depth_surface_ = back_buffer_depth_surface_;
-
- return result;
-}
-
-// prepares DX9 for rendering PART of the frame. Returns true on success.
-bool RendererD3D9::PlatformSpecificBeginDraw() {
- // Only perform ops with the device if we have it.
- if (have_device_) {
- return HR(d3d_device_->BeginScene());
- } else {
- // Return false if we have lost the device.
- return false;
- }
-}
-
-// NOTE: End draw can be called multiple times per frame. If want something
-// to happen only once per frame it belongs in FinishRendering.
-void RendererD3D9::PlatformSpecificEndDraw() {
- if (have_device_) {
- HR(d3d_device_->EndScene());
- }
-}
-
-void RendererD3D9::PlatformSpecificFinishRendering() {
- current_d3d_surface_ = NULL;
- current_d3d_depth_surface_ = NULL;
-
- if (have_device_) {
- // Release the back-buffer references.
- back_buffer_surface_ = NULL;
- back_buffer_depth_surface_ = NULL;
-
-#ifdef O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
- if (showing_fullscreen_message_) {
- // Message should display for 3 seconds after transition to fullscreen.
- float elapsed_time =
- fullscreen_message_timer_.GetElapsedTimeWithoutClearing();
- const float display_duration = 3.5f;
- if (elapsed_time > display_duration) {
- showing_fullscreen_message_ = false;
- } else {
- if (BeginDraw()) {
- ShowFullscreenMessage(elapsed_time, display_duration);
- EndDraw();
- }
- }
- }
-#endif
- }
-}
-
-void RendererD3D9::PlatformSpecificPresent() {
- if (have_device_) {
- // No need to call Present(...) if we are rendering to an off-screen
- // target.
- if (!off_screen_surface_) {
- d3d_device_->Present(NULL, NULL, NULL, NULL);
- }
- }
-}
-
-void RendererD3D9::ApplyDirtyStates() {
-}
-
-#ifdef O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
-// TODO(gman): Why is this code in here? Shouldn't this use O3D to render this
-// instead of D3D?
-void RendererD3D9::ShowFullscreenMessage(float elapsed_time,
- float display_duration) {
- RECT rect;
- const float line_thickness = 60.0f;
- const float line_height = line_thickness - 1; // Prevent a gap at the top.
- const float line_width = 340.0f;
- const D3DXCOLOR background_color(0.0f, 0.0f, 0.0f, 0.5f);
- const float curve_radius = 9.0f;
- const float curve_radius_squared = curve_radius * curve_radius;
- const float line_base_thickness = line_thickness - curve_radius;
- const float line_base_height = line_height - curve_radius;
- const float line_x = width() - line_width;
-
- float y_offset = 0;
- const float animation_length = 0.25f;
- if (elapsed_time < animation_length) {
- y_offset = (elapsed_time / animation_length - 1) * line_height;
- } else if (display_duration - elapsed_time < animation_length) {
- y_offset = ((display_duration - elapsed_time) / animation_length - 1) *
- line_height;
- }
-
- SetRect(&rect, static_cast<int>(line_x), static_cast<int>(y_offset),
- width(), static_cast<int>(y_offset + line_height));
-
- D3DXVECTOR2 line_vertices[2];
- HR(fullscreen_message_line_->SetWidth(line_base_thickness));
- line_vertices[0].x = line_x;
- line_vertices[0].y = y_offset + line_base_height / 2;
- line_vertices[1].x = static_cast<float>(width());
- line_vertices[1].y = y_offset + line_base_height / 2;
- HR(fullscreen_message_line_->Draw(line_vertices, 2, background_color));
-
- HR(fullscreen_message_line_->SetWidth(1));
- HR(fullscreen_message_line_->Begin());
- for (int i = 0; i < curve_radius; ++i) {
- const float x = line_x + curve_radius - sqrt(curve_radius_squared - i * i);
- const float y = y_offset + i + line_base_height;
- line_vertices[0].x = x;
- line_vertices[0].y = y;
- line_vertices[1].x = static_cast<float>(width());
- line_vertices[1].y = y;
- HR(fullscreen_message_line_->Draw(line_vertices, 2, background_color));
- }
- HR(fullscreen_message_line_->End());
-
- DWORD z_enable; // Back up this setting and restore it afterward.
- d3d_device_->GetRenderState(D3DRS_ZENABLE, &z_enable);
- d3d_device_->SetRenderState(D3DRS_ZENABLE, FALSE);
-
- HR(fullscreen_message_font_->DrawText(NULL,
- L"Press ESC to exit fullscreen", -1, &rect,
- DT_CENTER | DT_VCENTER, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f)));
-
- d3d_device_->SetRenderState(D3DRS_ZENABLE, z_enable);
-}
-#endif
-
-void RendererD3D9::SetRenderSurfacesPlatformSpecific(
- const RenderSurface* surface,
- const RenderDepthStencilSurface* surface_depth) {
- const RenderSurfaceD3D9 *d3d_render_surface =
- down_cast<const RenderSurfaceD3D9*>(surface);
- const RenderDepthStencilSurfaceD3D9 *d3d_render_depth_surface =
- down_cast<const RenderDepthStencilSurfaceD3D9*>(surface_depth);
-
- IDirect3DSurface9 *d3d_surface =
- d3d_render_surface ? d3d_render_surface->GetSurfaceHandle() : NULL;
- IDirect3DSurface9 *d3d_depth_surface = d3d_render_depth_surface ?
- d3d_render_depth_surface->GetSurfaceHandle() : NULL;
-
- // At least one of the surfaces must be non-null.
- DCHECK(d3d_surface || d3d_depth_surface);
-
- current_d3d_surface_ = d3d_surface;
- current_d3d_depth_surface_ = d3d_depth_surface;
-
- HR(d3d_device()->SetRenderTarget(0, d3d_surface));
- HR(d3d_device()->SetDepthStencilSurface(d3d_depth_surface));
-}
-
-void RendererD3D9::SetBackBufferPlatformSpecific() {
- current_d3d_surface_ = back_buffer_surface_;
- current_d3d_depth_surface_ = back_buffer_depth_surface_;
-
- HR(d3d_device()->SetRenderTarget(0, back_buffer_surface_));
- HR(d3d_device()->SetDepthStencilSurface(back_buffer_depth_surface_));
-}
-
-StreamBank::Ref RendererD3D9::CreateStreamBank() {
- return StreamBank::Ref(new StreamBankD3D9(service_locator(), d3d_device()));
-}
-
-Primitive::Ref RendererD3D9::CreatePrimitive() {
- return Primitive::Ref(new PrimitiveD3D9(service_locator(), d3d_device()));
-}
-
-DrawElement::Ref RendererD3D9::CreateDrawElement() {
- return DrawElement::Ref(new DrawElementD3D9(service_locator()));
-}
-
-VertexBuffer::Ref RendererD3D9::CreateVertexBuffer() {
- return VertexBuffer::Ref(new VertexBufferD3D9(service_locator(),
- d3d_device()));
-}
-
-// Creates and returns a D3D9 specific integer buffer.
-IndexBuffer::Ref RendererD3D9::CreateIndexBuffer() {
- return IndexBuffer::Ref(new IndexBufferD3D9(service_locator(),
- d3d_device(),
- use_small_index_buffers_));
-}
-
-Effect::Ref RendererD3D9::CreateEffect() {
- return Effect::Ref(new EffectD3D9(service_locator(), d3d_device()));
-}
-
-Sampler::Ref RendererD3D9::CreateSampler() {
- return Sampler::Ref(new SamplerD3D9(service_locator(), d3d_device()));
-}
-
-ParamCache* RendererD3D9::CreatePlatformSpecificParamCache() {
- return new ParamCacheD3D9(service_locator());
-}
-
-// Attempts to create a Texture2D with the given specs. If creation fails
-// then the method returns NULL.
-Texture2D::Ref RendererD3D9::CreatePlatformSpecificTexture2D(
- int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- return Texture2D::Ref(Texture2DD3D9::Create(service_locator(),
- format,
- levels,
- width,
- height,
- this,
- enable_render_surfaces));
-}
-
-// Attempts to create a TextureCUBE with the given specs. If creation fails
-// then the method returns NULL.
-TextureCUBE::Ref RendererD3D9::CreatePlatformSpecificTextureCUBE(
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces) {
- return TextureCUBE::Ref(TextureCUBED3D9::Create(service_locator(),
- format,
- levels,
- edge_length,
- this,
- enable_render_surfaces));
-}
-
-RenderDepthStencilSurface::Ref RendererD3D9::CreateDepthStencilSurface(
- int width,
- int height) {
- DepthStencilSurfaceConstructor *depth_constructor =
- new DepthStencilSurfaceConstructor(service_locator(), width, height);
-
- // Note that since the returned surface is not associated with a Texture
- // mip-level, NULL is passed for the texture argument.
- return RenderDepthStencilSurface::Ref(
- new RenderDepthStencilSurfaceD3D9(service_locator(),
- width,
- height,
- depth_constructor));
-}
-
-const int* RendererD3D9::GetRGBAUByteNSwizzleTable() {
- static int swizzle_table[] = { 2, 1, 0, 3, };
- return swizzle_table;
-}
-
-// This is a factory function for creating Renderer objects. Since
-// we're implementing D3D9, we only ever return a D3D9 renderer.
-Renderer* Renderer::CreateDefaultRenderer(ServiceLocator* service_locator) {
- return RendererD3D9::CreateDefault(service_locator);
-}
-} // namespace o3d
diff --git a/o3d/core/win/d3d9/renderer_d3d9.h b/o3d/core/win/d3d9/renderer_d3d9.h
deleted file mode 100644
index 6fe3225..0000000
--- a/o3d/core/win/d3d9/renderer_d3d9.h
+++ /dev/null
@@ -1,284 +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 declaration of the RendererD3D9 class.
-
-#ifndef O3D_CORE_WIN_D3D9_RENDERER_D3D9_H_
-#define O3D_CORE_WIN_D3D9_RENDERER_D3D9_H_
-
-#include <atlbase.h>
-#include <d3d9.h>
-
-#include <vector>
-
-#include "core/cross/display_mode.h"
-#include "core/cross/display_window.h"
-#include "core/cross/renderer.h"
-#include "core/cross/state.h"
-#include "core/cross/texture.h"
-#include "core/cross/timer.h"
-#include "core/cross/types.h"
-
-interface ID3DXFont;
-interface ID3DXLine;
-
-namespace o3d {
-
-class Material;
-class Texture2D;
-class ObjectManager;
-class ParamCache;
-class SemanticManager;
-
-// The RenderedD9D9 class implements the genereric Renderer interface using
-// DirectX9.
-class RendererD3D9 : public Renderer {
- public:
- // Creates a default Renderer.
- static RendererD3D9* CreateDefault(ServiceLocator* service_locator);
- virtual ~RendererD3D9();
-
- // Initialises the renderer for use, claiming hardware resources.
- virtual InitStatus InitPlatformSpecific(const DisplayWindow& display,
- bool off_screen);
-
- // Released all hardware resources.
- virtual void Destroy();
-
- // Attempts to reset the back buffer to its new dimensions.
- virtual void Resize(int width, int height);
-
- // Overridden from Renderer.
- virtual bool GoFullscreen(const DisplayWindow& display,
- int mode_id);
-
- // Overridden from Renderer.
- virtual bool CancelFullscreen(const DisplayWindow& display,
- int width, int height);
-
- // Tells whether we're currently displayed fullscreen or not.
- virtual bool fullscreen() const {
- return fullscreen_;
- }
-
- // Get a vector of the available fullscreen display modes.
- // Clears *modes on error.
- virtual void GetDisplayModes(std::vector<DisplayMode> *modes);
-
- // Get a single fullscreen display mode by id.
- // Returns true on success, false on error.
- virtual bool GetDisplayMode(int id, DisplayMode *mode);
-
- // Creates a StreamBank, returning a platform specific implementation class.
- virtual StreamBank::Ref CreateStreamBank();
-
- // Creates a Primitive, returning a platform specific implementation class.
- virtual Primitive::Ref CreatePrimitive();
-
- // Creates a DrawElement, returning a platform specific implementation
- // class.
- virtual DrawElement::Ref CreateDrawElement();
-
- // Creates and returns a D3D9 specific float buffer.
- virtual VertexBuffer::Ref CreateVertexBuffer();
-
- // Creates and returns a D3D9 specific integer buffer.
- virtual IndexBuffer::Ref CreateIndexBuffer();
-
- // Creates and returns a D3D9 specific Effect object.
- virtual Effect::Ref CreateEffect();
-
- // Creates and returns a D3D9 specific Sampler object.
- virtual Sampler::Ref CreateSampler();
-
- // Creates and returns a platform-specific RenderDepthStencilSurface object
- // for use as a depth-stencil render target.
- virtual RenderDepthStencilSurface::Ref CreateDepthStencilSurface(
- int width,
- int height);
-
- inline LPDIRECT3DDEVICE9 d3d_device() const { return d3d_device_; }
- inline LPDIRECT3D9 d3d() const { return d3d_; }
-
- inline DWORD supported_depth_format() const {
- return supported_depth_format_;
- }
-
- // Overridden from Renderer.
- virtual const int* GetRGBAUByteNSwizzleTable();
-
- protected:
- // Keep the constructor protected so only factory methods can create
- // renderers.
- explicit RendererD3D9(ServiceLocator* service_locator);
-
- // Overridden from Renderer.
- virtual bool PlatformSpecificBeginDraw();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificEndDraw();
-
- // Overridden from Renderer.
- virtual bool PlatformSpecificStartRendering();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificFinishRendering();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificPresent();
-
- // Overridden from Renderer.
- virtual void PlatformSpecificClear(const Float4 &color,
- bool color_flag,
- float depth,
- bool depth_flag,
- int stencil,
- bool stencil_flag);
-
- // Overridden from Renderer.
- virtual ParamCache* CreatePlatformSpecificParamCache();
-
- // Overridden from Renderer.
- virtual void SetBackBufferPlatformSpecific();
-
- // Overridden from Renderer.
- virtual void SetRenderSurfacesPlatformSpecific(
- const RenderSurface* surface,
- const RenderDepthStencilSurface* depth_surface);
-
- // Sets the viewport. This is the platform specific version.
- void SetViewportInPixels(int left,
- int top,
- int width,
- int height,
- float min_z,
- float max_z);
-
- // Overridden from Renderer.
- virtual Texture2D::Ref CreatePlatformSpecificTexture2D(
- int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
- // Overridden from Renderer.
- virtual TextureCUBE::Ref CreatePlatformSpecificTextureCUBE(
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
- // Overridden from Renderer.
- virtual void ApplyDirtyStates();
-
- private:
- ServiceDependency<ObjectManager> object_manager_;
- ServiceDependency<SemanticManager> semantic_manager_;
-
- // Instance of the D3D9 interface.
- CComPtr<IDirect3D9> d3d_;
-
- // Instance of the D3DDevice9 interface.
- CComPtr<IDirect3DDevice9> d3d_device_;
-
- // D3DFORMAT value of the depth surface type supported.
- DWORD supported_depth_format_;
-
- // Pointer to interface of the off-screen-surface used for off-screen
- // rendering. Is non-null when off-screen rendering is enabled.
- CComPtr<IDirect3DSurface9> off_screen_surface_;
-
- CComPtr<IDirect3DSurface9> back_buffer_surface_;
- CComPtr<IDirect3DSurface9> back_buffer_depth_surface_;
-
- CComPtr<IDirect3DSurface9> current_d3d_surface_;
- CComPtr<IDirect3DSurface9> current_d3d_depth_surface_;
-
- // The display mode we are in.
- D3DDISPLAYMODE d3d_display_mode_;
-
- // D3DPresent parameters (for initializing and resetting the device.)
- D3DPRESENT_PARAMETERS d3d_present_parameters_;
-
- // Flag to tell use we need to use small index buffers.
- bool use_small_index_buffers_;
-
- // Flag to tell us whether we have or lost the device.
- bool have_device_;
-
- // The monitor/adapter the window is on.
- HMONITOR current_monitor_;
- UINT current_adapter_;
-
- // Indicates we're rendering fullscreen rather than in the plugin region.
- bool fullscreen_;
-#ifdef O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
- // Indicates we're showing the "Press Escape..." banner.
- bool showing_fullscreen_message_;
- // We want to show the message for about 3 seconds.
- ElapsedTimeTimer fullscreen_message_timer_;
- // Draws the actual message.
- void ShowFullscreenMessage(float elapsedTime, float display_duration);
-#endif
-
- // Invalidates all resources which are in D3DPOOL_DEFAULT.
- // Used before we try to reset the device, when the device is lost.
- // (ie when suspending the computer, locking it, etc.)
- // Returns true on success and false on failure.
- bool InvalidateDeviceObjects();
-
- // Restore all resources which are in D3DPOOL_DEFAULT.
- // Used after we reset the direct3d device to restore these resources.
- // Returns true on success and false on failure.
- bool RestoreDeviceObjects();
-
- // This function tests if the device is lost and sets the have_device_ flag
- // appropriately.
- // It attempts to reset the device if it is lost by calling ResetDevice().
- void TestLostDevice();
-
- // Attempts to reset the device.
- // Returns true on success.
- bool ResetDevice();
-
-#ifdef O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
- // The font to use to display the message when we go to fullscreen.
- CComPtr<ID3DXFont> fullscreen_message_font_;
- // The line used to draw the background for the message.
- CComPtr<ID3DXLine> fullscreen_message_line_;
-#endif
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_WIN_D3D9_RENDERER_D3D9_H_
diff --git a/o3d/core/win/d3d9/sampler_d3d9.cc b/o3d/core/win/d3d9/sampler_d3d9.cc
deleted file mode 100644
index 36a0029..0000000
--- a/o3d/core/win/d3d9/sampler_d3d9.cc
+++ /dev/null
@@ -1,202 +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 definition of SamplerD3D9.
-
-#include "core/cross/precompile.h"
-
-#include "core/win/d3d9/sampler_d3d9.h"
-
-#include "core/cross/error.h"
-#include "core/cross/renderer.h"
-#include "core/cross/renderer_platform.h"
-#include "core/win/d3d9/utils_d3d9.h"
-
-namespace o3d {
-
-SamplerD3D9::SamplerD3D9(ServiceLocator* service_locator,
- IDirect3DDevice9* d3d_device)
- : Sampler(service_locator),
- renderer_(static_cast<RendererD3D9*>(
- service_locator->GetService<Renderer>())),
- d3d_device_(d3d_device) {
- DCHECK(d3d_device);
-}
-
-SamplerD3D9::~SamplerD3D9() {
-}
-
-void SamplerD3D9::SetAddressMode(int sampler_unit,
- D3DSAMPLERSTATETYPE sampler_type,
- Sampler::AddressMode o3d_mode,
- D3DTEXTUREADDRESS default_mode) {
- D3DTEXTUREADDRESS d3d_mode = default_mode;
- switch (o3d_mode) {
- case WRAP:
- d3d_mode = D3DTADDRESS_WRAP;
- break;
- case MIRROR:
- d3d_mode = D3DTADDRESS_MIRROR;
- break;
- case CLAMP:
- d3d_mode = D3DTADDRESS_CLAMP;
- break;
- case BORDER:
- d3d_mode = D3DTADDRESS_BORDER;
- break;
- default:
- DLOG(ERROR) << "Unknown Address mode " << static_cast<int>(o3d_mode);
- return;
- }
-
- HR(d3d_device_->SetSamplerState(sampler_unit, sampler_type, d3d_mode));
-}
-
-namespace {
-
-D3DTEXTUREFILTERTYPE D3DMagFilter(Sampler::FilterType o3d_mag_filter) {
- // For mag filters only POINT and LINEAR make sense. Everything else
- // we convert to LINEAR.
- switch (o3d_mag_filter) {
- case Sampler::POINT:
- return D3DTEXF_POINT;
- case Sampler::LINEAR:
- return D3DTEXF_LINEAR;
- default:
- return D3DTEXF_LINEAR;
- }
-}
-
-D3DTEXTUREFILTERTYPE D3DMinFilter(Sampler::FilterType o3d_mag_filter) {
- // Allowable min filters are POINT, LINEAR and ANISOTROPIC
- switch (o3d_mag_filter) {
- case Sampler::POINT:
- return D3DTEXF_POINT;
- case Sampler::LINEAR:
- return D3DTEXF_LINEAR;
- case Sampler::ANISOTROPIC:
- return D3DTEXF_ANISOTROPIC;
- default:
- return D3DTEXF_LINEAR;
- }
-}
-
-D3DTEXTUREFILTERTYPE D3DMipFilter(Sampler::FilterType o3d_mag_filter) {
- // Allowable mip filters are NONE, POINT and LINEAR
- switch (o3d_mag_filter) {
- case Sampler::NONE:
- return D3DTEXF_NONE;
- case Sampler::POINT:
- return D3DTEXF_POINT;
- case Sampler::LINEAR:
- return D3DTEXF_LINEAR;
- default:
- return D3DTEXF_LINEAR;
- }
-}
-
-} // namespace
-
-void SamplerD3D9::SetTextureAndStates(int sampler_unit) {
- DLOG_ASSERT(d3d_device_);
- DLOG_ASSERT(renderer_);
-
- // First get the d3d texture and set it.
- Texture* texture_object = texture();
- if (!texture_object) {
- texture_object = renderer_->error_texture();
- if (!texture_object) {
- O3D_ERROR(service_locator())
- << "Missing texture for sampler " << name();
- texture_object = renderer_->fallback_error_texture();
- }
- }
-
- if (!renderer_->SafeToBindTexture(texture_object)) {
- O3D_ERROR(renderer_->service_locator())
- << "Attempt to bind texture, " << texture_object->name()
- << " when drawing to same texture as a RenderSurface";
- texture_object = renderer_->error_texture();
- }
-
- IDirect3DBaseTexture9* d3d_texture =
- static_cast<IDirect3DBaseTexture9*>(texture_object->GetTextureHandle());
-
- HR(d3d_device_->SetTexture(sampler_unit, d3d_texture));
-
- SetAddressMode(sampler_unit,
- D3DSAMP_ADDRESSU,
- address_mode_u(),
- D3DTADDRESS_WRAP);
-
- SetAddressMode(sampler_unit,
- D3DSAMP_ADDRESSV,
- address_mode_v(),
- D3DTADDRESS_WRAP);
-
- if (texture_object->IsA(TextureCUBE::GetApparentClass())) {
- SetAddressMode(sampler_unit,
- D3DSAMP_ADDRESSW,
- address_mode_w(),
- D3DTADDRESS_WRAP);
- }
-
- HR(d3d_device_->SetSamplerState(sampler_unit,
- D3DSAMP_MAGFILTER,
- D3DMagFilter(mag_filter())));
-
- HR(d3d_device_->SetSamplerState(sampler_unit,
- D3DSAMP_MINFILTER,
- D3DMinFilter(min_filter())));
-
- HR(d3d_device_->SetSamplerState(sampler_unit,
- D3DSAMP_MIPFILTER,
- D3DMipFilter(mip_filter())));
-
- Float4 color = border_color();
- DWORD d3d_color = D3DCOLOR_COLORVALUE(color[0], color[1], color[2], color[3]);
- HR(d3d_device_->SetSamplerState(sampler_unit,
- D3DSAMP_BORDERCOLOR,
- d3d_color));
-
- HR(d3d_device_->SetSamplerState(sampler_unit,
- D3DSAMP_MAXANISOTROPY,
- max_anisotropy()));
-}
-
-void SamplerD3D9::ResetTexture(int sampler_unit) {
- DLOG_ASSERT(d3d_device_);
-
- HR(d3d_device_->SetTexture(sampler_unit, NULL));
-}
-
-} // namespace o3d
diff --git a/o3d/core/win/d3d9/sampler_d3d9.h b/o3d/core/win/d3d9/sampler_d3d9.h
deleted file mode 100644
index f31e1b8..0000000
--- a/o3d/core/win/d3d9/sampler_d3d9.h
+++ /dev/null
@@ -1,72 +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 declaration of the SamplerD3D9 class.
-
-#ifndef O3D_CORE_WIN_D3D9_SAMPLER_D3D9_H_
-#define O3D_CORE_WIN_D3D9_SAMPLER_D3D9_H_
-
-#include <atlbase.h>
-#include <d3d9.h>
-#include "core/cross/sampler.h"
-
-namespace o3d {
-
-class RendererD3D9;
-
-// Sampler2DD3D9 is an implementation of the Sampler object for D3D9.
-class SamplerD3D9 : public Sampler {
- public:
- SamplerD3D9(ServiceLocator* service_locator, IDirect3DDevice9* d3d_device);
- virtual ~SamplerD3D9();
-
- // Sets the d3d texture and sampler states for the given sampler unit.
- void SetTextureAndStates(int sampler_unit);
-
- // Sets the d3d texture to NULL.
- void ResetTexture(int sampler_unit);
-
- private:
- void SetAddressMode(int sampler_unit,
- D3DSAMPLERSTATETYPE sampler_type,
- Sampler::AddressMode o3d_mode,
- D3DTEXTUREADDRESS default_mode);
-
- RendererD3D9* renderer_;
- CComPtr<IDirect3DDevice9> d3d_device_;
-
- DISALLOW_COPY_AND_ASSIGN(SamplerD3D9);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_WIN_D3D9_SAMPLER_D3D9_H_
diff --git a/o3d/core/win/d3d9/software_renderer_d3d9.h b/o3d/core/win/d3d9/software_renderer_d3d9.h
deleted file mode 100644
index 5c7cdfc..0000000
--- a/o3d/core/win/d3d9/software_renderer_d3d9.h
+++ /dev/null
@@ -1,46 +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_CORE_WIN_D3D9_SOFTWARE_RENDERER_D3D9_H
-#define O3D_CORE_WIN_D3D9_SOFTWARE_RENDERER_D3D9_H
-
-#include <d3d9.h>
-
-namespace o3d {
-
-// Not implemented.
-inline bool SetupSoftwareRenderer(IDirect3D9* d3d) {
- return false;
-}
-
-} // namespace o3d
-
-#endif // O3D_CORE_WIN_D3D9_SOFTWARE_RENDERER_D3D9_H
diff --git a/o3d/core/win/d3d9/stream_bank_d3d9.cc b/o3d/core/win/d3d9/stream_bank_d3d9.cc
deleted file mode 100644
index 52868fc..0000000
--- a/o3d/core/win/d3d9/stream_bank_d3d9.cc
+++ /dev/null
@@ -1,185 +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 definition of StreamBankD3D9.
-
-#include "core/cross/precompile.h"
-
-#include "core/win/d3d9/stream_bank_d3d9.h"
-
-#include "core/cross/buffer.h"
-#include "core/cross/param_cache.h"
-#include "core/cross/renderer.h"
-#include "core/cross/error.h"
-#include "core/win/d3d9/buffer_d3d9.h"
-#include "core/win/d3d9/d3d_entry_points.h"
-#include "core/win/d3d9/draw_element_d3d9.h"
-#include "core/win/d3d9/effect_d3d9.h"
-#include "core/win/d3d9/param_cache_d3d9.h"
-#include "core/win/d3d9/utils_d3d9.h"
-
-// Someone defines min, conflicting with std::min
-#ifdef min
-#undef min
-#endif
-
-namespace o3d {
-
-StreamBankD3D9::StreamBankD3D9(ServiceLocator* service_locator,
- IDirect3DDevice9* d3d_device)
- : StreamBank(service_locator),
- d3d_device_(d3d_device),
- vertex_declaration_(NULL) {
- DCHECK(d3d_device);
-}
-
-StreamBankD3D9::~StreamBankD3D9() {
- FreeVertexDeclaration();
-}
-
-void StreamBankD3D9::FreeVertexDeclaration() {
- if (vertex_declaration_) {
- vertex_declaration_->Release();
- vertex_declaration_ = NULL;
- }
-}
-
-// Releases any old vertex declaration so a new one will be created when
-// rendering that encompasses the change in streams.
-void StreamBankD3D9::OnUpdateStreams() {
- FreeVertexDeclaration();
-}
-
-// Looks for any streams that are required by the vertex shader for which there
-// is no equivalent stream bound to the o3d streambank. If there are such
-// streams it returns failure.
-bool StreamBankD3D9::CheckForMissingVertexStreams(
- EffectD3D9* effect,
- Stream::Semantic* missing_semantic,
- int* missing_semantic_index) {
- DCHECK(missing_semantic);
- DCHECK(missing_semantic_index);
- EffectStreamInfoArray streamInfos;
- effect->GetStreamInfo(&streamInfos);
- for (EffectStreamInfoArray::size_type i = 0;
- i < streamInfos.size(); ++i) {
- Stream::Semantic semantic = streamInfos[i].semantic();
- int semantic_index = streamInfos[i].semantic_index();
- StreamParamVector::const_iterator iter;
- for (iter = vertex_stream_params_.begin();
- iter != vertex_stream_params_.end();
- ++iter) {
- const Stream& stream = (*iter)->stream();
- if (stream.semantic() == semantic &&
- stream.semantic_index() == semantic_index) {
- break;
- }
- }
- if (iter == vertex_stream_params_.end()) {
- // no matching stream was found.
- *missing_semantic = semantic;
- *missing_semantic_index = semantic_index;
- return false;
- }
- }
- return true;
-}
-
-bool StreamBankD3D9::BindStreamsForRendering(unsigned int* max_vertices) {
- DCHECK(max_vertices);
- *max_vertices = UINT_MAX;
- {
- StreamParamVector::const_iterator stream_iter;
- unsigned int count = 0;
- for (stream_iter = vertex_stream_params_.begin();
- stream_iter != vertex_stream_params_.end();
- ++stream_iter, count++) {
- const Stream& vertex_stream = (*stream_iter)->stream();
- const Field& field = vertex_stream.field();
- VertexBufferD3D9 *vertex_buffer =
- down_cast<VertexBufferD3D9*>(field.buffer());
- if (!vertex_buffer) {
- O3D_ERROR(service_locator())
- << "stream has no buffer in StreamBank '" << name() << "'";
- return false;
- }
- // TODO: Support stride of 0. The plan is to make it if num_elements
- // is 1 then do stride = 0. The problem is this is hard to do in GL.
- // so for now we're not doing it.
- HR(d3d_device_->SetStreamSource(count,
- vertex_buffer->d3d_buffer(),
- 0,
- vertex_buffer->stride()));
- // If the buffer has changed structure then we need to re-create the
- // vertex declaration.
- if (vertex_stream.last_field_change_count() !=
- vertex_buffer->field_change_count()) {
- FreeVertexDeclaration();
- vertex_stream.set_last_field_change_count(
- vertex_buffer->field_change_count());
- }
- *max_vertices = std::min(*max_vertices, vertex_stream.GetMaxVertices());
- }
- }
-
- // Create the vertex declaration if it does not exist.
- if (!vertex_declaration_) {
- D3DVERTEXELEMENT9 *vertex_elements
- = new D3DVERTEXELEMENT9[vertex_stream_params_.size()+1];
-
- StreamParamVector::const_iterator stream_iter;
- unsigned int count = 0;
- for (stream_iter = vertex_stream_params_.begin();
- stream_iter != vertex_stream_params_.end();
- ++stream_iter, count++) {
- const Stream& stream = (*stream_iter)->stream();
- vertex_elements[count].Stream = count;
- vertex_elements[count].Offset = stream.field().offset();
- vertex_elements[count].Type = DX9DataType(stream.field());
- vertex_elements[count].Method = D3DDECLMETHOD_DEFAULT;
- vertex_elements[count].Usage = DX9UsageType(stream.semantic());
- vertex_elements[count].UsageIndex = stream.semantic_index();
- }
- D3DVERTEXELEMENT9 end_element = D3DDECL_END();
- vertex_elements[count] = end_element;
-
- HR(d3d_device_->CreateVertexDeclaration(vertex_elements,
- &vertex_declaration_));
- delete [] vertex_elements;
- }
-
- HR(d3d_device_->SetVertexDeclaration(vertex_declaration_));
-
- return true;
-}
-
-} // namespace o3d
diff --git a/o3d/core/win/d3d9/stream_bank_d3d9.h b/o3d/core/win/d3d9/stream_bank_d3d9.h
deleted file mode 100644
index d1026d0..0000000
--- a/o3d/core/win/d3d9/stream_bank_d3d9.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 contains the declaration of the StreamBankD3D9 class.
-
-#ifndef O3D_CORE_WIN_D3D9_STREAM_BANK_D3D9_H_
-#define O3D_CORE_WIN_D3D9_STREAM_BANK_D3D9_H_
-
-#include <d3d9.h>
-#include "core/cross/stream_bank.h"
-#include "core/win/d3d9/effect_d3d9.h"
-
-namespace o3d {
-
-class EffectD3D9;
-
-// StreamBankD3D9 is the DX9 implementation of the StreamBank. It provides the
-// necessary interfaces for setting the geometry streams on the StreamBank.
-class StreamBankD3D9 : public StreamBank {
- public:
- explicit StreamBankD3D9(ServiceLocator* service_locator,
- IDirect3DDevice9* d3d_device);
- ~StreamBankD3D9();
-
- // Sets the streams for rendering.
- // Parameter:
- // max_vertrices: pointer to variable to receive the maximum vertices
- // the streams can render.
- // Returns:
- // True if all the streams are available.
- bool BindStreamsForRendering(unsigned int* max_vertices);
-
- // Checks for all required streams before rendering.
- bool CheckForMissingVertexStreams(EffectD3D9* effect,
- Stream::Semantic* missing_semantic,
- int* missing_semantic_index);
-
- protected:
- // Overridden from StreamBank.
- virtual void OnUpdateStreams();
-
- private:
-
- // Frees the vertex declaration if there is one.
- void FreeVertexDeclaration();
-
- IDirect3DDevice9* d3d_device_;
- IDirect3DVertexDeclaration9* vertex_declaration_;
-};
-} // o3d
-
-#endif // O3D_CORE_WIN_D3D9_STREAM_BANK_D3D9_H_
diff --git a/o3d/core/win/d3d9/texture_d3d9.cc b/o3d/core/win/d3d9/texture_d3d9.cc
deleted file mode 100644
index c90d3f1..0000000
--- a/o3d/core/win/d3d9/texture_d3d9.cc
+++ /dev/null
@@ -1,997 +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 "core/cross/precompile.h"
-#include "core/win/d3d9/texture_d3d9.h"
-
-#include "core/cross/error.h"
-#include "core/cross/types.h"
-#include "core/win/d3d9/utils_d3d9.h"
-#include "core/win/d3d9/renderer_d3d9.h"
-#include "core/win/d3d9/render_surface_d3d9.h"
-
-namespace o3d {
-
-namespace {
-
-Texture::RGBASwizzleIndices g_d3d_abgr32f_swizzle_indices = {2, 1, 0, 3};
-
-// Converts an O3D texture format to a D3D texture format.
-D3DFORMAT DX9Format(Texture::Format format) {
- switch (format) {
- case Texture::XRGB8: return D3DFMT_X8R8G8B8;
- case Texture::ARGB8: return D3DFMT_A8R8G8B8;
- case Texture::ABGR16F: return D3DFMT_A16B16G16R16F;
- case Texture::R32F: return D3DFMT_R32F;
- case Texture::ABGR32F: return D3DFMT_A32B32G32R32F;
- case Texture::DXT1: return D3DFMT_DXT1;
- case Texture::DXT3: return D3DFMT_DXT3;
- case Texture::DXT5: return D3DFMT_DXT5;
- default: return D3DFMT_UNKNOWN;
- };
-}
-
-// Converts a TextureCUBE::CubeFace value to an equivalent D3D9 value.
-static D3DCUBEMAP_FACES DX9CubeFace(TextureCUBE::CubeFace face) {
- switch (face) {
- case TextureCUBE::FACE_POSITIVE_X:
- return D3DCUBEMAP_FACE_POSITIVE_X;
- case TextureCUBE::FACE_NEGATIVE_X:
- return D3DCUBEMAP_FACE_NEGATIVE_X;
- case TextureCUBE::FACE_POSITIVE_Y:
- return D3DCUBEMAP_FACE_POSITIVE_Y;
- case TextureCUBE::FACE_NEGATIVE_Y:
- return D3DCUBEMAP_FACE_NEGATIVE_Y;
- case TextureCUBE::FACE_POSITIVE_Z:
- return D3DCUBEMAP_FACE_POSITIVE_Z;
- case TextureCUBE::FACE_NEGATIVE_Z:
- return D3DCUBEMAP_FACE_NEGATIVE_Z;
- }
-
- // TODO: Figure out how to get errors out of here to the client.
- DLOG(ERROR) << "Unknown Cube Face enumeration " << face;
- return D3DCUBEMAP_FACE_FORCE_DWORD;
-}
-
-// Constructs an Direct3D texture object. Out variable returns the status of
-// the constructed texture including if resize to POT is required, and the
-// actual mip dimensions used.
-HRESULT CreateTexture2DD3D9(RendererD3D9* renderer,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool enable_render_surfaces,
- bool* resize_to_pot,
- unsigned int* mip_width,
- unsigned int* mip_height,
- IDirect3DTexture9** d3d_texture) {
- IDirect3DDevice9 *d3d_device = renderer->d3d_device();
- *resize_to_pot = !renderer->supports_npot() && !image::IsPOT(width, height);
- *mip_width = width;
- *mip_height = height;
-
- if (*resize_to_pot) {
- *mip_width = image::ComputePOTSize(*mip_width);
- *mip_height = image::ComputePOTSize(*mip_height);
- }
-
- DWORD usage = (enable_render_surfaces) ? D3DUSAGE_RENDERTARGET : 0;
- D3DPOOL pool = (enable_render_surfaces) ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED;
- D3DFORMAT d3d_format = DX9Format(format);
-
- HRESULT tex_result = d3d_device->CreateTexture(*mip_width,
- *mip_height,
- levels,
- usage,
- d3d_format,
- pool,
- d3d_texture,
- NULL);
- if (!HR(tex_result)) {
- DLOG(ERROR) << "2D texture creation failed with the following parameters: "
- << "(" << *mip_width << " x " << *mip_height << ") x "
- << levels << "; format = " << format;
- }
- return tex_result;
-}
-
-// Constructs an Direct3D cube texture object. Out variable returns the
-// status of the constructed texture including if resize to POT is required,
-// and the actual mip edge length used.
-HRESULT CreateTextureCUBED3D9(RendererD3D9* renderer,
- int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces,
- bool* resize_to_pot,
- unsigned int* edge_width,
- IDirect3DCubeTexture9** d3d_texture) {
- IDirect3DDevice9 *d3d_device = renderer->d3d_device();
- *resize_to_pot = !renderer->supports_npot() &&
- !image::IsPOT(edge_length, edge_length);
- *edge_width = edge_length;
- if (*resize_to_pot) {
- *edge_width = image::ComputePOTSize(*edge_width);
- }
-
- DWORD usage = (enable_render_surfaces) ? D3DUSAGE_RENDERTARGET : 0;
- D3DPOOL pool = (enable_render_surfaces) ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED;
- D3DFORMAT d3d_format = DX9Format(format);
-
- HRESULT tex_result = d3d_device->CreateCubeTexture(*edge_width,
- levels,
- usage,
- d3d_format,
- pool,
- d3d_texture,
- NULL);
- if (!HR(tex_result)) {
- DLOG(ERROR) << "CUBE texture creation failed with the following "
- << "parameters: "
- << "(" << *edge_width << " x " << *edge_width << ") x "
- << levels << "; format = " << format;
- }
-
- return tex_result;
-}
-
-// Class providing a construction callback routine for extracting a
-// RenderSurface from a cube-face and mip-level of a cube-texture.
-// Note: This class maintains a reference-counted pointer to the texture
-// object, so that the lifetime of the Texture is guaranteed to be at least
-// as long as that of the class.
-class CubeFaceSurfaceConstructor : public SurfaceConstructor {
- public:
- CubeFaceSurfaceConstructor(TextureCUBED3D9 *texture,
- TextureCUBE::CubeFace face,
- int mip_level)
- : cube_texture_(texture->GetWeakPointer()),
- face_(face),
- mip_level_(mip_level) {
- }
-
- virtual HRESULT ConstructSurface(IDirect3DSurface9** surface) {
- TextureCUBED3D9* texture =
- down_cast<TextureCUBED3D9*>(cube_texture_.Get());
- if (!texture) {
- return E_FAIL;
- }
- IDirect3DCubeTexture9* d3d_cube_texture =
- static_cast<IDirect3DCubeTexture9*>(texture->GetTextureHandle());
- return d3d_cube_texture->GetCubeMapSurface(DX9CubeFace(face_),
- mip_level_,
- surface);
- }
-
- private:
- Texture::WeakPointerType cube_texture_;
- TextureCUBE::CubeFace face_;
- int mip_level_;
- DISALLOW_COPY_AND_ASSIGN(CubeFaceSurfaceConstructor);
-};
-
-// Class providing a construction callback routine for extracting a
-// RenderSurface from a mip-level of a texture.
-// Note: This class maintains a reference-counted pointer to the texture
-// object, so that the lifetime of the Texture is guaranteed to be at least
-// as long as that of the class.
-class TextureSurfaceConstructor : public SurfaceConstructor {
- public:
- TextureSurfaceConstructor(Texture2DD3D9* texture, int mip_level)
- : texture_(texture->GetWeakPointer()),
- mip_level_(mip_level) {
- }
-
- virtual HRESULT ConstructSurface(IDirect3DSurface9** surface) {
- Texture2DD3D9* texture = down_cast<Texture2DD3D9*>(texture_.Get());
- if (!texture) {
- return E_FAIL;
- }
- IDirect3DTexture9* d3d_texture =
- static_cast<IDirect3DTexture9*>(texture->GetTextureHandle());
- return d3d_texture->GetSurfaceLevel(mip_level_, surface);
- }
-
- private:
- Texture::WeakPointerType texture_;
- int mip_level_;
- DISALLOW_COPY_AND_ASSIGN(TextureSurfaceConstructor);
-};
-
-void SetTextureRectUncompressed(Texture::Format format,
- const uint8* src,
- int src_pitch,
- unsigned src_width,
- unsigned src_height,
- uint8* dst,
- int dst_pitch) {
- size_t bytes_per_line = image::ComputePitch(format, src_width);
- for (unsigned yy = 0; yy < src_height; ++yy) {
- memcpy(dst, src, bytes_per_line);
- src += src_pitch;
- dst += dst_pitch;
- }
-}
-
-void SetTextureRectCompressed(Texture::Format format,
- const uint8* src,
- unsigned src_width,
- unsigned src_height,
- uint8* dst,
- int dst_pitch) {
- unsigned blocks_across = (src_width + 3) / 4;
- unsigned blocks_down = (src_height + 3) / 4;
- unsigned bytes_per_block = format == Texture::DXT1 ? 8 : 16;
- unsigned bytes_per_row = bytes_per_block * blocks_across;
- for (unsigned yy = 0; yy < blocks_down; ++yy) {
- memcpy(dst, src, bytes_per_row);
- src += bytes_per_row;
- dst += dst_pitch;
- }
-}
-
-bool SetTextureRect(
- ServiceLocator* service_locator,
- IDirect3DTexture9* d3d_texture,
- Texture::Format format,
- int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned src_width,
- unsigned src_height,
- const void* src_data,
- int src_pitch) {
- DCHECK(src_data);
- bool compressed = Texture::IsCompressedFormat(format);
-
- RECT rect = {dst_left, dst_top, dst_left + src_width, dst_top + src_height};
- D3DLOCKED_RECT out_rect = {0};
-
- if (!HR(d3d_texture->LockRect(
- level, &out_rect, compressed ? NULL : &rect, 0))) {
- O3D_ERROR(service_locator) << "Failed to Lock Texture2D (D3D9)";
- return false;
- }
-
- const uint8* src = static_cast<const uint8*>(src_data);
- uint8* dst = static_cast<uint8*>(out_rect.pBits);
- if (!compressed) {
- SetTextureRectUncompressed(format, src, src_pitch, src_width, src_height,
- dst, out_rect.Pitch);
- } else {
- SetTextureRectCompressed(
- format, src, src_width, src_height, dst, out_rect.Pitch);
- }
- if (!HR(d3d_texture->UnlockRect(level))) {
- O3D_ERROR(service_locator) << "Failed to Unlock Texture2D (D3D9)";
- return false;
- }
- return true;
-}
-
-bool SetTextureFaceRect(
- ServiceLocator* service_locator,
- IDirect3DCubeTexture9* d3d_texture,
- Texture::Format format,
- TextureCUBE::CubeFace face,
- int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned src_width,
- unsigned src_height,
- const void* src_data,
- int src_pitch) {
- DCHECK(src_data);
- bool compressed = Texture::IsCompressedFormat(format);
-
- RECT rect = {dst_left, dst_top, dst_left + src_width, dst_top + src_height};
- D3DLOCKED_RECT out_rect = {0};
-
- D3DCUBEMAP_FACES d3d_face = DX9CubeFace(face);
-
- if (!HR(d3d_texture->LockRect(
- d3d_face, level, &out_rect, compressed ? NULL : &rect, 0))) {
- O3D_ERROR(service_locator) << "Failed to Lock TextureCUBE (D3D9)";
- return false;
- }
-
- const uint8* src = static_cast<const uint8*>(src_data);
- uint8* dst = static_cast<uint8*>(out_rect.pBits);
- if (!compressed) {
- SetTextureRectUncompressed(format, src, src_pitch, src_width, src_height,
- dst, out_rect.Pitch);
- } else {
- SetTextureRectCompressed(
- format, src, src_width, src_height, dst, out_rect.Pitch);
- }
- if (!HR(d3d_texture->UnlockRect(d3d_face, level))) {
- O3D_ERROR(service_locator) << "Failed to Unlock TextureCUBE (D3D9)";
- return false;
- }
- return true;
-}
-
-} // unnamed namespace
-
-// Constructs a 2D texture object from the given (existing) D3D 2D texture.
-Texture2DD3D9::Texture2DD3D9(ServiceLocator* service_locator,
- IDirect3DTexture9* tex,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool resize_to_pot,
- bool enable_render_surfaces)
- : Texture2D(service_locator,
- width,
- height,
- format,
- levels,
- enable_render_surfaces),
- resize_to_pot_(resize_to_pot),
- d3d_texture_(tex),
- backing_bitmap_(Bitmap::Ref(new Bitmap(service_locator))) {
- DCHECK(tex);
-}
-
-// Attempts to create a IDirect3DTexture9 with the given specs. If the creation
-// of the texture succeeds then it creates a Texture2DD3D9 object around it and
-// returns it. This is the safe way to create a Texture2DD3D9 object that
-// contains a valid D3D9 texture.
-Texture2DD3D9* Texture2DD3D9::Create(ServiceLocator* service_locator,
- Texture::Format format,
- int levels,
- int width,
- int height,
- RendererD3D9* renderer,
- bool enable_render_surfaces) {
- DCHECK_NE(format, Texture::UNKNOWN_FORMAT);
- CComPtr<IDirect3DTexture9> d3d_texture;
- bool resize_to_pot;
- unsigned int mip_width, mip_height;
- if (!HR(CreateTexture2DD3D9(renderer,
- format,
- levels,
- width,
- height,
- enable_render_surfaces,
- &resize_to_pot,
- &mip_width,
- &mip_height,
- &d3d_texture))) {
- DLOG(ERROR) << "Failed to create Texture2D (D3D9) : ";
- return NULL;
- }
-
- Texture2DD3D9 *texture = new Texture2DD3D9(service_locator,
- d3d_texture,
- format,
- levels,
- width,
- height,
- resize_to_pot,
- enable_render_surfaces);
-
- if (resize_to_pot) {
- texture->backing_bitmap_->Allocate(format, width, height, levels,
- Bitmap::IMAGE);
- }
-
- // Clear the texture.
- // This is platform specific because some platforms, (command-buffers),
- // will guarantee the textures are cleared so we don't have to.
- {
- size_t row_size = image::ComputeMipChainSize(width, 1, format, 1);
- scoped_array<uint8> zero(new uint8[row_size]);
- memset(zero.get(), 0, row_size);
- for (int level = 0; level < levels; ++level) {
- if (enable_render_surfaces) {
- texture->GetRenderSurface(level);
- } else if (!texture->IsCompressed()) {
- texture->SetRect(level, 0, 0,
- image::ComputeMipDimension(level, width),
- image::ComputeMipDimension(level, height),
- zero.get(), 0);
- }
- }
- }
-
- return texture;
-}
-
-// Destructor releases the D3D9 texture resource.
-Texture2DD3D9::~Texture2DD3D9() {
- d3d_texture_ = NULL;
-}
-
-void Texture2DD3D9::UpdateBackedMipLevel(unsigned int level) {
- DCHECK_LT(level, static_cast<unsigned int>(levels()));
- DCHECK(backing_bitmap_->image_data());
- DCHECK_EQ(backing_bitmap_->width(), width());
- DCHECK_EQ(backing_bitmap_->height(), height());
- DCHECK_EQ(backing_bitmap_->format(), format());
- DCHECK_EQ(backing_bitmap_->num_mipmaps(), levels());
-
- unsigned int mip_width = image::ComputeMipDimension(level, width());
- unsigned int mip_height = image::ComputeMipDimension(level, height());
- unsigned int rect_width = mip_width;
- unsigned int rect_height = mip_height;
- rect_width = std::max(1U, image::ComputePOTSize(width()) >> level);
- rect_height = std::max(1U, image::ComputePOTSize(height()) >> level);
-
- RECT rect = {0, 0, rect_width, rect_height};
- D3DLOCKED_RECT out_rect = {0};
-
- if (!HR(d3d_texture_->LockRect(level, &out_rect, &rect, 0))) {
- O3D_ERROR(service_locator())
- << "Failed to lock texture level " << level << ".";
- return;
- }
-
- DCHECK(out_rect.pBits);
- uint8* dst = static_cast<uint8*>(out_rect.pBits);
-
- const uint8 *mip_data = backing_bitmap_->GetMipData(level);
- if (resize_to_pot_) {
- image::Scale(mip_width, mip_height, format(), mip_data,
- rect_width, rect_height,
- static_cast<uint8 *>(out_rect.pBits),
- out_rect.Pitch);
- } else {
- if (!IsCompressed()) {
- SetTextureRectUncompressed(
- format(), mip_data,
- image::ComputePitch(format(), mip_width),
- mip_width, mip_height,
- dst, out_rect.Pitch);
- } else {
- SetTextureRectCompressed(
- format(), mip_data, mip_width, mip_height, dst, out_rect.Pitch);
- }
- }
-
- if (!HR(d3d_texture_->UnlockRect(level))) {
- O3D_ERROR(service_locator())
- << "Failed to unlock texture level " << level << ".";
- }
-}
-
-RenderSurface::Ref Texture2DD3D9::PlatformSpecificGetRenderSurface(
- int mip_level) {
- if (!render_surfaces_enabled()) {
- O3D_ERROR(service_locator())
- << "Attempting to get RenderSurface from non-render-surface-enabled"
- << " Texture: " << name();
- return RenderSurface::Ref(NULL);
- }
-
- if (mip_level >= levels() || mip_level < 0) {
- O3D_ERROR(service_locator())
- << "Attempting to access non-existent mip_level " << mip_level
- << " in render-target texture \"" << name() << "\".";
- return RenderSurface::Ref(NULL);
- }
-
- return RenderSurface::Ref(
- new RenderSurfaceD3D9(
- service_locator(),
- width() >> mip_level,
- height() >> mip_level,
- this,
- new TextureSurfaceConstructor(this, mip_level)));
-}
-
-void Texture2DD3D9::SetRect(int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned src_width,
- unsigned src_height,
- const void* src_data,
- int src_pitch) {
- if (level >= levels() || level < 0) {
- O3D_ERROR(service_locator())
- << "Trying to SetRect on non-existent level " << level
- << " on Texture \"" << name() << "\"";
- return;
- }
- if (render_surfaces_enabled()) {
- O3D_ERROR(service_locator())
- << "Attempting to SetRect a render-target texture: " << name();
- return;
- }
-
- unsigned mip_width = image::ComputeMipDimension(level, width());
- unsigned mip_height = image::ComputeMipDimension(level, height());
-
- if (dst_left + src_width > mip_width ||
- dst_top + src_height > mip_height) {
- O3D_ERROR(service_locator())
- << "SetRect(" << level << ", " << dst_left << ", " << dst_top << ", "
- << src_width << ", " << src_height << ") out of range for texture << \""
- << name() << "\"";
- return;
- }
-
- bool entire_rect = dst_left == 0 && dst_top == 0 &&
- src_width == mip_width && src_height == mip_height;
- bool compressed = IsCompressed();
-
- if (compressed && !entire_rect) {
- O3D_ERROR(service_locator())
- << "SetRect must be full rectangle for compressed textures";
- return;
- }
-
- bool success = true;
- if (resize_to_pot_) {
- DCHECK(backing_bitmap_->image_data());
- DCHECK(!compressed);
- // We need to update the backing mipmap and then use that to update the
- // texture.
- backing_bitmap_->SetRect(
- level, dst_left, dst_top, src_width, src_height, src_data, src_pitch);
- UpdateBackedMipLevel(level);
- } else {
- success = SetTextureRect(service_locator(),
- d3d_texture_,
- format(),
- level,
- dst_left,
- dst_top,
- src_width,
- src_height,
- src_data,
- src_pitch);
- }
- if (success && level == 0) {
- TextureUpdated();
- }
-}
-
-// Locks the given mipmap level of this texture for loading from main memory,
-// and returns a pointer to the buffer.
-bool Texture2DD3D9::PlatformSpecificLock(
- int level, void** texture_data, int* pitch, Texture::AccessMode mode) {
- DCHECK(texture_data);
- DCHECK(pitch);
- DCHECK_GE(level, 0);
- DCHECK_LT(level, levels());
-
- unsigned int mip_width = image::ComputeMipDimension(level, width());
- unsigned int mip_height = image::ComputeMipDimension(level, height());
-
- if (resize_to_pot_) {
- DCHECK(backing_bitmap_->image_data());
- *texture_data = backing_bitmap_->GetMipData(level);
- *pitch = image::ComputePitch(format(), mip_width);
- return true;
- } else {
- RECT rect = {0, 0, mip_width, mip_height};
- D3DLOCKED_RECT out_rect = {0};
-
- if (HR(d3d_texture_->LockRect(level, &out_rect, &rect,
- mode == kReadOnly ? D3DLOCK_READONLY : 0))) {
- *texture_data = out_rect.pBits;
- *pitch = out_rect.Pitch;
- return true;
- } else {
- *texture_data = NULL;
- return false;
- }
- }
-}
-
-// Unlocks the given mipmap level of this texture.
-bool Texture2DD3D9::PlatformSpecificUnlock(int level) {
- DCHECK_GE(level, 0);
- DCHECK_LT(level, levels());
-
- bool result = false;
- if (resize_to_pot_) {
- UpdateBackedMipLevel(level);
- result = true;
- } else {
- result = HR(d3d_texture_->UnlockRect(level));
- }
- return result;
-}
-
-bool Texture2DD3D9::OnLostDevice() {
- // Textures created with RenderSurface support are placed in the default
- // pool, so release them here.
- if (render_surfaces_enabled()) {
- d3d_texture_ = NULL;
- }
- return true;
-}
-
-bool Texture2DD3D9::OnResetDevice() {
- if (render_surfaces_enabled()) {
- DCHECK(d3d_texture_ == NULL);
- Renderer* renderer = service_locator()->GetService<Renderer>();
- RendererD3D9 *renderer_d3d9 = down_cast<RendererD3D9*>(renderer);
- bool resize_to_pot;
- unsigned int mip_width, mip_height;
- return HR(CreateTexture2DD3D9(renderer_d3d9,
- format(),
- levels(),
- width(),
- height(),
- render_surfaces_enabled(),
- &resize_to_pot,
- &mip_width,
- &mip_height,
- &d3d_texture_));
- }
- return true;
-}
-
-const Texture::RGBASwizzleIndices& Texture2DD3D9::GetABGR32FSwizzleIndices() {
- return g_d3d_abgr32f_swizzle_indices;
-}
-
-// Constructs a cube texture object from the given (existing) D3D Cube texture.
-TextureCUBED3D9::TextureCUBED3D9(ServiceLocator* service_locator,
- IDirect3DCubeTexture9* tex,
- int edge_length,
- Texture::Format format,
- int levels,
- bool resize_to_pot,
- bool enable_render_surfaces)
- : TextureCUBE(service_locator,
- edge_length,
- format,
- levels,
- enable_render_surfaces),
- resize_to_pot_(resize_to_pot),
- d3d_cube_texture_(tex) {
- for (int ii = 0; ii < static_cast<int>(NUMBER_OF_FACES); ++ii) {
- backing_bitmaps_[ii] = Bitmap::Ref(new Bitmap(service_locator));
- }
-}
-
-// Attempts to create a D3D9 CubeTexture with the given specs. If creation
-// fails the method returns NULL. Otherwise, it wraps around the newly created
-// texture a TextureCUBED3D9 object and returns a pointer to it.
-TextureCUBED3D9* TextureCUBED3D9::Create(ServiceLocator* service_locator,
- Texture::Format format,
- int levels,
- int edge_length,
- RendererD3D9 *renderer,
- bool enable_render_surfaces) {
- DCHECK_NE(format, Texture::UNKNOWN_FORMAT);
- DCHECK_GE(levels, 1);
-
- CComPtr<IDirect3DCubeTexture9> d3d_texture;
- bool resize_to_pot;
- unsigned int edge;
- if (!HR(CreateTextureCUBED3D9(renderer,
- edge_length,
- format,
- levels,
- enable_render_surfaces,
- &resize_to_pot,
- &edge,
- &d3d_texture))) {
- DLOG(ERROR) << "Failed to create TextureCUBE (D3D9)";
- return NULL;
- }
-
- TextureCUBED3D9 *texture = new TextureCUBED3D9(service_locator,
- d3d_texture,
- edge_length,
- format,
- levels,
- resize_to_pot,
- enable_render_surfaces);
-
- if (resize_to_pot) {
- for (int ii = 0; ii < static_cast<int>(NUMBER_OF_FACES); ++ii) {
- texture->backing_bitmaps_[ii]->Allocate(
- format, edge_length, edge_length, levels, Bitmap::IMAGE);
- }
- }
-
- // Clear the texture.
- // This is platform specific because some platforms, (command-buffers), will
- // guarantee the textures are cleared so we don't have to.
- {
- size_t row_size = image::ComputeMipChainSize(edge_length, 1, format, 1);
- scoped_array<uint8> zero(new uint8[row_size]);
- memset(zero.get(), 0, row_size);
- for (int level = 0; level < levels; ++level) {
- for (int face = 0; face < static_cast<int>(NUMBER_OF_FACES); ++face) {
- if (enable_render_surfaces) {
- texture->GetRenderSurface(static_cast<CubeFace>(face), level);
- } else if (!texture->IsCompressed()) {
- texture->SetRect(static_cast<CubeFace>(face),level , 0, 0,
- image::ComputeMipDimension(level, edge_length),
- image::ComputeMipDimension(level, edge_length),
- zero.get(), 0);
- }
- }
- }
- }
-
- return texture;
-}
-
-
-
-// Destructor releases the D3D9 texture resource.
-TextureCUBED3D9::~TextureCUBED3D9() {
- d3d_cube_texture_ = NULL;
-}
-
-void TextureCUBED3D9::UpdateBackedMipLevel(TextureCUBE::CubeFace face,
- unsigned int level) {
- Bitmap* backing_bitmap = backing_bitmaps_[face].Get();
- DCHECK_LT(level, static_cast<unsigned int>(levels()));
- DCHECK(backing_bitmap->image_data());
- DCHECK_EQ(backing_bitmap->width(), edge_length());
- DCHECK_EQ(backing_bitmap->height(), edge_length());
- DCHECK_EQ(backing_bitmap->format(), format());
- DCHECK_EQ(backing_bitmap->num_mipmaps(), levels());
-
- unsigned int mip_edge = std::max(1, edge_length() >> level);
- unsigned int rect_edge = mip_edge;
- if (resize_to_pot_) {
- rect_edge = std::max(1U, image::ComputePOTSize(edge_length()) >> level);
- }
-
- RECT rect = {0, 0, rect_edge, rect_edge};
- D3DLOCKED_RECT out_rect = {0};
- D3DCUBEMAP_FACES d3d_face = DX9CubeFace(face);
-
- if (!HR(d3d_cube_texture_->LockRect(d3d_face, level, &out_rect, &rect, 0))) {
- O3D_ERROR(service_locator())
- << "Failed to lock texture level " << level << " face " << face << ".";
- return;
- }
-
- DCHECK(out_rect.pBits);
- uint8* dst = static_cast<uint8*>(out_rect.pBits);
-
- const uint8 *mip_data = backing_bitmap->GetMipData(level);
- if (resize_to_pot_) {
- image::Scale(mip_edge, mip_edge, format(), mip_data,
- rect_edge, rect_edge,
- static_cast<uint8 *>(out_rect.pBits),
- out_rect.Pitch);
- } else {
- if (!IsCompressed()) {
- SetTextureRectUncompressed(
- format(), mip_data,
- image::ComputePitch(format(), mip_edge),
- mip_edge, mip_edge,
- dst, out_rect.Pitch);
- } else {
- SetTextureRectCompressed(
- format(), mip_data, mip_edge, mip_edge, dst, out_rect.Pitch);
- }
- }
-
- if (!HR(d3d_cube_texture_->UnlockRect(d3d_face, level))) {
- O3D_ERROR(service_locator())
- << "Failed to unlock texture level " << level << " face " << face
- << ".";
- }
-}
-
-RenderSurface::Ref TextureCUBED3D9::PlatformSpecificGetRenderSurface(
- TextureCUBE::CubeFace face,
- int mip_level) {
- if (!render_surfaces_enabled()) {
- O3D_ERROR(service_locator())
- << "Attempting to get RenderSurface from non-render-surface-enabled"
- << " Texture: " << name();
- return RenderSurface::Ref(NULL);
- }
-
- if (mip_level >= levels() || mip_level < 0) {
- O3D_ERROR(service_locator())
- << "Attempting to access non-existent mip_level " << mip_level
- << " in render-target texture \"" << name() << "\".";
- return RenderSurface::Ref(NULL);
- }
-
- int edge = edge_length() >> mip_level;
- return RenderSurface::Ref(
- new RenderSurfaceD3D9(
- service_locator(),
- edge,
- edge,
- this,
- new CubeFaceSurfaceConstructor(this, face, mip_level)));
-}
-
-void TextureCUBED3D9::SetRect(TextureCUBE::CubeFace face,
- int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned src_width,
- unsigned src_height,
- const void* src_data,
- int src_pitch) {
- if (static_cast<int>(face) < 0 || static_cast<int>(face) >= NUMBER_OF_FACES) {
- O3D_ERROR(service_locator())
- << "Trying to SetRect invalid face " << face << " on Texture \""
- << name() << "\"";
- return;
- }
- if (level >= levels() || level < 0) {
- O3D_ERROR(service_locator())
- << "Trying to SetRect non-existent level " << level
- << " on Texture \"" << name() << "\"";
- return;
- }
- if (render_surfaces_enabled()) {
- O3D_ERROR(service_locator())
- << "Attempting to SetRect a render-target texture: " << name();
- return;
- }
-
- unsigned mip_width = image::ComputeMipDimension(level, edge_length());
- unsigned mip_height = mip_width;
-
- if (dst_left + src_width > mip_width ||
- dst_top + src_height > mip_height) {
- O3D_ERROR(service_locator())
- << "SetRect(" << level << ", " << dst_left << ", " << dst_top << ", "
- << src_width << ", " << src_height << ") out of range for texture << \""
- << name() << "\"";
- return;
- }
-
- bool entire_rect = dst_left == 0 && dst_top == 0 &&
- src_width == mip_width && src_height == mip_height;
- bool compressed = IsCompressed();
-
- if (compressed && !entire_rect) {
- O3D_ERROR(service_locator())
- << "SetRect must be full rectangle for compressed textures";
- return;
- }
-
- bool success = true;
- if (resize_to_pot_) {
- Bitmap* backing_bitmap = backing_bitmaps_[face].Get();
- DCHECK(backing_bitmap->image_data());
- DCHECK(!compressed);
- // We need to update the backing mipmap and then use that to update the
- // texture.
- backing_bitmap->SetRect(
- level, dst_left, dst_top, src_width, src_height, src_data, src_pitch);
- UpdateBackedMipLevel(face, level);
- } else {
- success = SetTextureFaceRect(service_locator(),
- d3d_cube_texture_,
- format(),
- face,
- level,
- dst_left,
- dst_top,
- src_width,
- src_height,
- src_data,
- src_pitch);
- }
- if (success && level == 0) {
- TextureUpdated();
- }
-}
-
-// Locks the given face and mipmap level of this texture for loading from
-// main memory, and returns a pointer to the buffer.
-bool TextureCUBED3D9::PlatformSpecificLock(
- CubeFace face, int level, void** texture_data, int* pitch,
- Texture::AccessMode mode) {
- DCHECK(texture_data);
- DCHECK(pitch);
- DCHECK_GE(level, 0);
- DCHECK_LT(level, levels());
-
- unsigned int mip_width = image::ComputeMipDimension(level, edge_length());
- unsigned int mip_height = mip_width;
-
- if (resize_to_pot_) {
- Bitmap* backing_bitmap = backing_bitmaps_[face].Get();
- DCHECK(backing_bitmap->image_data());
- *texture_data = backing_bitmap->GetMipData(level);
- *pitch = image::ComputePitch(format(), mip_width);
- return true;
- } else {
- RECT rect = {0, 0, mip_width, mip_height};
- D3DLOCKED_RECT out_rect = {0};
-
- if (HR(d3d_cube_texture_->LockRect(
- DX9CubeFace(face), level,
- &out_rect, &rect,
- mode == kReadOnly ? D3DLOCK_READONLY : 0))) {
- *texture_data = out_rect.pBits;
- *pitch = out_rect.Pitch;
- return true;
- } else {
- *texture_data = NULL;
- return false;
- }
- }
-}
-
-// Unlocks the given face and mipmap level of this texture.
-bool TextureCUBED3D9::PlatformSpecificUnlock(CubeFace face, int level) {
- DCHECK_GE(level, 0);
- DCHECK_LT(level, levels());
- bool result = false;
- if (resize_to_pot_) {
- UpdateBackedMipLevel(face, level);
- result = true;
- } else {
- result = HR(d3d_cube_texture_->UnlockRect(DX9CubeFace(face), level));
- }
- return result;
-}
-
-bool TextureCUBED3D9::OnLostDevice() {
- // Textures created with RenderSurface support are placed in the default
- // pool, so release them here.
- if (render_surfaces_enabled()) {
- d3d_cube_texture_ = NULL;
- }
- return true;
-}
-
-bool TextureCUBED3D9::OnResetDevice() {
- if (render_surfaces_enabled()) {
- DCHECK(d3d_cube_texture_ == NULL);
- Renderer* renderer = service_locator()->GetService<Renderer>();
- RendererD3D9 *renderer_d3d9 = down_cast<RendererD3D9*>(renderer);
- bool resize_to_pot;
- unsigned int mip_edge;
- return HR(CreateTextureCUBED3D9(renderer_d3d9,
- edge_length(),
- format(),
- levels(),
- render_surfaces_enabled(),
- &resize_to_pot,
- &mip_edge,
- &d3d_cube_texture_));
- }
- return true;
-}
-
-const Texture::RGBASwizzleIndices& TextureCUBED3D9::GetABGR32FSwizzleIndices() {
- return g_d3d_abgr32f_swizzle_indices;
-}
-
-} // namespace o3d
diff --git a/o3d/core/win/d3d9/texture_d3d9.h b/o3d/core/win/d3d9/texture_d3d9.h
deleted file mode 100644
index 8f53ffe..0000000
--- a/o3d/core/win/d3d9/texture_d3d9.h
+++ /dev/null
@@ -1,213 +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 declarations for Texture2DD3D9 and TextureCUBED3D9.
-
-#ifndef O3D_CORE_WIN_D3D9_TEXTURE_D3D9_H_
-#define O3D_CORE_WIN_D3D9_TEXTURE_D3D9_H_
-
-#include <atlbase.h>
-#include <vector>
-
-#include "core/cross/bitmap.h"
-#include "core/cross/texture.h"
-#include "core/cross/types.h"
-
-interface IDirect3DTexture9;
-interface IDirect3DCubeTexture9;
-interface IDirect3DDevice9;
-
-namespace o3d {
-
-class RendererD3D9;
-
-// Texture2DD3D9 implements the Texture2D interface with DX9.
-class Texture2DD3D9 : public Texture2D {
- public:
- typedef SmartPointer<Texture2DD3D9> Ref;
-
- // Creates a new Texture2DD3D9 with the given specs. If the D3D9 texture
- // creation fails then it returns NULL otherwise it returns a pointer to the
- // newly created Texture object.
- static Texture2DD3D9* Create(ServiceLocator* service_locator,
- Texture::Format format,
- int levels,
- int width,
- int height,
- RendererD3D9* renderer,
- bool enable_render_surfaces);
-
- virtual ~Texture2DD3D9();
-
- // Overridden from Texture2D
- virtual void SetRect(int level,
- unsigned left,
- unsigned top,
- unsigned width,
- unsigned height,
- const void* src_data,
- int src_pitch);
-
- // Returns the implementation-specific texture handle for this texture.
- virtual void* GetTextureHandle() const { return d3d_texture_; }
-
- // Handler for lost device. This invalidates the texture for a device reset.
- bool OnLostDevice();
-
- // Handler for reset device. This restores the texture after a device reset.
- bool OnResetDevice();
-
- // Gets a RGBASwizzleIndices that contains a mapping from
- // RGBA to the internal format used by the rendering API.
- virtual const RGBASwizzleIndices& GetABGR32FSwizzleIndices();
-
- protected:
- // Overridden from Texture2D
- virtual bool PlatformSpecificLock(
- int level, void** texture_data, int* pitch, AccessMode mode);
-
- // Overridden from Texture2D
- virtual bool PlatformSpecificUnlock(int level);
-
- // Overridden from Texture2D
- virtual RenderSurface::Ref PlatformSpecificGetRenderSurface(int mip_level);
-
- private:
- // Initializes the Texture2DD3D9 from a DX9 texture.
- Texture2DD3D9(ServiceLocator* service_locator,
- IDirect3DTexture9* tex,
- Texture::Format format,
- int levels,
- int width,
- int height,
- bool resize_to_pot,
- bool enable_render_surfaces);
-
- // Updates a mip level, sending it from the backing bitmap to Direct3D,
- // rescaling it if resize_to_pot_ is set.
- void UpdateBackedMipLevel(unsigned int level);
-
- // Whether or not this texture needs to be resized from NPOT to pot behind
- // the scenes.
- bool resize_to_pot_;
-
- // A pointer to the Direct3D 2D texture object containing this texture.
- CComPtr<IDirect3DTexture9> d3d_texture_;
-
- // A bitmap used to back the NPOT textures on POT-only hardware.
- Bitmap::Ref backing_bitmap_;
-
- DISALLOW_COPY_AND_ASSIGN(Texture2DD3D9);
-};
-
-// TextureCUBED3D9 implements the TextureCUBE interface with DX9.
-class TextureCUBED3D9 : public TextureCUBE {
- public:
- typedef SmartPointer<TextureCUBED3D9> Ref;
-
- // Creates a new TextureCUBED3D9 with the given specs. If the D3D9 texture
- // creation fails then it returns NULL otherwise it returns a pointer to the
- // newly created Texture object.
- static TextureCUBED3D9* Create(ServiceLocator* service_locator,
- Texture::Format format,
- int levels,
- int edge_length,
- RendererD3D9* renderer,
- bool enable_render_surfaces);
-
- virtual ~TextureCUBED3D9();
-
- // Overridden from TextureCUBE
- virtual void SetRect(CubeFace face,
- int level,
- unsigned dst_left,
- unsigned dst_top,
- unsigned width,
- unsigned height,
- const void* src_data,
- int src_pitch);
-
- // Returns the implementation-specific texture handle for this texture.
- virtual void* GetTextureHandle() const { return d3d_cube_texture_; }
-
- // Handler for lost device. This invalidates the texture for a device reset.
- bool OnLostDevice();
-
- // Handler for reset device. This restores the texture after a device reset.
- bool OnResetDevice();
-
- // Gets a RGBASwizzleIndices that contains a mapping from
- // RGBA to the internal format used by the rendering API.
- virtual const RGBASwizzleIndices& GetABGR32FSwizzleIndices();
-
- protected:
- // Overridden from TextureCUBE
- virtual bool PlatformSpecificLock(
- CubeFace face, int level, void** texture_data, int* pitch,
- AccessMode mode);
-
- // Overridden from TextureCUBE
- virtual bool PlatformSpecificUnlock(CubeFace face, int level);
-
- // Overridden from TextureCUBE.
- virtual RenderSurface::Ref PlatformSpecificGetRenderSurface(CubeFace face,
- int level);
-
- private:
- TextureCUBED3D9(ServiceLocator* service_locator,
- IDirect3DCubeTexture9* tex,
- int edge_length,
- Texture::Format format,
- int levels,
- bool resize_to_pot,
- bool enable_render_surfaces);
-
- // Whether or not this texture needs to be resized from NPOT to pot behind
- // the scenes.
- bool resize_to_pot_;
-
- // Updates a mip level, sending it from the backing bitmap to Direct3D,
- // rescaling it if resize_to_pot_ is set.
- void UpdateBackedMipLevel(CubeFace face, unsigned int level);
-
- // A pointer to the Direct3D cube texture object containing this texture.
- CComPtr<IDirect3DCubeTexture9> d3d_cube_texture_;
-
- // Bitmaps used to back the NPOT textures on POT-only hardware.
- Bitmap::Ref backing_bitmaps_[NUMBER_OF_FACES];
-
- DISALLOW_COPY_AND_ASSIGN(TextureCUBED3D9);
-};
-
-} // namespace o3d
-
-#endif // O3D_CORE_WIN_D3D9_TEXTURE_D3D9_H_
diff --git a/o3d/core/win/d3d9/utils_d3d9.cc b/o3d/core/win/d3d9/utils_d3d9.cc
deleted file mode 100644
index 0d0d8e4..0000000
--- a/o3d/core/win/d3d9/utils_d3d9.cc
+++ /dev/null
@@ -1,119 +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 of handy methods used by the
-// O3D DirectX code.
-
-#include "core/cross/precompile.h"
-#include "core/win/d3d9/utils_d3d9.h"
-
-#include "core/cross/field.h"
-
-namespace o3d {
-
-// Converts from a Field datatype to a suitable dx9 type
-D3DDECLTYPE DX9DataType(const Field& field) {
- if (field.IsA(FloatField::GetApparentClass())) {
- switch (field.num_components()) {
- case 1:
- return D3DDECLTYPE_FLOAT1;
- case 2:
- return D3DDECLTYPE_FLOAT2;
- case 3:
- return D3DDECLTYPE_FLOAT3;
- case 4:
- return D3DDECLTYPE_FLOAT4;
- }
- } else if (field.IsA(UByteNField::GetApparentClass())) {
- switch (field.num_components()) {
- case 4:
- return D3DDECLTYPE_D3DCOLOR;
- }
- }
- DLOG(ERROR) << "Unknown Stream DataType";
- return D3DDECLTYPE_UNUSED;
-}
-
-// Converts from Stream::Semantic to a suitable dx9 usage type.
-D3DDECLUSAGE DX9UsageType(Stream::Semantic semantic) {
- switch (semantic) {
- case Stream::POSITION:
- return D3DDECLUSAGE_POSITION;
- break;
- case Stream::NORMAL:
- return D3DDECLUSAGE_NORMAL;
- break;
- case Stream::TANGENT:
- return D3DDECLUSAGE_TANGENT;
- break;
- case Stream::BINORMAL:
- return D3DDECLUSAGE_BINORMAL;
- break;
- case Stream::COLOR:
- return D3DDECLUSAGE_COLOR;
- break;
- case Stream::TEXCOORD:
- return D3DDECLUSAGE_TEXCOORD;
- break;
- }
- DLOG(ERROR) << "Unknown DX9 Usage Type";
- return D3DDECLUSAGE_SAMPLE;
-}
-
-// Convertes a dx9 semantic to a matching Stream semantic.
-Stream::Semantic SemanticFromDX9UsageType(D3DDECLUSAGE usage) {
- switch (usage) {
- case D3DDECLUSAGE_POSITION:
- return Stream::POSITION;
- break;
- case D3DDECLUSAGE_NORMAL:
- return Stream::NORMAL;
- break;
- case D3DDECLUSAGE_TANGENT:
- return Stream::TANGENT;
- break;
- case D3DDECLUSAGE_BINORMAL:
- return Stream::BINORMAL;
- break;
- case D3DDECLUSAGE_COLOR:
- return Stream::COLOR;
- break;
- case D3DDECLUSAGE_TEXCOORD:
- return Stream::TEXCOORD;
- break;
- default:
- DLOG(ERROR) << "Unknown DX9 semantic type";
- return Stream::UNKNOWN_SEMANTIC;
- }
-}
-
-} // namespace o3d
diff --git a/o3d/core/win/d3d9/utils_d3d9.h b/o3d/core/win/d3d9/utils_d3d9.h
deleted file mode 100644
index 6e1cd20..0000000
--- a/o3d/core/win/d3d9/utils_d3d9.h
+++ /dev/null
@@ -1,72 +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 of handy methods and macros used by the
-// O3D DirectX code.
-
-#ifndef O3D_CORE_WIN_D3D9_UTILS_D3D9_H_
-#define O3D_CORE_WIN_D3D9_UTILS_D3D9_H_
-
-#include <d3d9.h>
-#include <DxErr.h>
-#include "base/logging.h"
-#include "core/cross/stream.h"
-
-#define HR(x) ::o3d::VerifyHResult((x), __FILE__, __LINE__, #x)
-
-namespace o3d {
-
-class Field;
-
-inline bool VerifyHResult(HRESULT hr, const char* file, int line,
- const char* call) {
- if (FAILED(hr)) {
- DLOG(ERROR) << "DX Error in file " << file
- << " line " << line << L": "
- << DXGetErrorString(hr) << L": " << call;
- return false;
- }
- return true;
-}
-
-union Float2DWord {
- float my_float;
- DWORD my_dword;
-};
-
-D3DDECLTYPE DX9DataType(const Field& stream);
-D3DDECLUSAGE DX9UsageType(Stream::Semantic semantic);
-Stream::Semantic SemanticFromDX9UsageType(D3DDECLUSAGE usage);
-
-} // namespace o3d
-
-#endif // O3D_CORE_WIN_D3D9_UTILS_D3D9_H_
diff --git a/o3d/core/win/display_window_win.h b/o3d/core/win/display_window_win.h
deleted file mode 100644
index 8684b1b..0000000
--- a/o3d/core/win/display_window_win.h
+++ /dev/null
@@ -1,60 +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_CORE_WIN_DISPLAY_WINDOW_WIN_H_
-#define O3D_CORE_WIN_DISPLAY_WINDOW_WIN_H_
-
-#include <windows.h>
-
-#include "core/cross/display_window.h"
-
-namespace o3d {
-
-/**
- * The DisplayWindowWindows class is a platform-specific
- * representation of a platform's display window. This implements the
- * Windows subclass of the DisplayWindow.
- */
-
-class DisplayWindowWindows : public DisplayWindow {
- public:
- DisplayWindowWindows() : hwnd_(NULL) {}
- virtual ~DisplayWindowWindows() {}
- HWND hwnd() const { return hwnd_; }
- void set_hwnd(const HWND& hwnd) { hwnd_ = hwnd; }
- private:
- HWND hwnd_;
- DISALLOW_COPY_AND_ASSIGN(DisplayWindowWindows);
-};
-} // end namespace o3d
-
-#endif // O3D_CORE_WIN_DISPLAY_WINDOW_WIN_H_
diff --git a/o3d/core/win/performance_timer.cc b/o3d/core/win/performance_timer.cc
deleted file mode 100644
index 8be923d..0000000
--- a/o3d/core/win/performance_timer.cc
+++ /dev/null
@@ -1,79 +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.
- */
-
-
-// The PerformanceTimer class measures elapsed time between Start and
-// Stop (using the highest resolution timer available on the
-// platform).
-
-#include "core/cross/precompile.h"
-
-#include "core/cross/performance_timer.h"
-
-#include "base/logging.h"
-
-namespace o3d {
-
-PerformanceTimer::PerformanceTimer(const char *name)
- : name_(name),
- start_time_(0),
- accum_time_(0) {
- start_time_ = 0;
- accum_time_ = 0;
-}
-
-void PerformanceTimer::Start() {
- LARGE_INTEGER start;
- QueryPerformanceCounter(&start);
- start_time_ = start.QuadPart;
-}
-
-void PerformanceTimer::Stop() {
- LARGE_INTEGER end;
- QueryPerformanceCounter(&end);
- accum_time_ += end.QuadPart - start_time_;
-}
-
-double PerformanceTimer::GetElapsedTime() {
- LARGE_INTEGER freq;
- QueryPerformanceFrequency(&freq);
- return static_cast<double>(accum_time_) / freq.QuadPart;
-}
-
-void PerformanceTimer::Print() {
- LOG(INFO) << name_.c_str() << " " << GetElapsedTime() << " seconds";
-}
-
-void PerformanceTimer::StopAndPrint() {
- Stop();
- Print();
-}
-}
diff --git a/o3d/documentation/Doxyfile b/o3d/documentation/Doxyfile
deleted file mode 100644
index b4e98e2..0000000
--- a/o3d/documentation/Doxyfile
+++ /dev/null
@@ -1,293 +0,0 @@
-# Doxyfile 1.5.7.1
-
-#---------------------------------------------------------------------------
-# Project related configuration options
-#---------------------------------------------------------------------------
-DOXYFILE_ENCODING = UTF-8
-PROJECT_NAME = O3D
-PROJECT_NUMBER =
-OUTPUT_DIRECTORY = scons-out/docs/obj/documentation
-CREATE_SUBDIRS = NO
-OUTPUT_LANGUAGE = English
-BRIEF_MEMBER_DESC = YES
-REPEAT_BRIEF = YES
-ABBREVIATE_BRIEF = "The $name class" \
- "The $name widget" \
- "The $name file" \
- is \
- provides \
- specifies \
- contains \
- represents \
- a \
- an \
- the
-ALWAYS_DETAILED_SEC = NO
-INLINE_INHERITED_MEMB = YES
-FULL_PATH_NAMES = NO
-STRIP_FROM_PATH = "C:/Documents and Settings/rlp/"
-STRIP_FROM_INC_PATH =
-SHORT_NAMES = NO
-JAVADOC_AUTOBRIEF = YES
-QT_AUTOBRIEF = NO
-MULTILINE_CPP_IS_BRIEF = NO
-INHERIT_DOCS = YES
-SEPARATE_MEMBER_PAGES = NO
-TAB_SIZE = 8
-ALIASES =
-OPTIMIZE_OUTPUT_FOR_C = NO
-OPTIMIZE_OUTPUT_JAVA = YES
-OPTIMIZE_FOR_FORTRAN = NO
-OPTIMIZE_OUTPUT_VHDL = NO
-BUILTIN_STL_SUPPORT = NO
-CPP_CLI_SUPPORT = NO
-SIP_SUPPORT = NO
-IDL_PROPERTY_SUPPORT = YES
-DISTRIBUTE_GROUP_DOC = NO
-SUBGROUPING = YES
-TYPEDEF_HIDES_STRUCT = NO
-SYMBOL_CACHE_SIZE = 0
-#---------------------------------------------------------------------------
-# Build related configuration options
-#---------------------------------------------------------------------------
-EXTRACT_ALL = NO
-EXTRACT_PRIVATE = NO
-EXTRACT_STATIC = NO
-EXTRACT_LOCAL_CLASSES = YES
-EXTRACT_LOCAL_METHODS = NO
-EXTRACT_ANON_NSPACES = NO
-HIDE_UNDOC_MEMBERS = YES
-HIDE_UNDOC_CLASSES = YES
-HIDE_FRIEND_COMPOUNDS = NO
-HIDE_IN_BODY_DOCS = NO
-INTERNAL_DOCS = NO
-CASE_SENSE_NAMES = NO
-HIDE_SCOPE_NAMES = NO
-SHOW_INCLUDE_FILES = NO
-INLINE_INFO = YES
-SORT_MEMBER_DOCS = YES
-SORT_BRIEF_DOCS = NO
-SORT_GROUP_NAMES = NO
-SORT_BY_SCOPE_NAME = YES
-GENERATE_TODOLIST = YES
-GENERATE_TESTLIST = YES
-GENERATE_BUGLIST = YES
-GENERATE_DEPRECATEDLIST= YES
-ENABLED_SECTIONS =
-MAX_INITIALIZER_LINES = 30
-SHOW_USED_FILES = NO
-SHOW_DIRECTORIES = NO
-SHOW_FILES = NO
-SHOW_NAMESPACES = YES
-FILE_VERSION_FILTER =
-LAYOUT_FILE = documentation/DoxygenLayout.xml
-#---------------------------------------------------------------------------
-# configuration options related to warning and progress messages
-#---------------------------------------------------------------------------
-QUIET = NO
-WARNINGS = YES
-WARN_IF_UNDOCUMENTED = YES
-WARN_IF_DOC_ERROR = YES
-WARN_NO_PARAMDOC = NO
-WARN_FORMAT = "$file:$line: $text"
-WARN_LOGFILE =
-#---------------------------------------------------------------------------
-# configuration options related to the input files
-#---------------------------------------------------------------------------
-INPUT = scons-out/docs/obj/documentation
-INPUT_ENCODING = UTF-8
-FILE_PATTERNS = *.c \
- *.cc \
- *.cxx \
- *.cpp \
- *.c++ \
- *.d \
- *.java \
- *.ii \
- *.ixx \
- *.ipp \
- *.i++ \
- *.inl \
- *.h \
- *.hh \
- *.hxx \
- *.hpp \
- *.h++ \
- *.idl \
- *.odl \
- *.cs \
- *.php \
- *.php3 \
- *.inc \
- *.m \
- *.mm \
- *.dox \
- *.py \
- *.f90 \
- *.f \
- *.vhd \
- *.vhdl
-RECURSIVE = NO
-EXCLUDE =
-EXCLUDE_SYMLINKS = NO
-EXCLUDE_PATTERNS =
-EXCLUDE_SYMBOLS =
-EXAMPLE_PATH =
-EXAMPLE_PATTERNS = *
-EXAMPLE_RECURSIVE = NO
-IMAGE_PATH =
-INPUT_FILTER =
-FILTER_PATTERNS =
-FILTER_SOURCE_FILES = NO
-#---------------------------------------------------------------------------
-# configuration options related to source browsing
-#---------------------------------------------------------------------------
-SOURCE_BROWSER = NO
-INLINE_SOURCES = NO
-STRIP_CODE_COMMENTS = YES
-REFERENCED_BY_RELATION = NO
-REFERENCES_RELATION = NO
-REFERENCES_LINK_SOURCE = YES
-USE_HTAGS = NO
-VERBATIM_HEADERS = NO
-#---------------------------------------------------------------------------
-# configuration options related to the alphabetical class index
-#---------------------------------------------------------------------------
-ALPHABETICAL_INDEX = NO
-COLS_IN_ALPHA_INDEX = 5
-IGNORE_PREFIX =
-#---------------------------------------------------------------------------
-# configuration options related to the HTML output
-#---------------------------------------------------------------------------
-GENERATE_HTML = YES
-HTML_OUTPUT = html
-HTML_FILE_EXTENSION = .html
-HTML_HEADER = documentation/header.html
-HTML_FOOTER = documentation/footer.html
-HTML_STYLESHEET = documentation/stylesheet.css
-HTML_ALIGN_MEMBERS = NO
-HTML_DYNAMIC_SECTIONS = NO
-GENERATE_DOCSET = NO
-DOCSET_FEEDNAME = "Doxygen generated docs"
-DOCSET_BUNDLE_ID = org.doxygen.Project
-GENERATE_HTMLHELP = NO
-CHM_FILE =
-HHC_LOCATION =
-GENERATE_CHI = NO
-CHM_INDEX_ENCODING =
-BINARY_TOC = NO
-TOC_EXPAND = NO
-GENERATE_QHP = NO
-QCH_FILE =
-QHP_NAMESPACE = org.doxygen.Project
-QHP_VIRTUAL_FOLDER = doc
-QHG_LOCATION =
-DISABLE_INDEX = NO
-ENUM_VALUES_PER_LINE = 4
-GENERATE_TREEVIEW = NONE
-TREEVIEW_WIDTH = 251
-FORMULA_FONTSIZE = 10
-#---------------------------------------------------------------------------
-# configuration options related to the LaTeX output
-#---------------------------------------------------------------------------
-GENERATE_LATEX = YES
-LATEX_OUTPUT = latex
-LATEX_CMD_NAME = latex
-MAKEINDEX_CMD_NAME = makeindex
-COMPACT_LATEX = NO
-PAPER_TYPE = a4wide
-EXTRA_PACKAGES =
-LATEX_HEADER =
-PDF_HYPERLINKS = YES
-USE_PDFLATEX = YES
-LATEX_BATCHMODE = NO
-LATEX_HIDE_INDICES = NO
-#---------------------------------------------------------------------------
-# configuration options related to the RTF output
-#---------------------------------------------------------------------------
-GENERATE_RTF = NO
-RTF_OUTPUT = rtf
-COMPACT_RTF = NO
-RTF_HYPERLINKS = NO
-RTF_STYLESHEET_FILE =
-RTF_EXTENSIONS_FILE =
-#---------------------------------------------------------------------------
-# configuration options related to the man page output
-#---------------------------------------------------------------------------
-GENERATE_MAN = NO
-MAN_OUTPUT = man
-MAN_EXTENSION = .3
-MAN_LINKS = NO
-#---------------------------------------------------------------------------
-# configuration options related to the XML output
-#---------------------------------------------------------------------------
-GENERATE_XML = NO
-XML_OUTPUT = xml
-XML_SCHEMA =
-XML_DTD =
-XML_PROGRAMLISTING = YES
-#---------------------------------------------------------------------------
-# configuration options for the AutoGen Definitions output
-#---------------------------------------------------------------------------
-GENERATE_AUTOGEN_DEF = NO
-#---------------------------------------------------------------------------
-# configuration options related to the Perl module output
-#---------------------------------------------------------------------------
-GENERATE_PERLMOD = NO
-PERLMOD_LATEX = NO
-PERLMOD_PRETTY = YES
-PERLMOD_MAKEVAR_PREFIX =
-#---------------------------------------------------------------------------
-# Configuration options related to the preprocessor
-#---------------------------------------------------------------------------
-ENABLE_PREPROCESSING = YES
-MACRO_EXPANSION = NO
-EXPAND_ONLY_PREDEF = NO
-SEARCH_INCLUDES = YES
-INCLUDE_PATH =
-INCLUDE_FILE_PATTERNS =
-PREDEFINED =
-EXPAND_AS_DEFINED =
-SKIP_FUNCTION_MACROS = YES
-#---------------------------------------------------------------------------
-# Configuration::additions related to external references
-#---------------------------------------------------------------------------
-TAGFILES =
-GENERATE_TAGFILE =
-ALLEXTERNALS = NO
-EXTERNAL_GROUPS = YES
-PERL_PATH = /usr/bin/perl
-#---------------------------------------------------------------------------
-# Configuration options related to the dot tool
-#---------------------------------------------------------------------------
-CLASS_DIAGRAMS = NO
-MSCGEN_PATH =
-HIDE_UNDOC_RELATIONS = YES
-HAVE_DOT = NO
-DOT_FONTNAME = FreeSans
-DOT_FONTSIZE = 10
-DOT_FONTPATH =
-CLASS_GRAPH = YES
-COLLABORATION_GRAPH = NO
-GROUP_GRAPHS = NO
-UML_LOOK = NO
-TEMPLATE_RELATIONS = NO
-INCLUDE_GRAPH = YES
-INCLUDED_BY_GRAPH = YES
-CALL_GRAPH = NO
-CALLER_GRAPH = NO
-GRAPHICAL_HIERARCHY = YES
-DIRECTORY_GRAPH = YES
-DOT_IMAGE_FORMAT = png
-DOT_PATH =
-DOTFILE_DIRS =
-DOT_GRAPH_MAX_NODES = 50
-MAX_DOT_GRAPH_DEPTH = 1000
-DOT_TRANSPARENT = YES
-DOT_MULTI_TARGETS = NO
-GENERATE_LEGEND = YES
-DOT_CLEANUP = YES
-#---------------------------------------------------------------------------
-# Configuration::additions related to the search engine
-#---------------------------------------------------------------------------
-SEARCHENGINE = NO
diff --git a/o3d/documentation/DoxygenLayout.xml b/o3d/documentation/DoxygenLayout.xml
deleted file mode 100644
index 17ccc77..0000000
--- a/o3d/documentation/DoxygenLayout.xml
+++ /dev/null
@@ -1,182 +0,0 @@
-<doxygenlayout version="1.0">
- <!-- Navigation index tabs for HTML output -->
- <navindex>
- <tab type="mainpage" visible="yes" title=""/>
- <tab type="pages" visible="yes" title=""/>
- <tab type="modules" visible="yes" title=""/>
- <tab type="namespaces" visible="yes" title="">
- <tab type="namespaces" visible="yes" title=""/>
- <tab type="namespacemembers" visible="yes" title=""/>
- </tab>
- <tab type="classes" visible="yes" title="">
- <tab type="classes" visible="yes" title=""/>
- <tab type="classindex" visible="$ALPHABETICAL_INDEX" title=""/>
- <tab type="hierarchy" visible="yes" title=""/>
- <tab type="classmembers" visible="yes" title=""/>
- </tab>
- <tab type="files" visible="yes" title="">
- <tab type="files" visible="yes" title=""/>
- <tab type="globals" visible="yes" title=""/>
- </tab>
- <tab type="dirs" visible="yes" title=""/>
- <tab type="examples" visible="yes" title=""/>
- </navindex>
-
- <!-- Layout definition for a class page -->
- <class>
- <briefdescription visible="yes"/>
- <includes visible="$SHOW_INCLUDE_FILES"/>
- <inheritancegraph visible="$CLASS_GRAPH"/>
- <allmemberslink visible="yes"/>
- <collaborationgraph visible="$COLLABORATION_GRAPH"/>
- <detaileddescription title=""/>
- <memberdecl>
- <membergroups visible="yes"/>
- <nestedclasses visible="yes" title=""/>
- <publictypes title=""/>
- <publicslots title=""/>
- <signals title=""/>
- <publicmethods title=""/>
- <publicstaticmethods title=""/>
- <publicattributes title=""/>
- <publicstaticattributes title=""/>
- <protectedtypes title=""/>
- <protectedslots title=""/>
- <protectedmethods title=""/>
- <protectedstaticmethods title=""/>
- <protectedattributes title=""/>
- <protectedstaticattributes title=""/>
- <packagetypes title=""/>
- <packagemethods title=""/>
- <packagestaticmethods title=""/>
- <packageattributes title=""/>
- <packagestaticattributes title=""/>
- <properties title=""/>
- <events title=""/>
- <privatetypes title=""/>
- <privateslots title=""/>
- <privatemethods title=""/>
- <privatestaticmethods title=""/>
- <privateattributes title=""/>
- <privatestaticattributes title=""/>
- <friends title=""/>
- <related title="" subtitle=""/>
- </memberdecl>
- <memberdef>
- <typedefs title=""/>
- <enums title=""/>
- <constructors title=""/>
- <functions title=""/>
- <related title=""/>
- <variables title=""/>
- <properties title=""/>
- <events title=""/>
- </memberdef>
- <usedfiles visible="$SHOW_USED_FILES"/>
- <authorsection visible="yes"/>
- </class>
-
- <!-- Layout definition for a namespace page -->
- <namespace>
- <briefdescription visible="yes"/>
- <memberdecl>
- <nestednamespaces visible="yes" title=""/>
- <classes visible="yes" title=""/>
- <membergroups visible="yes"/>
- <typedefs title=""/>
- <enums title=""/>
- <functions title=""/>
- <variables title=""/>
- </memberdecl>
- <detaileddescription title=""/>
- <memberdef>
- <typedefs title=""/>
- <enums title=""/>
- <functions title=""/>
- <variables title=""/>
- </memberdef>
- <authorsection visible="yes"/>
- </namespace>
-
- <!-- Layout definition for a file page -->
- <file>
- <briefdescription visible="yes"/>
- <includes visible="$SHOW_INCLUDE_FILES"/>
- <includegraph visible="$INCLUDE_GRAPH"/>
- <includedbygraph visible="$INCLUDED_BY_GRAPH"/>
- <sourcelink visible="yes"/>
- <memberdecl>
- <classes visible="yes" title=""/>
- <namespaces visible="yes" title=""/>
- <defines title=""/>
- <typedefs title=""/>
- <enums title=""/>
- <functions title=""/>
- <variables title=""/>
- </memberdecl>
- <detaileddescription title=""/>
- <memberdef>
- <defines title=""/>
- <typedefs title=""/>
- <enums title=""/>
- <functions title=""/>
- <variables title=""/>
- </memberdef>
- <authorsection/>
- </file>
-
- <!-- Layout definition for a group page -->
- <group>
- <briefdescription visible="yes"/>
- <groupgraph visible="$GROUP_GRAPHS"/>
- <memberdecl>
- <classes visible="yes" title=""/>
- <namespaces visible="yes" title=""/>
- <dirs visible="yes" title=""/>
- <nestedgroups visible="yes" title=""/>
- <files visible="yes" title=""/>
- <defines title=""/>
- <typedefs title=""/>
- <enums title=""/>
- <enumvalues title=""/>
- <functions title=""/>
- <variables title=""/>
- <signals title=""/>
- <publicslots title=""/>
- <protectedslots title=""/>
- <privateslots title=""/>
- <events title=""/>
- <properties title=""/>
- <friends title=""/>
- </memberdecl>
- <detaileddescription title=""/>
- <memberdef>
- <pagedocs/>
- <defines title=""/>
- <typedefs title=""/>
- <enums title=""/>
- <enumvalues title=""/>
- <functions title=""/>
- <variables title=""/>
- <signals title=""/>
- <publicslots title=""/>
- <protectedslots title=""/>
- <privateslots title=""/>
- <events title=""/>
- <properties title=""/>
- <friends title=""/>
- </memberdef>
- <authorsection visible="yes"/>
- </group>
-
- <!-- Layout definition for a directory page -->
- <directory>
- <briefdescription visible="yes"/>
- <directorygraph visible="yes"/>
- <memberdecl>
- <dirs visible="yes"/>
- <files visible="yes"/>
- </memberdecl>
- <detaileddescription title=""/>
- </directory>
-</doxygenlayout>
diff --git a/o3d/documentation/build_docs.bat b/o3d/documentation/build_docs.bat
deleted file mode 100755
index bad9281..0000000
--- a/o3d/documentation/build_docs.bat
+++ /dev/null
@@ -1,33 +0,0 @@
-@echo OFF
-REM Copyright 2009, Google Inc.
-REM All rights reserved.
-REM
-REM Redistribution and use in source and binary forms, with or without
-REM modification, are permitted provided that the following conditions are
-REM met:
-REM
-REM * Redistributions of source code must retain the above copyright
-REM notice, this list of conditions and the following disclaimer.
-REM * Redistributions in binary form must reproduce the above
-REM copyright notice, this list of conditions and the following disclaimer
-REM in the documentation and/or other materials provided with the
-REM distribution.
-REM * Neither the name of Google Inc. nor the names of its
-REM contributors may be used to endorse or promote products derived from
-REM this software without specific prior written permission.
-REM
-REM THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-REM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-REM LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-REM A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-REM OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-REM SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-REM LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-REM DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-REM THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-REM (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-REM OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-set PYTHONDIR=%~dp0..\..\third_party\python_24
-call %PYTHONDIR%\setup_env.bat
-%PYTHONDIR%\python.exe %~dp0\build_docs.py %*
diff --git a/o3d/documentation/build_docs.py b/o3d/documentation/build_docs.py
deleted file mode 100755
index bfd3538..0000000
--- a/o3d/documentation/build_docs.py
+++ /dev/null
@@ -1,354 +0,0 @@
-#!/usr/bin/python2.4
-# 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.
-
-
-"""Docbuilder for O3D and o3djs."""
-
-
-import os
-import os.path
-import sys
-import imp
-import types
-import glob
-import subprocess
-import shutil
-import re
-
-
-_java_exe = ''
-_output_dir = ''
-_third_party_dir = ''
-_o3d_third_party_dir = ''
-_script_path = os.path.dirname(os.path.realpath(__file__))
-_js_copyright = """
-/*
- * 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.
- */
-"""
-
-GlobalsDict = { }
-
-
-def MakePath(*file_paths):
- """Makes a path absolute given a path relative to this script."""
- return os.path.join(_script_path, *file_paths)
-
-
-def MakeCommandName(name):
- """adds '.exe' if on Windows"""
- if os.name == 'nt':
- return name + '.exe'
- return name
-
-
-def Execute(args):
- """Executes an external program."""
- # Comment the next line in for debugging.
- # print "Execute: ", ' '.join(args)
- if subprocess.call(args) > 0:
- raise RuntimeError('FAILED: ' + ' '.join(args))
-
-
-def AppendBasePath(folder, filenames):
- """Appends a base path to a ist of files"""
- return [os.path.join(folder, filename) for filename in filenames]
-
-
-def RunNixysa(idl_files, generate, output_dir, nixysa_options):
- """Executes Nixysa."""
- Execute([
- sys.executable,
- MakePath(_o3d_third_party_dir, 'nixysa', 'codegen.py'),
- '--binding-module=o3d:%s' % MakePath('..', 'plugin', 'o3d_binding.py'),
- '--generate=' + generate,
- '--force',
- '--output-dir=' + output_dir] +
- nixysa_options +
- idl_files)
-
-
-def RunJSDocToolkit(js_files, ezt_output_dir, html_output_dir, prefix, mode,
- baseURL, topURL, exports_file):
- """Executes the JSDocToolkit."""
- list_filename = MakePath(_output_dir, 'doclist.conf')
- f = open(list_filename, 'w')
- f.write('{\nD:{\n')
- f.write('prefix: "%s",\n' % prefix)
- f.write('baseURL: "%s",\n' % baseURL)
- f.write('topURL: "%s",\n' % topURL)
- f.write('mode: "%s",\n' % mode)
- f.write('htmlOutDir: "%s",\n' % html_output_dir.replace('\\', '/'))
- f.write('exportsFile: "%s",\n' % exports_file.replace('\\', '/'))
- f.write('endMarker: ""\n')
- f.write('},\n')
- f.write('_: [\n')
- for filename in js_files:
- f.write('"%s",\n' % filename.replace('\\', '/'))
- f.write(']\n}\n')
- f.close()
-
- files_dir = MakePath(_third_party_dir, 'jsdoctoolkit', 'files')
- Execute([
- _java_exe,
- '-Djsdoc.dir=%s' % files_dir,
- '-jar',
- MakePath(files_dir, 'jsrun.jar'),
- MakePath(files_dir, 'app', 'run.js'),
- '-v',
- '-t=%s' % MakePath('jsdoc-toolkit-templates'),
- '-d=' + ezt_output_dir,
- '-c=' + list_filename])
-
-
-def DeleteOldDocs(docs_js_outpath):
- try:
- shutil.rmtree(docs_js_outpath);
- except:
- pass
-
-
-def BuildJavaScriptForDocsFromIDLs(idl_files, output_dir):
- RunNixysa(idl_files, 'jsheader', output_dir,
- ['--properties-equal-undefined', '--overloaded-function-docs'])
-
-
-def BuildJavaScriptForExternsFromIDLs(idl_files, output_dir):
- if (os.path.exists(output_dir)):
- for filename in glob.glob(os.path.join(output_dir, '*.js')):
- os.unlink(filename)
- RunNixysa(idl_files, 'jsheader', output_dir, ['--no-return-docs'])
-
-
-def BuildO3DDocsFromJavaScript(js_files, ezt_output_dir, html_output_dir):
- RunJSDocToolkit(js_files, ezt_output_dir, html_output_dir,
- 'classo3d_1_1_', 'o3d', '', '', '')
-
-
-def BuildO3DClassHierarchy(html_output_dir):
- # TODO(gman): We need to make mutliple graphs. One for Params, one for
- # ParamMatrix4, one for RenderNode, one for everythng else.
- dot_path = MakePath(_third_party_dir, 'graphviz', 'files', 'bin',
- MakeCommandName('dot'))
- if os.path.exists(dot_path):
- Execute([
- dot_path,
- '-Tcmapx', '-o' + MakePath(html_output_dir, 'class_hierarchy.map'),
- '-Tpng', '-o' + MakePath(html_output_dir, 'class_hierarchy.png'),
- MakePath(html_output_dir, 'class_hierarchy.dot')])
-
-
-def BuildO3DJSDocs(js_files, ezt_output_dir, html_output_dir, exports_file):
- # The backslashes below on 'jsdocs/' and '../' must stay.
- RunJSDocToolkit(js_files, ezt_output_dir, html_output_dir, 'js_1_0_', 'o3djs',
- 'jsdocs/', '../', exports_file)
-
-
-def BuildO3DExternsFile(js_files_dir, extra_externs_file, externs_file):
- outfile = open(externs_file, 'w')
- filenames = (glob.glob(os.path.join(js_files_dir, '*.js')) +
- [extra_externs_file])
- for filename in filenames:
- print "-----", filename
- infile = open(filename, 'r')
- lines = infile.readlines()
- infile.close()
- filtered = []
- skipping = False
- # strip out @o3dparameter stuff
- for line in lines:
- if skipping:
- if line.startswith(' * @') or line.startswith(' */'):
- skipping = False
- if not skipping:
- if line.startswith(' * @o3dparameter'):
- skipping = True
- if not skipping:
- filtered.append(line)
- outfile.write(''.join(filtered))
- outfile.close()
-
-
-def BuildCompiledO3DJS(o3djs_files,
- externs_path,
- o3d_externs_js_path,
- compiled_o3djs_outpath):
- Execute([
- _java_exe,
- '-jar',
- MakePath('..', '..', 'o3d-internal', 'jscomp', 'JSCompiler_deploy.jar'),
- '--property_renaming', 'OFF',
- '--variable_renaming', 'LOCAL',
- '--jscomp_error=visibility',
- '--jscomp_error=accessControls',
- '--strict',
- '--externs=%s' % externs_path,
- ('--externs=%s' % o3d_externs_js_path),
- ('--js_output_file=%s' % compiled_o3djs_outpath)] +
- ['-js=%s' % (x, ) for x in o3djs_files]);
-
- # strip out goog.exportSymbol and move o3djs.require to end
- file = open(compiled_o3djs_outpath, 'r')
- contents = file.read()
- file.close()
- contents = re.sub(r'goog.exportSymbol\([^\)]*\);', '', contents)
- requires = set(re.findall(r'o3djs.require\([^\)]*\);', contents))
- contents = re.sub(r'o3djs.require\([^\)]*\);', '', contents)
- file = open(compiled_o3djs_outpath, 'w')
- file.write(_js_copyright)
- file.write(contents)
- file.write('\n')
- file.write('\n'.join(requires))
- file.close()
-
-
-def CopyStaticFiles(o3d_docs_ezt_outpath, o3d_docs_html_outpath):
- files = ['stylesheet.css',
- 'prettify.css',
- 'prettify.js',
- 'tabs.css',
- 'tab_l.gif',
- 'tab_r.gif',
- 'tab_b.gif']
- for file in files:
- shutil.copyfile(MakePath('jsdoc-toolkit-templates', 'static', file),
- MakePath(os.path.join(o3d_docs_ezt_outpath, file)))
- shutil.copyfile(MakePath('jsdoc-toolkit-templates', 'static', file),
- MakePath(os.path.join(o3d_docs_html_outpath, file)))
-
-
-def main(argv):
- """Builds the O3D API docs and externs and the o3djs docs."""
- global _java_exe
- _java_exe = argv[0]
- global _third_party_dir
- _third_party_dir = argv[1]
- global _o3d_third_party_dir
- _o3d_third_party_dir = os.path.normpath(
- os.path.join(os.path.dirname(__file__), '..', 'third_party'))
-
- # Fix up the python path of subprocesses by setting PYTHONPATH.
- pythonpath = os.pathsep.join([MakePath(_o3d_third_party_dir, 'gflags', 'python'),
- MakePath(_o3d_third_party_dir, 'ply')])
-
- orig_pythonpath = os.environ.get('PYTHONPATH')
- if orig_pythonpath:
- pythonpath = os.pathsep.join([pythonpath, orig_pythonpath])
-
- os.environ['PYTHONPATH'] = pythonpath
-
- js_list_filename = MakePath('..', 'samples', 'o3djs', 'js_list.manifest')
- idl_list_filename = MakePath('..', 'plugin', 'idl_list.manifest')
- js_list_basepath = os.path.dirname(js_list_filename)
- idl_list_basepath = os.path.dirname(idl_list_filename)
-
- global _output_dir
- _output_dir = argv[2]
- docs_outpath = os.path.join(_output_dir, 'documentation')
- docs_js_outpath = MakePath(docs_outpath, 'apijs')
- externs_js_outpath = MakePath(_output_dir, 'externs')
- o3d_docs_ezt_outpath = MakePath(docs_outpath, 'reference')
- o3d_docs_html_outpath = MakePath(docs_outpath, 'local_html')
- o3djs_docs_ezt_outpath = MakePath(docs_outpath, 'reference', 'jsdocs')
- o3djs_docs_html_outpath = MakePath(docs_outpath, 'local_html', 'jsdocs')
- o3d_externs_path = MakePath(_output_dir, 'o3d-externs.js')
- o3djs_exports_path = MakePath(_output_dir, 'o3d-exports.js')
- compiled_o3djs_outpath = MakePath(docs_outpath, 'base.js')
- externs_path = MakePath('externs', 'externs.js')
- o3d_extra_externs_path = MakePath('externs', 'o3d-extra-externs.js')
-
- js_list = eval(open(js_list_filename, "r").read())
- idl_list = eval(open(idl_list_filename, "r").read())
-
- idl_files = AppendBasePath(idl_list_basepath, idl_list)
- o3djs_files = AppendBasePath(js_list_basepath, js_list)
-
- # we need to put base.js first?
- o3djs_files = (
- filter(lambda x: x.endswith('base.js'), o3djs_files) +
- filter(lambda x: not x.endswith('base.js'), o3djs_files))
-
- docs_js_files = [os.path.join(
- docs_js_outpath,
- os.path.splitext(os.path.basename(f))[0] + '.js')
- for f in idl_list]
-
- try:
- DeleteOldDocs(MakePath(docs_outpath))
- BuildJavaScriptForDocsFromIDLs(idl_files, docs_js_outpath)
- BuildO3DDocsFromJavaScript([o3d_extra_externs_path] + docs_js_files,
- o3d_docs_ezt_outpath, o3d_docs_html_outpath)
- BuildO3DClassHierarchy(o3d_docs_html_outpath)
- BuildJavaScriptForExternsFromIDLs(idl_files, externs_js_outpath)
- BuildO3DExternsFile(externs_js_outpath,
- o3d_extra_externs_path,
- o3d_externs_path)
- BuildO3DJSDocs(o3djs_files + [o3d_externs_path], o3djs_docs_ezt_outpath,
- o3djs_docs_html_outpath, o3djs_exports_path)
- CopyStaticFiles(o3d_docs_ezt_outpath, o3d_docs_html_outpath)
- BuildCompiledO3DJS(o3djs_files + [o3djs_exports_path],
- externs_path,
- o3d_externs_path,
- compiled_o3djs_outpath)
- except Exception:
- if os.path.exists(compiled_o3djs_outpath):
- os.unlink(compiled_o3djs_outpath)
- raise
-
-
-if __name__ == '__main__':
- main(sys.argv[1:])
diff --git a/o3d/documentation/classtree.bat b/o3d/documentation/classtree.bat
deleted file mode 100644
index f15bbe8..0000000
--- a/o3d/documentation/classtree.bat
+++ /dev/null
@@ -1,33 +0,0 @@
-@echo OFF
-REM Copyright 2009, Google Inc.
-REM All rights reserved.
-REM
-REM Redistribution and use in source and binary forms, with or without
-REM modification, are permitted provided that the following conditions are
-REM met:
-REM
-REM * Redistributions of source code must retain the above copyright
-REM notice, this list of conditions and the following disclaimer.
-REM * Redistributions in binary form must reproduce the above
-REM copyright notice, this list of conditions and the following disclaimer
-REM in the documentation and/or other materials provided with the
-REM distribution.
-REM * Neither the name of Google Inc. nor the names of its
-REM contributors may be used to endorse or promote products derived from
-REM this software without specific prior written permission.
-REM
-REM THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-REM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-REM LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-REM A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-REM OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-REM SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-REM LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-REM DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-REM THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-REM (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-REM OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-set PYTHONDIR=%~dp0..\..\third_party\python_24
-call %PYTHONDIR%\setup_env.bat
-%PYTHONDIR%\python.exe %~dp0\classtree.py %*
diff --git a/o3d/documentation/classtree.py b/o3d/documentation/classtree.py
deleted file mode 100644
index 36308e5..0000000
--- a/o3d/documentation/classtree.py
+++ /dev/null
@@ -1,166 +0,0 @@
-#!/usr/bin/python2.4
-# 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.
-
-
-"""Creates unordered list of classes and packages."""
-
-
-import os.path
-import re
-import sys
-
-# Special regular expressions for search and replace
-list_item_string = ('<a class="el" href="([a-zA-Z0-9_]*.html)">'
- '([a-zA-Z0-9\.]*)</a></td>')
-LIST_ITEM = re.compile(list_item_string)
-
-
-def HyphenateWord(original_word, max_length, join_str='-'):
- """Breaks a word at max_length with hyphens.
-
- If the word is still too long (i.e., length > 2*max_length), the word will
- be split again. The word will be split at word breaks defined by a
- switch from lowercase to uppercase. The function will attempt to break at
- the closest switch before the max_length number of letters. If there is no
- upper case letter before the max_length, the original word will be returned.
- If max_length is 0 the original word will be returned.
-
- Args:
- original_word: the word to break.
- max_length: maximum length in chars for any piece of the word.
- join_str: characters to join the hyphenated parts with, defaults to '-'
- Returns:
- the hyphenated word.
- """
- word_list = []
- while len(original_word) > max_length:
- for i in range(max_length, -1, -1):
- if original_word[i].isupper():
- word_list += [original_word[:i]]
- original_word = original_word[i:]
- break
- if i == 0:
- # There was no uppercase letter found so we don't break and just
- # return the original word
- return original_word
-
- word_list += [original_word]
-
- return join_str.join(word_list)
-
-
-def CreateListItems(input_html_file, max_length, html_directory):
- """Creates html for a list of items based on the input html file.
-
- Args:
- input_html_file: file to extract list items from.
- max_length: maximum length for sidebar entry.
- html_directory: relative html path for linked files.
- Returns:
- item_list: a list representing the new html.
- """
- infile = open(input_html_file, 'r')
- lines_list = infile.readlines()
- infile.close()
-
- item_list = [' <ul>\n']
- format_string = (' <li><a href="%s%s">%s</a></li>\n')
- heading_format_string = (' <li><font class="sidebar-heading">%s'
- '</font></li>\n')
-
- previous_package = ''
- for line in lines_list:
- match = re.search(LIST_ITEM, line)
- if match:
- split_name = match.group(2).split('.')
- short_name = HyphenateWord(split_name[-1], max_length, '-<br>')
- package = '.'.join(split_name[:-1])
- if package != previous_package:
- item_list += [heading_format_string % package]
- previous_package = package
- item_list += [format_string % (html_directory, match.group(1),
- short_name)]
-
- item_list += [' </ul>\n']
-
- return item_list
-
-
-def CreateClassTreeHtmlFile(classtree_items, directory, html_directory):
- """Creates classtree.html file which has item lists based on class structure.
-
- The html file is only the lists and no surrounding html (body tag, etc.) as
- it is meant to be inserted into ezt html.
-
- Args:
- classtree_items: list of header-filename pairs to create list from.
- directory: location of the input html files to CreateListItems.
- html_directory: relative html path for linked files.
- """
- # Open file to write
- filename = os.path.join(directory, 'classtree.html')
- outfile = open(filename, 'w')
-
- originals_directory = os.path.join(directory, 'original_html')
-
- output_list = ['<ul>\n']
- for ct_item in classtree_items:
- output_list += [' <li><a href="%s' % html_directory]
- output_list += ['%s">%s</a>\n' % (ct_item[1], ct_item[0])]
- full_file_name = os.path.join(originals_directory, ct_item[1])
- output_list += CreateListItems(full_file_name, 16, html_directory)
- output_list += [' </li>\n']
- output_list += ['</ul>\n']
-
- outfile.writelines(output_list)
- outfile.close()
-
-
-def main():
- usage_string = 'This script generates an html list of the classes and '
- usage_string += 'packages. The output file is called classtree.html. If no '
- usage_string += 'directory is specified, . is used as a default\n'
- usage_string += 'Usage: classtree.py <directory>'
-
- print usage_string
-
- # Specify the default directory
- directory = '.'
- if len(sys.argv) > 1:
- directory = sys.argv[1]
- #create classtree items
- classtree_items = [('Packages', 'namespaces.html'),
- ('Classes', 'annotated.html')]
- # create the class tree
- CreateClassTreeHtmlFile(classtree_items, directory,
- '/apis/o3d/docs/reference/')
-
-if __name__ == '__main__':
- main()
diff --git a/o3d/documentation/documentation.gyp b/o3d/documentation/documentation.gyp
deleted file mode 100644
index 0c51cdf..0000000
--- a/o3d/documentation/documentation.gyp
+++ /dev/null
@@ -1,115 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- # We only want the documentation targets to be defined if the JS
- # Compiler is available, so we use python to find out if it's
- # available.
- 'jscomp_exists': '<!(python ../build/file_exists.py '
- '../../o3d-internal/jscomp/JSCompiler_deploy.jar)',
- 'conditions': [
- [ 'OS=="mac"', {
- # We need to point to Java 6 explicitly on Mac OS X
- 'java_exe%': '/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Commands/java'
- }, {
- # OS!="mac"
- 'java_exe%': 'java'
- }],
- ],
- },
- 'includes': [
- '../build/common.gypi',
- ],
- 'targets': [
- ],
- 'conditions': [
- [ '"<(jscomp_exists)"=="True"',
- {
- # Define these here so we don't run the scripts unless we need to.
- 'variables': {
- 'input_js_files': [
- '<!@(python get_docs_files.py --js)',
- ],
- 'input_idl_files': [
- '<!@(python get_docs_files.py --idl)',
- ],
- },
- 'targets': [
- {
- 'target_name': 'documentation',
- 'type': 'none',
- 'actions': [
- {
- 'action_name': 'build_docs',
- 'inputs': [
- '<@(input_js_files)',
- '<@(input_idl_files)',
- 'jsdoc-toolkit-templates/annotated.tmpl',
- 'jsdoc-toolkit-templates/class.tmpl',
- 'jsdoc-toolkit-templates/classtree.tmpl',
- 'jsdoc-toolkit-templates/dot.tmpl',
- 'jsdoc-toolkit-templates/filelist.tmpl',
- 'jsdoc-toolkit-templates/members.tmpl',
- 'jsdoc-toolkit-templates/namespaces.tmpl',
- 'jsdoc-toolkit-templates/publish.js',
- 'jsdoc-toolkit-templates/static/header.html',
- 'jsdoc-toolkit-templates/static/footer.html',
- 'jsdoc-toolkit-templates/static/stylesheet.css',
- 'jsdoc-toolkit-templates/static/tabs.css',
- 'jsdoc-toolkit-templates/static/tab_l.gif',
- 'jsdoc-toolkit-templates/static/tab_r.gif',
- 'jsdoc-toolkit-templates/static/tab_b.gif',
- 'externs/externs.js',
- 'externs/o3d-extra-externs.js',
- 'build_docs.py'
- ],
- 'outputs': [
- # There are really a whole lot more outputs than
- # this, but to determine what they are would require
- # having the entire docs script run every time, so
- # we just depend on the ultimate compiled base.js
- # file, which is rebuilt every time the docs build
- # happens.
- '<(PRODUCT_DIR)/docs/documentation/base.js',
- ],
- 'action': [
- 'python',
- 'build_docs.py',
- '<@(java_exe)',
- '../../third_party',
- '<(PRODUCT_DIR)/docs',
- ],
- },
- ],
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)/samples/o3djs',
- 'files': [
- '<(PRODUCT_DIR)/docs/documentation/base.js',
- ],
- },
- ],
- },
- ],
- },
- {
- 'targets': [
- {
- # Empty target if the js compiler doesn't exist.
- 'target_name': 'documentation',
- 'type': 'none',
- },
- ],
- },
- ],
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/documentation/externs/externs.js b/o3d/documentation/externs/externs.js
deleted file mode 100644
index 4e694b0..0000000
--- a/o3d/documentation/externs/externs.js
+++ /dev/null
@@ -1,1859 +0,0 @@
-// Copyright 2006 Google Inc.
-// All Rights Reserved.
-
-// Common external variables when compiling
-// DEPRECATED: please use the files in //javascript/externs/...
-
-// JavaScript objects
-/**
- * @constructor
- * @param {*} var_args
- * @return {!Array}
- */
-function Array(var_args) {}
-/**
- * @constructor
- * @param {*} opt_value
- * @return {boolean}
- */
-function Boolean(opt_value) {}
-/**
- * @constructor
- * @return {string}
- */
-function Date(opt_yr_num, opt_mo_num, opt_day_num, opt_hr_num, opt_min_num,
- opt_sec_num, opt_ms_num) {}
-/**
- * @constructor
- * @param {*} opt_message
- * @param {*} opt_file
- * @param {*} opt_line
- * @return {!Error}
- */
-function Error(opt_message, opt_file, opt_line) {}
-/**
- * @constructor
- * @param {*} var_args
- */
-function Function(var_args) {}
-/**
- * @constructor
- * @param {*} opt_value
- * @return {number}
- */
-function Number(opt_value) {}
-/**
- * @constructor
- * @param {*} opt_value
- */
-function Object(opt_value) {}
-/**
- * @constructor
- * @param {*} opt_pattern
- * @param {*} opt_flags
- * @return {!RegExp}
- */
-function RegExp(opt_pattern, opt_flags) {}
-/**
- * @constructor
- * @param {*} opt_str
- * @return {string}
- */
-function String(opt_str) {}
-
-// For IE, returns an object representing key-value pairs for all the global
-// variables prefixed with str, e.g. test*
-function RuntimeObject(opt_str) {}
-
-/** @constructor */
-function Arguments() {}
-
-// JavaScript functions
-// escape() and unescape() should only be used in browser where
-// encode/decodeURIComponent are not present, as the latter
-// handle fancy Unicode characters.
-function decodeURI(x) {}
-function decodeURIComponent(x) {}
-function encodeURI(x) {}
-function encodeURIComponent(x) {}
-function escape(x) {} // Caution: Read comments above regarding
-function unescape(x) {} // use of escape and unescape.
-function isFinite(x) {}
-function isNaN(x) {}
-function parseFloat(x) {}
-// base is required. If you really want to parse octal or hex based on the
-// leader, then pass undefind as the base.
-function parseInt(x, base) {}
-function eval(x) {}
-
-// JavaScript builtins
-var arguments;
-var Infinity;
-var Math;
-var NaN;
-var undefined;
-
-var builtins = {};
-builtins.arguments; // deprecated
-builtins.arity; // deprecated
-builtins.caller;
-builtins.constructor;
-builtins.length;
-builtins.name;
-builtins.prototype;
-
-// Window properties
-// Only common properties are here, others such as open() and setTimeout()
-// should be used with an explicit window object
-
-/**
- * @constructor
- * @extends {EventTarget}
- */
-function Window() {}
-
-var window;
-var top;
-var navigator;
-var document;
-var screen;
-var self;
-function alert(x) {}
-function confirm(x) {}
-function prompt(x, opt_value) {}
-
-// Magic functions for Firefox's LiveConnect.
-// We'll probably never use these in practice. But redefining them
-// will fire up the JVM, so we want to reserve the symbol names.
-var JavaArray;
-var JavaClass;
-var JavaMember;
-var JavaObject;
-var JavaPackage;
-var Packages;
-var java;
-var netscape;
-var sun;
-
-// Browser objects
-/** @constructor */ function ActiveXObject(name, opt_location) {}
-/** @constructor */ function CSSStyleDeclaration() {}
-/** @constructor */ function StyleSheet() {}
-/** @constructor */ function DOMParser() {}
-// Image can't be used as a function
-/**
- * @constructor
- * @extends {EventTarget}
- */
-function Image(opt_width, opt_height) {}
-/** @constructor */ function XMLHttpRequest() {}
-/** @constructor */ function XMLSerializer() {}
-/**
- * @noalias
- * @constructor
- */
-function XPathResult() {}
-/** @constructor */ function XSLTProcessor() {}
-/** @constructor */ function Range() {}
-/** @constructor */ function NodeFilter() {}
-/** @constructor */ function Option(opt_text, opt_value, opt_defaultSelected,
- opt_selected) {}
-var opera;
-
-// Browser types for type checking
-// see http://www.w3.org/TR/DOM-Level-2-HTML/ecma-script-binding.html
-
-// TODO(nicksantos): Rewrite all the DOM interfaces as interfaces, instead
-// of kluding them as an inheritance hierarchy.
-
-/**
- * @constructor
- * @extends {Node}
- */
-function Document() {}
-
-/**
- * @constructor
- * @extends {Node}
- */
-function DocumentFragment() {}
-
-/**
- * @constructor
- * @extends {Node}
- */
-function DocumentType() {}
-
-/**
- * @constructor
- * @extends {EventTarget}
- */
-function Node() {}
-
-/** @constructor */ function NodeList() {}
-
-/**
- * @constructor
- * @extends {Node}
- */
-function Element() {}
-
-/**
- * @constructor
- * @extends {Node}
- */
-function CharacterData() {}
-
-/**
- * @constructor
- * @extends {CharacterData}
- */
-function Text() {}
-
-/** @constructor */ function Event() {}
-/** @constructor */ function EventTarget() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLAnchorElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLAppletElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLAreaElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLBaseElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLBaseFontElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLBlockquoteElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLBodyElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLBRElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLButtonElement() {}
-
-/**
- * @constructor
- */
-function HTMLCollection() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLDirectoryElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLDivElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLDListElement() {}
-
-/**
- * @constructor
- * @extends {Document}
- */
-function HTMLDocument() {}
-
-/**
- * @constructor
- * @extends {Element}
- */
-function HTMLElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLFieldSetElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLFontElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLFormElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLFrameElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLFrameSetElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLHeadElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLHeadingElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLHRElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLHtmlElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLIFrameElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLImageElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLInputElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLIsIndexElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLLabelElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLLayerElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLLegendElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLLIElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLLinkElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLMapElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLMenuElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLMetaElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLModElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLObjectElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLOListElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLOptGroupElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLOptionElement() {}
-
-/**
- * @constructor
- */
-function HTMLOptionsCollection() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLParagraphElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLParamElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLPreElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLQuoteElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLScriptElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLSelectElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLSpanElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLStyleElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLTableCaptionElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLTableCellElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLTableColElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLTableElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLTableRowElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLTableSectionElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLTextAreaElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLTitleElement() {}
-
-/**
- * @constructor
- * @extends {HTMLElement}
- */
-function HTMLUListElement() {}
-
-// Gecko Selection interface
-/** @constructor */ function Selection() {}
-
-// IE Range interface
-/** @constructor */ function TextRange() {}
-
-// IE Control Range interface
-/** @constructor */ function controlRange() {}
-
-// Safari and Firefox canvas rendering context
-/** @constructor */ function CanvasRenderingContext2D() {}
-
-// Browser object methods and properties
-
-/**
- * The postMessage method (as defined by HTML5 spec and implemented in FF3).
- * @param {string} message
- * @param {string} targetOrigin
- */
-Window.prototype.postMessage = function(message, targetOrigin) {};
-
-/**
- * The postMessage method (as implemented in Opera).
- * @param {string} message
- */
-Document.prototype.postMessage = function(message) {};
-
-// Below is a generic list of methods and properties defined on various
-// browser/DOM objects. Ideally these would be defined on the appropriate
-// prototypes (as is done above). As long as the list below is around,
-// please keep it alphabetically sorted.
-var methods = {};
-methods.$1;
-methods.$2;
-methods.$3;
-methods.$4;
-methods.$5;
-methods.$6;
-methods.$7;
-methods.$8;
-methods.$9;
-methods.ANY_TYPE;
-methods.ANY_UNORDERED_NODE_TYPE;
-methods.ATTRIBUTE_NODE;
-methods.AT_TARGET;
-methods.BOOLEAN_TYPE;
-methods.BUBBLING_PHASE;
-methods.CAPTURING_PHASE;
-methods.CDATA_SECTION_NODE;
-methods.CHARSET_RULE;
-methods.COMMENT_NODE;
-methods.CSS_ATTR;
-methods.CSS_CM;
-methods.CSS_COUNTER;
-methods.CSS_CUSTOM;
-methods.CSS_DEG;
-methods.CSS_DIMENSION;
-methods.CSS_EMS;
-methods.CSS_EXS;
-methods.CSS_GRAD;
-methods.CSS_HZ;
-methods.CSS_IDENT;
-methods.CSS_IN;
-methods.CSS_INHERIT;
-methods.CSS_KHZ;
-methods.CSS_MM;
-methods.CSS_MS;
-methods.CSS_NUMBER;
-methods.CSS_PC;
-methods.CSS_PERCENTAGE;
-methods.CSS_PRIMITIVE_VALUE;
-methods.CSS_PT;
-methods.CSS_PX;
-methods.CSS_RAD;
-methods.CSS_RECT;
-methods.CSS_RGBCOLOR;
-methods.CSS_S;
-methods.CSS_STRING;
-methods.CSS_UNKNOWN;
-methods.CSS_URI;
-methods.CSS_VALUE_LIST;
-methods.DOCUMENT_FRAGMENT_NODE;
-methods.DOCUMENT_NODE;
-methods.DOCUMENT_TYPE_NODE;
-methods.DOMSTRING_SIZE_ERR;
-methods.E;
-methods.ELEMENT_NODE;
-methods.END_TO_END;
-methods.END_TO_START;
-methods.ENTITY_NODE;
-methods.ENTITY_REFERENCE_NODE;
-methods.FILTER_ACCEPT;
-methods.FILTER_REJECT;
-methods.FILTER_SKIP;
-methods.FIRST_ORDERED_NODE_TYPE;
-methods.FONT_FACE_RULE;
-methods.HIERARCHY_REQUEST_ERR;
-methods.HORIZONTAL_AXIS;
-methods.IMPORT_RULE;
-methods.INDEX_SIZE_ERR;
-methods.INFINITY;
-methods.INUSE_ATTRIBUTE_ERR;
-methods.INVALID_ACCESS_ERR;
-methods.INVALID_CHARACTER_ERR;
-methods.INVALID_MODIFICATION_ERR;
-methods.INVALID_STATE_ERR;
-methods.LOG10E;
-methods.LOG2E;
-methods.MAX_VALUE;
-methods.MEDIA_RULE;
-methods.MIN_VALUE;
-methods.MODIFICATION;
-methods.NAMESPACE_ERR;
-methods.NEGATIVE_INFINITY;
-methods.NOTATION_NODE;
-methods.NOT_FOUND_ERR;
-methods.NOT_SUPPORTED_ERR;
-methods.NO_DATA_ALLOWED_ERR;
-methods.NO_MODIFICATION_ALLOWED_ERR;
-methods.NUMBER_TYPE;
-methods.NaN;
-methods.ORDERED_NODE_ITERATOR_TYPE;
-methods.ORDERED_NODE_SNAPSHOT_TYPE;
-methods.PAGE_RULE;
-methods.PI;
-methods.POSITIVE_INFINITY;
-methods.PROCESSING_INSTRUCTION_NODE;
-methods.PercentLoaded; // flash?
-methods.REMOVAL;
-methods.SHOW_ALL;
-methods.SHOW_ATTRIBUTE;
-methods.SHOW_CDATA_SECTION;
-methods.SHOW_COMMENT;
-methods.SHOW_DOCUMENT;
-methods.SHOW_DOCUMENT_FRAGMENT;
-methods.SHOW_DOCUMENT_TYPE;
-methods.SHOW_ELEMENT;
-methods.SHOW_ENTITY;
-methods.SHOW_ENTITY_REFERENCE;
-methods.SHOW_NOTATION;
-methods.SHOW_PROCESSING_INSTRUCTION;
-methods.SHOW_TEXT;
-methods.START_TO_END;
-methods.START_TO_START;
-methods.STRING_TYPE;
-methods.STYLE_RULE;
-methods.SYNTAX_ERR;
-methods.TEXT_NODE;
-methods.TGotoLabel;
-methods.TPlay;
-methods.UNKNOWN_RULE;
-methods.UNORDERED_NODE_ITERATOR_TYPE;
-methods.UNORDERED_NODE_SNAPSHOT_TYPE;
-methods.UNSPECIFIED_EVENT_TYPE_ERR;
-methods.UTC;
-methods.VERTICAL_AXIS;
-methods.WRONG_DOCUMENT_ERR;
-methods.aLink;
-methods.abbr;
-methods.abort;
-methods.abs;
-methods.accept;
-methods.acceptCharset;
-methods.acceptNode;
-methods.accessKey;
-methods.acos;
-methods.action;
-methods.activeElement;
-methods.actualEncoding;
-methods.add;
-methods.addColorStop;
-methods.addElement;
-methods.addEventListener;
-methods.addRange;
-methods.addRule;
-methods.adoptNode;
-methods.alert;
-methods.align;
-methods.alinkColor;
-methods.all;
-methods.alt;
-methods.altGraphKey;
-methods.altKey;
-methods.anchorNode;
-methods.anchorOffset;
-methods.anchors;
-methods.angle;
-methods.appCodeName;
-methods.appName;
-methods.appVersion;
-methods.appendChild = function(newChild) {};
-methods.appendData;
-methods.appendMedium;
-methods.applets;
-methods.apply;
-methods.arc;
-methods.arcTo;
-methods.archive;
-methods.areas;
-methods.arguments;
-methods.asin;
-methods.assign;
-methods.async;
-methods.atan2;
-methods.atan;
-methods.atob;
-methods.attachEvent;
-methods.attrChange;
-methods.attrName;
-methods.attributes;
-methods.availHeight;
-methods.availWidth;
-methods.axis;
-methods.back;
-methods.baseNode;
-methods.baseOffset;
-methods.beginPath;
-methods.bezierCurveTo;
-methods.bgColor;
-methods.blendTrans;
-methods.blue;
-methods.blur;
-methods.body;
-methods.boundingWidth;
-methods.btoa;
-methods.bubbles;
-methods.button;
-methods.call;
-methods.callee;
-methods.caller;
-methods.cancelBubble;
-methods.cancelable;
-methods.canHaveChildren;
-methods.caption;
-methods.captureEvents;
-methods.ceil;
-methods.cellIndex;
-methods.cellPadding;
-methods.cellSpacing;
-methods.cells;
-methods.ch;
-methods.chOff;
-methods.charAt = function(index) {};
-methods.charCode;
-methods.charCodeAt;
-methods.characterSet;
-methods.charset;
-methods.checked;
-methods.childNodes;
-methods.children;
-methods.childNodes;
-methods.cite;
-methods.className;
-methods.clearData;
-methods.clearInterval = function(intervalRev) {};
-methods.clearParameters;
-methods.clearRect;
-methods.clearShadow;
-methods.clearTimeout = function(timeoutRef) {};
-methods.click;
-methods.clientHeight;
-methods.clientLeft;
-methods.clientTop;
-methods.clientWidth;
-methods.clientX;
-methods.clientY;
-methods.clipboardData;
-methods.cloneContents;
-methods.cloneNode = function(deepClone) {};
-methods.cloneRange;
-methods.close;
-methods.closed;
-methods.closePath;
-methods.closed;
-methods.code;
-methods.codeBase;
-methods.codeType;
-methods.colSpan;
-methods.collapse;
-methods.collapseToEnd;
-methods.collapseToStart;
-methods.collapsed;
-methods.color;
-methods.color2;
-methods.colorDepth;
-methods.cols;
-methods.commonAncestorContainer;
-methods.compact;
-methods.compareBoundaryPoints;
-methods.compareEndPoints;
-methods.compareDocumentPosition = function(el) {};
-methods.compatMode;
-methods.comparePoint;
-methods.complete;
-methods.componentFromPoint;
-methods.concat;
-methods.console;
-methods.constructor;
-methods.contains;
-methods.containsNode;
-methods.contentDocument;
-methods.contentEditable;
-methods.contentWindow;
-methods.cookie;
-methods.cookieEnabled;
-methods.coordorigin;
-methods.coords;
-methods.coordsize;
-methods.cos;
-methods.createAttribute;
-methods.createAttributeNS;
-methods.createCDATASection;
-methods.createCSSStyleSheet;
-methods.createCaption;
-methods.createComment;
-methods.createControlRange;
-methods.createContextualFragment;
-methods.createDocument;
-methods.createDocumentFragment;
-methods.createDocumentType;
-methods.createElement;
-methods.createElementNS;
-methods.createEntityReference;
-methods.createEvent;
-methods.createEventObject;
-methods.createHTMLDocument;
-methods.createLinearGradient;
-methods.createNode;
-methods.createNodeIterator;
-methods.createNSResolver;
-methods.createPattern;
-methods.createPopup;
-methods.createProcessingInstruction;
-methods.createProcessor = function() {}; // XSLT
-methods.createRadialGradient;
-methods.createRange;
-methods.createStyleSheet;
-methods.createTFoot;
-methods.createTHead;
-methods.createTextNode;
-methods.createTextRange = function() {};
-methods.createTreeWalker;
-methods.cssRules;
-methods.cssText;
-methods.cssValueType;
-methods.ctrlKey;
-methods.currentNode;
-methods.currentStyle;
-methods.currentTarget;
-methods.data;
-methods.dataTransfer;
-methods.dateTime;
-methods.declare;
-methods.defaultCharset;
-methods.defaultChecked;
-methods.defaultSelected;
-methods.defaultValue;
-methods.defaultView;
-methods.defer;
-methods.deleteCaption;
-methods.deleteCell;
-methods.deleteContents;
-methods.deleteData;
-methods.deleteMedium;
-methods.deleteRow;
-methods.deleteRule;
-methods.deleteTFoot;
-methods.deleteTHead;
-methods.description;
-methods.designMode;
-methods.detach;
-methods.detachEvent;
-methods.detail;
-methods.dir;
-methods.direction;
-methods.disabled;
-methods.dispatchEvent;
-methods.doctype;
-methods.document;
-methods.documentElement;
-methods.documentMode;
-methods.domain;
-methods.drawImage;
-methods.drawImageFromRect;
-methods.dropEffect;
-methods.dump;
-methods.duplicate = function() {};
-methods.effectAllowed;
-methods.elementFromPoint;
-methods.elements;
-methods.embeds;
-methods.empty;
-methods.enabledPlugin;
-methods.encoding;
-methods.enctype;
-methods.endContainer;
-methods.endOffset;
-methods.entities;
-methods.evaluate = function(
- xpathExpression, contextNode, namespaceResolver, resultType, result) {};
-methods.event;
-methods.eventPhase;
-methods.exec;
-methods.execCommand;
-methods.execScript;
-methods.expand;
-methods.expandEntityReferences;
-methods.explicitOriginalTarget;
-methods.exp = function(x) {};
-methods.expn;
-methods.extend;
-methods.extentNode;
-methods.extentOffset;
-methods.extractContents;
-methods.eval;
-methods.every;
-methods.face;
-methods.fgColor;
-methods.fileName;
-methods.filename;
-methods.fill = function() {};
-methods.filled;
-methods.fillcolor;
-methods.fillRect;
-methods.fillStyle;
-methods.filter;
-methods.filters;
-methods.findText; // IE text ranges
-methods.fireEvent;
-methods.firstChild;
-methods.floor;
-methods.focus;
-methods.focusNode;
-methods.focusOffset;
-methods.forEach;
-methods.form;
-methods.forms;
-methods.forward;
-methods.frame;
-methods.frames;
-methods.frameBorder;
-methods.frameElement;
-methods.fromCharCode = function(var_args) {};
-methods.fromElement;
-methods.getAllResponseHeaders;
-methods.getAttribute;
-methods.getAttributeNS;
-methods.getAttributeNode;
-methods.getAttributeNodeNS;
-methods.getBookmark;
-methods.getBoundingClientRect = function() {};
-methods.getBoxObjectFor = function(node) {};
-methods.getComputedStyle;
-methods.getContext;
-methods.getCounterValue;
-methods.getData;
-methods.getDate;
-methods.getDay;
-methods.getElementById;
-methods.getElementsByName;
-methods.getElementsByClassName;
-methods.getElementsByTagName;
-methods.getElementsByTagNameNS;
-methods.getFloatValue;
-methods.getFullYear;
-methods.getHours;
-methods.getImageData = function(sx, sy, sw, sh) {};
-methods.getMatchedCSSRules;
-methods.getMilliseconds;
-methods.getMinutes;
-methods.getMonth;
-methods.getNamedItem;
-methods.getNamedItemNS;
-methods.getOverrideStyle;
-methods.getParameter;
-methods.getPropertyCSSValue;
-methods.getPropertyPriority;
-methods.getPropertyShorthand;
-methods.getPropertyValue;
-methods.getRGBColorValue;
-methods.getRangeAt;
-methods.getRectValue;
-methods.getResponseHeader;
-methods.getSeconds;
-methods.getSelection;
-methods.getStringValue;
-methods.getTime;
-methods.getTimezoneOffset;
-methods.getUTCDate;
-methods.getUTCDay;
-methods.getUTCFullYear;
-methods.getUTCHours;
-methods.getUTCMilliseconds;
-methods.getUTCMinutes;
-methods.getUTCMonth;
-methods.getUTCSeconds;
-methods.GetVariable; // ActiveXObject
-methods.global;
-methods.globalAlpha;
-methods.globalCompositeOperation;
-methods.go;
-methods.green;
-methods.handleEvent;
-methods.hasAttribute;
-methods.hasAttributeNS;
-methods.hasAttributes = function() {};
-methods.hasChildNodes = function() {};
-methods.hasFeature;
-methods.hasFocus;
-methods.hasOwnProperty;
-methods.hash;
-methods.head;
-methods.headers;
-methods.history;
-methods.host;
-methods.hostname;
-methods.href;
-methods.hreflang;
-methods.hspace;
-methods.htmlFor;
-methods.htmlText;
-methods.httpEquiv;
-methods.id;
-methods.identifier;
-methods.ignoreCase;
-methods.images;
-methods.implementation;
-methods.imports;
-methods.importNode;
-methods.importStylesheet;
-methods.indeterminate;
-methods.index;
-methods.indexOf;
-methods.initEvent;
-methods.initKeyboardEvent;
-methods.initMouseEvent;
-methods.initMutationEvent;
-methods.initUIEvent;
-methods.innerHTML;
-methods.innerHeight;
-methods.innerText;
-methods.innerWidth;
-methods.inputEncoding;
-methods.input; // XSLT
-methods.inRange;
-methods.insertAdjacentText = function(where, text) {};
-methods.insertBefore = function(newNode, childNode) {};
-methods.insertCell;
-methods.insertData;
-methods.insertNode;
-methods.insertRow;
-methods.insertRule;
-methods.internalSubset;
-methods.intersectsNode;
-methods.invalidIteratorState;
-methods.isCollapsed;
-methods.isContentEditable;
-methods.isEqual = function(textRange) {};
-methods.isPointInPath = function(x, y) {};
-methods.isMap;
-methods.isOpen;
-methods.isPointInPath = function(x, y) {};
-methods.isPropertyImplicit;
-methods.isPrototypeOf;
-methods.isSupported = function(feature, version) {};
-methods.item;
-methods.iterateNext = function() {};
-methods.javaEnabled;
-methods.join;
-methods.keyCode;
-methods.keyIdentifier;
-methods.keyLocation;
-methods.KhtmlOpacity;
-methods.label;
-methods.lang;
-methods.language;
-methods.lastChild;
-methods.lastIndex;
-methods.lastIndexOf;
-methods.lastMatch;
-methods.lastModified;
-methods.lastParen;
-methods.layerX;
-methods.layerY;
-methods.leftContext;
-methods.length;
-methods.line;
-methods.lineCap;
-methods.lineJoin;
-methods.lineNumber;
-methods.lineTo;
-methods.lineWidth;
-methods.linkColor;
-methods.links;
-methods.localName;
-methods.load; // XSLT
-methods.loadXML;
-methods.localeCompare;
-methods.location;
-methods.log;
-methods.longDesc;
-methods.map;
-methods.marginHeight;
-methods.marginWidth;
-methods.match;
-methods.max;
-methods.maxLength;
-methods.media;
-methods.mediaText;
-methods.mergeAttributes;
-methods.message;
-methods.metaKey;
-methods.method;
-methods.mimeTypes;
-methods.min;
-methods.miterLimit;
-methods.move = function(unit, opt_count) {};
-methods.moveBy;
-methods.moveEnd;
-methods.moveStart;
-methods.moveTo;
-methods.moveToElementText = function(node) {};
-methods.moveToPoint;
-methods.multiline;
-methods.multiple;
-methods.name;
-methods.namedItem;
-methods.namespaces;
-methods.namespaceURI;
-methods.naturalHeight;
-methods.naturalWidth;
-methods.navigationMode;
-methods.newValue;
-methods.nextNode;
-methods.nextSibling;
-methods.nodeType;
-methods.noHref;
-methods.noResize;
-methods.noShade;
-methods.now; // Date.now()
-methods.noWrap;
-methods.nodeName;
-methods.nodeType;
-methods.nodeValue;
-methods.normalize = function() {};
-methods.notationName;
-methods.notations;
-methods.object;
-methods.offsetHeight;
-methods.offsetLeft;
-methods.offsetParent;
-methods.offsetTop;
-methods.offsetWidth;
-methods.offsetX;
-methods.offsetY;
-methods.onabort;
-methods.onbeforeunload;
-methods.onblur;
-methods.onchange;
-methods.onclick;
-methods.oncontextmenu;
-methods.ondblclick;
-methods.ondrag;
-methods.ondragend;
-methods.ondragenter; // IE
-methods.ondragleave; // IE
-methods.ondragover; // IE
-methods.ondragstart; // IE
-methods.ondrop; // IE
-methods.onerror;
-methods.onfocus;
-methods.onkeydown;
-methods.onkeypress;
-methods.onkeyup;
-methods.onLine;
-methods.onload;
-methods.onmousedown;
-methods.onmousemove;
-methods.onmouseout;
-methods.onmouseover;
-methods.onmouseup;
-methods.onmousewheel;
-methods.onpropertychange;
-methods.onreadystatechange;
-methods.onresize;
-methods.onscroll;
-methods.onselect;
-methods.onselectend;
-methods.onselectstart;
-methods.onsubmit;
-methods.onunload;
-methods.opacity;
-methods.open;
-methods.openDialog;
-methods.opener;
-methods.opera;
-methods.options;
-methods.originalTarget;
-methods.outerHTML;
-methods.outerHeight;
-methods.outerText;
-methods.outerWidth;
-methods.output; // XSLT
-methods.overflowX;
-methods.overflowY;
-methods.overrideMimeType;
-methods.ownerDocument;
-methods.ownerElement;
-methods.ownerNode;
-methods.ownerRule;
-methods.owningElement;
-methods.pageX;
-methods.pageXOffset;
-methods.pageY;
-methods.pageYOffset;
-methods.parentElement = function() {};
-methods.parent;
-methods.parentNode;
-methods.parentRule;
-methods.parentStyleSheet;
-methods.parentWindow;
-methods.parse;
-methods.parseError;
-methods.parseFromString;
-methods.parseJSON;
-methods.pasteHTML;
-methods.pathname;
-methods.peek;
-methods.pixelBottom;
-methods.pixelDepth;
-methods.pixelHeight;
-methods.pixelLeft;
-methods.pixelRight;
-methods.pixelTop;
-methods.pixelWidth;
-methods.platform;
-methods.play;
-methods.plugins;
-methods.pointerBeforeReferenceNode;
-methods.pop;
-methods.port;
-methods.pow;
-methods.preferredStylesheetSet;
-methods.prefix;
-methods.prevValue;
-methods.preventDefault;
-methods.previousNode;
-methods.previousSibling;
-methods.primitiveType;
-methods.print;
-methods.product;
-methods.productSub;
-methods.profile;
-methods.prompt;
-methods.propertyIsEnumerable;
-methods.propertyName;
-methods.protocol;
-methods.publicId;
-methods.push;
-methods.putImageData = function(image, dx, dy) {};
-methods.quadraticCurveTo;
-methods.queryCommandEnabled;
-methods.queryCommandIndeterm;
-methods.queryCommandState;
-methods.queryCommandSupported;
-methods.queryCommandValue;
-methods.querySelector = function(selector) {};
-methods.querySelectorAll = function(selector) {};
-methods.quote = function() {};
-methods.rangeCount;
-methods.random;
-methods.rangeCount;
-methods.readOnly;
-methods.readyState;
-methods.rect;
-methods.red;
-methods.reduce = function(callback, opt_initialValue) {};
-methods.reduceRight = function(callback, opt_initialValue) {};
-methods.referenceNode;
-methods.referrer;
-methods.refresh;
-methods.rel;
-methods.relatedNode;
-methods.relatedTarget;
-methods.releaseCapture;
-methods.releaseEvents;
-methods.reload;
-methods.remove;
-methods.removeAllRanges;
-methods.removeAttribute;
-methods.removeAttributeNS;
-methods.removeAttributeNode;
-methods.removeChild = function(oldChild) {};
-methods.removeEventListener;
-methods.removeExpression = function(propertyName) {};
-methods.removeNamedItem;
-methods.removeNamedItemNS;
-methods.removeNode;
-methods.removeParameter;
-methods.removeProperty;
-methods.repeat;
-methods.replace;
-methods.replaceChild = function(newNode, childNode) {};
-methods.replaceData;
-methods.replaceNode = function(newNode) {};
-methods.reset;
-methods.resizeBy = function(x, y) {};
-methods.resizeTo = function(w, h) {};
-methods.resolveExternals; // XSLT
-methods.responseText;
-methods.responseXML;
-methods.restore;
-methods.result;
-methods.returnValue;
-methods.rev;
-methods.reverse;
-methods.rightContext;
-methods.rotate;
-methods.rotation;
-methods.round;
-methods.rowIndex;
-methods.rowSpan;
-methods.rows;
-methods.rules;
-methods.runtimeStyle;
-methods.save;
-methods.scale;
-methods.scheme;
-methods.scope;
-methods.screen;
-methods.screenLeft;
-methods.screenTop;
-methods.screenX;
-methods.screenY;
-methods.scripts;
-methods.scroll = function(x, y) {};
-methods.scrollBy;
-methods.scrollByLines;
-methods.scrollByPages;
-methods.scrollHeight;
-methods.scrollIntoView;
-methods.scrollLeft;
-methods.scrollTo = function(x, y) {};
-methods.scrollTop;
-methods.scrollWidth;
-methods.scrollX;
-methods.scrollY;
-methods.scrolling;
-methods.search;
-methods.sectionRowIndex;
-methods.select;
-methods.selectNode;
-methods.selectNodeContents;
-methods.selectNodes = function(patternString) {};
-methods.selectSingleNode = function(patternString) {};
-methods.selected;
-methods.selectedIndex;
-methods.selectedStylesheetSet;
-methods.selection;
-methods.selectionEnd;
-methods.selectionStart;
-methods.selectorText;
-methods.send;
-methods.separator;
-methods.serializeToString;
-methods.setActive = function() {};
-methods.setAlpha;
-methods.setAttribute;
-methods.setAttributeNS;
-methods.setAttributeNode;
-methods.setAttributeNodeNS;
-methods.setBaseAndExtent;
-methods.setCapture;
-methods.setCompositeOperation;
-methods.setData;
-methods.setDate;
-methods.setDragImage;
-methods.setEnd;
-methods.setEndAfter;
-methods.setEndBefore;
-methods.setEndPoint = function(type, range) {};
-methods.setExpression = function(propertyName, expression) {};
-methods.setFillColor;
-methods.setFloatValue;
-methods.setFullYear;
-methods.setHours;
-methods.setInterval = function(fn, interval) {};
-methods.setLineCap;
-methods.setLineJoin;
-methods.setLineWidth;
-methods.setMilliseconds;
-methods.setMinutes;
-methods.setMiterLimit;
-methods.setMonth;
-methods.setNamedItem;
-methods.setNamedItemNS;
-methods.setParameter;
-methods.setPosition;
-methods.setProperty;
-methods.setRequestHeader;
-methods.setSUTCSeconds;
-methods.setSeconds;
-methods.setSelectionRange;
-methods.setShadow;
-methods.setStart;
-methods.setStartAfter;
-methods.setStartBefore;
-methods.setStringValue;
-methods.setStrokeColor;
-methods.setTime;
-methods.setTimeout = function(fn, time) {};
-methods.setTransform = function(m11, m12, m21, m22, dx, dy) {};
-methods.setUTCDate;
-methods.setUTCFullYear;
-methods.setUTCHours;
-methods.setUTCMilliseconds;
-methods.setUTCMinutes;
-methods.setUTCMonth;
-methods.setUTCSeconds;
-methods.shadowBlur;
-methods.shadowColor;
-methods.shadowOffsetX;
-methods.shadowOffsetY;
-methods.shape;
-methods.sheet;
-methods.shift;
-methods.shiftKey;
-methods.showModalDialog = function(url, opt_arguments, opt_features) {};
-methods.sin;
-methods.singleNodeValue;
-methods.slice;
-methods.snapshotItem = function(index) {};
-methods.snapshotLength;
-methods.some;
-methods.sort;
-methods.source;
-methods.sourceIndex;
-methods.sourceURL;
-methods.span;
-methods.specified;
-methods.splice;
-methods.split;
-methods.splitText;
-methods.sqrt;
-methods.src;
-methods.srcElement;
-methods.stack;
-methods.standby;
-methods.start;
-methods.startContainer;
-methods.startOffset;
-methods.status;
-methods.statusText;
-methods.stop;
-methods.stopPropagation;
-methods.stroke;
-methods.strokecolor;
-methods.stroked;
-methods.strokeRect;
-methods.strokeStyle;
-methods.strokeweight;
-methods.style;
-methods.styleSheet;
-methods.stylesheet; // XSLT
-methods.styleSheets;
-methods.submit;
-methods.substr = function(start, opt_length) {};
-methods.substring = function(start, opt_end) {};
-methods.substringData;
-methods.suffixes;
-methods.summary;
-methods.surroundContents;
-methods.systemId;
-methods.tBodies;
-methods.tFoot;
-methods.tHead;
-methods.tabIndex;
-methods.tagName;
-methods.tags;
-methods.tan;
-methods.target;
-methods.test;
-methods.text;
-methods.textContent;
-methods.timeStamp;
-methods.title;
-methods.toDateString;
-methods.toElement;
-methods.toExponential;
-methods.toFixed;
-methods.toJSONString;
-methods.toLocaleDateString;
-methods.toLocaleLowerCase;
-methods.toLocaleString;
-methods.toLocaleTimeString;
-methods.toLocaleUpperCase;
-methods.toLowerCase;
-methods.toPrecision;
-methods.toSource;
-methods.toString;
-methods.toSource;
-methods.toTimeString;
-methods.toUTCString;
-methods.toUpperCase;
-methods.transform = function(m11, m12, m21, m22, dx, dy) {};
-methods.setTransform = function(m11, m12, m21, m22, dx, dy) {};
-methods.transformToDocument;
-methods.transformToFragment;
-methods.translate;
-methods.type;
-methods.types;
-methods.uneval;
-methods.unshift;
-methods.unselectable;
-methods.useMap;
-methods.userAgent;
-methods.vAlign;
-methods.value;
-methods.valueOf;
-methods.valueType;
-methods.vendor;
-methods.version;
-methods.view;
-methods.visible;
-methods.vlinkColor;
-methods.vspace;
-methods.watch;
-methods.whatToShow;
-methods.wheelDelta;
-methods.wheelDeltaX;
-methods.wheelDeltaY;
-methods.which;
-methods.write;
-methods.writeln;
-methods.x;
-methods.xml;
-methods.y;
-
-// CSS style properties
-methods.azimuth;
-methods.background;
-methods.backgroundAttachment;
-methods.backgroundColor;
-methods.backgroundImage;
-methods.backgroundPosition;
-methods.backgroundPositionX;
-methods.backgroundPositionY;
-methods.backgroundRepeat;
-methods.border;
-methods.borderCollapse;
-methods.borderColor;
-methods.borderSpacing;
-methods.borderStyle;
-methods.borderTop;
-methods.borderRight;
-methods.borderBottom;
-methods.borderLeft;
-methods.borderTopColor;
-methods.borderRightColor;
-methods.borderBottomColor;
-methods.borderLeftColor;
-methods.borderTopStyle;
-methods.borderRightStyle;
-methods.borderBottomStyle;
-methods.borderLeftStyle;
-methods.borderTopWidth;
-methods.borderRightWidth;
-methods.borderBottomWidth;
-methods.borderLeftWidth;
-methods.borderWidth;
-methods.bottom;
-methods.captionSide;
-methods.clear;
-methods.clip;
-methods.color;
-methods.content;
-methods.counterIncrement;
-methods.counterReset;
-methods.cssFloat;
-methods.cue;
-methods.cueAfter;
-methods.cueBefore;
-methods.cursor;
-methods.direction;
-methods.display;
-methods.elevation;
-methods.emptyCells;
-methods.font;
-methods.fontFamily;
-methods.fontSize;
-methods.fontSizeAdjust;
-methods.fontStretch;
-methods.fontStyle;
-methods.fontVariant;
-methods.fontWeight;
-methods.height;
-methods.hideFocus;
-methods.left;
-methods.letterSpacing;
-methods.lineHeight;
-methods.listStyle;
-methods.listStyleImage;
-methods.listStylePosition;
-methods.listStyleType;
-methods.margin;
-methods.marginBottom;
-methods.marginLeft;
-methods.marginRight;
-methods.marginTop;
-methods.markerOffset;
-methods.marks;
-methods.maxHeight;
-methods.maxWidth;
-methods.minHeight;
-methods.minWidth;
-methods.orphans;
-methods.outline;
-methods.outlineColor;
-methods.outlineStyle;
-methods.outlineWidth;
-methods.overflow;
-methods.padding;
-methods.paddingTop;
-methods.paddingRight;
-methods.paddingBottom;
-methods.paddingLeft;
-methods.page;
-methods.pageBreakAfter;
-methods.pageBreakBefore;
-methods.pageBreakInside;
-methods.pause;
-methods.pauseAfter;
-methods.pauseBefore;
-methods.pitch;
-methods.pitchRange;
-methods.position;
-methods.quotes;
-methods.richness;
-methods.right;
-methods.size;
-methods.speak;
-methods.speakHeader;
-methods.speakNumeral;
-methods.speakPunctuation;
-methods.speechRate;
-methods.stress;
-methods.styleFloat;
-methods.tableLayout;
-methods.textAlign;
-methods.textDecoration;
-methods.textIndent;
-methods.textShadow;
-methods.textTransform;
-methods.top;
-methods.unicodeBidi;
-methods.verticalAlign;
-methods.visibility;
-methods.voiceFamily;
-methods.volume;
-methods.whiteSpace;
-methods.widows;
-methods.width;
-methods.wordSpacing;
-methods.wordWrap;
-methods.zIndex;
-methods.zoom;
-
-// Gecko-only CSS style names. Copied from:
-// http://lxr.mozilla.org/mozilla1.8.0/source/dom/public/idl/css/nsIDOMCSS2Properties.idl
-methods.MozAppearance;
-methods.MozBackgroundClip;
-methods.MozBackgroundInlinePolicy;
-methods.MozBackgroundOrigin;
-methods.MozBinding;
-methods.MozBorderBottomColors;
-methods.MozBorderLeftColors;
-methods.MozBorderRightColors;
-methods.MozBorderTopColors;
-methods.MozBorderRadius;
-methods.MozBorderRadiusTopleft;
-methods.MozBorderRadiusTopright;
-methods.MozBorderRadiusBottomleft;
-methods.MozBorderRadiusBottomright;
-methods.MozBoxAlign;
-methods.MozBoxDirection;
-methods.MozBoxFlex;
-methods.MozBoxOrient;
-methods.MozBoxOrdinalGroup;
-methods.MozBoxPack;
-methods.MozBoxSizing;
-methods.MozColumnCount;
-methods.MozColumnWidth;
-methods.MozColumnGap;
-methods.MozFloatEdge;
-methods.MozForceBrokenImageIcon;
-methods.MozImageRegion;
-methods.MozMarginEnd;
-methods.MozMarginStart;
-methods.MozOpacity;
-methods.MozOutline;
-methods.MozOutlineColor;
-methods.MozOutlineRadius;
-methods.MozOutlineRadiusTopleft;
-methods.MozOutlineRadiusTopright;
-methods.MozOutlineRadiusBottomleft;
-methods.MozOutlineRadiusBottomright;
-methods.MozOutlineStyle;
-methods.MozOutlineWidth;
-methods.MozOutlineOffset;
-methods.MozPaddingEnd;
-methods.MozPaddingStart;
-methods.MozUserFocus;
-methods.MozUserInput;
-methods.MozUserModify;
-methods.MozUserSelect;
-
-// Webkit-only CSS style names. Copied from:
-// https://svn.corp.google.com/v/chrome/trunk/third_party/WebKit/WebCore/css/CSSPropertyNames.in?view=markup
-methods.WebkitAppearance;
-methods.WebkitBackgroundClip;
-methods.WebkitBackgroundComposite;
-methods.WebkitBackgroundOrigin;
-methods.WebkitBackgroundSize;
-methods.WebkitBinding;
-methods.WebkitBorderBottomLeftRadius;
-methods.WebkitBorderBottomRightRadius;
-methods.WebkitBorderFit;
-methods.WebkitBorderHorizontalSpacing;
-methods.WebkitBorderImage;
-methods.WebkitBorderRadius;
-methods.WebkitBorderTopLeftRadius;
-methods.WebkitBorderTopRightRadius;
-methods.WebkitBorderVerticalSpacing;
-methods.WebkitBoxAlign;
-methods.WebkitBoxDirection;
-methods.WebkitBoxFlex;
-methods.WebkitBoxFlexGroup;
-methods.WebkitBoxLines;
-methods.WebkitBoxOrdinalGroup;
-methods.WebkitBoxOrient;
-methods.WebkitBoxPack;
-methods.WebkitBoxShadow;
-methods.WebkitBoxSizing;
-methods.WebkitColumnBreakAfter;
-methods.WebkitColumnBreakBefore;
-methods.WebkitColumnBreakInside;
-methods.WebkitColumnCount;
-methods.WebkitColumnGap;
-methods.WebkitColumnRule;
-methods.WebkitColumnRuleColor;
-methods.WebkitColumnRuleStyle;
-methods.WebkitColumnRuleWidth;
-methods.WebkitColumnWidth;
-methods.WebkitColumns;
-methods.WebkitDashboardRegion;
-methods.WebkitFontSizeDelta;
-methods.WebkitHighlight;
-methods.WebkitLineBreak;
-methods.WebkitLineClamp;
-methods.WebkitMarginBottomCollapse;
-methods.WebkitMarginCollapse;
-methods.WebkitMarginStart;
-methods.WebkitMarginTopCollapse;
-methods.WebkitMarquee;
-methods.WebkitMarqueeDirection;
-methods.WebkitMarqueeIncrement;
-methods.WebkitMarqueeRepetition;
-methods.WebkitMarqueeSpeed;
-methods.WebkitMarqueeStyle;
-methods.WebkitMatchNearestMailBlockquoteColor;
-methods.WebkitNbspMode;
-methods.WebkitPaddingStart;
-methods.WebkitRtlOrdering;
-methods.WebkitTextDecorationsInEffect;
-methods.WebkitTextFillColor;
-methods.WebkitTextSecurity;
-methods.WebkitTextSizeAdjust;
-methods.WebkitTextStroke;
-methods.WebkitTextStrokeColor;
-methods.WebkitTextStrokeWidth;
-methods.WebkitTransform;
-methods.WebkitTransformOrigin;
-methods.WebkitTransformOriginX;
-methods.WebkitTransformOriginY;
-methods.WebkitTransition;
-methods.WebkitTransitionDuration;
-methods.WebkitTransitionProperty;
-methods.WebkitTransitionRepeatCount;
-methods.WebkitTransitionTimingFunction;
-methods.WebkitUserDrag;
-methods.WebkitUserModify;
-methods.WebkitUserSelect;
diff --git a/o3d/documentation/externs/o3d-extra-externs.js b/o3d/documentation/externs/o3d-extra-externs.js
deleted file mode 100644
index 82a62e0..0000000
--- a/o3d/documentation/externs/o3d-extra-externs.js
+++ /dev/null
@@ -1,55 +0,0 @@
-
-/**
- * Special global variable for V8 instances.
- */
-var plugin;
-
-/**
- * The main namespace for the o3d plugin.
- * @constructor
- */
-var o3d;
-
-/**
- * @type {!Object}
- */
-var Exception = goog.typedef;
-
-/**
- * A namespace for the Cursor.
- * @namespace
- */
-o3d.Cursor = o3d.Cursor || { };
-
-/**
- * A namespace for the VectorMath.
- * @namespace
- */
-var Vectormath;
-
-/**
- * A namespace for the VectorMath.Aos
- * @namespace
- */
-Vectormath.Aos = Vectormath.Aos || { };
-
-/**
- * A stand-in class definition for Float32Array.
- * @param {number} size The size.
- * @constructor
- */
-var Float32Array = function(size) { };
-
-/**
- * A 4x4 Matrix of floats
- * @type {!Array.<!Array.<number>>}
- */
-o3d.Matrix4 = goog.typedef;
-
-/**
- * RangeError.
- * why is this sometimes needed and sometimes not?
- * @exception
- */
-var RangeError;
-
diff --git a/o3d/documentation/ezt_formatter.bat b/o3d/documentation/ezt_formatter.bat
deleted file mode 100644
index bd0b99e..0000000
--- a/o3d/documentation/ezt_formatter.bat
+++ /dev/null
@@ -1,33 +0,0 @@
-@echo OFF
-REM Copyright 2009, Google Inc.
-REM All rights reserved.
-REM
-REM Redistribution and use in source and binary forms, with or without
-REM modification, are permitted provided that the following conditions are
-REM met:
-REM
-REM * Redistributions of source code must retain the above copyright
-REM notice, this list of conditions and the following disclaimer.
-REM * Redistributions in binary form must reproduce the above
-REM copyright notice, this list of conditions and the following disclaimer
-REM in the documentation and/or other materials provided with the
-REM distribution.
-REM * Neither the name of Google Inc. nor the names of its
-REM contributors may be used to endorse or promote products derived from
-REM this software without specific prior written permission.
-REM
-REM THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-REM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-REM LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-REM A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-REM OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-REM SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-REM LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-REM DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-REM THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-REM (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-REM OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-set PYTHONDIR=%~dp0..\..\third_party\python_24
-call %PYTHONDIR%\setup_env.bat
-%PYTHONDIR%\python.exe %~dp0\ezt_formatter.py %*
diff --git a/o3d/documentation/ezt_formatter.py b/o3d/documentation/ezt_formatter.py
deleted file mode 100644
index feccdf4..0000000
--- a/o3d/documentation/ezt_formatter.py
+++ /dev/null
@@ -1,351 +0,0 @@
-#!/usr/bin/python2.4
-# 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.
-
-
-"""HTML formatter for ezt docs."""
-
-
-import os
-import os.path
-import re
-import shutil
-import sys
-
-
-class DoxygenJavascriptifier(object):
- """Convert C++ documentation into Javascript style.
-
- Documentation may be automatically generated using doxygen. However,
- doxygen only outputs C++ formatted documentation, that is it uses C++
- conventions for specifying many items even if the java option is selected in
- the configuration file.
-
- In order to make the documentation look like Javascript documentation,
- additional corrections must be made which this class takes care of.
-
- Since doxygen allows you to name functions and class whatever you wish, this
- class assumes that you have already chosen to name them with standard
- Javascript conventions (such as camel-case) and therefore does not try to
- correct that.
-
- Though many of the replacements are simply eliminated, they are left as
- individual items in the dictionary for clarity.
-
- Attributes:
- cpp_to_js: a list of c++ to javascript replacement tuples
- static_function_regex: regular expression describing a static function
- declaration
- """
-
- global_function_tag = '[<a class="doxygen-global">global function</a>]'
- static_function2_regex = re.compile(r'<li>(.*)static(.*)$')
- cpp_to_js = [(re.compile(r'::'), '.'),
- (re.compile(r'\[pure\]'), ''),
- (re.compile(r'\[pure virtual\]'), ''),
- (re.compile(r'\[virtual\]'), ''),
- (re.compile(r'\[protected\]'), ''),
- (re.compile(r'\[static\]'), global_function_tag),
- (re.compile(r'\[explicit\]'), ''),
- (re.compile(r'\bvirtual\b'), ''),
- (re.compile(r'\bpure\b'), ''),
- (re.compile(r'\bprotected\b'), ''),
- (re.compile(r'\bvoid\b'), ''),
- (re.compile(r'\bunsigned\b'), ''),
- (re.compile(r'\bstatic\b'), ''),
- (re.compile(r'\bStatic\b'), 'Global'),
- (re.compile(r'\bint\b'), 'Number'),
- (re.compile(r'\bfloat\b'), 'Number'),
- (re.compile(r'\bNULL\b'), 'null'),
- (re.compile(r'=0'), ''),
- # Replace "std.vector<class_name>" with "Array" since vectors
- # don't exist in Javascript. There is no type for Array in
- # Javascript.
- (re.compile(r'std.vector&lt;[\w\s<>"/.=+]*&gt;'), 'Array'),
- # Remove mention of Vectormath.Aos namespace since it is
- # invisible to Javascript.
- (re.compile(r'Vectormath.Aos.Vector3'), 'Vector3'),
- (re.compile(r'Vectormath.Aos.Vector4'), 'Vector4'),
- (re.compile(r'Vectormath.Aos.Point3'), 'Point3'),
- (re.compile(r'Vectormath.Aos.Matrix4'), 'Matrix4'),
- (re.compile(r'Vectormath.Aos.Quat'), 'Quat'),
- (re.compile(r'\bconst\b'), '')]
-
- def Javascriptify(self, lines_list):
- """Replaces C++-style items with more Javascript-like ones.
-
- This includes removing many identifiers such as pure, virtual, protected,
- static and explicit which are not used in Javascript and replacing
- notation such as '::' with its corresponding Javascript equivalent,
- '.' in this case.
-
- Args:
- lines_list: the list of lines to correct.
- Returns:
- the corrected lines in javascript format.
- """
- for index, line in enumerate(lines_list):
- line = self.LabelStaticAsGlobal(line)
- for cpp_expression, js_expression in self.cpp_to_js:
- line = re.sub(cpp_expression, js_expression, line)
- lines_list[index] = line
- return lines_list
-
- def LabelStaticAsGlobal(self, line):
- """If a function is static, we indicate it is a global function.
-
- Since static does not make sense for Javascript we refer to these
- functions as global. To designate global function, we place a
- [global function] tag after the function declaration. Doxygen by
- default leaves the static descriptor in front of the function so
- this function looks for the descriptor, removes it and puts the
- tag at the end.
-
- Args:
- line: the line to correct.
- Returns:
- the corrected line.
- """
- match = re.search(self.static_function2_regex, line)
- if match is not None:
- line = '<li>%s%s %s\n' % (match.group(1), match.group(2),
- self.global_function_tag)
- return line
-
-
-class EZTFormatter(object):
- """This class converts doxygen output into ezt ready files.
-
- When doxygen outputs files, it contains its own formatting such as adding
- navigation tabs to the top of each page. This class contains several
- functions for stripping down doxygen output and formatting doxygen output
- to be easily parsed by ezt.
-
- This class assumes that any header/footer boilerplate code (that is code
- added by the user rather than doxygen at the start or end of a file) is
- indicated by special indicator strings surrounding it. Namely at the
- start of boilerplate code: 'BOILERPLATE - DO NOT EDIT THIS BLOCK' and
- at the end of boilerplate code: 'END OF BOILERPLATE'.
-
- Attributes:
- content_start_regex: regular expression for end of boilerplate code
- content_end_regex: regular expression for start of boilerplate code
- div_regex: regular expression of html div
- div_end_regex: regular expression of closing html div
- navigation_regex: regular expression indicating doxygen navigation tabs
- html_suffix_regex: regular expression html file suffix
- current_directory: location of files being worked on
- originals_directory: directory to store copies of original html files
- modifiers: list of functions to apply to files passed in
- """
- content_start_regex = re.compile('END OF BOILERPLATE')
- content_end_regex = re.compile('BOILERPLATE - DO NOT EDIT THIS BLOCK')
- div_regex = re.compile('<div(.*)>')
- div_end_regex = re.compile('</div>')
- navigation_regex = re.compile('<div class=\"tabs\"(.*)>')
- html_suffix_regex = re.compile('\.html$')
-
- def __init__(self, current_directory):
-
- self.current_directory = current_directory
- self.originals_directory = os.path.join(current_directory, 'original_html')
- if not os.path.exists(self.originals_directory):
- os.mkdir(self.originals_directory)
- self.modifiers = []
-
- def RegisterModifier(self, modifier):
- """Adds the modifier function to the list of modifier functions.
-
- Args:
- modifier: the function modifies a list of strings of code
- """
- self.modifiers += [modifier]
-
- def MakeBackupCopy(self, input_file):
- """Makes backup copy of input_file by copying to originals directory.
-
- Args:
- input_file: basename of file to backup.
- """
- shutil.copy(os.path.join(self.current_directory, input_file),
- self.originals_directory)
-
- def PerformFunctionsOnFile(self, input_file):
- """Opens a file as a list, modifies the list and writes to same file.
-
- Args:
- input_file: the file being operated on.
- """
- infile = open(input_file, 'r')
- lines_list = infile.readlines()
- infile.close()
-
- for function in self.modifiers:
- lines_list = function(lines_list)
-
- outfile = open(input_file, 'w')
- outfile.writelines(lines_list)
- outfile.close()
-
- def FixBrackets(self, lines_list):
- """Adjust brackets to be ezt style.
-
- Fix the brackets such that any open bracket '[' becomes '[[]' in order to
- not conflict with the brackets ezt uses as special characters.
-
- EZT uses boilerplate code at the beginning and end of each file. When
- editing a file, however, we don't want to touch the boilerplate code.
- We can look for special indicators through regular expressions of
- where the content lies between the boilerplate sections and then only
- apply the desired function line by line to the html between those
- sections.
-
- This is a destructive operation and will write over the input file.
-
- Args:
- lines_list: the file to fix broken into lines.
- Returns:
- the lines_list with correctly formatted brackets.
- """
- outside_boilerplate = False
- for index, line in enumerate(lines_list):
- if self.content_end_regex.search(line) and outside_boilerplate:
- # We've reached the end of content; return our work
- return lines_list
- elif self.content_start_regex.search(line):
- # We've found the start of real content, end of boilerplate
- outside_boilerplate = True
- elif outside_boilerplate:
- # Inside real content; fix brackets
- lines_list[index] = line.replace('[', '[[]')
- else:
- pass # Inside boilerplate.
- return lines_list
-
- def RemoveNavigation(self, lines_list):
- """Remove html defining navigation tabs.
-
- This function removes the lines between the <div class ="tabs">...</div>
- which will eliminate the navigation tabs Doxygen outputs at the top of
- its documentation. These are extraneous for Google's codesite which
- produces its own navigation using the ezt templates.
-
- Nested <div>'s are handled, but it currently expects no more than one
- <div>...</div> set per line.
-
- This is a destructive operation and will write over the input file.
-
- Args:
- lines_list: the lines of the file to fix.
- Returns:
- the lines_list reformatted to not include tabs div set.
- """
- start_index = -1
- div_queue = []
- start_end_pairs = {}
- for index, line in enumerate(lines_list):
- # Start by looking for the start of the navigation section
- if self.navigation_regex.search(line):
- start_index = index
- if self.div_regex.search(line):
- if start_index > -1:
- div_queue.append(index)
- if self.div_end_regex.search(line):
- if start_index > -1:
- # If we pop our start_index, we have found the matching </div>
- # to our <div class="tabs">
- if div_queue.pop() == start_index:
- start_end_pairs[start_index] = index
- start_index = -1
-
- # Delete the offending lines
- keys = start_end_pairs.keys()
- keys.sort()
- keys.reverse()
- for k in keys:
- del lines_list[k:start_end_pairs[k]+1]
- return lines_list
-
- def RenameFiles(self, input_file):
- """Fix file suffixes from .html to .ezt.
-
- This will also backup original html files to the originals directory.
-
- This operation will overwrite the previous ezt file.
-
- NOTE: If the originals directory is not a directory, the file will
- be overwritten.
-
- Args:
- input_file: the file to fix.
- """
- # If the file does not end in .html, we do not want to continue
- if self.html_suffix_regex.search(input_file):
- new_name = re.sub(self.html_suffix_regex, '.ezt', input_file)
- shutil.copy(input_file, self.originals_directory)
- # Rename file. If file exists, rename will not overwrite, and produce
- # OSError. So delete the old file first in that case.
- try:
- os.rename(input_file, new_name)
- except OSError:
- os.remove(new_name)
- os.rename(input_file, new_name)
-
-
-def main():
- usage_string = ('This script is meant to convert .html files into .ezt files '
- 'in addition to eliminating any C++-style notations and '
- 'replacing them with their Javascript-style counter parts.\n'
- 'Note: This will write over existing files as well as nuke '
- 'any associated directories such as "original_html" located '
- 'in the same directory as the first argument\n'
- 'Usage: ezt_formatter.py <html_file(s)>')
-
- files = sys.argv[1:]
- if not files:
- # We have no files, so return, showing usage
- print usage_string
- return
-
- # current_directory should be the same for all files
- current_directory = os.path.dirname(files[0])
- formatter = EZTFormatter(current_directory)
- dj = DoxygenJavascriptifier()
- formatter.RegisterModifier(formatter.RemoveNavigation)
- formatter.RegisterModifier(dj.Javascriptify)
- formatter.RegisterModifier(formatter.FixBrackets)
-
- for f in files:
- formatter.PerformFunctionsOnFile(f)
- formatter.RenameFiles(f)
-
- formatter.MakeBackupCopy('stylesheet.css')
-
-if __name__ == '__main__':
- main()
diff --git a/o3d/documentation/ezt_formatter_test.py b/o3d/documentation/ezt_formatter_test.py
deleted file mode 100644
index 7d0ece6..0000000
--- a/o3d/documentation/ezt_formatter_test.py
+++ /dev/null
@@ -1,197 +0,0 @@
-#!/usr/bin/python2.4
-# 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.
-
-
-"""Test for ezt_formatter."""
-
-
-import os
-import os.path
-import ezt_formatter
-import unittest
-
-class EZTFormatterUnitTest(unittest.TestCase):
- def setUp(self):
- self.formatter = ezt_formatter.EZTFormatter('.')
- self.java = ezt_formatter.DoxygenJavascriptifier()
-
- def tearDown(self):
- os.rmdir(self.formatter.originals_directory)
-
- def CreateContentList(self, inner_content):
- content = ['[BOILERPLATE - DO NOT EDIT THIS BLOCK]']
- content += ['[END OF BOILERPLATE]']
- content += inner_content
- content += ['[BOILERPLATE - DO NOT EDIT THIS BLOCK]']
- content += ['[END OF BOILERPLATE]']
- return content
-
- def testJavascriptify(self):
- # test numbers
- content = ['int myInt()']
- content += ['myFloat(float f);']
- java_content = self.java.Javascriptify(content)
- self.assertTrue(java_content[0] == 'Number myInt()')
- self.assertTrue(java_content[1] == 'myFloat(Number f);')
- # test non-javascript tags
- content = ['pure test::myVar [pure virtual] Static']
- content += ['const void testFunction() [virtual] [pure]']
- content += ['testing [explicit]']
- content += ['virtual [protected] test;']
- content += ['static unsigned int function();']
- content += ['const float testing::test()=0']
- content += ['protected testing() [pure]']
- content += ['[pure]']
- java_content = self.java.Javascriptify(content)
- self.assertTrue(java_content[0] == ' test.myVar Global')
- self.assertTrue(java_content[1] == ' testFunction() ')
- self.assertTrue(java_content[2] == 'testing ')
- self.assertTrue(java_content[3] == ' test;')
- self.assertTrue(java_content[4] == ' Number function();')
- self.assertTrue(java_content[5] == ' Number testing.test()')
- self.assertTrue(java_content[6] == ' testing() ')
- self.assertFalse(java_content[7])
- # test static tag
- content = ['myTestFunction() [static]']
- java_content = self.java.Javascriptify(content)
- self.assertTrue(java_content[0] == ('myTestFunction() [<a class="doxygen-'
- 'global">global function</a>]'))
- # test null
- content = ['return NULL;']
- java_content = self.java.Javascriptify(content)
- self.assertTrue(java_content[0] == 'return null;')
- # test Array
- content = ['std.vector&lt;test::arrayType&gt; myArray']
- java_content = self.java.Javascriptify(content)
- self.assertTrue(java_content[0] == 'Array myArray')
-
- def testJavascriptifyGlobal(self):
- content = '<li>static test'
- java_content = self.java.LabelStaticAsGlobal(content)
- self.assertTrue(java_content == ('<li> test [<a class="doxygen-global">'
- 'global function</a>]\n'))
- content = '<li>abcdefg static myFunction(abc)<br>'
- java_content = self.java.LabelStaticAsGlobal(content)
- self.assertTrue(java_content == ('<li>abcdefg myFunction(abc)<br> [<a '
- 'class="doxygen-global">global function'
- '</a>]\n'))
- content = 'static abcde'
- java_content = self.java.LabelStaticAsGlobal(content)
- self.assertTrue(java_content == content)
-
- def testBackupCopy(self):
- test_file = 'test_backup_file'
- open(test_file, 'w')
- self.formatter.MakeBackupCopy(test_file)
- test_file_backup = os.path.join(self.formatter.originals_directory,
- test_file)
- self.assertTrue(os.path.exists(test_file))
- self.assertTrue(os.path.exists(test_file_backup))
- os.remove(test_file)
- os.remove(test_file_backup)
-
- def testPerformFunctionsOnFile(self):
- def ReplaceTest(lines_list):
- new_lines_list = []
- for line in lines_list:
- new_lines_list += [line.replace('test', 'pass')]
- return new_lines_list
-
- test_file = 'test_file'
- lines = ['test\n'] * 20
- outfile = open(test_file, 'w')
- outfile.writelines(lines)
- outfile.close()
-
- self.formatter.RegisterModifier(ReplaceTest)
- self.formatter.PerformFunctionsOnFile(test_file)
-
- infile = open(test_file, 'r')
- infile_lines = infile.readlines()
- infile.close()
- for in_line in infile_lines:
- self.assertTrue(in_line == 'pass\n')
- os.remove(test_file)
-
- def testRemoveNavigation(self):
- content = ['<div class="test">']
- content += ['<div>']
- content += ['<div>']
- content += ['<div class="tabs" name="additional information to parse">']
- content += ['<div>']
- content += ['miscellaneous tab information']
- content += ['</div>']
- content += ['</div>']
- content += ['</div>']
- content += ['</div>']
- content += ['</div>']
- fixed_content = self.formatter.RemoveNavigation(content)
- self.assertTrue(len(fixed_content) == 6)
- self.assertTrue(fixed_content[0] == '<div class="test">')
- self.assertTrue(fixed_content[1] == '<div>')
- self.assertTrue(fixed_content[2] == '<div>')
- self.assertTrue(fixed_content[3] == '</div>')
- self.assertTrue(fixed_content[4] == '</div>')
- self.assertTrue(fixed_content[5] == '</div>')
-
- def testFixBrackets(self):
- content = ['test1']
- content += ['test2[]']
- content += ['test[3]']
- content += ['test[[4]]']
- content = self.CreateContentList(content)
- fixed_content = self.formatter.FixBrackets(content)
- self.assertTrue(fixed_content[2] == 'test1')
- self.assertTrue(fixed_content[3] == 'test2[[]]')
- self.assertTrue(fixed_content[4] == 'test[[]3]')
- self.assertTrue(fixed_content[5] == 'test[[][[]4]]')
-
- def testRenameFiles(self):
- html_file = 'test.html'
- ezt_file = 'test.ezt'
- open(html_file, 'w')
- self.formatter.RenameFiles(html_file)
- self.assertFalse(os.path.exists(html_file))
- self.assertTrue(os.path.exists(ezt_file))
- originals_html_file = os.path.join(self.formatter.originals_directory,
- html_file)
- self.assertTrue(originals_html_file)
- # test functionality when file already exists
- open(html_file, 'w')
- self.formatter.RenameFiles(html_file)
- self.assertFalse(os.path.exists(html_file))
- self.assertTrue(os.path.exists(ezt_file))
- self.assertTrue(originals_html_file)
- os.remove(originals_html_file)
- os.remove(ezt_file)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/o3d/documentation/ezt_formatter_unittest.bat b/o3d/documentation/ezt_formatter_unittest.bat
deleted file mode 100644
index da0494c3d..0000000
--- a/o3d/documentation/ezt_formatter_unittest.bat
+++ /dev/null
@@ -1,33 +0,0 @@
-@echo OFF
-REM Copyright 2009, Google Inc.
-REM All rights reserved.
-REM
-REM Redistribution and use in source and binary forms, with or without
-REM modification, are permitted provided that the following conditions are
-REM met:
-REM
-REM * Redistributions of source code must retain the above copyright
-REM notice, this list of conditions and the following disclaimer.
-REM * Redistributions in binary form must reproduce the above
-REM copyright notice, this list of conditions and the following disclaimer
-REM in the documentation and/or other materials provided with the
-REM distribution.
-REM * Neither the name of Google Inc. nor the names of its
-REM contributors may be used to endorse or promote products derived from
-REM this software without specific prior written permission.
-REM
-REM THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-REM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-REM LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-REM A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-REM OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-REM SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-REM LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-REM DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-REM THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-REM (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-REM OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-set PYTHONDIR=%~dp0..\..\third_party\python_24
-call %PYTHONDIR%\setup_env.bat
-%PYTHONDIR%\python.exe %~dp0\ezt_formatter_test.py %*
diff --git a/o3d/documentation/footer.html b/o3d/documentation/footer.html
deleted file mode 100644
index bbdaf4d..0000000
--- a/o3d/documentation/footer.html
+++ /dev/null
@@ -1,10 +0,0 @@
-</div><!-- end doxygen-ref -->
-[## BOILERPLATE - DO NOT EDIT THIS BLOCK ##]
-[#] </div><!-- end gc-pagecontent -->
-[#] </div><!-- end gooey wrapper -->
-[#]
-[#] [include "/_common_page_footer.ezt"]
-[#]
-[#] </body>
-[#]</html>
-[## END OF BOILERPLATE ##]
diff --git a/o3d/documentation/get_docs_files.py b/o3d/documentation/get_docs_files.py
deleted file mode 100644
index dd4bf3d..0000000
--- a/o3d/documentation/get_docs_files.py
+++ /dev/null
@@ -1,52 +0,0 @@
-#!/usr/bin/env python
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Helper script to generate file lists for documentation.gyp."""
-
-import os
-import sys
-import types
-
-
-def AppendBasePath(folder, filenames):
- """Appends a base path to a ist of files"""
- return [os.path.join(folder, filename) for filename in filenames]
-
-
-def GetIdlFiles():
- idl_list_filename = os.path.join('..', 'plugin', 'idl_list.manifest')
- idl_list_basepath = os.path.dirname(idl_list_filename)
- files = eval(open(idl_list_filename, "r").read())
- idl_files = AppendBasePath(idl_list_basepath, files)
- return idl_files
-
-
-def GetJsFiles():
- js_list_filename = os.path.join('..', 'samples', 'o3djs', 'js_list.manifest')
- js_list_basepath = os.path.dirname(js_list_filename)
- files = eval(open(js_list_filename, "r").read())
- o3djs_files = AppendBasePath(js_list_basepath, files)
- return o3djs_files
-
-
-# Read in the manifest files (which are just really simple python files),
-# and scrape out the file lists.
-# TODO(gspencer): Since we no longer use the scons build, we should
-# rework this so that the lists are just python lists so we can just
-# do a simple eval instead of having to emulate scons import.
-def main(argv):
- files = []
- if argv[0] == '--js':
- files = GetJsFiles()
- if argv[0] == '--idl':
- files = GetIdlFiles()
- files.sort()
- for file in files:
- # gyp wants paths with slashes, not backslashes.
- print file.replace("\\", "/")
-
-
-if __name__ == "__main__":
- main(sys.argv[1:])
diff --git a/o3d/documentation/header.html b/o3d/documentation/header.html
deleted file mode 100644
index 73347e5..0000000
--- a/o3d/documentation/header.html
+++ /dev/null
@@ -1,29 +0,0 @@
-[include "/apis/o3d/_local_variables.ezt"] [# the _local_variables.ezt file should be at the root of your document hierarchy ]
-[define section]docs[end] [# this should almost always be "docs," if the file lives in the "Docs" section (top nav). Otherwise, it's "home," "articles," "download," or "terms" ]
-[define page_title]O3D API[end] [# this is the title for only this page ]
-
-[## BOILERPLATE - DO NOT EDIT THIS BLOCK - VERSION 1.66 ##]
-[#]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
-[#]<html>
-[#] <head>
-[#] [include "/apis/_common_head_elements.ezt"]
-[#] <link href="/css/semantic_headers.css" rel="stylesheet" type="text/css" />
-[#] <link href="stylesheet.css" rel="stylesheet" type="text/css">
-[#] <link href="tabs.css" rel="stylesheet" type="text/css">
-[#] </head>
-[#]
-[#] <body class="gc-documentation">
-[#]
-[#] [define content_section]#gc-pagecontent[end]
-[#] [define navigation_section]#gc-toc[end]
-[#] [include "/_common_page_header.ezt"]
-[#] <div class="g-section g-tpl-170">
-[#]
-[#] <div class="g-unit g-first" id="gc-toc">
-[#] [include toc_path]
-[#] <a class="hidden" href="#gc-topnav-anchor">More [title] resource links</a>
-[#] </div>
-[#]
-[#] <div class="g-unit" id="gc-pagecontent">
-[## END OF BOILERPLATE ##]
-<div id="doxygen-ref">
diff --git a/o3d/documentation/jsdoc-toolkit-templates/annotated.tmpl b/o3d/documentation/jsdoc-toolkit-templates/annotated.tmpl
deleted file mode 100644
index 7f87e49..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/annotated.tmpl
+++ /dev/null
@@ -1,27 +0,0 @@
-<!-- ============================== header ================================= -->
-<!-- begin static/header.html -->
-{+include("static/header.html")+}
-<!-- end static/header.html -->
-
-<div id="doxygen-ref">
-<!-- Genreated by jsdoctoolkit 2.1.0 -->
-<div class="navigation" id="top">
-</div>
-<div class="contents">
-<h1>Class List</h1>
-Here are the classes, structs, unions and interfaces with brief descriptions:
-
-<table>
- {! var allClasses = data.filter(function($){return !$.isNamespace}).sort(makeSortby("alias")); !}
- <for each="thisClass" in="allClasses">
- <tr><td class="indexkey"><a class="el" href="{+getLinkToClassByAlias(thisClass.alias)+}">{+thisClass.alias+}</a></td><td class="indexvalue"></td></tr>
- </for>
-</table>
-
-</div><!-- end contents -->
-</div><!-- end doxygen-ref -->
-
-<!-- ============================== footer ================================= -->
-<!-- begin static/footer.html -->
-{+include("static/footer.html")+}
-<!-- end static/footer.html -->
diff --git a/o3d/documentation/jsdoc-toolkit-templates/class.tmpl b/o3d/documentation/jsdoc-toolkit-templates/class.tmpl
deleted file mode 100644
index 950462b..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/class.tmpl
+++ /dev/null
@@ -1,419 +0,0 @@
-{!
-thisClass = data;
-!}
-
-<!-- ============================== header ================================= -->
- <!-- begin static/header.html -->
- {+include("static/header.html")+}
- <!-- end static/header.html -->
-
-<div id="doxygen-ref">
-<!-- Genreated by jsdoctoolkit 2.1.0 -->
-<div class="navigation" id="top">
- <div class="navpath">{+getHierarchicalLinksToClassByAlias(thisClass.alias,'el')+}</div>
-</div>
-
-<div class="contents">
-<h1>{+thisClass.alias+} <if test="thisClass.isNamespace">Module</if><if test="!thisClass.isNamespace">Class</if> Reference</h1>
-<if test="thisClass.inheritsFrom.length">
- Inherits <a class="el" href="{+getLinkToClassByAlias(thisClass.inheritsFrom[0])+}">{+thisClass.inheritsFrom[0]+}</a>
-</if>
-<p/>
-
-<p/>
-<a href="{+getLinkToClassMembersByAlias(thisClass.alias)+}">List of all members.</a>
-<hr/>
-<a name="_details"></a>
-<h2>Detailed Description</h2>
-<if test="thisClass.classDesc">{+sanitizeForEZT(thisClass.classDesc)+}</if>
-<if test="!thisClass.classDesc">{+sanitizeForEZT(thisClass.desc)+}</if>
-
-<if test="getOutputMode() !== 'o3d' && thisClass.srcFile.length">
-<h2>Source</h2>
-<a name="_source" href="http://code.google.com/p/o3d/source/browse/trunk/samples/{+getSourcePath(thisClass)+}">{+getSourcePath(thisClass)+}</a>
-</if>
-
-<!-- =========== SEE ALSO =========== -->
-<if test="data.see.length">
- <h2>See Also</h2>
- <ul>
- <for each="seeAlso" in="data.see">
- <li>
- {+linkifyTypeSpec(makeName('[Class See Also]', thisClass.alias), seeAlso)+}
- </li>
- </for>
- </ul>
-</if>
-
-<!-- =========== SEE ALSO =========== -->
-
-<!-- ========== CONSTRUCTOR SUMMARY ============== -->
-<if test="shouldWriteConstructor(data)">
- <h2>Constructor</h2>
- <ul>
- <li><a class="el" href="{+data.name+}">{+data.alias+}</a><if test="data.classType != 'Namespace '">{+ makeSignature(data.params) +}</if></li>
- </ul>
-</if>
-
-<!-- ========== PUBLIC TYPES =========== -->
-{! var ownTypes = getPublicTypes(data).sort(makeSortby("name"));
- var justEnums = [];
- for (var ot = 0; ot < ownTypes.length; ++ot) {
- if (isEnum(ownTypes[ot])) {
- justEnums.push(ownTypes[ot]);
- }
- }
-!}
-<if test="ownTypes.length">
- <h2>Public Types</h2>
- <table class="summary">
- <for each="property" in="ownTypes">
- <tr>
- <td>
- <if test="isEnum(property)">
- enum <a class="el" href="#{+property.name+}">{+property.name+}</a>
- </if>
- <if test="!isEnum(property)">
- {+linkifySingleType(makeName('[Type Summary]'), property.memberOf+'.'+property.name)+}
- </if>
- </td>
- <td>{+linkifySingleType(makeName('[Type Summary inherit]'), getParentName(property))+}</td>
- </tr>
- </for>
- </table>
-</if>
-
-<!-- ========== METHOD SUMMARY =========== -->
-<if test="thisClass.methods.length">
- {! var ownMethods = data.methods.sort(makeSortby("name")); !}
- <if test="ownMethods.length">
- <h2>Public Member Functions</h2>
- <table class="summary">
- <for each="method" in="ownMethods">
- <if test="!method.isPrivate">
- <tr>
- <td class="type">
- <if test="method.type.length">{+linkifyTypeSpec(makeName('[Method Summary]', thisClass.alias, method.name), method.type)+}&nbsp;</if>
- </td>
- <td><a class="el" href="#{+method.name+}">{+getNonOverloadedName(method.name)+}</a>{+makeSignature(method.params)+}
- <if test="isDeprecated(method)">
- <span class="deprecated">[[]**DEPRECATED**]</span>
- </if>
- </td>
- <td>{+linkifySingleType(makeName('[Method Summary inherit]'), getParentName(method))+}</td>
- </tr>
- </if>
- </for>
- </table>
- </if>
-</if>
-
-<!-- =========== PROPERTY SUMMARY =========== -->
-{! var ownProperties = getPublicProperties(data).sort(makeSortby("name")); !}
-<if test="ownProperties.length">
- <h2>Public Properties</h2>
- <table class="summary">
- <for each="property" in="ownProperties">
- <tr>
- <td class="type">
- <if test="property.isStatic||!property.memberOf">&lt;Global&gt;&nbsp;</if>
- {+linkifyTypeSpec(makeName('[Property Summary]', thisClass.alias, property.name), getPropertyType(property))+}
- </td>
- <td><a class="el" href="#{+property.name+}">{+property.name+}</a>
- <if test="isDeprecated(property)">
- <span class="deprecated">[[]**DEPRECATED**]</span>
- </if>
- </td>
- <td>{+linkifySingleType(makeName('[Prop Summary inherit]'), getParentName(property))+}</td>
- </tr>
- </for>
- </table>
-</if>
-
-<!-- ========== PARAMETER SUMMARY =========== -->
-{! var ownParameters = getParameters(data); !}
-<if test="ownParameters.length">
- <h2>Parameters</h2>
- <table class="summary">
- <for each="param" in="ownParameters">
- <tr>
- <td class="type">
- {+linkifyTypeSpec(makeName('[Param Summary]', thisClass.alias, param.name), param.type)+}
- </td>
- <td><a class="el" href="#param_{+param.name+}">{+param.name+}</a></td>
- <td>{+linkifySingleType(makeName('[Param Summary inherit]'), param.parent)+}</td>
- </tr>
- </for>
- </table>
-</if>
-
-<!-- ========== CONSTRUCTOR DETAIL ============== -->
-<if test="shouldWriteConstructor(data)">
- <hr/>
- <h2>Constructor</h2>
- <a class="anchor" name="{+data.name+}"></a>
- <div class="memitem">
- <div class="memproto">
- <table class="memname">
- <if test="data.params && data.params.length">
- {!
- var tempCSS = "memname";
- var tempName = data.alias;
- var tempParen = "(";
- var tempEnd = data.params.length > 1 ? "" : ")"
- !}
- <for each="param" in="data.params">
- <tr>
- <td class="{+tempCSS+}">{+tempName+}</td>
- <td>{+tempParen+}</td>
- <td class="paramtype">{+linkifyTypeSpec(makeName('[Constructor Param]', thisClass.alias, param.name), param.type)+}</td>
- <td class="paramname"><em>{+param.name+}</em></td>
- <td><if test="$param_last">)</if></td>
- <td></td>
- </tr>
- {!
- tempCSS = "paramkey";
- tempName = "";
- tempParen = "";
- !}
- </for>
- </if>
- <if test="!data.params || data.params.length == 0">
- <tr>
- <td class="memname">{+data.alias+}</td>
- <td>(</td>
- <td class="paramtype"></td>
- <td class="paramname"></td>
- <td>)</td>
- <td></td>
- </tr>
- </if>
- </table>
- </div>
-
- <div class="memdoc">
- <p/>
- {+sanitizeForEZT(data.desc)+}
- <if test="data.params && data.params.length">
- <dl compact><dt><b>Parameters:</b></dt>
- <dd>
- <table border="0" cellspacing="2" cellpadding="0">
- <for each="param" in="data.params">
- <tr><td valign="top"></td><td valign="top"><em>{+param.name+}</em></td><td>{+sanitizeForEZT(param.desc)+}</td></tr>
- </for>
- </table>
- </dd>
- </dl>
- </if>
- </div>
-
- </div>
-</if>
-
-
-<!-- =========== TYPES DETAIL ============== -->
-
-<if test="defined(justEnums) && justEnums.length">
- <hr/>
- <h2>Public Types Documentation</h2>
- <for each="property" in="justEnums">
- <a class="anchor" name="{+property.name+}"></a>
- <div class="memitem">
- <div class="memproto">
- <table class="memname">
- <tr>
- <td class="memname">{+isEnum(property)?'enum ':''+}{+property.memberOf+"."+property.name+}</td>
- </tr>
- </table>
- </div>
-
- <div class="memdoc">
- <p/>
- {+sanitizeForEZT(property.desc)+}
- </div>
-
- <if test="property.see.length">
- <dl compact><td><b>See Also:</b></dt>
- <dd><ul>
- <for each="seeAlso" in="property.see">
- <li>
- {+linkifyTypeSpec(makeName('[Property See Also]', thisClass.alias), seeAlso)+}
- </li>
- </for>
- </ul></dd>
- </dl>
- </if>
-
- </div>
- </for>
-</if>
-
-
-<!-- =========== METHOD DETAIL ============== -->
-<if test="defined(ownMethods) && ownMethods.length">
- <hr/>
- <h2>Member Function Documentation</h2>
- <for each="member" in="ownMethods">
- <if test="!member.isPrivate">
- <a class="anchor" name="{+member.name+}"></a>
- <div class="memitem">
- <div class="memproto">
- <table class="memname">
- {! var tempInherited = member.memberOf == thisClass.alias ? "" : ("[[]inherited from <a class=\"el\" href=\"" + getLinkToClassByAlias(member.memberOf) + "\">" + member.memberOf + "</a>]"); !}
- <if test="member.params && member.params.length">
- {!
- var tempCSS = "memname";
- var tempName = linkifyTypeSpecForReturn(makeName('[Method Detail]', thisClass.alias, member.name), member.type)+" "+getDocName(data, member);
- var tempParen = "(";
- var tempEnd = member.params.length > 1 ? "" : ")"
- !}
- <for each="param" in="member.params">
- <tr>
- <td class="{+tempCSS+}">{+tempName+}</td>
- <td>{+tempParen+}</td>
- <td class="paramtype">{+linkifyTypeSpec(makeName('[Param Detail]', thisClass.alias, member.name, param.name), param.type)+}</td>
- <td class="paramname"><em>{+param.name+}</em></td>
- <td><if test="$param_last">)</if></td>
- <td><code><if test="$param_last">{+tempInherited+}</if></code></td>
- </tr>
- {!
- tempCSS = "paramkey";
- tempName = "";
- tempParen = "";
- !}
- </for>
- </if>
- <if test="!member.params || member.params.length == 0">
- <tr>
- <td class="memname">{+getDocName(data, member)+}</td>
- <td>(</td>
- <td class="paramtype"></td>
- <td class="paramname"></td>
- <td>)</td>
- <td>{+tempInherited+}</td>
- </tr>
- </if>
- <if test="isDeprecated(member)">
- <td colspan="6" class="deprecated">[[]**DEPRECATED**]</td>
- </if>
- </table>
- </div>
-
- <div class="memdoc">
- <p/>
- {+sanitizeForEZT(member.desc)+}
- <if test="member.params && member.params.length">
- <dl compact><dt><b>Parameters:</b></dt>
- <dd>
- <table border="0" cellspacing="2" cellpadding="0">
- <for each="param" in="member.params">
- <tr><td valign="top"></td><td valign="top"><em>{+param.name+}</em></td><td>
- {+sanitizeForEZT(param.desc)+}</td></tr>
- </for>
- </table>
- </dd>
- </dl>
- </if>
- <if test="member.type && member.type.length">
- <dl class="return" compact><dt><b>Returns:</b></dt>
- <dd>
- {+linkifyTypeSpec(makeName('[Return detail]', thisClass.alias, member.name), member.type)+}.<if test="member.returns && member.returns.length">{+sanitizeForEZT(member.returns[0].desc)+}</if>
- </dd>
- </if>
- </div>
-
- <if test="member.see.length">
- <dl compact><td><b>See Also:</b></dt>
- <dd><ul>
- <for each="seeAlso" in="member.see">
- <li>
- {+linkifyTypeSpec(makeName('[Method See Also]', thisClass.alias, '[See Also]'), seeAlso)+}
- </li>
- </for>
- </ul></dd>
- </dl>
- </if>
-
- </div>
- </if>
- </for>
-</if>
-
-<!-- =========== PROPERTY DETAIL ============== -->
-
-<if test="defined(ownProperties) && ownProperties.length">
- <hr/>
- <h2>Member Property Documentation</h2>
- <for each="property" in="ownProperties">
- <a class="anchor" name="{+property.name+}"></a>
- <div class="memitem">
- <div class="memproto">
- <table class="memname">
- <tr>
- <td class="memname">{+linkifyTypeSpec(makeName('[Property Detail]', thisClass.alias, property.name), getPropertyType(property))+} {+getDocName(data, property)+}
- <if test="isDeprecated(property)">
- <span class="deprecated">[[]**DEPRECATED**]</span>
- </if>
- {+ (property.memberOf == thisClass.alias) ? "" : ("[[]inherited from <a class=\"el\" href=\"" + getLinkToClassByAlias(property.memberOf) + "\">" + property.memberOf + "</a>]") +}
- </td>
- </tr>
- </table>
- </div>
-
- <div class="memdoc">
- <p/>
- {+sanitizeForEZT(property.desc)+}
- </div>
-
- <if test="property.see.length">
- <dl compact><td><b>See Also:</b></dt>
- <dd><ul>
- <for each="seeAlso" in="property.see">
- <li>
- {+linkifyTypeSpec(makeName('[Property See Also]', thisClass.alias), seeAlso)+}
- </li>
- </for>
- </ul></dd>
- </dl>
- </if>
-
- </div>
- </for>
-</if>
-
-<!-- =========== PARAMETER DETAIL ============== -->
-
-<if test="defined(ownParameters) && ownParameters.length">
- <hr/>
- <h2>Parameter Documentation</h2>
- <for each="param" in="ownParameters">
- <a class="anchor" name="param_{+param.name+}"></a>
- <div class="memitem">
- <div class="memproto">
- <table class="memname">
- <tr>
- <td class="memname">{+linkifyTypeSpec(makeName('[Param Detail]', thisClass.alias, param.name), param.type)+} {+param.name+}
- {+ (param.parent == thisClass.alias) ? "" : ("[[]inherited from " + linkifySingleType(makeName('[Param Details inherit]'), param.parent) + "]") +}
- </td>
- </tr>
- </table>
- </div>
-
- <div class="memdoc">
- <p/>
- {+sanitizeForEZT(param.desc)+}
- </div>
-
- </div>
- </for>
-</if>
-
-</div><!-- end contents -->
-</div><!-- end doxygen-ref -->
-
-<!-- ============================== footer ================================= -->
- <!-- begin static/footer.html -->
- {+include("static/footer.html")+}
- <!-- end static/footer.html -->
-
-
diff --git a/o3d/documentation/jsdoc-toolkit-templates/classtree.tmpl b/o3d/documentation/jsdoc-toolkit-templates/classtree.tmpl
deleted file mode 100644
index e5a04e6..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/classtree.tmpl
+++ /dev/null
@@ -1,15 +0,0 @@
-<ul>
- <li><a href="/apis/o3d/docs/reference/{+getBaseURL()+}namespaces.html">Modules</a>
- <ul>
- {! var allNamespaces = data.filter(function($){return $.isNamespace}).sort(makeSortby("alias")); !}
- <for each="thisClass" in="allNamespaces">
- <li><a href="/apis/o3d/docs/reference/{+getBaseURL()+}{+getLinkToClassByAlias(thisClass.alias)+}">{+hyphenateWord(thisClass.name, 16, '-<br/>')+}</a></li>
- </for>
- </ul>
- </li>
- <li><a href="/apis/o3d/docs/reference/{+getBaseURL()+}annotated.html">Classes</a>
- {! var allClasses = data.filter(function($){return !$.isNamespace}).sort(makeSortby("alias")); !}
- {+getClassHierarchyHTML(allClasses)+}
- </li>
-</ul>
-
diff --git a/o3d/documentation/jsdoc-toolkit-templates/dot.tmpl b/o3d/documentation/jsdoc-toolkit-templates/dot.tmpl
deleted file mode 100644
index a669cb6..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/dot.tmpl
+++ /dev/null
@@ -1,21 +0,0 @@
-digraph G {
- graph [
- rankdir = LR
- ]
- node [
- color = aquamarine
- style = filled
- shape = box
- ]
- edge [
- dir = back
- ]
- {! var allClasses = data.filter(function($){return !$.isNamespace}).sort(makeSortby("alias")); !}
- <for each="thisClass" in="allClasses">
- <if test="thisClass.inheritsFrom.length">
- {+thisClass.inheritsFrom[0].replace('o3d.', '')+} -> {+thisClass.alias.replace('o3d.','')+}
- {+thisClass.alias.replace('o3d.','')+} [URL="/apis/o3d/docs/reference/{+getBaseURL()+}{+getLinkToClassByAlias(thisClass.alias)+}"]
- </if>
- </for>
-}
-
diff --git a/o3d/documentation/jsdoc-toolkit-templates/exports.tmpl b/o3d/documentation/jsdoc-toolkit-templates/exports.tmpl
deleted file mode 100644
index 8d291fd..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/exports.tmpl
+++ /dev/null
@@ -1,33 +0,0 @@
-{! thisClass = data; !}
-// ========== CLASS ===========
-goog.exportSymbol('{+getSymbolNameForExport(data)+}', {+getSymbolNameForExport(data)+});
-// ========== PUBLIC TYPES ===========
-{! var ownTypes = getPublicTypes(data).sort(makeSortby("name")); !}
-<if test="ownTypes.length">
- <for each="property" in="ownTypes">
- <if test="isEnum(property)">
-goog.exportSymbol('{+getSymbolNameForExport(property)+}', {+getSymbolNameForExport(property)+});
- </if>
- </for>
-</if>
-
-// ========== METHODS ===========
-<if test="thisClass.methods.length">
- {! var ownMethods = data.methods.sort(makeSortby("name")); !}
- <if test="ownMethods.length">
- <for each="method" in="ownMethods">
- <if test="!method.isPrivate">
-goog.exportSymbol('{+getSymbolNameForExport(method)+}', {+getSymbolNameForExport(method)+});
- </if>
- </for>
- </if>
-</if>
-
-//- =========== PROPERTIES ===========
-{! var ownProperties = getPublicProperties(data).sort(makeSortby("name")); !}
-<if test="ownProperties.length">
- <for each="property" in="ownProperties">
-goog.exportSymbol('{+getSymbolNameForExport(property)+}', {+getSymbolNameForExport(property)+});
- </for>
-</if>
-
diff --git a/o3d/documentation/jsdoc-toolkit-templates/filelist.tmpl b/o3d/documentation/jsdoc-toolkit-templates/filelist.tmpl
deleted file mode 100644
index 5be3659..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/filelist.tmpl
+++ /dev/null
@@ -1,7 +0,0 @@
-<ul>
- {! var allFiles = data.filter(function($){return $.is('FILE')}).sort(makeSortby("alias")); !}
- <for each="thisFile" in="allFiles">
- <li><a href="[path_to_samples]{+getSourcePath(thisFile)+}">{+getSourcePath(thisFile)+}</a></li>
- </for>
-</ul>
-
diff --git a/o3d/documentation/jsdoc-toolkit-templates/members.tmpl b/o3d/documentation/jsdoc-toolkit-templates/members.tmpl
deleted file mode 100644
index e5f4ed6..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/members.tmpl
+++ /dev/null
@@ -1,65 +0,0 @@
-{!
-thisClass = data;
-!}
-
-<!-- ============================== header ================================= -->
- <!-- begin static/header.html -->
- {+include("static/header.html")+}
- <!-- end static/header.html -->
-
-<div id="doxygen-ref">
-<!-- Genreated by jsdoctoolkit 2.1.0 -->
-<div class="navigation" id="top">
-</div>
-
-<div class="contents">
-<h1>{+thisClass.alias+} Member List</h1>
-This is the complete list of members for
-<a class="el" href="{+getLinkToClassByAlias(thisClass.alias)+}">{+thisClass.alias+}</a>, including all inherited members.
-<p/>
-<table>
-
-<!-- ========== CONSTRUCTOR SUMMARY ============== -->
-<if test="shouldWriteConstructor(data)">
-<tr class="memlist"><td><a class="el" href="{+getLinkToClassByAlias(thisClass.alias)+}#{+data.name+}">{+data.alias+}</a><if test="data.classType != 'Namespace '">{+ makeSignature(data.params) +}</if></td><td><a class="el" href="{+getLinkToClassByAlias(thisClass.memberOf)+}">{+thisClass.memberOf+}</a></td><td></td></tr>
-</if>
-
-<!-- ========== METHOD SUMMARY =========== -->
-<if test="thisClass.methods.length">
- {! var ownMethods = data.methods.sort(makeSortby("name")); !}
- <if test="ownMethods.length">
- <for each="method" in="ownMethods">
- <if test="!method.isPrivate">
- <tr class="memlist"><td><a class="el" href="{+getLinkToClassByAlias(thisClass.alias)+}#{+method.name+}">{+getNonOverloadedName(method.name)+}</a>{+ makeSignature(method.params) +}</td><td><a class="el" href="{+getLinkToClassByAlias(method.memberOf)+}">{+method.memberOf+}</a></td><td></td></tr>
- </if>
- </for>
- </if>
-</if>
-
-<!-- =========== FIELD SUMMARY =========== -->
-<if test="data.properties.length">
- {! var ownProperties = data.properties.sort(makeSortby("name")); !}
- <if test="ownProperties.length">
- <for each="property" in="ownProperties">
- <if test="!property.isPrivate">
- <tr class="memlist"><td><a class="el" href="{+getLinkToClassByAlias(thisClass.alias)+}#{+property.name+}">{+property.name+}</a></td><td><a class="el" href="{+getLinkToClassByAlias(property.memberOf)+}">{+property.memberOf+}</a></td><td></td></tr>
- </if>
- </for>
- </if>
-</if>
-
-</table>
-
-
-<!-- =========== END FIELD SUMMARY =========== -->
-
-</div><!-- end contents -->
-</div><!-- end doxygen-ref -->
-
-<!-- ============================== footer ================================= -->
- <!-- begin static/footer.html -->
- {+include("static/footer.html")+}
- <!-- end static/footer.html -->
-
-
-
diff --git a/o3d/documentation/jsdoc-toolkit-templates/namespaces.tmpl b/o3d/documentation/jsdoc-toolkit-templates/namespaces.tmpl
deleted file mode 100644
index 13ccfe4..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/namespaces.tmpl
+++ /dev/null
@@ -1,26 +0,0 @@
-<!-- ============================== header ================================= -->
-<!-- begin static/header.html -->
-{+include("static/header.html")+}
-<!-- end static/header.html -->
-
-<div id="doxygen-ref">
-<!-- Genreated by jsdoctoolkit 2.1.0 -->
-<div class="navigation" id="top">
-</div>
-<div class="contents">
-<h1>Module List</h1>
-Here are the modules with brief descriptions:
-
-<table>
- {! var allClasses = data.filter(function($){return $.isNamespace}).sort(makeSortby("alias")); !}
- <for each="thisClass" in="allClasses">
- <tr><td class="indexkey"><a class="el" href="{+getLinkToClassByAlias(thisClass.alias)+}">{+thisClass.alias+}</a></td><td class="indexvalue"></td></tr>
- </for>
-</table>
-
-</div><!-- end contents -->
-</div><!-- end doxygen-ref -->
-<!-- ============================== footer ================================= -->
-<!-- begin static/footer.html -->
-{+include("static/footer.html")+}
-<!-- end static/footer.html -->
diff --git a/o3d/documentation/jsdoc-toolkit-templates/publish.js b/o3d/documentation/jsdoc-toolkit-templates/publish.js
deleted file mode 100644
index 0518b6f..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/publish.js
+++ /dev/null
@@ -1,1255 +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.
- */
-
-
-/**
- * @fileoverview The jsdoctoolkit loads this file and calls publish()
- */
-
-
-var g_symbolSet; // so we can look stuff up below.
-var g_symbolArray;
-var g_filePrefix;
-var g_skipRE;
-var g_validJSDOCTypes = {
- 'boolean': true,
- 'Event': true,
- 'Element': true,
- 'null': true,
- 'number': true,
- 'Number': true,
- 'object': true,
- 'Object': true,
- '*': true,
- '...': true,
- 'RegExp': true,
- 'string': true,
- 'String': true,
- 'XMLHttpRequest': true,
- 'void': true,
- 'undefined': true};
-var g_unknownTypes = { };
-var g_numErrors = 0;
-var g_o3djsMode = false;
-var g_outputMode;
-var g_baseURL;
-var g_topURL;
-var g_templates = [];
-var g_o3dPropertyRE = /^(\w+)\s+(\w+)\s+/;
-var g_startContainerRE = /^(?:function\(|!function\(|[\(<{[])/;
-var g_containerRE = /function\(|!function\(|[\(<{[]/;
-var g_overloadRE = /xxxOVERLOADED\d+xxx/;
-var g_overloadStr = 'xxxOVERLOADED';
-var g_firstOverloadStr = 'xxxOVERLOADED0xxx';
-var g_openCloseMap = {
- 'function(': ')',
- '!function(': ')',
- '(': ')',
- '<': '>',
- '[': ']',
- '{': '}'};
-var g_closeMap = {
- ')': true,
- '>': true,
- ']': true,
- '}': true};
-var g_symbolsWithoutOverload = {};
-
-/**
- * Called automatically by JsDoc Toolkit.
- * @param {SymbolSet} symbolSet Set of all symbols in all files.
- */
-function publish(symbolSet) {
- try {
- publishInternal(symbolSet);
- } catch (e) {
- generateError(e);
- }
-
- if (g_numErrors > 0) {
- print('Num Errors: ' + g_numErrors);
- System.exit(1);
- }
-}
-
-/**
- * Called by us to catch errors.
- * @param {SymbolSet} symbolSet Set of all symbols in all files.
- */
-function publishInternal(symbolSet) {
- publish.conf = { // trailing slash expected for dirs
- ext: '.ezt',
- outDir: JSDOC.opt.d,
- templatesDir: JSDOC.opt.t,
- symbolsDir: '',
- exportsFile: JSDOC.opt.D.exportsFile,
- prefix: JSDOC.opt.D.prefix,
- mode: JSDOC.opt.D.mode};
- publish.conf.srcDir = publish.conf.outDir + 'src/';
- publish.conf.htmlDir = JSDOC.opt.D.htmlOutDir;
- g_baseURL = JSDOC.opt.D.baseURL;
- g_topURL = JSDOC.opt.D.topURL;
- g_outputMode = JSDOC.opt.D.mode;
-
- for (var key in publish.conf) {
- print ("publish.conf." + key + ": " + publish.conf[key])
- }
-
- if (publish.conf.mode == 'o3djs') {
- g_o3djsMode = true;
- }
-
- // In o3djs mode, don't generate docs for these.
- g_skipRE = new RegExp('^(o3d$|o3d\\.|Vectormath)');
-
- // Symbols we should always skip.
- var alwaysSkipRE = new RegExp('^(_global_|VectorMath|Aos)');
-
- // is source output is suppressed, just display the links to the source file
- if (JSDOC.opt.s && defined(Link) && Link.prototype._makeSrcLink) {
- Link.prototype._makeSrcLink = function(srcFilePath) {
- return '&lt;' + srcFilePath + '&gt;';
- }
- }
-
- // create the folders and subfolders to hold the output
- IO.mkPath((publish.conf.outDir).split('/'));
- IO.mkPath((publish.conf.htmlDir).split('/'));
-
- // used to allow Link to check the details of things being linked to
- Link.symbolSet = symbolSet;
- Link.base = '../';
-
- // used to allow other parts of this module to access database of symbols
- // and the file prefix.
- g_symbolSet = symbolSet;
- g_filePrefix = publish.conf.prefix;
-
- // create the required templates
- try {
- var templatesDir = publish.conf.templatesDir;
- var classTemplate = new JSDOC.JsPlate(templatesDir + 'class.tmpl');
- var exportsTemplate = new JSDOC.JsPlate(templatesDir + 'exports.tmpl');
- var membersTemplate = new JSDOC.JsPlate(templatesDir + 'members.tmpl');
- var classTreeTemplate = new JSDOC.JsPlate(templatesDir + 'classtree.tmpl');
- var fileListTemplate = new JSDOC.JsPlate(templatesDir + 'filelist.tmpl');
- var annotatedTemplate = new JSDOC.JsPlate(templatesDir + 'annotated.tmpl');
- var namespacesTemplate = new JSDOC.JsPlate(templatesDir +
- 'namespaces.tmpl');
- var dotTemplate = new JSDOC.JsPlate(templatesDir + 'dot.tmpl');
- } catch(e) {
- generateError('Couldn\'t create the required templates: ' + e);
- System.exit(1);
- }
-
- // some utility filters
- function hasNoParent($) {return ($.memberOf == '')}
- function isaFile($) {return ($.is('FILE'))}
- function isaClass($) {return ($.is('CONSTRUCTOR') || $.isNamespace)}
-
- // get an array version of the symbolset, useful for filtering
- var symbols = symbolSet.toArray();
- g_symbolArray = symbols;
-
- // create the hilited source code files
- if (false) {
- var files = JSDOC.opt.srcFiles;
- for (var i = 0, l = files.length; i < l; i++) {
- var file = files[i];
- makeSrcFile(file, publish.conf.srcDir);
- }
- }
-
- // Comment this lines in to see all symbol information.
- //for (var ii = 0; ii < symbols.length; ++ii) {
- // var symbol = symbols[ii];
- // print('------[' + symbol.name + ']-------------------------------------');
- // dumpObject(symbol, 5);
- //}
-
- // get a list of all the classes in the symbolset
- var classes = symbols.filter(isaClass).sort(makeSortby('alias'));
- var filteredClasses = [];
- var exports = '';
-
- // create each of the class pages
- for (var i = 0, l = classes.length; i < l; i++) {
- var symbol = classes[i];
- g_unknownTypes = { };
-
- symbol.events = symbol.getEvents(); // 1 order matters
- symbol.methods = symbol.getMethods(); // 2
-
- if ((g_o3djsMode && g_skipRE.test(symbol.alias)) ||
- alwaysSkipRE.test(symbol.alias)) {
- print('Skipping docs for : ' + symbol.alias);
- continue;
- }
-
- print('Generating docs for: ' + symbol.alias);
-
- filteredClasses.push(symbol);
-
- // Comment these lines in to see what data is available to the templates.
- //if (symbol.name == 'Canvas') {
- // print('------[' + symbol.name + ']-----------------------------------');
- // dumpObject(symbol, 5);
- //}
-
- // <a href='symbol.source'>symbol.filename</a>
- symbol.source = symbol.srcFile; // This is used as a link to the source
- symbol.filename = symbol.srcFile; // This is display as the link.
-
- var output = '';
- output = classTemplate.process(symbol);
-
- IO.saveFile(publish.conf.outDir,
- (publish.conf.prefix + symbol.alias +
- '_ref' + publish.conf.ext).toLowerCase(),
- output);
- IO.saveFile(publish.conf.htmlDir,
- (publish.conf.prefix + symbol.alias +
- '_ref.html').toLowerCase(),
- output);
-
- var output = '';
- output = membersTemplate.process(symbol);
- IO.saveFile(publish.conf.outDir,
- (publish.conf.prefix + symbol.alias +
- '_members' + publish.conf.ext).toLowerCase(),
- output);
- IO.saveFile(publish.conf.htmlDir,
- (publish.conf.prefix + symbol.alias +
- '_members.html').toLowerCase(),
- output);
-
- if (publish.conf.exportsFile) {
- exports += exportsTemplate.process(symbol);
- }
- }
-
- var classTree = classTreeTemplate.process(filteredClasses);
- IO.saveFile(publish.conf.outDir, 'classtree.html', classTree);
- IO.saveFile(publish.conf.htmlDir, 'classtree.html', classTree);
-
- var fileList = fileListTemplate.process(symbols);
- IO.saveFile(publish.conf.outDir, 'filelist.html', fileList);
- IO.saveFile(publish.conf.htmlDir, 'filelist.html', fileList);
-
- var annotated = annotatedTemplate.process(filteredClasses);
- IO.saveFile(publish.conf.outDir, 'annotated' + publish.conf.ext, annotated);
- IO.saveFile(publish.conf.htmlDir, 'annotated.html', annotated);
-
- var namespaces = namespacesTemplate.process(filteredClasses);
- IO.saveFile(publish.conf.outDir, 'namespaces' + publish.conf.ext, namespaces);
- IO.saveFile(publish.conf.htmlDir, 'namespaces.html', namespaces);
-
- var dot = dotTemplate.process(filteredClasses);
- IO.saveFile(publish.conf.htmlDir, 'class_hierarchy.dot', dot);
-
- if (publish.conf.exportsFile) {
- print("Writing exports: " + publish.conf.exportsFile);
- var blankLineRE = /\n *\n/gm;
- while (blankLineRE.test(exports)) {
- exports = exports.replace(blankLineRE, '\n');
- }
- var parts = publish.conf.exportsFile.replace('\\', '/').
- match(/(.*?)\/([^\/]+)$/);
- IO.saveFile(parts[1], parts[2], exports);
- }
-}
-
-/**
- * Gets just the first sentence (up to a full stop).
- * Should not break on dotted variable names.
- * @param {string} desc Description to extract summary from.
- * @return {string} summary.
- */
-function summarize(desc) {
- if (typeof desc != 'undefined')
- return desc.match(/([\w\W]+?\.)[^a-z0-9_$]/i) ? RegExp.$1 : desc;
-}
-
-/**
- * Makes a symbol sorter by some attribute.
- * @param {string} attribute to sort by.
- * @return {number} sorter result.
- */
-function makeSortby(attribute) {
- return function(a, b) {
- if (a[attribute] != undefined && b[attribute] != undefined) {
- a = a[attribute].toLowerCase();
- b = b[attribute].toLowerCase();
- if (a < b) return -1;
- if (a > b) return 1;
- return 0;
- }
- }
-}
-
-/**
- * Pull in the contents of an external file at the given path.
- * @param {string} path Path of file relative to template directory.
- * @return {string} contents of file.
- */
-function include(path) {
- var template = g_templates[path];
- if (!template) {
- try {
- template = new JSDOC.JsPlate(JSDOC.opt.t + path);
- } catch (e) {
- generateError('Could not include: ' + path + '\n' + e);
- template = '';
- }
- g_templates[path] = template;
- }
- var output = template.process({});
- return output;
-}
-
-/**
- * Turns a raw source file into a code-hilited page in the docs.
- * @param {string} path Path to source.
- * @param {string} srcDir path to place to store hilited page.
- * @param {string} opt_name to name output file.
- *
- */
-function makeSrcFile(path, srcDir, opt_name) {
- if (JSDOC.opt.s) return;
-
- if (!opt_name) {
- opt_name = path.replace(/\.\.?[\\\/]/g, '').replace(/[\\\/]/g, '_');
- opt_name = opt_name.replace(/\:/g, '_');
- }
-
- var src = {path: path, name: opt_name, charset: IO.encoding, hilited: ''};
-
- if (defined(JSDOC.PluginManager)) {
- JSDOC.PluginManager.run('onPublishSrc', src);
- }
-
- if (src.hilited) {
- IO.saveFile(srcDir, opt_name + publish.conf.ext, src.hilited);
- }
-}
-
-/**
- * Builds output for displaying function parameters.
- * @param {Array} params Array of function params.
- * @return {string} string in format '(param1, param2)'.
- */
-function makeSignature(params) {
- if (!params) return '()';
- var signature = '(' +
- params.filter(
- function($) {
- return $.name.indexOf('.') == -1; // don't show config params in signature
- }
- ).map(
- function($) {
- return $.name;
- }
- ).join(', ') + ')';
- return signature;
-}
-
-/**
- * Find symbol {@link ...} strings in text and turn into html links.
- * @param {string} str String to modify.
- * @return {string} modifed string.
- */
-function resolveLinks(str) {
- str = str.replace(/\{@link ([^} ]+) ?\}/gi,
- function(match, symbolName) {
- return new Link().toSymbol(symbolName);
- }
- );
-
- return str;
-}
-
-/**
- * Makes a link for a symbol.
- *
- * @param {string} symbolName Name of symbol
- * @param {string} extra extra
- * @param {string} opt_bookmark Optional bookmark.
- */
-function makeSymbolLink(symbolName, extra, opt_bookmark) {
- var prefix = g_filePrefix;
- if (g_o3djsMode && g_skipRE.test(symbolName)) {
- prefix = '../classo3d_1_1_';
- }
- return (prefix + symbolName + extra +
- '.html').toLowerCase() +
- (opt_bookmark ? '#' + opt_bookmark : '');
-}
-
-/**
- * Make link from symbol.
- * @param {Object} symbol Symbol from class database.
- * @param {string} opt_extra extra suffix to add before '.html'.
- * @return {string} url to symbol.
- */
-function getLinkToSymbol(symbol, opt_extra) {
- opt_extra = opt_extra || '_ref';
- if (symbol.is('CONSTRUCTOR') || symbol.isNamespace) {
- return makeSymbolLink(symbol.alias, opt_extra);
- } else {
- var parentSymbol = getSymbol(symbol.memberOf);
- return makeSymbolLink(parentSymbol.alias, opt_extra, symbol.name);
- }
-}
-
-/**
- * Given a class alias, returns a link to its reference page
- * @param {string} classAlias Fully qualified name of class.
- * @return {string} url to class.
- */
-function getLinkToClassByAlias(classAlias) {
- var symbol = getSymbol(classAlias);
- if (!symbol) {
- throw Error('no documentation for "' + classAlias + '"');
- }
- return getLinkToSymbol(symbol);
-}
-
-/**
- * Given a class alias, returns a link to its member reference page
- * @param {string} classAlias Fully qualified name of class.
- * @return {string} url to class in members file.
- */
-function getLinkToClassMembersByAlias(classAlias) {
- var symbol = getSymbol(classAlias);
- return getLinkToSymbol(symbol, '_members');
-}
-
-/**
- * Given a class alias like o3djs.namespace.function returns an HTML string
- * with a link to each part (o3djs, namespace, function)
- * @param {string} classAlias Fully qualified alias of class.
- * @param {string} opt_cssClassId css class Id to put in class="" instead links.
- * @return {string} html with links to each class and parent.
- */
-function getHierarchicalLinksToClassByAlias(classAlias, opt_cssClassId) {
- var parts = classAlias.split('.');
- var name = '';
- var html = '';
- var delim = '';
- var classId = '';
- if (opt_cssClassId) {
- classId = ' class="' + opt_cssClassId + '"';
- }
- for (var pp = 0; pp < parts.length; ++pp) {
- var part = parts[pp];
- name = name + delim + part;
- link = getLinkToClassByAlias(name);
- html = html + delim + '<a' + classId +
- ' href="' + link + '">' + part + '</a>';
- delim = '.';
- }
- return html;
-}
-
-/**
- * Dumps a javascript object.
- *
- * @param {Object} obj Object to dump.
- * @param {number} depth Depth to dump (0 = forever).
- * @param {string} opt_prefix Prefix to put before each line.
- */
-function dumpObject(obj, depth, opt_prefix) {
- opt_prefix = opt_prefix || '';
- --depth;
- for (var prop in obj) {
- if (typeof obj[prop] != 'function') {
- dumpWithPrefix(prop + ' : ' + obj[prop], opt_prefix);
- if (depth != 0) {
- dumpObject(obj[prop], depth, opt_prefix + ' ');
- }
- }
- }
-}
-
-/**
- * Dumps a string, putting a prefix before each line
- * @param {string} str String to dump.
- * @param {string} prefix Prefix to put before each line.
- */
-function dumpWithPrefix(str, prefix) {
- var parts = str.split('\n');
- for (var pp = 0; pp < parts.length; ++pp) {
- print(prefix + parts[pp]);
- }
-}
-
-/**
- * gets the type of a property.
- * @param {!object} property Property object.
- * @return {string} type of property.
- */
-function getPropertyType(property) {
- if (property.type.length > 0) {
- return property.type;
- } else {
- var tag = property.comment.getTag('type');
- if (tag.length > 0) {
- return tag[0].type;
- } else {
- return 'undefined';
- }
- }
-}
-
-/**
- * Gets the parameters for a class.
- * Parameters are an o3d specific thing. We have to look for tags that
- * start with @o3dparameter
- * @param {!Symbol} symbol
- */
-function getParameters(symbol) {
- var params = [];
- if (symbol.inheritsFrom.length) {
- params = getParameters(getSymbol(symbol.inheritsFrom[0]));
- }
-
- var tags = symbol.comment.getTag('o3dparameter');
- for (var ii = 0; ii < tags.length; ++ii) {
- var tag = tags[ii];
- var tagString = tag.toString();
- var parts = tagString.match(g_o3dPropertyRE);
- if (!parts) {
- generateError('Malformed o3dparameter specification for ' + symbol.alias +
- ' : "' + tag + '"');
- } else {
- var descString = tagString.substr(parts[0].length);
- var param = {
- name: parts[1],
- type: 'o3d.' + parts[2],
- desc: descString,
- parent: symbol.alias,
- };
- params.push(param);
- }
- }
- return params;
-}
-
-/**
- * Generates an HTML class hierarchy.
- * @param {!Array.<!Symbol>} classes Class to make hierarchy from.
- * @return {string} HTML hierarchical list of classes.
- */
-function getClassHierarchyHTML(classes) {
- var classTree = {};
-
- for (var cc = 0; cc < classes.length; ++cc) {
- var thisClass = classes[cc];
- var stack = [thisClass];
- while (thisClass.inheritsFrom !== undefined &&
- thisClass.inheritsFrom.length > 0) {
- var parentName = thisClass.inheritsFrom[0];
- thisClass = getSymbol(parentName);
- stack.push(thisClass);
- }
-
- var node = classTree;
- for (var ii = stack.length - 1; ii >= 0; --ii) {
- var thisClass = stack[ii];
- var className = thisClass.alias;
- if (!node[className]) {
- node[className] = { };
- }
- node = node[className];
- }
- }
-
- return addParts(classTree, '');
-
- /**
- * Recursively creates hierarchical list of classes.
- * @param {!Object} node A hash of class names to derived classes.
- * @param {string} prefix Prefix to put in front of each line.
- */
- function addParts(node, prefix) {
- var output = '';
- var names = [];
- for (var name in node) {
- names.push(name);
- }
- if (names.length > 0) {
- output += prefix + '<ul>\n';
- names = names.sort();
- for (var kk = 0; kk < names.length; ++kk) {
- var name = names[kk];
- var shortName = name;
- var period = name.lastIndexOf('.');
- if (period >= 0) {
- shortName = name.substr(period + 1);
- }
- output += prefix + '<li><a href="/apis/o3d/docs/reference/' +
- getBaseURL() +
- getLinkToClassByAlias(name) +
- '">' +
- hyphenateWord(shortName, 16, '-<br/>') +
- '</a>';
- output += addParts(node[name], prefix + ' ') + '\n';
- output += prefix + '</li>\n';
- }
- output += prefix + '</ul>\n';
- }
- return output;
- }
-}
-
-/**
- * Returns whether or not the symbol is deprecated. Apparently jsdoctoolkit is
- * supposed to extract this info for us but it's not so we have to do it
- * manually.
- * @param {!Symbol} symbol The symbol to check.
- * @return {boolean} True if the symbol is deprecated.
- */
-function isDeprecated(symbol) {
- var tags = symbol.comment.getTag('deprecated');
- return tags.length > 0;
-}
-
-/**
- * Converts [ to [[] for ezt files.
- * Also converts '\n\n' to <br/></br>
- * @param {string} str to sanitize.
- * @return {string} Sanitized string.
- */
-function sanitizeForEZT(str) {
- str = str.replace(/<pre>/g, '<pre class="prettyprint">');
- return str.replace(/\[/g, '[[]').replace(/\n\n/g, '<br/><br/>');
-}
-
-/**
- * Check if string starts with another string.
- * @param {string} str String to check.
- * @param {string} prefix Prefix to check for.
- * @return {boolean} True if str starts with prefix.
- */
-function startsWith(str, prefix) {
- return str.substring(0, prefix.length) === prefix;
-}
-
-/**
- * Check if string ends with another string.
- * @param {string} str String to check.
- * @param {string} suffix Suffix to check for.
- * @return {boolean} True if str ends with suffix.
- */
-function endsWith(str, suffix) {
- return str.substring(str.length - suffix.length) === suffix;
-}
-
-/**
- * Returns a string stripped of leading and trailing whitespace.
- * @param {string} str String to strip.
- * @return {string} stripped string.
- */
-function stripWhitespace(str) {
- return str.replace(/^\s+/, '').replace(/\s+$/, '');
-}
-
-/**
- * Converts a camelCase name to underscore as in TypeOfFruit becomes
- * type_of_fruit.
- * @param {string} str CamelCase string.
- * @return {string} underscorified str.
- */
-function camelCaseToUnderscore(str) {
- function toUnderscore(match) {
- return '_' + match.toLowerCase();
- }
- return str[0].toLowerCase() +
- str.substring(1).replace(/[A-Z]/g, toUnderscore);
-}
-
-/**
- * Prints a warning about an unknown type only once.
- * @param {string} place Use to print error message if type not found.
- * @param {string} type Type specification.
- */
-function reportUnknownType(place, type) {
- if (!g_unknownTypes[type]) {
- g_unknownTypes[type] = true;
- generatePlaceError (place, 'reference to unknown type: "' + type + '"');
- }
-}
-
-/**
- * Gets index of closing character.
- * @param {string} str string to search.
- * @param {number} startIndex index to start searching at. Must be an opening
- * character.
- * @return {number} Index of closing character or (-1) if not found.
- */
-function getIndexOfClosingCharacter(str, startIndex) {
- var stack = [];
- if (!g_openCloseMap[str[startIndex]]) {
- throw 'startIndex does not point to opening character.';
- }
- var endIndex = str.length;
- while (startIndex < endIndex) {
- var c = str[startIndex];
- var closing = g_openCloseMap[c];
- if (closing) {
- stack.unshift(closing);
- } else {
- closing = g_closeMap[c];
- if (closing) {
- var expect = stack.shift()
- if (c != expect) {
- return -1;
- }
- if (stack.length == 0) {
- return startIndex;
- }
- }
- }
- ++startIndex;
- }
- return -1;
-}
-
-/**
- * Make's a name by concatenating strings.
- * @param {...[string]} strings to concatenate.
- * @return {string} Concatenated string.
- */
-function makeName() {
- var str = '';
- for (var ii = 0; ii < arguments.length; ++ii) {
- if (str) {
- str += '.';
- }
- str += arguments[ii];
- }
- return str;
-}
-
-/**
- * Generates an error msg.
- * @param {string} msg.
- */
-function generateError(msg) {
- ++g_numErrors;
- print('ERROR: ' + msg);
-}
-
-/**
- * Generates an error msg.
- * @param {string} place Use to print error message.
- * @param {string} msg.
- */
-function generatePlaceError(place, msg) {
- generateError(place + ': ' + msg);
-}
-
-/**
- * Converts a reference to a single JSDOC type specification to an html link.
- * @param {string} place Use to print error message if type not found.
- * @param {string} str to linkify.
- * @return {string} linkified string.
- */
-function linkifySingleType(place, type) {
- if (!type) {
- generatePlaceError(place, 'type is empty');
- return '';
- }
- type = stripWhitespace(type);
- var not = '';
- var equals = '';
- // Remove ! if it exists.
- if (type[0] == '!') {
- not = '!'
- type = type.substring(1);
- }
- if (endsWith(type, '=')) {
- equals = '=';
- type = type.substring(0, type.length - 1);
- }
-
- var link = type;
-
- // Check for array wrapper.
- if (startsWith(type, 'Array.<')) {
- var closingAngle = getIndexOfClosingCharacter(type, 6);
- if (closingAngle < 0) {
- generatePlaceError(place, 'Unmatched "<" in Array type : ' + type);
- } else {
- link = 'Array.&lt;' +
- linkifySingleType(place, type.substring(7, closingAngle)) + '>';
- }
- } else if (startsWith(type, 'Object.<')) {
- var closingAngle = getIndexOfClosingCharacter(type, 7);
- if (closingAngle < 0) {
- generatePlaceError(place, 'Unmatched "<" in Object type : ' + type);
- } else {
- var objectSpec = type.substring(8, closingAngle);
- var elements = objectSpec.split(/\s*,\s*/);
- if (elements.length != 2) {
- generatePlaceError(place, 'An Object spec must have exactly 2 types');
- }
- link = 'Object.&lt;' +
- linkifySingleType(place, elements[0]) + ', ' +
- linkifySingleType(place, elements[1]) + '>';
- }
- } else if (startsWith(type, 'function(')) {
- var closingParen = getIndexOfClosingCharacter(type, 8);
- if (closingParen < 0) {
- generatePlaceError(place, 'Unmatched "(" in function type : ' + type);
- } else {
- var end = type.substring(closingParen + 1);
- if (!startsWith(end, ': ')) {
- generatePlaceError(place,
- 'Malformed return specification on function. Must be' +
- ' "function(args): type" including the space after the colon.');
- } else {
- var output = '';
- var argsStr = type.substring(9, closingParen);
- if (argsStr) {
- // TODO(gman): This needs to split taking parens, brackets and angle
- // brackets into account.
- var args = argsStr.split(/ *, */);
- for (var ii = 0; ii < args.length; ++ii) {
- if (ii > 0) {
- output += ', ';
- }
- output += linkifyTypeSpec(place, args[ii]);
- }
- }
- link = 'function(' + output + '): ' +
- linkifyTypeSpec(place, end.substring(2));
- }
- }
- } else if (startsWith(type, '{') && endsWith(type, '}')) {
- // found a record.
- var elements = type.substr(1, type.length - 2).split(/\s*,\s*/);
- var output = '{';
- for (var ii = 0; ii < elements.length; ++ii) {
- if (ii > 0) {
- output += ', ';
- }
- var element = elements[ii];
- var colon = element.indexOf(': ');
- if (colon < 0) {
- generatePlaceError(place,
- 'Malformed record specification. Format must be ' +
- '{id1: type1, id2: type2, ...}.');
- output += element;
- } else {
- var name = element.substring(0, colon);
- var subType = element.substring(colon + 2);
- output += name + ':&nbsp;' + linkifyTypeSpec(place, subType);
- }
- }
- link = output + '}';
- } else {
- var symbol = getSymbol(type);
- if (symbol) {
- link = '<a class="el" href="' + getLinkToSymbol(symbol) + '">' +
- type + '</a>';
- } else {
- // See if the symbol is a property or field.
- var found = false;
- var period = type.lastIndexOf('.');
- if (period >= 0 && type != '...') {
- var subType = type.substring(0, period);
- var member = type.substring(period + 1);
- symbol = getSymbol(subType);
- if (symbol) {
- if (symbol.hasMember(member) ||
- symbol.hasMember(member + g_firstOverloadStr)) {
- var field = type.substring(period + 1);
- link = '<a class="el" href="' + getLinkToSymbol(symbol) + '#' +
- field + '">' + type + '</a>';
- found = true;
- }
- }
- }
-
- if (!found) {
- if (type[0] == '?') {
- type = type.substring(1);
- }
- if (!g_validJSDOCTypes[type]) {
- reportUnknownType(place, type);
- }
- }
- }
- }
-
- return not + link + equals;
-}
-
-/**
- * Splits a string by containers. A string like "ab(cd,ef)gh" will
- * be returned as ['ab', '(cd,ef)', 'gh']
- * @param {string} str String to split.
- * @return {!Array.<string>} The split string parts.
- */
-function splitByContainers(str) {
- var parts = [];
- for (;;) {
- var match = str.match(g_containerRE);
- if (!match) {
- if (str.length > 0) {
- parts.push(str);
- }
- return parts;
- }
- var startIndex = str.indexOf(match);
- if (startIndex != 0) {
- parts.push(str.substring(0, startIndex));
- }
- var endIndex = getIndexOfClosingCharacter(
- str, startIndex + match.toString().length - 1);
- if (endIndex < 0) {
- throw 'no closing character for "' + str[startIndex] + '" in "' + str +
- '"';
- }
- var piece = str.substring(startIndex, endIndex + 1);
- parts.push(piece);
- str = str.substring(endIndex + 1);
- }
-}
-
-/**
- * Fix function specs.
- * The jsdoctoolkit wrongly converts ',' to | as in 'function(a, b)' to
- * 'function(a|b)' and '{id1: type1, id2: type2}' to '{id1: type1|id2: type2}'
- * so we need to put those back here (or fix jsdoctoolkit, the proper solution).
- * Worse, we have to distinguish between 'function(a|b)' and '(a|b)'. The former
- * needs to become 'function(a, b)' while the later needs to stay the same.
- *
- * @param {string} str JSDOC type specification string .
- * @param {boolean} opt_paren True if we are inside a paren.
- * @return {string} str with '|' converted back to ', ' unless the specification
- * starts with '(' and ends with ')'. That's not a very good check beacuse
- * you could 'function((string|number)) and this would fail to do the right
- * thing.
- */
-function fixSpecCommas(str, opt_paren) {
- var start = str.match(g_startContainerRE);
- if (start) {
- var startStr = start.toString();
- var closing = g_openCloseMap[startStr];
- if (closing) {
- var lastChar = str[str.length - 1];
- if (lastChar == closing) {
- var middle = str.substring(startStr.length, str.length - 1);
- return startStr +
- fixSpecCommas(middle, startStr === '(') +
- lastChar;
- }
- }
- }
-
- if (str.match(g_containerRE)) {
- var parts = splitByContainers(str);
- for (var ii = 0; ii < parts.length; ++ii) {
- parts[ii] = fixSpecCommas(parts[ii], opt_paren);
- }
- return parts.join('');
- } else {
- if (opt_paren) {
- return str;
- }
- return str.replace(/\|/g, ', ');
- }
-}
-
-/**
- * Converts a JSDOC type specification into html links. For example
- * '(!o3djs.math.Vector3|!o3djs.math.Vector4)' would change to
- * '(!<a href="??">o3djs.math.Vector3</a>
- * |!<a href="??">o3djs.math.Vector4</a>)'.
- * @param {string} place Use to print error message if type not found.
- * @param {string} str to linkify.
- * @return {string} linkified string.
- */
-function linkifyTypeSpec(place, str) {
- var output = '';
- if (str) {
- try {
- var fixed = fixSpecCommas(str);
- } catch (e) {
- generatePlaceError(place, e);
- }
- // TODO: needs to split outside of parens and angle brackets.
- if (startsWith(fixed, '(') && endsWith(fixed, ')')) {
- var types = fixed.substring(1, fixed.length - 1).split('|');
- output += '(';
- for (var tt = 0; tt < types.length; ++tt) {
- if (tt > 0) {
- output += '|';
- }
- output += linkifySingleType(place, types[tt]);
- }
- output += ')';
- } else {
- output += linkifySingleType(place, fixed);
- }
- } else {
- generatePlaceError(place, 'missing type specification (' + str + ')');
- }
- return output;
-}
-
-/**
- * Same as linkifyTypeSpec but allows str to be undefined or ''.
- * @param {string} place Use to print error message if type not found.
- * @param {string} str to linkify.
- * @return {string} linkified string.
- */
-function linkifyTypeSpecForReturn(place, str) {
- if (str) {
- return linkifyTypeSpec(place, str);
- }
- return '';
-}
-
-/**
- * Check if a symbol is an enum.
- * @param {!Symbol} symbol Symbol to check.
- * @return {boolean} true if symbol is an enum
- */
-function isEnum(symbol) {
- if (symbol.isStatic && !symbol.isNamespace) {
- if (symbol.comment && symbol.comment.tagTexts) {
- for (var ii = 0; ii < symbol.comment.tagTexts.length; ++ii) {
- var tag = symbol.comment.tagTexts[ii];
- if (startsWith(tag.toString(), 'enum')) {
- return true;
- }
- }
- }
- }
- return false;
-}
-
-/**
- * Gets the public properties of a symbol.
- * @param {!Symbol} symbol The symbol to get properties from.
- * @return {!Array.<!Symbol>} The public properties of the symbol.
- */
-function getPublicProperties(symbol) {
- var publicProperties = [];
- for (var ii = 0; ii < symbol.properties.length; ++ii) {
- var property = symbol.properties[ii];
- if (!property.isPrivate && !property.isNamespace && !isEnum(property)) {
- publicProperties.push(property);
- }
- }
- return publicProperties;
-}
-
-/**
- * Gets the public types of a symbol.
- * @param {!Symbol} symbol The symbol to get properties from.
- * @return {!Array.<!Symbol>} The public types of the symbol.
- */
-function getPublicTypes(symbol) {
- var publicTypes = [];
- for (var ii = 0; ii < symbol.properties.length; ++ii) {
- var type = symbol.properties[ii];
- if (!type.isPrivate && !type.isNamespace && isEnum(type)) {
- publicTypes.push(type);
- }
- }
- for (var ii = 0; ii < g_symbolArray.length; ++ii) {
- var type = g_symbolArray[ii];
- if (type.memberOf == symbol.alias &&
- !type.isPrivate &&
- type.is('CONSTRUCTOR')) {
- publicTypes.push(type);
- }
- }
- return publicTypes;
-}
-
-/**
- * Gets a symbol for a type.
- * This is here mostly for debugging so you can insert a print before or after
- * each call to g_symbolSet.getSymbol.
- * @param {string} type fully qualified type.
- * @return {Symbol} The symbol object for the type or null if not found.
- */
-function getSymbol(type) {
- return g_symbolSet.getSymbol(type);
-}
-
-/**
- * Gets the source path for a symbol starting from 'o3djs/'
- * @param {!Symbol} symbol The symbol to get the source name for.
- * @return {string} The name of the source file.
- */
-function getSourcePath(symbol) {
- var path = symbol.srcFile.replace(/\\/g, '/');
- var index = path.indexOf('/o3djs/');
- return path.substring(index + 1);
-}
-
-/**
- * Gets the name of the parent of a symbol.
- * @param {!Symbol} symbol The symbol to get the parent of
- * @return {string} The parent's name.
- */
-function getParentName(symbol) {
- var parent = getSymbol(symbol.memberOf);
- return parent.isNamespace ? symbol.memberOf : parent.alias;
-}
-
-/**
- * Gets a qualified name. Used for members. For namespaces will return the fully
- * qualified name. For objects will return just ObjectName.method
- * @param {!Symbol} method The method or property to get a qualified name for.
- * @return {string} The qualified name for the method or property.
- */
-function getQualifiedName(method) {
- return getParentName(method) + '.' + method.name;
-}
-
-/**
- * Removes the "xxxOVERLOADEDxxx" part of a name
- * @param {string} name Name that may have a overloaded suffux.
- * @return {string} The name without the overloaded suffix.
- */
-function getNonOverloadedName(name) {
- var index = name.indexOf(g_overloadStr);
- if (index >= 0) {
- return name.substring(0, index);
- }
- return name;
-}
-
-/**
- * Gets a Documentation name. For members of a namespace returns the fully
- * qualified name. For members of a class returns ClassName.name
- * @param {!Symbol} parent Symbol that we are making docs for.
- * @param {!Symbol} child Method or property of parent to get doc name for.
- * @return {string} Doc name for child.
- */
-function getDocName(parent, child) {
- if (parent.isNamespace) {
- return child.memberOf + "." + getNonOverloadedName(child.name);
- }
- return parent.name + "." + getNonOverloadedName(child.name);
-}
-
-/**
- * Gets a symbol name for export. If the method or property is static returns
- * "Namespace.Class.method". If not returns "Namespace.Class.prototype.method".
- * @param {!Symbol} symbol Symbol to get name for.
- * @return {string} Name of symbol.
- */
-function getSymbolNameForExport(symbol) {
- if (!symbol.memberOf) {
- return symbol.name;
- }
- return symbol.memberOf +
- ((symbol.isStatic || symbol.isNamespace) ? '.' : '.prototype.') +
- symbol.name;
-}
-
-/**
- * Gets the base URL for links.
- */
-function getBaseURL() {
- return g_baseURL;
-}
-
-/**
- * Gets the top URL for links.
- */
-function getTopURL() {
- return g_topURL;
-}
-
-/**
- * Returns the output mode.
- * @return {string} The output mode.
- */
-function getOutputMode() {
- return g_outputMode;
-}
-
-/**
- * Returns true if we should write constructor docs.
- * @param {!Symbol} symbol The symbol that might have a constructor.
- * @return {boolean} true if we should write a constructor.
- */
-function shouldWriteConstructor(symbol) {
- return g_outputMode != 'o3d' &&
- !symbol.isPrivate &&
- !symbol.isBuiltin() &&
- !symbol.isNamespace &&
- symbol.is('CONSTRUCTOR');
-}
-
-/**
- * Splits a camelCase word into an array of word parts.
- * @param {string} word camelCase word.
- * @return {!Array.<string>} The word split into word parts.
- */
-function splitCamelCase(word) {
- var spacesAdded = word.replace(/([A-Z])/g, ' $1');
- return spacesAdded.split(' ');
-}
-
-/**
- * Breaks a word at max_length with hyphens. Assumes word is camelCase
- * @param {string} word Word to break.
- * @param {number} maxLength word will continue to be split until no part is
- * this longer than this if possible.
- * @param {string} string to use to join split parts.
- * @return {string} The word split then joined with joinString.
- */
-function hyphenateWord(word, maxLength, joinString) {
- var words = splitCamelCase(word);
- var hyphenated = '';
- var newWord = '';
- for (var ii = 0; ii < words.length; ++ii) {
- var part = words[ii];
- var temp = newWord + part;
- if (temp.length > maxLength) {
- hyphenated += newWord + joinString;
- newWord = '';
- }
- newWord += part;
- }
- hyphenated += newWord;
- return hyphenated;
-}
diff --git a/o3d/documentation/jsdoc-toolkit-templates/static/footer.html b/o3d/documentation/jsdoc-toolkit-templates/static/footer.html
deleted file mode 100644
index 031bf6d..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/static/footer.html
+++ /dev/null
@@ -1,10 +0,0 @@
-[## BOILERPLATE - DO NOT EDIT THIS BLOCK ##]
-[#] </div><!-- end gc-pagecontent -->
-[#] </div><!-- end gooey wrapper -->
-[#]
-[#] [include "/_common_page_footer.ezt"]
-[#]
-[#] </body>
-[#]</html>
-[## END OF BOILERPLATE ##]
-
diff --git a/o3d/documentation/jsdoc-toolkit-templates/static/header.html b/o3d/documentation/jsdoc-toolkit-templates/static/header.html
deleted file mode 100644
index e06b775..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/static/header.html
+++ /dev/null
@@ -1,30 +0,0 @@
-[include "/apis/o3d/_local_variables.ezt"] [# the _local_variables.ezt file should be at the root of your document hierarchy ]
-[define section]docs[end] [# this should almost always be "docs," if the file lives in the "Docs" section (top nav). Otherwise, it's "home," "articles," "download," or "terms" ]
-[define page_title]O3D API[end] [# this is the title for only this page ]
-
-[## BOILERPLATE - DO NOT EDIT THIS BLOCK - VERSION 1.66 ##]
-[#]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
-[#]<html>
-[#] <head>
-[#] [include "/apis/_common_head_elements.ezt"]
-[#] <link href="/css/semantic_headers.css" rel="stylesheet" type="text/css" />
-[#] <link href="{+getTopURL()+}stylesheet.css" rel="stylesheet" type="text/css">
-[#] <link href="{+getTopURL()+}tabs.css" rel="stylesheet" type="text/css">
-[#] <link href="{+getTopURL()+}prettify.css" rel="stylesheet" type="text/css">
-[#] <script type="text/javascript" src="{+getTopURL()+}prettify.js"></script>
-[#] </head>
-[#]
-[#] <body class="gc-documentation" onload="prettyPrint()">
-[#]
-[#] [define content_section]#gc-pagecontent[end]
-[#] [define navigation_section]#gc-toc[end]
-[#] [include "/_common_page_header.ezt"]
-[#] <div class="g-section g-tpl-170">
-[#]
-[#] <div class="g-unit g-first" id="gc-toc">
-[#] [include toc_path]
-[#] <a class="hidden" href="#gc-topnav-anchor">More [title] resource links</a>
-[#] </div>
-[#]
-[#] <div class="g-unit" id="gc-pagecontent">
-[## END OF BOILERPLATE ##]
diff --git a/o3d/documentation/jsdoc-toolkit-templates/static/prettify.css b/o3d/documentation/jsdoc-toolkit-templates/static/prettify.css
deleted file mode 100644
index 1b4954b..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/static/prettify.css
+++ /dev/null
@@ -1,34 +0,0 @@
-.str{ color: #008 }
-.kwd{ color: #808 }
-.com{ color: #800 }
-.typ{ color: #606 }
-.lit{ color: #066 }
-.pun{ color: #660 }
-.pln{ color: #060 }
-.tag{ color: #008 }
-.atn{ color: #606 }
-.atv{ color: #080 }
-.dec{ color: #606 }
-.prettyprint{
- font-family: Fixed, monospace;
- font-size: 95%;
- margin: 4px 8px 4px 2px;
- padding: 4px 6px;
- border: 1px solid #CCC;
- background-color: #f5f5f5;
-}
-.re.prettyprint{
-}
-@media print {
- .str{ color: #060 }
- .kwd{ color: #006; font-weight: bold }
- .com{ color: #600; font-style: italic }
- .typ{ color: #404; font-weight: bold }
- .lit{ color: #044 }
- .pun{ color: #440 }
- .pln{ color: #000 }
- .tag{ color: #006;font-weight: bold }
- .atn{ color: #404 }
- .atv{ color: #060 }
-}
-
diff --git a/o3d/documentation/jsdoc-toolkit-templates/static/prettify.js b/o3d/documentation/jsdoc-toolkit-templates/static/prettify.js
deleted file mode 100644
index 8fc4c93..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/static/prettify.js
+++ /dev/null
@@ -1,23 +0,0 @@
-function H(){var x=navigator&&navigator.userAgent&&/\bMSIE 6\./.test(navigator.userAgent);H=function(){return x};return x}(function(){function x(b){b=b.split(/ /g);var a={};for(var c=b.length;--c>=0;){var d=b[c];if(d)a[d]=null}return a}var y="break continue do else for if return while ",U=y+"auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile ",D=U+"catch class delete false import new operator private protected public this throw true try ",
-I=D+"alignof align_union asm axiom bool concept concept_map const_cast constexpr decltype dynamic_cast explicit export friend inline late_check mutable namespace nullptr reinterpret_cast static_assert static_cast template typeid typename typeof using virtual wchar_t where ",J=D+"boolean byte extends final finally implements import instanceof null native package strictfp super synchronized throws transient ",V=J+"as base by checked decimal delegate descending event fixed foreach from group implicit in interface internal into is lock object out override orderby params readonly ref sbyte sealed stackalloc string select uint ulong unchecked unsafe ushort var ",
-K=D+"debugger eval export function get null set undefined var with Infinity NaN ",L="caller delete die do dump elsif eval exit foreach for goto if import last local my next no our print package redo require sub undef unless until use wantarray while BEGIN END ",M=y+"and as assert class def del elif except exec finally from global import in is lambda nonlocal not or pass print raise try with yield False True None ",N=y+"alias and begin case class def defined elsif end ensure false in module next nil not or redo rescue retry self super then true undef unless until when yield BEGIN END ",
-O=y+"case done elif esac eval fi function in local set then until ",W=I+V+K+L+M+N+O;function X(b){return b>="a"&&b<="z"||b>="A"&&b<="Z"}function u(b,a,c,d){b.unshift(c,d||0);try{a.splice.apply(a,b)}finally{b.splice(0,2)}}var Y=(function(){var b=["!","!=","!==","#","%","%=","&","&&","&&=","&=","(","*","*=","+=",",","-=","->","/","/=",":","::",";","<","<<","<<=","<=","=","==","===",">",">=",">>",">>=",">>>",">>>=","?","@","[","^","^=","^^","^^=","{","|","|=","||","||=","~","break","case","continue",
-"delete","do","else","finally","instanceof","return","throw","try","typeof"],a="(?:(?:(?:^|[^0-9.])\\.{1,3})|(?:(?:^|[^\\+])\\+)|(?:(?:^|[^\\-])-)";for(var c=0;c<b.length;++c){var d=b[c];a+=X(d.charAt(0))?"|\\b"+d:"|"+d.replace(/([^=<>:&])/g,"\\$1")}a+="|^)\\s*$";return new RegExp(a)})(),P=/&/g,Q=/</g,R=/>/g,Z=/\"/g;function $(b){return b.replace(P,"&amp;").replace(Q,"&lt;").replace(R,"&gt;").replace(Z,"&quot;")}function E(b){return b.replace(P,"&amp;").replace(Q,"&lt;").replace(R,"&gt;")}var aa=
-/&lt;/g,ba=/&gt;/g,ca=/&apos;/g,da=/&quot;/g,ea=/&amp;/g,fa=/&nbsp;/g;function ga(b){var a=b.indexOf("&");if(a<0)return b;for(--a;(a=b.indexOf("&#",a+1))>=0;){var c=b.indexOf(";",a);if(c>=0){var d=b.substring(a+3,c),g=10;if(d&&d.charAt(0)==="x"){d=d.substring(1);g=16}var e=parseInt(d,g);if(!isNaN(e))b=b.substring(0,a)+String.fromCharCode(e)+b.substring(c+1)}}return b.replace(aa,"<").replace(ba,">").replace(ca,"'").replace(da,'"').replace(ea,"&").replace(fa," ")}function S(b){return"XMP"===b.tagName}
-function z(b,a){switch(b.nodeType){case 1:var c=b.tagName.toLowerCase();a.push("<",c);for(var d=0;d<b.attributes.length;++d){var g=b.attributes[d];if(!g.specified)continue;a.push(" ");z(g,a)}a.push(">");for(var e=b.firstChild;e;e=e.nextSibling)z(e,a);if(b.firstChild||!/^(?:br|link|img)$/.test(c))a.push("</",c,">");break;case 2:a.push(b.name.toLowerCase(),'="',$(b.value),'"');break;case 3:case 4:a.push(E(b.nodeValue));break}}var F=null;function ha(b){if(null===F){var a=document.createElement("PRE");
-a.appendChild(document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />'));F=!/</.test(a.innerHTML)}if(F){var c=b.innerHTML;if(S(b))c=E(c);return c}var d=[];for(var g=b.firstChild;g;g=g.nextSibling)z(g,d);return d.join("")}function ia(b){var a=0;return function(c){var d=null,g=0;for(var e=0,h=c.length;e<h;++e){var f=c.charAt(e);switch(f){case "\t":if(!d)d=[];d.push(c.substring(g,e));var i=b-a%b;a+=i;for(;i>=0;i-=" ".length)d.push(" ".substring(0,i));g=e+1;break;
-case "\n":a=0;break;default:++a}}if(!d)return c;d.push(c.substring(g));return d.join("")}}var ja=/(?:[^<]+|<!--[\s\S]*?--\>|<!\[CDATA\[([\s\S]*?)\]\]>|<\/?[a-zA-Z][^>]*>|<)/g,ka=/^<!--/,la=/^<\[CDATA\[/,ma=/^<br\b/i;function na(b){var a=b.match(ja),c=[],d=0,g=[];if(a)for(var e=0,h=a.length;e<h;++e){var f=a[e];if(f.length>1&&f.charAt(0)==="<"){if(ka.test(f))continue;if(la.test(f)){c.push(f.substring(9,f.length-3));d+=f.length-12}else if(ma.test(f)){c.push("\n");++d}else g.push(d,f)}else{var i=ga(f);
-c.push(i);d+=i.length}}return{source:c.join(""),tags:g}}function v(b,a){var c={};(function(){var g=b.concat(a);for(var e=g.length;--e>=0;){var h=g[e],f=h[3];if(f)for(var i=f.length;--i>=0;)c[f.charAt(i)]=h}})();var d=a.length;return function(g,e){e=e||0;var h=[e,"pln"],f="",i=0,j=g;while(j.length){var o,m=null,k,l=c[j.charAt(0)];if(l){k=j.match(l[1]);m=k[0];o=l[0]}else{for(var n=0;n<d;++n){l=a[n];var p=l[2];if(p&&!p.test(f))continue;k=j.match(l[1]);if(k){m=k[0];o=l[0];break}}if(!m){o="pln";m=j.substring(0,
-1)}}h.push(e+i,o);i+=m.length;j=j.substring(m.length);if(o!=="com"&&/\S/.test(m))f=m}return h}}var oa=v([],[["pln",/^[^<]+/,null],["dec",/^<!\w[^>]*(?:>|$)/,null],["com",/^<!--[\s\S]*?(?:--\>|$)/,null],["src",/^<\?[\s\S]*?(?:\?>|$)/,null],["src",/^<%[\s\S]*?(?:%>|$)/,null],["src",/^<(script|style|xmp)\b[^>]*>[\s\S]*?<\/\1\b[^>]*>/i,null],["tag",/^<\/?\w[^<>]*>/,null]]);function pa(b){var a=oa(b);for(var c=0;c<a.length;c+=2)if(a[c+1]==="src"){var d,g;d=a[c];g=c+2<a.length?a[c+2]:b.length;var e=b.substring(d,
-g),h=e.match(/^(<[^>]*>)([\s\S]*)(<\/[^>]*>)$/);if(h)a.splice(c,2,d,"tag",d+h[1].length,"src",d+h[1].length+(h[2]||"").length,"tag")}return a}var qa=v([["atv",/^\'[^\']*(?:\'|$)/,null,"'"],["atv",/^\"[^\"]*(?:\"|$)/,null,'"'],["pun",/^[<>\/=]+/,null,"<>/="]],[["tag",/^[\w:\-]+/,/^</],["atv",/^[\w\-]+/,/^=/],["atn",/^[\w:\-]+/,null],["pln",/^\s+/,null," \t\r\n"]]);function ra(b,a){for(var c=0;c<a.length;c+=2){var d=a[c+1];if(d==="tag"){var g,e;g=a[c];e=c+2<a.length?a[c+2]:b.length;var h=b.substring(g,
-e),f=qa(h,g);u(f,a,c,2);c+=f.length-2}}return a}function r(b){var a=[],c=[];if(b.tripleQuotedStrings)a.push(["str",/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""]);else if(b.multiLineStrings)a.push(["str",/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"]);else a.push(["str",/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
-null,"\"'"]);c.push(["pln",/^(?:[^\'\"\`\/\#]+)/,null," \r\n"]);if(b.hashComments)a.push(["com",/^#[^\r\n]*/,null,"#"]);if(b.cStyleComments)c.push(["com",/^\/\/[^\r\n]*/,null]);if(b.regexLiterals)c.push(["str",/^\/(?:[^\\\*\/\[]|\\[\s\S]|\[(?:[^\]\\]|\\.)*(?:\]|$))+(?:\/|$)/,Y]);if(b.cStyleComments)c.push(["com",/^\/\*[\s\S]*?(?:\*\/|$)/,null]);var d=x(b.keywords);b=null;var g=v(a,c),e=v([],[["pln",/^\s+/,null," \r\n"],["pln",/^[a-z_$@][a-z_$@0-9]*/i,null],["lit",/^0x[a-f0-9]+[a-z]/i,null],["lit",
-/^(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d+)(?:e[+\-]?\d+)?[a-z]*/i,null,"123456789"],["pun",/^[^\s\w\.$@]+/,null]]);function h(f,i){for(var j=0;j<i.length;j+=2){var o=i[j+1];if(o==="pln"){var m,k,l,n;m=i[j];k=j+2<i.length?i[j+2]:f.length;l=f.substring(m,k);n=e(l,m);for(var p=0,t=n.length;p<t;p+=2){var w=n[p+1];if(w==="pln"){var A=n[p],B=p+2<t?n[p+2]:l.length,s=f.substring(A,B);if(s===".")n[p+1]="pun";else if(s in d)n[p+1]="kwd";else if(/^@?[A-Z][A-Z$]*[a-z][A-Za-z$]*$/.test(s))n[p+1]=s.charAt(0)==="@"?"lit":
-"typ"}}u(n,i,j,2);j+=n.length-2}}return i}return function(f){var i=g(f);i=h(f,i);return i}}var G=r({keywords:W,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function sa(b,a){for(var c=0;c<a.length;c+=2){var d=a[c+1];if(d==="src"){var g,e;g=a[c];e=c+2<a.length?a[c+2]:b.length;var h=G(b.substring(g,e));for(var f=0,i=h.length;f<i;f+=2)h[f]+=g;u(h,a,c,2);c+=h.length-2}}return a}function ta(b,a){var c=false;for(var d=0;d<a.length;d+=2){var g=a[d+1],e,h;if(g==="atn"){e=
-a[d];h=d+2<a.length?a[d+2]:b.length;c=/^on|^style$/i.test(b.substring(e,h))}else if(g==="atv"){if(c){e=a[d];h=d+2<a.length?a[d+2]:b.length;var f=b.substring(e,h),i=f.length,j=i>=2&&/^[\"\']/.test(f)&&f.charAt(0)===f.charAt(i-1),o,m,k;if(j){m=e+1;k=h-1;o=f}else{m=e+1;k=h-1;o=f.substring(1,f.length-1)}var l=G(o);for(var n=0,p=l.length;n<p;n+=2)l[n]+=m;if(j){l.push(k,"atv");u(l,a,d+2,0)}else u(l,a,d,2)}c=false}}return a}function ua(b){var a=pa(b);a=ra(b,a);a=sa(b,a);a=ta(b,a);return a}function va(b,
-a,c){var d=[],g=0,e=null,h=null,f=0,i=0,j=ia(8);function o(k){if(k>g){if(e&&e!==h){d.push("</span>");e=null}if(!e&&h){e=h;d.push('<span class="',e,'">')}var l=E(j(b.substring(g,k))).replace(/(\r\n?|\n| ) /g,"$1&nbsp;").replace(/\r\n?|\n/g,"<br />");d.push(l);g=k}}while(true){var m;m=f<a.length?(i<c.length?a[f]<=c[i]:true):false;if(m){o(a[f]);if(e){d.push("</span>");e=null}d.push(a[f+1]);f+=2}else if(i<c.length){o(c[i]);h=c[i+1];i+=2}else break}o(b.length);if(e)d.push("</span>");return d.join("")}
-var C={};function q(b,a){for(var c=a.length;--c>=0;){var d=a[c];if(!C.hasOwnProperty(d))C[d]=b;else if("console"in window)console.log("cannot override language handler %s",d)}}q(G,["default-code"]);q(ua,["default-markup","html","htm","xhtml","xml","xsl"]);q(r({keywords:I,hashComments:true,cStyleComments:true}),["c","cc","cpp","cs","cxx","cyc"]);q(r({keywords:J,cStyleComments:true}),["java"]);q(r({keywords:O,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);q(r({keywords:M,hashComments:true,
-multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);q(r({keywords:L,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);q(r({keywords:N,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);q(r({keywords:K,cStyleComments:true,regexLiterals:true}),["js"]);function T(b,a){try{var c=na(b),d=c.source,g=c.tags;if(!C.hasOwnProperty(a))a=/^\s*</.test(d)?"default-markup":"default-code";var e=C[a].call({},d);return va(d,g,e)}catch(h){if("console"in window){console.log(h);
-console.trace()}return b}}function wa(b){var a=H(),c=[document.getElementsByTagName("pre"),document.getElementsByTagName("code"),document.getElementsByTagName("xmp")],d=[];for(var g=0;g<c.length;++g)for(var e=0;e<c[g].length;++e)d.push(c[g][e]);c=null;var h=0;function f(){var i=(new Date).getTime()+250;for(;h<d.length&&(new Date).getTime()<i;h++){var j=d[h];if(j.className&&j.className.indexOf("prettyprint")>=0){var o=j.className.match(/\blang-(\w+)\b/);if(o)o=o[1];var m=false;for(var k=j.parentNode;k;k=
-k.parentNode)if((k.tagName==="pre"||k.tagName==="code"||k.tagName==="xmp")&&k.className&&k.className.indexOf("prettyprint")>=0){m=true;break}if(!m){var l=ha(j);l=l.replace(/(?:\r\n?|\n)$/,"");var n=T(l,o);if(!S(j))j.innerHTML=n;else{var p=document.createElement("PRE");for(var t=0;t<j.attributes.length;++t){var w=j.attributes[t];if(w.specified)p.setAttribute(w.name,w.value)}p.innerHTML=n;j.parentNode.replaceChild(p,j);p=j}if(a&&j.tagName==="PRE"){var A=j.getElementsByTagName("br");for(var B=A.length;--B>=
-0;){var s=A[B];s.parentNode.replaceChild(document.createTextNode("\r\n"),s)}}}}}if(h<d.length)setTimeout(f,250);else if(b)b()}f()}window.PR_normalizedHtml=z;window.prettyPrintOne=T;window.prettyPrint=wa;window.PR={createSimpleLexer:v,registerLangHandler:q,sourceDecorator:r,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ"}})();
diff --git a/o3d/documentation/jsdoc-toolkit-templates/static/stylesheet.css b/o3d/documentation/jsdoc-toolkit-templates/static/stylesheet.css
deleted file mode 100644
index 9ed8e38..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/static/stylesheet.css
+++ /dev/null
@@ -1,246 +0,0 @@
-/*
- * Based off the Doxygen generated template stylesheet and trimmed/edited to
- * remove items that would conflict with codesite or other overlying
- * stylesheets while maintaining the desired look and feel.
- *
- * The #doxygen-ref is an id tag which encompasses code generated by doxygen
- * and allows override of standard html tags while not affecting the rest
- * of the page such as sidebars.
- */
-
-A.qindex {
- text-decoration: none;
- font-weight: bold;
- color: #1A419D;
-}
-A.qindex:visited {
- text-decoration: none;
- font-weight: bold;
- color: #1A419D
-}
-A.qindex:hover {
- text-decoration: none;
- background-color: #ddf;
-}
-A.qindexHL {
- text-decoration: none;
- font-weight: bold;
- background-color: #66c;
- color: #fff;
- border: 1px double #9295C2;
-}
-A.qindexHL:hover,
-A.qindexHL:visited {
- text-decoration: none;
- background-color: #66c;
- color: #fff;
-}
-A.el {
- text-decoration: none;
- font-weight: bold;
-}
-A.elRef {
- font-weight: bold;
-}
-A.code:link,
-A.code:visited {
- text-decoration: none;
- font-weight: normal;
- color: #00F;
-}
-A.codeRef:link,
-A.codeRef:visited {
- font-weight: normal;
- color: #00F;
-}
-A:hover {
- text-decoration: none;
- background-color: #f2f2ff;
-}
-DL.el {
- margin-left: -1cm;
-}
-.fragment {
- font-family: Fixed, monospace;
- font-size: 95%;
-}
-PRE.fragment {
- border: 1px solid #CCC;
- background-color: #f5f5f5;
- margin: 4px 8px 4px 2px
- padding: 4px 6px;
-}
-DIV.ah {
- background-color: black;
- font-weight: bold;
- color: #fff;
- margin-bottom: 3px;
- margin-top: 3px
-}
-TD.md {
- background-color: #e1e1e4;
- font-weight: bold;
- border: none;
-}
-TD.mdPrefix {
- background-color: #e1e1e4;
- color: #606060;
- font-size: 80%;
- border: none;
-}
-TD.mdname1 {
- background-color: #e1e1e4;
- font-weight: bold;
- color: #602020;
- border: none;
-}
-.memitem {
- padding: 4px;
- background-color: #ffff;
-}
-.memname {
- background-color: #e1e1e4;
- white-space: nowrap;
- font-weight: bold;
-}
-.memdoc{
- padding-left: 10px;
-}
-#doxygen-ref div.memproto td {
- background-color: #e1e1e4;
-}
-.memproto {
- background-color: #e1e1e4;
- width: 100%;
- border-width: 1px;
- border-style: solid;
- border-color: #e1e1f4;
- font-weight: bold;
- -moz-border-radius: 8px 8px 8px 8px;
-}
-.memproto .deprecated,
-.memname .deprecated,
-.summary .deprecated {
- color: red;
-}
-.paramkey {
- text-align: right;
-}
-.paramtype {
- white-space: nowrap;
-}
-.paramname {
- color: #602020;
- font-style: italic;
- white-space: nowrap;
-}
-DIV.groupHeader {
- margin: 12px 16px 6px auto;
- font-weight: bold;
-}
-DIV.groupText {
- margin-left: 16px;
- font-style: italic;
- font-size: 90%;
-}
-TR.memlist {
- background-color: #f0f0f0;
-}
-P.formulaDsp {
- text-align: center;
-}
-IMG.formulaInl {
- vertical-align: middle;
-}
-SPAN.keyword,
-SPAN.keywordflow {
- color: #008000;
-}
-SPAN.keywordtyp {
- color: #604020;
-}
-SPAN.comment {
- color: #800000;
-}
-SPAN.preprocessor {
- color: #806020;
-}
-SPAN.stringliteral {
- color: #002080;
-}
-SPAN.charliteral {
- color: #008080;
-}
-.mdTable {
- background-color: #e1e1e4;
- border: none;
- padding: 0;
-}
-.mdRow {
- padding: 8px 10px;
- border: none;
-}
-.mdescLeft,
-.mdescRight {
- padding: 0 8px 4px 8px;
- font-size: 80%;
- font-style: italic;
- background-color: #FAFAFA;
- border: 1px none #E0E0E0;
- margin: 0;
-}
-.search {
- color: #039;
- font-weight: bold;
-}
-FORM.search {
- margin: 0 auto;
-}
-INPUT.search {
- font-size: 75%;
- color: #000080;
- font-weight: normal;
- background-color: #e8eef2;
-}
-TD.tiny{
- font-size: 75%;
-}
-#doxygen-ref HR {
- height: 1px;
- border: none;
- border-top: 1px solid black;
-}
-#doxygen-ref table,
-#doxygen-ref td,
-#doxygen-ref tr {
- border:none;
-}
-#doxygen-ref .contents H1 {
- text-align: center;
- background-color: #ffffff;
- border: 0;
-}
-#doxygen-ref H2 {
- margin-left: 0;
- margin-bottom: 5px;
-}
-#doxygen-ref CAPTION {
- font-weight: bold;
-}
-#doxygen-ref .contents .summary {
- line-height: 1em;
-}
-#doxygen-ref .contents .summary TD {
-}
-#doxygen-ref .contents .summary .type {
- text-align: right;
-}
-.memdoc {
- padding-left: 30px;
-}
-.memitem {
- border-top:1px solid #E5ECF9;
-}
-.doxygen-global {
- background-color: #ffcc66;
-} \ No newline at end of file
diff --git a/o3d/documentation/jsdoc-toolkit-templates/static/tab_b.gif b/o3d/documentation/jsdoc-toolkit-templates/static/tab_b.gif
deleted file mode 100644
index 0d62348..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/static/tab_b.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/documentation/jsdoc-toolkit-templates/static/tab_l.gif b/o3d/documentation/jsdoc-toolkit-templates/static/tab_l.gif
deleted file mode 100644
index 9b1e633..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/static/tab_l.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/documentation/jsdoc-toolkit-templates/static/tab_r.gif b/o3d/documentation/jsdoc-toolkit-templates/static/tab_r.gif
deleted file mode 100644
index ce9dd9f..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/static/tab_r.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/documentation/jsdoc-toolkit-templates/static/tabs.css b/o3d/documentation/jsdoc-toolkit-templates/static/tabs.css
deleted file mode 100644
index 16b1be0..0000000
--- a/o3d/documentation/jsdoc-toolkit-templates/static/tabs.css
+++ /dev/null
@@ -1,102 +0,0 @@
-/* tabs styles, based on http://www.alistapart.com/articles/slidingdoors */
-
-DIV.tabs
-{
- float : left;
- width : 100%;
- background : url("tab_b.gif") repeat-x bottom;
- margin-bottom : 4px;
-}
-
-DIV.tabs UL
-{
- margin : 0px;
- padding-left : 10px;
- list-style : none;
-}
-
-DIV.tabs LI, DIV.tabs FORM
-{
- display : inline;
- margin : 0px;
- padding : 0px;
-}
-
-DIV.tabs FORM
-{
- float : right;
-}
-
-DIV.tabs A
-{
- float : left;
- background : url("tab_r.gif") no-repeat right top;
- border-bottom : 1px solid #84B0C7;
- font-size : 8px;
- font-weight : bold;
- text-decoration : none;
-}
-
-DIV.tabs A:hover
-{
- background-position: 100% -150px;
-}
-
-DIV.tabs A:link, DIV.tabs A:visited,
-DIV.tabs A:active, DIV.tabs A:hover
-{
- color: #1A419D;
-}
-
-DIV.tabs SPAN
-{
- float : left;
- display : block;
- background : url("tab_l.gif") no-repeat left top;
- padding : 5px 9px;
- white-space : nowrap;
-}
-
-DIV.tabs INPUT
-{
- float : right;
- display : inline;
- font-size : 1em;
-}
-
-DIV.tabs TD
-{
- font-size : 8px;
- font-weight : bold;
- text-decoration : none;
-}
-
-
-
-/* Commented Backslash Hack hides rule from IE5-Mac \*/
-DIV.tabs SPAN {float : none;}
-/* End IE5-Mac hack */
-
-DIV.tabs A:hover SPAN
-{
- background-position: 0% -150px;
-}
-
-DIV.tabs LI.current A
-{
- background-position: 100% -150px;
- border-width : 0px;
-}
-
-DIV.tabs LI.current SPAN
-{
- background-position: 0% -150px;
- padding-bottom : 6px;
-}
-
-DIV.navpath
-{
- background : none;
- border : none;
- border-bottom : 1px solid #84B0C7;
-}
diff --git a/o3d/google_update/google_update.gyp b/o3d/google_update/google_update.gyp
deleted file mode 100644
index dc814c3..0000000
--- a/o3d/google_update/google_update.gyp
+++ /dev/null
@@ -1,32 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- },
- 'includes': [
- '../build/common.gypi',
- ],
- 'targets': [
- {
- 'target_name': 'getextras',
- 'type': 'executable',
- 'include_dirs': [
- '..',
- '<(INTERMEDIATE_DIR)',
- ],
- 'sources': [
- 'google_update_idl.idl',
- 'performondemand.cc',
- ],
- },
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/google_update/google_update_idl.idl b/o3d/google_update/google_update_idl.idl
deleted file mode 100644
index 4b8f499..0000000
--- a/o3d/google_update/google_update_idl.idl
+++ /dev/null
@@ -1,243 +0,0 @@
-// Copyright 2007-2009 Google Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-// ========================================================================
-//
-// The proxy clsid #defined as PROXY_CLSID_IS in mk_common needs to be changed
-// anytime any interface below changes, or if a new interface is added.
-
-import "oaidl.idl";
-import "ocidl.idl";
-
-[
- object,
- uuid(5B25A8DC-1780-4178-A629-6BE8B8DEFAA2),
- oleautomation,
- nonextensible,
- pointer_default(unique)
-]
-interface IBrowserHttpRequest2 : IUnknown {
- // This method will send request/data from the browser process.
- // @param url URL where request will be send.
- // @param post_data POST data, if any. Can be NULL.
- // @param request_headers HTTP request headers, if any. Can be NULL.
- // @param response_headers_needed HTTP response headers that are needed.
- // Should be one of the values listed here:
- // http://go/queryinfoflags
- // The input is a SAFEARRAY of DWORD. Can be a
- // VT_EMPTY.
- // @param response_headers HTTP response headers, returned as SAFEARRAY
- // of BSTR. The values corresponding one-to-one
- // with the response_headers_needed values. Can
- // be NULL if response_headers_needed==VT_EMPTY
- // @param response_code HTTP response code.
- // @param cache_filename Cache file that contains the response data.
- HRESULT Send([in] BSTR url,
- [in] BSTR post_data,
- [in] BSTR request_headers,
- [in] VARIANT response_headers_needed,
- [out] VARIANT* response_headers,
- [out] DWORD* response_code,
- [out] BSTR* cache_filename);
-};
-
-[
- object,
- oleautomation,
- uuid(128C2DA6-2BC0-44c0-B3F6-4EC22E647964),
- helpstring("Google Update IProcessLauncher Interface"),
- pointer_default(unique)
-]
-interface IProcessLauncher : IUnknown {
- // @param cmd_line The full command line to execute.
- HRESULT LaunchCmdLine([in, string] const WCHAR* cmd_line);
-
- // @param browser_type The browser to start.
- // @param url The url to launch the browser with.
- HRESULT LaunchBrowser([in] DWORD browser_type,
- [in, string] const WCHAR* url);
-
- // @param app_id Unique id to identify the calling client application
- // @param event_id Unique id for the command
- // @param caller_proc_id The process id of the calling process
- // @param proc_handle The process handle valid in the caller's context
- HRESULT LaunchCmdElevated([in, string] const WCHAR* app_guid,
- [in, string] const WCHAR* cmd_id,
- [in] DWORD caller_proc_id,
- [out] ULONG_PTR* proc_handle);
-};
-
-typedef enum {
- COMPLETION_CODE_SUCCESS = 1,
- COMPLETION_CODE_SUCCESS_CLOSE_UI,
- COMPLETION_CODE_ERROR,
- COMPLETION_CODE_RESTART_ALL_BROWSERS,
- COMPLETION_CODE_REBOOT,
- COMPLETION_CODE_RESTART_BROWSER,
- COMPLETION_CODE_RESTART_ALL_BROWSERS_NOTICE_ONLY,
- COMPLETION_CODE_REBOOT_NOTICE_ONLY,
- COMPLETION_CODE_RESTART_BROWSER_NOTICE_ONLY,
- COMPLETION_CODE_RUN_COMMAND,
-} CompletionCodes;
-
-[
- object,
- oleautomation,
- uuid(1C642CED-CA3B-4013-A9DF-CA6CE5FF6503),
- helpstring("GoogleUpdate UI-specific events Interface"),
- pointer_default(unique)
-]
-interface IProgressWndEvents : IUnknown {
- // The UI is closing down. The user has clicked on either the "X" or the
- // other buttons of the UI to close the window.
- HRESULT DoClose();
-
- // Pause has been clicked on.
- HRESULT DoPause();
-
- // Resume has been clicked on.
- HRESULT DoResume();
-
- // RestartBrowsers button has been clicked on.
- HRESULT DoRestartBrowsers();
-
- // Reboot button has been clicked on.
- HRESULT DoReboot();
-
- // Launch Browser.
- HRESULT DoLaunchBrowser([in, string] const WCHAR* url);
-};
-
-
-[
- object,
- oleautomation,
- uuid(49D7563B-2DDB-4831-88C8-768A53833837),
- helpstring("IJobObserver Interface"),
- pointer_default(unique)
-]
-interface IJobObserver : IUnknown {
- HRESULT OnShow();
- HRESULT OnCheckingForUpdate();
- HRESULT OnUpdateAvailable([in, string] const WCHAR* version_string);
- HRESULT OnWaitingToDownload();
- HRESULT OnDownloading([in] int time_remaining_ms, [in] int pos);
- HRESULT OnWaitingToInstall();
- HRESULT OnInstalling();
- HRESULT OnPause();
- HRESULT OnComplete([in] CompletionCodes code,
- [in, string] const WCHAR* reserved);
- HRESULT SetEventSink([in] IProgressWndEvents* ui_sink);
-};
-
-// TODO: Component story.
-// TODO: Should CheckForUpdate be synchronous? We can avoid the
-// observer. However, it may block the UI.
-// TODO: On-Demand Installs.
-[
- object,
- oleautomation,
- uuid(31AC3F11-E5EA-4a85-8A3D-8E095A39C27B),
- helpstring("IGoogleUpdate Interface"),
- pointer_default(unique)
-]
-interface IGoogleUpdate : IUnknown {
- // @param guid The guid for the app to be updated.
- // @param observer The eventing interface.
- HRESULT CheckForUpdate([in, string] const WCHAR* guid,
- [in] IJobObserver* observer);
-
- // @param guid The guid for the app to be updated.
- // @param observer The eventing interface.
- HRESULT Update([in, string] const WCHAR* guid,
- [in] IJobObserver* observer);
-};
-
-// IGoogleUpdateCore is an internal Omaha interface.
-[
- object,
- oleautomation,
- uuid(909489C2-85A6-4322-AA56-D25278649D67),
- helpstring("Google Update Core Interface"),
- pointer_default(unique)
-]
-interface IGoogleUpdateCore : IUnknown
-{
- // Runs a command elevated.
- //
- // @param app_id Unique id to identify the calling client application
- // @param event_id Unique id for the command
- // @param caller_proc_id The process id of the calling process
- // @param proc_handle The process handle valid in the caller's context
- HRESULT LaunchCmdElevated([in, string] const WCHAR* app_guid,
- [in, string] const WCHAR* cmd_id,
- [in] DWORD caller_proc_id,
- [out] ULONG_PTR* proc_handle);
-};
-
-[
- uuid(7E6CD20B-8688-4960-96D9-B979471577B8),
- version(1.0),
- helpstring("Google Update Type Library")
-]
-library GoogleUpdateLib {
- importlib("stdole2.tlb");
- [
- uuid(ABC01078-F197-4b0b-ADBC-CFE684B39C82),
- helpstring("ProcessLauncherClass Class")
- ]
- coclass ProcessLauncherClass {
- [default] interface IProcessLauncher;
- }
-
- // This coclass declaration exists only for the purpose of forcing
- // ::RegisterTypeLib() to register the interfaces within. This is
- // required so that we can marshal/unmarshal the interfaces using the TypeLib
- // marshaler.
- [
- uuid(9564861C-3469-4c9a-956A-74D5690790E6),
- helpstring("InterfaceRegistrar Class")
- ]
- coclass InterfaceRegistrar {
- [default] interface IBrowserHttpRequest2;
- interface IJobObserver;
- interface IProgressWndEvents;
- }
-
- [
- uuid(2F0E2680-9FF5-43c0-B76E-114A56E93598),
- helpstring("OnDemand updates for per-user applications.")
- ]
- coclass OnDemandUserAppsClass {
- [default] interface IGoogleUpdate;
- }
-
- [
- uuid(6F8BD55B-E83D-4a47-85BE-81FFA8057A69),
- helpstring("OnDemand updates for per-machine applications.")
- ]
- coclass OnDemandMachineAppsClass {
- [default] interface IGoogleUpdate;
- }
-
- [
- uuid(E225E692-4B47-4777-9BED-4FD7FE257F0E),
- helpstring("GoogleUpdateCore Class")
- ]
- coclass GoogleUpdateCoreClass
- {
- [default] interface IGoogleUpdateCore;
- }
-
-};
-
diff --git a/o3d/google_update/performondemand.cc b/o3d/google_update/performondemand.cc
deleted file mode 100644
index 0b7977c..0000000
--- a/o3d/google_update/performondemand.cc
+++ /dev/null
@@ -1,546 +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.
- */
-
-// A simple tool for performing and interacting with on demand updates.
-
-#include "google_update/performondemand.h"
-#include <windows.h>
-#include <sddl.h>
-#include <shlobj.h>
-#include <atltime.h>
-#include <tchar.h>
-
-namespace o3d {
-
-namespace google_update {
-
-// Helper function to convert string to GUID
-GUID StringToGuid(const CString& str) {
- GUID guid(GUID_NULL);
- if (!str.IsEmpty()) {
- TCHAR* s = const_cast<TCHAR*>(str.GetString());
- if (NO_ERROR != ::CLSIDFromString(s, &guid)) {
- // Docs don't guarantee that the guid's unmodified on failure.
- guid = GUID_NULL;
- }
- }
- return guid;
-}
-
-#define arraysize(x) (sizeof(x) / sizeof(x[0]))
-
-CString GuidToString(const GUID& guid) {
- TCHAR guid_str[40] = {0};
- ::StringFromGUID2(guid, guid_str, arraysize(guid_str));
- ::CharUpperBuff(guid_str, arraysize(guid_str));
- return guid_str;
-}
-
-HRESULT GetRegKeyValue(HKEY hkey_parent, const TCHAR *key_name,
- const TCHAR * value_name, TCHAR * * value) {
- HKEY hkey;
- LONG res = ::RegOpenKeyEx(hkey_parent, key_name, 0, KEY_READ, &hkey);
- HRESULT hr = HRESULT_FROM_WIN32(res);
-
- if (hr != S_OK) {
- return hr;
- }
-
- DWORD byte_count = 0;
- DWORD type = 0;
-
- // first get the size of the string buffer
- res = ::SHQueryValueEx(hkey, value_name, NULL, &type, NULL, &byte_count);
- hr = HRESULT_FROM_WIN32(res);
-
- if (hr == S_OK) {
- // allocate room for the string and a terminating \0
- *value = new TCHAR[(byte_count / sizeof(TCHAR)) + 1];
-
- if ((*value) != NULL) {
- if (byte_count != 0) {
- // make the call again
- res = ::SHQueryValueEx(hkey, value_name, NULL, &type,
- reinterpret_cast<byte*>(*value), &byte_count);
- hr = HRESULT_FROM_WIN32(res);
- } else {
- (*value)[0] = _T('\0');
- }
-
- if (hr == S_OK && (type != REG_SZ) && (type != REG_MULTI_SZ) &&
- (type != REG_EXPAND_SZ)) {
- hr = E_UNEXPECTED;
- }
- } else {
- hr = E_OUTOFMEMORY;
- }
- }
-
- ::RegCloseKey(hkey);
- return hr;
-}
-
-HRESULT SetRegKeyValue(HKEY hkey_parent, const TCHAR *key_name,
- const TCHAR *value_name, const TCHAR *value, DWORD value_size) {
- HKEY hkey;
- LONG res = ::RegCreateKeyEx(hkey_parent, key_name, 0, 0,
- REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hkey, NULL);
- HRESULT hr = HRESULT_FROM_WIN32(res);
-
- if (hr != S_OK) {
- return hr;
- }
-
- res = ::RegSetValueEx(hkey, value_name, 0, REG_SZ,
- reinterpret_cast<const BYTE *>(value), value_size);
- hr = HRESULT_FROM_WIN32(res);
-
- ::RegCloseKey(hkey);
- return hr;
-}
-
-// Reads the Proxy information for the given interface from HKCU, and registers
-// it with COM.
-HRESULT RegisterHKCUPSClsid(IID iid,
- HMODULE* proxy_module,
- DWORD* revoke_cookie) {
- *proxy_module = NULL;
- *revoke_cookie = 0;
-
- const TCHAR* const hkcu_classes_key = _T("Software\\Classes\\");
-
- // Get the registered proxy for the interface.
- CString interface_proxy_clsid_key;
- interface_proxy_clsid_key.Format(_T("%sInterface\\%s\\ProxyStubClsid32"),
- hkcu_classes_key, GuidToString(iid));
- TCHAR *proxy_clsid32_value;
- HRESULT hr = GetRegKeyValue(HKEY_CURRENT_USER,
- interface_proxy_clsid_key,
- NULL,
- &proxy_clsid32_value);
- if (FAILED(hr)) {
- return hr;
- }
-
- // Get the location of the proxy/stub DLL.
- CString proxy_server32_entry;
- proxy_server32_entry.Format(_T("%sClsid\\%s\\InprocServer32"),
- hkcu_classes_key, proxy_clsid32_value);
- TCHAR *hkcu_proxy_dll_path;
- hr = GetRegKeyValue(HKEY_CURRENT_USER,
- proxy_server32_entry,
- NULL,
- &hkcu_proxy_dll_path);
- if (FAILED(hr)) {
- return hr;
- }
-
- // Get the proxy/stub class object.
- typedef HRESULT (STDAPICALLTYPE *DllGetClassObjectTypedef)(REFCLSID clsid,
- REFIID iid,
- void** ptr);
- *proxy_module = ::LoadLibrary(hkcu_proxy_dll_path);
- DllGetClassObjectTypedef fn = NULL;
-
- fn = reinterpret_cast<DllGetClassObjectTypedef>(
- ::GetProcAddress(*proxy_module, "DllGetClassObject"));
- if (!fn) {
- hr = HRESULT_FROM_WIN32(::GetLastError());
- return hr;
- }
- CComPtr<IPSFactoryBuffer> fb;
- CLSID proxy_clsid = StringToGuid(proxy_clsid32_value);
- hr = (*fn)(proxy_clsid, IID_IPSFactoryBuffer, reinterpret_cast<void**>(&fb));
- if (FAILED(hr)) {
- return hr;
- }
-
- // Register the proxy/stub class object.
- hr = ::CoRegisterClassObject(proxy_clsid, fb, CLSCTX_INPROC_SERVER,
- REGCLS_MULTIPLEUSE, revoke_cookie);
- if (FAILED(hr)) {
- return hr;
- }
-
- // Relate the interface with the proxy/stub, so COM does not do a lookup when
- // unmarshaling the interface.
- hr = ::CoRegisterPSClsid(iid, proxy_clsid);
- if (FAILED(hr)) {
- return hr;
- }
-
- return S_OK;
-}
-
-// Assumes you're running on Vista; call IsRunningOnVista first to check.
-bool IsUserRunningSplitToken() {
- HANDLE process_token;
- if (!::OpenProcessToken(GetCurrentProcess(),
- TOKEN_QUERY,
- &process_token)) {
- return false;
- }
-
- TOKEN_ELEVATION_TYPE elevation_type = TokenElevationTypeDefault;
- DWORD size_returned = 0;
- bool ret = false;
- if (::GetTokenInformation(process_token,
- TokenElevationType,
- &elevation_type,
- sizeof(elevation_type),
- &size_returned)) {
- ret = elevation_type == TokenElevationTypeFull ||
- elevation_type == TokenElevationTypeLimited;
- }
- ::CloseHandle(process_token);
-
- return ret;
-}
-
-// If this function fails to find any of the info it's looking for, it'll
-// default to saying "No, this isn't Vista".
-bool IsRunningOnVista() {
- // Use GetVersionEx to get OS and Service Pack information.
- OSVERSIONINFOEX osviex;
- ::ZeroMemory(&osviex, sizeof(OSVERSIONINFOEX));
- osviex.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
- BOOL success = ::GetVersionEx(reinterpret_cast<OSVERSIONINFO *>(&osviex));
-
- // If ::GetVersionEx fails when given an OSVERSIONINFOEX then we're running
- // on NT4.0SP5 or earlier.
- if (!success) {
- return false;
- } else if (osviex.dwPlatformId == VER_PLATFORM_WIN32_NT &&
- osviex.dwMajorVersion == 6 && osviex.dwMinorVersion == 0) {
- return true;
- }
-
- return false;
-}
-
-// Sets the thread token to medium integrity, which allows for out-of-proc HKCU
-// COM server activation. For more info on process integrity levels, see
-// http://en.wikipedia.org/wiki/Mandatory_Integrity_Control.
-DWORD SetTokenIntegrityLevelMedium(HANDLE token) {
- PSID medium_sid = NULL;
- if (!::ConvertStringSidToSid(SDDL_ML_MEDIUM, &medium_sid)) {
- return ::GetLastError();
- }
-
- TOKEN_MANDATORY_LABEL label = {0};
- label.Label.Attributes = SE_GROUP_INTEGRITY;
- label.Label.Sid = medium_sid;
-
- size_t size = sizeof(TOKEN_MANDATORY_LABEL) + ::GetLengthSid(medium_sid);
- BOOL success = ::SetTokenInformation(token, TokenIntegrityLevel, &label,
- size);
- DWORD result = success ? ERROR_SUCCESS : ::GetLastError();
- ::LocalFree(medium_sid);
- return result;
-}
-
-// A helper class for clients of the Google Update on-demand out-of-proc COM
-// server. An instance of this class is typically created on the stack. The
-// class does nothing for cases where the OS is not Vista with UAC off.
-// This class does the following:
-// * Calls CoInitializeSecurity with cloaking set to dynamic. This makes COM
-// use the thread token instead of the process token.
-// * Impersonates and sets the thread token to medium integrity. This allows for
-// out-of-proc HKCU COM server activation.
-// * Reads and registers per-user proxies for the interfaces that on-demand
-// exposes.
-class VistaProxyRegistrar {
- public:
- VistaProxyRegistrar()
- : googleupdate_cookie_(0),
- jobobserver_cookie_(0),
- progresswndevents_cookie_(0),
- is_impersonated(false),
- failed(false),
- googleupdate_library_(NULL),
- jobobserver_library_(NULL),
- progresswndevents_library_(NULL) {
- HRESULT hr = VistaProxyRegistrarImpl();
- if (FAILED(hr)) {
- failed = true;
- }
- }
-
- ~VistaProxyRegistrar() {
- if (googleupdate_cookie_) {
- if (FAILED((::CoRevokeClassObject(googleupdate_cookie_)))) {
- // TODO: How can we get errors out of the installer?
- // LOG(ERROR("CoRevokeClassObject failed."));
- }
- }
-
- if (jobobserver_cookie_) {
- if (FAILED((::CoRevokeClassObject(jobobserver_cookie_)))) {
- // LOG(ERROR("CoRevokeClassObject failed."));
- }
- }
-
- if (progresswndevents_cookie_) {
- if (FAILED((::CoRevokeClassObject(progresswndevents_cookie_)))) {
- // LOG(ERROR("CoRevokeClassObject failed."));
- }
- }
-
- if (is_impersonated) {
- if (FAILED(::RevertToSelf())) {
- // LOG(ERROR("RevertToSelf failed."));
- }
- }
- ::FreeLibrary(googleupdate_library_);
- ::FreeLibrary(jobobserver_library_);
- ::FreeLibrary(progresswndevents_library_);
- }
-
- private:
- HRESULT VistaProxyRegistrarImpl() {
- if (!IsRunningOnVista() ||
- IsUserRunningSplitToken() ||
- !::IsUserAnAdmin()) {
- return S_OK;
- }
-
- // Needs to be called very early on in a process.
- // Turn on dynamic cloaking so COM picks up the impersonated thread token.
- HRESULT hr = ::CoInitializeSecurity(
- NULL,
- -1,
- NULL,
- NULL,
- RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
- RPC_C_IMP_LEVEL_IDENTIFY,
- NULL,
- EOAC_DYNAMIC_CLOAKING,
- NULL);
- if (FAILED(hr)) {
- return hr;
- }
-
- is_impersonated = !!::ImpersonateSelf(SecurityImpersonation);
- if (!is_impersonated) {
- hr = HRESULT_FROM_WIN32(::GetLastError());
- return hr;
- }
-
- HANDLE thread_token;
- if (!::OpenThreadToken(::GetCurrentThread(),
- TOKEN_ALL_ACCESS,
- false,
- &thread_token)) {
- hr = HRESULT_FROM_WIN32(::GetLastError());
- return hr;
- }
-
- DWORD result = SetTokenIntegrityLevelMedium(thread_token);
- ::CloseHandle(thread_token);
- if (result != ERROR_SUCCESS) {
- return HRESULT_FROM_WIN32(result);
- }
-
- hr = RegisterHKCUPSClsid(__uuidof(IGoogleUpdate),
- &googleupdate_library_,
- &googleupdate_cookie_);
- if (FAILED(hr)) {
- return hr;
- }
-
- hr = RegisterHKCUPSClsid(__uuidof(IJobObserver),
- &jobobserver_library_,
- &jobobserver_cookie_);
- if (FAILED(hr)) {
- return hr;
- }
-
- hr = RegisterHKCUPSClsid(__uuidof(IProgressWndEvents),
- &progresswndevents_library_,
- &progresswndevents_cookie_);
- if (FAILED(hr)) {
- return hr;
- }
-
- return S_OK;
- }
-
- private:
- HMODULE googleupdate_library_;
- HMODULE jobobserver_library_;
- HMODULE progresswndevents_library_;
-
- DWORD googleupdate_cookie_;
- DWORD jobobserver_cookie_;
- DWORD progresswndevents_cookie_;
- bool is_impersonated;
- bool failed;
-};
-
-class scoped_co_init {
- public:
- scoped_co_init() {
- hr_ = ::CoInitializeEx(0, COINIT_APARTMENTTHREADED);
- }
- ~scoped_co_init() {
- if (SUCCEEDED(hr_))
- ::CoUninitialize();
- }
- private:
- HRESULT hr_;
-};
-
-int PerformOnDemandInstall(CString guid) {
- // Verify that the guid is valid.
- GUID parsed = StringToGuid(guid);
- if (parsed == GUID_NULL) {
- return -1;
- }
-
- // Set a fake registry value that tells Google Update that the package is
- // already installed, but with an ancient version that needs updating. This
- // is because Google Update doesn't really support install-on-demand, only
- // update-on-demand.
- // TODO: Check with the google_update team if this does any damage if the
- // software's already installed. If so, we should attempt to determine
- // whether it's installed first--although we should be wary of trusting
- // these registry entries, which might be stale.
- CString key_path(_T("Software\\Google\\Update\\Clients\\"));
- key_path += guid;
- CString value = _T("0.0.0.1");
- HRESULT hr = SetRegKeyValue(HKEY_CURRENT_USER, key_path, _T("pv"),
- value, value.GetLength() * sizeof(TCHAR));
-
- if (FAILED(hr)) {
- return hr;
- }
- int timeout = 60;
- CComModule module;
- scoped_co_init com_apt;
- VistaProxyRegistrar registrar;
-
- CComObject<JobObserver>* job_observer;
- hr = CComObject<JobObserver>::CreateInstance(&job_observer);
- if (!SUCCEEDED(hr)) {
- return -1;
- }
- CComPtr<IJobObserver> job_holder(job_observer);
-
- CComPtr<IGoogleUpdate> on_demand;
- hr = on_demand.CoCreateInstance(__uuidof(OnDemandUserAppsClass));
-
- if (!SUCCEEDED(hr)) {
- return -1;
- }
-
- hr = on_demand->Update(guid, job_observer);
-
- if (!SUCCEEDED(hr)) {
- return -1;
- }
-
- // Main message loop:
- MSG msg;
- SYSTEMTIME start_system_time = {0};
- SYSTEMTIME current_system_time = {0};
- ::GetSystemTime(&start_system_time);
- CTime start_time(start_system_time);
- CTimeSpan timeout_period(0, 0, 0, timeout);
-
- while (::GetMessage(&msg, NULL, 0, 0))
- {
- ::TranslateMessage(&msg);
- ::DispatchMessage(&msg);
- ::GetSystemTime(&current_system_time);
- CTime current_time(current_system_time);
- CTimeSpan elapsed_time = current_time - start_time;
- if (timeout_period < elapsed_time) {
- // TODO: Right now the timeout does correctly break, but then
- // the COM interactions continue on to completion.
- break;
- }
- }
- int ret_val = job_observer->observed;
-
- if (!ret_val) {
- return -1; // This really shouldn't happen, but just in case...
- }
-
- if (ret_val & (JobObserver::ON_COMPLETE_SUCCESS |
- JobObserver::ON_COMPLETE_SUCCESS_CLOSE_UI)) {
- return 0; // The success case.
- }
-
- return ret_val; // Otherwise tell what happened. Never sets all bits (-1).
-}
-
-int GetD3DX9() {
- return PerformOnDemandInstall("{34B2805D-C72C-4f81-AED5-5A22D1E092F1}");
-}
-
-} // namespace google_update
-
-} // namespace o3d
-
-// Arguments expected:
-// [0]: Our binary's name, as usual
-// [1]: The process ID of the Google Update process, in hex; we'll wait for it
-// to exit before doing our stuff. If there's no process ID supplied, don't
-// wait.
-int _tmain(int argc, TCHAR* argv[]) {
- if (argc > 2) {
- return -1;
- }
- if (argc == 2) {
- TCHAR *end = NULL;
- DWORD google_update_id = _tcstol(argv[1], &end, 16);
- if (!google_update_id || end == argv[1]) {
- return -1;
- }
-
- HANDLE google_update_handle = OpenProcess(SYNCHRONIZE, false,
- google_update_id);
-
- if (google_update_handle) {
- // 120 minutes is safer than INFINITY, but effectively the same thing.
- DWORD timeout = 120 * 60 * 1000;
- DWORD waitResponse = WaitForSingleObject(google_update_handle, timeout);
-
- if (waitResponse == WAIT_TIMEOUT || waitResponse == WAIT_FAILED) {
- return -1;
- }
- if (waitResponse != WAIT_ABANDONED && waitResponse != WAIT_OBJECT_0) {
- return -1;
- }
- } // Else optimistically assume it already exited.
- }
- return o3d::google_update::GetD3DX9();
-}
diff --git a/o3d/google_update/performondemand.h b/o3d/google_update/performondemand.h
deleted file mode 100644
index 3441940..0000000
--- a/o3d/google_update/performondemand.h
+++ /dev/null
@@ -1,193 +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_GOOGLE_UPDATE_PERFORMONDEMAND_H_
-#define O3D_GOOGLE_UPDATE_PERFORMONDEMAND_H_
-
-#pragma once
-#include <windows.h>
-#include <atlbase.h>
-#include <atlcom.h>
-#include "google_update_idl.h" // NOLINT
-
-class JobObserver
- : public CComObjectRootEx<CComSingleThreadModel>,
- public IJobObserver {
- public:
-
- enum ReturnCodes {
- ON_COMPLETE_SUCCESS = 0x00000001,
- ON_COMPLETE_SUCCESS_CLOSE_UI = 0x00000002,
- ON_COMPLETE_ERROR = 0x00000004,
- ON_COMPLETE_RESTART_ALL_BROWSERS = 0x00000008,
- ON_COMPLETE_REBOOT = 0x00000010,
- ON_SHOW = 0x00000020,
- ON_CHECKING_FOR_UPDATES = 0x00000040,
- ON_UPDATE_AVAILABLE = 0x00000080,
- ON_WAITING_TO_DOWNLOAD = 0x00000100,
- ON_DOWNLOADING = 0x00000200,
- ON_WAITING_TO_INSTALL = 0x00000400,
- ON_INSTALLING = 0x00000800,
- ON_PAUSE = 0x00001000,
- SET_EVENT_SINK = 0x00002000,
- ON_COMPLETE_RESTART_BROWSER = 0x00004000,
- ON_COMPLETE_RESTART_ALL_BROWSERS_NOTICE_ONLY = 0x00008000,
- ON_COMPLETE_REBOOT_NOTICE_ONLY = 0x00010000,
- ON_COMPLETE_RESTART_BROWSER_NOTICE_ONLY = 0x00020000,
- ON_COMPLETE_RUN_COMMAND = 0x00040000,
- };
-
- BEGIN_COM_MAP(JobObserver)
- COM_INTERFACE_ENTRY(IJobObserver)
- END_COM_MAP()
-
- // Each interaction enables a bit in observed, which is eventually returned as
- // a return code.
- int observed;
-
- // Similar to observed, misbehave_modes_ and close_modes_ take on bits from
- // the list of all events. For example, if close_modes_ | ON_DOWNLOADING
- // is true, then when ON_DOWNLOADING is called, DoClose will be called.
- int misbehave_modes_;
- int close_modes_;
- bool do_closed_called;
-
- JobObserver()
- : observed(0), misbehave_modes_(0), close_modes_(0),
- do_closed_called(false) {
- }
- virtual ~JobObserver() {
- }
-
- void Reset() {
- observed = 0;
- misbehave_modes_ = 0;
- close_modes_ = 0;
- do_closed_called = false;
- }
-
- void AddMisbehaveMode(int event_code) {
- misbehave_modes_ |= event_code;
- }
-
- void AddCloseMode(int event_code) {
- close_modes_ |= event_code;
- }
-
- HRESULT HandleEvent(int event_code) {
- observed |= event_code;
-
- if ((event_code & close_modes_) && !do_closed_called) {
- do_closed_called = true;
- event_sink_->DoClose();
- }
-
- if (event_code & misbehave_modes_) {
- return E_FAIL;
- } else {
- return S_OK;
- }
- }
-
- // JobObserver implementation.
- STDMETHOD(OnShow)() {
- return HandleEvent(ON_SHOW);
- }
- STDMETHOD(OnCheckingForUpdate)() {
- return HandleEvent(ON_CHECKING_FOR_UPDATES);
- }
- STDMETHOD(OnUpdateAvailable)(const TCHAR* version_string) {
- return HandleEvent(ON_UPDATE_AVAILABLE);
- }
- STDMETHOD(OnWaitingToDownload)() {
- return HandleEvent(ON_WAITING_TO_INSTALL);
- }
- STDMETHOD(OnDownloading)(int time_remaining_ms, int pos) {
- return HandleEvent(ON_DOWNLOADING);
- }
- STDMETHOD(OnWaitingToInstall)() {
- return HandleEvent(ON_WAITING_TO_INSTALL);
- }
- STDMETHOD(OnInstalling)() {
- return HandleEvent(ON_INSTALLING);
- }
- STDMETHOD(OnPause)() {
- return HandleEvent(ON_PAUSE);
- }
- STDMETHOD(OnComplete)(CompletionCodes code, const TCHAR* text) {
- int event_code = 0;
- switch (code) {
- case COMPLETION_CODE_SUCCESS:
- event_code |= ON_COMPLETE_SUCCESS;
- break;
- case COMPLETION_CODE_SUCCESS_CLOSE_UI:
- event_code |= ON_COMPLETE_SUCCESS_CLOSE_UI;
- break;
- case COMPLETION_CODE_ERROR:
- event_code |= ON_COMPLETE_ERROR;
- break;
- case COMPLETION_CODE_RESTART_ALL_BROWSERS:
- event_code |= ON_COMPLETE_RESTART_ALL_BROWSERS;
- break;
- case COMPLETION_CODE_REBOOT:
- event_code |= ON_COMPLETE_REBOOT;
- break;
- case COMPLETION_CODE_RESTART_BROWSER:
- event_code |= ON_COMPLETE_RESTART_BROWSER;
- break;
- case COMPLETION_CODE_RESTART_ALL_BROWSERS_NOTICE_ONLY:
- event_code |= ON_COMPLETE_RESTART_ALL_BROWSERS_NOTICE_ONLY;
- break;
- case COMPLETION_CODE_REBOOT_NOTICE_ONLY:
- event_code |= ON_COMPLETE_REBOOT_NOTICE_ONLY;
- break;
- case COMPLETION_CODE_RESTART_BROWSER_NOTICE_ONLY:
- event_code |= ON_COMPLETE_RESTART_BROWSER_NOTICE_ONLY;
- break;
- case COMPLETION_CODE_RUN_COMMAND:
- event_code |= ON_COMPLETE_RUN_COMMAND;
- break;
- default:
- break;
- }
- ::PostThreadMessage(::GetCurrentThreadId(), WM_QUIT, 0, 0);
- return HandleEvent(event_code);
- }
- STDMETHOD(SetEventSink)(IProgressWndEvents* event_sink) {
- event_sink_ = event_sink;
- return HandleEvent(SET_EVENT_SINK);
- }
-
- CComPtr<IProgressWndEvents> event_sink_;
-};
-
-#endif // O3D_GOOGLE_UPDATE_PERFORMONDEMAND_H_
diff --git a/o3d/gypbuild b/o3d/gypbuild
deleted file mode 100755
index b1b2f3a..0000000
--- a/o3d/gypbuild
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/bin/bash
-# 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.
-
-readonly SCRIPT_DIR="$(dirname "$0")"
-readonly SCRIPT_DIR_ABS="$(cd "$SCRIPT_DIR" ; pwd)"
-
-# Use the batch file as an entry point if on cygwin.
-if [ "$OSTYPE" = "cygwin" ]; then
- "$SCRIPT_DIR_ABS/gypbuild.bat" "$@"
-else
- python "$SCRIPT_DIR_ABS/gypbuild.py" "$@"
-fi
-
diff --git a/o3d/gypbuild.bat b/o3d/gypbuild.bat
deleted file mode 100644
index 8d51bb2..0000000
--- a/o3d/gypbuild.bat
+++ /dev/null
@@ -1,33 +0,0 @@
-@echo off
-REM Copyright 2009, Google Inc.
-REM All rights reserved.
-REM
-REM Redistribution and use in source and binary forms, with or without
-REM modification, are permitted provided that the following conditions are
-REM met:
-REM
-REM * Redistributions of source code must retain the above copyright
-REM notice, this list of conditions and the following disclaimer.
-REM * Redistributions in binary form must reproduce the above
-REM copyright notice, this list of conditions and the following disclaimer
-REM in the documentation and/or other materials provided with the
-REM distribution.
-REM * Neither the name of Google Inc. nor the names of its
-REM contributors may be used to endorse or promote products derived from
-REM this software without specific prior written permission.
-REM
-REM THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-REM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-REM LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-REM A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-REM OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-REM SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-REM LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-REM DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-REM THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-REM (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-REM OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-"%~dp0\..\third_party\python_24\python" -O -OO "%~dp0\gypbuild.py" %*
-
-
diff --git a/o3d/gypbuild.py b/o3d/gypbuild.py
deleted file mode 100755
index 785e187..0000000
--- a/o3d/gypbuild.py
+++ /dev/null
@@ -1,292 +0,0 @@
-#! /usr/bin/env python
-# Copyright 2009 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Builds a particlar platform so the user does not have to know platform
-# specific build commands for every single platform.
-
-# TODO(gman): Add help.
-# TODO(gman): Add cross platform modes like "debug", "opt", "test", "docs"
-# TODO(gman): Add cross platform switches like "-clean" and "-rebuild".
-# TODO(gman): Add cross platform options like "-verbose".
-# TODO(gman): Add cross platform options like "-presubmit", "-selenium",
-# "-unit_tests"
-
-import os
-import os.path
-import sys
-import re
-import subprocess
-import platform
-sys.path.append('build')
-import is_admin
-from optparse import OptionParser
-
-
-class GypBuilder(object):
- """A class to help build gyp projects in a cross platform way"""
-
- class Builder(object):
- """Base Class for building."""
-
- def __init__(self, builder):
- self.builder = builder
-
- def Log(self, *args):
- """Prints something if verbose is true."""
- self.builder.Log(args)
-
- def Execute(self, args):
- """Executes an external program if execute is true."""
- self.builder.Execute(args)
-
- def Dopresubmit(self, targets, options):
- """Builds and runs both the unit tests and selenium."""
- self.Dounit_tests(targets, options)
- self.Doselenium(targets, options)
-
- def Doselenium(self, targets, options):
- """Builds and runs the selenium tests."""
- print "selenium not yet implemented."
-
- def Dounit_tests(self, targets, options):
- """Builds and runs the unit tests."""
- print "unit_tests not yet implemented."
-
- def CleanTargets(self, targets, options):
- """Cleans the targets."""
- print "clean not implemented for this platform."
-
-
- class OSXBuilder(Builder):
- """Class for building on OSX."""
-
- def __init__(self, builder):
- GypBuilder.Builder.__init__(self, builder)
-
- def GetSolutionPath(self):
- """Gets the solution path."""
- return '%s.xcodeproj' % GypBuilder.base_name
-
- def CleanTargets(self, targets, options):
- """Cleans the specifed targets."""
- solution = self.GetSolutionPath()
- self.Execute(['xcodebuild',
- '-project', solution,
- 'clean'])
-
- def Dobuild(self, targets, options):
- """Builds the specifed targets."""
- solution = self.GetSolutionPath()
- self.Execute(['xcodebuild',
- '-project', solution])
-
- class WinBuilder(Builder):
- """Class for building on Windows."""
-
- def __init__(self, builder):
- GypBuilder.Builder.__init__(self, builder)
-
- def GetSolutionPath(self):
- """Gets the solution path."""
- return os.path.abspath('%s.sln' % GypBuilder.base_name)
-
- def CheckVisualStudioVersionVsSolution(self, solution):
- """Checks the solution matches the cl version."""
- f = open(solution, "r")
- line = f.readline()
- f.close()
- m = re.search(r'Format Version (\d+)\.', line)
- if m:
- solution_version = int(m.group(1))
- else:
- print "FAILURE: Unknown solution version in %s" % solution
- sys.exit(1)
-
- output = subprocess.Popen(['cl.exe'],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE).communicate()[1]
- m = re.search(r'Compiler Version (\d+)\.', output)
- if m:
- compiler_version = int(m.group(1))
- else:
- print "FAILURE: Unknown cl.exe version."
- sys.exit(1)
-
- # Compiler Solution
- # Visual Studio .NET 2005 14 9
- # Visual Studio .NET 2008 15 10
- # Visual Studio .NET 2010 ?? ??
- if (compiler_version - 14) > (solution_version - 9):
- vs_map = {
- 14: '2005',
- 15: '2008',
- 16: '2010',
- }
- sln_map = {
- 9: '2005',
- 10: '2008',
- 11: '2010',
- }
- vs_version = vs_map[compiler_version]
- print ("ERROR: solution (%s) version does not match "
- "Visual Studio version (%s)" %
- (sln_map[solution_version], vs_version))
- print "You should 'set GYP_MSVS_VERSION=auto'"
- print "and run 'gclient runhooks --force'"
- sys.exit(1)
-
- def CleanTargets(self, targets, options):
- """Cleans the targets."""
- solution = self.GetSolutionPath()
- self.Execute(['devenv.com',
- solution,
- '/clean',
- options.version])
-
- def Dobuild(self, targets, options):
- """Builds the specifed targets."""
- solution = self.GetSolutionPath()
- if not is_admin.IsAdmin():
- print ("WARNING: selenium_ie will not run unless you run as admin "
- "or turn off UAC.\nAfter switching to admin run "
- "'gclient runhooks --force'")
- self.CheckVisualStudioVersionVsSolution(solution)
- self.Execute(['devenv.com',
- solution,
- '/build',
- options.version])
- # TODO(gman): Should I check for devenv and if it does not exist
- # use msbuild? Msbuild is significantly slower than devenv.
- #self.Execute(['msbuild',
- # solution,
- # '/p:Configuration=%s' % options.version])
-
- class LinuxBuilder(Builder):
- """Class for building on Linux."""
-
- def __init__(self, builder):
- GypBuilder.Builder.__init__(self, builder)
-
- def GetSolutionPath(self):
- """Gets the solution path."""
- return '%s.Makefile' % GypBuilder.base_name
-
- def CleanTargets(self, targets, options):
- """Cleans the targets."""
- print "clean not implemented for this platform."
-
- def Dobuild(self, targets, options):
- """Builds the specifed targets."""
- solution = self.GetSolutionPath()
- self.Execute(['make', '-f', solution])
-
- # Use "o3d" for chrome only build?
- base_name = "o3d_all"
-
- def __init__(self, args):
- self.execute = True
- self.verbose = False
-
- modes = ["build", "presubmit", "selenium", "unit_tests"]
- versions = ["Debug", "Release"]
-
- parser = OptionParser()
- parser.add_option(
- "--list-targets", action="store_true",
- help="lists all available targets.")
- parser.add_option(
- "--no-execute", action="store_true", default=False,
- help="just prints commands that would get executed.")
- parser.add_option(
- "--verbose", action="store_true",
- help="prints more output.")
- parser.add_option(
- "--targets", action="append",
- help="targets to build separated by commas.")
- parser.add_option(
- "--clean", action="store_true",
- help="cleans the targets.")
- parser.add_option(
- "--rebuild", action="store_true",
- help="cleans, then builds targets")
- parser.add_option(
- "--version", choices=versions, default="Debug",
- help="version to build. Versions are '%s'. Default='Debug' " %
- "', '".join(versions))
- parser.add_option(
- "--mode", choices=modes, default="build",
- help="mode to use. Valid modes are '%s'. Default='build' " %
- "', '".join(modes))
-
- (options, args) = parser.parse_args(args=args)
-
- self.verbose = options.verbose
- self.execute = not options.no_execute
-
- if options.list_targets:
- print "Not yet implemented"
- sys.exit(0)
-
- self.Log("mode:", options.mode)
-
- targets = options.targets
- if targets:
- # flatten the targets.
- targets = sum([t.split(",") for t in targets], [])
-
- os.chdir("build")
-
- # Create a platform specific builder.
- if os.name == 'nt':
- builder = self.WinBuilder(self)
- elif platform.system() == 'Darwin':
- builder = self.OSXBuilder(self)
- elif platform.system() == 'Linux':
- builder = self.LinuxBuilder(self)
- else:
- print "ERROR: Unknown platform."
- sys.exit(1)
-
- # clean if asked.
- if options.clean or options.rebuild:
- builder.CleanTargets(targets, options)
- if not options.rebuild:
- return
-
- # call a Do method based on the mode.
- func = getattr(builder, "Do%s" % options.mode)
- func(targets, options)
-
- def Log(self, *args):
- """Prints something if verbose is true."""
- if self.verbose:
- print args
-
- def Execute(self, args):
- """Executes an external program if execute is true."""
- if self.execute:
- self.Log(" ".join(args))
- if subprocess.call(args) > 0:
- raise RuntimeError("FAILED: " + " ".join(args))
- else:
- print " ".join(args)
-
-
-def main(args):
- GypBuilder(args[1:])
-
-if __name__ == "__main__":
- main(sys.argv)
-
diff --git a/o3d/import/archive.gyp b/o3d/import/archive.gyp
deleted file mode 100644
index 525f6c9a..0000000
--- a/o3d/import/archive.gyp
+++ /dev/null
@@ -1,94 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- },
- 'includes': [
- '../build/common.gypi',
- ],
- 'target_defaults': {
- 'include_dirs': [
- '..',
- '../..',
- '../../<(cgdir)/include',
- '../../<(gtestdir)',
- ],
- },
- 'targets': [
- {
- 'target_name': 'o3dArchive',
- 'type': 'static_library',
- 'dependencies': [
- '../../<(zlibdir)/zlib.gyp:zlib',
- ],
- 'sources': [
- 'cross/archive_processor.cc',
- 'cross/archive_processor.h',
- 'cross/archive_request.cc',
- 'cross/archive_request.h',
- 'cross/gz_compressor.cc',
- 'cross/gz_compressor.h',
- 'cross/gz_decompressor.cc',
- 'cross/gz_decompressor.h',
- 'cross/iarchive_generator.h',
- 'cross/memory_buffer.h',
- 'cross/memory_stream.cc',
- 'cross/memory_stream.h',
- 'cross/main_thread_archive_callback_client.cc',
- 'cross/main_thread_archive_callback_client.h',
- 'cross/raw_data.cc',
- 'cross/raw_data.h',
- 'cross/tar_processor.cc',
- 'cross/tar_processor.h',
- 'cross/targz_generator.h',
- 'cross/targz_processor.cc',
- 'cross/targz_processor.h',
- 'cross/threaded_stream_processor.cc',
- 'cross/threaded_stream_processor.h',
- ],
- },
- {
- 'target_name': 'o3dArchiveTest',
- 'type': 'none',
- 'dependencies': [
- 'o3dArchive',
- ],
- 'direct_dependent_settings': {
- 'sources': [
- 'cross/gz_compressor_test.cc',
- 'cross/gz_decompressor_test.cc',
- 'cross/memory_buffer_test.cc',
- 'cross/memory_stream_test.cc',
- 'cross/raw_data_test.cc',
- 'cross/tar_processor_test.cc',
- 'cross/targz_processor_test.cc',
- 'cross/threaded_stream_processor_test.cc',
- ],
- },
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)/archive_files',
- 'files': [
- "../tests/archive_files/BumpReflect.fx",
- "../tests/archive_files/bogus.tar.gz",
- "../tests/archive_files/keyboard.jpg",
- "../tests/archive_files/keyboard.jpg.gz",
- "../tests/archive_files/perc.aif",
- "../tests/archive_files/test1.tar",
- "../tests/archive_files/test1.tar.gz",
- "../tests/archive_files/test2.tar.gz",
- ],
- },
- ],
- },
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/import/cross/archive_processor.cc b/o3d/import/cross/archive_processor.cc
deleted file mode 100644
index 47b3d35..0000000
--- a/o3d/import/cross/archive_processor.cc
+++ /dev/null
@@ -1,88 +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 <stdio.h>
-#include <sys/stat.h>
-
-#include "import/cross/archive_processor.h"
-
-#include "base/logging.h"
-#include "import/cross/memory_buffer.h"
-#include "zlib.h"
-
-const int kChunkSize = 16384;
-
-namespace o3d {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-StreamProcessor::Status ArchiveProcessor::ProcessEntireStream(
- MemoryReadStream *stream) {
- Status status;
-
- // decompress until deflate stream ends or error
- do {
- int remaining = stream->GetRemainingByteCount();
-
- int process_this_time = remaining < kChunkSize ? remaining : kChunkSize;
- status = ProcessBytes(stream, process_this_time);
- } while (status == IN_PROGRESS);
-
- return status;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-StreamProcessor::Status ArchiveProcessor::ProcessFile(const char *filename) {
- struct stat file_info;
- int result = stat(filename, &file_info);
- if (result != 0) return FAILURE;
-
- int file_length = file_info.st_size;
- if (file_length == 0) return FAILURE;
-
- MemoryBuffer<uint8> buffer;
- buffer.Allocate(file_length);
- uint8 *p = buffer;
-
- // Test by reading in a tar.gz file and sending through the
- // progressive streaming system
- FILE *fp = fopen(filename, "rb");
- if (!fp) return FAILURE; // can't open file!
- if (static_cast<size_t>(file_length) !=
- fread(p, sizeof(uint8), file_length, fp))
- return FAILURE;
- if (0 != fclose(fp)) return FAILURE;
-
- MemoryReadStream stream(p, file_length);
-
- return ProcessEntireStream(&stream);
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/archive_processor.h b/o3d/import/cross/archive_processor.h
deleted file mode 100644
index 5e55a24..0000000
--- a/o3d/import/cross/archive_processor.h
+++ /dev/null
@@ -1,97 +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_IMPORT_CROSS_ARCHIVE_PROCESSOR_H_
-#define O3D_IMPORT_CROSS_ARCHIVE_PROCESSOR_H_
-
-#include <string>
-#include "base/basictypes.h"
-#include "import/cross/memory_stream.h"
-
-namespace o3d {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class ArchiveFileInfo {
- public:
- ArchiveFileInfo(const std::string &filename, int file_size)
- : filename_(filename), file_size_(file_size) {}
-
- virtual ~ArchiveFileInfo() {}
-
- const std::string &GetFileName() const { return filename_; }
- int GetFileSize() const { return file_size_; }
-
- private:
- std::string filename_;
- int file_size_;
-};
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class ArchiveCallbackClient {
- public:
- virtual ~ArchiveCallbackClient() {}
- virtual void ReceiveFileHeader(const ArchiveFileInfo &file_info) = 0;
- virtual bool ReceiveFileData(MemoryReadStream *stream, size_t nbytes) = 0;
- virtual void Close(bool success) = 0;
-};
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class ArchiveProcessor: public StreamProcessor {
- public:
- explicit ArchiveProcessor(ArchiveCallbackClient *callback_client) {}
-
- virtual ~ArchiveProcessor() {}
-
- // Call to "push" bytes into the processor. They will be decompressed and
- // the appropriate callbacks on |callback_client| will happen
- // as files come in...
- virtual Status ProcessBytes(MemoryReadStream *stream,
- size_t bytes_to_process) = 0;
-
- // Decompresses the complete file archive, making file callbacks as the files
- // come in...
- virtual Status ProcessFile(const char *filename);
-
- // Decompresses the complete archive from memory,
- // making file callbacks as the files come in...
- virtual Status ProcessEntireStream(MemoryReadStream *stream);
-
- protected:
- DISALLOW_COPY_AND_ASSIGN(ArchiveProcessor);
-};
-
-#ifndef NDEBUG
-// For debugging, report a zlib or i/o error
-extern void zerr(int result);
-#endif
-} // namespace o3d
-#endif // O3D_IMPORT_CROSS_ARCHIVE_PROCESSOR_H_
diff --git a/o3d/import/cross/archive_request.cc b/o3d/import/cross/archive_request.cc
deleted file mode 100644
index 3de246a..0000000
--- a/o3d/import/cross/archive_request.cc
+++ /dev/null
@@ -1,255 +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 definition of the ArchiveRequest class.
-
-#include "import/cross/archive_request.h"
-
-#include "core/cross/pack.h"
-#include "core/cross/imain_thread_task_poster.h"
-#include "import/cross/targz_processor.h"
-#include "import/cross/main_thread_archive_callback_client.h"
-#include "import/cross/threaded_stream_processor.h"
-
-#define DEBUG_ARCHIVE_CALLBACKS 0
-
-using glue::DownloadStream;
-
-namespace o3d {
-
-O3D_DEFN_CLASS(ArchiveRequest, ObjectBase);
-
-// NOTE: The file starts with "aaaaaaaa" in the hope that most tar.gz creation
-// utilties can easily sort with this being the file first in the .tgz
-// Otherwise you'll have to manually force it to be the first file.
-const char* const ArchiveRequest::kO3DMarker = "aaaaaaaa.o3d";
-const char* const ArchiveRequest::kO3DMarkerContent = "o3d";
-const size_t ArchiveRequest::kO3DMarkerContentLength = 3;
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-ArchiveRequest::ArchiveRequest(ServiceLocator* service_locator,
- Pack *pack)
- : ObjectBase(service_locator),
- pack_(pack),
- done_(false),
- success_(false),
- ready_state_(0),
- stream_length_(0),
- bytes_received_(0) {
- IMainThreadTaskPoster* main_thread_task_poster =
- service_locator->GetService<IMainThreadTaskPoster>();
- if (main_thread_task_poster->IsSupported()) {
- main_thread_archive_callback_client_ = new MainThreadArchiveCallbackClient(
- service_locator, this);
- extra_processor_ = new TarGzProcessor(main_thread_archive_callback_client_);
- archive_processor_ = new ThreadedStreamProcessor(extra_processor_);
- } else {
- main_thread_archive_callback_client_ = NULL;
- extra_processor_ = NULL;
- archive_processor_ = new TarGzProcessor(this);
- }
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-ArchiveRequest::~ArchiveRequest() {
- delete archive_processor_;
- delete extra_processor_;
- delete main_thread_archive_callback_client_;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-ArchiveRequest *ArchiveRequest::Create(ServiceLocator* service_locator,
- Pack *pack) {
- ArchiveRequest *request = new ArchiveRequest(service_locator, pack);
- return request;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void ArchiveRequest::NewStreamCallback(DownloadStream *stream) {
- // we're starting to stream - make note of the stream length
- stream_length_ = stream->GetStreamLength();
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-int32 ArchiveRequest::WriteReadyCallback(DownloadStream *stream) {
- // Setting this too high causes Firefox to timeout in the Write callback.
- return 128 * 1024;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-int32 ArchiveRequest::WriteCallback(DownloadStream *stream,
- int32 offset,
- int32 length,
- void *data) {
- // Count the bytes as they stream in
- bytes_received_ += length;
-
- MemoryReadStream memory_stream(reinterpret_cast<uint8*>(data), length);
-
- // Progressively decompress the bytes we've just been given
- StreamProcessor::Status status =
- archive_processor_->ProcessBytes(&memory_stream, length);
-
- if (status == StreamProcessor::FAILURE) {
- set_success(false);
- set_error("Invalid gzipped tar file");
- stream->Cancel(); // tell the browser to stop downloading
- // NOTE: Cancel will call NPP_Cancel which in turn will call
- // ArchiveRequest::FinishedCallback so we don't do anything here since
- // we may already have been deleted on return.
- }
-
- return length;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Loads the Archive file, calls the JS callback to notify success.
-void ArchiveRequest::FinishedCallback(DownloadStream *stream,
- bool success,
- const std::string &filename,
- const std::string &mime_type) {
- archive_processor_->Close(success);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// ArchiveCallbackClient methods
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void ArchiveRequest::ReceiveFileHeader(const ArchiveFileInfo &file_info) {
- int file_size = file_info.GetFileSize();
-
-#if DEBUG_ARCHIVE_CALLBACKS
- printf("\n");
- printf("-----------------------------------------------------------------\n");
- printf("File Name: %s\n", file_info.GetFileName().c_str());
- printf("File Size: %d\n", file_size);
- printf("-----------------------------------------------------------------\n");
-#endif
-
- if (file_size > 0) { // skip over directory entries (with zero file size)
- // Save filename for when we create our RawData object
- current_filename_ = file_info.GetFileName();
-
- temp_buffer_.Allocate(file_size);
- file_memory_stream_.Assign(static_cast<uint8*>(temp_buffer_),
- file_size);
- }
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool ArchiveRequest::ReceiveFileData(MemoryReadStream *input_stream,
- size_t nbytes) {
- // hold on to ourselves in case we are freed in the callback.
- ArchiveRequest::Ref temp(this);
- assert(input_stream->GetRemainingByteCount() >= nbytes);
- assert(file_memory_stream_.GetRemainingByteCount() >= nbytes);
-
- // Buffer file bytes from |input_stream| to |file_memory_stream_|
- file_memory_stream_.Write(input_stream->GetDirectMemoryPointer(), nbytes);
- input_stream->Skip(nbytes);
-
- // If we've just filled our file temp buffer then callback
- if (file_memory_stream_.GetRemainingByteCount() == 0) {
- // We've reached the end of file
-
- // Check if this is file metadata (extra file attributes) and skip if so
- // On the Mac, the tar command marks metadata by
- // pre-pending "._" to the filename
- bool is_metadata = false;
- std::string::size_type j = current_filename_.find("._");
- if (j != std::string::npos) {
- if (j == 0 || current_filename_[j - 1] == '/') is_metadata = true;
- }
-
- // Skip ".DS_Store" file which may be created in Mac-generated archives
- j = current_filename_.find(".DS_Store");
- if (j != std::string::npos) {
- if (j == 0 || current_filename_[j - 1] == '/') is_metadata = true;
- }
-
- if (!is_metadata && onfileavailable()) {
- // keep track of the "current" data object which the callback will use
- RawData::Ref raw_data = RawData::Create(
- service_locator(),
- current_filename_,
- temp_buffer_,
- file_memory_stream_.GetTotalStreamLength() );
-
- // keeps them all around until the ArchiveRequest goes away
- raw_data_list_.push_back(raw_data);
-
- // If it's the first file is must be the kO3DMarker or else it's an error.
- if (raw_data_list_.size() == 1) {
- if (raw_data->uri().compare(kO3DMarker) != 0 ||
- raw_data->StringValue().compare(kO3DMarkerContent) != 0) {
- set_error(String("Archive '") + uri_ +
- String("' is not intended for O3D. Missing '") +
- kO3DMarker + String("' as first file in archive."));
- return false;
- }
- } else {
- raw_data_ = raw_data;
- onfileavailable()->Run(raw_data);
- raw_data_.Reset();
- }
-
- // If data hasn't been discarded (inside callback) then writes out to
- // temp file so we can get the data back at a later time
- raw_data.Get()->Flush();
-
- // Remove the reference to the raw_data so we don't have undefined
- // behavior after the callback.
- raw_data.Reset();
- }
- }
- return true;
-}
-
-void ArchiveRequest::Close(bool success) {
- set_ready_state(ArchiveRequest::STATE_LOADED);
-
- // Since the standard codes only go far enough to tell us that the download
- // succeeded, we set the success [and implicitly the done] flags to give the
- // rest of the story.
- set_success(success);
- if (!success) {
- // I have no idea if an error is already set here but one MUST be set
- // so let's check.
- if (error().empty()) {
- set_error(String("Could not download archive: ") + uri());
- }
- }
- if (onreadystatechange())
- onreadystatechange()->Run();
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/archive_request.h b/o3d/import/cross/archive_request.h
deleted file mode 100644
index 980c449..0000000
--- a/o3d/import/cross/archive_request.h
+++ /dev/null
@@ -1,208 +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 declaration of the ArchiveRequest class.
-
-#ifndef O3D_IMPORT_CROSS_ARCHIVE_REQUEST_H_
-#define O3D_IMPORT_CROSS_ARCHIVE_REQUEST_H_
-
-#include <algorithm>
-#include <string>
-
-#include "base/scoped_ptr.h"
-#include "core/cross/callback.h"
-#include "core/cross/object_base.h"
-#include "core/cross/pack.h"
-#include "import/cross/targz_processor.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-#include "import/cross/raw_data.h"
-#include "plugin/cross/download_stream.h"
-
-namespace o3d {
-
-typedef Closure ArchiveReadyStateChangeCallback;
-typedef Callback1<RawData*> ArchiveFileAvailableCallback;
-
-// An ArchiveRequest object is used to carry out an asynchronous request
-// for a file to be loaded.
-class ArchiveRequest : public ObjectBase, public ArchiveCallbackClient {
- public:
- enum ReadyState { // These are copied from XMLHttpRequest.
- STATE_INIT = 0,
- STATE_OPEN = 1,
- STATE_SENT = 2,
- STATE_RECEIVING = 3,
- STATE_LOADED = 4,
- };
-
- // A file by this name must be the first file in the archive otherwise
- // the archive is rejected. This is a security measure so that O3D
- // can not be used to open arbitrary .tgz files but only those files someone
- // has specifically prepared for O3D. This file will not be passed to
- // the onfileavailable callback.
- static const char* const kO3DMarker;
-
- // The contents of the O3D marker file. Arguably the content should not matter
- // but for the sake of completeness we define the content so there is no
- // ambiguity.
- static const char* const kO3DMarkerContent;
-
- // The size of the O3D_MARKER_CONTENT.
- static const size_t kO3DMarkerContentLength;
-
- public:
- typedef SmartPointer<ArchiveRequest> Ref;
-
- virtual ~ArchiveRequest();
-
- static ArchiveRequest *Create(ServiceLocator* service_locator,
- Pack *pack);
-
-
- // Streaming callbacks
- virtual void NewStreamCallback(glue::DownloadStream *stream);
- virtual int32 WriteReadyCallback(glue::DownloadStream *stream);
- virtual int32 WriteCallback(glue::DownloadStream *stream,
- int32 offset,
- int32 length,
- void *data);
-
- virtual void FinishedCallback(glue::DownloadStream *stream,
- bool success,
- const std::string &filename,
- const std::string &mime_type);
-
- // ArchiveCallbackClient methods
- virtual void ReceiveFileHeader(const ArchiveFileInfo &file_info);
- virtual bool ReceiveFileData(MemoryReadStream *stream, size_t nbytes);
- virtual void Close(bool success);
-
- Pack *pack() {
- return pack_.Get(); // Set at creation time and never changed.
- }
-
- ArchiveFileAvailableCallback *onfileavailable() {
- return onfileavailable_.get();
- }
- void set_onfileavailable(ArchiveFileAvailableCallback *onfileavailable) {
- onfileavailable_.reset(onfileavailable);
- }
-
- ArchiveReadyStateChangeCallback *onreadystatechange() {
- return onreadystatechange_.get();
- }
- void set_onreadystatechange(
- ArchiveReadyStateChangeCallback *onreadystatechange) {
- onreadystatechange_.reset(onreadystatechange);
- }
-
- // returns the "current" data object (used by the callback)
- RawData *data() {
- return raw_data_.Get();
- }
-
- const String& uri() {
- return uri_;
- }
- void set_uri(const String& uri) {
- uri_ = uri;
- }
-
- bool done() {
- return done_;
- }
-
- bool success() {
- return success_;
- }
- void set_success(bool success) {
- success_ = success;
- done_ = true;
- pack_.Reset(); // Remove pack reference to allow garbage collection of pack.
- }
-
- const String& error() const {
- return error_;
- }
- void set_error(const String& error) {
- error_ = error;
- }
-
- int ready_state() {
- return ready_state_;
- }
- void set_ready_state(int state) {
- ready_state_ = state;
- }
-
- int stream_length() {
- return stream_length_;
- }
-
- int bytes_received() {
- return bytes_received_;
- }
-
- protected:
- ArchiveRequest(ServiceLocator* service_locator, Pack *pack);
-
- Pack::Ref pack_;
- scoped_ptr<ArchiveReadyStateChangeCallback> onreadystatechange_;
- scoped_ptr<ArchiveFileAvailableCallback> onfileavailable_;
- String uri_;
-
- // Request state
- bool done_; // Set after completion/failure to indicate success_ is valid.
- bool success_; // Set after completion/failure to indicate which it is.
- int ready_state_; // Like the XMLHttpRequest variable of the same name.
- String error_; // Set after completion on failure.
-
- StreamProcessor *archive_processor_;
- StreamProcessor *extra_processor_;
- ArchiveCallbackClient* main_thread_archive_callback_client_;
- std::vector<RawData::Ref> raw_data_list_;
- RawData::Ref raw_data_;
- MemoryBuffer<uint8> temp_buffer_;
- MemoryWriteStream file_memory_stream_;
- String current_filename_;
-
- int stream_length_; // total length of stream
- int bytes_received_; // bytes received so far
-
- O3D_DECL_CLASS(ArchiveRequest, ObjectBase)
- DISALLOW_IMPLICIT_CONSTRUCTORS(ArchiveRequest);
-}; // ArchiveRequest
-
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_ARCHIVE_REQUEST_H_
diff --git a/o3d/import/cross/camera_info.cc b/o3d/import/cross/camera_info.cc
deleted file mode 100644
index 3f46e4c..0000000
--- a/o3d/import/cross/camera_info.cc
+++ /dev/null
@@ -1,98 +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 "import/cross/camera_info.h"
-
-namespace o3d {
-
-O3D_OBJECT_BASE_DEFN_CLASS(
- "o3djs.CameraInfo", CameraInfo, JSONObject);
-O3D_OBJECT_BASE_DEFN_CLASS(
- "o3djs.PerspectiveCameraInfo", PerspectiveCameraInfo, CameraInfo);
-O3D_OBJECT_BASE_DEFN_CLASS(
- "o3djs.OrthographicCameraInfo", OrthographicCameraInfo, CameraInfo);
-
-const char* CameraInfo::kAspectRatioParamName = "aspectRatio";
-const char* CameraInfo::kNearZParamName = "nearZ";
-const char* CameraInfo::kFarZParamName = "farZ";
-const char* CameraInfo::kTransformValueName = "transform";
-const char* CameraInfo::kEyeValueName = "eye";
-const char* CameraInfo::kTargetValueName = "target";
-const char* CameraInfo::kUpValueName = "up";
-
-CameraInfo::CameraInfo(ServiceLocator* service_locator)
- : JSONObject(service_locator) {
- RegisterParamRef(kAspectRatioParamName, &aspect_ratio_param_);
- RegisterParamRef(kNearZParamName, &near_z_param_);
- RegisterParamRef(kFarZParamName, &far_z_param_);
- RegisterJSONValue(kTransformValueName, &transform_value_);
- RegisterJSONValue(kEyeValueName, &eye_value_);
- RegisterJSONValue(kTargetValueName, &target_value_);
- RegisterJSONValue(kUpValueName, &up_value_);
-
- set_aspect_ratio(1.0f);
- set_near_z(0.01f);
- set_far_z(10000.0f);
-}
-
-const char* OrthographicCameraInfo::kMagXParamName = "magX";
-const char* OrthographicCameraInfo::kMagYParamName = "magY";
-
-OrthographicCameraInfo::OrthographicCameraInfo(ServiceLocator* service_locator)
- : CameraInfo(service_locator) {
- RegisterParamRef(kMagXParamName, &mag_x_param_);
- RegisterParamRef(kMagYParamName, &mag_y_param_);
-
- set_mag_x(1.0f);
- set_mag_y(1.0f);
-}
-
-ObjectBase::Ref OrthographicCameraInfo::Create(
- ServiceLocator* service_locator) {
- return ObjectBase::Ref(new OrthographicCameraInfo(service_locator));
-}
-
-const char* PerspectiveCameraInfo::kFieldOfViewYParamName = "fieldOfViewY";
-
-PerspectiveCameraInfo::PerspectiveCameraInfo(ServiceLocator* service_locator)
- : CameraInfo(service_locator) {
- RegisterParamRef(kFieldOfViewYParamName, &field_of_view_y_param_);
-
- set_field_of_view_y(30.0f * 3.14159f / 180.0f);
-}
-
-ObjectBase::Ref PerspectiveCameraInfo::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new PerspectiveCameraInfo(service_locator));
-}
-
-} // namespace o3d
-
-
diff --git a/o3d/import/cross/camera_info.h b/o3d/import/cross/camera_info.h
deleted file mode 100644
index 94c88a6..0000000
--- a/o3d/import/cross/camera_info.h
+++ /dev/null
@@ -1,221 +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 CameraInfo class.
-
-#ifndef O3D_IMPORT_CROSS_CAMERA_INFO_H_
-#define O3D_IMPORT_CROSS_CAMERA_INFO_H_
-
-#include "import/cross/json_object.h"
-
-namespace o3d {
-
-// CameraInfo is a used for serialization only and is not part of the
-// normal O3D plugin. It is used for information about the camera.
-class CameraInfo : public JSONObject {
- public:
- typedef SmartPointer<CameraInfo> Ref;
-
- static const char* kAspectRatioParamName;
- static const char* kNearZParamName;
- static const char* kFarZParamName;
- static const char* kTransformValueName;
- static const char* kEyeValueName;
- static const char* kTargetValueName;
- static const char* kUpValueName;
-
- // Gets the near_z.
- float near_z() const {
- return near_z_param_->value();
- }
-
- // Sets the near_z.
- void set_near_z(float value) {
- near_z_param_->set_value(value);
- }
-
- // Gets the far_z.
- float far_z() const {
- return far_z_param_->value();
- }
-
- // Sets the far_z.
- void set_far_z(float value) {
- far_z_param_->set_value(value);
- }
-
- // Gets the aspect_ratio.
- float aspect_ratio() const {
- return aspect_ratio_param_->value();
- }
-
- // Sets the aspect_ratio.
- void set_aspect_ratio(float value) {
- aspect_ratio_param_->set_value(value);
- }
-
- // Gets the transform.
- Transform* transform() const {
- return transform_value_->value();
- }
-
- // Sets the transform.
- void set_transform(Transform* value) {
- transform_value_->set_value(value);
- }
-
- // Gets the eye.
- Float3 eye() const {
- return eye_value_->value();
- }
-
- // Sets the eye.
- void set_eye(const Float3& value) {
- eye_value_->set_value(value);
- }
-
- // Gets the target.
- Float3 target() const {
- return target_value_->value();
- }
-
- // Sets the target.
- void set_target(const Float3& value) {
- target_value_->set_value(value);
- }
-
- // Gets the up.
- Float3 up() const {
- return up_value_->value();
- }
-
- // Sets the up.
- void set_up(const Float3& value) {
- up_value_->set_value(value);
- }
-
- protected:
- explicit CameraInfo(ServiceLocator* service_locator);
-
- private:
- // We make these params so we can easily attach animation to the camera's
- // parameters.
- ParamFloat::Ref aspect_ratio_param_;
- ParamFloat::Ref near_z_param_;
- ParamFloat::Ref far_z_param_;
-
- // These are not params, just JSON values.
- JSONTransform::Ref transform_value_;
- JSONOptionalFloat3::Ref eye_value_;
- JSONOptionalFloat3::Ref target_value_;
- JSONOptionalFloat3::Ref up_value_;
-
- O3D_OBJECT_BASE_DECL_CLASS(CameraInfo, JSONObject);
- DISALLOW_COPY_AND_ASSIGN(CameraInfo);
-};
-
-class OrthographicCameraInfo : public CameraInfo {
- public:
- typedef SmartPointer<OrthographicCameraInfo> Ref;
-
- static const char* kMagXParamName;
- static const char* kMagYParamName;
-
- // Gets the mag_x.
- float mag_x() const {
- return mag_x_param_->value();
- }
-
- // Sets the mag_x.
- void set_mag_x(float value) {
- mag_x_param_->set_value(value);
- }
-
- // Gets the mag_y.
- float mag_y() const {
- return mag_y_param_->value();
- }
-
- // Sets the mag_y.
- void set_mag_y(float value) {
- mag_y_param_->set_value(value);
- }
-
- private:
- explicit OrthographicCameraInfo(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // We make these params so we can easily attach animation to the camera's
- // parameters.
- ParamFloat::Ref mag_x_param_;
- ParamFloat::Ref mag_y_param_;
-
- O3D_OBJECT_BASE_DECL_CLASS(OrthographicCameraInfo, CameraInfo);
- DISALLOW_COPY_AND_ASSIGN(OrthographicCameraInfo);
-};
-
-class PerspectiveCameraInfo : public CameraInfo {
- public:
- typedef SmartPointer<PerspectiveCameraInfo> Ref;
-
- static const char* kFieldOfViewYParamName;
-
- // Gets the field_of_view_y.
- float field_of_view_y() const {
- return field_of_view_y_param_->value();
- }
-
- // Sets the field_of_view_y.
- void set_field_of_view_y(float value) {
- field_of_view_y_param_->set_value(value);
- }
-
- private:
- explicit PerspectiveCameraInfo(ServiceLocator* service_locator);
-
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- // We make these params so we can easily attach animation to the camera's
- // parameters.
- ParamFloat::Ref field_of_view_y_param_;
-
- O3D_OBJECT_BASE_DECL_CLASS(PerspectiveCameraInfo, CameraInfo);
- DISALLOW_COPY_AND_ASSIGN(PerspectiveCameraInfo);
-};
-
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_CAMERA_INFO_H_
-
diff --git a/o3d/import/cross/camera_info_test.cc b/o3d/import/cross/camera_info_test.cc
deleted file mode 100644
index 662b161..0000000
--- a/o3d/import/cross/camera_info_test.cc
+++ /dev/null
@@ -1,222 +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 "tests/common/win/testing_common.h"
-#include "import/cross/camera_info.h"
-#include "core/cross/class_manager.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-#include "utils/cross/math_gtest.h"
-
-namespace o3d {
-
-namespace {
-
-// A class to test CameraInfo.
-class TestCameraInfo : public CameraInfo {
- public:
- typedef SmartPointer<TestCameraInfo> Ref;
-
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- private:
- explicit TestCameraInfo(ServiceLocator* service_locator)
- : CameraInfo(service_locator) {
- }
-
- O3D_OBJECT_BASE_DECL_CLASS(TestCameraInfo, CameraInfo);
- DISALLOW_COPY_AND_ASSIGN(TestCameraInfo);
-};
-
-O3D_OBJECT_BASE_DEFN_CLASS(
- "o3djs.TestCameraInfo", TestCameraInfo, CameraInfo);
-
-ObjectBase::Ref TestCameraInfo::Create(
- ServiceLocator* service_locator) {
- return ObjectBase::Ref(new TestCameraInfo(service_locator));
-}
-
-} // anonymous namespace
-
-class TestCameraInfoTest : public testing::Test {
- protected:
- TestCameraInfoTest()
- : class_manager_(g_service_locator),
- object_manager_(g_service_locator),
- class_register_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ClassManager> class_manager_;
- ServiceDependency<ObjectManager> object_manager_;
- ClassManager::Register<TestCameraInfo> class_register_;
- Pack* pack_;
-};
-
-void TestCameraInfoTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void TestCameraInfoTest::TearDown() {
- object_manager_->DestroyPack(pack_);
-}
-
-// Creates a TestCameraInfo, tests basic properties.
-TEST_F(TestCameraInfoTest, TestTestCameraInfo) {
- TestCameraInfo *camera_info = pack()->Create<TestCameraInfo>();
- EXPECT_TRUE(camera_info->IsA(TestCameraInfo::GetApparentClass()));
- EXPECT_TRUE(camera_info->IsA(CameraInfo::GetApparentClass()));
- EXPECT_TRUE(camera_info->IsA(JSONObject::GetApparentClass()));
- EXPECT_TRUE(camera_info->IsA(ParamObject::GetApparentClass()));
-
- EXPECT_EQ(camera_info->aspect_ratio(), 1.0f);
- EXPECT_EQ(camera_info->near_z(), 0.01f);
- EXPECT_EQ(camera_info->far_z(), 10000.0f);
- EXPECT_TRUE(camera_info->transform() == NULL);
-
- Transform* transform = pack()->Create<Transform>();
- ASSERT_TRUE(transform != NULL);
-
- camera_info->set_aspect_ratio(2.0f);
- camera_info->set_near_z(0.02f);
- camera_info->set_far_z(20000.0f);
- camera_info->set_transform(transform);
- camera_info->set_eye(Float3(10.0f, 20.0f, 30.0f));
- camera_info->set_target(Float3(11.0f, 22.0f, 33.0f));
- camera_info->set_up(Float3(12.0f, 23.0f, 34.0f));
-
- EXPECT_EQ(camera_info->aspect_ratio(), 2.0f);
- EXPECT_EQ(camera_info->near_z(), 0.02f);
- EXPECT_EQ(camera_info->far_z(), 20000.0f);
- EXPECT_TRUE(camera_info->transform() == transform);
- EXPECT_EQ(camera_info->eye(), Float3(10.0f, 20.0f, 30.0f));
- EXPECT_EQ(camera_info->target(), Float3(11.0f, 22.0f, 33.0f));
- EXPECT_EQ(camera_info->up(), Float3(12.0f, 23.0f, 34.0f));
-}
-
-class PerspectiveCameraInfoTest : public testing::Test {
- protected:
- PerspectiveCameraInfoTest()
- : class_manager_(g_service_locator),
- object_manager_(g_service_locator),
- class_register_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ClassManager> class_manager_;
- ServiceDependency<ObjectManager> object_manager_;
- ClassManager::Register<PerspectiveCameraInfo> class_register_;
- Pack* pack_;
-};
-
-void PerspectiveCameraInfoTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void PerspectiveCameraInfoTest::TearDown() {
- object_manager_->DestroyPack(pack_);
-}
-
-// Creates a PerspectiveCameraInfo, tests basic properties.
-TEST_F(PerspectiveCameraInfoTest, TestPerspectiveCameraInfo) {
- PerspectiveCameraInfo *camera_info = pack()->Create<PerspectiveCameraInfo>();
- EXPECT_TRUE(camera_info->IsA(PerspectiveCameraInfo::GetApparentClass()));
- EXPECT_TRUE(camera_info->IsA(CameraInfo::GetApparentClass()));
- EXPECT_TRUE(camera_info->IsA(JSONObject::GetApparentClass()));
- EXPECT_TRUE(camera_info->IsA(ParamObject::GetApparentClass()));
-
- EXPECT_EQ(camera_info->field_of_view_y(), 30.0f * 3.14159f / 180.0f);
-
- camera_info->set_field_of_view_y(60.0f * 3.14159f / 180.0f);
-
- EXPECT_EQ(camera_info->field_of_view_y(), 60.0f * 3.14159f / 180.0f);
-}
-
-class OrthographicCameraInfoTest : public testing::Test {
- protected:
- OrthographicCameraInfoTest()
- : class_manager_(g_service_locator),
- object_manager_(g_service_locator),
- class_register_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ClassManager> class_manager_;
- ServiceDependency<ObjectManager> object_manager_;
- ClassManager::Register<OrthographicCameraInfo> class_register_;
- Pack* pack_;
-};
-
-void OrthographicCameraInfoTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void OrthographicCameraInfoTest::TearDown() {
- object_manager_->DestroyPack(pack_);
-}
-
-// Creates a OrthographicCameraInfo, tests basic properties.
-TEST_F(OrthographicCameraInfoTest, TestOrthographicCameraInfo) {
- OrthographicCameraInfo *camera_info =
- pack()->Create<OrthographicCameraInfo>();
- EXPECT_TRUE(camera_info->IsA(OrthographicCameraInfo::GetApparentClass()));
- EXPECT_TRUE(camera_info->IsA(CameraInfo::GetApparentClass()));
- EXPECT_TRUE(camera_info->IsA(JSONObject::GetApparentClass()));
- EXPECT_TRUE(camera_info->IsA(ParamObject::GetApparentClass()));
-
- EXPECT_EQ(camera_info->mag_x(), 1.0f);
- EXPECT_EQ(camera_info->mag_y(), 1.0f);
-
- camera_info->set_mag_x(2.0f);
- camera_info->set_mag_y(3.0f);
-
- EXPECT_EQ(camera_info->mag_x(), 2.0f);
- EXPECT_EQ(camera_info->mag_y(), 3.0f);
-}
-
-} // namespace o3d
-
diff --git a/o3d/import/cross/collada.cc b/o3d/import/cross/collada.cc
deleted file mode 100644
index 6047da0..0000000
--- a/o3d/import/cross/collada.cc
+++ /dev/null
@@ -1,3079 +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 functions for importing COLLADA files into O3D.
-#include "import/cross/precompile.h"
-
-#include "base/file_path.h"
-#include "base/file_util.h"
-#include "base/process_util.h"
-#include "base/utf_string_conversions.h"
-#include "core/cross/class_manager.h"
-#include "core/cross/curve.h"
-#include "core/cross/error.h"
-#include "core/cross/function.h"
-#include "core/cross/ierror_status.h"
-#include "core/cross/math_utilities.h"
-#include "core/cross/matrix4_axis_rotation.h"
-#include "core/cross/matrix4_composition.h"
-#include "core/cross/matrix4_scale.h"
-#include "core/cross/matrix4_translation.h"
-#include "core/cross/pack.h"
-#include "core/cross/param_operation.h"
-#include "core/cross/primitive.h"
-#include "core/cross/sampler.h"
-#include "core/cross/skin.h"
-#include "core/cross/stream.h"
-#include "import/cross/collada.h"
-#include "import/cross/collada_conditioner.h"
-#include "import/cross/collada_zip_archive.h"
-#include "import/cross/destination_buffer.h"
-#include "import/cross/file_output_stream_processor.h"
-#include "utils/cross/file_path_utils.h"
-#include "third_party/libtxc_dxtn/files/txc_dxtn.h"
-
-#define COLLADA_NAMESPACE "collada"
-#define COLLADA_NAMESPACE_SEPARATOR "."
-
-// Macro to provide a uniform prefix for all string constants created by
-// COLLADA.
-#define COLLADA_STRING_CONSTANT(value) \
- (COLLADA_NAMESPACE COLLADA_NAMESPACE_SEPARATOR value)
-
-
-namespace o3d {
-
-const char* Collada::kLightingTypeParamName =
- COLLADA_STRING_CONSTANT("lightingType");
-
-const char* Collada::kLightingTypeConstant = "constant";
-const char* Collada::kLightingTypePhong = "phong";
-const char* Collada::kLightingTypeBlinn = "blinn";
-const char* Collada::kLightingTypeLambert = "lambert";
-const char* Collada::kLightingTypeUnknown = "unknown";
-
-const char* Collada::kMaterialParamNameEmissive = "emissive";
-const char* Collada::kMaterialParamNameAmbient = "ambient";
-const char* Collada::kMaterialParamNameDiffuse = "diffuse";
-const char* Collada::kMaterialParamNameSpecular = "specular";
-const char* Collada::kMaterialParamNameShininess = "shininess";
-const char* Collada::kMaterialParamNameSpecularFactor = "specularFactor";
-const char* Collada::kMaterialParamNameEmissiveSampler = "emissiveSampler";
-const char* Collada::kMaterialParamNameAmbientSampler = "ambientSampler";
-const char* Collada::kMaterialParamNameDiffuseSampler = "diffuseSampler";
-const char* Collada::kMaterialParamNameSpecularSampler = "specularSampler";
-const char* Collada::kMaterialParamNameBumpSampler = "bumpSampler";
-
-class TranslationMap : public FCDGeometryIndexTranslationMap {
-};
-
-namespace {
-
-Vector3 FMVector3ToVector3(const FMVector3& fmvector3) {
- return Vector3(fmvector3.x, fmvector3.y, fmvector3.z);
-}
-
-Vector4 FMVector4ToVector4(const FMVector4& fmvector4) {
- return Vector4(fmvector4.x, fmvector4.y, fmvector4.z, fmvector4.w);
-}
-
-Float2 FMVector2ToFloat2(const FMVector2& fmvector2) {
- return Float2(fmvector2.x, fmvector2.y);
-}
-
-Matrix4 FMMatrix44ToMatrix4(const FMMatrix44& fmmatrix44) {
- return Matrix4(Vector4(fmmatrix44[0][0],
- fmmatrix44[0][1],
- fmmatrix44[0][2],
- fmmatrix44[0][3]),
- Vector4(fmmatrix44[1][0],
- fmmatrix44[1][1],
- fmmatrix44[1][2],
- fmmatrix44[1][3]),
- Vector4(fmmatrix44[2][0],
- fmmatrix44[2][1],
- fmmatrix44[2][2],
- fmmatrix44[2][3]),
- Vector4(fmmatrix44[3][0],
- fmmatrix44[3][1],
- fmmatrix44[3][2],
- fmmatrix44[3][3]));
-}
-} // anonymous namespace
-
-void ColladaDataMap::Clear() {
- original_data_.clear();
-}
-
-bool ColladaDataMap::AddData(const FilePath& file_path,
- const std::string& data,
- ServiceLocator* service_locator) {
- std::pair<OriginalDataMap::iterator, bool> result =
- original_data_.insert(std::pair<FilePath, std::string>(file_path, data));
- if (!result.second) {
- O3D_ERROR(service_locator)
- << "Attempt to map 2 resources to the same file path:"
- << FilePathToUTF8(file_path).c_str();
- }
- return result.second;
-}
-
-std::vector<FilePath> ColladaDataMap::GetOriginalDataFilenames() const {
- std::vector<FilePath> result;
- for (OriginalDataMap::const_iterator iter = original_data_.begin();
- iter != original_data_.end();
- ++iter) {
- result.push_back(iter->first);
- }
- return result;
-}
-
-const std::string& ColladaDataMap::GetOriginalData(
- const FilePath& filename) const {
- static const std::string empty;
- OriginalDataMap::const_iterator entry = original_data_.find(filename);
- if (entry != original_data_.end()) {
- return entry->second;
- } else {
- return empty;
- }
-}
-
-// Import the given COLLADA file or ZIP file into the given scene.
-// This is the external interface to o3d.
-bool Collada::Import(Pack* pack,
- const FilePath& filename,
- Transform* parent,
- ParamFloat* animation_input,
- const Options& options) {
- Collada collada(pack, options);
- return collada.ImportFile(filename, parent, animation_input);
-}
-
-bool Collada::Import(Pack* pack,
- const String& filename,
- Transform* parent,
- ParamFloat* animation_input,
- const Options& options) {
- return Collada::Import(pack,
- UTF8ToFilePath(filename),
- parent,
- animation_input,
- options);
-}
-
-void Collada::Init(ServiceLocator* service_locator) {
- ClassManager* class_manager=
- service_locator->GetService<o3d::ClassManager>();
- class_manager->AddTypedClass<DestinationBuffer>();
-}
-
-// Parameters:
-// pack: The pack into which the scene objects will be placed.
-// Returns true on success.
-Collada::Collada(Pack* pack, const Options& options)
- : service_locator_(pack->service_locator()),
- pack_(pack),
- options_(options),
- dummy_effect_(NULL),
- dummy_material_(NULL),
- instance_root_(NULL),
- collada_zip_archive_(NULL),
- cull_enabled_(false),
- cull_front_(false),
- front_cw_(false),
- unique_filename_counter_(0) {
-}
-
-Collada::~Collada() {
- delete collada_zip_archive_;
-}
-
-void Collada::ClearData() {
- textures_.clear();
- original_data_map_.Clear();
- effects_.clear();
- shapes_.clear();
- skinned_shapes_.clear();
- materials_.clear();
- delete collada_zip_archive_;
- collada_zip_archive_ = NULL;
- cull_enabled_ = false;
- cull_front_ = false;
- front_cw_ = false;
- delete instance_root_;
- instance_root_ = NULL;
- base_path_ = FilePath(FilePath::kCurrentDirectory);
- unique_filename_counter_ = 0;
-}
-
-// Import the given COLLADA file or ZIP file under the given parent node.
-// Parameters:
-// filename: The COLLADA or ZIPped COLLADA file to import.
-// parent: The parent node under which the imported nodes will be
-// placed. If NULL, nodes will be placed under the
-// client's root.
-// animation_input: The float parameter used as the input to the animation
-// (if present). This is usually time. This can be null
-// if there is no animation.
-// Returns true on success.
-bool Collada::ImportFile(const FilePath& filename, Transform* parent,
- ParamFloat* animation_input) {
- // Each time we start a new import, we need to clear out data from
- // the last import (if any).
- ClearData();
-
- // Convert the base_path given in the options to an absolute path.
- base_path_ = options_.base_path;
- file_util::AbsolutePath(&base_path_);
-
- bool status = false;
- if (ZipArchive::IsZipFile(FilePathToUTF8(filename))) {
- status = ImportZIP(filename, parent, animation_input);
- } else {
- status = ImportDAE(filename, parent, animation_input);
- }
-
- if (!status) {
- // TODO(o3d): this could probably be the original URI instead of some
- // filename in the temp folder.
- O3D_ERROR(service_locator_) << "Unable to import: "
- << FilePathToUTF8(filename).c_str();
- }
-
- return status;
-}
-
-// Imports the given ZIP file into the given client.
-// Parameters: see Import() above.
-// Returns true on success.
-bool Collada::ImportZIP(const FilePath& filename, Transform* parent,
- ParamFloat* animation_input) {
- // This uses minizip, which avoids decompressing the zip archive to a
- // temp directory...
- //
- bool status = false;
- int result = 0;
-
- String filename_str = FilePathToUTF8(filename);
- collada_zip_archive_ = new ColladaZipArchive(filename_str, &result);
-
- if (result == UNZ_OK) {
- FCollada::Initialize();
- FCDocument* doc = FCollada::NewTopDocument();
-
- if (doc) {
- std::string model_path = collada_zip_archive_->GetColladaPath().c_str();
-
- size_t doc_buffer_size = 0;
- char *doc_buffer = collada_zip_archive_->GetFileData(model_path,
- &doc_buffer_size);
-
- if (doc_buffer && doc_buffer_size > 0) {
- DLOG(INFO) << "Loading Collada model \""
- << model_path << "\" from zip file \""
- << filename_str << "\"";
-
- std::wstring model_path_w = UTF8ToWide(model_path);
-
- bool fc_status = FCollada::LoadDocumentFromMemory(model_path_w.c_str(),
- doc,
- doc_buffer,
- doc_buffer_size);
-
-
- if (fc_status) {
- if (options_.condition_document) {
- ColladaConditioner conditioner(service_locator_);
- if (conditioner.ConditionDocument(doc, collada_zip_archive_)) {
- status = ImportDAEDocument(doc,
- fc_status,
- parent,
- animation_input);
- }
- } else {
- status = ImportDAEDocument(doc, fc_status, parent, animation_input);
- }
- }
- }
- doc->Release();
- }
- FCollada::Release();
- }
-
- if (!status) {
- delete collada_zip_archive_;
- collada_zip_archive_ = NULL;
- }
-
- return status;
-}
-
-// Imports the given COLLADA file (.DAE) into the given pack.
-// Parameters:
-// see Import() above.
-// Returns:
-// true on success.
-bool Collada::ImportDAE(const FilePath& filename,
- Transform* parent,
- ParamFloat* animation_input) {
- if (!parent) {
- return false;
- }
- bool status = false;
- FCollada::Initialize();
- FCDocument* doc = FCollada::NewTopDocument();
- if (doc) {
- std::wstring filename_w = FilePathToWide(filename);
- bool fc_status = FCollada::LoadDocumentFromFile(doc, filename_w.c_str());
- if (options_.condition_document) {
- ColladaConditioner conditioner(service_locator_);
- if (conditioner.ConditionDocument(doc, NULL)) {
- status = ImportDAEDocument(doc, fc_status, parent, animation_input);
- }
- } else {
- status = ImportDAEDocument(doc, fc_status, parent, animation_input);
- }
- doc->Release();
- }
- FCollada::Release();
- return status;
-}
-
-// Imports the given FCDocument document (already loaded) into the given pack.
-// Returns:
-// true on success.
-bool Collada::ImportDAEDocument(FCDocument* doc,
- bool fc_status,
- Transform* parent,
- ParamFloat* animation_input) {
- if (!parent) {
- return false;
- }
- bool status = false;
- if (doc) {
- if (fc_status) {
- Vector3 up_axis = options_.up_axis;
- FMVector3 up(up_axis.getX(), up_axis.getY(), up_axis.getZ());
- // Transform the document to the given up vector
-
- FCDocumentTools::StandardizeUpAxisAndLength(doc, up);
-
- // Import all the textures in the file. Even if they are not used by
- // materials or models the user put them in the file and might need them
- // at runtime.
- //
- // TODO(o3d): Add option to skip this step if user just wants what's
- // actually used by models. The rest of the code already deals with this.
- FCDImageLibrary* image_library = doc->GetImageLibrary();
- for (uint32 i = 0; i < image_library->GetEntityCount(); i++) {
- FCDEntity* entity = image_library->GetEntity(i);
- LOG_ASSERT(entity);
- LOG_ASSERT(entity->GetType() == FCDEntity::IMAGE);
- FCDImage* image = down_cast<FCDImage*>(entity);
- BuildTextureFromImage(image);
- }
-
- // Import all the materials in the file. Even if they are not used by
- // models the user put them in the file and might need them at runtime.
- //
- // TODO(o3d): Add option to skip this step if user just wants what's
- // actually used by models. The rest of the code already deals with this.
- FCDMaterialLibrary* material_library = doc->GetMaterialLibrary();
- for (uint32 i = 0; i < material_library->GetEntityCount(); i++) {
- FCDEntity* entity = material_library->GetEntity(i);
- LOG_ASSERT(entity);
- LOG_ASSERT(entity->GetType() == FCDEntity::MATERIAL);
- FCDMaterial* collada_material = down_cast<FCDMaterial*>(entity);
- BuildMaterial(doc, collada_material);
- }
-
- // Import the scene objects, starting at the root.
- FCDSceneNode* scene = doc->GetVisualSceneInstance();
- if (scene) {
- instance_root_ = CreateInstanceTree(scene);
- if (ImportTree(instance_root_, parent, animation_input)) {
- if (ImportTreeInstances(doc, instance_root_)) {
- status = true;
- }
- }
- delete instance_root_;
- instance_root_ = NULL;
- }
- }
- }
- return status;
-}
-
-namespace {
-
-Curve::Infinity ConvertInfinity(FUDaeInfinity::Infinity infinity) {
- switch (infinity) {
- case FUDaeInfinity::LINEAR :
- return Curve::LINEAR;
- case FUDaeInfinity::CYCLE :
- return Curve::CYCLE;
- case FUDaeInfinity::CYCLE_RELATIVE :
- return Curve::CYCLE_RELATIVE;
- case FUDaeInfinity::OSCILLATE :
- return Curve::OSCILLATE;
- default:
- return Curve::CONSTANT;
- }
-}
-
-StepCurveKey* BuildStepKey(Curve* curve, FCDAnimationKey* fcd_key,
- float output_scale) {
- StepCurveKey* key = curve->Create<StepCurveKey>();
- key->SetInput(fcd_key->input);
- key->SetOutput(fcd_key->output * output_scale);
- return key;
-}
-
-LinearCurveKey* BuildLinearKey(Curve* curve, FCDAnimationKey* fcd_key,
- float output_scale) {
- LinearCurveKey* key = curve->Create<LinearCurveKey>();
- key->SetInput(fcd_key->input);
- key->SetOutput(fcd_key->output * output_scale);
- return key;
-}
-
-BezierCurveKey* BuildBezierKey(Curve* curve, FCDAnimationKeyBezier* fcd_key,
- float output_scale) {
- BezierCurveKey* key = curve->Create<BezierCurveKey>();
- key->SetInput(fcd_key->input);
- key->SetOutput(fcd_key->output * output_scale);
- Float2 in_tangent = FMVector2ToFloat2(fcd_key->inTangent);
- in_tangent[1] *= output_scale;
- key->SetInTangent(in_tangent);
- Float2 out_tangent = FMVector2ToFloat2(fcd_key->outTangent);
- out_tangent[1] *= output_scale;
- key->SetOutTangent(out_tangent);
- return key;
-}
-
-void BindParams(ParamObject* input_object, const char* input_param_name,
- ParamObject* output_object, const char* output_param_name) {
- Param* input_param = input_object->GetUntypedParam(input_param_name);
- DCHECK(input_param);
-
- Param* output_param = output_object->GetUntypedParam(output_param_name);
- DCHECK(output_param);
-
- bool ok = input_param->Bind(output_param);
- DCHECK_EQ(ok, true);
-}
-
-void BindParams(ParamObject* input_object, const char* input_param_name,
- Param* output_param) {
- Param* input_param = input_object->GetUntypedParam(input_param_name);
- DCHECK(input_param);
-
- bool ok = input_param->Bind(output_param);
- DCHECK_EQ(ok, true);
-}
-
-void BindParams(Param* input_param,
- ParamObject* output_object, const char* output_param_name) {
- Param* output_param = output_object->GetUntypedParam(output_param_name);
- DCHECK(output_param);
-
- bool ok = input_param->Bind(output_param);
- DCHECK_EQ(ok, true);
-}
-
-// Runs effect_string through the filter, replacing it in place.
-bool ConvertCgToGlsl(const FilePath& converter, String* effect_string) {
- FilePath temporary_file_name;
- FILE* temporary_file = file_util::CreateAndOpenTemporaryFile(
- &temporary_file_name);
- if (!temporary_file)
- return false;
-
- fwrite(effect_string->c_str(), 1, effect_string->length(), temporary_file);
- effect_string->clear();
- file_util::CloseFile(temporary_file);
-
-#if defined(OS_WIN)
- // Assumes python.exe is in PATH. Doesn't seem there's an easy way
- // to test whether it is without launching a process.
- FilePath python(FILE_PATH_LITERAL("python.exe"));
- CommandLine cmd_line(python);
- cmd_line.AppendLooseValue(FilePathToWide(converter));
-#else
- CommandLine cmd_line(converter);
-#endif
-
- cmd_line.AppendLooseValue(L"-i");
- std::wstring temporary_file_string =
- o3d::FilePathToWide(temporary_file_name);
-#if defined(OS_WIN)
- // Quote to be safe. Note that this breaks on POSIX platforms.
- std::wstring quote(L"\"");
- temporary_file_string =
- quote + temporary_file_string + quote;
-#endif
- cmd_line.AppendLooseValue(temporary_file_string);
- bool rc = ::base::GetAppOutput(cmd_line, effect_string);
-
- file_util::Delete(temporary_file_name, false);
- return rc;
-}
-} // namespace anonymous
-
-bool Collada::BuildFloatAnimation(ParamFloat* result,
- FCDAnimated* animated,
- const char* qualifier,
- ParamFloat* animation_input,
- float output_scale,
- float default_value) {
- if (animated != NULL) {
- FCDAnimationCurve* fcd_curve = animated->FindCurve(qualifier);
- if (fcd_curve != NULL) {
- FunctionEval* function_eval = pack_->Create<FunctionEval>();
- BindParams(function_eval, FunctionEval::kInputParamName, animation_input);
-
- Curve* curve = pack_->Create<Curve>();
- function_eval->set_function_object(curve);
-
- curve->set_pre_infinity(ConvertInfinity(fcd_curve->GetPreInfinity()));
- curve->set_post_infinity(ConvertInfinity(fcd_curve->GetPostInfinity()));
-
- for (unsigned int i = 0; i != fcd_curve->GetKeyCount(); ++i) {
- FCDAnimationKey* fcd_key = fcd_curve->GetKey(i);
- switch (fcd_key->interpolation) {
- case FUDaeInterpolation::STEP:
- BuildStepKey(curve, fcd_key, output_scale);
- break;
- case FUDaeInterpolation::BEZIER:
- BuildBezierKey(curve, static_cast<FCDAnimationKeyBezier*>(fcd_key),
- output_scale);
- break;
- default:
- BuildLinearKey(curve, fcd_key, output_scale);
- break;
- }
- }
-
- BindParams(result, function_eval, FunctionEval::kOutputParamName);
- return true;
- }
- }
-
- result->set_value(default_value * output_scale);
- return false;
-}
-
-bool Collada::BuildFloat3Animation(ParamFloat3* result, FCDAnimated* animated,
- ParamFloat* animation_input,
- const Float3& default_value) {
- ParamOp3FloatsToFloat3* to_float3 =
- pack_->Create<ParamOp3FloatsToFloat3>();
-
- static const char* const kQualifiers[3] = { ".X", ".Y", ".Z" };
- static const char* const kInputs[3] = {
- ParamOp3FloatsToFloat3::kInput0ParamName,
- ParamOp3FloatsToFloat3::kInput1ParamName,
- ParamOp3FloatsToFloat3::kInput2ParamName,
- };
- bool any_animated = false;
- for (int i = 0; i != 3; ++i) {
- ParamFloat* to_float3_input = to_float3->GetParam<ParamFloat>(kInputs[i]);
- any_animated |= BuildFloatAnimation(to_float3_input,
- animated, kQualifiers[i],
- animation_input, 1.0f,
- default_value[i]);
- }
-
- if (any_animated) {
- BindParams(result, to_float3, ParamOp3FloatsToFloat3::kOutputParamName);
- return true;
- } else {
- pack_->RemoveObject(to_float3);
- result->set_value(default_value);
- return false;
- }
-}
-
-ParamMatrix4* Collada::BuildComposition(FCDTMatrix* transform,
- ParamMatrix4* input_matrix,
- ParamFloat* animation_input) {
- Matrix4Composition* composition = pack_->Create<Matrix4Composition>();
- Matrix4 matrix = FMMatrix44ToMatrix4(transform->ToMatrix());
-
- ParamOp16FloatsToMatrix4* to_matrix4 =
- pack_->Create<ParamOp16FloatsToMatrix4>();
- bool any_animated = false;
- for (int i = 0; i != 16; ++i) {
- int row = i / 4;
- int column = i % 4;
-
- std::stringstream input_name;
- input_name << "input" << i;
- ParamFloat* to_matrix4_input = to_matrix4->GetParam<ParamFloat>(
- input_name.str().c_str());
-
- std::stringstream qualifier;
- qualifier << "(" << row << ")" << "(" << column << ")";
- any_animated |= BuildFloatAnimation(to_matrix4_input,
- transform->GetAnimated(),
- qualifier.str().c_str(),
- animation_input, 1.0f,
- matrix[row][column]);
- }
-
- if (any_animated) {
- BindParams(composition, Matrix4Composition::kLocalMatrixParamName,
- to_matrix4, ParamOp16FloatsToMatrix4::kOutputParamName);
- } else {
- pack_->RemoveObject(to_matrix4);
- composition->set_local_matrix(matrix);
- }
-
- BindParams(composition, Matrix4Composition::kInputMatrixParamName,
- input_matrix);
- return composition->GetParam<ParamMatrix4>(
- Matrix4Composition::kOutputMatrixParamName);
-}
-
-ParamMatrix4* Collada::BuildComposition(const Matrix4& matrix,
- ParamMatrix4* input_matrix) {
- Matrix4Composition* composition = pack_->Create<Matrix4Composition>();
- composition->set_local_matrix(matrix);
- BindParams(composition, Matrix4Composition::kInputMatrixParamName,
- input_matrix);
- return composition->GetParam<ParamMatrix4>(
- Matrix4Composition::kOutputMatrixParamName);
-}
-
-ParamMatrix4* Collada::BuildTranslation(FCDTTranslation* transform,
- ParamMatrix4* input_matrix,
- ParamFloat* animation_input) {
- Matrix4Translation* translation = pack_->Create<Matrix4Translation>();
-
- ParamFloat3* animated_param = translation->GetParam<ParamFloat3>(
- Matrix4Translation::kTranslationParamName);
- Vector3 default_value = FMVector3ToVector3(transform->GetTranslation());
- BuildFloat3Animation(animated_param, transform->GetAnimated(),
- animation_input, Float3(default_value));
-
- BindParams(translation, Matrix4Composition::kInputMatrixParamName,
- input_matrix);
- return translation->GetParam<ParamMatrix4>(
- Matrix4Composition::kOutputMatrixParamName);
-}
-
-ParamMatrix4* Collada::BuildRotation(FCDTRotation* transform,
- ParamMatrix4* input_matrix,
- ParamFloat* animation_input) {
- Matrix4AxisRotation* rotation = pack_->Create<Matrix4AxisRotation>();
-
- ParamFloat3* animated_axis = rotation->GetParam<ParamFloat3>(
- Matrix4AxisRotation::kAxisParamName);
- Vector3 default_axis = FMVector3ToVector3(transform->GetAxis());
- BuildFloat3Animation(animated_axis, transform->GetAnimated(),
- animation_input, Float3(default_axis));
-
- ParamFloat* animated_angle = rotation->GetParam<ParamFloat>(
- Matrix4AxisRotation::kAngleParamName);
- float default_angle = transform->GetAngle();
- BuildFloatAnimation(animated_angle,
- transform->GetAnimated(),
- ".ANGLE",
- animation_input,
- o3d::kPi / 180.0f,
- default_angle);
-
- BindParams(rotation, Matrix4Composition::kInputMatrixParamName, input_matrix);
- return rotation->GetParam<ParamMatrix4>(
- Matrix4Composition::kOutputMatrixParamName);
-}
-
-ParamMatrix4* Collada::BuildScaling(FCDTScale* transform,
- ParamMatrix4* input_matrix,
- ParamFloat* animation_input) {
- Matrix4Scale* scaling = pack_->Create<Matrix4Scale>();
-
- ParamFloat3* animated_param = scaling->GetParam<ParamFloat3>(
- Matrix4Scale::kScaleParamName);
- Vector3 default_value = FMVector3ToVector3(transform->GetScale());
- BuildFloat3Animation(animated_param, transform->GetAnimated(),
- animation_input, Float3(default_value));
-
- BindParams(scaling, Matrix4Composition::kInputMatrixParamName, input_matrix);
- return scaling->GetParam<ParamMatrix4>(
- Matrix4Composition::kOutputMatrixParamName);
-}
-
-// Builds a Transform node corresponding to the transform elements of
-// a given node. All transformations (rotation, translation, scale,
-// etc) are collapsed into a single Transform.
-// Parameters:
-// node: The FCollada node whose transforms are replicated.
-// Return value:
-// The new Transform.
-Transform* Collada::BuildTransform(FCDSceneNode* node,
- Transform* parent_transform,
- ParamFloat* animation_input) {
- const wchar_t* name = node->GetName().c_str();
-
- String name_utf8 = WideToUTF8(name);
-
- Transform* transform = pack_->Create<Transform>();
- transform->set_name(name_utf8);
- transform->SetParent(parent_transform);
-
- bool any_animated = false;
- for (size_t i = 0; i < node->GetTransformCount(); i++) {
- FCDTransform* fcd_transform = node->GetTransform(i);
- any_animated |= fcd_transform->IsAnimated();
- }
-
- if (any_animated) {
- // At least one of the collada transforms is animated so construct the
- // transform hierarchy and connect its output to the local_matrix for
- // this node.
- ParamMatrix4* input_matrix = NULL;
- for (size_t i = 0; i < node->GetTransformCount(); i++) {
- FCDTransform* fcd_transform = node->GetTransform(i);
- switch (fcd_transform->GetType()) {
- case FCDTransform::MATRIX :
- input_matrix = BuildComposition(
- static_cast<FCDTMatrix*>(fcd_transform),
- input_matrix, animation_input);
- break;
- case FCDTransform::TRANSLATION:
- input_matrix = BuildTranslation(
- static_cast<FCDTTranslation*>(fcd_transform),
- input_matrix, animation_input);
- break;
- case FCDTransform::ROTATION:
- input_matrix = BuildRotation(
- static_cast<FCDTRotation*>(fcd_transform),
- input_matrix, animation_input);
- break;
- case FCDTransform::SCALE:
- input_matrix = BuildScaling(
- static_cast<FCDTScale*>(fcd_transform),
- input_matrix, animation_input);
- break;
- default:
- input_matrix = BuildComposition(
- FMMatrix44ToMatrix4(fcd_transform->ToMatrix()),
- input_matrix);
- break;
- }
- }
-
- ParamMatrix4* local_matrix_param = transform->GetParam<ParamMatrix4>(
- Transform::kLocalMatrixParamName);
- local_matrix_param->Bind(input_matrix);
- } else {
- // None of collada transforms are animated so just compute the
- // overall transform and set it as the value of the local_matrix
- // for this node. This saves memory and improves performance but
- // more importantly it will allow JavaScript code to set the value of
- // the local_matrix directly without first having to unbind it.
- Matrix4 local_matrix(Matrix4::identity());
- for (size_t i = 0; i < node->GetTransformCount(); i++) {
- FCDTransform* fcd_transform = node->GetTransform(i);
- local_matrix *= FMMatrix44ToMatrix4(fcd_transform->ToMatrix());
- }
- transform->set_local_matrix(local_matrix);
- }
-
- return transform;
-}
-
-NodeInstance *Collada::CreateInstanceTree(FCDSceneNode *node) {
- NodeInstance *instance = new NodeInstance(node);
- NodeInstance::NodeInstanceList &children = instance->children();
- for (size_t i = 0; i < node->GetChildrenCount(); ++i) {
- FCDSceneNode *child_node = node->GetChild(i);
- NodeInstance *child_instance = CreateInstanceTree(child_node);
- children.push_back(child_instance);
- }
- return instance;
-}
-
-NodeInstance *NodeInstance::FindNodeInTree(FCDSceneNode *node) {
- if (node == node_)
- return this;
- for (unsigned int i = 0; i < children_.size(); ++i) {
- NodeInstance *instance = children_[i]->FindNodeInTree(node);
- if (instance)
- return instance;
- }
- return NULL;
-}
-
-NodeInstance *Collada::FindNodeInstance(FCDSceneNode *node) {
- // First try the fast path, in the case where the node is not instanced more
- // than once.
- NodeInstance *instance = FindNodeInstanceFast(node);
- if (!instance) {
- // If it fails, look in the whole instance tree.
- instance = instance_root_->FindNodeInTree(node);
- }
- return instance;
-}
-
-NodeInstance *Collada::FindNodeInstanceFast(FCDSceneNode *node) {
- if (node == instance_root_->node())
- return instance_root_;
- // If the node is instanced more than once, fail.
- if (node->GetParentCount() != 1)
- return NULL;
- NodeInstance *parent_instance = FindNodeInstanceFast(node->GetParent(0));
- // Look for self in parent's childrens.
- return parent_instance->FindNodeShallow(node);
-}
-
-// Recursively imports a tree of nodes from FCollada, rooted at the
-// given node, into the O3D scene.
-// Parameters:
-// instance: The root NodeInstance from which to import.
-// parent_transform: The parent Transform under which the tree will be placed.
-// animation_input: The float parameter used as the input to the animation
-// (if present). This is usually time. This can be null
-// if there is no animation.
-bool Collada::ImportTree(NodeInstance *instance,
- Transform* parent_transform,
- ParamFloat* animation_input) {
- FCDSceneNode *node = instance->node();
- Transform* transform = BuildTransform(node, parent_transform,
- animation_input);
- instance->set_transform(transform);
-
- // recursively import the rest of the nodes in the tree
- const NodeInstance::NodeInstanceList &children = instance->children();
- for (size_t i = 0; i < children.size(); ++i) {
- if (!ImportTree(children[i], transform, animation_input)) {
- return false;
- }
- }
- return true;
-}
-
-bool Collada::ImportTreeInstances(FCDocument* doc,
- NodeInstance *node_instance) {
- FCDSceneNode *node = node_instance->node();
- // recursively import the rest of the nodes in the tree
- const NodeInstance::NodeInstanceList &children = node_instance->children();
- for (size_t i = 0; i < children.size(); ++i) {
- if (!ImportTreeInstances(doc, children[i])) {
- return false;
- }
- }
-
- Transform* transform = node_instance->transform();
- for (size_t i = 0; i < node->GetInstanceCount(); ++i) {
- FCDEntityInstance* instance = node->GetInstance(i);
- FCDCamera* camera(NULL);
- FCDGeometryInstance* geom_instance(NULL);
-
- LOG_ASSERT(instance != 0);
- // Import each node based on what kind of entity it is
- // TODO(o3d): add more entity types as they are supported
- switch (instance->GetEntityType()) {
- case FCDEntity::CAMERA:
- // camera entity
- camera = down_cast<FCDCamera*>(instance->GetEntity());
- BuildCamera(doc, camera, transform, node);
- break;
- case FCDEntity::GEOMETRY: {
- // geometry entity
- geom_instance = static_cast<FCDGeometryInstance*>(instance);
- Shape* shape = GetShape(doc, geom_instance);
- if (shape) {
- transform->AddShape(shape);
- }
- break;
- }
- case FCDEntity::CONTROLLER: {
- FCDControllerInstance* controller_instance =
- static_cast<FCDControllerInstance*> (instance);
- FCDController* controller =
- static_cast<FCDController*>(controller_instance->GetEntity());
- if (controller) {
- if (controller->IsSkin()) {
- Shape* shape = GetSkinnedShape(doc,
- controller_instance,
- node_instance,
- transform);
- if (shape) {
- transform->AddShape(shape);
- } else {
- return false;
- }
- }
- }
- break;
- }
- default:
- // do nothing
- break;
- }
- }
- return true;
-}
-
-// Converts an FCollada vertex attribute semantic into an O3D
-// vertex attribute semantic. Returns the O3D semantic, or
-// UNKNOWN_SEMANTIC on failure.
-static Stream::Semantic C2G3DSemantic(FUDaeGeometryInput::Semantic semantic) {
- switch (semantic) {
- case FUDaeGeometryInput::POSITION: return Stream::POSITION;
- case FUDaeGeometryInput::VERTEX: return Stream::POSITION;
- case FUDaeGeometryInput::NORMAL: return Stream::NORMAL;
- case FUDaeGeometryInput::TEXTANGENT: return Stream::TANGENT;
- case FUDaeGeometryInput::TEXBINORMAL: return Stream::BINORMAL;
- case FUDaeGeometryInput::TEXCOORD: return Stream::TEXCOORD;
- case FUDaeGeometryInput::COLOR: return Stream::COLOR;
- default: return Stream::UNKNOWN_SEMANTIC;
- }
-}
-
-// Imports information from a Collada camera node and places it in Params of
-// the transform corresponding to the node it's parented under.
-// Parameters:
-// doc: The FCollada document from which to import nodes.
-// camera: The FCDCamera node in question
-// transform: The O3D Transform on which the camera parameters
-// will be created. It cannot be NULL.
-// parent_node: The FCDSceneNode that the parent transform was created
-// from. This node is used to extract possible LookAt
-// elements. It cannot be NULL.
-void Collada::BuildCamera(FCDocument* doc,
- FCDCamera* camera,
- Transform* transform,
- FCDSceneNode* parent_node) {
- LOG_ASSERT(doc && camera && transform && parent_node);
-
- // Create a transform node for the camera
- String camera_name = WideToUTF8(camera->GetName().c_str());
-
- // Tag this node as a camera
- ParamString* param_tag = transform->CreateParam<ParamString>(
- COLLADA_STRING_CONSTANT("tags"));
-
- // Add more tags when required
- param_tag->set_value("camera");
-
- // Create the rest of the params
-
- // Projection type: either 'orthographic' or 'perspective'
- ParamString* param_proj_type =
- transform->CreateParam<ParamString>(
- COLLADA_STRING_CONSTANT("projectionType"));
-
- // Aspect ratio
- float camera_aspect_ratio;
- ParamFloat* param_proj_aspect_ratio =
- transform->CreateParam<ParamFloat>(
- COLLADA_STRING_CONSTANT("projectionAspectRatio"));
-
- // Near/far z-planes
- float camera_near_z, camera_far_z;
- ParamFloat* param_proj_nearz =
- transform->CreateParam<ParamFloat>(
- COLLADA_STRING_CONSTANT("projectionNearZ"));
- ParamFloat* param_proj_farz =
- transform->CreateParam<ParamFloat>(
- COLLADA_STRING_CONSTANT("projectionFarZ"));
-
- // Calculate shared params
- camera_near_z = camera->GetNearZ();
- camera_far_z = camera->GetFarZ();
- param_proj_nearz->set_value(camera_near_z);
- param_proj_farz->set_value(camera_far_z);
-
- if (camera->GetProjectionType() == FCDCamera::ORTHOGRAPHIC) {
- // Orthographic projection
- param_proj_type->set_value("orthographic");
-
- // Additional params
- // Horizontal and vertical magnifications
- ParamFloat* param_proj_mag_x =
- transform->CreateParam<ParamFloat>(
- COLLADA_STRING_CONSTANT("projectionMagX"));
- ParamFloat* param_proj_mag_y =
- transform->CreateParam<ParamFloat>(
- COLLADA_STRING_CONSTANT("projectionMagY"));
-
- // Find aspect ratio and magnifications
- float camera_mag_x, camera_mag_y;
- if (camera->HasHorizontalMag() && camera->HasVerticalMag())
- camera_aspect_ratio = camera->GetMagY() / camera->GetMagX();
- else
- camera_aspect_ratio = camera->GetAspectRatio();
-
- if (camera->HasHorizontalMag())
- camera_mag_x = camera->GetMagX();
- else
- camera_mag_x = camera->GetMagY() * camera_aspect_ratio;
-
- if (camera->HasVerticalMag())
- camera_mag_y = camera->GetMagY();
- else
- camera_mag_y = camera->GetMagX() / camera_aspect_ratio;
-
- // Set the values of the additional params
- param_proj_mag_x->set_value(camera_mag_x);
- param_proj_mag_y->set_value(camera_mag_y);
- param_proj_aspect_ratio->set_value(camera_aspect_ratio);
- } else if (camera->GetProjectionType() == FCDCamera::PERSPECTIVE) {
- // Perspective projection
- param_proj_type->set_value("perspective");
-
- // Additional params
- // Vertical field of view
- ParamFloat* param_proj_fov_y =
- transform->CreateParam<ParamFloat>(
- COLLADA_STRING_CONSTANT("perspectiveFovY"));
-
- // Find aspect ratio and vertical FOV
- float camera_fov_y;
- if (camera->HasHorizontalFov() && camera->HasVerticalFov())
- camera_aspect_ratio = camera->GetFovY() / camera->GetFovX();
- else
- camera_aspect_ratio = camera->GetAspectRatio();
-
- if (camera->HasVerticalFov())
- camera_fov_y = camera->GetFovY();
- else
- camera_fov_y = camera->GetFovX() / camera_aspect_ratio;
-
- // Set the values of the additional params
- param_proj_fov_y->set_value(camera_fov_y);
- param_proj_aspect_ratio->set_value(camera_aspect_ratio);
- }
-
- // Search the FCDSceneNode for a LookAt element, extract the eye, target,
- // and up values and store them as Params on the Transform. If multiple
- // LookAt elements are defined under the parent node, we only pick the first
- // one.
- for (size_t i = 0; i < parent_node->GetTransformCount(); i++) {
- FCDTransform* transform_object = parent_node->GetTransform(i);
- if (transform_object->GetType() == FCDTransform::LOOKAT) {
- FCDTLookAt* look_at = static_cast<FCDTLookAt*>(transform_object);
- FMVector3 position = look_at->GetPosition();
- FMVector3 target = look_at->GetTarget();
- FMVector3 up = look_at->GetUp();
-
- // Get the world matrix of the transform above the camera transform.
- // We use this value to transform the eye, target and up to the world
- // coordinate system so that they can be used directly to make a camera
- // view matrix.
- Matrix4 parent_world = Matrix4::identity();
- if (transform->parent())
- parent_world = transform->parent()->GetUpdatedWorldMatrix();
-
- ParamFloat3* param_eye_position =
- transform->CreateParam<ParamFloat3>(
- COLLADA_STRING_CONSTANT("eyePosition"));
- Vector4 world_eye = parent_world * Point3(position.x,
- position.y,
- position.z);
- param_eye_position->set_value(Float3(world_eye.getX(),
- world_eye.getY(),
- world_eye.getZ()));
-
- ParamFloat3* param_target_position =
- transform->CreateParam<ParamFloat3>(
- COLLADA_STRING_CONSTANT("targetPosition"));
- Vector4 world_target = parent_world * Point3(target.x,
- target.y,
- target.z);
- param_target_position->set_value(Float3(world_target.getX(),
- world_target.getY(),
- world_target.getZ()));
-
- ParamFloat3* param_up_vector =
- transform->CreateParam<ParamFloat3>(
- COLLADA_STRING_CONSTANT("upVector"));
- Vector4 world_up = parent_world * Vector4(up.x, up.y, up.z, 0.0f);
- param_up_vector->set_value(Float3(world_up.getX(),
- world_up.getY(),
- world_up.getZ()));
-
- break;
- }
- }
-}
-
-Shape* Collada::GetShape(FCDocument* doc,
- FCDGeometryInstance* geom_instance) {
- Shape* shape = NULL;
- FCDGeometry* geom = static_cast<FCDGeometry*>(geom_instance->GetEntity());
- if (geom) {
- fm::string geom_id = geom->GetDaeId();
- shape = shapes_[geom_id.c_str()];
- if (!shape) {
- shape = BuildShape(doc, geom_instance, geom, NULL);
- if (!shape)
- return NULL;
- shapes_[geom_id.c_str()] = shape;
- }
- }
- return shape;
-}
-
-Shape* Collada::GetSkinnedShape(FCDocument* doc,
- FCDControllerInstance* instance,
- NodeInstance *parent_node_instance,
- Transform* parent) {
- Shape* shape = NULL;
- FCDController* controller =
- static_cast<FCDController*>(instance->GetEntity());
- if (controller && controller->IsSkin()) {
- fm::string id = controller->GetDaeId();
- shape = skinned_shapes_[id.c_str()];
- if (!shape) {
- shape = BuildSkinnedShape(doc, instance, parent_node_instance, parent);
- if (!shape)
- return NULL;
- skinned_shapes_[id.c_str()] = shape;
- }
- }
- return shape;
-}
-
-// Builds an O3D shape node corresponding to a given FCollada geometry
-// instance.
-Shape* Collada::BuildShape(FCDocument* doc,
- FCDGeometryInstance* geom_instance,
- FCDGeometry* geom,
- TranslationMap* translationMap) {
- Shape* shape = NULL;
- LOG_ASSERT(doc && geom_instance && geom);
- if (geom && geom->IsMesh()) {
- String geom_name = WideToUTF8(geom->GetName().c_str());
- shape = pack_->Create<Shape>();
- shape->set_name(geom_name);
- FCDGeometryMesh* mesh = geom->GetMesh();
- LOG_ASSERT(mesh);
- FCDGeometryPolygonsTools::Triangulate(mesh);
- FCDGeometryPolygonsTools::GenerateUniqueIndices(mesh, NULL, translationMap);
- size_t num_polygons = mesh->GetPolygonsCount();
- size_t num_indices = mesh->GetFaceVertexCount();
- if (num_polygons <= 0 || num_indices <= 0) return NULL;
- FCDGeometrySource* pos_source =
- mesh->FindSourceByType(FUDaeGeometryInput::POSITION);
- if (pos_source == NULL) return NULL;
- size_t num_vertices = pos_source->GetValueCount();
- size_t num_sources = mesh->GetSourceCount();
-
- // Create vertex streams corresponding to the COLLADA sources.
- // These streams are common to all polygon sets in this mesh.
- // The BuildSkinnedShape code assumes this so if you change it you'll need
- // to fix BuildSkinnedShape.
- StreamBank* stream_bank = pack_->Create<StreamBank>();
- stream_bank->set_name(geom_name);
-
- int semantic_counts[Stream::TEXCOORD + 1] = { 0, };
-
- scoped_array<Field*> fields(new Field*[num_sources]);
-
- VertexBuffer* vertex_buffer = pack_->Create<VertexBuffer>();
- vertex_buffer->set_name(geom_name);
-
- // first create all the fields.
- for (size_t s = 0; s < num_sources; ++s) {
- FCDGeometrySource* source = mesh->GetSource(s);
- LOG_ASSERT(source);
- Stream::Semantic semantic = C2G3DSemantic(source->GetType());
- LOG_ASSERT(semantic <= Stream::TEXCOORD);
- if (semantic == Stream::UNKNOWN_SEMANTIC) continue;
-
- // The call to GenerateUniqueIndices() above should have made
- // all sources the same length.
- LOG_ASSERT(source->GetValueCount() == num_vertices);
-
- int stride = source->GetStride();
- if (semantic == Stream::COLOR && stride == 4) {
- fields[s] = vertex_buffer->CreateField(UByteNField::GetApparentClass(),
- stride);
- } else {
- fields[s] = vertex_buffer->CreateField(FloatField::GetApparentClass(),
- stride);
- }
- }
-
- if (!vertex_buffer->AllocateElements(num_vertices)) {
- O3D_ERROR(service_locator_) << "Failed to allocate vertex buffer";
- return NULL;
- }
-
- for (size_t s = 0; s < num_sources; ++s) {
- FCDGeometrySource* source = mesh->GetSource(s);
- LOG_ASSERT(source);
- Stream::Semantic semantic = C2G3DSemantic(source->GetType());
- LOG_ASSERT(semantic <= Stream::TEXCOORD);
- if (semantic == Stream::UNKNOWN_SEMANTIC) continue;
- int stride = source->GetStride();
-
- const float* source_data = source->GetData();
- if (semantic == Stream::TANGENT || semantic == Stream::BINORMAL) {
- // FCollada uses the convention that the tangent points
- // along -u and the binormal along -v in model space.
- // Convert to the more common convention where the tangent
- // points along +u and the binormal along +v. This is what, for
- // example, tools that convert height maps to normal maps tend to
- // assume. It is also what the O3D shaders assume.
- size_t num_values = source->GetDataCount();
- scoped_array<float>values(new float[num_values]);
- for (size_t i = 0; i < num_values ; ++i) {
- values[i] = -source_data[i];
- }
- fields[s]->SetFromFloats(&values[0], stride, 0, num_vertices);
- } else {
- fields[s]->SetFromFloats(source_data, stride, 0, num_vertices);
- }
-
- stream_bank->SetVertexStream(semantic, semantic_counts[semantic],
- fields[s], 0);
- // NOTE: This doesn't really seem like the correct thing to do but I'm not
- // sure we have enough info to do the correct thing. The issue is we
- // need to connect these streams to the shader, the shader needs to know
- // which streams go with which varying parameters but for the standard
- // collada materials I don't think any such information is available.
- ++semantic_counts[semantic];
- }
-
- for (size_t p = 0; p < num_polygons; ++p) {
- FCDGeometryPolygons* polys = mesh->GetPolygons(p);
- FCDGeometryPolygonsInput* input = polys->GetInput(0);
-
- size_t size = input->GetIndexCount();
- size_t vertices_per_primitive = 0;
- Primitive::PrimitiveType primitive_type;
- switch (polys->GetPrimitiveType()) {
- case FCDGeometryPolygons::POLYGONS:
- vertices_per_primitive = 3;
- primitive_type = Primitive::TRIANGLELIST;
- break;
- case FCDGeometryPolygons::LINES:
- vertices_per_primitive = 2;
- primitive_type = Primitive::LINELIST;
- break;
- default:
- // unsupported geometry type; skip it
- continue;
- }
-
- // If there are no vertices, don't make this primitive.
- if (size == 0) continue;
-
- // If we don't have a multiple of the verts-per-primitive, bail now.
- if (size % vertices_per_primitive != 0) {
- O3D_ERROR(service_locator_) << "Geometry \"" << geom_name
- << "\" contains " << size
- << " vertices, which is not a multiple of "
- << vertices_per_primitive << "; skipped";
- continue;
- }
-
- // Get the material for this polygon set.
- Material* material = NULL;
- FCDMaterialInstance* mat_instance = geom_instance->FindMaterialInstance(
- polys->GetMaterialSemantic());
- if (mat_instance) {
- FCDMaterial* collada_material = mat_instance->GetMaterial();
- material = BuildMaterial(doc, collada_material);
- }
- if (!material) {
- material = GetDummyMaterial();
- }
- // Create an index buffer for this group of polygons.
-
- String primitive_name(geom_name + "|" + material->name());
-
- IndexBuffer* indexBuffer = pack_->Create<IndexBuffer>();
- indexBuffer->set_name(primitive_name);
- if (!indexBuffer->AllocateElements(size)) {
- O3D_ERROR(service_locator_) << "Failed to allocate index buffer.";
- return NULL;
- }
- indexBuffer->index_field()->SetFromUInt32s(input->GetIndices(), 1, 0,
- size);
-
- // Create a primitive for this group of polygons.
- Primitive* primitive = pack_->Create<Primitive>();
- primitive->set_name(primitive_name);
-
- primitive->set_material(material);
-
- primitive->SetOwner(shape);
- primitive->set_primitive_type(primitive_type);
- size_t num_prims = size / vertices_per_primitive;
- primitive->set_number_primitives(static_cast<unsigned int>(num_prims));
- primitive->set_number_vertices(static_cast<unsigned int>(num_vertices));
-
- // Set the index buffer for this primitive.
- primitive->set_index_buffer(indexBuffer);
-
- // Set the vertex streams for this primitive to the common set for this
- // mesh.
- primitive->set_stream_bank(stream_bank);
- }
- }
- return shape;
-}
-
-Shape* Collada::BuildSkinnedShape(FCDocument* doc,
- FCDControllerInstance* instance,
- NodeInstance *parent_node_instance,
- Transform* parent) {
- // TODO(o3d): Handle chained controllers. Morph->Skin->...
- // TODO(gman): Change this to correctly create the skin, separate from
- // ParamArray and SkinEval so that we can support instanced skins.
- Shape* shape = NULL;
- LOG_ASSERT(doc && instance);
- FCDController* controller =
- static_cast<FCDController*>(instance->GetEntity());
- if (controller && controller->IsSkin()) {
- FCDSkinController* skin_controller = controller->GetSkinController();
- TranslationMap translationMap;
- shape = BuildShape(doc,
- instance,
- controller->GetBaseGeometry(),
- &translationMap);
- if (!shape) {
- return NULL;
- }
-
- // Convert the translation table to new->old map.
- size_t num_vertices = 0;
- std::vector<unsigned> new_to_old_indices;
- {
- // walk the map once to figure out the number of vertices.
- TranslationMap::iterator end = translationMap.end();
- for (TranslationMap::iterator it = translationMap.begin();
- it != end;
- ++it) {
- num_vertices += it->second.size();
- }
-
- // Init our array to UINT_MAX so we can check for collisions
- new_to_old_indices.resize(num_vertices, UINT_MAX);
-
- // walk the map again and fill out our remap table.
- for (TranslationMap::iterator it = translationMap.begin();
- it != end;
- ++it) {
- const UInt32List& intlist = it->second;
- for (size_t gg = 0; gg < intlist.size(); ++gg) {
- unsigned new_index = intlist[gg];
- LOG_ASSERT(new_to_old_indices.at(new_index) == UINT_MAX);
- new_to_old_indices[new_index] = it->first;
- }
- }
- }
-
- // There's a BIG assumption here. We assume the first primitive on the shape
- // has vertex buffers that are shared on all the primitives under this shape
- // such that we only need to copy the first primitive's vertex buffers to
- // skin everything. This is actually what was BuildShape was doing at the
- // time this code was written.
- const ElementRefArray& elements = shape->GetElementRefs();
- if (elements.empty()) {
- return NULL;
- }
- // check that they all use the same StreamBank and are all Primitives
- for (unsigned ii = 0; ii < elements.size(); ++ii) {
- if (!elements[ii]->IsA(Primitive::GetApparentClass())) {
- O3D_ERROR(service_locator_)
- << "Element in Shape '" << shape->name() << "' is not a Primitive.";
- return NULL;
- }
- if (down_cast<Primitive*>(elements[ii].Get())->stream_bank() !=
- down_cast<Primitive*>(elements[0].Get())->stream_bank()) {
- O3D_ERROR(service_locator_)
- << "More than one StreamBank in Shape '" << shape->name() << "'.";
- return NULL;
- }
- }
- Primitive* primitive = down_cast<Primitive*>(elements[0].Get());
-
- String controller_name = WideToUTF8(controller->GetName().c_str());
-
- ParamArray* matrices = pack_->Create<ParamArray>();
- Skin* skin = pack_->Create<Skin>();
- skin->set_name(controller_name);
- SkinEval* skin_eval = pack_->Create<SkinEval>();
- skin_eval->set_name(controller_name);
-
- skin_eval->set_skin(skin);
- skin_eval->set_matrices(matrices);
- skin_eval->GetParam<ParamMatrix4>(SkinEval::kBaseParamName)->Bind(
- parent->GetParam<ParamMatrix4>(Transform::kWorldMatrixParamName));
-
- // Bind bones to matrices
- size_t num_bones = instance->GetJointCount();
- if (num_bones > 0) {
- matrices->CreateParam<ParamMatrix4>(num_bones - 1);
- for (size_t ii = 0; ii < num_bones; ++ii) {
- FCDSceneNode* node = instance->GetJoint(ii);
- LOG_ASSERT(node);
- // Note: in case of instancing, the intended instance is ill-defined,
- // but that is a problem in the Collada document itself. So we'll assume
- // the file is somewhat well defined.
- // First we try the single instance case.
- NodeInstance *node_instance = FindNodeInstanceFast(node);
- if (!node_instance) {
- // Second we try nodes underneath the same parent as the controller
- // instance. Max and Maya seem to do that.
- node_instance = parent_node_instance->FindNodeInTree(node);
- }
- if (!node_instance) {
- // Third we try in the entire tree.
- node_instance = instance_root_->FindNodeInTree(node);
- }
- if (!node_instance) {
- String bone_name = WideToUTF8(node->GetName().c_str());
- O3D_ERROR(service_locator_)
- << "Could not find node instance for bone " << bone_name.c_str();
- continue;
- }
- Transform* bone = node_instance->transform();
- LOG_ASSERT(bone);
- matrices->GetUntypedParam(ii)->Bind(
- bone->GetUntypedParam(Transform::kWorldMatrixParamName));
- }
- }
-
- Matrix4 bind_shape_matrix(
- FMMatrix44ToMatrix4(skin_controller->GetBindShapeTransform()));
- Matrix4 inverse_bind_shape_matrix(inverse(bind_shape_matrix));
-
- // Get the bind pose inverse matrices
- LOG_ASSERT(num_bones == skin_controller->GetJointCount());
- for (size_t ii = 0; ii < num_bones; ++ii) {
- FCDSkinControllerJoint* joint = skin_controller->GetJoint(ii);
- skin->SetInverseBindPoseMatrix(
- ii, FMMatrix44ToMatrix4(joint->GetBindPoseInverse()));
- }
-
- // Get Influences.
- for (size_t ii = 0; ii < num_vertices; ++ii) {
- unsigned old_index = new_to_old_indices[ii];
- FCDSkinControllerVertex* vertex =
- skin_controller->GetVertexInfluence(old_index);
- Skin::Influences influences;
- size_t num_influences = vertex->GetPairCount();
- for (size_t jj = 0; jj < num_influences; ++jj) {
- FCDJointWeightPair* weight_pair = vertex->GetPair(jj);
- influences.push_back(Skin::Influence(weight_pair->jointIndex,
- weight_pair->weight));
- }
- skin->SetVertexInfluences(ii, influences);
- }
-
- Matrix4 matrix(bind_shape_matrix);
-
- // Copy shape->primitive buffers.
- // Here we need to also split the original vertex buffer. The issue is
- // the original VertexBuffer might contain POSITION, NORMAL, TEXCOORD,
- // COLOR. Of those, only POSITION and NORMAL are copied to the SourceBuffer.
- // The VertexBuffer still contains POSITON, NORMAL, TEXCOORD, and COLOR so
- // two issues come up
- //
- // 1) If we serialize that VertexBuffer, POSITION and NORMAL are stored
- // twice. Once in the SourceBuffer, again in the VertexBuffer. That's a lot
- // of data to download just to throw it away.
- //
- // 2) If we want to instance the skin we'll need to make a new VertexBuffer
- // so we can store the skinned vertices for the second instance. But we'd
- // like to share the COLOR and TEXCOORDS. To do that they need to be in
- // a separate VertexBuffer.
- StreamBank* old_stream_bank = primitive->stream_bank();
- StreamBank* new_stream_bank = pack_->Create<StreamBank>();
- new_stream_bank->set_name(String("skinned_") + old_stream_bank->name());
- Buffer* old_buffer = NULL;
- SourceBuffer* source_buffer = pack_->Create<SourceBuffer>();
- VertexBuffer* shared_buffer = pack_->Create<VertexBuffer>();
- DestinationBuffer* dest_buffer = pack_->Create<DestinationBuffer>();
- const StreamParamVector& source_stream_params =
- old_stream_bank->vertex_stream_params();
- std::vector<Field*> source_fields(source_stream_params.size(), NULL);
- std::vector<Field*> dest_fields(source_stream_params.size(), NULL);
- // first make all the fields.
- for (unsigned ii = 0; ii < source_stream_params.size(); ++ii) {
- const Stream& source_stream = source_stream_params[ii]->stream();
- const Field& field = source_stream.field();
- if (old_buffer == NULL) {
- old_buffer = field.buffer();
- } else if (old_buffer != field.buffer()) {
- O3D_ERROR(service_locator_)
- << "More than 1 buffer used by StreamBank '"
- << old_stream_bank->name().c_str()
- << "' which the collada importer does not currently support";
- }
- bool copied = false;
- if (field.IsA(FloatField::GetApparentClass()) &&
- (field.num_components() == 3 ||
- field.num_components() == 4)) {
- switch (source_stream.semantic()) {
- case Stream::POSITION:
- case Stream::NORMAL:
- case Stream::BINORMAL:
- case Stream::TANGENT: {
- copied = true;
- unsigned num_source_components = field.num_components();
- unsigned num_source_vertices = source_stream.GetMaxVertices();
- if (num_source_vertices != num_vertices) {
- O3D_ERROR(service_locator_)
- << "Number of vertices in stream_bank '"
- << old_stream_bank->name().c_str()
- << "' does not equal the number of vertices in the Skin '"
- << skin->name().c_str() << "'";
- return NULL;
- }
- source_fields[ii] = source_buffer->CreateField(
- FloatField::GetApparentClass(), num_source_components);
- DCHECK(source_fields[ii]);
- dest_fields[ii] = dest_buffer->CreateField(
- FloatField::GetApparentClass(), num_source_components);
- DCHECK(dest_fields[ii]);
- if (!new_stream_bank->SetVertexStream(
- source_stream.semantic(),
- source_stream.semantic_index(),
- dest_fields[ii],
- 0)) {
- O3D_ERROR(service_locator_)
- << "could not SetVertexStream on StreamBank '"
- << new_stream_bank->name() << "'";
- return NULL;
- }
- }
- default:
- // do nothing
- break;
- }
- }
- if (!copied) {
- // It's a shared field, copy it to the shared buffer.
- source_fields[ii] = shared_buffer->CreateField(field.GetClass(),
- field.num_components());
- new_stream_bank->SetVertexStream(source_stream.semantic(),
- source_stream.semantic_index(),
- source_fields[ii],
- 0);
- }
- }
-
- if (!source_buffer->AllocateElements(num_vertices) ||
- !shared_buffer->AllocateElements(num_vertices) ||
- !dest_buffer->AllocateElements(num_vertices)) {
- O3D_ERROR(service_locator_)
- << "Failed to allocate destination vertex buffer";
- return NULL;
- }
-
- for (unsigned ii = 0; ii < source_stream_params.size(); ++ii) {
- const Stream& source_stream = source_stream_params[ii]->stream();
- const Field& field = source_stream.field();
- bool copied = false;
- if (field.IsA(FloatField::GetApparentClass()) &&
- (field.num_components() == 3 ||
- field.num_components() == 4)) {
- switch (source_stream.semantic()) {
- case Stream::POSITION:
- case Stream::NORMAL:
- case Stream::BINORMAL:
- case Stream::TANGENT: {
- copied = true;
- unsigned num_source_components = field.num_components();
- Field* source_field = source_fields[ii];
-
- std::vector<float> data(num_vertices * num_source_components);
- field.GetAsFloats(0, &data[0], num_source_components,
- num_vertices);
- // TODO(o3d): Remove this matrix multiply. I don't think it is
- // needed.
- for (unsigned vv = 0; vv < num_vertices; ++vv) {
- float* values = &data[vv * num_source_components];
- switch (field.num_components()) {
- case 3: {
- if (source_stream.semantic() == Stream::POSITION) {
- Vector4 result(matrix * Point3(values[0],
- values[1],
- values[2]));
- values[0] = result.getElem(0);
- values[1] = result.getElem(1);
- values[2] = result.getElem(2);
- } else {
- Vector4 result(matrix * Vector3(values[0],
- values[1],
- values[2]));
- values[0] = result.getElem(0);
- values[1] = result.getElem(1);
- values[2] = result.getElem(2);
- }
- break;
- }
- case 4: {
- Vector4 result(matrix * Vector4(values[0],
- values[1],
- values[2],
- values[3]));
- values[0] = result.getElem(0);
- values[1] = result.getElem(1);
- values[2] = result.getElem(2);
- values[3] = result.getElem(3);
- break;
- }
- }
- }
- source_field->SetFromFloats(&data[0], num_source_components, 0,
- num_vertices);
- // Bind streams
- skin_eval->SetVertexStream(source_stream.semantic(),
- source_stream.semantic_index(),
- source_field,
- 0);
- new_stream_bank->BindStream(skin_eval,
- source_stream.semantic(),
- source_stream.semantic_index());
- break;
- }
- default:
- // do nothing
- break;
- }
- }
- if (!copied) {
- Field* source_field = source_fields[ii];
- source_field->Copy(field);
- }
- }
-
- // Set all primitives to use new stream bank.
- for (unsigned ii = 0; ii < elements.size(); ++ii) {
- down_cast<Primitive*>(elements[ii].Get())->set_stream_bank(
- new_stream_bank);
- }
- pack_->RemoveObject(old_stream_bank);
- if (old_buffer) {
- source_buffer->set_name(String("source_") + old_buffer->name());
- dest_buffer->set_name(String("skinned_") + old_buffer->name());
- shared_buffer->set_name(String("shared_") + old_buffer->name());
- pack_->RemoveObject(old_buffer);
- }
- }
- return shape;
-}
-
-Texture* Collada::BuildTextureFromImage(FCDImage* image) {
- const fstring filename = image->GetFilename();
- Texture* tex = textures_[filename.c_str()];
- if (!tex) {
- FilePath file_path = WideToFilePath(filename.c_str());
- FilePath uri = file_path;
-
- std::string tempfile;
- if (collada_zip_archive_) {
- // If we're getting data from a zip archive, then we just strip
- // the "/" from the beginning of the name, since that represents
- // the root of the archive, and we can assume all the paths in
- // the archive are relative to that.
- if (uri.value()[0] == FILE_PATH_LITERAL('/')) {
- uri = FilePath(uri.value().substr(1));
- }
- // NOTE: We have the opportunity to simply extract a memory
- // buffer for the image data here, but currently the image loaders expect
- // to read a file, so we write out a temp file...
-
- // filename_utf8 points to the name of the file inside the archive
- // (it doesn't actually live on the filesystem so we make a temp file)
- if (collada_zip_archive_->GetTempFileFromFile(FilePathToUTF8(file_path),
- &tempfile)) {
- file_path = UTF8ToFilePath(tempfile);
- }
- } else {
- GetRelativePathIfPossible(base_path_, uri, &uri);
- }
-
- if (!FindFile(options_.file_paths, file_path, &file_path)) {
- O3D_ERROR(service_locator_) << "Could not find file: " << filename;
- return NULL;
- }
-
- tex = Texture::Ref(
- pack_->CreateTextureFromFile(FilePathToUTF8(uri),
- file_path,
- image::UNKNOWN,
- options_.generate_mipmaps));
- if (tex) {
- const fstring name(image->GetName());
- tex->set_name(WideToUTF8(name.c_str()));
- }
-
- bool inserted_original_data = false;
- bool is_dds = uri.MatchesExtension(UTF8ToFilePathStringType(".dds"));
-
- if (is_dds &&
- options_.convert_dds_to_png &&
- options_.keep_original_data) {
- // The Texture stubs used by the converter don't have a working
- // PlatformSpecificLock, so we need to reload the images using
- // the Bitmap class. We also need to do the DXTn decompression
- // on the CPU because D3D wouldn't provide access to the
- // decompressed data anyway.
-
- // These need to match the order of TextureCUBE::CubeFace.
- static const char* cube_suffixes[6] = {
- "_posx", "_negx", "_posy", "_negy", "_posz", "_negz"
- };
- static const char* cube_prefixes[6] = {
- "posx_", "negx_", "posy_", "negy_", "posz_", "negz_"
- };
-
- BitmapRefArray bitmaps;
- bool is_cube_map = false;
- if (Bitmap::LoadFromFile(service_locator_, file_path,
- image::UNKNOWN, &bitmaps)) {
- is_cube_map = bitmaps.size() == 6;
- for (unsigned int i = 0; i < bitmaps.size(); i++) {
- bool is_compressed =
- (tex->format() == Texture::DXT1 ||
- tex->format() == Texture::DXT3 ||
- tex->format() == Texture::DXT5);
- Bitmap::Ref src_bitmap = bitmaps[i];
- int pitch = src_bitmap->GetMipPitch(0);
- if (is_compressed) {
- // TODO(kbr): there is a bug somewhere in
- // Bitmap::GetMipPitch for compressed textures where its
- // result is off by a factor of two, at least for DXT1
- // textures. Don't have time to debug it right now.
- pitch /= 2;
- }
- uint8* data = src_bitmap->GetMipData(0);
- int width = src_bitmap->width();
- int height = src_bitmap->height();
- int row_width = width * 4;
- int decompressed_size = width * height * 4;
- scoped_array<uint8> decompressed_data(new uint8[decompressed_size]);
- memset(decompressed_data.get(), 0, decompressed_size);
- if (is_compressed) {
- for (int src_y = 0; src_y < height; src_y++) {
- int dest_y = src_y;
- if (is_cube_map) {
- dest_y = height - src_y - 1;
- }
- for (int x = 0; x < width; x++) {
- uint8* ptr =
- &decompressed_data.get()[row_width * dest_y + 4 * x];
- switch (src_bitmap->format()) {
- case Texture::DXT1: {
- fetch_2d_texel_rgba_dxt1(pitch, data, x, src_y, ptr);
- break;
- }
- case Texture::DXT3: {
- fetch_2d_texel_rgba_dxt3(pitch, data, x, src_y, ptr);
- break;
- }
- case Texture::DXT5: {
- fetch_2d_texel_rgba_dxt5(pitch, data, x, src_y, ptr);
- break;
- }
- default:
- DLOG(ERROR) << "Unsupported DDS compressed texture format "
- << src_bitmap->format();
- break;
- }
- // Need to swap the red and blue channels.
- std::swap(ptr[0], ptr[2]);
- }
- }
- } else if (src_bitmap->format() == Texture::XRGB8 ||
- src_bitmap->format() == Texture::ARGB8) {
- for (int src_y = 0; src_y < height; src_y++) {
- int dest_y = src_y;
- if (is_cube_map) {
- dest_y = height - src_y - 1;
- }
- memcpy(decompressed_data.get() + row_width * dest_y,
- data + pitch * src_y,
- row_width);
- }
- } else {
- DLOG(ERROR) << "Unsupported DDS uncompressed texture format "
- << src_bitmap->format();
- return NULL;
- }
- Bitmap::Ref bitmap(new Bitmap(service_locator_));
- bitmap->Allocate(Texture::ARGB8,
- width,
- height,
- 1,
- Bitmap::IMAGE);
- bitmap->SetRect(0, 0, 0, width, height,
- decompressed_data.get(),
- row_width);
- std::vector<uint8> png_data;
- if (!bitmap->WriteToPNGStream(&png_data)) {
- DLOG(ERROR) << "Error writing PNG file for cube map";
- }
- FilePath png_uri = uri;
- if (is_cube_map) {
- png_uri = png_uri.InsertBeforeExtensionASCII(cube_suffixes[i]);
- }
- png_uri = png_uri.ReplaceExtension(UTF8ToFilePathStringType(".png"));
- std::string contents;
- contents.append(reinterpret_cast<char*>(&png_data.front()),
- png_data.size());
- original_data_map_.AddData(png_uri, contents, service_locator_);
- inserted_original_data = true;
-
- // We need to rewrite the o3d.uri param in the Texture as
- // well. For cube map textures, we insert six params named
- // "o3d.negx_uri", etc. and remove the "o3d.uri" param.
- ParamString* uri_param = NULL;
- if (is_cube_map) {
- String name(O3D_STRING_CONSTANT(""));
- name = name.append(cube_prefixes[i]).append("uri");
- uri_param = tex->CreateParam<ParamString>(name);
- } else {
- uri_param = tex->GetParam<ParamString>(O3D_STRING_CONSTANT("uri"));
- }
- DCHECK(uri_param != NULL);
- uri_param->set_value(FilePathToUTF8(png_uri));
- }
- }
- if (is_cube_map) {
- ParamString* uri_param =
- tex->GetParam<ParamString>(O3D_STRING_CONSTANT("uri"));
- DCHECK(uri_param != NULL);
- tex->RemoveParam(uri_param);
- }
- }
-
- if (options_.keep_original_data && !inserted_original_data) {
- // Cache the original data by URI so we can recover it later.
- std::string contents;
- file_util::ReadFileToString(file_path, &contents);
- original_data_map_.AddData(uri, contents, service_locator_);
- }
-
- if (tempfile.size() > 0) ZipArchive::DeleteFile(tempfile);
- textures_[filename.c_str()] = tex;
- }
- return tex;
-}
-
-Texture* Collada::BuildTexture(FCDEffectParameterSurface* surface) {
- // Create the texture.
- Texture* tex = NULL;
- if (surface->GetImageCount() > 0) {
- FCDImage* image = surface->GetImage(0);
- tex = BuildTextureFromImage(image);
- }
- return tex;
-}
-
-// Sets an O3D parameter value from a given FCollada effect parameter.
-// instance.
-// Parameters:
-// param_object: The param_object whose parameter is to be modified.
-// param_name: The name of the parameter to be set.
-// fc_param: The FCollada effect parameter whose value is used.
-// Returns true on success.
-bool Collada::SetParamFromFCEffectParam(ParamObject* param_object,
- const String &param_name,
- FCDEffectParameter *fc_param) {
- if (!param_object || !fc_param) return false;
- FCDEffectParameter::Type type = fc_param->GetType();
- bool rc = false;
- if (type == FCDEffectParameter::FLOAT) {
- FCDEffectParameterFloat* float_param =
- static_cast<FCDEffectParameterFloat*>(fc_param);
- ParamFloat* param = param_object->CreateParam<ParamFloat>(param_name);
- if (param) {
- param->set_value(float_param->GetValue());
- rc = true;
- }
- } else if (type == FCDEffectParameter::FLOAT2) {
- FCDEffectParameterFloat2* float2_param =
- static_cast<FCDEffectParameterFloat2*>(fc_param);
- FMVector2 v = float2_param->GetValue();
- ParamFloat2* param = param_object->CreateParam<ParamFloat2>(param_name);
- if (param) {
- Float2 f(v.x, v.y);
- param->set_value(f);
- rc = true;
- }
- } else if (type == FCDEffectParameter::FLOAT3) {
- FCDEffectParameterFloat3* float3_param =
- static_cast<FCDEffectParameterFloat3*>(fc_param);
- FMVector3 v = float3_param->GetValue();
- ParamFloat3* param = param_object->CreateParam<ParamFloat3>(param_name);
- if (!param)
- return false;
- Float3 f(v.x, v.y, v.z);
- param->set_value(f);
- rc = true;
- } else if (type == FCDEffectParameter::VECTOR) {
- FCDEffectParameterVector* vector_param =
- static_cast<FCDEffectParameterVector*>(fc_param);
- FMVector4 v = vector_param->GetValue();
- ParamFloat4* param = param_object->CreateParam<ParamFloat4>(param_name);
- if (param) {
- Float4 f(v.x, v.y, v.z, v.w);
- param->set_value(f);
- rc = true;
- }
- } else if (type == FCDEffectParameter::INTEGER) {
- FCDEffectParameterInt* int_param =
- static_cast<FCDEffectParameterInt*>(fc_param);
- ParamInteger* param = param_object->CreateParam<ParamInteger>(param_name);
- if (param) {
- param->set_value(int_param->GetValue());
- rc = true;
- }
- } else if (type == FCDEffectParameter::BOOLEAN) {
- FCDEffectParameterBool* bool_param =
- static_cast<FCDEffectParameterBool*>(fc_param);
- ParamBoolean* param = param_object->CreateParam<ParamBoolean>(param_name);
- if (param) {
- param->set_value(bool_param->GetValue());
- rc = true;
- }
- } else if (type == FCDEffectParameter::MATRIX) {
- FCDEffectParameterMatrix* matrix_param =
- static_cast<FCDEffectParameterMatrix*>(fc_param);
- ParamMatrix4* param = param_object->CreateParam<ParamMatrix4>(param_name);
- if (param) {
- param->set_value(FMMatrix44ToMatrix4(matrix_param->GetValue()));
- rc = true;
- }
- } else if (type == FCDEffectParameter::SAMPLER) {
- FCDEffectParameterSampler* sampler =
- static_cast<FCDEffectParameterSampler*>(fc_param);
- ParamSampler* sampler_param = param_object->CreateParam<ParamSampler>(
- param_name);
- if (sampler_param) {
- Sampler* o3d_sampler = pack_->Create<Sampler>();
- o3d_sampler->set_name(param_name);
- sampler_param->set_value(o3d_sampler);
-
- FCDEffectParameterSurface* surface = sampler->GetSurface();
- if (surface) {
- Texture* tex = BuildTexture(surface);
-
- // Set the texture on the sampler.
- if (tex) {
- o3d_sampler->set_texture(tex);
- rc = true;
- }
- }
- SetSamplerStates(sampler, o3d_sampler);
- }
- } else if (type == FCDEffectParameter::SURFACE) {
- // TODO(o3d): This code is here to handle the NV_import profile
- // exported by Max's DirectX Shader materials, which references
- // only references texture params (not samplers). Once we move
- // completely to using samplers and add sampler blocks to our
- // collada file then we should eliminate this codepath.
-
- FCDEffectParameterSurface* surface =
- static_cast<FCDEffectParameterSurface*>(fc_param);
-
- Texture* tex = BuildTexture(surface);
- if (tex) {
- ParamTexture* param = param_object->CreateParam<ParamTexture>(param_name);
- if (param) {
- param->set_value(tex);
- rc = true;
- }
- }
- }
- return rc;
-}
-
-Effect* Collada::GetDummyEffect() {
- if (!dummy_effect_) {
- // Create a dummy effect, just so we can see something
- dummy_effect_ = pack_->Create<Effect>();
- dummy_effect_->set_name(
- COLLADA_STRING_CONSTANT("substituteForMissingOrBadEffect"));
- dummy_effect_->LoadFromFXString(
- "float4x4 worldViewProj : WorldViewProjection;"
- "float4 vs(float4 v : POSITION ) : POSITION {"
- " return mul(v, worldViewProj);"
- "}"
- "float4 ps() : COLOR {"
- " return float4(1, 0, 1, 1);"
- "}\n"
- "// #o3d VertexShaderEntryPoint vs\n"
- "// #o3d PixelShaderEntryPoint ps\n");
- }
- return dummy_effect_;
-}
-
-Material* Collada::GetDummyMaterial() {
- if (!dummy_material_) {
- dummy_material_ = pack_->Create<Material>();
- dummy_material_->set_name(
- COLLADA_STRING_CONSTANT("substituteForMissingOrBadMaterial"));
- dummy_material_->set_effect(GetDummyEffect());
- }
- return dummy_material_;
-}
-
-static const char* GetLightingType(FCDEffectStandard* std_profile) {
- FCDEffectStandard::LightingType type = std_profile->GetLightingType();
- switch (type) {
- case FCDEffectStandard::CONSTANT:
- return Collada::kLightingTypeConstant;
- case FCDEffectStandard::PHONG:
- return Collada::kLightingTypePhong;
- case FCDEffectStandard::BLINN:
- return Collada::kLightingTypeBlinn;
- case FCDEffectStandard::LAMBERT:
- return Collada::kLightingTypeLambert;
- default:
- return Collada::kLightingTypeUnknown;
- }
-}
-
-static FCDEffectProfileFX* FindProfileFX(FCDEffect* effect) {
- FCDEffectProfile* profile = effect->FindProfile(FUDaeProfileType::HLSL);
- if (!profile) {
- profile = effect->FindProfile(FUDaeProfileType::CG);
- if (!profile) {
- return NULL;
- }
- }
- return static_cast<FCDEffectProfileFX*>(profile);
-}
-
-Material* Collada::BuildMaterial(FCDocument* doc,
- FCDMaterial* collada_material) {
- if (!doc || !collada_material) {
- return NULL;
- }
-
- fm::string material_id = collada_material->GetDaeId();
- Material* material = materials_[material_id.c_str()];
- if (!material) {
- Effect* effect = NULL;
- FCDEffect* collada_effect = collada_material->GetEffect();
- if (collada_effect) {
- effect = GetEffect(doc, collada_effect);
- }
-
- String collada_material_name = WideToUTF8(
- collada_material->GetName().c_str());
- Material* material = pack_->Create<Material>();
- material->set_name(collada_material_name);
- material->set_effect(effect);
- SetParamsFromMaterial(collada_material, material);
-
- // If this is a COLLADA-FX profile, add the render states from the
- // COLLADA-FX sections.
- FCDEffectProfileFX* profile_fx = FindProfileFX(collada_effect);
- if (profile_fx) {
- if (profile_fx->GetTechniqueCount() > 0) {
- FCDEffectTechnique* technique = profile_fx->GetTechnique(0);
- if (technique->GetPassCount() > 0) {
- FCDEffectPass* pass = technique->GetPass(0);
- State* state = pack_->Create<State>();
- state->set_name("pass_state");
- cull_enabled_ = cull_front_ = front_cw_ = false;
- for (size_t i = 0; i < pass->GetRenderStateCount(); ++i) {
- AddRenderState(pass->GetRenderState(i), state);
- }
- material->set_state(state);
- }
- }
- } else {
- FCDEffectStandard* std_profile = static_cast<FCDEffectStandard *>(
- collada_effect->FindProfile(FUDaeProfileType::COMMON));
- if (std_profile) {
- ParamString* type_tag = material->CreateParam<ParamString>(
- kLightingTypeParamName);
- type_tag->set_value(GetLightingType(std_profile));
- }
- }
- materials_[material_id.c_str()] = material;
- }
- return material;
-}
-
-Effect* Collada::GetEffect(FCDocument* doc, FCDEffect* collada_effect) {
- Effect* effect = NULL;
- fm::string effect_id = collada_effect->GetDaeId();
- effect = effects_[effect_id.c_str()];
- if (!effect) {
- effect = BuildEffect(doc, collada_effect);
- if (effect) effects_[effect_id.c_str()] = effect;
- }
- return effect;
-}
-
-// Builds an O3D effect from a COLLADA effect. If a COLLADA-FX
-// (Cg/HLSL) effect is present, it will be used and a programmable
-// Effect generated. If not, an attempt is made to use one of the fixed-
-// function profiles if present (eg., Constant, Lambert).
-// Parameters:
-// doc: The FCollada document from which to import nodes.
-// collada_effect: The COLLADA effect from which shaders will be taken.
-// Returns:
-// the newly-created effect, or NULL or error.
-Effect* Collada::BuildEffect(FCDocument* doc, FCDEffect* collada_effect) {
- if (!doc || !collada_effect) return NULL;
- // TODO(o3d): Remove all of this to be replaced by parsing Collada-FX
- // and profile_O3D only.
- Effect* effect = NULL;
- FCDEffectProfileFX* profile_fx = FindProfileFX(collada_effect);
- if (profile_fx) {
- if (profile_fx->GetCodeCount() > 0) {
- FCDEffectCode* code = profile_fx->GetCode(0);
- String effect_string;
- FilePath file_path;
- if (code->GetType() == FCDEffectCode::CODE) {
- fstring code_string = code->GetCode();
- effect_string = WideToUTF8(code_string.c_str());
- unique_filename_counter_++;
- String file_name = "embedded-shader-" +
- IntToString(unique_filename_counter_) + ".fx";
- file_path = FilePath(FILE_PATH_LITERAL("shaders"));
- file_path = file_path.Append(UTF8ToFilePath(file_name));
- } else if (code->GetType() == FCDEffectCode::INCLUDE) {
- fstring path = code->GetFilename();
- file_path = WideToFilePath(path.c_str());
- if (collada_zip_archive_ && !file_path.empty()) {
- // Make absolute path be relative to root of archive.
- if (file_path.value()[0] == FILE_PATH_LITERAL('/')) {
- file_path = FilePath(file_path.value().substr(1));
- }
- size_t effect_data_size;
- char *effect_data =
- collada_zip_archive_->GetFileData(FilePathToUTF8(file_path),
- &effect_data_size);
- if (effect_data) {
- effect_string = effect_data;
- free(effect_data);
- } else {
- O3D_ERROR(service_locator_)
- << "Unable to read effect data for effect '"
- << FilePathToUTF8(file_path) << "'";
- return NULL;
- }
- } else {
- FilePath temp_path = file_path;
- if (!FindFile(options_.file_paths, temp_path, &temp_path)) {
- O3D_ERROR(service_locator_) << "Could not find file: " << path;
- return NULL;
- }
- file_util::ReadFileToString(temp_path, &effect_string);
- }
- }
- String collada_effect_name = WideToUTF8(
- collada_effect->GetName().c_str());
- effect = pack_->Create<Effect>();
- effect->set_name(collada_effect_name);
-
- ParamString* param = effect->CreateParam<ParamString>(
- O3D_STRING_CONSTANT("uri"));
- DCHECK(param != NULL);
- param->set_value(FilePathToUTF8(file_path));
-
- if (!effect->LoadFromFXString(effect_string)) {
- pack_->RemoveObject(effect);
- O3D_ERROR(service_locator_) << "Unable to load effect '"
- << FilePathToUTF8(file_path).c_str()
- << "'";
- return NULL;
- }
-
- if (options_.convert_cg_to_glsl) {
- if (!ConvertCgToGlsl(options_.converter_tool, &effect_string))
- O3D_ERROR(service_locator_) << "Shader conversion failed.";
- }
-
- if (options_.keep_original_data) {
- // Cache the original data by URI so we can recover it later.
- original_data_map_.AddData(file_path, effect_string, service_locator_);
- }
- }
- } else {
- FCDExtra* extra = collada_effect->GetExtra();
- if (extra && extra->GetTypeCount() > 0) {
- FCDEType* type = extra->GetType(0);
- if (type) {
- FCDETechnique* technique = type->FindTechnique("NV_import");
- if (technique) {
- FCDENode* node = technique->FindChildNode("import");
- if (node) {
- FCDEAttribute* url_attrib = node->FindAttribute("url");
- if (url_attrib) {
- fstring url = url_attrib->GetValue();
- const FUFileManager* mgr = doc->GetFileManager();
- LOG_ASSERT(mgr != NULL);
- FUUri uri = mgr->GetCurrentUri();
- FUUri effect_uri = uri.Resolve(url_attrib->GetValue());
- fstring path = effect_uri.GetAbsolutePath();
-
- String collada_effect_name = WideToUTF8(
- collada_effect->GetName().c_str());
-
- FilePath file_path = WideToFilePath(path.c_str());
-
- String effect_string;
-
- if (collada_zip_archive_ && !file_path.empty()) {
- // Make absolute path be relative to root of archive.
- if (file_path.value()[0] == FILE_PATH_LITERAL('/')) {
- file_path = FilePath(file_path.value().substr(1));
- }
- // shader file can be extracted in memory from zip archive
- // so lets get the data and turn it into a string
- size_t effect_data_size;
- char *effect_data =
- collada_zip_archive_->GetFileData(FilePathToUTF8(file_path),
- &effect_data_size);
- if (effect_data) {
- effect_string = effect_data;
- free(effect_data);
- } else {
- O3D_ERROR(service_locator_)
- << "Unable to read effect data for effect '"
- << FilePathToUTF8(file_path) << "'";
- return NULL;
- }
- } else {
- file_util::ReadFileToString(file_path, &effect_string);
- }
-
- effect = pack_->Create<Effect>();
- effect->set_name(collada_effect_name);
-
- ParamString* param = effect->CreateParam<ParamString>(
- O3D_STRING_CONSTANT("uri"));
- DCHECK(param != NULL);
- param->set_value(FilePathToUTF8(file_path));
-
- if (!effect->LoadFromFXString(effect_string)) {
- pack_->RemoveObject(effect);
- O3D_ERROR(service_locator_) << "Unable to load effect '"
- << FilePathToUTF8(file_path).c_str()
- << "'";
- return NULL;
- }
- if (options_.keep_original_data) {
- // Cache the original data by URI so we can recover it later.
- original_data_map_.AddData(file_path, effect_string,
- service_locator_);
- }
- }
- }
- }
- }
- }
- }
- return effect;
-}
-
-// Gets a typed value from an FCollada state. T is the type to get,
-// state is the state from which to retrieve the value, and offset is
-// the index into the state's data (in sizeof T objects) at which the
-// value is located.
-template <class T>
-static T GetStateValue(FCDEffectPassState* state, size_t offset) {
- LOG_ASSERT(offset * sizeof(T) < state->GetDataSize());
- return *(reinterpret_cast<T*>(state->GetData()) + offset);
-}
-
-// Converts an FCollada blend type into an O3D state blending function.
-// On error, an error string is logged. "type" is the FCollada type to convert,
-// and "collada" is the Collada importer used for logging errors.
-static State::BlendingFunction ConvertBlendType(
- ServiceLocator* service_locator,
- FUDaePassStateBlendType::Type type) {
- switch (type) {
- case FUDaePassStateBlendType::ZERO:
- return State::BLENDFUNC_ZERO;
- case FUDaePassStateBlendType::ONE:
- return State::BLENDFUNC_ONE;
- case FUDaePassStateBlendType::SOURCE_COLOR:
- return State::BLENDFUNC_SOURCE_COLOR;
- case FUDaePassStateBlendType::ONE_MINUS_SOURCE_COLOR:
- return State::BLENDFUNC_INVERSE_SOURCE_COLOR;
- case FUDaePassStateBlendType::SOURCE_ALPHA:
- return State::BLENDFUNC_SOURCE_ALPHA;
- case FUDaePassStateBlendType::ONE_MINUS_SOURCE_ALPHA:
- return State::BLENDFUNC_INVERSE_SOURCE_ALPHA;
- case FUDaePassStateBlendType::DESTINATION_ALPHA:
- return State::BLENDFUNC_DESTINATION_ALPHA;
- case FUDaePassStateBlendType::ONE_MINUS_DESTINATION_ALPHA:
- return State::BLENDFUNC_INVERSE_DESTINATION_ALPHA;
- case FUDaePassStateBlendType::DESTINATION_COLOR:
- return State::BLENDFUNC_DESTINATION_COLOR;
- case FUDaePassStateBlendType::ONE_MINUS_DESTINATION_COLOR:
- return State::BLENDFUNC_INVERSE_DESTINATION_COLOR;
- case FUDaePassStateBlendType::SOURCE_ALPHA_SATURATE:
- return State::BLENDFUNC_SOURCE_ALPHA_SATUTRATE;
- default:
- O3D_ERROR(service_locator) << "Invalid blend type";
- return State::BLENDFUNC_ONE;
- }
-}
-
-// Converts an FCollada blend equation into an O3D state blending
-// equation. On error, an error string is logged. "equation" is the
-// FCollada equation to convert, and "collada" is the Collada importer
-// used for logging errors.
-static State::BlendingEquation ConvertBlendEquation(
- ServiceLocator* service_locator,
- FUDaePassStateBlendEquation::Equation equation) {
- switch (equation) {
- case FUDaePassStateBlendEquation::ADD:
- return State::BLEND_ADD;
- case FUDaePassStateBlendEquation::SUBTRACT:
- return State::BLEND_SUBTRACT;
- case FUDaePassStateBlendEquation::REVERSE_SUBTRACT:
- return State::BLEND_REVERSE_SUBTRACT;
- case FUDaePassStateBlendEquation::MIN:
- return State::BLEND_MIN;
- case FUDaePassStateBlendEquation::MAX:
- return State::BLEND_MAX;
- default:
- O3D_ERROR(service_locator) << "Invalid blend equation";
- return State::BLEND_ADD;
- }
-}
-
-// Converts an FCollada comparison function into an O3D state blending
-// equation. On error, an error string is logged. "function" is the
-// FCollada comparison function to convert, and "collada" is the Collada
-// importer used for logging errors.
-static State::Comparison ConvertComparisonFunction(
- ServiceLocator* service_locator,
- FUDaePassStateFunction::Function function) {
- switch (function) {
- case FUDaePassStateFunction::NEVER:
- return State::CMP_NEVER;
- case FUDaePassStateFunction::LESS:
- return State::CMP_LESS;
- case FUDaePassStateFunction::LESS_EQUAL:
- return State::CMP_LEQUAL;
- case FUDaePassStateFunction::EQUAL:
- return State::CMP_EQUAL;
- case FUDaePassStateFunction::GREATER:
- return State::CMP_GREATER;
- case FUDaePassStateFunction::NOT_EQUAL:
- return State::CMP_NOTEQUAL;
- case FUDaePassStateFunction::GREATER_EQUAL:
- return State::CMP_GEQUAL;
- case FUDaePassStateFunction::ALWAYS:
- return State::CMP_ALWAYS;
- default:
- O3D_ERROR(service_locator) << "Invalid comparison function";
- return State::CMP_NEVER;
- }
-}
-
-// Converts an FCollada polygon fill mode into an O3D fill mode.
-// On error, an error string is logged. "mode" is the FCollada fill
-// mode to convert, and "collada" is the Collada importer used for
-// logging errors.
-static State::Fill ConvertFillMode(ServiceLocator* service_locator,
- FUDaePassStatePolygonMode::Mode mode) {
- switch (mode) {
- case FUDaePassStatePolygonMode::POINT:
- return State::POINT;
- case FUDaePassStatePolygonMode::LINE:
- return State::WIREFRAME;
- case FUDaePassStatePolygonMode::FILL:
- return State::SOLID;
- default:
- O3D_ERROR(service_locator) << "Invalid polygon fill mode";
- return State::SOLID;
- }
-}
-
-// Converts an FCollada stencil operation into an O3D stencil operation.
-// On error, an error string is logged. "operation" is the FCollada operation
-// to convert, and "collada" is the Collada importer used for logging errors.
-static State::StencilOperation ConvertStencilOp(
- ServiceLocator* service_locator,
- FUDaePassStateStencilOperation::Operation operation) {
- switch (operation) {
- case FUDaePassStateStencilOperation::KEEP:
- return State::STENCIL_KEEP;
- case FUDaePassStateStencilOperation::ZERO:
- return State::STENCIL_ZERO;
- case FUDaePassStateStencilOperation::REPLACE:
- return State::STENCIL_REPLACE;
- case FUDaePassStateStencilOperation::INCREMENT:
- return State::STENCIL_INCREMENT_SATURATE;
- case FUDaePassStateStencilOperation::DECREMENT:
- return State::STENCIL_DECREMENT_SATURATE;
- case FUDaePassStateStencilOperation::INVERT:
- return State::STENCIL_INVERT;
- case FUDaePassStateStencilOperation::INCREMENT_WRAP:
- return State::STENCIL_INCREMENT;
- case FUDaePassStateStencilOperation::DECREMENT_WRAP:
- return State::STENCIL_DECREMENT;
- default:
- O3D_ERROR(service_locator) << "Invalid stencil operation";
- return State::STENCIL_KEEP;
- }
-}
-
-// Updates the O3D state object's cull mode from the OpenGL-style
-// cull modes used by COLLADA-FX sections. "state" is the O3D state
-// on which to set the cull mode. If "cull_front_" is true, the system is
-// culling front-facing polygons, otherwise it's culling back-facing. If
-// "front_cw_" is true, polygons with clockwise winding are considered
-// front-facing, otherwise counter-clockwise winding is considered
-// front-facing. if "cull_enabled_" is false, culling is disabled.
-void Collada::UpdateCullingState(State* state) {
- ParamInteger* face = state->GetStateParam<ParamInteger>(
- State::kCullModeParamName);
- if (cull_front_ ^ front_cw_) {
- face->set_value(cull_enabled_ ? State::CULL_CCW : State::CULL_NONE);
- } else {
- face->set_value(cull_enabled_ ? State::CULL_CW : State::CULL_NONE);
- }
-}
-
-// Sets a boolean state param in an O3D state object. "state" is the
-// state object, "name" is the name of the state param to set, and "value"
-// is the boolean value. If the state param does not exist, or is not
-// of the correct type, an assert is logged.
-static void SetBoolState(State* state, const char* name, bool value) {
- ParamBoolean* param = state->GetStateParam<ParamBoolean>(name);
- LOG_ASSERT(param);
- param->set_value(value);
-}
-
-// Sets a floating-point state param in an O3D state object.
-// "state" is the state object, "name" is the name of the state param
-// to set, and "value" is the floating-point value. If the state
-// param does not exist, or is not of the correct type, an assert
-// is logged.
-static void SetFloatState(State* state, const char* name, float value) {
- ParamFloat* param = state->GetStateParam<ParamFloat>(name);
- LOG_ASSERT(param);
- param->set_value(value);
-}
-
-// Sets a Float4 state param in an O3D state object. "state" is
-// the state object, "name" is the name of the state param to set, and
-// "value" is the Float4 value. If the state param does not exist, or
-// is not of the correct type, an assert is logged.
-static void SetFloat4State(State* state,
- const char* name,
- const Float4& value) {
- ParamFloat4* param = state->GetStateParam<ParamFloat4>(name);
- LOG_ASSERT(param);
- param->set_value(value);
-}
-
-// Sets a integer state param in an O3D state object. "state" is
-// the state object, "name" is the name of the state param to set, and
-// "value" is the Float4 value. If the state param does not exist, or
-// is not of the correct type, an assert is logged.
-static void SetIntState(State* state, const char* name, int value) {
- ParamInteger* param = state->GetStateParam<ParamInteger>(name);
- LOG_ASSERT(param);
- param->set_value(value);
-}
-
-// Sets the stencil state params for polygons with clockwise
-// winding. "state" is the O3D state object in which to set
-// state, "fail", "zfail", and "zpass" are the corresponding stencil
-// settings.
-static void SetCWStencilSettings(State* state,
- State::StencilOperation fail,
- State::StencilOperation zfail,
- State::StencilOperation zpass) {
- SetIntState(state, State::kStencilFailOperationParamName, fail);
- SetIntState(state, State::kStencilZFailOperationParamName, zfail);
- SetIntState(state, State::kStencilPassOperationParamName, zpass);
-}
-
-// Sets the stencil state params for polygons with counter-clockwise
-// winding. "state" is the O3D state object in which to set
-// state, "fail", "zfail", and "zpass" are the corresponding stencil
-// settings.
-static void SetCCWStencilSettings(State* state,
- State::StencilOperation fail,
- State::StencilOperation zfail,
- State::StencilOperation zpass) {
- SetIntState(state, State::kCCWStencilFailOperationParamName, fail);
- SetIntState(state, State::kCCWStencilZFailOperationParamName, zfail);
- SetIntState(state, State::kCCWStencilPassOperationParamName, zpass);
-}
-
-// Sets the stencil state params for polygons with the given winding
-// order. "state" is the O3D state object in which to set
-// state, "fail", "zfail", and "zpass" are the corresponding stencil
-// settings. If "cw" is true, clockwise winding settings will be set,
-// otherwise counter-clockwise winding settings are set.
-static void SetStencilSettings(State* state,
- bool cw,
- State::StencilOperation fail,
- State::StencilOperation zfail,
- State::StencilOperation zpass) {
- if (cw) {
- SetCWStencilSettings(state, fail, zfail, zpass);
- } else {
- SetCCWStencilSettings(state, fail, zfail, zpass);
- }
-}
-
-// Adds the appropriate O3D state params to the given state object
-// corresponding to a given FCollada Pass State. If unsupported or
-// invalid states are specified, an error message is set.
-void Collada::AddRenderState(FCDEffectPassState* pass_state, State* state) {
- switch (pass_state->GetType()) {
- case FUDaePassState::ALPHA_FUNC: {
- State::Comparison function = ConvertComparisonFunction(
- service_locator_,
- GetStateValue<FUDaePassStateFunction::Function>(pass_state, 0));
- float value = GetStateValue<float>(pass_state, 1);
- SetIntState(state, State::kAlphaComparisonFunctionParamName, function);
- SetFloatState(state, State::kAlphaReferenceParamName, value);
- break;
- }
- case FUDaePassState::BLEND_FUNC: {
- State::BlendingFunction src = ConvertBlendType(
- service_locator_,
- GetStateValue<FUDaePassStateBlendType::Type>(pass_state, 0));
- State::BlendingFunction dest = ConvertBlendType(
- service_locator_,
- GetStateValue<FUDaePassStateBlendType::Type>(pass_state, 1));
- SetIntState(state, State::kSourceBlendFunctionParamName, src);
- SetIntState(state, State::kDestinationBlendFunctionParamName, dest);
- SetBoolState(state, State::kSeparateAlphaBlendEnableParamName, false);
- break;
- }
- case FUDaePassState::BLEND_FUNC_SEPARATE: {
- State::BlendingFunction src_rgb = ConvertBlendType(
- service_locator_,
- GetStateValue<FUDaePassStateBlendType::Type>(pass_state, 0));
- State::BlendingFunction dest_rgb = ConvertBlendType(
- service_locator_,
- GetStateValue<FUDaePassStateBlendType::Type>(pass_state, 1));
- State::BlendingFunction src_alpha = ConvertBlendType(
- service_locator_,
- GetStateValue<FUDaePassStateBlendType::Type>(pass_state, 2));
- State::BlendingFunction dest_alpha = ConvertBlendType(
- service_locator_,
- GetStateValue<FUDaePassStateBlendType::Type>(pass_state, 3));
- SetIntState(state, State::kSourceBlendFunctionParamName, src_rgb);
- SetIntState(state, State::kDestinationBlendFunctionParamName, dest_rgb);
- SetIntState(state, State::kSourceBlendAlphaFunctionParamName, src_alpha);
- SetIntState(state, State::kDestinationBlendAlphaFunctionParamName,
- dest_alpha);
- SetBoolState(state, State::kSeparateAlphaBlendEnableParamName, true);
- break;
- }
- case FUDaePassState::BLEND_EQUATION: {
- State::BlendingEquation value = ConvertBlendEquation(
- service_locator_,
- GetStateValue<FUDaePassStateBlendEquation::Equation>(pass_state, 0));
- SetIntState(state, State::kBlendEquationParamName, value);
- SetIntState(state, State::kBlendAlphaEquationParamName, value);
- break;
- }
- case FUDaePassState::BLEND_EQUATION_SEPARATE: {
- State::BlendingEquation rgb = ConvertBlendEquation(
- service_locator_,
- GetStateValue<FUDaePassStateBlendEquation::Equation>(pass_state, 0));
- State::BlendingEquation alpha = ConvertBlendEquation(
- service_locator_,
- GetStateValue<FUDaePassStateBlendEquation::Equation>(pass_state, 1));
- SetIntState(state, State::kBlendEquationParamName, rgb);
- SetIntState(state, State::kBlendAlphaEquationParamName, alpha);
- break;
- }
- case FUDaePassState::CULL_FACE: {
- FUDaePassStateFaceType::Type culled_faces =
- GetStateValue<FUDaePassStateFaceType::Type>(pass_state, 0);
- switch (culled_faces) {
- case FUDaePassStateFaceType::FRONT: {
- cull_front_ = true;
- break;
- }
- case FUDaePassStateFaceType::BACK: {
- cull_front_ = false;
- break;
- }
- case FUDaePassStateFaceType::FRONT_AND_BACK: {
- O3D_ERROR(service_locator_)
- << "FRONT_AND_BACK culling is unsupported";
- break;
- }
- case FUDaePassStateFaceType::INVALID:
- O3D_ERROR(service_locator_) << "INVALID culling type";
- break;
- }
- UpdateCullingState(state);
- break;
- }
- case FUDaePassState::DEPTH_FUNC: {
- State::Comparison function = ConvertComparisonFunction(
- service_locator_,
- GetStateValue<FUDaePassStateFunction::Function>(pass_state, 0));
- SetIntState(state, State::kZComparisonFunctionParamName, function);
- break;
- }
- case FUDaePassState::FRONT_FACE: {
- FUDaePassStateFrontFaceType::Type type =
- GetStateValue<FUDaePassStateFrontFaceType::Type>(pass_state, 0);
- front_cw_ = type == FUDaePassStateFrontFaceType::CLOCKWISE;
- break;
- }
- case FUDaePassState::POLYGON_MODE: {
- FUDaePassStateFaceType::Type face =
- GetStateValue<FUDaePassStateFaceType::Type>(pass_state, 0);
- State::Fill mode = ConvertFillMode(
- service_locator_,
- GetStateValue<FUDaePassStatePolygonMode::Mode>(pass_state, 1));
- if (face != FUDaePassStateFaceType::FRONT_AND_BACK) {
- O3D_ERROR(service_locator_)
- << "Separate polygon fill modes are unsupported";
- }
- SetIntState(state, State::kFillModeParamName, mode);
- break;
- }
- case FUDaePassState::STENCIL_FUNC: {
- State::Comparison func = ConvertComparisonFunction(
- service_locator_,
- GetStateValue<FUDaePassStateFunction::Function>(pass_state, 0));
- uint8 ref = GetStateValue<uint8>(pass_state, 4);
- uint8 mask = GetStateValue<uint8>(pass_state, 5);
- SetIntState(state, State::kStencilComparisonFunctionParamName, func);
- SetIntState(state, State::kStencilReferenceParamName, ref);
- SetIntState(state, State::kStencilMaskParamName, mask);
- SetBoolState(state, State::kTwoSidedStencilEnableParamName, false);
- break;
- }
- case FUDaePassState::STENCIL_FUNC_SEPARATE: {
- State::Comparison front = ConvertComparisonFunction(
- service_locator_,
- GetStateValue<FUDaePassStateFunction::Function>(pass_state, 0));
- State::Comparison back = ConvertComparisonFunction(
- service_locator_,
- GetStateValue<FUDaePassStateFunction::Function>(pass_state, 1));
- uint8 ref = GetStateValue<uint8>(pass_state, 8);
- uint8 mask = GetStateValue<uint8>(pass_state, 9);
- SetIntState(state, State::kStencilComparisonFunctionParamName, front);
- SetIntState(state, State::kCCWStencilComparisonFunctionParamName, back);
- SetIntState(state, State::kStencilReferenceParamName, ref);
- SetIntState(state, State::kStencilMaskParamName, mask);
- SetBoolState(state, State::kTwoSidedStencilEnableParamName, true);
- break;
- }
- case FUDaePassState::STENCIL_OP: {
- State::StencilOperation fail = ConvertStencilOp(
- service_locator_,
- GetStateValue<FUDaePassStateStencilOperation::Operation>(pass_state,
- 0));
- State::StencilOperation zfail = ConvertStencilOp(
- service_locator_,
- GetStateValue<FUDaePassStateStencilOperation::Operation>(pass_state,
- 1));
- State::StencilOperation zpass = ConvertStencilOp(
- service_locator_,
- GetStateValue<FUDaePassStateStencilOperation::Operation>(pass_state,
- 2));
- SetStencilSettings(state, front_cw_, fail, zfail, zpass);
- SetBoolState(state, State::kTwoSidedStencilEnableParamName, false);
- break;
- }
- case FUDaePassState::STENCIL_OP_SEPARATE: {
- FUDaePassStateFaceType::Type type =
- GetStateValue<FUDaePassStateFaceType::Type>(pass_state, 0);
- State::StencilOperation fail = ConvertStencilOp(
- service_locator_,
- GetStateValue<FUDaePassStateStencilOperation::Operation>(pass_state,
- 0));
- State::StencilOperation zfail = ConvertStencilOp(
- service_locator_,
- GetStateValue<FUDaePassStateStencilOperation::Operation>(pass_state,
- 1));
- State::StencilOperation zpass = ConvertStencilOp(
- service_locator_,
- GetStateValue<FUDaePassStateStencilOperation::Operation>(pass_state,
- 2));
- switch (type) {
- case FUDaePassStateFaceType::FRONT:
- SetStencilSettings(state, front_cw_, fail, zfail, zpass);
- SetBoolState(state, State::kTwoSidedStencilEnableParamName, true);
- break;
- case FUDaePassStateFaceType::BACK:
- SetStencilSettings(state, !front_cw_, fail, zfail, zpass);
- SetBoolState(state, State::kTwoSidedStencilEnableParamName, true);
- break;
- case FUDaePassStateFaceType::FRONT_AND_BACK:
- SetStencilSettings(state, front_cw_, fail, zfail, zpass);
- SetStencilSettings(state, !front_cw_, fail, zfail, zpass);
- SetBoolState(state, State::kTwoSidedStencilEnableParamName, false);
- break;
- default:
- O3D_ERROR(service_locator_)
- << "Unknown polygon face mode in STENCIL_OP_SEPARATE";
- break;
- }
- break;
- }
- case FUDaePassState::STENCIL_MASK: {
- uint32 mask = GetStateValue<uint8>(pass_state, 0);
- SetIntState(state, State::kStencilWriteMaskParamName, mask);
- break;
- }
- case FUDaePassState::STENCIL_MASK_SEPARATE: {
- O3D_ERROR(service_locator_) << "Separate stencil mask is unsupported";
- break;
- }
- case FUDaePassState::COLOR_MASK: {
- bool red = GetStateValue<bool>(pass_state, 0);
- bool green = GetStateValue<bool>(pass_state, 1);
- bool blue = GetStateValue<bool>(pass_state, 2);
- bool alpha = GetStateValue<bool>(pass_state, 3);
- int mask = 0x0;
- if (red) mask |= 0x1;
- if (green) mask |= 0x2;
- if (blue) mask |= 0x4;
- if (alpha) mask |= 0x8;
- SetIntState(state, State::kColorWriteEnableParamName, mask);
- break;
- }
- case FUDaePassState::DEPTH_MASK: {
- bool value = GetStateValue<bool>(pass_state, 0);
- SetBoolState(state, State::kZWriteEnableParamName, value);
- break;
- }
- case FUDaePassState::POINT_SIZE: {
- float value = GetStateValue<float>(pass_state, 0);
- SetFloatState(state, State::kPointSizeParamName, value);
- break;
- }
- case FUDaePassState::POLYGON_OFFSET: {
- float value1 = GetStateValue<float>(pass_state, 0);
- float value2 = GetStateValue<float>(pass_state, 1);
- SetFloatState(state, State::kPolygonOffset1ParamName, value1);
- SetFloatState(state, State::kPolygonOffset2ParamName, value2);
- break;
- }
- case FUDaePassState::BLEND_COLOR: {
- FMVector4 value = GetStateValue<FMVector4>(pass_state, 0);
- Float4 v(value.x, value.y, value.z, value.w);
- SetFloat4State(state, State::kPolygonOffset1ParamName, v);
- break;
- }
- case FUDaePassState::ALPHA_TEST_ENABLE: {
- bool value = GetStateValue<bool>(pass_state, 0);
- SetBoolState(state, State::kAlphaTestEnableParamName, value);
- break;
- }
- case FUDaePassState::BLEND_ENABLE: {
- bool value = GetStateValue<bool>(pass_state, 0);
- SetBoolState(state, State::kAlphaBlendEnableParamName, value);
- break;
- }
- case FUDaePassState::CULL_FACE_ENABLE: {
- cull_enabled_ = GetStateValue<bool>(pass_state, 0);
- UpdateCullingState(state);
- break;
- }
- case FUDaePassState::DEPTH_TEST_ENABLE: {
- bool value = GetStateValue<bool>(pass_state, 0);
- SetBoolState(state, State::kZEnableParamName, value);
- break;
- }
- case FUDaePassState::DITHER_ENABLE: {
- bool value = GetStateValue<bool>(pass_state, 0);
- SetBoolState(state, State::kDitherEnableParamName, value);
- break;
- }
- case FUDaePassState::LINE_SMOOTH_ENABLE: {
- bool value = GetStateValue<bool>(pass_state, 0);
- SetBoolState(state, State::kLineSmoothEnableParamName, value);
- break;
- }
- case FUDaePassState::STENCIL_TEST_ENABLE: {
- bool value = GetStateValue<bool>(pass_state, 0);
- SetBoolState(state, State::kStencilEnableParamName, value);
- break;
- }
- default:
- // do nothing
- break;
- }
-}
-
-// Converts an FCollada texture sampler wrap mode to an O3D Sampler
-// AddressMode.
-static Sampler::AddressMode ConvertSamplerAddressMode(
- FUDaeTextureWrapMode::WrapMode wrap_mode) {
- switch (wrap_mode) {
- case FUDaeTextureWrapMode::WRAP:
- return Sampler::WRAP;
- case FUDaeTextureWrapMode::MIRROR:
- return Sampler::MIRROR;
- case FUDaeTextureWrapMode::CLAMP:
- return Sampler::CLAMP;
- case FUDaeTextureWrapMode::BORDER:
- return Sampler::BORDER;
- default:
- return Sampler::WRAP;
- }
-}
-
-// Converts an FCollada filter func to an O3D Sampler FilterType.
-// Since the Collada filter spec allows both GL-style combo mag/min filters,
-// and DX-style (separate min/mag/mip filters), this function extracts
-// only the first (min) part of a GL-style filter.
-static Sampler::FilterType ConvertFilterType(
- FUDaeTextureFilterFunction::FilterFunction filter_function,
- bool allow_none) {
- switch (filter_function) {
- case FUDaeTextureFilterFunction::NEAREST:
- case FUDaeTextureFilterFunction::NEAREST_MIPMAP_NEAREST:
- case FUDaeTextureFilterFunction::NEAREST_MIPMAP_LINEAR:
- return Sampler::POINT;
- case FUDaeTextureFilterFunction::LINEAR:
- case FUDaeTextureFilterFunction::LINEAR_MIPMAP_NEAREST:
- case FUDaeTextureFilterFunction::LINEAR_MIPMAP_LINEAR:
- return Sampler::LINEAR;
- // TODO(o3d): Once FCollada supports COLLADA v1.5, turn this on:
- // case FUDaeTextureFilterFunction::ANISOTROPIC:
- // return Sampler::ANISOTROPIC;
- case FUDaeTextureFilterFunction::NONE:
- return allow_none ? Sampler::NONE : Sampler::LINEAR;
- default:
- return Sampler::LINEAR;
- }
-}
-
-
-// Retrieves the mipmap part of a GL-style filter function.
-// If no mipmap part is specified, it is assumed to be POINT.
-static Sampler::FilterType ConvertMipmapFilter(
- FUDaeTextureFilterFunction::FilterFunction filter_function) {
- switch (filter_function) {
- case FUDaeTextureFilterFunction::NEAREST_MIPMAP_NEAREST:
- case FUDaeTextureFilterFunction::LINEAR_MIPMAP_NEAREST:
- case FUDaeTextureFilterFunction::UNKNOWN:
- return Sampler::POINT;
- case FUDaeTextureFilterFunction::NEAREST_MIPMAP_LINEAR:
- case FUDaeTextureFilterFunction::LINEAR_MIPMAP_LINEAR:
- return Sampler::LINEAR;
- default:
- return Sampler::NONE;
- }
-}
-
-// Sets the texture sampler states on an O3D sampler from the
-// settings found in an FCollada sampler.
-// Parameters:
-// effect_sampler: The FCollada sampler.
-// o3d_sampler: The O3D sampler object.
-void Collada::SetSamplerStates(FCDEffectParameterSampler* effect_sampler,
- Sampler* o3d_sampler) {
- FUDaeTextureWrapMode::WrapMode wrap_s = effect_sampler->GetWrapS();
- FUDaeTextureWrapMode::WrapMode wrap_t = effect_sampler->GetWrapT();
- Texture *texture = o3d_sampler->texture();
- if (texture && texture->IsA(TextureCUBE::GetApparentClass())) {
- // Our default is WRAP, but cube maps should use CLAMP
- if (wrap_s == FUDaeTextureWrapMode::UNKNOWN)
- wrap_s = FUDaeTextureWrapMode::CLAMP;
- if (wrap_t == FUDaeTextureWrapMode::UNKNOWN)
- wrap_t = FUDaeTextureWrapMode::CLAMP;
- }
-
- FUDaeTextureFilterFunction::FilterFunction min_filter =
- effect_sampler->GetMinFilter();
- FUDaeTextureFilterFunction::FilterFunction mag_filter =
- effect_sampler->GetMagFilter();
-
- FUDaeTextureFilterFunction::FilterFunction mip_filter =
- effect_sampler->GetMipFilter();
- // TODO(o3d): Once FCollada supports COLLADA v1.5, turn this on:
- // int max_anisotropy = effect_sampler->GetMaxAnisotropy();
-
- o3d_sampler->set_address_mode_u(ConvertSamplerAddressMode(wrap_s));
- o3d_sampler->set_address_mode_v(ConvertSamplerAddressMode(wrap_t));
-
- // The Collada spec allows for both DX-style and GL-style specification
- // of texture filtering modes. In DX-style, Min, Mag and Mip filters
- // are specified separately, and may be Linear, Point or None.
- // In GL-style, only Min and Mag are specified, with the Mip filter
- // encoded as a combo setting in the Min filter. E.g.,
- // LinearMipmapLinear => Min Linear, Mip Linear,
- // LinearMipmapNearest => Min Linear, Mip Point,
- // Linear => Min Linear, Mip None (no mipmapping).
-
- // In order to sort this out, if the Mip filter is "unknown" (missing),
- // we assume GL-style specification, and extract the Mip setting from
- // the latter part of the GL-style Min setting. If the Mip filter is
- // specified, we assume a DX-style specification, and the three
- // components are assigned separately. Any GL-style combo
- // modes used in DX mode are ignored (only the first part is used).
-
- o3d_sampler->set_min_filter(ConvertFilterType(min_filter, false));
- o3d_sampler->set_mag_filter(ConvertFilterType(mag_filter, false));
-
- // If the mip filter is set to "UNKNOWN", we assume it's a GL-style
- // mode, and use the 2nd part of the Min filter for the mip type. Otherwise,
- // we use the first part.
- if (mip_filter == FUDaeTextureFilterFunction::UNKNOWN) {
- o3d_sampler->set_mip_filter(ConvertMipmapFilter(min_filter));
- } else {
- o3d_sampler->set_mip_filter(ConvertFilterType(mip_filter, true));
- }
-
- // TODO(o3d): Once FCollada supports COLLADA v1.5, turn this on:
- // o3d_sampler->set_max_anisotropy(max_anisotropy);
-}
-
-// Sets the value of a Param on the given ParamObject from an FCollada
-// standard-profile effect parameter. If the FCollada parameter
-// contains a texture, the sampler_param_name and channel is used to set
-// a Sampler Param in o3d from the surface. If not, the
-// color_param_name is used to create set a vector Param value.
-// Parameters:
-// effect_standard: The fixed-function FCollada effect from which
-// to retrieve the parameter value.
-// param_object: The ParamObject on which parameters will be set.
-// color_param_mame: The name of the param to set, if a vector.
-// sampler_param_mame: The name of the param to set, if a texture sampler.
-// color_param: The FCollada parameter from which to retrieve the
-// new value.
-// channel: The texture channel to use (if any).
-void Collada::SetParamFromStandardEffectParam(
- FCDEffectStandard* effect_standard,
- ParamObject* param_object,
- const char* color_param_name,
- const char* sampler_param_name,
- FCDEffectParameter* color_param,
- int channel) {
- if (effect_standard->GetTextureCount(channel) > 0) {
- FCDTexture* texture = effect_standard->GetTexture(channel, 0);
- FCDEffectParameterSampler* sampler = texture->GetSampler();
- SetParamFromFCEffectParam(param_object, sampler_param_name, sampler);
- } else if (color_param) {
- SetParamFromFCEffectParam(param_object, color_param_name, color_param);
- }
-}
-
-// Sets the values of a ParamObject parameters from a given FCollada material
-// node. If a corresponding ParamObject parameter is not found, the FCollada
-// parameter is ignored.
-// TODO(o3d): Should we ignore params not found? Maybe the user wants those for
-// things other than rendering.
-// Parameters:
-// material: The FCollada material node from which to retrieve values.
-// param_object: The ParamObject on which parameters will be set.
-void Collada::SetParamsFromMaterial(FCDMaterial* material,
- ParamObject* param_object) {
- size_t pcount = material->GetEffectParameterCount();
- // TODO(o3d): This test (for determining if we used the
- // programmable profile or the fixed-func profile) is not very robust.
- // Remove this once the Material changes are in.
- if (pcount > 0) {
- for (size_t i = 0; i < pcount; ++i) {
- FCDEffectParameter* p = material->GetEffectParameter(i);
- LOG_ASSERT(p);
- String param_name(p->GetReference());
- // Check for an effect binding
- FCDEffectProfileFX* profile_fx = FindProfileFX(material->GetEffect());
- if (profile_fx) {
- FCDEffectTechnique* technique = profile_fx->GetTechnique(0);
- if (technique->GetPassCount() > 0) {
- FCDEffectPass* pass = technique->GetPass(0);
- for (size_t j = 0; j < pass->GetShaderCount(); ++j) {
- FCDEffectPassShader* shader = pass->GetShader(j);
- FCDEffectPassBind* bind =
- shader->FindBindingReference(p->GetReference());
- if (bind) {
- param_name = *bind->symbol;
- break;
- }
- }
- }
- }
- SetParamFromFCEffectParam(param_object, param_name, p);
- }
- } else {
- FCDEffect* effect = material->GetEffect();
- FCDEffectStandard* effect_standard;
- if (effect && (effect_standard = static_cast<FCDEffectStandard *>(
- effect->FindProfile(FUDaeProfileType::COMMON))) != NULL) {
- SetParamFromStandardEffectParam(effect_standard,
- param_object,
- kMaterialParamNameEmissive,
- kMaterialParamNameEmissiveSampler,
- effect_standard->GetEmissionColorParam(),
- FUDaeTextureChannel::EMISSION);
- SetParamFromStandardEffectParam(effect_standard,
- param_object,
- kMaterialParamNameAmbient,
- kMaterialParamNameAmbientSampler,
- effect_standard->GetAmbientColorParam(),
- FUDaeTextureChannel::AMBIENT);
- SetParamFromStandardEffectParam(effect_standard,
- param_object,
- kMaterialParamNameDiffuse,
- kMaterialParamNameDiffuseSampler,
- effect_standard->GetDiffuseColorParam(),
- FUDaeTextureChannel::DIFFUSE);
- SetParamFromStandardEffectParam(effect_standard,
- param_object,
- kMaterialParamNameSpecular,
- kMaterialParamNameSpecularSampler,
- effect_standard->GetSpecularColorParam(),
- FUDaeTextureChannel::SPECULAR);
- SetParamFromStandardEffectParam(effect_standard,
- param_object,
- NULL,
- kMaterialParamNameBumpSampler,
- NULL,
- FUDaeTextureChannel::BUMP);
- SetParamFromFCEffectParam(param_object,
- kMaterialParamNameShininess,
- effect_standard->GetShininessParam());
- SetParamFromFCEffectParam(param_object,
- kMaterialParamNameSpecularFactor,
- effect_standard->GetSpecularFactorParam());
- }
- }
-}
-} // namespace o3d
diff --git a/o3d/import/cross/collada.h b/o3d/import/cross/collada.h
deleted file mode 100644
index 18b5937..0000000
--- a/o3d/import/cross/collada.h
+++ /dev/null
@@ -1,507 +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 functions for importing COLLADA files into O3D.
-
-#ifndef O3D_IMPORT_CROSS_COLLADA_H_
-#define O3D_IMPORT_CROSS_COLLADA_H_
-
-#include <map>
-#include <string>
-#include <vector>
-#include "base/file_path.h"
-#include "core/cross/param.h"
-#include "core/cross/types.h"
-#include "utils/cross/file_path_utils.h"
-
-class FCDocument;
-class FCDAnimated;
-class FCDCamera;
-class FCDSceneNode;
-class FCDGeometry;
-class FCDGeometryInstance;
-class FCDControllerInstance;
-class FCDMaterial;
-class FCDEffect;
-class FCDEffectStandard;
-class FCDEffectParameter;
-class FCDEffectParameterSampler;
-class FCDEffectParameterSurface;
-class FCDEffectPassState;
-class FCDImage;
-class FCDTMatrix;
-class FCDTTranslation;
-class FCDTRotation;
-class FCDTScale;
-
-class FilePath;
-
-namespace o3d {
-
-class ClassManager;
-class ColladaZipArchive;
-class Effect;
-class IErrorStatus;
-class Material;
-class Pack;
-class ParamObject;
-class Sampler;
-class ShaderBuilderHelper;
-class Shape;
-class State;
-class Texture;
-class Transform;
-class TranslationMap;
-
-// This class keeps an association between a Collada node instance and a
-// transform.
-// This takes ownership of its children NodeInstances.
-class NodeInstance {
- public:
- typedef std::vector<NodeInstance *> NodeInstanceList;
-
- explicit NodeInstance(FCDSceneNode *node) : node_(node), transform_(NULL) {}
- ~NodeInstance() {
- for (unsigned int i = 0; i < children_.size(); ++i) {
- delete children_[i];
- }
- }
-
- // Gets the Collada node associated with this node instance.
- FCDSceneNode *node() const { return node_; }
-
- // Gets the Transform associated with this node instance.
- Transform *transform() const { return transform_; }
-
- // Sets the Transform associated with this node instance.
- void set_transform(Transform *transform) { transform_ = transform; }
-
- // Gets the list of this node instance's children.
- NodeInstanceList &children() { return children_; }
-
- // Finds the NodeInstance representing a scene node in the direct children of
- // this NodeInstance.
- NodeInstance *FindNodeShallow(FCDSceneNode *node) {
- for (unsigned int i = 0; i < children_.size(); ++i) {
- NodeInstance *child = children_[i];
- if (child->node() == node) return child;
- }
- return NULL;
- }
-
- // Finds the NodeInstance representing a scene node in the sub-tree starting
- // at this NodeInstance.
- NodeInstance *FindNodeInTree(FCDSceneNode *node);
-
- private:
- FCDSceneNode *node_;
- Transform *transform_;
- std::vector<NodeInstance *> children_;
-};
-
-class ColladaDataMap {
- public:
- // Adds a data to a filepath. Note, it is an error to associate more than one
- // data to the same filepath.
- bool AddData(const FilePath& file_path,
- const std::string& data,
- ServiceLocator* service_locator);
-
- // Access to the filenames of the original data for texture and
- // sound assets imported when ImportFile was called. These will
- // only return results after an import if the keep_original_data
- // option was set to true when the Collada object was created.
- std::vector<FilePath> GetOriginalDataFilenames() const;
- const std::string& GetOriginalData(const FilePath& filename) const;
-
- // Clears the map.
- void Clear();
-
- private:
- // A map containing the original data (still in original format)
- // used to create the textures, sounds, etc., indexed by filename.
- typedef std::map<FilePath, std::string> OriginalDataMap;
- OriginalDataMap original_data_;
-};
-
-class Collada {
- public:
- struct Options {
- Options()
- : generate_mipmaps(true),
- keep_original_data(false),
- condition_document(false),
- up_axis(0.0f, 0.0f, 0.0f),
- base_path(FilePath::kCurrentDirectory),
- convert_dds_to_png(false),
- convert_cg_to_glsl(false),
- converter_tool() {}
- // Whether or not to generate mip-maps on the textures we load.
- bool generate_mipmaps;
-
- // Whether or not to retain the original form for textures for later
- // access by filename.
- bool keep_original_data;
-
- // Whether or not to condition documents for o3d as part of
- // loading them.
- bool condition_document;
-
- // What the up-axis of the imported geometry should be.
- Vector3 up_axis;
-
- // The base path to use for determining the relative paths for
- // asset URIs.
- FilePath base_path;
-
- // A List of paths to search for files in.
- std::vector<FilePath> file_paths;
-
- // True means convert DDS files to PNGs. For cube map textures, this
- // implies writing six separate PNGs.
- bool convert_dds_to_png;
-
- // If true, run converter tool on shaders.
- bool convert_cg_to_glsl;
-
- // Path to the shader converter tool.
- FilePath converter_tool;
- };
-
- // Collada Param Names.
- // TODO(gman): Remove these as we switch this stuff to JSON
- static const char* kLightingTypeParamName;
-
- // Lighitng Types.
- // TODO(gman): Remove these as we switch this stuff to JSON
- static const char* kLightingTypeConstant;
- static const char* kLightingTypePhong;
- static const char* kLightingTypeBlinn;
- static const char* kLightingTypeLambert;
- static const char* kLightingTypeUnknown;
-
- // Material Param Names.
- static const char* kMaterialParamNameEmissive;
- static const char* kMaterialParamNameAmbient;
- static const char* kMaterialParamNameDiffuse;
- static const char* kMaterialParamNameSpecular;
- static const char* kMaterialParamNameShininess;
- static const char* kMaterialParamNameSpecularFactor;
- static const char* kMaterialParamNameEmissiveSampler;
- static const char* kMaterialParamNameAmbientSampler;
- static const char* kMaterialParamNameDiffuseSampler;
- static const char* kMaterialParamNameSpecularSampler;
- static const char* kMaterialParamNameBumpSampler;
-
- // Use this if you need access to data after the import (as the
- // converter does).
- Collada(Pack* pack, const Options& options);
- virtual ~Collada();
-
- // Imports the given COLLADA file or ZIP file into the given scene.
- // This is the external interface to o3d.
- // Parameters:
- // pack: The pack into which the scene objects will be placed.
- // filename: The COLLADA or ZIPped COLLADA file to import.
- // parent: The parent node under which the imported nodes will be placed.
- // If NULL, nodes will be placed under the client's root.
- // animation_input: The counter parameter used to control transform
- // animation in the collada file.
- // options: The Options structure (see above) that describes any
- // desired options.
- // Returns true on success.
- static bool Import(Pack* pack,
- const FilePath& filename,
- Transform* parent,
- ParamFloat* animation_input,
- const Options& options);
-
- // Same thing but with String filename.
- static bool Import(Pack* pack,
- const String& filename,
- Transform* parent,
- ParamFloat* animation_input,
- const Options& options);
-
- // Imports the given COLLADA file or ZIP file into the pack given to
- // the constructor.
- bool ImportFile(const FilePath& filename, Transform* parent,
- ParamFloat* animation_input);
-
- // Init the Collada Importer.
- static void Init(ServiceLocator* service_locator);
-
- const ColladaDataMap& original_data_map() const {
- return original_data_map_;
- }
-
- private:
- // Imports the given ZIP file into the given pack.
- bool ImportZIP(const FilePath& filename, Transform* parent,
- ParamFloat* animation_input);
-
- // Imports the given COLLADA file (.DAE) into the current pack.
- bool ImportDAE(const FilePath& filename,
- Transform* parent,
- ParamFloat* animation_input);
-
- // Imports the given FCDocument (already loaded) into the current pack.
- bool ImportDAEDocument(FCDocument* doc,
- bool fc_status,
- Transform* parent,
- ParamFloat* animation_input);
-
- // Creates the instance tree corresponding to the collada scene node DAG.
- // A separate NodeInstance is created every time a particular node is
- // traversed. The caller must destroy the returned NodeInstance.
- static NodeInstance *CreateInstanceTree(FCDSceneNode *node);
-
- // Recursively imports a tree of nodes from FCollada, rooted at the
- // given node, into the O3D scene.
- bool ImportTree(NodeInstance *instance,
- Transform* parent,
- ParamFloat* animation_input);
-
- // Recursively imports a tree of instances (shapes, etc..) from FCollada,
- // rooted at the given node, into the O3D scene. This is a separate step
- // from ImportTree because various kinds of instances can reference other
- // parts of the tree.
- bool ImportTreeInstances(FCDocument* doc,
- NodeInstance* instance);
-
- bool BuildFloatAnimation(ParamFloat* result,
- FCDAnimated* animated,
- const char* qualifier,
- ParamFloat* animation_input,
- float output_scale,
- float default_value);
-
- bool BuildFloat3Animation(ParamFloat3* result, FCDAnimated* animated,
- ParamFloat* animation_input,
- const Float3& default_value);
-
- ParamMatrix4* BuildComposition(FCDTMatrix* transform,
- ParamMatrix4* input_matrix,
- ParamFloat* animation_input);
-
- ParamMatrix4* BuildComposition(const Matrix4& matrix,
- ParamMatrix4* input_matrix);
-
- ParamMatrix4* BuildTranslation(FCDTTranslation* transform,
- ParamMatrix4* input_matrix,
- ParamFloat* animation_input);
-
- ParamMatrix4* BuildRotation(FCDTRotation* transform,
- ParamMatrix4* input_matrix,
- ParamFloat* animation_input);
-
- ParamMatrix4* BuildScaling(FCDTScale* transform,
- ParamMatrix4* input_matrix,
- ParamFloat* animation_input);
-
- // Builds a Transform node corresponding to the transform elements of
- // a given node. All transformations (rotation, translation, scale,
- // etc) are collapsed into a single Transform.
- Transform* BuildTransform(FCDSceneNode* node,
- Transform* parent_transform,
- ParamFloat* animation_input);
-
- // Extracts the various camera parameters from a Collada Camera object and
- // stored them as Params on an O3D Transform.
- void BuildCamera(FCDocument* doc,
- FCDCamera* camera,
- Transform* transform,
- FCDSceneNode* parent_node);
-
- // Gets an O3D shape corresponding to a given FCollada geometry instance.
- // If the Shape does not exist, Builds one.
- Shape* GetShape(FCDocument* doc,
- FCDGeometryInstance* geom_instance);
-
- // Builds O3D shape corresponding to a given FCollada geometry instance.
- Shape* BuildShape(FCDocument* doc,
- FCDGeometryInstance* geom_instance,
- FCDGeometry* geom,
- TranslationMap* translationMap);
-
- // Gets an O3D skinned shape corresponding to a given FCollada controller
- // instance. If the Shape does not exist, Builds one.
- Shape* GetSkinnedShape(FCDocument* doc,
- FCDControllerInstance* instance,
- NodeInstance *parent_node_instance,
- Transform* parent);
-
- // Builds O3D skinned shape corresponding to a given FCollada controller
- // instance.
- Shape* BuildSkinnedShape(FCDocument* doc,
- FCDControllerInstance* instance,
- NodeInstance *parent_node_instance,
- Transform* parent);
-
- // Builds an O3D texture corresponding to a given FCollada surface
- // parameter.
- Texture* BuildTexture(FCDEffectParameterSurface* surface);
-
- // Builds an O3D texture corresponding to a given FCDImage.
- Texture* BuildTextureFromImage(FCDImage* image);
-
- // Builds an O3D material from a COLLADA effect and material. If a
- // COLLADA-FX (Cg/HLSL) effect is present, it will be used and a programmable
- // Effect generated. If not, an attempt is made to use one of the fixed-
- // function profiles if present (eg., Constant, Lambert).
- Material* BuildMaterial(FCDocument* doc, FCDMaterial* material);
-
- // Gets an O3D effect correpsonding to a given FCollada effect. If the
- // effect does not already exist it is created.
- Effect* GetEffect(FCDocument* doc, FCDEffect* effect);
-
- // Builds an O3D effect from a COLLADA effect and material. If a
- // COLLADA-FX (Cg/HLSL) effect is present, it will be used and a programmable
- // Effect generated. If not, an attempt is made to use one of the fixed-
- // function profiles if present (eg., Constant, Lambert).
- Effect* BuildEffect(FCDocument* doc, FCDEffect* effect);
-
- // Copies the texture sampler states from an FCollada sampler to an O3D
- // sampler.
- void SetSamplerStates(FCDEffectParameterSampler* effect_sampler,
- Sampler* o3d_sampler);
-
- // Converts the given COLLADA pass state into one or more state
- // parameters on the given O3D state object.
- void AddRenderState(FCDEffectPassState* pass_state, State* state);
-
- // Sets the O3D culling state based on the OpenGL-style states that
- // COLLADA-FX uses, cached in cull_enabled_, cull_front_ and front_cw_.
- void UpdateCullingState(State* state);
-
- // Sets an O3D parameter value from a given FCollada effect parameter.
- bool SetParamFromFCEffectParam(ParamObject *param_object,
- const String &param_name,
- FCDEffectParameter *fc_param);
-
- // Sets the value of a Param on the given ParamObject from an FCollada
- // standard-profile effect parameter. If the FCollada parameter
- // contains a texture, the sampler_param_name and channel is used to set
- // a Sampler Param in o3d from the surface. If not, the
- // color_param_name is used to create set a vector Param value.
- void SetParamFromStandardEffectParam(FCDEffectStandard* effect_standard,
- ParamObject* param_object,
- const char* color_param_name,
- const char* sampler_param_name,
- FCDEffectParameter* color_param,
- int channel);
-
- // Sets the values of shape parameters from a given FCollada material node.
- // If a corresponding shape parameter is not found, the FCollada parameter
- // is ignored.
- void SetParamsFromMaterial(FCDMaterial* material, ParamObject* param_object);
-
- // Finds a node instance corresponding to a scene node. Since a particular
- // scene node can be instanced multiple times, this will return an arbitrary
- // instance.
- NodeInstance *FindNodeInstance(FCDSceneNode *node);
-
- // Finds the node instance corresponding to a scene node if it is not
- // instanced, by following the only parent of the nodes until it reaches the
- // root. This will return NULL if the node can't be found, or if the node is
- // instanced more than once.
- NodeInstance *FindNodeInstanceFast(FCDSceneNode *node);
-
- // Clears out any residual data from the last import. Doesn't
- // affect the Pack or the options, just intermediate data structures
- // in this object.
- void ClearData();
-
- // Gets a dummy effect or creates one if none exists.
- Effect* GetDummyEffect();
-
- // Gets a dummy material or creates one if none exists.
- Material* GetDummyMaterial();
-
- ServiceLocator* service_locator_;
-
- // The object from which error status is retreived.
- IErrorStatus* error_status_;
-
- // The Pack into which newly-created nodes will be placed.
- Pack* pack_;
-
- // The import options to use;
- Options options_;
-
- // The effect used if we can't create an effect.
- Effect* dummy_effect_;
-
- // The material used if we can't create a material.
- Material* dummy_material_;
-
- // The root of the instance node tree.
- NodeInstance* instance_root_;
-
- // A map of the Textures created by the importer, indexed by filename.
- std::map<const std::wstring, Texture*> textures_;
-
- // A map of the Effects created by the importer, indexed by DAE id.
- std::map<const std::string, Effect*> effects_;
-
- // A map of the Shapes created by the importer, indexed by DAE id.
- std::map<const std::string, Shape*> shapes_;
-
- // A map of the Skinned Shapes created by the importer, indexed by DAE id.
- std::map<const std::string, Shape*> skinned_shapes_;
-
- // A map of the Materials created by the importer, indexed by DAE id.
- std::map<const std::string, Material*> materials_;
-
- // All the errors accumlated during loading.
- String errors_;
-
- // The absolute path to the top of the model hierarchy, to use for
- // determining the relative paths to other files.
- FilePath base_path_;
-
- // Original data by FilePath
- ColladaDataMap original_data_map_;
-
- ColladaZipArchive *collada_zip_archive_;
-
- // Some temporaries used by the state importer
- bool cull_enabled_;
- bool cull_front_;
- bool front_cw_;
-
- int unique_filename_counter_;
-
- DISALLOW_COPY_AND_ASSIGN(Collada);
-};
-}
-#endif // O3D_IMPORT_CROSS_COLLADA_H_
diff --git a/o3d/import/cross/collada_conditioner.cc b/o3d/import/cross/collada_conditioner.cc
deleted file mode 100644
index b5fef31..0000000
--- a/o3d/import/cross/collada_conditioner.cc
+++ /dev/null
@@ -1,578 +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 "import/cross/precompile.h"
-
-#include "import/cross/collada_conditioner.h"
-
-#include "base/file_path.h"
-#include "base/file_util.h"
-#include "base/utf_string_conversions.h"
-#include "compiler/technique/technique_parser.h"
-#include "core/cross/error.h"
-#include "core/cross/types.h"
-#include "import/cross/collada.h"
-#include "import/cross/collada_zip_archive.h"
-#include "utils/cross/file_path_utils.h"
-#include "utils/cross/temporary_file.h"
-
-namespace o3d {
-namespace {
-FUDaeTextureFilterFunction::FilterFunction LookupFilterFunction(
- const char* name) {
- struct {
- const char* name;
- FUDaeTextureFilterFunction::FilterFunction func;
- } functions[] = {
- {"None", FUDaeTextureFilterFunction::NONE},
- {"Linear", FUDaeTextureFilterFunction::LINEAR},
- {"Point", FUDaeTextureFilterFunction::NEAREST}, // DX
- {"Nearest", FUDaeTextureFilterFunction::NEAREST}, // GL
- {"LinearMipmapLinear", FUDaeTextureFilterFunction::LINEAR_MIPMAP_LINEAR},
- {"LinearMipmapNearest", FUDaeTextureFilterFunction::LINEAR_MIPMAP_NEAREST},
- {"NearestMipmapNearest", FUDaeTextureFilterFunction::LINEAR_MIPMAP_NEAREST},
- {"NearestMipmapLinear", FUDaeTextureFilterFunction::NEAREST_MIPMAP_LINEAR},
- // TODO: Once FCollada supports the COLLADA v1.5 spec,
- // turn this on.
- // "Anisotropic", FUDaeTextureFilterFunction::ANISOTROPIC,
- };
- for (size_t i = 0; i < sizeof(functions) / sizeof(functions[0]); ++i) {
- if (!base::strcasecmp(functions[i].name, name)) {
- return functions[i].func;
- }
- }
- return FUDaeTextureFilterFunction::UNKNOWN;
-}
-
-#undef CLAMP
-
-FUDaeTextureWrapMode::WrapMode LookupWrapMode(const char* name) {
- struct {
- const char* name;
- FUDaeTextureWrapMode::WrapMode mode;
- } modes[] = {
- {"None", FUDaeTextureWrapMode::NONE},
- // DX-style names:
- {"Wrap", FUDaeTextureWrapMode::WRAP},
- {"Mirror", FUDaeTextureWrapMode::MIRROR},
- {"Clamp", FUDaeTextureWrapMode::CLAMP},
- {"Border", FUDaeTextureWrapMode::BORDER},
- // GL-style names:
- {"Repeat", FUDaeTextureWrapMode::WRAP},
- {"MirroredRepeat", FUDaeTextureWrapMode::MIRROR},
- {"ClampToEdge", FUDaeTextureWrapMode::CLAMP},
- {"ClampToBorder", FUDaeTextureWrapMode::BORDER},
- };
- for (size_t i = 0; i < sizeof(modes) / sizeof(modes[0]); ++i) {
- if (!base::strcasecmp(modes[i].name, name)) {
- return modes[i].mode;
- }
- }
- return FUDaeTextureWrapMode::UNKNOWN;
-}
-
-FCDEffectParameter* FindParameter(FCDMaterial* material, const char* name) {
- for (size_t i = 0; i < material->GetEffectParameterCount(); ++i) {
- FCDEffectParameter* p = material->GetEffectParameter(i);
- if (!strcmp(p->GetReference(), name)) {
- return p;
- }
- }
- return NULL;
-}
-
-void SetSamplerStates(const SamplerState& sampler,
- FCDEffectParameterSampler* sampler_out) {
- sampler_out->SetReference(sampler.name.c_str());
- sampler_out->SetMinFilter(LookupFilterFunction(sampler.min_filter.c_str()));
- sampler_out->SetMagFilter(LookupFilterFunction(sampler.mag_filter.c_str()));
- sampler_out->SetMipFilter(LookupFilterFunction(sampler.mip_filter.c_str()));
- sampler_out->SetWrapS(LookupWrapMode(sampler.address_u.c_str()));
- sampler_out->SetWrapT(LookupWrapMode(sampler.address_u.c_str()));
-
- // TODO: Once FCollada supports the COLLADA v1.5 spec, turn this on.
- // sampler_out->SetMaxAnisotropy(atoi(sampler.max_anisotropy.c_str()));
-}
-
-const PassDeclaration* FindValidTechnique(
- const TechniqueDeclarationList& technique_list) {
-
- // Look for a ps2_0/vs2_0 technique, or an arbfp1/arbvp1 technique
- TechniqueDeclarationList::const_iterator i;
- for (i = technique_list.begin(); i != technique_list.end(); ++i) {
- // Skip all multi-pass techniques
- if (i->pass.size() != 1) continue;
-
- const PassDeclaration& pass = i->pass[0];
- if ((pass.vertex_shader_profile == "vs_2_0" &&
- pass.fragment_shader_profile == "ps_2_0") ||
- (pass.vertex_shader_profile == "arbvp1" &&
- pass.fragment_shader_profile == "arbfp1")) {
- return &pass;
- }
- }
- return NULL;
-}
-
-bool IsColumnMajor(const PassDeclaration* pass) {
- return pass->vertex_shader_profile == "arbvp1" ||
- pass->fragment_shader_profile == "arbfp1";
-}
-} // end anonymous namespace.
-
-ColladaConditioner::ColladaConditioner(ServiceLocator* service_locator)
- : service_locator_(service_locator) {
-}
-
-ColladaConditioner::~ColladaConditioner() {
-}
-
-bool ColladaConditioner::HandleEmbeddedShaders(FCDEffect* collada_effect,
- FCDEffectProfileFX* profile_fx,
- ColladaZipArchive* archive) {
- bool found = false;
- size_t len = profile_fx->GetTechniqueCount();
- for (size_t j = 0; j < len && !found; ++j) {
- FCDEffectTechnique* technique = profile_fx->GetTechnique(j);
- if (!technique) continue;
- // We only support single-pass effects (for now).
- if (technique->GetPassCount() != 1) continue;
- FCDEffectPass* pass = technique->GetPass(0);
- if (!pass) continue;
- FCDEffectPassShader* vertex_shader = pass->GetVertexShader();
- if (!vertex_shader) continue;
- FCDEffectPassShader* fragment_shader = pass->GetFragmentShader();
- if (!fragment_shader) continue;
- // Note: We ignore the compiler targets in the ColladaFX section,
- // since they are often wrong (ColladaMAX puts ps 3.0/vs 3.0 in,
- // regardless of the actual shader), and consult the shader file
- // itself instead.
- SamplerStateList sampler_list;
- FCDEffectCode* code = vertex_shader->GetCode();
- String shader_source_out;
- if (code->GetType() == FCDEffectCode::CODE) {
- fstring code_string = code->GetCode();
- String shader_source_in(WideToUTF8(code_string.c_str()));
- FilePath stdin_path(FILE_PATH_LITERAL("<stdin>"));
- if (RewriteShader(shader_source_in,
- &shader_source_out,
- stdin_path,
- &sampler_list,
- NULL,
- NULL)) {
- found = true;
- }
- code->SetCode(UTF8ToWide(shader_source_out).c_str());
- } else if (code->GetType() == FCDEffectCode::INCLUDE) {
- FilePath file_path(WideToFilePath(code->GetFilename().c_str()));
- TemporaryFile temp_file;
- if (!TemporaryFile::Create(&temp_file)) {
- O3D_ERROR(service_locator_) << "Unable to create temporary file '"
- << FilePathToUTF8(temp_file.path()).c_str()
- << "' for rewriting shader.";
- return false;
- }
- if (!RewriteShaderFile(archive,
- file_path,
- temp_file.path(),
- &sampler_list,
- NULL,
- NULL)) {
- return false;
- }
-
- // Read the shader from the temp file, and add it to the output map.
- String shader_source;
- if (!file_util::ReadFileToString(temp_file.path(), &shader_source)) {
- O3D_ERROR(service_locator_) << "Unable to read temporary file.";
- return false;
- }
- code->SetCode(UTF8ToWide(shader_source).c_str());
- }
- }
-
- if (!found) {
- String effect_name = WideToUTF8(collada_effect->GetName().c_str());
- O3D_ERROR(service_locator_) << "No valid technique found for effect \""
- << effect_name << "\".";
- return false;
- }
- return true;
-}
-
-// This non-standard effect technique (NV_import) is the one used by
-// 3ds Max when exporting files using native DX materials, so
-// unfortunately we have to support it.
-bool ColladaConditioner::HandleNVImport(FCDocument* doc,
- FCDEffect* collada_effect,
- const FUUri& original_uri,
- ColladaZipArchive* archive) {
- FCDExtra* extra = collada_effect->GetExtra();
- // There is no actual type tag in the XML, but FCollada constructs one
- // for us anyway.
- if (extra && extra->GetTypeCount() > 0) {
- FCDEType* type = extra->GetType(0);
- if (type) {
- FCDETechnique* technique = type->FindTechnique("NV_import");
- if (technique) {
- FCDENode* node = technique->FindChildNode("import");
- if (node) {
- FCDEAttribute* url_attrib = node->FindAttribute("url");
- if (url_attrib) {
- FUFileManager* mgr = doc->GetFileManager();
- DCHECK(mgr != NULL);
- // Escape any %hex values in the URL, resolve it relative
- // to the document root, and convert it to an absolute path.
- fstring url = FUXmlParser::XmlToString(url_attrib->GetValue());
- FUUri effect_uri = original_uri.Resolve(url);
- fstring path = effect_uri.GetAbsolutePath();
-
- FilePath in_filename(WideToFilePath(path.c_str()));
- TemporaryFile temp_file;
- if (!TemporaryFile::Create(&temp_file)) {
- O3D_ERROR(service_locator_) << "Unable to create temporary file.";
- }
- SamplerStateList sampler_list;
- // Check that the file exists; error if not.
- if (!mgr->FileExists(path)) {
- O3D_ERROR(service_locator_) << "Shader file \""
- << WideToUTF8(path.c_str()).c_str()
- << "\" does not exist.";
- return false;
- }
-
- String vs_entry;
- String ps_entry;
- if (!RewriteShaderFile(archive,
- in_filename,
- temp_file.path(),
- &sampler_list,
- &vs_entry,
- &ps_entry)) {
- return false;
- }
-
- // Create a new HLSL profile to hold the rewritten effect.
- FCDEffectProfile* profile =
- collada_effect->AddProfile(FUDaeProfileType::HLSL);
- FCDEffectProfileFX* profile_fx =
- down_cast<FCDEffectProfileFX*>(profile);
- // Move the shader file to the COLLADA-FX section.
- FCDEffectTechnique* fx_technique = profile_fx->AddTechnique();
-
- FCDEffectCode* code = profile_fx->AddCode();
-
- // Read the shader from the temp file, and add it to the
- // output map.
- String shader_source;
- if (!file_util::ReadFileToString(temp_file.path(),
- &shader_source)) {
- O3D_ERROR(service_locator_) << "Unable to read temporary file.";
- return false;
- }
-
- // Set the embedded code to the rewritten shader.
- code->SetCode(UTF8ToWide(shader_source).c_str());
-
- FCDEffectPass* pass = fx_technique->AddPass();
- FCDEffectPassShader* vertex_shader = pass->AddVertexShader();
- FCDEffectPassShader* fragment_shader =
- pass->AddFragmentShader();
-
- vertex_shader->SetCode(code);
- vertex_shader->SetName(vs_entry.c_str());
-
- fragment_shader->SetCode(code);
- fragment_shader->SetName(ps_entry.c_str());
-
- // Change the setparams
- SamplerStateList::const_iterator it;
- for (it = sampler_list.begin(); it != sampler_list.end(); ++it) {
- // Create a <sampler> tag.
- FCDEffectParameterSampler* sampler =
- down_cast<FCDEffectParameterSampler*>(
- profile->AddEffectParameter(
- FCDEffectParameter::SAMPLER));
- LOG_ASSERT(sampler != 0);
- // Set the sampler parameters from the ones found in
- // the FX file.
- SetSamplerStates(*it, sampler);
- }
-
- // For each material which uses this effect,
- FCDMaterialLibrary* lib = doc->GetMaterialLibrary();
- for (size_t i = 0; i < lib->GetEntityCount(); ++i) {
- FCDMaterial* material = lib->GetEntity(i);
- LOG_ASSERT(material != 0);
- if (material->GetEffect() == collada_effect) {
- // For each sampler in the FX file,
- SamplerStateList::const_iterator it;
- for (it = sampler_list.begin();
- it != sampler_list.end();
- ++it) {
- // Create a <sampler> tag.
- FCDEffectParameterSampler* sampler =
- down_cast<FCDEffectParameterSampler*>(
- material->AddEffectParameter(
- FCDEffectParameter::SAMPLER));
- LOG_ASSERT(sampler != 0);
- // Set the sampler states from FX file states
- SetSamplerStates(*it, sampler);
- // Set this sampler to be a modifier, so it appears
- // as a <setparam> tag in the COLLADA file.
- sampler->SetModifier();
- // Set its surface to be the mapping from the texture
- // attribute of the sampler_state in the FX file.
- FCDEffectParameter* surface = FindParameter(
- material, it->texture.c_str());
- if (surface && surface->GetType() ==
- FCDEffectParameter::SURFACE) {
- sampler->SetSurface(
- down_cast<FCDEffectParameterSurface*>(surface));
- }
- }
- }
- }
-
- // Remove the NV_import technique from the COLLADA DOM.
- technique->Release();
- }
- }
- }
- }
- }
- return true;
-}
-
-// Verifies that all shaders conform to O3D's shader language
-// (intersection of Cg and HLSL), and fix the shader and image file URLs
-// to be relative to the output file root.
-bool ColladaConditioner::ConditionDocument(FCDocument* doc,
- ColladaZipArchive* archive) {
- FUUri original_uri = doc->GetFileUrl();
- FCDEffectLibrary* effectLibrary = doc->GetEffectLibrary();
-
- for (size_t i = 0; i < effectLibrary->GetEntityCount(); ++i) {
- FCDEffect* collada_effect = effectLibrary->GetEntity(i);
- DCHECK(collada_effect != NULL);
- FCDEffectProfile* profile =
- collada_effect->FindProfile(FUDaeProfileType::HLSL);
- if (!profile) {
- profile = collada_effect->FindProfile(FUDaeProfileType::CG);
- }
- if (profile) {
- // Handle embedded shaders.
- FCDEffectProfileFX* profile_fx =
- static_cast<FCDEffectProfileFX*>(profile);
- if (!HandleEmbeddedShaders(collada_effect, profile_fx, archive)) {
- return false;
- }
- } else {
- if (!HandleNVImport(doc, collada_effect, original_uri, archive)) {
- return false;
- }
- }
- }
- return true;
-}
-
-// Rewrites the given shader file to conform to o3d specs. This
-// function finds a valid ps2.0/vs2.0 or arbvp/fp technique, writes
-// out the entry points in our comment format, and writes out the
-// shader without technique blocks. Returns false if in_filename
-// can't be opened for reading, out_filename can't be opened for
-// writing, or if the shader is not valid (see RewriteShader). If the
-// archive is non-NULL, reads its input from the given zip archive
-// instead of from the file system.
-bool ColladaConditioner::RewriteShaderFile(ColladaZipArchive* archive,
- const FilePath& in_filename,
- const FilePath& out_filename,
- SamplerStateList* sampler_list,
- String* vs_entry,
- String* ps_entry) {
- FilePath input_file = in_filename;
- TemporaryFile temporary_output_file;
- TemporaryFile temporary_input_file;
- if (!TemporaryFile::Create(&temporary_output_file)) {
- O3D_ERROR(service_locator_) << "Unable to create temporary file.";
- return false;
- }
- if (archive) {
- if (!TemporaryFile::Create(&temporary_input_file)) {
- O3D_ERROR(service_locator_) << "Unable to create temporary file.";
- return false;
- }
- input_file = temporary_input_file.path();
- size_t size = 0;
- char* contents = archive->GetColladaAssetData(FilePathToUTF8(in_filename),
- &size);
- if (file_util::WriteFile(input_file, contents, size) == -1) {
- O3D_ERROR(service_locator_) << "Unable to write to temporary file.";
- return false;
- }
- }
- if (!PreprocessShaderFile(input_file, temporary_output_file.path())) {
- return false;
- }
- String shader_source_in;
- if (!file_util::ReadFileToString(temporary_output_file.path(),
- &shader_source_in)) {
- O3D_ERROR(service_locator_) << "Unable to read temporary file.";
- return false;
- }
-
- String shader_source_out;
- if (!RewriteShader(shader_source_in,
- &shader_source_out,
- in_filename,
- sampler_list,
- vs_entry,
- ps_entry)) {
- return false;
- }
-
- if (file_util::WriteFile(out_filename,
- shader_source_out.c_str(),
- shader_source_out.size()) == -1) {
- O3D_ERROR(service_locator_) << "Couldn't write temporary shader file "
- << FilePathToUTF8(out_filename).c_str();
- return false;
- }
- return true;
-}
-
-// Rewrites the given shader to conform to o3d specs.
-// This function finds a valid ps2.0/vs2.0 or arbvp/fp technique,
-// strips the technique block from the input shader, and adds the
-// vertex and fragment shader entry points in our comment format.
-// Returns false if no valid technique could be found, or if the
-// resulting shader cannot not be compiled as both HLSL and Cg.
-bool ColladaConditioner::RewriteShader(const String& shader_source_in,
- String* shader_source_out,
- const FilePath& in_filename,
- SamplerStateList* sampler_list,
- String* ps_entry,
- String* vs_entry) {
- TechniqueDeclarationList technique_list;
- bool column_major;
-
- // Parse out the technique block and samplers from the file
- String error_string;
- if (!ParseFxString(shader_source_in,
- shader_source_out,
- sampler_list,
- &technique_list,
- &error_string)) {
- O3D_ERROR(service_locator_) << error_string;
- return false;
- }
-
- const PassDeclaration* pass = FindValidTechnique(technique_list);
-
- if (!pass) {
- O3D_ERROR(service_locator_)
- << "Couldn't find compatible technique in effect file \""
- << FilePathToUTF8(in_filename).c_str() << "\".";
- return false;
- }
-
- if (!CompileHLSL(shader_source_out->c_str(),
- pass->vertex_shader_entry,
- pass->fragment_shader_entry)) {
- O3D_ERROR(service_locator_) << "Shader file \""
- << FilePathToUTF8(in_filename).c_str()
- << "\" could not be compiled as HLSL.\n";
- return false;
- }
-
- if (!CompileCg(in_filename,
- shader_source_out->c_str(),
- pass->vertex_shader_entry,
- pass->fragment_shader_entry)) {
- O3D_ERROR(service_locator_) << "Shader file \""
- << FilePathToUTF8(in_filename).c_str()
- << "\" could not be compiled as Cg.\n";
- return false;
- }
-
- if (vs_entry) *vs_entry = pass->vertex_shader_entry;
- if (ps_entry) *ps_entry = pass->fragment_shader_entry;
- column_major = IsColumnMajor(pass);
- *shader_source_out += "// #o3d VertexShaderEntryPoint ";
- *shader_source_out += pass->vertex_shader_entry + "\n";
- *shader_source_out += "// #o3d PixelShaderEntryPoint ";
- *shader_source_out += pass->fragment_shader_entry + "\n";
- *shader_source_out += "// #o3d MatrixLoadOrder ";
- *shader_source_out += column_major ? "ColumnMajor" : "RowMajor";
- *shader_source_out += "\n";
-
- return true;
-}
-
-bool ColladaConditioner::CompileCg(const FilePath& filename,
- const String& shader_source,
- const String& vs_entry,
- const String& ps_entry) {
- bool retval = false;
- String shader_source_cg = shader_source;
- shader_source_cg +=
- "technique t {\n"
- " pass p {\n"
- " VertexShader = compile arbvp1 " + vs_entry + "();\n"
- " PixelShader = compile arbfp1 " + ps_entry + "();\n"
- " }\n"
- "};\n";
-
- // Create a Cg context in which to compile the given .FX file.
- CGcontext context = cgCreateContext();
-
- cgGLRegisterStates(context);
-
- // Create a Cg effect from the FX file.
- CGeffect effect = cgCreateEffect(context, shader_source_cg.c_str(), NULL);
- if (!effect || !cgIsEffect(effect) || cgGetError() != CG_NO_ERROR) {
- const char* errors = cgGetLastListing(context);
- String message = FilePathToUTF8(filename) + ":\n";
- if (errors) {
- message += String(errors) + "\n";
- } else {
- message += "Unknown Cg compilation error.\n";
- }
- O3D_ERROR(service_locator_) << message;
- } else {
- cgDestroyEffect(effect);
- retval = true;
- }
- cgDestroyContext(context);
- return retval;
-}
-} // namespace o3d
diff --git a/o3d/import/cross/collada_conditioner.h b/o3d/import/cross/collada_conditioner.h
deleted file mode 100644
index 72df84d..0000000
--- a/o3d/import/cross/collada_conditioner.h
+++ /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 contains the declarations for the functions in the
-// O3D COLLADA conditioner namespace. These functions do most of
-// the actual work of conditioning and packagaging a DAE file for use
-// in O3D.
-
-#ifndef O3D_IMPORT_CROSS_COLLADA_CONDITIONER_H_
-#define O3D_IMPORT_CROSS_COLLADA_CONDITIONER_H_
-
-#include "core/cross/types.h"
-#include "compiler/technique/technique_structures.h"
-
-class FCDEffect;
-class FCDEffectProfileFX;
-class FCDocument;
-class FUUri;
-class FilePath;
-
-namespace o3d {
-
-class ColladaZipArchive;
-class ServiceLocator;
-
-class ColladaConditioner {
- public:
- explicit ColladaConditioner(ServiceLocator* service_locator);
- ~ColladaConditioner();
-
- // This function conditions the given document for use in O3D. This
- // mainly includes checking that the referenced shaders compile
- // against both the Cg (all platforms) and D3D (windows only)
- // runtimes, and converting the shaders to the common shader
- // language used by O3D. The converts all the shaders to inline
- // "code" shaders instead of "included" shaders. It also handles
- // converting "NV_Import" shaders produced by 3dsMax to something
- // o3d can read. Returns false on failure. If archive is non-NULL,
- // then it attempts to read shader files from the give zip archive
- // instead of from the disk.
- bool ConditionDocument(FCDocument* doc, ColladaZipArchive* archive);
-
- // This takes the given shader file and rewrites it to have the
- // proper form for O3D. If the archive parameter is non-NULL, then
- // the input file is read from the archive instead of from the
- // regular filesystem.
- bool RewriteShaderFile(ColladaZipArchive* archive,
- const FilePath& in_filename,
- const FilePath& out_filename,
- SamplerStateList* sampler_list,
- String* vs_entry,
- String* ps_entry);
-
- // This test-compiles the given shader source with the HLSL
- // compiler, if there is one available on the platform. This
- // function is implemented separately for each platform. If there
- // is no HLSL compiler available on this platform, this function
- // returns 'true'.
- bool CompileHLSL(const String& shader_source,
- const String& vs_entry,
- const String& ps_entry);
-
- // This test-compiles the given shader source with the Cg compiler,
- // if there is one available on the platform. This function is
- // implemented separately for each platform. If there is no Cg
- // compiler available on this platform, this function returns
- // 'true'.
- bool CompileCg(const FilePath& filename,
- const String& shader_source,
- const String& vs_entry,
- const String& ps_entry);
-
- protected:
- // This preprocesses the given file using the Cgc compiler. It
- // doesn't compile the shader, it just preprocesses it. This is
- // implemented separately for each platform, since it invokes the
- // compiler as a separate process.
- bool PreprocessShaderFile(const FilePath& in_filename,
- const FilePath& out_filename);
-
- // This takes the given COLLADA shader source code and rewrites it
- // to have the proper form for O3D. It finds the entry points and
- // sets vs_entry and ps_entry to what it finds.
- bool RewriteShader(const String& shader_source_in,
- String* shader_source_out,
- const FilePath& in_filename,
- SamplerStateList* sampler_list,
- String* vs_entry,
- String* ps_entry);
-
- // Handle all the embedded shaders in the document.
- bool HandleEmbeddedShaders(FCDEffect* collada_effect,
- FCDEffectProfileFX* profile_fx,
- ColladaZipArchive* archive);
-
- bool HandleNVImport(FCDocument* doc,
- FCDEffect* collada_effect,
- const FUUri& original_uri,
- ColladaZipArchive* archive);
- private:
- ServiceLocator* service_locator_;
-
- DISALLOW_COPY_AND_ASSIGN(ColladaConditioner);
-};
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_COLLADA_CONDITIONER_H_
diff --git a/o3d/import/cross/collada_conditioner_stub.cc b/o3d/import/cross/collada_conditioner_stub.cc
deleted file mode 100644
index 6c1be1e..0000000
--- a/o3d/import/cross/collada_conditioner_stub.cc
+++ /dev/null
@@ -1,90 +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 "import/cross/precompile.h"
-
-#include "import/cross/collada_conditioner.h"
-
-#include "core/cross/service_locator.h"
-#include "import/cross/collada.h"
-
-namespace o3d {
-ColladaConditioner::ColladaConditioner(ServiceLocator* service_locator)
- : service_locator_(service_locator) {
-}
-
-ColladaConditioner::~ColladaConditioner() {
-}
-
-bool ColladaConditioner::HandleEmbeddedShaders(FCDEffect* collada_effect,
- FCDEffectProfileFX* profile_fx,
- ColladaZipArchive* archive) {
- return true;
-}
-
-bool ColladaConditioner::HandleNVImport(FCDocument* doc,
- FCDEffect* collada_effect,
- const FUUri& original_uri,
- ColladaZipArchive* archive) {
- return true;
-}
-
-bool ColladaConditioner::ConditionDocument(FCDocument* doc,
- ColladaZipArchive* archive) {
- return true;
-}
-
-bool ColladaConditioner::RewriteShaderFile(ColladaZipArchive* archive,
- const FilePath& in_filename,
- const FilePath& out_filename,
- SamplerStateList* sampler_list,
- String* vs_entry,
- String* ps_entry) {
- return true;
-}
-
-bool ColladaConditioner::RewriteShader(const String& shader_source_in,
- String* shader_source_out,
- const FilePath& in_filename,
- SamplerStateList* sampler_list,
- String* ps_entry,
- String* vs_entry) {
- return true;
-}
-
-bool ColladaConditioner::CompileCg(const FilePath& filename,
- const String& shader_source,
- const String& vs_entry,
- const String& ps_entry) {
- return true;
-}
-} // namespace o3d
diff --git a/o3d/import/cross/collada_zip_archive.cc b/o3d/import/cross/collada_zip_archive.cc
deleted file mode 100644
index f150a4c..0000000
--- a/o3d/import/cross/collada_zip_archive.cc
+++ /dev/null
@@ -1,80 +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.
- */
-
-
-// A basic C++ wrapper for a collada zip file
-// it looks for the first .dae file in the archive and is able to resolve
-// partial pathnames (from the image URI's in the collada file) to files in the
-// archive
-
-#include "base/string_util.h"
-#include "import/cross/collada_zip_archive.h"
-
-using std::vector;
-using std::string;
-
-namespace o3d {
-
-ColladaZipArchive::ColladaZipArchive(const std::string &zip_filename,
- int *result)
- : ZipArchive(zip_filename, result) {
- if (result && (*result == UNZ_OK)) {
- // look through the archive and locate the first file with a .dae extension
- vector<ZipFileInfo> infolist;
- GetInformationList(&infolist);
-
- bool dae_found = false;
- for (vector<ZipFileInfo>::size_type i = 0; i < infolist.size(); ++i) {
- const char *name = infolist[i].name.c_str();
- int length = strlen(name);
-
- if (length > 4) {
- const char *suffix = name + length - 4;
- if (!base::strcasecmp(suffix, ".dae")) {
- dae_pathname_ = name;
- dae_directory_ = dae_pathname_;
- RemoveLastPathComponent(&dae_directory_);
- dae_found = true;
- break;
- }
- }
- }
-
- if (!dae_found && result) *result = -1;
- }
-}
-
-// Convert paths relative to the collada file to archive paths
-char *ColladaZipArchive::GetColladaAssetData(const string &filename,
- size_t *size) {
- return GetRelativeFileData(filename, dae_directory_, size);
-}
-} // end namespace o3d
diff --git a/o3d/import/cross/collada_zip_archive.h b/o3d/import/cross/collada_zip_archive.h
deleted file mode 100644
index 018b3bf..0000000
--- a/o3d/import/cross/collada_zip_archive.h
+++ /dev/null
@@ -1,73 +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.
- */
-
-
-// A basic C++ wrapper for a collada zip file
-// it looks for the first .dae file in the archive and is able to resolve
-// partial pathnames (from the URI's in the collada file) to files in the
-// archive
-
-#ifndef O3D_IMPORT_CROSS_COLLADA_ZIP_ARCHIVE_H_
-#define O3D_IMPORT_CROSS_COLLADA_ZIP_ARCHIVE_H_
-
-#include "import/cross/zip_archive.h"
-
-#include <string>
-#include <vector>
-
-namespace o3d {
-
-class ColladaZipArchive : public ZipArchive {
- public:
- ColladaZipArchive(const std::string &zip_filename, int *result);
-
- // |filename| is taken to be relative to the directory containing the
- // first collada file found in the archive. It may contain relative path
- // elements ("../"). These are the types of file references to images
- // contained in the collada file.
- //
- // Extracts a single file and returns a pointer to the file's content.
- // Returns NULL if |filename| doesn't match any in the archive
- // or an error occurs. The caller must call free() on the returned pointer
- //
- virtual char *GetColladaAssetData(const std::string &filename,
- size_t *size);
-
- const std::string& GetColladaPath() const { return dae_pathname_; }
- const std::string& GetColladaDirectory() const { return dae_directory_; }
-
- protected:
- std::string dae_pathname_;
- std::string dae_directory_;
-};
-} // end namespace o3d
-
-#endif // O3D_IMPORT_CROSS_COLLADA_ZIP_ARCHIVE_H_
diff --git a/o3d/import/cross/destination_buffer.cc b/o3d/import/cross/destination_buffer.cc
deleted file mode 100644
index d52bda8..0000000
--- a/o3d/import/cross/destination_buffer.cc
+++ /dev/null
@@ -1,79 +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 "import/cross/destination_buffer.h"
-
-namespace o3d {
-
-O3D_OBJECT_BASE_DEFN_CLASS(
- "o3djs.DestinationBuffer", DestinationBuffer, VertexBuffer);
-
-DestinationBuffer::DestinationBuffer(ServiceLocator* service_locator)
- : VertexBuffer(service_locator),
- buffer_() {
-}
-
-DestinationBuffer::~DestinationBuffer() {
- ConcreteFree();
-}
-
-void DestinationBuffer::ConcreteFree() {
- buffer_.reset();
-}
-
-bool DestinationBuffer::ConcreteAllocate(size_t size_in_bytes) {
- ConcreteFree();
-
- buffer_.reset(new char[size_in_bytes]);
-
- return true;
-}
-
-bool DestinationBuffer::ConcreteLock(AccessMode access_mode,
- void **buffer_data) {
- if (!buffer_.get()) {
- return false;
- }
-
- *buffer_data = reinterpret_cast<void*>(buffer_.get());
- return true;
-}
-
-bool DestinationBuffer::ConcreteUnlock() {
- return buffer_.get() != NULL;
-}
-
-ObjectBase::Ref DestinationBuffer::Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new DestinationBuffer(service_locator));
-}
-
-} // namespace o3d
-
diff --git a/o3d/import/cross/destination_buffer.h b/o3d/import/cross/destination_buffer.h
deleted file mode 100644
index 8b4b5d2..0000000
--- a/o3d/import/cross/destination_buffer.h
+++ /dev/null
@@ -1,83 +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 DestinationBuffer class.
-
-#ifndef O3D_IMPORT_CROSS_DESTINATION_BUFFER_H_
-#define O3D_IMPORT_CROSS_DESTINATION_BUFFER_H_
-
-#include "core/cross/buffer.h"
-
-namespace o3d {
-
-// DestinationBuffer is a used for serialization only and is not part of the
-// normal O3D plugin. It is used for Skinning to distinguish between a normal
-// VertexBuffer that needs to have its contents serialized and a
-// DestinationBuffer that only needs to know its structure but not its
-// contents.
-class DestinationBuffer : public VertexBuffer {
- public:
- typedef SmartPointer<DestinationBuffer> Ref;
-
- ~DestinationBuffer();
-
- protected:
- // Overridden from Buffer.
- virtual bool ConcreteAllocate(size_t size_in_bytes);
-
- // Overridden from Buffer.
- virtual bool ConcreteLock(AccessMode access_mode, void **buffer_data);
-
- // Overridden from Buffer.
- virtual bool ConcreteUnlock();
-
- explicit DestinationBuffer(ServiceLocator* service_locator);
-
- protected:
- // Frees the buffer if it exists.
- void ConcreteFree();
-
- private:
- friend class IClassManager;
- static ObjectBase::Ref Create(ServiceLocator* service_locator);
-
- scoped_array<char> buffer_; // The actual data for this buffer.
-
- O3D_OBJECT_BASE_DECL_CLASS(DestinationBuffer, VertexBuffer);
- DISALLOW_COPY_AND_ASSIGN(DestinationBuffer);
-};
-
-
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_DESTINATION_BUFFER_H_
-
diff --git a/o3d/import/cross/destination_buffer_test.cc b/o3d/import/cross/destination_buffer_test.cc
deleted file mode 100644
index 2ad2513..0000000
--- a/o3d/import/cross/destination_buffer_test.cc
+++ /dev/null
@@ -1,104 +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 "tests/common/win/testing_common.h"
-#include "import/cross/destination_buffer.h"
-#include "core/cross/class_manager.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-
-namespace o3d {
-
-class DestinationBufferTest : public testing::Test {
- protected:
- DestinationBufferTest()
- : class_manager_(g_service_locator),
- object_manager_(g_service_locator) {
- class_manager_->AddTypedClass<DestinationBuffer>();
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ClassManager> class_manager_;
- ServiceDependency<ObjectManager> object_manager_;
- Pack* pack_;
-};
-
-void DestinationBufferTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void DestinationBufferTest::TearDown() {
- object_manager_->DestroyPack(pack_);
-}
-
-
-// Creates a Destination buffer, tests basic properties, and checks that writing
-// then reading data works.
-TEST_F(DestinationBufferTest, TestDestinationBuffer) {
- Buffer *buffer = pack()->Create<DestinationBuffer>();
- EXPECT_TRUE(buffer->IsA(DestinationBuffer::GetApparentClass()));
- EXPECT_TRUE(buffer->IsA(VertexBuffer::GetApparentClass()));
- EXPECT_TRUE(buffer->IsA(Buffer::GetApparentClass()));
-
- const size_t kSize = 100;
- Field* field = buffer->CreateField(UInt32Field::GetApparentClass(), 1);
- ASSERT_TRUE(field != NULL);
- ASSERT_TRUE(buffer->AllocateElements(kSize));
- EXPECT_EQ(kSize * sizeof(uint32), buffer->GetSizeInBytes()); // NOLINT
-
- // Put some data into the buffer.
- uint32 *data = NULL;
- ASSERT_TRUE(buffer->LockAs(Buffer::WRITE_ONLY, &data));
- ASSERT_TRUE(data != NULL);
- for (uint32 i = 0; i < kSize; ++i) {
- data[i] = i;
- }
- ASSERT_TRUE(buffer->Unlock());
-
- data = NULL;
- // Read the data from the buffer, checks that it's the expected values.
- ASSERT_TRUE(buffer->LockAs(Buffer::READ_ONLY, &data));
- ASSERT_TRUE(data != NULL);
- for (uint32 i = 0; i < kSize; ++i) {
- EXPECT_EQ(i, data[i]);
- }
- ASSERT_TRUE(buffer->Unlock());
-}
-
-
-} // namespace o3d
-
diff --git a/o3d/import/cross/file_output_stream_processor.cc b/o3d/import/cross/file_output_stream_processor.cc
deleted file mode 100644
index 10e3579..0000000
--- a/o3d/import/cross/file_output_stream_processor.cc
+++ /dev/null
@@ -1,61 +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 declaration of class FileOutputStreamProcessor.
-
-#include <stdio.h>
-#include "base/logging.h"
-#include "import/cross/file_output_stream_processor.h"
-
-namespace o3d {
-FileOutputStreamProcessor::FileOutputStreamProcessor(FILE* file)
- : file_(file) {
- DCHECK(file != NULL);
-}
-
-StreamProcessor::Status FileOutputStreamProcessor::ProcessBytes(
- MemoryReadStream *stream,
- size_t bytes_to_process) {
- DCHECK(file_ != NULL);
- size_t num_written = fwrite(stream->GetDirectMemoryPointer(),
- 1,
- bytes_to_process,
- file_);
- return num_written == bytes_to_process ? IN_PROGRESS : FAILURE;
-}
-
-void FileOutputStreamProcessor::Close(bool success) {
- fclose(file_);
- file_ = NULL;
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/file_output_stream_processor.h b/o3d/import/cross/file_output_stream_processor.h
deleted file mode 100644
index ff3b24e..0000000
--- a/o3d/import/cross/file_output_stream_processor.h
+++ /dev/null
@@ -1,57 +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 declaration of class FileOutputStreamProcessor.
-
-#ifndef O3D_IMPORT_CROSS_FILE_OUTPUT_STREAM_PROCESSOR_H_
-#define O3D_IMPORT_CROSS_FILE_OUTPUT_STREAM_PROCESSOR_H_
-
-#include "import/cross/memory_stream.h"
-
-namespace o3d {
-
-// A StringReader accepts binary data and writes it to a file.
-class FileOutputStreamProcessor : public StreamProcessor {
- public:
- explicit FileOutputStreamProcessor(FILE* file);
-
- virtual Status ProcessBytes(MemoryReadStream *stream,
- size_t bytes_to_process);
- virtual void Close(bool success);
-
- private:
- FILE* file_;
- DISALLOW_COPY_AND_ASSIGN(FileOutputStreamProcessor);
-};
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_FILE_OUTPUT_STREAM_PROCESSOR_H_
diff --git a/o3d/import/cross/gz_compressor.cc b/o3d/import/cross/gz_compressor.cc
deleted file mode 100644
index d6a98cf..0000000
--- a/o3d/import/cross/gz_compressor.cc
+++ /dev/null
@@ -1,149 +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.
- */
-
-//
-// GzCompressor compresses a byte stream using gzip compression
-// calling the client's ProcessBytes() method with the compressed stream
-//
-
-#include "import/cross/gz_compressor.h"
-
-#include <assert.h>
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-#include "zutil.h"
-
-const size_t kChunkSize = 16384;
-
-namespace o3d {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-GzCompressor::GzCompressor(StreamProcessor *callback_client)
- : stream_is_closed_(false),
- callback_client_(callback_client) {
- strm_.zalloc = Z_NULL;
- strm_.zfree = Z_NULL;
- strm_.opaque = Z_NULL;
-
- // Store this, so we can later check if it's OK to start processing
- int result = deflateInit2(
- &strm_,
- Z_DEFAULT_COMPRESSION,
- Z_DEFLATED,
- MAX_WBITS + 16, // 16 means write out gzip header/trailer
- DEF_MEM_LEVEL,
- Z_DEFAULT_STRATEGY);
-
- initialized_ = result == Z_OK;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void GzCompressor::Close(bool success) {
- if (!stream_is_closed_) {
- // Flush the compression stream
- MemoryReadStream stream(NULL, 0);
- CompressBytes(&stream, 0, true);
-
- // Deallocate resources
- deflateEnd(&strm_);
- stream_is_closed_ = true;
- }
-
- callback_client_->Close(success);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-GzCompressor::~GzCompressor() {
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-StreamProcessor::Status GzCompressor::ProcessBytes(MemoryReadStream *stream,
- size_t bytes_to_process) {
- // Basic sanity check
- if (stream->GetDirectMemoryPointer() == NULL || bytes_to_process == 0) {
- return FAILURE;
- }
-
- return CompressBytes(stream, bytes_to_process, false);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-StreamProcessor::Status GzCompressor::CompressBytes(MemoryReadStream *stream,
- size_t bytes_to_process,
- bool flush) {
- // Don't even bother trying if we didn't get initialized properly
- if (!initialized_) return FAILURE;
-
- uint8 out[kChunkSize];
-
- // Don't try to read more than our stream has
- size_t remaining = stream->GetRemainingByteCount();
- if (bytes_to_process > remaining) {
- return FAILURE;
- }
-
- // Use direct memory access on the MemoryStream object
- const uint8 *input_data = stream->GetDirectMemoryPointer();
- stream->Skip(bytes_to_process);
-
- // Fill out the zlib z_stream struct
- strm_.avail_in = bytes_to_process;
- strm_.next_in = const_cast<uint8*>(input_data);
-
- // We need to flush the stream when we reach the end
- int flush_code = flush ? Z_FINISH : Z_NO_FLUSH;
-
- // Run deflate() on input until output buffer not full
- int result;
- do {
- strm_.avail_out = kChunkSize;
- strm_.next_out = out;
-
- result = deflate(&strm_, flush_code);
- if (result == Z_STREAM_ERROR)
- return FAILURE;
-
- size_t have = kChunkSize - strm_.avail_out;
-
- // Callback with the compressed byte stream
- MemoryReadStream decompressed_stream(out, have);
- if (have > 0 && callback_client_) {
- if (callback_client_->ProcessBytes(&decompressed_stream,
- have) == FAILURE) {
- return FAILURE;
- }
- }
- } while (strm_.avail_out == 0);
-
- return result == Z_OK ? IN_PROGRESS : FAILURE;
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/gz_compressor.h b/o3d/import/cross/gz_compressor.h
deleted file mode 100644
index 43dbf0f..0000000
--- a/o3d/import/cross/gz_compressor.h
+++ /dev/null
@@ -1,73 +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.
- */
-
-//
-// GzCompressor compresses a byte stream using gzip compression
-// calling the client's ProcessBytes() method with the compressed stream
-//
-
-#ifndef O3D_IMPORT_CROSS_GZ_COMPRESSOR_H_
-#define O3D_IMPORT_CROSS_GZ_COMPRESSOR_H_
-
-#include "base/basictypes.h"
-#include "zlib.h"
-#include "import/cross/memory_stream.h"
-
-namespace o3d {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class GzCompressor : public StreamProcessor {
- public:
- explicit GzCompressor(StreamProcessor *callback_client);
- virtual ~GzCompressor();
-
- virtual Status ProcessBytes(MemoryReadStream *stream,
- size_t bytes_to_process);
-
- // Must call when all bytes to compress have been sent (with ProcessBytes)
- virtual void Close(bool success);
-
- private:
- Status CompressBytes(MemoryReadStream *stream,
- size_t bytes_to_process,
- bool flush);
-
- z_stream strm_; // low-level zlib state
- bool initialized_;
- bool stream_is_closed_;
- StreamProcessor *callback_client_;
-
- DISALLOW_COPY_AND_ASSIGN(GzCompressor);
-};
-
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_GZ_COMPRESSOR_H_
diff --git a/o3d/import/cross/gz_compressor_test.cc b/o3d/import/cross/gz_compressor_test.cc
deleted file mode 100644
index 3ca59d0..0000000
--- a/o3d/import/cross/gz_compressor_test.cc
+++ /dev/null
@@ -1,202 +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 <sys/stat.h>
-#include <string>
-
-#include "import/cross/memory_stream.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/gz_decompressor.h"
-#include "import/cross/gz_compressor.h"
-#include "tests/common/win/testing_common.h"
-#include "tests/common/cross/test_utils.h"
-
-namespace o3d {
-
-class GzCompressorTest : public testing::Test {
-};
-
-using o3d::MemoryReadStream;
-using o3d::MemoryWriteStream;
-using o3d::GzCompressor;
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Class for receiving the decompressed byte stream
-class DecompressorClient : public o3d::StreamProcessor {
- public:
- explicit DecompressorClient(size_t uncompressed_byte_size)
- : buffer_(uncompressed_byte_size),
- write_stream_(buffer_, uncompressed_byte_size),
- closed_(false),
- success_(false) {}
-
- virtual Status ProcessBytes(MemoryReadStream *stream,
- size_t bytes_to_process) {
- // Make sure the output stream isn't full yet
- EXPECT_TRUE(write_stream_.GetRemainingByteCount() >= bytes_to_process);
-
- // Buffer the decompressed bytes
- const uint8 *p = stream->GetDirectMemoryPointer();
- stream->Skip(bytes_to_process);
- write_stream_.Write(p, bytes_to_process);
-
- return SUCCESS;
- }
-
- virtual void Close(bool success) {
- closed_ = true;
- success_ = success;
- }
-
- void VerifyDecompressedOutput(uint8 *original_data) {
- // Make sure we filled up the output buffer
- EXPECT_EQ(0U, write_stream_.GetRemainingByteCount());
-
- // Verify decompressed data with the original data we fed into the
- // compressor
- EXPECT_EQ(0, memcmp(original_data, buffer_, buffer_.GetLength()));
- }
-
- bool closed() const {
- return closed_;
- }
-
- bool success() const {
- return success_;
- }
-
- private:
- size_t uncompressed_byte_size_;
- MemoryBuffer<uint8> buffer_;
- MemoryWriteStream write_stream_;
- bool closed_;
- bool success_;
-};
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Class for receiving the compressed byte stream
-class CompressorClient : public o3d::StreamProcessor {
- public:
- explicit CompressorClient(size_t uncompressed_byte_size)
- : decompressor_client_(uncompressed_byte_size),
- decompressor_(&decompressor_client_),
- closed_(false),
- success_(false) {
- };
-
- virtual Status ProcessBytes(MemoryReadStream *stream,
- size_t bytes_to_process) {
- // We're receiving compressed bytes here, so feed them back into
- // the decompressor. Since we're making a compression / decompression
- // round trip, we should end up with the same (initial) byte stream
- // we can verify this at the end
- Status status = decompressor_.ProcessBytes(stream, bytes_to_process);
-
- EXPECT_TRUE(status == IN_PROGRESS || status == SUCCESS);
-
- return SUCCESS;
- }
-
- virtual void Close(bool success) {
- closed_ = true;
- success_ = success;
- }
-
- void VerifyDecompressedOutput(uint8 *original_data) {
- // Send it on to the client, since its the one with the buffered data
- decompressor_client_.VerifyDecompressedOutput(original_data);
- }
-
- bool closed() const {
- return closed_;
- }
-
- bool success() const {
- return success_;
- }
-
- private:
- DecompressorClient decompressor_client_;
- o3d::GzDecompressor decompressor_;
- bool closed_;
- bool success_;
-};
-
-
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-TEST_F(GzCompressorTest, RoundTripCompressionDecompression) {
- // We'll compress this file
- String filepath = *g_program_path + "/archive_files/keyboard.jpg";
-
- size_t file_length;
- uint8 *p = test_utils::ReadFile(filepath.c_str(), &file_length);
- ASSERT_TRUE(p != NULL);
-
- MemoryReadStream input_file_stream(p, file_length);
-
- // Gets callbacks with compressed bytes
- CompressorClient compressor_client(file_length);
-
- GzCompressor compressor(&compressor_client);
-
- // Compress the entire file contents.
- // |compressor_client| will take the compressed byte stream and send it
- // directly to a decompressor.
- //
- // Since we're making a compression / decompression
- // round trip, we should end up with the same (initial) byte stream
- // we can verify this at the end by calling VerifyDecompressedOutput()
- StreamProcessor::Status status =
- compressor.ProcessBytes(&input_file_stream, file_length);
- EXPECT_NE(StreamProcessor::FAILURE, status);
-
- compressor.Close(true);
-
- compressor_client.VerifyDecompressedOutput(p);
- EXPECT_TRUE(compressor_client.closed());
- EXPECT_TRUE(compressor_client.success());
-
- free(p);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-TEST_F(GzCompressorTest, PassesFailureThroughToClient) {
- CompressorClient compressor_client(1000);
- GzCompressor compressor(&compressor_client);
- compressor.Close(false);
-
- EXPECT_TRUE(compressor_client.closed());
- EXPECT_FALSE(compressor_client.success());
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/gz_decompressor.cc b/o3d/import/cross/gz_decompressor.cc
deleted file mode 100644
index 5499958..0000000
--- a/o3d/import/cross/gz_decompressor.cc
+++ /dev/null
@@ -1,130 +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.
- */
-
-//
-// GzDecompressor decompresses a gzip compressed byte stream
-// calling the client's ProcessBytes() method with the uncompressed stream
-//
-
-#include "import/cross/gz_decompressor.h"
-
-#include <assert.h>
-#include "import/cross/memory_stream.h"
-
-const size_t kChunkSize = 16384;
-
-namespace o3d {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-GzDecompressor::GzDecompressor(StreamProcessor *callback_client)
- : callback_client_(callback_client) {
- // Initialize inflate state
- strm_.zalloc = Z_NULL;
- strm_.zfree = Z_NULL;
- strm_.opaque = Z_NULL;
- strm_.avail_in = 0;
- strm_.next_in = Z_NULL;
-
- // Store this, so we can later check if it's OK to start processing
- initialized_ = inflateInit2(&strm_, 31) == Z_OK;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-GzDecompressor::~GzDecompressor() {
- inflateEnd(&strm_);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-//
-StreamProcessor::Status GzDecompressor::ProcessBytes(MemoryReadStream *stream,
- size_t bytes_to_process) {
- // Don't even bother trying if we didn't get initialized properly
- if (!initialized_) return FAILURE;
-
- uint8 out[kChunkSize];
- int result;
- size_t have;
-
- // Don't try to read more than our stream has
- size_t remaining = stream->GetRemainingByteCount();
- if (bytes_to_process > remaining) {
- return FAILURE;
- }
-
- // Use direct memory access on the MemoryStream object
- strm_.avail_in = bytes_to_process;
- strm_.next_in = const_cast<uint8*>(stream->GetDirectMemoryPointer());
- stream->Skip(bytes_to_process);
-
- // Run inflate() on input until output buffer not full
- do {
- strm_.avail_out = kChunkSize;
- strm_.next_out = out;
-
- result = inflate(&strm_, Z_NO_FLUSH);
-
- // error check here - return error codes if necessary
- assert(result != Z_STREAM_ERROR); /* state not clobbered */
- switch (result) {
- case Z_NEED_DICT:
- case Z_DATA_ERROR:
- case Z_MEM_ERROR:
- return FAILURE;
- }
-
- have = kChunkSize - strm_.avail_out;
-
- // Callback with the decompressed byte stream
- MemoryReadStream decompressed_stream(out, have);
- if (callback_client_) {
- if (callback_client_->ProcessBytes(&decompressed_stream,
- have) == FAILURE) {
- return FAILURE;
- }
- }
- } while (strm_.avail_out == 0);
-
- switch (result) {
- case Z_OK:
- case Z_BUF_ERROR: // Zlib docs say this is expected.
- return IN_PROGRESS;
- case Z_STREAM_END:
- return SUCCESS;
- default:
- return FAILURE;
- }
-}
-
-void GzDecompressor::Close(bool success) {
- callback_client_->Close(success);
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/gz_decompressor.h b/o3d/import/cross/gz_decompressor.h
deleted file mode 100644
index 02d2c7a..0000000
--- a/o3d/import/cross/gz_decompressor.h
+++ /dev/null
@@ -1,66 +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.
- */
-
-//
-// GzDecompressor decompresses a gzip compressed byte stream
-// calling the client's ProcessBytes() method with the uncompressed stream
-//
-
-#ifndef O3D_IMPORT_CROSS_GZ_DECOMPRESSOR_H_
-#define O3D_IMPORT_CROSS_GZ_DECOMPRESSOR_H_
-
-#include "base/basictypes.h"
-#include "zlib.h"
-#include "import/cross/memory_stream.h"
-
-namespace o3d {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class GzDecompressor : public StreamProcessor {
- public:
- explicit GzDecompressor(StreamProcessor *callback_client);
- virtual ~GzDecompressor();
-
- virtual Status ProcessBytes(MemoryReadStream *stream,
- size_t bytes_to_process);
- virtual void Close(bool success);
-
- private:
- z_stream strm_; // low-level zlib state
- bool initialized_;
- StreamProcessor *callback_client_;
-
- DISALLOW_COPY_AND_ASSIGN(GzDecompressor);
-};
-
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_GZ_DECOMPRESSOR_H_
diff --git a/o3d/import/cross/gz_decompressor_test.cc b/o3d/import/cross/gz_decompressor_test.cc
deleted file mode 100644
index f2d1212..0000000
--- a/o3d/import/cross/gz_decompressor_test.cc
+++ /dev/null
@@ -1,171 +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 <sys/stat.h>
-#include <algorithm>
-
-#include "import/cross/gz_decompressor.h"
-#include "import/cross/memory_buffer.h"
-#include "tests/common/win/testing_common.h"
-#include "tests/common/cross/test_utils.h"
-
-using test_utils::ReadFile;
-
-namespace o3d {
-
-class GzDecompressorTest : public testing::Test {
-};
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Receives bytes from the decompressor and buffers them
-//
-class GzTestClient : public StreamProcessor {
- public:
- explicit GzTestClient(size_t uncompressed_size)
- : closed_(false),
- success_(false) {
- buffer_.Allocate(uncompressed_size);
- stream_.Assign(buffer_, uncompressed_size);
- }
-
- virtual Status ProcessBytes(MemoryReadStream *input_stream,
- size_t bytes_to_process) {
- // Buffer the uncompressed bytes we're given
- const uint8 *p = input_stream->GetDirectMemoryPointer();
- input_stream->Skip(bytes_to_process);
-
- size_t bytes_written = stream_.Write(p, bytes_to_process);
- EXPECT_EQ(bytes_written, bytes_to_process);
-
- return SUCCESS;
- }
-
- virtual void Close(bool success) {
- closed_ = true;
- success_ = success;
- }
-
- // When we're done decompressing, we can check the results here
- uint8 *GetResultBuffer() { return buffer_; }
- size_t GetResultLength() const { return stream_.GetStreamPosition(); }
-
- bool closed() const {
- return closed_;
- }
-
- bool success() const {
- return success_;
- }
-
- private:
- MemoryBuffer<uint8> buffer_;
- MemoryWriteStream stream_;
- bool closed_;
- bool success_;
-};
-
-// Loads a tar.gz file, runs it through the processor.
-// In our callbacks, we verify that we receive three files with known contents
-//
-TEST_F(GzDecompressorTest, LoadGzFile) {
- String compressed_file = *g_program_path + "/archive_files/keyboard.jpg.gz";
- String uncompressed_file = *g_program_path + "/archive_files/keyboard.jpg";
-
- // Read the compressed and uncompressed files into memory.
- // We can then run the decompressor and check it against the expected
- // uncompressed data...
- size_t compressed_size;
- size_t uncompressed_size;
- uint8 *compressed_data = ReadFile(compressed_file, &compressed_size);
- uint8 *expected_uncompressed_data =
- ReadFile(uncompressed_file, &uncompressed_size);
-
- ASSERT_TRUE(compressed_data != NULL);
- ASSERT_TRUE(expected_uncompressed_data != NULL);
-
- // Gets callbacks for the uncompressed data
- GzTestClient decompressor_client(uncompressed_size);
-
- // The class we're testing...
- GzDecompressor decompressor(&decompressor_client);
-
- // Now that we've read the compressed file into memory, lets
- // feed it, a chunk at a time, into the decompressor
- const int kChunkSize = 512;
-
- MemoryReadStream compressed_stream(compressed_data, compressed_size);
- int bytes_to_process = compressed_size;
-
- StreamProcessor::Status status = StreamProcessor::SUCCESS;
- while (bytes_to_process > 0) {
- int bytes_this_time =
- bytes_to_process < kChunkSize ? bytes_to_process : kChunkSize;
-
- status = decompressor.ProcessBytes(&compressed_stream, bytes_this_time);
- EXPECT_TRUE(status != StreamProcessor::FAILURE);
-
- bytes_to_process -= bytes_this_time;
- }
-
- decompressor.Close(true);
-
- EXPECT_TRUE(status == StreamProcessor::SUCCESS);
-
- // Now let's verify that what we just decompressed matches exactly
- // what's in the reference file...
-
- // First check that the lengths match
- EXPECT_EQ(decompressor_client.GetResultLength(), uncompressed_size);
-
- // Now check the data
- int result = memcmp(decompressor_client.GetResultBuffer(),
- expected_uncompressed_data,
- uncompressed_size);
- EXPECT_EQ(0, result);
-
- EXPECT_TRUE(decompressor_client.closed());
- EXPECT_TRUE(decompressor_client.success());
-
- free(compressed_data);
- free(expected_uncompressed_data);
-}
-
-TEST_F(GzDecompressorTest, PassesFailureThroughToClient) {
- GzTestClient decompressor_client(1000);
- GzDecompressor decompressor(&decompressor_client);
- decompressor.Close(false);
-
- EXPECT_TRUE(decompressor_client.closed());
- EXPECT_FALSE(decompressor_client.success());
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/iarchive_generator.h b/o3d/import/cross/iarchive_generator.h
deleted file mode 100644
index 04f3a46..0000000
--- a/o3d/import/cross/iarchive_generator.h
+++ /dev/null
@@ -1,65 +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 declaration of class IArchiveGenerator.
-
-#ifndef O3D_IMPORT_CROSS_IARCHIVE_GENERATOR_H_
-#define O3D_IMPORT_CROSS_IARCHIVE_GENERATOR_H_
-
-#include "core/cross/types.h"
-
-namespace o3d {
-
-class MemoryReadStream;
-
-class IArchiveGenerator {
- public:
- virtual ~IArchiveGenerator() {
- }
-
- // Call AddFile() for each file entry, followed by calls to AddFileBytes()
- // for the file's data
- virtual bool AddFile(const String& file_name,
- size_t file_size) = 0;
-
- // Call with the file's data (after calling AddFile)
- // may be called one time will all the file's data, or multiple times
- // until all the data is provided
- virtual int AddFileBytes(MemoryReadStream* stream, size_t n) = 0;
-
- // Must be called to finish the archiving operation.
- virtual void Close(bool success) = 0;
-};
-
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_IARCHIVE_GENERATOR_H_
diff --git a/o3d/import/cross/json_object.cc b/o3d/import/cross/json_object.cc
deleted file mode 100644
index 906e730..0000000
--- a/o3d/import/cross/json_object.cc
+++ /dev/null
@@ -1,66 +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 JSON Object class.
-
-#include "import/cross/json_object.h"
-
-namespace o3d {
-
-O3D_OBJECT_BASE_DEFN_CLASS("o3djs.JSONObject", JSONObject, ParamObject);
-
-JSONObject::JSONObject(ServiceLocator* service_locator)
- : ParamObject(service_locator) {
-}
-
-void JSONObject::AddProperty(const String& name, JSONValue* value) {
- std::pair<NameValueMap::iterator, bool> result = properties_.insert(
- std::pair<String, JSONValue::Ref>(name, JSONValue::Ref(value)));
- DCHECK(result.second);
-}
-
-void JSONObject::Serialize(StructuredWriter* writer) const {
- writer->WritePropertyName("object");
- writer->OpenObject();
- for (NameValueMap::const_iterator it(properties_.begin());
- it != properties_.end();
- ++it) {
- if (it->second->exists()) {
- writer->WritePropertyName(it->first);
- it->second->Serialize(writer);
- }
- }
- writer->CloseObject();
-}
-
-} // namespace o3d
-
-
diff --git a/o3d/import/cross/json_object.h b/o3d/import/cross/json_object.h
deleted file mode 100644
index a4c153a..0000000
--- a/o3d/import/cross/json_object.h
+++ /dev/null
@@ -1,289 +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 JSONObject class.
-
-#ifndef O3D_IMPORT_CROSS_JSON_OBJECT_H_
-#define O3D_IMPORT_CROSS_JSON_OBJECT_H_
-
-#include <map>
-#include "core/cross/param_object.h"
-#include "core/cross/material.h"
-#include "core/cross/transform.h"
-#include "serializer/cross/serializer.h"
-
-namespace o3d {
-
-class StructuredWriter;
-
-// A JSONValue is a base class for all JSON values stored in a JSONObject.
-class JSONValue : public RefCounted {
- public:
- typedef SmartPointer<JSONValue> Ref;
-
- virtual ~JSONValue() {
- }
-
- // Whether or not this value exists.
- bool exists() const {
- return exists_;
- }
-
- // Sets the existence of this value.
- void set_exists(bool exists) {
- exists_ = exists;
- }
-
- // Function to serialize the value of this JSON value.
- virtual void Serialize(StructuredWriter* writer) const = 0;
-
- protected:
- // optional means the value is optional. If true the value defaults to
- // not existing. If false the value defaults to existing.
- explicit JSONValue(bool optional)
- : optional_(optional), exists_(!optional) {
- }
-
- private:
- bool optional_;
- bool exists_; // used for optional values.
-};
-
-// A Template for optional typed non-ref JSON values.
-template<class T, bool optional>
-class TypedJSONValue : public JSONValue {
- public:
- typedef T DataType;
- TypedJSONValue()
- : JSONValue(optional) {
- }
- virtual ~TypedJSONValue() {}
-
- // Sets the value stored in the JSONValue.
- void set_value(const DataType& value) {
- set_exists(true);
- value_ = value;
- }
-
- // Returns the current value stored in the JSONValue.
- DataType value() const {
- DCHECK(exists());
- return value_;
- }
-
- // Overridden from JSONValue.
- virtual void Serialize(StructuredWriter* writer) const {
- DCHECK(exists());
- o3d::Serialize(writer, value());
- }
-
- private:
- // The value stored in the JSONValue.
- DataType value_;
-
- DISALLOW_COPY_AND_ASSIGN(TypedJSONValue);
-};
-
-// A Template for typed ref JSON values.
-template<typename T>
-class TypedRefJSONValue : public JSONValue {
- public:
- typedef T* Pointer;
- typedef T DataType;
-
- TypedRefJSONValue()
- : JSONValue(false) {
- }
-
- virtual ~TypedRefJSONValue() {
- }
-
- // Set the value stored in the.
- void set_value(Pointer const value) {
- value_ = typename T::Ref(value);
- }
-
- // Returns the current value stored in the Param.
- Pointer value() const {
- return value_.Get();
- }
-
- // Overridden from JSONValue.
- virtual void Serialize(StructuredWriter* writer) const {
- o3d::Serialize(writer, static_cast<ObjectBase*>(value()));
- }
-
- protected:
- typename T::Ref value_;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(TypedRefJSONValue);
-};
-
-// Classes for various types of JSON Data.
-class JSONFloat : public TypedJSONValue<float, false> {
- public:
- typedef SmartPointer<JSONFloat> Ref;
- JSONFloat() {
- set_value(0.0f);
- }
-};
-class JSONFloat2 : public TypedJSONValue<Float2, false> {
- public:
- typedef SmartPointer<JSONFloat2> Ref;
- JSONFloat2() {
- set_value(Float2(0.0f, 0.0f));
- }
-};
-class JSONFloat3 : public TypedJSONValue<Float3, false> {
- public:
- typedef SmartPointer<JSONFloat3> Ref;
- JSONFloat3() {
- set_value(Float3(0.0f, 0.0f, 0.0f));
- }
-};
-class JSONFloat4 : public TypedJSONValue<Float4, false> {
- public:
- typedef SmartPointer<JSONFloat4> Ref;
- JSONFloat4() {
- set_value(Float4(0.0f, 0.0f, 0.0f, 0.0f));
- }
-};
-class JSONMatrix4 : public TypedJSONValue<Matrix4, false> {
- public:
- typedef SmartPointer<JSONMatrix4> Ref;
- JSONMatrix4() {
- set_value(Matrix4::identity());
- }
-};
-class JSONInteger : public TypedJSONValue<int, false> {
- public:
- typedef SmartPointer<JSONInteger> Ref;
- JSONInteger() {
- set_value(0);
- }
-};
-class JSONBoolean : public TypedJSONValue<bool, false> {
- public:
- typedef SmartPointer<JSONBoolean> Ref;
- JSONBoolean() {
- set_value(false);
- }
-};
-class JSONString : public TypedJSONValue<String, false> {
- public:
- typedef SmartPointer<JSONString> Ref;
-};
-class JSONTransform : public TypedRefJSONValue<Transform> {
- public:
- typedef SmartPointer<JSONTransform> Ref;
-};
-class JSONMaterial : public TypedRefJSONValue<Material> {
- public:
- typedef SmartPointer<JSONMaterial> Ref;
-};
-class JSONOptionalFloat : public TypedJSONValue<float, true> {
- public:
- typedef SmartPointer<JSONOptionalFloat> Ref;
-};
-class JSONOptionalFloat2 : public TypedJSONValue<Float2, true> {
- public:
- typedef SmartPointer<JSONOptionalFloat2> Ref;
-};
-class JSONOptionalFloat3 : public TypedJSONValue<Float3, true> {
- public:
- typedef SmartPointer<JSONOptionalFloat3> Ref;
-};
-class JSONOptionalFloat4 : public TypedJSONValue<Float4, true> {
- public:
- typedef SmartPointer<JSONOptionalFloat4> Ref;
-};
-class JSONOptionalMatrix4 : public TypedJSONValue<Matrix4, true> {
- public:
- typedef SmartPointer<JSONOptionalMatrix4> Ref;
-};
-class JSONOptionalInteger : public TypedJSONValue<int, true> {
- public:
- typedef SmartPointer<JSONOptionalInteger> Ref;
-};
-class JSONOptionalBoolean : public TypedJSONValue<bool, true> {
- public:
- typedef SmartPointer<JSONOptionalBoolean> Ref;
-};
-class JSONOptionalString : public TypedJSONValue<String, true> {
- public:
- typedef SmartPointer<JSONOptionalString> Ref;
-};
-
-// A JSONObject is a used for serialization only and is not part of the normal
-// O3D plugin. It is used to easily add name/value pairs to be serialized by the
-// serializer as JSON objects. Being that it's ParamObject you have 2 choices
-// for getting data serialized. As O3D Params or as JSONValues. The reason to
-// use one over the other... Params can be animated but are relatively heavy.
-// JSONValues become plane JavaScript when deserialized.
-// To add a Param use RegisterParamRef, to add a JSONValue use
-// RegisterJSONValue.
-class JSONObject : public ParamObject {
- public:
- typedef SmartPointer<JSONObject> Ref;
- typedef std::map<String, JSONValue::Ref> NameValueMap;
-
- // Seralizes the JSONObject.
- void Serialize(StructuredWriter* writer) const;
-
- protected:
- explicit JSONObject(ServiceLocator* service_locator);
-
- // Registers a pointer to a reference to a JSONValue.
- // Parameters:
- // name: name of JSONValue
- // ref_pointer: Pointer to typed reference to JSONValue.
- template<typename T>
- void RegisterJSONValue(const String& name, T* ref_pointer) {
- *ref_pointer = T(new typename T::ClassType());
- AddProperty(name, ref_pointer->Get());
- }
-
- private:
- // Adds a property to this JSON Object.
- void AddProperty(const String& name, JSONValue* value);
-
- NameValueMap properties_;
-
- O3D_OBJECT_BASE_DECL_CLASS(JSONObject, ParamObject);
- DISALLOW_COPY_AND_ASSIGN(JSONObject);
-};
-
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_JSON_OBJECT_H_
-
-
diff --git a/o3d/import/cross/json_object_test.cc b/o3d/import/cross/json_object_test.cc
deleted file mode 100644
index 137de45..0000000
--- a/o3d/import/cross/json_object_test.cc
+++ /dev/null
@@ -1,448 +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 "tests/common/win/testing_common.h"
-#include "import/cross/json_object.h"
-#include "core/cross/class_manager.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/service_dependency.h"
-#include "utils/cross/string_writer.h"
-#include "utils/cross/json_writer.h"
-#include "utils/cross/math_gtest.h"
-
-namespace o3d {
-
-namespace {
-
-// A class to test JSONObject
-class TestJSONObject : public JSONObject {
- public:
- typedef SmartPointer<TestJSONObject> Ref;
-
- static const char* kFloatValueName;
- static const char* kFloat2ValueName;
- static const char* kFloat3ValueName;
- static const char* kFloat4ValueName;
- static const char* kMatrix4ValueName;
- static const char* kIntegerValueName;
- static const char* kBooleanValueName;
- static const char* kStringValueName;
- static const char* kTransformValueName;
- static const char* kMaterialValueName;
- static const char* kOptionalFloatValueName;
- static const char* kOptionalFloat2ValueName;
- static const char* kOptionalFloat3ValueName;
- static const char* kOptionalFloat4ValueName;
- static const char* kOptionalMatrix4ValueName;
- static const char* kOptionalIntegerValueName;
- static const char* kOptionalBooleanValueName;
- static const char* kOptionalStringValueName;
-
- float float_value() const {
- return float_value_->value();
- }
-
- void set_float_value(float value) {
- float_value_->set_value(value);
- }
-
- Float2 float2_value() const {
- return float2_value_->value();
- }
-
- void set_float2_value(const Float2& value) {
- float2_value_->set_value(value);
- }
-
- Float3 float3_value() const {
- return float3_value_->value();
- }
-
- void set_float3_value(const Float3& value) {
- float3_value_->set_value(value);
- }
-
- Float4 float4_value() const {
- return float4_value_->value();
- }
-
- void set_float4_value(const Float4& value) {
- float4_value_->set_value(value);
- }
-
- Matrix4 matrix4_value() const {
- return matrix4_value_->value();
- }
-
- void set_matrix4_value(const Matrix4& value) {
- matrix4_value_->set_value(value);
- }
-
- int integer_value() const {
- return integer_value_->value();
- }
-
- void set_integer_value(int value) {
- integer_value_->set_value(value);
- }
-
- bool boolean_value() const {
- return boolean_value_->value();
- }
-
- void set_boolean_value(bool value) {
- boolean_value_->set_value(value);
- }
-
- String string_value() const {
- return string_value_->value();
- }
-
- void set_string_value(const String& value) {
- string_value_->set_value(value);
- }
-
- Transform* transform_value() const {
- return transform_value_->value();
- }
-
- void set_transform_value(Transform* value) {
- transform_value_->set_value(value);
- }
-
- Material* material_value() const {
- return material_value_->value();
- }
-
- void set_material_value(Material* value) {
- material_value_->set_value(value);
- }
-
- float optional_float_value() const {
- return optional_float_value_->value();
- }
-
- void set_optional_float_value(float value) {
- optional_float_value_->set_value(value);
- }
-
- Float2 optional_float2_value() const {
- return optional_float2_value_->value();
- }
-
- void set_optional_float2_value(const Float2& value) {
- optional_float2_value_->set_value(value);
- }
-
- Float3 optional_float3_value() const {
- return optional_float3_value_->value();
- }
-
- void set_optional_float3_value(const Float3& value) {
- optional_float3_value_->set_value(value);
- }
-
- Float4 optional_float4_value() const {
- return optional_float4_value_->value();
- }
-
- void set_optional_float4_value(const Float4& value) {
- optional_float4_value_->set_value(value);
- }
-
- Matrix4 optional_matrix4_value() const {
- return optional_matrix4_value_->value();
- }
-
- void set_optional_matrix4_value(const Matrix4& value) {
- optional_matrix4_value_->set_value(value);
- }
-
- int optional_integer_value() const {
- return optional_integer_value_->value();
- }
-
- void set_optional_integer_value(int value) {
- optional_integer_value_->set_value(value);
- }
-
- bool optional_boolean_value() const {
- return optional_boolean_value_->value();
- }
-
- void set_optional_boolean_value(bool value) {
- optional_boolean_value_->set_value(value);
- }
-
- String optional_string_value() const {
- return optional_string_value_->value();
- }
-
- void set_optional_string_value(const String& value) {
- optional_string_value_->set_value(value);
- }
-
- static ObjectBase::Ref Create(ServiceLocator* service_locator) {
- return ObjectBase::Ref(new TestJSONObject(service_locator));
- }
-
- private:
- explicit TestJSONObject(ServiceLocator* service_locator)
- : JSONObject(service_locator) {
- RegisterJSONValue(kFloatValueName, &float_value_);
- RegisterJSONValue(kFloat2ValueName, &float2_value_);
- RegisterJSONValue(kFloat3ValueName, &float3_value_);
- RegisterJSONValue(kFloat4ValueName, &float4_value_);
- RegisterJSONValue(kMatrix4ValueName, &matrix4_value_);
- RegisterJSONValue(kIntegerValueName, &integer_value_);
- RegisterJSONValue(kBooleanValueName, &boolean_value_);
- RegisterJSONValue(kStringValueName, &string_value_);
- RegisterJSONValue(kTransformValueName, &transform_value_);
- RegisterJSONValue(kMaterialValueName, &material_value_);
- RegisterJSONValue(kOptionalFloatValueName, &optional_float_value_);
- RegisterJSONValue(kOptionalFloat2ValueName, &optional_float2_value_);
- RegisterJSONValue(kOptionalFloat3ValueName, &optional_float3_value_);
- RegisterJSONValue(kOptionalFloat4ValueName, &optional_float4_value_);
- RegisterJSONValue(kOptionalMatrix4ValueName, &optional_matrix4_value_);
- RegisterJSONValue(kOptionalIntegerValueName, &optional_integer_value_);
- RegisterJSONValue(kOptionalBooleanValueName, &optional_boolean_value_);
- RegisterJSONValue(kOptionalStringValueName, &optional_string_value_);
- }
-
- // One of each type of JSONValue
- JSONFloat::Ref float_value_;
- JSONFloat2::Ref float2_value_;
- JSONFloat3::Ref float3_value_;
- JSONFloat4::Ref float4_value_;
- JSONMatrix4::Ref matrix4_value_;
- JSONInteger::Ref integer_value_;
- JSONBoolean::Ref boolean_value_;
- JSONString::Ref string_value_;
- JSONTransform::Ref transform_value_;
- JSONMaterial::Ref material_value_;
- JSONOptionalFloat::Ref optional_float_value_;
- JSONOptionalFloat2::Ref optional_float2_value_;
- JSONOptionalFloat3::Ref optional_float3_value_;
- JSONOptionalFloat4::Ref optional_float4_value_;
- JSONOptionalMatrix4::Ref optional_matrix4_value_;
- JSONOptionalInteger::Ref optional_integer_value_;
- JSONOptionalBoolean::Ref optional_boolean_value_;
- JSONOptionalString::Ref optional_string_value_;
-
- O3D_OBJECT_BASE_DECL_CLASS(TestJSONObject, JSONObject);
- DISALLOW_COPY_AND_ASSIGN(TestJSONObject);
-};
-
-O3D_OBJECT_BASE_DEFN_CLASS("TestJSONObject", TestJSONObject, JSONObject);
-
-const char* TestJSONObject::kFloatValueName = "floatValue";
-const char* TestJSONObject::kFloat2ValueName = "float2Value";
-const char* TestJSONObject::kFloat3ValueName = "float3Value";
-const char* TestJSONObject::kFloat4ValueName = "float4Value";
-const char* TestJSONObject::kMatrix4ValueName = "matrix4Value";
-const char* TestJSONObject::kIntegerValueName = "integerValue";
-const char* TestJSONObject::kBooleanValueName = "booleanValue";
-const char* TestJSONObject::kStringValueName = "stringValue";
-const char* TestJSONObject::kTransformValueName = "transformValue";
-const char* TestJSONObject::kMaterialValueName = "materialValue";
-const char* TestJSONObject::kOptionalFloatValueName = "optionalFloatValue";
-const char* TestJSONObject::kOptionalFloat2ValueName = "optionalFloat2Value";
-const char* TestJSONObject::kOptionalFloat3ValueName = "optionalFloat3Value";
-const char* TestJSONObject::kOptionalFloat4ValueName = "optionalFloat4Value";
-const char* TestJSONObject::kOptionalMatrix4ValueName = "optionalMatrix4Value";
-const char* TestJSONObject::kOptionalIntegerValueName = "optionalIntegerValue";
-const char* TestJSONObject::kOptionalStringValueName = "optionalStringValue";
-const char* TestJSONObject::kOptionalBooleanValueName = "optionalBooleanValue";
-
-} // anonymous namespace
-
-class JSONObjectTest : public testing::Test {
- protected:
- JSONObjectTest()
- : class_manager_(g_service_locator),
- object_manager_(g_service_locator),
- class_register_(g_service_locator) {
- }
-
- virtual void SetUp();
- virtual void TearDown();
-
- Pack* pack() { return pack_; }
-
- private:
- ServiceDependency<ClassManager> class_manager_;
- ServiceDependency<ObjectManager> object_manager_;
- ClassManager::Register<TestJSONObject> class_register_;
- Pack* pack_;
-};
-
-void JSONObjectTest::SetUp() {
- pack_ = object_manager_->CreatePack();
-}
-
-void JSONObjectTest::TearDown() {
- object_manager_->DestroyPack(pack_);
-}
-
-// Creates a JSONObject, tests basic properties.
-TEST_F(JSONObjectTest, BasicTest) {
- TestJSONObject* object = pack()->Create<TestJSONObject>();
- ASSERT_TRUE(object != NULL);
- EXPECT_TRUE(object->IsA(TestJSONObject::GetApparentClass()));
- EXPECT_TRUE(object->IsA(JSONObject::GetApparentClass()));
- EXPECT_TRUE(object->IsA(ParamObject::GetApparentClass()));
-
- // Test everything has its default value.
- EXPECT_EQ(object->float_value(), 0.0f);
- EXPECT_EQ(object->float2_value(), Float2(0.0f, 0.0f));
- EXPECT_EQ(object->float2_value(), Float2(0.0f, 0.0f));
- EXPECT_EQ(object->float3_value(), Float3(0.0f, 0.0f, 0.0f));
- EXPECT_EQ(object->float4_value(), Float4(0.0f, 0.0f, 0.0f, 0.0f));
- EXPECT_EQ(object->matrix4_value(), Matrix4::identity());
- EXPECT_EQ(object->integer_value(), 0);
- EXPECT_FALSE(object->boolean_value());
- EXPECT_EQ(object->string_value(), "");
- EXPECT_TRUE(object->transform_value() == NULL);
- EXPECT_TRUE(object->material_value() == NULL);
-
- // Test that all the values got created by serializing it.
- {
- StringWriter output(StringWriter::LF);
- JsonWriter json_writer(&output, 2);
- object->Serialize(&json_writer);
- json_writer.Close();
- // There is an assumption here that objects will be serialized in this
- // order.
- static const char *kExpected =
- "\"object\": {\n"
- " \"booleanValue\": false,\n"
- " \"float2Value\": [0,0],\n"
- " \"float3Value\": [0,0,0],\n"
- " \"float4Value\": [0,0,0,0],\n"
- " \"floatValue\": 0,\n"
- " \"integerValue\": 0,\n"
- " \"materialValue\": null,\n"
- " \"matrix4Value\": [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]],\n"
- " \"stringValue\": \"\",\n"
- " \"transformValue\": null\n"
- "}\n";
- EXPECT_EQ(kExpected, output.ToString());
- }
-}
-
-TEST_F(JSONObjectTest, SetTest) {
- TestJSONObject* object = pack()->Create<TestJSONObject>();
- ASSERT_TRUE(object != NULL);
- // Test setting the values.
- Matrix4 test_matrix(Vector4(1.0f, 2.0f, 3.0f, 4.0f),
- Vector4(2.0f, 2.0f, 8.0f, 9.0f),
- Vector4(3.0f, 5.0f, 3.0f, 10.0f),
- Vector4(4.0f, 6.0f, 7.0f, 4.0f));
- Matrix4 test_matrix2(Vector4(11.0f, 12.0f, 13.0f, 14.0f),
- Vector4(12.0f, 12.0f, 18.0f, 19.0f),
- Vector4(13.0f, 15.0f, 13.0f, 110.0f),
- Vector4(14.0f, 16.0f, 17.0f, 14.0f));
-
- object->set_float_value(1.2f);
- object->set_float2_value(Float2(3.4f, 5.6f));
- object->set_float3_value(Float3(7.8f, 9.0f, 10.0f));
- object->set_float4_value(Float4(11.0f, 12.0f, 13.0f, 14.0f));
- object->set_matrix4_value(test_matrix);
- object->set_integer_value(123);
- object->set_boolean_value(true);
- object->set_string_value("test");
- object->set_optional_float_value(15.0f);
- object->set_optional_float2_value(Float2(14.0f, 15.0f));
- object->set_optional_float3_value(Float3(13.0f, 14.0f, 15.0f));
- object->set_optional_float4_value(Float4(12.0f, 13.0f, 14.0f, 15.0f));
- object->set_optional_matrix4_value(test_matrix2);
- object->set_optional_integer_value(456);
- object->set_optional_string_value("hello");
- object->set_optional_boolean_value(false);
-
- Transform* transform = pack()->Create<Transform>();
- Material* material = pack()->Create<Material>();
- ASSERT_TRUE(transform != NULL);
- ASSERT_TRUE(material != NULL);
-
- object->set_transform_value(transform);
- object->set_material_value(material);
-
- // Check the new values
- EXPECT_EQ(object->float_value(), 1.2f);
- EXPECT_EQ(object->float2_value(), Float2(3.4f, 5.6f));
- EXPECT_EQ(object->float3_value(), Float3(7.8f, 9.0f, 10.0f));
- EXPECT_EQ(object->float4_value(), Float4(11.0f, 12.0f, 13.0f, 14.0f));
- EXPECT_EQ(object->matrix4_value(), test_matrix);
- EXPECT_EQ(object->integer_value(), 123);
- EXPECT_TRUE(object->boolean_value());
- EXPECT_EQ(object->string_value(), "test");
- EXPECT_TRUE(object->transform_value() == transform);
- EXPECT_TRUE(object->material_value() == material);
-
- // See that they got set by serializing them.
- {
- StringWriter output(StringWriter::LF);
- JsonWriter json_writer(&output, 2);
- object->Serialize(&json_writer);
- json_writer.Close();
-
- char buffer[1000];
- static const char* kExpected =
- "\"object\": {\n"
- " \"booleanValue\": true,\n"
- " \"float2Value\": [3.4,5.6],\n"
- " \"float3Value\": [7.8,9,10],\n"
- " \"float4Value\": [11,12,13,14],\n"
- " \"floatValue\": 1.2,\n"
- " \"integerValue\": 123,\n"
- " \"materialValue\": {\"ref\":%d},\n"
- " \"matrix4Value\": [[1,2,3,4],[2,2,8,9],[3,5,3,10],[4,6,7,4]],\n"
- " \"optionalBooleanValue\": false,\n"
- " \"optionalFloat2Value\": [14,15],\n"
- " \"optionalFloat3Value\": [13,14,15],\n"
- " \"optionalFloat4Value\": [12,13,14,15],\n"
- " \"optionalFloatValue\": 15,\n"
- " \"optionalIntegerValue\": 456,\n"
- " \"optionalMatrix4Value\": "
- "[[11,12,13,14],[12,12,18,19],[13,15,13,110],[14,16,17,14]],\n"
- " \"optionalStringValue\": \"hello\",\n"
- " \"stringValue\": \"test\",\n"
- " \"transformValue\": {\"ref\":%d}\n"
- "}\n";
- sprintf(buffer, kExpected, material->id(), transform->id()); // NOLINT
- EXPECT_EQ(static_cast<const char*>(buffer), output.ToString());
- }
-}
-
-} // namespace o3d
-
diff --git a/o3d/import/cross/main_thread_archive_callback_client.cc b/o3d/import/cross/main_thread_archive_callback_client.cc
deleted file mode 100644
index 2fbbaaa..0000000
--- a/o3d/import/cross/main_thread_archive_callback_client.cc
+++ /dev/null
@@ -1,138 +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.
- */
-
-// MainThreadArchiveCallbackClient forwards data from one thread to
-// another client that will run on the main thread.
-
-#include "core/cross/imain_thread_task_poster.h"
-#include "core/cross/service_locator.h"
-#include "import/cross/main_thread_archive_callback_client.h"
-#include "base/task.h"
-
-namespace o3d {
-
-// Called on main thread.
-MainThreadArchiveCallbackClient::MainThreadArchiveCallbackClient(
- ServiceLocator* service_locator,
- ArchiveCallbackClient *receiver)
- : main_thread_task_poster_(
- service_locator->GetService<IMainThreadTaskPoster>()),
- receiver_(receiver),
- success_(new Success) {
- success_->value = true;
-}
-
-// Called on main thread.
-MainThreadArchiveCallbackClient::~MainThreadArchiveCallbackClient() {
- // Signal pending tasks on main thread not to call the receiver. They are not
- // running concurrently because this destructor is also called on the main
- // thread.
- success_->value = false;
-}
-
-// Called on other thread.
-void MainThreadArchiveCallbackClient::ReceiveFileHeader(
- const ArchiveFileInfo &file_info) {
- main_thread_task_poster_->PostTask(NewRunnableFunction(
- &MainThreadArchiveCallbackClient::ForwardReceiveFileHeader,
- success_,
- receiver_,
- file_info));
-}
-
-// Called on other thread.
-bool MainThreadArchiveCallbackClient::ReceiveFileData(
- MemoryReadStream *stream, size_t size) {
- // Copy stream into temporary buffer. Deleted after it is received by the main
- // thread.
- uint8* buffer = new uint8[size];
- stream->Read(buffer, size);
-
- main_thread_task_poster_->PostTask(NewRunnableFunction(
- &MainThreadArchiveCallbackClient::ForwardReceiveFileData,
- success_,
- receiver_,
- buffer,
- size));
-
- return success_->value;
-}
-
-void MainThreadArchiveCallbackClient::Close(bool success) {
- main_thread_task_poster_->PostTask(NewRunnableFunction(
- &MainThreadArchiveCallbackClient::ForwardClose,
- success_,
- receiver_,
- success));
-}
-
-// Called on main thread.
-void MainThreadArchiveCallbackClient::ForwardReceiveFileHeader(
- SuccessPtr success,
- ArchiveCallbackClient* client,
- ArchiveFileInfo file_info) {
- if (success->value) {
- client->ReceiveFileHeader(file_info);
- }
-}
-
-// Called on main thread.
-void MainThreadArchiveCallbackClient::ForwardReceiveFileData(
- SuccessPtr success,
- ArchiveCallbackClient* client,
- uint8* bytes, size_t size) {
- // Just delete the buffer if there was a previous failure.
- if (!success->value) {
- delete[] bytes;
- return;
- }
-
- MemoryReadStream stream(bytes, size);
- if (!client->ReceiveFileData(&stream, size)) {
- // Do not set this to true on success. That might overwrite a false written
- // by the other thread intended to indicate that the receiver is no
- // longer valid.
- success->value = false;
- }
-
- // Delete temporary buffer allocated by other thread when the main thread is
- // finished with it.
- delete[] bytes;
-}
-
-void MainThreadArchiveCallbackClient::ForwardClose(
- SuccessPtr success_ptr,
- ArchiveCallbackClient* client,
- bool success) {
- client->Close(success && success_ptr->value);
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/main_thread_archive_callback_client.h b/o3d/import/cross/main_thread_archive_callback_client.h
deleted file mode 100644
index 7da39f7..0000000
--- a/o3d/import/cross/main_thread_archive_callback_client.h
+++ /dev/null
@@ -1,85 +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.
- */
-
-// MainThreadArchiveCallbackClient forwards data from one thread to
-// another client that will run on the main thread.
-
-#ifndef O3D_IMPORT_CROSS_MAIN_THREAD_ARCHIVE_CALLBACK_CLIENT_H_
-#define O3D_IMPORT_CROSS_MAIN_THREAD_ARCHIVE_CALLBACK_CLIENT_H_
-
-#include "base/basictypes.h"
-#include "base/thread.h"
-#include "import/cross/archive_processor.h"
-#include "import/cross/memory_stream.h"
-
-namespace o3d {
-
-class IMainThreadTaskPoster;
-class ServiceLocator;
-
-class MainThreadArchiveCallbackClient : public ArchiveCallbackClient {
- public:
- MainThreadArchiveCallbackClient(ServiceLocator* service_locator,
- ArchiveCallbackClient *receiver);
- virtual ~MainThreadArchiveCallbackClient();
-
- virtual void ReceiveFileHeader(const ArchiveFileInfo &file_info);
- virtual bool ReceiveFileData(MemoryReadStream *stream, size_t size);
- virtual void Close(bool success);
-
- private:
- struct Success : ::base::RefCountedThreadSafe< Success > {
- bool value;
- };
-
- typedef scoped_refptr<Success> SuccessPtr;
-
- static void ForwardReceiveFileHeader(SuccessPtr success,
- ArchiveCallbackClient* client,
- ArchiveFileInfo file_info);
-
- static void ForwardReceiveFileData(SuccessPtr success,
- ArchiveCallbackClient* client,
- uint8* bytes, size_t size);
-
- static void ForwardClose(SuccessPtr success_ptr,
- ArchiveCallbackClient* client,
- bool success);
-
- IMainThreadTaskPoster* main_thread_task_poster_;
- ArchiveCallbackClient* receiver_;
- SuccessPtr success_;
-
- DISALLOW_COPY_AND_ASSIGN(MainThreadArchiveCallbackClient);
-};
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_MAIN_THREAD_ARCHIVE_CALLBACK_CLIENT_H_
diff --git a/o3d/import/cross/main_thread_archive_callback_client_test.cc b/o3d/import/cross/main_thread_archive_callback_client_test.cc
deleted file mode 100644
index ac3243a..0000000
--- a/o3d/import/cross/main_thread_archive_callback_client_test.cc
+++ /dev/null
@@ -1,219 +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 functionality of the MainThreadArchiveCallbackClient class
-
-#include "tests/common/win/testing_common.h"
-#include "base/task.h"
-#include "core/cross/imain_thread_task_poster.h"
-#include "core/cross/service_implementation.h"
-#include "import/cross/main_thread_archive_callback_client.h"
-
-namespace o3d {
-
-// Simple standin for IMainThreadTaskPoster that invokes tasks asynchronously.
-class TestMainThreadTaskPoster : IMainThreadTaskPoster {
- public:
- TestMainThreadTaskPoster(ServiceLocator* service_locator)
- : service_(service_locator, this) {
- }
-
- virtual bool IsSupported() {
- return true;
- }
-
- virtual void PostTask(Task* task) {
- tasks_.push_back(task);
- }
-
- void Flush() {
- for (size_t i = 0; i < tasks_.size(); ++i) {
- tasks_[i]->Run();
- delete tasks_[i];
- }
- tasks_.clear();
- }
-
- private:
- ServiceImplementation<IMainThreadTaskPoster> service_;
- std::vector<Task*> tasks_;
-};
-
-class MockArchiveCallbackClient : public ArchiveCallbackClient {
- public:
- MockArchiveCallbackClient()
- : receive_file_header_calls_(0),
- receive_file_header_calls_file_info_("", 0),
- receive_file_data_calls_(0),
- receive_file_data_stream_(NULL),
- receive_file_data_size_(0),
- receive_file_data_result_(false),
- close_calls_(0),
- close_success_(false) {
- }
-
- virtual void ReceiveFileHeader(const ArchiveFileInfo &file_info) {
- ++receive_file_header_calls_;
- receive_file_header_calls_file_info_ = file_info;
- }
-
- virtual bool ReceiveFileData(MemoryReadStream* stream, size_t size) {
- ++receive_file_data_calls_;
- receive_file_data_stream_.reset(new uint8[size]);
- stream->Read(receive_file_data_stream_.get(), size);
- receive_file_data_size_ = size;
- return receive_file_data_result_;
- }
-
- virtual void Close(bool success) {
- ++close_calls_;
- close_success_ = success;
- }
-
- int receive_file_header_calls_;
- ArchiveFileInfo receive_file_header_calls_file_info_;
-
- int receive_file_data_calls_;
- scoped_array<uint8> receive_file_data_stream_;
- size_t receive_file_data_size_;
- bool receive_file_data_result_;
-
- int close_calls_;
- bool close_success_;
-};
-
-class MainThreadArchiveCallbackClientTest : public testing::Test {
- public:
- MainThreadArchiveCallbackClientTest()
- : main_thread_task_poster_(&service_locator_) {
- }
-
- protected:
- virtual void SetUp() {
- receiver_client_ = new MockArchiveCallbackClient;
- main_thread_client_ = new MainThreadArchiveCallbackClient(
- &service_locator_, receiver_client_);
- }
-
- virtual void TearDown() {
- delete receiver_client_;
- delete main_thread_client_;
- }
-
- ServiceLocator service_locator_;
- TestMainThreadTaskPoster main_thread_task_poster_;
- MockArchiveCallbackClient* receiver_client_;
- MainThreadArchiveCallbackClient* main_thread_client_;
-};
-
-TEST_F(MainThreadArchiveCallbackClientTest,
- ReceiveFileHeaderForwardsToReceiver) {
- ArchiveFileInfo info("hello", 7);
- main_thread_client_->ReceiveFileHeader(info);
- main_thread_task_poster_.Flush();
-
- EXPECT_EQ(1, receiver_client_->receive_file_header_calls_);
- EXPECT_EQ("hello",
- receiver_client_->receive_file_header_calls_file_info_.GetFileName());
- EXPECT_EQ(7,
- receiver_client_->receive_file_header_calls_file_info_.GetFileSize());
-}
-
-TEST_F(MainThreadArchiveCallbackClientTest,
- ReceiveFileDataForwardsToReceiverAndReturnsTrueFirstTime) {
- uint8 buffer[] = {1, 2, 3};
- MemoryReadStream stream(buffer, sizeof(buffer));
- receiver_client_->receive_file_data_result_ = true;
- EXPECT_TRUE(main_thread_client_->ReceiveFileData(&stream, sizeof(buffer)));
- main_thread_task_poster_.Flush();
-
- EXPECT_EQ(1, receiver_client_->receive_file_data_calls_);
- EXPECT_EQ(0, memcmp(receiver_client_->receive_file_data_stream_.get(),
- buffer, sizeof(buffer)));
- EXPECT_EQ(sizeof(buffer), receiver_client_->receive_file_data_size_);
-}
-
-TEST_F(MainThreadArchiveCallbackClientTest,
- ReceiveFileDataReportsFailureInSubsequentCall) {
- receiver_client_->receive_file_data_result_ = true;
-
- uint8 buffer[] = {1, 2, 3, 4, 5, 6};
- MemoryReadStream stream(buffer, sizeof(buffer));
-
- receiver_client_->receive_file_data_result_ = false;
- EXPECT_TRUE(main_thread_client_->ReceiveFileData(&stream, 3));
- main_thread_task_poster_.Flush();
- EXPECT_EQ(1, receiver_client_->receive_file_data_calls_);
-
-
- receiver_client_->receive_file_data_result_ = false;
- EXPECT_FALSE(main_thread_client_->ReceiveFileData(&stream, 3));
- main_thread_task_poster_.Flush();
- EXPECT_EQ(1, receiver_client_->receive_file_data_calls_);
-}
-
-TEST_F(MainThreadArchiveCallbackClientTest,
- ReceiveFileHeaderForwardsUnsuccessfulClose) {
- main_thread_client_->Close(false);
- main_thread_task_poster_.Flush();
-
- EXPECT_EQ(1, receiver_client_->close_calls_);
- EXPECT_FALSE(receiver_client_->close_success_);
-}
-
-TEST_F(MainThreadArchiveCallbackClientTest,
- ReceiveFileHeaderForwardsSuccessfulClose) {
- main_thread_client_->Close(true);
- main_thread_task_poster_.Flush();
-
- EXPECT_EQ(1, receiver_client_->close_calls_);
- EXPECT_TRUE(receiver_client_->close_success_);
-}
-
-TEST_F(MainThreadArchiveCallbackClientTest,
- CloseForwardsFailureOfPreviousUnreportedCall) {
- receiver_client_->receive_file_data_result_ = true;
-
- uint8 buffer[] = {1, 2, 3};
- MemoryReadStream stream(buffer, sizeof(buffer));
-
- receiver_client_->receive_file_data_result_ = false;
- EXPECT_TRUE(main_thread_client_->ReceiveFileData(&stream, sizeof(buffer)));
- main_thread_task_poster_.Flush();
- EXPECT_EQ(1, receiver_client_->receive_file_data_calls_);
-
- main_thread_client_->Close(true);
- main_thread_task_poster_.Flush();
- EXPECT_FALSE(receiver_client_->close_success_);
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/memory_buffer.h b/o3d/import/cross/memory_buffer.h
deleted file mode 100644
index 8d5640f..0000000
--- a/o3d/import/cross/memory_buffer.h
+++ /dev/null
@@ -1,78 +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.
- */
-
-
-// A MemoryBuffer object represents an array of type T.
-// Please note that T is really intended to be used
-// for integral types (char, int, float, double)
-// It's very useful when used as a stack-based object or
-// member variable, offering a cleaner, more direct alternative,
-// in some cases, to using smart-pointers in conjunction with operator new
-//
-// Example usage:
-//
-// MemoryBuffer<int> buffer(1024);
-// for (int i = 0; i < 1024; ++i) {
-// buffer[i] = i;
-// }
-
-#ifndef O3D_IMPORT_CROSS_MEMORY_BUFFER_H_
-#define O3D_IMPORT_CROSS_MEMORY_BUFFER_H_
-
-#include <string.h>
-#include <stdlib.h>
-#include <vector>
-
-#include "base/basictypes.h"
-
-// Allocates an array of type T
-
-template <class T>
-class MemoryBuffer {
- public:
- MemoryBuffer() {};
- explicit MemoryBuffer(size_t num_elems) : vector_(num_elems, 0) { }
-
- void Allocate(size_t num_elems) { AllocateClear(num_elems); }
- void AllocateClear(size_t num_elems) { vector_.assign(num_elems, 0); }
- void Deallocate() { vector_.clear(); }
- void Clear() { AllocateClear(vector_.size()); } // sets to all zero values
- void Resize(size_t n) { vector_.resize(n); }
- size_t GetLength() { return vector_.size(); }
- operator T *() { return &vector_[0]; }
-
- private:
- std::vector<T> vector_;
-
- DISALLOW_COPY_AND_ASSIGN(MemoryBuffer);
-};
-
-#endif // O3D_IMPORT_CROSS_MEMORY_BUFFER_H_
diff --git a/o3d/import/cross/memory_buffer_test.cc b/o3d/import/cross/memory_buffer_test.cc
deleted file mode 100644
index 47797bb..0000000
--- a/o3d/import/cross/memory_buffer_test.cc
+++ /dev/null
@@ -1,98 +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 functionality of the MemoryBuffer class
-
-#include "core/cross/client.h"
-#include "tests/common/win/testing_common.h"
-#include "core/cross/error.h"
-#include "import/cross/memory_buffer.h"
-
-namespace o3d {
-
-// Test fixture for RawData testing.
-class MemoryBufferTest : public testing::Test {
-};
-
-// Test RawData
-TEST_F(MemoryBufferTest, Basic) {
- int i;
- MemoryBuffer<int> buffer;
- // Check that initially the buffer is not allocated
- ASSERT_EQ(0U, buffer.GetLength());
-
- // Allocate and check the length is good
- const int kBufferLength = 1024;
- buffer.Allocate(kBufferLength);
- ASSERT_EQ(kBufferLength, static_cast<int>(buffer.GetLength()));
-
- // Once allocated, the initial contents should be zero
- // Check that the buffer contents are zeroed out
- bool buffer_is_cleared = true;
- for (i = 0; i < kBufferLength; ++i) {
- if (buffer[i] != 0) {
- buffer_is_cleared = false;
- break;
- }
- }
- ASSERT_TRUE(buffer_is_cleared);
-
- // Write some values and check that they're OK
- for (i = 0; i < kBufferLength; ++i) {
- buffer[i] = i;
- }
- bool buffer_values_good = true;
- for (i = 0; i < kBufferLength; ++i) {
- if (buffer[i] != i) {
- buffer_values_good = false;
- break;
- }
- }
- ASSERT_TRUE(buffer_values_good);
-
- // Now, clear the buffer and check that it worked
- buffer.Clear();
- buffer_is_cleared = true;
- for (i = 0; i < kBufferLength; ++i) {
- if (buffer[i] != 0) {
- buffer_is_cleared = false;
- break;
- }
- }
- ASSERT_TRUE(buffer_is_cleared);
-
- // Deallocate the buffer and verify its length
- buffer.Deallocate();
- ASSERT_EQ(0U, buffer.GetLength());
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/memory_stream.cc b/o3d/import/cross/memory_stream.cc
deleted file mode 100644
index 9a4d6c5..0000000
--- a/o3d/import/cross/memory_stream.cc
+++ /dev/null
@@ -1,401 +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.
- */
-
-//
-// MemoryReadStream and MemoryWriteStream are simple stream wrappers around
-// memory buffers.
-
-#include "import/cross/memory_stream.h"
-#include "core/cross/types.h"
-
-#if !defined(IS_LITTLE_ENDIAN) && !defined(IS_BIG_ENDIAN)
-#error "IS_LITTLE_ENDIAN or IS_BIG_ENDIAN must be defined!"
-#endif
-
-namespace o3d {
-
-namespace {
-union Int16Union {
- uint8 c[2];
- int16 i;
-};
-
-union UInt16Union {
- uint8 c[2];
- uint16 i;
-};
-
-union Int32Union {
- uint8 c[4];
- int32 i;
-};
-
-union UInt32Union {
- uint8 c[4];
- uint32 i;
-};
-
-union Int32FloatUnion {
- int32 i;
- float f;
-};
-
-union UInt32FloatUnion {
- uint32 i;
- float f;
-};
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-static int16 SwapInt16(const int16 *value) {
- // endian-swap two bytes
- uint8 p[2];
- const char *q = reinterpret_cast<const char*>(value);
- p[0] = q[1];
- p[1] = q[0];
-
- return *reinterpret_cast<int16*>(p);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-static uint16 SwapUInt16(const uint16 *value) {
- // endian-swap two bytes
- uint8 p[2];
- const char *q = reinterpret_cast<const char*>(value);
- p[0] = q[1];
- p[1] = q[0];
-
- return *reinterpret_cast<const uint16*>(p);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-static int32 SwapInt32(const int32 *value) {
- // endian-swap four bytes
- char p[4];
- const char *q = reinterpret_cast<const char*>(value);
- p[0] = q[3];
- p[1] = q[2];
- p[2] = q[1];
- p[3] = q[0];
-
- return *reinterpret_cast<const int32*>(p);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-static uint32 SwapUInt32(const uint32 *value) {
- // endian-swap four bytes
- char p[4];
- const char *q = reinterpret_cast<const char*>(value);
- p[0] = q[3];
- p[1] = q[2];
- p[2] = q[1];
- p[3] = q[0];
-
- return *reinterpret_cast<const uint32*>(p);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-int16 MemoryReadStream::ReadLittleEndianInt16() {
- Int16Union u;
- Read(u.c, 2);
-
-#ifdef IS_BIG_ENDIAN
- return SwapInt16(&u.i);
-#else
- return u.i;
-#endif
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-uint16 MemoryReadStream::ReadLittleEndianUInt16() {
- UInt16Union u;
- Read(u.c, 2);
-
-#ifdef IS_BIG_ENDIAN
- return SwapUint16(&u.i);
-#else
- return u.i;
-#endif
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-int16 MemoryReadStream::ReadBigEndianInt16() {
- Int16Union u;
- Read(u.c, 2);
-
-#ifdef IS_LITTLE_ENDIAN
- return SwapInt16(&u.i);
-#else
- return u.i;
-#endif
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-uint16 MemoryReadStream::ReadBigEndianUInt16() {
- UInt16Union u;
- Read(u.c, 2);
-
-#ifdef IS_LITTLE_ENDIAN
- return SwapUInt16(&u.i);
-#else
- return u.i;
-#endif
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-int32 MemoryReadStream::ReadLittleEndianInt32() {
- Int32Union u;
- Read(u.c, 4);
-
-#ifdef IS_BIG_ENDIAN
- return SwapInt32(&u.i);
-#else
- return u.i;
-#endif
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-uint32 MemoryReadStream::ReadLittleEndianUInt32() {
- UInt32Union u;
- Read(u.c, 4);
-
-#ifdef IS_BIG_ENDIAN
- return SwapUInt32(&u.i);
-#else
- return u.i;
-#endif
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-int32 MemoryReadStream::ReadBigEndianInt32() {
- Int32Union u;
- Read(u.c, 4);
-
-#ifdef IS_LITTLE_ENDIAN
- return SwapInt32(&u.i);
-#else
- return u.i;
-#endif
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-uint32 MemoryReadStream::ReadBigEndianUInt32() {
- UInt32Union u;
- Read(u.c, 4);
-
-#ifdef IS_LITTLE_ENDIAN
- return SwapUInt32(&u.i);
-#else
- return u.i;
-#endif
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-float MemoryReadStream::ReadLittleEndianFloat32() {
- // Read in as int32 then interpret as float32
- Int32FloatUnion u;
- u.i = ReadLittleEndianInt32();
- return u.f;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-float MemoryReadStream::ReadBigEndianFloat32() {
- // Read in as int32 then interpret as float32
- Int32FloatUnion u;
- u.i = ReadBigEndianInt32();
- return u.f;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MemoryWriteStream::WriteLittleEndianInt16(int16 i) {
- Int16Union u;
-
-#ifdef IS_BIG_ENDIAN
- u.i = SwapInt16(&i);
-#else
- u.i = i;
-#endif
-
- Write(u.c, 2);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MemoryWriteStream::WriteLittleEndianUInt16(uint16 i) {
- UInt16Union u;
-
-#ifdef IS_BIG_ENDIAN
- u.i = SwapUInt16(&i);
-#else
- u.i = i;
-#endif
-
- Write(u.c, 2);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MemoryWriteStream::WriteBigEndianInt16(int16 i) {
- Int16Union u;
-
-#ifdef IS_LITTLE_ENDIAN
- u.i = SwapInt16(&i);
-#else
- u.i = i;
-#endif
-
- Write(u.c, 2);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MemoryWriteStream::WriteBigEndianUInt16(uint16 i) {
- UInt16Union u;
-
-#ifdef IS_LITTLE_ENDIAN
- u.i = SwapUInt16(&i);
-#else
- u.i = i;
-#endif
-
- Write(u.c, 2);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MemoryWriteStream::WriteLittleEndianInt32(int32 i) {
- Int32Union u;
-
-#ifdef IS_BIG_ENDIAN
- u.i = SwapInt32(&i);
-#else
- u.i = i;
-#endif
-
- Write(u.c, 4);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MemoryWriteStream::WriteLittleEndianUInt32(uint32 i) {
- UInt32Union u;
-
-#ifdef IS_BIG_ENDIAN
- u.i = SwapUInt32(&i);
-#else
- u.i = i;
-#endif
-
- Write(u.c, 4);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MemoryWriteStream::WriteBigEndianInt32(int32 i) {
- Int32Union u;
-
-#ifdef IS_LITTLE_ENDIAN
- u.i = SwapInt32(&i);
-#else
- u.i = i;
-#endif
-
- Write(u.c, 4);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MemoryWriteStream::WriteBigEndianUInt32(uint32 i) {
- UInt32Union u;
-
-#ifdef IS_LITTLE_ENDIAN
- u.i = SwapUInt32(&i);
-#else
- u.i = i;
-#endif
-
- Write(u.c, 4);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MemoryWriteStream::WriteLittleEndianFloat32(float f) {
- // Interpret byte-pattern of f as int32 and write out
- Int32FloatUnion u;
- u.f = f;
- WriteLittleEndianInt32(u.i);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void MemoryWriteStream::WriteBigEndianFloat32(float f) {
- // Interpret byte-pattern of f as int32 and write out
- Int32FloatUnion u;
- u.f = f;
- WriteBigEndianInt32(u.i);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// A couple of useful utility functions
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Returns the bytes pointed to by |value| as little-endian 16
-int16 MemoryReadStream::GetLittleEndianInt16(const int16 *value) {
-#ifdef IS_BIG_ENDIAN
- return SwapInt16(value);
-#else
- return *value;
-#endif
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Returns the bytes pointed to by |value| as little-endian 16
-uint16 MemoryReadStream::GetLittleEndianUInt16(const uint16 *value) {
-#ifdef IS_BIG_ENDIAN
- return SwapUInt16(value);
-#else
- return *value;
-#endif
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Returns the bytes pointed to by |value| as little-endian 32
-int32 MemoryReadStream::GetLittleEndianInt32(const int32 *value) {
-#ifdef IS_BIG_ENDIAN
- return SwapInt32(value);
-#else
- return *value;
-#endif
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Returns the bytes pointed to by |value| as little-endian 32
-uint32 MemoryReadStream::GetLittleEndianUInt32(const uint32 *value) {
-#ifdef IS_BIG_ENDIAN
- return SwapUint32(value);
-#else
- return *value;
-#endif
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/memory_stream.h b/o3d/import/cross/memory_stream.h
deleted file mode 100644
index 2801b2b..0000000
--- a/o3d/import/cross/memory_stream.h
+++ /dev/null
@@ -1,288 +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.
- */
-
-//
-// MemoryReadStream and MemoryWriteStream are simple stream wrappers around
-// memory buffers. Their constructers take a pointer to the memory and
-// the length of the buffer. They are useful for pipeline based processing
-// of byte-streams.
-//
-// MemoryReadStream maintains its stream position
-// and can be read with the Read() method, returning the number of bytes
-// read (similar to fread()).
-//
-// MemoryWriteStream maintains its stream position
-// and can be written with the Write() method, returning the number of bytes
-// actually written (similar to fwrite()).
-
-#ifndef O3D_IMPORT_CROSS_MEMORY_STREAM_H_
-#define O3D_IMPORT_CROSS_MEMORY_STREAM_H_
-
-#include <string.h>
-#include "base/basictypes.h"
-
-namespace o3d {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class MemoryReadStream {
- public:
- MemoryReadStream(const uint8 *memory, size_t n)
- : memory_(memory), read_index_(0), length_(n) {}
-
- // Explicit copy constructor
- MemoryReadStream(const MemoryReadStream &stream)
- : memory_(stream.memory_),
- read_index_(stream.read_index_),
- length_(stream.length_) {}
-
- virtual ~MemoryReadStream() {}
-
- // Similar to fread(), will try to copy |n| bytes to address |p|
- // (copies fewer bytes if the stream doesn't have enough data)
- // returns the number of bytes copied
- virtual size_t Read(void *p, size_t n) {
- size_t remaining = GetRemainingByteCount();
- size_t bytes_to_read = (n < remaining) ? n : remaining;
- memcpy(p, memory_ + read_index_, bytes_to_read);
- read_index_ += bytes_to_read;
- return bytes_to_read;
- }
-
- // Attempts to read a complete object of type T
- // returns |true| on success
- template<typename T>
- bool ReadAs(T *p) {
- size_t bytes_read = this->Read(reinterpret_cast<char*>(p),
- sizeof(T));
- return (bytes_read == sizeof(T));
- }
-
- // Reads the next byte in the stream (if there are any left)
- // If the stream has run dry (is empty) then returns 0
- // To check number of bytes available, call GetRemainingByteCount()
- virtual uint8 ReadByte() {
- if (read_index_ >= length_) return 0;
-
- uint8 byte = memory_[read_index_];
- read_index_++;
-
- return byte;
- }
-
- // 16 and 32bit integer reading for both little and big endian
- int16 ReadLittleEndianInt16();
- uint16 ReadLittleEndianUInt16();
- int16 ReadBigEndianInt16();
- uint16 ReadBigEndianUInt16();
- int32 ReadLittleEndianInt32();
- uint32 ReadLittleEndianUInt32();
- int32 ReadBigEndianInt32();
- uint32 ReadBigEndianUInt32();
-
- // IEEE 32-bit float reading (little and big endian)
- float ReadLittleEndianFloat32();
- float ReadBigEndianFloat32();
-
- // Returns the number of bytes left in the stream (which can be read)
- size_t GetRemainingByteCount() {
- return length_ - read_index_;
- };
-
- // Returns |true| if the read position is at end-of-stream
- // (no more bytes left to read)
- bool EndOfStream() { return GetRemainingByteCount() == 0; }
-
- // Instead of calling Read(), this gives direct access to the data
- // without a memcpy().
- // Calling GetRemainingByteCount() will give the number of remaining bytes
- // starting at this address...
- const uint8 *GetDirectMemoryPointer() { return memory_ + read_index_; }
-
- // Same as GetDirectMemoryPointer() but returns pointer of desired type
- template <typename T>
- T *GetDirectMemoryPointerAs() {
- return reinterpret_cast<T*>(GetDirectMemoryPointer());
- };
-
- // Advances the read position by |n| bytes
- void Skip(size_t n) {
- size_t remaining = GetRemainingByteCount();
- read_index_ += (n < remaining) ? n : remaining;
- }
-
- // Changes the read position to the given byte offset.
- // This allows random access into the stream similar to fseek()
- bool Seek(size_t seek_pos) {
- bool valid = (seek_pos >= 0 && seek_pos <= length_);
- if (valid) {
- read_index_ = seek_pos;
- }
- return valid;
- }
-
- // Returns the total number of bytes in the stream
- size_t GetTotalStreamLength() const { return length_; }
-
-
- // Returns the byte position (offset from start of stream)
- // this is effectively the number of bytes which have, so far,
- // been read
- size_t GetStreamPosition() const { return read_index_; }
-
- // utility methods (swaps the value if necessary)
- static int16 GetLittleEndianInt16(const int16 *value);
- static uint16 GetLittleEndianUInt16(const uint16 *value);
- static int32 GetLittleEndianInt32(const int32 *value);
- static uint32 GetLittleEndianUInt32(const uint32 *value);
-
- protected:
- const uint8 *memory_;
- size_t read_index_;
- size_t length_;
-
- // Disallow assignment
- void operator=(const MemoryReadStream&);
-};
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class MemoryWriteStream {
- public:
- // May be completely initialized by calling Assign()
- MemoryWriteStream() : memory_(NULL), write_index_(0), length_(0) {}
-
- MemoryWriteStream(uint8 *memory, size_t n)
- : memory_(memory), write_index_(0), length_(n) {}
-
- // Explicit copy constructor
- MemoryWriteStream(const MemoryWriteStream &stream)
- : memory_(stream.memory_),
- write_index_(stream.write_index_),
- length_(stream.length_) {}
-
- virtual ~MemoryWriteStream() {}
-
- // In the case where the default constructor was used, this is useful
- // to assign a pointer to memory and a length in bytes.
- void Assign(uint8 *memory, size_t n) {
- memory_ = memory;
- length_ = n;
- write_index_ = 0;
- }
-
- // Changes the write position to the given byte offset.
- // This allows random access into the stream similar to fseek()
- bool Seek(size_t seek_pos) {
- bool valid = (seek_pos >= 0 && seek_pos <= length_);
- if (valid) {
- write_index_ = seek_pos;
- }
- return valid;
- }
-
- // Similar to fwrite(), will try to copy |n| bytes from address |p|
- // (copies fewer bytes if the stream doesn't have enough data)
- // returns the number of bytes copied
- virtual size_t Write(const void *p, size_t n) {
- size_t remaining = GetRemainingByteCount();
- size_t bytes_to_write = (n < remaining) ? n : remaining;
- memcpy(memory_ + write_index_, p, bytes_to_write);
- write_index_ += bytes_to_write;
- return bytes_to_write;
- }
-
- void WriteByte(uint8 byte) {
- Write(&byte, 1);
- }
-
- // 16 and 32bit integer writing for both little and big endian
- void WriteLittleEndianInt16(int16 i);
- void WriteLittleEndianUInt16(uint16 i);
- void WriteBigEndianInt16(int16 i);
- void WriteBigEndianUInt16(uint16 i);
- void WriteLittleEndianInt32(int32 i);
- void WriteLittleEndianUInt32(uint32 i);
- void WriteBigEndianInt32(int32 i);
- void WriteBigEndianUInt32(uint32 i);
-
- // IEEE 32-bit float writing (little and big endian)
- void WriteLittleEndianFloat32(float f);
- void WriteBigEndianFloat32(float f);
-
- // Returns the number of bytes left in the stream (which can be written)
- size_t GetRemainingByteCount() {
- return length_ - write_index_;
- };
-
- // Returns |true| if the read position is at end-of-stream
- // (no more bytes left to read)
- bool EndOfStream() { return GetRemainingByteCount() == 0; }
-
- // Returns the total number of bytes in the stream
- size_t GetTotalStreamLength() const { return length_; }
-
- // Returns the byte position (offset from start of stream)
- // this is effectively the number of bytes which have, so far,
- // been written
- size_t GetStreamPosition() const { return write_index_; }
-
- protected:
- uint8 *memory_;
- size_t write_index_;
- size_t length_;
-
- // Disallow assignment
- void operator=(const MemoryWriteStream&);
-};
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Abstract interface to process a memory stream
-class StreamProcessor {
- public:
-
-// Status is defined in Linux
-#ifdef Status
-#undef Status
-#endif
- enum Status {
- IN_PROGRESS,
- SUCCESS,
- FAILURE,
- };
-
- virtual ~StreamProcessor() {}
- virtual Status ProcessBytes(MemoryReadStream *stream,
- size_t bytes_to_process) = 0;
- virtual void Close(bool success) = 0;
-};
-
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_MEMORY_STREAM_H_
diff --git a/o3d/import/cross/memory_stream_test.cc b/o3d/import/cross/memory_stream_test.cc
deleted file mode 100644
index 3b238fe..0000000
--- a/o3d/import/cross/memory_stream_test.cc
+++ /dev/null
@@ -1,329 +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 functionality of the MemoryReadStream and MemoryWriteStream
-// classes
-
-#include "core/cross/client.h"
-#include "tests/common/win/testing_common.h"
-#include "core/cross/error.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-#include "core/cross/types.h"
-
-#if !defined(IS_LITTLE_ENDIAN) && !defined(IS_BIG_ENDIAN)
-#error "IS_LITTLE_ENDIAN or IS_BIG_ENDIAN must be defined!"
-#endif
-
-namespace o3d {
-
-static char *kTestString = const_cast<char*>
- ("Tests functionality of the MemoryReadStream and MemoryWriteStream classes");
-
-
-// Test fixture for MemoryReadStream and MemoryWriteStream.
-class MemoryStreamTest : public testing::Test {
-};
-
-// Test reading from a buffer using MemoryReadStream
-TEST_F(MemoryStreamTest, Read) {
- int i;
-
- // Put a test string in a memory buffer
- const int kStringLength = strlen(kTestString);
- MemoryBuffer<uint8> buffer(kStringLength);
-
- for (i = 0; i < kStringLength; ++i) {
- buffer[i] = kTestString[i];
- }
-
- // Now, create a read stream on that buffer and verify that it reads
- // correctly...
- MemoryReadStream read_stream(buffer, buffer.GetLength());
-
- EXPECT_EQ(buffer.GetLength(), read_stream.GetTotalStreamLength());
- EXPECT_EQ(kStringLength,
- static_cast<int>(read_stream.GetTotalStreamLength()));
-
- // Read one byte at a time and verify
- uint8 c;
- for (i = 0; i < kStringLength; ++i) {
- c = read_stream.ReadByte();
- EXPECT_EQ(c, kTestString[i]);
- }
- // Read an extra byte and verify it's zero
- c = read_stream.ReadByte();
- EXPECT_EQ(c, 0);
-
- // Now, create a 2nd read stream
- MemoryReadStream read_stream2(buffer, buffer.GetLength());
- // Get direct memory access and check the pointer is correct
- const uint8 *p = read_stream2.GetDirectMemoryPointer();
- EXPECT_EQ(const_cast<uint8*>(p), static_cast<uint8*>(buffer));
-
- // Test the Read() method
-
- // First read 5 bytes
- MemoryBuffer<uint8> read_buffer(kStringLength);
- int bytes_read = read_stream2.Read(read_buffer, 5);
-
- // Verify bytes read, stream position and remaining byte count
- EXPECT_EQ(5, bytes_read);
- EXPECT_EQ(5U, read_stream2.GetStreamPosition());
- EXPECT_EQ(kStringLength - 5,
- static_cast<int>(read_stream2.GetRemainingByteCount()));
-
- // Next read the remaining bytes
- bytes_read = read_stream2.Read(read_buffer + 5, kStringLength - 5);
- EXPECT_EQ(kStringLength - 5, bytes_read);
-
- // Make sure we read the correct data
- EXPECT_EQ(0, memcmp(read_buffer, buffer, kStringLength));
-
- // Try to read some more, even though we're at stream end
- bytes_read = read_stream2.Read(read_buffer, 1000);
- EXPECT_EQ(0, bytes_read); // make sure no bytes were read
-
- // Now, create a 3rd read stream
- MemoryReadStream read_stream3(buffer, buffer.GetLength());
-
- // Let's test the Skip() method
- read_stream3.Skip(6); // skip over the first 6 bytes
-
- // Read three bytes in a row and verify
- uint8 c1 = read_stream3.ReadByte();
- uint8 c2 = read_stream3.ReadByte();
- uint8 c3 = read_stream3.ReadByte();
- EXPECT_EQ('f', c1);
- EXPECT_EQ('u', c2);
- EXPECT_EQ('n', c3);
-}
-
-// Test Writing to a buffer using MemoryWriteStream
-TEST_F(MemoryStreamTest, Write) {
- // Create a write stream without assigning it to memory yet
- MemoryWriteStream empty_stream;
-
- // Verfify length is zero
- EXPECT_EQ(0U, empty_stream.GetTotalStreamLength());
-
- // Now, assign it to the string (OK, we can't really write to
- // this memory, but we're just checking the API here
- const int kStringLength = strlen(kTestString);
- empty_stream.Assign(reinterpret_cast<uint8*>(kTestString), kStringLength);
-
- // Sanity check on length, position, remaining
- EXPECT_EQ(kStringLength,
- static_cast<int>(empty_stream.GetTotalStreamLength()));
- EXPECT_EQ(0U, empty_stream.GetStreamPosition());
- EXPECT_EQ(kStringLength,
- static_cast<int>(empty_stream.GetRemainingByteCount()));
-
- // Create a write stream on a buffer we can write to
- MemoryBuffer<uint8> buffer(kStringLength);
- MemoryWriteStream write_stream(buffer, buffer.GetLength());
- EXPECT_EQ(static_cast<int>(buffer.GetLength()), kStringLength);
-
- // Write 5 bytes
- uint8 *p = reinterpret_cast<uint8*>(kTestString);
- int bytes_written = write_stream.Write(p, 5);
- EXPECT_EQ(5, bytes_written);
- EXPECT_EQ(5U, write_stream.GetStreamPosition());
- EXPECT_EQ(kStringLength - 5,
- static_cast<int>(write_stream.GetRemainingByteCount()));
-
- // Write the remaining bytes in the string
- bytes_written = write_stream.Write(p + 5, kStringLength - 5);
- EXPECT_EQ(kStringLength - 5, bytes_written);
- EXPECT_EQ(kStringLength, static_cast<int>(write_stream.GetStreamPosition()));
- EXPECT_EQ(0U, write_stream.GetRemainingByteCount());
-
- // Verify we wrote the correct data
- EXPECT_EQ(0, memcmp(buffer, kTestString, kStringLength));
-
- // Try to write some more even though the buffer is full
- bytes_written = write_stream.Write(p, kStringLength);
- EXPECT_EQ(0, bytes_written);
-}
-
-// Basic sanity check for endian writing/reading
-TEST_F(MemoryStreamTest, EndianSanity16) {
- // Sanity check int16
- MemoryBuffer<int16> buffer16(2);
- int16 *p = buffer16;
- uint8 *p8 = reinterpret_cast<uint8*>(p);
- MemoryWriteStream write_stream(p8, sizeof(int16) * 2);
-
- int16 value = 0x1234;
- write_stream.WriteLittleEndianInt16(value);
- write_stream.WriteBigEndianInt16(value);
-
- // Verify that the bytes are in the correct order
- uint8 low_byte = value & 0xff;
- uint8 high_byte = value >> 8;
-
- // validate little-endian
- EXPECT_EQ(low_byte, p8[0]);
- EXPECT_EQ(high_byte, p8[1]);
-
- // validate big-endian
- EXPECT_EQ(high_byte, p8[2]);
- EXPECT_EQ(low_byte, p8[3]);
-}
-
-// Basic sanity check for endian writing/reading
-TEST_F(MemoryStreamTest, EndianSanity32) {
- // Sanity check int32
- MemoryBuffer<int32> buffer32(2);
- int32 *p = buffer32;
- uint8 *p8 = reinterpret_cast<uint8*>(p);
- MemoryWriteStream write_stream(p8, sizeof(int32) * 2);
-
- int32 value = 0x12345678;
- write_stream.WriteLittleEndianInt32(value);
- write_stream.WriteBigEndianInt32(value);
-
- // Verify that the bytes are in the correct order
- uint8 byte1 = value & 0xff;
- uint8 byte2 = (value >> 8) & 0xff;
- uint8 byte3 = (value >> 16) & 0xff;
- uint8 byte4 = (value >> 24) & 0xff;
-
- // validate little-endian
- EXPECT_EQ(byte1, p8[0]);
- EXPECT_EQ(byte2, p8[1]);
- EXPECT_EQ(byte3, p8[2]);
- EXPECT_EQ(byte4, p8[3]);
-
- // validate big-endian
- EXPECT_EQ(byte4, p8[4]);
- EXPECT_EQ(byte3, p8[5]);
- EXPECT_EQ(byte2, p8[6]);
- EXPECT_EQ(byte1, p8[7]);
-}
-
-// Basic sanity check for endian writing/reading
-TEST_F(MemoryStreamTest, EndianSanityFloat32) {
- // Sanity check int32
- MemoryBuffer<float> buffer32(2);
- float *p = buffer32;
- uint8 *p8 = reinterpret_cast<uint8*>(p);
- MemoryWriteStream write_stream(p8, sizeof(int32) * 2);
-
- union {
- int32 ivalue;
- float fvalue;
- } value;
- value.fvalue = 3.14159f;
- write_stream.WriteLittleEndianFloat32(value.fvalue);
- write_stream.WriteBigEndianFloat32(value.fvalue);
-
- // Verify that the bytes are in the correct order
- uint8 byte1 = value.ivalue & 0xff;
- uint8 byte2 = (value.ivalue >> 8) & 0xff;
- uint8 byte3 = (value.ivalue >> 16) & 0xff;
- uint8 byte4 = (value.ivalue >> 24) & 0xff;
-
- // validate little-endian
- EXPECT_EQ(byte1, p8[0]);
- EXPECT_EQ(byte2, p8[1]);
- EXPECT_EQ(byte3, p8[2]);
- EXPECT_EQ(byte4, p8[3]);
-
- // validate big-endian
- EXPECT_EQ(byte4, p8[4]);
- EXPECT_EQ(byte3, p8[5]);
- EXPECT_EQ(byte2, p8[6]);
- EXPECT_EQ(byte1, p8[7]);
-}
-
-// Write then read int16, int32, and float32 little/big endian values
-TEST_F(MemoryStreamTest, Endian) {
- const int16 kValue1 = 13243;
- const int32 kValue2 = 2393043;
- const float kValue3 = -0.039483f;
- const int16 kValue4 = -3984;
- const float kValue5 = 1234.5678f;
- const uint8 kValue6 = 5; // write a single byte to make things interesting
- const int32 kValue7 = -3920393;
-
- size_t total_size = sizeof(kValue1) +
- sizeof(kValue2) +
- sizeof(kValue3) +
- sizeof(kValue4) +
- sizeof(kValue5) +
- sizeof(kValue6) +
- sizeof(kValue7);
-
- MemoryBuffer<uint8> buffer(total_size);
-
- // write the values to the buffer
- uint8 *p8 = buffer;
- MemoryWriteStream write_stream(p8, total_size);
-
- write_stream.WriteLittleEndianInt16(kValue1);
- write_stream.WriteBigEndianInt32(kValue2);
- write_stream.WriteLittleEndianFloat32(kValue3);
- write_stream.WriteBigEndianInt16(kValue4);
- write_stream.WriteBigEndianFloat32(kValue5);
- write_stream.Write(&kValue6, 1);
- write_stream.WriteLittleEndianInt32(kValue7);
-
- // now read them back in and verify
- int16 read_value1;
- int32 read_value2;
- float read_value3;
- int16 read_value4;
- float read_value5;
- uint8 read_value6;
- int32 read_value7;
- MemoryReadStream read_stream(p8, total_size);
-
- read_value1 = read_stream.ReadLittleEndianInt16();
- read_value2 = read_stream.ReadBigEndianInt32();
- read_value3 = read_stream.ReadLittleEndianFloat32();
- read_value4 = read_stream.ReadBigEndianInt16();
- read_value5 = read_stream.ReadBigEndianFloat32();
- read_stream.Read(&read_value6, 1);
- read_value7 = read_stream.ReadLittleEndianInt32();
-
- // Validate
- EXPECT_EQ(read_value1, kValue1);
- EXPECT_EQ(read_value2, kValue2);
- EXPECT_EQ(read_value3, kValue3);
- EXPECT_EQ(read_value4, kValue4);
- EXPECT_EQ(read_value5, kValue5);
- EXPECT_EQ(read_value6, kValue6);
- EXPECT_EQ(read_value7, kValue7);
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/precompile.cc b/o3d/import/cross/precompile.cc
deleted file mode 100644
index 8a70235..0000000
--- a/o3d/import/cross/precompile.cc
+++ /dev/null
@@ -1,33 +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 "import/cross/precompile.h"
diff --git a/o3d/import/cross/precompile.h b/o3d/import/cross/precompile.h
deleted file mode 100644
index 98ad5ca..0000000
--- a/o3d/import/cross/precompile.h
+++ /dev/null
@@ -1,116 +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_IMPORT_CROSS_PRECOMPILE_H_
-#define O3D_IMPORT_CROSS_PRECOMPILE_H_
-
-#ifdef OS_WIN
-#include <windows.h>
-#include <shellapi.h>
-#include <stdlib.h>
-#endif
-
-#ifdef __cplusplus
-
-#if defined(RENDERER_D3D9)
-#include <d3dx9.h>
-#endif // defined(RENDERER_D3D9)
-
-#if defined(RENDERER_GL)
-#include <GL/glew.h>
-#if defined(OS_WIN)
-#include <GL/wglew.h>
-#endif
-#endif // defined(RENDERER_GL)
-
-#if defined(RENDERER_GLES2)
-#include <GL/glew.h>
-#if defined(OS_WIN)
-#include <GL/wglew.h>
-#endif
-#endif // defined(RENDERER_GLES2)
-
-#include <Cg/cg.h>
-#include <Cg/cgGL.h>
-#include <FCollada.h>
-#include <FCDocument/FCDocument.h>
-#include <FCDocument/FCDocumentTools.h>
-#include <FCDocument/FCDAnimated.h>
-#include <FCDocument/FCDAnimationCurve.h>
-#include <FCDocument/FCDAnimationKey.h>
-#include <FCDocument/FCDEffect.h>
-#include <FCDocument/FCDEffectCode.h>
-#include <FCDocument/FCDEffectParameter.h>
-#include <FCDocument/FCDEffectParameterSurface.h>
-#include <FCDocument/FCDEffectParameterSampler.h>
-#include <FCDocument/FCDEffectPass.h>
-#include <FCDocument/FCDEffectPassShader.h>
-#include <FCDocument/FCDEffectPassState.h>
-#include <FCDocument/FCDEffectProfile.h>
-#include <FCDocument/FCDEffectProfileFX.h>
-#include <FCDocument/FCDEffectStandard.h>
-#include <FCDocument/FCDEffectTechnique.h>
-#include <FCDocument/FCDExtra.h>
-#include <FCDocument/FCDEntity.h>
-#include <FCDocument/FCDImage.h>
-#include <FCDocument/FCDMaterial.h>
-#include <FCDocument/FCDMaterialInstance.h>
-#include <FCDocument/FCDLibrary.h>
-#include <FCDocument/FCDSceneNode.h>
-#include <FCDocument/FCDCamera.h>
-#include <FCDocument/FCDGeometry.h>
-#include <FCDocument/FCDGeometryInstance.h>
-#include <FCDocument/FCDGeometryMesh.h>
-#include <FCDocument/FCDGeometryPolygons.h>
-#include <FCDocument/FCDGeometryPolygonsInput.h>
-#include <FCDocument/FCDGeometryPolygonsTools.h>
-#include <FCDocument/FCDGeometrySource.h>
-#include <FCDocument/FCDController.h>
-#include <FCDocument/FCDControllerInstance.h>
-#include <FCDocument/FCDSkinController.h>
-#include <FCDocument/FCDTexture.h>
-#include <FCDocument/FCDTransform.h>
-#include <FUtils/FUFileManager.h>
-#include <FUtils/FUUri.h>
-#include <FUtils/FUXmlParser.h>
-
-#ifndef OS_WIN
-#include <vector>
-using std::min;
-using std::max;
-#endif
-
-#include <sstream>
-
-#endif // __cplusplus
-
-#endif // O3D_IMPORT_CROSS_PRECOMPILE_H_
diff --git a/o3d/import/cross/raw_data.cc b/o3d/import/cross/raw_data.cc
deleted file mode 100644
index e5c0246..0000000
--- a/o3d/import/cross/raw_data.cc
+++ /dev/null
@@ -1,291 +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 implementation for raw-data which may be used
-// by the progressive streaming archive system
-
-#include "import/cross/raw_data.h"
-
-#include "base/file_path.h"
-#include "base/file_util.h"
-#include "core/cross/error.h"
-#include "utils/cross/dataurl.h"
-#include "utils/cross/file_path_utils.h"
-
-using file_util::OpenFile;
-using file_util::CloseFile;
-using file_util::GetFileSize;
-
-namespace o3d {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// RawData class
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-O3D_DEFN_CLASS(RawData, ParamObject);
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-RawData::RawData(ServiceLocator* service_locator,
- const String &uri,
- const void *data,
- size_t length)
- : ParamObject(service_locator), uri_(uri), allow_string_value_(true) {
- // make private copy of data
- data_.reset(new uint8[length]);
- length_ = length;
- memcpy(data_.get(), data, length);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-RawData::Ref RawData::Create(ServiceLocator* service_locator,
- const String &uri,
- const void *data,
- size_t length) {
- return RawData::Ref(new RawData(service_locator, uri, data, length));
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-RawData::Ref RawData::CreateFromFile(ServiceLocator* service_locator,
- const String &uri,
- const String& filename) {
- RawData::Ref data(Create(service_locator, uri, NULL, 0));
- if (!data->SetFromFile(filename)) {
- data.Reset();
- }
-
- return data;
-}
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-RawData::Ref RawData::CreateFromDataURL(ServiceLocator* service_locator,
- const String& data_url) {
- RawData::Ref raw_data(Create(service_locator, "", NULL, 0));
- if (!raw_data->SetFromDataURL(data_url)) {
- raw_data.Reset();
- }
-
- return raw_data;
-}
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-RawData::~RawData() {
- Discard();
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool RawData::SetFromFile(const String& filename) {
- // We can't allow general string files to be downloaded from anywhere
- // as that would override the security measures that have been added to
- // XMLHttpRequest over the years. Images and other binary datas are okay.
- // because RawData can only be passed to stuff that understands specific
- // formats.
- allow_string_value_ = false;
- FilePath filepath = UTF8ToFilePath(filename);
- FILE *file = OpenFile(filepath, "rb");
- bool result = false;
- if (!file) {
- DLOG(ERROR) << "file not found \"" << filename << "\"";
- } else {
- // Determine the file's length
- int64 file_size64;
- if (!GetFileSize(filepath, &file_size64)) {
- DLOG(ERROR) << "error getting file size \"" << filename << "\"";
- } else {
- if (file_size64 > 0xffffffffLL) {
- DLOG(ERROR) << "file is too large \"" << filename << "\"";
- } else {
- size_t file_length = static_cast<size_t>(file_size64);
-
- // Load the file data into memory
- data_.reset(new uint8[file_length]);
- length_ = file_length;
- if (fread(data_.get(), file_length, 1, file) != 1) {
- DLOG(ERROR) << "error reading file \"" << filename << "\"";
- } else {
- result = true;
- }
- }
- }
- CloseFile(file);
- }
-
- return result;
-}
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool RawData::SetFromDataURL(const String& data_url) {
- String error_string;
- size_t data_length = 0;
- bool no_errors = dataurl::FromDataURL(data_url,
- &data_,
- &data_length,
- &error_string);
- length_ = data_length;
- if (!no_errors) {
- O3D_ERROR(service_locator()) << error_string;
- return false;
- }
- return true;
-}
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-const uint8 *RawData::GetData() const {
- // Return data immediately if we have it
- if (data_.get()) {
- return data_.get();
- } else {
- DLOG(ERROR) << "cannot retrieve data object - it has been released";
- return NULL;
- }
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-namespace {
-
-// Simple UTF8 validation.
-// Params:
-// data: RawData to validate.
-// utf8_length: pointer to size_t to receieve length of UTF8 data.
-// Returns:
-// the start of the UTF-8 string or NULL if not valid UTF-8.
-const char* GetValidUTF8(const RawData& data, size_t* utf8_length) {
- DCHECK(utf8_length);
- const uint8* s = data.GetDataAs<const uint8>(0);
- if (!s) {
- return NULL;
- }
- size_t length = data.GetLength();
-
- // Check for BOM and skip it.
- if (length >= 3 && s[0] == 0xEF && s[1] == 0xBB && s[2] == 0xBF) {
- length -= 3;
- s += 3;
- }
-
- const uint8* start = s;
- *utf8_length = length;
-
- while (length) {
- uint8 c = *s++;
- if (c >= 0x80) {
- // It's a multi-byte character
- if (c >= 0xC2 && c <= 0xF4) {
- uint32 codepoint;
- size_t remaining_code_length = 0;
- if ((c & 0xE0) == 0xC0) {
- codepoint = c & 0x1F;
- remaining_code_length = 1;
- } else if ((c & 0xF0) == 0xE0) {
- codepoint = c & 0x0F;
- remaining_code_length = 2;
- } else if ((c & 0xF8) == 0xF0) {
- codepoint = c & 0x07;
- remaining_code_length = 3;
- }
- if (remaining_code_length == 0 || remaining_code_length > length) {
- // Not valid UTF-8
- return NULL;
- }
- length -= remaining_code_length;
- for (size_t cc = 0; cc < remaining_code_length; ++cc) {
- c = *s++;
- if ((c & 0xC0) != 0x80) {
- // Not valid UTF-8
- return NULL;
- }
- codepoint = (codepoint << 6) | (c & 0x3F);
- }
- if (codepoint >= 0xD800 && codepoint < 0xDFFF) {
- // Not valid UTF-8
- return NULL;
- }
- } else {
- // Not valid UTF.
- return NULL;
- }
- } else if (c == 0x00) {
- // It's NULL, not UTF-8
- return NULL;
- }
- --length;
- }
- return reinterpret_cast<const char*>(start);
-};
-
-} // anonymous namespace
-
-String RawData::StringValue() const {
- // NOTE: Originally it was thought to only allow certain extensions.
- // Unfortunately it's not clear what list of extensions are valid. The list of
- // extensions that might be useful to an application is nearly infinite (.txt,
- // .json, .xml, .ini, .csv, .php, .js, .html, .css .xsl, .dae, etc.) So,
- // instead we validate the string is valid UTF-8 AND that there are no NULLs
- // in the string.
-
- // We can't allow general string files to be downloaded from anywhere
- // as that would override the security measures that have been added to
- // XMLHttpRequest over the years. Images and other binary datas are okay.
- // because RawData can only be passed to stuff that understands specific
- // formats.
- if (!allow_string_value_) {
- O3D_ERROR(service_locator())
- << "You can only get a stringValue from RawDatas inside archives.";
- } else {
- size_t length;
- const char* utf8 = GetValidUTF8(*this, &length);
- if (!utf8) {
- O3D_ERROR(service_locator()) << "RawData is not valid UTF-8 string";
- } else {
- return String (utf8, length);
- }
- }
- return String();
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void RawData::Discard() {
- data_.reset();
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool RawData::IsOffsetLengthValid(size_t offset, size_t length) const {
- if (offset + length < offset) {
- O3D_ERROR(service_locator()) << "overflow";
- return false;
- }
- if (offset + length > length_) {
- O3D_ERROR(service_locator()) << "illegal data offset or size";
- return false;
- }
- return true;
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/raw_data.h b/o3d/import/cross/raw_data.h
deleted file mode 100644
index 9f433cc..0000000
--- a/o3d/import/cross/raw_data.h
+++ /dev/null
@@ -1,121 +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 implementation for raw-data which is used
-// by the progressive streaming archive system
-//
-// A RawData object is just a pointer to some memory of a given length.
-// This data may represent string data, image data, audio data, etc..
-
-#ifndef O3D_IMPORT_CROSS_RAW_DATA_H_
-#define O3D_IMPORT_CROSS_RAW_DATA_H_
-
-#include "base/scoped_ptr.h"
-#include "core/cross/param_object.h"
-
-namespace o3d {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class RawData : public ParamObject {
- public:
- typedef SmartPointer<RawData> Ref;
-
- static RawData::Ref Create(ServiceLocator* service_locator,
- const String &uri,
- const void *data,
- size_t length);
-
- static RawData::Ref CreateFromFile(ServiceLocator* service_locator,
- const String &uri,
- const String& filename);
-
- // Creates a RawData object, taking as input a string containing a
- // data URL.
- static RawData::Ref CreateFromDataURL(ServiceLocator* service_locator,
- const String& data_url);
-
- virtual ~RawData();
-
- const uint8 *GetData() const;
-
- template <typename T>
- const T* GetDataAs(size_t offset) const {
- return reinterpret_cast<const T*>(GetData() + offset);
- };
-
- size_t GetLength() const { return length_; }
-
- String StringValue() const;
-
- const String& uri() const { return uri_; }
- void set_uri(const String& uri) { uri_ = uri; }
-
- // Historically this wrote the data out to a temp file and deleted it from
- // memory, but that functionality was removed due to security concerns. In any
- // event, a RawData object that is big enough to be worth removing from memory
- // will occupy multiple complete pages which won't be in the process's working
- // set, so the OS will eventually remove it from the physical memory anyway
- // and bring it back in when we next access it.
- void Flush() {}
-
- // deletes the data
- void Discard();
-
- bool IsOffsetLengthValid(size_t offset, size_t length) const;
-
- private:
- String uri_;
- scoped_array<uint8> data_;
- size_t length_;
- bool allow_string_value_;
-
- RawData(ServiceLocator* service_locator,
- const String &uri,
- const void *data,
- size_t length);
-
- bool SetFromFile(const String& filename);
-
- // Decodes data from a data URL and stores that data in this
- // RawData object. Returns false on error, true otherwise
- bool SetFromDataURL(const String& data_url);
-
- friend class IClassManager;
- friend class Pack;
-
- O3D_DECL_CLASS(RawData, ParamObject)
- DISALLOW_COPY_AND_ASSIGN(RawData);
-};
-
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_RAW_DATA_H_
diff --git a/o3d/import/cross/raw_data_test.cc b/o3d/import/cross/raw_data_test.cc
deleted file mode 100644
index fe0f212..0000000
--- a/o3d/import/cross/raw_data_test.cc
+++ /dev/null
@@ -1,285 +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 functionality of the RawData class
-
-#include "tests/common/win/testing_common.h"
-#include "utils/cross/file_path_utils.h"
-#include "base/file_path.h"
-#include "base/file_util.h"
-#include "core/cross/error.h"
-#include "core/cross/error_status.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/raw_data.h"
-
-using file_util::OpenFile;
-using file_util::CloseFile;
-using file_util::GetFileSize;
-
-namespace o3d {
-
-namespace {
-
-// Checks if an error has occured on the client then clears the error.
-bool CheckErrorExists(IErrorStatus* error_status) {
- bool have_error = !error_status->GetLastError().empty();
- error_status->ClearLastError();
- return have_error;
-}
-
-} // anonymous namespace
-
-// Test fixture for RawData testing.
-class RawDataTest : public testing::Test {
- protected:
- RawDataTest()
- : error_status_(g_service_locator) {
- }
-
- IErrorStatus* error_status() { return &error_status_; }
-
- private:
- ErrorStatus error_status_;
-};
-
-// Test RawData
-TEST_F(RawDataTest, Basic) {
- String uri("test_filename");
- const int kBufferLength = 1024;
-
- // Create a buffer and initialize it will some values
- MemoryBuffer<uint8> buffer(kBufferLength);
- for (int i = 0; i < kBufferLength; i++) {
- buffer[i] = i % 256;
- }
-
-
- RawData::Ref ref = RawData::Create(g_service_locator,
- uri,
- buffer,
- buffer.GetLength() );
- RawData *raw_data = ref;
-
- // Check that it got created.
- ASSERT_TRUE(raw_data != NULL);
-
- // Now, let's make sure it got the data length correct
- ASSERT_EQ(raw_data->GetLength(), buffer.GetLength());
-
- // Check the contents are correct
- ASSERT_EQ(0, memcmp(raw_data->GetData(), buffer, buffer.GetLength()));
-
- // Check that the uri is correct
- ASSERT_EQ(raw_data->uri(), uri);
-}
-
-TEST_F(RawDataTest, CreateFromFile) {
- String uri("test_filename");
- String filename = *g_program_path + "/bitmap_test/tga-256x256-24bit.tga";
- RawData::Ref ref = RawData::CreateFromFile(g_service_locator,
- uri,
- filename);
- ASSERT_FALSE(ref.IsNull());
- FilePath filepath = UTF8ToFilePath(filename);
- FILE *file = OpenFile(filepath, "rb");
- ASSERT_TRUE(file != NULL);
- int64 file_size64;
- ASSERT_TRUE(GetFileSize(filepath, &file_size64));
- size_t file_length = static_cast<size_t>(file_size64);
- ASSERT_TRUE(file_length > 0);
- scoped_array<uint8> data(new uint8[file_length]);
- ASSERT_EQ(fread(data.get(), file_length, 1, file), 1U);
- CloseFile(file);
-
- ASSERT_EQ(file_length, ref->GetLength());
- ASSERT_EQ(0, memcmp(ref->GetData(), data.get(), file_length));
-}
-
-TEST_F(RawDataTest, CreateFromFileFail) {
- String uri("test_filename");
- String filename = *g_program_path + "/bitmap_test/non-existent-file.foo";
- RawData::Ref ref = RawData::CreateFromFile(g_service_locator,
- uri,
- filename);
- ASSERT_TRUE(ref.IsNull());
-}
-
-TEST_F(RawDataTest, CreateFromFileStringValue) {
- String uri("test_filename");
- String filename = *g_program_path + "/unittest_data/fur.fx";
- RawData::Ref ref = RawData::CreateFromFile(g_service_locator,
- uri,
- filename);
- ASSERT_FALSE(ref.IsNull());
- EXPECT_TRUE(ref->GetLength() > 0);
- EXPECT_FALSE(CheckErrorExists(error_status()));
- // We should NOT be able to get a string value from an individually
- // loaded RawData.
- EXPECT_TRUE(ref->StringValue().empty());
- EXPECT_TRUE(CheckErrorExists(error_status()));
-}
-
-namespace {
-
-struct TestData {
- const uint8* data;
- size_t length;
- bool valid;
- size_t offset;
-};
-
-} // anonymous namespace
-
-TEST_F(RawDataTest, StringValue) {
- // A BOM in the front (valid)
- static const uint8 data_0[] = {
- 0xEF,
- 0xBB,
- 0xBF,
- 0x65,
- 0x66,
- 0x65,
- 0x67,
- };
-
- // A null in the string (invalid)
- static const uint8 data_1[] = {
- 0x65,
- 0x66,
- 0x00,
- 0x67,
- };
-
- // A valid string
- static const uint8 data_2[] = {
- 0x65,
- 0x66,
- 0x65,
- 0x67,
- };
-
- // Null at the end (invalid)
- static const uint8 data_3[] = {
- 0x65,
- 0x66,
- 0x65,
- 0x67,
- 0x00,
- };
-
- // A badly formed utf-8 like string (invalid)
- static const uint8 data_4[] = {
- 0xE9,
- 0xBE,
- 0xE0,
- };
-
- // A badly formed utf-8 like string (invalid)
- static const uint8 data_5[] = {
- 0xC1,
- 0x65,
- 0x66,
- };
-
- // A badly formed utf-8 like string (invalid)
- static const uint8 data_6[] = {
- 0x65,
- 0x66,
- 0xF4,
- };
-
- // A valid multi-byte utf-8 string (valid)
- static const uint8 data_7[] = {
- 0xE9,
- 0xBE,
- 0x8D,
- 0xF0,
- 0x90,
- 0x90,
- 0x92,
- };
-
- // A UTF-8 but in D800-DFFF range
- static const uint8 data_8[] = {
- 0xED,
- 0xA0,
- 0xA1,
- };
-
- TestData test_datas[] = {
- { &data_0[0], arraysize(data_0), true, 3, },
- { &data_1[0], arraysize(data_1), false, },
- { &data_2[0], arraysize(data_2), true, },
- { &data_3[0], arraysize(data_3), false, },
- { &data_4[0], arraysize(data_4), false, },
- { &data_5[0], arraysize(data_5), false, },
- { &data_6[0], arraysize(data_6), false, },
- { &data_7[0], arraysize(data_7), true, },
- { &data_8[0], arraysize(data_8), false, },
- };
-
- for (unsigned ii = 0; ii < arraysize(test_datas); ++ii) {
- TestData& test_data = test_datas[ii];
- RawData::Ref raw_data = RawData::Create(g_service_locator,
- "test",
- test_data.data,
- test_data.length);
- String str(raw_data->StringValue());
- if (test_data.valid) {
- size_t test_length = test_data.length - test_data.offset;
- const char* test_string = reinterpret_cast<const char*>(test_data.data +
- test_data.offset);
- EXPECT_EQ(str.size(), test_length);
- EXPECT_EQ(str.compare(0, test_length, test_string, test_length), 0);
- } else {
- EXPECT_TRUE(str.empty());
- }
- }
-}
-
-TEST_F(RawDataTest, CreateFromDataURL) {
- RawData::Ref ref = RawData::CreateFromDataURL(g_service_locator,
- "data:;base64,YWJj");
- ASSERT_FALSE(ref.IsNull());
- EXPECT_EQ(3u, ref->GetLength());
- EXPECT_FALSE(CheckErrorExists(error_status()));
- EXPECT_EQ(0, memcmp(ref->GetData(), "abc", 3));
-}
-
-TEST_F(RawDataTest, CreateFromDataURLFail) {
- RawData::Ref ref = RawData::CreateFromDataURL(g_service_locator,
- "data:;base64,Y");
- EXPECT_TRUE(ref.IsNull());
- EXPECT_TRUE(CheckErrorExists(error_status()));
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/tar_generator.cc b/o3d/import/cross/tar_generator.cc
deleted file mode 100644
index 6c21ac0..0000000
--- a/o3d/import/cross/tar_generator.cc
+++ /dev/null
@@ -1,242 +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 "import/cross/memory_buffer.h"
-#include "import/cross/tar_generator.h"
-
-using std::string;
-
-#if defined(OS_WIN)
- #define snprintf _snprintf
-#endif
-
-namespace o3d {
-
-const int kMaxFilenameSizeOldFormat = 100;
-
-const int kFileNameOffset = 0;
-const int kFileModeOffset = 100;
-const int kUserIDOffset = 108;
-const int kGroupIDOffset = 116;
-const int kFileSizeOffset = 124;
-const int kModifyTimeOffset = 136;
-const int kHeaderCheckSumOffset = 148;
-const int kLinkFlagOffset = 156;
-const int kMagicOffset = 257;
-const int kUserNameOffset = 265;
-const int kGroupNameOffset = 297;
-// This is the name GNU Tar puts in a header block if the block is really
-// a long filename block.
-static const char* kLongLink = "././@LongLink";
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool TarGenerator::AddFile(const String &file_name, size_t file_size) {
- if (!AddDirectoryEntryIfNeeded(file_name)) {
- return false;
- }
- return AddEntry(file_name, file_size, false);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool TarGenerator::AddDirectory(const String &file_name) {
- return AddEntry(file_name, 0, true);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// We keep a map so we add a particular directory entry only once
-bool TarGenerator::AddDirectoryEntryIfNeeded(const String &file_name) {
- string::size_type index = file_name.find_last_of('/');
-
- if (index != string::npos) {
- String dir_name = file_name.substr(0, index + 1); // keep the '/' at end
- if (!directory_map_[dir_name]) {
- directory_map_[dir_name] = true;
- return AddDirectory(dir_name);
- }
- }
- return true;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-
-void TarGenerator::WriteHeader(const String& file_name,
- size_t file_size,
- char type,
- int mode,
- int user_id,
- int group_id,
- int mod_time) {
- // first write out last data block from last file (if any)
- FlushDataBuffer(true);
-
- // next fill out a tar header
- MemoryBuffer<uint8> header(TAR_HEADER_SIZE); // initializes header to zeroes
-
- // leave room for NULL-termination
- uint8 *h = header;
- char *p = reinterpret_cast<char*>(h);
-
- // File name
- strncpy(p, file_name.c_str(), kMaxFilenameSizeOldFormat - 1);
-
- // File mode
- ::snprintf(p + kFileModeOffset, 8, "%07o", mode);
-
- // UserID
- ::snprintf(p + kUserIDOffset, 8, "%07o", user_id);
-
- // GroupID
- ::snprintf(p + kGroupIDOffset, 8, "%07o", group_id);
-
- // File size
- ::snprintf(p + kFileSizeOffset, 12, "%011o",
- static_cast<unsigned int>(file_size));
-
- // Modification time
- // TODO: write the correct current time here...
- ::snprintf(p + kModifyTimeOffset, 12, "%07o", mod_time);
-
- // Initialize Header checksum so check sum can be computed
- // by ComputeCheckSum() which will fill in the value here
- ::memset(p + kHeaderCheckSumOffset, 32, 8);
-
- // We only support ordinary files,directories and long filename blogs, which
- // is fine for our use case
- p[kLinkFlagOffset] = type;
-
- // Magic offset
- ::snprintf(p + kMagicOffset, 8, "ustar ");
-
- // User name
- ::snprintf(p + kUserNameOffset, 32, "guest");
-
- // Group name
- ::snprintf(p + kGroupNameOffset, 32, "staff");
-
- // This has to be done at the end
- ComputeCheckSum(header);
-
- if (callback_client_) {
- MemoryReadStream stream(header, TAR_HEADER_SIZE);
- callback_client_->ProcessBytes(&stream, TAR_HEADER_SIZE);
- }
-}
-
-
-bool TarGenerator::AddEntry(const String &file_name,
- size_t file_size,
- bool is_directory) {
- // If filename is longer 99 chars, use the GNU format to write out a longer
- // filename.
- if (file_name.size() >= static_cast<unsigned>(kMaxFilenameSizeOldFormat)) {
- WriteHeader(kLongLink,
- file_name.size(),
- 'L',
- 0,
- 0,
- 0,
- 0);
-
- MemoryReadStream stream(
- reinterpret_cast<const uint8*>(file_name.c_str()), file_name.size());
- AddFileBytes(&stream, file_name.size());
- }
-
- WriteHeader(file_name,
- file_size,
- is_directory ? '5' : '0',
- is_directory ? 0755 : 0644,
- 0765,
- 0204,
- 011131753141);
-
- return true;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void TarGenerator::ComputeCheckSum(uint8 *header) {
- unsigned int checksum = 0;
- for (int i = 0; i < TAR_HEADER_SIZE; ++i) {
- checksum += header[i];
- }
- snprintf(reinterpret_cast<char*>(header + kHeaderCheckSumOffset),
- 8, "%06o%c%c", checksum, 0, 0);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-int TarGenerator::AddFileBytes(MemoryReadStream *stream, size_t n) {
- if (callback_client_) {
- FlushDataBuffer(false); // flush any old data sitting around
-
- // we'll directly write as much of the data as we can, writing full blocks
- int nblocks = n / TAR_BLOCK_SIZE;
- size_t direct_bytes_to_write = nblocks * TAR_BLOCK_SIZE;
- if (direct_bytes_to_write > 0) {
- callback_client_->ProcessBytes(stream, direct_bytes_to_write);
- }
-
- // now, buffer the remainder (less than TAR_BLOCK_SIZE)
- size_t remainder = n - direct_bytes_to_write;
-
- const uint8 *p = stream->GetDirectMemoryPointer();
- data_buffer_stream_.Write(p, remainder);
- stream->Skip(remainder);
- }
-
- return 0;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void TarGenerator::FlushDataBuffer(bool flush_padding_zeroes) {
- size_t buffered_bytes = data_buffer_stream_.GetStreamPosition();
- if (buffered_bytes > 0 && callback_client_) {
- // write out the complete data block (which may be zero padded at the end)
- size_t bytes_to_flush =
- flush_padding_zeroes ? TAR_BLOCK_SIZE : buffered_bytes;
-
- MemoryReadStream stream(data_block_buffer_, bytes_to_flush);
- callback_client_->ProcessBytes(&stream, bytes_to_flush);
-
- // get ready to start buffering next data block
- data_block_buffer_.Clear();
- data_buffer_stream_.Seek(0);
- }
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void TarGenerator::Close(bool success) {
- FlushDataBuffer(true);
- callback_client_->Close(success);
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/tar_generator.h b/o3d/import/cross/tar_generator.h
deleted file mode 100644
index 7bb0ac4..0000000
--- a/o3d/import/cross/tar_generator.h
+++ /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.
- */
-
-//
-// TarGenerator generates a tar byte stream (uncompressed).
-//
-// A tar byte stream consists of a series of file headers, each followed by
-// the actual file data. Each file header starts on a block-aligned offset
-// with the blocksize 512. The start of data for each file is also
-// block-aligned. Zero-padding is added at the end of the file's data,
-// if necessary to block-align...
-//
-// The normal usage is to call the AddFile() method for each file to add to the
-// archive, then make one or more calls to AddFileBytes() to give the file's
-// data. Then repeat this sequence for each file to be added. When done,
-// call Finalize().
-
-#ifndef O3D_IMPORT_CROSS_TAR_GENERATOR_H_
-#define O3D_IMPORT_CROSS_TAR_GENERATOR_H_
-
-#include <map>
-#include <string>
-#include "base/basictypes.h"
-#include "core/cross/types.h"
-#include "import/cross/iarchive_generator.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-
-namespace o3d {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class TarGenerator : public IArchiveGenerator {
- public:
- explicit TarGenerator(StreamProcessor *callback_client)
- : callback_client_(callback_client),
- data_block_buffer_(TAR_BLOCK_SIZE), // initialized to zeroes
- data_buffer_stream_(data_block_buffer_, TAR_BLOCK_SIZE) {}
-
- // Call AddFile() for each file entry, followed by calls to AddFileBytes()
- // for the file's data. Returns true on success.
- virtual bool AddFile(const String &file_name, size_t file_size);
-
- // Call to "push" bytes to be processed - our client will get called back
- // with the byte stream, with files rounded up to the nearest block size
- // (with zero padding)
- virtual int AddFileBytes(MemoryReadStream *stream, size_t n);
-
- // Must call this after all files and file data have been written
- virtual void Close(bool success);
-
- private:
- // Returns true on success.
- bool AddEntry(const String &file_name,
- size_t file_size,
- bool is_directory);
-
- // Returns true on success.
- bool AddDirectory(const String &file_name);
-
- // Returns true on success.
- bool AddDirectoryEntryIfNeeded(const String &file_name);
-
- // Checksum for each header
- void ComputeCheckSum(uint8 *header);
-
- // Writes a head block.
- void WriteHeader(const String& filename,
- size_t file_size,
- char type,
- int mode,
- int user_id,
- int group_id,
- int mod_time);
-
- // flushes buffered file data to the client callback
- // if |flush_padding_zeroes| is |true| then flush a complete block
- // with zero padding even if less was buffered
- void FlushDataBuffer(bool flush_padding_zeroes);
-
- enum {TAR_HEADER_SIZE = 512};
- enum {TAR_BLOCK_SIZE = 512};
-
- StreamProcessor *callback_client_;
-
- // Buffers file data here - file data is in multiples of TAR_BLOCK_SIZE
- MemoryBuffer<uint8> data_block_buffer_;
- MemoryWriteStream data_buffer_stream_;
-
- // We use DirectoryMap to keep track of which directories we've already
- // written out headers for. The client doesn't need to explicitly
- // add the directory entries. Instead, the files will be stripped to their
- // base path and entries added for the directories as needed...
- struct StrCmp {
- bool operator()(const std::string &s1, const std::string &s2) const {
- return strcmp(s1.c_str(), s2.c_str()) < 0;
- }
- };
-
- typedef std::map<const std::string, bool, StrCmp> DirectoryMap;
-
- DirectoryMap directory_map_;
-
- DISALLOW_COPY_AND_ASSIGN(TarGenerator);
-};
-
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_TAR_GENERATOR_H_
diff --git a/o3d/import/cross/tar_generator_test.cc b/o3d/import/cross/tar_generator_test.cc
deleted file mode 100644
index 1659e98..0000000
--- a/o3d/import/cross/tar_generator_test.cc
+++ /dev/null
@@ -1,445 +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 "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-#include "import/cross/tar_generator.h"
-#include "tests/common/win/testing_common.h"
-#include "tests/common/cross/test_utils.h"
-
-namespace o3d {
-
-using o3d::StreamProcessor;
-using o3d::MemoryReadStream;
-using o3d::MemoryWriteStream;
-using o3d::TarGenerator;
-
-class TarGeneratorTest : public testing::Test {
-};
-
-const int kBlockSize = 512;
-
-const int kMaxFilenameSize = 100;
-
-const int kFileNameOffset = 0;
-const int kFileModeOffset = 100;
-const int kUserIDOffset = 108;
-const int kGroupIDOffset = 116;
-const int kFileSizeOffset = 124;
-const int kModifyTimeOffset = 136;
-const int kHeaderCheckSumOffset = 148;
-const int kLinkFlagOffset = 156;
-const int kMagicOffset = 257;
-const int kUserNameOffset = 265;
-const int kGroupNameOffset = 297;
-
-const char *kLongLink = "././@LongLink";
-const char *kDirName1 = "test/apples/";
-const char *kDirName2 = "test/oranges/";
-const char *kFileName1 = "test/apples/file1";
-const char *kFileName2 = "test/apples/file2";
-const char *kFileName3 = "test/oranges/file3";
-const char *kFileName4 =
- "ThisIsAFilenameLongerThen100CharsThisIsAFilenameLongerThen100Chars"
- "ThisIsAFilenameLongerThen100CharsThisIsAFilenameLongerThen100Chars";
-
-// The first file is less than one block in size
-const char *kFileContents1 =
- "The cellphone is the world most ubiquitous computer.\n"
- "The four billion cellphones in use around the globe carry personal\n"
- "information, provide access to the Web and are being used more and more\n"
- "to navigate the real world. And as cellphones change how we live,\n"
- "computer scientists say, they are also changing\n"
- "how we think about information\n";
-
-// The 2nd file takes two blocks
-const char *kFileContents2 =
- "From Hong Kong to eastern Europe to Wall Street, financial gloom was\n"
- "everywhere on Tuesday.\n"
- "Stock markets around the world staggered lower. In New York,\n"
- "the Dow fell more than 3 percent, coming within sight of its worst\n"
- "levels since the credit crisis erupted. Financial shares were battered.\n"
- "And rattled investors clamored to buy rainy-day investments like gold\n"
- "and Treasury debt. It was a global wave of selling spurred by rising\n"
- "worries about how banks, automakers entire countries would fare\n"
- "in a deepening global downturn.\n"
- "'Nobody believes it&'s going get better yet,' said Howard Silverblatt,\n"
- "senior index analyst at Standard & Poors. 'Do you see that light at\n"
- "the end of the tunnel? Any kind of light? Right now, it's not there'\n"
- "yet.\n";
-
-// The 3rd file takes one block
-const char *kFileContents3 = "nothing much here...\n";
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Receives the tar bytestream from the TarGenerator.
-// We validate the bytestream as it comes in...
-//
-class CallbackClient : public StreamProcessor {
- public:
- // states for state machine, with each state representing one
- // received block of the tar stream.
- // The blocks can be either headers (for directories and files)
- // or data blocks (zero padded at the end to make a full block)
- enum ValidationState {
- VALIDATE_DIRECTORY_HEADER1, // header 1 is directory so no file data
- VALIDATE_FILE_HEADER1,
- VALIDATE_FILE_DATA1, // 1st file takes one block
- VALIDATE_FILE_HEADER2,
- VALIDATE_FILE_DATA2_BLOCK1, // 2nd file takes two blocks
- VALIDATE_FILE_DATA2_BLOCK2,
- VALIDATE_DIRECTORY_HEADER2, // 3rd file is in another directory
- VALIDATE_FILE_HEADER3,
- VALIDATE_FILE_DATA3,
- VALIDATE_FILE_LONGNAME_HEADER4, // 4th file has a long name.
- VALIDATE_FILE_LONGNAME_DATA4,
- VALIDATE_FILE_HEADER4,
- VALIDATE_FILE_DATA4,
- FINISHED
- };
-
- CallbackClient()
- : state_(VALIDATE_DIRECTORY_HEADER1),
- total_bytes_received_(0),
- memory_block_(kBlockSize),
- write_stream_(memory_block_, kBlockSize),
- closed_(false),
- success_(false) {
- }
-
- virtual Status ProcessBytes(MemoryReadStream *stream,
- size_t bytes_to_process);
-
- virtual void Close(bool success) {
- closed_ = true;
- success_ = success;
- }
-
- size_t GetTotalBytesReceived() { return total_bytes_received_; }
- int GetState() { return state_; }
-
- bool closed() const {
- return closed_;
- }
-
- bool success() const {
- return success_;
- }
-
- private:
- bool IsOctalDigit(uint8 c);
- bool IsOctalString(uint8 *p);
- unsigned int ComputeCheckSum(uint8 *header);
-
- void ValidateData(uint8 *header, const char *file_contents);
-
- void ValidateHeader(uint8 *header,
- const char *file_name,
- size_t file_length);
-
- // For debugging
- void DumpMemoryBlock(uint8 *block);
-
- int state_;
- size_t total_bytes_received_;
- MemoryBuffer<uint8> memory_block_;
- MemoryWriteStream write_stream_;
- bool closed_;
- bool success_;
-};
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-StreamProcessor::Status CallbackClient::ProcessBytes(MemoryReadStream *stream,
- size_t bytes_to_process) {
- total_bytes_received_ += bytes_to_process;
-
- while (bytes_to_process > 0) {
- size_t remaining = write_stream_.GetRemainingByteCount();
-
- size_t bytes_this_time =
- bytes_to_process < remaining ? bytes_to_process : remaining;
-
- const uint8 *p = stream->GetDirectMemoryPointer();
- stream->Skip(bytes_this_time);
-
- write_stream_.Write(p, bytes_this_time);
-
- // our block buffer is full, so validate it according to our state
- // machine
- if (write_stream_.GetRemainingByteCount() == 0) {
- // DumpMemoryBlock(memory_block_); // uncomment for debugging
-
- switch (state_) {
- case VALIDATE_DIRECTORY_HEADER1:
- ValidateHeader(memory_block_, kDirName1, 0);
- break;
-
- case VALIDATE_FILE_HEADER1:
- ValidateHeader(memory_block_, kFileName1, strlen(kFileContents1));
- break;
-
- case VALIDATE_FILE_DATA1:
- ValidateData(memory_block_, kFileContents1);
- break;
-
- case VALIDATE_FILE_HEADER2:
- ValidateHeader(memory_block_, kFileName2, strlen(kFileContents2));
- break;
-
- case VALIDATE_FILE_DATA2_BLOCK1:
- // file2 data is larger than one one block, so we'll verify
- // the two blocks are correct
- ValidateData(memory_block_, kFileContents2);
- break;
-
- case VALIDATE_FILE_DATA2_BLOCK2:
- ValidateData(memory_block_, kFileContents2 + kBlockSize);
- break;
-
- case VALIDATE_DIRECTORY_HEADER2:
- ValidateHeader(memory_block_, kDirName2, 0);
- break;
-
- case VALIDATE_FILE_HEADER3:
- ValidateHeader(memory_block_, kFileName3, strlen(kFileContents3));
- break;
-
- case VALIDATE_FILE_DATA3:
- ValidateData(memory_block_, kFileContents3);
- break;
-
- case VALIDATE_FILE_LONGNAME_HEADER4:
- ValidateHeader(memory_block_, kLongLink, strlen(kFileName4));
- break;
-
- case VALIDATE_FILE_LONGNAME_DATA4:
- ValidateData(memory_block_, kFileName4);
- break;
-
- case VALIDATE_FILE_HEADER4: {
- String first_99_chars(kFileName4, 99);
- ValidateHeader(memory_block_, first_99_chars.c_str(),
- strlen(kFileContents3));
- break;
- }
-
- case VALIDATE_FILE_DATA4:
- ValidateData(memory_block_, kFileContents3);
- break;
-
- case FINISHED:
- break;
- }
-
- // Advance to the next state
- ++state_;
-
- // So next time we write, we start at beginning of buffer
- write_stream_.Seek(0);
- }
-
- bytes_to_process -= bytes_this_time;
- }
-
- return IN_PROGRESS;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool CallbackClient::IsOctalDigit(uint8 c) {
- return (c >= '0' && c <= '7');
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool CallbackClient::IsOctalString(uint8 *p) {
- while (IsOctalDigit(*p)) ++p;
- return *p == 0;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-unsigned int CallbackClient::ComputeCheckSum(uint8 *header) {
- unsigned int checksum = 0;
- for (int i = 0; i < kBlockSize; ++i) {
- uint8 value = header[i];
- if (i >= kHeaderCheckSumOffset && i < kHeaderCheckSumOffset + 8) {
- value = 32; // treat checksum itself as ' '
- }
- checksum += value;
- }
- return checksum;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// for now |file_contents| must be less than a block size...
-void CallbackClient::ValidateData(uint8 *header,
- const char *file_contents) {
- // only check up to one block size worth of data
- int zero_pad_start_index = strlen(file_contents);
- if (zero_pad_start_index > kBlockSize) zero_pad_start_index = kBlockSize;
-
- if (zero_pad_start_index <= kBlockSize) {
- // file data must match
- uint8 *p = memory_block_;
- EXPECT_EQ(0, strncmp(file_contents, (const char*)p, kBlockSize));
-
- // check that zero padding is there
- bool zero_padding_good = true;
- for (int i = zero_pad_start_index; i < kBlockSize; ++i) {
- if (memory_block_[i] != 0) {
- zero_padding_good = false;
- break;
- }
- }
- EXPECT_TRUE(zero_padding_good);
- }
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void CallbackClient::ValidateHeader(uint8 *header,
- const char *file_name,
- size_t file_length) {
- // Validate file name
- EXPECT_EQ(0,
- strcmp(reinterpret_cast<char*>(header) + kFileNameOffset,
- file_name));
-
- // Validate length
- int length_in_header;
- sscanf((const char*)header + kFileSizeOffset, "%o", &length_in_header);
- EXPECT_EQ(file_length, static_cast<unsigned>(length_in_header));
-
-
- EXPECT_EQ(0, header[kMaxFilenameSize - 1]);
-
- EXPECT_TRUE(IsOctalString(header + kFileModeOffset));
- EXPECT_EQ(0, header[kFileModeOffset + 7]);
-
- EXPECT_TRUE(IsOctalString(header + kUserIDOffset));
- EXPECT_EQ(0, header[kUserIDOffset + 7]);
-
- EXPECT_TRUE(IsOctalString(header + kGroupIDOffset));
- EXPECT_EQ(0, header[kGroupIDOffset + 7]);
-
- EXPECT_TRUE(IsOctalString(header + kFileSizeOffset));
- EXPECT_EQ(0, header[kFileSizeOffset + 11]);
-
- EXPECT_TRUE(IsOctalString(header + kModifyTimeOffset));
- EXPECT_EQ(0, header[kModifyTimeOffset + 11]);
-
- EXPECT_TRUE(IsOctalString(header + kHeaderCheckSumOffset));
- EXPECT_EQ(0, header[kHeaderCheckSumOffset + 6]);
-
- // For now we only have directories '5' or normal files '0'
- int link_flag = header[kLinkFlagOffset];
- EXPECT_TRUE(link_flag == '0' || link_flag == '5' || link_flag == 'L');
-
- EXPECT_EQ(0, strcmp((const char*)header + kMagicOffset, "ustar "));
-
- EXPECT_EQ(0, header[kUserNameOffset + 31]);
- EXPECT_EQ(0, header[kGroupNameOffset + 31]);
-
- // Validate checksum
- int checksum = ComputeCheckSum(header);
- int header_checksum;
- sscanf((const char*)header + kHeaderCheckSumOffset, "%o", &header_checksum);
-
- EXPECT_EQ(checksum, header_checksum);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// For debugging purposes
-void CallbackClient::DumpMemoryBlock(uint8 *block) {
- for (int i = 0; i < kBlockSize; ++i) {
- if ((i % 16) == 0) printf("\n");
- char c = block[i];
- if (c == 0) {
- c = '.';
- }
- printf("%c", c);
- }
- printf("\n");
-}
-
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Creates a tar file with three files in two directories
-//
-TEST_F(TarGeneratorTest, CreateSimpleArchive) {
- CallbackClient client;
- TarGenerator generator(&client);
-
- const int kFileLength1 = strlen(kFileContents1);
- const int kFileLength2 = strlen(kFileContents2);
- const int kFileLength3 = strlen(kFileContents3);
-
- EXPECT_TRUE(generator.AddFile(kFileName1, kFileLength1));
- MemoryReadStream file1_stream(reinterpret_cast<const uint8*>(kFileContents1),
- kFileLength1);
- generator.AddFileBytes(&file1_stream, kFileLength1);
-
- EXPECT_TRUE(generator.AddFile(kFileName2, kFileLength2));
- MemoryReadStream file2_stream(reinterpret_cast<const uint8*>(kFileContents2),
- kFileLength2);
- generator.AddFileBytes(&file2_stream, kFileLength2);
-
- EXPECT_TRUE(generator.AddFile(kFileName3, kFileLength3));
- MemoryReadStream file3_stream(reinterpret_cast<const uint8*>(kFileContents3),
- kFileLength3);
- generator.AddFileBytes(&file3_stream, kFileLength3);
- EXPECT_TRUE(generator.AddFile(kFileName4, kFileLength3));
- MemoryReadStream file4_stream(reinterpret_cast<const uint8*>(kFileContents3),
- kFileLength3);
- generator.AddFileBytes(&file4_stream, kFileLength3);
-
- generator.Close(true);
-
- // Verify that the tar byte stream produced is exactly divisible by
- // the block size
- size_t bytes_received = client.GetTotalBytesReceived();
- EXPECT_EQ(0U, bytes_received % kBlockSize);
-
- // Make sure the state machine is in the expected state
- EXPECT_EQ(CallbackClient::FINISHED, client.GetState());
-
- EXPECT_TRUE(client.closed());
- EXPECT_TRUE(client.success());
-}
-
-TEST_F(TarGeneratorTest, PassesThroughFailure) {
- CallbackClient client;
- TarGenerator generator(&client);
- generator.Close(false);
-
- EXPECT_TRUE(client.closed());
- EXPECT_FALSE(client.success());
-}
-
-} // namespace
diff --git a/o3d/import/cross/tar_processor.cc b/o3d/import/cross/tar_processor.cc
deleted file mode 100644
index b4c268e..0000000
--- a/o3d/import/cross/tar_processor.cc
+++ /dev/null
@@ -1,177 +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.
- */
-
-//
-// TarProcessor processes a tar byte stream (uncompressed).
-
-#include "base/logging.h"
-#include "import/cross/tar_processor.h"
-
-namespace o3d {
-
-static const int kFileSizeOffset = 124;
-static const int kLinkFlagOffset = 156;
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-StreamProcessor::Status TarProcessor::ProcessBytes(MemoryReadStream *stream,
- size_t n) {
- // Keep processing the byte-stream until we've consumed all we're given
- //
- size_t bytes_to_consume = n;
-
- while (bytes_to_consume > 0) {
- // First see if we have any more header bytes to read
- if (header_bytes_read_ < TAR_HEADER_SIZE) {
- // Read header bytes
- size_t header_bytes_remaining = TAR_HEADER_SIZE - header_bytes_read_;
- size_t bytes_to_read = std::min(bytes_to_consume, header_bytes_remaining);
- size_t bytes_read =
- stream->Read(reinterpret_cast<uint8*>(header_ + header_bytes_read_),
- bytes_to_read);
- if (bytes_read != bytes_to_read) {
- return FAILURE;
- }
-
- header_bytes_read_ += bytes_to_read;
- bytes_to_consume -= bytes_to_read;
-
- if (header_bytes_read_ == TAR_HEADER_SIZE) {
- // The tar format stupidly represents size_t values as octal strings!!
- unsigned int file_size = 0u;
- sscanf(header_ + kFileSizeOffset, "%o", &file_size);
-
- // Check if it's a long filename
- char type = header_[kLinkFlagOffset];
- if (type == 'L') {
- getting_filename_ = true;
- // We should pick some size that's too large.
- if (file_size > 1024) {
- return FAILURE;
- }
- } else {
- getting_filename_ = false;
- const char *filename = (const char *)header_;
- if (!file_name_.empty()) {
- filename = file_name_.c_str();
- }
-
- // Only callback client if this is a "real" header
- // (filename is not NULL)
- // Extra zero-padding can be added by the gzip compression
- // (at end of archive), so ignore these ones.
- //
- // Also, ignore entries for directories (which have zero size)
- if (header_[0] != 0 && file_size > 0) {
- ArchiveFileInfo info(filename, file_size);
- callback_client_->ReceiveFileHeader(info);
- } else if (header_[0] == 0) {
- // If filename is empty due to zero-padding then file size
- // should also be zero.
- if (file_size != 0)
- return FAILURE;
- }
- }
-
- // Round filesize up to nearest block size
- file_bytes_to_read_ =
- (file_size + TAR_BLOCK_SIZE - 1) & ~(TAR_BLOCK_SIZE - 1);
-
- // Our client doesn't want to be bothered with the block padding,
- // so only send him the actual file bytes
- client_file_bytes_to_read_ = file_size;
-
- // Clear the file_name_ so we don't use it next time.
- file_name_.clear();
- }
- }
-
- if (bytes_to_consume > 0) {
- // Looks like we have some left-over bytes past the header
- // -- size_terpret as file bytes
- if (client_file_bytes_to_read_ > 0) {
- // Callback to client with some file data
-
- // Use a copy of the stream in case the client doesn't read
- // the amount they're supposed to
- MemoryReadStream client_read_stream(*stream);
-
- size_t client_bytes_this_time =
- std::min(bytes_to_consume, client_file_bytes_to_read_);
-
- if (getting_filename_) {
- String name_piece(
- client_read_stream.GetDirectMemoryPointerAs<const char>(),
- client_bytes_this_time);
- client_read_stream.Skip(client_bytes_this_time);
- file_name_ += name_piece;
- } else {
- if (!callback_client_->ReceiveFileData(&client_read_stream,
- client_bytes_this_time)) {
- return FAILURE;
- }
- }
-
- client_file_bytes_to_read_ -= client_bytes_this_time;
- file_bytes_to_read_ -= client_bytes_this_time;
-
- // Advance stream the amount the client should have consumed
- stream->Skip(client_bytes_this_time);
-
- bytes_to_consume -= client_bytes_this_time;
- }
-
- // Now, check if we have any padding bytes (up to block size)
- // past the file data
- if (bytes_to_consume > 0) {
- size_t bytes_to_skip = std::min(bytes_to_consume, file_bytes_to_read_);
- stream->Skip(bytes_to_skip);
- file_bytes_to_read_ -= bytes_to_skip;
- bytes_to_consume -= bytes_to_skip;
- }
-
- if (file_bytes_to_read_ == 0) {
- // We've read all of the file data,
- // so now expect the next file header
-
- // setting to 0 makes us want more header bytes
- header_bytes_read_ = 0;
- }
- }
- }
-
- return IN_PROGRESS;
-}
-
-void TarProcessor::Close(bool success) {
- callback_client_->Close(success);
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/tar_processor.h b/o3d/import/cross/tar_processor.h
deleted file mode 100644
index 66d4b4aa..0000000
--- a/o3d/import/cross/tar_processor.h
+++ /dev/null
@@ -1,97 +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.
- */
-
-//
-// TarProcessor processes a tar byte stream (uncompressed).
-//
-// A tar byte stream consists of a series of file headers, each followed by
-// the actual file data. Each file header starts on a block-aligned offset
-// with the blocksize 512. The start of data for each file is also
-// block-aligned.
-//
-// As a TarProcessor receives bytes, it calls the client
-// callback method ReceiveFileHeader() when each complete file header has been
-// received. Then the client's ReceiveFileData() will be called (possibly
-// repeatedly) as the file's data is received. This is repeated until all of
-// the files in the archive have been processed.
-
-#ifndef O3D_IMPORT_CROSS_TAR_PROCESSOR_H_
-#define O3D_IMPORT_CROSS_TAR_PROCESSOR_H_
-
-#include "base/basictypes.h"
-#include "core/cross/types.h"
-#include "import/cross/memory_stream.h"
-#include "import/cross/archive_processor.h"
-
-namespace o3d {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class TarProcessor : public StreamProcessor {
- public:
- explicit TarProcessor(ArchiveCallbackClient *callback_client)
- : callback_client_(callback_client),
- header_bytes_read_(0),
- getting_filename_(false),
- file_bytes_to_read_(0) {}
-
- virtual ~TarProcessor() {}
-
- // Call to "push" bytes to be processed - the appropriate callback will get
- // called when we have enough data
- virtual Status ProcessBytes(MemoryReadStream *stream, size_t n);
-
- virtual void Close(bool success);
-
- private:
- enum {TAR_HEADER_SIZE = 512};
- enum {TAR_BLOCK_SIZE = 512};
-
- ArchiveCallbackClient *callback_client_;
- size_t header_bytes_read_;
- char header_[TAR_HEADER_SIZE];
- bool getting_filename_;
- String file_name_;
-
- // Initialized to total number of file bytes,
- // including zero padding up to block size
- // We read this many bytes to get to the next header
- size_t file_bytes_to_read_;
-
- // Initialized to the actual file size (not counting zero-padding) - keeps
- // track of number of bytes the client needs to read for the current file
- size_t client_file_bytes_to_read_;
-
- DISALLOW_COPY_AND_ASSIGN(TarProcessor);
-};
-
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_TAR_PROCESSOR_H_
diff --git a/o3d/import/cross/tar_processor_test.cc b/o3d/import/cross/tar_processor_test.cc
deleted file mode 100644
index 4da0f97..0000000
--- a/o3d/import/cross/tar_processor_test.cc
+++ /dev/null
@@ -1,186 +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 "import/cross/targz_processor.h"
-#include "tests/common/win/testing_common.h"
-#include "tests/common/cross/test_utils.h"
-
-namespace o3d {
-
-class TarProcessorTest : public testing::Test {
-};
-
-// We verify that the tar file contains exactly these filenames
-static const char *kFilename1 = "test/file1";
-static const char *kFilename2 =
- "test/file1ThisIsAFilenameLongerThen100Chars"
- "ThisIsAFilenameLongerThen100Chars"
- "ThisIsAFilenameLongerThen100CharsThisIsAFilenameLongerThen100Chars";
-static const char *kFilename3 = "test/file2";
-static const char *kFilename4 = "test/file3";
-
-// With each file having these exact contents
-
-// we should receive these (and exactly these bytes in this order)
-static const char *kConcatenatedContents =
- "the cat in the hat\n" // file 1 contents.
- "this file has a long name" // file 2 contents.
- "abracadabra\n" // file 3 contents.
- "I think therefore I am\n" // file 4 contents.
- ""; // end
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class TarTestClient : public ArchiveCallbackClient {
- public:
- explicit TarTestClient() : file_count_(0), index_(0) {}
- // ArchiveCallbackClient methods
- virtual void ReceiveFileHeader(const ArchiveFileInfo &file_info);
- virtual bool ReceiveFileData(MemoryReadStream *stream, size_t nbytes);
-
- virtual void Close(bool success) {
- closed_ = true;
- success_ = success;
- }
-
- int GetFileCount() const { return file_count_; }
- size_t GetNumTotalBytesReceived() const { return index_; }
-
- bool closed() const {
- return closed_;
- }
-
- bool success() const {
- return success_;
- }
-
- private:
- int file_count_;
- int index_;
- bool closed_;
- bool success_;
-};
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void TarTestClient::ReceiveFileHeader(const ArchiveFileInfo &file_info) {
- // We get called one time for each file in the archive
-
- // Check that the filenames match our expectation
- switch (file_count_) {
- case 0:
- EXPECT_TRUE(!strcmp(kFilename1, file_info.GetFileName().c_str()));
- break;
- case 1:
- EXPECT_TRUE(!strcmp(kFilename2, file_info.GetFileName().c_str()));
- break;
- case 2:
- EXPECT_TRUE(!strcmp(kFilename3, file_info.GetFileName().c_str()));
- break;
- case 3:
- EXPECT_TRUE(!strcmp(kFilename4, file_info.GetFileName().c_str()));
- break;
- }
-
- file_count_++;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool TarTestClient::ReceiveFileData(MemoryReadStream *stream, size_t nbytes) {
- const char *p = reinterpret_cast<const char*>(
- stream->GetDirectMemoryPointer());
-
- // Note: ReceiveFileData() may be called multiple times for each file, until
- // the complete file contents have been given...
-
- // We're receiving three file, one after the other
- // The bytes we receive are the concatenated contents of the three files
- // (with calls to ReceiveFileHeader() separating each one)
- //
- EXPECT_TRUE(index_ + nbytes <= strlen(kConcatenatedContents));
- EXPECT_TRUE(!strncmp(kConcatenatedContents + index_, p, nbytes));
-
- index_ += nbytes;
-
- return true;
-}
-
-// Loads a tar file, runs it through the processor.
-// In our callbacks, we verify that we receive three files with known contents
-//
-TEST_F(TarProcessorTest, LoadTarFile) {
- String filepath = *g_program_path + "/archive_files/test1.tar";
-
- // Read the test tar file into memory
- size_t file_size;
- uint8 *tar_data = test_utils::ReadFile(filepath, &file_size);
- ASSERT_TRUE(tar_data != NULL);
-
- // Gets header and file data callbacks
- TarTestClient callback_client;
-
- // The class we're testing...
- TarProcessor tar_processor(&callback_client);
-
- // Now that we've read the compressed file into memory, lets
- // feed it, a chunk at a time, into the tar_processor
- const int kChunkSize = 32;
-
- MemoryReadStream tar_stream(tar_data, file_size);
- int bytes_to_process = file_size;
-
- while (bytes_to_process > 0) {
- int bytes_this_time =
- bytes_to_process < kChunkSize ? bytes_to_process : kChunkSize;
-
- StreamProcessor::Status status = tar_processor.ProcessBytes(
- &tar_stream, bytes_this_time);
- EXPECT_TRUE(status != StreamProcessor::FAILURE);
-
- bytes_to_process -= bytes_this_time;
- }
- tar_processor.Close(true);
-
- EXPECT_TRUE(callback_client.closed());
- EXPECT_TRUE(callback_client.success());
-
- free(tar_data);
-}
-
-TEST_F(TarProcessorTest, PassesThroughFailure) {
- TarTestClient callback_client;
- TarProcessor tar_processor(&callback_client);
- tar_processor.Close(false);
-
- EXPECT_TRUE(callback_client.closed());
- EXPECT_FALSE(callback_client.success());
-}
-
-} // namespace
diff --git a/o3d/import/cross/targz_generator.cc b/o3d/import/cross/targz_generator.cc
deleted file mode 100644
index aa75712..0000000
--- a/o3d/import/cross/targz_generator.cc
+++ /dev/null
@@ -1,64 +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 "import/cross/memory_buffer.h"
-#include "import/cross/targz_generator.h"
-
-namespace o3d {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-TarGzGenerator::TarGzGenerator(StreamProcessor *callback_client)
- : gz_compressor_(callback_client), tar_generator_(&gz_compressor_) {
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool TarGzGenerator::AddFile(const String &file_name, size_t file_size) {
- return tar_generator_.AddFile(file_name, file_size);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-int TarGzGenerator::AddFileBytes(MemoryReadStream *stream, size_t n) {
- return tar_generator_.AddFileBytes(stream, n);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-int TarGzGenerator::AddFileBytes(const uint8 *data, size_t n) {
- MemoryReadStream stream(data, n);
- return AddFileBytes(&stream, n);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void TarGzGenerator::Close(bool success) {
- tar_generator_.Close(success);
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/targz_generator.h b/o3d/import/cross/targz_generator.h
deleted file mode 100644
index b8eb216..0000000
--- a/o3d/import/cross/targz_generator.h
+++ /dev/null
@@ -1,85 +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.
- */
-
-//
-// TarGzGenerator generates a "tar.gz" byte stream.
-// In other words, given a series of files, it will first create a tar archive
-// from them, then apply gzip compression.
-// This would be equivalent to using the "tar cf" command followed by "gzip"
-//
-// The normal usage is to call the AddFile() method for each file to add to the
-// archive, then make one or more calls to AddFileBytes() to give the file's
-// data. Then repeat this sequence for each file to be added. When done,
-// call Finalize().
-
-#ifndef O3D_IMPORT_CROSS_TARGZ_GENERATOR_H_
-#define O3D_IMPORT_CROSS_TARGZ_GENERATOR_H_
-
-#include <string>
-#include "base/basictypes.h"
-#include "core/cross/types.h"
-#include "import/cross/gz_compressor.h"
-#include "import/cross/iarchive_generator.h"
-#include "import/cross/memory_stream.h"
-#include "import/cross/tar_generator.h"
-
-namespace o3d {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class TarGzGenerator : public IArchiveGenerator {
- public:
- // |callback_client| receives the tar.gz byte stream
- explicit TarGzGenerator(StreamProcessor *callback_client);
-
- // Call AddFile() for each file entry, followed by calls to AddFileBytes()
- // for the file's data
- virtual bool AddFile(const String &file_name,
- size_t file_size);
-
- // Call with the file's data (after calling AddFile)
- // may be called one time with all the file's data, or multiple times
- // until all the data is provided
- virtual int AddFileBytes(MemoryReadStream *stream, size_t n);
- int AddFileBytes(const uint8 *data, size_t n);
-
- // Must call this after all files and file data have been written
- virtual void Close(bool success);
-
- private:
- GzCompressor gz_compressor_;
- TarGenerator tar_generator_;
-
- DISALLOW_COPY_AND_ASSIGN(TarGzGenerator);
-};
-
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_TARGZ_GENERATOR_H_
diff --git a/o3d/import/cross/targz_generator_test.cc b/o3d/import/cross/targz_generator_test.cc
deleted file mode 100644
index e3331f3..0000000
--- a/o3d/import/cross/targz_generator_test.cc
+++ /dev/null
@@ -1,199 +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 <string>
-
-#include "base/file_util.h"
-#include "import/cross/memory_stream.h"
-#include "import/cross/targz_generator.h"
-#include "tests/common/cross/test_utils.h"
-#include "tests/common/win/testing_common.h"
-#include "utils/cross/file_path_utils.h"
-
-// Define to generate a new golden file for the archive test. Don't
-// leave this enabled, as it may affect the results of the test.
-#undef GENERATE_GOLDEN
-
-namespace o3d {
-
-class TarGzGeneratorTest : public testing::Test {
-};
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class TarGzTestClient : public StreamProcessor {
- public:
- explicit TarGzTestClient(size_t reference_size)
- : compressed_data_(reference_size),
- write_stream_(compressed_data_, reference_size),
- closed_(false),
- success_(false) {
- };
-
- virtual Status ProcessBytes(MemoryReadStream *stream,
- size_t bytes_to_process) {
- // Simply buffer up the tar.gz bytes
- // When we've gotten them all our Validate() method will be called
- const uint8 *p = stream->GetDirectMemoryPointer();
- stream->Skip(bytes_to_process);
-
- size_t remaining = write_stream_.GetRemainingByteCount();
- EXPECT_TRUE(bytes_to_process <= remaining);
-
- write_stream_.Write(p, bytes_to_process);
-
- return SUCCESS;
- }
-
- virtual void Close(bool success) {
- closed_ = true;
- success_ = success;
- }
-
- // Checks that the data from the reference tar.gz file matches the tar.gz
- // stream we just ge5nerated
- uint8* compressed_data() {
- uint8 *received_data = compressed_data_;
- return received_data;
- }
-
- size_t compressed_data_length() {
- return compressed_data_.GetLength();
- }
-
-#if defined(GENERATE_GOLDEN)
- char* received_data() {
- uint8 *data = compressed_data_;
- data[9] = 3; // Force platform in header to 'UNIX'.
- return reinterpret_cast<char*>(data);
- }
-
- int received_data_length() {
- return compressed_data_.GetLength();
- }
-#endif
-
- bool closed() const {
- return closed_;
- }
-
- bool success() const {
- return success_;
- }
-
- private:
- MemoryBuffer<uint8> compressed_data_;
- MemoryWriteStream write_stream_;
- bool closed_;
- bool success_;
-
- DISALLOW_COPY_AND_ASSIGN(TarGzTestClient);
-};
-
-// Generates a tar.gz archive (in memory) containing three files (image, audio,
-// shader) in three separate directories. The generated archive is then
-// compared with a reference tar.gz file which is known to be correct.
-//
-TEST_F(TarGzGeneratorTest, GenerateTarGz) {
- String targz_reference_file = *g_program_path + "/archive_files/test2.tar.gz";
- String image_file = *g_program_path + "/archive_files/keyboard.jpg";
- String audio_file = *g_program_path + "/archive_files/perc.aif";
- String shader_file = *g_program_path + "/archive_files/BumpReflect.fx";
-
- size_t targz_reference_size;
- size_t image_size;
- size_t audio_size;
- size_t shader_size;
-
- // Read the test files into memory
- uint8 *targz_data =
- test_utils::ReadFile(targz_reference_file, &targz_reference_size);
- uint8 *image_data = test_utils::ReadFile(image_file, &image_size);
- uint8 *audio_data = test_utils::ReadFile(audio_file, &audio_size);
- uint8 *shader_data = test_utils::ReadFile(shader_file, &shader_size);
- ASSERT_TRUE(targz_data != NULL);
- ASSERT_TRUE(image_data != NULL);
- ASSERT_TRUE(audio_data != NULL);
- ASSERT_TRUE(shader_data != NULL);
-
- ASSERT_NE(0U, targz_reference_size);
-
- TarGzTestClient test_client(targz_reference_size);
- TarGzGenerator targz_generator(&test_client);
-
- targz_generator.AddFile("test/images/keyboard.jpg", image_size);
- targz_generator.AddFileBytes(image_data, image_size);
-
- targz_generator.AddFile("test/audio/perc.aif", audio_size);
- targz_generator.AddFileBytes(audio_data, audio_size);
-
- targz_generator.AddFile("test/shaders/BumpReflect.fx", shader_size);
- targz_generator.AddFileBytes(shader_data, shader_size);
-
- targz_generator.Close(true);
-
-#if defined(GENERATE_GOLDEN)
- std::string new_golden_file = *g_program_path +
- "/archive_files/new_golden_test2.tar.gz";
- file_util::WriteFile(UTF8ToFilePath(new_golden_file),
- test_client.received_data(),
- test_client.received_data_length());
-
-#endif
-
- uint8 *received_data = test_client.compressed_data();
-
- // The platform header in our reference file is set to UNIX, so
- // force received data to match for all platforms.
- received_data[9] = 3;
-
- EXPECT_EQ(0, memcmp(targz_data,
- received_data,
- test_client.compressed_data_length()));
-
- EXPECT_TRUE(test_client.closed());
- EXPECT_TRUE(test_client.success());
-
- free(targz_data);
- free(image_data);
- free(audio_data);
- free(shader_data);
-}
-
-TEST_F(TarGzGeneratorTest, PassesThroughCloseFailure) {
- TarGzTestClient test_client(1000);
- TarGzGenerator targz_generator(&test_client);
- targz_generator.Close(false);
-
- EXPECT_TRUE(test_client.closed());
- EXPECT_FALSE(test_client.success());
-}
-} // namespace o3d
diff --git a/o3d/import/cross/targz_processor.cc b/o3d/import/cross/targz_processor.cc
deleted file mode 100644
index 5fb1275..0000000
--- a/o3d/import/cross/targz_processor.cc
+++ /dev/null
@@ -1,69 +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.
- */
-
-//
-// TarGzProcessor processes a gzipped tar stream (tar.gz)
-// compressed byte stream
-//
-
-#include "import/cross/targz_processor.h"
-
-#include <assert.h>
-#include "import/cross/memory_stream.h"
-
-#define CHUNK 16384
-
-namespace o3d {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// The |gz_decompressor_| processes a compressed byte stream, calling back
-// into |tar_processor_| with the decompressed byte stream
-// Finally, |tar_processor_| calls back to |callback_client| with file header
-// and file data callbacks...
-//
-TarGzProcessor::TarGzProcessor(ArchiveCallbackClient *callback_client)
- : ArchiveProcessor(callback_client),
- tar_processor_(callback_client),
- gz_decompressor_(&tar_processor_) {
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-//
-StreamProcessor::Status TarGzProcessor::ProcessBytes(MemoryReadStream *stream,
- size_t bytes_to_process) {
- return gz_decompressor_.ProcessBytes(stream, bytes_to_process);
-}
-
-void TarGzProcessor::Close(bool success) {
- gz_decompressor_.Close(success);
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/targz_processor.h b/o3d/import/cross/targz_processor.h
deleted file mode 100644
index 061d66e..0000000
--- a/o3d/import/cross/targz_processor.h
+++ /dev/null
@@ -1,67 +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.
- */
-
-//
-// TarGzProcessor processes a gzipped tar stream (tar.gz)
-// compressed byte stream
-//
-
-#ifndef O3D_IMPORT_CROSS_TARGZ_PROCESSOR_H_
-#define O3D_IMPORT_CROSS_TARGZ_PROCESSOR_H_
-
-#include "base/basictypes.h"
-#include "import/cross/archive_processor.h"
-#include "import/cross/gz_decompressor.h"
-#include "import/cross/tar_processor.h"
-#include "zlib.h"
-
-namespace o3d {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class TarGzProcessor : public ArchiveProcessor {
- public:
- explicit TarGzProcessor(ArchiveCallbackClient *callback_client);
-
- virtual Status ProcessBytes(MemoryReadStream *stream,
- size_t bytes_to_process);
-
- virtual void Close(bool success);
-
- private:
- TarProcessor tar_processor_;
- GzDecompressor gz_decompressor_;
-
- DISALLOW_COPY_AND_ASSIGN(TarGzProcessor);
-};
-
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_TARGZ_PROCESSOR_H_
diff --git a/o3d/import/cross/targz_processor_test.cc b/o3d/import/cross/targz_processor_test.cc
deleted file mode 100644
index 37d70a4..0000000
--- a/o3d/import/cross/targz_processor_test.cc
+++ /dev/null
@@ -1,171 +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 "import/cross/targz_processor.h"
-#include "tests/common/win/testing_common.h"
-
-namespace o3d {
-
-class TarGzProcessorTest : public testing::Test {
-};
-
-// We verify that the tar.gz file contains exactly these filenames
-const char *kFilename1 = "test/file1";
-const char *kFilename2 = "test/file2";
-const char *kFilename3 = "test/file3";
-
-// With each file having these exact contents
-#define kFileContents1 "the cat in the hat\n"
-#define kFileContents2 "abracadabra\n"
-#define kFileContents3 "I think therefore I am\n"
-
-// we should receive these (and exactly these bytes in this order)
-const char *kConcatenatedContents =
- kFileContents1 kFileContents2 kFileContents3;
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class ArchiveTestClient : public ArchiveCallbackClient {
- public:
- explicit ArchiveTestClient()
- : file_count_(0),
- index_(0),
- closed_(false),
- success_(false) {}
-
- // ArchiveCallbackClient methods
- virtual void ReceiveFileHeader(const ArchiveFileInfo &file_info);
- virtual bool ReceiveFileData(MemoryReadStream *stream, size_t nbytes);
-
- virtual void Close(bool success) {
- closed_ = true;
- success_ = success;
- }
-
- int GetFileCount() const { return file_count_; }
- size_t GetNumTotalBytesReceived() const { return index_; }
-
- bool closed() const {
- return closed_;
- }
-
- bool success() const {
- return success_;
- }
-
- private:
- int file_count_;
- int index_;
- bool closed_;
- bool success_;
-};
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void ArchiveTestClient::ReceiveFileHeader(const ArchiveFileInfo &file_info) {
- // We get called one time for each file in the archive
-
- // Check that the filenames match our expectation
- switch (file_count_) {
- case 0:
- EXPECT_TRUE(!strcmp(kFilename1, file_info.GetFileName().c_str()));
- break;
- case 1:
- EXPECT_TRUE(!strcmp(kFilename2, file_info.GetFileName().c_str()));
- break;
- case 2:
- EXPECT_TRUE(!strcmp(kFilename3, file_info.GetFileName().c_str()));
- break;
- }
-
- file_count_++;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool ArchiveTestClient::ReceiveFileData(MemoryReadStream *stream,
- size_t nbytes) {
- const char *p = reinterpret_cast<const char*>(
- stream->GetDirectMemoryPointer());
-
- // Note: ReceiveFileData() may be called multiple times for each file, until
- // the complete file contents have been given...
-
- // We're receiving three file, one after the other
- // The bytes we receive are the concatenated contents of the three files
- // (with calls to ReceiveFileHeader() separating each one)
- //
- EXPECT_TRUE(index_ + nbytes <= strlen(kConcatenatedContents));
- EXPECT_TRUE(!strncmp(kConcatenatedContents + index_, p, nbytes));
-
- index_ += nbytes;
-
- return true;
-}
-
-// Loads a tar.gz file, runs it through the processor.
-// In our callbacks, we verify that we receive three files with known contents
-//
-TEST_F(TarGzProcessorTest, LoadTarGzFile) {
- String filepath = *g_program_path + "/archive_files/test1.tar.gz";
-
- ArchiveTestClient test_callback_client;
-
- TarGzProcessor processor(&test_callback_client);
- StreamProcessor::Status status = processor.ProcessFile(filepath.c_str());
- processor.Close(true);
-
- EXPECT_EQ(StreamProcessor::SUCCESS, status);
-
- EXPECT_EQ(3, test_callback_client.GetFileCount());
- EXPECT_EQ(strlen(kConcatenatedContents),
- test_callback_client.GetNumTotalBytesReceived());
-
- EXPECT_TRUE(test_callback_client.closed());
- EXPECT_TRUE(test_callback_client.success());
-}
-
-// Tries to load something with a tar.gz extension, but which isn't
-// really a tar.gz and contains random text
-//
-TEST_F(TarGzProcessorTest, LoadBogusTarGzFile) {
- String filepath = *g_program_path + "/archive_files/bogus.tar.gz";
-
- ArchiveTestClient test_callback_client;
-
- TarGzProcessor processor(&test_callback_client);
- StreamProcessor::Status status = processor.ProcessFile(filepath.c_str());
- processor.Close(false);
-
- EXPECT_EQ(StreamProcessor::FAILURE, status);
-
- EXPECT_TRUE(test_callback_client.closed());
- EXPECT_FALSE(test_callback_client.success());
-}
-} // namespace
diff --git a/o3d/import/cross/threaded_stream_processor.cc b/o3d/import/cross/threaded_stream_processor.cc
deleted file mode 100644
index c389c54..0000000
--- a/o3d/import/cross/threaded_stream_processor.cc
+++ /dev/null
@@ -1,116 +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.
- */
-
-// ThreadedStreamProcessor forwards data from one thread to
-// another processor that will run on a new thread owned by the
-// ThreadedStreamProcessor.
-
-#include "import/cross/threaded_stream_processor.h"
-#include "base/task.h"
-
-namespace o3d {
-
-ThreadedStreamProcessor::ThreadedStreamProcessor(StreamProcessor *receiver)
- : receiver_(receiver),
- thread_("ThreadedStreamProcessor"),
- status_(IN_PROGRESS) {
-}
-
-ThreadedStreamProcessor::~ThreadedStreamProcessor() {
- // Wait for the other thread to stop so it does not access this object after
- // it has been destroyed.
- StopThread();
-}
-
-void ThreadedStreamProcessor::StartThread() {
- if (!thread_.IsRunning()) {
- thread_.Start();
- }
-}
-
-void ThreadedStreamProcessor::StopThread() {
- if (thread_.IsRunning()) {
- thread_.Stop();
- }
-}
-
-StreamProcessor::Status ThreadedStreamProcessor::ProcessBytes(
- MemoryReadStream *stream,
- size_t bytes_to_process) {
- // Report any error on the other thread.
- if (status_ == FAILURE) {
- return status_;
- }
-
- StartThread();
-
- // Copy the bytes. They are deleted by the other thread when it has processed
- // them.
- uint8* copy = new uint8[bytes_to_process];
- stream->Read(copy, bytes_to_process);
-
- // Post a task to call ForwardBytes on the other thread.
- thread_.message_loop()->PostTask(FROM_HERE, NewRunnableFunction(
- &ThreadedStreamProcessor::ForwardBytes, this, copy, bytes_to_process));
-
- return IN_PROGRESS;
-}
-
-void ThreadedStreamProcessor::Close(bool success) {
- StartThread();
-
- // Post a task to call ForwardClose on the other thread.
- thread_.message_loop()->PostTask(FROM_HERE, NewRunnableFunction(
- &ThreadedStreamProcessor::ForwardClose, this, success));
-}
-
-void ThreadedStreamProcessor::ForwardBytes(
- ThreadedStreamProcessor* processor, const uint8* bytes, size_t size) {
- // Do not forward if an error has ocurred. Just delete the buffer.
- if (processor->status_ == FAILURE) {
- delete[] bytes;
- return;
- }
-
- // Pass bytes to the receiver.
- MemoryReadStream stream(bytes, size);
- processor->status_ = processor->receiver_->ProcessBytes(&stream, size);
-
- // Delete the buffer once the receiver is finished with them.
- delete[] bytes;
-}
-
-void ThreadedStreamProcessor::ForwardClose(ThreadedStreamProcessor* processor,
- bool success) {
- processor->receiver_->Close(success && (processor->status_ != FAILURE));
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/threaded_stream_processor.h b/o3d/import/cross/threaded_stream_processor.h
deleted file mode 100644
index f040eb4..0000000
--- a/o3d/import/cross/threaded_stream_processor.h
+++ /dev/null
@@ -1,72 +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.
- */
-
-// ThreadedStreamProcessor forwards data from one thread to
-// another processor that will run on a new thread owned by the
-// ThreadedStreamProcessor.
-
-#ifndef O3D_IMPORT_CROSS_THREADED_STREAM_PROCESSOR_H_
-#define O3D_IMPORT_CROSS_THREADED_STREAM_PROCESSOR_H_
-
-#include "base/basictypes.h"
-#include "base/thread.h"
-#include "import/cross/memory_stream.h"
-
-namespace o3d {
-
-class ThreadedStreamProcessor : public StreamProcessor {
- public:
- explicit ThreadedStreamProcessor(StreamProcessor *receiver);
- virtual ~ThreadedStreamProcessor();
-
- virtual Status ProcessBytes(MemoryReadStream *stream,
- size_t bytes_to_process);
-
- virtual void Close(bool success);
-
- void StartThread();
- void StopThread();
-
- private:
- static void ForwardBytes(ThreadedStreamProcessor* processor,
- const uint8* data, size_t size);
-
- static void ForwardClose(ThreadedStreamProcessor* processor, bool success);
-
- StreamProcessor* receiver_;
- ::base::Thread thread_;
- Status status_;
-
- DISALLOW_COPY_AND_ASSIGN(ThreadedStreamProcessor);
-};
-} // namespace o3d
-
-#endif // O3D_IMPORT_CROSS_THREADED_STREAM_PROCESSOR_H_
diff --git a/o3d/import/cross/threaded_stream_processor_test.cc b/o3d/import/cross/threaded_stream_processor_test.cc
deleted file mode 100644
index 0a4530f..0000000
--- a/o3d/import/cross/threaded_stream_processor_test.cc
+++ /dev/null
@@ -1,155 +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 "import/cross/memory_buffer.h"
-#include "import/cross/threaded_stream_processor.h"
-#include "tests/common/win/testing_common.h"
-#include "tests/common/cross/test_utils.h"
-
-using test_utils::ReadFile;
-
-namespace o3d {
-
-class ThreadedStreamProcessorTest : public testing::Test {
- protected:
-};
-
-class TestReceiver : public StreamProcessor {
- public:
- explicit TestReceiver(size_t size) : closed_(false), success_(false) {
- buffer_.Allocate(size);
- stream_.Assign(buffer_, size);
- }
-
- virtual Status ProcessBytes(MemoryReadStream *input_stream,
- size_t bytes_to_process) {
- const uint8 *p = input_stream->GetDirectMemoryPointer();
- input_stream->Skip(bytes_to_process);
-
- size_t bytes_written = stream_.Write(p, bytes_to_process);
- EXPECT_EQ(bytes_written, bytes_to_process);
-
- return SUCCESS;
- }
-
- virtual void Close(bool success) {
- closed_ = true;
- success_ = success;
- }
-
- uint8 *GetResultBuffer() { return buffer_; }
- size_t GetResultLength() const { return stream_.GetStreamPosition(); }
-
- bool closed() const {
- return closed_;
- }
-
- bool success() const {
- return success_;
- }
-
- private:
- MemoryBuffer<uint8> buffer_;
- MemoryWriteStream stream_;
- bool closed_;
- bool success_;
-};
-
-TEST_F(ThreadedStreamProcessorTest, CanForwardZeroBuffers) {
- TestReceiver receiver(1000);
- ThreadedStreamProcessor processor(&receiver);
- processor.Close(true);
- processor.StopThread();
-
- EXPECT_EQ(0U, receiver.GetResultLength());
- EXPECT_TRUE(receiver.closed());
- EXPECT_TRUE(receiver.success());
-}
-
-TEST_F(ThreadedStreamProcessorTest, CanForwardOneBufferOfZeroBytes) {
- uint8 buffer[5] = { 1, 2, 3, 4, 5 };
- TestReceiver receiver(1000);
-
- ThreadedStreamProcessor processor(&receiver);
- MemoryReadStream stream(buffer, sizeof(buffer));
- processor.ProcessBytes(&stream, 0);
- processor.Close(true);
- processor.StopThread();
-
- EXPECT_EQ(0U, receiver.GetResultLength());
- EXPECT_TRUE(receiver.closed());
- EXPECT_TRUE(receiver.success());
-}
-
-TEST_F(ThreadedStreamProcessorTest, CanForwardOneBufferFullOfBytes) {
- uint8 buffer[5] = { 1, 2, 3, 4, 5 };
- TestReceiver receiver(1000);
-
- ThreadedStreamProcessor processor(&receiver);
- MemoryReadStream stream(buffer, sizeof(buffer));
- processor.ProcessBytes(&stream, sizeof(buffer));
- processor.Close(true);
- processor.StopThread();
-
- EXPECT_EQ(sizeof(buffer), receiver.GetResultLength());
- EXPECT_EQ(0, memcmp(buffer, receiver.GetResultBuffer(), sizeof(buffer)));
- EXPECT_TRUE(receiver.closed());
- EXPECT_TRUE(receiver.success());
-}
-
-TEST_F(ThreadedStreamProcessorTest, CanForwardTwoBuffersFullOfBytes) {
- uint8 buffer[5] = { 1, 2, 3, 4, 5 };
- TestReceiver receiver(1000);
-
- ThreadedStreamProcessor processor(&receiver);
- MemoryReadStream stream(buffer, sizeof(buffer));
- processor.ProcessBytes(&stream, 2);
- processor.ProcessBytes(&stream, 3);
- processor.Close(true);
- processor.StopThread();
-
- EXPECT_EQ(sizeof(buffer), receiver.GetResultLength());
- EXPECT_EQ(0, memcmp(buffer, receiver.GetResultBuffer(), sizeof(buffer)));
- EXPECT_TRUE(receiver.closed());
- EXPECT_TRUE(receiver.success());
-}
-
-TEST_F(ThreadedStreamProcessorTest, PassesThroughStreamFailed) {
- TestReceiver receiver(1000);
- ThreadedStreamProcessor processor(&receiver);
- processor.Close(false);
- processor.StopThread();
-
- EXPECT_TRUE(receiver.closed());
- EXPECT_FALSE(receiver.success());
-}
-
-} // namespace o3d
diff --git a/o3d/import/cross/zip_archive.cc b/o3d/import/cross/zip_archive.cc
deleted file mode 100644
index 1baf996..0000000
--- a/o3d/import/cross/zip_archive.cc
+++ /dev/null
@@ -1,891 +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.
- */
-
-
-// A basic C++ wrapper for a zip file
-// Adapted from miniunz.c from minizip open source code by Gilles Vollant.
-// Copyright (C) 1998-2005 Gilles Vollant
-
-#include "import/cross/zip_archive.h"
-
-#include "base/basictypes.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-#include <errno.h>
-#include <fcntl.h>
-
-#ifdef OS_POSIX
-#include <unistd.h>
-#include <utime.h>
-#include <sys/stat.h>
-#else
-#include <direct.h>
-#include <io.h>
-#include <rpc.h>
-#endif
-
-using std::vector;
-using std::string;
-
-#if defined(OS_WIN)
-// Windows #defines this...
-#undef DeleteFile
-#endif
-
-#ifndef ALLOW_USER_QUERY
-#define ALLOW_USER_QUERY 0 // 1: ask before overwriting files
-#endif
-
-#ifndef DEBUGLOG_DESTINATION
-#define DEBUGLOG_DESTINATION 0 // 0: no debug output 1: output to stdout
-#endif
-
-#if DEBUGLOG_DESTINATION == 1
-#define DEBUGLOG(...) printf(__VA_ARGS__)
-#else
-#define DEBUGLOG(...)
-#endif
-
-
-#define CASESENSITIVITY (1) // activate case sensitivity
-#define WRITEBUFFERSIZE (8192)
-#define MAXFILENAME (1024)
-
-// Creates a basic C++ wrapper for a zip file
-ZipArchive::ZipArchive(const std::string &zip_filename, int *result)
- : zip_filename_(zip_filename), zip_file_ref_(0) {
- const char *zip_filename_c = zip_filename_.c_str();
- char filename_try[MAXFILENAME + 16] = "";
- strncpy(filename_try, zip_filename_c, MAXFILENAME - 1);
-
- // strncpy doesn't append the trailing NULL if the string is too long.
- filename_try[MAXFILENAME] = '\0';
-
- zip_file_ref_ = unzOpen(zip_filename_c);
-
- // try appending .zip if |zip_filename| as given wasn't found
- if (zip_file_ref_ == NULL) {
- strcat(filename_try, ".zip");
- zip_file_ref_ = unzOpen(filename_try);
- }
-
- if (zip_file_ref_ == NULL) {
- DEBUGLOG("Cannot open %s or %s.zip\n", zip_filename_c, zip_filename_c);
- if (result) {
- *result = 1;
- return;
- }
- }
- DEBUGLOG("%s opened\n", filename_try);
-
- *result = UNZ_OK;
-}
-
-ZipArchive::~ZipArchive() {
- unzClose(zip_file_ref_);
- zip_file_ref_ = 0;
-}
-
-// The returned filenames should adhere to the zip archive spec
-// (UTF8 with '/' as the path separator)
-// If the zip file is badly constructed then this assumption may be invalid.
-// The filenames will contain a leading '/', with '/' indicating the "root"
-// of the zip archive (as if the zip archive were a filesystem)
-//
-int ZipArchive::GetInformationList(vector<ZipFileInfo> *infolist) {
- if (!infolist) return -1;
-
- unz_global_info gi;
- int result = unzGetGlobalInfo(zip_file_ref_, &gi);
-
- if (result == UNZ_OK) {
- unzGoToFirstFile(zip_file_ref_);
-
- for (uLong i = 0; i < gi.number_entry; ++i) {
- // get the info for this entry
- char filename_inzip[MAXFILENAME]; // MAX_PATH
- ZipFileInfo file_info;
- result = unzGetCurrentFileInfo(zip_file_ref_,
- &file_info,
- filename_inzip,
- sizeof(filename_inzip),
- NULL,
- 0,
- NULL,
- 0);
-
- file_info.name = "/" + string(filename_inzip);
- infolist->push_back(file_info);
-
- if ((i + 1) < gi.number_entry) {
- result = unzGoToNextFile(zip_file_ref_);
- if (result != UNZ_OK) {
- DEBUGLOG("error %d with zipfile in unzGoToNextFile\n", result);
- break;
- }
- }
- }
- }
-
- return result;
-}
-
-// Returns information for |filename| in |*info|
-// returns 0 if successful
-// |filename| is expected to have a leading '/' (as is returned by
-// GetInformationList() )
-//
-int ZipArchive::GetFileInfo(const string &filename, ZipFileInfo *info) {
- if (!info) return -1;
-
- unzGoToFirstFile(zip_file_ref_);
- unzFile uf = zip_file_ref_;
-
- string actual_filename;
- GetActualFilename(filename, &actual_filename);
-
- if (unzLocateFile(uf, actual_filename.c_str(), CASESENSITIVITY) != UNZ_OK) {
- DEBUGLOG("file %s not found in the zipfile\n", actual_filename.c_str());
- return 2;
- }
-
- // get the info for this entry
- char filename_inzip[MAXFILENAME];
- int result = unzGetCurrentFileInfo(uf,
- info,
- filename_inzip,
- sizeof(filename_inzip),
- NULL,
- 0,
- NULL,
- 0);
-
- info->name = "/" + string(filename_inzip);
-
- return result;
-}
-
-// Extracts the entire archive to disk
-int ZipArchive::Extract() {
- const char *filename_to_extract = NULL;
- const char *password = NULL;
-
- int opt_do_extract = 1;
- int opt_do_extract_withoutpath = 0;
- int opt_overwrite = 0;
- int opt_extractdir = 0;
- const char *dirname = NULL;
-
- if (opt_do_extract == 1) {
-#if defined(OS_WIN)
- if (opt_extractdir && ::_chdir(dirname)) {
- DEBUGLOG("Error changing into %s, aborting\n", dirname);
- exit(-1);
- }
-#else
- if (opt_extractdir && ::chdir(dirname)) {
- DEBUGLOG("Error changing into %s, aborting\n", dirname);
- exit(-1);
- }
-#endif
-
- if (filename_to_extract == NULL) {
- return DoExtract(opt_do_extract_withoutpath,
- opt_overwrite,
- password);
- } else {
- return ExtractOneFile(filename_to_extract,
- opt_do_extract_withoutpath,
- opt_overwrite,
- password);
- }
- }
-
- unzCloseCurrentFile(zip_file_ref_);
- return 1;
-}
-
-// Extracts a single file to disk
-int ZipArchive::ExtractOneFile(const string &filename,
- int opt_extract_without_path,
- int opt_overwrite,
- const char *password) {
- string actual_filename;
- GetActualFilename(filename, &actual_filename);
-
- unzGoToFirstFile(zip_file_ref_);
- if (unzLocateFile(zip_file_ref_,
- actual_filename.c_str(),
- CASESENSITIVITY) != UNZ_OK) {
- DEBUGLOG("file %s not found in the zipfile\n", actual_filename.c_str());
- return 2;
- }
-
- if (ExtractCurrentFile(&opt_extract_without_path,
- &opt_overwrite,
- password) == UNZ_OK) {
- return UNZ_OK;
- } else {
- return 1;
- }
-}
-
-
-// Extracts a single file and returns a pointer to the file's content.
-// Returns NULL if |filename| doesn't match any in the archive
-// or an error occurs. The caller must call free() on the returned pointer
-char *ZipArchive::GetFileData(const string &filename, size_t *size) {
- string actual_filename;
- GetActualFilename(filename, &actual_filename);
-
- unzFile uf = zip_file_ref_;
-
- unzGoToFirstFile(uf);
- if (unzLocateFile(uf, actual_filename.c_str(), CASESENSITIVITY) != UNZ_OK) {
- DEBUGLOG("file %s not found in the zipfile\n", actual_filename.c_str());
- return NULL;
- }
-
- // determine the size of the uncompressed file
- unz_file_info file_info;
- char filename_inzip[MAXFILENAME];
- int result = unzGetCurrentFileInfo(uf,
- &file_info,
- filename_inzip,
- sizeof(filename_inzip),
- NULL,
- 0,
- NULL,
- 0);
-
- if (result != UNZ_OK) return NULL;
-
- if (size) *size = file_info.uncompressed_size;
-
- result = unzOpenCurrentFilePassword(uf, NULL);
-
- char *buffer = NULL;
-
- if (result == UNZ_OK) {
- const int kBufferChunkSize = 32768;
- void *temp_buffer = malloc(kBufferChunkSize);
-
- // allocate one extra byte so we can NULL terminate
- // but don't report this extra byte in the |size| we return
- // NULL terminating is useful if the data retrieved is to be interpreted
- // as string data and doesn't harm anything else
- buffer = reinterpret_cast<char*>(malloc(file_info.uncompressed_size + 1));
- buffer[file_info.uncompressed_size] = 0;
- uint32 buffer_index = 0;
-
- uint32 nbytes;
- do {
- nbytes = unzReadCurrentFile(uf, temp_buffer, kBufferChunkSize);
- if (nbytes < 0) {
- DEBUGLOG("error %d with zipfile in unzReadCurrentFile\n", result);
- result = -1;
- break;
- }
- if (nbytes > 0) {
- // check that we're not exceeding the expected uncompressed size!
- if (buffer_index + nbytes > file_info.uncompressed_size) {
- result = -2;
- break;
- }
- memcpy(buffer + buffer_index, temp_buffer, nbytes);
- buffer_index += nbytes;
- }
- } while (nbytes > 0);
-
- free(temp_buffer);
-
- if (result == UNZ_OK) {
- result = unzCloseCurrentFile(uf);
- }
- }
-
- if (result != UNZ_OK) {
- free(buffer);
- buffer = NULL;
- }
-
- return buffer;
-}
-
-// Convert paths relative to |root_path| to archive paths
-// The |root_path| should start with '/' and should be an actual
-// directory in the zip archive.
-//
-char *ZipArchive::GetRelativeFileData(const string &relative_path,
- const string &root_path,
- size_t *size) {
- string converted_filename(relative_path);
- ConvertRelativeToAbsolutePath(&converted_filename, root_path);
-
- return GetFileData(converted_filename, size);
-}
-
-// private/protected methods
-//
-#ifdef OS_MACOSX
-#pragma mark -
-#endif
-
-int ZipArchive::ExtractCurrentFile(const int *popt_extract_without_path,
- int *popt_overwrite,
- const char *password) {
- int result = UNZ_OK;
-
- unz_file_info file_info;
- char filename_inzip[MAXFILENAME];
- result = unzGetCurrentFileInfo(zip_file_ref_,
- &file_info,
- filename_inzip,
- sizeof(filename_inzip),
- NULL,
- 0,
- NULL,
- 0);
-
- if (result != UNZ_OK) {
- DEBUGLOG("error %d with zipfile in unzGetCurrentFileInfo\n", result);
- return result;
- }
-
- DEBUGLOG("ExtractCurrentFile: %s\n", filename_inzip);
-
- uInt size_buf = WRITEBUFFERSIZE;
- void *buf = malloc(size_buf);
-
- char *filename_withoutpath;
- char *p;
- p = filename_withoutpath = filename_inzip;
- while ((*p) != '\0') {
- if (((*p) == '/') || ((*p) == '\\'))
- filename_withoutpath = p + 1;
- p++;
- }
-
- if ((*filename_withoutpath) == '\0') {
- if ((*popt_extract_without_path) == 0) {
- DEBUGLOG("creating directory: %s\n", filename_inzip);
- MyMkDir(filename_inzip);
- }
- } else {
- char *write_filename;
- int skip = 0;
-
- if ((*popt_extract_without_path) == 0) {
- write_filename = filename_inzip;
- } else {
- write_filename = filename_withoutpath;
- }
-
- result = unzOpenCurrentFilePassword(zip_file_ref_, password);
- if (result != UNZ_OK) {
- DEBUGLOG("error %d with zipfile in unzOpenCurrentFilePassword\n", result);
- }
-
-#if ALLOW_USER_QUERY
- if (((*popt_overwrite) == 0) && (result == UNZ_OK)) {
- char rep = 0;
- FILE* ftestexist;
- ftestexist = fopen(write_filename, "rb");
-
- if (ftestexist != NULL) {
- fclose(ftestexist);
-
- do {
- char answer[128];
- int ret;
-
- DEBUGLOG("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",
- write_filename);
-
- ret = scanf("%1s", answer);
- if (ret != 1) {
- exit(EXIT_FAILURE);
- }
- rep = answer[0];
- if ((rep >= 'a') && (rep <= 'z'))
- rep -= 0x20;
- }
- while ((rep != 'Y') && (rep != 'N') && (rep != 'A'));
- }
-
- if (rep == 'N')
- skip = 1;
-
- if (rep == 'A')
- *popt_overwrite = 1;
- }
-#endif // ALLOW_USER_QUERY
-
- FILE *fout = NULL;
- if ((skip == 0) && (result == UNZ_OK)) {
- DEBUGLOG("fopen: %s\n", write_filename);
-
- fout = fopen(write_filename, "wb");
-
- // some zipfiles don't contain directory alone before file
- if ((fout == NULL) && ((*popt_extract_without_path) == 0) &&
- (filename_withoutpath != reinterpret_cast<char*>(filename_inzip))) {
- char c = *(filename_withoutpath - 1);
- *(filename_withoutpath-1) = '\0';
- MakeDir(write_filename);
- *(filename_withoutpath - 1) = c;
- fout = fopen(write_filename, "wb");
- }
-
- if (fout == NULL) {
- DEBUGLOG("error opening %s\n", write_filename);
- }
- }
-
- if (fout != NULL) {
- DEBUGLOG(" extracting: %s\n", write_filename);
-
- do {
- result = unzReadCurrentFile(zip_file_ref_, buf, size_buf);
-
- if (result < 0) {
- DEBUGLOG("error %d with zipfile in unzReadCurrentFile\n", result);
- break;
- }
-
- if (result > 0)
- if (fwrite(buf, result, 1, fout) != 1) {
- DEBUGLOG("error in writing extracted file\n");
- result = UNZ_ERRNO;
- break;
- }
- } while (result > 0);
-
- if (fout) {
- fclose(fout);
- }
-
- if (result == 0) {
- ChangeFileDate(write_filename,
- file_info.dosDate,
- file_info.tmu_date);
- }
- }
-
- if (result == UNZ_OK) {
- result = unzCloseCurrentFile(zip_file_ref_);
- if (result != UNZ_OK) {
- DEBUGLOG("error %d with zipfile in unzCloseCurrentFile\n", result);
- }
- } else {
- unzCloseCurrentFile(zip_file_ref_); // don't lose the error
- }
- }
-
- free(buf);
- return result;
-}
-
-int ZipArchive::DoExtract(int opt_extract_without_path,
- int opt_overwrite,
- const char *password) {
- unz_global_info gi;
- int result = unzGetGlobalInfo(zip_file_ref_, &gi);
-
- if (result != UNZ_OK)
- DEBUGLOG("error %d with zipfile in unzGetGlobalInfo \n", result)
-
- for (uLong i = 0; i < gi.number_entry; ++i) {
- if (ExtractCurrentFile(&opt_extract_without_path,
- &opt_overwrite,
- password) != UNZ_OK)
- break;
-
- if ((i + 1) < gi.number_entry) {
- result = unzGoToNextFile(zip_file_ref_);
- if (result != UNZ_OK) {
- DEBUGLOG("error %d with zipfile in unzGoToNextFile\n", result)
- break;
- }
- }
- }
-
- return UNZ_OK;
-}
-
-// ChangeFileDate : change the date/time of a file
-// filename : the filename of the file where date/time must be modified
-// dosdate : the new date at the MSDos format (4 bytes)
-// tmu_date : the SAME new date at the tm_unz format
-void ZipArchive::ChangeFileDate(const char *filename,
- uLong dosdate,
- tm_unz tmu_date) {
-#if 0 // don't need or want this for now
-#ifdef WIN32
- HANDLE hFile;
- FILETIME ftm, ftLocal, ftCreate, ftLastAcc, ftLastWrite;
-
- hFile = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
- 0, NULL, OPEN_EXISTING, 0, NULL);
- GetFileTime(hFile, &ftCreate, &ftLastAcc, &ftLastWrite);
- DosDateTimeToFileTime((WORD)(dosdate>>16), (WORD)dosdate, &ftLocal);
- LocalFileTimeToFileTime(&ftLocal, &ftm);
- SetFileTime(hFile, &ftm, &ftLastAcc, &ftm);
- CloseHandle(hFile);
-#else
-#if defined(OS_LINUX) || defined(OS_MACOSX)
- struct utimbuf ut;
- struct tm newdate;
- newdate.tm_sec = tmu_date.tm_sec;
- newdate.tm_min = tmu_date.tm_min;
- newdate.tm_hour = tmu_date.tm_hour;
- newdate.tm_mday = tmu_date.tm_mday;
- newdate.tm_mon = tmu_date.tm_mon;
-
- if (tmu_date.tm_year > 1900)
- newdate.tm_year = tmu_date.tm_year - 1900;
- else
- newdate.tm_year = tmu_date.tm_year;
-
- newdate.tm_isdst = -1;
-
- ut.actime = ut.modtime = mktime(&newdate);
- utime(filename, &ut);
-#endif
-#endif
-#endif
-}
-
-
-int ZipArchive::MyMkDir(const char *dirname) {
- int ret = 0;
-#if defined(OS_WIN)
- ret = ::_mkdir(dirname);
-#else
-#if defined(OS_LINUX) || defined(OS_MACOSX)
- ret = ::mkdir(dirname, 0775);
-#endif
-#endif
- return ret;
-}
-
-int ZipArchive::MakeDir(const char *newdir) {
- int len = static_cast<int>(strlen(newdir));
-
- if (len <= 0)
- return 0;
-
- char *buffer = reinterpret_cast<char*>(malloc(len + 1));
- strcpy(buffer, newdir);
-
- if (buffer[len - 1] == '/') {
- buffer[len - 1] = '\0';
- }
-
- if (MyMkDir(buffer) == 0) {
- free(buffer);
- return 1;
- }
-
- char *p = buffer + 1;
- while (1) {
- while (*p && *p != '\\' && *p != '/')
- p++;
-
- char hold = *p;
- *p = 0;
-
- if ((MyMkDir(buffer) == -1) && (errno == ENOENT)) {
- DEBUGLOG("couldn't create directory %s\n", buffer);
- free(buffer);
- return 0;
- }
-
- if (hold == 0)
- break;
-
- *p++ = hold;
- }
-
- free(buffer);
- return 1;
-}
-
-
-// Prints information about the given zip archive
-int ZipArchive::Print() {
- unzGoToFirstFile(zip_file_ref_);
-
- unz_global_info gi;
- int result = unzGetGlobalInfo(zip_file_ref_, &gi);
- if (result != UNZ_OK) {
- printf("error %d with zipfile in unzGetGlobalInfo \n", result);
- } else {
- printf(" Length Method Size Ratio Date Time CRC-32 Name\n");
- printf(" ------ ------ ---- ----- ---- ---- ------ ----\n");
-
- for (uint32 i = 0; i < gi.number_entry; ++i) {
- char filename_inzip[MAXFILENAME];
- ZipFileInfo file_info;
- result = unzGetCurrentFileInfo(zip_file_ref_,
- &file_info,
- filename_inzip,
- sizeof(filename_inzip),
- NULL,
- 0,
- NULL,
- 0);
-
- if (result != UNZ_OK) {
- DEBUGLOG("error %d with zipfile in unzGetCurrentFileInfo\n", result);
- break;
- }
-
- file_info.name = filename_inzip;
- file_info.Print(false);
-
- if ((i + 1) < gi.number_entry) {
- result = unzGoToNextFile(zip_file_ref_);
- if (result != UNZ_OK) {
- DEBUGLOG("error %d with zipfile in unzGoToNextFile\n", result);
- break;
- }
- }
- }
-
- DEBUGLOG("\n");
- }
-
- return result;
-}
-
-// Prints information about the given file
-void ZipFileInfo::Print(bool print_header) {
- if (print_header) {
- printf(" Length Method Size Ratio Date Time CRC-32 Name\n");
- printf(" ------ ------ ---- ----- ---- ---- ------ ----\n");
- }
-
- uLong ratio = 0;
- if (uncompressed_size > 0) {
- ratio = (compressed_size * 100) / uncompressed_size;
- }
-
- // display a '*' if the file is encrypted
- char charCrypt = ' ';
- if ((flag & 1) != 0) {
- charCrypt = '*';
- }
-
- const char *string_method;
- if (compression_method == 0) {
- string_method = "Stored";
- } else if (compression_method == Z_DEFLATED) {
- uInt iLevel = (uInt)((flag & 0x6) / 2);
- if (iLevel == 0) {
- string_method = "Defl:N";
- } else if (iLevel == 1) {
- string_method = "Defl:X";
- } else { // i.e., ((iLevel == 2) || (iLevel == 3))
- string_method = "Defl:F"; // 2:fast , 3 : extra fast
- }
- } else {
- string_method = "Unkn. ";
- }
-
- printf("%7lu %6s%c%7lu %3lu%% %2.2lu-%2.2lu-%2.2lu "
- "%2.2lu:%2.2lu %8.8lx %s\n",
- uncompressed_size,
- string_method,
- charCrypt,
- compressed_size,
- ratio,
- (uLong)tmu_date.tm_mon + 1,
- (uLong)tmu_date.tm_mday,
- (uLong)tmu_date.tm_year % 100,
- (uLong)tmu_date.tm_hour,
- (uLong)tmu_date.tm_min,
- (uLong)crc, name.c_str());
-}
-
-bool ZipArchive::IsZipFile(const std::string& filename) {
- int result;
- // If we can open it, it's a zip file.
- ZipArchive archive(filename, &result);
- return result == UNZ_OK;
-}
-
-#ifdef OS_MACOSX
-#pragma mark -
-#endif
-
-// assumes |path| is UTF8 with '/' as the path separator
-void ZipArchive::RemoveLastPathComponent(string *path) {
- // This gets rid of trailing slashes, if any.
- int length = path->size();
- while ((*path)[length - 1] == '/' && length > 0) {
- path->resize(length - 1);
- length = path->size();
- }
-
- string::size_type index = path->find_last_of('/');
-
- if (index == string::npos) {
- *path = "";
- } else {
- path->resize(index + 1); // keep a trailing '/'
- }
-}
-
-// This assumes |path| is UTF8 with '/' as the path separator normally
-// it should be a relative IETF URI path
-void ZipArchive::ConvertRelativeToAbsolutePath(string *rel_path,
- const string &root_path) {
- string base_path(root_path);
- string path(*rel_path);
-
- if (!path.empty() && path[0] == '/') {
- // Path is already absolute.
- return;
- } else {
- while (path.size() >= 2 && path[0] == '.' && path[1] == '/') {
- path = path.substr(2); // strip off leading ./'s
- }
-
- while (path.find("../") == 0) {
- path = path.substr(3); // strip off a leading ../
- RemoveLastPathComponent(&base_path); // strip off a base dir element.
- }
-
- *rel_path = base_path + path;
- }
-}
-
-// This removes leading '/' which is the form that the minizip library
-// likes. The public ZipArchive API expects pathnames to have the
-// leading '/' treating the zip archive as a file-system rooted at '/'
-void ZipArchive::GetActualFilename(const string &filename,
- string *actual_filename) {
- if (filename.find('/') == 0) {
- *actual_filename = filename.substr(1);
- } else {
- *actual_filename = filename;
- }
-}
-
-bool ZipArchive::GetTempFileFromFile(const string &filename,
- string *temp_filename) {
- if (!temp_filename) return false;
-
- size_t data_size;
- char *data = GetFileData(filename, &data_size);
-
- if (data) {
-#if defined(OS_WIN)
- // get the temp directory
- char temp_path[MAX_PATH];
- if (!GetTempPathA(MAX_PATH, temp_path)) {
- return false;
- }
-
- // now generate a GUID
- UUID guid = {0};
- UuidCreate(&guid);
-
- // and format into a wide-string
- char guid_string[37];
- ::_snprintf(
- guid_string, sizeof(guid_string) / sizeof(guid_string[0]),
- "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
- guid.Data1, guid.Data2, guid.Data3,
- guid.Data4[0], guid.Data4[1], guid.Data4[2],
- guid.Data4[3], guid.Data4[4], guid.Data4[5],
- guid.Data4[6], guid.Data4[7]);
-
- // format a complete file path for the temp file
- char fullpath[MAX_PATH];
-
- int dot_position = filename.rfind('.');
- if (dot_position != string::npos) {
- // try to retain the original file suffix (.jpg, etc.)
- ::_snprintf(fullpath, MAX_PATH, "%s%s%s",
- temp_path,
- guid_string,
- filename.substr(dot_position).c_str());
- } else {
- ::_snprintf(fullpath, MAX_PATH, "%s\\%s",
- temp_path,
- guid_string);
- }
-
- FILE *tempfile = fopen(fullpath, "wb");
-
- if (tempfile) {
- fwrite(data, 1, data_size, tempfile);
- fclose(tempfile);
- *temp_filename = fullpath;
- } else {
- return false;
- }
-
-#else
- // get just the final path component
- string::size_type pos = filename.rfind('/');
- if (pos != string::npos) {
- // TODO : need to get "proper" temp dir for user
- // TODO : need to append GUID to filename
- std::string tmp = "/tmp/" + filename.substr(pos + 1);
- FILE *fp = fopen(tmp.c_str(), "w");
-
- if (fp) {
- fwrite(data, 1, data_size, fp);
- fclose(fp);
- *temp_filename = tmp;
- } else {
- return false;
- }
- }
-#endif
- }
-
- return true;
-}
-
-void ZipArchive::DeleteFile(const string &filename) {
-#if defined(OS_WIN)
- ::_unlink(filename.c_str());
-#else
- ::unlink(filename.c_str());
-#endif
-}
diff --git a/o3d/import/cross/zip_archive.h b/o3d/import/cross/zip_archive.h
deleted file mode 100644
index aa3f9bc..0000000
--- a/o3d/import/cross/zip_archive.h
+++ /dev/null
@@ -1,217 +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.
- */
-
-
-// A basic C++ wrapper for a zip file
-// Adapted from miniunz.c from minizip open source code by Gilles Vollant.
-
-/*
- Copyright (C) 1998-2005 Gilles Vollant
-
- This unzip package allow creates .ZIP file, compatible with PKZip 2.04g
- WinZip, InfoZip tools and compatible.
- Multi volume ZipFile (span) are not supported.
- Encryption compatible with pkzip 2.04g only supported
- Old compressions used by old PKZip 1.x are not supported
-
- For uncompress .zip file, look at unzip.h
-
-
- I WAIT FEEDBACK at mail info@winimage.com
- Visit also http://www.winimage.com/zLibDll/unzip.html for evolution
-
- Condition of use and distribution are the same than zlib :
-
- This software is provided 'as-is', without any express or implied
- warranty. In no event will the authors be held liable for any damages
- arising from the use of this software.
-
- Permission is granted to anyone to use this software for any purpose,
- including commercial applications, and to alter it and redistribute it
- freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented; you must not
- claim that you wrote the original software. If you use this software
- in a product, an acknowledgment in the product documentation would be
- appreciated but is not required.
- 2. Altered source versions must be plainly marked as such, and must not be
- misrepresented as being the original software.
- 3. This notice may not be removed or altered from any source distribution.
-
-*/
-
-
-/* Examples Usages:
-
- int result;
- ZipArchive archive("test.zip", &result);
-
- if (result == UNZ_OK) {
- archive.Print();
-
- vector<ZipFileInfo> infolist;
- archive.GetInformationList(&infolist);
-
- // get all file information and print all file names
- for (int i = 0; i < infolist.size(); ++i) {
- printf("[%d] %s\n", i + 1, infolist[i].name.c_str() );
- }
-
- // can get information based on file name in the archive
- // print information about the first file
- if (infolist.size() > 0) {
- ZipFileInfo info;
- result = archive.GetFileInfo(infolist[0].name, &info);
-
- if (result == UNZ_OK) {
- info.Print(true);
- }
- }
-
-
- size_t data_size;
- char *data = archive.GetFileData(infolist[0].name, &data_size);
- printf("data = %p : data_size = %d\n", data, data_size);
-*/
-
-#ifndef O3D_IMPORT_CROSS_ZIP_ARCHIVE_H_
-#define O3D_IMPORT_CROSS_ZIP_ARCHIVE_H_
-
-#include <string>
-#include <vector>
-
-#include "contrib/minizip/unzip.h"
-
-#if defined(OS_WIN)
-// Windows #defines this.
-#undef DeleteFile
-#endif
-
-// structure containing the unz_file_info information plus the file name
-struct ZipFileInfo : public unz_file_info {
- std::string name;
-
- void Print(bool print_header); // prints info to stdout
-};
-
-class ZipArchive {
- public:
- // Returns UNZ_OK in |result| on success
- ZipArchive(const std::string &zip_filename, int *result);
- virtual ~ZipArchive();
-
- // The returned filenames should adhere to the zip archive spec
- // (UTF8 with '/' as the path separator)
- // If the zip file is badly constructed then this assumption may be invalid.
- // returns UNZ_OK on success
- int GetInformationList(std::vector<ZipFileInfo> *infolist);
-
- // Returns information for |filename| in |*info|
- // returns UNZ_OK if successful
- virtual int GetFileInfo(const std::string &filename, ZipFileInfo *info);
-
- // Extracts a single file and returns a pointer to the file's content.
- // Returns NULL if |filename| doesn't match any in the archive
- // or an error occurs. The caller must call free() on the returned pointer
- // the buffer allocated will actually be one byte greater then reported in
- // |size|. And this extra byte is set to zero. This way the data may
- // be interpreted as a string, and doesn't harm anything else.
- //
- virtual char *GetFileData(const std::string &filename, size_t *size);
-
- // |relative_path| is taken to be relative to |root_path|
- // It may contain relative path elements ("../")
- //
- // Extracts a single file and returns a pointer to the file's content.
- // Returns NULL if |filename| doesn't match any in the archive
- // or an error occurs. The caller must call free() on the returned pointer
- //
- virtual char *GetRelativeFileData(const std::string &relative_path,
- const std::string &root_path,
- size_t *size);
-
- // Extracts the entire archive to disk (relative to current working dir)
- // returns UNZ_OK on success
- int Extract();
-
- // Extracts a single file to disk (relative to current working dir)
- // returns UNZ_OK on success
- int ExtractOneFile(const std::string &filename,
- int opt_extract_without_path,
- int opt_overwrite,
- const char *password);
-
- // Extracts |filename| from the archive, saves to a temp file, and sets
- // the path to the temp file in |temp_filename|
- // returns |true| on success
- //
- bool GetTempFileFromFile(const std::string &filename,
- std::string *temp_filename);
-
- // So we can delete the temp file we made
- static void DeleteFile(const std::string &filename);
-
- // Lists content of archive to stdout
- // returns UNZ_OK on success
- int Print();
-
- // Tests the given file to see if it is a zip file.
- // (Added by Google)
- static bool IsZipFile(const std::string& filename);
-
- protected:
- void ChangeFileDate(const char *filename, uLong dosdate, tm_unz tmu_date);
-
- int MyMkDir(const char *dirname);
-
- int MakeDir(const char *newdir);
-
- int ExtractCurrentFile(const int *popt_extract_without_path,
- int *popt_overwrite,
- const char *password);
-
- int DoExtract(int opt_extract_without_path,
- int opt_overwrite,
- const char *password);
-
- void RemoveLastPathComponent(std::string *string);
-
- void ConvertRelativeToAbsolutePath(std::string *path,
- const std::string &root_path);
-
- void GetActualFilename(const std::string &filename,
- std::string *actual_filename);
-
- std::string zip_filename_;
- unzFile zip_file_ref_;
-};
-
-#endif // O3D_IMPORT_CROSS_ZIP_ARCHIVE_H_
diff --git a/o3d/import/import.gyp b/o3d/import/import.gyp
deleted file mode 100644
index c616c3b..0000000
--- a/o3d/import/import.gyp
+++ /dev/null
@@ -1,130 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- },
- 'includes': [
- '../build/common.gypi',
- ],
- 'target_defaults': {
- 'include_dirs': [
- '..',
- '../..',
- '../../<(cgdir)/include',
- '../../<(glewdir)/include',
- '../../<(gtestdir)',
- ],
- },
- 'targets': [
- {
- 'target_name': 'o3dImport',
- 'type': 'static_library',
- 'dependencies': [
- 'archive.gyp:o3dArchive',
- '../../<(antlrdir)/antlr.gyp:antlr3c',
- '../../<(fcolladadir)/fcollada.gyp:fcollada',
- '../../<(jpegdir)/libjpeg.gyp:libjpeg',
- '../../<(pngdir)/libpng.gyp:libpng',
- '../../<(zlibdir)/zlib.gyp:zlib',
- '../compiler/technique/technique.gyp:o3dTechnique',
- '../build/libs.gyp:cg_libs',
- ],
- 'sources': [
- 'cross/collada_conditioner.cc',
- 'cross/collada_conditioner.h',
- 'cross/collada.cc',
- 'cross/collada.h',
- 'cross/collada_zip_archive.cc',
- 'cross/collada_zip_archive.h',
- 'cross/file_output_stream_processor.cc',
- 'cross/file_output_stream_processor.h',
- 'cross/precompile.h',
- 'cross/tar_generator.cc',
- 'cross/tar_generator.h',
- 'cross/targz_generator.cc',
- 'cross/targz_generator.h',
- 'cross/zip_archive.cc',
- 'cross/zip_archive.h',
- ],
- 'conditions' : [
- ['OS == "win"',
- {
- 'msvs_system_include_dirs': [
- '$(DXSDK_DIR)/Include',
- ],
- 'sources': [
- 'win/collada_conditioner_win.cc',
- ],
- },
- ],
- ['OS == "mac"',
- {
- 'sources': [
- 'mac/collada_conditioner_mac.mm',
- ],
- 'include_dirs': [
- '../../third_party/glew/files/include',
- ],
- 'link_settings': {
- 'libraries': [
- '$(SDKROOT)/System/Library/Frameworks/Foundation.framework',
- ],
- },
- },
- ],
- ['OS == "linux"',
- {
- 'sources': [
- 'linux/collada_conditioner_linux.cc',
- ],
- 'include_dirs': [
- '../../third_party/glew/files/include',
- ],
- },
- ],
- ],
- },
- {
- 'target_name': 'o3dSerializationObjects',
- 'type': 'static_library',
- 'sources': [
- 'cross/camera_info.cc',
- 'cross/camera_info.h',
- 'cross/destination_buffer.cc',
- 'cross/destination_buffer.h',
- 'cross/json_object.cc',
- 'cross/json_object.h',
- ],
- },
- {
- 'target_name': 'o3dImportTest',
- 'type': 'none',
- 'direct_dependent_settings': {
- 'sources': [
- 'cross/tar_generator_test.cc',
- 'cross/targz_generator_test.cc',
- ],
- },
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)/unittest_data',
- 'files': [
- 'test_data/crate.dae',
- 'test_data/crate.jpg',
- 'test_data/rock01.tga',
- 'test_data/rock02.tga',
- ],
- },
- ],
- },
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/import/linux/collada_conditioner_linux.cc b/o3d/import/linux/collada_conditioner_linux.cc
deleted file mode 100644
index 640c134..0000000
--- a/o3d/import/linux/collada_conditioner_linux.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 defintions of the functions in the
-// conditioner namespace, which do the bulk of the work of
-// conditioning a Collada file for use in O3D.
-
-#include "import/cross/precompile.h"
-
-#include <sys/wait.h>
-#include <vector>
-
-#include "base/base_paths.h"
-#include "base/file_path.h"
-#include "base/path_service.h"
-#include "core/cross/error.h"
-#include "core/cross/service_locator.h"
-#include "import/cross/collada.h"
-#include "import/cross/collada_conditioner.h"
-
-namespace o3d {
-
-bool ColladaConditioner::CompileHLSL(const String& shader_source,
- const String& vs_entry,
- const String& ps_entry) {
- // The HLSL compiler isn't available on Linux.
- return true;
-}
-
-// Find cgc executable, and run it on the input so that we can get a
-// preprocessed version out.
-bool ColladaConditioner::PreprocessShaderFile(const FilePath& in_filename,
- const FilePath& out_filename) {
- FilePath executable_path;
- if (!PathService::Get(base::DIR_EXE, &executable_path)) {
- O3D_ERROR(service_locator_) << "Couldn't get executable path.";
- return false;
- }
- executable_path = executable_path.Append(FILE_PATH_LITERAL("cgc"));
-
- std::vector<const char*> args;
- args.push_back(executable_path.value().c_str());
- args.push_back("-E");
- args.push_back(in_filename.value().c_str());
- args.push_back("-o");
- args.push_back(out_filename.value().c_str());
- args.push_back(NULL);
- char** args_array = const_cast<char**>(&*args.begin());
-
- pid_t pid = ::fork();
- if (pid < 0) {
- return false;
- }
- if (pid == 0) {
- DLOG(INFO) << "Now invoking '"
- << args_array[0] << " "
- << args_array[1] << " "
- << args_array[2] << " "
- << args_array[3] << " "
- << args_array[4] << "'";
- char *environ[] = {NULL};
- ::execve(args[0], args_array, environ);
- NOTREACHED() << "Problems invoking "
- << args_array[0] << " "
- << args_array[1] << " "
- << args_array[2] << " "
- << args_array[3] << " "
- << args_array[4];
- }
-
- int status;
- ::wait(&status);
- if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
- return true;
- } else {
- if (WIFEXITED(status)) {
- DLOG(ERROR) << "Cgc terminated with status: " << WEXITSTATUS(status);
- }
- if (WIFSIGNALED(status)) {
- DLOG(ERROR) << "Cgc received a signal: " << WTERMSIG(status);
- if (WCOREDUMP(status)) {
- DLOG(ERROR) << "and Cgc dumped a core file.";
- }
- }
- if (WIFSTOPPED(status)) {
- DLOG(ERROR) << "Cgc is stopped on a signal: " << WSTOPSIG(status);
- }
- }
- return false;
-}
-} // end namespace o3d
diff --git a/o3d/import/mac/collada_conditioner_mac.mm b/o3d/import/mac/collada_conditioner_mac.mm
deleted file mode 100644
index cb39e85..0000000
--- a/o3d/import/mac/collada_conditioner_mac.mm
+++ /dev/null
@@ -1,105 +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 defintions of the functions in the
-// conditioner namespace, which do the bulk of the work of
-// conditioning a Collada file for use in O3D.
-
-#include "import/cross/precompile.h"
-
-#include <vector>
-#import <Cocoa/Cocoa.h>
-
-#include "base/base_paths.h"
-#include "base/file_path.h"
-#include "base/path_service.h"
-#include "core/cross/error.h"
-#include "import/cross/collada.h"
-#include "import/cross/collada_conditioner.h"
-#include "utils/cross/file_path_utils.h"
-
-namespace o3d {
-bool ColladaConditioner::CompileHLSL(const String& shader_source,
- const String& vs_entry,
- const String& ps_entry) {
- // The HLSL compiler isn't available on Mac.
- return true;
-}
-
-// Find cgc executable, and run it on the input so that we can get a
-// preprocessed version out.
-bool ColladaConditioner::PreprocessShaderFile(const FilePath& in_filename,
- const FilePath& out_filename) {
- FilePath executable_path;
- if (!PathService::Get(base::DIR_EXE, &executable_path)) {
- O3D_ERROR(service_locator_) << "Couldn't get executable path.";
- return false;
- }
- executable_path = executable_path.Append(FILE_PATH_LITERAL("cgc"));
-
- // Have to convert the file paths to UTF-8
- std::string executable_path_utf8 = FilePathToUTF8(executable_path);
- std::string in_filename_utf8 = FilePathToUTF8(in_filename);
- std::string out_filename_utf8 = FilePathToUTF8(out_filename);
-
- DLOG(INFO) << "Now invoking '"
- << executable_path_utf8 << " -E "
- << in_filename_utf8 << " -o "
- << out_filename_utf8 << "'";
-
- // Now we have to convert the UTF-8 file paths to NSStrings.
- NSString *executable_path_ns =
- [[[NSString alloc] initWithUTF8String:executable_path_utf8.c_str()]
- autorelease];
- NSString *in_filename_ns =
- [[[NSString alloc] initWithUTF8String:in_filename_utf8.c_str()]
- autorelease];
- NSString *out_filename_ns =
- [[[NSString alloc] initWithUTF8String:out_filename_utf8.c_str()]
- autorelease];
-
- NSTask *task = [[[NSTask alloc] init] autorelease];
- [task setLaunchPath:executable_path_ns];
- [task setArguments:[NSArray arrayWithObjects:@"-E", in_filename_ns,
- @"-o", out_filename_ns, nil]];
-
- // We send the output to a pipe, even though the tool doesn't really
- // output anything. This is so that the invocation of the command
- // will be synchronous, and we can be sure that the output file has
- // been written by the time we exit this function.
- NSPipe *pipe = [NSPipe pipe];
- [task setStandardOutput:pipe];
- [task launch];
- [[pipe fileHandleForReading] readDataToEndOfFile];
- return true;
-}
-} // end namespace o3d
diff --git a/o3d/import/test_data/crate.dae b/o3d/import/test_data/crate.dae
deleted file mode 100644
index 36565ffd..0000000
--- a/o3d/import/test_data/crate.dae
+++ /dev/null
@@ -1,239 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-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.
--->
-
-<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">
- <asset>
- <contributor>
- <authoring_tool>Maya2008 | ColladaMaya v3.05B</authoring_tool>
- <comments>ColladaMaya export options: bakeTransforms=0;exportPolygonMeshes=1;bakeLighting=0;isSampling=0;
-curveConstrainSampling=0;removeStaticCurves=1;exportCameraAsLookat=0;
-exportLights=1;exportCameras=1;exportJointsAndSkin=1;
-exportAnimations=1;exportTriangles=0;exportInvisibleNodes=0;
-exportNormals=1;exportTexCoords=1;
-exportVertexColors=1;exportVertexColorsAnimation=0;exportTangents=0;
-exportTexTangents=0;exportConstraints=1;exportPhysics=1;exportXRefs=0;
-dereferenceXRefs=1;cameraXFov=0;cameraYFov=1</comments>
- </contributor>
- <created>2008-03-05T22:10:14Z</created>
- <modified>2008-03-05T22:10:14Z</modified>
- <unit meter="0.01" name="centimeter"/>
- <up_axis>Y_UP</up_axis>
- </asset>
- <library_physics_scenes>
- <physics_scene id="MayaNativePhysicsScene">
- <technique_common>
- <gravity>0 -980 0</gravity>
- <time_step>0.083</time_step>
- </technique_common>
- </physics_scene>
- </library_physics_scenes>
- <library_images>
- <image id="file1" name="file1">
- <init_from>rock01.tga</init_from>
- <extra>
- <technique profile="MAYA">
- <dgnode_type>kFile</dgnode_type>
- <image_sequence>0</image_sequence>
- </technique>
- </extra>
- </image>
- </library_images>
- <library_materials>
- <material id="phong1" name="phong1">
- <instance_effect url="#phong1-fx"/>
- </material>
- </library_materials>
- <library_effects>
- <effect id="phong1-fx">
- <profile_COMMON>
- <newparam sid="file1-surface">
- <surface type="2D">
- <init_from>file1</init_from>
- <format>A8R8G8B8</format>
- </surface>
- </newparam>
- <newparam sid="file1-sampler">
- <sampler2D>
- <source>file1-surface</source>
- <wrap_s>WRAP</wrap_s>
- <wrap_t>WRAP</wrap_t>
- <minfilter>NONE</minfilter>
- <magfilter>NONE</magfilter>
- <mipfilter>NONE</mipfilter>
- </sampler2D>
- </newparam>
- <technique sid="common">
- <phong>
- <emission>
- <color>0 0 0 1</color>
- </emission>
- <ambient>
- <color>0 0 0 1</color>
- </ambient>
- <diffuse>
- <texture texture="file1-sampler" texcoord="TEX0">
- <extra>
- <technique profile="MAYA">
- <wrapU>1</wrapU>
- <wrapV>1</wrapV>
- <mirrorU>0</mirrorU>
- <mirrorV>0</mirrorV>
- <coverageU>1</coverageU>
- <coverageV>1</coverageV>
- <translateFrameU>0</translateFrameU>
- <translateFrameV>0</translateFrameV>
- <rotateFrame>0</rotateFrame>
- <stagger>0</stagger>
- <fast>0</fast>
- <repeatU>1</repeatU>
- <repeatV>1</repeatV>
- <offsetU>0</offsetU>
- <offsetV>0</offsetV>
- <rotateUV>0</rotateUV>
- <noiseU>0</noiseU>
- <noiseV>0</noiseV>
- <blend_mode>NONE</blend_mode>
- </technique>
- </extra>
- </texture>
- </diffuse>
- <specular>
- <color>0.5 0.5 0.5 1</color>
- </specular>
- <shininess>
- <float>20</float>
- </shininess>
- <reflective>
- <color>0 0 0 1</color>
- </reflective>
- <reflectivity>
- <float>0.5</float>
- </reflectivity>
- <transparent opaque="RGB_ZERO">
- <color>0 0 0 1</color>
- </transparent>
- <transparency>
- <float>1</float>
- </transparency>
- </phong>
- <extra>
- <technique profile="FCOLLADA"/>
- </extra>
- </technique>
- </profile_COMMON>
- </effect>
- </library_effects>
- <library_geometries>
- <geometry id="cubeShape" name="cubeShape">
- <mesh>
- <source id="cubeShape-positions" name="position">
- <float_array id="cubeShape-positions-array" count="24">-0.5 -0.5 0.5 0.5 -0.5 0.5 -0.5 0.5 0.5 0.5 0.5 0.5 -0.5 0.5 -0.5 0.5 0.5 -0.5 -0.5 -0.5 -0.5 0.5 -0.5 -0.5</float_array>
- <technique_common>
- <accessor source="#cubeShape-positions-array" count="8" stride="3">
- <param name="X" type="float"/>
- <param name="Y" type="float"/>
- <param name="Z" type="float"/>
- </accessor>
- </technique_common>
- </source>
- <source id="cubeShape-normals" name="normal">
- <float_array id="cubeShape-normals-array" count="72">0 0 1 0 0 1 0 0 1 0 0 1 0 1 0 0 1 0 0 1 0 0 1 0 0 0 -1 0 0 -1 0 0 -1 0 0 -1 0 -1 0 0 -1 0 0 -1 0 0 -1 0 1 0 0 1 0 0 1 0 0 1 0 0 -1 0 0 -1 0 0 -1 0 0 -1 0 0</float_array>
- <technique_common>
- <accessor source="#cubeShape-normals-array" count="24" stride="3">
- <param name="X" type="float"/>
- <param name="Y" type="float"/>
- <param name="Z" type="float"/>
- </accessor>
- </technique_common>
- </source>
- <source id="cubeShape-map1" name="map1">
- <float_array id="cubeShape-map1-array" count="48">1 0 1 0 0 0 0 1 0 0 1 1 0 0 1 1 0 1 1 1 1 0 1 1 0 0 0 1 0 0 1 1 0 0 1 1 1 0 0 1 1 0 1 0 0 1 0 1</float_array>
- <technique_common>
- <accessor source="#cubeShape-map1-array" count="24" stride="2">
- <param name="S" type="float"/>
- <param name="T" type="float"/>
- </accessor>
- </technique_common>
- </source>
- <vertices id="cubeShape-vertices">
- <input semantic="POSITION" source="#cubeShape-positions"/>
- </vertices>
- <polylist material="phong1SG" count="6">
- <input semantic="VERTEX" source="#cubeShape-vertices" offset="0"/>
- <input semantic="NORMAL" source="#cubeShape-normals" offset="1"/>
- <input semantic="TEXCOORD" source="#cubeShape-map1" offset="2" set="0"/>
- <vcount>4 4 4 4 4 4</vcount>
- <p>0 0 14 1 1 1 3 2 17 2 3 19 2 4 2 3 5 18 5 6 5 4 7 22 4 8 4 5 9 20 7 10 7 6 11 23 6 12 6 7 13 21 1 14 9 0 15 8 1 16 16 7 17 10 5 18 11 3 19 3 6 20 12 0 21 0 2 22 15 4 23 13</p>
- </polylist>
- </mesh>
- <extra>
- <technique profile="MAYA">
- <double_sided>1</double_sided>
- <dynamic_attributes>
- <miShadingSamplesOverride short_name="mso" type="bool">0</miShadingSamplesOverride>
- <miShadingSamples short_name="msh" type="float">0</miShadingSamples>
- <miMaxDisplaceOverride short_name="mdo" type="bool">0</miMaxDisplaceOverride>
- <miMaxDisplace short_name="mmd" type="float">0</miMaxDisplace>
- </dynamic_attributes>
- </technique>
- </extra>
- </geometry>
- </library_geometries>
- <library_visual_scenes>
- <visual_scene id="VisualSceneNode" name="crate">
- <node id="cube" name="cube" type="NODE">
- <rotate sid="rotateZ">0 0 1 0</rotate>
- <rotate sid="rotateY">0 1 0 0</rotate>
- <rotate sid="rotateX">1 0 0 0</rotate>
- <instance_geometry url="#cubeShape">
- <bind_material>
- <technique_common>
- <instance_material symbol="phong1SG" target="#phong1">
- <bind_vertex_input semantic="TEX0" input_semantic="TEXCOORD" input_set="0"/>
- </instance_material>
- </technique_common>
- </bind_material>
- </instance_geometry>
- </node>
- <extra>
- <technique profile="FCOLLADA">
- <start_time>0.041666</start_time>
- <end_time>2</end_time>
- </technique>
- </extra>
- </visual_scene>
- </library_visual_scenes>
- <scene>
- <instance_physics_scene url="#MayaNativePhysicsScene"/>
- <instance_visual_scene url="#VisualSceneNode"/>
- </scene>
-</COLLADA>
diff --git a/o3d/import/test_data/crate.jpg b/o3d/import/test_data/crate.jpg
deleted file mode 100644
index 19d3033..0000000
--- a/o3d/import/test_data/crate.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/import/test_data/rock01.tga b/o3d/import/test_data/rock01.tga
deleted file mode 100644
index 666741d..0000000
--- a/o3d/import/test_data/rock01.tga
+++ /dev/null
Binary files differ
diff --git a/o3d/import/test_data/rock02.tga b/o3d/import/test_data/rock02.tga
deleted file mode 100644
index 481f657..0000000
--- a/o3d/import/test_data/rock02.tga
+++ /dev/null
Binary files differ
diff --git a/o3d/import/win/collada_conditioner_win.cc b/o3d/import/win/collada_conditioner_win.cc
deleted file mode 100644
index 0d99319..0000000
--- a/o3d/import/win/collada_conditioner_win.cc
+++ /dev/null
@@ -1,154 +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 platform-specific implementations of certain
-// methods of ColladaConditioner.
-
-#include "import/cross/precompile.h"
-
-#include <d3dx9effect.h>
-
-#include "base/base_paths.h"
-#include "base/file_path.h"
-#include "base/path_service.h"
-#include "core/cross/error.h"
-#include "core/cross/service_locator.h"
-#include "import/cross/collada.h"
-#include "import/cross/collada_conditioner.h"
-
-namespace o3d {
-
-const int kTimeoutInSeconds = 30;
-
-bool ColladaConditioner::CompileHLSL(const String& shader_source,
- const String& vs_entry,
- const String& ps_entry) {
- bool retval = false;
- String shader_source_hlsl = shader_source;
- shader_source_hlsl +=
- "technique t {\n"
- " pass p {\n"
- " VertexShader = compile vs_2_0 " + vs_entry + "();\n"
- " PixelShader = compile ps_2_0 " + ps_entry + "();\n"
- " }\n"
- "};\n";
-
- // Create an effect compiler from the FX file.
- ID3DXEffectCompiler* compiler = NULL;
- ID3DXBuffer* parse_errors = NULL;
- HRESULT hr = ::D3DXCreateEffectCompiler(shader_source_hlsl.c_str(),
- static_cast<UINT>(
- shader_source_hlsl.size()),
- NULL,
- NULL,
- 0,
- &compiler,
- &parse_errors);
-
- if (hr != D3D_OK) {
- const char* error_str = reinterpret_cast<const char*>(
- parse_errors->GetBufferPointer());
- O3D_ERROR(service_locator_) << error_str;
- } else {
- ID3DXBuffer* effect_buffer;
- ID3DXBuffer* error_buffer;
- hr = compiler->CompileEffect(0, &effect_buffer, &error_buffer);
- if (hr != S_OK) {
- const char* compile_errors = reinterpret_cast<const char*>(
- error_buffer->GetBufferPointer());
- O3D_ERROR(service_locator_) << compile_errors;
- } else {
- retval = true;
- if (effect_buffer) effect_buffer->Release();
- if (error_buffer) error_buffer->Release();
- }
- if (compiler) compiler->Release();
- if (parse_errors) parse_errors->Release();
- }
- return retval;
-}
-
-// Find cgc executable, and run it on the input so that we can get a
-// preprocessed version out.
-bool ColladaConditioner::PreprocessShaderFile(const FilePath& in_filename,
- const FilePath& out_filename) {
- FilePath executable_path;
- if (!PathService::Get(base::DIR_EXE, &executable_path)) {
- O3D_ERROR(service_locator_) << "Couldn't get executable path.";
- return false;
- }
- executable_path = executable_path.Append(FILE_PATH_LITERAL("cgc.exe"));
- std::wstring cmd;
- cmd = L"\"" + executable_path.value() + L"\" ";
- cmd += L"-E \"" + in_filename.value() + L"\" ";
- cmd += L"-o \"" + out_filename.value() + L"\"";
-
- // Have to dup the string because CreateProcessW might modify the
- // contents.
- wchar_t* buf = ::_wcsdup(cmd.c_str());
-
- // Initialize structure to zero with default array initializer.
- PROCESS_INFORMATION process_info = {0};
- // Initialize structure to it's size, followed by zeros.
- STARTUPINFO startup_info = {sizeof(STARTUPINFO)};
-
- BOOL success = ::CreateProcessW(NULL,
- buf,
- NULL,
- NULL,
- TRUE,
- 0,
- NULL,
- NULL,
- &startup_info,
- &process_info);
-
- if (success) {
- success = FALSE;
- int exit_code = ::WaitForSingleObject(process_info.hProcess,
- kTimeoutInSeconds * 1000);
- if (exit_code == WAIT_OBJECT_0) {
- success = TRUE;
- } else if (exit_code == WAIT_TIMEOUT) {
- O3D_ERROR(service_locator_) << "Timed out waiting for cg compiler!";
- } else {
- O3D_ERROR(service_locator_) << "Couldn't start cg compiler (cgc.exe).";
- }
- } else {
- O3D_ERROR(service_locator_) << "Couldn't start cg compiler (cgc.exe).";
- }
- ::CloseHandle(process_info.hProcess);
- ::CloseHandle(process_info.hThread);
- ::free(buf);
- return success == TRUE;
-}
-} // end namespace o3d
diff --git a/o3d/installer/installer.gyp b/o3d/installer/installer.gyp
deleted file mode 100644
index dba0f4d..0000000
--- a/o3d/installer/installer.gyp
+++ /dev/null
@@ -1,59 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- },
- 'includes': [
- '../build/branding.gypi',
- '../build/common.gypi',
- ],
- 'targets': [
- {
- 'target_name': 'installer',
- 'type': 'none',
- 'conditions': [
- # We suppress building the installers for third parties using custom
- # branding, because they contain a lot of hard-coded logic that assumes
- # the official branding. A rebranded build must instead be shipped
- # as part of some third-party's own installer.
- ['<(plugin_rebranded) == 0',
- {
- 'conditions': [
- ['OS=="win"',
- {
- 'dependencies': [
- 'win/installer.gyp:installer',
- 'win/installer.gyp:extras_installer',
- ],
- },
- ],
- ['OS=="mac"',
- {
- 'dependencies': [
- 'mac/installer.gyp:disk_image',
- ],
- },
- ],
- ['OS=="linux"',
- {
- 'dependencies': [
- 'linux/installer.gyp:installer',
- ],
- },
- ],
- ],
- }
- ],
- ],
- },
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/installer/linux/debian.in/changelog.in b/o3d/installer/linux/debian.in/changelog.in
deleted file mode 100644
index 5f53aee..0000000
--- a/o3d/installer/linux/debian.in/changelog.in
+++ /dev/null
@@ -1,6 +0,0 @@
-google-o3d (VERSION) unstable; urgency=low
-
- * New upstream release. For historical releases, please see
- http://code.google.com/p/o3d/
-
- -- Jeff Bailey <jeffbailey@google.com> DATE
diff --git a/o3d/installer/linux/debian.in/compat b/o3d/installer/linux/debian.in/compat
deleted file mode 100644
index 1e8b314..0000000
--- a/o3d/installer/linux/debian.in/compat
+++ /dev/null
@@ -1 +0,0 @@
-6
diff --git a/o3d/installer/linux/debian.in/control b/o3d/installer/linux/debian.in/control
deleted file mode 100644
index 53c67a4..0000000
--- a/o3d/installer/linux/debian.in/control
+++ /dev/null
@@ -1,26 +0,0 @@
-Source: google-o3d
-Maintainer: Tristan Schmelcher <tschmelcher@google.com>
-Build-Depends-Indep: debhelper (>= 5), cdbs
-Priority: optional
-Section: web
-Standards-Version: 3.7.3
-
-Package: google-o3d
-Architecture: any
-Depends: ${shlibs:Depends}
-Conflicts: o3d-plugin
-Replaces: o3d-plugin
-Description: Google O3D Plugin
- O3D is an open-source web API for creating rich, interactive 3D applications in
- the browser.
- .
- This package provides the NPAPI browser plugin for running O3D-based web apps.
-
-Package: google-o3d-dbgsym
-Architecture: any
-Depends: google-o3d (= ${Source-Version})
-Description: Google O3D Plugin Debug Symbols
- O3D is an open-source web API for creating rich, interactive 3D applications in
- the browser.
- .
- This package contains symbol files for debugging.
diff --git a/o3d/installer/linux/debian.in/copyright b/o3d/installer/linux/debian.in/copyright
deleted file mode 100644
index 37e8e65..0000000
--- a/o3d/installer/linux/debian.in/copyright
+++ /dev/null
@@ -1,7 +0,0 @@
-This package was debianized by Jeff Bailey <jeffbailey@google.com> on
-Wed, 20 Jan 2010 14:19:30 -0500
-
-Copyright (C) 2010 Google, Inc. under the terms of the new BSD license.
-
-On Debian systems, the complete text of the BSD License can be found in the
-file /usr/share/common-licenses/BSD
diff --git a/o3d/installer/linux/debian.in/debian.gyp b/o3d/installer/linux/debian.in/debian.gyp
deleted file mode 100644
index 63846ac..0000000
--- a/o3d/installer/linux/debian.in/debian.gyp
+++ /dev/null
@@ -1,100 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'includes': [
- '../../../build/common.gypi',
- '../../../build/version.gypi',
- ],
- 'variables': {
- 'INSTALLER_DIR': '<(PRODUCT_DIR)/installer',
- 'DEBIAN_DIR': '<(INSTALLER_DIR)/debian',
- },
- 'conditions': [
- [ 'target_arch=="x64"',
- {
- 'variables': { 'ARCH': 'amd64' }
- },
- {
- 'variables': { 'ARCH': 'i386' }
- },
- ],
- ],
- 'targets': [
- {
- 'target_name': 'debian',
- 'dependencies': [
- '../../../build/libs.gyp:cg_libs',
- '../../../plugin/plugin.gyp:npo3dautoplugin',
- ],
- 'type': 'none',
- 'copies': [
- {
- 'destination': '<(DEBIAN_DIR)',
- 'files': [
- 'compat',
- 'control',
- 'copyright',
- 'google-o3d.install',
- 'google-o3d.links',
- 'google-o3d.lintian-overrides',
- 'rules',
- ],
- },
- ],
- 'actions': [
- {
- 'action_name': 'deb_mk_changelog',
- 'inputs': [
- 'changelog.in',
- 'mk_changelog.py',
- ],
- 'outputs': [
- '<(DEBIAN_DIR)/changelog',
- ],
- 'action': [
- 'python',
- 'mk_changelog.py',
- '--version=<(plugin_version)',
- '--out=<(DEBIAN_DIR)/changelog',
- '--in=changelog.in',
- ],
- },
- {
- 'action_name': 'make_deb',
- 'inputs': [
- '<(PRODUCT_DIR)/libnpo3dautoplugin.so',
- '<(PRODUCT_DIR)/libCg.so',
- '<(PRODUCT_DIR)/libCgGL.so',
- '<(DEBIAN_DIR)/changelog',
- '<(DEBIAN_DIR)/compat',
- '<(DEBIAN_DIR)/control',
- '<(DEBIAN_DIR)/copyright',
- '<(DEBIAN_DIR)/google-o3d.install',
- '<(DEBIAN_DIR)/google-o3d.links',
- '<(DEBIAN_DIR)/google-o3d.lintian-overrides',
- '<(DEBIAN_DIR)/rules',
- ],
- 'action': [
- 'sh',
- '-c',
- 'cd "<(INSTALLER_DIR)" && dpkg-buildpackage '
- '-uc ' # Don't sign the changes file
- '-tc ' # Clean the tree
- '-b ' # Don't produce a source build
- '-a<(ARCH) '
- '-D ' # -a suppresses build-dep checking, so turn it back on
- '-rfakeroot'
- ],
- 'outputs': [
- '<(PRODUCT_DIR)/google-o3d_<(plugin_version)_<(ARCH).changes',
- '<(PRODUCT_DIR)/google-o3d_<(plugin_version)_<(ARCH).deb',
- '<(PRODUCT_DIR)/' +
- 'google-o3d-dbgsym_<(plugin_version)_<(ARCH).deb',
- ],
- },
- ],
- },
- ],
-}
diff --git a/o3d/installer/linux/debian.in/google-o3d.install b/o3d/installer/linux/debian.in/google-o3d.install
deleted file mode 100644
index 5182bd3..0000000
--- a/o3d/installer/linux/debian.in/google-o3d.install
+++ /dev/null
@@ -1,3 +0,0 @@
-../libCgGL.so /opt/google/o3d/lib
-../libCg.so /opt/google/o3d/lib
-../libnpo3dautoplugin.so /opt/google/o3d
diff --git a/o3d/installer/linux/debian.in/google-o3d.links b/o3d/installer/linux/debian.in/google-o3d.links
deleted file mode 100644
index 229103d..0000000
--- a/o3d/installer/linux/debian.in/google-o3d.links
+++ /dev/null
@@ -1,8 +0,0 @@
-opt/google/o3d/libnpo3dautoplugin.so /usr/lib/mozilla/plugins/libnpo3dautoplugin.so
-opt/google/o3d/libnpo3dautoplugin.so /usr/lib/firefox/plugins/libnpo3dautoplugin.so
-opt/google/o3d/libnpo3dautoplugin.so /usr/lib/iceape/plugins/libnpo3dautoplugin.so
-opt/google/o3d/libnpo3dautoplugin.so /usr/lib/iceweasel/plugins/libnpo3dautoplugin.so
-opt/google/o3d/libnpo3dautoplugin.so /usr/lib/xulrunner/plugins/libnpo3dautoplugin.so
-opt/google/o3d/libnpo3dautoplugin.so /usr/lib/midbrowser/plugins/libnpo3dautoplugin.so
-opt/google/o3d/libnpo3dautoplugin.so /usr/lib/xulrunner-addons/plugins/libnpo3dautoplugin.so
-
diff --git a/o3d/installer/linux/debian.in/google-o3d.lintian-overrides b/o3d/installer/linux/debian.in/google-o3d.lintian-overrides
deleted file mode 100644
index 9c08475..0000000
--- a/o3d/installer/linux/debian.in/google-o3d.lintian-overrides
+++ /dev/null
@@ -1,21 +0,0 @@
-# We are not part of Debian/Ubuntu, so installing into /opt is correct.
-google-o3d: dir-or-file-in-opt opt/google/
-
-# We are not part of Debian/Ubuntu, so installing into /opt is correct.
-google-o3d: dir-or-file-in-opt opt/google/o3d/
-
-# We are not part of Debian/Ubuntu, so installing into /opt is correct.
-google-o3d: dir-or-file-in-opt opt/google/o3d/lib/
-
-# We are not part of Debian/Ubuntu, so installing into /opt is correct.
-google-o3d: dir-or-file-in-opt opt/google/o3d/lib/libCg.so
-
-# We are not part of Debian/Ubuntu, so installing into /opt is correct.
-google-o3d: dir-or-file-in-opt opt/google/o3d/lib/libCgGL.so
-
-# We are not part of Debian/Ubuntu, so installing into /opt is correct.
-google-o3d: dir-or-file-in-opt opt/google/o3d/lib/libnpo3dautoplugin.so
-
-# This is needed to find ourselves in /opt
-google-o3d: binary-or-shlib-defines-rpath ./opt/google/o3d/lib/libnpo3dautoplugin.so /opt/google/o3d/lib
-
diff --git a/o3d/installer/linux/debian.in/mk_changelog.py b/o3d/installer/linux/debian.in/mk_changelog.py
deleted file mode 100644
index abebade0..0000000
--- a/o3d/installer/linux/debian.in/mk_changelog.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/python2.4
-#
-# Copyright 2010 Google Inc. All Rights Reserved.
-
-'''Makes a debian/changelog file from a template'''
-
-__author__ = 'jeffbailey@google.com (Jeff Bailey)'
-
-import optparse
-import os
-import subprocess
-import sys
-
-def GetOptionParser():
- '''Constructs and configures an option parser for this script.
-
- Returns:
- An initalised OptionParser instance.
- '''
- parser = optparse.OptionParser('usage: %prog [options]')
- parser.add_option('-v', '--version', dest='version',
- help='O3D version number')
- parser.add_option('-i', '--in', dest='infile',
- help='Input file')
- parser.add_option('-o', '--out', dest='outfile',
- help='Output file')
- return parser
-
-def Main():
- parser = GetOptionParser()
- (options, args) = parser.parse_args()
-
- version = options.version
- outfile = options.outfile
- infile = options.infile
-
- if not version:
- parser.error('Missing --version')
-
- if not outfile:
- parser.error('Missing --out')
-
- if not infile:
- parser.error('Missing --in')
-
- deb_date = os.popen('date -R').read().rstrip()
- sed_exp = "-e 's/VERSION/%s/' -e 's/DATE/%s/'" % (version, deb_date)
-
- sed_cmd = '/bin/sed %s %s >%s' % (sed_exp, infile, outfile)
-
- print sed_cmd
- os.system(sed_cmd)
-
-if __name__ == '__main__':
- sys.exit(Main())
diff --git a/o3d/installer/linux/debian.in/rules b/o3d/installer/linux/debian.in/rules
deleted file mode 100755
index c30869b..0000000
--- a/o3d/installer/linux/debian.in/rules
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/usr/bin/make -f
-
-
-include /usr/share/cdbs/1/rules/debhelper.mk
-
-DEB_DH_STRIP_ARGS=--dbg-package=google-o3d-dbgsym
-
-# Don't call ldconfig. We're in /opt, which isn't supported.
-DEB_DH_MAKESHLIBS_ARGS_google-o3d := -n
-
-# This is needed on Hardy. Lucid will remove this requirement.
-binary-install/google-o3d::
- -dh_lintian -pgoogle-o3d
diff --git a/o3d/installer/linux/generic/setup.sh b/o3d/installer/linux/generic/setup.sh
deleted file mode 100755
index d6e6467..0000000
--- a/o3d/installer/linux/generic/setup.sh
+++ /dev/null
@@ -1,160 +0,0 @@
-#!/bin/sh
-# Installs O3D plugin for Linux.
-#
-# 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.
-
-PATH=$PATH:/sbin:/usr/bin/:/usr/local/bin
-
-CheckArch() {
- # Look for 32 or 64 bit arch from the kernel. If we can not get a read
- # on the arch, we'll go with "unknown".
- ARCH=$(uname -m)
- case $ARCH in
- i?86 | i86*)
- ARCH="32bit";;
- x86_64 | amd64)
- ARCH="64bit";;
- *)
- ARCH="unknown";;
- esac
-
- echo "System architecture mapped to: $ARCH"
-}
-
-
-SetRootUser() {
- # We need to be root (or run as sudo) in order to perform setup.
- USER=$(id -u)
- if [ "$USER" != "0" ]; then
- echo "You must be root (or sudo) to install this package."
- exit 1
- fi
-}
-
-
-UninstallO3d() {
- # Uninstall previous version(s) of O3D before running setup
- if [ -x "/opt/google/o3d/uninstall.sh" ]; then
- echo "Removing previous version(s) of O3D"
- /opt/google/o3d/uninstall.sh
- fi
-}
-
-
-SetupO3d() {
- # Create npapi plugin directories, copy and symlink libs.
- O3D_DIR="/opt/google/o3d"
- LIB_DIR=${O3D_DIR}/lib
-
- PLUGIN_DIRS="/usr/lib/firefox/plugins
- /usr/lib/iceape/plugins
- /usr/lib/iceweasel/plugins
- /usr/lib/midbrowser/plugins
- /usr/lib/mozilla/plugins
- /usr/lib/xulrunner/plugins
- /usr/lib/xulrunner-addons/plugins"
-
- LIBS="libCg.so
- libCgGL.so"
-
- LIBGLEW="libGLEW.so.1.5"
-
- LIB3D="libnpo3dautoplugin.so"
-
- # Check for libGLEW on local system.
- echo -n "Checking for libGLEW..."
- ldconfig -p | grep $LIBGLEW
- if [ $? -ne 0 ]; then
- echo "
- ERROR: The OpenGL Extension Wrangler ($LIBGLEW) was not found on your
- system. This tool is required for O3D. Please install libGLEW using your
- system's package manager."
- exit 1
- else
- echo "ok"
- fi
-
- echo -n "Creating plugin directories..."
- mkdir -p $PLUGIN_DIRS $O3D_DIR $LIB_DIR
- echo "ok"
-
- echo -n "Installing files to $O3D_DIR..."
- install --mode=0644 ${LIB3D} $O3D_DIR
- install --mode=0755 ./uninstall.sh $O3D_DIR
- install --mode=0644 ${LIBS} $LIB_DIR
- echo "ok"
-
- echo -n "Creating symlinks to plugin..."
- for dir in $PLUGIN_DIRS; do
- ln -sf ${O3D_DIR}/${LIB3D} ${dir}/
- done
- echo "ok"
-
- # 64bit only: Check for nspluginwrapper, wrap libnpo3dautoplugin.so if found.
- if [ "$ARCH" = "64bit" ]; then
- echo -n "Attempting to wrap $LIB3D via nspluginwrapper..."
- NSPW=$(which nspluginwrapper)
- if [ -z "$NSPW" ]; then
- echo "
- nspluginwrapper not found. Without nspluginwrapper you will be
- unable to use O3D in 64-bit browsers. Continue installation? (y/N)"
- read answer
- if [ "$answer" = "y" ]; then
- echo "Ok, Installation complete."
- exit 0
- else
- echo "Aborted install at user request."
- exit 1
- fi
- fi
- WRAPPED_PLUGIN_PATH="/usr/lib/mozilla/plugins/npwrapper.libnpo3dautoplugin.so"
- APPS="iceape iceweasel firefox xulrunner midbrowser xulrunner-addons"
- echo -n "Wrapping $LIB3D..."
- $NSPW -i ${O3D_DIR}/${LIB3D}
- echo "ok"
- echo -n "Creating symlinks to npwrapper.libnpo3dautoplugin.so..."
- for app in $APPS; do
- ln -sf $WRAPPED_PLUGIN_PATH /usr/lib/${app}/plugins/
- done
- echo "ok"
- fi
-
- if [ $? -ne 0 ]; then
- echo "Installation failed"
- exit 1
- else
- echo "Installation completed successfully!"
- fi
-}
-
-CheckArch
-SetRootUser
-UninstallO3d
-SetupO3d
diff --git a/o3d/installer/linux/generic/uninstall.sh b/o3d/installer/linux/generic/uninstall.sh
deleted file mode 100755
index d967111..0000000
--- a/o3d/installer/linux/generic/uninstall.sh
+++ /dev/null
@@ -1,111 +0,0 @@
-#!/bin/sh
-# Uninstalls O3D plugin for Linux
-#
-# 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.
-
-PATH=$PATH:/usr/bin/:/usr/local/bin
-
-CheckArch() {
- # Look for 32 or 64 bit arch from the kernel. If we can not get a read
- # on the arch, we'll go with "unknown".
- ARCH=$(uname -m)
- case $ARCH in
- i?86 | i86*)
- ARCH="32bit";;
- x86_64 | amd64)
- ARCH="64bit";;
- *)
- ARCH="unknown";;
- esac
-
- echo "System architecture mapped to: $ARCH"
-}
-
-
-SetRootUser() {
- # We need to be root (or run as sudo) in order to perform uninstall.
- USER=$(id -u)
- if [ "$USER" != "0" ]; then
- echo "You must be root (or sudo) to remove this package."
- exit 1
- fi
-}
-
-
-Uninstall() {
- # Remove O3D plugin, dirs and symlinks.
- O3D_DIR="/opt/google/o3d"
- APPS="mozilla firefox iceape iceweasel xulrunner midbrowser xulrunner-addons"
- LIBS="libCg.so libCgGL.so"
- LIB3D="libnpo3dautoplugin.so"
- LIB3D_WRAPPED="npwrapper.libnpo3dautoplugin.so"
-
- # Prompt user for verification to remove files and directories.
- echo "
- Do you wish to completely remove all previous version(s) of
- the O3D plugin, directories and included libs? (y/N)"
- read answer
- if [ "$answer" = "y" ]; then
- echo -n "Removing O3D plugin and directories..."
- rm ${O3D_DIR}/libnpo3dautoplugin.so
- rm ${O3D_DIR}/lib/libCg.so
- rm ${O3D_DIR}/lib/libCgGL.so
- for app in $APPS; do
- if [ -L "/usr/lib/${app}/plugins/${LIB3D}" ]; then
- rm /usr/lib/${app}/plugins/${LIB3D}
- fi
- done
- rm ${O3D_DIR}/uninstall.sh
- rmdir $O3D_DIR
- echo "ok"
- else
- echo "Aborting at users request"
- exit 0
- fi
-
- # If 64bit, remove the wrapped plugin.
- if [ "$ARCH" = "64bit" ]; then
- echo -n "Removing $LIB3D_WRAPPED..."
- for app in $APPS; do
- if [ -L "/usr/lib/${app}/plugins/${LIB3D_WRAPPED}" ]; then
- rm /usr/lib/${app}/plugins/${LIB3D_WRAPPED}
- fi
- done
- echo "Done. Uninstall complete!"
- exit 0
- fi
-
- echo "Done. Uninstall complete!"
- exit 0
-}
-
-CheckArch
-SetRootUser
-Uninstall
diff --git a/o3d/installer/linux/installer.gyp b/o3d/installer/linux/installer.gyp
deleted file mode 100644
index 91f4898..0000000
--- a/o3d/installer/linux/installer.gyp
+++ /dev/null
@@ -1,21 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'targets': [
- {
- 'target_name': 'installer',
- 'type': 'none',
- 'conditions': [
- [ '"<!(whereis dpkg-buildpackage)" != "dpkg-buildpackage:"',
- {
- 'dependencies': [
- 'debian.in/debian.gyp:debian',
- ],
- },
- ],
- ],
- },
- ],
-}
diff --git a/o3d/installer/mac/O3D_Stats/English.lproj/InfoPlist.strings b/o3d/installer/mac/O3D_Stats/English.lproj/InfoPlist.strings
deleted file mode 100644
index a03f1e5..0000000
--- a/o3d/installer/mac/O3D_Stats/English.lproj/InfoPlist.strings
+++ /dev/null
@@ -1,5 +0,0 @@
-/* Localized versions of Info.plist keys */
-
-
-NSHumanReadableCopyright = "© Google Inc, 2009";
-InstallerSectionTitle = "Statistics";
diff --git a/o3d/installer/mac/O3D_Stats/English.lproj/Localizable.strings b/o3d/installer/mac/O3D_Stats/English.lproj/Localizable.strings
deleted file mode 100644
index 3aef4d4..0000000
--- a/o3d/installer/mac/O3D_Stats/English.lproj/Localizable.strings
+++ /dev/null
@@ -1,3 +0,0 @@
-/* Localized versions of Info.plist keys */
-
-"PaneTitle" = "Statistics";
diff --git a/o3d/installer/mac/O3D_Stats/English.lproj/O3D_Stats.xib b/o3d/installer/mac/O3D_Stats/English.lproj/O3D_Stats.xib
deleted file mode 100644
index e5302b2..0000000
--- a/o3d/installer/mac/O3D_Stats/English.lproj/O3D_Stats.xib
+++ /dev/null
@@ -1,586 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<archive type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="7.03">
- <data>
- <int key="IBDocument.SystemTarget">0</int>
- <string key="IBDocument.SystemVersion">9G55</string>
- <string key="IBDocument.InterfaceBuilderVersion">677</string>
- <string key="IBDocument.AppKitVersion">949.43</string>
- <string key="IBDocument.HIToolboxVersion">353.00</string>
- <object class="NSMutableArray" key="IBDocument.EditedObjectIDs">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <integer value="8"/>
- </object>
- <object class="NSArray" key="IBDocument.PluginDependencies">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
- </object>
- <object class="NSMutableDictionary" key="IBDocument.Metadata">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <object class="NSArray" key="dict.sortedKeys">
- <bool key="EncodedWithXMLCoder">YES</bool>
- </object>
- <object class="NSMutableArray" key="dict.values">
- <bool key="EncodedWithXMLCoder">YES</bool>
- </object>
- </object>
- <object class="NSMutableArray" key="IBDocument.RootObjects" id="995885815">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <object class="NSCustomObject" id="533019728">
- <string key="NSClassName">InstallerSection</string>
- </object>
- <object class="NSCustomObject" id="304932500">
- <string key="NSClassName">FirstResponder</string>
- </object>
- <object class="NSCustomObject" id="521373648">
- <string key="NSClassName">O3D_StatsPane</string>
- </object>
- <object class="NSCustomView" id="878039515">
- <reference key="NSNextResponder"/>
- <int key="NSvFlags">256</int>
- <object class="NSMutableArray" key="NSSubviews">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <object class="NSTextField" id="566423633">
- <reference key="NSNextResponder" ref="878039515"/>
- <int key="NSvFlags">268</int>
- <string key="NSFrame">{{17, 282}, {384, 28}}</string>
- <reference key="NSSuperview" ref="878039515"/>
- <bool key="NSEnabled">YES</bool>
- <object class="NSTextFieldCell" key="NSCell" id="809567365">
- <int key="NSCellFlags">67239424</int>
- <int key="NSCellFlags2">272629760</int>
- <string key="NSContents">Help us improve O3D</string>
- <object class="NSFont" key="NSSupport" id="316557201">
- <string key="NSName">LucidaGrande-Bold</string>
- <double key="NSSize">1.300000e+01</double>
- <int key="NSfFlags">16</int>
- </object>
- <reference key="NSControlView" ref="566423633"/>
- <object class="NSColor" key="NSBackgroundColor" id="222943333">
- <int key="NSColorSpace">6</int>
- <string key="NSCatalogName">System</string>
- <string key="NSColorName">controlColor</string>
- <object class="NSColor" key="NSColor">
- <int key="NSColorSpace">3</int>
- <bytes key="NSWhite">MC42NjY2NjY2OQA</bytes>
- </object>
- </object>
- <object class="NSColor" key="NSTextColor" id="20271656">
- <int key="NSColorSpace">6</int>
- <string key="NSCatalogName">System</string>
- <string key="NSColorName">controlTextColor</string>
- <object class="NSColor" key="NSColor">
- <int key="NSColorSpace">3</int>
- <bytes key="NSWhite">MAA</bytes>
- </object>
- </object>
- </object>
- </object>
- <object class="NSTextField" id="760275755">
- <reference key="NSNextResponder" ref="878039515"/>
- <int key="NSvFlags">268</int>
- <string key="NSFrame">{{17, 217}, {384, 57}}</string>
- <reference key="NSSuperview" ref="878039515"/>
- <bool key="NSEnabled">YES</bool>
- <object class="NSTextFieldCell" key="NSCell" id="386271124">
- <int key="NSCellFlags">67239424</int>
- <int key="NSCellFlags2">272629760</int>
- <string key="NSContents">When you enable statistics, non-personal technical data will be automatically sent to Google to help us improve O3D.</string>
- <object class="NSFont" key="NSSupport" id="223084996">
- <string key="NSName">LucidaGrande</string>
- <double key="NSSize">1.300000e+01</double>
- <int key="NSfFlags">16</int>
- </object>
- <reference key="NSControlView" ref="760275755"/>
- <reference key="NSBackgroundColor" ref="222943333"/>
- <reference key="NSTextColor" ref="20271656"/>
- </object>
- </object>
- <object class="NSMatrix" id="1021698340">
- <reference key="NSNextResponder" ref="878039515"/>
- <int key="NSvFlags">268</int>
- <string key="NSFrame">{{119, 130}, {190, 64}}</string>
- <reference key="NSSuperview" ref="878039515"/>
- <bool key="NSEnabled">YES</bool>
- <int key="NSNumRows">2</int>
- <int key="NSNumCols">1</int>
- <object class="NSMutableArray" key="NSCells">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <object class="NSButtonCell" id="1007645086">
- <int key="NSCellFlags">-2080244224</int>
- <int key="NSCellFlags2">0</int>
- <string key="NSContents">Enable statistics</string>
- <reference key="NSSupport" ref="223084996"/>
- <int key="NSTag">1</int>
- <reference key="NSControlView" ref="1021698340"/>
- <int key="NSButtonFlags">1211912703</int>
- <int key="NSButtonFlags2">128</int>
- <object class="NSButtonImageSource" key="NSAlternateImage" id="899163449">
- <string key="NSImageName">NSRadioButton</string>
- </object>
- <string key="NSAlternateContents"/>
- <string key="NSKeyEquivalent"/>
- <int key="NSPeriodicDelay">200</int>
- <int key="NSPeriodicInterval">25</int>
- </object>
- <object class="NSButtonCell" id="291237987">
- <int key="NSCellFlags">67239424</int>
- <int key="NSCellFlags2">0</int>
- <string key="NSContents">Disable statistics</string>
- <reference key="NSSupport" ref="223084996"/>
- <reference key="NSControlView" ref="1021698340"/>
- <int key="NSButtonFlags">1211912703</int>
- <int key="NSButtonFlags2">128</int>
- <object class="NSImage" key="NSNormalImage">
- <int key="NSImageFlags">549453824</int>
- <string key="NSSize">{18, 18}</string>
- <object class="NSMutableArray" key="NSReps">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <object class="NSArray">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <integer value="0" id="8"/>
- <object class="NSBitmapImageRep">
- <object class="NSData" key="NSTIFFRepresentation">
- <bytes key="NS.bytes">TU0AKgAABRgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAADwRERGLJycnySsrK/A1NTXw
-IyMjyRwcHIsJCQk8AAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFFRUVdVBQUOCoqKj/
-29vb//n5+f/6+vr/2tra/6qqqv9UVFTgHx8fdQAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUZGRl5
-dXV198PDw//8/Pz////////////////////////////U1NT/fHx89yUlJXkAAAAFAAAAAAAAAAAAAAAA
-AAAAAxEREUZqamrmtbW1/+3t7f/+/v7//v7+//7+/v/9/f3//f39//39/f/39/f/xMTE/3d3d+YZGRlG
-AAAAAwAAAAAAAAAAAAAACkJCQqGtra3/xsbG/+vr6//y8vL/9fX1//X19f/z8/P/9fX1//Ly8v/u7u7/
-0tLS/6+vr/9KSkqhAAAACgAAAAAAAAAAAAAAF3h4eN2/v7//z8/P/93d3f/q6ur/7+/v/+/v7//w8PD/
-7e3t/+3t7f/i4uL/zs7O/8XFxf98fHzdAAAAFwAAAAAAAAADAAAAJKSkpPjOzs7/2dnZ/+Dg4P/i4uL/
-5eXl/+bm5v/n5+f/5eXl/+Li4v/e3t7/2tra/9DQ0P+srKz4AAAAJAAAAAMAAAADAAAALrCwsPrW1tb/
-3t7e/+Tk5P/p6en/6+vr/+zs7P/p6en/6+vr/+fn5//k5OT/4ODg/9nZ2f+zs7P6AAAALgAAAAMAAAAD
-AAAALp2dnezg4OD/5eXl/+rq6v/u7u7/8PDw//Dw8P/x8fH/8PDw/+7u7v/q6ur/5ubm/+Hh4f+ZmZns
-AAAALgAAAAMAAAADAAAAJG5ubs/l5eX/6enp/+/v7//y8vL/9vb2//r6+v/5+fn/9/f3//b29v/x8fH/
-6+vr/+Tk5P9ra2vPAAAAJAAAAAMAAAAAAAAAFy4uLpPCwsL67Ozs//Pz8//5+fn//v7+//7+/v/+/v7/
-/v7+//v7+//19fX/8PDw/8LCwvosLCyTAAAAFwAAAAAAAAAAAAAACgAAAENfX1/S5OTk/vn5+f/+/v7/
-///////////////////////////8/Pz/5ubm/l9fX9IAAABDAAAACgAAAAAAAAAAAAAAAwAAABcAAABl
-YmJi3NLS0v3////////////////////////////////V1dX9ZGRk3AAAAGUAAAAXAAAAAwAAAAAAAAAA
-AAAAAAAAAAUAAAAfAAAAZTMzM8KAgIDwv7+//O3t7f/t7e3/v7+//ICAgPAzMzPCAAAAZQAAAB8AAAAF
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAFwAAAEMAAAB3AAAAnwAAALMAAACzAAAAnwAAAHcAAABD
-AAAAFwAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAoAAAAXAAAAJAAAAC4AAAAu
-AAAAJAAAABcAAAAKAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAwAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgEAAAMAAAABABIAAAEB
-AAMAAAABABIAAAECAAMAAAAEAAAFxgEDAAMAAAABAAEAAAEGAAMAAAABAAIAAAERAAQAAAABAAAACAES
-AAMAAAABAAEAAAEVAAMAAAABAAQAAAEWAAMAAAABBxwAAAEXAAQAAAABAAAFEAEcAAMAAAABAAEAAAFS
-AAMAAAABAAEAAAFTAAMAAAAEAAAFzodzAAcAAAwYAAAF1gAAAAAACAAIAAgACAABAAEAAQABAAAMGGFw
-cGwCAAAAbW50clJHQiBYWVogB9YABAADABMALAASYWNzcEFQUEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAPbWAAEAAAAA0y1hcHBs2U706y3Sst1fqit5+wYbUQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAOclhZWgAAASwAAAAUZ1hZWgAAAUAAAAAUYlhZWgAAAVQAAAAUd3RwdAAAAWgAAAAUY2hhZAAA
-AXwAAAAsclRSQwAAAagAAAAOZ1RSQwAAAbgAAAAOYlRSQwAAAcgAAAAOdmNndAAAAdgAAAMSbmRpbgAA
-BOwAAAY+ZGVzYwAACywAAABkZHNjbQAAC5AAAAAubW1vZAAAC8AAAAAoY3BydAAAC+gAAAAtWFlaIAAA
-AAAAAF1KAAA0kQAACCVYWVogAAAAAAAAdCAAALRgAAAjPVhZWiAAAAAAAAAlbAAAFyoAAKfDWFlaIAAA
-AAAAAPNSAAEAAAABFs9zZjMyAAAAAAABDEIAAAXe///zJgAAB5IAAP2R///7ov///aMAAAPcAADAbGN1
-cnYAAAAAAAAAAQHNAABjdXJ2AAAAAAAAAAEBzQAAY3VydgAAAAAAAAABAc0AAHZjZ3QAAAAAAAAAAAAD
-AQAAAQACBAUGBwkKCw0ODxASExQWFxgaGxweHyAiIyQmJygpKywtLzAxMjM1Njc4OTs8PT5AQUJDREZH
-SElKS0xOT1BRUlNUVVZXWFlaW1xdXl9hYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gIGCg4SF
-hoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnZ6foKGio6SlpqanqKmqq6ytra6vsLGysrO0tba3uLi5uru8
-vL2+v8DBwcLDxMXGxsfIycrKy8zNzs7P0NHS0tPU1dbW19jZ2drb3Nzd3t/g4eLi4+Tl5ufo6enq6+zt
-7u/w8fHy8/T19vf4+fr7/P3+/v8AAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR8gISIjJCUnKCkq
-Ky0uLzAxMzQ1Njc4OTo7PD0/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaWltcXV5fYGFiY2RlZmdo
-aWprbG1ub3BxcnN0dXZ3d3h5ent8fH1+f4CBgoKDhIWGh4iIiYqLjI2Oj5CRkpOUlJWWl5iZmpucnZ2e
-n6ChoqOkpaamp6ipqqusra6vsLCxsrO0tba3uLm5uru8vb6/wMHCw8TFx8jJysvMzc7P0NDR0tPU1dbX
-2Nna29ze3+Dh4uPk5ebn6err7O3u7/Hy8/T19vf5+vv8/f7/AAIDAwQFBgcICQoKCwwNDg8QERITFBUW
-FxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODg5Ojs8PT4+P0BBQkNDREVGR0hJSUpLTE1O
-Tk9QUVJSU1RVVVZXWFhZWltbXF1eXl9gYWFiY2RkZWZnZ2hpaWprbGxtbm5vcHFxcnNzdHV1dnd4eHl6
-ent8fH1+fn+AgYGCg4SEhYaHiImJiouMjY6Oj5CRkpOTlJWWl5iZmZqbnJ2en6ChoqOkpaanqKmqq6yt
-rq+xsrO0tba3uLq7vL2+wMHDxMbHycrMzs/R0tTW19nb3d7g4uTm6Ors7vDy9Pb4+vz+/wAAbmRpbgAA
-AAAAAAY2AACXGgAAVjoAAFPKAACJ3gAAJ8IAABaoAABQDQAAVDkAAiuFAAIZmQABeFEAAwEAAAIAAAAA
-AAEABgANABcAIwAxAEAAUgBlAHsAkwCrAMUA4gD/AR8BPwFhAYUBqgHQAfgCIAJLAncCpQLSAwIDMwNl
-A5gDzgQFBD0EdQSvBOsFKQVnBacF6AYqBm4GtQb8B0UHkgfkCDkIkAjnCT4JmAn0ClAKrQsLC2sLygwq
-DIwM8Q1XDcAOKA6SDv4PbA/bEE0QxBE7EbQSMRKwEzITuRREFNAVYBXxFocXHhfAGGIZBBmsGlQa+RuU
-HC4czh1yHhQeux9jIA0gvCFoIhkizyOJJEEk+SW6JnknOygFKMspkypiKzIsASzXLawuhy9gMD4xGzH8
-MtszvzSgNYY2cjdcOEw5OTorOxs8CD0EPfU+6z/nQOFB2ELUQ9VE00XcRttH5EjxSgBLCUwdTTFOUE9v
-UI9Rt1LdVAVVNlZsV6VY4FohW21ct135X09goGH0Y0tkqGYFZ19oxGova5ptCG54b/BxbnLsdG119Xd/
-eQh6knwqfcV/W4D4gpSEO4Xih4CJKorYjIqOOY/jkZuTWJUOlsyYiZpSnB6d4Z+soX+jWqUvpxOo+6rj
-rMuuwLC4sra0rra0uL+60LzfvwDBHcLdxLXGhchYyi7MCs3lz7rRmtOA1WPXR9kq2xPc/97s4M/iveSn
-5o3obupT7ELuLPAM8fLz0PW396H5f/tZ/T3//wAAAAEAAwALABYAJQA3AE0AZQCBAJ8AwQDlAQsBNQFh
-AZABwQH1AisCZAKfAtwDHANfA6MD6gQ0BH8EzQT1BR0FcAXEBhsGdAbPBy0HXAeMB+4IUgi4CSAJVAmK
-CfYKZArVC0cLgQu8DDIMqw0mDaIOIQ6hDyQPqRAvELgQ/RFDEc8SXRLuE4AUFRSrFUMV3RZ5FxcXthhY
-GPwZoRpIGvEbnBxJHPgdqB5bHw8fxSB9ITch8iKwJDAk8yW3Jn4nRigQKNwpqSp5K0osHCzxLccuoC95
-MFUxMzISMvMz1TS5NaA2hzdxOFw5STo4Oyg8Gj4DPvs/9EDuQepD6ETpRexG8Uf3SP9LFEwhTTBOQE9S
-UGZSklOrVMVV4Vb/WB5ZP1phW4Vcq13SXvthUmJ/Y69k4GYSZ0dofGm0au1tZG6ib+FxInJlc6l073Y2
-d396FXtjfLJ+A39VgKmB/4NWhK+GCYjCiiGLgYzjjkePrJESknuT5Ja8mCuZm5sMnH+d9J9qoOGiWqPV
-pVGmz6eOqE6pzqtRrNSuWq/gsWmy8rR+tgu5Kbq6vE294b93wQ7Cp8RBxd3He8kZyrrLisxbzf/Po9FK
-0vHUm9ZF1/HZn9tO3Cbc/96x4GTiGePQ5YjnQegf6Pzquex27jbv9/G583z0X/VC9wj40Pqa/GX+Mf//
-AAAAAQADAAsAJQA3AE0AZQCBAJ8AwQELATUBYQGQAcEB9QIrAmQCnwLcAxwDXwOjA+oENAR/BM0FHQVw
-BcQGGwZ0Bs8HLQeMB+4IUgi4CSAJign2CmQK1QtHC7wMMgyrDSYNog4hDqEPJA+pEC8QuBFDEl0S7hOA
-FBUUqxVDFnkXFxe2GFgY/BpIGvEbnBxJHPgdqB8PH8UgfSE3IfIjbyQwJPMltydGKBAo3Cp5K0osHC3H
-LqAveTEzMhIy8zS5NaA2hzhcOUk6ODwaPQ4+Az/0QO5C6EPoROlG8Uf3SglLFEwhTkBPUlF7UpJUxVXh
-Vv9ZP1phXKtd0mAlYVJjr2TgZhJofGm0au1tZG6ib+FxInJldO92Nnd/eMl6FXyyfgN/VYCpgf+Er4YJ
-h2WIwoohi4GOR4+skRKSe5PklVCWvJgrmZubDJx/nfSfaqDholqj1aVRps+oTqnOq1Gs1K2Xrlqv4LFp
-svK0frYLt5m5Kbnxurq8Tb3hv3fBDsHawqfEQcUPxd3He8hKyRnKusuKzFvN/87Rz6PQdtFK0vHTxtSb
-1kXXG9fx2MjZn9tO3Cbc/93Y3rHfiuBk4hni9ePQ5KzliOZk50HoH+j86drqueuX7HbtVu427xbv9/DX
-8bnymvN89F/1QvYl9wj37PjQ+bX6mvt//GX9S/4x//8AAGRlc2MAAAAAAAAACkNvbG9yIExDRAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAABtbHVjAAAAAAAAAAEAAAAMZW5VUwAAABIAAAAcAEMAbwBsAG8AcgAgAEwAQwBE
-AABtbW9kAAAAAAAABhAAAJxOAAAAAL5zkQAAAAAAAAAAAAAAAAAAAAAAdGV4dAAAAABDb3B5cmlnaHQg
-QXBwbGUgQ29tcHV0ZXIsIEluYy4sIDIwMDUAAAAAA</bytes>
- </object>
- </object>
- </object>
- </object>
- <object class="NSColor" key="NSColor" id="440852265">
- <int key="NSColorSpace">3</int>
- <bytes key="NSWhite">MCAwAA</bytes>
- </object>
- </object>
- <reference key="NSAlternateImage" ref="899163449"/>
- <int key="NSPeriodicDelay">400</int>
- <int key="NSPeriodicInterval">75</int>
- </object>
- </object>
- <string key="NSCellSize">{190, 31}</string>
- <string key="NSIntercellSpacing">{4, 2}</string>
- <int key="NSMatrixFlags">1151868928</int>
- <string key="NSCellClass">NSActionCell</string>
- <object class="NSButtonCell" key="NSProtoCell" id="916470276">
- <int key="NSCellFlags">67239424</int>
- <int key="NSCellFlags2">0</int>
- <string key="NSContents">Radio</string>
- <reference key="NSSupport" ref="223084996"/>
- <int key="NSButtonFlags">1211912703</int>
- <int key="NSButtonFlags2">128</int>
- <object class="NSImage" key="NSNormalImage">
- <int key="NSImageFlags">549453824</int>
- <string key="NSSize">{18, 18}</string>
- <object class="NSMutableArray" key="NSReps">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <object class="NSArray">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <reference ref="8"/>
- <object class="NSBitmapImageRep">
- <object class="NSData" key="NSTIFFRepresentation">
- <bytes key="NS.bytes">TU0AKgAABRgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAMAAAADAAAAAwAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAADwRERGLJycnySsrK/A1NTXw
-IyMjyRwcHIsJCQk8AAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFFRUVdVBQUOCoqKj/
-29vb//n5+f/6+vr/2tra/6qqqv9UVFTgHx8fdQAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUZGRl5
-dXV198PDw//8/Pz////////////////////////////U1NT/fHx89yUlJXkAAAAFAAAAAAAAAAAAAAAA
-AAAAAxEREUZqamrmtbW1/+3t7f/+/v7//v7+//7+/v/9/f3//f39//39/f/39/f/xMTE/3d3d+YZGRlG
-AAAAAwAAAAAAAAAAAAAACkJCQqGtra3/xsbG/+vr6//y8vL/9fX1//X19f/z8/P/9fX1//Ly8v/u7u7/
-0tLS/6+vr/9KSkqhAAAACgAAAAAAAAAAAAAAF3h4eN2/v7//z8/P/93d3f/q6ur/7+/v/+/v7//w8PD/
-7e3t/+3t7f/i4uL/zs7O/8XFxf98fHzdAAAAFwAAAAAAAAADAAAAJKSkpPjOzs7/2dnZ/+Dg4P/i4uL/
-5eXl/+bm5v/n5+f/5eXl/+Li4v/e3t7/2tra/9DQ0P+srKz4AAAAJAAAAAMAAAADAAAALrCwsPrW1tb/
-3t7e/+Tk5P/p6en/6+vr/+zs7P/p6en/6+vr/+fn5//k5OT/4ODg/9nZ2f+zs7P6AAAALgAAAAMAAAAD
-AAAALp2dnezg4OD/5eXl/+rq6v/u7u7/8PDw//Dw8P/x8fH/8PDw/+7u7v/q6ur/5ubm/+Hh4f+ZmZns
-AAAALgAAAAMAAAADAAAAJG5ubs/l5eX/6enp/+/v7//y8vL/9vb2//r6+v/5+fn/9/f3//b29v/x8fH/
-6+vr/+Tk5P9ra2vPAAAAJAAAAAMAAAAAAAAAFy4uLpPCwsL67Ozs//Pz8//5+fn//v7+//7+/v/+/v7/
-/v7+//v7+//19fX/8PDw/8LCwvosLCyTAAAAFwAAAAAAAAAAAAAACgAAAENfX1/S5OTk/vn5+f/+/v7/
-///////////////////////////8/Pz/5ubm/l9fX9IAAABDAAAACgAAAAAAAAAAAAAAAwAAABcAAABl
-YmJi3NLS0v3////////////////////////////////V1dX9ZGRk3AAAAGUAAAAXAAAAAwAAAAAAAAAA
-AAAAAAAAAAUAAAAfAAAAZTMzM8KAgIDwv7+//O3t7f/t7e3/v7+//ICAgPAzMzPCAAAAZQAAAB8AAAAF
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAFwAAAEMAAAB3AAAAnwAAALMAAACzAAAAnwAAAHcAAABD
-AAAAFwAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAoAAAAXAAAAJAAAAC4AAAAu
-AAAAJAAAABcAAAAKAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAwAAAAMAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADQEAAAMAAAABABIAAAEB
-AAMAAAABABIAAAECAAMAAAAEAAAFugEDAAMAAAABAAEAAAEGAAMAAAABAAIAAAERAAQAAAABAAAACAES
-AAMAAAABAAEAAAEVAAMAAAABAAQAAAEWAAMAAAABBxwAAAEXAAQAAAABAAAFEAEcAAMAAAABAAEAAAFS
-AAMAAAABAAEAAAFTAAMAAAAEAAAFwgAAAAAACAAIAAgACAABAAEAAQABA</bytes>
- </object>
- </object>
- </object>
- </object>
- <reference key="NSColor" ref="440852265"/>
- </object>
- <reference key="NSAlternateImage" ref="899163449"/>
- <int key="NSPeriodicDelay">400</int>
- <int key="NSPeriodicInterval">75</int>
- </object>
- <reference key="NSSelectedCell" ref="1007645086"/>
- <reference key="NSBackgroundColor" ref="222943333"/>
- <object class="NSColor" key="NSCellBackgroundColor">
- <int key="NSColorSpace">3</int>
- <bytes key="NSWhite">MQA</bytes>
- </object>
- <reference key="NSFont" ref="316557201"/>
- </object>
- </object>
- <string key="NSFrameSize">{418, 330}</string>
- <reference key="NSSuperview"/>
- <object class="NSMutableString" key="NSClassName">
- <characters key="NS.bytes">NSView</characters>
- </object>
- <string key="NSExtension">NSResponder</string>
- </object>
- <object class="NSCustomObject" id="330240596">
- <string key="NSClassName">NSApplication</string>
- </object>
- </object>
- <object class="IBObjectContainer" key="IBDocument.Objects">
- <object class="NSMutableArray" key="connectionRecords">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <object class="IBConnectionRecord">
- <object class="IBOutletConnection" key="connection">
- <string key="label">firstPane</string>
- <reference key="source" ref="533019728"/>
- <reference key="destination" ref="521373648"/>
- </object>
- <int key="connectionID">6</int>
- </object>
- <object class="IBConnectionRecord">
- <object class="IBOutletConnection" key="connection">
- <string key="label">parentSection</string>
- <reference key="source" ref="521373648"/>
- <reference key="destination" ref="533019728"/>
- </object>
- <int key="connectionID">7</int>
- </object>
- <object class="IBConnectionRecord">
- <object class="IBOutletConnection" key="connection">
- <string key="label">contentView</string>
- <reference key="source" ref="521373648"/>
- <reference key="destination" ref="878039515"/>
- </object>
- <int key="connectionID">9</int>
- </object>
- <object class="IBConnectionRecord">
- <object class="IBOutletConnection" key="connection">
- <string key="label">statsOnRadio</string>
- <reference key="source" ref="521373648"/>
- <reference key="destination" ref="1007645086"/>
- </object>
- <int key="connectionID">19</int>
- </object>
- <object class="IBConnectionRecord">
- <object class="IBOutletConnection" key="connection">
- <string key="label">statsOffRadio</string>
- <reference key="source" ref="521373648"/>
- <reference key="destination" ref="291237987"/>
- </object>
- <int key="connectionID">20</int>
- </object>
- <object class="IBConnectionRecord">
- <object class="IBOutletConnection" key="connection">
- <string key="label">statsRadioMatrix</string>
- <reference key="source" ref="521373648"/>
- <reference key="destination" ref="1021698340"/>
- </object>
- <int key="connectionID">21</int>
- </object>
- <object class="IBConnectionRecord">
- <object class="IBOutletConnection" key="connection">
- <string key="label">statsOnRadio_</string>
- <reference key="source" ref="521373648"/>
- <reference key="destination" ref="1007645086"/>
- </object>
- <int key="connectionID">22</int>
- </object>
- <object class="IBConnectionRecord">
- <object class="IBOutletConnection" key="connection">
- <string key="label">statsOffRadio_</string>
- <reference key="source" ref="521373648"/>
- <reference key="destination" ref="291237987"/>
- </object>
- <int key="connectionID">23</int>
- </object>
- <object class="IBConnectionRecord">
- <object class="IBOutletConnection" key="connection">
- <string key="label">statsRadioMatrix_</string>
- <reference key="source" ref="521373648"/>
- <reference key="destination" ref="1021698340"/>
- </object>
- <int key="connectionID">24</int>
- </object>
- </object>
- <object class="IBMutableOrderedSet" key="objectRecords">
- <object class="NSArray" key="orderedObjects">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <object class="IBObjectRecord">
- <int key="objectID">0</int>
- <object class="NSArray" key="object" id="0">
- <bool key="EncodedWithXMLCoder">YES</bool>
- </object>
- <reference key="children" ref="995885815"/>
- <nil key="parent"/>
- </object>
- <object class="IBObjectRecord">
- <int key="objectID">-2</int>
- <reference key="object" ref="533019728"/>
- <reference key="parent" ref="0"/>
- <string type="base64-UTF8" key="objectName">RmlsZSdzIE93bmVyA</string>
- </object>
- <object class="IBObjectRecord">
- <int key="objectID">-1</int>
- <reference key="object" ref="304932500"/>
- <reference key="parent" ref="0"/>
- <string key="objectName">First Responder</string>
- </object>
- <object class="IBObjectRecord">
- <int key="objectID">5</int>
- <reference key="object" ref="521373648"/>
- <reference key="parent" ref="0"/>
- <string key="objectName">O3D_StatsPane</string>
- </object>
- <object class="IBObjectRecord">
- <int key="objectID">8</int>
- <reference key="object" ref="878039515"/>
- <object class="NSMutableArray" key="children">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <reference ref="566423633"/>
- <reference ref="760275755"/>
- <reference ref="1021698340"/>
- </object>
- <reference key="parent" ref="0"/>
- <string key="objectName">View</string>
- </object>
- <object class="IBObjectRecord">
- <int key="objectID">-3</int>
- <reference key="object" ref="330240596"/>
- <reference key="parent" ref="0"/>
- <string key="objectName">Application</string>
- </object>
- <object class="IBObjectRecord">
- <int key="objectID">11</int>
- <reference key="object" ref="566423633"/>
- <object class="NSMutableArray" key="children">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <reference ref="809567365"/>
- </object>
- <reference key="parent" ref="878039515"/>
- </object>
- <object class="IBObjectRecord">
- <int key="objectID">12</int>
- <reference key="object" ref="809567365"/>
- <reference key="parent" ref="566423633"/>
- </object>
- <object class="IBObjectRecord">
- <int key="objectID">13</int>
- <reference key="object" ref="760275755"/>
- <object class="NSMutableArray" key="children">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <reference ref="386271124"/>
- </object>
- <reference key="parent" ref="878039515"/>
- </object>
- <object class="IBObjectRecord">
- <int key="objectID">14</int>
- <reference key="object" ref="386271124"/>
- <reference key="parent" ref="760275755"/>
- </object>
- <object class="IBObjectRecord">
- <int key="objectID">15</int>
- <reference key="object" ref="1021698340"/>
- <object class="NSMutableArray" key="children">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <reference ref="916470276"/>
- <reference ref="291237987"/>
- <reference ref="1007645086"/>
- </object>
- <reference key="parent" ref="878039515"/>
- </object>
- <object class="IBObjectRecord">
- <int key="objectID">16</int>
- <reference key="object" ref="916470276"/>
- <reference key="parent" ref="1021698340"/>
- </object>
- <object class="IBObjectRecord">
- <int key="objectID">17</int>
- <reference key="object" ref="291237987"/>
- <reference key="parent" ref="1021698340"/>
- </object>
- <object class="IBObjectRecord">
- <int key="objectID">18</int>
- <reference key="object" ref="1007645086"/>
- <reference key="parent" ref="1021698340"/>
- </object>
- </object>
- </object>
- <object class="NSMutableDictionary" key="flattenedProperties">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <object class="NSMutableArray" key="dict.sortedKeys">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <string>-1.IBPluginDependency</string>
- <string>-2.IBPluginDependency</string>
- <string>-3.IBPluginDependency</string>
- <string>11.IBPluginDependency</string>
- <string>12.IBPluginDependency</string>
- <string>13.IBPluginDependency</string>
- <string>14.IBPluginDependency</string>
- <string>15.IBPluginDependency</string>
- <string>16.IBPluginDependency</string>
- <string>17.IBPluginDependency</string>
- <string>18.IBPluginDependency</string>
- <string>5.IBPluginDependency</string>
- <string>5.ImportedFromIB2</string>
- <string>8.IBEditorWindowLastContentRect</string>
- <string>8.IBPluginDependency</string>
- <string>8.ImportedFromIB2</string>
- <string>8.editorWindowContentRectSynchronizationRect</string>
- </object>
- <object class="NSMutableArray" key="dict.values">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
- <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
- <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
- <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
- <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
- <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
- <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
- <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
- <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
- <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
- <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
- <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
- <integer value="1" id="5"/>
- <string>{{336, 964}, {418, 330}}</string>
- <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
- <reference ref="5"/>
- <string>{{467, 510}, {418, 330}}</string>
- </object>
- </object>
- <object class="NSMutableDictionary" key="unlocalizedProperties">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <object class="NSArray" key="dict.sortedKeys">
- <bool key="EncodedWithXMLCoder">YES</bool>
- </object>
- <object class="NSMutableArray" key="dict.values">
- <bool key="EncodedWithXMLCoder">YES</bool>
- </object>
- </object>
- <nil key="activeLocalization"/>
- <object class="NSMutableDictionary" key="localizations">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <object class="NSArray" key="dict.sortedKeys">
- <bool key="EncodedWithXMLCoder">YES</bool>
- </object>
- <object class="NSMutableArray" key="dict.values">
- <bool key="EncodedWithXMLCoder">YES</bool>
- </object>
- </object>
- <nil key="sourceID"/>
- <int key="maxID">24</int>
- </object>
- <object class="IBClassDescriber" key="IBDocument.Classes">
- <object class="NSMutableArray" key="referencedPartialClassDescriptions">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <object class="IBPartialClassDescription">
- <string key="className">O3D_StatsPane</string>
- <string key="superclassName">InstallerPane</string>
- <object class="NSMutableDictionary" key="outlets">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <object class="NSMutableArray" key="dict.sortedKeys">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <string>statsOffRadio_</string>
- <string>statsOnRadio_</string>
- <string>statsRadioMatrix_</string>
- </object>
- <object class="NSMutableArray" key="dict.values">
- <bool key="EncodedWithXMLCoder">YES</bool>
- <string>NSButtonCell</string>
- <string>NSButtonCell</string>
- <string>NSMatrix</string>
- </object>
- </object>
- <object class="IBClassDescriptionSource" key="sourceIdentifier">
- <string key="majorKey">IBProjectSource</string>
- <string key="minorKey">O3D_StatsPane.h</string>
- </object>
- </object>
- </object>
- </object>
- <int key="IBDocument.localizationMode">0</int>
- <string key="IBDocument.LastKnownRelativeProjectPath">../O3D_Stats.xcodeproj</string>
- <int key="IBDocument.defaultPropertyAccessControl">3</int>
- </data>
-</archive>
diff --git a/o3d/installer/mac/O3D_Stats/Info.plist b/o3d/installer/mac/O3D_Stats/Info.plist
deleted file mode 100644
index 181fd45..0000000
--- a/o3d/installer/mac/O3D_Stats/Info.plist
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>CFBundleDevelopmentRegion</key>
- <string>English</string>
- <key>CFBundleExecutable</key>
- <string>${EXECUTABLE_NAME}</string>
- <key>CFBundleIconFile</key>
- <string></string>
- <key>CFBundleIdentifier</key>
- <string>com.google.${PRODUCT_NAME:identifier}</string>
- <key>CFBundleInfoDictionaryVersion</key>
- <string>6.0</string>
- <key>CFBundleName</key>
- <string>${PRODUCT_NAME}</string>
- <key>CFBundlePackageType</key>
- <string>BNDL</string>
- <key>CFBundleShortVersionString</key>
- <string>4.0</string>
- <key>CFBundleSignature</key>
- <string>O3Di</string>
- <key>CFBundleVersion</key>
- <string>2.0</string>
- <key>InstallerSectionTitle</key>
- <string>Statistics</string>
- <key>NSMainNibFile</key>
- <string>O3D_Stats</string>
- <key>NSPrincipalClass</key>
- <string>InstallerSection</string>
-</dict>
-</plist>
diff --git a/o3d/installer/mac/O3D_Stats/InstallerSections.plist b/o3d/installer/mac/O3D_Stats/InstallerSections.plist
deleted file mode 100644
index 0c840f8..0000000
--- a/o3d/installer/mac/O3D_Stats/InstallerSections.plist
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>SectionOrder</key>
- <array>
- <string>Introduction</string>
- <string>ReadMe</string>
- <string>License</string>
- <string>O3D_Stats.bundle</string>
- <string>Target</string>
- <string>PackageSelection</string>
- <string>Install</string>
- </array>
-</dict>
-</plist>
diff --git a/o3d/installer/mac/O3D_Stats/O3D_Stats.xcodeproj/project.pbxproj b/o3d/installer/mac/O3D_Stats/O3D_Stats.xcodeproj/project.pbxproj
deleted file mode 100644
index 961c1c7..0000000
--- a/o3d/installer/mac/O3D_Stats/O3D_Stats.xcodeproj/project.pbxproj
+++ /dev/null
@@ -1,291 +0,0 @@
-// !$*UTF8*$!
-{
- archiveVersion = 1;
- classes = {
- };
- objectVersion = 45;
- objects = {
-
-/* Begin PBXBuildFile section */
- 8D5B49B0048680CD000E48DA /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 089C167DFE841241C02AAC07 /* InfoPlist.strings */; };
- 8D5B49B4048680CD000E48DA /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1058C7ADFEA557BF11CA2CBB /* Cocoa.framework */; };
- B40F7FFC06739E1B0053A16B /* InstallerPlugins.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B40F7FFB06739E1B0053A16B /* InstallerPlugins.framework */; };
- B44C200B06739AE500D31AA1 /* O3D_StatsPane.m in Sources */ = {isa = PBXBuildFile; fileRef = B44C200906739AE500D31AA1 /* O3D_StatsPane.m */; };
- B47CF355067B4E030066DBF6 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = B47CF353067B4E030066DBF6 /* Localizable.strings */; };
- EE3F05FC0DD294BA00EA504A /* O3D_Stats.xib in Resources */ = {isa = PBXBuildFile; fileRef = EE3F05FA0DD294BA00EA504A /* O3D_Stats.xib */; };
-/* End PBXBuildFile section */
-
-/* Begin PBXFileReference section */
- 089C1672FE841209C02AAC07 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = /System/Library/Frameworks/Foundation.framework; sourceTree = "<absolute>"; };
- 089C167EFE841241C02AAC07 /* English */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/InfoPlist.strings; sourceTree = "<group>"; };
- 089C167FFE841241C02AAC07 /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = /System/Library/Frameworks/AppKit.framework; sourceTree = "<absolute>"; };
- 1058C7ADFEA557BF11CA2CBB /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = /System/Library/Frameworks/Cocoa.framework; sourceTree = "<absolute>"; };
- 32DBCF630370AF2F00C91783 /* O3D_Stats_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = O3D_Stats_Prefix.pch; sourceTree = "<group>"; };
- 8D5B49B6048680CD000E48DA /* O3D_Stats.bundle */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = O3D_Stats.bundle; sourceTree = BUILT_PRODUCTS_DIR; };
- 8D5B49B7048680CD000E48DA /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
- B40F7FFB06739E1B0053A16B /* InstallerPlugins.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = InstallerPlugins.framework; path = /System/Library/Frameworks/InstallerPlugins.framework; sourceTree = "<absolute>"; };
- B44C200806739AE500D31AA1 /* O3D_StatsPane.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = O3D_StatsPane.h; sourceTree = "<group>"; };
- B44C200906739AE500D31AA1 /* O3D_StatsPane.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = O3D_StatsPane.m; sourceTree = "<group>"; };
- B47CF354067B4E030066DBF6 /* English */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/Localizable.strings; sourceTree = "<group>"; };
- B4A6B2A60673D523003CD9B2 /* InstallerSections.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = InstallerSections.plist; sourceTree = "<group>"; };
- EE3F05FB0DD294BA00EA504A /* English */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = English; path = English.lproj/O3D_Stats.xib; sourceTree = "<group>"; };
-/* End PBXFileReference section */
-
-/* Begin PBXFrameworksBuildPhase section */
- 8D5B49B3048680CD000E48DA /* Frameworks */ = {
- isa = PBXFrameworksBuildPhase;
- buildActionMask = 2147483647;
- files = (
- 8D5B49B4048680CD000E48DA /* Cocoa.framework in Frameworks */,
- B40F7FFC06739E1B0053A16B /* InstallerPlugins.framework in Frameworks */,
- );
- runOnlyForDeploymentPostprocessing = 0;
- };
-/* End PBXFrameworksBuildPhase section */
-
-/* Begin PBXGroup section */
- 089C166AFE841209C02AAC07 /* InstallerPlugin */ = {
- isa = PBXGroup;
- children = (
- 08FB77AFFE84173DC02AAC07 /* Classes */,
- 32C88E010371C26100C91783 /* Other Sources */,
- 089C167CFE841241C02AAC07 /* Resources */,
- 089C1671FE841209C02AAC07 /* Frameworks and Libraries */,
- 19C28FB8FE9D52D311CA2CBB /* Products */,
- );
- name = InstallerPlugin;
- sourceTree = "<group>";
- };
- 089C1671FE841209C02AAC07 /* Frameworks and Libraries */ = {
- isa = PBXGroup;
- children = (
- 1058C7ACFEA557BF11CA2CBB /* Linked Frameworks */,
- 1058C7AEFEA557BF11CA2CBB /* Other Frameworks */,
- );
- name = "Frameworks and Libraries";
- sourceTree = "<group>";
- };
- 089C167CFE841241C02AAC07 /* Resources */ = {
- isa = PBXGroup;
- children = (
- EE3F05FA0DD294BA00EA504A /* O3D_Stats.xib */,
- B47CF353067B4E030066DBF6 /* Localizable.strings */,
- B4A6B2A60673D523003CD9B2 /* InstallerSections.plist */,
- 8D5B49B7048680CD000E48DA /* Info.plist */,
- 089C167DFE841241C02AAC07 /* InfoPlist.strings */,
- );
- name = Resources;
- sourceTree = "<group>";
- };
- 08FB77AFFE84173DC02AAC07 /* Classes */ = {
- isa = PBXGroup;
- children = (
- B44C200906739AE500D31AA1 /* O3D_StatsPane.m */,
- B44C200806739AE500D31AA1 /* O3D_StatsPane.h */,
- );
- name = Classes;
- sourceTree = "<group>";
- };
- 1058C7ACFEA557BF11CA2CBB /* Linked Frameworks */ = {
- isa = PBXGroup;
- children = (
- 1058C7ADFEA557BF11CA2CBB /* Cocoa.framework */,
- B40F7FFB06739E1B0053A16B /* InstallerPlugins.framework */,
- );
- name = "Linked Frameworks";
- sourceTree = "<group>";
- };
- 1058C7AEFEA557BF11CA2CBB /* Other Frameworks */ = {
- isa = PBXGroup;
- children = (
- 089C1672FE841209C02AAC07 /* Foundation.framework */,
- 089C167FFE841241C02AAC07 /* AppKit.framework */,
- );
- name = "Other Frameworks";
- sourceTree = "<group>";
- };
- 19C28FB8FE9D52D311CA2CBB /* Products */ = {
- isa = PBXGroup;
- children = (
- 8D5B49B6048680CD000E48DA /* O3D_Stats.bundle */,
- );
- name = Products;
- sourceTree = "<group>";
- };
- 32C88E010371C26100C91783 /* Other Sources */ = {
- isa = PBXGroup;
- children = (
- 32DBCF630370AF2F00C91783 /* O3D_Stats_Prefix.pch */,
- );
- name = "Other Sources";
- sourceTree = "<group>";
- };
-/* End PBXGroup section */
-
-/* Begin PBXNativeTarget section */
- 8D5B49AC048680CD000E48DA /* O3D_Stats */ = {
- isa = PBXNativeTarget;
- buildConfigurationList = B44174E608BA33C40065BEDE /* Build configuration list for PBXNativeTarget "O3D_Stats" */;
- buildPhases = (
- 8D5B49AF048680CD000E48DA /* Resources */,
- 8D5B49B1048680CD000E48DA /* Sources */,
- 8D5B49B3048680CD000E48DA /* Frameworks */,
- );
- buildRules = (
- );
- dependencies = (
- );
- name = O3D_Stats;
- productInstallPath = "$(HOME)/Library/Bundles";
- productName = InstallerPlugin;
- productReference = 8D5B49B6048680CD000E48DA /* O3D_Stats.bundle */;
- productType = "com.apple.product-type.bundle";
- };
-/* End PBXNativeTarget section */
-
-/* Begin PBXProject section */
- 089C1669FE841209C02AAC07 /* Project object */ = {
- isa = PBXProject;
- buildConfigurationList = B44174EA08BA33C40065BEDE /* Build configuration list for PBXProject "O3D_Stats" */;
- compatibilityVersion = "Xcode 3.1";
- hasScannedForEncodings = 1;
- mainGroup = 089C166AFE841209C02AAC07 /* InstallerPlugin */;
- projectDirPath = "";
- projectRoot = "";
- targets = (
- 8D5B49AC048680CD000E48DA /* O3D_Stats */,
- );
- };
-/* End PBXProject section */
-
-/* Begin PBXResourcesBuildPhase section */
- 8D5B49AF048680CD000E48DA /* Resources */ = {
- isa = PBXResourcesBuildPhase;
- buildActionMask = 2147483647;
- files = (
- 8D5B49B0048680CD000E48DA /* InfoPlist.strings in Resources */,
- B47CF355067B4E030066DBF6 /* Localizable.strings in Resources */,
- EE3F05FC0DD294BA00EA504A /* O3D_Stats.xib in Resources */,
- );
- runOnlyForDeploymentPostprocessing = 0;
- };
-/* End PBXResourcesBuildPhase section */
-
-/* Begin PBXSourcesBuildPhase section */
- 8D5B49B1048680CD000E48DA /* Sources */ = {
- isa = PBXSourcesBuildPhase;
- buildActionMask = 2147483647;
- files = (
- B44C200B06739AE500D31AA1 /* O3D_StatsPane.m in Sources */,
- );
- runOnlyForDeploymentPostprocessing = 0;
- };
-/* End PBXSourcesBuildPhase section */
-
-/* Begin PBXVariantGroup section */
- 089C167DFE841241C02AAC07 /* InfoPlist.strings */ = {
- isa = PBXVariantGroup;
- children = (
- 089C167EFE841241C02AAC07 /* English */,
- );
- name = InfoPlist.strings;
- sourceTree = "<group>";
- };
- B47CF353067B4E030066DBF6 /* Localizable.strings */ = {
- isa = PBXVariantGroup;
- children = (
- B47CF354067B4E030066DBF6 /* English */,
- );
- name = Localizable.strings;
- sourceTree = "<group>";
- };
- EE3F05FA0DD294BA00EA504A /* O3D_Stats.xib */ = {
- isa = PBXVariantGroup;
- children = (
- EE3F05FB0DD294BA00EA504A /* English */,
- );
- name = O3D_Stats.xib;
- sourceTree = "<group>";
- };
-/* End PBXVariantGroup section */
-
-/* Begin XCBuildConfiguration section */
- B44174E708BA33C40065BEDE /* Debug */ = {
- isa = XCBuildConfiguration;
- buildSettings = {
- COPY_PHASE_STRIP = NO;
- GCC_DYNAMIC_NO_PIC = NO;
- GCC_ENABLE_FIX_AND_CONTINUE = NO;
- GCC_OPTIMIZATION_LEVEL = 0;
- GCC_PRECOMPILE_PREFIX_HEADER = YES;
- GCC_PREFIX_HEADER = O3D_Stats_Prefix.pch;
- INFOPLIST_FILE = Info.plist;
- INSTALL_PATH = "$(HOME)/Library/Bundles";
- PRODUCT_NAME = O3D_Stats;
- WRAPPER_EXTENSION = bundle;
- ZERO_LINK = YES;
- };
- name = Debug;
- };
- B44174E808BA33C40065BEDE /* Release */ = {
- isa = XCBuildConfiguration;
- buildSettings = {
- DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
- GCC_PRECOMPILE_PREFIX_HEADER = YES;
- GCC_PREFIX_HEADER = O3D_Stats_Prefix.pch;
- INFOPLIST_FILE = Info.plist;
- INSTALL_PATH = "$(HOME)/Library/Bundles";
- PRODUCT_NAME = O3D_Stats;
- WRAPPER_EXTENSION = bundle;
- };
- name = Release;
- };
- B44174EB08BA33C40065BEDE /* Debug */ = {
- isa = XCBuildConfiguration;
- buildSettings = {
- ARCHS = i386;
- GCC_C_LANGUAGE_STANDARD = c99;
- GCC_WARN_ABOUT_RETURN_TYPE = YES;
- GCC_WARN_UNUSED_VARIABLE = YES;
- PREBINDING = NO;
- SDKROOT = macosx10.4;
- };
- name = Debug;
- };
- B44174EC08BA33C40065BEDE /* Release */ = {
- isa = XCBuildConfiguration;
- buildSettings = {
- ARCHS = i386;
- GCC_C_LANGUAGE_STANDARD = c99;
- GCC_WARN_ABOUT_RETURN_TYPE = YES;
- GCC_WARN_UNUSED_VARIABLE = YES;
- PREBINDING = NO;
- SDKROOT = macosx10.4;
- };
- name = Release;
- };
-/* End XCBuildConfiguration section */
-
-/* Begin XCConfigurationList section */
- B44174E608BA33C40065BEDE /* Build configuration list for PBXNativeTarget "O3D_Stats" */ = {
- isa = XCConfigurationList;
- buildConfigurations = (
- B44174E708BA33C40065BEDE /* Debug */,
- B44174E808BA33C40065BEDE /* Release */,
- );
- defaultConfigurationIsVisible = 0;
- defaultConfigurationName = Release;
- };
- B44174EA08BA33C40065BEDE /* Build configuration list for PBXProject "O3D_Stats" */ = {
- isa = XCConfigurationList;
- buildConfigurations = (
- B44174EB08BA33C40065BEDE /* Debug */,
- B44174EC08BA33C40065BEDE /* Release */,
- );
- defaultConfigurationIsVisible = 0;
- defaultConfigurationName = Release;
- };
-/* End XCConfigurationList section */
- };
- rootObject = 089C1669FE841209C02AAC07 /* Project object */;
-}
diff --git a/o3d/installer/mac/O3D_Stats/O3D_StatsPane.h b/o3d/installer/mac/O3D_Stats/O3D_StatsPane.h
deleted file mode 100644
index 6889341..0000000
--- a/o3d/installer/mac/O3D_Stats/O3D_StatsPane.h
+++ /dev/null
@@ -1,54 +0,0 @@
-//
-// O3D_StatsPane.h
-// O3D_Stats
-//
-
-/*
- * 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 <Cocoa/Cocoa.h>
-#import <InstallerPlugins/InstallerPlugins.h>
-
-@interface O3D_StatsPane : InstallerPane {
- IBOutlet NSButtonCell *statsOnRadio_;
- IBOutlet NSButtonCell *statsOffRadio_;
- IBOutlet NSMatrix *statsRadioMatrix_;
-}
-
-
-- (BOOL)shouldExitPane:(InstallerSectionDirection)dir;
-
-- (void)didEnterPane:(InstallerSectionDirection)dir;
-
-
-@end
diff --git a/o3d/installer/mac/O3D_Stats/O3D_StatsPane.m b/o3d/installer/mac/O3D_Stats/O3D_StatsPane.m
deleted file mode 100644
index 7e129a0..0000000
--- a/o3d/installer/mac/O3D_Stats/O3D_StatsPane.m
+++ /dev/null
@@ -1,92 +0,0 @@
-//
-// O3D_StatsPane.m
-// O3D_Stats
-//
-
-/*
- * 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 "O3D_StatsPane.h"
-
-#define kPrefString @"O3D_STATS"
-
-
-@implementation O3D_StatsPane
-
-// Read a pref string for current user, but global to all apps.
-static NSString* ReadGlobalPreferenceString(NSString *key) {
- return (NSString *)CFPreferencesCopyValue((CFStringRef)key,
- kCFPreferencesAnyApplication,
- kCFPreferencesCurrentUser,
- kCFPreferencesCurrentHost);
-}
-
-
-// Write a pref string for the current user, but global to all apps.
-static void WriteGlobalPreferenceString(NSString *key,
- NSString *value) {
- CFPreferencesSetValue((CFStringRef)key,
- (CFPropertyListRef)value,
- kCFPreferencesAnyApplication,
- kCFPreferencesCurrentUser,
- kCFPreferencesCurrentHost);
-
- CFPreferencesSynchronize(kCFPreferencesAnyApplication,
- kCFPreferencesCurrentUser,
- kCFPreferencesCurrentHost);
-}
-
-
-- (NSString *)title {
- NSBundle *bundle = [NSBundle bundleForClass:[self class]];
-
- return [bundle localizedStringForKey:@"PaneTitle"
- value:nil
- table:nil];
-}
-
-
-- (BOOL)shouldExitPane:(InstallerSectionDirection)dir {
- BOOL statsOn = [statsRadioMatrix_ selectedCell] == statsOnRadio_;
-
- WriteGlobalPreferenceString(kPrefString, statsOn ? @"YES" : @"NO");
- return YES;
-}
-
-- (void)didEnterPane:(InstallerSectionDirection)dir {
- NSString *value = ReadGlobalPreferenceString(kPrefString);
- BOOL statsOn = ![value isEqualToString:@"NO"];
-
- [statsRadioMatrix_ selectCell: statsOn ? statsOnRadio_ : statsOffRadio_];
-}
-
-
-@end
diff --git a/o3d/installer/mac/O3D_Stats/O3D_Stats_Prefix.pch b/o3d/installer/mac/O3D_Stats/O3D_Stats_Prefix.pch
deleted file mode 100644
index b3c37ff..0000000
--- a/o3d/installer/mac/O3D_Stats/O3D_Stats_Prefix.pch
+++ /dev/null
@@ -1,7 +0,0 @@
-//
-// Prefix header for all source files of the 'InstallerPlugin' target in the 'InstallerPlugin' project.
-//
-
-#ifdef __OBJC__
- #import <Cocoa/Cocoa.h>
-#endif
diff --git a/o3d/installer/mac/O3D_Stats/version.plist b/o3d/installer/mac/O3D_Stats/version.plist
deleted file mode 100644
index a548b4b..0000000
--- a/o3d/installer/mac/O3D_Stats/version.plist
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>BuildVersion</key>
- <string>32</string>
- <key>CFBundleVersion</key>
- <string>1.0</string>
- <key>ProjectName</key>
- <string>DevToolsWizardTemplates</string>
- <key>SourceVersion</key>
- <string>3670000</string>
-</dict>
-</plist>
diff --git a/o3d/installer/mac/installer.gyp b/o3d/installer/mac/installer.gyp
deleted file mode 100644
index 7ff46bf..0000000
--- a/o3d/installer/mac/installer.gyp
+++ /dev/null
@@ -1,57 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- },
- 'includes': [
- '../../build/common.gypi',
- '../../build/version.gypi',
- ],
- 'targets': [
- {
- 'target_name': 'installer',
- 'type': 'none',
- 'dependencies': [
- '../../converter/converter.gyp:o3dConverter',
- '../../breakpad/breakpad.gyp:reporter',
- '../../documentation/documentation.gyp:*',
- '../../plugin/plugin.gyp:npo3dautoplugin',
- '../../samples/samples.gyp:samples',
- ],
- 'postbuilds': [
- {
- 'variables': {
- 'installer_script_path': './make_installer.sh',
- },
- 'postbuild_name': 'Make Installer',
- 'action': ['<(installer_script_path)', '<(plugin_version)',],
- },
- ],
- },
- {
- 'target_name': 'disk_image',
- 'type': 'none',
- 'dependencies': [
- 'installer',
- ],
- 'postbuilds': [
- {
- 'variables': {
- 'disk_image_script_path': './make_disk_image.sh',
- },
- 'postbuild_name': 'Make Disk Image',
- 'action': ['<(disk_image_script_path)', '<(plugin_version)',],
- },
- ],
- },
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/installer/mac/make_disk_image.sh b/o3d/installer/mac/make_disk_image.sh
deleted file mode 100755
index 0022834..0000000
--- a/o3d/installer/mac/make_disk_image.sh
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/bin/bash
-# Makes O3D disk image file.
-# Syntax: make_disk_image version_string
-#
-# 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.
-
-# Make disk image by copying all the bits we need to a new directory and then
-# calling hdiutil to make a dmg of it.
-# Obviously, this should run after the script that makes the installer.
-
-O3D_INTERNAL_DIR="${PROJECT_DIR}/../../../o3d-internal"
-# If the o3d-internal depot is present, make disk image.
-if [ -d "${O3D_INTERNAL_DIR}" ]
-then
- MAC_INSTALLER_DIR="${O3D_INTERNAL_DIR}/mac_installer"
- if [ -d "${MAC_INSTALLER_DIR}" ]
- then
- # Make disk image dir
- IMG_DIR="${BUILT_PRODUCTS_DIR}/DMG_SRC"
- # Delete any existing directory so we can start from scratch.
- rm -rf "${IMG_DIR}"
- mkdir "${IMG_DIR}"
-
- if [ -d "${IMG_DIR}" ]
- then
- # Delete existing dmg if present.
- rm -f "${BUILT_PRODUCTS_DIR}/o3d.dmg"
-
- # Get keystone auto update script.
- cp "${MAC_INSTALLER_DIR}/.keystone_install" "${IMG_DIR}"
-
- # Get O3D install package.
- cp -R "${BUILT_PRODUCTS_DIR}/O3D.mpkg" "${IMG_DIR}"
-
- # Make disk image from the folder we just created.
- hdiutil create -srcfolder "${IMG_DIR}" \
- -size 30mb -ov -fs HFS+ -imagekey zlib-level=9 \
- -volname "O3D ${1}" \
- "${BUILT_PRODUCTS_DIR}/o3d.dmg"
-
- # Delete source folder now we are done.
- rm -rf "${IMG_DIR}"
-
- echo "Mac disk image built"
- else
- echo Could not create dir "${IMG_DIR}".
- fi
- else
- echo Mac installer directory not found.
- fi
-else
- echo External build - not making disk image.
-fi
-
diff --git a/o3d/installer/mac/make_installer.sh b/o3d/installer/mac/make_installer.sh
deleted file mode 100755
index 5b1069c..0000000
--- a/o3d/installer/mac/make_installer.sh
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/bin/bash
-# Makes the O3D installer.
-# Syntax: make_installer version_string
-#
-# 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.
-
-# Make the installer by copying any missing raw materials to the built products
-# directory and then invoking "freeze" on the installer project file.
-# Does not currently use the passed-in version string.
-
-O3D_INTERNAL_DIR="${PROJECT_DIR}/../../../o3d-internal"
-# If the o3d-internal depot is present, make installer.
-if [ -d "${O3D_INTERNAL_DIR}" ]
-then
- MAC_INSTALLER_DIR="${O3D_INTERNAL_DIR}/mac_installer"
- if [ -d "${MAC_INSTALLER_DIR}" ]
- then
- # Get the installer project.
- cp -f "${MAC_INSTALLER_DIR}/o3d.packproj" \
- "${BUILT_PRODUCTS_DIR}"
-
- # Get the keystone post install script.
- cp -f "${MAC_INSTALLER_DIR}/postflight.sh" \
- "${BUILT_PRODUCTS_DIR}"
-
- # Get keystone.
- cp -R -f "${MAC_INSTALLER_DIR}/GoogleSoftwareUpdate.pkg" \
- "${BUILT_PRODUCTS_DIR}"
-
- # Get the installer plug-in which asks about stats collection.
- cp -R -f "${MAC_INSTALLER_DIR}/O3D_Stats.bundle" \
- "${BUILT_PRODUCTS_DIR}"
-
- # Now we have everything in-place, make the installer.
- /usr/local/bin/freeze "${BUILT_PRODUCTS_DIR}/o3d.packproj"
-
- echo Mac installer built.
- else
- echo Mac installer directory not found.
- fi
-else
- echo External build - not making installer.
-fi
-
diff --git a/o3d/installer/win/custom_actions.cc b/o3d/installer/win/custom_actions.cc
deleted file mode 100644
index 8b716e2..0000000
--- a/o3d/installer/win/custom_actions.cc
+++ /dev/null
@@ -1,466 +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.
- */
-
-// Custom installer action which checks if DirectX 9.0c or later is present.
-
-#include <dxdiag.h>
-#include <msi.h>
-#include <msiquery.h>
-#include <shellapi.h>
-#include <shlwapi.h>
-#include <tchar.h>
-#include <strsafe.h> // Must be after tchar.h.
-#include <windows.h>
-#include <atlstr.h>
-#include <Cg/cg.h>
-#include <Cg/cgGL.h>
-#include <GL/glext.h>
-#include <GL/wglew.h>
-
-#include "plugin/win/update_lock.h"
-#include "plugin/cross/plugin_logging.h"
-#include "plugin/cross/plugin_metrics.h"
-
-#pragma comment(linker, "/EXPORT:CheckDirectX=_CheckDirectX@4")
-#pragma comment(linker, "/EXPORT:CheckOpenGL=_CheckOpenGL@4")
-#pragma comment(linker, "/EXPORT:IsSoftwareRunning=_IsSoftwareRunning@4")
-#pragma comment(linker, "/EXPORT:InstallD3DXIfNeeded=_InstallD3DXIfNeeded@4")
-
-
-
-#if 0
-// NOTE: Useful for debugging, but not currently in use. Left here so
-// that I don't have to figure out how to write it again.
-void PopupMsiError(MSIHANDLE installer_handle, int id) {
- PMSIHANDLE record_handle = MsiCreateRecord(1);
- MsiRecordSetInteger(record_handle, 1, id);
- MsiProcessMessage(installer_handle, INSTALLMESSAGE(INSTALLMESSAGE_USER|MB_OK),
- record_handle);
- MsiCloseHandle(record_handle);
-}
-#endif
-
-void WriteToMsiLog(MSIHANDLE installer_handle, TCHAR *message) {
- PMSIHANDLE record_handle = MsiCreateRecord(1);
- MsiRecordSetString(record_handle, 1, message);
- MsiProcessMessage(installer_handle, INSTALLMESSAGE_INFO, record_handle);
- MsiCloseHandle(record_handle);
-}
-
-HRESULT SetRegKeyValueString(HKEY hkey_parent, const TCHAR *key_name,
- const TCHAR *value_name, const TCHAR *value, DWORD value_size) {
- HKEY hkey;
- LONG res = ::RegCreateKeyEx(hkey_parent, key_name, 0, 0,
- REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hkey, NULL);
- HRESULT hr = HRESULT_FROM_WIN32(res);
-
- if (hr != S_OK) {
- return hr;
- }
-
- res = ::RegSetValueEx(hkey, value_name, 0, REG_SZ,
- reinterpret_cast<const BYTE *>(value), value_size);
- hr = HRESULT_FROM_WIN32(res);
-
- ::RegCloseKey(hkey);
- return hr;
-}
-
-HRESULT SetRegKeyValueDWord(HKEY hkey_parent, const TCHAR *key_name,
- const TCHAR *value_name, DWORD value) {
- HKEY hkey;
- LONG res = ::RegCreateKeyEx(hkey_parent, key_name, 0, 0,
- REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hkey, NULL);
- HRESULT hr = HRESULT_FROM_WIN32(res);
-
- if (hr != S_OK) {
- return hr;
- }
-
- res = ::RegSetValueEx(hkey, value_name, 0, REG_DWORD,
- reinterpret_cast<const BYTE *>(&value), sizeof(value));
- hr = HRESULT_FROM_WIN32(res);
-
- ::RegCloseKey(hkey);
- return hr;
-}
-
-void ErrorAndSetUnknownGLDrivers(MSIHANDLE installer_handle, TCHAR *message) {
- WriteToMsiLog(installer_handle, message);
- const int gl_not_found = 99999999;
- o3d::metric_gl_major_version = gl_not_found;
- o3d::metric_gl_minor_version = gl_not_found;
-}
-
-// Returns true on success.
-bool GetOpenGLMetrics(MSIHANDLE installer_handle) {
- WNDCLASS wc;
- if (!GetClassInfo(GetModuleHandle(NULL), L"TEMPGL", &wc)) {
- ZeroMemory(&wc, sizeof(WNDCLASS));
- wc.hInstance = GetModuleHandle(NULL);
- wc.lpfnWndProc = DefWindowProc;
- wc.lpszClassName = L"TEMPGL";
-
- if (!RegisterClass(&wc)) {
- WriteToMsiLog(installer_handle, _T("Failed to register window class."));
- return false;
- }
- }
-
- HWND temp_hwnd = CreateWindow(L"TEMPGL", L"TEMPGL", 0, CW_USEDEFAULT,
- CW_USEDEFAULT, 0, 0, // size 0 by 0
- NULL, NULL, GetModuleHandle(NULL), NULL);
- if (!temp_hwnd) {
- ErrorAndSetUnknownGLDrivers(installer_handle, _T("CreateWindow failed."));
- return false;
- }
-
- // get the device context
- HDC temp_dc = GetDC(temp_hwnd);
- if (!temp_dc) {
- ErrorAndSetUnknownGLDrivers(installer_handle, _T("GetDC failed."));
- return false;
- }
-
- // find default pixel format
- PIXELFORMATDESCRIPTOR pfd;
- ZeroMemory(&pfd, sizeof(PIXELFORMATDESCRIPTOR));
- pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
- pfd.nVersion = 1;
- pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
- int pixelformat = ChoosePixelFormat(temp_dc, &pfd);
-
- // set the pixel format for the dc
- if (!SetPixelFormat(temp_dc, pixelformat, &pfd)) {
- ErrorAndSetUnknownGLDrivers(installer_handle, _T("SetPixelFormat failed."));
- return false;
- }
-
- // create rendering context
- HGLRC gl_context = wglCreateContext(temp_dc);
- if (!gl_context) {
- ErrorAndSetUnknownGLDrivers(installer_handle,
- _T("wglCreateContext failed."));
- return false;
- }
-
- if (!wglMakeCurrent(temp_dc, gl_context)) {
- ErrorAndSetUnknownGLDrivers(installer_handle, _T("wglMakeCurrent failed."));
- return false;
- }
-
- const char *gl_version_string =
- reinterpret_cast<const char*>(glGetString(GL_VERSION));
- const char *gl_extensions_string =
- reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
- if ((gl_version_string == NULL) || (gl_extensions_string == NULL)) {
- ErrorAndSetUnknownGLDrivers(installer_handle, _T("No GL found."));
- return true;
- }
-
- // Get the OpenGL version from the start of the string.
- int gl_major = 0, gl_minor = 0;
- sscanf(gl_version_string, "%u.%u", &gl_major, &gl_minor);
- o3d::metric_gl_major_version = gl_major;
- o3d::metric_gl_minor_version = gl_minor;
-
- // Get the HLSL version.
- // On OpenGL 1.x it's 1.0 if the GL_ARB_shading_language_100 extension is
- // present.
- // On OpenGL 2.x it's a matter of getting the GL_SHADING_LANGUAGE_VERSION
- // string.
- int gl_hlsl_major = 0, gl_hlsl_minor = 0;
- if ((gl_major == 1) &&
- strstr(gl_extensions_string, "GL_ARB_shading_language_100")) {
- gl_hlsl_major = 1;
- gl_hlsl_minor = 0;
- } else if (gl_major >= 2) {
- const char* glsl_version_string =
- reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION));
- if (glsl_version_string) {
- sscanf(glsl_version_string, "%u.%u", &gl_hlsl_major, &gl_hlsl_minor);
- }
- }
- o3d::metric_gl_hlsl_major_version = gl_hlsl_major;
- o3d::metric_gl_hlsl_minor_version = gl_hlsl_minor;
-
- // Clean up
- wglDeleteContext(gl_context);
- ReleaseDC(temp_hwnd, temp_dc);
- DestroyWindow(temp_hwnd);
- UnregisterClass(L"TEMPGL", wc.hInstance);
- return true;
-}
-
-bool GetOpenGLVersion(MSIHANDLE installer_handle) {
- HRESULT hr = CoInitialize(NULL);
- o3d::PluginLogging g_logger;
- stats_report::g_global_metrics.Initialize();
- // Get OpenGL stats logged
- if (!GetOpenGLMetrics(installer_handle)) {
- return false;
- }
- if (!g_logger.ProcessMetrics(true, false, false)) {
- return false;
- }
- stats_report::g_global_metrics.Uninitialize();
- return true;
-}
-
-// Retrieve the currently installed version of DirectX using a COM
-// DxDiagProvider. Returns 0 on error.
-DWORD GetDirectXVersion() {
- HRESULT hr;
- DWORD directx_version = 0;
- DWORD directx_version_major = 0;
- DWORD directx_version_minor = 0;
- TCHAR directx_version_letter = ' ';
-
- bool cleanup_com = false;
-
- bool success_getting_major = false;
- bool success_getting_minor = false;
- bool success_getting_letter = false;
-
- // Init COM. COM may fail if its already been inited with a different
- // concurrency model. And if it fails you shouldn't release it.
- hr = CoInitialize(NULL);
- cleanup_com = SUCCEEDED(hr);
-
- // Get an IDxDiagProvider
- IDxDiagProvider* dx_diag_provider = NULL;
- hr = CoCreateInstance(CLSID_DxDiagProvider,
- NULL,
- CLSCTX_INPROC_SERVER,
- IID_IDxDiagProvider,
- reinterpret_cast<LPVOID*>(&dx_diag_provider));
- if (SUCCEEDED(hr)) {
- // Fill out a DXDIAG_INIT_PARAMS struct
- DXDIAG_INIT_PARAMS dx_diag_init_param;
- ZeroMemory(&dx_diag_init_param, sizeof(DXDIAG_INIT_PARAMS));
- dx_diag_init_param.dwSize = sizeof(DXDIAG_INIT_PARAMS);
- dx_diag_init_param.dwDxDiagHeaderVersion = DXDIAG_DX9_SDK_VERSION;
- dx_diag_init_param.bAllowWHQLChecks = false;
- dx_diag_init_param.pReserved = NULL;
-
- // Init the DxDiagProvider
- hr = dx_diag_provider->Initialize(&dx_diag_init_param);
- if (SUCCEEDED(hr)) {
- IDxDiagContainer* dx_diag_root = NULL;
- IDxDiagContainer* dx_diag_system_info = NULL;
-
- // Get the DxDiag root container
- hr = dx_diag_provider->GetRootContainer(&dx_diag_root);
- if (SUCCEEDED(hr)) {
- // Get the object called DxDiag_SystemInfo
- hr = dx_diag_root->GetChildContainer(L"DxDiag_SystemInfo",
- &dx_diag_system_info);
- if (SUCCEEDED(hr)) {
- VARIANT var;
- VariantInit(&var);
-
- // Get the "dwDirectXVersionMajor" property
- hr = dx_diag_system_info->GetProp(L"dwDirectXVersionMajor", &var);
- if (SUCCEEDED(hr) && var.vt == VT_UI4) {
- directx_version_major = var.ulVal;
- success_getting_major = true;
- }
- VariantClear(&var);
-
- // Get the "dwDirectXVersionMinor" property
- hr = dx_diag_system_info->GetProp(L"dwDirectXVersionMinor", &var);
- if (SUCCEEDED(hr) && var.vt == VT_UI4) {
- directx_version_minor = var.ulVal;
- success_getting_minor = true;
- }
- VariantClear(&var);
-
- // Get the "szDirectXVersionLetter" property
- hr = dx_diag_system_info->GetProp(L"szDirectXVersionLetter", &var);
- if (SUCCEEDED(hr) && var.vt == VT_BSTR &&
- SysStringLen(var.bstrVal) != 0) {
-#ifdef UNICODE
- directx_version_letter = var.bstrVal[0];
-#else
- char strDestination[10];
- WideCharToMultiByte(CP_ACP, 0, var.bstrVal, -1, strDestination,
- 10 * sizeof(CHAR), NULL, NULL);
- directx_version_letter =
- static_cast<char>(tolower(strDestination[0]));
-#endif
- success_getting_letter = true;
- }
- VariantClear(&var);
-
- // If it all worked right, then mark it down
- if (success_getting_major && success_getting_minor &&
- success_getting_letter) {
- // Convert to hex representation.
- directx_version = directx_version_major;
- directx_version <<= 8;
- directx_version += directx_version_minor;
- directx_version <<= 8;
- if (directx_version_letter >= 'a' &&
- directx_version_letter <= 'z') {
- directx_version += (directx_version_letter - 'a') + 1;
- }
- }
- dx_diag_system_info->Release();
- }
- dx_diag_root->Release();
- }
- }
- dx_diag_provider->Release();
- }
-
- if (cleanup_com) {
- CoUninitialize();
- }
- return directx_version;
-}
-
-HRESULT SetCustomUpdateError(MSIHANDLE installer_handle,
- DWORD error_code,
- CString message) {
- wchar_t key_name[256];
- DWORD key_size = 256;
- UINT ret = MsiGetProperty(installer_handle, L"GoogleUpdateResultKey",
- reinterpret_cast<LPWSTR>(&key_name), &key_size);
- if (ret != ERROR_SUCCESS) {
- WriteToMsiLog(installer_handle, _T("MsiGetProperty failed!"));
- return ERROR_READ_FAULT;
- } else {
- HRESULT hr = SetRegKeyValueDWord(HKEY_CURRENT_USER, key_name,
- _T("InstallerResult"), 1 /* FAILED_CUSTOM_ERROR */);
- if (hr != S_OK) {
- WriteToMsiLog(installer_handle, _T("SetRegKeyValueDWord failed!"));
- return hr;
- }
- hr = SetRegKeyValueDWord(HKEY_CURRENT_USER, key_name,
- _T("InstallerError"), error_code);
- if (hr != S_OK) {
- WriteToMsiLog(installer_handle, _T("SetRegKeyValueDWord failed!"));
- return hr;
- }
- hr = SetRegKeyValueString(HKEY_CURRENT_USER, key_name,
- _T("InstallerResultUIString"),
- message, message.GetLength() * sizeof(TCHAR));
- if (hr != S_OK) {
- WriteToMsiLog(installer_handle, _T("SetRegKeyValueString failed!"));
- return hr;
- }
- }
- return S_OK;
-}
-
-// Check whether DirectX version 9.0c or higher is installed and
-// notify the installer about the result.
-extern "C" UINT __stdcall CheckDirectX(MSIHANDLE installer_handle) {
- // Get current version.
- DWORD installed_version = GetDirectXVersion();
-
- // 0x090003 == 9.0c
- if (installed_version >= 0x090003) {
- // Set msi property to let the installer know that the currently
- // installed version of dx is new enough.
- UINT ret = MsiSetProperty(installer_handle, L"DIRECTX_9_0_C_INSTALLED",
- L"1");
- } else {
- // TODO: This will need i18n when we do that for the rest of o3d.
- CString message =
- _T("O3D needs an installation of DirectX 9.0 revision C or later.\n")
- _T("\nPlease download the latest version of DirectX from ")
- _T("http://www.microsoft.com/download.");
- DWORD error_code = 1603; /* Fatal error during installation */
- if (SetCustomUpdateError(installer_handle, error_code, message) != S_OK) {
- return ERROR_WRITE_FAULT;
- }
- }
- return ERROR_SUCCESS;
-}
-
-// Check the version of OpenGL installed and save a registry key
-extern "C" UINT __stdcall CheckOpenGL(MSIHANDLE installer_handle) {
- if (!GetOpenGLVersion(installer_handle)) {
- WriteToMsiLog(installer_handle, _T("GetOpenGLVersion failed!"));
- }
- return ERROR_SUCCESS;
-}
-
-// Check to see whether the plugin is currently running. If it is, we can't
-// update the plugin. The installer will check for the SOFTWARE_RUNNING flag
-// and exit if it's trying to do a silent update. Knowing that it's failed this
-// time, it'll try again later.
-extern "C" UINT __stdcall IsSoftwareRunning(MSIHANDLE installer_handle) {
- if (!update_lock::CanUpdate()) {
- MsiSetProperty(installer_handle, L"SOFTWARE_RUNNING", L"1");
- }
-
- return ERROR_SUCCESS;
-}
-
-// TODO: Get security to review this method in particular, as it runs an
-// executable in a predictable location.
-extern "C" UINT __stdcall InstallD3DXIfNeeded(MSIHANDLE installer_handle) {
- HANDLE handle = ::LoadLibrary(L"d3dx9_36.dll");
- if (handle) {
- ::CloseHandle(handle);
- } else {
- // 2 output characters per byte in the input due to hex format, then one
- // extra for the NUL.
- TCHAR idString[sizeof(DWORD) * 2 + 1];
- HRESULT hr = ::StringCchPrintf(idString, sizeof(idString) / sizeof(TCHAR),
- _T("%x"), ::GetCurrentProcessId());
- if (!SUCCEEDED(hr)) {
- WriteToMsiLog(installer_handle, _T("StringCchPrintf failed!"));
- return ERROR_GEN_FAILURE;
- }
- TCHAR getextras_path[] = _T("%TEMP%\\Extras\\getextras.exe");
- SHELLEXECUTEINFO info = {0};
- info.cbSize = sizeof(info);
- info.fMask = SEE_MASK_DOENVSUBST | SEE_MASK_FLAG_NO_UI | SEE_MASK_UNICODE;
- info.lpVerb = _T("open");
- info.lpFile = getextras_path;
- info.lpParameters = idString;
- // SW_HIDE is a wild guess, but seems as good as any.
- info.nShow = SW_HIDE;
- info.lpDirectory = NULL;
- if (!::ShellExecuteEx(&info)) {
- WriteToMsiLog(installer_handle,
- _T("ShellExecuteEx of getextras.exe failed."));
- WriteToMsiLog(installer_handle,
- _T("Path was:"));
- WriteToMsiLog(installer_handle, getextras_path);
- return ERROR_GEN_FAILURE;
- }
- }
- return ERROR_SUCCESS;
-}
diff --git a/o3d/installer/win/docs.url b/o3d/installer/win/docs.url
deleted file mode 100644
index 54d3edc..0000000
--- a/o3d/installer/win/docs.url
+++ /dev/null
@@ -1,4 +0,0 @@
-[InternetShortcut]
-URL=http://go.corp.google.com/o3d
-IconFile=http://www.google.com/favicon.ico
-IconIndex=1
diff --git a/o3d/installer/win/driver_blacklist.txt b/o3d/installer/win/driver_blacklist.txt
deleted file mode 100644
index 1b45e75..0000000
--- a/o3d/installer/win/driver_blacklist.txt
+++ /dev/null
@@ -1,12 +0,0 @@
-# This file contains the GUIDs of blacklisted drivers as unsigned ints in hex.
-# File format:
-# # comments out to the end of a line.
-# Lines should be no longer than 256 characters. Still, to keep things
-# simple, just put one GUID per line.
-# Whitespace is ignored except in that it separates GUIDs.
-# No other characters are legal.
-
-# Sample GUID [DO NOT UNCOMMENT THIS LINE]:
-# 0xd7b71e3e
-
-# Actual blacklisted drivers:
diff --git a/o3d/installer/win/installer.gyp b/o3d/installer/win/installer.gyp
deleted file mode 100644
index 0f100d3..0000000
--- a/o3d/installer/win/installer.gyp
+++ /dev/null
@@ -1,328 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- 'wixdir': 'third_party\\wix_2_0_4221\\files',
- 'dx_redist_path': '../../../o3d-internal/third_party/dx_nov_2007_redist',
- 'dx_redist_exists': '<!(python ../../build/file_exists.py ../../../o3d-internal/third_party/dx_nov_2007_redist/d3dx9_36.dll)',
- 'guidgen': '..\\..\\nbguidgen\\win\\nbguidgen.exe',
-
- # Unique guid for o3d namespace
- 'o3d_namespace_guid': 'B445DBAE-F5F9-435A-9A9B-088261CDF00A',
-
- # Changing the following values would break upgrade paths, so we
- # hard-code the values instead of generating them.
- 'bad_old_o3d_upgrade_code': 'dc819ed6-4155-3cff-b580-45626aed5848',
- 'o3d_extras_google_update_guid': '{34B2805D-C72C-4f81-AED5-5A22D1E092F1}',
- 'o3d_extras_upgrade_code': 'c271f2f0-c7ad-3bc9-8216-211436aa2244',
- 'o3d_npp_google_update_guid': '{70308795-045C-42da-8F4E-D452381A7459}',
- 'o3d_npp_upgrade_code': '0f098121-2876-3c23-bd4c-501220ecbb42',
-
- # We don't actually want the extras version to update by itself;
- # it should change only when we actually add something to the
- # installer or change the d3dx9 version. This version is
- # therefore independent of the o3d plugin and sdk versions.
- 'extrasversion': '0,1,1,0',
- 'dotextrasversion': '0.1.1.0',
-
- # Registry paths for Google Update
- 'google_update_reg_path': 'Software\\Google\\Update\\Clients\\',
- 'google_update_state_reg_path': 'Software\\Google\\Update\\ClientState\\',
- },
- 'includes': [
- '../../build/common.gypi',
- '../../build/version.gypi',
- ],
- 'targets': [
- {
- 'target_name': 'cactions',
- 'type': 'shared_library',
- 'sources': [
- 'custom_actions.cc',
- ],
- 'dependencies': [
- '../../../base/base.gyp:base',
- '../../build/libs.gyp:cg_libs',
- '../../build/libs.gyp:gl_libs',
- '../../plugin/plugin.gyp:o3dPluginLogging',
- '../../statsreport/statsreport.gyp:o3dStatsReport',
- ],
- 'include_dirs': [
- '../..',
- '../../..',
- '../../<(glewdir)/include',
- '../../<(cgdir)/include',
- '<(INTERMEDIATE_DIR)',
- ],
- 'msvs_system_include_dirs': [
- '$(DXSDK_DIR)/Include',
- ],
- 'defines': [
- 'NOMINMAX',
- 'WIN32',
- 'WIN32_LEAN_AND_MEAN',
- '_ATL_SECURE_NO_WARNINGS',
- '_CRT_SECURE_NO_DEPRECATE',
- '_UNICODE', # turn on unicode
- '_WIN32_WINNT=0x0600',
- '_WINDOWS',
- ],
- 'libraries': [
- '-ladvapi32.lib',
- '"$(DXSDK_DIR)/Lib/x86/dxguid.lib"',
- '-lmsi.lib',
- '-lole32.lib',
- '-loleaut32.lib',
- '-lshell32.lib',
- '-lshlwapi.lib',
- '-luser32.lib',
- ],
- # Disable the #pragma deprecated warning because
- # ATL seems to use deprecated CRT libs.
- 'msvs_disabled_warnings': [4995],
- 'msvs_configuration_attributes': {
- 'UseOfATL': '1', # 1 = static link to ATL, 2 = dynamic link
- },
- },
- {
- 'target_name': 'installer',
- 'type': 'none',
- 'variables': {
- 'candle_exe': '../../../<(wixdir)/candle.exe',
- 'light_exe': '../../../<(wixdir)/light.exe',
- 'custom_actions_path': '<(PRODUCT_DIR)/cactions.dll',
- 'd3dx_guid': '<!(<(guidgen) <(o3d_namespace_guid) '
- 'd3dx-<!(python ../../plugin/version_info.py '
- '--set_version=<(plugin_version) --commaversion))',
- 'dbl_path': '../../installer/win/driver_blacklist.txt',
- 'dx_redist_guid': '<!(<(guidgen) <(o3d_namespace_guid) '
- 'dx_redist-<!(python ../../plugin/version_info.py '
- '--set_version=<(plugin_version) --commaversion))',
- 'get_extras_path': '<(PRODUCT_DIR)/getextras.exe',
- 'ieplugin_path': '<(PRODUCT_DIR)/o3d_host.dll',
- 'include_software_renderer':
- '<!(python ../../build/file_exists.py '
- '../../../<(swiftshaderdir)/swiftshader_d3d9.dll)',
- 'npplugin_path': '<(PRODUCT_DIR)/npo3dautoplugin.dll',
- 'o3d_driver_blacklist_guid': '<!(<(guidgen) <(o3d_namespace_guid) '
- 'o3d_driver_blacklist-<!(python ../../plugin/version_info.py '
- '--set_version=<(plugin_version) --commaversion))',
- 'o3d_get_extras_guid':
- '<!(<(guidgen) <(o3d_namespace_guid) extras_installer-)',
- 'o3d_iep_component_guid': '<!(<(guidgen) <(o3d_namespace_guid) '
- 'o3d_ieplugin_component-<!(python ../../plugin/version_info.py '
- '--set_version=<(plugin_version) --commaversion))',
- 'o3d_npp_component_guid': '<!(<(guidgen) <(o3d_namespace_guid) '
- 'o3d_npplugin_component-<!(python ../../plugin/version_info.py '
- '--set_version=<(plugin_version) --commaversion))',
- 'o3d_npp_google_update_reg_component_guid':
- '<!(<(guidgen) <(o3d_namespace_guid) '
- 'o3d_user_google_update_reg_component-'
- '<!(python ../../plugin/version_info.py '
- '--set_version=<(plugin_version) --commaversion))',
- 'o3d_npp_package_guid': '<!(<(guidgen) <(o3d_namespace_guid) '
- 'o3d_package-<!(python ../../plugin/version_info.py '
- '--set_version=<(plugin_version) --commaversion))',
- 'o3d_npp_product_guid': '<!(<(guidgen) <(o3d_namespace_guid) '
- 'o3d_product-<!(python ../../plugin/version_info.py '
- '--set_version=<(plugin_version) --commaversion))',
- 'o3d_npp_reg_key':
- '<(google_update_reg_path)<(o3d_npp_google_update_guid)',
- 'o3d_npp_state_reg_key':
- '<(google_update_state_reg_path)<(o3d_npp_google_update_guid)',
- 'o3d_reporter_guid':
- '<!(<(guidgen) <(o3d_namespace_guid) '
- 'o3d_reporter-<!(python ../../plugin/version_info.py '
- '--set_version=<(plugin_version) --commaversion))',
- 'o3d_software_renderer_guid': '<!(<(guidgen) <(o3d_namespace_guid) '
- 'o3d_software_renderer-<!(python ../../plugin/version_info.py '
- '--set_version=<(plugin_version) --commaversion))',
- 'rep_path': '<(PRODUCT_DIR)/reporter.exe',
- 'software_renderer_path':
- '../../../<(swiftshaderdir)/swiftshader_d3d9.dll',
- },
- 'dependencies': [
- '../../converter/converter.gyp:o3dConverter',
- '../../breakpad/breakpad.gyp:reporter',
- '../../google_update/google_update.gyp:getextras',
- '../../documentation/documentation.gyp:*',
- '../../plugin/plugin.gyp:npo3dautoplugin',
- '../../plugin/plugin.gyp:o3d_host',
- '../../samples/samples.gyp:samples',
- '../../build/libs.gyp:cg_libs',
- '../../build/libs.gyp:gl_libs',
- 'cactions',
- ],
- 'rules': [
- {
- 'rule_name': 'candle',
- 'extension': 'wxs',
- 'process_outputs_as_sources': 1,
- 'inputs': [
- '<(candle_exe)',
- '../../installer/win/docs.url',
- '<(PRODUCT_DIR)/cactions.dll',
- '<(PRODUCT_DIR)/cg.dll',
- '<(PRODUCT_DIR)/cgGL.dll',
- '<(PRODUCT_DIR)/cgc.exe',
- '<(PRODUCT_DIR)/o3dConditioner.exe',
- '<(dbl_path)',
- '<(get_extras_path)',
- '<(ieplugin_path)',
- '<(npplugin_path)',
- '<(rep_path)',
- ],
- 'outputs': [
- '<(RULE_INPUT_ROOT).wixobj',
- ],
- 'action': [
- '<(candle_exe)',
- '-nologo',
- '-dCustomActionsPath=<(custom_actions_path)',
- '-dD3DXGuid=<(d3dx_guid)',
- '-dDBLGuid=<(o3d_driver_blacklist_guid)',
- '-dDBLPath=<(dbl_path)',
- '-dDeprecatedUpgradeCode=<(bad_old_o3d_upgrade_code)',
- '-dGetExtrasGuid=<(o3d_get_extras_guid)',
- '-dGetExtrasPath=<(get_extras_path)',
- '-dIEPluginPath=<(ieplugin_path)',
- '-dIepComponentGuid=<(o3d_iep_component_guid)',
- '-dIncludeSoftwareRenderer=include_software_renderer',
- '-dNPPluginPath=<(npplugin_path)',
- '-dNppComponentGuid=<(o3d_npp_component_guid)',
- '-dNppGoogleUpdateRegGuid=<(o3d_npp_google_update_reg_component_guid)',
- '-dNppGoogleUpdateRegKey=<(o3d_npp_reg_key)',
- '-dNppGoogleUpdateStateRegKey=<(o3d_npp_state_reg_key)',
- '-dNppPackageGuid=<(o3d_npp_package_guid)',
- '-dNppProductGuid=<(o3d_npp_product_guid)',
- '-dNppUpgradeCode=<(o3d_npp_upgrade_code)',
- '-dNppVersion=<(plugin_version)',
- '-dRepGuid=<(o3d_reporter_guid)',
- '-dRepPath=<(rep_path)',
- '-dSoftwareRendererGuid=<(o3d_software_renderer_guid)',
- '-dSoftwareRendererPath=<(software_renderer_path)',
- '-o',
- '<(RULE_INPUT_ROOT).wixobj',
- '<(RULE_INPUT_PATH)',
- ],
- 'message': 'Generating installer from <(RULE_INPUT_PATH)',
- },
- {
- 'rule_name': 'light',
- 'extension': 'wixobj',
- 'process_outputs_as_sources': 1,
- 'inputs': [
- '<(light_exe)',
- ],
- 'outputs': [
- '<(PRODUCT_DIR)/<(RULE_INPUT_ROOT).msi',
- ],
- 'action': [
- '<(light_exe)',
- '-nologo',
- '-out',
- '<(PRODUCT_DIR)/<(RULE_INPUT_ROOT).msi',
- '<(RULE_INPUT_PATH)',
- ],
- 'message': 'Linking installer from <(RULE_INPUT_PATH)',
- },
- ],
- 'sources': [
- 'o3d.wxs',
- ],
- },
- ],
- 'conditions': [
- ['"<(dx_redist_exists)" == "True"',
- {
- 'targets': [
- {
- 'target_name': 'extras_installer',
- 'type': 'none',
- 'variables': {
- 'candle_exe': '../../../<(wixdir)/candle.exe',
- 'light_exe': '../../../<(wixdir)/light.exe',
- 'o3d_extras_d3dx_component_guid': '<!(<(guidgen) <(o3d_namespace_guid) '
- 'o3d_extras_d3dx_component-<!(python ../../plugin/version_info.py '
- '--set_version=<(plugin_version) --commaversion))',
- 'o3d_extras_package_guid': '<!(<(guidgen) <(o3d_namespace_guid) '
- 'o3d_extras_package-<(extrasversion))',
- 'o3d_extras_product_guid': '<!(<(guidgen) <(o3d_namespace_guid) '
- 'o3d_extras_product-<(extrasversion))',
- 'o3d_extras_reg_key':
- '<(google_update_reg_path)<(o3d_extras_google_update_guid)',
- },
- 'rules': [
- {
- 'rule_name': 'candle',
- 'extension': 'wxs',
- 'process_outputs_as_sources': 1,
- 'inputs': [
- '<(candle_exe)',
- ],
- 'outputs': [
- '<(RULE_INPUT_ROOT).wixobj',
- ],
- 'action': [
- '<(candle_exe)',
- '-nologo',
- '-dDxRedistPath=<(dx_redist_path)',
- '-dExtrasD3DXComponentGuid=<(o3d_extras_d3dx_component_guid)',
- '-dExtrasGoogleUpdateRegGuid=<(o3d_extras_google_update_guid)',
- '-dExtrasGoogleUpdateRegKey=<(o3d_extras_reg_key)',
- '-dExtrasPackageGuid=<(o3d_extras_package_guid)',
- '-dExtrasProductGuid=<(o3d_extras_product_guid)',
- '-dExtrasUpgradeCode=<(o3d_extras_upgrade_code)',
- '-dExtrasVersion=<(dotextrasversion)',
- '-o',
- '<(RULE_INPUT_ROOT).wixobj',
- '<(RULE_INPUT_PATH)',
- ],
- 'message': 'Generating extras installer from <(RULE_INPUT_PATH)',
- },
- {
- 'rule_name': 'light',
- 'extension': 'wixobj',
- 'process_outputs_as_sources': 1,
- 'inputs': [
- '<(light_exe)',
- ],
- 'outputs': [
- '<(PRODUCT_DIR)/<(RULE_INPUT_ROOT).msi',
- ],
- 'action': [
- '<(light_exe)',
- '-nologo',
- '-out',
- '<(PRODUCT_DIR)/<(RULE_INPUT_ROOT).msi',
- '<(RULE_INPUT_PATH)',
- ],
- 'message': 'Linking extras installer from <(RULE_INPUT_PATH)',
- },
- ],
- 'sources': [
- 'o3dextras.wxs',
- ],
- },
- ],
- },
- {
- 'targets': [
- {
- 'target_name': 'extras_installer',
- 'type': 'none',
- },
- ],
- },
- ],
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/installer/win/o3d.wxs b/o3d/installer/win/o3d.wxs
deleted file mode 100644
index 645cb89..0000000
--- a/o3d/installer/win/o3d.wxs
+++ /dev/null
@@ -1,355 +0,0 @@
-<?xml version='1.0' encoding='windows-1252'?>
-
-<!--
-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.
--->
-
-<!--
-Wix script for building o3d installer.
--->
-
-<Wix xmlns='http://schemas.microsoft.com/wix/2003/01/wi'>
-
- <Product Name='O3D Plugin' Id='$(var.NppProductGuid)'
- Language='1033' Codepage='1252' Version='$(var.NppVersion)'
- Manufacturer='Google' UpgradeCode='$(var.NppUpgradeCode)'>
-
- <Package Id='$(var.NppPackageGuid)' Keywords='Installer'
- Description='O3D Plugin Installer' Manufacturer='Google'
- InstallerVersion='101' InstallPrivileges='limited'
- Languages='1033' Compressed='yes' SummaryCodepage='1252' />
-
- <Media Id='1' Cabinet='o3dplugin.cab' EmbedCab='yes'
- CompressionLevel='high'/>
-
- <!-- Checks if the custom action for detecting directx has failed
- and displays an error message if that is the case. -->
- <Condition
- Message='O3D needs an installation of DirectX 9.0c or higher. Please download the latest version of DirectX from http://www.microsoft.com/download.'>
- DIRECTX_9_0_C_INSTALLED
- </Condition>
-
- <!-- Prevent silent updates from installing if O3D is running.
- If UILevel is less than or equal to 2, the update is silent.
- If UILevel is greater than 2, the update is not silent.
- The message should never be seen since this condition will attempt
- to display the message only when the install is silent. -->
- <Condition
- Message='Please first close any running instances of O3D.'>
- UILevel > 2 OR NOT (SOFTWARE_RUNNING) OR REMOVE ~= "ALL"
- </Condition>
-
- <!-- Copy the plugin to the mozilla plugin folder under
- 'Documents and Settings' -->
- <Directory Id='TARGETDIR' Name='SourceDir'>
- <Directory Id='AppDataFolder' Name='QFiles'>
- <Directory Id='pu.MozillaDir' Name='Mozilla'>
- <Directory Id='pu.FirefoxPluginsDir' Name='plugins'>
- <Component Id='pu.Npdll' Guid='$(var.NppComponentGuid)'>
- <File Id='pu.GoogleNpapiDll.dll' Name='npo3d.dll'
- LongName='npo3dautoplugin.dll' DiskId='1'
- Source='$(var.NPPluginPath)' Vital='yes' />
- <Registry Id='pu.NpapiPlugin' Root='HKCU'
- Key='Software\MozillaPlugins\@google.com/O3DPlugin'>
- <Registry Id='pu.NpapiPluginPath' Type='string'
- Action='write' Name='Path' Value='[pu.FirefoxPluginsDir]npo3dautoplugin.dll' />
- <Registry Id='pu.NpapiPluginName' Type='string'
- Action='write' Name='ProductName' Value='O3D Plugin' />
- <Registry Id='pu.NpapiPluginDescription' Type='string'
- Action='write' Name='Description' Value='O3D Plugin' />
- <Registry Id='pu.NpapiPluginVendor' Type='string'
- Action='write' Name='Vendor' Value='Google' />
- <Registry Id='pu.NpapiPluginVersion' Type='string'
- Action='write' Name='Version' Value='$(var.NppVersion)' />
- </Registry>
- <Condition>NOT (ALLUSERS)</Condition>
- </Component>
- <?if $(var.IncludeSoftwareRenderer) = True ?>
- <Directory Id='O3DPrivateDllDir' Name='O3D'
- LongName='O3DExtras'>
- <Component Id='SoftwareRenderer'
- Guid='$(var.SoftwareRendererGuid)'>
- <File Id='renderer' LongName="swiftshader_d3d9.dll"
- Vital='yes' DiskId='1' Name="ss_d3d9.dll"
- src='$(var.SoftwareRendererPath)' />
- <Condition>NOT (ALLUSERS)</Condition>
- </Component>
- </Directory>
- <?endif ?>
- </Directory>
- </Directory>
- <Directory Id='Google' Name='Google'>
- <Directory Id='O3D' Name='O3D'>
- <Component Id='InstallReporter' Guid='$(var.RepGuid)'>
- <File
- Id='Reporter'
- Name='reporter.exe'
- DiskId='1'
- Source='$(var.RepPath)'
- Vital='yes'/>
- <Condition>NOT (ALLUSERS)</Condition>
- </Component>
- <Component Id='InstallDriverBlacklist' Guid='$(var.DBLGuid)'>
- <!-- Note: the "Name" here is required, but is overridden by
- the "LongName". -->
- <File
- Id='DriverBlacklist'
- Name='BadDrvrs.txt'
- LongName='driver_blacklist.txt'
- DiskId='1'
- Source='$(var.DBLPath)'
- Vital='yes'/>
- <Condition>NOT (ALLUSERS)</Condition>
- </Component>
- <Component Id='pu.IEdll'
- Guid='$(var.IepComponentGuid)'>
- <File Id='pu.GoogleActiveXDll.dll' Name='o3d_host.dll'
- DiskId='1' Source='$(var.IEPluginPath)' Vital='yes'/>
- <!-- We add all of these registry values here, instead
- of running regsvr32 on the dll because otherwise we
- leave cruft behind if the dll is manually removed
- or corrupted.
-
- If COM interfaces are added to the DLL, you can
- recreate this list by running the RegCap.exe tool
- (part of Visual Studio) to extract the list of
- registry entries from o3d_host.dll, and then use
- tallow.exe (part of WiX) to convert that .reg file
- to WiX XML form. -->
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}"
- Value="O3DHostControl Class" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}\ProgID"
- Value="o3d_host.O3DHostControl.1" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}\VersionIndependentProgID"
- Value="o3d_host.O3DHostControl" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}\Programmable" />
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}\InprocServer32"
- Value="[#pu.GoogleActiveXDll.dll]" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}\InprocServer32"
- Name="ThreadingModel" Value="Apartment" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}\Control" />
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}\Insertable" />
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}\ToolboxBitmap32"
- Value="[#pu.GoogleActiveXDll.dll], 102" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}\MiscStatus"
- Value="0" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}\MiscStatus\1"
- Value="131473" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}\TypeLib"
- Value="{D4F6E31C-E952-48FE-9833-6AE308BD79C6}" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}\Version"
- Value="1.0" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}\Implemented Categories" />
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}\Implemented Categories\{7DD95801-9882-11CF-9FA9-00AA006C42C4}" />
- <Registry Root="HKCU" Key="Software\Classes\CLSID\{9666A772-407E-4F90-BC37-982E8160EB2D}\Implemented Categories\{7DD95802-9882-11CF-9FA9-00AA006C42C4}" />
- <Registry Root="HKCU" Key="Software\Classes\o3d_host.O3DHostControl.1"
- Value="O3DHostControl Class" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\o3d_host.O3DHostControl.1\CLSID"
- Value="{9666A772-407E-4F90-BC37-982E8160EB2D}" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\o3d_host.O3DHostControl.1\Insertable" />
- <Registry Root="HKCU" Key="Software\Classes\o3d_host.O3DHostControl"
- Value="O3DHostControl Class" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\o3d_host.O3DHostControl\CLSID"
- Value="{9666A772-407E-4F90-BC37-982E8160EB2D}" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\o3d_host.O3DHostControl\CurVer"
- Value="o3d_host.O3DHostControl.1" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\TypeLib" />
- <Registry Root="HKCU" Key="Software\Classes\TypeLib\{D4F6E31C-E952-48FE-9833-6AE308BD79C6}" />
- <Registry Root="HKCU" Key="Software\Classes\TypeLib\{D4F6E31C-E952-48FE-9833-6AE308BD79C6}\1.0"
- Value="npapi_host2 1.0 Type Library" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\TypeLib\{D4F6E31C-E952-48FE-9833-6AE308BD79C6}\1.0\FLAGS"
- Value="0" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\TypeLib\{D4F6E31C-E952-48FE-9833-6AE308BD79C6}\1.0\0" />
- <Registry Root="HKCU" Key="Software\Classes\TypeLib\{D4F6E31C-E952-48FE-9833-6AE308BD79C6}\1.0\0\win32"
- Value="[#pu.GoogleActiveXDll.dll]" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\Interface" />
- <Registry Root="HKCU" Key="Software\Classes\Interface\{56D79537-181C-4A38-ADF5-E12EC24D7FC7}"
- Value="IHostControl" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\Interface\{56D79537-181C-4A38-ADF5-E12EC24D7FC7}\ProxyStubClsid"
- Value="{00020424-0000-0000-C000-000000000046}" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\Interface\{56D79537-181C-4A38-ADF5-E12EC24D7FC7}\ProxyStubClsid32"
- Value="{00020424-0000-0000-C000-000000000046}" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\Interface\{56D79537-181C-4A38-ADF5-E12EC24D7FC7}\TypeLib"
- Value="{D4F6E31C-E952-48FE-9833-6AE308BD79C6}" Type="string" />
- <Registry Root="HKCU" Key="Software\Classes\Interface\{56D79537-181C-4A38-ADF5-E12EC24D7FC7}\TypeLib"
- Name="Version" Value="1.0" Type="string" />
- <Condition>NOT (ALLUSERS)</Condition>
- </Component>
- </Directory>
- </Directory>
- </Directory>
- <Directory Id='TempFolder' Name='TmpFiles'>
- <!-- This continues to run after we exit, so we don't clean it up.
- It's in the temp dir, so that's not so bad. It *must* be placed where
- performondemand.cc is expecting it to be!
- TODO: Figure out how to get it removed as of the next reboot.
- TODO: We also don't remove the extras on uninstall. We don't
- want to on upgrade, just on a full uninstall; can we tell the
- difference? -->
- <Directory Id='ExtrasTempDir' Name='Extras'>
- <Component Id='GetExtras'
- Guid='$(var.GetExtrasGuid)'>
- <File Id='getextras' Name="getxtras" LongName='getextras.exe'
- DiskId='1' src='$(var.GetExtrasPath)' />
- </Component>
- </Directory>
- </Directory>
-
- <!-- Write the current version of the plugin to the Google Update
- registry key for auto update. -->
- <Component Id='pu.UpdaterReg' Guid='$(var.NppGoogleUpdateRegGuid)'>
- <Registry Id='pu.UpdaterRegistryKeys' Root='HKCU'
- Key='$(var.NppGoogleUpdateRegKey)'
- Name='pv' Value='$(var.NppVersion)' Action='write'
- Type='string' />
- <Registry Id='pu.UpdaterRegistryKeys2' Root='HKCU'
- Key='$(var.NppGoogleUpdateRegKey)'
- Name='name' Value='o3d' Action='write'
- Type='string' />
- <Registry Id='pu.UpdaterRegistryKeys3' Root='HKCU'
- Key='$(var.NppGoogleUpdateRegKey)'
- Name='lang' Value='en' Action='write'
- Type='string' />
- <Registry Id='pu.TrackReg' Root='HKCU'
- Key='$(var.NppGoogleUpdateStateRegKey)'
- Name='dr' Value='0' Action='write'
- Type='string' />
- <Condition>NOT (ALLUSERS)</Condition>
- </Component>
- </Directory>
-
- <!-- List of actions to be performed. -->
- <Feature Id='G3DPlugin' Title='O3D Plugin' Level='1'>
- <ComponentRef Id='GetExtras' />
- <ComponentRef Id='pu.Npdll' />
- <ComponentRef Id='pu.IEdll'/>
- <ComponentRef Id='pu.UpdaterReg' />
- <ComponentRef Id='InstallReporter'/>
- <ComponentRef Id='InstallDriverBlacklist'/>
- <?if $(var.IncludeSoftwareRenderer) = True ?>
- <ComponentRef Id='SoftwareRenderer'/>
- <?endif ?>
- </Feature>
-
- <!-- Identify previous versions to remove before installing. The deprecated
- one dates to when we accidentally used the same upgrade code for the
- SDK and the plugin, so they'll both try to uninstall it, just in case.
- At worst, the user will have one or the other disappear mysteriously,
- but only once.
- -->
- <Upgrade Id='$(var.DeprecatedUpgradeCode)'>
- <UpgradeVersion OnlyDetect='no' Property='UPGRADING_DEPR'/>
- </Upgrade>
- <Upgrade Id='$(var.NppUpgradeCode)'>
- <UpgradeVersion
- Minimum='0.0.0.0' IncludeMinimum='yes'
- Maximum='$(var.NppVersion)' IncludeMaximum='yes'
- OnlyDetect='no' Property='UPGRADING'/>
- </Upgrade>
-
- <!-- Custom action to tell CheckDirectX where to report errors. -->
- <CustomAction
- Id='SetupGoogleUpdateRegistryKey'
- Property='GoogleUpdateResultKey'
- Value='$(var.NppGoogleUpdateStateRegKey)' />
- <!-- Custom action for detecting DirectX 9.0c or higher. -->
- <CustomAction
- Id='CheckDirectX'
- BinaryKey='CustomActions'
- DllEntry='CheckDirectX' />
- <!-- Custom action for detecting OpenGL Version. -->
- <CustomAction
- Id='CheckOpenGL'
- BinaryKey='CustomActions'
- DllEntry='CheckOpenGL' />
-
- <!-- Custom action for checking that we're not already running. -->
- <CustomAction
- Id='IsSoftwareRunning'
- BinaryKey='CustomActions'
- DllEntry='IsSoftwareRunning' />
-
- <Binary
- Id='CustomActions'
- SourceFile='$(var.CustomActionsPath)' />
-
- <!-- Custom action for telling Google Update to install d3dx if necessary. -->
- <CustomAction
- Id='InstallD3DXIfNeeded'
- BinaryKey='CustomActions'
- DllEntry='InstallD3DXIfNeeded'
- Execute='deferred' />
-
- <!-- Custom action needs to be in the InstallUISequence to make
- sure it has been executed before the Condition check. -->
- <InstallUISequence>
- <Custom
- Action='SetupGoogleUpdateRegistryKey'
- Before='CheckDirectX' />
- <Custom
- Action='IsSoftwareRunning'
- Before='CheckDirectX' />
- <Custom
- Action='CheckDirectX'
- Before='LaunchConditions' />
- <Custom
- Action='CheckOpenGL'
- Before='CheckDirectX' />
- </InstallUISequence>
-
- <InstallExecuteSequence>
- <Custom
- Action='SetupGoogleUpdateRegistryKey'
- Before='CheckDirectX' />
- <Custom
- Action='IsSoftwareRunning'
- Before='CheckDirectX' />
- <Custom
- Action='CheckDirectX'
- Before='LaunchConditions' />
- <Custom
- Action='CheckOpenGL'
- Before='CheckDirectX' />
- <Custom
- Action='InstallD3DXIfNeeded'
- After='InstallFiles'>
- NOT Installed
- </Custom>
- <UnregisterClassInfo>
- (REMOVE="ALL") OR UPGRADING OR UPGRADING_DEPR
- </UnregisterClassInfo>
- <RemoveExistingProducts After='InstallInitialize'>
- UPGRADING OR UPGRADING_DEPR
- </RemoveExistingProducts>
- <RegisterClassInfo/>
- </InstallExecuteSequence>
-
- </Product>
-</Wix>
diff --git a/o3d/installer/win/o3d_sdk.wxs b/o3d/installer/win/o3d_sdk.wxs
deleted file mode 100644
index b3dcaa0..0000000
--- a/o3d/installer/win/o3d_sdk.wxs
+++ /dev/null
@@ -1,223 +0,0 @@
-<?xml version='1.0' encoding='windows-1252'?>
-
-<!--
-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.
--->
-
-<!--
- Wix script for building o3d installer.
--->
-
-<Wix xmlns='http://schemas.microsoft.com/wix/2003/01/wi'>
-
- <Product Name='O3D SDK' Id='$(var.SDKProductGuid)'
- Language='1033' Codepage='1252' Version='$(var.SDKVersion)'
- Manufacturer='Google' UpgradeCode='$(var.SDKUpgradeCode)'>
- <Package Id='$(var.SDKPackageGuid)' Keywords='Installer'
- Description='O3D SDK Installer' Manufacturer='Google'
- InstallerVersion='101' InstallPrivileges='limited'
- Languages='1033' Compressed='yes' SummaryCodepage='1252' />
-
- <Media Id='1' Cabinet='o3dSDK.cab' EmbedCab='yes'
- CompressionLevel='high'/>
-
- <!-- Checks if the custom action for detecting directx has failed
- and displays an error message if that is the case. -->
- <Condition
- Message='O3D needs an installation of DirectX 9.0c or higher. Please download the latest version of DirectX from http://www.microsoft.com/download.'>
- DIRECTX_9_0_C_INSTALLED
- </Condition>
-
- <Directory
- Id='TARGETDIR'
- Name='SourceDir'>
- <Directory
- Id='ProgramMenuFolder'
- Name='PMenu'
- LongName='Programs'>
- <Directory
- Id='ProgramMenuDir'
- Name='O3D'
- LongName='O3D' />
- </Directory>
- <!-- Start menu items. -->
- <Directory
- Id='AppDataFolder'
- Name='QMenu'>
- <Directory
- Id='Google'
- Name='Google'>
- <Directory
- Id='O3D'
- Name='O3D'>
- <Directory
- Id='INSTALLDIR'
- Name='O3D'
- LongName='O3D' />
- <?include docs.wxs ?>
- <!-- Collada items. -->
- <Component Id='InstallCollada' Guid='$(var.SDKColladaGuid)'>
- <File
- Id='O3DSDKCollada'
- Name='o3dCond.exe'
- LongName='o3dConditioner.exe'
- DiskId='1'
- Source='$(var.SDKColladaPath)'>
- <Shortcut
- Id="O3DSDKColladaShortcut"
- Directory="ProgramMenuDir"
- Name="o3dCond.exe"
- LongName="Collada Conditioner"/>
- </File>
- <File
- Id='CGLib1'
- Name='cg.dll'
- LongName='cg.dll'
- DiskId='1'
- Source='$(var.SDKCG1Path)'/>
- <File
- Id='CGLib2'
- Name='cgGL.dll'
- LongName='cgGL.dll'
- DiskId='1'
- Source='$(var.SDKCG2Path)'/>
- <File
- Id='CGC'
- Name='cgc.exe'
- LongName='cgc.exe'
- DiskId='1'
- Source='$(var.SDKCGCPath)'/>
- <!-- We're just dropping this dll in here for now. Later, if we
- want to save space, we can do the same download-on-demand of the
- extras package that the plugin does. That will require the
- conditioner/exporter to use LoadLibrary to load d3dx9_36.dll,
- however. -->
- <File
- Id='D3DX9'
- Name='d3dx9_36.dll'
- LongName='d3dx9_36.dll'
- DiskId='1'
- Source='$(var.DxRedistPath)\d3dx9_36.dll'/>
- <Condition>NOT (ALLUSERS)</Condition>
- </Component>
- </Directory>
- </Directory>
- </Directory>
- <!-- Write the current version of the plugin to the Google Update
- registry key for auto update. -->
- <Component Id='UpdaterReg' Guid='$(var.SDKGoogleUpdateRegGuid)'>
- <Registry Id='pu.UpdaterRegistryKeys' Root='HKCU'
- Key='$(var.SDKGoogleUpdateRegKey)'
- Name='pv' Value='$(var.SDKVersion)' Action='write'
- Type='string' />
- <Registry Id='pu.UpdaterRegistryKeys2' Root='HKCU'
- Key='$(var.SDKGoogleUpdateRegKey)'
- Name='name' Value='o3d_sdk' Action='write'
- Type='string' />
- <Registry Id='pu.UpdaterRegistryKeys3' Root='HKCU'
- Key='$(var.SDKGoogleUpdateRegKey)'
- Name='lang' Value='en' Action='write'
- Type='string' />
- <Condition>NOT (ALLUSERS)</Condition>
- </Component>
- </Directory>
-
- <?include docs_features.wxs ?>
- <Feature
- Id='SDKCollada'
- Level='1'>
- <ComponentRef
- Id='InstallCollada'/>
- </Feature>
- <Feature
- Id='UpdateRegistry'
- Level='1'>
- <ComponentRef
- Id='UpdaterReg'/>
- </Feature>
-
- <!-- Identify previous versions to remove before installing. The deprecated
- one dates to when we accidentally used the same upgrade code for the SDK and
- the plugin, so they'll both try to uninstall it, just in case. At worst,
- the user will have one or the other disappear mysteriously, but only once.
- -->
- <Upgrade Id='$(var.DeprecatedUpgradeCode)'>
- <UpgradeVersion OnlyDetect='no' Property='UPGRADING_DEPR'/>
- </Upgrade>
- <Upgrade Id='$(var.SDKUpgradeCode)'>
- <UpgradeVersion
- Minimum='0.0.0.0' IncludeMinimum='yes'
- Maximum='$(var.SDKVersion)' IncludeMaximum='yes'
- OnlyDetect='no' Property='UPGRADING'/>
- </Upgrade>
-
- <!-- Custom action for detecting DirectX 9.0c or higher. -->
- <CustomAction
- Id='CheckDirectX'
- BinaryKey='CustomActions'
- DllEntry='CheckDirectX' />
-
- <Binary
- Id='CustomActions'
- SourceFile='cactions.dll' />
-
- <InstallExecuteSequence>
- <!-- We have to FindRelatedProducts before the LaunchConditions checks,
- so that we know if we're upgrading before we tell folks they need to be
- administrators. LaunchConditions happens at sequence number 100, and
- CheckDirectX is 99. -->
- <FindRelatedProducts Sequence='98' />
- <Custom
- Action='CheckDirectX'
- Before='LaunchConditions' />
- <UnregisterClassInfo>
- (REMOVE="ALL") OR UPGRADING OR UPGRADING_DEPR
- </UnregisterClassInfo>
- <RemoveExistingProducts After='InstallInitialize'>
- UPGRADING OR UPGRADING_DEPR
- </RemoveExistingProducts>
- <RegisterClassInfo/>
- </InstallExecuteSequence>
-
- <!-- Custom action needs to be in the InstallUISequence to make
- sure it has been executed before the Condition check. -->
- <InstallUISequence>
- <FindRelatedProducts Sequence='98' />
- <!-- We have to FindRelatedProducts before the LaunchConditions checks,
- so that we know if we're upgrading before we tell folks they need to be
- administrators. LaunchConditions happens at sequence number 100, and
- CheckDirectX is 99. -->
- <Custom
- Action='CheckDirectX'
- Before='LaunchConditions' />
- </InstallUISequence>
-
- </Product>
-</Wix>
diff --git a/o3d/installer/win/o3dextras.wxs b/o3d/installer/win/o3dextras.wxs
deleted file mode 100644
index 9568236..0000000
--- a/o3d/installer/win/o3dextras.wxs
+++ /dev/null
@@ -1,120 +0,0 @@
-<?xml version='1.0' encoding='windows-1252'?>
-
-<!--
-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.
--->
-
-<!--
- Wix script for the installer that puts the d3dx9 dll where o3d can find
- it.
--->
-
-<Wix xmlns='http://schemas.microsoft.com/wix/2003/01/wi'>
-
- <Product Name='O3D Extras' Id='$(var.ExtrasProductGuid)'
- Language='1033' Codepage='1252' Version='$(var.ExtrasVersion)'
- Manufacturer='Google' UpgradeCode='$(var.ExtrasUpgradeCode)'>
- <Package Id='$(var.ExtrasPackageGuid)' Keywords='Installer'
- Description='O3D Extras Installer' Manufacturer='Google'
- InstallerVersion='101' InstallPrivileges='limited'
- Languages='1033' Compressed='yes' SummaryCodepage='1252' />
-
- <Media Id='1' Cabinet='o3dExtras.cab' EmbedCab='yes'
- CompressionLevel='high'/>
-
- <Directory Id='TARGETDIR' Name='SourceDir'>
- <Directory Id='AppDataFolder' Name='QFiles'>
- <Directory Id='pu.MozillaDir' Name='Mozilla'>
- <Directory Id='pu.FirefoxPluginsDir' Name='plugins'>
- <Directory Id='O3DPrivateDllDir' Name='O3D'
- LongName='O3DExtras'>
- <Component Id='D3DXRedist' Guid='$(var.ExtrasD3DXComponentGuid)'>
- <File Id='d3dx' Name="d3dx9_36.dll" Vital='yes'
- DiskId='1' src='$(var.DxRedistPath)\d3dx9_36.dll' />
- <Condition>NOT (ALLUSERS)</Condition>
- </Component>
- </Directory>
- </Directory>
- </Directory>
- </Directory>
- <!-- Write the current version of the plugin to the Google Update
- registry key for auto update. -->
- <Component Id='pu.UpdateReg' Guid='$(var.ExtrasGoogleUpdateRegGuid)'>
- <Registry Id='pu.UpdateRegistryKeys' Root='HKCU'
- Key='$(var.ExtrasGoogleUpdateRegKey)'
- Name='pv' Value='$(var.ExtrasVersion)' Action='write'
- Type='string' />
- <Registry Id='pu.UpdateRegistryKeys2' Root='HKCU'
- Key='$(var.ExtrasGoogleUpdateRegKey)'
- Name='name' Value='o3d_extras' Action='write'
- Type='string' />
- <Registry Id='pu.UpdateRegistryKeys3' Root='HKCU'
- Key='$(var.ExtrasGoogleUpdateRegKey)'
- Name='lang' Value='en' Action='write'
- Type='string' />
- <Condition>NOT (ALLUSERS)</Condition>
- </Component>
- </Directory>
-
- <Feature
- Id='UpdateRegistry'
- Level='1'>
- <ComponentRef
- Id='pu.UpdateReg'/>
- </Feature>
- <Feature
- Id='DirectX'
- Level='1'>
- <ComponentRef
- Id='D3DXRedist'/>
- </Feature>
-
- <Upgrade Id='$(var.ExtrasUpgradeCode)'>
- <UpgradeVersion
- Minimum='0.0.0.0' IncludeMinimum='yes'
- Maximum='$(var.ExtrasVersion)' IncludeMaximum='yes'
- OnlyDetect='no' Property='UPGRADING'/>
- </Upgrade>
-
- <InstallExecuteSequence>
- <UnregisterClassInfo>
- (REMOVE="ALL") OR UPGRADING
- </UnregisterClassInfo>
- <RemoveExistingProducts After='InstallInitialize'>
- UPGRADING
- </RemoveExistingProducts>
- <RegisterClassInfo/>
- </InstallExecuteSequence>
-
- <InstallUISequence>
- </InstallUISequence>
-
- </Product>
-</Wix>
diff --git a/o3d/nbguidgen/win/md5.cc b/o3d/nbguidgen/win/md5.cc
deleted file mode 100644
index dad056e..0000000
--- a/o3d/nbguidgen/win/md5.cc
+++ /dev/null
@@ -1,254 +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 is adapted from libtomcrypt, which has been released into the
-// public domain.
-
-#include "nbguidgen/win/md5.h"
-#include <memory.h>
-
-#undef MAX
-#undef MIN
-#define MAX(x, y) ( ((x) > (y)) ? (x) : (y) )
-#define MIN(x, y) ( ((x) < (y)) ? (x) : (y) )
-
-#ifdef _MSC_VER
-
-/* instrinsic rotate */
-#include <stdlib.h>
-#pragma intrinsic(_lrotr, _lrotl)
-#define ROR(x, n) _lrotr(x, n)
-#define ROL(x, n) _lrotl(x, n)
-
-#else
-
-/* rotates the hard way */
-#define ROL(x, y) ( (((unsigned long)(x) << (unsigned long)((y) & 31)) | \
- (((unsigned long)(x) & 0xFFFFFFFFUL) >> \
- (unsigned long)(32-((y) & 31)))) & 0xFFFFFFFFUL)
-#define ROR(x, y) ( ((((unsigned long)(x) & 0xFFFFFFFFUL) >> \
- (unsigned long)((y) & 31)) | \
- ((unsigned long)(x) << \
- (unsigned long)(32 - ((y) & 31)))) & 0xFFFFFFFFUL)
-
-#endif
-
-#define STORE32L(x, y) \
- { (y)[3] = (unsigned char)(((x) >> 24)&255); \
- (y)[2] = (unsigned char)(((x) >> 16)&255); \
- (y)[1] = (unsigned char)(((x) >> 8)&255); \
- (y)[0] = (unsigned char)((x) & 255); }
-
-#define LOAD32L(x, y) \
- { x = ((unsigned long)((y)[3] & 255)<<24) | \
- ((unsigned long)((y)[2] & 255)<<16) | \
- ((unsigned long)((y)[1] & 255)<<8) | \
- ((unsigned long)((y)[0] & 255)); }
-
-#define STORE64L(x, y) \
- { (y)[7] = (unsigned char)(((x) >> 56) & 255); \
- (y)[6] = (unsigned char)(((x) >> 48) & 255); \
- (y)[5] = (unsigned char)(((x) >> 40) & 255); \
- (y)[4] = (unsigned char)(((x) >> 32) & 255); \
- (y)[3] = (unsigned char)(((x) >> 24) & 255); \
- (y)[2] = (unsigned char)(((x) >> 16) & 255); \
- (y)[1] = (unsigned char)(((x) >> 8) & 255); \
- (y)[0] = (unsigned char)((x) & 255); }
-
-#define F(x, y, z) (z ^ (x & (y ^ z)))
-#define G(x, y, z) (y ^ (z & (y ^ x)))
-#define H(x, y, z) (x^y^z)
-#define I(x, y, z) (y^(x|(~z)))
-
-#define FF(a, b, c, d, M, s, t) \
- a = (a + F(b, c, d) + M + t); \
- a = ROL(a, s) + b;
-
-#define GG(a, b, c, d, M, s, t) \
- a = (a + G(b, c, d) + M + t); \
- a = ROL(a, s) + b;
-
-#define HH(a, b, c, d, M, s, t) \
- a = (a + H(b, c, d) + M + t); \
- a = ROL(a, s) + b;
-
-#define II(a, b, c, d, M, s, t) \
- a = (a + I(b, c, d) + M + t); \
- a = ROL(a, s) + b;
-
-static void md5_compress(md5_t *md) {
- unsigned long i, W[16], a, b, c, d;
-
- /* copy the state into 512-bits into W[0..15] */
- for (i = 0; i < 16; i++) {
- LOAD32L(W[i], md->buf + (4*i));
- }
-
- /* copy state */
- a = md->state[0];
- b = md->state[1];
- c = md->state[2];
- d = md->state[3];
-
- FF(a, b, c, d, W[0], 7, 0xd76aa478UL)
- FF(d, a, b, c, W[1], 12, 0xe8c7b756UL)
- FF(c, d, a, b, W[2], 17, 0x242070dbUL)
- FF(b, c, d, a, W[3], 22, 0xc1bdceeeUL)
- FF(a, b, c, d, W[4], 7, 0xf57c0fafUL)
- FF(d, a, b, c, W[5], 12, 0x4787c62aUL)
- FF(c, d, a, b, W[6], 17, 0xa8304613UL)
- FF(b, c, d, a, W[7], 22, 0xfd469501UL)
- FF(a, b, c, d, W[8], 7, 0x698098d8UL)
- FF(d, a, b, c, W[9], 12, 0x8b44f7afUL)
- FF(c, d, a, b, W[10], 17, 0xffff5bb1UL)
- FF(b, c, d, a, W[11], 22, 0x895cd7beUL)
- FF(a, b, c, d, W[12], 7, 0x6b901122UL)
- FF(d, a, b, c, W[13], 12, 0xfd987193UL)
- FF(c, d, a, b, W[14], 17, 0xa679438eUL)
- FF(b, c, d, a, W[15], 22, 0x49b40821UL)
- GG(a, b, c, d, W[1], 5, 0xf61e2562UL)
- GG(d, a, b, c, W[6], 9, 0xc040b340UL)
- GG(c, d, a, b, W[11], 14, 0x265e5a51UL)
- GG(b, c, d, a, W[0], 20, 0xe9b6c7aaUL)
- GG(a, b, c, d, W[5], 5, 0xd62f105dUL)
- GG(d, a, b, c, W[10], 9, 0x02441453UL)
- GG(c, d, a, b, W[15], 14, 0xd8a1e681UL)
- GG(b, c, d, a, W[4], 20, 0xe7d3fbc8UL)
- GG(a, b, c, d, W[9], 5, 0x21e1cde6UL)
- GG(d, a, b, c, W[14], 9, 0xc33707d6UL)
- GG(c, d, a, b, W[3], 14, 0xf4d50d87UL)
- GG(b, c, d, a, W[8], 20, 0x455a14edUL)
- GG(a, b, c, d, W[13], 5, 0xa9e3e905UL)
- GG(d, a, b, c, W[2], 9, 0xfcefa3f8UL)
- GG(c, d, a, b, W[7], 14, 0x676f02d9UL)
- GG(b, c, d, a, W[12], 20, 0x8d2a4c8aUL)
- HH(a, b, c, d, W[5], 4, 0xfffa3942UL)
- HH(d, a, b, c, W[8], 11, 0x8771f681UL)
- HH(c, d, a, b, W[11], 16, 0x6d9d6122UL)
- HH(b, c, d, a, W[14], 23, 0xfde5380cUL)
- HH(a, b, c, d, W[1], 4, 0xa4beea44UL)
- HH(d, a, b, c, W[4], 11, 0x4bdecfa9UL)
- HH(c, d, a, b, W[7], 16, 0xf6bb4b60UL)
- HH(b, c, d, a, W[10], 23, 0xbebfbc70UL)
- HH(a, b, c, d, W[13], 4, 0x289b7ec6UL)
- HH(d, a, b, c, W[0], 11, 0xeaa127faUL)
- HH(c, d, a, b, W[3], 16, 0xd4ef3085UL)
- HH(b, c, d, a, W[6], 23, 0x04881d05UL)
- HH(a, b, c, d, W[9], 4, 0xd9d4d039UL)
- HH(d, a, b, c, W[12], 11, 0xe6db99e5UL)
- HH(c, d, a, b, W[15], 16, 0x1fa27cf8UL)
- HH(b, c, d, a, W[2], 23, 0xc4ac5665UL)
- II(a, b, c, d, W[0], 6, 0xf4292244UL)
- II(d, a, b, c, W[7], 10, 0x432aff97UL)
- II(c, d, a, b, W[14], 15, 0xab9423a7UL)
- II(b, c, d, a, W[5], 21, 0xfc93a039UL)
- II(a, b, c, d, W[12], 6, 0x655b59c3UL)
- II(d, a, b, c, W[3], 10, 0x8f0ccc92UL)
- II(c, d, a, b, W[10], 15, 0xffeff47dUL)
- II(b, c, d, a, W[1], 21, 0x85845dd1UL)
- II(a, b, c, d, W[8], 6, 0x6fa87e4fUL)
- II(d, a, b, c, W[15], 10, 0xfe2ce6e0UL)
- II(c, d, a, b, W[6], 15, 0xa3014314UL)
- II(b, c, d, a, W[13], 21, 0x4e0811a1UL)
- II(a, b, c, d, W[4], 6, 0xf7537e82UL)
- II(d, a, b, c, W[11], 10, 0xbd3af235UL)
- II(c, d, a, b, W[2], 15, 0x2ad7d2bbUL)
- II(b, c, d, a, W[9], 21, 0xeb86d391UL)
-
- md->state[0] = md->state[0] + a;
- md->state[1] = md->state[1] + b;
- md->state[2] = md->state[2] + c;
- md->state[3] = md->state[3] + d;
-}
-
-void MD5Init(md5_t *md) {
- md->state[0] = 0x67452301UL;
- md->state[1] = 0xefcdab89UL;
- md->state[2] = 0x98badcfeUL;
- md->state[3] = 0x10325476UL;
- md->curlen = 0;
- md->length = 0;
-}
-
-void MD5Process(md5_t *md, const unsigned char *buf, unsigned long len) {
- unsigned long n;
- while (len > 0) {
- n = MIN(len, (64 - md->curlen));
- memcpy(md->buf + md->curlen, buf, (size_t)n);
- md->curlen += n;
- buf += n;
- len -= n;
-
- /* is 64 bytes full? */
- if (md->curlen == 64) {
- md5_compress(md);
- md->length += 512;
- md->curlen = 0;
- }
- }
-}
-
-void MD5Finish(md5_t *md, unsigned char *hash) {
- int i;
-
- /* increase the length of the message */
- md->length += md->curlen * 8;
-
- /* append the '1' bit */
- md->buf[md->curlen++] = (unsigned char)0x80;
-
- /* if the length is currently above 56 bytes we append zeros
- * then compress. Then we can fall back to padding zeros and length
- * encoding like normal.
- */
- if (md->curlen > 56) {
- while (md->curlen < 64) {
- md->buf[md->curlen++] = (unsigned char)0;
- }
- md5_compress(md);
- md->curlen = 0;
- }
-
- /* pad upto 56 bytes of zeroes */
- while (md->curlen < 56) {
- md->buf[md->curlen++] = (unsigned char)0;
- }
-
- /* store length */
- STORE64L(md->length, md->buf+56);
- md5_compress(md);
-
- /* copy output */
- for (i = 0; i < 4; i++) {
- STORE32L(md->state[i], hash+(4*i));
- }
-}
diff --git a/o3d/nbguidgen/win/md5.h b/o3d/nbguidgen/win/md5.h
deleted file mode 100644
index 8a47e57..0000000
--- a/o3d/nbguidgen/win/md5.h
+++ /dev/null
@@ -1,46 +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_NBGUIDGEN_WIN_MD5_H_
-#define O3D_NBGUIDGEN_WIN_MD5_H_
-
-typedef struct {
- __int64 length;
- unsigned long state[4], curlen;
- unsigned char buf[64];
-} md5_t;
-
-void MD5Init(md5_t *md);
-void MD5Process(md5_t *md, const unsigned char *buf, unsigned long len);
-void MD5Finish(md5_t * md, unsigned char *hash);
-
-#endif // O3D_NBGUIDGEN_WIN_MD5_H_
diff --git a/o3d/nbguidgen/win/nbguidgen.cc b/o3d/nbguidgen/win/nbguidgen.cc
deleted file mode 100644
index 8720d90..0000000
--- a/o3d/nbguidgen/win/nbguidgen.cc
+++ /dev/null
@@ -1,166 +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 <objbase.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include "nbguidgen/win/md5.h"
-
-// This tool generates name-based GUIDs.
-
-// The quoted comments refer to various sections of RFC 4122, which explains
-// inter alia how to generate a name-based GUID.
-
-void GenerateNameBasedGUID(const unsigned char *namespace_guid_bytes,
- const char *name, unsigned char *guid_bytes) {
- // "Compute the hash of the name space ID concatenated with the name."
- int concatenated_input_len = 16 + static_cast<int>(strlen(name));
- unsigned char *concatenated_inputs =
- static_cast<unsigned char *>(malloc(concatenated_input_len));
- memcpy(concatenated_inputs, namespace_guid_bytes, 16);
- memcpy(&concatenated_inputs[16], name, strlen(name));
-
- md5_t md5;
- MD5Init(&md5);
- MD5Process(&md5, concatenated_inputs, concatenated_input_len);
- free(concatenated_inputs);
- MD5Finish(&md5, guid_bytes);
-
- // "Set the four most significant bits (bits 12 through 15) of the
- // time_hi_and_version field to the appropriate 4-bit version number
- // from Section 4.1.3."
- //
- // Msb0 Msb1 Msb2 Msb3 Version Description
- // 0 0 1 1 3 The name-based version
- // specified in this document
- // that uses MD5 hashing.
- guid_bytes[6] &= 0x0f;
- guid_bytes[6] |= 0x30;
-
- // "Set the two most significant bits (bits 6 and 7) of the
- // clock_seq_hi_and_reserved to zero and one, respectively."
- guid_bytes[8] &= 0x3f;
- guid_bytes[8] |= static_cast<unsigned char>(0x80);
-}
-
-bool ConvertStringToSerializedGUID(const char *s, unsigned char *g) {
- GUID namespace_guid;
- wchar_t namespace_guid_wide[38 + 1];
-
- if (strlen(s) > 38) {
- return false;
- }
- if (strlen(s) == 38) {
- mbstowcs(namespace_guid_wide, s, INT_MAX);
- }
-
- // Undocumented feature: accept GUIDs that are missing braces.
- if (strlen(s) == 36 && s[0] != '{') {
- namespace_guid_wide[0] = L'{';
- mbstowcs(namespace_guid_wide + 1, s, INT_MAX);
- wcscat(namespace_guid_wide, L"}");
- }
- if (FAILED(CLSIDFromString(namespace_guid_wide, &namespace_guid))) {
- return false;
- }
-
- int ngi = 0;
- g[ngi++] = static_cast<unsigned char>(namespace_guid.Data1 >> 24);
- g[ngi++] = static_cast<unsigned char>(namespace_guid.Data1 >> 16);
- g[ngi++] = static_cast<unsigned char>(namespace_guid.Data1 >> 8);
- g[ngi++] = static_cast<unsigned char>(namespace_guid.Data1);
-
- g[ngi++] = static_cast<unsigned char>(namespace_guid.Data2 >> 8);
- g[ngi++] = static_cast<unsigned char>(namespace_guid.Data2);
-
- g[ngi++] = static_cast<unsigned char>(namespace_guid.Data3 >> 8);
- g[ngi++] = static_cast<unsigned char>(namespace_guid.Data3);
-
- memcpy(&g[ngi], namespace_guid.Data4, sizeof(namespace_guid.Data4));
-
- return true;
-}
-
-// Permanent unit test
-//
-// Unfortunately, the single concrete example of such a GUID in the RFC is
-// incorrect. Authorities on the web suggest that the correct output for
-// (6ba7b810-9dad-11d1-80b4-00c04fd430c8, "www.widgets.com") is
-// 3d813cbb-47fb-32ba-91df-831e1593ac29, and this program passes that test.
-static bool run_unit_test() {
- unsigned char hash[16] = { 0 };
- const unsigned char known_hash[16] = { 0x3d, 0x81, 0x3c, 0xbb,
- 0x47, 0xfb,
- 0x32, 0xba,
- 0x91, 0xdf, 0x83, 0x1e, 0x15, 0x93, 0xac, 0x29 };
- const unsigned char namespace_DNS_GUID[16] = {0x6b, 0xa7, 0xb8, 0x10,
- 0x9d, 0xad,
- 0x11, 0xd1,
- 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8};
- GenerateNameBasedGUID(namespace_DNS_GUID, "www.widgets.com", hash);
-
- return (0 == memcmp(hash, known_hash, 16));
-}
-
-int main(int argc, char *argv[]) {
- if (argc != 3) {
- fprintf(stderr, "This tool generates name-based GUIDs as described in "
- "RFC 4122.\r\nUsage: gguidgen namespace-guid name\r\n");
- return 1;
- }
-
- if (!run_unit_test()) {
- fprintf(stderr, "This program is broken.\r\n");
- return 1;
- }
-
- unsigned char namespace_guid_as_bytes[16] = { 0 };
- if (!ConvertStringToSerializedGUID(argv[1], namespace_guid_as_bytes)) {
- fprintf(stderr, "Namespace must be a GUID of the form "
- "{00000000-0000-0000-0000-000000000000}.\r\n");
- return 1;
- }
-
- unsigned char hash[16] = { 0 };
- GenerateNameBasedGUID(namespace_guid_as_bytes, argv[2], hash);
-
- printf(
- "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
- hash[0], hash[1], hash[2], hash[3],
- hash[4], hash[5],
- hash[6], hash[7],
- hash[8], hash[9],
- hash[10], hash[11], hash[12], hash[13], hash[14], hash[15]);
-
- return 0;
-}
diff --git a/o3d/nbguidgen/win/nbguidgen.exe b/o3d/nbguidgen/win/nbguidgen.exe
deleted file mode 100644
index cf3d75f..0000000
--- a/o3d/nbguidgen/win/nbguidgen.exe
+++ /dev/null
Binary files differ
diff --git a/o3d/plugin/cross/archive_request_static_glue.cc b/o3d/plugin/cross/archive_request_static_glue.cc
deleted file mode 100644
index c11fd1c..0000000
--- a/o3d/plugin/cross/archive_request_static_glue.cc
+++ /dev/null
@@ -1,214 +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 "plugin/cross/archive_request_static_glue.h"
-
-#include "base/basictypes.h"
-#include "plugin/cross/stream_manager.h"
-#include "plugin/cross/o3d_glue.h"
-#include "import/cross/archive_request.h"
-
-namespace glue {
-namespace namespace_o3d {
-namespace class_ArchiveRequest {
-
-using _o3d::PluginObject;
-using o3d::Pack;
-using o3d::ArchiveRequest;
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// Callbacks
-//
-// TODO : get rid of these horrible callback objects which end up just
-// dispatching to the ArchiveRequest object.
-// Need to change the StreamManager class to implement an interface:
-// WriteReadyCallback
-// WriteCallback
-// FinishedCallback
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class ArchiveNewStreamCallback : public StreamManager::NewStreamCallback {
- public:
- explicit ArchiveNewStreamCallback(ArchiveRequest *request)
- : request_(request) { }
-
- virtual void Run(DownloadStream *stream) {
- request_->NewStreamCallback(stream);
- }
-
- private:
- ArchiveRequest::Ref request_;
- DISALLOW_COPY_AND_ASSIGN(ArchiveNewStreamCallback);
-};
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class ArchiveWriteReadyCallback : public StreamManager::WriteReadyCallback {
- public:
- explicit ArchiveWriteReadyCallback(ArchiveRequest *request)
- : request_(request) { }
-
- virtual int32 Run(DownloadStream *stream) {
- return request_->WriteReadyCallback(stream);
- }
-
- private:
- ArchiveRequest::Ref request_;
- DISALLOW_COPY_AND_ASSIGN(ArchiveWriteReadyCallback);
-};
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-class ArchiveWriteCallback : public StreamManager::WriteCallback {
- public:
- explicit ArchiveWriteCallback(ArchiveRequest *request) : request_(request) {
- }
-
- virtual int32 Run(DownloadStream *stream,
- int32 offset,
- int32 length,
- void *data) {
- return request_->WriteCallback(stream, offset, length, data);
- }
-
- private:
- ArchiveRequest::Ref request_;
- DISALLOW_COPY_AND_ASSIGN(ArchiveWriteCallback);
-};
-
-class ArchiveFinishedCallback : public StreamManager::FinishedCallback {
- public:
- explicit ArchiveFinishedCallback(ArchiveRequest *request)
- : request_(request) {
- }
-
- virtual ~ArchiveFinishedCallback() {
- // If the file request was interrupted (for example we moved to a new page
- // before the file transfer was completed) then we tell the FileRequest
- // object that the request failed. It's important to call this here since
- // set_success() will release the pack reference that the FileRequest holds
- // which will allow the pack to be garbage collected.
- if (!request_->done()) {
- request_->set_success(false);
- }
- }
-
- // Loads the Archive file, calls the JS callback to notify success.
- virtual void Run(DownloadStream *stream,
- bool success,
- const std::string &filename,
- const std::string &mime_type) {
- request_->FinishedCallback(stream, success, filename, mime_type);
- }
-
- private:
- ArchiveRequest::Ref request_;
- DISALLOW_COPY_AND_ASSIGN(ArchiveFinishedCallback);
-};
-
-// Sets up the parameters required for all ArchiveRequests.
-void userglue_method_open(void *plugin_data,
- ArchiveRequest *request,
- const String &method,
- const String &uri) {
- if (request->done()) {
- request->set_success(false);
- request->set_ready_state(ArchiveRequest::STATE_INIT); // not ready
- return; // We don't yet support reusing ArchiveRequests.
- }
-
- String method_lower(method);
- std::transform(method.begin(), method.end(), method_lower.begin(), ::tolower);
- if (method_lower != "get") {
- request->set_success(false);
- return; // We don't yet support fetching files via POST.
- }
- request->set_uri(uri);
- request->set_ready_state(ArchiveRequest::STATE_OPEN);
-}
-
-// Starts progressively downloading the requested file
-// The ArchiveRequest object will get callbacks as bytes stream in
-void userglue_method_send(void *plugin_data,
- ArchiveRequest *request) {
- PluginObject *plugin_object = static_cast<PluginObject *>(plugin_data);
- StreamManager *stream_manager = plugin_object->stream_manager();
- bool result = false;
-
- if (request->done()) {
- request->set_success(false);
- return; // ArchiveRequests can't be reused.
- }
- if (request->ready_state() != 1) { // Forgot to call open, or other error.
- request->set_success(false);
- return;
- }
- CHECK(request->pack());
-
- ArchiveNewStreamCallback *new_stream_callback =
- new ArchiveNewStreamCallback(request);
-
- ArchiveWriteReadyCallback *writeready_callback =
- new ArchiveWriteReadyCallback(request);
-
- ArchiveWriteCallback *write_callback =
- new ArchiveWriteCallback(request);
-
- ArchiveFinishedCallback *finished_callback =
- new ArchiveFinishedCallback(request);
-
- if (finished_callback) {
- DownloadStream *stream = stream_manager->LoadURL(request->uri(),
- new_stream_callback,
- writeready_callback,
- write_callback,
- finished_callback,
- NP_NORMAL);
- if (!stream) {
- // We don't call O3D_ERROR here because the URI may be user set
- // so we don't want to cause an error callback when the developer
- // may not be able to know the URI is correct.
- request->set_error("could not create download stream");
-
- // We need to call the callback to report failure. Because it's async, the
- // code making the request can't know that once it has called send() that
- // the request still exists since send() may have called the callback and
- // the callback may have deleted the request.
- request->FinishedCallback(NULL, false, request->uri(), std::string(""));
- }
-
- // If stream is not NULL request may not exist as LoadURL may already have
- // completed and therefore called the callback which may have freed the
- // request so we can't set anything on the request here.
- }
-}
-
-} // namespace class_ArchiveRequest
-} // namespace namespace_o3d
-} // namespace glue
diff --git a/o3d/plugin/cross/archive_request_static_glue.h b/o3d/plugin/cross/archive_request_static_glue.h
deleted file mode 100644
index 199de08..0000000
--- a/o3d/plugin/cross/archive_request_static_glue.h
+++ /dev/null
@@ -1,66 +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 glue for FileRequest actions.
-
-#ifndef O3D_PLUGIN_ARCHIVE_REQUEST_STATIC_GLUE_H_
-#define O3D_PLUGIN_ARCHIVE_REQUEST_STATIC_GLUE_H_
-
-#include "core/cross/callback.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-class ArchiveRequest;
-} // namespace o3d
-
-namespace glue {
-namespace namespace_o3d {
-namespace class_ArchiveRequest {
-
-using o3d::ArchiveRequest;
-using o3d::String;
-
-// Sets up the parameters required for all FileRequests.
-void userglue_method_open(void *plugin_data,
- ArchiveRequest *request,
- const String &method,
- const String &uri);
-
-// Starts downloading or reading the requested file, passing in a callback that
-// will parse and incorporate the file upon success.
-void userglue_method_send(void *plugin_data,
- ArchiveRequest *request);
-} // namespace class_FileRequest
-} // namespace namespace_o3d
-} // namespace glue
-
-#endif // O3D_PLUGIN_ARCHIVE_REQUEST_STATIC_GLUE_H_
diff --git a/o3d/plugin/cross/async_loading.cc b/o3d/plugin/cross/async_loading.cc
deleted file mode 100644
index e0f577f..0000000
--- a/o3d/plugin/cross/async_loading.cc
+++ /dev/null
@@ -1,288 +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 implements the asynchronous file-loading glue.
-
-#include <algorithm>
-
-#include "plugin/cross/async_loading.h"
-#include "plugin/cross/o3d_glue.h"
-#include "plugin/cross/stream_manager.h"
-#include "core/cross/bitmap.h"
-#include "core/cross/error_status.h"
-#include "core/cross/file_request.h"
-#include "core/cross/pack.h"
-#include "core/cross/texture.h"
-#include "import/cross/raw_data.h"
-
-namespace glue {
-namespace namespace_o3d {
-namespace class_FileRequest {
-
-using _o3d::PluginObject;
-using o3d::Bitmap;
-using o3d::Pack;
-using o3d::RawData;
-using o3d::Texture;
-
-// StreamManager::FinishedCallback
-// implementation that imports the file as a texture once downloaded.
-// When the download completes, LoadTextureURLCallback::Run() will be called,
-// which will parse and load the downloaded file. After that load is complete,
-// onreadystatechange will be run to notify the user.
-class LoadTextureURLCallback : public StreamManager::FinishedCallback {
- public:
- // Creates a new LoadTextureURLCallback.
- static LoadTextureURLCallback *Create(FileRequest *request) {
- return new LoadTextureURLCallback(request);
- }
-
- virtual ~LoadTextureURLCallback() {
- // If the file request was interrupted (for example we moved to a new page
- // before the file transfer was completed) then we tell the FileRequest
- // object that the request failed. It's important to call this here since
- // set_success() will release the pack reference that the FileRequest holds
- // which will allow the pack to be garbage collected.
- if (!request_->done()) {
- request_->set_success(false);
- }
- }
-
- // Loads the texture file, calls the JS callback to pass back the texture
- // object.
- virtual void Run(DownloadStream*,
- bool success,
- const std::string &filename,
- const std::string &mime_type) {
- Texture::Ref texture;
- if (success) {
- o3d::ErrorCollector error_collector(request_->service_locator());
- request_->set_ready_state(FileRequest::STATE_LOADED);
- // Try to get the image file type from the returned MIME type.
- // Unfortunately, TGA and DDS don't have standard MIME type, so we may
- // have to rely on the filename, or let the image loader figure it out by
- // itself (by trying every possible type).
- o3d::image::ImageFileType image_type =
- o3d::image::GetFileTypeFromMimeType(mime_type.c_str());
- texture = Texture::Ref(
- request_->pack()->CreateTextureFromFile(
- request_->uri(),
- filename.c_str(),
- image_type,
- request_->generate_mipmaps()));
- if (texture) {
- texture->set_name(request_->uri());
- request_->set_texture(texture);
- } else {
- success = false;
- }
- request_->set_error(error_collector.errors());
- } else {
- // No error is passed in from the stream but we MUST have an error
- // for the request to work on the javascript side.
- request_->set_error("Could not download texture: " + request_->uri());
- }
- request_->set_success(success);
- // Since the standard codes only go far enough to tell us that the download
- // succeeded, we set the success [and implicitly the done] flags to give the
- // rest of the story.
- if (request_->onreadystatechange())
- request_->onreadystatechange()->Run();
- }
-
- private:
- FileRequest::Ref request_;
-
- explicit LoadTextureURLCallback(FileRequest *request)
- : request_(request) {
- }
-};
-
-// StreamManager::FinishedCallback
-// implementation that imports the file as a RawData once downloaded. When the
-// download completes, LoadRawDataURLCallback::Run() will be called, which will
-// parse and load the downloaded file. After that load is complete,
-// onreadystatechange will be run to notify the user.
-class LoadRawDataURLCallback : public StreamManager::FinishedCallback {
- public:
- // Creates a new LoadRawDataURLCallback.
- static LoadRawDataURLCallback *Create(FileRequest *request) {
- return new LoadRawDataURLCallback(request);
- }
-
- virtual ~LoadRawDataURLCallback() {
- // If the file request was interrupted (for example we moved to a new page
- // before the file transfer was completed) then we tell the FileRequest
- // object that the request failed. It's important to call this here since
- // set_success() will release the pack reference that the FileRequest holds
- // which will allow the pack to be garbage collected.
- if (!request_->done()) {
- request_->set_success(false);
- }
- }
-
- // Loads the RawData file, calls the JS callback to pass back the RawData
- // object.
- virtual void Run(DownloadStream*,
- bool success,
- const std::string &filename,
- const std::string &mime_type) {
- RawData::Ref data;
- if (success) {
- o3d::ErrorCollector error_collector(request_->service_locator());
- request_->set_ready_state(FileRequest::STATE_LOADED);
- data = RawData::Ref(RawData::CreateFromFile(request_->service_locator(),
- request_->uri(),
- filename));
- if (data) {
- request_->set_data(data);
- } else {
- success = false;
- }
- request_->set_error(error_collector.errors());
- } else {
- // No error is passed in from the stream but we MUST have an error
- // for the request to work on the javascript side.
- request_->set_error("Could not download: " + request_->uri());
- }
- request_->set_success(success);
- // Since the standard codes only go far enough to tell us that the download
- // succeeded, we set the success [and implicitly the done] flags to give the
- // rest of the story.
- if (request_->onreadystatechange())
- request_->onreadystatechange()->Run();
- }
-
- private:
- FileRequest::Ref request_;
-
- explicit LoadRawDataURLCallback(FileRequest *request)
- : request_(request) {
- }
-};
-
-// Sets up the parameters required for all FileRequests.
-void userglue_method_open(void *plugin_data,
- FileRequest *request,
- const String &method,
- const String &uri,
- bool async) {
- if (!async) {
- request->set_success(false);
- O3D_ERROR(request->service_locator())
- << ("synchronous request not supported");
- return; // We don't yet support synchronous requests.
- }
- if (request->done()) {
- request->set_success(false);
- request->set_ready_state(FileRequest::STATE_INIT); // Show we're unready.
- O3D_ERROR(request->service_locator())
- << "request can not be reused";
- return; // We don't yet support reusing FileRequests.
- }
-
- String method_lower(method);
- std::transform(method.begin(), method.end(), method_lower.begin(), ::tolower);
- if (method_lower != "get") {
- request->set_success(false);
- O3D_ERROR(request->service_locator())
- << "request does not support POST yet";
- return; // We don't yet support fetching files via POST.
- }
- request->set_uri(uri);
- request->set_ready_state(FileRequest::STATE_OPEN);
-}
-
-// Starts downloading or reading the requested file, passing in a callback that
-// will parse and incorporate the file upon success.
-void userglue_method_send(void *plugin_data,
- FileRequest *request) {
- PluginObject *plugin_object = static_cast<PluginObject *>(plugin_data);
- StreamManager *stream_manager = plugin_object->stream_manager();
- StreamManager::FinishedCallback *callback = NULL;
-
- if (request->done()) {
- request->set_success(false);
- O3D_ERROR(request->service_locator())
- << "request can not be reused";
- return; // FileRequests can't be reused.
- }
- if (request->ready_state() != 1) { // Forgot to call open, or other error.
- request->set_success(false);
- O3D_ERROR(request->service_locator())
- << "open must be called before send";
- return;
- }
- CHECK(request->pack());
-
- switch (request->type()) {
- case FileRequest::TYPE_TEXTURE:
- callback = LoadTextureURLCallback::Create(request);
- break;
- case FileRequest::TYPE_RAWDATA:
- callback = LoadRawDataURLCallback::Create(request);
- break;
- default:
- CHECK(false);
- }
- if (callback) {
- DownloadStream *stream =
- stream_manager->LoadURL(request->uri(),
- NULL, // new stream callback
- NULL, // write ready callback
- NULL, // write callback
- callback, // finished callback
- NP_ASFILEONLY);
-
- if (!stream) {
- request->set_success(false);
-
- // We don't call O3D_ERROR here because the URI may be user set
- // so we don't want to cause an error callback when the devloper
- // may not be able to know the URI is correct.
- request->set_error("could not create download stream");
-
- // We need to call the callback to report failure. Because it's async, the
- // code making the request can't know that once it has called send() that
- // the request still exists since send() may have called the callback and
- // the callback may have deleted the request.
- request->onreadystatechange()->Run();
- }
-
- // If stream is not NULL request may not exist as LoadURL may already have
- // completed and therefore called the callback which may have freed the
- // request so we can't set anything on the request here.
- }
-}
-
-} // namespace class_FileRequest
-} // namespace namespace_o3d
-} // namespace glue
diff --git a/o3d/plugin/cross/async_loading.h b/o3d/plugin/cross/async_loading.h
deleted file mode 100644
index b64175e..0000000
--- a/o3d/plugin/cross/async_loading.h
+++ /dev/null
@@ -1,67 +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 glue for FileRequest actions.
-
-#ifndef O3D_PLUGIN_CROSS_ASYNC_LOADING_H_
-#define O3D_PLUGIN_CROSS_ASYNC_LOADING_H_
-
-#include "core/cross/callback.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-class FileRequest;
-} // namespace o3d
-
-namespace glue {
-namespace namespace_o3d {
-namespace class_FileRequest {
-
-using o3d::FileRequest;
-using o3d::String;
-
-// Sets up the parameters required for all FileRequests.
-void userglue_method_open(void *plugin_data,
- FileRequest *request,
- const String &method,
- const String &uri,
- bool async);
-
-// Starts downloading or reading the requested file, passing in a callback that
-// will parse and incorporate the file upon success.
-void userglue_method_send(void *plugin_data,
- FileRequest *request);
-} // namespace class_FileRequest
-} // namespace namespace_o3d
-} // namespace glue
-
-#endif // O3D_PLUGIN_CROSS_ASYNC_LOADING_H_
diff --git a/o3d/plugin/cross/blacklist.cc b/o3d/plugin/cross/blacklist.cc
deleted file mode 100644
index 9a0b33f..0000000
--- a/o3d/plugin/cross/blacklist.cc
+++ /dev/null
@@ -1,73 +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 <iostream>
-#include <fstream>
-
-#include "plugin/cross/config.h"
-#include "base/logging.h"
-
-namespace o3d {
-
-// Checks the driver GUID against the blacklist file. Returns true if there's a
-// match [this driver is blacklisted] or if an IO error occurred. Check the
-// state of input_file to determine which it was.
-//
-// Note that this function always returns false if the guid is 0, since it will
-// be zero if we had a failure in reading it, and the user will already have
-// been warned.
-bool IsDriverBlacklisted(std::ifstream *input_file, unsigned int guid) {
- if (!guid) {
- return false;
- }
- *input_file >> std::ws;
- while (input_file->good()) {
- if (input_file->peek() == '#') {
- char comment[256];
- input_file->getline(comment, 256);
- // If the line was too long for this to work, it'll set the failbit.
- } else {
- unsigned int id;
- *input_file >> std::hex >> id;
- if (id == guid) {
- return true;
- }
- }
- *input_file >> std::ws; // Skip whitespace here, to catch EOF cleanly.
- }
- if (input_file->fail()) {
- LOG(ERROR) << "Failed to read the blacklisted driver file completely.";
- return true;
- }
- CHECK(input_file->eof());
- return false;
-}
-} // namespace o3d
diff --git a/o3d/plugin/cross/config.h b/o3d/plugin/cross/config.h
deleted file mode 100644
index 45fbaf5..0000000
--- a/o3d/plugin/cross/config.h
+++ /dev/null
@@ -1,119 +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 a few functions to check the user's hardware and software
-// configuration.
-
-#ifndef O3D_PLUGIN_CROSS_CONFIG_H_
-#define O3D_PLUGIN_CROSS_CONFIG_H_
-
-#include <fstream>
-#include <string>
-#include "plugin/cross/o3d_glue.h"
-
-namespace o3d {
-
-// Returns the user agent string.
-// Arguments:
-// npp: plugin instance.
-// Returns:
-// The user agent string.
-std::string GetUserAgent(NPP npp);
-
-struct GPUDevice {
- unsigned int vendor_id;
- unsigned int device_id;
- std::string driver;
- std::string description;
- std::string name;
- unsigned int guid;
-};
-
-// Asks the user to ok a continuation
-// Arguments:
-// npp: plugin instance.
-// error: the error to signal.
-// Returns:
-// true if the error was overridden by the user, false otherwise.
-bool AskUser(NPP npp, const std::string &error);
-
-// Gets the device information.
-// Arguments:
-// device: a GPUDevice structure that will contain the vendor and device IDs.
-// name: a pointer to a string that will contain the device string.
-// Returns:
-// true if successful. If not, device and name are not modified.
-bool GetGPUDevice(NPP npp, GPUDevice *device);
-
-// Checks that the current hardware and software configuration is supported,
-// prompting the user to give him and option to run anyway.
-// Arguments:
-// npp: plugin instance.
-// Returns:
-// Whether to allow the plug-in to run.
-bool CheckConfig(NPP npp);
-
-// The following functions are platform-dependent, and are implemented in the
-// respective {platform}/config.cc files
-
-// Checks the operating system version.
-bool CheckOSVersion(NPP npp);
-
-// Checks the user agent string.
-bool CheckUserAgent(NPP npp, const std::string &user_agent);
-
-// Used to get the text file that lists blacklisted driver GUIDs.
-// Returns true on success.
-bool OpenDriverBlacklistFile(std::ifstream *input_file);
-
-// Checks the driver GUID against the blacklist file. Returns true if there's a
-// match [this driver is blacklisted] or if an IO error occurred. Check the
-// state of input_file to determine which it was.
-// Note that this function always returns false if the guid is 0, since it will
-// be 0 if we had a failure in reading it, and the user will already have been
-// warned.
-bool IsDriverBlacklisted(std::ifstream *input_file, unsigned int guid);
-
-// Checks the current hardware, software configurations and puts the values
-// into metrics.
-bool GetUserConfigMetrics();
-
-// Checks the browser version.
-// Arguments:
-// npp: plugin instance.
-bool GetUserAgentMetrics(NPP npp);
-
-bool GetOpenGLMetrics();
-
-} // namespace o3d
-
-#endif // O3D_PLUGIN_CROSS_CONFIG_H_
diff --git a/o3d/plugin/cross/config_common.cc b/o3d/plugin/cross/config_common.cc
deleted file mode 100644
index c58ad47..0000000
--- a/o3d/plugin/cross/config_common.cc
+++ /dev/null
@@ -1,218 +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 common code to check the hardware and software
-// configuration of the client machine:
-// - User agent (browser)
-// - OS version
-// - GPU vendor
-
-#ifdef RENDERER_D3D9
-#include <d3d9.h>
-#endif
-
-#include <iostream>
-#include <fstream>
-
-#include "base/logging.h"
-#include "core/cross/install_check.h"
-#include "plugin/cross/config.h"
-#include "plugin/cross/o3d_glue.h"
-#include "core/cross/error.h"
-#include "third_party/nixysa/static_glue/npapi/common.h"
-
-using glue::_o3d::GetServiceLocator;
-
-namespace o3d {
-
-// Gets the value of "navigator.userAgent" in the JavaScript context, which
-// contains the user agent string.
-std::string GetUserAgent(NPP npp) {
- GLUE_PROFILE_START(npp, "NPN_UserAgent");
- const char* user_agent = NPN_UserAgent(npp);
- GLUE_PROFILE_STOP(npp, "NPN_UserAgent");
- std::string uagent_string;
- if (user_agent) {
- uagent_string = std::string(user_agent);
- }
- return uagent_string;
-}
-
-// Pops up a dialog box using JavaScript showing the error and gives the user a
-// chance to continue anyway.
-bool AskUser(NPP npp, const std::string &error) {
- NPObject *global_object;
- GLUE_PROFILE_START(npp, "NPN_GetValue");
- NPN_GetValue(npp, NPNVWindowNPObject, &global_object);
- GLUE_PROFILE_STOP(npp, "NPN_GetValue");
- GLUE_PROFILE_START(npp, "NPN_GetStringIdentifier");
- NPIdentifier alert_id = NPN_GetStringIdentifier("confirm");
- GLUE_PROFILE_STOP(npp, "NPN_GetStringIdentifier");
- std::string message = std::string("O3D: ") + error;
- // TODO: internationalize message.
- // TODO: Should this change to call some hardcoded javascript function
- // like "o3djs.util.confirmContinuation" or even a global name like
- // o3djs_confirmContinuation. This would move localization outside
- // C++ and give the developer a chance to handle it his own way.
- message += "\nPress OK to continue anyway.";
-
- NPVariant args[1];
- NPVariant result;
- STRINGN_TO_NPVARIANT(message.c_str(), message.length(), args[0]);
- GLUE_PROFILE_START(npp, "NPN_Invoke");
- bool temp = NPN_Invoke(npp, global_object, alert_id, args, 1, &result);
- GLUE_PROFILE_STOP(npp, "NPN_Invoke");
- if (temp) {
- bool retval = NPVARIANT_IS_BOOLEAN(result) && NPVARIANT_TO_BOOLEAN(result);
- GLUE_PROFILE_START(npp, "NPN_ReleaseVariantValue");
- NPN_ReleaseVariantValue(&result);
- GLUE_PROFILE_STOP(npp, "NPN_ReleaseVariantValue");
- return retval;
- } else {
- return false;
- }
-}
-
-// Gets the GPU device IDs and name, pops up a dialog box to confirm with the
-// user in case we can't get the information.
-bool GetGPUDevice(NPP npp, GPUDevice *device) {
-#if defined(RENDERER_D3D9)
- // Check GPU vendor using D3D.
- IDirect3D9 *d3d = Direct3DCreate9(D3D_SDK_VERSION);
- if (!d3d) {
- O3D_ERROR(GetServiceLocator(npp)) << "Direct3D9 is unavailable";
- return false;
- }
- D3DADAPTER_IDENTIFIER9 identifier;
- HRESULT hr = d3d->GetAdapterIdentifier(D3DADAPTER_DEFAULT, 0, &identifier);
- d3d->Release();
- if (hr != D3D_OK) {
- O3D_ERROR(GetServiceLocator(npp)) << "Unable to get device ID";
- device->vendor_id = 0;
- device->device_id = 0;
- device->name = "Unknown";
- device->driver = "Unknown";
- device->description = "Unknown";
- device->guid = 0;
- return false;
- }
- device->vendor_id = identifier.VendorId;
- device->device_id = identifier.DeviceId;
- device->name = identifier.DeviceName;
- device->driver = identifier.Driver;
- device->description = identifier.Description;
- device->guid = identifier.DeviceIdentifier.Data1;
- return true;
-#else
- // TODO: check GL version, blacklisted vendors ?
- device->vendor_id = 0;
- device->device_id = 0;
- device->name = "Unknown";
- device->driver = "Unknown";
- device->description = "Unknown";
- device->guid = 0;
- return true;
-#endif
-}
-
-// List of "black-listed" GPUs.
-//
-// A Vendor ID of 0 means end of the list. A device ID of 0 means the entire
-// line of devices from this vendor is black-listed.
-//
-// NOTE: Black-listed GPUs are only for GPUs that have security or stability
-// issues. GPUs that are missing required features are handled by the renderer.
-static const GPUDevice g_blacklisted_gpus[] = {
- {0, 0, }, // End Marker
-};
-
-// Checks various configuration elements:
-// - Windows version
-// - GPU vendor
-// - User agent (browser)
-bool CheckConfig(NPP npp) {
- if (!CheckOSVersion(npp)) return false;
-
- GPUDevice device;
- if (!GetGPUDevice(npp, &device)) return false;
- for (unsigned int i = 0;
- g_blacklisted_gpus[i].vendor_id != 0; ++i) {
- if (device.vendor_id == g_blacklisted_gpus[i].vendor_id &&
- (device.device_id == g_blacklisted_gpus[i].device_id ||
- g_blacklisted_gpus[i].device_id == 0)) {
- O3D_ERROR(GetServiceLocator(npp))
- << "Unsupported GPU device: " + device.name;
- return false;
- }
- }
-
- {
- std::ifstream blacklist_file;
- std::string error;
- if (!OpenDriverBlacklistFile(&blacklist_file)) {
- // Allow missing blacklist file for now, or else pulse and developer
- // builds [which don't install the file] will fail.
- // TODO: Look into this again for the public release.
- // error = "Failed to open driver blacklist file.\n"
- // "Can't verify that it's safe to run O3D.";
- } else if (IsDriverBlacklisted(&blacklist_file, device.guid)) {
- if (blacklist_file.fail()) {
- error = "Error reading driver blacklist file.\n"
- "Can't verify that it's safe to run O3D.";
- } else {
- error = "Your driver cannot run O3D safely.";
- }
- }
- if (error.length() && !AskUser(npp, error)) {
- return false;
- }
- }
-
- {
- std::string error;
- if (!o3d::RendererInstallCheck(&error)) {
- if (error.length()) {
- O3D_ERROR(GetServiceLocator(npp)) << error;
- } else {
- O3D_ERROR(GetServiceLocator(npp))
- << "Could not initialize the graphics driver.";
- }
- return false;
- }
- }
-
- // Check User agent. Only Firefox, Chrome, Safari and IE are supported.
- std::string user_agent = GetUserAgent(npp);
- if (!CheckUserAgent(npp, user_agent)) return false;
- return true;
-}
-} // namespace o3d
diff --git a/o3d/plugin/cross/download_stream.h b/o3d/plugin/cross/download_stream.h
deleted file mode 100644
index 8222386..0000000
--- a/o3d/plugin/cross/download_stream.h
+++ /dev/null
@@ -1,66 +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_PLUGIN_CROSS_DOWNLOAD_STREAM_H_
-#define O3D_PLUGIN_CROSS_DOWNLOAD_STREAM_H_
-
-#include <string>
-
-namespace glue {
-
-// Abstract interface representing a download
-class DownloadStream {
- public:
- enum State {
- STREAM_REQUESTED,
- STREAM_STARTED, // in progress
- STREAM_FINISHED // completed successfully or terminated
- };
-
- virtual ~DownloadStream() {}
-
- virtual std::string GetURL() = 0;
-
- // Returns empty string if no cache file
- virtual std::string GetCachedFile() = 0;
-
- virtual State GetState() = 0;
- virtual int GetReceivedByteCount() = 0;
- virtual size_t GetStreamLength() = 0;
-
- // Stops downloading
- virtual void Cancel() = 0;
-};
-
-} // namespace glue
-
-#endif // O3D_PLUGIN_CROSS_DOWNLOAD_STREAM_H_
diff --git a/o3d/plugin/cross/main.cc b/o3d/plugin/cross/main.cc
deleted file mode 100644
index c6a2b43..0000000
--- a/o3d/plugin/cross/main.cc
+++ /dev/null
@@ -1,460 +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 "plugin/cross/main.h"
-
-#include "base/at_exit.h"
-#include "base/command_line.h"
-#include "base/file_util.h"
-#include "plugin/cross/config.h"
-#include "plugin/cross/out_of_memory.h"
-#include "plugin/cross/whitelist.h"
-#ifdef OS_WIN
-#include "breakpad/win/bluescreen_detector.h"
-#include <intrin.h>
-#endif
-
-using glue::_o3d::PluginObject;
-using glue::StreamManager;
-
-#if !defined(O3D_INTERNAL_PLUGIN)
-
-#ifdef OS_WIN
-#define O3D_DEBUG_LOG_FILENAME L"debug.log"
-#else
-#define O3D_DEBUG_LOG_FILENAME "debug.log"
-#endif
-
-#if defined(OS_WIN) || defined(OS_MACOSX)
-o3d::PluginLogging *g_logger = NULL;
-static bool g_logging_initialized = false;
-#ifdef OS_WIN
-static o3d::BluescreenDetector *g_bluescreen_detector = NULL;
-#endif // OS_WIN
-#endif // OS_WIN || OS_MACOSX
-
-// We would normally make this a stack variable in main(), but in a
-// plugin, that's not possible, so we make it a global. When the DLL is loaded
-// this it gets constructed and when it is unlooaded it is destructed. Note
-// that this cannot be done in NP_Initialize and NP_Shutdown because those
-// calls do not necessarily signify the DLL being loaded and unloaded. If the
-// DLL is not unloaded then the values of global variables are preserved.
-static base::AtExitManager g_at_exit_manager;
-
-int BreakpadEnabler::scope_count_ = 0;
-
-#endif // O3D_INTERNAL_PLUGIN
-
-namespace o3d {
-
-NPError NP_GetValue(NPPVariable variable, void *value) {
- switch (variable) {
- case NPPVpluginNameString:
- *static_cast<char **>(value) = const_cast<char*>(O3D_PLUGIN_NAME);
- break;
- case NPPVpluginDescriptionString:
- *static_cast<char **>(value) = const_cast<char*>(O3D_PLUGIN_DESCRIPTION);
- break;
- default:
- return NPERR_INVALID_PARAM;
- break;
- }
- return NPERR_NO_ERROR;
-}
-
-int16 NPP_HandleEvent(NPP instance, void *event) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
- if (!obj) {
- return 0;
- }
-
- return PlatformNPPHandleEvent(instance, obj, event);
-}
-
-NPError NPP_NewStream(NPP instance,
- NPMIMEType type,
- NPStream *stream,
- NPBool seekable,
- uint16 *stype) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
- if (!obj) {
- return NPERR_INVALID_PARAM;
- }
-
- StreamManager *stream_manager = obj->stream_manager();
- if (stream_manager->NewStream(stream, stype)) {
- return NPERR_NO_ERROR;
- } else {
- // TODO: find out which error we should return
- return NPERR_INVALID_PARAM;
- }
-}
-
-NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
- if (!obj) {
- return NPERR_NO_ERROR;
- }
-
- StreamManager *stream_manager = obj->stream_manager();
- if (stream_manager->DestroyStream(stream, reason)) {
- return NPERR_NO_ERROR;
- } else {
- // TODO: find out which error we should return
- return NPERR_INVALID_PARAM;
- }
-}
-
-int32 NPP_WriteReady(NPP instance, NPStream *stream) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
- if (!obj) {
- return 0;
- }
-
- StreamManager *stream_manager = obj->stream_manager();
- return stream_manager->WriteReady(stream);
-}
-
-int32 NPP_Write(NPP instance, NPStream *stream, int32 offset, int32 len,
- void *buffer) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
- if (!obj) {
- return 0;
- }
-
- StreamManager *stream_manager = obj->stream_manager();
- return stream_manager->Write(stream, offset, len, buffer);
-}
-
-void NPP_Print(NPP instance, NPPrint *platformPrint) {
- HANDLE_CRASHES;
-}
-
-void NPP_URLNotify(NPP instance, const char *url, NPReason reason,
- void *notifyData) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
- if (!obj) {
- return;
- }
-
- StreamManager *stream_manager = obj->stream_manager();
- stream_manager->URLNotify(url, reason, notifyData);
-}
-
-NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) {
- HANDLE_CRASHES;
- if (!instance) {
- // Our ActiveX wrapper calls us like this as a way of saying that what it
- // really wants to call is NP_GetValue(). :/
- return o3d::NP_GetValue(variable, value);
- }
- PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
- if (!obj) {
- return NPERR_INVALID_PARAM;
- }
-
- switch (variable) {
- case NPPVpluginScriptableNPObject: {
- void **v = static_cast<void **>(value);
- // Return value is expected to be retained
- GLUE_PROFILE_START(instance, "retainobject");
- NPN_RetainObject(obj);
- GLUE_PROFILE_STOP(instance, "retainobject");
- *v = obj;
- break;
- }
- default: {
- NPError ret = PlatformNPPGetValue(obj, variable, value);
- if (ret == NPERR_INVALID_PARAM)
- // TODO(tschmelcher): Do we still need to fall back to this now that we
- // have the ActiveX special case above?
- ret = o3d::NP_GetValue(variable, value);
- return ret;
- }
- }
- return NPERR_NO_ERROR;
-}
-
-NPError NPP_New(NPMIMEType pluginType,
- NPP instance,
- uint16 mode,
- int16 argc,
- char *argn[],
- char *argv[],
- NPSavedData *saved) {
- HANDLE_CRASHES;
-
-#if !defined(O3D_INTERNAL_PLUGIN) && (defined(OS_WIN) || defined(OS_MACOSX))
- // TODO(tschmelcher): Support this on Linux?
- if (!g_logging_initialized) {
- // Get user config metrics. These won't be stored though unless the user
- // opts-in for usagestats logging
- GetUserAgentMetrics(instance);
- GetUserConfigMetrics();
- // Create usage stats logs object
- g_logger = o3d::PluginLogging::InitializeUsageStatsLogging();
-#ifdef OS_WIN
- if (g_logger) {
- // Setup blue-screen detection
- g_bluescreen_detector = new o3d::BluescreenDetector();
- g_bluescreen_detector->Start();
- }
-#endif
- g_logging_initialized = true;
- }
-#endif
-
- if (!IsDomainAuthorized(instance)) {
- return NPERR_INVALID_URL;
- }
-
- PluginObject *obj = glue::_o3d::PluginObject::Create(instance);
- instance->pdata = obj;
- glue::_o3d::InitializeGlue(instance);
- obj->Init(argc, argn, argv);
- return PlatformNPPNew(instance, obj);
-}
-
-NPError NPP_Destroy(NPP instance, NPSavedData **save) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
- if (!obj) {
- return NPERR_NO_ERROR;
- }
-
- NPError err = PlatformNPPDestroy(instance, obj);
-
- NPN_ReleaseObject(obj);
- instance->pdata = NULL;
-
- return err;
-}
-
-NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) {
- HANDLE_CRASHES;
- return NPERR_GENERIC_ERROR;
-}
-
-NPError NPP_SetWindow(NPP instance, NPWindow* window) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
- if (!obj) {
- return NPERR_NO_ERROR;
- }
-
- return PlatformNPPSetWindow(instance, obj, window);
-}
-
-// Called when the browser has finished attempting to stream data to
-// a file as requested. If fname == NULL the attempt was not successful.
-void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
- if (!obj) {
- return;
- }
-
- StreamManager *stream_manager = obj->stream_manager();
- PlatformNPPStreamAsFile(stream_manager, stream, fname);
-}
-
-} // namespace o3d
-
-#if defined(O3D_INTERNAL_PLUGIN)
-namespace o3d {
-#else
-extern "C" {
-#endif
-
-// Detect CPU has SSE2
-#if defined(__pic__) && defined(__i386__)
-void __cpuid(int cpu_info[4], int info_type) {
- __asm__ volatile (
- "mov %%ebx, %%edi\n"
- "cpuid\n"
- "xchg %%edi, %%ebx\n"
- : "=a"(cpu_info[0]), "=D"(cpu_info[1]), "=c"(cpu_info[2]), "=d"(cpu_info[3])
- : "a"(info_type)
- );
-}
-#elif defined(__i386__) || defined(__x86_64__)
-void __cpuid(int cpu_info[4], int info_type) {
- __asm__ volatile (
- "cpuid\n"
- : "=a"(cpu_info[0]), "=b"(cpu_info[1]), "=c"(cpu_info[2]), "=d"(cpu_info[3])
- : "a"(info_type)
- );
-}
-#endif
-
-#if defined(__x86_64__) || defined(_M_X64) || \
- defined(__i386__) || defined(_M_IX86)
-bool CpuHasSSE2() {
- int cpu_info[4];
- __cpuid(cpu_info, 1);
- return (cpu_info[3] & 0x04000000) != 0;
-}
-#endif
-
-NPError EXPORT_SYMBOL OSCALL NP_Initialize(NPNetscapeFuncs *browserFuncs
-#ifdef OS_LINUX
- ,
- NPPluginFuncs *pluginFuncs
-#endif
- ) {
-
-// On x86, detect lack of SSE2 and quit before a crash occurs.
-// TODO(fbarchard): Remove this when -msse2 is removed or SSE2 is required.
-#if defined(__x86_64__) || defined(_M_X64) || \
- defined(__i386__) || defined(_M_IX86)
- if (!CpuHasSSE2()) {
- return NPERR_MODULE_LOAD_FAILED_ERROR;
- }
-#endif
-
- HANDLE_CRASHES;
- NPError err = InitializeNPNApi(browserFuncs);
- if (err != NPERR_NO_ERROR) {
- return err;
- }
-
-#ifdef OS_LINUX
- NP_GetEntryPoints(pluginFuncs);
-#endif // OS_LINUX
-
-#if !defined(O3D_INTERNAL_PLUGIN)
- if (!o3d::SetupOutOfMemoryHandler())
- return NPERR_MODULE_LOAD_FAILED_ERROR;
-#endif // O3D_INTERNAL_PLUGIN
-
- err = o3d::PlatformPreNPInitialize();
- if (err != NPERR_NO_ERROR) {
- return err;
- }
-
-#if !defined(O3D_INTERNAL_PLUGIN)
- // Turn on the logging.
- CommandLine::Init(0, NULL);
-
- FilePath log;
- file_util::GetTempDir(&log);
- log = log.Append(O3D_DEBUG_LOG_FILENAME);
-
- InitLogging(log.value().c_str(),
- logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,
- logging::DONT_LOCK_LOG_FILE,
- logging::APPEND_TO_OLD_LOG_FILE);
-#endif // O3D_INTERNAL_PLUGIN
-
- DLOG(INFO) << "NP_Initialize";
-
- return o3d::PlatformPostNPInitialize();
-}
-
-NPError EXPORT_SYMBOL OSCALL NP_Shutdown(void) {
- HANDLE_CRASHES;
- DLOG(INFO) << "NP_Shutdown";
-
- NPError err = o3d::PlatformPreNPShutdown();
- if (err != NPERR_NO_ERROR) {
- return err;
- }
-
-#if !defined(O3D_INTERNAL_PLUGIN)
-#if defined(OS_WIN) || defined(OS_MACOSX)
- if (g_logger) {
- // Do a last sweep to aggregate metrics before we shut down
- g_logger->ProcessMetrics(true, false, false);
- delete g_logger;
- g_logger = NULL;
- g_logging_initialized = false;
- stats_report::g_global_metrics.Uninitialize();
- }
-#endif // OS_WIN || OS_MACOSX
-
- CommandLine::Reset();
-
-#ifdef OS_WIN
- // Strictly speaking, on windows, it's not really necessary to call
- // Stop(), but we do so for completeness
- if (g_bluescreen_detector) {
- g_bluescreen_detector->Stop();
- delete g_bluescreen_detector;
- g_bluescreen_detector = NULL;
- }
-#endif // OS_WIN
-#endif // O3D_INTERNAL_PLUGIN
-
- return o3d::PlatformPostNPShutdown();
-}
-
-NPError EXPORT_SYMBOL OSCALL NP_GetEntryPoints(NPPluginFuncs *pluginFuncs) {
- HANDLE_CRASHES;
- pluginFuncs->version = 11;
- pluginFuncs->size = sizeof(*pluginFuncs);
- pluginFuncs->newp = o3d::NPP_New;
- pluginFuncs->destroy = o3d::NPP_Destroy;
- pluginFuncs->setwindow = o3d::NPP_SetWindow;
- pluginFuncs->newstream = o3d::NPP_NewStream;
- pluginFuncs->destroystream = o3d::NPP_DestroyStream;
- pluginFuncs->asfile = o3d::NPP_StreamAsFile;
- pluginFuncs->writeready = o3d::NPP_WriteReady;
- pluginFuncs->write = o3d::NPP_Write;
- pluginFuncs->print = o3d::NPP_Print;
- pluginFuncs->event = o3d::NPP_HandleEvent;
- pluginFuncs->urlnotify = o3d::NPP_URLNotify;
- pluginFuncs->getvalue = o3d::NPP_GetValue;
- pluginFuncs->setvalue = o3d::NPP_SetValue;
-
- return NPERR_NO_ERROR;
-}
-
-char* NP_GetMIMEDescription(void) {
- return const_cast<char*>(O3D_PLUGIN_NPAPI_MIMETYPE "::O3D MIME");
-}
-
-} // namespace o3d / extern "C"
-
-#if !defined(O3D_INTERNAL_PLUGIN)
-extern "C" {
-NPError EXPORT_SYMBOL NP_GetValue(void *instance, NPPVariable variable,
- void *value) {
- return o3d::NP_GetValue(variable, value);
-}
-}
-#endif
diff --git a/o3d/plugin/cross/main.h b/o3d/plugin/cross/main.h
deleted file mode 100644
index d54fed2..0000000
--- a/o3d/plugin/cross/main.h
+++ /dev/null
@@ -1,171 +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 header is used by the platform-specific portions of the plugin
-// main implementation to define the cross-platform parts of the
-// interface and global variables.
-
-#ifndef O3D_PLUGIN_CROSS_MAIN_H_
-#define O3D_PLUGIN_CROSS_MAIN_H_
-
-#include <npfunctions.h>
-
-#include "plugin/cross/o3d_glue.h"
-#include "plugin/cross/plugin_logging.h"
-#include "plugin/cross/stream_manager.h"
-#include "third_party/nixysa/static_glue/npapi/common.h"
-#include "third_party/nixysa/static_glue/npapi/npn_api.h"
-
-#if defined(OS_LINUX) && !defined(O3D_INTERNAL_PLUGIN)
-#define EXPORT_SYMBOL __attribute__((visibility ("default")))
-#else
-#define EXPORT_SYMBOL
-#endif
-
-#if defined(O3D_INTERNAL_PLUGIN)
-#define HANDLE_CRASHES void(0)
-#else // O3D_INTERNAL_PLUGIN
-
-#if defined(OS_WIN) || defined(OS_MACOSX)
-extern o3d::PluginLogging *g_logger;
-#endif
-
-// BreakpadEnabler is a simple class to keep track of whether or not
-// we're executing code that we want to handle crashes for
-// (when the o3d plugin is running in Firefox, we don't want to handle
-// crashes for the Flash plugin or Firefox, just the o3d code)
-// Create a stack-based instance at the start of each function
-// where crash handling is desired.
-
-#define HANDLE_CRASHES BreakpadEnabler enabler
-
-class BreakpadEnabler {
- public:
- BreakpadEnabler() {
- ++scope_count_;
- }
-
- virtual ~BreakpadEnabler() {
- --scope_count_;
- }
-
- static bool IsEnabled() { return scope_count_ > 0; }
-
- private:
- static int scope_count_;
-};
-
-#endif // O3D_INTERNAL_PLUGIN
-
-#if defined(O3D_INTERNAL_PLUGIN)
-namespace o3d {
-#else
-extern "C" {
-#endif
- NPError EXPORT_SYMBOL OSCALL NP_Initialize(NPNetscapeFuncs *browserFuncs
-#ifdef OS_LINUX
- ,
- NPPluginFuncs *pluginFuncs
-#endif
- );
-
- NPError EXPORT_SYMBOL OSCALL NP_Shutdown(void);
- NPError EXPORT_SYMBOL OSCALL NP_GetEntryPoints(NPPluginFuncs *pluginFuncs);
-}
-
-namespace o3d {
-
-// Plugin entry points, implemented in main.cc.
-
-NPError NPP_Destroy(NPP instance, NPSavedData **save);
-NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason);
-NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value);
-
-NPError NPP_New(NPMIMEType pluginType,
- NPP instance,
- uint16 mode,
- int16 argc,
- char *argn[],
- char *argv[],
- NPSavedData *saved);
-
-NPError NPP_NewStream(NPP instance,
- NPMIMEType type,
- NPStream *stream,
- NPBool seekable,
- uint16 *stype);
-
-NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value);
-NPError NPP_SetWindow(NPP instance, NPWindow *window);
-
-int32 NPP_Write(NPP instance,
- NPStream *stream,
- int32 offset,
- int32 len,
- void *buffer);
-
-int32 NPP_WriteReady(NPP instance, NPStream *stream);
-void NPP_Print(NPP instance, NPPrint *platformPrint);
-int16 NPP_HandleEvent(NPP instance, void *event);
-
-void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname);
-
-void NPP_URLNotify(NPP instance,
- const char *url,
- NPReason reason,
- void *notifyData);
-
-// Platform-specific helpers, implemented in main_<platform>.(cc|mm)
-
-NPError PlatformPreNPInitialize();
-NPError PlatformPostNPInitialize();
-NPError PlatformPreNPShutdown();
-NPError PlatformPostNPShutdown();
-
-NPError PlatformNPPDestroy(NPP instance, glue::_o3d::PluginObject *obj);
-NPError PlatformNPPGetValue(glue::_o3d::PluginObject *obj,
- NPPVariable variable,
- void *value);
-int16 PlatformNPPHandleEvent(NPP instance,
- glue::_o3d::PluginObject *obj,
- void *event);
-NPError PlatformNPPNew(NPP instance, glue::_o3d::PluginObject *obj);
-NPError PlatformNPPSetWindow(NPP instance,
- glue::_o3d::PluginObject *obj,
- NPWindow *window);
-void PlatformNPPStreamAsFile(glue::StreamManager *stream_manager,
- NPStream *stream,
- const char *fname);
-
-}; // namespace o3d
-
-#endif // O3D_PLUGIN_CROSS_MAIN_H_
diff --git a/o3d/plugin/cross/main_remote_cb.cc b/o3d/plugin/cross/main_remote_cb.cc
deleted file mode 100644
index e2346ed..0000000
--- a/o3d/plugin/cross/main_remote_cb.cc
+++ /dev/null
@@ -1,210 +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 implements the entry points for the windowless O3D plugin that
-// relies on a GPU plugin for output.
-
-#include "base/at_exit.h"
-#include "base/command_line.h"
-#include "base/logging.h"
-#include "base/scoped_ptr.h"
-#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"
-#include "gpu_plugin/np_utils/np_object_pointer.h"
-#include "gpu_plugin/np_utils/np_utils.h"
-#include "plugin/cross/main.h"
-
-using glue::_o3d::PluginObject;
-using glue::StreamManager;
-using o3d::Event;
-using gpu_plugin::NPObjectPointer;
-using gpu_plugin::NPInvoke;
-
-namespace {
-const uint32 kTimerInterval = 16;
-
-gpu_plugin::NPBrowser* g_browser;
-
-#if defined(OS_WIN)
-const wchar_t* const kLogFile = L"debug.log";
-#else
-const char* const kLogFile = "debug.log";
-#endif
-} // end anonymous namespace
-
-#if defined(O3D_INTERNAL_PLUGIN)
-namespace o3d {
-#else
-extern "C" {
-#endif
-
-NPError EXPORT_SYMBOL OSCALL NP_Initialize(NPNetscapeFuncs *browserFuncs) {
- CommandLine::Init(0, NULL);
- InitLogging(kLogFile,
- logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,
- logging::DONT_LOCK_LOG_FILE,
- logging::APPEND_TO_OLD_LOG_FILE);
-
- NPError retval = InitializeNPNApi(browserFuncs);
- if (retval != NPERR_NO_ERROR) return retval;
-
- g_browser = new gpu_plugin::NPBrowser(browserFuncs);
-
- return NPERR_NO_ERROR;
-}
-
-NPError EXPORT_SYMBOL OSCALL NP_Shutdown(void) {
- DLOG(INFO) << "NP_Shutdown";
-
- CommandLine::Reset();
-
- return NPERR_NO_ERROR;
-}
-
-} // namespace o3d / extern "C"
-
-namespace o3d {
-
-NPError PlatformNPPGetValue(NPP instance, NPPVariable variable, void *value) {
- return NPERR_NO_ERROR;
-}
-
-void OnTimer(NPP instance, uint32 timer_id) {
- PluginObject* plugin_object = static_cast<PluginObject*>(instance->pdata);
- if (plugin_object) {
- // If the GPU plugin object has been set and the renderer is not initialized
- // then attempt to initialize it.
- NPObjectPointer<NPObject> gpu_plugin_object(
- plugin_object->GetGPUPluginObject());
- if (gpu_plugin_object.Get() && !plugin_object->renderer()) {
- NPObjectPointer<NPObject> command_buffer;
- if (NPInvoke(plugin_object->npp(),
- gpu_plugin_object,
- "openCommandBuffer",
- &command_buffer)) {
- DisplayWindowCB default_display;
- default_display.set_npp(plugin_object->npp());
- default_display.set_command_buffer(command_buffer);
- plugin_object->CreateRenderer(default_display);
-
- // Get the GPU plugins size and resize the renderer.
- int32 width;
- int32 height;
- if (NPInvoke(plugin_object->npp(),
- gpu_plugin_object,
- "getWidth",
- &width) &&
- NPInvoke(plugin_object->npp(),
- gpu_plugin_object,
- "getHeight",
- &height)) {
- plugin_object->renderer()->Resize(width, height);
- plugin_object->client()->Init();
- }
- }
- }
-
- plugin_object->client()->Tick();
- if (plugin_object->client()->render_mode() ==
- o3d::Client::RENDERMODE_CONTINUOUS) {
- plugin_object->client()->RenderClient(true);
- }
- }
-}
-
-NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc,
- char *argn[], char *argv[], NPSavedData *saved) {
- NPError error = NPN_SetValue(
- instance, NPPVpluginWindowBool, reinterpret_cast<void*>(false));
- if (error != NPERR_NO_ERROR)
- return error;
-
- PluginObject* plugin_object = glue::_o3d::PluginObject::Create(
- instance);
- instance->pdata = plugin_object;
- glue::_o3d::InitializeGlue(instance);
- plugin_object->Init(argc, argn, argv);
-
- gpu_plugin::NPBrowser::get()->ScheduleTimer(instance,
- kTimerInterval,
- true,
- OnTimer);
-
- return NPERR_NO_ERROR;
-}
-
-NPError NPP_Destroy(NPP instance, NPSavedData **save) {
- PluginObject *plugin_object = static_cast<PluginObject*>(instance->pdata);
- if (plugin_object) {
- plugin_object->TearDown();
- NPN_ReleaseObject(plugin_object);
- instance->pdata = NULL;
- }
-
- return NPERR_NO_ERROR;
-}
-
-NPError NPP_SetWindow(NPP instance, NPWindow *window) {
- return NPERR_NO_ERROR;
-}
-
-// Called when the browser has finished attempting to stream data to
-// a file as requested. If fname == NULL the attempt was not successful.
-void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname) {
- PluginObject *plugin_object = static_cast<PluginObject*>(instance->pdata);
- StreamManager *stream_manager = plugin_object->stream_manager();
- stream_manager->SetStreamFile(stream, fname);
-}
-
-int16 NPP_HandleEvent(NPP instance, void *event) {
- return 0;
-}
-} // namespace o3d
-
-namespace glue {
-namespace _o3d {
-bool PluginObject::GetDisplayMode(int mode_id, o3d::DisplayMode *mode) {
- return renderer()->GetDisplayMode(mode_id, mode);
-}
-
-// TODO: Where should this really live? It's platform-specific, but in
-// PluginObject, which mainly lives in cross/o3d_glue.h+cc.
-bool PluginObject::RequestFullscreenDisplay() {
- return false;
-}
-
-void PluginObject::CancelFullscreenDisplay() {
-}
-} // namespace _o3d
-} // namespace glue
diff --git a/o3d/plugin/cross/main_thread_task_poster.cc b/o3d/plugin/cross/main_thread_task_poster.cc
deleted file mode 100644
index d20b206..0000000
--- a/o3d/plugin/cross/main_thread_task_poster.cc
+++ /dev/null
@@ -1,62 +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 <npapi.h>
-#include "npn_api.h"
-#include "plugin/cross/main_thread_task_poster.h"
-
-namespace o3d {
-
-MainThreadTaskPoster::MainThreadTaskPoster(ServiceLocator* service_locator,
- NPP npp)
- : service_(service_locator, this),
- npp_(npp) {
-}
-
-MainThreadTaskPoster::~MainThreadTaskPoster() {
-}
-
-bool MainThreadTaskPoster::IsSupported() {
- return IsPluginThreadAsyncCallSupported(npp_);
-}
-
-void MainThreadTaskPoster::PostTask(Task* task) {
- DCHECK(IsSupported());
- NPN_PluginThreadAsyncCall(npp_, &MainThreadTaskPoster::RunTask, task);
-}
-
-void MainThreadTaskPoster::RunTask(void* data) {
- Task* task = static_cast<Task*>(data);
- task->Run();
- delete task;
-}
-} // namespace o3d
diff --git a/o3d/plugin/cross/main_thread_task_poster.h b/o3d/plugin/cross/main_thread_task_poster.h
deleted file mode 100644
index e322af1..0000000
--- a/o3d/plugin/cross/main_thread_task_poster.h
+++ /dev/null
@@ -1,57 +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_PLUGIN_CROSS_MAIN_THREAD_TASK_POSTER_H
-#define O3D_PLUGIN_CROSS_MAIN_THREAD_TASK_POSTER_H
-
-#include <npapi.h>
-#include "core/cross/imain_thread_task_poster.h"
-#include "core/cross/service_implementation.h"
-
-namespace o3d {
-
-class MainThreadTaskPoster : public IMainThreadTaskPoster {
- public:
- MainThreadTaskPoster(ServiceLocator* service_locator, NPP npp);
- virtual ~MainThreadTaskPoster();
- virtual bool IsSupported();
- virtual void PostTask(Task* task);
- private:
- static void RunTask(void* data);
- ServiceImplementation<IMainThreadTaskPoster> service_;
- NPP npp_;
- DISALLOW_COPY_AND_ASSIGN(MainThreadTaskPoster);
-};
-
-} // namespace o3d
-
-#endif // O3D_PLUGIN_CROSS_MAIN_THREAD_TASK_POSTER_H
diff --git a/o3d/plugin/cross/marshaling_utils.h b/o3d/plugin/cross/marshaling_utils.h
deleted file mode 100644
index 1a8b4d0..0000000
--- a/o3d/plugin/cross/marshaling_utils.h
+++ /dev/null
@@ -1,129 +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 utility functions for marshaling between
-// C++ types and dynamic types.
-
-#ifndef O3D_PLUGIN_CROSS_MARSHALING_UTILS_H_
-#define O3D_PLUGIN_CROSS_MARSHALING_UTILS_H_
-
-#include <vector>
-
-namespace o3d {
-
-// Converts a std::vector<float>, representing a JavaScript array
-// of numbers, to a FloatN, VectorN, or PointN. This template function
-// supports conversion to any type which accesses float elements using
-// operator[].
-template <typename VectorType, int dimension>
-VectorType VectorToType(void* plugin_data,
- const std::vector<float>& dynamic_value) {
- if (dynamic_value.size() != dimension) {
- o3d::ServiceLocator* service_locator =
- static_cast<glue::_o3d::PluginObject*>(
- plugin_data)->service_locator();
- O3D_ERROR(service_locator)
- << "Vector type expected array of " << dimension
- << " number values, got " << dynamic_value.size();
- return VectorType();
- }
- VectorType vector_value;
- for (int i = 0; i < dimension; ++i) {
- vector_value[i] = dynamic_value[i];
- }
- return vector_value;
-}
-
-// Converts a FloatN, VectorN or PointN to an std::vector<float>.
-// This template function supports conversion from any type which
-// accesses float elements using operator[].
-template <typename VectorType, int dimension>
-std::vector<float> VectorFromType(const VectorType& vector_value) {
- std::vector<float> dynamic_value(dimension);
- for (int i = 0; i < dimension; ++i) {
- dynamic_value[i] = vector_value[i];
- }
- return dynamic_value;
-}
-
-// Converts an std::vector<std::vector<float> > to a MatrixN.
-template <typename MatrixType, int rows, int columns>
-MatrixType VectorOfVectorToType(
- void* plugin_data,
- const std::vector<std::vector<float> >& dynamic_value) {
- if (dynamic_value.size() != rows) {
- o3d::ServiceLocator* service_locator =
- static_cast<glue::_o3d::PluginObject*>(
- plugin_data)->service_locator();
- O3D_ERROR(service_locator)
- << "Matrix type expected array of " << rows
- << " arrays of " << columns << " number values, got "
- << dynamic_value.size() << " rows";
- return MatrixType();
- }
- MatrixType matrix_value;
- for (int i = 0; i != rows; ++i) {
- if (dynamic_value[i].size() != columns) {
- o3d::ServiceLocator* service_locator =
- static_cast<glue::_o3d::PluginObject*>(
- plugin_data)->service_locator();
- O3D_ERROR(service_locator)
- << "Matrix type expected array of " << rows
- << " arrays of " << columns << " number values, got "
- << dynamic_value[i].size() << " columns in row "
- << i;
- return MatrixType();
- }
- for (int j = 0; j < columns; ++j) {
- matrix_value.setElem(i, j, dynamic_value[i][j]);
- }
- }
- return matrix_value;
-}
-
-// Converts a MatrixN to a std::vector<std::vector<float> >.
-template <typename MatrixType, int rows, int columns>
-std::vector<std::vector<float> > VectorOfVectorFromType(
- const MatrixType& matrix_value) {
- std::vector<std::vector<float> > dynamic_value(rows);
- for (int i = 0; i < rows; ++i) {
- dynamic_value[i].resize(columns);
- for (int j = 0; j < columns; ++j) {
- dynamic_value[i][j] = matrix_value.getElem(i, j);
- }
- }
- return dynamic_value;
-}
-
-} // namespace o3d
-
-#endif // O3D_PLUGIN_CROSS_MARSHALING_UTILS_H_
diff --git a/o3d/plugin/cross/np_v8_bridge.cc b/o3d/plugin/cross/np_v8_bridge.cc
deleted file mode 100644
index ced02d2..0000000
--- a/o3d/plugin/cross/np_v8_bridge.cc
+++ /dev/null
@@ -1,1578 +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.
- */
-
-
-// Code relating to interoperation of V8 JavaScript engine with NPAPI.
-// Tests are in o3d/tests/selenium/tests/v8.html. They can be run
-// by opening the web page in a browser or as part of the selenium tests.
-
-#include <npapi.h>
-#include <sstream>
-#include <vector>
-#include "base/scoped_ptr.h"
-#include "plugin/cross/np_v8_bridge.h"
-
-using v8::AccessorInfo;
-using v8::Arguments;
-using v8::Array;
-using v8::Context;
-using v8::DontDelete;
-using v8::DontEnum;
-using v8::External;
-using v8::Function;
-using v8::FunctionTemplate;
-using v8::HandleScope;
-using v8::Int32;
-using v8::Integer;
-using v8::Local;
-using v8::Message;
-using v8::Null;
-using v8::Number;
-using v8::Object;
-using v8::ObjectTemplate;
-using v8::Persistent;
-using v8::PropertyAttribute;
-using v8::ReadOnly;
-using v8::Script;
-using v8::TryCatch;
-using v8::Undefined;
-using v8::Value;
-
-namespace o3d {
-
-// Only used during debugging. Type "o3d::DebugV8String(a.val_)" in the
-// watch window to get the string representation of a V8 object.
-const char* DebugV8String(Value* value) {
- static char buffer[4096];
- if (value == NULL) {
- ::base::snprintf(buffer, sizeof(buffer), "<null>");
- } else {
- value->ToString()->WriteUtf8(buffer);
- }
- return buffer;
-}
-
-namespace {
-
-// The indices of the internal fields of a V8 proxy for an NPObject.
-enum {
- // Pointer to the bridge that created the proxy.
- V8_NP_OBJECT_BRIDGE,
- // Pointer to the wrapped NPObject.
- V8_NP_OBJECT_WRAPPED,
- V8_NP_OBJECT_NUM_INTERNAL_FIELDS
-};
-
-// The name of the "hidden" property in a V8 non-proxy object that contains
-// an External that points to the NPObject proxy for it. The property does
-// not exist if there is no associated NPObject proxy.
-const char* const kInternalProperty = "internal_property_";
-
-// Convert an NPIdentifier (NULL, string or integer) to a V8 value.
-Local<Value> NPToV8Identifier(NPIdentifier np_identifier) {
- if (np_identifier == NULL) {
- return Local<Value>();
- } else if (NPN_IdentifierIsString(np_identifier)) {
- NPUTF8* utf8_name = NPN_UTF8FromIdentifier(np_identifier);
- Local<v8::String> v8_identifier = v8::String::New(utf8_name);
- NPN_MemFree(utf8_name);
- return v8_identifier;
- } else {
- return Integer::New(NPN_IntFromIdentifier(np_identifier));
- }
-}
-
-// Convert a V8 value (empty, string or integer) into an NPIdentifier.
-NPIdentifier V8ToNPIdentifier(v8::Handle<Value> v8_identifier) {
- if (v8_identifier.IsEmpty()) {
- return NULL;
- } else if (v8_identifier->IsNumber()) {
- return NPN_GetIntIdentifier(v8_identifier->Int32Value());
- } else if (v8_identifier->IsString()) {
- return NPN_GetStringIdentifier(
- *v8::String::Utf8Value(v8_identifier->ToString()));
- } else {
- return NULL;
- }
-}
-} // namespace anonymous
-
-// The class of NPObject proxies that wrap V8 objects. These field the NPAPI
-// functions and translate them into V8 calls.
-class NPV8Object : public NPObject {
- public:
- static NPObjectPtr<NPV8Object> Create(NPV8Bridge* bridge,
- Local<Object> v8_object) {
- NPObjectPtr<NPV8Object> np_object =
- NPObjectPtr<NPV8Object>::AttachToReturned(
- static_cast<NPV8Object*>(NPN_CreateObject(bridge->npp(),
- &np_class_)));
- np_object->v8_object_ = Persistent<Object>::New(v8_object);
- np_object->bridge_ = bridge;
- return np_object;
- }
-
- v8::Handle<Object> v8_object() const {
- return v8_object_;
- }
-
- // Drop references between NPObject and V8 object. Must be called before the
- // NPObject is destroyed so V8 can garbage collect the associated V8 object.
- void UnlinkFromV8() {
- HandleScope handle_scope;
- if (!v8_object_.IsEmpty()) {
- v8_object_->DeleteHiddenValue(v8::String::NewSymbol(kInternalProperty));
- v8_object_.Dispose();
- v8_object_.Clear();
- }
- }
-
- static NPClass np_class_;
-
- private:
- NPV8Object() : bridge_(NULL) {
- }
-
- static NPObject* Allocate(NPP npp, NPClass* np_class) {
- v8::Locker locker;
-
- NPV8Object* np_v8_object = new NPV8Object();
- np_v8_object->bridge_ = NULL;
- return np_v8_object;
- }
-
- static void Deallocate(NPObject* np_object) {
- v8::Locker locker;
-
- NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
- // Uncomment this line to see objects with a non-zero reference
- // count being deallocated. For example, Firefox does this when unloading
- // the plugin.
- // DCHECK_EQ(0, np_v8_object_map->referenceCount);
- np_v8_object->UnlinkFromV8();
- delete np_v8_object;
- }
-
- static void Invalidate(NPObject* np_object) {
- v8::Locker locker;
-
- NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
- np_v8_object->bridge_ = NULL;
- np_v8_object->UnlinkFromV8();
- }
-
- static bool HasMethod(NPObject* np_object, NPIdentifier np_name) {
- v8::Locker locker;
-
- NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
- NPV8Bridge* bridge = np_v8_object->bridge_;
- if (bridge == NULL)
- return false;
-
- HandleScope handle_scope;
- Context::Scope scope(bridge->script_context());
- TryCatch tryCatch;
-
- v8::Handle<Object> v8_object = np_v8_object->v8_object_;
- if (v8_object.IsEmpty())
- return false;
-
- Local<Value> v8_name = NPToV8Identifier(np_name);
- Local<Value> value = v8_object->Get(v8_name);
- if (tryCatch.HasCaught()) {
- bridge->ReportV8Exception(tryCatch);
- return false;
- }
-
- // Returns true iff the object has a property with the given name and
- // the object assigned to the property is a function. This works for V8
- // functions and assigned browser JavaScript functions (because their
- // proxies are created from FunctionTemplates so V8 considers them to be
- // functions).
- return !value.IsEmpty() && value->IsFunction();
- }
-
- // Called when a method is invoked through "obj.m(...)".
- static bool Invoke(NPObject* np_object, NPIdentifier np_name,
- const NPVariant* np_args, uint32_t numArgs,
- NPVariant* result) {
- v8::Locker locker;
-
- // This works around a bug in Chrome:
- // http://code.google.com/p/chromium/issues/detail?id=5110
- // NPN_InvokeDefault is transformed into a call to Invoke on the plugin with
- // a null method name identifier.
- if (np_name == NULL) {
- return InvokeDefault(np_object, np_args, numArgs, result);
- }
-
- NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
- NPV8Bridge* bridge = np_v8_object->bridge_;
- if (bridge == NULL)
- return false;
-
- HandleScope handle_scope;
- Context::Scope scope(bridge->script_context());
- TryCatch tryCatch;
-
- v8::Handle<Object> v8_object = np_v8_object->v8_object_;
- if (v8_object.IsEmpty())
- return false;
-
- Local<Value> v8_name = NPToV8Identifier(np_name);
- Local<Value> value = v8_object->Get(v8_name);
- if (value.IsEmpty() || !value->IsFunction())
- return false;
- Local<Function> function = Local<Function>::Cast(value);
- std::vector<v8::Handle<Value> > v8_args(numArgs);
- for (uint32_t i = 0; i != numArgs; ++i) {
- v8_args[i] = bridge->NPToV8Variant(np_args[i]);
- }
-
- *result = bridge->V8ToNPVariant(
- function->Call(v8_object, numArgs,
- numArgs == 0 ? NULL : &v8_args.front()));
- if (tryCatch.HasCaught()) {
- bridge->ReportV8Exception(tryCatch);
- return false;
- }
- return true;
- }
-
- // Called when an object is called as a function "f(...)".
- static bool InvokeDefault(NPObject* np_object, const NPVariant* np_args,
- uint32_t numArgs, NPVariant* result) {
- v8::Locker locker;
-
- NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
- NPV8Bridge* bridge = np_v8_object->bridge_;
- if (bridge == NULL)
- return false;
-
- HandleScope handle_scope;
- Context::Scope scope(bridge->script_context());
- TryCatch tryCatch;
-
- v8::Handle<Object> v8_object = np_v8_object->v8_object_;
- if (v8_object.IsEmpty())
- return false;
-
- if (!v8_object->IsFunction())
- return false;
- v8::Handle<Function> function = v8::Handle<Function>::Cast(v8_object);
-
- std::vector<v8::Handle<Value> > v8_args(numArgs);
- for (uint32_t i = 0; i != numArgs; ++i) {
- v8_args[i] = bridge->NPToV8Variant(np_args[i]);
- }
-
- *result = bridge->V8ToNPVariant(
- function->Call(v8_object, numArgs,
- numArgs == 0 ? NULL : &v8_args.front()));
- if (tryCatch.HasCaught()) {
- bridge->ReportV8Exception(tryCatch);
- return false;
- }
- return true;
- }
-
- // Called when an object is called as a constructor "new C(...)".
- static bool Construct(NPObject* np_object, const NPVariant* np_args,
- uint32_t numArgs, NPVariant* result) {
- v8::Locker locker;
-
- NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
- NPV8Bridge* bridge = np_v8_object->bridge_;
- if (bridge == NULL)
- return false;
-
- HandleScope handle_scope;
- Context::Scope scope(bridge->script_context());
- TryCatch tryCatch;
-
- v8::Handle<Object> v8_object = np_v8_object->v8_object_;
- if (v8_object.IsEmpty())
- return false;
-
- if (!v8_object->IsFunction())
- return false;
- v8::Handle<Function> function = v8::Handle<Function>::Cast(v8_object);
-
- std::vector<v8::Handle<Value> > v8_args(numArgs);
- for (uint32_t i = 0; i != numArgs; ++i) {
- v8_args[i] = bridge->NPToV8Variant(np_args[i]);
- }
-
- Local<Object> v8_result = function->NewInstance(
- numArgs, numArgs == 0 ? NULL : &v8_args.front());
- if (v8_result.IsEmpty())
- return false;
-
- *result = bridge->V8ToNPVariant(v8_result);
- if (tryCatch.HasCaught()) {
- bridge->ReportV8Exception(tryCatch);
- return false;
- }
- return true;
- }
-
- static bool HasProperty(NPObject* np_object, NPIdentifier np_name) {
- v8::Locker locker;
-
- NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
- NPV8Bridge* bridge = np_v8_object->bridge_;
- if (bridge == NULL)
- return false;
-
- HandleScope handle_scope;
- Context::Scope scope(bridge->script_context());
-
- v8::Handle<Object> v8_object = np_v8_object->v8_object_;
- if (v8_object.IsEmpty())
- return false;
-
- // This is a better approach than the one below. It allows functions
- // to be retreived as first class objects. Unfortunately we can't
- // support this yet because of a Chrome bug:
- // http://code.google.com/p/chromium/issues/detail?id=5742
- // if (NPN_IdentifierIsString(np_name)) {
- // Local<v8::String> v8_name = Local<v8::String>::Cast(
- // NPToV8Identifier(np_name));
- // return v8_object->Has(v8_name);
- // } else {
- // return v8_object->Has(NPN_IntFromIdentifier(np_name));
- // }
-
- // Instead hide properties with function type. This ensures that Chrome
- // will invoke them with Invoke rather than InvokeDefault. The problem
- // with InvokeDefault is it doesn't tell us what "this" should be
- // bound to, whereas Invoke does.
- Local<Value> v8_name = NPToV8Identifier(np_name);
- if (NPN_IdentifierIsString(np_name)) {
- if (!v8_object->Has(v8_name->ToString())) {
- return false;
- }
- } else {
- if (!v8_object->Has(NPN_IntFromIdentifier(np_name))) {
- return false;
- }
- }
- Local<Value> v8_property_value = v8_object->Get(v8_name);
- if (v8_property_value->IsFunction()) {
- return false;
- }
-
- return true;
- }
-
- static bool GetProperty(NPObject* np_object, NPIdentifier np_name,
- NPVariant* result) {
- v8::Locker locker;
-
- NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
- NPV8Bridge* bridge = np_v8_object->bridge_;
- if (bridge == NULL)
- return false;
-
- HandleScope handle_scope;
- Context::Scope scope(bridge->script_context());
- TryCatch tryCatch;
-
- v8::Handle<Object> v8_object = np_v8_object->v8_object_;
- if (v8_object.IsEmpty())
- return false;
-
- Local<Value> v8_name = NPToV8Identifier(np_name);
- Local<Value> v8_property_value = v8_object->Get(v8_name);
- if (tryCatch.HasCaught()) {
- bridge->ReportV8Exception(tryCatch);
- return false;
- }
-
- // See comment in HasProperty. Do not return properties that are
- // functions. It will prevent Chrome from invoking them as methods.
- if (v8_property_value.IsEmpty() || v8_property_value->IsFunction())
- return false;
-
- *result = bridge->V8ToNPVariant(v8_property_value);
- return true;
- }
-
- static bool SetProperty(NPObject* np_object, NPIdentifier np_name,
- const NPVariant* np_value) {
- v8::Locker locker;
-
- NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
- NPV8Bridge* bridge = np_v8_object->bridge_;
- if (bridge == NULL)
- return false;
-
- HandleScope handle_scope;
- Context::Scope scope(bridge->script_context());
- TryCatch tryCatch;
-
- v8::Handle<Object> v8_object = np_v8_object->v8_object_;
- if (v8_object.IsEmpty())
- return false;
-
- Local<Value> v8_name = NPToV8Identifier(np_name);
- bool success = v8_object->Set(v8_name, bridge->NPToV8Variant(*np_value));
-
- if (tryCatch.HasCaught()) {
- bridge->ReportV8Exception(tryCatch);
- return false;
- }
-
- return success;
- }
-
- static bool RemoveProperty(NPObject* np_object, NPIdentifier np_name) {
- v8::Locker locker;
-
- NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
- NPV8Bridge* bridge = np_v8_object->bridge_;
- if (bridge == NULL)
- return false;
-
- HandleScope handle_scope;
- Context::Scope scope(bridge->script_context());
- TryCatch tryCatch;
-
- v8::Handle<Object> v8_object = np_v8_object->v8_object_;
- if (v8_object.IsEmpty())
- return false;
-
- bool success;
- if (NPN_IdentifierIsString(np_name)) {
- NPUTF8* utf8_name = NPN_UTF8FromIdentifier(np_name);
- Local<v8::String> v8_name = v8::String::New(utf8_name);
- NPN_MemFree(utf8_name);
- success = v8_object->Delete(v8_name);
- } else {
- success = v8_object->Delete(NPN_IntFromIdentifier(np_name));
- }
-
- if (tryCatch.HasCaught()) {
- bridge->ReportV8Exception(tryCatch);
- return false;
- }
-
- return success;
- }
-
- static bool Enumerate(NPObject* np_object, NPIdentifier** np_names,
- uint32_t* numNames) {
- v8::Locker locker;
-
- NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
- NPV8Bridge* bridge = np_v8_object->bridge_;
- if (bridge == NULL)
- return false;
-
- HandleScope handle_scope;
- Context::Scope scope(bridge->script_context());
-
- v8::Handle<Object> v8_object = np_v8_object->v8_object_;
- if (v8_object.IsEmpty())
- return false;
-
- Local<Array> v8_names = v8_object->GetPropertyNames();
-
- // Due to a bug in Chrome, need to filter out any properties that
- // are functions. See comment in HasProperty.
- int num_non_function_properties = 0;
- int length = v8_names->Length();
- for (int i = 0; i < length; ++i) {
- Local<Value> v8_property_value =
- v8_object->Get(v8_names->Get(Int32::New(i)));
- if (!v8_property_value->IsFunction()) {
- ++num_non_function_properties;
- }
- }
- *numNames = num_non_function_properties;
- *np_names = static_cast<NPIdentifier*> (
- NPN_MemAlloc(num_non_function_properties * sizeof(NPIdentifier)));
- int j = 0;
- for (uint32_t i = 0; i != v8_names->Length(); ++i) {
- Local<Value> v8_name = v8_names->Get(Int32::New(i));
- Local<Value> v8_property_value = v8_object->Get(v8_name);
- if (!v8_property_value->IsFunction()) {
- (*np_names)[j++] = V8ToNPIdentifier(v8_name);
- }
- }
-
- return true;
- }
-
- NPV8Bridge* bridge_;
- AutoV8Persistent<Object> v8_object_;
- DISALLOW_COPY_AND_ASSIGN(NPV8Object);
-};
-
-NPClass NPV8Object::np_class_ = {
- NP_CLASS_STRUCT_VERSION,
- Allocate,
- Deallocate,
- Invalidate,
- HasMethod,
- Invoke,
- InvokeDefault,
- HasProperty,
- GetProperty,
- SetProperty,
- RemoveProperty,
- Enumerate,
- Construct
-};
-
-NPV8Bridge::NPV8Bridge(ServiceLocator* service_locator, NPP npp)
- : service_locator_(service_locator),
- error_status_(service_locator),
- npp_(npp) {
- np_name_identifier_ = NPN_GetStringIdentifier("name");
- np_call_identifier_ = NPN_GetStringIdentifier("call");
- np_length_identifier_ = NPN_GetStringIdentifier("length");
- np_proxy_identifier_ = NPN_GetStringIdentifier("npv8_proxy_");
-}
-
-NPV8Bridge::~NPV8Bridge() {
- v8::Locker locker;
-
- // Do not call weak reference callback after the bridge is destroyed
- // because the callbacks assume it exists. The only purpose of the callback
- // is to remove the corresponding object entry from the NP-V8 object map
- // and its about to get cleared anyway.
- for (NPV8ObjectMap::iterator it = np_v8_object_map_.begin();
- it != np_v8_object_map_.end(); ++it) {
- it->second.ClearWeak();
- }
-}
-
-NPObjectPtr<NPObject> NPV8Bridge::NPEvaluateObject(const char* script) {
- NPString np_script = { script, strlen(script) };
- NPVariant np_variant;
- NPObjectPtr<NPObject> np_result;
- if (NPN_Evaluate(npp_, global_np_object_.Get(), &np_script, &np_variant)) {
- if (NPVARIANT_IS_OBJECT(np_variant)) {
- np_result = NPObjectPtr<NPObject>(NPVARIANT_TO_OBJECT(np_variant));
- }
- NPN_ReleaseVariantValue(&np_variant);
- }
- return np_result;
-}
-
-namespace {
-// Create code that looks like this:
-// (function(func, protoArray) {
-// return function() {
-// switch (arguments.length) {
-// case 0:
-// return func.call(this);
-// case 1:
-// return func.call(this,
-// arguments[0]);
-// case 2:
-// return func.call(this,
-// arguments[0],
-// arguments[1]);
-// ...
-// default:
-// var args = protoArray.slice();
-// for (var i = 0; i < arguments.length; ++i) {
-// args[i] = arguments[i];
-// }
-// return func.apply(this, args);
-// }
-// };
-// })
-String MakeWrapFunctionScript() {
- std::ostringstream code;
- code << "(function(func, protoArray) {";
- code << " return function() {";
- code << " switch (arguments.length) {";
- for (int i = 0; i <= 10; ++i) {
- code << " case " << i << ": return func.call(this";
- for (int j = 0; j < i; ++j) {
- code << ", arguments[" << j << "]";
- }
- code << ");";
- }
- code << " default:";
- code << " var args = protoArray.slice();";
- code << " for (var i = 0; i < arguments.length; ++i) {";
- code << " args.push(arguments[i]);";
- code << " }";
- code << " return func.apply(this, args);";
- code << " }";
- code << " };";
- code << "})";
- return code.str();
-}
-} // namespace anonymous
-
-void NPV8Bridge::Initialize(const NPObjectPtr<NPObject>& global_np_object) {
- v8::Locker locker;
-
- HandleScope handle_scope;
-
- global_np_object_ = global_np_object;
-
- // This template is used for V8 proxies of NPObjects.
- v8_np_constructor_template_ = Persistent<FunctionTemplate>::New(
- FunctionTemplate::New());
- InitializeV8ObjectTemplate(v8_np_constructor_template_->InstanceTemplate());
-
- // This template is used for the global V8 object.
- Local<FunctionTemplate> v8_global_template = FunctionTemplate::New();
- InitializeV8ObjectTemplate(v8_global_template->PrototypeTemplate());
-
- script_context_ = Context::New(NULL, v8_global_template->InstanceTemplate());
- Context::Scope scope(script_context_);
-
- // Give the global object a prototype that allows V8 to access global
- // variables in another JavaScript environemnt over NPAPI.
- Local<Object> v8_global_prototype =
- Local<Object>::Cast(script_context_->Global()->GetPrototype());
- Local<Object> v8_global_prototype2 =
- Local<Object>::Cast(v8_global_prototype->GetPrototype());
- global_prototype_ = Persistent<Object>::New(v8_global_prototype2);
- NPToV8Object(v8_global_prototype2, global_np_object);
-
- function_map_ = Persistent<Object>::New(Object::New());
-
- // Create a browser JavaScript function that can later be called to get the
- // type of an object (as the browser sees it). This is useful for determining
- // whether an object received over NPAPI is a function (which means its
- // proxy must be created from a FunctionTemplate rather than an
- // ObjectTemplate).
- static const char kIsFunctionScript[] =
- "(function(obj) { return obj instanceof Function; })";
- np_is_function_function_ = NPEvaluateObject(kIsFunctionScript);
-
- // Create a browser JavaScript function that can later be used to enumerate
- // the properties of an object. This is used as a fallback if NPN_Evaluate
- // is not implemented by the browser (like Firefox 2) and the enumerate
- // callback is not implemented by the NPObject.
- static const char kEnumerateScript[] =
- "(function(object) {"
- " var properties = [];"
- " for (var property in object) {"
- " if (object.hasOwnProperty(property)) {"
- " properties[properties.length++] = property;"
- " }"
- " }"
- " return properties;"
- "})";
- np_enumerate_function_ = NPEvaluateObject(kEnumerateScript);
-
- // Create a browser JavaScript function that can later be used to create
- // a wrapper around an V8 function proxy, making it appear to be a real
- // browser function.
- np_wrap_function_function_ = NPEvaluateObject(
- MakeWrapFunctionScript().c_str());
-
- // Create an NPObject proxy for a V8 array. This is for the browser to use as
- // a prototype for creating new V8 arrays with slice().
- np_empty_array_ = V8ToNPObject(v8::Array::New(0));
-}
-
-void NPV8Bridge::ReleaseNPObjects() {
- v8::Locker locker;
-
- np_v8_object_map_.clear();
- np_construct_functions_.clear();
-
- global_np_object_.Clear();
- np_is_function_function_.Clear();
- np_enumerate_function_.Clear();
- np_wrap_function_function_.Clear();
- np_empty_array_.Clear();
-}
-
-v8::Handle<Context> NPV8Bridge::script_context() {
- return script_context_;
-}
-
-bool NPV8Bridge::Evaluate(const NPVariant* np_args, int numArgs,
- NPVariant* np_result) {
- v8::Locker locker;
-
- HandleScope handle_scope;
- Context::Scope scope(script_context_);
-
- Local<Value> v8_code;
- if (numArgs == 1) {
- v8_code = NPToV8Variant(np_args[0]);
- } else {
- return false;
- }
-
- if (v8_code.IsEmpty() || !v8_code->IsString())
- return false;
-
- TryCatch tryCatch;
-
- Local<v8::String> v8_code_string = v8_code->ToString();
- Local<Script> v8_script = v8::Script::Compile(v8_code_string);
-
- if (tryCatch.HasCaught()) {
- // Newer version of v8 doesn't like eval('function () { ... }') but wants
- // instead eval('(function () { ... })'). Old js code may still try to pass
- // that in, so add a pair of ( ) around the given string, and try again.
- tryCatch.Reset();
- int length = v8_code_string->Utf8Length();
- // Note: this string is not 0-terminated.
- scoped_array<char> paren_string(new char[length + 2]);
- v8_code_string->WriteUtf8(paren_string.get() + 1, length);
- paren_string[0] = '(';
- paren_string[length + 1] = ')';
- v8_code_string = v8::String::New(paren_string.get(), length + 2);
-
- v8_script = v8::Script::Compile(v8_code_string);
-
- if (tryCatch.HasCaught()) {
- ReportV8Exception(tryCatch);
- return false;
- }
- }
- if (v8_script.IsEmpty())
- return false;
-
- Local<Value> v8_result = v8_script->Run();
- if (tryCatch.HasCaught()) {
- ReportV8Exception(tryCatch);
- return false;
- }
- if (v8_result.IsEmpty())
- return false;
-
- *np_result = V8ToNPVariant(v8_result);
- return true;
-}
-
-void NPV8Bridge::SetGlobalProperty(const String& name,
- NPObjectPtr<NPObject>& np_object) {
- v8::Locker locker;
-
- HandleScope handle_scope;
- Context::Scope scope(script_context_);
- script_context_->Global()->Set(v8::String::New(name.c_str()),
- NPToV8Object(np_object));
-}
-
-NPVariant NPV8Bridge::V8ToNPVariant(Local<Value> value) {
- NPVariant np_variant;
- if (value.IsEmpty() || value->IsUndefined()) {
- VOID_TO_NPVARIANT(np_variant);
- } else if (value->IsNull()) {
- NULL_TO_NPVARIANT(np_variant);
- } else if (value->IsBoolean()) {
- BOOLEAN_TO_NPVARIANT(value->BooleanValue(), np_variant);
- } else if (value->IsInt32()) {
- INT32_TO_NPVARIANT(value->Int32Value(), np_variant);
- } else if (value->IsNumber()) {
- DOUBLE_TO_NPVARIANT(value->NumberValue(), np_variant);
- } else if (value->IsString()) {
- Local<v8::String> v8_string = value->ToString();
- int utf8_length = v8_string->Length();
- NPUTF8* utf8_chars = static_cast<NPUTF8*>(NPN_MemAlloc(utf8_length + 1));
- v8_string->WriteUtf8(utf8_chars);
- STRINGN_TO_NPVARIANT(utf8_chars, utf8_length, np_variant);
- } else if (value->IsObject()) {
- Local<Object> v8_object = value->ToObject();
- NPObjectPtr<NPObject> np_object = V8ToNPObject(v8_object);
- OBJECT_TO_NPVARIANT(np_object.Disown(), np_variant);
- }
- return np_variant;
-}
-
-Local<Value> NPV8Bridge::NPToV8Variant(const NPVariant& np_variant) {
- Local<Value> v8_result;
- switch (np_variant.type) {
- case NPVariantType_Void:
- v8_result = Local<Value>::New(Undefined());
- break;
- case NPVariantType_Null:
- v8_result = Local<Value>::New(Null());
- break;
- case NPVariantType_Bool:
- v8_result = Local<Value>::New(
- v8::Boolean::New(NPVARIANT_TO_BOOLEAN(np_variant)));
- break;
- case NPVariantType_Int32:
- v8_result = Local<Value>::New(
- Int32::New(NPVARIANT_TO_INT32(np_variant)));
- break;
- case NPVariantType_Double:
- v8_result = Local<Value>::New(
- Number::New(NPVARIANT_TO_DOUBLE(np_variant)));
- break;
- case NPVariantType_String:
- {
- NPString np_string = NPVARIANT_TO_STRING(np_variant);
- v8_result = Local<Value>::New(
- v8::String::New(np_string.UTF8Characters, np_string.UTF8Length));
- break;
- }
- case NPVariantType_Object:
- v8_result = NPToV8Object(
- NPObjectPtr<NPObject>(NPVARIANT_TO_OBJECT(np_variant)));
- break;
- default:
- v8_result = Local<Value>();
- break;
- }
- return v8_result;
-}
-
-NPObjectPtr<NPObject> NPV8Bridge::V8ToNPObject(Local<Value> v8_value) {
- NPObjectPtr<NPObject> np_object;
- if (!v8_value.IsEmpty() && v8_value->IsObject()) {
- Local<Object> v8_object = Local<Object>::Cast(v8_value);
- if (v8_object->InternalFieldCount() == 0) {
- // It is must be a V8 created JavaScript object (or function), a V8
- // function proxy for an NP function or a V8 function proxy for a named
- // native method. If it is already associated with an NP object then that
- // will be stored in the "internal property". Return that if it's there,
- // otherwise create a new NP proxy.
- Local<v8::String> internal_name = v8::String::NewSymbol(
- kInternalProperty);
- Local<Value> v8_internal = v8_object->GetHiddenValue(internal_name);
-
- if (v8_internal.IsEmpty() || v8_internal->IsUndefined()) {
- // No existing NP object so create a proxy and store it in the "internal
- // property".
- np_object = NPV8Object::Create(this, v8_object);
- v8_internal = External::New(np_object.Get());
- v8_object->SetHiddenValue(internal_name, v8_internal);
- } else {
- np_object = NPObjectPtr<NPObject>(
- static_cast<NPObject*>(
- Local<External>::Cast(v8_internal)->Value()));
- }
-
- // If it is a V8 function then wrap it in a browser function so that its
- // typeof will be reported as 'function' in the browser and it can be
- // used in cases where a real function is required (rather than an
- // object that just happens to be invocable.
- if (v8_value->IsFunction() &&
- np_object->_class == &NPV8Object::np_class_) {
- np_object = WrapV8Function(np_object);
- }
- } else {
- // This is a V8 object proxy. The NP object is referenced from an internal
- // field.
- Local<Value> internal = v8_object->GetInternalField(
- V8_NP_OBJECT_WRAPPED);
- np_object = NPObjectPtr<NPObject>(
- static_cast<NPObject*>(Local<External>::Cast(internal)->Value()));
- }
- }
- return np_object;
-}
-
-// Wrap NPV8Object proxying a V8 function in a browser function so that its
-// typeof will be reported as 'function' in the browser and it can be
-// used in cases where a real function is required (rather than an
-// object that just happens to be invocable.
-// A new wrapper function is created whenever a V8 function crosses into the
-// browser. So === won't do the right thing in the browser.
-NPObjectPtr<NPObject> NPV8Bridge::WrapV8Function(
- const NPObjectPtr<NPObject>& np_object) {
-
- NPObjectPtr<NPObject> np_result = np_object;
- NPVariant np_args[2];
- OBJECT_TO_NPVARIANT(np_object.Get(), np_args[0]);
- OBJECT_TO_NPVARIANT(np_empty_array_.Get(), np_args[1]);
- NPVariant np_variant;
- if (NPN_InvokeDefault(npp_, np_wrap_function_function_.Get(),
- np_args, 2, &np_variant)) {
- if (NPVARIANT_IS_OBJECT(np_variant)) {
- NPObjectPtr<NPObject> np_wrapper(NPVARIANT_TO_OBJECT(np_variant));
-
- // Add a reference back to the NPV8Object so we can find it again.
- if (NPN_SetProperty(npp_, np_wrapper.Get(), np_proxy_identifier_,
- &np_args[0])) {
- np_result = np_wrapper;
- }
- }
- NPN_ReleaseVariantValue(&np_variant);
- }
- return np_result;
-}
-
-Local<Value> NPV8Bridge::NPToV8Object(const NPObjectPtr<NPObject>& np_object) {
- if (np_object.IsNull())
- return Local<Value>::New(Null());
-
- // This might be a wrapper for a function. Find the actual proxy in that
- // case.
- NPObjectPtr<NPObject> np_real_object = np_object;
- {
- // NPN_GetProperty might cause an O3D NPObject to set an error if the
- // property does not exist. Prevent that. It would be better to simply
- // test whether the property exists by calling NPN_HasProperty but that
- // is not supported in Mac Safari.
- ErrorSuppressor error_suppressor(service_locator_);
- NPVariant np_variant;
- if (NPN_GetProperty(npp_, np_real_object.Get(), np_proxy_identifier_,
- &np_variant)) {
- if (NPVARIANT_IS_OBJECT(np_variant)) {
- np_real_object = NPVARIANT_TO_OBJECT(np_variant);
- }
- NPN_ReleaseVariantValue(&np_variant);
- }
- }
-
- if (np_real_object->_class == &NPV8Object::np_class_) {
- NPV8Object* np_v8_object = static_cast<NPV8Object*>(np_real_object.Get());
- return Local<Object>::New(np_v8_object->v8_object());
- } else {
- NPV8ObjectMap::const_iterator it = np_v8_object_map_.find(np_real_object);
- if (it != np_v8_object_map_.end())
- return Local<Object>::New(it->second);
-
- if (IsNPFunction(np_real_object)) {
- return NPToV8Function(np_real_object);
- } else {
- Local<Function> v8_function = v8_np_constructor_template_->GetFunction();
- Local<Object> v8_object = v8_function->NewInstance();
- if (!v8_object.IsEmpty()) {
- // NewInstance sets a JavaScript exception if it fails. Eventually
- // it'll be caught when control flow hits a TryCatch. Just make sure
- // not to dereference it before then.
- NPToV8Object(v8_object, np_real_object);
- }
- return v8_object;
- }
- }
-}
-
-void NPV8Bridge::NPToV8Object(v8::Local<Object> v8_target,
- const NPObjectPtr<NPObject>& np_object) {
- v8_target->SetInternalField(V8_NP_OBJECT_BRIDGE, External::New(this));
- v8_target->SetInternalField(V8_NP_OBJECT_WRAPPED,
- External::New(np_object.Get()));
- RegisterV8Object(v8_target, np_object);
-}
-
-bool NPV8Bridge::IsNPFunction(const NPObjectPtr<NPObject>& np_object) {
- // Before invoking the potentially expensive instanceof function (it has to
- // go through the browser) check whether the object has a call
- // property. If it doesn't have one then it isn't a JavaScript
- // function.
- if (!NPN_HasProperty(npp_, np_object.Get(), np_call_identifier_)) {
- return false;
- }
-
- // If it looks like it might be a function then call the instanceof function
- // in the browser to confirm.
- bool is_function = false;
- NPVariant np_object_variant;
- OBJECT_TO_NPVARIANT(np_object.Get(), np_object_variant);
- NPVariant np_is_function;
- if (NPN_InvokeDefault(npp_, np_is_function_function_.Get(),
- &np_object_variant, 1, &np_is_function)) {
- if (NPVARIANT_IS_BOOLEAN(np_is_function)) {
- is_function = NPVARIANT_TO_BOOLEAN(np_is_function);
- }
- NPN_ReleaseVariantValue(&np_is_function);
- }
- return is_function;
-}
-
-v8::Local<v8::Function> NPV8Bridge::NPToV8Function(
- const NPObjectPtr<NPObject>& np_function) {
- Local<FunctionTemplate> v8_function_template = FunctionTemplate::New(
- V8CallFunction, External::New(this));
-
- Local<Function> v8_function = v8_function_template->GetFunction();
-
- Local<v8::String> internal_name = v8::String::NewSymbol(
- kInternalProperty);
- v8_function->SetHiddenValue(internal_name, External::New(np_function.Get()));
-
- // Copy function name from NP function.
- NPVariant np_name;
- if (NPN_GetProperty(npp_, np_function.Get(), np_name_identifier_, &np_name)) {
- Local<Value> v8_name_value = NPToV8Variant(np_name);
- NPN_ReleaseVariantValue(&np_name);
- if (!v8_name_value.IsEmpty() && v8_name_value->IsString()) {
- Local<v8::String> v8_name = Local<v8::String>::Cast(v8_name_value);
- v8_function->SetName(v8_name);
- }
- }
-
- RegisterV8Object(v8_function, np_function);
- return v8_function;
-}
-
-void NPV8Bridge::RegisterV8Object(v8::Local<v8::Object> v8_object,
- const NPObjectPtr<NPObject>& np_object) {
- np_v8_object_map_[np_object] = Persistent<Object>::New(v8_object);
- np_v8_object_map_[np_object].MakeWeak(this, NPV8WeakReferenceCallback);
-}
-
-bool NPV8Bridge::IsNPObjectReferenced(NPObjectPtr<NPObject> np_object) {
- return np_v8_object_map_.find(np_object) != np_v8_object_map_.end();
-}
-
-void NPV8Bridge::InitializeV8ObjectTemplate(
- Local<ObjectTemplate> v8_object_template) {
- v8_object_template->SetInternalFieldCount(
- V8_NP_OBJECT_NUM_INTERNAL_FIELDS);
- v8_object_template->SetNamedPropertyHandler(V8NamedPropertyGetter,
- V8NamedPropertySetter,
- V8NamedPropertyQuery,
- V8NamedPropertyDeleter,
- V8NamedPropertyEnumerator);
- v8_object_template->SetIndexedPropertyHandler(V8IndexedPropertyGetter,
- V8IndexedPropertySetter,
- V8IndexedPropertyQuery,
- V8IndexedPropertyDeleter,
- V8IndexedPropertyEnumerator);
- v8_object_template->SetCallAsFunctionHandler(V8CallAsFunction);
-}
-
-void NPV8Bridge::NPV8WeakReferenceCallback(Persistent<Value> v8_value,
- void* parameter) {
- HandleScope handle_scope;
- NPV8Bridge* bridge = static_cast<NPV8Bridge*>(parameter);
- NPObjectPtr<NPObject> np_object = bridge->V8ToNPObject(
- Local<Value>::New(v8_value));
- bridge->np_v8_object_map_.erase(np_object);
-}
-
-void NPV8Bridge::ReportV8Exception(const TryCatch& v8_try_catch) {
- if (v8_try_catch.HasCaught()) {
- Local<Message> v8_message = v8_try_catch.Message();
- if (v8_message.IsEmpty()) {
- Local<Value> v8_exception = v8_try_catch.Exception();
- if (v8_exception.IsEmpty()) {
- error_status_->SetLastError(
- "An unknown exception ocurred while executing V8 JavaScript code");
- } else {
- v8::String::Utf8Value as_utf8(v8_exception);
- if (*as_utf8) {
- error_status_->SetLastError(*as_utf8);
- } else {
- error_status_->SetLastError(
- "An exception was thrown but its toString method failed");
- }
- }
- } else {
- String source_line(*v8::String::Utf8Value(v8_message->GetSourceLine()));
- String text(*v8::String::Utf8Value(v8_message->Get()));
- String message = text + " in " + source_line;
- error_status_->SetLastError(message);
- }
- }
-}
-
-v8::Local<v8::Array> NPV8Bridge::NPToV8IdentifierArray(
- const NPVariant& np_array, bool named) {
- Local<Array> v8_array;
- if (!NPVARIANT_IS_OBJECT(np_array))
- return v8_array;
-
- NPObject* np_array_object = NPVARIANT_TO_OBJECT(np_array);
- NPVariant np_length;
- if (NPN_GetProperty(npp_, np_array_object, np_length_identifier_,
- &np_length)) {
- Local<Value> v8_length = NPToV8Variant(np_length);
- NPN_ReleaseVariantValue(&np_length);
-
- if (v8_length.IsEmpty() || !v8_length->IsNumber())
- return v8_array;
-
- int length = v8_length->Int32Value();
- Local<Array> v8_untrimmed_array = Array::New(length);
- int num_elements = 0;
- for (int i = 0; i < length; ++i) {
- NPVariant np_element;
- if (!NPN_GetProperty(npp_, np_array_object, NPN_GetIntIdentifier(i),
- &np_element))
- return Local<Array>();
- Local<Value> v8_element = NPToV8Variant(np_element);
- NPN_ReleaseVariantValue(&np_element);
- if (v8_element->IsString() == named) {
- v8_untrimmed_array->Set(Int32::New(num_elements), v8_element);
- ++num_elements;
- }
- }
- v8_array = Array::New(num_elements);
- for (int i = 0; i < num_elements; ++i) {
- Local<Integer> i_handle = Integer::New(i);
- v8_array->Set(i_handle, v8_untrimmed_array->Get(i_handle));
- }
- }
-
- return v8_array;
-}
-
-Local<Array> NPV8Bridge::NPToV8IdentifierArray(const NPIdentifier* ids,
- uint32_t id_count, bool named) {
- int num_elements = 0;
- for (uint32_t i = 0; i < id_count; ++i) {
- if (NPN_IdentifierIsString(ids[i]) == named) {
- ++num_elements;
- }
- }
- Local<Array> v8_array = Array::New(num_elements);
- int j = 0;
- for (uint32_t i = 0; i < id_count; ++i) {
- if (NPN_IdentifierIsString(ids[i]) == named) {
- v8_array->Set(Integer::New(j), NPToV8Identifier(ids[i]));
- ++j;
- }
- }
- return v8_array;
-}
-
-Local<Array> NPV8Bridge::Enumerate(const NPObjectPtr<NPObject> np_object,
- bool named) {
- Local<Array> v8_array;
-
- // First try calling NPN_Enumerate. This will return false if the browser
- // does not support NPN_Enumerate.
- NPIdentifier* ids;
- uint32_t id_count;
- if (NPN_Enumerate(npp_, np_object.Get(), &ids, &id_count)) {
- v8_array = NPToV8IdentifierArray(ids, id_count, named);
- NPN_MemFree(ids);
- } else if (np_object->_class->structVersion >= NP_CLASS_STRUCT_VERSION_ENUM &&
- np_object->_class->enumerate != NULL &&
- np_object->_class->enumerate(np_object.Get(), &ids, &id_count)) {
- // Next see if the object has an enumerate callback and invoke it
- // directly. This is the path used when V8 enumerates the
- // properties of a native object if the browser does not support
- // NPN_Enumerate.
- v8_array = NPToV8IdentifierArray(ids, id_count, named);
- NPN_MemFree(ids);
- } else {
- // The final fallback is to invoke a JavaScript function that
- // enumerates all the properties into an array and returns it to
- // the plugin.
- NPVariant np_result;
- NPVariant np_arg;
- OBJECT_TO_NPVARIANT(np_object.Get(), np_arg);
- if (NPN_InvokeDefault(npp_, np_enumerate_function_.Get(), &np_arg, 1,
- &np_result)) {
- v8_array = NPToV8IdentifierArray(np_result, named);
- NPN_ReleaseVariantValue(&np_result);
- }
- }
-
- return v8_array;
-}
-
-v8::Handle<Value> NPV8Bridge::V8PropertyGetter(Local<Value> v8_name,
- const AccessorInfo& info) {
- Local<Value> v8_result;
-
- Local<Object> holder = info.Holder();
- NPV8Bridge* bridge = static_cast<NPV8Bridge*>(
- Local<External>::Cast(
- holder->GetInternalField(V8_NP_OBJECT_BRIDGE))->Value());
- Context::Scope scope(bridge->script_context());
-
- if (holder.IsEmpty())
- return v8_result;
-
- NPObjectPtr<NPObject> np_object = bridge->V8ToNPObject(holder);
- if (np_object.IsNull())
- return v8_result;
-
- NPIdentifier np_name = V8ToNPIdentifier(v8_name);
- if (np_name == NULL)
- return v8_result;
-
- NPVariant np_result;
- if (NPN_HasProperty(bridge->npp_, np_object.Get(), np_name) &&
- NPN_GetProperty(bridge->npp_, np_object.Get(), np_name, &np_result)) {
- v8_result = bridge->NPToV8Variant(np_result);
- NPN_ReleaseVariantValue(&np_result);
- } else if (np_object->_class->hasMethod != NULL &&
- np_object->_class->hasMethod(np_object.Get(), np_name)) {
- // It's not calling NPN_HasMethod here because of a bug in Firefox
- // (Mozilla bug ID 467945), where NPN_HasMethod forwards to the object's
- // hasProperty function instead. The workaround is to sidestep npruntime.
- v8_result = bridge->function_map_->Get(v8_name);
- if (v8_result.IsEmpty() || v8_result->IsUndefined()) {
- Local<FunctionTemplate> function_template =
- FunctionTemplate::New(V8CallNamedMethod, v8_name);
- v8_result = function_template->GetFunction();
- bridge->function_map_->Set(v8_name, v8_result);
- }
- }
-
- return v8_result;
-}
-
-v8::Handle<Value> NPV8Bridge::V8PropertySetter(
- Local<Value> v8_name,
- Local<Value> v8_value,
- const AccessorInfo& info) {
- Local<Value> v8_result;
-
- Local<Object> holder = info.Holder();
- NPV8Bridge* bridge = static_cast<NPV8Bridge*>(
- Local<External>::Cast(
- holder->GetInternalField(V8_NP_OBJECT_BRIDGE))->Value());
- Context::Scope scope(bridge->script_context());
-
- NPObjectPtr<NPObject> np_object = bridge->V8ToNPObject(holder);
- if (np_object.IsNull())
- return v8_result;
-
- NPIdentifier np_name = V8ToNPIdentifier(v8_name);
- if (np_name == NULL)
- return v8_result;
-
- NPVariant np_value = bridge->V8ToNPVariant(v8_value);
- NPN_SetProperty(bridge->npp_, np_object.Get(), np_name, &np_value);
- NPN_ReleaseVariantValue(&np_value);
-
- return v8_result;
-}
-
-v8::Handle<v8::Boolean> NPV8Bridge::V8PropertyDeleter(
- Local<Value> v8_name,
- const AccessorInfo& info) {
- Local<Object> holder = info.Holder();
- NPV8Bridge* bridge = static_cast<NPV8Bridge*>(
- Local<External>::Cast(
- holder->GetInternalField(V8_NP_OBJECT_BRIDGE))->Value());
- Context::Scope scope(bridge->script_context());
-
- NPObjectPtr<NPObject> np_object = bridge->V8ToNPObject(holder);
- if (np_object.IsNull())
- return v8::Handle<v8::Boolean>();
-
- NPIdentifier np_name = V8ToNPIdentifier(v8_name);
- if (np_name == NULL)
- return v8::Handle<v8::Boolean>();
-
- // Workaround for a bug in Chrome. Chrome does not check whether the
- // removeProperty callback is implemented before calling it, causing
- // NPN_RemoveProperty to crash if it is not. So do the check before calling
- // it.
- bool deleted = np_object->_class->removeProperty != NULL &&
- NPN_RemoveProperty(bridge->npp_, np_object.Get(), np_name);
- return v8::Boolean::New(deleted);
-}
-
-v8::Handle<Value> NPV8Bridge::V8NamedPropertyGetter(Local<v8::String> v8_name,
- const AccessorInfo& info) {
- return V8PropertyGetter(v8_name, info);
-}
-
-v8::Handle<Value> NPV8Bridge::V8NamedPropertySetter(Local<v8::String> v8_name,
- Local<Value> v8_value,
- const AccessorInfo& info) {
- return V8PropertySetter(v8_name, v8_value, info);
-}
-
-v8::Handle<v8::Integer> NPV8Bridge::V8NamedPropertyQuery(
- Local<v8::String> v8_name,
- const AccessorInfo& info) {
- Local<Object> holder = info.Holder();
- NPV8Bridge* bridge = static_cast<NPV8Bridge*>(
- Local<External>::Cast(
- holder->GetInternalField(V8_NP_OBJECT_BRIDGE))->Value());
- Context::Scope scope(bridge->script_context());
-
- NPObjectPtr<NPObject> np_object = bridge->V8ToNPObject(holder);
- if (np_object.IsNull())
- return v8::Handle<v8::Integer>();
-
- NPIdentifier np_name = V8ToNPIdentifier(v8_name);
- if (np_name == NULL)
- return v8::Handle<v8::Integer>();
-
- bool has = NPN_HasProperty(bridge->npp_, np_object.Get(), np_name) ||
- NPN_HasMethod(bridge->npp_, np_object.Get(), np_name);
- if (!has)
- return v8::Handle<v8::Integer>();
- return v8::Integer::New(0);
-}
-
-v8::Handle<v8::Boolean> NPV8Bridge::V8NamedPropertyDeleter(
- Local<v8::String> v8_name,
- const AccessorInfo& info) {
- return V8PropertyDeleter(v8_name, info);
-}
-
-v8::Handle<Array> NPV8Bridge::V8NamedPropertyEnumerator(
- const AccessorInfo& info) {
- Local<Object> holder = info.Holder();
- NPV8Bridge* bridge = static_cast<NPV8Bridge*>(
- Local<External>::Cast(
- holder->GetInternalField(V8_NP_OBJECT_BRIDGE))->Value());
- Context::Scope scope(bridge->script_context());
-
- NPObjectPtr<NPObject> np_object = bridge->V8ToNPObject(holder);
- if (np_object.IsNull())
- return v8::Handle<Array>();
-
- return bridge->Enumerate(np_object, true);
-}
-
-v8::Handle<Value> NPV8Bridge::V8IndexedPropertyGetter(
- uint32_t index,
- const AccessorInfo& info) {
- return V8PropertyGetter(Integer::New(index), info);
-}
-
-v8::Handle<Value> NPV8Bridge::V8IndexedPropertySetter(
- uint32_t index,
- Local<Value> v8_value,
- const AccessorInfo& info) {
- return V8PropertySetter(Integer::New(index), v8_value, info);
-}
-
-v8::Handle<v8::Boolean> NPV8Bridge::V8IndexedPropertyQuery(
- uint32_t index,
- const AccessorInfo& info) {
- Local<Object> holder = info.Holder();
- NPV8Bridge* bridge = static_cast<NPV8Bridge*>(
- Local<External>::Cast(
- holder->GetInternalField(V8_NP_OBJECT_BRIDGE))->Value());
- Context::Scope scope(bridge->script_context());
-
- NPObjectPtr<NPObject> np_object = bridge->V8ToNPObject(holder);
- if (np_object.IsNull())
- return v8::Handle<v8::Boolean>();
-
- Local<Value> v8_name = Integer::New(index);
- NPIdentifier np_name = V8ToNPIdentifier(v8_name);
- if (np_name == NULL)
- return v8::Handle<v8::Boolean>();
-
- bool has = NPN_HasProperty(bridge->npp_, np_object.Get(), np_name) ||
- NPN_HasMethod(bridge->npp_, np_object.Get(), np_name);
- return v8::Boolean::New(has);
-}
-
-v8::Handle<v8::Boolean> NPV8Bridge::V8IndexedPropertyDeleter(
- uint32_t index,
- const AccessorInfo& info) {
- return V8PropertyDeleter(Integer::New(index), info);
-}
-
-v8::Handle<Array> NPV8Bridge::V8IndexedPropertyEnumerator(
- const AccessorInfo& info) {
- Local<Object> holder = info.Holder();
- NPV8Bridge* bridge = static_cast<NPV8Bridge*>(
- Local<External>::Cast(
- holder->GetInternalField(V8_NP_OBJECT_BRIDGE))->Value());
- Context::Scope scope(bridge->script_context());
-
- NPObjectPtr<NPObject> np_object = bridge->V8ToNPObject(holder);
- if (np_object.IsNull())
- return v8::Handle<Array>();
-
- return bridge->Enumerate(np_object, false);
-}
-
-v8::Handle<Value> NPV8Bridge::V8CallNamedMethod(const Arguments& args) {
- Local<Value> v8_result;
-
- if (args.IsConstructCall())
- return v8_result;
-
- Local<Object> v8_holder = args.Holder();
- NPV8Bridge* bridge = static_cast<NPV8Bridge*>(
- Local<External>::Cast(
- v8_holder->GetInternalField(V8_NP_OBJECT_BRIDGE))->Value());
- Context::Scope scope(bridge->script_context());
-
- NPObjectPtr<NPObject> np_this = bridge->V8ToNPObject(v8_holder);
- if (np_this.IsNull())
- return v8_result;
-
- v8::Handle<Value> v8_name = args.Data();
- NPIdentifier np_name = V8ToNPIdentifier(v8_name);
- if (np_name == NULL)
- return v8_result;
-
- std::vector<NPVariant> np_args(args.Length());
- for (int i = 0; i != args.Length(); ++i) {
- np_args[i] = bridge->V8ToNPVariant(args[i]);
- }
-
- NPVariant np_result;
- if (NPN_Invoke(bridge->npp_,
- np_this.Get(),
- np_name,
- args.Length() == 0 ? NULL : &np_args.front(),
- args.Length(),
- &np_result)) {
- v8_result = bridge->NPToV8Variant(np_result);
- NPN_ReleaseVariantValue(&np_result);
- }
-
- for (int i = 0; i != args.Length(); ++i) {
- NPN_ReleaseVariantValue(&np_args[i]);
- }
-
- return v8_result;
-}
-
-v8::Handle<Value> NPV8Bridge::V8CallFunction(const Arguments& args) {
- Local<Value> v8_result;
-
- NPV8Bridge* bridge = static_cast<NPV8Bridge*>(
- Local<External>::Cast(args.Data())->Value());
- Context::Scope scope(bridge->script_context());
-
- Local<Function> v8_callee = args.Callee();
- Local<Object> v8_this = args.This();
-
- // Allocate an extra argument element for the "this" pointer. This is only
- // used if we end up invoking a method through function.call(this, arg0, ...,
- // argn).
- std::vector<NPVariant> np_args(args.Length() + 1);
- VOID_TO_NPVARIANT(np_args[0]);
- for (int i = 0; i != args.Length(); ++i) {
- np_args[i + 1] = bridge->V8ToNPVariant(args[i]);
- }
-
- // Need to determine whether the object was called as a standalone function,
- // a method or a constructor. The constructor case is easy: args has a flag
- // for it. If the function was called standalone then "this" will reference
- // the global object. Otherwise assume it is a method invocation.
- NPVariant np_result;
- if (args.IsConstructCall()) {
- // NPN_Construct was giving me trouble on some browsers (like Chrome). It
- // might have better support in the future. For the time being, I'm using
- // this alternative.
- NPObjectPtr<NPObject> np_construct_function =
- bridge->GetNPConstructFunction(args.Length());
- np_args[0] = bridge->V8ToNPVariant(v8_callee);
- if (NPN_InvokeDefault(bridge->npp_, np_construct_function.Get(),
- &np_args[0], args.Length() + 1, &np_result)) {
- v8_result = bridge->NPToV8Variant(np_result);
- NPN_ReleaseVariantValue(&np_result);
- }
- } else if (v8_this == bridge->script_context_->Global()) {
- // Treat standalone case specially. We use NPN_InvokeDefault rather than
- // NPN_Invoke with the "call" method because we want to have "this" refer
- // to the browser's global environment rather than the V8 global
- // environment.
- NPObjectPtr<NPObject> np_callee = bridge->V8ToNPObject(v8_callee);
- if (NPN_InvokeDefault(bridge->npp_, np_callee.Get(), 1 + &np_args[0],
- args.Length(), &np_result)) {
- v8_result = bridge->NPToV8Variant(np_result);
- NPN_ReleaseVariantValue(&np_result);
- }
- } else {
- // Invoke a function as a method by invoking its "call" call method. This
- // is not the usual way of invoking a method in runtime. The usual way would
- // to be to call NPN_Invoke on the target object (the one to be bound to
- // "this") with a method name. But we don't know the method name. We don't
- // even know if the function is assigned to one of the properties of the
- // target object. To avoid that trouble, we invoke the function's "call"
- // method with "this" as an explicit argument.
- NPObjectPtr<NPObject> np_callee = bridge->V8ToNPObject(v8_callee);
- np_args[0] = bridge->V8ToNPVariant(v8_this);
- if (NPN_Invoke(bridge->npp_, np_callee.Get(), bridge->np_call_identifier_,
- &np_args[0], args.Length() + 1, &np_result)) {
- v8_result = bridge->NPToV8Variant(np_result);
- NPN_ReleaseVariantValue(&np_result);
- }
- }
-
- for (int i = 0; i != args.Length() + 1; ++i) {
- NPN_ReleaseVariantValue(&np_args[i]);
- }
-
- return v8_result;
-}
-
-v8::Handle<Value> NPV8Bridge::V8CallAsFunction(const Arguments& args) {
- Local<Value> v8_result;
-
- Local<Object> v8_callee = args.This();
- NPV8Bridge* bridge = static_cast<NPV8Bridge*>(
- Local<External>::Cast(
- v8_callee->GetInternalField(V8_NP_OBJECT_BRIDGE))->Value());
- Context::Scope scope(bridge->script_context());
-
- std::vector<NPVariant> np_args(args.Length());
- for (int i = 0; i != args.Length(); ++i) {
- np_args[i] = bridge->V8ToNPVariant(args[i]);
- }
-
- NPVariant np_result;
- NPObjectPtr<NPObject> np_callee = bridge->V8ToNPObject(v8_callee);
- if (NPN_InvokeDefault(bridge->npp_, np_callee.Get(),
- args.Length() == 0 ? NULL : &np_args[0], args.Length(),
- &np_result)) {
- v8_result = bridge->NPToV8Variant(np_result);
- NPN_ReleaseVariantValue(&np_result);
- }
-
- for (int i = 0; i != args.Length(); ++i) {
- NPN_ReleaseVariantValue(&np_args[i]);
- }
-
- return v8_result;
-}
-
-// Evaluates and returns an NP function that will construct an object. The
-// function takes the constructor and constructor arguments as arguments.
-// I'm doing this because not all browsers seem to support calling NPN_Construct
-// on JavaScript constructor functions.
-NPObjectPtr<NPObject> NPV8Bridge::GetNPConstructFunction(int arity) {
- NPConstructFunctionMap::const_iterator it = np_construct_functions_.find(
- arity);
- if (it != np_construct_functions_.end())
- return it->second;
-
- // Build a function that looks like:
- // (function (c,p0,p1) { return new c(p0,p1); })
- std::ostringstream code;
- code << "(function(c";
- for (int i = 0; i != arity; ++i) {
- code << ",p" << i;
- }
- code << ") { return new c(";
- String separator = "";
- for (int i = 0; i != arity; ++i) {
- code << separator << String("p") << i;
- separator = ",";
- }
- code << "); })";
-
- return NPEvaluateObject(code.str().c_str());
-}
-} // namespace o3d
diff --git a/o3d/plugin/cross/np_v8_bridge.h b/o3d/plugin/cross/np_v8_bridge.h
deleted file mode 100644
index e3ce65c..0000000
--- a/o3d/plugin/cross/np_v8_bridge.h
+++ /dev/null
@@ -1,414 +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.
- */
-
-
-// Code relating to interoperation of V8 JavaScript engine with NPAPI.
-
-#ifndef O3D_PLUGIN_CROSS_NP_V8_BRIDGE_H_
-#define O3D_PLUGIN_CROSS_NP_V8_BRIDGE_H_
-
-#include <npapi.h>
-#include <npruntime.h>
-#include <map>
-
-#include "base/hash_tables.h"
-#include "core/cross/error_status.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/types.h"
-
-// The XLib header files define these preprocessor macros which v8 uses as
-// identifiers. Need to undefine them before including v8.
-#ifdef None
-#undef None
-#endif
-
-#ifdef True
-#undef True
-#endif
-
-#ifdef False
-#undef False
-#endif
-
-#ifdef Value
-#undef Value
-#endif
-
-#include "v8/include/v8.h"
-
-namespace o3d {
-
-// Smart pointer for NPObjects that automatically retains and releases the
-// reference count.
-template <typename T>
-class NPObjectPtr {
- public:
- NPObjectPtr()
- : owned(true),
- object_(NULL) {
- }
-
- template <typename U>
- explicit NPObjectPtr(U* object)
- : object_(object) {
- Retain();
- }
-
- NPObjectPtr(const NPObjectPtr& rhs)
- : object_(rhs.object_) {
- Retain();
- }
-
- template <typename U>
- explicit NPObjectPtr(const NPObjectPtr<U>& rhs)
- : object_(rhs.Get()) {
- Retain();
- }
-
- ~NPObjectPtr() {
- Release();
- }
-
- template <typename U>
- NPObjectPtr& operator=(U* rhs) {
- Release();
- object_ = rhs;
- Retain();
- return *this;
- }
-
- NPObjectPtr& operator=(const NPObjectPtr& rhs) {
- Release();
- object_ = rhs.object_;
- Retain();
- return *this;
- }
-
- template <typename U>
- NPObjectPtr& operator=(const NPObjectPtr<U>& rhs) {
- Release();
- object_ = rhs.Get();
- Retain();
- return *this;
- }
-
- bool operator<(const NPObjectPtr& rhs) const {
- return object_ < rhs.object_;
- }
-
- bool operator==(const NPObjectPtr& rhs) const {
- return object_ == rhs.object_;
- }
-
- T* operator->() const {
- return object_;
- }
-
- T* Get() const {
- return object_;
- }
-
- bool IsNull() const {
- return object_ == NULL;
- }
-
- void Clear() {
- Release();
- object_ = NULL;
- }
-
- // Does not increment the reference count. When a function returns a pointer
- // to an NPObject, the rule is that its reference count has already been
- // incremented on behalf of the caller.
- static NPObjectPtr AttachToReturned(T* object) {
- NPObjectPtr result(object);
- result.Release();
- return result;
- }
-
- // Calling this prevents the NPObject's reference count from being decremented
- // by this smart pointer when it is destroyed or a new reference is assigned.
- T* Disown() const {
- owned = false;
- return object_;
- }
-
- private:
- void Retain() {
- owned = true;
- if (object_ != NULL) {
- NPN_RetainObject(object_);
- }
- }
-
- void Release() {
- if (owned && object_ != NULL) {
- NPN_ReleaseObject(object_);
- }
- }
-
- mutable bool owned;
- T* object_;
-};
-
-} // namespace o3d
-
-// Hashes an NPObject so it can be used in a hash_map.
-#if defined(COMPILER_GCC)
-namespace __gnu_cxx {
-
-template<class T>
-struct hash<o3d::NPObjectPtr<T> > {
- std::size_t operator()(const o3d::NPObjectPtr<T>& ptr) const {
- return hash<size_t>()(reinterpret_cast<size_t>(ptr.Get()));
- }
-};
-
-} // namespace __gnu_cxx
-#elif defined(COMPILER_MSVC)
-namespace stdext {
-
-template<class T>
-inline size_t hash_value(const o3d::NPObjectPtr<T>& ptr) {
- return hash_value(reinterpret_cast<size_t>(ptr.Get()));
-}
-
-} // namespace stdext
-#endif // COMPILER
-
-namespace o3d {
-
-// A V8 handle that automatically disposes itself when it is destroyed. There
-// must be only one of these for each persistent handle, otherwise they might
-// be disposed more than once.
-template <typename T>
-class AutoV8Persistent : public v8::Persistent<T> {
- public:
- AutoV8Persistent() {}
-
- template <typename U>
- explicit AutoV8Persistent(const v8::Persistent<U>& rhs)
- : v8::Persistent<T>(rhs) {
- }
-
- template <typename U>
- AutoV8Persistent& operator=(const v8::Persistent<U>& rhs) {
- *(v8::Persistent<T>*)this = rhs;
- return *this;
- }
-
- ~AutoV8Persistent() {
- this->Dispose();
- this->Clear();
- }
-};
-
-// The bridge provides a way of evaluating JavaScript in the V8 engine and
-// marshalling between V8 and NPAPI representations of objects and values.
-class NPV8Bridge {
- friend class NPV8Object;
- public:
- NPV8Bridge(ServiceLocator* service_locator, NPP npp);
- ~NPV8Bridge();
-
- NPP npp() { return npp_; }
-
- // Initializes the V8 environment. The global NPObject is wrapped with a V8
- // proxy and used as the global environment's prototype. This means that if
- // a variable cannot be resolved in the V8 environment then it will attempt
- // to resolve it in the NPObject. This allows V8 to read global variables in
- // the browser environment. Note that assignments will never go to the
- // global environment's prototype, changes will only be visible locally.
- void Initialize(const NPObjectPtr<NPObject>& global_np_object);
-
- // This function tells the bridge to forget and release all of the NPObjects
- // that it knows about.
- void ReleaseNPObjects();
-
- v8::Handle<v8::Context> script_context();
-
- // Evaluates some JavaScript code in V8. It currently expects only one
- // argument in the argument array, which must be a string containing the
- // JavaScript code to evaluate. It returns the result of the evaluation
- // as an NPAPI variant, which must be freed using NPN_ReleaseVariantValue.
- bool Evaluate(const NPVariant* np_args, int numArgs, NPVariant* np_result);
-
- // Adds an object property to the V8 global environment.
- void SetGlobalProperty(const String& name,
- NPObjectPtr<NPObject>& np_object);
-
- private:
-
- // Converts a V8 value into an NPVariant. The NPVariant must be freed with
- // NPN_ReleaseVariantValue. Caller must enter the script context.
- NPVariant V8ToNPVariant(v8::Local<v8::Value> value);
-
- // Converts an NPVariant to a V8 value. Caller must enter the script context.
- v8::Local<v8::Value> NPToV8Variant(const NPVariant& np_variant);
-
- // Converts a V8 object to an NPObject, either by wrapping the V8 object
- // with an NPV8Object proxy or if the V8 object is a proxy, returning the
- // NPObject it wraps. Caller must enter the script context.
- NPObjectPtr<NPObject> V8ToNPObject(v8::Local<v8::Value> v8_object);
-
- // Converts an NPObject to a V8 object, either by wrapping the NPObject with
- // a V8 proxy or if the NPObject is a proxy, returning the V8 object it wraps.
- // Caller must enter the script context.
- v8::Local<v8::Value> NPToV8Object(const NPObjectPtr<NPObject>& np_object);
-
- // Determines whether the given NPObject is currently referenced by V8 through
- // a proxy.
- bool IsNPObjectReferenced(NPObjectPtr<NPObject> np_object);
-
- NPObjectPtr<NPObject> NPEvaluateObject(const char* script);
-
- void NPToV8Object(v8::Local<v8::Object> v8_target,
- const NPObjectPtr<NPObject>& np_object);
-
- bool IsNPFunction(const NPObjectPtr<NPObject>& np_object);
-
- v8::Local<v8::Function> NPToV8Function(
- const NPObjectPtr<NPObject>& np_function);
-
- void ReleaseUnreferencedWrapperFunctions();
-
- NPObjectPtr<NPObject> WrapV8Function(const NPObjectPtr<NPObject>& np_object);
-
- void RegisterV8Object(v8::Local<v8::Object> v8_object,
- const NPObjectPtr<NPObject>& np_object);
-
- void InitializeV8ObjectTemplate(
- v8::Local<v8::ObjectTemplate> v8_object_template);
-
- static void NPV8WeakReferenceCallback(v8::Persistent<v8::Value> value,
- void* parameter);
-
- void ReportV8Exception(const v8::TryCatch& tryCatch);
-
- v8::Local<v8::Array> NPToV8IdentifierArray(
- const NPVariant& np_array, bool named);
-
- v8::Local<v8::Array> NPToV8IdentifierArray(
- const NPIdentifier* ids, uint32_t id_count, bool named);
-
- // Implements enumeration of NPObject properties using NPN_Evaluate where
- // supported by the browser or otherwise falling back on emulation. Returns
- // either named or indexed properties depending on named parameter.
- v8::Local<v8::Array> Enumerate(const NPObjectPtr<NPObject> np_object,
- bool named);
-
- static v8::Handle<v8::Value> V8PropertyGetter(v8::Local<v8::Value> v8_name,
- const v8::AccessorInfo& info);
-
- static v8::Handle<v8::Value> V8PropertySetter(v8::Local<v8::Value> v8_name,
- v8::Local<v8::Value> v8_value,
- const v8::AccessorInfo& info);
-
- static v8::Handle<v8::Boolean> V8PropertyDeleter(
- v8::Local<v8::Value> v8_name,
- const v8::AccessorInfo& info);
-
- static v8::Handle<v8::Value> V8NamedPropertyGetter(
- v8::Local<v8::String> v8_name,
- const v8::AccessorInfo& info);
-
- static v8::Handle<v8::Value> V8NamedPropertySetter(
- v8::Local<v8::String> v8_name,
- v8::Local<v8::Value> v8_value,
- const v8::AccessorInfo& info);
-
- static v8::Handle<v8::Integer> V8NamedPropertyQuery(
- v8::Local<v8::String> v8_name,
- const v8::AccessorInfo& info);
-
- static v8::Handle<v8::Boolean> V8NamedPropertyDeleter(
- v8::Local<v8::String> v8_name,
- const v8::AccessorInfo& info);
-
- static v8::Handle<v8::Array> V8NamedPropertyEnumerator(
- const v8::AccessorInfo& info);
-
- static v8::Handle<v8::Value> V8IndexedPropertyGetter(
- uint32_t index,
- const v8::AccessorInfo& info);
-
- static v8::Handle<v8::Value> V8IndexedPropertySetter(
- uint32_t index,
- v8::Local<v8::Value> v8_value,
- const v8::AccessorInfo& info);
-
- static v8::Handle<v8::Boolean> V8IndexedPropertyQuery(
- uint32_t index,
- const v8::AccessorInfo& info);
-
- static v8::Handle<v8::Boolean> V8IndexedPropertyDeleter(
- uint32_t index,
- const v8::AccessorInfo& info);
-
- static v8::Handle<v8::Array> V8IndexedPropertyEnumerator(
- const v8::AccessorInfo& info);
-
- static v8::Handle<v8::Value> V8CallNamedMethod(const v8::Arguments& args);
-
- static v8::Handle<v8::Value> V8CallFunction(const v8::Arguments& args);
-
- static v8::Handle<v8::Value> V8CallAsFunction(const v8::Arguments& args);
-
- NPObjectPtr<NPObject> GetNPConstructFunction(int arity);
-
- typedef ::base::hash_map<NPObjectPtr<NPObject>,
- AutoV8Persistent<v8::Object> > NPV8ObjectMap;
-
- typedef std::map<int, NPObjectPtr<NPObject> > NPConstructFunctionMap;
-
- ServiceLocator* service_locator_;
- ServiceDependency<IErrorStatus> error_status_;
- NPP npp_;
- NPObjectPtr<NPObject> global_np_object_;
- AutoV8Persistent<v8::Context> script_context_;
- AutoV8Persistent<v8::FunctionTemplate> v8_np_constructor_template_;
- AutoV8Persistent<v8::Object> function_map_;
- AutoV8Persistent<v8::Object> global_prototype_;
- NPV8ObjectMap np_v8_object_map_;
- NPObjectPtr<NPObject> np_enumerate_function_;
- NPObjectPtr<NPObject> np_is_function_function_;
- NPObjectPtr<NPObject> np_wrap_function_function_;
- NPConstructFunctionMap np_construct_functions_;
- NPIdentifier np_name_identifier_;
- NPIdentifier np_call_identifier_;
- NPIdentifier np_length_identifier_;
- NPIdentifier np_proxy_identifier_;
- NPObjectPtr<NPObject> np_empty_array_;
- DISALLOW_COPY_AND_ASSIGN(NPV8Bridge);
-};
-} // namespace o3d
-
-#endif // O3D_PLUGIN_CROSS_NP_V8_BRIDGE_H_
diff --git a/o3d/plugin/cross/o3d_glue.cc b/o3d/plugin/cross/o3d_glue.cc
deleted file mode 100644
index b5d2d58..0000000
--- a/o3d/plugin/cross/o3d_glue.cc
+++ /dev/null
@@ -1,1243 +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 <build/build_config.h>
-#ifdef OS_WIN
-#include <windows.h>
-#include <shellapi.h>
-#endif // OS_WIN
-
-#include <string>
-#include <algorithm>
-#include "core/cross/image_utils.h"
-#include "core/cross/renderer.h"
-#include "core/cross/texture.h"
-#include "core/cross/client_info.h"
-#include "plugin/cross/o3d_glue.h"
-#include "plugin/cross/config.h"
-#include "plugin/cross/stream_manager.h"
-#include "third_party/nixysa/static_glue/npapi/npn_api.h"
-#include "client_glue.h"
-#include "globals_glue.h"
-
-#ifdef OS_MACOSX
-#include "plugin_mac.h"
-#endif
-
-#ifdef OS_LINUX
-#include <X11/cursorfont.h>
-#endif
-
-namespace glue {
-namespace _o3d {
-
-using o3d::Bitmap;
-using o3d::Texture;
-using o3d::Texture2D;
-
-void RegisterType(NPP npp, const ObjectBase::Class *clientclass,
- NPClass *npclass) {
- PluginObject *plugin_object = static_cast<PluginObject *>(npp->pdata);
- plugin_object->RegisterType(clientclass, npclass);
-}
-
-bool CheckObject(NPP npp, NPObject *npobject,
- const ObjectBase::Class *clientclass) {
- PluginObject *plugin_object = static_cast<PluginObject *>(npp->pdata);
- return plugin_object->CheckObject(npobject, clientclass);
-}
-
-NPAPIObject *GetNPObject(NPP npp, ObjectBase *object) {
- PluginObject *plugin_object = static_cast<PluginObject *>(npp->pdata);
- return plugin_object->GetNPObject(object);
-}
-
-NPObject *Allocate(NPP npp, NPClass *npclass) {
- return new NPAPIObject(npp);
-}
-void Deallocate(NPObject *object) {
- NPAPIObject *npobject = static_cast<NPAPIObject *>(object);
- if (npobject->mapped()) {
- NPP npp = npobject->npp();
- PluginObject *plugin_object = static_cast<PluginObject *>(npp->pdata);
- plugin_object->UnmapObject(npobject);
- }
- delete npobject;
-}
-
-ServiceLocator *GetServiceLocator(NPP npp) {
- PluginObject *plugin_object = static_cast<PluginObject *>(npp->pdata);
- return plugin_object->service_locator();
-}
-
-Client *GetClient(NPP npp) {
- PluginObject *plugin_object = static_cast<PluginObject *>(npp->pdata);
- return plugin_object->client();
-}
-
-PluginObject::PluginObject(NPP npp)
- : npp_(npp),
- evaluation_counter_(&service_locator_),
- class_manager_(&service_locator_),
- client_info_manager_(&service_locator_),
- object_manager_(&service_locator_),
- profiler_(&service_locator_),
- main_thread_task_poster_(&service_locator_, npp),
- fullscreen_(false),
- renderer_(NULL),
- features_(NULL),
- fullscreen_region_valid_(false),
- renderer_init_status_(Renderer::UNINITIALIZED),
- pending_ticks_(0),
-#ifdef OS_WIN
- hWnd_(NULL),
- plugin_hWnd_(NULL),
- content_hWnd_(NULL),
- got_dblclick_(false),
- painted_once_(false),
-#endif
-#ifdef OS_MACOSX
- renderer_is_software_(false),
- scroll_is_in_progress_(false),
- drawing_model_(NPDrawingModelQuickDraw),
- event_model_(NPEventModelCarbon),
- mac_window_(0),
- mac_window_selected_tab_(0),
- mac_cocoa_window_(0),
- mac_surface_hidden_(0),
- mac_cg_context_ref_(0),
- mac_agl_context_(0),
- mac_cgl_context_(0),
- mac_cgl_pbuffer_(0),
- last_mac_event_time_(0),
- gl_layer_(NULL),
- mac_fullscreen_window_(NULL),
- mac_fullscreen_nsopenglcontext_(NULL),
- mac_fullscreen_nsopenglpixelformat_(NULL),
- was_offscreen_(false),
-#endif // OS_MACOSX
-#ifdef OS_LINUX
- display_(NULL),
- window_(0),
- fullscreen_window_(0),
- xt_widget_(NULL),
- xt_app_context_(NULL),
- xt_interval_(0),
- last_click_time_(0),
- drawable_(0),
- gdk_display_(NULL),
- gtk_container_(NULL),
- gtk_fullscreen_container_(NULL),
- gtk_event_source_(NULL),
- event_handler_id_(0),
- timeout_id_(0),
- fullscreen_pending_(false),
- draw_(true),
- in_plugin_(false),
-#endif
-#if defined(CB_SERVICE_REMOTE)
- gpu_plugin_object_(NULL),
-#endif
- np_v8_bridge_(&service_locator_, npp),
- stream_manager_(new StreamManager(npp)),
- cursor_type_(o3d::Cursor::DEFAULT),
- prev_width_(0),
- prev_height_(0),
- offscreen_rendering_enabled_(false) {
-#if defined(OS_WIN) || defined(OS_LINUX)
- memset(cursors_, 0, sizeof(cursors_));
-#endif
-
-#ifdef OS_MACOSX
- memset(last_buffer_rect_, 0, sizeof(last_buffer_rect_));
-#endif
-
-#ifdef OS_LINUX
- memset(got_double_click_, 0, sizeof(got_double_click_));
-#endif
-
- // create an O3D object
- client_ = new Client(&service_locator_);
-
- globals_npobject_ = glue::CreateStaticNPObject(npp);
- client_npobject_ =
- glue::namespace_o3d::class_Client::GetNPObject(npp, client_);
- user_agent_ = o3d::GetUserAgent(npp);
-}
-
-PluginObject::~PluginObject() {
-}
-
-void PluginObject::Init(int argc, char* argn[], char* argv[]) {
- DCHECK(argc == 0 || (argn != NULL && argv != NULL));
- features_ = new Features(&service_locator_);
-
- std::string o3d_name("o3d_features");
-
- for (int ii = 0; ii < argc; ++ii) {
- DCHECK(argn[ii]);
- const char* name = argn[ii];
- if (o3d_name.compare(name) == 0) {
- DCHECK(argv[ii]);
- features_->Init(argv[ii]);
- break;
- }
- }
-
- NPObject* np_window;
- NPN_GetValue(npp_, NPNVWindowNPObject, &np_window);
- o3d::NPObjectPtr<NPObject> np_window_ptr =
- o3d::NPObjectPtr<NPObject>::AttachToReturned(np_window);
- np_v8_bridge_.Initialize(np_window_ptr);
-
- o3d::NPObjectPtr<NPObject> np_plugin_ptr(this);
- np_v8_bridge_.SetGlobalProperty(o3d::String("plugin"),
- np_plugin_ptr);
-}
-
-void PluginObject::TearDown() {
- DisableOffscreenRendering();
-#ifdef OS_WIN
- ClearPluginProperty(hWnd_);
-#elif defined(OS_MACOSX)
- o3d::ReleaseSafariBrowserWindow(mac_cocoa_window_);
- CleanupFullscreenOpenGLContext();
-#elif defined(OS_LINUX)
- SetDisplay(NULL);
-#endif // OS_WIN
- UnmapAll();
-
- // Delete the StreamManager to cleanup any streams that are in midflight.
- // This needs to happen here, before the client is deleted as the streams
- // could be holding references to FileRequest objects.
- stream_manager_.reset(NULL);
-
- delete client_;
- client_ = NULL;
-
- // Release the graphics context before deletion.
- DeleteRenderer();
-
- delete features_;
- features_ = NULL;
-
- // There is a reference cycle between the V8 bridge and the plugin.
- // Explicitly remove all V8 references during tear-down, so that the cycle is
- // broken, and the reference counting system will successfully delete the
- // plugin.
- np_v8_bridge_.ReleaseNPObjects();
-}
-
-void PluginObject::CreateRenderer(const o3d::DisplayWindow& display_window) {
- bool software_renderer = false;
- // In case CreateRenderer is called more than once, reset to the
- // uninitialized state..
- DeleteRenderer();
- renderer_init_status_ = o3d::Renderer::UNINITIALIZED;
-
- if (features_->render_mode() != Renderer::RENDER_MODE_2D) {
- if (!o3d::CheckConfig(npp_)) {
- renderer_init_status_ = o3d::Renderer::GPU_NOT_UP_TO_SPEC;
- } else {
- renderer_ = o3d::Renderer::CreateDefaultRenderer(&service_locator_);
- DCHECK(renderer_);
-
- // Attempt to initialize renderer.
- renderer_init_status_ = renderer_->Init(display_window, false);
- if (renderer_init_status_ != o3d::Renderer::SUCCESS) {
- DeleteRenderer();
- } else {
- ClientInfoManager* client_info_manager =
- service_locator()->GetService<ClientInfoManager>();
- software_renderer =
- client_info_manager->client_info().software_renderer();
- }
- }
- }
- if (software_renderer &&
- (features_->render_mode() == Renderer::RENDER_MODE_AUTO)) {
- // If the client is OK with 2d mode, we prefer to use cairo instead of a
- // software renderer. We don't need the 3D renderer we just created.
- DeleteRenderer();
- renderer_init_status_ = o3d::Renderer::GPU_NOT_UP_TO_SPEC;
- DLOG(INFO) << "Software renderer detected. Falling back to o2d.";
- }
- if ((renderer_init_status_ != o3d::Renderer::SUCCESS) &&
- (features_->render_mode() != Renderer::RENDER_MODE_3D)) {
- // Attempt to fall back to o2d renderer
- renderer_ = o3d::Renderer::Create2DRenderer(&service_locator_);
- if (renderer_) {
- renderer_init_status_ = renderer_->Init(display_window, false);
- if (renderer_init_status_ != o3d::Renderer::SUCCESS) {
- DeleteRenderer();
- } else {
- ClientInfoManager* client_info_manager =
- service_locator()->GetService<ClientInfoManager>();
- client_info_manager->SetRender2d(true);
- }
- }
- }
-}
-
-void PluginObject::DeleteRenderer() {
- if (renderer_) {
- delete renderer_;
- renderer_ = NULL;
- }
-}
-
-
-#ifdef OS_MACOSX
-
-// These following 3 methods are needed for a Safari workaround - basically it
-// does not notify us when our tab is hidden by tab switching, and just stops
-// sending us events. The workaround is to keep track of when the browser last
-// sent us an event, and what the selected tab was at that time. If we find that
-// we are no longer getting events and the selected tab value has changed,
-// DetectTabHiding() starts returning true when the timer calls it and code
-// elsewhere can take action. SafariBrowserWindowForWindowRef() and
-// SelectedTabForSafariBrowserWindow() are both written in such a way that
-// non-Safari browsers should yield NULL, so DetectTabHiding would always
-// return false and the workaround would not be triggered.
-
-
-// Function gets notified every time we receive a Mac event.
-// It records the time of the event and tries to read the selected tab value
-// from Safari (on other browsers this tab value should always be NULL).
-// Written so that last_mac_event_time_ is always valid or NULL.
-void PluginObject::MacEventReceived(bool updateTab) {
- CFDateRef now = CFDateCreate(NULL, CFAbsoluteTimeGetCurrent());
- CFDateRef previousTime = last_mac_event_time_;
- last_mac_event_time_ = now;
- if (previousTime != NULL) {
- CFRelease(previousTime);
- }
- mac_cocoa_window_ = o3d::SafariBrowserWindowForWindowRef(mac_window_);
- if (!mac_window_selected_tab_ || updateTab) {
- mac_window_selected_tab_ =
- o3d::SelectedTabForSafariBrowserWindow(mac_cocoa_window_);
- }
-}
-
-// Returns the time elapsed since the MacEventReceived function was last called.
-CFTimeInterval PluginObject::TimeSinceLastMacEvent() {
- CFTimeInterval elapsed = 0.0;
- if (last_mac_event_time_ != NULL) {
- CFDateRef now = CFDateCreate(NULL, CFAbsoluteTimeGetCurrent());
- elapsed = CFDateGetTimeIntervalSinceDate(now, last_mac_event_time_);
- CFRelease(now);
- }
- return elapsed;
-}
-
-// Detects if Safari has hidden our tab.
-// The heuristic is that we have not received any Mac events for a certain time
-// and also the value for selected tab is different from the value it had the
-// last time we did get a Mac event.
-bool PluginObject::DetectTabHiding() {
- const CFTimeInterval kMacTimeOut = 0.2; // a fifth of a second
- if (TimeSinceLastMacEvent() < kMacTimeOut)
- return false;
-
- if (!mac_cocoa_window_) {
- mac_cocoa_window_ = o3d::SafariBrowserWindowForWindowRef(mac_window_);
- }
-
- return o3d::SelectedTabForSafariBrowserWindow(mac_cocoa_window_) !=
- mac_window_selected_tab_;
-}
-
-
-// Pick a constant way out of Apple's 0-22 range for our "no theme cursor"
-// constant.
-const ThemeCursor kNoThemeCursorForThat = 1000;
-
-// Map o3d cursors to Mac theme cursors if possible, otherwise return
-// kNoThemeCursorForThat.
-ThemeCursor O3DToMacThemeCursor(o3d::Cursor::CursorType cursor_type) {
- switch (cursor_type) {
- case o3d::Cursor::DEFAULT:
- return kThemeArrowCursor;
- case o3d::Cursor::NONE: // There is no standard blank cursor.
- return kNoThemeCursorForThat;
- case o3d::Cursor::CROSSHAIR:
- return kThemeCrossCursor;
- case o3d::Cursor::POINTER:
- return kThemePointingHandCursor;
- case o3d::Cursor::E_RESIZE:
- return kThemeResizeRightCursor;
- case o3d::Cursor::NE_RESIZE: // No diagonal resize directions on Mac.
- return kNoThemeCursorForThat;
- case o3d::Cursor::NW_RESIZE: // No diagonal resize directions on Mac.
- return kNoThemeCursorForThat;
- case o3d::Cursor::N_RESIZE:
- return kThemeResizeUpCursor;
- case o3d::Cursor::SE_RESIZE: // No diagonal resize directions on Mac.
- return kNoThemeCursorForThat;
- case o3d::Cursor::SW_RESIZE: // No diagonal resize directions on Mac.
- return kNoThemeCursorForThat;
- case o3d::Cursor::S_RESIZE:
- return kThemeResizeDownCursor;
- case o3d::Cursor::W_RESIZE:
- return kThemeResizeLeftCursor;
- case o3d::Cursor::MOVE:
- return kThemeOpenHandCursor;
- case o3d::Cursor::TEXT:
- return kThemeIBeamCursor;
- case o3d::Cursor::WAIT:
- return kThemeWatchCursor;
- case o3d::Cursor::PROGRESS:
- return kThemeSpinningCursor;
- case o3d::Cursor::HELP: // No standard Help cursor.
- return kNoThemeCursorForThat;
- }
-
- return kNoThemeCursorForThat;
-}
-
-
-// Set cursor to the one specified in cursor_type_.
-// TODO add support for cursors that don't have equivalent Mac
-// theme cursors.
-void PluginObject::PlatformSpecificSetCursor() {
- if (cursor_type_ == o3d::Cursor::NONE) {
- // hide cursor if visible
- if (CGCursorIsVisible()) {
- CGDisplayHideCursor(kCGDirectMainDisplay);
- }
- } else {
- ThemeCursor the_id = O3DToMacThemeCursor(cursor_type_);
-
- if (the_id != kNoThemeCursorForThat) {
- SetThemeCursor(the_id);
- } else {
- // could add code here to set other cursors by other means
- SetThemeCursor(kThemeArrowCursor);
- }
- // show cursor if hidden
- if (!CGCursorIsVisible())
- CGDisplayShowCursor(kCGDirectMainDisplay);
- }
-}
-
-bool PluginObject::SetRendererIsSoftware(bool state) {
- renderer_is_software_ = state;
- ClientInfoManager* client_info_manager =
- service_locator()->GetService<ClientInfoManager>();
- client_info_manager->SetSoftwareRenderer(state);
-}
-
-#endif // OS_MACOSX
-
-void PluginObject::RegisterType(const ObjectBase::Class *clientclass,
- NPClass *npclass) {
- client_to_np_class_map_[clientclass] = npclass;
- np_to_client_class_map_[npclass] = clientclass;
-}
-
-bool PluginObject::CheckObject(NPObject *npobject,
- const ObjectBase::Class *clientclass) const {
- if (!npobject) return true;
- NPClass *npclass = npobject->_class;
- NPToClientClassMap::const_iterator it = np_to_client_class_map_.find(npclass);
- if (it == np_to_client_class_map_.end()) return false;
- if (static_cast<NPAPIObject *>(npobject)->npp()->pdata != this) {
- // The object was created by another plug-in instance. Don't allow direct
- // references to these objects, that would cause havok.
- return false;
- }
- return ObjectBase::ClassIsA(it->second, clientclass);
-}
-
-NPAPIObject *PluginObject::GetNPObject(ObjectBase *object) {
- if (!object) return NULL;
- NPAPIObject *npobject = object_map_[object->id()];
- if (!npobject) {
- NPClass *npclass = GetNPClass(object->GetClass());
- GLUE_PROFILE_START(npp_, "createobject");
- npobject = static_cast<NPAPIObject *>(NPN_CreateObject(npp_, npclass));
- GLUE_PROFILE_STOP(npp_, "createobject");
- npobject->Initialize(object);
- object_map_[object->id()] = npobject;
- npobject->set_mapped(true);
- } else {
- GLUE_PROFILE_START(npp_, "retainobject");
- NPN_RetainObject(npobject);
- GLUE_PROFILE_STOP(npp_, "retainobject");
- }
- return npobject;
-}
-
-void PluginObject::UnmapObject(NPAPIObject *npobject) {
- npobject->set_mapped(false);
- object_map_.erase(npobject->id());
-}
-
-void PluginObject::UnmapAll() {
- for (ClientObjectMap::iterator it = object_map_.begin();
- it != object_map_.end(); ++it) {
- it->second->set_mapped(false);
- }
- object_map_.clear();
-}
-
-NPClass *PluginObject::GetNPClass(const ObjectBase::Class *clientclass) {
- const ObjectBase::Class *cursor = clientclass;
- while (cursor) {
- ClientToNPClassMap::const_iterator it =
- client_to_np_class_map_.find(cursor);
- if (it != client_to_np_class_map_.end()) {
- NPClass *npclass = it->second;
- if (cursor != clientclass) client_to_np_class_map_[clientclass] = npclass;
- return npclass;
- }
- cursor = cursor->parent();
- }
- return NULL;
-}
-// Static function to handle log asserts in the FATAL ERROR case
-void PluginObject::LogAssertHandlerFunction(const std::string& str) {
- DLOG(ERROR) << "FATAL LOG ERROR: " << str;
-}
-
-#if defined(CB_SERVICE_REMOTE)
-void PluginObject::SetGPUPluginObject(NPObject* gpu_plugin_object) {
- if (gpu_plugin_object) {
- NPN_RetainObject(gpu_plugin_object);
- }
-
- if (gpu_plugin_object_) {
- NPN_ReleaseObject(gpu_plugin_object_);
- }
-
- gpu_plugin_object_ = gpu_plugin_object;
-}
-#endif
-
-enum {
- kPropClient,
- kPropGpuConfig,
- kNumPropertyIds
-};
-
-static NPIdentifier property_ids[kNumPropertyIds];
-static const NPUTF8 *property_names[kNumPropertyIds] = {
- "client",
- "gpuConfig",
-};
-
-enum {
- kMethodEval,
-
-#if defined(CB_SERVICE_REMOTE)
- kMethodSetGPUPluginObject,
- kMethodGetGPUPluginObject,
-#endif
-
- kNumMethodIds,
-};
-
-static NPIdentifier method_ids[kNumMethodIds];
-static const NPUTF8 *method_names[kNumMethodIds] = {
- "eval",
-
-#if defined(CB_SERVICE_REMOTE)
- "setGPUPluginObject",
- "getGPUPluginObject",
-#endif
-};
-
-static NPObject *PluginAllocate(NPP npp, NPClass *npclass) {
- return new PluginObject(npp);
-}
-
-static void PluginDeallocate(NPObject *object) {
- delete static_cast<PluginObject *>(object);
-}
-
-static bool PluginHasMethod(NPObject *header, NPIdentifier name) {
- DebugScopedId id(name);
- PluginObject *plugin_object = static_cast<PluginObject *>(header);
- for (int i = 0; i < kNumMethodIds; ++i) {
- if (name == method_ids[i]) {
- return true;
- }
- }
-
- NPObject *globals = plugin_object->globals_npobject();
- return globals->_class->hasMethod(globals, name);
-}
-
-static bool PluginInvoke(NPObject *header, NPIdentifier name,
- const NPVariant *args, uint32_t arg_count,
- NPVariant *np_result) {
- DebugScopedId id(name);
- PluginObject *plugin_object = static_cast<PluginObject *>(header);
- if (name == method_ids[kMethodEval]) {
- return plugin_object->np_v8_bridge()->Evaluate(args, arg_count, np_result);
- }
-#if defined(CB_SERVICE_REMOTE)
- else if (name == method_ids[kMethodGetGPUPluginObject]) {
- if (arg_count != 0)
- return false;
- ValueToNPVariant(plugin_object->GetGPUPluginObject(), np_result);
- return true;
- } else if (name == method_ids[kMethodSetGPUPluginObject]) {
- if (arg_count != 1)
- return false;
- VOID_TO_NPVARIANT(*np_result);
- NPObjectPointer<NPObject> gpu_plugin_object;
- if (NPVariantToValue(&gpu_plugin_object, args[0])) {
- plugin_object->SetGPUPluginObject(gpu_plugin_object.Get());
- return true;
- } else {
- return false;
- }
- } // NOLINT
-#endif // CB_SERVICE_REMOTE
- else { // NOLINT
- NPObject *globals = plugin_object->globals_npobject();
- return globals->_class->invoke(globals, name, args, arg_count, np_result);
- }
-}
-
-static bool PluginInvokeDefault(NPObject *header, const NPVariant *args,
- uint32_t arg_count, NPVariant *result) {
- PluginObject *plugin_object = static_cast<PluginObject *>(header);
- NPP npp = plugin_object->npp();
- NPObject *globals = plugin_object->globals_npobject();
- return globals->_class->invokeDefault(globals, args, arg_count, result);
-}
-
-static bool PluginHasProperty(NPObject *header, NPIdentifier name) {
- DebugScopedId id(name);
- PluginObject *plugin_object = static_cast<PluginObject *>(header);
- NPP npp = plugin_object->npp();
- for (unsigned int i = 0; i < kNumPropertyIds; ++i) {
- if (name == property_ids[i]) return true;
- }
- NPObject *globals = plugin_object->globals_npobject();
- return globals->_class->hasProperty(globals, name);
-}
-
-static bool PluginGetProperty(NPObject *header, NPIdentifier name,
- NPVariant *variant) {
- DebugScopedId id(name);
- PluginObject *plugin_object = static_cast<PluginObject *>(header);
- NPP npp = plugin_object->npp();
- if (name == property_ids[kPropGpuConfig]) {
- // Gets the GPU config (VendorID, DeviceID, name) as a string.
- // NOTE: this should probably be removed before we ship.
- o3d::GPUDevice device;
- bool result = o3d::GetGPUDevice(npp, &device);
- if (!result) return false;
- std::string return_value = std::string("VendorID = 0x");
- char id_text[9];
- base::snprintf(id_text, sizeof(id_text), "%04x", device.vendor_id);
- return_value += id_text;
- return_value += ", DeviceID = 0x";
- base::snprintf(id_text, sizeof(id_text), "%04x", device.device_id);
- return_value += id_text;
- return_value += ", DeviceName = '";
- return_value += device.name + "'";
- return_value += ", Driver = '";
- return_value += device.driver + "'";
- return_value += ", Description = '";
- return_value += device.description + "'";
- return_value += ", GUID = 0x";
- base::snprintf(id_text, sizeof(id_text), "%08x", device.guid);
- return_value += id_text;
- GLUE_PROFILE_START(npp, "StringToNPVariant");
- bool temp = StringToNPVariant(return_value, variant);
- GLUE_PROFILE_STOP(npp, "StringToNPVariant");
- return temp;
- }
-
- if (name == property_ids[kPropClient]) {
- NPObject *npobject = plugin_object->client_npobject();
- GLUE_PROFILE_START(npp, "retainobject");
- NPN_RetainObject(npobject);
- GLUE_PROFILE_STOP(npp, "retainobject");
- OBJECT_TO_NPVARIANT(npobject, *variant);
- return true;
- }
- NPObject *globals = plugin_object->globals_npobject();
- return globals->_class->getProperty(globals, name, variant);
-}
-
-static bool PluginSetProperty(NPObject *header, NPIdentifier name,
- const NPVariant *variant) {
- DebugScopedId id(name);
- PluginObject *plugin_object = static_cast<PluginObject *>(header);
- NPP npp = plugin_object->npp();
- if (name == property_ids[kPropClient]) {
- return false;
- }
- NPObject *globals = plugin_object->globals_npobject();
- return globals->_class->setProperty(globals, name, variant);
-}
-
-static bool PluginEnumerate(NPObject *header, NPIdentifier **value,
- uint32_t *count) {
- *count = kNumPropertyIds + kNumMethodIds + glue::GetStaticPropertyCount();
- PluginObject *plugin_object = static_cast<PluginObject *>(header);
- NPP npp = plugin_object->npp();
- GLUE_PROFILE_START(npp, "memalloc");
- *value = static_cast<NPIdentifier *>(
- NPN_MemAlloc(*count * sizeof(NPIdentifier)));
- GLUE_PROFILE_STOP(npp, "memalloc");
- memcpy(*value, property_ids, kNumPropertyIds * sizeof(NPIdentifier));
- memcpy(*value + kNumPropertyIds, method_ids,
- kNumMethodIds * sizeof(NPIdentifier));
- glue::StaticEnumeratePropertyHelper(
- *value + kNumPropertyIds + kNumMethodIds);
- return true;
-}
-
-static NPClass plugin_npclass = {
- NP_CLASS_STRUCT_VERSION,
- PluginAllocate,
- PluginDeallocate,
- 0,
- PluginHasMethod,
- PluginInvoke,
- 0,
- PluginHasProperty,
- PluginGetProperty,
- PluginSetProperty,
- 0,
- PluginEnumerate,
-};
-
-PluginObject *PluginObject::Create(NPP npp) {
- GLUE_PROFILE_START(npp, "createobject");
- PluginObject *plugin_object =
- static_cast<PluginObject *>(NPN_CreateObject(npp, &plugin_npclass));
- GLUE_PROFILE_STOP(npp, "createobject");
- return plugin_object;
-}
-
-void InitializeGlue(NPP npp) {
- GLUE_PROFILE_START(npp, "getstringidentifiers");
- NPN_GetStringIdentifiers(property_names, kNumPropertyIds, property_ids);
- NPN_GetStringIdentifiers(method_names, kNumMethodIds, method_ids);
- GLUE_PROFILE_STOP(npp, "getstringidentifiers");
- glue::InitializeGlue(npp);
-}
-
-// Plugin has been resized.
-void PluginObject::Resize(int width, int height) {
- // check that the window size has actually changed
- if (prev_width_ != width || prev_height_ != height) {
- prev_width_ = width;
- prev_height_ = height;
-
- if (renderer_ && !fullscreen_) {
- // If we are rendering offscreen, we may need to reallocate the
- // render surfaces.
- if (offscreen_rendering_enabled_) {
- AllocateOffscreenRenderSurfaces(width, height);
- }
-
- // 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(prev_width_, prev_height_);
- // This is just so that the client can send an event to the user.
- client()->SendResizeEvent(prev_width_, prev_height_, fullscreen_);
- }
- }
-}
-
-int PluginObject::width() const {
- if (renderer_) {
- return renderer_->width();
- }
- return 0;
-}
-
-int PluginObject::height() const {
- if (renderer_) {
- return renderer_->height();
- }
- return 0;
-}
-
-bool PluginObject::SetFullscreenClickRegion(int x, int y, int width, int height,
- int mode_id) {
- bool success = false;
- o3d::DisplayMode mode;
- // Make sure it's a valid ID first.
- if (GetDisplayMode(mode_id, &mode)) {
- fullscreen_region_valid_ = true;
- fullscreen_region_x_ = x;
- fullscreen_region_y_ = y;
- fullscreen_region_width_ = width;
- fullscreen_region_height_ = height;
- fullscreen_region_mode_id_ = mode_id;
- success = true;
- }
- return success;
-}
-
-// On Mac there is a different implementation in plugin_mac.mm.
-#ifndef OS_MACOSX
-void PluginObject::GetDisplayModes(std::vector<o3d::DisplayMode> *modes) {
- if (renderer()) {
- renderer()->GetDisplayModes(modes);
- } else {
- modes->clear();
- }
-}
-#endif
-
-void PluginObject::RedirectToFile(const char *url) {
- char cmd[] = "window.location = 'file:///%s';";
- scoped_array<char> full_cmd(new char[strlen(url) + sizeof(cmd)]);
- sprintf(full_cmd.get(), cmd, url);
-
- NPObject *global_object;
- NPN_GetValue(npp(), NPNVWindowNPObject, &global_object);
- NPString string;
- string.UTF8Characters = full_cmd.get();
- string.UTF8Length = strlen(string.UTF8Characters);
- NPVariant result;
- bool temp = NPN_Evaluate(npp(), global_object, &string, &result);
- if (temp) {
- NPN_ReleaseVariantValue(&result);
- }
-}
-
-o3d::Cursor::CursorType PluginObject::cursor() const {
- return cursor_type_;
-}
-
-void PluginObject::set_cursor(o3d::Cursor::CursorType cursor_type) {
- cursor_type_ = cursor_type;
- PlatformSpecificSetCursor();
-}
-
-#ifdef OS_WIN
-static const wchar_t* kWindowPropertyName = L"o3d";
-
-void PluginObject::StorePluginProperty(HWND hWnd, PluginObject *obj) {
- if (obj->GetHWnd()) { // Clear out the record from the old window first.
- ClearPluginProperty(obj->GetHWnd());
- }
- obj->SetHWnd(hWnd);
- StorePluginPropertyUnsafe(hWnd, obj);
-}
-
-void PluginObject::StorePluginPropertyUnsafe(HWND hWnd, PluginObject *obj) {
- if (hWnd) {
- SetProp(hWnd, kWindowPropertyName, static_cast<HANDLE>(obj));
- ::DragAcceptFiles(hWnd, true);
- }
-}
-
-PluginObject *PluginObject::GetPluginProperty(HWND hWnd) {
- return static_cast<PluginObject*>(GetProp(hWnd, kWindowPropertyName));
-}
-
-void PluginObject::ClearPluginProperty(HWND hWnd) {
- if (hWnd) {
- // TODO: convert to using app::win::ScopedProp.
- RemoveProp(hWnd, kWindowPropertyName);
- ::DragAcceptFiles(hWnd, false);
- }
-}
-
-static LPCTSTR O3DToWindowsCursor(o3d::Cursor::CursorType cursor_type) {
- switch (cursor_type) {
- case o3d::Cursor::DEFAULT:
- return IDC_ARROW;
- case o3d::Cursor::NONE:
- return NULL;
- case o3d::Cursor::CROSSHAIR:
- return IDC_CROSS;
- case o3d::Cursor::POINTER:
- return IDC_HAND;
- case o3d::Cursor::E_RESIZE:
- return IDC_SIZEWE;
- case o3d::Cursor::NE_RESIZE:
- return IDC_SIZENESW;
- case o3d::Cursor::NW_RESIZE:
- return IDC_SIZENWSE;
- case o3d::Cursor::N_RESIZE:
- return IDC_SIZENS;
- case o3d::Cursor::SE_RESIZE:
- return IDC_SIZENWSE;
- case o3d::Cursor::SW_RESIZE:
- return IDC_SIZENESW;
- case o3d::Cursor::S_RESIZE:
- return IDC_SIZENS;
- case o3d::Cursor::W_RESIZE:
- return IDC_SIZEWE;
- case o3d::Cursor::MOVE:
- return IDC_SIZEALL;
- case o3d::Cursor::TEXT:
- return IDC_IBEAM;
- case o3d::Cursor::WAIT:
- return IDC_WAIT;
- case o3d::Cursor::PROGRESS:
- return IDC_APPSTARTING;
- case o3d::Cursor::HELP:
- return IDC_HELP;
- }
- return IDC_ARROW;
-}
-
-void PluginObject::PlatformSpecificSetCursor() {
- if (!cursors_[cursor_type_]) {
- cursors_[cursor_type_] = ::LoadCursor(NULL,
- O3DToWindowsCursor(cursor_type_));
- }
- ::SetCursor(cursors_[cursor_type_]);
-}
-
-#endif // OS_WIN
-
-#ifdef OS_LINUX
-
-void PluginObject::SetDisplay(Display *display) {
- if (display_ != display) {
- if (display_) {
- for (int i = 0; i < o3d::Cursor::NUM_CURSORS; ++i) {
- if (cursors_[i]) {
- XFreeCursor(display_, cursors_[i]);
- cursors_[i] = 0;
- }
- }
- }
- display_ = display;
- }
-}
-
-static unsigned int O3DToX11CursorShape(o3d::Cursor::CursorType cursor_type) {
- switch (cursor_type) {
- case o3d::Cursor::DEFAULT:
- return XC_arrow;
- case o3d::Cursor::CROSSHAIR:
- return XC_crosshair;
- case o3d::Cursor::POINTER:
- return XC_hand2;
- case o3d::Cursor::E_RESIZE:
- return XC_right_side;
- case o3d::Cursor::NE_RESIZE:
- return XC_top_right_corner;
- case o3d::Cursor::NW_RESIZE:
- return XC_top_left_corner;
- case o3d::Cursor::N_RESIZE:
- return XC_top_side;
- case o3d::Cursor::SE_RESIZE:
- return XC_bottom_right_corner;
- case o3d::Cursor::SW_RESIZE:
- return XC_bottom_left_corner;
- case o3d::Cursor::S_RESIZE:
- return XC_bottom_side;
- case o3d::Cursor::W_RESIZE:
- return XC_left_side;
- case o3d::Cursor::MOVE:
- return XC_fleur;
- case o3d::Cursor::TEXT:
- return XC_xterm;
- case o3d::Cursor::WAIT:
- return XC_watch;
- case o3d::Cursor::PROGRESS:
- NOTIMPLEMENTED();
- return XC_watch;
- case o3d::Cursor::HELP:
- NOTIMPLEMENTED();
- return XC_arrow;
- }
- NOTIMPLEMENTED();
- return XC_arrow;
-}
-
-static Cursor O3DToX11Cursor(Display *display, Window window,
- o3d::Cursor::CursorType cursor_type) {
- switch (cursor_type) {
- case o3d::Cursor::NONE: {
- // There is no X11 primitive for hiding the cursor. The standard practice
- // is to define a custom cursor from a 1x1 invisible pixmap.
- static char zero[1] = {0};
- Pixmap zero_pixmap = XCreateBitmapFromData(display, window, zero, 1, 1);
- DLOG_ASSERT(zero_pixmap);
- if (!zero_pixmap) {
- return 0;
- }
- // This could actually be any colour, since our mask pixmap specifies that
- // no pixels are visible.
- XColor black;
- black.red = 0;
- black.green = 0;
- black.blue = 0;
- Cursor cursor = XCreatePixmapCursor(display, zero_pixmap, zero_pixmap,
- &black, &black, 0, 0);
- XFreePixmap(display, zero_pixmap);
- return cursor;
- }
-
- default:
- return XCreateFontCursor(display, O3DToX11CursorShape(cursor_type));
- }
-}
-
-void PluginObject::PlatformSpecificSetCursor() {
- if (!cursors_[cursor_type_]) {
- // According to the docs, the window here is only relevant for selecting the
- // screen, and we always create our fullscreen and embedded windows on the
- // same screen, so we can just always use the embedded window.
- cursors_[cursor_type_] = O3DToX11Cursor(display_, window_, cursor_type_);
- }
- Window window = fullscreen_ ? fullscreen_window_ : window_;
- XDefineCursor(display_, window, cursors_[cursor_type_]);
-}
-
-#endif // OS_LINUX
-
-void PluginObject::TickPluginObject(void* data) {
- PluginObject* plugin_object = static_cast<PluginObject*>(data);
- plugin_object->ExecuteAsyncTick();
-}
-
-void PluginObject::AsyncTick() {
- if (pending_ticks_ >= 1)
- return;
-
- ++pending_ticks_;
-
- // In Chrome NPN_PluginThreadAsyncCall doesn't seem to function properly.
- // We resort to loading a data: url with zero bytes to get a tick callback
- // asynchronously.
- // TODO(vangelis): Remove this special path when Chrome's
- // NPN_PluginThreadAsyncCall is fixed.
- if (IsChrome()) {
- class TickCallback : public StreamManager::FinishedCallback {
- public:
- explicit TickCallback(PluginObject* plugin_object)
- : plugin_object_(plugin_object) {
- }
-
- virtual void Run(DownloadStream*,
- bool,
- const std::string&,
- const std::string&) {
- plugin_object_->ExecuteAsyncTick();
- }
-
- private:
- PluginObject* plugin_object_;
- };
-
- if (!stream_manager_->LoadURL("data:,", NULL, NULL, NULL,
- new TickCallback(this), NP_NORMAL)) {
- DLOG(ERROR) << "Chrome failed to access data url";
- // If the async call fails then tick synchronously.
- Tick();
- }
- } else {
- // Invoke Tick asynchronously if NPN_PluginThreadAsyncCall is supported.
- // Otherwise invoke it synchronously.
- if (IsPluginThreadAsyncCallSupported(npp_)) {
- NPN_PluginThreadAsyncCall(npp_, TickPluginObject, this);
- } else {
- Tick();
- }
- }
-}
-
-void PluginObject::ExecuteAsyncTick() {
- // Check the plugin has not been destroyed already. Chrome sometimes invokes
- // async callbacks after destruction.
- if (!client())
- return;
-
- // Don't allow reentrancy through asynchronous ticks. Chrome sometimes does
- // this. It is also possible for the asyncronous call to be invoked while
- // a message is being handled. This prevents that.
- Client::ScopedIncrement reentrance_count(client());
- if (reentrance_count.get() > 1) {
- --pending_ticks_;
- return;
- }
-
- Tick();
-}
-
-void PluginObject::Tick() {
- DCHECK_GT(pending_ticks_, 0);
- --pending_ticks_;
-
- client_->Tick();
- if (renderer_ && renderer_->need_to_render()) {
- client_->RenderClient(true);
- }
-}
-
-void PluginObject::EnableOffscreenRendering() {
- if (!offscreen_rendering_enabled_) {
- AllocateOffscreenRenderSurfaces(width(), height());
- offscreen_rendering_enabled_ = true;
- }
-}
-
-void PluginObject::DisableOffscreenRendering() {
- if (offscreen_rendering_enabled_) {
- DeallocateOffscreenRenderSurfaces();
- offscreen_rendering_enabled_ = false;
- }
-}
-
-bool PluginObject::IsOffscreenRenderingEnabled() const {
- return offscreen_rendering_enabled_;
-}
-
-RenderSurface::Ref PluginObject::GetOffscreenRenderSurface() const {
- return offscreen_render_surface_;
-}
-
-Bitmap::Ref PluginObject::GetOffscreenBitmap() const {
- return offscreen_readback_bitmap_;
-}
-
-bool PluginObject::AllocateOffscreenRenderSurfaces(int width, int height) {
- int pot_width =
- static_cast<int>(o3d::image::ComputePOTSize(width));
- int pot_height =
- static_cast<int>(o3d::image::ComputePOTSize(height));
- if (!renderer_ || pot_width == 0 || pot_height == 0) {
- return false;
- }
- bool must_reallocate_render_surfaces =
- (offscreen_render_surface_.IsNull() ||
- offscreen_depth_render_surface_.IsNull() ||
- offscreen_render_surface_->width() != pot_width ||
- offscreen_render_surface_->height() != pot_height);
- if (must_reallocate_render_surfaces) {
- Texture2D::Ref texture = renderer_->CreateTexture2D(
- pot_width,
- pot_height,
- Texture::ARGB8,
- 1,
- true);
- if (texture.IsNull()) {
- return false;
- }
- RenderSurface::Ref surface(texture->GetRenderSurface(0));
- if (surface.IsNull()) {
- return false;
- }
- RenderDepthStencilSurface::Ref depth(renderer_->CreateDepthStencilSurface(
- pot_width,
- pot_height));
- if (depth.IsNull()) {
- return false;
- }
- offscreen_texture_ = texture;
- offscreen_render_surface_ = surface;
- offscreen_depth_render_surface_ = depth;
- }
- offscreen_render_surface_->SetClipSize(width, height);
- offscreen_depth_render_surface_->SetClipSize(width, height);
- if (offscreen_readback_bitmap_.IsNull() ||
- offscreen_readback_bitmap_->width() != width ||
- offscreen_readback_bitmap_->height() != height) {
- o3d::Bitmap::Ref bitmap = Bitmap::Ref(
- new Bitmap(service_locator()));
- bitmap->Allocate(Texture::ARGB8,
- width, height, 1, Bitmap::IMAGE);
- offscreen_readback_bitmap_ = bitmap;
- }
- // Tell the Client about the newly allocated surfaces so that normal
- // calls to RenderClient can automatically do the right thing.
- client_->SetOffscreenRenderingSurfaces(offscreen_render_surface_,
- offscreen_depth_render_surface_);
- return true;
-}
-
-void PluginObject::DeallocateOffscreenRenderSurfaces() {
- if (client_) {
- client_->SetOffscreenRenderingSurfaces(RenderSurface::Ref(),
- RenderDepthStencilSurface::Ref());
- }
- offscreen_render_surface_.Reset();
- offscreen_depth_render_surface_.Reset();
- offscreen_readback_bitmap_.Reset();
-}
-
-} // namespace _o3d
-
-namespace globals {
-
-using _o3d::PluginObject;
-// This implements the definition in common.h of a function to receive
-// all glue error reports.
-void SetLastError(NPP npp, const char *error) {
- PluginObject *plugin_object = static_cast<PluginObject *>(npp->pdata);
- O3D_ERROR(plugin_object->service_locator()) << error;
-}
-
-// These implement the definitions in common.h of functions to receive
-// all profiling calls.
-void ProfileStart(NPP npp, const std::string& key) {
- PluginObject *plugin_object = static_cast<PluginObject *>(npp->pdata);
- if (plugin_object) { // May not be initialized yet.
- plugin_object->client()->ProfileStart(key);
- }
-}
-
-void ProfileStop(NPP npp, const std::string& key) {
- PluginObject *plugin_object = static_cast<PluginObject *>(npp->pdata);
- if (plugin_object) { // May not be initialized yet.
- plugin_object->client()->ProfileStop(key);
- }
-}
-
-void ProfileReset(NPP npp) {
- PluginObject *plugin_object = static_cast<PluginObject *>(npp->pdata);
- if (plugin_object) { // May not be initialized yet.
- plugin_object->client()->ProfileReset();
- }
-}
-
-std::string ProfileToString(NPP npp) {
- PluginObject *plugin_object = static_cast<PluginObject *>(npp->pdata);
- if (plugin_object) { // May not be initialized yet.
- return plugin_object->client()->ProfileToString();
- } else {
- return "";
- }
-}
-
-} // namespace globals
-} // namespace glue
diff --git a/o3d/plugin/cross/o3d_glue.h b/o3d/plugin/cross/o3d_glue.h
deleted file mode 100644
index 79cdcd9..0000000
--- a/o3d/plugin/cross/o3d_glue.h
+++ /dev/null
@@ -1,568 +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_PLUGIN_CROSS_O3D_GLUE_H_
-#define O3D_PLUGIN_CROSS_O3D_GLUE_H_
-
-#include <build/build_config.h>
-
-#ifdef OS_MACOSX
-#include <OpenGL/OpenGL.h>
-#include <AGL/agl.h>
-#include <CoreGraphics/CGContext.h>
-#endif
-
-#ifdef OS_LINUX
-#include <X11/Xlib.h>
-#include <X11/Intrinsic.h>
-#include <gtk/gtk.h>
-#endif
-
-
-#include <map>
-#include <set>
-#include <string>
-#include <vector>
-#include "base/scoped_ptr.h"
-#include "base/hash_tables.h"
-#include "core/cross/bitmap.h"
-#include "core/cross/display_mode.h"
-#include "core/cross/display_window.h"
-#include "core/cross/object_base.h"
-#include "core/cross/service_locator.h"
-#include "core/cross/evaluation_counter.h"
-#include "core/cross/class_manager.h"
-#include "core/cross/client_info.h"
-#include "core/cross/cursor.h"
-#include "core/cross/features.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/error.h"
-#include "core/cross/profiler.h"
-#include "core/cross/render_surface.h"
-#include "core/cross/texture.h"
-#include "plugin/cross/main_thread_task_poster.h"
-#include "plugin/cross/np_v8_bridge.h"
-#ifdef OS_MACOSX
-#include "plugin/mac/fullscreen_window_mac.h"
-#endif
-#include "client_glue.h"
-#include "third_party/nixysa/static_glue/npapi/common.h"
-
-namespace o3d {
-class Client;
-class Renderer;
-}
-
-// Hashes the NPClass and ObjectBase types so they can be used in a hash_map.
-#if defined(COMPILER_GCC)
-namespace __gnu_cxx {
-
-template<>
-struct hash<NPClass*> {
- std::size_t operator()(NPClass* const& ptr) const {
- return hash<size_t>()(reinterpret_cast<size_t>(ptr));
- }
-};
-
-template<>
-struct hash<const o3d::ObjectBase::Class*> {
- std::size_t operator()(const o3d::ObjectBase::Class* const& ptr) const {
- return hash<size_t>()(reinterpret_cast<size_t>(ptr));
- }
-};
-
-} // namespace __gnu_cxx
-#elif defined(COMPILER_MSVC)
-namespace stdext {
-
-template<>
-inline size_t hash_value(NPClass* const& ptr) {
- return hash_value(reinterpret_cast<size_t>(ptr));
-}
-
-template<>
-inline size_t hash_value(const o3d::ObjectBase::Class* const& ptr) {
- return hash_value(reinterpret_cast<size_t>(ptr));
-}
-
-} // namespace stdext
-#endif // COMPILER
-
-namespace glue {
-class StreamManager;
-
-namespace _o3d {
-using o3d::Id;
-using o3d::ObjectBase;
-using o3d::Bitmap;
-using o3d::Client;
-using o3d::ClassManager;
-using o3d::ClientInfoManager;
-using o3d::EvaluationCounter;
-using o3d::Features;
-using o3d::EvaluationCounter;
-using o3d::MainThreadTaskPoster;
-using o3d::ObjectManager;
-using o3d::Profiler;
-using o3d::Renderer;
-using o3d::RenderSurface;
-using o3d::RenderDepthStencilSurface;
-using o3d::ServiceLocator;
-using o3d::Texture2D;
-#ifdef OS_MACOSX
-using o3d::FullscreenWindowMac;
-#endif
-
-class NPAPIObject: public NPObject {
- NPP npp_;
- Id id_;
- bool mapped_;
- public:
- explicit NPAPIObject(NPP npp): npp_(npp), id_(0), mapped_(false) {}
- void Initialize(const ObjectBase *object) { id_ = object->id(); }
- NPP npp() const { return npp_; }
- Id id() const { return id_; }
- bool mapped() const { return mapped_; }
- void set_mapped(bool mapped) { mapped_ = mapped; }
-};
-void RegisterType(NPP npp, const ObjectBase::Class *clientclass,
- NPClass *npclass);
-bool CheckObject(NPP npp, NPObject *npobject,
- const ObjectBase::Class *clientclass);
-NPAPIObject *GetNPObject(NPP npp, ObjectBase *object);
-NPObject *Allocate(NPP npp, NPClass *npclass);
-void Deallocate(NPObject *object);
-ServiceLocator *GetServiceLocator(NPP npp);
-Client *GetClient(NPP npp);
-void InitializeGlue(NPP npp);
-
-typedef glue::namespace_o3d::class_Client::NPAPIObject ClientNPObject;
-
-class PluginObject: public NPObject {
- typedef ::base::hash_map<Id, NPAPIObject *> ClientObjectMap;
- typedef ::base::hash_map<const ObjectBase::Class *, NPClass *>
- ClientToNPClassMap;
- typedef ::base::hash_map<NPClass *, const ObjectBase::Class *>
- NPToClientClassMap;
-
- NPP npp_;
- ServiceLocator service_locator_;
- EvaluationCounter evaluation_counter_;
- ClassManager class_manager_;
- ClientInfoManager client_info_manager_;
- ObjectManager object_manager_;
- Profiler profiler_;
- MainThreadTaskPoster main_thread_task_poster_;
- bool fullscreen_; // Are we rendered fullscreen or in the plugin region?
- Renderer *renderer_;
- Client *client_;
- Features* features_;
- ClientObjectMap object_map_;
- ClientToNPClassMap client_to_np_class_map_;
- NPToClientClassMap np_to_client_class_map_;
- NPObject *globals_npobject_;
- ClientNPObject *client_npobject_;
- std::string user_agent_;
- Renderer::InitStatus renderer_init_status_;
- int pending_ticks_;
-
- // The current cursor type.
- o3d::Cursor::CursorType cursor_type_;
-
- // Last known dimensions of plugin
- int prev_width_;
- int prev_height_;
-
- o3d::NPV8Bridge np_v8_bridge_;
- scoped_ptr<StreamManager> stream_manager_;
-
- public:
-#ifdef OS_WIN
- void SetHWnd(HWND hWnd) {
- hWnd_ = hWnd;
- }
- HWND GetHWnd() {
- return hWnd_;
- }
- void SetPluginHWnd(HWND hWnd) {
- plugin_hWnd_ = hWnd;
- }
- HWND GetPluginHWnd() {
- return plugin_hWnd_;
- }
- void SetContentHWnd(HWND hWnd) {
- content_hWnd_ = hWnd;
- }
- HWND GetContentHWnd() {
- return content_hWnd_;
- }
- bool RecordPaint() {
- bool painted = painted_once_;
- painted_once_ = true;
- return painted;
- }
- bool got_dblclick() const { return got_dblclick_; }
- void set_got_dblclick(bool got_dblclick) { got_dblclick_ = got_dblclick; }
-#elif defined(OS_LINUX)
- void SetGtkEventSource(GtkWidget *widget);
- gboolean OnGtkConfigure(GtkWidget *widget,
- GdkEventConfigure *configure_event);
- gboolean OnGtkDelete(GtkWidget *widget,
- GdkEvent *configure);
- void SetDisplay(Display *display);
-#elif defined(OS_MACOSX)
- FullscreenWindowMac* GetFullscreenMacWindow() {
- return mac_fullscreen_window_;
- }
-
- void SetFullscreenMacWindow(FullscreenWindowMac* window) {
- mac_fullscreen_window_ = window;
- }
-
- WindowRef GetMacWindow() {
- return mac_window_;
- }
-
- bool ScrollIsInProgress() { return scroll_is_in_progress_; }
- void SetScrollIsInProgress(bool state) { scroll_is_in_progress_ = state; }
- bool scroll_is_in_progress_;
-
- bool RendererIsSoftware() {return renderer_is_software_;}
- bool SetRendererIsSoftware(bool state);
- bool renderer_is_software_;
-
- AGLContext GetMacAGLContext() {
- return mac_agl_context_;
- }
-
- CGLContextObj GetMacCGLContext() {
- return mac_cgl_context_;
- }
-
- void SetMacCGLContext(CGLContextObj obj);
-
- CGLContextObj GetFullscreenShareContext();
- CGLPixelFormatObj GetFullscreenCGLPixelFormatObj();
- void* GetFullscreenNSOpenGLContext();
- void CleanupFullscreenOpenGLContext();
-
- NPDrawingModel drawing_model_;
- NPEventModel event_model_;
- WindowRef mac_window_; // may be NULL in the Chrome case
- // these vars needed for the Safari tab switch detection hack
- CFDateRef last_mac_event_time_;
- void * mac_cocoa_window_;
- void* mac_window_selected_tab_;
- bool mac_surface_hidden_;
- // end of Safari tab detection vars
- GLint last_buffer_rect_[4];
- Point last_plugin_loc_;
- // each of these three can be NULL depending on drawing_model
- CGContextRef mac_cg_context_ref_;
- AGLContext mac_agl_context_;
- CGLContextObj mac_cgl_context_;
- void *gl_layer_;
- // If in Chrome, we actually do all of our rendering offscreen, and
- // bootstrap off a 1x1 pbuffer
- CGLPBufferObj mac_cgl_pbuffer_;
-
- // Fullscreen related stuff.
- // NULL if not in fullscreen mode.
- // Must not be a scoped_ptr due to reentrancy during termination.
- FullscreenWindowMac* mac_fullscreen_window_;
- // When rendering using CGL, we need to use an NSOpenGLContext to
- // implement full-screen support. In order to share textures and
- // other resources between the core CGL context and the full-screen
- // one, we need to allocate the NSOpenGLContext first, because with
- // pre-10.6 APIs it isn't possible to make an NSOpenGLContext share
- // resources with a preexisting CGLContextObj.
- void* mac_fullscreen_nsopenglcontext_;
- // On 10.5 (Core Graphics drawing model) it appears that we need to
- // forcibly reuse the CGLContextObj from the NSOpenGLPixelFormat
- // that we use to create the NSOpenGLContext for full-screen, or
- // the share context is reported invalid.
- void* mac_fullscreen_nsopenglpixelformat_;
- // Indication when we transition to full-screen mode of whether we
- // were using off-screen rendering (Core Graphics drawing model, in
- // particular).
- bool was_offscreen_;
-
-#endif // OS_MACOSX
-#ifdef OS_LINUX
- Window window_;
- Window fullscreen_window_;
-
- // Xt mode
- Widget xt_widget_;
- XtAppContext xt_app_context_;
- XtIntervalId xt_interval_;
- Time last_click_time_;
-
- // XEmbed mode
- Window drawable_;
- GdkDisplay *gdk_display_;
- GtkWidget *gtk_container_;
- GtkWidget *gtk_fullscreen_container_;
- GtkWidget *gtk_event_source_;
- gulong event_handler_id_;
- bool got_double_click_[3];
- guint timeout_id_;
- bool fullscreen_pending_;
-
- bool draw_;
- bool in_plugin_;
-#endif
- explicit PluginObject(NPP npp);
- ~PluginObject();
- void Init(int argc, char* argn[], char* argv[]);
- void TearDown();
- ServiceLocator* service_locator() { return &service_locator_; }
- Features *features() { return features_; }
- Client *client() { return client_; }
- Renderer *renderer() { return renderer_; }
- NPP npp() { return npp_; }
- void RegisterType(const ObjectBase::Class *clientclass, NPClass *npclass);
- bool CheckObject(NPObject *npobject,
- const ObjectBase::Class *clientclass) const;
- NPAPIObject *GetNPObject(ObjectBase *object);
- void UnmapObject(NPAPIObject *npobject);
- void UnmapAll();
- NPClass *GetNPClass(const ObjectBase::Class *clientclass);
-
- NPObject *globals_npobject() { return globals_npobject_; }
- ClientNPObject *client_npobject() { return client_npobject_; }
-
- static const char* kOnRenderEventName;
-
- static PluginObject *Create(NPP npp);
-
- StreamManager *stream_manager() const { return stream_manager_.get(); }
-
- static void LogAssertHandlerFunction(const std::string& str);
-
- Renderer::InitStatus renderer_init_status() const {
- return renderer_init_status_;
- }
-
- // Plugin has been resized.
- void Resize(int width, int height);
-
- int width() const;
- int height() const;
-
- // Fullscreen stuff
- bool fullscreen() const {
- return fullscreen_;
- }
-
- // Fetch one mode by externally visible id, returning true on success.
- bool GetDisplayMode(int id, o3d::DisplayMode *mode);
-
- // Get a vector of the available fullscreen display modes.
- // Clears *modes on error.
- void GetDisplayModes(std::vector<o3d::DisplayMode> *modes);
-
- // This isn't exposed directly to JavaScript for security reasons; it gets
- // called by the platform-specific event-handling code if the region set by
- // SetFullscreenClickRegion is clicked. It requests the mode previously set
- // by SetFullscreenClickRegion(), and fails if there wasn't one.
-#ifdef OS_LINUX
- bool RequestFullscreenDisplay(guint32 timestamp);
-#else
- bool RequestFullscreenDisplay();
-#endif
-
- // Make a region of the plugin area that will invoke fullscreen mode if
- // clicked. The app developer is responsible for communicating this to the
- // user, as this region has no visible marker. The developer is also
- // responsible for updating this region if the plugin gets resized, as we
- // don't know whether or how to scale it.
- // Fails if the mode_id supplied isn't valid. Returns true on success.
- bool SetFullscreenClickRegion(int x, int y, int width, int height,
- int mode_id);
- void ClearFullscreenClickRegion() {
- fullscreen_region_valid_ = false;
- }
-
- // Tests a mouse click location for a hit on the fullscreen click region.
- bool HitFullscreenClickRegion(int x, int y) {
- if (!fullscreen_region_valid_ || fullscreen_) {
- return false;
- }
- return (x >= fullscreen_region_x_) &&
- (x - fullscreen_region_x_ < fullscreen_region_width_) &&
- (y >= fullscreen_region_y_) &&
- (y - fullscreen_region_y_ < fullscreen_region_height_);
- }
-
- // Deactivate fullscreen mode.
- void CancelFullscreenDisplay();
-
- // Redirect by setting window.location to file:///<url>.
- void RedirectToFile(const char *url);
-
- // Get the cursor's shape.
- o3d::Cursor::CursorType cursor() const;
-
- // Set the cursor's shape.
- void set_cursor(o3d::Cursor::CursorType cursor_type);
-
- // Sets the cursor to whatever the current cursor is.
- void PlatformSpecificSetCursor();
-
- // Asynchronously (if possible, synchronously otherwise) invoke Tick. No
- // operation if an asynchronous tick is already pending.
- void AsyncTick();
-
- // Tick the client.
- void Tick();
-
- const std::string& user_agent() const { return user_agent_; }
- bool IsFirefox() const {
- return user_agent_.find("Firefox") != user_agent_.npos;
- }
- bool IsChrome() const {
- return user_agent_.find("Chrome") != user_agent_.npos;
- }
- bool IsMSIE() const {
- return user_agent_.find("MSIE") != user_agent_.npos;
- }
-
- o3d::NPV8Bridge* np_v8_bridge() { return &np_v8_bridge_; }
-
- // Creates the renderer.
- void CreateRenderer(const o3d::DisplayWindow& display_window);
-
- // Deletes the renderer.
- void DeleteRenderer();
-
-#ifdef OS_MACOSX
- // Methods needed for the Safari tab-switching hack.
- void MacEventReceived(bool updateTab);
-
- CFTimeInterval TimeSinceLastMacEvent();
-
- bool DetectTabHiding();
-#endif
-
-#ifdef OS_WIN
- // Stashes a pointer to the plugin on the HWND, and keeps a corresponding
- // pointer to the HWND on the plugin. If the plugin's already registered with
- // an HWND, this will clear out the plugin pointer on the old HWND before
- // setting up the new one.
- static void StorePluginProperty(HWND hWnd, PluginObject *obj);
- // Similar to StorePluginProperty, but doesn't clear out any old pointers.
- static void StorePluginPropertyUnsafe(HWND hWnd, PluginObject *obj);
- // Looks up the plugin stored on this HWND.
- static PluginObject *GetPluginProperty(HWND hWnd);
- // Clears out the plugin stored on this HWND.
- static void ClearPluginProperty(HWND hWnd);
- // One bit of state that helps us turn the sequence of events that windows
- // produces on a double click into what JavaScript is expecting.
- bool got_dblclick_;
-#endif // OS_WIN
-#ifdef OS_LINUX
- bool in_plugin() const { return in_plugin_; }
- void set_in_plugin(bool value) { in_plugin_ = value; }
- Time last_click_time() const { return last_click_time_; }
- void set_last_click_time(Time value) { last_click_time_ = value; }
-#endif
-
-#if defined(CB_SERVICE_REMOTE)
- void SetGPUPluginObject(NPObject* gpu_plugin_object);
- NPObject* GetGPUPluginObject() {
- return gpu_plugin_object_;
- }
-#endif
-
- // Support for rendering the plugin's content into render surfaces.
- // This is currently different than offscreen rendering support in
- // the renderer. It is a bit of a mess because only the PluginObject
- // and Renderer have the necessary information about the viewport
- // size, and only the Client has enough information to properly
- // initiate a render.
- void EnableOffscreenRendering();
- void DisableOffscreenRendering();
- bool IsOffscreenRenderingEnabled() const;
- RenderSurface::Ref GetOffscreenRenderSurface() const;
- RenderDepthStencilSurface::Ref GetOffscreenDepthRenderSurface() const;
- Bitmap::Ref GetOffscreenBitmap() const;
-
- private:
- // Called through the browser's NPN_PluginThreadAsyncCall
- static void TickPluginObject(void* data);
-
- // Completes the work of an AsyncTick().
- void ExecuteAsyncTick();
-
- bool fullscreen_region_valid_;
- int fullscreen_region_x_;
- int fullscreen_region_y_;
- int fullscreen_region_width_;
- int fullscreen_region_height_;
- int fullscreen_region_mode_id_;
-#ifdef OS_WIN
- HWND hWnd_; // The window we are currently drawing to (use this).
- HWND plugin_hWnd_; // The window we were given inside the browser.
- HWND content_hWnd_; // The window containing the D3D or OpenGL content.
- HCURSOR cursors_[o3d::Cursor::NUM_CURSORS]; // loaded windows cursors.
- HCURSOR hCursor_;
- bool painted_once_;
-#elif defined(OS_LINUX)
- Display *display_;
- Cursor cursors_[o3d::Cursor::NUM_CURSORS]; // loaded windows cursors.
-#endif // OS_WIN
-
-#if defined(CB_SERVICE_REMOTE)
- NPObject* gpu_plugin_object_;
-#endif
-
- // Support for offscreen rendering and thereby windowless plugins.
- // Currently used only for the CoreGraphics drawing model on Mac OS
- // X when there is no WindowRef. It would be nicer to put this in
- // the Renderer and/or make its off_screen mode work everywhere, but
- // this is only a legacy solution for older browsers.
- bool offscreen_rendering_enabled_;
- Texture2D::Ref offscreen_texture_;
- RenderSurface::Ref offscreen_render_surface_;
- RenderDepthStencilSurface::Ref offscreen_depth_render_surface_;
- Bitmap::Ref offscreen_readback_bitmap_;
-
- bool AllocateOffscreenRenderSurfaces(int width, int height);
- void DeallocateOffscreenRenderSurfaces();
-};
-
-} // namespace o3d
-} // namespace glue
-
-
-#endif // O3D_PLUGIN_CROSS_O3D_GLUE_H_
diff --git a/o3d/plugin/cross/out_of_memory.cc b/o3d/plugin/cross/out_of_memory.cc
deleted file mode 100644
index db71932..0000000
--- a/o3d/plugin/cross/out_of_memory.cc
+++ /dev/null
@@ -1,239 +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 implements a failure handler for the new
-// operator and malloc for Windows and Mac. (On Linux,
-// chrome's libbase.a implements one already.)
-
-#include "plugin/cross/out_of_memory.h"
-
-#ifdef OS_LINUX
-namespace o3d {
-bool SetupOutOfMemoryHandler() {
- return true;
-}
-}
-#else
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <wchar.h>
-#include <build/build_config.h>
-
-#ifdef _MSC_VER
-#include <new.h>
-#endif
-
-#ifdef OS_WIN
-#include <windows.h>
-#endif
-
-#if defined(OS_MACOSX) || defined(OS_LINUX)
-#include <dlfcn.h>
-#endif
-
-#include "plugin/cross/plugin_metrics.h"
-
-#ifdef _MSC_VER
-extern "C" {
- void* _getptd();
-} // _MSC_VER
-#endif
-
-namespace o3d {
-namespace {
-// The reserve is allocated just after the plugin starts.
-// In the event that an allocation fails, the reserve is
-// freed, hopefully freeing enough memory to allow any code
-// run after abort() to do its work.
-const size_t kReserveSize = 1024 * 256;
-void* g_reserve;
-
-// This is called when a memory allocation fails in the plugin. Note
-// that it will not be called if a memory allocation fails in another
-// shared library, such as in the c runtime library on platforms where
-// we use a shared c runtime library. In those cases, we have to hope
-// that the allocation failed because new was called (in which case an
-// exception will be thrown but the reserve will not be freed) or that
-// the calling library correctly checks for a NULL return and does
-// something appropriate.
-int HandleOutOfMemory(size_t size) {
- if (g_reserve != NULL) {
- // First time round, free the reserve and exit with abort.
- // This should allow some crash reporting before the process
- // exits.signal
- free(g_reserve);
- g_reserve = NULL;
-
- // Do this on MacOSX and Linux when they support metrics.
- // Also, at the time of writing, the matrics logging is not
- // hooked up to breakpad, so this metric will not get logged
- // anywhere! Remove this comment when that is done and tested.
-#ifdef OS_WIN
- ++metric_out_of_memory_total;
-#endif // OS_MACOSX
-
- fprintf(stderr, "Aborting: out of memory allocating %lu bytes\n",
- static_cast<unsigned long>(size));
-
-#ifdef OS_WIN
- // This is different on Windows so that it is comnpatible with
- // the way that breakpad works. On Windows, it intercepts
- // exceptions. On unixy platforms, it handles signals. Also,
- // on Windows, this is friendlier to the browser's own crash
- // logging (for browsers that log crashes).
- RaiseException(ERROR_OUTOFMEMORY,
- EXCEPTION_NONCONTINUABLE_EXCEPTION,
- 0, NULL);
-#else // OS_WIN
- abort();
-#endif // OS_WIN
- } else {
- // If the handler is reentered, try to exit without raising
- // SIGABRT (or executing exit handlers).
- _exit(EXIT_FAILURE);
- }
- return 0;
-}
-} // namespace anonymous
-
-bool SetupOutOfMemoryHandler() {
-#ifdef _MSC_VER
- // Workaround for MSVC. Sometimes the runtime calls this when
- // there is not enough memory to allocate the "per-thread
- // data structure". Calling this forces the "per-thread data
- // structure" to be allocated.
- _getptd();
-
- // This causes malloc failures to call the new handler as well.
- // It is not necessary to replace the implementations of malloc,
- // etc under MSVC.
- _set_new_mode(1);
- _set_new_handler(HandleOutOfMemory);
-#endif // _MSC_VER
-
- g_reserve = malloc(kReserveSize);
-
- return true;
-}
-} // namespace o3d
-
-#if defined(OS_MACOSX)
-namespace {
-void* dlsym_helper(const char* symbol_name) {
- void* ptr = dlsym(RTLD_NEXT, symbol_name);
- if (ptr == NULL) {
- fprintf(stderr, "Error: could not locate symbol \"%s\"\n", symbol_name);
- abort();
- }
- return ptr;
-}
-} // namespace anonymous
-
-void* operator new(size_t size) {
- return malloc(size);
-}
-
-void operator delete(void* ptr) {
- free(ptr);
-}
-
-extern "C" {
-void *malloc(size_t size) {
- typedef void* (*Func)(size_t);
- static Func func = (Func) dlsym_helper("malloc");
- void* ptr = func(size);
- if (ptr == NULL)
- o3d::HandleOutOfMemory(size);
- return ptr;
-}
-
-void *realloc(void* old_ptr, size_t new_size) {
- typedef void* (*Func)(void*, size_t);
- static Func func = reinterpret_cast<Func>(dlsym_helper("realloc"));
- void* ptr = func(old_ptr, new_size);
-
- // realloc() returns NULL when you ask for zero bytes. This differs
- // from malloc() which returns a pointer to a zero sized allocated block.
- if (new_size != 0 && ptr == NULL)
- o3d::HandleOutOfMemory(new_size);
- return ptr;
-}
-
-void *calloc(size_t num_items, size_t size) {
- typedef void* (*Func)(size_t, size_t);
- static Func func = reinterpret_cast<Func>(dlsym_helper("calloc"));
- void* ptr = func(num_items, size);
- if (ptr == NULL)
- o3d::HandleOutOfMemory(size);
- return ptr;
-}
-
-void *valloc(size_t size) {
- typedef void* (*Func)(size_t);
- static Func func = reinterpret_cast<Func>(dlsym_helper("valloc"));
- void* ptr = func(size);
- if (ptr == NULL)
- o3d::HandleOutOfMemory(size);
- return ptr;
-}
-
-void* memalign(size_t alignment, size_t size) {
- typedef void* (*Func)(size_t, size_t);
- static Func func = reinterpret_cast<Func>(dlsym_helper("memalign"));
- void* ptr = func(alignment, size);
- if (ptr == NULL)
- o3d::HandleOutOfMemory(size);
- return ptr;
-}
-
-char* strdup(const char* ptr) {
- typedef char* (*Func)(const char*);
- static Func func = reinterpret_cast<Func>(dlsym_helper("strdup"));
- char* result = func(ptr);
- if (ptr != NULL && result == NULL)
- o3d::HandleOutOfMemory((strlen(ptr) + 1) * sizeof(char));
- return result;
-}
-
-wchar_t* wcsdup(const wchar_t* ptr) {
- typedef wchar_t* (*Func)(const wchar_t*);
- static Func func = reinterpret_cast<Func>(dlsym_helper("wcsdup"));
- wchar_t* result = func(ptr);
- if (ptr != NULL && result == NULL)
- o3d::HandleOutOfMemory((wcslen(ptr) + 1) * sizeof(wchar_t));
- return result;
-}
-}
-#endif // defined(OS_MACOSX)
-#endif // defined(OS_LINUX)
-
diff --git a/o3d/plugin/cross/out_of_memory.h b/o3d/plugin/cross/out_of_memory.h
deleted file mode 100644
index 03a321f..0000000
--- a/o3d/plugin/cross/out_of_memory.h
+++ /dev/null
@@ -1,43 +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 a failure handler for the new
-// operator and malloc and a function to set it up.
-
-#ifndef O3D_PLUGIN_CROSS_OUT_OF_MEMORY_H_
-#define O3D_PLUGIN_CROSS_OUT_OF_MEMORY_H_
-
-namespace o3d {
-bool SetupOutOfMemoryHandler();
-}
-
-#endif // O3D_PLUGIN_CROSS_OUT_OF_MEMORY_H_
diff --git a/o3d/plugin/cross/plugin_logging.h b/o3d/plugin/cross/plugin_logging.h
deleted file mode 100644
index 7997cb4..0000000
--- a/o3d/plugin/cross/plugin_logging.h
+++ /dev/null
@@ -1,158 +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 logging object which performs the metric aggregation
-// and uploading. This class takes care of the initialization of the logging
-// object and determining if the user has opted in or out to having logs sent
-// back. Furthermore, there are some helper functions to make testing easier.
-
-#ifndef O3D_PLUGIN_CROSS_PLUGIN_LOGGING_H_
-#define O3D_PLUGIN_CROSS_PLUGIN_LOGGING_H_
-
-#include "statsreport/metrics.h"
-#include "statsreport/common/highres_timer.h"
-#include "base/scoped_ptr.h"
-#include "base/basictypes.h"
-
-namespace o3d {
-
-class PluginLogging {
- public:
- PluginLogging();
- virtual ~PluginLogging() {}
-
- // Check to see if sufficient time has passed to process metrics. If such
- // time has passed, we reset the timer and proceed with processing metrics.
- //
- // Returns true if the metrics were processed properly.
- bool UpdateLogging();
-
- // Record how much time the plugin has spent running.
- virtual void RecordProcessTimes();
-
- // Takes care of gathering current statistics and uploading them to the server
- // if necessary.
- //
- // Parameters:
- // exiting - whether the program is exiting
- // force_report - whether to force the metrics to upload to the server
- // save_old_metrics - whether to clear the metrics before aggregating
- //
- // Returns true if metrics were uploaded and/or aggregated successfully.
- virtual bool ProcessMetrics(const bool exiting,
- const bool force_report,
- const bool save_old_metrics);
-
- // A helper function to call AggregateMetrics used for testing. Calls
- // AggregateMetrics which gathers up the current metrics, puts them in
- // the registry and then resets them.
- virtual void DoAggregateMetrics();
-
- // A helper function for testing. This function calls
- // stats_report::AggregateAndReportMetrics which will aggregate the metrics
- // and upload to the server if sufficient time has passed.
- //
- // Parameters:
- // extra_url_argument - extra url to be added after source id (O3D)
- // and version number
- // user_agent - eventually the client_id, currently not used
- //
- // Returns true if metrics were uploaded successfully. Note: false does
- // not necessarily mean an error; just that no metrics were uploaded.
- virtual bool DoAggregateAndReportMetrics(const char* extra_url_arguments,
- const char* user_agent,
- const bool force_report,
- const bool save_old_metrics);
-
- // PluginLogging assumes ownership of the timer.
- void SetTimer(HighresTimer* timer);
-
- // Factory method for creating the logger and taking care of initialization
- // and checks for opt-in/out.
- //
- // Returns the results CreateUsageStatsLogger which will be a pointer to new
- // PluginLogging object if the user opted in or NULL if they opted out.
- //
- // The existence of a PluginLogging object is used to check if logging is
- // turned on in other parts of the code.
- static PluginLogging* InitializeUsageStatsLogging();
-
- // Access the key determing opt-in. Separated out for testing.
- // Returns true if the user opted in.
-#ifdef OS_MACOSX
- static bool GetOptInKeyValue(void);
-#else
- static bool GetOptInKeyValue(const wchar_t* clientstate_registry_key,
- const wchar_t* opt_in_registry_key);
-#endif
-
- // Method for actually creating the logger. Separated out for testing.
- //
- // Returns the results CreateUsageStatsLogger which will be a pointer to new
- // PluginLogging object if the user opted in or NULL if they opted out.
- //
- // The existence of a PluginLogging object is used to check if logging is
- // turned on in other parts of the code.
- template <class LoggingType>
- static LoggingType* CreateUsageStatsLogger(const bool opt_in) {
- if (opt_in == true) {
- // They opted in!
- LoggingType* logger = new LoggingType();
- stats_report::g_global_metrics.Initialize();
-
- // Do an initial grab of the metrics. Don't pass true for force_report.
- // This will force an upload of the metrics the first time o3d is run
- // since the lastTransmission metric will not exist.
- logger->ProcessMetrics(false, false, true);
- return logger;
- }
- // Otherwise, they opted out so we make sure the registry is clear
- ClearLogs();
- return NULL;
- }
-
- // Method for cleaning out the logs. Used if the user opts-out to make sure
- // we don't retain any information from them.
- static void ClearLogs();
-
- private:
- // Timer for determining the next time aggregation should occur.
- scoped_ptr<HighresTimer> timer_;
- uint64 running_time_;
- uint64 prev_uptime_seconds_;
- uint64 prev_cputime_seconds_;
- DISALLOW_COPY_AND_ASSIGN(PluginLogging);
-};
-
-} // namespace o3d
-
-#endif // O3D_PLUGIN_CROSS_PLUGIN_LOGGING_H_
diff --git a/o3d/plugin/cross/plugin_logging_test.cc b/o3d/plugin/cross/plugin_logging_test.cc
deleted file mode 100644
index a480604..0000000
--- a/o3d/plugin/cross/plugin_logging_test.cc
+++ /dev/null
@@ -1,228 +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 "plugin/cross/plugin_logging.h"
-#include <shlwapi.h>
-#ifdef OS_WIN
-#include <atlbase.h>
-#endif
-#include "statsreport/metrics.h"
-#include "statsreport/uploader.h"
-#ifdef OS_WIN
-#include "tests/common/win/testing_common.h"
-#endif
-
-// This mock class mimics the timer so that we don't actually have to wait for
-// the timer to timeout in the tests since we're not testing the timer here.
-class MockTimer : public HighresTimer {
- public:
- using HighresTimer::Start;
- MockTimer() : elapsed_ms_(0) {}
- virtual ULONGLONG GetElapsedMs() const;
- virtual void SetElapsedMs(const ULONGLONG ms);
-
- private:
- ULONGLONG elapsed_ms_;
-};
-
-ULONGLONG MockTimer::GetElapsedMs() const {
- return elapsed_ms_;
-}
-void MockTimer::SetElapsedMs(const ULONGLONG ms) {
- elapsed_ms_ = ms;
-}
-
-// This mock class mocks the stats uploader so we don't a) log false stats
-// and b) send hits to the server every time we run the tests.
-class MockStatsUploader : public stats_report::StatsUploader {
- public:
- MockStatsUploader() {}
- ~MockStatsUploader() {}
- virtual bool UploadMetrics(const char* extra_url_data,
- const char* user_agent,
- const char *content);
-};
-
-bool MockStatsUploader::UploadMetrics(const char* extra_url_data,
- const char* user_agent,
- const char *content) {
- // Return true to indicate that they were uploaded successfully.
- return true;
-}
-
-// This subclass is here just to make the protected methods public, so
-// the testing functions can call them.
-class MockPluginLogging : public o3d::PluginLogging {
- public:
- using o3d::PluginLogging::UpdateLogging;
- using o3d::PluginLogging::SetTimer;
- MockPluginLogging() : o3d::PluginLogging(),
- aggregate_metrics_success_(0),
- upload_metrics_success_(false) {}
- virtual bool ProcessMetrics(const bool exiting, const bool force_report);
- virtual void DoAggregateMetrics();
- virtual bool DoAggregateAndReportMetrics(const char* extra_url_arguments,
- const char* user_agent,
- const bool force_report);
- void SetAggregateMetricsSuccess(const int value);
- int AggregateMetricsSuccess();
- int UploadMetricsSuccess();
- private:
- int aggregate_metrics_success_;
- bool upload_metrics_success_;
-};
-
-bool MockPluginLogging::ProcessMetrics(const bool exiting,
- const bool force_report) {
- return true;
-}
-
-void MockPluginLogging::DoAggregateMetrics() {
- aggregate_metrics_success_ = 1;
-}
-
-bool MockPluginLogging::DoAggregateAndReportMetrics(
- const char* extra_url_arguments,
- const char* user_agent,
- const bool force_report) {
- aggregate_metrics_success_ = 2;
- MockStatsUploader stats_uploader;
- upload_metrics_success_ = TestableAggregateAndReportMetrics(
- extra_url_arguments,
- user_agent,
- force_report,
- &stats_uploader);
- return upload_metrics_success_;
-}
-
-void MockPluginLogging::SetAggregateMetricsSuccess(const int value) {
- aggregate_metrics_success_ = value;
-}
-
-int MockPluginLogging::AggregateMetricsSuccess() {
- return aggregate_metrics_success_;
-}
-
-int MockPluginLogging::UploadMetricsSuccess() {
- return upload_metrics_success_;
-}
-
-// Test fixture for the PluginLogging tests.
-class PluginLoggingTests : public testing::Test {
- protected:
- virtual void SetUp();
- virtual void TearDown();
-
- MockPluginLogging* plugin_logging() { return plugin_logging_; }
- void SetPluginLogging(MockPluginLogging* plugin_logging_in) {
- plugin_logging_ = plugin_logging_in;
- }
- MockTimer* mock_timer() { return mock_timer_; }
-
- private:
- MockPluginLogging* plugin_logging_;
- MockTimer* mock_timer_;
-};
-
-void PluginLoggingTests::SetUp() {
- HRESULT hr = CoInitialize(NULL);
- mock_timer_ = new MockTimer();
- plugin_logging_ = new MockPluginLogging();
- plugin_logging_->SetTimer(mock_timer_);
- stats_report::g_global_metrics.Initialize();
-}
-
-void PluginLoggingTests::TearDown() {
- // Only unitialize if a plugin_logging_ exists.
- // If it does not exist, it means we also never initialized.
- if (plugin_logging_) {
- delete plugin_logging_;
- stats_report::g_global_metrics.Uninitialize();
- }
-}
-
-// Test if the metric collection is properly initialized.
-TEST_F(PluginLoggingTests, InitializeMetricCollection) {
- EXPECT_TRUE(stats_report::g_global_metrics.initialized());
-}
-
-// Tests the PluginLogging's metric processing functions.
-TEST_F(PluginLoggingTests, ProcessMetricsTests) {
- EXPECT_FALSE(plugin_logging()->UpdateLogging());
- // NOTE: This time should be greater than the desired time.
- mock_timer()->SetElapsedMs(5 * 60 * 1000);
- EXPECT_TRUE(plugin_logging()->UpdateLogging());
-
- // This time should be less than the interval.
- mock_timer()->SetElapsedMs(1000);
- EXPECT_FALSE(plugin_logging()->UpdateLogging());
-}
-
-// Tests that the proper method to aggregate metrics was called.
-TEST_F(PluginLoggingTests, AggregateMetricsTests) {
- // Start by initializing the variable which tells us success or not.
- plugin_logging()->SetAggregateMetricsSuccess(0);
- // Pass false for "exiting" parameter to call AggregateMetrics.
- // Value does not matter for "force_report" for this testt so pass false.
- EXPECT_TRUE(plugin_logging()->PluginLogging::ProcessMetrics(true, false));
- EXPECT_EQ(plugin_logging()->AggregateMetricsSuccess(), 1);
-
- plugin_logging()->SetAggregateMetricsSuccess(0);
- // Pass true for "exiting" parameter to call AggregateAndReportMetrics.
- // Value does not matter for "force_report" for this testt so pass false.
- EXPECT_TRUE(plugin_logging()->PluginLogging::ProcessMetrics(false, false));
- EXPECT_EQ(plugin_logging()->AggregateMetricsSuccess(), 2);
-}
-
-// Check that the force_report boolean forces reporting of the metrics.
-TEST_F(PluginLoggingTests, CheckForceReport) {
- // Using this call rather than just calling TestableAggregateAndReportMetrics
- // directly because this is the stand alone call that we want to test.
- // Pass false for "exiting" since reporting does not happen otherwise.
- EXPECT_TRUE(plugin_logging()->PluginLogging::ProcessMetrics(false, true));
-}
-
-// Tests that when opt_in is turned on we create a logger and process metrics.
-TEST_F(PluginLoggingTests, CheckOptIn) {
- TearDown();
- SetPluginLogging(
- o3d::PluginLogging::CreateUsageStatsLogger<MockPluginLogging>(true));
- EXPECT_TRUE(plugin_logging());
-}
-
-// Tests that when opt_in is turned OFF we do not create a logger.
-TEST_F(PluginLoggingTests, CheckOptOut) {
- TearDown();
- SetPluginLogging(
- o3d::PluginLogging::CreateUsageStatsLogger<MockPluginLogging>(false));
- EXPECT_FALSE(plugin_logging());
-}
diff --git a/o3d/plugin/cross/plugin_main.h b/o3d/plugin/cross/plugin_main.h
deleted file mode 100644
index 8528571..0000000
--- a/o3d/plugin/cross/plugin_main.h
+++ /dev/null
@@ -1,38 +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 TOOLS_IDLGLUE_NG_O3D_GLUE_PLUGIN_MAIN_H_
-#define TOOLS_IDLGLUE_NG_O3D_GLUE_PLUGIN_MAIN_H_
-
-#include "plugin/cross/o3d_glue.h"
-
-#endif // TOOLS_IDLGLUE_NG_O3D_GLUE_PLUGIN_MAIN_H_
diff --git a/o3d/plugin/cross/plugin_metrics.h b/o3d/plugin/cross/plugin_metrics.h
deleted file mode 100644
index 0fcb5e6..0000000
--- a/o3d/plugin/cross/plugin_metrics.h
+++ /dev/null
@@ -1,152 +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.
- */
-
-
-// Declares the system metrics used by the plugin.
-
-#ifndef O3D_PLUGIN_CROSS_PLUGIN_METRICS_H_
-#define O3D_PLUGIN_CROSS_PLUGIN_METRICS_H_
-
-#include "statsreport/metrics.h"
-
-namespace o3d {
-// NOTE: DO NOT REORDER THESE ENUMS!
-// This enum will be used by stats analysis code as well and they must stay in
-// sync. When this stat is reported, it only reports an integer that we compare
-// against this enum so the order is very important.
-// We start at 1, as 0 is reserved for "no value", ie we didn't check.
-enum BrowserTypeName {
- BROWSER_NAME_UNKNOWN = 1,
- BROWSER_NAME_CHROME,
- BROWSER_NAME_SAFARI,
- BROWSER_NAME_FIREFOX,
- BROWSER_NAME_MSIE,
- BROWSER_NAME_OPERA,
- BROWSER_NAME_CAMINO,
- BROWSER_NAME_OMNIWEB
-};
-
-// This enum is simply for easy viewing of data
-enum SystemType {
- SYSTEM_NAME_WIN = 1,
- SYSTEM_NAME_MAC,
- SYSTEM_NAME_LINUX
-};
-
-// User operating system
-DECLARE_METRIC_integer(system_type);
-
-DECLARE_METRIC_integer(windows_major_version);
-DECLARE_METRIC_integer(windows_minor_version);
-DECLARE_METRIC_integer(windows_sp_major_version);
-DECLARE_METRIC_integer(windows_sp_minor_version);
-
-DECLARE_METRIC_integer(mac_major_version);
-DECLARE_METRIC_integer(mac_minor_version);
-DECLARE_METRIC_integer(mac_bugfix_version);
-
-DECLARE_METRIC_integer(gl_major_version);
-DECLARE_METRIC_integer(gl_minor_version);
-DECLARE_METRIC_integer(gl_hlsl_major_version);
-DECLARE_METRIC_integer(gl_hlsl_minor_version);
-
-
-DECLARE_METRIC_bool(POW2_texture_caps);
-DECLARE_METRIC_bool(NONPOW2CONDITIONAL_texture_caps);
-
-// User GPU
-DECLARE_METRIC_integer(gpu_vendor_id);
-DECLARE_METRIC_integer(gpu_device_id);
-DECLARE_METRIC_integer(gpu_driver_major_version);
-DECLARE_METRIC_integer(gpu_driver_minor_version);
-DECLARE_METRIC_integer(gpu_driver_bugfix_version);
-DECLARE_METRIC_integer(gpu_vram_size);
-DECLARE_METRIC_bool(direct3d_available);
-
-
-// Shader versions
-DECLARE_METRIC_integer(pixel_shader_main_version);
-DECLARE_METRIC_integer(pixel_shader_sub_version);
-DECLARE_METRIC_integer(vertex_shader_main_version);
-DECLARE_METRIC_integer(vertex_shader_sub_version);
-
-// Browser
-DECLARE_METRIC_integer(browser_type);
-DECLARE_METRIC_integer(browser_major_version);
-DECLARE_METRIC_integer(browser_minor_version);
-DECLARE_METRIC_integer(browser_bugfix_version);
-
-// Running time for instance of plugin
-DECLARE_METRIC_count(uptime_seconds);
-DECLARE_METRIC_count(cpu_time_seconds);
-DECLARE_METRIC_timing(running_time_seconds);
-
-// Crashes
-// How many times the plugin has crashed. Not all crashes may be reported.
-DECLARE_METRIC_count(crashes_total);
-DECLARE_METRIC_count(crashes_uploaded);
-DECLARE_METRIC_count(out_of_memory_total);
-
-// Bluescreens
-// How many times has the plugin caused a bluescreen of death
-DECLARE_METRIC_count(bluescreens_total);
-
-// D3D Caps
-DECLARE_METRIC_integer(d3d_devcaps);
-DECLARE_METRIC_integer(d3d_misccaps);
-DECLARE_METRIC_integer(d3d_rastercaps);
-DECLARE_METRIC_integer(d3d_zcmpcaps);
-DECLARE_METRIC_integer(d3d_srcblendcaps);
-DECLARE_METRIC_integer(d3d_dstblendcaps);
-DECLARE_METRIC_integer(d3d_alphacaps);
-DECLARE_METRIC_integer(d3d_texcaps);
-DECLARE_METRIC_integer(d3d_texfiltercaps);
-DECLARE_METRIC_integer(d3d_cubetexfiltercaps);
-DECLARE_METRIC_integer(d3d_texaddrcaps);
-DECLARE_METRIC_integer(d3d_linecaps);
-DECLARE_METRIC_integer(d3d_stencilcaps);
-DECLARE_METRIC_integer(d3d_texopcaps);
-DECLARE_METRIC_integer(d3d_vs20caps);
-DECLARE_METRIC_integer(d3d_vs20_dynflowctrldepth);
-DECLARE_METRIC_integer(d3d_vs20_numtemps);
-DECLARE_METRIC_integer(d3d_vs20_staticflowctrldepth);
-DECLARE_METRIC_integer(d3d_ps20caps);
-DECLARE_METRIC_integer(d3d_ps20_dynflowctrldepth);
-DECLARE_METRIC_integer(d3d_ps20_numtemps);
-DECLARE_METRIC_integer(d3d_ps20_staticflowctrldepth);
-DECLARE_METRIC_integer(d3d_ps20_numinstrslots);
-
-// Installs and uninstalls
-// TODO: Will likely need to get from Google Update
-
-} // namespace o3d
-
-#endif // O3D_PLUGIN_CROSS_PLUGIN_METRICS_H_
diff --git a/o3d/plugin/cross/stream_manager.cc b/o3d/plugin/cross/stream_manager.cc
deleted file mode 100644
index 783b114..0000000
--- a/o3d/plugin/cross/stream_manager.cc
+++ /dev/null
@@ -1,356 +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 "plugin/cross/stream_manager.h"
-
-#include <algorithm>
-#include <map>
-
-#include "base/logging.h"
-#include "plugin/cross/o3d_glue.h"
-#include "third_party/nixysa/static_glue/npapi/common.h"
-
-namespace glue {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-StreamManager::StreamManager(NPP plugin_instance)
- : plugin_instance_(plugin_instance) {
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-StreamManager::~StreamManager() {
- // If the destructor gets called while streams are in mid-flight then delete
- // them here to make sure we can garbage collect cleanly.
- std::vector<NPDownloadStream *>::iterator it;
- for (it = entries_.begin(); it < entries_.end(); ++it) {
- delete (*it);
- }
- entries_.clear();
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-DownloadStream *StreamManager::LoadURL(const std::string &url,
- NewStreamCallback *new_stream_callback,
- WriteReadyCallback *write_ready_callback,
- WriteCallback *write_callback,
- FinishedCallback *finished_callback,
- uint16 stream_type) {
- DCHECK(finished_callback != NULL);
-
- NPDownloadStream *entry = new NPDownloadStream(url,
- "",
- stream_type,
- plugin_instance_,
- new_stream_callback,
- write_ready_callback,
- write_callback,
- finished_callback);
-
- GLUE_PROFILE_START(plugin_instance_, "geturlnotify");
- // NPN_GetURLNotify may call-back into the plug-in before returning, so
- // add the download stream entry before making the call.
- entries_.push_back(entry);
- NPError ret = NPN_GetURLNotify(plugin_instance_, url.c_str(), NULL, entry);
- GLUE_PROFILE_STOP(plugin_instance_, "geturlnotify");
- if (ret != NPERR_NO_ERROR) {
- // If the operation failed, it's possible that the browser hosting
- // environment did not call the appropriate notify routines which
- // clean up the entries_ stack. We check if the entry is still
- // at the top, and delete it here.
- if (!entries_.empty() && entries_.back() == entry) {
- entries_.pop_back();
- // NOTE: Should we run the finished_callback here ?
- delete entry;
- entry = NULL;
- }
- }
- return entry;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool StreamManager::CheckEntry(NPDownloadStream *entry) {
- std::vector<NPDownloadStream *>::iterator it =
- std::find(entries_.begin(), entries_.end(), entry);
- return it != entries_.end();
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool StreamManager::NewStream(NPStream *stream, uint16 *stype) {
- NPDownloadStream *entry = static_cast<NPDownloadStream*>(stream->notifyData);
- if (!CheckEntry(entry)) {
- // We got a new stream, but we don't know about it.
- return false;
- }
- return entry->NewStream(stream, stype);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool StreamManager::DestroyStream(NPStream *stream, NPReason reason) {
- NPDownloadStream *entry = static_cast<NPDownloadStream*>(stream->notifyData);
- if (!CheckEntry(entry)) {
- // We don't know about this stream.
- return false;
- }
- DCHECK_EQ(stream, entry->GetStream());
-
- return entry->DestroyStream(reason);
-}
-
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool StreamManager::SetStreamFile(NPStream *stream, const char *filename) {
- NPDownloadStream *entry = static_cast<NPDownloadStream*>(stream->notifyData);
- if (!CheckEntry(entry)) {
- // We don't know about this stream.
- return false;
- }
- DCHECK_EQ(stream, entry->GetStream());
-
- return entry->SetStreamFile(filename);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool StreamManager::URLNotify(const char *url,
- NPReason reason,
- void *notifyData) {
- NPDownloadStream *entry = static_cast<NPDownloadStream *>(notifyData);
- if (!CheckEntry(entry)) {
- // We don't know about this stream.
- return false;
- }
-
- std::vector<NPDownloadStream *>::iterator it =
- std::find(entries_.begin(), entries_.end(), entry);
- DCHECK(it != entries_.end());
- entries_.erase(it);
-
- bool result = entry->URLNotify(reason);
- delete entry;
- return result;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-int32 StreamManager::WriteReady(NPStream *stream) {
- NPDownloadStream *entry = static_cast<NPDownloadStream*>(stream->notifyData);
- if (!CheckEntry(entry)) {
- // We don't know about this stream.
- return 0;
- }
-
- return entry->WriteReady();
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-int32 StreamManager::Write(NPStream *stream,
- int32 offset,
- int32 len,
- void *buffer) {
- NPDownloadStream *entry = static_cast<NPDownloadStream*>(stream->notifyData);
- if (!CheckEntry(entry)) {
- // We don't know about this stream.
- return 0;
- }
-
- return entry->Write(offset, len, buffer);
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// DownloadStream implementation
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-StreamManager::NPDownloadStream::~NPDownloadStream() {
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-std::string StreamManager::NPDownloadStream::GetURL() {
- return url_;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-std::string StreamManager::NPDownloadStream::GetCachedFile() {
- return file_;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-DownloadStream::State StreamManager::NPDownloadStream::GetState() {
- return state_;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-int StreamManager::NPDownloadStream::GetReceivedByteCount() {
- return bytes_received_;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-size_t StreamManager::NPDownloadStream::GetStreamLength() {
- return stream_ ? stream_->end : 0;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-void StreamManager::NPDownloadStream::Cancel() {
- NPN_DestroyStream(plugin_instance_, stream_, NPRES_USER_BREAK);
- state_ = STREAM_FINISHED;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-// NPDownloadStream implementation
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-typedef std::map<std::string, std::string> StringMap;
-
-// Extracts headers from the browser-returned header string, as a name->value
-// map.
-static StringMap ExtractHeaders(const char *header_string) {
- using std::string;
- StringMap map;
- if (!header_string) return map;
- string headers = header_string;
- // Doc says headers as returned by the browser are LF-terminated, including
- // the last one.
- // It's unclear if they are rewritten by the browser to be in a "canonical"
- // form (i.e. single-line, no extra space etc.). We currently assume that
- // they are.
- // TODO: verify this, and/or implement correct parsing to handle RFC
- // 1945/2616 parsing.
- string::size_type index = 0;
- while (index < headers.size()) {
- string::size_type eol = std::min(headers.size(), headers.find("\n", index));
- string line = headers.substr(index, eol-index);
- string::size_type separator = line.find(":");
- if (separator != string::npos) {
- string key = line.substr(0, separator);
- string value;
- if (separator + 1 < line.size()) {
- string::size_type value_index =
- line.find_first_not_of(" \t", separator + 1);
- if (value_index != string::npos)
- value = line.substr(value_index);
- }
- map[key] = value;
- }
- index = eol + 1;
- }
-
- return map;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool StreamManager::NPDownloadStream::NewStream(NPStream *new_stream,
- uint16 *stype) {
- stream_ = new_stream;
- state_ = DownloadStream::STREAM_STARTED;
- *stype = stream_type_;
-
- // callback if provided
- if (new_stream_callback_.get()) {
- new_stream_callback_->Run(this);
- }
-
- return true;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool StreamManager::NPDownloadStream::DestroyStream(NPReason reason) {
- stream_ = NULL;
- state_ = DownloadStream::STREAM_FINISHED;
- return true;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool StreamManager::NPDownloadStream::SetStreamFile(const char *filename) {
- if (finished_callback_.get()) {
- StringMap header_map = ExtractHeaders(stream_->headers);
- std::string mime_type = header_map["Content-Type"];
- file_ = filename;
- // On success, run the finished_callback.
- if (file_.size() != 0) {
- // finished_callback should only be called once.
- finished_callback_->Run(this, true, file_, mime_type);
- finished_callback_.reset(NULL);
- }
- }
-
- return true;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-bool StreamManager::NPDownloadStream::URLNotify(NPReason reason) {
- if (finished_callback_.get()) {
- // On failure, run the finished_callback.
- // Note that the streaming case (NP_NORMAL) does not get a file
- // so we can't check its size
- if ((reason != NPRES_DONE) ||
- (stream_type_ != NP_NORMAL && file_.empty())) {
- // finished_callback should only be called once.
- finished_callback_->Run(this, false, "", "");
- finished_callback_.reset(NULL);
- }
-
- // Finished callback for streaming case
- // where SetStreamFile() is not called
- if (reason == NPRES_DONE && stream_type_ == NP_NORMAL) {
- finished_callback_->Run(this, true, "", "");
- finished_callback_.reset(NULL);
- }
- }
-
- new_stream_callback_.reset(NULL);
- write_ready_callback_.reset(NULL);
- write_callback_.reset(NULL);
-
- return true;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-int32 StreamManager::NPDownloadStream::WriteReady() {
- if (write_ready_callback_.get()) {
- return write_ready_callback_->Run(this);
- }
-
- return 4096;
-}
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-int32 StreamManager::NPDownloadStream::Write(int32 offset,
- int32 len,
- void *buffer) {
- if (write_callback_.get()) {
- int32 n = write_callback_->Run(this, offset, len, buffer);
- bytes_received_ += n;
- return n;
- }
-
- return len;
-}
-
-} // namespace glue
diff --git a/o3d/plugin/cross/stream_manager.h b/o3d/plugin/cross/stream_manager.h
deleted file mode 100644
index f7c6723..0000000
--- a/o3d/plugin/cross/stream_manager.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.
- */
-
-
-#ifndef EXPERIMENTAL_O3D_O3DPLUGIN_AUTOGEN_O3D_GLUE_STREAM_MANAGER_H_
-#define EXPERIMENTAL_O3D_O3DPLUGIN_AUTOGEN_O3D_GLUE_STREAM_MANAGER_H_
-
-#include <npapi.h>
-#include <string>
-#include <vector>
-#include "base/scoped_ptr.h"
-#include "core/cross/callback.h"
-#include "plugin/cross/download_stream.h"
-
-namespace glue {
-
-// Stream manager class, to help managing asynchronous loading of URLs into
-// files.
-class StreamManager {
- public:
- // TODO : get rid of these horrible callback objects
- // and use an interface instead
- typedef o3d::Callback1<DownloadStream*> NewStreamCallback;
-
- typedef o3d::Callback4<DownloadStream*,
- bool,
- const std::string &,
- const std::string &> FinishedCallback;
-
- // The signature for these callbacks corresponds to the NPP_WriteReady()
- // and NPP_Write() calls
- typedef o3d::ResultCallback1<int32, DownloadStream*> WriteReadyCallback;
-
- typedef o3d::ResultCallback4<int32,
- DownloadStream*,
- int32,
- int32,
- void*> WriteCallback;
-
- explicit StreamManager(NPP plugin_instance);
- ~StreamManager();
-
- // Loads URL into a file, calls finished_callback->Run(success, filename)
- // when done.
- // returns a DownloadStream object (or NULL) if error
- // filename is the name of the file where the contents of the URL are
- // stored.
- // LoadURL() takes ownership of new_stream_callback, write_ready_callback,
- // write_callback, and callback: They will be deleted once the stream has
- // completed.
- DownloadStream *LoadURL(const std::string &url,
- NewStreamCallback *new_stream_callback,
- WriteReadyCallback *write_ready_callback,
- WriteCallback *write_callback,
- FinishedCallback *callback,
- uint16 stream_type);
-
- // Manages the NPP_NewStream callback.
- bool NewStream(NPStream *stream, uint16 *stype);
- // Manages the NPP_DestroyStream callback.
- bool DestroyStream(NPStream *stream, NPReason reason);
- // Manages the NPP_StreamAsFile callback.
- bool SetStreamFile(NPStream *stream, const char *filename);
- // Manages the NPP_URLNotify callback.
- bool URLNotify(const char *url, NPReason reason, void *notifyData);
-
- // Continuous streaming support
- int32 WriteReady(NPStream *stream);
- int32 Write(NPStream *stream, int32 offset, int32 len, void *buffer);
-
- private:
- class NPDownloadStream : public DownloadStream {
- public:
- NPDownloadStream(const std::string &url,
- const std::string &file,
- uint16 stream_type,
- NPP plugin_instance,
- NewStreamCallback *new_stream_callback,
- WriteReadyCallback *write_ready_callback,
- WriteCallback *write_callback,
- FinishedCallback *callback)
- : url_(url),
- file_(file),
- stream_type_(stream_type),
- plugin_instance_(plugin_instance),
- stream_(NULL),
- new_stream_callback_(new_stream_callback),
- write_ready_callback_(write_ready_callback),
- write_callback_(write_callback),
- finished_callback_(callback),
- bytes_received_(0),
- state_(STREAM_REQUESTED) {}
-
- virtual ~NPDownloadStream();
-
- // DownloadStream interface
- virtual std::string GetURL();
- virtual std::string GetCachedFile();
- virtual State GetState();
- virtual int GetReceivedByteCount();
- virtual size_t GetStreamLength();
- virtual void Cancel();
-
- // NPAPI stream stuff
- NPStream *GetStream() const { return stream_; }
- bool NewStream(NPStream *new_stream, uint16 *stype);
- bool DestroyStream(NPReason reason);
- bool SetStreamFile(const char *filename);
- bool URLNotify(NPReason reason);
- int32 WriteReady();
- int32 Write(int32 offset, int32 len, void *buffer);
-
-
- private:
- std::string url_;
- std::string file_;
-
- // stream type (as file or continuous stream)
- uint16 stream_type_;
-
- NPP plugin_instance_;
- NPStream *stream_;
-
- // callbacks
- scoped_ptr<NewStreamCallback> new_stream_callback_;
- scoped_ptr<WriteReadyCallback> write_ready_callback_;
- scoped_ptr<WriteCallback> write_callback_;
- scoped_ptr<FinishedCallback> finished_callback_;
-
- int bytes_received_;
- State state_;
- };
- bool CheckEntry(NPDownloadStream *entry);
-
- NPP plugin_instance_;
- std::vector<NPDownloadStream *> entries_;
-};
-
-} // namespace glue
-
-#endif // EXPERIMENTAL_O3D_O3DPLUGIN_AUTOGEN_O3D_GLUE_STREAM_MANAGER_H_
diff --git a/o3d/plugin/cross/texture_static_glue.cc b/o3d/plugin/cross/texture_static_glue.cc
deleted file mode 100644
index a3da6ef..0000000
--- a/o3d/plugin/cross/texture_static_glue.cc
+++ /dev/null
@@ -1,606 +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 <vector>
-#include "core/cross/pointer_utils.h"
-#include "core/cross/error.h"
-#include "core/cross/math_utilities.h"
-#include "core/cross/texture.h"
-#include "core/cross/image_utils.h"
-
-namespace {
-
-void SetRectCheck(o3d::Texture* self,
- void* data,
- int pitch,
- int destination_x,
- int destination_y,
- int texture_width,
- int texture_height,
- int source_width,
- int source_height,
- const std::vector<float>& values) {
- unsigned num_components;
- unsigned swizzle[4] = {2, 1, 0, 3};
- switch (self->format()) {
- case o3d::Texture::XRGB8:
- num_components = 3;
- break;
- case o3d::Texture::R32F:
- swizzle[0] = 0;
- num_components = 1;
- break;
- case o3d::Texture::ARGB8:
- case o3d::Texture::ABGR16F:
- num_components = 4;
- break;
- case o3d::Texture::ABGR32F: {
- num_components = 4;
- const o3d::Texture::RGBASwizzleIndices& indices =
- self->GetABGR32FSwizzleIndices();
- for (int ii = 0; ii < 4; ++ii) {
- swizzle[ii] = indices[ii];
- }
- break;
- }
- default:
- DCHECK(false);
- return;
- }
-
- // clip
- int source_x = 0;
- int source_y = 0;
- int copy_width = source_width;
- int copy_height = source_height;
-
- if (destination_x < 0) {
- copy_width += destination_x;
- source_x -= destination_x;
- destination_x = 0;
- }
- if (destination_x + copy_width > static_cast<int>(texture_width)) {
- copy_width -= destination_x + copy_width - texture_width;
- }
-
- if (destination_y < 0) {
- copy_height += destination_y;
- source_y -= destination_y;
- destination_y = 0;
- }
- if (destination_y + copy_height > static_cast<int>(texture_height)) {
- copy_height -= destination_y + copy_height - texture_height;
- }
-
- if (copy_width <= 0 || copy_height <= 0) {
- return;
- }
-
- const float* source =
- &values[0] +
- (source_y * source_width + source_x) * num_components;
- unsigned source_stride = (source_width - copy_width) * num_components;
- switch (self->format()) {
- case o3d::Texture::ABGR16F: {
- uint16* dest_line =
- static_cast<uint16*>(data) +
- (destination_y * texture_width + destination_x) * num_components;
- for (; copy_height > 0; --copy_height) {
- uint16* destination = dest_line;
- for (int xx = 0; xx < copy_width; ++xx) {
- for (unsigned element = 0; element < num_components; ++element) {
- destination[element] = Vectormath::Aos::FloatToHalf(
- source[swizzle[element]]);
- }
- destination += num_components;
- source += num_components;
- }
- dest_line = o3d::AddPointerOffset<uint16*>(dest_line, pitch);
- source += source_stride;
- }
- break;
- }
- case o3d::Texture::R32F:
- case o3d::Texture::ABGR32F: {
- float* dest_line =
- static_cast<float*>(data) +
- (destination_y * texture_width + destination_x) * num_components;
- for (; copy_height > 0; --copy_height) {
- float* destination = dest_line;
- for (int xx = 0; xx < copy_width; ++xx) {
- for (unsigned element = 0; element < num_components; ++element) {
- destination[element] = source[swizzle[element]];
- }
- destination += num_components;
- source += num_components;
- }
- dest_line = o3d::AddPointerOffset<float*>(dest_line, pitch);
- source += source_stride;
- }
- break;
- }
- default: {
- uint8* dest_line =
- static_cast<uint8*>(data) +
- (destination_y * texture_width + destination_x) * 4;
- for (; copy_height > 0; --copy_height) {
- uint8* destination = dest_line;
- for (int xx = 0; xx < copy_width; ++xx) {
- destination[0] = static_cast<unsigned char>(
- source[swizzle[0]] * 255.0f);
- destination[1] = static_cast<unsigned char>(
- source[swizzle[1]] * 255.0f);
- destination[2] = static_cast<unsigned char>(
- source[swizzle[2]] * 255.0f);
- destination[3] = (num_components == 4) ?
- static_cast<unsigned char>(source[swizzle[3]] * 255.0f) : 255;
- destination += 4;
- source += num_components;
- }
- dest_line = o3d::AddPointerOffset<uint8*>(dest_line, pitch);
- source += source_stride;
- }
- break;
- }
- }
-}
-
-void SetRectCheck2D(o3d::Texture2D* self,
- int level,
- int destination_x,
- int destination_y,
- int source_width,
- const std::vector<float>& values,
- bool check_needed) {
- if (level < 0 || level >= self->levels()) {
- O3D_ERROR(self->service_locator())
- << "level (" << level << " out of range";
- return;
- }
- if (values.empty() || source_width <= 0) {
- return;
- }
- unsigned num_values = values.size();
- unsigned texture_width = std::max(self->width() >> level, 1);
- unsigned texture_height = std::max(self->height() >> level, 1);
- unsigned num_components;
- switch (self->format()) {
- case o3d::Texture::XRGB8:
- num_components = 3;
- break;
- case o3d::Texture::R32F:
- num_components = 1;
- break;
- case o3d::Texture::ARGB8:
- case o3d::Texture::ABGR16F:
- num_components = 4;
- break;
- case o3d::Texture::ABGR32F: {
- num_components = 4;
- break;
- }
- default:
- O3D_ERROR(self->service_locator())
- << "Texture::Set not supported for this type of texture";
- return;
- }
- if (num_values % num_components != 0) {
- O3D_ERROR(self->service_locator())
- << "The number of elements passed in must be a multiple of "
- << num_components;
- }
- unsigned num_elements = num_values / num_components;
- if (num_elements % source_width != 0) {
- O3D_ERROR(self->service_locator())
- << "The number of elements passed in must be a multiple of the "
- << "width";
- return;
- }
- unsigned source_height = num_elements / source_width;
- if (check_needed) {
- unsigned needed = num_components * texture_width * texture_height;
- if (num_values != needed) {
- O3D_ERROR(self->service_locator())
- << "needed " << needed << " values but " << num_values
- << " passed in.";
- return;
- }
- }
- o3d::Texture2D::LockHelper helper(self, level, o3d::Texture::kWriteOnly);
- void* data = helper.GetData();
- if (!data) {
- O3D_ERROR(self->service_locator()) << "could not lock texture";
- return;
- }
-
- SetRectCheck(self, data, helper.pitch(),
- destination_x, destination_y,
- texture_width, texture_height,
- source_width, source_height,
- values);
-}
-
-void SetRectCheckCUBE(o3d::TextureCUBE* self,
- o3d::TextureCUBE::CubeFace face,
- int level,
- int destination_x,
- int destination_y,
- int source_width,
- const std::vector<float>& values,
- bool check_needed) {
- if (level < 0 || level >= self->levels()) {
- O3D_ERROR(self->service_locator())
- << "level (" << level << " out of range";
- return;
- }
- if (values.empty() || source_width <= 0) {
- return;
- }
- unsigned num_values = values.size();
- unsigned texture_width = std::max(self->edge_length() >> level, 1);
- unsigned texture_height = texture_width;
- unsigned num_components;
- switch (self->format()) {
- case o3d::Texture::XRGB8:
- num_components = 3;
- break;
- case o3d::Texture::R32F:
- num_components = 1;
- break;
- case o3d::Texture::ARGB8:
- case o3d::Texture::ABGR16F:
- num_components = 4;
- break;
- case o3d::Texture::ABGR32F: {
- num_components = 4;
- break;
- }
- default:
- O3D_ERROR(self->service_locator())
- << "Texture::Set not supported for this type of texture";
- return;
- }
- if (num_values % num_components != 0) {
- O3D_ERROR(self->service_locator())
- << "The number of elements passed in must be a multiple of "
- << num_components;
- }
- unsigned num_elements = num_values / num_components;
- if (num_elements % source_width != 0) {
- O3D_ERROR(self->service_locator())
- << "The number of elements passed in must be a multiple of the "
- << "width";
- return;
- }
- unsigned source_height = num_elements / source_width;
- if (check_needed) {
- unsigned needed = num_components * texture_width * texture_height;
- if (num_values != needed) {
- O3D_ERROR(self->service_locator())
- << "needed " << needed << " values but " << num_values
- << " passed in.";
- return;
- }
- }
- o3d::TextureCUBE::LockHelper helper(
- self, face, level, o3d::Texture::kWriteOnly);
- void* data = helper.GetData();
- if (!data) {
- O3D_ERROR(self->service_locator()) << "could not lock texture";
- return;
- }
-
- SetRectCheck(self, data, helper.pitch(),
- destination_x, destination_y,
- texture_width, texture_height,
- source_width, source_height,
- values);
-}
-
-// Assumes dst points to width * height * num_components floats.
-void GetRect(o3d::Texture* self,
- const void* src_data,
- int src_pitch,
- int x,
- int y,
- int width,
- int height,
- float* dst) {
- unsigned num_components;
- unsigned swizzle[4] = {2, 1, 0, 3};
- switch (self->format()) {
- case o3d::Texture::XRGB8:
- num_components = 3;
- break;
- case o3d::Texture::R32F:
- swizzle[0] = 0;
- num_components = 1;
- break;
- case o3d::Texture::ARGB8:
- case o3d::Texture::ABGR16F:
- num_components = 4;
- break;
- case o3d::Texture::ABGR32F: {
- num_components = 4;
- const o3d::Texture::RGBASwizzleIndices& indices =
- self->GetABGR32FSwizzleIndices();
- for (int ii = 0; ii < 4; ++ii) {
- swizzle[ii] = indices[ii];
- }
- break;
- }
- default:
- DCHECK(false);
- return;
- }
-
- switch (self->format()) {
- case o3d::Texture::ABGR16F: {
- uint16* src_line = o3d::PointerFromVoidPointer<uint16*>(
- src_data,
- (y * src_pitch)) + x * num_components;
- for (; height > 0; --height) {
- uint16* src = src_line;
- for (int xx = 0; xx < width; ++xx) {
- for (unsigned element = 0; element < num_components; ++element) {
- dst[swizzle[element]] = Vectormath::Aos::HalfToFloat(src[element]);
- }
- dst += num_components;
- src += num_components;
- }
- src_line = o3d::AddPointerOffset<uint16*>(src_line, src_pitch);
- }
- break;
- }
- case o3d::Texture::R32F:
- case o3d::Texture::ABGR32F: {
- float* src_line = o3d::PointerFromVoidPointer<float*>(
- src_data,
- (y * src_pitch)) + x * num_components;
- for (; height > 0; --height) {
- float* src = src_line;
- for (int xx = 0; xx < width; ++xx) {
- for (unsigned element = 0; element < num_components; ++element) {
- dst[swizzle[element]] = src[element];
- }
- dst += num_components;
- src += num_components;
- }
- src_line = o3d::AddPointerOffset<float*>(src_line, src_pitch);
- }
- break;
- }
- default: {
- uint8* src_line = o3d::PointerFromVoidPointer<uint8*>(
- src_data,
- (y * src_pitch)) + x * num_components;
- for (; height > 0; --height) {
- uint8* src = src_line;
- for (int xx = 0; xx < width; ++xx) {
- dst[swizzle[0]] = static_cast<float>(src[0]) / 255.0f;
- dst[swizzle[1]] = static_cast<float>(src[1]) / 255.0f;
- dst[swizzle[2]] = static_cast<float>(src[2]) / 255.0f;
- if (num_components == 4) {
- dst[swizzle[3]] = static_cast<float>(src[3]) / 255.0f;
- }
- dst += num_components;
- src += 4;
- }
- src_line = o3d::AddPointerOffset<uint8*>(src_line, src_pitch);
- }
- break;
- }
- }
-}
-
-} // anonymous namespace
-
-namespace glue {
-namespace namespace_o3d {
-namespace class_Texture2D {
-
-void userglue_method_SetRect(o3d::Texture2D* self,
- int level,
- int destination_x,
- int destination_y,
- int source_width,
- const std::vector<float>& values) {
- SetRectCheck2D(self,
- level,
- destination_x,
- destination_y,
- source_width,
- values,
- false);
-}
-void userglue_method_Set(o3d::Texture2D* self,
- int level,
- const std::vector<float>& values) {
- SetRectCheck2D(
- self, level, 0, 0,
- o3d::image::ComputeMipDimension(level, self->width()),
- values, true);
-}
-std::vector<float> userglue_method_GetRect(o3d::Texture2D* self,
- int level,
- int x,
- int y,
- int width,
- int height) {
- std::vector<float> empty;
- if (level < 0 || level >= self->levels()) {
- O3D_ERROR(self->service_locator())
- << "level (" << level << " out of range";
- return empty;
- }
- if (width <= 0 || height <= 0) {
- O3D_ERROR(self->service_locator())
- << "width and height must be positive";
- return empty;
- }
-
- int mip_width =
- static_cast<int>(o3d::image::ComputeMipDimension(level, self->width()));
- int mip_height =
- static_cast<int>(o3d::image::ComputeMipDimension(level, self->height()));
-
- if (x < 0 || x + width > mip_width || y < 0 || y + height > mip_height) {
- O3D_ERROR(self->service_locator()) << "area out of range";
- return empty;
- }
-
- unsigned num_components;
- switch (self->format()) {
- case o3d::Texture::XRGB8:
- num_components = 3;
- break;
- case o3d::Texture::R32F:
- num_components = 1;
- break;
- case o3d::Texture::ARGB8:
- case o3d::Texture::ABGR16F:
- num_components = 4;
- break;
- case o3d::Texture::ABGR32F: {
- num_components = 4;
- break;
- }
- default:
- O3D_ERROR(self->service_locator())
- << "Texture::Set not supported for this type of texture";
- return empty;
- }
- o3d::Texture2D::LockHelper helper(self, level, o3d::Texture::kReadOnly);
- void* data = helper.GetData();
- if (!data) {
- O3D_ERROR(self->service_locator()) << "could not lock texture";
- return empty;
- }
-
- std::vector<float> values(width * height * num_components, 0);
- GetRect(self, data, helper.pitch(), x, y, width, height, &values[0]);
- return values;
-}
-
-} // namespace class_Texture2D
-
-namespace class_TextureCUBE {
-
-void userglue_method_SetRect(o3d::TextureCUBE* self,
- o3d::TextureCUBE::CubeFace face,
- int level,
- int destination_x,
- int destination_y,
- int source_width,
- const std::vector<float>& values) {
- SetRectCheckCUBE(self,
- face,
- level,
- destination_x,
- destination_y,
- source_width,
- values,
- false);
-}
-void userglue_method_Set(o3d::TextureCUBE* self,
- o3d::TextureCUBE::CubeFace face,
- int level,
- const std::vector<float>& values) {
- SetRectCheckCUBE(self, face, level, 0, 0,
- o3d::image::ComputeMipDimension(level, self->edge_length()),
- values, true);
-}
-std::vector<float> userglue_method_GetRect(o3d::TextureCUBE* self,
- o3d::TextureCUBE::CubeFace face,
- int level,
- int x,
- int y,
- int width,
- int height) {
- std::vector<float> empty;
- if (level < 0 || level >= self->levels()) {
- O3D_ERROR(self->service_locator())
- << "level (" << level << " out of range";
- return empty;
- }
- if (width <= 0 || height <= 0) {
- O3D_ERROR(self->service_locator())
- << "width and height must be positive";
- return empty;
- }
-
- int mip_length = static_cast<int>(o3d::image::ComputeMipDimension(
- level, self->edge_length()));
-
- if (x < 0 || x + width > mip_length || y < 0 || y + height > mip_length) {
- O3D_ERROR(self->service_locator()) << "area out of range";
- return empty;
- }
-
- unsigned num_components;
- switch (self->format()) {
- case o3d::Texture::XRGB8:
- num_components = 3;
- break;
- case o3d::Texture::R32F:
- num_components = 1;
- break;
- case o3d::Texture::ARGB8:
- case o3d::Texture::ABGR16F:
- num_components = 4;
- break;
- case o3d::Texture::ABGR32F: {
- num_components = 4;
- break;
- }
- default:
- O3D_ERROR(self->service_locator())
- << "Texture::Set not supported for this type of texture";
- return empty;
- }
- o3d::TextureCUBE::LockHelper helper(
- self, face, level, o3d::Texture::kReadOnly);
- void* data = helper.GetData();
- if (!data) {
- O3D_ERROR(self->service_locator()) << "could not lock texture";
- return empty;
- }
-
- std::vector<float> values(width * height * num_components, 0);
- GetRect(self, data, helper.pitch(), x, y, width, height, &values[0]);
- return values;
-}
-
-} // namespace class_TextureCUBE
-
-} // namespace namespace_o3d
-} // namespace glue
-
diff --git a/o3d/plugin/cross/whitelist.cc b/o3d/plugin/cross/whitelist.cc
deleted file mode 100644
index 7ec78c3..0000000
--- a/o3d/plugin/cross/whitelist.cc
+++ /dev/null
@@ -1,213 +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 "plugin/cross/whitelist.h"
-
-#include <string>
-
-#include "base/basictypes.h"
-#include "base/logging.h"
-
-namespace o3d {
-
-#if !defined(O3D_PLUGIN_DOMAIN_WHITELIST) && \
- !defined(O3D_PLUGIN_ENABLE_FULLSCREEN_MSG)
-#error "No whitelist and no fullscreen message is a security vulnerability"
-#endif
-
-#ifdef O3D_PLUGIN_DOMAIN_WHITELIST
-
-static const char *const kDomainWhitelist[] = {
- // This macro contains the comma-separated string literals for the whitelist
- O3D_PLUGIN_DOMAIN_WHITELIST
-};
-
-static const char kHttpProtocol[] = "http://";
-static const char kHttpsProtocol[] = "https://";
-
-// For testing purposes assume local files valid too.
-static const char kLocalFileUrlProtocol[] = "file://";
-
-static bool GetPropertyByNameString(NPP instance,
- NPObject *obj,
- const char *name_str,
- NPVariant *out) {
- // Create an identifier for the name.
- NPIdentifier identifier = NPN_GetStringIdentifier(name_str);
- return NPN_GetProperty(instance, obj, identifier, out);
-}
-
-static std::string GetURL(NPP instance) {
- std::string url;
- // get URL for the loading page - first approach from
- // http://developer.mozilla.org/en/docs/Getting_the_page_URL_in_NPAPI_plugin
- // Get the window object.
- // note: on some browsers, this will increment the window ref count.
- // on others, it won't.
- // this is a bug in.... something, but no one agrees what.
- // http://lists.apple.com/archives/webkitsdk-dev/2005/Aug/msg00044.html
- NPObject *window_obj = NULL;
- NPError err = NPN_GetValue(instance, NPNVWindowNPObject,
- &window_obj);
- if (NPERR_NO_ERROR != err) {
- LOG(ERROR) << "getvalue failed (err = " << err << ")";
- goto exit0;
- }
- {
- // Declare a local variant value for the location.
- NPVariant location_variant_value;
- // Get the location property from the window object
- // (which is another object).
- bool success = GetPropertyByNameString(instance,
- window_obj,
- "location",
- &location_variant_value);
- if (!success) {
- LOG(ERROR) << "getproperty failed (location)";
- goto exit0;
- }
- if (!NPVARIANT_IS_OBJECT(location_variant_value)) {
- LOG(ERROR) << "location property has wrong type: "
- << location_variant_value.type;
- goto exit1;
- }
- {
- // Get a pointer to the "location" object.
- NPObject *location_obj = NPVARIANT_TO_OBJECT(location_variant_value);
- // Declare a local variant value for the href.
- NPVariant href_variant_value;
- // Get the location property from the location object.
- success = GetPropertyByNameString(instance,
- location_obj,
- "href",
- &href_variant_value);
- if (!success) {
- LOG(ERROR) << "getproperty failed (href)";
- goto exit1;
- }
- if (!NPVARIANT_IS_STRING(href_variant_value)) {
- LOG(ERROR) << "href property has wrong type: "
- << href_variant_value.type;
- goto exit2;
- }
- // let's just grab the NPUTF8 from the variant and make a std::string
- // from it.
- url = std::string(
- static_cast<const char *>(
- NPVARIANT_TO_STRING(href_variant_value).UTF8Characters),
- static_cast<size_t>(
- NPVARIANT_TO_STRING(href_variant_value).UTF8Length));
-
- exit2:
- NPN_ReleaseVariantValue(&href_variant_value);
- }
- exit1:
- NPN_ReleaseVariantValue(&location_variant_value);
- }
- exit0:
- return url;
-}
-
-static std::string ParseUrlHost(const std::string &in_url) {
- size_t host_start;
- if (in_url.find(kHttpProtocol) == 0) {
- host_start = sizeof(kHttpProtocol) - 1;
- } else if (in_url.find(kHttpsProtocol) == 0) {
- host_start = sizeof(kHttpsProtocol) - 1;
- } else {
- // Do not allow usage on non http/https pages.
- return "";
- }
- size_t path_start = in_url.find("/", host_start);
- if (path_start == std::string::npos) {
- path_start = in_url.size();
- }
- const std::string host_and_port(
- in_url.substr(host_start, path_start - host_start));
- size_t colon_pos = host_and_port.find(":");
- if (colon_pos == std::string::npos) {
- colon_pos = host_and_port.size();
- }
- return host_and_port.substr(0, colon_pos);
-}
-
-static bool IsDomainWhitelisted(const std::string &in_url) {
- if (in_url.find(kLocalFileUrlProtocol) == 0) {
- // Starts with file://, so it's a local file. Allow access for testing
- // purposes.
- return true;
- } else {
- std::string host(ParseUrlHost(in_url));
-
- // convert the host to a lower-cased version so we
- // don't have to worry about case mismatches.
- for (size_t i = 0; i < host.length(); ++i) {
- host[i] = tolower(host[i]);
- }
-
- for (size_t i = 0; i < arraysize(kDomainWhitelist); ++i) {
- size_t pos = host.rfind(kDomainWhitelist[i]);
- if (pos != std::string::npos &&
- ((pos + strlen(kDomainWhitelist[i]) == host.length())))
- return true;
- }
-
- return false;
- }
-}
-
-#endif // O3D_PLUGIN_DOMAIN_WHITELIST
-
-bool IsDomainAuthorized(NPP instance) {
-#ifdef O3D_PLUGIN_DOMAIN_WHITELIST
- std::string url(GetURL(instance));
- if (url.empty()) {
- // This can happen in Chrome due to a bug with cross-origin security checks,
- // including on legitimate pages. Until it's fixed we'll just allow any
- // domain when this happens.
- // http://code.google.com/p/chromium/issues/detail?id=64229
- LOG(WARNING) <<
- "Allowing use despite inability to determine the hosting page";
- return true;
- }
- bool authorized = IsDomainWhitelisted(url);
- if (!authorized) {
- LOG(ERROR) << "Unauthorized domain";
- }
- return authorized;
-#else
- // No whitelist; allow usage on any website. (This is the default.)
- return true;
-#endif
-}
-
-} // namespace o3d
diff --git a/o3d/plugin/cross/whitelist.h b/o3d/plugin/cross/whitelist.h
deleted file mode 100644
index 150043a..0000000
--- a/o3d/plugin/cross/whitelist.h
+++ /dev/null
@@ -1,44 +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_PLUGIN_CROSS_WHITELIST_H_
-#define O3D_PLUGIN_CROSS_WHITELIST_H_
-
-#include "third_party/nixysa/static_glue/npapi/npn_api.h"
-
-namespace o3d {
-
-bool IsDomainAuthorized(NPP instance);
-
-} // namespace o3d
-
-#endif // O3D_PLUGIN_CROSS_WHITELIST_H_
diff --git a/o3d/plugin/idl/archive_request.idl b/o3d/plugin/idl/archive_request.idl
deleted file mode 100644
index 36283b6..0000000
--- a/o3d/plugin/idl/archive_request.idl
+++ /dev/null
@@ -1,176 +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.
- */
-
-namespace o3d {
-
-[include="import/cross/archive_request.h", async]
-callback void ArchiveReadyStateChangeCallback();
-
-[include="import/cross/archive_request.h"]
-callback void ArchiveFileAvailableCallback(RawData rawData);
-
-%[
- An ArchiveRequest object is used to carry out an asynchronous request for a
- compressed archive (containing multiple files).
-
- Note: The archive must have as its first file a file named 'aaaaaaaa.o3d'
- who's contents is 'o3d'. This is to prevent O3D being used to open
- archive files that were not meant for it.
-
- \code
- var request = pack.createArchiveRequest();
- request.open("GET", url);
-
- request.onfileavailable = myFileAvailableCallback;
- request.onreadystatechange = myReadyStateChangeCallback;
- request.send();
-
- function myFileAvailableCallback(rawData) {
- dump("uri: " + rawData.uri + "\n");
- dump("content: " + rawData.stringValue + "\n");
-
- // You can pass a RawData to various creation functions. Note: rawData
- // is only valid until you remove the request.
- // Examples:
- if (rawData.uri == 'mytexture.jpg')
- pack.createTexture2d(rawData, makeMips);
- if (rawData.uri == 'myvertices.bin')
- vertexBuffer.set(rawData);
- if (rawData.uri == 'myAudio.mp3')
- audioSystem.createSound(rawData);
- }
-
- function myReadyStateChangeCallback() {
- if (request.done) {
- if (request.success) {
- // there were no errors trying to read the archive
- } else {
- dump(request.error);
- }
- }
- }
-
- // When you are done with the RawDatas loaded by the request, remove
- // the request from the pack to free them.
- pack.removeObject(request);
- \endcode
-%]
-
-[nocpp, include="import/cross/archive_request.h"] class ArchiveRequest
- : ObjectBase {
- %[
- A callback that gets called each time readyState changes.
- %]
- [setter]
- ArchiveReadyStateChangeCallback? onreadystatechange;
-
- %[
- A callback that gets called each time a file fully downloads and becomes
- available.
- %]
- [setter]
- ArchiveFileAvailableCallback? onfileavailable;
-
- %[
- The uri of the archive being downloaded.
- %]
- [getter] String uri;
-
- %[
- A RawData object representing the file that is currently available.
- Note: This value is only valid inside the onfileavailable callback.
- Note: This property is deprecated. It is now an argument of the
- onfileavailable callback.
- @deprecated
- %]
- [getter] RawData? data;
-
- %[
- The length of the entire archive in bytes.
-
- Use this value along with bytesReceived to figure out the download progress.
- %]
- [getter] int streamLength;
-
- %[
- The number of bytes downloaded so far.
-
- You can use this value along with streamLength to figure out the download
- progress.
- %]
- [getter] int bytesReceived;
-
- %[
- Holds the same values as in XMLHttpRequest:
- \li 0 = uninitialized
- \li 1 = opened
- \li 2 = sent
- \li 3 = receiving
- \li 4 = loaded (the file has been downloaded, but may or may not have been
- parsed yet)
- %]
- [getter] int readyState;
-
- %[
- Indicates whether processing for this FileRequest has finished.
- %]
- [getter] bool done;
-
- %[
- This field is only valid if done is true. It indicates whether or not the
- request succeeded. If false see error for an error message.
- %]
- [getter] bool success;
-
- %[
- An error message.
- If done is true and success is false this will be an error message
- describing what went wrong.
- %]
- [getter] String error;
-
- %[
- Sets up several of the request fields.
- \param method "GET" is the only supported method at this time
- \param uri the location of the file to fetch
- %]
- [nocpp, userglue, plugin_data] void open(
- String method, String uri);
-
- %[
- Send the request.
- Unlike XMLHttpRequest the onreadystatechange callback will be called no
- matter what, with success or failure.
- %]
- [nocpp, userglue, plugin_data] void send();
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/bitmap.idl b/o3d/plugin/idl/bitmap.idl
deleted file mode 100644
index 7eb07f2..0000000
--- a/o3d/plugin/idl/bitmap.idl
+++ /dev/null
@@ -1,112 +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.
- */
-
-
-namespace o3d {
-
-%[
- Bitmap provides an interface for basic image operations on bitmap,
- including scale and crop. A Bitmap can be created from RawData via
- pack.createBitmapsFromRawData(), and also can be transferred to mip of a
- Texure2D or a specific face of TextureCUBE via methods in Texture.
-%]
-
-[nocpp, include="core/cross/bitmap.h"]
-class Bitmap : ParamObject {
- %[
- After loading an array of Bitmaps with pack.createBitmapsFromRawData
- you can inspect their semantic to see what they were intended for. This is
- mostly to distinguish between 6 bitmaps that are faces of a cubemap and 6
- bitmaps that are slices of a 3d texture.
-
- \li FACE_POSITIVE_X, 1 face of a cubemap
- \li FACE_NEGATIVE_X, 1 face of a cubemap
- \li FACE_POSITIVE_Y, 1 face of a cubemap
- \li FACE_NEGATIVE_Y, 1 face of a cubemap
- \li FACE_POSITIVE_Z, 1 face of a cubemap
- \li FACE_NEGATIVE_Z, 1 face of a cubemap
- \li IMAGE, normal 2d image
- \li SLICE, a slice of a 3d texture.
- %]
- enum Semantic {
- FACE_POSITIVE_X,
- FACE_NEGATIVE_X,
- FACE_POSITIVE_Y,
- FACE_NEGATIVE_Y,
- FACE_POSITIVE_Z,
- FACE_NEGATIVE_Z,
- IMAGE,
- SLICE
- };
-
- %[
- Flips a bitmap vertically in place.
- %]
- void FlipVertically();
-
- %[
- Generates mip maps from the source level to lower levels.
-
- You can not currently generate mips for DXT textures although you can load
- them from dds files.
-
- \param source_level The level to use as the source of the mips.
- \param num_levels The number of levels to generate below the source level.
- %]
- void GenerateMips(int source_level, int num_levels);
-
- %[
- The width of the bitmap (read only).
- %]
- [getter] int width_;
-
- %[
- The height of the bitmap (read only).
- %]
- [getter] int height_;
-
- %[
- The format of the bitmap (read only).
- %]
- [getter] Texture::Format format_;
-
- %[
- Number mip-maps (read only)
- %]
- [getter] int num_mipmaps_;
-
- %[
- The Semantic of the bitmap.
- %]
- [getter] Semantic semantic_;
-}; // Bitmap
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/bounding_box.idl b/o3d/plugin/idl/bounding_box.idl
deleted file mode 100644
index 23e5d88..0000000
--- a/o3d/plugin/idl/bounding_box.idl
+++ /dev/null
@@ -1,211 +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.
- */
-
-// TODO: some how make this file conditionally compile different for C++
-// vs Javascript like with #ifdef CPLUSPLUS etc..
-namespace o3d {
-
-%[
- A BoundingBox represents an Axis Aligned Bounding Box.
-%]
-[binding_model=by_value, marshaled, nocpp, include="core/cross/bounding_box.h", no_marshaled_docs]
-class BoundingBox {
- %[
- Creates BoundingBox from min_extent and max_extent
- \param min_extent minimum extent of the box.
- \param max_extent maximum extent of the box.
- %]
- BoundingBox(Vectormath::Aos::Point3 min_extent,
- Vectormath::Aos::Point3 max_extent);
-
- %[
- Assigns a JavaScript array of arrays of numbers into a BoundingBox.
- This property is implicitly invoked whenever such an array is assigned to
- a BoundingBox property or such an array is passed as a BoundingBox method
- parameter.
- %]
- [plugin_data, userglue, userglue_setter, setter, nodocs]
- float[][] marshaled;
-
- %[
- True if this boundingbox has been initialized.
- %]
- [getter] bool valid_;
-
- %[
- The min extent of the box.
- %]
- [getter] Vectormath::Aos::Point3 min_extent;
-
- %[
- The max extent of the box.
- %]
- [getter] Vectormath::Aos::Point3 max_extent;
-
- %[
- Multiplies the bounding box by the given matrix returning a new bounding
- box.
- \param matrix The matrix to multiply by.
- \return The new bounding box.
- %]
- [const, userglue] BoundingBox Mul(Vectormath::Aos::Matrix4 matrix);
-
- %[
- Adds a bounding box to this bounding box returning a bounding box that
- encompases both.
- \param box BoundingBox to add to this BoundingBox.
- \return The new bounding box.
- %]
- [const, userglue] BoundingBox Add(BoundingBox box);
-
- %[
- Checks if a ray defined in same coordinate system as this box intersects
- this bounding box.
- \param start position of start of ray in local space.
- \param end position of end of ray in local space.
- \return RayIntersectionInfo. If result.value is false then something was
- wrong like using this function with an uninitialized bounding box. If
- result.intersected is true then the ray intersected the box
- and result.position is the exact point of intersection.
- %]
- [const, userglue]
- o3d::RayIntersectionInfo IntersectRay(Vectormath::Aos::Point3 start,
- Vectormath::Aos::Point3 end);
-
- %[
- Checks if a ray defined in same coordinate system as this box intersects
- this bounding box.
- \param startX The x coordinate of start of ray in local space.
- \param startY The y coordinate of start of ray in local space.
- \param startZ The z coordinate of start of ray in local space.
- \param endX The x coordinate of end of ray in local space.
- \param endY The y coordinate of end of ray in local space.
- \param endZ The z coordinate of end of ray in local space.
- \return RayIntersectionInfo. If result.value is false then something was
- wrong like using this function with an uninitialized bounding box. If
- result.intersected is true then the ray intersected the box
- and result.position is the exact point of intersection.
- %]
- [const, userglue]
- o3d::RayIntersectionInfo IntersectRay(float startX,
- float startY,
- float startZ,
- float endX,
- float endY,
- float endZ);
-
- %[
- Returns true if the bounding box is inside the frustum.
- \param matrix Matrix to transform the box from its local space to view
- frustum space.
- \return True if the box is in the frustum.
- %]
- [const] bool InFrustum(Vectormath::Aos::Matrix4 matrix);
-
- [verbatim=cpp_glue] %{
- void userglue_setter_marshaled(
- void* plugin_data,
- o3d::BoundingBox* _this,
- const std::vector<std::vector<float> >& values) {
- if (values.empty()) {
- *_this = o3d::BoundingBox();
- } else if (values.size() != 2) {
- o3d::ServiceLocator* service_locator =
- static_cast<glue::_o3d::PluginObject*>(
- plugin_data)->service_locator();
- O3D_ERROR(service_locator)
- << "BoundingBox: expected 2 values, got " << values.size();
- } else {
- for (std::vector<float>::size_type i = 0; i < values.size(); ++i) {
- if (values[i].size() != 3) {
- o3d::ServiceLocator* service_locator =
- static_cast<glue::_o3d::PluginObject*>(
- plugin_data)->service_locator();
- O3D_ERROR(service_locator)
- << "BoundingBox: expected 3 values, got " << values.size();
- return;
- }
- }
- *_this = o3d::BoundingBox(
- Vectormath::Aos::Point3(values[0][0], values[0][1], values[0][2]),
- Vectormath::Aos::Point3(values[1][0], values[1][1], values[1][2]));
- }
- }
- o3d::BoundingBox userglue_method_Mul(
- o3d::BoundingBox* self,
- const Vectormath::Aos::Matrix4 &matrix) {
- o3d::BoundingBox bounding_box;
- self->Mul(matrix, &bounding_box);
- return bounding_box;
- }
- o3d::BoundingBox userglue_method_Add(
- o3d::BoundingBox* self,
- const o3d::BoundingBox& box) {
- o3d::BoundingBox result;
- self->Add(box, &result);
- return result;
- }
- o3d::RayIntersectionInfo userglue_method_IntersectRay(
- o3d::BoundingBox* self,
- const Vectormath::Aos::Point3& start,
- const Vectormath::Aos::Point3& end) {
- o3d::RayIntersectionInfo ray_intersection_info;
- self->IntersectRay(start, end, &ray_intersection_info);
- return ray_intersection_info;
- }
- o3d::RayIntersectionInfo userglue_method_IntersectRay(
- o3d::BoundingBox* self,
- float startX,
- float startY,
- float startZ,
- float endX,
- float endY,
- float endZ) {
- o3d::RayIntersectionInfo ray_intersection_info;
- self->IntersectRay(Vectormath::Aos::Point3(startX, startY, startZ),
- Vectormath::Aos::Point3(endX, endY, endZ),
- &ray_intersection_info);
- return ray_intersection_info;
- }
- %}
-}; // BoundingBox
-
-%[
- A Param which stores a BoundingBox.
-%]
-[nocpp, include="core/cross/param.h"] class ParamBoundingBox : Param {
- %[
- The BoundingBox stored by the Param.
- %]
- [getter, setter] BoundingBox value_;
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/buffer.idl b/o3d/plugin/idl/buffer.idl
deleted file mode 100644
index 37d25a2..0000000
--- a/o3d/plugin/idl/buffer.idl
+++ /dev/null
@@ -1,482 +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.
- */
-
-namespace o3d {
-
-%[
- The Buffer object is a low level container for a flat list of
- floating point or integer values. These are currently used to define
- geometry.
-%]
-[nocpp, include="core/cross/buffer.h"]
-class Buffer : NamedObject {
- %[
- Allocates memory for the data to be stored in the buffer based on
- the types of fields set on the buffer.
-
- \param num_elements Number of elements to allocate..
- \return True if operation was successful.
- %]
- [userglue] bool AllocateElements(unsigned int num_elements);
-
- %[
- Defines a field on this buffer.
-
- Note: Creating a field after having allocated the buffer is an expensive
- operation as the data currently in the buffer has to be shuffled around
- to make room for the new field.
-
- \param field_type type of data in the field. Valid types are "FloatField",
- "UInt32Field", "UByteNField".
- \param num_components number of components in the field.
- \return The created field.
- %]
- [userglue, noreturndocs]
- Field? CreateField(String field_type, unsigned int num_components);
-
- %[
- Removes a field from this buffer.
-
- Note: Removing a field after having allocated the buffer is an expensive
- operation as the data currently in the buffer has to be shuffled around
- to remove the old field.
-
- \param field field to remove.
- %]
- void RemoveField(Field field);
-
- %[
- Sets the values in the buffer given a RawData object.
-
- \param raw_data contains data to assign to the Buffer data itself.
- \return True if operation was successful.
- %]
- bool Set(RawData raw_data);
-
- %[
- Sets the values in the buffer given a RawData object.
-
- \param raw_data contains data to assign to the Buffer data itself.
- \param offset is a byte offset from the start of raw_data
- \param length is the byte length of the data to set
- \return True if operation was successful.
- %]
- bool Set(RawData raw_data,
- size_t offset,
- size_t length);
-
- %[
- Number of elements in the buffer.
- %]
- [getter] unsigned int num_elements;
-
- %[
- The total components in all fields in this buffer.
- %]
- [getter] unsigned int total_components;
-
- %[
- The fields currently set on the buffer.
- %]
- [userglue_getter, getter] FieldArray fields;
-
- [verbatim=cpp_glue] %{
- o3d::Field* userglue_method_CreateField(
- o3d::Buffer* buffer,
- const o3d::String& field_type,
- unsigned int num_components) {
- return buffer->CreateFieldByClassName(field_type, num_components);
- }
- o3d::FieldArray userglue_getter_fields(o3d::Buffer* buffer) {
- const o3d::FieldRefArray buffer_fields = buffer->fields();
- o3d::FieldArray fields(buffer_fields.size());
- for (size_t ii = 0; ii < buffer_fields.size(); ++ii) {
- fields[ii] = buffer_fields[ii].Get();
- }
- return fields;
- }
- bool userglue_method_AllocateElements(o3d::Buffer* buffer,
- unsigned int num_elements) {
- bool result = buffer->AllocateElements(num_elements);
- if (result) {
- // Clear the buffer so at least from Javascript we can't get garbage.
- o3d::BufferLockHelper locker(buffer);
- void* data = locker.GetData(o3d::Buffer::WRITE_ONLY);
- if (!data) {
- O3D_ERROR(buffer->service_locator())
- << "could not lock buffer";
- } else {
- memset(data, 0, buffer->GetSizeInBytes());
- }
- }
- return result;
- }
- %}
-};
-
-%[
- VertexBufferBase is a the base class for both VertexBuffer and SourceBuffer
-
- \sa o3d.VertexBuffer
- \sa o3d.SourceBuffer
-%]
-[nocpp, include="core/cross/buffer.h"]
-class VertexBufferBase : Buffer {
- %[
- Gets a copy of the values of the data stored in the buffer.
- Modifying this copy has no effect on the buffer.
-
- \return An array of values.
- %]
- [nocpp, userglue] float[] Get();
-
- %[
- Gets a copy of a sub range of the values in the data stored in the buffer.
- Modifying this copy has no effect on the buffer.
-
- \param start_index index of the element value to get.
- \param num_elements the number of elements to get.
- \return An array of values.
- %]
- [nocpp, userglue]
- float[] GetAt(unsigned int start_index, unsigned int num_elements);
-
- %[
- Sets the values of the data stored in the buffer.
- The number of values passed in must be a multiple of the number of
- components needed for the fields defined on this buffer.
-
- \param values Values to be stored in the buffer.
- \return True if operation was successful.
- %]
- [nocpp, userglue] bool Set(float[] values);
-
- %[
- Sets the values of the data stored in the buffer. The buffer must have
- already been created either through buffer.set or buffer.allocateElements
-
- The number of values passed in must be a multiple of the number of
- components needed for the fields defined on this buffer.
-
- \param start_index index of first value to set.
- \param values Values to be stored in the buffer starting at index.
- %]
- [nocpp, userglue] void SetAt(unsigned int start_index, float[] values);
-
- [verbatim=cpp_glue] %{
- std::vector<float> userglue_method_Get(o3d::VertexBufferBase *buffer) {
- std::vector<float> retval;
- o3d::BufferLockHelper helper(buffer);
- float* buffer_data = helper.GetDataAs<float>(
- o3d::Buffer::READ_ONLY);
- if (!buffer_data) {
- O3D_ERROR(buffer->service_locator())
- << "could not lock buffer";
- } else {
- retval.resize(buffer->total_components() * buffer->num_elements());
- unsigned element_offset = 0;
- // for each field, copy the stuff into the array.
- const o3d::FieldRefArray& fields = buffer->fields();
- for (unsigned ff = 0; ff < fields.size(); ++ff) {
- o3d::Field* field = fields[ff];
- field->GetAsFloats(0,
- &retval[0] + element_offset,
- field->num_components(),
- buffer->num_elements());
- element_offset += field->num_components();
- }
- }
- return retval;
- }
- std::vector<float> userglue_method_GetAt(o3d::VertexBufferBase *buffer,
- unsigned int start_index,
- unsigned int length) {
- std::vector<float> retval;
- if (start_index + length > buffer->num_elements() ||
- start_index + length < start_index) {
- O3D_ERROR(buffer->service_locator())
- << "number of requested values would run past end of buffer";
- } else {
- o3d::BufferLockHelper helper(buffer);
- float* buffer_data = helper.GetDataAs<float>(
- o3d::Buffer::READ_ONLY);
- if (!buffer_data) {
- O3D_ERROR(buffer->service_locator())
- << "could not lock buffer";
- } else {
- retval.resize(length * buffer->total_components());
- unsigned element_offset = 0;
- // for each field, copy the stuff into the array.
- const o3d::FieldRefArray& fields = buffer->fields();
- for (unsigned ff = 0; ff < fields.size(); ++ff) {
- o3d::Field* field = fields[ff];
- field->GetAsFloats(start_index,
- &retval[0] + element_offset,
- field->num_components(),
- length);
- element_offset += field->num_components();
- }
- }
- }
- return retval;
- }
- bool userglue_method_Set(o3d::VertexBufferBase *buffer,
- const std::vector<float> &values) {
- unsigned int total_components = buffer->total_components();
- size_t size = values.size();
- if (total_components == 0) {
- O3D_ERROR(buffer->service_locator())
- << "no fields are defined on the buffer";
- return false;
- }
- if (size % total_components != 0) {
- O3D_ERROR(buffer->service_locator())
- << "the number of values passed in is not a multiple of the number"
- << " of components in the fields on the buffer.";
- return false;
- }
-
- unsigned num_elements = size / total_components;
-
- if (!buffer->AllocateElements(num_elements)) {
- return false;
- }
-
- o3d::BufferLockHelper helper(buffer);
- void* buffer_data = helper.GetData(o3d::Buffer::WRITE_ONLY);
- if (!buffer_data) {
- O3D_ERROR(buffer->service_locator())
- << "could not lock buffer";
- return false;
- }
-
- unsigned element_offset = 0;
- // for each field, copy the stuff out of the array.
- const o3d::FieldRefArray& fields = buffer->fields();
- for (unsigned ff = 0; ff < fields.size(); ++ff) {
- o3d::Field* field = fields[ff];
- field->SetFromFloats(&values[element_offset],
- total_components,
- 0,
- num_elements);
- element_offset += field->num_components();
- }
- return true;
- }
- void userglue_method_SetAt(o3d::VertexBufferBase *buffer,
- unsigned int start_index,
- const std::vector<float> &values) {
- unsigned int total_components = buffer->total_components();
- size_t size = values.size();
- if (total_components == 0) {
- O3D_ERROR(buffer->service_locator())
- << "no fields are defined on the buffer";
- return;
- }
- if (size % total_components != 0) {
- O3D_ERROR(buffer->service_locator())
- << "the number of values passed in is not a multiple of the number"
- << " of components in the fields on the buffer.";
- return;
- }
-
- unsigned num_elements_to_set = size / total_components;
- unsigned last_element = start_index + num_elements_to_set;
- if (last_element > buffer->num_elements() ||
- last_element < start_index) {
- O3D_ERROR(buffer->service_locator())
- << "Attempt to set elements outside of Buffer";
- return;
- }
-
- o3d::BufferLockHelper helper(buffer);
- void* buffer_data = helper.GetData(o3d::Buffer::WRITE_ONLY);
- if (!buffer_data) {
- O3D_ERROR(buffer->service_locator())
- << "could not lock buffer";
- return;
- }
-
- unsigned element_offset = 0;
- // for each field, copy the stuff out of the array.
- const o3d::FieldRefArray& fields = buffer->fields();
- for (unsigned ff = 0; ff < fields.size(); ++ff) {
- o3d::Field* field = fields[ff];
- field->SetFromFloats(&values[element_offset],
- total_components,
- start_index,
- num_elements_to_set);
- element_offset += field->num_components();
- }
- }
- %}
-};
-
-%[
- VertexBuffer is a Buffer object used for storing vertex data for geometry.
- (e.g. vertex positions, normals, colors, etc).
- A VertexBuffer can be rendered directly by the GPU.
-
- \sa o3d.SourceBuffer
-%]
-[nocpp, include="core/cross/buffer.h"]
-class VertexBuffer : VertexBufferBase {
-};
-
-%[
- SourceBuffer is a Buffer object used for storing vertex data for
- geometry. (e.g. vertex positions, normals, colors, etc).
-
- A SourceBuffer is the source for operations like skinning and morph
- targets. It can not be directly rendered by the GPU.
-
- \sa o3d.VertexBuffer
-%]
-[nocpp, include="core/cross/buffer.h"]
-class SourceBuffer : VertexBufferBase {
-};
-
-%[
- IndexBuffer is a buffer object used for storing geometry index data (e.g.
- triangle indices).
-%]
-[nocpp, include="core/cross/buffer.h"] class IndexBuffer : Buffer {
- %[
- Sets the values of the data stored in the buffer.
-
- \param values Values to be stored in the buffer.
- \return True if operation was successful.
- %]
- [nocpp, userglue] bool Set(unsigned int[] values);
-
- %[
- Sets the values of the data stored in the buffer. The buffer must have
- already been created either through buffer.set or buffer.allocateElements.
-
- \param start_index index of first value to set.
- \param values Values to be stored in the buffer starting at index.
- %]
- [nocpp, userglue] void SetAt(unsigned int start_index, unsigned int[] values);
-
- [verbatim=cpp_glue] %{
- bool userglue_method_Set(o3d::IndexBuffer *buffer,
- const std::vector<unsigned int> &values) {
- unsigned int total_components = buffer->total_components();
- size_t size = values.size();
- if (total_components == 0) {
- O3D_ERROR(buffer->service_locator())
- << "no fields are defined on the buffer";
- return false;
- }
- if (size % total_components != 0) {
- O3D_ERROR(buffer->service_locator())
- << "the number of values passed in is not a multiple of the number"
- << " of components in the fields on the buffer.";
- return false;
- }
-
- unsigned num_elements = size / total_components;
-
- if (!buffer->AllocateElements(num_elements)) {
- return false;
- }
-
- o3d::BufferLockHelper helper(buffer);
- void* buffer_data = helper.GetData(o3d::Buffer::WRITE_ONLY);
- if (!buffer_data) {
- O3D_ERROR(buffer->service_locator())
- << "could not lock buffer";
- return false;
- }
-
- unsigned element_offset = 0;
- // for each field, copy the stuff out of the array.
- const o3d::FieldRefArray& fields = buffer->fields();
- for (unsigned ff = 0; ff < fields.size(); ++ff) {
- o3d::Field* field = fields[ff];
- field->SetFromUInt32s(&values[element_offset],
- total_components,
- 0,
- num_elements);
- element_offset += field->num_components();
- }
- return true;
- }
- void userglue_method_SetAt(o3d::IndexBuffer *buffer,
- unsigned int start_index,
- const std::vector<unsigned int> &values) {
- unsigned int total_components = buffer->total_components();
- size_t size = values.size();
- if (total_components == 0) {
- O3D_ERROR(buffer->service_locator())
- << "no fields are defined on the buffer";
- return;
- }
- if (size % total_components != 0) {
- O3D_ERROR(buffer->service_locator())
- << "the number of values passed in is not a multiple of the number"
- << " of components in the fields on the buffer.";
- return;
- }
-
- unsigned num_elements_to_set = size / total_components;
- unsigned last_element = start_index + num_elements_to_set;
- if (last_element > buffer->num_elements() ||
- last_element < start_index) {
- O3D_ERROR(buffer->service_locator())
- << "Attempt to set elements outside of Buffer";
- return;
- }
-
- o3d::BufferLockHelper helper(buffer);
- void* buffer_data = helper.GetData(o3d::Buffer::WRITE_ONLY);
- if (!buffer_data) {
- O3D_ERROR(buffer->service_locator())
- << "could not lock buffer";
- return;
- }
-
- unsigned element_offset = 0;
- // for each field, copy the stuff out of the array.
- const o3d::FieldRefArray& fields = buffer->fields();
- for (unsigned ff = 0; ff < fields.size(); ++ff) {
- o3d::Field* field = fields[ff];
- field->SetFromUInt32s(&values[element_offset],
- total_components,
- start_index,
- num_elements_to_set);
- element_offset += field->num_components();
- }
- }
- %}
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/canvas.idl b/o3d/plugin/idl/canvas.idl
deleted file mode 100644
index 446d5b7..0000000
--- a/o3d/plugin/idl/canvas.idl
+++ /dev/null
@@ -1,185 +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.
- */
-
-
-namespace o3d {
-
-%[
-Canvas provides an interface for drawing text and 2D primitives on a 2D surface.
-The contents of the canvas surface can be transfered to a compatible Texture2D
-object via the copyToTexture() method. Each Canvas object maintains
-a stack of 2D transformation matrices which allow fine control over
-the placement of drawable elements. Both geometry and drawing coordinates
-provided to every draw call are transformed by the concatenation of
-all matrices in the stack.
-%]
-
-[nocpp, include="core/cross/canvas.h"]
-class Canvas : ParamObject {
- %[
- Sets the size of the bitmap area that the Canvas uses.
- \param width The width of the bitmap.
- \param height The height of the bitmap.
- \return true if the Canvas surface was allocated successfully.
- %]
- bool SetSize(int width, int height);
-
- %[
- Clears the bitmap's pixels with the specified color.
- \param color The color to clear the bitmap with, provided as an array of
- four values [red, green, blue, alpha]. All values should be between 0.0
- and 1.0. For alpha values 0.0 is transparent and 1.0 opaque.
- %]
- [userglue] void Clear(Float4 color);
-
- %[
- Draws the specified rectangle using the specified paint. The rectangle will
- be filled based on the color and shader in the paint.
- \param left The left side of the rectangle to be drawn
- \param top The top side of the rectangle to be drawn
- \param right The right side of the rectangle to be drawn
- \param bottom The bottom side of the rectangle to be drawn
- \param paint The paint used to draw the rectangle
- %]
- void DrawRect(float left,
- float top,
- float right,
- float bottom,
- CanvasPaint paint);
-
- %[
- Draws the text, with origin at (x,y), using the specified paint. The origin
- is interpreted based on the textAlign property in the paint.
- \param text String of text to be drawn
- \param x The x coordinate for the text origin
- \param y The y coordinate for the text origin
- \param paint The CanvasPaint object that specifies the text style, size, etc
- %]
- void DrawText(String text, float x, float y, CanvasPaint paint);
-
- %[
- Draws the text with its baseline along the
- specified path. The paint's textAlign property determines where along the
- path to start the text. The path must contain at least two positions.
- \param text String of text to be drawn
- \param positions An array of x,y positions making up the path.
- \param horizontalOffset The distance along the path to add to the text
- starting position.
- \param verticalOffset The distance above(-) or below(+) the path to position
- the text.
- \param paint The CanvasPaint object that specifies the text style, size,
- etc.
- %]
- void DrawTextOnPath(String text,
- Float2[] positions,
- float horizontalOffset,
- float verticalOffset,
- CanvasPaint paint);
-
- %[
- Draws the contents of the specified texture onto the canvas surface.
- The bottom left corner of the bitmap will be at (x, y) and transformed by
- the current matrix. Only ARGB8 and XRGB8 textures are supported. For XRG8
- textures, Alpha is assumed to be 1 (opaque).
- \param texture The Texture2D object where the bitmap is extracted from.
- \param left The position of the left side of the bitmap.
- \param bottom The position of the bottom side of the bitmap.
- @deprecated
- %]
- void DrawBitmap(Texture2D texture, float left, float bottom);
-
- %[
- This call saves the current matrix and pushes a
- copy onto a private stack. Subsequent calls to translate, scale,
- rotate all operate on this copy.
- When the balancing call to restoreMatrix() is made, this copy is deleted and
- the previous matrix is restored.
- %]
- void SaveMatrix();
-
- %[
- Balances a call to saveMatrix(), and removes modifications to matrix
- since the last save call. It is an error to call this more than
- previous calls to saveMatrix().
- %]
- void RestoreMatrix();
-
- %[
- Adds a rotation to the current canvas matrix.
- \param degrees The amount to rotate, in degrees
- %]
- void Rotate(float degrees);
-
-
- %[
- Adds a scale to the current canvas matrix.
- \param sx The amount to scale in x
- \param sy The amount to scale in y
- %]
- void Scale(float sx, float sy);
-
- %[
- Adds a translation to the current canvas matrix.
- \param dx The amount to translate in x
- \param dy The amount to translate in y
- %]
- void Translate(float dx, float dy);
-
- %[
- Copies the contents of the Canvas to a 2D texture object. The size of the
- texture must match exactly the size of the Canvas set by the setSize() method.
- The format of the texture must be set to either ARGB8 or XRGB8.
- \param texture Texture to copy to.
- @deprecated
- \sa o3d.Texture2D.drawImage
- %]
- void CopyToTexture(Texture2D texture);
-
- %[
- The width of the bitmap used by the Canvas (read only).
- %]
- [getter] int width_;
-
- %[
- The height of the bitmap used by the Canvas (read only).
- %]
- [getter] int height_;
-
- [verbatim=cpp_glue] %{
- void userglue_method_Clear(o3d::Canvas* canvas,
- const o3d::Float4& color) {
- canvas->Clear(color[0], color[1], color[2], color[3]);
- }
- %}
-
-}; // Canvas
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/canvas_paint.idl b/o3d/plugin/idl/canvas_paint.idl
deleted file mode 100644
index 4cc7951..0000000
--- a/o3d/plugin/idl/canvas_paint.idl
+++ /dev/null
@@ -1,193 +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.
- */
-
-
-namespace o3d {
-
-%[
- CanvasFontMetrics is used to return values, measured in pixels, describing
- the properties of a font used by the CanvasPaint objects. All the properties
- of CanvasFontMetrics are read-only.
-%]
-
-[binding_model=by_value, nocpp, include="core/cross/canvas_paint.h"]
-class CanvasFontMetrics {
- %[
- The greatest distance above the baseline for any glyph (will be <= 0)
- %]
- [getter] float top_;
-
- %[
- The recommended distance above the baseline (will be <= 0)
- %]
- [getter] float ascent_;
-
- %[
- The recommended distance below the baseline (will be >= 0)
- %]
- [getter] float descent_;
-
- %[
- The greatest distance below the baseline for any glyph (will be >= 0)
- %]
- [getter] float bottom_;
-
- %[
- The recommended distance to add between lines of text (will be >= 0)
- %]
- [getter] float leading_;
-}; // CanvasFontMetrics
-
-
-%[
- The CanvasPaint class is used for specifying how to draw objects and text to
- a canvas.
-%]
-
-[nocpp, include="core/cross/canvas_paint.h"]
-class CanvasPaint : ParamObject {
- %[
- \var Style
- \li NORMAL,
- \li BOLD,
- \li ITALIC,
- \li BOLD_ITALIC
- Text styles
- %]
- enum Style {
- NORMAL,
- BOLD,
- ITALIC,
- BOLD_ITALIC
- };
-
- %[
- \var TextAlign
- \li LEFT,
- \li CENTER,
- \li RIGHT,
- Text alignment options
- %]
- enum TextAlign {
- LEFT,
- CENTER,
- RIGHT
- };
-
- %[
- Sets the color and radius of an outline around the text. Setting the
- radius to 0 cancels the outline effect. The outline and shadow effects are
- mutually exclusive.
- \param radius Distance outward from object to draw the background
- \param color Color of the outline
- %]
- void SetOutline(float radius, Float4 color);
-
- %[
- Create a blur shadow effect on this paint. Setting the radius to 0 cancels
- the shadow effect.
- \param radius radius to blur the paint
- \param offset_y offset of the blur in X
- \param offset_x offset of the blur in Y
- \param color color for the blur
- %]
- void SetShadow(float radius,
- float offset_x,
- float offset_y,
- Float4 color);
-
- %[
- Returns metrics describing the font currently set on this paint object.
- \return The font metrics.
- %]
- CanvasFontMetrics GetFontMetrics();
-
- %[
- Returns the bounds of the given text string when rendered with this paint.
- The bounds are returned as an array containing [left, top, right, bottom]
- values relative to (0, 0).
- \param text The string of text to be measured.
- \return The bounds of text.
- %]
- Float4 MeasureText(String text);
-
- %[
- The color used for all the draw operations using this paint.
- Default = [0, 0, 0, 1].
- %]
- [getter, setter] Float4 color;
-
- %[
- The size of the font used for drawing text.
- Default = 10.
- %]
- [getter, setter] float text_size;
-
- %[
- The font typeface used for drawing text. Passing an empty string will
- revert to the default font.
- Default = "".
- %]
- [getter, setter] String text_typeface;
-
- %[
- The style applied to the text (e.g. italic, bold, etc)
- Default = NORMAL.
- %]
- [getter, setter] Style text_style;
-
- %[
- The alignment mode used for drawing text.
- Default = LEFT.
- %]
- [getter, setter] TextAlign text_align;
-
- %[
- The 2D shader used by this paint. Set to null to stop using a shader.
- %]
- [getter, setter] CanvasShader? shader;
-
- %[
- Metrics of the current font used by the paint object.
- %]
- [userglue_getter, getter] CanvasFontMetrics font_metrics;
-
- [verbatim=cpp_glue] %{
- o3d::CanvasFontMetrics userglue_getter_font_metrics(
- o3d::CanvasPaint* self) {
- return self->GetFontMetrics();
- }
- %}
-
-}; // CanvasPaint
-
-} // namespace o3d
-
diff --git a/o3d/plugin/idl/canvas_shader.idl b/o3d/plugin/idl/canvas_shader.idl
deleted file mode 100644
index daa3399..0000000
--- a/o3d/plugin/idl/canvas_shader.idl
+++ /dev/null
@@ -1,98 +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.
- */
-
-
-namespace o3d {
-
-%[
-CanvasShader is the base class of 2D gradient shaders that can be applied to a
-CanvasPaint. When a shader is assigned to a CanvasPaint object, all subsequent
-drawing (text and objects) will use the shader pattern as a fill material.
-%]
-
-[nocpp, include="core/cross/canvas_shader.h"]
-class CanvasShader : ParamObject {
- %[
- \var TileMode
- \li CLAMP copy the edge color if the shader draws outside of its bounds
- \li REPEAT repeat horizontally and vertically outside its bounds
- \li MIRROR same as above, alternating mirror images
- %]
- enum TileMode {
- CLAMP, /* copy the edge color if the shader draws outside of its bounds */
- REPEAT, /* repeat horizontally and vertically outside its bounds */
- MIRROR /* same, alternating mirror images */
- };
-
-}; // class CanvasShader
-
-%[
-A shader that generates a linear gradient between two specified points. Two or
-more colors need to be specified for the gradient.
-%]
-[nocpp, include="core/cross/canvas_shader.h"]
-class CanvasLinearGradient : CanvasShader {
- %[
- The start point of this gradient.
- Default = [0, 0].
- %]
- [getter, setter] Float2 start_point;
-
- %[
- The end point of this gradient.
- Default = [0, 0].
- %]
- [getter, setter] Float2 end_point;
-
- %[
- The array of colors to be distributed between the two points in RBGA format
- stored as an array of [r, g, b, a] colors.
- Default = [[0, 0, 0, 1], [0, 0, 0, 1]].
- %]
- [getter, setter] Float4[] colors;
-
- %[
- The relative position of each corresponding color in the color array.
- Values must begin with 0 and end with 1.0 and there should be exactly as
- many numbers as there are colors. If positions is set to an empty array then
- the colors are distributed evenly between between the start and end point.
- %]
- [getter, setter] float[] positions;
-
- %[
- The TileMode of this gradient which controls how the gradient pattern
- repeats.
- Default = REPEAT.
- %]
- [getter, setter] TileMode tile_mode;
-
-}; // class CanvasLinearGradient
-} // namespace o3d
diff --git a/o3d/plugin/idl/clear_buffer.idl b/o3d/plugin/idl/clear_buffer.idl
deleted file mode 100644
index 5b27e5a..0000000
--- a/o3d/plugin/idl/clear_buffer.idl
+++ /dev/null
@@ -1,92 +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.
- */
-
-namespace o3d {
-
-%[
- A ClearBuffer is a render node that clears the color buffer, zbuffer and/or
- stencil buffer of the current render target.
-
- @o3dparameter clearColor ParamFloat4 The color to clear to.
- @o3dparameter clearColorFloat ParamBoolean True to clear the color of the
- current render target.
- @o3dparameter clearColor ParamFloat The depth value to clear to (0.0 to 1.0).
- @o3dparameter clearColorFloat ParamBoolean True to clear the depth of the
- current render target.
- @o3dparameter clearColor ParamInteger The stencil value to clear to.
- @o3dparameter clearColorFloat ParamBoolean True to clear the stencil of the
- current render target.
-%]
-
-[nocpp, include="core/cross/clear_buffer.h"] class ClearBuffer
- : RenderNode {
- %[
- The color to clear the buffer in RGBA Float4 format.
- Default = [0, 0, 0, 1]
- %]
- [getter, setter] Float4 clear_color;
-
- %[
- true clears the current render target's color buffer to the clear color.
- false does not clear the color buffer.
- Default = true.
- %]
- [getter, setter] bool clear_color_flag_;
-
- %[
- The value to clear the depth buffer (0.0 to 1.0)
- Default = 1.
- %]
- [getter, setter] float clear_depth_;
-
- %[
- true clears the current render target's depth buffer to the clear depth
- value. false does not clear the depth buffer.
- Default = true.
- %]
- [getter, setter] bool clear_depth_flag_;
-
- %[
- The value to clear the stencil buffer to (0 - 255).
- Default = 0.
- %]
- [getter, setter] int clear_stencil_;
-
- %[
- true clears the current render target's stencil buffer to the clear stencil
- value. false does not clear the stencil buffer
- Default = true.
- %]
- [getter, setter] bool clear_stencil_flag_;
-
-}; // ClearBuffer
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/client.idl b/o3d/plugin/idl/client.idl
deleted file mode 100644
index d492c96..0000000
--- a/o3d/plugin/idl/client.idl
+++ /dev/null
@@ -1,695 +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 public interface specification for the client.
-
-namespace o3d {
-
-%[
- IdArray is a typdef for an array of Ids.
-%]
-typedef Id[] IdArray;
-
-%[
- PackArray is a typdef for an array of Packs.
-%]
-typedef Pack[] PackArray;
-
-%[
- ObjectBaseArray is a typdef for an array of ObjectBase objects.
-%]
-typedef ObjectBase[] ObjectBaseArray;
-
-callback void LostResourcesCallback();
-
-callback void EventCallback(Event event_descriptor);
-
-%[
- The Renderer class provides the abstract interface to each platform's
- rendering library.
-%]
-[binding_model=by_pointer, include="core/cross/renderer.h", nocpp, glue_iface]
-class Renderer {
- %[
- The initialization status of the renderer.
-
- \var InitStatus,
- \li UNINITIALIZED,
- \li SUCCESS, The renderer is initialized.
- \li GPU_NOT_UP_TO_SPEC, The renderer determined the user's machine cannot
- run O3D.
- \li OUT_OF_RESOURCES, The user's machine does not have enough graphic
- resources available to start another instance of the O3D renderer.
- \li INITIALIZATION_ERROR, Some unknown error such as e.g. drivers not
- being installed correctly.
- %]
- enum InitStatus {
- UNINITIALIZED,
- SUCCESS,
- GPU_NOT_UP_TO_SPEC,
- OUT_OF_RESOURCES,
- INITIALIZATION_ERROR
- };
-
- %[
- This is used in SetFullscreenClickRegion to request the current display
- mode, such that the change to full-screen mode won't change the screen
- resolution or refresh rate.
-
- \var DisplayModes,
- \li DISPLAY_MODE_DEFAULT
- %]
- enum DisplayModes {
- DISPLAY_MODE_DEFAULT
- };
-};
-
-%[
- The ClientInfo is used to get information about the client.
-%]
-[binding_model=by_value, include="core/cross/client_info.h", nocpp, glue_iface]
-class ClientInfo {
- %[
- The number of objects the client is currently tracking.
- You can use this to check that you are correctly freeing resources.
- %]
- [getter] int num_objects;
-
- %[
- The amount of texture memory used.
- %]
- [getter] int texture_memory_used;
-
- %[
- The amount of texture memory used.
- %]
- [getter] int buffer_memory_used;
-
- %[
- Whether or not O3D is using the software renderer.
-
- For testing purposes you can force O3D to use the software renderer
- by setting the environment variable O3D_FORCE_SOFTWARE_RENDERER to
- anything.
-
- \code
- set O3D_FORCE_SOFTWARE_RENDERER=foo
- \endcode
- or
- \code
- export O3D_FORCE_SOFTWARE_RENDERER=foo
- \endcode
-
- You can set it at a system level if you want to set it for all
- browser instances or set it from a command line and start your
- browser from that same command line if you want to effect just
- that instance of the browser.
-
- Note that many browers require special command line options to
- run in a separate process, otherwise they default to finding
- the browser process already running and using that. For example
- firefox requires the option -no-remote.
- %]
- [getter] bool software_renderer;
-
- %[
- Whether or not the GPU supports non power of two textures.
- NOTE: O3D always allows non power of two textures.
-
- The only reason to look at this flag is for things like video that are
- updating the texture every frame. In that case, you might want to know
- that you could run faster if you used a power of 2 texture instead of
- a non power of 2 texture.
- %]
- [getter] bool non_power_of_two_textures;
-
- %[
- True if shaders need to be GLSL instead of Cg/HLSL.
- %]
- [getter] bool glsl;
-
- %[
- True if rendering in 2d mode
- %]
- [getter] bool render_2d;
-};
-
-%[
- The Client class is the main point of entry to O3D. It defines methods
- for creating and deleting packs. Each new object created by the Client is
- assigned a unique ID.
-
- The Client has a root transform for the transform graph and a root render
- node for the render graph.
-%]
-[binding_model=by_pointer, include="core/cross/client.h",
- nocpp, glue_iface]
-class Client {
-
- callback void RenderCallback(RenderEvent render_event);
- callback void TickCallback(TickEvent tick_event);
- callback void ErrorCallback(String error_msg);
-
- %[
- The transform graph root Transform
- %]
- [getter] Transform root_;
-
- %[
- Call this function from window.onunload to ensure the browser does not
- continue to call callbacks (like the render callback) after the page is
- unloaded. It is possible that during unload the browser unloads all the
- javascript code, but then, after that, still asks the plugin to render. The
- browser then calls javascript functions that no longer exist which causes an
- error. To prevent that situation you need to clear all your callbacks on
- unload. cleanup handles that for you so you don't have to dispose each and
- every callback by hand.
- %]
- void Cleanup();
-
- %[
- Creates a pack object.
- \return A pack object.
- %]
- Pack CreatePack();
-
- %[
- Searches the Client for an object matching the given id.
-
- \param id The id of the object to look for.
- \return The object or null if a object with the given id is not found.
- %]
- [const, noreturndocs] ObjectBase? GetObjectById(Id id);
-
- %[
- Searches the Client for objects of a particular name and type.
- \param name name of object to look for.
- \param class_name name of class to look for.
- \return Array of objects found.
- %]
- [const, noretundocs] ObjectArray GetObjects(String name, String class_name);
-
- %[
- Searches the Client for objects of a particular type.
- \param class_name name of class to look for.
- \return Array of objects found.
- %]
- [const, noreturndocs] ObjectArray GetObjectsByClassName(String class_name);
-
- %[
- \li RENDERMODE_CONTINUOUS, Draw as often as possible up to refresh rate.
- \li RENDERMODE_ON_DEMAND, Draw once then only when the OS requests it
- (like uncovering part of a window.)
- %]
- enum RenderMode {
- RENDERMODE_CONTINUOUS, // Draw as often as possible up to refresh rate.
- RENDERMODE_ON_DEMAND // Draw once then when the OS request it
- // (like uncovering part of a window.)
- };
-
- %[
- The current render mode. The default mode is RENDERMODE_CONTINUOUS.\n
- Valid values are:
- \li RENDERMODE_CONTINUOUS, Draw as often as possible up to refresh rate.
- \li RENDERMODE_ON_DEMAND, Draw when the OS requests it (like uncovering
- part of a window.)
- %]
- [getter, setter] RenderMode render_mode_;
-
- %[
- Forces a render of the current scene if the current render mode is
- RENDERMODE_ON_DEMAND.
- %]
- void Render();
-
- %[
- Renders a render graph.
-
- Normally the client calls this function automatically for you effectively
- doing a client.renderTree(client.renderGraphRoot) but there are cases
- where it is beneficial to be able to call this yourself and pass it
- different roots when you need to manipulate something between calls.
-
- This function can only be called from inside a render callback. If you call
- it the client will not do its default call as mentioned above.
-
- \param render_node root RenderNode to start rendering from.
- %]
- void RenderTree(RenderNode render_node);
-
- %[
- Returns an array of DisplayModes which are available for use in full-screen
- mode.
- \return An array of DisplayModes.
- %]
- [userglue, plugin_data] DisplayMode[] GetDisplayModes();
-
- %[
- Makes a region of the plugin area that will invoke full-screen mode if
- clicked. The developer is responsible for communicating this to the user,
- as this region has no visible marker. The developer is also responsible for
- updating this region if the plugin gets resized, as we don't know whether or
- how to scale it. There can be only one full-screen click region at a time;
- calling this again will override any previous call.
-
- \param x x position in pixels.
- \param y y position in pixels.
- \param width width in pixels.
- \param height height in pixels.
- \param mode_id Id of mode to use.
- %]
- [userglue, plugin_data]
- void SetFullscreenClickRegion(
- int x, int y, int width, int height, int mode_id);
- %[
- Deactivates the plugin click region that was previously created with
- SetFullscreenClickRegion().
- %]
- [userglue, plugin_data]
- void ClearFullscreenClickRegion();
- %[
- Cancels full-screen display, reverting to displaying content only in the
- plugin region. If the plugin is already not in full-screen mode, this has
- no effect. This does not deactivate the plugin click region--if the user
- clicks there again, we'll go back to full-screen display.
- %]
- [userglue, plugin_data] void CancelFullscreenDisplay();
-
- %[
- Gets info about the client.
- %]
- [userglue_getter, getter, plugin_data]
- ClientInfo client_info;
-
- %[
- Whether content is displayed in full-screen mode or in a plugin window. The
- default is false [not full-screen].
- %]
- [userglue_getter, getter, plugin_data]
- bool fullscreen;
-
- %[
- Returns the width of the current drawing area [plugin or full-screen] in
- pixels.
- %]
- [userglue_getter, getter, plugin_data]
- int width;
-
- %[
- Returns the height of the current drawing area [plugin or full-screen] in
- pixels.
- %]
- [userglue_getter, getter, plugin_data]
- int height;
-
- %[
- The root of the render graph.
- %]
- [getter] RenderNode render_graph_root_;
-
- %[
- Sets the per frame render callback.
-
- Note: The callback will not be called recursively. When your callback is
- called if you somehow manage to cause the client to render more frames
- before you've returned from the callback you will not be called for those
- frames.
-
- \code
- g_client.setRenderCallback(onrender);
-
- function onrender(render_event) {
- var elapsedTime = render_event.elapsedTime;
-
- // elapsedTime is the time elasped since the last callback.
- // You can use this value to make your application frame rate independent.
- // For example:
- // position = position + velocity_in_units_per_second * elapsedTime;
- }
- \endcode
-
- \param render_callback The callback to call each frame.
- %]
- void SetRenderCallback(RenderCallback? render_callback);
-
- %[
- Clears the per frame render callback.
- %]
- void ClearRenderCallback();
-
- %[
- Sets a render callback to be called at the end of the
- rendering cycle of each frame.
-
- Note: The callback will not be called recursively. When your callback is
- called if you somehow manage to cause the client to render more frames
- before you've returned from the callback you will not be called for those
- frames.
-
- \code
- g_client.setPostRenderCallback(onpostrender);
-
- function onpostrender(render_event) {
- var elapsedTime = render_event.elapsedTime;
-
- // elapsedTime is the time elasped since the last callback.
- // You can use this value to make your application frame rate independent.
- // For example:
- // position = position + velocity_in_units_per_second * elapsedTime;
- }
- \endcode
-
- \param post_render_callback The callback to call each frame.
- %]
- void SetPostRenderCallback(RenderCallback? post_render_callback);
-
- %[
- Clears the post render callback.
- %]
- void ClearPostRenderCallback();
-
- %[
- Sets the lost resources callback.
-
- The contents of certain resources, RenderSurfaces, can get discarded by the
- system under certain circumstances. If you application needs that contents
- to be in a certain state then you can set a callback giving your program the
- opportunity to restore that state if and when it is lost.
-
- \param lost_resources_callback The callback when resources are lost.
- %]
- void SetLostResourcesCallback(LostResourcesCallback? lost_resources_callback);
-
- %[
- Clears the lost resources callback.
- %]
- void ClearLostResourcesCallback();
-
- %[
- Sets a callback for a given event type.
- types.
- There can be only one callback for a given event type at a time; setting a
- new one deletes the old one.
-
- \param type Type of event to set callback for.
- \param handler Function to call on event.
-
- \sa o3d.Event
- %]
- void SetEventCallback(String type, EventCallback? handler);
-
- %[
- Removes the previously-registered callback for an event of the given type.
- \param type Type of event to clear callback for.
- %]
- void ClearEventCallback(String type);
-
- %[
- Sets the texture to use when a Texture or Sampler is missing while
- rendering. The default is a red texture with a yellow no symbol.
- <span style="color:yellow; background-color: red;">&Oslash;</span>.
- If you set it to null you'll get an error if you try to render something
- that is missing a needed Texture, Sampler or ParamSampler.
-
- For example if you don't care about missing textures, setting it to a black
- texture would be one option. Another example is if you want to write all
- your shaders to expect a texture then set this to a white texture. If you
- want to make sure you are not missing any textures set it null and see if
- you get any errors using Client.setErrorCallback or Client.lastError.
-
- \code
- // Set the error texture to black.
- var t = g_pack.createTexture2D('', 1, 1, g_o3d.Texture.XRGB8, 1);
- t.set(0, [0, 0, 0]);
- g_client.setErrorTexture(t);
- \endcode
-
- \param texture texture to use for missing textures or null.
- %]
- void SetErrorTexture(Texture? texture);
-
- %[
- Sets a callback for when the client ticks. The client processes some things
- like animation timers at up to 100hz. This callback will get called before
- each of those process ticks.
-
- NOTE: The client takes ownership of the TickCallback you
- pass in. It will be deleted if you call SetTickCallback a
- second time or if you call ClearTickCallback.
-
- Note: The callback will not be called recursively.
-
- \param tick_callback TickCallback to call when the Client ticks.
- %]
- void SetTickCallback(TickCallback? tick_callback);
-
- %[
- Clears the tick callback
-
- NOTE: The client takes ownership of the TickCallback you
- pass in. It will be deleted if you call SetTickCallback a second
- time or if you call ClearTickCallback
- %]
- void ClearTickCallback();
-
- %[
- Sets a callback for when the client gets an error. For example when a shader
- is compiled and there is an error or if you attempt to bind a param to a
- param of an incompatible type.
-
- NOTE: The client takes ownership of the ErrorCallback you
- pass in. It will be deleted if you call SetErrorCallback a
- second time or if you call ClearErrorCallback.
-
- NOTE: The callback will not be called recursively. If you are in a
- callback, and do something that causes another error before you have
- returned from the callback, your callback will not be called a second time.
-
- NOTE: If you put up an alert in response to an error it is best if you
- clear the error callback before you put up the alert. Otherwise you'll get
- an alert everytime the client tries to render which is every time you close
- the current alert which means you'll be in an infinite loop of alerts.
-
- \param error_callback ErrorCallback to call when the Client gets an error.
- %]
- void SetErrorCallback(ErrorCallback? error_callback);
-
- %[
- Clears the Error callback
-
- NOTE: The client takes ownership of the ErrorCallback you
- pass in. It will be deleted if you call SetErrorCallback a second
- time or if you call ClearErrorCallback.
- %]
- void ClearErrorCallback();
-
- %[
- Makes all parameters get re-evaluated.
- %]
- void InvalidateAllParameters();
-
- %[
- Gets a copy of the current backbuffer of O3D as a data: url.
-
- NOTE: Calling it will cause a render to happen.
-
- \return A Data URL for the backbuffer.
- %]
- String ToDataURL();
-
- %[
- Gets a copy of the current backbuffer of O3D as a data: url.
- \param mime_type The type of data url you want. Currently O3D only supports
- image/png. See HTML5 canvas tag for info about toDataURL.
- \return A Data URL for the backbuffer.
- %]
- [userglue] String ToDataURL(String mime_type);
-
- %[
- Returns the status of initializing the renderer so we can display the
- appropriate message. We require a certain minimum set of graphics
- capabilities. If the user's computer does not have his minimum
- set this will be GPU_NOT_UP_TO_SPEC. If the user is out of graphics
- resources this will be OUT_OF_RESOURCES. If some other error happened this
- will be INITIALIZATION_ERROR. Otherwise it will be SUCCESS.
- %]
- [userglue_getter, getter, plugin_data]
- Renderer::InitStatus renderer_init_status;
-
- %[
- Gets / Sets the cursor's shape.
- Default = DEFAULT.
- %]
- [userglue_getter, userglue_setter, getter, setter, plugin_data]
- Cursor::CursorType cursor;
-
- %[
- Returns the socket address of the IMC message queue associated with the
- Client.
- \return The socket address.
- %]
- [const] String GetMessageQueueAddress();
-
- %[
- The last error reported by the plugin.
- %]
- [userglue_getter, getter] String last_error_;
-
- %[
- All the objects managed by this client.
-
- Each access to this field gets the entire list so it is best to get it
- just once. For example:
- \code
- var objects = client.objects;
- for (var i = 0; i < objects.length; i++) {
- var object = objects[i];
- }
- \endcode
-
- Note that modifications to this array [e.g. push()] will not affect
- the underlying Client, while modifications to the array's members
- <strong>will</strong> affect them.
- %]
- [userglue_getter, getter] ObjectBaseArray objects_;
-
- %[
- Clears the error returned in lastError.
- %]
- void ClearLastError();
-
- %[
- Resets the profiling information.
- %]
- void ProfileReset();
-
- %[
- Returns the profiling information as a string.
- \return The profiling info.
- %]
- String ProfileToString();
-
- %[
- A unique id for this client.
- %]
- [getter=id] Id client_id;
-
- [verbatim=cpp_glue] %{
- o3d::String userglue_getter_last_error_(
- o3d::Client* self) {
- return self->GetLastError();
- }
- o3d::ObjectBaseArray userglue_getter_objects_(
- o3d::Client* self) {
- return self->GetByClass<o3d::ObjectBase>();
- }
- o3d::ClientInfo userglue_getter_client_info(
- void *plugin_data, o3d::Client *self) {
- glue::_o3d::PluginObject *plugin =
- static_cast<glue::_o3d::PluginObject*>(plugin_data);
- o3d::ClientInfoManager* client_info_manager =
- plugin->service_locator()->GetService<o3d::ClientInfoManager>();
- return client_info_manager->client_info();
- }
- std::vector<o3d::DisplayMode> userglue_method_GetDisplayModes(
- void *plugin_data, o3d::Client *self) {
- std::vector<o3d::DisplayMode> modes;
- static_cast<glue::_o3d::PluginObject*>(plugin_data)->GetDisplayModes(
- &modes);
- return modes;
- }
- o3d::String userglue_method_ToDataURL(o3d::Client* self,
- const o3d::String& mime_type) {
- // We ignore the mime_type since it's only a suggestion
- // and we only return the required image/png type.
- return self->ToDataURL();
- }
- void userglue_method_SetFullscreenClickRegion(
- void *plugin_data, o3d::Client *self, int x, int y, int width,
- int height, int mode_id) {
- glue::_o3d::PluginObject *plugin =
- static_cast<glue::_o3d::PluginObject*>(plugin_data);
- if (!plugin->SetFullscreenClickRegion(x, y, width, height, mode_id)) {
- O3D_ERROR(plugin->service_locator())
- << "Call to SetFullscreenClickRegion failed.";
- }
- }
- void userglue_method_ClearFullscreenClickRegion(
- void *plugin_data, o3d::Client *self) {
- static_cast<glue::_o3d::PluginObject*>(plugin_data)->
- ClearFullscreenClickRegion();
- }
- void userglue_method_CancelFullscreenDisplay(
- void *plugin_data, o3d::Client *self) {
- static_cast<glue::_o3d::PluginObject*>(plugin_data)->
- CancelFullscreenDisplay();
- }
- bool userglue_getter_fullscreen(
- void *plugin_data,
- o3d::Client* self) {
- return static_cast<glue::_o3d::PluginObject*>(
- plugin_data)->fullscreen();
- }
- int userglue_getter_width(
- void *plugin_data,
- o3d::Client* self) {
- return static_cast<glue::_o3d::PluginObject*>(
- plugin_data)->width();
- }
- int userglue_getter_height(
- void *plugin_data,
- o3d::Client* self) {
- return static_cast<glue::_o3d::PluginObject*>(
- plugin_data)->height();
- }
- void userglue_setter_cursor(void* plugin_data,
- o3d::Client* self,
- o3d::Cursor::CursorType cursor_type) {
- static_cast<glue::_o3d::PluginObject*>(plugin_data)->set_cursor(
- cursor_type);
- }
- o3d::Cursor::CursorType userglue_getter_cursor(
- void* plugin_data,
- o3d::Client* self) {
- return static_cast<glue::_o3d::PluginObject*>(
- plugin_data)->cursor();
- }
- o3d::Renderer::InitStatus userglue_getter_renderer_init_status(
- void* plugin_data, o3d::Client*) {
- return static_cast<glue::_o3d::PluginObject*>(
- plugin_data)->renderer_init_status();
- }
- %}
-};
-
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/codegen.py b/o3d/plugin/idl/codegen.py
deleted file mode 100644
index d82d7ab..0000000
--- a/o3d/plugin/idl/codegen.py
+++ /dev/null
@@ -1,37 +0,0 @@
-#!/usr/bin/python2.4
-# Copyright 2009 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# This file is just here so that we can modify the python path before
-# invoking nixysa.
-
-import subprocess
-import sys
-import os
-
-script_dir = os.path.join(os.path.dirname(__file__))
-third_party = os.path.normpath(
- os.path.join(script_dir, '..', '..', 'third_party'))
-pythonpath = os.pathsep.join([os.path.join(third_party, 'gflags', 'python'),
- os.path.join(third_party, 'ply')])
-
-orig_pythonpath = os.environ.get('PYTHONPATH')
-if orig_pythonpath:
- pythonpath = os.pathsep.join([pythonpath, orig_pythonpath])
-
-os.environ['PYTHONPATH'] = pythonpath
-
-nixysa = os.path.join(third_party, 'nixysa', 'codegen.py')
-status = subprocess.call([sys.executable, nixysa] + sys.argv[1:])
-sys.exit(status)
diff --git a/o3d/plugin/idl/counter.idl b/o3d/plugin/idl/counter.idl
deleted file mode 100644
index 7cc5d20..0000000
--- a/o3d/plugin/idl/counter.idl
+++ /dev/null
@@ -1,253 +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.
- */
-
-namespace o3d {
-
-typedef float[] NumberArray;
-typedef NumberArray[] NumberArrayArray;
-
-%[
- A Counter counts seconds, ticks or render frames depending on the type of
- counter. You can set where it starts counting from and where it stops counting
- at, whether or not it is running or paused and how it loops or does not loop.
- You can also give it callbacks to call at specific count values.
-
- @o3dparameter running ParamBoolean Whether or not this counter is running.
- @o3dparameter forward ParamBoolean The direction this counter is counting.
- @o3dparameter start ParamFloat The start value for this counter.
- @o3dparameter end ParamFloat The end value for this counter
- @o3dparameter countMode ParamInteger The counting mode for this counter.
- @o3dparameter count ParamFloat The current count for this counter.
- @o3dparameter multiplier ParamFloat The time multiplier for this counter.
-%]
-[nocpp, include="core/cross/counter.h"] class Counter
- : ParamObject {
-
- callback void CounterCallback();
-
- %[
- \var CountMode
- \li CONTINUOUS, Keep running the counter forever.
- \li ONCE, Stop at start or end depending on the direction.
- \li CYCLE, When at end, jump back to start or visa versa.
- \li OSCILLATE, Go from start to end back to start.
- };
- %]
- enum CountMode {
- CONTINUOUS,
- ONCE,
- CYCLE,
- OSCILLATE
- };
-
- %[
- Whether or not this counter is running.
- Default = true.
- %]
- [getter, setter] bool running_;
-
- %[
- Which direction this counter is counting.
- Default = true.
- %]
- [getter, setter] bool forward_;
-
- %[
- The start count for this counter.
- Default = 0.
- %]
- [getter, setter] float start_;
-
- %[
- The end count for this counter.
- Default = 0.
- %]
- [getter, setter] float end_;
-
- %[
- The current count value for this counter.
- Default = 0.
- %]
- [getter] float count_;
-
- %[
- The current count mode for this counter.
- Default = CONTINUOUS.
- %]
- [getter, setter] CountMode count_mode_;
-
- %[
- Sets the current count value for this counter as well as the resetting
- the state of the callbacks.
-
- In other words. Assume start = 1, end = 5, count = 1, and you have a
- callback at 3.
-
- <code>
- myCounter.start = 1;
- myCounter.end = 5;
- myCounter.addCallback(3, myCallback);
- myCounter.reset();
-
- myCounter.advance(2); // count is now 3, myCallback is called.
- myCounter.advance(2); // count is now 5
- </code>
-
- vs.
-
- <code>
- myCounter.start = 1;
- myCounter.end = 5;
- myCounter.addCallback(3, myCallback);
- myCounter.reset();
-
- myCounter.advance(2); // count is now 3, myCallback is called.
- myCounter.setCount(3); // count is now 3, callback state has been reset.
- myCounter.advance(2); // count is now 5, myCallback is called.
- </code>
-
- In the second case myCallback was called twice.
-
- \param count Value to set the count to.
- %]
- void SetCount(float count);
-
- %[
- A multiplier used when advancing the count. The default value is 1.0.
- For example you could set this to 0.5 to run the counter at half speed
- or 2.0 to run it at double speed.
- Default = 1.
- %]
- [getter, setter] float multiplier_;
-
- %[
- Resets the counter back to the start or end time depending on the forward
- setting and also resets the Callback state.
- Note: Reset does not change the running state of the counter.
- %]
- void Reset();
-
- %[
- Advances the counter the given amount. The actual amount advanced depends
- on the forward and multiplier settings. The formula is
-
- <code>
- new_count = count + advance_amount * multiplier * (forward ? 1.0 : -1.0);
- </code>
-
- Any callbacks that fall in the range between the counter's current count and
- the amount advanced will be called.
-
- This function is normally called automatically by the client if the counter
- is set to running = true. but you can call it manually.
-
- \param advance_amount Amount to advance count.
- %]
- [userglue] void Advance(float advance_amount);
-
- %[
- Adds a callback for a given count value. Only one callback can be
- added to a specific count value. If another callback is added with the
- same count value the previous callback for that value will be replaced.
-
- Note: A callback at start will only get called when counting backward, a
- callback at end will only get called counting forward.
-
- \param count Count at which to call callback.
- \param counter_callback Callback to call at given count.
- %]
- void AddCallback(float count, CounterCallback? counter_callback);
-
- %[
- Removes a callback for a given count value.
-
- \param count Count to remove callback for,
- \return true if there was a callback for that count, false if there was not
- a callback for that count.
- %]
- bool RemoveCallback(float count);
-
- %[
- Removes all the callbacks on this counter.
- %]
- void RemoveAllCallbacks();
-
- %[
- Returns all the counts for which all callback has been added.
- \return Array of counts.
- %]
- [userglue, const] NumberArray GetCallbackCounts();
-
- [verbatim=cpp_glue] %{
- // This is userglue because we need to force the client to call any
- // callbacks that need to be called as a result of the advance.
- void userglue_method_Advance(o3d::Counter* self,
- float advance_amount) {
- o3d::Counter::CounterCallbackQueue queue;
- self->Advance(advance_amount, &queue);
- queue.CallCounterCallbacks();
- }
- std::vector<float> userglue_method_GetCallbackCounts(
- o3d::Counter* self) {
- const o3d::Counter::CounterCallbackInfoArray& callbacks =
- self->GetCallbacks();
- std::vector<float> float_array;
- float_array.reserve(callbacks.size());
- for (unsigned ii = 0; ii < callbacks.size(); ++ii) {
- float_array.push_back(callbacks[ii].count());
- }
- return float_array;
- }
- %}
-}; // Counter
-
-%[
- A Counter that counts seconds.
-%]
-[nocpp, include="core/cross/counter.h"] class SecondCounter
- : Counter {
-}; // SecondCounter
-
-%[
- A Counter that counts render frames.
-%]
-[nocpp, include="core/cross/counter.h"] class RenderFrameCounter
- : Counter {
-}; // RenderFrameCounter
-
-%[
- A Counter that counts ticks.
-%]
-[nocpp, include="core/cross/counter.h"] class TickCounter
- : Counter {
-}; // TickCounter
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/cursor.idl b/o3d/plugin/idl/cursor.idl
deleted file mode 100644
index 9899bba..0000000
--- a/o3d/plugin/idl/cursor.idl
+++ /dev/null
@@ -1,82 +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 IDL declaration of the CursorType enumeration.
-
-namespace o3d {
-
-[include="core/cross/cursor.h"]
-namespace Cursor {
-
-%[
- \var CursorType
- \li DEFAULT
- \li NONE
- \li CROSSHAIR
- \li POINTER
- \li E_RESIZE
- \li NE_RESIZE
- \li NW_RESIZE
- \li N_RESIZE
- \li SE_RESIZE
- \li SW_RESIZE
- \li S_RESIZE
- \li W_RESIZE
- \li MOVE
- \li TEXT
- \li WAIT
- \li PROGRESS
- \li HELP
-%]
-enum CursorType {
- DEFAULT,
- NONE,
- CROSSHAIR,
- POINTER,
- E_RESIZE,
- NE_RESIZE,
- NW_RESIZE,
- N_RESIZE,
- SE_RESIZE,
- SW_RESIZE,
- S_RESIZE,
- W_RESIZE,
- MOVE,
- TEXT,
- WAIT,
- PROGRESS,
- HELP
-};
-
-} // namespace Cursor
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/curve.idl b/o3d/plugin/idl/curve.idl
deleted file mode 100644
index eacb901..0000000
--- a/o3d/plugin/idl/curve.idl
+++ /dev/null
@@ -1,330 +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.
- */
-
-namespace o3d {
-
-%[
- A CurveKey prepresents a key on an Curve.
-%]
-[nocpp, include="core/cross/curve.h"]
-class CurveKey : ObjectBase {
-
- %[
- The input of this key.
- %]
- [getter, setter, userglue_setter] float input;
-
- %[
- The output of this key.
- %]
- [getter, setter, userglue_setter] float output;
-
- %[
- Destroys this key, removing it from its owner.
- %]
- void Destroy();
-
- [verbatim=cpp_glue] %{
- void userglue_setter_input(o3d::CurveKey* self, float value) {
- self->SetInput(value);
- }
- void userglue_setter_output(o3d::CurveKey* self, float value) {
- self->SetOutput(value);
- }
- %}
-}; // CurveKey
-
-typedef CurveKey[] CurveKeyArray;
-
-%[
- An CurveKey that holds its output (is not interpolated between this key
- and the next.)
-%]
-[nocpp, include="core/cross/curve.h"]
-class StepCurveKey : CurveKey {
-};
-
-%[
- An CurveKey that linearly interpolates between this key and the next key.
-%]
-[nocpp, include="core/cross/curve.h"]
-class LinearCurveKey : CurveKey {
-};
-
-%[
- An CurveKey that uses a bezier curve for interpolation between this key
- and the next.
-%]
-[nocpp, include="core/cross/curve.h"]
-class BezierCurveKey : CurveKey {
- %[
- The in tangent for this key.
- %]
- [setter, getter, userglue_setter] Float2 in_tangent;
-
- %[
- The out tangent for this key.
- %]
- [setter, getter, userglue_setter] Float2 out_tangent;
-
- [verbatim=cpp_glue] %{
- void userglue_setter_in_tangent(o3d::BezierCurveKey* self,
- const o3d::Float2& tangent) {
- self->SetInTangent(tangent);
- }
- void userglue_setter_out_tangent(o3d::BezierCurveKey* self,
- const o3d::Float2& tangent) {
- self->SetOutTangent(tangent);
- }
- %}
-};
-
-%[
- A Curve stores a bunch of CurveKeys and given a value
- representing an input point on a curve returns the output of the curve for
- that input. Curve is data only. It is used by 1 or more
- FunctionEval objects or by direct use from javascript.
-%]
-[nocpp, include="core/cross/curve.h"]
-class Curve : Function {
- %[
- enum Infinity {
- \li CONSTANT, Uses the output value of the first or last animation key.
- \li LINEAR, Takes the distance between the closest animation key
- input value and the evaluation time. Multiplies this
- distance against the instant slope at the closest
- animation key and offsets the result with the closest
- animation key output value.
- \li CYCLE, Cycles over the first and last keys using
- input = (input - first) % (last - first) + first;
- Note that in CYCLE mode you can never get the end output
- because a cycle goes from start to end exclusive of end.
- \li CYCLE_RELATIVE, Same as cycle except the offset of the entire
- cycle is added to each consecutive cycle.
- \li OSCILLATE, Ping Pongs between the first and last keys.
- };
- %]
- enum Infinity {
- CONSTANT,
- LINEAR,
- CYCLE,
- CYCLE_RELATIVE,
- OSCILLATE
- };
-
- %[
- The behavior of the curve before the first key.
- Default = CONSTANT.
- %]
- [getter, setter] Infinity pre_infinity;
-
- %[
- The behavior of the curve after the last key.
- Default = CONSTANT.
- %]
- [getter, setter] Infinity post_infinity;
-
- %[
- Whether or not a cache is used to speed up evaluation of this Curve
- Default = true.
- \sa o3d.Curve.sampleRate
- %]
- [getter, setter] bool use_cache;
-
- %[
- Gets the sample rate for the cache. By default Animation data is
- cached so that using the animation is fast. To do this the keys that
- represent the animation are sampled. The higher the frequency of the
- samples the closer the cache will match the actual keys.
- The default is 1/30 (30hz). You can set it anywhere from 1/240th (240hz) to
- any larger value. Note: Setting the sample rate has the side effect of
- invalidating the cache thereby causing it to get rebuilt.
- Must be 1/240 or greater. Default = 1/30.
- %]
- [getter, setter, userglue_setter] float sample_rate;
-
- %[
- Returns whether or not the curve is discontinuous. A discontinuous curve
- takes more time to evaluate.
- \return True if the curve is discontinuous.
- %]
- [const] bool IsDiscontinuous();
-
- %[
- The keys for this curve.
- %]
- [const, getter, userglue_getter] CurveKeyArray keys;
-
- %[
- Adds 1 or more StepKeys to this Curve.
-
- Example:
- \code
- // Creates 2 keys.
- // 1 key at 0 with an output of 10
- // 1 key at 20 with an output of 30
- curve.addStepKeys([0,10,20,30]);
- \endcode.
-
- \param keys Array of input, output pairs.
- %]
- [userglue] void AddStepKeys(NumberArray keys);
-
- %[
- Adds 1 or more LinearKeys to this Curve.
-
- Example:
- \code
- // Creates 2 keys.
- // 1 key at 0 with an output of 10
- // 1 key at 20 with an output of 30
- curve.addLinearKeys([0,10,20,30]);
- \endcode.
-
- \param keys Array of input, output pairs.
- %]
- [userglue] void AddLinearKeys(NumberArray keys);
-
- %[
- Adds 1 or more BezierKeys to this Curve.
-
- Example:
- \code
- // Creates 2 keys.
- // 1 key at 0 with an output of 10, in tangent of 1,9, out tangent 9,0.5
- // 1 key at 20 with an output of 30, in tangent of 30, 3, out tangent 4, 28
- curve.addBezierKeys([0,10,1,9,9,0.5,2,30,3,4,28]);
- \endcode.
-
- \param keys Array of input, output pairs.
- %]
- [userglue] void AddBezierKeys(NumberArray keys);
-
- %[
- Creates a new key for this curve.
- \param key_type name of key class to create. Valid type names are:
- \li 'o3d.StepCurveKey',
- \li 'o3d.LinearCurveKey',
- \li 'o3d.BezierCurveKey',
- \return The created key.
- %]
- [userglue] CurveKey CreateKey(String key_type);
-
- %[
- Deserializes from the curve data given a RawData object.
-
- \param raw_data contains curve data
- \param offset is a byte offset from the start of raw_data
- \param length is the byte length of the data to set
- \return True if operation was successful.
- %]
- bool Set(o3d::RawData raw_data,
- size_t offset,
- size_t length);
-
- %[
- Deserializes from the curve data given a RawData object.
- \param raw_data entire contents contains curve data
- \return True if operation was successful.
- %]
- bool Set(o3d::RawData raw_data);
-
- [verbatim=cpp_glue] %{
- void userglue_setter_sample_rate(o3d::Curve* self, float rate) {
- self->SetSampleRate(rate);
- }
- o3d::CurveKey* userglue_method_CreateKey(o3d::Curve* self,
- o3d::String& key_type) {
- return self->CreateKeyByClassName(key_type);
- }
- void userglue_method_AddStepKeys(o3d::Curve* self,
- const std::vector<float>& values) {
- const int kNumStepKeyValues = 2;
- if (values.size() % kNumStepKeyValues != 0) {
- O3D_ERROR(self->service_locator())
- << "expected multiple of 2 values got " << values.size();
- } else {
- for (unsigned ii = 0; ii < values.size(); ii += kNumStepKeyValues) {
- o3d::StepCurveKey* key = self->Create<o3d::StepCurveKey>();
- key->SetInput(values[ii]);
- key->SetOutput(values[ii + 1]);
- }
- }
- }
- void userglue_method_AddLinearKeys(o3d::Curve* self,
- const std::vector<float>& values) {
- const int kNumLinearKeyValues = 2;
- if (values.size() % kNumLinearKeyValues != 0) {
- O3D_ERROR(self->service_locator())
- << "expected multiple of 2 values got " << values.size();
- } else {
- for (unsigned ii = 0; ii < values.size(); ii += kNumLinearKeyValues) {
- o3d::LinearCurveKey* key =
- self->Create<o3d::LinearCurveKey>();
- key->SetInput(values[ii]);
- key->SetOutput(values[ii + 1]);
- }
- }
- }
- void userglue_method_AddBezierKeys(o3d::Curve* self,
- const std::vector<float>& values) {
- const int kNumBezierKeyValues = 6;
- if (values.size() % kNumBezierKeyValues != 0) {
- O3D_ERROR(self->service_locator())
- << "expected multiple of 6 values got " << values.size();
- } else {
- for (unsigned ii = 0; ii < values.size(); ii += kNumBezierKeyValues) {
- o3d::BezierCurveKey* key =
- self->Create<o3d::BezierCurveKey>();
- key->SetInput(values[ii]);
- key->SetOutput(values[ii + 1]);
- key->SetInTangent(o3d::Float2(values[ii + 2],
- values[ii + 3]));
- key->SetOutTangent(o3d::Float2(values[ii + 4],
- values[ii + 5]));
- }
- }
- }
- o3d::CurveKeyArray userglue_getter_keys(o3d::Curve* self) {
- const o3d::CurveKeyRefArray& source_keys = self->keys();
- o3d::CurveKeyArray keys;
- keys.reserve(source_keys.size());
- for (unsigned ii = 0; ii < source_keys.size(); ++ii) {
- keys.push_back(source_keys[ii].Get());
- }
- return keys;
- }
- %}
-}; // Curve
-
-} // namespace o3d
-
-
diff --git a/o3d/plugin/idl/display_mode.idl b/o3d/plugin/idl/display_mode.idl
deleted file mode 100644
index 9f5efd7..0000000
--- a/o3d/plugin/idl/display_mode.idl
+++ /dev/null
@@ -1,64 +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.
- */
-
-namespace o3d {
-
-%[
- A DisplayMode describes the size and refresh rate of a display mode; it's
- usually used in [or when transitioning into] fullscreen mode.%]
-
-[binding_model=by_value, nocpp, include="core/cross/display_mode.h"]
-class DisplayMode {
-
- %[
- The width in pixels of the screen when in this mode.
- %]
- [getter] int width;
-
- %[
- The height in pixels of the screen when in this mode.
- %]
- [getter] int height;
-
- %[
- The refresh rate in Hz.
- %]
- [getter] int refresh_rate;
-
- %[
- An opaque identifier used to identify the mode when requesting a fullscreen
- transition.
- %]
- [getter] int id;
-
-}; // DisplayMode
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/draw_context.idl b/o3d/plugin/idl/draw_context.idl
deleted file mode 100644
index 5141d37..0000000
--- a/o3d/plugin/idl/draw_context.idl
+++ /dev/null
@@ -1,63 +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.
- */
-
-namespace o3d {
-
-%[
- The DrawContext defines the parameters used for a particular drawing pass.
- It contains two 4-by-4 matrix params, view and
- projection. These correspond to the viewing and projection transformation
- matrices.
-
- @o3dparameter view ParamMatrix4 The view matrix for this DrawContext.
- @o3dparameter projection ParamMatrix4 The projection matrix for this
- DrawContext.
-%]
-
-[nocpp, include="core/cross/draw_context.h"] class DrawContext
- : ParamObject {
- %[
- The view matrix represents the viewing transformation, used to take vertices
- from world space to view space.
- Default = Identity.
- %]
- [getter, setter] Vectormath::Aos::Matrix4 view;
-
- %[
- The projection matrix represents the projection transformation, used to take
- vertices from view space to screen space. This matrix is usually an
- orthographic or perspective transformation.
- Default = Identity.
- %]
- [getter, setter] Vectormath::Aos::Matrix4 projection;
-}; // DrawContext
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/draw_element.idl b/o3d/plugin/idl/draw_element.idl
deleted file mode 100644
index 5181f32..0000000
--- a/o3d/plugin/idl/draw_element.idl
+++ /dev/null
@@ -1,77 +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.
- */
-
-namespace o3d {
-
-%[
- A DrawElement causes an Element to be Drawn with a particular material.
- You can override other Effect parameters by adding corresponding params to
- the DrawElement.
-
- \sa o3d.Element
- \sa o3d.Material
- \sa o3d.Effect
-
- @o3dparameter material ParamMaterial The material used to render this
- the Element that owns this DrawElement.
-%]
-[nocpp, include="core/cross/material.h"] class DrawElement
- : ParamObject {
-
- %[
- The Material for this DrawElement. If it is null the material of owner will
- be used.
- %]
- [getter, setter] Material? material_;
-
- %[
- The current owner of this Draw Element. Set to null to stop being owned.
-
- Note: DrawElements are referenced by the Pack they are created in and their
- owner. If the DrawElement is removed from its Pack then setting the owner
- to null will free the DrawElement. Or, visa versa, if you set the
- DrawElement's owner to null then removing it from its Pack will free the
- DrawElement.
- %]
- [getter, setter, userglue_setter] Element? owner_;
-
- [verbatim=cpp_glue] %{
- void userglue_setter_owner_(
- o3d::DrawElement* _this,
- o3d::Element* owner) {
- _this->SetOwner(owner);
- }
- %}
-}; // DrawElement
-
-typedef DrawElement[] DrawElementArray;
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/draw_list.idl b/o3d/plugin/idl/draw_list.idl
deleted file mode 100644
index 66fdcb74..0000000
--- a/o3d/plugin/idl/draw_list.idl
+++ /dev/null
@@ -1,56 +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.
- */
-
-namespace o3d {
-
-%[
- A DrawList gets used during rendering to collect DrawElements to
- render. Each Material references a DrawList. Depending on the material, as
- DrawElements get collected they will be put on different DrawLists.
-%]
-[nocpp, include="core/cross/draw_list.h"] class DrawList
- : NamedObject {
- %[
- \var SortMethod,
- \li BY_PERFORMANCE
- \li BY_Z_ORDER
- \li BY_PRIORITY
-
- Method to sort DrawList by.
- %]
- enum SortMethod {
- BY_PERFORMANCE = 0,
- BY_Z_ORDER = 1,
- BY_PRIORITY = 2
- };
-}; // DrawList
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/draw_pass.idl b/o3d/plugin/idl/draw_pass.idl
deleted file mode 100644
index c627151..0000000
--- a/o3d/plugin/idl/draw_pass.idl
+++ /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.
- */
-
-namespace o3d {
-
-%[
- A DrawPass renders a DrawList.
-
- @o3dparameter drawList ParamDrawList The DrawList used by this DrawPass.
- @o3dparameter sortMethod ParamInteger The method of sorting this DrawPass.
-%]
-[nocpp, include="core/cross/draw_pass.h"] class DrawPass
- : RenderNode {
- %[
- The DrawList for this DrawPass.
- %]
- [getter, setter] DrawList? draw_list_;
-
- %[
- The sort method for this DrawPass to draw the DrawList by.
- Default = BY_PERFORMANCE.
- \sa o3d.DrawList
- %]
- [getter, setter] DrawList::SortMethod sort_method_;
-}; // Material
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/effect.idl b/o3d/plugin/idl/effect.idl
deleted file mode 100644
index 808671e..0000000
--- a/o3d/plugin/idl/effect.idl
+++ /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.
- */
-
-namespace o3d {
-
-%[
- EffectParameterInfo holds information about the Parameters an Effect needs.
- \sa o3d.Effect.getParameterInfo
-%]
-[binding_model=by_value, nocpp, include="core/cross/effect.h"]
-class EffectParameterInfo {
- %[
- The name of the parameter.
- %]
- [getter] String name;
-
- %[
- The type of the parameter.
- %]
- [userglue_getter, getter] String class_name;
-
- %[
- The number of elements. Non-zero for array types, zero for non-array types.
- %]
- [getter] int num_elements;
-
- %[
- The semantic of the parameter. This is always in UPPERCASE.
- %]
- [getter] String semantic;
-
- %[
- If this is a standard parameter (SAS) this will be the name of the type
- of Param needed. Otherwise it will be the empty string.
-
- Standard Parameters are generally handled automatically by o3d but you
- can supply your own if you have a unique situation.
- %]
- [userglue_getter, getter] String sas_class_name;
-
- [verbatim=cpp_glue] %{
- o3d::String userglue_getter_class_name(
- const o3d::EffectParameterInfo& self) {
- return self.class_type()->name();
- }
- o3d::String userglue_getter_sas_class_name(
- const o3d::EffectParameterInfo& self) {
- return self.sas_class_type() ? self.sas_class_type()->name() : "";
- }
- %}
-};
-
-typedef EffectParameterInfo[] EffectParameterInfoArray;
-
-%[
- EffectStreamInfo holds information about the Streams an Effect needs.
- \sa o3d.Effect.getStreamInfo
-%]
-[binding_model=by_value, nocpp, include="core/cross/effect.h"]
-class EffectStreamInfo {
- %[
- The semantic of the stream.
- %]
- [getter] Stream::Semantic semantic;
-
- %[
- The semantic index of the stream.
- %]
- [getter] int semantic_index;
-};
-
-typedef EffectStreamInfo[] EffectStreamInfoArray;
-
-%[
- An Effect contains a vertex and pixel shader.
-%]
-
-[nocpp, include="core/cross/effect.h"] class Effect : ParamObject {
- %[
- Loads the vertex and pixel shader programs from an string containing
- an O3D FX description.
-
- The string is subset of CG and HLSL. No techinques are allowed.
-
- To define the entry points add 2 lines in the following format.
- \code
- "// #o3d VertexShaderEntryPoint myVertexShader\n"
- "// #o3d PixelShaderEntryPoint myPixelShader\n"
- \endcode
-
- where "myVertexShader" and "myPixelShader" are the names of your
- vertex and pixel shaders. At this time the format of those 2 lines
- is extremely strict. You must have 1 and exactly 1 space between // and
- #o3d, between #o3d and
- VertexShaderEntryPoint/PixelShaderEntryPoint and between those and your
- entry points.
-
- You must also specify a matrix load order like this.
-
- \code
- // #o3d MatrixLoadOrder RowMajor
- \endcode
-
- Valid orders are RowMajor and ColumnMajor
-
- Note: Currently it is possible to create effects strings that work on only
- one platform (GL or D3D). You should test your shaders on both platforms.
-
- By version 1.0 this function will enforce shaders
- that only work on both platforms. That format is mostly CG.
-
- \param effect the code of the effect.
- \return True if successful.
- %]
- [virtual, pure] bool LoadFromFXString(String effect);
-
- %[
- For each of the effect's uniform parameters, creates corresponding
- parameters on the given ParamObject. Skips SAS Parameters.
-
- If a Param with the same name but the wrong type already exists on the
- given ParamObject CreateUniformParameters will attempt to replace it with
- one of the correct type.
-
- Note: The most common thing to pass to this function is a Material but
- depending on your application it may be more appropriate to pass in a
- Transform, Effect, Element or DrawElement.
-
- \param param_object The param object on which the new paramters will be
- created.
- \sa o3d.Effect.createSASParameters
- %]
- void CreateUniformParameters(ParamObject param_object);
-
- %[
- For each of the effect's uniform parameters, if it is a SAS parameter
- creates corresponding StandardParamMatrix4 parameters on the given
- ParamObject. Note that SAS parameters are handled automatically by the
- rendering system. so except in some rare cases there is no reason to call
- this function. Also be aware that the StandardParamMatrix4 Paramters like
- WorldViewProjectionParamMatrix4, etc.. are only valid during rendering.
- At all other times they will not return valid values.
-
- If a Param with the same name but the wrong type already exists on the
- given ParamObject CreateSASParameters will attempt to replace it with
- one of the correct type.
-
- \param param_object The param object on which the new paramters will be
- created.
- \sa o3d.Effect.createUniformParameters
- %]
- void CreateSASParameters(ParamObject param_object);
-
- %[
- Gets info about the parameters this effect needs.
- \return an array of EffectParameterInfos.
- %]
- [userglue] EffectParameterInfoArray GetParameterInfo();
-
- %[
- Gets info about the streams this effect needs.
- \return an array of EffectParameterInfos.
- %]
- [userglue] EffectStreamInfoArray GetStreamInfo();
-
- %[
- \var MatrixLoadOrder,
- \li ROW_MAJOR, Matrix parameters are loaded in row-major order (DX-style).
- \li COLUMN_MAJOR, Matrix parameters are loaded in column-major order
- (OpenGL-style).
- %]
- enum MatrixLoadOrder {
- ROW_MAJOR,
- COLUMN_MAJOR
- };
-
- %[
- The order in which matrix data is loaded to the GPU.
- %]
- [getter] MatrixLoadOrder matrix_load_order_;
-
- %[
- The source for the shaders on this Effect.
- %]
- [getter] String source_;
-
- [verbatim=cpp_glue] %{
- std::vector<o3d::EffectParameterInfo> userglue_method_GetParameterInfo(
- o3d::Effect* self) {
- std::vector<o3d::EffectParameterInfo> info_array;
- self->GetParameterInfo(&info_array);
- return info_array;
- }
- std::vector<o3d::EffectStreamInfo> userglue_method_GetStreamInfo(
- o3d::Effect* self) {
- std::vector<o3d::EffectStreamInfo> info_array;
- self->GetStreamInfo(&info_array);
- return info_array;
- }
- %}
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/element.idl b/o3d/plugin/idl/element.idl
deleted file mode 100644
index 9e2a5f1..0000000
--- a/o3d/plugin/idl/element.idl
+++ /dev/null
@@ -1,185 +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.
- */
-
-namespace o3d {
-
-typedef DrawElement[] DrawElementArray;
-
-%[
- An Element manages DrawElements for classes inherited from Element.
-
- @o3dparameter material ParamMaterial The Material used by this Element.
- @o3dparameter boundingBox ParamBoundingBox The BoundingBox used by this
- Element for culling.
- @o3dparameter zSortPoint ParamFloat3 The point to sort by when rendering this
- Element in a z ordered DrawPass.
- @o3dparameter cull ParamBoolean Whether or not to attempt to cull this
- element based on whether or not its bounding box is in the view frustum.
-%]
-[nocpp, include="core/cross/element.h"] class Element : ParamObject {
-
- %[
- The Material for this element.
- %]
- [getter, setter] Material? material_;
-
- %[
- The BoundingBox for this element. If culling is on this bounding box will be
- tested against the view frustum of any draw context used to render this
- Element.
- Default = [[0, 0, 0], [0, 0, 0]].
- %]
- [getter, setter] BoundingBox bounding_box_;
-
- %[
- The z sort point for this element. If this Element is drawn by a DrawPass
- that is set to sort by z order this value will be multiplied by the
- worldViewProjection matrix to compute a z value to sort by.
- Default = [0, 0, 0].
- %]
- [getter, setter] Float3 z_sort_point;
-
- %[
- The priority for this element. Used to sort if this Element is drawn by a
- DrawPass that is set to sort by priority.
- Default = 0.
- %]
- [getter, setter] float priority_;
-
- %[
- The cull settings for this element. If true this Element will be culled
- by the bounding box above compared to the view frustum it is being rendered
- with.
- Default = false.
- %]
- [getter, setter] bool cull_;
-
- %[
- The current owner of this Draw Element. Pass in null to stop being owned.
-
- Note: Elements are referenced by the Pack they are created in and their
- owner. If the Element is removed from its Pack then setting the owner
- to null will free the Element. Or, visa versa, if you set the
- Element's owner to null then removing it from its Pack will free the
- Element.
- %]
- [getter, setter, userglue_setter] Shape? owner_;
-
- %[
- Gets all the DrawElements under this Element.
-
- Each access to this field gets the entire list so it is best to get it
- just once. For example:
- \code
- var drawElements = element.drawElements;
- for (var i = 0; i < drawElements.length; i++) {
- var drawElement = drawElements[i];
- }
- \endcode
-
- Note that modifications to this array [e.g. push()] will not affect
- the underlying Element, while modifications to the members of the array.
- <strong>will</strong> affect them.
- %]
- [userglue_getter, getter] DrawElementArray draw_elements_;
-
- %[
- Creates a DrawElement for this Element. Note that unlike
- Shape.createDrawElements and Transform.createDrawElements this one will
- create more than one element for the same material.
-
- \param pack pack used to manage created DrawElement.
- \param material material to use for DrawElement. If you pass null
- it will use the material on this Element. This allows you to easily
- setup the default (just draw as is) by passing null or setup a shadow
- pass by passing in a shadow material.
- \return The created draw element.
- %]
- DrawElement CreateDrawElement(Pack pack,
- Material? material);
-
- %[
- Computes the intersection of a ray in the same coordinate system as
- the specified POSITION stream.
- \param position_stream_index Index of POSITION stream.
- \param cull which side of the triangles to ignore.
- \param start position of start of ray in local space.
- \param end position of end of ray. in local space.
- \return RayIntersectionInfo class. If valid() is false then something
- was wrong, Check client::GetLastError(). If intersected() is true then
- the ray intersected a something. position() is the exact point of
- intersection.
- %]
- [const, userglue] RayIntersectionInfo IntersectRay(
- int position_stream_index,
- State::Cull cull,
- Vectormath::Aos::Point3 start,
- Vectormath::Aos::Point3 end);
-
- %[
- Computes the bounding box in same coordinate system as the specified
- POSITION stream.
- \param position_stream_index Index of POSITION stream.
- \return The boundingbox for this element in local space.
- %]
- [const, userglue] BoundingBox GetBoundingBox(int position_stream_index);
-
- [verbatim=cpp_glue] %{
- void userglue_setter_owner_(
- o3d::Element* _this,
- o3d::Shape* owner) {
- _this->SetOwner(owner);
- }
- o3d::RayIntersectionInfo userglue_method_IntersectRay(
- o3d::Element* self,
- int semantic_index,
- o3d::State::Cull cull,
- const Vectormath::Aos::Point3& start,
- const Vectormath::Aos::Point3& end) {
- o3d::RayIntersectionInfo result;
- self->IntersectRay(semantic_index, cull, start, end, &result);
- return result;
- }
- o3d::BoundingBox userglue_method_GetBoundingBox(
- o3d::Element* self,
- int semantic_index) {
- o3d::BoundingBox result;
- self->GetBoundingBox(semantic_index, &result);
- return result;
- }
- o3d::DrawElementArray userglue_getter_draw_elements_(
- o3d::Element* self) {
- return self->GetDrawElements();
- }
- %}
-}; // Element
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/event.idl b/o3d/plugin/idl/event.idl
deleted file mode 100644
index ba6f315..0000000
--- a/o3d/plugin/idl/event.idl
+++ /dev/null
@@ -1,186 +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 public interface specification for the event object
-// passed to event handlers by the client.
-
-namespace o3d {
-
-%[
- An Event object contains information describing a JavaScript event; it's used
- as an argument to event handlers triggered by the plugin.%]
-
-[binding_model=by_value, nocpp, include="core/cross/event.h"]
-class Event {
-
- %[
- String identifiers for JavaScript events.
- \var type
- \li invalid
- \li click
- \li dblclick
- \li mousedown
- \li mousemove
- \li mouseup
- \li wheel
- \li keydown
- \li keypress
- \li keyup
- \li resize
- %]
- enum Type {
- TYPE_INVALID,
- TYPE_CLICK,
- TYPE_DBLCLICK,
- TYPE_MOUSEDOWN,
- TYPE_MOUSEMOVE,
- TYPE_MOUSEUP,
- TYPE_WHEEL,
- TYPE_KEYDOWN,
- TYPE_KEYPRESS,
- TYPE_KEYUP,
- TYPE_RESIZE
- };
- %[
- The type of event this object represents.
- \var type
- \li invalid
- \li click
- \li dblclick
- \li keydown
- \li keypress
- \li keyup
- \li mousedown
- \li mousemove
- \li mouseup
- \li wheel
- \li resize
- %]
- [userglue_getter, getter] String type;
- %[
- \var Button,
- \li BUTTON_LEFT
- \li BUTTON_RIGHT
- \li BUTTON_MIDDLE
- \li BUTTON_4
- \li BUTTON_5
- Constants used to identify mouse buttons.
- %]
- enum Button {
- BUTTON_LEFT = 0,
- BUTTON_MIDDLE = 1,
- BUTTON_RIGHT = 2,
- BUTTON_4 = 3,
- BUTTON_5 = 4
- };
- %[
- Which mouse button caused the event, in the case of mousedown, mouseup,
- click, and dblclick events. This uses the values in enum Button.
- %]
- [getter] int button;
- %[
- Whether the ctrl key was pressed at the time of the event.
- %]
- [getter] bool ctrl_key;
- %[
- Whether the alt [option, on OSX] key was pressed at the time of the event.
- %]
- [getter] bool alt_key;
- %[
- Whether the shift key was pressed at the time of the event.
- %]
- [getter] bool shift_key;
- %[
- Whether the meta [command, on OSX] key was pressed at the time of the event.
- %]
- [getter] bool meta_key;
- %[
- The key code of the key pressed or released.
- %]
- [getter] int key_code;
- %[
- The character created by a keypress event.
- %]
- [getter, property=r] int char_code;
- %[
- The x-coordinate in pixels from the left side of the plugin or fullscreen
- display region.
- %]
- [getter] int x;
- %[
- The y-coordinate in pixels from the top of the plugin or fullscreen
- display region.
- %]
- [getter] int y;
- %[
- The x-coordinate in pixels from the left side of the screen.
- %]
- [getter] int screen_x;
- %[
- The y-coordinate in pixels from the top of the screen.
- %]
- [getter] int screen_y;
- %[
- The horizontal scroll offset for wheel events, in arbitrary units.
- Positive values mean right; negative mean left.
- %]
- [getter] int delta_x;
- %[
- The vertical scroll offset for wheel events, in arbitrary units.
- Positive values mean up or away from the user; negative mean down or toward
- the user.
- %]
- [getter] int delta_y;
- %[
- The width in pixels of the plugin or fullscreen display region as a result
- of this event.
- %]
- [getter] int width;
- %[
- The height in pixels of the plugin or fullscreen display region as a result
- of this event.
- %]
- [getter] int height;
- %[
- Whether we're currently displaying in fullscreen mode.
- %]
- [getter] bool fullscreen;
-
- [verbatim=cpp_glue] %{
- o3d::String userglue_getter_type(
- const o3d::Event& self) {
- return self.type_string();
- }
- %}
-}; // Event
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/field.idl b/o3d/plugin/idl/field.idl
deleted file mode 100644
index 4c68b9b..0000000
--- a/o3d/plugin/idl/field.idl
+++ /dev/null
@@ -1,245 +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.
- */
-
-namespace o3d {
-
-%[
- A Field is a base class that manages a set of components in a
- Buffer of a specific type. Fields are managed by Buffers and can not be
- directly created. When a Buffer is destroyed or if a Field is removed from a
- Buffer the Field's buffer property will be set to null.
-%]
-[nocpp, include="core/cross/buffer.h"]
-class Field : NamedObject {
- %[
- The number of components in this field.
- %]
- [getter] unsigned int num_components;
-
- %[
- The Buffer the field belongs to.
- %]
- [getter] Buffer? buffer;
-
- %[
- The offset of this field in the Buffer in bytes.
- %]
- [getter] unsigned int offset;
-
- %[
- The size of one element of this field.
- %]
- [getter] unsigned int size;
-};
-
-%[
- A field that contains floating point numbers.
-%]
-[nocpp, include="core/cross/buffer.h"]
-class FloatField : Field {
- %[
- Sets the values of the data stored in the field.
-
- The buffer for the field must have already been created either through
- buffer.set or through buffer.allocateElements.
-
- The number of values passed in must be a multiple of the number of
- components needed for the field.
-
- \param start_index index of first value to set.
- \param values Values to be stored in the buffer starting at index.
- %]
- [userglue] void SetAt(unsigned int start_index, float[] values);
-
- %[
- Gets the values stored in the field.
-
- \param start_index index of the first value to get.
- \param num_elements number of elements to read from field.
- \return The values of the field.
- %]
- [userglue] float[] GetAt(unsigned int start_index, unsigned int num_elements);
-
- [verbatim=cpp_glue] %{
- void userglue_method_SetAt(o3d::FloatField* field,
- unsigned int start_index,
- const std::vector<float>& values) {
- if (values.size() % field->num_components() != 0) {
- O3D_ERROR(field->service_locator())
- << "the number of values passed in is not a multiple of the number"
- << " of components in the field.";
- return;
- }
- if (!values.empty()) {
- field->SetFromFloats(&values[0], field->num_components(), start_index,
- values.size() / field->num_components());
- }
- }
- std::vector<float> userglue_method_GetAt(
- o3d::FloatField* field,
- unsigned int start_index,
- unsigned int num_elements) {
- std::vector<float> retval;
- if (field->RangeValid(start_index, num_elements)) {
- retval.resize(num_elements * field->num_components());
- field->GetAsFloats(start_index, &retval[0], field->num_components(),
- num_elements);
- }
- return retval;
- }
- %}
-};
-
-%[
- A field that contains unsigned integers.
-%]
-[nocpp, include="core/cross/buffer.h"]
-class UInt32Field : Field {
- %[
- Sets the values of the data stored in the field.
-
- The buffer for the field must have already been created either through
- buffer.set or through buffer.allocateElements.
-
- The number of values passed in must be a multiple of the number of
- components needed for the field.
-
- \param start_index index of first value to set.
- \param values Values to be stored in the buffer starting at index.
- %]
- [userglue] void SetAt(unsigned int start_index, unsigned int[] values);
-
- %[
- Gets the values stored in the field.
-
- \param start_index index of the first value to get.
- \param num_elements number of elements to read from field.
- \return The values of the field.
- %]
- [userglue] unsigned int[] GetAt(unsigned int start_index,
- unsigned int num_elements);
-
- [verbatim=cpp_glue] %{
- void userglue_method_SetAt(o3d::UInt32Field* field,
- unsigned int start_index,
- const std::vector<unsigned int>& values) {
- if (values.size() % field->num_components() != 0) {
- O3D_ERROR(field->service_locator())
- << "the number of values passed in is not a multiple of the number"
- << " of components in the field.";
- return;
- }
- if (!values.empty()) {
- field->SetFromUInt32s(&values[0], field->num_components(), start_index,
- values.size() / field->num_components());
- }
- }
- std::vector<uint32> userglue_method_GetAt(
- o3d::UInt32Field* field,
- unsigned int start_index,
- unsigned int num_elements) {
- std::vector<uint32> retval;
- if (field->RangeValid(start_index, num_elements)) {
- retval.resize(num_elements * field->num_components());
- field->GetAsUInt32s(start_index, &retval[0], field->num_components(),
- num_elements);
- }
- return retval;
- }
- %}
-};
-
-%[
- A field that contains unsigned bytes that each represent a 0 to 1 value.
- A typical use is for vertex colors since 4 bytes per vertex color are much
- smaller than 4 floats per vertex color.
-%]
-[nocpp, include="core/cross/buffer.h"]
-class UByteNField : Field {
- %[
- Sets the values of the data stored in the field.
-
- The buffer for the field must have already been created either through
- buffer.set or through buffer.allocateElements.
-
- The number of values passed in must be a multiple of the number of
- components needed for the field.
-
- \param start_index index of first value to set.
- \param values Values to be stored in the buffer starting at index.
- %]
- [userglue] void SetAt(unsigned int start_index, float[] values);
-
- %[
- Gets the values stored in the field.
-
- \param start_index index of the first value to get.
- \param num_elements number of elements to read from field.
- \return The values of the field.
- %]
- [userglue] float[] GetAt(unsigned int start_index, unsigned int num_elements);
-
- [verbatim=cpp_glue] %{
- void userglue_method_SetAt(o3d::UByteNField* field,
- unsigned int start_index,
- const std::vector<float>& values) {
- if (values.size() % field->num_components() != 0) {
- O3D_ERROR(field->service_locator())
- << "the number of values passed in is not a multiple of the number"
- << " of components in the field.";
- return;
- }
- if (!values.empty()) {
- field->SetFromFloats(&values[0], field->num_components(), start_index,
- values.size() / field->num_components());
- }
- }
- std::vector<float> userglue_method_GetAt(
- o3d::UByteNField* field,
- unsigned int start_index,
- unsigned int num_elements) {
- std::vector<float> retval;
- if (field->RangeValid(start_index, num_elements)) {
- retval.resize(num_elements * field->num_components());
- field->GetAsFloats(start_index, &retval[0], field->num_components(),
- num_elements);
- }
- return retval;
- }
- %}
-};
-
-%[
- An array of fields.
-%]
-typedef Field[] FieldArray;
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/file_request.idl b/o3d/plugin/idl/file_request.idl
deleted file mode 100644
index b83b58e..0000000
--- a/o3d/plugin/idl/file_request.idl
+++ /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.
- */
-
-namespace o3d {
-
-[include="core/cross/file_request.h", async]
-callback void FileRequestCallback();
-
-%[
- A FileRequest is used to carry out an asynchronous request for a file
- to be loaded. Its use parallels that of XMLHttpRequest; you create one, call
- open, set the onreadystatechange callback, and call send.
- Note that unlike XMLHttpRequests, FileRequests cannot be reused.
-
- For RawData loads, on success the RawData will be stored in the data field
- on the FileRequest itself. It is only valid until the FileRequest is freed by
- calling pack.removeObject(request).
-
- \code
- var request = pack.createFileRequest("RAWDATA");
- request.open("GET", url, true);
- request.onreadystatechange = function() {
- if (request.done) {
- if (request.success) {
- var rawData = request.data;
- // do something with raw data like create a bitmap.
- ...
- } else {
- dump('Load of rawdata returned failure.');
- }
- // Free the request (and the rawData)
- pack.removeObject(request);
- }
- };
- request.send();
- \endcode
-%]
-
-[nocpp, include="core/cross/file_request.h"] class FileRequest
- : ObjectBase {
- %[
- A callback to call whenever the ready state of the request changes.
- %]
- [setter=set_onreadystatechange]
- FileRequestCallback onreadystatechange;
-
- %[
- The URI this request is for.
- %]
- [getter=uri] String uri;
- %[
- On completion of successful texture file loads, this holds the loaded
- texture. Loading textures through FileRequest is depreated.
- @deprecated
- %]
- [getter=texture] Texture? texture;
-
- %[
- On completion of successful RawData file loads, this holds the loaded
- RawData.
- %]
- [getter=data] RawData? data;
-
- %[
- Whether or not to generate mip-maps on textures that are loaded (default:
- true). Mip-maps are not generated for DXTC textures. DDS files can contain
- pre-computed mip-maps for DXTC textures though.
- Loading textures through FileRequest is depreated.
- @deprecated
- %]
- [getter, setter] bool generate_mipmaps;
-
- %[
- This holds the same values as in XMLHttpRequest:
- \li 0 = uninitialized
- \li 1 = opened
- \li 2 = sent
- \li 3 = receiving
- \li 4 = loaded (the file has been downloaded, but may or may not have been
- parsed yet)
- %]
- [getter=ready_state] int readyState;
- %[
- This indicates whether any further processing will be done on this
- FileRequest.
- %]
- [getter=done] bool done;
- %[
- This field is only valid if done is true. It indicates whether or not the
- request succeeded. If it failed error holds an error message.
- %]
- [getter=success] bool success;
-
- %[
- An error message.
- If done is true and success is false this will be an error message
- describing what went wrong.
- %]
- [getter] String error;
-
- %[
- Set up several of the request fields.
- \param method "GET" is the only supported method at this time
- \param uri the location of the file to fetch
- \param async true is the only legal value at this time
- %]
- [nocpp, userglue, plugin_data] void open(
- String method, String uri, bool async);
-
- %[
- Send the request.
- Unlike XMLHttpRequest the onreadystatechange callback will be called no
- matter what, with success or failure.
- %]
- [nocpp, userglue, plugin_data] void send();
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/function.idl b/o3d/plugin/idl/function.idl
deleted file mode 100644
index 5f8a7f8..0000000
--- a/o3d/plugin/idl/function.idl
+++ /dev/null
@@ -1,93 +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.
- */
-
-namespace o3d {
-
-%[
- A Function is a class that has an Evaluate method. Evaluate takes 1 input and
- returns 1 output.
-%]
-[nocpp, include="core/cross/function.h"]
-class Function : NamedObject {
- %[
- Gets an output for this function for the given input.
- \param input Input to get output at.
- \return The output for the given input.
- %]
- [const, userglue] float Evaluate(float input);
-
- [verbatim=cpp_glue] %{
- float userglue_method_Evaluate(o3d::Function* self, float value) {
- return self->Evaluate(value, NULL);
- }
- %}
-}; // Function
-
-%[
- A Param which stores a Function.
-%]
-[nocpp, include="core/cross/function.h"] class ParamFunction : Param {
- %[
- The Function stored by the Param.
- %]
- [getter, setter] Function? value_;
-};
-
-%[
- A FunctionEval evaluates a Function through parameters.
-
- @o3dparameter input ParamFloat The input to the function.
- @o3dparameter functionObject ParamFunction The function to apply the input to.
- @o3dparameter output ParamFloat The result of applying the input to the
- function.
-%]
-[nocpp, include="core/cross/function.h"]
-class FunctionEval : ParamObject {
- %[
- The input to the function.
- Default = 0.
- %]
- [getter, setter] float input;
-
- %[
- The output of the function for the given input.
- %]
- [getter] float output;
-
- %[
- The function to evaluate.
- %]
- [getter, setter] Function? function_object;
-}; // FunctionEval
-
-} // namespace o3d
-
-
diff --git a/o3d/plugin/idl/get_idl_files.py b/o3d/plugin/idl/get_idl_files.py
deleted file mode 100644
index bf330b6..0000000
--- a/o3d/plugin/idl/get_idl_files.py
+++ /dev/null
@@ -1,26 +0,0 @@
-#!/usr/bin/env python
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Helper script to generate file lists for idl.gyp."""
-
-import os.path
-import sys
-import types
-
-
-# Read in the manifest files (which are just really simple python files),
-# and scrape out the file lists.
-def main(argv):
- idl_list_filename = os.path.join('..', 'idl_list.manifest')
- files = eval(open(idl_list_filename, "r").read())
- files = [os.path.basename(f) for f in files]
- files.sort()
- for file in files:
- # gyp wants paths with slashes, not backslashes.
- print file.replace("\\", "/")
-
-
-if __name__ == "__main__":
- main(sys.argv[1:])
diff --git a/o3d/plugin/idl/idl.gyp b/o3d/plugin/idl/idl.gyp
deleted file mode 100644
index 81ead55..0000000
--- a/o3d/plugin/idl/idl.gyp
+++ /dev/null
@@ -1,118 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'includes': [
- '../../build/common.gypi',
- ],
- 'variables': {
- 'chromium_code': 0,
- 'idl_out_path': '<(SHARED_INTERMEDIATE_DIR)/idl_glue',
- 'static_glue_dir': '../../../<(nixysadir)/static_glue/npapi',
- 'idl_files': [
- '<!@(python get_idl_files.py)',
- 'layer.idl',
- 'pattern.idl',
- ],
- },
- 'target_defaults': {
- 'include_dirs': [
- '../..',
- '../../..',
- '../../../<(npapidir)/include',
- '../../../<(zlibdir)',
- '../../../skia/config',
- '../../plugin/cross',
- '<(static_glue_dir)',
- '<(idl_out_path)',
- ],
- 'conditions': [
- ['OS=="win"',
- {
- 'defines': [
- 'OS_WINDOWS',
- ],
- },
- ],
- ['OS=="mac"',
- {
- 'include_dirs': [
- '../mac',
- ],
- 'defines': [
- 'XP_MACOSX',
- ],
- },
- ],
- ],
- },
- 'targets': [
- {
- # This target is only used when we're not built as part of Chrome,
- # since chrome has its own implementation of the NPAPI from webkit.
- 'target_name': 'o3dNpnApi',
- 'type': 'static_library',
- 'include_dirs': [
- '../../../<(npapidir)/include',
- ],
- 'sources': [
- '<(static_glue_dir)/npn_api.cc',
- ],
- },
- {
- 'target_name': 'o3dPluginIdl',
- 'type': 'static_library',
- 'dependencies': [
- '../../../<(zlibdir)/zlib.gyp:zlib',
- '../../../base/base.gyp:base',
- '../../../skia/skia.gyp:skia',
- ],
- 'direct_dependent_settings': {
- 'include_dirs': [
- '../../../<(npapidir)/include',
- '<(idl_out_path)',
- '<(static_glue_dir)',
- ],
- },
- 'actions': [
- {
- 'action_name': 'generate_idl',
- 'process_outputs_as_sources': 1,
- 'inputs': [
- '<@(idl_files)',
- ],
- 'outputs': [
- '<(idl_out_path)/hash',
- '<(idl_out_path)/globals_glue.cc',
- '<(idl_out_path)/globals_glue.h',
- '<!@(python idl_filenames.py \'<(idl_out_path)\' <@(idl_files))',
- ],
- 'action': [
- 'python',
- 'codegen.py',
- '--binding-module=o3d:../../plugin/o3d_binding.py',
- '--generate=npapi',
- '--output-dir=<(idl_out_path)',
- '<@(idl_files)',
- ],
- 'message': 'Generating IDL glue code.',
- },
- ],
- 'sources': [
- '../cross/archive_request_static_glue.cc',
- '../cross/archive_request_static_glue.h',
- '../cross/o3d_glue.cc',
- '../cross/o3d_glue.h',
- '<(static_glue_dir)/common.cc',
- '<(static_glue_dir)/static_object.cc',
- ],
- },
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/plugin/idl/idl_filenames.py b/o3d/plugin/idl/idl_filenames.py
deleted file mode 100644
index ceb1575..0000000
--- a/o3d/plugin/idl/idl_filenames.py
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/usr/bin/env python
-
-# This script takes a list of inputs and generates a list of outputs
-# that Nixysa will generate. It passes through any files not ending
-# in .idl, and converts idl files into corresponding .cc and .h files.
-
-# The first argument is the destintation directory for the output
-# files, and the rest are relative paths to the source files. The
-# output is posix paths, because that's what GYP expects.
-
-import sys
-import posixpath
-
-output_dir = sys.argv[1]
-
-for file in sys.argv[2:]:
- (base, suffix) = posixpath.splitext(file)
- if suffix == ".idl":
- print posixpath.normpath(posixpath.join(output_dir, "%s_glue.h" % base))
- print posixpath.normpath(posixpath.join(output_dir, "%s_glue.cc" % base))
- else:
- print posixpath.normpath(posixpath.join(output_dir, file))
-
-sys.exit(0)
diff --git a/o3d/plugin/idl/layer.idl b/o3d/plugin/idl/layer.idl
deleted file mode 100644
index 1b9a8f7..0000000
--- a/o3d/plugin/idl/layer.idl
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-namespace o3d {
-
-namespace o2d {
-
-%[
- A Layer is a rectangular region of the O2D canvas to be filled with a
- particular Pattern, with automatic clipping based on stacking order.
-%]
-[nocpp, include="core/cross/cairo/layer.h"] class Layer : ObjectBase {
- %[
- Available painting operators.
-
- \var PaintOperator,
- \li BLEND, Alpha-blend the Pattern on top of lower Layers based on its
- alpha channel. (Default)
- \li BLEND_WITH_TRANSPARENCY, Like BLEND, but scale the alpha channel down
- based on the alpha property of the Layer as an
- additional fractional transparency.
- \li COPY, Copy the colour content of the Pattern directly to the
- destination, ignoring the alpha channel.
- \li COPY_WITH_FADING, Like COPY, but fade the colour to black based on the
- alpha property of the Layer as an additional
- fractional brightness.
- %]
- enum PaintOperator {
- BLEND,
- BLEND_WITH_TRANSPARENCY,
- COPY,
- COPY_WITH_FADING
- };
-
- %[
- The Pattern used to paint this Layer.
- %]
- [getter, setter] Pattern? pattern;
-
- %[
- Whether this layer should be visible or not.
- %]
- [getter, setter] bool visible;
-
- %[
- Paint everywhere rather than just within the region defined by the x, y,
- width, and height.
- %]
- [getter, setter] bool everywhere;
-
- %[
- The transparency for the BLEND_WITH_TRANSPARENCY operator or the fading for
- the COPY_WITH_FADING operator.
- %]
- [getter, setter] double alpha;
-
- %[
- The x coordinate of the top-left corner of this layer.
- %]
- [getter, setter] double x;
-
- %[
- The y coordinate of the top-left corner of this layer.
- %]
- [getter, setter] double y;
-
- %[
- The z coordinate of the layer (used only to determine stacking order).
- %]
- [getter, setter] double z;
-
- %[
- The width of this layer.
- %]
- [getter, setter] double width;
-
- %[
- The height of this layer.
- %]
- [getter, setter] double height;
-
- %[
- A scaling factor to apply to the pattern's x-axis.
- %]
- [getter, setter] double scale_x;
-
- %[
- A scaling factor to apply to the pattern's y-axis.
- %]
- [getter, setter] double scale_y;
-
- %[
- The paint operator to use for painting this Layer.
- %]
- [getter, setter] PaintOperator paint_operator;
-}; // Layer
-
-} // namespace o2d
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/material.idl b/o3d/plugin/idl/material.idl
deleted file mode 100644
index 890f04f..0000000
--- a/o3d/plugin/idl/material.idl
+++ /dev/null
@@ -1,63 +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.
- */
-
-namespace o3d {
-
-%[
- A Material holds the various uniform parameters an Effect needs to render.
- For example a Lambert effect might need "diffuse", "ambient", "emissive".
- The parameters needed on a Material will vary depending its Effect.
- Note that a material MUST have its drawList set in order for objects using it
- to render.
-
- @o3dparameter state ParamState The State used by this material.
- @o3dparameter effect ParamEffect The Effect used by this material.
- @o3dparameter drawList ParamDrawList The the DrawList used by this material.
-%]
-[nocpp, include="core/cross/material.h"] class Material : ParamObject {
-
- %[
- The Effect for this material.
- %]
- [getter, setter] Effect? effect_;
-
- %[
- The State for this material.
- %]
- [getter, setter] State? state_;
-
- %[
- The DrawList this material will render on.
- %]
- [getter, setter] DrawList? draw_list_;
-}; // Material
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/matrix4_axis_rotation.idl b/o3d/plugin/idl/matrix4_axis_rotation.idl
deleted file mode 100644
index aa78dcc..0000000
--- a/o3d/plugin/idl/matrix4_axis_rotation.idl
+++ /dev/null
@@ -1,72 +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.
- */
-
-namespace o3d {
-
-%[
- This param operation applies a rotation to its input matrix. The
- rotation is specified in terms of an angle and an axis of rotation.
- It can be used, for example, to supply the local matrix of a transform.
-
- @o3dparameter inputMatrix ParamMatrix4 The input matrix.
- @o3dparameter axis ParamFloat3 The axis of rotation.
- @o3dparameter angle ParamFloat The amount of rotation.
- @o3dparameter outputMatrix ParamMatrix4 The result of rotating the input
- matrix by the specified rotation.
-%]
-[nocpp, include="core/cross/matrix4_axis_rotation.h"]
-class Matrix4AxisRotation : ParamObject {
- %[
- The local rotation axis. This must be a unit vector.
- Default = [0, 0, 0].
- %]
- [getter, setter] Float3 axis;
-
- %[
- The angle of rotation in radians.
- Default = 0.
- %]
- [getter, setter] float angle;
-
- %[
- The input matrix.
- Default = Identity.
- %]
- [getter, setter] Vectormath::Aos::Matrix4 input_matrix;
-
- %[
- The output is equal to the rotation of the input matrix.
- %]
- [getter] Vectormath::Aos::Matrix4 output_matrix;
-}; // Matrix4AxisRotation
-
-} // namespace o3d
-
diff --git a/o3d/plugin/idl/matrix4_composition.idl b/o3d/plugin/idl/matrix4_composition.idl
deleted file mode 100644
index bd899b1..0000000
--- a/o3d/plugin/idl/matrix4_composition.idl
+++ /dev/null
@@ -1,66 +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.
- */
-
-namespace o3d {
-
-%[
- This param operation composes (multiplies) a local matrix with an input
- matrix. It can be used, for example, to supply the local matrix of a
- transform.
-
- @o3dparameter inputMatrix ParamMatrix4 The input matrix.
- @o3dparameter localMatrix ParamMatrix4 The local matrix.
- @o3dparameter outputMatrix ParamMatrix4 The result of multiplying the input
- matrix by the local matrix.
-%]
-[nocpp, include="core/cross/matrix4_composition.h"]
-class Matrix4Composition : ParamObject {
- %[
- The local matrix.
- Default = Identity.
- %]
- [getter, setter] Vectormath::Aos::Matrix4 local_matrix;
-
- %[
- The input matrix.
- Default = Identity.
- %]
- [getter, setter] Vectormath::Aos::Matrix4 input_matrix;
-
- %[
- The output is equal to the composition (multiplication) of the inpur
- matrix with the local matrix.
- %]
- [getter] Vectormath::Aos::Matrix4 output_matrix;
-}; // Matrix4Composition
-
-} // namespace o3d
-
diff --git a/o3d/plugin/idl/matrix4_scale.idl b/o3d/plugin/idl/matrix4_scale.idl
deleted file mode 100644
index a4766db2..0000000
--- a/o3d/plugin/idl/matrix4_scale.idl
+++ /dev/null
@@ -1,64 +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.
- */
-
-namespace o3d {
-
-%[
- This param operation applies a scaling to its input matrix.
- It can be used, for example, to supply the local matrix of a transform.
-
- @o3dparameter inputMatrix ParamMatrix4 The input matrix.
- @o3dparameter scale ParamFloat3 The scale.
- @o3dparameter outputMatrix ParamMatrix4 The result of scaling the input matrix
- by the translation.
-%]
-[nocpp, include="core/cross/matrix4_scale.h"]
-class Matrix4Scale : ParamObject {
- %[
- The local scaling.
- Default = [0, 0, 0].
- %]
- [getter, setter] Float3 scale;
-
- %[
- The parent matrix.
- Default = Identity.
- %]
- [getter, setter] Vectormath::Aos::Matrix4 input_matrix;
-
- %[
- The output is equal to the scale of the input matrix.
- %]
- [getter] Vectormath::Aos::Matrix4 output_matrix;
-}; // Matrix4Scale
-
-} // namespace o3d
-
diff --git a/o3d/plugin/idl/matrix4_translation.idl b/o3d/plugin/idl/matrix4_translation.idl
deleted file mode 100644
index 673df67..0000000
--- a/o3d/plugin/idl/matrix4_translation.idl
+++ /dev/null
@@ -1,64 +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.
- */
-
-namespace o3d {
-
-%[
- This param operation applies a translation to its input matrix.
- It can be used, for example, to supply the local matrix of a transform.
-
- @o3dparameter inputMatrix ParamMatrix4 The input matrix.
- @o3dparameter translation ParamFloat3 The translation.
- @o3dparameter outputMatrix ParamMatrix4 The result of translating
- the input matrix by the translation.
-%]
-[nocpp, include="core/cross/matrix4_translation.h"]
-class Matrix4Translation : ParamObject {
- %[
- The local translation.
- Default = [0, 0, 0].
- %]
- [getter, setter] Float3 translation;
-
- %[
- The input matrix.
- Default = Identity.
- %]
- [getter, setter] Vectormath::Aos::Matrix4 input_matrix;
-
- %[
- The output is equal to the translation of the input matrix.
- %]
- [getter] Vectormath::Aos::Matrix4 output_matrix;
-}; // Matrix4Translation
-
-} // namespace o3d
-
diff --git a/o3d/plugin/idl/named.idl b/o3d/plugin/idl/named.idl
deleted file mode 100644
index f73be6b..0000000
--- a/o3d/plugin/idl/named.idl
+++ /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.
- */
-
-namespace o3d {
-
-%[
- The base class of most O3D run-time objects.
-%]
-
-[binding_model=o3d,include="core/cross/object_base.h"]
-class ObjectBase {
- %[
- Unique id of the object.
-
- This id will be unique, even across multiple O3D clients in the same
- page.
- %]
- [getter, userglue_getter] Id client_id;
-
- [verbatim=cpp_header] %{
- static Class *GetApparentClass() { return NULL; }
- %}
-
- %[
- The concrete class name for an object derived from ObjectBase.
-
- If you want to know if an object is of a certain type you should use
- objectBase.isAClassName
-
- \code
- var t = pack.createObject('o3d.Transform');
- t.className == 'o3d.Transform'; // true
- \endcode
- %]
- [userglue_getter, getter] String class_name_;
-
- %[
- Takes the name of a class as an argument, and returns true if this object is
- either an instance of that class or derives from that class.
- \code
- var t = pack.createObject('o3d.Transform');
- t.isAClassName('o3d.Transform'); // true
- t.isAClassName('o3d.ParamObject'); // true
- t.isAClassName('o3d.Shape'); // false
- \endcode
- \param class_name Name of class to check for.
- \return true if this object is a or is derived from the given class name.
- %]
- bool IsAClassName(String class_name);
-
- [verbatim=cpp_glue] %{
- o3d::Id userglue_getter_client_id(o3d::ObjectBase* self) {
- return self->id();
- }
- o3d::String userglue_getter_class_name_(o3d::ObjectBase* self) {
- return self->GetClassName();
- }
- %}
-};
-
-%[
- Base class for all objects that are identifiable by a name.
-%]
-[binding_model=o3d, include="core/cross/named_object.h"]
-class NamedObjectBase: ObjectBase {
- %[
- The object's name.
- Default = "".
- %]
- [getter] String name;
-
-};
-
-%[
- Base class for all objects that can have their name set.
-%]
-[binding_model=o3d, include="core/cross/named_object.h"]
-class NamedObject: NamedObjectBase {
- %[
- The object's name.
-
- Setting this has no meaning to O3D, but is useful for debugging and for
- the functions Client.getObjects, Pack.getObject,
- RenderNode.getRenderNodesByNameInTree and
- RenderNode.getTransformsByNameInTree
- which search for objects by name.
- %]
- // NOTE: I tried putting just setter here but nixysa can't handle that.
- [getter, setter] String name;
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/pack.idl b/o3d/plugin/idl/pack.idl
deleted file mode 100644
index 3fd5b6d..0000000
--- a/o3d/plugin/idl/pack.idl
+++ /dev/null
@@ -1,337 +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.
- */
-
-namespace o3d {
-
-typedef ObjectBase[] ObjectArray;
-typedef Bitmap[] BitmapArray;
-
-%[
- A Pack object functions as a container for O3D objects. The Pack
- is used to control the lifetime scope of a collection of objects in bulk. The
- Pack object achieves this by simply storing a set of references to its
- contained objects, which ensures that the ref-counts for those objects never
- reach zero while the pack is alive.
- \sa o3d.Pack.removeObject
- \sa o3d.Pack.destroy
-%]
-[nocpp, include="core/cross/pack.h"] class Pack : NamedObject {
-
- %[
- Removes all internal references to the Pack from the client.
- The pack, and all objects contained in it are permitted to be destroyed
- after the pack's destruction. Objects will only be destroyed after all
- references to them have been removed.
-
- NOTE: Calling pack.destroy does NOT free your resources. It justs releases
- the pack's reference to those resources. An example should hopefully make
- it clearer.
-
- pack.destroy() is effectively almost the same as this.
-
- \code
- var objectsInPack = pack.getObjectsByClassName('o3d.ObjectBase');
- for (var ii = 0; ii < objectsInPack.length; ++ii) {
- pack.removeObject(objectsInPack[ii]);
- }
- \endcode
-
- The only difference is that after all the objects are removed the pack
- itself will be released from the client. See documentation on
- pack.removeObject for why this is important.
-
- It's important to note that many objects are only referenced by the pack.
- Textures, Effects, Materials, for example. That means the moment you call
- pack.destroy() those objects will be freed. If the client then tries to
- render and some objects are missing you'll immediately get an error.
- %]
- void Destroy();
-
- %[
- Removes a pack's reference to an object. Any object created from
- pack.create___ function can be removed. This releases the pack's reference
- to that object so if nothing else is referencing that object it will be
- deleted.
-
- NOTE: Calling pack.removeObject does NOT automatically free your resource.
- It just releases the pack's reference to that resource. An example should
- hopefully make it clearer.
-
- Suppose you make a transform like this:
-
- \code
- var myTransform = pack.createObject('Transform');
- myTransform.parent = g_client.root;
- pack.removeObject(myTransform);
- \endcode
-
- In the code above, myTransform is referenced twice. Once by the pack, and
- again by g_client.root So in this case, calling pack.removeObject()
- only releases the pack's reference leaving the reference by g_client.root.
-
- \code
- myTransform.parent = null;
- \endcode
-
- Now the last reference has been removed and myTransform will be freed.
-
- \param object Object to remove.
- \return True if the object was successfully removed. False if the object
- is not part of this pack.
-
- \sa o3d.Pack.destroy
- %]
- bool RemoveObject(ObjectBase object);
-
- %[
- Creates an Object by Class name.
-
- Note: You may omit the 'o3d.'.
-
- \param type_name name of Class to create. Valid type names are:
- \li o3d.Bitmap
- \li o3d.Canvas
- \li o3d.CanvasLinearGradient
- \li o3d.CanvasPaint
- \li o3d.ClearBuffer
- \li o3d.Counter
- \li o3d.Curve
- \li o3d.DrawContext
- \li o3d.DrawElement
- \li o3d.DrawList
- \li o3d.DrawPass
- \li o3d.Effect
- \li o3d.FunctionEval
- \li o3d.IndexBuffer
- \li o3d.Material
- \li o3d.ParamArray
- \li o3d.ParamObject
- \li o3d.Primitive
- \li o3d.RenderFrameCounter
- \li o3d.RenderNode
- \li o3d.RenderSurfaceSet
- \li o3d.Sampler
- \li o3d.SecondCounter
- \li o3d.Shape
- \li o3d.Skin
- \li o3d.SkinEval
- \li o3d.SourceBuffer
- \li o3d.State
- \li o3d.StateSet
- \li o3d.StreamBank
- \li o3d.Texture2D
- \li o3d.TextureCUBE
- \li o3d.TickCounter
- \li o3d.Transform
- \li o3d.TreeTraversal
- \li o3d.VertexBuffer
- \li o3d.Viewport
- \li o3d.Matrix4AxisRotation
- \li o3d.Matrix4Composition
- \li o3d.Matrix4Scale
- \li o3d.Matrix4Translation
- \li o3d.ParamOp2FloatsToFloat2
- \li o3d.ParamOp3FloatsToFloat3
- \li o3d.ParamOp4FloatsToFloat4
- \li o3d.ParamOp16FloatsToMatrix4
- \li o3d.TRSToMatrix4
- \return The created object.
- %]
- [noreturndocs] ObjectBase? CreateObject(String type_name);
-
- %[
- Creates a new Texture2D object of the specified size and format and
- reserves the necessary resources for it.
-
- Note: If enable_render_surfaces is true, then the dimensions must be a
- power of two.
-
- \param width The width of the texture area in texels (max = 2048)
- \param height The height of the texture area in texels (max = 2048)
- \param format The memory format of each texel
- \param levels The number of mipmap levels. Use zero to create the compelete
- mipmap chain.
- \param enable_render_surfaces If true, the texture object will expose
- RenderSurface objects through GetRenderSurface(...).
- \return The Texture2D object.
-
- %]
- Texture2D? CreateTexture2D(int width,
- int height,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
- %[
- Creates a new TextureCUBE object of the specified size and format and
- reserves the necessary resources for it.
- Note: If enable_render_surfaces is true, then the dimensions must be a
- power of two.
-
- \param edge_length The edge of the texture area in texels (max = 2048)
- \param format The memory format of each texel
- \param levels The number of mipmap levels. Use zero to create the compelete
- mipmap chain.
- \param enable_render_surfaces If true, the texture object will expose
- RenderSurface objects through GetRenderSurface(...).
- \return The TextureCUBE object.
- %]
- TextureCUBE? CreateTextureCUBE(int edge_length,
- Texture::Format format,
- int levels,
- bool enable_render_surfaces);
-
- %[
- Creates a new RenderDepthStencilSurface object of a format suitable for use
- as a depth-stencil render target.
- Note: The dimensions of the RenderDepthStencilSurface must be a power of
- two.
-
- \param width The width of the RenderSurface in pixels
- \param height The height of the RenderSurface in pixels
- \return The RenderSurface object.
- %]
- RenderDepthStencilSurface? CreateDepthStencilSurface(int width, int height);
-
- %[
- Search the pack for all objects of a certain class with a certain name.
-
- Note that modifications to this array [e.g. push()] will not affect
- the underlying Pack, while modifications to the array's members
- <strong>will</strong> affect them.
-
- \param name Name to look for
- \param class_type_name the Class of the object. It is okay to pass base
- types for example "o3d.RenderNode" will return ClearBuffers,
- DrawPasses, etc...
- \return Array of Objects.
- %]
- [const, noreturndocs]
- ObjectArray GetObjects(String name, String class_type_name);
-
- %[
- Search the pack for all objects of a certain class
-
- Note that modifications to this array [e.g. push()] will not affect
- the underlying Pack, while modifications to the array's members
- <strong>will</strong> affect them.
-
- \param class_type_name the Class of the object. It is okay to pass base
- types for example "o3d.RenderNode" will return ClearBuffers,
- DrawPasses, etc...
- \return Array of Objects.
- %]
- [const, noreturndocs]
- ObjectArray GetObjectsByClassName(String class_type_name);
-
- %[
- All the objects managed by this pack.
-
- Each access to this field gets the entire list so it is best to get it
- just once. For example:
- \code
- var objects = pack.objects;
- for (var i = 0; i < objects.length; i++) {
- var object = objects[i];
- }
- \endcode
-
- Note that modifications to this array [e.g. push()] will not affect
- the underlying Pack, while modifications to the array's members
- <strong>will</strong> affect them.
- %]
- [userglue_getter, getter] ObjectBaseArray objects_;
-
- %[
- Creates a FileRequest to be used to asynchronously load a Texture or
- RawData. Note: Loading a "TEXTURE" is deprecated. The recommended way to
- load a texture is to load a RawData, use that to create Bitmap, Massage
- the Bitmap to your liking the use that to create a Texture.
- \param type Must be "TEXTURE" or "RAWDATA"
- \return a FileRequest
- %]
- [noccp, userglue] FileRequest? CreateFileRequest(String type);
- [verbatim=cpp_glue, include="core/cross/file_request.h"] %{
- o3d::FileRequest *userglue_method_CreateFileRequest(
- o3d::Pack *pack, const o3d::String &type) {
- return pack->CreateFileRequest(type);
- }
- o3d::ObjectBaseArray userglue_getter_objects_(
- o3d::Pack* self) {
- return self->GetByClass<o3d::ObjectBase>();
- }
- %}
-
- %[
- Creates an ArchiveRequest so we can stream in assets from an archive
- \return an ArchiveRequest
- %]
- [noccp, userglue] ArchiveRequest CreateArchiveRequest();
- [verbatim=cpp_glue, include="import/cross/archive_request.h"] %{
- o3d::ArchiveRequest *userglue_method_CreateArchiveRequest(
- o3d::Pack *pack) {
- return pack->CreateArchiveRequest();
- }
- %}
-
- %[
- Creates a Texture given a RawData object
- \param raw_data The RawData to create the texture from.
- \param generate_mips True if you want O3D to generate mip maps for the
- texture.
- \return the Texture
- \sa o3d.Pack.createBitmapsFromRawData
- @deprecated
- %]
- Texture? CreateTextureFromRawData(RawData raw_data,
- bool generate_mips);
-
- %[
- Create Bitmaps from RawData.
-
- If you load a cube map you'll get 6 an array of 6 Bitmaps.
- If you load a volume map you'll get an array of n Bitmaps.
- If there is an error you'll get an empty array.
-
- \param raw_data contains the bitmap data in a supported format.
- \return An Array of Bitmaps object.
- %]
- BitmapArray CreateBitmapsFromRawData(RawData raw_data);
-
- %[
- Create RawData given a data URL.
- \param data_url The data URL from which to create the RawData.
- \return The RawData.
- %]
- RawData CreateRawDataFromDataURL(String data_url);
-}; // Pack
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/param.idl b/o3d/plugin/idl/param.idl
deleted file mode 100644
index 49aa369..0000000
--- a/o3d/plugin/idl/param.idl
+++ /dev/null
@@ -1,336 +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.
- */
-
-namespace o3d {
-
-typedef Param[] ParamVector;
-
-%[
- Params store data defined name/value pairs on ParamObjects.
- Each Param has a name, a type and a value that can be set and queried.
- One of their uses is to hold "uniform constants" used to parameterize shaders.
- Params can be connected in a source/destination fashion such that a target
- Param gets its value from the source param.
-%]
-
-[nocpp, include="core/cross/param.h"] class Param : NamedObjectBase {
-
- [verbatim=cpp_header] %{
- static int data_length_[NUM_PARAM_TYPES]; // Data size requirements per type
-
- void *data_; // Storage for Param value
- const void *handle_; // Handle to an implementation specific object holding
- // corresponding to the Param
- %}
-
- %[
- If true, this param will make sure its input param is up to date when
- using it as a source. Default = true.
-
- This is for helping with Param cycles.
-
- If paramA gets its value from paramB and paramB gets its value from
- paramA:\n
- If you go paramA.value, paramB will evaluate then copy to paramA.\n
- If you go paramB.value, paramA will evaluate then copy to paramB.\n
- If you set paramB.updateInput = false, then:\n
- If you go paramA.value, paramB will evaluate then copy to paramA.\n
- If you go paramB.value, paramB just copy paramA. paramA will NOT evaluate
- when paramB asks for its value.
- %]
- [getter, setter, property=rw] bool update_input;
-
- %[
- Directly binds two Param elements such that this
- parameter gets its value from the source parameter. The
- source must be compatible with this parameter.
-
- \param source_param The parameter that the value originates from. Passing in
- null will unbind any parameter currently bound.
- \return True if the bind succeeded.
- %]
- bool Bind(Param? source_param);
-
- %[
- Breaks any input connection coming into the Param.
- %]
- void UnbindInput();
-
- %[
- Breaks a specific param-bind output connection on this param.
-
- \param destination_param param to unbind.
- %]
- void UnbindOutput(Param destination_param);
-
- %[
- Breaks all param-bind output connections on this param.
- %]
- void UnbindOutputs();
-
- %[
- If true the param is read only. Its value can not be set nor can it be used
- as the destination in a ParamBind
- %]
- [getter, property=r] bool read_only_;
-
- %[
- The input connection for this param.
- %]
- [getter, property_r] Param? input_connection;
-
- %[
- The output connections for this param.
- %]
- [getter, property=r] ParamVector output_connections;
-};
-
-%[
- A Param class which stores a single float.
- Default Value = 0.
-%]
-[nocpp, include="core/cross/param.h"] class ParamFloat : Param {
- %[
- The float stored by the Param.
- %]
- [getter, setter, property=rw] float value_;
-};
-
-%[
- A Param class which stores a Float2.
- Default Value = [0, 0].
-%]
-[nocpp, include="core/cross/param.h"] class ParamFloat2 : Param {
- %[
- The Float2 stored by the Param as an array of 2 numbers.
- %]
- [setter, getter, property=rw, nocpp] Float2 value;
-
- %[
- Sets the value of ParamFloat2 by 2 numbers.
- \param v0 first value.
- \param v1 second value.
- %]
- [userglue] void set(float v0, float v1);
-
- [verbatim=cpp_glue] %{
- void userglue_method_set(o3d::ParamFloat2* self,
- float v0,
- float v1) {
- self->set_value(o3d::Float2(v0, v1));
- }
- %}
-};
-
-%[
- A Param class which stores a Float3.
- Default Value = [0, 0, 0].
-%]
-[nocpp, include="core/cross/param.h"] class ParamFloat3 : Param {
- %[
- The Float3 stored by the Param as an array of 3 numbers.
- %]
- [setter, getter, property=rw, nocpp] Float3 value;
-
- %[
- Sets the entries of the value of ParamFloat3 to the 3 given numbers.
- \param v0 first value.
- \param v1 second value.
- \param v2 third value.
- %]
- [userglue] void set(float v0, float v1, float v2);
-
- [verbatim=cpp_glue] %{
- void userglue_method_set(o3d::ParamFloat3* self,
- float v0,
- float v1,
- float v2) {
- self->set_value(o3d::Float3(v0, v1, v2));
- }
- %}
-};
-
-%[
- A Param class which stores a Float4.
- Default Value = [0, 0, 0, 0].
-%]
-[nocpp, include="core/cross/param.h"] class ParamFloat4 : Param {
- %[
- The Float4 stored by the Param as an array of 4 numbers.
- %]
- [setter, getter, property=rw, nocpp] Float4 value;
-
- %[
- Sets the value of ParamFloat4 by 4 numbers.
- \param v0 first value.
- \param v1 second value.
- \param v2 third value.
- \param v3 fourth value.
- %]
- [userglue] void set(float v0, float v1, float v2, float v3);
-
- [verbatim=cpp_glue] %{
- void userglue_method_set(o3d::ParamFloat4* self,
- float v0,
- float v1,
- float v2,
- float v3) {
- self->set_value(o3d::Float4(v0, v1, v2, v3));
- }
- %}
-};
-
-%[
- A Param class which stores a 4-by-4 matrix.
- Default Value = Identity.
-%]
-[nocpp, include="core/cross/param.h"] class ParamMatrix4 : Param {
- %[
- Sets the 4-by-4 matrix stored by the Param by a length-4 array of arrays of
- 4 numbers.
- %]
- [getter, setter, property=rw, nocpp] Vectormath::Aos::Matrix4 value;
-};
-
-%[
- A Param class which stores an integer.
- Default Value = 0.
-%]
-[nocpp, include="core/cross/param.h"] class ParamInteger : Param {
- %[
- The integer stored by the Param.
- %]
- [getter, setter, property=rw] int value_;
-};
-
-%[
- A Param class which stores a boolean.
- Default Value = false.
-%]
-[nocpp, include="core/cross/param.h"] class ParamBoolean : Param {
- %[
- The boolean stored by the Param.
- %]
- [getter, setter, property=rw] bool value_;
-};
-
-%[
- A Param which stores a string.
- Default Value = "".
-%]
-[nocpp, include="core/cross/param.h"] class ParamString : Param {
- %[
- The string stored by the Param.
- %]
- [getter, setter, property=rw] String value_;
-};
-
-%[
- A Param which stores a Sampler.
-%]
-[nocpp, include="core/cross/sampler.h"] class ParamSampler : Param {
- %[
- The Sampler stored by the Param.
- %]
- [getter, setter, property=rw] Sampler? value_;
-};
-
-%[
- A Param which stores a Texture.
-%]
-[nocpp, include="core/cross/param.h"] class ParamTexture : Param {
- %[
- The Texture stored by the Param.
- %]
- [getter, setter, property=rw] Texture? value_;
-};
-
-%[
- A Param which stores a Material.
-%]
-[nocpp, include="core/cross/param.h"] class ParamMaterial : Param {
- %[
- The Material stored by the Param.
- %]
- [getter, setter, property=rw] Material? value_;
-};
-
-%[
- A Param which stores a State.
-%]
-[nocpp, include="core/cross/param.h"] class ParamState : Param {
- %[
- The State stored by the Param.
- %]
- [getter, setter, property=rw] State? value_;
-};
-
-%[
- A Param which stores a Effect.
-%]
-[nocpp, include="core/cross/param.h"] class ParamEffect : Param {
- %[
- The Effect stored by the Param.
- %]
- [getter, setter, property=rw] Effect? value_;
-};
-
-%[
- A Param which stores a Transform.
-%]
-[nocpp, include="core/cross/param.h"] class ParamTransform : Param {
- %[
- The Transform stored by the Param.
- %]
- [getter, setter, property=rw] Transform? value_;
-};
-
-%[
- A Param which stores a DrawList.
-%]
-[nocpp, include="core/cross/draw_context.h"] class ParamDrawList : Param {
- %[
- The DrawList stored by the Param.
- %]
- [getter, setter, property=rw] DrawList? value_;
-};
-
-%[
- A Param which stores a DrawContext.
-%]
-[nocpp, include="core/cross/param.h"] class ParamDrawContext : Param {
- %[
- The DrawContext stored by the Param.
- %]
- [getter, setter, property=rw] DrawContext? value_;
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/param_array.idl b/o3d/plugin/idl/param_array.idl
deleted file mode 100644
index 63156d4..0000000
--- a/o3d/plugin/idl/param_array.idl
+++ /dev/null
@@ -1,149 +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.
- */
-
-namespace o3d {
-
-%[
- A ParamArray is an object that holds an array of Params.
-%]
-
-[nocpp, include="core/cross/param_array.h"] class ParamArray
- : NamedObject {
-
- %[
- Creates a Param of the given type at the index requested. If a Param
- already exists at that index the new param will be replace it. If the
- index is past the end of the current array params of the requested type
- will be created to fill out the array to the requested index.
-
- \param index index at which to create new param.
- \param param_type_name The type of Param to create. For a list of valid
- types see ParamObject.createParam
- \return Param created at index or null if failure.
-
- %]
- [userglue] Param? CreateParam(unsigned int index, String param_type_name);
-
- %[
- Gets a Param by index.
-
- \param index Index of Param to get.
- \return The Param at index, or null if out of range.
- %]
- [userglue, const] Param? GetParam(unsigned int index);
-
- %[
- Removes a range of params.
-
- \param start_index Index of first param to remove.
- \param num_to_remove The number of params to remove starting at start_index.
- %]
- void RemoveParams(unsigned int start_index, unsigned int num_to_remove);
-
- %[
- Resizes the array.
-
- \param num_params The number of params to make the array.
- \param param_type_name The type of Param to create if resizing
- requires params to be created. For a list of valid types see
- ParamObject.createParam
- %]
- [userglue] void Resize(unsigned int num_params, String param_type_name);
-
- %[
- Gets all the param on this param object.
-
- Each access to this field gets the entire list, so it is best to get it
- just once. For example:
- \code
- var params = ParamArray.params;
- for (var i = 0; i < params.length; i++) {
- var param = params[i];
- }
- \endcode
-
- Note that modifications to this array [e.g. push()] will not affect
- the underlying ParamObject, while modifications to the array's members
- <strong>will</strong> affect them.
- %]
- [userglue_getter, getter] ParamVector params_;
-
- %[
- Returns the number of parameters in this ParamArray.
- %]
- [userglue_getter, getter] unsigned int length;
-
- [verbatim=cpp_glue] %{
- o3d::ParamVector userglue_getter_params_(
- o3d::ParamArray *self) {
- const o3d::ParamArray::ParamRefVector& src_params = self->params();
- o3d::ParamVector params(src_params.size());
- for (unsigned ii = 0; ii < src_params.size(); ++ii) {
- params[ii] = src_params[ii];
- }
- return params;
- }
- unsigned int userglue_getter_length(
- o3d::ParamArray *self) {
- return self->size();
- }
- o3d::Param* userglue_method_CreateParam(
- o3d:: ParamArray *self,
- unsigned int index,
- const o3d::String& param_type_name) {
- return self->CreateParamByClassName(index, param_type_name);
- }
- void userglue_method_Resize(
- o3d:: ParamArray *self,
- unsigned int num_params,
- const o3d::String& param_type_name) {
- self->ResizeByClassName(num_params, param_type_name);
- }
- o3d::Param* userglue_method_GetParam(
- o3d:: ParamArray *self,
- unsigned int index) {
- return self->GetUntypedParam(index);
- }
- %}
-
-}; // ParamArray
-
-%[
- A Param which stores a ParamArray.
-%]
-[nocpp, include="core/cross/param.h"] class ParamParamArray : Param {
- %[
- The ParamArray stored by the Param.
- %]
- [getter, setter] ParamArray value_;
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/param_object.idl b/o3d/plugin/idl/param_object.idl
deleted file mode 100644
index b0877a5..0000000
--- a/o3d/plugin/idl/param_object.idl
+++ /dev/null
@@ -1,164 +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.
- */
-
-namespace o3d {
-
-%[
- A ParamObject is the base class for all objects that can have Params.
- Defines methods to add and remove params, search for params, etc.
-%]
-[nocpp, include="core/cross/param_object.h"]
-class ParamObject : NamedObject {
- %[
- Creates a Param with the given name and type on the ParamObject.
- Will fail if a param with the same name already exists.
-
- \param param_name The name of the Param to be created.
- \param param_type_name The type of Param to create. Valid types are
- \li 'o3d.ParamBoolean'
- \li 'o3d.ParamBoundingBox'
- \li 'o3d.ParamDrawContext'
- \li 'o3d.ParamDrawList'
- \li 'o3d.ParamEffect'
- \li 'o3d.ParamFloat'
- \li 'o3d.ParamFloat2'
- \li 'o3d.ParamFloat3'
- \li 'o3d.ParamFloat4'
- \li 'o3d.ParamFunction'
- \li 'o3d.ParamInteger'
- \li 'o3d.ParamMaterial'
- \li 'o3d.ParamMatrix4'
- \li 'o3d.ParamParamArray'
- \li 'o3d.ParamRenderSurface'
- \li 'o3d.ParamRenderDepthStencilSurface'
- \li 'o3d.ParamSampler'
- \li 'o3d.ParamSkin'
- \li 'o3d.ParamStreamBank'
- \li 'o3d.ParamState'
- \li 'o3d.ParamString'
- \li 'o3d.ParamTexture'
- \li 'o3d.ParamTransform'
- \li 'o3d.ProjectionParamMatrix4'
- \li 'o3d.ProjectionInverseParamMatrix4'
- \li 'o3d.ProjectionTransposeParamMatrix4'
- \li 'o3d.ProjectionInverseTransposeParamMatrix4'
- \li 'o3d.ViewParamMatrix4'
- \li 'o3d.ViewInverseParamMatrix4'
- \li 'o3d.ViewTransposeParamMatrix4'
- \li 'o3d.ViewInverseTransposeParamMatrix4'
- \li 'o3d.ViewProjectionParamMatrix4'
- \li 'o3d.ViewProjectionInverseParamMatrix4'
- \li 'o3d.ViewProjectionTransposeParamMatrix4'
- \li 'o3d.ViewProjectionInverseTransposeParamMatrix4'
- \li 'o3d.WorldParamMatrix4'
- \li 'o3d.WorldInverseParamMatrix4'
- \li 'o3d.WorldTransposeParamMatrix4'
- \li 'o3d.WorldInverseTransposeParamMatrix4'
- \li 'o3d.WorldViewParamMatrix4'
- \li 'o3d.WorldViewInverseParamMatrix4'
- \li 'o3d.WorldViewTransposeParamMatrix4'
- \li 'o3d.WorldViewInverseTransposeParamMatrix4'
- \li 'o3d.WorldViewProjectionParamMatrix4'
- \li 'o3d.WorldViewProjectionInverseParamMatrix4'
- \li 'o3d.WorldViewProjectionTransposeParamMatrix4'
- \li 'o3d.WorldViewProjectionInverseTransposeParamMatrix4'
- \return The newly created Param or null on failure.
- %]
- [userglue, noreturndocs]
- Param? CreateParam(String param_name, String param_type_name);
-
- %[
- Searches by name for a Param defined in the object.
-
- \param param_name Name to search for.
- \return The Param with the given name, or null otherwise.
- %]
- [userglue, const, noreturndocs]
- Param? GetParam(String param_name);
-
- %[
- Removes a Param from a ParamObject.
-
- This function will fail if the param does not exist on this ParamObject
- or if the param is unremovable.
-
- \param param param to remove.
- \return True if the param was removed.
- %]
- bool RemoveParam(Param param);
-
- %[
- Gets all the param on this param object.
-
- Each access to this field gets the entire list, so it is best to get it
- just once. For example:
- \code
- var params = paramObject.params;
- for (var i = 0; i < params.length; i++) {
- var param = params[i];
- }
- \endcode
-
- Note that modifications to this array [e.g. push()] will not affect
- the underlying ParamObject, while modifications to the array's members
- <strong>will</strong> affect them.
- %]
- [userglue_getter, getter, property=r] ParamVector params_;
-
- %[
- Copies all the params from a the given source_param_object to this param
- object. Does not replace any currently existing params with the same name.
-
- \param source_param_object param object to copy params from.
- %]
- void CopyParams(ParamObject source_param_object);
-
- [verbatim=cpp_glue] %{
- o3d::ParamVector userglue_getter_params_(
- o3d::ParamObject *self) {
- return self->GetParams();
- }
- o3d::Param* userglue_method_CreateParam(
- o3d:: ParamObject *self,
- const o3d::String& param_name,
- const o3d::String& param_type_name) {
- return self->CreateParamByClassName(param_name, param_type_name);
- }
-
- o3d::Param* userglue_method_GetParam(
- o3d:: ParamObject *self,
- const o3d::String& param_name) {
- return self->GetUntypedParam(param_name);
- }
- %}
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/param_operation.idl b/o3d/plugin/idl/param_operation.idl
deleted file mode 100644
index ddb086e..0000000
--- a/o3d/plugin/idl/param_operation.idl
+++ /dev/null
@@ -1,353 +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.
- */
-
-namespace o3d {
-
-%[
- A Param operation that takes 2 floats to produce a Float2.
-
- @o3dparameter input0 ParamFloat The first float.
- @o3dparameter input1 ParamFloat The second float.
- @o3dparameter output ParamFloat2 The Float2 that is the combination of input0
- and input1.
-%]
-[nocpp, include="core/cross/param_operation.h"]
-class ParamOp2FloatsToFloat2 : ParamObject {
- %[
- The first value for the Float2.
- Default = 0.
- %]
- [getter, setter] float input_0;
-
- %[
- The second value for the Float2.
- Default = 0.
- %]
- [getter, setter] float input_1;
-
- %[
- The Float2 that results from the inputs.
- %]
- [getter] Float2 output;
-};
-
-%[
- A Param operation that takes 3 floats to produce a Float3.
-
- @o3dparameter input0 ParamFloat The first float.
- @o3dparameter input1 ParamFloat The second float.
- @o3dparameter input2 ParamFloat The third float.
- @o3dparameter output ParamFloat3 The Float3 that is the combination of input0,
- input1, and input2.
-%]
-[nocpp, include="core/cross/param_operation.h"]
-class ParamOp3FloatsToFloat3 : ParamObject {
- %[
- The first value for the Float3.
- Default = 0.
- %]
- [getter, setter] float input_0;
-
- %[
- The second value for the Float3.
- Default = 0.
- %]
- [getter, setter] float input_1;
-
- %[
- The third value for the Float3.
- Default = 0.
- %]
- [getter, setter] float input_2;
-
- %[
- The Float3 that results from the inputs.
- %]
- [getter] Float3 output;
-};
-
-%[
- A Param operation that takes 4 floats to produce a Float4.
-
- @o3dparameter input0 ParamFloat The first float.
- @o3dparameter input1 ParamFloat The second float.
- @o3dparameter input2 ParamFloat The third float.
- @o3dparameter input3 ParamFloat The fourth float.
- @o3dparameter output ParamFloat4 The Float4 that is the combination of input0,
- input1, input2, and input3.
-%]
-[nocpp, include="core/cross/param_operation.h"]
-class ParamOp4FloatsToFloat4 : ParamObject {
- %[
- The first value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_0;
-
- %[
- The second value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_1;
-
- %[
- The third value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_2;
-
- %[
- The fourth value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_3;
-
- %[
- The Float4 that results from the inputs.
- %]
- [getter] Float4 output;
-};
-
-%[
- A Param operation that takes 16 floats to produce a Matrix4.
-
- @o3dparameter input0 ParamFloat The 1st float.
- @o3dparameter input1 ParamFloat The 2nd float.
- @o3dparameter input2 ParamFloat The 3rd float.
- @o3dparameter input3 ParamFloat The 4th float.
- @o3dparameter input4 ParamFloat The 5th float.
- @o3dparameter input5 ParamFloat The 6th float.
- @o3dparameter input6 ParamFloat The 7th float.
- @o3dparameter input7 ParamFloat The 8th float.
- @o3dparameter input8 ParamFloat The 9th float.
- @o3dparameter input9 ParamFloat The 10th float.
- @o3dparameter input10 ParamFloat The 11th float.
- @o3dparameter input11 ParamFloat The 12th float.
- @o3dparameter input12 ParamFloat The 13th float.
- @o3dparameter input13 ParamFloat The 14th float.
- @o3dparameter input14 ParamFloat The 15th float.
- @o3dparameter input15 ParamFloat The 16th float.
- @o3dparameter output ParamMatrix4 The Matrix4 that is the combination of
- the inputs in the following order
- <pre>
- [[input0, input1, input2, input3],
- [input4, input5, input6, input7],
- [input8, input9, input10, input11],
- [input12, input13, input14, input15]]
- </pre>
-%]
-[nocpp, include="core/cross/param_operation.h"]
-class ParamOp16FloatsToMatrix4 : ParamObject {
- %[
- The first value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_0;
-
- %[
- The second value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_1;
-
- %[
- The third value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_2;
-
- %[
- The fourth value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_3;
-
- %[
- The fifth value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_4;
-
- %[
- The sixth value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_5;
-
- %[
- The seventh value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_6;
-
- %[
- The eighth value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_7;
-
- %[
- The ninth value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_8;
-
- %[
- The tenth value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_9;
-
- %[
- The eleventh value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_10;
-
- %[
- The twelfth value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_11;
-
- %[
- The thirteenth value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_12;
-
- %[
- The fourteenth value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_13;
-
- %[
- The fifteenth value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_14;
-
- %[
- The sixteenth value for the Float4.
- Default = 0.
- %]
- [getter, setter] float input_15;
-
- %[
- The Matrix4 that results from the inputs.
- %]
- [getter] Vectormath::Aos::Matrix4 output;
-};
-
-%[
- A Param operation that takes 9 floats to produce a 4-by-4 matrix.
- The 9 floats encode a translation vector, angles of rotation around the x, y,
- and z axes, and three scaling factors. The resulting transformation scales
- first, then then rotates around the z-axis, then the y-axis, then the x-axis,
- then translates.
-
- @o3dparameter translateX ParamFloat The x component of the translation.
- @o3dparameter translateY ParamFloat The y component of the translation.
- @o3dparameter translateZ ParamFloat The z component of the translation.
- @o3dparameter rotateX ParamFloat The x component of the rotation.
- @o3dparameter rotateY ParamFloat The y component of the rotation.
- @o3dparameter rotateZ ParamFloat The z component of the rotation.
- @o3dparameter scaleX ParamFloat The x component of the scale.
- @o3dparameter scaleY ParamFloat The y component of the scale.
- @o3dparameter scaleZ ParamFloat The z component of the scale.
- @o3dparameter output ParamMatrix4 The matrix described by the components.
-%]
-[nocpp, include="core/cross/param_operation.h"]
-class TRSToMatrix4 : ParamObject {
- %[
- The x translation for the Matrix4.
- Default = 0.
- %]
- [getter, setter] float translate_x;
-
- %[
- The y translation for the Matrix4.
- Default = 0.
- %]
- [getter, setter] float translate_y;
-
- %[
- The z translation for the Matrix4.
- Default = 0.
- %]
- [getter, setter] float translate_z;
-
- %[
- The x rotation for the Matrix4.
- Default = 0.
- %]
- [getter, setter] float rotate_x;
-
- %[
- The y rotation for the Matrix4.
- Default = 0.
- %]
- [getter, setter] float rotate_y;
-
- %[
- The z rotation for the Matrix4.
- Default = 0.
- %]
- [getter, setter] float rotate_z;
-
- %[
- The x scale for the Matrix4.
- Default = 0.
- %]
- [getter, setter] float scale_x;
-
- %[
- The y scale for the Matrix4.
- Default = 0.
- %]
- [getter, setter] float scale_y;
-
- %[
- The z scale for the Matrix4.
- Default = 0.
- %]
- [getter, setter] float scale_z;
-
- %[
- The Matrix4 that results from the inputs.
- %]
- [getter] Vectormath::Aos::Matrix4 output;
-};
-
-} // namespace o3d
-
-
diff --git a/o3d/plugin/idl/pattern.idl b/o3d/plugin/idl/pattern.idl
deleted file mode 100644
index c6779de..0000000
--- a/o3d/plugin/idl/pattern.idl
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Copyright 2011, 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.
- */
-
-namespace o3d {
-
-namespace o2d {
-
-%[
- A Pattern is a container for pixel content for painting to a Layer.
-%]
-[nocpp, include="core/cross/cairo/pattern.h"] class Pattern : ObjectBase {
- %[
- Available extend methods.
-
- \var ExtendType,
- \li NONE, Pixels outside of the source pattern are fully transparent
- \li REPEAT, The pattern is tiled by repeating
- \li REFLECT, The pattern is tiled by reflecting at the edges
- \li PAD, Pixels outside of the pattern copy the closest pixel from the
- source
- %]
- enum ExtendType {
- NONE,
- REPEAT,
- REFLECT,
- PAD
- };
-
- %[
- Available resizing filters.
-
- \var FilterType,
- \li FAST, A high-performance filter, with quality similar to NEAREST
- \li GOOD, A reasonable-performance filter, with quality similar to BILINEAR
- \li BEST, The highest-quality available, performance may not be suitable
- for interactive use
- \li NEAREST, Nearest-neighbor filtering
- \li BILINEAR, Linear interpolation in two dimensions
- %]
- enum FilterType {
- FAST,
- GOOD,
- BEST,
- NEAREST,
- BILINEAR
- };
-
- %[
- Create a pattern that paints the content of a texture.
-
- \param pack The Pack to add the created object to.
- \param texture The texture to paint.
- \return The created pattern
- %]
- [static] Pattern? CreateTexturePattern(Pack pack, Texture texture);
-
- %[
- Create a pattern that paints a solid colour.
-
- \param pack The Pack to add the created object to.
- \param red The red component.
- \param blue The blue component.
- \param green The green component.
- \return The created pattern
- %]
- [static] Pattern? CreateRgbPattern(Pack pack,
- double red,
- double green,
- double blue);
-
- %[
- Create a pattern that paints a solid colour with transparency.
-
- \param pack The Pack to add the created object to.
- \param red The red component.
- \param blue The blue component.
- \param green The green component.
- \param alpha The alpha component.
- \return The created pattern
- %]
- [static] Pattern? CreateRgbaPattern(Pack pack,
- double red,
- double green,
- double blue,
- double alpha);
-
- %[
- Set the affine transformation matrix that maps user space to pattern space.
- The default matrix is the identity matrix, so that no transformation occurs.
-
- \param xx xx component of the affine transformation
- \param yx yx component of the affine transformation
- \param xy xy component of the affine transformation
- \param yy yy component of the affine transformation
- \param x0 X translation component of the affine transformation
- \param y0 Y translation component of the affine transformation
- %]
- void SetAffineTransform(double xx,
- double yx,
- double xy,
- double yy,
- double x0,
- double y0);
-
- %[
- The extend method to use to fill in areas outside of this Pattern.
- %]
- [setter] ExtendType extend;
-
- %[
- The filter to use when resizing this Pattern.
- %]
- [setter] FilterType filter;
-}; // Pattern
-
-} // namespace o2d
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/plugin.idl b/o3d/plugin/idl/plugin.idl
deleted file mode 100644
index 26a00b9..0000000
--- a/o3d/plugin/idl/plugin.idl
+++ /dev/null
@@ -1,59 +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 public interface specification for the plugin.
-
-[verbatim=js_header] %{
- /*!
- * \mainpage API Reference
- *
- * O3D is a plug-in for your browser. In order to make o3d produce
- * the graphics you see in the demos, you'll need to access the plug-in and its
- * components from within JavaScript. You can do so through a member variable
- * on the plug-in called \a client, representing the instance of o3d within
- * the plug-in.
- *
- * Here is how to access the client itself:
- * \code
- * g_client = document.o3d.client;
- * \endcode
- *
- * where <code>document.o3d</code>
- * represents the plug-in (rather than the Client instance within the plug-in).
- * Not much else can be done with the plug-in, so you will want to access
- * the \a client as shown above.
- *
- * Now that you know how to access the instance of o3d from your
- * JavaScript, check out the rest of the API for more information on how to
- * make o3d do what you want.
- */
-%}
diff --git a/o3d/plugin/idl/primitive.idl b/o3d/plugin/idl/primitive.idl
deleted file mode 100644
index cf32673..0000000
--- a/o3d/plugin/idl/primitive.idl
+++ /dev/null
@@ -1,100 +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.
- */
-
-namespace o3d {
-
-%[
- A Primitive is a type of Element that is made from a list of points,
- lines or triangles that use a single material.
-
- @o3dparameter streamBank ParamStreamBank The StreamBank used by this
- Primitive.
-%]
-[nocpp, include="core/cross/primitive.h"]
-class Primitive : Element {
- %[
- \var PrimitiveType,
- \li POINTLIST,
- \li LINELIST,
- \li LINESTRIP,
- \li TRIANGLELIST,
- \li TRIANGLESTRIP,
- \li TRIANGLEFAN
-
- Type of geometric primitives used by the Primitive.
- %]
- enum PrimitiveType {
- POINTLIST = 1,
- LINELIST = 2,
- LINESTRIP = 3,
- TRIANGLELIST = 4,
- TRIANGLESTRIP = 5,
- TRIANGLEFAN = 6
- };
-
- %[
- The type of primitive the primitive is (i.e., Primitive::POINTLIST,
- Primitive::LINELIST, Primitive::TRIANGLELIST, etc.)
- Default = TRIANGLELIST.
- %]
- [getter, setter] Primitive::PrimitiveType primitive_type;
-
- %[
- The number of vertices the primitive has.
- Default = 0.
- %]
- [getter, setter] unsigned int number_vertices;
-
- %[
- The number of rendering primitives (i.e., triangles, points, lines) the
- primitive has.
- Default = 0.
- %]
- [getter, setter] unsigned int number_primitives;
-
- %[
- The index of the first vertex to render.
- Default = 0.
- %]
- [getter, setter] unsigned int start_index;
-
- %[
- The stream bank this primitive uses for vertices.
- %]
- [getter, setter] StreamBank? stream_bank;
-
- %[
- The index buffer for the primitive. If null the primitive is non-indexed.
- %]
- [getter, setter] IndexBuffer? index_buffer;
-}; // Primitive
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/processed_path.idl b/o3d/plugin/idl/processed_path.idl
deleted file mode 100644
index 0ba7ca8..0000000
--- a/o3d/plugin/idl/processed_path.idl
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-namespace o3d {
-
-%[
- A ProcessedPath holds a series of 2D vector drawing commands (i.e.,
- move-to, line-to, quad-to, cubic-to) and the results of processing
- this series of commands into a triangle mesh for rendering on the
- GPU. It is only an internal class; this functionality is exposed via
- the o3djs.gpu2d library.
-%]
-
-[nocpp, include="core/cross/processed_path.h"] class ProcessedPath
- : ObjectBase {
- %[
- Clears out all of the curve segments that have been added to this
- path.
- %]
- [nodocs]
- void Clear();
-
- %[
- Moves the pen to the given absolute X,Y coordinates. If a contour
- isn't currently open on this path, one is opened.
- \param x the x coordinate to move to
- \param y the y coordinate to move to
- %]
- [nodocs]
- void MoveTo(float x, float y);
-
- %[
- Draws a line from the current coordinates to the given absolute
- X,Y coordinates.
- \param x the x coordinate to draw a line to
- \param y the y coordinate to draw a line to
- %]
- [nodocs]
- void LineTo(float x, float y);
-
- %[
- Draws a quadratic curve from the current coordinates through the
- given control point and end point, specified in absolute
- coordinates.
- \param cx the x coordinate of the quadratic's control point
- \param cy the y coordinate of the quadratic's control point
- \param x the x coordinate of the quadratic's end point
- \param y the y coordinate of the quadratic's end point
- %]
- [nodocs]
- void QuadraticTo(float cx, float cy, float x, float y);
-
- %[
- Draws a cubic curve from the current coordinates through the
- given control points and end point, specified in absolute
- coordinates.
- \param c0x the x coordinate of the cubic's first control point
- \param c0y the y coordinate of the cubic's first control point
- \param c1x the x coordinate of the cubic's second control point
- \param c1y the y coordinate of the cubic's second control point
- \param x the x coordinate of the cubic's end point
- \param y the y coordinate of the cubic's end point
- %]
- [nodocs]
- void CubicTo(float c0x, float c0y,
- float c1x, float c1y,
- float x, float y);
-
- %[
- Closes the currently open contour on this path.
- %]
- [nodocs]
- void Close();
-
- %[
- Creates the triangle mesh which will render the given curve
- segments. There are two regions: exterior and interior. The
- exterior region covers the portions containing the curve
- segments. It has two associated fields: a 2D floating point field
- for the positions, and a 3D floating point field for the
- Loop/Blinn texture coordinates. The interior region has one 2D
- floating point field for the positions. The contents of the fields
- are organized for rendering as non-indexed triangles.
- %]
- [nodocs]
- void CreateMesh(Field exterior_positions,
- Field exterior_texture_coordinates,
- Field interior_positions);
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/raw_data.idl b/o3d/plugin/idl/raw_data.idl
deleted file mode 100644
index c252f46..0000000
--- a/o3d/plugin/idl/raw_data.idl
+++ /dev/null
@@ -1,88 +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.
- */
-
-namespace o3d {
-
-%[
- A RawData object contains raw binary data which could contain
- image, audio, text, or other information.
-
- \code
- var request = g_pack.createArchiveRequest();
-
- request.onfileavailable = function(rawData) {
- var texture = g_pack.createTextureFromRawData(rawData, true);
- ...
- };
-
- request.send();
-
- \endcode
-%]
-
-[nocpp, include="import/cross/raw_data.h"] class RawData : ParamObject {
- %[
- Returns the raw data as a string. The data must be a valid utf-8 string
- and the uri must end in .json, .txt, .xml, .ini or .csv
- %]
- [getter, userglue_getter, StringValue] String string_value;
-
- %[
- The uri of the RawData.
- %]
- [getter] String uri;
-
- %[
- The length in bytes of the RawData.
- %]
- [getter=GetLength] size_t length;
-
- %[
- Discards all the resources associated with this data object.
- %]
- void Discard();
-
- %[
- Flushes the memory resources associated with this data object,
- but keeps a cache in case the data object is used later.
- %]
- void Flush();
-
- [verbatim=cpp_glue, include="import/cross/raw_data.h"] %{
- o3d::String userglue_getter_string_value(
- o3d::RawData* self) {
- return self->StringValue();
- }
- %}
-
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/ray_intersection_info.idl b/o3d/plugin/idl/ray_intersection_info.idl
deleted file mode 100644
index 176a46e..0000000
--- a/o3d/plugin/idl/ray_intersection_info.idl
+++ /dev/null
@@ -1,64 +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.
- */
-
-namespace o3d {
-
-%[
- A RayIntersectionInfo is used to return the results of ray intersection tests.
-%]
-
-[binding_model=by_value, nocpp, include="core/cross/ray_intersection_info.h"]
-class RayIntersectionInfo {
- %[
- True if this ray intersection info is valid. For example if you call
- element.intersectRay on an element that has no vertex buffers the result
- will be invalid.
- %]
- [getter] bool valid_;
-
- %[
- True if this ray intersection intersected something.
- %]
- [getter] bool intersected_;
-
- %[
- The position the ray intersected something.
- %]
- [getter] Vectormath::Aos::Point3 position;
-
- %[
- The index of the primitive that was intersected.
- %]
- [getter] int primitive_index_;
-
-}; // RayIntersectionInfo
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/render_event.idl b/o3d/plugin/idl/render_event.idl
deleted file mode 100644
index 4719596..0000000
--- a/o3d/plugin/idl/render_event.idl
+++ /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 defines the public interface for the RenderEvent class.
-
-namespace o3d {
-
-%[
- This class is used to pass infomation to a registered onrender callback.
-%]
-[binding_model=by_value, include="core/cross/render_event.h",
- nocpp,glue_iface] class RenderEvent {
- %[
- The elapsed time in seconds since the last frame was rendered.
- %]
- [getter] float elapsed_time_;
-
- %[
- The time it took to render.
- %]
- [getter] float render_time_;
-
- %[
- The time it took to render and process tick callbacks, render callbacks,
- counter callbacks.
- %]
- [getter] float active_time_;
-
- %[
- The number of transforms processed last frame.
-
- This is the number of transforms the renderer considered for traversing.
- A Transform may not be considered for traversing either because it is not in
- one of the subtrees the TreeTraversals are setup to traverse or because it
- one of its parents was culled or set to visible = false.
- %]
- [getter] int transforms_processed_;
-
- %[
- The number of transforms that were culled last frame directly.
-
- Of the transforms processed, how many were culled.
- %]
- [getter] int transforms_culled_;
-
- %[
- The number of draw elements processed last frame.
-
- This is the number of draw elements the renderer considered for rendering.
- If a transform is not traversed either because it is not in one of the
- subtrees the TreeTraversals are setup to traverse or because it is marked
- as visible = false then any draw elements in that part of the transform
- graph are not processed.
- %]
- [getter] int draw_elements_processed_;
-
- %[
- The number of draw elements that were culled last frame directly.
- (vs culled hierarchically)
- %]
- [getter] int draw_elements_culled_;
-
- %[
- The number of draw elements rendered last frame. Note: a draw element can
- be rendered more than once per frame based on how many transforms it is
- under and how many DrawPasses use the DrawLists it is put on.
- %]
- [getter] int draw_elements_rendered_;
-
- %[
- The number of low-level primitives rendered last frame. This is the sum of
- the number primitives (triangles, lines) submitted to the renderer.
- %]
- [getter] int primitives_rendered_;
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/render_node.idl b/o3d/plugin/idl/render_node.idl
deleted file mode 100644
index 44696b8..0000000
--- a/o3d/plugin/idl/render_node.idl
+++ /dev/null
@@ -1,140 +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.
- */
-
-namespace o3d {
-
-%[
- RenderNode is the base of all RenderNodes in the render graph.
- RenderNodes are rendered in order of priority.
-
- @o3dparameter priority ParamFloat The priority of this render node. Lower
- priorities are rendered first.
- @o3dparameter active ParamBoolean If true this node is processed. If false
- it is not.
-%]
-[nocpp, include="core/cross/render_node.h"]
- class RenderNode : ParamObject {
-
- %[
- Sets the priority of this render node. lower priorities are rendered first.
- Default = 0.
- %]
- [getter, setter] float priority_;
-
- %[
- Setting false skips this render node. Setting true processes this render
- node. (ie, renders whatever it's supposed to render)
- Default = true.
- %]
- [getter, setter] bool active_;
-
- %[
- Sets the parent of the node by re-parenting the node under parent_node.
- Setting parent_node to null removes the node and the entire subtree below
- it from the render graph.
- %]
- [setter, userglue_setter] RenderNode? parent_;
-
- %[
- The immediate children of this RenderNode.
-
- Each access to this field gets the entire list so it is best to get it
- just once. For example:
- \code
- var children = renderNode.children;
- for (var i = 0; i < children.length; i++) {
- var child = children[i];
- }
- \endcode
-
- Note that modifications to this array [e.g. push()] will not affect
- the underlying RenderNode, while modifications to the array's members
- <strong>will</strong> affect them.
- %]
- [userglue_getter, getter] RenderNodeArray children_;
-
- %[
- Returns this render node and all its descendants. Note that this render node
- might not be in the render graph.
-
- Note that modifications to this array [e.g. push()] will not affect
- the underlying RenderNode, while modifications to the array's members
- <strong>will</strong> affect them.
-
- \return An array containing all render nodes of the subtree.
- %]
- [nocpp] RenderNodeArray GetRenderNodesInTree();
-
- %[
- Searches for render nodes that match the given name in the hierarchy under
- and including this render node. Since there can be several render nodes with
- a given name the results are returned in an array.
-
- Note that modifications to this array [e.g. push()] will not affect
- the underlying RenderNode, while modifications to the array's members
- <strong>will</strong> affect them.
-
- \param name Rendernode name to look for.
- \return An array containing all nodes among this node and its decendants
- that have the given name.
- %]
- [nocpp] RenderNodeArray GetRenderNodesByNameInTree(String name);
-
- %[
- Searches for render nodes that match the given class name in the hierarchy
- under and including this render node.
-
- Note that modifications to this array [e.g. push()] will not affect
- the underlying RenderNode, while modifications to the array's members
- <strong>will</strong> affect them.
-
- \param class_name class name to look for.
- \return An array containing all nodes among this node and its decendants
- whose type is class_name.
- %]
- RenderNodeArray GetRenderNodesByClassNameInTree(String class_name);
-
- [verbatim=cpp_glue] %{
- void userglue_setter_parent_(
- o3d::RenderNode* _this,
- o3d::RenderNode* parent) {
- _this->SetParent(parent);
- }
- o3d::RenderNodeArray userglue_getter_children_(
- o3d::RenderNode *self) {
- return self->GetChildren();
- }
- %}
-}; // RenderNode
-
-typedef RenderNode[] RenderNodeArray;
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/render_surface.idl b/o3d/plugin/idl/render_surface.idl
deleted file mode 100644
index 183341c..0000000
--- a/o3d/plugin/idl/render_surface.idl
+++ /dev/null
@@ -1,105 +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.
- */
-
-namespace o3d {
-
-%[
- A RenderSurfaceBase is the base for RenderSurface and
- RenderDepthStencilSurface.
-
- @o3dparameter width ParamInteger The width of this RenderSurface.
- [Read Only]
- @o3dparameter height ParamInteger The height of this RenderSurface.
- [Read Only]
- @o3dparameter texture ParamTexture The texture of this RenderSurface.
- [Read Only]
-%]
-[nocpp, include="core/cross/render_surface.h"] class RenderSurfaceBase
- : ParamObject {
- %[
- The width of the surface, in pixels.
- %]
- [field_access=private, getter] int width;
-
- %[
- The height of the surface, in pixels.
- %]
- [field_access=private, getter] int height;
-
-}; // RenderSurfaceBaes
-
-
-%[
- A RenderSurface encapsulates the notion of a renderable surface.
- When used in conjunction with a RenderSurfaceSet node in the render graph,
- the API allows for rendering of primitives to the given surface.
- RenderSurface objects are not constructable through the Pack API, they may
- only be accessed through the texture getRenderSurface(...) interfaces.
-%]
-[nocpp, include="core/cross/render_surface.h"] class RenderSurface
- : RenderSurfaceBase {
- %[
- The texture in which this surface is contained.
- %]
- [field_access=private, getter] Texture? texture;
-}; // RenderSurface
-
-%[
- A Param which stores a RenderSurface.
-%]
-[nocpp, include="core/cross/render_surface.h"] class ParamRenderSurface : Param
-{%[
- The RenderSurface stored by the Param.
- %]
- [getter, setter] RenderSurface? value_;
-};
-
-%[
- A RenderDepthStencilSurface represents a depth stencil render surface.
-%]
-[nocpp, include="core/cross/render_surface.h"]
-class RenderDepthStencilSurface
- : RenderSurfaceBase {
-}; // RenderDepthStencilSurface
-
-%[
- A Param which stores a RenderDepthStencilSurface.
-%]
-[nocpp, include="core/cross/render_surface.h"]
-class ParamRenderDepthStencilSurface : Param
-{%[
- The RenderDepthStencilSurface stored by the Param.
- %]
- [getter, setter] RenderDepthStencilSurface? value_;
-};
-
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/render_surface_set.idl b/o3d/plugin/idl/render_surface_set.idl
deleted file mode 100644
index bcfd858..0000000
--- a/o3d/plugin/idl/render_surface_set.idl
+++ /dev/null
@@ -1,67 +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.
- */
-
-namespace o3d {
-
-%[
- A RenderSurfaceSet node will bind depth and color RenderSurface nodes
- to the current rendering context. All RenderNodes descending
- from the given RenderSurfaceSet node will operate on the contents of
- the bound depth and color buffers.
- Note the following usage constraints of this node:
- 1) If both a color and depth surface is bound, then they must be of matching
- dimensions.
- 2) At least one of render_surface and render_depth_surface must non-null.
-
- @o3dparameter renderSurface ParamRenderSurface The render surface to set.
- @o3dparameter renderDepthStencilSurface ParamRenderDepthStencilSurface The
- depth stencil render surface to set.
-%]
-[nocpp, include="core/cross/render_surface_set.h"]
-class RenderSurfaceSet : RenderNode {
-
- %[
- The render surface to which the color contents of all RenderNode children
- should be drawn.
- %]
- [getter, setter]
- RenderSurface? render_surface_;
-
- %[
- The render depth stencil surface to which the depth contents of all
- RenderNode children should be drawn.
- %]
- [getter, setter]
- RenderDepthStencilSurface? render_depth_stencil_surface_;
-
-}; // RenderSurfaceSet
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/sampler.idl b/o3d/plugin/idl/sampler.idl
deleted file mode 100644
index a6608ed..0000000
--- a/o3d/plugin/idl/sampler.idl
+++ /dev/null
@@ -1,143 +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.
- */
-
-namespace o3d {
-
-%[
- Sampler is the base of all texture samplers. Texture samplers encapsulate
- a texture reference with a set of states that define how the texture
- gets applied to a surface. Sampler states are set either via Params defined
- on the Sampler object or directly via one the convenience methods defined
- on the Sampler. The following states are supported (default values are in
- parenthesis):
- \li 'addressModeU' (WRAP)
- \li 'addressModeV' (WRAP)
- \li 'addressModeW' (WRAP)
- \li 'magFilter' (LINEAR)
- \li 'minFilter' (LINEAR)
- \li 'mipFilter' (POINT)
- \li 'borderColor' ([0,0,0,0])
- \li 'maxAnisotropy' (1)
-%]
-
-[nocpp, include="core/cross/sampler.h"]
-class Sampler : ParamObject {
- %[
- \var AddressMode,
- Controls what happens with texture coordinates outside the [0..1] range.
- \li WRAP
- \li MIRROR
- \li CLAMP
- \li BORDER
- %]
- enum AddressMode {
- WRAP,
- MIRROR,
- CLAMP,
- BORDER
- };
-
- %[
- \var FilterType,
- Texture filtering types.
- \li NONE
- \li POINT
- \li LINEAR
- \li ANISOTROPIC
- %]
- enum FilterType {
- NONE,
- POINT,
- LINEAR,
- ANISOTROPIC
- };
-
- %[
- The texture address mode for the u coordinate.
- Default = WRAP.
- %]
- [getter, setter] AddressMode address_mode_u_;
-
- %[
- The texture address mode for the v coordinate.
- Default = WRAP.
- %]
- [getter, setter] AddressMode address_mode_v_;
-
- %[
- The texture address mode for the w coordinate.
- Default = WRAP.
- %]
- [getter, setter] AddressMode address_mode_w_;
-
- %[
- The magnification filter. Valid values for the mag filter are: POINT and
- LINEAR.
- Default = LINEAR.
- %]
- [getter, setter] FilterType mag_filter_;
-
- %[
- The minification filter. Valid values for the min filter are: POINT, LINEAR
- and ANISOTROPIC.
- Default = LINEAR.
- %]
- [getter, setter] FilterType min_filter_;
-
- %[
- The mipmap filter used during minification. Valid values for the mip filter
- are: NONE, POINT and LINEAR.
- Default = LINEAR.
- %]
- [getter, setter] FilterType mip_filter_;
-
- %[
- Color returned for texture coordinates outside the [0,1] range when the
- address mode is set to BORDER.
- Default = [0, 0, 0, 0].
- %]
- [getter, setter] Float4 border_color;
-
- %[
- Degree of anisotropy used when the ANISOTROPIC filter type is used.
- Default = 1.
- %]
- [getter, setter] int max_anisotropy_;
-
- %[
- The Texture object used by this Sampler.
- %]
- [getter, setter] Texture? texture_;
-}; // Sampler
-
-
-} // namespace o3d
-
diff --git a/o3d/plugin/idl/shape.idl b/o3d/plugin/idl/shape.idl
deleted file mode 100644
index b72f88f..0000000
--- a/o3d/plugin/idl/shape.idl
+++ /dev/null
@@ -1,89 +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.
- */
-
-namespace o3d {
-
-typedef Element[] ElementArray;
-
-%[
- The Shape represents a collection of Elements. The typical example is a
- cube with 6 faces where each face uses a different material would be
- represented as 1 Shape with 6 Elements, one for each material.
-%]
-
-[nocpp, include="core/cross/shape.h"] class Shape : ParamObject {
- %[
- The elements owned by this shape.
-
- Each access to this field gets the entire list so it is best to get it
- just once. For example:
- \code
- var elements = renderNode.elements;
- for (var i = 0; i < elements.length; i++) {
- var element = elements[i];
- }
- \endcode
-
- Note that modifications to this array [e.g. push()] will not affect
- the underlying Shape, while modifications to the array's members
- <strong>will</strong> affect them.
- %]
- [userglue_getter, getter, userglue_setter, setter]
- ElementArray elements_;
-
- %[
- Creates a DrawElement for each Element owned by this Shape.
- If an Element already has a DrawElement that uses \a material a new
- DrawElement will not be created.
- \param pack pack used to manage created DrawElements.
- \param material material to use for each DrawElement. If you pass null it
- will use the material on the corresponding Element.
- This allows you to easily setup the default (just draw as is) by passing
- null or setup a shadow pass by passing in a shadow material.
- %]
- void CreateDrawElements(Pack pack,
- Material? material);
-
- [verbatim=cpp_glue] %{
-
- o3d::ElementArray userglue_getter_elements_(
- o3d::Shape *self) {
- return self->GetElements();
- }
- void userglue_setter_elements_(
- o3d::Shape *_this,
- const o3d::ElementArray& elements) {
- _this->SetElements(elements);
- }
- %}
-}; // Shape
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/skin.idl b/o3d/plugin/idl/skin.idl
deleted file mode 100644
index 762358d..0000000
--- a/o3d/plugin/idl/skin.idl
+++ /dev/null
@@ -1,274 +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 idlglue declaration of Skin and SkinEval.
-
-namespace o3d {
-
-%[
- A Skin holds an array of matrix indices and influences for vertices in a skin.
- A Skin is data only and can be used by one or more SkinEvals to implement
- skinning.
-%]
-[nocpp, include="core/cross/skin.h"] class Skin
- : NamedObject {
-
- %[
- Sets the influences for an individual vertex.
-
- \param vertex_index The index of the vertex to set influences for
- \param influences An array of pairs of numbers where the first number
- is the index of the matrix to influence the vertex and the second
- number is the amount of influence where 0 = no influence and 1 = 100%
- influence.
- %]
- [userglue] void SetVertexInfluences(unsigned int vertex_index,
- NumberArray influences);
-
- %[
- Gets the influences for an individual vertex.
- \param vertex_index the index of the vertex to get influences from.
- \return Returns an Array of number pairs where the first number of each
- pair is the index of a matrix that influences this vertex and the
- second number is the amount of influence where 0 = no influence
- and 1 = 100% influcence.
- %]
- [const, userglue] NumberArray GetVertexInfluences(unsigned int vertex_index);
-
- %[
- An array with one element per vertex, where each element is an array of
- influences consisting of a number pair, where the first number is a
- matrix index and the second is the amount of influence.
- %]
- [getter,userglue_getter,setter,userglue_setter]
- NumberArray[] influences_;
-
- %[
- Sets the inverse bind pose matrix for a particular joint/bone/transform.
- \param index index of bone/joint/transform.
- \param matrix Inverse bind pose matrix for that joint.
- %]
- void SetInverseBindPoseMatrix(unsigned int index,
- Vectormath::Aos::Matrix4 matrix);
-
- %[
- The array of inverse bone matrices
- %]
- [getter,setter] Vectormath::Aos::Matrix4[]
- inverse_bind_pose_matrices_;
-
- // TODO: Add setter that takes an array of matrices and sets all
- // of the matrix arrays.
- // TODO: Add SetNumberInverseBindPoseMatrices
- // TODO: Add SetNumberVertexInflucences
-
- %[
- Deserializes from the skin data given a RawData object.
-
- \param raw_data contains skin data
- \param offset is a byte offset from the start of raw_data
- \param length is the byte length of the data to set
- \return True if operation was successful.
- %]
- bool Set(o3d::RawData raw_data,
- size_t offset,
- size_t length);
-
- %[
- Deserializes from the skin data given a RawData object.
- \param raw_data entire contents contains skin data
- \return True if operation was successful.
- %]
- bool Set(o3d::RawData raw_data);
-
- [verbatim=cpp_glue] %{
- void userglue_method_SetVertexInfluences(o3d::Skin* self,
- unsigned int vertex_index,
- const std::vector<float>& values) {
- if (values.size() % 2 != 0) {
- O3D_ERROR(self->service_locator())
- << "odd number of values passed into SetVertexInfluence. "
- << "Even number required as they are pairs.";
- } else {
- o3d::Skin::Influences influences;
- for (unsigned ii = 0; ii < values.size(); ii += 2) {
- influences.push_back(o3d::Skin::Influence(
- static_cast<unsigned int>(values[ii]),
- values[ii + 1]));
- }
- self->SetVertexInfluences(vertex_index, influences);
- }
- }
- std::vector<std::vector<float> > userglue_getter_influences_(
- o3d::Skin* _this) {
- const o3d::Skin::InfluencesArray& influences = _this->influences();
- std::vector<std::vector<float> > result(influences.size());
- for (int i = 0; i != influences.size(); ++i) {
- const o3d::Skin::Influences& vertex_influences = influences[i];
- for (int j = 0; j != vertex_influences.size(); ++j) {
- const o3d::Skin::Influence& influence = vertex_influences[j];
- result[i].push_back(static_cast<float>(influence.matrix_index));
- result[i].push_back(influence.weight);
- }
- }
- return result;
- }
- void userglue_setter_influences_(
- o3d::Skin* _this,
- const std::vector<std::vector<float> >& input) {
- for (int i = 0; i != input.size(); ++i) {
- const std::vector<float>& vertex_input = input[i];
- o3d::Skin::Influences influences(vertex_input.size() / 2);
- for (int j = 0; j != vertex_input.size() / 2; ++j) {
- influences[j] = o3d::Skin::Influence(
- static_cast<int>(vertex_input[j * 2]),
- vertex_input[j * 2 + 1]);
- }
- _this->SetVertexInfluences(i, influences);
- }
- }
- std::vector<float> userglue_method_GetVertexInfluences(
- o3d::Skin* self,
- unsigned int vertex_index) {
- std::vector<float> values;
- const o3d::Skin::Influences* influences =
- self->GetVertexInfluences(vertex_index);
- if (influences) {
- values.resize(influences->size() * 2);
- for (unsigned ii = 0; ii < influences->size(); ++ii) {
- values[ii * 2 + 0] =
- static_cast<float>((*influences)[ii].matrix_index);
- values[ii * 2 + 1] = (*influences)[ii].weight;
- }
- }
- return values;
- }
- %}
-
-}; // Skin
-
-%[
- A SkinEval is a VertexSource that takes its Streams, a ParamArray of 4-by-4
- matrices and a Skin and skins the vertices in its streams storing the results
- in bound output streams.
-%]
-[nocpp, include="core/cross/skin.h"] class SkinEval
- : VertexSource {
-
- %[
- The Skin to use for skinning.
- %]
- [getter, setter] Skin? skin;
-
- %[
- The array of matrices to use for skinning.
- %]
- [getter, setter] ParamArray matrices;
-
- %[
- The base matrix to subtract from the matrices before skinning.
- %]
- [getter, setter] Vectormath::Aos::Matrix4 base;
-
- %[
- Binds a SourceBuffer field to the SkinEval and defines how the data in the
- field should be interpreted. The field's buffer must be of a
- compatible type otherwise the binding fails and the function returns false.
- \param semantic The particular use of this stream.
- \param semantic_index Which index of a particular semantic to use.
- \param field The field containing information for this stream.
- \param start_index The first element to use.
- \return True if successful.
- %]
- [virtual] bool SetVertexStream(Stream::Semantic semantic,
- int semantic_index,
- Field field,
- unsigned int start_index);
-
-
- %[
- Removes a vertex stream from this SkinEval.
- \param semantic The particular use of this stream.
- \param semantic_index Which index of a particular semantic to use.
- \return true if the specified stream existed.
- %]
- bool RemoveVertexStream(Stream::Semantic semantic, int semantic_index);
-
- %[
- Searches the vertex streams bound to the SkinEval for one with the given
- stream semantic.
- \param semantic The particular use of this stream.
- \param semantic_index Which index of a particular semantic to use.
- \return The found stream or NULL if it does not exist.
- %]
- [userglue]
- Stream GetVertexStream(Stream::Semantic semantic, int semantic_index);
-
- %[
- A vector of the vertex streams on this SkinEval.
- %]
- [userglue_getter, getter] StreamVector vertex_streams;
-
- [verbatim=cpp_glue] %{
- std::vector<o3d::Stream*> userglue_getter_vertex_streams(
- o3d::SkinEval* self) {
- std::vector<o3d::Stream*> streams;
- const o3d::StreamParamVector& stream_params =
- self->vertex_stream_params();
- streams.reserve(stream_params.size());
- for (unsigned ii = 0; ii < stream_params.size(); ++ii) {
- streams.push_back(
- const_cast<o3d::Stream*>(&stream_params[ii]->stream()));
- }
- return streams;
- }
- o3d::Stream* userglue_method_GetVertexStream(
- o3d::SkinEval* self,
- o3d::Stream::Semantic semantic,
- int semantic_index) {
- return const_cast<o3d::Stream*>(
- self->GetVertexStream(semantic, semantic_index));
- }
- %}
-}; // SkinEval
-
-%[
- A Param which stores a Skin.
-%]
-[nocpp, include="core/cross/skin.h"] class ParamSkin : Param {
- %[
- The Skin stored by the Param.
- %]
- [getter, setter] Skin? value_;
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/standard_param.idl b/o3d/plugin/idl/standard_param.idl
deleted file mode 100644
index b893bbc7..0000000
--- a/o3d/plugin/idl/standard_param.idl
+++ /dev/null
@@ -1,200 +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.
- */
-
-namespace o3d {
-
-%[
- A type of ParamMatrix4 that supplies the current world matrix at render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class WorldParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current inverse world matrix at
- render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class WorldInverseParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current world transpose matrix at
- render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class WorldTransposeParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current inverse world transpose
- matrix at render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class WorldInverseTransposeParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current view matrix at render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class ViewParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current inverse view matrix at render
- time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class ViewInverseParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current view transpose matrix at
- render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class ViewTransposeParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current inverse view transpose matrix
- at render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class ViewInverseTransposeParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current projecton matrix at render
- time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class ProjectionParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current inverse projection matrix at
- render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class ProjectionInverseParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current projection transpose matrix
- at render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class ProjectionTransposeParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current inverse projection transpose
- matrix at render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class ProjectionInverseTransposeParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current world view matrix at
- render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class WorldViewParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current inverse world view matrix at
- render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class WorldViewInverseParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current transpose world view matrix
- at render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class WorldViewTransposeParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current inverse world view
- transpose matrix at render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class WorldViewInverseTransposeParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current view projection matrix at
- render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class ViewProjectionParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current inverse view projection
- matrix at render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class ViewProjectionInverseParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current view projection transpose
- matrix at render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class ViewProjectionTransposeParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current inverse view projection
- transpose matrix at render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class ViewProjectionInverseTransposeParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current world view projection matrix
- at render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class WorldViewProjectionParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current inverse world view projection
- matrix at render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class WorldViewProjectionInverseParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current world view projection
- transpose matrix at render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class WorldViewProjectionTransposeParamMatrix4 : ParamMatrix4 {
-};
-
-%[
- A type of ParamMatrix4 that supplies the current inverse world view projection
- transpose matrix at render time.
-%]
-[nocpp, include="core/cross/standard_param.h"] class WorldViewProjectionInverseTransposeParamMatrix4 : ParamMatrix4 {
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/state.idl b/o3d/plugin/idl/state.idl
deleted file mode 100644
index 230b462..0000000
--- a/o3d/plugin/idl/state.idl
+++ /dev/null
@@ -1,288 +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.
- */
-
-namespace o3d {
-
-%[
- A State object sets the RenderStates for a particular material or StateSet.
-%]
-[nocpp, include="core/cross/state.h"] class State : ParamObject {
- %[
- \var Comparison
- \li CMP_NEVER (Never)
- \li CMP_LESS (Less Than)
- \li CMP_EQUAL (Equal To)
- \li CMP_LEQUAL (Less Than or Equal To)
- \li CMP_GREATER (Greater Than)
- \li CMP_NOTEQUAL (Not Equal To)
- \li CMP_GEQUAL (Greater Than or Equal To)
- \li CMP_ALWAYS (Always)
- %]
- enum Comparison {
- CMP_NEVER, /* Never */
- CMP_LESS, /* Less Than */
- CMP_EQUAL, /* Equal To */
- CMP_LEQUAL, /* Less Than or Equal To */
- CMP_GREATER, /* Greater Than */
- CMP_NOTEQUAL, /* Not Equal To */
- CMP_GEQUAL, /* Greater Than or Equal To */
- CMP_ALWAYS /* Always */
- };
-
- %[
- \var Cull
- \li CULL_NONE Don't Cull by face
- \li CULL_CW Cull clock-wise faces
- \li CULL_CCW Cull counter clock-wise faces
- %]
- enum Cull {
- CULL_NONE, /* Don't Cull by face */
- CULL_CW, /* Cull clock-wise faces*/
- CULL_CCW /* Cull counter clock-wise faces */
- };
-
- %[
- \var Fill
- \li POINT
- \li WIREFRAME
- \li SOLID
- %]
- enum Fill {
- POINT, /* Points */
- WIREFRAME, /* Wireframe */
- SOLID /* Solid */
- };
-
- %[
- \var BlendingFunction
- \li BLENDFUNC_ZERO
- \li BLENDFUNC_ONE
- \li BLENDFUNC_SOURCE_COLOR
- \li BLENDFUNC_INVERSE_SOURCE_COLOR
- \li BLENDFUNC_SOURCE_ALPHA
- \li BLENDFUNC_INVERSE_SOURCE_ALPHA
- \li BLENDFUNC_DESTINATION_ALPHA
- \li BLENDFUNC_INVERSE_DESTINATION_ALPHA
- \li BLENDFUNC_DESTINATION_COLOR
- \li BLENDFUNC_INVERSE_DESTINATION_COLOR
- \li BLENDFUNC_SOURCE_ALPHA_SATUTRATE
- %]
- enum BlendingFunction {
- BLENDFUNC_ZERO,
- BLENDFUNC_ONE,
- BLENDFUNC_SOURCE_COLOR,
- BLENDFUNC_INVERSE_SOURCE_COLOR,
- BLENDFUNC_SOURCE_ALPHA,
- BLENDFUNC_INVERSE_SOURCE_ALPHA,
- BLENDFUNC_DESTINATION_ALPHA,
- BLENDFUNC_INVERSE_DESTINATION_ALPHA,
- BLENDFUNC_DESTINATION_COLOR,
- BLENDFUNC_INVERSE_DESTINATION_COLOR,
- BLENDFUNC_SOURCE_ALPHA_SATUTRATE
- };
-
- %[
- \var BlendingEquation
- \li BLEND_ADD
- \li BLEND_SUBTRACT
- \li BLEND_REVERSE_SUBTRACT
- \li BLEND_MIN
- \li BLEND_MAX
- %]
- enum BlendingEquation {
- BLEND_ADD,
- BLEND_SUBTRACT,
- BLEND_REVERSE_SUBTRACT,
- BLEND_MIN,
- BLEND_MAX
- };
-
- %[
- \var StencilOperation
- \li STENCIL_KEEP
- \li STENCIL_ZERO
- \li STENCIL_REPLACE
- \li STENCIL_INCREMENT_SATURATE
- \li STENCIL_DECREMENT_SATURATE
- \li STENCIL_INVERT
- \li STENCIL_INCREMENT
- \li STENCIL_DECREMENT
- %]
- enum StencilOperation {
- STENCIL_KEEP,
- STENCIL_ZERO,
- STENCIL_REPLACE,
- STENCIL_INCREMENT_SATURATE,
- STENCIL_DECREMENT_SATURATE,
- STENCIL_INVERT,
- STENCIL_INCREMENT,
- STENCIL_DECREMENT
- };
-
- %[
- Returns a Param for a given state. If the param does not already exist it
- will be created. If the state_name is invalid it will return null.
- \param state_name name of the state
- \return param or null if no matching state.
-
- Example:
- \code
- // Gets the client.
- g_o3d = document.o3d.o3d;
- ...
- // Creates a state object.
- var state = my_pack.createState("my_state");
-
- // Sets some states.
- state.getStateParam('o3d.StencilEnable').value = true;
- state.getStateParam('o3d.StencilReference').value = 25;
- state.getStateParam('o3d.StencilPassOperation').value =
- g_o3d.State.STENCIL_REPLACE;
- state.getStateParam('o3d.StencilComparisonFunction').value =
- g_o3d.State.CMP_ALWAYS;
- state.getStateParam('o3d.ZEnable').value = false;
- state.getStateParam('o3d.ZWriteEnable').value = false;
- state.getStateParam('o3d.ColorWriteEnable').value = 0;
- \endcode
- Valid states:
- <table>
- <tr><td>State Name</td><td>Type</td><td>Default Value</td></tr>
- <tr><td>o3d.AlphaBlendEnable</td><td>ParamBoolean</td>
- <td>default = false</td></tr>
- <tr><td>o3d.AlphaComparisonFunction</td><td>ParamInteger,
- State.Comparison</td><td>default = State.CMP_ALWAYS</td></tr>
- <tr><td>o3d.AlphaReference</td><td>ParamFloat 0-1</td>
- <td>default = 0</td></tr>
- <tr><td>o3d.AlphaTestEnable</td><td>ParamBoolean</td>
- <td>default = false</td></tr>
- <tr><td>o3d.BlendAlphaEquation</td>
- <td>ParamInteger, State.BlendingEquation</td>
- <td>default = State.BLEND_ADD</td></tr>
- <tr><td>o3d.BlendEquation</td>
- <td>ParamInteger, State.BlendingEquation</td>
- <td>default = State.BLEND_ADD</td></tr>
- <tr><td>o3d.CCWStencilComparisonFunction</td>
- <td>ParamInteger, State.Comparison</td>
- <td>default = State.CMP_ALWAYS</td></tr>
- <tr><td>o3d.CCWStencilFailOperation</td>
- <td>ParamInteger, State.StencilOperation</td>
- <td>default = State.STENCIL_KEEP</td></tr>
- <tr><td>o3d.CCWStencilPassOperation</td>
- <td>ParamInteger, State.StencilOperation</td>
- <td>default = State.STENCIL_KEEP</td></tr>
- <tr><td>o3d.CCWStencilZFailOperation</td>
- <td>ParamInteger, State.StencilOperation</td>
- <td>default = State.STENCIL_KEEP</td></tr>
- <tr><td>o3d.ColorWriteEnable</td>
- <td>ParamInteger 0-15 bit 0 = red, bit 1 = green,
- bit 2 = blue, bit 3 = alpha</td><td>default = 15</td></tr>
- <tr><td>o3d.CullMode</td><td>ParamInteger, State.Cull</td>
- <td>default = State.CULL_CW</td></tr>
- <tr><td>o3d.DestinationBlendAlphaFunction</td>
- <td>ParamInteger, State.BlendingFunction</td>
- <td>default = State.BLENDFUNC_ZERO</td></tr>
- <tr><td>o3d.DestinationBlendFunction</td>
- <td>ParamInteger, State.BlendingFunction</td>
- <td>default = State.BLENDFUNC_ZERO</td></tr>
- <tr><td>o3d.DitherEnable</td><td>ParamBoolean</td>
- <td>default = false</td></tr>
- <tr><td>o3d.FillMode</td><td>ParamInteger, State.Fill</td>
- <td>default = State.SOLID</td></tr>
- <tr><td>o3d.LineSmoothEnable</td><td>ParamBoolean</td>
- <td>default = false</td></tr>
- <tr><td>o3d.PointSize</td><td>ParamFloat</td><td>TBD</td></tr>
- <tr><td>o3d.PointSpriteEnable</td><td>ParamBoolean</td>
- <td>default = false</td></tr>
- <tr><td>o3d.PolygonOffset1</td>
- <td>ParamFloat, polygon offset slope factor<td>0</td></tr>
- <tr><td>o3d.PolygonOffset2</td><td>ParamFloat, polygon offset bias (in
- resolvable units)<td>0</td></tr>
- <tr><td>o3d.SeparateAlphaBlendEnable</td><td>ParamBoolean</td>
- <td>default = false;</td></tr>
- <tr><td>o3d.SourceBlendAlphaFunction</td>
- <td>ParamInteger, State.BlendingFunction</td>
- <td>default = State.BLENDFUNC_ONE</td></tr>
- <tr><td>o3d.SourceBlendFunction</td>
- <td>ParamInteger, State.BlendingFunction</td>
- <td>default = State.BLENDFUNC_ONE</td></tr>
- <tr><td>o3d.StencilComparisonFunction</td>
- <td>ParamInteger, State.Comparison</td>
- <td>default = State.CMP_ALWAYS</td></tr>
- <tr><td>o3d.StencilEnable</td><td>ParamBoolean</td>
- <td>default = false</td></tr>
- <tr><td>o3d.StencilFailOperation</td>
- <td>ParamInteger, State.StencilOperation</td>
- <td>default = State.STENCIL_KEEP</td></tr>
- <tr><td>o3d.StencilMask</td><td>ParamInteger 0-255</td>
- <td>default = 255</td></tr>
- <tr><td>o3d.StencilPassOperation</td>
- <td>ParamInteger, State.StencilOperation</td>
- <td>default = State.STENCIL_KEEP</td></tr>
- <tr><td>o3d.StencilReference</td><td>ParamInteger 0-255</td>
- <td>default = 0</td></tr>
- <tr><td>o3d.StencilWriteMask</td><td>ParamInteger 0-255</td>
- <td>default = 255</td></tr>
- <tr><td>o3d.StencilZFailOperation</td>
- <td>ParamInteger, State.StencilOperation</td>
- <td>default = State.STENCIL_KEEP</td></tr>
- <tr><td>o3d.TwoSidedStencilEnable</td><td>ParamBoolean</td>
- <td>default = false</td></tr>
- <tr><td>o3d.ZComparisonFunction</td>
- <td>ParamInteger, State.Comparison</td>
- <td>default = State.CMP_LESS</td></tr>
- <tr><td>o3d.ZEnable</td><td>ParamBoolean</td>
- <td>default = true</td></tr>
- <tr><td>o3d.ZWriteEnable</td><td>ParamBoolean</td>
- <td>default = true</td></tr>
- </table>
-
- Note: Polygon offset is computed with the following formula:
- \code
- totalOffset = PolygonOffset1 * slope + PolygonOffset2 * r
- \endcode
- Slope is the maximum difference in depth between 2 adjacent pixels of the
- polygon. r is the smallest value that would fail the NOTEQUAL test against
- 0.
- Typical useful values to layer a polygon on top of another one are -1.0 for
- each of PolygonOffset1 and PolygonOffset2.
- %]
- [nocpp, userglue] Param? GetStateParam(String state_name);
-
- [verbatim=cpp_glue] %{
- o3d::Param* userglue_method_GetStateParam(
- o3d::State *self,
- const o3d::String& state_name) {
- return self->GetUntypedStateParam(state_name);
- }
- %}
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/state_set.idl b/o3d/plugin/idl/state_set.idl
deleted file mode 100644
index 3c767ed..0000000
--- a/o3d/plugin/idl/state_set.idl
+++ /dev/null
@@ -1,51 +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.
- */
-
-namespace o3d {
-
-%[
- A StateSet is a render node that sets render states of all of its
- children. You can make this a parent of a part of the render graph to set
- render states in a more global way.
-
- @o3dparameter state ParamState The State the defines what states to set.
-%]
-[nocpp, include="core/cross/state_set.h"] class StateSet
- : RenderNode {
-
- %[
- The State for this StateSet.
- %]
- [getter, setter] State? state_;
-
-}; // StateSet
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/stream.idl b/o3d/plugin/idl/stream.idl
deleted file mode 100644
index 991ade3..0000000
--- a/o3d/plugin/idl/stream.idl
+++ /dev/null
@@ -1,118 +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.
- */
-
-%[
- Namespace o3d
-%]
-namespace o3d {
-
-%[
- A stream object defines how Buffer data is interpreted by an Effect when
- rendering a Primitive..
- It contains a pointer to a Field, a semantic and semantic index
- that determine how the data is accessed.
-%]
-
-[nocpp, include="core/cross/stream.h"]
-class Stream : ObjectBase {
- %[
- \var Semantic,
- \li UNKNOWN_SEMANTIC = 0,
- \li POSITION,
- \li NORMAL,
- \li TANGENT,
- \li BINORMAL,
- \li COLOR,
- \li TEXCOORD
-
- Semantics used when binding buffers to the streambank. They determine how
- the Stream links up to the shader inputs.
- %]
- enum Semantic {
- UNKNOWN_SEMANTIC = 0,
- POSITION,
- NORMAL,
- TANGENT,
- BINORMAL,
- COLOR,
- TEXCOORD
- };
-
- %[
- The associated Field.
- %]
- [userglue_getter, getter] Field? field;
-
- %[
- The semantic specified for the Stream.
- %]
- [getter] Semantic semantic;
-
- %[
- The semantic index specified for the Stream
- (eg., TEXCOORD1 = 1, BINORMAL7 = 7, etc).
- %]
- [getter] int semantic_index;
-
- %[
- The start index for the Stream.
- %]
- [getter] unsigned int start_index;
-
- [verbatim=cpp_glue] %{
- o3d::Field* userglue_getter_field(o3d::Stream* self) {
- return const_cast<o3d::Field*>(&self->field());
- }
- %}
-};
-
-%[
- An array of Streams.
-%]
-typedef Stream[] StreamVector;
-
-%[
- A Param which stores a Stream.
-%]
-[nocpp, include="core/cross/stream.h"] class ParamVertexBufferStream : Param {
- %[
- The Stream stored by the Param.
- %]
- [userglue_getter, getter] Stream? stream;
- [verbatim=cpp_glue] %{
- o3d::Stream* userglue_getter_stream(
- o3d::ParamVertexBufferStream* self) {
- return const_cast<o3d::Stream*>(&self->stream());
- }
- %}
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/stream_bank.idl b/o3d/plugin/idl/stream_bank.idl
deleted file mode 100644
index 45e7179..0000000
--- a/o3d/plugin/idl/stream_bank.idl
+++ /dev/null
@@ -1,125 +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.
- */
-
-namespace o3d {
-
-%[
- The StreamBank a collection of streams that hold vertices.
-%]
-[nocpp, include="core/cross/primitive.h"]
-class StreamBank : VertexSource {
-
- %[
- Binds a VertexBuffer field to the StreamBank and defines how the data in
- the buffer should be interpreted. The field's buffer must be of a
- compatible type otherwise the binding fails and the function returns false.
- \param semantic The particular use of this stream.
- \param semantic_index Which index of a particular semantic to use.
- \param field The field containing information for this stream.
- \param start_index The first element to use.
- \return True if successful.
- %]
- bool SetVertexStream(Stream::Semantic semantic,
- int semantic_index,
- Field field,
- unsigned int start_index);
-
- %[
- Searches the vertex streams bound to the StreamBank for one with the given
- stream semantic. If a stream is not found then it returns null.
- \param semantic The particular use of this stream.
- \param semantic_index Which index of a particular semantic to use.
- \return The found stream or null if it does not exist.
- %]
- [userglue]
- Stream? GetVertexStream(Stream::Semantic semantic, int semantic_index);
-
- %[
- Removes a vertex stream from this StreamBank.
- \param semantic The particular use of this stream.
- \param semantic_index Which index of a particular semantic to use.
- \return true if the specified stream existed.
- %]
- bool RemoveVertexStream(Stream::Semantic semantic, int semantic_index);
-
- %[
- An array of the vertex streams on this StreamBank.
-
- Each access to this field gets the entire list so it is best to get it
- just once. For example:
- \code
- var streams = streamBank.vertexStreams;
- for (var i = 0; i < streams.length; i++) {
- var stream = streams[i];
- }
- \endcode
-
- Note that modifications to this array [e.g. push()] will not affect
- the underlying StreamBank, while modifications to the members of the array.
- <strong>will</strong> affect them.
- %]
- [userglue_getter, getter] StreamVector vertex_streams;
-
- [verbatim=cpp_glue] %{
- std::vector<o3d::Stream*> userglue_getter_vertex_streams(
- o3d::StreamBank* self) {
- std::vector<o3d::Stream*> streams;
- const o3d::StreamParamVector& stream_params =
- self->vertex_stream_params();
- streams.reserve(stream_params.size());
- for (unsigned ii = 0; ii < stream_params.size(); ++ii) {
- streams.push_back(
- const_cast<o3d::Stream*>(&stream_params[ii]->stream()));
- }
- return streams;
- }
- o3d::Stream* userglue_method_GetVertexStream(
- o3d::StreamBank* self,
- o3d::Stream::Semantic semantic,
- int semantic_index) {
- return const_cast<o3d::Stream*>(
- self->GetVertexStream(semantic, semantic_index));
- }
- %}
-}; // StreamBank
-
-%[
- A Param which stores a StreamBank.
-%]
-[nocpp, include="core/cross/stream_bank.h"]
-class ParamStreamBank : Param {
- %[
- The StreamBank stored by the Param.
- %]
- [getter, setter] StreamBank? value_;
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/texture.idl b/o3d/plugin/idl/texture.idl
deleted file mode 100644
index 2c11f16..0000000
--- a/o3d/plugin/idl/texture.idl
+++ /dev/null
@@ -1,564 +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.
- */
-
-namespace o3d {
-
-%[
- The Texture class is a base class for image data used in texture mapping.
-%]
-[include="core/cross/texture_base.h"] class Texture : ParamObject {
- %[
- \var Format,
- \li UNKNOWN_FORMAT
- \li XRGB8
- \li ARGB8
- \li ABGR16F
- \li R32F
- \li ABGR32F
- \li DXT1
- \li DXT3
- \li DXT5
-
- The in-memory format of the texture bitmap.
-
- NOTE: The R32F format is different on GL vs D3D. If you use it in a shader
- you must only use the red channel. The green, blue and alpha channels are
- undefined.
-
- For example:
- \code
- ...
-
- // The texture sampler is used to access the texture bitmap in the fragment
- // shader.
- sampler texSampler0;
-
- ...
-
- // input parameters for our vertex shader
- struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
- };
-
- float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- // ** Use only valid channels. ** ---------+
- // |
- // V
- return tex2D(texSampler0, input.texcoord).rrrr;
- }
- \endcode
-
- @o3dparameter levels ParamInteger The number of mip levels in this texture.
- [Read Only]
- %]
- enum Format {
- UNKNOWN_FORMAT,
- XRGB8,
- ARGB8,
- ABGR16F,
- R32F,
- ABGR32F,
- DXT1,
- DXT3,
- DXT5
- };
-
- %[
- The memory format used for storing the bitmap associated with the texture
- object.
- %]
- [getter] Format format;
-
- %[
- The number of mipmap levels used by the texture.
- %]
- [getter] int levels;
-
- %[
- True of all the alpha values in the texture are 1.0
- %]
- [getter, getter, setter] bool alpha_is_one;
-
- %[
- The count of total updates made to this texture.
- %]
- [getter] int update_count;
-
- %[
- The count of updates made to this texture that were rendered to the screen.
- %]
- [getter] int render_count;
-
- %[
- Generates Mips.
- \param source_level the mip to use as the source.
- \param num_levels the number of mips from the source to generate.
- %]
- void GenerateMips(int source_level, int num_levels);
-
-}; // Texture
-
-%[
- A class for 2D textures that defines the interface for getting
- the dimensions of the texture, its memory format and number of mipmap levels.
-
- @o3dparameter width ParamInteger The width of this texture in pixels.
- [Read Only]
- @o3dparameter height ParamInteger The height of this texture in pixels.
- [Read Only]
-%]
-[include="core/cross/texture.h"] class Texture2D : Texture {
- %[
- The width of the texture, in texels.
- %]
- [getter] int width;
-
- %[
- The height of the texture, in texels.
- %]
- [getter] int height;
-
- %[
- Returns a RenderSurface object associated with a mip_level of a texture.
-
- \param mip_level The mip-level of the surface to be returned.
- \return The RenderSurface object.
- %]
- RenderSurface? GetRenderSurface(int mip_level);
-
- %[
- Returns a RenderSurface object associated with a mip_level of a texture.
-
- \param mip_level The mip-level of the surface to be returned.
- \param pack This parameter is no longer used. The surface exists as long as
- the texture it came from exists.
- \return The RenderSurface object.
- %]
- [userglue] RenderSurface? GetRenderSurface(int mip_level, Pack pack);
-
- // TODO: Add Get, GetRect.
- %[
- Sets the values of the data stored in the texture.
-
- It is not recommend that you call this for large textures but it is useful
- for making simple ramps or noise textures for shaders.
-
- NOTE: the number of values must equal the size of the texture * the number
- of elements. In other words, for a XRGB8 texture there must be
- width * height * 3 values. For an ARGB8, ABGR16F or ABGR32F texture there
- must be width * height * 4 values. For an R32F texture there must be
- width * height values.
-
- NOTE: the order of channels is R G B for XRGB8 textures and R G B A
- for ARGB8, ABGR16F and ABGR32F textures so for example for XRGB8 textures\n
- \n
- [1, 0, 0] = a red pixel\n
- [0, 0, 1] = a blue pixel\n
- \n
- For ARGB8, ABGR16F, ABGR32F textures\n
- \n
- [1, 0, 0, 0] = a red pixel with zero alpha\n
- [1, 0, 0, 1] = a red pixel with one alpha\n
- [0, 0, 1, 1] = a blue pixel with one alpha\n
-
- \param level the mip level to update.
- \param values Values to be stored in the buffer.
- %]
- [nocpp, userglue]
- void Set(int level, float[] values);
-
- %[
- Sets a rectangular area of values in a texture.
-
- Does clipping. In other words if you pass in a 10x10 pixel array
- and give it destination of (-5, -5) it will only use the bottom 5x5
- pixels of the array you passed in to set the top 5x5 pixels of the
- texture.
-
- See o3d.Texture2D.set for details on formats.
-
- \param level the mip level to update.
- \param destination_x The x coordinate of the area in the texture to affect.
- \param destination_y The y coordinate of the area in the texture to affect.
- \param source_width The width of the area to effect. The height is
- determined by the size of the array passed in.
- \param values Values to be stored in the buffer.
- \see o3d.Texture2D.set
- %]
- [nocpp, userglue]
- void SetRect(int level,
- int destination_x,
- int destination_y,
- int source_width,
- float[] values);
-
- %[
- Gets a rectangular area of values from a texture.
-
- See o3d.Texture2D.set for details on formats.
- Can not be used for compressed textures.
-
- \param level the mip level to get.
- \param x The x coordinate of the area in the texture to retrieve.
- \param y The y coordinate of the area in the texture to retrieve.
- \param width The width of the area to retrieve.
- \param height The height of the area to retrieve.
- \return Array of pixel values.
- %]
- [nocpp, userglue]
- float[] GetRect(int level,
- int x,
- int y,
- int width,
- int height);
-
- %[
- Sets the content of the texture to the content of the bitmap. The texture
- and the bitmap must be the same dimensions and the same format.
-
- \param bitmap The bitmap to copy data from.
- %]
- [userglue]
- void SetFromBitmap(Bitmap bitmap);
-
- [verbatim=cpp_glue] %{
- void userglue_method_SetFromBitmap(o3d::Texture2D* self,
- o3d::Bitmap* bitmap) {
- self->SetFromBitmap(*bitmap);
- }
- o3d::RenderSurface* userglue_method_GetRenderSurface(o3d::Texture2D* self,
- int mip_level,
- o3d::Pack* pack) {
- return self->GetRenderSurface(mip_level);
- }
- %}
-
- %[
- Copy pixels from source bitmap to certain mip level.
- Scales if the width and height of source and dest do not match.
-
- \param source_img The source bitmap.
- \param source_mip which mip from the source to copy from.
- \param source_x x-coordinate of the starting pixel in the source image.
- \param source_y y-coordinate of the starting pixel in the source image.
- \param source_width width of the source image to draw.
- \param source_height Height of the source image to draw.
- \param dest_mip on which mip level to draw to.
- \param dest_x x-coordinate of the starting pixel in the destination texture.
- \param dest_y y-coordinate of the starting pixel in the destination texture.
- \param dest_width width of the dest image.
- \param dest_height height of the dest image.
- %]
- [userglue]
- void DrawImage(Bitmap source_img, int source_mip,
- int source_x, int source_y,
- int source_width, int source_height,
- int dest_mip,
- int dest_x, int dest_y,
- int dest_width, int dest_height);
-
- %[
- Copy pixels from source canvas to certain mip level.
- Scales if the width and height of source and dest do not match.
-
- \param source_img The source canvas.
- \param source_x x-coordinate of the starting pixel in the source image.
- \param source_y y-coordinate of the starting pixel in the source image.
- \param source_width width of the source image to draw.
- \param source_height Height of the source image to draw.
- \param dest_mip on which mip level to draw to.
- \param dest_x x-coordinate of the starting pixel in the destination texture.
- \param dest_y y-coordinate of the starting pixel in the destination texture.
- \param dest_width width of the dest image.
- \param dest_height height of the dest image.
- %]
- [userglue, include="core/cross/canvas.h"]
- void DrawImage(Canvas source_img,
- int source_x, int source_y,
- int source_width, int source_height,
- int dest_mip,
- int dest_x, int dest_y,
- int dest_width, int dest_height);
-
-
- [verbatim=cpp_glue] %{
- void userglue_method_DrawImage(
- o3d::Texture2D* self,
- o3d::Bitmap* source_img, int source_mip, int source_x, int source_y,
- int source_width, int source_height,
- int dest_mip,
- int dest_x, int dest_y,
- int dest_width, int dest_height) {
- self->DrawImage(*source_img, source_mip, source_x, source_y,
- source_width, source_height,
- dest_mip, dest_x, dest_y,
- dest_width, dest_height);
- }
- void userglue_method_DrawImage(
- o3d::Texture2D* self,
- o3d::Canvas* source_img, int source_x, int source_y,
- int source_width, int source_height,
- int dest_mip,
- int dest_x, int dest_y,
- int dest_width, int dest_height) {
- self->DrawImage(*source_img, source_x, source_y,
- source_width, source_height,
- dest_mip, dest_x, dest_y,
- dest_width, dest_height);
- }
-%}
-}; // Texture2D
-
-
-%[
- TextureCUBE is a class for textures used for cube mapping. A cube texture
- stores bitmaps for the 6 faces of a cube and is addressed via three texture
- coordinates.
-
- @o3dparameter edgeLength ParamInteger The length of any edge of this texture.
- [Read Only]
-%]
-[include="core/cross/texture.h"] class TextureCUBE : Texture {
- %[
- \var CubeFace,
- \li FACE_POSITIVE_X
- \li FACE_NEGATIVE_X
- \li FACE_POSITIVE_Y
- \li FACE_NEGATIVE_Y
- \li FACE_POSITIVE_Z
- \li FACE_NEGATIVE_Z
-
- The names of each of the six faces of a cube map texture.
- %]
- enum CubeFace {
- FACE_POSITIVE_X,
- FACE_NEGATIVE_X,
- FACE_POSITIVE_Y,
- FACE_NEGATIVE_Y,
- FACE_POSITIVE_Z,
- FACE_NEGATIVE_Z };
-
- %[
- The length of each edge of the cube, in texels.
- %]
- [field_access=private, getter] int edge_length;
-
- %[
- Returns a RenderSurface object associated with a given cube face and
- mip_level of a texture.
-
- \param face The cube face from which to extract the surface.
- \param mip_level The mip-level of the surface to be returned.
- \return The RenderSurface object.
- %]
- RenderSurface? GetRenderSurface(CubeFace face, int mip_level);
-
- %[
- Returns a RenderSurface object associated with a given cube face and
- mip_level of a texture.
-
- \param face The cube face from which to extract the surface.
- \param mip_level The mip-level of the surface to be returned.
- \param pack This parameter is no longer used. The surface exists as long as
- the texture it came from exists.
- \return The RenderSurface object.
- %]
- [userglue]
- RenderSurface? GetRenderSurface(CubeFace face, int mip_level, Pack pack);
-
- %[
- Sets the values of the data stored in the texture.
-
- It is not recommend that you call this for large textures but it is useful
- for making simple ramps or noise textures for shaders.
-
- See o3d.Texture2D.set for details on formats.
-
- \param face the face to update.
- \param level the mip level to update.
- \param values Values to be stored in the buffer.
- %]
- [nocpp, userglue]
- void Set(CubeFace face, int level, float[] values);
-
- %[
- Sets a rectangular area of values in a texture.
-
- Does clipping. In other words if you pass in a 10x10 pixel array
- and give it destination of (-5, -5) it will only use the bottom 5x5
- pixels of the array you passed in to set the top 5x5 pixels of the
- texture.
-
- See o3d.Texture2D.set for details on formats.
-
- \param face the face to update.
- \param level the mip level to update.
- \param destination_x The x coordinate of the area in the texture to affect.
- \param destination_y The y coordinate of the area in the texture to affect.
- \param source_width The width of the area to effect. The height is
- determined by the size of the array passed in.
- \param values Values to be stored in the buffer.
- \see o3d.Texture2D.set
- %]
- [nocpp, userglue]
- void SetRect(CubeFace face,
- int level,
- int destination_x,
- int destination_y,
- int source_width,
- float[] values);
-
- %[
- Gets a rectangular area of values from a texture.
-
- See o3d.Texture2D.set for details on formats.
- Can not be used for compressed textures.
-
- \param face the face to get.
- \param level the mip level to get.
- \param x The x coordinate of the area in the texture to retrieve.
- \param y The y coordinate of the area in the texture to retrieve.
- \param width The width of the area to retrieve.
- \param height The height of the area to retrieve.
- \return Array of pixel values.
- %]
- [nocpp, userglue]
- float[] GetRect(CubeFace face,
- int level,
- int x,
- int y,
- int width,
- int height);
-
- %[
- Sets the content of a face of the texture to the content of the bitmap. The
- texture and the bitmap must be the same dimensions and the same format.
-
- \param face The face to set.
- \param bitmap The bitmap to copy data from.
- %]
- [userglue]
- void SetFromBitmap(CubeFace face, Bitmap bitmap);
-
- [verbatim=cpp_glue] %{
- void userglue_method_SetFromBitmap(o3d::TextureCUBE* self,
- o3d::TextureCUBE::CubeFace face,
- o3d::Bitmap* bitmap) {
- self->SetFromBitmap(face, *bitmap);
- }
- %}
-
- %[
- Copy pixels from source bitmap to certain face and mip level.
- Scales if the width and height of source and dest do not match.
-
- \param source_img The source bitmap.
- \param source_mip which mip of the source to copy from.
- \param source_x x-coordinate of the starting pixel in the source image.
- \param source_y y-coordinate of the starting pixel in the source image.
- \param source_width width of the source image to draw.
- \param source_height Height of the source image to draw.
- \param face on which face to draw on.
- \param dest_mip on which mip level to draw on.
- \param dest_x x-coordinate of the starting pixel in the destination texture.
- \param dest_y y-coordinate of the starting pixel in the destination texture.
- \param dest_width width of the destination image.
- \param dest_height height of the destination image.
- %]
- [userglue]
- void DrawImage(Bitmap source_img, int source_mip, int source_x, int source_y,
- int source_width, int source_height,
- CubeFace face, int dest_mip,
- int dest_x, int dest_y,
- int dest_width, int dest_height);
-
- %[
- Copy pixels from source canvas to certain face and mip level.
- Scales if the width and height of source and dest do not match.
-
- \param source_img The source canvas.
- \param source_x x-coordinate of the starting pixel in the source image.
- \param source_y y-coordinate of the starting pixel in the source image.
- \param source_width width of the source image to draw.
- \param source_height Height of the source image to draw.
- \param face on which face to draw on.
- \param dest_mip on which mip level to draw on.
- \param dest_x x-coordinate of the starting pixel in the destination texture.
- \param dest_y y-coordinate of the starting pixel in the destination texture.
- \param dest_width width of the destination image.
- \param dest_height height of the destination image.
- %]
- [userglue, include="core/cross/canvas.h"]
- void DrawImage(Canvas source_img, int source_x, int source_y,
- int source_width, int source_height,
- CubeFace face, int dest_mip,
- int dest_x, int dest_y,
- int dest_width, int dest_height);
-
- [verbatim=cpp_glue] %{
- void userglue_method_DrawImage(
- o3d::TextureCUBE* self,
- o3d::Bitmap* source_img, int source_mip, int source_x, int source_y,
- int source_width, int source_height,
- o3d::TextureCUBE::CubeFace dest_face, int dest_mip,
- int dest_x, int dest_y,
- int dest_width, int dest_height) {
- self->DrawImage(*source_img, source_mip, source_x, source_y,
- source_width, source_height,
- dest_face, dest_mip,
- dest_x, dest_y,
- dest_width, dest_height);
- }
- void userglue_method_DrawImage(
- o3d::TextureCUBE* self,
- o3d::Canvas* source_img, int source_x, int source_y,
- int source_width, int source_height,
- o3d::TextureCUBE::CubeFace dest_face, int dest_mip,
- int dest_x, int dest_y,
- int dest_width, int dest_height) {
- self->DrawImage(*source_img, source_x, source_y,
- source_width, source_height,
- dest_face, dest_mip,
- dest_x, dest_y,
- dest_width, dest_height);
- }
- o3d::RenderSurface* userglue_method_GetRenderSurface(
- o3d::TextureCUBE* self,
- o3d::TextureCUBE::CubeFace face,
- int mip_level,
- o3d::Pack* pack) {
- return self->GetRenderSurface(face, mip_level);
- }
- %}
-}; // TextureCUBE
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/tick_event.idl b/o3d/plugin/idl/tick_event.idl
deleted file mode 100644
index c8b5891..0000000
--- a/o3d/plugin/idl/tick_event.idl
+++ /dev/null
@@ -1,49 +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 public interface for the TickEvent class.
-
-namespace o3d {
-
-%[
- This class is used to pass infomation to a registered ontick callback.
-%]
-[binding_model=by_value, include="core/cross/tick_event.h",
- nocpp,glue_iface] class TickEvent {
- %[
- Use this property to get the elapsed time since the last tick event
- in seconds.
- %]
- [getter] float elapsed_time_;
-};
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/transform.idl b/o3d/plugin/idl/transform.idl
deleted file mode 100644
index bc359f2..0000000
--- a/o3d/plugin/idl/transform.idl
+++ /dev/null
@@ -1,385 +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.
- */
-
-namespace o3d {
-
-typedef Shape[] ShapeArray;
-
-%[
- The Transform defines parent child relationship and a localMatrix..
- A Transform can have one or no parents and
- an arbitrary number of children.
-
- @o3dparameter localMatrix ParamMatrix4 The local matrix for this transform.
- @o3dparameter worldMatrix ParamMatrix4 The world matrix of this transform.
- @o3dparameter visible ParamBoolean Whether or not this transform and all its
- children are visible.
- @o3dparameter boundingBox ParamBoundingBox The bounding box for this transform
- and all its children.
- @o3dparameter cull ParamBoolean Whether or not to attempt to cull this
- transform and all its children based on whether or not its bounding box
- is in the view frustum.
- %]
-[nocpp, include="core/cross/transform.h"] class Transform
- : ParamObject {
- %[
- The Visibility for this transform.
- Default = true.
- %]
- [getter, setter] bool visible_;
-
- %[
- Sets the parent of the transform by re-parenting the transform under
- parent. Setting parent to null removes the transform and the
- entire subtree below it from the transform graph.
- If the operation would create a cycle it fails.
- %]
- [setter, userglue_setter] Transform? parent_;
-
- %[
- The immediate children of this Transform.
-
- Each access to this field gets the entire list, so it is best to get it
- just once. For example:
- \code
- var children = transform.children;
- for (var i = 0; i < children.length; i++) {
- var child = children[i];
- }
- \endcode
-
- Note that modifications to this array [e.g. additions to it] will not affect
- the underlying Transform, while modifications to the members of the array
- <strong>will</strong> affect them.
- %]
- [userglue_getter, getter] TransformArray children_;
-
- %[
- Returns all the transforms under this transform including this one.
-
- Note that modifications to this array [e.g. additions to it] will not affect
- the underlying Transform, while modifications to the members of the array
- <strong>will</strong> affect them.
-
- \return An array containing the transforms of the subtree.
- %]
- TransformArray GetTransformsInTree();
-
- %[
- Searches for transforms that match the given name in the hierarchy under and
- including this transform. Since there can be more than one transform with a
- given name, results are returned in an array.
-
- Note that modifications to this array [e.g. additions to it] will not affect
- the underlying Transform, while modifications to the members of the array
- <strong>will</strong> affect them.
-
- \param name Transform name to look for.
- \return An array containing the transforms of the under and including this
- transform matching the given name.
- %]
- TransformArray GetTransformsByNameInTree(String name);
-
- %[
- Evaluates and returns the current world matrix.
-
- \return The updated world matrix.
- %]
- Vectormath::Aos::Matrix4 GetUpdatedWorldMatrix();
-
- %[
- Adds a shape do this transform.
- \param shape Shape to add.
- %]
- void AddShape(Shape shape);
-
- %[
- Removes a shape from this transform.
- \param shape Shape to remove.
- \return true if successful, false if shape was not in this transform.
- %]
- bool RemoveShape(Shape shape);
-
- %[
- Gets the shapes owned by this transform.
-
- Each access to this field gets the entire list so it is best to get it
- just once. For example:
- \code
- var shapes = transform.shapes;
- for (var i = 0; i < shapes.length; i++) {
- var shape = shapes[i];
- }
- \endcode
-
- Note that modifications to this array [e.g. additions to it] will not affect
- the underlying Transform, while modifications to the members of the array
- <strong>will</strong> affect them.
- %]
- [userglue_getter, getter, userglue_setter, setter]
- ShapeArray shapes_;
-
- %[
- Walks the tree of transforms starting with this transform and creates
- draw elements. If an Element already has a DrawElement that uses material a
- new DrawElement will not be created.
- \param pack Pack used to manage created elements.
- \param material Material to use for each element. If you pass null, it will
- use the material on the element to which a draw element is being added.
- In other words, a DrawElement will use the material of the
- corresponding Element if material is null. This allows you to easily
- setup the default (just draw as is) by passing null or setup a shadow
- pass by passing in a shadow material.
- %]
- void CreateDrawElements(Pack pack,
- Material? material);
-
- %[
- World (model) matrix as it was last computed.
- %]
- [getter] Vectormath::Aos::Matrix4 world_matrix;
-
- %[
- Local transformation matrix.
- Default = Identity.
- %]
- [getter, setter, nocpp] Vectormath::Aos::Matrix4 local_matrix;
-
- %[
- The cull setting for this transform. If true this Transform will be culled
- by having its bounding box compared to the view frustum of any draw context
- it is used with.
- Default = false.
- %]
- [getter, setter] bool cull_;
-
- %[
- The BoundingBox for this Transform. If culling is on this bounding box will
- be tested against the view frustum of any draw context used to with this
- Transform.
- %]
- [getter, setter] BoundingBox bounding_box_;
-
- %[
- Sets the local matrix of this transform to the identity matrix.
- %]
- [userglue] void identity();
-
- %[
- Pre-composes the local matrix of this Transform with a translation. For
- example, if the local matrix is a rotation then new local matrix will
- translate by the given vector and then rotated.
-
- \param translation vector of 3 entries by which to translate.
- %]
- [userglue] void translate(Vectormath::Aos::Vector3 translation);
-
- %[
- Pre-composes the local matrix of this Transform with a translation. For
- example, if the local matrix is a rotation then the new local matrix will
- translate by the given amounts and then rotate.
-
- \param x amount to translate in x.
- \param y amount to translate in y.
- \param z amount to translate in z.
- %]
- [userglue] void translate(float x, float y, float z);
-
- %[
- Pre-composes the local matrix of this Transform with a rotation about the
- x-axis. For example, if the local matrix is a tranlsation, the new local
- matrix will rotate around the x-axis and then translate.
-
- \param radians The number of radians to rotate around x-axis.
- %]
- [userglue] void rotateX(float radians);
-
- %[
- Pre-composes the local matrix of this Transform with a rotation about the
- y-axis. For example, if the local matrix is a translation, the new local
- matrix will rotate around the y-axis and then translate.
-
- \param radians The number of radians to rotate around y-axis.
- %]
- [userglue] void rotateY(float radians);
-
- %[
- Pre-composes the local matrix of this Transform with a rotation about the
- z-axis. For example, if the local matrix is a translation, the new local
- matrix will rotate around the z-axis and then translate.
-
- \param radians The number of radians to rotate around z-axis.
- %]
- [userglue] void rotateZ(float radians);
-
- %[
- Pre-composes the local matrix of this Transform with a rotation.
- Interprets the three entries of the given vector as angles by which to
- rotate around the x, y and z axes. Rotates around the x-axis first,
- then the y-axis, then the z-axis.
-
- \param radiansXYZ A vector of angles (in radians) by which to rotate
- around the x, y and z axes.
- %]
- [userglue] void rotateZYX(Vectormath::Aos::Vector3 radiansXYZ);
-
- %[
- Pre-composes the local matrix of this Transform with a rotation around the
- given axis. For example, if the local matrix is a translation, the new
- local matrix will rotate around the given axis and then translate.
-
- \param radians The number of radians to rotate.
- \param axis a non-zero vector representing the axis around which to rotate.
- %]
- [userglue] void axisRotate(Vectormath::Aos::Vector3 axis, float radians);
-
- %[
- Pre-composes the local matrix of this Transform with a rotation defined by
- the given quaternion.
-
- \param unit_quat A non-zero quaternion to be interpreted as a rotation.
- %]
- [userglue] void quaternionRotate(Vectormath::Aos::Quat unit_quat);
-
- %[
- Pre-composes the local matrix of this transform by a scaling transformation.
- For example, if the local matrix is a rotation, the new local matrix will
- scale and then rotate.
-
- \param scale amount to scale.
- %]
- [userglue] void scale(Vectormath::Aos::Vector3 scale);
-
- %[
- Pre-composes the local matrix of this transform by a scaling transformation.
- For example, if the local matrix is a rotation, the new local matrix will
- scale and then rotate.
-
- \param x amount to scale in the x dimension.
- \param y amount to scale in the y dimension.
- \param z amount to scale in the z dimension.
- %]
- [userglue] void scale(float x, float y, float z);
-
- [verbatim=cpp_glue] %{
- void userglue_setter_parent_(
- o3d::Transform* _this,
- o3d::Transform* parent) {
- _this->SetParent(parent);
- }
- o3d::TransformArray userglue_getter_children_(
- o3d::Transform *self) {
- return self->GetChildren();
- }
- o3d::ShapeArray userglue_getter_shapes_(
- o3d::Transform *self) {
- return self->GetShapes();
- }
- void userglue_setter_shapes_(
- o3d::Transform *self,
- const o3d::ShapeArray& shapes) {
- self->SetShapes(shapes);
- }
- void userglue_method_identity(o3d::Transform* self) {
- self->set_local_matrix(Vectormath::Aos::Matrix4::identity());
- }
- void userglue_method_translate(
- o3d::Transform* self,
- const Vectormath::Aos::Vector3& translation) {
- self->set_local_matrix(
- self->local_matrix() *
- Vectormath::Aos::Matrix4::translation(translation));
- }
- void userglue_method_translate(o3d::Transform* self,
- float x,
- float y,
- float z) {
- self->set_local_matrix(self->local_matrix() *
- Vectormath::Aos::Matrix4::translation(
- Vectormath::Aos::Vector3(x, y, z)));
- }
- void userglue_method_rotateX(o3d::Transform* self,
- float radians) {
- self->set_local_matrix(self->local_matrix() *
- Vectormath::Aos::Matrix4::rotationX(radians));
- }
- void userglue_method_rotateY(o3d::Transform* self,
- float radians) {
- self->set_local_matrix(self->local_matrix() *
- Vectormath::Aos::Matrix4::rotationY(radians));
- }
- void userglue_method_rotateZ(o3d::Transform* self,
- float radians) {
- self->set_local_matrix(self->local_matrix() *
- Vectormath::Aos::Matrix4::rotationZ(radians));
- }
- void userglue_method_rotateZYX(o3d::Transform* self,
- const Vectormath::Aos::Vector3& radiansXYZ) {
- self->set_local_matrix(self->local_matrix() *
- Vectormath::Aos::Matrix4::rotationZYX(radiansXYZ));
- }
- void userglue_method_axisRotate(o3d::Transform* self,
- const Vectormath::Aos::Vector3& axis,
- float radians) {
- self->set_local_matrix(
- self->local_matrix() *
- Vectormath::Aos::Matrix4::rotation(radians,
- Vectormath::Aos::normalize(axis)));
- }
- void userglue_method_quaternionRotate(o3d::Transform* self,
- const Vectormath::Aos::Quat& quat) {
- self->set_local_matrix(self->local_matrix() *
- Vectormath::Aos::Matrix4::rotation(
- Vectormath::Aos::normalize(quat)));
- }
- void userglue_method_scale(
- o3d::Transform* self,
- const Vectormath::Aos::Vector3& scale) {
- self->set_local_matrix(self->local_matrix() *
- Vectormath::Aos::Matrix4::scale(scale));
- }
- void userglue_method_scale(o3d::Transform* self,
- float x,
- float y,
- float z) {
- self->set_local_matrix(
- self->local_matrix() *
- Vectormath::Aos::Matrix4::scale(Vectormath::Aos::Vector3(x, y, z)));
- }
- %}
-}; // Transform
-
-%[
- TransformArray is a typdef for an array of Transforms.
-%]
-typedef Transform[] TransformArray;
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/tree_traversal.idl b/o3d/plugin/idl/tree_traversal.idl
deleted file mode 100644
index e167c7a..0000000
--- a/o3d/plugin/idl/tree_traversal.idl
+++ /dev/null
@@ -1,74 +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.
- */
-
-namespace o3d {
-
-%[
- A TreeTraversal has multiple DrawLists registered with it. Each DrawList has
- a DrawContext registered with it. At render time the TreeTraversal walks the
- transform graph from the transform it's pointing at and for each DrawElement
- it finds who's matertial matches one of its registered DrawLists it adds that
- DrawElement to that DrawList.
-
- @o3dparameter transform ParamTransform The root transform to start traversing
- by this TreeTraveral.
-%]
-[nocpp, include="core/cross/tree_traversal.h"] class TreeTraversal
- : RenderNode {
-
- %[
- The root Transform this TreeTraversal will start traversing from.
- %]
- [getter, setter] Transform? transform_;
-
- %[
- Registers a DrawList with this TreeTraversal so that when this
- TreeTraversal traverses its tree, DrawElements using materials that use
- this DrawList will be added though possibly culled by the view frustum of
- the DrawContext. Note: passing in the same DrawList more than once will
- override the previous settings for that DrawList.
- \param draw_list DrawList to register.
- \param draw_context DrawContext to use with the DrawList.
- \param reset true if you want the DrawList reset before traversing.
- %]
- void RegisterDrawList(DrawList draw_list,
- DrawContext draw_context,
- bool reset);
-
- %[
- Unregisters a DrawList with this TreeTraversal.
- \param draw_list DrawList to unregister.
- \return true if unregistered. false if this draw_list was not registered.
- %]
- bool UnregisterDrawList(DrawList draw_list);
-}; // TreeTraversal
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/types.idl b/o3d/plugin/idl/types.idl
deleted file mode 100644
index 5756d9e..0000000
--- a/o3d/plugin/idl/types.idl
+++ /dev/null
@@ -1,130 +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.
- */
-
-// TODO: some how make this file conditionally compile different for C++
-// vs JavaScript like with #ifdef CPLUSPLUS etc..
-[verbatim=cpp_glue,include="plugin/cross/marshaling_utils.h"]
-namespace o3d {
-
-%[
- A data type consisting of 2 numbers. A Float2 is represented in JavaScript by
- an array containing 2 numbers: [x, y].
-%]
-[binding_model=by_value, marshaled, nocpp, include="core/cross/types.h"]
-class Float2 {
- [plugin_data, userglue_getter, userglue_setter, getter, setter, nodocs]
- float[] marshaled;
-
- [verbatim=cpp_glue] %{
- void userglue_setter_marshaled(
- void* plugin_data,
- o3d::Float2* self,
- const std::vector<float>& dynamicValue) {
- *self = o3d::VectorToType<o3d::Float2, 2>(
- plugin_data, dynamicValue);
- }
-
- std::vector<float> userglue_getter_marshaled(
- void* plugin_data,
- const o3d::Float2& self) {
- return o3d::VectorFromType<o3d::Float2, 2>(self);
- }
- %}
-};
-
-%[
- A data type consisting of 3 numbers. A Float3 is represented in JavaScript by
- an array containing 3 numbers: [x, y, z].
-%]
-[binding_model=by_value, marshaled, nocpp, include="core/cross/types.h"]
-class Float3 {
- [plugin_data, userglue_getter, userglue_setter, getter, setter, nodocs]
- float[] marshaled;
-
- [verbatim=cpp_glue] %{
- void userglue_setter_marshaled(
- void* plugin_data,
- o3d::Float3* self,
- const std::vector<float>& dynamicValue) {
- *self = o3d::VectorToType<o3d::Float3, 3>(
- plugin_data, dynamicValue);
- }
-
- std::vector<float> userglue_getter_marshaled(
- void* plugin_data,
- const o3d::Float3& self) {
- return o3d::VectorFromType<o3d::Float3, 3>(self);
- }
- %}
-};
-
-%[
- A data type consisting of 4 numbers. A Float4 is represented in JavaScript by
- an array containing 4 numbers: [x, y, z, w].
-%]
-[binding_model=by_value, marshaled, nocpp, include="core/cross/types.h"]
-class Float4 {
- [plugin_data, userglue_getter, userglue_setter, getter, setter, nodocs]
- float[] marshaled;
-
- [verbatim=cpp_glue] %{
- void userglue_setter_marshaled(
- void* plugin_data,
- o3d::Float4* self,
- const std::vector<float>& dynamicValue) {
- *self = o3d::VectorToType<o3d::Float4, 4>(
- plugin_data, dynamicValue);
- }
-
- std::vector<float> userglue_getter_marshaled(
- void* plugin_data,
- const o3d::Float4& self) {
- return o3d::VectorFromType<o3d::Float4, 4>(self);
- }
- %}
-};
-
-%[
- Id used to uniquely identify objects.
-%]
-[include="core/cross/types.h"] typedef int Id;
-
-%[
- Data type for passing data around in the scenegraph.
-%]
-[include="core/cross/types.h"] typedef float Float;
-
-%[
- Data type for passing data around in the scenegraph.
-%]
-[include="core/cross/types.h"] typedef std::string String;
-
-} // namespace o3d
diff --git a/o3d/plugin/idl/vector.idl b/o3d/plugin/idl/vector.idl
deleted file mode 100644
index 2d7d988..0000000
--- a/o3d/plugin/idl/vector.idl
+++ /dev/null
@@ -1,216 +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="plugin/cross/marshaling_utils.h"] %{
-%}
-
-namespace Vectormath {
-namespace Aos {
-
-%[
- A data type representing a 3d direction. A Vector3 is represented in
- JavaScript by an array containing 3 numbers: [x, y, z].
-%]
-[binding_model=by_value, marshaled, nocpp, include=
- "third_party/vectormath/files/vectormathlibrary/include/vectormath/scalar/cpp/vectormath_aos.h"]
-class Vector3 {
- [plugin_data, userglue_getter, userglue_setter, getter, setter, nodocs]
- float[] marshaled;
-
- [verbatim=cpp_glue] %{
- void userglue_setter_marshaled(
- void* plugin_data,
- Vectormath::Aos::Vector3* self,
- const std::vector<float>& dynamicValue) {
- *self = o3d::VectorToType<Vectormath::Aos::Vector3, 3>(
- plugin_data, dynamicValue);
- }
-
- std::vector<float> userglue_getter_marshaled(
- void* plugin_data,
- const Vectormath::Aos::Vector3& self) {
- return
- o3d::VectorFromType<Vectormath::Aos::Vector3, 3>(self);
- }
- %}
-};
-
-%[
- A data type representing a 3d point. A Point3 is represented in
- JavaScript by an array containing 3 numbers: [x, y, z].
-%]
-[binding_model=by_value, marshaled, nocpp, include=
- "third_party/vectormath/files/vectormathlibrary/include/vectormath/scalar/cpp/vectormath_aos.h"]
-class Point3 {
- [plugin_data, userglue_getter, userglue_setter, getter, setter, nodocs]
- float[] marshaled;
-
- [verbatim=cpp_glue] %{
- void userglue_setter_marshaled(
- void* plugin_data,
- Vectormath::Aos::Point3* self,
- const std::vector<float>& dynamicValue) {
- *self = o3d::VectorToType<Vectormath::Aos::Point3, 3>(
- plugin_data, dynamicValue);
- }
-
- std::vector<float> userglue_getter_marshaled(
- void* plugin_data,
- const Vectormath::Aos::Point3& self) {
- return o3d::VectorFromType<Vectormath::Aos::Point3, 3>(self);
- }
- %}
-};
-
-%[
- A data type representing a 4 value Vector. A Vector4 is represented in
- JavaScript by an array containing 4 numbers: [x, y, z, w].
-%]
-[binding_model=by_value, marshaled, nocpp, include=
- "third_party/vectormath/files/vectormathlibrary/include/vectormath/scalar/cpp/vectormath_aos.h"]
-class Vector4 {
- [plugin_data, userglue_getter, userglue_setter, getter, setter, nodocs]
- float[] marshaled;
-
- [verbatim=cpp_glue] %{
- void userglue_setter_marshaled(
- void* plugin_data,
- Vectormath::Aos::Vector4* self,
- const std::vector<float>& dynamicValue) {
- *self = o3d::VectorToType<Vectormath::Aos::Vector4, 4>(
- plugin_data, dynamicValue);
- }
-
- std::vector<float> userglue_getter_marshaled(
- void* plugin_data,
- const Vectormath::Aos::Vector4& self) {
- return
- o3d::VectorFromType<Vectormath::Aos::Vector4, 4>(self);
- }
- %}
-};
-
-%[
- A data type representing a 3x3 Matrix. A Matrix3 is represented in JavaScript
- by an array containing 3 arrays of 3 numbers each:
- \code
- [[x0, y0, z0],
- [x1, y1, z1],
- [x2, y2, z2]]
- \endcode
-%]
-[binding_model=by_value, marshaled, nocpp, include=
- "third_party/vectormath/files/vectormathlibrary/include/vectormath/scalar/cpp/vectormath_aos.h"]
-class Matrix3 {
- [plugin_data, userglue_getter, userglue_setter, getter, setter, nodocs]
- float[][] marshaled;
-
- [verbatim=cpp_glue] %{
- void userglue_setter_marshaled(
- void* plugin_data,
- Vectormath::Aos::Matrix3* self,
- const std::vector<std::vector<float> >& dynamicValue) {
- *self = o3d::VectorOfVectorToType<Vectormath::Aos::Matrix3, 3, 3>(
- plugin_data, dynamicValue);
- }
-
- std::vector<std::vector<float> > userglue_getter_marshaled(
- void* plugin_data,
- const Vectormath::Aos::Matrix3& self) {
- return o3d::VectorOfVectorFromType<Vectormath::Aos::Matrix3, 3, 3>(
- self);
- }
- %}
-};
-
-%[
- A data type representing a 4x4 Matrix. A Matrix4 is represented in JavaScript
- by an array containing 4 arrays of 4 numbers each:
- \code
- [[x0, y0, z0, w0],
- [x1, y1, z1, w1],
- [x2, y2, z2, w2],
- [x3, y3, z3, w3]]
- \endcode
-%]
-[binding_model=by_value, marshaled, nocpp, include=
- "third_party/vectormath/files/vectormathlibrary/include/vectormath/scalar/cpp/vectormath_aos.h"]
-class Matrix4 {
- [plugin_data, userglue_getter, userglue_setter, getter, setter, nodocs]
- float[][] marshaled;
-
- [verbatim=cpp_glue] %{
- void userglue_setter_marshaled(
- void* plugin_data,
- Vectormath::Aos::Matrix4* self,
- const std::vector<std::vector<float> >& dynamicValue) {
- *self = o3d::VectorOfVectorToType<Vectormath::Aos::Matrix4, 4, 4>(
- plugin_data, dynamicValue);
- }
-
- std::vector<std::vector<float> > userglue_getter_marshaled(
- void* plugin_data,
- const Vectormath::Aos::Matrix4& self) {
- return o3d::VectorOfVectorFromType<Vectormath::Aos::Matrix4, 4, 4>(
- self);
- }
- %}
-};
-
-%[
- A data type representing a Quaterion. A Quat is represented in JavaScript
- by an array containing 4 numbers: [x, y, z, w]
-%]
-[binding_model=by_value, marshaled, nocpp, include=
- "third_party/vectormath/files/vectormathlibrary/include/vectormath/scalar/cpp/vectormath_aos.h"]
-class Quat {
- [plugin_data, userglue_getter, userglue_setter, getter, setter, nodocs]
- float[] marshaled;
-
- [verbatim=cpp_glue] %{
- void userglue_setter_marshaled(
- void* plugin_data,
- Vectormath::Aos::Quat* self,
- const std::vector<float>& dynamicValue) {
- *self = o3d::VectorToType<Vectormath::Aos::Quat, 4>(
- plugin_data, dynamicValue);
- }
-
- std::vector<float> userglue_getter_marshaled(
- void* plugin_data,
- const Vectormath::Aos::Quat& self) {
- return o3d::VectorFromType<Vectormath::Aos::Quat, 4>(self);
- }
- %}
-};
-
-}
-}
diff --git a/o3d/plugin/idl/vertex_source.idl b/o3d/plugin/idl/vertex_source.idl
deleted file mode 100644
index 92cfe58..0000000
--- a/o3d/plugin/idl/vertex_source.idl
+++ /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.
- */
-
-
-// This file contains the idlglue declaration of VertexSource.
-
-namespace o3d {
-
-%[
- A VertexSource is an object that allows binding Streams such that the
- VertexSource updates the Buffers of the Streams that have been bound to it.
- An example of a VertexSource object is a SkinEval
-%]
-[nocpp, include="core/cross/vertex_source.h"] class VertexSource
- : ParamObject {
-
- %[
- Bind the source stream to the corresponding stream in this VertexSource.
-
- \param source Source to get vertices from.
- \param semantic The semantic of the vertices to get
- \param semantic_index The semantic index of the vertices to get.
- \return True if success. False if failure. If the requested semantic or
- semantic index do not exist on the source or this source the bind will
- fail.
- %]
- bool BindStream(VertexSource source,
- Stream::Semantic semantic,
- int semantic_index);
-
- %[
- Unbinds the requested stream.
- \param semantic The semantic of the vertices to unbind
- \param semantic_index The semantic index of the vertices to unbind.
- \return True if unbound. False those vertices do not exist or were not
- bound.
- %]
- bool UnbindStream(Stream::Semantic semantic, int semantic_index);
-}; // VertexSource
-
-} // namespace o3d
-
diff --git a/o3d/plugin/idl/viewport.idl b/o3d/plugin/idl/viewport.idl
deleted file mode 100644
index 0e12f94..0000000
--- a/o3d/plugin/idl/viewport.idl
+++ /dev/null
@@ -1,72 +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.
- */
-
-namespace o3d {
-
-%[
- A Viewport is a render node that sets the render viewport and depth range for
- its children. It uses an array in the format [left, top, width, height] where
- left, top, width and height are in a 0.0 to 1.0 range that represent positions
- and dimensions relative to the size of the client's rendering area. The depth
- range is represented by an array in the format [min Z, max Z]. The depth range
- provides the mapping of the clip space coordinates into normalized z buffer
- coordinates.
-
- @o3dparameter viewport ParamFloat4 The viewport setting.
- @o3dparameter depthRange ParamFloat2 The depth range setting.
-%]
-[nocpp, include="core/cross/viewport.h"] class Viewport
- : RenderNode {
- %[
- The position and size to set the viewport in
- [left, top, width, height] format.
-
- Note: These values must describe a rectangle that is 100% inside the client
- area. In other words, [0.5, 0.0, 1.0, 1.0] would describe an area that is
- 1/2 off right side of the screen. That is an invalid value and will be
- clipped to [0.5, 0.0, 0.5, 1.0].
-
- Default = [0.0, 0.0, 1.0, 1.0]. In other words, the full area.
-
- \sa o3d.Viewport
- %]
- [getter, setter] Float4 viewport;
-
- %[
- The min Z and max Z depth range in [min Z, max Z] format.
- Default = [0.0, 1.0].
-
- \sa o3d.Viewport
- %]
- [getter, setter] Float2 depth_range;
-}; // Viewport
-
-} // namespace o3d
diff --git a/o3d/plugin/idl_list.manifest b/o3d/plugin/idl_list.manifest
deleted file mode 100644
index 5e388dc..0000000
--- a/o3d/plugin/idl_list.manifest
+++ /dev/null
@@ -1,92 +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.
-
-
-[ 'idl/bitmap.idl',
- 'idl/bounding_box.idl',
- 'idl/buffer.idl',
- 'idl/canvas.idl',
- 'idl/canvas_paint.idl',
- 'idl/canvas_shader.idl',
- 'idl/clear_buffer.idl',
- 'idl/client.idl',
- 'idl/counter.idl',
- 'idl/cursor.idl',
- 'idl/curve.idl',
- 'idl/display_mode.idl',
- 'idl/draw_context.idl',
- 'idl/draw_element.idl',
- 'idl/draw_list.idl',
- 'idl/draw_pass.idl',
- 'idl/effect.idl',
- 'idl/element.idl',
- 'idl/event.idl',
- 'idl/field.idl',
- 'idl/file_request.idl',
- 'idl/function.idl',
- 'idl/material.idl',
- 'idl/matrix4_axis_rotation.idl',
- 'idl/matrix4_composition.idl',
- 'idl/matrix4_scale.idl',
- 'idl/matrix4_translation.idl',
- 'idl/named.idl',
- 'idl/pack.idl',
- 'idl/param_array.idl',
- 'idl/param.idl',
- 'idl/param_object.idl',
- 'idl/param_operation.idl',
- 'idl/plugin.idl',
- 'idl/primitive.idl',
- 'idl/processed_path.idl',
- 'idl/ray_intersection_info.idl',
- 'idl/render_event.idl',
- 'idl/render_node.idl',
- 'idl/render_surface.idl',
- 'idl/render_surface_set.idl',
- 'idl/sampler.idl',
- 'idl/shape.idl',
- 'idl/skin.idl',
- 'idl/standard_param.idl',
- 'idl/state.idl',
- 'idl/state_set.idl',
- 'idl/stream.idl',
- 'idl/stream_bank.idl',
- 'idl/texture.idl',
- 'idl/tick_event.idl',
- 'idl/transform.idl',
- 'idl/tree_traversal.idl',
- 'idl/types.idl',
- 'idl/vector.idl',
- 'idl/vertex_source.idl',
- 'idl/viewport.idl',
- 'idl/archive_request.idl',
- 'idl/raw_data.idl',
-]
-
-
diff --git a/o3d/plugin/linux/config.cc b/o3d/plugin/linux/config.cc
deleted file mode 100644
index c45c24f..0000000
--- a/o3d/plugin/linux/config.cc
+++ /dev/null
@@ -1,66 +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 code to check the hardware and software configuration of
-// the client machine:
-// - User agent (browser)
-// - OS version
-// - GPU vendor
-
-#include "plugin/cross/config.h"
-
-#include <iostream>
-#include <fstream>
-
-namespace o3d {
-
-// Checks OS version
-bool CheckOSVersion(NPP npp) {
- return true;
-}
-
-bool CheckUserAgent(NPP npp, const std::string &user_agent) {
- // TODO: check user agent.
- return true;
-}
-
-bool OpenDriverBlacklistFile(std::ifstream *input_file) {
- // TODO
- return false;
-}
-
-bool GetUserConfigMetrics() {
- // TODO: Finish this function!
- return true;
-}
-
-} // namespace o3d
diff --git a/o3d/plugin/linux/envvars.cc b/o3d/plugin/linux/envvars.cc
deleted file mode 100644
index 30f56b3..0000000
--- a/o3d/plugin/linux/envvars.cc
+++ /dev/null
@@ -1,84 +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 <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "plugin/linux/envvars.h"
-
-#include "base/logging.h"
-
-namespace o3d {
-
-static const unsigned int kMaxEnvVarLength = 1024;
-
-void LoadEnvironmentVariablesFile(const char *path) {
- FILE *env_vars_file = fopen(path, "r");
- // It is not an error if the file is missing. We treat it the same as if it
- // were empty.
- if (env_vars_file) {
- char buffer[kMaxEnvVarLength];
- while (!feof(env_vars_file) ) {
- if (fgets(buffer, sizeof(buffer), env_vars_file)) {
- char *equals = strchr(buffer, '=');
- if (!equals) {
- LOG(ERROR) << "Malformed environment variables file";
- continue;
- }
- char *value = equals + 1;
- *equals = '\0';
- int length = strlen(value);
- if (value[length - 1] == '\n') {
- value[length - 1] = '\0';
- }
- if (setenv(buffer, value, 1) != 0) {
- LOG(ERROR) << "Couldn't add " << buffer << "=" << value
- << " to environment";
- } else {
- // Custom environment variables could be relevant for debugging
- // problem reports, so log this too.
- LOG(INFO) << "Defined " << buffer << "=" << value;
- }
- } else if (ferror(env_vars_file)) {
- PLOG(ERROR) << "Error reading from environment variables file";
- break;
- } else {
- break;
- }
- }
- if (fclose(env_vars_file) != 0) {
- PLOG(ERROR) << "Unable to close environment variables file";
- }
- }
-}
-
-} // namespace o3d
diff --git a/o3d/plugin/linux/envvars.h b/o3d/plugin/linux/envvars.h
deleted file mode 100644
index d1d3e30..0000000
--- a/o3d/plugin/linux/envvars.h
+++ /dev/null
@@ -1,43 +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_PLUGIN_LINUX_ENVVARS_H_
-#define O3D_PLUGIN_LINUX_ENVVARS_H_
-
-namespace o3d {
-
-// Loads a list of environment variables into the current process from a text
-// file. Each line in the file must be a NAME=VALUE pair.
-void LoadEnvironmentVariablesFile(const char *path);
-
-} // namespace o3d
-
-#endif // O3D_PLUGIN_LINUX_ENVVARS_H_
diff --git a/o3d/plugin/linux/main_linux.cc b/o3d/plugin/linux/main_linux.cc
deleted file mode 100644
index 05f5f26..0000000
--- a/o3d/plugin/linux/main_linux.cc
+++ /dev/null
@@ -1,971 +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 implements the platform specific parts of the plugin for
-// the Linux platform.
-
-#include "plugin/cross/main.h"
-
-#include <X11/keysym.h>
-#include <gdk/gdkx.h>
-#include <gdk/gdkkeysyms.h>
-
-#include "base/logging.h"
-#include "base/third_party/nspr/prtypes.h"
-#include "core/cross/event.h"
-#include "core/linux/display_window_linux.h"
-#include "plugin/linux/envvars.h"
-#if !defined(O3D_INTERNAL_PLUGIN)
-#include "breakpad/linux/breakpad.h"
-#endif
-
-using glue::_o3d::PluginObject;
-using glue::StreamManager;
-using o3d::DisplayWindowLinux;
-using o3d::Event;
-
-namespace {
-
-bool g_xembed_support = false;
-
-#if !defined(O3D_INTERNAL_PLUGIN)
-o3d::Breakpad g_breakpad;
-#endif
-
-#ifdef O3D_PLUGIN_ENV_VARS_FILE
-static const char kEnvVarsFilePath[] = O3D_PLUGIN_ENV_VARS_FILE;
-#endif
-
-static void DrawPlugin(PluginObject *obj) {
- // Limit drawing to no more than once every timer tick.
- if (!obj->draw_) return;
- // Don't allow re-entrant rendering (can happen in Chrome)
- if (obj->client()->IsRendering()) return;
- obj->client()->RenderClient(true);
- obj->draw_ = false;
-}
-
-// Xt support functions
-
-void LinuxTimer(XtPointer data, XtIntervalId* id) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(data);
- DCHECK(obj->xt_interval_ == *id);
- obj->client()->Tick();
- obj->draw_ = true;
- if (obj->renderer()) {
- if (obj->client()->NeedsRender()) {
- // NOTE: this draws no matter what instead of just invalidating the
- // region, which means it will execute even if the plug-in window is
- // invisible.
- DrawPlugin(obj);
- }
- }
- obj->xt_interval_ =
- XtAppAddTimeOut(obj->xt_app_context_, 8, LinuxTimer, obj);
-}
-
-void LinuxExposeHandler(Widget w,
- XtPointer user_data,
- XEvent *event,
- Boolean *cont) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(user_data);
- if (event->type != Expose) return;
- DrawPlugin(obj);
-}
-
-static int KeySymToDOMKeyCode(KeySym key_sym) {
- // See https://developer.mozilla.org/en/DOM/Event/UIEvent/KeyEvent for the
- // DOM values.
- // X keycodes are not useful, because they describe the geometry, not the
- // associated symbol, so a 'Q' on a QWERTY (US) keyboard has the same keycode
- // as a 'A' on an AZERTY (french) one.
- // Key symbols are closer to what the DOM expects, but they depend on the
- // shift/control/alt combination - the same key has several symbols ('a' vs
- // 'A', '1' vs '!', etc.), so we do extra work so that 'a' and 'A' both
- // generate the same DOM keycode.
- if ((key_sym >= XK_0 && key_sym <= XK_Z)) {
- // DOM keycode matches ASCII value, as does the keysym.
- return key_sym;
- } else if ((key_sym >= XK_a && key_sym <= XK_z)) {
- return key_sym - XK_a + XK_A;
- } else if ((key_sym >= XK_KP_0 && key_sym <= XK_KP_9)) {
- return 0x60 + key_sym - XK_KP_0;
- } else if ((key_sym >= XK_F1 && key_sym <= XK_F24)) {
- return 0x70 + key_sym - XK_F1;
- }
- switch (key_sym) {
- case XK_Cancel:
- return 0x03;
- case XK_Help:
- return 0x06;
- case XK_BackSpace:
- return 0x08;
- case XK_Tab:
- return 0x09;
- case XK_Clear:
- return 0x0C;
- case XK_Return:
- return 0x0D;
- case XK_KP_Enter:
- return 0x0E;
- case XK_Shift_L:
- case XK_Shift_R:
- return 0x10;
- case XK_Control_L:
- case XK_Control_R:
- return 0x11;
- case XK_Alt_L:
- case XK_Alt_R:
- return 0x12;
- case XK_Pause:
- return 0x13;
- case XK_Caps_Lock:
- return 0x14;
- case XK_Escape:
- return 0x1B;
- case XK_space:
- return 0x20;
- case XK_Page_Up:
- case XK_KP_Page_Up:
- return 0x21;
- case XK_Page_Down:
- case XK_KP_Page_Down:
- return 0x22;
- case XK_End:
- case XK_KP_End:
- return 0x23;
- case XK_Home:
- case XK_KP_Home:
- return 0x24;
- case XK_Left:
- case XK_KP_Left:
- return 0x25;
- case XK_Up:
- case XK_KP_Up:
- return 0x26;
- case XK_Right:
- case XK_KP_Right:
- return 0x27;
- case XK_Down:
- case XK_KP_Down:
- return 0x28;
- case XK_Print:
- return 0x2C;
- case XK_Insert:
- case XK_KP_Insert:
- return 0x2D;
- case XK_Delete:
- case XK_KP_Delete:
- return 0x2E;
- case XK_Menu:
- return 0x5D;
- case XK_asterisk:
- case XK_KP_Multiply:
- return 0x6A;
- case XK_plus:
- case XK_KP_Add:
- return 0x6B;
- case XK_underscore:
- return 0x6C;
- case XK_minus:
- case XK_KP_Subtract:
- return 0x6E;
- case XK_KP_Decimal:
- return 0x6E;
- case XK_KP_Divide:
- return 0x6F;
- case XK_Num_Lock:
- return 0x90;
- case XK_Scroll_Lock:
- return 0x91;
- case XK_comma:
- return 0xBC;
- case XK_period:
- return 0xBE;
- case XK_slash:
- return 0xBF;
- case XK_grave:
- return 0xC0;
- case XK_bracketleft:
- return 0xDB;
- case XK_backslash:
- return 0xDC;
- case XK_bracketright:
- return 0xDD;
- case XK_apostrophe:
- return 0xDE;
- case XK_Meta_L:
- case XK_Meta_R:
- return 0xE0;
- default:
- return 0;
- }
-}
-
-static int GetXModifierState(int x_state) {
- int modifier_state = 0;
- if (x_state & ControlMask) {
- modifier_state |= Event::MODIFIER_CTRL;
- }
- if (x_state & ShiftMask) {
- modifier_state |= Event::MODIFIER_SHIFT;
- }
- if (x_state & Mod1Mask) {
- modifier_state |= Event::MODIFIER_ALT;
- }
- if (x_state & Mod2Mask) {
- modifier_state |= Event::MODIFIER_META;
- }
- return modifier_state;
-}
-
-void LinuxKeyHandler(Widget w,
- XtPointer user_data,
- XEvent *xevent,
- Boolean *cont) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(user_data);
- XKeyEvent *key_event = &xevent->xkey;
- Event::Type type;
- switch (xevent->type) {
- case KeyPress:
- type = Event::TYPE_KEYDOWN;
- break;
- case KeyRelease:
- type = Event::TYPE_KEYUP;
- break;
- default:
- return;
- }
- Event event(type);
- char char_code = 0;
- KeySym key_sym;
- int result = XLookupString(key_event, &char_code, sizeof(char_code),
- &key_sym, NULL);
- event.set_key_code(KeySymToDOMKeyCode(key_sym));
- int modifier_state = GetXModifierState(key_event->state);
- event.set_modifier_state(modifier_state);
- obj->client()->AddEventToQueue(event);
- if (xevent->type == KeyPress && result > 0) {
- event.clear_key_code();
- event.set_char_code(char_code);
- event.set_type(Event::TYPE_KEYPRESS);
- obj->client()->AddEventToQueue(event);
- }
-}
-
-// TODO: Any way to query the system for the correct value ? According to
-// http://library.gnome.org/devel/gdk/stable/gdk-Event-Structures.html GTK uses
-// 250ms.
-const unsigned int kDoubleClickTime = 250; // in ms
-
-void LinuxMouseButtonHandler(Widget w,
- XtPointer user_data,
- XEvent *xevent,
- Boolean *cont) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(user_data);
- XButtonEvent *button_event = &xevent->xbutton;
- Event::Type type;
- switch (xevent->type) {
- case ButtonPress:
- type = Event::TYPE_MOUSEDOWN;
- break;
- case ButtonRelease:
- type = Event::TYPE_MOUSEUP;
- break;
- default:
- return;
- }
- Event event(type);
- switch (button_event->button) {
- case 1:
- event.set_button(Event::BUTTON_LEFT);
- break;
- case 2:
- event.set_button(Event::BUTTON_MIDDLE);
- break;
- case 3:
- event.set_button(Event::BUTTON_RIGHT);
- break;
- case 4:
- case 5:
- // Mouse wheel. 4 is up, 5 is down. Reported by X as Press/Release.
- // Ignore the Press, report the Release as the wheel event.
- if (xevent->type == ButtonPress)
- return;
- event.set_type(Event::TYPE_WHEEL);
- event.set_delta(0, (button_event->button == 4) ? 1 : -1);
- break;
- default:
- return;
- }
- int modifier_state = GetXModifierState(button_event->state);
- event.set_modifier_state(modifier_state);
- event.set_position(button_event->x, button_event->y,
- button_event->x_root, button_event->y_root,
- obj->in_plugin());
- obj->client()->AddEventToQueue(event);
- if (event.type() == Event::TYPE_MOUSEUP && obj->in_plugin()) {
- // The event manager automatically generates CLICK from MOUSEDOWN, MOUSEUP.
- if (button_event->time < obj->last_click_time() + kDoubleClickTime) {
- obj->set_last_click_time(0);
- event.set_type(Event::TYPE_DBLCLICK);
- obj->client()->AddEventToQueue(event);
- } else {
- obj->set_last_click_time(button_event->time);
- }
- }
-}
-
-void LinuxMouseMoveHandler(Widget w,
- XtPointer user_data,
- XEvent *xevent,
- Boolean *cont) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(user_data);
- if (xevent->type != MotionNotify)
- return;
- XMotionEvent *motion_event = &xevent->xmotion;
- Event event(Event::TYPE_MOUSEMOVE);
- int modifier_state = GetXModifierState(motion_event->state);
- event.set_modifier_state(modifier_state);
- event.set_position(motion_event->x, motion_event->y,
- motion_event->x_root, motion_event->y_root,
- obj->in_plugin());
- obj->client()->AddEventToQueue(event);
-}
-
-void LinuxEnterLeaveHandler(Widget w,
- XtPointer user_data,
- XEvent *xevent,
- Boolean *cont) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(user_data);
- switch (xevent->type) {
- case EnterNotify:
- obj->set_in_plugin(true);
- break;
- case LeaveNotify:
- obj->set_in_plugin(false);
- break;
- default:
- return;
- }
-}
-
-// XEmbed / GTK support functions
-static int GetGtkModifierState(int gtk_state) {
- int modifier_state = 0;
- if (gtk_state & GDK_CONTROL_MASK) {
- modifier_state |= Event::MODIFIER_CTRL;
- }
- if (gtk_state & GDK_SHIFT_MASK) {
- modifier_state |= Event::MODIFIER_SHIFT;
- }
- if (gtk_state & GDK_MOD1_MASK) {
- modifier_state |= Event::MODIFIER_ALT;
- }
-#if 0
- // TODO: This code is temporarily disabled until we figure out which exact
- // version of GTK to test for: GDK_META_MASK doesn't exist in older (e.g. 2.8)
- // versions.
- if (gtk_state & GDK_META_MASK) {
- modifier_state |= Event::MODIFIER_META;
- }
-#endif
- return modifier_state;
-}
-
-static gboolean GtkHandleMouseMove(GtkWidget *widget,
- GdkEventMotion *motion_event,
- PluginObject *obj) {
- Event event(Event::TYPE_MOUSEMOVE);
- int modifier_state = GetGtkModifierState(motion_event->state);
- event.set_modifier_state(modifier_state);
- event.set_position(static_cast<int>(motion_event->x),
- static_cast<int>(motion_event->y),
- static_cast<int>(motion_event->x_root),
- static_cast<int>(motion_event->y_root),
- obj->in_plugin());
- obj->client()->AddEventToQueue(event);
- return TRUE;
-}
-
-static gboolean GtkHandleMouseButton(GtkWidget *widget,
- GdkEventButton *button_event,
- PluginObject *obj) {
- // On a double-click, Gtk produces: BUTTON_PRESS, BUTTON_RELEASE,
- // BUTTON_PRESS, 2BUTTON_PRESS, BUTTON_RELEASE.
- // JavaScript should receive: down, up, [optional move, ] click, down,
- // up, click, dblclick.
- // The EventManager turns (down, up) into click, since we need that on all
- // platforms.
- // So when a 2BUTTON_PRESS occurs, we keep track of this, so that we can
- // issue a corresponding dblclick when BUTTON_RELEASE comes.
- Event::Button button;
- switch (button_event->button) {
- case 1:
- button = Event::BUTTON_LEFT;
- break;
- case 2:
- button = Event::BUTTON_MIDDLE;
- break;
- case 3:
- button = Event::BUTTON_RIGHT;
- break;
- default:
- return FALSE;
- }
- Event::Type type;
- switch (button_event->type) {
- case GDK_BUTTON_PRESS:
- type = Event::TYPE_MOUSEDOWN;
- break;
- case GDK_BUTTON_RELEASE:
- type = Event::TYPE_MOUSEUP;
- break;
- case GDK_2BUTTON_PRESS:
- obj->got_double_click_[button_event->button - 1] = true;
- return TRUE;
- default:
- return FALSE;
- }
- Event event(type);
- int modifier_state = GetGtkModifierState(button_event->state);
- event.set_modifier_state(modifier_state);
- event.set_button(button);
- event.set_position(static_cast<int>(button_event->x),
- static_cast<int>(button_event->y),
- static_cast<int>(button_event->x_root),
- static_cast<int>(button_event->y_root),
- obj->in_plugin());
- obj->client()->AddEventToQueue(event);
- if (event.type() == Event::TYPE_MOUSEUP && obj->in_plugin() &&
- obj->got_double_click_[button_event->button - 1]) {
- obj->got_double_click_[button_event->button - 1] = false;
- event.set_type(Event::TYPE_DBLCLICK);
- obj->client()->AddEventToQueue(event);
- }
- if (event.in_plugin() && event.type() == Event::TYPE_MOUSEDOWN &&
- obj->HitFullscreenClickRegion(event.x(), event.y())) {
- obj->RequestFullscreenDisplay(button_event->time);
- }
- return TRUE;
-}
-
-static gboolean GtkHandleKey(GtkWidget *widget,
- GdkEventKey *key_event,
- PluginObject *obj) {
- Event::Type type;
- switch (key_event->type) {
- case GDK_KEY_PRESS:
- type = Event::TYPE_KEYDOWN;
- break;
- case GDK_KEY_RELEASE:
- type = Event::TYPE_KEYUP;
- break;
- default:
- return FALSE;
- }
- Event event(type);
- // Logically, GTK events and X events use a different namespace for the
- // various values, but in practice, all the keys we use have the same values,
- // because one of the paths in GTK uses straight X to do the translation. So
- // we can use the same function here.
- int key_code = KeySymToDOMKeyCode(key_event->keyval);
- event.set_key_code(key_code);
- int modifier_state = GetGtkModifierState(key_event->state);
- event.set_modifier_state(modifier_state);
- obj->client()->AddEventToQueue(event);
- int char_code = gdk_keyval_to_unicode(key_event->keyval);
- if (key_event->type == GDK_KEY_PRESS && char_code != 0) {
- event.clear_key_code();
- event.set_char_code(char_code);
- event.set_type(Event::TYPE_KEYPRESS);
- obj->client()->AddEventToQueue(event);
- }
- // No need to check for Alt+F4 because Gtk (or the window manager?) handles
- // that and delivers a destroy event to us already.
- if (event.type() == Event::TYPE_KEYDOWN &&
- event.key_code() == 0x1B) { // escape
- obj->CancelFullscreenDisplay();
- }
- return TRUE;
-}
-
-static gboolean GtkHandleScroll(GtkWidget *widget,
- GdkEventScroll *scroll_event,
- PluginObject *obj) {
- Event event(Event::TYPE_WHEEL);
- switch (scroll_event->direction) {
- case GDK_SCROLL_UP:
- event.set_delta(0, 1);
- break;
- case GDK_SCROLL_DOWN:
- event.set_delta(0, -1);
- break;
- case GDK_SCROLL_LEFT:
- event.set_delta(-1, 0);
- break;
- case GDK_SCROLL_RIGHT:
- event.set_delta(1, 0);
- break;
- default:
- return FALSE;
- }
- int modifier_state = GetGtkModifierState(scroll_event->state);
- event.set_modifier_state(modifier_state);
- event.set_position(static_cast<int>(scroll_event->x),
- static_cast<int>(scroll_event->y),
- static_cast<int>(scroll_event->x_root),
- static_cast<int>(scroll_event->y_root),
- obj->in_plugin());
- obj->client()->AddEventToQueue(event);
- return TRUE;
-}
-
-static gboolean GtkEventCallback(GtkWidget *widget,
- GdkEvent *event,
- gpointer user_data) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(user_data);
- DLOG_ASSERT(widget == obj->gtk_event_source_);
- switch (event->type) {
- case GDK_EXPOSE:
- if (GTK_WIDGET_DRAWABLE(widget)) {
- obj->draw_ = true;
- DrawPlugin(obj);
- }
- return TRUE;
- case GDK_ENTER_NOTIFY:
- obj->set_in_plugin(true);
- return TRUE;
- case GDK_LEAVE_NOTIFY:
- obj->set_in_plugin(false);
- return TRUE;
- case GDK_MOTION_NOTIFY:
- return GtkHandleMouseMove(widget, &event->motion, obj);
- case GDK_BUTTON_PRESS:
- case GDK_2BUTTON_PRESS:
- case GDK_BUTTON_RELEASE:
- return GtkHandleMouseButton(widget, &event->button, obj);
- case GDK_KEY_PRESS:
- case GDK_KEY_RELEASE:
- return GtkHandleKey(widget, &event->key, obj);
- case GDK_SCROLL:
- return GtkHandleScroll(widget, &event->scroll, obj);
- default:
- return FALSE;
- }
-}
-
-static gboolean GtkConfigureEventCallback(GtkWidget *widget,
- GdkEventConfigure *configure_event,
- gpointer user_data) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(user_data);
- return obj->OnGtkConfigure(widget, configure_event);
-}
-
-static gboolean GtkDeleteEventCallback(GtkWidget *widget,
- GdkEvent *event,
- gpointer user_data) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(user_data);
- return obj->OnGtkDelete(widget, event);
-}
-
-static gboolean GtkTimeoutCallback(gpointer user_data) {
- HANDLE_CRASHES;
- PluginObject *obj = static_cast<PluginObject *>(user_data);
- obj->draw_ = true;
- obj->client()->Tick();
- if (obj->renderer()) {
- if (obj->client()->NeedsRender()) {
- GtkWidget *widget;
- if (obj->fullscreen()) {
- widget = obj->gtk_fullscreen_container_;
- } else {
- widget = obj->gtk_container_;
- }
- gtk_widget_queue_draw(widget);
- }
- }
- return TRUE;
-}
-
-} // end anonymous namespace
-
-namespace o3d {
-
-NPError PlatformPreNPInitialize() {
-#if !defined(O3D_INTERNAL_PLUGIN)
- // Setup breakpad
- g_breakpad.Initialize();
- g_breakpad.set_version(O3D_PLUGIN_VERSION);
-#endif
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformPostNPInitialize() {
-#ifdef O3D_PLUGIN_ENV_VARS_FILE
- // Before doing anything more, we first load our environment variables file.
- // This file is a newline-delimited list of any system-specific environment
- // variables that need to be set in the browser. Since we are a shared library
- // and not an executable, we can't set them at browser start time, so we
- // instead set them in every process that loads our shared library. It is
- // important that we do this as early as possible so that any relevant
- // variables are already set when we initialize our shared library
- // dependencies.
- o3d::LoadEnvironmentVariablesFile(kEnvVarsFilePath);
-#endif
-
- // Check for XEmbed support in the browser.
- // Tragically, nspluginwrapper thinks that the type of boolean variables is
- // supposed to be PRBool, which has size of 4, and not NPBool, which has size
- // of 1, so we have to use PRBool here so that an integer-sized write by the
- // plugin host will succeed and not clobber anything else on our stack.
- PRBool xembed_support = PR_FALSE;
- NPError err = NPN_GetValue(NULL, NPNVSupportsXEmbedBool, &xembed_support);
- if (err != NPERR_NO_ERROR)
- xembed_support = PR_FALSE;
-
- if (xembed_support) {
- // Check for Gtk2 toolkit support in the browser.
- NPNToolkitType toolkit = static_cast<NPNToolkitType>(0);
- err = NPN_GetValue(NULL, NPNVToolkit, &toolkit);
- if (err != NPERR_NO_ERROR || toolkit != NPNVGtk2)
- xembed_support = PR_FALSE;
- }
- g_xembed_support = xembed_support != PR_FALSE;
-
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformPreNPShutdown() {
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformPostNPShutdown() {
-#if !defined(O3D_INTERNAL_PLUGIN)
- g_breakpad.Shutdown();
-#endif
-
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformNPPGetValue(PluginObject *obj,
- NPPVariable variable,
- void *value) {
- switch (variable) {
- case NPPVpluginNeedsXEmbed:
- *static_cast<NPBool *>(value) = g_xembed_support;
- return NPERR_NO_ERROR;
- default:
- return NPERR_INVALID_PARAM;
- }
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformNPPNew(NPP instance, PluginObject *obj) {
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformNPPDestroy(NPP instance, PluginObject *obj) {
- // TODO(tschmelcher): Do we really have to do this before the other teardown
- // below? If not then we can factor out the platform-specific TearDown()
- // calls into NPP_Destroy() in main.cc.
- obj->TearDown();
-
- if (obj->xt_widget_) {
- // NOTE: This crashes. Not sure why, possibly the widget has
- // already been destroyed, but we haven't received a SetWindow(NULL).
- // XtRemoveEventHandler(obj->xt_widget_, ExposureMask, False,
- // LinuxExposeHandler, obj);
- obj->xt_widget_ = NULL;
- }
- if (obj->xt_interval_) {
- XtRemoveTimeOut(obj->xt_interval_);
- obj->xt_interval_ = 0;
- }
- if (obj->timeout_id_) {
- g_source_remove(obj->timeout_id_);
- obj->timeout_id_ = 0;
- }
- if (obj->gtk_container_) {
- gtk_widget_destroy(obj->gtk_container_);
- obj->gtk_container_ = NULL;
- }
- if (obj->gtk_fullscreen_container_) {
- gtk_widget_destroy(obj->gtk_fullscreen_container_);
- obj->gtk_fullscreen_container_ = NULL;
- }
- if (obj->gdk_display_) {
- gdk_display_close(obj->gdk_display_);
- obj->gdk_display_ = NULL;
- }
- obj->gtk_event_source_ = NULL;
- obj->event_handler_id_ = 0;
- obj->window_ = 0;
- obj->drawable_ = 0;
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformNPPSetWindow(NPP instance,
- PluginObject *obj,
- NPWindow *window) {
- NPSetWindowCallbackStruct *cb_struct =
- static_cast<NPSetWindowCallbackStruct *>(window->ws_info);
- Window xwindow = reinterpret_cast<Window>(window->window);
- if (xwindow != obj->window_) {
- Display *display = cb_struct->display;
- Window drawable = xwindow;
- if (g_xembed_support) {
- // We asked for a XEmbed plugin, the xwindow is a GtkSocket, we create
- // a GtkPlug to go into it.
- obj->gdk_display_ = gdk_display_open(XDisplayString(display));
- LOG_ASSERT(obj->gdk_display_) << "Unable to open X11 display";
- display = GDK_DISPLAY_XDISPLAY(obj->gdk_display_);
- obj->gtk_container_ =
- gtk_plug_new_for_display(obj->gdk_display_, xwindow);
- // Firefox has a bug where it sometimes destroys our parent widget before
- // calling NPP_Destroy. We handle this by hiding our X window instead of
- // destroying it. Without this, future OpenGL calls can raise a
- // GLXBadDrawable error and kill the browser process.
- g_signal_connect(obj->gtk_container_, "delete-event",
- G_CALLBACK(gtk_widget_hide_on_delete), NULL);
- gtk_widget_set_double_buffered(obj->gtk_container_, FALSE);
- if (!obj->fullscreen()) {
- obj->SetGtkEventSource(obj->gtk_container_);
- }
- gtk_widget_show(obj->gtk_container_);
- drawable = GDK_WINDOW_XID(obj->gtk_container_->window);
- obj->timeout_id_ = g_timeout_add(8, GtkTimeoutCallback, obj);
- } else {
- // No XEmbed support, the xwindow is a Xt Widget.
- Widget widget = XtWindowToWidget(display, xwindow);
- if (!widget) {
- DLOG(ERROR) << "window is not a Widget";
- return NPERR_MODULE_LOAD_FAILED_ERROR;
- }
- obj->xt_widget_ = widget;
- XtAddEventHandler(widget, ExposureMask, 0, LinuxExposeHandler, obj);
- XtAddEventHandler(widget, KeyPressMask|KeyReleaseMask, 0,
- LinuxKeyHandler, obj);
- XtAddEventHandler(widget, ButtonPressMask|ButtonReleaseMask, 0,
- LinuxMouseButtonHandler, obj);
- XtAddEventHandler(widget, PointerMotionMask, 0,
- LinuxMouseMoveHandler, obj);
- XtAddEventHandler(widget, EnterWindowMask|LeaveWindowMask, 0,
- LinuxEnterLeaveHandler, obj);
- obj->xt_app_context_ = XtWidgetToApplicationContext(widget);
- obj->xt_interval_ =
- XtAppAddTimeOut(obj->xt_app_context_, 8, LinuxTimer, obj);
- }
-
- // Create and assign the graphics context.
- o3d::DisplayWindowLinux default_display;
- default_display.set_display(display);
- default_display.set_window(drawable);
-
- obj->CreateRenderer(default_display);
- obj->client()->Init();
- obj->SetDisplay(display);
- obj->window_ = xwindow;
- obj->drawable_ = drawable;
- }
- obj->Resize(window->width, window->height);
-
- return NPERR_NO_ERROR;
-}
-
-void PlatformNPPStreamAsFile(StreamManager *stream_manager,
- NPStream *stream,
- const char *fname) {
- stream_manager->SetStreamFile(stream, fname);
-}
-
-int16 PlatformNPPHandleEvent(NPP instance, PluginObject *obj, void *event) {
- return 0;
-}
-
-} // namespace o3d
-
-// TODO(tschmelcher): This stuff does not belong in this file.
-namespace glue {
-namespace _o3d {
-
-void PluginObject::SetGtkEventSource(GtkWidget *widget) {
- if (gtk_event_source_) {
- g_signal_handler_disconnect(G_OBJECT(gtk_event_source_),
- event_handler_id_);
- }
- gtk_event_source_ = widget;
- if (gtk_event_source_) {
- gtk_widget_add_events(gtk_event_source_,
- GDK_BUTTON_PRESS_MASK |
- GDK_BUTTON_RELEASE_MASK |
- GDK_SCROLL_MASK |
- GDK_KEY_PRESS_MASK |
- GDK_KEY_RELEASE_MASK |
- GDK_POINTER_MOTION_MASK |
- GDK_EXPOSURE_MASK |
- GDK_ENTER_NOTIFY_MASK |
- GDK_LEAVE_NOTIFY_MASK);
- event_handler_id_ = g_signal_connect(gtk_event_source_, "event",
- G_CALLBACK(GtkEventCallback), this);
- }
-}
-
-gboolean PluginObject::OnGtkConfigure(GtkWidget *widget,
- GdkEventConfigure *configure_event) {
- DLOG_ASSERT(widget == gtk_fullscreen_container_);
- if (fullscreen_pending_) {
- // Our fullscreen window has been placed and sized. Switch to it.
- fullscreen_pending_ = false;
- fullscreen_window_ = GDK_WINDOW_XID(gtk_fullscreen_container_->window);
- DisplayWindowLinux display;
- display.set_display(display_);
- display.set_window(fullscreen_window_);
- prev_width_ = renderer()->width();
- prev_height_ = renderer()->height();
- if (!renderer()->GoFullscreen(display, fullscreen_region_mode_id_)) {
- gtk_widget_destroy(gtk_fullscreen_container_);
- gtk_fullscreen_container_ = NULL;
- fullscreen_window_ = 0;
- // The return value is for whether we handled the event, not whether it
- // was successful, so return TRUE event for error.
- return TRUE;
- }
- SetGtkEventSource(gtk_fullscreen_container_);
- }
- renderer()->Resize(configure_event->width, configure_event->height);
- client()->SendResizeEvent(renderer()->width(), renderer()->height(),
- true);
- fullscreen_ = true;
- // Return false here so that the default handler in GTK will still be invoked.
- return FALSE;
-}
-
-gboolean PluginObject::OnGtkDelete(GtkWidget *widget,
- GdkEvent *event) {
- DLOG_ASSERT(widget == gtk_fullscreen_container_);
- CancelFullscreenDisplay();
- return TRUE;
-}
-
-bool PluginObject::GetDisplayMode(int id, o3d::DisplayMode *mode) {
- return renderer()->GetDisplayMode(id, mode);
-}
-
-// TODO: Where should this really live? It's platform-specific, but in
-// PluginObject, which mainly lives in cross/o3d_glue.h+cc.
-bool PluginObject::RequestFullscreenDisplay(guint32 timestamp) {
- if (fullscreen_ || fullscreen_pending_) {
- return false;
- }
- if (!g_xembed_support) {
- // I tested every Linux browser I could that worked with our plugin and not
- // a single one lacked XEmbed/Gtk2 support, so I don't think that case is
- // worth implementing.
- DLOG(ERROR) << "Fullscreen not supported without XEmbed/Gtk2; please use a "
- "modern web browser";
- return false;
- }
- GtkWidget *widget = gtk_window_new(GTK_WINDOW_TOPLEVEL);
- // The returned object counts as both a widget and a window.
- GtkWindow *window = GTK_WINDOW(widget);
- // Ensure that the fullscreen window is displayed on the same screen as the
- // embedded window.
- GdkScreen *screen = gtk_window_get_screen(GTK_WINDOW(gtk_container_));
- gtk_window_set_screen(window, screen);
- // The window title shouldn't normally be visible, but the user will see it
- // if they Alt+Tab to another app.
- gtk_window_set_title(window, "O3D Application");
- // Suppresses the title bar, resize controls, etc.
- gtk_window_set_decorated(window, FALSE);
- // Stops Gtk from writing an off-screen buffer to the display, which conflicts
- // with our GL rendering.
- gtk_widget_set_double_buffered(widget, FALSE);
- gtk_window_set_keep_above(window, TRUE);
- // In the case of Xinerama or TwinView, these will be the dimensions of the
- // whole desktop, which is wrong, but the window manager is smart enough to
- // restrict our size to that of the main screen.
- gint width = gdk_screen_get_width(screen);
- gint height = gdk_screen_get_height(screen);
- gtk_window_set_default_size(window, width, height);
- // This is probably superfluous since we have already set an appropriate
- // size, but let's do it anyway. It could still be relevant for some window
- // managers.
- gtk_window_fullscreen(window);
- g_signal_connect(window, "configure-event",
- G_CALLBACK(GtkConfigureEventCallback), this);
- g_signal_connect(window, "delete-event",
- G_CALLBACK(GtkDeleteEventCallback), this);
- gtk_fullscreen_container_ = widget;
- // The timestamp here is optional, but its inclusion is preferred.
- gtk_window_present_with_time(window, timestamp);
- // Explicitly set focus, otherwise we may not get it depending on the window
- // manager's policy for present.
- gdk_window_focus(widget->window, timestamp);
- // We defer switching to the new window until it gets displayed and assigned
- // it's final dimensions in the configure-event.
- fullscreen_pending_ = true;
- return true;
-}
-
-void PluginObject::CancelFullscreenDisplay() {
- if (!fullscreen_) {
- return;
- }
- o3d::DisplayWindowLinux default_display;
- default_display.set_display(display_);
- default_display.set_window(drawable_);
- if (!renderer()->CancelFullscreen(default_display,
- prev_width_,
- prev_height_)) {
- return;
- }
- renderer()->Resize(prev_width_, prev_height_);
- client()->SendResizeEvent(renderer()->width(), renderer()->height(),
- false);
- SetGtkEventSource(gtk_container_);
- gtk_widget_destroy(gtk_fullscreen_container_);
- gtk_fullscreen_container_ = NULL;
- fullscreen_window_ = 0;
- fullscreen_ = false;
-}
-} // namespace _o3d
-} // namespace glue
diff --git a/o3d/plugin/mac/Info.plist b/o3d/plugin/mac/Info.plist
deleted file mode 100644
index 857c3c5..0000000
--- a/o3d/plugin/mac/Info.plist
+++ /dev/null
@@ -1,62 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>CFBundleName</key>
- <string>@@@PluginName@@@</string>
- <key>CFBundleDevelopmentRegion</key>
- <string>English</string>
- <key>CFBundleExecutable</key>
- <string>@@@PluginNpapiFilename@@@</string>
- <key>CFBundleIconFile</key>
- <string></string>
- <key>CFBundleIdentifier</key>
- <string>com.google.o3d</string>
- <key>CFBundleInfoDictionaryVersion</key>
- <string>6.0</string>
- <key>CFBundlePackageType</key>
- <string>BRPL</string>
- <key>CFBundleSignature</key>
- <string>TEST</string>
- <key>CFBundleVersion</key>
- <string>@@@ProductVersion@@@</string>
- <key>CFBundleShortVersionString</key>
- <string>@@@ProductVersion@@@</string>
- <key>CCFBundleGetInfoString</key>
- <string>"Version @@@ProductVersion@@@, Copyright 2009, Google Inc."</string>
- <key>CSResourcesFileMapped</key>
- <true/>
- <key>WebPluginDescription</key>
- <string>@@@PluginDescription@@@</string>
- <key>WebPluginMIMETypes</key>
- <dict>
- <key>@@@PluginNpapiMimeType@@@</key>
- <dict>
- <key>WebPluginTypeDescription</key>
- <string>@@@PluginName@@@ Type</string>
- </dict>
- </dict>
- <key>WebPluginName</key>
- <string>@@@PluginName@@@</string>
- <key>O3DForceSoftwareRenderer</key>
- <false/>
- <key>BreakpadInspectorLocation</key>
- <string>/Library/Internet Plug-Ins/@@@PluginNpapiFilename@@@.plugin/Contents/Resources/crash_inspector</string>
- <key>BreakpadReporterExeLocation</key>
- <string>/Library/Internet Plug-Ins/@@@PluginNpapiFilename@@@.plugin/Contents/Resources/crash_report_sender.app/Contents/MacOS/crash_report_sender</string>
- <key>BreakpadProduct</key>
- <string>O3D</string>
- <key>BreakpadProductDisplay</key>
- <string>@@@PluginName@@@</string>
- <key>BreakpadVendor</key>
- <string>Google</string>
- <key>BreakpadVersion</key>
- <string>@@@ProductVersion@@@ (mac)</string>
- <key>BreakpadSendAndExit</key>
- <string>1</string>
- <key>BreakpadReportInterval</key>
- <string>3600</string>
- <key>BreakpadURL</key>
- <string>@@@PluginBreakpadURL@@@</string>
-</dict>
-</plist>
diff --git a/o3d/plugin/mac/Resources/English.lproj/InfoPlist.strings b/o3d/plugin/mac/Resources/English.lproj/InfoPlist.strings
deleted file mode 100644
index 5cfd33d..0000000
--- a/o3d/plugin/mac/Resources/English.lproj/InfoPlist.strings
+++ /dev/null
@@ -1,10 +0,0 @@
-/*
- File: InfoPlist.strings
-
- Description:Finder Bundle Information
-
- Localized versions of Info.plist keys */
-
-CFBundleName = "O3D Plugin";
-
-NSHumanReadableCopyright = "Copyright 2009, Google, Inc.";
diff --git a/o3d/plugin/mac/Tools/fix_install_names.sh b/o3d/plugin/mac/Tools/fix_install_names.sh
deleted file mode 100755
index 518f59c..0000000
--- a/o3d/plugin/mac/Tools/fix_install_names.sh
+++ /dev/null
@@ -1,21 +0,0 @@
-#!/bin/sh
-
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# Since the web-plugin is not the main executable, we need to change
-# the @executable_path reference to @loader_path for our embedded frameworks
-#
-
-# First take care of Breakpad.framework
-/usr/bin/install_name_tool -change \
- @executable_path/../Frameworks/Breakpad.framework/Versions/A/Breakpad \
- @loader_path/../Frameworks/Breakpad.framework/Versions/A/Breakpad \
- "$1"
-
-# Cg.framework
-/usr/bin/install_name_tool -change \
- @executable_path/../Library/Frameworks/Cg.framework/Cg \
- @loader_path/../Frameworks/Cg.framework/Cg \
- "$1"
diff --git a/o3d/plugin/mac/config_mac.mm b/o3d/plugin/mac/config_mac.mm
deleted file mode 100644
index df5673c..0000000
--- a/o3d/plugin/mac/config_mac.mm
+++ /dev/null
@@ -1,361 +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 code to check the hardware and software configuration of
-// the client machine:
-// - User agent (browser)
-// - OS version
-// - GPU vendor
-
-#include <IOKit/IOKitLib.h>
-
-#include <iostream>
-#include <fstream>
-
-#include "core/cross/renderer.h"
-#include "plugin/cross/config.h"
-#include "plugin/cross/plugin_metrics.h"
-#include "plugin_mac.h"
-
-@interface BundleReader : NSObject {
-}
-
-- (BOOL)boolValueForKey:(NSString*)key;
-@end
-
-@implementation BundleReader
-
-- (BOOL) boolValueForKey:(NSString*)key {
- NSBundle *bundle = [NSBundle bundleForClass:[self class]];
- return [[bundle objectForInfoDictionaryKey:key] boolValue];
-}
-@end
-
-namespace o3d {
-
-// Trivial little functions to check for the OS version boundaries we care about
-// and keep the result cached so they are cheap to call repeatedly.
-
-
-// Returns whether OS is 10.4 (Tiger) or higher.
-static bool IsMacOSTenFourOrHigher() {
- static bool isCached = false, result = false;
- if (!isCached) {
- SInt32 major = 0, minor = 0;
- // These selectors don't exist pre 10.4 but as we check the error
- // the function will correctly return NO which is the right answer.
- result = ((Gestalt(gestaltSystemVersionMajor, &major) == noErr) &&
- (Gestalt(gestaltSystemVersionMinor, &minor) == noErr) &&
- ((major > 10) || (major == 10 && minor >= 4)));
- isCached = true;
- }
- return result;
-}
-
-
-// Checks OS version
-bool CheckOSVersion(NPP npp) {
- // TODO: turn this back on when ready.
- if (!IsMacOSTenFourOrHigher()) {
- std::string error =
- std::string("Unsupported Mac OS X version. 10.4 is required.");
- return AskUser(npp, error);
- }
- return true;
-}
-
-bool CheckUserAgent(NPP npp, const std::string &user_agent) {
- return true;
-}
-
-bool OpenDriverBlacklistFile(std::ifstream *input_file) {
- // TODO:
- return false;
-}
-
-
-static CFTypeRef SearchPortForProperty(io_registry_entry_t dspPort,
- CFStringRef propertyName) {
- return IORegistryEntrySearchCFProperty(dspPort,
- kIOServicePlane,
- propertyName,
- kCFAllocatorDefault,
- kIORegistryIterateRecursively |
- kIORegistryIterateParents);
-}
-
-
-static void CFReleaseIf(CFTypeRef d) {
- if (d)
- CFRelease(d);
-}
-
-
-static UInt32 IntValueOfCFData(CFDataRef d) {
- UInt32 value = 0;
-
- if (d) {
- const UInt32 *vp = reinterpret_cast<const UInt32*>(CFDataGetBytePtr(d));
- if (vp != NULL)
- value = *vp;
- }
-
- return value;
-}
-
-
-static int IntValueOfCFNumber(CFNumberRef n) {
- int value = 0;
-
- if ((n != NULL) && (CFGetTypeID(n) == CFNumberGetTypeID()))
- CFNumberGetValue(n, kCFNumberSInt32Type, &value);
-
- return value;
-}
-
-
-static void GetVideoCardInfo(CGDirectDisplayID displayID,
- int *vendorID,
- int *deviceID,
- int *vramSize) {
- io_registry_entry_t dspPort = CGDisplayIOServicePort(displayID);
-
- CFTypeRef vendorIDRef = SearchPortForProperty(dspPort, CFSTR("vendor-id"));
- if (vendorID) *vendorID = IntValueOfCFData((CFDataRef)vendorIDRef);
-
- CFTypeRef deviceIDRef = SearchPortForProperty(dspPort, CFSTR("device-id"));
- if (deviceID) *deviceID = IntValueOfCFData((CFDataRef)deviceIDRef);
-
- CFTypeRef typeCodeRef = SearchPortForProperty(dspPort,
- CFSTR(kIOFBMemorySizeKey));
- if (vramSize) *vramSize = IntValueOfCFNumber((CFNumberRef)typeCodeRef);
-
- CFReleaseIf(vendorIDRef);
- CFReleaseIf(deviceIDRef);
- CFReleaseIf(typeCodeRef);
-}
-
-struct GPUInfo {
- int vendorID;
- int deviceID;
-};
-
-// A list of GPUs which we know will not work well in o3d
-// We want to fallback to using the software render for these
-GPUInfo softwareRenderList[] = {
- {0x8086, 0x2a02}, // Intel GMA X3100 Macbook
- {0x8086, 0x27a2} // Intel GMA 950 Mac Mini
-};
-
-static bool BundleFlagForcesSoftwareRenderer() {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- BundleReader *bundle = [[[BundleReader alloc] init] autorelease];
- BOOL result = [bundle boolValueForKey:@"O3DForceSoftwareRenderer"];
- [pool release];
- return result != NO;
-}
-
-bool UseSoftwareRenderer() {
- static bool use_software_renderer = false;
- static bool is_initialized = false;
-
- if (!is_initialized) {
- if (BundleFlagForcesSoftwareRenderer()) {
- use_software_renderer = true;
- } else {
- int vendorID;
- int deviceID;
- GetVideoCardInfo(kCGDirectMainDisplay,
- &vendorID,
- &deviceID,
- NULL);
-
- use_software_renderer = false;
- int list_count = arraysize(softwareRenderList);
- for (int i = 0; i < list_count; ++i) {
- GPUInfo &softwareRenderInfo = softwareRenderList[i];
- if (vendorID == softwareRenderInfo.vendorID
- && deviceID == softwareRenderInfo.deviceID) {
- use_software_renderer = true;
- break;
- }
- }
- }
- is_initialized = true;
- }
-
- return use_software_renderer || Renderer::IsForceSoftwareRenderer();
-}
-
-static bool GetVideoCardMetrics(CGDirectDisplayID displayID) {
- int vendorID;
- int deviceID;
- int vramSize;
- GetVideoCardInfo(displayID,
- &vendorID,
- &deviceID,
- &vramSize);
-
- o3d::metric_gpu_vendor_id = vendorID;
- o3d::metric_gpu_device_id = deviceID;
- o3d::metric_gpu_vram_size = vramSize;
-
- return true;
-}
-
-
-// Return a pointer to the last character with value c in string s.
-// Returns NULL if c is not found.
-static char* FindLastChar(char *s, char c) {
- char *s_found = NULL;
-
- while (*s != '\0') {
- if (*s == c)
- s_found = s;
- s++;
- }
-
- return s_found;
-}
-
-
-bool GetOpenGLMetrics() {
- char *gl_version_string = (char*)glGetString(GL_VERSION);
- char *gl_extensions_string = (char*)glGetString(GL_EXTENSIONS);
-
- if ((gl_version_string == NULL) || (gl_extensions_string == NULL))
- return false;
-
- // Get the OpenGL version from the start of the string.
- int gl_major = 0, gl_minor = 0;
- sscanf(gl_version_string, "%u.%u", &gl_major, &gl_minor);
- o3d::metric_gl_major_version = gl_major;
- o3d::metric_gl_minor_version = gl_minor;
-
- // Get the OpenGL driver version.
- // This bit is Mac specific - Mac OpenGL drivers have the driver version
- // at the end of the gl version string preceded by a dash.
- char *s = FindLastChar(gl_version_string, '-');
- if (s) {
- char *driver_string = s + 1; // skip '-'
- int driver_major = 0, driver_minor = 0, driver_bugfix = 0;
- sscanf(driver_string, "%u.%u.%u",
- &driver_major, &driver_minor, &driver_bugfix);
- o3d::metric_gpu_driver_major_version = driver_major;
- o3d::metric_gpu_driver_minor_version = driver_minor;
- o3d::metric_gpu_driver_bugfix_version = driver_bugfix;
- }
-
- // Get the HLSL version.
- // On OpenGL 1.x it's 1.0 if the GL_ARB_shading_language_100 extension is
- // present.
- // On OpenGL 2.x it's a matter of getting the GL_SHADING_LANGUAGE_VERSION
- // string.
- int gl_hlsl_major = 0, gl_hlsl_minor = 0;
- if ((gl_major == 1) &&
- strstr(gl_extensions_string, "GL_ARB_shading_language_100")) {
- gl_hlsl_major = 1;
- gl_hlsl_minor = 0;
- } else if (gl_major >= 2) {
- char* glsl_version_string = (char*)glGetString(GL_SHADING_LANGUAGE_VERSION);
- if (glsl_version_string) {
- sscanf(glsl_version_string, "%u.%u", &gl_hlsl_major, &gl_hlsl_minor);
- }
- }
- o3d::metric_gl_hlsl_major_version = gl_hlsl_major;
- o3d::metric_gl_hlsl_minor_version = gl_hlsl_minor;
-
- return true;
-}
-
-
-bool GetUserConfigMetrics() {
- // Check Mac version.
- o3d::metric_system_type = o3d::SYSTEM_NAME_MAC;
-
- SInt32 major = 0, minor = 0, bugfix = 0;
-
- Gestalt(gestaltSystemVersionMajor, &major);
- Gestalt(gestaltSystemVersionMinor, &minor);
- Gestalt(gestaltSystemVersionBugFix, &bugfix);
-
- o3d::metric_mac_major_version = major; // eg 10
- o3d::metric_mac_minor_version = minor; // eg 5
- o3d::metric_mac_bugfix_version = bugfix; // eg 6
-
- o3d::metric_direct3d_available.Set(false);
-
- GetVideoCardMetrics(kCGDirectMainDisplay);
-
- return true;
-}
-
-
-bool GetUserAgentMetrics(NPP npp) {
- // Check User agent so we can get the browser
- // TODO: This is the best we could come up with for this in order to
- // go from browser to string.
- GLUE_PROFILE_START(npp, "uagent");
- std::string user_agent = NPN_UserAgent(npp);
- GLUE_PROFILE_STOP(npp, "uagent");
- // The Chrome user_agent string also contains Safari. Search for Chrome first.
- if (std::string::npos != user_agent.find("Chrome")) {
- o3d::metric_browser_type = o3d::BROWSER_NAME_CHROME;
- // The OmniWeb user_agent also contains Safari. Search for OmniWeb first.
- } else if (std::string::npos != user_agent.find("OmniWeb")) {
- o3d::metric_browser_type = o3d::BROWSER_NAME_OMNIWEB;
- // Now we can safely look for Safari.
- } else if (std::string::npos != user_agent.find("Safari")) {
- o3d::metric_browser_type = o3d::BROWSER_NAME_SAFARI;
- } else if (std::string::npos != user_agent.find("Opera")) {
- o3d::metric_browser_type = o3d::BROWSER_NAME_OPERA;
- } else if (std::string::npos != user_agent.find("Firefox")) {
- o3d::metric_browser_type = o3d::BROWSER_NAME_FIREFOX;
- } else if (std::string::npos != user_agent.find("MSIE")) {
- o3d::metric_browser_type = o3d::BROWSER_NAME_MSIE;
- } else if (std::string::npos != user_agent.find("Camino")) {
- o3d::metric_browser_type = o3d::BROWSER_NAME_CAMINO;
- } else {
- o3d::metric_browser_type = o3d::BROWSER_NAME_UNKNOWN;
- }
-
- int browser_major = 0, browser_minor = 0, browser_bugfix = 0;
- if (GetBrowserVersionInfo(&browser_major, &browser_minor, &browser_bugfix)) {
- o3d::metric_browser_major_version = browser_major;
- o3d::metric_browser_minor_version = browser_minor;
- o3d::metric_browser_bugfix_version = browser_bugfix;
- }
-
- return true;
-}
-
-} // namespace o3d
diff --git a/o3d/plugin/mac/fullscreen_window_mac.h b/o3d/plugin/mac/fullscreen_window_mac.h
deleted file mode 100644
index 61cd840..0000000
--- a/o3d/plugin/mac/fullscreen_window_mac.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright 2010, 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_PLUGIN_MAC_FULLSCREEN_WINDOW_MAC_H_
-#define O3D_PLUGIN_MAC_FULLSCREEN_WINDOW_MAC_H_
-
-#include <OpenGL/OpenGL.h>
-
-#include "base/basictypes.h"
-#include "base/scoped_ptr.h"
-
-#include "plugin/mac/overlay_window_mac.h"
-
-// Abstract base class for the full-screen window. Provides the
-// ability to easily choose between Carbon and Cocoa implementations.
-
-namespace glue {
-namespace _o3d {
-class PluginObject;
-} // namespace _o3d
-} // namespace glue
-
-namespace o3d {
-
-class FullscreenWindowMac {
- public:
- static FullscreenWindowMac* Create(glue::_o3d::PluginObject* obj,
- int target_width,
- int target_height);
- virtual ~FullscreenWindowMac();
-
- virtual bool Initialize(int target_width,
- int target_height);
- virtual void IdleCallback();
- virtual bool Shutdown(const GLint* last_buffer_rect);
-
- virtual CGRect GetWindowBounds() const = 0;
- virtual bool IsActive() const = 0;
- virtual void PrepareToRender() const = 0;
- virtual void FinishRendering() const = 0;
-
- protected:
- FullscreenWindowMac() {}
-
- private:
-#ifdef O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
- scoped_ptr<OverlayWindowMac> overlay_window_;
-#endif
-
- DISALLOW_COPY_AND_ASSIGN(FullscreenWindowMac);
-};
-
-} // namespace o3d
-
-#endif // O3D_PLUGIN_MAC_FULLSCREEN_WINDOW_MAC_H_
-
diff --git a/o3d/plugin/mac/fullscreen_window_mac.mm b/o3d/plugin/mac/fullscreen_window_mac.mm
deleted file mode 100644
index cc5f26d..0000000
--- a/o3d/plugin/mac/fullscreen_window_mac.mm
+++ /dev/null
@@ -1,702 +0,0 @@
-/*
- * Copyright 2010, 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 "fullscreen_window_mac.h"
-
-#include <AppKit/NSEvent.h>
-#include <Cocoa/Cocoa.h>
-#include <QuickTime/QuickTime.h>
-
-#import "graphics_utils_mac.h"
-#import "overlay_window_mac.h"
-#import "plugin_mac.h"
-#import "base/cocoa_protocols_mac.h"
-#import "base/logging.h"
-#import "base/scoped_nsobject.h"
-#import "core/cross/display_mode.h"
-#import "plugin/cross/o3d_glue.h"
-#import "plugin/mac/graphics_utils_mac.h"
-
-using glue::_o3d::PluginObject;
-
-namespace o3d {
-
-//----------------------------------------------------------------------
-// Carbon full-screen implementation.
-//
-
-// Convenience function for fetching SInt32 parameters from Carbon EventRefs.
-static SInt32 GetIntEventParam(EventRef inEvent, EventParamName inName) {
- SInt32 value = 0;
- return (GetEventParameter(inEvent, inName, typeSInt32, NULL, sizeof(value),
- NULL, &value) == noErr) ? value : 0;
-}
-
-
-// Maps the MacOS button numbers to the constants used by our
-// event mechanism. Not quite as obvious as you might think, as the Mac
-// thinks the numbering should go left, right, middle and our W3C-influenced
-// system goes left, middle, right.
-// Defaults to left-button if passed a strange value. Pass Cocoa mouse button
-// codes as-is (they start at 0), pass Carbon button codes - 1.
-o3d::Event::Button MacOSMouseButtonNumberToO3DButton(int inButton) {
-
- switch(inButton) {
- case 0:
- return o3d::Event::BUTTON_LEFT;
- case 1:
- return o3d::Event::BUTTON_RIGHT;
- case 2:
- return o3d::Event::BUTTON_MIDDLE;
- case 3:
- return o3d::Event::BUTTON_4;
- case 4:
- return o3d::Event::BUTTON_5;
- }
-
- return o3d::Event::BUTTON_LEFT;
-}
-
-
-// Handles the CarbonEvents that we get sent for the fullscreen mode window.
-// Most of these can be converted to EventRecord events and handled by the
-// HandleCarbonEvent() function in main_mac.mm, but some have no equivalent in
-// that space, scroll-wheel events for example, and so must be handled here.
-static OSStatus HandleFullscreenWindow(EventHandlerCallRef inHandlerCallRef,
- EventRef inEvent,
- void *inUserData) {
- OSType event_class = GetEventClass(inEvent);
- OSType event_kind = GetEventKind(inEvent);
- NPP instance = (NPP)inUserData;
- PluginObject* obj = (PluginObject*)(instance->pdata);
- HIPoint mouse_loc = { 0.0, 0.0 };
- bool is_scroll_event = event_class == kEventClassMouse &&
- (event_kind == kEventMouseScroll ||
- event_kind == kEventMouseWheelMoved);
-
- // If it's any kind of mouse event, get the global mouse loc.
- if (event_class == kEventClassMouse) {
- GetEventParameter(inEvent, kEventParamMouseLocation,
- typeHIPoint, NULL,
- sizeof(mouse_loc), NULL,
- &mouse_loc);
- }
-
- // Handle the two kinds of scroll message we understand.
- if (is_scroll_event) {
- SInt32 x_scroll = 0;
- SInt32 y_scroll = 0;
- EventMouseWheelAxis axis = kEventMouseWheelAxisY;
-
- switch (event_kind) {
- // The newer kind of scroll event, as sent when two-finger
- // dragging on a touchpad.
- case kEventMouseScroll:
- x_scroll = GetIntEventParam(inEvent,
- kEventParamMouseWheelSmoothHorizontalDelta);
- y_scroll = GetIntEventParam(inEvent,
- kEventParamMouseWheelSmoothVerticalDelta);
-
- // only pass x or y value - pass whichever is larger
- if (x_scroll && y_scroll) {
- if (abs(x_scroll) > abs(y_scroll))
- y_scroll = 0;
- else
- x_scroll = 0;
- }
- break;
- // The older kind of scroll event, as sent when using the wheel on
- // a third-party mouse.
- case kEventMouseWheelMoved:
- GetEventParameter(inEvent, kEventParamMouseWheelAxis,
- typeMouseWheelAxis, NULL,
- sizeof(axis), NULL,
- &axis);
-
- if (axis == kEventMouseWheelAxisY) {
- y_scroll = GetIntEventParam(inEvent,
- kEventParamMouseWheelDelta);
- } else {
- x_scroll = GetIntEventParam(inEvent,
- kEventParamMouseWheelDelta);
- }
- break;
- }
-
- // Dispatch the event now that we have all the data.
- if (x_scroll || y_scroll) {
- o3d::Event event(o3d::Event::TYPE_WHEEL);
- event.set_delta(x_scroll, y_scroll);
- // Global and local locs are the same, in this case,
- // as we have a fullscreen window at 0,0.
- event.set_position(mouse_loc.x, mouse_loc.y,
- mouse_loc.x, mouse_loc.y, true);
- obj->client()->AddEventToQueue(event);
- }
- return noErr;
- } else if (event_class == kEventClassMouse &&
- (event_kind == kEventMouseDown || event_kind == kEventMouseUp)) {
-
- o3d::Event::Type type = (event_kind == kEventMouseDown) ?
- o3d::Event::TYPE_MOUSEDOWN :
- o3d::Event::TYPE_MOUSEUP;
- o3d::Event event(type);
- event.set_position(mouse_loc.x, mouse_loc.y,
- mouse_loc.x, mouse_loc.y, true);
-
- EventMouseButton button = 0;
- GetEventParameter(inEvent, kEventParamMouseButton,
- typeMouseButton, NULL,
- sizeof(button), NULL,
- &button);
- // Carbon mouse button numbers start at 1, so subtract 1 here -
- // Cocoa mouse buttons, by contrast, start at 0).
- event.set_button(MacOSMouseButtonNumberToO3DButton(button - 1));
-
- // add the modifiers to the event, if any
- UInt32 carbonMods = GetIntEventParam(inEvent,
- kEventParamKeyModifiers);
- if (carbonMods) {
- int modifier_state = 0;
- if (carbonMods & controlKey) {
- modifier_state |= o3d::Event::MODIFIER_CTRL;
- }
- if (carbonMods & shiftKey) {
- modifier_state |= o3d::Event::MODIFIER_SHIFT;
- }
- if (carbonMods & optionKey) {
- modifier_state |= o3d::Event::MODIFIER_ALT;
- }
- if (carbonMods & cmdKey) {
- modifier_state |= o3d::Event::MODIFIER_META;
- }
-
- event.set_modifier_state(modifier_state);
- }
-
- obj->client()->AddEventToQueue(event);
- } else { // not a scroll event or a click
-
- // All other events are currently handled by being converted to an
- // old-style EventRecord as passed by the classic NPAPI interface
- // and dispatched through our common routine.
- EventRecord eventRecord;
-
- if (ConvertEventRefToEventRecord(inEvent, &eventRecord)) {
- HandleCarbonEvent(&eventRecord, (NPP)inUserData);
- return noErr;
- } else {
- return eventNotHandledErr;
- }
- }
- return noErr;
-}
-
-
-static WindowRef CreateFullscreenWindow(WindowRef window,
- PluginObject *obj) {
- Rect bounds = CGRect2Rect(CGDisplayBounds(CGMainDisplayID()));
- OSStatus err = noErr;
- EventTypeSpec eventTypes[] = {
- {kEventClassKeyboard, kEventRawKeyDown},
- {kEventClassKeyboard, kEventRawKeyRepeat},
- {kEventClassKeyboard, kEventRawKeyUp},
- {kEventClassMouse, kEventMouseDown},
- {kEventClassMouse, kEventMouseUp},
- {kEventClassMouse, kEventMouseMoved},
- {kEventClassMouse, kEventMouseDragged},
- {kEventClassMouse, kEventMouseScroll},
- {kEventClassMouse, kEventMouseWheelMoved}
- };
-
- if (window == NULL)
- err = CreateNewWindow(kSimpleWindowClass,
- kWindowStandardHandlerAttribute,
- &bounds,
- &window);
- if (err)
- return NULL;
-
- SetWindowLevel(window, CGShieldingWindowLevel() + 1);
-
- InstallEventHandler(GetWindowEventTarget(window), HandleFullscreenWindow,
- sizeof(eventTypes)/sizeof(eventTypes[0]), eventTypes,
- obj->npp(), NULL);
- ShowWindow(window);
- return window;
-}
-
-class CarbonFullscreenWindowMac : public FullscreenWindowMac {
- public:
- CarbonFullscreenWindowMac(PluginObject* obj);
- virtual ~CarbonFullscreenWindowMac();
-
- virtual bool Initialize(int target_width, int target_height);
- virtual bool Shutdown(const GLint* last_buffer_rect);
- virtual CGRect GetWindowBounds() const;
- virtual bool IsActive() const;
- virtual void PrepareToRender() const;
- virtual void FinishRendering() const;
-
- private:
- PluginObject* obj_;
- WindowRef fullscreen_window_;
- Ptr fullscreen_state_;
-
- DISALLOW_COPY_AND_ASSIGN(CarbonFullscreenWindowMac);
-};
-
-CarbonFullscreenWindowMac::CarbonFullscreenWindowMac(PluginObject* obj)
- : obj_(obj),
- fullscreen_window_(NULL),
- fullscreen_state_(NULL) {
-}
-
-CarbonFullscreenWindowMac::~CarbonFullscreenWindowMac() {
-}
-
-bool CarbonFullscreenWindowMac::Initialize(int target_width,
- int target_height) {
- // check which mode we are in now
- o3d::DisplayMode current_mode;
- GetCurrentDisplayMode(&current_mode);
-
- WindowRef temp_window = NULL;
-
- // Determine if screen mode switching is actually required.
- if (target_width != 0 &&
- target_height != 0 &&
- target_width != current_mode.width() &&
- target_height != current_mode.height()) {
- short short_target_width = target_width;
- short short_target_height = target_height;
- BeginFullScreen(&fullscreen_state_,
- nil, // Value of nil selects the main screen.
- &short_target_width,
- &short_target_height,
- &temp_window,
- NULL,
- fullScreenCaptureAllDisplays);
- } else {
- SetSystemUIMode(kUIModeAllSuppressed, kUIOptionAutoShowMenuBar);
- fullscreen_state_ = NULL;
- }
-
- fullscreen_window_ = CreateFullscreenWindow(NULL, obj_);
- SetWindowForAGLContext(obj_->GetMacAGLContext(), fullscreen_window_);
- aglDisable(obj_->GetMacAGLContext(), AGL_BUFFER_RECT);
- // This must be done after all of the above setup in order for the
- // overlay window to appear on top.
- FullscreenWindowMac::Initialize(target_width, target_height);
- return true;
-}
-
-bool CarbonFullscreenWindowMac::Shutdown(const GLint* last_buffer_rect) {
- FullscreenWindowMac::Shutdown(last_buffer_rect);
- SetWindowForAGLContext(obj_->GetMacAGLContext(), obj_->GetMacWindow());
- aglSetInteger(obj_->GetMacAGLContext(), AGL_BUFFER_RECT, last_buffer_rect);
- aglEnable(obj_->GetMacAGLContext(), AGL_BUFFER_RECT);
- if (fullscreen_window_) {
- HideWindow(fullscreen_window_);
- ReleaseWindowGroup(GetWindowGroup(fullscreen_window_));
- DisposeWindow(fullscreen_window_);
- fullscreen_window_ = NULL;
- }
- if (fullscreen_state_) {
- EndFullScreen(fullscreen_state_, 0);
- fullscreen_state_ = NULL;
- } else {
- SetSystemUIMode(kUIModeNormal, 0);
- }
- return true;
-}
-
-CGRect CarbonFullscreenWindowMac::GetWindowBounds() const {
- Rect bounds = {0,0,0,0};
- ::GetWindowBounds(fullscreen_window_, kWindowContentRgn, &bounds);
- return Rect2CGRect(bounds);
-}
-
-bool CarbonFullscreenWindowMac::IsActive() const {
- return fullscreen_window_ == ActiveNonFloatingWindow();
-}
-
-void CarbonFullscreenWindowMac::PrepareToRender() const {
- // Nothing needs to be done here; the AGL context used to render
- // into the plugin region is reused for rendering into the
- // full-screen window.
-}
-
-void CarbonFullscreenWindowMac::FinishRendering() const {
-}
-
-//----------------------------------------------------------------------
-// Cocoa full-screen implementation.
-//
-
-class CocoaFullscreenWindowMac;
-
-} // namespace o3d
-
-using o3d::CocoaFullscreenWindowMac;
-
-@interface O3DFullscreenView : NSView {
-}
-
-- (void)rightMouseDown:(NSEvent*)theEvent;
-
-@end
-
-@interface O3DFullscreenWindow : NSWindow<NSWindowDelegate> {
- CocoaFullscreenWindowMac* owner_;
-}
-
-- (id)initWithOwner:(CocoaFullscreenWindowMac*)owner;
-
-@end
-
-namespace o3d {
-
-class CocoaFullscreenWindowMac : public FullscreenWindowMac {
- public:
- CocoaFullscreenWindowMac(PluginObject* obj);
- virtual ~CocoaFullscreenWindowMac();
-
- virtual bool Initialize(int target_width, int target_height);
- virtual bool Shutdown(const GLint* last_buffer_rect);
- virtual CGRect GetWindowBounds() const;
- virtual bool IsActive() const;
- virtual void PrepareToRender() const;
- virtual void FinishRendering() const;
-
- void DispatchKeyEvent(NPCocoaEventType kind,
- NSEvent* event);
- void DispatchMouseEvent(NPCocoaEventType kind,
- NSEvent* event);
- void DispatchFocusLostEvent();
-
- private:
- PluginObject* obj_;
- // The CGL context with which the plugin was previously rendering.
- CGLContextObj saved_cgl_context_;
- // This must not be a scoped_nsobject. AppKit must have
- // responsibility for releasing this object to prevent it from being
- // deleted in the middle of a focus transfer.
- O3DFullscreenWindow* window_;
- scoped_nsobject<O3DFullscreenView> view_;
- NSOpenGLContext* context_;
- // State bit indicating whether we are still in the process of going
- // full-screen.
- mutable bool going_fullscreen_;
-
- DISALLOW_COPY_AND_ASSIGN(CocoaFullscreenWindowMac);
-};
-
-} // namespace o3d
-
-@implementation O3DFullscreenView
-- (void)rightMouseDown:(NSEvent*)event {
- // Needed to forward right mouse button events.
- NSResponder* next = [self nextResponder];
- if (next != nil) {
- [next rightMouseDown:event];
- }
-}
-@end
-
-@implementation O3DFullscreenWindow
-- (id) initWithOwner:(CocoaFullscreenWindowMac*)owner {
- // The screen containing the menu bar is always index 0 in the
- // screens array. We could also consider taking the screen with the
- // focus fullscreen; this is the result of [NSScreen mainScreen].
- NSScreen* mainScreen = [[NSScreen screens] objectAtIndex:0];
-
- self = [super initWithContentRect:[mainScreen frame]
- styleMask:NSBorderlessWindowMask
- backing:NSBackingStoreBuffered
- defer:NO
- screen:mainScreen];
- if (self) {
- owner_ = owner;
- [self setAcceptsMouseMovedEvents:YES];
- // We need to set ourselves as the delegate in order to receive
- // focus changed notifications.
- [self setDelegate:self];
- }
- return self;
-}
-
-- (BOOL)canBecomeKeyWindow {
- // Needed to receive keyboard events.
- return YES;
-}
-
-- (void)keyDown:(NSEvent*)event {
- owner_->DispatchKeyEvent(NPCocoaEventKeyDown, event);
-}
-
-- (void)keyUp:(NSEvent*)event {
- owner_->DispatchKeyEvent(NPCocoaEventKeyUp, event);
-}
-
-- (void)mouseDown:(NSEvent*)event {
- owner_->DispatchMouseEvent(NPCocoaEventMouseDown, event);
-}
-
-- (void)mouseDragged:(NSEvent*)event {
- owner_->DispatchMouseEvent(NPCocoaEventMouseDragged, event);
-}
-
-- (void)mouseEntered:(NSEvent*)event {
- owner_->DispatchMouseEvent(NPCocoaEventMouseEntered, event);
-}
-
-- (void)mouseExited:(NSEvent*)event {
- owner_->DispatchMouseEvent(NPCocoaEventMouseExited, event);
-}
-
-- (void)mouseMoved:(NSEvent*)event {
- owner_->DispatchMouseEvent(NPCocoaEventMouseMoved, event);
-}
-
-- (void)mouseUp:(NSEvent*)event {
- owner_->DispatchMouseEvent(NPCocoaEventMouseUp, event);
-}
-
-- (void)rightMouseDown:(NSEvent*)event {
- owner_->DispatchMouseEvent(NPCocoaEventMouseDown, event);
-}
-
-- (void)rightMouseDragged:(NSEvent*)event {
- owner_->DispatchMouseEvent(NPCocoaEventMouseDragged, event);
-}
-
-- (void)rightMouseUp:(NSEvent*)event {
- owner_->DispatchMouseEvent(NPCocoaEventMouseUp, event);
-}
-
-- (void)otherMouseDown:(NSEvent*)event {
- owner_->DispatchMouseEvent(NPCocoaEventMouseDown, event);
-}
-
-- (void)otherMouseDragged:(NSEvent*)event {
- owner_->DispatchMouseEvent(NPCocoaEventMouseDragged, event);
-}
-
-- (void)otherMouseUp:(NSEvent*)event {
- owner_->DispatchMouseEvent(NPCocoaEventMouseUp, event);
-}
-
-- (void)windowDidResignKey:(NSNotification*)notification {
- owner_->DispatchFocusLostEvent();
-}
-
-- (void)windowDidResignMain:(NSNotification*)notification {
- owner_->DispatchFocusLostEvent();
-}
-
-@end
-
-namespace o3d {
-
-CocoaFullscreenWindowMac::CocoaFullscreenWindowMac(PluginObject* obj)
- : obj_(obj),
- saved_cgl_context_(NULL),
- window_(nil),
- going_fullscreen_(false) {
-}
-
-CocoaFullscreenWindowMac::~CocoaFullscreenWindowMac() {
-}
-
-bool CocoaFullscreenWindowMac::Initialize(int target_width,
- int target_height) {
- window_ = [[O3DFullscreenWindow alloc] initWithOwner: this];
- if (window_ == nil) {
- return false;
- }
- [window_ setLevel:NSMainMenuWindowLevel+1];
- [window_ setOpaque:YES];
- view_.reset([[O3DFullscreenView alloc] init]);
- [window_ setContentView:view_];
-
- // Fetch the NSOpenGLContext which was created earlier and which
- // shares resources with the already-created CGLContextObj.
- context_ = (NSOpenGLContext*) obj_->GetFullscreenNSOpenGLContext();
- [context_ setView:view_];
- // We need to make the plugin think we are rendering directly with
- // the CGLContextObj underneath the NSOpenGLContext, because the
- // renderer uses CGLSetCurrentContext directly when preparing to
- // render. This should be a no-op because we already make the
- // wrapper NSOpenGLContext current in PrepareToRender.
- saved_cgl_context_ = obj_->GetMacCGLContext();
- obj_->SetMacCGLContext((CGLContextObj) [context_ CGLContextObj]);
- [window_ makeKeyAndOrderFront:window_];
- FullscreenWindowMac::Initialize(target_width, target_height);
- going_fullscreen_ = true;
- return true;
-}
-
-bool CocoaFullscreenWindowMac::Shutdown(const GLint* last_buffer_rect) {
- if (saved_cgl_context_) {
- obj_->SetMacCGLContext(saved_cgl_context_);
- saved_cgl_context_ = NULL;
- }
- [NSOpenGLContext clearCurrentContext];
- if (context_) {
- [context_ clearDrawable];
- context_ = nil;
- }
- if (window_) {
- [window_ close];
- window_ = nil;
- }
- view_.reset();
- return true;
-}
-
-CGRect CocoaFullscreenWindowMac::GetWindowBounds() const {
- NSRect frame = [window_ frame];
- return CGRectMake(frame.origin.x, frame.origin.y,
- frame.size.width, frame.size.height);
-}
-
-bool CocoaFullscreenWindowMac::IsActive() const {
- if (going_fullscreen_)
- return true;
- return [window_ isKeyWindow] && [window_ isMainWindow];
-}
-
-void CocoaFullscreenWindowMac::PrepareToRender() const {
- [context_ update];
- [context_ makeCurrentContext];
- going_fullscreen_ = false;
-}
-
-void CocoaFullscreenWindowMac::FinishRendering() const {
- [context_ flushBuffer];
-}
-
-void CocoaFullscreenWindowMac::DispatchKeyEvent(NPCocoaEventType kind,
- NSEvent* event) {
- NPCocoaEvent cocoa_event;
- memset(&cocoa_event, 0, sizeof(cocoa_event));
- // We need to dispatch events through HandleCocoaEvent in order for
- // the escape key to disable full-screen, for example.
- cocoa_event.type = kind;
- cocoa_event.data.key.modifierFlags = [event modifierFlags];
- cocoa_event.data.key.characters = (NPNSString*) [event characters];
- cocoa_event.data.key.charactersIgnoringModifiers =
- (NPNSString*) [event charactersIgnoringModifiers];
- cocoa_event.data.key.isARepeat = [event isARepeat];
- cocoa_event.data.key.keyCode = [event keyCode];
- HandleCocoaEvent(obj_->npp(), &cocoa_event, false);
-}
-
-void CocoaFullscreenWindowMac::DispatchMouseEvent(NPCocoaEventType kind,
- NSEvent* event) {
- NPCocoaEvent cocoa_event;
- memset(&cocoa_event, 0, sizeof(cocoa_event));
- cocoa_event.type = kind;
- cocoa_event.data.mouse.modifierFlags = [event modifierFlags];
- NSPoint location = [event locationInWindow];
- cocoa_event.data.mouse.pluginX = location.x;
- // We must transform the Y origin to the upper left.
- NSRect frame = [window_ frame];
- cocoa_event.data.mouse.pluginY = frame.size.height - location.y;
- cocoa_event.data.mouse.buttonNumber = [event buttonNumber];
- cocoa_event.data.mouse.clickCount = [event clickCount];
- cocoa_event.data.mouse.deltaX = [event deltaX];
- cocoa_event.data.mouse.deltaY = [event deltaY];
- cocoa_event.data.mouse.deltaZ = [event deltaZ];
- HandleCocoaEvent(obj_->npp(), &cocoa_event, false);
-}
-
-void CocoaFullscreenWindowMac::DispatchFocusLostEvent() {
- NPCocoaEvent cocoa_event;
- memset(&cocoa_event, 0, sizeof(cocoa_event));
- cocoa_event.type = NPCocoaEventFocusChanged;
- // cocoa_event.data.focus.hasFocus is already false.
- // We aren't testing this in HandleCocoaEvent anyway.
- HandleCocoaEvent(obj_->npp(), &cocoa_event, false);
-}
-
-//----------------------------------------------------------------------
-// FullscreenWindowMac implementation.
-//
-
-FullscreenWindowMac* FullscreenWindowMac::Create(
- glue::_o3d::PluginObject* obj,
- int target_width,
- int target_height) {
- FullscreenWindowMac* window = NULL;
- if (obj->GetMacAGLContext()) {
- DLOG(INFO) << "Using Carbon full-screen code.";
- window = new CarbonFullscreenWindowMac(obj);
- } else if (obj->GetMacCGLContext()) {
- DLOG(INFO) << "Using Cocoa full-screen code.";
- window = new CocoaFullscreenWindowMac(obj);
- }
- if (window && !window->Initialize(target_width, target_height)) {
- delete window;
- window = NULL;
- }
-
- return window;
-}
-
-FullscreenWindowMac::~FullscreenWindowMac() {
-}
-
-bool FullscreenWindowMac::Initialize(int target_width, int target_height) {
-#ifdef O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
- overlay_window_.reset(new OverlayWindowMac());
-#endif
- return true;
-}
-
-void FullscreenWindowMac::IdleCallback() {
-#ifdef O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
- if (overlay_window_.get()) {
- overlay_window_->IdleCallback();
- }
-#endif
-}
-
-bool FullscreenWindowMac::Shutdown(const GLint* last_buffer_rect) {
-#ifdef O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
- overlay_window_.reset();
-#endif
- return true;
-}
-
-} // namespace o3d
-
diff --git a/o3d/plugin/mac/graphics_utils_mac.h b/o3d/plugin/mac/graphics_utils_mac.h
deleted file mode 100644
index bfa408c..0000000
--- a/o3d/plugin/mac/graphics_utils_mac.h
+++ /dev/null
@@ -1,62 +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_PLUGIN_MAC_GRAPHICS_UTILS_MAC_H_
-#define O3D_PLUGIN_MAC_GRAPHICS_UTILS_MAC_H_
-
-#include <Carbon/Carbon.h>
-#include <Cocoa/Cocoa.h>
-#include <AGL/agl.h>
-
-namespace o3d {
-
-void SlideWindowToRect(WindowRef the_window,
- CGRect destination_rect,
- double transition_duration_seconds);
-
-void SetWindowLevel(WindowRef window, int level);
-
-bool SetWindowForAGLContext(AGLContext context, WindowRef window);
-
-bool IsMacOSTenFiveOrHigher();
-
-bool IsMacOSTenSixOrHigher();
-
-Rect CGRect2Rect(const CGRect &inRect);
-
-CGRect Rect2CGRect(const Rect &inRect);
-
-void PaintRoundedCGRect(CGContextRef context, CGRect rect,
- float radius, bool fill);
-
-} // namespace o3d
-
-#endif // O3D_PLUGIN_MAC_GRAPHICS_UTILS_MAC_H_
diff --git a/o3d/plugin/mac/graphics_utils_mac.mm b/o3d/plugin/mac/graphics_utils_mac.mm
deleted file mode 100644
index ee1aa3f..0000000
--- a/o3d/plugin/mac/graphics_utils_mac.mm
+++ /dev/null
@@ -1,150 +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 "plugin/mac/graphics_utils_mac.h"
-
-namespace o3d {
-
-// Slide a window to a different rect, asynchronously, over a period of time.
-void SlideWindowToRect(WindowRef the_window,
- CGRect destination_rect,
- double transition_duration_seconds) {
- TransitionWindowOptions options = {0, transition_duration_seconds,
- NULL, NULL};
- TransitionWindowWithOptions(the_window,
- kWindowSlideTransitionEffect,
- kWindowMoveTransitionAction,
- &destination_rect, true, &options);
-}
-
-// Sets a Carbon window to a custom window level, by creating a new window
-// group at that level and adding the window to the group.
-void SetWindowLevel(WindowRef window, int level) {
- WindowGroupRef wGroup = NULL;
- WindowGroupAttributes attrs = 0;
- CreateWindowGroup(attrs, &wGroup);
- SetWindowGroupLevel(wGroup, level);
- SetWindowGroup(window, wGroup);
-}
-
-
-// Given a WindowRef and an AGLContext, make the context draw in that window.
-// Return Value: true if the window is successfully set, false otherwise.
-bool SetWindowForAGLContext(AGLContext context, WindowRef window) {
- return (IsMacOSTenFiveOrHigher()) ?
- aglSetWindowRef(context, window) :
- aglSetDrawable(context, GetWindowPort(window));
-}
-
-
-// Returns whether OS is 10.5 (Leopard) or higher.
-bool IsMacOSTenFiveOrHigher() {
- static bool isCached = false, result = false;
-
- if (!isCached) {
- SInt32 major = 0;
- SInt32 minor = 0;
- // These selectors don't exist pre 10.4 but as we check the error
- // the function will correctly return NO which is the right answer.
- result = ((::Gestalt(gestaltSystemVersionMajor, &major) == noErr) &&
- (::Gestalt(gestaltSystemVersionMinor, &minor) == noErr) &&
- ((major > 10) || (major == 10 && minor >= 5)));
- isCached = true;
- }
- return result;
-}
-
-// Returns whether OS is 10.6 (Snow Leopard) or higher.
-bool IsMacOSTenSixOrHigher() {
- static bool isCached = false, result = false;
-
- if (!isCached) {
- SInt32 major = 0;
- SInt32 minor = 0;
- // These selectors don't exist pre 10.4 but as we check the error
- // the function will correctly return NO which is the right answer.
- result = ((::Gestalt(gestaltSystemVersionMajor, &major) == noErr) &&
- (::Gestalt(gestaltSystemVersionMinor, &minor) == noErr) &&
- ((major > 10) || (major == 10 && minor >= 6)));
- isCached = true;
- }
- return result;
-}
-
-Rect CGRect2Rect(const CGRect &inRect) {
- Rect outRect;
- outRect.left = inRect.origin.x;
- outRect.top = inRect.origin.y;
- outRect.right = inRect.origin.x + inRect.size.width;
- outRect.bottom = inRect.origin.y + inRect.size.height;
- return outRect;
-}
-
-
-CGRect Rect2CGRect(const Rect &inRect) {
- CGRect outRect;
- outRect.origin.x = inRect.left;
- outRect.origin.y = inRect.top;
- outRect.size.width = inRect.right - inRect.left;
- outRect.size.height = inRect.bottom - inRect.top;
- return outRect;
-}
-
-
-// Paint a round rect, with the corner radius you specify, either filled or
-// stroked.
-void PaintRoundedCGRect(CGContextRef context,
- CGRect rect,
- float radius,
- bool fill) {
- CGFloat lx = CGRectGetMinX(rect);
- CGFloat cx = CGRectGetMidX(rect);
- CGFloat rx = CGRectGetMaxX(rect);
- CGFloat by = CGRectGetMinY(rect);
- CGFloat cy = CGRectGetMidY(rect);
- CGFloat ty = CGRectGetMaxY(rect);
-
- CGContextBeginPath(context);
- CGContextMoveToPoint(context, lx, cy);
- CGContextAddArcToPoint(context, lx, by, cx, by, radius);
- CGContextAddArcToPoint(context, rx, by, rx, cy, radius);
- CGContextAddArcToPoint(context, rx, ty, cx, ty, radius);
- CGContextAddArcToPoint(context, lx, ty, lx, cy, radius);
- CGContextClosePath(context);
-
- if (fill)
- CGContextFillPath(context);
- else
- CGContextStrokePath(context);
-}
-
-} // namespace o3d
diff --git a/o3d/plugin/mac/main_mac.mm b/o3d/plugin/mac/main_mac.mm
deleted file mode 100644
index 1d53afd..0000000
--- a/o3d/plugin/mac/main_mac.mm
+++ /dev/null
@@ -1,1347 +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 implements the platform specific parts of the plugin for
-// the Macintosh platform.
-
-#include "plugin/cross/main.h"
-
-#import <Cocoa/Cocoa.h>
-#include <Carbon/Carbon.h>
-#include <OpenGL/OpenGL.h>
-#include <AGL/agl.h>
-#include <AGL/aglRenderers.h>
-
-#include "base/logging.h"
-#include "core/cross/event.h"
-#include "core/mac/display_window_mac.h"
-#include "plugin/cross/config.h"
-#include "plugin/cross/plugin_metrics.h"
-#include "plugin/mac/plugin_mac.h"
-#include "plugin/mac/graphics_utils_mac.h"
-#include "plugin/mac/fullscreen_window_mac.h"
-#import "plugin/mac/o3d_layer.h"
-
-using glue::_o3d::PluginObject;
-using glue::StreamManager;
-using o3d::Bitmap;
-using o3d::DisplayWindowMac;
-using o3d::Event;
-using o3d::FullscreenWindowMac;
-using o3d::Renderer;
-
-namespace {
-
-#define CFTIMER
-// #define DEFERRED_DRAW_ON_NULLEVENTS
-
-
-// Helper that extracts the O3DLayer obj c object from the PluginObject
-// and coerces it to the right type. The code can't live in the PluginObject
-// since it's c++ code and doesn't know about objective c types, and it saves
-// lots of casts elsewhere in the code.
-static O3DLayer* ObjO3DLayer(PluginObject* obj) {
- return static_cast<O3DLayer*>(obj ? obj->gl_layer_ : nil);
-}
-
-void DrawPlugin(PluginObject* obj, bool send_callback, CGContextRef context) {
- obj->client()->RenderClient(send_callback);
- Renderer* renderer = obj->renderer();
- if (obj->IsOffscreenRenderingEnabled() && renderer && context) {
- DCHECK_EQ(obj->drawing_model_, NPDrawingModelCoreGraphics);
- DCHECK(obj->mac_cgl_pbuffer_);
- // We need to read back the framebuffer and draw it to the screen using
- // CoreGraphics.
- renderer->StartRendering();
- Bitmap::Ref bitmap = obj->GetOffscreenBitmap();
- obj->GetOffscreenRenderSurface()->GetIntoBitmap(bitmap);
- bitmap->FlipVertically();
- renderer->FinishRendering();
- uint8* data = bitmap->GetMipData(0);
- unsigned width = bitmap->width();
- unsigned height = bitmap->height();
- int rowBytes = width * 4;
- CGContextSaveGState(context);
-
- CGDataProviderRef dataProvider =
- CGDataProviderCreateWithData(0, data, rowBytes * height, 0);
- CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
- // We need to use kCGImageAlphaNoneSkipFirst to discard the alpha channel.
- // O3D's output is currently semantically opaque.
- CGImageRef cgImage = CGImageCreate(width,
- height,
- 8,
- 32,
- rowBytes,
- colorSpace,
- kCGImageAlphaNoneSkipFirst |
- kCGBitmapByteOrder32Host,
- dataProvider,
- 0,
- false,
- kCGRenderingIntentDefault);
- CGRect rect = CGRectMake(0, 0, width, height);
- // We want to completely overwrite the previous frame's
- // rendering results.
- CGContextSetBlendMode(context, kCGBlendModeCopy);
- CGContextSetInterpolationQuality(context, kCGInterpolationNone);
- CGContextDrawImage(context, rect, cgImage);
- CGImageRelease(cgImage);
- CGColorSpaceRelease(colorSpace);
- CGDataProviderRelease(dataProvider);
- CGContextRestoreGState(context);
- }
-}
-
-unsigned char GetMacEventKeyChar(const EventRecord *the_event) {
- unsigned char the_char = the_event->message & charCodeMask;
- return the_char;
-}
-
-unsigned char GetMacEventKeyCode(const EventRecord *the_event) {
- unsigned char the_key_code = (the_event->message & keyCodeMask) >> 8;
- return the_key_code;
-}
-
-
-// Cocoa key events for things like arrow key presses can have strange unicode
-// values in the 0xF700-0xF747 range, eg NSUpArrowFunctionKey is 0xF700.
-// These values are defined in NSEvent.h.
-// Map the ones we care about to the more commonly understood values in
-// the Mac system header Events.h, eg kUpArrowCharCode is 30.
-int TranslateMacUnicodeControlChar(int theChar) {
- switch(theChar) {
- case NSUpArrowFunctionKey:
- return kUpArrowCharCode;
- case NSDownArrowFunctionKey:
- return kDownArrowCharCode;
- case NSLeftArrowFunctionKey:
- return kLeftArrowCharCode;
- case NSRightArrowFunctionKey:
- return kRightArrowCharCode;
- }
- return theChar;
-}
-
-
-// The Mac standard char codes for arrow keys are different from the
-// web standard.
-// Also in the browser world the enter key gets mapped to be the same as the
-// return key.
-int TranslateMacControlCharToWebChar(int theChar) {
- switch(theChar) {
- case kUpArrowCharCode:
- return 38;
- case kDownArrowCharCode:
- return 40;
- case kLeftArrowCharCode:
- return 37;
- case kRightArrowCharCode:
- return 39;
- case kEnterCharCode:
- return kReturnCharCode;
- }
- return theChar;
-}
-
-
-// Given an instance, and some event data, calls Javascript methods
-// placed on the object tag so that the keystrokes can be handled in
-// Javascript.
-void DispatchKeyboardEvent(PluginObject* obj,
- EventKind kind,
- int theChar,
- int theKeyCode,
- EventModifiers mods) {
- theChar = TranslateMacUnicodeControlChar(theChar);
- theChar = TranslateMacControlCharToWebChar(theChar);
- int upperChar = (theChar >= 'a' && theChar <='z') ? theChar - 32 : theChar;
-
- Event::Type type = Event::TYPE_KEYDOWN; // Init to something valid.
- switch (kind) {
- case keyDown:
- // We'll also have to send a keypress below.
- type = Event::TYPE_KEYDOWN;
- break;
- case autoKey:
- type = Event::TYPE_KEYPRESS;
- break;
- case keyUp:
- type = Event::TYPE_KEYUP;
- break;
- default:
- return;
- break;
- }
- Event event(type);
-
- switch (kind) {
- case keyDown:
- case keyUp:
- event.set_key_code(upperChar);
- break;
- case autoKey:
- event.set_char_code(theChar);
- break;
- default:
- LOG(FATAL) << "Unknown keyboard event: " << kind;
- }
-
- int modifier_state = 0;
- if (mods & controlKey) {
- modifier_state |= Event::MODIFIER_CTRL;
- }
- if (mods & shiftKey) {
- modifier_state |= Event::MODIFIER_SHIFT;
- }
- if (mods & optionKey) {
- modifier_state |= Event::MODIFIER_ALT;
- }
- if (mods & cmdKey) {
- modifier_state |= Event::MODIFIER_META;
- }
- event.set_modifier_state(modifier_state);
- obj->client()->AddEventToQueue(event);
- if (type == Event::TYPE_KEYDOWN) {
- event.clear_key_code();
- event.set_char_code(theChar);
- event.set_type(Event::TYPE_KEYPRESS);
- obj->client()->AddEventToQueue(event);
- }
-}
-
-// Given an instance, and a MacOS keyboard event, calls Javascript methods
-// placed on the object tag so that the keystrokes can be handled in
-// Javascript.
-void DispatchMacKeyboardEvent(PluginObject* obj,
- EventRecord* the_event) {
- DispatchKeyboardEvent(obj,
- the_event->what,
- GetMacEventKeyChar(the_event),
- GetMacEventKeyCode(the_event),
- the_event->modifiers);
-}
-
-static void HandleCarbonMouseEvent(PluginObject* obj,
- EventRecord* the_event) {
- DCHECK(obj);
- DCHECK(obj->client());
- int screen_x = the_event->where.h;
- int screen_y = the_event->where.v;
- static Point last_mouse_loc = {0,0};
-
- o3d::Event::Type type;
- switch (the_event->what) {
- case mouseDown:
- type = o3d::Event::TYPE_MOUSEDOWN;
- break;
- case mouseUp:
- type = o3d::Event::TYPE_MOUSEUP;
- break;
- case nullEvent:
- case osEvt: // can be various things but in this context it's mouse move
- if (last_mouse_loc.h == screen_x && last_mouse_loc.v == screen_y)
- return;
- type = o3d::Event::TYPE_MOUSEMOVE;
- break;
- default:
- LOG(FATAL) << "Unknown mouse event: " << the_event->what;
- return;
- }
-
- last_mouse_loc = the_event->where;
- bool in_plugin = false; // Did the event happen within our drawing region?
-
- int x, y;
- // now make x and y plugin relative coords
- if (obj->GetFullscreenMacWindow()) {
- Rect wBounds = o3d::CGRect2Rect(
- obj->GetFullscreenMacWindow()->GetWindowBounds());
- x = screen_x - wBounds.left;
- y = screen_y - wBounds.top;
- in_plugin = true;
- } else {
- Rect wBounds;
- GetWindowBounds(obj->mac_window_,
- (obj->drawing_model_ == NPDrawingModelQuickDraw) ?
- kWindowGlobalPortRgn : kWindowStructureRgn,
- &wBounds);
- x = screen_x - wBounds.left - obj->last_plugin_loc_.h;
- y = screen_y - wBounds.top - obj->last_plugin_loc_.v;
- in_plugin = x >= 0 && y >= 0 && x < obj->width() && y < obj->height();
- }
-
- o3d::Event event(type);
- int modifier_state = 0;
- if (the_event->modifiers & controlKey) {
- modifier_state |= o3d::Event::MODIFIER_CTRL;
- }
- if (the_event->modifiers & shiftKey) {
- modifier_state |= o3d::Event::MODIFIER_SHIFT;
- }
- if (the_event->modifiers & optionKey) {
- modifier_state |= o3d::Event::MODIFIER_ALT;
- }
- if (the_event->modifiers & cmdKey) {
- modifier_state |= o3d::Event::MODIFIER_META;
- }
-
- event.set_modifier_state(modifier_state);
-
- // TODO: Figure out how to detect and set buttons properly.
- if (the_event->modifiers & btnState) {
- event.set_button(o3d::Event::BUTTON_LEFT);
- }
-
- event.set_position(x, y, screen_x, screen_y, in_plugin);
- obj->client()->AddEventToQueue(event);
-
- if (in_plugin && type == Event::TYPE_MOUSEDOWN &&
- obj->HitFullscreenClickRegion(x, y)) {
- obj->RequestFullscreenDisplay();
- }
-}
-
-// Handle a mouse-related NPCocoaEvent.
-// These events come from the new Cocoa revision of the NPAPI spec,
-// currently implemented only in Safari.
-// See https://wiki.mozilla.org/Mac:NPAPI_Event_Models
-static void HandleCocoaMouseEvent(PluginObject* obj,
- NPCocoaEvent* the_event) {
- DCHECK(obj);
- DCHECK(obj->client());
- int screen_x = the_event->data.mouse.pluginX;
- int screen_y = the_event->data.mouse.pluginY;
-
- o3d::Event::Type type;
- switch (the_event->type) {
- case NPCocoaEventMouseDown:
- type = o3d::Event::TYPE_MOUSEDOWN;
- break;
- case NPCocoaEventMouseUp:
- type = o3d::Event::TYPE_MOUSEUP;
- break;
- // The Mac makes a distinction between moved and dragged (ie moved with
- // the button down), but the O3D event model does not.
- case NPCocoaEventMouseMoved:
- case NPCocoaEventMouseDragged:
- type = o3d::Event::TYPE_MOUSEMOVE;
- break;
- case NPCocoaEventScrollWheel:
- type = o3d::Event::TYPE_WHEEL;
- break;
- // Don't care about these currently.
- case NPCocoaEventMouseEntered:
- case NPCocoaEventMouseExited:
- default:
- return;
- }
-
- int x = the_event->data.mouse.pluginX;
- int y = the_event->data.mouse.pluginY;
-
- // Did the event happen within our drawing region?
- bool in_plugin = x >= 0 && y >= 0 && x < obj->width() && y < obj->height();
-
- o3d::Event event(type);
- int modifier_state = 0;
- if (the_event->data.mouse.modifierFlags & NSControlKeyMask) {
- modifier_state |= o3d::Event::MODIFIER_CTRL;
- }
- if (the_event->data.mouse.modifierFlags &
- (NSAlphaShiftKeyMask | NSShiftKeyMask)) {
- modifier_state |= o3d::Event::MODIFIER_SHIFT;
- }
- if (the_event->data.mouse.modifierFlags & NSAlternateKeyMask) {
- modifier_state |= o3d::Event::MODIFIER_ALT;
- }
- if (the_event->data.mouse.modifierFlags & NSCommandKeyMask) {
- modifier_state |= o3d::Event::MODIFIER_META;
- }
-
- event.set_modifier_state(modifier_state);
-
- if (the_event->type == NPCocoaEventScrollWheel) {
- if (the_event->data.mouse.deltaX && the_event->data.mouse.deltaY) {
- if (abs(the_event->data.mouse.deltaX) >
- abs(the_event->data.mouse.deltaY)) {
- the_event->data.mouse.deltaY = 0;
- } else {
- the_event->data.mouse.deltaX = 0;
- }
- }
- event.set_delta(the_event->data.mouse.deltaX * 10.0,
- the_event->data.mouse.deltaY * 10.0);
- }
-
- if ((the_event->type == NPCocoaEventMouseDown) ||
- (the_event->type == NPCocoaEventMouseUp)) {
- event.set_button(
- o3d::MacOSMouseButtonNumberToO3DButton(
- the_event->data.mouse.buttonNumber));
- }
-
- event.set_position(x, y, screen_x, screen_y, in_plugin);
- obj->client()->AddEventToQueue(event);
-
- if (in_plugin && type == Event::TYPE_MOUSEDOWN &&
- obj->HitFullscreenClickRegion(x, y)) {
- obj->RequestFullscreenDisplay();
- }
-}
-
-
-
-
-// Convert an NSEvent style modifiers field to an EventRecord style one.
-// Not all bits have a representation in the target type, eg NSFunctionKeyMask
-// but we just need to convert the basic modifiers that need to be passed on
-// to Javascript.
-EventModifiers CocoaToEventRecordModifiers(NSUInteger inMods) {
- EventModifiers outMods = 0;
-
- // NSEvent distinuishes between the shift key being down and the capslock key,
- // but the W3C event spec does not make this distinction.
- if (inMods & (NSAlphaShiftKeyMask | NSShiftKeyMask))
- outMods |= shiftKey;
- if (inMods & NSControlKeyMask)
- outMods |= controlKey;
- if (inMods & NSAlternateKeyMask)
- outMods |= optionKey;
- if (inMods & NSCommandKeyMask)
- outMods |= cmdKey;
-
- return outMods;
-}
-
-// List of message types from mozilla's nsplugindefs.h, which is more
-// complete than the list in NPAPI.h.
-enum nsPluginEventType {
- nsPluginEventType_GetFocusEvent = (osEvt + 16),
- nsPluginEventType_LoseFocusEvent,
- nsPluginEventType_AdjustCursorEvent,
- nsPluginEventType_MenuCommandEvent,
- nsPluginEventType_ClippingChangedEvent,
- nsPluginEventType_ScrollingBeginsEvent,
- nsPluginEventType_ScrollingEndsEvent,
- nsPluginEventType_Idle = 0
-};
-
-// When to prefer Core Animation. Safari's support in 10.5 was too
-// buggy to attempt to use.
-static bool PreferCoreAnimation() {
- bool isSafari = o3d::metric_browser_type.value() == o3d::BROWSER_NAME_SAFARI;
- return (!isSafari || o3d::IsMacOSTenSixOrHigher());
-}
-
-static void SuppressRenderModeAuto(PluginObject* obj) {
- // If the web app specified RenderMode=Auto but the best available drawing
- // model for 3D is one for which 2D is not implemented then we cannot
- // provide an automatic 2D fallback because it is not legal to change drawing
- // or event models outside of NPP_New(). To achieve a 2D fallback the web app
- // will have to watch for initialization errors and reload the plugin with
- // RenderMode=2D.
- if (obj->features()->render_mode() == Renderer::RENDER_MODE_AUTO) {
- DLOG(INFO) << "Suppressing RenderMode=Auto for incompatible drawing model";
- obj->features()->set_render_mode(Renderer::RENDER_MODE_3D);
- }
-}
-
-// Negotiates the best plugin drawing and event model, sets the
-// browser to use that, and updates the PluginObject so we can
-// remember which one we chose. We prefer these combinations in the
-// given order:
-// - Core Animation drawing model, Cocoa event model
-// - QuickDraw drawing model, Carbon event model
-// - Core Graphics drawing model, Cocoa or Carbon event model
-// If the browser doesn't even understand the question, we use the
-// QuickDraw drawing model and Carbon event model for best backward
-// compatibility.
-//
-// This ordering provides the best forward-looking behavior while
-// still providing compatibility with older browsers. Even though Core Graphics
-// is newer than QuickDraw, we prefer QuickDraw when available because the Core
-// Graphics rendering path with OpenGL is pathologically sub-optimal.
-//
-// Returns NPERR_NO_ERROR (0) if successful, otherwise an NPError code.
-NPError Mac_SetBestEventAndDrawingModel(NPP instance, PluginObject* obj) {
- NPError err = NPERR_NO_ERROR;
- NPBool supportsCocoaEventModel = FALSE;
- NPBool supportsCarbonEventModel = FALSE;
- NPBool supportsCoreGraphics = FALSE;
- NPBool supportsQuickDraw = FALSE;
- NPBool supportsCoreAnimation = FALSE;
-
- // See if browser supports Cocoa event model.
- err = NPN_GetValue(instance,
- NPNVsupportsCocoaBool,
- &supportsCocoaEventModel);
- if (err != NPERR_NO_ERROR) {
- supportsCocoaEventModel = FALSE;
- err = NPERR_NO_ERROR; // browser doesn't support switchable event models
- }
-
- // See if browser supports Carbon event model.
- err = NPN_GetValue(instance,
- NPNVsupportsCarbonBool,
- &supportsCarbonEventModel);
- if (err != NPERR_NO_ERROR) {
- supportsCarbonEventModel = FALSE;
- err = NPERR_NO_ERROR;
- }
-
- // Test for QuickDraw support.
- err = NPN_GetValue(instance,
- NPNVsupportsQuickDrawBool,
- &supportsQuickDraw);
- if (err != NPERR_NO_ERROR)
- supportsQuickDraw = FALSE;
-
- // Test for Core Graphics support.
- err = NPN_GetValue(instance,
- NPNVsupportsCoreGraphicsBool,
- &supportsCoreGraphics);
- if (err != NPERR_NO_ERROR)
- supportsCoreGraphics = FALSE;
-
- // Test for Core Animation support.
- err = NPN_GetValue(instance,
- NPNVsupportsCoreAnimationBool,
- &supportsCoreAnimation);
- if (err != NPERR_NO_ERROR)
- supportsCoreAnimation = FALSE;
-
- // Fix up values for older browsers which don't even understand
- // these questions.
- if (!supportsCarbonEventModel && !supportsCocoaEventModel) {
- supportsCarbonEventModel = TRUE;
- }
-
- if (!supportsQuickDraw && !supportsCoreGraphics && !supportsCoreAnimation) {
- // Must be a very old browser such as FF2. Avoid calling
- // NPN_SetValue for the event or drawing models at all.
- obj->drawing_model_ = NPDrawingModelQuickDraw;
- obj->event_model_ = NPEventModelCarbon;
- DLOG(INFO) << "Legacy browser, assuming QuickDraw and Carbon";
- SuppressRenderModeAuto(obj);
- return NPERR_NO_ERROR;
- }
-
- // Now that we have our information, decide on the appropriate combination.
- NPDrawingModel drawing_model = NPDrawingModelQuickDraw;
- NPEventModel event_model = NPEventModelCarbon;
-
- // If the web app has requested 2D mode then we only want to select drawing
- // models supported by RendererCairo (currently only Core Graphics).
- bool wants_2d = obj->features()->render_mode() == Renderer::RENDER_MODE_2D;
-
- if (!wants_2d && supportsCoreAnimation && supportsCocoaEventModel &&
- PreferCoreAnimation()) {
- drawing_model = NPDrawingModelCoreAnimation;
- event_model = NPEventModelCocoa;
- DLOG(INFO) << "Selecting Core Animation and Cocoa";
- SuppressRenderModeAuto(obj);
- } else if (!wants_2d && supportsQuickDraw && supportsCarbonEventModel) {
- drawing_model = NPDrawingModelQuickDraw;
- event_model = NPEventModelCarbon;
- DLOG(INFO) << "Selecting QuickDraw and Carbon";
- SuppressRenderModeAuto(obj);
- } else if (supportsCoreGraphics && supportsCocoaEventModel) {
- drawing_model = NPDrawingModelCoreGraphics;
- event_model = NPEventModelCocoa;
- DLOG(INFO) << "Selecting Core Graphics and Cocoa";
- } else if (supportsCoreGraphics && supportsCarbonEventModel) {
- drawing_model = NPDrawingModelCoreGraphics;
- event_model = NPEventModelCarbon;
- DLOG(INFO) << "Selecting Core Graphics and Carbon";
- } else {
- // If all of the above tests failed, we are running on a browser
- // which we don't know how to handle.
- return NPERR_GENERIC_ERROR;
- }
-
- // Earlier versions of this code did not check the return value of
- // the call to set the event model.
- NPN_SetValue(instance, NPPVpluginEventModel,
- reinterpret_cast<void*>(event_model));
- err = NPN_SetValue(instance, NPPVpluginDrawingModel,
- reinterpret_cast<void*>(drawing_model));
-
- if (err != NPERR_NO_ERROR) {
- return err;
- }
-
- obj->drawing_model_ = drawing_model;
- obj->event_model_ = event_model;
- return NPERR_NO_ERROR;
-}
-} // end anonymous namespace
-
-#if defined(O3D_INTERNAL_PLUGIN)
-namespace o3d {
-#else
-extern "C" {
-#endif
-
-#if !defined(O3D_INTERNAL_PLUGIN)
-
-// Wrapper that discards the return value to match the expected type of
-// NPP_ShutdownProcPtr.
-static void NPP_ShutdownWrapper() {
- NP_Shutdown();
-}
-
-// This code is needed to support browsers based on a slightly dated version
-// of the NPAPI such as Firefox 2, and Camino 1.6. These browsers expect there
-// to be a main() to call to do basic setup.
-int main(NPNetscapeFuncs* browserFuncs,
- NPPluginFuncs* pluginFuncs,
- NPP_ShutdownProcPtr* shutdownProc) {
- HANDLE_CRASHES;
- NPError error = NP_Initialize(browserFuncs);
- if (error == NPERR_NO_ERROR)
- error = NP_GetEntryPoints(pluginFuncs);
- *shutdownProc = NPP_ShutdownWrapper;
-
- return error;
-}
-
-#endif // O3D_INTERNAL_PLUGIN
-
-} // namespace o3d / extern "C"
-
-namespace o3d {
-
-NPError PlatformPreNPInitialize() {
-#if !defined(O3D_INTERNAL_PLUGIN)
- o3d::InitializeBreakpad();
-
-#ifdef CFTIMER
- o3d::gRenderTimer.Start();
-#endif // CFTIMER
-#endif // O3D_INTERNAL_PLUGIN
-
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformPostNPInitialize() {
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformPreNPShutdown() {
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformPostNPShutdown() {
-#if !defined(O3D_INTERNAL_PLUGIN)
-#ifdef CFTIMER
- o3d::gRenderTimer.Stop();
-#endif
-
- o3d::ShutdownBreakpad();
-#endif // O3D_INTERNAL_PLUGIN
-
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformNPPGetValue(PluginObject *obj,
- NPPVariable variable,
- void *value) {
- switch (variable) {
- case NPPVpluginCoreAnimationLayer:
- if (!ObjO3DLayer(obj)) {
- // Setup layer
- O3DLayer* gl_layer = [[[O3DLayer alloc] init] retain];
-
- gl_layer.autoresizingMask =
- kCALayerWidthSizable + kCALayerHeightSizable;
- obj->gl_layer_ = gl_layer;
-
- [gl_layer setPluginObject:obj];
- }
- // Make sure to return a retained layer
- *(CALayer**)value = ObjO3DLayer(obj);
- return NPERR_NO_ERROR;
- break;
- default:
- return NPERR_INVALID_PARAM;
- }
-
- return NPERR_INVALID_PARAM;
-}
-
-bool HandleCarbonEvent(EventRecord* the_event, NPP instance) {
- PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
- bool handled = false;
- FullscreenWindowMac* fullscreen_window = obj->GetFullscreenMacWindow();
-
- if (g_logger) g_logger->UpdateLogging();
-
- // Help the plugin keep track of when we last saw an event so the CFTimer can
- // notice if we get cut off, eg by our tab being hidden by Safari, which there
- // is no other way for us to detect.
- obj->MacEventReceived(the_event->what != nsPluginEventType_LoseFocusEvent);
-
- switch (the_event->what) {
- case nullEvent:
-#ifdef DEFERRED_DRAW_ON_NULLEVENTS
- GLUE_PROFILE_START(instance, "forceredraw");
- NPN_ForceRedraw(instance); // invalidate to cause a redraw
- GLUE_PROFILE_STOP(instance, "forceredraw");
-#elif defined(CFTIMER)
-#else
- DrawPlugin(obj, true, obj->mac_cg_context_ref_);
-#endif
- // Safari tab switching recovery code.
- if (obj->mac_surface_hidden_) {
- obj->mac_surface_hidden_ = false;
- NPN_ForceRedraw(instance); // invalidate to cause a redraw
- }
-
- // Auto-recovery for any situation where another window comes in front
- // of the fullscreen window and we need to exit fullscreen mode.
- // This can happen because another browser window has come forward, or
- // because another app has been called to the front.
- if (fullscreen_window && !fullscreen_window->IsActive()) {
- obj->CancelFullscreenDisplay();
- }
-
- // Send nullEvents to HandleCarbonMouseEvent so they can be used to
- // simulate mouse moved events. Not needed in fullscreen mode, where we
- // really do get mouse moved events. See the osEvt case below.
- if (!fullscreen_window)
- HandleCarbonMouseEvent(obj, the_event);
-
- handled = true;
- break;
- case updateEvt:
- // We dispatch a render callback from this point iff using Core Graphics.
- // With CoreGraphics+Carbon this is the only source of rendering, whereas
- // with QuickDraw+Carbon the main source of rendering is in
- // RenderTimer::TimerCallback().
- DrawPlugin(obj,
- obj->drawing_model_ == NPDrawingModelCoreGraphics,
- obj->mac_cg_context_ref_);
- handled = true;
- break;
- case osEvt:
- // These are mouse moved messages when so tagged in the high byte.
- if ((the_event->message >> 24) == mouseMovedMessage) {
- HandleCarbonMouseEvent(obj, the_event);
- handled = true;
- }
- break;
- case mouseDown:
- HandleCarbonMouseEvent(obj, the_event);
- break;
- case mouseUp:
- HandleCarbonMouseEvent(obj, the_event);
- handled = true;
- break;
- case keyDown:
- // Hard-coded trapdoor to get out of fullscreen mode if user hits escape.
- if ((GetMacEventKeyChar(the_event) == '\e') && fullscreen_window) {
- obj->CancelFullscreenDisplay();
- break;
- } // otherwise fall through
- case autoKey:
- case keyUp: {
- DispatchMacKeyboardEvent(obj, the_event);
- handled = true;
- break;
- }
- case nsPluginEventType_ScrollingBeginsEvent:
- obj->SetScrollIsInProgress(true);
- break;
- case nsPluginEventType_ScrollingEndsEvent:
- obj->SetScrollIsInProgress(false);
- break;
- default:
- break;
- }
- return handled;
-}
-
-// Handle an NPCocoaEvent style event. The Cocoa event interface is
-// a recent addition to the NAPI spec.
-// See https://wiki.mozilla.org/Mac:NPAPI_Event_Models for further details.
-// The principle advantages are that we can get scrollwheel messages,
-// mouse-moved messages, and can tell which mouse button was pressed.
-// This API will also be required for a carbon-free 64 bit version for 10.6.
-bool HandleCocoaEvent(NPP instance, NPCocoaEvent* the_event,
- bool initiated_from_browser) {
- PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
- FullscreenWindowMac* fullscreen_window = obj->GetFullscreenMacWindow();
- bool handled = false;
-
- if (g_logger) g_logger->UpdateLogging();
-
- bool lostFocus = the_event->type == NPCocoaEventFocusChanged &&
- !the_event->data.focus.hasFocus;
- obj->MacEventReceived(!lostFocus);
- switch (the_event->type) {
- case NPCocoaEventDrawRect:
- if (obj->drawing_model_ == NPDrawingModelCoreAnimation) {
- O3DLayer* layer = ObjO3DLayer(obj);
- if (layer) {
- [layer setNeedsDisplay];
- }
- } else {
- // We need to call the render callback from here if we are using
- // Core Graphics because it doesn't get called anywhere else.
- CGContextRef new_mac_cg_context_ref = the_event->data.draw.context;
- if (new_mac_cg_context_ref != obj->mac_cg_context_ref_) {
- obj->mac_cg_context_ref_ = new_mac_cg_context_ref;
- // Update the Renderer's CGContextRef (only RendererCairo actually
- // uses it).
- o3d::DisplayWindowMac display;
- display.set_agl_context(obj->mac_agl_context_);
- display.set_cgl_context(obj->mac_cgl_context_);
- display.set_cg_context_ref(obj->mac_cg_context_ref_);
- obj->renderer()->ChangeDisplayWindow(display);
- }
- DrawPlugin(obj, true, obj->mac_cg_context_ref_);
- }
- handled = true;
- break;
- case NPCocoaEventMouseDown:
- case NPCocoaEventMouseUp:
- case NPCocoaEventMouseMoved:
- case NPCocoaEventMouseDragged:
- case NPCocoaEventMouseEntered:
- case NPCocoaEventMouseExited:
- case NPCocoaEventScrollWheel:
- if (the_event->type == NPCocoaEventMouseUp &&
- initiated_from_browser && fullscreen_window) {
- // The mouse-up event associated with the mouse-down that caused
- // the app to go full-screen is dispatched against the browser
- // window rather than the full-screen window. Apps that have an
- // icon which toggles full-screen and windowed mode therefore come
- // out of full-screen immediately when the icon is clicked, since
- // the mouse-up occurs at the same location as the mouse-down. Work
- // around this by squelching this mouse up event. This seems to
- // work acceptably for known apps. We could do better by
- // redispatching all mouse events through the full-screen window
- // until the first mouse up.
- break;
- }
-
- HandleCocoaMouseEvent(obj, the_event);
- break;
- case NPCocoaEventKeyDown:
- // Hard-coded trapdoor to get out of fullscreen mode if user hits escape.
- if (fullscreen_window) {
- NSString *chars =
- (NSString*) the_event->data.key.charactersIgnoringModifiers;
-
- if (chars == NULL || [chars length] == 0) {
- break;
- }
-
- if ([chars characterAtIndex:0] == '\e') {
- obj->CancelFullscreenDisplay();
- break;
- }
- } // otherwise fall through
- case NPCocoaEventKeyUp: {
- EventKind eventKind = (the_event->type == NPCocoaEventKeyUp) ? keyUp :
- (the_event->data.key.isARepeat) ? autoKey : keyDown;
-
- EventModifiers modifiers =
- CocoaToEventRecordModifiers(the_event->data.key.modifierFlags);
-
- NSString *chars =
- (NSString*) the_event->data.key.charactersIgnoringModifiers;
-
- if (chars == NULL || [chars length] == 0) {
- break;
- }
-
- DispatchKeyboardEvent(obj,
- eventKind,
- [chars characterAtIndex:0],
- the_event->data.key.keyCode,
- modifiers);
- break;
- }
- case NPCocoaEventFlagsChanged:
- case NPCocoaEventFocusChanged:
- case NPCocoaEventWindowFocusChanged:
- // Safari tab switching recovery code.
- if (obj->mac_surface_hidden_) {
- obj->mac_surface_hidden_ = false;
- NPN_ForceRedraw(instance); // invalidate to cause a redraw
- }
-
- // Auto-recovery for any situation where another window comes in front
- // of the fullscreen window and we need to exit fullscreen mode.
- // This can happen because another browser window has come forward, or
- // because another app has been called to the front.
- // TODO: We'll have problems with this when dealing with e.g.
- // Japanese text input IME windows.
- // Note that we ignore focus transfer events coming from the
- // browser while in full-screen mode, because otherwise we
- // frequently disable full-screen mode almost immediately after
- // entering it.
- if (fullscreen_window && !fullscreen_window->IsActive() &&
- !initiated_from_browser) {
- obj->CancelFullscreenDisplay();
- }
-
- break;
- case NPCocoaEventTextInput:
- break;
- }
-
- return handled;
-}
-
-NPError PlatformNPPNew(NPP instance, PluginObject *obj) {
- NPError err = Mac_SetBestEventAndDrawingModel(instance, obj);
- if (err != NPERR_NO_ERROR)
- return err;
-#ifdef CFTIMER
- if (obj->drawing_model_ == NPDrawingModelCoreAnimation) {
- o3d::gRenderTimer.AddInstance(instance);
- }
-#endif
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformNPPDestroy(NPP instance, PluginObject *obj) {
-#if defined(CFTIMER)
- o3d::gRenderTimer.RemoveInstance(instance);
-#endif
-
- // TODO(maf) / TODO(kbr): are we leaking AGL / CGL contexts?
-
- if (obj->drawing_model_ == NPDrawingModelCoreAnimation) {
- O3DLayer* layer = ObjO3DLayer(obj);
- if (layer) {
- // Prevent the layer from rendering any more.
- [layer setPluginObject:NULL];
- }
- }
-
- obj->TearDown();
-
- return NPERR_NO_ERROR;
-}
-
-bool CheckForAGLError() {
- return aglGetError() != AGL_NO_ERROR;
-}
-
-NPError PlatformNPPSetWindow(NPP instance,
- PluginObject *obj,
- NPWindow* window) {
- WindowRef new_window = NULL;
-
- assert(window != NULL);
-
- if (window->window == NULL &&
- obj->drawing_model_ != NPDrawingModelCoreGraphics &&
- obj->drawing_model_ != NPDrawingModelCoreAnimation) {
- return NPERR_NO_ERROR;
- }
-
- obj->last_plugin_loc_.h = window->x;
- obj->last_plugin_loc_.v = window->y;
-
- bool mac_cg_context_ref_changed = false;
-
- switch (obj->drawing_model_) {
- case NPDrawingModelCoreAnimation: {
- O3DLayer* o3dLayer = ObjO3DLayer(obj);
- [o3dLayer setWidth: window->width height: window->height];
- return NPERR_NO_ERROR;
- }
- case NPDrawingModelCoreGraphics: {
- // In some browsers (Safari 4 on 10.5, Chrome on 10.5), window->window is
- // NULL when using the Cocoa event model. In that situation we get our
- // CGContextRef in HandleCocoaEvent() instead.
- if (window->window != NULL) {
- NP_CGContext* np_cg = reinterpret_cast<NP_CGContext*>(window->window);
- if (obj->event_model_ == NPEventModelCocoa) {
- NSWindow * ns_window = reinterpret_cast<NSWindow*>(np_cg->window);
- new_window = reinterpret_cast<WindowRef>([ns_window windowRef]);
- } else {
- new_window = static_cast<OpaqueWindowPtr*>(np_cg->window);
- }
- CGContextRef new_mac_cg_context_ref = np_cg->context;
- if (new_mac_cg_context_ref != obj->mac_cg_context_ref_) {
- obj->mac_cg_context_ref_ = new_mac_cg_context_ref;
- mac_cg_context_ref_changed = true;
- }
- }
- break;
- }
- case NPDrawingModelQuickDraw: {
- NP_Port* np_qd = reinterpret_cast<NP_Port*>(window->window);
- if (np_qd->port)
- new_window = GetWindowFromPort(np_qd->port);
- // Safari 4 on Snow Leopard is sending us a spurious
- // NPP_SetWindow where we can not determine the WindowRef from
- // the port. Ignore this.
- if (obj->mac_window_ != NULL &&
- new_window == NULL)
- return NPERR_NO_ERROR;
- break;
- }
- default:
- return NPERR_INCOMPATIBLE_VERSION_ERROR;
- break;
- }
-
- // Whether the target window has changed.
- bool window_changed = new_window != obj->mac_window_;
-
- // Whether we already had a window before this call.
- bool had_a_window = obj->mac_window_ != NULL;
-
- obj->mac_window_ = new_window;
-
- if (obj->drawing_model_ == NPDrawingModelCoreAnimation) {
- if (obj->mac_cgl_context_) {
- CGLSetCurrentContext(obj->mac_cgl_context_);
- }
- } else if (obj->drawing_model_ == NPDrawingModelCoreGraphics) {
- // It's important to skip this when RenderMode=2D is specified because it
- // can make OSX on an MBP6,2 flip between the Intel and NVIDIA GPUs multiple
- // times in FF, which significantly delays our start-up.
- if (obj->features()->render_mode() != Renderer::RENDER_MODE_2D &&
- obj->mac_cgl_pbuffer_ == NULL) {
- // We initialize things with a CGL context rendering to a 1x1
- // pbuffer. Later we use the O3D RenderSurface APIs to set up the
- // framebuffer object which is used for rendering.
- CGLContextObj share_context = obj->GetFullscreenShareContext();
- CGLPixelFormatObj pixel_format = obj->GetFullscreenCGLPixelFormatObj();
- if (!share_context || !pixel_format) {
- // This can happen in FF when using Core Graphics, though curiously
- // only on certain websites.
- LOG(ERROR) << "Failed to create share context and/or pixel format";
- // We continue initializing, though without a CGLContextObj RendererGL
- // will fail to initialize. If the web app is using RenderMode=Auto
- // though then Cairo will work.
- } else {
- CGLError result;
- CGLContextObj context;
- result = CGLCreateContext(pixel_format, share_context, &context);
- if (result != kCGLNoError) {
- DLOG(ERROR) << "Error " << result << " creating context.";
- return NPERR_GENERIC_ERROR;
- }
- CGLPBufferObj pbuffer;
- if ((result = CGLCreatePBuffer(1, 1,
- GL_TEXTURE_2D, GL_RGBA,
- 0, &pbuffer)) != kCGLNoError) {
- CGLDestroyContext(context);
- DLOG(ERROR) << "Error " << result << " creating pbuffer.";
- return NPERR_GENERIC_ERROR;
- }
- if ((result = CGLSetPBuffer(context, pbuffer, 0, 0, 0)) !=
- kCGLNoError) {
- CGLDestroyContext(context);
- CGLDestroyPBuffer(pbuffer);
- DLOG(ERROR) << "Error " << result << " attaching pbuffer to context.";
- return NPERR_GENERIC_ERROR;
- }
- // Must make the context current for renderer creation to succeed
- CGLSetCurrentContext(context);
- obj->mac_cgl_context_ = context;
- obj->mac_cgl_pbuffer_ = pbuffer;
- }
- }
- } else if (!had_a_window && obj->mac_agl_context_ == NULL) {
- // setup AGL context
- AGLPixelFormat myAGLPixelFormat = NULL;
-
- // We need to spec out a few similar but different sets of renderer
- // specifications - define some macros to lessen the duplication.
-#define O3D_DEPTH_SETTINGS AGL_RGBA, AGL_DEPTH_SIZE, 24,
-#define O3D_STENCIL_SETTINGS AGL_STENCIL_SIZE, 8,
-#define O3D_HARDWARE_RENDERER AGL_ACCELERATED, AGL_NO_RECOVERY,
-#define O3D_SOFTWARE_RENDERER AGL_RENDERER_ID, AGL_RENDERER_GENERIC_FLOAT_ID,
-#define O3D_MULTISAMPLE AGL_MULTISAMPLE, \
- AGL_SAMPLE_BUFFERS_ARB, 1, AGL_SAMPLES_ARB, 4, AGL_MULTISAMPLE,
-#define O3D_END AGL_NONE
-
-#ifdef USE_AGL_DOUBLE_BUFFER
-#define O3D_DOUBLE_BUFFER_SETTINGS AGL_DOUBLEBUFFER,
-#else
-#define O3D_DOUBLE_BUFFER_SETTINGS
-#endif
-
- if (!UseSoftwareRenderer()) {
- // Try to create a hardware context with the following
- // specification
- GLint attributes[] = {
- O3D_DEPTH_SETTINGS
- O3D_STENCIL_SETTINGS
- O3D_DOUBLE_BUFFER_SETTINGS
- O3D_HARDWARE_RENDERER
- O3D_MULTISAMPLE
- O3D_END
- };
- myAGLPixelFormat = aglChoosePixelFormat(NULL,
- 0,
- attributes);
-
- // If this fails, then don't try to be as ambitious
- // (so don't ask for multi-sampling), but still require hardware
- if (myAGLPixelFormat == NULL) {
- GLint low_end_attributes[] = {
- O3D_DEPTH_SETTINGS
- O3D_STENCIL_SETTINGS
- O3D_DOUBLE_BUFFER_SETTINGS
- O3D_HARDWARE_RENDERER
- O3D_END
- };
- myAGLPixelFormat = aglChoosePixelFormat(NULL,
- 0,
- low_end_attributes);
- }
- }
-
- if (myAGLPixelFormat == NULL) {
- // Fallback to software renderer either if the vendorID/gpuID
- // is known to be problematic, or if the hardware context failed
- // to get created
- //
- // Note that we don't request multisampling since it's too slow.
- GLint software_renderer_attributes[] = {
- O3D_DEPTH_SETTINGS
- O3D_STENCIL_SETTINGS
- O3D_DOUBLE_BUFFER_SETTINGS
- O3D_SOFTWARE_RENDERER
- O3D_END
- };
- myAGLPixelFormat = aglChoosePixelFormat(NULL,
- 0,
- software_renderer_attributes);
-
- obj->SetRendererIsSoftware(true);
- }
-
- if (myAGLPixelFormat == NULL || CheckForAGLError())
- return NPERR_MODULE_LOAD_FAILED_ERROR;
-
- obj->mac_agl_context_ = aglCreateContext(myAGLPixelFormat, NULL);
-
- if (CheckForAGLError())
- return NPERR_MODULE_LOAD_FAILED_ERROR;
-
- aglDestroyPixelFormat(myAGLPixelFormat);
-
- if (!SetWindowForAGLContext(obj->mac_agl_context_, obj->mac_window_))
- return NPERR_MODULE_LOAD_FAILED_ERROR;
-
- aglSetCurrentContext(obj->mac_agl_context_);
-
- GetOpenGLMetrics();
-
-#ifdef USE_AGL_DOUBLE_BUFFER
- GLint swapInterval = 1; // request synchronization
- aglSetInteger(obj->mac_agl_context_, AGL_SWAP_INTERVAL, &swapInterval);
-#endif
- }
-
- int clipHeight = window->clipRect.bottom - window->clipRect.top;
- int clipWidth = window->clipRect.right - window->clipRect.left;
-
- int x_offset = window->clipRect.left - window->x;
- int y_offset = window->clipRect.top - window->y;
- int gl_x_origin = x_offset;
- int gl_y_origin = window->clipRect.bottom - (window->y + window->height);
-
- // Firefox calls us with an empty cliprect all the time, toggling our
- // cliprect back and forth between empty and the normal value, particularly
- // during scrolling.
- // As we need to make our AGL surface track the clip rect, honoring all of
- // these calls would result in spectacular flashing.
- // The goal here is to try to spot the calls we can safely ignore.
- // The bogus empty cliprects always have left and top of the real clip.
- // A null cliprect should always be honored ({0,0,0,0} means a hidden tab),
- // as should the first ever call to this function,
- // or an attempt to change the window.
- // The call at the end of a scroll step is also honored.
- // Otherwise, skip this change and do not hide our context.
- bool is_empty_cliprect = (clipHeight <= 0 || clipWidth <= 0);
- bool is_null_cliprect = (window->clipRect.bottom == 0 &&
- window->clipRect.top == 0 &&
- window->clipRect.left == 0 &&
- window->clipRect.right == 0);
-
- if (is_empty_cliprect && (!is_null_cliprect) &&
- had_a_window && (!window_changed) && !obj->ScrollIsInProgress() &&
- !mac_cg_context_ref_changed) {
- return NPERR_NO_ERROR;
- }
-
- // Workaround - the Apple software renderer crashes if you set the drawing
- // area to 0x0, so use 1x1.
- if (is_empty_cliprect && obj->RendererIsSoftware())
- clipWidth = clipHeight = 1;
-
- // update size and location of the agl context
- if (obj->mac_agl_context_) {
-
- // We already had a window, and now we've got a different window -
- // this can happen when the user drags out a tab in Safari into its own
- // window.
- if (had_a_window && window_changed)
- SetWindowForAGLContext(obj->mac_agl_context_, obj->mac_window_);
-
- aglSetCurrentContext(obj->mac_agl_context_);
-
- Rect windowRect = {0, 0, 0, 0};
- GetWindowBounds(obj->mac_window_,
- (obj->drawing_model_ == NPDrawingModelQuickDraw) ?
- kWindowContentRgn : kWindowStructureRgn,
- &windowRect);
-
- int windowHeight = windowRect.bottom - windowRect.top;
-
- // These are in window coords, the weird bit being that agl wants the
- // location of the bottom of the GL context in y flipped coords,
- // eg 100 would mean the bottom of the GL context was 100 up from the
- // bottom of the window.
- obj->last_buffer_rect_[0] = window->x + x_offset;
- obj->last_buffer_rect_[1] = (windowHeight - (window->y + clipHeight))
- - y_offset; // this param is y flipped
- obj->last_buffer_rect_[2] = clipWidth;
- obj->last_buffer_rect_[3] = clipHeight;
- obj->mac_surface_hidden_ = false;
-
- // If in fullscreen, just remember the desired change in geometry so
- // we restore to the right rectangle.
- if (obj->GetFullscreenMacWindow() != NULL)
- return NPERR_NO_ERROR;
-
- aglSetInteger(obj->mac_agl_context_, AGL_BUFFER_RECT,
- obj->last_buffer_rect_);
- aglEnable(obj->mac_agl_context_, AGL_BUFFER_RECT);
- }
-
- if (obj->renderer()) {
- // Renderer is already initialized from a previous call to this function,
- // just update size and position and return.
- if (obj->drawing_model_ == NPDrawingModelCoreGraphics) {
- if (!obj->renderer()->SupportsCoreGraphics()) {
- obj->EnableOffscreenRendering();
- }
- if (mac_cg_context_ref_changed) {
- o3d::DisplayWindowMac display;
- display.set_agl_context(obj->mac_agl_context_);
- display.set_cgl_context(obj->mac_cgl_context_);
- display.set_cg_context_ref(obj->mac_cg_context_ref_);
- obj->renderer()->ChangeDisplayWindow(display);
- }
- obj->Resize(window->width, window->height);
- } else if (had_a_window) {
- obj->renderer()->SetClientOriginOffset(gl_x_origin, gl_y_origin);
- obj->Resize(window->width, window->height);
- }
- return NPERR_NO_ERROR;
- }
-
- // Else this is the first call.
-
- // Create and assign the graphics context.
- o3d::DisplayWindowMac default_display;
- default_display.set_agl_context(obj->mac_agl_context_);
- default_display.set_cgl_context(obj->mac_cgl_context_);
- default_display.set_cg_context_ref(obj->mac_cg_context_ref_);
-
- obj->CreateRenderer(default_display);
-
- // if the renderer cannot be created (maybe the features are not supported)
- // then we can proceed no further
- if (!obj->renderer()) {
- if (obj->mac_agl_context_) {
- ::aglDestroyContext(obj->mac_agl_context_);
- obj->mac_agl_context_ = NULL;
- }
- }
-
- obj->client()->Init();
-
- if (obj->renderer()) {
- if (obj->drawing_model_ == NPDrawingModelCoreGraphics) {
- if (!obj->renderer()->SupportsCoreGraphics()) {
- // Browser is using Core Graphics but renderer doesn't support it, so we
- // must render off-screen and then read back into software to re-render
- // with Core Graphics.
- obj->EnableOffscreenRendering();
- }
- } else {
- obj->renderer()->SetClientOriginOffset(gl_x_origin, gl_y_origin);
- }
-
- obj->Resize(window->width, window->height);
-#ifdef CFTIMER
- // now that the graphics context is setup, add this instance to the timer
- // list so it gets drawn repeatedly
- gRenderTimer.AddInstance(instance);
-#endif // CFTIMER
- }
-
- return NPERR_NO_ERROR;
-}
-
-void PlatformNPPStreamAsFile(StreamManager *stream_manager,
- NPStream *stream,
- const char *fname) {
- // Some browsers give us an absolute HFS path in fname, some give us an
- // absolute Posix path, so convert to Posix if needed.
- if ((!fname) || (fname[0] == '/') || !fname[0]) {
- stream_manager->SetStreamFile(stream, fname);
- } else {
- const char* converted_fname = CreatePosixFilePathFromHFSFilePath(fname);
- if (converted_fname == NULL)
- return; // TODO should also log error if we ever get here
- stream_manager->SetStreamFile(stream, converted_fname);
- delete converted_fname;
- }
-}
-
-int16 PlatformNPPHandleEvent(NPP instance, PluginObject *obj, void *event) {
- if (obj->event_model_ == NPEventModelCarbon) {
- EventRecord* theEvent = static_cast<EventRecord*>(event);
- return HandleCarbonEvent(theEvent, instance) ? 1 : 0;
- } else if (obj->event_model_ == NPEventModelCocoa){
- return HandleCocoaEvent(instance, (NPCocoaEvent*)event, true) ? 1 : 0;
- }
- return 0;
-}
-
-} // namespace o3d
diff --git a/o3d/plugin/mac/o3d_layer.h b/o3d/plugin/mac/o3d_layer.h
deleted file mode 100644
index 8b71ea0..0000000
--- a/o3d/plugin/mac/o3d_layer.h
+++ /dev/null
@@ -1,62 +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 <Cocoa/Cocoa.h>
-#import <QuartzCore/QuartzCore.h>
-
-#import "plugin/cross/o3d_glue.h"
-
-using glue::_o3d::PluginObject;
-
-@interface O3DLayer : CAOpenGLLayer {
- CGLContextObj glContext_;
- PluginObject *obj_;
- BOOL created_context_;
- BOOL was_resized_;
- int width_;
- int height_;
-}
-
-- (CGLContextObj)glContext;
-
-- (void)drawInCGLContext:(CGLContextObj)ctx
- pixelFormat:(CGLPixelFormatObj)pf
- forLayerTime:(CFTimeInterval)t
- displayTime:(const CVTimeStamp *)ts;
-
-- (void)setPluginObject:(PluginObject *)obj;
-
-- (void)setWidth:(int)width
- height:(int)height;
-
-@end
-
diff --git a/o3d/plugin/mac/o3d_layer.mm b/o3d/plugin/mac/o3d_layer.mm
deleted file mode 100644
index 05364ab3..0000000
--- a/o3d/plugin/mac/o3d_layer.mm
+++ /dev/null
@@ -1,196 +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 "plugin_mac.h"
-#import <OpenGL/OpenGL.h>
-#import "o3d_layer.h"
-
-#include "display_window_mac.h"
-using o3d::DisplayWindowMac;
-
-@implementation O3DLayer
-
-
-- (id)init {
- self = [super init];
-
- // Set ourselves up to composite correctly. Users can write
- // arbitrary alpha values into the back buffer but O3D's output is
- // defined as being opaque. For correct rendering results we must
- // basically drop the alpha channel while drawing to the screen
- // using Core Animation. Setting the opaque flag achieves this.
- if (self != nil) {
- self.opaque = YES;
- }
-
- return self;
-}
-
-- (void)setPluginObject:(PluginObject *)obj {
- obj_ = obj;
-}
-
-
-/* Called when a new frame needs to be generated for layer time 't'.
- * 'ctx' is attached to the rendering destination. It's state is
- * otherwise undefined. When non-null 'ts' describes the display
- * timestamp associated with layer time 't'. The default implementation
- * of the method flushes the context. */
-
-
-- (void)drawInCGLContext:(CGLContextObj)ctx
- pixelFormat:(CGLPixelFormatObj)pf
- forLayerTime:(CFTimeInterval)t
- displayTime:(const CVTimeStamp *)ts {
- // Watch out for the plugin being destroyed out from under us.
- if (!obj_) {
- return;
- }
-
- // Set the current context to the one given to us.
- CGLSetCurrentContext(ctx);
-
- if (created_context_) {
- DCHECK_EQ(ctx, obj_->mac_cgl_context_);
- o3d::DisplayWindowMac default_display;
- default_display.set_agl_context(obj_->mac_agl_context_);
- default_display.set_cgl_context(obj_->mac_cgl_context_);
- obj_->CreateRenderer(default_display);
- obj_->client()->Init();
- created_context_ = false;
- }
-
- if (was_resized_) {
- obj_->Resize(width_, height_);
- was_resized_ = false;
- }
-
-
- if (obj_) {
- obj_->client()->RenderClient(true);
- }
-
- // Call super to finalize the drawing. By default it just calls glFlush().
- [super drawInCGLContext:ctx pixelFormat:pf forLayerTime:t displayTime:ts];
-}
-
-- (BOOL)canDrawInCGLContext:(CGLContextObj)ctx
- pixelFormat:(CGLPixelFormatObj)pf
- forLayerTime:(CFTimeInterval)t
- displayTime:(const CVTimeStamp *)ts {
- return YES;
-}
-
-
-
-
-/* Called by the CAOpenGLLayer implementation when a rendering context
- * is needed by the layer. Should return an OpenGL context with
- * renderers from pixel format 'pixelFormat'. The default implementation
- * allocates a new context with a null share context. */
-- (CGLContextObj)copyCGLContextForPixelFormat:(CGLPixelFormatObj)pixelFormat {
- if (glContext_ == NULL) {
- CGLContextObj share_context = obj_->GetFullscreenShareContext();
- DCHECK(share_context);
- if (CGLCreateContext(pixelFormat, share_context, &glContext_) !=
- kCGLNoError) {
- glContext_ = [super copyCGLContextForPixelFormat:pixelFormat];
- }
- obj_->SetMacCGLContext(glContext_);
- created_context_ = true;
- }
- return glContext_;
-}
-
-/*
-- (CGLPixelFormatObj)copyCGLPixelFormatForDisplayMask:(uint32_t)mask {
- return [super copyCGLPixelFormatForDisplayMask:mask];
-}*/
-
-
-#define PFA(number) static_cast<CGLPixelFormatAttribute>(number)
-
-#define O3D_COLOR_AND_DEPTH_SETTINGS kCGLPFAClosestPolicy, \
- kCGLPFAColorSize, PFA(24), \
- kCGLPFAAlphaSize, PFA(8), \
- kCGLPFADepthSize, PFA(24), \
- kCGLPFADoubleBuffer,
-#define O3D_STENCIL_SETTINGS kCGLPFAStencilSize, PFA(8),
-#define O3D_HARDWARE_RENDERER kCGLPFAAccelerated, kCGLPFANoRecovery,
-#define O3D_MULTISAMPLE kCGLPFAMultisample, kCGLPFASamples, PFA(4),
-#define O3D_DISPLAY_MASK(mask) kCGLPFADisplayMask, PFA(mask),
-#define O3D_END PFA(0)
-- (CGLPixelFormatObj)copyCGLPixelFormatForDisplayMask:(uint32_t)mask {
- const CGLPixelFormatAttribute attributes[] = {
- O3D_COLOR_AND_DEPTH_SETTINGS
- O3D_STENCIL_SETTINGS
- O3D_HARDWARE_RENDERER
- O3D_DISPLAY_MASK(mask)
- O3D_MULTISAMPLE
- O3D_END
- };
- CGLPixelFormatObj pixel_format = NULL;
- GLint num_screens = 0;
- if (!CGLChoosePixelFormat(attributes, &pixel_format, &num_screens) &&
- pixel_format) {
- return pixel_format;
- } else {
- // Try a less capable set.
- static const CGLPixelFormatAttribute low_end_attributes[] = {
- O3D_COLOR_AND_DEPTH_SETTINGS
- O3D_STENCIL_SETTINGS
- O3D_HARDWARE_RENDERER
- O3D_DISPLAY_MASK(mask)
- O3D_END
- };
- if (!CGLChoosePixelFormat(low_end_attributes,
- &pixel_format, &num_screens) && pixel_format) {
- return pixel_format;
- } else {
- // Do whatever the superclass supports.
- return [super copyCGLPixelFormatForDisplayMask:mask];
- }
- }
-}
-
-
-- (CGLContextObj)glContext {
- return glContext_;
-}
-
-- (void)setWidth:(int)width height:(int)height {
- width_ = width;
- height_ = height;
- was_resized_ = true;
-}
-
-@end
diff --git a/o3d/plugin/mac/o3d_plugin.r b/o3d/plugin/mac/o3d_plugin.r
deleted file mode 100644
index cf1cc69..0000000
--- a/o3d/plugin/mac/o3d_plugin.r
+++ /dev/null
@@ -1,15 +0,0 @@
-#include <CoreServices/CoreServices.r>
-
-resource 'STR#' (126) { {
- "@@@PluginDescription@@@",
- "@@@PluginName@@@"
-} };
-
-resource 'STR#' (127) { {
- "@@@PluginName@@@"
-} };
-
-resource 'STR#' (128) { {
- "@@@PluginNpapiMimeType@@@",
- ""
-} };
diff --git a/o3d/plugin/mac/overlay_window_mac.h b/o3d/plugin/mac/overlay_window_mac.h
deleted file mode 100644
index f848b8b..0000000
--- a/o3d/plugin/mac/overlay_window_mac.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright 2010, 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_PLUGIN_MAC_OVERLAY_WINDOW_MAC_H_
-#define O3D_PLUGIN_MAC_OVERLAY_WINDOW_MAC_H_
-
-#include <Carbon/Carbon.h>
-
-#include "base/basictypes.h"
-
-// Draws the text indicating how to get out of full-screen mode.
-
-namespace o3d {
-
-class OverlayWindowMac {
- public:
- OverlayWindowMac();
- ~OverlayWindowMac();
-
- // Runs the idle callback for this overlay window, which just
- // transitions the window on to and off of the screen.
- void IdleCallback();
-
- private:
- WindowRef overlay_window_;
- double time_to_hide_overlay_;
-
- DISALLOW_COPY_AND_ASSIGN(OverlayWindowMac);
-};
-
-} // namespace o3d
-
-#endif // O3D_PLUGIN_MAC_OVERLAY_WINDOW_MAC_H_
-
diff --git a/o3d/plugin/mac/overlay_window_mac.mm b/o3d/plugin/mac/overlay_window_mac.mm
deleted file mode 100644
index ea3af06..0000000
--- a/o3d/plugin/mac/overlay_window_mac.mm
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
- * Copyright 2010, 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 "overlay_window_mac.h"
-
-#import "plugin/mac/graphics_utils_mac.h"
-
-#ifdef O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
-
-#define kTransitionTime 1.0
-
-namespace o3d {
-
-// A little wrapper for ATSUSetAttributes to make calling it with one attribute
-// less annoying.
-static void MySetAttribute(ATSUStyle style,
- ATSUAttributeTag tag,
- ByteCount size,
- ATSUAttributeValuePtr value) {
-
- ATSUAttributeTag tags[2] = {tag, 0};
- ByteCount sizes[2] = {size, 0};
- ATSUAttributeValuePtr values[2] = {value, 0};
-
- ATSUSetAttributes(style, 1, tags, sizes, values);
-}
-
-// A little wrapper for ATSUSetLayoutControls to make calling it with one
-// attribute less annoying.
-static void MySetLayoutControl(ATSUTextLayout layout,
- ATSUAttributeTag tag,
- ByteCount size,
- ATSUAttributeValuePtr value) {
-
- ATSUAttributeTag tags[2] = {tag, 0};
- ByteCount sizes[2] = {size, 0};
- ATSUAttributeValuePtr values[2] = {value, 0};
-
- ATSUSetLayoutControls(layout, 1, tags, sizes, values);
-}
-
-// Returns the unicode 16 chars that we need to display as the fullscreen
-// message. Should be disposed with free() after use.
-static UniChar * GetFullscreenDisplayText(int *returned_length) {
- // TODO this will need to be a localized string.
- NSString* ns_display_text = @"Press ESC to exit fullscreen";
- int count = [ns_display_text length];
- UniChar* display_text_16 = (UniChar*) calloc(count, sizeof(UniChar));
-
- [ns_display_text getCharacters:display_text_16];
- *returned_length = count;
- return display_text_16;
-}
-
-
-static void DrawToOverlayWindow(WindowRef overlayWindow) {
- CGContextRef overlayContext = NULL;
- CGFloat kWhiteOpaque[] = {1.0, 1.0, 1.0, 1.0};
- CGFloat kBlackNotOpaque[] = {0.0, 0.0, 0.0, 0.5};
- Rect bounds = {0, 0, 0, 0};
- const char* kOverlayWindowFontName = "Arial";
- const int kPointSize = 22;
- const float kShadowRadius = 5.0;
- const float kRoundRectRadius = 9.0;
- const float kTextLeftMargin = 15.0;
- const float kTextBottomMargin = 22.0;
-
- QDBeginCGContext(GetWindowPort(overlayWindow), &overlayContext);
- GetWindowBounds(overlayWindow, kWindowContentRgn, &bounds);
-
- // Make the global rect local.
- bounds.right -= bounds.left;
- bounds.left = 0;
- bounds.bottom -= bounds.top;
- bounds.top = 0;
-
- CGRect cgTotalRect = Rect2CGRect(bounds);
- CGContextSetShouldSmoothFonts(overlayContext, true);
- CGContextClearRect(overlayContext, cgTotalRect);
-
- CGColorSpaceRef myColorSpace = CGColorSpaceCreateDeviceRGB();
- CGColorRef shadow = CGColorCreate(myColorSpace, kBlackNotOpaque);
- CGColorRef roundRectBackColor = CGColorCreate(myColorSpace, kBlackNotOpaque);
- CGSize shadowOffset = {0.0,0.0};
-
- CGContextSetFillColor(overlayContext, kWhiteOpaque);
- CGContextSetStrokeColor(overlayContext, kWhiteOpaque);
-
- // Draw the round rect background.
- CGContextSaveGState(overlayContext);
- CGContextSetFillColorWithColor(overlayContext, roundRectBackColor);
- CGRect cg_rounded_area =
- CGRectMake(// Offset from left and bottom to give shadow its space.
- kShadowRadius, kShadowRadius,
- // Increase width and height so rounded corners
- // will be clipped out, except at bottom left.
- (bounds.right - bounds.left) + 30,
- (bounds.bottom - bounds.top) + 30);
- // Save state before applying shadow.
- CGContextSetShadowWithColor(overlayContext, shadowOffset,
- kShadowRadius, shadow);
- PaintRoundedCGRect(overlayContext, cg_rounded_area, kRoundRectRadius, true);
- // Restore graphics state to remove shadow.
- CGContextRestoreGState(overlayContext);
-
- // Draw the text.
- int text_length = 0;
- UniChar* display_text = GetFullscreenDisplayText(&text_length);
-
- if ((text_length > 0) && (display_text != NULL)) {
- ATSUStyle style;
- ATSUTextLayout layout;
- ATSUFontID font;
- Fixed pointSize = Long2Fix(kPointSize);
- Boolean is_bold = true;
-
- ATSUCreateStyle(&style);
- ATSUFindFontFromName(kOverlayWindowFontName, strlen(kOverlayWindowFontName),
- kFontFullName, kFontNoPlatformCode, kFontNoScriptCode,
- kFontNoLanguageCode, &font);
-
- MySetAttribute(style, kATSUFontTag, sizeof(font), &font);
- MySetAttribute(style, kATSUSizeTag, sizeof(pointSize), &pointSize);
- MySetAttribute(style, kATSUQDBoldfaceTag, sizeof(Boolean), &is_bold);
-
-
- ATSUCreateTextLayout(&layout);
- ATSUSetTextPointerLocation(layout, display_text,
- kATSUFromTextBeginning, kATSUToTextEnd,
- text_length);
- ATSUSetRunStyle(layout, style, kATSUFromTextBeginning, kATSUToTextEnd);
-
- MySetLayoutControl(layout, kATSUCGContextTag,
- sizeof(CGContextRef), &overlayContext);
-
- // Need to enable this for languages like Japanese to draw as something
- // other than a series of squares.
- ATSUSetTransientFontMatching(layout, true);
-
-
- CGContextSetFillColor(overlayContext, kWhiteOpaque);
- ATSUDrawText(layout, kATSUFromTextBeginning, kATSUToTextEnd,
- X2Fix(kShadowRadius + kTextLeftMargin),
- X2Fix(kShadowRadius + kTextBottomMargin));
- ATSUDisposeStyle(style);
- ATSUDisposeTextLayout(layout);
- free(display_text);
- }
-
- CGColorRelease(roundRectBackColor);
- CGColorRelease(shadow);
- CGColorSpaceRelease (myColorSpace);
-
- QDEndCGContext(GetWindowPort(overlayWindow), &overlayContext);
-}
-
-static OSStatus HandleOverlayWindow(EventHandlerCallRef inHandlerCallRef,
- EventRef inEvent,
- void *inUserData) {
- OSType event_class = GetEventClass(inEvent);
- OSType event_kind = GetEventKind(inEvent);
-
- if (event_class == kEventClassWindow &&
- event_kind == kEventWindowPaint) {
- WindowRef theWindow = NULL;
- GetEventParameter(inEvent, kEventParamDirectObject,
- typeWindowRef, NULL,
- sizeof(theWindow), NULL,
- &theWindow);
- if (theWindow) {
- CallNextEventHandler(inHandlerCallRef, inEvent);
- DrawToOverlayWindow(theWindow);
- }
- }
-
- return noErr;
-}
-
-
-
-static Rect GetOverlayWindowRect(bool visible) {
-#define kOverlayHeight 60
-#define kOverlayWidth 340
- Rect screen_bounds = CGRect2Rect(CGDisplayBounds(CGMainDisplayID()));
- Rect hidden_window_bounds = {screen_bounds.top - kOverlayHeight,
- screen_bounds.right - kOverlayWidth,
- screen_bounds.top,
- screen_bounds.right};
- Rect visible_window_bounds = {screen_bounds.top,
- screen_bounds.right - kOverlayWidth,
- screen_bounds.top + kOverlayHeight,
- screen_bounds.right};
-
- return (visible) ? visible_window_bounds : hidden_window_bounds;
-}
-
-
-static WindowRef CreateOverlayWindow(void) {
- Rect window_bounds = GetOverlayWindowRect(false);
- WindowClass wClass = kOverlayWindowClass;
- WindowRef window = NULL;
- OSStatus err = noErr;
- WindowAttributes overlayAttributes = kWindowNoShadowAttribute |
- kWindowIgnoreClicksAttribute |
- kWindowNoActivatesAttribute |
- kWindowStandardHandlerAttribute;
- EventTypeSpec eventTypes[] = {
- {kEventClassWindow, kEventWindowPaint},
- {kEventClassWindow, kEventWindowShown}
- };
-
- err = CreateNewWindow(wClass,
- overlayAttributes,
- &window_bounds,
- &window);
- if (err)
- return NULL;
-
- SetWindowLevel(window, CGShieldingWindowLevel() + 1);
- InstallEventHandler(GetWindowEventTarget(window), HandleOverlayWindow,
- sizeof(eventTypes)/sizeof(eventTypes[0]), eventTypes,
- NULL, NULL);
- return window;
-}
-
-OverlayWindowMac::OverlayWindowMac()
- : overlay_window_(NULL),
- time_to_hide_overlay_(0.0) {
- overlay_window_ = CreateOverlayWindow();
- ShowWindow(overlay_window_);
- o3d::SlideWindowToRect(overlay_window_,
- Rect2CGRect(GetOverlayWindowRect(true)),
- kTransitionTime);
-
- // Hide the overlay text 4 seconds from now.
- time_to_hide_overlay_ = [NSDate timeIntervalSinceReferenceDate] + 4.0;
-}
-
-OverlayWindowMac::~OverlayWindowMac() {
- HideWindow(overlay_window_);
- ReleaseWindowGroup(GetWindowGroup(overlay_window_));
- DisposeWindow(overlay_window_);
-}
-
-void OverlayWindowMac::IdleCallback() {
- if ((overlay_window_ != NULL) &&
- (time_to_hide_overlay_ != 0.0) &&
- (time_to_hide_overlay_ < [NSDate timeIntervalSinceReferenceDate])) {
- time_to_hide_overlay_ = 0.0;
- SlideWindowToRect(overlay_window_,
- Rect2CGRect(GetOverlayWindowRect(false)),
- kTransitionTime);
- }
-}
-
-} // namespace o3d
-
-#endif // O3D_PLUGIN_ENABLE_FULLSCREEN_MSG
diff --git a/o3d/plugin/mac/plugin_copy_frameworks.sh b/o3d/plugin/mac/plugin_copy_frameworks.sh
deleted file mode 100755
index 8de8ace..0000000
--- a/o3d/plugin/mac/plugin_copy_frameworks.sh
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/bin/sh
-
-# Copy stripped frameworks inside the plugin.
-
-PLUGIN_NPAPI_FILENAME=$1
-
-ditto --arch i386 \
- "${PROJECT_DIR}/../../third_party/cg/files/mac/Cg.framework" \
- "${BUILT_PRODUCTS_DIR}/${PLUGIN_NPAPI_FILENAME}.plugin/Contents/Frameworks/Cg.framework"
-
-# Delete the .svn directories
-find "${BUILT_PRODUCTS_DIR}/${PLUGIN_NPAPI_FILENAME}.plugin/Contents/Frameworks/Cg.framework" -type d -name .svn -print0 | xargs -0 rm -r
-
-ditto --arch i386 \
- "${BUILT_PRODUCTS_DIR}/crash_report_sender.app" \
- "${BUILT_PRODUCTS_DIR}/${PLUGIN_NPAPI_FILENAME}.plugin/Contents/Resources/crash_report_sender.app"
-
-ditto --arch i386 \
- "${BUILT_PRODUCTS_DIR}/crash_inspector" \
- "${BUILT_PRODUCTS_DIR}/${PLUGIN_NPAPI_FILENAME}.plugin/Contents/Resources/crash_inspector"
diff --git a/o3d/plugin/mac/plugin_fix_install_names.sh b/o3d/plugin/mac/plugin_fix_install_names.sh
deleted file mode 100755
index a2cdbf0..0000000
--- a/o3d/plugin/mac/plugin_fix_install_names.sh
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/bin/sh
-
-# Make plugin look in its private Frameworks directory for these frameworks.
-
-
-# Cg.framework
-/usr/bin/install_name_tool -change \
- @executable_path/../Library/Frameworks/Cg.framework/Cg \
- @loader_path/../Frameworks/Cg.framework/Cg \
- "${BUILT_PRODUCTS_DIR}/${EXECUTABLE_PATH}"
diff --git a/o3d/plugin/mac/plugin_logging-mac.mm b/o3d/plugin/mac/plugin_logging-mac.mm
deleted file mode 100644
index 674f0ca..0000000
--- a/o3d/plugin/mac/plugin_logging-mac.mm
+++ /dev/null
@@ -1,242 +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 code to perform the necessary logging operations
-// including:
-// - initializing logging object
-// - aggregating metrics
-// - uploading metrics to the stats server
-
-#include <build/build_config.h>
-#include "statsreport/const-mac.h"
-#include "core/cross/types.h"
-#include "statsreport/metrics.h"
-#include "plugin/cross/plugin_logging.h"
-#include "plugin/cross/plugin_metrics.h"
-#include "statsreport/common/const_product.h"
-#include "statsreport/uploader.h"
-
-namespace o3d {
-
-
-#define kPrefString @"O3D_STATS"
-#define kUserKey @"Google_O3D_User"
-
-
-PluginLogging::PluginLogging() : timer_(new HighresTimer()),
- running_time_(0),
- prev_uptime_seconds_(0),
- prev_cputime_seconds_(0) {
- DLOG(INFO) << "Creating logger.";
- timer_->Start();
-}
-
-bool PluginLogging::UpdateLogging() {
- // Check that sufficient time has passed since last aggregation
- // Otherwise we can just return
- if (timer_->GetElapsedMs() <
- static_cast<unsigned>(kStatsAggregationIntervalMSec))
- return false;
-
- // Sufficient time has passed, let's process
- // Reset timer
- timer_->Start();
- // We are not exiting just yet so pass false for that argument
- // And we don't have to force it, so pass false for forcing
- return ProcessMetrics(false, false, false);
-}
-
-
-
-void PluginLogging::RecordProcessTimes() {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- ProcessSerialNumber myProcess = {0, kCurrentProcess};
-
- NSDictionary* processDict = (NSDictionary*)ProcessInformationCopyDictionary(
- &myProcess,
- kProcessDictionaryIncludeAllInformationMask);
-
- ProcessInfoExtendedRec info;
- bzero(&info, sizeof(info));
- GetProcessInformation(&myProcess, (ProcessInfoRec*)&info);
-
- NSDate* launchDate = [processDict objectForKey:@"LSLaunchTime"];
- NSDate* nowDate = [NSDate dateWithTimeIntervalSinceNow:0];
- NSTimeInterval uptime = [nowDate timeIntervalSinceDate:launchDate];
-
- uint64 additional_uptime = uptime - prev_uptime_seconds_;
- metric_uptime_seconds += additional_uptime;
- running_time_ += additional_uptime;
- prev_uptime_seconds_ = uptime;
-
- uint64 cputime = ((double)info.processActiveTime) / 60.0;
- metric_cpu_time_seconds += (cputime - prev_cputime_seconds_);
- prev_cputime_seconds_ = cputime;
-
- [pool release];
-}
-
-static NSString* generateGUID() {
- CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
- NSString* returned = (NSString*)CFUUIDCreateString(kCFAllocatorDefault,
- uuidRef);
- CFRelease(uuidRef);
- return returned;
-}
-
-
-// Read a pref string for current user, but global to all apps.
-static NSString* ReadGlobalPreferenceString(NSString *key) {
- return (NSString *)CFPreferencesCopyValue((CFStringRef)key,
- kCFPreferencesAnyApplication,
- kCFPreferencesCurrentUser,
- kCFPreferencesCurrentHost);
-}
-
-
-// Write a pref string for the current user, but global to all apps.
-static void WriteGlobalPreferenceString(NSString *key,
- NSString *value) {
- CFPreferencesSetValue((CFStringRef)key,
- (CFPropertyListRef)value,
- kCFPreferencesAnyApplication,
- kCFPreferencesCurrentUser,
- kCFPreferencesCurrentHost);
-
- CFPreferencesSynchronize(kCFPreferencesAnyApplication,
- kCFPreferencesCurrentUser,
- kCFPreferencesCurrentHost);
-}
-
-
-static const char *GetUserID(void) {
- static NSString* id_str = NULL;
-
- if (id_str == NULL) {
- // if not in cache, try to read it
- id_str = ReadGlobalPreferenceString(kUserKey);
-
- // if it was not stored, then create and store it
- if (!id_str) {
- id_str = generateGUID();
- WriteGlobalPreferenceString(kUserKey, id_str);
- }
- }
- return [id_str UTF8String];
-}
-
-
-bool PluginLogging::ProcessMetrics(const bool exiting,
- const bool force_report,
- const bool save_old_metrics) {
- DLOG(INFO) << "ProcessMetrics()";
- // Grab incremental process times, has to be done each time
- // around the loop, because - well - time passes between
- // iterations :)
- RecordProcessTimes();
-
- // This mutex protects the writing to the registry. This way,
- // if we have multiple instances attempting to aggregate at
- // once, they won't overwrite one another.
-
- // 1. return if we can't get mutex
-
-
- if (exiting) {
- // If we're exiting, we aggregate to make sure that we record
- // the tail activity for posterity. We don't report, because
- // that might delay the process exit arbitrarily, and we don't
- // want that.
- // We also make sure to add a sample to the running time
- metric_running_time_seconds.AddSample(running_time_);
- DoAggregateMetrics();
- } else {
- // TODO: placeholder - where is this supposed to come from?
- std::string user_id(GetUserID());
- std::string ui_param("ui=");
- std::string client_id_argument = ui_param + user_id;
- std::string user_agent8 = std::string(kUserAgent) +
- PRODUCT_VERSION_STRING;
- DoAggregateAndReportMetrics(client_id_argument.c_str(),
- user_agent8.c_str(), force_report,
- save_old_metrics);
- }
-
-
- // 2. release mutex
-
- return true;
-}
-
-void PluginLogging::DoAggregateMetrics() {
- DLOG(INFO) << "DoAggregateMetrics()";
- stats_report::AggregateMetrics();
-}
-
-bool PluginLogging::DoAggregateAndReportMetrics(
- const char* extra_url_arguments,
- const char* user_agent,
- const bool force_report,
- const bool save_old_metrics) {
- DLOG(INFO) << "DoAggregateAndReportMetrics()";
- // AggregateAndReportMetrics returns true if metrics were uploaded
- return stats_report::AggregateAndReportMetrics(extra_url_arguments,
- user_agent,
- force_report,
- save_old_metrics);
-}
-
-void PluginLogging::SetTimer(HighresTimer* timer) {
- timer_.reset(timer);
-}
-
-
-PluginLogging* PluginLogging::InitializeUsageStatsLogging() {
- bool opt_in = GetOptInKeyValue();
-
- return CreateUsageStatsLogger<PluginLogging>(opt_in);
-}
-
-bool PluginLogging::GetOptInKeyValue(void) {
-#ifdef NDEBUG
- NSString *value = ReadGlobalPreferenceString(kPrefString);
- return ![value isEqualToString:@"NO"];
-#else
- return true;
-#endif
-}
-
-void PluginLogging::ClearLogs() {
- stats_report::ResetPersistentMetrics();
-}
-
-} // namespace o3d
diff --git a/o3d/plugin/mac/plugin_mac.h b/o3d/plugin/mac/plugin_mac.h
deleted file mode 100644
index a6cc30a..0000000
--- a/o3d/plugin/mac/plugin_mac.h
+++ /dev/null
@@ -1,116 +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_PLUGIN_MAC_PLUGIN_MAC_H_
-#define O3D_PLUGIN_MAC_PLUGIN_MAC_H_
-
-#include <CoreFoundation/CoreFoundation.h>
-#include <npfunctions.h>
-#include <AGL/agl.h>
-#include <vector>
-
-// Just for o3d::Event::Button at the moment.
-#include "core/cross/event.h"
-
-namespace o3d {
-
-class DisplayMode;
-
-// RenderTimer maintains an animation timer (nominally running at 60fps)
-//
-// Keeps track of the current NPP instances running in the browser and then
-// renders each one during each timer callback.
-class RenderTimer {
- public:
- RenderTimer() {}
-
- void Start();
- void Stop();
-
- void AddInstance(NPP instance);
- void RemoveInstance(NPP instance);
-
- typedef std::vector<NPP>::iterator InstanceIterator;
-
- private:
- RenderTimer(const RenderTimer&);
-
- static void TimerCallback(CFRunLoopTimerRef timer, void* info);
- CFRunLoopTimerRef timerRef_;
- static std::vector<NPP> instances_;
-};
-
-extern RenderTimer gRenderTimer;
-
-void InitializeBreakpad();
-void ShutdownBreakpad();
-
-
-void* SafariBrowserWindowForWindowRef(WindowRef theWindow);
-
-void* SelectedTabForSafariBrowserWindow(void* cocoaWindow);
-
-void ReleaseSafariBrowserWindow(void* browserWindow);
-
-
-// Some miscellaneous helper functions...
-
-void GetCurrentDisplayMode(DisplayMode *mode);
-
-void CFReleaseIfNotNull(CFTypeRef cf);
-
-
-// Converts an old style Mac HFS path eg "HD:Users:xxx:file.zip" into a standard
-// Posix path eg "/Users/xxx/file.zip" Assumes UTF8 in and out, returns a block
-// of memory allocated with new, so you'll want to delete this at some point.
-// Returns NULL in the event of an error.
-char* CreatePosixFilePathFromHFSFilePath(const char* hfsPath);
-
-bool HandleCarbonEvent(EventRecord* the_event, NPP instance);
-
-// initiated_from_browser indicates whether the event came from the
-// browser's window. It will be false if the event originated from the
-// full-screen window.
-bool HandleCocoaEvent(NPP instance, NPCocoaEvent* the_event,
- bool initiated_from_browser);
-
-o3d::Event::Button MacOSMouseButtonNumberToO3DButton(int inButton);
-
-bool GetBrowserVersionInfo(int *returned_major,
- int *returned_minor,
- int *returned_bugfix);
-
-bool UseSoftwareRenderer();
-
-} // namespace o3d
-
-#endif // O3D_PLUGIN_MAC_PLUGIN_MAC_H_
diff --git a/o3d/plugin/mac/plugin_mac.mm b/o3d/plugin/mac/plugin_mac.mm
deleted file mode 100644
index 509a465..0000000
--- a/o3d/plugin/mac/plugin_mac.mm
+++ /dev/null
@@ -1,717 +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 <GL/glew.h>
-#include "plugin_mac.h"
-#include "Breakpad.h"
-#include <Cocoa/Cocoa.h>
-#include <QuickTime/QuickTime.h>
-#include "plugin/cross/o3d_glue.h"
-#include "plugin/cross/main.h"
-#include "core/mac/display_window_mac.h"
-#include "core/cross/gl/renderer_gl.h"
-#include "plugin/mac/graphics_utils_mac.h"
-#import "plugin/mac/o3d_layer.h"
-
-
-#if !defined(O3D_INTERNAL_PLUGIN)
-BreakpadRef gBreakpadRef = NULL;
-#endif
-
-using glue::_o3d::PluginObject;
-using o3d::DisplayWindowMac;
-
-@interface NSWindowController (plugin_hack)
-- (id)selectedTab;
-@end
-
-namespace o3d {
-
-// Returns the version number of the running Mac browser, as parsed from
-// the short version string in the plist of the app's bundle.
-bool GetBrowserVersionInfo(int *returned_major,
- int *returned_minor,
- int *returned_bugfix) {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- int major = 0;
- int minor = 0;
- int bugfix = 0;
- NSBundle *app_bundle = [NSBundle mainBundle];
- NSString *versionString =
- [app_bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
-
- if ([versionString length]) {
- NSScanner *versionScanner = [NSScanner scannerWithString:versionString];
- NSCharacterSet *dotSet =
- [NSCharacterSet characterSetWithCharactersInString:@"."];
- NSCharacterSet *numSet =
- [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
- NSCharacterSet *notNumSet = [numSet invertedSet];
-
- // Skip anything at start that is not a number.
- [versionScanner scanCharactersFromSet:notNumSet intoString:NULL];
-
- // Keep reading values until we get all 3 numbers, or something isn't found.
- if ([versionScanner scanInt:&major])
- if ([versionScanner scanCharactersFromSet:dotSet intoString:NULL])
- if ([versionScanner scanInt:&minor])
- if ([versionScanner scanCharactersFromSet:dotSet intoString:NULL])
- [versionScanner scanInt:&bugfix];
- }
-
- *returned_major = major;
- *returned_minor = minor;
- *returned_bugfix = bugfix;
-
- [pool release];
-
- // If we read any version numbers, then we succeeded.
- return (major || minor || bugfix);
-}
-
-
-// Code for peeking at the selected tab object for a WindowRef in Safari. This
-// is purely so we can detect changes in active tab in Safari, since it does not
-// notify us when our tab is hidden or revealed.
-//
-// If the browser is not Safari these functions should harmlessly be NULL since
-// the walk from windowref to cocoa window (of type "BrowserWindow") to cocoa
-// windowcontroller to selectedTab should harmlessly break down somewhere along
-// the way.
-//
-// This is useful merely for peeking at Safari's internal state for a tab change
-// event, as Safari does not notify us when this happens. It coerces the value
-// to a void*, as the plain .cc files don't like the type id, and we actually
-// only care whether the value changes or not.
-
-
-void ReleaseSafariBrowserWindow(void* browserWindow) {
- if (browserWindow) {
- NSWindow* cocoaWindow = (NSWindow*) browserWindow;
- // Retain the WindowRef so it doesn't go away when we release the
- // NSWindow copy we made.
- WindowRef theWindow = (WindowRef)[cocoaWindow windowRef];
- if (theWindow)
- CFRetain(theWindow);
- [cocoaWindow release];
- }
-}
-
-void* SafariBrowserWindowForWindowRef(WindowRef theWindow) {
- if (theWindow != NULL) {
- NSWindow* cocoaWindow = [[NSWindow alloc] initWithWindowRef:theWindow];
- if (cocoaWindow) {
- if (strcmp(object_getClassName(cocoaWindow), "BrowserWindow") == 0) {
- return cocoaWindow;
- } else {
- // Retain the WindowRef so it doesn't go away when we release the
- // NSWindow copy we made.
- CFRetain(theWindow);
- [cocoaWindow release];
- }
- }
- }
- return NULL;
-}
-
-void* SelectedTabForSafariBrowserWindow(void* browserWindow) {
- id selectedTab = nil;
- NSWindow* cocoaWindow = (NSWindow*) browserWindow;
- if (cocoaWindow) {
- @try {
- selectedTab = [[cocoaWindow windowController] selectedTab];
- } @catch(NSException* exc) {
- }
- }
- return (void*) selectedTab;
-}
-
-// Detects when Safari has hidden or revealed our tab.
-// If a hide event is detected, it sets the mac_surface_hidden_ flag and hides
-// the surface.
-// Later, if the mac_surface_hidden_ flag is set but we are no longer hidden,
-// ie DetectTabHiding is now returning false, it restores the surface to the
-// previous state.
-void ManageSafariTabSwitching(PluginObject* obj) {
- // This is only needed when we are using an AGL context and need to hide
- // and show it.
- if (!obj->mac_agl_context_)
- return;
-
- if (obj->DetectTabHiding()) {
- if (!obj->mac_surface_hidden_) {
- obj->mac_surface_hidden_ = true;
- GLint rect[4] = {0,0,0,0};
- aglSetInteger(obj->mac_agl_context_, AGL_BUFFER_RECT, rect);
- aglEnable(obj->mac_agl_context_, AGL_BUFFER_RECT);
- }
- } else if (obj->mac_surface_hidden_) {
- obj->mac_surface_hidden_ = false;
- aglSetInteger(obj->mac_agl_context_, AGL_BUFFER_RECT,
- obj->last_buffer_rect_);
- aglEnable(obj->mac_agl_context_, AGL_BUFFER_RECT);
- }
-}
-
-
-#pragma mark ____RenderTimer
-
-RenderTimer gRenderTimer;
-std::vector<NPP> RenderTimer::instances_;
-
-void RenderTimer::Start() {
- CFRunLoopTimerContext timerContext;
- memset(&timerContext, 0, sizeof(timerContext));
- timerContext.info = (void*)NULL;
-
- if (!timerRef_) {
- timerRef_ = CFRunLoopTimerCreate(NULL,
- 1.0,
- 1.0 / 60.0,
- 0,
- 0,
- TimerCallback,
- &timerContext);
-
- CFRunLoopAddTimer(CFRunLoopGetCurrent(), timerRef_, kCFRunLoopCommonModes);
- }
-}
-
-void RenderTimer::Stop() {
- if (timerRef_) {
- CFRunLoopTimerInvalidate(timerRef_);
- timerRef_ = NULL;
- }
- instances_.clear(); // this should already be empty, but make sure
-}
-
-void RenderTimer::AddInstance(NPP instance) {
- // avoid adding the same instance twice!
- InstanceIterator i = find(instances_.begin(), instances_.end(), instance);
- if (i == instances_.end()) {
- instances_.push_back(instance);
- }
-}
-
-void RenderTimer::RemoveInstance(NPP instance) {
- InstanceIterator i = find(instances_.begin(), instances_.end(), instance);
- if (i != instances_.end()) {
- instances_.erase(i);
- }
-}
-
-void RenderTimer::TimerCallback(CFRunLoopTimerRef timer, void* info) {
- HANDLE_CRASHES;
- int instance_count = instances_.size();
- for (int i = 0; i < instance_count; ++i) {
- NPP instance = instances_[i];
- PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
-
- // RenderClient() and Tick() may cause events to be processed,
- // leading to reentrant calling of this code. Detect and avoid
- // this case.
- if (obj->client()->IsRendering() || obj->client()->IsTicking()) {
- continue;
- }
-
- bool in_fullscreen = obj->GetFullscreenMacWindow();
-
- if (obj->drawing_model_ == NPDrawingModelCoreAnimation &&
- !in_fullscreen) {
- O3DLayer* o3dLayer = static_cast<O3DLayer*>(obj->gl_layer_);
- if (o3dLayer) {
- obj->client()->Tick();
-
- if (obj->client()->NeedsRender()) {
- [o3dLayer setNeedsDisplay];
- }
- }
- continue;
- }
-
- ManageSafariTabSwitching(obj);
- obj->client()->Tick();
-
- // It's possible that event processing may have torn down the
- // full-screen window in the call above.
- in_fullscreen = obj->GetFullscreenMacWindow();
-
- if (in_fullscreen) {
- obj->GetFullscreenMacWindow()->IdleCallback();
- }
-
- // We're visible if (a) we are in fullscreen mode, (b) we are using
- // QuickDraw and our cliprect height and width are both a sensible size, ie
- // > 1 pixel, or (c) we are using Core Graphics.
- //
- // We don't check for 0 as we have to size to 1 x 1 on occasion rather than
- // 0 x 0 to avoid crashing the Apple software renderer, but do not want to
- // actually draw to a 1 x 1 pixel area.
- bool plugin_visible = in_fullscreen ||
- (obj->drawing_model_ == NPDrawingModelQuickDraw &&
- obj->last_buffer_rect_[2] > 1 && obj->last_buffer_rect_[3] > 1) ||
- obj->drawing_model_ == NPDrawingModelCoreGraphics;
-
- if (plugin_visible && obj->renderer()) {
- if (obj->client()->NeedsRender()) {
- // Force a sync to the VBL (once per timer callback)
- // to avoid tearing, if using GL.
- GLint sync = (i == 0);
- if (obj->mac_cgl_context_) {
- CGLSetParameter(obj->mac_cgl_context_, kCGLCPSwapInterval, &sync);
- } else if (obj->mac_agl_context_) {
- aglSetInteger(obj->mac_agl_context_, AGL_SWAP_INTERVAL, &sync);
- }
-
- if (obj->drawing_model_ == NPDrawingModelCoreGraphics) {
- NPRect rect = { 0 };
- rect.bottom = obj->height();
- rect.right = obj->width();
- NPN_InvalidateRect(instance, &rect);
- } else {
- if (in_fullscreen) {
- obj->GetFullscreenMacWindow()->PrepareToRender();
- }
- obj->client()->RenderClient(true);
- if (in_fullscreen) {
- obj->GetFullscreenMacWindow()->FinishRendering();
- }
- }
- }
- }
- }
-}
-
-#pragma mark ____BREAKPAD
-
-bool IsBrowserChrome() {
- NSString *processName = [[NSProcessInfo processInfo] processName];
- NSString *chromeString = @"Google Chrome Helper";
- bool areEqual = [processName isEqualToString:chromeString];
- return areEqual;
-}
-
-bool ExceptionCallback(int exception_type,
- int exception_code,
- mach_port_t crashing_thread,
- void* context) {
- return BreakpadEnabler::IsEnabled();
-}
-
-void InitializeBreakpad() {
- // Don't initialize if we are running in the Chrome browser
- // since Chrome already runs Breakpad and on Mac the two
- // instances collide and break crash dump reporting.
- if (!gBreakpadRef && !IsBrowserChrome()) {
- NSBundle* bundle = [NSBundle bundleWithIdentifier:@"com.google.o3d"];
- NSDictionary* info = [bundle infoDictionary];
-
- gBreakpadRef = BreakpadCreate(info);
- BreakpadSetFilterCallback(gBreakpadRef, ExceptionCallback, NULL);
- }
-}
-
-void ShutdownBreakpad() {
- BreakpadRelease(gBreakpadRef);
- gBreakpadRef = NULL;
-}
-
-#pragma mark ____MISCELLANEOUS_HELPER
-
-void CFReleaseIfNotNull(CFTypeRef cf) {
- if (cf != NULL)
- CFRelease(cf);
-}
-
-
-
-// Converts an old style Mac HFS path eg "HD:Users:xxx:file.zip" into
-// a standard Posix path eg "/Users/xxx/file.zip"
-// Assumes UTF8 in and out, returns a block of memory allocated with new,
-// so you'll want to delete this at some point.
-// Returns NULL in the event of an error.
-char* CreatePosixFilePathFromHFSFilePath(const char* hfsPath) {
- CFStringRef cfHFSPath = NULL;
- CFStringRef cfPosixPath = NULL;
- CFURLRef cfHFSURL = NULL;
- char* posix_path = NULL;
-
- if (hfsPath && hfsPath[0]) {
- cfHFSPath = CFStringCreateWithCString(kCFAllocatorDefault,
- hfsPath,
- kCFStringEncodingUTF8);
- if (cfHFSPath) {
- cfHFSURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
- cfHFSPath,
- kCFURLHFSPathStyle,
- false);
- if (cfHFSURL) {
- cfPosixPath = CFURLCopyFileSystemPath(cfHFSURL, kCFURLPOSIXPathStyle);
- if (cfPosixPath) {
- // returned value includes space for 0 terminator byte
- int maxSize =
- CFStringGetMaximumSizeOfFileSystemRepresentation(cfPosixPath);
- posix_path = new char [maxSize];
- CFStringGetFileSystemRepresentation(cfPosixPath,
- posix_path,
- maxSize);
- }
- }
- }
- }
- CFReleaseIfNotNull(cfHFSPath);
- CFReleaseIfNotNull(cfPosixPath);
- CFReleaseIfNotNull(cfHFSURL);
- return posix_path;
-}
-
-
-
-#pragma mark ____SCREEN_RESOLUTION_MANAGEMENT
-
-
-// Constant kO3D_MODE_OFFSET is added to the position in the array returned by
-// CGDisplayAvailableModes to make it an ID. This makes IDs distinguishable from
-// array positions when debugging, and also means that ID 0 can have a special
-// meaning (current mode) rather than meaning the first resolution in the list.
-const int kO3D_MODE_OFFSET = 100;
-
-// Extracts data from the Core Graphics screen mode data passed in.
-// Returns false if the mode is an undesirable one, ie if it is not safe for
-// the current screen hardware, is stretched, or is interlaced.
-// Returns various information about the mode in the var parameters passed.
-static bool ExtractDisplayModeData(NSDictionary *mode_dict,
- int *width,
- int *height,
- int *refresh_rate,
- int *bits_per_pixel) {
-
- *width = [[mode_dict objectForKey:(id)kCGDisplayWidth] intValue];
- *height = [[mode_dict objectForKey:(id)kCGDisplayHeight] intValue];
- *refresh_rate = [[mode_dict objectForKey:(id)kCGDisplayRefreshRate] intValue];
- *bits_per_pixel =
- [[mode_dict objectForKey:(id)kCGDisplayBitsPerPixel] intValue];
-
- if (![mode_dict objectForKey:(id)kCGDisplayModeIsSafeForHardware])
- return false;
-
- if ([mode_dict objectForKey:(id)kCGDisplayModeIsStretched])
- return false;
-
- if ([mode_dict objectForKey:(id)kCGDisplayModeIsInterlaced])
- return false;
-
- return true;
-}
-
-
-// Returns information on a display mode, which is mode n - kO3D_MODE_OFFSET
-// in the raw list returned by CGDisplayAvailableModes on the main screen,
-// with kO3D_MODE_OFFSET + 0 being the first entry in the array.
-static bool GetOtherDisplayMode(int id, o3d::DisplayMode *mode) {
- NSArray *mac_modes = (NSArray*) CGDisplayAvailableModes(CGMainDisplayID());
- int num_modes = [mac_modes count];
- int array_offset = id - kO3D_MODE_OFFSET;
-
- if (array_offset >= 0 && array_offset < num_modes) {
- int width = 0;
- int height = 0;
- int refresh_rate = 0;
- int bpp = 0;
-
- ExtractDisplayModeData([mac_modes objectAtIndex:array_offset],
- &width, &height, &refresh_rate, &bpp);
- mode->Set(width, height, refresh_rate, id);
- return true;
- }
-
- return false;
-}
-
-
-static int GetCGDisplayModeID(NSDictionary* mode_dict) {
- return [[mode_dict valueForKey:@"Mode"] intValue];
-}
-
-// Returns DisplayMode data for the current state of the main display.
-void GetCurrentDisplayMode(o3d::DisplayMode *mode) {
- int width = 0;
- int height = 0;
- int refresh_rate = 0;
- int bpp = 0;
- int mode_id = 0;
-
- NSDictionary* current_mode =
- (NSDictionary*)CGDisplayCurrentMode(CGMainDisplayID());
-
- // To get the O3D mode id of the current mode, we need to find it in the list
- // of all modes, since the id we use is it's index + kO3D_MODE_OFFSET.
-
- // Get the CG id of current mode so that we will recognize it.
- int current_cg_id = GetCGDisplayModeID(current_mode);
-
- // Get list of all modes.
- NSArray *modes = (NSArray*)CGDisplayAvailableModes(CGMainDisplayID());
- int num_modes = [modes count];
-
- // Find current mode in that list, and compute the O3D id for it.
- for (int x = 0 ; x < num_modes ; x++) {
- if (GetCGDisplayModeID([modes objectAtIndex:x]) == current_cg_id) {
- mode_id = x + kO3D_MODE_OFFSET;
- break;
- }
- }
-
- ExtractDisplayModeData(current_mode, &width, &height, &refresh_rate, &bpp);
- mode->Set(width, height, refresh_rate, mode_id);
-}
-
-
-
-} // namespace o3d
-
-
-bool PluginObject::GetDisplayMode(int id, o3d::DisplayMode *mode) {
- if (id == o3d::Renderer::DISPLAY_MODE_DEFAULT) {
- GetCurrentDisplayMode(mode);
- return true;
- } else {
- return GetOtherDisplayMode(id, mode);
- }
-}
-
-
-void PluginObject::GetDisplayModes(std::vector<o3d::DisplayMode> *modes) {
- NSArray* mac_modes = (NSArray*)CGDisplayAvailableModes(CGMainDisplayID());
- int num_modes = [mac_modes count];
- std::vector<o3d::DisplayMode> modes_found;
-
- for (int i = 0; i < num_modes; ++i) {
- int width = 0;
- int height = 0;
- int refresh_rate = 0;
- int bpp = 0;
-
- if (o3d::ExtractDisplayModeData([mac_modes objectAtIndex:i],
- &width,
- &height,
- &refresh_rate,
- &bpp) && bpp == 32)
- modes_found.push_back(o3d::DisplayMode(width, height, refresh_rate,
- i + o3d::kO3D_MODE_OFFSET));
- }
-
- modes->swap(modes_found);
-}
-
-
-#pragma mark ____FULLSCREEN_SWITCHING
-
-namespace glue {
-namespace _o3d {
-
-bool PluginObject::RequestFullscreenDisplay() {
- // If already in fullscreen mode, do nothing.
- if (GetFullscreenMacWindow())
- return false;
-
- int target_width = 0;
- int target_height = 0;
-
- if (fullscreen_region_valid_ &&
- fullscreen_region_mode_id_ != Renderer::DISPLAY_MODE_DEFAULT) {
- o3d::DisplayMode the_mode;
- if (GetDisplayMode(fullscreen_region_mode_id_, &the_mode)) {
- target_width = the_mode.width();
- target_height = the_mode.height();
- }
- }
-
- was_offscreen_ = IsOffscreenRenderingEnabled();
- if (was_offscreen_) {
- DisableOffscreenRendering();
- }
-
- FullscreenWindowMac* fullscreen_window =
- FullscreenWindowMac::Create(this, target_width, target_height);
- if (!fullscreen_window) {
- if (was_offscreen_) {
- EnableOffscreenRendering();
- }
- return false;
- }
- SetFullscreenMacWindow(fullscreen_window);
- Rect bounds = o3d::CGRect2Rect(fullscreen_window->GetWindowBounds());
-
- renderer()->SetClientOriginOffset(0, 0);
- renderer_->Resize(bounds.right - bounds.left, bounds.bottom - bounds.top);
-
- fullscreen_ = true;
- client()->SendResizeEvent(renderer_->width(), renderer_->height(), true);
-
- return true;
-}
-
-void PluginObject::CancelFullscreenDisplay() {
- FullscreenWindowMac* window = GetFullscreenMacWindow();
-
- // if not in fullscreen mode, do nothing
- if (!window)
- return;
-
- // The focus change during closing of the fullscreen window may
- // cause the plugin to become reentrant. Store the full-screen
- // window on the stack to prevent attempting to shut down twice.
- SetFullscreenMacWindow(NULL);
- window->Shutdown(last_buffer_rect_);
- delete window;
- renderer_->Resize(prev_width_, prev_height_);
- fullscreen_ = false;
- client()->SendResizeEvent(prev_width_, prev_height_, false);
-
- if (was_offscreen_) {
- EnableOffscreenRendering();
- }
-
- // Somehow the browser window does not automatically activate again
- // when we close the fullscreen window, so explicitly reactivate it.
- if (mac_cocoa_window_) {
- NSWindow* browser_window = (NSWindow*) mac_cocoa_window_;
- [browser_window makeKeyAndOrderFront:browser_window];
- } else if (mac_window_) {
- SelectWindow(mac_window_);
- }
-}
-
-#define PFA(number) static_cast<NSOpenGLPixelFormatAttribute>(number)
-
-#define O3D_NSO_COLOR_AND_DEPTH_SETTINGS NSOpenGLPFAClosestPolicy, \
- NSOpenGLPFAColorSize, PFA(24), \
- NSOpenGLPFAAlphaSize, PFA(8), \
- NSOpenGLPFADepthSize, PFA(24), \
- NSOpenGLPFADoubleBuffer,
-// The Core Animation code path on 10.6 core dumps if the
-// NSOpenGLPFAPixelBuffer and NSOpenGLPFAWindow attributes are
-// specified. It seems risky for the 10.5 code path if they aren't,
-// since this actual CGLPixelFormatObj is used to create the pbuffer's
-// context, but no ill effects have been seen there so leaving them
-// out for now.
-#define O3D_NSO_PBUFFER_SETTINGS
-#define O3D_NSO_STENCIL_SETTINGS NSOpenGLPFAStencilSize, PFA(8),
-#define O3D_NSO_HARDWARE_RENDERER \
- NSOpenGLPFAAccelerated, NSOpenGLPFANoRecovery,
-#define O3D_NSO_MULTISAMPLE \
- NSOpenGLPFAMultisample, NSOpenGLPFASamples, PFA(4),
-#define O3D_NSO_END PFA(0)
-
-CGLContextObj PluginObject::GetFullscreenShareContext() {
- if (mac_fullscreen_nsopenglcontext_ == NULL) {
- static const NSOpenGLPixelFormatAttribute attributes[] = {
- O3D_NSO_COLOR_AND_DEPTH_SETTINGS
- O3D_NSO_PBUFFER_SETTINGS
- O3D_NSO_STENCIL_SETTINGS
- O3D_NSO_HARDWARE_RENDERER
- O3D_NSO_MULTISAMPLE
- O3D_NSO_END
- };
- NSOpenGLPixelFormat* pixel_format =
- [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes];
- if (!pixel_format) {
- // Try a less capable set.
- static const NSOpenGLPixelFormatAttribute low_end_attributes[] = {
- O3D_NSO_COLOR_AND_DEPTH_SETTINGS
- O3D_NSO_PBUFFER_SETTINGS
- O3D_NSO_STENCIL_SETTINGS
- O3D_NSO_HARDWARE_RENDERER
- O3D_NSO_END
- };
- pixel_format =
- [[NSOpenGLPixelFormat alloc] initWithAttributes:low_end_attributes];
- }
- if (pixel_format) {
- mac_fullscreen_nsopenglpixelformat_ = pixel_format;
-
- NSOpenGLContext* context =
- [[NSOpenGLContext alloc] initWithFormat:pixel_format
- shareContext:nil];
- mac_fullscreen_nsopenglcontext_ = context;
- } else {
- DLOG(ERROR) << "Error choosing NSOpenGLPixelFormat.";
- }
- }
-
- NSOpenGLContext* context = (NSOpenGLContext*) mac_fullscreen_nsopenglcontext_;
- return (CGLContextObj) [context CGLContextObj];
-}
-
-void* PluginObject::GetFullscreenNSOpenGLContext() {
- return mac_fullscreen_nsopenglcontext_;
-}
-
-CGLPixelFormatObj PluginObject::GetFullscreenCGLPixelFormatObj() {
- NSOpenGLPixelFormat* pixel_format =
- (NSOpenGLPixelFormat*) mac_fullscreen_nsopenglpixelformat_;
- if (pixel_format == nil) {
- return NULL;
- }
- return (CGLPixelFormatObj) [pixel_format CGLPixelFormatObj];
-}
-
-void PluginObject::CleanupFullscreenOpenGLContext() {
- NSOpenGLContext* context =
- (NSOpenGLContext*) mac_fullscreen_nsopenglcontext_;
- mac_fullscreen_nsopenglcontext_ = NULL;
- if (context) {
- [context release];
- }
- NSOpenGLPixelFormat* format =
- (NSOpenGLPixelFormat*) mac_fullscreen_nsopenglpixelformat_;
- mac_fullscreen_nsopenglpixelformat_ = NULL;
- if (format) {
- [format release];
- }
-}
-
-void PluginObject::SetMacCGLContext(CGLContextObj context) {
- mac_cgl_context_ = context;
- if (renderer_) {
-#ifdef RENDERER_GLES2
- ((o3d::RendererGLES2*) renderer_)->set_mac_cgl_context(context);
-#else
- ((o3d::RendererGL*) renderer_)->set_mac_cgl_context(context);
-#endif
- }
-}
-
-} // namespace glue
-} // namespace o3d
diff --git a/o3d/plugin/mac/plugin_metrics-mac.cc b/o3d/plugin/mac/plugin_metrics-mac.cc
deleted file mode 100644
index 56c3a14..0000000
--- a/o3d/plugin/mac/plugin_metrics-mac.cc
+++ /dev/null
@@ -1,85 +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 "statsreport/metrics.h"
-#include "plugin/cross/plugin_metrics.h"
-
-namespace o3d {
-DEFINE_METRIC_integer(system_type);
-
-DEFINE_METRIC_integer(mac_major_version);
-DEFINE_METRIC_integer(mac_minor_version);
-DEFINE_METRIC_integer(mac_bugfix_version);
-
-// User GPU
-DEFINE_METRIC_integer(gpu_vendor_id);
-DEFINE_METRIC_integer(gpu_device_id);
-DEFINE_METRIC_integer(gpu_driver_major_version);
-DEFINE_METRIC_integer(gpu_driver_minor_version);
-DEFINE_METRIC_integer(gpu_driver_bugfix_version);
-DEFINE_METRIC_integer(gpu_vram_size);
-DEFINE_METRIC_bool(direct3d_available);
-
-
-// Shader versions
-DEFINE_METRIC_integer(pixel_shader_main_version);
-DEFINE_METRIC_integer(pixel_shader_sub_version);
-DEFINE_METRIC_integer(vertex_shader_main_version);
-DEFINE_METRIC_integer(vertex_shader_sub_version);
-
-DEFINE_METRIC_bool(POW2_texture_caps);
-DEFINE_METRIC_bool(NONPOW2CONDITIONAL_texture_caps);
-
-DEFINE_METRIC_integer(browser_type);
-DEFINE_METRIC_integer(browser_major_version);
-DEFINE_METRIC_integer(browser_minor_version);
-DEFINE_METRIC_integer(browser_bugfix_version);
-
-DEFINE_METRIC_timing(running_time);
-
-DEFINE_METRIC_count(uptime_seconds);
-DEFINE_METRIC_count(cpu_time_seconds);
-DEFINE_METRIC_timing(running_time_seconds);
-
-DEFINE_METRIC_count(crashes_total);
-DEFINE_METRIC_count(crashes_uploaded);
-DEFINE_METRIC_count(out_of_memory_total);
-
-DEFINE_METRIC_count(bluescreens_total);
-
-// OpenGL Caps - insert more here
-DEFINE_METRIC_integer(gl_major_version);
-DEFINE_METRIC_integer(gl_minor_version);
-DEFINE_METRIC_integer(gl_hlsl_major_version);
-DEFINE_METRIC_integer(gl_hlsl_minor_version);
-
-} // namespace o3d
diff --git a/o3d/plugin/npapi_host_control/win/dispatch_proxy.cc b/o3d/plugin/npapi_host_control/win/dispatch_proxy.cc
deleted file mode 100644
index 64c8c23..0000000
--- a/o3d/plugin/npapi_host_control/win/dispatch_proxy.cc
+++ /dev/null
@@ -1,325 +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.
- */
-
-#define _SCL_SECURE_NO_WARNINGS
-#include "plugin/npapi_host_control/win/dispatch_proxy.h"
-
-#include <atlstr.h>
-#include <dispex.h>
-#include <oaidl.h>
-
-#include <base/scoped_ptr.h>
-#include <algorithm>
-#include <vector>
-
-#include "plugin/npapi_host_control/win/np_browser_proxy.h"
-#include "plugin/npapi_host_control/win/variant_utils.h"
-
-namespace {
-
-// Helper routine that invokes an IDispatchEx interface with argument values
-// provided by NPAPI variant objects.
-HRESULT DispatchInvoke(NPBrowserProxy* browser_proxy,
- IDispatchEx *dispatch,
- DWORD flags,
- DISPID member,
- const NPVariant* arguments,
- int arg_count,
- NPVariant* result) {
- // Convert the NPAPI arguments to COM variant objects.
- scoped_array<CComVariant> local_args(new CComVariant[arg_count]);
- for (int x = 0; x < arg_count; ++x) {
- // Note that IDispatch expects arguments in reverse order.
- NPVariantToVariant(browser_proxy,
- &arguments[x],
- &local_args[arg_count - x - 1]);
- }
-
- HRESULT hr = S_OK;
- CComVariant return_arg;
- DISPPARAMS disp_arguments = {0};
- disp_arguments.cArgs = arg_count;
- disp_arguments.rgvarg = local_args.get();
- hr = dispatch->InvokeEx(member,
- LOCALE_SYSTEM_DEFAULT,
- static_cast<WORD>(flags),
- &disp_arguments,
- &return_arg,
- NULL,
- NULL);
-
- // If the invoke succeeded, then convert and store the return argument.
- if (SUCCEEDED(hr)) {
- VariantToNPVariant(browser_proxy, &return_arg, result);
- }
-
- return hr;
-}
-
-} // unnamed namespace
-
-DispatchProxy::DispatchProxy(IDispatchEx* dispatch,
- NPBrowserProxy* browser_proxy)
- : dispatch_(dispatch),
- browser_proxy_(browser_proxy) {
- _class = &kNPClass;
- referenceCount = 1;
-}
-
-DispatchProxy::~DispatchProxy() {
- ATLASSERT(referenceCount == 0);
- CComPtr<IDispatchEx> dispatchex_object;
- if (browser_proxy_) {
- browser_proxy_->UnregisterDispatchProxy(dispatch_);
- }
-}
-
-DISPID DispatchProxy::GetDispatchId(NPIdentifier name, DWORD flags) const {
- DISPID dispatch_id = -1;
-
- NPUTF8* method_name =
- browser_proxy_->GetBrowserFunctions()->utf8fromidentifier(name);
-
- // Convert the UTF8-NPAPI string to a wide string.
- int required_size = 0;
- required_size = MultiByteToWideChar(CP_UTF8, 0, method_name,
- -1, NULL, 0);
-
- CComBSTR wide_name(required_size - 1);
- MultiByteToWideChar(CP_UTF8, 0, method_name,
- -1, (BSTR) wide_name, required_size);
- dispatch_->GetDispID(wide_name, flags, &dispatch_id);
-
- browser_proxy_->GetBrowserFunctions()->memfree(method_name);
-
- return dispatch_id;
-}
-
-bool DispatchProxy::HasMethod(NPObject *header, NPIdentifier name) {
- DispatchProxy *proxy = static_cast<DispatchProxy*>(header);
- return proxy->GetDispatchId(name, 0) != -1;
-}
-
-bool DispatchProxy::InvokeEntry(NPObject *header,
- NPIdentifier name,
- const NPVariant *args,
- uint32_t arg_count,
- NPVariant *result) {
- DispatchProxy *proxy = static_cast<DispatchProxy*>(header);
-
- DISPID entry_dispid = proxy->GetDispatchId(name, 0);
- if (entry_dispid == -1) {
- return false;
- }
-
- HRESULT hr = DispatchInvoke(proxy->browser_proxy_, proxy->dispatch_,
- DISPATCH_METHOD, entry_dispid, args, arg_count,
- result);
-
- return SUCCEEDED(hr);
-}
-
-bool DispatchProxy::InvokeDefault(NPObject *header,
- const NPVariant *args,
- uint32_t arg_count,
- NPVariant *result) {
- DispatchProxy *proxy = static_cast<DispatchProxy*>(header);
-
- HRESULT hr = DispatchInvoke(proxy->browser_proxy_, proxy->dispatch_,
- DISPATCH_METHOD, DISPID_VALUE, args,
- arg_count, result);
-
- return SUCCEEDED(hr);
-}
-
-bool DispatchProxy::Construct(NPObject *header,
- const NPVariant *args,
- uint32_t arg_count,
- NPVariant *result) {
- DispatchProxy *proxy = static_cast<DispatchProxy*>(header);
-
- HRESULT hr = DispatchInvoke(proxy->browser_proxy_, proxy->dispatch_,
- DISPATCH_CONSTRUCT, DISPID_VALUE, args,
- arg_count, result);
-
- return SUCCEEDED(hr);
-}
-
-bool DispatchProxy::HasProperty(NPObject *header, NPIdentifier name) {
- DispatchProxy *proxy = static_cast<DispatchProxy*>(header);
- return proxy->GetDispatchId(name, 0) != -1;
-}
-
-bool DispatchProxy::GetPropertyEntry(NPObject *header,
- NPIdentifier name,
- NPVariant *variant) {
- DispatchProxy *proxy = static_cast<DispatchProxy*>(header);
- DISPID dispatch_id = proxy->GetDispatchId(name, 0);
- if (dispatch_id == -1) {
- return false;
- }
-
- CComVariant result_value;
- DISPPARAMS invoke_args = {0};
- HRESULT hr = proxy->dispatch_->Invoke(dispatch_id, IID_NULL,
- LOCALE_SYSTEM_DEFAULT,
- DISPATCH_PROPERTYGET,
- &invoke_args,
- &result_value, NULL, 0);
- if (SUCCEEDED(hr)) {
- VariantToNPVariant(proxy->browser_proxy_, &result_value, variant);
- }
-
- return SUCCEEDED(hr);
-}
-
-bool DispatchProxy::SetPropertyEntry(NPObject *header,
- NPIdentifier name,
- const NPVariant *variant) {
- DispatchProxy *proxy = static_cast<DispatchProxy*>(header);
- DISPID dispatch_id = proxy->GetDispatchId(name, fdexNameEnsure);
-
- // Indicate failure if the property does not exist.
- if (dispatch_id == -1) {
- return false;
- }
-
- CComVariant dispatch_variant;
- NPVariantToVariant(proxy->browser_proxy_, const_cast<NPVariant*>(variant),
- &dispatch_variant);
-
- // Prepare the dispatch arguments for the call. Note that the named
- // argument DISPID_PROPERTYPUT is required.
- DISPID put_id = DISPID_PROPERTYPUT;
- DISPPARAMS invoke_args = {0};
- invoke_args.cArgs = 1;
- invoke_args.rgvarg = &dispatch_variant;
- invoke_args.cNamedArgs = 1;
- invoke_args.rgdispidNamedArgs = &put_id;
-
- CComVariant return_arg;
- HRESULT hr = proxy->dispatch_->Invoke(dispatch_id, IID_NULL,
- LOCALE_SYSTEM_DEFAULT,
- DISPATCH_PROPERTYPUT, &invoke_args,
- &return_arg, NULL, NULL);
-
- return SUCCEEDED(hr);
-}
-
-bool DispatchProxy::RemovePropertyEntry(NPObject *header,
- NPIdentifier name) {
- DispatchProxy *proxy = static_cast<DispatchProxy*>(header);
- DISPID dispatch_id = proxy->GetDispatchId(name, 0);
- if (dispatch_id == -1) {
- return true;
- }
-
- HRESULT hr = proxy->dispatch_->DeleteMemberByDispID(dispatch_id);
-
- return SUCCEEDED(hr);
-}
-
-bool DispatchProxy::EnumeratePropertyEntries(NPObject *header,
- NPIdentifier **result,
- uint32_t *count) {
- DispatchProxy *proxy = static_cast<DispatchProxy*>(header);
- *result = NULL;
- *count = 0;
-
- std::vector<NPIdentifier> np_identifiers;
- DISPID dispatch_id = DISPID_STARTENUM;
- for (;;) {
- HRESULT hr = proxy->dispatch_->GetNextDispID(fdexEnumAll, dispatch_id,
- &dispatch_id);
- if (hr == S_FALSE) {
- *count = np_identifiers.size();
- *result = static_cast<NPIdentifier*>(
- proxy->browser_proxy_->GetBrowserFunctions()->memalloc(
- np_identifiers.size() * sizeof(NPIdentifier)));
- std::copy(np_identifiers.begin(), np_identifiers.end(), *result);
- return true;
- }
-
- if (FAILED(hr))
- break;
-
- CComBSTR name_bstr;
- hr = proxy->dispatch_->GetMemberName(dispatch_id, &name_bstr);
- if (FAILED(hr))
- break;
-
- CString name_wide((BSTR) name_bstr);
-
- int utf8_bytes = WideCharToMultiByte(CP_UTF8, 0, name_wide.GetBuffer(),
- name_wide.GetLength() + 1,
- NULL, 0, NULL, NULL);
- scoped_array<NPUTF8> name_utf8(new NPUTF8[utf8_bytes]);
- WideCharToMultiByte(CP_UTF8, 0, name_wide.GetBuffer(),
- name_wide.GetLength() + 1,
- name_utf8.get(), utf8_bytes, NULL, NULL);
-
- NPIdentifier np_identifier =
- proxy->browser_proxy_->GetBrowserFunctions()->
- getstringidentifier(name_utf8.get());
- np_identifiers.push_back(np_identifier);
- }
-
- return false;
-}
-
-NPObject * DispatchProxy::Allocate(NPP npp, NPClass *aClass) {
- DispatchProxy *instance = new DispatchProxy();
- instance->_class = aClass;
- instance->referenceCount = 1;
- return instance;
-}
-
-void DispatchProxy::Deallocate(NPObject *obj) {
- DispatchProxy *proxy = static_cast<DispatchProxy*>(obj);
- ATLASSERT(proxy->referenceCount == 0);
- delete proxy;
-}
-
-NPClass DispatchProxy::kNPClass = {
- NP_CLASS_STRUCT_VERSION,
- Allocate,
- Deallocate,
- NULL,
- HasMethod,
- InvokeEntry,
- InvokeDefault,
- HasProperty,
- GetPropertyEntry,
- SetPropertyEntry,
- RemovePropertyEntry,
- EnumeratePropertyEntries,
- Construct
-};
diff --git a/o3d/plugin/npapi_host_control/win/dispatch_proxy.h b/o3d/plugin/npapi_host_control/win/dispatch_proxy.h
deleted file mode 100644
index ceb651f..0000000
--- a/o3d/plugin/npapi_host_control/win/dispatch_proxy.h
+++ /dev/null
@@ -1,197 +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.
- */
-
-
-// File declaring a class providing a wrapper between the NPAPI NPObject
-// interface, and COM's IDispatchEx interface.
-
-#ifndef O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_DISPATCH_PROXY_H_
-#define O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_DISPATCH_PROXY_H_
-
-#include <atlctl.h>
-#include <dispex.h>
-
-#include "third_party/npapi/include/npfunctions.h"
-#include "plugin/npapi_host_control/win/np_browser_proxy.h"
-
-class NPBrowserProxy;
-
-// Class implementing a NPAPI interface wrapper around IDispatchEx automation
-// objects.
-class DispatchProxy : public NPObject {
- public:
- DispatchProxy(IDispatchEx* dispatch,
- NPBrowserProxy* browser_proxy);
- virtual ~DispatchProxy();
-
- // Returns the NPAPI interface for accessing the instance of the object.
- static NPClass* GetNPClass() {
- return &kNPClass;
- }
-
- CComPtr<IDispatchEx> GetDispatchEx() const {
- return dispatch_;
- }
-
- void SetBrowserProxy(NPBrowserProxy* browser_proxy) {
- browser_proxy_ = browser_proxy;
- }
-
- private:
- DispatchProxy() : browser_proxy_(NULL) {}
-
- // COM object of which this is a proxy.
- CComPtr<IDispatchEx> dispatch_;
-
- // Back pointer to the NPAPI browser environment in which the plugin resides.
- NPBrowserProxy* browser_proxy_;
-
- // Function to convert NPAPI automation identifiers to COM dispatch ID's.
- // Parameters:
- // name: NPAPI identifier for which we are to find the corresponding
- // dispatch ID.
- // flags: Flags to pass to GetDispID.
- // Returns:
- // A valid dispatch-id if the corresponding member or property exists on
- // the hosted automation object, -1 otherwise.
- DISPID GetDispatchId(NPIdentifier name, DWORD flags) const;
-
- // The following set of static methods implement the NPAPI object interface
- // for DispatchProxy objects.
-
- // Function to determine the existance of a scriptable method.
- // Parameters:
- // header: 'this' for the function call.
- // name: NPAPI dispatch identifier associated with the method name.
- // Returns:
- // true if the method is found.
- static bool HasMethod(NPObject *header, NPIdentifier name);
-
- // Invokes a scriptable method on the object with the given arguments, and
- // returns a variant result.
- // Parameters:
- // header: 'this' for the function call.
- // name: NPAPI dispatch identifier associated with the method name.
- // args: Array of NPVariant objects used as arguments for the method call.
- // arg_count: Number of arguments in args.
- // result: Pointer to variant receiving the return value of the method.
- // Returns:
- // true on successfull invocation of an existing method, false otherwise.
- static bool InvokeEntry(NPObject *header, NPIdentifier name,
- const NPVariant *args, uint32_t arg_count,
- NPVariant *result);
-
- // Invokes the object with the given arguments, and returns a variant result.
- // Parameters:
- // header: function object to call.
- // args: Array of NPVariant objects used as arguments for the method call.
- // arg_count: Number of arguments in args.
- // result: Pointer to variant receiving the return value of the method.
- // Returns:
- // true on successfull invocation of an existing method, false otherwise.
- static bool InvokeDefault(NPObject *header, const NPVariant *args,
- uint32_t argument_count, NPVariant *result);
-
- // Invokes an object as a constructor function with the given arguments, and
- // returns a variant result.
- // Parameters:
- // header: function object to call.
- // args: Array of NPVariant objects used as arguments for the method call.
- // arg_count: Number of arguments in args.
- // result: Pointer to variant receiving the return value of the method.
- // Returns:
- // true on successfull invocation of an existing method, false otherwise.
- static bool Construct(NPObject *header, const NPVariant *args,
- uint32_t argument_count, NPVariant *result);
-
- // Determines the existence of a scriptable property on the object instance.
- // Parameters:
- // header: 'this' for the function call.
- // name: NPAPI dispatch identifier associated with the propertyname.
- // Returns:
- // true if the property exists.
- static bool HasProperty(NPObject *header, NPIdentifier name);
-
- // Returns the value of a scriptable property.
- // Parameters:
- // header: 'this' for the function call.
- // name: NPAPI dispatch identifier associated with the propertyname.
- // variant: Contains the value of the property upon return.
- // Returns:
- // true if the property is successfully assigned.
- static bool GetPropertyEntry(NPObject *header, NPIdentifier name,
- NPVariant *variant);
-
- // Assigns the value of a scriptable property.
- // Parameters:
- // header: 'this' for the function call.
- // name: NPAPI dispatch identifier associated with the propertyname.
- // variant: Value to which the property is to be assigned.
- // Returns:
- // true if the property is successfully assigned.
- static bool SetPropertyEntry(NPObject *header, NPIdentifier name,
- const NPVariant *variant);
-
- // Removes a scriptable property.
- // Parameters:
- // header: object to remove property from.
- // name: NPAPI dispatch identifier associated with the propertyname.
- // Returns:
- // true if the property is successfully assigned.
- static bool RemovePropertyEntry(NPObject *header, NPIdentifier name);
-
- // Returns an enumeration of all properties present on the instance object.
- // Parameters:
- // header: 'this' for the function call.
- // value: Returned pointer to an array of NPidentifers for all of the
- // properties on the object.
- // count: The number of elements in the value array.
- // Returns:
- // false always. This routine is not implemented.
- static bool EnumeratePropertyEntries(NPObject *header, NPIdentifier **value,
- uint32_t *count);
-
- // Custom class allocation routine.
- // Parameters:
- // npp: The plugin instance data.
- // class_functions: The NPClass function table for the class to construct.
- static NPObject * Allocate(NPP npp, NPClass *class_functions);
-
- // Custom destruction routine.
- static void Deallocate(NPObject *obj);
-
- // Static V-Table instance for the NPAPI interface for DispatchProxy objects.
- static NPClass kNPClass;
-
- DISALLOW_COPY_AND_ASSIGN(DispatchProxy);
-};
-
-#endif // O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_DISPATCH_PROXY_H_
diff --git a/o3d/plugin/npapi_host_control/win/host_control.cc b/o3d/plugin/npapi_host_control/win/host_control.cc
deleted file mode 100644
index 99e7696..0000000
--- a/o3d/plugin/npapi_host_control/win/host_control.cc
+++ /dev/null
@@ -1,620 +0,0 @@
-// Copyright 2009, Google Inc. All rights reserved.
-// Portions of this file were adapted from the Mozilla project.
-// See https://developer.mozilla.org/en/ActiveX_Control_for_Hosting_Netscape_Plug-ins_in_IE
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1994-2000
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- * Adam Lock <adamlock@eircom.net>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#include "plugin/npapi_host_control/win/host_control.h"
-
-#include <mshtml.h>
-
-#include "plugin/npapi_host_control/win/np_plugin_proxy.h"
-#include "plugin/npapi_host_control/win/np_object_proxy.h"
-#include "plugin/npapi_host_control/win/stream_operation.h"
-
-namespace {
-
-// Helper function converting UTF-8 encoded input-string to a NULL-terminated
-// wide-character array.
-HRESULT ConvertMultiByteToWideChar(const char* input_string,
- scoped_array<wchar_t>* wide_string) {
- if (!wide_string || !input_string) {
- return E_INVALIDARG;
- }
-
- int required_size = 0;
- required_size = MultiByteToWideChar(CP_UTF8, 0, input_string, -1, NULL, 0);
- // Add one extra element so that we may explicitly null-terminate the string.
- wide_string->reset(new wchar_t[required_size + 1]);
- if (!wide_string->get()) {
- return E_FAIL;
- }
- MultiByteToWideChar(CP_UTF8, 0, input_string, -1, wide_string->get(),
- required_size + 1);
- (*wide_string)[required_size] = 0;
- return S_OK;
-}
-
-// Helper function that checks a user agent string for 'MSIE', the indicator for
-// Internet Explorer.
-bool IsMSIE(const char* user_agent) {
- ATLASSERT(user_agent);
- if (!user_agent) {
- return false;
- }
- static const char* kMSIETag = "MSIE";
- return strstr(user_agent, kMSIETag) != NULL;
-}
-
-} // unnamed namespace
-
-CHostControl::CHostControl()
- : browser_proxy_(NULL),
- plugin_proxy_(NULL),
- embedded_name_(NULL),
- user_agent_(NULL) {
- // Request that this control be windowed.
- m_bWindowOnly = true;
-}
-
-CHostControl::~CHostControl() {
-}
-
-STDMETHODIMP CHostControl::InterfaceSupportsErrorInfo(REFIID riid) {
- static const IID* arr[] = {
- &IID_IHostControl,
- };
-
- for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
- if (InlineIsEqualGUID(*arr[i], riid)) {
- return S_OK;
- }
- }
- return S_FALSE;
-}
-
-
-const char* CHostControl::GetUserAgent() const {
- // Capture the user agent on the first call.
- if (!user_agent_.get()) {
- CComBSTR user_agent;
- HRESULT hr = E_FAIL;
- if (NULL != static_cast<IOmNavigator*>(navigator_)) {
- hr = navigator_->get_userAgent(&user_agent);
- }
- if (SUCCEEDED(hr)) {
- // Convert to UTF-8 and null terminate the string.
- int size_required = WideCharToMultiByte(CP_UTF8, 0, user_agent, -1,
- NULL, NULL, NULL, NULL);
- user_agent_.reset(new char[size_required + 1]);
- WideCharToMultiByte(CP_UTF8, 0, user_agent, -1,
- user_agent_.get(), size_required + 1, NULL, NULL);
- user_agent_[size_required] = 0;
- }
- }
-
- return user_agent_.get();
-}
-
-LRESULT CHostControl::OnCreate(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL &bHandled) {
- NPWindow window = {0};
- window.window = m_hWnd;
- CREATESTRUCT *create_struct = reinterpret_cast<CREATESTRUCT*>(lParam);
- window.type = NPWindowTypeWindow;
- window.x = create_struct->x;
- window.y = create_struct->y;
- window.width = create_struct->cx;
- window.height = create_struct->cy;
-
- // Get the web browser through the site the control is attached to.
- // Note: The control could be running in some other container than IE
- // so code shouldn't expect this function to work all the time.
- service_provider_ = m_spClientSite;
- if (service_provider_ == NULL)
- return -1;
-
- if (FAILED(service_provider_->QueryService(IID_IWebBrowserApp,
- &web_browser_app_))) {
- return -1;
- }
-
- // Navigate the ActiveX interface hierarchy to the IOmNavigator interface.
- CComPtr<IDispatch> dispatch;
- if (FAILED(web_browser_app_->get_Document(&dispatch))) {
- return -1;
- }
-
- if (FAILED(dispatch->QueryInterface(&document_dispatch_))) {
- return -1;
- }
-
- if (FAILED(document_dispatch_->QueryInterface(&html_document2_))) {
- return -1;
- }
-
- if (FAILED(document_dispatch_->QueryInterface(&html_document3_))) {
- return -1;
- }
-
- if (FAILED(html_document2_->get_parentWindow(&html_window_))) {
- return -1;
- }
-
- if (FAILED(html_window_->get_navigator(&navigator_))) {
- return -1;
- }
-
- // Only permit the control to create an instance of the hosted plug-in iff
- // we are presently running in Internet Explorer.
- if (!IsMSIE(GetUserAgent())) {
- TearDown();
- return -1;
- }
-
- if (FAILED(html_window_->QueryInterface(&window_dispatch_))) {
- return -1;
- }
-
- // Construct and cache a moniker for the url of the page where the plugin
- // is hosted.
- CComBSTR url_string;
- if (FAILED(html_document2_->get_URL(&url_string))) {
- return -1;
- }
-
- if (FAILED(CreateURLMonikerEx(NULL, url_string, &url_moniker_,
- URL_MK_UNIFORM))) {
- return -1;
- }
-
- browser_proxy_.reset(new NPBrowserProxy(this, window_dispatch_));
- if (!plugin_proxy_->Init(browser_proxy_.get(),
- window,
- plugin_argument_names_,
- plugin_argument_values_)) {
- browser_proxy_.reset();
- return -1;
- }
-
- return 0;
-}
-
-void CHostControl::TearDown() {
- if (embedded_name_) {
- SysFreeString(embedded_name_);
- embedded_name_ = NULL;
- }
-
- // Note: We do not delete the plug-in instance here, because we can
- // re-initialize it on the subsequent WM_CREATE message.
- if (plugin_proxy_.get()) {
- plugin_proxy_->TearDown();
- }
-
- if (browser_proxy_.get()) {
- browser_proxy_->TearDown();
- }
-
- browser_proxy_.reset();
- user_agent_.reset();
-
- url_moniker_ = NULL;
- window_dispatch_ = NULL;
- navigator_ = NULL;
- html_window_ = NULL;
- html_document3_ = NULL;
- html_document2_ = NULL;
- document_dispatch_ = NULL;
- web_browser_app_ = NULL;
- service_provider_.Release();
-}
-
-LRESULT CHostControl::OnDestroy(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL &bHandled) {
- // OnDestroy processing does not imply that the plug-in is to be permanently
- // destroyed - IE will send WM_CREATE, WM_DESTROY message pairs multiple times
- // to the same control instance as it is moved throughout the DOM.
- // We tear-down the object entirely here, so that it can be fully
- // reconstructed, if necessary, on the next WM_CREATE.
- TearDown();
-
- return 0;
-}
-
-LRESULT CHostControl::OnPluginAsyncCall(UINT message,
- WPARAM w_param,
- LPARAM l_param,
- BOOL& handled) {
- typedef void (*Function)(void*);
- Function function = reinterpret_cast<Function>(w_param);
- void* data = reinterpret_cast<void*>(l_param);
- function(data);
- handled = TRUE;
- return 0;
-}
-
-HRESULT CHostControl::FinalConstruct() {
- return ConstructPluginProxy();
-}
-
-
-void CHostControl::FinalRelease() {
- plugin_proxy_.reset();
-}
-
-HRESULT CHostControl::OpenUrlStream(const wchar_t *url, void *notify_data) {
- return StreamOperation::OpenURL(plugin_proxy_.get(), url, notify_data);
-}
-
-STDMETHODIMP CHostControl::GetTypeInfoCount(UINT *pctinfo) {
- if (!pctinfo) {
- return E_POINTER;
- } else {
- *pctinfo = 0;
- }
- return S_OK;
-}
-
-STDMETHODIMP CHostControl::GetTypeInfo(UINT itinfo,
- LCID lcid,
- ITypeInfo **pptinfo) {
- return E_NOTIMPL;
-}
-
-STDMETHODIMP CHostControl::GetIDsOfNames(REFIID riid,
- LPOLESTR *rgszNames,
- UINT cNames,
- LCID lcid,
- DISPID *rgdispid) {
- // Forward all requests through the typelib before defaulting to the
- // NPAPI plugin.
- HRESULT hr = DispatchImpl::GetIDsOfNames(riid, rgszNames, cNames,
- lcid, rgdispid);
- if (SUCCEEDED(hr)) {
- return hr;
- }
-
- if (plugin_proxy_.get()) {
- CComPtr<INPObjectProxy> script_object;
- hr = plugin_proxy_->GetScriptableObject(&script_object);
- if (SUCCEEDED(hr)) {
- return script_object->GetIDsOfNames(riid, rgszNames, cNames, lcid,
- rgdispid);
- } else {
- return hr;
- }
- } else {
- return E_FAIL;
- }
-}
-
-STDMETHODIMP CHostControl::Invoke(DISPID dispidMember,
- REFIID riid,
- LCID lcid,
- WORD wFlags,
- DISPPARAMS *pdispparams,
- VARIANT *pvarResult,
- EXCEPINFO *pexcepinfo,
- UINT *puArgErr) {
- // Forward all Invoke requests through the typelib first.
- HRESULT hr = DispatchImpl::Invoke(dispidMember, riid, lcid, wFlags,
- pdispparams, pvarResult, pexcepinfo,
- puArgErr);
- if (SUCCEEDED(hr)) {
- return hr;
- }
-
- // Disregard reserved dispatch-ids corresponding to VB/OLE.
- if (static_cast<int>(dispidMember) < 0)
- return E_FAIL;
-
- if (plugin_proxy_.get()) {
- CComPtr<INPObjectProxy> script_object;
- hr = plugin_proxy_->GetScriptableObject(&script_object);
- if (SUCCEEDED(hr)) {
- return script_object->Invoke(dispidMember, riid, lcid, wFlags,
- pdispparams, pvarResult, pexcepinfo,
- puArgErr);
- } else {
- return hr;
- }
- } else {
- return E_FAIL;
- }
-}
-
-STDMETHODIMP CHostControl::DeleteMemberByDispID(DISPID id) {
- HRESULT hr;
- if (plugin_proxy_.get()) {
- CComPtr<INPObjectProxy> script_object;
- hr = plugin_proxy_->GetScriptableObject(&script_object);
- if (SUCCEEDED(hr)) {
- return script_object->DeleteMemberByDispID(id);
- } else {
- return hr;
- }
- } else {
- return E_FAIL;
- }
-}
-
-STDMETHODIMP CHostControl::DeleteMemberByName(BSTR bstrName, DWORD grfdex) {
- HRESULT hr;
- if (plugin_proxy_.get()) {
- CComPtr<INPObjectProxy> script_object;
- hr = plugin_proxy_->GetScriptableObject(&script_object);
- if (SUCCEEDED(hr)) {
- return script_object->DeleteMemberByName(bstrName, grfdex);
- } else {
- return hr;
- }
- } else {
- return E_FAIL;
- }
-}
-
-STDMETHODIMP CHostControl::GetDispID(BSTR bstrName,
- DWORD grfdex,
- DISPID* pid) {
- // Forward all DISPID requests through the typelib before defaulting to the
- // to the NPAPI plugin.
- HRESULT hr;
- if (SUCCEEDED(hr = DispatchImpl::GetIDsOfNames(IID_NULL,
- &bstrName,
- 1,
- LOCALE_SYSTEM_DEFAULT,
- pid))) {
- return hr;
- }
-
- if (plugin_proxy_.get()) {
- CComPtr<INPObjectProxy> script_object;
- hr = plugin_proxy_->GetScriptableObject(&script_object);
- if (SUCCEEDED(hr)) {
- return script_object->GetDispID(bstrName, grfdex, pid);
- } else {
- return hr;
- }
- } else {
- return E_FAIL;
- }
-}
-
-STDMETHODIMP CHostControl::GetMemberName(DISPID id,
- BSTR* pbstrName) {
- HRESULT hr;
- if (plugin_proxy_.get()) {
- CComPtr<INPObjectProxy> script_object;
- hr = plugin_proxy_->GetScriptableObject(&script_object);
- if (SUCCEEDED(hr)) {
- return script_object->GetMemberName(id, pbstrName);
- } else {
- return hr;
- }
- } else {
- return E_FAIL;
- }
-}
-
-STDMETHODIMP CHostControl::GetMemberProperties(DISPID id,
- DWORD grfdexFetch,
- DWORD* pgrfdex) {
- HRESULT hr;
- if (plugin_proxy_.get()) {
- CComPtr<INPObjectProxy> script_object;
- hr = plugin_proxy_->GetScriptableObject(&script_object);
- if (SUCCEEDED(hr)) {
- return script_object->GetMemberProperties(id, grfdexFetch, pgrfdex);
- } else {
- return hr;
- }
- } else {
- return E_FAIL;
- }
-}
-
-STDMETHODIMP CHostControl::GetNameSpaceParent(IUnknown** punk) {
- HRESULT hr;
- if (plugin_proxy_.get()) {
- CComPtr<INPObjectProxy> script_object;
- hr = plugin_proxy_->GetScriptableObject(&script_object);
- if (SUCCEEDED(hr)) {
- return script_object->GetNameSpaceParent(punk);
- } else {
- return hr;
- }
- } else {
- return E_FAIL;
- }
-}
-
-STDMETHODIMP CHostControl::GetNextDispID(DWORD grfdex,
- DISPID id,
- DISPID* pid) {
- HRESULT hr;
- if (plugin_proxy_.get()) {
- CComPtr<INPObjectProxy> script_object;
- hr = plugin_proxy_->GetScriptableObject(&script_object);
- if (SUCCEEDED(hr)) {
- return script_object->GetNextDispID(grfdex, id, pid);
- } else {
- return hr;
- }
- } else {
- return E_FAIL;
- }
-}
-
-STDMETHODIMP CHostControl::InvokeEx(DISPID id,
- LCID lcid,
- WORD wFlags,
- DISPPARAMS* pdb,
- VARIANT* pVarRes,
- EXCEPINFO* pei,
- IServiceProvider* pspCaller) {
- // Forward all InvokeEx requests through the typelib
- HRESULT hr = DispatchImpl::Invoke(id, IID_NULL, lcid, wFlags,
- pdb, pVarRes, pei,
- NULL);
- if (SUCCEEDED(hr)) {
- return hr;
- }
-
- if (plugin_proxy_.get()) {
- CComPtr<INPObjectProxy> script_object;
- hr = plugin_proxy_->GetScriptableObject(&script_object);
- if (SUCCEEDED(hr)) {
- return script_object->InvokeEx(id, lcid, wFlags, pdb, pVarRes, pei,
- pspCaller);
- } else {
- return hr;
- }
- } else {
- return E_FAIL;
- }
-}
-
-// Receive the arguments provided to the plug-in in the param-tag.
-STDMETHODIMP CHostControl::Load(IPropertyBag* property_bag,
- IErrorLog* error_log) {
- if (!property_bag) {
- return E_INVALIDARG;
- }
-
- // Iterate through all of the properties provided, and register them, in
- // ASCII-string form with the control.
- CComQIPtr<IPropertyBag2> property_bag2 = property_bag;
- if (property_bag2) {
- ULONG property_count;
- if (SUCCEEDED(property_bag2->CountProperties(&property_count))) {
- for (ULONG x = 0; x < property_count; ++x) {
- PROPBAG2 property = {0};
- ULONG properties_read = 0;
- if (SUCCEEDED(property_bag2->GetPropertyInfo(x, 1, &property,
- &properties_read))) {
- CComVariant variant;
- HRESULT prop_hr;
- if (SUCCEEDED(property_bag2->Read(1, &property, NULL,
- &variant, &prop_hr))) {
- if (SUCCEEDED(variant.ChangeType(VT_BSTR))) {
- USES_CONVERSION;
- RegisterPluginParameter(OLE2A(property.pstrName),
- OLE2A(variant.bstrVal));
- }
- }
- // According to the msdn documentation, the name of the property
- // must be freed through CoTaskMemFree.
- // See: http://msdn.microsoft.com/en-us/library/aa768191(VS.85).aspx
- CoTaskMemFree(property.pstrName);
- }
- }
- }
- }
-
- return IPersistPropertyBagImpl<CHostControl>::Load(property_bag, error_log);
-}
-
-STDMETHODIMP CHostControl::SetObjectRects(LPCRECT lprcPosRect,
- LPCRECT lprcClipRect) {
- if (plugin_proxy_.get()) {
- NPWindow window = {0};
- window.window = m_hWnd;
- window.type = NPWindowTypeWindow;
- window.x = lprcPosRect->left;
- window.y = lprcPosRect->top;
- window.width = lprcPosRect->right - lprcPosRect->left;
- window.height = lprcPosRect->bottom - lprcPosRect->top;
- if (!plugin_proxy_->SetWindow(window)) {
- return E_FAIL;
- }
- }
-
- return CComControlBase::IOleInPlaceObject_SetObjectRects(lprcPosRect,
- lprcClipRect);
-}
-
-HRESULT CHostControl::GetStringProperty(NPPVariable np_property_variable,
- BSTR* string) {
- HRESULT hr;
- if (FAILED(hr = ConstructPluginProxy())) {
- return hr;
- }
-
- char* property = NULL;
- if (NPERR_NO_ERROR != plugin_proxy_->GetPluginFunctions()->getvalue(
- NULL,
- np_property_variable,
- &property)) {
- return E_FAIL;
- }
-
- scoped_array<wchar_t> wide_property;
- if (FAILED(hr = ConvertMultiByteToWideChar(property, &wide_property))) {
- return hr;
- }
- *string = SysAllocString(wide_property.get());
- return S_OK;
-}
-
-STDMETHODIMP CHostControl::get_description(BSTR *returned_description) {
- return GetStringProperty(NPPVpluginDescriptionString, returned_description);
-}
-
-STDMETHODIMP CHostControl::get_name(BSTR *returned_name) {
- return GetStringProperty(NPPVpluginNameString, returned_name);
-}
-
-HRESULT CHostControl::ConstructPluginProxy() {
- // If the plugin has already been constructed, then exit early.
- if (plugin_proxy_.get()) {
- return S_OK;
- }
-
- HRESULT hr;
- NPPluginProxy* plugin_proxy = NULL;
- if (FAILED(hr = NPPluginProxy::Create(&plugin_proxy))) {
- return hr;
- }
-
- plugin_proxy_.reset(plugin_proxy);
- return S_OK;
-}
diff --git a/o3d/plugin/npapi_host_control/win/host_control.h b/o3d/plugin/npapi_host_control/win/host_control.h
deleted file mode 100644
index 9a4fc68..0000000
--- a/o3d/plugin/npapi_host_control/win/host_control.h
+++ /dev/null
@@ -1,275 +0,0 @@
-// Copyright 2009, Google Inc. All rights reserved.
-// Portions of this file were adapted from the Mozilla project.
-// See https://developer.mozilla.org/en/ActiveX_Control_for_Hosting_Netscape_Plug-ins_in_IE
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1994-2000
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- * Adam Lock <adamlock@eircom.net>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-
-// Declares a COM class implementing an ActiveX control capable of hosting
-// an NPAPI plugin on an OLE site.
-
-#ifndef O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_HOST_CONTROL_H_
-#define O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_HOST_CONTROL_H_
-
-#include <atlctl.h>
-#include <dispex.h>
-#include <vector>
-
-#include "base/scoped_ptr.h"
-
-// Directory not included, as this file is auto-generated from the
-// type library.
-#include "npapi_host_control.h"
-#include "plugin/npapi_host_control/win/np_browser_proxy.h"
-
-class NPPluginProxy;
-
-const UINT WM_PLUGINASYNCCALL = WM_USER + 100;
-
-// Class implementing an ActiveX control for containing NPAPI plugin-objects.
-// This needs to be CComMultiThreadModel because these objects are concurrently
-// AddRefed and Released from StreamOperation threads.
-class ATL_NO_VTABLE CHostControl
- : public CComObjectRootEx<CComMultiThreadModel>,
- public CComCoClass<CHostControl, &CLSID_HostControl>,
- public CComControl<CHostControl>,
- // IMPORTANT IMPLEMENTATION NOTE:
- // Pass 0xFFFF to the major and minor versions of the IDispatchImpl
- // for trigger the behaviour in CComTypeInfoHolder::GetTI that forces
- // the type-library to be loaded from the module, not through the
- // registry.
- // Without this behaviour, the plug-in fails to load on Vista with UAC
- // disabled. This is because all processes run at elevated integrity
- // with UAC disabled. Because the plug-in is registered as a per-user
- // control (under HKCU), it will fail to load the type-library through
- // the registry: Elevated processes do not view the contents of the HKCU
- // hive, so it will appear as if the control was not installed properly.
- public IDispatchImpl<IHostControl, &IID_IHostControl,
- &LIBID_npapi_host_controlLib,
- 0xFFFF,
- 0xFFFF>,
- public IOleControlImpl<CHostControl>,
- public IOleObjectImpl<CHostControl>,
- public IOleInPlaceActiveObjectImpl<CHostControl>,
- public IOleInPlaceObjectWindowlessImpl<CHostControl>,
- public ISupportErrorInfo,
- public IProvideClassInfo2Impl<&CLSID_HostControl, NULL,
- &LIBID_npapi_host_controlLib>,
- public IObjectSafetyImpl<CHostControl,
- INTERFACESAFE_FOR_UNTRUSTED_CALLER |
- INTERFACESAFE_FOR_UNTRUSTED_DATA>,
- public IPersistPropertyBagImpl<CHostControl>,
- public IPersistStorageImpl<CHostControl>,
- public IConnectionPointContainerImpl<CHostControl>,
- public IPropertyNotifySinkCP<CHostControl> {
- public:
- CHostControl();
- virtual ~CHostControl();
-
-DECLARE_OLEMISC_STATUS(OLEMISC_RECOMPOSEONRESIZE |
- OLEMISC_CANTLINKINSIDE |
- OLEMISC_INSIDEOUT |
- OLEMISC_ACTIVATEWHENVISIBLE |
- OLEMISC_SETCLIENTSITEFIRST
-)
-
-DECLARE_REGISTRY_RESOURCEID(IDR_HOSTCONTROL)
-
-BEGIN_MSG_MAP(CHostControl)
- MESSAGE_HANDLER(WM_CREATE, OnCreate)
- MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
- MESSAGE_HANDLER(WM_PLUGINASYNCCALL, OnPluginAsyncCall)
-END_MSG_MAP()
-
-BEGIN_CONNECTION_POINT_MAP(CHostControl)
- CONNECTION_POINT_ENTRY(IID_IPropertyNotifySink)
-END_CONNECTION_POINT_MAP()
-
-// Register this control as safe for initialization and scripting. If these
-// categories are skipped, IE will force the user to permit the control to
-// allow scripting at every page view.
-BEGIN_CATEGORY_MAP(CHostControl)
- IMPLEMENTED_CATEGORY(CATID_SafeForScripting)
- IMPLEMENTED_CATEGORY(CATID_SafeForInitializing)
-END_CATEGORY_MAP()
-
-BEGIN_COM_MAP(CHostControl)
- COM_INTERFACE_ENTRY(IHostControl)
- COM_INTERFACE_ENTRY(IDispatch)
- COM_INTERFACE_ENTRY(IDispatchEx)
- COM_INTERFACE_ENTRY(IOleInPlaceObject)
- COM_INTERFACE_ENTRY2(IOleWindow, IOleInPlaceObjectWindowless)
- COM_INTERFACE_ENTRY(IOleInPlaceActiveObject)
- COM_INTERFACE_ENTRY(IOleControl)
- COM_INTERFACE_ENTRY(IOleObject)
- COM_INTERFACE_ENTRY(ISupportErrorInfo)
- COM_INTERFACE_ENTRY(IProvideClassInfo)
- COM_INTERFACE_ENTRY(IProvideClassInfo2)
- COM_INTERFACE_ENTRY(IPersistPropertyBag)
- COM_INTERFACE_ENTRY(IPersistStorage)
- COM_INTERFACE_ENTRY(IConnectionPointContainer)
-END_COM_MAP()
-
-BEGIN_PROP_MAP(CHostControl)
-END_PROP_MAP()
-
- STDMETHOD(GetTypeInfoCount)(UINT* pctinfo);
- STDMETHOD(GetTypeInfo)(UINT itinfo, LCID lcid, ITypeInfo** pptinfo);
- STDMETHOD(GetIDsOfNames)(REFIID riid, LPOLESTR* rgszNames, UINT cNames,
- LCID lcid, DISPID* rgdispid);
- STDMETHOD(Invoke)(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags,
- DISPPARAMS* pdispparams, VARIANT* pvarResult,
- EXCEPINFO* pexcepinfo, UINT* puArgErr);
- STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
-
- STDMETHOD(DeleteMemberByDispID)(DISPID id);
- STDMETHOD(DeleteMemberByName)(BSTR bstrName, DWORD grfdex);
- STDMETHOD(GetDispID)(BSTR bstrName, DWORD grfdex, DISPID* pid);
- STDMETHOD(GetMemberName)(DISPID id, BSTR* pbstrName);
- STDMETHOD(GetMemberProperties)(DISPID id, DWORD grfdexFertch, DWORD* pgrfdex);
- STDMETHOD(GetNameSpaceParent)(IUnknown** ppunk);
- STDMETHOD(GetNextDispID)(DWORD grfdex, DISPID id, DISPID* pid);
- STDMETHOD(InvokeEx)(DISPID id, LCID lcid, WORD wFlags, DISPPARAMS* pdp,
- VARIANT* pVarRes, EXCEPINFO* pei,
- IServiceProvider* pspCaller);
-
- // Method overridden from IPersistPropertyBagImpl.
- STDMETHOD(Load(IPropertyBag *pPropBag, IErrorLog *pErrorLog));
-
- STDMETHOD(SetObjectRects(LPCRECT lprcPosRect,
- LPCRECT lprcClipRect));
-
- // Returns the properties associated with the NPPVpluginNameString, and
- // NPPVpluginDescriptionString identifiers of the loaded plug-in. These
- // properties can be used for plug-in introspection and version-dependent
- // behaviour.
- STDMETHOD(get_description)(BSTR *returned_description);
- STDMETHOD(get_name)(BSTR *returned_name);
-
- LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
- LRESULT OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
- LRESULT OnPluginAsyncCall(UINT message, WPARAM w_param, LPARAM l_param,
- BOOL& handled);
-
- // Initiates a data transfer, calling back into the hosted plug-in instance
- // on status updates. Does not block on the transfer.
- // Parameters:
- // url: The url from which to receive data.
- // notify_data: Opaque handle to data provided by the plug-in instance.
- // This data will be passed back to the plug-in during
- // all call-backs.
- // Returns:
- // S_OK on success.
- HRESULT OpenUrlStream(const wchar_t *url, void *notify_data);
-
- // Returns the user-agent string of the browser hosting the control.
- // Returns NULL on failure.
- const char* GetUserAgent() const;
-
- // Return a moniker representing the url of the page in which the plugin is
- // contained.
- IMoniker* GetURLMoniker() const {
- return url_moniker_;
- }
-
- DECLARE_PROTECT_FINAL_CONSTRUCT()
- HRESULT FinalConstruct();
- void FinalRelease();
-
- private:
- // Performs all of the basic construction of the hosted NPPluginProxy object,
- // but does not initialize an active instance of the plug-in.
- HRESULT ConstructPluginProxy();
-
- // Returns an NPAPI property from the hosted plug-in.
- // Parameters:
- // np_property_variable: NPPVariable value corresponding to the property
- // to return.
- // string: Pointer to BString that receives the property.
- // Returns:
- // S_OK on success.
- HRESULT GetStringProperty(NPPVariable np_property_variable, BSTR* string);
-
- // Free all resources allocated when constructing the windowed instance
- // of the hosted plug-in in OnCreate(...).
- void TearDown();
-
- void RegisterPluginParameter(const char *name, const char *value) {
- ATLASSERT(name && value);
- plugin_argument_names_.push_back(CStringA(name));
- plugin_argument_values_.push_back(CStringA(value));
- }
-
- // Browser proxy instance used to communicate with the hosted NPAPI plugin.
- scoped_ptr<NPBrowserProxy> browser_proxy_;
-
- // Pointer to the plugin being hosted by the control.
- scoped_ptr<NPPluginProxy> plugin_proxy_;
-
- // Cached value of the name of the control as it exists in the HTML DOM.
- BSTR embedded_name_;
-
- // Cached string representation of the user-agent, initialized by first call
- // to GetUserAgent.
- mutable scoped_array<char> user_agent_;
-
- CComPtr<IWebBrowserApp> web_browser_app_;
- CComQIPtr<IServiceProvider, &IID_IServiceProvider> service_provider_;
- CComPtr<IDispatchEx> document_dispatch_;
- CComPtr<IHTMLDocument2> html_document2_;
- CComPtr<IHTMLDocument3> html_document3_;
- CComPtr<IDispatchEx> window_dispatch_;
- CComPtr<IHTMLWindow2> html_window_;
- CComPtr<IOmNavigator> navigator_;
- CComPtr<IMoniker> url_moniker_;
-
- // Array of strings to be passed as name/value arguments to the NPAPI
- // plug-in instance during construction in NPP_New.
- std::vector<CStringA> plugin_argument_names_;
- std::vector<CStringA> plugin_argument_values_;
-
- typedef IDispatchImpl<IHostControl, &IID_IHostControl,
- &LIBID_npapi_host_controlLib,
- 0xFFFF, 0xFFFF> DispatchImpl;
-
- DISALLOW_COPY_AND_ASSIGN(CHostControl);
-};
-
-// Register this COM class with the COM module.
-OBJECT_ENTRY_AUTO(__uuidof(HostControl), CHostControl);
-
-#endif // O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_HOST_CONTROL_H_
diff --git a/o3d/plugin/npapi_host_control/win/host_control.rgs_template b/o3d/plugin/npapi_host_control/win/host_control.rgs_template
deleted file mode 100644
index 93d33e0..0000000
--- a/o3d/plugin/npapi_host_control/win/host_control.rgs_template
+++ /dev/null
@@ -1,42 +0,0 @@
-HKCU
-{
- Software
- {
- Classes
- {
- @@@PluginActiveXHostControlName@@@.O3DHostControl.1 = s 'O3DHostControl Class'
- {
- CLSID = s '{@@@PluginActiveXHostControlClsid@@@}'
- 'Insertable'
- }
- @@@PluginActiveXHostControlName@@@.O3DHostControl = s 'O3DHostControl Class'
- {
- CLSID = s '{@@@PluginActiveXHostControlClsid@@@}'
- CurVer = s '@@@PluginActiveXHostControlName@@@.O3DHostControl.1'
- }
- NoRemove CLSID
- {
- ForceRemove {@@@PluginActiveXHostControlClsid@@@} = s 'O3DHostControl Class'
- {
- ProgID = s '@@@PluginActiveXHostControlName@@@.O3DHostControl.1'
- VersionIndependentProgID = s '@@@PluginActiveXHostControlName@@@.O3DHostControl'
- ForceRemove 'Programmable'
- InprocServer32 = s '%MODULE%'
- {
- val ThreadingModel = s 'Apartment'
- }
- val AppID = s '%APPID%'
- ForceRemove 'Control'
- ForceRemove 'Insertable'
- ForceRemove 'ToolboxBitmap32' = s '%MODULE%, 102'
- 'MiscStatus' = s '0'
- {
- '1' = s '%OLEMISC%'
- }
- 'TypeLib' = s '{@@@PluginActiveXTypeLibClsid@@@}'
- 'Version' = s '1.0'
- }
- }
- }
- }
-}
diff --git a/o3d/plugin/npapi_host_control/win/module.h b/o3d/plugin/npapi_host_control/win/module.h
deleted file mode 100644
index 5074504..0000000
--- a/o3d/plugin/npapi_host_control/win/module.h
+++ /dev/null
@@ -1,68 +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 ATL module class used by the O3D host ActiveX control.
-
-#ifndef O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_MODULE_H_
-#define O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_MODULE_H_
-
-#include "npapi_host_control.h"
-
-class NPAPIHostControlModule : public CAtlDllModuleT<NPAPIHostControlModule> {
- public:
- NPAPIHostControlModule() { InitializeCriticalSection(&cs_); }
- virtual ~NPAPIHostControlModule() { DeleteCriticalSection(&cs_); }
-
- // Routine used to serialize threads executing within the control. Enters
- // a critical section shared for the process hosting the control.
- static void LockModule() {
- EnterCriticalSection(&GetGlobalInstance()->cs_);
- }
-
- // Routine used to serialize threads executing within the control. Leaves
- // the critical section entered in lock_module().
- static void UnlockModule() {
- LeaveCriticalSection(&GetGlobalInstance()->cs_);
- }
-
- // Accessor routine for the global pointer _pAtlModule maintained by ATL.
- static NPAPIHostControlModule* GetGlobalInstance() {
- return static_cast<NPAPIHostControlModule*>(_pAtlModule);
- }
-
- DECLARE_LIBID(LIBID_npapi_host_controlLib)
- private:
- CRITICAL_SECTION cs_;
- DISALLOW_COPY_AND_ASSIGN(NPAPIHostControlModule);
-};
-
-#endif // O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_MODULE_H_
diff --git a/o3d/plugin/npapi_host_control/win/np_browser_proxy.cc b/o3d/plugin/npapi_host_control/win/np_browser_proxy.cc
deleted file mode 100644
index f951460..0000000
--- a/o3d/plugin/npapi_host_control/win/np_browser_proxy.cc
+++ /dev/null
@@ -1,834 +0,0 @@
-// Copyright 2009, Google Inc. All rights reserved.
-// Portions of this file were adapted from the Mozilla project.
-// See https://developer.mozilla.org/en/ActiveX_Control_for_Hosting_Netscape_Plug-ins_in_IE
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1994-2000
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- * Adam Lock <adamlock@eircom.net>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#include <atlstr.h>
-
-#include <string>
-#include <set>
-
-#include "plugin/npapi_host_control/win/host_control.h"
-#include "plugin/npapi_host_control/win/variant_utils.h"
-
-namespace {
-
-// Helper routine that invokes the host-control stream request function.
-NPError OpenURL(NPBrowserProxy* browser_proxy,
- const char *url,
- const char *target,
- void *notify_data) {
- CHostControl* host_control = browser_proxy->GetHostingControl();
-
- USES_CONVERSION;
- HRESULT hr = host_control->OpenUrlStream(A2CW(url), notify_data);
- return SUCCEEDED(hr) ? NPERR_NO_ERROR : NPERR_GENERIC_ERROR;
-}
-} // unnamed namespace
-
-NPNetscapeFuncs NPBrowserProxy::kNetscapeFunctions = {
- sizeof(kNetscapeFunctions),
- NPVERS_HAS_PLUGIN_THREAD_ASYNC_CALL,
- NPN_GetURL,
- NPN_PostURL,
- NPN_RequestRead,
- NPN_NewStream,
- NPN_Write,
- NPN_DestroyStream,
- NPN_Status,
- NPN_UserAgent,
- NPN_MemAlloc,
- NPN_MemFree,
- NPN_MemFlush,
- NPN_ReloadPlugins,
- NPN_GetJavaEnv,
- NPN_GetJavaPeer,
- NPN_GetURLNotify,
- NPN_PostURLNotify,
- NPN_GetValue,
- NPN_SetValue,
- NPN_InvalidateRect,
- NPN_InvalidateRegion,
- NPN_ForceRedraw,
- NPN_GetStringIdentifier,
- NPN_GetStringIdentifiers,
- NPN_GetIntIdentifier,
- NPN_IdentifierIsString,
- NPN_UTF8FromIdentifier,
- NPN_IntFromIdentifier,
- NPN_CreateObject,
- NPN_RetainObject,
- NPN_ReleaseObject,
- NPN_Invoke,
- NPN_InvokeDefault,
- NPN_Evaluate,
- NPN_GetProperty,
- NPN_SetProperty,
- NPN_RemoveProperty,
- NPN_HasProperty,
- NPN_HasMethod,
- NPN_ReleaseVariantValue,
- NPN_SetException,
- NULL,
- NULL,
- NPN_Enumerate,
- NPN_PluginThreadAsyncCall,
-};
-
-NPBrowserProxy::NPBrowserProxy(CHostControl* host, IDispatchEx* window_dispatch)
- : host_control_(host) {
- vwindow_object_ = new DispatchProxy(window_dispatch, this);
-
- CComPtr<IUnknown> unknown_identity;
- HRESULT hr = window_dispatch->QueryInterface(&unknown_identity);
- ATLASSERT(SUCCEEDED(hr));
-
- dispatch_proxy_map_[unknown_identity] = vwindow_object_;
- call_identifier_ = NPN_GetStringIdentifier("call");
-}
-
-NPBrowserProxy::~NPBrowserProxy() {
- for (NPObjectProxyMap::iterator it = np_object_proxy_map_.begin();
- it != np_object_proxy_map_.end(); ++it) {
- it->second->SetBrowserProxy(NULL);
- }
- for (DispatchProxyMap::iterator it = dispatch_proxy_map_.begin();
- it != dispatch_proxy_map_.end(); ++it) {
- it->second->SetBrowserProxy(NULL);
- GetBrowserFunctions()->releaseobject(it->second);
- }
-}
-
-CComPtr<IDispatchEx> NPBrowserProxy::GetDispatchObject(NPObject* np_object) {
- if (np_object == NULL) {
- return CComPtr<IDispatchEx>();
- }
-
- // If the NPObject is already wrapping an IDispatchEx interface, then
- // return that interface directly.
- if (np_object->_class == DispatchProxy::GetNPClass()) {
- DispatchProxy *dispatch_proxy =
- static_cast<DispatchProxy*>(np_object);
- return dispatch_proxy->GetDispatchEx();
- } else {
- // If the NPObject already has a proxy then return that.
- NPObjectProxyMap::iterator it = np_object_proxy_map_.find(np_object);
- if (it != np_object_proxy_map_.end()) {
- CComPtr<IDispatchEx> dispatch_ex(NULL);
- HRESULT hr = it->second.QueryInterface(&dispatch_ex);
- if (SUCCEEDED(hr)) {
- return dispatch_ex;
- } else {
- return NULL;
- }
- }
-
- // Create a new NPObject proxy, register it for future use and return it.
- CComObject<NPObjectProxy>* proxy_instance;
- HRESULT hr = CComObject<NPObjectProxy>::CreateInstance(&proxy_instance);
- if (FAILED(hr))
- return NULL;
-
- CComPtr<INPObjectProxy> proxy_wrapper;
- hr = proxy_instance->QueryInterface(&proxy_wrapper);
- if (SUCCEEDED(hr)) {
- proxy_wrapper->SetBrowserProxy(this);
- proxy_wrapper->SetHostedObject(np_object);
- RegisterNPObjectProxy(np_object, proxy_wrapper);
-
- CComPtr<IDispatchEx> dispatch_proxy_wrapper;
- hr = proxy_wrapper.QueryInterface(&dispatch_proxy_wrapper);
- ATLASSERT(SUCCEEDED(hr));
- return dispatch_proxy_wrapper;
- }
- }
- return CComPtr<IDispatchEx>();
-}
-
-NPObject* NPBrowserProxy::GetNPObject(IDispatch* dispatch_object) {
- if (dispatch_object == NULL)
- return NULL;
-
- // If the COM object is already wrapping an NPObject then return that NPObject
- // directly.
- NPObject* np_object;
- CComPtr<INPObjectProxy> np_object_proxy;
- if (SUCCEEDED(dispatch_object->QueryInterface(&np_object_proxy))) {
- if (SUCCEEDED(np_object_proxy->GetNPObjectInstance(
- reinterpret_cast<void**>(&np_object))))
- return np_object;
- else
- return NULL;
- } else {
- CComPtr<IUnknown> unknown_identity;
- if (FAILED(dispatch_object->QueryInterface(&unknown_identity))) {
- return NULL;
- }
-
- // If the COM object already has a proxy then return that. Note that the
- // map is keyed on IUnknown ptrs - this is because COM explicitly states
- // that the IUnknown interface is the only reliable identity mechanism.
- DispatchProxyMap::iterator it = dispatch_proxy_map_.find(unknown_identity);
- if (it != dispatch_proxy_map_.end()) {
- GetBrowserFunctions()->retainobject(it->second);
- return it->second;
- }
-
- // Create a new DispatchProxy.
- CComPtr<IDispatchEx> dispatchex_object;
- if (FAILED(dispatch_object->QueryInterface(&dispatchex_object))) {
- return NULL;
- }
- DispatchProxy* dispatch_proxy = new DispatchProxy(dispatchex_object,
- this);
- dispatch_proxy_map_[unknown_identity] = dispatch_proxy;
- return dispatch_proxy;
- }
-}
-
-void NPBrowserProxy::RegisterNPObjectProxy(
- NPObject* np_object,
- const CComPtr<INPObjectProxy>& proxy_wrapper) {
- np_object_proxy_map_[np_object] = proxy_wrapper;
-}
-
-void NPBrowserProxy::UnregisterNPObjectProxy(NPObject* np_object) {
- np_object_proxy_map_.erase(np_object);
-}
-
-void NPBrowserProxy::UnregisterDispatchProxy(IDispatchEx* dispatch_object) {
- CComPtr<IUnknown> unknown_identity;
- HRESULT hr = dispatch_object->QueryInterface(&unknown_identity);
- ATLASSERT(SUCCEEDED(hr));
- if (!SUCCEEDED(hr)) {
- return;
- }
-
- DispatchProxyMap::iterator it = dispatch_proxy_map_.find(unknown_identity);
- ATLASSERT(it != dispatch_proxy_map_.end());
- GetBrowserFunctions()->releaseobject(it->second);
- dispatch_proxy_map_.erase(it);
-}
-
-NPError NPBrowserProxy::NPN_GetURL(NPP npp,
- const char* relativeURL,
- const char* target) {
- if (!npp) {
- return NPERR_INVALID_INSTANCE_ERROR;
- }
- ATLASSERT(false && "NPN_GetURL not implemented");
- return NPERR_NO_ERROR;
-}
-
-
-NPError NPBrowserProxy::NPN_GetURLNotify(NPP npp,
- const char* relativeURL,
- const char* target,
- void* notifyData) {
- if (!npp) {
- return NPERR_INVALID_INSTANCE_ERROR;
- }
-
- NPBrowserProxy *browser_proxy = static_cast<NPBrowserProxy*>(npp->ndata);
- return OpenURL(browser_proxy, relativeURL, target, notifyData);
-}
-
-
-
-NPError NPBrowserProxy::NPN_PostURLNotify(NPP npp,
- const char *relativeURL,
- const char *target,
- uint32 len,
- const char *buf,
- NPBool file,
- void *notifyData) {
- if (!npp) {
- return NPERR_INVALID_INSTANCE_ERROR;
- }
- ATLASSERT(false && "NPN_PostURLNotify not implemented.");
- return NPERR_NO_ERROR;
-}
-
-NPError NPBrowserProxy::NPN_PostURL(NPP npp,
- const char *relativeURL,
- const char *target,
- uint32 len,
- const char *buf,
- NPBool file) {
- if (!npp) {
- return NPERR_INVALID_INSTANCE_ERROR;
- }
- ATLASSERT(false && "NPN_PostURL not implemented.");
- return NPERR_NO_ERROR;
-}
-
-NPError NPBrowserProxy::NPN_NewStream(NPP npp,
- NPMIMEType type,
- const char* window,
- NPStream* *result) {
- if (!npp) {
- return NPERR_INVALID_INSTANCE_ERROR;
- }
- ATLASSERT(false && "NPN_NewStream not implemented.");
- return NPERR_GENERIC_ERROR;
-}
-
-
-int32 NPBrowserProxy::NPN_Write(NPP npp,
- NPStream *pstream,
- int32 len,
- void *buffer) {
- if (!npp) {
- return NPERR_INVALID_INSTANCE_ERROR;
- }
- ATLASSERT(false && "NPN_Write not implemented.");
- return NPERR_GENERIC_ERROR;
-}
-
-NPError NPBrowserProxy::NPN_DestroyStream(NPP npp,
- NPStream *pstream,
- NPError reason) {
- if (!npp) {
- return NPERR_INVALID_INSTANCE_ERROR;
- }
- ATLASSERT(false && "NPN_DestroyStream not implemented.");
- return NPERR_GENERIC_ERROR;
-}
-
-void NPBrowserProxy::NPN_Status(NPP npp, const char *message) {
- if (!npp) {
- return;
- }
-}
-
-void *NPBrowserProxy::NPN_MemAlloc(uint32 size) {
- return malloc(size);
-}
-
-void NPBrowserProxy::NPN_MemFree(void *ptr) {
- if (ptr) {
- free(ptr);
- }
-}
-
-uint32 NPBrowserProxy::NPN_MemFlush(uint32 size) {
- return 0;
-}
-
-void NPBrowserProxy::NPN_ReloadPlugins(NPBool reloadPages) {
- ATLASSERT(false && "NPN_ReloadPlugins not implemented.");
-}
-
-void NPBrowserProxy::NPN_InvalidateRect(NPP npp, NPRect *invalidRect) {
- if (!npp) {
- return;
- }
- ATLASSERT(false && "NPN_InvalidateRect not implemented.");
-}
-
-void NPBrowserProxy::NPN_InvalidateRegion(NPP npp, NPRegion invalidRegion) {
- if (!npp) {
- return;
- }
- ATLASSERT(false && "NPN_InvalidateRect not implemented.");
-}
-
-void NPBrowserProxy::NPN_ForceRedraw(NPP npp) {
- if (!npp) {
- return;
- }
- ATLASSERT(false && "NPN_ForceRedraw not implemented.");
-}
-
-NPError NPBrowserProxy::NPN_GetValue(NPP npp,
- NPNVariable variable,
- void *result) {
- if (!npp) {
- return NPERR_INVALID_INSTANCE_ERROR;
- }
-
- if (!result) {
- return NPERR_INVALID_PARAM;
- }
-
- NPBrowserProxy *browser_proxy = static_cast<NPBrowserProxy*>(npp->ndata);
- ATLASSERT(browser_proxy);
-
- switch (variable) {
- case NPNVxDisplay :
- return NPERR_GENERIC_ERROR;
- case NPNVnetscapeWindow:
- *(static_cast<HWND*>(result)) =
- browser_proxy->GetHostingControl()->m_hWnd;
- break;
- case NPNVjavascriptEnabledBool :
- *(static_cast<NPBool*>(result)) = TRUE;
- break;
- case NPNVasdEnabledBool :
- *(static_cast<NPBool*>(result)) = FALSE;
- break;
- case NPNVisOfflineBool :
- *(reinterpret_cast<NPBool*>(result)) = FALSE;
- break;
- case NPNVWindowNPObject :
- ++browser_proxy->GetVWindowObject()->referenceCount;
- *(static_cast<NPObject**>(result)) =
- browser_proxy->GetVWindowObject();
- break;
- case NPNVPluginElementNPObject :
- ATLASSERT(false && "NPNVPluginElementNPObject not supported.");
- return NPERR_GENERIC_ERROR;
- default:
- ATLASSERT(false && "Unrecognized NPN_GetValue request.");
- return NPERR_GENERIC_ERROR;
- }
-
- return NPERR_NO_ERROR;
-}
-
-NPError NPBrowserProxy::NPN_SetValue(NPP npp,
- NPPVariable variable,
- void *result) {
- if (!npp) {
- return NPERR_INVALID_INSTANCE_ERROR;
- }
- ATLASSERT(false && "NPN_SetValue not implemented.");
- return NPERR_GENERIC_ERROR;
-}
-
-NPError NPBrowserProxy::NPN_RequestRead(NPStream *pstream,
- NPByteRange *rangeList) {
- if (!pstream || !rangeList || !pstream->ndata) {
- return NPERR_INVALID_PARAM;
- }
- ATLASSERT(false && "NPN_RequestRead not implemented.");
- return NPERR_GENERIC_ERROR;
-}
-
-void* NPBrowserProxy::NPN_GetJavaEnv() {
- return NULL;
-}
-
-
-const char* NPBrowserProxy::NPN_UserAgent(NPP npp) {
- if (!npp) {
- return "";
- }
-
- NPBrowserProxy *browser_proxy = static_cast<NPBrowserProxy*>(npp->ndata);
- ATLASSERT(browser_proxy);
- return browser_proxy->GetHostingControl()->GetUserAgent();
-}
-
-void* NPBrowserProxy::NPN_GetJavaClass(void* handle) {
- return NULL;
-}
-
-void* NPBrowserProxy::NPN_GetJavaPeer(NPP npp) {
- return NULL;
-}
-
-NPObject* NPBrowserProxy::NPN_CreateObject(NPP npp,
- NPClass *aClass) {
- if (!npp || !aClass) {
- return NULL;
- }
-
- NPObject *new_object = NULL;
-
- // If the class exports a custom allocation routine, then invoke that.
- if (aClass->allocate) {
- new_object = aClass->allocate(npp, aClass);
- new_object->_class = aClass;
- } else {
- new_object = new NPObject;
- new_object->_class = aClass;
- }
-
- new_object->referenceCount = 1;
-
- return new_object;
-}
-
-NPObject * NPBrowserProxy::NPN_RetainObject(NPObject *obj) {
- if (obj) {
- ++obj->referenceCount;
- }
- return obj;
-}
-
-
-void NPBrowserProxy::NPN_ReleaseObject(NPObject *object) {
- if (object) {
- if (0 == --object->referenceCount) {
- if (object->_class->deallocate) {
- object->_class->deallocate(object);
- } else {
- delete object;
- }
- }
- }
-}
-
-// Disable warnings concerning reinterpret casts to un-related pointer types
-// for the below functions.
-#pragma warning(push)
-#pragma warning(disable:4312)
-#pragma warning(disable:4311)
-
-namespace {
-const uint32_t kNPIdentifierIntFlag = 0x1;
-}
-
-NPIdentifier NPBrowserProxy::NPN_GetStringIdentifier(const NPUTF8 *name) {
- // Note that this routine returns the address of the string as it is stored
- // in a set. This implies that any virtual address value could be the
- // returned identifier. The name & description properties of the CHostControl
- // object will not conflict with these, because they are within the VMA region
- // that is unmapped.
- static std::set<std::string> identifiers;
- std::string std_name(name);
- std::pair<std::set<std::string>::iterator, bool> result =
- identifiers.insert(std_name);
- const std::string& key = *(result.first);
- uint32_t tag = reinterpret_cast<uint32_t>(&key);
- ATLASSERT(0 == (tag & kNPIdentifierIntFlag));
- return reinterpret_cast<NPIdentifier>(tag);
-}
-
-void NPBrowserProxy::NPN_GetStringIdentifiers(const NPUTF8 **names,
- int32_t nameCount,
- NPIdentifier *identifiers) {
- for (int x = 0; x < nameCount; ++x) {
- identifiers[x] = NPN_GetStringIdentifier(names[x]);
- }
-}
-
-NPUTF8 * NPBrowserProxy::NPN_UTF8FromIdentifier(NPIdentifier identifier) {
- ATLASSERT(identifier != NULL);
- int32_t tag = reinterpret_cast<uint32_t>(identifier);
- if (0 == (tag & kNPIdentifierIntFlag)) {
- const std::string* key = reinterpret_cast<const std::string*>(tag);
- NPUTF8* identifier_value = static_cast<NPUTF8*>(
- NPN_MemAlloc(static_cast<uint32_t>(key->length() + 1)));
- memcpy(identifier_value, key->c_str(), key->length() + 1);
- return identifier_value;
- } else {
- // This is not a standard feature of NPN_UTF8FromIdentifier. Normally you
- // cannot convert an integer identifier to a string. We support it here
- // because IE and COM represent integer identifiers as strings in places.
- // For example, if IDispathEx::GetMemberName is invoked with an id for
- // an integer indexed property, the only things to do are return a
- // string representation of the integer or an error.
- CStringA string;
- string.Format("%d", tag >> 1);
- NPUTF8* identifier_value = static_cast<NPUTF8*>(
- NPN_MemAlloc(string.GetLength() + 1));
- memcpy(identifier_value, string.GetBuffer(), string.GetLength() + 1);
- return identifier_value;
- }
-}
-
-NPIdentifier NPBrowserProxy::NPN_GetIntIdentifier(int32_t intid) {
- ATLASSERT(intid <= 0x7FFFFFFF);
- return reinterpret_cast<NPIdentifier>((intid << 1) | kNPIdentifierIntFlag);
-}
-
-int32_t NPBrowserProxy::NPN_IntFromIdentifier(NPIdentifier identifier) {
- ATLASSERT(identifier != NULL);
- int32_t tag = reinterpret_cast<int32_t>(identifier);
- ATLASSERT(kNPIdentifierIntFlag == (tag & kNPIdentifierIntFlag));
- return tag >> 1;
-}
-
-bool NPBrowserProxy::NPN_IdentifierIsString(NPIdentifier identifier) {
- ATLASSERT(identifier != NULL);
- uint32_t tag = reinterpret_cast<uint32_t>(identifier);
- return (tag & kNPIdentifierIntFlag) == 0;
-}
-
-#pragma warning(pop)
-
-void NPBrowserProxy::NPN_ReleaseVariantValue(NPVariant *variant) {
- switch (variant->type) {
- case NPVariantType_Void:
- case NPVariantType_Null:
- case NPVariantType_Bool:
- case NPVariantType_Int32:
- case NPVariantType_Double:
- break;
- case NPVariantType_String:
- NPN_MemFree(
- const_cast<NPUTF8*>(variant->value.stringValue.UTF8Characters));
- break;
- case NPVariantType_Object:
- NPN_ReleaseObject(variant->value.objectValue);
- break;
- default:
- ATLASSERT(false && "Unrecognized NPVariant type.");
- break;
- }
-}
-
-bool NPBrowserProxy::NPN_GetProperty(NPP npp,
- NPObject *obj,
- NPIdentifier propertyName,
- NPVariant *result) {
- if (!npp || !obj || !obj->_class->getProperty) {
- return false;
- }
- return obj->_class->getProperty(obj, propertyName, result);
-}
-
-bool NPBrowserProxy::NPN_SetProperty(NPP npp,
- NPObject *obj,
- NPIdentifier propertyName,
- const NPVariant *value) {
- if (!npp || !obj || !obj->_class->setProperty) {
- return false;
- }
- return obj->_class->setProperty(obj, propertyName, value);
-}
-
-bool NPBrowserProxy::NPN_HasProperty(NPP npp,
- NPObject *npobj,
- NPIdentifier propertyName) {
- if (!npp || !npobj || !npobj->_class->hasProperty) {
- return false;
- }
- return npobj->_class->hasProperty(npobj, propertyName);
-}
-
-bool NPBrowserProxy::NPN_RemoveProperty(NPP npp,
- NPObject *npobj,
- NPIdentifier propertyName) {
- if (!npp || !npobj || !npobj->_class->removeProperty) {
- return false;
- }
- return npobj->_class->removeProperty(npobj, propertyName);
-}
-
-bool NPBrowserProxy::NPN_HasMethod(NPP npp,
- NPObject *npobj,
- NPIdentifier methodName) {
- if (!npp || !npobj || !npobj->_class->hasMethod) {
- return false;
- }
- return npobj->_class->hasMethod(npobj, methodName);
-}
-
-bool NPBrowserProxy::NPN_Invoke(NPP npp,
- NPObject *obj,
- NPIdentifier methodName,
- const NPVariant *args,
- unsigned argCount,
- NPVariant *result) {
- if (!npp || !obj || !obj->_class->invoke) {
- return false;
- }
- return obj->_class->invoke(obj, methodName, args, argCount, result);
-}
-
-bool NPBrowserProxy::NPN_InvokeDefault(NPP npp,
- NPObject *obj,
- const NPVariant *args,
- unsigned argCount,
- NPVariant *result) {
- if (!npp || !obj || !obj->_class->invokeDefault) {
- return false;
- }
- return obj->_class->invokeDefault(obj, args, argCount, result);
-}
-
-bool NPBrowserProxy::NPN_Construct(NPP npp,
- NPObject *obj,
- const NPVariant *args,
- unsigned argCount,
- NPVariant *result) {
- if (!npp || !obj || !obj->_class->construct) {
- return false;
- }
- return obj->_class->construct(obj, args, argCount, result);
-}
-
-bool NPBrowserProxy::NPN_Enumerate(NPP npp,
- NPObject* obj,
- NPIdentifier** ids,
- uint32_t* idCount) {
- if (!npp || !obj || !obj->_class->enumerate || !ids || !idCount) {
- return false;
- }
- return obj->_class->enumerate(obj, ids, idCount);
-}
-
-// Construct a new JavaScript object using the given global constructor
-// and argument values.
-bool NPBrowserProxy::ConstructObject(NPP npp,
- NPObject* window_object,
- NPUTF8* constructor_name,
- NPVariant* args,
- uint32_t numArgs,
- NPObject** result) {
- bool success = false;
- NPIdentifier constructor_identifier = NPN_GetStringIdentifier(
- constructor_name);
- NPVariant constructor_variant;
- if (NPN_GetProperty(npp, window_object, constructor_identifier,
- &constructor_variant)) {
- if (NPVARIANT_IS_OBJECT(constructor_variant)) {
- NPObject* constructor_object = NPVARIANT_TO_OBJECT(constructor_variant);
- if (constructor_object != NULL) {
- NPVariant object_variant;
- if (NPN_InvokeDefault(npp, constructor_object, args, numArgs,
- &object_variant)) {
- if (NPVARIANT_IS_OBJECT(object_variant)) {
- *result = NPVARIANT_TO_OBJECT(object_variant);
- NPN_RetainObject(*result);
- success = true;
- }
- NPN_ReleaseVariantValue(&object_variant);
- }
- }
- }
- NPN_ReleaseVariantValue(&constructor_variant);
- }
- return success;
-}
-
-bool NPBrowserProxy::NPN_Evaluate(NPP npp,
- NPObject *obj,
- NPString *script,
- NPVariant *result) {
- if (!npp || !obj || !script) {
- return false;
- }
-
- NPBrowserProxy *browser_proxy = static_cast<NPBrowserProxy*>(npp->ndata);
- CHostControl *host_control = browser_proxy->GetHostingControl();
- ATLASSERT(host_control);
-
- NPObject* window_object = browser_proxy->GetVWindowObject();
- if (obj != window_object) {
- return false;
- }
-
- // Causing IE to run JavaScript code is straightforward if you don't need the
- // result of the evaluation. You can just call IHTMLWindow::execScript. It
- // does not return a valid result though (it specifically says that on MSDN).
- //
- // I tried two other approaches, both of which had the same issue: they didn't
- // return the result. The first unsuccessul approach was to get the "eval"
- // propery of the window object and invoke it as a function with the JS code
- // as the argument. That returns no result. The second unsuccessful approach
- // was to get the "Function" constructor from the window object and invoke it
- // with the JS code as an argument. That should give you a function object and
- // invoking it should evaluate the JS code and return the result. It does not
- // return a result.
- //
- // The final approach (which worked) is to create a Function that additionally
- // takes a temporary object as an argument. The JS code is modified to assign
- // its result to a property of that temporary object called "result". After
- // evaluating the function, the result can then be retrieved from the
- // temporary object.
- bool success = false;
- NPObject* result_object;
- if (ConstructObject(npp, window_object, "Object", NULL, 0, &result_object)) {
- CStringA function_code;
- function_code.Format("result_object.result = (%s);",
- script->UTF8Characters);
-
- NPVariant args[2];
- STRINGZ_TO_NPVARIANT("result_object", args[0]);
- STRINGN_TO_NPVARIANT(function_code.GetBuffer(),
- (uint32_t) function_code.GetLength(),
- args[1]);
- NPObject* function_object;
- if (ConstructObject(npp, window_object, "Function", args, 2,
- &function_object)) {
- OBJECT_TO_NPVARIANT(result_object, args[0]);
- NPVariant dummy_result;
- if (NPN_InvokeDefault(npp, function_object, args, 1, &dummy_result)) {
- NPIdentifier result_identifier = NPN_GetStringIdentifier("result");
- if (NPN_GetProperty(npp, result_object, result_identifier, result)) {
- success = true;
- }
- NPN_ReleaseVariantValue(&dummy_result);
- }
- NPN_ReleaseObject(function_object);
- }
- NPN_ReleaseObject(result_object);
- }
- return success;
-}
-
-void NPBrowserProxy::NPN_PluginThreadAsyncCall(NPP npp,
- void (*function)(void *),
- void *data) {
- if (!npp || !function) {
- return;
- }
-
- NPBrowserProxy *browser_proxy = static_cast<NPBrowserProxy*>(npp->ndata);
- CHostControl *host_control = browser_proxy->GetHostingControl();
- ATLASSERT(host_control);
-
- host_control->PostMessage(WM_PLUGINASYNCCALL,
- reinterpret_cast<WPARAM>(function),
- reinterpret_cast<LPARAM>(data));
-}
-
-void NPBrowserProxy::NPN_SetException(NPObject *obj,
- const NPUTF8 *message) {
- ATLASSERT(false && "NPN_SetException not implemented");
-}
-
-NPNetscapeFuncs* NPBrowserProxy::GetBrowserFunctions() {
- return &kNetscapeFunctions;
-}
-
-void NPBrowserProxy::TearDown() {
- // All NPObjectProxy instances stored in the java-script environment must
- // be marked so that scripted operations on these operations fail after
- // the plug-in has been torn down. We release the hosted object on all of
- // these wrappers to prevent access, and allow deletion of the NPAPI objects.
- NPObjectProxyMap::iterator np_object_iter(np_object_proxy_map_.begin()),
- np_object_end(np_object_proxy_map_.end());
- for (; np_object_iter != np_object_end; ++np_object_iter) {
- np_object_iter->second->ReleaseHosted();
- }
-}
diff --git a/o3d/plugin/npapi_host_control/win/np_browser_proxy.h b/o3d/plugin/npapi_host_control/win/np_browser_proxy.h
deleted file mode 100644
index 2bcd63d..0000000
--- a/o3d/plugin/npapi_host_control/win/np_browser_proxy.h
+++ /dev/null
@@ -1,282 +0,0 @@
-// Copyright 2009, Google Inc. All rights reserved.
-// Portions of this file were adapted from the Mozilla project.
-// See https://developer.mozilla.org/en/ActiveX_Control_for_Hosting_Netscape_Plug-ins_in_IE
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1994-2000
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- * Adam Lock <adamlock@eircom.net>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-
-// File declaring NPBrowserProxy class providing a subset of the NPAPI browser
-// entry points for hosting Mozilla NPAPI plugin objects.
-
-#ifndef O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_NP_BROWSER_PROXY_H_
-#define O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_NP_BROWSER_PROXY_H_
-
-#include <dispex.h>
-#include <map>
-#include "third_party/npapi/include/npfunctions.h"
-#include "plugin/npapi_host_control/win/dispatch_proxy.h"
-#include "plugin/npapi_host_control/win/np_object_proxy.h"
-
-class CHostControl;
-class DispatchProxy;
-
-// Class implementing the NPAPI browser interface for an ActiveX environment.
-class NPBrowserProxy {
- public:
- explicit NPBrowserProxy(CHostControl* host, IDispatchEx* window_dispatch);
- ~NPBrowserProxy();
-
- // Returns the 'v-table' object for interacting with the NPAPI interface
- // of the hosted browser environment.
- static NPNetscapeFuncs* GetBrowserFunctions();
-
- // Returns the hosting COM control.
- CHostControl* GetHostingControl() {
- return host_control_;
- }
-
- // Returns a place-holder object for the browser property. Used in
- // conjunction with NPN_GetValue and NPNVWindowNPObject.
- DispatchProxy* GetVWindowObject() {
- return vwindow_object_;
- }
-
- // Create or get the existing COM object for the given NPObject. Ensures
- // each NPObject only has a single proxy.
- CComPtr<IDispatchEx> GetDispatchObject(NPObject* np_object);
-
- // Create or get the existing NPObject for the given COM object. Ensures
- // each COM object only has a single proxy. Caller must release the object.
- NPObject* GetNPObject(IDispatch* dispatch_object);
-
- // Registers an NPObject with its associated INPObjectProxy.
- void RegisterNPObjectProxy(
- NPObject* np_object,
- const CComPtr<INPObjectProxy>& proxy_wrapper);
-
- // Called by the NPObjectProxy when it is destroyed.
- void UnregisterNPObjectProxy(NPObject* np_object);
-
- // Called by the DispatchProxy when it is destroyed.
- void UnregisterDispatchProxy(IDispatchEx* dispatch_object);
-
- NPIdentifier call_identifier() const { return call_identifier_; }
-
- // Prepares all allocated resources for the destruction of the NPBrowserProxy
- // instance. Ensures that all objects returned to the IE scripting
- // environment become unaccessable.
- void TearDown();
-
- private:
- typedef std::map<NPObject*, CComPtr<INPObjectProxy> > NPObjectProxyMap;
-
- typedef std::map<IUnknown*, DispatchProxy*> DispatchProxyMap;
-
- // Back-pointer to the COM control hosting the NPAPI plug-in.
- CHostControl* host_control_;
-
- // Pointer to place-holder object for the NPNVWindowNPObject value
- // accessible through NPN_GetValue.
- DispatchProxy* vwindow_object_;
-
- // Map of all NPObjects wrapped with NPObjectProxys.
- NPObjectProxyMap np_object_proxy_map_;
-
- // Map of all IDispatchEx objects wrapped with DispatchProxies.
- DispatchProxyMap dispatch_proxy_map_;
-
- NPIdentifier call_identifier_;
-
- // The following functions implement a sub-set of the NPAPI browser object
- // interface. The function naming has been preserved from that in the
- // NPAPI interface headers. For documentation on the expected behaviour
- // of these routines, please refer to the following:
- // http://developer.mozilla.org/en/Gecko_Plugin_API_Reference/Plug-in_Side_Plug-in_API
- static NPError NPN_RequestRead(NPStream *pstream, NPByteRange *rangeList);
-
- static NPError NPN_GetURLNotify(NPP npp,
- const char* relativeURL,
- const char* target,
- void* notifyData);
-
- static NPError NPN_GetValue(NPP npp, NPNVariable variable, void *r_value);
-
- static NPError NPN_SetValue(NPP npp, NPPVariable variable, void *r_value);
-
- static NPError NPN_GetURL(NPP npp,
- const char* relativeURL,
- const char* target);
-
- static NPError NPN_PostURLNotify(NPP npp,
- const char* relativeURL,
- const char *target,
- uint32 len,
- const char *buf,
- NPBool file,
- void* notifyData);
-
- static NPError NPN_PostURL(NPP npp,
- const char* relativeURL,
- const char *target,
- uint32 len,
- const char *buf,
- NPBool file);
-
- static NPError NPN_NewStream(NPP npp,
- NPMIMEType type,
- const char* window,
- NPStream **pstream);
-
- static int32 NPN_Write(NPP npp, NPStream *pstream, int32 len, void *buffer);
-
- static NPError NPN_DestroyStream(NPP npp, NPStream *pstream, NPError reason);
-
- static void NPN_Status(NPP npp, const char *message);
-
- static void* NPN_MemAlloc(uint32 size);
-
- static void NPN_MemFree(void *ptr);
-
- static uint32 NPN_MemFlush(uint32 size);
-
- static void NPN_ReloadPlugins(NPBool reloadPages);
-
- static void NPN_InvalidateRect(NPP npp, NPRect *invalidRect);
-
- static void NPN_InvalidateRegion(NPP npp, NPRegion invalidRegion);
-
- static const char* NPN_UserAgent(NPP npp);
-
- static void* NPN_GetJavaEnv(void);
-
- static void* NPN_GetJavaPeer(NPP npp);
-
- static void* NPN_GetJavaClass(void* handle);
-
- static void NPN_ForceRedraw(NPP npp);
-
- static NPObject* NPN_CreateObject(NPP npp, NPClass *aClass);
-
- static NPObject* NPN_RetainObject(NPObject *object);
-
- static void NPN_ReleaseObject(NPObject *object);
-
- static NPIdentifier NPN_GetStringIdentifier(const NPUTF8 *name);
-
- static void NPN_GetStringIdentifiers(const NPUTF8 **names,
- int32_t nameCount,
- NPIdentifier *identifiers);
-
- static NPUTF8* NPN_UTF8FromIdentifier(NPIdentifier identifier);
-
- static NPIdentifier NPN_GetIntIdentifier(int32_t intid);
- static int32_t NPN_IntFromIdentifier(NPIdentifier identifier);
- static bool NPN_IdentifierIsString(NPIdentifier identifier);
-
- static void NPN_ReleaseVariantValue(NPVariant *variant);
-
- static bool NPN_GetProperty(NPP npp, NPObject *obj,
- NPIdentifier propertyName,
- NPVariant *result);
-
- static bool NPN_SetProperty(NPP npp,
- NPObject *obj,
- NPIdentifier propertyName,
- const NPVariant *value);
-
- static bool NPN_HasProperty(NPP npp,
- NPObject *npobj,
- NPIdentifier propertyName);
-
- static bool NPN_RemoveProperty(NPP npp,
- NPObject *npobj,
- NPIdentifier propertyName);
-
- static bool NPN_HasMethod(NPP npp,
- NPObject *npobj,
- NPIdentifier methodName);
-
- static bool NPN_Invoke(NPP npp,
- NPObject *obj,
- NPIdentifier methodName,
- const NPVariant *args,
- unsigned argCount,
- NPVariant *result);
-
- static bool NPN_InvokeDefault(NPP npp,
- NPObject *obj,
- const NPVariant *args,
- unsigned argCount,
- NPVariant *result);
-
- static bool NPN_Construct(NPP npp,
- NPObject *obj,
- const NPVariant *args,
- unsigned argCount,
- NPVariant *result);
-
- static bool NPN_Enumerate(NPP npp,
- NPObject* obj,
- NPIdentifier** ids,
- uint32_t* idCOunt);
-
- static bool ConstructObject(NPP npp,
- NPObject* window_object,
- NPUTF8* constructor_name,
- NPVariant* args,
- uint32_t numArgs,
- NPObject** result);
-
- static bool NPN_Evaluate(NPP npp,
- NPObject *obj,
- NPString *script,
- NPVariant *result);
-
- static void NPN_PluginThreadAsyncCall(NPP npp,
- void (*function)(void *),
- void *data);
-
- static void NPN_SetException(NPObject *obj, const NPUTF8 *message);
-
- // Static table of function pointers to the member function entry points
- // for the NPAPI browser environment interface.
- static NPNetscapeFuncs kNetscapeFunctions;
-
- DISALLOW_COPY_AND_ASSIGN(NPBrowserProxy);
-};
-
-#endif // O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_NP_BROWSER_PROXY_H_
diff --git a/o3d/plugin/npapi_host_control/win/np_object_proxy.cc b/o3d/plugin/npapi_host_control/win/np_object_proxy.cc
deleted file mode 100644
index b70b02b..0000000
--- a/o3d/plugin/npapi_host_control/win/np_object_proxy.cc
+++ /dev/null
@@ -1,518 +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 <oaidl.h>
-#include <atlstr.h>
-#include <vector>
-
-#include "base/scoped_ptr.h"
-#include "plugin/npapi_host_control/win/np_object_proxy.h"
-#include "plugin/npapi_host_control/win/np_browser_proxy.h"
-#include "plugin/npapi_host_control/win/variant_utils.h"
-#include "third_party/npapi/include/npfunctions.h"
-
-namespace {
-
-// Helper routine copying NPVariant object to a destination COM Variant.
-// Both arguments may be null. Argument com_result must be a properly
-// initialized VARIANT instance.
-void CopyToCOMResult(NPBrowserProxy* browser_proxy,
- NPVariant* np_result,
- VARIANT* com_result) {
- if (com_result && np_result) {
- CComVariant intermediate_result;
- NPVariantToVariant(browser_proxy, np_result, &intermediate_result);
- VariantCopy(com_result, &intermediate_result);
- }
-}
-
-} // unnamed namespace
-
-
-NPObjectProxy::NPObjectProxy()
- : hosted_(NULL),
- browser_proxy_(NULL) {
-}
-
-NPObjectProxy::~NPObjectProxy() {
- if (hosted_) {
- if (browser_proxy_) {
- browser_proxy_->UnregisterNPObjectProxy(hosted_);
- }
- NPBrowserProxy::GetBrowserFunctions()->releaseobject(hosted_);
- }
-}
-
-STDMETHODIMP NPObjectProxy::SetHostedObject(void* hosted) {
- ATLASSERT(hosted);
- if (hosted_) {
- NPBrowserProxy::GetBrowserFunctions()->releaseobject(hosted_);
- }
- hosted_ = static_cast<NPObject*>(hosted);
- NPBrowserProxy::GetBrowserFunctions()->retainobject(hosted_);
- return S_OK;
-}
-
-STDMETHODIMP NPObjectProxy::ReleaseHosted() {
- if (hosted_) {
- NPBrowserProxy::GetBrowserFunctions()->releaseobject(hosted_);
- hosted_ = NULL;
- }
- return S_OK;
-}
-
-STDMETHODIMP NPObjectProxy::GetTypeInfoCount(UINT* pctinfo) {
- // This class does not support type info.
- if (!pctinfo) {
- return E_POINTER;
- } else {
- *pctinfo = 0;
- }
- return S_OK;
-}
-
-STDMETHODIMP NPObjectProxy::GetTypeInfo(UINT itinfo,
- LCID lcid,
- ITypeInfo** pptinfo) {
- // This class does not support type info.
- return E_NOTIMPL;
-}
-
-STDMETHODIMP NPObjectProxy::GetIDsOfNames(REFIID riid,
- LPOLESTR* rgszNames,
- UINT cNames,
- LCID lcid,
- DISPID* rgdispid) {
- if (!hosted_) {
- return E_FAIL;
- }
-
- // Use the ids from the plugin to return dispatch ids
- NPIdentifier *supported_ids = NULL;
- uint32 id_count = 0;
-
- if (!hosted_->_class->enumerate(hosted_, &supported_ids, &id_count)) {
- return E_FAIL;
- }
-
- // Convert all of the wide string arguments to UTF-8.
- scoped_array<char *> utf8_names(new char*[cNames]);
- for (UINT x = 0; x < cNames; ++x) {
- size_t name_length = wcstombs(NULL, rgszNames[x], 0) + 1;
- utf8_names[x] = new char[name_length];
- wcstombs(utf8_names[x], rgszNames[x], name_length);
- rgdispid[x] = DISPID_UNKNOWN;
- }
-
- int ids_found = 0;
- // For each string in the input arguments, look for a match in the set of
- // ids supported by the object instance.
- NPUTF8 *string_id = NULL;
- for (uint32 x = 0; x < id_count; ++x) {
- string_id = NPBrowserProxy::GetBrowserFunctions()->
- utf8fromidentifier(supported_ids[x]);
- ATLASSERT(string_id);
- for (UINT y = 0; y < cNames; ++y) {
- if (strcmp(utf8_names[y], string_id) == 0) {
- // Return the ADDRESS of the supported ids string as the DISPID
- // for the method.
- rgdispid[y] = reinterpret_cast<DISPID>(supported_ids[x]);
- ++ids_found;
- break;
- }
- }
- NPBrowserProxy::GetBrowserFunctions()->memfree(string_id);
- }
-
- // Free all intermediate string resources.
- for (UINT x = 0; x < cNames; ++x) {
- delete[] utf8_names[x];
- }
- NPBrowserProxy::GetBrowserFunctions()->memfree(supported_ids);
-
- return (ids_found == cNames) ? S_OK : DISP_E_UNKNOWNNAME;
-}
-
-STDMETHODIMP NPObjectProxy::Invoke(DISPID dispidMember,
- REFIID riid,
- LCID lcid,
- WORD wFlags,
- DISPPARAMS* pdispparams,
- VARIANT* pvarResult,
- EXCEPINFO* pexcepinfo,
- UINT* puArgErr) {
- if (!hosted_) {
- return E_FAIL;
- }
-
- return InvokeEx(dispidMember, lcid, wFlags, pdispparams, pvarResult,
- pexcepinfo, NULL);
-}
-
-STDMETHODIMP NPObjectProxy::DeleteMemberByDispID(DISPID id) {
- if (!hosted_) {
- return E_FAIL;
- }
-
- NPIdentifier np_identifier = reinterpret_cast<NPIdentifier>(id);
- if (hosted_->_class->removeProperty != NULL &&
- hosted_->_class->removeProperty(hosted_, np_identifier)) {
- return S_OK;
- }
- return S_FALSE;
-}
-
-STDMETHODIMP NPObjectProxy::DeleteMemberByName(BSTR bstrName, DWORD grfdex) {
- if (!hosted_) {
- return E_FAIL;
- }
- DISPID id;
- HRESULT hr = GetDispID(bstrName, grfdex, &id);
- if (hr == DISP_E_UNKNOWNNAME) {
- // The semantics of JavaScript are that deleting a property that does not
- // exist succeeds.
- return S_OK;
- } else if (FAILED(hr)) {
- // Otherwise fail.
- return S_FALSE;
- } else {
- return DeleteMemberByDispID(id);
- }
-}
-
-STDMETHODIMP NPObjectProxy::GetDispID(BSTR bstrName,
- DWORD grfdex,
- DISPID* pid) {
- if (!hosted_) {
- return E_FAIL;
- }
-
- *pid = NULL;
- CString name(bstrName);
- int num_utf8_bytes = WideCharToMultiByte(CP_UTF8, 0, name.GetBuffer(),
- name.GetLength() + 1, NULL, 0,
- NULL, NULL);
- std::vector<NPUTF8> utf8_name(num_utf8_bytes);
- WideCharToMultiByte(CP_UTF8, 0, name.GetBuffer(), name.GetLength() + 1,
- &utf8_name[0], num_utf8_bytes, NULL, NULL);
-
- NPIdentifier np_identifier =
- NPBrowserProxy::GetBrowserFunctions()->getstringidentifier(
- &utf8_name[0]);
-
- // This method can be called to determine whether an object has a property
- // with the given name. So check that before converting to an NPIdentifier.
- if (!HasPropertyOrMethod(np_identifier))
- return DISP_E_UNKNOWNNAME;
-
- *pid = reinterpret_cast<DISPID>(np_identifier);
- return S_OK;
-}
-
-STDMETHODIMP NPObjectProxy::GetMemberName(DISPID id,
- BSTR* pbstrName) {
- if (!hosted_) {
- return E_FAIL;
- }
- NPIdentifier np_identifier = reinterpret_cast<NPIdentifier>(id);
-
- // Make sure the id is valid on this object. It might have been deleted since
- // it was returned by GetDispID.
- if (!HasPropertyOrMethod(np_identifier))
- return DISP_E_UNKNOWNNAME;
-
- NPUTF8* utf8_name = NPBrowserProxy::GetBrowserFunctions()->utf8fromidentifier(
- np_identifier);
- int num_wide_chars = MultiByteToWideChar(CP_UTF8, 0, utf8_name, -1, NULL, 0);
- CString name;
- MultiByteToWideChar(CP_UTF8, 0, utf8_name, -1,
- name.GetBuffer(num_wide_chars), num_wide_chars);
- name.ReleaseBuffer(num_wide_chars - 1);
- *pbstrName = name.AllocSysString();
- NPBrowserProxy::GetBrowserFunctions()->memfree(utf8_name);
- return S_OK;
-}
-
-STDMETHODIMP NPObjectProxy::GetMemberProperties(DISPID id,
- DWORD grfdexFetch,
- DWORD* pgrfdex) {
- if (!hosted_) {
- return E_FAIL;
- }
-
- // NPAPI does not provide a way to get all the information this function
- // expects to be returned. This is what IE7 returns for some native objects.
- return E_NOTIMPL;
-}
-
-STDMETHODIMP NPObjectProxy::GetNameSpaceParent(IUnknown** punk) {
- if (!hosted_) {
- return E_FAIL;
- }
-
- // JavaScript does not have namespaces. An alternative would be to return
- // an error code.
- *punk = NULL;
- return S_OK;
-}
-
-STDMETHODIMP NPObjectProxy::GetNextDispID(DWORD grfdex,
- DISPID id,
- DISPID* pid) {
- if (!hosted_) {
- return E_FAIL;
- }
-
- HRESULT hr = S_FALSE;
- NPIdentifier* ids;
- uint32_t num_ids = 0;
- if (hosted_->_class->enumerate != NULL &&
- hosted_->_class->enumerate(hosted_, &ids, &num_ids)) {
- if (id == DISPID_STARTENUM && num_ids > 0) {
- *pid = reinterpret_cast<DISPID>(ids[0]);
- hr = S_OK;
- } else {
- if (!ids) {
- return S_FALSE;
- }
- uint32_t i;
- for (i = 0; i != num_ids; ++i) {
- if (ids[i] == reinterpret_cast<NPIdentifier>(id))
- break;
- }
- if (i + 1 < num_ids) {
- *pid = reinterpret_cast<DISPID>(ids[i + 1]);
- hr = S_OK;
- }
- }
- NPBrowserProxy::GetBrowserFunctions()->memfree(ids);
- }
- return hr;
-}
-
-STDMETHODIMP NPObjectProxy::InvokeEx(DISPID id,
- LCID lcid,
- WORD wFlags,
- DISPPARAMS* pdb,
- VARIANT* pVarRes,
- EXCEPINFO* pei,
- IServiceProvider* pspCaller) {
- if (!hosted_) {
- return E_FAIL;
- }
- HRESULT hr = E_FAIL;
- NPIdentifier np_identifier = reinterpret_cast<NPIdentifier>(id);
-
- if (wFlags & (DISPATCH_METHOD | DISPATCH_CONSTRUCT)) {
- // Get the "this" pointer if provided or default to the hosted object.
- // We cannot support more general bindings for "this" through npruntime.
- // This might arise if the function is invoked through
- // my_function.call(my_this, args) from JScript.
- if (pdb->cNamedArgs == 1 && pdb->rgdispidNamedArgs[0] == DISPID_THIS) {
- NPVariant np_this_variant;
- VariantToNPVariant(
- browser_proxy_,
- &pdb->rgvarg[0],
- &np_this_variant);
- NPObject* np_this_object = NULL;
- if (NPVARIANT_IS_OBJECT(np_this_variant)) {
- np_this_object = NPVARIANT_TO_OBJECT(np_this_variant);
- }
- NPBrowserProxy::GetBrowserFunctions()->releasevariantvalue(
- &np_this_variant);
- if (np_this_object != hosted_) {
- return E_FAIL;
- }
- } else if (pdb->cNamedArgs != 0) {
- return DISP_E_NONAMEDARGS;
- }
-
- // Convert the arguments to NPVariants.
- int num_unnamed_arguments = pdb->cArgs - pdb->cNamedArgs;
- scoped_array<NPVariant> np_arguments(new NPVariant[num_unnamed_arguments]);
- for (int x = 0; x < num_unnamed_arguments; ++x) {
- // Note that IDispatch expects arguments in the reverse order.
- VariantToNPVariant(
- browser_proxy_,
- &pdb->rgvarg[pdb->cArgs - x - 1],
- &np_arguments[x]);
- }
-
- // IDispatch supports the notion of default methods with the DISPID value
- // DISPID_VALUE.
- NPVariant result;
- if (DISPID_VALUE == id) {
- if (wFlags & DISPATCH_CONSTRUCT) {
- if (hosted_->_class->construct != NULL &&
- hosted_->_class->construct(hosted_,
- np_arguments.get(),
- num_unnamed_arguments,
- &result)) {
- CopyToCOMResult(browser_proxy_, &result, pVarRes);
- NPBrowserProxy::GetBrowserFunctions()->releasevariantvalue(&result);
- hr = S_OK;
- }
- } else {
- if (hosted_->_class->invokeDefault != NULL &&
- hosted_->_class->invokeDefault(hosted_,
- np_arguments.get(),
- num_unnamed_arguments,
- &result)) {
- CopyToCOMResult(browser_proxy_, &result, pVarRes);
- NPBrowserProxy::GetBrowserFunctions()->releasevariantvalue(&result);
- hr = S_OK;
- }
- }
- } else if (hosted_->_class->hasMethod != NULL &&
- hosted_->_class->hasMethod(hosted_, np_identifier)) {
- if (hosted_->_class->invoke != NULL &&
- hosted_->_class->invoke(hosted_,
- np_identifier,
- np_arguments.get(),
- num_unnamed_arguments,
- &result)) {
- CopyToCOMResult(browser_proxy_, &result, pVarRes);
- NPBrowserProxy::GetBrowserFunctions()->releasevariantvalue(&result);
- hr = S_OK;
- }
- } else if (hosted_->_class->hasProperty != NULL &&
- hosted_->_class->hasProperty(hosted_, np_identifier)) {
- // If the object does not have a method with the given identifier,
- // it may have a property with that id that we can invoke the default
- // method upon.
- NPVariant np_property_variant;
- if (hosted_->_class->getProperty != NULL &&
- hosted_->_class->getProperty(hosted_, np_identifier,
- &np_property_variant)) {
- if (NPVARIANT_IS_OBJECT(np_property_variant)) {
- NPObject* np_property_object = NPVARIANT_TO_OBJECT(
- np_property_variant);
- if (np_property_object->_class->invokeDefault != NULL) {
- if (np_property_object->_class->invokeDefault(
- np_property_object,
- np_arguments.get(),
- num_unnamed_arguments,
- &result)) {
- CopyToCOMResult(browser_proxy_, &result, pVarRes);
- NPBrowserProxy::GetBrowserFunctions()->releasevariantvalue(
- &result);
- hr = S_OK;
- }
- } else {
- hr = DISP_E_TYPEMISMATCH;
- }
- } else {
- hr = DISP_E_TYPEMISMATCH;
- }
- NPBrowserProxy::GetBrowserFunctions()->
- releasevariantvalue(&np_property_variant);
- }
- } else {
- hr = DISP_E_MEMBERNOTFOUND;
- }
-
- // Release all of the converted arguments.
- for (int x = 0; x < num_unnamed_arguments; ++x) {
- NPBrowserProxy::GetBrowserFunctions()->releasevariantvalue(
- &np_arguments[x]);
- }
- } else if (wFlags & DISPATCH_PROPERTYPUT) {
- if (pdb->cArgs == 1) {
- if (id == DISPID_VALUE) {
- hr = DISP_E_MEMBERNOTFOUND;
- } else {
- // Convert the COM variant to the corresponding NPVariant.
- NPVariant property_in;
- VariantToNPVariant(browser_proxy_, &pdb->rgvarg[0], &property_in);
- if (hosted_->_class->setProperty != NULL &&
- hosted_->_class->setProperty(hosted_,
- np_identifier,
- &property_in)) {
- hr = S_OK;
- }
- NPBrowserProxy::GetBrowserFunctions()->releasevariantvalue(
- &property_in);
- }
- } else {
- hr = DISP_E_BADPARAMCOUNT;
- }
- } else if (wFlags & DISPATCH_PROPERTYGET) {
- if (pdb->cArgs == 0) {
- // Sometimes JScript asks an object for its default value. Returning
- // itself appears to be ther right thing to do.
- if (id == DISPID_VALUE) {
- pVarRes->vt = VT_DISPATCH;
- pVarRes->pdispVal = this;
- AddRef();
- hr = S_OK;
- } else {
- NPVariant property_out;
- if (hosted_->_class->hasProperty != NULL &&
- !hosted_->_class->hasProperty(hosted_, np_identifier)) {
- hr = DISP_E_MEMBERNOTFOUND;
- } else if (hosted_->_class->getProperty != NULL &&
- hosted_->_class->getProperty(hosted_,
- np_identifier,
- &property_out)) {
- CopyToCOMResult(browser_proxy_, &property_out, pVarRes);
- NPBrowserProxy::GetBrowserFunctions()->releasevariantvalue(
- &property_out);
- hr = S_OK;
- }
- }
- } else {
- hr = DISP_E_BADPARAMCOUNT;
- }
- }
- return hr;
-}
-
-STDMETHODIMP NPObjectProxy::GetNPObjectInstance(void **np_instance) {
- if (!hosted_) {
- return E_FAIL;
- }
-
- *np_instance = hosted_;
- NPBrowserProxy::GetBrowserFunctions()->retainobject(hosted_);
- return S_OK;
-}
-
-bool NPObjectProxy::HasPropertyOrMethod(NPIdentifier np_identifier) {
- if (!hosted_) {
- return false;
- }
-
- return (hosted_->_class->hasProperty != NULL &&
- hosted_->_class->hasProperty(hosted_, np_identifier)) ||
- (hosted_->_class->hasMethod != NULL &&
- hosted_->_class->hasMethod(hosted_, np_identifier));
-}
diff --git a/o3d/plugin/npapi_host_control/win/np_object_proxy.h b/o3d/plugin/npapi_host_control/win/np_object_proxy.h
deleted file mode 100644
index 8f29d25..0000000
--- a/o3d/plugin/npapi_host_control/win/np_object_proxy.h
+++ /dev/null
@@ -1,124 +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.
- */
-
-
-// File declaring NPObjectProxy class. This class wraps the NPAPI scripting
-// interface with a COM IDispatchEx interface to allow interop between ActiveX
-// and NPObject instances.
-
-#ifndef O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_NP_OBJECT_PROXY_H_
-#define O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_NP_OBJECT_PROXY_H_
-
-#include <atlctl.h>
-#include <dispex.h>
-
-// File included without directory because it is auto-generated by the
-// type-lib.
-#include "npapi_host_control.h"
-
-#include "third_party/npapi/include/npfunctions.h"
-
-struct NPObject;
-class NPBrowserProxy;
-
-// COM class implementing a basic IDispatchEx interface that wraps the NPAPI
-// NPObject scripting functionality.
-class ATL_NO_VTABLE NPObjectProxy :
- public CComObjectRootEx<CComSingleThreadModel>,
- public IDispatchImpl<INPObjectProxy, &IID_INPObjectProxy,
- &LIBID_npapi_host_controlLib>,
- public IObjectSafetyImpl<NPObjectProxy,
- INTERFACESAFE_FOR_UNTRUSTED_CALLER> {
- public:
- NPObjectProxy();
- virtual ~NPObjectProxy();
-
-BEGIN_COM_MAP(NPObjectProxy)
- COM_INTERFACE_ENTRY(INPObjectProxy)
- COM_INTERFACE_ENTRY(IDispatch)
- COM_INTERFACE_ENTRY(IDispatchEx)
-END_COM_MAP()
-
- STDMETHOD(SetBrowserProxy)(void* browser_proxy) {
- browser_proxy_ = static_cast<NPBrowserProxy*>(browser_proxy);
- return S_OK;
- }
-
- // Routine implementing INPObjectProxy interface method, returning a raw
- // pointer to a NPObject instance. Note that the reference count of the
- // returned NPObject has been incremented. The returned object should
- // be released by the hosting browser proxy to prevent memory leaks.
- STDMETHOD(GetNPObjectInstance)(void **np_instance);
- STDMETHOD(SetHostedObject)(void* hosted_object);
- STDMETHOD(ReleaseHosted)();
-
- // Routines implementing the IDispatchEx COM interface.
- STDMETHOD(GetTypeInfoCount)(UINT* pctinfo);
- STDMETHOD(GetTypeInfo)(UINT itinfo, LCID lcid, ITypeInfo** pptinfo);
- STDMETHOD(GetIDsOfNames)(REFIID riid,
- LPOLESTR* rgszNames,
- UINT cNames,
- LCID lcid,
- DISPID* rgdispid);
- STDMETHOD(Invoke)(DISPID dispidMember,
- REFIID riid,
- LCID lcid,
- WORD wFlags,
- DISPPARAMS* pdispparams,
- VARIANT* pvarResult,
- EXCEPINFO* pexcepinfo,
- UINT* puArgErr);
-
- STDMETHOD(DeleteMemberByDispID)(DISPID id);
- STDMETHOD(DeleteMemberByName)(BSTR bstrName, DWORD grfdex);
- STDMETHOD(GetDispID)(BSTR bstrName, DWORD grfdex, DISPID* pid);
- STDMETHOD(GetMemberName)(DISPID id, BSTR* pbstrName);
- STDMETHOD(GetMemberProperties)(DISPID id, DWORD grfdexFetch, DWORD* pgrfdex);
- STDMETHOD(GetNameSpaceParent)(IUnknown** ppunk);
- STDMETHOD(GetNextDispID)(DWORD grfdex, DISPID id, DISPID* pid);
- STDMETHOD(InvokeEx)(DISPID id, LCID lcid, WORD wFlags, DISPPARAMS* pdp,
- VARIANT* pVarRes, EXCEPINFO* pei,
- IServiceProvider* pspCaller);
-
- DECLARE_PROTECT_FINAL_CONSTRUCT();
- private:
- bool HasPropertyOrMethod(NPIdentifier np_identifier);
-
- // Pointer to NPObject for which this instance is a proxy IDispatchEx.
- NPObject *hosted_;
-
- // Back-pointer to the NPAPI browser proxy.
- NPBrowserProxy* browser_proxy_;
-
- DISALLOW_COPY_AND_ASSIGN(NPObjectProxy);
-};
-
-#endif // O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_NP_OBJECT_PROXY_H_
diff --git a/o3d/plugin/npapi_host_control/win/np_plugin_proxy.cc b/o3d/plugin/npapi_host_control/win/np_plugin_proxy.cc
deleted file mode 100644
index 5404c5f..0000000
--- a/o3d/plugin/npapi_host_control/win/np_plugin_proxy.cc
+++ /dev/null
@@ -1,454 +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 "plugin/npapi_host_control/win/np_plugin_proxy.h"
-
-#include <shlobj.h>
-#include <shlwapi.h>
-
-#include <algorithm>
-#include "base/scoped_ptr.h"
-#include "plugin/npapi_host_control/win/module.h"
-#include "plugin/npapi_host_control/win/np_browser_proxy.h"
-#include "plugin/npapi_host_control/win/np_object_proxy.h"
-#include "plugin/npapi_host_control/win/stream_operation.h"
-
-namespace {
-
-#define WIDE(s) WIDE2(s)
-#define WIDE2(s) L##s
-
-const wchar_t kPluginName[] = WIDE(O3D_PLUGIN_NPAPI_FILENAME) L".dll";
-const wchar_t kAppDataPluginLocation[] =
- L"Mozilla\\plugins\\" WIDE(O3D_PLUGIN_NPAPI_FILENAME) L".dll";
-
-// Returns the path to the O3D plug-in located in the current user's
-// Application Data directory. Returns NULL on failure.
-// Note: The caller does not need to free the returned string.
-const wchar_t* GetApplicationDataPluginPath() {
- static wchar_t kAppDataPath[MAX_PATH] = {0};
- HRESULT hr = SHGetFolderPath(0, CSIDL_APPDATA, NULL, 0, kAppDataPath);
- if (SUCCEEDED(hr)) {
- PathAppend(kAppDataPath, kAppDataPluginLocation);
- return kAppDataPath;
- } else {
- return NULL;
- }
-}
-
-// Returns a path to the O3D plug-in corresponding to the value of the
-// MOZ_PLUGIN_PATH environment variable. This variable is used to override
-// the default directory where FireFox will search for plug-ins.
-// Note: The caller does not need to free the returned string.
-const wchar_t* GetMozillaPluginPath() {
- static wchar_t kMozillaPluginPath[MAX_PATH] = {0};
- DWORD chars_written = GetEnvironmentVariable(L"MOZ_PLUGIN_PATH",
- kMozillaPluginPath,
- MAX_PATH);
- if (chars_written == 0) {
- return NULL;
- } else if (chars_written > MAX_PATH) {
- ATLASSERT(false && "MOZ_PLUGIN_PATH too large to represent a path.");
- return NULL;
- } else {
- PathAppend(kMozillaPluginPath, kPluginName);
- return kMozillaPluginPath;
- }
-}
-
-const wchar_t kProgramFilesPluginLocation[] =
- L"Mozilla Firefox\\plugins\\" WIDE(O3D_PLUGIN_NPAPI_FILENAME) L".dll";
-
-// Returns the path to the O3D plug-in located in the Program
-// Files directory. Returns NULL on failure.
-// Note: The caller does not need to free the returned string.
-const wchar_t* GetProgramFilesPluginPath() {
- static wchar_t kProgramFilesPath[MAX_PATH] = {0};
- HRESULT hr = SHGetFolderPath(0,
- CSIDL_PROGRAM_FILES,
- NULL,
- 0,
- kProgramFilesPath);
- if (SUCCEEDED(hr)) {
- PathAppend(kProgramFilesPath, kProgramFilesPluginLocation);
- return kProgramFilesPath;
- } else {
- return NULL;
- }
-}
-
-// Helper class implementing RAII semantics for locking the ATL module.
-class AutoModuleLock {
- public:
- AutoModuleLock() {
- NPAPIHostControlModule::LockModule();
- }
- ~AutoModuleLock() {
- NPAPIHostControlModule::UnlockModule();
- }
- private:
- DISALLOW_COPY_AND_ASSIGN(AutoModuleLock);
-};
-
-// Helper routine that populates nested scoped arrays of characters
-// from std vectors of CStringA objects. This routine is used to make
-// a local copy of the name/value arguments to the plug-in instance,
-// so that any local modifications on the arguments performed during
-// plug-in initialization won't propagate to future instantiations of
-// the plug-in.
-void ConstructLocalPluginArgs(const std::vector<CStringA>& names,
- const std::vector<CStringA>& values,
- short* argc,
- scoped_array<scoped_array<char> >* argn,
- scoped_array<scoped_array<char> >* argv) {
- ATLASSERT(argc && argn && argv);
- ATLASSERT(names.size() == values.size());
-
- *argc = static_cast<short>(names.size());
- if (names.empty()) {
- argn->reset(NULL);
- argv->reset(NULL);
- return;
- }
-
- // Copy the contents of the name and value arrays to the scoped_array
- // parameters.
- argn->reset(new scoped_array<char>[*argc]);
- argv->reset(new scoped_array<char>[*argc]);
- for (int x = 0; x < *argc; ++x) {
- char* name = new char[names[x].GetLength() + 1];
- char* value = new char[values[x].GetLength() + 1];
-
- strcpy(name, static_cast<const char*>(names[x]));
- strcpy(value, static_cast<const char*>(values[x]));
-
- (*argn)[x].reset(name);
- (*argv)[x].reset(value);
- }
-}
-
-} // unnamed namespace
-
-int NPPluginProxy::kPluginInstanceCount = 0;
-
-NPPluginProxy::NPPluginProxy()
- : browser_proxy_(NULL),
- scriptable_object_(NULL),
- NP_Initialize_(NULL),
- NP_GetEntryPoints_(NULL),
- NP_Shutdown_(NULL),
- plugin_module_(0),
- initialized_(false) {
- npp_data_.ndata = npp_data_.pdata = NULL;
- memset(&plugin_funcs_, NULL, sizeof(plugin_funcs_));
-}
-
-NPPluginProxy::~NPPluginProxy() {
- // Serialize the destruction of instances so that there are no races on
- // the instance count, and library loads.
- AutoModuleLock lock;
- if (0 == --kPluginInstanceCount) {
- if (NP_Shutdown_) {
- NP_Shutdown_();
- }
- }
-
- FreeLibrary(plugin_module_);
- ATLASSERT(active_stream_ops_.empty() &&
- "Destruction of plugin proxy with still-pending streaming ops.");
-}
-
-bool NPPluginProxy::MapEntryPoints(HMODULE loaded_module) {
- // Initialize the function pointers to the plugin entry points.
- NP_Initialize_ = reinterpret_cast<NP_InitializeFunc>(
- GetProcAddress(loaded_module, "NP_Initialize"));
- NP_GetEntryPoints_ = reinterpret_cast<NP_GetEntryPointsFunc>(
- GetProcAddress(loaded_module, "NP_GetEntryPoints"));
- NP_Shutdown_ = reinterpret_cast<NP_ShutdownFunc>(
- GetProcAddress(loaded_module, "NP_Shutdown"));
-
- if (!NP_Initialize_ || !NP_GetEntryPoints_ || !NP_Shutdown_) {
- ATLASSERT(false && "NPAPI DLL exports not present.");
- return false;
- }
-
- // Plugin-initialization is to be performed once, at initial plug-in
- // loading time. Note that this routine must be accessed serially to
- // protect against races on kPluginInstanceCount.
- if (0 == kPluginInstanceCount) {
- if (NPERR_NO_ERROR != NP_Initialize_(
- browser_proxy_->GetBrowserFunctions())) {
- ATLASSERT(false && "NPAPI initialization failure.");
- return false;
- }
- }
- ++kPluginInstanceCount;
-
- if (NPERR_NO_ERROR != NP_GetEntryPoints_(&plugin_funcs_)) {
- ATLASSERT(false && "Unknown failure getting NPAPI entry points.");
- return false;
- }
-
- plugin_module_ = loaded_module;
- return true;
-}
-
-bool NPPluginProxy::Init(NPBrowserProxy* browser_proxy,
- const NPWindow& window,
- const std::vector<CStringA>& argument_names,
- const std::vector<CStringA>& argument_values) {
- ATLASSERT(plugin_module_ &&
- "Plugin module not loaded before initialization.");
- ATLASSERT(browser_proxy && "Browser environment required for plugin init.");
- ATLASSERT(!initialized_ && "Duplicate initialization");
- browser_proxy_ = browser_proxy;
-
- // Store a pointer to the browser proxy instance in the netscape data
- // of the plugin data. This will be the only access point to the browser
- // instance from within the NPBrowserProxy NPAPI functions.
- npp_data_.ndata = static_cast<void*>(browser_proxy_);
-
- scoped_array<scoped_array<char> > argn, argv;
- short argc;
-
- // Build a local-copy of the plug-in arguments, so that any modifications
- // on the name/value pairs will not be propagated to future instantiations.
- ConstructLocalPluginArgs(argument_names,
- argument_values,
- &argc,
- &argn,
- &argv);
-
- if (NPERR_NO_ERROR != plugin_funcs_.newp(
- "No mime type",
- GetNPP(),
- NP_EMBED,
- argc,
- reinterpret_cast<char**>(argn.get()),
- reinterpret_cast<char**>(argv.get()),
- NULL)) {
- ATLASSERT(false && "Unknown failure creating NPAPI plugin instance.");
- return false;
- }
-
- if (NPERR_NO_ERROR != plugin_funcs_.setwindow(
- GetNPP(),
- const_cast<NPWindow*>(&window))) {
- plugin_funcs_.destroy(GetNPP(), NULL);
- ATLASSERT(false && "Unknown failure binding plugin window.");
- return false;
- }
-
- // We assume that the plugin is scripted, so get the scripting entry points
- // from the plugin.
- NPObject *np_object = NULL;
- if (NPERR_NO_ERROR != plugin_funcs_.getvalue(
- GetNPP(),
- NPPVpluginScriptableNPObject,
- static_cast<void*>(&np_object))) {
- plugin_funcs_.destroy(GetNPP(), NULL);
- ATLASSERT(false && "Unable to initialize NPAPI scripting interface.");
- return false;
- }
- ATLASSERT(np_object);
-
- scriptable_object_ = browser_proxy_->GetDispatchObject(np_object);
-
- NPBrowserProxy::GetBrowserFunctions()->releaseobject(np_object);
-
- initialized_ = true;
-
- return true;
-}
-
-bool NPPluginProxy::SetWindow(const NPWindow& window) {
- // The ATLASSERT() upon failed NPP_New() can generate a reentrant
- // SetWindow() call, which we must be prepared to ignore.
- if (!initialized_) return false;
-
- if (plugin_funcs_.setwindow != NULL &&
- NPERR_NO_ERROR != plugin_funcs_.setwindow(
- GetNPP(),
- const_cast<NPWindow*>(&window))) {
- plugin_funcs_.destroy(GetNPP(), NULL);
- ATLASSERT(false && "Unknown failure re-setting plugin window.");
- return false;
- }
- return true;
-}
-
-void NPPluginProxy::TearDown() {
- // Block until all stream operations requested by this plug-in have
- // completed.
- HRESULT hr;
- std::vector<HANDLE> stream_handles;
- for (StreamOpArray::size_type x = 0; x < active_stream_ops_.size(); ++x) {
- // Request that the stream finish early - so that large file transfers do
- // not block leaving the page.
- hr = active_stream_ops_[x]->RequestCancellation();
- ATLASSERT(SUCCEEDED(hr) &&
- "Failed to request cancellation of pending data stream.");
- stream_handles.push_back(active_stream_ops_[x]->GetThreadHandle());
- }
-
- static const unsigned int kWaitTimeOut = 120000;
- while (!stream_handles.empty()) {
- DWORD wait_code = MsgWaitForMultipleObjects(
- static_cast<DWORD>(stream_handles.size()),
- &stream_handles[0],
- FALSE,
- kWaitTimeOut,
- QS_ALLINPUT);
- wait_code -= WAIT_OBJECT_0;
- if (wait_code == stream_handles.size()) {
- MSG msg;
- GetMessage(&msg, NULL, 0, 0);
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- } else if (wait_code >= 0 && wait_code < stream_handles.size()) {
- // A thread has completed, so remove the handle and continue.
- stream_handles.erase(stream_handles.begin() + wait_code);
- } else {
- if (wait_code == WAIT_TIMEOUT + WAIT_OBJECT_0) {
- ATLASSERT(false &&
- "Time-out waiting for completion of streaming operation.");
- } else {
- ATLASSERT(false &&
- "Unknown error waiting on streaming operation completion.");
- }
- // There has been a catastropic error waiting for the pending transfers.
- // Kill all of the threads and leave the loop.
- // Note: This approach will potentially leak resources allocated by
- // the plug-in, but it prevents access to stale data by the threads
- // once the plug-in has been unloaded.
- for (StreamOpArray::size_type x = 0;
- x < active_stream_ops_.size(); ++x) {
- BOOL thread_kill = TerminateThread(stream_handles[x], 0);
- ATLASSERT(thread_kill && "Failure killing stalled download thread.");
- }
- break;
- }
- }
-
- if (plugin_module_) {
- scriptable_object_ = NULL;
- plugin_funcs_.destroy(GetNPP(), NULL);
- }
-
- initialized_ = false;
-}
-
-void NPPluginProxy::RegisterStreamOperation(StreamOperation* stream_op) {
-#ifndef NDEBUG
- StreamOpArray::iterator iter = std::find(active_stream_ops_.begin(),
- active_stream_ops_.end(),
- stream_op);
- ATLASSERT(iter == active_stream_ops_.end() &&
- "Duplicate registration of a StreamOperation.");
-#endif
- active_stream_ops_.push_back(stream_op);
-}
-
-void NPPluginProxy::UnregisterStreamOperation(StreamOperation* stream_op) {
- StreamOpArray::iterator iter = std::find(active_stream_ops_.begin(),
- active_stream_ops_.end(),
- stream_op);
- ATLASSERT(iter != active_stream_ops_.end() &&
- "Unregistration of an unrecognized StreamOperation.");
- active_stream_ops_.erase(iter);
-}
-
-HRESULT NPPluginProxy::GetScriptableObject(
- INPObjectProxy** scriptable_object) const {
- ATLASSERT(scriptable_object);
-
- if (!scriptable_object_) {
- return E_FAIL;
- }
-
- *scriptable_object = scriptable_object_;
- (*scriptable_object)->AddRef();
- return S_OK;
-}
-
-HRESULT NPPluginProxy::Create(NPPluginProxy** proxy_instance) {
- ATLASSERT(proxy_instance);
- // Lock the module so that there are no races against the NP_Initialize
- // and NP_Shutdown calls. NP_Initialize and NP_Shutdown parallel the
- // behaviour of DLL_PROCESS_ATTACH and DLL_PROCESS_DETACH.
- // We serialize all construction and destruction to ensure that any
- // plug-in initialization mimics this behaviour.
- AutoModuleLock lock;
-
- // First attempt to load the plug-in from the directory specified by the
- // MOZ_PLUGIN_PATH directory.
- HMODULE np_plugin = NULL;
- const wchar_t *plugin_path = GetMozillaPluginPath();
- if (plugin_path) {
- np_plugin = LoadLibrary(plugin_path);
- }
-
- if (!np_plugin) {
- // Attempt to load the plug-in from the installation directory.
- plugin_path = GetApplicationDataPluginPath();
- if (plugin_path) {
- np_plugin = LoadLibrary(plugin_path);
- }
-
- if (!np_plugin) {
- plugin_path = GetProgramFilesPluginPath();
- if (plugin_path) {
- np_plugin = LoadLibrary(plugin_path);
- }
-
- if (!np_plugin) {
- // As a last-ditch attempt, try to load the plug-in using the system
- // library path.
- np_plugin = LoadLibrary(kPluginName);
- if (!np_plugin) {
- ATLASSERT(false && "Unable to load plugin module.");
- return E_FAIL;
- }
- }
- }
- }
-
- // Load and initialize the plug-in with the current window settings.
- scoped_ptr<NPPluginProxy> plugin_proxy(new NPPluginProxy);
- if (!plugin_proxy->MapEntryPoints(np_plugin)) {
- FreeLibrary(np_plugin);
- return E_FAIL;
- }
-
- *proxy_instance = plugin_proxy.release();
- return S_OK;
-}
diff --git a/o3d/plugin/npapi_host_control/win/np_plugin_proxy.h b/o3d/plugin/npapi_host_control/win/np_plugin_proxy.h
deleted file mode 100644
index 58509db..0000000
--- a/o3d/plugin/npapi_host_control/win/np_plugin_proxy.h
+++ /dev/null
@@ -1,161 +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.
- */
-
-
-// File declaring a class wrapping the raw npapi interface as exported from
-// a Mozilla plug-in.
-
-#ifndef O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_NP_PLUGIN_PROXY_H_
-#define O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_NP_PLUGIN_PROXY_H_
-
-#include <vector>
-#include "third_party/npapi/include/npfunctions.h"
-
-class NPBrowserProxy;
-struct INPObjectProxy;
-class StreamOperation;
-
-typedef NPError (__stdcall *NP_InitializeFunc)(NPNetscapeFuncs* functions);
-typedef NPError (__stdcall *NP_GetEntryPointsFunc)(NPPluginFuncs* functions);
-typedef NPError (__stdcall *NP_ShutdownFunc)();
-
-class NPPluginProxy {
- public:
- ~NPPluginProxy();
-
- // Initializes and binds this instance to the npapi plugin exported by
- // the given module. Note that the object takes control of the lifetime of
- // module, and will unload it at instance destruction time.
- // Parameters:
- // browser_proxy: Browser environment in which the plug-in will reside.
- // window: NPWindow structure initialized for the plug-in.
- // argument_names: Array of string-argument names to be passed to the
- // construction routine NPP_New.
- // argument_values: Array of string-argument values to be passed to the
- // construction routine NPP_New.
- // Returns:
- // true if the plugin successfully loaded and initialized in the provided
- // window.
- bool Init(NPBrowserProxy* browser_proxy,
- const NPWindow& window,
- const std::vector<CStringA>& argument_names,
- const std::vector<CStringA>& argument_values);
-
- // Sets the target window of the npapi plugin. This may be called
- // repeatedly during its lifetime, in particular to set the plugin's
- // size.
- bool SetWindow(const NPWindow& window);
-
- // Frees all resources allocated in Init, and blocks on all pending stream
- // operations.
- void TearDown();
-
- // Get the 'v-table' interface for the hosted plugin member functions.
- const NPPluginFuncs* GetPluginFunctions() const {
- return &plugin_funcs_;
- }
-
- // Get the plugin data associated with this instance.
- NPP_t* GetNPP() {
- return &npp_data_;
- }
-
- // Return the NPAPI object containing the scripting entry points for the
- // plugin.
- HRESULT GetScriptableObject(INPObjectProxy** scriptable_object) const;
-
- // Return a pointer to the NPAPI browser environment hosting the plugin.
- NPBrowserProxy* browser_proxy() const {
- return browser_proxy_;
- }
-
- // Registers stream_op with the list of active stream operations.
- void RegisterStreamOperation(StreamOperation* stream_op);
-
- // Removes stream_op from the set of active stream operations.
- void UnregisterStreamOperation(StreamOperation* stream_op);
-
- static HRESULT Create(NPPluginProxy** instance);
-
- private:
- // Basic constructor that does not perform any plugin-specific operations.
- // Simply prepares the structure for initialization.
- NPPluginProxy();
-
- // Stores pointers to the NPAPI entry points present in the passed in module.
- // This routine also performs one-time initialization of the plug-in,
- // but does not create a live instance.
- // loaded_module: Handle to a loaded module containing exports for a npapi
- // plugin.
- // Returns:
- // true if the NPAPI plugin entry points were present in the module.
- bool MapEntryPoints(HMODULE loaded_module);
-
- // Pointer to the npapi browser environment in which the plugin lives.
- // A smart pointer is not used, as this is a back-pointer.
- NPBrowserProxy* browser_proxy_;
-
- // Cached scritable object for interacting with the plugin.
- CComPtr<INPObjectProxy> scriptable_object_;
-
- // Cache of plugin instance member functions.
- NPPluginFuncs plugin_funcs_;
-
- // Pointers to the three main entry points of the plug-in.
- NP_InitializeFunc NP_Initialize_;
- NP_GetEntryPointsFunc NP_GetEntryPoints_;
- NP_ShutdownFunc NP_Shutdown_;
-
- // The handle to the loaded plugin module. The plugin unloads this module
- // upon destruction.
- HMODULE plugin_module_;
-
- // Plugin instance data passed to all plugin-calls.
- NPP_t npp_data_;
-
- typedef std::vector<StreamOperation*> StreamOpArray;
-
- // The set of currently pending/downloading streaming operations spawned
- // by the plugin.
- StreamOpArray active_stream_ops_;
-
- // Whether this plugin instance is in an initialized state.
- bool initialized_;
-
- // Global count of the number of currently live plugin instances. Used
- // to ensure that NP_Initialize and NP_Shutdown are called only once
- // per loading of the plugin module.
- static int kPluginInstanceCount;
-
- DISALLOW_COPY_AND_ASSIGN(NPPluginProxy);
-};
-
-#endif // O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_NP_PLUGIN_PROXY_H_
diff --git a/o3d/plugin/npapi_host_control/win/npapi_host_control.cc b/o3d/plugin/npapi_host_control/win/npapi_host_control.cc
deleted file mode 100644
index 4d1223e..0000000
--- a/o3d/plugin/npapi_host_control/win/npapi_host_control.cc
+++ /dev/null
@@ -1,73 +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.
- */
-
-
-// File implements the ActiveX entry points and module class for the
-// NPAPI ActiveX host control
-
-#include "plugin/npapi_host_control/win/module.h"
-#include "plugin/npapi_host_control/win/resource.h"
-
-namespace {
-NPAPIHostControlModule atl_module;
-} // unnamed namespace
-
-extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason,
- LPVOID lpReserved) {
- return atl_module.DllMain(dwReason, lpReserved);
-}
-
-
-// Used to determine whether the DLL can be unloaded by OLE.
-STDAPI DllCanUnloadNow(void) {
- return atl_module.DllCanUnloadNow();
-}
-
-
-// Returns a class factory to create an object of the requested type
-STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) {
- return atl_module.DllGetClassObject(rclsid, riid, ppv);
-}
-
-
-// Adds entries to the system registry.
-STDAPI DllRegisterServer(void) {
- // Registers object, typelib and all interfaces in typelib
- HRESULT hr = atl_module.DllRegisterServer();
- return hr;
-}
-
-
-// DllUnregisterServer - Removes entries from the system registry
-STDAPI DllUnregisterServer(void) {
- HRESULT hr = atl_module.DllUnregisterServer();
- return hr;
-}
diff --git a/o3d/plugin/npapi_host_control/win/npapi_host_control.def b/o3d/plugin/npapi_host_control/win/npapi_host_control.def
deleted file mode 100644
index fe80c77..0000000
--- a/o3d/plugin/npapi_host_control/win/npapi_host_control.def
+++ /dev/null
@@ -1,9 +0,0 @@
-; npapi_host_control.def : Declares the module parameters.
-
-LIBRARY "o3d_host.DLL"
-
-EXPORTS
- DllCanUnloadNow PRIVATE
- DllGetClassObject PRIVATE
- DllRegisterServer PRIVATE
- DllUnregisterServer PRIVATE
diff --git a/o3d/plugin/npapi_host_control/win/npapi_host_control.idl_template b/o3d/plugin/npapi_host_control/win/npapi_host_control.idl_template
deleted file mode 100644
index 207c15a..0000000
--- a/o3d/plugin/npapi_host_control/win/npapi_host_control.idl_template
+++ /dev/null
@@ -1,92 +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.
- */
-
-// npapi_host2.idl : IDL source for npapi_host2
-//
-
-// This file will be processed by the MIDL tool to
-// produce the type library (npapi_host2.tlb) and marshalling code.
-
-#include "olectl.h"
-import "dispex.idl";
-import "oaidl.idl";
-import "ocidl.idl";
-
-[
- object,
- uuid(56D79537-181C-4A38-ADF5-E12EC24D7FC7),
- dual,
- nonextensible,
- helpstring("IHostControl Interface"),
- pointer_default(unique)
-]
-interface IHostControl : IDispatchEx {
- // Note the assignement of the ids here: These values will not conflict
- // with the auto-generated ids for the hosted NPAPI plugin object.
- [propget, helpstring("The description of the installed plugin."), id(1)]
- HRESULT description([out, retval] BSTR* returned_description);
- [propget, helpstring("The name of the installed plugin."), id(2)]
- HRESULT name([out, retval] BSTR* returned_name);
-};
-
-[
- object,
- uuid(89681DED-6CE8-407f-989C-C4FEDE5330A8),
- pointer_default(unique)
-]
-interface INPObjectProxy : IDispatchEx {
- // The following set of routines are not remoteable, as they all reference
- // a void pointer, which is relevant to the in-proc instance of classes
- // implementing this interface.
- [local] HRESULT GetNPObjectInstance([out] void ** instance);
- [local] HRESULT SetBrowserProxy([in] void* browser_proxy);
- [local] HRESULT SetHostedObject([in] void* hosted_object);
- [local] HRESULT ReleaseHosted();
-};
-
-[
- uuid(@@@PluginActiveXTypeLibClsid@@@),
- version(1.0),
- helpstring("npapi_host2 1.0 Type Library")
-]
-library npapi_host_controlLib
-{
- importlib("stdole2.tlb");
- [
- uuid(@@@PluginActiveXHostControlClsid@@@),
- //control,
- helpstring("HostControl Class")
- ]
- coclass HostControl
- {
- [default] interface IHostControl;
- };
-};
diff --git a/o3d/plugin/npapi_host_control/win/npapi_host_control.rc b/o3d/plugin/npapi_host_control/win/npapi_host_control.rc
deleted file mode 100644
index 374baab..0000000
--- a/o3d/plugin/npapi_host_control/win/npapi_host_control.rc
+++ /dev/null
@@ -1,121 +0,0 @@
-// Microsoft Visual C++ generated resource script.
-//
-#include "resource.h"
-
-#define APSTUDIO_READONLY_SYMBOLS
-/////////////////////////////////////////////////////////////////////////////
-//
-// Generated from the TEXTINCLUDE 2 resource.
-//
-#include "winres.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 ""winres.h""\r\n"
- "\0"
-END
-
-3 TEXTINCLUDE
-BEGIN
- "1 TYPELIB ""npapi_host_control.tlb""\r\n"
- "\0"
-END
-
-#endif // APSTUDIO_INVOKED
-
-
-/////////////////////////////////////////////////////////////////////////////
-//
-// Version
-//
-
-VS_VERSION_INFO VERSIONINFO
- FILEVERSION 1,0,0,1
- PRODUCTVERSION 1,0,0,1
- FILEFLAGSMASK 0x3fL
-#ifdef _DEBUG
- FILEFLAGS 0x1L
-#else
- FILEFLAGS 0x0L
-#endif
- FILEOS 0x4L
- FILETYPE 0x2L
- FILESUBTYPE 0x0L
-BEGIN
- BLOCK "StringFileInfo"
- BEGIN
- BLOCK "040904e4"
- BEGIN
- VALUE "CompanyName", "Google Inc."
- VALUE "FileDescription", O3D_PLUGIN_DESCRIPTION
- VALUE "FileVersion", "1.0.0.0"
- VALUE "LegalCopyright", "Copyright 2009 Google Inc. All Rights Reserved."
- VALUE "InternalName", "o3d_host.dll"
- VALUE "OriginalFilename", "o3d_host.dll"
- VALUE "ProductName", O3D_PLUGIN_NAME
- VALUE "ProductVersion", O3D_PLUGIN_VERSION
- END
- END
- BLOCK "VarFileInfo"
- BEGIN
- VALUE "Translation", 0x409, 1252
- END
-END
-
-
-/////////////////////////////////////////////////////////////////////////////
-//
-// REGISTRY
-//
-
-IDR_NPAPI_HOST_CONTROL REGISTRY "npapi_host_control.rgs"
-IDR_HOSTCONTROL REGISTRY "host_control.rgs"
-
-/////////////////////////////////////////////////////////////////////////////
-//
-// String Table
-//
-
-STRINGTABLE
-BEGIN
- IDS_PROJNAME "npapi_host_control"
-END
-
-#endif // English (U.S.) resources
-/////////////////////////////////////////////////////////////////////////////
-
-
-
-#ifndef APSTUDIO_INVOKED
-/////////////////////////////////////////////////////////////////////////////
-//
-// Generated from the TEXTINCLUDE 3 resource.
-//
-1 TYPELIB "npapi_host_control.tlb"
-
-/////////////////////////////////////////////////////////////////////////////
-#endif // not APSTUDIO_INVOKED
-
diff --git a/o3d/plugin/npapi_host_control/win/npapi_host_control.rgs b/o3d/plugin/npapi_host_control/win/npapi_host_control.rgs
deleted file mode 100644
index 1db1fc5..0000000
--- a/o3d/plugin/npapi_host_control/win/npapi_host_control.rgs
+++ /dev/null
@@ -1,17 +0,0 @@
-HKCU
-{
- Software
- {
- Classes
- {
- NoRemove AppID
- {
- '%APPID%' = s 'o3d_host'
- 'o3d_host.DLL'
- {
- val AppID = s '%APPID%'
- }
- }
- }
- }
-}
diff --git a/o3d/plugin/npapi_host_control/win/precompile.cc b/o3d/plugin/npapi_host_control/win/precompile.cc
deleted file mode 100644
index 832211b..0000000
--- a/o3d/plugin/npapi_host_control/win/precompile.cc
+++ /dev/null
@@ -1,33 +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 "plugin/npapi_host_control/win/precompile.h"
diff --git a/o3d/plugin/npapi_host_control/win/precompile.h b/o3d/plugin/npapi_host_control/win/precompile.h
deleted file mode 100644
index ef3d0b0..0000000
--- a/o3d/plugin/npapi_host_control/win/precompile.h
+++ /dev/null
@@ -1,83 +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.
- */
-
-
-// Precompiled header generated by Visual Studio 2008.
-
-#ifndef O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_PRECOMPILE_H_
-#define O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_PRECOMPILE_H_
-
-#ifndef STRICT
-#define STRICT
-#endif
-
-// Modify the following defines if you have to target a platform prior to the
-// ones specified below.
-// Refer to MSDN for the latest info on corresponding values for
-// different platforms.
-#ifndef WINVER // Allow use of features specific to Windows XP or later.
-#define WINVER 0x0501 // Change this to the appropriate value to target
- // other versions of Windows.
-#endif
-
-#ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later.
-#define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target
- // other versions of Windows.
-#endif
-
-#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or
- // later.
-#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to
- // target Windows Me or later.
-#endif
-
-#ifndef _WIN32_IE // Allow use of features specific to IE 6.0 or later.
-#define _WIN32_IE 0x0600 // Change this to the appropriate value to target
- // other versions of IE.
-#endif
-
-#define _ATL_APARTMENT_THREADED
-#define _ATL_NO_AUTOMATIC_NAMESPACE
-
-// Some CString constructors will be explicit.
-#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS
-
-
-#include <atlbase.h>
-#include <atlcom.h>
-#include <atlstr.h>
-
-#include "base/basictypes.h"
-#include "plugin/npapi_host_control/win/resource.h"
-
-using namespace ATL;
-
-#endif // O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_PRECOMPILE_H_
diff --git a/o3d/plugin/npapi_host_control/win/resource.h b/o3d/plugin/npapi_host_control/win/resource.h
deleted file mode 100644
index 4ca98ac..0000000
--- a/o3d/plugin/npapi_host_control/win/resource.h
+++ /dev/null
@@ -1,54 +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_PLUGIN_NPAPI_HOST_CONTROL_WIN_RESOURCE_H_
-#define O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_RESOURCE_H_
-
-// Microsoft Visual C++ generated include file. Used by npapi_host2.rc
-#define IDS_PROJNAME 100
-#define IDR_NPAPI_HOST_CONTROL 101
-#define IDB_HOSTCONTROL 102
-#define IDR_HOSTCONTROL 103
-
-
-
-// Next default values for new objects.
-#ifdef APSTUDIO_INVOKED
-#ifndef APSTUDIO_READONLY_SYMBOLS
-#define _APS_NEXT_RESOURCE_VALUE 201
-#define _APS_NEXT_COMMAND_VALUE 32768
-#define _APS_NEXT_CONTROL_VALUE 201
-#define _APS_NEXT_SYMED_VALUE 106
-#endif
-#endif
-
-#endif // O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_RESOURCE_H_
diff --git a/o3d/plugin/npapi_host_control/win/stream_operation.cc b/o3d/plugin/npapi_host_control/win/stream_operation.cc
deleted file mode 100644
index b18c3c9..0000000
--- a/o3d/plugin/npapi_host_control/win/stream_operation.cc
+++ /dev/null
@@ -1,773 +0,0 @@
-// Copyright 2009, Google Inc. All rights reserved.
-// Portions of this file were adapted from the Mozilla project.
-// See https://developer.mozilla.org/en/ActiveX_Control_for_Hosting_Netscape_Plug-ins_in_IE
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1994-2000
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- * Adam Lock <adamlock@eircom.net>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#include <wininet.h>
-
-#include "plugin/npapi_host_control/win/stream_operation.h"
-#include "plugin/npapi_host_control/win/host_control.h"
-#include "plugin/npapi_host_control/win/np_plugin_proxy.h"
-
-namespace {
-
-// The following classes are used to package arguments for interacting with
-// the hosted NPAPI plug-in.
-struct NPPDestroyStreamArgs {
- NPP npp_;
- NPStream *stream_;
- NPReason reason_;
- NPError *return_code_;
-};
-
-struct NPPNewStreamArgs {
- NPP npp_;
- NPMIMEType type_;
- NPStream *stream_;
- NPBool seekable_;
- uint16 *stype_;
- NPError *return_code_;
-};
-
-struct NPPAsFileArgs {
- NPP npp_;
- NPStream *stream_;
- const char* fname_;
-};
-
-struct NPPUrlNotifyArgs {
- NPP npp_;
- const char* url_;
- NPReason reason_;
- void *notify_data_;
-};
-
-struct NPPWriteReadyArgs {
- NPP npp_;
- NPStream *stream_;
- int32 *return_value_;
-};
-
-struct NPPWriteArgs {
- NPP npp_;
- NPStream *stream_;
- int32 offset_;
- int32 len_;
- void* buffer_;
- int32 *return_value_;
-};
-
-// Helper function that constructs the full url from a moniker associated with
-// a base 'left-side' url prefix, and a stream operation.
-HRESULT ConstructFullURLPath(const StreamOperation& stream_operation,
- IMoniker* base_moniker,
- CString* out_string) {
- ATLASSERT(base_moniker && out_string);
-
- HRESULT hr = S_OK;
- CComPtr<IMoniker> full_url_moniker;
- if (FAILED(hr = CreateURLMonikerEx(base_moniker,
- stream_operation.GetURL(),
- &full_url_moniker,
- URL_MK_UNIFORM))) {
- return hr;
- }
-
- // Determine if the monikers share a common prefix. If they do, then
- // we can allow the data fetch to proceed - The same origin criteria has been
- // satisfied.
- CComPtr<IMoniker> prefix_moniker;
- bool urls_contain_prefix = false;
- hr = MonikerCommonPrefixWith(base_moniker, full_url_moniker, &prefix_moniker);
- if (SUCCEEDED(hr)) {
- urls_contain_prefix = true;
- }
-
- CComPtr<IBindCtx> bind_context;
- if (FAILED(hr = CreateBindCtx(0, &bind_context))) {
- return hr;
- }
-
- CComPtr<IMalloc> malloc_interface;
- if (FAILED(hr = CoGetMalloc(1, &malloc_interface))) {
- return hr;
- }
-
- LPOLESTR full_url_path = NULL;
- if (FAILED(hr = full_url_moniker->GetDisplayName(bind_context,
- NULL,
- &full_url_path))) {
- return hr;
- }
-
- if (!urls_contain_prefix) {
- // If the urls do not contain a common prefix, validate the access request
- // based on the fully qualified uri's.
- LPOLESTR base_path_name = NULL;
- if (FAILED(hr = base_moniker->GetDisplayName(bind_context,
- NULL,
- &base_path_name))) {
- malloc_interface->Free(full_url_path);
- return hr;
- }
- }
-
- *out_string = full_url_path;
- malloc_interface->Free(full_url_path);
-
- return S_OK;
-}
-
-// Helper routine implementing a custom version of SendMessage(...).
-// The StreamingOperation class uses windows messages to communicate transfer
-// notifications to the plug-in. This is required so that the plug-in will
-// receive notifications synchronously on the main-browser thread.
-// SendMessage is not appropriate, because messages 'sent' to a window are NOT
-// processed during DispatchMessage, but instead during GetMessage, PeekMessage
-// and others. Because the JScript engine periodically peeks the message
-// queue during JavaScript evaluation, the plug-in would be notified, and
-// potentially call back into the JavaScript environment causing unexpected
-// reentrancy.
-HRESULT CustomSendMessage(HWND window_handle, UINT message, LPARAM l_param) {
- // Mimic the behaviour of SendMessage by posting to the window, and then
- // blocking on an event. Note that the message handlers must set
- // the event.
- HANDLE local_event = CreateEvent(NULL, TRUE, FALSE, NULL);
- if (!local_event) {
- return E_FAIL;
- }
-
- if (!PostMessage(window_handle, message,
- reinterpret_cast<WPARAM>(&local_event), l_param)) {
- CloseHandle(local_event);
- return E_FAIL;
- }
-
- HRESULT hr;
- static const unsigned int kWaitTimeOut = 120000;
- bool done = false;
- while (!done) {
- DWORD wait_code = MsgWaitForMultipleObjects(1,
- &local_event,
- FALSE,
- kWaitTimeOut,
- QS_ALLINPUT);
- switch (wait_code) {
- case WAIT_OBJECT_0:
- hr = S_OK;
- done = true;
- break;
- case WAIT_OBJECT_0 + 1:
- MSG msg;
- GetMessage(&msg, NULL, 0, 0);
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- break;
- case WAIT_TIMEOUT:
- // If the plug-in is busy processing JavaScript code, it's possible
- // that we may time-out here. We don't break out of the loop, because
- // the event will eventually be signaled when the JS is done
- // processing.
- ATLASSERT(false && "Time out waiting for response from main thread.");
- break;
- default:
- ATLASSERT(false &&
- "Critical failure waiting for response from main thread.");
- hr = E_FAIL;
- done = true;
- break;
- }
- }
-
- CloseHandle(local_event);
- return hr;
-}
-
-} // unnamed namespace
-
-StreamOperation::StreamOperation()
- : stream_size_(0),
- stream_received_(0),
- stream_type_(NP_NORMAL),
- temp_file_(NULL),
- thread_handle_(NULL),
- cancel_requested_(false) {
- memset(&np_stream_, 0, sizeof(np_stream_));
-}
-
-StreamOperation::~StreamOperation() {
-}
-
-void StreamOperation::OnFinalMessage(HWND hWnd) {
- CWindowImplBase::OnFinalMessage(hWnd);
- if (owner_) {
- owner_->UnregisterStreamOperation(this);
- }
-
- // The binding holds a reference to the stream operation, which forms
- // a cyclic reference chain. Release the binding so that both objects
- // can be destroyed.
- binding_ = NULL;
-
- // The object has an artificially boosted reference count to ensure that it
- // stays alive as long as it may receive window messages. Release this
- // reference here, and potentially free the instance.
- Release();
-}
-
-HRESULT STDMETHODCALLTYPE StreamOperation::OnStartBinding(DWORD dwReserved,
- IBinding *pib) {
- binding_ = pib;
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE StreamOperation::GetPriority(LONG *pnPriority) {
- return E_NOTIMPL;
-}
-
-HRESULT STDMETHODCALLTYPE StreamOperation::OnLowResource(DWORD reserved) {
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE StreamOperation::OnProgress(ULONG ulProgress,
- ULONG ulProgressMax,
- ULONG ulStatusCode,
- LPCWSTR szStatusText) {
- if (cancel_requested_) {
- binding_->Abort();
- return S_OK;
- }
-
- // Capture URL re-directs and MIME-type status notifications.
- switch (ulStatusCode) {
- case BINDSTATUS_BEGINDOWNLOADDATA:
- case BINDSTATUS_REDIRECTING:
- url_ = szStatusText;
- break;
- case BINDSTATUS_MIMETYPEAVAILABLE:
- content_type_ = szStatusText;
- break;
- default:
- break;
- }
-
- // Track the current progress of the streaming transfer.
- stream_size_ = ulProgressMax;
- stream_received_ = ulProgress;
-
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE StreamOperation::OnStopBinding(HRESULT hresult,
- LPCWSTR szError) {
- NPReason reason = SUCCEEDED(hresult) ? NPRES_DONE : NPRES_NETWORK_ERR;
- USES_CONVERSION;
-
- // Notify the calling plug-in that the transfer has completed.
- if (stream_type_ == NP_ASFILE || stream_type_ == NP_ASFILEONLY) {
- if (temp_file_) {
- fclose(temp_file_);
- }
-
- if (reason == NPRES_DONE) {
- NPPAsFileArgs arguments = {
- owner_->GetNPP(),
- GetNPStream(),
- W2A(temp_file_name_)
- };
- CustomSendMessage(m_hWnd, WM_NPP_ASFILE,
- reinterpret_cast<LPARAM>(&arguments));
- }
- }
-
- if (reason == NPRES_DONE) {
- NPError error_return;
- NPPDestroyStreamArgs destroy_stream_args = {
- owner_->GetNPP(),
- GetNPStream(),
- reason,
- &error_return
- };
- CustomSendMessage(m_hWnd, WM_NPP_DESTROYSTREAM,
- reinterpret_cast<LPARAM>(&destroy_stream_args));
- ATLASSERT(NPERR_NO_ERROR == error_return);
- }
-
- NPPUrlNotifyArgs url_args = {
- owner_->GetNPP(),
- W2A(url_),
- reason,
- GetNotifyData()
- };
- CustomSendMessage(m_hWnd, WM_NPP_URLNOTIFY,
- reinterpret_cast<LPARAM>(&url_args));
-
- // Clear the intermediate file from the cache.
- _wremove(temp_file_name_);
- temp_file_name_ = L"";
-
- // The operation has completed, so tear-down the intermediate window, and
- // exit the worker thread.
- CustomSendMessage(m_hWnd, WM_TEAR_DOWN, 0);
- PostQuitMessage(0);
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE StreamOperation::GetBindInfo(DWORD *grfBINDF,
- BINDINFO *pbindinfo) {
- // Request an asynchronous transfer of the data.
- *grfBINDF = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE |
- BINDF_GETNEWESTVERSION;
-
- int cbSize = pbindinfo->cbSize;
- memset(pbindinfo, 0, cbSize);
- pbindinfo->cbSize = cbSize;
- pbindinfo->dwBindVerb = BINDVERB_GET;
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE StreamOperation::OnDataAvailable(
- DWORD grfBSCF,
- DWORD dwSize,
- FORMATETC *pformatetc,
- STGMEDIUM *pstgmed) {
- if (pstgmed->tymed != TYMED_ISTREAM || !pstgmed->pstm) {
- return S_OK;
- }
-
- // Don't bother processing any data if the stream has been canceled.
- if (cancel_requested_) {
- binding_->Abort();
- return S_OK;
- }
-
- // Notify the plugin that a new stream has been opened.
- if (grfBSCF & BSCF_FIRSTDATANOTIFICATION) {
- USES_CONVERSION;
- np_stream_.url = W2CA(url_);
- np_stream_.end = stream_size_;
- np_stream_.lastmodified = 0;
- np_stream_.notifyData = GetNotifyData();
-
- uint16 stream_type = NP_NORMAL;
-
- NPError np_error;
- NPPNewStreamArgs new_stream_args = {
- owner_->GetNPP(),
- const_cast<char*>(W2CA(GetContentType())),
- GetNPStream(),
- FALSE,
- &stream_type,
- &np_error
- };
- CustomSendMessage(m_hWnd, WM_NPP_NEWSTREAM,
- reinterpret_cast<LPARAM>(&new_stream_args));
- if (np_error != NPERR_NO_ERROR) {
- return E_FAIL;
- }
-
- // Cache the stream type requested by the plug-in.
- stream_type_ = stream_type;
- }
-
- if (grfBSCF & BSCF_INTERMEDIATEDATANOTIFICATION ||
- grfBSCF & BSCF_LASTDATANOTIFICATION) {
- // Read all of the available data, and pass it to the plug-in, if requested.
- HRESULT hr;
- char local_data[16384];
- DWORD bytes_received_total = 0;
- // If a large number of bytes have been received, then this loop can
- // take a long time to complete - which will block the user from leaving
- // the page as the plug-in waits for all transfers to complete. We
- // add a check on cancel_requested_ to allow for early bail-out.
- while (bytes_received_total < dwSize &&
- !cancel_requested_) {
- int bytes_to_read = dwSize - bytes_received_total;
- unsigned long bytes_read = 0;
-
- if (bytes_to_read > sizeof(local_data)) {
- bytes_to_read = sizeof(local_data);
- }
-
- if (stream_type_ == NP_NORMAL || stream_type_ == NP_ASFILE) {
- int32 bytes_to_accept;
- NPPWriteReadyArgs write_ready_args = {
- owner_->GetNPP(),
- GetNPStream(),
- &bytes_to_accept
- };
- CustomSendMessage(m_hWnd, WM_NPP_WRITEREADY,
- reinterpret_cast<LPARAM>(&write_ready_args));
-
- if (bytes_to_read > bytes_to_accept) {
- bytes_to_read = bytes_to_accept;
- }
- }
-
- // If the plug-in has indicated that it is not prepared to read any data,
- // then bail early.
- if (bytes_to_read == 0) {
- break;
- }
-
- hr = pstgmed->pstm->Read(local_data, bytes_to_read, &bytes_read);
- if (FAILED(hr) || S_FALSE == hr) {
- break;
- }
-
- // Pass the data to the plug-in.
- if (stream_type_ == NP_NORMAL || stream_type_ == NP_ASFILE) {
- int consumed_bytes;
- NPPWriteArgs write_args = {
- owner_->GetNPP(),
- GetNPStream(),
- bytes_received_total,
- bytes_read,
- local_data,
- &consumed_bytes
- };
- CustomSendMessage(m_hWnd, WM_NPP_WRITE,
- reinterpret_cast<LPARAM>(&write_args));
- ATLASSERT(consumed_bytes == bytes_read);
- }
-
- if (stream_type_ == NP_ASFILE || stream_type_ == NP_ASFILEONLY) {
- // If the plug-in requested access to the data through a file, then
- // create a temporary file and write the data to it.
- if (!temp_file_) {
- temp_file_name_= _wtempnam(NULL, L"npapi_host_temp");
- _wfopen_s(&temp_file_, temp_file_name_, L"wb");
- }
- fwrite(local_data, bytes_read, 1, temp_file_);
- }
- bytes_received_total += bytes_read;
- }
- }
- return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE StreamOperation::OnObjectAvailable(REFIID riid,
- IUnknown *punk) {
- return S_OK;
-}
-
-HRESULT StreamOperation::OpenURL(NPPluginProxy *owning_plugin,
- const wchar_t *url,
- void *notify_data) {
- HRESULT hr;
-
- // The StreamOperation instance is created with a ref-count of zero,
- // so we explicitly attach a CComPtr to the object to boost the count, and
- // manage the lifetime of the object.
- CComObject<StreamOperation> *stream_ptr;
- CComObject<StreamOperation>::CreateInstance(&stream_ptr);
- CComPtr<CComObject<StreamOperation> > stream_object = stream_ptr;
- if (!stream_object) {
- return E_OUTOFMEMORY;
- }
-
- CComPtr<CHostControl> host_control =
- owning_plugin->browser_proxy()->GetHostingControl();
- CComPtr<IMoniker> base_url_moniker = host_control->GetURLMoniker();
-
- stream_object->SetURL(url);
- stream_object->SetNotifyData(notify_data);
- stream_object->SetOwner(owning_plugin);
-
- CString full_path;
- if (FAILED(hr = ConstructFullURLPath(*stream_object,
- base_url_moniker,
- &full_path))) {
- return hr;
- }
-
- stream_object->SetFullURL(full_path);
-
- // Validate the URL. If the URL is invalid there is no need to create a new
- // thread only to have it immediately fail.
- URL_COMPONENTS components = { sizeof(URL_COMPONENTS) };
- if (!InternetCrackUrl(full_path, 0, 0, &components))
- return E_INVALIDARG;
- if (components.nScheme != INTERNET_SCHEME_FILE &&
- components.nScheme != INTERNET_SCHEME_FTP &&
- components.nScheme != INTERNET_SCHEME_HTTP &&
- components.nScheme != INTERNET_SCHEME_HTTPS) {
- return E_INVALIDARG;
- }
-
- // Create an object window on this thread that will be sent messages when
- // something happens on the worker thread.
- HWND temporary_window = stream_object->Create(HWND_DESKTOP);
- ATLASSERT(temporary_window);
- if (!temporary_window) {
- return E_FAIL;
- }
-
- // Artificially increment the reference count of the stream_object instance
- // to ensure that the object will not be deleted until WM_NC_DESTROY is
- // processed and OnFinalMessage is invoked.
- // Note: The operator-> is not used, because it returns a type overloading
- // the public access of AddRef/Release.
- (*stream_object).AddRef();
-
- stream_object->thread_handle_ = reinterpret_cast<HANDLE>(
- _beginthreadex(NULL,
- 0,
- WorkerProc,
- static_cast<void*>(stream_object),
- CREATE_SUSPENDED,
- NULL));
- ATLASSERT(stream_object->thread_handle_);
- if (!stream_object->thread_handle_) {
- stream_object->DestroyWindow();
- return E_FAIL;
- }
-
- owning_plugin->RegisterStreamOperation(stream_object);
- if (!ResumeThread(stream_object->thread_handle_)) {
- owning_plugin->UnregisterStreamOperation(stream_object);
- stream_object->DestroyWindow();
- // If the thread never resumed, then we can safely terminate it here - it
- // has not had a chance to allocate any resources that would be leaked.
- TerminateThread(stream_object->thread_handle_, 0);
- return E_FAIL;
- }
-
- return S_OK;
-}
-
-unsigned int __stdcall StreamOperation::WorkerProc(void* worker_arguments) {
- CComObject<StreamOperation> *stream_object =
- static_cast<CComObject<StreamOperation> *>(worker_arguments);
- ATLASSERT(stream_object);
-
- // Initialize the COM run-time for this new thread.
- HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
- ATLASSERT(SUCCEEDED(hr) && "Failure to initialize worker COM apartment.");
- if (FAILED(hr)) {
- CustomSendMessage(stream_object->m_hWnd, WM_TEAR_DOWN, 0);
- CoUninitialize();
- return 0;
- }
-
- {
- // Get the ActiveX control so the request is within the context of the
- // plugin. Among other things, this lets the browser reject file:// uris
- // when the page is loaded over http://.
- CComPtr<IUnknown> caller;
- stream_object->owner_->browser_proxy()->GetHostingControl()->QueryInterface(
- IID_IUnknown,
- reinterpret_cast<void**>(&caller));
-
- // Note that the OnStopBinding(...) routine, which is always called, will
- // post WM_QUIT to this thread.
- hr = URLOpenStream(caller, stream_object->GetFullURL(), 0,
- static_cast<IBindStatusCallback*>(stream_object));
-
- // Pump messages until WM_QUIT arrives
- MSG msg;
- while (GetMessage(&msg, NULL, 0, 0)) {
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- }
- }
-
- CoUninitialize();
- return 0;
-}
-
-LRESULT StreamOperation::OnNPPNewStream(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL& bHandled) {
- NPPNewStreamArgs *args = reinterpret_cast<NPPNewStreamArgs*>(lParam);
- ATLASSERT(args);
-
- // If the stream was canceled, don't pass the notification to the plug-in.
- if (!cancel_requested_) {
- *args->return_code_ = owner_->GetPluginFunctions()->newstream(
- args->npp_,
- args->type_,
- args->stream_,
- args->seekable_,
- args->stype_);
- } else {
- *args->return_code_ = NPERR_GENERIC_ERROR;
- }
-
- if (wParam) {
- HANDLE* event_handle = reinterpret_cast<HANDLE*>(wParam);
- SetEvent(*event_handle);
- }
- return 0;
-}
-
-LRESULT StreamOperation::OnNPPDestroyStream(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL& bHandled) {
- NPPDestroyStreamArgs *args = reinterpret_cast<NPPDestroyStreamArgs*>(lParam);
- ATLASSERT(args);
-
- // If the stream was canceled, don't pass the notification to the plug-in.
- if (!cancel_requested_) {
- *args->return_code_ = owner_->GetPluginFunctions()->destroystream(
- args->npp_,
- args->stream_,
- args->reason_);
- } else {
- *args->return_code_ = NPERR_NO_ERROR;
- }
-
- if (wParam) {
- HANDLE* event_handle = reinterpret_cast<HANDLE*>(wParam);
- SetEvent(*event_handle);
- }
- return 0;
-}
-
-LRESULT StreamOperation::OnNPPAsFile(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL& bHandled) {
- NPPAsFileArgs *args = reinterpret_cast<NPPAsFileArgs*>(lParam);
- ATLASSERT(args);
-
- // If the stream was canceled, don't pass the notification to the plug-in.
- if (!cancel_requested_) {
- owner_->GetPluginFunctions()->asfile(args->npp_, args->stream_,
- args->fname_);
- }
-
- if (wParam) {
- HANDLE* event_handle = reinterpret_cast<HANDLE*>(wParam);
- SetEvent(*event_handle);
- }
- return 0;
-}
-
-LRESULT StreamOperation::OnNPPUrlNotify(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL& bHandled) {
- NPPUrlNotifyArgs *args = reinterpret_cast<NPPUrlNotifyArgs*>(lParam);
- ATLASSERT(args);
-
- // If the stream was canceled, don't pass the notification to the plug-in.
- if (!cancel_requested_) {
- owner_->GetPluginFunctions()->urlnotify(args->npp_, args->url_,
- args->reason_, args->notify_data_);
- }
- if (wParam) {
- HANDLE* event_handle = reinterpret_cast<HANDLE*>(wParam);
- SetEvent(*event_handle);
- }
- return 0;
-}
-
-LRESULT StreamOperation::OnNPPWriteReady(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL& bHandled) {
- NPPWriteReadyArgs *args = reinterpret_cast<NPPWriteReadyArgs*>(lParam);
- ATLASSERT(args);
-
- // If the stream was canceled, don't pass the notification to the plug-in.
- if (!cancel_requested_) {
- *args->return_value_ = owner_->GetPluginFunctions()->writeready(
- args->npp_,
- args->stream_);
- } else {
- // Indicate to the download thread that 0 bytes are ready to be received.
- *args->return_value_ = 0;
- }
-
- if (wParam) {
- HANDLE* event_handle = reinterpret_cast<HANDLE*>(wParam);
- SetEvent(*event_handle);
- }
- return 0;
-}
-
-LRESULT StreamOperation::OnNPPWrite(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL& bHandled) {
- NPPWriteArgs *args = reinterpret_cast<NPPWriteArgs*>(lParam);
- ATLASSERT(args);
-
- // If the stream was canceled, don't pass the notification to the plug-in.
- if (!cancel_requested_) {
- *args->return_value_ = owner_->GetPluginFunctions()->write(
- args->npp_,
- args->stream_,
- args->offset_,
- args->len_,
- args->buffer_);
- } else {
- *args->return_value_ = args->len_;
- }
-
- if (wParam) {
- HANDLE* event_handle = reinterpret_cast<HANDLE*>(wParam);
- SetEvent(*event_handle);
- }
- return 0;
-}
-
-LRESULT StreamOperation::OnTearDown(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL& bHandled) {
- // DestroyWindow must be called on the same thread as where the window was
- // constructed, so make the call here.
- DestroyWindow();
-
- if (wParam) {
- HANDLE* event_handle = reinterpret_cast<HANDLE*>(wParam);
- SetEvent(*event_handle);
- }
- return 0;
-}
-
-HRESULT StreamOperation::RequestCancellation() {
- ATLASSERT(binding_ &&
- "Cancellation request on a stream that has not been bound.");
- cancel_requested_ = true;
- return S_OK;
-}
diff --git a/o3d/plugin/npapi_host_control/win/stream_operation.h b/o3d/plugin/npapi_host_control/win/stream_operation.h
deleted file mode 100644
index 6f1ae97..0000000
--- a/o3d/plugin/npapi_host_control/win/stream_operation.h
+++ /dev/null
@@ -1,270 +0,0 @@
-// Copyright 2009, Google Inc. All rights reserved.
-// Portions of this file were adapted from the Mozilla project.
-// See https://developer.mozilla.org/en/ActiveX_Control_for_Hosting_Netscape_Plug-ins_in_IE
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1994-2000
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- * Adam Lock <adamlock@eircom.net>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-
-// File declaring StreamOperation class encapsulating basic support
-// for the NPAPI GetURL streaming interface.
-
-#ifndef O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_STREAM_OPERATION_H_
-#define O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_STREAM_OPERATION_H_
-
-#include <atlwin.h>
-#include <atlstr.h>
-#include <urlmon.h>
-
-#include "third_party/npapi/include/npfunctions.h"
-
-class NPPluginProxy;
-
-#define WM_NPP_NEWSTREAM WM_USER
-#define WM_NPP_ASFILE WM_USER + 1
-#define WM_NPP_DESTROYSTREAM WM_USER + 2
-#define WM_NPP_URLNOTIFY WM_USER + 3
-#define WM_NPP_WRITEREADY WM_USER + 4
-#define WM_NPP_WRITE WM_USER + 5
-
-#define WM_TEAR_DOWN WM_USER + 10
-
-// StreamOperation class used to provide a subset of the NPAPI GetURL* API.
-// Class makes use of urlmon's IBindStatusCallback to receive notifications
-// from urlmon as data is transferred. Refer to the MSDN documentation
-// for information on the usage model of IBindStatusCallback.
-class ATL_NO_VTABLE StreamOperation :
- public CComObjectRootEx<CComMultiThreadModel>,
- public CWindowImpl<StreamOperation, CWindow, CNullTraits>,
- public CComCoClass<StreamOperation, &CLSID_NULL>,
- public IBindStatusCallback {
- public:
- typedef CWindowImpl<StreamOperation, CWindow, CNullTraits> CWindowImplBase;
-
- StreamOperation();
- ~StreamOperation();
-
- // Assign/Retrieve the url from which to stream the data.
- void SetURL(const wchar_t* url) {
- url_ = url;
- }
-
- const ATL::CStringW& GetURL() const {
- return url_;
- }
-
- void SetFullURL(const wchar_t* url) {
- full_url_ = url;
- }
-
- const ATL::CStringW& GetFullURL() const {
- return full_url_;
- }
-
- // Returns the MIME-type of the data stream.
- const ATL::CStringW& GetContentType() const {
- return content_type_;
- }
-
- NPStream* GetNPStream() {
- return &np_stream_;
- }
-
- HANDLE GetThreadHandle() const {
- return thread_handle_;
- }
-
- // Assign the owning plugin pointer that spawned this operation.
- void SetOwner(NPPluginProxy* plugin) {
- owner_ = plugin;
- }
-
- // Assign/Retrieve the opaque NPAPI-provided callback data for the
- // stream-operation.
- void SetNotifyData(void *notify_data) {
- notify_data_ = notify_data;
- }
-
- void* GetNotifyData() {
- return notify_data_;
- }
-
- // Call to request that the streaming operation terminate early. As soon as
- // the streaming thread sees the request has been cancelled, it aborts its
- // binding.
- HRESULT RequestCancellation();
-
-BEGIN_COM_MAP(StreamOperation)
- COM_INTERFACE_ENTRY(IBindStatusCallback)
-END_COM_MAP()
-
- // To allow interaction with non-thread-safe NPAPI plug-in modules, the
- // streaming code uses Windows message pumps to serialize the interactions
- // calling back into the plug-in on the thread in which the plug-in resides.
- // When information about the state of the streaming request is provided
- // through a IBindStatusCallback routine, the thread will post a message
- // to the window created by the StreamOperation instance. Because this
- // window will reside in the same thread as the calling plug-in, we are
- // guaranteed serialization and mutual exclusion of the handling of the
- // routines below.
-BEGIN_MSG_MAP(StreamOperation)
- MESSAGE_HANDLER(WM_NPP_NEWSTREAM, OnNPPNewStream)
- MESSAGE_HANDLER(WM_NPP_ASFILE, OnNPPAsFile)
- MESSAGE_HANDLER(WM_NPP_DESTROYSTREAM, OnNPPDestroyStream)
- MESSAGE_HANDLER(WM_NPP_URLNOTIFY, OnNPPUrlNotify)
- MESSAGE_HANDLER(WM_NPP_WRITEREADY, OnNPPWriteReady)
- MESSAGE_HANDLER(WM_NPP_WRITE, OnNPPWrite)
- MESSAGE_HANDLER(WM_TEAR_DOWN, OnTearDown);
-END_MSG_MAP()
-
- // Helper function called in response to WM_TEAR_DOWN to destroy class
- // resources on the appropriate thread.
- LRESULT OnTearDown(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL& bHandled);
-
- // The following OnNPP... routines forward the respective notification to
- // the plugin that spawned the data transmission.
- LRESULT OnNPPNewStream(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL& bHandled);
-
- LRESULT OnNPPDestroyStream(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL& bHandled);
-
- LRESULT OnNPPAsFile(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL& bHandled);
-
- LRESULT OnNPPUrlNotify(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL& bHandled);
-
- LRESULT OnNPPWriteReady(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL& bHandled);
-
- LRESULT OnNPPWrite(UINT uMsg,
- WPARAM wParam,
- LPARAM lParam,
- BOOL& bHandled);
-
- // Methods implementing the IBindStatusCallback interface. Refer to
- // the MSDN documentation for the expected behaviour of these routines.
- virtual HRESULT STDMETHODCALLTYPE OnStartBinding(DWORD dwReserved,
- IBinding *pib);
-
- virtual HRESULT STDMETHODCALLTYPE GetPriority(LONG *pnPriority);
-
- virtual HRESULT STDMETHODCALLTYPE OnLowResource(DWORD reserved);
-
- virtual HRESULT STDMETHODCALLTYPE OnProgress(ULONG ulProgress,
- ULONG ulProgressMax,
- ULONG ulStatusCode,
- LPCWSTR szStatusText);
-
- virtual HRESULT STDMETHODCALLTYPE OnStopBinding(HRESULT hresult,
- LPCWSTR szError);
-
- virtual HRESULT STDMETHODCALLTYPE GetBindInfo(DWORD *grfBINDF,
- BINDINFO *pbindinfo);
-
- virtual HRESULT STDMETHODCALLTYPE OnDataAvailable(DWORD grfBSCF,
- DWORD dwSize,
- FORMATETC *pformatetc,
- STGMEDIUM *pstgmed);
-
- virtual HRESULT STDMETHODCALLTYPE OnObjectAvailable(REFIID riid,
- IUnknown *punk);
-
- static HRESULT OpenURL(NPPluginProxy *owning_plugin, const wchar_t* url,
- void *notify_data);
-
- virtual void OnFinalMessage(HWND hWnd);
-
- DECLARE_PROTECT_FINAL_CONSTRUCT();
- private:
- // Callback object for interacting with the urlmon streaming manager.
- ATL::CComPtr<IBinding> binding_;
-
- // The url from which the data is fetched, and the associated MIME-type.
- ATL::CStringW url_;
- ATL::CStringW full_url_;
- ATL::CStringW content_type_;
-
- // Back-pointer to the plug-in instance requesting the data transfer.
- NPPluginProxy *owner_;
-
- // Opaque data specified at request initiation that is passed back to the
- // plug-in during call-back invocation.
- void *notify_data_;
-
- NPStream np_stream_;
-
- int stream_size_;
- int stream_received_;
-
- // Cache of the type of stream requested by the plug-in. May be one of:
- // NP_NORMAL, NP_ASFILE, NP_ASFILEONLY.
- int stream_type_;
-
- // Pointer to file handle used to save incoming data if the stream type is
- // NP_ASFILE or NP_ASFILEONLY.
- FILE* temp_file_;
-
- // Temporary file name.
- CStringW temp_file_name_;
-
- // Handle to the worker-thread where the streaming notifications are received.
- HANDLE thread_handle_;
-
- // Value used to indicate the streaming operation should stop processing
- // input data.
- bool cancel_requested_;
-
- static unsigned int __stdcall WorkerProc(void *worker_arguments);
-
- DISALLOW_COPY_AND_ASSIGN(StreamOperation);
-};
-
-#endif // O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_STREAM_OPERATION_H_
diff --git a/o3d/plugin/npapi_host_control/win/variant_utils.cc b/o3d/plugin/npapi_host_control/win/variant_utils.cc
deleted file mode 100644
index cdd9499..0000000
--- a/o3d/plugin/npapi_host_control/win/variant_utils.cc
+++ /dev/null
@@ -1,207 +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 "plugin/npapi_host_control/win/variant_utils.h"
-#include "base/scoped_ptr.h"
-#include "plugin/npapi_host_control/win/dispatch_proxy.h"
-
-void VariantToNPVariant(NPBrowserProxy* browser_proxy,
- const VARIANT* source,
- NPVariant* destination) {
- ATLASSERT(!(source->vt & VT_ARRAY));
-
- switch (source->vt) {
- case VT_EMPTY:
- VOID_TO_NPVARIANT(*destination);
- break;
- case VT_NULL:
- NULL_TO_NPVARIANT(*destination);
- break;
- case VT_I2:
- INT32_TO_NPVARIANT(source->iVal, *destination);
- break;
- case VT_I4:
- INT32_TO_NPVARIANT(source->intVal, *destination);
- break;
- case VT_R4:
- DOUBLE_TO_NPVARIANT(source->fltVal, *destination);
- break;
- case VT_R8:
- DOUBLE_TO_NPVARIANT(source->dblVal, *destination);
- break;
- case VT_CY:
- case VT_DATE:
- ATLASSERT(false);
- break;
- case VT_BSTR: {
- // BSTR objects may be NULL to indicate an empty string.
- if (source->bstrVal) {
- int required_size = WideCharToMultiByte(CP_UTF8, 0, source->bstrVal,
- -1, NULL, 0, NULL, NULL);
- ATLASSERT(required_size != 0);
-
- char* string_contents = static_cast<char*>(
- browser_proxy->GetBrowserFunctions()->memalloc(required_size));
- WideCharToMultiByte(CP_UTF8, 0, source->bstrVal, -1, string_contents,
- required_size, NULL, NULL);
- STRINGN_TO_NPVARIANT(string_contents, required_size - 1,
- *destination);
- } else {
- char* string_contents = static_cast<char*>(
- browser_proxy->GetBrowserFunctions()->memalloc(1));
- string_contents[0] = 0;
- STRINGN_TO_NPVARIANT(string_contents, 0, *destination);
- }
- break;
- }
- case VT_DISPATCH:
- OBJECT_TO_NPVARIANT(browser_proxy->GetNPObject(source->pdispVal),
- *destination);
- break;
- case VT_ERROR:
- ATLASSERT(false);
- break;
- case VT_BOOL:
- BOOLEAN_TO_NPVARIANT(source->boolVal, *destination);
- break;
- case VT_VARIANT:
- case VT_UNKNOWN:
- case VT_DECIMAL:
- ATLASSERT(false);
- break;
- case VT_I1:
- INT32_TO_NPVARIANT(source->iVal, *destination);
- break;
- case VT_UI1:
- INT32_TO_NPVARIANT(source->iVal, *destination);
- break;
- case VT_UI2:
- INT32_TO_NPVARIANT(source->iVal, *destination);
- break;
- case VT_UI4:
- INT32_TO_NPVARIANT(source->iVal, *destination);
- break;
- case VT_I8:
- case VT_UI8:
- ATLASSERT(false);
- break;
- case VT_INT:
- INT32_TO_NPVARIANT(source->iVal, *destination);
- break;
- case VT_UINT:
- INT32_TO_NPVARIANT(source->iVal, *destination);
- break;
- case VT_VOID:
- VOID_TO_NPVARIANT(*destination);
- break;
- case VT_HRESULT:
- case VT_PTR:
- case VT_SAFEARRAY:
- case VT_CARRAY:
- case VT_USERDEFINED:
- case VT_LPSTR:
- case VT_LPWSTR:
- case VT_RECORD:
- case VT_INT_PTR:
- case VT_UINT_PTR:
- case VT_FILETIME:
- case VT_BLOB:
- case VT_STREAM:
- case VT_STORAGE:
- case VT_STREAMED_OBJECT:
- case VT_STORED_OBJECT:
- case VT_BLOB_OBJECT:
- case VT_CF:
- case VT_CLSID:
- case VT_VERSIONED_STREAM:
- case VT_BSTR_BLOB:
- case VT_VECTOR:
- case VT_ARRAY:
- case VT_BYREF:
- case VT_RESERVED:
- case VT_ILLEGAL:
- ATLASSERT(false);
- break;
- default:
- break;
- }
-}
-
-void NPVariantToVariant(NPBrowserProxy* browser_proxy,
- const NPVariant* source,
- CComVariant* destination) {
- if (!destination) {
- return;
- }
-
- switch (source->type) {
- case NPVariantType_Void:
- destination->ChangeType(VT_VOID, NULL);
- break;
- case NPVariantType_Null:
- destination->ChangeType(VT_NULL, NULL);
- break;
- case NPVariantType_Bool:
- *destination = source->value.boolValue;
- break;
- case NPVariantType_Int32:
- *destination = source->value.intValue;
- break;
- case NPVariantType_Double:
- *destination = source->value.doubleValue;
- break;
- case NPVariantType_String: {
- int required_size = 0;
- required_size = MultiByteToWideChar(
- CP_UTF8, 0,
- source->value.stringValue.UTF8Characters,
- source->value.stringValue.UTF8Length, NULL, 0);
-
- scoped_array<wchar_t> wide_value(new wchar_t[required_size + 1]);
- MultiByteToWideChar(
- CP_UTF8, 0,
- source->value.stringValue.UTF8Characters,
- source->value.stringValue.UTF8Length, wide_value.get(),
- required_size + 1);
- wide_value[required_size] = 0;
-
- *destination = wide_value.get();
- break;
- }
- case NPVariantType_Object:
- *destination = browser_proxy->GetDispatchObject(
- source->value.objectValue);
- break;
- default:
- ATLASSERT(false);
- }
-}
diff --git a/o3d/plugin/npapi_host_control/win/variant_utils.h b/o3d/plugin/npapi_host_control/win/variant_utils.h
deleted file mode 100644
index 88bf18a..0000000
--- a/o3d/plugin/npapi_host_control/win/variant_utils.h
+++ /dev/null
@@ -1,65 +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.
- */
-
-
-// File declaring helper functions for conversion between ActiveX and
-// NPAPI variant types.
-
-#ifndef O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_VARIANT_UTILS_H_
-#define O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_VARIANT_UTILS_H_
-
-#include "plugin/npapi_host_control/win/np_browser_proxy.h"
-#include "plugin/npapi_host_control/win/np_object_proxy.h"
-
-// Converts an ActiveX variant to an NPAPI variant.
-// Parameters:
-// browser_proxy: The emulated NPAPI browser environment, required for
-// managing NPAPI string resource construction, etc.
-// source: The source COM VARIANT.
-// destination: The NPAPI variant to receive the value stored in the source.
-// On failure, the destination will be empty.
-void VariantToNPVariant(NPBrowserProxy* browser_proxy,
- const VARIANT* source,
- NPVariant* destination);
-
-
-// Converts a NPAPI variant to an ActiveX variant.
-// Parameters:
-// browser_proxy: The emulated NPAPI browser environment, required for
-// managing NPAPI string resource construction, etc.
-// source: The source NPAPI variant.
-// destination: The COM VARIANT to receive the value stored in the source.
-// On failure, the destination will be empty.
-void NPVariantToVariant(NPBrowserProxy* browser_proxy,
- const NPVariant* source,
- CComVariant* destination);
-
-#endif // O3D_PLUGIN_NPAPI_HOST_CONTROL_WIN_VARIANT_UTILS_H_
diff --git a/o3d/plugin/o3d_binding.py b/o3d/plugin/o3d_binding.py
deleted file mode 100644
index c0ae572..0000000
--- a/o3d/plugin/o3d_binding.py
+++ /dev/null
@@ -1,536 +0,0 @@
-#!/usr/bin/python2.4
-# 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.
-
-"""o3d binding model module.
-
-This module implements the glue functions for the o3d binding model, binding
-O3D objects.
-
-In C++, objects using this binding model are passed and returned by pointer.
-For example
-void SetValue(Class *value);
-Class *GetValue();
-
-For JS bindings, the browser object holds an id, representing the C++ object
-through that can be accessed through the Client object.
-"""
-
-
-import string
-
-import cpp_utils
-import java_utils
-
-
-class CallingConstructor(Exception):
- """Raised when trying to call a constructor on an O3D object."""
- pass
-
-
-def JavaMemberString(scope, type_defn):
- """Gets the representation of a member name in Java.
-
- Args:
- scope: a Definition for the scope in which the expression will be written.
- type_defn: a Definition for the type.
-
- Returns:
- a string representing the type
- """
- return java_utils.GetScopedName(scope, type_defn)
-
-
-def CppTypedefString(scope, type_defn):
- """Gets the representation of a type when used in a C++ typedef.
-
- Args:
- scope: a Definition for the scope in which the expression will be written.
- type_defn: a Definition for the type.
-
- Returns:
- a (string, boolean) pair, the first element being the representation of
- the type, the second element indicating whether or not the definition of
- the type is needed for the expression to be valid.
- """
- return cpp_utils.GetScopedName(scope, type_defn), False
-
-
-def CppMemberString(scope, type_defn):
- """Gets the representation of a type when used as a C++ class member.
-
- Args:
- scope: a Definition for the scope in which the expression will be written.
- type_defn: a Definition for the type.
-
- Returns:
- a (string, boolean) pair, the first element being the representation of
- the type, the second element indicating whether or not the definition of
- the type is needed for the expression to be valid.
- """
- return '%s*' % cpp_utils.GetScopedName(scope, type_defn), False
-
-
-def CppReturnValueString(scope, type_defn):
- """Gets the representation of a type when used as a C++ function return value.
-
- Args:
- scope: a Definition for the scope in which the expression will be written.
- type_defn: a Definition for the type.
-
- Returns:
- a (string, boolean) pair, the first element being the representation of
- the type, the second element indicating whether or not the definition of
- the type is needed for the expression to be valid.
- """
- return '%s*' % cpp_utils.GetScopedName(scope, type_defn), False
-
-
-def CppParameterString(scope, type_defn):
- """Gets the representation of a type when used for a function parameter.
-
- Args:
- scope: a Definition for the scope in which the expression will be written.
- type_defn: a Definition for the type.
-
- Returns:
- a (string, boolean) pair, the first element being the representation of
- the type, the second element indicating whether or not the definition of
- the type is needed for the expression to be valid.
- """
- return '%s*' % cpp_utils.GetScopedName(scope, type_defn), False
-
-
-def CppMutableParameterString(scope, type_defn):
- """Gets the representation of a type for a mutable function parameter.
-
- Args:
- scope: a Definition for the scope in which the expression will be written.
- type_defn: a Definition for the type.
-
- Returns:
- a (string, boolean) pair, the first element being the string representing
- the type, the second element indicating whether or not the definition of
- the type is needed for the expression to be valid.
- """
- return '%s*' % cpp_utils.GetScopedName(scope, type_defn), False
-
-
-def CppMutableToNonMutable(scope, type_defn, expr):
- """Gets the string converting a mutable expression to a non-mutable one.
-
- Args:
- scope: a Definition for the scope in which the expression will be written.
- type_defn: a Definition for the type.
- expr: a string for the mutable expression.
-
- Returns:
- a string, which is the non-mutable expression.
- """
- (scope, type_defn) = (scope, type_defn) # silence gpylint.
- return expr
-
-
-def CppBaseClassString(scope, type_defn):
- """Gets the representation of a type for a base class.
-
- Args:
- scope: a Definition for the scope in which the expression will be written.
- type_defn: a Definition for the type.
-
- Returns:
- a (string, boolean) pair, the first element being the string representing
- the type, the second element indicating whether or not the definition of
- the type is needed for the expression to be valid.
- """
- return cpp_utils.GetScopedName(scope, type_defn)
-
-
-def CppCallMethod(scope, type_defn, object_expr, mutable, method, param_exprs):
- """Gets the representation of a member function call.
-
- Args:
- scope: a Definition for the scope in which the expression will be written.
- type_defn: a Definition, representing the type of the object being called.
- object_expr: a string, which is the expression for the object being called.
- mutable: a boolean, whether or not the 'object_expr' expression is mutable
- or not
- method: a Function, representing the function to call.
- param_exprs: a list of strings, each being the expression for the value of
- each parameter.
-
- Returns:
- a string, which is the expression for the function call.
- """
- (scope, type_defn, mutable) = (scope, type_defn, mutable) # silence gpylint.
- return '%s->%s(%s)' % (object_expr, method.name, ', '.join(param_exprs))
-
-
-def CppCallStaticMethod(scope, type_defn, method, param_exprs):
- """Gets the representation of a static function call.
-
- Args:
- scope: a Definition for the scope in which the expression will be written.
- type_defn: a Definition, representing the type of the object being called.
- method: a Function, representing the function to call.
- param_exprs: a list of strings, each being the expression for the value of
- each parameter.
-
- Returns:
- a string, which is the expression for the function call.
- """
- return '%s::%s(%s)' % (cpp_utils.GetScopedName(scope, type_defn),
- method.name, ', '.join(param_exprs))
-
-
-def CppCallConstructor(scope, type_defn, method, param_exprs):
- """Gets the representation of a constructor call.
-
- Args:
- scope: a Definition for the scope in which the expression will be written.
- type_defn: a Definition, representing the type of the object being called.
- method: a Function, representing the constructor to call.
- param_exprs: a list of strings, each being the expression for the value of
- each parameter.
-
- Returns:
- a string, which is the expression for the constructor call.
-
- Raises:
- CallingConstructor: always. O3D objects can't be constructed directly.
- """
- raise CallingConstructor
-
-
-def CppSetField(scope, type_defn, object_expr, field, param_expr):
- """Gets the representation of an expression setting a field in an object.
-
- Args:
- scope: a Definition for the scope in which the expression will be written.
- type_defn: a Definition, representing the type of the object containing the
- field being set.
- object_expr: a string, which is the expression for the object containing
- the field being set.
- field: a string, the name of the field to be set.
- param_expr: a strings, being the expression for the value to be set.
-
- Returns:
- a string, which is the expression for setting the field.
- """
- (scope, type_defn) = (scope, type_defn) # silence gpylint.
- return '%s->%s(%s)' % (object_expr, cpp_utils.GetSetterName(field),
- param_expr)
-
-
-def CppGetField(scope, type_defn, object_expr, field):
- """Gets the representation of an expression getting a field in an object.
-
- Args:
- scope: a Definition for the scope in which the expression will be written.
- type_defn: a Definition, representing the type of the object containing the
- field being retrieved.
- object_expr: a string, which is the expression for the object containing
- the field being retrieved.
- field: a string, the name of the field to be retrieved.
-
- Returns:
- a string, which is the expression for getting the field.
- """
- (scope, type_defn) = (scope, type_defn) # silence gpylint.
- return '%s->%s()' % (object_expr, cpp_utils.GetGetterName(field))
-
-
-def CppSetStatic(scope, type_defn, field, param_expr):
- """Gets the representation of an expression setting a static field.
-
- Args:
- scope: a Definition for the scope in which the expression will be written.
- type_defn: a Definition, representing the type of the object containing the
- field being set.
- field: a string, the name of the field to be set.
- param_expr: a strings, being the expression for the value to be set.
-
- Returns:
- a string, which is the expression for setting the field.
- """
- return '%s::%s(%s)' % (cpp_utils.GetScopedName(scope, type_defn),
- cpp_utils.GetSetterName(field), param_expr)
-
-
-def CppGetStatic(scope, type_defn, field):
- """Gets the representation of an expression getting a static field.
-
- Args:
- scope: a Definition for the scope in which the expression will be written.
- type_defn: a Definition, representing the type of the object containing the
- field being retrieved.
- field: a string, the name of the field to be retrieved.
-
- Returns:
- a string, which is the expression for getting the field.
- """
- return '%s::%s()' % (cpp_utils.GetScopedName(scope, type_defn),
- cpp_utils.GetGetterName(field))
-
-
-def JSDocTypeString(type_defn):
- """Gets the representation of a type in JSDoc notation.
-
- Args:
- type_defn: a Definition for the type.
-
- Returns:
- a string that is the JSDoc notation of type_defn.
- """
- type_defn = type_defn.GetFinalType()
- type_stack = type_defn.GetParentScopeStack()
- name = type_defn.name
- return '!' + '.'.join([s.name for s in type_stack[1:]] + [name])
-
-
-_binding_glue_header_template = string.Template('')
-
-
-def NpapiBindingGlueHeader(scope, type_defn):
- """Gets the NPAPI glue header for a given type.
-
- Args:
- scope: a Definition for the scope in which the glue will be written.
- type_defn: a Definition, representing the type.
-
- Returns:
- a string, the glue header.
- """
- class_name = cpp_utils.GetScopedName(scope, type_defn)
- return _binding_glue_header_template.substitute(Class=class_name)
-
-
-_binding_glue_cpp_template = string.Template("""
-void InitializeGlue(NPP npp) {
- InitializeIds(npp);
- glue::_o3d::RegisterType(npp, ${Class}::GetApparentClass(), &npclass);
-}
-
-glue::_o3d::NPAPIObject *GetNPObject(NPP npp, ${Class}* object) {
- return glue::_o3d::GetNPObject(npp, object);
-}
-
-static NPObject *Allocate(NPP npp, NPClass *theClass) {
- return glue::_o3d::Allocate(npp, theClass);
-}
-
-static void Deallocate(NPObject *header) {
- return glue::_o3d::Deallocate(header);
-}
-""")
-
-
-def NpapiBindingGlueCpp(scope, type_defn):
- """Gets the NPAPI glue implementation for a given type.
-
- Args:
- scope: a Definition for the scope in which the glue will be written.
- type_defn: a Definition, representing the type.
-
- Returns:
- a string, the glue implementation.
- """
- class_name = cpp_utils.GetScopedName(scope, type_defn)
- return _binding_glue_cpp_template.substitute(Class=class_name)
-
-
-dispatch_function_header_template = string.Template("""
-glue::_o3d::NPAPIObject *${variable_npobject} =
- static_cast<glue::_o3d::NPAPIObject *>(header);
-NPP ${npp} = ${variable_npobject}->npp();
-${Class} *${variable} = glue::_o3d::GetClient(
- ${npp})->GetById<${Class}>(${variable_npobject}->id());
-${result} = (${variable} != NULL);
-if (!${result}) {
- O3D_ERROR(glue::_o3d::GetServiceLocator(${npp})) <<
- "Invalid object; perhaps it's been destroyed already?";
-}
-""")
-
-
-def NpapiDispatchFunctionHeader(scope, type_defn, variable, npp, success):
- """Gets a header for NPAPI glue dispatch functions.
-
- This function creates a string containing a C++ code snippet that should be
- included at the beginning of NPAPI glue dispatch functions like Invoke or
- GetProperty. This code snippet will declare and initialize certain variables
- that will be used in the dispatch functions, like the NPObject representing
- the object, or a pointer to the NPP instance.
-
- Args:
- scope: a Definition for the scope in which the glue will be written.
- type_defn: a Definition, representing the type.
- variable: a string, representing a name of a variable that can be used to
- store a reference to the object.
- npp: a string, representing the name of the variable that holds the pointer
- to the NPP instance. Will be declared by the code snippet.
- success: the name of a bool variable containing the current success status.
- (is not declared by the code snippet).
-
- Returns:
- a (string, string) pair, the first string being the code snippet, and the
- second string being an expression to access the object.
- """
- class_name = cpp_utils.GetScopedName(scope, type_defn)
- variable_npobject = '%s_npobject' % variable
- text = dispatch_function_header_template.substitute(
- variable_npobject=variable_npobject, npp=npp, variable=variable,
- Class=class_name, result=success)
- return text, variable
-
-
-from_npvariant_template = string.Template("""
-${Class} *${variable} = NULL;
-if (NPVARIANT_IS_OBJECT(${input})) {
- NPObject *npobject = NPVARIANT_TO_OBJECT(${input});
- if (glue::_o3d::CheckObject(npp, npobject,
- ${Class}::GetApparentClass())) {
- glue::_o3d::NPAPIObject *client_object =
- static_cast<glue::_o3d::NPAPIObject *>(npobject);
- ${variable} =
- glue::_o3d::GetClient(${npp})->GetById<${Class}>(
- client_object->id());
- if (${variable} == NULL) {
- ${result} = false;
- *error_handle = "Error in " ${context}
- ": input wasn't a valid object from this plugin instance.";
- } else {
- ${result} = true;
- }
- } else {
- *error_handle = "Error in " ${context}
- ": invalid type.";
- ${result} = false;
- }
-} else {
- *error_handle = "Error in " ${context}
- ": was expecting an object.";
- ${result} = false;
-}
-""")
-
-
-def NpapiFromNPVariant(scope, type_defn, input_expr, variable, success,
- exception_context, npp):
- """Gets the string to get a value from a NPVariant.
-
- This function creates a string containing a C++ code snippet that is used to
- retrieve a value from a NPVariant. If an error occurs, like if the NPVariant
- is not of the correct type, the snippet will set the success status variable
- to false and set *error_handle with an appropriate error message.
-
- Args:
- scope: a Definition for the scope in which the glue will be written.
- type_defn: a Definition, representing the type of the value.
- input_expr: an expression representing the NPVariant to get the value from.
- variable: a string, representing a name of a variable that can be used to
- store a reference to the value.
- success: the name of a bool variable containing the current success status.
- exception_context: the name of a string containing context information, for
- use in exception reporting.
- npp: a string, representing the name of the variable that holds the pointer
- to the NPP instance.
-
- Returns:
- a (string, string) pair, the first string being the code snippet and the
- second one being the expression to access that value.
- """
- class_name = cpp_utils.GetScopedName(scope, type_defn)
- text = from_npvariant_template.substitute(Class=class_name,
- variable=variable,
- input=input_expr,
- npp=npp,
- result=success,
- context=exception_context)
- return (text, variable)
-
-
-expr_to_npobject_template = string.Template("""
-glue::_o3d::NPAPIObject *${variable} =
- glue::_o3d::GetNPObject(${npp}, ${expr});
-if (!${variable}) {
- *error_handle = "Error : type cannot be null.";
- ${result} = false;
-}
-""")
-
-npobject_to_npvariant_template = string.Template("""
-OBJECT_TO_NPVARIANT(${variable}, *${output});
-""")
-
-
-def NpapiExprToNPVariant(scope, type_defn, variable, expression, output,
- success, npp):
- """Gets the string to store a value into a NPVariant.
-
- This function creates a string containing a C++ code snippet that is used to
- store a value into a NPVariant. That operation takes two phases, one that
- allocates necessary NPAPI resources, and that can fail, and one that actually
- sets the NPVariant (that can't fail). If an error occurs, the snippet will
- set the success status variable to false.
-
- Args:
- scope: a Definition for the scope in which the glue will be written.
- type_defn: a Definition, representing the type of the value.
- variable: a string, representing a name of a variable that can be used to
- store a reference to the value.
- expression: a string representing the expression that yields the value to
- be stored.
- output: an expression representing a pointer to the NPVariant to store the
- value into.
- success: the name of a bool variable containing the current success status.
- npp: a string, representing the name of the variable that holds the pointer
- to the NPP instance.
-
- Returns:
- a (string, string) pair, the first string being the code snippet for the
- first phase, and the second one being the code snippet for the second phase.
- """
- (scope, type_defn) = (scope, type_defn) # silence gpylint.
- phase_1_text = expr_to_npobject_template.substitute(variable=variable,
- npp=npp,
- expr=expression,
- result=success)
- phase_2_text = npobject_to_npvariant_template.substitute(
- variable=variable,
- output=output,
- result=success)
- return phase_1_text, phase_2_text
-
-
-def main():
- pass
-
-if __name__ == '__main__':
- main()
diff --git a/o3d/plugin/o3d_iface_generator.py b/o3d/plugin/o3d_iface_generator.py
deleted file mode 100644
index 82092bf..0000000
--- a/o3d/plugin/o3d_iface_generator.py
+++ /dev/null
@@ -1,618 +0,0 @@
-#!/usr/bin/python2.4
-# 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.
-
-
-"""O3D interface class generator.
-
-This module generates the O3D interface classes.
-"""
-
-
-import os
-import syntax_tree
-import cpp_utils
-import naming
-
-class CircularDefinition(Exception):
- """Raised when a circular type definition is found."""
-
- def __init__(self, type_defn):
- Exception.__init__(self)
- self.type = type_defn
-
-
-class BadForwardDeclaration(Exception):
- """Raised when an impossible forward declaration is required."""
-
-
-def ForwardDecl(section, type_defn):
- """Emits the forward declaration of a type, if possible.
-
- Inner types (declared inside a class) cannot be forward-declared.
- Only classes can be forward-declared.
-
- Args:
- section: the section to emit to.
- type_defn: the Definition for the type to forward-declare.
-
- Raises:
- BadForwardDeclaration: an inner type or a non-class was passed as an
- argument.
- """
- # inner types cannot be forward-declared
- if type_defn.parent.defn_type != 'Namespace':
- raise BadForwardDeclaration
- stack = type_defn.GetParentScopeStack()
- if type_defn.defn_type == 'Class':
- for scope in stack:
- if scope.name:
- section.PushNamespace(scope.name)
- section.EmitCode('class %s;' % type_defn.name)
- for scope in stack[::-1]:
- if scope.name:
- section.PopNamespace()
- else:
- raise BadForwardDeclaration
-
-
-class O3DInterfaceGenerator(object):
- """Header generator class.
-
- This class takes care of the details of generating a C++ header file
- containing all the definitions from a syntax tree.
-
- It contains a list of functions named after each of the Definition classes in
- syntax_tree, with a common signature. The appropriate function will be called
- for each definition, to generate the code for that definition.
- """
-
- class GenerationContext(object):
- def __init__(self, header_scope, cpp_scope, header_section, cpp_section):
- self.header_scope = header_scope
- self.header_section = header_section
- self.cpp_scope = cpp_scope
- self.cpp_section = cpp_section
- self.needed_decl = set()
- self.needed_defn = set()
- self.emitted_defn = set()
-
- def Fork(self, header_scope, cpp_scope, header_section, cpp_section):
- new_context = type(self)(header_scope, cpp_scope, header_section,
- cpp_section)
- new_context.needed_decl = self.needed_decl
- new_context.needed_defn = self.needed_defn
- new_context.emitted_defn = self.emitted_defn
- return new_context
-
- def CheckType(self, need_defn, type_defn):
- """Checks for the definition or declaration of a type.
-
- This function helps keeping track of which types are needed to be defined
- or declared in the C++ file before other definitions can happen. If the
- definition is needed (and is not in this C++ header file), the proper
- include will be generated. If the type only needs to be forward-declared,
- the forward declaration will be output (if the type is not otherwise
- defined).
-
- Args:
- need_defn: a boolean, True if the C++ definition of the type is needed,
- False if only the declaration is needed.
- type_defn: the Definition of the type to check.
- """
- while type_defn.defn_type == 'Array':
- # arrays are implicitly defined with their data type
- type_defn = type_defn.data_type
- if need_defn:
- if type_defn not in self.emitted_defn:
- self.needed_defn.add(type_defn)
- else:
- if type_defn in self.emitted_defn:
- return
- if type_defn.parent and type_defn.parent.defn_type != 'Namespace':
- # inner type: need the definition of the parent.
- self.CheckType(True, type_defn.parent)
- else:
- # only forward-declare classes.
- # typedefs could be forward-declared by emitting the definition again,
- # but this necessitates the source type to be forward-declared before.
- # TODO: see if it is possible to find a proper ordering that let
- # us forward-declare typedefs instead of needing to include the
- # definition.
- if type_defn.defn_type == 'Class':
- self.needed_decl.add(type_defn)
- else:
- self.needed_defn.add(type_defn)
-
- def __init__(self, output_dir, namespace):
- self._output_dir = output_dir
- self._void_type = namespace.LookupTypeRecursive('void')
-
- def GetHeaderFile(self, idl_file):
- return idl_file.source.split('.')[0] + '.h'
-
- def GetCppFile(self, idl_file):
- return idl_file.source.split('.')[0] + '.cc'
-
- def GetInterfaceInclude(self, type_defn):
- if self.NeedsGlue(type_defn):
- return self.GetHeaderFile(type_defn.source.file)
- else:
- return type_defn.GetDefinitionInclude()
-
- def GetImplementationInclude(self, type_defn):
- return type_defn.GetDefinitionInclude()
-
- def IsVoid(self, type_defn):
- return type_defn.GetFinalType() == self._void_type
-
- def NeedsGlue(self, obj):
- return obj.LookupBindingModel() == 'o3d' or 'glue_iface' in obj.attributes
-
- def GetSectionFromAttributes(self, parent_section, defn):
- """Gets the code section appropriate for a given definition.
-
- Classes have 3 definition sections: private, protected and public. This
- function will pick one of the sections, based on the attributes of the
- definition, if its parent is a class. For other scopes (namespaces) it will
- return the parent scope main section.
-
- Args:
- parent_section: the main section for the parent scope.
- defn: the definition.
-
- Returns:
- the appropriate section.
- """
- if defn.parent and defn.parent.defn_type == 'Class':
- if 'private' in defn.attributes:
- return parent_section.GetSection('private:') or parent_section
- elif 'protected' in defn.attributes:
- return parent_section.GetSection('protected:') or parent_section
- else:
- return parent_section.GetSection('public:') or parent_section
- else:
- return parent_section
-
- def Verbatim(self, context, obj):
- """Generates the code for a Verbatim definition.
-
- Verbatim definitions being written for a particular type of output file,
- this function will check the 'verbatim' attribute, and only emit the
- verbatim code if it is 'cpp_header'.
-
- Args:
- parent_section: the main section of the parent scope.
- obj: the Verbatim definition.
- """
- try:
- verbatim_attr = obj.attributes['verbatim']
- except KeyError:
- source = obj.source
- print ('%s:%d ignoring verbatim with no verbatim attribute' %
- (source.file.source, source.line))
- return
- if verbatim_attr == 'o3d_iface_header':
- section = self.GetSectionFromAttributes(context.header_section, obj)
- section.EmitCode(obj.text)
- elif verbatim_attr == 'o3d_iface_cpp':
- context.cpp_section.EmitCode(obj.text)
-
- def Typedef(self, context, obj):
- """Generates the code for a Typedef definition.
-
- Args:
- parent_section: the main section of the parent scope.
- obj: the Typedef definition.
-
- Returns:
- a list of (boolean, Definition) pairs, of all the types that need
- to be declared (boolean is False) or defined (boolean is True) before
- this definition.
- """
- section = self.GetSectionFromAttributes(context.header_section, obj)
- bm = obj.type.binding_model
- type_string, unused_need_defn = bm.CppTypedefString(context.header_scope,
- obj.type)
- context.CheckType(True, obj.type)
- section.EmitCode('typedef %s %s;' % (type_string, obj.name))
-
- def Variable(self, context, obj):
- """Generates the code for a Variable definition.
-
- This function will generate the member/global variable declaration, as well
- as the setter/getter functions if specified in the attributes.
-
- Args:
- parent_section: the main section of the parent scope.
- obj: the Variable definition.
- """
- bm = obj.type.binding_model
- type_string, need_defn = bm.CppMemberString(context.header_scope, obj.type)
- context.CheckType(need_defn, obj.type)
- need_glue = self.NeedsGlue(obj) or (obj.parent.is_type and
- self.NeedsGlue(obj.parent));
-
- getter_attributes = {}
- if 'static' in obj.attributes:
- getter_attributes['static'] = obj.attributes['static']
- static = 'static '
- else:
- static = ''
- for attr in ['public', 'protected', 'private']:
- if attr in obj.attributes:
- getter_attributes[attr] = obj.attributes[attr]
-
- if not need_glue:
- if obj.parent.defn_type == 'Class':
- if 'field_access' in obj.attributes:
- member_section = context.header_section.GetSection(
- obj.attributes['field_access'] + ':')
- else:
- member_section = context.header_section.GetSection('private:')
- else:
- member_section = context.header_section
- field_name = naming.Normalize(obj.name, naming.LowerTrailing)
- member_section.EmitCode('%s%s %s;' % (static, type_string, field_name))
-
- if 'getter' in obj.attributes:
- func = obj.MakeGetter(getter_attributes, cpp_utils.GetGetterName(obj))
- if need_glue:
- self.FunctionGlue(context, func)
- impl = None
- else:
- impl = ' { return %s; }' % field_name
- self.FunctionDecl(context, func, impl)
- if 'setter' in obj.attributes:
- func = obj.MakeSetter(getter_attributes, cpp_utils.GetSetterName(obj))
- if need_glue:
- self.FunctionGlue(context, func)
- impl = None
- else:
- impl = ' { %s = %s; }' % (field_name, obj.name)
- self.FunctionDecl(context, func, impl)
-
- def GetParamsDecls(self, scope, obj, context=None):
- param_strings = []
- for p in obj.params:
- bm = p.type.binding_model
- if p.mutable:
- text, need_defn = bm.CppMutableParameterString(scope, p.type)
- else:
- text, need_defn = bm.CppParameterString(scope, p.type)
- if context:
- context.CheckType(need_defn, p.type)
- param_strings += ['%s %s' % (text, p.name)]
- return ', '.join(param_strings)
-
- def FunctionDecl(self, context, obj, impl_string=None):
- section = self.GetSectionFromAttributes(context.header_section, obj)
- if not impl_string:
- impl_string = ';'
- params_string = self.GetParamsDecls(context.header_scope, obj, context)
- prefix_strings = []
- suffix_strings = []
- for attrib in ['static', 'virtual', 'inline']:
- if attrib in obj.attributes:
- prefix_strings.append(attrib)
- if prefix_strings:
- prefix_strings.append('')
- if 'const' in obj.attributes:
- suffix_strings.append('const')
- if 'pure' in obj.attributes:
- suffix_strings.append('= 0')
- if suffix_strings:
- suffix_strings.insert(0, '')
- prefix = ' '.join(prefix_strings)
- suffix = ' '.join(suffix_strings)
- if obj.type:
- bm = obj.type.binding_model
- return_type, need_defn = bm.CppReturnValueString(context.header_scope,
- obj.type)
- context.CheckType(need_defn, obj.type)
- section.EmitCode('%s%s %s(%s)%s%s' % (prefix, return_type, obj.name,
- params_string, suffix, impl_string))
- else:
- section.EmitCode('%s%s(%s)%s%s' % (prefix, obj.name, params_string,
- suffix, impl_string))
-
- def FunctionGlue(self, context, obj):
- if not obj.type:
- # TODO autogen a factory
- return
- if 'pure' in obj.attributes:
- return
-
- if obj.parent.is_type:
- func_name = '%s::%s' % (obj.parent.name, obj.name)
- if 'static' in obj.attributes:
- call_prefix = 'impl::' + func_name
- else:
- # this_call
- if self.NeedsGlue(obj.parent):
- call_prefix = 'GetImpl()->'
- else:
- call_prefix = ''
- else:
- call_prefix = ''
- func_name = obj.name
-
- params_string = self.GetParamsDecls(context.cpp_scope, obj)
- param_exprs = []
- for p in obj.params:
- if self.NeedsGlue(p.type):
- param_exprs.append('%s->GetImpl()' % p.name)
- else:
- param_exprs.append(p.name)
-
- if not self.IsVoid(obj.type):
- return_prefix = 'return '
- if self.NeedsGlue(obj.type):
- return_suffix = '->GetIface()'
- else:
- return_suffix = ''
- else:
- return_prefix = ''
- return_suffix = ''
-
- bm = obj.type.binding_model
- return_type, unused = bm.CppReturnValueString(context.header_scope,
- obj.type)
- if 'const' in obj.attributes:
- func_suffix = ' const'
- else:
- func_suffix = ''
-
- section = context.cpp_section
- section.EmitCode('%s %s(%s)%s {' % (return_type, func_name, params_string,
- func_suffix))
- section.EmitCode('%s%s%s(%s)%s;' % (return_prefix, call_prefix, obj.name,
- ', '.join(param_exprs), return_suffix))
- section.EmitCode('}')
-
- def Function(self, context, obj):
- """Generates the code for a Function definition.
-
- Args:
- parent_section: the main section of the parent scope.
- obj: the Function definition.
- """
- self.FunctionDecl(context, obj)
- if self.NeedsGlue(obj) or (obj.parent.is_type and
- self.NeedsGlue(obj.parent)):
- self.FunctionGlue(context, obj)
-
- def Class(self, context, obj):
- """Generates the code for a Class definition.
-
- This function will recursively generate the code for all the definitions
- inside the class. These definitions will be output into one of 3 sections
- (private, protected, public), depending on their attributes. These
- individual sections will only be output if they are not empty.
-
- Args:
- parent_section: the main section of the parent scope.
- obj: the Class definition.
- """
- h_section = self.GetSectionFromAttributes(context.header_section,
- obj).CreateSection(obj.name)
- c_section = context.cpp_section
-
- need_glue = self.NeedsGlue(obj)
- if need_glue:
- h_section.PushNamespace('impl')
- h_section.EmitCode('class %s;' % obj.name)
- h_section.PopNamespace()
- h_section.EmitCode('')
- if obj.base_type:
- bm = obj.base_type.binding_model
- h_section.EmitCode('class %s : public %s {' %
- (obj.name, bm.CppBaseClassString(context.header_scope,
- obj.base_type)))
- context.CheckType(True, obj.base_type)
- else:
- h_section.EmitCode('class %s {' % obj.name)
- public_section = h_section.CreateSection('public:')
- protected_section = h_section.CreateSection('protected:')
- private_section = h_section.CreateSection('private:')
-
- new_context = context.Fork(obj, context.cpp_scope, h_section, c_section)
- self.DefinitionList(new_context, obj.defn_list)
-
- if need_glue:
- public_section.EmitCode('impl::%s *GetImpl();' % obj.name)
- c_section.EmitCode('impl::%s *%s::GetImpl() {' % (obj.name, obj.name))
- c_section.EmitCode('return static_cast<impl::%s *>(impl_);' % obj.name)
- c_section.EmitCode('}')
-
- if not public_section.IsEmpty():
- public_section.AddPrefix('public:')
- if not protected_section.IsEmpty():
- protected_section.AddPrefix('protected:')
- if not private_section.IsEmpty():
- private_section.AddPrefix('private:')
- h_section.EmitCode('};')
-
- def Namespace(self, context, obj):
- """Generates the code for a Namespace definition.
-
- This function will recursively generate the code for all the definitions
- inside the namespace.
-
- Args:
- parent_section: the main section of the parent scope.
- obj: the Namespace definition.
- """
- context.header_section.PushNamespace(obj.name)
- context.cpp_section.PushNamespace(obj.name)
- new_context = context.Fork(obj, obj, context.header_section,
- context.cpp_section)
- self.DefinitionList(new_context, obj.defn_list)
- context.header_section.PopNamespace()
- context.cpp_section.PopNamespace()
-
- def Typename(self, context, obj):
- """Generates the code for a Typename definition.
-
- Since typenames (undefined types) cannot be expressed in C++, this function
- will not output code. The definition may be output with a verbatim section.
-
- Args:
- parent_section: the main section of the parent scope.
- scope: the parent scope.
- obj: the Typename definition.
- """
-
- def Enum(self, context, obj):
- """Generates the code for an Enum definition.
-
- Args:
- parent_section: the main section of the parent scope.
- scope: the parent scope.
- obj: the Enum definition.
- """
- section = self.GetSectionFromAttributes(context.header_section, obj)
- section.EmitCode('enum %s {' % obj.name)
- for value in obj.values:
- if value.value is None:
- section.EmitCode('%s,' % value.name)
- else:
- section.EmitCode('%s = %s,' % (value.name, value.value))
- section.EmitCode('};')
-
- def DefinitionList(self, context, defn_list):
- """Generates the code for all the definitions in a list.
-
- Args:
- parent_section: the main section of the parent scope.
- scope: the parent scope.
- defn_list: the list of definitions.
- """
- for obj in defn_list:
- context.emitted_defn.add(obj)
- # array types are implicitly defined
- for k in obj.array_defns:
- context.emitted_defn.add(obj.array_defns[k])
- getattr(self, obj.defn_type)(context, obj)
-
- def Generate(self, idl_file, namespace, defn_list):
- """Generates the header file.
-
- Args:
- idl_file: the source IDL file containing the definitions, as a
- idl_parser.File instance.
- namespace: a Definition for the global namespace.
- defn_list: the list of top-level definitions.
-
- Returns:
- a cpp_utils.CppFileWriter that contains the C++ header file code.
-
- Raises:
- CircularDefinition: circular definitions were found in the file.
- """
- all_defn = syntax_tree.GetObjectsRecursive(defn_list)
- need_glue = False
- for defn in all_defn:
- if self.NeedsGlue(defn):
- need_glue = True
- break
- if not need_glue:
- return []
-
- header_writer = cpp_utils.CppFileWriter(
- '%s/%s' % (self._output_dir, self.GetHeaderFile(idl_file)), True)
-
- cpp_writer = cpp_utils.CppFileWriter(
- '%s/%s' % (self._output_dir, self.GetCppFile(idl_file)), True)
-
- h_decl_section = header_writer.CreateSection('decls')
- h_code_section = header_writer.CreateSection('defns')
- c_code_section = cpp_writer.CreateSection('glue')
-
- context = self.GenerationContext(namespace, namespace, h_code_section,
- c_code_section)
-
- self.DefinitionList(context, defn_list)
-
- context.needed_decl -= context.needed_defn
- if context.needed_decl:
- for type_defn in context.needed_decl:
- # TODO: sort by namespace so that we don't open and close them
- # more than necessary.
- ForwardDecl(h_decl_section, type_defn)
- h_decl_section.EmitCode('')
-
- for type_defn in context.needed_defn:
- if type_defn.source.file == idl_file:
- raise CircularDefinition(type_defn)
-
- h_includes = set(self.GetInterfaceInclude(type_defn)
- for type_defn in context.needed_defn)
- c_includes = set(self.GetImplementationInclude(type_defn)
- for type_defn in context.emitted_defn
- if self.NeedsGlue(type_defn))
- c_includes.add(self.GetHeaderFile(idl_file))
-
- for include_file in h_includes:
- if include_file is not None:
- header_writer.AddInclude(include_file)
- for include_file in c_includes:
- if include_file is not None:
- cpp_writer.AddInclude(include_file)
- return [header_writer, cpp_writer]
-
-
-def ProcessFiles(output_dir, pairs, namespace):
- """Generates the headers for all input files.
-
- Args:
- output_dir: the output directory.
- pairs: a list of (idl_parser.File, syntax_tree.Definition list) describing
- the list of top-level definitions in each source file.
- namespace: a syntax_tree.Namespace for the global namespace.
-
- Returns:
- a list of cpp_utils.CppFileWriter, one for each output file.
- """
- output_dir = output_dir + '/iface'
- if not os.access(output_dir + '/', os.F_OK):
- os.makedirs(output_dir)
-
- generator = O3DInterfaceGenerator(output_dir, namespace)
- writer_list = []
- for (f, defn) in pairs:
- writer_list += generator.Generate(f, namespace, defn)
- return writer_list
-
-
-def main():
- pass
-
-if __name__ == '__main__':
- main()
diff --git a/o3d/plugin/plugin.gyp b/o3d/plugin/plugin.gyp
deleted file mode 100644
index 0a282a54..0000000
--- a/o3d/plugin/plugin.gyp
+++ /dev/null
@@ -1,853 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# PLEASE NOTE: This file contains the targets for generating the
-# plugin two different ways -- once as a shared library, and once as a
-# static library. The static library is only built if we are inside
-# of a Chrome tree, and it gets built with different defined symbols,
-# and without the packaging code on the Mac. The shared library gets
-# built in an o3d tree, or in a chrome tree when built by an o3d
-# developer (someone who has added the .gclient stanza to include
-# DEPS_chrome). This results in having two targets in this file which
-# are largely identical, but still significantly different.
-#
-# Please be sure and synchronize these two targets so that we can
-# continue to build both the standalone plugin and the Chrome-embedded
-# plugin.
-
-{
- 'variables': {
- 'chromium_code': 1,
- 'plugin_sources': [
- 'cross/async_loading.cc',
- 'cross/async_loading.h',
- 'cross/blacklist.cc',
- 'cross/config.h',
- 'cross/config_common.cc',
- 'cross/download_stream.h',
- 'cross/main.cc',
- 'cross/main.h',
- 'cross/main_thread_task_poster.cc',
- 'cross/main_thread_task_poster.h',
- 'cross/marshaling_utils.h',
- 'cross/np_v8_bridge.cc',
- 'cross/np_v8_bridge.h',
- 'cross/out_of_memory.cc',
- 'cross/out_of_memory.h',
- 'cross/plugin_logging.h',
- 'cross/plugin_main.h',
- 'cross/stream_manager.cc',
- 'cross/stream_manager.h',
- 'cross/texture_static_glue.cc',
- 'cross/whitelist.cc',
- ],
- 'plugin_depends': [
- '../../<(jpegdir)/libjpeg.gyp:libjpeg',
- '../../<(pngdir)/libpng.gyp:libpng',
- '../../<(zlibdir)/zlib.gyp:zlib',
- '../../base/base.gyp:base',
- '../../skia/skia.gyp:skia',
- '../../v8/tools/gyp/v8.gyp:v8',
- '../core/core.gyp:o3dCore',
- '../core/core.gyp:o3dCorePlatform',
- '../import/archive.gyp:o3dArchive',
- '../utils/utils.gyp:o3dUtils',
- '../../native_client/src/shared/imc/imc.gyp:google_nacl_imc',
- 'idl/idl.gyp:o3dPluginIdl',
- ],
- # A comma-separated list of strings, each double-quoted.
- 'plugin_domain_whitelist%': '',
- },
- 'includes': [
- '../build/branding.gypi',
- '../build/common.gypi',
- '../build/version.gypi',
- ],
- 'target_defaults': {
- 'include_dirs': [
- '..',
- '../..',
- '../../<(gtestdir)',
- ],
- 'defines': [
- 'O3D_PLUGIN_DESCRIPTION="<!(python version_info.py --set_name="<(plugin_name)" --set_version="<(plugin_version)" --set_npapi_mimetype="<(plugin_npapi_mimetype)" --description)"',
- 'O3D_PLUGIN_NPAPI_FILENAME="<(plugin_npapi_filename)"',
- 'O3D_PLUGIN_NPAPI_MIMETYPE="<(plugin_npapi_mimetype)"',
- 'O3D_PLUGIN_NAME="<(plugin_name)"',
- 'O3D_PLUGIN_VERSION="<(plugin_version)"',
- 'O3D_PLUGIN_INSTALLDIR_CSIDL=<(plugin_installdir_csidl)',
- 'O3D_PLUGIN_VENDOR_DIRECTORY="<(plugin_vendor_directory)"',
- 'O3D_PLUGIN_PRODUCT_DIRECTORY="<(plugin_product_directory)"',
- ],
- 'conditions': [
- # The funky quoting here is so that GYP doesn't shoot itself in the foot
- # when expanding a quoted variable which itself contains quotes.
- ["""'<(plugin_domain_whitelist)' != ''""",
- {
- 'defines': [
- 'O3D_PLUGIN_DOMAIN_WHITELIST=<(plugin_domain_whitelist)',
- ],
- },
- ],
- ],
- },
- 'targets': [
- {
- # This is the shared library version of the plugin.
- 'variables': {
- # Default values. Can be overridden with GYP_DEFINES for ease of
- # repackaging.
- 'plugin_rpath%' : '/opt/google/o3d/lib', # empty => none
- 'plugin_env_vars_file%' : '/opt/google/o3d/envvars', # empty => none
- 'conditions' : [
- ['renderer == "gl"',
- {
- 'as_needed_ldflags': [
- # The Cg libs use three other libraries without linking to them,
- # which breaks --as-needed, so we have to specify them here before
- # the --as-needed flag.
- '-lGL', # Used by libCgGL
- '-lpthread', # Used by libCg
- '-lm', # Used by libCg
- # GYP dumps all static and shared libraries into one archive group
- # on the command line in arbitrary order, which breaks
- # --as-needed, so we have to specify the out-of-order ones before
- # the --as-needed flag.
- '-lCgGL',
- '-ldl', # Used by breakpad
- '-lrt',
- ]
- }, {
- 'as_needed_ldflags': []
- }
- ],
- ]
- },
- 'target_name': '<(plugin_npapi_filename)',
- 'type': 'loadable_module',
- 'dependencies': [
- '<@(plugin_depends)',
- 'idl/idl.gyp:o3dNpnApi',
- ],
- 'sources': [
- '<@(plugin_sources)',
- ],
- 'conditions' : [
- ['OS != "linux"',
- {
- 'dependencies': [
- '../statsreport/statsreport.gyp:o3dStatsReport',
- 'add_version',
- 'o3dPluginLogging',
- ],
- },
- ],
- ['renderer == "gl"',
- {
- 'dependencies': [
- '../build/libs.gyp:gl_libs',
- '../build/libs.gyp:cg_libs',
- ],
- },
- ],
- ['renderer == "gles2"',
- {
- 'dependencies': [
- '../build/libs.gyp:gles2_libs',
- ],
- },
- ],
- ['OS == "mac"',
- {
- 'mac_bundle': 1,
- 'product_extension': 'plugin',
- 'conditions': [
- ['"<(plugin_npapi_filename)" == "npo3dautoplugin"',
- {
- # The unbranded Mac plugin's name is a special case.
- 'product_name': 'O3D',
- },
- {
- 'product_name': '<(plugin_npapi_filename)',
- },
- ],
- ],
- 'dependencies': [
- '../../breakpad/breakpad.gyp:breakpad',
- ],
- 'xcode_settings': {
- 'INFOPLIST_FILE': '<(SHARED_INTERMEDIATE_DIR)/plugin/Info.plist',
- },
- 'mac_bundle_resources': [
- 'mac/Resources/English.lproj',
- ],
- 'sources': [
- 'mac/config_mac.mm',
- 'mac/fullscreen_window_mac.h',
- 'mac/fullscreen_window_mac.mm',
- 'mac/o3d_layer.mm',
- 'mac/o3d_plugin.r',
- 'mac/overlay_window_mac.h',
- 'mac/overlay_window_mac.mm',
- 'mac/plugin_logging-mac.mm',
- 'mac/plugin_mac.h',
- 'mac/plugin_mac.mm',
- 'mac/graphics_utils_mac.mm',
- 'mac/main_mac.mm',
- ],
- 'mac_framework_dirs': [
- '../../<(cgdir)',
- ],
- 'include_dirs': [
- '../../breakpad/src/client/mac/Framework',
- ],
- 'defines': [
- 'XP_MACOSX=1',
- ],
- 'link_settings': {
- 'libraries': [
- '$(SDKROOT)/System/Library/Frameworks/QuartzCore.framework',
- '$(SDKROOT)/System/Library/Frameworks/Cocoa.framework',
- '$(SDKROOT)/System/Library/Frameworks/Carbon.framework',
- '$(SDKROOT)/System/Library/Frameworks/AGL.framework',
- '$(SDKROOT)/System/Library/Frameworks/Foundation.framework',
- '$(SDKROOT)/System/Library/Frameworks/IOKit.framework',
- '$(SDKROOT)/System/Library/Frameworks/OpenGL.framework',
- '$(SDKROOT)/System/Library/Frameworks/QuickTime.framework',
- 'libbreakpad.a',
- 'libbreakpad_utilities.a',
- '../../<(glewdir)/lib/libMacStaticGLEW.a',
- ],
- },
- 'postbuilds': [
- {
- 'variables': {
- # Define install_name in a variable ending in _path
- # so that gyp understands it's a path and performs proper
- # relativization during dict merging.
- 'install_name_path': 'mac/plugin_fix_install_names.sh',
- },
- 'postbuild_name': 'Fix Framework Paths',
- 'action': ['<(install_name_path)'],
- },
- {
- 'variables': {
- # Define copy_frameworks in a variable ending in _path
- # so that gyp understands it's a path and performs proper
- # relativization during dict merging.
- 'copy_frameworks_path': 'mac/plugin_copy_frameworks.sh',
- },
- 'postbuild_name': 'Copy Frameworks',
- 'conditions': [
- ['"<(plugin_npapi_filename)" == "npo3dautoplugin"',
- {
- # The unbranded Mac plugin's name is a special case.
- 'action': ['<(copy_frameworks_path)', 'O3D'],
- },
- {
- 'action': ['<(copy_frameworks_path)',
- '<(plugin_npapi_filename)'],
- },
- ],
- ],
- },
- {
- 'postbuild_name': 'Process Resource File',
- 'action': ['python',
- 'version_info.py',
- '--set_name=<(plugin_name)',
- '--set_version=<(plugin_version)',
- '--set_npapi_mimetype=<(plugin_npapi_mimetype)',
- 'mac/o3d_plugin.r',
- '${BUILT_PRODUCTS_DIR}/O3D.r',
- ],
- },
- {
- 'postbuild_name': 'Compile Resource File',
- 'conditions': [
- ['"<(plugin_npapi_filename)" == "npo3dautoplugin"',
- {
- # The unbranded Mac plugin's name is a special case.
- 'action': ['/usr/bin/Rez',
- '-useDF',
- '-o',
- '${BUILT_PRODUCTS_DIR}/O3D.plugin/Contents/Resources/O3D.rsrc',
- '${BUILT_PRODUCTS_DIR}/O3D.r',
- ],
- },
- {
- 'action': ['/usr/bin/Rez',
- '-useDF',
- '-o',
- '${BUILT_PRODUCTS_DIR}/<(plugin_npapi_filename).plugin/Contents/Resources/<(plugin_npapi_filename).rsrc',
- '${BUILT_PRODUCTS_DIR}/O3D.r',
- ],
- },
- ],
- ],
- },
- ],
- },
- ],
- ['OS == "linux"',
- {
- 'dependencies': [
- '../../breakpad/breakpad.gyp:breakpad_client',
- '../breakpad/breakpad.gyp:o3dBreakpad',
- ],
- 'sources': [
- 'linux/config.cc',
- 'linux/envvars.cc',
- 'linux/main_linux.cc',
- ],
- 'ldflags': [
- '-Wl,-znodelete',
- '-Wl,--gc-sections',
- '<!@(pkg-config --libs-only-L xt)',
- '<(as_needed_ldflags)',
- # Directs the linker to only generate dependencies on libraries
- # that we actually use. Must come last.
- '-Wl,--as-needed',
- ],
- 'libraries': [
- '<!@(pkg-config --libs-only-l xt)',
- ],
- 'conditions' : [
- ['plugin_rpath != ""',
- {
- 'ldflags': [
- '-Wl,-rpath', '-Wl,<(plugin_rpath)',
- ],
- },
- ],
- ['plugin_env_vars_file != ""',
- {
- 'defines': [
- 'O3D_PLUGIN_ENV_VARS_FILE="<(plugin_env_vars_file)"',
- ],
- },
- ],
- ],
- },
- ],
- ['OS == "win"',
- {
- 'dependencies': [
- '../breakpad/breakpad.gyp:o3dBreakpad',
- ],
- 'include_dirs': [
- # So that o3dPlugin.rc can find resource.h.
- 'win',
- ],
- 'sources': [
- 'win/config.cc',
- 'win/logger_main.cc',
- 'win/main_win.cc',
- '<(SHARED_INTERMEDIATE_DIR)/plugin/o3dPlugin.def',
- '<(SHARED_INTERMEDIATE_DIR)/plugin/o3dPlugin.rc',
- 'win/plugin_logging-win32.cc',
- 'win/resource.h',
- 'win/update_lock.cc',
- 'win/update_lock.h',
- ],
- 'link_settings': {
- 'libraries': [
- '-lrpcrt4.lib',
- ],
- },
- },
- ],
- ['OS == "win" and renderer == "d3d9"',
- {
- 'link_settings': {
- 'libraries': [
- '"$(DXSDK_DIR)/Lib/x86/d3dx9.lib"',
- '-ld3d9.lib',
- '"$(DXSDK_DIR)/Lib/x86/DxErr.lib"',
- ],
- },
- },
- ],
- ],
- },
- ],
- 'conditions': [
- ['o3d_in_chrome == "True"',
- {
- # Only use the "static_library" plugin target if we're
- # building in a chrome tree, since we don't need it in an O3D
- # tree.
- 'targets': [
- {
- 'variables': {
- # By default the built-in Chrome version does not read an env
- # vars file, but this can be overridden by giving a different
- # value for this.
- 'plugin_env_vars_file%' : '',
- },
- 'target_name': 'o3dPlugin',
- 'type': 'static_library',
- 'dependencies': [
- '<@(plugin_depends)',
- ],
- 'sources': [
- '<@(plugin_sources)',
- ],
- 'defines':['O3D_INTERNAL_PLUGIN=1'],
- 'conditions' : [
- ['OS != "linux"',
- {
- 'dependencies': [
- '../statsreport/statsreport.gyp:o3dStatsReport',
- 'add_version',
- 'o3dPluginLogging',
- ],
- },
- ],
- ['renderer == "gl"',
- {
- 'dependencies': [
- '../build/libs.gyp:gl_libs',
- '../build/libs.gyp:cg_libs',
- ],
- },
- ],
- ['renderer == "gles2"',
- {
- 'dependencies': [
- '../build/libs.gyp:gles2_libs',
- ],
- },
- ],
- ['OS == "mac"',
- {
- 'mac_bundle': 1,
- 'product_extension': 'plugin',
- 'conditions': [
- ['"<(plugin_npapi_filename)" == "npo3dautoplugin"',
- {
- # The unbranded Mac plugin's name is a special case.
- 'product_name': 'O3D',
- },
- {
- 'product_name': '<(plugin_npapi_filename)',
- },
- ],
- ],
- 'dependencies': [
- '../../breakpad/breakpad.gyp:breakpad',
- ],
- 'xcode_settings': {
- 'INFOPLIST_FILE': '<(SHARED_INTERMEDIATE_DIR)/plugin/Info.plist',
- },
- 'mac_bundle_resources': [
- 'mac/Resources/English.lproj',
- ],
- 'sources': [
- 'mac/config_mac.mm',
- 'mac/main_mac.mm',
- 'mac/o3d_plugin.r',
- 'mac/plugin_logging-mac.mm',
- 'mac/plugin_mac.h',
- 'mac/plugin_mac.mm',
- 'mac/graphics_utils_mac.mm',
- ],
- 'mac_framework_dirs': [
- '../../<(cgdir)',
- ],
- 'include_dirs': [
- '../../breakpad/src/client/mac/Framework',
- ],
- 'defines': [
- 'XP_MACOSX=1',
- ],
- 'link_settings': {
- 'libraries': [
- '$(SDKROOT)/System/Library/Frameworks/Cocoa.framework',
- '$(SDKROOT)/System/Library/Frameworks/Carbon.framework',
- '$(SDKROOT)/System/Library/Frameworks/AGL.framework',
- '$(SDKROOT)/System/Library/Frameworks/Foundation.framework',
- '$(SDKROOT)/System/Library/Frameworks/IOKit.framework',
- '$(SDKROOT)/System/Library/Frameworks/OpenGL.framework',
- '$(SDKROOT)/System/Library/Frameworks/QuickTime.framework',
- 'libbreakpad.a',
- 'libbreakpad_utilities.a',
- '../../<(glewdir)/lib/libMacStaticGLEW.a',
- ],
- },
- },
- ],
- ['OS == "linux"',
- {
- 'sources': [
- 'linux/main_linux.cc',
- 'linux/config.cc',
- 'linux/envvars.cc',
- ],
- 'link_settings': {
- 'libraries': [
- '-lGL',
- ],
- },
- # On Linux, shared library targets aren't copied to the
- # product dir automatically. Filed GYP issue #74 to address this.
- # TODO(gspencer): Remove when issue #74 is resolved.
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)',
- 'files': [
- '<(PRODUCT_DIR)/obj/o3d/plugin/<(SHARED_LIB_PREFIX)<(_target_name)<(SHARED_LIB_SUFFIX)',
- ],
- },
- ],
- 'conditions' : [
- ['plugin_env_vars_file != ""',
- {
- 'defines': [
- 'O3D_PLUGIN_ENV_VARS_FILE="<(plugin_env_vars_file)"',
- ],
- },
- ],
- ],
- },
- ],
- ['OS == "win"',
- {
- 'dependencies': [
- '../breakpad/breakpad.gyp:o3dBreakpad',
- ],
- 'include_dirs': [
- # So that o3dPlugin.rc can find resource.h.
- 'win',
- ],
- 'sources': [
- 'win/config.cc',
- 'win/logger_main.cc',
- 'win/main_win.cc',
- '<(SHARED_INTERMEDIATE_DIR)/plugin/o3dPlugin.def',
- '<(SHARED_INTERMEDIATE_DIR)/plugin/o3dPlugin.rc',
- 'win/plugin_logging-win32.cc',
- 'win/resource.h',
- 'win/update_lock.cc',
- 'win/update_lock.h',
- ],
- 'link_settings': {
- 'libraries': [
- '-lrpcrt4.lib',
- ],
- },
- },
- ],
- ['OS == "win" and renderer == "d3d9"',
- {
- 'link_settings': {
- 'libraries': [
- '"$(DXSDK_DIR)/Lib/x86/d3dx9.lib"',
- '-ld3d9.lib',
- ],
- },
- },
- ],
- ['OS == "win" and renderer == "d3d9"',
- {
- 'link_settings': {
- 'libraries': [
- '"$(DXSDK_DIR)/Lib/x86/DxErr.lib"',
- ],
- },
- },
- ],
- ],
- },
- ],
- },
- ],
- ['OS != "linux"',
- {
- 'targets': [
- {
- 'target_name': 'o3dPluginLogging',
- 'type': 'static_library',
- 'conditions': [
- ['OS=="win"',
- {
- 'sources': [
- 'win/plugin_metrics-win32.cc',
- 'win/plugin_logging-win32.cc',
- ],
- },
- ],
- ['OS=="mac"',
- {
- 'sources': [
- 'mac/plugin_metrics-mac.cc',
- 'mac/plugin_logging-mac.mm',
- ],
- },
- ],
- ],
- },
- {
- 'target_name': 'add_version',
- 'type': 'none',
- 'actions': [
- {
- 'action_name': 'add_version_rc',
- 'inputs': [
- 'version_info.py',
- ],
- 'conditions': [
- ['OS=="win"',
- {
- 'inputs': [
- 'win/o3dPlugin.rc_template',
- ],
- 'outputs': [
- '<(SHARED_INTERMEDIATE_DIR)/plugin/o3dPlugin.rc'
- ],
- 'action': ['python',
- 'version_info.py',
- '--set_name=<(plugin_name)',
- '--set_version=<(plugin_version)',
- '--set_npapi_filename=<(plugin_npapi_filename)',
- '--set_npapi_mimetype=<(plugin_npapi_mimetype)',
- 'win/o3dPlugin.rc_template',
- '<(SHARED_INTERMEDIATE_DIR)/plugin/o3dPlugin.rc'],
- },
- ],
- ['OS=="mac"',
- {
- 'inputs': [
- 'mac/Info.plist',
- ],
- 'outputs': [
- '<(SHARED_INTERMEDIATE_DIR)/plugin/Info.plist',
- ],
- 'variables': {
- # Ridiculously, it is impossible to define a GYP
- # variable whose value depends on the choice of build
- # configuration, so to get this to be the staging URL
- # when building Debug we define it as a shell fragment
- # that uses command substitution to evaluate to
- # different things based on the Xcode "CONFIGURATION"
- # environment variable. We further have to use ``
- # instead of $() because GYP/Xcode mangles $().
- 'o3d_plugin_breakpad_url':
- '`if [ "$CONFIGURATION" = Debug ]; then '
- 'echo https://clients2.google.com/cr/staging_report; '
- 'else '
- 'echo https://clients2.google.com/cr/report; '
- 'fi`'
- },
- 'conditions': [
- ['"<(plugin_npapi_filename)" == "npo3dautoplugin"',
- {
- # The unbranded Mac plugin's name is a special case.
- 'action': ['sh',
- '-c',
- 'python '
- 'version_info.py '
- '--set_name="<(plugin_name)" '
- '--set_version="<(plugin_version)" '
- '--set_npapi_filename="O3D" '
- '--set_npapi_mimetype="<(plugin_npapi_mimetype)" '
- '--set_o3d_plugin_breakpad_url="<(o3d_plugin_breakpad_url)" '
- '"mac/Info.plist" '
- '"<(SHARED_INTERMEDIATE_DIR)/plugin/Info.plist"',
- ],
- },
- {
- 'action': ['sh',
- '-c',
- 'python '
- 'version_info.py '
- '--set_name="<(plugin_name)" '
- '--set_version="<(plugin_version)" '
- '--set_npapi_filename="<(plugin_npapi_filename)" '
- '--set_npapi_mimetype="<(plugin_npapi_mimetype)" '
- '--set_o3d_plugin_breakpad_url="<(o3d_plugin_breakpad_url)" '
- '"mac/Info.plist" '
- '"<(SHARED_INTERMEDIATE_DIR)/plugin/Info.plist"',
- ],
- },
- ],
- ],
- },
- ],
- ],
- },
- ],
- 'conditions': [
- ['OS=="win"',
- {
- 'actions': [
- {
- 'action_name': 'add_version_def',
- 'inputs': [
- 'version_info.py',
- 'win/o3dPlugin.def_template',
- ],
- 'outputs': [
- '<(SHARED_INTERMEDIATE_DIR)/plugin/o3dPlugin.def',
- ],
- 'action': ['python',
- 'version_info.py',
- '--set_npapi_filename=<(plugin_npapi_filename)',
- 'win/o3dPlugin.def_template',
- '<(SHARED_INTERMEDIATE_DIR)/plugin/o3dPlugin.def'],
- },
- ],
- },
- ],
- ],
- },
- ],
- },
- ],
- ['OS=="win"',
- {
- 'targets': [
- {
- 'target_name': 'gen_host_control_rgs',
- 'type': 'none',
- 'actions': [
- {
- 'action_name': 'gen_host_control_rgs',
- 'inputs': [
- 'version_info.py',
- 'npapi_host_control/win/host_control.rgs_template',
- ],
- 'outputs': [
- '<(SHARED_INTERMEDIATE_DIR)/plugin/host_control.rgs',
- ],
- 'action': ['python',
- 'version_info.py',
- '--set_version=<(plugin_version)',
- '--set_activex_hostcontrol_clsid=' +
- '<(plugin_activex_hostcontrol_clsid)',
- '--set_activex_typelib_clsid=<(plugin_activex_typelib_clsid)',
- '--set_activex_hostcontrol_name=' +
- '<(plugin_activex_hostcontrol_name)',
- '--set_activex_typelib_name=<(plugin_activex_typelib_name)',
- 'npapi_host_control/win/host_control.rgs_template',
- '<(SHARED_INTERMEDIATE_DIR)/plugin/host_control.rgs',
- ],
- },
- ],
- },
- {
- 'target_name': 'gen_npapi_host_control_idl',
- 'type': 'none',
- 'actions': [
- {
- 'action_name': 'gen_npapi_host_control_idl',
- 'inputs': [
- 'version_info.py',
- 'npapi_host_control/win/npapi_host_control.idl_template',
- ],
- 'outputs': [
- '<(SHARED_INTERMEDIATE_DIR)/plugin/npapi_host_control.idl',
- ],
- 'action': ['python',
- 'version_info.py',
- '--set_version=<(plugin_version)',
- '--set_activex_hostcontrol_clsid=' +
- '<(plugin_activex_hostcontrol_clsid)',
- '--set_activex_typelib_clsid=<(plugin_activex_typelib_clsid)',
- '--set_activex_hostcontrol_name=' +
- '<(plugin_activex_hostcontrol_name)',
- '--set_activex_typelib_name=<(plugin_activex_typelib_name)',
- 'npapi_host_control/win/npapi_host_control.idl_template',
- '<(SHARED_INTERMEDIATE_DIR)/plugin/npapi_host_control.idl',
- ],
- },
- ],
- },
- {
- 'target_name': 'o3d_host',
- 'type': 'shared_library',
- 'dependencies': [
- 'gen_host_control_rgs',
- 'gen_npapi_host_control_idl',
- ],
- 'include_dirs': [
- '<(INTERMEDIATE_DIR)',
- # So that npapi_host_control.rc can find host_control.rgs.
- '<(SHARED_INTERMEDIATE_DIR)/plugin',
- ],
- 'sources': [
- '<(INTERMEDIATE_DIR)/npapi_host_control_i.c',
- 'npapi_host_control/win/dispatch_proxy.cc',
- 'npapi_host_control/win/dispatch_proxy.h',
- 'npapi_host_control/win/host_control.cc',
- 'npapi_host_control/win/host_control.h',
- 'npapi_host_control/win/module.h',
- 'npapi_host_control/win/np_browser_proxy.cc',
- 'npapi_host_control/win/np_browser_proxy.h',
- 'npapi_host_control/win/np_object_proxy.cc',
- 'npapi_host_control/win/np_object_proxy.h',
- 'npapi_host_control/win/np_plugin_proxy.cc',
- 'npapi_host_control/win/np_plugin_proxy.h',
- 'npapi_host_control/win/npapi_host_control.cc',
- '<(SHARED_INTERMEDIATE_DIR)/plugin/npapi_host_control.idl',
- 'npapi_host_control/win/npapi_host_control.rc',
- 'npapi_host_control/win/precompile.h',
- 'npapi_host_control/win/resource.h',
- 'npapi_host_control/win/stream_operation.cc',
- 'npapi_host_control/win/stream_operation.h',
- 'npapi_host_control/win/variant_utils.cc',
- 'npapi_host_control/win/variant_utils.h',
- ],
- 'link_settings': {
- 'libraries': [
- '-lwininet.lib',
- ],
- },
- 'defines': [
- '_MIDL_USE_GUIDDEF_',
- 'DLL_NPAPI_HOST_CONTROL_EXPORT',
- ],
- 'msvs_settings': {
- 'VCLinkerTool': {
- 'ModuleDefinitionFile':
- 'npapi_host_control/win/npapi_host_control.def'
- },
- 'VCCLCompilerTool': {
- 'ForcedIncludeFiles':
- 'plugin/npapi_host_control/win/precompile.h',
- 'CompileAs': '2', # Build all the files as C++, since
- # ATL requires that.
- },
- },
- 'msvs_configuration_attributes': {
- 'UseOfATL': '1', # 1 = static link to ATL, 2 = dynamic link
- },
- },
- ],
- },
- ],
- # If compiling with re-branding, we alias the branded NPAPI target name to
- # the unbranded one so that targets depending on it can just refer to it
- # by a constant name.
- ['"<(plugin_npapi_filename)" != "npo3dautoplugin"',
- {
- 'targets': [
- {
- 'target_name': 'npo3dautoplugin',
- 'type': 'none',
- 'dependencies': [
- '<(plugin_npapi_filename)',
- ],
- },
- ],
- },
- ],
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/plugin/version_info.py b/o3d/plugin/version_info.py
deleted file mode 100644
index 0777e03..0000000
--- a/o3d/plugin/version_info.py
+++ /dev/null
@@ -1,138 +0,0 @@
-#!/usr/bin/python2.4
-# Copyright 2009 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# This script does substitution on a list of files for
-# version-specific information relating to the plugin.
-
-import os.path
-import re
-import sys
-
-script_dir = os.path.join(os.path.dirname(sys.argv[0]))
-gflags_dir = os.path.normpath(
- os.path.join(script_dir, '..', 'third_party', 'gflags', 'python'))
-sys.path.append(gflags_dir)
-
-import gflags
-
-FLAGS = gflags.FLAGS
-gflags.DEFINE_boolean('description', False,
- 'Print out the plugin description and exit.')
-
-gflags.DEFINE_boolean('commaversion', False,
- 'Print out the plugin version with commas and exit.')
-
-gflags.DEFINE_string('set_name', '',
- 'Sets the plugin name to use.')
-
-gflags.DEFINE_string('set_version', '',
- 'Sets the plugin version to use.')
-
-gflags.DEFINE_string('set_npapi_filename', '',
- 'Sets the plugin NPAPI filename to use.')
-
-gflags.DEFINE_string('set_npapi_mimetype', '',
- 'Sets the plugin NPAPI mimetype to use.')
-
-gflags.DEFINE_string('set_activex_hostcontrol_clsid', '',
- 'Sets the ActiveX HostControl\'s CLSID to use.')
-
-gflags.DEFINE_string('set_activex_typelib_clsid', '',
- 'Sets the ActiveX TypeLib\'s CLSID to use.')
-
-gflags.DEFINE_string('set_activex_hostcontrol_name', '',
- 'Sets the ActiveX HostControl\'s name to use.')
-
-gflags.DEFINE_string('set_activex_typelib_name', '',
- 'Sets the ActiveX TypeLib\'s name to use.')
-
-gflags.DEFINE_string('set_o3d_plugin_breakpad_url', '',
- 'Sets the o3d Crash Dump Upload URL to use.')
-
-def DoReplace(in_filename, out_filename, replacements):
- '''Replace the version placeholders in the given filename with the
- replacements.'''
- if not os.path.exists(in_filename):
- raise Exception(r'''Input template file %s doesn't exist.''' % in_filename)
- input_file = open(in_filename, 'r')
- input = input_file.read()
- input_file.close()
- for (source, target) in replacements:
- input = re.sub(source, target, input)
-
- output_file = open(out_filename, 'wb')
- output_file.write(input)
- output_file.close()
-
-def main(argv):
- try:
- files = FLAGS(argv) # Parse flags
- except gflags.FlagsError, e:
- print '%s.\nUsage: %s [<options>] [<input_file> <output_file>]\n%s' % \
- (e, sys.argv[0], FLAGS)
- sys.exit(1)
-
- # Strip off argv[0]
- files = files[1:]
-
- # This name is used by Javascript to find the plugin therefore it must
- # not change. If you change this you must change the name in
- # samples/o3djs/util.js but be aware, changing the name
- # will break all apps that use o3d on the web.
- O3D_PLUGIN_NAME = FLAGS.set_name
- O3D_PLUGIN_VERSION = FLAGS.set_version
- O3D_PLUGIN_VERSION_COMMAS = O3D_PLUGIN_VERSION.replace('.', ',')
- O3D_PLUGIN_DESCRIPTION = '%s version:%s' % (O3D_PLUGIN_NAME,
- O3D_PLUGIN_VERSION)
- O3D_PLUGIN_NPAPI_FILENAME = FLAGS.set_npapi_filename
- O3D_PLUGIN_NPAPI_MIMETYPE = FLAGS.set_npapi_mimetype
- O3D_PLUGIN_ACTIVEX_HOSTCONTROL_CLSID = FLAGS.set_activex_hostcontrol_clsid
- O3D_PLUGIN_ACTIVEX_TYPELIB_CLSID = FLAGS.set_activex_typelib_clsid
- O3D_PLUGIN_ACTIVEX_HOSTCONTROL_NAME = FLAGS.set_activex_hostcontrol_name
- O3D_PLUGIN_ACTIVEX_TYPELIB_NAME = FLAGS.set_activex_typelib_name
- O3D_PLUGIN_BREAKPAD_URL = FLAGS.set_o3d_plugin_breakpad_url
-
- if FLAGS.description:
- print '%s' % O3D_PLUGIN_DESCRIPTION
- sys.exit(0)
-
- if FLAGS.commaversion:
- print '%s' % O3D_PLUGIN_VERSION_COMMAS
- sys.exit(0)
-
- plugin_replace_strings = [
- ('@@@PluginName@@@', O3D_PLUGIN_NAME),
- ('@@@ProductVersionCommas@@@', O3D_PLUGIN_VERSION_COMMAS),
- ('@@@ProductVersion@@@', O3D_PLUGIN_VERSION),
- ('@@@PluginDescription@@@', O3D_PLUGIN_DESCRIPTION),
- ('@@@PluginNpapiFilename@@@', O3D_PLUGIN_NPAPI_FILENAME),
- ('@@@PluginNpapiMimeType@@@', O3D_PLUGIN_NPAPI_MIMETYPE),
- ('@@@PluginActiveXHostControlClsid@@@',
- O3D_PLUGIN_ACTIVEX_HOSTCONTROL_CLSID),
- ('@@@PluginActiveXTypeLibClsid@@@', O3D_PLUGIN_ACTIVEX_TYPELIB_CLSID),
- ('@@@PluginActiveXHostControlName@@@',
- O3D_PLUGIN_ACTIVEX_HOSTCONTROL_NAME),
- ('@@@PluginActiveXTypeLibName@@@', O3D_PLUGIN_ACTIVEX_TYPELIB_NAME),
- ('@@@PluginBreakpadURL@@@', O3D_PLUGIN_BREAKPAD_URL),
- ]
-
- if len(files) == 2:
- DoReplace(files[0], files[1], plugin_replace_strings)
- elif len(files) > 0:
- raise Exception(r'You must supply and input and output filename for '
- r'replacement.')
-
-if __name__ == '__main__':
- main(sys.argv)
diff --git a/o3d/plugin/win/config.cc b/o3d/plugin/win/config.cc
deleted file mode 100644
index b1d28fe..0000000
--- a/o3d/plugin/win/config.cc
+++ /dev/null
@@ -1,241 +0,0 @@
-/*
- * Copyright 2011, 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 code to check the hardware and software configuration of
-// the client machine:
-// - User agent (browser)
-// - Windows version
-// - GPU vendor
-
-// TODO: Waiting on posix updates to be able to include this in order
-// to parse the useragent string for browser version.
-// #include <regex.h>
-#include <shlobj.h>
-#include <shlwapi.h>
-#include <tchar.h>
-#include <windows.h>
-#ifdef RENDERER_D3D9
-#include <d3d9.h>
-#endif
-
-#include <string>
-#include <iostream>
-#include <fstream>
-
-#include "base/logging.h"
-#include "plugin/cross/config.h"
-#include "plugin/cross/plugin_metrics.h"
-#include "core/cross/install_check.h"
-#include "third_party/nixysa/static_glue/npapi/common.h"
-
-namespace o3d {
-
-// Check Windows version.
-bool CheckOSVersion(NPP npp) {
- OSVERSIONINFOEX version = {sizeof(OSVERSIONINFOEX)}; // NOLINT
- GetVersionEx(reinterpret_cast<OSVERSIONINFO *>(&version));
- if (version.dwMajorVersion == 5 && version.dwMinorVersion == 1) {
- // NT 5.1 = Windows XP
- if (version.wServicePackMajor < 2) {
- // TODO: internationalize messages.
- std::string error = std::string("Windows XP Service Pack 2 is required.");
- if (!AskUser(npp, error)) return false;
- }
- } else if (version.dwMajorVersion > 5 ||
- (version.dwMajorVersion == 5 && version.dwMinorVersion >= 2)) {
- // 6.0 is Vista or Server 2008; it's now worth a try.
- } else {
- std::string error = std::string("Unsupported Windows version.");
- if (!AskUser(npp, error)) return false;
- }
- return true;
-}
-
-// Checks user agent string. We only allow Firefox, Chrome, Safari and IE.
-bool CheckUserAgent(NPP npp, const std::string &user_agent) {
- if (user_agent.find("Firefox") == user_agent.npos &&
- user_agent.find("Chrome") == user_agent.npos &&
- user_agent.find("MSIE") == user_agent.npos &&
- user_agent.find("Safari") == user_agent.npos &&
- user_agent.find("Opera") == user_agent.npos) {
- std::string error = std::string("Unsupported user agent: ") + user_agent;
- return AskUser(npp, error);
- }
- return true;
-}
-
-bool OpenDriverBlacklistFile(std::ifstream *input_file) {
- CHECK(input_file);
- CHECK(!input_file->is_open());
-
- // Determine the full path.
- // It will look something like:
- // "c:\Documents and Settings\username\Application Data\Google\O3D\
- // driver_blacklist.txt"
-
- TCHAR app_data_path[MAX_PATH];
- HRESULT result = SHGetFolderPath(
- NULL,
- O3D_PLUGIN_INSTALLDIR_CSIDL,
- NULL,
- 0,
- app_data_path);
-
- if (result != 0) {
- return false;
- }
-
- PathAppend(app_data_path,
- _T(O3D_PLUGIN_VENDOR_DIRECTORY) _T("\\")
- _T(O3D_PLUGIN_PRODUCT_DIRECTORY) _T("\\driver_blacklist.txt"));
- if (!PathFileExists(app_data_path)) {
- return false;
- }
- input_file->open(app_data_path, std::ifstream::in);
- return input_file->good();
-}
-
-bool GetUserConfigMetrics() {
- // Check Windows version.
- o3d::metric_system_type = o3d::SYSTEM_NAME_WIN;
-
- OSVERSIONINFOEX version = {sizeof(OSVERSIONINFOEX)}; // NOLINT
- GetVersionEx(reinterpret_cast<OSVERSIONINFO *>(&version));
- o3d::metric_windows_major_version = version.dwMajorVersion;
- o3d::metric_windows_minor_version = version.dwMinorVersion;
- o3d::metric_windows_sp_major_version = version.wServicePackMajor;
- o3d::metric_windows_sp_minor_version = version.wServicePackMinor;
-
- // Check the device capabilities.
-#ifdef RENDERER_D3D9
- // Check GPU vendor using D3D.
- IDirect3D9 *d3d = Direct3DCreate9(D3D_SDK_VERSION);
- if (!d3d) {
- o3d::metric_direct3d_available.Set(false);
- DLOG(ERROR) << "Direct3D9 is unavailable";
- return false;
- }
- o3d::metric_direct3d_available.Set(true);
- D3DADAPTER_IDENTIFIER9 identifier;
- HRESULT hr = d3d->GetAdapterIdentifier(D3DADAPTER_DEFAULT, 0, &identifier);
- D3DCAPS9 d3d_caps;
- HRESULT caps_result = d3d->GetDeviceCaps(D3DADAPTER_DEFAULT,
- D3DDEVTYPE_HAL,
- &d3d_caps);
- // Get GPU device information
- if (hr != D3D_OK) {
- DLOG(ERROR) << "Unable to get device ID";
- return false;
- }
- o3d::metric_gpu_vendor_id = identifier.VendorId;
- o3d::metric_gpu_device_id = identifier.DeviceId;
- o3d::metric_gpu_driver_major_version = identifier.DriverVersion.LowPart;
- o3d::metric_gpu_driver_minor_version = identifier.DriverVersion.HighPart;
-
- // Need to release after we get the vram size
- d3d->Release();
-
- // Get shader versions
- DWORD pixel_shader = d3d_caps.PixelShaderVersion;
- o3d::metric_pixel_shader_main_version =
- D3DSHADER_VERSION_MAJOR(pixel_shader);
- o3d::metric_pixel_shader_sub_version =
- D3DSHADER_VERSION_MINOR(pixel_shader);
- DWORD vertex_shader = d3d_caps.VertexShaderVersion;
- o3d::metric_vertex_shader_main_version =
- D3DSHADER_VERSION_MAJOR(vertex_shader);
- o3d::metric_vertex_shader_sub_version =
- D3DSHADER_VERSION_MINOR(vertex_shader);
-
- // Detemine if device can handle NPoT textures
- o3d::metric_POW2_texture_caps.Set(
- (d3d_caps.TextureCaps & D3DPTEXTURECAPS_POW2) != 0);
- o3d::metric_NONPOW2CONDITIONAL_texture_caps.Set(
- (d3d_caps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) != 0);
-
- o3d::metric_d3d_devcaps = d3d_caps.DevCaps;
- o3d::metric_d3d_misccaps = d3d_caps.PrimitiveMiscCaps;
- o3d::metric_d3d_rastercaps = d3d_caps.RasterCaps;
- o3d::metric_d3d_zcmpcaps = d3d_caps.ZCmpCaps;
- o3d::metric_d3d_srcblendcaps = d3d_caps.SrcBlendCaps;
- o3d::metric_d3d_dstblendcaps = d3d_caps.DestBlendCaps;
- o3d::metric_d3d_alphacaps = d3d_caps.AlphaCmpCaps;
- o3d::metric_d3d_texcaps = d3d_caps.TextureCaps;
- o3d::metric_d3d_texfiltercaps = d3d_caps.TextureFilterCaps;
- o3d::metric_d3d_cubetexfiltercaps = d3d_caps.CubeTextureFilterCaps;
- o3d::metric_d3d_texaddrcaps = d3d_caps.TextureAddressCaps;
- o3d::metric_d3d_linecaps = d3d_caps.LineCaps;
- o3d::metric_d3d_stencilcaps = d3d_caps.StencilCaps;
- o3d::metric_d3d_texopcaps = d3d_caps.TextureOpCaps;
- o3d::metric_d3d_vs20caps = d3d_caps.VS20Caps.Caps;
- o3d::metric_d3d_vs20_dynflowctrldepth =
- d3d_caps.VS20Caps.DynamicFlowControlDepth;
- o3d::metric_d3d_vs20_numtemps = d3d_caps.VS20Caps.NumTemps;
- o3d::metric_d3d_vs20_staticflowctrldepth =
- d3d_caps.VS20Caps.StaticFlowControlDepth;
- o3d::metric_d3d_ps20caps = d3d_caps.PS20Caps.Caps;
- o3d::metric_d3d_ps20_dynflowctrldepth =
- d3d_caps.PS20Caps.DynamicFlowControlDepth;
- o3d::metric_d3d_ps20_numtemps = d3d_caps.PS20Caps.NumTemps;
- o3d::metric_d3d_ps20_staticflowctrldepth =
- d3d_caps.PS20Caps.StaticFlowControlDepth;
- o3d::metric_d3d_ps20_numinstrslots = d3d_caps.PS20Caps.NumInstructionSlots;
-#else
- o3d::metric_direct3d_available.Set(false);
-#endif
- return true;
-}
-
-bool GetUserAgentMetrics(NPP npp) {
- // Check User agent so we can get the browser
- // TODO: This is the best we could come up with for this in order to
- // go from browser to string.
- GLUE_PROFILE_START(npp, "uagent");
- std::string user_agent = NPN_UserAgent(npp);
- GLUE_PROFILE_STOP(npp, "uagent");
- // The Chrome user_agent string also contains Safari. Search for Chrome first.
- if (std::string::npos != user_agent.find("Chrome")) {
- o3d::metric_browser_type = o3d::BROWSER_NAME_CHROME;
- } else if (std::string::npos != user_agent.find("Safari")) {
- o3d::metric_browser_type = o3d::BROWSER_NAME_SAFARI;
- } else if (std::string::npos != user_agent.find("Opera")) {
- o3d::metric_browser_type = o3d::BROWSER_NAME_OPERA;
- } else if (std::string::npos != user_agent.find("Firefox")) {
- o3d::metric_browser_type = o3d::BROWSER_NAME_FIREFOX;
- } else if (std::string::npos != user_agent.find("MSIE")) {
- o3d::metric_browser_type = o3d::BROWSER_NAME_MSIE;
- } else {
- o3d::metric_browser_type = o3d::BROWSER_NAME_UNKNOWN;
- }
- return true;
-}
-} // namespace o3d
diff --git a/o3d/plugin/win/logger_main.cc b/o3d/plugin/win/logger_main.cc
deleted file mode 100644
index d41ca09..0000000
--- a/o3d/plugin/win/logger_main.cc
+++ /dev/null
@@ -1,58 +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 main function for a small program which calls
-// the logging code and initiate an upload of logs.
-
-#include <windows.h>
-#include <stdlib.h>
-#include <shlwapi.h>
-#include "plugin/cross/plugin_logging.h"
-#include "statsreport/metrics.h"
-
-//-----------------------------------------------------------------------------
-// Name: main()
-// Desc: The application's entry point
-//-----------------------------------------------------------------------------
-int main(int argc, wchar_t **argv) {
- printf("Starting stats logging.\n");
- HRESULT hr = CoInitialize(NULL);
- o3d::PluginLogging g_logger;
- stats_report::g_global_metrics.Initialize();
- if (!g_logger.ProcessMetrics(false, true, false)) {
- printf("Error with stats logging.'n");
- exit(1);
- }
- printf("Stats logging successful.\n");
- stats_report::g_global_metrics.Uninitialize();
- exit(0);
-}
diff --git a/o3d/plugin/win/main_win.cc b/o3d/plugin/win/main_win.cc
deleted file mode 100644
index efea1a5..0000000
--- a/o3d/plugin/win/main_win.cc
+++ /dev/null
@@ -1,956 +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 implements the platform specific parts of the plugin for
-// the Windows platform.
-
-#include "plugin/cross/main.h"
-
-#include <windows.h>
-#include <windowsx.h>
-#include <shellapi.h>
-
-#include "base/logging.h"
-#include "core/cross/display_mode.h"
-#include "core/cross/event.h"
-#include "core/win/display_window_win.h"
-#include "pixman-win32-tls.h"
-#include "v8/include/v8.h"
-#if !defined(O3D_INTERNAL_PLUGIN)
-#include "breakpad/win/exception_handler_win32.h"
-#endif
-#include "plugin/cross/o3d_glue.h"
-
-using glue::_o3d::PluginObject;
-using glue::StreamManager;
-using o3d::DisplayWindowWindows;
-using o3d::Event;
-
-namespace {
-// The instance handle of the O3D DLL.
-HINSTANCE g_module_instance;
-} // namespace anonymous
-
-#if !defined(O3D_INTERNAL_PLUGIN)
-// Used for breakpad crash handling
-static ExceptionManager *g_exception_manager = NULL;
-
-extern "C" BOOL WINAPI DllMain(HINSTANCE instance,
- DWORD reason,
- LPVOID reserved) {
- g_module_instance = instance;
-
- if (reason == DLL_PROCESS_DETACH) {
- // Teardown V8 when the plugin dll is unloaded.
- // NOTE: NP_Shutdown would have been a good place for this code but
- // unfortunately it looks like it gets called even when the dll
- // isn't really unloaded. This is a problem since after calling
- // V8::Dispose(), V8 cannot be initialized again.
- bool v8_disposed = v8::V8::Dispose();
- if (!v8_disposed)
- DLOG(ERROR) << "Failed to release V8 resources.";
- return true;
- }
- return true;
-}
-#endif // O3D_INTERNAL_PLUGIN
-
-namespace {
-const wchar_t* const kO3DWindowClassName = L"O3DWindowClass";
-
-void CleanupAllWindows(PluginObject *obj);
-
-static int HandleKeyboardEvent(PluginObject *obj,
- HWND hWnd,
- UINT Msg,
- WPARAM wParam,
- LPARAM lParam) {
- DCHECK(obj);
- DCHECK(obj->client());
- Event::Type type;
- // First figure out which kind of event to create, and do any event-specific
- // processing that can be done prior to creating it.
- switch (Msg) {
- case WM_KEYDOWN:
- case WM_SYSKEYDOWN:
- type = Event::TYPE_KEYDOWN;
- break;
- case WM_KEYUP:
- case WM_SYSKEYUP:
- type = Event::TYPE_KEYUP;
- break;
- case WM_CHAR:
- case WM_SYSCHAR:
- type = Event::TYPE_KEYPRESS;
- break;
- default:
- LOG(FATAL) << "Unknown keyboard event: " << Msg;
- }
- Event event(type);
- switch (Msg) {
- case WM_KEYDOWN:
- case WM_SYSKEYDOWN:
- case WM_KEYUP:
- case WM_SYSKEYUP:
- event.set_key_code(wParam);
- break;
- case WM_CHAR:
- case WM_SYSCHAR:
- event.set_char_code(wParam);
- break;
- default:
- LOG(FATAL) << "Unknown keyboard event: " << Msg;
- }
- // TODO: Try out TranslateAccelerator to see if that causes
- // accelerators to start working. They would then evade JavaScript handlers,
- // though, so perhaps we'd have to check to see if we want to handle them
- // first? That would require going around the event queue, at least
- // partially. OTOH I see hints in blog posts that only Firefox allows
- // handlers to suppress syskeys anyway, so maybe it's not that big a
- // deal...unless apps want to use those keys...and depending on what happens
- // in other browsers.
-
- unsigned char keyboard_state[256];
- if (!::GetKeyboardState(static_cast<PBYTE>(keyboard_state))) {
- LOG(ERROR) << "GetKeyboardState failed.";
- return 1;
- }
-
- int modifier_state = 0;
- if (keyboard_state[VK_CONTROL] & 0x80) {
- modifier_state |= Event::MODIFIER_CTRL;
- }
- if (keyboard_state[VK_SHIFT] & 0x80) {
- modifier_state |= Event::MODIFIER_SHIFT;
- }
- if (keyboard_state[VK_MENU] & 0x80) {
- modifier_state |= Event::MODIFIER_ALT;
- }
- event.set_modifier_state(modifier_state);
-
- if (event.type() == Event::TYPE_KEYDOWN &&
- (wParam == VK_ESCAPE ||
- (wParam == VK_F4 && (modifier_state & Event::MODIFIER_ALT)))) {
- obj->CancelFullscreenDisplay();
- }
-
- obj->client()->AddEventToQueue(event);
- return 0;
-}
-
-void HandleMouseEvent(PluginObject *obj,
- HWND hWnd,
- UINT Msg,
- WPARAM wParam,
- LPARAM lParam) {
- DCHECK(obj);
- DCHECK(obj->client());
- bool fake_dblclick = false;
- Event::Type type;
- int x = GET_X_LPARAM(lParam);
- int y = GET_Y_LPARAM(lParam);
- int screen_x, screen_y;
- bool in_plugin = false;
- {
- RECT rect;
- if (!::GetWindowRect(hWnd, &rect)) {
- DCHECK(false);
- return;
- }
- if (Msg == WM_MOUSEWHEEL || Msg == WM_MOUSEHWHEEL ||
- Msg == WM_CONTEXTMENU) {
- // These messages return screen-relative coordinates, not
- // window-relative coordinates.
- screen_x = x;
- screen_y = y;
- x -= rect.left;
- y -= rect.top;
- } else {
- screen_x = x + rect.left;
- screen_y = y + rect.top;
- }
- if (x >= 0 && x < rect.right - rect.left &&
- y >= 0 && y < rect.bottom - rect.top) {
- // x, y are 0-based from the top-left corner of the plugin. Rect is in
- // screen coordinates, with bottom > top, right > left.
- in_plugin = true;
- }
- }
- // First figure out which kind of event to create, and do any event-specific
- // processing that can be done prior to creating it.
- switch (Msg) {
- case WM_MOUSEMOVE:
- type = Event::TYPE_MOUSEMOVE;
- break;
-
- case WM_LBUTTONDOWN:
- case WM_RBUTTONDOWN:
- case WM_MBUTTONDOWN:
-#if (_WIN32_WINNT >= 0x0500)
- case WM_XBUTTONDOWN:
-#endif
- type = Event::TYPE_MOUSEDOWN;
- obj->set_got_dblclick(false);
- SetCapture(hWnd); // Capture mouse to make sure we get the mouseup.
- break;
-
- case WM_LBUTTONUP:
- case WM_RBUTTONUP:
- case WM_MBUTTONUP:
-#if (_WIN32_WINNT >= 0x0500)
- case WM_XBUTTONUP:
-#endif
- type = Event::TYPE_MOUSEUP;
- if (obj->got_dblclick()) {
- fake_dblclick = in_plugin;
- obj->set_got_dblclick(false);
- }
- ReleaseCapture();
- break;
-
- case WM_LBUTTONDBLCLK:
- case WM_RBUTTONDBLCLK:
- case WM_MBUTTONDBLCLK:
-#if (_WIN32_WINNT >= 0x0500)
- case WM_XBUTTONDBLCLK:
-#endif
- // On a double-click, windows produces: down, up, move, dblclick, up.
- // JavaScript should receive: down, up, [optional move, ] click, down,
- // up, click, dblclick.
- // The EventManager turns (down, up) into click, since we need that on all
- // platforms. Windows then has to turn (dblclick, up) into (down, up,
- // click, dblclick) IFF both events took place in the plugin. If only the
- // dblclick did, it just turns into a down. If only the up did, it's just
- // an up, and we shouldn't be passing along the down/dblclick anyway. So
- // we turn the doubleclick into a mousedown, store the fact that it was a
- // doubleclick, and wait for the corresponding mouseup to finish off the
- // sequence. If we get anything that indicates that we missed the mouseup
- // [because it went to a different window or element], we forget about the
- // dblclick.
- DCHECK(in_plugin);
- obj->set_got_dblclick(true);
- type = Event::TYPE_MOUSEDOWN;
- SetCapture(hWnd); // Capture mouse to make sure we get the mouseup.
- break;
-
- case WM_MOUSEWHEEL:
- case WM_MOUSEHWHEEL:
- type = Event::TYPE_WHEEL;
- break;
-
- case WM_CONTEXTMENU:
- type = Event::TYPE_CONTEXTMENU;
- break;
-
- default:
- LOG(FATAL) << "Unknown mouse event: " << Msg;
- }
- Event event(type);
- // Now do any event-specific code that requires an Event object.
- switch (Msg) {
- case WM_LBUTTONDOWN:
- case WM_LBUTTONUP:
- case WM_LBUTTONDBLCLK:
- event.set_button(Event::BUTTON_LEFT);
- break;
-
- case WM_RBUTTONDOWN:
- case WM_RBUTTONUP:
- case WM_RBUTTONDBLCLK:
- event.set_button(Event::BUTTON_RIGHT);
- break;
-
- case WM_MBUTTONDOWN:
- case WM_MBUTTONUP:
- case WM_MBUTTONDBLCLK:
- event.set_button(Event::BUTTON_MIDDLE);
- break;
-
-#if (_WIN32_WINNT >= 0x0500)
- case WM_XBUTTONDOWN:
- case WM_XBUTTONUP:
- case WM_XBUTTONDBLCLK:
- if (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) {
- event.set_button(Event::BUTTON_4);
- } else {
- event.set_button(Event::BUTTON_5);
- }
- break;
-#endif
- case WM_MOUSEWHEEL:
- event.set_delta(0, GET_WHEEL_DELTA_WPARAM(wParam));
- break;
- case WM_MOUSEHWHEEL:
- event.set_delta(GET_WHEEL_DELTA_WPARAM(wParam), 0);
- break;
-
- default:
- break;
- }
-
- if (event.type() != WM_CONTEXTMENU) {
- // Only the context menu event doesn't get this information.
- int modifier_state = 0;
- if (wParam & MK_CONTROL) {
- modifier_state |= Event::MODIFIER_CTRL;
- }
- if (wParam & MK_SHIFT) {
- modifier_state |= Event::MODIFIER_SHIFT;
- }
- if (::GetKeyState(VK_MENU) < 0) {
- modifier_state |= Event::MODIFIER_ALT;
- }
- event.set_modifier_state(modifier_state);
- }
-
- event.set_position(x, y, screen_x, screen_y, in_plugin);
- obj->client()->AddEventToQueue(event);
- if (fake_dblclick) {
- event.set_type(Event::TYPE_DBLCLICK);
- obj->client()->AddEventToQueue(event);
- }
- if (in_plugin && type == Event::TYPE_MOUSEDOWN &&
- obj->HitFullscreenClickRegion(x, y)) {
- obj->RequestFullscreenDisplay();
- }
-}
-
-LRESULT HandleDragAndDrop(PluginObject *obj, WPARAM wParam) {
- HDROP hDrop = reinterpret_cast<HDROP>(wParam);
- UINT num_files = ::DragQueryFile(hDrop, 0xFFFFFFFF, NULL, 0);
- if (!num_files) {
- ::DragFinish(hDrop);
- return 0;
- }
- UINT path_len = ::DragQueryFile(hDrop, 0, NULL, 0);
- // Let's limit that length, just in case.
- if (!path_len || path_len > 4096) {
- ::DragFinish(hDrop);
- return 0;
- }
- scoped_array<TCHAR> path(new TCHAR[path_len + 1]); // Add 1 for the NUL.
- UINT num_chars = ::DragQueryFile(hDrop, 0, path.get(), path_len + 1);
- DCHECK(num_chars == path_len);
- ::DragFinish(hDrop);
-
- char *path_to_use = NULL;
-#ifdef UNICODE // TCHAR is WCHAR
- // TODO: We definitely need to move this to a string utility class.
- int bytes_needed = ::WideCharToMultiByte(CP_UTF8,
- 0,
- path.get(),
- num_chars + 1,
- NULL,
- 0,
- NULL,
- NULL);
- // Let's limit that length, just in case.
- if (!bytes_needed || bytes_needed > 4096) {
- return 0;
- }
- scoped_array<char> utf8_path(new char[bytes_needed]);
- int bytes_conv = ::WideCharToMultiByte(CP_UTF8,
- 0,
- path.get(),
- num_chars + 1,
- utf8_path.get(),
- bytes_needed,
- NULL,
- NULL);
- DCHECK(bytes_conv == bytes_needed);
- path_to_use = utf8_path.get();
- num_chars = bytes_conv;
-#else
- path_to_use = path.get();
-#endif
-
- for (UINT i = 0; i < num_chars; ++i) {
- if (path_to_use[i] == '\\') {
- path_to_use[i] = '/';
- }
- }
- obj->RedirectToFile(path_to_use);
-
- return 1;
-}
-
-static const UINT kDestroyWindowMessageID = WM_USER + 1;
-
-LRESULT CALLBACK WindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) {
- // To work around deadlocks caused by calling DestroyWindow
- // synchronously during plugin destruction in Chrome's multi-process
- // architecture, we call DestroyWindow asynchronously.
- if (Msg == kDestroyWindowMessageID) {
- ::DestroyWindow(hWnd);
- // Do not touch anything related to the plugin; it has likely
- // already been destroyed.
- return 0;
- }
-
- PluginObject *obj = PluginObject::GetPluginProperty(hWnd);
- if (obj == NULL) { // It's not my window
- return 1; // 0 often means we handled it.
- }
-
- // Limit the ways in which we can be reentrant. Note that this WindowProc
- // may be called by different threads. For example, IE will register plugin
- // instances on separate threads.
- o3d::Client::ScopedIncrement reentrance_count(obj->client());
-
- switch (Msg) {
- case WM_PAINT: {
- PAINTSTRUCT paint_struct;
- HDC hdc = ::BeginPaint(hWnd, &paint_struct);
- if (paint_struct.rcPaint.right - paint_struct.rcPaint.left != 0 ||
- paint_struct.rcPaint.bottom - paint_struct.rcPaint.top != 0) {
- if (obj->renderer()) {
- // It appears to be necessary to use GDI to paint something at least
- // once before D3D rendering will work in Vista with Aero.
- if (!obj->RecordPaint()) {
- ::SetPixelV(hdc, 0, 0, RGB(0, 0, 0));
- }
- obj->renderer()->set_need_to_render(true);
- } else {
- // If the Client has no Renderer associated with it, paint the
- // draw area gray.
- ::SelectObject(paint_struct.hdc, GetStockObject(DKGRAY_BRUSH));
- ::Rectangle(paint_struct.hdc,
- paint_struct.rcPaint.left,
- paint_struct.rcPaint.top,
- paint_struct.rcPaint.right,
- paint_struct.rcPaint.bottom);
- }
- }
- ::EndPaint(hWnd, &paint_struct);
- return 0;
- }
- case WM_SETCURSOR: {
- obj->set_cursor(obj->cursor());
- return 1;
- }
- case WM_ERASEBKGND: {
- // Tell windows we don't need the background cleared.
- return 1;
- }
-
- case WM_TIMER: {
- if (reentrance_count.get() > 1) {
- break; // Ignore this message; we're reentrant.
- }
-
-#if !defined(O3D_INTERNAL_PLUGIN)
- if (g_logger) g_logger->UpdateLogging();
-#endif
-
- // If rendering continuously, invalidate the window and force a paint if
- // it is visible. The paint invalidates the renderer and Tick will later
- // repaint the window.
- if (obj->client()->NeedsContinuousRender()) {
- InvalidateRect(obj->GetHWnd(), NULL, FALSE);
- UpdateWindow(obj->GetHWnd());
- }
-
- obj->AsyncTick();
-
- break;
- }
- case WM_NCDESTROY: {
- // Win32 docs say we must remove all our properties before destruction.
- // However, this message doesn't appear to come early enough to be useful
- // when running in Chrome, at least.
- PluginObject::ClearPluginProperty(hWnd);
- break;
- }
- case WM_LBUTTONDOWN:
- case WM_LBUTTONDBLCLK:
- case WM_RBUTTONDOWN:
- case WM_RBUTTONDBLCLK:
- case WM_MBUTTONDOWN:
- case WM_MBUTTONDBLCLK:
-#if (_WIN32_WINNT >= 0x0500)
- case WM_XBUTTONDOWN:
- case WM_XBUTTONDBLCLK:
-#endif
- case WM_MOUSEWHEEL:
- case WM_MOUSEHWHEEL:
- // Without this SetFocus, if you alt+tab away from Firefox, then click
- // back in the plugin, Firefox will get keyboard focus but we won't.
- // However, if we do it on mouseup as well, then the click that triggers
- // fullscreen, and is followed by a mouseup in the plugin, which will grab
- // the focus back from the fullscreen window.
- ::SetFocus(hWnd);
- // FALL THROUGH
- case WM_LBUTTONUP:
- case WM_RBUTTONUP:
- case WM_MBUTTONUP:
-#if (_WIN32_WINNT >= 0x0500)
- case WM_XBUTTONUP:
-#endif
- case WM_MOUSEMOVE:
- case WM_CONTEXTMENU:
- HandleMouseEvent(obj, hWnd, Msg, wParam, lParam);
- break;
-
- case WM_DEADCHAR:
- case WM_SYSDEADCHAR:
- case WM_UNICHAR:
- // I believe these are redundant; TODO: Test this on a non-US
- // keyboard.
- break;
-
- case WM_CHAR:
- case WM_SYSCHAR:
- case WM_KEYDOWN:
- case WM_KEYUP:
- case WM_SYSKEYDOWN:
- case WM_SYSKEYUP:
- return HandleKeyboardEvent(obj, hWnd, Msg, wParam, lParam);
-
- case WM_DROPFILES:
- return HandleDragAndDrop(obj, wParam);
-
- case WM_ACTIVATE:
- // We don't receive WM_KILLFOCUS when Alt-Tabbing away from a
- // full-screen window. We do however get WM_ACTIVATE.
- if (LOWORD(wParam) == WA_INACTIVE) {
- if (obj->fullscreen()) {
- obj->CancelFullscreenDisplay();
- }
- }
- return 0;
-
- case WM_KILLFOCUS:
- // If we lose focus [which also happens on alt+f4 killing the fullscreen
- // window] fall back to plugin mode to avoid lost-device awkwardness.
- // TODO: We'll have problems with this when dealing with e.g.
- // Japanese text input IME windows.
- if (obj->fullscreen()) {
- // TODO(kbr): consider doing this somehow more asynchronously;
- // not supposed to cause window activation in the WM_KILLFOCUS
- // handler
- obj->CancelFullscreenDisplay();
- return 0;
- }
- // FALL THROUGH
- case WM_SETFOCUS:
- default:
- // Decrement reentrance_count here. It's OK if this call
- // boomerangs back to us, given that we're not in the middle of doing
- // anything caused by this message. Since we decrement reentrance_count
- // manually, its destructor will know not to.
- reentrance_count.decrement();
-
- return ::CallWindowProc(::DefWindowProc,
- hWnd,
- Msg,
- wParam,
- lParam);
- }
- return 0;
-}
-
-static const wchar_t* kOrigWndProcName = L"o3dOrigWndProc";
-
-LRESULT CALLBACK PluginWindowInterposer(HWND hWnd,
- UINT Msg,
- WPARAM wParam,
- LPARAM lParam) {
- PluginObject *obj = PluginObject::GetPluginProperty(hWnd);
-
- // Need to get the original window proc before potentially calling
- // CleanupAllWindows which will clear it.
- WNDPROC proc = static_cast<WNDPROC>(GetProp(hWnd, kOrigWndProcName));
- DCHECK(proc != NULL);
-
- switch (Msg) {
- case WM_PAINT: {
- // For nicer startup appearance, allow the browser to paint the
- // plugin window until we start to draw 3D content. Forbid the
- // browser from painting once we have started to draw to prevent
- // a flash in Firefox upon our receiving focus the first time.
- if (obj != NULL && obj->renderer() != NULL) {
- if (obj->renderer()->presented_once()) {
- // Tell Windows we painted the window region.
- ::ValidateRect(hWnd, NULL);
- return 0;
- }
- }
- // Break out to call the original window procedure to paint the
- // window.
- break;
- }
-
- case WM_DESTROY:
- if (obj != NULL) {
- CleanupAllWindows(obj);
- }
- break;
-
- default:
- break;
- }
-
- return CallWindowProc(proc, hWnd, Msg, wParam, lParam);
-}
-
-bool RegisterO3DWindowClass() {
- WNDCLASSEX window_class;
- ZeroMemory(&window_class, sizeof(window_class));
- window_class.cbSize = sizeof(window_class);
- window_class.hInstance = g_module_instance;
- window_class.lpfnWndProc = WindowProc;
- window_class.lpszClassName = kO3DWindowClassName;
- // We use CS_OWNDC in case we are rendering OpenGL into this window.
- window_class.style = CS_DBLCLKS | CS_OWNDC;
- return RegisterClassEx(&window_class) != 0;
-}
-
-void UnregisterO3DWindowClass() {
- UnregisterClass(kO3DWindowClassName, g_module_instance);
-}
-
-void CleanupAllWindows(PluginObject *obj) {
- if (obj->GetContentHWnd()) {
- ::KillTimer(obj->GetContentHWnd(), 0);
- PluginObject::ClearPluginProperty(obj->GetContentHWnd());
- ::PostMessage(obj->GetContentHWnd(), kDestroyWindowMessageID, 0, 0);
- obj->SetContentHWnd(NULL);
- }
-
- if (obj->GetPluginHWnd()) {
- // Restore the original WNDPROC on the plugin window so that we
- // don't attempt to call into the O3D DLL after it's been unloaded.
- LONG_PTR origWndProc = reinterpret_cast<LONG_PTR>(
- GetProp(obj->GetPluginHWnd(),
- kOrigWndProcName));
- DCHECK(origWndProc != NULL);
- // TODO: this leaks.
- RemoveProp(obj->GetPluginHWnd(), kOrigWndProcName);
- SetWindowLongPtr(obj->GetPluginHWnd(), GWLP_WNDPROC, origWndProc);
-
- PluginObject::ClearPluginProperty(obj->GetPluginHWnd());
- obj->SetPluginHWnd(NULL);
- }
-
- obj->SetHWnd(NULL);
-}
-
-// Re-parents the content_hwnd into the containing_hwnd, resizing the
-// content_hwnd to the given width and height in the process.
-void ReplaceContentWindow(HWND content_hwnd,
- HWND containing_hwnd,
- int width, int height) {
- // In Chrome browser, IPC might block this call. This doesn't happen with
- // firefox or internet explorer. For Chome, do not hide the window. Haven't
- // any artifacts with this change when exiting from full screen.
- PluginObject *obj = PluginObject::GetPluginProperty(content_hwnd);
- if (obj && !obj->IsChrome()) {
- ::ShowWindow(content_hwnd, SW_HIDE);
- }
- LONG_PTR style = ::GetWindowLongPtr(content_hwnd, GWL_STYLE);
- style |= WS_CHILD;
- ::SetWindowLongPtr(content_hwnd, GWL_STYLE, style);
- LONG_PTR exstyle = ::GetWindowLongPtr(content_hwnd, GWL_EXSTYLE);
- exstyle &= ~WS_EX_TOOLWINDOW;
- ::SetWindowLongPtr(content_hwnd, GWL_EXSTYLE, exstyle);
- ::SetParent(content_hwnd, containing_hwnd);
- BOOL res = ::SetWindowPos(content_hwnd, containing_hwnd,
- 0, 0, width, height,
- SWP_NOZORDER | SWP_ASYNCWINDOWPOS);
- DCHECK(res);
- ::ShowWindow(content_hwnd, SW_SHOW);
-}
-
-// Get the screen rect of the monitor the window is on, in virtual screen
-// coordinates.
-// Return true on success, false on failure.
-bool GetScreenRect(HWND hwnd,
- RECT* rect) {
- HMONITOR monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONULL);
- if (monitor == NULL)
- return false;
-
- MONITORINFO monitor_info;
- monitor_info.cbSize = sizeof(monitor_info);
- if (GetMonitorInfo(monitor, &monitor_info)) {
- *rect = monitor_info.rcMonitor;
- return true;
- } else {
- return false;
- }
-}
-
-} // namespace anonymous
-
-namespace o3d {
-
-NPError PlatformPreNPInitialize() {
-#if !defined(O3D_INTERNAL_PLUGIN)
- // Setup crash handler
- if (!g_exception_manager) {
- g_exception_manager = new ExceptionManager(false);
- g_exception_manager->StartMonitoring();
- }
-#endif // O3D_INTERNAL_PLUGIN
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformPostNPInitialize() {
- if (!RegisterO3DWindowClass())
- return NPERR_MODULE_LOAD_FAILED_ERROR;
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformPreNPShutdown() {
- // TODO(tschmelcher): Is there a reason we need to do this before the main
- // shutdown tasks? If not, we can axe the PlatformPreNPShutdown() function.
- UnregisterO3DWindowClass();
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformPostNPShutdown() {
-#if !defined(O3D_INTERNAL_PLUGIN)
- // TODO : This is commented out until we can determine if
- // it's safe to shutdown breakpad at this stage (Gears, for
- // example, never deletes...)
- // Shutdown breakpad
- // delete g_exception_manager;
-#endif
-
- // Clean up all pixman TLS entries.
- pixman_win32_tls_shutdown();
-
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformNPPNew(NPP instance, PluginObject *obj) {
- if (obj->IsChrome()) {
- // We want our O3D process to take priority over the browser and other apps.
- HANDLE process = ::GetCurrentProcess();
- DWORD priority = ABOVE_NORMAL_PRIORITY_CLASS;
- ::SetPriorityClass(process, priority);
- }
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformNPPDestroy(NPP instance, PluginObject *obj) {
- if (obj->GetHWnd()) {
- CleanupAllWindows(obj);
- }
-
- obj->TearDown();
-
- // Clean up pixman TLS thread local storage.
- pixman_win32_tls_shutdown_thread();
-
- return NPERR_NO_ERROR;
-}
-
-NPError PlatformNPPGetValue(PluginObject *obj,
- NPPVariable variable,
- void *value) {
- return NPERR_INVALID_PARAM;
-}
-
-NPError PlatformNPPSetWindow(NPP instance,
- PluginObject *obj,
- NPWindow *window) {
- HWND hWnd = static_cast<HWND>(window->window);
- if (!hWnd) {
- // Chrome calls us this way before NPP_Destroy.
- if (obj->GetHWnd()) {
- CleanupAllWindows(obj);
- }
- return NPERR_NO_ERROR;
- }
- if (obj->GetPluginHWnd() == hWnd) {
- // May need to resize the content window.
- DCHECK(obj->GetContentHWnd());
- // Avoid spurious resize requests.
- if (window->width != obj->width() ||
- window->height != obj->height()) {
- if (!obj->fullscreen() && window->width > 0 && window->height > 0) {
- ::SetWindowPos(obj->GetContentHWnd(), obj->GetPluginHWnd(), 0, 0,
- window->width, window->height,
- SWP_NOZORDER | SWP_NOREPOSITION);
- }
- // Even if we are in full-screen mode, store off the new width
- // and height to restore to them later.
- obj->Resize(window->width, window->height);
- // Only propagate this resize event to the client if it isn't in
- // full-screen mode.
- if (!obj->fullscreen()) {
- obj->client()->SendResizeEvent(obj->width(), obj->height(), false);
- }
- }
- return NPERR_NO_ERROR;
- }
-
- DCHECK(!obj->GetPluginHWnd());
- obj->SetPluginHWnd(hWnd);
-
- // Subclass the plugin window's window procedure to avoid processing
- // WM_PAINT. This seems to only be necessary for Firefox, which
- // overdraws our plugin the first time it gains focus.
- SetProp(hWnd, kOrigWndProcName,
- reinterpret_cast<HANDLE>(GetWindowLongPtr(hWnd, GWLP_WNDPROC)));
- PluginObject::StorePluginPropertyUnsafe(hWnd, obj);
- SetWindowLongPtr(hWnd, GWLP_WNDPROC,
- reinterpret_cast<LONG_PTR>(PluginWindowInterposer));
-
- // Create the content window, into which O3D always renders, rather
- // than alternating rendering between the browser's window and a
- // separate full-screen window. The O3D window is removed from the
- // browser's hierarchy and made top-level in order to go to
- // full-screen mode via Direct3D. This solves fundamental focus
- // fighting problems seen on Windows Vista.
- HWND content_window =
- CreateWindow(kO3DWindowClassName,
- L"O3D Window",
- WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
- 0, 0,
- window->width, window->height,
- hWnd,
- NULL,
- g_module_instance,
- NULL);
- obj->SetContentHWnd(content_window);
- PluginObject::StorePluginProperty(content_window, obj);
- ::ShowWindow(content_window, SW_SHOW);
- ::ShowWindow(hWnd, SW_SHOW);
-
- // create and assign the graphics context
- DisplayWindowWindows default_display;
- default_display.set_hwnd(obj->GetHWnd());
- obj->CreateRenderer(default_display);
- obj->client()->Init();
- obj->Resize(window->width, window->height);
-
- // 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
- // rate of the monitor or 100fps, which ever is lower.
- ::SetTimer(obj->GetHWnd(), 0, 10, NULL);
-
- return NPERR_NO_ERROR;
-}
-
-void PlatformNPPStreamAsFile(StreamManager *stream_manager,
- NPStream *stream,
- const char *fname) {
- stream_manager->SetStreamFile(stream, fname);
-}
-
-int16 PlatformNPPHandleEvent(NPP instance, PluginObject *obj, void *event) {
- return 0;
-}
-
-} // namespace o3d
-
-// TODO(tschmelcher): This stuff does not belong in this file.
-namespace glue {
-namespace _o3d {
-bool PluginObject::GetDisplayMode(int mode_id, o3d::DisplayMode *mode) {
- return renderer()->GetDisplayMode(mode_id, mode);
-}
-
-// TODO: Where should this really live? It's platform-specific, but in
-// PluginObject, which mainly lives in cross/o3d_glue.h+cc.
-bool PluginObject::RequestFullscreenDisplay() {
- bool success = false;
- DCHECK(GetPluginHWnd());
- DCHECK(GetContentHWnd());
- if (!fullscreen_ && renderer_ && fullscreen_region_valid_) {
- DCHECK(renderer_->fullscreen() == fullscreen_);
- // The focus window we pass into IDirect3D9::CreateDevice must not
- // fight with the full-screen window for the focus. The best way
- // to achieve this is to re-use the content window for full-screen
- // mode.
- ::ShowWindow(GetContentHWnd(), SW_HIDE);
- ::SetParent(GetContentHWnd(), NULL);
- // Remove WS_CHILD from the window style
- LONG_PTR style = ::GetWindowLongPtr(GetContentHWnd(), GWL_STYLE);
- style &= ~WS_CHILD;
- ::SetWindowLongPtr(GetContentHWnd(), GWL_STYLE, style);
- // Add WS_EX_TOOLWINDOW to the window exstyle so the content window won't
- // show in the Taskbar.
- LONG_PTR exstyle = ::GetWindowLongPtr(GetContentHWnd(), GWL_EXSTYLE);
- exstyle |= WS_EX_TOOLWINDOW;
- ::SetWindowLongPtr(GetContentHWnd(), GWL_EXSTYLE, exstyle);
- ::ShowWindow(GetContentHWnd(), SW_SHOW);
- // We need to resize the full-screen window to the desired size of
- // the display mode early, before calling
- // Renderer::GoFullscreen().
- RECT screen_rect;
- if (GetScreenRect(GetPluginHWnd(), &screen_rect)) {
- ::SetWindowPos(GetContentHWnd(), HWND_TOPMOST,
- screen_rect.left, screen_rect.top,
- screen_rect.right - screen_rect.left + 1,
- screen_rect.bottom - screen_rect.top + 1,
- SWP_NOZORDER | SWP_NOREPOSITION | SWP_ASYNCWINDOWPOS);
- DisplayWindowWindows display;
- display.set_hwnd(GetContentHWnd());
- if (renderer_->GoFullscreen(display,
- fullscreen_region_mode_id_)) {
- fullscreen_ = true;
- client()->SendResizeEvent(renderer_->width(), renderer_->height(),
- true);
- success = true;
- }
- }
-
- if (!success) {
- ReplaceContentWindow(GetContentHWnd(), GetPluginHWnd(),
- prev_width_, prev_height_);
- LOG(ERROR) << "Failed to switch to fullscreen mode.";
- }
- }
- return success;
-}
-
-void PluginObject::CancelFullscreenDisplay() {
- DCHECK(GetPluginHWnd());
- if (fullscreen_) {
- DCHECK(renderer());
- DCHECK(renderer()->fullscreen());
- fullscreen_ = false;
- DisplayWindowWindows display;
- display.set_hwnd(GetContentHWnd());
- if (!renderer_->CancelFullscreen(display, prev_width_, prev_height_)) {
- LOG(FATAL) << "Failed to get the renderer out of fullscreen mode!";
- }
- ReplaceContentWindow(GetContentHWnd(), GetPluginHWnd(),
- prev_width_, prev_height_);
- client()->SendResizeEvent(prev_width_, prev_height_, false);
- }
-}
-} // namespace _o3d
-} // namespace glue
diff --git a/o3d/plugin/win/o3dPlugin.def_template b/o3d/plugin/win/o3dPlugin.def_template
deleted file mode 100644
index 4e3600a..0000000
--- a/o3d/plugin/win/o3dPlugin.def_template
+++ /dev/null
@@ -1,6 +0,0 @@
-LIBRARY @@@PluginNpapiFilename@@@
-
-EXPORTS
- NP_GetEntryPoints @1
- NP_Initialize @2
- NP_Shutdown @3
diff --git a/o3d/plugin/win/o3dPlugin.rc_template b/o3d/plugin/win/o3dPlugin.rc_template
deleted file mode 100644
index 3fb0940..0000000
--- a/o3d/plugin/win/o3dPlugin.rc_template
+++ /dev/null
@@ -1,106 +0,0 @@
-// Microsoft Visual C++ generated resource script.
-//
-#include "resource.h"
-
-#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 @@@ProductVersionCommas@@@
- PRODUCTVERSION @@@ProductVersionCommas@@@
- FILEFLAGSMASK 0x17L
-#ifdef _DEBUG
- FILEFLAGS 0x1L
-#else
- FILEFLAGS 0x0L
-#endif
- FILEOS 0x4L
- FILETYPE 0x2L
- FILESUBTYPE 0x0L
-BEGIN
- BLOCK "StringFileInfo"
- BEGIN
- BLOCK "040904e4"
- BEGIN
- // This value must not change format as it is used by javascript
- // to find the plugin.
- VALUE "FileDescription", "@@@PluginDescription@@@"
- VALUE "FileVersion", "@@@ProductVersionCommas@@@"
- VALUE "InternalName", "@@@PluginNpapiFilename@@@"
- VALUE "LegalCopyright", "Copyright (C) 2007"
- VALUE "MIMEType", "@@@PluginNpapiMimeType@@@"
- VALUE "OriginalFilename", "@@@PluginNpapiFilename@@@.dll"
- // This value must not change as it is used by javascript
- // to find the plugin.
- VALUE "ProductName", "@@@PluginName@@@"
- VALUE "ProductVersion", "@@@ProductVersionCommas@@@"
- 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/plugin/win/o3dPlugin.sln b/o3d/plugin/win/o3dPlugin.sln
deleted file mode 100644
index d4ab270..0000000
--- a/o3d/plugin/win/o3dPlugin.sln
+++ /dev/null
@@ -1,92 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 9.00
-# Visual Studio 2005
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "o3dPlugin", "o3dPlugin.vcproj", "{F431F75C-5EA2-4E96-BA23-B44A951A9276}"
- ProjectSection(WebsiteProperties) = preProject
- Debug.AspNetCompiler.Debug = "True"
- Release.AspNetCompiler.Debug = "False"
- EndProjectSection
- ProjectSection(ProjectDependencies) = postProject
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B} = {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}
- {7D7B36BE-B994-4BE2-A60C-753C19E5A9EA} = {7D7B36BE-B994-4BE2-A60C-753C19E5A9EA}
- {6028E8C8-F1DC-4248-9961-B0CADFEA244C} = {6028E8C8-F1DC-4248-9961-B0CADFEA244C}
- {E1978291-230F-4F95-A227-84A13F22833C} = {E1978291-230F-4F95-A227-84A13F22833C}
- EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "o3dImport", "..\..\..\..\o3d\import\win\import.vcproj", "{6028E8C8-F1DC-4248-9961-B0CADFEA244C}"
- ProjectSection(WebsiteProperties) = preProject
- Debug.AspNetCompiler.Debug = "True"
- Release.AspNetCompiler.Debug = "False"
- EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "o3dCore", "..\..\..\..\o3d\core\win\core_win.vcproj", "{B57C4010-AE66-47A2-8B1F-F839B6E6A67B}"
- ProjectSection(WebsiteProperties) = preProject
- Debug.AspNetCompiler.Debug = "True"
- Release.AspNetCompiler.Debug = "False"
- EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "o3d_base", "..\..\..\..\o3d\base\win\o3d_base.vcproj", "{E1978291-230F-4F95-A227-84A13F22833C}"
- ProjectSection(WebsiteProperties) = preProject
- Debug.AspNetCompiler.Debug = "True"
- Release.AspNetCompiler.Debug = "False"
- EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "google_nacl_imc", "..\..\..\..\native_client\intermodule_comm\google_nacl_imc\google_nacl_imc.vcproj", "{7D7B36BE-B994-4BE2-A60C-753C19E5A9EA}"
- ProjectSection(WebsiteProperties) = preProject
- Debug.AspNetCompiler.Debug = "True"
- Release.AspNetCompiler.Debug = "False"
- EndProjectSection
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- DebugD3D9|Win32 = DebugD3D9|Win32
- DebugGL|Win32 = DebugGL|Win32
- ReleaseD3D9|Win32 = ReleaseD3D9|Win32
- ReleaseGL|Win32 = ReleaseGL|Win32
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {F431F75C-5EA2-4E96-BA23-B44A951A9276}.DebugD3D9|Win32.ActiveCfg = DebugD3D9|Win32
- {F431F75C-5EA2-4E96-BA23-B44A951A9276}.DebugD3D9|Win32.Build.0 = DebugD3D9|Win32
- {F431F75C-5EA2-4E96-BA23-B44A951A9276}.DebugGL|Win32.ActiveCfg = DebugGL|Win32
- {F431F75C-5EA2-4E96-BA23-B44A951A9276}.DebugGL|Win32.Build.0 = DebugGL|Win32
- {F431F75C-5EA2-4E96-BA23-B44A951A9276}.ReleaseD3D9|Win32.ActiveCfg = ReleaseD3D9|Win32
- {F431F75C-5EA2-4E96-BA23-B44A951A9276}.ReleaseD3D9|Win32.Build.0 = ReleaseD3D9|Win32
- {F431F75C-5EA2-4E96-BA23-B44A951A9276}.ReleaseGL|Win32.ActiveCfg = ReleaseGL|Win32
- {F431F75C-5EA2-4E96-BA23-B44A951A9276}.ReleaseGL|Win32.Build.0 = ReleaseGL|Win32
- {6028E8C8-F1DC-4248-9961-B0CADFEA244C}.DebugD3D9|Win32.ActiveCfg = DebugD3D9|Win32
- {6028E8C8-F1DC-4248-9961-B0CADFEA244C}.DebugD3D9|Win32.Build.0 = DebugD3D9|Win32
- {6028E8C8-F1DC-4248-9961-B0CADFEA244C}.DebugGL|Win32.ActiveCfg = DebugGL|Win32
- {6028E8C8-F1DC-4248-9961-B0CADFEA244C}.DebugGL|Win32.Build.0 = DebugGL|Win32
- {6028E8C8-F1DC-4248-9961-B0CADFEA244C}.ReleaseD3D9|Win32.ActiveCfg = ReleaseD3D9|Win32
- {6028E8C8-F1DC-4248-9961-B0CADFEA244C}.ReleaseD3D9|Win32.Build.0 = ReleaseD3D9|Win32
- {6028E8C8-F1DC-4248-9961-B0CADFEA244C}.ReleaseGL|Win32.ActiveCfg = ReleaseGL|Win32
- {6028E8C8-F1DC-4248-9961-B0CADFEA244C}.ReleaseGL|Win32.Build.0 = ReleaseGL|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.DebugD3D9|Win32.ActiveCfg = DebugD3D9|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.DebugD3D9|Win32.Build.0 = DebugD3D9|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.DebugGL|Win32.ActiveCfg = DebugGL|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.DebugGL|Win32.Build.0 = DebugGL|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.ReleaseD3D9|Win32.ActiveCfg = ReleaseD3D9|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.ReleaseD3D9|Win32.Build.0 = ReleaseD3D9|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.ReleaseGL|Win32.ActiveCfg = ReleaseGL|Win32
- {B57C4010-AE66-47A2-8B1F-F839B6E6A67B}.ReleaseGL|Win32.Build.0 = ReleaseGL|Win32
- {E1978291-230F-4F95-A227-84A13F22833C}.DebugD3D9|Win32.ActiveCfg = Debug|Win32
- {E1978291-230F-4F95-A227-84A13F22833C}.DebugD3D9|Win32.Build.0 = Debug|Win32
- {E1978291-230F-4F95-A227-84A13F22833C}.DebugGL|Win32.ActiveCfg = Debug|Win32
- {E1978291-230F-4F95-A227-84A13F22833C}.DebugGL|Win32.Build.0 = Debug|Win32
- {E1978291-230F-4F95-A227-84A13F22833C}.ReleaseD3D9|Win32.ActiveCfg = Release|Win32
- {E1978291-230F-4F95-A227-84A13F22833C}.ReleaseD3D9|Win32.Build.0 = Release|Win32
- {E1978291-230F-4F95-A227-84A13F22833C}.ReleaseGL|Win32.ActiveCfg = Release|Win32
- {E1978291-230F-4F95-A227-84A13F22833C}.ReleaseGL|Win32.Build.0 = Release|Win32
- {7D7B36BE-B994-4BE2-A60C-753C19E5A9EA}.DebugD3D9|Win32.ActiveCfg = Debug|Win32
- {7D7B36BE-B994-4BE2-A60C-753C19E5A9EA}.DebugD3D9|Win32.Build.0 = Debug|Win32
- {7D7B36BE-B994-4BE2-A60C-753C19E5A9EA}.DebugGL|Win32.ActiveCfg = Debug|Win32
- {7D7B36BE-B994-4BE2-A60C-753C19E5A9EA}.DebugGL|Win32.Build.0 = Debug|Win32
- {7D7B36BE-B994-4BE2-A60C-753C19E5A9EA}.ReleaseD3D9|Win32.ActiveCfg = Release|Win32
- {7D7B36BE-B994-4BE2-A60C-753C19E5A9EA}.ReleaseD3D9|Win32.Build.0 = Release|Win32
- {7D7B36BE-B994-4BE2-A60C-753C19E5A9EA}.ReleaseGL|Win32.ActiveCfg = Release|Win32
- {7D7B36BE-B994-4BE2-A60C-753C19E5A9EA}.ReleaseGL|Win32.Build.0 = Release|Win32
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
-EndGlobal
diff --git a/o3d/plugin/win/plugin_logging-win32.cc b/o3d/plugin/win/plugin_logging-win32.cc
deleted file mode 100644
index c27e2dc..0000000
--- a/o3d/plugin/win/plugin_logging-win32.cc
+++ /dev/null
@@ -1,312 +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 code to perform the necessary logging operations
-// including initializing logging object, aggregating metrics, and uploading
-// metrics to the stats server.
-
-#include <build/build_config.h>
-#ifdef OS_WIN
-#include <atlbase.h>
-#include "statsreport/const-win32.h"
-#endif
-#include "core/cross/types.h"
-#include "plugin/cross/plugin_logging.h"
-#include "plugin/cross/plugin_metrics.h"
-#include "statsreport/common/const_product.h"
-#include "statsreport/metrics.h"
-#include "statsreport/uploader.h"
-namespace o3d {
-
-
-HRESULT StringEscape(const CString& str_in,
- bool segment_only,
- CString* escaped_string);
-HRESULT GetRegStringValue(bool is_machine_key,
- const CString& relative_key_path,
- const CString& value_name,
- CString* value);
-
-PluginLogging::PluginLogging() : timer_(new HighresTimer()),
- running_time_(0),
- prev_uptime_seconds_(0),
- prev_cputime_seconds_(0) {
- DLOG(INFO) << "Creating logger.";
- timer_->Start();
-}
-
-bool PluginLogging::UpdateLogging() {
- // If sufficient time has not passed since last aggregation, we can just
- // return until next time.
- if (timer_->GetElapsedMs() <
- static_cast<unsigned>(kStatsAggregationIntervalMSec))
- return false;
-
- // Reset timer.
- timer_->Start();
- // We are not exiting just yet so pass false for that argument.
- // We don't have to force stats reporting, so pass false for forcing, too.
- return ProcessMetrics(false, false, false);
-}
-
-static uint64 ToSeconds(FILETIME time) {
- ULARGE_INTEGER t;
- t.u.HighPart = time.dwHighDateTime;
- t.u.LowPart = time.dwLowDateTime;
-
- return t.QuadPart / 10000000L;
-}
-
-void PluginLogging::RecordProcessTimes() {
- FILETIME creation_time, exit_time, kernel_time, user_time;
- if (!::GetProcessTimes(::GetCurrentProcess(), &creation_time, &exit_time,
- &kernel_time, &user_time)) {
- return;
- }
- FILETIME now;
- ::GetSystemTimeAsFileTime(&now);
- uint64 uptime = ToSeconds(now) - ToSeconds(creation_time);
- uint64 additional_uptime = uptime - prev_uptime_seconds_;
- metric_uptime_seconds += additional_uptime;
- running_time_ += additional_uptime;
- prev_uptime_seconds_ = uptime;
-
- uint64 cputime = ToSeconds(kernel_time) + ToSeconds(user_time);
- metric_cpu_time_seconds += (cputime - prev_cputime_seconds_);
- prev_cputime_seconds_ = cputime;
-}
-
-bool PluginLogging::ProcessMetrics(const bool exiting,
- const bool force_report,
- const bool save_old_metrics) {
- DLOG(INFO) << "ProcessMetrics()";
- // Grab incremental process times. This has to be done each time
- // around the loop since time passes between iterations.
- RecordProcessTimes();
-
- // This mutex protects the writing to the registry. This way,
- // if we have multiple instances attempting to aggregate at
- // once, they won't overwrite one another.
- CHandle mutex(::CreateMutexA(NULL, FALSE, kMetricsLockName));
- if (NULL == mutex.m_h) {
- DLOG(WARNING) << "Unable to create metrics mutex";
- return false;
- }
-
- // If we can't get the mutex in 3 seconds, let's go around again.
- DWORD wait_result = ::WaitForSingleObject(mutex, 3000);
- if (WAIT_OBJECT_0 != wait_result) {
- DLOG(WARNING) << "Unable to get metrics mutex, error "
- << std::hex << wait_result;
- return false;
- }
- if (exiting) {
- // If we're exiting, we aggregate to make sure that we record
- // the tail activity for posterity. We don't report, because
- // that might delay the process exit.
- // We also make sure to add a sample to the total running time.
- metric_running_time_seconds.AddSample(running_time_);
- DoAggregateMetrics();
- } else {
- CString user_id;
- if (FAILED(GetRegStringValue(true, // is_machine_key
- CString(kRelativeGoopdateRegPath),
- CString(kRegValueUserId),
- &user_id))) {
- user_id = CString("unknown user_id");
- }
- CString user_id_escaped;
- StringEscape(user_id, true, &user_id_escaped);
- CStringA client_id_argument = CString("ui=")
- + user_id_escaped.GetString();
- DLOG(INFO) << "client id " << client_id_argument;
-
- std::string user_agent8 = std::string(kUserAgent) +
- PRODUCT_VERSION_STRING;
- DoAggregateAndReportMetrics(client_id_argument,
- user_agent8.c_str(), force_report,
- save_old_metrics);
- }
-
- ::ReleaseMutex(mutex);
-
- return true;
-}
-
-void PluginLogging::DoAggregateMetrics() {
- DLOG(INFO) << "DoAggregateMetrics()";
- stats_report::AggregateMetrics();
-}
-
-bool PluginLogging::DoAggregateAndReportMetrics(
- const char* extra_url_arguments,
- const char* user_agent,
- const bool force_report,
- const bool save_old_metrics) {
- DLOG(INFO) << "DoAggregateAndReportMetrics()";
- // This eturns true if metrics were uploaded.
- return stats_report::AggregateAndReportMetrics(extra_url_arguments,
- user_agent,
- force_report,
- save_old_metrics);
-}
-
-// This method is used for testing.
-void PluginLogging::SetTimer(HighresTimer* timer) {
- timer_.reset(timer);
-}
-
-// Reads the specified string value from the specified registry key.
-// Only supports value types REG_SZ and REG_EXPAND_SZ.
-// REG_EXPAND_SZ strings are not expanded.
-HRESULT GetRegStringValue(bool is_machine_key,
- const CString& relative_key_path,
- const CString& value_name,
- CString* value) {
- if (!value) {
- return E_INVALIDARG;
- }
-
- value->Empty();
- HKEY root_key = is_machine_key ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
- HKEY key = NULL;
- LONG res = ::RegOpenKeyEx(root_key, relative_key_path, 0, KEY_READ, &key);
- if (res != ERROR_SUCCESS) {
- return HRESULT_FROM_WIN32(res);
- }
-
- // First get the size of the string buffer.
- DWORD type = 0;
- DWORD byte_count = 0;
- res = ::RegQueryValueEx(key, value_name, NULL, &type, NULL, &byte_count);
- if (ERROR_SUCCESS != res) {
- return HRESULT_FROM_WIN32(res);
- }
- if ((type != REG_SZ && type != REG_EXPAND_SZ) || (0 == byte_count)) {
- return E_FAIL;
- }
-
- CString local_value;
- // GetBuffer throws when not able to allocate the requested buffer.
- TCHAR* buffer = local_value.GetBuffer(byte_count / sizeof(TCHAR));
- res = ::RegQueryValueEx(key,
- value_name,
- NULL,
- NULL,
- reinterpret_cast<byte*>(buffer),
- &byte_count);
- if (ERROR_SUCCESS == res) {
- local_value.ReleaseBufferSetLength(byte_count / sizeof(TCHAR));
- *value = local_value;
- }
-
- return HRESULT_FROM_WIN32(res);
-}
-
-HRESULT StringEscape(const CString& str_in,
- bool segment_only,
- CString* escaped_string) {
- if (!escaped_string) {
- return E_INVALIDARG;
- }
-
- DWORD buf_len = INTERNET_MAX_URL_LENGTH + 1;
- HRESULT hr = ::UrlEscape(str_in,
- escaped_string->GetBufferSetLength(buf_len),
- &buf_len,
- segment_only ?
- URL_ESCAPE_PERCENT | URL_ESCAPE_SEGMENT_ONLY :
- URL_ESCAPE_PERCENT);
- if (SUCCEEDED(hr)) {
- escaped_string->ReleaseBuffer();
- }
- return hr;
-}
-
-PluginLogging* PluginLogging::InitializeUsageStatsLogging() {
- HKEY hkcu;
- ::RegOpenKeyEx(HKEY_CURRENT_USER,
- kClientstateRegistryKey,
- 0,
- KEY_SET_VALUE,
- &hkcu);
- ::RegSetValueEx(hkcu, L"dr", 0, REG_SZ, (LPBYTE)"1\0", 2);
- ::RegCloseKey(hkcu);
-
- bool opt_in = GetOptInKeyValue(kClientstateRegistryKey, kOptInRegistryKey);
-
- return CreateUsageStatsLogger<PluginLogging>(opt_in);
-}
-
-bool PluginLogging::GetOptInKeyValue(const wchar_t* clientstate_registry_key,
- const wchar_t* opt_in_registry_key) {
-#ifdef NDEBUG
- HKEY hkcu_opt;
- if (::RegOpenKeyEx(HKEY_CURRENT_USER,
- clientstate_registry_key,
- 0,
- KEY_QUERY_VALUE,
- &hkcu_opt) != ERROR_SUCCESS) {
- return false;
- }
- DWORD opt_value;
- DWORD value_type;
- ULONG value_len = sizeof(opt_value);
- if (::RegQueryValueEx(hkcu_opt, opt_in_registry_key, 0,
- &value_type, reinterpret_cast<BYTE *>(&opt_value),
- &value_len) != ERROR_SUCCESS) {
- return false;
- }
- ::RegCloseKey(hkcu_opt);
-
- return opt_value == 1;
-#else
- // If we are debugging, always return true.
- return true;
-#endif
- // Default to opt-out for situations we don't handle.
- return false;
-}
-
-void PluginLogging::ClearLogs() {
- CRegKey key;
- CString key_name;
- key_name.Format(stats_report::kStatsKeyFormatString,
- PRODUCT_NAME_STRING_WIDE);
- LONG err = key.Create(HKEY_CURRENT_USER, key_name);
- if (ERROR_SUCCESS != err) {
- DLOG(WARNING) << "Unable to open metrics key";
- }
- stats_report::ResetPersistentMetrics(&key);
-}
-
-} // namespace o3d
diff --git a/o3d/plugin/win/plugin_metrics-win32.cc b/o3d/plugin/win/plugin_metrics-win32.cc
deleted file mode 100644
index 4e3b05a..0000000
--- a/o3d/plugin/win/plugin_metrics-win32.cc
+++ /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.
- */
-
-
-#include "statsreport/metrics.h"
-#include "plugin/cross/plugin_metrics.h"
-
-namespace o3d {
-DEFINE_METRIC_integer(system_type);
-
-DEFINE_METRIC_integer(windows_major_version);
-DEFINE_METRIC_integer(windows_minor_version);
-DEFINE_METRIC_integer(windows_sp_major_version);
-DEFINE_METRIC_integer(windows_sp_minor_version);
-
-// User GPU
-DEFINE_METRIC_integer(gpu_vendor_id);
-DEFINE_METRIC_integer(gpu_device_id);
-DEFINE_METRIC_integer(gpu_driver_major_version);
-DEFINE_METRIC_integer(gpu_driver_minor_version);
-DEFINE_METRIC_integer(gpu_vram_size);
-DEFINE_METRIC_bool(direct3d_available);
-
-// Shader versions
-DEFINE_METRIC_integer(pixel_shader_main_version);
-DEFINE_METRIC_integer(pixel_shader_sub_version);
-DEFINE_METRIC_integer(vertex_shader_main_version);
-DEFINE_METRIC_integer(vertex_shader_sub_version);
-
-DEFINE_METRIC_bool(POW2_texture_caps);
-DEFINE_METRIC_bool(NONPOW2CONDITIONAL_texture_caps);
-
-DEFINE_METRIC_integer(browser_type);
-DEFINE_METRIC_integer(browser_major_version);
-DEFINE_METRIC_integer(browser_minor_version);
-DEFINE_METRIC_integer(browser_bugfix_version);
-
-DEFINE_METRIC_timing(running_time);
-
-DEFINE_METRIC_count(uptime_seconds);
-DEFINE_METRIC_count(cpu_time_seconds);
-DEFINE_METRIC_timing(running_time_seconds);
-
-DEFINE_METRIC_count(crashes_total);
-DEFINE_METRIC_count(crashes_uploaded);
-DEFINE_METRIC_count(out_of_memory_total);
-
-DEFINE_METRIC_count(bluescreens_total);
-
-// OpenGL Caps - insert more here
-DEFINE_METRIC_integer(gl_major_version);
-DEFINE_METRIC_integer(gl_minor_version);
-DEFINE_METRIC_integer(gl_hlsl_major_version);
-DEFINE_METRIC_integer(gl_hlsl_minor_version);
-
-// D3D Caps
-DEFINE_METRIC_integer(d3d_devcaps);
-DEFINE_METRIC_integer(d3d_misccaps);
-DEFINE_METRIC_integer(d3d_rastercaps);
-DEFINE_METRIC_integer(d3d_zcmpcaps);
-DEFINE_METRIC_integer(d3d_srcblendcaps);
-DEFINE_METRIC_integer(d3d_dstblendcaps);
-DEFINE_METRIC_integer(d3d_alphacaps);
-DEFINE_METRIC_integer(d3d_texcaps);
-DEFINE_METRIC_integer(d3d_texfiltercaps);
-DEFINE_METRIC_integer(d3d_cubetexfiltercaps);
-DEFINE_METRIC_integer(d3d_texaddrcaps);
-DEFINE_METRIC_integer(d3d_linecaps);
-DEFINE_METRIC_integer(d3d_stencilcaps);
-DEFINE_METRIC_integer(d3d_texopcaps);
-DEFINE_METRIC_integer(d3d_vs20caps);
-DEFINE_METRIC_integer(d3d_vs20_dynflowctrldepth);
-DEFINE_METRIC_integer(d3d_vs20_numtemps);
-DEFINE_METRIC_integer(d3d_vs20_staticflowctrldepth);
-DEFINE_METRIC_integer(d3d_ps20caps);
-DEFINE_METRIC_integer(d3d_ps20_dynflowctrldepth);
-DEFINE_METRIC_integer(d3d_ps20_numtemps);
-DEFINE_METRIC_integer(d3d_ps20_staticflowctrldepth);
-DEFINE_METRIC_integer(d3d_ps20_numinstrslots);
-
-} // namespace o3d
diff --git a/o3d/plugin/win/resource.h b/o3d/plugin/win/resource.h
deleted file mode 100644
index f4b98ca..0000000
--- a/o3d/plugin/win/resource.h
+++ /dev/null
@@ -1,46 +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.
- */
-
-//{{NO_DEPENDENCIES}}
-// Microsoft Visual C++ generated include file.
-// Used by o3d_plugin.rc
-//
-
-// Next default values for new objects
-//
-#ifdef APSTUDIO_INVOKED
-#ifndef APSTUDIO_READONLY_SYMBOLS
-#define _APS_NEXT_RESOURCE_VALUE 421
-#define _APS_NEXT_COMMAND_VALUE 40001
-#define _APS_NEXT_CONTROL_VALUE 1001
-#define _APS_NEXT_SYMED_VALUE 421
-#endif
-#endif
diff --git a/o3d/plugin/win/update_lock.cc b/o3d/plugin/win/update_lock.cc
deleted file mode 100644
index 257aeb2..0000000
--- a/o3d/plugin/win/update_lock.cc
+++ /dev/null
@@ -1,43 +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 "update_lock.h"
-
-#if !defined(O3D_INTERNAL_PLUGIN)
-
-namespace {
-// Instantiate a global object to indicate that the application is running.
-update_lock::HandleWrapper g_update_lock(update_lock::LockFromUpdates());
-
-} // anonymous namespace
-
-#endif // O3D_INTERNAL_PLUGIN
diff --git a/o3d/plugin/win/update_lock.h b/o3d/plugin/win/update_lock.h
deleted file mode 100644
index 8e7b419..0000000
--- a/o3d/plugin/win/update_lock.h
+++ /dev/null
@@ -1,104 +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_PLUGIN_WIN_UPDATE_LOCK_H_
-#define O3D_PLUGIN_WIN_UPDATE_LOCK_H_
-
-#if !defined(O3D_INTERNAL_PLUGIN)
-
-#include <windows.h>
-#include "base/basictypes.h"
-
-namespace update_lock {
-
-const TCHAR kRunningEventName[] =
- L"Global\\{AA4817F6-5DB2-482f-92E9-6BD2FF9F3B14}";
-
-class HandleWrapper {
- public:
- HandleWrapper(HANDLE handle) {
- handle_ = handle;
- }
- ~HandleWrapper() {
- CloseHandle(handle_);
- }
- HANDLE handle() {
- return handle_;
- }
- private:
- HANDLE handle_;
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(HandleWrapper);
-}; // HandleWrapper
-
-// Returns true if the software is currently not running and can be updated.
-bool CanUpdate() {
- // Look for Global kernel object created when application is running
- HandleWrapper running_event(
- OpenEvent(EVENT_ALL_ACCESS, FALSE, kRunningEventName));
- if (NULL != running_event.handle()) {
- return false;
- }
- return true;
-}
-
-// Returns a HANDLE that should be closed when the software is shutting down.
-HANDLE LockFromUpdates() {
- SECURITY_ATTRIBUTES* security_attributes = NULL;
- SECURITY_ATTRIBUTES security_attributes_buffer;
- SECURITY_DESCRIPTOR security_descriptor;
-
- ZeroMemory(&security_attributes_buffer, sizeof(security_attributes_buffer));
- security_attributes_buffer.nLength = sizeof(security_attributes_buffer);
- security_attributes_buffer.bInheritHandle = FALSE;
-
- // initialize the security descriptor and give it a NULL DACL
- if (InitializeSecurityDescriptor(&security_descriptor,
- SECURITY_DESCRIPTOR_REVISION)) {
- if (SetSecurityDescriptorDacl(&security_descriptor, TRUE,
- (PACL)NULL, FALSE)) {
- security_attributes_buffer.lpSecurityDescriptor = &security_descriptor;
- security_attributes = &security_attributes_buffer;
- }
- }
- // An event is used to lock out updates since events are closed by the OS
- // if their process dies. So, updates can still happen if an O3D executable
- // crashes (as long as all instances of the running event are closed, either
- // properly or due to a crash).
- return CreateEvent(security_attributes, FALSE, FALSE, kRunningEventName);
-}
-} // namespace update_lock
-
-#endif // O3D_INTERNAL_PLUGIN
-
-#endif // O3D_PLUGIN_WIN_UPDATE_LOCK_H_
-
diff --git a/o3d/samples/2d.html b/o3d/samples/2d.html
deleted file mode 100644
index 2faa3d0..0000000
--- a/o3d/samples/2d.html
+++ /dev/null
@@ -1,558 +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.
--->
-
-<!--
-2D in O3D.
-
-2d is easy in o3d.
-
-Things to notice:
-
-*) Pixel perfect alignment with the screen.
-
- The client area is 800x600 pixels. google-square.png is 200x200 pixels.
- There is a 1 pixel border in the google-square.png texture. Notice they line
- up exactly with each other and to the edge of the client area.
-
-*) Screen Top Left = 0,0 vs Center = 0,0
-
- This demo is set so the client area's top left corner is 0,0.
- If you want the center to be 0,0 just call setScreenOriginToCenter.
- You will have to adjust the math below to match.
-
-*) Image Top left = 0,0 vs Center = 0,0
-
- The g_googleSquares are all loaded with their origin set to the top left
- so you can see they rotate around the top left and are positioned from
- the top left
-
- The g_squares and the g_things are loaded with their origin set to the center
- so you can see they rotate and scale around their centers.
-
-*) 2d rotation, scale, fading, color changing
-
- transform.rotateZ rotates in 2d.
- transform.scale(x, y, 1) scales in 2d.
- image.setColor(1, 1, 1, ?) fades out.
- image.setColor(?, ?, ?, 1) sets the color multiplier
-
-*) Setting draw order by setting Z. negative z is more behind.
-
- the g_googleSquares have a Z of -2 so they are the furthest back.
- the g_squares have Z of -1 so they are in the middle
- the g_things have a Z of 0 so they are in the front.
-
- The Z range is -0.998 to 999
-
- That is because the camera is sitting at -1 Z and has the range set
- in the projection matrix from 0.001 to 1000
-
-*) Things to be aware of.
-
- Because we are doing 2d, draw order matters but you can only choose
- the order by setting the Z value. If you don't set the Z values correctly
- you will see issues. For example if 2 images are at the same Z and draw
- so that they overlap there is no guarntee which one will get drawn first.
-
- Note: Right now I think it is which ever one happens to be in the transform
- graph first. Maybe we should enforce this and then you can use insertBefore,
- insertAfter to change the order instead of setting Z.
-
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-2D in O3D.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.loader');
-
-
-// global variables
-var g_coordWidth = 800; // The number of units across our area
-var g_coordHeight = 600; // The number of units down our area
-var g_tileWidth = 64;
-var g_tileHeight = 64;
-var g_pillarWidth = 128;
-var g_pillarHeight = 256;
-var g_playerWidth = 183;
-var g_playerHeight = 198;
-var g_tilesAcross = Math.floor((g_coordWidth + g_tileWidth - 1) /
- g_tileWidth) + 1;
-var g_tilesDown = Math.floor((g_coordHeight + g_tileHeight - 1) /
- g_tileHeight) + 1;
-var g_pixelsAcrossMap = g_tilesAcross * 64;
-var g_pixelsAcrossPillarMap = (Math.floor((g_coordWidth + g_pillarWidth - 1) /
- g_pillarWidth) + 1) * g_pillarWidth;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_planeShape;
-var g_textures = [];
-var g_textureUrls = [
- 'assets/purple-flower.png', // 0
- 'assets/orange-flower.png', // 1
- 'assets/egg.png', // 2
- 'assets/google-square.png', // 3
- 'assets/square.png', // 4
- 'assets/texture_b3.jpg', // 5
- 'assets/pillar.png', // 6
- 'assets/block.png', // 7
- 'assets/android.png' // 8
-];
-var g_googleSquares = [];
-var g_squares = [];
-var g_things = [];
-var g_tiles = [];
-var g_pillars = [];
-var g_pillarScale = [];
-var g_player;
-var g_map = [
- [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
- [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [ 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0],
- [ 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
- [ 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
- [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
- [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
- [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
-];
-var g_randSeed = 0;
-
-/**
- * Creates the client area.
- */
-function init() {
- // These are here so they are visible to both the browser (so selenium sees
- // them) and V8.
- window.g_clock = 0;
- window.g_timeMult = 1;
- window.g_finished = false; // for selenium testing
-
- // Comment out the line below to run the sample in the browser JavaScript
- // engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Sets the origin of the screen to the top left. Assumes the area is 800 pixels
- * by 600 pixels.
- *
- * We have to pick some representation. If we have an image that's 800x600 and
- * we want to display it pixel perfect in an 800x600 area then we set the values
- * below to 800x600. If instead we were to set them to the width and height of
- * the area and say our area was 400x300 it will still be pixel perfect (1 to 1
- * pixels) which would meaning only the top left 400x300 pixels of our 800x600
- * image would show up.
- *
- * Doing it this way, we get pixel perfect at 800x600 and if we change the size
- * of the area, say to 400x300 to 640x480 or any other 4:3 ratio, our program
- * will still work as expected. It won't be 1x1 pixels but it will put things
- * where we want them within our scaled area. If our area is not 4:3 our image
- * will get a little stretched into the new aspect ratio but generally that's
- * still better than having some of our app not appear.
- *
- * The other option is to always set the values below to the width and height of
- * our area and then make all the code that positions things calculate where to
- * put things and how to scale them to fit which is a lot more work though may
- * be appropriate depending on the application.
- */
-function setScreenOriginToTopLeft() {
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- 0 + 0.5,
- g_coordWidth + 0.5,
- g_coordHeight + 0.5,
- 0 + 0.5,
- 0.001,
- 1000);
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 0, 1], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Sets the origin of the screen to the center. Assumes the area is 800 pixels
- * by 600 pixels. See setScreenOriginToTopLeft.
- */
-function setScreenOriginToCenter() {
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -g_coordWidth * 0.5 + 0.5,
- g_coordWidth * 0.5 + 0.5,
- g_coordHeight * 0.5 + 0.5,
- -g_coordHeight * 0.5 + 0.5,
- 0.001,
- 1000);
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 0, 1], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Set window.g_client as well. Otherwise when the sample runs in V8, selenium
- // won't be able to find this variable (it can only see the browser
- // environment).
- window.g_client = g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set the background color to blue.
- g_viewInfo.clearBuffer.clearColor = [0.1, 0.1, 1, 1];
-
- // Set culling to none so we can flip images using rotation or negative scale.
- g_viewInfo.zOrderedState.getStateParam('CullMode').value =
- g_o3d.State.CULL_NONE;
- g_viewInfo.zOrderedState.getStateParam('ZWriteEnable').value = false;
-
- // Create an orthographic matrix for 2d stuff.
- setScreenOriginToTopLeft();
- //setScreenOriginToCenter();
-
- // Load an effect file and create an effect and material with it.
- var material = o3djs.material.createMaterialFromFile(
- g_pack,
- 'shaders/texture-colormult.shader',
- g_viewInfo.zOrderedDrawList);
-
- // Set the material params which act as the default. We'll override these with
- // params on transforms.
- material.getParam('colorMult').value = [1, 1, 1, 1];
-
- // Create a 2d plane. createPlane makes an XZ plane by default
- // so we pass in matrix to rotate it to an XY plane. We could do
- // all our manipluations in XZ but most people seem to like XY for 2D.
- g_planeShape = o3djs.primitives.createPlane(
- g_pack,
- material,
- 1,
- 1,
- 1,
- 1,
- [[1, 0, 0, 0],
- [0, 0, 1, 0],
- [0,-1, 0, 0],
- [0, 0, 0, 1]]);
-
- // Load all the textures.
- var loader = o3djs.loader.createLoader(initStep3);
- for (var ii = 0; ii < g_textureUrls.length; ++ii) {
- loadTexture(loader, g_textureUrls[ii], ii);
- }
- loader.finish();
-}
-
-/**
- * Loads a texture and saves it in the g_textures array.
- * @param {!o3djs.loader.Loader} loader The loader to load with.
- * @param {string} url of texture to load
- * @param {number} index Index to put texture in g_textures
- */
-function loadTexture(loader, url, index) {
- loader.loadTexture(g_pack, url, function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- g_textures[index] = texture;
- }
- });
-}
-
-/**
- * Now that the textures are loaded continue.
- */
-function initStep3() {
- for (var ii = 0; ii < 12; ++ii) {
- g_googleSquares[ii] = new Image(g_textures[3], true);
- g_squares[ii] = new Image(g_textures[4], false);
- g_things[ii] = new Image(g_textures[ii % 3], false);
- g_pillars[ii] = new Image(g_textures[6], true);
- g_pillarScale[ii] = g_math.pseudoRandom() * 1.5 + 0.5;
- }
-
- for (var yy = 0; yy < g_tilesDown; ++yy) {
- g_tiles[yy] = [];
- for (var xx = 0; xx < g_tilesAcross; ++xx) {
- if (g_map[yy][xx]) {
- g_tiles[yy][xx] = new Image(g_textures[7], true);
- }
- }
- }
-
- g_player = new Image(g_textures[8], true);
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onrender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- // Update g_clock in the browser and cache a V8 copy that can be accesse
- // efficiently. g_clock must be in the browser for selenium.
- var clock = window.g_clock + elapsedTime * window.g_timeMult;
- window.g_clock = clock;
-
- var duration = 4;
- var parts = 4;
- var fadeTime = 1;
- var partOffset = duration - fadeTime;
- var cycle = duration * parts - parts;
-
- var computeFade = function(fadeClock) {
- var fade = 1;
- if (fadeClock < fadeTime) {
- fade = fadeClock / fadeTime;
- } else if (fadeClock > duration - fadeTime) {
- fade = Math.max(duration - fadeClock, 0) / fadeTime;
- }
- return fade;
- };
-
- // Position, fade and rotate the google squares and flowers, eggs.
- for (var yy = 0; yy < 3; ++yy) {
- for (var xx = 0; xx < 4; ++xx) {
- var index = yy * 4 + xx;
- var newIndex = (index + Math.floor(clock * 0.5)) % 12
- var offset = (newIndex == 0) ? (clock * 0.5 % 1) : 0;
-
- // compute the amount to fade the google squares.
- var fade = computeFade((clock + partOffset * 0) % cycle);
-
- // position and rotate the google squares.
- var image = g_googleSquares[newIndex];
- image.transform.identity();
- image.transform.translate(xx * 200, yy * 200, -2);
- image.transform.rotateZ(Math.PI * 2 * offset);
- image.setColor(Math.sin(index + clock * 2.2) * 0.2 + 0.6,
- Math.sin(index + clock * 3.3) * 0.2 + 0.6,
- Math.sin(index + clock * 4.4) * 0.2 + 0.6,
- fade);
-
- // compute the amount to fade the squares.
- fade = computeFade((clock + partOffset * 1) % cycle);
-
- // position and rotate the squares.
- var image = g_squares[index];
- image.setColor(1, 1, 1,
- fade * (Math.sin(index + clock) * 0.5 + 0.5));
- image.transform.identity();
- image.transform.translate(xx * 200 + 100, yy * 200 + 100, -1);
- image.transform.rotateZ(Math.PI * 2 * offset);
- image.transform.scale(1, Math.sin(clock * 2+ index), 1);
-
- // compute the amount to fade the things.
- fade = computeFade((clock + partOffset * 2) % cycle);
-
- // position, rotate and scale the things.
- var image = g_things[index];
- var nx = newIndex % 4;
- var ny = Math.floor(newIndex / 4);
- offset = clock * 0.5 % 1;
- image.transform.identity();
- image.transform.translate(nx * 300 - 200 + offset * 300,
- ny * 200 + 100 +
- Math.sin(clock * 4 + index * 2) * 50,
- 0);
- image.transform.rotateZ((0.1 + index * 0.1) * clock);
- var scale = Math.sin(index + clock) * 1.0 + 1.7;
- image.transform.scale(scale, scale, 1);
- image.setColor(1, 1, 1, fade);
- }
- }
-
- // Position and fade the 2d tile based game.
- {
- // This is NOT the best way to a 2d platformer but it does at least show
- // displaying the graphics of one.
-
- // compute the amount to fade the tiles and pillars.
- var fade = computeFade((clock + partOffset * 3) % cycle);
-
- // position the pillars
- for (var xx = 0; xx < 12; ++xx) {
- var image = g_pillars[xx];
- image.setColor(1, 1 , 1, fade);
- image.transform.identity();
- var xOffset =
- (g_pixelsAcrossPillarMap - g_pillarWidth * 2) -
- ((((xx + clock * 0.3) * 238) + g_pillarWidth) %
- g_pixelsAcrossPillarMap - g_pillarWidth);
- image.transform.translate(xOffset, 600 - 256 * g_pillarScale[xx],
- -6);
- image.transform.scale(1, g_pillarScale[xx], 1);
- }
-
- // position the tiles.
- for (var yy = 0; yy < g_tilesDown; ++yy) {
- for (var xx = 0; xx < g_tilesAcross; ++xx) {
- if (g_map[yy][xx]) {
- var image = g_tiles[yy][xx];
- image.setColor(1, 1, 1, fade);
- image.transform.identity();
- var xOffset =
- (g_pixelsAcrossMap - g_tileWidth * 2) -
- ((((xx + clock * 2) * g_tileWidth) + g_tileWidth) %
- g_pixelsAcrossMap - g_tileWidth);
- image.transform.translate(xOffset, yy * g_tileHeight, -5);
- }
- }
- }
-
- {
- // position the player.
- g_player.setColor(1, 1, 1, fade);
- var xOffset =
- (g_pixelsAcrossMap - g_tileWidth * 2) -
- (((((4.0 + clock * 2) * g_tileWidth) + g_tileWidth) %
- g_pixelsAcrossMap + g_tileWidth) - g_tileWidth);
- g_player.transform.identity();
- g_player.transform.translate(xOffset,
- 5 * g_tileHeight - g_playerHeight -
- Math.abs(Math.sin(clock * 5)) * 100,
- -4);
- }
- }
-}
-
-/**
- * Creates an Image object which is a transform and a child scaleTransform
- * scaled to match the texture
- *
- * @constructor
- * @param {!o3d.Texture} texture The texture
- * @param {boolean} opt_topLeft If true the origin of the image will be it's
- * topleft corner, the default is the center of the image.
- */
-function Image(texture, opt_topLeft) {
- // create a transform for positioning
- this.transform = g_pack.createObject('Transform');
- this.transform.parent = g_client.root;
-
- // create a transform for scaling to the size of the image just so
- // we don't have to manage that manually in the transform above.
- this.scaleTransform = g_pack.createObject('Transform');
- this.scaleTransform.parent = this.transform;
-
- // setup the sampler for the texture
- this.sampler = g_pack.createObject('Sampler');
- this.sampler.addressModeU = g_o3d.Sampler.CLAMP;
- this.sampler.addressModeV = g_o3d.Sampler.CLAMP;
- this.paramSampler = this.scaleTransform.createParam('texSampler0',
- 'ParamSampler');
- this.paramSampler.value = this.sampler;
-
- // Setup our UV offsets and color multiplier
- this.paramColorMult = this.scaleTransform.createParam('colorMult',
- 'ParamFloat4');
-
- this.setColor(1, 1, 1, 1);
-
- this.sampler.texture = texture;
- this.scaleTransform.addShape(g_planeShape);
- if (opt_topLeft) {
- this.scaleTransform.translate(texture.width / 2, texture.height / 2, 0);
- }
- this.scaleTransform.scale(texture.width, -texture.height, 1);
-}
-
-/**
- * Sets the color multiplier for the image.
- * @param {number} r Red component.
- * @param {number} g Green component.
- * @param {number} b Blue component.
- * @param {number} a Alpha component.
- */
-Image.prototype.setColor = function(r, g, b, a) {
- this.paramColorMult.set(r, g, b, a);
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body onload="init()" onunload="unload()">
-<h1>2D In O3D</h1>
-Doing 2D in O3D.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/GoogleIO-2009/assets/colorbar.png b/o3d/samples/GoogleIO-2009/assets/colorbar.png
deleted file mode 100644
index 629c378..0000000
--- a/o3d/samples/GoogleIO-2009/assets/colorbar.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/GoogleIO-2009/assets/style.css b/o3d/samples/GoogleIO-2009/assets/style.css
deleted file mode 100644
index 2c4a145..0000000
--- a/o3d/samples/GoogleIO-2009/assets/style.css
+++ /dev/null
@@ -1,8 +0,0 @@
-html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- font-family: Arial, sans-serif;
-}
-
diff --git a/o3d/samples/GoogleIO-2009/shaders/checker.shader b/o3d/samples/GoogleIO-2009/shaders/checker.shader
deleted file mode 100644
index a6c2ae8..0000000
--- a/o3d/samples/GoogleIO-2009/shaders/checker.shader
+++ /dev/null
@@ -1,111 +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.
- */
-
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-float4x4 world : WORLD;
-
-// light position
-float3 lightWorldPos;
-float3 lightColor;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float4 normal : NORMAL;
- float2 texcoord : TEXCOORD0;
-};
-
-// input parameters for our pixel shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0;
- float3 normal : TEXCOORD1;
- float3 worldPosition : TEXCOORD2;
-};
-
-// function for getting the checker pattern
-float4 checker(float2 uv) {
- float checkSize = 10;
- float fmodResult = fmod(floor(checkSize * uv.x) + floor(checkSize * uv.y),
- 2.0);
- return (fmodResult < 1) ?
- float4(0.4, 0.5, 0.5, 1) :
- float4(0.6, 0.8, 0.8, 1);
-}
-
-/**
- * Our vertex shader. In the vertex shader, we calculate the lighting.
- * Then we'll combine it with our checker pattern input the pixel shader.
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
-
- // Transform position into clip space.
- output.position = mul(input.position, worldViewProjection);
-
- // Transform normal into world space, where we can do lighting
- // calculations even if the world transform contains scaling.
- output.normal = mul(input.normal, worldInverseTranspose).xyz;
-
- // Calculate surface position in world space.
- output.worldPosition = mul(input.position, world).xyz;
-
- output.texcoord = input.texcoord;
-
- return output;
-}
-
-/**
- * Our pixel shader. We take the lighting color we got from the vertex sahder
- * and combine it with our checker pattern. We only need to use the x
- * coordinate of our input.col because we gave it uniform color
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
-
- float3 worldNormal = normalize(input.normal);
-
- // Apply diffuse lighting in world space in case the world transform
- // contains scaling.
- float4 check = checker(input.texcoord);
- float4 directionalIntensity = saturate(dot(worldNormal, surfaceToLight));
- float4 outColor = directionalIntensity * check;
- return float4(outColor.rgb, 1);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/GoogleIO-2009/step01ex.html b/o3d/samples/GoogleIO-2009/step01ex.html
deleted file mode 100644
index 8c131d0..0000000
--- a/o3d/samples/GoogleIO-2009/step01ex.html
+++ /dev/null
@@ -1,176 +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.
--->
-<!--
-Google I/O O3D Sample.
-
-This sample shows the steps to make a simple frame rate independent game.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Google I/O O3D Sample
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- font-family: Arial, sans-serif;
- }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_globalParams;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_eye = [15, 25, 50];
-var g_target = [0, 10, 0];
-var g_up = [0, 1, 0];
-var g_viewMatrix;
-
-/**
- * Updates the projection matrix.
- */
-function updateProjection() {
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_o3dWidth / g_o3dHeight, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-}
-
-/*
- * Updates the camera.
- */
-function updateCamera() {
- g_viewMatrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
- g_viewInfo.drawContext.view = g_viewMatrix;
-};
-
-/**
- * Updates global variables of the client's size if they have changed.
- */
-function updateClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (g_o3dWidth != newWidth || g_o3dHeight != newHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- updateProjection();
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- updateClientSize();
- updateCamera();
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table style="width: 100%; height:100%;">
- <tr style="height: 50px;"><td>
- <div style="width: 100%; height: 50px; font-size: large;">
- <img src="assets/colorbar.png" width="100%" height="10px"/><br/>
- Google I/O 2009 O3D Sample
- </div>
- </td></tr>
- <tr style="height: 100%;"><td>
- <div style="width: 100%; height: 100%;">
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- </div>
- </td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/GoogleIO-2009/step02ex.html b/o3d/samples/GoogleIO-2009/step02ex.html
deleted file mode 100644
index b2466ae..0000000
--- a/o3d/samples/GoogleIO-2009/step02ex.html
+++ /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.
--->
-<!--
-Google I/O O3D Sample.
-
-This sample shows the steps to make a simple frame rate independent game.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Google I/O O3D Sample
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- font-family: Arial, sans-serif;
- }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_playerTransform;
-var g_globalParams;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_eye = [15, 25, 50];
-var g_target = [0, 10, 0];
-var g_up = [0, 1, 0];
-var g_viewMatrix;
-
-/**
- * Updates the projection matrix.
- */
-function updateProjection() {
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_o3dWidth / g_o3dHeight, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-}
-
-/*
- * Updates the camera.
- */
-function updateCamera() {
- g_viewMatrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
- g_viewInfo.drawContext.view = g_viewMatrix;
-};
-
-/**
- * Updates global variables of the client's size if they have changed.
- */
-function updateClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (g_o3dWidth != newWidth || g_o3dHeight != newHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- updateProjection();
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- updateClientSize();
- updateCamera();
-
- var redMaterial = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [0.2, 1, 0.2, 1]); // green
-
- var checkerMaterial = o3djs.material.createMaterialFromFile(
- g_pack, 'shaders/checker.shader', g_viewInfo.performanceDrawList);
-
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Create a cylinder.
- var shape = o3djs.primitives.createCylinder(
- g_pack, redMaterial, 2.5, 5, 20, 1,
- g_math.matrix4.translation([0, 2.5, 0]));
- g_playerTransform = g_pack.createObject('Transform');
- g_playerTransform.parent = g_root;
- g_playerTransform.addShape(shape);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table style="width: 100%; height:100%;">
- <tr style="height: 50px;"><td>
- <div style="width: 100%; height: 50px; font-size: large;">
- <img src="assets/colorbar.png" width="100%" height="10px"/><br/>
- Google I/O 2009 O3D Sample
- </div>
- </td></tr>
- <tr style="height: 100%;"><td>
- <div style="width: 100%; height: 100%;">
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- </div>
- </td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/GoogleIO-2009/step03ex.html b/o3d/samples/GoogleIO-2009/step03ex.html
deleted file mode 100644
index 0de8221..0000000
--- a/o3d/samples/GoogleIO-2009/step03ex.html
+++ /dev/null
@@ -1,254 +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.
--->
-<!--
-Google I/O O3D Sample.
-
-This sample shows the steps to make a simple frame rate independent game.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Google I/O O3D Sample
-</title>
-<link rel="stylesheet" type="text/css" href="assets/style.css" />
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_globalParams;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_keyDown = []; // which keys are down by key code.
-var g_playerTransform;
-var g_playerXPosition = 0;
-var g_playerZPosition = 0;
-var g_eye = [15, 25, 50];
-var g_target = [0, 10, 0];
-var g_up = [0, 1, 0];
-var g_viewMatrix;
-
-/**
- * Updates the projection matrix.
- */
-function updateProjection() {
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_o3dWidth / g_o3dHeight, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-}
-
-/*
- * Updates the camera.
- */
-function updateCamera() {
- g_viewMatrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
- g_viewInfo.drawContext.view = g_viewMatrix;
-};
-
-/**
- * Updates global variables of the client's size if they have changed.
- */
-function updateClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (g_o3dWidth != newWidth || g_o3dHeight != newHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- updateProjection();
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- updateCamera();
-
- var redMaterial = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [0.2, 1, 0.2, 1]); // green
-
- var checkerMaterial = o3djs.material.createMaterialFromFile(
- g_pack, 'shaders/checker.shader', g_viewInfo.performanceDrawList);
-
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Create a cylinder.
- var shape = o3djs.primitives.createCylinder(
- g_pack, redMaterial, 2.5, 5, 20, 1,
- g_math.matrix4.translation([0, 2.5, 0]));
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- g_playerTransform = transform;
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- o3djs.event.addEventListener(g_o3dElement, 'keydown', onKeyDown);
- o3djs.event.addEventListener(g_o3dElement, 'keyup', onKeyUp);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Tracks key down events.
- * @param {Event} e keyboard event.
- */
-function onKeyDown(e) {
- g_keyDown[e.keyCode] = true;
-}
-
-/**
- * Tracks key up events.
- * @param {Event} e keyboard event.
- */
-function onKeyUp(e) {
- g_keyDown[e.keyCode] = false;
-}
-
-/**
- * Look at keys.
- */
-function handleMoveKeys() {
- var directionX = 0;
- var directionZ = 0;
-
- if (g_keyDown[37] || g_keyDown[65]) { directionX = -3; }
- if (g_keyDown[39] || g_keyDown[68]) { directionX = 3; }
- if (g_keyDown[38] || g_keyDown[87]) { directionZ = -3; }
- if (g_keyDown[40] || g_keyDown[83]) { directionZ = 3; }
-
- g_playerXPosition += directionX;
- g_playerZPosition += directionZ;
-
- g_playerTransform.identity();
- g_playerTransform.translate(g_playerXPosition, 0, g_playerZPosition);
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- updateClientSize();
- handleMoveKeys();
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table style="width: 100%; height:100%;">
- <tr style="height: 50px;"><td>
- <div style="width: 100%; height: 50px; font-size: large;">
- <img src="assets/colorbar.png" width="100%" height="10px"/><br/>
- Google I/O 2009 O3D Sample
- </div>
- </td></tr>
- <tr style="height: 100%;"><td>
- <div style="width: 100%; height: 100%;">
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- </div>
- </td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/GoogleIO-2009/step04ex.html b/o3d/samples/GoogleIO-2009/step04ex.html
deleted file mode 100644
index a72259f..0000000
--- a/o3d/samples/GoogleIO-2009/step04ex.html
+++ /dev/null
@@ -1,264 +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.
--->
-<!--
-Google I/O O3D Sample.
-
-This sample shows the steps to make a simple frame rate independent game.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Google I/O O3D Sample
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- font-family: Arial, sans-serif;
- }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// constants
-var MOVE_VELOCITY = 25; // in units per second.
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_globalParams;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_keyDown = []; // which keys are down by key code.
-var g_playerTransform;
-var g_playerXPosition = 0;
-var g_playerZPosition = 0;
-var g_eye = [15, 25, 50];
-var g_target = [0, 10, 0];
-var g_up = [0, 1, 0];
-var g_viewMatrix;
-
-/**
- * Updates the projection matrix.
- */
-function updateProjection() {
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_o3dWidth / g_o3dHeight, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-}
-
-/*
- * Updates the camera.
- */
-function updateCamera() {
- g_viewMatrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
- g_viewInfo.drawContext.view = g_viewMatrix;
-};
-
-/**
- * Updates global variables of the client's size if they have changed.
- */
-function updateClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (g_o3dWidth != newWidth || g_o3dHeight != newHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- updateProjection();
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- updateCamera();
-
- var redMaterial = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [0.2, 1, 0.2, 1]); // green
-
- var checkerMaterial = o3djs.material.createMaterialFromFile(
- g_pack, 'shaders/checker.shader', g_viewInfo.performanceDrawList);
-
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Create a cylinder.
- var shape = o3djs.primitives.createCylinder(
- g_pack, redMaterial, 2.5, 5, 20, 1,
- g_math.matrix4.translation([0, 2.5, 0]));
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- g_playerTransform = transform;
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- o3djs.event.addEventListener(g_o3dElement, 'keydown', onKeyDown);
- o3djs.event.addEventListener(g_o3dElement, 'keyup', onKeyUp);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Tracks key down events.
- * @param {Event} e keyboard event.
- */
-function onKeyDown(e) {
- g_keyDown[e.keyCode] = true;
-}
-
-/**
- * Tracks key up events.
- * @param {Event} e keyboard event.
- */
-function onKeyUp(e) {
- g_keyDown[e.keyCode] = false;
-}
-
-/**
- * Look at keys.
- */
-function handleMoveKeys(elapsedTime) {
- var directionX = 0;
- var directionZ = 0;
-
- if (g_keyDown[37] || g_keyDown[65]) { directionX = -1; }
- if (g_keyDown[39] || g_keyDown[68]) { directionX = 1; }
- if (g_keyDown[38] || g_keyDown[87]) { directionZ = -1; }
- if (g_keyDown[40] || g_keyDown[83]) { directionZ = 1; }
-
- g_playerXPosition += MOVE_VELOCITY * directionX * elapsedTime;
- g_playerZPosition += MOVE_VELOCITY * directionZ * elapsedTime;
-
- g_playerTransform.identity();
- g_playerTransform.translate(g_playerXPosition, 0, g_playerZPosition);
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- updateClientSize();
- handleMoveKeys(elapsedTime);
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table style="width: 100%; height:100%;">
- <tr style="height: 50px;"><td>
- <div style="width: 100%; height: 50px; font-size: large;">
- <img src="assets/colorbar.png" width="100%" height="10px"/><br/>
- Google I/O 2009 O3D Sample
- </div>
- </td></tr>
- <tr style="height: 100%;"><td>
- <div style="width: 100%; height: 100%;">
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- </div>
- </td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/GoogleIO-2009/step05ex.html b/o3d/samples/GoogleIO-2009/step05ex.html
deleted file mode 100644
index 4dfb4cc..0000000
--- a/o3d/samples/GoogleIO-2009/step05ex.html
+++ /dev/null
@@ -1,292 +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.
--->
-<!--
-Google I/O O3D Sample.
-
-This sample shows the steps to make a simple frame rate independent game.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Google I/O O3D Sample
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- font-family: Arial, sans-serif;
- }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// constants
-var MOVE_VELOCITY = 25; // in units per second.
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_globalParams;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_keyDown = []; // which keys are down by key code.
-var g_playerTransform;
-var g_playerXPosition = 0;
-var g_playerZPosition = 0;
-var g_eye = [15, 25, 50];
-var g_target = [0, 10, 0];
-var g_up = [0, 1, 0];
-var g_viewMatrix;
-var g_moveMatrix;
-
-/**
- * Updates the projection matrix.
- */
-function updateProjection() {
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_o3dWidth / g_o3dHeight, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-}
-
-/**
- * Given a view matrix computes an movement matrix to make it easy
- * to move something relative to the camera view in the XZ plane.
- * @param {!o3djs.math.Matrix4} viewMatrix A view matrix.
- * @return {!o3djs.math.Matrix4} A movement matrix.
- */
-function computeMoveMatrixFromViewMatrix(viewMatrix) {
- var cameraMatrix = g_math.matrix4.inverse(viewMatrix);
- var xAxis = g_math.cross([0, 1, 0], cameraMatrix[2].slice(0, 3));
- var zAxis = g_math.cross(xAxis, [0, 1, 0]);
- return [
- xAxis.concat(0),
- [0, 1, 0, 0],
- zAxis.concat(0),
- [0, 0, 0, 1]];
-}
-
-/*
- * Updates the camera.
- */
-function updateCamera() {
- g_viewMatrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
- g_viewInfo.drawContext.view = g_viewMatrix;
- g_moveMatrix = computeMoveMatrixFromViewMatrix(g_viewMatrix);
-};
-
-/**
- * Updates global variables of the client's size if they have changed.
- */
-function updateClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (g_o3dWidth != newWidth || g_o3dHeight != newHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- updateProjection();
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- updateCamera();
-
- var redMaterial = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [0.2, 1, 0.2, 1]); // green
-
- var checkerMaterial = o3djs.material.createMaterialFromFile(
- g_pack, 'shaders/checker.shader', g_viewInfo.performanceDrawList);
-
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Create a cylinder.
- var shape = o3djs.primitives.createCylinder(
- g_pack, redMaterial, 2.5, 5, 20, 1,
- g_math.matrix4.translation([0, 2.5, 0]));
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- g_playerTransform = transform;
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- o3djs.event.addEventListener(g_o3dElement, 'keydown', onKeyDown);
- o3djs.event.addEventListener(g_o3dElement, 'keyup', onKeyUp);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Tracks key down events.
- * @param {Event} e keyboard event.
- */
-function onKeyDown(e) {
- g_keyDown[e.keyCode] = true;
-}
-
-/**
- * Tracks key up events.
- * @param {Event} e keyboard event.
- */
-function onKeyUp(e) {
- g_keyDown[e.keyCode] = false;
-}
-
-/**
- * Look at keys.
- */
-function handleMoveKeys(elapsedTime) {
- var directionX = 0;
- var directionZ = 0;
-
- if (g_keyDown[37] || g_keyDown[65]) { directionX = -1; }
- if (g_keyDown[39] || g_keyDown[68]) { directionX = 1; }
- if (g_keyDown[38] || g_keyDown[87]) { directionZ = -1; }
- if (g_keyDown[40] || g_keyDown[83]) { directionZ = 1; }
-
- if (directionX != 0 || directionZ != 0) {
- var moveTranslation = g_math.matrix4.transformPoint(
- g_moveMatrix,
- [MOVE_VELOCITY * directionX * elapsedTime,
- 0,
- MOVE_VELOCITY * directionZ * elapsedTime]);
-
- g_playerXPosition += moveTranslation[0];
- g_playerZPosition += moveTranslation[2];
-
- g_playerTransform.identity();
- g_playerTransform.translate(g_playerXPosition, 0, g_playerZPosition);
- }
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- updateClientSize();
- handleMoveKeys(elapsedTime);
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table style="width: 100%; height:100%;">
- <tr style="height: 50px;"><td>
- <div style="width: 100%; height: 50px; font-size: large;">
- <img src="assets/colorbar.png" width="100%" height="10px"/><br/>
- Google I/O 2009 O3D Sample
- </div>
- </td></tr>
- <tr style="height: 100%;"><td>
- <div style="width: 100%; height: 100%;">
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- </div>
- </td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/GoogleIO-2009/step06ex.html b/o3d/samples/GoogleIO-2009/step06ex.html
deleted file mode 100644
index e61c868..0000000
--- a/o3d/samples/GoogleIO-2009/step06ex.html
+++ /dev/null
@@ -1,301 +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.
--->
-<!--
-Google I/O O3D Sample.
-
-This sample shows the steps to make a simple frame rate independent game.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Google I/O O3D Sample
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- font-family: Arial, sans-serif;
- }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// constants
-var MOVE_VELOCITY = 25; // in units per second.
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_globalParams;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_keyDown = []; // which keys are down by key code.
-var g_playerTransform;
-var g_playerXPosition = 0;
-var g_playerZPosition = 0;
-var g_eye = [15, 25, 50];
-var g_target = [0, 10, 0];
-var g_up = [0, 1, 0];
-var g_viewMatrix;
-var g_moveMatrix;
-
-/**
- * Updates the projection matrix.
- */
-function updateProjection() {
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_o3dWidth / g_o3dHeight, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-}
-
-/**
- * Given a view matrix computes an movement matrix to make it easy
- * to move something relative to the camera view in the XZ plane.
- * @param {!o3djs.math.Matrix4} viewMatrix A view matrix.
- * @return {!o3djs.math.Matrix4} A movement matrix.
- */
-function computeMoveMatrixFromViewMatrix(viewMatrix) {
- var cameraMatrix = g_math.matrix4.inverse(viewMatrix);
- var xAxis = g_math.cross([0, 1, 0], cameraMatrix[2].slice(0, 3));
- var zAxis = g_math.cross(xAxis, [0, 1, 0]);
- return [
- xAxis.concat(0),
- [0, 1, 0, 0],
- zAxis.concat(0),
- [0, 0, 0, 1]];
-}
-
-/*
- * Updates the camera.
- */
-function updateCamera() {
- g_viewMatrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
- g_viewInfo.drawContext.view = g_viewMatrix;
- g_moveMatrix = computeMoveMatrixFromViewMatrix(g_viewMatrix);
-};
-
-/**
- * Updates global variables of the client's size if they have changed.
- */
-function updateClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (g_o3dWidth != newWidth || g_o3dHeight != newHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- updateProjection();
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- updateCamera();
-
- var redMaterial = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [0.2, 1, 0.2, 1]); // green
-
- var checkerMaterial = o3djs.material.createMaterialFromFile(
- g_pack, 'shaders/checker.shader', g_viewInfo.performanceDrawList);
-
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Create a cylinder.
- var shape = o3djs.primitives.createCylinder(
- g_pack, redMaterial, 2.5, 5, 20, 1,
- g_math.matrix4.translation([0, 2.5, 0]));
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- g_playerTransform = transform;
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- o3djs.event.addEventListener(g_o3dElement, 'keydown', onKeyDown);
- o3djs.event.addEventListener(g_o3dElement, 'keyup', onKeyUp);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Tracks key down events.
- * @param {Event} e keyboard event.
- */
-function onKeyDown(e) {
- g_keyDown[e.keyCode] = true;
-}
-
-/**
- * Tracks key up events.
- * @param {Event} e keyboard event.
- */
-function onKeyUp(e) {
- g_keyDown[e.keyCode] = false;
-}
-
-/**
- * Look at keys.
- */
-function handleMoveKeys(elapsedTime) {
- var directionX = 0;
- var directionZ = 0;
-
- if (g_keyDown[37] || g_keyDown[65]) { directionX = -1; }
- if (g_keyDown[39] || g_keyDown[68]) { directionX = 1; }
- if (g_keyDown[38] || g_keyDown[87]) { directionZ = -1; }
- if (g_keyDown[40] || g_keyDown[83]) { directionZ = 1; }
-
- if (directionX != 0 || directionZ != 0) {
- var moveTranslation = g_math.matrix4.transformPoint(
- g_moveMatrix,
- [MOVE_VELOCITY * directionX * elapsedTime,
- 0,
- MOVE_VELOCITY * directionZ * elapsedTime]);
-
- g_playerXPosition += moveTranslation[0];
- g_playerZPosition += moveTranslation[2];
-
- g_playerTransform.identity();
- g_playerTransform.translate(g_playerXPosition, 0, g_playerZPosition);
- }
-}
-
-/**
- * Move the camera.
- */
-function moveCamera() {
- g_target = [g_playerXPosition, 10, g_playerZPosition];
- updateCamera();
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- updateClientSize();
- handleMoveKeys(elapsedTime);
- moveCamera();
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table style="width: 100%; height:100%;">
- <tr style="height: 50px;"><td>
- <div style="width: 100%; height: 50px; font-size: large;">
- <img src="assets/colorbar.png" width="100%" height="10px"/><br/>
- Google I/O 2009 O3D Sample
- </div>
- </td></tr>
- <tr style="height: 100%;"><td>
- <div style="width: 100%; height: 100%;">
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- </div>
- </td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/GoogleIO-2009/step07ex.html b/o3d/samples/GoogleIO-2009/step07ex.html
deleted file mode 100644
index 31f5a74..0000000
--- a/o3d/samples/GoogleIO-2009/step07ex.html
+++ /dev/null
@@ -1,302 +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.
--->
-<!--
-Google I/O O3D Sample.
-
-This sample shows the steps to make a simple frame rate independent game.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Google I/O O3D Sample
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- font-family: Arial, sans-serif;
- }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// constants
-var MOVE_VELOCITY = 25; // in units per second.
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_globalParams;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_keyDown = []; // which keys are down by key code.
-var g_playerTransform;
-var g_playerXPosition = 0;
-var g_playerZPosition = 0;
-var g_eye = [15, 25, 50];
-var g_target = [0, 10, 0];
-var g_up = [0, 1, 0];
-var g_viewMatrix;
-var g_moveMatrix;
-
-/**
- * Updates the projection matrix.
- */
-function updateProjection() {
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_o3dWidth / g_o3dHeight, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-}
-
-/**
- * Given a view matrix computes an movement matrix to make it easy
- * to move something relative to the camera view in the XZ plane.
- * @param {!o3djs.math.Matrix4} viewMatrix A view matrix.
- * @return {!o3djs.math.Matrix4} A movement matrix.
- */
-function computeMoveMatrixFromViewMatrix(viewMatrix) {
- var cameraMatrix = g_math.matrix4.inverse(viewMatrix);
- var xAxis = g_math.cross([0, 1, 0], cameraMatrix[2].slice(0, 3));
- var zAxis = g_math.cross(xAxis, [0, 1, 0]);
- return [
- xAxis.concat(0),
- [0, 1, 0, 0],
- zAxis.concat(0),
- [0, 0, 0, 1]];
-}
-
-/*
- * Updates the camera.
- */
-function updateCamera() {
- g_viewMatrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
- g_viewInfo.drawContext.view = g_viewMatrix;
- g_moveMatrix = computeMoveMatrixFromViewMatrix(g_viewMatrix);
-};
-
-/**
- * Updates global variables of the client's size if they have changed.
- */
-function updateClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (g_o3dWidth != newWidth || g_o3dHeight != newHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- updateProjection();
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- updateCamera();
-
- var redMaterial = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [0.2, 1, 0.2, 1]); // green
-
- var checkerMaterial = o3djs.material.createMaterialFromFile(
- g_pack, 'shaders/checker.shader', g_viewInfo.performanceDrawList);
-
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Create a cylinder.
- var shape = o3djs.primitives.createCylinder(
- g_pack, redMaterial, 2.5, 5, 20, 1,
- g_math.matrix4.translation([0, 2.5, 0]));
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- g_playerTransform = transform;
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- o3djs.event.addEventListener(g_o3dElement, 'keydown', onKeyDown);
- o3djs.event.addEventListener(g_o3dElement, 'keyup', onKeyUp);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Tracks key down events.
- * @param {Event} e keyboard event.
- */
-function onKeyDown(e) {
- g_keyDown[e.keyCode] = true;
-}
-
-/**
- * Tracks key up events.
- * @param {Event} e keyboard event.
- */
-function onKeyUp(e) {
- g_keyDown[e.keyCode] = false;
-}
-
-/**
- * Look at keys.
- */
-function handleMoveKeys(elapsedTime) {
- var directionX = 0;
- var directionZ = 0;
-
- if (g_keyDown[37] || g_keyDown[65]) { directionX = -1; }
- if (g_keyDown[39] || g_keyDown[68]) { directionX = 1; }
- if (g_keyDown[38] || g_keyDown[87]) { directionZ = -1; }
- if (g_keyDown[40] || g_keyDown[83]) { directionZ = 1; }
-
- if (directionX != 0 || directionZ != 0) {
- var moveTranslation = g_math.matrix4.transformPoint(
- g_moveMatrix,
- [MOVE_VELOCITY * directionX * elapsedTime,
- 0,
- MOVE_VELOCITY * directionZ * elapsedTime]);
-
- g_playerXPosition += moveTranslation[0];
- g_playerZPosition += moveTranslation[2];
-
- g_playerTransform.identity();
- g_playerTransform.translate(g_playerXPosition, 0, g_playerZPosition);
- }
-}
-
-/**
- * Move the camera.
- */
-function moveCamera() {
- var newTarget = [g_playerXPosition, 10, g_playerZPosition];
- g_target = g_math.lerpVector(g_target, newTarget, 0.03);
- updateCamera();
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- updateClientSize();
- handleMoveKeys(elapsedTime);
- moveCamera();
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table style="width: 100%; height:100%;">
- <tr style="height: 50px;"><td>
- <div style="width: 100%; height: 50px; font-size: large;">
- <img src="assets/colorbar.png" width="100%" height="10px"/><br/>
- Google I/O 2009 O3D Sample
- </div>
- </td></tr>
- <tr style="height: 100%;"><td>
- <div style="width: 100%; height: 100%;">
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- </div>
- </td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/GoogleIO-2009/step08ex.html b/o3d/samples/GoogleIO-2009/step08ex.html
deleted file mode 100644
index f0426fb..0000000
--- a/o3d/samples/GoogleIO-2009/step08ex.html
+++ /dev/null
@@ -1,330 +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.
--->
-<!--
-Google I/O O3D Sample.
-
-This sample shows the steps to make a simple frame rate independent game.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Google I/O O3D Sample
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- font-family: Arial, sans-serif;
- }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// constants
-var MOVE_VELOCITY = 25; // in units per second.
-var JUMP_VELOCITY = 100;
-var GRAVITY = -500;
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_globalParams;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_keyDown = []; // which keys are down by key code.
-var g_playerTransform;
-var g_playerXPosition = 0;
-var g_playerYPosition = 0;
-var g_playerZPosition = 0;
-var g_eye = [15, 25, 50];
-var g_target = [0, 10, 0];
-var g_up = [0, 1, 0];
-var g_viewMatrix;
-var g_moveMatrix;
-var g_canJump = true;
-var g_jumping = false;
-var g_playerYVelocity = 0;
-
-/**
- * Updates the projection matrix.
- */
-function updateProjection() {
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_o3dWidth / g_o3dHeight, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-}
-
-/**
- * Given a view matrix computes an movement matrix to make it easy
- * to move something relative to the camera view in the XZ plane.
- * @param {!o3djs.math.Matrix4} viewMatrix A view matrix.
- * @return {!o3djs.math.Matrix4} A movement matrix.
- */
-function computeMoveMatrixFromViewMatrix(viewMatrix) {
- var cameraMatrix = g_math.matrix4.inverse(viewMatrix);
- var xAxis = g_math.cross([0, 1, 0], cameraMatrix[2].slice(0, 3));
- var zAxis = g_math.cross(xAxis, [0, 1, 0]);
- return [
- xAxis.concat(0),
- [0, 1, 0, 0],
- zAxis.concat(0),
- [0, 0, 0, 1]];
-}
-
-/*
- * Updates the camera.
- */
-function updateCamera() {
- g_viewMatrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
- g_viewInfo.drawContext.view = g_viewMatrix;
- g_moveMatrix = computeMoveMatrixFromViewMatrix(g_viewMatrix);
-};
-
-/**
- * Updates global variables of the client's size if they have changed.
- */
-function updateClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (g_o3dWidth != newWidth || g_o3dHeight != newHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- updateProjection();
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- updateCamera();
-
- var redMaterial = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [0.2, 1, 0.2, 1]); // green
-
- var checkerMaterial = o3djs.material.createMaterialFromFile(
- g_pack, 'shaders/checker.shader', g_viewInfo.performanceDrawList);
-
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Create a cylinder.
- var shape = o3djs.primitives.createCylinder(
- g_pack, redMaterial, 2.5, 5, 20, 1,
- g_math.matrix4.translation([0, 2.5, 0]));
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- g_playerTransform = transform;
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- o3djs.event.addEventListener(g_o3dElement, 'keydown', onKeyDown);
- o3djs.event.addEventListener(g_o3dElement, 'keyup', onKeyUp);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Tracks key down events.
- * @param {Event} e keyboard event.
- */
-function onKeyDown(e) {
- g_keyDown[e.keyCode] = true;
-}
-
-/**
- * Tracks key up events.
- * @param {Event} e keyboard event.
- */
-function onKeyUp(e) {
- g_keyDown[e.keyCode] = false;
-}
-
-/**
- * Look at keys.
- */
-function handleMoveKeys(elapsedTime) {
- var directionX = 0;
- var directionZ = 0;
-
- if (g_keyDown[37] || g_keyDown[65]) { directionX = -1; }
- if (g_keyDown[39] || g_keyDown[68]) { directionX = 1; }
- if (g_keyDown[38] || g_keyDown[87]) { directionZ = -1; }
- if (g_keyDown[40] || g_keyDown[83]) { directionZ = 1; }
-
- if (g_canJump) {
- if (g_keyDown[32]) {
- g_jumping = true;
- g_canJump = false;
- g_playerYVelocity = JUMP_VELOCITY;
- }
- } else {
- if (g_jumping) {
- g_playerYVelocity += GRAVITY * elapsedTime;
- g_playerYPosition += g_playerYVelocity * elapsedTime;
- if (g_playerYPosition <= 0) {
- g_playerYPosition = 0;
- g_jumping = false;
- }
- } else {
- if (!g_keyDown[32]) {
- g_canJump = true;
- }
- }
- }
-
- if (directionX != 0 || directionZ != 0) {
- var moveTranslation = g_math.matrix4.transformPoint(
- g_moveMatrix,
- [MOVE_VELOCITY * directionX * elapsedTime,
- 0,
- MOVE_VELOCITY * directionZ * elapsedTime]);
-
- g_playerXPosition += moveTranslation[0];
- g_playerZPosition += moveTranslation[2];
- }
-
- g_playerTransform.identity();
- g_playerTransform.translate(
- g_playerXPosition, g_playerYPosition, g_playerZPosition);
-}
-
-/**
- * Move the camera.
- */
-function moveCamera() {
- var newTarget = [g_playerXPosition, 10, g_playerZPosition];
- g_target = g_math.lerpVector(g_target, newTarget, 0.03);
- updateCamera();
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- updateClientSize();
- handleMoveKeys(elapsedTime);
- moveCamera();
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table style="width: 100%; height:100%;">
- <tr style="height: 50px;"><td>
- <div style="width: 100%; height: 50px; font-size: large;">
- <img src="assets/colorbar.png" width="100%" height="10px"/><br/>
- Google I/O 2009 O3D Sample
- </div>
- </td></tr>
- <tr style="height: 100%;"><td>
- <div style="width: 100%; height: 100%;">
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- </div>
- </td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/GoogleIO-2009/step09ex.html b/o3d/samples/GoogleIO-2009/step09ex.html
deleted file mode 100644
index 6e1afb7..0000000
--- a/o3d/samples/GoogleIO-2009/step09ex.html
+++ /dev/null
@@ -1,358 +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.
--->
-<!--
-Google I/O O3D Sample.
-
-This sample shows the steps to make a simple frame rate independent game.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Google I/O O3D Sample
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- font-family: Arial, sans-serif;
- }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.particles');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// constants
-var MOVE_VELOCITY = 25; // in units per second.
-var JUMP_VELOCITY = 100;
-var GRAVITY = -500;
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_globalParams;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_keyDown = []; // which keys are down by key code.
-var g_playerTransform;
-var g_playerXPosition = 0;
-var g_playerYPosition = 0;
-var g_playerZPosition = 0;
-var g_eye = [15, 25, 50];
-var g_target = [0, 10, 0];
-var g_up = [0, 1, 0];
-var g_viewMatrix;
-var g_moveMatrix;
-var g_canJump = true;
-var g_jumping = false;
-var g_playerYVelocity = 0;
-var g_particleSystem;
-var g_poofEmitter;
-var g_poof;
-
-/**
- * Updates the projection matrix.
- */
-function updateProjection() {
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_o3dWidth / g_o3dHeight, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-}
-
-/**
- * Given a view matrix computes an movement matrix to make it easy
- * to move something relative to the camera view in the XZ plane.
- * @param {!o3djs.math.Matrix4} viewMatrix A view matrix.
- * @return {!o3djs.math.Matrix4} A movement matrix.
- */
-function computeMoveMatrixFromViewMatrix(viewMatrix) {
- var cameraMatrix = g_math.matrix4.inverse(viewMatrix);
- var xAxis = g_math.cross([0, 1, 0], cameraMatrix[2].slice(0, 3));
- var zAxis = g_math.cross(xAxis, [0, 1, 0]);
- return [
- xAxis.concat(0),
- [0, 1, 0, 0],
- zAxis.concat(0),
- [0, 0, 0, 1]];
-}
-
-/*
- * Updates the camera.
- */
-function updateCamera() {
- g_viewMatrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
- g_viewInfo.drawContext.view = g_viewMatrix;
- g_moveMatrix = computeMoveMatrixFromViewMatrix(g_viewMatrix);
-};
-
-/**
- * Updates global variables of the client's size if they have changed.
- */
-function updateClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (g_o3dWidth != newWidth || g_o3dHeight != newHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- updateProjection();
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- updateCamera();
-
- var redMaterial = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [0.2, 1, 0.2, 1]); // green
-
- var checkerMaterial = o3djs.material.createMaterialFromFile(
- g_pack, 'shaders/checker.shader', g_viewInfo.performanceDrawList);
-
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Create a cylinder.
- var shape = o3djs.primitives.createCylinder(
- g_pack, redMaterial, 2.5, 5, 20, 1,
- g_math.matrix4.translation([0, 2.5, 0]));
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- g_playerTransform = transform;
-
- g_particleSystem = o3djs.particles.createParticleSystem(g_pack, g_viewInfo);
- g_poofEmitter = g_particleSystem.createParticleEmitter();
- g_poofEmitter.setState(o3djs.particles.ParticleStateIds.ADD);
- g_poofEmitter.setColorRamp(
- [1, 1, 1, 0.3,
- 1, 1, 1, 0]);
- g_poofEmitter.setParameters({
- numParticles: 30,
- lifeTime: 0.5,
- startTime: 0,
- startSize: 5,
- endSize: 10,
- spinSpeedRange: 10},
- function(index, parameters) {
- var angle = Math.random() * 2 * Math.PI;
- parameters.velocity = g_math.matrix4.transformPoint(
- g_math.matrix4.rotationY(angle), [25, 2.5, 0]);
- parameters.acceleration = g_math.mulVectorVector(
- parameters.velocity, [-1.5, 1, -1.5]);
- });
- g_poof = g_poofEmitter.createOneShot(g_root);
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- o3djs.event.addEventListener(g_o3dElement, 'keydown', onKeyDown);
- o3djs.event.addEventListener(g_o3dElement, 'keyup', onKeyUp);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Tracks key down events.
- * @param {Event} e keyboard event.
- */
-function onKeyDown(e) {
- g_keyDown[e.keyCode] = true;
-}
-
-/**
- * Tracks key up events.
- * @param {Event} e keyboard event.
- */
-function onKeyUp(e) {
- g_keyDown[e.keyCode] = false;
-}
-
-/**
- * Look at keys.
- */
-function handleMoveKeys(elapsedTime) {
- var directionX = 0;
- var directionZ = 0;
-
- if (g_keyDown[37] || g_keyDown[65]) { directionX = -1; }
- if (g_keyDown[39] || g_keyDown[68]) { directionX = 1; }
- if (g_keyDown[38] || g_keyDown[87]) { directionZ = -1; }
- if (g_keyDown[40] || g_keyDown[83]) { directionZ = 1; }
-
- if (g_canJump) {
- if (g_keyDown[32]) {
- g_jumping = true;
- g_canJump = false;
- g_playerYVelocity = JUMP_VELOCITY;
- }
- } else {
- if (g_jumping) {
- g_playerYVelocity += GRAVITY * elapsedTime;
- g_playerYPosition += g_playerYVelocity * elapsedTime;
- if (g_playerYPosition <= 0) {
- g_playerYPosition = 0;
- g_poof.trigger(
- [g_playerXPosition, g_playerYPosition, g_playerZPosition]);
- g_jumping = false;
- }
- } else {
- if (!g_keyDown[32]) {
- g_canJump = true;
- }
- }
- }
-
- if (directionX != 0 || directionZ != 0) {
- var moveTranslation = g_math.matrix4.transformPoint(
- g_moveMatrix,
- [MOVE_VELOCITY * directionX * elapsedTime,
- 0,
- MOVE_VELOCITY * directionZ * elapsedTime]);
-
- g_playerXPosition += moveTranslation[0];
- g_playerZPosition += moveTranslation[2];
- }
-
- g_playerTransform.identity();
- g_playerTransform.translate(
- g_playerXPosition, g_playerYPosition, g_playerZPosition);
-}
-
-/**
- * Move the camera.
- */
-function moveCamera() {
- var newTarget = [g_playerXPosition, 10, g_playerZPosition];
- g_target = g_math.lerpVector(g_target, newTarget, 0.03);
- updateCamera();
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- updateClientSize();
- handleMoveKeys(elapsedTime);
- moveCamera();
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table style="width: 100%; height:100%;">
- <tr style="height: 50px;"><td>
- <div style="width: 100%; height: 50px; font-size: large;">
- <img src="assets/colorbar.png" width="100%" height="10px"/><br/>
- Google I/O 2009 O3D Sample
- </div>
- </td></tr>
- <tr style="height: 100%;"><td>
- <div style="width: 100%; height: 100%;">
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- </div>
- </td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/GoogleIO-2009/step10ex.html b/o3d/samples/GoogleIO-2009/step10ex.html
deleted file mode 100644
index 7e92911..0000000
--- a/o3d/samples/GoogleIO-2009/step10ex.html
+++ /dev/null
@@ -1,361 +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.
--->
-<!--
-Google I/O O3D Sample.
-
-This sample shows the steps to make a simple frame rate independent game.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Google I/O O3D Sample
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- font-family: Arial, sans-serif;
- }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.particles');
-o3djs.require('o3djs.scene');
-o3djs.require('o3djs.pack');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// constants
-var MOVE_VELOCITY = 25; // in units per second.
-var JUMP_VELOCITY = 100;
-var GRAVITY = -500;
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_globalParams;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_keyDown = []; // which keys are down by key code.
-var g_playerTransform;
-var g_playerXPosition = 0;
-var g_playerYPosition = 0;
-var g_playerZPosition = 0;
-var g_eye = [15, 25, 50];
-var g_target = [0, 10, 0];
-var g_up = [0, 1, 0];
-var g_viewMatrix;
-var g_moveMatrix;
-var g_canJump = true;
-var g_jumping = false;
-var g_playerYVelocity = 0;
-var g_particleSystem;
-var g_poofEmitter;
-var g_poof;
-
-/**
- * Updates the projection matrix.
- */
-function updateProjection() {
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_o3dWidth / g_o3dHeight, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-}
-
-/**
- * Given a view matrix computes an movement matrix to make it easy
- * to move something relative to the camera view in the XZ plane.
- * @param {!o3djs.math.Matrix4} viewMatrix A view matrix.
- * @return {!o3djs.math.Matrix4} A movement matrix.
- */
-function computeMoveMatrixFromViewMatrix(viewMatrix) {
- var cameraMatrix = g_math.matrix4.inverse(viewMatrix);
- var xAxis = g_math.cross([0, 1, 0], cameraMatrix[2].slice(0, 3));
- var zAxis = g_math.cross(xAxis, [0, 1, 0]);
- return [
- xAxis.concat(0),
- [0, 1, 0, 0],
- zAxis.concat(0),
- [0, 0, 0, 1]];
-}
-
-/*
- * Updates the camera.
- */
-function updateCamera() {
- g_viewMatrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
- g_viewInfo.drawContext.view = g_viewMatrix;
- g_moveMatrix = computeMoveMatrixFromViewMatrix(g_viewMatrix);
-};
-
-/**
- * Updates global variables of the client's size if they have changed.
- */
-function updateClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (g_o3dWidth != newWidth || g_o3dHeight != newHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- updateProjection();
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- updateCamera();
-
- var checkerMaterial = o3djs.material.createMaterialFromFile(
- g_pack, 'shaders/checker.shader', g_viewInfo.performanceDrawList);
-
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Load character.
- var transform = g_pack.createObject('Transform');
- g_playerTransform = transform;
- var playerPack = g_client.createPack();
- o3djs.scene.loadScene(g_client, playerPack, g_playerTransform,
- 'assets/character.o3dtgz', initStep3);
-}
-
-/**
- * Continue setting up after the model has loaded.
- */
-function initStep3(playerPack, parent, exception) {
- o3djs.pack.preparePack(playerPack, g_viewInfo);
- o3djs.material.bindParams(playerPack, g_globalParams);
- g_playerTransform.parent = g_root;
-
- g_particleSystem = o3djs.particles.createParticleSystem(g_pack, g_viewInfo);
- g_poofEmitter = g_particleSystem.createParticleEmitter();
- g_poofEmitter.setState(o3djs.particles.ParticleStateIds.ADD);
- g_poofEmitter.setColorRamp(
- [1, 1, 1, 0.3,
- 1, 1, 1, 0]);
- g_poofEmitter.setParameters({
- numParticles: 30,
- lifeTime: 0.5,
- startTime: 0,
- startSize: 5,
- endSize: 10,
- spinSpeedRange: 10},
- function(index, parameters) {
- var angle = Math.random() * 2 * Math.PI;
- parameters.velocity = g_math.matrix4.transformPoint(
- g_math.matrix4.rotationY(angle), [25, 2.5, 0]);
- parameters.acceleration = g_math.mulVectorVector(
- parameters.velocity, [-1.5, 1, -1.5]);
- });
- g_poof = g_poofEmitter.createOneShot(g_root);
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- o3djs.event.addEventListener(g_o3dElement, 'keydown', onKeyDown);
- o3djs.event.addEventListener(g_o3dElement, 'keyup', onKeyUp);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Tracks key down events.
- * @param {Event} e keyboard event.
- */
-function onKeyDown(e) {
- g_keyDown[e.keyCode] = true;
-}
-
-/**
- * Tracks key up events.
- * @param {Event} e keyboard event.
- */
-function onKeyUp(e) {
- g_keyDown[e.keyCode] = false;
-}
-
-/**
- * Look at keys.
- */
-function handleMoveKeys(elapsedTime) {
- var directionX = 0;
- var directionZ = 0;
-
- if (g_keyDown[37] || g_keyDown[65]) { directionX = -1; }
- if (g_keyDown[39] || g_keyDown[68]) { directionX = 1; }
- if (g_keyDown[38] || g_keyDown[87]) { directionZ = -1; }
- if (g_keyDown[40] || g_keyDown[83]) { directionZ = 1; }
-
- if (g_canJump) {
- if (g_keyDown[32]) {
- g_jumping = true;
- g_canJump = false;
- g_playerYVelocity = JUMP_VELOCITY;
- }
- } else {
- if (g_jumping) {
- g_playerYVelocity += GRAVITY * elapsedTime;
- g_playerYPosition += g_playerYVelocity * elapsedTime;
- if (g_playerYPosition <= 0) {
- g_playerYPosition = 0;
- g_poof.trigger(
- [g_playerXPosition, g_playerYPosition, g_playerZPosition]);
- g_jumping = false;
- }
- } else {
- if (!g_keyDown[32]) {
- g_canJump = true;
- }
- }
- }
-
- if (directionX != 0 || directionZ != 0) {
- var moveTranslation = g_math.matrix4.transformPoint(
- g_moveMatrix,
- [MOVE_VELOCITY * directionX * elapsedTime,
- 0,
- MOVE_VELOCITY * directionZ * elapsedTime]);
-
- g_playerXPosition += moveTranslation[0];
- g_playerZPosition += moveTranslation[2];
- }
-
- g_playerTransform.identity();
- g_playerTransform.translate(
- g_playerXPosition, g_playerYPosition, g_playerZPosition);
-}
-
-/**
- * Move the camera.
- */
-function moveCamera() {
- var newTarget = [g_playerXPosition, 10, g_playerZPosition];
- g_target = g_math.lerpVector(g_target, newTarget, 0.03);
- updateCamera();
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- updateClientSize();
- handleMoveKeys(elapsedTime);
- moveCamera();
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table style="width: 100%; height:100%;">
- <tr style="height: 50px;"><td>
- <div style="width: 100%; height: 50px; font-size: large;">
- <img src="assets/colorbar.png" width="100%" height="10px"/><br/>
- Google I/O 2009 O3D Sample
- </div>
- </td></tr>
- <tr style="height: 100%;"><td>
- <div style="width: 100%; height: 100%;">
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- </div>
- </td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/GoogleIO-2009/step11ex.html b/o3d/samples/GoogleIO-2009/step11ex.html
deleted file mode 100644
index db9fd9e..0000000
--- a/o3d/samples/GoogleIO-2009/step11ex.html
+++ /dev/null
@@ -1,365 +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.
--->
-<!--
-Google I/O O3D Sample.
-
-This sample shows the steps to make a simple frame rate independent game.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Google I/O O3D Sample
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- font-family: Arial, sans-serif;
- }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.particles');
-o3djs.require('o3djs.scene');
-o3djs.require('o3djs.pack');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// constants
-var MOVE_VELOCITY = 25; // in units per second.
-var JUMP_VELOCITY = 100;
-var GRAVITY = -500;
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_globalParams;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_keyDown = []; // which keys are down by key code.
-var g_playerTransform;
-var g_playerXPosition = 0;
-var g_playerYPosition = 0;
-var g_playerZPosition = 0;
-var g_playerDirection = 0;
-var g_eye = [15, 25, 50];
-var g_target = [0, 10, 0];
-var g_up = [0, 1, 0];
-var g_viewMatrix;
-var g_moveMatrix;
-var g_canJump = true;
-var g_jumping = false;
-var g_playerYVelocity = 0;
-var g_particleSystem;
-var g_poofEmitter;
-var g_poof;
-
-/**
- * Updates the projection matrix.
- */
-function updateProjection() {
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_o3dWidth / g_o3dHeight, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-}
-
-/**
- * Given a view matrix computes an movement matrix to make it easy
- * to move something relative to the camera view in the XZ plane.
- * @param {!o3djs.math.Matrix4} viewMatrix A view matrix.
- * @return {!o3djs.math.Matrix4} A movement matrix.
- */
-function computeMoveMatrixFromViewMatrix(viewMatrix) {
- var cameraMatrix = g_math.matrix4.inverse(viewMatrix);
- var xAxis = g_math.cross([0, 1, 0], cameraMatrix[2].slice(0, 3));
- var zAxis = g_math.cross(xAxis, [0, 1, 0]);
- return [
- xAxis.concat(0),
- [0, 1, 0, 0],
- zAxis.concat(0),
- [0, 0, 0, 1]];
-}
-
-/*
- * Updates the camera.
- */
-function updateCamera() {
- g_viewMatrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
- g_viewInfo.drawContext.view = g_viewMatrix;
- g_moveMatrix = computeMoveMatrixFromViewMatrix(g_viewMatrix);
-};
-
-/**
- * Updates global variables of the client's size if they have changed.
- */
-function updateClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (g_o3dWidth != newWidth || g_o3dHeight != newHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- updateProjection();
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- updateCamera();
-
- var checkerMaterial = o3djs.material.createMaterialFromFile(
- g_pack, 'shaders/checker.shader', g_viewInfo.performanceDrawList);
-
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Load character.
- var transform = g_pack.createObject('Transform');
- g_playerTransform = transform;
- var playerPack = g_client.createPack();
- o3djs.scene.loadScene(g_client, playerPack, g_playerTransform,
- 'assets/character.o3dtgz', initStep3);
-}
-
-/**
- * Continue setting up after the model has loaded.
- */
-function initStep3(playerPack, parent, exception) {
- o3djs.pack.preparePack(playerPack, g_viewInfo);
- o3djs.material.bindParams(playerPack, g_globalParams);
- g_playerTransform.parent = g_root;
-
- g_particleSystem = o3djs.particles.createParticleSystem(g_pack, g_viewInfo);
- g_poofEmitter = g_particleSystem.createParticleEmitter();
- g_poofEmitter.setState(o3djs.particles.ParticleStateIds.ADD);
- g_poofEmitter.setColorRamp(
- [1, 1, 1, 0.3,
- 1, 1, 1, 0]);
- g_poofEmitter.setParameters({
- numParticles: 30,
- lifeTime: 0.5,
- startTime: 0,
- startSize: 5,
- endSize: 10,
- spinSpeedRange: 10},
- function(index, parameters) {
- var angle = Math.random() * 2 * Math.PI;
- parameters.velocity = g_math.matrix4.transformPoint(
- g_math.matrix4.rotationY(angle), [25, 2.5, 0]);
- parameters.acceleration = g_math.mulVectorVector(
- parameters.velocity, [-1.5, 1, -1.5]);
- });
- g_poof = g_poofEmitter.createOneShot(g_root);
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- o3djs.event.addEventListener(g_o3dElement, 'keydown', onKeyDown);
- o3djs.event.addEventListener(g_o3dElement, 'keyup', onKeyUp);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Tracks key down events.
- * @param {Event} e keyboard event.
- */
-function onKeyDown(e) {
- g_keyDown[e.keyCode] = true;
-}
-
-/**
- * Tracks key up events.
- * @param {Event} e keyboard event.
- */
-function onKeyUp(e) {
- g_keyDown[e.keyCode] = false;
-}
-
-/**
- * Look at keys.
- */
-function handleMoveKeys(elapsedTime) {
- var directionX = 0;
- var directionZ = 0;
-
- if (g_keyDown[37] || g_keyDown[65]) { directionX = -1; }
- if (g_keyDown[39] || g_keyDown[68]) { directionX = 1; }
- if (g_keyDown[38] || g_keyDown[87]) { directionZ = -1; }
- if (g_keyDown[40] || g_keyDown[83]) { directionZ = 1; }
-
- if (g_canJump) {
- if (g_keyDown[32]) {
- g_jumping = true;
- g_canJump = false;
- g_playerYVelocity = JUMP_VELOCITY;
- }
- } else {
- if (g_jumping) {
- g_playerYVelocity += GRAVITY * elapsedTime;
- g_playerYPosition += g_playerYVelocity * elapsedTime;
- if (g_playerYPosition <= 0) {
- g_playerYPosition = 0;
- g_poof.trigger(
- [g_playerXPosition, g_playerYPosition, g_playerZPosition]);
- g_jumping = false;
- }
- } else {
- if (!g_keyDown[32]) {
- g_canJump = true;
- }
- }
- }
-
- if (directionX != 0 || directionZ != 0) {
- var moveTranslation = g_math.matrix4.transformPoint(
- g_moveMatrix,
- [MOVE_VELOCITY * directionX * elapsedTime,
- 0,
- MOVE_VELOCITY * directionZ * elapsedTime]);
- var targetDirection = Math.atan2(moveTranslation[0], moveTranslation[2]);
- g_playerDirection = g_math.lerpRadian(g_playerDirection, targetDirection,
- 0.2);
- g_playerXPosition += moveTranslation[0];
- g_playerZPosition += moveTranslation[2];
- }
-
- g_playerTransform.identity();
- g_playerTransform.translate(
- g_playerXPosition, g_playerYPosition, g_playerZPosition);
- g_playerTransform.rotateY(g_playerDirection);
-}
-
-/**
- * Move the camera.
- */
-function moveCamera() {
- var newTarget = [g_playerXPosition, 10, g_playerZPosition];
- g_target = g_math.lerpVector(g_target, newTarget, 0.03);
- updateCamera();
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- updateClientSize();
- handleMoveKeys(elapsedTime);
- moveCamera();
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table style="width: 100%; height:100%;">
- <tr style="height: 50px;"><td>
- <div style="width: 100%; height: 50px; font-size: large;">
- <img src="assets/colorbar.png" width="100%" height="10px"/><br/>
- Google I/O 2009 O3D Sample
- </div>
- </td></tr>
- <tr style="height: 100%;"><td>
- <div style="width: 100%; height: 100%;">
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- </div>
- </td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/GoogleIO-2009/step12ex.html b/o3d/samples/GoogleIO-2009/step12ex.html
deleted file mode 100644
index 99c7ce4..0000000
--- a/o3d/samples/GoogleIO-2009/step12ex.html
+++ /dev/null
@@ -1,394 +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.
--->
-<!--
-Google I/O O3D Sample.
-
-This sample shows the steps to make a simple frame rate independent game.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Google I/O O3D Sample
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- font-family: Arial, sans-serif;
- }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.particles');
-o3djs.require('o3djs.scene');
-o3djs.require('o3djs.pack');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// constants
-var MOVE_VELOCITY = 25; // in units per second.
-var JUMP_VELOCITY = 100;
-var GRAVITY = -500;
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_globalParams;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_keyDown = []; // which keys are down by key code.
-var g_playerTransform;
-var g_playerXPosition = 0;
-var g_playerYPosition = 0;
-var g_playerZPosition = 0;
-var g_playerDirection = 0;
-var g_animParam;
-var g_playerMode;
-var g_eye = [15, 25, 50];
-var g_target = [0, 10, 0];
-var g_up = [0, 1, 0];
-var g_viewMatrix;
-var g_moveMatrix;
-var g_canJump = true;
-var g_jumping = false;
-var g_playerYVelocity = 0;
-var g_particleSystem;
-var g_poofEmitter;
-var g_poof;
-
-var IDLE_START_TIME = 247 / 30;
-var IDLE_END_TIME = 573 / 30;
-var IDLE_TIME_RANGE = IDLE_END_TIME - IDLE_START_TIME;
-
-var g_animTimer = IDLE_START_TIME;
-
-/**
- * Updates the projection matrix.
- */
-function updateProjection() {
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_o3dWidth / g_o3dHeight, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-}
-
-/**
- * Given a view matrix computes an movement matrix to make it easy
- * to move something relative to the camera view in the XZ plane.
- * @param {!o3djs.math.Matrix4} viewMatrix A view matrix.
- * @return {!o3djs.math.Matrix4} A movement matrix.
- */
-function computeMoveMatrixFromViewMatrix(viewMatrix) {
- var cameraMatrix = g_math.matrix4.inverse(viewMatrix);
- var xAxis = g_math.cross([0, 1, 0], cameraMatrix[2].slice(0, 3));
- var zAxis = g_math.cross(xAxis, [0, 1, 0]);
- return [
- xAxis.concat(0),
- [0, 1, 0, 0],
- zAxis.concat(0),
- [0, 0, 0, 1]];
-}
-
-/*
- * Updates the camera.
- */
-function updateCamera() {
- g_viewMatrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
- g_viewInfo.drawContext.view = g_viewMatrix;
- g_moveMatrix = computeMoveMatrixFromViewMatrix(g_viewMatrix);
-};
-
-/**
- * Updates global variables of the client's size if they have changed.
- */
-function updateClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (g_o3dWidth != newWidth || g_o3dHeight != newHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- updateProjection();
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- updateCamera();
-
- var checkerMaterial = o3djs.material.createMaterialFromFile(
- g_pack, 'shaders/checker.shader', g_viewInfo.performanceDrawList);
-
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Load character.
- var transform = g_pack.createObject('Transform');
- g_playerTransform = transform;
- var playerPack = g_client.createPack();
- var paramObject = playerPack.createObject('ParamObject');
- g_animParam = paramObject.createParam('animTime', 'ParamFloat');
- o3djs.scene.loadScene(g_client, playerPack, g_playerTransform,
- 'assets/character.o3dtgz', initStep3,
- {opt_animSource: g_animParam});
-}
-
-/**
- * Continue setting up after the model has loaded.
- */
-function initStep3(playerPack, parent, exception) {
- o3djs.pack.preparePack(playerPack, g_viewInfo);
- o3djs.material.bindParams(playerPack, g_globalParams);
- g_playerTransform.parent = g_root;
-
- g_particleSystem = o3djs.particles.createParticleSystem(g_pack, g_viewInfo);
- g_poofEmitter = g_particleSystem.createParticleEmitter();
- g_poofEmitter.setState(o3djs.particles.ParticleStateIds.ADD);
- g_poofEmitter.setColorRamp(
- [1, 1, 1, 0.3,
- 1, 1, 1, 0]);
- g_poofEmitter.setParameters({
- numParticles: 30,
- lifeTime: 0.5,
- startTime: 0,
- startSize: 5,
- endSize: 10,
- spinSpeedRange: 10},
- function(index, parameters) {
- var angle = Math.random() * 2 * Math.PI;
- parameters.velocity = g_math.matrix4.transformPoint(
- g_math.matrix4.rotationY(angle), [25, 2.5, 0]);
- parameters.acceleration = g_math.mulVectorVector(
- parameters.velocity, [-1.5, 1, -1.5]);
- });
- g_poof = g_poofEmitter.createOneShot(g_root);
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- o3djs.event.addEventListener(g_o3dElement, 'keydown', onKeyDown);
- o3djs.event.addEventListener(g_o3dElement, 'keyup', onKeyUp);
-
- window.g_finished = true; // for selenium testing.
- window.o3d_prepForSelenium = function() {
- g_animParam.value = 0;
- g_animParam = {value: 0};
- }
-}
-
-/**
- * Tracks key down events.
- * @param {Event} e keyboard event.
- */
-function onKeyDown(e) {
- g_keyDown[e.keyCode] = true;
-}
-
-/**
- * Tracks key up events.
- * @param {Event} e keyboard event.
- */
-function onKeyUp(e) {
- g_keyDown[e.keyCode] = false;
-}
-
-/**
- * Look at keys.
- */
-function handleMoveKeys(elapsedTime) {
- var directionX = 0;
- var directionZ = 0;
-
- if (g_keyDown[37] || g_keyDown[65]) { directionX = -1; }
- if (g_keyDown[39] || g_keyDown[68]) { directionX = 1; }
- if (g_keyDown[38] || g_keyDown[87]) { directionZ = -1; }
- if (g_keyDown[40] || g_keyDown[83]) { directionZ = 1; }
-
- if (g_canJump) {
- if (g_keyDown[32]) {
- g_jumping = true;
- g_canJump = false;
- g_playerYVelocity = JUMP_VELOCITY;
- }
- } else {
- if (g_jumping) {
- g_playerYVelocity += GRAVITY * elapsedTime;
- g_playerYPosition += g_playerYVelocity * elapsedTime;
- if (g_playerYPosition <= 0) {
- g_playerYPosition = 0;
- g_poof.trigger(
- [g_playerXPosition, g_playerYPosition, g_playerZPosition]);
- g_jumping = false;
- }
- } else {
- if (!g_keyDown[32]) {
- g_canJump = true;
- }
- }
- }
-
- if (directionX != 0 || directionZ != 0) {
- var moveTranslation = g_math.matrix4.transformPoint(
- g_moveMatrix,
- [MOVE_VELOCITY * directionX * elapsedTime,
- 0,
- MOVE_VELOCITY * directionZ * elapsedTime]);
- var targetDirection = Math.atan2(moveTranslation[0], moveTranslation[2]);
- g_playerDirection = g_math.lerpRadian(g_playerDirection, targetDirection,
- 0.2);
- g_playerXPosition += moveTranslation[0];
- g_playerZPosition += moveTranslation[2];
- }
-
- g_playerTransform.identity();
- g_playerTransform.translate(
- g_playerXPosition, g_playerYPosition, g_playerZPosition);
- g_playerTransform.rotateY(g_playerDirection);
-}
-
-/**
- * Move the camera.
- */
-function moveCamera() {
- var newTarget = [g_playerXPosition, 10, g_playerZPosition];
- g_target = g_math.lerpVector(g_target, newTarget, 0.03);
- updateCamera();
-}
-
-/**
- * Deal with player animation.
- */
-function handleAnimation(elapsedTime) {
- g_animTimer += elapsedTime;
- if (g_animTimer >= IDLE_END_TIME) {
- g_animTimer = g_math.modClamp(g_animTimer,
- IDLE_TIME_RANGE,
- IDLE_START_TIME);
- }
- g_animParam.value = g_animTimer;
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- updateClientSize();
- handleMoveKeys(elapsedTime);
- handleAnimation(elapsedTime);
- moveCamera();
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table style="width: 100%; height:100%;">
- <tr style="height: 50px;"><td>
- <div style="width: 100%; height: 50px; font-size: large;">
- <img src="assets/colorbar.png" width="100%" height="10px"/><br/>
- Google I/O 2009 O3D Sample
- </div>
- </td></tr>
- <tr style="height: 100%;"><td>
- <div style="width: 100%; height: 100%;">
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- </div>
- </td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/GoogleIO-2009/step13ex.html b/o3d/samples/GoogleIO-2009/step13ex.html
deleted file mode 100644
index 62f56fc..0000000
--- a/o3d/samples/GoogleIO-2009/step13ex.html
+++ /dev/null
@@ -1,570 +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.
--->
-<!--
-Google I/O O3D Sample.
-
-This sample shows the steps to make a simple frame rate independent game.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Google I/O O3D Sample
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- font-family: Arial, sans-serif;
- }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.particles');
-o3djs.require('o3djs.scene');
-o3djs.require('o3djs.pack');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// constants
-var MOVE_VELOCITY = 25; // in units per second.
-var JUMP_VELOCITY = 100;
-var GRAVITY = -500;
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_globalParams;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_keyDown = []; // which keys are down by key code.
-var g_playerTransform;
-var g_playerPosition = [0, 0, 0];
-var g_playerDirection = 0;
-var g_animParam;
-var g_playerMode;
-var g_eye = [15, 25, 50];
-var g_target = [0, 10, 0];
-var g_up = [0, 1, 0];
-var g_viewMatrix;
-var g_moveMatrix;
-var g_canJump = true;
-var g_jumping = false;
-var g_playerVelocity = [0, 0, 0];
-var g_targetDirection = 0;
-var g_particleSystem;
-var g_poofEmitter;
-var g_poof;
-
-var g_anims = {
- idle1: {startFrame: 0, endFrame: 30},
- walk: {startFrame: 31, endFrame: 71},
- jumpStart: {startFrame: 72, endFrame: 87},
- jumpUp: {startFrame: 87, endFrame: 87},
- jumpCrest: {startFrame: 87, endFrame: 91},
- jumpFall: {startFrame: 91, endFrame: 91},
- jumpLand: {startFrame: 91, endFrame: 110},
- run: {startFrame: 111, endFrame: 127},
- idle2: {startFrame: 128, endFrame: 173},
- idle3: {startFrame: 174, endFrame: 246},
- idle4: {startFrame: 247, endFrame: 573}};
-
-var g_animation;
-var g_animTimer;
-
-/**
- * Updates the projection matrix.
- */
-function updateProjection() {
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_o3dWidth / g_o3dHeight, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-}
-
-/**
- * Given a view matrix computes an movement matrix to make it easy
- * to move something relative to the camera view in the XZ plane.
- * @param {!o3djs.math.Matrix4} viewMatrix A view matrix.
- * @return {!o3djs.math.Matrix4} A movement matrix.
- */
-function computeMoveMatrixFromViewMatrix(viewMatrix) {
- var cameraMatrix = g_math.matrix4.inverse(viewMatrix);
- var xAxis = g_math.cross([0, 1, 0], cameraMatrix[2].slice(0, 3));
- var zAxis = g_math.cross(xAxis, [0, 1, 0]);
- return [
- xAxis.concat(0),
- [0, 1, 0, 0],
- zAxis.concat(0),
- [0, 0, 0, 1]];
-}
-
-/*
- * Updates the camera.
- */
-function updateCamera() {
- g_viewMatrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
- g_viewInfo.drawContext.view = g_viewMatrix;
- g_moveMatrix = computeMoveMatrixFromViewMatrix(g_viewMatrix);
-};
-
-/**
- * Updates global variables of the client's size if they have changed.
- */
-function updateClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (g_o3dWidth != newWidth || g_o3dHeight != newHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- updateProjection();
- }
-}
-
-/**
- * Start an animation.
- * @param {!Object} animation to start.
- */
-function startAnimation(animation) {
- g_animation = animation;
- g_animTimer = g_animation.startTime;
-}
-
-/**
- * Starts a new mode.
- * @param {number} mode Mode to start.
- */
-function startMode(mode) {
- if (mode != g_playerMode) {
- g_playerMode = mode;
- mode.init();
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Convert anim frames to anim times.
- for (var animName in g_anims) {
- var anim = g_anims[animName];
- anim.startTime = anim.startFrame / 30;
- anim.endTime = anim.endFrame / 30;
- anim.timeRange = anim.endTime - anim.startTime;
- }
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- updateCamera();
-
- var checkerMaterial = o3djs.material.createMaterialFromFile(
- g_pack, 'shaders/checker.shader', g_viewInfo.performanceDrawList);
-
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Load character.
- var transform = g_pack.createObject('Transform');
- g_playerTransform = transform;
- var playerPack = g_client.createPack();
- var paramObject = playerPack.createObject('ParamObject');
- g_animParam = paramObject.createParam('animTime', 'ParamFloat');
- o3djs.scene.loadScene(g_client, playerPack, g_playerTransform,
- 'assets/character.o3dtgz', initStep3,
- {opt_animSource: g_animParam});
-}
-
-/**
- * Continue setting up after the model has loaded.
- */
-function initStep3(playerPack, parent, exception) {
- o3djs.pack.preparePack(playerPack, g_viewInfo);
- o3djs.material.bindParams(playerPack, g_globalParams);
- g_playerTransform.parent = g_root;
-
- g_particleSystem = o3djs.particles.createParticleSystem(g_pack, g_viewInfo);
- g_poofEmitter = g_particleSystem.createParticleEmitter();
- g_poofEmitter.setState(o3djs.particles.ParticleStateIds.ADD);
- g_poofEmitter.setColorRamp(
- [1, 1, 1, 0.3,
- 1, 1, 1, 0]);
- g_poofEmitter.setParameters({
- numParticles: 30,
- lifeTime: 0.5,
- startTime: 0,
- startSize: 5,
- endSize: 10,
- spinSpeedRange: 10},
- function(index, parameters) {
- var angle = Math.random() * 2 * Math.PI;
- parameters.velocity = g_math.matrix4.transformPoint(
- g_math.matrix4.rotationY(angle), [25, 2.5, 0]);
- parameters.acceleration = g_math.mulVectorVector(
- parameters.velocity, [-1.5, 1, -1.5]);
- });
- g_poof = g_poofEmitter.createOneShot(g_root);
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- o3djs.event.addEventListener(g_o3dElement, 'keydown', onKeyDown);
- o3djs.event.addEventListener(g_o3dElement, 'keyup', onKeyUp);
-
- window.g_finished = true; // for selenium testing.
- window.o3d_prepForSelenium = function() {
- g_animParam.value = 0;
- g_animParam = {value: 0};
- }
-}
-
-/**
- * Tracks key down events.
- * @param {Event} e keyboard event.
- */
-function onKeyDown(e) {
- g_keyDown[e.keyCode] = true;
-}
-
-/**
- * Tracks key up events.
- * @param {Event} e keyboard event.
- */
-function onKeyUp(e) {
- g_keyDown[e.keyCode] = false;
-}
-
-/**
- * Look at keys.
- */
-function handleMoveKeys(elapsedTime) {
- var directionX = 0;
- var directionZ = 0;
-
- if (g_keyDown[37] || g_keyDown[65]) { directionX = -1; }
- if (g_keyDown[39] || g_keyDown[68]) { directionX = 1; }
- if (g_keyDown[38] || g_keyDown[87]) { directionZ = -1; }
- if (g_keyDown[40] || g_keyDown[83]) { directionZ = 1; }
-
- if (g_canJump) {
- if (g_keyDown[32]) {
- startMode(g_modes.JUMP);
- }
- } else {
- if (!g_jumping) {
- if (!g_keyDown[32]) {
- g_canJump = true;
- }
- }
- }
-
- if (directionX != 0 || directionZ != 0) {
- if (!g_jumping) {
- startMode(g_modes.WALK);
- }
- var moveTranslation = g_math.matrix4.transformPoint(
- g_moveMatrix,
- [MOVE_VELOCITY * directionX, 0, MOVE_VELOCITY * directionZ]);
- g_targetDirection = Math.atan2(moveTranslation[0],
- moveTranslation[2]);
- g_playerVelocity[0] = moveTranslation[0];
- g_playerVelocity[2] = moveTranslation[2];
- } else {
- g_playerVelocity[0] = 0;
- g_playerVelocity[2] = 0;
- if (!g_jumping) {
- startMode(g_modes.IDLE);
- }
- }
-}
-
-/**
- * Moves the camera.
- */
-function moveCamera() {
- var newTarget = [g_playerPosition[0], 10, g_playerPosition[2]];
- g_target = g_math.lerpVector(g_target, newTarget, 0.03);
- updateCamera();
-}
-
-/**
- * Updates the direction.
- * @param {number} elapsedTime Time elasped since last frame.
- */
-function updateDirection(elapsedTime) {
- g_playerDirection = g_math.lerpRadian(g_playerDirection, g_targetDirection,
- 0.2);
-}
-
-/**
- * Adds gravity to velocity.
- * @param {number} elapsedTime Time elasped since last frame.
- */
-function calculateGravity(elapsedTime) {
- g_playerVelocity[1] += GRAVITY * elapsedTime;
-}
-
-/**
- * Updates the player's position.
- * @param {number} elapsedTime Time elasped since last frame.
- */
-function updateMovement(elapsedTime) {
- g_playerPosition = g_math.addVector(g_playerPosition,
- g_math.mulVectorScalar(g_playerVelocity,
- elapsedTime));
-}
-
-var g_modes = {};
-
-/**
- * Handle idle mode.
- */
-g_modes.IDLE = {
- init: function() {
- startAnimation(g_anims.idle1);
- g_jumping = false;
- },
- handle: function(elapsedTime) {
- updateDirection(elapsedTime);
- g_animTimer += elapsedTime;
- if (g_animTimer >= g_animation.endTime) {
- // Pick an idle at random.
- var idle = 0;
- if (Math.random() > 0.8) {
- // Choose another idle.
- idle = Math.floor(Math.random() * 10 / 3);
- if (idle > 3) {
- idle = 3;
- }
- }
- var idleName = 'idle' + (idle + 1);
- startAnimation(g_anims[idleName]);
- }
- }
-};
-
-/**
- * Handle walk mode.
- */
-g_modes.WALK = {
- init: function() {
- startAnimation(g_anims.run);
- g_jumping = false;
- },
- handle: function(elapsedTime) {
- updateDirection(elapsedTime);
- updateMovement(elapsedTime);
- g_animTimer += elapsedTime;
- if (g_animTimer >= g_animation.endTime) {
- g_animTimer = g_math.modClamp(g_animTimer,
- g_animation.timeRange,
- g_animation.startTime);
- }
- }
-};
-
-/**
- * Handle jump mode.
- */
-g_modes.JUMP = {
- init: function() {
- startAnimation(g_anims.jumpStart);
- g_jumping = true;
- g_canJump = false;
- g_playerVelocity[1] = JUMP_VELOCITY;
- },
- handle: function(elapsedTime) {
- g_animTimer += elapsedTime;
- if (g_animTimer >= g_animation.endTime) {
- startMode(g_modes.JUMP_UP);
- }
- }
-};
-
-g_modes.JUMP_UP = {
- init: function() {
- startAnimation(g_anims.jumpUp);
- },
- handle: function(elapsedTime) {
- updateDirection(elapsedTime);
- calculateGravity(elapsedTime);
- updateMovement(elapsedTime);
- if (g_playerVelocity[1] < 10) {
- startMode(g_modes.JUMP_CREST);
- }
- }
-};
-
-g_modes.JUMP_CREST = {
- init: function() {
- startAnimation(g_anims.jumpCrest);
- },
- handle: function(elapsedTime) {
- updateDirection(elapsedTime);
- calculateGravity(elapsedTime);
- updateMovement(elapsedTime);
- g_animTimer += elapsedTime;
- if (g_animTimer >= g_animation.endTime) {
- startMode(g_modes.JUMP_FALL);
- }
- }
-};
-
-g_modes.JUMP_FALL = {
- init: function() {
- startAnimation(g_anims.jumpFall);
- },
- handle: function(elapsedTime) {
- updateDirection(elapsedTime);
- calculateGravity(elapsedTime);
- updateMovement(elapsedTime);
- if (g_playerPosition[1] <= 0) {
- startMode(g_modes.JUMP_LAND);
- g_playerPosition[1] = 0;
- g_playerVelocity[1] = 0;
- g_poof.trigger(g_playerPosition);
- }
- }
-};
-
-g_modes.JUMP_LAND = {
- init: function() {
- startAnimation(g_anims.jumpLand);
- },
- handle: function(elapsedTime) {
- updateDirection(elapsedTime);
- g_animTimer += elapsedTime;
- if (g_animTimer >= g_animation.endTime) {
- g_jumping = false;
- startMode(g_modes.IDLE);
- }
- }
-};
-
-function updatePlayer() {
- g_animParam.value = g_animTimer;
- g_playerTransform.identity();
- g_playerTransform.translate(g_playerPosition);
- g_playerTransform.rotateY(g_playerDirection);
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- updateClientSize();
- handleMoveKeys(elapsedTime);
- g_playerMode.handle(elapsedTime);
- updatePlayer();
- moveCamera();
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table style="width: 100%; height:100%;">
- <tr style="height: 50px;"><td>
- <div style="width: 100%; height: 50px; font-size: large;">
- <img src="assets/colorbar.png" width="100%" height="10px"/><br/>
- Google I/O 2009 O3D Sample
- </div>
- </td></tr>
- <tr style="height: 100%;"><td>
- <div style="width: 100%; height: 100%;">
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- </div>
- </td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/GoogleIO-2009/step14ex.html b/o3d/samples/GoogleIO-2009/step14ex.html
deleted file mode 100644
index a1545c4..0000000
--- a/o3d/samples/GoogleIO-2009/step14ex.html
+++ /dev/null
@@ -1,581 +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.
--->
-<!--
-Google I/O O3D Sample.
-
-This sample shows the steps to make a simple frame rate independent game.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Google I/O O3D Sample
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- font-family: Arial, sans-serif;
- }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.particles');
-o3djs.require('o3djs.scene');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.loader');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// constants
-var MOVE_VELOCITY = 25; // in units per second.
-var JUMP_VELOCITY = 100;
-var GRAVITY = -500;
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_globalParams;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_keyDown = []; // which keys are down by key code.
-var g_playerTransform;
-var g_playerPosition = [0, 0, 0];
-var g_playerDirection = 0;
-var g_animParam;
-var g_playerMode;
-var g_eye = [15, 25, 50];
-var g_target = [0, 10, 0];
-var g_up = [0, 1, 0];
-var g_viewMatrix;
-var g_moveMatrix;
-var g_canJump = true;
-var g_jumping = false;
-var g_playerVelocity = [0, 0, 0];
-var g_targetDirection = 0;
-var g_worldTransform;
-var g_particleSystem;
-var g_poofEmitter;
-var g_poof;
-
-var g_anims = {
- idle1: {startFrame: 0, endFrame: 30},
- walk: {startFrame: 31, endFrame: 71},
- jumpStart: {startFrame: 72, endFrame: 87},
- jumpUp: {startFrame: 87, endFrame: 87},
- jumpCrest: {startFrame: 87, endFrame: 91},
- jumpFall: {startFrame: 91, endFrame: 91},
- jumpLand: {startFrame: 91, endFrame: 110},
- run: {startFrame: 111, endFrame: 127},
- idle2: {startFrame: 128, endFrame: 173},
- idle3: {startFrame: 174, endFrame: 246},
- idle4: {startFrame: 247, endFrame: 573}};
-
-var g_animation;
-var g_animTimer;
-
-/**
- * Updates the projection matrix.
- */
-function updateProjection() {
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_o3dWidth / g_o3dHeight, // aspect ratio
- 0.1, // Near plane.
- 15000); // Far plane.
-}
-
-/**
- * Given a view matrix computes an movement matrix to make it easy
- * to move something relative to the camera view in the XZ plane.
- * @param {!o3djs.math.Matrix4} viewMatrix A view matrix.
- * @return {!o3djs.math.Matrix4} A movement matrix.
- */
-function computeMoveMatrixFromViewMatrix(viewMatrix) {
- var cameraMatrix = g_math.matrix4.inverse(viewMatrix);
- var xAxis = g_math.cross([0, 1, 0], cameraMatrix[2].slice(0, 3));
- var zAxis = g_math.cross(xAxis, [0, 1, 0]);
- return [
- xAxis.concat(0),
- [0, 1, 0, 0],
- zAxis.concat(0),
- [0, 0, 0, 1]];
-}
-
-/*
- * Updates the camera.
- */
-function updateCamera() {
- g_viewMatrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
- g_viewInfo.drawContext.view = g_viewMatrix;
- g_moveMatrix = computeMoveMatrixFromViewMatrix(g_viewMatrix);
-};
-
-/**
- * Updates global variables of the client's size if they have changed.
- */
-function updateClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (g_o3dWidth != newWidth || g_o3dHeight != newHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- updateProjection();
- }
-}
-
-/**
- * Start an animation.
- * @param {!Object} animation to start.
- */
-function startAnimation(animation) {
- g_animation = animation;
- g_animTimer = g_animation.startTime;
-}
-
-/**
- * Starts a new mode.
- * @param {number} mode Mode to start.
- */
-function startMode(mode) {
- if (mode != g_playerMode) {
- g_playerMode = mode;
- mode.init();
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Convert anim frames to anim times.
- for (var animName in g_anims) {
- var anim = g_anims[animName];
- anim.startTime = anim.startFrame / 30;
- anim.endTime = anim.endFrame / 30;
- anim.timeRange = anim.endTime - anim.startTime;
- }
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- updateCamera();
-
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [600, 2000, 400];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Load character.
- var transform = g_pack.createObject('Transform');
- g_playerTransform = transform;
- var playerPack = g_client.createPack();
- var paramObject = playerPack.createObject('ParamObject');
- g_animParam = paramObject.createParam('animTime', 'ParamFloat');
- var loader = o3djs.loader.createLoader(initStep3);
- loader.loadScene(g_client, playerPack, g_playerTransform,
- 'assets/character.o3dtgz', prepareScene,
- {opt_animSource: g_animParam});
- var worldPack = g_client.createPack();
- g_worldTransform = worldPack.createObject('Transform');
- loader.loadScene(g_client, worldPack, g_worldTransform,
- 'assets/background.o3dtgz', prepareScene)
- loader.finish();
-}
-
-/**
- * Setup the just loaded scene.
- * @param {!o3d.Pack} pack The pack the scene was loaded into.
- * @param {!o3d.Transform} parent The parent of the scene.
- * @param {*} exception An exception or null if success.
- */
-function prepareScene(pack, parent, exception) {
- o3djs.pack.preparePack(pack, g_viewInfo);
- o3djs.material.bindParams(pack, g_globalParams);
- parent.parent = g_root;
-}
-
-/**
- * Continue setting up after the both the model and character have loaded.
- */
-function initStep3() {
- // Fix for artists not using the same scale on background vs character
- g_worldTransform.scale(10, 10, 10);
- // Fix for current collada import bugs.
- var m = g_client.getObjects('Road', 'o3d.Material')[0];
- m.getParam('shininess').value = 100;
-
- g_particleSystem = o3djs.particles.createParticleSystem(g_pack, g_viewInfo);
- g_poofEmitter = g_particleSystem.createParticleEmitter();
- g_poofEmitter.setState(o3djs.particles.ParticleStateIds.ADD);
- g_poofEmitter.setColorRamp(
- [1, 1, 1, 0.3,
- 1, 1, 1, 0]);
- g_poofEmitter.setParameters({
- numParticles: 30,
- lifeTime: 0.5,
- startTime: 0,
- startSize: 5,
- endSize: 10,
- spinSpeedRange: 10},
- function(index, parameters) {
- var angle = Math.random() * 2 * Math.PI;
- parameters.velocity = g_math.matrix4.transformPoint(
- g_math.matrix4.rotationY(angle), [25, 2.5, 0]);
- parameters.acceleration = g_math.mulVectorVector(
- parameters.velocity, [-1.5, 1, -1.5]);
- });
- g_poof = g_poofEmitter.createOneShot(g_root);
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- o3djs.event.addEventListener(g_o3dElement, 'keydown', onKeyDown);
- o3djs.event.addEventListener(g_o3dElement, 'keyup', onKeyUp);
-
- window.g_finished = true; // for selenium testing.
- window.o3d_prepForSelenium = function() {
- g_animParam.value = 0;
- g_animParam = {value: 0};
- }
-}
-
-/**
- * Tracks key down events.
- * @param {Event} e keyboard event.
- */
-function onKeyDown(e) {
- g_keyDown[e.keyCode] = true;
-}
-
-/**
- * Tracks key up events.
- * @param {Event} e keyboard event.
- */
-function onKeyUp(e) {
- g_keyDown[e.keyCode] = false;
-}
-
-/**
- * Look at keys.
- */
-function handleMoveKeys(elapsedTime) {
- var directionX = 0;
- var directionZ = 0;
-
- if (g_keyDown[37] || g_keyDown[65]) { directionX = -1; }
- if (g_keyDown[39] || g_keyDown[68]) { directionX = 1; }
- if (g_keyDown[38] || g_keyDown[87]) { directionZ = -1; }
- if (g_keyDown[40] || g_keyDown[83]) { directionZ = 1; }
-
- if (g_canJump) {
- if (g_keyDown[32]) {
- startMode(g_modes.JUMP);
- }
- } else {
- if (!g_jumping) {
- if (!g_keyDown[32]) {
- g_canJump = true;
- }
- }
- }
-
- if (directionX != 0 || directionZ != 0) {
- if (!g_jumping) {
- startMode(g_modes.WALK);
- }
- var moveTranslation = g_math.matrix4.transformPoint(
- g_moveMatrix,
- [MOVE_VELOCITY * directionX, 0, MOVE_VELOCITY * directionZ]);
- g_targetDirection = Math.atan2(moveTranslation[0],
- moveTranslation[2]);
- g_playerVelocity[0] = moveTranslation[0];
- g_playerVelocity[2] = moveTranslation[2];
- } else {
- g_playerVelocity[0] = 0;
- g_playerVelocity[2] = 0;
- if (!g_jumping) {
- startMode(g_modes.IDLE);
- }
- }
-}
-
-/**
- * Move the camera.
- */
-function moveCamera() {
- var newTarget = [g_playerPosition[0], 10, g_playerPosition[2]];
- g_target = g_math.lerpVector(g_target, newTarget, 0.03);
- updateCamera();
-}
-
-/**
- * Updates the direction.
- * @param {number} elapsedTime Time elasped since last frame.
- */
-function updateDirection(elapsedTime) {
- g_playerDirection = g_math.lerpRadian(g_playerDirection, g_targetDirection,
- 0.2);
-}
-
-/**
- * Adds gravity to velocity.
- * @param {number} elapsedTime Time elasped since last frame.
- */
-function calculateGravity(elapsedTime) {
- g_playerVelocity[1] += GRAVITY * elapsedTime;
-}
-
-/**
- * Updates the player's position.
- * @param {number} elapsedTime Time elasped since last frame.
- */
-function updateMovement(elapsedTime) {
- g_playerPosition = g_math.addVector(g_playerPosition,
- g_math.mulVectorScalar(g_playerVelocity,
- elapsedTime));
-}
-
-var g_modes = {};
-
-/**
- * Handle idle mode.
- */
-g_modes.IDLE = {
- init: function() {
- startAnimation(g_anims.idle1);
- g_jumping = false;
- },
- handle: function(elapsedTime) {
- updateDirection(elapsedTime);
- g_animTimer += elapsedTime;
- if (g_animTimer >= g_animation.endTime) {
- // Pick an idle at random.
- var idle = 0;
- if (Math.random() > 0.8) {
- // Choose another idle.
- idle = Math.floor(Math.random() * 10 / 3);
- if (idle > 3) {
- idle = 3;
- }
- }
- var idleName = 'idle' + (idle + 1);
- startAnimation(g_anims[idleName]);
- }
- }
-};
-
-/**
- * Handle walk mode.
- */
-g_modes.WALK = {
- init: function() {
- startAnimation(g_anims.run);
- g_jumping = false;
- },
- handle: function(elapsedTime) {
- updateDirection(elapsedTime);
- updateMovement(elapsedTime);
- g_animTimer += elapsedTime;
- if (g_animTimer >= g_animation.endTime) {
- g_animTimer = g_math.modClamp(g_animTimer,
- g_animation.timeRange,
- g_animation.startTime);
- }
- }
-};
-
-/**
- * Handle jump mode.
- */
-g_modes.JUMP = {
- init: function() {
- startAnimation(g_anims.jumpStart);
- g_jumping = true;
- g_canJump = false;
- g_playerVelocity[1] = JUMP_VELOCITY;
- },
- handle: function(elapsedTime) {
- g_animTimer += elapsedTime;
- if (g_animTimer >= g_animation.endTime) {
- startMode(g_modes.JUMP_UP);
- }
- }
-};
-
-g_modes.JUMP_UP = {
- init: function() {
- startAnimation(g_anims.jumpUp);
- },
- handle: function(elapsedTime) {
- updateDirection(elapsedTime);
- calculateGravity(elapsedTime);
- updateMovement(elapsedTime);
- if (g_playerVelocity[1] < 10) {
- startMode(g_modes.JUMP_CREST);
- }
- }
-};
-
-g_modes.JUMP_CREST = {
- init: function() {
- startAnimation(g_anims.jumpCrest);
- },
- handle: function(elapsedTime) {
- updateDirection(elapsedTime);
- calculateGravity(elapsedTime);
- updateMovement(elapsedTime);
- g_animTimer += elapsedTime;
- if (g_animTimer >= g_animation.endTime) {
- startMode(g_modes.JUMP_FALL);
- }
- }
-};
-
-g_modes.JUMP_FALL = {
- init: function() {
- startAnimation(g_anims.jumpFall);
- },
- handle: function(elapsedTime) {
- updateDirection(elapsedTime);
- calculateGravity(elapsedTime);
- updateMovement(elapsedTime);
- if (g_playerPosition[1] <= 0) {
- startMode(g_modes.JUMP_LAND);
- g_playerPosition[1] = 0;
- g_playerVelocity[1] = 0;
- g_poof.trigger(g_playerPosition);
- }
- }
-};
-
-g_modes.JUMP_LAND = {
- init: function() {
- startAnimation(g_anims.jumpLand);
- },
- handle: function(elapsedTime) {
- updateDirection(elapsedTime);
- g_animTimer += elapsedTime;
- if (g_animTimer >= g_animation.endTime) {
- g_jumping = false;
- startMode(g_modes.IDLE);
- }
- }
-};
-
-function updatePlayer() {
- g_animParam.value = g_animTimer;
- g_playerTransform.identity();
- g_playerTransform.translate(g_playerPosition);
- g_playerTransform.rotateY(g_playerDirection);
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- updateClientSize();
- handleMoveKeys(elapsedTime);
- g_playerMode.handle(elapsedTime);
- updatePlayer();
- moveCamera();
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table style="width: 100%; height:100%;">
- <tr style="height: 50px;"><td>
- <div style="width: 100%; height: 50px; font-size: large;">
- <img src="assets/colorbar.png" width="100%" height="10px"/><br/>
- Google I/O 2009 O3D Sample
- </div>
- </td></tr>
- <tr style="height: 100%;"><td>
- <div style="width: 100%; height: 100%;">
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- </div>
- </td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/MANIFEST b/o3d/samples/MANIFEST
deleted file mode 100644
index 7aecc23..0000000
--- a/o3d/samples/MANIFEST
+++ /dev/null
@@ -1,224 +0,0 @@
-[ 'archive-textures.html',
- 'assets/android.png',
- 'assets/archive_textures.o3dtgz',
- 'assets/block.png',
- 'assets/brush.png',
- 'assets/dome1.o3dtgz',
- 'assets/dome2.o3dtgz',
- 'assets/dome3.o3dtgz',
- 'assets/dome4.o3dtgz',
- 'assets/egg.png',
- 'assets/four_pixel.png',
- 'assets/fullscreen.png',
- 'assets/gauge.png',
- 'assets/gaugeback.png',
- 'assets/gears_init.js',
- 'assets/google-square.png',
- 'assets/hi.jpg',
- 'assets/iconback.png',
- 'assets/kitty_151_idle_stand05_cff1.o3dtgz',
- 'assets/normalmap.dds',
- 'assets/one-pixel-white.tga',
- 'assets/old-school-shadow.png',
- 'assets/orange-flower.png',
- 'assets/part1.o3dtgz',
- 'assets/part2.o3dtgz',
- 'assets/part3.o3dtgz',
- 'assets/particle-anim.png',
- 'assets/pillar.png',
- 'assets/poolballs.png',
- 'assets/purple-flower.png',
- 'assets/radar.png',
- 'assets/ripple.png',
- 'assets/rock_bumps.jpg',
- 'assets/rock_texture.jpg',
- 'assets/seven_shapes.o3dtgz',
- 'assets/shaving_cream.jpg',
- 'assets/shaving_cream.png',
- 'assets/shaving_cream_300x300.jpg',
- 'assets/square.png',
- 'assets/stencil_frame.o3dtgz',
- 'assets/teapot.o3dtgz',
- 'assets/teapot_vertices.js',
- 'assets/texture_b3.jpg',
- 'assets/yard.o3dtgz',
- 'beachdemo/assets/beachdemo.o3dtgz',
- 'beachdemo/assets/beach-low-poly.o3dtgz',
- 'beachdemo/assets/pe_fire.jpg',
- 'beachdemo/assets/pe_mist.png',
- 'beachdemo/assets/sky-cubemap.dds',
- 'beachdemo/beachdemo.html',
- 'beachdemo/beachdemo.js',
- 'GoogleIO-2009/step01ex.html',
- 'GoogleIO-2009/step02ex.html',
- 'GoogleIO-2009/step03ex.html',
- 'GoogleIO-2009/step04ex.html',
- 'GoogleIO-2009/step05ex.html',
- 'GoogleIO-2009/step06ex.html',
- 'GoogleIO-2009/step07ex.html',
- 'GoogleIO-2009/step08ex.html',
- 'GoogleIO-2009/step09ex.html',
- 'GoogleIO-2009/step10ex.html',
- 'GoogleIO-2009/step11ex.html',
- 'GoogleIO-2009/step12ex.html',
- 'GoogleIO-2009/step13ex.html',
- 'GoogleIO-2009/step14ex.html',
- 'GoogleIO-2009/shaders/checker.shader',
- 'GoogleIO-2009/assets/background.o3dtgz',
- 'GoogleIO-2009/assets/character.o3dtgz',
- 'GoogleIO-2009/assets/colorbar.png',
- 'GoogleIO-2009/assets/style.css',
- 'box2d-3d/box2d-3d.html',
- 'box2d-3d/demos/LICENSE.txt',
- 'box2d-3d/demos/README.o3d',
- 'box2d-3d/demos/compound.js',
- 'box2d-3d/demos/crank.js',
- 'box2d-3d/demos/demo_base.js',
- 'box2d-3d/demos/demos.js',
- 'box2d-3d/demos/draw_world.js',
- 'box2d-3d/demos/manager.js',
- 'box2d-3d/demos/pendulum.js',
- 'box2d-3d/demos/stack.js',
- 'box2d-3d/demos/top.js',
- 'box2d-3d/third_party/box2d/LICENSE.txt',
- 'box2d-3d/third_party/box2d/README.o3d',
- 'box2d-3d/third_party/box2d/box2d.js',
- 'box2d-3d/third_party/prototype-1.6.0.2.js',
- 'canvas-fonts.html',
- 'checkers.html',
- 'debugging.html',
- 'fullscreen.html',
- 'home-configurators/cb_images/cb_item_thumbnails.jpg',
- 'home-configurators/cb_images/toolselector.gif',
- 'home-configurators/cb_images/unbranded_bg.png',
- 'home-configurators/cbassets/Agra_Rug.o3dtgz',
- 'home-configurators/cbassets/Asimi_Rug.o3dtgz',
- 'home-configurators/cbassets/Camden_Chair.o3dtgz',
- 'home-configurators/cbassets/Elements_Bookshelf.o3dtgz',
- 'home-configurators/cbassets/Ferrara_Rug.o3dtgz',
- 'home-configurators/cbassets/House_Roofless.o3dtgz',
- 'home-configurators/cbassets/Lounge_Chair.o3dtgz',
- 'home-configurators/cbassets/Lounge_Chaise.o3dtgz',
- 'home-configurators/cbassets/Lounge_Sofa.o3dtgz',
- 'home-configurators/cbassets/Lounge_Storage_Ottoman.o3dtgz',
- 'home-configurators/cbassets/Madison_Dining_Table.o3dtgz',
- 'home-configurators/cbassets/Miles_Side_Chair.o3dtgz',
- 'home-configurators/cbassets/Pullman_Bar_Stool.o3dtgz',
- 'home-configurators/cbassets/Puzzle_TV_Stand.o3dtgz',
- 'home-configurators/cbassets/Stow_Leather_Ottoman.o3dtgz',
- 'home-configurators/cbassets/Tivoli_Dining_Table.o3dtgz',
- 'home-configurators/cbassets/Tivoli_Miles_Dining_Set.o3dtgz',
- 'home-configurators/cbassets/Troy_Chair.o3dtgz',
- 'home-configurators/cbassets/Troy_Ottoman.o3dtgz',
- 'home-configurators/cbassets/Troy_Sofa.o3dtgz',
- 'home-configurators/cbassets/Troy_Storage_Ottoman.o3dtgz',
- 'home-configurators/cbassets/Troy_Twin_Sleeper.o3dtgz',
- 'home-configurators/deletetool.js',
- 'home-configurators/homedesigner.html',
- 'home-configurators/movetool.js',
- 'home-configurators/orbittool.js',
- 'home-configurators/pantool.js',
- 'home-configurators/rotatetool.js',
- 'home-configurators/viewer.js',
- 'home-configurators/zoomtool.js',
- 'io/README.txt',
- 'io/actors/actor.js',
- 'io/actors/arrow.js',
- 'io/actors/avatar.js',
- 'io/actors/coin.js',
- 'io/actors/horizontalpad.js',
- 'io/actors/mover.js',
- 'io/actors/spikem.js',
- 'io/actors/verticalpad.js',
- 'io/autoincludes.js',
- 'io/cutscenes.js',
- 'io/dynamic_lights.js',
- 'io/editor.html',
- 'io/gamelogic.js',
- 'io/init.js',
- 'io/io.html',
- 'io/levels/all_actors.js',
- 'io/levels/all_actors.skp',
- 'io/levels/all_actors.o3dtgz',
- 'io/levels/map1.js',
- 'io/levels/map1.skp',
- 'io/levels/map1.o3dtgz',
- 'io/levels/starter_level.skp',
- 'io/sound/_MISS.mp3',
- 'io/sound/_PUNCH.mp3',
- 'io/sound/_SMASH.mp3',
- 'io/sound/_woosh.mp3',
- 'io/sound/ah.mp3',
- 'io/sound/arrow.mp3',
- 'io/sound/coin_3.mp3',
- 'io/sound/music.mp3',
- 'io/sound/page.mp3',
- 'io/sound/soundplayer.js',
- 'io/sound/soundplayer.swf',
- 'io/sound/step1.mp3',
- 'io/sound/step2.mp3',
- 'io/sound/step3.mp3',
- 'io/sound/ug.mp3',
- 'io/ui/bgtile.jpg',
- 'io/ui/book_capbottom.jpg',
- 'io/ui/book_capleft.jpg',
- 'io/ui/book_capright.jpg',
- 'io/ui/book_captop.jpg',
- 'io/ui/book_cover.jpg',
- 'io/ui/book_innercover.jpg',
- 'io/ui/book_page1.jpg',
- 'io/ui/book_page2.jpg',
- 'io/ui/book_page3.jpg',
- 'io/ui/book_pageblank.jpg',
- 'io/ui/covershadow.png',
- 'io/ui/io.css',
- 'io/ui/logo.gif',
- 'io/ui/scrollwork.gif',
- 'pingpong/instructions.gif',
- 'pingpong/logo.gif',
- 'pingpong/o3dPingPong.html',
- 'shaders/README',
- 'shaders/billboard.shader',
- 'shaders/binormal.shader',
- 'shaders/bump.shader',
- 'shaders/checker.shader',
- 'shaders/diffuse.shader',
- 'shaders/green-blue-checker.shader',
- 'shaders/imposter.shader',
- 'shaders/one-channel-texture.shader',
- 'shaders/normal.shader',
- 'shaders/phong-vertex-anim.shader',
- 'shaders/phong-with-colormult.shader',
- 'shaders/solid-color.shader',
- 'shaders/tangent.shader',
- 'shaders/texture-colormult.shader',
- 'shaders/texture-only.shader',
- 'shaders/toon.shader',
- 'shaders/vertex-color.shader',
- 'shaders/yuv2rgb.shader',
- 'shadow-map.html',
- 'simpleviewer/assets/cube.o3dtgz',
- 'simpleviewer/simpleviewer.html',
- 'trends/assets/clouds.jpg',
- 'trends/assets/earth-large-with-ocean-mask.png',
- 'trends/assets/earth-large.jpg',
- 'trends/assets/earth.jpg',
- 'trends/assets/energy.png',
- 'trends/assets/moon.jpg',
- 'trends/assets/night-large.jpg',
- 'trends/assets/night.jpg',
- 'trends/trends.html',
- 'yuv2rgb.html',
- # WebGL compatible assets
- 'assets/teapot/scene.json',
- 'assets/teapot/images/image0.png',
- 'assets/teapot/images/image1_negx.png',
- 'assets/teapot/images/image1_negy.png',
- 'assets/teapot/images/image1_negz.png',
- 'assets/teapot/images/image1_posx.png',
- 'assets/teapot/images/image1_posy.png',
- 'assets/teapot/images/image1_posz.png',
- 'assets/teapot/shaders/shader0.fx',
- 'simpleviewer/assets/cube/scene.json',
- 'simpleviewer/assets/cube/textures/crate.jpg',
-]
diff --git a/o3d/samples/animated-scene.html b/o3d/samples/animated-scene.html
deleted file mode 100644
index c9e4b72..0000000
--- a/o3d/samples/animated-scene.html
+++ /dev/null
@@ -1,228 +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.
--->
-
-<!--
-Animated Scene.
-
-Load a scene with animation and play it back.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Animated Scene.
-</title>
-<style type="text/css">
-.status { color: red; }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_finished = false; // for selenium testing
-var g_clock = 0;
-var g_timeMult = 1;
-var g_animTimeParam;
-var g_animEndTime = 249 / 30; // 249 30hz frames.
-var g_loadInfo;
-var g_downloadPercent = -1;
-
-/**
- * Sets the status message
- * @param {string} msg The message.
- */
-function setStatus(msg) {
- var element = document.getElementById('status');
- if (element) {
- element.innerHTML = msg;
- }
-}
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- */
-function loadScene(pack, fileName, parent) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- g_loadInfo = o3djs.scene.loadScene(
- g_client, pack, parent, scenePath, callback,
- { opt_animSource: g_animTimeParam});
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- g_loadInfo = null;
- if (exception) {
- setStatus('could **not** load ' + fileName + '. ' + exception);
- return;
- }
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- g_client.width,
- g_client.height);
- // Copy the view and projection to the draw context.
- g_viewInfo.drawContext.view = cameraInfo.view;
- g_viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
-
- // Reset the clock.
- g_clock = 0;
-
- setStatus('');
-
- g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create a param to bind to the animation.
- var paramObject = g_pack.createObject('ParamObject');
- g_animTimeParam = paramObject.createParam('myClock', 'ParamFloat');
-
- // Creates a transform to put our data on.
- var myDataRoot = g_pack.createObject('Transform');
-
- // Connects our root to the client root.
- myDataRoot.parent = g_client.root;
-
- // Load the scene into the transform graph as a child myDataRoot
- loadScene(g_pack, 'assets/kitty_151_idle_stand05_cff1.o3dtgz', myDataRoot);
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onRender);
-}
-
-// update the animation clock
-function onRender(render_event) {
- // Get the number of seconds since the last render.
- var elapsedTime = render_event.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- // Repeat the animation over and over.
- g_clock = g_clock % g_animEndTime;
-
- // Set the time to display.
- g_animTimeParam.value = g_clock;
-
- if (g_loadInfo) {
- var progressInfo = g_loadInfo.getKnownProgressInfoSoFar();
- if (progressInfo.percent != g_downloadPercent) {
- g_downloadPercent = progressInfo.percent;
- setStatus('Loading... ' + progressInfo.percent + '%' +
- ' (' + progressInfo.downloaded +
- ' of ' + progressInfo.totalBytes + progressInfo.suffix + ')');
- }
- }
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Animated scene.</h1>
-Loads an scene with animation and plays it back.
-<div class="status" id="status">Loading...</div>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/animation.html b/o3d/samples/animation.html
deleted file mode 100644
index 52e2ca4..0000000
--- a/o3d/samples/animation.html
+++ /dev/null
@@ -1,288 +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.
--->
-
-<!--
-O3D Animation.
-
-Shows various things being animated by O3D.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Animation.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_framesRendered = 0;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_finished = false; // for selenium
-var g_groupTransforms = [];
-var GROUPS_ACROSS = 2;
-var UNITS_ACROSS_GROUP = 2;
-var TOTAL_ACROSS = GROUPS_ACROSS * UNITS_ACROSS_GROUP;
-var HALF_WIDTH = TOTAL_ACROSS * 0.0;
-var UNIT_SPACING = 200;
-
-/**
- * Creates an oscillating animation to animate a single float from 0 to
- * endOutput over endInput seconds with a little bit of ease in, ease out.
- *
- * @param {!o3d.Pack} pack Pack to associate created objects with.
- * @param {!o3d.ParamObject} paramObject Object that has param to animate.
- * @param {string} paramName Name of the param to animate.
- * @param {number} endInput Number of seconds to take to get
- * @param {number} endOutput Target value.
- */
-function attachParamFloatAnimation(pack,
- paramObject,
- paramName,
- endInput,
- endOutput) {
- // Create a FunctionEval through which to evaluate the curve.
- var functionEval = pack.createObject('FunctionEval');
-
- // Bind the param we want to get its value from our FunctionEval's output.
- paramObject.getParam(paramName).bind(functionEval.getParam('output'));
-
- // Create a curve
- var curve = pack.createObject('Curve');
-
- // Set the functionEval to use the curve as it's function.
- functionEval.functionObject = curve;
-
- // Create 2 keys for the curve.
- var key1 = curve.createKey('BezierCurveKey');
- key1.input = 0;
- key1.output = 0;
- key1.outTangent = [0, endInput * 2 / 3];
- var key2 = curve.createKey('BezierCurveKey');
- key2.inTangent = [endInput / 3, endOutput];
- key2.input = endInput;
- key2.output = endOutput;
-
- // Set the curve to oscillate.
- curve.postInfinity = g_o3d.Curve.OSCILLATE;
-
- // Make a SecondCounter to provide an input to the functionEval.
- var counter = pack.createObject('SecondCounter');
-
- // Bind the counter's count to the input of the FunctionEval.
- functionEval.getParam('input').bind(counter.getParam('count'));
-}
-
-/**
- * Creates an oscillating animation to animate a single float of a float4 from 0
- * to endOutput over endInput seconds with a little bit of ease in, ease out.
- *
- * @param {!o3d.Pack} pack Pack to associate created objects with.
- * @param {!o3d.ParamObject} paramObject Object that has param to animate.
- * @param {string} paramName Name of the param Float4 to animate.
- * @param {string} innerParamName Name of the individual float to animate.
- * @param {number} endInput Duration of animation.
- * @param {number} endOutput Target value.
- * @return {!o3d.ParamObject} The created ParamOperation.
- */
-function attach1FloatOfFloat4Animation(pack,
- paramObject,
- paramName,
- innerParamName,
- endInput,
- endOutput) {
-
- var paramOp = pack.createObject('ParamOp4FloatsToFloat4');
- paramObject.getParam(paramName).bind(paramOp.getParam('output'));
- attachParamFloatAnimation(pack, paramOp, innerParamName, endInput, endOutput);
- return paramOp;
-}
-
-/**
- * Creates an animation to animate one of the 9 values of a TRSToMatrix4 and
- * binds it to a transform.
- *
- * @param {!o3d.Pack} pack Pack to associate created objects with.
- * @param {!o3d.Transform} transform Transform to animate.
- * @param {number} endInput Duration of animation.
- * @param {number} endOutput Target value.
- * @param {string} paramName Name of param to animate.
- * @return {!o3d.TRSToMatrix4} The created TRSToMatrix4.
- */
-function attachTRSAnimation(pack, transform, endInput, endOutput, paramName) {
- var trs = pack.createObject('TRSToMatrix4');
- transform.getParam('localMatrix').bind(trs.getParam('output'));
- attachParamFloatAnimation(pack, trs, paramName, endInput, endOutput);
- return trs;
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and sets up some shapes with animations.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create our projection matrix, with a vertical field of view of 45
- // degrees a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 10000);
-
- // Set our view
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [100, 50, 400], // Eye.
- [0, 0, 0], // Target.
- [0, 1, 0]); // Up.
-
- // Create a basic material
- var material = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [1, 1, 1, 1],
- true);
-
- var data = [ { paramName: 'translateY',
- endOutput: 50,
- color: [1, 0, 0, 1] },
- { paramName: 'rotateY',
- endOutput: Math.PI,
- color: [0, 1, 0, 1] },
- { paramName: 'scaleY',
- endOutput: 3,
- color: [1, 1, 0, 1] },
- { paramName: '',
- endOutput: Math.PI * 3,
- color: [1, 1, 0, 1] } ];
-
- for (var ii = 0; ii < 4; ++ii) {
- var xPos = (ii - 1.5) * 100;
- // Create a shape.
- var shape;
- switch (ii) {
- case 0:
- case 2:
- shape = o3djs.primitives.createSphere(g_pack, material, 40, 10, 12);
- break;
- case 1:
- case 3:
- shape = o3djs.primitives.createCube(g_pack, material, 60);
- break;
- }
-
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.addShape(shape);
-
- // Change the color of each one
- transform.createParam('diffuse', 'ParamFloat4').value = data[ii].color;
-
- switch (ii) {
- case 0:
- case 1:
- case 2:
- var trs = attachTRSAnimation(g_pack,
- transform,
- ii * 0.6 + 0.5,
- data[ii].endOutput,
- data[ii].paramName);
-
- // space them out.
- trs.translateX = xPos;
- break;
-
- case 3: {
- var paramOp = attach1FloatOfFloat4Animation(g_pack,
- transform,
- 'diffuse',
- 'input3',
- 0.5,
- 1);
- paramOp.input1 = 1;
- paramOp.input2 = 1;
- transform.translate(xPos, 0, 0);
- break;
- }
- }
- }
-
- g_finished = true; // for selenium
-}
-
-</script>
-</head>
-<body>
-<h1>Animation</h1>
-Once the scene is setup no Javascript is running.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/archive-textures.html b/o3d/samples/archive-textures.html
deleted file mode 100644
index f150bff9..0000000
--- a/o3d/samples/archive-textures.html
+++ /dev/null
@@ -1,287 +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.
--->
-
-<!--
-
-In this tutorial, we show how to progressively load in textures from a tar.gz archive.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Progressive Texture Loading
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.io');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.texture');
-
-// Events
-// Run the init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_finished = false; // for selenium testing
-var g_repeatDownload = false; // for selenium testing
-var g_streamingStarted = false;
-var g_fileCount = 0;
-var g_textureCount = 0;
-
-// This is for offsetting our textures from each other as they arrive
-var g_x = -200.0;
-var g_y = -200.0;
-
-function makeShape(texture) {
- // Create a material.
- var myMaterial = o3djs.material.createMaterialFromFile(
- g_pack,
- 'shaders/texture-only.shader',
- g_viewInfo.performanceDrawList);
-
- // Creates a quad.
- var myShape = o3djs.primitives.createPlane(g_pack,
- myMaterial,
- 300, // width
- 300, // height
- 1, // quads across
- 1); // quads down
-
- // Get the material's sampler parameter, get the sampler on it and set its
- // texture.
- var sampler_param = myMaterial.getParam('texSampler0');
- var sampler = sampler_param.value;
-
- // Set the texture to use.
- sampler.texture = texture;
-
- // adjust the scale of our transform to match the aspect ratio of
- // the texture. Of course we could also have waited until now to build
- // our plane and set its width and height to match instead of scaling
- // here.
- var textureWidth = texture.width;
- var textureHeight = texture.height;
- var hScale = 1;
- var vScale = 1;
- if (textureWidth > textureHeight) {
- vScale = textureHeight / textureWidth;
- } else if (textureHeight > textureWidth) {
- hScale = textureWidth / textureHeight;
- }
- // We now attach our quad to the root of the transform graph.
- // We do this after the texture has loaded, otherwise we'd be attempting
- // to display something invalid.
-
- // Make a transform for each quad.
- var transform = g_pack.createObject('Transform');
-
- transform.translate(g_x, g_textureCount, g_y);
- transform.scale(hScale, 1, vScale);
- transform.addShape(myShape);
- transform.parent = g_client.root;
-
- // Diagonally offset the next texture we load
- g_x += 5.0;
- g_y += 5.0;
-
- return myShape;
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Spawns a raw-data request, creating a textured quad for each true
- * in the downloaded archive_textures.tar.gz file.
- */
-function createArchiveRequest() {
- // Start a request for loading the tar.gz archive containing a bunch of
- // image files. We'll then make textures from each one...
- var loadInfo = o3djs.io.loadArchiveAdvanced(
- g_pack,
- './assets/archive_textures.o3dtgz',
- onFileAvailable,
- function(request, exception) {
- // We are finished with the request so remove it.
- g_pack.removeObject(request);
-
- // Check for errors.
- if (!exception) {
- // When run in selenium this sample will continuously spawn a data
- // request so that it can verify that a page refresh during a
- // download does not crash or hang the browser.
- if (g_repeatDownload) {
- createArchiveRequest();
- }
- g_finished = true;
- } else {
- alert('Failed to load archive!\n' + exception);
- }
- });
-
- // This is called for each file in the archive as it arrives
- function onFileAvailable(rawData) {
- g_streamingStarted = true;
-
- // Create a texture from the RawData object that was just made available.
- var texture = o3djs.texture.createTextureFromRawData(g_pack, rawData, true);
-
- // Free the raw data object immediately since we're done with it.
- // If we don't call this the RawData will stay around so we can use it
- // later. For this app we won't need it later so we discard it now.
- rawData.discard();
-
- // Verify that the texture was created correctly and count it if so...
- if (texture) g_textureCount++; // for selenium testing
-
- // Display progress information.
- var n = loadInfo.getTotalBytesDownloaded();
- var streamLength = loadInfo.getTotalKnownBytesToStreamSoFar();
-
- var progressInfo = n + ' bytes of ' + streamLength;
- var fileInfo = 'file name = ' + rawData.uri
- + ' :: length = ' + rawData.length + ' bytes';
-
- var info = document.getElementById('info');
-
- var textureInfo = 'texture = ' + texture.width + 'x' + texture.height;
-
- // If the page is reloaded before all of the textures have been created,
- // IE will still invoke this call-back (even after the 'info' element has
- // been removed).
- if (info) {
- info.innerHTML = info.innerHTML + progressInfo + " :: " + fileInfo +
- " :: " + textureInfo + "<br>";
- }
-
- g_fileCount++;
-
- if (texture) {
- var shape = makeShape(texture);
- }
- }
-}
-
-/**
- * Initializes the O3D global variables.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-}
-
-/**
- * Loads the O3D effect, and loads a tar.gz archive containing a bunch of image
- * files. We'll create textures from them as they come in.
- */
-function startLoad() {
- // Disallow streaming of the content more than once.
- document.getElementById("startLoad").disabled = true;
- var clearId = window.setInterval(function() {
- // Wait until the page has finished loading, and the client O3D areas have
- // been created.
- if (!g_client) {
- return;
- } else {
- window.clearInterval(clearId);
- }
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set up an orthographic projection.
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -g_client.width * 0.5,
- g_client.width * 0.5,
- -g_client.height * 0.5,
- g_client.height * 0.5,
- 0.1,
- 1000);
-
- // Move the camera above the origin looking down.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 500, 0], // eye
- [0, 0, 0], // target
- [0, 0, -1]); // up
-
- createArchiveRequest();
- }, 200);
-}
-
-</script>
-</head>
-<body>
-<h1>Progressive archive loading</h1>
-This tutorial shows how to load textures progressively from a compressed archive.
-<br><br/>
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px"></div>
-<!-- End of O3D plugin -->
-
-<br><br/>
-
-<!-- This div is for logging the progress of the progressive loading -->
-<div>
-<input type="button" id="startLoad" value="Start Loading" onclick="startLoad()" />
-</div>
-<div id="info">
- <h1>File Loading Progress</h1>
-</div>
-
-
-</body>
-</html>
diff --git a/o3d/samples/assets/android.png b/o3d/samples/assets/android.png
deleted file mode 100644
index 8ffbc61..0000000
--- a/o3d/samples/assets/android.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/archive_textures.o3dtgz b/o3d/samples/assets/archive_textures.o3dtgz
deleted file mode 100644
index 1d1cf35..0000000
--- a/o3d/samples/assets/archive_textures.o3dtgz
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/block.png b/o3d/samples/assets/block.png
deleted file mode 100644
index b0e45c6..0000000
--- a/o3d/samples/assets/block.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/brush.png b/o3d/samples/assets/brush.png
deleted file mode 100644
index 6e9079f..0000000
--- a/o3d/samples/assets/brush.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/egg.png b/o3d/samples/assets/egg.png
deleted file mode 100644
index caa2718..0000000
--- a/o3d/samples/assets/egg.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/empty.txt b/o3d/samples/assets/empty.txt
deleted file mode 100644
index e69de29..0000000
--- a/o3d/samples/assets/empty.txt
+++ /dev/null
diff --git a/o3d/samples/assets/four_pixel.png b/o3d/samples/assets/four_pixel.png
deleted file mode 100644
index 02e84a3..0000000
--- a/o3d/samples/assets/four_pixel.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/fullscreen.png b/o3d/samples/assets/fullscreen.png
deleted file mode 100644
index a4edb49..0000000
--- a/o3d/samples/assets/fullscreen.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/gauge.png b/o3d/samples/assets/gauge.png
deleted file mode 100644
index 4813779..0000000
--- a/o3d/samples/assets/gauge.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/gaugeback.png b/o3d/samples/assets/gaugeback.png
deleted file mode 100644
index 5d713f0..0000000
--- a/o3d/samples/assets/gaugeback.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/gears_init.js b/o3d/samples/assets/gears_init.js
deleted file mode 100644
index 5f44f09b..0000000
--- a/o3d/samples/assets/gears_init.js
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright 2007, Google Inc.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-// 2. 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.
-// 3. 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 AUTHOR ``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 AUTHOR 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.
-//
-// Sets up google.gears.*, which is *the only* supported way to access Gears.
-//
-// Circumvent this file at your own risk!
-//
-// In the future, Gears may automatically define google.gears.* without this
-// file. Gears may use these objects to transparently fix bugs and compatibility
-// issues. Applications that use the code below will continue to work seamlessly
-// when that happens.
-
-(function() {
- // We are already defined. Hooray!
- if (window.google && google.gears) {
- return;
- }
-
- var factory = null;
-
- // Firefox
- if (typeof GearsFactory != 'undefined') {
- factory = new GearsFactory();
- } else {
- // IE
- try {
- factory = new ActiveXObject('Gears.Factory');
- // privateSetGlobalObject is only required and supported on WinCE.
- if (factory.getBuildInfo().indexOf('ie_mobile') != -1) {
- factory.privateSetGlobalObject(this);
- }
- } catch (e) {
- // Safari
- if ((typeof navigator.mimeTypes != 'undefined')
- && navigator.mimeTypes["application/x-googlegears"]) {
- factory = document.createElement("object");
- factory.style.display = "none";
- factory.width = 0;
- factory.height = 0;
- factory.type = "application/x-googlegears";
- document.documentElement.appendChild(factory);
- }
- }
- }
-
- // *Do not* define any objects if Gears is not installed. This mimics the
- // behavior of Gears defining the objects in the future.
- if (!factory) {
- return;
- }
-
- // Now set up the objects, being careful not to overwrite anything.
- //
- // Note: In Internet Explorer for Windows Mobile, you can't add properties to
- // the window object. However, global objects are automatically added as
- // properties of the window object in all browsers.
- if (!window.google) {
- google = {};
- }
-
- if (!google.gears) {
- google.gears = {factory: factory};
- }
-})();
diff --git a/o3d/samples/assets/google-square.png b/o3d/samples/assets/google-square.png
deleted file mode 100644
index 4917f34..0000000
--- a/o3d/samples/assets/google-square.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/hi.jpg b/o3d/samples/assets/hi.jpg
deleted file mode 100644
index d65cdcc..0000000
--- a/o3d/samples/assets/hi.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/iconback.png b/o3d/samples/assets/iconback.png
deleted file mode 100644
index 28ccf80..0000000
--- a/o3d/samples/assets/iconback.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/normalmap.dds b/o3d/samples/assets/normalmap.dds
deleted file mode 100644
index ed1fdd7..0000000
--- a/o3d/samples/assets/normalmap.dds
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/old-school-shadow.png b/o3d/samples/assets/old-school-shadow.png
deleted file mode 100644
index 1a17773..0000000
--- a/o3d/samples/assets/old-school-shadow.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/one-pixel-white.png b/o3d/samples/assets/one-pixel-white.png
deleted file mode 100644
index 823a18d..0000000
--- a/o3d/samples/assets/one-pixel-white.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/one-pixel-white.tga b/o3d/samples/assets/one-pixel-white.tga
deleted file mode 100644
index fa26977..0000000
--- a/o3d/samples/assets/one-pixel-white.tga
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/orange-flower.png b/o3d/samples/assets/orange-flower.png
deleted file mode 100644
index 6b68390..0000000
--- a/o3d/samples/assets/orange-flower.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/particle-anim.png b/o3d/samples/assets/particle-anim.png
deleted file mode 100644
index e78cfe7..0000000
--- a/o3d/samples/assets/particle-anim.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/pillar.png b/o3d/samples/assets/pillar.png
deleted file mode 100644
index 11fe2a4..0000000
--- a/o3d/samples/assets/pillar.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/poolballs.png b/o3d/samples/assets/poolballs.png
deleted file mode 100644
index 974618a..0000000
--- a/o3d/samples/assets/poolballs.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/purple-flower.png b/o3d/samples/assets/purple-flower.png
deleted file mode 100644
index 1c1c24c..0000000
--- a/o3d/samples/assets/purple-flower.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/radar.png b/o3d/samples/assets/radar.png
deleted file mode 100644
index 113ca84..0000000
--- a/o3d/samples/assets/radar.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/ripple.png b/o3d/samples/assets/ripple.png
deleted file mode 100644
index 78c2d76..0000000
--- a/o3d/samples/assets/ripple.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/rock_bumps.jpg b/o3d/samples/assets/rock_bumps.jpg
deleted file mode 100644
index 0744fe4..0000000
--- a/o3d/samples/assets/rock_bumps.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/rock_texture.jpg b/o3d/samples/assets/rock_texture.jpg
deleted file mode 100644
index d298941..0000000
--- a/o3d/samples/assets/rock_texture.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/shaving_cream.jpg b/o3d/samples/assets/shaving_cream.jpg
deleted file mode 100644
index 0d2bd09..0000000
--- a/o3d/samples/assets/shaving_cream.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/shaving_cream.png b/o3d/samples/assets/shaving_cream.png
deleted file mode 100644
index 9d9b4b0..0000000
--- a/o3d/samples/assets/shaving_cream.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/shaving_cream_300x300.jpg b/o3d/samples/assets/shaving_cream_300x300.jpg
deleted file mode 100644
index 7e288ed..0000000
--- a/o3d/samples/assets/shaving_cream_300x300.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/square.png b/o3d/samples/assets/square.png
deleted file mode 100644
index fe6ca68..0000000
--- a/o3d/samples/assets/square.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/assets/teapot_vertices.js b/o3d/samples/assets/teapot_vertices.js
deleted file mode 100644
index 5e31812..0000000
--- a/o3d/samples/assets/teapot_vertices.js
+++ /dev/null
@@ -1,32 +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.
- */
-
-var g_teapotVertices = [17.8349, 0, 30.574, 17.586, 0, 31.5146, 17.8747, 0, 31.8281, 18.4619, 0, 31.5146, 19.1088, 0, 30.574, 16.4527, -7.00018, 30.574, 16.2231, -6.90252, 31.5146, 16.4894, -7.01581, 31.8281, 17.0311, -7.24628, 31.5146, 17.6278, -7.5002, 30.574, 12.6627, -12.6627, 30.574, 12.4861, -12.4861, 31.5146, 12.691, -12.691, 31.8281, 13.1079, -13.1079, 31.5146, 13.5672, -13.5672, 30.574, 7.00018, -16.4527, 30.574, 6.90252, -16.2231, 31.5146, 7.01581, -16.4894, 31.8281, 7.24628, -17.0311, 31.5146, 7.5002, -17.6278, 30.574, 0, -17.8349, 30.574, 0, -17.586, 31.5146, 0, -17.8747, 31.8281, 0, -18.4619, 31.5146, 0, -19.1088, 30.574, -7.48387, -16.4527, 30.574, -7.10658, -16.2231, 31.5146, -7.07627, -16.4894, 31.8281, -7.25384, -17.0311, 31.5146, -7.5002, -17.6278, 30.574, -13.0927, -12.6627, 30.574, -12.6675, -12.4861, 31.5146, -12.7448, -12.691, 31.8281, -13.1146, -13.1079, 31.5146, -13.5672, -13.5672, 30.574, -16.6139, -7.00018, 30.574, -16.2911, -6.90252, 31.5146, -16.5095, -7.01581, 31.8281, -17.0336, -7.24628, 31.5146, -17.6278, -7.5002, 30.574, -17.8349, 0, 30.574, -17.586, 0, 31.5146, -17.8747, 0, 31.8281, -18.4619, 0, 31.5146, -19.1088, 0, 30.574, -16.4527, 7.00018, 30.574, -16.2231, 6.90252, 31.5146, -16.4894, 7.01581, 31.8281, -17.0311, 7.24628, 31.5146, -17.6278, 7.5002, 30.574, -12.6627, 12.6627, 30.574, -12.4861, 12.4861, 31.5146, -12.691, 12.691, 31.8281, -13.1079, 13.1079, 31.5146, -13.5672, 13.5672, 30.574, -7.00018, 16.4527, 30.574, -6.90252, 16.2231, 31.5146, -7.01581, 16.4894, 31.8281, -7.24628, 17.0311, 31.5146, -7.5002, 17.6278, 30.574, 0, 17.8349, 30.574, 0, 17.586, 31.5146, 0, 17.8747, 31.8281, 0, 18.4619, 31.5146, 0, 19.1088, 30.574, 7.00018, 16.4527, 30.574, 6.90252, 16.2231, 31.5146, 7.01581, 16.4894, 31.8281, 7.24628, 17.0311, 31.5146, 7.5002, 17.6278, 30.574, 12.6627, 12.6627, 30.574, 12.4861, 12.4861, 31.5146, 12.691, 12.691, 31.8281, 13.1079, 13.1079, 31.5146, 13.5672, 13.5672, 30.574, 16.4527, 7.00018, 30.574, 16.2231, 6.90252, 31.5146, 16.4894, 7.01581, 31.8281, 17.0311, 7.24628, 31.5146, 17.6278, 7.5002, 30.574, 21.4476, 0, 25.5729, 23.4879, 0, 20.6614, 24.931, 0, 15.929, 25.4784, 0, 11.4653, 19.7854, -8.41819, 25.5729, 21.6676, -9.21899, 20.6614, 22.9988, -9.78541, 15.929, 23.5038, -10.0003, 11.4653, 15.2278, -15.2278, 25.5729, 16.6764, -16.6764, 20.6614, 17.701, -17.701, 15.929, 18.0896, -18.0896, 11.4653, 8.41819, -19.7854, 25.5729, 9.21899, -21.6676, 20.6614, 9.78541, -22.9988, 15.929, 10.0003, -23.5038, 11.4653, 0, -21.4476, 25.5729, 0, -23.4879, 20.6614, 0, -24.931, 15.929, 0, -25.4784, 11.4653, -8.41819, -19.7854, 25.5729, -9.21899, -21.6676, 20.6614, -9.78541, -22.9988, 15.929, -10.0003, -23.5038, 11.4653, -15.2278, -15.2278, 25.5729, -16.6764, -16.6764, 20.6614, -17.701, -17.701, 15.929, -18.0896, -18.0896, 11.4653, -19.7854, -8.41819, 25.5729, -21.6676, -9.21899, 20.6614, -22.9988, -9.78541, 15.929, -23.5038, -10.0003, 11.4653, -21.4476, 0, 25.5729, -23.4879, 0, 20.6614, -24.931, 0, 15.929, -25.4784, 0, 11.4653, -19.7854, 8.41819, 25.5729, -21.6676, 9.21899, 20.6614, -22.9988, 9.78541, 15.929, -23.5038, 10.0003, 11.4653, -15.2278, 15.2278, 25.5729, -16.6764, 16.6764, 20.6614, -17.701, 17.701, 15.929, -18.0896, 18.0896, 11.4653, -8.41819, 19.7854, 25.5729, -9.21899, 21.6676, 20.6614, -9.78541, 22.9988, 15.929, -10.0003, 23.5038, 11.4653, 0, 21.4476, 25.5729, 0, 23.4879, 20.6614, 0, 24.931, 15.929, 0, 25.4784, 11.4653, 8.41819, 19.7854, 25.5729, 9.21899, 21.6676, 20.6614, 9.78541, 22.9988, 15.929, 10.0003, 23.5038, 11.4653, 15.2278, 15.2278, 25.5729, 16.6764, 16.6764, 20.6614, 17.701, 17.701, 15.929, 18.0896, 18.0896, 11.4653, 19.7854, 8.41819, 25.5729, 21.6676, 9.21899, 20.6614, 22.9988, 9.78541, 15.929, 23.5038, 10.0003, 11.4653, 24.4831, 0, 7.6883, 22.2936, 0, 4.89662, 20.104, 0, 3.00067, 19.1088, 0, 1.91088, 22.5857, -9.60962, 7.6883, 20.5658, -8.75023, 4.89662, 18.546, -7.89083, 3.00067, 17.6278, -7.5002, 1.91088, 17.383, -17.383, 7.6883, 15.8284, -15.8284, 4.89662, 14.2739, -14.2739, 3.00067, 13.5672, -13.5672, 1.91088, 9.60962, -22.5857, 7.6883, 8.75023, -20.5658, 4.89662, 7.89083, -18.546, 3.00067, 7.5002, -17.6278, 1.91088, 0, -24.4831, 7.6883, 0, -22.2936, 4.89662, 0, -20.104, 3.00067, 0, -19.1088, 1.91088, -9.60962, -22.5857, 7.6883, -8.75023, -20.5658, 4.89662, -7.89083, -18.546, 3.00067, -7.5002, -17.6278, 1.91088, -17.383, -17.383, 7.6883, -15.8284, -15.8284, 4.89662, -14.2739, -14.2739, 3.00067, -13.5672, -13.5672, 1.91088, -22.5857, -9.60962, 7.6883, -20.5658, -8.75023, 4.89662, -18.546, -7.89083, 3.00067, -17.6278, -7.5002, 1.91088, -24.4831, 0, 7.6883, -22.2936, 0, 4.89662, -20.104, 0, 3.00067, -19.1088, 0, 1.91088, -22.5857, 9.60962, 7.6883, -20.5658, 8.75023, 4.89662, -18.546, 7.89083, 3.00067, -17.6278, 7.5002, 1.91088, -17.383, 17.383, 7.6883, -15.8284, 15.8284, 4.89662, -14.2739, 14.2739, 3.00067, -13.5672, 13.5672, 1.91088, -9.60962, 22.5857, 7.6883, -8.75023, 20.5658, 4.89662, -7.89083, 18.546, 3.00067, -7.5002, 17.6278, 1.91088, 0, 24.4831, 7.6883, 0, 22.2936, 4.89662, 0, 20.104, 3.00067, 0, 19.1088, 1.91088, 9.60962, 22.5857, 7.6883, 8.75023, 20.5658, 4.89662, 7.89083, 18.546, 3.00067, 7.5002, 17.6278, 1.91088, 17.383, 17.383, 7.6883, 15.8284, 15.8284, 4.89662, 14.2739, 14.2739, 3.00067, 13.5672, 13.5672, 1.91088, 22.5857, 9.60962, 7.6883, 20.5658, 8.75023, 4.89662, 18.546, 7.89083, 3.00067, 17.6278, 7.5002, 1.91088, 18.6758, 0, 1.20923, 16.3619, 0, 0.597149, 10.6442, 0, 0.164216, 0, 0, 0, 17.2285, -7.33027, 1.20923, 15.0938, -6.42204, 0.597149, 9.81926, -4.17784, 0.164216, 13.2598, -13.2598, 1.20923, 11.6169, -11.6169, 0.597149, 7.55737, -7.55737, 0.164216, 7.33027, -17.2285, 1.20923, 6.42204, -15.0938, 0.597149, 4.17784, -9.81926, 0.164216, 0, -18.6758, 1.20923, 0, -16.3619, 0.597149, 0, -10.6442, 0.164216, -7.33027, -17.2285, 1.20923, -6.42204, -15.0938, 0.597149, -4.17784, -9.81926, 0.164216, -13.2598, -13.2598, 1.20923, -11.6169, -11.6169, 0.597149, -7.55737, -7.55737, 0.164216, -17.2285, -7.33027, 1.20923, -15.0938, -6.42204, 0.597149, -9.81926, -4.17784, 0.164216, -18.6758, 0, 1.20923, -16.3619, 0, 0.597149, -10.6442, 0, 0.164216, -17.2285, 7.33027, 1.20923, -15.0938, 6.42204, 0.597149, -9.81926, 4.17784, 0.164216, -13.2598, 13.2598, 1.20923, -11.6169, 11.6169, 0.597149, -7.55737, 7.55737, 0.164216, -7.33027, 17.2285, 1.20923, -6.42204, 15.0938, 0.597149, -4.17784, 9.81926, 0.164216, 0, 18.6758, 1.20923, 0, 16.3619, 0.597149, 0, 10.6442, 0.164216, 7.33027, 17.2285, 1.20923, 6.42204, 15.0938, 0.597149, 4.17784, 9.81926, 0.164216, 13.2598, 13.2598, 1.20923, 11.6169, 11.6169, 0.597149, 7.55737, 7.55737, 0.164216, 17.2285, 7.33027, 1.20923, 15.0938, 6.42204, 0.597149, 9.81926, 4.17784, 0.164216, -20.3827, 0, 25.7969, -26.3343, 0, 25.7521, -30.7333, 0, 25.4386, -33.4603, 0, 24.5876, -34.3958, 0, 22.9305, -20.1836, -2.14974, 26.2447, -26.5116, -2.14974, 26.1929, -31.1563, -2.14974, 25.8304, -34.017, -2.14974, 24.8465, -34.9929, -2.14974, 22.9305, -19.7457, -2.86632, 27.23, -26.9016, -2.86632, 27.1628, -32.0868, -2.86632, 26.6926, -35.2418, -2.86632, 25.4162, -36.3067, -2.86632, 22.9305, -19.3078, -2.14974, 28.2153, -27.2916, -2.14974, 28.1327, -33.0174, -2.14974, 27.5547, -36.4665, -2.14974, 25.9858, -37.6204, -2.14974, 22.9305, -19.1088, 0, 28.6632, -27.4689, 0, 28.5736, -33.4404, 0, 27.9466, -37.0233, 0, 26.2447, -38.2176, 0, 22.9305, -19.3078, 2.14974, 28.2153, -27.2916, 2.14974, 28.1327, -33.0174, 2.14974, 27.5547, -36.4665, 2.14974, 25.9858, -37.6204, 2.14974, 22.9305, -19.7457, 2.86632, 27.23, -26.9016, 2.86632, 27.1628, -32.0868, 2.86632, 26.6926, -35.2418, 2.86632, 25.4162, -36.3067, 2.86632, 22.9305, -20.1836, 2.14974, 26.2447, -26.5116, 2.14974, 26.1929, -31.1563, 2.14974, 25.8304, -34.017, 2.14974, 24.8465, -34.9929, 2.14974, 22.9305, -33.8982, 0, 20.3329, -32.3257, 0, 17.1979, -29.5589, 0, 14.0629, -25.4784, 0, 11.4653, -34.4409, -2.14974, 20.0822, -32.7113, -2.14974, 16.8153, -29.6942, -2.14974, 13.5905, -25.2793, -2.14974, 10.8681, -35.6349, -2.86632, 19.5305, -33.5598, -2.86632, 15.9737, -29.9918, -2.86632, 12.5513, -24.8414, -2.86632, 9.55439, -36.8289, -2.14974, 18.9788, -34.4082, -2.14974, 15.1321, -30.2895, -2.14974, 11.5122, -24.4035, -2.14974, 8.24066, -37.3716, 0, 18.7281, -34.7939, 0, 14.7496, -30.4248, 0, 11.0398, -24.2045, 0, 7.64351, -36.8289, 2.14974, 18.9788, -34.4082, 2.14974, 15.1321, -30.2895, 2.14974, 11.5122, -24.4035, 2.14974, 8.24066, -35.6349, 2.86632, 19.5305, -33.5598, 2.86632, 15.9737, -29.9918, 2.86632, 12.5513, -24.8414, 2.86632, 9.55439, -34.4409, 2.14974, 20.0822, -32.7113, 2.14974, 16.8153, -29.6942, 2.14974, 13.5905, -25.2793, 2.14974, 10.8681, 21.6566, 0, 18.1533, 27.7674, 0, 19.5566, 30.4148, 0, 22.9305, 31.8679, 0, 27.021, 34.3958, 0, 30.574, 21.6566, -4.72942, 16.5112, 28.234, -4.27036, 18.339, 31.0119, -3.26044, 22.2214, 32.5956, -2.25051, 26.7644, 35.5901, -1.79145, 30.574, 21.6566, -6.3059, 12.8984, 29.2603, -5.69382, 15.6602, 32.3257, -4.34725, 20.6614, 34.1967, -3.00067, 26.1999, 38.2176, -2.3886, 30.574, 21.6566, -4.72942, 9.28567, 30.2867, -4.27036, 12.9815, 33.6394, -3.26044, 19.1013, 35.7979, -2.25051, 25.6354, 40.845, -1.79145, 30.574, 21.6566, 0, 7.64351, 30.7532, 0, 11.7638, 34.2366, 0, 18.3922, 36.5256, 0, 25.3788, 42.0393, 0, 30.574, 21.6566, 4.72942, 9.28567, 30.2867, 4.27036, 12.9815, 33.6394, 3.26044, 19.1013, 35.7979, 2.25051, 25.6354, 40.845, 1.79145, 30.574, 21.6566, 6.3059, 12.8984, 29.2603, 5.69382, 15.6602, 32.3257, 4.34725, 20.6614, 34.1967, 3.00067, 26.1999, 38.2176, 2.3886, 30.574, 21.6566, 4.72942, 16.5112, 28.234, 4.27036, 18.339, 31.0119, 3.26044, 22.2214, 32.5956, 2.25051, 26.7644, 35.5901, 1.79145, 30.574, 35.3114, 0, 31.1115, 35.9882, 0, 31.2906, 36.1872, 0, 31.1115, 35.6697, 0, 30.574, 36.5905, -1.67948, 31.1377, 37.1887, -1.43316, 31.3326, 37.2066, -1.18683, 31.1482, 36.4659, -1.07487, 30.574, 39.4044, -2.23931, 31.1955, 39.8299, -1.91088, 31.425, 39.4492, -1.58245, 31.229, 38.2176, -1.43316, 30.574, 42.2183, -1.67948, 31.2532, 42.471, -1.43316, 31.5174, 41.6917, -1.18683, 31.3099, 39.9692, -1.07487, 30.574, 43.4973, 0, 31.2794, 43.6715, 0, 31.5593, 42.7111, 0, 31.3466, 40.7654, 0, 30.574, 42.2183, 1.67948, 31.2532, 42.471, 1.43316, 31.5174, 41.6917, 1.18683, 31.3099, 39.9692, 1.07487, 30.574, 39.4044, 2.23931, 31.1955, 39.8299, 1.91088, 31.425, 39.4492, 1.58245, 31.229, 38.2176, 1.43316, 30.574, 36.5905, 1.67948, 31.1377, 37.1887, 1.43316, 31.3326, 37.2066, 1.18683, 31.1482, 36.4659, 1.07487, 30.574, 0, 0, 40.1284, 4.33928, 0, 39.5014, 4.14023, 0, 37.9787, 2.50803, 0, 36.0977, 2.54784, 0, 34.3958, 4.0045, -1.7077, 39.5014, 3.82071, -1.62907, 37.9787, 2.31416, -0.985912, 36.0977, 2.35038, -1.00003, 34.3958, 3.08492, -3.08492, 39.5014, 2.94315, -2.94315, 37.9787, 1.78204, -1.78204, 36.0977, 1.80896, -1.80896, 34.3958, 1.7077, -4.0045, 39.5014, 1.62907, -3.82071, 37.9787, 0.985912, -2.31416, 36.0977, 1.00003, -2.35038, 34.3958, 0, -4.33928, 39.5014, 0, -4.14023, 37.9787, 0, -2.50803, 36.0977, 0, -2.54784, 34.3958, -1.7077, -4.0045, 39.5014, -1.62907, -3.82071, 37.9787, -0.985912, -2.31416, 36.0977, -1.00003, -2.35038, 34.3958, -3.08492, -3.08492, 39.5014, -2.94315, -2.94315, 37.9787, -1.78204, -1.78204, 36.0977, -1.80896, -1.80896, 34.3958, -4.0045, -1.7077, 39.5014, -3.82071, -1.62907, 37.9787, -2.31416, -0.985912, 36.0977, -2.35038, -1.00003, 34.3958, -4.33928, 0, 39.5014, -4.14023, 0, 37.9787, -2.50803, 0, 36.0977, -2.54784, 0, 34.3958, -4.0045, 1.7077, 39.5014, -3.82071, 1.62907, 37.9787, -2.31416, 0.985912, 36.0977, -2.35038, 1.00003, 34.3958, -3.08492, 3.08492, 39.5014, -2.94315, 2.94315, 37.9787, -1.78204, 1.78204, 36.0977, -1.80896, 1.80896, 34.3958, -1.7077, 4.0045, 39.5014, -1.62907, 3.82071, 37.9787, -0.985912, 2.31416, 36.0977, -1.00003, 2.35038, 34.3958, 0, 4.33928, 39.5014, 0, 4.14023, 37.9787, 0, 2.50803, 36.0977, 0, 2.54784, 34.3958, 1.7077, 4.0045, 39.5014, 1.62907, 3.82071, 37.9787, 0.985912, 2.31416, 36.0977, 1.00003, 2.35038, 34.3958, 3.08492, 3.08492, 39.5014, 2.94315, 2.94315, 37.9787, 1.78204, 1.78204, 36.0977, 1.80896, 1.80896, 34.3958, 4.0045, 1.7077, 39.5014, 3.82071, 1.62907, 37.9787, 2.31416, 0.985912, 36.0977, 2.35038, 1.00003, 34.3958, 5.81225, 0, 33.2612, 10.5098, 0, 32.4849, 14.7297, 0, 31.7086, 16.5609, 0, 30.574, 5.3618, -2.28131, 33.2612, 9.69532, -4.12511, 32.4849, 13.5881, -5.7814, 31.7086, 15.2775, -6.50017, 30.574, 4.1267, -4.1267, 33.2612, 7.46198, -7.46198, 32.4849, 10.4581, -10.4581, 31.7086, 11.7583, -11.7583, 30.574, 2.28131, -5.3618, 33.2612, 4.12511, -9.69532, 32.4849, 5.7814, -13.5881, 31.7086, 6.50017, -15.2775, 30.574, 0, -5.81225, 33.2612, 0, -10.5098, 32.4849, 0, -14.7297, 31.7086, 0, -16.5609, 30.574, -2.28131, -5.3618, 33.2612, -4.12511, -9.69532, 32.4849, -5.7814, -13.5881, 31.7086, -6.50017, -15.2775, 30.574, -4.1267, -4.1267, 33.2612, -7.46198, -7.46198, 32.4849, -10.4581, -10.4581, 31.7086, -11.7583, -11.7583, 30.574, -5.3618, -2.28131, 33.2612, -9.69532, -4.12511, 32.4849, -13.5881, -5.7814, 31.7086, -15.2775, -6.50017, 30.574, -5.81225, 0, 33.2612, -10.5098, 0, 32.4849, -14.7297, 0, 31.7086, -16.5609, 0, 30.574, -5.3618, 2.28131, 33.2612, -9.69532, 4.12511, 32.4849, -13.5881, 5.7814, 31.7086, -15.2775, 6.50017, 30.574, -4.1267, 4.1267, 33.2612, -7.46198, 7.46198, 32.4849, -10.4581, 10.4581, 31.7086, -11.7583, 11.7583, 30.574, -2.28131, 5.3618, 33.2612, -4.12511, 9.69532, 32.4849, -5.7814, 13.5881, 31.7086, -6.50017, 15.2775, 30.574, 0, 5.81225, 33.2612, 0, 10.5098, 32.4849, 0, 14.7297, 31.7086, 0, 16.5609, 30.574, 2.28131, 5.3618, 33.2612, 4.12511, 9.69532, 32.4849, 5.7814, 13.5881, 31.7086, 6.50017, 15.2775, 30.574, 4.1267, 4.1267, 33.2612, 7.46198, 7.46198, 32.4849, 10.4581, 10.4581, 31.7086, 11.7583, 11.7583, 30.574, 5.3618, 2.28131, 33.2612, 9.69532, 4.12511, 32.4849, 13.5881, 5.7814, 31.7086, 15.2775, 6.50017, 30.574];
diff --git a/o3d/samples/assets/texture_b3.jpg b/o3d/samples/assets/texture_b3.jpg
deleted file mode 100644
index 01170c8..0000000
--- a/o3d/samples/assets/texture_b3.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/beachdemo/assets/pe_fire.jpg b/o3d/samples/beachdemo/assets/pe_fire.jpg
deleted file mode 100644
index 2a2c959..0000000
--- a/o3d/samples/beachdemo/assets/pe_fire.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/beachdemo/assets/pe_mist.png b/o3d/samples/beachdemo/assets/pe_mist.png
deleted file mode 100644
index 41d895a..0000000
--- a/o3d/samples/beachdemo/assets/pe_mist.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/beachdemo/assets/sky-cubemap.dds b/o3d/samples/beachdemo/assets/sky-cubemap.dds
deleted file mode 100644
index 2bfdada..0000000
--- a/o3d/samples/beachdemo/assets/sky-cubemap.dds
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/beachdemo/beachdemo-glsl.html b/o3d/samples/beachdemo/beachdemo-glsl.html
deleted file mode 100644
index c194714..0000000
--- a/o3d/samples/beachdemo/beachdemo-glsl.html
+++ /dev/null
@@ -1,150 +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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
- <title>
- Beach Demo
- </title>
-<style type="text/css">
-html, body {
- margin: 0;
- padding: 0;
- border: 0;
- height: 100%;
-}
-textarea {
- width: 95%;
- height: 95%;
-}
-#proppanel {
- font-size: xx-small;
- background-color: lightblue;
- font-family: Arial, san-serif;
-}
-#materialpanel table {
- width: 100%;
-}
-#proppanel .even {
- background-color: #ccddff;
-}
-#proppanel .odd {
- background-color: #ffffff;
-}
-
-#materialpanel {
- font-size: xx-small;
- font-family: Arial, san-serif;
-}
-#materialpanel table {
- width: 100%;
-}
-#materialpanel input[type=text] {
- font-size: x-small;
-}
-#materialpanel .even {
- background-color: #ccddff;
-}
-#materialpanel .odd {
- background-color: #ccddff;
-}
-
-#materialpanel label {
-}
-#materialpanel .field {
- white-space: nowrap;
-}
-#materialpanel label {
-}
-#effectpanel {
- background-color: lightgreen;
-}
-#effecttabs {
-}
-#effecttabs .tab {
-}
-#effecttabs .selected {
- background-color: yellow;
-}
-</style>
-</head>
-<body onload="init()" onunload="uninit()">
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" src="beachdemo-glsl.js"></script>
-<div style="width: 100%; height: 100%;">
- <div id="upperpanel" style="width: 100%; height: 100%;">
- <div
- id="o3d"
- style="
- width: 100%;
- height: 100%;
- float: left;
- background-color: blue;
- "></div>
- <div
- id="materialpanel"
- style="
- width: 20%;
- height: 100%;
- overflow: auto;
- display: none;
- "><table><tr><td><input type="text" value="foogoo"/></td></tr></table></div>
- <div
- id="proppanel"
- style="
- width: 20%;
- height: 100%;
- overflow: auto;
- display: none;
- "></div>
- </div>
- <div
- id="effectpanel"
- style="
- width: 100%;
- height: 30%;
- display: none;
- overflow: auto;
- ">
-<div style="height:10%;">
- <input type="button" value="Compile" id="compileButton"></input>
- <span id="effecttabs"></span>
-</div>
-<div style="height:90%;"><textarea id="effecttextarea"></textarea>
-</div>
- </div>
-</div>
-</body>
-</html>
-
-
diff --git a/o3d/samples/beachdemo/beachdemo-glsl.js b/o3d/samples/beachdemo/beachdemo-glsl.js
deleted file mode 100644
index 2506690..0000000
--- a/o3d/samples/beachdemo/beachdemo-glsl.js
+++ /dev/null
@@ -1,2779 +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.
- */
-
-
-/**
- * @fileoverview The beachdemo javascript.
- */
-
-
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.dump');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.loader');
-o3djs.require('o3djs.picking');
-o3djs.require('o3djs.canvas');
-o3djs.require('o3djs.fps');
-o3djs.require('o3djs.debug');
-o3djs.require('o3djs.particles');
-o3djs.require('o3djs.performance');
-o3djs.require('o3djs.io');
-
-var PROXY_HEIGHT = 5150;
-
-// client.root
-// |
-// g_mainRoot
-// |
-// +-----+--------+----------------+
-// | | |
-// g_baseRoot g_waterTransform g_skyDomeTransform
-// |
-// g_sceneRoot
-
-var g_re;
-var g_animateCamera = false;
-var g_cameraDuration = 1;
-var g_cameraPoint;
-var g_cameraPointIndex = 0;
-var g_cameraTimer = 0;
-var g_demoTimer = 0;
-var g_runDemo = true;
-var g_oldCameraClock = 0;
-var g_speedTransforms = [[], [], [], []];
-var g_sceneRoot;
-var g_baseRoot;
-var g_reflectionClipHeight = 100;
-var g_mainClipHeight = 100000000;
-var g_o3d;
-var g_hudFadeTime;
-var g_helpVisible = false;
-var g_math;
-var g_key;
-var g_paint;
-var g_sceneUrl;
-var g_quaternions;
-var g_waterMode = 0;
-var g_updateRenderTargets = true;
-var g_compileEffect;
-var g_reflectRefract = false;
-var g_environmentSampler;
-var g_materialPanelElement;
-var g_propPanelElement;
-var g_effectPanelElement;
-var g_upperPanelElement;
-var g_effectTabsElement;
-var g_effectTextAreaElement;
-var g_editableEffects = [];
-var g_editableEffectsSource = [];
-var g_currentEditEffect;
-var g_faderColorParam;
-var g_faderTransform;
-var g_renderTargetDisplayRoot;
-var g_sceneElement;
-var g_client;
-var g_scenePack;
-var g_proxyPack;
-var g_mainPack;
-var g_fadeParams = [];
-var g_mainViewInfo; // main view
-var g_hudRoot; // root transform for hud.
-var g_mainRoot;
-var g_proxyRoot;
-var g_waterLevel = 500;
-var g_reflectionViewInfo;
-var g_refractionViewInfo;
-var g_hudViewInfo;
-var g_loader;
-var g_loadInfo;
-var g_reflectionClipState;
-var g_refractionClipState;
-var g_mainRenderGraphRoot;
-var g_reflectionSurfaceSet;
-var g_refractionSurfaceSet;
-var g_skyDomeTransform;
-var g_waterTransform;
-var g_reflectionTexture;
-var g_refractionTexture;
-var g_reflectionImage;
-var g_refrectionImage;
-var g_depthSurface;
-var g_globalParams;
-var g_globalClockParam;
-var g_clipHeightParam;
-var g_lightPositionParam;
-var g_lightDirectionParam;
-var g_lightColorParam;
-var g_proxyOffsetParam;
-var g_originalLightColor;
-var g_viewPositionParam;
-var g_underwaterMaterials;
-var g_whiteTexture;
-var g_whiteSampler;
-var g_waterMaterial;
-var g_waterEffect;
-var g_waterColorAndSkyEffect;
-var g_waterStyle2Effect;
-var g_torchMaterial;
-var g_torchEmitter;
-var g_torchTexture;
-var g_mistTexture;
-var g_topMistEmitter;
-var g_bottomMistEmitter;
-var g_rippleEmitter;
-var g_skyDomeMaterial;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-var g_o3dElement;
-var g_cameraInfos = [];
-var g_cameraMoveSpeedMultiplier = 50;
-var g_keyCurrentlyDown = 0; // If any key is currently down this is true.
-var g_keyDown = []; // which keys are down by key code.
-var g_keyDownKeyCodeFunctions = {};
-var g_keyUpKeyCodeFunctions = {};
-var g_materialSwapTable = [];
-var g_showingSimpleMaterialsMode = 0;
-var g_simpleEffects = [];
-var g_originalSampler = { };
-var g_dragStartContext;
-var g_dragging = false;
-var g_imageShape;
-var g_imageMaterial;
-var g_imageEffect;
-var g_waterColor = [0.13, 0.19, 0.22, 1];
-var g_hudQuad;
-var g_fpsManager;
-var g_fpsVisible = false;
-var g_particleSystem;
-var g_particleLoader;
-var g_downloadPercent = -1;
-var g_showError = false;
-var g_sceneEffects = [];
-var g_sceneTexturesByURI;
-var g_renderTargetWidth = 256;
-var g_renderTargetHeight = 256;
-var g_perfMon;
-var g_shaders = {};
-
-var g_camera = {
- farPlane: 80000,
- nearPlane: 10,
- up: [0, 0, 1],
- fieldOfView: Math.PI / 4, // 45 degrees
- eye: [-9662, -10927, 1920],
- targetVector: [0.43, 0.90, 0.02],
- xAxis: [0.8335, -0.5522, -0.0157],
- minFieldOfView: 5 * Math.PI / 180,
- maxFieldOfView: 70 * Math.PI / 180
-};
-
-var g_cameraPoints = [
- { duration: 15,
- start: {eye: [-7952.043, -3027.629, 1782.494],
- targetVector: [0.054, 0.997, -0.059],
- fieldOfView: 45},
- end: {eye: [4579.533, -3707.403, 1782.494],
- targetVector: [0.221, 0.963, 0.156],
- fieldOfView: 45}},
- { duration: 5,
- start: {eye: [-9862.542, -11676.196, 1888.062],
- targetVector: [0.552, 0.834, -0.007],
- fieldOfView: 45},
- end: {eye: [-4809.674, -4048.170, 1822.536],
- targetVector: [0.552, 0.834, -0.007],
- fieldOfView: 45}},
- { duration: 5,
- start: {eye: [2728.344, -6393.682, 2241.729],
- targetVector: [-0.312, 0.949, 0.039],
- fieldOfView: 45},
- end: {eye: [-1683.553, 3379.889, 3616.049],
- targetVector: [-0.118, 0.796, 0.594],
- fieldOfView: 45}},
- { duration: 5,
- start: {eye: [1499.756, -2208.060, 380.914],
- targetVector: [-0.537, 0.788, 0.303],
- fieldOfView: 45},
- end: {eye: [7333.003, -6937.257, 4163.998],
- targetVector: [-0.811, 0.509, -0.290],
- fieldOfView: 45}},
- { duration: 5,
- start: {eye: [4746.377, 1086.006, 3433.715],
- targetVector: [-0.982, 0.188, -0.036],
- fieldOfView: 45},
- end: {eye: [4746.377, 1086.006, 3433.715],
- targetVector: [-0.996, 0.072, 0.044],
- fieldOfView: 6.49667876045379}},
- { duration: 5,
- start: {eye: [-4173.890, -4212.830, 398.267],
- targetVector: [-0.339, 0.900, 0.272],
- fieldOfView: 45},
- end: {eye: [-4149.606, -4391.048, 2110.549],
- targetVector: [0.007, 0.998, 0.065],
- fieldOfView: 45}},
- { duration: 5,
- start: {eye: [-4809.674, -4048.170, 1822.536],
- targetVector: [0.294, 0.956, -0.022],
- fieldOfView: 45},
- end: {eye: [-4535.282, -187.079, 2537.158],
- targetVector: [0.146, 0.971, 0.190],
- fieldOfView: 45}}];
-
-// The artists followed no rules. The assumption by the o3djs libraries
-// is that textures with non-one alpha should be drawn with alpha
-// blending on in the zOrderedDrawPass, otherwise they should be drawn
-// with alpha blending off in the performanceDrawPass but the artists gave
-// us textures that have non-one alpha even though they are meant to be
-// drawn opaque.
-//
-// The next most common way to decide whether to use opaque or
-// transparent blending is a naming convention but the arists
-// didn't do that either.
-//
-// For some cases it doesn't really matter but, (1) drawing with alpha
-// blending on is much slower than off and (2) drawing in the
-// zOrderedDrawPass has to sort which is slow and sometimes things
-// can get sorted wrong if they are too large relative to each other.
-//
-// So, here's a hard coded list to set the materials to the correct
-// drawList :-(
-function makeInfo(list, reflect, refract, main, type, effect) {
- return {
- list: list,
- reflect: reflect,
- refract: refract,
- main: main,
- type: type,
- effect: effect};
-}
-var g_materialLists = {
- // ---------------------------- list reflect refract main adj
- '_6_-_Default': makeInfo(0, true, false, true, 1,
- 'just_color'),
- 'default': makeInfo(1, false, false, true, 1, // palmTreeB
- 'diffuse_bump'),
- 'Folg_BushA_mat': makeInfo(1, true, false, true, 1,
- 'diffuse_bump'),
- 'Folg_BushB_mat': makeInfo(1, true, false, true, 1,
- 'diffuse_bump'),
- 'Folg_BushC_mat': makeInfo(1, true, false, true, 1,
- 'diffuse_bump'),
- 'Folg_coralD_mat': makeInfo(1, false, true, false, 1,
- 'diffuse'),
- 'Folg_coralG_mat': makeInfo(1, false, true, false, 1,
- 'diffuse'),
- 'Folg_coralRockA_mat': makeInfo(0, false, true, false, 2,
- 'diffuse_bump_2textures'),
- 'Folg_coralRockB_mat': makeInfo(0, false, true, false, 2,
- 'diffuse_bump_2textures'),
- 'Folg_FernA_mat': makeInfo(1, true, false, true, 1,
- 'diffuse'),
- 'Folg_hangingFerns_mat': makeInfo(1, true, false, true, 1,
- 'diffuse_bump'),
- 'Folg_largeFernA_mat': makeInfo(1, true, false, true, 1,
- 'diffuse'),
- 'Folg_LeafyPlantA_mat': makeInfo(1, true, false, true, 1,
- 'diffuse_bump'),
- 'Folg_palmTreeA': makeInfo(1, false, false, true, 1,
- 'diffuse'),
- 'Prop_brokenShip_mat': makeInfo(0, true, true, true, 0,
- 'diffuse'),
- 'Prop_pillarA_mat': makeInfo(0, false, false, true, 0,
- 'diffuse_bump_specular'),
- 'prop_tikiMaskA': makeInfo(0, false, false, true, 0,
- 'diffuse_bump_specular'),
- 'Prop_TorchA_mat': makeInfo(0, false, false, true, 0,
- 'diffuse'),
- 'Prop_wallA_mat': makeInfo(0, false, false, true, 0,
- 'diffuse_bump'),
- 'Props_Bridge_mat': makeInfo(0, true, false, true, 0,
- 'diffuse'),
- 'Rock_Dark': makeInfo(0, true, true, true, 2,
- 'diffuse_bump'),
- 'Sand_Dark': makeInfo(0, false, true, false, 0,
- 'diffuse_bump_2textures'),
- 'Standard_2': makeInfo(0, true, true, false, 0, // palmfrawns
- 'diffuse'),
- 'Standard_3': makeInfo(1, false, true, true, 0, // waterfall
- ''),
- 'Rock_Dark_Island': makeInfo(0, true, true, true, 2, // Island
- 'diffuse_bump_blend')};
-
-var g_randSeed = 0;
-var g_randRange = Math.pow(2, 32);
-
-/**
- * Dumps a vector with a name label in a format useful for javascript.
- * @param {string} name The name.
- * @param {!o3d.math.Vector3} v The vector.
- */
-function dumpVector(name, v) {
- o3djs.dump.dump(
- ' ' + name + ': [' +
- v[0].toFixed(3) + ', ' +
- v[1].toFixed(3) + ', ' +
- v[2].toFixed(3) + '],\n');
-}
-
-/**
- * Dump the camera info in a format useful for javascript.
- */
-function dumpCameraInfo() {
- o3djs.dump.dump('{');
- dumpVector('eye', g_camera.eye);
- dumpVector('targetVector', g_camera.targetVector);
- o3djs.dump.dump(' fieldOfView: ' +
- g_math.radToDeg(g_camera.fieldOfView) + '};\n');
-}
-
-// ***************************** Mouse functions *******************************
-
-/**
- * Handler for onmousedown.
- * @param {event} e A mouse event.
- */
-function onMouseDown(e) {
- if (!g_keyCurrentlyDown) {
- g_dragging = true;
- g_dragStartContext = {
- view: o3djs.math.copyMatrix(g_mainViewInfo.drawContext.view),
- projection: o3djs.math.copyMatrix(g_mainViewInfo.drawContext.projection),
- offsetX: g_client.width * 0.5 - e.x,
- offsetY: g_client.height * 0.5 - e.y
- };
- stopAnimatedCamera();
- }
-}
-
-/**
- * Handler for onmousemove.
- * @param {event} e A mouse event.
- */
-function onMouseMove(e) {
- if (g_dragging) {
- // Compute the world ray based on the view we had when we started dragging.
- var worldRay = o3djs.picking.clientPositionToWorldRayEx(
- g_o3dWidth - (e.x + g_dragStartContext.offsetX),
- g_o3dHeight - (e.y + g_dragStartContext.offsetY),
- g_dragStartContext.view,
- g_dragStartContext.projection,
- g_o3dWidth,
- g_o3dHeight);
-
- g_camera.targetVector = g_math.normalize(g_math.subVector(worldRay.near,
- g_camera.eye));
- updateCamera();
- stopAnimatedCamera();
- }
-}
-
-/**
- * Handler for onmouseup.
- * @param {event} e A mouse event.
- */
-function onMouseUp(e) {
- g_dragging = false;
-}
-
-/**
- * Hander for the scroll wheel.
- * @param {Event} e Mouse event.
- */
-function onWheel(e) {
- if (e.deltaY) {
- var target = g_camera.minFieldOfView;
- if (e.deltaY < 0) {
- target = g_camera.maxFieldOfView;
- }
-
- g_camera.fieldOfView = g_math.lerpScalar(target, g_camera.fieldOfView, 0.9);
-
- updateProjection();
- stopAnimatedCamera();
- }
-}
-
-// *************************** Keyboard functions ******************************
-
-/**
- * Tracks key down events.
- * @param {Event} e keyboard event.
- */
-function onKeyDown(e) {
- if (!g_dragging && !g_keyDown[e.keyCode]) {
- ++g_keyCurrentlyDown;
- g_keyDown[e.keyCode] = true;
-
- var keyFunction = g_keyDownKeyCodeFunctions[e.keyCode];
- if (keyFunction) {
- keyFunction(e);
- }
- }
-}
-
-/**
- * Tracks key up events.
- * @param {Event} e keyboard event.
- */
-function onKeyUp(e) {
- if (g_keyDown[e.keyCode]) {
- --g_keyCurrentlyDown;
- g_keyDown[e.keyCode] = false;
-
- var keyFunction = g_keyUpKeyCodeFunctions[e.keyCode];
- if (keyFunction) {
- keyFunction(e);
- }
- }
-}
-
-/**
- * Converts a keyCode or charCode to a keyCode.
- * @param {number|string} code The key code or char code.
- * @return {number} the key code.
- */
-function convertToKeyCode(code) {
- if (typeof(code) == 'string') {
- code = code.charCodeAt(0);
- if (code >= 'a'.charCodeAt(0)) {
- code += 65 - 'a'.charCodeAt(0);
- }
- }
- return code;
-}
-
-/**
- * Registers a key code with a key up function.
- * @param {number|string} keyCode The key code to register a function with.
- * @param {!function(!event): void} keyFunction A function that will be passed
- * the event for the key.
- */
-function registerKeyDownFunction(keyCode, keyFunction) {
- g_keyDownKeyCodeFunctions[convertToKeyCode(keyCode)] = keyFunction;
-}
-
-/**
- * Registers a key code with a key down function.
- * @param {number|string} keyCode The key code to register a function with.
- * @param {!function(!event): void} keyFunction A function that will be passed
- * the event for the key.
- */
-function registerKeyUpFunction(keyCode, keyFunction) {
- g_keyUpKeyCodeFunctions[convertToKeyCode(keyCode)] = keyFunction;
-}
-
-/**
- * Registers a key code with a both a key down and key up function.
- * @param {number|string} keyCode The key code to register a function with.
- * @param {!function(!event): void} keyUpFunction A function that will be passed
- * the event for the key being released.
- * @param {!function(!event): void} keyDownFunction A function that will be
- * passed the event for the key being down..
- */
-function registerKeyUpDownFunction(keyCode, keyUpFunction, keyDownFunction) {
- registerKeyUpFunction(keyCode, keyUpFunction);
- registerKeyUpFunction(keyCode, keyDownFunction);
-}
-
-/**
- * Registers key handlers.
- */
-function registerKeyHandlers() {
- registerKeyDownFunction('0', keySetCamera);
- registerKeyDownFunction('1', keySetCamera);
- registerKeyDownFunction('2', keySetCamera);
- registerKeyDownFunction('3', keySetCamera);
- registerKeyDownFunction('4', keySetCamera);
- registerKeyDownFunction('5', keySetCamera);
- registerKeyDownFunction('6', keySetCamera);
- registerKeyDownFunction('7', keySetCamera);
- registerKeyDownFunction('8', keySetCamera);
- registerKeyDownFunction('9', keySetCamera);
-
- registerKeyDownFunction('h', toggleHelp);
- registerKeyDownFunction('p', togglePropsPanel);
- registerKeyDownFunction('m', toggleMaterialPanel);
- registerKeyDownFunction('e', toggleEffectPanel);
- registerKeyDownFunction('r', toggleRenderTargets);
- registerKeyDownFunction('f', toggleFps);
- registerKeyDownFunction('c', toggleSimpleMaterials);
- registerKeyDownFunction('o', toggleWaterEffect);
- registerKeyDownFunction('q', toggleDemoCamera);
-
- // Comment the line below in to enable dumping camera info.
- // This can be used to generate camera points for the animated
- // camera but is only compatible with Firefox.
- //registerKeyDownFunction('z', dumpCameraInfo);
-}
-
-// **************************** Camera Functions *******************************
-
-/**
- * Updates the camera (the view matrix of the drawContext) with the current
- * camera settings.
- */
-function updateCamera() {
- var target = g_math.addVector(g_camera.eye, g_camera.targetVector);
- var view = g_math.matrix4.lookAt(g_camera.eye,
- target,
- g_camera.up);
- g_viewPositionParam.value = g_camera.eye;
- g_mainViewInfo.drawContext.view = view;
- g_reflectionViewInfo.drawContext.view = view;
- g_refractionViewInfo.drawContext.view = view;
- var cameraMatrix = g_math.inverse4(view);
- g_camera.xAxis = cameraMatrix[0].splice(0, 3);
- g_updateRenderTargets = true;
-}
-
-/**
- * Updates the projection matrix of the drawContext with the current camera
- * settings.
- */
-function updateProjection() {
- // Create a perspective projection matrix.
- g_mainViewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_camera.fieldOfView, g_o3dWidth / g_o3dHeight, g_camera.nearPlane,
- g_camera.farPlane);
-
- g_reflectionViewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_camera.fieldOfView, g_o3dWidth / g_o3dHeight,
- g_camera.nearPlane, g_camera.farPlane);
-
- g_refractionViewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_camera.fieldOfView, g_o3dWidth / g_o3dHeight,
- g_camera.nearPlane, g_camera.farPlane);
-
- g_hudViewInfo.drawContext.projection = g_math.matrix4.orthographic(
- 0 + 0.5,
- g_o3dWidth + 0.5,
- g_o3dHeight + 0.5,
- 0 + 0.5,
- 0.001,
- 1000);
- g_updateRenderTargets = true;
-}
-
-/**
- * Update the fader plane for the current client area size.
- */
-function updateFaderPlane() {
- // Scale fader plane to cover screen.
- // If we made a custom shader for this this wouldn't be needed.
- g_faderTransform.identity();
- g_faderTransform.translate(0, 0, -10);
- g_faderTransform.scale(g_client.width, g_client.height, 1);
-}
-
-/**
- * Sets the camera to a preset.
- * @param {number} cameraIndex Index of camera preset.
- */
-function setCamera(cameraIndex) {
- var cameraInfo = g_cameraInfos[cameraIndex];
- // pull out camera info from view matrix.
- var cameraMatrix = g_math.inverse4(cameraInfo.view);
- g_camera.eye = cameraMatrix[3].splice(0, 3);
- g_camera.targetVector = g_math.negativeVector(cameraMatrix[2].splice(0, 3));
- //g_camera.fieldOfView = cameraInfo.fieldOfViewRadians;
- g_camera.fieldOfView = o3djs.math.degToRad(45);
-
- updateCamera();
- updateProjection();
- stopAnimatedCamera();
-}
-
-/**
- * Moves the camera in its local X axis.
- * @param {number} direction Position or negative amount to move.
- */
-function moveCameraLeftRight(direction) {
- direction *= g_cameraMoveSpeedMultiplier;
- g_camera.eye = g_math.addVector(
- g_camera.eye,
- g_math.mulVectorScalar(g_camera.xAxis, direction));
- updateCamera();
- stopAnimatedCamera();
-}
-
-/**
- * Moves the camera in its local Z axis.
- * @param {number} direction Position or negative amount to move.
- */
-function moveCameraForwardBack(direction) {
- direction *= g_cameraMoveSpeedMultiplier;
- g_camera.eye = g_math.addVector(
- g_camera.eye,
- g_math.mulVectorScalar(g_camera.targetVector, direction));
- updateCamera();
- stopAnimatedCamera();
-}
-
-// ************************ Effect Editor Functions ****************************
-
-/**
- * Starts editing an effect.
- * @param {number} effectId The clientId of the effect.
- */
-function editEffect(effectId) {
- if (g_currentEditEffect) {
- // Save the current edit.
- // TODO: would it be better to have a textarea per effect and
- // hide / unhide them?
- g_editableEffectsSource[g_currentEditEffect.clientId] =
- g_effectTextAreaElement.value;
- }
-
- var effect = g_client.getObjectById(effectId);
- g_effectTextAreaElement.value = g_editableEffectsSource[effectId];
-
- g_currentEditEffect = effect;
-}
-
-/**
- * Edits an effect from the value on an option element
- */
-function editEffectFromElement() {
- var element = o3djs.util.getElementById('effectselect');
- editEffect(parseInt(element.value));
-}
-
-/**
- * Compiles the current effect.
- */
-function compileEffect() {
- if (g_currentEditEffect) {
- var source = g_effectTextAreaElement.value;
-
- // Turn off the default error callback so we can get the error ourselves.
- g_client.clearErrorCallback();
- g_client.clearLastError();
- g_compileEffect.loadFromFXString(source);
- var error = g_client.lastError;
- o3djs.base.setErrorHandler(g_client);
- if (error) {
- alert(error);
- } else {
- g_currentEditEffect.loadFromFXString(source);
- // TODO: call createUniformParameters for all materials
- // using this effect then call setupMaterialEditor so it will
- // display new parameters.
-
- // Tell the render targets to update.
- g_updateRenderTargets = true;
- }
- }
-}
-
-/**
- * Setup effect editor.
- */
-function setupEffectEditor() {
- // create an effect for testing.
- g_compileEffect = g_mainPack.createObject('Effect');
-
- var compileButton = o3djs.util.getElementById('compileButton');
- compileButton.onclick = compileEffect;
-
- // create pseudo tabs.
- // TODO: Make it look prettier.
- var html = '<select id="effectselect">';
- for (var ii = 0; ii < g_editableEffects.length; ++ii) {
- var effect = g_editableEffects[ii];
- g_editableEffectsSource[effect.clientId] = effect.source;
- html += '' +
- '<option value="' + effect.clientId + '">' + effect.name + '</option>';
- }
- g_effectTabsElement.innerHTML = html + '</select>';
- var element = o3djs.util.getElementById('effectselect');
- element.onchange = editEffectFromElement;
- element.onblur = editEffectFromElement;
-
- // Setup the first effect.
- editEffect(g_editableEffects[0].clientId);
-}
-
-// ************************* Prop Editor Functions *****************************
-
-/**
- * Setups the prop editor.
- */
-function setupPropEditor() {
- var propPrefixes = {watersurface: true};
- var transforms = g_scenePack.getObjectsByClassName('o3d.Transform');
- for (var tt = 0; tt < transforms.length; ++tt) {
- var transform = transforms[tt];
- if (transform.shapes.length > 0) {
- var name = transform.name;
- //if (!isNaN(name.substring(name.length -1))) {
- // var prefix = name.replace(/\d*$/, '');
- // if (prefix.length > 0) {
- // propPrefixes[prefix] = true;
- // }
- //}
- propPrefixes[name] = true;
- }
- }
-
- var html = '<table>';
- var count = 0;
- for (var prefix in propPrefixes) {
- html += '' +
- '<tr class="' + ((count % 2 == 0) ? 'even' : 'odd') + '"><td>' +
- '<input id="prop_' + prefix + '" ' +
- 'type="checkbox" CHECKED />' +
- prefix +
- '</td></tr>';
- ++count;
- }
- g_propPanelElement.innerHTML = html + '</table>';
- for (var prefix in propPrefixes) {
- var input = o3djs.util.getElementById('prop_' + prefix);
- input.onclick = o3djs.util.curry(toggleProp, prefix);
- }
-}
-
-/**
- * Toggles props.
- * Goes through all transforms in the client and if their name starts with
- * prefix sets their visibility to true or false.
- * @param {string} prefix Prefix of props to toggle.
- */
-function toggleProp(prefix) {
- var element = o3djs.util.getElementById('prop_' + prefix);
- var visible = element.checked;
- // We should probably cache all the transforms since this is an expensive
- // operation.
- var transforms = g_client.getObjectsByClassName('o3d.Transform');
- for (var tt = 0; tt < transforms.length; ++tt) {
- var transform = transforms[tt];
- if (transform.name.substring(0, prefix.length) === prefix) {
- transform.visible = visible;
- }
- }
- // Tell the render targets to update.
- g_updateRenderTargets = true;
-}
-
-// *********************** Material Editor Functions ***************************
-
-/**
- * Escapes a string, changing < to &lt;
- * @param {string} str to escape.
- * @return {string} escaped string.
- */
-function escapeHTML(str) {
- return str.replace(/</g, '&lt;');
-}
-
-/**
- * Gets a param value as a string
- * @param {!o3d.Param} param Param to get value from.
- * @return {string} value of param as a string.
- */
-function getParamAsString(param) {
- if (param.isAClassName('o3d.ParamFloat')) {
- return param.value.toFixed(5);
- } else if (param.isAClassName('o3d.ParamFloat4')) {
- var value = param.value;
- for (var ii = 0; ii < value.length; ++ii) {
- value[ii] = value[ii].toFixed(2);
- }
- return value.toString();
- } else {
- return '--na--';
- }
-}
-
-/**
- * Reads the current value of the input and sets the matching param to that
- * value.
- * @param {number} paramId Id of param and input.
- */
-function updateParam(paramId) {
- var param = g_client.getObjectById(paramId);
- var element = o3djs.util.getElementById('param_' + paramId);
- var value = element.value;
- var error = false;
- var v;
- if (param.isAClassName('o3d.ParamFloat')) {
- if (isNaN(value)) {
- error = true;
- }
- v = parseFloat(value);
- } else if (param.isAClassName('o3d.ParamFloat4')) {
- var values = value.split(/ *, *| +/);
- if (values.length != 4) {
- error = true;
- } else {
- v = [];
- for (var ii = 0; ii < values.length; ++ii) {
- if (isNaN(values[ii])) {
- error = true;
- break;
- }
- v[ii] = parseFloat(values[ii]);
- }
- }
- }
-
- if (!error) {
- param.value = v;
- // Tell the render targets to update.
- g_updateRenderTargets = true;
- }
-
- element.style.backgroundColor = error ? '#fcc' : '';
-}
-
-/**
- * Creates the html to edit the given param object.
- * @param {!o3d.ParamObject} paramObject The param object to create html for.
- * @param {string} rowClass name of class for row.
- * @return {string} the generated HTML.
- */
-function createHTMLForParamObject(paramObject, rowClass) {
- var html = '' +
- '<tr class="' + rowClass + '">' +
- '<td class="name" colspan="2">' + escapeHTML(paramObject.name) + '</td>' +
- '</tr>';
- var params = paramObject.params;
- for (var pp = 0; pp < params.length; ++pp) {
- var param = params[pp];
- // Skip builtins and ones with an input connection.
- if (param.name.substring(0, 4) !== 'o3d.' &&
- param.inputConnection == null &&
- (param.isAClassName('o3d.ParamFloat') ||
- param.isAClassName('o3d.ParamFloat4'))) {
- html += '' +
- '<tr>' +
- '<td class="field">' +
- '<label>' + escapeHTML(param.name) + '</label>' +
- '</td>' +
- '<td class="value">' +
- '<input type="text" id="param_' + param.clientId + '" ' +
- 'value="' + getParamAsString(param) + '"></input>' +
- '</td>' +
- '</tr>';
- }
- }
- return html;
-}
-
-/**
- * Sets the onblur and onchange handlers in the html for a given param object.
- * @param {!o3d.ParamObject} paramObject The param object to create html for.
- */
-function setHTMLHandlersForParamObject(paramObject) {
- var params = paramObject.params;
- for (var pp = 0; pp < params.length; ++pp) {
- var param = params[pp];
- // Skip builtins and ones with an input connection.
- if (param.name.substring(0, 4) !== 'o3d.' &&
- param.inputConnection == null &&
- (param.isAClassName('o3d.ParamFloat') ||
- param.isAClassName('o3d.ParamFloat4'))) {
- var input = o3djs.util.getElementById('param_' + param.clientId);
- input.onblur = o3djs.util.curry(updateParam, param.clientId);
- input.onchange = o3djs.util.curry(updateParam, param.clientId);
- }
- }
-}
-
-/**
- * Sets up html with event handers to edit the material parameters.
- */
-function setupMaterialEditor() {
- var html = '<table>';
- var materials = g_scenePack.getObjectsByClassName('o3d.Material');
- var count = 0;
- materials.unshift(g_globalParams);
- materials.unshift(g_waterMaterial);
- materials.unshift(g_underwaterMaterials[0]);
- materials.unshift(g_underwaterMaterials[1]);
- for (var mm = 0; mm < materials.length; ++mm) {
- var material = materials[mm];
- html += createHTMLForParamObject(material, count % 2 == 0 ? 'even' : 'odd');
- ++count;
- }
- g_materialPanelElement.innerHTML = html + '</table>';
-
- for (var mm = 0; mm < materials.length; ++mm) {
- var material = materials[mm];
- setHTMLHandlersForParamObject(material)
- }
-}
-
-// ************************* Specific Key Handlers *****************************
-
-function setupWaterHeavyUpdateOnlyOnViewChange() {
- g_waterMaterial.effect = g_waterEffect;
-}
-
-function setupWaterHeavyUpdateAlways() {
- g_waterMaterial.effect = g_waterEffect;
-}
-
-function setupWaterJustSkyAndColor() {
- g_waterMaterial.effect = g_waterColorAndSkyEffect;
-}
-
-function setupWaterStyle2() {
- g_waterMaterial.effect = g_waterStyle2Effect;
-}
-
-/**
- * Toggles the water effect.
- * @param {Event} e Event for key that was pressed.
- */
-function toggleWaterEffect(e) {
- ++g_waterMode;
- if (g_waterMode == 4) {
- g_waterMode = 0;
- }
-
- switch (g_waterMode) {
- case 0:
- setupWaterHeavyUpdateOnlyOnViewChange();
- break;
- case 1:
- setupWaterHeavyUpdateAlways();
- break;
- case 2:
- setupWaterJustSkyAndColor();
- break;
- case 3:
- setupWaterStyle2();
- break;
- }
-}
-
-/**
- * Toggles the animted camera.
- * @param {Event} e Event for key that was pressed.
- */
-function toggleDemoCamera(e) {
- g_runDemo = !g_runDemo;
- if (g_runDemo) {
- g_animateCamera = true;
- } else {
- stopAnimatedCamera();
- }
-}
-
-/**
- * Restores and original sampler on params of a certain name.
- * @param {!o3d.ParamObject} paramObject Object to restore samplers on.
- * @param {string} samplerName Name of sampler parameter to restore.
- */
-function restoreOriginalSampler(paramObject, samplerName) {
- var param = paramObject.getParam(samplerName);
- if (param) {
- param.value = g_originalSampler[param.clientId];
- }
-}
-
-/**
- * Replaces samplers on params of a certain name with a white sampler.
- * @param {!o3d.ParamObject} paramObject Object to replace samplers on.
- * @param {string} samplerName Name of sampler parameter to replace samplers on.
- */
-function replaceSamplerWithWhiteSampler(paramObject, samplerName) {
- var param = paramObject.getParam(samplerName);
- if (param) {
- g_originalSampler[param.clientId] = param.value;
- param.value = g_whiteSampler;
- }
-}
-
-/**
- * Toggles the materials to simple effects.
- * @param {Event} e Event for key that was pressed.
- */
-function toggleSimpleMaterials(e) {
- g_updateRenderTargets = true;
-
- var materials = g_scenePack.getObjectsByClassName('o3d.Material');
- materials.unshift(g_waterMaterial);
- materials.unshift(g_underwaterMaterials[0]);
- materials.unshift(g_underwaterMaterials[1]);
-
- ++g_showingSimpleMaterialsMode;
- g_showingSimpleMaterialsMode = g_showingSimpleMaterialsMode % 4;
-
- switch (g_showingSimpleMaterialsMode) {
- case 1: {
- g_originalLightColor = g_lightColorParam.value;
- g_lightColorParam.value = [1, 1, 1, 1];
- var drawElements = g_scenePack.getObjectsByClassName('o3d.DrawElement');
- for (var ii = 0; ii < drawElements.length; ++ii) {
- replaceSamplerWithWhiteSampler(drawElements[ii], 'diffuseSampler');
- }
- break;
- }
- case 2: {
- g_lightColorParam.value = g_originalLightColor;
- var drawElements = g_scenePack.getObjectsByClassName('o3d.DrawElement');
- for (var ii = 0; ii < drawElements.length; ++ii) {
- restoreOriginalSampler(drawElements[ii], 'diffuseSampler');
- }
- break;
- }
- }
-
- for (var mm = 0; mm < materials.length; ++mm) {
- var material = materials[mm];
- switch (g_showingSimpleMaterialsMode) {
- case 0: {
- material.effect = g_materialSwapTable[material.clientId];
- break;
- }
- case 1: {
- replaceSamplerWithWhiteSampler(material, 'diffuseSampler');
- replaceSamplerWithWhiteSampler(material, 'diffuse2Sampler');
- break;
- }
- case 2: {
- restoreOriginalSampler(material, 'diffuseSampler');
- restoreOriginalSampler(material, 'diffuse2Sampler');
-
- var effect = material.effect;
- g_materialSwapTable[material.clientId] = effect;
- if (!g_simpleEffects[effect.clientId]) {
- // eat some random number to get pleasing colors.
- g_math.pseudoRandom();
- g_math.pseudoRandom();
- var newEffect = g_mainPack.createObject('Effect');
- newEffect.loadFromFXString(g_shaders.simpleshader);
- newEffect.createUniformParameters(newEffect);
- newEffect.getParam('simpleColor').value = [
- g_math.pseudoRandom(),
- g_math.pseudoRandom(),
- g_math.pseudoRandom(),
- 1];
- g_simpleEffects[effect.clientId] = newEffect;
- }
- material.effect = g_simpleEffects[effect.clientId];
- break;
- }
- case 3: {
- material.effect = g_imageEffect;
- break;
- }
- }
- }
-}
-
-/**
- * Toggles the render target display.
- * @param {Event} e Event for key that was pressed.
- */
-function toggleRenderTargets(e) {
- g_renderTargetDisplayRoot.visible = !g_renderTargetDisplayRoot.visible;
-}
-
-/**
- * Toggles the fps display.
- * @param {Event} e Event for key that was pressed.
- */
-function toggleFps(e) {
- g_fpsVisible = !g_fpsVisible;
- g_fpsManager.setVisible(g_fpsVisible);
-}
-
-function togglePropsPanel(e) {
- if (g_propPanelElement.style.display === '') {
- g_propPanelElement.style.display = 'none';
- g_sceneElement.style.width = '100%';
- } else {
- g_materialPanelElement.style.display = 'none';
- g_propPanelElement.style.display = '';
- g_sceneElement.style.width = '80%';
- }
-}
-
-/**
- * Toggles the material panel.
- * @param {Event} e Event for key that was pressed.
- */
-function toggleMaterialPanel(e) {
- if (g_materialPanelElement.style.display === '') {
- g_materialPanelElement.style.display = 'none';
- g_sceneElement.style.width = '100%';
- } else {
- g_propPanelElement.style.display = 'none';
- g_materialPanelElement.style.display = '';
- g_sceneElement.style.width = '80%';
- }
-}
-
-/**
- * Toggles the effect panel.
- * @param {Event} e Event for key that was pressed.
- */
-function toggleEffectPanel(e) {
- if (g_effectPanelElement.style.display === '') {
- g_effectPanelElement.style.display = 'none';
- g_upperPanelElement.style.height = '100%';
- } else {
- g_effectPanelElement.style.display = '';
- g_upperPanelElement.style.height = '70%';
- }
-}
-
-/**
- * Sets the camera to a camera preset from a key press.
- * @param {Event} e Event for key that was pressed. Expects 0-9.
- */
-function keySetCamera(e) {
- var index = e.keyCode - 49;
- if (index < 0) {
- index = 9;
- }
- var cameraInfo = g_cameraInfos[index];
- if (cameraInfo) {
- setCamera(index);
- }
-}
-
-// ***************************** Scene Functions *******************************
-
-/**
- * Sets the position of the sun, updating shader parameters.
- * @param {!o3djs.math.Vector3} position The position of the sun.
- */
-function setSunPosition(position) {
- g_lightPositionParam.value = position;
- g_lightDirectionParam.value = g_math.negativeVector(
- g_math.normalize(position));
- g_lightDirectionParam.value = g_math.normalize(position);
-}
-
-// ********************************** Misc *************************************
-
-/**
- * Sets a param if it exists.
- * @param {!o3d.ParamObject} paramObject The object that has the param.
- * @param {string} paramName name of param.
- * @param {*} value the value for the param.
- */
-function setParam(paramObject, paramName, value) {
- var param = paramObject.getParam(paramName);
- if (param) {
- param.value = value;
- }
-}
-
-/**
- * Binds a param if it exists.
- * @param {!o3d.ParamObject} paramObject The object that has the param.
- * @param {string} paramName name of param.
- * @param {!o3d.Param} sourceParam The param to bind to.
- */
-function bindParam(paramObject, paramName, sourceParam) {
- var param = paramObject.getParam(paramName);
- if (param) {
- param.bind(sourceParam);
- }
-}
-
-/**
- * Prints out a transform tree.
- * @param {!o3d.Transform} transform transform to print.
- * @param {string} prefix Prefix to print.
- */
-function dumpTransforms(transform, prefix) {
- var materialName = '';
- var shapes = transform.shapes;
- if (shapes.length > 0) {
- materialName = ' (' + shapes[0].elements[0].material.name + ')';
- }
- o3djs.dump.dump(prefix + transform.name + materialName + '\n');
- var children = transform.children;
- for (var cc = 0; cc < children.length; ++cc) {
- dumpTransforms(children[cc], prefix + ' ');
- }
-}
-
-/**
- * Adds transforms at each level of the scene to group things by where they
- * need to be rendered, refraction, main, both.
- * @param {!o3d.Transform} transform Transform to scan.
- */
-function getSpeedTransforms(transform) {
- // 0 : neither, 1 : main, 2 : reflect, 3 : both
- var speedTransforms = [];
- var children = transform.children;
- for (var cc = 0; cc < children.length; ++cc) {
- var child = children[cc];
- var check = child;
-
- // If a child has a single child of the same but with the suffix
- // '_PIVOT' use that as the check node.
- var checkChildren = child.children;
- if (checkChildren.length == 1 &&
- checkChildren[0].name == child.name + '_PIVOT') {
- check = checkChildren[0];
- }
- // If check has a shape that has a primitive that uses one of the
- // materials on the list then attach it to a speed transform.
- var grouped = false;
- var shapes = check.shapes;
- if (shapes.length > 0) {
- // gets assume 1 shape, 1 element
- var material = shapes[0].elements[0].material;
- var materialInfo = g_materialLists[material.name];
- if (materialInfo) {
- grouped = true;
- var index = (materialInfo.main ? 1 : 0) +
- (materialInfo.reflect ? 2 : 0);
- var speedTransform = speedTransforms[index];
- if (!speedTransform) {
- speedTransform = g_mainPack.createObject('Transform');
- speedTransform.name = 'speed_' + index;
- speedTransform.parent = transform;
- speedTransforms[index] = speedTransform;
- }
- child.parent = speedTransform;
- }
- }
-
- if (!grouped) {
- getSpeedTransforms(child);
- }
- }
-
- // Now add speed transforms to global list.
- for (var ii = 0; ii < 4; ++ii) {
- if (speedTransforms[ii]) {
- g_speedTransforms[ii].push(speedTransforms[ii]);
- }
- }
-}
-
-/**
- * Gets a texture from g_scenePack.
- * @param {string} textureName Name of texture.
- * @return {!o3d.Texture} The requested texture.
- */
-function getTexture(textureName) {
- // I'm searching by URI because the old conditioner sadly renamed all the
- // textures making it next to impossible to find things :-(
- if (!g_sceneTexturesByURI) {
- g_sceneTexturesByURI = { };
- var textures = g_scenePack.getObjectsByClassName('o3d.Texture');
- for (var tt = 0; tt < textures.length; ++tt) {
- var texture = textures[tt];
- var uri = texture.getParam('uri').value;
- g_sceneTexturesByURI[uri] = texture;
- }
- }
-
- return g_sceneTexturesByURI['images/' + textureName];
-}
-
-/**
- * Adds a texture to a material.
- * @param {!o3d.Material} material Material to add texture to.
- * @param {string} samplerName Name of sampler parameter to attach texture to.
- * @param {string} textureName Name of texture.
- */
-function addTexture(material, samplerName, textureName) {
- var param = material.createParam(samplerName, 'ParamSampler');
- var sampler = g_scenePack.createObject('Sampler');
- param.value = sampler;
- sampler.texture = getTexture(textureName);
-}
-
-/**
- * Sets up the materials in the scene.
- */
-function setupSceneMaterials() {
- var drawLists = [g_mainViewInfo.performanceDrawList,
- g_mainViewInfo.zOrderedDrawList];
-
- var adjust = [
- {shininess: 50, specular: [0.5, 0.5, 0.5, 1]},
- {shininess: 100, specular: [0.3, 0.5, 0.3, 1]},
- {shininess: 80, specular: [0.3, 0.3, 0.3, 1]}];
-
- // Setup the materials. Because Collada can't really handle
- // the materials needed we pretty much have to do this manaually. It would
- // have been good to make a rule for it but I have no time.
- for (var name in g_materialLists) {
- var info = g_materialLists[name];
- var materials = g_scenePack.getObjects(name, 'o3d.Material');
- for (var mm = 0; mm < materials.length; ++mm) {
- var material = materials[mm];
- if (info.effect) {
- var effect = g_sceneEffects[info.effect];
- if (!effect) {
- effect = g_scenePack.createObject('Effect');
- effect.name = info.effect;
- var fxString = g_shaders[info.effect];
- effect.loadFromFXString(fxString);
- g_sceneEffects[info.effect] = effect;
- g_editableEffects.push(effect);
- }
- material.effect = effect;
- material.createParam('lightWorldPos', 'ParamFloat3');
- material.createParam('lightColor', 'ParamFloat4');
- material.createParam('clipHeight', 'ParamFloat');
-
- // special handling for island and seafloor materials.
- if (info.effect == 'diffuse_bump_blend') {
- addTexture(material, 'diffuse2Sampler', 'image1.dds');
- }
- }
- material.drawList = drawLists[info.list];
-
- // Manually connect all the materials' lightWorldPos params or a global
- // light param.
- bindParam(material, 'lightWorldPos', g_lightPositionParam);
- bindParam(material, 'lightColor', g_lightColorParam);
- bindParam(material, 'clipHeight', g_clipHeightParam);
- setParam(material, 'ambient', [0.2, 0.2, 0.2, 1]);
-
- var type = info.type;
- setParam(material, 'shininess', adjust[type].shininess);
- setParam(material, 'specular', adjust[type].specular);
- }
- }
-}
-
-/**
- * Loads the proxy.
- */
-function loadProxy() {
- function callback(pack, parent, exception) {
- g_loadInfo = null;
- if (exception) {
- showError(exception);
- } else {
- loadMainScene();
-
- o3djs.pack.preparePack(pack, g_mainViewInfo);
-
- var material = pack.getObjectsByClassName('o3d.Material')[0];
- var effect = g_mainPack.createObject('Effect');
- effect.loadFromFXString(g_shaders.proxy);
- effect.createUniformParameters(material);
- setParam(material, 'lightWorldPos', [0, -100000, 200000]);
- setParam(material, 'ambient', [0, 0, 0, 0]);
- setParam(material, 'diffuse', [0.7, 0.7, 0.7, 0.5]);
- setParam(material, 'specular', [0, 0, 0, 0]);
- bindParam(material, 'offset', g_proxyOffsetParam);
- material.effect = effect;
- material.drawList = g_mainViewInfo.zOrderedDrawList;
- var state = pack.createObject('State');
- material.state = state;
- state.getStateParam('AlphaReference').value = 0.0;
- state.getStateParam('CullMode').value = g_o3d.State.CULL_CCW;
- var material2 = pack.createObject('Material');
- effect.createUniformParameters(material2);
- material2.copyParams(material);
- bindParam(material2, 'offset', g_proxyOffsetParam);
- material2.effect = effect;
- material2.drawList = g_mainViewInfo.zOrderedDrawList;
-
- state = pack.createObject('State');
- material2.state = state;
- state.getStateParam('AlphaReference').value = 0.0;
- state.getStateParam('CullMode').value = g_o3d.State.CULL_CW;
-
- parent.createDrawElements(pack, material2);
- }
- }
-
- g_proxyPack = g_client.createPack();
- g_proxyRoot = g_proxyPack.createObject('Transform');
- g_proxyRoot.parent = g_baseRoot;
-
- try {
- var url = o3djs.util.getAbsoluteURI('assets/beach-low-poly.o3dtgz');
- g_loadInfo = o3djs.scene.loadScene(g_client, g_proxyPack, g_proxyRoot,
- url, callback, {opt_async: false});
- } catch (e) {
- showError(e);
- }
-}
-
-/**
- * Loads the main scene.
- */
-function loadMainScene() {
- function callback(pack, parent, exception) {
- g_loadInfo = null;
- if (exception) {
- showError(exception);
- } else {
- g_proxyRoot.visible = false;
-
- setupWaterfall();
-
- // Generate draw elements and setup material draw lists.
- parent.createDrawElements(pack, null);
-
- setupSceneMaterials();
-
- // Turn off culling since we can see the entire world checking culling
- // is a waste of CPU time.
- var elements = g_scenePack.getObjectsByClassName('o3d.Element');
- for (var ee = 0; ee < elements.length; ++ee) {
- elements[ee].cull = false;
- o3djs.element.setBoundingBoxAndZSortPoint(elements[ee]);
- }
-
- // Add missing streams to terrain.
- var terrainNames = [
- 'terrainSpireA_002',
- 'terrainSpireA_003',
- 'terrainLargeRock',
- 'terrainSpireA_001'];
- var semantics = [
- g_o3d.Stream.TEXCOORD,
- g_o3d.Stream.BINORMAL,
- g_o3d.Stream.TANGENT];
- for (var tt = 0; tt < terrainNames.length; ++tt) {
- var streamBank = g_scenePack.getObjects(terrainNames[tt],
- 'o3d.StreamBank')[0];
- for (var ii = 0; ii < semantics.length; ++ii) {
- var stream = streamBank.getVertexStream(semantics[ii], 0);
- streamBank.setVertexStream(semantics[ii], 1, stream.field, 0)
- }
- }
-
- g_cameraInfos = o3djs.camera.getCameraInfos(parent,
- g_o3dWidth,
- g_o3dHeight);
- setCamera(1);
- setupUnderwater();
-
- getSpeedTransforms(g_sceneRoot);
-
- //o3djs.dump.dump("--------\n");
- //dumpTransforms(g_sceneRoot, '');
-
- setupMaterialEditor();
- setupEffectEditor();
- setupPropEditor();
-
- registerKeyHandlers();
-
- if (false) {
- o3djs.dump.dump('---dump g_scenePack shapes---\n');
- var shapes = g_scenePack.getObjectsByClassName('o3d.Shape');
- for (var t = 0; t < shapes.length; t++) {
- var shape = shapes[t];
- o3djs.dump.dump('shape ' + t + ': ' + shape.name + '\n');
- //o3djs.dump.dumpShape(shape);
- }
- }
-
- if (false) {
- o3djs.dump.dump('---dump g_scenePack materials---\n');
- var materials = g_scenePack.getObjectsByClassName('o3d.Material');
- for (var t = 0; t < materials.length; t++) {
- var material = materials[t];
- o3djs.dump.dump (
- ' ' + t + ' : ' + material.className +
- ' : "' + material.name + '"\n');
- var params = material.params;
- for (var p = 0; p < params.length; ++p) {
- var param = params[p];
- if (param.className == 'o3d.ParamSampler') {
- o3djs.dump.dump(' ' + p + ': ' +
- param.value.texture.name + '\n');
- }
- }
- //o3djs.dump.dumpParams(materials[t], ' ');
- }
- }
-
- if (false) {
- o3djs.dump.dump('---dump g_scenePack textures---\n');
- var textures = g_scenePack.getObjectsByClassName('o3d.Texture');
- for (var t = 0; t < textures.length; t++) {
- o3djs.dump.dump(t + ': ');
- o3djs.dump.dumpTexture(textures[t]);
- }
-
- o3djs.dump.dump('---dump g_scenePack effects---\n');
- var effects = g_scenePack.getObjectsByClassName('o3d.Effect');
- for (var t = 0; t < effects.length; t++) {
- o3djs.dump.dump (' ' + t + ' : ' + effects[t].className +
- ' : "' + effects[t].name + '"\n');
- o3djs.dump.dumpParams(effects[t], ' ');
- }
- }
- }
- g_perfMon = o3djs.performance.createPerformanceMonitor(
- 25, 35, increaseRenderTargetResolution, decreaseRenderTargetResolution);
- }
-
- try {
- // We need to make a subloader because we can't make the particles
- // until both the scene and the particle textures are loaded.
- g_loadInfo = g_loader.loadInfo;
- g_particleLoader = g_loader.createLoader(setupParticles);
- g_particleLoader.loadTexture(
- g_mainPack,
- o3djs.util.getAbsoluteURI('assets/pe_fire.jpg'),
- function(texture, success) {
- g_torchTexture = texture;
- });
- g_particleLoader.loadTexture(
- g_mainPack,
- o3djs.util.getAbsoluteURI('assets/pe_mist.png'),
- function(texture, success) {
- g_mistTexture = texture;
- });
-
- var url = o3djs.util.getAbsoluteURI('assets/beachdemo.o3dtgz');
- g_particleLoader.loadScene(
- g_client, g_scenePack, g_sceneRoot, url, callback, {opt_async: false});
- g_particleLoader.finish()
- g_loader.finish();
- } catch (e) {
- showError(e);
- }
-}
-
-/**
- * Records the client's size if it's changed.
- */
-function setClientSize() {
- var newWidth = parseInt(g_client.width);
- var newHeight = parseInt(g_client.height);
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- updateProjection();
- g_fpsManager.resize(g_o3dWidth, g_o3dHeight);
- g_fpsManager.setPosition(g_o3dWidth - 80, 10);
- updateFaderPlane();
- }
-}
-
-/**
- * Moves the camera based on key state.
- */
-function handleCameraKeys() {
- var moveX = 0;
- var moveY = 0;
-
- if (g_keyDown[37] || g_keyDown[65]) {
- moveX = -1;
- }
- if (g_keyDown[39] || g_keyDown[68]) {
- moveX = 1;
- }
- if (g_keyDown[38] || g_keyDown[87]) {
- moveY = 1;
- }
- if (g_keyDown[40] || g_keyDown[83]) {
- moveY = -1;
- }
-
- if (moveX) {
- moveCameraLeftRight(moveX);
- stopAnimatedCamera();
- }
-
- if (moveY) {
- moveCameraForwardBack(moveY);
- stopAnimatedCamera();
- }
-}
-
-/**
- * Sets the speed transforms visible or invisible to turn on/off whole groups of
- * shapes not needed for certain rendering.
- * @param {boolean} main Turn on stuff marked for main.
- * @param {boolean} reflect Turn on stuff marked for reflect.
- * @param {boolean} force Force visible to true.
- */
-function setSpeedTransforms(main, reflect, force) {
- var mask = (main ? 1 : 0) + (reflect ? 2 : 0);
- for (var ii = 0; ii < 4; ++ii) {
- var visible = ((ii & mask) != 0) || force;
- var speedTransforms = g_speedTransforms[ii];
- for (var jj = 0; jj < speedTransforms.length; ++jj) {
- speedTransforms[jj].visible = visible;
- }
- }
-}
-
-/**
- * Eases in a number.
- * @param {number} value Value to ease in. Must be 0 to 1.
- * @return {number} Ease in version of value.
- */
-function easeIn(value) {
- return 1 - Math.cos(value * Math.PI * 0.5);
-}
-
-/**
- * Eases out a number.
- * @param {number} value Value to ease out. Must be 0 to 1.
- * @return {number} Ease out version of value.
- */
-function easeOut(value) {
- return Math.sin(value * Math.PI * 0.5);
-}
-
-/**
- * Ease in and out a number.
- * @param {number} value Value to ease in out. Must be 0 to 1.
- * @return {number} Ease in out version of value.
- */
-function easeInOut(value) {
- if (value < 0.5) {
- return easeIn(value * 2) * 0.5;
- } else {
- return easeOut(value * 2 - 1) * 0.5 + 0.5;
- }
-}
-
-/**
- * Stops the animated camera.
- */
-function stopAnimatedCamera() {
- g_animateCamera = false;
- g_demoTimer = 30;
- g_cameraTimer = 0;
- g_faderTransform.visible = false;
-}
-
-/**
- * Animates the camera.
- * @param {number} elapsedTime Elapsed time in seconds.
- */
-function animateCamera(elapsedTime) {
- if (g_animateCamera && window.g_finished) {
- g_cameraTimer -= elapsedTime;
-
- if (g_cameraTimer <= 0) {
- ++g_cameraPointIndex;
- if (g_cameraPointIndex >= g_cameraPoints.length) {
- g_cameraPointIndex = 0;
- }
- g_cameraPoint = g_cameraPoints[g_cameraPointIndex];
- g_cameraDuration = g_cameraPoint.duration * 3;
- g_cameraTimer = g_cameraDuration;
- }
-
- var lerp = 1;
- if (g_cameraTimer > 1) {
- var moveDuration = g_cameraDuration - 1;
- var timer = g_cameraTimer - 1;
- lerp = easeInOut(1 - timer / moveDuration);
-
- if (g_cameraTimer > g_cameraDuration - 1) {
- var fade = g_cameraTimer - (g_cameraDuration - 1);
- g_faderTransform.visible = true;
- g_faderColorParam.value = [0, 0, 0, fade];
- } else {
- g_faderTransform.visible = false;
- }
- } else {
- g_faderTransform.visible = true;
- g_faderColorParam.value = [0, 0, 0, 1 - g_cameraTimer];
- }
-
- g_camera.eye = g_math.lerpVector(g_cameraPoint.start.eye,
- g_cameraPoint.end.eye,
- lerp);
- g_camera.targetVector = g_math.lerpVector(g_cameraPoint.start.targetVector,
- g_cameraPoint.end.targetVector,
- lerp);
- g_camera.fieldOfView = g_math.degToRad(
- g_math.lerpScalar(g_cameraPoint.start.fieldOfView,
- g_cameraPoint.end.fieldOfView,
- lerp));
-
- updateCamera();
- updateProjection();
- } else {
- if (g_runDemo) {
- g_demoTimer -= elapsedTime;
- if (g_demoTimer <= 0) {
- g_animateCamera = true;
- }
- }
- }
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Info about this frame.
- */
-function onRender(renderEvent) {
- // save off the render event so look at it from the debugger.
- g_re = renderEvent;
-
- var elapsedTime = renderEvent.elapsedTime * window.g_timeMult;
- if (g_hudFadeTime > 0) {
- g_hudFadeTime -= elapsedTime;
- if (g_hudFadeTime <= 0) {
- g_hudQuad.transform.visible = false;
- }
- }
-
- // This is for selenium so that the hud is predictable.
- if (g_hudFadeTime > 0 && window.g_timeMult == 0) {
- g_hudFadeTime = 0;
- g_hudQuad.transform.visible = false;
- }
-
- // Normally I'd have used a SecondCounter but so we can run this in
- // selenium I set it up this way to be easy.
- window.g_clock += elapsedTime;
- g_globalClockParam.value = window.g_clock;
-
- if (g_loadInfo) {
- var progressInfo = g_loadInfo.getKnownProgressInfoSoFar();
- g_proxyOffsetParam.value = progressInfo.percent / 100 * PROXY_HEIGHT;
- if (progressInfo.percent != g_downloadPercent) {
- g_downloadPercent = progressInfo.percent;
- setHudText('Loading... ' + progressInfo.percent + '%' +
- ' (' + progressInfo.downloaded +
- ' of ' + progressInfo.totalBytes + progressInfo.suffix + ')');
- }
- }
-
- // This if is for selenium to make the camera predictable.
- if (window.g_timeMult) {
- animateCamera(elapsedTime);
- } else {
- setCamera(1);
- }
-
- handleCameraKeys();
- setClientSize();
- g_fpsManager.update(renderEvent);
-
- if (g_updateRenderTargets || g_waterMode == 1) {
- g_updateRenderTargets = false;
-
- // Render the reflection texture.
- setSpeedTransforms(false, true, false);
- g_clipHeightParam.value = g_reflectionClipHeight;
- g_client.root.identity();
- g_client.root.scale(1, 1, -1); // flip the scene
- g_client.renderTree(g_reflectionSurfaceSet);
-
- // Render the refraction texture.
- setSpeedTransforms(true, true, true);
- g_client.root.identity();
- g_client.root.scale(1, 1, 1 /* 0.75 */); // squish the scene.
- g_client.renderTree(g_refractionSurfaceSet);
- }
-
- // Render the main scene.
- setSpeedTransforms(true, false, false);
- g_clipHeightParam.value = g_mainClipHeight;
- g_client.root.identity();
- g_client.renderTree(g_mainViewInfo.root);
-
- // Render the HUD.
- g_client.renderTree(g_hudViewInfo.root);
-
- // Render the FPS display.
- g_client.renderTree(g_fpsManager.viewInfo.root);
-
- if (g_perfMon) {
- g_perfMon.onRender(renderEvent.elapsedTime);
- }
-}
-
-function onAllLoadingFinished() {
- g_loader = null;
- g_animateCamera = true;
-
- showHint();
-
- window.o3d_prepForSelenium = prepForSelenium;
- window.g_finished = true; // for selenium testing.
-}
-
-// Put the demo in a consistent state.
-function prepForSelenium() {
- // Turn off the perf monitor.
- g_perfMon = null;
-
- // Set the render targets to a fixed size.
- g_renderTargetWidth = 256;
- g_renderTargetHeight = 256;
- setupRenderTargets();
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- // These are here so they are shared by both V8 and the browser.
- window.g_finished = false; // for selenium
- window.g_timeMult = 1;
- window.g_clock = 0;
-
- // Comment out the line below to run the sample in the browser JavaScript
- // engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.util.addScriptUri('');
- o3djs.util.makeClients(initStep2);
-}
-
-function setupRenderTargets() {
- var oldReflectionTexture;
- var oldRefractionTexture;
- var oldDepthSurface;
-
- if (g_reflectionTexture) {
- g_mainPack.removeObject(g_reflectionSurfaceSet.renderSurface);
- g_mainPack.removeObject(g_refractionSurfaceSet.renderSurface);
- g_mainPack.removeObject(g_reflectionTexture);
- g_mainPack.removeObject(g_refractionTexture);
- g_mainPack.removeObject(g_depthSurface);
- } else {
- // First time only.
- g_reflectionSurfaceSet = g_mainPack.createObject('RenderSurfaceSet');
- g_refractionSurfaceSet = g_mainPack.createObject('RenderSurfaceSet');
- }
-
- // Create Render Targets for the reflection and refraction.
- g_reflectionTexture = g_mainPack.createTexture2D(g_renderTargetWidth,
- g_renderTargetHeight,
- g_o3d.Texture.ARGB8, 1,
- true);
- var reflectionSurface = g_reflectionTexture.getRenderSurface(0);
- g_refractionTexture = g_mainPack.createTexture2D(g_renderTargetWidth,
- g_renderTargetHeight,
- g_o3d.Texture.XRGB8, 1,
- true);
- var refractionSurface = g_refractionTexture.getRenderSurface(0);
- g_depthSurface = g_mainPack.createDepthStencilSurface(g_renderTargetWidth,
- g_renderTargetHeight);
-
- // Set up the render graph to generate them.
- g_reflectionSurfaceSet.renderSurface = reflectionSurface;
- g_reflectionSurfaceSet.renderDepthStencilSurface = g_depthSurface;
-
- g_refractionSurfaceSet.renderSurface = refractionSurface;
- g_refractionSurfaceSet.renderDepthStencilSurface = g_depthSurface;
-
- g_updateRenderTargets = true;
-
- if (g_waterMaterial) { // Every time after the first.
- var sampler = g_waterMaterial.getParam('reflectionSampler').value;
- sampler.texture = g_reflectionTexture;
- sampler = g_waterMaterial.getParam('refractionSampler').value;
- sampler.texture = g_refractionTexture;
- g_reflectionImage.sampler.texture = g_reflectionTexture;
- g_refractionImage.sampler.texture = g_refractionTexture;
- }
-}
-
-function increaseRenderTargetResolution() {
- var changed;
- if (g_renderTargetWidth < 2048) {
- g_renderTargetWidth <<= 1;
- changed = true;
- }
- if (g_renderTargetHeight < 2048) {
- g_renderTargetHeight <<= 1;
- changed = true;
- }
- setupRenderTargets();
-}
-
-function decreaseRenderTargetResolution() {
- var changed;
- if (g_renderTargetWidth > 256) {
- g_renderTargetWidth >>= 1;
- changed = true;
- }
- if (g_renderTargetHeight > 256) {
- g_renderTargetHeight >>= 1;
- changed = true;
- }
- setupRenderTargets();
-}
-
-/**
- * Loads shader files into g_shaders object.
- */
-function loadShaders() {
- var ii;
- var n;
- var names = [
- 'diffuse',
- 'diffuse_bump',
- 'diffuse_bump_2textures',
- 'diffuse_bump_blend',
- 'diffuse_bump_blend_underwater',
- 'diffuse_bump_specular',
- 'imageshader',
- 'just_color',
- 'proxy',
- 'simpleshader',
- 'skydomeshader',
- 'underwatershader',
- 'watercolorandskyshader',
- 'waterfallshader',
- 'watershader',
- 'waterstyle2',
- ];
-
- o3djs.effect.setLanguage('glsl');
- o3djs.particles.setLanguage('glsl');
- o3djs.canvas.setLanguage('glsl');
- o3djs.fps.setLanguage('glsl');
-
- for (ii = 0; ii < names.length; ++ii) {
- n = names[ii];
- g_shaders[n] =
- o3djs.io.loadTextFileSynchronous('shaders_glsl/' + n + '.glsl');
- }
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- loadShaders();
-
- g_materialPanelElement = o3djs.util.getElementById('materialpanel');
- g_propPanelElement = o3djs.util.getElementById('proppanel');
- g_effectPanelElement = o3djs.util.getElementById('effectpanel');
- g_upperPanelElement = o3djs.util.getElementById('upperpanel');
- g_effectTabsElement = o3djs.util.getElementById('effecttabs');
- g_effectTextAreaElement = o3djs.util.getElementById('effecttextarea');
- g_sceneElement = o3djs.util.getElementById('o3d');
-
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_quaternions = o3djs.quaternions;
- window.g_client = g_client = g_o3dElement.client;
-
- g_mainPack = g_client.createPack();
- g_scenePack = g_client.createPack();
-
- g_mainRoot = g_mainPack.createObject('Transform');
- g_baseRoot = g_scenePack.createObject('Transform');
- g_baseRoot.parent = g_mainRoot;
- g_sceneRoot = g_scenePack.createObject('Transform');
- g_sceneRoot.parent = g_baseRoot;
- g_mainRoot.parent = g_client.root;
- g_sceneRoot.translate(0, 0, -g_waterLevel);
-
- setupRenderTargets();
-
- // Create states to set clipping.
- g_reflectionClipState = g_mainPack.createObject('State');
- g_reflectionClipState.getStateParam('AlphaTestEnable').value = true;
- g_reflectionClipState.getStateParam('AlphaComparisonFunction').value =
- g_o3d.State.CMP_GREATER;
- var reflectionStateSet = g_mainPack.createObject('StateSet');
- reflectionStateSet.state = g_reflectionClipState;
- reflectionStateSet.parent = g_reflectionSurfaceSet;
-
- var fStrength = 4.0;
- g_refractionClipState = g_mainPack.createObject('State');
- g_refractionClipState.getStateParam('AlphaTestEnable').value = true;
- g_refractionClipState.getStateParam('AlphaComparisonFunction').value =
- g_o3d.State.CMP_GREATER;
-
- var refractionStateSet = g_mainPack.createObject('StateSet');
- refractionStateSet.state = g_refractionClipState;
- refractionStateSet.parent = g_refractionSurfaceSet;
-
- // Create the render graph for the main view.
- g_mainViewInfo = o3djs.rendergraph.createBasicView(
- g_mainPack,
- g_mainRoot);
-
- // Create a render graph for the reflection map
- g_reflectionViewInfo = o3djs.rendergraph.createExtraView(g_mainViewInfo);
- g_reflectionViewInfo.root.parent = reflectionStateSet;
- g_reflectionViewInfo.treeTraversal.transform = g_baseRoot;
- g_reflectionViewInfo.performanceState.getStateParam('CullMode').value =
- g_o3d.State.CULL_CCW;
- g_reflectionViewInfo.performanceState.getStateParam(
- 'ColorWriteEnable').value = 15;
- g_reflectionViewInfo.zOrderedState.getStateParam('CullMode').value =
- g_o3d.State.CULL_CCW;
- g_reflectionViewInfo.zOrderedState.getStateParam(
- 'ColorWriteEnable').value = 15;
-
- // Create a render graph for the refraction map
- g_refractionViewInfo = o3djs.rendergraph.createBasicView(
- g_mainPack,
- g_baseRoot,
- refractionStateSet);
-
- // Create a render graph for the HUD
- g_hudRoot = g_mainPack.createObject('Transform');
- g_hudViewInfo = o3djs.rendergraph.createBasicView(
- g_mainPack,
- g_hudRoot);
- g_hudViewInfo.clearBuffer.clearColorFlag = false;
-
- g_hudViewInfo.zOrderedState.getStateParam('CullMode').value =
- g_o3d.State.CULL_NONE;
-
- g_hudViewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 0, 1], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- //g_reflectionViewInfo.clearBuffer.clearColor = [0.5, 1, 0.5, 1];
- //g_refractionViewInfo.clearBuffer.clearColor = [0.5, 0.5, 1, 1];
- g_reflectionViewInfo.clearBuffer.clearColor = [0, 0, 0, 0];
- g_refractionViewInfo.clearBuffer.clearColor = g_waterColor;
-
- // Set some names so it's easier to debug.
- g_mainViewInfo.performanceDrawList.name = 'performanceDrawList';
- g_mainViewInfo.zOrderedDrawList.name = 'zOrderedDrawList';
-
- // Turn off culling for transparent stuff so we can see the backs of leaves.
- g_mainViewInfo.zOrderedState.getStateParam('CullMode').value =
- g_o3d.State.CULL_NONE;
- g_mainViewInfo.zOrderedState.getStateParam('AlphaReference').value = 0.7;
-
- // Turn on alpha test in the performance list for our clipping plane.
- g_mainViewInfo.performanceState.getStateParam('AlphaTestEnable').value = true;
- g_mainViewInfo.performanceState.getStateParam(
- 'AlphaComparisonFunction').value = g_o3d.State.CMP_GREATER;
-
- g_fpsManager = o3djs.fps.createFPSManager(g_mainPack,
- g_client.width,
- g_client.height);
- g_fpsManager.setVisible(false);
-
- // Create a param object to hold a few params to drive things globally.
- g_globalParams = g_mainPack.createObject('ParamObject');
- g_globalParams.name = 'global params';
- g_globalClockParam = g_globalParams.createParam('clock', 'ParamFloat');
- g_lightPositionParam = g_globalParams.createParam('lightWorldPos',
- 'ParamFloat3');
- g_lightDirectionParam = g_globalParams.createParam('lightDirection',
- 'ParamFloat3');
- g_lightColorParam = g_globalParams.createParam('lightColor',
- 'ParamFloat4');
- g_lightColorParam.value = [2.0, 1.8, 1.4, 1];
- setSunPosition([0, -100000, 200000]);
-
- g_clipHeightParam = g_globalParams.createParam('clipHeight', 'ParamFloat');
- g_proxyOffsetParam = g_globalParams.createParam('offset', 'ParamFloat');
-
- g_particleSystem = o3djs.particles.createParticleSystem(
- g_mainPack,
- g_mainViewInfo,
- g_globalClockParam,
- g_math.pseudoRandom);
-
- // Since we set the state for the draw pass to 'AlphaReference' = 0.7
- // We need to set it back to 0.0 for the particles.
- for (var ii = 0; ii < g_particleSystem.particleStates.length; ++ii) {
- g_particleSystem.particleStates[ii].getStateParam(
- 'AlphaReference').value = 0.0;
- }
-
- g_editableEffects.push(g_particleSystem.effects[0]);
- g_editableEffects.push(g_particleSystem.effects[1]);
-
- g_loader = o3djs.loader.createLoader(onAllLoadingFinished);
-
- setupWater();
- setupHud();
-
- loadProxy();
-
- // It's important to create stuff in g_mainPack and not g_scenePack because
- // g_scenePack will be scanned and modified after loading.
-
- setClientSize();
- updateCamera();
- updateProjection();
-
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', onMouseDown);
- o3djs.event.addEventListener(g_o3dElement, 'mousemove', onMouseMove);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', onMouseUp);
- o3djs.event.addEventListener(g_o3dElement, 'wheel', onWheel);
- o3djs.event.addEventListener(g_o3dElement, 'keydown', onKeyDown);
- o3djs.event.addEventListener(g_o3dElement, 'keyup', onKeyUp);
-
- // If we don't check the size of the client area every frame we don't get a
- // chance to adjust the perspective matrix fast enough to keep up with the
- // browser resizing us.
- g_client.setRenderCallback(onRender);
-
- // Because we don't render the render targets every frame of the OS has
- // to reset them their contents will get lost. In that case O3D will notify
- // us through this callback so we can re-render our render targets.
- g_client.setLostResourcesCallback(function() {
- g_updateRenderTargets = true;
- });
-}
-
-/**
- * Loads a texture.
- *
- * @param {!o3djs.loader.Loader} loader Loader to use to load texture.
- * @param {!o3d.Pack} pack Pack to load texture in.
- * @param {!o3d.Material} material Material to attach sampler to.
- * @param {string} samplerName Name of sampler.
- * @param {string} textureName filename of texture.
- * @return {!o3d.Sampler} Sampler attached to material.
- */
-function loadTexture(loader, pack, material, samplerName, textureName) {
- var sampler = pack.createObject('Sampler');
- setParam(material, samplerName, sampler);
-
- var url = o3djs.util.getAbsoluteURI('assets/' + textureName);
- loader.loadTexture(pack, url, function(texture, success) {
- sampler.texture = texture;
- });
-
- return sampler;
-}
-
-/**
- * Create the waterfall effect.
- */
-function setupWaterfall() {
- // A prefix for waterfall materials would have been better.
- var material = g_scenePack.getObjects('Standard_3', 'o3d.Material')[0];
-
- // Create an effect with a v offset parameter so we can scroll the
- // UVs.
- var effect = g_mainPack.createObject('Effect');
- effect.name = 'waterfall';
- effect.loadFromFXString(g_shaders.waterfallshader);
- effect.createUniformParameters(material);
-
- g_editableEffects.push(effect);
-
- // Set the waterfall to use additive blending.
- var state = g_mainPack.createObject('State');
- state.getStateParam('SourceBlendFunction').value =
- g_o3d.State.BLENDFUNC_SOURCE_ALPHA;
- state.getStateParam('DestinationBlendFunction').value =
- g_o3d.State.BLENDFUNC_ONE;
- state.getStateParam('AlphaReference').value = 0.0;
- //state.getStateParam('ZWriteEnable').value = false;
-
- material.state = state;
- material.drawList = g_mainViewInfo.zOrderedDrawList;
- material.effect = effect;
-
- // Create a counter to scroll the Vs.
- // var counter = g_mainPack.createObject('SecondCounter');
- // material.getParam('vOffset').bind(counter.getParam('count'));
- //
- // For selenium testing we need a global clock.
- material.getParam('vOffset').bind(g_globalClockParam);
-
-}
-
-/**
- * Setup underwater.
- * Must be called after the scene has loaded.
- * NOTE: The coral needs a new shader that supports normal maps
- * but it's a low priority to fix right now.
- */
-function setupUnderwater() {
- var effect = g_mainPack.createObject('Effect');
- effect.name = 'underwater';
- effect.loadFromFXString(g_shaders.underwatershader);
- g_editableEffects.push(effect);
-
- // make 2 materials, one for zOrdered, one for performance.
- var materials = [];
- for (var ii = 0; ii < 2; ++ii) {
- var material = g_mainPack.createObject('Material');
- // Copy the water params so this material gets access to the noise samplers.
- // and the clock regardless of whether or not it uses them. That way you
- // can access them as you edit the shader live.
- material.copyParams(g_waterMaterial);
- material.effect = effect;
- effect.createUniformParameters(material);
-
- bindParam(material, 'sunVector', g_lightDirectionParam);
- setParam(material, 'waterColor', g_waterColor);
- setParam(material, 'fadeFudge', -1 / 1800);
- bindParam(material, 'clock', g_globalClockParam);
-
- g_fadeParams[ii] = material.getParam('fadeFudge');
- materials[ii] = material;
- }
-
- materials[0].drawList = g_refractionViewInfo.performanceDrawList;
- materials[0].name = 'underwaterOpaque';
- materials[1].drawList = g_refractionViewInfo.zOrderedDrawList;
- materials[1].name = 'underwaterTransparent';
-
- g_underwaterMaterials = materials;
-
- // put a draw element on each element in the scene to draw it with the
- // underwater shader.
- var elements = g_scenePack.getObjectsByClassName('o3d.Element');
- for (var ee = 0; ee < elements.length; ++ee) {
- var element = elements[ee];
- var originalMaterial = element.material;
- var materialInfo = g_materialLists[originalMaterial.name];
- if ((!materialInfo || materialInfo.refract) &&
- element.name != 'Seafloor|Sand_Dark' &&
- (!materialInfo || materialInfo.effect != 'diffuse_bump_2textures')) {
- // Use the sampler from the original material.
- var originalSamplerParam = originalMaterial.getParam('diffuseSampler');
- if (originalSamplerParam) {
- var drawElement = element.createDrawElement(
- g_scenePack,
- originalMaterial.drawList == g_mainViewInfo.performanceDrawList ?
- materials[0] : materials[1]);
- // create a Sampler Param on this draw element to use instead of the
- // material's.
- var samplerParam = drawElement.createParam('diffuseSampler',
- 'ParamSampler');
- samplerParam.value = originalSamplerParam.value;
- }
- }
- }
-
- // Special case the sand and coral rocks.
- var materialNames = {
- 'Sand_Dark': {texture: 'image3.dds'},
- 'Folg_coralRockA_mat': {texture: 'image30.dds'},
- 'Folg_coralRockB_mat': {texture: 'image30.dds'}};
- for (var name in materialNames) {
- var info = materialNames[name];
- var material = g_scenePack.getObjects(name, 'o3d.Material')[0];
- material.drawList = g_refractionViewInfo.performanceDrawList;
- addTexture(material, 'diffuse2Sampler', info.texture);
- }
-}
-
-/**
- * Create the water effect.
- */
-function setupWater() {
- var waterEffects = ['watershader', 'watercolorandskyshader', 'waterstyle2'];
- var effects = [];
- for (var ee = 0; ee < waterEffects.length; ++ee) {
- var name = waterEffects[ee]
- var effect = g_mainPack.createObject('Effect');
- effect.name = name;
- effect.loadFromFXString(g_shaders[name]);
- effects[ee] = effect;
- g_editableEffects.push(effect);
- }
- g_waterEffect = effects[0];
- g_waterColorAndSkyEffect = effects[1];
- g_waterStyle2Effect = effects[2];
-
- var effect = g_waterEffect;
-
- var material = g_mainPack.createObject('Material');
- g_waterMaterial = material;
- material.name = 'water';
- material.drawList = g_mainViewInfo.performanceDrawList;
- material.effect = effect;
- effect.createUniformParameters(material);
-
- // We could reuse the one from the waterfall but let's make 2 anyway.
- // var counter = g_mainPack.createObject('SecondCounter');
- // For selenium testing we need a global clock.
-
- setParam(material, 'waterColor', g_waterColor);
- setParam(material, 'reflectionRefractionOffset', 0.1);
- //material.getParam('clock').bind(counter.getParam('count'));
- material.getParam('clock').bind(g_globalClockParam);
- g_viewPositionParam = material.getParam('viewPosition');
-
- var sampler = g_mainPack.createObject('Sampler');
- sampler.texture = g_refractionTexture;
- sampler.addressModeU = g_o3d.Sampler.MIRROR;
- sampler.addressModeV = g_o3d.Sampler.MIRROR;
- setParam(material, 'refractionSampler', sampler);
- sampler = g_mainPack.createObject('Sampler');
- sampler.texture = g_reflectionTexture;
- sampler.addressModeU = g_o3d.Sampler.MIRROR;
- sampler.addressModeV = g_o3d.Sampler.MIRROR;
- setParam(material, 'reflectionSampler', sampler);
-
- var shape = o3djs.primitives.createPlane(g_mainPack, material,
- 100000, 100000, 100, 100,
- [[1, 0, 0, 0],
- [0, 0, 1, 0],
- [0, -1, 0, 0],
- [0, 0, 0, 1]]);
-
- g_waterTransform = g_mainPack.createObject('Transform');
- g_waterTransform.name = 'watersurface';
- g_waterTransform.addShape(shape);
-
- function waterAssetsLoaded() {
- g_waterTransform.parent = g_mainRoot;
- setupSkyDome();
- }
-
- // Create a loader for the water so we can know when all its assets have
- // loaded.
- var loader = g_loader.createLoader(waterAssetsLoaded);
-
- g_environmentSampler = loadTexture(loader, g_mainPack, material,
- 'environmentSampler',
- 'sky-cubemap.dds');
-
- // Create some textures.
- var textureInfo = [
- {width: 128, height: 128, type: 0, name: 'noiseSampler'},
- {width: 64, height: 64, type: 0, name: 'noiseSampler2'},
- {width: 32, height: 32, type: 0, name: 'noiseSampler3'},
- {width: 32, height: 1, type: 1, name: 'fresnelSampler'}
- ];
-
- for (var tt = 0; tt < textureInfo.length; ++tt) {
- var info = textureInfo[tt];
- var pixels = [];
-
- switch (info.type) {
- case 0:
- // Create a noise texture.
- for (var yy = 0; yy < info.height; ++yy) {
- for (var xx = 0; xx < info.width; ++xx) {
- for (var cc = 0; cc < 3; ++cc) {
- pixels.push(g_math.pseudoRandom());
- }
- }
- }
- break;
- case 1:
- // Create a ramp texture. (this needs to be a fresnel ramp?)
- for (var yy = 0; yy < info.height; ++yy) {
- for (var xx = 0; xx < info.width; ++xx) {
- // TODO: figure this out.
- var color = Math.pow(1 - xx / info.width, 10);
- for (var cc = 0; cc < 3; ++cc) {
- pixels.push(color);
- }
- }
- }
- break;
- }
- var texture = g_mainPack.createTexture2D(
- info.width, info.height, g_o3d.Texture.XRGB8, 1, false);
- texture.set(0, pixels);
- var sampler = g_mainPack.createObject('Sampler');
- sampler.texture = texture;
- setParam(material, info.name, sampler);
- }
-
- loader.finish();
-}
-
-/**
- * Create particles.
- */
-function setupParticles() {
- setupTorches();
- setupMist();
-}
-
-/**
- * Create the torches.
- */
-function setupTorches() {
- g_torchEmitter = g_particleSystem.createParticleEmitter(g_torchTexture);
- g_torchEmitter.setState(o3djs.particles.ParticleStateIds.ADD);
- g_torchEmitter.setColorRamp(
- [1, 1, 0, 1,
- 1, 0, 0, 1,
- 0, 0, 0, 1,
- 0, 0, 0, 0.5,
- 0, 0, 0, 0]);
- g_torchEmitter.setParameters({
- numParticles: 40,
- lifeTime: 2,
- timeRange: 2,
- startSize: 50,
- endSize: 90,
- positionRange: [10, 10, 10],
- velocity: [0, 0, 60], velocityRange: [15, 15, 15],
- acceleration: [0, 0, -20],
- spinSpeedRange: 4}
- );
-
- g_torchMaterial = g_torchEmitter.material;
-
- // Add one to each torch.
- var shape = g_torchEmitter.shape;
- g_scenePack.getObjects('particle_torch01',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_torch02',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_torch03',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_torch04',
- 'o3d.Transform')[0].addShape(shape);
-}
-
-/**
- * Create the mist.
- */
-function setupMist() {
- g_topMistEmitter = g_particleSystem.createParticleEmitter(g_mistTexture);
- g_topMistEmitter.setState(o3djs.particles.ParticleStateIds.ADD);
- g_topMistEmitter.setColorRamp(
- [1, 1, 1, 2,
- 1, 1, 1, 0]);
- g_topMistEmitter.setParameters({
- numParticles: 20,
- timeRange: 3,
- lifeTime: 3, lifeTimeRange: 1,
- startSize: 400,
- endSize: 600,
- position: [-100, -100, 0], positionRange: [25, 25, 0],
- velocity: [0, 0, 150], velocityRange: [15, 15, 15],
- worldAcceleration: [0, 0, -500],
- spinSpeedRange: 8}
- );
-
- // Add one to each top.
- var shape = g_topMistEmitter.shape;
- g_scenePack.getObjects('particle_falltop01',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_falltop02',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_falltop03',
- 'o3d.Transform')[0].addShape(shape);
-
- g_bottomMistEmitter = g_particleSystem.createParticleEmitter(g_mistTexture);
- g_bottomMistEmitter.setState(o3djs.particles.ParticleStateIds.ADD);
- g_bottomMistEmitter.setColorRamp(
- [1, 1, 1, 1,
- 1, 1, 1, 0]);
- g_bottomMistEmitter.setParameters({
- numParticles: 40,
- lifeTime: 2,
- timeRange: 2,
- startSize: 800,
- endSize: 1500,
- position: [0, 0, 100], positionRange: [200, 200, 10],
- velocityRange: [200, 200, 0],
- acceleration: [0, 0, -20],
- spinSpeedRange: 4}
- );
-
- // Add one to each bottom.
- shape = g_bottomMistEmitter.shape;
-
- g_scenePack.getObjects('particle_fallbottom01',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_fallbottom02',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_fallbottom03',
- 'o3d.Transform')[0].addShape(shape);
-
- g_rippleEmitter = g_particleSystem.createParticleEmitter(g_mistTexture);
- g_rippleEmitter.setState(o3djs.particles.ParticleStateIds.ADD);
- g_rippleEmitter.setColorRamp(
- [0.7, 0.8, 1, 0.5,
- 1, 1, 1, 0]);
- g_rippleEmitter.setParameters({
- numParticles: 20,
- lifeTime: 2,
- timeRange: 2,
- startSize: 50,
- endSize: 10000,
- position: [0, 0, 10], positionRange: [250, 250, 0],
- orientation: o3djs.quaternions.rotationX(Math.PI / 2),
- billboard: false});
-
- // Add one to each bottom.
- shape = g_rippleEmitter.shape;
-
- g_scenePack.getObjects('particle_fallbottom01',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_fallbottom02',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_fallbottom03',
- 'o3d.Transform')[0].addShape(shape);
-}
-
-function setupSkyDome() {
- // Create the skydome effect.
- var effect = g_mainPack.createObject('Effect');
- effect.name = 'skydome';
- effect.loadFromFXString(g_shaders.skydomeshader);
- g_editableEffects.push(effect);
-
- var material = g_mainPack.createObject('Material');
- g_skyDomeMaterial = material;
- material.name = 'skydome';
- material.drawList = g_mainViewInfo.performanceDrawList;
- material.effect = effect;
- effect.createUniformParameters(material);
-
- material.getParam('environmentSampler').value = g_environmentSampler;
-
- // Create a special quad to draw the sky. We won't transform this quad
- // at all. It's already in clip-space.
- var shape = o3djs.primitives.createPlane(g_mainPack, material,
- 2, 2, 1, 1,
- [[1, 0, 0, 0],
- [0, 0, 1, 0],
- [0, -1, 0, 0],
- [0, 0, 0.99999, 1]]);
-
- g_skyDomeTransform = g_mainPack.createObject('Transform');
- g_skyDomeTransform.parent = g_mainRoot;
- g_skyDomeTransform.addShape(shape);
-}
-
-/**
- * Creates an Image object which is a transform and a child scaleTransform
- * scaled to match the texture
- *
- * @constructor
- * @param {!o3d.Transform} parent Transform to parent image too.
- * @param {!o3d.Texture} texture The texture.
- * @param {boolean} opt_topLeft If true the origin of the image will be it's
- * topleft corner, the default is the center of the image.
- */
-function Image(parent, texture, opt_topLeft) {
- // create a transform for positioning
- this.transform = g_mainPack.createObject('Transform');
- this.transform.parent = parent;
-
- // create a transform for scaling to the size of the image just so
- // we don't have to manage that manually in the transform above.
- this.scaleTransform = g_mainPack.createObject('Transform');
- this.scaleTransform.parent = this.transform;
-
- // setup the sampler for the texture
- this.sampler = g_mainPack.createObject('Sampler');
- this.sampler.addressModeU = g_o3d.Sampler.CLAMP;
- this.sampler.addressModeV = g_o3d.Sampler.CLAMP;
- this.paramSampler = this.scaleTransform.createParam('diffuseSampler',
- 'ParamSampler');
- this.paramSampler.value = this.sampler;
-
- this.sampler.texture = texture;
- this.scaleTransform.addShape(g_imageShape);
- if (opt_topLeft) {
- this.scaleTransform.translate(texture.width / 2, texture.height / 2, 0);
- }
- this.scaleTransform.scale(texture.width, -texture.height, 1);
- this.colorParam = this.scaleTransform.createParam('colorMult', 'ParamFloat4');
- this.colorParam.value = [1, 1, 1, 1];
-}
-
-/**
- * Sets up the hud.
- */
-function setupHud() {
- var effect = g_mainPack.createObject('Effect');
- effect.name = 'hud';
- effect.loadFromFXString(g_shaders.imageshader);
- g_editableEffects.push(effect);
- // Make the default colorMult 1, 1, 1, 1 uncase it is not supplied by the
- // material.
- effect.createParam('colorMult', 'ParamFloat4').value = [1, 1, 1, 1];
-
- g_imageEffect = effect;
-
- var g_imageMaterial = g_mainPack.createObject('Material');
- g_imageMaterial.drawList = g_hudViewInfo.zOrderedDrawList;
- g_imageMaterial.effect = effect;
- effect.createUniformParameters(g_imageMaterial);
- g_imageMaterial.getParam('colorMult').value = [1, 1, 1, 1];
-
- g_renderTargetDisplayRoot = g_mainPack.createObject('Transform');
- g_renderTargetDisplayRoot.parent = g_hudRoot;
- g_renderTargetDisplayRoot.visible = false;
-
- g_imageShape = o3djs.primitives.createPlane(g_mainPack, g_imageMaterial,
- 1, 1, 1, 1,
- [[1, 0, 0, 0],
- [0, 0, 1, 0],
- [0, 1, 0, 0],
- [0, 0, 0, 1]]);
-
- // Because it's easier to make a texture here than manage another effect
- var backTexture = g_mainPack.createTexture2D(
- 1, 1, g_o3d.Texture.XRGB8, 1, false);
- backTexture.set(0, [1, 1, 1]);
-
- g_whiteTexture = backTexture;
- g_whiteSampler = g_mainPack.createObject('Sampler');
- g_whiteSampler.texture = g_whiteTexture;
-
- // Make images to show the render targets.
- for (var ii = 0; ii < 2; ++ii) {
- var textureDisplaySquareSize = 256;
- var renderTargetTexture = (ii == 0) ? g_reflectionTexture :
- g_refractionTexture;
- var x = 10;
- var y = 10 + ii * (textureDisplaySquareSize + 10);
- var borderSize = 2;
- var image;
- // make a back image to create a border around render target.
- image = new Image(g_renderTargetDisplayRoot, backTexture, true);
- image.transform.translate(x - borderSize, y - borderSize, -3);
- image.transform.scale(textureDisplaySquareSize + borderSize * 2,
- textureDisplaySquareSize + borderSize * 2,
- 1);
- image = new Image(g_renderTargetDisplayRoot, renderTargetTexture, true);
- image.transform.translate(x, y, -2);
- image.transform.scale(textureDisplaySquareSize / g_renderTargetWidth,
- textureDisplaySquareSize / g_renderTargetHeight, 1);
- if (ii == 0) {
- g_reflectionImage = image;
- } else {
- g_refractionImage = image;
- }
- }
-
- // Make a fader plane.
- {
- var image = new Image(g_hudRoot, backTexture, true);
- g_faderTransform = image.transform;
- g_faderTransform.visible = false;
- g_faderColorParam = image.colorParam;
- updateFaderPlane();
- }
-
- // Make a canvas for text.
- var canvasLib = o3djs.canvas.create(g_mainPack,
- g_hudRoot,
- g_hudViewInfo);
-
- g_hudQuad = canvasLib.createXYQuad(20, 20, -1, 512, 512, true);
- g_paint = g_mainPack.createObject('CanvasPaint');
-
- g_paint.setOutline(3, [1, 1, 1, 1]);
- g_paint.textAlign = g_o3d.CanvasPaint.LEFT;
- g_paint.textSize = 16;
- g_paint.textTypeface = 'Arial';
- g_paint.color = [0, 0, 0, 1];
-
- setHudText('Loading...');
-}
-
-/**
- * Sets the text on the hud.
- * @param {string} text The text to display.
- */
-function setHudText(text) {
- if (g_showError) {
- return;
- }
- var canvas = g_hudQuad.canvas;
- canvas.clear([0, 0, 0, 0]);
- canvas.saveMatrix();
- var lines = text.split('\n');
- for (var ll = 0; ll < lines.length; ++ll) {
- var tabs = lines[ll].split('\t');
- for (var tt = 0; tt < tabs.length; ++tt) {
- canvas.drawText(tabs[tt], 10 + tt * 120, 30 + 20 * ll, g_paint);
- }
- }
- canvas.restoreMatrix();
-
- g_hudQuad.updateTexture();
-}
-
-/**
- * Show a hint message.
- */
-function showHint() {
- g_hudQuad.transform.visible = true;
- g_hudFadeTime = 0.0;
- setHudText('press H for help.');
-}
-
-/**
- * Show a help message.
- */
-function toggleHelp() {
- g_hudFadeTime = 0.0;
- g_helpVisible = !g_helpVisible;
- g_hudQuad.transform.visible = true;
- if (g_helpVisible) {
- setHudText('1 - 4\t: Camera Preset\n' +
- 'Mouse\t: Look Around\n' +
- 'Wheel\t: Field of View\n' +
- 'Arrows\t: Move Camera\n' +
- 'p\t: Toggle Props\n' +
- 'm\t: Edit Materials\n' +
- 'e\t: Edit Effects\n' +
- 'r\t: Show Render Targets\n' +
- 'c\t: Use Simple Shaders\n' +
- 'f\t: Show FPS\n' +
- 'h\t: Show Help\n' +
- 'o\t: Change Water Effect\n' +
- 'q\t: Toggle demo camera\n');
- } else {
- showHint();
- }
-}
-
-/**
- * Show error.
- * @param {string} msg Msg to display.
- */
-function showError(msg) {
- g_hudQuad.transform.visible = true;
- setHudText('Error: Could not load scene.\n' + msg);
- g_showError = true;
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
diff --git a/o3d/samples/beachdemo/beachdemo.html b/o3d/samples/beachdemo/beachdemo.html
deleted file mode 100644
index 67db3bd..0000000
--- a/o3d/samples/beachdemo/beachdemo.html
+++ /dev/null
@@ -1,150 +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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
- <title>
- Beach Demo
- </title>
-<style type="text/css">
-html, body {
- margin: 0;
- padding: 0;
- border: 0;
- height: 100%;
-}
-textarea {
- width: 95%;
- height: 95%;
-}
-#proppanel {
- font-size: xx-small;
- background-color: lightblue;
- font-family: Arial, san-serif;
-}
-#materialpanel table {
- width: 100%;
-}
-#proppanel .even {
- background-color: #ccddff;
-}
-#proppanel .odd {
- background-color: #ffffff;
-}
-
-#materialpanel {
- font-size: xx-small;
- font-family: Arial, san-serif;
-}
-#materialpanel table {
- width: 100%;
-}
-#materialpanel input[type=text] {
- font-size: x-small;
-}
-#materialpanel .even {
- background-color: #ccddff;
-}
-#materialpanel .odd {
- background-color: #ccddff;
-}
-
-#materialpanel label {
-}
-#materialpanel .field {
- white-space: nowrap;
-}
-#materialpanel label {
-}
-#effectpanel {
- background-color: lightgreen;
-}
-#effecttabs {
-}
-#effecttabs .tab {
-}
-#effecttabs .selected {
- background-color: yellow;
-}
-</style>
-</head>
-<body onload="init()" onunload="uninit()">
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" src="beachdemo.js"></script>
-<div style="width: 100%; height: 100%;">
- <div id="upperpanel" style="width: 100%; height: 100%;">
- <div
- id="o3d"
- style="
- width: 100%;
- height: 100%;
- float: left;
- background-color: blue;
- "></div>
- <div
- id="materialpanel"
- style="
- width: 20%;
- height: 100%;
- overflow: auto;
- display: none;
- "><table><tr><td><input type="text" value="foogoo"/></td></tr></table></div>
- <div
- id="proppanel"
- style="
- width: 20%;
- height: 100%;
- overflow: auto;
- display: none;
- "></div>
- </div>
- <div
- id="effectpanel"
- style="
- width: 100%;
- height: 30%;
- display: none;
- overflow: auto;
- ">
-<div style="height:10%;">
- <input type="button" value="Compile" id="compileButton"></input>
- <span id="effecttabs"></span>
-</div>
-<div style="height:90%;"><textarea id="effecttextarea"></textarea>
-</div>
- </div>
-</div>
-</body>
-</html>
-
-
diff --git a/o3d/samples/beachdemo/beachdemo.js b/o3d/samples/beachdemo/beachdemo.js
deleted file mode 100644
index 3c3cac0..0000000
--- a/o3d/samples/beachdemo/beachdemo.js
+++ /dev/null
@@ -1,2772 +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.
- */
-
-
-/**
- * @fileoverview The beachdemo javascript.
- */
-
-
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.dump');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.loader');
-o3djs.require('o3djs.picking');
-o3djs.require('o3djs.canvas');
-o3djs.require('o3djs.fps');
-o3djs.require('o3djs.debug');
-o3djs.require('o3djs.particles');
-o3djs.require('o3djs.performance');
-o3djs.require('o3djs.io');
-
-var PROXY_HEIGHT = 5150;
-
-// client.root
-// |
-// g_mainRoot
-// |
-// +-----+--------+----------------+
-// | | |
-// g_baseRoot g_waterTransform g_skyDomeTransform
-// |
-// g_sceneRoot
-
-var g_re;
-var g_animateCamera = false;
-var g_cameraDuration = 1;
-var g_cameraPoint;
-var g_cameraPointIndex = 0;
-var g_cameraTimer = 0;
-var g_demoTimer = 0;
-var g_runDemo = true;
-var g_oldCameraClock = 0;
-var g_speedTransforms = [[], [], [], []];
-var g_sceneRoot;
-var g_baseRoot;
-var g_reflectionClipHeight = 100;
-var g_mainClipHeight = 100000000;
-var g_o3d;
-var g_hudFadeTime;
-var g_helpVisible = false;
-var g_math;
-var g_key;
-var g_paint;
-var g_sceneUrl;
-var g_quaternions;
-var g_waterMode = 0;
-var g_updateRenderTargets = true;
-var g_compileEffect;
-var g_reflectRefract = false;
-var g_environmentSampler;
-var g_materialPanelElement;
-var g_propPanelElement;
-var g_effectPanelElement;
-var g_upperPanelElement;
-var g_effectTabsElement;
-var g_effectTextAreaElement;
-var g_editableEffects = [];
-var g_editableEffectsSource = [];
-var g_currentEditEffect;
-var g_faderColorParam;
-var g_faderTransform;
-var g_renderTargetDisplayRoot;
-var g_sceneElement;
-var g_client;
-var g_scenePack;
-var g_proxyPack;
-var g_mainPack;
-var g_fadeParams = [];
-var g_mainViewInfo; // main view
-var g_hudRoot; // root transform for hud.
-var g_mainRoot;
-var g_proxyRoot;
-var g_waterLevel = 500;
-var g_reflectionViewInfo;
-var g_refractionViewInfo;
-var g_hudViewInfo;
-var g_loader;
-var g_loadInfo;
-var g_reflectionClipState;
-var g_refractionClipState;
-var g_mainRenderGraphRoot;
-var g_reflectionSurfaceSet;
-var g_refractionSurfaceSet;
-var g_skyDomeTransform;
-var g_waterTransform;
-var g_reflectionTexture;
-var g_refractionTexture;
-var g_reflectionImage;
-var g_refrectionImage;
-var g_depthSurface;
-var g_globalParams;
-var g_globalClockParam;
-var g_clipHeightParam;
-var g_lightPositionParam;
-var g_lightDirectionParam;
-var g_lightColorParam;
-var g_proxyOffsetParam;
-var g_originalLightColor;
-var g_viewPositionParam;
-var g_underwaterMaterials;
-var g_whiteTexture;
-var g_whiteSampler;
-var g_waterMaterial;
-var g_waterEffect;
-var g_waterColorAndSkyEffect;
-var g_waterStyle2Effect;
-var g_torchMaterial;
-var g_torchEmitter;
-var g_torchTexture;
-var g_mistTexture;
-var g_topMistEmitter;
-var g_bottomMistEmitter;
-var g_rippleEmitter;
-var g_skyDomeMaterial;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-var g_o3dElement;
-var g_cameraInfos = [];
-var g_cameraMoveSpeedMultiplier = 50;
-var g_keyCurrentlyDown = 0; // If any key is currently down this is true.
-var g_keyDown = []; // which keys are down by key code.
-var g_keyDownKeyCodeFunctions = {};
-var g_keyUpKeyCodeFunctions = {};
-var g_materialSwapTable = [];
-var g_showingSimpleMaterialsMode = 0;
-var g_simpleEffects = [];
-var g_originalSampler = { };
-var g_dragStartContext;
-var g_dragging = false;
-var g_imageShape;
-var g_imageMaterial;
-var g_imageEffect;
-var g_waterColor = [0.13, 0.19, 0.22, 1];
-var g_hudQuad;
-var g_fpsManager;
-var g_fpsVisible = false;
-var g_particleSystem;
-var g_particleLoader;
-var g_downloadPercent = -1;
-var g_showError = false;
-var g_sceneEffects = [];
-var g_sceneTexturesByURI;
-var g_renderTargetWidth = 256;
-var g_renderTargetHeight = 256;
-var g_perfMon;
-var g_shaders = {};
-
-var g_camera = {
- farPlane: 80000,
- nearPlane: 10,
- up: [0, 0, 1],
- fieldOfView: Math.PI / 4, // 45 degrees
- eye: [-9662, -10927, 1920],
- targetVector: [0.43, 0.90, 0.02],
- xAxis: [0.8335, -0.5522, -0.0157],
- minFieldOfView: 5 * Math.PI / 180,
- maxFieldOfView: 70 * Math.PI / 180
-};
-
-var g_cameraPoints = [
- { duration: 15,
- start: {eye: [-7952.043, -3027.629, 1782.494],
- targetVector: [0.054, 0.997, -0.059],
- fieldOfView: 45},
- end: {eye: [4579.533, -3707.403, 1782.494],
- targetVector: [0.221, 0.963, 0.156],
- fieldOfView: 45}},
- { duration: 5,
- start: {eye: [-9862.542, -11676.196, 1888.062],
- targetVector: [0.552, 0.834, -0.007],
- fieldOfView: 45},
- end: {eye: [-4809.674, -4048.170, 1822.536],
- targetVector: [0.552, 0.834, -0.007],
- fieldOfView: 45}},
- { duration: 5,
- start: {eye: [2728.344, -6393.682, 2241.729],
- targetVector: [-0.312, 0.949, 0.039],
- fieldOfView: 45},
- end: {eye: [-1683.553, 3379.889, 3616.049],
- targetVector: [-0.118, 0.796, 0.594],
- fieldOfView: 45}},
- { duration: 5,
- start: {eye: [1499.756, -2208.060, 380.914],
- targetVector: [-0.537, 0.788, 0.303],
- fieldOfView: 45},
- end: {eye: [7333.003, -6937.257, 4163.998],
- targetVector: [-0.811, 0.509, -0.290],
- fieldOfView: 45}},
- { duration: 5,
- start: {eye: [4746.377, 1086.006, 3433.715],
- targetVector: [-0.982, 0.188, -0.036],
- fieldOfView: 45},
- end: {eye: [4746.377, 1086.006, 3433.715],
- targetVector: [-0.996, 0.072, 0.044],
- fieldOfView: 6.49667876045379}},
- { duration: 5,
- start: {eye: [-4173.890, -4212.830, 398.267],
- targetVector: [-0.339, 0.900, 0.272],
- fieldOfView: 45},
- end: {eye: [-4149.606, -4391.048, 2110.549],
- targetVector: [0.007, 0.998, 0.065],
- fieldOfView: 45}},
- { duration: 5,
- start: {eye: [-4809.674, -4048.170, 1822.536],
- targetVector: [0.294, 0.956, -0.022],
- fieldOfView: 45},
- end: {eye: [-4535.282, -187.079, 2537.158],
- targetVector: [0.146, 0.971, 0.190],
- fieldOfView: 45}}];
-
-// The artists followed no rules. The assumption by the o3djs libraries
-// is that textures with non-one alpha should be drawn with alpha
-// blending on in the zOrderedDrawPass, otherwise they should be drawn
-// with alpha blending off in the performanceDrawPass but the artists gave
-// us textures that have non-one alpha even though they are meant to be
-// drawn opaque.
-//
-// The next most common way to decide whether to use opaque or
-// transparent blending is a naming convention but the arists
-// didn't do that either.
-//
-// For some cases it doesn't really matter but, (1) drawing with alpha
-// blending on is much slower than off and (2) drawing in the
-// zOrderedDrawPass has to sort which is slow and sometimes things
-// can get sorted wrong if they are too large relative to each other.
-//
-// So, here's a hard coded list to set the materials to the correct
-// drawList :-(
-function makeInfo(list, reflect, refract, main, type, effect) {
- return {
- list: list,
- reflect: reflect,
- refract: refract,
- main: main,
- type: type,
- effect: effect};
-}
-var g_materialLists = {
- // ---------------------------- list reflect refract main adj
- '_6_-_Default': makeInfo(0, true, false, true, 1,
- 'just_color'),
- 'default': makeInfo(1, false, false, true, 1, // palmTreeB
- 'diffuse_bump'),
- 'Folg_BushA_mat': makeInfo(1, true, false, true, 1,
- 'diffuse_bump'),
- 'Folg_BushB_mat': makeInfo(1, true, false, true, 1,
- 'diffuse_bump'),
- 'Folg_BushC_mat': makeInfo(1, true, false, true, 1,
- 'diffuse_bump'),
- 'Folg_coralD_mat': makeInfo(1, false, true, false, 1,
- 'diffuse'),
- 'Folg_coralG_mat': makeInfo(1, false, true, false, 1,
- 'diffuse'),
- 'Folg_coralRockA_mat': makeInfo(0, false, true, false, 2,
- 'diffuse_bump_2textures'),
- 'Folg_coralRockB_mat': makeInfo(0, false, true, false, 2,
- 'diffuse_bump_2textures'),
- 'Folg_FernA_mat': makeInfo(1, true, false, true, 1,
- 'diffuse'),
- 'Folg_hangingFerns_mat': makeInfo(1, true, false, true, 1,
- 'diffuse_bump'),
- 'Folg_largeFernA_mat': makeInfo(1, true, false, true, 1,
- 'diffuse'),
- 'Folg_LeafyPlantA_mat': makeInfo(1, true, false, true, 1,
- 'diffuse_bump'),
- 'Folg_palmTreeA': makeInfo(1, false, false, true, 1,
- 'diffuse'),
- 'Prop_brokenShip_mat': makeInfo(0, true, true, true, 0,
- 'diffuse'),
- 'Prop_pillarA_mat': makeInfo(0, false, false, true, 0,
- 'diffuse_bump_specular'),
- 'prop_tikiMaskA': makeInfo(0, false, false, true, 0,
- 'diffuse_bump_specular'),
- 'Prop_TorchA_mat': makeInfo(0, false, false, true, 0,
- 'diffuse'),
- 'Prop_wallA_mat': makeInfo(0, false, false, true, 0,
- 'diffuse_bump'),
- 'Props_Bridge_mat': makeInfo(0, true, false, true, 0,
- 'diffuse'),
- 'Rock_Dark': makeInfo(0, true, true, true, 2,
- 'diffuse_bump'),
- 'Sand_Dark': makeInfo(0, false, true, false, 0,
- 'diffuse_bump_2textures'),
- 'Standard_2': makeInfo(0, true, true, false, 0, // palmfrawns
- 'diffuse'),
- 'Standard_3': makeInfo(1, false, true, true, 0, // waterfall
- ''),
- 'Rock_Dark_Island': makeInfo(0, true, true, true, 2, // Island
- 'diffuse_bump_blend')};
-
-var g_randSeed = 0;
-var g_randRange = Math.pow(2, 32);
-
-/**
- * Dumps a vector with a name label in a format useful for javascript.
- * @param {string} name The name.
- * @param {!o3d.math.Vector3} v The vector.
- */
-function dumpVector(name, v) {
- o3djs.dump.dump(
- ' ' + name + ': [' +
- v[0].toFixed(3) + ', ' +
- v[1].toFixed(3) + ', ' +
- v[2].toFixed(3) + '],\n');
-}
-
-/**
- * Dump the camera info in a format useful for javascript.
- */
-function dumpCameraInfo() {
- o3djs.dump.dump('{');
- dumpVector('eye', g_camera.eye);
- dumpVector('targetVector', g_camera.targetVector);
- o3djs.dump.dump(' fieldOfView: ' +
- g_math.radToDeg(g_camera.fieldOfView) + '};\n');
-}
-
-// ***************************** Mouse functions *******************************
-
-/**
- * Handler for onmousedown.
- * @param {event} e A mouse event.
- */
-function onMouseDown(e) {
- if (!g_keyCurrentlyDown) {
- g_dragging = true;
- g_dragStartContext = {
- view: o3djs.math.copyMatrix(g_mainViewInfo.drawContext.view),
- projection: o3djs.math.copyMatrix(g_mainViewInfo.drawContext.projection),
- offsetX: g_client.width * 0.5 - e.x,
- offsetY: g_client.height * 0.5 - e.y
- };
- stopAnimatedCamera();
- }
-}
-
-/**
- * Handler for onmousemove.
- * @param {event} e A mouse event.
- */
-function onMouseMove(e) {
- if (g_dragging) {
- // Compute the world ray based on the view we had when we started dragging.
- var worldRay = o3djs.picking.clientPositionToWorldRayEx(
- g_o3dWidth - (e.x + g_dragStartContext.offsetX),
- g_o3dHeight - (e.y + g_dragStartContext.offsetY),
- g_dragStartContext.view,
- g_dragStartContext.projection,
- g_o3dWidth,
- g_o3dHeight);
-
- g_camera.targetVector = g_math.normalize(g_math.subVector(worldRay.near,
- g_camera.eye));
- updateCamera();
- stopAnimatedCamera();
- }
-}
-
-/**
- * Handler for onmouseup.
- * @param {event} e A mouse event.
- */
-function onMouseUp(e) {
- g_dragging = false;
-}
-
-/**
- * Hander for the scroll wheel.
- * @param {Event} e Mouse event.
- */
-function onWheel(e) {
- if (e.deltaY) {
- var target = g_camera.minFieldOfView;
- if (e.deltaY < 0) {
- target = g_camera.maxFieldOfView;
- }
-
- g_camera.fieldOfView = g_math.lerpScalar(target, g_camera.fieldOfView, 0.9);
-
- updateProjection();
- stopAnimatedCamera();
- }
-}
-
-// *************************** Keyboard functions ******************************
-
-/**
- * Tracks key down events.
- * @param {Event} e keyboard event.
- */
-function onKeyDown(e) {
- if (!g_dragging && !g_keyDown[e.keyCode]) {
- ++g_keyCurrentlyDown;
- g_keyDown[e.keyCode] = true;
-
- var keyFunction = g_keyDownKeyCodeFunctions[e.keyCode];
- if (keyFunction) {
- keyFunction(e);
- }
- }
-}
-
-/**
- * Tracks key up events.
- * @param {Event} e keyboard event.
- */
-function onKeyUp(e) {
- if (g_keyDown[e.keyCode]) {
- --g_keyCurrentlyDown;
- g_keyDown[e.keyCode] = false;
-
- var keyFunction = g_keyUpKeyCodeFunctions[e.keyCode];
- if (keyFunction) {
- keyFunction(e);
- }
- }
-}
-
-/**
- * Converts a keyCode or charCode to a keyCode.
- * @param {number|string} code The key code or char code.
- * @return {number} the key code.
- */
-function convertToKeyCode(code) {
- if (typeof(code) == 'string') {
- code = code.charCodeAt(0);
- if (code >= 'a'.charCodeAt(0)) {
- code += 65 - 'a'.charCodeAt(0);
- }
- }
- return code;
-}
-
-/**
- * Registers a key code with a key up function.
- * @param {number|string} keyCode The key code to register a function with.
- * @param {!function(!event): void} keyFunction A function that will be passed
- * the event for the key.
- */
-function registerKeyDownFunction(keyCode, keyFunction) {
- g_keyDownKeyCodeFunctions[convertToKeyCode(keyCode)] = keyFunction;
-}
-
-/**
- * Registers a key code with a key down function.
- * @param {number|string} keyCode The key code to register a function with.
- * @param {!function(!event): void} keyFunction A function that will be passed
- * the event for the key.
- */
-function registerKeyUpFunction(keyCode, keyFunction) {
- g_keyUpKeyCodeFunctions[convertToKeyCode(keyCode)] = keyFunction;
-}
-
-/**
- * Registers a key code with a both a key down and key up function.
- * @param {number|string} keyCode The key code to register a function with.
- * @param {!function(!event): void} keyUpFunction A function that will be passed
- * the event for the key being released.
- * @param {!function(!event): void} keyDownFunction A function that will be
- * passed the event for the key being down..
- */
-function registerKeyUpDownFunction(keyCode, keyUpFunction, keyDownFunction) {
- registerKeyUpFunction(keyCode, keyUpFunction);
- registerKeyUpFunction(keyCode, keyDownFunction);
-}
-
-/**
- * Registers key handlers.
- */
-function registerKeyHandlers() {
- registerKeyDownFunction('0', keySetCamera);
- registerKeyDownFunction('1', keySetCamera);
- registerKeyDownFunction('2', keySetCamera);
- registerKeyDownFunction('3', keySetCamera);
- registerKeyDownFunction('4', keySetCamera);
- registerKeyDownFunction('5', keySetCamera);
- registerKeyDownFunction('6', keySetCamera);
- registerKeyDownFunction('7', keySetCamera);
- registerKeyDownFunction('8', keySetCamera);
- registerKeyDownFunction('9', keySetCamera);
-
- registerKeyDownFunction('h', toggleHelp);
- registerKeyDownFunction('p', togglePropsPanel);
- registerKeyDownFunction('m', toggleMaterialPanel);
- registerKeyDownFunction('e', toggleEffectPanel);
- registerKeyDownFunction('r', toggleRenderTargets);
- registerKeyDownFunction('f', toggleFps);
- registerKeyDownFunction('c', toggleSimpleMaterials);
- registerKeyDownFunction('o', toggleWaterEffect);
- registerKeyDownFunction('q', toggleDemoCamera);
-
- // Comment the line below in to enable dumping camera info.
- // This can be used to generate camera points for the animated
- // camera but is only compatible with Firefox.
- //registerKeyDownFunction('z', dumpCameraInfo);
-}
-
-// **************************** Camera Functions *******************************
-
-/**
- * Updates the camera (the view matrix of the drawContext) with the current
- * camera settings.
- */
-function updateCamera() {
- var target = g_math.addVector(g_camera.eye, g_camera.targetVector);
- var view = g_math.matrix4.lookAt(g_camera.eye,
- target,
- g_camera.up);
- g_viewPositionParam.value = g_camera.eye;
- g_mainViewInfo.drawContext.view = view;
- g_reflectionViewInfo.drawContext.view = view;
- g_refractionViewInfo.drawContext.view = view;
- var cameraMatrix = g_math.inverse4(view);
- g_camera.xAxis = cameraMatrix[0].splice(0, 3);
- g_updateRenderTargets = true;
-}
-
-/**
- * Updates the projection matrix of the drawContext with the current camera
- * settings.
- */
-function updateProjection() {
- // Create a perspective projection matrix.
- g_mainViewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_camera.fieldOfView, g_o3dWidth / g_o3dHeight, g_camera.nearPlane,
- g_camera.farPlane);
-
- g_reflectionViewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_camera.fieldOfView, g_o3dWidth / g_o3dHeight,
- g_camera.nearPlane, g_camera.farPlane);
-
- g_refractionViewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_camera.fieldOfView, g_o3dWidth / g_o3dHeight,
- g_camera.nearPlane, g_camera.farPlane);
-
- g_hudViewInfo.drawContext.projection = g_math.matrix4.orthographic(
- 0 + 0.5,
- g_o3dWidth + 0.5,
- g_o3dHeight + 0.5,
- 0 + 0.5,
- 0.001,
- 1000);
- g_updateRenderTargets = true;
-}
-
-/**
- * Update the fader plane for the current client area size.
- */
-function updateFaderPlane() {
- // Scale fader plane to cover screen.
- // If we made a custom shader for this this wouldn't be needed.
- g_faderTransform.identity();
- g_faderTransform.translate(0, 0, -10);
- g_faderTransform.scale(g_client.width, g_client.height, 1);
-}
-
-/**
- * Sets the camera to a preset.
- * @param {number} cameraIndex Index of camera preset.
- */
-function setCamera(cameraIndex) {
- var cameraInfo = g_cameraInfos[cameraIndex];
- // pull out camera info from view matrix.
- var cameraMatrix = g_math.inverse4(cameraInfo.view);
- g_camera.eye = cameraMatrix[3].splice(0, 3);
- g_camera.targetVector = g_math.negativeVector(cameraMatrix[2].splice(0, 3));
- //g_camera.fieldOfView = cameraInfo.fieldOfViewRadians;
- g_camera.fieldOfView = o3djs.math.degToRad(45);
-
- updateCamera();
- updateProjection();
- stopAnimatedCamera();
-}
-
-/**
- * Moves the camera in its local X axis.
- * @param {number} direction Position or negative amount to move.
- */
-function moveCameraLeftRight(direction) {
- direction *= g_cameraMoveSpeedMultiplier;
- g_camera.eye = g_math.addVector(
- g_camera.eye,
- g_math.mulVectorScalar(g_camera.xAxis, direction));
- updateCamera();
- stopAnimatedCamera();
-}
-
-/**
- * Moves the camera in its local Z axis.
- * @param {number} direction Position or negative amount to move.
- */
-function moveCameraForwardBack(direction) {
- direction *= g_cameraMoveSpeedMultiplier;
- g_camera.eye = g_math.addVector(
- g_camera.eye,
- g_math.mulVectorScalar(g_camera.targetVector, direction));
- updateCamera();
- stopAnimatedCamera();
-}
-
-// ************************ Effect Editor Functions ****************************
-
-/**
- * Starts editing an effect.
- * @param {number} effectId The clientId of the effect.
- */
-function editEffect(effectId) {
- if (g_currentEditEffect) {
- // Save the current edit.
- // TODO: would it be better to have a textarea per effect and
- // hide / unhide them?
- g_editableEffectsSource[g_currentEditEffect.clientId] =
- g_effectTextAreaElement.value;
- }
-
- var effect = g_client.getObjectById(effectId);
- g_effectTextAreaElement.value = g_editableEffectsSource[effectId];
-
- g_currentEditEffect = effect;
-}
-
-/**
- * Edits an effect from the value on an option element
- */
-function editEffectFromElement() {
- var element = o3djs.util.getElementById('effectselect');
- editEffect(parseInt(element.value));
-}
-
-/**
- * Compiles the current effect.
- */
-function compileEffect() {
- if (g_currentEditEffect) {
- var source = g_effectTextAreaElement.value;
-
- // Turn off the default error callback so we can get the error ourselves.
- g_client.clearErrorCallback();
- g_client.clearLastError();
- g_compileEffect.loadFromFXString(source);
- var error = g_client.lastError;
- o3djs.base.setErrorHandler(g_client);
- if (error) {
- alert(error);
- } else {
- g_currentEditEffect.loadFromFXString(source);
- // TODO: call createUniformParameters for all materials
- // using this effect then call setupMaterialEditor so it will
- // display new parameters.
-
- // Tell the render targets to update.
- g_updateRenderTargets = true;
- }
- }
-}
-
-/**
- * Setup effect editor.
- */
-function setupEffectEditor() {
- // create an effect for testing.
- g_compileEffect = g_mainPack.createObject('Effect');
-
- var compileButton = o3djs.util.getElementById('compileButton');
- compileButton.onclick = compileEffect;
-
- // create pseudo tabs.
- // TODO: Make it look prettier.
- var html = '<select id="effectselect">';
- for (var ii = 0; ii < g_editableEffects.length; ++ii) {
- var effect = g_editableEffects[ii];
- g_editableEffectsSource[effect.clientId] = effect.source;
- html += '' +
- '<option value="' + effect.clientId + '">' + effect.name + '</option>';
- }
- g_effectTabsElement.innerHTML = html + '</select>';
- var element = o3djs.util.getElementById('effectselect');
- element.onchange = editEffectFromElement;
- element.onblur = editEffectFromElement;
-
- // Setup the first effect.
- editEffect(g_editableEffects[0].clientId);
-}
-
-// ************************* Prop Editor Functions *****************************
-
-/**
- * Setups the prop editor.
- */
-function setupPropEditor() {
- var propPrefixes = {watersurface: true};
- var transforms = g_scenePack.getObjectsByClassName('o3d.Transform');
- for (var tt = 0; tt < transforms.length; ++tt) {
- var transform = transforms[tt];
- if (transform.shapes.length > 0) {
- var name = transform.name;
- //if (!isNaN(name.substring(name.length -1))) {
- // var prefix = name.replace(/\d*$/, '');
- // if (prefix.length > 0) {
- // propPrefixes[prefix] = true;
- // }
- //}
- propPrefixes[name] = true;
- }
- }
-
- var html = '<table>';
- var count = 0;
- for (var prefix in propPrefixes) {
- html += '' +
- '<tr class="' + ((count % 2 == 0) ? 'even' : 'odd') + '"><td>' +
- '<input id="prop_' + prefix + '" ' +
- 'type="checkbox" CHECKED />' +
- prefix +
- '</td></tr>';
- ++count;
- }
- g_propPanelElement.innerHTML = html + '</table>';
- for (var prefix in propPrefixes) {
- var input = o3djs.util.getElementById('prop_' + prefix);
- input.onclick = o3djs.util.curry(toggleProp, prefix);
- }
-}
-
-/**
- * Toggles props.
- * Goes through all transforms in the client and if their name starts with
- * prefix sets their visibility to true or false.
- * @param {string} prefix Prefix of props to toggle.
- */
-function toggleProp(prefix) {
- var element = o3djs.util.getElementById('prop_' + prefix);
- var visible = element.checked;
- // We should probably cache all the transforms since this is an expensive
- // operation.
- var transforms = g_client.getObjectsByClassName('o3d.Transform');
- for (var tt = 0; tt < transforms.length; ++tt) {
- var transform = transforms[tt];
- if (transform.name.substring(0, prefix.length) === prefix) {
- transform.visible = visible;
- }
- }
- // Tell the render targets to update.
- g_updateRenderTargets = true;
-}
-
-// *********************** Material Editor Functions ***************************
-
-/**
- * Escapes a string, changing < to &lt;
- * @param {string} str to escape.
- * @return {string} escaped string.
- */
-function escapeHTML(str) {
- return str.replace(/</g, '&lt;');
-}
-
-/**
- * Gets a param value as a string
- * @param {!o3d.Param} param Param to get value from.
- * @return {string} value of param as a string.
- */
-function getParamAsString(param) {
- if (param.isAClassName('o3d.ParamFloat')) {
- return param.value.toFixed(5);
- } else if (param.isAClassName('o3d.ParamFloat4')) {
- var value = param.value;
- for (var ii = 0; ii < value.length; ++ii) {
- value[ii] = value[ii].toFixed(2);
- }
- return value.toString();
- } else {
- return '--na--';
- }
-}
-
-/**
- * Reads the current value of the input and sets the matching param to that
- * value.
- * @param {number} paramId Id of param and input.
- */
-function updateParam(paramId) {
- var param = g_client.getObjectById(paramId);
- var element = o3djs.util.getElementById('param_' + paramId);
- var value = element.value;
- var error = false;
- var v;
- if (param.isAClassName('o3d.ParamFloat')) {
- if (isNaN(value)) {
- error = true;
- }
- v = parseFloat(value);
- } else if (param.isAClassName('o3d.ParamFloat4')) {
- var values = value.split(/ *, *| +/);
- if (values.length != 4) {
- error = true;
- } else {
- v = [];
- for (var ii = 0; ii < values.length; ++ii) {
- if (isNaN(values[ii])) {
- error = true;
- break;
- }
- v[ii] = parseFloat(values[ii]);
- }
- }
- }
-
- if (!error) {
- param.value = v;
- // Tell the render targets to update.
- g_updateRenderTargets = true;
- }
-
- element.style.backgroundColor = error ? '#fcc' : '';
-}
-
-/**
- * Creates the html to edit the given param object.
- * @param {!o3d.ParamObject} paramObject The param object to create html for.
- * @param {string} rowClass name of class for row.
- * @return {string} the generated HTML.
- */
-function createHTMLForParamObject(paramObject, rowClass) {
- var html = '' +
- '<tr class="' + rowClass + '">' +
- '<td class="name" colspan="2">' + escapeHTML(paramObject.name) + '</td>' +
- '</tr>';
- var params = paramObject.params;
- for (var pp = 0; pp < params.length; ++pp) {
- var param = params[pp];
- // Skip builtins and ones with an input connection.
- if (param.name.substring(0, 4) !== 'o3d.' &&
- param.inputConnection == null &&
- (param.isAClassName('o3d.ParamFloat') ||
- param.isAClassName('o3d.ParamFloat4'))) {
- html += '' +
- '<tr>' +
- '<td class="field">' +
- '<label>' + escapeHTML(param.name) + '</label>' +
- '</td>' +
- '<td class="value">' +
- '<input type="text" id="param_' + param.clientId + '" ' +
- 'value="' + getParamAsString(param) + '"></input>' +
- '</td>' +
- '</tr>';
- }
- }
- return html;
-}
-
-/**
- * Sets the onblur and onchange handlers in the html for a given param object.
- * @param {!o3d.ParamObject} paramObject The param object to create html for.
- */
-function setHTMLHandlersForParamObject(paramObject) {
- var params = paramObject.params;
- for (var pp = 0; pp < params.length; ++pp) {
- var param = params[pp];
- // Skip builtins and ones with an input connection.
- if (param.name.substring(0, 4) !== 'o3d.' &&
- param.inputConnection == null &&
- (param.isAClassName('o3d.ParamFloat') ||
- param.isAClassName('o3d.ParamFloat4'))) {
- var input = o3djs.util.getElementById('param_' + param.clientId);
- input.onblur = o3djs.util.curry(updateParam, param.clientId);
- input.onchange = o3djs.util.curry(updateParam, param.clientId);
- }
- }
-}
-
-/**
- * Sets up html with event handers to edit the material parameters.
- */
-function setupMaterialEditor() {
- var html = '<table>';
- var materials = g_scenePack.getObjectsByClassName('o3d.Material');
- var count = 0;
- materials.unshift(g_globalParams);
- materials.unshift(g_waterMaterial);
- materials.unshift(g_underwaterMaterials[0]);
- materials.unshift(g_underwaterMaterials[1]);
- for (var mm = 0; mm < materials.length; ++mm) {
- var material = materials[mm];
- html += createHTMLForParamObject(material, count % 2 == 0 ? 'even' : 'odd');
- ++count;
- }
- g_materialPanelElement.innerHTML = html + '</table>';
-
- for (var mm = 0; mm < materials.length; ++mm) {
- var material = materials[mm];
- setHTMLHandlersForParamObject(material)
- }
-}
-
-// ************************* Specific Key Handlers *****************************
-
-function setupWaterHeavyUpdateOnlyOnViewChange() {
- g_waterMaterial.effect = g_waterEffect;
-}
-
-function setupWaterHeavyUpdateAlways() {
- g_waterMaterial.effect = g_waterEffect;
-}
-
-function setupWaterJustSkyAndColor() {
- g_waterMaterial.effect = g_waterColorAndSkyEffect;
-}
-
-function setupWaterStyle2() {
- g_waterMaterial.effect = g_waterStyle2Effect;
-}
-
-/**
- * Toggles the water effect.
- * @param {Event} e Event for key that was pressed.
- */
-function toggleWaterEffect(e) {
- ++g_waterMode;
- if (g_waterMode == 4) {
- g_waterMode = 0;
- }
-
- switch (g_waterMode) {
- case 0:
- setupWaterHeavyUpdateOnlyOnViewChange();
- break;
- case 1:
- setupWaterHeavyUpdateAlways();
- break;
- case 2:
- setupWaterJustSkyAndColor();
- break;
- case 3:
- setupWaterStyle2();
- break;
- }
-}
-
-/**
- * Toggles the animted camera.
- * @param {Event} e Event for key that was pressed.
- */
-function toggleDemoCamera(e) {
- g_runDemo = !g_runDemo;
- if (g_runDemo) {
- g_animateCamera = true;
- } else {
- stopAnimatedCamera();
- }
-}
-
-/**
- * Restores and original sampler on params of a certain name.
- * @param {!o3d.ParamObject} paramObject Object to restore samplers on.
- * @param {string} samplerName Name of sampler parameter to restore.
- */
-function restoreOriginalSampler(paramObject, samplerName) {
- var param = paramObject.getParam(samplerName);
- if (param) {
- param.value = g_originalSampler[param.clientId];
- }
-}
-
-/**
- * Replaces samplers on params of a certain name with a white sampler.
- * @param {!o3d.ParamObject} paramObject Object to replace samplers on.
- * @param {string} samplerName Name of sampler parameter to replace samplers on.
- */
-function replaceSamplerWithWhiteSampler(paramObject, samplerName) {
- var param = paramObject.getParam(samplerName);
- if (param) {
- g_originalSampler[param.clientId] = param.value;
- param.value = g_whiteSampler;
- }
-}
-
-/**
- * Toggles the materials to simple effects.
- * @param {Event} e Event for key that was pressed.
- */
-function toggleSimpleMaterials(e) {
- g_updateRenderTargets = true;
-
- var materials = g_scenePack.getObjectsByClassName('o3d.Material');
- materials.unshift(g_waterMaterial);
- materials.unshift(g_underwaterMaterials[0]);
- materials.unshift(g_underwaterMaterials[1]);
-
- ++g_showingSimpleMaterialsMode;
- g_showingSimpleMaterialsMode = g_showingSimpleMaterialsMode % 4;
-
- switch (g_showingSimpleMaterialsMode) {
- case 1: {
- g_originalLightColor = g_lightColorParam.value;
- g_lightColorParam.value = [1, 1, 1, 1];
- var drawElements = g_scenePack.getObjectsByClassName('o3d.DrawElement');
- for (var ii = 0; ii < drawElements.length; ++ii) {
- replaceSamplerWithWhiteSampler(drawElements[ii], 'diffuseSampler');
- }
- break;
- }
- case 2: {
- g_lightColorParam.value = g_originalLightColor;
- var drawElements = g_scenePack.getObjectsByClassName('o3d.DrawElement');
- for (var ii = 0; ii < drawElements.length; ++ii) {
- restoreOriginalSampler(drawElements[ii], 'diffuseSampler');
- }
- break;
- }
- }
-
- for (var mm = 0; mm < materials.length; ++mm) {
- var material = materials[mm];
- switch (g_showingSimpleMaterialsMode) {
- case 0: {
- material.effect = g_materialSwapTable[material.clientId];
- break;
- }
- case 1: {
- replaceSamplerWithWhiteSampler(material, 'diffuseSampler');
- replaceSamplerWithWhiteSampler(material, 'diffuse2Sampler');
- break;
- }
- case 2: {
- restoreOriginalSampler(material, 'diffuseSampler');
- restoreOriginalSampler(material, 'diffuse2Sampler');
-
- var effect = material.effect;
- g_materialSwapTable[material.clientId] = effect;
- if (!g_simpleEffects[effect.clientId]) {
- // eat some random number to get pleasing colors.
- g_math.pseudoRandom();
- g_math.pseudoRandom();
- var newEffect = g_mainPack.createObject('Effect');
- newEffect.loadFromFXString(g_shaders.simpleshader);
- newEffect.createUniformParameters(newEffect);
- newEffect.getParam('simpleColor').value = [
- g_math.pseudoRandom(),
- g_math.pseudoRandom(),
- g_math.pseudoRandom(),
- 1];
- g_simpleEffects[effect.clientId] = newEffect;
- }
- material.effect = g_simpleEffects[effect.clientId];
- break;
- }
- case 3: {
- material.effect = g_imageEffect;
- break;
- }
- }
- }
-}
-
-/**
- * Toggles the render target display.
- * @param {Event} e Event for key that was pressed.
- */
-function toggleRenderTargets(e) {
- g_renderTargetDisplayRoot.visible = !g_renderTargetDisplayRoot.visible;
-}
-
-/**
- * Toggles the fps display.
- * @param {Event} e Event for key that was pressed.
- */
-function toggleFps(e) {
- g_fpsVisible = !g_fpsVisible;
- g_fpsManager.setVisible(g_fpsVisible);
-}
-
-function togglePropsPanel(e) {
- if (g_propPanelElement.style.display === '') {
- g_propPanelElement.style.display = 'none';
- g_sceneElement.style.width = '100%';
- } else {
- g_materialPanelElement.style.display = 'none';
- g_propPanelElement.style.display = '';
- g_sceneElement.style.width = '80%';
- }
-}
-
-/**
- * Toggles the material panel.
- * @param {Event} e Event for key that was pressed.
- */
-function toggleMaterialPanel(e) {
- if (g_materialPanelElement.style.display === '') {
- g_materialPanelElement.style.display = 'none';
- g_sceneElement.style.width = '100%';
- } else {
- g_propPanelElement.style.display = 'none';
- g_materialPanelElement.style.display = '';
- g_sceneElement.style.width = '80%';
- }
-}
-
-/**
- * Toggles the effect panel.
- * @param {Event} e Event for key that was pressed.
- */
-function toggleEffectPanel(e) {
- if (g_effectPanelElement.style.display === '') {
- g_effectPanelElement.style.display = 'none';
- g_upperPanelElement.style.height = '100%';
- } else {
- g_effectPanelElement.style.display = '';
- g_upperPanelElement.style.height = '70%';
- }
-}
-
-/**
- * Sets the camera to a camera preset from a key press.
- * @param {Event} e Event for key that was pressed. Expects 0-9.
- */
-function keySetCamera(e) {
- var index = e.keyCode - 49;
- if (index < 0) {
- index = 9;
- }
- var cameraInfo = g_cameraInfos[index];
- if (cameraInfo) {
- setCamera(index);
- }
-}
-
-// ***************************** Scene Functions *******************************
-
-/**
- * Sets the position of the sun, updating shader parameters.
- * @param {!o3djs.math.Vector3} position The position of the sun.
- */
-function setSunPosition(position) {
- g_lightPositionParam.value = position;
- g_lightDirectionParam.value = g_math.negativeVector(
- g_math.normalize(position));
- g_lightDirectionParam.value = g_math.normalize(position);
-}
-
-// ********************************** Misc *************************************
-
-/**
- * Sets a param if it exists.
- * @param {!o3d.ParamObject} paramObject The object that has the param.
- * @param {string} paramName name of param.
- * @param {*} value the value for the param.
- */
-function setParam(paramObject, paramName, value) {
- var param = paramObject.getParam(paramName);
- if (param) {
- param.value = value;
- }
-}
-
-/**
- * Binds a param if it exists.
- * @param {!o3d.ParamObject} paramObject The object that has the param.
- * @param {string} paramName name of param.
- * @param {!o3d.Param} sourceParam The param to bind to.
- */
-function bindParam(paramObject, paramName, sourceParam) {
- var param = paramObject.getParam(paramName);
- if (param) {
- param.bind(sourceParam);
- }
-}
-
-/**
- * Prints out a transform tree.
- * @param {!o3d.Transform} transform transform to print.
- * @param {string} prefix Prefix to print.
- */
-function dumpTransforms(transform, prefix) {
- var materialName = '';
- var shapes = transform.shapes;
- if (shapes.length > 0) {
- materialName = ' (' + shapes[0].elements[0].material.name + ')';
- }
- o3djs.dump.dump(prefix + transform.name + materialName + '\n');
- var children = transform.children;
- for (var cc = 0; cc < children.length; ++cc) {
- dumpTransforms(children[cc], prefix + ' ');
- }
-}
-
-/**
- * Adds transforms at each level of the scene to group things by where they
- * need to be rendered, refraction, main, both.
- * @param {!o3d.Transform} transform Transform to scan.
- */
-function getSpeedTransforms(transform) {
- // 0 : neither, 1 : main, 2 : reflect, 3 : both
- var speedTransforms = [];
- var children = transform.children;
- for (var cc = 0; cc < children.length; ++cc) {
- var child = children[cc];
- var check = child;
-
- // If a child has a single child of the same but with the suffix
- // '_PIVOT' use that as the check node.
- var checkChildren = child.children;
- if (checkChildren.length == 1 &&
- checkChildren[0].name == child.name + '_PIVOT') {
- check = checkChildren[0];
- }
- // If check has a shape that has a primitive that uses one of the
- // materials on the list then attach it to a speed transform.
- var grouped = false;
- var shapes = check.shapes;
- if (shapes.length > 0) {
- // gets assume 1 shape, 1 element
- var material = shapes[0].elements[0].material;
- var materialInfo = g_materialLists[material.name];
- if (materialInfo) {
- grouped = true;
- var index = (materialInfo.main ? 1 : 0) +
- (materialInfo.reflect ? 2 : 0);
- var speedTransform = speedTransforms[index];
- if (!speedTransform) {
- speedTransform = g_mainPack.createObject('Transform');
- speedTransform.name = 'speed_' + index;
- speedTransform.parent = transform;
- speedTransforms[index] = speedTransform;
- }
- child.parent = speedTransform;
- }
- }
-
- if (!grouped) {
- getSpeedTransforms(child);
- }
- }
-
- // Now add speed transforms to global list.
- for (var ii = 0; ii < 4; ++ii) {
- if (speedTransforms[ii]) {
- g_speedTransforms[ii].push(speedTransforms[ii]);
- }
- }
-}
-
-/**
- * Gets a texture from g_scenePack.
- * @param {string} textureName Name of texture.
- * @return {!o3d.Texture} The requested texture.
- */
-function getTexture(textureName) {
- // I'm searching by URI because the old conditioner sadly renamed all the
- // textures making it next to impossible to find things :-(
- if (!g_sceneTexturesByURI) {
- g_sceneTexturesByURI = { };
- var textures = g_scenePack.getObjectsByClassName('o3d.Texture');
- for (var tt = 0; tt < textures.length; ++tt) {
- var texture = textures[tt];
- var uri = texture.getParam('uri').value;
- g_sceneTexturesByURI[uri] = texture;
- }
- }
-
- return g_sceneTexturesByURI['images/' + textureName];
-}
-
-/**
- * Adds a texture to a material.
- * @param {!o3d.Material} material Material to add texture to.
- * @param {string} samplerName Name of sampler parameter to attach texture to.
- * @param {string} textureName Name of texture.
- */
-function addTexture(material, samplerName, textureName) {
- var param = material.createParam(samplerName, 'ParamSampler');
- var sampler = g_scenePack.createObject('Sampler');
- param.value = sampler;
- sampler.texture = getTexture(textureName);
-}
-
-/**
- * Sets up the materials in the scene.
- */
-function setupSceneMaterials() {
- var drawLists = [g_mainViewInfo.performanceDrawList,
- g_mainViewInfo.zOrderedDrawList];
-
- var adjust = [
- {shininess: 50, specular: [0.5, 0.5, 0.5, 1]},
- {shininess: 100, specular: [0.3, 0.5, 0.3, 1]},
- {shininess: 80, specular: [0.3, 0.3, 0.3, 1]}];
-
- // Setup the materials. Because Collada can't really handle
- // the materials needed we pretty much have to do this manaually. It would
- // have been good to make a rule for it but I have no time.
- for (var name in g_materialLists) {
- var info = g_materialLists[name];
- var materials = g_scenePack.getObjects(name, 'o3d.Material');
- for (var mm = 0; mm < materials.length; ++mm) {
- var material = materials[mm];
- if (info.effect) {
- var effect = g_sceneEffects[info.effect];
- if (!effect) {
- effect = g_scenePack.createObject('Effect');
- effect.name = info.effect;
- var fxString = g_shaders[info.effect];
- effect.loadFromFXString(fxString);
- g_sceneEffects[info.effect] = effect;
- g_editableEffects.push(effect);
- }
- material.effect = effect;
- material.createParam('lightWorldPos', 'ParamFloat3');
- material.createParam('lightColor', 'ParamFloat4');
- material.createParam('clipHeight', 'ParamFloat');
-
- // special handling for island and seafloor materials.
- if (info.effect == 'diffuse_bump_blend') {
- addTexture(material, 'diffuse2Sampler', 'image1.dds');
- }
- }
- material.drawList = drawLists[info.list];
-
- // Manually connect all the materials' lightWorldPos params or a global
- // light param.
- bindParam(material, 'lightWorldPos', g_lightPositionParam);
- bindParam(material, 'lightColor', g_lightColorParam);
- bindParam(material, 'clipHeight', g_clipHeightParam);
- setParam(material, 'ambient', [0.2, 0.2, 0.2, 1]);
-
- var type = info.type;
- setParam(material, 'shininess', adjust[type].shininess);
- setParam(material, 'specular', adjust[type].specular);
- }
- }
-}
-
-/**
- * Loads the proxy.
- */
-function loadProxy() {
- function callback(pack, parent, exception) {
- g_loadInfo = null;
- if (exception) {
- showError(exception);
- } else {
- loadMainScene();
-
- o3djs.pack.preparePack(pack, g_mainViewInfo);
-
- var material = pack.getObjectsByClassName('o3d.Material')[0];
- var effect = g_mainPack.createObject('Effect');
- effect.loadFromFXString(g_shaders.proxy);
- effect.createUniformParameters(material);
- setParam(material, 'lightWorldPos', [0, -100000, 200000]);
- setParam(material, 'ambient', [0, 0, 0, 0]);
- setParam(material, 'diffuse', [0.7, 0.7, 0.7, 0.5]);
- setParam(material, 'specular', [0, 0, 0, 0]);
- bindParam(material, 'offset', g_proxyOffsetParam);
- material.effect = effect;
- material.drawList = g_mainViewInfo.zOrderedDrawList;
- var state = pack.createObject('State');
- material.state = state;
- state.getStateParam('AlphaReference').value = 0.0;
- state.getStateParam('CullMode').value = g_o3d.State.CULL_CCW;
- var material2 = pack.createObject('Material');
- effect.createUniformParameters(material2);
- material2.copyParams(material);
- bindParam(material2, 'offset', g_proxyOffsetParam);
- material2.effect = effect;
- material2.drawList = g_mainViewInfo.zOrderedDrawList;
-
- state = pack.createObject('State');
- material2.state = state;
- state.getStateParam('AlphaReference').value = 0.0;
- state.getStateParam('CullMode').value = g_o3d.State.CULL_CW;
-
- parent.createDrawElements(pack, material2);
- }
- }
-
- g_proxyPack = g_client.createPack();
- g_proxyRoot = g_proxyPack.createObject('Transform');
- g_proxyRoot.parent = g_baseRoot;
-
- try {
- var url = o3djs.util.getAbsoluteURI('assets/beach-low-poly.o3dtgz');
- g_loadInfo = o3djs.scene.loadScene(g_client, g_proxyPack, g_proxyRoot,
- url, callback, {opt_async: false});
- } catch (e) {
- showError(e);
- }
-}
-
-/**
- * Loads the main scene.
- */
-function loadMainScene() {
- function callback(pack, parent, exception) {
- g_loadInfo = null;
- if (exception) {
- showError(exception);
- } else {
- g_proxyRoot.visible = false;
-
- setupWaterfall();
-
- // Generate draw elements and setup material draw lists.
- parent.createDrawElements(pack, null);
-
- setupSceneMaterials();
-
- // Turn off culling since we can see the entire world checking culling
- // is a waste of CPU time.
- var elements = g_scenePack.getObjectsByClassName('o3d.Element');
- for (var ee = 0; ee < elements.length; ++ee) {
- elements[ee].cull = false;
- o3djs.element.setBoundingBoxAndZSortPoint(elements[ee]);
- }
-
- // Add missing streams to terrain.
- var terrainNames = [
- 'terrainSpireA_002',
- 'terrainSpireA_003',
- 'terrainLargeRock',
- 'terrainSpireA_001'];
- var semantics = [
- g_o3d.Stream.TEXCOORD,
- g_o3d.Stream.BINORMAL,
- g_o3d.Stream.TANGENT];
- for (var tt = 0; tt < terrainNames.length; ++tt) {
- var streamBank = g_scenePack.getObjects(terrainNames[tt],
- 'o3d.StreamBank')[0];
- for (var ii = 0; ii < semantics.length; ++ii) {
- var stream = streamBank.getVertexStream(semantics[ii], 0);
- streamBank.setVertexStream(semantics[ii], 1, stream.field, 0)
- }
- }
-
- g_cameraInfos = o3djs.camera.getCameraInfos(parent,
- g_o3dWidth,
- g_o3dHeight);
- setCamera(1);
- setupUnderwater();
-
- getSpeedTransforms(g_sceneRoot);
-
- //o3djs.dump.dump("--------\n");
- //dumpTransforms(g_sceneRoot, '');
-
- setupMaterialEditor();
- setupEffectEditor();
- setupPropEditor();
-
- registerKeyHandlers();
-
- if (false) {
- o3djs.dump.dump('---dump g_scenePack shapes---\n');
- var shapes = g_scenePack.getObjectsByClassName('o3d.Shape');
- for (var t = 0; t < shapes.length; t++) {
- var shape = shapes[t];
- o3djs.dump.dump('shape ' + t + ': ' + shape.name + '\n');
- //o3djs.dump.dumpShape(shape);
- }
- }
-
- if (false) {
- o3djs.dump.dump('---dump g_scenePack materials---\n');
- var materials = g_scenePack.getObjectsByClassName('o3d.Material');
- for (var t = 0; t < materials.length; t++) {
- var material = materials[t];
- o3djs.dump.dump (
- ' ' + t + ' : ' + material.className +
- ' : "' + material.name + '"\n');
- var params = material.params;
- for (var p = 0; p < params.length; ++p) {
- var param = params[p];
- if (param.className == 'o3d.ParamSampler') {
- o3djs.dump.dump(' ' + p + ': ' +
- param.value.texture.name + '\n');
- }
- }
- //o3djs.dump.dumpParams(materials[t], ' ');
- }
- }
-
- if (false) {
- o3djs.dump.dump('---dump g_scenePack textures---\n');
- var textures = g_scenePack.getObjectsByClassName('o3d.Texture');
- for (var t = 0; t < textures.length; t++) {
- o3djs.dump.dump(t + ': ');
- o3djs.dump.dumpTexture(textures[t]);
- }
-
- o3djs.dump.dump('---dump g_scenePack effects---\n');
- var effects = g_scenePack.getObjectsByClassName('o3d.Effect');
- for (var t = 0; t < effects.length; t++) {
- o3djs.dump.dump (' ' + t + ' : ' + effects[t].className +
- ' : "' + effects[t].name + '"\n');
- o3djs.dump.dumpParams(effects[t], ' ');
- }
- }
- }
- g_perfMon = o3djs.performance.createPerformanceMonitor(
- 25, 35, increaseRenderTargetResolution, decreaseRenderTargetResolution);
- }
-
- try {
- // We need to make a subloader because we can't make the particles
- // until both the scene and the particle textures are loaded.
- g_loadInfo = g_loader.loadInfo;
- g_particleLoader = g_loader.createLoader(setupParticles);
- g_particleLoader.loadTexture(
- g_mainPack,
- o3djs.util.getAbsoluteURI('assets/pe_fire.jpg'),
- function(texture, success) {
- g_torchTexture = texture;
- });
- g_particleLoader.loadTexture(
- g_mainPack,
- o3djs.util.getAbsoluteURI('assets/pe_mist.png'),
- function(texture, success) {
- g_mistTexture = texture;
- });
-
- var url = o3djs.util.getAbsoluteURI('assets/beachdemo.o3dtgz');
- g_particleLoader.loadScene(
- g_client, g_scenePack, g_sceneRoot, url, callback, {opt_async: false});
- g_particleLoader.finish()
- g_loader.finish();
- } catch (e) {
- showError(e);
- }
-}
-
-/**
- * Records the client's size if it's changed.
- */
-function setClientSize() {
- var newWidth = parseInt(g_client.width);
- var newHeight = parseInt(g_client.height);
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- updateProjection();
- g_fpsManager.resize(g_o3dWidth, g_o3dHeight);
- g_fpsManager.setPosition(g_o3dWidth - 80, 10);
- updateFaderPlane();
- }
-}
-
-/**
- * Moves the camera based on key state.
- */
-function handleCameraKeys() {
- var moveX = 0;
- var moveY = 0;
-
- if (g_keyDown[37] || g_keyDown[65]) {
- moveX = -1;
- }
- if (g_keyDown[39] || g_keyDown[68]) {
- moveX = 1;
- }
- if (g_keyDown[38] || g_keyDown[87]) {
- moveY = 1;
- }
- if (g_keyDown[40] || g_keyDown[83]) {
- moveY = -1;
- }
-
- if (moveX) {
- moveCameraLeftRight(moveX);
- stopAnimatedCamera();
- }
-
- if (moveY) {
- moveCameraForwardBack(moveY);
- stopAnimatedCamera();
- }
-}
-
-/**
- * Sets the speed transforms visible or invisible to turn on/off whole groups of
- * shapes not needed for certain rendering.
- * @param {boolean} main Turn on stuff marked for main.
- * @param {boolean} reflect Turn on stuff marked for reflect.
- * @param {boolean} force Force visible to true.
- */
-function setSpeedTransforms(main, reflect, force) {
- var mask = (main ? 1 : 0) + (reflect ? 2 : 0);
- for (var ii = 0; ii < 4; ++ii) {
- var visible = ((ii & mask) != 0) || force;
- var speedTransforms = g_speedTransforms[ii];
- for (var jj = 0; jj < speedTransforms.length; ++jj) {
- speedTransforms[jj].visible = visible;
- }
- }
-}
-
-/**
- * Eases in a number.
- * @param {number} value Value to ease in. Must be 0 to 1.
- * @return {number} Ease in version of value.
- */
-function easeIn(value) {
- return 1 - Math.cos(value * Math.PI * 0.5);
-}
-
-/**
- * Eases out a number.
- * @param {number} value Value to ease out. Must be 0 to 1.
- * @return {number} Ease out version of value.
- */
-function easeOut(value) {
- return Math.sin(value * Math.PI * 0.5);
-}
-
-/**
- * Ease in and out a number.
- * @param {number} value Value to ease in out. Must be 0 to 1.
- * @return {number} Ease in out version of value.
- */
-function easeInOut(value) {
- if (value < 0.5) {
- return easeIn(value * 2) * 0.5;
- } else {
- return easeOut(value * 2 - 1) * 0.5 + 0.5;
- }
-}
-
-/**
- * Stops the animated camera.
- */
-function stopAnimatedCamera() {
- g_animateCamera = false;
- g_demoTimer = 30;
- g_cameraTimer = 0;
- g_faderTransform.visible = false;
-}
-
-/**
- * Animates the camera.
- * @param {number} elapsedTime Elapsed time in seconds.
- */
-function animateCamera(elapsedTime) {
- if (g_animateCamera && window.g_finished) {
- g_cameraTimer -= elapsedTime;
-
- if (g_cameraTimer <= 0) {
- ++g_cameraPointIndex;
- if (g_cameraPointIndex >= g_cameraPoints.length) {
- g_cameraPointIndex = 0;
- }
- g_cameraPoint = g_cameraPoints[g_cameraPointIndex];
- g_cameraDuration = g_cameraPoint.duration * 3;
- g_cameraTimer = g_cameraDuration;
- }
-
- var lerp = 1;
- if (g_cameraTimer > 1) {
- var moveDuration = g_cameraDuration - 1;
- var timer = g_cameraTimer - 1;
- lerp = easeInOut(1 - timer / moveDuration);
-
- if (g_cameraTimer > g_cameraDuration - 1) {
- var fade = g_cameraTimer - (g_cameraDuration - 1);
- g_faderTransform.visible = true;
- g_faderColorParam.value = [0, 0, 0, fade];
- } else {
- g_faderTransform.visible = false;
- }
- } else {
- g_faderTransform.visible = true;
- g_faderColorParam.value = [0, 0, 0, 1 - g_cameraTimer];
- }
-
- g_camera.eye = g_math.lerpVector(g_cameraPoint.start.eye,
- g_cameraPoint.end.eye,
- lerp);
- g_camera.targetVector = g_math.lerpVector(g_cameraPoint.start.targetVector,
- g_cameraPoint.end.targetVector,
- lerp);
- g_camera.fieldOfView = g_math.degToRad(
- g_math.lerpScalar(g_cameraPoint.start.fieldOfView,
- g_cameraPoint.end.fieldOfView,
- lerp));
-
- updateCamera();
- updateProjection();
- } else {
- if (g_runDemo) {
- g_demoTimer -= elapsedTime;
- if (g_demoTimer <= 0) {
- g_animateCamera = true;
- }
- }
- }
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Info about this frame.
- */
-function onRender(renderEvent) {
- // save off the render event so look at it from the debugger.
- g_re = renderEvent;
-
- var elapsedTime = renderEvent.elapsedTime * window.g_timeMult;
- if (g_hudFadeTime > 0) {
- g_hudFadeTime -= elapsedTime;
- if (g_hudFadeTime <= 0) {
- g_hudQuad.transform.visible = false;
- }
- }
-
- // This is for selenium so that the hud is predictable.
- if (g_hudFadeTime > 0 && window.g_timeMult == 0) {
- g_hudFadeTime = 0;
- g_hudQuad.transform.visible = false;
- }
-
- // Normally I'd have used a SecondCounter but so we can run this in
- // selenium I set it up this way to be easy.
- window.g_clock += elapsedTime;
- g_globalClockParam.value = window.g_clock;
-
- if (g_loadInfo) {
- var progressInfo = g_loadInfo.getKnownProgressInfoSoFar();
- g_proxyOffsetParam.value = progressInfo.percent / 100 * PROXY_HEIGHT;
- if (progressInfo.percent != g_downloadPercent) {
- g_downloadPercent = progressInfo.percent;
- setHudText('Loading... ' + progressInfo.percent + '%' +
- ' (' + progressInfo.downloaded +
- ' of ' + progressInfo.totalBytes + progressInfo.suffix + ')');
- }
- }
-
- // This if is for selenium to make the camera predictable.
- if (window.g_timeMult) {
- animateCamera(elapsedTime);
- } else {
- setCamera(1);
- }
-
- handleCameraKeys();
- setClientSize();
- g_fpsManager.update(renderEvent);
-
- if (g_updateRenderTargets || g_waterMode == 1) {
- g_updateRenderTargets = false;
-
- // Render the reflection texture.
- setSpeedTransforms(false, true, false);
- g_clipHeightParam.value = g_reflectionClipHeight;
- g_client.root.identity();
- g_client.root.scale(1, 1, -1); // flip the scene
- g_client.renderTree(g_reflectionSurfaceSet);
-
- // Render the refraction texture.
- setSpeedTransforms(true, true, true);
- g_client.root.identity();
- g_client.root.scale(1, 1, 1 /* 0.75 */); // squish the scene.
- g_client.renderTree(g_refractionSurfaceSet);
- }
-
- // Render the main scene.
- setSpeedTransforms(true, false, false);
- g_clipHeightParam.value = g_mainClipHeight;
- g_client.root.identity();
- g_client.renderTree(g_mainViewInfo.root);
-
- // Render the HUD.
- g_client.renderTree(g_hudViewInfo.root);
-
- // Render the FPS display.
- g_client.renderTree(g_fpsManager.viewInfo.root);
-
- if (g_perfMon) {
- g_perfMon.onRender(renderEvent.elapsedTime);
- }
-}
-
-function onAllLoadingFinished() {
- g_loader = null;
- g_animateCamera = true;
-
- showHint();
-
- window.o3d_prepForSelenium = prepForSelenium;
- window.g_finished = true; // for selenium testing.
-}
-
-// Put the demo in a consistent state.
-function prepForSelenium() {
- // Turn off the perf monitor.
- g_perfMon = null;
-
- // Set the render targets to a fixed size.
- g_renderTargetWidth = 256;
- g_renderTargetHeight = 256;
- setupRenderTargets();
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- // These are here so they are shared by both V8 and the browser.
- window.g_finished = false; // for selenium
- window.g_timeMult = 1;
- window.g_clock = 0;
-
- // Comment out the line below to run the sample in the browser JavaScript
- // engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.util.addScriptUri('');
- o3djs.util.makeClients(initStep2);
-}
-
-function setupRenderTargets() {
- var oldReflectionTexture;
- var oldRefractionTexture;
- var oldDepthSurface;
-
- if (g_reflectionTexture) {
- g_mainPack.removeObject(g_reflectionSurfaceSet.renderSurface);
- g_mainPack.removeObject(g_refractionSurfaceSet.renderSurface);
- g_mainPack.removeObject(g_reflectionTexture);
- g_mainPack.removeObject(g_refractionTexture);
- g_mainPack.removeObject(g_depthSurface);
- } else {
- // First time only.
- g_reflectionSurfaceSet = g_mainPack.createObject('RenderSurfaceSet');
- g_refractionSurfaceSet = g_mainPack.createObject('RenderSurfaceSet');
- }
-
- // Create Render Targets for the reflection and refraction.
- g_reflectionTexture = g_mainPack.createTexture2D(g_renderTargetWidth,
- g_renderTargetHeight,
- g_o3d.Texture.ARGB8, 1,
- true);
- var reflectionSurface = g_reflectionTexture.getRenderSurface(0);
- g_refractionTexture = g_mainPack.createTexture2D(g_renderTargetWidth,
- g_renderTargetHeight,
- g_o3d.Texture.XRGB8, 1,
- true);
- var refractionSurface = g_refractionTexture.getRenderSurface(0);
- g_depthSurface = g_mainPack.createDepthStencilSurface(g_renderTargetWidth,
- g_renderTargetHeight);
-
- // Set up the render graph to generate them.
- g_reflectionSurfaceSet.renderSurface = reflectionSurface;
- g_reflectionSurfaceSet.renderDepthStencilSurface = g_depthSurface;
-
- g_refractionSurfaceSet.renderSurface = refractionSurface;
- g_refractionSurfaceSet.renderDepthStencilSurface = g_depthSurface;
-
- g_updateRenderTargets = true;
-
- if (g_waterMaterial) { // Every time after the first.
- var sampler = g_waterMaterial.getParam('reflectionSampler').value;
- sampler.texture = g_reflectionTexture;
- sampler = g_waterMaterial.getParam('refractionSampler').value;
- sampler.texture = g_refractionTexture;
- g_reflectionImage.sampler.texture = g_reflectionTexture;
- g_refractionImage.sampler.texture = g_refractionTexture;
- }
-}
-
-function increaseRenderTargetResolution() {
- var changed;
- if (g_renderTargetWidth < 2048) {
- g_renderTargetWidth <<= 1;
- changed = true;
- }
- if (g_renderTargetHeight < 2048) {
- g_renderTargetHeight <<= 1;
- changed = true;
- }
- setupRenderTargets();
-}
-
-function decreaseRenderTargetResolution() {
- var changed;
- if (g_renderTargetWidth > 256) {
- g_renderTargetWidth >>= 1;
- changed = true;
- }
- if (g_renderTargetHeight > 256) {
- g_renderTargetHeight >>= 1;
- changed = true;
- }
- setupRenderTargets();
-}
-
-/**
- * Loads shader files into g_shaders object.
- */
-function loadShaders() {
- var ii;
- var n;
- var names = [
- 'diffuse',
- 'diffuse_bump',
- 'diffuse_bump_2textures',
- 'diffuse_bump_blend',
- 'diffuse_bump_blend_underwater',
- 'diffuse_bump_specular',
- 'imageshader',
- 'just_color',
- 'proxy',
- 'simpleshader',
- 'skydomeshader',
- 'underwatershader',
- 'watercolorandskyshader',
- 'waterfallshader',
- 'watershader',
- 'waterstyle2',
- ];
- for (ii = 0; ii < names.length; ++ii) {
- n = names[ii];
- g_shaders[n] = o3djs.io.loadTextFileSynchronous('shaders_cg/' + n + '.cg');
- }
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- loadShaders();
-
- g_materialPanelElement = o3djs.util.getElementById('materialpanel');
- g_propPanelElement = o3djs.util.getElementById('proppanel');
- g_effectPanelElement = o3djs.util.getElementById('effectpanel');
- g_upperPanelElement = o3djs.util.getElementById('upperpanel');
- g_effectTabsElement = o3djs.util.getElementById('effecttabs');
- g_effectTextAreaElement = o3djs.util.getElementById('effecttextarea');
- g_sceneElement = o3djs.util.getElementById('o3d');
-
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_quaternions = o3djs.quaternions;
- window.g_client = g_client = g_o3dElement.client;
-
- g_mainPack = g_client.createPack();
- g_scenePack = g_client.createPack();
-
- g_mainRoot = g_mainPack.createObject('Transform');
- g_baseRoot = g_scenePack.createObject('Transform');
- g_baseRoot.parent = g_mainRoot;
- g_sceneRoot = g_scenePack.createObject('Transform');
- g_sceneRoot.parent = g_baseRoot;
- g_mainRoot.parent = g_client.root;
- g_sceneRoot.translate(0, 0, -g_waterLevel);
-
- setupRenderTargets();
-
- // Create states to set clipping.
- g_reflectionClipState = g_mainPack.createObject('State');
- g_reflectionClipState.getStateParam('AlphaTestEnable').value = true;
- g_reflectionClipState.getStateParam('AlphaComparisonFunction').value =
- g_o3d.State.CMP_GREATER;
- var reflectionStateSet = g_mainPack.createObject('StateSet');
- reflectionStateSet.state = g_reflectionClipState;
- reflectionStateSet.parent = g_reflectionSurfaceSet;
-
- var fStrength = 4.0;
- g_refractionClipState = g_mainPack.createObject('State');
- g_refractionClipState.getStateParam('AlphaTestEnable').value = true;
- g_refractionClipState.getStateParam('AlphaComparisonFunction').value =
- g_o3d.State.CMP_GREATER;
-
- var refractionStateSet = g_mainPack.createObject('StateSet');
- refractionStateSet.state = g_refractionClipState;
- refractionStateSet.parent = g_refractionSurfaceSet;
-
- // Create the render graph for the main view.
- g_mainViewInfo = o3djs.rendergraph.createBasicView(
- g_mainPack,
- g_mainRoot);
-
- // Create a render graph for the reflection map
- g_reflectionViewInfo = o3djs.rendergraph.createExtraView(g_mainViewInfo);
- g_reflectionViewInfo.root.parent = reflectionStateSet;
- g_reflectionViewInfo.treeTraversal.transform = g_baseRoot;
- g_reflectionViewInfo.performanceState.getStateParam('CullMode').value =
- g_o3d.State.CULL_CCW;
- g_reflectionViewInfo.performanceState.getStateParam(
- 'ColorWriteEnable').value = 15;
- g_reflectionViewInfo.zOrderedState.getStateParam('CullMode').value =
- g_o3d.State.CULL_CCW;
- g_reflectionViewInfo.zOrderedState.getStateParam(
- 'ColorWriteEnable').value = 15;
-
- // Create a render graph for the refraction map
- g_refractionViewInfo = o3djs.rendergraph.createBasicView(
- g_mainPack,
- g_baseRoot,
- refractionStateSet);
-
- // Create a render graph for the HUD
- g_hudRoot = g_mainPack.createObject('Transform');
- g_hudViewInfo = o3djs.rendergraph.createBasicView(
- g_mainPack,
- g_hudRoot);
- g_hudViewInfo.clearBuffer.clearColorFlag = false;
-
- g_hudViewInfo.zOrderedState.getStateParam('CullMode').value =
- g_o3d.State.CULL_NONE;
-
- g_hudViewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 0, 1], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- //g_reflectionViewInfo.clearBuffer.clearColor = [0.5, 1, 0.5, 1];
- //g_refractionViewInfo.clearBuffer.clearColor = [0.5, 0.5, 1, 1];
- g_reflectionViewInfo.clearBuffer.clearColor = [0, 0, 0, 0];
- g_refractionViewInfo.clearBuffer.clearColor = g_waterColor;
-
- // Set some names so it's easier to debug.
- g_mainViewInfo.performanceDrawList.name = 'performanceDrawList';
- g_mainViewInfo.zOrderedDrawList.name = 'zOrderedDrawList';
-
- // Turn off culling for transparent stuff so we can see the backs of leaves.
- g_mainViewInfo.zOrderedState.getStateParam('CullMode').value =
- g_o3d.State.CULL_NONE;
- g_mainViewInfo.zOrderedState.getStateParam('AlphaReference').value = 0.7;
-
- // Turn on alpha test in the performance list for our clipping plane.
- g_mainViewInfo.performanceState.getStateParam('AlphaTestEnable').value = true;
- g_mainViewInfo.performanceState.getStateParam(
- 'AlphaComparisonFunction').value = g_o3d.State.CMP_GREATER;
-
- g_fpsManager = o3djs.fps.createFPSManager(g_mainPack,
- g_client.width,
- g_client.height);
- g_fpsManager.setVisible(false);
-
- // Create a param object to hold a few params to drive things globally.
- g_globalParams = g_mainPack.createObject('ParamObject');
- g_globalParams.name = 'global params';
- g_globalClockParam = g_globalParams.createParam('clock', 'ParamFloat');
- g_lightPositionParam = g_globalParams.createParam('lightWorldPos',
- 'ParamFloat3');
- g_lightDirectionParam = g_globalParams.createParam('lightDirection',
- 'ParamFloat3');
- g_lightColorParam = g_globalParams.createParam('lightColor',
- 'ParamFloat4');
- g_lightColorParam.value = [2.0, 1.8, 1.4, 1];
- setSunPosition([0, -100000, 200000]);
-
- g_clipHeightParam = g_globalParams.createParam('clipHeight', 'ParamFloat');
- g_proxyOffsetParam = g_globalParams.createParam('offset', 'ParamFloat');
-
- g_particleSystem = o3djs.particles.createParticleSystem(
- g_mainPack,
- g_mainViewInfo,
- g_globalClockParam,
- g_math.pseudoRandom);
-
- // Since we set the state for the draw pass to 'AlphaReference' = 0.7
- // We need to set it back to 0.0 for the particles.
- for (var ii = 0; ii < g_particleSystem.particleStates.length; ++ii) {
- g_particleSystem.particleStates[ii].getStateParam(
- 'AlphaReference').value = 0.0;
- }
-
- g_editableEffects.push(g_particleSystem.effects[0]);
- g_editableEffects.push(g_particleSystem.effects[1]);
-
- g_loader = o3djs.loader.createLoader(onAllLoadingFinished);
-
- setupWater();
- setupHud();
-
- loadProxy();
-
- // It's important to create stuff in g_mainPack and not g_scenePack because
- // g_scenePack will be scanned and modified after loading.
-
- setClientSize();
- updateCamera();
- updateProjection();
-
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', onMouseDown);
- o3djs.event.addEventListener(g_o3dElement, 'mousemove', onMouseMove);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', onMouseUp);
- o3djs.event.addEventListener(g_o3dElement, 'wheel', onWheel);
- o3djs.event.addEventListener(g_o3dElement, 'keydown', onKeyDown);
- o3djs.event.addEventListener(g_o3dElement, 'keyup', onKeyUp);
-
- // If we don't check the size of the client area every frame we don't get a
- // chance to adjust the perspective matrix fast enough to keep up with the
- // browser resizing us.
- g_client.setRenderCallback(onRender);
-
- // Because we don't render the render targets every frame of the OS has
- // to reset them their contents will get lost. In that case O3D will notify
- // us through this callback so we can re-render our render targets.
- g_client.setLostResourcesCallback(function() {
- g_updateRenderTargets = true;
- });
-}
-
-/**
- * Loads a texture.
- *
- * @param {!o3djs.loader.Loader} loader Loader to use to load texture.
- * @param {!o3d.Pack} pack Pack to load texture in.
- * @param {!o3d.Material} material Material to attach sampler to.
- * @param {string} samplerName Name of sampler.
- * @param {string} textureName filename of texture.
- * @return {!o3d.Sampler} Sampler attached to material.
- */
-function loadTexture(loader, pack, material, samplerName, textureName) {
- var sampler = pack.createObject('Sampler');
- setParam(material, samplerName, sampler);
-
- var url = o3djs.util.getAbsoluteURI('assets/' + textureName);
- loader.loadTexture(pack, url, function(texture, success) {
- sampler.texture = texture;
- });
-
- return sampler;
-}
-
-/**
- * Create the waterfall effect.
- */
-function setupWaterfall() {
- // A prefix for waterfall materials would have been better.
- var material = g_scenePack.getObjects('Standard_3', 'o3d.Material')[0];
-
- // Create an effect with a v offset parameter so we can scroll the
- // UVs.
- var effect = g_mainPack.createObject('Effect');
- effect.name = 'waterfall';
- effect.loadFromFXString(g_shaders.waterfallshader);
- effect.createUniformParameters(material);
-
- g_editableEffects.push(effect);
-
- // Set the waterfall to use additive blending.
- var state = g_mainPack.createObject('State');
- state.getStateParam('SourceBlendFunction').value =
- g_o3d.State.BLENDFUNC_SOURCE_ALPHA;
- state.getStateParam('DestinationBlendFunction').value =
- g_o3d.State.BLENDFUNC_ONE;
- state.getStateParam('AlphaReference').value = 0.0;
- //state.getStateParam('ZWriteEnable').value = false;
-
- material.state = state;
- material.drawList = g_mainViewInfo.zOrderedDrawList;
- material.effect = effect;
-
- // Create a counter to scroll the Vs.
- // var counter = g_mainPack.createObject('SecondCounter');
- // material.getParam('vOffset').bind(counter.getParam('count'));
- //
- // For selenium testing we need a global clock.
- material.getParam('vOffset').bind(g_globalClockParam);
-
-}
-
-/**
- * Setup underwater.
- * Must be called after the scene has loaded.
- * NOTE: The coral needs a new shader that supports normal maps
- * but it's a low priority to fix right now.
- */
-function setupUnderwater() {
- var effect = g_mainPack.createObject('Effect');
- effect.name = 'underwater';
- effect.loadFromFXString(g_shaders.underwatershader);
- g_editableEffects.push(effect);
-
- // make 2 materials, one for zOrdered, one for performance.
- var materials = [];
- for (var ii = 0; ii < 2; ++ii) {
- var material = g_mainPack.createObject('Material');
- // Copy the water params so this material gets access to the noise samplers.
- // and the clock regardless of whether or not it uses them. That way you
- // can access them as you edit the shader live.
- material.copyParams(g_waterMaterial);
- material.effect = effect;
- effect.createUniformParameters(material);
-
- bindParam(material, 'sunVector', g_lightDirectionParam);
- setParam(material, 'waterColor', g_waterColor);
- setParam(material, 'fadeFudge', -1 / 1800);
- bindParam(material, 'clock', g_globalClockParam);
-
- g_fadeParams[ii] = material.getParam('fadeFudge');
- materials[ii] = material;
- }
-
- materials[0].drawList = g_refractionViewInfo.performanceDrawList;
- materials[0].name = 'underwaterOpaque';
- materials[1].drawList = g_refractionViewInfo.zOrderedDrawList;
- materials[1].name = 'underwaterTransparent';
-
- g_underwaterMaterials = materials;
-
- // put a draw element on each element in the scene to draw it with the
- // underwater shader.
- var elements = g_scenePack.getObjectsByClassName('o3d.Element');
- for (var ee = 0; ee < elements.length; ++ee) {
- var element = elements[ee];
- var originalMaterial = element.material;
- var materialInfo = g_materialLists[originalMaterial.name];
- if ((!materialInfo || materialInfo.refract) &&
- element.name != 'Seafloor|Sand_Dark' &&
- (!materialInfo || materialInfo.effect != 'diffuse_bump_2textures')) {
- // Use the sampler from the original material.
- var originalSamplerParam = originalMaterial.getParam('diffuseSampler');
- if (originalSamplerParam) {
- var drawElement = element.createDrawElement(
- g_scenePack,
- originalMaterial.drawList == g_mainViewInfo.performanceDrawList ?
- materials[0] : materials[1]);
- // create a Sampler Param on this draw element to use instead of the
- // material's.
- var samplerParam = drawElement.createParam('diffuseSampler',
- 'ParamSampler');
- samplerParam.value = originalSamplerParam.value;
- }
- }
- }
-
- // Special case the sand and coral rocks.
- var materialNames = {
- 'Sand_Dark': {texture: 'image3.dds'},
- 'Folg_coralRockA_mat': {texture: 'image30.dds'},
- 'Folg_coralRockB_mat': {texture: 'image30.dds'}};
- for (var name in materialNames) {
- var info = materialNames[name];
- var material = g_scenePack.getObjects(name, 'o3d.Material')[0];
- material.drawList = g_refractionViewInfo.performanceDrawList;
- addTexture(material, 'diffuse2Sampler', info.texture);
- }
-}
-
-/**
- * Create the water effect.
- */
-function setupWater() {
- var waterEffects = ['watershader', 'watercolorandskyshader', 'waterstyle2'];
- var effects = [];
- for (var ee = 0; ee < waterEffects.length; ++ee) {
- var name = waterEffects[ee]
- var effect = g_mainPack.createObject('Effect');
- effect.name = name;
- effect.loadFromFXString(g_shaders[name]);
- effects[ee] = effect;
- g_editableEffects.push(effect);
- }
- g_waterEffect = effects[0];
- g_waterColorAndSkyEffect = effects[1];
- g_waterStyle2Effect = effects[2];
-
- var effect = g_waterEffect;
-
- var material = g_mainPack.createObject('Material');
- g_waterMaterial = material;
- material.name = 'water';
- material.drawList = g_mainViewInfo.performanceDrawList;
- material.effect = effect;
- effect.createUniformParameters(material);
-
- // We could reuse the one from the waterfall but let's make 2 anyway.
- // var counter = g_mainPack.createObject('SecondCounter');
- // For selenium testing we need a global clock.
-
- setParam(material, 'waterColor', g_waterColor);
- setParam(material, 'reflectionRefractionOffset', 0.1);
- //material.getParam('clock').bind(counter.getParam('count'));
- material.getParam('clock').bind(g_globalClockParam);
- g_viewPositionParam = material.getParam('viewPosition');
-
- var sampler = g_mainPack.createObject('Sampler');
- sampler.texture = g_refractionTexture;
- sampler.addressModeU = g_o3d.Sampler.MIRROR;
- sampler.addressModeV = g_o3d.Sampler.MIRROR;
- setParam(material, 'refractionSampler', sampler);
- sampler = g_mainPack.createObject('Sampler');
- sampler.texture = g_reflectionTexture;
- sampler.addressModeU = g_o3d.Sampler.MIRROR;
- sampler.addressModeV = g_o3d.Sampler.MIRROR;
- setParam(material, 'reflectionSampler', sampler);
-
- var shape = o3djs.primitives.createPlane(g_mainPack, material,
- 100000, 100000, 100, 100,
- [[1, 0, 0, 0],
- [0, 0, 1, 0],
- [0, -1, 0, 0],
- [0, 0, 0, 1]]);
-
- g_waterTransform = g_mainPack.createObject('Transform');
- g_waterTransform.name = 'watersurface';
- g_waterTransform.addShape(shape);
-
- function waterAssetsLoaded() {
- g_waterTransform.parent = g_mainRoot;
- setupSkyDome();
- }
-
- // Create a loader for the water so we can know when all its assets have
- // loaded.
- var loader = g_loader.createLoader(waterAssetsLoaded);
-
- g_environmentSampler = loadTexture(loader, g_mainPack, material,
- 'environmentSampler',
- 'sky-cubemap.dds');
-
- // Create some textures.
- var textureInfo = [
- {width: 128, height: 128, type: 0, name: 'noiseSampler'},
- {width: 64, height: 64, type: 0, name: 'noiseSampler2'},
- {width: 32, height: 32, type: 0, name: 'noiseSampler3'},
- {width: 32, height: 1, type: 1, name: 'fresnelSampler'}
- ];
-
- for (var tt = 0; tt < textureInfo.length; ++tt) {
- var info = textureInfo[tt];
- var pixels = [];
-
- switch (info.type) {
- case 0:
- // Create a noise texture.
- for (var yy = 0; yy < info.height; ++yy) {
- for (var xx = 0; xx < info.width; ++xx) {
- for (var cc = 0; cc < 3; ++cc) {
- pixels.push(g_math.pseudoRandom());
- }
- }
- }
- break;
- case 1:
- // Create a ramp texture. (this needs to be a fresnel ramp?)
- for (var yy = 0; yy < info.height; ++yy) {
- for (var xx = 0; xx < info.width; ++xx) {
- // TODO: figure this out.
- var color = Math.pow(1 - xx / info.width, 10);
- for (var cc = 0; cc < 3; ++cc) {
- pixels.push(color);
- }
- }
- }
- break;
- }
- var texture = g_mainPack.createTexture2D(
- info.width, info.height, g_o3d.Texture.XRGB8, 1, false);
- texture.set(0, pixels);
- var sampler = g_mainPack.createObject('Sampler');
- sampler.texture = texture;
- setParam(material, info.name, sampler);
- }
-
- loader.finish();
-}
-
-/**
- * Create particles.
- */
-function setupParticles() {
- setupTorches();
- setupMist();
-}
-
-/**
- * Create the torches.
- */
-function setupTorches() {
- g_torchEmitter = g_particleSystem.createParticleEmitter(g_torchTexture);
- g_torchEmitter.setState(o3djs.particles.ParticleStateIds.ADD);
- g_torchEmitter.setColorRamp(
- [1, 1, 0, 1,
- 1, 0, 0, 1,
- 0, 0, 0, 1,
- 0, 0, 0, 0.5,
- 0, 0, 0, 0]);
- g_torchEmitter.setParameters({
- numParticles: 40,
- lifeTime: 2,
- timeRange: 2,
- startSize: 50,
- endSize: 90,
- positionRange: [10, 10, 10],
- velocity: [0, 0, 60], velocityRange: [15, 15, 15],
- acceleration: [0, 0, -20],
- spinSpeedRange: 4}
- );
-
- g_torchMaterial = g_torchEmitter.material;
-
- // Add one to each torch.
- var shape = g_torchEmitter.shape;
- g_scenePack.getObjects('particle_torch01',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_torch02',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_torch03',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_torch04',
- 'o3d.Transform')[0].addShape(shape);
-}
-
-/**
- * Create the mist.
- */
-function setupMist() {
- g_topMistEmitter = g_particleSystem.createParticleEmitter(g_mistTexture);
- g_topMistEmitter.setState(o3djs.particles.ParticleStateIds.ADD);
- g_topMistEmitter.setColorRamp(
- [1, 1, 1, 2,
- 1, 1, 1, 0]);
- g_topMistEmitter.setParameters({
- numParticles: 20,
- timeRange: 3,
- lifeTime: 3, lifeTimeRange: 1,
- startSize: 400,
- endSize: 600,
- position: [-100, -100, 0], positionRange: [25, 25, 0],
- velocity: [0, 0, 150], velocityRange: [15, 15, 15],
- worldAcceleration: [0, 0, -500],
- spinSpeedRange: 8}
- );
-
- // Add one to each top.
- var shape = g_topMistEmitter.shape;
- g_scenePack.getObjects('particle_falltop01',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_falltop02',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_falltop03',
- 'o3d.Transform')[0].addShape(shape);
-
- g_bottomMistEmitter = g_particleSystem.createParticleEmitter(g_mistTexture);
- g_bottomMistEmitter.setState(o3djs.particles.ParticleStateIds.ADD);
- g_bottomMistEmitter.setColorRamp(
- [1, 1, 1, 1,
- 1, 1, 1, 0]);
- g_bottomMistEmitter.setParameters({
- numParticles: 40,
- lifeTime: 2,
- timeRange: 2,
- startSize: 800,
- endSize: 1500,
- position: [0, 0, 100], positionRange: [200, 200, 10],
- velocityRange: [200, 200, 0],
- acceleration: [0, 0, -20],
- spinSpeedRange: 4}
- );
-
- // Add one to each bottom.
- shape = g_bottomMistEmitter.shape;
-
- g_scenePack.getObjects('particle_fallbottom01',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_fallbottom02',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_fallbottom03',
- 'o3d.Transform')[0].addShape(shape);
-
- g_rippleEmitter = g_particleSystem.createParticleEmitter(g_mistTexture);
- g_rippleEmitter.setState(o3djs.particles.ParticleStateIds.ADD);
- g_rippleEmitter.setColorRamp(
- [0.7, 0.8, 1, 0.5,
- 1, 1, 1, 0]);
- g_rippleEmitter.setParameters({
- numParticles: 20,
- lifeTime: 2,
- timeRange: 2,
- startSize: 50,
- endSize: 10000,
- position: [0, 0, 10], positionRange: [250, 250, 0],
- orientation: o3djs.quaternions.rotationX(Math.PI / 2),
- billboard: false});
-
- // Add one to each bottom.
- shape = g_rippleEmitter.shape;
-
- g_scenePack.getObjects('particle_fallbottom01',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_fallbottom02',
- 'o3d.Transform')[0].addShape(shape);
- g_scenePack.getObjects('particle_fallbottom03',
- 'o3d.Transform')[0].addShape(shape);
-}
-
-function setupSkyDome() {
- // Create the skydome effect.
- var effect = g_mainPack.createObject('Effect');
- effect.name = 'skydome';
- effect.loadFromFXString(g_shaders.skydomeshader);
- g_editableEffects.push(effect);
-
- var material = g_mainPack.createObject('Material');
- g_skyDomeMaterial = material;
- material.name = 'skydome';
- material.drawList = g_mainViewInfo.performanceDrawList;
- material.effect = effect;
- effect.createUniformParameters(material);
-
- material.getParam('environmentSampler').value = g_environmentSampler;
-
- // Create a special quad to draw the sky. We won't transform this quad
- // at all. It's already in clip-space.
- var shape = o3djs.primitives.createPlane(g_mainPack, material,
- 2, 2, 1, 1,
- [[1, 0, 0, 0],
- [0, 0, 1, 0],
- [0, -1, 0, 0],
- [0, 0, 0.99999, 1]]);
-
- g_skyDomeTransform = g_mainPack.createObject('Transform');
- g_skyDomeTransform.parent = g_mainRoot;
- g_skyDomeTransform.addShape(shape);
-}
-
-/**
- * Creates an Image object which is a transform and a child scaleTransform
- * scaled to match the texture
- *
- * @constructor
- * @param {!o3d.Transform} parent Transform to parent image too.
- * @param {!o3d.Texture} texture The texture.
- * @param {boolean} opt_topLeft If true the origin of the image will be it's
- * topleft corner, the default is the center of the image.
- */
-function Image(parent, texture, opt_topLeft) {
- // create a transform for positioning
- this.transform = g_mainPack.createObject('Transform');
- this.transform.parent = parent;
-
- // create a transform for scaling to the size of the image just so
- // we don't have to manage that manually in the transform above.
- this.scaleTransform = g_mainPack.createObject('Transform');
- this.scaleTransform.parent = this.transform;
-
- // setup the sampler for the texture
- this.sampler = g_mainPack.createObject('Sampler');
- this.sampler.addressModeU = g_o3d.Sampler.CLAMP;
- this.sampler.addressModeV = g_o3d.Sampler.CLAMP;
- this.paramSampler = this.scaleTransform.createParam('diffuseSampler',
- 'ParamSampler');
- this.paramSampler.value = this.sampler;
-
- this.sampler.texture = texture;
- this.scaleTransform.addShape(g_imageShape);
- if (opt_topLeft) {
- this.scaleTransform.translate(texture.width / 2, texture.height / 2, 0);
- }
- this.scaleTransform.scale(texture.width, -texture.height, 1);
- this.colorParam = this.scaleTransform.createParam('colorMult', 'ParamFloat4');
- this.colorParam.value = [1, 1, 1, 1];
-}
-
-/**
- * Sets up the hud.
- */
-function setupHud() {
- var effect = g_mainPack.createObject('Effect');
- effect.name = 'hud';
- effect.loadFromFXString(g_shaders.imageshader);
- g_editableEffects.push(effect);
- // Make the default colorMult 1, 1, 1, 1 uncase it is not supplied by the
- // material.
- effect.createParam('colorMult', 'ParamFloat4').value = [1, 1, 1, 1];
-
- g_imageEffect = effect;
-
- var g_imageMaterial = g_mainPack.createObject('Material');
- g_imageMaterial.drawList = g_hudViewInfo.zOrderedDrawList;
- g_imageMaterial.effect = effect;
- effect.createUniformParameters(g_imageMaterial);
- g_imageMaterial.getParam('colorMult').value = [1, 1, 1, 1];
-
- g_renderTargetDisplayRoot = g_mainPack.createObject('Transform');
- g_renderTargetDisplayRoot.parent = g_hudRoot;
- g_renderTargetDisplayRoot.visible = false;
-
- g_imageShape = o3djs.primitives.createPlane(g_mainPack, g_imageMaterial,
- 1, 1, 1, 1,
- [[1, 0, 0, 0],
- [0, 0, 1, 0],
- [0, 1, 0, 0],
- [0, 0, 0, 1]]);
-
- // Because it's easier to make a texture here than manage another effect
- var backTexture = g_mainPack.createTexture2D(
- 1, 1, g_o3d.Texture.XRGB8, 1, false);
- backTexture.set(0, [1, 1, 1]);
-
- g_whiteTexture = backTexture;
- g_whiteSampler = g_mainPack.createObject('Sampler');
- g_whiteSampler.texture = g_whiteTexture;
-
- // Make images to show the render targets.
- for (var ii = 0; ii < 2; ++ii) {
- var textureDisplaySquareSize = 256;
- var renderTargetTexture = (ii == 0) ? g_reflectionTexture :
- g_refractionTexture;
- var x = 10;
- var y = 10 + ii * (textureDisplaySquareSize + 10);
- var borderSize = 2;
- var image;
- // make a back image to create a border around render target.
- image = new Image(g_renderTargetDisplayRoot, backTexture, true);
- image.transform.translate(x - borderSize, y - borderSize, -3);
- image.transform.scale(textureDisplaySquareSize + borderSize * 2,
- textureDisplaySquareSize + borderSize * 2,
- 1);
- image = new Image(g_renderTargetDisplayRoot, renderTargetTexture, true);
- image.transform.translate(x, y, -2);
- image.transform.scale(textureDisplaySquareSize / g_renderTargetWidth,
- textureDisplaySquareSize / g_renderTargetHeight, 1);
- if (ii == 0) {
- g_reflectionImage = image;
- } else {
- g_refractionImage = image;
- }
- }
-
- // Make a fader plane.
- {
- var image = new Image(g_hudRoot, backTexture, true);
- g_faderTransform = image.transform;
- g_faderTransform.visible = false;
- g_faderColorParam = image.colorParam;
- updateFaderPlane();
- }
-
- // Make a canvas for text.
- var canvasLib = o3djs.canvas.create(g_mainPack,
- g_hudRoot,
- g_hudViewInfo);
-
- g_hudQuad = canvasLib.createXYQuad(20, 20, -1, 512, 512, true);
- g_paint = g_mainPack.createObject('CanvasPaint');
-
- g_paint.setOutline(3, [1, 1, 1, 1]);
- g_paint.textAlign = g_o3d.CanvasPaint.LEFT;
- g_paint.textSize = 16;
- g_paint.textTypeface = 'Arial';
- g_paint.color = [0, 0, 0, 1];
-
- setHudText('Loading...');
-}
-
-/**
- * Sets the text on the hud.
- * @param {string} text The text to display.
- */
-function setHudText(text) {
- if (g_showError) {
- return;
- }
- var canvas = g_hudQuad.canvas;
- canvas.clear([0, 0, 0, 0]);
- canvas.saveMatrix();
- var lines = text.split('\n');
- for (var ll = 0; ll < lines.length; ++ll) {
- var tabs = lines[ll].split('\t');
- for (var tt = 0; tt < tabs.length; ++tt) {
- canvas.drawText(tabs[tt], 10 + tt * 120, 30 + 20 * ll, g_paint);
- }
- }
- canvas.restoreMatrix();
-
- g_hudQuad.updateTexture();
-}
-
-/**
- * Show a hint message.
- */
-function showHint() {
- g_hudQuad.transform.visible = true;
- g_hudFadeTime = 0.0;
- setHudText('press H for help.');
-}
-
-/**
- * Show a help message.
- */
-function toggleHelp() {
- g_hudFadeTime = 0.0;
- g_helpVisible = !g_helpVisible;
- g_hudQuad.transform.visible = true;
- if (g_helpVisible) {
- setHudText('1 - 4\t: Camera Preset\n' +
- 'Mouse\t: Look Around\n' +
- 'Wheel\t: Field of View\n' +
- 'Arrows\t: Move Camera\n' +
- 'p\t: Toggle Props\n' +
- 'm\t: Edit Materials\n' +
- 'e\t: Edit Effects\n' +
- 'r\t: Show Render Targets\n' +
- 'c\t: Use Simple Shaders\n' +
- 'f\t: Show FPS\n' +
- 'h\t: Show Help\n' +
- 'o\t: Change Water Effect\n' +
- 'q\t: Toggle demo camera\n');
- } else {
- showHint();
- }
-}
-
-/**
- * Show error.
- * @param {string} msg Msg to display.
- */
-function showError(msg) {
- g_hudQuad.transform.visible = true;
- setHudText('Error: Could not load scene.\n' + msg);
- g_showError = true;
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
diff --git a/o3d/samples/beachdemo/shaders_cg/diffuse.cg b/o3d/samples/beachdemo/shaders_cg/diffuse.cg
deleted file mode 100644
index e530cf4..0000000
--- a/o3d/samples/beachdemo/shaders_cg/diffuse.cg
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-uniform float4x4 world : WORLD;
-uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-uniform float3 lightWorldPos;
-uniform float4 lightColor;
-uniform float clipHeight;
-uniform float4x4 viewInverse : VIEWINVERSE;
-uniform float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-uniform float4 emissive;
-uniform float4 ambient;
-sampler2D diffuseSampler;
-uniform float4 specular;
-uniform float shininess;
-
-struct InVertex {
- float4 position : POSITION;
- float4 normal : NORMAL;
- float2 diffuseUV : TEXCOORD0;
-};
-
-struct OutVertex {
- float4 position : POSITION;
- float2 diffuseUV : TEXCOORD0;
- float4 worldPosition: TEXCOORD1;
- float3 normal : TEXCOORD2;
-};
-
-OutVertex vertexShaderFunction(InVertex input) {
- OutVertex output;
- output.position = mul(input.position, worldViewProjection);
- output.worldPosition = mul(input.position, world);
- output.diffuseUV = input.diffuseUV;
- output.normal = mul(float4(input.normal.xyz,0), worldInverseTranspose).xyz;
- return output;
-}
-
-float4 pixelShaderFunction(OutVertex input) : COLOR {
- float4 diffuse = tex2D(diffuseSampler, input.diffuseUV);
- float3 normal = normalize(input.normal);
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
- float3 surfaceToView = normalize(viewInverse[3] - input.worldPosition);
- float3 halfVector = normalize(surfaceToLight + surfaceToView);
- float4 litR = lit(dot(normal, surfaceToLight), dot(normal, halfVector), shininess);
- float alpha = input.worldPosition.z > clipHeight ? 0 : diffuse.a;
- return float4((emissive + lightColor * (ambient * diffuse + diffuse * litR.y + specular * litR.z)).rgb, alpha);
-}
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_cg/diffuse_bump.cg b/o3d/samples/beachdemo/shaders_cg/diffuse_bump.cg
deleted file mode 100644
index a0b943c..0000000
--- a/o3d/samples/beachdemo/shaders_cg/diffuse_bump.cg
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-uniform float4x4 world : WORLD;
-uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-uniform float3 lightWorldPos;
-uniform float4 lightColor;
-uniform float clipHeight;
-uniform float4x4 viewInverse : VIEWINVERSE;
-uniform float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-uniform float4 emissive;
-uniform float4 ambient;
-sampler2D diffuseSampler;
-uniform float4 specular;
-sampler2D bumpSampler;
-uniform float shininess;
-
-struct InVertex {
- float4 position : POSITION;
- float4 normal : NORMAL;
- float2 diffuseUV : TEXCOORD0;
- float3 tangent : TANGENT;
- float3 binormal : BINORMAL;
-};
-
-struct OutVertex {
- float4 position : POSITION;
- float2 diffuseUV : TEXCOORD0;
- float3 tangent : TEXCOORD1;
- float3 binormal : TEXCOORD2;
- float4 worldPosition: TEXCOORD3;
- float3 normal : TEXCOORD4;
-};
-
-OutVertex vertexShaderFunction(InVertex input) {
- OutVertex output;
- output.position = mul(input.position, worldViewProjection);
- output.worldPosition = mul(input.position, world);
- output.diffuseUV = input.diffuseUV;
- output.normal = mul(float4(input.normal.xyz,0), worldInverseTranspose).xyz;
- output.binormal = mul(float4(input.binormal,0), worldInverseTranspose).xyz;
- output.tangent = mul(float4(input.tangent,0), worldInverseTranspose).xyz;
- return output;
-}
-
-float4 pixelShaderFunction(OutVertex input) : COLOR {
- float4 diffuse = tex2D(diffuseSampler, input.diffuseUV);
- float3x3 tangentToWorld = float3x3(input.tangent,
- input.binormal,
- input.normal);
- float3 tangentNormal = tex2D(bumpSampler, input.diffuseUV.xy).xyz -
- float3(0.5, 0.5, 0.5);
- float3 normal = mul(tangentNormal, tangentToWorld);
- normal = normalize(normal);
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
- float3 surfaceToView = normalize(viewInverse[3] - input.worldPosition);
- float3 halfVector = normalize(surfaceToLight + surfaceToView);
- float4 litR = lit(dot(normal, surfaceToLight),
- dot(normal, halfVector),
- shininess);
- float alpha = input.worldPosition.z > clipHeight ? 0 : diffuse.a;
- return float4((emissive + lightColor *
- (ambient * diffuse +
- diffuse * litR.y +
- specular * litR.z)).rgb, alpha);
-}
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_cg/diffuse_bump_2textures.cg b/o3d/samples/beachdemo/shaders_cg/diffuse_bump_2textures.cg
deleted file mode 100644
index efd71be..0000000
--- a/o3d/samples/beachdemo/shaders_cg/diffuse_bump_2textures.cg
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-uniform float4x4 world : WORLD;
-uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-uniform float3 lightWorldPos;
-uniform float4 lightColor;
-uniform float4x4 viewInverse : VIEWINVERSE;
-uniform float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-uniform float4 emissive;
-uniform float4 ambient;
-sampler2D diffuseSampler;
-sampler2D diffuse2Sampler;
-uniform float4 specular;
-sampler2D bumpSampler;
-uniform float shininess;
-
-struct InVertex {
- float4 position : POSITION;
- float4 normal : NORMAL;
- float2 diffuseUV : TEXCOORD0;
- float3 tangent : TANGENT;
- float3 binormal : BINORMAL;
- float4 color : COLOR;
-};
-
-struct OutVertex {
- float4 position : POSITION;
- float2 diffuseUV : TEXCOORD0;
- float3 tangent : TEXCOORD1;
- float3 binormal : TEXCOORD2;
- float4 worldPosition: TEXCOORD3;
- float3 normal : TEXCOORD4;
- float4 color : COLOR;
-};
-
-OutVertex vertexShaderFunction(InVertex input) {
- OutVertex output;
- output.position = mul(input.position, worldViewProjection);
- output.worldPosition = mul(input.position, world);
- output.diffuseUV = input.diffuseUV;
- output.normal = mul(float4(input.normal.xyz,0), worldInverseTranspose).xyz;
- output.binormal = mul(float4(input.binormal,0), worldInverseTranspose).xyz;
- output.tangent = mul(float4(input.tangent,0), worldInverseTranspose).xyz;
- output.color = input.color;
- return output;
-}
-
-float4 pixelShaderFunction(OutVertex input) : COLOR {
- float4 diffuse = tex2D(diffuseSampler, input.diffuseUV);
- float4 diffuse2 = tex2D(diffuse2Sampler, input.diffuseUV);
- diffuse = lerp(diffuse, diffuse2, input.color);
- float3x3 tangentToWorld = float3x3(input.tangent,
- input.binormal,
- input.normal);
- float3 tangentNormal = tex2D(bumpSampler, input.diffuseUV.xy).xyz -
- float3(0.5, 0.5, 0.5);
- float3 normal = mul(tangentNormal, tangentToWorld);
- normal = normalize(normal);
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
- float3 surfaceToView = normalize(viewInverse[3] - input.worldPosition);
- float3 halfVector = normalize(surfaceToLight + surfaceToView);
- float4 litR = lit(dot(normal, surfaceToLight),
- dot(normal, halfVector),
- shininess);
- float alpha = input.worldPosition.z < 0 ? diffuse.a : 0;
- return float4((emissive +
- (ambient * diffuse +
- diffuse * litR.y +
- specular * litR.z)).rgb, alpha);
-}
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_cg/diffuse_bump_blend.cg b/o3d/samples/beachdemo/shaders_cg/diffuse_bump_blend.cg
deleted file mode 100644
index 6f9c18b..0000000
--- a/o3d/samples/beachdemo/shaders_cg/diffuse_bump_blend.cg
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-uniform float4x4 world : WORLD;
-uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-uniform float3 lightWorldPos;
-uniform float4 lightColor;
-uniform float clipHeight;
-uniform float4x4 viewInverse : VIEWINVERSE;
-uniform float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-uniform float4 emissive;
-uniform float4 ambient;
-sampler2D diffuseSampler;
-sampler2D diffuse2Sampler;
-uniform float4 specular;
-sampler2D bumpSampler;
-uniform float shininess;
-
-struct InVertex {
- float4 position : POSITION;
- float4 normal : NORMAL;
- float2 diffuseUV : TEXCOORD0;
- float2 diffuse2UV : TEXCOORD1;
- float3 tangent : TANGENT;
- float3 tangent2 : TANGENT1;
- float3 binormal : BINORMAL;
- float3 binormal2 : BINORMAL1;
- float4 color : COLOR;
-};
-
-struct OutVertex {
- float4 position : POSITION;
- float4 diffuseUV : TEXCOORD0;
- float3 tangent : TEXCOORD1;
- float3 tangent2 : TEXCOORD2;
- float3 binormal : TEXCOORD3;
- float3 binormal2 : TEXCOORD4;
- float4 worldPosition: TEXCOORD5;
- float3 normal : TEXCOORD6;
- float4 color : COLOR;
-};
-
-OutVertex vertexShaderFunction(InVertex input) {
- OutVertex output;
- output.position = mul(input.position, worldViewProjection);
- output.worldPosition = mul(input.position, world);
- output.diffuseUV = float4(input.diffuseUV, input.diffuse2UV);
- output.normal = mul(float4(input.normal.xyz,0), worldInverseTranspose).xyz;
- output.binormal = mul(float4(input.binormal,0), worldInverseTranspose).xyz;
- output.tangent = mul(float4(input.tangent,0), worldInverseTranspose).xyz;
- output.binormal2 = mul(float4(input.binormal2,0), worldInverseTranspose).xyz;
- output.tangent2 = mul(float4(input.tangent2,0), worldInverseTranspose).xyz;
- output.color = output.color;
- return output;
-}
-
-float4 pixelShaderFunction(OutVertex input) : COLOR {
- float4 diffuse1 = tex2D(diffuseSampler, input.diffuseUV.xy);
- float4 diffuse2 = tex2D(diffuse2Sampler, input.diffuseUV.zw);
- float3x3 tangentToWorld = float3x3(input.tangent,
- input.binormal,
- input.normal);
- float3 tangentNormal = tex2D(bumpSampler, input.diffuseUV.xy).xyz -
- float3(0.5, 0.5, 0.5);
- float3 normal = mul(tangentNormal, tangentToWorld);
- normal = normalize(normal);
- tangentToWorld = float3x3(input.tangent2, input.binormal2, input.normal);
- tangentNormal = tex2D(bumpSampler, input.diffuseUV.zw).xyz -
- float3(0.5, 0.5, 0.5);
- float3 normal2 = mul(tangentNormal, tangentToWorld);
- normal2 = normalize(normal2);
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
- float3 surfaceToView = normalize(viewInverse[3] - input.worldPosition);
- float3 halfVector = normalize(surfaceToLight + surfaceToView);
- float4 litR = lit(dot(normal, surfaceToLight),
- dot(normal, halfVector),
- shininess);
- float4 diffuse = lerp(diffuse1, diffuse2, input.color.a);
- float alpha = input.worldPosition.z > clipHeight ? 0 : diffuse.a;
- return float4((emissive + lightColor *
- (ambient * diffuse +
- diffuse * litR.y +
- specular * litR.z)).rgb, alpha);
-}
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_cg/diffuse_bump_blend_underwater.cg b/o3d/samples/beachdemo/shaders_cg/diffuse_bump_blend_underwater.cg
deleted file mode 100644
index eb782e9..0000000
--- a/o3d/samples/beachdemo/shaders_cg/diffuse_bump_blend_underwater.cg
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-uniform float4x4 world : WORLD;
-uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-uniform float3 lightWorldPos;
-uniform float4 lightColor;
-uniform float4x4 viewInverse : VIEWINVERSE;
-uniform float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-uniform float4 emissive;
-uniform float4 ambient;
-sampler2D diffuseSampler;
-sampler2D diffuse2Sampler;
-uniform float4 specular;
-sampler2D bumpSampler;
-uniform float shininess;
-
-struct InVertex {
- float4 position : POSITION;
- float4 normal : NORMAL;
- float2 diffuseUV : TEXCOORD0;
- float2 diffuse2UV : TEXCOORD1;
- float3 tangent : TANGENT;
- float3 tangent2 : TANGENT1;
- float3 binormal : BINORMAL;
- float3 binormal2 : BINORMAL1;
- float4 color : COLOR;
-};
-
-struct OutVertex {
- float4 position : POSITION;
- float4 diffuseUV : TEXCOORD0;
- float3 tangent : TEXCOORD1;
- float3 tangent2 : TEXCOORD2;
- float3 binormal : TEXCOORD3;
- float3 binormal2 : TEXCOORD4;
- float4 worldPosition: TEXCOORD5;
- float3 normal : TEXCOORD6;
- float4 color : COLOR;
-};
-
-OutVertex vertexShaderFunction(InVertex input) {
- OutVertex output;
- output.position = mul(input.position, worldViewProjection);
- output.worldPosition = mul(input.position, world);
- output.diffuseUV = float4(input.diffuseUV, input.diffuse2UV);
- output.normal = mul(float4(input.normal.xyz,0), worldInverseTranspose).xyz;
- output.binormal = mul(float4(input.binormal,0), worldInverseTranspose).xyz;
- output.tangent = mul(float4(input.tangent,0), worldInverseTranspose).xyz;
- output.binormal2 = mul(float4(input.binormal2,0), worldInverseTranspose).xyz;
- output.tangent2 = mul(float4(input.tangent2,0), worldInverseTranspose).xyz;
- output.color = output.color;
- return output;
-}
-
-float4 pixelShaderFunction(OutVertex input) : COLOR {
- float4 diffuse1 = tex2D(diffuseSampler, input.diffuseUV.xy);
- float4 diffuse2 = tex2D(diffuse2Sampler, input.diffuseUV.zw);
- float3x3 tangentToWorld = float3x3(input.tangent,
- input.binormal,
- input.normal);
- float3 tangentNormal = tex2D(bumpSampler, input.diffuseUV.xy).xyz -
- float3(0.5, 0.5, 0.5);
- float3 normal = mul(tangentNormal, tangentToWorld);
- normal = normalize(normal);
- tangentToWorld = float3x3(input.tangent2, input.binormal2, input.normal);
- tangentNormal = tex2D(bumpSampler, input.diffuseUV.zw).xyz -
- float3(0.5, 0.5, 0.5);
- float3 normal2 = mul(tangentNormal, tangentToWorld);
- normal2 = normalize(normal2);
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
- float3 surfaceToView = normalize(viewInverse[3] - input.worldPosition);
- float3 halfVector = normalize(surfaceToLight + surfaceToView);
- float4 litR = lit(dot(normal, surfaceToLight),
- dot(normal, halfVector),
- shininess);
- float4 diffuse = lerp(diffuse1, diffuse2, input.color.a);
- float alpha = input.worldPosition.z > 0 ? 0 : diffuse.a;
- return float4((emissive + lightColor *
- (ambient * diffuse +
- diffuse * litR.y +
- specular * litR.z)).rgb, alpha);
-}
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_cg/diffuse_bump_specular.cg b/o3d/samples/beachdemo/shaders_cg/diffuse_bump_specular.cg
deleted file mode 100644
index c3a1e13..0000000
--- a/o3d/samples/beachdemo/shaders_cg/diffuse_bump_specular.cg
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-uniform float4x4 world : WORLD;
-uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-uniform float3 lightWorldPos;
-uniform float4 lightColor;
-uniform float clipHeight;
-uniform float4x4 viewInverse : VIEWINVERSE;
-uniform float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-uniform float4 emissive;
-uniform float4 ambient;
-sampler2D diffuseSampler;
-sampler2D specularSampler;
-sampler2D bumpSampler;
-uniform float shininess;
-
-struct InVertex {
- float4 position : POSITION;
- float4 normal : NORMAL;
- float2 diffuseUV : TEXCOORD0;
- float3 tangent : TANGENT;
- float3 binormal : BINORMAL;
-};
-
-struct OutVertex {
- float4 position : POSITION;
- float2 diffuseUV : TEXCOORD0;
- float3 tangent : TEXCOORD1;
- float3 binormal : TEXCOORD2;
- float4 worldPosition: TEXCOORD3;
- float3 normal : TEXCOORD4;
-};
-
-OutVertex vertexShaderFunction(InVertex input) {
- OutVertex output;
- output.position = mul(input.position, worldViewProjection);
- output.worldPosition = mul(input.position, world);
- output.diffuseUV = input.diffuseUV;
- output.normal = mul(float4(input.normal.xyz,0), worldInverseTranspose).xyz;
- output.binormal = mul(float4(input.binormal,0), worldInverseTranspose).xyz;
- output.tangent = mul(float4(input.tangent,0), worldInverseTranspose).xyz;
- return output;
-}
-
-float4 pixelShaderFunction(OutVertex input) : COLOR {
- float4 diffuse = tex2D(diffuseSampler, input.diffuseUV);
- float4 specular = tex2D(specularSampler, input.diffuseUV);
- float3x3 tangentToWorld = float3x3(input.tangent, input.binormal, input.normal);
- float3 tangentNormal = tex2D(bumpSampler, input.diffuseUV.xy).xyz -
- float3(0.5, 0.5, 0.5);
- float3 normal = mul(tangentNormal, tangentToWorld);
- normal = normalize(normal);
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
- float3 surfaceToView = normalize(viewInverse[3] - input.worldPosition);
- float3 halfVector = normalize(surfaceToLight + surfaceToView);
- float4 litR = lit(dot(normal, surfaceToLight),
- dot(normal, halfVector),
- shininess);
- float alpha = input.worldPosition.z > clipHeight ? 0 : diffuse.a;
- return float4((emissive + lightColor *
- (ambient * diffuse +
- diffuse * litR.y +
- specular * litR.z)).rgb, alpha);
-}
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_cg/imageshader.cg b/o3d/samples/beachdemo/shaders_cg/imageshader.cg
deleted file mode 100644
index 37aaa94..0000000
--- a/o3d/samples/beachdemo/shaders_cg/imageshader.cg
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-
-float4 colorMult;
-sampler diffuseSampler;
-
-
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0;
-};
-
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD2;
-};
-
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(input.position, worldViewProjection);
- output.texcoord = input.texcoord;
- return output;
-}
-
-float4 pixelShaderFunction(PixelShaderInput input) : COLOR {
- return tex2D(diffuseSampler, input.texcoord) * colorMult;
-}
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_cg/just_color.cg b/o3d/samples/beachdemo/shaders_cg/just_color.cg
deleted file mode 100644
index 030e2f1..0000000
--- a/o3d/samples/beachdemo/shaders_cg/just_color.cg
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-uniform float4x4 world : WORLD;
-uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-uniform float3 lightWorldPos;
-uniform float4 lightColor;
-uniform float clipHeight;
-uniform float4x4 viewInverse : VIEWINVERSE;
-uniform float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-uniform float4 emissive;
-uniform float4 ambient;
-uniform float4 diffuse;
-uniform float4 specular;
-uniform float shininess;
-
-struct InVertex {
- float4 position : POSITION;
- float4 normal : NORMAL;
-};
-
-struct OutVertex {
- float4 position : POSITION;
- float4 worldPosition: TEXCOORD0;
- float3 normal : TEXCOORD1;
-};
-
-OutVertex vertexShaderFunction(InVertex input) {
- OutVertex output;
- output.position = mul(input.position, worldViewProjection);
- output.worldPosition = mul(input.position, world);
- output.normal = mul(float4(input.normal.xyz,0), worldInverseTranspose).xyz;
- return output;
-}
-
-float4 pixelShaderFunction(OutVertex input) : COLOR {
- float3 normal = normalize(input.normal);
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
- float3 surfaceToView = normalize(viewInverse[3] - input.worldPosition);
- float3 halfVector = normalize(surfaceToLight + surfaceToView);
- float4 litR = lit(dot(normal, surfaceToLight),
- dot(normal, halfVector),
- shininess);
- float alpha = input.worldPosition.z > clipHeight ? 0 : diffuse.a;
- return float4((emissive + lightColor *
- (ambient * diffuse +
- diffuse * litR.y +
- specular * litR.z)).rgb, alpha);
-}
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_cg/proxy.cg b/o3d/samples/beachdemo/shaders_cg/proxy.cg
deleted file mode 100644
index 1c5ca59..0000000
--- a/o3d/samples/beachdemo/shaders_cg/proxy.cg
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-uniform float4x4 world : WORLD;
-uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-uniform float3 lightWorldPos;
-uniform float4 lightColor;
-uniform float4x4 viewInverse : VIEWINVERSE;
-uniform float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-uniform float4 emissive;
-uniform float4 ambient;
-uniform float4 diffuse;
-uniform float4 specular;
-uniform float shininess;
-uniform float offset;
-
-struct InVertex {
- float4 position : POSITION;
- float4 normal : NORMAL;
-};
-
-struct OutVertex {
- float4 position : POSITION;
- float4 worldPosition: TEXCOORD0;
- float3 normal : TEXCOORD1;
-};
-
-OutVertex vertexShaderFunction(InVertex input) {
- OutVertex output;
- output.position = mul(input.position, worldViewProjection);
- output.worldPosition = mul(input.position, world);
- output.normal = mul(float4(input.normal.xyz,0), worldInverseTranspose).xyz;
- return output;
-}
-
-float4 pixelShaderFunction(OutVertex input) : COLOR {
- float3 normal = normalize(input.normal);
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
- float3 surfaceToView = normalize(viewInverse[3] - input.worldPosition);
- float3 halfVector = normalize(surfaceToLight + surfaceToView);
- float4 litR = lit(dot(normal, surfaceToLight),
- dot(normal, halfVector),
- shininess);
- float alpha = input.worldPosition.z > offset ? 0 : diffuse.a;
- return float4((emissive + lightColor *
- (ambient * diffuse +
- diffuse * litR.y +
- specular * litR.z)).rgb, alpha);
-}
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_cg/simpleshader.cg b/o3d/samples/beachdemo/shaders_cg/simpleshader.cg
deleted file mode 100644
index 7698b75..0000000
--- a/o3d/samples/beachdemo/shaders_cg/simpleshader.cg
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-uniform float4 simpleColor;
-
-struct VertexShaderInput {
- float4 position : POSITION;
-};
-
-struct PixelShaderInput {
- float4 position : POSITION;
-};
-
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(input.position, worldViewProjection);
- return output;
-}
-
-float4 pixelShaderFunction(PixelShaderInput input) : COLOR {
- return simpleColor;
-}
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_cg/skydomeshader.cg b/o3d/samples/beachdemo/shaders_cg/skydomeshader.cg
deleted file mode 100644
index da10332..0000000
--- a/o3d/samples/beachdemo/shaders_cg/skydomeshader.cg
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-uniform float4x4 worldViewProjectionInverse : VIEWPROJECTIONINVERSE;
-uniform float4x4 viewInverse : VIEWINVERSE;
-samplerCUBE environmentSampler;
-
-struct VertexShaderInput {
- float4 position : POSITION;
-};
-
-struct PixelShaderInput {
- float4 position : POSITION;
- float3 worldPosition : TEXCOORD0;
-};
-
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = input.position;
- float4 temp = mul(input.position, worldViewProjectionInverse);
- output.worldPosition = temp.xyz / temp.w;
- return output;
-}
-
-float4 pixelShaderFunction(PixelShaderInput input) : COLOR {
- float3 viewVector = normalize(viewInverse[3].xyz - input.worldPosition);
- return texCUBE(environmentSampler, float3(viewVector.x,
- abs(-viewVector.z) + 0.01,
- -viewVector.y));
-}
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_cg/underwatershader.cg b/o3d/samples/beachdemo/shaders_cg/underwatershader.cg
deleted file mode 100644
index 2b05598..0000000
--- a/o3d/samples/beachdemo/shaders_cg/underwatershader.cg
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-uniform float4x4 world : WORLD;
-uniform float4x4 viewProjection : VIEWPROJECTION;
-uniform float4 waterColor;
-uniform float3 sunVector;
-uniform float fadeFudge;
-
-sampler diffuseSampler;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float3 normal : NORMAL;
- float2 texcoord : TEXCOORD0;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0;
- float fade : TEXCOORD1;
- float4 color : TEXCOORD2;
- float4 worldPosition : TEXCOORD3;
-};
-
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- float4 worldPosition = mul(input.position, world);
- output.position = mul(float4(worldPosition.xyz, 1), viewProjection);
- output.worldPosition = worldPosition;
- output.texcoord = input.texcoord;
- output.color = dot(sunVector,
- normalize(mul(float4(input.normal, 0), world)));
- output.fade = 0.2 + 0.8 * saturate(worldPosition.z * fadeFudge);
-
- return output;
-}
-
-float4 pixelShaderFunction(PixelShaderInput input) : COLOR {
- float4 color = tex2D(diffuseSampler, input.texcoord);
-// float4 diffuse = tex2D(diffuseSampler, input.texcoord);
-// float4 color = lerp(diffuse * input.color, waterColor, input.fade);
- float alpha = input.worldPosition.z < 100 ? color.a : 0;
- return float4(color.xyz, alpha);
-}
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_cg/watercolorandskyshader.cg b/o3d/samples/beachdemo/shaders_cg/watercolorandskyshader.cg
deleted file mode 100644
index 64e1d2a..0000000
--- a/o3d/samples/beachdemo/shaders_cg/watercolorandskyshader.cg
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-// The 4x4 world view projection matrix.
-float4x4 world : WORLD;
-float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-float4x4 view : VIEW;
-float4x4 viewProjection : VIEWPROJECTION;
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-float3 viewPosition;
-float4 waterColor;
-float reflectionRefractionOffset;
-float clock;
-
-samplerCUBE environmentSampler;
-sampler2D fresnelSampler; // TODO: should be 1D.
-sampler2D noiseSampler;
-sampler2D noiseSampler2;
-sampler2D noiseSampler3;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0;
- float3 viewVector : TEXCOORD1;
- float3 screenPosition : TEXCOORD2;
-};
-
-/**
- * Vertex Shader
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- /**
- * We transform each vertex by the world view projection matrix to bring
- * it from world space to projection space.
- *
- * We return its color unchanged.
- */
- PixelShaderInput output;
-
- float4 worldPosition = mul(input.position, world);
- output.position = mul(worldPosition, viewProjection);
- output.viewVector = normalize(worldPosition.xyz - viewPosition.xyz);
- output.texcoord = input.texcoord;
-
- float4 tpos = mul(float4(worldPosition.x, worldPosition.y, 0, 1),
- viewProjection);
- output.screenPosition = tpos.xyz / tpos.w;
- output.screenPosition.xy = 0.5 + 0.5 * output.screenPosition.xy *
- float2(1, -1);
- output.screenPosition.z = reflectionRefractionOffset /
- output.screenPosition.z;
-
- return output;
-}
-/**
- * Pixel Shader - pixel shader does nothing but return the color.
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- float3 viewVector = float3(input.viewVector.x,
- input.viewVector.z,
- -input.viewVector.y);
-
- float2 texcoord = input.texcoord * 4;
- float3 n1 = tex2D(noiseSampler,
- texcoord +
- float2(clock * 0.01, clock * 0.02));
- float3 n2 = tex2D(noiseSampler2,
- texcoord +
- float2(clock * 0.03, clock * 0.01));
- float3 n3 = tex2D(noiseSampler3,
- texcoord +
- float2(clock * 0.005, clock * 0.007));
-
- float3 N = normalize(n1 + n2 * 2 + n3 * 4 + float3(-3.5, 16, -3.5));
-
- float3 R = normalize(reflect(viewVector, N));
- R.y = R.y < 0.01 ? 0.01 : R.y;
-
- //float f = tex1D(fresnelSampler, dot(R, N));
- float f = tex2D(fresnelSampler, float2(dot(R, N), 0.5)).x;
-
- // Lookup the sky color
- float3 skyReflection = texCUBE(environmentSampler, R);
-
- float3 color = lerp(waterColor.xyz, skyReflection, f);
-
- return float4(color, 1);
-}
-
-// Here we tell our effect file the functions
-// which specify our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_cg/waterfallshader.cg b/o3d/samples/beachdemo/shaders_cg/waterfallshader.cg
deleted file mode 100644
index a5071fa..0000000
--- a/o3d/samples/beachdemo/shaders_cg/waterfallshader.cg
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-uniform float4x4 world : WORLD;
-uniform float4x4 viewInverse : VIEWINVERSE;
-uniform float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-uniform float3 lightWorldPos;
-uniform float vOffset;
-
-sampler diffuseSampler;
-
-struct VertexShaderInput {
- float4 position : POSITION;
- float4 normal : NORMAL;
- float2 texcoord : TEXCOORD0;
-};
-
-struct PixelShaderInput {
- float4 position : POSITION;
- float3 normal : TEXCOORD0;
- float3 worldPosition : TEXCOORD1;
- float2 texcoord : TEXCOORD2;
-};
-
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(input.position, worldViewProjection);
- float3 worldPosition = mul(input.position, world).xyz;
- output.normal = mul(input.normal, worldInverseTranspose).xyz;
- output.worldPosition = worldPosition;
- output.texcoord = input.texcoord;
- return output;
-}
-
-float4 pixelShaderFunction(PixelShaderInput input) : COLOR {
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
- float3 worldNormal = normalize(input.normal);
- float3 surfaceToView = normalize(viewInverse[3].xyz - input.worldPosition);
- float3 halfVector = normalize(surfaceToLight + surfaceToView);
- float4 litResult = lit(dot(worldNormal, surfaceToLight),
- dot(worldNormal, halfVector), 0);
- float4 diffuse = tex2D(diffuseSampler, float2(input.texcoord.x,
- input.texcoord.y + vOffset));
- float4 outColor = (diffuse * litResult.y);
- return diffuse;
- //return float4(outColor.rgb, 1);
-}
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_cg/watershader.cg b/o3d/samples/beachdemo/shaders_cg/watershader.cg
deleted file mode 100644
index 9d4d07c..0000000
--- a/o3d/samples/beachdemo/shaders_cg/watershader.cg
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-// The 4x4 world view projection matrix.
-float4x4 world : WORLD;
-float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-float4x4 view : VIEW;
-float4x4 viewProjection : VIEWPROJECTION;
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-float3 viewPosition;
-float4 waterColor;
-float reflectionRefractionOffset;
-float clock;
-
-samplerCUBE environmentSampler;
-sampler2D fresnelSampler; // TODO: should be 1D.
-sampler2D refractionSampler; // This is a render target.
-sampler2D reflectionSampler; // This is a render target.
-sampler2D noiseSampler;
-sampler2D noiseSampler2;
-sampler2D noiseSampler3;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0;
- float3 viewVector : TEXCOORD1;
- float3 screenPosition : TEXCOORD2;
-};
-
-/**
- * Vertex Shader
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- /**
- * We transform each vertex by the world view projection matrix to bring
- * it from world space to projection space.
- *
- * We return its color unchanged.
- */
- PixelShaderInput output;
-
- float4 worldPosition = mul(input.position, world);
- output.position = mul(worldPosition, viewProjection);
- output.viewVector = normalize(worldPosition.xyz - viewPosition.xyz);
- output.texcoord = input.texcoord;
-
- float4 tpos = mul(float4(worldPosition.x, worldPosition.y, 0, 1),
- viewProjection);
- output.screenPosition = tpos.xyz / tpos.w;
- output.screenPosition.xy = 0.5 + 0.5 * output.screenPosition.xy *
- float2(1, -1);
- output.screenPosition.z = reflectionRefractionOffset /
- output.screenPosition.z;
-
- return output;
-}
-/**
- * Pixel Shader - pixel shader does nothing but return the color.
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- float3 viewVector = float3(input.viewVector.x,
- input.viewVector.z,
- -input.viewVector.y);
-
- float2 texcoord = input.texcoord * 4;
- float3 n1 = tex2D(noiseSampler,
- texcoord +
- float2(clock * 0.01, clock * 0.02));
- float3 n2 = tex2D(noiseSampler2,
- texcoord +
- float2(clock * 0.03, clock * 0.01));
- float3 n3 = tex2D(noiseSampler3,
- texcoord +
- float2(clock * 0.005, clock * 0.007));
-
- float3 N = normalize(n1 + n2 * 2 + n3 * 4 + float3(-3.5, 16, -3.5));
-
- float3 R = normalize(reflect(viewVector, N));
- R.y = R.y < 0.01 ? 0.01 : R.y;
-
- //float f = tex1D(fresnelSampler, dot(R, N));
- float f = tex2D(fresnelSampler, float2(dot(R, N), 0.5)).x;
- float4 reflection = tex2D(
- reflectionSampler,
- input.screenPosition.xy - input.screenPosition.z * N.xy + float2(0, 0.1));
- // I still don't understand where my math is wrong such that I need this 0.1
- // fudge factor.
-
- // Lookup the sky color
- float3 skyReflection = texCUBE(environmentSampler, R);
-
- // lerping with reflection.a means that where there is terrain reflected
- // we get terrain, otherwise we get sky.
- float3 color = lerp(skyReflection,
- reflection.rgb, reflection.a);
-
- // lookup the refraction color.
- float3 refraction = tex2D(
- refractionSampler,
- (input.screenPosition.xy - input.screenPosition.z * N.xz +
- float2(0, 0.05)) * float2(1, 0.95)); // fudge
-
- float3 finalColor = lerp(refraction, color, f);
-
- // Uncomment any one of the lines below to see just part of the water
- // calculation.
-
- //finalColor = skyReflection; // sky only.
- //finalColor = reflection.xyz; // reflection only.
- //finalColor = refraction; // refraction only.
- //finalColor = lerp(float3(0,1,0), float3(1,0,0), f); // reflection/refraction mix
- //finalColor = color; // sky only.
- return float4(finalColor, 1);
-}
-
-// Here we tell our effect file the functions
-// which specify our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_cg/waterstyle2.cg b/o3d/samples/beachdemo/shaders_cg/waterstyle2.cg
deleted file mode 100644
index 196c358..0000000
--- a/o3d/samples/beachdemo/shaders_cg/waterstyle2.cg
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
-};
-
-/**
- * Vertex Shader
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- /**
- * We transform each vertex by the world view projection matrix to bring
- * it from world space to projection space.
- *
- * We return its color unchanged.
- */
- PixelShaderInput output;
-
- output.position = mul(input.position, worldViewProjection);
- return output;
-}
-/**
- * Pixel Shader - pixel shader does nothing but return the color.
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return float4(0, 0, 0.5, 1);
-}
-
-// Here we tell our effect file the functions
-// which specify our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/beachdemo/shaders_glsl/diffuse.glsl b/o3d/samples/beachdemo/shaders_glsl/diffuse.glsl
deleted file mode 100644
index f334791..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/diffuse.glsl
+++ /dev/null
@@ -1,221 +0,0 @@
-// glslv profile log:
-// (70) : warning C7011: implicit cast from "float4" to "float3"
-// (71) : warning C7011: implicit cast from "float4" to "float3"
-// 79 lines, 2 warnings, 0 errors.
-
-// glslf profile log:
-// (70) : warning C7011: implicit cast from "float4" to "float3"
-// (71) : warning C7011: implicit cast from "float4" to "float3"
-// 79 lines, 2 warnings, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic clipHeight
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuseSampler
-//semantic specular
-//semantic shininess
-//var float4x4 world : WORLD : _ZZ2Sworld[0], 4 : -1 : 1
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : _ZZ2SworldViewProjection[0], 4 : -1 : 1
-//var float3 lightWorldPos : : : -1 : 0
-//var float4 lightColor : : : -1 : 0
-//var float clipHeight : : : -1 : 0
-//var float4x4 viewInverse : VIEWINVERSE : , 4 : -1 : 0
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : _ZZ2SworldInverseTranspose[0], 4 : -1 : 1
-//var float4 emissive : : : -1 : 0
-//var float4 ambient : : : -1 : 0
-//var sampler2D diffuseSampler : : : -1 : 0
-//var float4 specular : : : -1 : 0
-//var float shininess : : : -1 : 0
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float4 input.normal : $vin.ATTR8 : $_ZZ3SZaTMP20 : 0 : 1
-//var float2 input.diffuseUV : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-//var float2 vertexShaderFunction.diffuseUV : $vout.TEXCOORD0 : TEXCOORD0 : -1 : 1
-//var float4 vertexShaderFunction.worldPosition : $vout.TEXCOORD1 : TEXCOORD1 : -1 : 1
-//var float3 vertexShaderFunction.normal : $vout.TEXCOORD2 : TEXCOORD2 : -1 : 1
-
-attribute vec4 position;
-attribute vec4 texcoord0;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct InVertex {
- vec4 position;
- vec4 normal;
- vec2 diffuseUV;
-};
-
-struct OutVertex {
- vec4 position;
- vec2 diffuseUV;
- vec4 worldPosition;
- vec3 normal;
-};
-
-OutVertex _ZZ3Sret_0;
-vec4 _ZZ3SrZh0015;
-vec4 _ZZ3SrZh0017;
-vec4 _ZZ3SrZh0019;
-vec4 _ZZ3SvZh0019;
-attribute vec4 normal;
-uniform mat4 world;
-uniform mat4 worldViewProjection;
-uniform mat4 worldInverseTranspose;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
-
- _ZZ3SrZh0015 = position.x*worldViewProjection[0];
- _ZZ3SrZh0015 = _ZZ3SrZh0015 + position.y*worldViewProjection[1];
- _ZZ3SrZh0015 = _ZZ3SrZh0015 + position.z*worldViewProjection[2];
- _ZZ3SrZh0015 = _ZZ3SrZh0015 + position.w*worldViewProjection[3];
- _ZZ3SrZh0017 = position.x*world[0];
- _ZZ3SrZh0017 = _ZZ3SrZh0017 + position.y*world[1];
- _ZZ3SrZh0017 = _ZZ3SrZh0017 + position.z*world[2];
- _ZZ3SrZh0017 = _ZZ3SrZh0017 + position.w*world[3];
- _ZZ3SvZh0019 = vec4(normal.x, normal.y, normal.z, 0.00000000E+00);
- _ZZ3SrZh0019 = _ZZ3SvZh0019.x*worldInverseTranspose[0];
- _ZZ3SrZh0019 = _ZZ3SrZh0019 + _ZZ3SvZh0019.y*worldInverseTranspose[1];
- _ZZ3SrZh0019 = _ZZ3SrZh0019 + _ZZ3SvZh0019.z*worldInverseTranspose[2];
- _ZZ3SrZh0019 = _ZZ3SrZh0019 + _ZZ3SvZh0019.w*worldInverseTranspose[3];
- _ZZ3SrZh0019.xyz;
- _ZZ3Sret_0.position = _ZZ3SrZh0015;
- _ZZ3Sret_0.diffuseUV = texcoord0.xy;
- _ZZ3Sret_0.worldPosition = _ZZ3SrZh0017;
- _ZZ3Sret_0.normal = _ZZ3SrZh0019.xyz;
- gl_TexCoord[0].xy = texcoord0.xy;
- gl_TexCoord[2].xyz = _ZZ3SrZh0019.xyz;
- _glPositionTemp = _ZZ3SrZh0015; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- gl_TexCoord[1] = _ZZ3SrZh0017;
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic clipHeight
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuseSampler
-//semantic specular
-//semantic shininess
-//var float4x4 world : WORLD : , 4 : -1 : 0
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float3 lightWorldPos : : _ZZ2SlightWorldPos : -1 : 1
-//var float4 lightColor : : _ZZ2SlightColor : -1 : 1
-//var float clipHeight : : _ZZ2SclipHeight : -1 : 1
-//var float4x4 viewInverse : VIEWINVERSE : _ZZ2SviewInverse[0], 4 : -1 : 1
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : , 4 : -1 : 0
-//var float4 emissive : : _ZZ2Semissive : -1 : 1
-//var float4 ambient : : _ZZ2Sambient : -1 : 1
-//var sampler2D diffuseSampler : : _ZZ2SdiffuseSampler : -1 : 1
-//var float4 specular : : _ZZ2Sspecular : -1 : 1
-//var float shininess : : _ZZ2Sshininess : -1 : 1
-//var float2 input.diffuseUV : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float4 input.worldPosition : $vin.TEXCOORD1 : TEXCOORD1 : 0 : 1
-//var float3 input.normal : $vin.TEXCOORD2 : TEXCOORD2 : 0 : 1
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct InVertex {
- vec4 normal;
- vec2 diffuseUV;
-};
-
-struct OutVertex {
- vec2 diffuseUV;
- vec4 worldPosition;
- vec3 normal;
-};
-
-vec4 _ZZ3Sret_0;
-vec3 _ZZ3SZDtemp16;
-float _ZZ3SxZh0021;
-vec3 _ZZ3SZDtemp22;
-vec3 _ZZ3SvZh0023;
-float _ZZ3SxZh0027;
-vec4 _ZZ3SZDtemp28;
-vec4 _ZZ3SvZh0029;
-float _ZZ3SxZh0033;
-vec3 _ZZ3SZDtemp34;
-vec3 _ZZ3SvZh0035;
-float _ZZ3SxZh0039;
-vec4 _ZZ3StmpZh0045;
-float _ZZ3SndotlZh0045;
-float _ZZ3SndothZh0045;
-vec4 _ZZ3SZDtemp46;
-float _ZZ3SspecularZh0047;
-float _ZZ3SxZh0051;
-uniform vec3 lightWorldPos;
-uniform vec4 lightColor;
-uniform float clipHeight;
-uniform mat4 viewInverse;
-uniform vec4 emissive;
-uniform vec4 ambient;
-uniform sampler2D diffuseSampler;
-uniform vec4 specular;
-uniform float shininess;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
- vec4 _ZZ4Sdiffuse;
- float _ZZ4Salpha;
- vec3 _ZZ4SZaTMP1;
-
- _ZZ4Sdiffuse = texture2D(diffuseSampler, gl_TexCoord[0].xy);
- _ZZ3SxZh0021 = dot(gl_TexCoord[2].xyz, gl_TexCoord[2].xyz);
- _ZZ3SZDtemp16 = inversesqrt(_ZZ3SxZh0021)*gl_TexCoord[2].xyz;
- _ZZ3SvZh0023 = lightWorldPos - gl_TexCoord[1].xyz;
- _ZZ3SxZh0027 = dot(_ZZ3SvZh0023, _ZZ3SvZh0023);
- _ZZ3SZDtemp22 = inversesqrt(_ZZ3SxZh0027)*_ZZ3SvZh0023;
- _ZZ3SvZh0029 = viewInverse[3] - gl_TexCoord[1];
- _ZZ3SxZh0033 = dot(_ZZ3SvZh0029, _ZZ3SvZh0029);
- _ZZ3SZDtemp28 = inversesqrt(_ZZ3SxZh0033)*_ZZ3SvZh0029;
- _ZZ3SvZh0035 = _ZZ3SZDtemp22 + _ZZ3SZDtemp28.xyz;
- _ZZ3SxZh0039 = dot(_ZZ3SvZh0035, _ZZ3SvZh0035);
- _ZZ3SZDtemp34 = inversesqrt(_ZZ3SxZh0039)*_ZZ3SvZh0035;
- _ZZ3SndotlZh0045 = dot(_ZZ3SZDtemp16, _ZZ3SZDtemp22);
- _ZZ3SndothZh0045 = dot(_ZZ3SZDtemp16, _ZZ3SZDtemp34);
- _ZZ3StmpZh0045 = vec4(_ZZ3SndotlZh0045, _ZZ3SndothZh0045, shininess, shininess);
- _ZZ3SxZh0051 = max(0.00000000E+00, _ZZ3StmpZh0045.y);
- _ZZ3SspecularZh0047 = _ZZ3StmpZh0045.x > 0.00000000E+00 ? pow(_ZZ3SxZh0051, _ZZ3StmpZh0045.z) : 0.00000000E+00;
- _ZZ3SZDtemp46 = vec4(1.00000000E+00, max(0.00000000E+00, _ZZ3StmpZh0045.x), _ZZ3SspecularZh0047, 1.00000000E+00);
- _ZZ4Salpha = gl_TexCoord[1].z > clipHeight ? 0.00000000E+00 : _ZZ4Sdiffuse.w;
- _ZZ4SZaTMP1 = (emissive + lightColor*(ambient*_ZZ4Sdiffuse + _ZZ4Sdiffuse*_ZZ3SZDtemp46.y + specular*_ZZ3SZDtemp46.z)).xyz;
- _ZZ3Sret_0 = vec4(_ZZ4SZaTMP1.x, _ZZ4SZaTMP1.y, _ZZ4SZaTMP1.z, _ZZ4Salpha);
- gl_FragColor = _ZZ3Sret_0;
- return;
-} // main end
-
diff --git a/o3d/samples/beachdemo/shaders_glsl/diffuse_bump.glsl b/o3d/samples/beachdemo/shaders_glsl/diffuse_bump.glsl
deleted file mode 100644
index 9e65bd7..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/diffuse_bump.glsl
+++ /dev/null
@@ -1,268 +0,0 @@
-// glslv profile log:
-// (83) : warning C7011: implicit cast from "float4" to "float3"
-// (84) : warning C7011: implicit cast from "float4" to "float3"
-// 98 lines, 2 warnings, 0 errors.
-
-// glslf profile log:
-// (83) : warning C7011: implicit cast from "float4" to "float3"
-// (84) : warning C7011: implicit cast from "float4" to "float3"
-// 98 lines, 2 warnings, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic clipHeight
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuseSampler
-//semantic specular
-//semantic bumpSampler
-//semantic shininess
-//var float4x4 world : WORLD : _ZZ2Sworld[0], 4 : -1 : 1
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : _ZZ2SworldViewProjection[0], 4 : -1 : 1
-//var float3 lightWorldPos : : : -1 : 0
-//var float4 lightColor : : : -1 : 0
-//var float clipHeight : : : -1 : 0
-//var float4x4 viewInverse : VIEWINVERSE : , 4 : -1 : 0
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : _ZZ2SworldInverseTranspose[0], 4 : -1 : 1
-//var float4 emissive : : : -1 : 0
-//var float4 ambient : : : -1 : 0
-//var sampler2D diffuseSampler : : : -1 : 0
-//var float4 specular : : : -1 : 0
-//var sampler2D bumpSampler : : : -1 : 0
-//var float shininess : : : -1 : 0
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float4 input.normal : $vin.ATTR8 : $_ZZ3SZaTMP29 : 0 : 1
-//var float2 input.diffuseUV : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float3 input.tangent : $vin.ATTR9 : $_ZZ3SZaTMP30 : 0 : 1
-//var float3 input.binormal : $vin.ATTR10 : $_ZZ3SZaTMP31 : 0 : 1
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-//var float2 vertexShaderFunction.diffuseUV : $vout.TEXCOORD0 : TEXCOORD0 : -1 : 1
-//var float3 vertexShaderFunction.tangent : $vout.TEXCOORD1 : TEXCOORD1 : -1 : 1
-//var float3 vertexShaderFunction.binormal : $vout.TEXCOORD2 : TEXCOORD2 : -1 : 1
-//var float4 vertexShaderFunction.worldPosition : $vout.TEXCOORD3 : TEXCOORD3 : -1 : 1
-//var float3 vertexShaderFunction.normal : $vout.TEXCOORD4 : TEXCOORD4 : -1 : 1
-
-attribute vec4 position;
-attribute vec4 texcoord0;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct InVertex {
- vec4 position;
- vec4 normal;
- vec2 diffuseUV;
- vec3 tangent;
- vec3 binormal;
-};
-
-struct OutVertex {
- vec4 position;
- vec2 diffuseUV;
- vec3 tangent;
- vec3 binormal;
- vec4 worldPosition;
- vec3 normal;
-};
-
-OutVertex _ZZ3Sret_0;
-vec4 _ZZ3SrZh0020;
-vec4 _ZZ3SrZh0022;
-vec4 _ZZ3SrZh0024;
-vec4 _ZZ3SvZh0024;
-vec4 _ZZ3SrZh0026;
-vec4 _ZZ3SvZh0026;
-vec4 _ZZ3SrZh0028;
-vec4 _ZZ3SvZh0028;
-attribute vec4 normal;
-attribute vec4 tangent;
-attribute vec4 binormal;
-uniform mat4 world;
-uniform mat4 worldViewProjection;
-uniform mat4 worldInverseTranspose;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
-
- _ZZ3SrZh0020 = position.x*worldViewProjection[0];
- _ZZ3SrZh0020 = _ZZ3SrZh0020 + position.y*worldViewProjection[1];
- _ZZ3SrZh0020 = _ZZ3SrZh0020 + position.z*worldViewProjection[2];
- _ZZ3SrZh0020 = _ZZ3SrZh0020 + position.w*worldViewProjection[3];
- _ZZ3SrZh0022 = position.x*world[0];
- _ZZ3SrZh0022 = _ZZ3SrZh0022 + position.y*world[1];
- _ZZ3SrZh0022 = _ZZ3SrZh0022 + position.z*world[2];
- _ZZ3SrZh0022 = _ZZ3SrZh0022 + position.w*world[3];
- _ZZ3SvZh0024 = vec4(normal.x, normal.y, normal.z, 0.00000000E+00);
- _ZZ3SrZh0024 = _ZZ3SvZh0024.x*worldInverseTranspose[0];
- _ZZ3SrZh0024 = _ZZ3SrZh0024 + _ZZ3SvZh0024.y*worldInverseTranspose[1];
- _ZZ3SrZh0024 = _ZZ3SrZh0024 + _ZZ3SvZh0024.z*worldInverseTranspose[2];
- _ZZ3SrZh0024 = _ZZ3SrZh0024 + _ZZ3SvZh0024.w*worldInverseTranspose[3];
- _ZZ3SrZh0024.xyz;
- _ZZ3SvZh0026 = vec4(binormal.x, binormal.y, binormal.z, 0.00000000E+00);
- _ZZ3SrZh0026 = _ZZ3SvZh0026.x*worldInverseTranspose[0];
- _ZZ3SrZh0026 = _ZZ3SrZh0026 + _ZZ3SvZh0026.y*worldInverseTranspose[1];
- _ZZ3SrZh0026 = _ZZ3SrZh0026 + _ZZ3SvZh0026.z*worldInverseTranspose[2];
- _ZZ3SrZh0026 = _ZZ3SrZh0026 + _ZZ3SvZh0026.w*worldInverseTranspose[3];
- _ZZ3SrZh0026.xyz;
- _ZZ3SvZh0028 = vec4(tangent.x, tangent.y, tangent.z, 0.00000000E+00);
- _ZZ3SrZh0028 = _ZZ3SvZh0028.x*worldInverseTranspose[0];
- _ZZ3SrZh0028 = _ZZ3SrZh0028 + _ZZ3SvZh0028.y*worldInverseTranspose[1];
- _ZZ3SrZh0028 = _ZZ3SrZh0028 + _ZZ3SvZh0028.z*worldInverseTranspose[2];
- _ZZ3SrZh0028 = _ZZ3SrZh0028 + _ZZ3SvZh0028.w*worldInverseTranspose[3];
- _ZZ3SrZh0028.xyz;
- _ZZ3Sret_0.position = _ZZ3SrZh0020;
- _ZZ3Sret_0.diffuseUV = texcoord0.xy;
- _ZZ3Sret_0.tangent = _ZZ3SrZh0028.xyz;
- _ZZ3Sret_0.binormal = _ZZ3SrZh0026.xyz;
- _ZZ3Sret_0.worldPosition = _ZZ3SrZh0022;
- _ZZ3Sret_0.normal = _ZZ3SrZh0024.xyz;
- gl_TexCoord[0].xy = texcoord0.xy;
- gl_TexCoord[2].xyz = _ZZ3SrZh0026.xyz;
- _glPositionTemp = _ZZ3SrZh0020; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- gl_TexCoord[4].xyz = _ZZ3SrZh0024.xyz;
- gl_TexCoord[1].xyz = _ZZ3SrZh0028.xyz;
- gl_TexCoord[3] = _ZZ3SrZh0022;
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic clipHeight
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuseSampler
-//semantic specular
-//semantic bumpSampler
-//semantic shininess
-//var float4x4 world : WORLD : , 4 : -1 : 0
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float3 lightWorldPos : : _ZZ2SlightWorldPos : -1 : 1
-//var float4 lightColor : : _ZZ2SlightColor : -1 : 1
-//var float clipHeight : : _ZZ2SclipHeight : -1 : 1
-//var float4x4 viewInverse : VIEWINVERSE : _ZZ2SviewInverse[0], 4 : -1 : 1
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : , 4 : -1 : 0
-//var float4 emissive : : _ZZ2Semissive : -1 : 1
-//var float4 ambient : : _ZZ2Sambient : -1 : 1
-//var sampler2D diffuseSampler : : _ZZ2SdiffuseSampler : -1 : 1
-//var float4 specular : : _ZZ2Sspecular : -1 : 1
-//var sampler2D bumpSampler : : _ZZ2SbumpSampler : -1 : 1
-//var float shininess : : _ZZ2Sshininess : -1 : 1
-//var float2 input.diffuseUV : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float3 input.tangent : $vin.TEXCOORD1 : TEXCOORD1 : 0 : 1
-//var float3 input.binormal : $vin.TEXCOORD2 : TEXCOORD2 : 0 : 1
-//var float4 input.worldPosition : $vin.TEXCOORD3 : TEXCOORD3 : 0 : 1
-//var float3 input.normal : $vin.TEXCOORD4 : TEXCOORD4 : 0 : 1
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct InVertex {
- vec4 normal;
- vec2 diffuseUV;
- vec3 tangent;
- vec3 binormal;
-};
-
-struct OutVertex {
- vec2 diffuseUV;
- vec3 tangent;
- vec3 binormal;
- vec4 worldPosition;
- vec3 normal;
-};
-
-vec4 _ZZ3Sret_0;
-vec3 _ZZ3SrZh0026;
-vec3 _ZZ3SZDtemp27;
-float _ZZ3SxZh0032;
-vec3 _ZZ3SZDtemp33;
-vec3 _ZZ3SvZh0034;
-float _ZZ3SxZh0038;
-vec4 _ZZ3SZDtemp39;
-vec4 _ZZ3SvZh0040;
-float _ZZ3SxZh0044;
-vec3 _ZZ3SZDtemp45;
-vec3 _ZZ3SvZh0046;
-float _ZZ3SxZh0050;
-vec4 _ZZ3StmpZh0056;
-float _ZZ3SndotlZh0056;
-float _ZZ3SndothZh0056;
-vec4 _ZZ3SZDtemp57;
-float _ZZ3SspecularZh0058;
-float _ZZ3SxZh0062;
-uniform vec3 lightWorldPos;
-uniform vec4 lightColor;
-uniform float clipHeight;
-uniform mat4 viewInverse;
-uniform vec4 emissive;
-uniform vec4 ambient;
-uniform sampler2D diffuseSampler;
-uniform vec4 specular;
-uniform sampler2D bumpSampler;
-uniform float shininess;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
- vec4 _ZZ4Sdiffuse;
- vec3 _ZZ4StangentNormal;
- float _ZZ4Salpha;
- vec3 _ZZ4SZaTMP4;
-
- _ZZ4Sdiffuse = texture2D(diffuseSampler, gl_TexCoord[0].xy);
- _ZZ4StangentNormal = texture2D(bumpSampler, gl_TexCoord[0].xy).xyz - vec3( 5.00000000E-01, 5.00000000E-01, 5.00000000E-01);
- _ZZ3SrZh0026 = _ZZ4StangentNormal.x*gl_TexCoord[1].xyz;
- _ZZ3SrZh0026 = _ZZ3SrZh0026 + _ZZ4StangentNormal.y*gl_TexCoord[2].xyz;
- _ZZ3SrZh0026 = _ZZ3SrZh0026 + _ZZ4StangentNormal.z*gl_TexCoord[4].xyz;
- _ZZ3SxZh0032 = dot(_ZZ3SrZh0026, _ZZ3SrZh0026);
- _ZZ3SZDtemp27 = inversesqrt(_ZZ3SxZh0032)*_ZZ3SrZh0026;
- _ZZ3SvZh0034 = lightWorldPos - gl_TexCoord[3].xyz;
- _ZZ3SxZh0038 = dot(_ZZ3SvZh0034, _ZZ3SvZh0034);
- _ZZ3SZDtemp33 = inversesqrt(_ZZ3SxZh0038)*_ZZ3SvZh0034;
- _ZZ3SvZh0040 = viewInverse[3] - gl_TexCoord[3];
- _ZZ3SxZh0044 = dot(_ZZ3SvZh0040, _ZZ3SvZh0040);
- _ZZ3SZDtemp39 = inversesqrt(_ZZ3SxZh0044)*_ZZ3SvZh0040;
- _ZZ3SvZh0046 = _ZZ3SZDtemp33 + _ZZ3SZDtemp39.xyz;
- _ZZ3SxZh0050 = dot(_ZZ3SvZh0046, _ZZ3SvZh0046);
- _ZZ3SZDtemp45 = inversesqrt(_ZZ3SxZh0050)*_ZZ3SvZh0046;
- _ZZ3SndotlZh0056 = dot(_ZZ3SZDtemp27, _ZZ3SZDtemp33);
- _ZZ3SndothZh0056 = dot(_ZZ3SZDtemp27, _ZZ3SZDtemp45);
- _ZZ3StmpZh0056 = vec4(_ZZ3SndotlZh0056, _ZZ3SndothZh0056, shininess, shininess);
- _ZZ3SxZh0062 = max(0.00000000E+00, _ZZ3StmpZh0056.y);
- _ZZ3SspecularZh0058 = _ZZ3StmpZh0056.x > 0.00000000E+00 ? pow(_ZZ3SxZh0062, _ZZ3StmpZh0056.z) : 0.00000000E+00;
- _ZZ3SZDtemp57 = vec4(1.00000000E+00, max(0.00000000E+00, _ZZ3StmpZh0056.x), _ZZ3SspecularZh0058, 1.00000000E+00);
- _ZZ4Salpha = gl_TexCoord[3].z > clipHeight ? 0.00000000E+00 : _ZZ4Sdiffuse.w;
- _ZZ4SZaTMP4 = (emissive + lightColor*(ambient*_ZZ4Sdiffuse + _ZZ4Sdiffuse*_ZZ3SZDtemp57.y + specular*_ZZ3SZDtemp57.z)).xyz;
- _ZZ3Sret_0 = vec4(_ZZ4SZaTMP4.x, _ZZ4SZaTMP4.y, _ZZ4SZaTMP4.z, _ZZ4Salpha);
- gl_FragColor = _ZZ3Sret_0;
- return;
-} // main end
-
diff --git a/o3d/samples/beachdemo/shaders_glsl/diffuse_bump_2textures.glsl b/o3d/samples/beachdemo/shaders_glsl/diffuse_bump_2textures.glsl
deleted file mode 100644
index 6b679fb..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/diffuse_bump_2textures.glsl
+++ /dev/null
@@ -1,279 +0,0 @@
-// glslv profile log:
-// (88) : warning C7011: implicit cast from "float4" to "float3"
-// (89) : warning C7011: implicit cast from "float4" to "float3"
-// 103 lines, 2 warnings, 0 errors.
-
-// glslf profile log:
-// (88) : warning C7011: implicit cast from "float4" to "float3"
-// (89) : warning C7011: implicit cast from "float4" to "float3"
-// 103 lines, 2 warnings, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuseSampler
-//semantic diffuse2Sampler
-//semantic specular
-//semantic bumpSampler
-//semantic shininess
-//var float4x4 world : WORLD : _ZZ2Sworld[0], 4 : -1 : 1
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : _ZZ2SworldViewProjection[0], 4 : -1 : 1
-//var float3 lightWorldPos : : : -1 : 0
-//var float4 lightColor : : : -1 : 0
-//var float4x4 viewInverse : VIEWINVERSE : , 4 : -1 : 0
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : _ZZ2SworldInverseTranspose[0], 4 : -1 : 1
-//var float4 emissive : : : -1 : 0
-//var float4 ambient : : : -1 : 0
-//var sampler2D diffuseSampler : : : -1 : 0
-//var sampler2D diffuse2Sampler : : : -1 : 0
-//var float4 specular : : : -1 : 0
-//var sampler2D bumpSampler : : : -1 : 0
-//var float shininess : : : -1 : 0
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float4 input.normal : $vin.ATTR8 : $_ZZ3SZaTMP29 : 0 : 1
-//var float2 input.diffuseUV : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float3 input.tangent : $vin.ATTR9 : $_ZZ3SZaTMP30 : 0 : 1
-//var float3 input.binormal : $vin.ATTR10 : $_ZZ3SZaTMP31 : 0 : 1
-//var float4 input.color : $vin.COLOR : COLOR : 0 : 1
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-//var float2 vertexShaderFunction.diffuseUV : $vout.TEXCOORD0 : TEXCOORD0 : -1 : 1
-//var float3 vertexShaderFunction.tangent : $vout.TEXCOORD1 : TEXCOORD1 : -1 : 1
-//var float3 vertexShaderFunction.binormal : $vout.TEXCOORD2 : TEXCOORD2 : -1 : 1
-//var float4 vertexShaderFunction.worldPosition : $vout.TEXCOORD3 : TEXCOORD3 : -1 : 1
-//var float3 vertexShaderFunction.normal : $vout.TEXCOORD4 : TEXCOORD4 : -1 : 1
-//var float4 vertexShaderFunction.color : $vout.COLOR : COLOR : -1 : 1
-
-attribute vec4 position;
-attribute vec4 texcoord0;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct InVertex {
- vec4 position;
- vec4 normal;
- vec2 diffuseUV;
- vec3 tangent;
- vec3 binormal;
- vec4 color;
-};
-
-struct OutVertex {
- vec4 position;
- vec2 diffuseUV;
- vec3 tangent;
- vec3 binormal;
- vec4 worldPosition;
- vec3 normal;
- vec4 color;
-};
-
-OutVertex _ZZ3Sret_0;
-vec4 _ZZ3SrZh0020;
-vec4 _ZZ3SrZh0022;
-vec4 _ZZ3SrZh0024;
-vec4 _ZZ3SvZh0024;
-vec4 _ZZ3SrZh0026;
-vec4 _ZZ3SvZh0026;
-vec4 _ZZ3SrZh0028;
-vec4 _ZZ3SvZh0028;
-attribute vec4 normal;
-attribute vec4 tangent;
-attribute vec4 binormal;
-uniform mat4 world;
-uniform mat4 worldViewProjection;
-uniform mat4 worldInverseTranspose;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
-
- _ZZ3SrZh0020 = position.x*worldViewProjection[0];
- _ZZ3SrZh0020 = _ZZ3SrZh0020 + position.y*worldViewProjection[1];
- _ZZ3SrZh0020 = _ZZ3SrZh0020 + position.z*worldViewProjection[2];
- _ZZ3SrZh0020 = _ZZ3SrZh0020 + position.w*worldViewProjection[3];
- _ZZ3SrZh0022 = position.x*world[0];
- _ZZ3SrZh0022 = _ZZ3SrZh0022 + position.y*world[1];
- _ZZ3SrZh0022 = _ZZ3SrZh0022 + position.z*world[2];
- _ZZ3SrZh0022 = _ZZ3SrZh0022 + position.w*world[3];
- _ZZ3SvZh0024 = vec4(normal.x, normal.y, normal.z, 0.00000000E+00);
- _ZZ3SrZh0024 = _ZZ3SvZh0024.x*worldInverseTranspose[0];
- _ZZ3SrZh0024 = _ZZ3SrZh0024 + _ZZ3SvZh0024.y*worldInverseTranspose[1];
- _ZZ3SrZh0024 = _ZZ3SrZh0024 + _ZZ3SvZh0024.z*worldInverseTranspose[2];
- _ZZ3SrZh0024 = _ZZ3SrZh0024 + _ZZ3SvZh0024.w*worldInverseTranspose[3];
- _ZZ3SrZh0024.xyz;
- _ZZ3SvZh0026 = vec4(binormal.x, binormal.y, binormal.z, 0.00000000E+00);
- _ZZ3SrZh0026 = _ZZ3SvZh0026.x*worldInverseTranspose[0];
- _ZZ3SrZh0026 = _ZZ3SrZh0026 + _ZZ3SvZh0026.y*worldInverseTranspose[1];
- _ZZ3SrZh0026 = _ZZ3SrZh0026 + _ZZ3SvZh0026.z*worldInverseTranspose[2];
- _ZZ3SrZh0026 = _ZZ3SrZh0026 + _ZZ3SvZh0026.w*worldInverseTranspose[3];
- _ZZ3SrZh0026.xyz;
- _ZZ3SvZh0028 = vec4(tangent.x, tangent.y, tangent.z, 0.00000000E+00);
- _ZZ3SrZh0028 = _ZZ3SvZh0028.x*worldInverseTranspose[0];
- _ZZ3SrZh0028 = _ZZ3SrZh0028 + _ZZ3SvZh0028.y*worldInverseTranspose[1];
- _ZZ3SrZh0028 = _ZZ3SrZh0028 + _ZZ3SvZh0028.z*worldInverseTranspose[2];
- _ZZ3SrZh0028 = _ZZ3SrZh0028 + _ZZ3SvZh0028.w*worldInverseTranspose[3];
- _ZZ3SrZh0028.xyz;
- _ZZ3Sret_0.position = _ZZ3SrZh0020;
- _ZZ3Sret_0.diffuseUV = texcoord0.xy;
- _ZZ3Sret_0.tangent = _ZZ3SrZh0028.xyz;
- _ZZ3Sret_0.binormal = _ZZ3SrZh0026.xyz;
- _ZZ3Sret_0.worldPosition = _ZZ3SrZh0022;
- _ZZ3Sret_0.normal = _ZZ3SrZh0024.xyz;
- _ZZ3Sret_0.color = gl_Color;
- gl_FrontColor = gl_Color;
- gl_TexCoord[0].xy = texcoord0.xy;
- gl_TexCoord[2].xyz = _ZZ3SrZh0026.xyz;
- _glPositionTemp = _ZZ3SrZh0020; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- gl_TexCoord[4].xyz = _ZZ3SrZh0024.xyz;
- gl_TexCoord[1].xyz = _ZZ3SrZh0028.xyz;
- gl_TexCoord[3] = _ZZ3SrZh0022;
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuseSampler
-//semantic diffuse2Sampler
-//semantic specular
-//semantic bumpSampler
-//semantic shininess
-//var float4x4 world : WORLD : , 4 : -1 : 0
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float3 lightWorldPos : : _ZZ2SlightWorldPos : -1 : 1
-//var float4 lightColor : : : -1 : 0
-//var float4x4 viewInverse : VIEWINVERSE : _ZZ2SviewInverse[0], 4 : -1 : 1
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : , 4 : -1 : 0
-//var float4 emissive : : _ZZ2Semissive : -1 : 1
-//var float4 ambient : : _ZZ2Sambient : -1 : 1
-//var sampler2D diffuseSampler : : _ZZ2SdiffuseSampler : -1 : 1
-//var sampler2D diffuse2Sampler : : _ZZ2Sdiffuse2Sampler : -1 : 1
-//var float4 specular : : _ZZ2Sspecular : -1 : 1
-//var sampler2D bumpSampler : : _ZZ2SbumpSampler : -1 : 1
-//var float shininess : : _ZZ2Sshininess : -1 : 1
-//var float2 input.diffuseUV : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float3 input.tangent : $vin.TEXCOORD1 : TEXCOORD1 : 0 : 1
-//var float3 input.binormal : $vin.TEXCOORD2 : TEXCOORD2 : 0 : 1
-//var float4 input.worldPosition : $vin.TEXCOORD3 : TEXCOORD3 : 0 : 1
-//var float3 input.normal : $vin.TEXCOORD4 : TEXCOORD4 : 0 : 1
-//var float4 input.color : $vin.COLOR : COLOR : 0 : 1
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct InVertex {
- vec4 normal;
- vec2 diffuseUV;
- vec3 tangent;
- vec3 binormal;
- vec4 color;
-};
-
-struct OutVertex {
- vec2 diffuseUV;
- vec3 tangent;
- vec3 binormal;
- vec4 worldPosition;
- vec3 normal;
- vec4 color;
-};
-
-vec4 _ZZ3Sret_0;
-vec3 _ZZ3SrZh0030;
-vec3 _ZZ3SZDtemp31;
-float _ZZ3SxZh0036;
-vec3 _ZZ3SZDtemp37;
-vec3 _ZZ3SvZh0038;
-float _ZZ3SxZh0042;
-vec4 _ZZ3SZDtemp43;
-vec4 _ZZ3SvZh0044;
-float _ZZ3SxZh0048;
-vec3 _ZZ3SZDtemp49;
-vec3 _ZZ3SvZh0050;
-float _ZZ3SxZh0054;
-vec4 _ZZ3StmpZh0060;
-float _ZZ3SndotlZh0060;
-float _ZZ3SndothZh0060;
-vec4 _ZZ3SZDtemp61;
-float _ZZ3SspecularZh0062;
-float _ZZ3SxZh0066;
-uniform vec3 lightWorldPos;
-uniform mat4 viewInverse;
-uniform vec4 emissive;
-uniform vec4 ambient;
-uniform sampler2D diffuseSampler;
-uniform sampler2D diffuse2Sampler;
-uniform vec4 specular;
-uniform sampler2D bumpSampler;
-uniform float shininess;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
- vec4 _ZZ4Sdiffuse;
- vec4 _ZZ4Sdiffuse2;
- vec3 _ZZ4StangentNormal;
- float _ZZ4Salpha;
- vec3 _ZZ4SZaTMP4;
-
- _ZZ4Sdiffuse = texture2D(diffuseSampler, gl_TexCoord[0].xy);
- _ZZ4Sdiffuse2 = texture2D(diffuse2Sampler, gl_TexCoord[0].xy);
- _ZZ4Sdiffuse = _ZZ4Sdiffuse + gl_Color*(_ZZ4Sdiffuse2 - _ZZ4Sdiffuse);
- _ZZ4StangentNormal = texture2D(bumpSampler, gl_TexCoord[0].xy).xyz - vec3( 5.00000000E-01, 5.00000000E-01, 5.00000000E-01);
- _ZZ3SrZh0030 = _ZZ4StangentNormal.x*gl_TexCoord[1].xyz;
- _ZZ3SrZh0030 = _ZZ3SrZh0030 + _ZZ4StangentNormal.y*gl_TexCoord[2].xyz;
- _ZZ3SrZh0030 = _ZZ3SrZh0030 + _ZZ4StangentNormal.z*gl_TexCoord[4].xyz;
- _ZZ3SxZh0036 = dot(_ZZ3SrZh0030, _ZZ3SrZh0030);
- _ZZ3SZDtemp31 = inversesqrt(_ZZ3SxZh0036)*_ZZ3SrZh0030;
- _ZZ3SvZh0038 = lightWorldPos - gl_TexCoord[3].xyz;
- _ZZ3SxZh0042 = dot(_ZZ3SvZh0038, _ZZ3SvZh0038);
- _ZZ3SZDtemp37 = inversesqrt(_ZZ3SxZh0042)*_ZZ3SvZh0038;
- _ZZ3SvZh0044 = viewInverse[3] - gl_TexCoord[3];
- _ZZ3SxZh0048 = dot(_ZZ3SvZh0044, _ZZ3SvZh0044);
- _ZZ3SZDtemp43 = inversesqrt(_ZZ3SxZh0048)*_ZZ3SvZh0044;
- _ZZ3SvZh0050 = _ZZ3SZDtemp37 + _ZZ3SZDtemp43.xyz;
- _ZZ3SxZh0054 = dot(_ZZ3SvZh0050, _ZZ3SvZh0050);
- _ZZ3SZDtemp49 = inversesqrt(_ZZ3SxZh0054)*_ZZ3SvZh0050;
- _ZZ3SndotlZh0060 = dot(_ZZ3SZDtemp31, _ZZ3SZDtemp37);
- _ZZ3SndothZh0060 = dot(_ZZ3SZDtemp31, _ZZ3SZDtemp49);
- _ZZ3StmpZh0060 = vec4(_ZZ3SndotlZh0060, _ZZ3SndothZh0060, shininess, shininess);
- _ZZ3SxZh0066 = max(0.00000000E+00, _ZZ3StmpZh0060.y);
- _ZZ3SspecularZh0062 = _ZZ3StmpZh0060.x > 0.00000000E+00 ? pow(_ZZ3SxZh0066, _ZZ3StmpZh0060.z) : 0.00000000E+00;
- _ZZ3SZDtemp61 = vec4(1.00000000E+00, max(0.00000000E+00, _ZZ3StmpZh0060.x), _ZZ3SspecularZh0062, 1.00000000E+00);
- _ZZ4Salpha = gl_TexCoord[3].z < 0.00000000E+00 ? _ZZ4Sdiffuse.w : 0.00000000E+00;
- _ZZ4SZaTMP4 = (emissive + ambient*_ZZ4Sdiffuse + _ZZ4Sdiffuse*_ZZ3SZDtemp61.y + specular*_ZZ3SZDtemp61.z).xyz;
- _ZZ3Sret_0 = vec4(_ZZ4SZaTMP4.x, _ZZ4SZaTMP4.y, _ZZ4SZaTMP4.z, _ZZ4Salpha);
- gl_FragColor = _ZZ3Sret_0;
- return;
-} // main end
-
diff --git a/o3d/samples/beachdemo/shaders_glsl/diffuse_bump_blend.glsl b/o3d/samples/beachdemo/shaders_glsl/diffuse_bump_blend.glsl
deleted file mode 100644
index ae9325b..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/diffuse_bump_blend.glsl
+++ /dev/null
@@ -1,337 +0,0 @@
-// glslv profile log:
-// (100) : warning C7011: implicit cast from "float4" to "float3"
-// (101) : warning C7011: implicit cast from "float4" to "float3"
-// (72) : warning C7050: "output.color" might be used before being initialized
-// 116 lines, 3 warnings, 0 errors.
-
-// glslf profile log:
-// (100) : warning C7011: implicit cast from "float4" to "float3"
-// (101) : warning C7011: implicit cast from "float4" to "float3"
-// 116 lines, 2 warnings, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic clipHeight
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuseSampler
-//semantic diffuse2Sampler
-//semantic specular
-//semantic bumpSampler
-//semantic shininess
-//var float4x4 world : WORLD : _ZZ2Sworld[0], 4 : -1 : 1
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : _ZZ2SworldViewProjection[0], 4 : -1 : 1
-//var float3 lightWorldPos : : : -1 : 0
-//var float4 lightColor : : : -1 : 0
-//var float clipHeight : : : -1 : 0
-//var float4x4 viewInverse : VIEWINVERSE : , 4 : -1 : 0
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : _ZZ2SworldInverseTranspose[0], 4 : -1 : 1
-//var float4 emissive : : : -1 : 0
-//var float4 ambient : : : -1 : 0
-//var sampler2D diffuseSampler : : : -1 : 0
-//var sampler2D diffuse2Sampler : : : -1 : 0
-//var float4 specular : : : -1 : 0
-//var sampler2D bumpSampler : : : -1 : 0
-//var float shininess : : : -1 : 0
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float4 input.normal : $vin.ATTR8 : $_ZZ3SZaTMP42 : 0 : 1
-//var float2 input.diffuseUV : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float2 input.diffuse2UV : $vin.TEXCOORD1 : TEXCOORD1 : 0 : 1
-//var float3 input.tangent : $vin.ATTR9 : $_ZZ3SZaTMP43 : 0 : 1
-//var float3 input.tangent2 : $vin.ATTR11 : $_ZZ3SZaTMP44 : 0 : 1
-//var float3 input.binormal : $vin.ATTR10 : $_ZZ3SZaTMP45 : 0 : 1
-//var float3 input.binormal2 : $vin.ATTR12 : $_ZZ3SZaTMP46 : 0 : 1
-//var float4 input.color : $vin.COLOR : : 0 : 0
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-//var float4 vertexShaderFunction.diffuseUV : $vout.TEXCOORD0 : TEXCOORD0 : -1 : 1
-//var float3 vertexShaderFunction.tangent : $vout.TEXCOORD1 : TEXCOORD1 : -1 : 1
-//var float3 vertexShaderFunction.tangent2 : $vout.TEXCOORD2 : TEXCOORD2 : -1 : 1
-//var float3 vertexShaderFunction.binormal : $vout.TEXCOORD3 : TEXCOORD3 : -1 : 1
-//var float3 vertexShaderFunction.binormal2 : $vout.TEXCOORD4 : TEXCOORD4 : -1 : 1
-//var float4 vertexShaderFunction.worldPosition : $vout.TEXCOORD5 : TEXCOORD5 : -1 : 1
-//var float3 vertexShaderFunction.normal : $vout.TEXCOORD6 : TEXCOORD6 : -1 : 1
-//var float4 vertexShaderFunction.color : $vout.COLOR : COLOR : -1 : 1
-
-attribute vec4 position;
-attribute vec4 texcoord0;
-attribute vec4 texcoord1;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct InVertex {
- vec4 position;
- vec4 normal;
- vec2 diffuseUV;
- vec2 diffuse2UV;
- vec3 tangent;
- vec3 tangent2;
- vec3 binormal;
- vec3 binormal2;
- vec4 color;
-};
-
-struct OutVertex {
- vec4 position;
- vec4 diffuseUV;
- vec3 tangent;
- vec3 tangent2;
- vec3 binormal;
- vec3 binormal2;
- vec4 worldPosition;
- vec3 normal;
- vec4 color;
-};
-
-OutVertex _ZZ3Sret_0;
-vec4 _ZZ3SrZh0029;
-vec4 _ZZ3SrZh0031;
-vec4 _ZZ3SrZh0033;
-vec4 _ZZ3SvZh0033;
-vec4 _ZZ3SrZh0035;
-vec4 _ZZ3SvZh0035;
-vec4 _ZZ3SrZh0037;
-vec4 _ZZ3SvZh0037;
-vec4 _ZZ3SrZh0039;
-vec4 _ZZ3SvZh0039;
-vec4 _ZZ3SrZh0041;
-vec4 _ZZ3SvZh0041;
-attribute vec4 normal;
-attribute vec4 tangent;
-attribute vec4 tangent1;
-attribute vec4 binormal;
-attribute vec4 binormal1;
-uniform mat4 world;
-uniform mat4 worldViewProjection;
-uniform mat4 worldInverseTranspose;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
- OutVertex _ZZ4Soutput;
-
- _ZZ3SrZh0029 = position.x*worldViewProjection[0];
- _ZZ3SrZh0029 = _ZZ3SrZh0029 + position.y*worldViewProjection[1];
- _ZZ3SrZh0029 = _ZZ3SrZh0029 + position.z*worldViewProjection[2];
- _ZZ3SrZh0029 = _ZZ3SrZh0029 + position.w*worldViewProjection[3];
- _ZZ3SrZh0031 = position.x*world[0];
- _ZZ3SrZh0031 = _ZZ3SrZh0031 + position.y*world[1];
- _ZZ3SrZh0031 = _ZZ3SrZh0031 + position.z*world[2];
- _ZZ3SrZh0031 = _ZZ3SrZh0031 + position.w*world[3];
- _ZZ4Soutput.diffuseUV = vec4(texcoord0.x, texcoord0.y, texcoord1.x, texcoord1.y);
- _ZZ3SvZh0033 = vec4(normal.x, normal.y, normal.z, 0.00000000E+00);
- _ZZ3SrZh0033 = _ZZ3SvZh0033.x*worldInverseTranspose[0];
- _ZZ3SrZh0033 = _ZZ3SrZh0033 + _ZZ3SvZh0033.y*worldInverseTranspose[1];
- _ZZ3SrZh0033 = _ZZ3SrZh0033 + _ZZ3SvZh0033.z*worldInverseTranspose[2];
- _ZZ3SrZh0033 = _ZZ3SrZh0033 + _ZZ3SvZh0033.w*worldInverseTranspose[3];
- _ZZ3SrZh0033.xyz;
- _ZZ3SvZh0035 = vec4(binormal.x, binormal.y, binormal.z, 0.00000000E+00);
- _ZZ3SrZh0035 = _ZZ3SvZh0035.x*worldInverseTranspose[0];
- _ZZ3SrZh0035 = _ZZ3SrZh0035 + _ZZ3SvZh0035.y*worldInverseTranspose[1];
- _ZZ3SrZh0035 = _ZZ3SrZh0035 + _ZZ3SvZh0035.z*worldInverseTranspose[2];
- _ZZ3SrZh0035 = _ZZ3SrZh0035 + _ZZ3SvZh0035.w*worldInverseTranspose[3];
- _ZZ3SrZh0035.xyz;
- _ZZ3SvZh0037 = vec4(tangent.x, tangent.y, tangent.z, 0.00000000E+00);
- _ZZ3SrZh0037 = _ZZ3SvZh0037.x*worldInverseTranspose[0];
- _ZZ3SrZh0037 = _ZZ3SrZh0037 + _ZZ3SvZh0037.y*worldInverseTranspose[1];
- _ZZ3SrZh0037 = _ZZ3SrZh0037 + _ZZ3SvZh0037.z*worldInverseTranspose[2];
- _ZZ3SrZh0037 = _ZZ3SrZh0037 + _ZZ3SvZh0037.w*worldInverseTranspose[3];
- _ZZ3SrZh0037.xyz;
- _ZZ3SvZh0039 = vec4(binormal1.x, binormal1.y, binormal1.z, 0.00000000E+00);
- _ZZ3SrZh0039 = _ZZ3SvZh0039.x*worldInverseTranspose[0];
- _ZZ3SrZh0039 = _ZZ3SrZh0039 + _ZZ3SvZh0039.y*worldInverseTranspose[1];
- _ZZ3SrZh0039 = _ZZ3SrZh0039 + _ZZ3SvZh0039.z*worldInverseTranspose[2];
- _ZZ3SrZh0039 = _ZZ3SrZh0039 + _ZZ3SvZh0039.w*worldInverseTranspose[3];
- _ZZ3SrZh0039.xyz;
- _ZZ3SvZh0041 = vec4(tangent1.x, tangent1.y, tangent1.z, 0.00000000E+00);
- _ZZ3SrZh0041 = _ZZ3SvZh0041.x*worldInverseTranspose[0];
- _ZZ3SrZh0041 = _ZZ3SrZh0041 + _ZZ3SvZh0041.y*worldInverseTranspose[1];
- _ZZ3SrZh0041 = _ZZ3SrZh0041 + _ZZ3SvZh0041.z*worldInverseTranspose[2];
- _ZZ3SrZh0041 = _ZZ3SrZh0041 + _ZZ3SvZh0041.w*worldInverseTranspose[3];
- _ZZ3SrZh0041.xyz;
- _ZZ3Sret_0.position = _ZZ3SrZh0029;
- _ZZ3Sret_0.diffuseUV = _ZZ4Soutput.diffuseUV;
- _ZZ3Sret_0.tangent = _ZZ3SrZh0037.xyz;
- _ZZ3Sret_0.tangent2 = _ZZ3SrZh0041.xyz;
- _ZZ3Sret_0.binormal = _ZZ3SrZh0035.xyz;
- _ZZ3Sret_0.binormal2 = _ZZ3SrZh0039.xyz;
- _ZZ3Sret_0.worldPosition = _ZZ3SrZh0031;
- _ZZ3Sret_0.normal = _ZZ3SrZh0033.xyz;
- _ZZ3Sret_0.color = _ZZ4Soutput.color;
- gl_FrontColor = _ZZ4Soutput.color;
- gl_TexCoord[0] = _ZZ4Soutput.diffuseUV;
- gl_TexCoord[6].xyz = _ZZ3SrZh0033.xyz;
- gl_TexCoord[2].xyz = _ZZ3SrZh0041.xyz;
- gl_TexCoord[5] = _ZZ3SrZh0031;
- _glPositionTemp = _ZZ3SrZh0029; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- gl_TexCoord[4].xyz = _ZZ3SrZh0039.xyz;
- gl_TexCoord[1].xyz = _ZZ3SrZh0037.xyz;
- gl_TexCoord[3].xyz = _ZZ3SrZh0035.xyz;
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic clipHeight
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuseSampler
-//semantic diffuse2Sampler
-//semantic specular
-//semantic bumpSampler
-//semantic shininess
-//var float4x4 world : WORLD : , 4 : -1 : 0
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float3 lightWorldPos : : _ZZ2SlightWorldPos : -1 : 1
-//var float4 lightColor : : _ZZ2SlightColor : -1 : 1
-//var float clipHeight : : _ZZ2SclipHeight : -1 : 1
-//var float4x4 viewInverse : VIEWINVERSE : _ZZ2SviewInverse[0], 4 : -1 : 1
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : , 4 : -1 : 0
-//var float4 emissive : : _ZZ2Semissive : -1 : 1
-//var float4 ambient : : _ZZ2Sambient : -1 : 1
-//var sampler2D diffuseSampler : : _ZZ2SdiffuseSampler : -1 : 1
-//var sampler2D diffuse2Sampler : : _ZZ2Sdiffuse2Sampler : -1 : 1
-//var float4 specular : : _ZZ2Sspecular : -1 : 1
-//var sampler2D bumpSampler : : _ZZ2SbumpSampler : -1 : 1
-//var float shininess : : _ZZ2Sshininess : -1 : 1
-//var float4 input.diffuseUV : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float3 input.tangent : $vin.TEXCOORD1 : TEXCOORD1 : 0 : 1
-//var float3 input.tangent2 : $vin.TEXCOORD2 : TEXCOORD2 : 0 : 1
-//var float3 input.binormal : $vin.TEXCOORD3 : TEXCOORD3 : 0 : 1
-//var float3 input.binormal2 : $vin.TEXCOORD4 : TEXCOORD4 : 0 : 1
-//var float4 input.worldPosition : $vin.TEXCOORD5 : TEXCOORD5 : 0 : 1
-//var float3 input.normal : $vin.TEXCOORD6 : TEXCOORD6 : 0 : 1
-//var float4 input.color : $vin.COLOR : COLOR : 0 : 1
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct InVertex {
- vec4 normal;
- vec2 diffuseUV;
- vec2 diffuse2UV;
- vec3 tangent;
- vec3 tangent2;
- vec3 binormal;
- vec3 binormal2;
- vec4 color;
-};
-
-struct OutVertex {
- vec4 diffuseUV;
- vec3 tangent;
- vec3 tangent2;
- vec3 binormal;
- vec3 binormal2;
- vec4 worldPosition;
- vec3 normal;
- vec4 color;
-};
-
-vec4 _ZZ3Sret_0;
-vec3 _ZZ3SrZh0033;
-vec3 _ZZ3SZDtemp34;
-float _ZZ3SxZh0039;
-vec3 _ZZ3SrZh0043;
-float _ZZ3SxZh0049;
-vec3 _ZZ3SZDtemp50;
-vec3 _ZZ3SvZh0051;
-float _ZZ3SxZh0055;
-vec4 _ZZ3SZDtemp56;
-vec4 _ZZ3SvZh0057;
-float _ZZ3SxZh0061;
-vec3 _ZZ3SZDtemp62;
-vec3 _ZZ3SvZh0063;
-float _ZZ3SxZh0067;
-vec4 _ZZ3StmpZh0073;
-float _ZZ3SndotlZh0073;
-float _ZZ3SndothZh0073;
-vec4 _ZZ3SZDtemp74;
-float _ZZ3SspecularZh0075;
-float _ZZ3SxZh0079;
-uniform vec3 lightWorldPos;
-uniform vec4 lightColor;
-uniform float clipHeight;
-uniform mat4 viewInverse;
-uniform vec4 emissive;
-uniform vec4 ambient;
-uniform sampler2D diffuseSampler;
-uniform sampler2D diffuse2Sampler;
-uniform vec4 specular;
-uniform sampler2D bumpSampler;
-uniform float shininess;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
- vec4 _ZZ4Sdiffuse1;
- vec4 _ZZ4Sdiffuse2;
- vec3 _ZZ4StangentNormal;
- vec4 _ZZ4Sdiffuse;
- float _ZZ4Salpha;
- vec3 _ZZ4SZaTMP5;
-
- _ZZ4Sdiffuse1 = texture2D(diffuseSampler, gl_TexCoord[0].xy);
- _ZZ4Sdiffuse2 = texture2D(diffuse2Sampler, gl_TexCoord[0].zw);
- _ZZ4StangentNormal = texture2D(bumpSampler, gl_TexCoord[0].xy).xyz - vec3( 5.00000000E-01, 5.00000000E-01, 5.00000000E-01);
- _ZZ3SrZh0033 = _ZZ4StangentNormal.x*gl_TexCoord[1].xyz;
- _ZZ3SrZh0033 = _ZZ3SrZh0033 + _ZZ4StangentNormal.y*gl_TexCoord[3].xyz;
- _ZZ3SrZh0033 = _ZZ3SrZh0033 + _ZZ4StangentNormal.z*gl_TexCoord[6].xyz;
- _ZZ3SxZh0039 = dot(_ZZ3SrZh0033, _ZZ3SrZh0033);
- _ZZ3SZDtemp34 = inversesqrt(_ZZ3SxZh0039)*_ZZ3SrZh0033;
- _ZZ4StangentNormal = texture2D(bumpSampler, gl_TexCoord[0].zw).xyz - vec3( 5.00000000E-01, 5.00000000E-01, 5.00000000E-01);
- _ZZ3SrZh0043 = _ZZ4StangentNormal.x*gl_TexCoord[2].xyz;
- _ZZ3SrZh0043 = _ZZ3SrZh0043 + _ZZ4StangentNormal.y*gl_TexCoord[4].xyz;
- _ZZ3SrZh0043 = _ZZ3SrZh0043 + _ZZ4StangentNormal.z*gl_TexCoord[6].xyz;
- _ZZ3SxZh0049 = dot(_ZZ3SrZh0043, _ZZ3SrZh0043);
- inversesqrt(_ZZ3SxZh0049)*_ZZ3SrZh0043;
- _ZZ3SvZh0051 = lightWorldPos - gl_TexCoord[5].xyz;
- _ZZ3SxZh0055 = dot(_ZZ3SvZh0051, _ZZ3SvZh0051);
- _ZZ3SZDtemp50 = inversesqrt(_ZZ3SxZh0055)*_ZZ3SvZh0051;
- _ZZ3SvZh0057 = viewInverse[3] - gl_TexCoord[5];
- _ZZ3SxZh0061 = dot(_ZZ3SvZh0057, _ZZ3SvZh0057);
- _ZZ3SZDtemp56 = inversesqrt(_ZZ3SxZh0061)*_ZZ3SvZh0057;
- _ZZ3SvZh0063 = _ZZ3SZDtemp50 + _ZZ3SZDtemp56.xyz;
- _ZZ3SxZh0067 = dot(_ZZ3SvZh0063, _ZZ3SvZh0063);
- _ZZ3SZDtemp62 = inversesqrt(_ZZ3SxZh0067)*_ZZ3SvZh0063;
- _ZZ3SndotlZh0073 = dot(_ZZ3SZDtemp34, _ZZ3SZDtemp50);
- _ZZ3SndothZh0073 = dot(_ZZ3SZDtemp34, _ZZ3SZDtemp62);
- _ZZ3StmpZh0073 = vec4(_ZZ3SndotlZh0073, _ZZ3SndothZh0073, shininess, shininess);
- _ZZ3SxZh0079 = max(0.00000000E+00, _ZZ3StmpZh0073.y);
- _ZZ3SspecularZh0075 = _ZZ3StmpZh0073.x > 0.00000000E+00 ? pow(_ZZ3SxZh0079, _ZZ3StmpZh0073.z) : 0.00000000E+00;
- _ZZ3SZDtemp74 = vec4(1.00000000E+00, max(0.00000000E+00, _ZZ3StmpZh0073.x), _ZZ3SspecularZh0075, 1.00000000E+00);
- _ZZ4Sdiffuse = _ZZ4Sdiffuse1 + gl_Color.w*(_ZZ4Sdiffuse2 - _ZZ4Sdiffuse1);
- _ZZ4Salpha = gl_TexCoord[5].z > clipHeight ? 0.00000000E+00 : _ZZ4Sdiffuse.w;
- _ZZ4SZaTMP5 = (emissive + lightColor*(ambient*_ZZ4Sdiffuse + _ZZ4Sdiffuse*_ZZ3SZDtemp74.y + specular*_ZZ3SZDtemp74.z)).xyz;
- _ZZ3Sret_0 = vec4(_ZZ4SZaTMP5.x, _ZZ4SZaTMP5.y, _ZZ4SZaTMP5.z, _ZZ4Salpha);
- gl_FragColor = _ZZ3Sret_0;
- return;
-} // main end
-
diff --git a/o3d/samples/beachdemo/shaders_glsl/diffuse_bump_blend_underwater.glsl b/o3d/samples/beachdemo/shaders_glsl/diffuse_bump_blend_underwater.glsl
deleted file mode 100644
index 2090494..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/diffuse_bump_blend_underwater.glsl
+++ /dev/null
@@ -1,332 +0,0 @@
-// glslv profile log:
-// (99) : warning C7011: implicit cast from "float4" to "float3"
-// (100) : warning C7011: implicit cast from "float4" to "float3"
-// (71) : warning C7050: "output.color" might be used before being initialized
-// 115 lines, 3 warnings, 0 errors.
-
-// glslf profile log:
-// (99) : warning C7011: implicit cast from "float4" to "float3"
-// (100) : warning C7011: implicit cast from "float4" to "float3"
-// 115 lines, 2 warnings, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuseSampler
-//semantic diffuse2Sampler
-//semantic specular
-//semantic bumpSampler
-//semantic shininess
-//var float4x4 world : WORLD : _ZZ2Sworld[0], 4 : -1 : 1
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : _ZZ2SworldViewProjection[0], 4 : -1 : 1
-//var float3 lightWorldPos : : : -1 : 0
-//var float4 lightColor : : : -1 : 0
-//var float4x4 viewInverse : VIEWINVERSE : , 4 : -1 : 0
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : _ZZ2SworldInverseTranspose[0], 4 : -1 : 1
-//var float4 emissive : : : -1 : 0
-//var float4 ambient : : : -1 : 0
-//var sampler2D diffuseSampler : : : -1 : 0
-//var sampler2D diffuse2Sampler : : : -1 : 0
-//var float4 specular : : : -1 : 0
-//var sampler2D bumpSampler : : : -1 : 0
-//var float shininess : : : -1 : 0
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float4 input.normal : $vin.ATTR8 : $_ZZ3SZaTMP41 : 0 : 1
-//var float2 input.diffuseUV : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float2 input.diffuse2UV : $vin.TEXCOORD1 : TEXCOORD1 : 0 : 1
-//var float3 input.tangent : $vin.ATTR9 : $_ZZ3SZaTMP42 : 0 : 1
-//var float3 input.tangent2 : $vin.ATTR11 : $_ZZ3SZaTMP43 : 0 : 1
-//var float3 input.binormal : $vin.ATTR10 : $_ZZ3SZaTMP44 : 0 : 1
-//var float3 input.binormal2 : $vin.ATTR12 : $_ZZ3SZaTMP45 : 0 : 1
-//var float4 input.color : $vin.COLOR : : 0 : 0
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-//var float4 vertexShaderFunction.diffuseUV : $vout.TEXCOORD0 : TEXCOORD0 : -1 : 1
-//var float3 vertexShaderFunction.tangent : $vout.TEXCOORD1 : TEXCOORD1 : -1 : 1
-//var float3 vertexShaderFunction.tangent2 : $vout.TEXCOORD2 : TEXCOORD2 : -1 : 1
-//var float3 vertexShaderFunction.binormal : $vout.TEXCOORD3 : TEXCOORD3 : -1 : 1
-//var float3 vertexShaderFunction.binormal2 : $vout.TEXCOORD4 : TEXCOORD4 : -1 : 1
-//var float4 vertexShaderFunction.worldPosition : $vout.TEXCOORD5 : TEXCOORD5 : -1 : 1
-//var float3 vertexShaderFunction.normal : $vout.TEXCOORD6 : TEXCOORD6 : -1 : 1
-//var float4 vertexShaderFunction.color : $vout.COLOR : COLOR : -1 : 1
-
-attribute vec4 position;
-attribute vec4 texcoord0;
-attribute vec4 texcoord1;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct InVertex {
- vec4 position;
- vec4 normal;
- vec2 diffuseUV;
- vec2 diffuse2UV;
- vec3 tangent;
- vec3 tangent2;
- vec3 binormal;
- vec3 binormal2;
- vec4 color;
-};
-
-struct OutVertex {
- vec4 position;
- vec4 diffuseUV;
- vec3 tangent;
- vec3 tangent2;
- vec3 binormal;
- vec3 binormal2;
- vec4 worldPosition;
- vec3 normal;
- vec4 color;
-};
-
-OutVertex _ZZ3Sret_0;
-vec4 _ZZ3SrZh0028;
-vec4 _ZZ3SrZh0030;
-vec4 _ZZ3SrZh0032;
-vec4 _ZZ3SvZh0032;
-vec4 _ZZ3SrZh0034;
-vec4 _ZZ3SvZh0034;
-vec4 _ZZ3SrZh0036;
-vec4 _ZZ3SvZh0036;
-vec4 _ZZ3SrZh0038;
-vec4 _ZZ3SvZh0038;
-vec4 _ZZ3SrZh0040;
-vec4 _ZZ3SvZh0040;
-attribute vec4 normal;
-attribute vec4 tangent;
-attribute vec4 tangent1;
-attribute vec4 binormal;
-attribute vec4 binormal1;
-uniform mat4 world;
-uniform mat4 worldViewProjection;
-uniform mat4 worldInverseTranspose;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
- OutVertex _ZZ4Soutput;
-
- _ZZ3SrZh0028 = position.x*worldViewProjection[0];
- _ZZ3SrZh0028 = _ZZ3SrZh0028 + position.y*worldViewProjection[1];
- _ZZ3SrZh0028 = _ZZ3SrZh0028 + position.z*worldViewProjection[2];
- _ZZ3SrZh0028 = _ZZ3SrZh0028 + position.w*worldViewProjection[3];
- _ZZ3SrZh0030 = position.x*world[0];
- _ZZ3SrZh0030 = _ZZ3SrZh0030 + position.y*world[1];
- _ZZ3SrZh0030 = _ZZ3SrZh0030 + position.z*world[2];
- _ZZ3SrZh0030 = _ZZ3SrZh0030 + position.w*world[3];
- _ZZ4Soutput.diffuseUV = vec4(texcoord0.x, texcoord0.y, texcoord1.x, texcoord1.y);
- _ZZ3SvZh0032 = vec4(normal.x, normal.y, normal.z, 0.00000000E+00);
- _ZZ3SrZh0032 = _ZZ3SvZh0032.x*worldInverseTranspose[0];
- _ZZ3SrZh0032 = _ZZ3SrZh0032 + _ZZ3SvZh0032.y*worldInverseTranspose[1];
- _ZZ3SrZh0032 = _ZZ3SrZh0032 + _ZZ3SvZh0032.z*worldInverseTranspose[2];
- _ZZ3SrZh0032 = _ZZ3SrZh0032 + _ZZ3SvZh0032.w*worldInverseTranspose[3];
- _ZZ3SrZh0032.xyz;
- _ZZ3SvZh0034 = vec4(binormal.x, binormal.y, binormal.z, 0.00000000E+00);
- _ZZ3SrZh0034 = _ZZ3SvZh0034.x*worldInverseTranspose[0];
- _ZZ3SrZh0034 = _ZZ3SrZh0034 + _ZZ3SvZh0034.y*worldInverseTranspose[1];
- _ZZ3SrZh0034 = _ZZ3SrZh0034 + _ZZ3SvZh0034.z*worldInverseTranspose[2];
- _ZZ3SrZh0034 = _ZZ3SrZh0034 + _ZZ3SvZh0034.w*worldInverseTranspose[3];
- _ZZ3SrZh0034.xyz;
- _ZZ3SvZh0036 = vec4(tangent.x, tangent.y, tangent.z, 0.00000000E+00);
- _ZZ3SrZh0036 = _ZZ3SvZh0036.x*worldInverseTranspose[0];
- _ZZ3SrZh0036 = _ZZ3SrZh0036 + _ZZ3SvZh0036.y*worldInverseTranspose[1];
- _ZZ3SrZh0036 = _ZZ3SrZh0036 + _ZZ3SvZh0036.z*worldInverseTranspose[2];
- _ZZ3SrZh0036 = _ZZ3SrZh0036 + _ZZ3SvZh0036.w*worldInverseTranspose[3];
- _ZZ3SrZh0036.xyz;
- _ZZ3SvZh0038 = vec4(binormal1.x, binormal1.y, binormal1.z, 0.00000000E+00);
- _ZZ3SrZh0038 = _ZZ3SvZh0038.x*worldInverseTranspose[0];
- _ZZ3SrZh0038 = _ZZ3SrZh0038 + _ZZ3SvZh0038.y*worldInverseTranspose[1];
- _ZZ3SrZh0038 = _ZZ3SrZh0038 + _ZZ3SvZh0038.z*worldInverseTranspose[2];
- _ZZ3SrZh0038 = _ZZ3SrZh0038 + _ZZ3SvZh0038.w*worldInverseTranspose[3];
- _ZZ3SrZh0038.xyz;
- _ZZ3SvZh0040 = vec4(tangent1.x, tangent1.y, tangent1.z, 0.00000000E+00);
- _ZZ3SrZh0040 = _ZZ3SvZh0040.x*worldInverseTranspose[0];
- _ZZ3SrZh0040 = _ZZ3SrZh0040 + _ZZ3SvZh0040.y*worldInverseTranspose[1];
- _ZZ3SrZh0040 = _ZZ3SrZh0040 + _ZZ3SvZh0040.z*worldInverseTranspose[2];
- _ZZ3SrZh0040 = _ZZ3SrZh0040 + _ZZ3SvZh0040.w*worldInverseTranspose[3];
- _ZZ3SrZh0040.xyz;
- _ZZ3Sret_0.position = _ZZ3SrZh0028;
- _ZZ3Sret_0.diffuseUV = _ZZ4Soutput.diffuseUV;
- _ZZ3Sret_0.tangent = _ZZ3SrZh0036.xyz;
- _ZZ3Sret_0.tangent2 = _ZZ3SrZh0040.xyz;
- _ZZ3Sret_0.binormal = _ZZ3SrZh0034.xyz;
- _ZZ3Sret_0.binormal2 = _ZZ3SrZh0038.xyz;
- _ZZ3Sret_0.worldPosition = _ZZ3SrZh0030;
- _ZZ3Sret_0.normal = _ZZ3SrZh0032.xyz;
- _ZZ3Sret_0.color = _ZZ4Soutput.color;
- gl_FrontColor = _ZZ4Soutput.color;
- gl_TexCoord[0] = _ZZ4Soutput.diffuseUV;
- gl_TexCoord[6].xyz = _ZZ3SrZh0032.xyz;
- gl_TexCoord[2].xyz = _ZZ3SrZh0040.xyz;
- gl_TexCoord[5] = _ZZ3SrZh0030;
- _glPositionTemp = _ZZ3SrZh0028; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- gl_TexCoord[4].xyz = _ZZ3SrZh0038.xyz;
- gl_TexCoord[1].xyz = _ZZ3SrZh0036.xyz;
- gl_TexCoord[3].xyz = _ZZ3SrZh0034.xyz;
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuseSampler
-//semantic diffuse2Sampler
-//semantic specular
-//semantic bumpSampler
-//semantic shininess
-//var float4x4 world : WORLD : , 4 : -1 : 0
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float3 lightWorldPos : : _ZZ2SlightWorldPos : -1 : 1
-//var float4 lightColor : : _ZZ2SlightColor : -1 : 1
-//var float4x4 viewInverse : VIEWINVERSE : _ZZ2SviewInverse[0], 4 : -1 : 1
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : , 4 : -1 : 0
-//var float4 emissive : : _ZZ2Semissive : -1 : 1
-//var float4 ambient : : _ZZ2Sambient : -1 : 1
-//var sampler2D diffuseSampler : : _ZZ2SdiffuseSampler : -1 : 1
-//var sampler2D diffuse2Sampler : : _ZZ2Sdiffuse2Sampler : -1 : 1
-//var float4 specular : : _ZZ2Sspecular : -1 : 1
-//var sampler2D bumpSampler : : _ZZ2SbumpSampler : -1 : 1
-//var float shininess : : _ZZ2Sshininess : -1 : 1
-//var float4 input.diffuseUV : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float3 input.tangent : $vin.TEXCOORD1 : TEXCOORD1 : 0 : 1
-//var float3 input.tangent2 : $vin.TEXCOORD2 : TEXCOORD2 : 0 : 1
-//var float3 input.binormal : $vin.TEXCOORD3 : TEXCOORD3 : 0 : 1
-//var float3 input.binormal2 : $vin.TEXCOORD4 : TEXCOORD4 : 0 : 1
-//var float4 input.worldPosition : $vin.TEXCOORD5 : TEXCOORD5 : 0 : 1
-//var float3 input.normal : $vin.TEXCOORD6 : TEXCOORD6 : 0 : 1
-//var float4 input.color : $vin.COLOR : COLOR : 0 : 1
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct InVertex {
- vec4 normal;
- vec2 diffuseUV;
- vec2 diffuse2UV;
- vec3 tangent;
- vec3 tangent2;
- vec3 binormal;
- vec3 binormal2;
- vec4 color;
-};
-
-struct OutVertex {
- vec4 diffuseUV;
- vec3 tangent;
- vec3 tangent2;
- vec3 binormal;
- vec3 binormal2;
- vec4 worldPosition;
- vec3 normal;
- vec4 color;
-};
-
-vec4 _ZZ3Sret_0;
-vec3 _ZZ3SrZh0032;
-vec3 _ZZ3SZDtemp33;
-float _ZZ3SxZh0038;
-vec3 _ZZ3SrZh0042;
-float _ZZ3SxZh0048;
-vec3 _ZZ3SZDtemp49;
-vec3 _ZZ3SvZh0050;
-float _ZZ3SxZh0054;
-vec4 _ZZ3SZDtemp55;
-vec4 _ZZ3SvZh0056;
-float _ZZ3SxZh0060;
-vec3 _ZZ3SZDtemp61;
-vec3 _ZZ3SvZh0062;
-float _ZZ3SxZh0066;
-vec4 _ZZ3StmpZh0072;
-float _ZZ3SndotlZh0072;
-float _ZZ3SndothZh0072;
-vec4 _ZZ3SZDtemp73;
-float _ZZ3SspecularZh0074;
-float _ZZ3SxZh0078;
-uniform vec3 lightWorldPos;
-uniform vec4 lightColor;
-uniform mat4 viewInverse;
-uniform vec4 emissive;
-uniform vec4 ambient;
-uniform sampler2D diffuseSampler;
-uniform sampler2D diffuse2Sampler;
-uniform vec4 specular;
-uniform sampler2D bumpSampler;
-uniform float shininess;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
- vec4 _ZZ4Sdiffuse1;
- vec4 _ZZ4Sdiffuse2;
- vec3 _ZZ4StangentNormal;
- vec4 _ZZ4Sdiffuse;
- float _ZZ4Salpha;
- vec3 _ZZ4SZaTMP5;
-
- _ZZ4Sdiffuse1 = texture2D(diffuseSampler, gl_TexCoord[0].xy);
- _ZZ4Sdiffuse2 = texture2D(diffuse2Sampler, gl_TexCoord[0].zw);
- _ZZ4StangentNormal = texture2D(bumpSampler, gl_TexCoord[0].xy).xyz - vec3( 5.00000000E-01, 5.00000000E-01, 5.00000000E-01);
- _ZZ3SrZh0032 = _ZZ4StangentNormal.x*gl_TexCoord[1].xyz;
- _ZZ3SrZh0032 = _ZZ3SrZh0032 + _ZZ4StangentNormal.y*gl_TexCoord[3].xyz;
- _ZZ3SrZh0032 = _ZZ3SrZh0032 + _ZZ4StangentNormal.z*gl_TexCoord[6].xyz;
- _ZZ3SxZh0038 = dot(_ZZ3SrZh0032, _ZZ3SrZh0032);
- _ZZ3SZDtemp33 = inversesqrt(_ZZ3SxZh0038)*_ZZ3SrZh0032;
- _ZZ4StangentNormal = texture2D(bumpSampler, gl_TexCoord[0].zw).xyz - vec3( 5.00000000E-01, 5.00000000E-01, 5.00000000E-01);
- _ZZ3SrZh0042 = _ZZ4StangentNormal.x*gl_TexCoord[2].xyz;
- _ZZ3SrZh0042 = _ZZ3SrZh0042 + _ZZ4StangentNormal.y*gl_TexCoord[4].xyz;
- _ZZ3SrZh0042 = _ZZ3SrZh0042 + _ZZ4StangentNormal.z*gl_TexCoord[6].xyz;
- _ZZ3SxZh0048 = dot(_ZZ3SrZh0042, _ZZ3SrZh0042);
- inversesqrt(_ZZ3SxZh0048)*_ZZ3SrZh0042;
- _ZZ3SvZh0050 = lightWorldPos - gl_TexCoord[5].xyz;
- _ZZ3SxZh0054 = dot(_ZZ3SvZh0050, _ZZ3SvZh0050);
- _ZZ3SZDtemp49 = inversesqrt(_ZZ3SxZh0054)*_ZZ3SvZh0050;
- _ZZ3SvZh0056 = viewInverse[3] - gl_TexCoord[5];
- _ZZ3SxZh0060 = dot(_ZZ3SvZh0056, _ZZ3SvZh0056);
- _ZZ3SZDtemp55 = inversesqrt(_ZZ3SxZh0060)*_ZZ3SvZh0056;
- _ZZ3SvZh0062 = _ZZ3SZDtemp49 + _ZZ3SZDtemp55.xyz;
- _ZZ3SxZh0066 = dot(_ZZ3SvZh0062, _ZZ3SvZh0062);
- _ZZ3SZDtemp61 = inversesqrt(_ZZ3SxZh0066)*_ZZ3SvZh0062;
- _ZZ3SndotlZh0072 = dot(_ZZ3SZDtemp33, _ZZ3SZDtemp49);
- _ZZ3SndothZh0072 = dot(_ZZ3SZDtemp33, _ZZ3SZDtemp61);
- _ZZ3StmpZh0072 = vec4(_ZZ3SndotlZh0072, _ZZ3SndothZh0072, shininess, shininess);
- _ZZ3SxZh0078 = max(0.00000000E+00, _ZZ3StmpZh0072.y);
- _ZZ3SspecularZh0074 = _ZZ3StmpZh0072.x > 0.00000000E+00 ? pow(_ZZ3SxZh0078, _ZZ3StmpZh0072.z) : 0.00000000E+00;
- _ZZ3SZDtemp73 = vec4(1.00000000E+00, max(0.00000000E+00, _ZZ3StmpZh0072.x), _ZZ3SspecularZh0074, 1.00000000E+00);
- _ZZ4Sdiffuse = _ZZ4Sdiffuse1 + gl_Color.w*(_ZZ4Sdiffuse2 - _ZZ4Sdiffuse1);
- _ZZ4Salpha = gl_TexCoord[5].z > 0.00000000E+00 ? 0.00000000E+00 : _ZZ4Sdiffuse.w;
- _ZZ4SZaTMP5 = (emissive + lightColor*(ambient*_ZZ4Sdiffuse + _ZZ4Sdiffuse*_ZZ3SZDtemp73.y + specular*_ZZ3SZDtemp73.z)).xyz;
- _ZZ3Sret_0 = vec4(_ZZ4SZaTMP5.x, _ZZ4SZaTMP5.y, _ZZ4SZaTMP5.z, _ZZ4Salpha);
- gl_FragColor = _ZZ3Sret_0;
- return;
-} // main end
-
diff --git a/o3d/samples/beachdemo/shaders_glsl/diffuse_bump_specular.glsl b/o3d/samples/beachdemo/shaders_glsl/diffuse_bump_specular.glsl
deleted file mode 100644
index c1984a2..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/diffuse_bump_specular.glsl
+++ /dev/null
@@ -1,270 +0,0 @@
-// glslv profile log:
-// (82) : warning C7011: implicit cast from "float4" to "float3"
-// (83) : warning C7011: implicit cast from "float4" to "float3"
-// 97 lines, 2 warnings, 0 errors.
-
-// glslf profile log:
-// (82) : warning C7011: implicit cast from "float4" to "float3"
-// (83) : warning C7011: implicit cast from "float4" to "float3"
-// 97 lines, 2 warnings, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic clipHeight
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuseSampler
-//semantic specularSampler
-//semantic bumpSampler
-//semantic shininess
-//var float4x4 world : WORLD : _ZZ2Sworld[0], 4 : -1 : 1
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : _ZZ2SworldViewProjection[0], 4 : -1 : 1
-//var float3 lightWorldPos : : : -1 : 0
-//var float4 lightColor : : : -1 : 0
-//var float clipHeight : : : -1 : 0
-//var float4x4 viewInverse : VIEWINVERSE : , 4 : -1 : 0
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : _ZZ2SworldInverseTranspose[0], 4 : -1 : 1
-//var float4 emissive : : : -1 : 0
-//var float4 ambient : : : -1 : 0
-//var sampler2D diffuseSampler : : : -1 : 0
-//var sampler2D specularSampler : : : -1 : 0
-//var sampler2D bumpSampler : : : -1 : 0
-//var float shininess : : : -1 : 0
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float4 input.normal : $vin.ATTR8 : $_ZZ3SZaTMP29 : 0 : 1
-//var float2 input.diffuseUV : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float3 input.tangent : $vin.ATTR9 : $_ZZ3SZaTMP30 : 0 : 1
-//var float3 input.binormal : $vin.ATTR10 : $_ZZ3SZaTMP31 : 0 : 1
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-//var float2 vertexShaderFunction.diffuseUV : $vout.TEXCOORD0 : TEXCOORD0 : -1 : 1
-//var float3 vertexShaderFunction.tangent : $vout.TEXCOORD1 : TEXCOORD1 : -1 : 1
-//var float3 vertexShaderFunction.binormal : $vout.TEXCOORD2 : TEXCOORD2 : -1 : 1
-//var float4 vertexShaderFunction.worldPosition : $vout.TEXCOORD3 : TEXCOORD3 : -1 : 1
-//var float3 vertexShaderFunction.normal : $vout.TEXCOORD4 : TEXCOORD4 : -1 : 1
-
-attribute vec4 position;
-attribute vec4 texcoord0;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct InVertex {
- vec4 position;
- vec4 normal;
- vec2 diffuseUV;
- vec3 tangent;
- vec3 binormal;
-};
-
-struct OutVertex {
- vec4 position;
- vec2 diffuseUV;
- vec3 tangent;
- vec3 binormal;
- vec4 worldPosition;
- vec3 normal;
-};
-
-OutVertex _ZZ3Sret_0;
-vec4 _ZZ3SrZh0020;
-vec4 _ZZ3SrZh0022;
-vec4 _ZZ3SrZh0024;
-vec4 _ZZ3SvZh0024;
-vec4 _ZZ3SrZh0026;
-vec4 _ZZ3SvZh0026;
-vec4 _ZZ3SrZh0028;
-vec4 _ZZ3SvZh0028;
-attribute vec4 normal;
-attribute vec4 tangent;
-attribute vec4 binormal;
-uniform mat4 world;
-uniform mat4 worldViewProjection;
-uniform mat4 worldInverseTranspose;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
-
- _ZZ3SrZh0020 = position.x*worldViewProjection[0];
- _ZZ3SrZh0020 = _ZZ3SrZh0020 + position.y*worldViewProjection[1];
- _ZZ3SrZh0020 = _ZZ3SrZh0020 + position.z*worldViewProjection[2];
- _ZZ3SrZh0020 = _ZZ3SrZh0020 + position.w*worldViewProjection[3];
- _ZZ3SrZh0022 = position.x*world[0];
- _ZZ3SrZh0022 = _ZZ3SrZh0022 + position.y*world[1];
- _ZZ3SrZh0022 = _ZZ3SrZh0022 + position.z*world[2];
- _ZZ3SrZh0022 = _ZZ3SrZh0022 + position.w*world[3];
- _ZZ3SvZh0024 = vec4(normal.x, normal.y, normal.z, 0.00000000E+00);
- _ZZ3SrZh0024 = _ZZ3SvZh0024.x*worldInverseTranspose[0];
- _ZZ3SrZh0024 = _ZZ3SrZh0024 + _ZZ3SvZh0024.y*worldInverseTranspose[1];
- _ZZ3SrZh0024 = _ZZ3SrZh0024 + _ZZ3SvZh0024.z*worldInverseTranspose[2];
- _ZZ3SrZh0024 = _ZZ3SrZh0024 + _ZZ3SvZh0024.w*worldInverseTranspose[3];
- _ZZ3SrZh0024.xyz;
- _ZZ3SvZh0026 = vec4(binormal.x, binormal.y, binormal.z, 0.00000000E+00);
- _ZZ3SrZh0026 = _ZZ3SvZh0026.x*worldInverseTranspose[0];
- _ZZ3SrZh0026 = _ZZ3SrZh0026 + _ZZ3SvZh0026.y*worldInverseTranspose[1];
- _ZZ3SrZh0026 = _ZZ3SrZh0026 + _ZZ3SvZh0026.z*worldInverseTranspose[2];
- _ZZ3SrZh0026 = _ZZ3SrZh0026 + _ZZ3SvZh0026.w*worldInverseTranspose[3];
- _ZZ3SrZh0026.xyz;
- _ZZ3SvZh0028 = vec4(tangent.x, tangent.y, tangent.z, 0.00000000E+00);
- _ZZ3SrZh0028 = _ZZ3SvZh0028.x*worldInverseTranspose[0];
- _ZZ3SrZh0028 = _ZZ3SrZh0028 + _ZZ3SvZh0028.y*worldInverseTranspose[1];
- _ZZ3SrZh0028 = _ZZ3SrZh0028 + _ZZ3SvZh0028.z*worldInverseTranspose[2];
- _ZZ3SrZh0028 = _ZZ3SrZh0028 + _ZZ3SvZh0028.w*worldInverseTranspose[3];
- _ZZ3SrZh0028.xyz;
- _ZZ3Sret_0.position = _ZZ3SrZh0020;
- _ZZ3Sret_0.diffuseUV = texcoord0.xy;
- _ZZ3Sret_0.tangent = _ZZ3SrZh0028.xyz;
- _ZZ3Sret_0.binormal = _ZZ3SrZh0026.xyz;
- _ZZ3Sret_0.worldPosition = _ZZ3SrZh0022;
- _ZZ3Sret_0.normal = _ZZ3SrZh0024.xyz;
- gl_TexCoord[0].xy = texcoord0.xy;
- gl_TexCoord[2].xyz = _ZZ3SrZh0026.xyz;
- _glPositionTemp = _ZZ3SrZh0020; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- gl_TexCoord[4].xyz = _ZZ3SrZh0024.xyz;
- gl_TexCoord[1].xyz = _ZZ3SrZh0028.xyz;
- gl_TexCoord[3] = _ZZ3SrZh0022;
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic clipHeight
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuseSampler
-//semantic specularSampler
-//semantic bumpSampler
-//semantic shininess
-//var float4x4 world : WORLD : , 4 : -1 : 0
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float3 lightWorldPos : : _ZZ2SlightWorldPos : -1 : 1
-//var float4 lightColor : : _ZZ2SlightColor : -1 : 1
-//var float clipHeight : : _ZZ2SclipHeight : -1 : 1
-//var float4x4 viewInverse : VIEWINVERSE : _ZZ2SviewInverse[0], 4 : -1 : 1
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : , 4 : -1 : 0
-//var float4 emissive : : _ZZ2Semissive : -1 : 1
-//var float4 ambient : : _ZZ2Sambient : -1 : 1
-//var sampler2D diffuseSampler : : _ZZ2SdiffuseSampler : -1 : 1
-//var sampler2D specularSampler : : _ZZ2SspecularSampler : -1 : 1
-//var sampler2D bumpSampler : : _ZZ2SbumpSampler : -1 : 1
-//var float shininess : : _ZZ2Sshininess : -1 : 1
-//var float2 input.diffuseUV : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float3 input.tangent : $vin.TEXCOORD1 : TEXCOORD1 : 0 : 1
-//var float3 input.binormal : $vin.TEXCOORD2 : TEXCOORD2 : 0 : 1
-//var float4 input.worldPosition : $vin.TEXCOORD3 : TEXCOORD3 : 0 : 1
-//var float3 input.normal : $vin.TEXCOORD4 : TEXCOORD4 : 0 : 1
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct InVertex {
- vec4 normal;
- vec2 diffuseUV;
- vec3 tangent;
- vec3 binormal;
-};
-
-struct OutVertex {
- vec2 diffuseUV;
- vec3 tangent;
- vec3 binormal;
- vec4 worldPosition;
- vec3 normal;
-};
-
-vec4 _ZZ3Sret_0;
-vec3 _ZZ3SrZh0028;
-vec3 _ZZ3SZDtemp29;
-float _ZZ3SxZh0034;
-vec3 _ZZ3SZDtemp35;
-vec3 _ZZ3SvZh0036;
-float _ZZ3SxZh0040;
-vec4 _ZZ3SZDtemp41;
-vec4 _ZZ3SvZh0042;
-float _ZZ3SxZh0046;
-vec3 _ZZ3SZDtemp47;
-vec3 _ZZ3SvZh0048;
-float _ZZ3SxZh0052;
-vec4 _ZZ3StmpZh0058;
-float _ZZ3SndotlZh0058;
-float _ZZ3SndothZh0058;
-vec4 _ZZ3SZDtemp59;
-float _ZZ3SspecularZh0060;
-float _ZZ3SxZh0064;
-uniform vec3 lightWorldPos;
-uniform vec4 lightColor;
-uniform float clipHeight;
-uniform mat4 viewInverse;
-uniform vec4 emissive;
-uniform vec4 ambient;
-uniform sampler2D diffuseSampler;
-uniform sampler2D specularSampler;
-uniform sampler2D bumpSampler;
-uniform float shininess;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
- vec4 _ZZ4Sdiffuse;
- vec4 _ZZ4Sspecular;
- vec3 _ZZ4StangentNormal;
- float _ZZ4Salpha;
- vec3 _ZZ4SZaTMP4;
-
- _ZZ4Sdiffuse = texture2D(diffuseSampler, gl_TexCoord[0].xy);
- _ZZ4Sspecular = texture2D(specularSampler, gl_TexCoord[0].xy);
- _ZZ4StangentNormal = texture2D(bumpSampler, gl_TexCoord[0].xy).xyz - vec3( 5.00000000E-01, 5.00000000E-01, 5.00000000E-01);
- _ZZ3SrZh0028 = _ZZ4StangentNormal.x*gl_TexCoord[1].xyz;
- _ZZ3SrZh0028 = _ZZ3SrZh0028 + _ZZ4StangentNormal.y*gl_TexCoord[2].xyz;
- _ZZ3SrZh0028 = _ZZ3SrZh0028 + _ZZ4StangentNormal.z*gl_TexCoord[4].xyz;
- _ZZ3SxZh0034 = dot(_ZZ3SrZh0028, _ZZ3SrZh0028);
- _ZZ3SZDtemp29 = inversesqrt(_ZZ3SxZh0034)*_ZZ3SrZh0028;
- _ZZ3SvZh0036 = lightWorldPos - gl_TexCoord[3].xyz;
- _ZZ3SxZh0040 = dot(_ZZ3SvZh0036, _ZZ3SvZh0036);
- _ZZ3SZDtemp35 = inversesqrt(_ZZ3SxZh0040)*_ZZ3SvZh0036;
- _ZZ3SvZh0042 = viewInverse[3] - gl_TexCoord[3];
- _ZZ3SxZh0046 = dot(_ZZ3SvZh0042, _ZZ3SvZh0042);
- _ZZ3SZDtemp41 = inversesqrt(_ZZ3SxZh0046)*_ZZ3SvZh0042;
- _ZZ3SvZh0048 = _ZZ3SZDtemp35 + _ZZ3SZDtemp41.xyz;
- _ZZ3SxZh0052 = dot(_ZZ3SvZh0048, _ZZ3SvZh0048);
- _ZZ3SZDtemp47 = inversesqrt(_ZZ3SxZh0052)*_ZZ3SvZh0048;
- _ZZ3SndotlZh0058 = dot(_ZZ3SZDtemp29, _ZZ3SZDtemp35);
- _ZZ3SndothZh0058 = dot(_ZZ3SZDtemp29, _ZZ3SZDtemp47);
- _ZZ3StmpZh0058 = vec4(_ZZ3SndotlZh0058, _ZZ3SndothZh0058, shininess, shininess);
- _ZZ3SxZh0064 = max(0.00000000E+00, _ZZ3StmpZh0058.y);
- _ZZ3SspecularZh0060 = _ZZ3StmpZh0058.x > 0.00000000E+00 ? pow(_ZZ3SxZh0064, _ZZ3StmpZh0058.z) : 0.00000000E+00;
- _ZZ3SZDtemp59 = vec4(1.00000000E+00, max(0.00000000E+00, _ZZ3StmpZh0058.x), _ZZ3SspecularZh0060, 1.00000000E+00);
- _ZZ4Salpha = gl_TexCoord[3].z > clipHeight ? 0.00000000E+00 : _ZZ4Sdiffuse.w;
- _ZZ4SZaTMP4 = (emissive + lightColor*(ambient*_ZZ4Sdiffuse + _ZZ4Sdiffuse*_ZZ3SZDtemp59.y + _ZZ4Sspecular*_ZZ3SZDtemp59.z)).xyz;
- _ZZ3Sret_0 = vec4(_ZZ4SZaTMP4.x, _ZZ4SZaTMP4.y, _ZZ4SZaTMP4.z, _ZZ4Salpha);
- gl_FragColor = _ZZ3Sret_0;
- return;
-} // main end
-
diff --git a/o3d/samples/beachdemo/shaders_glsl/imageshader.glsl b/o3d/samples/beachdemo/shaders_glsl/imageshader.glsl
deleted file mode 100644
index 07c3940..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/imageshader.glsl
+++ /dev/null
@@ -1,105 +0,0 @@
-// glslv profile log:
-// 61 lines, 0 errors.
-
-// glslf profile log:
-// 61 lines, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic colorMult
-//semantic diffuseSampler
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : _ZZ2SworldViewProjection[0], 4 : -1 : 1
-//var float4 colorMult : : : -1 : 0
-//var sampler diffuseSampler : : : -1 : 0
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float2 input.texcoord : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-//var float2 vertexShaderFunction.texcoord : $vout.TEXCOORD2 : TEXCOORD2 : -1 : 1
-
-attribute vec4 position;
-attribute vec4 texcoord0;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct VertexShaderInput {
- vec4 position;
- vec2 texcoord;
-};
-
-struct PixelShaderInput {
- vec4 position;
- vec2 texcoord;
-};
-
-PixelShaderInput _ZZ3Sret_0;
-vec4 _ZZ3SrZh0004;
-uniform mat4 worldViewProjection;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
-
- _ZZ3SrZh0004 = position.x*worldViewProjection[0];
- _ZZ3SrZh0004 = _ZZ3SrZh0004 + position.y*worldViewProjection[1];
- _ZZ3SrZh0004 = _ZZ3SrZh0004 + position.z*worldViewProjection[2];
- _ZZ3SrZh0004 = _ZZ3SrZh0004 + position.w*worldViewProjection[3];
- _ZZ3Sret_0.position = _ZZ3SrZh0004;
- _ZZ3Sret_0.texcoord = texcoord0.xy;
- gl_TexCoord[2].xy = texcoord0.xy;
- _glPositionTemp = _ZZ3SrZh0004; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic colorMult
-//semantic diffuseSampler
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float4 colorMult : : _ZZ2ScolorMult : -1 : 1
-//var sampler diffuseSampler : : _ZZ2SdiffuseSampler : -1 : 1
-//var float2 input.texcoord : $vin.TEXCOORD2 : TEXCOORD2 : 0 : 1
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct VertexShaderInput {
- vec2 texcoord;
-};
-
-struct PixelShaderInput {
- vec2 texcoord;
-};
-
-vec4 _ZZ3Sret_0;
-sampler2D _ZZ3SsZh0004;
-uniform vec4 colorMult;
-uniform sampler diffuseSampler;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
-
- _ZZ3SsZh0004 = sampler2D(diffuseSampler);
- _ZZ3Sret_0 = texture2D(_ZZ3SsZh0004, gl_TexCoord[2].xy)*colorMult;
- gl_FragColor = _ZZ3Sret_0;
- return;
-} // main end
-
diff --git a/o3d/samples/beachdemo/shaders_glsl/just_color.glsl b/o3d/samples/beachdemo/shaders_glsl/just_color.glsl
deleted file mode 100644
index 61c0c9a..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/just_color.glsl
+++ /dev/null
@@ -1,209 +0,0 @@
-// glslv profile log:
-// (66) : warning C7011: implicit cast from "float4" to "float3"
-// (67) : warning C7011: implicit cast from "float4" to "float3"
-// 81 lines, 2 warnings, 0 errors.
-
-// glslf profile log:
-// (66) : warning C7011: implicit cast from "float4" to "float3"
-// (67) : warning C7011: implicit cast from "float4" to "float3"
-// 81 lines, 2 warnings, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic clipHeight
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuse
-//semantic specular
-//semantic shininess
-//var float4x4 world : WORLD : _ZZ2Sworld[0], 4 : -1 : 1
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : _ZZ2SworldViewProjection[0], 4 : -1 : 1
-//var float3 lightWorldPos : : : -1 : 0
-//var float4 lightColor : : : -1 : 0
-//var float clipHeight : : : -1 : 0
-//var float4x4 viewInverse : VIEWINVERSE : , 4 : -1 : 0
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : _ZZ2SworldInverseTranspose[0], 4 : -1 : 1
-//var float4 emissive : : : -1 : 0
-//var float4 ambient : : : -1 : 0
-//var float4 diffuse : : : -1 : 0
-//var float4 specular : : : -1 : 0
-//var float shininess : : : -1 : 0
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float4 input.normal : $vin.ATTR8 : $_ZZ3SZaTMP20 : 0 : 1
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-//var float4 vertexShaderFunction.worldPosition : $vout.TEXCOORD0 : TEXCOORD0 : -1 : 1
-//var float3 vertexShaderFunction.normal : $vout.TEXCOORD1 : TEXCOORD1 : -1 : 1
-
-attribute vec4 position;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct InVertex {
- vec4 position;
- vec4 normal;
-};
-
-struct OutVertex {
- vec4 position;
- vec4 worldPosition;
- vec3 normal;
-};
-
-OutVertex _ZZ3Sret_0;
-vec4 _ZZ3SrZh0015;
-vec4 _ZZ3SrZh0017;
-vec4 _ZZ3SrZh0019;
-vec4 _ZZ3SvZh0019;
-attribute vec4 normal;
-uniform mat4 world;
-uniform mat4 worldViewProjection;
-uniform mat4 worldInverseTranspose;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
-
- _ZZ3SrZh0015 = position.x*worldViewProjection[0];
- _ZZ3SrZh0015 = _ZZ3SrZh0015 + position.y*worldViewProjection[1];
- _ZZ3SrZh0015 = _ZZ3SrZh0015 + position.z*worldViewProjection[2];
- _ZZ3SrZh0015 = _ZZ3SrZh0015 + position.w*worldViewProjection[3];
- _ZZ3SrZh0017 = position.x*world[0];
- _ZZ3SrZh0017 = _ZZ3SrZh0017 + position.y*world[1];
- _ZZ3SrZh0017 = _ZZ3SrZh0017 + position.z*world[2];
- _ZZ3SrZh0017 = _ZZ3SrZh0017 + position.w*world[3];
- _ZZ3SvZh0019 = vec4(normal.x, normal.y, normal.z, 0.00000000E+00);
- _ZZ3SrZh0019 = _ZZ3SvZh0019.x*worldInverseTranspose[0];
- _ZZ3SrZh0019 = _ZZ3SrZh0019 + _ZZ3SvZh0019.y*worldInverseTranspose[1];
- _ZZ3SrZh0019 = _ZZ3SrZh0019 + _ZZ3SvZh0019.z*worldInverseTranspose[2];
- _ZZ3SrZh0019 = _ZZ3SrZh0019 + _ZZ3SvZh0019.w*worldInverseTranspose[3];
- _ZZ3SrZh0019.xyz;
- _ZZ3Sret_0.position = _ZZ3SrZh0015;
- _ZZ3Sret_0.worldPosition = _ZZ3SrZh0017;
- _ZZ3Sret_0.normal = _ZZ3SrZh0019.xyz;
- gl_TexCoord[0] = _ZZ3SrZh0017;
- _glPositionTemp = _ZZ3SrZh0015; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- gl_TexCoord[1].xyz = _ZZ3SrZh0019.xyz;
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic clipHeight
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuse
-//semantic specular
-//semantic shininess
-//var float4x4 world : WORLD : , 4 : -1 : 0
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float3 lightWorldPos : : _ZZ2SlightWorldPos : -1 : 1
-//var float4 lightColor : : _ZZ2SlightColor : -1 : 1
-//var float clipHeight : : _ZZ2SclipHeight : -1 : 1
-//var float4x4 viewInverse : VIEWINVERSE : _ZZ2SviewInverse[0], 4 : -1 : 1
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : , 4 : -1 : 0
-//var float4 emissive : : _ZZ2Semissive : -1 : 1
-//var float4 ambient : : _ZZ2Sambient : -1 : 1
-//var float4 diffuse : : _ZZ2Sdiffuse : -1 : 1
-//var float4 specular : : _ZZ2Sspecular : -1 : 1
-//var float shininess : : _ZZ2Sshininess : -1 : 1
-//var float4 input.worldPosition : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float3 input.normal : $vin.TEXCOORD1 : TEXCOORD1 : 0 : 1
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct InVertex {
- vec4 normal;
-};
-
-struct OutVertex {
- vec4 worldPosition;
- vec3 normal;
-};
-
-vec4 _ZZ3Sret_0;
-vec3 _ZZ3SZDtemp14;
-float _ZZ3SxZh0019;
-vec3 _ZZ3SZDtemp20;
-vec3 _ZZ3SvZh0021;
-float _ZZ3SxZh0025;
-vec4 _ZZ3SZDtemp26;
-vec4 _ZZ3SvZh0027;
-float _ZZ3SxZh0031;
-vec3 _ZZ3SZDtemp32;
-vec3 _ZZ3SvZh0033;
-float _ZZ3SxZh0037;
-vec4 _ZZ3StmpZh0043;
-float _ZZ3SndotlZh0043;
-float _ZZ3SndothZh0043;
-vec4 _ZZ3SZDtemp44;
-float _ZZ3SspecularZh0045;
-float _ZZ3SxZh0049;
-uniform vec3 lightWorldPos;
-uniform vec4 lightColor;
-uniform float clipHeight;
-uniform mat4 viewInverse;
-uniform vec4 emissive;
-uniform vec4 ambient;
-uniform vec4 diffuse;
-uniform vec4 specular;
-uniform float shininess;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
- float _ZZ4Salpha;
- vec3 _ZZ4SZaTMP1;
-
- _ZZ3SxZh0019 = dot(gl_TexCoord[1].xyz, gl_TexCoord[1].xyz);
- _ZZ3SZDtemp14 = inversesqrt(_ZZ3SxZh0019)*gl_TexCoord[1].xyz;
- _ZZ3SvZh0021 = lightWorldPos - gl_TexCoord[0].xyz;
- _ZZ3SxZh0025 = dot(_ZZ3SvZh0021, _ZZ3SvZh0021);
- _ZZ3SZDtemp20 = inversesqrt(_ZZ3SxZh0025)*_ZZ3SvZh0021;
- _ZZ3SvZh0027 = viewInverse[3] - gl_TexCoord[0];
- _ZZ3SxZh0031 = dot(_ZZ3SvZh0027, _ZZ3SvZh0027);
- _ZZ3SZDtemp26 = inversesqrt(_ZZ3SxZh0031)*_ZZ3SvZh0027;
- _ZZ3SvZh0033 = _ZZ3SZDtemp20 + _ZZ3SZDtemp26.xyz;
- _ZZ3SxZh0037 = dot(_ZZ3SvZh0033, _ZZ3SvZh0033);
- _ZZ3SZDtemp32 = inversesqrt(_ZZ3SxZh0037)*_ZZ3SvZh0033;
- _ZZ3SndotlZh0043 = dot(_ZZ3SZDtemp14, _ZZ3SZDtemp20);
- _ZZ3SndothZh0043 = dot(_ZZ3SZDtemp14, _ZZ3SZDtemp32);
- _ZZ3StmpZh0043 = vec4(_ZZ3SndotlZh0043, _ZZ3SndothZh0043, shininess, shininess);
- _ZZ3SxZh0049 = max(0.00000000E+00, _ZZ3StmpZh0043.y);
- _ZZ3SspecularZh0045 = _ZZ3StmpZh0043.x > 0.00000000E+00 ? pow(_ZZ3SxZh0049, _ZZ3StmpZh0043.z) : 0.00000000E+00;
- _ZZ3SZDtemp44 = vec4(1.00000000E+00, max(0.00000000E+00, _ZZ3StmpZh0043.x), _ZZ3SspecularZh0045, 1.00000000E+00);
- _ZZ4Salpha = gl_TexCoord[0].z > clipHeight ? 0.00000000E+00 : diffuse.w;
- _ZZ4SZaTMP1 = (emissive + lightColor*(ambient*diffuse + diffuse*_ZZ3SZDtemp44.y + specular*_ZZ3SZDtemp44.z)).xyz;
- _ZZ3Sret_0 = vec4(_ZZ4SZaTMP1.x, _ZZ4SZaTMP1.y, _ZZ4SZaTMP1.z, _ZZ4Salpha);
- gl_FragColor = _ZZ3Sret_0;
- return;
-} // main end
-
diff --git a/o3d/samples/beachdemo/shaders_glsl/proxy.glsl b/o3d/samples/beachdemo/shaders_glsl/proxy.glsl
deleted file mode 100644
index 140ce79..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/proxy.glsl
+++ /dev/null
@@ -1,209 +0,0 @@
-// glslv profile log:
-// (66) : warning C7011: implicit cast from "float4" to "float3"
-// (67) : warning C7011: implicit cast from "float4" to "float3"
-// 81 lines, 2 warnings, 0 errors.
-
-// glslf profile log:
-// (66) : warning C7011: implicit cast from "float4" to "float3"
-// (67) : warning C7011: implicit cast from "float4" to "float3"
-// 81 lines, 2 warnings, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuse
-//semantic specular
-//semantic shininess
-//semantic offset
-//var float4x4 world : WORLD : _ZZ2Sworld[0], 4 : -1 : 1
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : _ZZ2SworldViewProjection[0], 4 : -1 : 1
-//var float3 lightWorldPos : : : -1 : 0
-//var float4 lightColor : : : -1 : 0
-//var float4x4 viewInverse : VIEWINVERSE : , 4 : -1 : 0
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : _ZZ2SworldInverseTranspose[0], 4 : -1 : 1
-//var float4 emissive : : : -1 : 0
-//var float4 ambient : : : -1 : 0
-//var float4 diffuse : : : -1 : 0
-//var float4 specular : : : -1 : 0
-//var float shininess : : : -1 : 0
-//var float offset : : : -1 : 0
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float4 input.normal : $vin.ATTR8 : $_ZZ3SZaTMP20 : 0 : 1
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-//var float4 vertexShaderFunction.worldPosition : $vout.TEXCOORD0 : TEXCOORD0 : -1 : 1
-//var float3 vertexShaderFunction.normal : $vout.TEXCOORD1 : TEXCOORD1 : -1 : 1
-
-attribute vec4 position;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct InVertex {
- vec4 position;
- vec4 normal;
-};
-
-struct OutVertex {
- vec4 position;
- vec4 worldPosition;
- vec3 normal;
-};
-
-OutVertex _ZZ3Sret_0;
-vec4 _ZZ3SrZh0015;
-vec4 _ZZ3SrZh0017;
-vec4 _ZZ3SrZh0019;
-vec4 _ZZ3SvZh0019;
-attribute vec4 normal;
-uniform mat4 world;
-uniform mat4 worldViewProjection;
-uniform mat4 worldInverseTranspose;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
-
- _ZZ3SrZh0015 = position.x*worldViewProjection[0];
- _ZZ3SrZh0015 = _ZZ3SrZh0015 + position.y*worldViewProjection[1];
- _ZZ3SrZh0015 = _ZZ3SrZh0015 + position.z*worldViewProjection[2];
- _ZZ3SrZh0015 = _ZZ3SrZh0015 + position.w*worldViewProjection[3];
- _ZZ3SrZh0017 = position.x*world[0];
- _ZZ3SrZh0017 = _ZZ3SrZh0017 + position.y*world[1];
- _ZZ3SrZh0017 = _ZZ3SrZh0017 + position.z*world[2];
- _ZZ3SrZh0017 = _ZZ3SrZh0017 + position.w*world[3];
- _ZZ3SvZh0019 = vec4(normal.x, normal.y, normal.z, 0.00000000E+00);
- _ZZ3SrZh0019 = _ZZ3SvZh0019.x*worldInverseTranspose[0];
- _ZZ3SrZh0019 = _ZZ3SrZh0019 + _ZZ3SvZh0019.y*worldInverseTranspose[1];
- _ZZ3SrZh0019 = _ZZ3SrZh0019 + _ZZ3SvZh0019.z*worldInverseTranspose[2];
- _ZZ3SrZh0019 = _ZZ3SrZh0019 + _ZZ3SvZh0019.w*worldInverseTranspose[3];
- _ZZ3SrZh0019.xyz;
- _ZZ3Sret_0.position = _ZZ3SrZh0015;
- _ZZ3Sret_0.worldPosition = _ZZ3SrZh0017;
- _ZZ3Sret_0.normal = _ZZ3SrZh0019.xyz;
- gl_TexCoord[0] = _ZZ3SrZh0017;
- _glPositionTemp = _ZZ3SrZh0015; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- gl_TexCoord[1].xyz = _ZZ3SrZh0019.xyz;
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic world : WORLD
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic lightWorldPos
-//semantic lightColor
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic emissive
-//semantic ambient
-//semantic diffuse
-//semantic specular
-//semantic shininess
-//semantic offset
-//var float4x4 world : WORLD : , 4 : -1 : 0
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float3 lightWorldPos : : _ZZ2SlightWorldPos : -1 : 1
-//var float4 lightColor : : _ZZ2SlightColor : -1 : 1
-//var float4x4 viewInverse : VIEWINVERSE : _ZZ2SviewInverse[0], 4 : -1 : 1
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : , 4 : -1 : 0
-//var float4 emissive : : _ZZ2Semissive : -1 : 1
-//var float4 ambient : : _ZZ2Sambient : -1 : 1
-//var float4 diffuse : : _ZZ2Sdiffuse : -1 : 1
-//var float4 specular : : _ZZ2Sspecular : -1 : 1
-//var float shininess : : _ZZ2Sshininess : -1 : 1
-//var float offset : : _ZZ2Soffset : -1 : 1
-//var float4 input.worldPosition : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float3 input.normal : $vin.TEXCOORD1 : TEXCOORD1 : 0 : 1
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct InVertex {
- vec4 normal;
-};
-
-struct OutVertex {
- vec4 worldPosition;
- vec3 normal;
-};
-
-vec4 _ZZ3Sret_0;
-vec3 _ZZ3SZDtemp14;
-float _ZZ3SxZh0019;
-vec3 _ZZ3SZDtemp20;
-vec3 _ZZ3SvZh0021;
-float _ZZ3SxZh0025;
-vec4 _ZZ3SZDtemp26;
-vec4 _ZZ3SvZh0027;
-float _ZZ3SxZh0031;
-vec3 _ZZ3SZDtemp32;
-vec3 _ZZ3SvZh0033;
-float _ZZ3SxZh0037;
-vec4 _ZZ3StmpZh0043;
-float _ZZ3SndotlZh0043;
-float _ZZ3SndothZh0043;
-vec4 _ZZ3SZDtemp44;
-float _ZZ3SspecularZh0045;
-float _ZZ3SxZh0049;
-uniform vec3 lightWorldPos;
-uniform vec4 lightColor;
-uniform mat4 viewInverse;
-uniform vec4 emissive;
-uniform vec4 ambient;
-uniform vec4 diffuse;
-uniform vec4 specular;
-uniform float shininess;
-uniform float offset;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
- float _ZZ4Salpha;
- vec3 _ZZ4SZaTMP1;
-
- _ZZ3SxZh0019 = dot(gl_TexCoord[1].xyz, gl_TexCoord[1].xyz);
- _ZZ3SZDtemp14 = inversesqrt(_ZZ3SxZh0019)*gl_TexCoord[1].xyz;
- _ZZ3SvZh0021 = lightWorldPos - gl_TexCoord[0].xyz;
- _ZZ3SxZh0025 = dot(_ZZ3SvZh0021, _ZZ3SvZh0021);
- _ZZ3SZDtemp20 = inversesqrt(_ZZ3SxZh0025)*_ZZ3SvZh0021;
- _ZZ3SvZh0027 = viewInverse[3] - gl_TexCoord[0];
- _ZZ3SxZh0031 = dot(_ZZ3SvZh0027, _ZZ3SvZh0027);
- _ZZ3SZDtemp26 = inversesqrt(_ZZ3SxZh0031)*_ZZ3SvZh0027;
- _ZZ3SvZh0033 = _ZZ3SZDtemp20 + _ZZ3SZDtemp26.xyz;
- _ZZ3SxZh0037 = dot(_ZZ3SvZh0033, _ZZ3SvZh0033);
- _ZZ3SZDtemp32 = inversesqrt(_ZZ3SxZh0037)*_ZZ3SvZh0033;
- _ZZ3SndotlZh0043 = dot(_ZZ3SZDtemp14, _ZZ3SZDtemp20);
- _ZZ3SndothZh0043 = dot(_ZZ3SZDtemp14, _ZZ3SZDtemp32);
- _ZZ3StmpZh0043 = vec4(_ZZ3SndotlZh0043, _ZZ3SndothZh0043, shininess, shininess);
- _ZZ3SxZh0049 = max(0.00000000E+00, _ZZ3StmpZh0043.y);
- _ZZ3SspecularZh0045 = _ZZ3StmpZh0043.x > 0.00000000E+00 ? pow(_ZZ3SxZh0049, _ZZ3StmpZh0043.z) : 0.00000000E+00;
- _ZZ3SZDtemp44 = vec4(1.00000000E+00, max(0.00000000E+00, _ZZ3StmpZh0043.x), _ZZ3SspecularZh0045, 1.00000000E+00);
- _ZZ4Salpha = gl_TexCoord[0].z > offset ? 0.00000000E+00 : diffuse.w;
- _ZZ4SZaTMP1 = (emissive + lightColor*(ambient*diffuse + diffuse*_ZZ3SZDtemp44.y + specular*_ZZ3SZDtemp44.z)).xyz;
- _ZZ3Sret_0 = vec4(_ZZ4SZaTMP1.x, _ZZ4SZaTMP1.y, _ZZ4SZaTMP1.z, _ZZ4Salpha);
- gl_FragColor = _ZZ3Sret_0;
- return;
-} // main end
-
diff --git a/o3d/samples/beachdemo/shaders_glsl/simpleshader.glsl b/o3d/samples/beachdemo/shaders_glsl/simpleshader.glsl
deleted file mode 100644
index 871199e..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/simpleshader.glsl
+++ /dev/null
@@ -1,90 +0,0 @@
-// glslv profile log:
-// 55 lines, 0 errors.
-
-// glslf profile log:
-// 55 lines, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic simpleColor
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : _ZZ2SworldViewProjection[0], 4 : -1 : 1
-//var float4 simpleColor : : : -1 : 0
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-
-attribute vec4 position;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct VertexShaderInput {
- vec4 position;
-};
-
-struct PixelShaderInput {
- vec4 position;
-};
-
-PixelShaderInput _ZZ3Sret_0;
-vec4 _ZZ3SrZh0003;
-uniform mat4 worldViewProjection;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
-
- _ZZ3SrZh0003 = position.x*worldViewProjection[0];
- _ZZ3SrZh0003 = _ZZ3SrZh0003 + position.y*worldViewProjection[1];
- _ZZ3SrZh0003 = _ZZ3SrZh0003 + position.z*worldViewProjection[2];
- _ZZ3SrZh0003 = _ZZ3SrZh0003 + position.w*worldViewProjection[3];
- _ZZ3Sret_0.position = _ZZ3SrZh0003;
- _glPositionTemp = _ZZ3SrZh0003; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic simpleColor
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float4 simpleColor : : _ZZ2SsimpleColor : -1 : 1
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct VertexShaderInput {
- int dummy;
-};
-
-struct PixelShaderInput {
- int dummy;
-};
-
-vec4 _ZZ3Sret_0;
-uniform vec4 simpleColor;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
-
- _ZZ3Sret_0 = simpleColor;
- gl_FragColor = simpleColor;
- return;
-} // main end
-
diff --git a/o3d/samples/beachdemo/shaders_glsl/skydomeshader.glsl b/o3d/samples/beachdemo/shaders_glsl/skydomeshader.glsl
deleted file mode 100644
index 64c01e9..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/skydomeshader.glsl
+++ /dev/null
@@ -1,116 +0,0 @@
-// glslv profile log:
-// 62 lines, 0 errors.
-
-// glslf profile log:
-// 62 lines, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic worldViewProjectionInverse : VIEWPROJECTIONINVERSE
-//semantic viewInverse : VIEWINVERSE
-//semantic environmentSampler
-//var float4x4 worldViewProjectionInverse : VIEWPROJECTIONINVERSE : _ZZ2SworldViewProjectionInverse[0], 4 : -1 : 1
-//var float4x4 viewInverse : VIEWINVERSE : , 4 : -1 : 0
-//var samplerCUBE environmentSampler : : : -1 : 0
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-//var float3 vertexShaderFunction.worldPosition : $vout.TEXCOORD0 : TEXCOORD0 : -1 : 1
-
-attribute vec4 position;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct VertexShaderInput {
- vec4 position;
-};
-
-struct PixelShaderInput {
- vec4 position;
- vec3 worldPosition;
-};
-
-PixelShaderInput _ZZ3Sret_0;
-vec4 _ZZ3SrZh0004;
-uniform mat4 viewProjectionInverse;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
- PixelShaderInput _ZZ4Soutput;
-
- _ZZ3SrZh0004 = position.x*viewProjectionInverse[0];
- _ZZ3SrZh0004 = _ZZ3SrZh0004 + position.y*viewProjectionInverse[1];
- _ZZ3SrZh0004 = _ZZ3SrZh0004 + position.z*viewProjectionInverse[2];
- _ZZ3SrZh0004 = _ZZ3SrZh0004 + position.w*viewProjectionInverse[3];
- _ZZ4Soutput.worldPosition = _ZZ3SrZh0004.xyz/_ZZ3SrZh0004.w;
- _ZZ3Sret_0.position = position;
- _ZZ3Sret_0.worldPosition = _ZZ4Soutput.worldPosition;
- gl_TexCoord[0].xyz = _ZZ4Soutput.worldPosition;
- _glPositionTemp = position; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic worldViewProjectionInverse : VIEWPROJECTIONINVERSE
-//semantic viewInverse : VIEWINVERSE
-//semantic environmentSampler
-//var float4x4 worldViewProjectionInverse : VIEWPROJECTIONINVERSE : , 4 : -1 : 0
-//var float4x4 viewInverse : VIEWINVERSE : _ZZ2SviewInverse[0], 4 : -1 : 1
-//var samplerCUBE environmentSampler : : _ZZ2SenvironmentSampler : -1 : 1
-//var float3 input.worldPosition : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct VertexShaderInput {
- int dummy;
-};
-
-struct PixelShaderInput {
- vec3 worldPosition;
-};
-
-vec4 _ZZ3Sret_0;
-vec3 _ZZ3SZDtemp3;
-vec3 _ZZ3SvZh0004;
-float _ZZ3SxZh0008;
-float _ZZ3SaZh0010;
-vec3 _ZZ3ScZh0012;
-vec3 _ZZ3SZaTMP13;
-uniform mat4 viewInverse;
-uniform samplerCube environmentSampler;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
-
- _ZZ3SZaTMP13.x = viewInverse[3].x;
- _ZZ3SZaTMP13.y = viewInverse[3].y;
- _ZZ3SZaTMP13.z = viewInverse[3].z;
- _ZZ3SvZh0004 = _ZZ3SZaTMP13 - gl_TexCoord[0].xyz;
- _ZZ3SxZh0008 = dot(_ZZ3SvZh0004, _ZZ3SvZh0004);
- _ZZ3SZDtemp3 = inversesqrt(_ZZ3SxZh0008)*_ZZ3SvZh0004;
- _ZZ3SaZh0010 = -_ZZ3SZDtemp3.z;
- _ZZ3ScZh0012 = vec3(_ZZ3SZDtemp3.x, abs(_ZZ3SaZh0010) + 9.99999978E-03, -_ZZ3SZDtemp3.y);
- _ZZ3Sret_0 = textureCube(environmentSampler, _ZZ3ScZh0012);
- gl_FragColor = _ZZ3Sret_0;
- return;
-} // main end
-
diff --git a/o3d/samples/beachdemo/shaders_glsl/underwatershader.glsl b/o3d/samples/beachdemo/shaders_glsl/underwatershader.glsl
deleted file mode 100644
index 6a7838f..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/underwatershader.glsl
+++ /dev/null
@@ -1,174 +0,0 @@
-// glslv profile log:
-// (64) : warning C7011: implicit cast from "float4" to "float3"
-// (64) : warning C7011: implicit cast from "float4" to "float3"
-// 80 lines, 2 warnings, 0 errors.
-
-// glslf profile log:
-// 80 lines, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic world : WORLD
-//semantic viewProjection : VIEWPROJECTION
-//semantic waterColor
-//semantic sunVector
-//semantic fadeFudge
-//semantic diffuseSampler
-//var float4x4 world : WORLD : _ZZ2Sworld[0], 4 : -1 : 1
-//var float4x4 viewProjection : VIEWPROJECTION : _ZZ2SviewProjection[0], 4 : -1 : 1
-//var float4 waterColor : : : -1 : 0
-//var float3 sunVector : : _ZZ2SsunVector : -1 : 1
-//var float fadeFudge : : _ZZ2SfadeFudge : -1 : 1
-//var sampler diffuseSampler : : : -1 : 0
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float3 input.normal : $vin.ATTR8 : $_ZZ3SZaTMP32 : 0 : 1
-//var float2 input.texcoord : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-//var float2 vertexShaderFunction.texcoord : $vout.TEXCOORD0 : TEXCOORD0 : -1 : 1
-//var float vertexShaderFunction.fade : $vout.TEXCOORD1 : TEXCOORD1 : -1 : 1
-//var float4 vertexShaderFunction.color : $vout.TEXCOORD2 : TEXCOORD2 : -1 : 1
-//var float4 vertexShaderFunction.worldPosition : $vout.TEXCOORD3 : TEXCOORD3 : -1 : 1
-
-attribute vec4 position;
-attribute vec4 texcoord0;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct VertexShaderInput {
- vec4 position;
- vec3 normal;
- vec2 texcoord;
-};
-
-struct PixelShaderInput {
- vec4 position;
- vec2 texcoord;
- float fade;
- vec4 color;
- vec4 worldPosition;
-};
-
-PixelShaderInput _ZZ3Sret_0;
-vec4 _ZZ3SrZh0011;
-vec4 _ZZ3SrZh0013;
-vec4 _ZZ3SvZh0013;
-vec4 _ZZ3SrZh0015;
-vec4 _ZZ3SvZh0015;
-vec4 _ZZ3SZDtemp16;
-float _ZZ3SxZh0023;
-float _ZZ3SxZh0025;
-float _ZZ3SZDtemp26;
-float _ZZ3SbZh0031;
-attribute vec4 normal;
-uniform mat4 world;
-uniform mat4 viewprojection;
-uniform vec3 sunVector;
-uniform float fadeFudge;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
- PixelShaderInput _ZZ4Soutput;
-
- _ZZ3SrZh0011 = position.x*world[0];
- _ZZ3SrZh0011 = _ZZ3SrZh0011 + position.y*world[1];
- _ZZ3SrZh0011 = _ZZ3SrZh0011 + position.z*world[2];
- _ZZ3SrZh0011 = _ZZ3SrZh0011 + position.w*world[3];
- _ZZ3SvZh0013 = vec4(_ZZ3SrZh0011.x, _ZZ3SrZh0011.y, _ZZ3SrZh0011.z, 1.00000000E+00);
- _ZZ3SrZh0013 = _ZZ3SvZh0013.x*viewprojection[0];
- _ZZ3SrZh0013 = _ZZ3SrZh0013 + _ZZ3SvZh0013.y*viewprojection[1];
- _ZZ3SrZh0013 = _ZZ3SrZh0013 + _ZZ3SvZh0013.z*viewprojection[2];
- _ZZ3SrZh0013 = _ZZ3SrZh0013 + _ZZ3SvZh0013.w*viewprojection[3];
- _ZZ3SvZh0015 = vec4(normal.x, normal.y, normal.z, 0.00000000E+00);
- _ZZ3SrZh0015 = _ZZ3SvZh0015.x*world[0];
- _ZZ3SrZh0015 = _ZZ3SrZh0015 + _ZZ3SvZh0015.y*world[1];
- _ZZ3SrZh0015 = _ZZ3SrZh0015 + _ZZ3SvZh0015.z*world[2];
- _ZZ3SrZh0015 = _ZZ3SrZh0015 + _ZZ3SvZh0015.w*world[3];
- _ZZ3SxZh0023 = dot(_ZZ3SrZh0015, _ZZ3SrZh0015);
- _ZZ3SZDtemp16 = inversesqrt(_ZZ3SxZh0023)*_ZZ3SrZh0015;
- _ZZ4Soutput.color = vec4(dot(sunVector, _ZZ3SZDtemp16.xyz), dot(sunVector, _ZZ3SZDtemp16.xyz), dot(sunVector, _ZZ3SZDtemp16.xyz), dot(sunVector, _ZZ3SZDtemp16.xyz));
- _ZZ3SxZh0025 = _ZZ3SrZh0011.z*fadeFudge;
- _ZZ3SbZh0031 = min(1.00000000E+00, _ZZ3SxZh0025);
- _ZZ3SZDtemp26 = max(0.00000000E+00, _ZZ3SbZh0031);
- _ZZ4Soutput.fade = 2.00000003E-01 + 8.00000012E-01*_ZZ3SZDtemp26;
- _ZZ3Sret_0.position = _ZZ3SrZh0013;
- _ZZ3Sret_0.texcoord = texcoord0.xy;
- _ZZ3Sret_0.fade = _ZZ4Soutput.fade;
- _ZZ3Sret_0.color = _ZZ4Soutput.color;
- _ZZ3Sret_0.worldPosition = _ZZ3SrZh0011;
- gl_TexCoord[0].xy = texcoord0.xy;
- gl_TexCoord[2] = _ZZ4Soutput.color;
- _glPositionTemp = _ZZ3SrZh0013; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- gl_TexCoord[1].x = _ZZ4Soutput.fade;
- gl_TexCoord[3] = _ZZ3SrZh0011;
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic world : WORLD
-//semantic viewProjection : VIEWPROJECTION
-//semantic waterColor
-//semantic sunVector
-//semantic fadeFudge
-//semantic diffuseSampler
-//var float4x4 world : WORLD : , 4 : -1 : 0
-//var float4x4 viewProjection : VIEWPROJECTION : , 4 : -1 : 0
-//var float4 waterColor : : : -1 : 0
-//var float3 sunVector : : : -1 : 0
-//var float fadeFudge : : : -1 : 0
-//var sampler diffuseSampler : : _ZZ2SdiffuseSampler : -1 : 1
-//var float2 input.texcoord : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float input.fade : $vin.TEXCOORD1 : : 0 : 0
-//var float4 input.color : $vin.TEXCOORD2 : : 0 : 0
-//var float4 input.worldPosition : $vin.TEXCOORD3 : TEXCOORD3 : 0 : 1
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct VertexShaderInput {
- vec3 normal;
- vec2 texcoord;
-};
-
-struct PixelShaderInput {
- vec2 texcoord;
- float fade;
- vec4 color;
- vec4 worldPosition;
-};
-
-vec4 _ZZ3Sret_0;
-sampler2D _ZZ3SsZh0009;
-uniform sampler diffuseSampler;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
- vec4 _ZZ4Scolor;
- float _ZZ4Salpha;
-
- _ZZ3SsZh0009 = sampler2D(diffuseSampler);
- _ZZ4Scolor = texture2D(_ZZ3SsZh0009, gl_TexCoord[0].xy);
- _ZZ4Salpha = gl_TexCoord[3].z < 1.00000000E+02 ? _ZZ4Scolor.w : 0.00000000E+00;
- _ZZ3Sret_0 = vec4(_ZZ4Scolor.x, _ZZ4Scolor.y, _ZZ4Scolor.z, _ZZ4Salpha);
- gl_FragColor = _ZZ3Sret_0;
- return;
-} // main end
-
diff --git a/o3d/samples/beachdemo/shaders_glsl/watercolorandskyshader.glsl b/o3d/samples/beachdemo/shaders_glsl/watercolorandskyshader.glsl
deleted file mode 100644
index f388f11..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/watercolorandskyshader.glsl
+++ /dev/null
@@ -1,236 +0,0 @@
-// glslv profile log:
-// (102) : warning C7011: implicit cast from "float4" to "float3"
-// (105) : warning C7011: implicit cast from "float4" to "float3"
-// (108) : warning C7011: implicit cast from "float4" to "float3"
-// (119) : warning C7011: implicit cast from "float4" to "float3"
-// 131 lines, 4 warnings, 0 errors.
-
-// glslf profile log:
-// (102) : warning C7011: implicit cast from "float4" to "float3"
-// (105) : warning C7011: implicit cast from "float4" to "float3"
-// (108) : warning C7011: implicit cast from "float4" to "float3"
-// (119) : warning C7011: implicit cast from "float4" to "float3"
-// 131 lines, 4 warnings, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic world : WORLD
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic view : VIEW
-//semantic viewProjection : VIEWPROJECTION
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic viewPosition
-//semantic waterColor
-//semantic reflectionRefractionOffset
-//semantic clock
-//semantic environmentSampler
-//semantic fresnelSampler
-//semantic noiseSampler
-//semantic noiseSampler2
-//semantic noiseSampler3
-//var float4x4 world : WORLD : _ZZ2Sworld[0], 4 : -1 : 1
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : , 4 : -1 : 0
-//var float4x4 view : VIEW : , 4 : -1 : 0
-//var float4x4 viewProjection : VIEWPROJECTION : _ZZ2SviewProjection[0], 4 : -1 : 1
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float3 viewPosition : : _ZZ2SviewPosition : -1 : 1
-//var float4 waterColor : : : -1 : 0
-//var float reflectionRefractionOffset : : _ZZ2SreflectionRefractionOffset : -1 : 1
-//var float clock : : : -1 : 0
-//var samplerCUBE environmentSampler : : : -1 : 0
-//var sampler2D fresnelSampler : : : -1 : 0
-//var sampler2D noiseSampler : : : -1 : 0
-//var sampler2D noiseSampler2 : : : -1 : 0
-//var sampler2D noiseSampler3 : : : -1 : 0
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float2 input.texcoord : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-//var float2 vertexShaderFunction.texcoord : $vout.TEXCOORD0 : TEXCOORD0 : -1 : 1
-//var float3 vertexShaderFunction.viewVector : $vout.TEXCOORD1 : TEXCOORD1 : -1 : 1
-//var float3 vertexShaderFunction.screenPosition : $vout.TEXCOORD2 : TEXCOORD2 : -1 : 1
-
-attribute vec4 position;
-attribute vec4 texcoord0;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct VertexShaderInput {
- vec4 position;
- vec2 texcoord;
-};
-
-struct PixelShaderInput {
- vec4 position;
- vec2 texcoord;
- vec3 viewVector;
- vec3 screenPosition;
-};
-
-PixelShaderInput _ZZ3Sret_0;
-vec4 _ZZ3SrZh0015;
-vec4 _ZZ3SrZh0017;
-vec3 _ZZ3SZDtemp18;
-vec3 _ZZ3SvZh0019;
-float _ZZ3SxZh0023;
-vec4 _ZZ3SrZh0025;
-vec4 _ZZ3SvZh0025;
-uniform mat4 world;
-uniform mat4 viewprojection;
-uniform vec3 viewPosition;
-uniform float reflectionRefractionOffset;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
- PixelShaderInput _ZZ4Soutput;
-
- _ZZ3SrZh0015 = position.x*world[0];
- _ZZ3SrZh0015 = _ZZ3SrZh0015 + position.y*world[1];
- _ZZ3SrZh0015 = _ZZ3SrZh0015 + position.z*world[2];
- _ZZ3SrZh0015 = _ZZ3SrZh0015 + position.w*world[3];
- _ZZ3SrZh0017 = _ZZ3SrZh0015.x*viewprojection[0];
- _ZZ3SrZh0017 = _ZZ3SrZh0017 + _ZZ3SrZh0015.y*viewprojection[1];
- _ZZ3SrZh0017 = _ZZ3SrZh0017 + _ZZ3SrZh0015.z*viewprojection[2];
- _ZZ3SrZh0017 = _ZZ3SrZh0017 + _ZZ3SrZh0015.w*viewprojection[3];
- _ZZ3SvZh0019 = _ZZ3SrZh0015.xyz - viewPosition.xyz;
- _ZZ3SxZh0023 = dot(_ZZ3SvZh0019, _ZZ3SvZh0019);
- _ZZ3SZDtemp18 = inversesqrt(_ZZ3SxZh0023)*_ZZ3SvZh0019;
- _ZZ3SvZh0025 = vec4(_ZZ3SrZh0015.x, _ZZ3SrZh0015.y, 0.00000000E+00, 1.00000000E+00);
- _ZZ3SrZh0025 = _ZZ3SvZh0025.x*viewprojection[0];
- _ZZ3SrZh0025 = _ZZ3SrZh0025 + _ZZ3SvZh0025.y*viewprojection[1];
- _ZZ3SrZh0025 = _ZZ3SrZh0025 + _ZZ3SvZh0025.z*viewprojection[2];
- _ZZ3SrZh0025 = _ZZ3SrZh0025 + _ZZ3SvZh0025.w*viewprojection[3];
- _ZZ4Soutput.screenPosition = _ZZ3SrZh0025.xyz/_ZZ3SrZh0025.w;
- _ZZ4Soutput.screenPosition.xy = 5.00000000E-01 + (5.00000000E-01*_ZZ4Soutput.screenPosition.xy)*vec2( 1.00000000E+00, -1.00000000E+00);
- _ZZ4Soutput.screenPosition.z = reflectionRefractionOffset/_ZZ4Soutput.screenPosition.z;
- _ZZ3Sret_0.position = _ZZ3SrZh0017;
- _ZZ3Sret_0.texcoord = texcoord0.xy;
- _ZZ3Sret_0.viewVector = _ZZ3SZDtemp18;
- _ZZ3Sret_0.screenPosition = _ZZ4Soutput.screenPosition;
- gl_TexCoord[0].xy = texcoord0.xy;
- gl_TexCoord[2].xyz = _ZZ4Soutput.screenPosition;
- _glPositionTemp = _ZZ3SrZh0017; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- gl_TexCoord[1].xyz = _ZZ3SZDtemp18;
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic world : WORLD
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic view : VIEW
-//semantic viewProjection : VIEWPROJECTION
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic viewPosition
-//semantic waterColor
-//semantic reflectionRefractionOffset
-//semantic clock
-//semantic environmentSampler
-//semantic fresnelSampler
-//semantic noiseSampler
-//semantic noiseSampler2
-//semantic noiseSampler3
-//var float4x4 world : WORLD : , 4 : -1 : 0
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : , 4 : -1 : 0
-//var float4x4 view : VIEW : , 4 : -1 : 0
-//var float4x4 viewProjection : VIEWPROJECTION : , 4 : -1 : 0
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float3 viewPosition : : : -1 : 0
-//var float4 waterColor : : _ZZ2SwaterColor : -1 : 1
-//var float reflectionRefractionOffset : : : -1 : 0
-//var float clock : : _ZZ2Sclock : -1 : 1
-//var samplerCUBE environmentSampler : : _ZZ2SenvironmentSampler : -1 : 1
-//var sampler2D fresnelSampler : : _ZZ2SfresnelSampler : -1 : 1
-//var sampler2D noiseSampler : : _ZZ2SnoiseSampler : -1 : 1
-//var sampler2D noiseSampler2 : : _ZZ2SnoiseSampler2 : -1 : 1
-//var sampler2D noiseSampler3 : : _ZZ2SnoiseSampler3 : -1 : 1
-//var float2 input.texcoord : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float3 input.viewVector : $vin.TEXCOORD1 : TEXCOORD1 : 0 : 1
-//var float3 input.screenPosition : $vin.TEXCOORD2 : : 0 : 0
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct VertexShaderInput {
- vec2 texcoord;
-};
-
-struct PixelShaderInput {
- vec2 texcoord;
- vec3 viewVector;
- vec3 screenPosition;
-};
-
-vec4 _ZZ3Sret_0;
-vec2 _ZZ3ScZh0017;
-vec2 _ZZ3ScZh0019;
-vec2 _ZZ3ScZh0021;
-vec3 _ZZ3SZDtemp22;
-vec3 _ZZ3SvZh0023;
-float _ZZ3SxZh0027;
-vec3 _ZZ3SZDtemp28;
-vec3 _ZZ3SZDtemp30;
-float _ZZ3SxZh0037;
-vec2 _ZZ3ScZh0041;
-uniform vec4 waterColor;
-uniform float clock;
-uniform samplerCube environmentSampler;
-uniform sampler2D fresnelSampler;
-uniform sampler2D noiseSampler;
-uniform sampler2D noiseSampler2;
-uniform sampler2D noiseSampler3;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
- vec3 _ZZ4SviewVector;
- vec2 _ZZ4Stexcoord;
- vec3 _ZZ4Sn1;
- vec3 _ZZ4Sn2;
- vec3 _ZZ4Sn3;
- vec3 _ZZ4SR;
- float _ZZ4Sf;
- vec3 _ZZ4SskyReflection;
- vec3 _ZZ4Scolor;
-
- _ZZ4SviewVector = vec3(gl_TexCoord[1].x, gl_TexCoord[1].z, -gl_TexCoord[1].y);
- _ZZ4Stexcoord = gl_TexCoord[0].xy*4.00000000E+00;
- _ZZ3ScZh0017 = _ZZ4Stexcoord + vec2(clock*9.99999978E-03, clock*1.99999996E-02);
- _ZZ4Sn1 = texture2D(noiseSampler, _ZZ3ScZh0017).xyz;
- _ZZ3ScZh0019 = _ZZ4Stexcoord + vec2(clock*2.99999993E-02, clock*9.99999978E-03);
- _ZZ4Sn2 = texture2D(noiseSampler2, _ZZ3ScZh0019).xyz;
- _ZZ3ScZh0021 = _ZZ4Stexcoord + vec2(clock*4.99999989E-03, clock*7.00000022E-03);
- _ZZ4Sn3 = texture2D(noiseSampler3, _ZZ3ScZh0021).xyz;
- _ZZ3SvZh0023 = _ZZ4Sn1 + _ZZ4Sn2*2.00000000E+00 + _ZZ4Sn3*4.00000000E+00 + vec3( -3.50000000E+00, 1.60000000E+01, -3.50000000E+00);
- _ZZ3SxZh0027 = dot(_ZZ3SvZh0023, _ZZ3SvZh0023);
- _ZZ3SZDtemp22 = inversesqrt(_ZZ3SxZh0027)*_ZZ3SvZh0023;
- _ZZ3SZDtemp28 = _ZZ4SviewVector - (2.00000000E+00*_ZZ3SZDtemp22)*dot(_ZZ3SZDtemp22, _ZZ4SviewVector);
- _ZZ3SxZh0037 = dot(_ZZ3SZDtemp28, _ZZ3SZDtemp28);
- _ZZ3SZDtemp30 = inversesqrt(_ZZ3SxZh0037)*_ZZ3SZDtemp28;
- _ZZ4SR = _ZZ3SZDtemp30;
- _ZZ4SR.y = _ZZ3SZDtemp30.y < 9.99999978E-03 ? 9.99999978E-03 : _ZZ3SZDtemp30.y;
- _ZZ3ScZh0041 = vec2(dot(_ZZ4SR, _ZZ3SZDtemp22), 5.00000000E-01);
- _ZZ4Sf = texture2D(fresnelSampler, _ZZ3ScZh0041).x;
- _ZZ4SskyReflection = textureCube(environmentSampler, _ZZ4SR).xyz;
- _ZZ4Scolor = waterColor.xyz + _ZZ4Sf*(_ZZ4SskyReflection - waterColor.xyz);
- _ZZ3Sret_0 = vec4(_ZZ4Scolor.x, _ZZ4Scolor.y, _ZZ4Scolor.z, 1.00000000E+00);
- gl_FragColor = _ZZ3Sret_0;
- return;
-} // main end
-
diff --git a/o3d/samples/beachdemo/shaders_glsl/waterfallshader.glsl b/o3d/samples/beachdemo/shaders_glsl/waterfallshader.glsl
deleted file mode 100644
index e15dd0d..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/waterfallshader.glsl
+++ /dev/null
@@ -1,194 +0,0 @@
-// glslv profile log:
-// 80 lines, 0 errors.
-
-// glslf profile log:
-// 80 lines, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic world : WORLD
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic lightWorldPos
-//semantic vOffset
-//semantic diffuseSampler
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : _ZZ2SworldViewProjection[0], 4 : -1 : 1
-//var float4x4 world : WORLD : _ZZ2Sworld[0], 4 : -1 : 1
-//var float4x4 viewInverse : VIEWINVERSE : , 4 : -1 : 0
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : _ZZ2SworldInverseTranspose[0], 4 : -1 : 1
-//var float3 lightWorldPos : : : -1 : 0
-//var float vOffset : : : -1 : 0
-//var sampler diffuseSampler : : : -1 : 0
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float4 input.normal : $vin.ATTR8 : $_ZZ3SZaTMP13 : 0 : 1
-//var float2 input.texcoord : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-//var float3 vertexShaderFunction.normal : $vout.TEXCOORD0 : TEXCOORD0 : -1 : 1
-//var float3 vertexShaderFunction.worldPosition : $vout.TEXCOORD1 : TEXCOORD1 : -1 : 1
-//var float2 vertexShaderFunction.texcoord : $vout.TEXCOORD2 : TEXCOORD2 : -1 : 1
-
-attribute vec4 position;
-attribute vec4 texcoord0;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct VertexShaderInput {
- vec4 position;
- vec4 normal;
- vec2 texcoord;
-};
-
-struct PixelShaderInput {
- vec4 position;
- vec3 normal;
- vec3 worldPosition;
- vec2 texcoord;
-};
-
-PixelShaderInput _ZZ3Sret_0;
-vec4 _ZZ3SrZh0008;
-vec4 _ZZ3SrZh0010;
-vec4 _ZZ3SrZh0012;
-attribute vec4 normal;
-uniform mat4 worldViewProjection;
-uniform mat4 world;
-uniform mat4 worldInverseTranspose;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
-
- _ZZ3SrZh0008 = position.x*worldViewProjection[0];
- _ZZ3SrZh0008 = _ZZ3SrZh0008 + position.y*worldViewProjection[1];
- _ZZ3SrZh0008 = _ZZ3SrZh0008 + position.z*worldViewProjection[2];
- _ZZ3SrZh0008 = _ZZ3SrZh0008 + position.w*worldViewProjection[3];
- _ZZ3SrZh0010 = position.x*world[0];
- _ZZ3SrZh0010 = _ZZ3SrZh0010 + position.y*world[1];
- _ZZ3SrZh0010 = _ZZ3SrZh0010 + position.z*world[2];
- _ZZ3SrZh0010 = _ZZ3SrZh0010 + position.w*world[3];
- _ZZ3SrZh0012 = normal.x*worldInverseTranspose[0];
- _ZZ3SrZh0012 = _ZZ3SrZh0012 + normal.y*worldInverseTranspose[1];
- _ZZ3SrZh0012 = _ZZ3SrZh0012 + normal.z*worldInverseTranspose[2];
- _ZZ3SrZh0012 = _ZZ3SrZh0012 + normal.w*worldInverseTranspose[3];
- _ZZ3SrZh0012.xyz;
- _ZZ3SrZh0010.xyz;
- _ZZ3Sret_0.position = _ZZ3SrZh0008;
- _ZZ3Sret_0.normal = _ZZ3SrZh0012.xyz;
- _ZZ3Sret_0.worldPosition = _ZZ3SrZh0010.xyz;
- _ZZ3Sret_0.texcoord = texcoord0.xy;
- gl_TexCoord[0].xyz = _ZZ3SrZh0012.xyz;
- gl_TexCoord[2].xy = texcoord0.xy;
- _glPositionTemp = _ZZ3SrZh0008; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- gl_TexCoord[1].xyz = _ZZ3SrZh0010.xyz;
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic world : WORLD
-//semantic viewInverse : VIEWINVERSE
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic lightWorldPos
-//semantic vOffset
-//semantic diffuseSampler
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float4x4 world : WORLD : , 4 : -1 : 0
-//var float4x4 viewInverse : VIEWINVERSE : _ZZ2SviewInverse[0], 4 : -1 : 1
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : , 4 : -1 : 0
-//var float3 lightWorldPos : : _ZZ2SlightWorldPos : -1 : 1
-//var float vOffset : : _ZZ2SvOffset : -1 : 1
-//var sampler diffuseSampler : : _ZZ2SdiffuseSampler : -1 : 1
-//var float3 input.normal : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float3 input.worldPosition : $vin.TEXCOORD1 : TEXCOORD1 : 0 : 1
-//var float2 input.texcoord : $vin.TEXCOORD2 : TEXCOORD2 : 0 : 1
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct VertexShaderInput {
- vec4 normal;
- vec2 texcoord;
-};
-
-struct PixelShaderInput {
- vec3 normal;
- vec3 worldPosition;
- vec2 texcoord;
-};
-
-vec4 _ZZ3Sret_0;
-vec3 _ZZ3SZDtemp7;
-vec3 _ZZ3SvZh0008;
-float _ZZ3SxZh0012;
-vec3 _ZZ3SZDtemp13;
-float _ZZ3SxZh0018;
-vec3 _ZZ3SZDtemp19;
-vec3 _ZZ3SvZh0020;
-float _ZZ3SxZh0024;
-vec3 _ZZ3SZDtemp25;
-vec3 _ZZ3SvZh0026;
-float _ZZ3SxZh0030;
-vec4 _ZZ3StmpZh0036;
-float _ZZ3SndotlZh0036;
-float _ZZ3SndothZh0036;
-float _ZZ3SspecularZh0038;
-float _ZZ3SxZh0042;
-sampler2D _ZZ3SsZh0046;
-vec2 _ZZ3ScZh0046;
-vec3 _ZZ3SZaTMP47;
-uniform mat4 viewInverse;
-uniform vec3 lightWorldPos;
-uniform float vOffset;
-uniform sampler diffuseSampler;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
- vec4 _ZZ4Sdiffuse;
-
- _ZZ3SvZh0008 = lightWorldPos - gl_TexCoord[1].xyz;
- _ZZ3SxZh0012 = dot(_ZZ3SvZh0008, _ZZ3SvZh0008);
- _ZZ3SZDtemp7 = inversesqrt(_ZZ3SxZh0012)*_ZZ3SvZh0008;
- _ZZ3SxZh0018 = dot(gl_TexCoord[0].xyz, gl_TexCoord[0].xyz);
- _ZZ3SZDtemp13 = inversesqrt(_ZZ3SxZh0018)*gl_TexCoord[0].xyz;
- _ZZ3SZaTMP47.x = viewInverse[3].x;
- _ZZ3SZaTMP47.y = viewInverse[3].y;
- _ZZ3SZaTMP47.z = viewInverse[3].z;
- _ZZ3SvZh0020 = _ZZ3SZaTMP47 - gl_TexCoord[1].xyz;
- _ZZ3SxZh0024 = dot(_ZZ3SvZh0020, _ZZ3SvZh0020);
- _ZZ3SZDtemp19 = inversesqrt(_ZZ3SxZh0024)*_ZZ3SvZh0020;
- _ZZ3SvZh0026 = _ZZ3SZDtemp7 + _ZZ3SZDtemp19;
- _ZZ3SxZh0030 = dot(_ZZ3SvZh0026, _ZZ3SvZh0026);
- _ZZ3SZDtemp25 = inversesqrt(_ZZ3SxZh0030)*_ZZ3SvZh0026;
- _ZZ3SndotlZh0036 = dot(_ZZ3SZDtemp13, _ZZ3SZDtemp7);
- _ZZ3SndothZh0036 = dot(_ZZ3SZDtemp13, _ZZ3SZDtemp25);
- _ZZ3StmpZh0036 = vec4(_ZZ3SndotlZh0036, _ZZ3SndothZh0036, 0.00000000E+00, 0.00000000E+00);
- _ZZ3SxZh0042 = max(0.00000000E+00, _ZZ3StmpZh0036.y);
- _ZZ3SspecularZh0038 = _ZZ3StmpZh0036.x > 0.00000000E+00 ? pow(_ZZ3SxZh0042, _ZZ3StmpZh0036.z) : 0.00000000E+00;
- vec4(1.00000000E+00, max(0.00000000E+00, _ZZ3StmpZh0036.x), _ZZ3SspecularZh0038, 1.00000000E+00);
- _ZZ3SsZh0046 = sampler2D(diffuseSampler);
- _ZZ3ScZh0046 = vec2(gl_TexCoord[2].x, gl_TexCoord[2].y + vOffset);
- _ZZ4Sdiffuse = texture2D(_ZZ3SsZh0046, _ZZ3ScZh0046);
- _ZZ3Sret_0 = _ZZ4Sdiffuse;
- gl_FragColor = _ZZ4Sdiffuse;
- return;
-} // main end
-
diff --git a/o3d/samples/beachdemo/shaders_glsl/watershader.glsl b/o3d/samples/beachdemo/shaders_glsl/watershader.glsl
deleted file mode 100644
index f8ecb99..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/watershader.glsl
+++ /dev/null
@@ -1,257 +0,0 @@
-// glslv profile log:
-// (104) : warning C7011: implicit cast from "float4" to "float3"
-// (107) : warning C7011: implicit cast from "float4" to "float3"
-// (110) : warning C7011: implicit cast from "float4" to "float3"
-// (126) : warning C7011: implicit cast from "float4" to "float3"
-// (137) : warning C7011: implicit cast from "float4" to "float3"
-// 157 lines, 5 warnings, 0 errors.
-
-// glslf profile log:
-// (104) : warning C7011: implicit cast from "float4" to "float3"
-// (107) : warning C7011: implicit cast from "float4" to "float3"
-// (110) : warning C7011: implicit cast from "float4" to "float3"
-// (126) : warning C7011: implicit cast from "float4" to "float3"
-// (137) : warning C7011: implicit cast from "float4" to "float3"
-// 157 lines, 5 warnings, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic world : WORLD
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic view : VIEW
-//semantic viewProjection : VIEWPROJECTION
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic viewPosition
-//semantic waterColor
-//semantic reflectionRefractionOffset
-//semantic clock
-//semantic environmentSampler
-//semantic fresnelSampler
-//semantic refractionSampler
-//semantic reflectionSampler
-//semantic noiseSampler
-//semantic noiseSampler2
-//semantic noiseSampler3
-//var float4x4 world : WORLD : _ZZ2Sworld[0], 4 : -1 : 1
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : , 4 : -1 : 0
-//var float4x4 view : VIEW : , 4 : -1 : 0
-//var float4x4 viewProjection : VIEWPROJECTION : _ZZ2SviewProjection[0], 4 : -1 : 1
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float3 viewPosition : : _ZZ2SviewPosition : -1 : 1
-//var float4 waterColor : : : -1 : 0
-//var float reflectionRefractionOffset : : _ZZ2SreflectionRefractionOffset : -1 : 1
-//var float clock : : : -1 : 0
-//var samplerCUBE environmentSampler : : : -1 : 0
-//var sampler2D fresnelSampler : : : -1 : 0
-//var sampler2D refractionSampler : : : -1 : 0
-//var sampler2D reflectionSampler : : : -1 : 0
-//var sampler2D noiseSampler : : : -1 : 0
-//var sampler2D noiseSampler2 : : : -1 : 0
-//var sampler2D noiseSampler3 : : : -1 : 0
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float2 input.texcoord : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-//var float2 vertexShaderFunction.texcoord : $vout.TEXCOORD0 : TEXCOORD0 : -1 : 1
-//var float3 vertexShaderFunction.viewVector : $vout.TEXCOORD1 : TEXCOORD1 : -1 : 1
-//var float3 vertexShaderFunction.screenPosition : $vout.TEXCOORD2 : TEXCOORD2 : -1 : 1
-
-attribute vec4 position;
-attribute vec4 texcoord0;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct VertexShaderInput {
- vec4 position;
- vec2 texcoord;
-};
-
-struct PixelShaderInput {
- vec4 position;
- vec2 texcoord;
- vec3 viewVector;
- vec3 screenPosition;
-};
-
-PixelShaderInput _ZZ3Sret_0;
-vec4 _ZZ3SrZh0017;
-vec4 _ZZ3SrZh0019;
-vec3 _ZZ3SZDtemp20;
-vec3 _ZZ3SvZh0021;
-float _ZZ3SxZh0025;
-vec4 _ZZ3SrZh0027;
-vec4 _ZZ3SvZh0027;
-uniform mat4 world;
-uniform mat4 viewprojection;
-uniform vec3 viewPosition;
-uniform float reflectionRefractionOffset;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
- PixelShaderInput _ZZ4Soutput;
-
- _ZZ3SrZh0017 = position.x*world[0];
- _ZZ3SrZh0017 = _ZZ3SrZh0017 + position.y*world[1];
- _ZZ3SrZh0017 = _ZZ3SrZh0017 + position.z*world[2];
- _ZZ3SrZh0017 = _ZZ3SrZh0017 + position.w*world[3];
- _ZZ3SrZh0019 = _ZZ3SrZh0017.x*viewprojection[0];
- _ZZ3SrZh0019 = _ZZ3SrZh0019 + _ZZ3SrZh0017.y*viewprojection[1];
- _ZZ3SrZh0019 = _ZZ3SrZh0019 + _ZZ3SrZh0017.z*viewprojection[2];
- _ZZ3SrZh0019 = _ZZ3SrZh0019 + _ZZ3SrZh0017.w*viewprojection[3];
- _ZZ3SvZh0021 = _ZZ3SrZh0017.xyz - viewPosition.xyz;
- _ZZ3SxZh0025 = dot(_ZZ3SvZh0021, _ZZ3SvZh0021);
- _ZZ3SZDtemp20 = inversesqrt(_ZZ3SxZh0025)*_ZZ3SvZh0021;
- _ZZ3SvZh0027 = vec4(_ZZ3SrZh0017.x, _ZZ3SrZh0017.y, 0.00000000E+00, 1.00000000E+00);
- _ZZ3SrZh0027 = _ZZ3SvZh0027.x*viewprojection[0];
- _ZZ3SrZh0027 = _ZZ3SrZh0027 + _ZZ3SvZh0027.y*viewprojection[1];
- _ZZ3SrZh0027 = _ZZ3SrZh0027 + _ZZ3SvZh0027.z*viewprojection[2];
- _ZZ3SrZh0027 = _ZZ3SrZh0027 + _ZZ3SvZh0027.w*viewprojection[3];
- _ZZ4Soutput.screenPosition = _ZZ3SrZh0027.xyz/_ZZ3SrZh0027.w;
- _ZZ4Soutput.screenPosition.xy = 5.00000000E-01 + (5.00000000E-01*_ZZ4Soutput.screenPosition.xy)*vec2( 1.00000000E+00, -1.00000000E+00);
- _ZZ4Soutput.screenPosition.z = reflectionRefractionOffset/_ZZ4Soutput.screenPosition.z;
- _ZZ3Sret_0.position = _ZZ3SrZh0019;
- _ZZ3Sret_0.texcoord = texcoord0.xy;
- _ZZ3Sret_0.viewVector = _ZZ3SZDtemp20;
- _ZZ3Sret_0.screenPosition = _ZZ4Soutput.screenPosition;
- gl_TexCoord[0].xy = texcoord0.xy;
- gl_TexCoord[2].xyz = _ZZ4Soutput.screenPosition;
- _glPositionTemp = _ZZ3SrZh0019; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- gl_TexCoord[1].xyz = _ZZ3SZDtemp20;
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic world : WORLD
-//semantic worldInverseTranspose : WORLDINVERSETRANSPOSE
-//semantic view : VIEW
-//semantic viewProjection : VIEWPROJECTION
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//semantic viewPosition
-//semantic waterColor
-//semantic reflectionRefractionOffset
-//semantic clock
-//semantic environmentSampler
-//semantic fresnelSampler
-//semantic refractionSampler
-//semantic reflectionSampler
-//semantic noiseSampler
-//semantic noiseSampler2
-//semantic noiseSampler3
-//var float4x4 world : WORLD : , 4 : -1 : 0
-//var float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE : , 4 : -1 : 0
-//var float4x4 view : VIEW : , 4 : -1 : 0
-//var float4x4 viewProjection : VIEWPROJECTION : , 4 : -1 : 0
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float3 viewPosition : : : -1 : 0
-//var float4 waterColor : : : -1 : 0
-//var float reflectionRefractionOffset : : : -1 : 0
-//var float clock : : _ZZ2Sclock : -1 : 1
-//var samplerCUBE environmentSampler : : _ZZ2SenvironmentSampler : -1 : 1
-//var sampler2D fresnelSampler : : _ZZ2SfresnelSampler : -1 : 1
-//var sampler2D refractionSampler : : _ZZ2SrefractionSampler : -1 : 1
-//var sampler2D reflectionSampler : : _ZZ2SreflectionSampler : -1 : 1
-//var sampler2D noiseSampler : : _ZZ2SnoiseSampler : -1 : 1
-//var sampler2D noiseSampler2 : : _ZZ2SnoiseSampler2 : -1 : 1
-//var sampler2D noiseSampler3 : : _ZZ2SnoiseSampler3 : -1 : 1
-//var float2 input.texcoord : $vin.TEXCOORD0 : TEXCOORD0 : 0 : 1
-//var float3 input.viewVector : $vin.TEXCOORD1 : TEXCOORD1 : 0 : 1
-//var float3 input.screenPosition : $vin.TEXCOORD2 : TEXCOORD2 : 0 : 1
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct VertexShaderInput {
- vec2 texcoord;
-};
-
-struct PixelShaderInput {
- vec2 texcoord;
- vec3 viewVector;
- vec3 screenPosition;
-};
-
-vec4 _ZZ3Sret_0;
-vec2 _ZZ3ScZh0019;
-vec2 _ZZ3ScZh0021;
-vec2 _ZZ3ScZh0023;
-vec3 _ZZ3SZDtemp24;
-vec3 _ZZ3SvZh0025;
-float _ZZ3SxZh0029;
-vec3 _ZZ3SZDtemp30;
-vec3 _ZZ3SZDtemp32;
-float _ZZ3SxZh0039;
-vec2 _ZZ3ScZh0043;
-vec2 _ZZ3ScZh0045;
-vec2 _ZZ3ScZh0051;
-uniform float clock;
-uniform samplerCube environmentSampler;
-uniform sampler2D fresnelSampler;
-uniform sampler2D refractionSampler;
-uniform sampler2D reflectionSampler;
-uniform sampler2D noiseSampler;
-uniform sampler2D noiseSampler2;
-uniform sampler2D noiseSampler3;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
- vec3 _ZZ4SviewVector;
- vec2 _ZZ4Stexcoord;
- vec3 _ZZ4Sn1;
- vec3 _ZZ4Sn2;
- vec3 _ZZ4Sn3;
- vec3 _ZZ4SR;
- float _ZZ4Sf;
- vec4 _ZZ4Sreflection;
- vec3 _ZZ4SskyReflection;
- vec3 _ZZ4Scolor;
- vec3 _ZZ4Srefraction;
- vec3 _ZZ4SfinalColor;
-
- _ZZ4SviewVector = vec3(gl_TexCoord[1].x, gl_TexCoord[1].z, -gl_TexCoord[1].y);
- _ZZ4Stexcoord = gl_TexCoord[0].xy*4.00000000E+00;
- _ZZ3ScZh0019 = _ZZ4Stexcoord + vec2(clock*9.99999978E-03, clock*1.99999996E-02);
- _ZZ4Sn1 = texture2D(noiseSampler, _ZZ3ScZh0019).xyz;
- _ZZ3ScZh0021 = _ZZ4Stexcoord + vec2(clock*2.99999993E-02, clock*9.99999978E-03);
- _ZZ4Sn2 = texture2D(noiseSampler2, _ZZ3ScZh0021).xyz;
- _ZZ3ScZh0023 = _ZZ4Stexcoord + vec2(clock*4.99999989E-03, clock*7.00000022E-03);
- _ZZ4Sn3 = texture2D(noiseSampler3, _ZZ3ScZh0023).xyz;
- _ZZ3SvZh0025 = _ZZ4Sn1 + _ZZ4Sn2*2.00000000E+00 + _ZZ4Sn3*4.00000000E+00 + vec3( -3.50000000E+00, 1.60000000E+01, -3.50000000E+00);
- _ZZ3SxZh0029 = dot(_ZZ3SvZh0025, _ZZ3SvZh0025);
- _ZZ3SZDtemp24 = inversesqrt(_ZZ3SxZh0029)*_ZZ3SvZh0025;
- _ZZ3SZDtemp30 = _ZZ4SviewVector - (2.00000000E+00*_ZZ3SZDtemp24)*dot(_ZZ3SZDtemp24, _ZZ4SviewVector);
- _ZZ3SxZh0039 = dot(_ZZ3SZDtemp30, _ZZ3SZDtemp30);
- _ZZ3SZDtemp32 = inversesqrt(_ZZ3SxZh0039)*_ZZ3SZDtemp30;
- _ZZ4SR = _ZZ3SZDtemp32;
- _ZZ4SR.y = _ZZ3SZDtemp32.y < 9.99999978E-03 ? 9.99999978E-03 : _ZZ3SZDtemp32.y;
- _ZZ3ScZh0043 = vec2(dot(_ZZ4SR, _ZZ3SZDtemp24), 5.00000000E-01);
- _ZZ4Sf = texture2D(fresnelSampler, _ZZ3ScZh0043).x;
- _ZZ3ScZh0045 = (gl_TexCoord[2].xy - gl_TexCoord[2].z*_ZZ3SZDtemp24.xy) + vec2( 0.00000000E+00, 1.00000001E-01);
- _ZZ4Sreflection = texture2D(reflectionSampler, _ZZ3ScZh0045);
- _ZZ4SskyReflection = textureCube(environmentSampler, _ZZ4SR).xyz;
- _ZZ4Scolor = _ZZ4SskyReflection + _ZZ4Sreflection.w*(_ZZ4Sreflection.xyz - _ZZ4SskyReflection);
- _ZZ3ScZh0051 = ((gl_TexCoord[2].xy - gl_TexCoord[2].z*_ZZ3SZDtemp24.xz) + vec2( 0.00000000E+00, 5.00000007E-02))*vec2( 1.00000000E+00, 9.49999988E-01);
- _ZZ4Srefraction = texture2D(refractionSampler, _ZZ3ScZh0051).xyz;
- _ZZ4SfinalColor = _ZZ4Srefraction + _ZZ4Sf*(_ZZ4Scolor - _ZZ4Srefraction);
- _ZZ3Sret_0 = vec4(_ZZ4SfinalColor.x, _ZZ4SfinalColor.y, _ZZ4SfinalColor.z, 1.00000000E+00);
- gl_FragColor = _ZZ3Sret_0;
- return;
-} // main end
-
diff --git a/o3d/samples/beachdemo/shaders_glsl/waterstyle2.glsl b/o3d/samples/beachdemo/shaders_glsl/waterstyle2.glsl
deleted file mode 100644
index 98218a4..0000000
--- a/o3d/samples/beachdemo/shaders_glsl/waterstyle2.glsl
+++ /dev/null
@@ -1,85 +0,0 @@
-// glslv profile log:
-// 73 lines, 0 errors.
-
-// glslf profile log:
-// 73 lines, 0 errors.
-
-// glslv output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslv
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslv
-//program vertexShaderFunction
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : _ZZ2SworldViewProjection[0], 4 : -1 : 1
-//var float4 input.position : $vin.POSITION : POSITION : 0 : 1
-//var float4 vertexShaderFunction.position : $vout.POSITION : POSITION : -1 : 1
-
-attribute vec4 position;
-vec4 _glPositionTemp;
-uniform vec4 dx_clipping;
-
-struct VertexShaderInput {
- vec4 position;
-};
-
-struct PixelShaderInput {
- vec4 position;
-};
-
-PixelShaderInput _ZZ3Sret_0;
-vec4 _ZZ3SrZh0002;
-uniform mat4 worldViewProjection;
-
- // main procedure, the original name was vertexShaderFunction
-void main()
-{
-
-
- _ZZ3SrZh0002 = position.x*worldViewProjection[0];
- _ZZ3SrZh0002 = _ZZ3SrZh0002 + position.y*worldViewProjection[1];
- _ZZ3SrZh0002 = _ZZ3SrZh0002 + position.z*worldViewProjection[2];
- _ZZ3SrZh0002 = _ZZ3SrZh0002 + position.w*worldViewProjection[3];
- _ZZ3Sret_0.position = _ZZ3SrZh0002;
- _glPositionTemp = _ZZ3SrZh0002; gl_Position = vec4(_glPositionTemp.x + _glPositionTemp.w * dx_clipping.x, dx_clipping.w * (_glPositionTemp.y + _glPositionTemp.w * dx_clipping.y), _glPositionTemp.z * 2.0 - _glPositionTemp.w, _glPositionTemp.w);
- return;
-} // main end
-
-
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
-// glslf output by Cg compiler
-// cgc version 2.0.0010, build date Dec 12 2007
-// command line args: -profile glslf
-//vendor NVIDIA Corporation
-//version 2.0.0.10
-//profile glslf
-//program pixelShaderFunction
-//semantic worldViewProjection : WORLDVIEWPROJECTION
-//var float4x4 worldViewProjection : WORLDVIEWPROJECTION : , 4 : -1 : 0
-//var float4 pixelShaderFunction : $vout.COLOR : COLOR : -1 : 1
-
-
-
-struct VertexShaderInput {
- int dummy;
-};
-
-struct PixelShaderInput {
- int dummy;
-};
-
-vec4 _ZZ3Sret_0;
-
- // main procedure, the original name was pixelShaderFunction
-void main()
-{
-
-
- _ZZ3Sret_0 = vec4( 0.00000000E+00, 0.00000000E+00, 5.00000000E-01, 1.00000000E+00);
- gl_FragColor = vec4( 0.00000000E+00, 0.00000000E+00, 5.00000000E-01, 1.00000000E+00);
- return;
-} // main end
-
diff --git a/o3d/samples/billboards.html b/o3d/samples/billboards.html
deleted file mode 100644
index 981ef3c..0000000
--- a/o3d/samples/billboards.html
+++ /dev/null
@@ -1,254 +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.
--->
-
-<!--
-Billboard example.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Billboard Example
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.io');
-o3djs.require('o3djs.loader');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_globalParams;
-var g_o3dElement;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-var g_cameraRadius = 35;
-var g_cameraSpeed = 0.3;
-var g_randSeed = 0;
-var g_textures = [];
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_client.width / g_client.height, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-
- var loader = o3djs.loader.createLoader(initStep3);
- loadTexture(loader, 'purple-flower.png');
- loadTexture(loader, 'pillar.png');
- loader.finish();
-}
-
-function loadTexture(loader, filename) {
- loader.loadTexture(g_pack,
- o3djs.util.getAbsoluteURI('assets/' + filename),
- rememberTexture);
-
- function rememberTexture(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- g_textures[filename] = texture;
- }
- }
-}
-
-function initStep3() {
- var redMaterial = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [0.2, 1, 0.2, 1]); // green
-
- var checkerMaterial = o3djs.material.createCheckerMaterial(g_pack,
- g_viewInfo);
-
- var billboardMaterial = o3djs.material.createMaterialFromFile(
- g_pack, 'shaders/billboard.shader', g_viewInfo.zOrderedDrawList);
-
- var imposterMaterial = o3djs.material.createMaterialFromFile(
- g_pack, 'shaders/imposter.shader', g_viewInfo.zOrderedDrawList);
-
- // Set the textures.
- // We don't need to create the params or the samplers because
- // createMaterialFromFile has already handled that for us.
- var sampler = billboardMaterial.getParam('texSampler0').value;
- sampler.texture = g_textures['purple-flower.png'];
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
-
- sampler = imposterMaterial.getParam('texSampler0').value;
- sampler.texture = g_textures['pillar.png'];
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
-
- // Create and bind standard params so we can see the light parameters
- // for the standard shaders globably.
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
-
- // Put on a transform.
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Create a cylinder.
- var cylinderShape = o3djs.primitives.createCylinder(
- g_pack, redMaterial, 0.5, 5, 20, 1,
- g_math.matrix4.translation([0, 2.5, 0]));
-
- // Create an XY plane for the billboard.
- var purpleFlowerPlane = o3djs.primitives.createPlane(
- g_pack, billboardMaterial, 5, 5, 1, 1,
- g_math.matrix4.rotationX(g_math.degToRad(90)));
-
- // Create an XY plane for the imposter.
- var pillarPlane = o3djs.primitives.createPlane(
- g_pack, imposterMaterial, 5, 5, 1, 1,
- g_math.matrix4.rotationX(g_math.degToRad(90)));
-
- // Create 30 cylinders and put a billboard or imposter on top of each one.
- for (var ii = 0; ii < 30; ++ii) {
- transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.translate((g_math.pseudoRandom() - 0.5) * 90,
- 0,
- (g_math.pseudoRandom() - 0.5) * 90);
- transform.addShape(cylinderShape);
-
- var topTransform = g_pack.createObject('Transform');
- topTransform.parent = transform;
- topTransform.translate(0, 7, 0);
- if (ii % 4 > 1) {
- topTransform.addShape(purpleFlowerPlane);
- } else {
- topTransform.addShape(pillarPlane);
- }
- }
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- var eye = [
- Math.sin(g_clock * g_cameraSpeed) * g_cameraRadius,
- 20 + 10 * Math.sin(g_clock * g_cameraSpeed * 4),
- Math.cos(g_clock * g_cameraSpeed) * g_cameraRadius];
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- eye,
- [0, 0, 0], // target
- [0, 1, 0]); // up
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Billboards</h1>
-<div>
-Flowers always face the camera.<br/>
-Pillars rotate around Y toward the camera.
-</div>
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-</body>
-</html>
diff --git a/o3d/samples/bitmap-draw-image.html b/o3d/samples/bitmap-draw-image.html
deleted file mode 100644
index e4daea6..0000000
--- a/o3d/samples/bitmap-draw-image.html
+++ /dev/null
@@ -1,247 +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.
--->
-
-<!--
-In this tutorial, we show how to create bitmaps and how to draw
-images on both bitmaps and textures.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Bitmap Draw Image Demo
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.loader');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Events
-// Run the init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_finished = false; // for selenium testing
-var g_eye;
-var g_target;
-var g_up;
-var g_bitmaps = []; // bitmaps by URL.
-
-function makeShape(texture) {
- // Create a material.
- var myMaterial = o3djs.material.createMaterialFromFile(
- g_pack,
- 'shaders/texture-only.shader',
- g_viewInfo.performanceDrawList);
-
- // Creates a quad.
- var myShape = o3djs.primitives.createPlane(g_pack,
- myMaterial,
- 3, // width
- 3, // height
- 1, // quads across
- 1); // quads down
-
- // Get the material's sampler parameter, get the sampler on it and set its
- // texture.
- var sampler_param = myMaterial.getParam('texSampler0');
- var sampler = sampler_param.value;
-
- // Set the texture to use.
- sampler.texture = texture;
-
- // adjust the scale of our transform to match the aspect ratio of
- // the texture. Of course we could also have waited until now to build
- // our plane and set its width and height to match instead of scaling
- // here.
- var textureWidth = texture.width;
- var textureHeight = texture.height;
- var hScale = 1;
- var vScale = 1;
- if (textureWidth > textureHeight) {
- vScale = textureHeight / textureWidth;
- } else if (textureHeight > textureWidth) {
- hScale = textureWidth / textureHeight;
- }
- // We now attach our quad to the root of the transform graph.
- // We do this after the texture has loaded, otherwise we'd be attempting
- // to display something invalid.
-
- // Make a transform for each quad.
- var transform = g_pack.createObject('Transform');
- transform.scale(hScale, 1, vScale);
- transform.addShape(myShape);
- transform.parent = g_client.root;
- g_finished = true;
- return myShape;
-}
-
-function loadBitmap(loader, url) {
- loader.loadBitmaps(g_pack, o3djs.util.getAbsoluteURI('assets/' + url),
- function(bitmaps, exception) {
- if (!exception) {
- // We know we are only loading 2D images so there will only be 1 bitmap.
- g_bitmaps[url] = bitmaps[0];
- } else {
- alert(exception);
- }
- });
-
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2, 'NotAntiAliased');
-}
-
-/**
- * Initializes O3D, loads the effect, and loads a tar.gz archive containing
- * a bunch of image files. We'll create bitmaps from them.
- * And use drawImage function to create texture as well as mipmaps.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set up an perspective projection.
- var proj_matrix = g_math.matrix4.perspective(
- g_math.degToRad(90),
- g_client.width / g_client.height,
- 0.1,
- 100);
-
- // Create the view matrix which tells the camera which way to point to.
- g_eye = [0, 1.5, 0];
- g_target = [0, 0, 0];
- g_up = [0, 0, -1];
- var view_matrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
-
- g_viewInfo.drawContext.view = view_matrix;
- g_viewInfo.drawContext.projection = proj_matrix;
-
- var loader = o3djs.loader.createLoader(callback);
- loadBitmap(loader, 'shaving_cream_300x300.jpg');
- loadBitmap(loader, 'four_pixel.png');
- loadBitmap(loader, 'hi.jpg');
- loader.finish();
-
- // Callback that happens when loader.finish() is called and all of
- // our textures have finished loading.
- function callback() {
- // Because bitmaps have their origin at the upper left, and in
- // this sample our plane is oriented with the texture coordinate
- // origin on the lower left, we need to flip all the bitmaps
- // vertically to match coordinate systems.
- var kids = g_bitmaps['shaving_cream_300x300.jpg'];
- kids.flipVertically();
- var four_square = g_bitmaps['four_pixel.png'];
- four_square.flipVertically();
- var label = g_bitmaps['hi.jpg'];
- label.flipVertically();
-
- var texture = g_pack.createTexture2D(300, 300, g_o3d.Texture.XRGB8, 0,
- false);
- // Draw bitmaps on the texture.
- // Scale down entire image into on lower left corner.
- texture.drawImage(kids, 0, 0, 0, 300, 300, 0, 0, 0, 150, 150);
-
- // Crop and scale up into the lower right corner.
- texture.drawImage(kids, 0, 0, 156, 100, 100, 0, 150, 0, 150, 150);
-
- // Flip and draw part of the image in the top left corner (and
- // texture coords are not inclusive -- they go from 0-299 for a
- // 300 pixel texture).
- texture.drawImage(kids, 0, 150, 150, 150, 150, 0, 149, 299, -150, -150);
-
- // Crop and draw cropped area in upper right corner, but we're
- // using a width and height that go beyond the edges of the image.
- texture.drawImage(kids, 0, 150, 150, 400, 400, 0, 150, 150, 400, 400);
-
- // Draw "O3D" label.
- texture.drawImage(label, 0, 0, 0, 100, 50, 0, 100, 125, 100, 50);
-
- // Fill in different mip-map levels with images that show at
- // different distances. (Scroll the mouse wheel to see).
-
- // Fill in medium level with whole image.
- texture.drawImage(kids, 0, 0, 0, 300, 300, 1, 0, 0, 150, 150);
-
- // Fill in smaller level with four pixel image.
- texture.drawImage(four_square, 0, 0, 0, 2, 2, 2, 0, 0, 75, 75);
-
- makeShape(texture);
- }
- o3djs.event.addEventListener(o3dElement, 'wheel', scrollMe);
-}
-
-function scrollMe(e) {
- g_eye = g_math.mulScalarVector((e.deltaY < 0 ? 11 : 13) / 12, g_eye);
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(g_eye, g_target, g_up);
-}
-</script>
-</head>
-<body>
-<h1>Bitmap Draw Image Demo</h1>
-This tutorial shows how to create bitmaps and how to draw images
-on both bitmaps and texture mipmaps.
-<br/>
-Scroll wheel to see different mipmaps.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px"></div>
-<!-- End of O3D plugin -->
-</body>
-</html> \ No newline at end of file
diff --git a/o3d/samples/box2d-3d/box2d-3d.html b/o3d/samples/box2d-3d/box2d-3d.html
deleted file mode 100644
index 7b32b24..0000000
--- a/o3d/samples/box2d-3d/box2d-3d.html
+++ /dev/null
@@ -1,138 +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.
--->
-
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>Box2DJS in 3D</title>
-
- <!--=============================-->
- <!-- Copy this part to your app. -->
- <!-- START -->
- <!--=============================-->
- <!-- libs -->
- <script type="text/javascript" src="third_party/prototype-1.6.0.2.js"></script>
-
- <!-- box2djs -->
- <script type="text/javascript" src='third_party/box2d/box2d.js'></script>
- <!--=============================-->
- <!-- Copy this part to your app. -->
- <!-- END -->
- <!--=============================-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
- <!-- demos -->
- <script src='demos/manager.js'></script>
- <script src='demos/draw_world.js'></script>
- <script src='demos/demo_base.js'></script>
- <script src='demos/top.js'></script>
- <script src='demos/stack.js'></script>
- <script src='demos/compound.js'></script>
- <script src='demos/pendulum.js'></script>
- <script src='demos/crank.js'></script>
- <script src='demos/demos.js'></script>
- <style type="text/css">
- html, body {
- border: 0;
- margin: 0;
- height: 100%;
- }
- </style>
- </head>
-<body onload="init()" onunload="uninit()">
-<table style="width: 100%; height: 100%;"><tr valign="top" style="height: 50px;"><td>
-<h1>Box2DJS in 3D</h1>
-<p>Based on <a href="http://box2d-js.sourceforge.net/">box2d-js</a>.<br/>
-Left Click to create a new object.<br/>
-Right Click (shift-click on OSX) to switch to the next demo.
-</p>
-</td></tr>
-<tr style="height: 100%;"><td>
-<div id="o3d" style="width: 100%; height: 100%;"></div>
-</td></tr></table>
-<div style="display:none;">
-<textarea id="shader">
-uniform float4x4 worldViewProj : WorldViewProjection;
-uniform float3 lightWorldPos;
-uniform float4 lightColor;
-uniform float4x4 world : World;
-uniform float4x4 view : View;
-uniform float4x4 worldIT : WorldInverseTranspose;
-uniform float4 emissive;
-uniform float4 ambient;
-uniform float4 colorMult;
-sampler2D diffuseSampler;
-uniform float4 specular;
-uniform float shininess;
-
-struct InVertex {
- float4 position : POSITION;
- float4 normal : NORMAL;
- float2 diffuseUV : TEXCOORD0;
-};
-
-struct OutVertex {
- float4 position : POSITION;
- float2 diffuseUV : TEXCOORD0;
- float3 n : TEXCOORD1;
- float3 l : TEXCOORD2;
- float3 v : TEXCOORD3;
-};
-
-OutVertex vs(InVertex IN) {
- OutVertex OUT;
- OUT.position = mul(IN.position, worldViewProj);
- OUT.diffuseUV = IN.diffuseUV;
- OUT.n = mul(IN.normal, worldIT).xyz;
- OUT.l = lightWorldPos - mul(IN.position, world).xyz;
- OUT.v = (view[3] - mul(IN.position, world)).xyz;
- return OUT;
-}
-
-float4 ps(OutVertex IN) : COLOR {
- float4 diffuse = tex2D(diffuseSampler, IN.diffuseUV) * colorMult;
- float3 l = normalize(IN.l); float3 n = normalize(IN.n);
- float3 r = normalize(reflect(n, l));
- float3 v = normalize(IN.v);
- float4 litR = lit(dot(n, l), dot(r, v), shininess);
- return float4((emissive + lightColor *
- (ambient + diffuse * litR.y + specular * litR.z)).rgb,
- diffuse.a);
-}
-
-// #o3d VertexShaderEntryPoint vs
-// #o3d PixelShaderEntryPoint ps
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
-</html>
diff --git a/o3d/samples/box2d-3d/demos/LICENSE.txt b/o3d/samples/box2d-3d/demos/LICENSE.txt
deleted file mode 100644
index c224b40..0000000
--- a/o3d/samples/box2d-3d/demos/LICENSE.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-The zlib/libpng License
-
-Copyright (c) 2008 ANDO Yasushi
-
-This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
-
-Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
-
- 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
-
- 3. This notice may not be removed or altered from any source distribution.
-
diff --git a/o3d/samples/box2d-3d/demos/README.o3d b/o3d/samples/box2d-3d/demos/README.o3d
deleted file mode 100644
index 2d3f954..0000000
--- a/o3d/samples/box2d-3d/demos/README.o3d
+++ /dev/null
@@ -1,5 +0,0 @@
-This directory contains a subset of Box2D-JS, available at
-http://box2d-js.sourceforge.net/ under the zlib/libpng license (see
-License.txt).
-The software was modified in certain places to make it work with O3D.
-Individual files are marked to indicate modifications occured.
diff --git a/o3d/samples/box2d-3d/demos/compound.js b/o3d/samples/box2d-3d/demos/compound.js
deleted file mode 100644
index e63b983..0000000
--- a/o3d/samples/box2d-3d/demos/compound.js
+++ /dev/null
@@ -1,71 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-demos.compound = {};
-demos.compound.createCompoundBall = function(world, x, y) {
- var ballSd1 = new b2CircleDef();
- ballSd1.density = 1.0;
- ballSd1.radius = 20;
- ballSd1.restitution = 0.2;
- ballSd1.localPosition.Set(-20, 0);
- var ballSd2 = new b2CircleDef();
- ballSd2.density = 1.0;
- ballSd2.radius = 20;
- ballSd2.restitution = 0.2;
- ballSd2.localPosition.Set(20, 0);
- var ballBd = new b2BodyDef();
- ballBd.AddShape(ballSd1);
- ballBd.AddShape(ballSd2);
- ballBd.position.Set(x, y);
- // NOTE: Added the following line to create a 3d object to display.
- ballBd.userData = g.mgr.createCompoundCylinder(20, -20, 20, 20);
- return world.CreateBody(ballBd);
-}
-
-demos.compound.createCompoundPoly = function(world, x, y) {
- var points = [[-30, 0], [30, 0], [0, 15]];
- var polySd1 = new b2PolyDef();
- polySd1.vertexCount = points.length;
- for (var i = 0; i < points.length; i++) {
- polySd1.vertices[i].Set(points[i][0], points[i][1]);
- }
- polySd1.localRotation = 0.3524 * Math.PI;
- var R1 = new b2Mat22(polySd1.localRotation);
- polySd1.localPosition = b2Math.b2MulMV(R1, new b2Vec2(30, 0));
- polySd1.density = 1.0;
- var polySd2 = new b2PolyDef();
- polySd2.vertexCount = points.length;
- for (var i = 0; i < points.length; i++) {
- polySd2.vertices[i].Set(points[i][0], points[i][1]);
- }
- polySd2.localRotation = -0.3524 * Math.PI;
- var R2 = new b2Mat22(polySd2.localRotation);
- polySd2.localPosition = b2Math.b2MulMV(R2, new b2Vec2(-30, 0));
- var polyBd = new b2BodyDef();
- polyBd.AddShape(polySd1);
- polyBd.AddShape(polySd2);
- polyBd.position.Set(x,y);
- // NOTE: Added the following line to create a 3d object to display.
- polyBd.userData = g.mgr.createCompoundWedge(points,
- polySd1.localPosition,
- polySd1.localRotation,
- points,
- polySd2.localPosition,
- polySd2.localRotation);
- return world.CreateBody(polyBd)
-}
-
-demos.compound.initWorld = function(world) {
- var i;
- for (i = 1; i <= 4; i++) {
- demos.compound.createCompoundPoly(world, 150 + 3 * Math.random(), 40 * i);
- }
- for (i = 1; i <= 4; i++) {
- demos.compound.createCompoundBall(world, 350 + 3 * Math.random(), 45 * i);
- }
-}
-demos.InitWorlds.push(demos.compound.initWorld);
-
-
diff --git a/o3d/samples/box2d-3d/demos/crank.js b/o3d/samples/box2d-3d/demos/crank.js
deleted file mode 100644
index 007c1dc..0000000
--- a/o3d/samples/box2d-3d/demos/crank.js
+++ /dev/null
@@ -1,79 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-demos.crank = {};
-demos.crank.initWorld = function(world) {
- var ground = world.m_groundBody;
-
- // Define crank.
- var sd = new b2BoxDef();
- sd.extents.Set(5, 25);
- sd.density = 1.0;
-
- var bd = new b2BodyDef();
- bd.userData = g.mgr.createBox(5, 25);
- bd.AddShape(sd);
-
- var rjd = new b2RevoluteJointDef();
-
- var prevBody = ground;
-
- bd.position.Set(500/2, 210);
- bd.userData = g.mgr.createBox(5, 25);
- var body = world.CreateBody(bd);
-
- rjd.anchorPoint.Set(500/2, 235);
- rjd.body1 = prevBody;
- rjd.body2 = body;
- rjd.motorSpeed = -1.0 * Math.PI;
- rjd.motorTorque = 500000000.0;
- rjd.enableMotor = true;
- world.CreateJoint(rjd);
-
- prevBody = body;
-
- // Define follower.
- sd.extents.Set(5, 45);
- bd.position.Set(500/2, 140);
- bd.userData = g.mgr.createBox(5, 45);
- body = world.CreateBody(bd);
-
- rjd.anchorPoint.Set(500/2, 185);
- rjd.body1 = prevBody;
- rjd.body2 = body;
- rjd.enableMotor = false;
- world.CreateJoint(rjd);
-
- prevBody = body;
-
- // Define piston
- sd.extents.Set(20, 20);
- bd.position.Set(500/2, 95);
- bd.userData = g.mgr.createBox(20, 20);
- body = world.CreateBody(bd);
-
- rjd.anchorPoint.Set(500/2, 95);
- rjd.body1 = prevBody;
- rjd.body2 = body;
- world.CreateJoint(rjd);
-
- var pjd = new b2PrismaticJointDef();
- pjd.anchorPoint.Set(500/2, 95);
- pjd.body1 = ground;
- pjd.body2 = body;
- pjd.axis.Set(0.0, 1.0);
- pjd.motorSpeed = 0.0; // joint friction
- pjd.motorForce = 100000.0;
- pjd.enableMotor = true;
-
- world.CreateJoint(pjd);
-
- // Create a payload
- sd.density = 2.0;
- bd.position.Set(500/2, 10);
- bd.userData = g.mgr.createBox(20, 20);
- world.CreateBody(bd);
-}
-demos.InitWorlds.push(demos.crank.initWorld);
diff --git a/o3d/samples/box2d-3d/demos/demo_base.js b/o3d/samples/box2d-3d/demos/demo_base.js
deleted file mode 100644
index 3379691..0000000
--- a/o3d/samples/box2d-3d/demos/demo_base.js
+++ /dev/null
@@ -1,59 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-function createWorld() {
- var worldAABB = new b2AABB();
- worldAABB.minVertex.Set(-1000, -1000);
- worldAABB.maxVertex.Set(1000, 1000);
- var gravity = new b2Vec2(0, 300);
- var doSleep = true;
- var world = new b2World(worldAABB, gravity, doSleep);
- createGround(world);
- createBox(world, 0, 125, 10, 250);
- createBox(world, 500, 125, 10, 250);
- return world;
-}
-
-function createGround(world) {
- var groundSd = new b2BoxDef();
- groundSd.extents.Set(250, 50);
- groundSd.restitution = 0.2;
- var groundBd = new b2BodyDef();
- groundBd.AddShape(groundSd);
- groundBd.position.Set(250, 340);
- // NOTE: Added the following line to create a 3d object to display.
- groundBd.userData = g.mgr.createBox(250, 50);
- return world.CreateBody(groundBd)
-}
-
-function createBall(world, x, y) {
- var ballSd = new b2CircleDef();
- ballSd.density = 1.0;
- ballSd.radius = 20;
- ballSd.restitution = 1.0;
- ballSd.friction = 0;
- var ballBd = new b2BodyDef();
- ballBd.AddShape(ballSd);
- ballBd.position.Set(x,y);
- // NOTE: Added the following line to create a 3d object to display.
- ballBd.userData = g.mgr.createCylinder(ballSd.radius);
- return world.CreateBody(ballBd);
-}
-
-function createBox(world, x, y, width, height, fixed) {
- if (typeof(fixed) == 'undefined') fixed = true;
- var boxSd = new b2BoxDef();
- if (!fixed) boxSd.density = 1.0;
- boxSd.extents.Set(width, height);
- var boxBd = new b2BodyDef();
- // NOTE: Added the following line to create a 3d object to display.
- boxBd.userData = g.mgr.createBox(width, height);
- boxBd.AddShape(boxSd);
- boxBd.position.Set(x,y);
- return world.CreateBody(boxBd)
-}
-
-var demos = {};
-demos.InitWorlds = [];
diff --git a/o3d/samples/box2d-3d/demos/demos.js b/o3d/samples/box2d-3d/demos/demos.js
deleted file mode 100644
index 8834790..0000000
--- a/o3d/samples/box2d-3d/demos/demos.js
+++ /dev/null
@@ -1,271 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.picking');
-
-var initId = 0;
-var world;
-var canvasWidth;
-var canvasHeight;
-var canvasTop;
-var canvasLeft;
-
-function setupWorld(did) {
- var transforms = g.client.getObjectsByClassName('o3d.Transform');
- for (var tt = 0; tt < transforms.length; ++tt) {
- var transform = transforms[tt];
- if (transform.clientId != g.root.clientId &&
- transform.clientId != g.client.root.clientId) {
- transform.parent = null;
- g.pack.removeObject(transform);
- }
- }
- if (!did) did = 0;
- world = createWorld();
- initId += did;
- initId %= demos.InitWorlds.length;
- if (initId < 0) initId = demos.InitWorlds.length + initId;
- demos.InitWorlds[initId](world);
-}
-function setupNextWorld() { setupWorld(1); }
-function setupPrevWorld() { setupWorld(-1); }
-function step(elapsedTime) {
- // NOTE: changed to use the renderEvent's elapsed time instead of
- // javascript timers. The check below makes the physics never do a time step
- // slower that 1/30th of a second because collision bugs will happen.
- if (elapsedTime > 1 / 30) {
- elapsedTime = 1 / 30;
- }
- var stepping = false;
- var timeStep = elapsedTime;
- var iteration = 1;
- if (world) {
- world.Step(timeStep, iteration);
- drawWorld(world);
- }
-}
-
-// When the sample is running in V8, window.g is the browser's global object and
-// g is v8's. When the sample is running only in the browser, they are the same
-// object.
-window.g = {};
-
-// A global object to track stuff with.
-var g = {
- o3dWidth: -1, // width of our client area
- o3dHeight: -1, // height of our client area
- materials: [], // all our materials
- shapes: [] // all our shapes
-};
-
-/**
- * Sets up the o3d stuff.
- * @param {HTML element} o3dElement The o3d object element.
- */
-function setupO3D(o3dElement) {
- // Initializes global variables and libraries.
- g.o3dElement = o3dElement;
- g.o3d = o3dElement.o3d;
- g.math = o3djs.math;
- g.client = o3dElement.client;
- g.mgr = new O3DManager();
-
- // The browser needs to be able to see these globals so that it can
- // call unload later.
- window.g.client = g.client;
-
- // Get the width and height of our client area.
- g.o3dWidth = g.client.width;
- g.o3dHeight = g.client.height;
-
- // Creates a pack to manage our resources/assets
- g.pack = g.client.createPack();
-
- // Create the render graph for a view.
- g.viewInfo = o3djs.rendergraph.createBasicView(
- g.pack,
- g.client.root,
- g.client.renderGraphRoot);
-
- // Create an object to hold global params.
- g.globalParamObject = g.pack.createObject('ParamObject');
- g.lightWorldPosParam = g.globalParamObject.createParam('lightWorldPos',
- 'ParamFloat3');
- g.lightColorParam = g.globalParamObject.createParam('lightColor',
- 'ParamFloat4');
- g.lightWorldPosParam.value = [200, -1500, -1000];
- g.lightColorParam.value = [1, 1, 1.0, 1.0];
-
- // Create Materials.
- g.materials = [];
- var material = g.pack.createObject('Material');
- var effect = g.pack.createObject('Effect');
- effect.loadFromFXString(document.getElementById('shader').value);
- material.effect = effect;
- effect.createUniformParameters(material);
- material.getParam('lightWorldPos').bind(g.lightWorldPosParam);
- material.getParam('lightColor').bind(g.lightColorParam);
- material.getParam('emissive').set(0, 0, 0, 1);
- material.getParam('ambient').set(0, 0, 0, 1);
- material.getParam('specular').set(1, 1, 1, 1);
- material.getParam('shininess').value = 20;
- material.drawList = g.viewInfo.performanceDrawList;
- g.materials[0] = material;
-
- // Create a kind of checkboardish texture.
- var pixels = [];
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 3; // rgb
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = 1;//Math.sin(Math.PI * 32 / x) * 0.2 + 0.8; // red
- pixels[offset + 1] = Math.floor(x / 8) % 2 * 0.2 + 0.8; // green
- pixels[offset + 2] = Math.floor(y / 8) % 2 * 0.5 + 0.5; // blue
- }
- }
- var texture = g.pack.createTexture2D(32, 32, g.o3d.Texture.XRGB8, 1, false);
- texture.set(0, pixels);
- var samplerParam = material.getParam('diffuseSampler');
- var sampler = g.pack.createObject('Sampler');
- samplerParam.value = sampler;
- sampler.texture = texture;
-
- // Creates a transform to put our data on.
- g.root = g.pack.createObject('Transform');
- g.root.parent = g.client.root;
-
- // make a cube for drawing lines
- g.lineShape = o3djs.primitives.createRainbowCube(
- g.pack,
- g.materials[0],
- 1,
- g.math.matrix4.translation([0, 0.5, 0]));
-
- // Set the projection matrix
- g.viewInfo.drawContext.projection = g.math.matrix4.perspective(
- g.math.degToRad(45),
- g.o3dWidth / g.o3dHeight,
- 0.1,
- 10000);
-
- // Set the view matrix.
- g.viewInfo.drawContext.view = g.math.matrix4.lookAt(
- [100, -50, -600],
- [250, 80, 0],
- [0, -1, 0]);
-
- // Make copies of the view and projection matrix to get fast access to them.
- g.projectionMatrix = g.math.matrix4.copy(g.viewInfo.drawContext.projection);
- g.viewMatrix = g.math.matrix4.copy(g.viewInfo.drawContext.view);
-
- // Make a bounding box to use for picking.
- g.worldBox = g.o3d.BoundingBox([0, -100, 0],
- [500, 250, 5]);
-
- // Steps the physics with a time of zero. This is left over from the orignial
- // code.
- step(0);
-
- g.client.setRenderCallback(o3dOnRender);
-}
-
-/**
- * Called just before rendering each frame.
- * @param {o3d.RenderEvent} renderEvent The render event passed by
- * o3d.
- */
-function o3dOnRender(renderEvent) {
- var newWidth = g.client.width;
- var newHeight = g.client.height;
- if (newWidth != g.o3dWidth || newHeight != g.o3dHeight) {
- g.o3dWidth = newWidth;
- g.o3dHeight = newHeight;
-
- // Adjust the projection matrix.
- var projectionMatrix = g.math.matrix4.perspective(g.math.degToRad(45),
- g.o3dWidth / g.o3dHeight,
- 0.1,
- 10000);
- g.viewInfo.drawContext.projection = projectionMatrix;
- g.projectionMatrix = projectionMatrix;
- }
- step(renderEvent.elapsedTime);
-}
-
-/**
- * This is the original setup code modified to work with o3d.
- * @param {Array} clientElements Array of o3d objects.
- */
-function setupStep2(clientElements) {
- var canvasElm = clientElements[0];
- canvasElm.id = 'canvas';
- setupO3D(canvasElm);
- setupWorld();
- canvasWidth = g.client.width;
- canvasHeight = g.client.height;
- canvasTop = parseInt(canvasElm.style.top);
- canvasLeft = parseInt(canvasElm.style.left);
- o3djs.event.addEventListener(canvasElm, 'mousedown', function(e) {
- if (e.shiftKey || e.button == g.o3d.Event.BUTTON_RIGHT) {
- setupPrevWorld();
- } else {
- createNewRandomObject(world, e);
- }
- });
-
- window.g_finished = true; // for selenium
-}
-
-/**
- * Creates a new random object using 3d picking to figure out where to start it.
- * @param {Object} world A B2World object.
- * @param {Object} offset Mouse position relative to o3d area.
- */
-function createNewRandomObject(world, offset) {
- var worldRay = o3djs.picking.clientPositionToWorldRayEx(
- offset.x,
- offset.y,
- g.viewMatrix,
- g.projectionMatrix,
- g.o3dWidth,
- g.o3dHeight);
- var rayIntersectionInfo = g.worldBox.intersectRay(worldRay.near,
- worldRay.far);
- if (rayIntersectionInfo.intersected) {
- var position = rayIntersectionInfo.position;
- if (Math.random() < 0.5) {
- demos.top.createBall(world, position[0], position[1]);
- } else {
- createBox(world, position[0], position[1], 10, 10, false);
- }
- }
-}
-
-function init() {
- window.g_finished = false; // for selenium.
-
- // Runs the sample in V8. Comment out this line to run it in the browser
- // JavaScript engine, for example if you want to debug it. This sample cannot
- // currently run in V8 on IE because it access the DOM.
- if (!o3djs.base.IsMSIE()) {
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
- o3djs.util.addScriptUri('third_party');
- o3djs.util.addScriptUri('demos');
- o3djs.util.addScriptUri('style');
- }
-
- o3djs.util.makeClients(setupStep2);
-}
-
-function uninit() {
- if (g.client) {
- g.client.cleanup();
- }
-}
diff --git a/o3d/samples/box2d-3d/demos/draw_world.js b/o3d/samples/box2d-3d/demos/draw_world.js
deleted file mode 100644
index b49ef1a..0000000
--- a/o3d/samples/box2d-3d/demos/draw_world.js
+++ /dev/null
@@ -1,90 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-// NOTE: Changed this file pretty significantly. The original uses a
-// canvas element and drew lines on it. This one just updates the positions and
-// orientations of o3d objects to match the physics as well as using a
-// scaled box to stand in for joints.
-
-/**
- * Draws all the object in the world.
- * @param {Object} world A B2World object managing the physics world.
- */
-function drawWorld(world) {
- for (var j = world.m_jointList; j; j = j.m_next) {
- drawJoint(j);
- }
- for (var b = world.m_bodyList; b; b = b.m_next) {
- var o3dShape = b.GetUserData();
- if (o3dShape) {
- o3dShape.updateTransform(b);
- }
- }
-}
-/**
- * Scales a joint transform to represnet a line.
- * @param {Object} transformInfo An object with o3d information for the
- * joint.
- * @param {Object} p1 An object with x and y fields that specify the origin of
- * the joint in 2d.
- * @param {Object} p2 An object with x an dy fields that specify the far end of
- * the joint in 2d.
- */
-function scaleJointTransform(transformInfo, p1, p2) {
- var dx = p2.x - p1.x;
- var dy = p2.y - p1.y;
- var length = Math.sqrt(dx * dx + dy * dy);
- var transform = transformInfo.transform;
- transform.identity();
- transform.translate(p1.x, p1.y, 0);
- transform.rotateZ(Math.atan2(-dx, dy));
- transform.scale(2, length, 2);
-}
-
-/**
- * Draws a joint
- * @param {Object} joint A b2Joint object representing a joint.
- */
-function drawJoint(joint) {
- var transformInfo = joint.m_o3dTransformInfo;
- if (!transformInfo) {
- // This joint did not already have something in o3d to represent it
- // so we create one here.
- var transform = g.pack.createObject('Transform');
- transform.parent = g.root;
- transform.addShape(g.lineShape);
- transformInfo = {
- transform: transform
- };
- joint.m_o3dTransformInfo = transformInfo;
- }
- var b1 = joint.m_body1;
- var b2 = joint.m_body2;
- var x1 = b1.m_position;
- var x2 = b2.m_position;
- var p1 = joint.GetAnchor1();
- var p2 = joint.GetAnchor2();
- switch (joint.m_type) {
- case b2Joint.e_distanceJoint:
- scaleJointTransform(transformInfo, p1, p2);
- break;
-
- case b2Joint.e_pulleyJoint:
- break;
-
- default:
- if (b1 == world.m_groundBody) {
- scaleJointTransform(transformInfo, p1, x2);
- }
- else if (b2 == world.m_groundBody) {
- scaleJointTransform(transformInfo, p1, x1);
- }
- else {
- scaleJointTransform(transformInfo, x1, x2);
- }
- break;
- }
-}
-
diff --git a/o3d/samples/box2d-3d/demos/manager.js b/o3d/samples/box2d-3d/demos/manager.js
deleted file mode 100644
index 8fc177b..0000000
--- a/o3d/samples/box2d-3d/demos/manager.js
+++ /dev/null
@@ -1,210 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-/**
- * O3DManager manages o3d objects for this demo.
- * @constructor
- */
-function O3DManager() {
- this.shapes = [];
-}
-
-/**
- * Gets or creates a cylinder shape. If a cylinder of the same radius already
- * exists that one will be returned, otherwise a new one will be created.
- * @param {number} radius Radius of cylinder to create.
- * @return {o3d.Shape} The shape.
- */
-O3DManager.prototype.createCylinder = function(radius) {
- var id = 'cylinder-' + radius;
- var shape = this.shapes[id];
- if (!shape) {
- shape = o3djs.primitives.createCylinder(g.pack,
- g.materials[0],
- radius, 40, 20, 1,
- [[1, 0, 0, 0],
- [0, 0, 1, 0],
- [0, -1, 0, 0],
- [0, 0, 0, 1]]);
- this.shapes[id] = shape;
- }
- return new O3DShape({shape: shape});
-};
-
-/**
- * Gets or creates a compound cylinder shape. If a compound cylinder shape of
- * the same parameters already exists that one will be returned, otherwise a new
- * one will be created.
- * @param {number} radius1 Radius of first cylinder.
- * @param {number} offset1 X Offset for first cylinder.
- * @param {number} radius2 Radius of second cylinder.
- * @param {number} offset2 X Offset for second cylinder.
- * @return {o3d.Shape} The shape.
- */
-O3DManager.prototype.createCompoundCylinder = function(radius1,
- offset1,
- radius2,
- offset2) {
- var id = 'compoundCylinder-' + radius1 + '-' + offset1 +
- '-' + radius2 + '-' + offset2;
- var shape = this.shapes[id];
- if (!shape) {
- shape = o3djs.primitives.createCylinder(
- g.pack, g.materials[0], radius1, 40, 20, 1,
- [[1, 0, 0, 0],
- [0, 0, 1, 0],
- [0, -1, 0, 0],
- [offset1, 0, 0, 1]]);
- shape2 = o3djs.primitives.createCylinder(
- g.pack, g.materials[0], radius2, 40, 20, 1,
- [[1, 0, 0, 0],
- [0, 0, 1, 0],
- [0, -1, 0, 0],
- [offset2, 0, 0, 1]]);
- shape2.elements[0].owner = shape;
- g.pack.removeObject(shape2);
- this.shapes[id] = shape;
- }
- return new O3DShape({shape: shape});
-};
-
-/**
- * Gets or creates a box shape. If a box of the same width and height already
- * exists that one will be returned, otherwise a new one will be created.
- * @param {number} width Width of box.
- * @param {number} height Height of box.
- * @return {o3d.Shape} The shape.
- */
-O3DManager.prototype.createBox = function(width, height) {
- var name = 'box-' + width + '-' + height;
- var shape = this.shapes[name];
- if (!shape) {
- shape = o3djs.primitives.createBox(g.pack,
- g.materials[0],
- width * 2, height * 2, 40);
- this.shapes[name] = shape;
- }
- return new O3DShape({shape: shape});
-};
-
-/**
- * Gets or creates a wedge shape. If a wedge of the same parametrs already
- * exists that one will be returned, otherwise a new one will be created.
- * @param {Array} points Array of points in the format
- * [[x1, y1], [x2, y2], [x3, y3]] that describe a 2d triangle.
- * @return {o3d.Shape} The shape.
- */
-O3DManager.prototype.createWedge = function(points) {
- var name = 'wedge';
- for (var pp = 0; pp < points.length; ++pp) {
- name += '-' + points[pp][0] + '-' + points[pp][1];
- }
- var shape = this.shapes[name];
- if (!shape) {
- shape = o3djs.primitives.createPrism(g.pack,
- g.materials[0],
- points, 40);
- this.shapes[name] = shape;
- }
- return new O3DShape({shape: shape});
-};
-
-/**
- * Gets or creates a compound wedge shape (2 wedges). If a compound wedge of the
- * same parametrs already exists that one will be returned, otherwise a new one
- * will be created.
- * @param {Array} points1 Array of points that describe a 2d triangle for the
- * first wedge in the format [[x1, y1], [x2, y2], [x3, y3]] .
- * @param {Object} position1 An object with x and y properties used to offset
- * the first wedge.
- * @param {number} rotation1 Rotation in radians to rotate the first wedge on
- * the z axis.
- * @param {Array} points2 Array of points that describe a 2d triangle for the
- * second wedge in the format [[x1, y1], [x2, y2], [x3, y3]] .
- * @param {Object} position2 An object with x and y properties used to offset
- * the second wedge.
- * @param {number} rotation2 Rotation in radians to rotate the second wedge on
- * the z axis.
- * @return {o3d.Shape} The shape.
- */
-O3DManager.prototype.createCompoundWedge = function(points1,
- position1,
- rotation1,
- points2,
- position2,
- rotation2) {
- var name = 'compoundWedge';
- for (var pp = 0; pp < points1.length; ++pp) {
- name += '-' + points1[pp][0] + '-' + points1[pp][1];
- }
- name += '-' + position1.x + '-' + position1.y + '-' + rotation1;
- for (var pp = 0; pp < points2.length; ++pp) {
- name += '-' + points2[pp][0] + '-' + points2[pp][1];
- }
- name += '-' + position2.x + '-' + position2.y + '-' + rotation2;
- var shape = this.shapes[name];
- if (!shape) {
- shape = o3djs.primitives.createPrism(
- g.pack,
- g.materials[0],
- points1,
- 40,
- g.math.matrix4.mul(
- g.math.matrix4.rotationZ(rotation1),
- g.math.matrix4.translation([position1.x, position1.y, 0])));
- shape2 = o3djs.primitives.createPrism(
- g.pack,
- g.materials[0],
- points2,
- 40,
- g.math.matrix4.mul(
- g.math.matrix4.rotationZ(rotation2),
- g.math.matrix4.translation([position2.x, position2.y, 0])));
- shape2.elements[0].owner = shape;
- g.pack.removeObject(shape2);
- this.shapes[name] = shape;
- }
- return new O3DShape({shape: shape});
-};
-
-/**
- * An O3DShape manages an O3D shape for the demo.
- * @constructor
- * @param {Object} spec An object that contains the fields needed to create the
- * O3DShape. Currently only the field "shape" is needed.
- */
-function O3DShape(spec) {
- this.init(spec);
-}
-
-/**
- * Initializes an O3DShape
- * @param {Object} spec An object that contains the fields needed to create the
- * O3DShape. Currently only the field "shape" is needed.
- */
-O3DShape.prototype.init = function(spec) {
- this.transform = g.pack.createObject('Transform');
- this.transform.parent = g.root;
- this.transform.addShape(spec.shape);
- this.transform.createParam('colorMult', 'ParamFloat4').value =
- [Math.random() * 0.8 + 0.2,
- Math.random() * 0.8 + 0.2,
- Math.random() * 0.8 + 0.2,
- 1];
-};
-
-/**
- * Updates the position and orientation of an O3DShape.
- * @param {Object} body A B2Body object from the Box2djs library.
- */
-O3DShape.prototype.updateTransform = function(body) {
- var transform = this.transform;
- var position = body.GetOriginPosition();
- transform.identity();
- transform.translate(position.x, position.y, 0);
- transform.rotateZ(body.GetRotation());
-};
-
-
diff --git a/o3d/samples/box2d-3d/demos/pendulum.js b/o3d/samples/box2d-3d/demos/pendulum.js
deleted file mode 100644
index 730d039..0000000
--- a/o3d/samples/box2d-3d/demos/pendulum.js
+++ /dev/null
@@ -1,25 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-demos.pendulum = {};
-demos.pendulum.initWorld = function(world) {
- var i;
- var ground = world.GetGroundBody();
- var jointDef = new b2RevoluteJointDef();
- var L = 150;
- for (i = 0; i < 4; i++) {
- jointDef.anchorPoint.Set(250 + 40 * i, 200 - L);
- jointDef.body1 = ground;
- jointDef.body2 = createBall(world, 250 + 40 * i, 200);
- world.CreateJoint(jointDef);
- }
- jointDef.anchorPoint.Set(250 - 40, 200 - L);
- jointDef.body1 = ground;
- jointDef.body2 = createBall(world, 250 - 40 - L, 200 - L);
- world.CreateJoint(jointDef);
-}
-demos.InitWorlds.push(demos.pendulum.initWorld);
-
-
diff --git a/o3d/samples/box2d-3d/demos/stack.js b/o3d/samples/box2d-3d/demos/stack.js
deleted file mode 100644
index ffee25b..0000000
--- a/o3d/samples/box2d-3d/demos/stack.js
+++ /dev/null
@@ -1,37 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-demos.stack = {};
-demos.stack.initWorld = function(world) {
- var sd = new b2BoxDef();
- var bd = new b2BodyDef();
- bd.AddShape(sd);
- sd.density = 1.0;
- sd.friction = 0.5;
- sd.extents.Set(10, 10);
-
- var i;
- for (i = 0; i < 8; i++) {
- bd.position.Set(500/2-Math.random()*2-1, (250-5-i*22));
- // NOTE: Added the following line to create a 3d object to display.
- bd.userData = g.mgr.createBox(10, 10);
- world.CreateBody(bd);
- }
- for (i = 0; i < 8; i++) {
- bd.position.Set(500/2-100-Math.random()*5+i, (250-5-i*22));
- // NOTE: Added the following line to create a 3d object to display.
- bd.userData = g.mgr.createBox(10, 10);
- world.CreateBody(bd);
- }
- for (i = 0; i < 8; i++) {
- bd.position.Set(500/2+100+Math.random()*5-i, (250-5-i*22));
- // NOTE: Added the following line to create a 3d object to display.
- bd.userData = g.mgr.createBox(10, 10);
- world.CreateBody(bd);
- }
-}
-demos.InitWorlds.push(demos.stack.initWorld);
-
-
diff --git a/o3d/samples/box2d-3d/demos/top.js b/o3d/samples/box2d-3d/demos/top.js
deleted file mode 100644
index e569e7e..0000000
--- a/o3d/samples/box2d-3d/demos/top.js
+++ /dev/null
@@ -1,53 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-demos.top = {};
-demos.top.createBall = function(world, x, y, rad, fixed) {
- var ballSd = new b2CircleDef();
- if (!fixed) ballSd.density = 1.0;
- ballSd.radius = rad || 10;
- ballSd.restitution = 0.2;
- var ballBd = new b2BodyDef();
- ballBd.AddShape(ballSd);
- ballBd.position.Set(x,y);
- // NOTE: Added the following line to create a 3d object to display.
- ballBd.userData = g.mgr.createCylinder(ballSd.radius);
- return world.CreateBody(ballBd);
-};
-demos.top.createPoly = function(world, x, y, points, fixed) {
- var polySd = new b2PolyDef();
- if (!fixed) polySd.density = 1.0;
- polySd.vertexCount = points.length;
- for (var i = 0; i < points.length; i++) {
- polySd.vertices[i].Set(points[i][0], points[i][1]);
- }
- var polyBd = new b2BodyDef();
- if (points.length == 3) {
- // NOTE: Added the following line to create a 3d object to display.
- polyBd.userData = g.mgr.createWedge(points);
- }
- polyBd.AddShape(polySd);
- polyBd.position.Set(x,y);
- return world.CreateBody(polyBd)
-};
-demos.top.initWorld = function(world) {
- demos.top.createBall(world, 350, 100, 50, true);
- demos.top.createPoly(world, 100, 100, [[0, 0], [10, 30], [-10, 30]], true);
- demos.top.createPoly(world, 150, 150, [[0, 0], [10, 30], [-10, 30]], true);
- var pendulum = createBox(world, 150, 100, 20, 20, false);
- var jointDef = new b2RevoluteJointDef();
- jointDef.body1 = pendulum;
- jointDef.body2 = world.GetGroundBody();
- jointDef.anchorPoint = pendulum.GetCenterPosition();
- world.CreateJoint(jointDef);
-
- var seesaw = demos.top.createPoly(world, 300, 200, [[0, 0], [100, 30], [-100, 30]]);
- jointDef.body1 = seesaw;
- jointDef.anchorPoint = seesaw.GetCenterPosition();
- world.CreateJoint(jointDef);
-};
-demos.InitWorlds.push(demos.top.initWorld);
-
-
diff --git a/o3d/samples/box2d-3d/third_party/box2d/LICENSE.txt b/o3d/samples/box2d-3d/third_party/box2d/LICENSE.txt
deleted file mode 100644
index c224b40..0000000
--- a/o3d/samples/box2d-3d/third_party/box2d/LICENSE.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-The zlib/libpng License
-
-Copyright (c) 2008 ANDO Yasushi
-
-This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
-
-Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
-
- 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
-
- 3. This notice may not be removed or altered from any source distribution.
-
diff --git a/o3d/samples/box2d-3d/third_party/box2d/README.o3d b/o3d/samples/box2d-3d/third_party/box2d/README.o3d
deleted file mode 100644
index 0f3fdc7..0000000
--- a/o3d/samples/box2d-3d/third_party/box2d/README.o3d
+++ /dev/null
@@ -1,5 +0,0 @@
-This directory contains a subset of Box2D-JS, available at
-http://box2d-js.sourceforge.net/ under the zlib/libpng license (see
-License.txt).
-The software was not modified, but only the portions under js/box2d in the
-original distribution are here.
diff --git a/o3d/samples/box2d-3d/third_party/box2d/box2d.js b/o3d/samples/box2d-3d/third_party/box2d/box2d.js
deleted file mode 100644
index 8b84f83..0000000
--- a/o3d/samples/box2d-3d/third_party/box2d/box2d.js
+++ /dev/null
@@ -1,1037 +0,0 @@
-/*
- * Box2Djs (port of Box2DFlash 1.4.3.1) - http://box2d-js.sourceforge.net/
- * Single-filed and jsmined ( http://code.google.com/p/jsmin-php/ ) by Mr.doob
- */
-
-var b2Settings=Class.create();b2Settings.prototype={initialize:function(){}}
-b2Settings.USHRT_MAX=0x0000ffff;b2Settings.b2_pi=Math.PI;b2Settings.b2_massUnitsPerKilogram=1.0;b2Settings.b2_timeUnitsPerSecond=1.0;b2Settings.b2_lengthUnitsPerMeter=30.0;b2Settings.b2_maxManifoldPoints=2;b2Settings.b2_maxShapesPerBody=64;b2Settings.b2_maxPolyVertices=8;b2Settings.b2_maxProxies=1024;b2Settings.b2_maxPairs=8*b2Settings.b2_maxProxies;b2Settings.b2_linearSlop=0.005*b2Settings.b2_lengthUnitsPerMeter;b2Settings.b2_angularSlop=2.0/180.0*b2Settings.b2_pi;b2Settings.b2_velocityThreshold=1.0*b2Settings.b2_lengthUnitsPerMeter/b2Settings.b2_timeUnitsPerSecond;b2Settings.b2_maxLinearCorrection=0.2*b2Settings.b2_lengthUnitsPerMeter;b2Settings.b2_maxAngularCorrection=8.0/180.0*b2Settings.b2_pi;b2Settings.b2_contactBaumgarte=0.2;b2Settings.b2_timeToSleep=0.5*b2Settings.b2_timeUnitsPerSecond;b2Settings.b2_linearSleepTolerance=0.01*b2Settings.b2_lengthUnitsPerMeter/b2Settings.b2_timeUnitsPerSecond;b2Settings.b2_angularSleepTolerance=2.0/180.0/b2Settings.b2_timeUnitsPerSecond;b2Settings.b2Assert=function(a)
-{if(!a){var nullVec;nullVec.x++;}};
-var b2Vec2=Class.create();b2Vec2.prototype={initialize:function(x_,y_){this.x=x_;this.y=y_;},SetZero:function(){this.x=0.0;this.y=0.0;},Set:function(x_,y_){this.x=x_;this.y=y_;},SetV:function(v){this.x=v.x;this.y=v.y;},Negative:function(){return new b2Vec2(-this.x,-this.y);},Copy:function(){return new b2Vec2(this.x,this.y);},Add:function(v)
-{this.x+=v.x;this.y+=v.y;},Subtract:function(v)
-{this.x-=v.x;this.y-=v.y;},Multiply:function(a)
-{this.x*=a;this.y*=a;},MulM:function(A)
-{var tX=this.x;this.x=A.col1.x*tX+A.col2.x*this.y;this.y=A.col1.y*tX+A.col2.y*this.y;},MulTM:function(A)
-{var tX=b2Math.b2Dot(this,A.col1);this.y=b2Math.b2Dot(this,A.col2);this.x=tX;},CrossVF:function(s)
-{var tX=this.x;this.x=s*this.y;this.y=-s*tX;},CrossFV:function(s)
-{var tX=this.x;this.x=-s*this.y;this.y=s*tX;},MinV:function(b)
-{this.x=this.x<b.x?this.x:b.x;this.y=this.y<b.y?this.y:b.y;},MaxV:function(b)
-{this.x=this.x>b.x?this.x:b.x;this.y=this.y>b.y?this.y:b.y;},Abs:function()
-{this.x=Math.abs(this.x);this.y=Math.abs(this.y);},Length:function()
-{return Math.sqrt(this.x*this.x+this.y*this.y);},Normalize:function()
-{var length=this.Length();if(length<Number.MIN_VALUE)
-{return 0.0;}
-var invLength=1.0/length;this.x*=invLength;this.y*=invLength;return length;},IsValid:function()
-{return b2Math.b2IsValid(this.x)&&b2Math.b2IsValid(this.y);},x:null,y:null};b2Vec2.Make=function(x_,y_)
-{return new b2Vec2(x_,y_);};
-var b2Mat22=Class.create();b2Mat22.prototype={initialize:function(angle,c1,c2)
-{if(angle==null)angle=0;this.col1=new b2Vec2();this.col2=new b2Vec2();if(c1!=null&&c2!=null){this.col1.SetV(c1);this.col2.SetV(c2);}
-else{var c=Math.cos(angle);var s=Math.sin(angle);this.col1.x=c;this.col2.x=-s;this.col1.y=s;this.col2.y=c;}},Set:function(angle)
-{var c=Math.cos(angle);var s=Math.sin(angle);this.col1.x=c;this.col2.x=-s;this.col1.y=s;this.col2.y=c;},SetVV:function(c1,c2)
-{this.col1.SetV(c1);this.col2.SetV(c2);},Copy:function(){return new b2Mat22(0,this.col1,this.col2);},SetM:function(m)
-{this.col1.SetV(m.col1);this.col2.SetV(m.col2);},AddM:function(m)
-{this.col1.x+=m.col1.x;this.col1.y+=m.col1.y;this.col2.x+=m.col2.x;this.col2.y+=m.col2.y;},SetIdentity:function()
-{this.col1.x=1.0;this.col2.x=0.0;this.col1.y=0.0;this.col2.y=1.0;},SetZero:function()
-{this.col1.x=0.0;this.col2.x=0.0;this.col1.y=0.0;this.col2.y=0.0;},Invert:function(out)
-{var a=this.col1.x;var b=this.col2.x;var c=this.col1.y;var d=this.col2.y;var det=a*d-b*c;det=1.0/det;out.col1.x=det*d;out.col2.x=-det*b;out.col1.y=-det*c;out.col2.y=det*a;return out;},Solve:function(out,bX,bY)
-{var a11=this.col1.x;var a12=this.col2.x;var a21=this.col1.y;var a22=this.col2.y;var det=a11*a22-a12*a21;det=1.0/det;out.x=det*(a22*bX-a12*bY);out.y=det*(a11*bY-a21*bX);return out;},Abs:function()
-{this.col1.Abs();this.col2.Abs();},col1:new b2Vec2(),col2:new b2Vec2()};
-var b2Math=Class.create();b2Math.prototype={initialize:function(){}}
-b2Math.b2IsValid=function(x)
-{return isFinite(x);};b2Math.b2Dot=function(a,b)
-{return a.x*b.x+a.y*b.y;};b2Math.b2CrossVV=function(a,b)
-{return a.x*b.y-a.y*b.x;};b2Math.b2CrossVF=function(a,s)
-{var v=new b2Vec2(s*a.y,-s*a.x);return v;};b2Math.b2CrossFV=function(s,a)
-{var v=new b2Vec2(-s*a.y,s*a.x);return v;};b2Math.b2MulMV=function(A,v)
-{var u=new b2Vec2(A.col1.x*v.x+A.col2.x*v.y,A.col1.y*v.x+A.col2.y*v.y);return u;};b2Math.b2MulTMV=function(A,v)
-{var u=new b2Vec2(b2Math.b2Dot(v,A.col1),b2Math.b2Dot(v,A.col2));return u;};b2Math.AddVV=function(a,b)
-{var v=new b2Vec2(a.x+b.x,a.y+b.y);return v;};b2Math.SubtractVV=function(a,b)
-{var v=new b2Vec2(a.x-b.x,a.y-b.y);return v;};b2Math.MulFV=function(s,a)
-{var v=new b2Vec2(s*a.x,s*a.y);return v;};b2Math.AddMM=function(A,B)
-{var C=new b2Mat22(0,b2Math.AddVV(A.col1,B.col1),b2Math.AddVV(A.col2,B.col2));return C;};b2Math.b2MulMM=function(A,B)
-{var C=new b2Mat22(0,b2Math.b2MulMV(A,B.col1),b2Math.b2MulMV(A,B.col2));return C;};b2Math.b2MulTMM=function(A,B)
-{var c1=new b2Vec2(b2Math.b2Dot(A.col1,B.col1),b2Math.b2Dot(A.col2,B.col1));var c2=new b2Vec2(b2Math.b2Dot(A.col1,B.col2),b2Math.b2Dot(A.col2,B.col2));var C=new b2Mat22(0,c1,c2);return C;};b2Math.b2Abs=function(a)
-{return a>0.0?a:-a;};b2Math.b2AbsV=function(a)
-{var b=new b2Vec2(b2Math.b2Abs(a.x),b2Math.b2Abs(a.y));return b;};b2Math.b2AbsM=function(A)
-{var B=new b2Mat22(0,b2Math.b2AbsV(A.col1),b2Math.b2AbsV(A.col2));return B;};b2Math.b2Min=function(a,b)
-{return a<b?a:b;};b2Math.b2MinV=function(a,b)
-{var c=new b2Vec2(b2Math.b2Min(a.x,b.x),b2Math.b2Min(a.y,b.y));return c;};b2Math.b2Max=function(a,b)
-{return a>b?a:b;};b2Math.b2MaxV=function(a,b)
-{var c=new b2Vec2(b2Math.b2Max(a.x,b.x),b2Math.b2Max(a.y,b.y));return c;};b2Math.b2Clamp=function(a,low,high)
-{return b2Math.b2Max(low,b2Math.b2Min(a,high));};b2Math.b2ClampV=function(a,low,high)
-{return b2Math.b2MaxV(low,b2Math.b2MinV(a,high));};b2Math.b2Swap=function(a,b)
-{var tmp=a[0];a[0]=b[0];b[0]=tmp;};b2Math.b2Random=function()
-{return Math.random()*2-1;};b2Math.b2NextPowerOfTwo=function(x)
-{x|=(x>>1)&0x7FFFFFFF;x|=(x>>2)&0x3FFFFFFF;x|=(x>>4)&0x0FFFFFFF;x|=(x>>8)&0x00FFFFFF;x|=(x>>16)&0x0000FFFF;return x+1;};b2Math.b2IsPowerOfTwo=function(x)
-{var result=x>0&&(x&(x-1))==0;return result;};b2Math.tempVec2=new b2Vec2();b2Math.tempVec3=new b2Vec2();b2Math.tempVec4=new b2Vec2();b2Math.tempVec5=new b2Vec2();b2Math.tempMat=new b2Mat22();
-var b2AABB=Class.create();b2AABB.prototype={IsValid:function(){var dX=this.maxVertex.x;var dY=this.maxVertex.y;dX=this.maxVertex.x;dY=this.maxVertex.y;dX-=this.minVertex.x;dY-=this.minVertex.y;var valid=dX>=0.0&&dY>=0.0;valid=valid&&this.minVertex.IsValid()&&this.maxVertex.IsValid();return valid;},minVertex:new b2Vec2(),maxVertex:new b2Vec2(),initialize:function(){this.minVertex=new b2Vec2();this.maxVertex=new b2Vec2();}};
-var b2Bound=Class.create();b2Bound.prototype={IsLower:function(){return(this.value&1)==0;},IsUpper:function(){return(this.value&1)==1;},Swap:function(b){var tempValue=this.value;var tempProxyId=this.proxyId;var tempStabbingCount=this.stabbingCount;this.value=b.value;this.proxyId=b.proxyId;this.stabbingCount=b.stabbingCount;b.value=tempValue;b.proxyId=tempProxyId;b.stabbingCount=tempStabbingCount;},value:0,proxyId:0,stabbingCount:0,initialize:function(){}}
-
-var b2BoundValues=Class.create();b2BoundValues.prototype={lowerValues:[0,0],upperValues:[0,0],initialize:function(){this.lowerValues=[0,0];this.upperValues=[0,0];}}
-
-var b2Pair=Class.create();b2Pair.prototype={SetBuffered:function(){this.status|=b2Pair.e_pairBuffered;},ClearBuffered:function(){this.status&=~b2Pair.e_pairBuffered;},IsBuffered:function(){return(this.status&b2Pair.e_pairBuffered)==b2Pair.e_pairBuffered;},SetRemoved:function(){this.status|=b2Pair.e_pairRemoved;},ClearRemoved:function(){this.status&=~b2Pair.e_pairRemoved;},IsRemoved:function(){return(this.status&b2Pair.e_pairRemoved)==b2Pair.e_pairRemoved;},SetFinal:function(){this.status|=b2Pair.e_pairFinal;},IsFinal:function(){return(this.status&b2Pair.e_pairFinal)==b2Pair.e_pairFinal;},userData:null,proxyId1:0,proxyId2:0,next:0,status:0,initialize:function(){}};b2Pair.b2_nullPair=b2Settings.USHRT_MAX;b2Pair.b2_nullProxy=b2Settings.USHRT_MAX;b2Pair.b2_tableCapacity=b2Settings.b2_maxPairs;b2Pair.b2_tableMask=b2Pair.b2_tableCapacity-1;b2Pair.e_pairBuffered=0x0001;b2Pair.e_pairRemoved=0x0002;b2Pair.e_pairFinal=0x0004;
-var b2PairCallback=Class.create();b2PairCallback.prototype={PairAdded:function(proxyUserData1,proxyUserData2){return null},PairRemoved:function(proxyUserData1,proxyUserData2,pairUserData){},initialize:function(){}};
-var b2BufferedPair=Class.create();b2BufferedPair.prototype={proxyId1:0,proxyId2:0,initialize:function(){}}
-
-var b2PairManager=Class.create();b2PairManager.prototype={initialize:function(){var i=0;this.m_hashTable=new Array(b2Pair.b2_tableCapacity);for(i=0;i<b2Pair.b2_tableCapacity;++i)
-{this.m_hashTable[i]=b2Pair.b2_nullPair;}
-this.m_pairs=new Array(b2Settings.b2_maxPairs);for(i=0;i<b2Settings.b2_maxPairs;++i)
-{this.m_pairs[i]=new b2Pair();}
-this.m_pairBuffer=new Array(b2Settings.b2_maxPairs);for(i=0;i<b2Settings.b2_maxPairs;++i)
-{this.m_pairBuffer[i]=new b2BufferedPair();}
-for(i=0;i<b2Settings.b2_maxPairs;++i)
-{this.m_pairs[i].proxyId1=b2Pair.b2_nullProxy;this.m_pairs[i].proxyId2=b2Pair.b2_nullProxy;this.m_pairs[i].userData=null;this.m_pairs[i].status=0;this.m_pairs[i].next=(i+1);}
-this.m_pairs[b2Settings.b2_maxPairs-1].next=b2Pair.b2_nullPair;this.m_pairCount=0;},Initialize:function(broadPhase,callback){this.m_broadPhase=broadPhase;this.m_callback=callback;},AddBufferedPair:function(proxyId1,proxyId2){var pair=this.AddPair(proxyId1,proxyId2);if(pair.IsBuffered()==false)
-{pair.SetBuffered();this.m_pairBuffer[this.m_pairBufferCount].proxyId1=pair.proxyId1;this.m_pairBuffer[this.m_pairBufferCount].proxyId2=pair.proxyId2;++this.m_pairBufferCount;}
-pair.ClearRemoved();if(b2BroadPhase.s_validate)
-{this.ValidateBuffer();}},RemoveBufferedPair:function(proxyId1,proxyId2){var pair=this.Find(proxyId1,proxyId2);if(pair==null)
-{return;}
-if(pair.IsBuffered()==false)
-{pair.SetBuffered();this.m_pairBuffer[this.m_pairBufferCount].proxyId1=pair.proxyId1;this.m_pairBuffer[this.m_pairBufferCount].proxyId2=pair.proxyId2;++this.m_pairBufferCount;}
-pair.SetRemoved();if(b2BroadPhase.s_validate)
-{this.ValidateBuffer();}},Commit:function(){var i=0;var removeCount=0;var proxies=this.m_broadPhase.m_proxyPool;for(i=0;i<this.m_pairBufferCount;++i)
-{var pair=this.Find(this.m_pairBuffer[i].proxyId1,this.m_pairBuffer[i].proxyId2);pair.ClearBuffered();var proxy1=proxies[pair.proxyId1];var proxy2=proxies[pair.proxyId2];if(pair.IsRemoved())
-{if(pair.IsFinal()==true)
-{this.m_callback.PairRemoved(proxy1.userData,proxy2.userData,pair.userData);}
-this.m_pairBuffer[removeCount].proxyId1=pair.proxyId1;this.m_pairBuffer[removeCount].proxyId2=pair.proxyId2;++removeCount;}
-else
-{if(pair.IsFinal()==false)
-{pair.userData=this.m_callback.PairAdded(proxy1.userData,proxy2.userData);pair.SetFinal();}}}
-for(i=0;i<removeCount;++i)
-{this.RemovePair(this.m_pairBuffer[i].proxyId1,this.m_pairBuffer[i].proxyId2);}
-this.m_pairBufferCount=0;if(b2BroadPhase.s_validate)
-{this.ValidateTable();}},AddPair:function(proxyId1,proxyId2){if(proxyId1>proxyId2){var temp=proxyId1;proxyId1=proxyId2;proxyId2=temp;}
-var hash=b2PairManager.Hash(proxyId1,proxyId2)&b2Pair.b2_tableMask;var pair=pair=this.FindHash(proxyId1,proxyId2,hash);if(pair!=null)
-{return pair;}
-var pIndex=this.m_freePair;pair=this.m_pairs[pIndex];this.m_freePair=pair.next;pair.proxyId1=proxyId1;pair.proxyId2=proxyId2;pair.status=0;pair.userData=null;pair.next=this.m_hashTable[hash];this.m_hashTable[hash]=pIndex;++this.m_pairCount;return pair;},RemovePair:function(proxyId1,proxyId2){if(proxyId1>proxyId2){var temp=proxyId1;proxyId1=proxyId2;proxyId2=temp;}
-var hash=b2PairManager.Hash(proxyId1,proxyId2)&b2Pair.b2_tableMask;var node=this.m_hashTable[hash];var pNode=null;while(node!=b2Pair.b2_nullPair)
-{if(b2PairManager.Equals(this.m_pairs[node],proxyId1,proxyId2))
-{var index=node;if(pNode){pNode.next=this.m_pairs[node].next;}
-else{this.m_hashTable[hash]=this.m_pairs[node].next;}
-var pair=this.m_pairs[index];var userData=pair.userData;pair.next=this.m_freePair;pair.proxyId1=b2Pair.b2_nullProxy;pair.proxyId2=b2Pair.b2_nullProxy;pair.userData=null;pair.status=0;this.m_freePair=index;--this.m_pairCount;return userData;}
-else
-{pNode=this.m_pairs[node];node=pNode.next;}}
-return null;},Find:function(proxyId1,proxyId2){if(proxyId1>proxyId2){var temp=proxyId1;proxyId1=proxyId2;proxyId2=temp;}
-var hash=b2PairManager.Hash(proxyId1,proxyId2)&b2Pair.b2_tableMask;return this.FindHash(proxyId1,proxyId2,hash);},FindHash:function(proxyId1,proxyId2,hash){var index=this.m_hashTable[hash];while(index!=b2Pair.b2_nullPair&&b2PairManager.Equals(this.m_pairs[index],proxyId1,proxyId2)==false)
-{index=this.m_pairs[index].next;}
-if(index==b2Pair.b2_nullPair)
-{return null;}
-return this.m_pairs[index];},ValidateBuffer:function(){},ValidateTable:function(){},m_broadPhase:null,m_callback:null,m_pairs:null,m_freePair:0,m_pairCount:0,m_pairBuffer:null,m_pairBufferCount:0,m_hashTable:null};b2PairManager.Hash=function(proxyId1,proxyId2)
-{var key=((proxyId2<<16)&0xffff0000)|proxyId1;key=~key+((key<<15)&0xFFFF8000);key=key^((key>>12)&0x000fffff);key=key+((key<<2)&0xFFFFFFFC);key=key^((key>>4)&0x0fffffff);key=key*2057;key=key^((key>>16)&0x0000ffff);return key;};b2PairManager.Equals=function(pair,proxyId1,proxyId2)
-{return(pair.proxyId1==proxyId1&&pair.proxyId2==proxyId2);};b2PairManager.EqualsPair=function(pair1,pair2)
-{return pair1.proxyId1==pair2.proxyId1&&pair1.proxyId2==pair2.proxyId2;};
-var b2BroadPhase=Class.create();b2BroadPhase.prototype={initialize:function(worldAABB,callback){this.m_pairManager=new b2PairManager();this.m_proxyPool=new Array(b2Settings.b2_maxPairs);this.m_bounds=new Array(2*b2Settings.b2_maxProxies);this.m_queryResults=new Array(b2Settings.b2_maxProxies);this.m_quantizationFactor=new b2Vec2();var i=0;this.m_pairManager.Initialize(this,callback);this.m_worldAABB=worldAABB;this.m_proxyCount=0;for(i=0;i<b2Settings.b2_maxProxies;i++){this.m_queryResults[i]=0;}
-this.m_bounds=new Array(2);for(i=0;i<2;i++){this.m_bounds[i]=new Array(2*b2Settings.b2_maxProxies);for(var j=0;j<2*b2Settings.b2_maxProxies;j++){this.m_bounds[i][j]=new b2Bound();}}
-var dX=worldAABB.maxVertex.x;var dY=worldAABB.maxVertex.y;dX-=worldAABB.minVertex.x;dY-=worldAABB.minVertex.y;this.m_quantizationFactor.x=b2Settings.USHRT_MAX/dX;this.m_quantizationFactor.y=b2Settings.USHRT_MAX/dY;var tProxy;for(i=0;i<b2Settings.b2_maxProxies-1;++i)
-{tProxy=new b2Proxy();this.m_proxyPool[i]=tProxy;tProxy.SetNext(i+1);tProxy.timeStamp=0;tProxy.overlapCount=b2BroadPhase.b2_invalid;tProxy.userData=null;}
-tProxy=new b2Proxy();this.m_proxyPool[b2Settings.b2_maxProxies-1]=tProxy;tProxy.SetNext(b2Pair.b2_nullProxy);tProxy.timeStamp=0;tProxy.overlapCount=b2BroadPhase.b2_invalid;tProxy.userData=null;this.m_freeProxy=0;this.m_timeStamp=1;this.m_queryResultCount=0;},InRange:function(aabb){var dX;var dY;var d2X;var d2Y;dX=aabb.minVertex.x;dY=aabb.minVertex.y;dX-=this.m_worldAABB.maxVertex.x;dY-=this.m_worldAABB.maxVertex.y;d2X=this.m_worldAABB.minVertex.x;d2Y=this.m_worldAABB.minVertex.y;d2X-=aabb.maxVertex.x;d2Y-=aabb.maxVertex.y;dX=b2Math.b2Max(dX,d2X);dY=b2Math.b2Max(dY,d2Y);return b2Math.b2Max(dX,dY)<0.0;},GetProxy:function(proxyId){if(proxyId==b2Pair.b2_nullProxy||this.m_proxyPool[proxyId].IsValid()==false)
-{return null;}
-return this.m_proxyPool[proxyId];},CreateProxy:function(aabb,userData){var index=0;var proxy;var proxyId=this.m_freeProxy;proxy=this.m_proxyPool[proxyId];this.m_freeProxy=proxy.GetNext();proxy.overlapCount=0;proxy.userData=userData;var boundCount=2*this.m_proxyCount;var lowerValues=new Array();var upperValues=new Array();this.ComputeBounds(lowerValues,upperValues,aabb);for(var axis=0;axis<2;++axis)
-{var bounds=this.m_bounds[axis];var lowerIndex=0;var upperIndex=0;var lowerIndexOut=[lowerIndex];var upperIndexOut=[upperIndex];this.Query(lowerIndexOut,upperIndexOut,lowerValues[axis],upperValues[axis],bounds,boundCount,axis);lowerIndex=lowerIndexOut[0];upperIndex=upperIndexOut[0];var tArr=new Array();var j=0;var tEnd=boundCount-upperIndex
-var tBound1;var tBound2;for(j=0;j<tEnd;j++){tArr[j]=new b2Bound();tBound1=tArr[j];tBound2=bounds[upperIndex+j];tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-tEnd=tArr.length;var tIndex=upperIndex+2;for(j=0;j<tEnd;j++){tBound2=tArr[j];tBound1=bounds[tIndex+j]
-tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-tArr=new Array();tEnd=upperIndex-lowerIndex;for(j=0;j<tEnd;j++){tArr[j]=new b2Bound();tBound1=tArr[j];tBound2=bounds[lowerIndex+j];tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-tEnd=tArr.length;tIndex=lowerIndex+1;for(j=0;j<tEnd;j++){tBound2=tArr[j];tBound1=bounds[tIndex+j]
-tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-++upperIndex;bounds[lowerIndex].value=lowerValues[axis];bounds[lowerIndex].proxyId=proxyId;bounds[upperIndex].value=upperValues[axis];bounds[upperIndex].proxyId=proxyId;bounds[lowerIndex].stabbingCount=lowerIndex==0?0:bounds[lowerIndex-1].stabbingCount;bounds[upperIndex].stabbingCount=bounds[upperIndex-1].stabbingCount;for(index=lowerIndex;index<upperIndex;++index)
-{bounds[index].stabbingCount++;}
-for(index=lowerIndex;index<boundCount+2;++index)
-{var proxy2=this.m_proxyPool[bounds[index].proxyId];if(bounds[index].IsLower())
-{proxy2.lowerBounds[axis]=index;}
-else
-{proxy2.upperBounds[axis]=index;}}}
-++this.m_proxyCount;for(var i=0;i<this.m_queryResultCount;++i)
-{this.m_pairManager.AddBufferedPair(proxyId,this.m_queryResults[i]);}
-this.m_pairManager.Commit();this.m_queryResultCount=0;this.IncrementTimeStamp();return proxyId;},DestroyProxy:function(proxyId){var proxy=this.m_proxyPool[proxyId];var boundCount=2*this.m_proxyCount;for(var axis=0;axis<2;++axis)
-{var bounds=this.m_bounds[axis];var lowerIndex=proxy.lowerBounds[axis];var upperIndex=proxy.upperBounds[axis];var lowerValue=bounds[lowerIndex].value;var upperValue=bounds[upperIndex].value;var tArr=new Array();var j=0;var tEnd=upperIndex-lowerIndex-1;var tBound1;var tBound2;for(j=0;j<tEnd;j++){tArr[j]=new b2Bound();tBound1=tArr[j];tBound2=bounds[lowerIndex+1+j];tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-tEnd=tArr.length;var tIndex=lowerIndex;for(j=0;j<tEnd;j++){tBound2=tArr[j];tBound1=bounds[tIndex+j]
-tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-tArr=new Array();tEnd=boundCount-upperIndex-1;for(j=0;j<tEnd;j++){tArr[j]=new b2Bound();tBound1=tArr[j];tBound2=bounds[upperIndex+1+j];tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-tEnd=tArr.length;tIndex=upperIndex-1;for(j=0;j<tEnd;j++){tBound2=tArr[j];tBound1=bounds[tIndex+j]
-tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-tEnd=boundCount-2;for(var index=lowerIndex;index<tEnd;++index)
-{var proxy2=this.m_proxyPool[bounds[index].proxyId];if(bounds[index].IsLower())
-{proxy2.lowerBounds[axis]=index;}
-else
-{proxy2.upperBounds[axis]=index;}}
-tEnd=upperIndex-1;for(var index2=lowerIndex;index2<tEnd;++index2)
-{bounds[index2].stabbingCount--;}
-this.Query([0],[0],lowerValue,upperValue,bounds,boundCount-2,axis);}
-for(var i=0;i<this.m_queryResultCount;++i)
-{this.m_pairManager.RemoveBufferedPair(proxyId,this.m_queryResults[i]);}
-this.m_pairManager.Commit();this.m_queryResultCount=0;this.IncrementTimeStamp();proxy.userData=null;proxy.overlapCount=b2BroadPhase.b2_invalid;proxy.lowerBounds[0]=b2BroadPhase.b2_invalid;proxy.lowerBounds[1]=b2BroadPhase.b2_invalid;proxy.upperBounds[0]=b2BroadPhase.b2_invalid;proxy.upperBounds[1]=b2BroadPhase.b2_invalid;proxy.SetNext(this.m_freeProxy);this.m_freeProxy=proxyId;--this.m_proxyCount;},MoveProxy:function(proxyId,aabb){var axis=0;var index=0;var bound;var prevBound
-var nextBound
-var nextProxyId=0;var nextProxy;if(proxyId==b2Pair.b2_nullProxy||b2Settings.b2_maxProxies<=proxyId)
-{return;}
-if(aabb.IsValid()==false)
-{return;}
-var boundCount=2*this.m_proxyCount;var proxy=this.m_proxyPool[proxyId];var newValues=new b2BoundValues();this.ComputeBounds(newValues.lowerValues,newValues.upperValues,aabb);var oldValues=new b2BoundValues();for(axis=0;axis<2;++axis)
-{oldValues.lowerValues[axis]=this.m_bounds[axis][proxy.lowerBounds[axis]].value;oldValues.upperValues[axis]=this.m_bounds[axis][proxy.upperBounds[axis]].value;}
-for(axis=0;axis<2;++axis)
-{var bounds=this.m_bounds[axis];var lowerIndex=proxy.lowerBounds[axis];var upperIndex=proxy.upperBounds[axis];var lowerValue=newValues.lowerValues[axis];var upperValue=newValues.upperValues[axis];var deltaLower=lowerValue-bounds[lowerIndex].value;var deltaUpper=upperValue-bounds[upperIndex].value;bounds[lowerIndex].value=lowerValue;bounds[upperIndex].value=upperValue;if(deltaLower<0)
-{index=lowerIndex;while(index>0&&lowerValue<bounds[index-1].value)
-{bound=bounds[index];prevBound=bounds[index-1];var prevProxyId=prevBound.proxyId;var prevProxy=this.m_proxyPool[prevBound.proxyId];prevBound.stabbingCount++;if(prevBound.IsUpper()==true)
-{if(this.TestOverlap(newValues,prevProxy))
-{this.m_pairManager.AddBufferedPair(proxyId,prevProxyId);}
-prevProxy.upperBounds[axis]++;bound.stabbingCount++;}
-else
-{prevProxy.lowerBounds[axis]++;bound.stabbingCount--;}
-proxy.lowerBounds[axis]--;bound.Swap(prevBound);--index;}}
-if(deltaUpper>0)
-{index=upperIndex;while(index<boundCount-1&&bounds[index+1].value<=upperValue)
-{bound=bounds[index];nextBound=bounds[index+1];nextProxyId=nextBound.proxyId;nextProxy=this.m_proxyPool[nextProxyId];nextBound.stabbingCount++;if(nextBound.IsLower()==true)
-{if(this.TestOverlap(newValues,nextProxy))
-{this.m_pairManager.AddBufferedPair(proxyId,nextProxyId);}
-nextProxy.lowerBounds[axis]--;bound.stabbingCount++;}
-else
-{nextProxy.upperBounds[axis]--;bound.stabbingCount--;}
-proxy.upperBounds[axis]++;bound.Swap(nextBound);index++;}}
-if(deltaLower>0)
-{index=lowerIndex;while(index<boundCount-1&&bounds[index+1].value<=lowerValue)
-{bound=bounds[index];nextBound=bounds[index+1];nextProxyId=nextBound.proxyId;nextProxy=this.m_proxyPool[nextProxyId];nextBound.stabbingCount--;if(nextBound.IsUpper())
-{if(this.TestOverlap(oldValues,nextProxy))
-{this.m_pairManager.RemoveBufferedPair(proxyId,nextProxyId);}
-nextProxy.upperBounds[axis]--;bound.stabbingCount--;}
-else
-{nextProxy.lowerBounds[axis]--;bound.stabbingCount++;}
-proxy.lowerBounds[axis]++;bound.Swap(nextBound);index++;}}
-if(deltaUpper<0)
-{index=upperIndex;while(index>0&&upperValue<bounds[index-1].value)
-{bound=bounds[index];prevBound=bounds[index-1];prevProxyId=prevBound.proxyId;prevProxy=this.m_proxyPool[prevProxyId];prevBound.stabbingCount--;if(prevBound.IsLower()==true)
-{if(this.TestOverlap(oldValues,prevProxy))
-{this.m_pairManager.RemoveBufferedPair(proxyId,prevProxyId);}
-prevProxy.lowerBounds[axis]++;bound.stabbingCount--;}
-else
-{prevProxy.upperBounds[axis]++;bound.stabbingCount++;}
-proxy.upperBounds[axis]--;bound.Swap(prevBound);index--;}}}},Commit:function(){this.m_pairManager.Commit();},QueryAABB:function(aabb,userData,maxCount){var lowerValues=new Array();var upperValues=new Array();this.ComputeBounds(lowerValues,upperValues,aabb);var lowerIndex=0;var upperIndex=0;var lowerIndexOut=[lowerIndex];var upperIndexOut=[upperIndex];this.Query(lowerIndexOut,upperIndexOut,lowerValues[0],upperValues[0],this.m_bounds[0],2*this.m_proxyCount,0);this.Query(lowerIndexOut,upperIndexOut,lowerValues[1],upperValues[1],this.m_bounds[1],2*this.m_proxyCount,1);var count=0;for(var i=0;i<this.m_queryResultCount&&count<maxCount;++i,++count)
-{var proxy=this.m_proxyPool[this.m_queryResults[i]];userData[i]=proxy.userData;}
-this.m_queryResultCount=0;this.IncrementTimeStamp();return count;},Validate:function(){var pair;var proxy1;var proxy2;var overlap;for(var axis=0;axis<2;++axis)
-{var bounds=this.m_bounds[axis];var boundCount=2*this.m_proxyCount;var stabbingCount=0;for(var i=0;i<boundCount;++i)
-{var bound=bounds[i];if(bound.IsLower()==true)
-{stabbingCount++;}
-else
-{stabbingCount--;}}}},ComputeBounds:function(lowerValues,upperValues,aabb)
-{var minVertexX=aabb.minVertex.x;var minVertexY=aabb.minVertex.y;minVertexX=b2Math.b2Min(minVertexX,this.m_worldAABB.maxVertex.x);minVertexY=b2Math.b2Min(minVertexY,this.m_worldAABB.maxVertex.y);minVertexX=b2Math.b2Max(minVertexX,this.m_worldAABB.minVertex.x);minVertexY=b2Math.b2Max(minVertexY,this.m_worldAABB.minVertex.y);var maxVertexX=aabb.maxVertex.x;var maxVertexY=aabb.maxVertex.y;maxVertexX=b2Math.b2Min(maxVertexX,this.m_worldAABB.maxVertex.x);maxVertexY=b2Math.b2Min(maxVertexY,this.m_worldAABB.maxVertex.y);maxVertexX=b2Math.b2Max(maxVertexX,this.m_worldAABB.minVertex.x);maxVertexY=b2Math.b2Max(maxVertexY,this.m_worldAABB.minVertex.y);lowerValues[0]=(this.m_quantizationFactor.x*(minVertexX-this.m_worldAABB.minVertex.x))&(b2Settings.USHRT_MAX-1);upperValues[0]=((this.m_quantizationFactor.x*(maxVertexX-this.m_worldAABB.minVertex.x))&0x0000ffff)|1;lowerValues[1]=(this.m_quantizationFactor.y*(minVertexY-this.m_worldAABB.minVertex.y))&(b2Settings.USHRT_MAX-1);upperValues[1]=((this.m_quantizationFactor.y*(maxVertexY-this.m_worldAABB.minVertex.y))&0x0000ffff)|1;},TestOverlapValidate:function(p1,p2){for(var axis=0;axis<2;++axis)
-{var bounds=this.m_bounds[axis];if(bounds[p1.lowerBounds[axis]].value>bounds[p2.upperBounds[axis]].value)
-return false;if(bounds[p1.upperBounds[axis]].value<bounds[p2.lowerBounds[axis]].value)
-return false;}
-return true;},TestOverlap:function(b,p)
-{for(var axis=0;axis<2;++axis)
-{var bounds=this.m_bounds[axis];if(b.lowerValues[axis]>bounds[p.upperBounds[axis]].value)
-return false;if(b.upperValues[axis]<bounds[p.lowerBounds[axis]].value)
-return false;}
-return true;},Query:function(lowerQueryOut,upperQueryOut,lowerValue,upperValue,bounds,boundCount,axis){var lowerQuery=b2BroadPhase.BinarySearch(bounds,boundCount,lowerValue);var upperQuery=b2BroadPhase.BinarySearch(bounds,boundCount,upperValue);for(var j=lowerQuery;j<upperQuery;++j)
-{if(bounds[j].IsLower())
-{this.IncrementOverlapCount(bounds[j].proxyId);}}
-if(lowerQuery>0)
-{var i=lowerQuery-1;var s=bounds[i].stabbingCount;while(s)
-{if(bounds[i].IsLower())
-{var proxy=this.m_proxyPool[bounds[i].proxyId];if(lowerQuery<=proxy.upperBounds[axis])
-{this.IncrementOverlapCount(bounds[i].proxyId);--s;}}
---i;}}
-lowerQueryOut[0]=lowerQuery;upperQueryOut[0]=upperQuery;},IncrementOverlapCount:function(proxyId){var proxy=this.m_proxyPool[proxyId];if(proxy.timeStamp<this.m_timeStamp)
-{proxy.timeStamp=this.m_timeStamp;proxy.overlapCount=1;}
-else
-{proxy.overlapCount=2;this.m_queryResults[this.m_queryResultCount]=proxyId;++this.m_queryResultCount;}},IncrementTimeStamp:function(){if(this.m_timeStamp==b2Settings.USHRT_MAX)
-{for(var i=0;i<b2Settings.b2_maxProxies;++i)
-{this.m_proxyPool[i].timeStamp=0;}
-this.m_timeStamp=1;}
-else
-{++this.m_timeStamp;}},m_pairManager:new b2PairManager(),m_proxyPool:new Array(b2Settings.b2_maxPairs),m_freeProxy:0,m_bounds:new Array(2*b2Settings.b2_maxProxies),m_queryResults:new Array(b2Settings.b2_maxProxies),m_queryResultCount:0,m_worldAABB:null,m_quantizationFactor:new b2Vec2(),m_proxyCount:0,m_timeStamp:0};b2BroadPhase.s_validate=false;b2BroadPhase.b2_invalid=b2Settings.USHRT_MAX;b2BroadPhase.b2_nullEdge=b2Settings.USHRT_MAX;b2BroadPhase.BinarySearch=function(bounds,count,value)
-{var low=0;var high=count-1;while(low<=high)
-{var mid=Math.floor((low+high)/2);if(bounds[mid].value>value)
-{high=mid-1;}
-else if(bounds[mid].value<value)
-{low=mid+1;}
-else
-{return(mid);}}
-return(low);};
-var b2Collision=Class.create();b2Collision.prototype={initialize:function(){}}
-b2Collision.b2_nullFeature=0x000000ff;b2Collision.ClipSegmentToLine=function(vOut,vIn,normal,offset)
-{var numOut=0;var vIn0=vIn[0].v;var vIn1=vIn[1].v;var distance0=b2Math.b2Dot(normal,vIn[0].v)-offset;var distance1=b2Math.b2Dot(normal,vIn[1].v)-offset;if(distance0<=0.0)vOut[numOut++]=vIn[0];if(distance1<=0.0)vOut[numOut++]=vIn[1];if(distance0*distance1<0.0)
-{var interp=distance0/(distance0-distance1);var tVec=vOut[numOut].v;tVec.x=vIn0.x+interp*(vIn1.x-vIn0.x);tVec.y=vIn0.y+interp*(vIn1.y-vIn0.y);if(distance0>0.0)
-{vOut[numOut].id=vIn[0].id;}
-else
-{vOut[numOut].id=vIn[1].id;}
-++numOut;}
-return numOut;};b2Collision.EdgeSeparation=function(poly1,edge1,poly2)
-{var vert1s=poly1.m_vertices;var count2=poly2.m_vertexCount;var vert2s=poly2.m_vertices;var normalX=poly1.m_normals[edge1].x;var normalY=poly1.m_normals[edge1].y;var tX=normalX;var tMat=poly1.m_R;normalX=tMat.col1.x*tX+tMat.col2.x*normalY;normalY=tMat.col1.y*tX+tMat.col2.y*normalY;var normalLocal2X=normalX;var normalLocal2Y=normalY;tMat=poly2.m_R;tX=normalLocal2X*tMat.col1.x+normalLocal2Y*tMat.col1.y;normalLocal2Y=normalLocal2X*tMat.col2.x+normalLocal2Y*tMat.col2.y;normalLocal2X=tX;var vertexIndex2=0;var minDot=Number.MAX_VALUE;for(var i=0;i<count2;++i)
-{var tVec=vert2s[i];var dot=tVec.x*normalLocal2X+tVec.y*normalLocal2Y;if(dot<minDot)
-{minDot=dot;vertexIndex2=i;}}
-tMat=poly1.m_R;var v1X=poly1.m_position.x+(tMat.col1.x*vert1s[edge1].x+tMat.col2.x*vert1s[edge1].y)
-var v1Y=poly1.m_position.y+(tMat.col1.y*vert1s[edge1].x+tMat.col2.y*vert1s[edge1].y)
-tMat=poly2.m_R;var v2X=poly2.m_position.x+(tMat.col1.x*vert2s[vertexIndex2].x+tMat.col2.x*vert2s[vertexIndex2].y)
-var v2Y=poly2.m_position.y+(tMat.col1.y*vert2s[vertexIndex2].x+tMat.col2.y*vert2s[vertexIndex2].y)
-v2X-=v1X;v2Y-=v1Y;var separation=v2X*normalX+v2Y*normalY;return separation;};b2Collision.FindMaxSeparation=function(edgeIndex,poly1,poly2,conservative)
-{var count1=poly1.m_vertexCount;var dX=poly2.m_position.x-poly1.m_position.x;var dY=poly2.m_position.y-poly1.m_position.y;var dLocal1X=(dX*poly1.m_R.col1.x+dY*poly1.m_R.col1.y);var dLocal1Y=(dX*poly1.m_R.col2.x+dY*poly1.m_R.col2.y);var edge=0;var maxDot=-Number.MAX_VALUE;for(var i=0;i<count1;++i)
-{var dot=(poly1.m_normals[i].x*dLocal1X+poly1.m_normals[i].y*dLocal1Y);if(dot>maxDot)
-{maxDot=dot;edge=i;}}
-var s=b2Collision.EdgeSeparation(poly1,edge,poly2);if(s>0.0&&conservative==false)
-{return s;}
-var prevEdge=edge-1>=0?edge-1:count1-1;var sPrev=b2Collision.EdgeSeparation(poly1,prevEdge,poly2);if(sPrev>0.0&&conservative==false)
-{return sPrev;}
-var nextEdge=edge+1<count1?edge+1:0;var sNext=b2Collision.EdgeSeparation(poly1,nextEdge,poly2);if(sNext>0.0&&conservative==false)
-{return sNext;}
-var bestEdge=0;var bestSeparation;var increment=0;if(sPrev>s&&sPrev>sNext)
-{increment=-1;bestEdge=prevEdge;bestSeparation=sPrev;}
-else if(sNext>s)
-{increment=1;bestEdge=nextEdge;bestSeparation=sNext;}
-else
-{edgeIndex[0]=edge;return s;}
-while(true)
-{if(increment==-1)
-edge=bestEdge-1>=0?bestEdge-1:count1-1;else
-edge=bestEdge+1<count1?bestEdge+1:0;s=b2Collision.EdgeSeparation(poly1,edge,poly2);if(s>0.0&&conservative==false)
-{return s;}
-if(s>bestSeparation)
-{bestEdge=edge;bestSeparation=s;}
-else
-{break;}}
-edgeIndex[0]=bestEdge;return bestSeparation;};b2Collision.FindIncidentEdge=function(c,poly1,edge1,poly2)
-{var count1=poly1.m_vertexCount;var vert1s=poly1.m_vertices;var count2=poly2.m_vertexCount;var vert2s=poly2.m_vertices;var vertex11=edge1;var vertex12=edge1+1==count1?0:edge1+1;var tVec=vert1s[vertex12];var normal1Local1X=tVec.x;var normal1Local1Y=tVec.y;tVec=vert1s[vertex11];normal1Local1X-=tVec.x;normal1Local1Y-=tVec.y;var tX=normal1Local1X;normal1Local1X=normal1Local1Y;normal1Local1Y=-tX;var invLength=1.0/Math.sqrt(normal1Local1X*normal1Local1X+normal1Local1Y*normal1Local1Y);normal1Local1X*=invLength;normal1Local1Y*=invLength;var normal1X=normal1Local1X;var normal1Y=normal1Local1Y;tX=normal1X;var tMat=poly1.m_R;normal1X=tMat.col1.x*tX+tMat.col2.x*normal1Y;normal1Y=tMat.col1.y*tX+tMat.col2.y*normal1Y;var normal1Local2X=normal1X;var normal1Local2Y=normal1Y;tMat=poly2.m_R;tX=normal1Local2X*tMat.col1.x+normal1Local2Y*tMat.col1.y;normal1Local2Y=normal1Local2X*tMat.col2.x+normal1Local2Y*tMat.col2.y;normal1Local2X=tX;var vertex21=0;var vertex22=0;var minDot=Number.MAX_VALUE;for(var i=0;i<count2;++i)
-{var i1=i;var i2=i+1<count2?i+1:0;tVec=vert2s[i2];var normal2Local2X=tVec.x;var normal2Local2Y=tVec.y;tVec=vert2s[i1];normal2Local2X-=tVec.x;normal2Local2Y-=tVec.y;tX=normal2Local2X;normal2Local2X=normal2Local2Y;normal2Local2Y=-tX;invLength=1.0/Math.sqrt(normal2Local2X*normal2Local2X+normal2Local2Y*normal2Local2Y);normal2Local2X*=invLength;normal2Local2Y*=invLength;var dot=normal2Local2X*normal1Local2X+normal2Local2Y*normal1Local2Y;if(dot<minDot)
-{minDot=dot;vertex21=i1;vertex22=i2;}}
-var tClip;tClip=c[0];tVec=tClip.v;tVec.SetV(vert2s[vertex21]);tVec.MulM(poly2.m_R);tVec.Add(poly2.m_position);tClip.id.features.referenceFace=edge1;tClip.id.features.incidentEdge=vertex21;tClip.id.features.incidentVertex=vertex21;tClip=c[1];tVec=tClip.v;tVec.SetV(vert2s[vertex22]);tVec.MulM(poly2.m_R);tVec.Add(poly2.m_position);tClip.id.features.referenceFace=edge1;tClip.id.features.incidentEdge=vertex21;tClip.id.features.incidentVertex=vertex22;};b2Collision.b2CollidePolyTempVec=new b2Vec2();b2Collision.b2CollidePoly=function(manifold,polyA,polyB,conservative)
-{manifold.pointCount=0;var edgeA=0;var edgeAOut=[edgeA];var separationA=b2Collision.FindMaxSeparation(edgeAOut,polyA,polyB,conservative);edgeA=edgeAOut[0];if(separationA>0.0&&conservative==false)
-return;var edgeB=0;var edgeBOut=[edgeB];var separationB=b2Collision.FindMaxSeparation(edgeBOut,polyB,polyA,conservative);edgeB=edgeBOut[0];if(separationB>0.0&&conservative==false)
-return;var poly1;var poly2;var edge1=0;var flip=0;var k_relativeTol=0.98;var k_absoluteTol=0.001;if(separationB>k_relativeTol*separationA+k_absoluteTol)
-{poly1=polyB;poly2=polyA;edge1=edgeB;flip=1;}
-else
-{poly1=polyA;poly2=polyB;edge1=edgeA;flip=0;}
-var incidentEdge=[new ClipVertex(),new ClipVertex()];b2Collision.FindIncidentEdge(incidentEdge,poly1,edge1,poly2);var count1=poly1.m_vertexCount;var vert1s=poly1.m_vertices;var v11=vert1s[edge1];var v12=edge1+1<count1?vert1s[edge1+1]:vert1s[0];var dvX=v12.x-v11.x;var dvY=v12.y-v11.y;var sideNormalX=v12.x-v11.x;var sideNormalY=v12.y-v11.y;var tX=sideNormalX;var tMat=poly1.m_R;sideNormalX=tMat.col1.x*tX+tMat.col2.x*sideNormalY;sideNormalY=tMat.col1.y*tX+tMat.col2.y*sideNormalY;var invLength=1.0/Math.sqrt(sideNormalX*sideNormalX+sideNormalY*sideNormalY);sideNormalX*=invLength;sideNormalY*=invLength;var frontNormalX=sideNormalX;var frontNormalY=sideNormalY;tX=frontNormalX;frontNormalX=frontNormalY;frontNormalY=-tX;var v11X=v11.x;var v11Y=v11.y;tX=v11X;tMat=poly1.m_R;v11X=tMat.col1.x*tX+tMat.col2.x*v11Y;v11Y=tMat.col1.y*tX+tMat.col2.y*v11Y;v11X+=poly1.m_position.x;v11Y+=poly1.m_position.y;var v12X=v12.x;var v12Y=v12.y;tX=v12X;tMat=poly1.m_R;v12X=tMat.col1.x*tX+tMat.col2.x*v12Y;v12Y=tMat.col1.y*tX+tMat.col2.y*v12Y;v12X+=poly1.m_position.x;v12Y+=poly1.m_position.y;var frontOffset=frontNormalX*v11X+frontNormalY*v11Y;var sideOffset1=-(sideNormalX*v11X+sideNormalY*v11Y);var sideOffset2=sideNormalX*v12X+sideNormalY*v12Y;var clipPoints1=[new ClipVertex(),new ClipVertex()];var clipPoints2=[new ClipVertex(),new ClipVertex()];var np=0;b2Collision.b2CollidePolyTempVec.Set(-sideNormalX,-sideNormalY);np=b2Collision.ClipSegmentToLine(clipPoints1,incidentEdge,b2Collision.b2CollidePolyTempVec,sideOffset1);if(np<2)
-return;b2Collision.b2CollidePolyTempVec.Set(sideNormalX,sideNormalY);np=b2Collision.ClipSegmentToLine(clipPoints2,clipPoints1,b2Collision.b2CollidePolyTempVec,sideOffset2);if(np<2)
-return;if(flip){manifold.normal.Set(-frontNormalX,-frontNormalY);}
-else{manifold.normal.Set(frontNormalX,frontNormalY);}
-var pointCount=0;for(var i=0;i<b2Settings.b2_maxManifoldPoints;++i)
-{var tVec=clipPoints2[i].v;var separation=(frontNormalX*tVec.x+frontNormalY*tVec.y)-frontOffset;if(separation<=0.0||conservative==true)
-{var cp=manifold.points[pointCount];cp.separation=separation;cp.position.SetV(clipPoints2[i].v);cp.id.Set(clipPoints2[i].id);cp.id.features.flip=flip;++pointCount;}}
-manifold.pointCount=pointCount;};b2Collision.b2CollideCircle=function(manifold,circle1,circle2,conservative)
-{manifold.pointCount=0;var dX=circle2.m_position.x-circle1.m_position.x;var dY=circle2.m_position.y-circle1.m_position.y;var distSqr=dX*dX+dY*dY;var radiusSum=circle1.m_radius+circle2.m_radius;if(distSqr>radiusSum*radiusSum&&conservative==false)
-{return;}
-var separation;if(distSqr<Number.MIN_VALUE)
-{separation=-radiusSum;manifold.normal.Set(0.0,1.0);}
-else
-{var dist=Math.sqrt(distSqr);separation=dist-radiusSum;var a=1.0/dist;manifold.normal.x=a*dX;manifold.normal.y=a*dY;}
-manifold.pointCount=1;var tPoint=manifold.points[0];tPoint.id.set_key(0);tPoint.separation=separation;tPoint.position.x=circle2.m_position.x-(circle2.m_radius*manifold.normal.x);tPoint.position.y=circle2.m_position.y-(circle2.m_radius*manifold.normal.y);};b2Collision.b2CollidePolyAndCircle=function(manifold,poly,circle,conservative)
-{manifold.pointCount=0;var tPoint;var dX;var dY;var xLocalX=circle.m_position.x-poly.m_position.x;var xLocalY=circle.m_position.y-poly.m_position.y;var tMat=poly.m_R;var tX=xLocalX*tMat.col1.x+xLocalY*tMat.col1.y;xLocalY=xLocalX*tMat.col2.x+xLocalY*tMat.col2.y;xLocalX=tX;var dist;var normalIndex=0;var separation=-Number.MAX_VALUE;var radius=circle.m_radius;for(var i=0;i<poly.m_vertexCount;++i)
-{var s=poly.m_normals[i].x*(xLocalX-poly.m_vertices[i].x)+poly.m_normals[i].y*(xLocalY-poly.m_vertices[i].y);if(s>radius)
-{return;}
-if(s>separation)
-{separation=s;normalIndex=i;}}
-if(separation<Number.MIN_VALUE)
-{manifold.pointCount=1;var tVec=poly.m_normals[normalIndex];manifold.normal.x=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;manifold.normal.y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tPoint=manifold.points[0];tPoint.id.features.incidentEdge=normalIndex;tPoint.id.features.incidentVertex=b2Collision.b2_nullFeature;tPoint.id.features.referenceFace=b2Collision.b2_nullFeature;tPoint.id.features.flip=0;tPoint.position.x=circle.m_position.x-radius*manifold.normal.x;tPoint.position.y=circle.m_position.y-radius*manifold.normal.y;tPoint.separation=separation-radius;return;}
-var vertIndex1=normalIndex;var vertIndex2=vertIndex1+1<poly.m_vertexCount?vertIndex1+1:0;var eX=poly.m_vertices[vertIndex2].x-poly.m_vertices[vertIndex1].x;var eY=poly.m_vertices[vertIndex2].y-poly.m_vertices[vertIndex1].y;var length=Math.sqrt(eX*eX+eY*eY);eX/=length;eY/=length;if(length<Number.MIN_VALUE)
-{dX=xLocalX-poly.m_vertices[vertIndex1].x;dY=xLocalY-poly.m_vertices[vertIndex1].y;dist=Math.sqrt(dX*dX+dY*dY);dX/=dist;dY/=dist;if(dist>radius)
-{return;}
-manifold.pointCount=1;manifold.normal.Set(tMat.col1.x*dX+tMat.col2.x*dY,tMat.col1.y*dX+tMat.col2.y*dY);tPoint=manifold.points[0];tPoint.id.features.incidentEdge=b2Collision.b2_nullFeature;tPoint.id.features.incidentVertex=vertIndex1;tPoint.id.features.referenceFace=b2Collision.b2_nullFeature;tPoint.id.features.flip=0;tPoint.position.x=circle.m_position.x-radius*manifold.normal.x;tPoint.position.y=circle.m_position.y-radius*manifold.normal.y;tPoint.separation=dist-radius;return;}
-var u=(xLocalX-poly.m_vertices[vertIndex1].x)*eX+(xLocalY-poly.m_vertices[vertIndex1].y)*eY;tPoint=manifold.points[0];tPoint.id.features.incidentEdge=b2Collision.b2_nullFeature;tPoint.id.features.incidentVertex=b2Collision.b2_nullFeature;tPoint.id.features.referenceFace=b2Collision.b2_nullFeature;tPoint.id.features.flip=0;var pX,pY;if(u<=0.0)
-{pX=poly.m_vertices[vertIndex1].x;pY=poly.m_vertices[vertIndex1].y;tPoint.id.features.incidentVertex=vertIndex1;}
-else if(u>=length)
-{pX=poly.m_vertices[vertIndex2].x;pY=poly.m_vertices[vertIndex2].y;tPoint.id.features.incidentVertex=vertIndex2;}
-else
-{pX=eX*u+poly.m_vertices[vertIndex1].x;pY=eY*u+poly.m_vertices[vertIndex1].y;tPoint.id.features.incidentEdge=vertIndex1;}
-dX=xLocalX-pX;dY=xLocalY-pY;dist=Math.sqrt(dX*dX+dY*dY);dX/=dist;dY/=dist;if(dist>radius)
-{return;}
-manifold.pointCount=1;manifold.normal.Set(tMat.col1.x*dX+tMat.col2.x*dY,tMat.col1.y*dX+tMat.col2.y*dY);tPoint.position.x=circle.m_position.x-radius*manifold.normal.x;tPoint.position.y=circle.m_position.y-radius*manifold.normal.y;tPoint.separation=dist-radius;};b2Collision.b2TestOverlap=function(a,b)
-{var t1=b.minVertex;var t2=a.maxVertex;var d1X=t1.x-t2.x;var d1Y=t1.y-t2.y;t1=a.minVertex;t2=b.maxVertex;var d2X=t1.x-t2.x;var d2Y=t1.y-t2.y;if(d1X>0.0||d1Y>0.0)
-return false;if(d2X>0.0||d2Y>0.0)
-return false;return true;};
-var Features=Class.create();Features.prototype={set_referenceFace:function(value){this._referenceFace=value;this._m_id._key=(this._m_id._key&0xffffff00)|(this._referenceFace&0x000000ff)},get_referenceFace:function(){return this._referenceFace;},_referenceFace:0,set_incidentEdge:function(value){this._incidentEdge=value;this._m_id._key=(this._m_id._key&0xffff00ff)|((this._incidentEdge<<8)&0x0000ff00)},get_incidentEdge:function(){return this._incidentEdge;},_incidentEdge:0,set_incidentVertex:function(value){this._incidentVertex=value;this._m_id._key=(this._m_id._key&0xff00ffff)|((this._incidentVertex<<16)&0x00ff0000)},get_incidentVertex:function(){return this._incidentVertex;},_incidentVertex:0,set_flip:function(value){this._flip=value;this._m_id._key=(this._m_id._key&0x00ffffff)|((this._flip<<24)&0xff000000)},get_flip:function(){return this._flip;},_flip:0,_m_id:null,initialize:function(){}};
-var b2ContactID=Class.create();b2ContactID.prototype={initialize:function(){this.features=new Features();this.features._m_id=this;},Set:function(id){this.set_key(id._key);},Copy:function(){var id=new b2ContactID();id.set_key(this._key);return id;},get_key:function(){return this._key;},set_key:function(value){this._key=value;this.features._referenceFace=this._key&0x000000ff;this.features._incidentEdge=((this._key&0x0000ff00)>>8)&0x000000ff;this.features._incidentVertex=((this._key&0x00ff0000)>>16)&0x000000ff;this.features._flip=((this._key&0xff000000)>>24)&0x000000ff;},features:new Features(),_key:0};
-var b2ContactPoint=Class.create();b2ContactPoint.prototype={position:new b2Vec2(),separation:null,normalImpulse:null,tangentImpulse:null,id:new b2ContactID(),initialize:function(){this.position=new b2Vec2();this.id=new b2ContactID();}};var b2Distance=Class.create();b2Distance.prototype={initialize:function(){}};b2Distance.ProcessTwo=function(p1Out,p2Out,p1s,p2s,points)
-{var rX=-points[1].x;var rY=-points[1].y;var dX=points[0].x-points[1].x;var dY=points[0].y-points[1].y;var length=Math.sqrt(dX*dX+dY*dY);dX/=length;dY/=length;var lambda=rX*dX+rY*dY;if(lambda<=0.0||length<Number.MIN_VALUE)
-{p1Out.SetV(p1s[1]);p2Out.SetV(p2s[1]);p1s[0].SetV(p1s[1]);p2s[0].SetV(p2s[1]);points[0].SetV(points[1]);return 1;}
-lambda/=length;p1Out.x=p1s[1].x+lambda*(p1s[0].x-p1s[1].x);p1Out.y=p1s[1].y+lambda*(p1s[0].y-p1s[1].y);p2Out.x=p2s[1].x+lambda*(p2s[0].x-p2s[1].x);p2Out.y=p2s[1].y+lambda*(p2s[0].y-p2s[1].y);return 2;};b2Distance.ProcessThree=function(p1Out,p2Out,p1s,p2s,points)
-{var aX=points[0].x;var aY=points[0].y;var bX=points[1].x;var bY=points[1].y;var cX=points[2].x;var cY=points[2].y;var abX=bX-aX;var abY=bY-aY;var acX=cX-aX;var acY=cY-aY;var bcX=cX-bX;var bcY=cY-bY;var sn=-(aX*abX+aY*abY);var sd=(bX*abX+bY*abY);var tn=-(aX*acX+aY*acY);var td=(cX*acX+cY*acY);var un=-(bX*bcX+bY*bcY);var ud=(cX*bcX+cY*bcY);if(td<=0.0&&ud<=0.0)
-{p1Out.SetV(p1s[2]);p2Out.SetV(p2s[2]);p1s[0].SetV(p1s[2]);p2s[0].SetV(p2s[2]);points[0].SetV(points[2]);return 1;}
-var n=abX*acY-abY*acX;var vc=n*(aX*bY-aY*bX);var va=n*(bX*cY-bY*cX);if(va<=0.0&&un>=0.0&&ud>=0.0)
-{var lambda=un/(un+ud);p1Out.x=p1s[1].x+lambda*(p1s[2].x-p1s[1].x);p1Out.y=p1s[1].y+lambda*(p1s[2].y-p1s[1].y);p2Out.x=p2s[1].x+lambda*(p2s[2].x-p2s[1].x);p2Out.y=p2s[1].y+lambda*(p2s[2].y-p2s[1].y);p1s[0].SetV(p1s[2]);p2s[0].SetV(p2s[2]);points[0].SetV(points[2]);return 2;}
-var vb=n*(cX*aY-cY*aX);if(vb<=0.0&&tn>=0.0&&td>=0.0)
-{var lambda=tn/(tn+td);p1Out.x=p1s[0].x+lambda*(p1s[2].x-p1s[0].x);p1Out.y=p1s[0].y+lambda*(p1s[2].y-p1s[0].y);p2Out.x=p2s[0].x+lambda*(p2s[2].x-p2s[0].x);p2Out.y=p2s[0].y+lambda*(p2s[2].y-p2s[0].y);p1s[1].SetV(p1s[2]);p2s[1].SetV(p2s[2]);points[1].SetV(points[2]);return 2;}
-var denom=va+vb+vc;denom=1.0/denom;var u=va*denom;var v=vb*denom;var w=1.0-u-v;p1Out.x=u*p1s[0].x+v*p1s[1].x+w*p1s[2].x;p1Out.y=u*p1s[0].y+v*p1s[1].y+w*p1s[2].y;p2Out.x=u*p2s[0].x+v*p2s[1].x+w*p2s[2].x;p2Out.y=u*p2s[0].y+v*p2s[1].y+w*p2s[2].y;return 3;};b2Distance.InPoinsts=function(w,points,pointCount)
-{for(var i=0;i<pointCount;++i)
-{if(w.x==points[i].x&&w.y==points[i].y)
-{return true;}}
-return false;};b2Distance.Distance=function(p1Out,p2Out,shape1,shape2)
-{var p1s=new Array(3);var p2s=new Array(3);var points=new Array(3);var pointCount=0;p1Out.SetV(shape1.m_position);p2Out.SetV(shape2.m_position);var vSqr=0.0;var maxIterations=20;for(var iter=0;iter<maxIterations;++iter)
-{var vX=p2Out.x-p1Out.x;var vY=p2Out.y-p1Out.y;var w1=shape1.Support(vX,vY);var w2=shape2.Support(-vX,-vY);vSqr=(vX*vX+vY*vY);var wX=w2.x-w1.x;var wY=w2.y-w1.y;var vw=(vX*wX+vY*wY);if(vSqr-b2Dot(vX*wX+vY*wY)<=0.01*vSqr)
-{if(pointCount==0)
-{p1Out.SetV(w1);p2Out.SetV(w2);}
-b2Distance.g_GJK_Iterations=iter;return Math.sqrt(vSqr);}
-switch(pointCount)
-{case 0:p1s[0].SetV(w1);p2s[0].SetV(w2);points[0]=w;p1Out.SetV(p1s[0]);p2Out.SetV(p2s[0]);++pointCount;break;case 1:p1s[1].SetV(w1);p2s[1].SetV(w2);points[1].x=wX;points[1].y=wY;pointCount=b2Distance.ProcessTwo(p1Out,p2Out,p1s,p2s,points);break;case 2:p1s[2].SetV(w1);p2s[2].SetV(w2);points[2].x=wX;points[2].y=wY;pointCount=b2Distance.ProcessThree(p1Out,p2Out,p1s,p2s,points);break;}
-if(pointCount==3)
-{b2Distance.g_GJK_Iterations=iter;return 0.0;}
-var maxSqr=-Number.MAX_VALUE;for(var i=0;i<pointCount;++i)
-{maxSqr=b2Math.b2Max(maxSqr,(points[i].x*points[i].x+points[i].y*points[i].y));}
-if(pointCount==3||vSqr<=100.0*Number.MIN_VALUE*maxSqr)
-{b2Distance.g_GJK_Iterations=iter;return Math.sqrt(vSqr);}}
-b2Distance.g_GJK_Iterations=maxIterations;return Math.sqrt(vSqr);};b2Distance.g_GJK_Iterations=0;
-var b2Manifold=Class.create();b2Manifold.prototype={initialize:function(){this.points=new Array(b2Settings.b2_maxManifoldPoints);for(var i=0;i<b2Settings.b2_maxManifoldPoints;i++){this.points[i]=new b2ContactPoint();}
-this.normal=new b2Vec2();},points:null,normal:null,pointCount:0};
-var b2OBB=Class.create();b2OBB.prototype={R:new b2Mat22(),center:new b2Vec2(),extents:new b2Vec2(),initialize:function(){this.R=new b2Mat22();this.center=new b2Vec2();this.extents=new b2Vec2();}};
-var b2Proxy=Class.create();b2Proxy.prototype={GetNext:function(){return this.lowerBounds[0];},SetNext:function(next){this.lowerBounds[0]=next;},IsValid:function(){return this.overlapCount!=b2BroadPhase.b2_invalid;},lowerBounds:[(0),(0)],upperBounds:[(0),(0)],overlapCount:0,timeStamp:0,userData:null,initialize:function(){this.lowerBounds=[(0),(0)];this.upperBounds=[(0),(0)];}}
-
-var ClipVertex=Class.create();ClipVertex.prototype={v:new b2Vec2(),id:new b2ContactID(),initialize:function(){this.v=new b2Vec2();this.id=new b2ContactID();}};var b2Shape=Class.create();b2Shape.prototype={TestPoint:function(p){return false},GetUserData:function(){return this.m_userData;},GetType:function(){return this.m_type;},GetBody:function(){return this.m_body;},GetPosition:function(){return this.m_position;},GetRotationMatrix:function(){return this.m_R;},ResetProxy:function(broadPhase){},GetNext:function(){return this.m_next;},initialize:function(def,body){this.m_R=new b2Mat22();this.m_position=new b2Vec2();this.m_userData=def.userData;this.m_friction=def.friction;this.m_restitution=def.restitution;this.m_body=body;this.m_proxyId=b2Pair.b2_nullProxy;this.m_maxRadius=0.0;this.m_categoryBits=def.categoryBits;this.m_maskBits=def.maskBits;this.m_groupIndex=def.groupIndex;},DestroyProxy:function()
-{if(this.m_proxyId!=b2Pair.b2_nullProxy)
-{this.m_body.m_world.m_broadPhase.DestroyProxy(this.m_proxyId);this.m_proxyId=b2Pair.b2_nullProxy;}},Synchronize:function(position1,R1,position2,R2){},QuickSync:function(position,R){},Support:function(dX,dY,out){},GetMaxRadius:function(){return this.m_maxRadius;},m_next:null,m_R:new b2Mat22(),m_position:new b2Vec2(),m_type:0,m_userData:null,m_body:null,m_friction:null,m_restitution:null,m_maxRadius:null,m_proxyId:0,m_categoryBits:0,m_maskBits:0,m_groupIndex:0};b2Shape.Create=function(def,body,center){switch(def.type)
-{case b2Shape.e_circleShape:{return new b2CircleShape(def,body,center);}
-case b2Shape.e_boxShape:case b2Shape.e_polyShape:{return new b2PolyShape(def,body,center);}}
-return null;};b2Shape.Destroy=function(shape)
-{if(shape.m_proxyId!=b2Pair.b2_nullProxy)
-shape.m_body.m_world.m_broadPhase.DestroyProxy(shape.m_proxyId);};b2Shape.e_unknownShape=-1;b2Shape.e_circleShape=0;b2Shape.e_boxShape=1;b2Shape.e_polyShape=2;b2Shape.e_meshShape=3;b2Shape.e_shapeTypeCount=4;b2Shape.PolyMass=function(massData,vs,count,rho)
-{var center=new b2Vec2();center.SetZero();var area=0.0;var I=0.0;var pRef=new b2Vec2(0.0,0.0);var inv3=1.0/3.0;for(var i=0;i<count;++i)
-{var p1=pRef;var p2=vs[i];var p3=i+1<count?vs[i+1]:vs[0];var e1=b2Math.SubtractVV(p2,p1);var e2=b2Math.SubtractVV(p3,p1);var D=b2Math.b2CrossVV(e1,e2);var triangleArea=0.5*D;area+=triangleArea;var tVec=new b2Vec2();tVec.SetV(p1);tVec.Add(p2);tVec.Add(p3);tVec.Multiply(inv3*triangleArea);center.Add(tVec);var px=p1.x;var py=p1.y;var ex1=e1.x;var ey1=e1.y;var ex2=e2.x;var ey2=e2.y;var intx2=inv3*(0.25*(ex1*ex1+ex2*ex1+ex2*ex2)+(px*ex1+px*ex2))+0.5*px*px;var inty2=inv3*(0.25*(ey1*ey1+ey2*ey1+ey2*ey2)+(py*ey1+py*ey2))+0.5*py*py;I+=D*(intx2+inty2);}
-massData.mass=rho*area;center.Multiply(1.0/area);massData.center=center;I=rho*(I-area*b2Math.b2Dot(center,center));massData.I=I;};b2Shape.PolyCentroid=function(vs,count,out)
-{var cX=0.0;var cY=0.0;var area=0.0;var pRefX=0.0;var pRefY=0.0;var inv3=1.0/3.0;for(var i=0;i<count;++i)
-{var p1X=pRefX;var p1Y=pRefY;var p2X=vs[i].x;var p2Y=vs[i].y;var p3X=i+1<count?vs[i+1].x:vs[0].x;var p3Y=i+1<count?vs[i+1].y:vs[0].y;var e1X=p2X-p1X;var e1Y=p2Y-p1Y;var e2X=p3X-p1X;var e2Y=p3Y-p1Y;var D=(e1X*e2Y-e1Y*e2X);var triangleArea=0.5*D;area+=triangleArea;cX+=triangleArea*inv3*(p1X+p2X+p3X);cY+=triangleArea*inv3*(p1Y+p2Y+p3Y);}
-cX*=1.0/area;cY*=1.0/area;out.Set(cX,cY);};
-var b2ShapeDef=Class.create();b2ShapeDef.prototype={initialize:function()
-{this.type=b2Shape.e_unknownShape;this.userData=null;this.localPosition=new b2Vec2(0.0,0.0);this.localRotation=0.0;this.friction=0.2;this.restitution=0.0;this.density=0.0;this.categoryBits=0x0001;this.maskBits=0xFFFF;this.groupIndex=0;},ComputeMass:function(massData)
-{massData.center=new b2Vec2(0.0,0.0)
-if(this.density==0.0)
-{massData.mass=0.0;massData.center.Set(0.0,0.0);massData.I=0.0;};switch(this.type)
-{case b2Shape.e_circleShape:{var circle=this;massData.mass=this.density*b2Settings.b2_pi*circle.radius*circle.radius;massData.center.Set(0.0,0.0);massData.I=0.5*(massData.mass)*circle.radius*circle.radius;}
-break;case b2Shape.e_boxShape:{var box=this;massData.mass=4.0*this.density*box.extents.x*box.extents.y;massData.center.Set(0.0,0.0);massData.I=massData.mass/3.0*b2Math.b2Dot(box.extents,box.extents);}
-break;case b2Shape.e_polyShape:{var poly=this;b2Shape.PolyMass(massData,poly.vertices,poly.vertexCount,this.density);}
-break;default:massData.mass=0.0;massData.center.Set(0.0,0.0);massData.I=0.0;break;}},type:0,userData:null,localPosition:null,localRotation:null,friction:null,restitution:null,density:null,categoryBits:0,maskBits:0,groupIndex:0};
-var b2BoxDef=Class.create();Object.extend(b2BoxDef.prototype,b2ShapeDef.prototype);Object.extend(b2BoxDef.prototype,{initialize:function()
-{this.type=b2Shape.e_unknownShape;this.userData=null;this.localPosition=new b2Vec2(0.0,0.0);this.localRotation=0.0;this.friction=0.2;this.restitution=0.0;this.density=0.0;this.categoryBits=0x0001;this.maskBits=0xFFFF;this.groupIndex=0;this.type=b2Shape.e_boxShape;this.extents=new b2Vec2(1.0,1.0);},extents:null});
-var b2CircleDef=Class.create();Object.extend(b2CircleDef.prototype,b2ShapeDef.prototype);Object.extend(b2CircleDef.prototype,{initialize:function()
-{this.type=b2Shape.e_unknownShape;this.userData=null;this.localPosition=new b2Vec2(0.0,0.0);this.localRotation=0.0;this.friction=0.2;this.restitution=0.0;this.density=0.0;this.categoryBits=0x0001;this.maskBits=0xFFFF;this.groupIndex=0;this.type=b2Shape.e_circleShape;this.radius=1.0;},radius:null});var b2CircleShape=Class.create();Object.extend(b2CircleShape.prototype,b2Shape.prototype);Object.extend(b2CircleShape.prototype,{TestPoint:function(p){var d=new b2Vec2();d.SetV(p);d.Subtract(this.m_position);return b2Math.b2Dot(d,d)<=this.m_radius*this.m_radius;},initialize:function(def,body,localCenter){this.m_R=new b2Mat22();this.m_position=new b2Vec2();this.m_userData=def.userData;this.m_friction=def.friction;this.m_restitution=def.restitution;this.m_body=body;this.m_proxyId=b2Pair.b2_nullProxy;this.m_maxRadius=0.0;this.m_categoryBits=def.categoryBits;this.m_maskBits=def.maskBits;this.m_groupIndex=def.groupIndex;this.m_localPosition=new b2Vec2();var circle=def;this.m_localPosition.Set(def.localPosition.x-localCenter.x,def.localPosition.y-localCenter.y);this.m_type=b2Shape.e_circleShape;this.m_radius=circle.radius;this.m_R.SetM(this.m_body.m_R);var rX=this.m_R.col1.x*this.m_localPosition.x+this.m_R.col2.x*this.m_localPosition.y;var rY=this.m_R.col1.y*this.m_localPosition.x+this.m_R.col2.y*this.m_localPosition.y;this.m_position.x=this.m_body.m_position.x+rX;this.m_position.y=this.m_body.m_position.y+rY;this.m_maxRadius=Math.sqrt(rX*rX+rY*rY)+this.m_radius;var aabb=new b2AABB();aabb.minVertex.Set(this.m_position.x-this.m_radius,this.m_position.y-this.m_radius);aabb.maxVertex.Set(this.m_position.x+this.m_radius,this.m_position.y+this.m_radius);var broadPhase=this.m_body.m_world.m_broadPhase;if(broadPhase.InRange(aabb))
-{this.m_proxyId=broadPhase.CreateProxy(aabb,this);}
-else
-{this.m_proxyId=b2Pair.b2_nullProxy;}
-if(this.m_proxyId==b2Pair.b2_nullProxy)
-{this.m_body.Freeze();}},Synchronize:function(position1,R1,position2,R2){this.m_R.SetM(R2);this.m_position.x=(R2.col1.x*this.m_localPosition.x+R2.col2.x*this.m_localPosition.y)+position2.x;this.m_position.y=(R2.col1.y*this.m_localPosition.x+R2.col2.y*this.m_localPosition.y)+position2.y;if(this.m_proxyId==b2Pair.b2_nullProxy)
-{return;}
-var p1X=position1.x+(R1.col1.x*this.m_localPosition.x+R1.col2.x*this.m_localPosition.y);var p1Y=position1.y+(R1.col1.y*this.m_localPosition.x+R1.col2.y*this.m_localPosition.y);var lowerX=Math.min(p1X,this.m_position.x);var lowerY=Math.min(p1Y,this.m_position.y);var upperX=Math.max(p1X,this.m_position.x);var upperY=Math.max(p1Y,this.m_position.y);var aabb=new b2AABB();aabb.minVertex.Set(lowerX-this.m_radius,lowerY-this.m_radius);aabb.maxVertex.Set(upperX+this.m_radius,upperY+this.m_radius);var broadPhase=this.m_body.m_world.m_broadPhase;if(broadPhase.InRange(aabb))
-{broadPhase.MoveProxy(this.m_proxyId,aabb);}
-else
-{this.m_body.Freeze();}},QuickSync:function(position,R){this.m_R.SetM(R);this.m_position.x=(R.col1.x*this.m_localPosition.x+R.col2.x*this.m_localPosition.y)+position.x;this.m_position.y=(R.col1.y*this.m_localPosition.x+R.col2.y*this.m_localPosition.y)+position.y;},ResetProxy:function(broadPhase)
-{if(this.m_proxyId==b2Pair.b2_nullProxy)
-{return;}
-var proxy=broadPhase.GetProxy(this.m_proxyId);broadPhase.DestroyProxy(this.m_proxyId);proxy=null;var aabb=new b2AABB();aabb.minVertex.Set(this.m_position.x-this.m_radius,this.m_position.y-this.m_radius);aabb.maxVertex.Set(this.m_position.x+this.m_radius,this.m_position.y+this.m_radius);if(broadPhase.InRange(aabb))
-{this.m_proxyId=broadPhase.CreateProxy(aabb,this);}
-else
-{this.m_proxyId=b2Pair.b2_nullProxy;}
-if(this.m_proxyId==b2Pair.b2_nullProxy)
-{this.m_body.Freeze();}},Support:function(dX,dY,out)
-{var len=Math.sqrt(dX*dX+dY*dY);dX/=len;dY/=len;out.Set(this.m_position.x+this.m_radius*dX,this.m_position.y+this.m_radius*dY);},m_localPosition:new b2Vec2(),m_radius:null});
-var b2MassData=Class.create();b2MassData.prototype={mass:0.0,center:new b2Vec2(0,0),I:0.0,initialize:function(){this.center=new b2Vec2(0,0);}}
-
-var b2PolyDef=Class.create();Object.extend(b2PolyDef.prototype,b2ShapeDef.prototype);Object.extend(b2PolyDef.prototype,{initialize:function()
-{this.type=b2Shape.e_unknownShape;this.userData=null;this.localPosition=new b2Vec2(0.0,0.0);this.localRotation=0.0;this.friction=0.2;this.restitution=0.0;this.density=0.0;this.categoryBits=0x0001;this.maskBits=0xFFFF;this.groupIndex=0;this.vertices=new Array(b2Settings.b2_maxPolyVertices);this.type=b2Shape.e_polyShape;this.vertexCount=0;for(var i=0;i<b2Settings.b2_maxPolyVertices;i++){this.vertices[i]=new b2Vec2();}},vertices:new Array(b2Settings.b2_maxPolyVertices),vertexCount:0});var b2PolyShape=Class.create();Object.extend(b2PolyShape.prototype,b2Shape.prototype);Object.extend(b2PolyShape.prototype,{TestPoint:function(p){var pLocal=new b2Vec2();pLocal.SetV(p);pLocal.Subtract(this.m_position);pLocal.MulTM(this.m_R);for(var i=0;i<this.m_vertexCount;++i)
-{var tVec=new b2Vec2();tVec.SetV(pLocal);tVec.Subtract(this.m_vertices[i]);var dot=b2Math.b2Dot(this.m_normals[i],tVec);if(dot>0.0)
-{return false;}}
-return true;},initialize:function(def,body,newOrigin){this.m_R=new b2Mat22();this.m_position=new b2Vec2();this.m_userData=def.userData;this.m_friction=def.friction;this.m_restitution=def.restitution;this.m_body=body;this.m_proxyId=b2Pair.b2_nullProxy;this.m_maxRadius=0.0;this.m_categoryBits=def.categoryBits;this.m_maskBits=def.maskBits;this.m_groupIndex=def.groupIndex;this.syncAABB=new b2AABB();this.syncMat=new b2Mat22();this.m_localCentroid=new b2Vec2();this.m_localOBB=new b2OBB();var i=0;var hX;var hY;var tVec;var aabb=new b2AABB();this.m_vertices=new Array(b2Settings.b2_maxPolyVertices);this.m_coreVertices=new Array(b2Settings.b2_maxPolyVertices);this.m_normals=new Array(b2Settings.b2_maxPolyVertices);this.m_type=b2Shape.e_polyShape;var localR=new b2Mat22(def.localRotation);if(def.type==b2Shape.e_boxShape)
-{this.m_localCentroid.x=def.localPosition.x-newOrigin.x;this.m_localCentroid.y=def.localPosition.y-newOrigin.y;var box=def;this.m_vertexCount=4;hX=box.extents.x;hY=box.extents.y;var hcX=Math.max(0.0,hX-2.0*b2Settings.b2_linearSlop);var hcY=Math.max(0.0,hY-2.0*b2Settings.b2_linearSlop);tVec=this.m_vertices[0]=new b2Vec2();tVec.x=localR.col1.x*hX+localR.col2.x*hY;tVec.y=localR.col1.y*hX+localR.col2.y*hY;tVec=this.m_vertices[1]=new b2Vec2();tVec.x=localR.col1.x*-hX+localR.col2.x*hY;tVec.y=localR.col1.y*-hX+localR.col2.y*hY;tVec=this.m_vertices[2]=new b2Vec2();tVec.x=localR.col1.x*-hX+localR.col2.x*-hY;tVec.y=localR.col1.y*-hX+localR.col2.y*-hY;tVec=this.m_vertices[3]=new b2Vec2();tVec.x=localR.col1.x*hX+localR.col2.x*-hY;tVec.y=localR.col1.y*hX+localR.col2.y*-hY;tVec=this.m_coreVertices[0]=new b2Vec2();tVec.x=localR.col1.x*hcX+localR.col2.x*hcY;tVec.y=localR.col1.y*hcX+localR.col2.y*hcY;tVec=this.m_coreVertices[1]=new b2Vec2();tVec.x=localR.col1.x*-hcX+localR.col2.x*hcY;tVec.y=localR.col1.y*-hcX+localR.col2.y*hcY;tVec=this.m_coreVertices[2]=new b2Vec2();tVec.x=localR.col1.x*-hcX+localR.col2.x*-hcY;tVec.y=localR.col1.y*-hcX+localR.col2.y*-hcY;tVec=this.m_coreVertices[3]=new b2Vec2();tVec.x=localR.col1.x*hcX+localR.col2.x*-hcY;tVec.y=localR.col1.y*hcX+localR.col2.y*-hcY;}
-else
-{var poly=def;this.m_vertexCount=poly.vertexCount;b2Shape.PolyCentroid(poly.vertices,poly.vertexCount,b2PolyShape.tempVec);var centroidX=b2PolyShape.tempVec.x;var centroidY=b2PolyShape.tempVec.y;this.m_localCentroid.x=def.localPosition.x+(localR.col1.x*centroidX+localR.col2.x*centroidY)-newOrigin.x;this.m_localCentroid.y=def.localPosition.y+(localR.col1.y*centroidX+localR.col2.y*centroidY)-newOrigin.y;for(i=0;i<this.m_vertexCount;++i)
-{this.m_vertices[i]=new b2Vec2();this.m_coreVertices[i]=new b2Vec2();hX=poly.vertices[i].x-centroidX;hY=poly.vertices[i].y-centroidY;this.m_vertices[i].x=localR.col1.x*hX+localR.col2.x*hY;this.m_vertices[i].y=localR.col1.y*hX+localR.col2.y*hY;var uX=this.m_vertices[i].x;var uY=this.m_vertices[i].y;var length=Math.sqrt(uX*uX+uY*uY);if(length>Number.MIN_VALUE)
-{uX*=1.0/length;uY*=1.0/length;}
-this.m_coreVertices[i].x=this.m_vertices[i].x-2.0*b2Settings.b2_linearSlop*uX;this.m_coreVertices[i].y=this.m_vertices[i].y-2.0*b2Settings.b2_linearSlop*uY;}}
-var minVertexX=Number.MAX_VALUE;var minVertexY=Number.MAX_VALUE;var maxVertexX=-Number.MAX_VALUE;var maxVertexY=-Number.MAX_VALUE;this.m_maxRadius=0.0;for(i=0;i<this.m_vertexCount;++i)
-{var v=this.m_vertices[i];minVertexX=Math.min(minVertexX,v.x);minVertexY=Math.min(minVertexY,v.y);maxVertexX=Math.max(maxVertexX,v.x);maxVertexY=Math.max(maxVertexY,v.y);this.m_maxRadius=Math.max(this.m_maxRadius,v.Length());}
-this.m_localOBB.R.SetIdentity();this.m_localOBB.center.Set((minVertexX+maxVertexX)*0.5,(minVertexY+maxVertexY)*0.5);this.m_localOBB.extents.Set((maxVertexX-minVertexX)*0.5,(maxVertexY-minVertexY)*0.5);var i1=0;var i2=0;for(i=0;i<this.m_vertexCount;++i)
-{this.m_normals[i]=new b2Vec2();i1=i;i2=i+1<this.m_vertexCount?i+1:0;this.m_normals[i].x=this.m_vertices[i2].y-this.m_vertices[i1].y;this.m_normals[i].y=-(this.m_vertices[i2].x-this.m_vertices[i1].x);this.m_normals[i].Normalize();}
-for(i=0;i<this.m_vertexCount;++i)
-{i1=i;i2=i+1<this.m_vertexCount?i+1:0;}
-this.m_R.SetM(this.m_body.m_R);this.m_position.x=this.m_body.m_position.x+(this.m_R.col1.x*this.m_localCentroid.x+this.m_R.col2.x*this.m_localCentroid.y);this.m_position.y=this.m_body.m_position.y+(this.m_R.col1.y*this.m_localCentroid.x+this.m_R.col2.y*this.m_localCentroid.y);b2PolyShape.tAbsR.col1.x=this.m_R.col1.x*this.m_localOBB.R.col1.x+this.m_R.col2.x*this.m_localOBB.R.col1.y;b2PolyShape.tAbsR.col1.y=this.m_R.col1.y*this.m_localOBB.R.col1.x+this.m_R.col2.y*this.m_localOBB.R.col1.y;b2PolyShape.tAbsR.col2.x=this.m_R.col1.x*this.m_localOBB.R.col2.x+this.m_R.col2.x*this.m_localOBB.R.col2.y;b2PolyShape.tAbsR.col2.y=this.m_R.col1.y*this.m_localOBB.R.col2.x+this.m_R.col2.y*this.m_localOBB.R.col2.y;b2PolyShape.tAbsR.Abs()
-hX=b2PolyShape.tAbsR.col1.x*this.m_localOBB.extents.x+b2PolyShape.tAbsR.col2.x*this.m_localOBB.extents.y;hY=b2PolyShape.tAbsR.col1.y*this.m_localOBB.extents.x+b2PolyShape.tAbsR.col2.y*this.m_localOBB.extents.y;var positionX=this.m_position.x+(this.m_R.col1.x*this.m_localOBB.center.x+this.m_R.col2.x*this.m_localOBB.center.y);var positionY=this.m_position.y+(this.m_R.col1.y*this.m_localOBB.center.x+this.m_R.col2.y*this.m_localOBB.center.y);aabb.minVertex.x=positionX-hX;aabb.minVertex.y=positionY-hY;aabb.maxVertex.x=positionX+hX;aabb.maxVertex.y=positionY+hY;var broadPhase=this.m_body.m_world.m_broadPhase;if(broadPhase.InRange(aabb))
-{this.m_proxyId=broadPhase.CreateProxy(aabb,this);}
-else
-{this.m_proxyId=b2Pair.b2_nullProxy;}
-if(this.m_proxyId==b2Pair.b2_nullProxy)
-{this.m_body.Freeze();}},syncAABB:new b2AABB(),syncMat:new b2Mat22(),Synchronize:function(position1,R1,position2,R2){this.m_R.SetM(R2);this.m_position.x=this.m_body.m_position.x+(R2.col1.x*this.m_localCentroid.x+R2.col2.x*this.m_localCentroid.y);this.m_position.y=this.m_body.m_position.y+(R2.col1.y*this.m_localCentroid.x+R2.col2.y*this.m_localCentroid.y);if(this.m_proxyId==b2Pair.b2_nullProxy)
-{return;}
-var hX;var hY;var v1=R1.col1;var v2=R1.col2;var v3=this.m_localOBB.R.col1;var v4=this.m_localOBB.R.col2;this.syncMat.col1.x=v1.x*v3.x+v2.x*v3.y;this.syncMat.col1.y=v1.y*v3.x+v2.y*v3.y;this.syncMat.col2.x=v1.x*v4.x+v2.x*v4.y;this.syncMat.col2.y=v1.y*v4.x+v2.y*v4.y;this.syncMat.Abs();hX=this.m_localCentroid.x+this.m_localOBB.center.x;hY=this.m_localCentroid.y+this.m_localOBB.center.y;var centerX=position1.x+(R1.col1.x*hX+R1.col2.x*hY);var centerY=position1.y+(R1.col1.y*hX+R1.col2.y*hY);hX=this.syncMat.col1.x*this.m_localOBB.extents.x+this.syncMat.col2.x*this.m_localOBB.extents.y;hY=this.syncMat.col1.y*this.m_localOBB.extents.x+this.syncMat.col2.y*this.m_localOBB.extents.y;this.syncAABB.minVertex.x=centerX-hX;this.syncAABB.minVertex.y=centerY-hY;this.syncAABB.maxVertex.x=centerX+hX;this.syncAABB.maxVertex.y=centerY+hY;v1=R2.col1;v2=R2.col2;v3=this.m_localOBB.R.col1;v4=this.m_localOBB.R.col2;this.syncMat.col1.x=v1.x*v3.x+v2.x*v3.y;this.syncMat.col1.y=v1.y*v3.x+v2.y*v3.y;this.syncMat.col2.x=v1.x*v4.x+v2.x*v4.y;this.syncMat.col2.y=v1.y*v4.x+v2.y*v4.y;this.syncMat.Abs();hX=this.m_localCentroid.x+this.m_localOBB.center.x;hY=this.m_localCentroid.y+this.m_localOBB.center.y;centerX=position2.x+(R2.col1.x*hX+R2.col2.x*hY);centerY=position2.y+(R2.col1.y*hX+R2.col2.y*hY);hX=this.syncMat.col1.x*this.m_localOBB.extents.x+this.syncMat.col2.x*this.m_localOBB.extents.y;hY=this.syncMat.col1.y*this.m_localOBB.extents.x+this.syncMat.col2.y*this.m_localOBB.extents.y;this.syncAABB.minVertex.x=Math.min(this.syncAABB.minVertex.x,centerX-hX);this.syncAABB.minVertex.y=Math.min(this.syncAABB.minVertex.y,centerY-hY);this.syncAABB.maxVertex.x=Math.max(this.syncAABB.maxVertex.x,centerX+hX);this.syncAABB.maxVertex.y=Math.max(this.syncAABB.maxVertex.y,centerY+hY);var broadPhase=this.m_body.m_world.m_broadPhase;if(broadPhase.InRange(this.syncAABB))
-{broadPhase.MoveProxy(this.m_proxyId,this.syncAABB);}
-else
-{this.m_body.Freeze();}},QuickSync:function(position,R){this.m_R.SetM(R);this.m_position.x=position.x+(R.col1.x*this.m_localCentroid.x+R.col2.x*this.m_localCentroid.y);this.m_position.y=position.y+(R.col1.y*this.m_localCentroid.x+R.col2.y*this.m_localCentroid.y);},ResetProxy:function(broadPhase){if(this.m_proxyId==b2Pair.b2_nullProxy)
-{return;}
-var proxy=broadPhase.GetProxy(this.m_proxyId);broadPhase.DestroyProxy(this.m_proxyId);proxy=null;var R=b2Math.b2MulMM(this.m_R,this.m_localOBB.R);var absR=b2Math.b2AbsM(R);var h=b2Math.b2MulMV(absR,this.m_localOBB.extents);var position=b2Math.b2MulMV(this.m_R,this.m_localOBB.center);position.Add(this.m_position);var aabb=new b2AABB();aabb.minVertex.SetV(position);aabb.minVertex.Subtract(h);aabb.maxVertex.SetV(position);aabb.maxVertex.Add(h);if(broadPhase.InRange(aabb))
-{this.m_proxyId=broadPhase.CreateProxy(aabb,this);}
-else
-{this.m_proxyId=b2Pair.b2_nullProxy;}
-if(this.m_proxyId==b2Pair.b2_nullProxy)
-{this.m_body.Freeze();}},Support:function(dX,dY,out)
-{var dLocalX=(dX*this.m_R.col1.x+dY*this.m_R.col1.y);var dLocalY=(dX*this.m_R.col2.x+dY*this.m_R.col2.y);var bestIndex=0;var bestValue=(this.m_coreVertices[0].x*dLocalX+this.m_coreVertices[0].y*dLocalY);for(var i=1;i<this.m_vertexCount;++i)
-{var value=(this.m_coreVertices[i].x*dLocalX+this.m_coreVertices[i].y*dLocalY);if(value>bestValue)
-{bestIndex=i;bestValue=value;}}
-out.Set(this.m_position.x+(this.m_R.col1.x*this.m_coreVertices[bestIndex].x+this.m_R.col2.x*this.m_coreVertices[bestIndex].y),this.m_position.y+(this.m_R.col1.y*this.m_coreVertices[bestIndex].x+this.m_R.col2.y*this.m_coreVertices[bestIndex].y));},m_localCentroid:new b2Vec2(),m_localOBB:new b2OBB(),m_vertices:null,m_coreVertices:null,m_vertexCount:0,m_normals:null});b2PolyShape.tempVec=new b2Vec2();b2PolyShape.tAbsR=new b2Mat22();
-var b2Body=Class.create();b2Body.prototype={SetOriginPosition:function(position,rotation){if(this.IsFrozen())
-{return;}
-this.m_rotation=rotation;this.m_R.Set(this.m_rotation);this.m_position=b2Math.AddVV(position,b2Math.b2MulMV(this.m_R,this.m_center));this.m_position0.SetV(this.m_position);this.m_rotation0=this.m_rotation;for(var s=this.m_shapeList;s!=null;s=s.m_next)
-{s.Synchronize(this.m_position,this.m_R,this.m_position,this.m_R);}
-this.m_world.m_broadPhase.Commit();},GetOriginPosition:function(){return b2Math.SubtractVV(this.m_position,b2Math.b2MulMV(this.m_R,this.m_center));},SetCenterPosition:function(position,rotation){if(this.IsFrozen())
-{return;}
-this.m_rotation=rotation;this.m_R.Set(this.m_rotation);this.m_position.SetV(position);this.m_position0.SetV(this.m_position);this.m_rotation0=this.m_rotation;for(var s=this.m_shapeList;s!=null;s=s.m_next)
-{s.Synchronize(this.m_position,this.m_R,this.m_position,this.m_R);}
-this.m_world.m_broadPhase.Commit();},GetCenterPosition:function(){return this.m_position;},GetRotation:function(){return this.m_rotation;},GetRotationMatrix:function(){return this.m_R;},SetLinearVelocity:function(v){this.m_linearVelocity.SetV(v);},GetLinearVelocity:function(){return this.m_linearVelocity;},SetAngularVelocity:function(w){this.m_angularVelocity=w;},GetAngularVelocity:function(){return this.m_angularVelocity;},ApplyForce:function(force,point)
-{if(this.IsSleeping()==false)
-{this.m_force.Add(force);this.m_torque+=b2Math.b2CrossVV(b2Math.SubtractVV(point,this.m_position),force);}},ApplyTorque:function(torque)
-{if(this.IsSleeping()==false)
-{this.m_torque+=torque;}},ApplyImpulse:function(impulse,point)
-{if(this.IsSleeping()==false)
-{this.m_linearVelocity.Add(b2Math.MulFV(this.m_invMass,impulse));this.m_angularVelocity+=(this.m_invI*b2Math.b2CrossVV(b2Math.SubtractVV(point,this.m_position),impulse));}},GetMass:function(){return this.m_mass;},GetInertia:function(){return this.m_I;},GetWorldPoint:function(localPoint){return b2Math.AddVV(this.m_position,b2Math.b2MulMV(this.m_R,localPoint));},GetWorldVector:function(localVector){return b2Math.b2MulMV(this.m_R,localVector);},GetLocalPoint:function(worldPoint){return b2Math.b2MulTMV(this.m_R,b2Math.SubtractVV(worldPoint,this.m_position));},GetLocalVector:function(worldVector){return b2Math.b2MulTMV(this.m_R,worldVector);},IsStatic:function(){return(this.m_flags&b2Body.e_staticFlag)==b2Body.e_staticFlag;},IsFrozen:function()
-{return(this.m_flags&b2Body.e_frozenFlag)==b2Body.e_frozenFlag;},IsSleeping:function(){return(this.m_flags&b2Body.e_sleepFlag)==b2Body.e_sleepFlag;},AllowSleeping:function(flag)
-{if(flag)
-{this.m_flags|=b2Body.e_allowSleepFlag;}
-else
-{this.m_flags&=~b2Body.e_allowSleepFlag;this.WakeUp();}},WakeUp:function(){this.m_flags&=~b2Body.e_sleepFlag;this.m_sleepTime=0.0;},GetShapeList:function(){return this.m_shapeList;},GetContactList:function()
-{return this.m_contactList;},GetJointList:function()
-{return this.m_jointList;},GetNext:function(){return this.m_next;},GetUserData:function(){return this.m_userData;},initialize:function(bd,world){this.sMat0=new b2Mat22();this.m_position=new b2Vec2();this.m_R=new b2Mat22(0);this.m_position0=new b2Vec2();var i=0;var sd;var massData;this.m_flags=0;this.m_position.SetV(bd.position);this.m_rotation=bd.rotation;this.m_R.Set(this.m_rotation);this.m_position0.SetV(this.m_position);this.m_rotation0=this.m_rotation;this.m_world=world;this.m_linearDamping=b2Math.b2Clamp(1.0-bd.linearDamping,0.0,1.0);this.m_angularDamping=b2Math.b2Clamp(1.0-bd.angularDamping,0.0,1.0);this.m_force=new b2Vec2(0.0,0.0);this.m_torque=0.0;this.m_mass=0.0;var massDatas=new Array(b2Settings.b2_maxShapesPerBody);for(i=0;i<b2Settings.b2_maxShapesPerBody;i++){massDatas[i]=new b2MassData();}
-this.m_shapeCount=0;this.m_center=new b2Vec2(0.0,0.0);for(i=0;i<b2Settings.b2_maxShapesPerBody;++i)
-{sd=bd.shapes[i];if(sd==null)break;massData=massDatas[i];sd.ComputeMass(massData);this.m_mass+=massData.mass;this.m_center.x+=massData.mass*(sd.localPosition.x+massData.center.x);this.m_center.y+=massData.mass*(sd.localPosition.y+massData.center.y);++this.m_shapeCount;}
-if(this.m_mass>0.0)
-{this.m_center.Multiply(1.0/this.m_mass);this.m_position.Add(b2Math.b2MulMV(this.m_R,this.m_center));}
-else
-{this.m_flags|=b2Body.e_staticFlag;}
-this.m_I=0.0;for(i=0;i<this.m_shapeCount;++i)
-{sd=bd.shapes[i];massData=massDatas[i];this.m_I+=massData.I;var r=b2Math.SubtractVV(b2Math.AddVV(sd.localPosition,massData.center),this.m_center);this.m_I+=massData.mass*b2Math.b2Dot(r,r);}
-if(this.m_mass>0.0)
-{this.m_invMass=1.0/this.m_mass;}
-else
-{this.m_invMass=0.0;}
-if(this.m_I>0.0&&bd.preventRotation==false)
-{this.m_invI=1.0/this.m_I;}
-else
-{this.m_I=0.0;this.m_invI=0.0;}
-this.m_linearVelocity=b2Math.AddVV(bd.linearVelocity,b2Math.b2CrossFV(bd.angularVelocity,this.m_center));this.m_angularVelocity=bd.angularVelocity;this.m_jointList=null;this.m_contactList=null;this.m_prev=null;this.m_next=null;this.m_shapeList=null;for(i=0;i<this.m_shapeCount;++i)
-{sd=bd.shapes[i];var shape=b2Shape.Create(sd,this,this.m_center);shape.m_next=this.m_shapeList;this.m_shapeList=shape;}
-this.m_sleepTime=0.0;if(bd.allowSleep)
-{this.m_flags|=b2Body.e_allowSleepFlag;}
-if(bd.isSleeping)
-{this.m_flags|=b2Body.e_sleepFlag;}
-if((this.m_flags&b2Body.e_sleepFlag)||this.m_invMass==0.0)
-{this.m_linearVelocity.Set(0.0,0.0);this.m_angularVelocity=0.0;}
-this.m_userData=bd.userData;},Destroy:function(){var s=this.m_shapeList;while(s)
-{var s0=s;s=s.m_next;b2Shape.Destroy(s0);}},sMat0:new b2Mat22(),SynchronizeShapes:function(){this.sMat0.Set(this.m_rotation0);for(var s=this.m_shapeList;s!=null;s=s.m_next)
-{s.Synchronize(this.m_position0,this.sMat0,this.m_position,this.m_R);}},QuickSyncShapes:function(){for(var s=this.m_shapeList;s!=null;s=s.m_next)
-{s.QuickSync(this.m_position,this.m_R);}},IsConnected:function(other){for(var jn=this.m_jointList;jn!=null;jn=jn.next)
-{if(jn.other==other)
-return jn.joint.m_collideConnected==false;}
-return false;},Freeze:function(){this.m_flags|=b2Body.e_frozenFlag;this.m_linearVelocity.SetZero();this.m_angularVelocity=0.0;for(var s=this.m_shapeList;s!=null;s=s.m_next)
-{s.DestroyProxy();}},m_flags:0,m_position:new b2Vec2(),m_rotation:null,m_R:new b2Mat22(0),m_position0:new b2Vec2(),m_rotation0:null,m_linearVelocity:null,m_angularVelocity:null,m_force:null,m_torque:null,m_center:null,m_world:null,m_prev:null,m_next:null,m_shapeList:null,m_shapeCount:0,m_jointList:null,m_contactList:null,m_mass:null,m_invMass:null,m_I:null,m_invI:null,m_linearDamping:null,m_angularDamping:null,m_sleepTime:null,m_userData:null};b2Body.e_staticFlag=0x0001;b2Body.e_frozenFlag=0x0002;b2Body.e_islandFlag=0x0004;b2Body.e_sleepFlag=0x0008;b2Body.e_allowSleepFlag=0x0010;b2Body.e_destroyFlag=0x0020;
-var b2BodyDef=Class.create();b2BodyDef.prototype={initialize:function()
-{this.shapes=new Array();this.userData=null;for(var i=0;i<b2Settings.b2_maxShapesPerBody;i++){this.shapes[i]=null;}
-this.position=new b2Vec2(0.0,0.0);this.rotation=0.0;this.linearVelocity=new b2Vec2(0.0,0.0);this.angularVelocity=0.0;this.linearDamping=0.0;this.angularDamping=0.0;this.allowSleep=true;this.isSleeping=false;this.preventRotation=false;},userData:null,shapes:new Array(),position:null,rotation:null,linearVelocity:null,angularVelocity:null,linearDamping:null,angularDamping:null,allowSleep:null,isSleeping:null,preventRotation:null,AddShape:function(shape)
-{for(var i=0;i<b2Settings.b2_maxShapesPerBody;++i)
-{if(this.shapes[i]==null)
-{this.shapes[i]=shape;break;}}}};
-var b2CollisionFilter=Class.create();b2CollisionFilter.prototype={ShouldCollide:function(shape1,shape2){if(shape1.m_groupIndex==shape2.m_groupIndex&&shape1.m_groupIndex!=0)
-{return shape1.m_groupIndex>0;}
-var collide=(shape1.m_maskBits&shape2.m_categoryBits)!=0&&(shape1.m_categoryBits&shape2.m_maskBits)!=0;return collide;},initialize:function(){}};b2CollisionFilter.b2_defaultFilter=new b2CollisionFilter;
-var b2Island=Class.create();b2Island.prototype={initialize:function(bodyCapacity,contactCapacity,jointCapacity,allocator)
-{var i=0;this.m_bodyCapacity=bodyCapacity;this.m_contactCapacity=contactCapacity;this.m_jointCapacity=jointCapacity;this.m_bodyCount=0;this.m_contactCount=0;this.m_jointCount=0;this.m_bodies=new Array(bodyCapacity);for(i=0;i<bodyCapacity;i++)
-this.m_bodies[i]=null;this.m_contacts=new Array(contactCapacity);for(i=0;i<contactCapacity;i++)
-this.m_contacts[i]=null;this.m_joints=new Array(jointCapacity);for(i=0;i<jointCapacity;i++)
-this.m_joints[i]=null;this.m_allocator=allocator;},Clear:function()
-{this.m_bodyCount=0;this.m_contactCount=0;this.m_jointCount=0;},Solve:function(step,gravity)
-{var i=0;var b;for(i=0;i<this.m_bodyCount;++i)
-{b=this.m_bodies[i];if(b.m_invMass==0.0)
-continue;b.m_linearVelocity.Add(b2Math.MulFV(step.dt,b2Math.AddVV(gravity,b2Math.MulFV(b.m_invMass,b.m_force))));b.m_angularVelocity+=step.dt*b.m_invI*b.m_torque;b.m_linearVelocity.Multiply(b.m_linearDamping);b.m_angularVelocity*=b.m_angularDamping;b.m_position0.SetV(b.m_position);b.m_rotation0=b.m_rotation;}
-var contactSolver=new b2ContactSolver(this.m_contacts,this.m_contactCount,this.m_allocator);contactSolver.PreSolve();for(i=0;i<this.m_jointCount;++i)
-{this.m_joints[i].PrepareVelocitySolver();}
-for(i=0;i<step.iterations;++i)
-{contactSolver.SolveVelocityConstraints();for(var j=0;j<this.m_jointCount;++j)
-{this.m_joints[j].SolveVelocityConstraints(step);}}
-for(i=0;i<this.m_bodyCount;++i)
-{b=this.m_bodies[i];if(b.m_invMass==0.0)
-continue;b.m_position.x+=step.dt*b.m_linearVelocity.x;b.m_position.y+=step.dt*b.m_linearVelocity.y;b.m_rotation+=step.dt*b.m_angularVelocity;b.m_R.Set(b.m_rotation);}
-for(i=0;i<this.m_jointCount;++i)
-{this.m_joints[i].PreparePositionSolver();}
-if(b2World.s_enablePositionCorrection)
-{for(b2Island.m_positionIterationCount=0;b2Island.m_positionIterationCount<step.iterations;++b2Island.m_positionIterationCount)
-{var contactsOkay=contactSolver.SolvePositionConstraints(b2Settings.b2_contactBaumgarte);var jointsOkay=true;for(i=0;i<this.m_jointCount;++i)
-{var jointOkay=this.m_joints[i].SolvePositionConstraints();jointsOkay=jointsOkay&&jointOkay;}
-if(contactsOkay&&jointsOkay)
-{break;}}}
-contactSolver.PostSolve();for(i=0;i<this.m_bodyCount;++i)
-{b=this.m_bodies[i];if(b.m_invMass==0.0)
-continue;b.m_R.Set(b.m_rotation);b.SynchronizeShapes();b.m_force.Set(0.0,0.0);b.m_torque=0.0;}},UpdateSleep:function(dt)
-{var i=0;var b;var minSleepTime=Number.MAX_VALUE;var linTolSqr=b2Settings.b2_linearSleepTolerance*b2Settings.b2_linearSleepTolerance;var angTolSqr=b2Settings.b2_angularSleepTolerance*b2Settings.b2_angularSleepTolerance;for(i=0;i<this.m_bodyCount;++i)
-{b=this.m_bodies[i];if(b.m_invMass==0.0)
-{continue;}
-if((b.m_flags&b2Body.e_allowSleepFlag)==0)
-{b.m_sleepTime=0.0;minSleepTime=0.0;}
-if((b.m_flags&b2Body.e_allowSleepFlag)==0||b.m_angularVelocity*b.m_angularVelocity>angTolSqr||b2Math.b2Dot(b.m_linearVelocity,b.m_linearVelocity)>linTolSqr)
-{b.m_sleepTime=0.0;minSleepTime=0.0;}
-else
-{b.m_sleepTime+=dt;minSleepTime=b2Math.b2Min(minSleepTime,b.m_sleepTime);}}
-if(minSleepTime>=b2Settings.b2_timeToSleep)
-{for(i=0;i<this.m_bodyCount;++i)
-{b=this.m_bodies[i];b.m_flags|=b2Body.e_sleepFlag;}}},AddBody:function(body)
-{this.m_bodies[this.m_bodyCount++]=body;},AddContact:function(contact)
-{this.m_contacts[this.m_contactCount++]=contact;},AddJoint:function(joint)
-{this.m_joints[this.m_jointCount++]=joint;},m_allocator:null,m_bodies:null,m_contacts:null,m_joints:null,m_bodyCount:0,m_jointCount:0,m_contactCount:0,m_bodyCapacity:0,m_contactCapacity:0,m_jointCapacity:0,m_positionError:null};b2Island.m_positionIterationCount=0;
-var b2TimeStep=Class.create();b2TimeStep.prototype={dt:null,inv_dt:null,iterations:0,initialize:function(){}};
-var b2ContactNode=Class.create();b2ContactNode.prototype={other:null,contact:null,prev:null,next:null,initialize:function(){}};
-var b2Contact=Class.create();b2Contact.prototype={GetManifolds:function(){return null},GetManifoldCount:function()
-{return this.m_manifoldCount;},GetNext:function(){return this.m_next;},GetShape1:function(){return this.m_shape1;},GetShape2:function(){return this.m_shape2;},initialize:function(s1,s2)
-{this.m_node1=new b2ContactNode();this.m_node2=new b2ContactNode();this.m_flags=0;if(!s1||!s2){this.m_shape1=null;this.m_shape2=null;return;}
-this.m_shape1=s1;this.m_shape2=s2;this.m_manifoldCount=0;this.m_friction=Math.sqrt(this.m_shape1.m_friction*this.m_shape2.m_friction);this.m_restitution=b2Math.b2Max(this.m_shape1.m_restitution,this.m_shape2.m_restitution);this.m_prev=null;this.m_next=null;this.m_node1.contact=null;this.m_node1.prev=null;this.m_node1.next=null;this.m_node1.other=null;this.m_node2.contact=null;this.m_node2.prev=null;this.m_node2.next=null;this.m_node2.other=null;},Evaluate:function(){},m_flags:0,m_prev:null,m_next:null,m_node1:new b2ContactNode(),m_node2:new b2ContactNode(),m_shape1:null,m_shape2:null,m_manifoldCount:0,m_friction:null,m_restitution:null};b2Contact.e_islandFlag=0x0001;b2Contact.e_destroyFlag=0x0002;b2Contact.AddType=function(createFcn,destroyFcn,type1,type2)
-{b2Contact.s_registers[type1][type2].createFcn=createFcn;b2Contact.s_registers[type1][type2].destroyFcn=destroyFcn;b2Contact.s_registers[type1][type2].primary=true;if(type1!=type2)
-{b2Contact.s_registers[type2][type1].createFcn=createFcn;b2Contact.s_registers[type2][type1].destroyFcn=destroyFcn;b2Contact.s_registers[type2][type1].primary=false;}};b2Contact.InitializeRegisters=function(){b2Contact.s_registers=new Array(b2Shape.e_shapeTypeCount);for(var i=0;i<b2Shape.e_shapeTypeCount;i++){b2Contact.s_registers[i]=new Array(b2Shape.e_shapeTypeCount);for(var j=0;j<b2Shape.e_shapeTypeCount;j++){b2Contact.s_registers[i][j]=new b2ContactRegister();}}
-b2Contact.AddType(b2CircleContact.Create,b2CircleContact.Destroy,b2Shape.e_circleShape,b2Shape.e_circleShape);b2Contact.AddType(b2PolyAndCircleContact.Create,b2PolyAndCircleContact.Destroy,b2Shape.e_polyShape,b2Shape.e_circleShape);b2Contact.AddType(b2PolyContact.Create,b2PolyContact.Destroy,b2Shape.e_polyShape,b2Shape.e_polyShape);};b2Contact.Create=function(shape1,shape2,allocator){if(b2Contact.s_initialized==false)
-{b2Contact.InitializeRegisters();b2Contact.s_initialized=true;}
-var type1=shape1.m_type;var type2=shape2.m_type;var createFcn=b2Contact.s_registers[type1][type2].createFcn;if(createFcn)
-{if(b2Contact.s_registers[type1][type2].primary)
-{return createFcn(shape1,shape2,allocator);}
-else
-{var c=createFcn(shape2,shape1,allocator);for(var i=0;i<c.GetManifoldCount();++i)
-{var m=c.GetManifolds()[i];m.normal=m.normal.Negative();}
-return c;}}
-else
-{return null;}};b2Contact.Destroy=function(contact,allocator){if(contact.GetManifoldCount()>0)
-{contact.m_shape1.m_body.WakeUp();contact.m_shape2.m_body.WakeUp();}
-var type1=contact.m_shape1.m_type;var type2=contact.m_shape2.m_type;var destroyFcn=b2Contact.s_registers[type1][type2].destroyFcn;destroyFcn(contact,allocator);};b2Contact.s_registers=null;b2Contact.s_initialized=false;
-var b2ContactConstraint=Class.create();b2ContactConstraint.prototype={initialize:function(){this.normal=new b2Vec2();this.points=new Array(b2Settings.b2_maxManifoldPoints);for(var i=0;i<b2Settings.b2_maxManifoldPoints;i++){this.points[i]=new b2ContactConstraintPoint();}},points:null,normal:new b2Vec2(),manifold:null,body1:null,body2:null,friction:null,restitution:null,pointCount:0};
-var b2ContactConstraintPoint=Class.create();b2ContactConstraintPoint.prototype={localAnchor1:new b2Vec2(),localAnchor2:new b2Vec2(),normalImpulse:null,tangentImpulse:null,positionImpulse:null,normalMass:null,tangentMass:null,separation:null,velocityBias:null,initialize:function(){this.localAnchor1=new b2Vec2();this.localAnchor2=new b2Vec2();}};
-var b2ContactRegister=Class.create();b2ContactRegister.prototype={createFcn:null,destroyFcn:null,primary:null,initialize:function(){}};
-var b2ContactSolver=Class.create();b2ContactSolver.prototype={initialize:function(contacts,contactCount,allocator){this.m_constraints=new Array();this.m_allocator=allocator;var i=0;var tVec;var tMat;this.m_constraintCount=0;for(i=0;i<contactCount;++i)
-{this.m_constraintCount+=contacts[i].GetManifoldCount();}
-for(i=0;i<this.m_constraintCount;i++){this.m_constraints[i]=new b2ContactConstraint();}
-var count=0;for(i=0;i<contactCount;++i)
-{var contact=contacts[i];var b1=contact.m_shape1.m_body;var b2=contact.m_shape2.m_body;var manifoldCount=contact.GetManifoldCount();var manifolds=contact.GetManifolds();var friction=contact.m_friction;var restitution=contact.m_restitution;var v1X=b1.m_linearVelocity.x;var v1Y=b1.m_linearVelocity.y;var v2X=b2.m_linearVelocity.x;var v2Y=b2.m_linearVelocity.y;var w1=b1.m_angularVelocity;var w2=b2.m_angularVelocity;for(var j=0;j<manifoldCount;++j)
-{var manifold=manifolds[j];var normalX=manifold.normal.x;var normalY=manifold.normal.y;var c=this.m_constraints[count];c.body1=b1;c.body2=b2;c.manifold=manifold;c.normal.x=normalX;c.normal.y=normalY;c.pointCount=manifold.pointCount;c.friction=friction;c.restitution=restitution;for(var k=0;k<c.pointCount;++k)
-{var cp=manifold.points[k];var ccp=c.points[k];ccp.normalImpulse=cp.normalImpulse;ccp.tangentImpulse=cp.tangentImpulse;ccp.separation=cp.separation;var r1X=cp.position.x-b1.m_position.x;var r1Y=cp.position.y-b1.m_position.y;var r2X=cp.position.x-b2.m_position.x;var r2Y=cp.position.y-b2.m_position.y;tVec=ccp.localAnchor1;tMat=b1.m_R;tVec.x=r1X*tMat.col1.x+r1Y*tMat.col1.y;tVec.y=r1X*tMat.col2.x+r1Y*tMat.col2.y;tVec=ccp.localAnchor2;tMat=b2.m_R;tVec.x=r2X*tMat.col1.x+r2Y*tMat.col1.y;tVec.y=r2X*tMat.col2.x+r2Y*tMat.col2.y;var r1Sqr=r1X*r1X+r1Y*r1Y;var r2Sqr=r2X*r2X+r2Y*r2Y;var rn1=r1X*normalX+r1Y*normalY;var rn2=r2X*normalX+r2Y*normalY;var kNormal=b1.m_invMass+b2.m_invMass;kNormal+=b1.m_invI*(r1Sqr-rn1*rn1)+b2.m_invI*(r2Sqr-rn2*rn2);ccp.normalMass=1.0/kNormal;var tangentX=normalY
-var tangentY=-normalX;var rt1=r1X*tangentX+r1Y*tangentY;var rt2=r2X*tangentX+r2Y*tangentY;var kTangent=b1.m_invMass+b2.m_invMass;kTangent+=b1.m_invI*(r1Sqr-rt1*rt1)+b2.m_invI*(r2Sqr-rt2*rt2);ccp.tangentMass=1.0/kTangent;ccp.velocityBias=0.0;if(ccp.separation>0.0)
-{ccp.velocityBias=-60.0*ccp.separation;}
-var tX=v2X+(-w2*r2Y)-v1X-(-w1*r1Y);var tY=v2Y+(w2*r2X)-v1Y-(w1*r1X);var vRel=c.normal.x*tX+c.normal.y*tY;if(vRel<-b2Settings.b2_velocityThreshold)
-{ccp.velocityBias+=-c.restitution*vRel;}}
-++count;}}},PreSolve:function(){var tVec;var tVec2;var tMat;for(var i=0;i<this.m_constraintCount;++i)
-{var c=this.m_constraints[i];var b1=c.body1;var b2=c.body2;var invMass1=b1.m_invMass;var invI1=b1.m_invI;var invMass2=b2.m_invMass;var invI2=b2.m_invI;var normalX=c.normal.x;var normalY=c.normal.y;var tangentX=normalY;var tangentY=-normalX;var j=0;var tCount=0;if(b2World.s_enableWarmStarting)
-{tCount=c.pointCount;for(j=0;j<tCount;++j)
-{var ccp=c.points[j];var PX=ccp.normalImpulse*normalX+ccp.tangentImpulse*tangentX;var PY=ccp.normalImpulse*normalY+ccp.tangentImpulse*tangentY;tMat=b1.m_R;tVec=ccp.localAnchor1;var r1X=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var r1Y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=b2.m_R;tVec=ccp.localAnchor2;var r2X=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var r2Y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;b1.m_angularVelocity-=invI1*(r1X*PY-r1Y*PX);b1.m_linearVelocity.x-=invMass1*PX;b1.m_linearVelocity.y-=invMass1*PY;b2.m_angularVelocity+=invI2*(r2X*PY-r2Y*PX);b2.m_linearVelocity.x+=invMass2*PX;b2.m_linearVelocity.y+=invMass2*PY;ccp.positionImpulse=0.0;}}
-else{tCount=c.pointCount;for(j=0;j<tCount;++j)
-{var ccp2=c.points[j];ccp2.normalImpulse=0.0;ccp2.tangentImpulse=0.0;ccp2.positionImpulse=0.0;}}}},SolveVelocityConstraints:function(){var j=0;var ccp;var r1X;var r1Y;var r2X;var r2Y;var dvX;var dvY;var lambda;var newImpulse;var PX;var PY;var tMat;var tVec;for(var i=0;i<this.m_constraintCount;++i)
-{var c=this.m_constraints[i];var b1=c.body1;var b2=c.body2;var b1_angularVelocity=b1.m_angularVelocity;var b1_linearVelocity=b1.m_linearVelocity;var b2_angularVelocity=b2.m_angularVelocity;var b2_linearVelocity=b2.m_linearVelocity;var invMass1=b1.m_invMass;var invI1=b1.m_invI;var invMass2=b2.m_invMass;var invI2=b2.m_invI;var normalX=c.normal.x;var normalY=c.normal.y;var tangentX=normalY;var tangentY=-normalX;var tCount=c.pointCount;for(j=0;j<tCount;++j)
-{ccp=c.points[j];tMat=b1.m_R;tVec=ccp.localAnchor1;r1X=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y
-r1Y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y
-tMat=b2.m_R;tVec=ccp.localAnchor2;r2X=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y
-r2Y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y
-dvX=b2_linearVelocity.x+(-b2_angularVelocity*r2Y)-b1_linearVelocity.x-(-b1_angularVelocity*r1Y);dvY=b2_linearVelocity.y+(b2_angularVelocity*r2X)-b1_linearVelocity.y-(b1_angularVelocity*r1X);var vn=dvX*normalX+dvY*normalY;lambda=-ccp.normalMass*(vn-ccp.velocityBias);newImpulse=b2Math.b2Max(ccp.normalImpulse+lambda,0.0);lambda=newImpulse-ccp.normalImpulse;PX=lambda*normalX;PY=lambda*normalY;b1_linearVelocity.x-=invMass1*PX;b1_linearVelocity.y-=invMass1*PY;b1_angularVelocity-=invI1*(r1X*PY-r1Y*PX);b2_linearVelocity.x+=invMass2*PX;b2_linearVelocity.y+=invMass2*PY;b2_angularVelocity+=invI2*(r2X*PY-r2Y*PX);ccp.normalImpulse=newImpulse;dvX=b2_linearVelocity.x+(-b2_angularVelocity*r2Y)-b1_linearVelocity.x-(-b1_angularVelocity*r1Y);dvY=b2_linearVelocity.y+(b2_angularVelocity*r2X)-b1_linearVelocity.y-(b1_angularVelocity*r1X);var vt=dvX*tangentX+dvY*tangentY;lambda=ccp.tangentMass*(-vt);var maxFriction=c.friction*ccp.normalImpulse;newImpulse=b2Math.b2Clamp(ccp.tangentImpulse+lambda,-maxFriction,maxFriction);lambda=newImpulse-ccp.tangentImpulse;PX=lambda*tangentX;PY=lambda*tangentY;b1_linearVelocity.x-=invMass1*PX;b1_linearVelocity.y-=invMass1*PY;b1_angularVelocity-=invI1*(r1X*PY-r1Y*PX);b2_linearVelocity.x+=invMass2*PX;b2_linearVelocity.y+=invMass2*PY;b2_angularVelocity+=invI2*(r2X*PY-r2Y*PX);ccp.tangentImpulse=newImpulse;}
-b1.m_angularVelocity=b1_angularVelocity;b2.m_angularVelocity=b2_angularVelocity;}},SolvePositionConstraints:function(beta){var minSeparation=0.0;var tMat;var tVec;for(var i=0;i<this.m_constraintCount;++i)
-{var c=this.m_constraints[i];var b1=c.body1;var b2=c.body2;var b1_position=b1.m_position;var b1_rotation=b1.m_rotation;var b2_position=b2.m_position;var b2_rotation=b2.m_rotation;var invMass1=b1.m_invMass;var invI1=b1.m_invI;var invMass2=b2.m_invMass;var invI2=b2.m_invI;var normalX=c.normal.x;var normalY=c.normal.y;var tangentX=normalY;var tangentY=-normalX;var tCount=c.pointCount;for(var j=0;j<tCount;++j)
-{var ccp=c.points[j];tMat=b1.m_R;tVec=ccp.localAnchor1;var r1X=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y
-var r1Y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y
-tMat=b2.m_R;tVec=ccp.localAnchor2;var r2X=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y
-var r2Y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y
-var p1X=b1_position.x+r1X;var p1Y=b1_position.y+r1Y;var p2X=b2_position.x+r2X;var p2Y=b2_position.y+r2Y;var dpX=p2X-p1X;var dpY=p2Y-p1Y;var separation=(dpX*normalX+dpY*normalY)+ccp.separation;minSeparation=b2Math.b2Min(minSeparation,separation);var C=beta*b2Math.b2Clamp(separation+b2Settings.b2_linearSlop,-b2Settings.b2_maxLinearCorrection,0.0);var dImpulse=-ccp.normalMass*C;var impulse0=ccp.positionImpulse;ccp.positionImpulse=b2Math.b2Max(impulse0+dImpulse,0.0);dImpulse=ccp.positionImpulse-impulse0;var impulseX=dImpulse*normalX;var impulseY=dImpulse*normalY;b1_position.x-=invMass1*impulseX;b1_position.y-=invMass1*impulseY;b1_rotation-=invI1*(r1X*impulseY-r1Y*impulseX);b1.m_R.Set(b1_rotation);b2_position.x+=invMass2*impulseX;b2_position.y+=invMass2*impulseY;b2_rotation+=invI2*(r2X*impulseY-r2Y*impulseX);b2.m_R.Set(b2_rotation);}
-b1.m_rotation=b1_rotation;b2.m_rotation=b2_rotation;}
-return minSeparation>=-b2Settings.b2_linearSlop;},PostSolve:function(){for(var i=0;i<this.m_constraintCount;++i)
-{var c=this.m_constraints[i];var m=c.manifold;for(var j=0;j<c.pointCount;++j)
-{var mPoint=m.points[j];var cPoint=c.points[j];mPoint.normalImpulse=cPoint.normalImpulse;mPoint.tangentImpulse=cPoint.tangentImpulse;}}},m_allocator:null,m_constraints:new Array(),m_constraintCount:0};
-var b2CircleContact=Class.create();Object.extend(b2CircleContact.prototype,b2Contact.prototype);Object.extend(b2CircleContact.prototype,{initialize:function(s1,s2){this.m_node1=new b2ContactNode();this.m_node2=new b2ContactNode();this.m_flags=0;if(!s1||!s2){this.m_shape1=null;this.m_shape2=null;return;}
-this.m_shape1=s1;this.m_shape2=s2;this.m_manifoldCount=0;this.m_friction=Math.sqrt(this.m_shape1.m_friction*this.m_shape2.m_friction);this.m_restitution=b2Math.b2Max(this.m_shape1.m_restitution,this.m_shape2.m_restitution);this.m_prev=null;this.m_next=null;this.m_node1.contact=null;this.m_node1.prev=null;this.m_node1.next=null;this.m_node1.other=null;this.m_node2.contact=null;this.m_node2.prev=null;this.m_node2.next=null;this.m_node2.other=null;this.m_manifold=[new b2Manifold()];this.m_manifold[0].pointCount=0;this.m_manifold[0].points[0].normalImpulse=0.0;this.m_manifold[0].points[0].tangentImpulse=0.0;},Evaluate:function(){b2Collision.b2CollideCircle(this.m_manifold[0],this.m_shape1,this.m_shape2,false);if(this.m_manifold[0].pointCount>0)
-{this.m_manifoldCount=1;}
-else
-{this.m_manifoldCount=0;}},GetManifolds:function()
-{return this.m_manifold;},m_manifold:[new b2Manifold()]});b2CircleContact.Create=function(shape1,shape2,allocator){return new b2CircleContact(shape1,shape2);};b2CircleContact.Destroy=function(contact,allocator){};
-var b2Conservative=Class.create();b2Conservative.prototype={initialize:function(){}}
-b2Conservative.R1=new b2Mat22();b2Conservative.R2=new b2Mat22();b2Conservative.x1=new b2Vec2();b2Conservative.x2=new b2Vec2();b2Conservative.Conservative=function(shape1,shape2){var body1=shape1.GetBody();var body2=shape2.GetBody();var v1X=body1.m_position.x-body1.m_position0.x;var v1Y=body1.m_position.y-body1.m_position0.y;var omega1=body1.m_rotation-body1.m_rotation0;var v2X=body2.m_position.x-body2.m_position0.x;var v2Y=body2.m_position.y-body2.m_position0.y;var omega2=body2.m_rotation-body2.m_rotation0;var r1=shape1.GetMaxRadius();var r2=shape2.GetMaxRadius();var p1StartX=body1.m_position0.x;var p1StartY=body1.m_position0.y;var a1Start=body1.m_rotation0;var p2StartX=body2.m_position0.x;var p2StartY=body2.m_position0.y;var a2Start=body2.m_rotation0;var p1X=p1StartX;var p1Y=p1StartY;var a1=a1Start;var p2X=p2StartX;var p2Y=p2StartY;var a2=a2Start;b2Conservative.R1.Set(a1);b2Conservative.R2.Set(a2);shape1.QuickSync(p1,b2Conservative.R1);shape2.QuickSync(p2,b2Conservative.R2);var s1=0.0;var maxIterations=10;var dX;var dY;var invRelativeVelocity=0.0;var hit=true;for(var iter=0;iter<maxIterations;++iter)
-{var distance=b2Distance.Distance(b2Conservative.x1,b2Conservative.x2,shape1,shape2);if(distance<b2Settings.b2_linearSlop)
-{if(iter==0)
-{hit=false;}
-else
-{hit=true;}
-break;}
-if(iter==0)
-{dX=b2Conservative.x2.x-b2Conservative.x1.x;dY=b2Conservative.x2.y-b2Conservative.x1.y;var dLen=Math.sqrt(dX*dX+dY*dY);var relativeVelocity=(dX*(v1X-v2X)+dY*(v1Y-v2Y))+Math.abs(omega1)*r1+Math.abs(omega2)*r2;if(Math.abs(relativeVelocity)<Number.MIN_VALUE)
-{hit=false;break;}
-invRelativeVelocity=1.0/relativeVelocity;}
-var ds=distance*invRelativeVelocity;var s2=s1+ds;if(s2<0.0||1.0<s2)
-{hit=false;break;}
-if(s2<(1.0+100.0*Number.MIN_VALUE)*s1)
-{hit=true;break;}
-s1=s2;p1X=p1StartX+s1*v1.x;p1Y=p1StartY+s1*v1.y;a1=a1Start+s1*omega1;p2X=p2StartX+s1*v2.x;p2Y=p2StartY+s1*v2.y;a2=a2Start+s1*omega2;b2Conservative.R1.Set(a1);b2Conservative.R2.Set(a2);shape1.QuickSync(p1,b2Conservative.R1);shape2.QuickSync(p2,b2Conservative.R2);}
-if(hit)
-{dX=b2Conservative.x2.x-b2Conservative.x1.x;dY=b2Conservative.x2.y-b2Conservative.x1.y;var length=Math.sqrt(dX*dX+dY*dY);if(length>FLT_EPSILON)
-{d*=b2_linearSlop/length;}
-if(body1.IsStatic())
-{body1.m_position.x=p1X;body1.m_position.y=p1Y;}
-else
-{body1.m_position.x=p1X-dX;body1.m_position.y=p1Y-dY;}
-body1.m_rotation=a1;body1.m_R.Set(a1);body1.QuickSyncShapes();if(body2.IsStatic())
-{body2.m_position.x=p2X;body2.m_position.y=p2Y;}
-else
-{body2.m_position.x=p2X+dX;body2.m_position.y=p2Y+dY;}
-body2.m_position.x=p2X+dX;body2.m_position.y=p2Y+dY;body2.m_rotation=a2;body2.m_R.Set(a2);body2.QuickSyncShapes();return true;}
-shape1.QuickSync(body1.m_position,body1.m_R);shape2.QuickSync(body2.m_position,body2.m_R);return false;};
-var b2NullContact=Class.create();Object.extend(b2NullContact.prototype,b2Contact.prototype);Object.extend(b2NullContact.prototype,{initialize:function(s1,s2){this.m_node1=new b2ContactNode();this.m_node2=new b2ContactNode();this.m_flags=0;if(!s1||!s2){this.m_shape1=null;this.m_shape2=null;return;}
-this.m_shape1=s1;this.m_shape2=s2;this.m_manifoldCount=0;this.m_friction=Math.sqrt(this.m_shape1.m_friction*this.m_shape2.m_friction);this.m_restitution=b2Math.b2Max(this.m_shape1.m_restitution,this.m_shape2.m_restitution);this.m_prev=null;this.m_next=null;this.m_node1.contact=null;this.m_node1.prev=null;this.m_node1.next=null;this.m_node1.other=null;this.m_node2.contact=null;this.m_node2.prev=null;this.m_node2.next=null;this.m_node2.other=null;},Evaluate:function(){},GetManifolds:function(){return null;}});
-var b2PolyAndCircleContact=Class.create();Object.extend(b2PolyAndCircleContact.prototype,b2Contact.prototype);Object.extend(b2PolyAndCircleContact.prototype,{initialize:function(s1,s2){this.m_node1=new b2ContactNode();this.m_node2=new b2ContactNode();this.m_flags=0;if(!s1||!s2){this.m_shape1=null;this.m_shape2=null;return;}
-this.m_shape1=s1;this.m_shape2=s2;this.m_manifoldCount=0;this.m_friction=Math.sqrt(this.m_shape1.m_friction*this.m_shape2.m_friction);this.m_restitution=b2Math.b2Max(this.m_shape1.m_restitution,this.m_shape2.m_restitution);this.m_prev=null;this.m_next=null;this.m_node1.contact=null;this.m_node1.prev=null;this.m_node1.next=null;this.m_node1.other=null;this.m_node2.contact=null;this.m_node2.prev=null;this.m_node2.next=null;this.m_node2.other=null;this.m_manifold=[new b2Manifold()];b2Settings.b2Assert(this.m_shape1.m_type==b2Shape.e_polyShape);b2Settings.b2Assert(this.m_shape2.m_type==b2Shape.e_circleShape);this.m_manifold[0].pointCount=0;this.m_manifold[0].points[0].normalImpulse=0.0;this.m_manifold[0].points[0].tangentImpulse=0.0;},Evaluate:function(){b2Collision.b2CollidePolyAndCircle(this.m_manifold[0],this.m_shape1,this.m_shape2,false);if(this.m_manifold[0].pointCount>0)
-{this.m_manifoldCount=1;}
-else
-{this.m_manifoldCount=0;}},GetManifolds:function()
-{return this.m_manifold;},m_manifold:[new b2Manifold()]})
-b2PolyAndCircleContact.Create=function(shape1,shape2,allocator){return new b2PolyAndCircleContact(shape1,shape2);};b2PolyAndCircleContact.Destroy=function(contact,allocator){};
-var b2PolyContact=Class.create();Object.extend(b2PolyContact.prototype,b2Contact.prototype);Object.extend(b2PolyContact.prototype,{initialize:function(s1,s2){this.m_node1=new b2ContactNode();this.m_node2=new b2ContactNode();this.m_flags=0;if(!s1||!s2){this.m_shape1=null;this.m_shape2=null;return;}
-this.m_shape1=s1;this.m_shape2=s2;this.m_manifoldCount=0;this.m_friction=Math.sqrt(this.m_shape1.m_friction*this.m_shape2.m_friction);this.m_restitution=b2Math.b2Max(this.m_shape1.m_restitution,this.m_shape2.m_restitution);this.m_prev=null;this.m_next=null;this.m_node1.contact=null;this.m_node1.prev=null;this.m_node1.next=null;this.m_node1.other=null;this.m_node2.contact=null;this.m_node2.prev=null;this.m_node2.next=null;this.m_node2.other=null;this.m0=new b2Manifold();this.m_manifold=[new b2Manifold()];this.m_manifold[0].pointCount=0;},m0:new b2Manifold(),Evaluate:function(){var tMani=this.m_manifold[0];var tPoints=this.m0.points;for(var k=0;k<tMani.pointCount;k++){var tPoint=tPoints[k];var tPoint0=tMani.points[k];tPoint.normalImpulse=tPoint0.normalImpulse;tPoint.tangentImpulse=tPoint0.tangentImpulse;tPoint.id=tPoint0.id.Copy();}
-this.m0.pointCount=tMani.pointCount;b2Collision.b2CollidePoly(tMani,this.m_shape1,this.m_shape2,false);if(tMani.pointCount>0)
-{var match=[false,false];for(var i=0;i<tMani.pointCount;++i)
-{var cp=tMani.points[i];cp.normalImpulse=0.0;cp.tangentImpulse=0.0;var idKey=cp.id.key;for(var j=0;j<this.m0.pointCount;++j)
-{if(match[j]==true)
-continue;var cp0=this.m0.points[j];var id0=cp0.id;if(id0.key==idKey)
-{match[j]=true;cp.normalImpulse=cp0.normalImpulse;cp.tangentImpulse=cp0.tangentImpulse;break;}}}
-this.m_manifoldCount=1;}
-else
-{this.m_manifoldCount=0;}},GetManifolds:function()
-{return this.m_manifold;},m_manifold:[new b2Manifold()]});b2PolyContact.Create=function(shape1,shape2,allocator){return new b2PolyContact(shape1,shape2);};b2PolyContact.Destroy=function(contact,allocator){};
-var b2ContactManager=Class.create();Object.extend(b2ContactManager.prototype,b2PairCallback.prototype);Object.extend(b2ContactManager.prototype,{initialize:function(){this.m_nullContact=new b2NullContact();this.m_world=null;this.m_destroyImmediate=false;},PairAdded:function(proxyUserData1,proxyUserData2){var shape1=proxyUserData1;var shape2=proxyUserData2;var body1=shape1.m_body;var body2=shape2.m_body;if(body1.IsStatic()&&body2.IsStatic())
-{return this.m_nullContact;}
-if(shape1.m_body==shape2.m_body)
-{return this.m_nullContact;}
-if(body2.IsConnected(body1))
-{return this.m_nullContact;}
-if(this.m_world.m_filter!=null&&this.m_world.m_filter.ShouldCollide(shape1,shape2)==false)
-{return this.m_nullContact;}
-if(body2.m_invMass==0.0)
-{var tempShape=shape1;shape1=shape2;shape2=tempShape;var tempBody=body1;body1=body2;body2=tempBody;}
-var contact=b2Contact.Create(shape1,shape2,this.m_world.m_blockAllocator);if(contact==null)
-{return this.m_nullContact;}
-else
-{contact.m_prev=null;contact.m_next=this.m_world.m_contactList;if(this.m_world.m_contactList!=null)
-{this.m_world.m_contactList.m_prev=contact;}
-this.m_world.m_contactList=contact;this.m_world.m_contactCount++;}
-return contact;},PairRemoved:function(proxyUserData1,proxyUserData2,pairUserData){if(pairUserData==null)
-{return;}
-var c=pairUserData;if(c!=this.m_nullContact)
-{if(this.m_destroyImmediate==true)
-{this.DestroyContact(c);c=null;}
-else
-{c.m_flags|=b2Contact.e_destroyFlag;}}},DestroyContact:function(c)
-{if(c.m_prev)
-{c.m_prev.m_next=c.m_next;}
-if(c.m_next)
-{c.m_next.m_prev=c.m_prev;}
-if(c==this.m_world.m_contactList)
-{this.m_world.m_contactList=c.m_next;}
-if(c.GetManifoldCount()>0)
-{var body1=c.m_shape1.m_body;var body2=c.m_shape2.m_body;var node1=c.m_node1;var node2=c.m_node2;body1.WakeUp();body2.WakeUp();if(node1.prev)
-{node1.prev.next=node1.next;}
-if(node1.next)
-{node1.next.prev=node1.prev;}
-if(node1==body1.m_contactList)
-{body1.m_contactList=node1.next;}
-node1.prev=null;node1.next=null;if(node2.prev)
-{node2.prev.next=node2.next;}
-if(node2.next)
-{node2.next.prev=node2.prev;}
-if(node2==body2.m_contactList)
-{body2.m_contactList=node2.next;}
-node2.prev=null;node2.next=null;}
-b2Contact.Destroy(c,this.m_world.m_blockAllocator);--this.m_world.m_contactCount;},CleanContactList:function()
-{var c=this.m_world.m_contactList;while(c!=null)
-{var c0=c;c=c.m_next;if(c0.m_flags&b2Contact.e_destroyFlag)
-{this.DestroyContact(c0);c0=null;}}},Collide:function()
-{var body1;var body2;var node1;var node2;for(var c=this.m_world.m_contactList;c!=null;c=c.m_next)
-{if(c.m_shape1.m_body.IsSleeping()&&c.m_shape2.m_body.IsSleeping())
-{continue;}
-var oldCount=c.GetManifoldCount();c.Evaluate();var newCount=c.GetManifoldCount();if(oldCount==0&&newCount>0)
-{body1=c.m_shape1.m_body;body2=c.m_shape2.m_body;node1=c.m_node1;node2=c.m_node2;node1.contact=c;node1.other=body2;node1.prev=null;node1.next=body1.m_contactList;if(node1.next!=null)
-{node1.next.prev=c.m_node1;}
-body1.m_contactList=c.m_node1;node2.contact=c;node2.other=body1;node2.prev=null;node2.next=body2.m_contactList;if(node2.next!=null)
-{node2.next.prev=node2;}
-body2.m_contactList=node2;}
-else if(oldCount>0&&newCount==0)
-{body1=c.m_shape1.m_body;body2=c.m_shape2.m_body;node1=c.m_node1;node2=c.m_node2;if(node1.prev)
-{node1.prev.next=node1.next;}
-if(node1.next)
-{node1.next.prev=node1.prev;}
-if(node1==body1.m_contactList)
-{body1.m_contactList=node1.next;}
-node1.prev=null;node1.next=null;if(node2.prev)
-{node2.prev.next=node2.next;}
-if(node2.next)
-{node2.next.prev=node2.prev;}
-if(node2==body2.m_contactList)
-{body2.m_contactList=node2.next;}
-node2.prev=null;node2.next=null;}}},m_world:null,m_nullContact:new b2NullContact(),m_destroyImmediate:null});
-var b2World=Class.create();b2World.prototype={initialize:function(worldAABB,gravity,doSleep){this.step=new b2TimeStep();this.m_contactManager=new b2ContactManager();this.m_listener=null;this.m_filter=b2CollisionFilter.b2_defaultFilter;this.m_bodyList=null;this.m_contactList=null;this.m_jointList=null;this.m_bodyCount=0;this.m_contactCount=0;this.m_jointCount=0;this.m_bodyDestroyList=null;this.m_allowSleep=doSleep;this.m_gravity=gravity;this.m_contactManager.m_world=this;this.m_broadPhase=new b2BroadPhase(worldAABB,this.m_contactManager);var bd=new b2BodyDef();this.m_groundBody=this.CreateBody(bd);},SetListener:function(listener){this.m_listener=listener;},SetFilter:function(filter){this.m_filter=filter;},CreateBody:function(def){var b=new b2Body(def,this);b.m_prev=null;b.m_next=this.m_bodyList;if(this.m_bodyList)
-{this.m_bodyList.m_prev=b;}
-this.m_bodyList=b;++this.m_bodyCount;return b;},DestroyBody:function(b)
-{if(b.m_flags&b2Body.e_destroyFlag)
-{return;}
-if(b.m_prev)
-{b.m_prev.m_next=b.m_next;}
-if(b.m_next)
-{b.m_next.m_prev=b.m_prev;}
-if(b==this.m_bodyList)
-{this.m_bodyList=b.m_next;}
-b.m_flags|=b2Body.e_destroyFlag;--this.m_bodyCount;b.m_prev=null;b.m_next=this.m_bodyDestroyList;this.m_bodyDestroyList=b;},CleanBodyList:function()
-{this.m_contactManager.m_destroyImmediate=true;var b=this.m_bodyDestroyList;while(b)
-{var b0=b;b=b.m_next;var jn=b0.m_jointList;while(jn)
-{var jn0=jn;jn=jn.next;if(this.m_listener)
-{this.m_listener.NotifyJointDestroyed(jn0.joint);}
-this.DestroyJoint(jn0.joint);}
-b0.Destroy();}
-this.m_bodyDestroyList=null;this.m_contactManager.m_destroyImmediate=false;},CreateJoint:function(def){var j=b2Joint.Create(def,this.m_blockAllocator);j.m_prev=null;j.m_next=this.m_jointList;if(this.m_jointList)
-{this.m_jointList.m_prev=j;}
-this.m_jointList=j;++this.m_jointCount;j.m_node1.joint=j;j.m_node1.other=j.m_body2;j.m_node1.prev=null;j.m_node1.next=j.m_body1.m_jointList;if(j.m_body1.m_jointList)j.m_body1.m_jointList.prev=j.m_node1;j.m_body1.m_jointList=j.m_node1;j.m_node2.joint=j;j.m_node2.other=j.m_body1;j.m_node2.prev=null;j.m_node2.next=j.m_body2.m_jointList;if(j.m_body2.m_jointList)j.m_body2.m_jointList.prev=j.m_node2;j.m_body2.m_jointList=j.m_node2;if(def.collideConnected==false)
-{var b=def.body1.m_shapeCount<def.body2.m_shapeCount?def.body1:def.body2;for(var s=b.m_shapeList;s;s=s.m_next)
-{s.ResetProxy(this.m_broadPhase);}}
-return j;},DestroyJoint:function(j)
-{var collideConnected=j.m_collideConnected;if(j.m_prev)
-{j.m_prev.m_next=j.m_next;}
-if(j.m_next)
-{j.m_next.m_prev=j.m_prev;}
-if(j==this.m_jointList)
-{this.m_jointList=j.m_next;}
-var body1=j.m_body1;var body2=j.m_body2;body1.WakeUp();body2.WakeUp();if(j.m_node1.prev)
-{j.m_node1.prev.next=j.m_node1.next;}
-if(j.m_node1.next)
-{j.m_node1.next.prev=j.m_node1.prev;}
-if(j.m_node1==body1.m_jointList)
-{body1.m_jointList=j.m_node1.next;}
-j.m_node1.prev=null;j.m_node1.next=null;if(j.m_node2.prev)
-{j.m_node2.prev.next=j.m_node2.next;}
-if(j.m_node2.next)
-{j.m_node2.next.prev=j.m_node2.prev;}
-if(j.m_node2==body2.m_jointList)
-{body2.m_jointList=j.m_node2.next;}
-j.m_node2.prev=null;j.m_node2.next=null;b2Joint.Destroy(j,this.m_blockAllocator);--this.m_jointCount;if(collideConnected==false)
-{var b=body1.m_shapeCount<body2.m_shapeCount?body1:body2;for(var s=b.m_shapeList;s;s=s.m_next)
-{s.ResetProxy(this.m_broadPhase);}}},GetGroundBody:function(){return this.m_groundBody;},step:new b2TimeStep(),Step:function(dt,iterations){var b;var other;this.step.dt=dt;this.step.iterations=iterations;if(dt>0.0)
-{this.step.inv_dt=1.0/dt;}
-else
-{this.step.inv_dt=0.0;}
-this.m_positionIterationCount=0;this.m_contactManager.CleanContactList();this.CleanBodyList();this.m_contactManager.Collide();var island=new b2Island(this.m_bodyCount,this.m_contactCount,this.m_jointCount,this.m_stackAllocator);for(b=this.m_bodyList;b!=null;b=b.m_next)
-{b.m_flags&=~b2Body.e_islandFlag;}
-for(var c=this.m_contactList;c!=null;c=c.m_next)
-{c.m_flags&=~b2Contact.e_islandFlag;}
-for(var j=this.m_jointList;j!=null;j=j.m_next)
-{j.m_islandFlag=false;}
-var stackSize=this.m_bodyCount;var stack=new Array(this.m_bodyCount);for(var k=0;k<this.m_bodyCount;k++)
-stack[k]=null;for(var seed=this.m_bodyList;seed!=null;seed=seed.m_next)
-{if(seed.m_flags&(b2Body.e_staticFlag|b2Body.e_islandFlag|b2Body.e_sleepFlag|b2Body.e_frozenFlag))
-{continue;}
-island.Clear();var stackCount=0;stack[stackCount++]=seed;seed.m_flags|=b2Body.e_islandFlag;;while(stackCount>0)
-{b=stack[--stackCount];island.AddBody(b);b.m_flags&=~b2Body.e_sleepFlag;if(b.m_flags&b2Body.e_staticFlag)
-{continue;}
-for(var cn=b.m_contactList;cn!=null;cn=cn.next)
-{if(cn.contact.m_flags&b2Contact.e_islandFlag)
-{continue;}
-island.AddContact(cn.contact);cn.contact.m_flags|=b2Contact.e_islandFlag;other=cn.other;if(other.m_flags&b2Body.e_islandFlag)
-{continue;}
-stack[stackCount++]=other;other.m_flags|=b2Body.e_islandFlag;}
-for(var jn=b.m_jointList;jn!=null;jn=jn.next)
-{if(jn.joint.m_islandFlag==true)
-{continue;}
-island.AddJoint(jn.joint);jn.joint.m_islandFlag=true;other=jn.other;if(other.m_flags&b2Body.e_islandFlag)
-{continue;}
-stack[stackCount++]=other;other.m_flags|=b2Body.e_islandFlag;}}
-island.Solve(this.step,this.m_gravity);this.m_positionIterationCount=b2Math.b2Max(this.m_positionIterationCount,b2Island.m_positionIterationCount);if(this.m_allowSleep)
-{island.UpdateSleep(dt);}
-for(var i=0;i<island.m_bodyCount;++i)
-{b=island.m_bodies[i];if(b.m_flags&b2Body.e_staticFlag)
-{b.m_flags&=~b2Body.e_islandFlag;}
-if(b.IsFrozen()&&this.m_listener)
-{var response=this.m_listener.NotifyBoundaryViolated(b);if(response==b2WorldListener.b2_destroyBody)
-{this.DestroyBody(b);b=null;island.m_bodies[i]=null;}}}}
-this.m_broadPhase.Commit();},Query:function(aabb,shapes,maxCount){var results=new Array();var count=this.m_broadPhase.QueryAABB(aabb,results,maxCount);for(var i=0;i<count;++i)
-{shapes[i]=results[i];}
-return count;},GetBodyList:function(){return this.m_bodyList;},GetJointList:function(){return this.m_jointList;},GetContactList:function(){return this.m_contactList;},m_blockAllocator:null,m_stackAllocator:null,m_broadPhase:null,m_contactManager:new b2ContactManager(),m_bodyList:null,m_contactList:null,m_jointList:null,m_bodyCount:0,m_contactCount:0,m_jointCount:0,m_bodyDestroyList:null,m_gravity:null,m_allowSleep:null,m_groundBody:null,m_listener:null,m_filter:null,m_positionIterationCount:0};b2World.s_enablePositionCorrection=1;b2World.s_enableWarmStarting=1;
-var b2WorldListener=Class.create();b2WorldListener.prototype={NotifyJointDestroyed:function(joint){},NotifyBoundaryViolated:function(body)
-{return b2WorldListener.b2_freezeBody;},initialize:function(){}};b2WorldListener.b2_freezeBody=0;b2WorldListener.b2_destroyBody=1;
-var b2JointNode=Class.create();b2JointNode.prototype={other:null,joint:null,prev:null,next:null,initialize:function(){}}
-
-var b2Joint=Class.create();b2Joint.prototype={GetType:function(){return this.m_type;},GetAnchor1:function(){return null},GetAnchor2:function(){return null},GetReactionForce:function(invTimeStep){return null},GetReactionTorque:function(invTimeStep){return 0.0},GetBody1:function()
-{return this.m_body1;},GetBody2:function()
-{return this.m_body2;},GetNext:function(){return this.m_next;},GetUserData:function(){return this.m_userData;},initialize:function(def){this.m_node1=new b2JointNode();this.m_node2=new b2JointNode();this.m_type=def.type;this.m_prev=null;this.m_next=null;this.m_body1=def.body1;this.m_body2=def.body2;this.m_collideConnected=def.collideConnected;this.m_islandFlag=false;this.m_userData=def.userData;},PrepareVelocitySolver:function(){},SolveVelocityConstraints:function(step){},PreparePositionSolver:function(){},SolvePositionConstraints:function(){return false},m_type:0,m_prev:null,m_next:null,m_node1:new b2JointNode(),m_node2:new b2JointNode(),m_body1:null,m_body2:null,m_islandFlag:null,m_collideConnected:null,m_userData:null};b2Joint.Create=function(def,allocator){var joint=null;switch(def.type)
-{case b2Joint.e_distanceJoint:{joint=new b2DistanceJoint(def);}
-break;case b2Joint.e_mouseJoint:{joint=new b2MouseJoint(def);}
-break;case b2Joint.e_prismaticJoint:{joint=new b2PrismaticJoint(def);}
-break;case b2Joint.e_revoluteJoint:{joint=new b2RevoluteJoint(def);}
-break;case b2Joint.e_pulleyJoint:{joint=new b2PulleyJoint(def);}
-break;case b2Joint.e_gearJoint:{joint=new b2GearJoint(def);}
-break;default:break;}
-return joint;};b2Joint.Destroy=function(joint,allocator){};b2Joint.e_unknownJoint=0;b2Joint.e_revoluteJoint=1;b2Joint.e_prismaticJoint=2;b2Joint.e_distanceJoint=3;b2Joint.e_pulleyJoint=4;b2Joint.e_mouseJoint=5;b2Joint.e_gearJoint=6;b2Joint.e_inactiveLimit=0;b2Joint.e_atLowerLimit=1;b2Joint.e_atUpperLimit=2;b2Joint.e_equalLimits=3;
-var b2JointDef=Class.create();b2JointDef.prototype={initialize:function()
-{this.type=b2Joint.e_unknownJoint;this.userData=null;this.body1=null;this.body2=null;this.collideConnected=false;},type:0,userData:null,body1:null,body2:null,collideConnected:null}
-
-var b2DistanceJoint=Class.create();Object.extend(b2DistanceJoint.prototype,b2Joint.prototype);Object.extend(b2DistanceJoint.prototype,{initialize:function(def){this.m_node1=new b2JointNode();this.m_node2=new b2JointNode();this.m_type=def.type;this.m_prev=null;this.m_next=null;this.m_body1=def.body1;this.m_body2=def.body2;this.m_collideConnected=def.collideConnected;this.m_islandFlag=false;this.m_userData=def.userData;this.m_localAnchor1=new b2Vec2();this.m_localAnchor2=new b2Vec2();this.m_u=new b2Vec2();var tMat;var tX;var tY;tMat=this.m_body1.m_R;tX=def.anchorPoint1.x-this.m_body1.m_position.x;tY=def.anchorPoint1.y-this.m_body1.m_position.y;this.m_localAnchor1.x=tX*tMat.col1.x+tY*tMat.col1.y;this.m_localAnchor1.y=tX*tMat.col2.x+tY*tMat.col2.y;tMat=this.m_body2.m_R;tX=def.anchorPoint2.x-this.m_body2.m_position.x;tY=def.anchorPoint2.y-this.m_body2.m_position.y;this.m_localAnchor2.x=tX*tMat.col1.x+tY*tMat.col1.y;this.m_localAnchor2.y=tX*tMat.col2.x+tY*tMat.col2.y;tX=def.anchorPoint2.x-def.anchorPoint1.x;tY=def.anchorPoint2.y-def.anchorPoint1.y;this.m_length=Math.sqrt(tX*tX+tY*tY);this.m_impulse=0.0;},PrepareVelocitySolver:function(){var tMat;tMat=this.m_body1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=this.m_body2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;this.m_u.x=this.m_body2.m_position.x+r2X-this.m_body1.m_position.x-r1X;this.m_u.y=this.m_body2.m_position.y+r2Y-this.m_body1.m_position.y-r1Y;var length=Math.sqrt(this.m_u.x*this.m_u.x+this.m_u.y*this.m_u.y);if(length>b2Settings.b2_linearSlop)
-{this.m_u.Multiply(1.0/length);}
-else
-{this.m_u.SetZero();}
-var cr1u=(r1X*this.m_u.y-r1Y*this.m_u.x);var cr2u=(r2X*this.m_u.y-r2Y*this.m_u.x);this.m_mass=this.m_body1.m_invMass+this.m_body1.m_invI*cr1u*cr1u+this.m_body2.m_invMass+this.m_body2.m_invI*cr2u*cr2u;this.m_mass=1.0/this.m_mass;if(b2World.s_enableWarmStarting)
-{var PX=this.m_impulse*this.m_u.x;var PY=this.m_impulse*this.m_u.y;this.m_body1.m_linearVelocity.x-=this.m_body1.m_invMass*PX;this.m_body1.m_linearVelocity.y-=this.m_body1.m_invMass*PY;this.m_body1.m_angularVelocity-=this.m_body1.m_invI*(r1X*PY-r1Y*PX);this.m_body2.m_linearVelocity.x+=this.m_body2.m_invMass*PX;this.m_body2.m_linearVelocity.y+=this.m_body2.m_invMass*PY;this.m_body2.m_angularVelocity+=this.m_body2.m_invI*(r2X*PY-r2Y*PX);}
-else
-{this.m_impulse=0.0;}},SolveVelocityConstraints:function(step){var tMat;tMat=this.m_body1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=this.m_body2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var v1X=this.m_body1.m_linearVelocity.x+(-this.m_body1.m_angularVelocity*r1Y);var v1Y=this.m_body1.m_linearVelocity.y+(this.m_body1.m_angularVelocity*r1X);var v2X=this.m_body2.m_linearVelocity.x+(-this.m_body2.m_angularVelocity*r2Y);var v2Y=this.m_body2.m_linearVelocity.y+(this.m_body2.m_angularVelocity*r2X);var Cdot=(this.m_u.x*(v2X-v1X)+this.m_u.y*(v2Y-v1Y));var impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;var PX=impulse*this.m_u.x;var PY=impulse*this.m_u.y;this.m_body1.m_linearVelocity.x-=this.m_body1.m_invMass*PX;this.m_body1.m_linearVelocity.y-=this.m_body1.m_invMass*PY;this.m_body1.m_angularVelocity-=this.m_body1.m_invI*(r1X*PY-r1Y*PX);this.m_body2.m_linearVelocity.x+=this.m_body2.m_invMass*PX;this.m_body2.m_linearVelocity.y+=this.m_body2.m_invMass*PY;this.m_body2.m_angularVelocity+=this.m_body2.m_invI*(r2X*PY-r2Y*PX);},SolvePositionConstraints:function(){var tMat;tMat=this.m_body1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=this.m_body2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var dX=this.m_body2.m_position.x+r2X-this.m_body1.m_position.x-r1X;var dY=this.m_body2.m_position.y+r2Y-this.m_body1.m_position.y-r1Y;var length=Math.sqrt(dX*dX+dY*dY);dX/=length;dY/=length;var C=length-this.m_length;C=b2Math.b2Clamp(C,-b2Settings.b2_maxLinearCorrection,b2Settings.b2_maxLinearCorrection);var impulse=-this.m_mass*C;this.m_u.Set(dX,dY);var PX=impulse*this.m_u.x;var PY=impulse*this.m_u.y;this.m_body1.m_position.x-=this.m_body1.m_invMass*PX;this.m_body1.m_position.y-=this.m_body1.m_invMass*PY;this.m_body1.m_rotation-=this.m_body1.m_invI*(r1X*PY-r1Y*PX);this.m_body2.m_position.x+=this.m_body2.m_invMass*PX;this.m_body2.m_position.y+=this.m_body2.m_invMass*PY;this.m_body2.m_rotation+=this.m_body2.m_invI*(r2X*PY-r2Y*PX);this.m_body1.m_R.Set(this.m_body1.m_rotation);this.m_body2.m_R.Set(this.m_body2.m_rotation);return b2Math.b2Abs(C)<b2Settings.b2_linearSlop;},GetAnchor1:function(){return b2Math.AddVV(this.m_body1.m_position,b2Math.b2MulMV(this.m_body1.m_R,this.m_localAnchor1));},GetAnchor2:function(){return b2Math.AddVV(this.m_body2.m_position,b2Math.b2MulMV(this.m_body2.m_R,this.m_localAnchor2));},GetReactionForce:function(invTimeStep)
-{var F=new b2Vec2();F.SetV(this.m_u);F.Multiply(this.m_impulse*invTimeStep);return F;},GetReactionTorque:function(invTimeStep)
-{return 0.0;},m_localAnchor1:new b2Vec2(),m_localAnchor2:new b2Vec2(),m_u:new b2Vec2(),m_impulse:null,m_mass:null,m_length:null});
-var b2DistanceJointDef=Class.create();Object.extend(b2DistanceJointDef.prototype,b2JointDef.prototype);Object.extend(b2DistanceJointDef.prototype,{initialize:function()
-{this.type=b2Joint.e_unknownJoint;this.userData=null;this.body1=null;this.body2=null;this.collideConnected=false;this.anchorPoint1=new b2Vec2();this.anchorPoint2=new b2Vec2();this.type=b2Joint.e_distanceJoint;},anchorPoint1:new b2Vec2(),anchorPoint2:new b2Vec2()});
-var b2Jacobian=Class.create();b2Jacobian.prototype={linear1:new b2Vec2(),angular1:null,linear2:new b2Vec2(),angular2:null,SetZero:function(){this.linear1.SetZero();this.angular1=0.0;this.linear2.SetZero();this.angular2=0.0;},Set:function(x1,a1,x2,a2){this.linear1.SetV(x1);this.angular1=a1;this.linear2.SetV(x2);this.angular2=a2;},Compute:function(x1,a1,x2,a2){return(this.linear1.x*x1.x+this.linear1.y*x1.y)+this.angular1*a1+(this.linear2.x*x2.x+this.linear2.y*x2.y)+this.angular2*a2;},initialize:function(){this.linear1=new b2Vec2();this.linear2=new b2Vec2();}};
-var b2GearJoint=Class.create();Object.extend(b2GearJoint.prototype,b2Joint.prototype);Object.extend(b2GearJoint.prototype,{GetAnchor1:function(){var tMat=this.m_body1.m_R;return new b2Vec2(this.m_body1.m_position.x+(tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y),this.m_body1.m_position.y+(tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y));},GetAnchor2:function(){var tMat=this.m_body2.m_R;return new b2Vec2(this.m_body2.m_position.x+(tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y),this.m_body2.m_position.y+(tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y));},GetReactionForce:function(invTimeStep){return new b2Vec2();},GetReactionTorque:function(invTimeStep){return 0.0;},GetRatio:function(){return this.m_ratio;},initialize:function(def){this.m_node1=new b2JointNode();this.m_node2=new b2JointNode();this.m_type=def.type;this.m_prev=null;this.m_next=null;this.m_body1=def.body1;this.m_body2=def.body2;this.m_collideConnected=def.collideConnected;this.m_islandFlag=false;this.m_userData=def.userData;this.m_groundAnchor1=new b2Vec2();this.m_groundAnchor2=new b2Vec2();this.m_localAnchor1=new b2Vec2();this.m_localAnchor2=new b2Vec2();this.m_J=new b2Jacobian();this.m_revolute1=null;this.m_prismatic1=null;this.m_revolute2=null;this.m_prismatic2=null;var coordinate1;var coordinate2;this.m_ground1=def.joint1.m_body1;this.m_body1=def.joint1.m_body2;if(def.joint1.m_type==b2Joint.e_revoluteJoint)
-{this.m_revolute1=def.joint1;this.m_groundAnchor1.SetV(this.m_revolute1.m_localAnchor1);this.m_localAnchor1.SetV(this.m_revolute1.m_localAnchor2);coordinate1=this.m_revolute1.GetJointAngle();}
-else
-{this.m_prismatic1=def.joint1;this.m_groundAnchor1.SetV(this.m_prismatic1.m_localAnchor1);this.m_localAnchor1.SetV(this.m_prismatic1.m_localAnchor2);coordinate1=this.m_prismatic1.GetJointTranslation();}
-this.m_ground2=def.joint2.m_body1;this.m_body2=def.joint2.m_body2;if(def.joint2.m_type==b2Joint.e_revoluteJoint)
-{this.m_revolute2=def.joint2;this.m_groundAnchor2.SetV(this.m_revolute2.m_localAnchor1);this.m_localAnchor2.SetV(this.m_revolute2.m_localAnchor2);coordinate2=this.m_revolute2.GetJointAngle();}
-else
-{this.m_prismatic2=def.joint2;this.m_groundAnchor2.SetV(this.m_prismatic2.m_localAnchor1);this.m_localAnchor2.SetV(this.m_prismatic2.m_localAnchor2);coordinate2=this.m_prismatic2.GetJointTranslation();}
-this.m_ratio=def.ratio;this.m_constant=coordinate1+this.m_ratio*coordinate2;this.m_impulse=0.0;},PrepareVelocitySolver:function(){var g1=this.m_ground1;var g2=this.m_ground2;var b1=this.m_body1;var b2=this.m_body2;var ugX;var ugY;var rX;var rY;var tMat;var tVec;var crug;var K=0.0;this.m_J.SetZero();if(this.m_revolute1)
-{this.m_J.angular1=-1.0;K+=b1.m_invI;}
-else
-{tMat=g1.m_R;tVec=this.m_prismatic1.m_localXAxis1;ugX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;ugY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=b1.m_R;rX=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;rY=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;crug=rX*ugY-rY*ugX;this.m_J.linear1.Set(-ugX,-ugY);this.m_J.angular1=-crug;K+=b1.m_invMass+b1.m_invI*crug*crug;}
-if(this.m_revolute2)
-{this.m_J.angular2=-this.m_ratio;K+=this.m_ratio*this.m_ratio*b2.m_invI;}
-else
-{tMat=g2.m_R;tVec=this.m_prismatic2.m_localXAxis1;ugX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;ugY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=b2.m_R;rX=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;rY=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;crug=rX*ugY-rY*ugX;this.m_J.linear2.Set(-this.m_ratio*ugX,-this.m_ratio*ugY);this.m_J.angular2=-this.m_ratio*crug;K+=this.m_ratio*this.m_ratio*(b2.m_invMass+b2.m_invI*crug*crug);}
-this.m_mass=1.0/K;b1.m_linearVelocity.x+=b1.m_invMass*this.m_impulse*this.m_J.linear1.x;b1.m_linearVelocity.y+=b1.m_invMass*this.m_impulse*this.m_J.linear1.y;b1.m_angularVelocity+=b1.m_invI*this.m_impulse*this.m_J.angular1;b2.m_linearVelocity.x+=b2.m_invMass*this.m_impulse*this.m_J.linear2.x;b2.m_linearVelocity.y+=b2.m_invMass*this.m_impulse*this.m_J.linear2.y;b2.m_angularVelocity+=b2.m_invI*this.m_impulse*this.m_J.angular2;},SolveVelocityConstraints:function(step){var b1=this.m_body1;var b2=this.m_body2;var Cdot=this.m_J.Compute(b1.m_linearVelocity,b1.m_angularVelocity,b2.m_linearVelocity,b2.m_angularVelocity);var impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;b1.m_linearVelocity.x+=b1.m_invMass*impulse*this.m_J.linear1.x;b1.m_linearVelocity.y+=b1.m_invMass*impulse*this.m_J.linear1.y;b1.m_angularVelocity+=b1.m_invI*impulse*this.m_J.angular1;b2.m_linearVelocity.x+=b2.m_invMass*impulse*this.m_J.linear2.x;b2.m_linearVelocity.y+=b2.m_invMass*impulse*this.m_J.linear2.y;b2.m_angularVelocity+=b2.m_invI*impulse*this.m_J.angular2;},SolvePositionConstraints:function(){var linearError=0.0;var b1=this.m_body1;var b2=this.m_body2;var coordinate1;var coordinate2;if(this.m_revolute1)
-{coordinate1=this.m_revolute1.GetJointAngle();}
-else
-{coordinate1=this.m_prismatic1.GetJointTranslation();}
-if(this.m_revolute2)
-{coordinate2=this.m_revolute2.GetJointAngle();}
-else
-{coordinate2=this.m_prismatic2.GetJointTranslation();}
-var C=this.m_constant-(coordinate1+this.m_ratio*coordinate2);var impulse=-this.m_mass*C;b1.m_position.x+=b1.m_invMass*impulse*this.m_J.linear1.x;b1.m_position.y+=b1.m_invMass*impulse*this.m_J.linear1.y;b1.m_rotation+=b1.m_invI*impulse*this.m_J.angular1;b2.m_position.x+=b2.m_invMass*impulse*this.m_J.linear2.x;b2.m_position.y+=b2.m_invMass*impulse*this.m_J.linear2.y;b2.m_rotation+=b2.m_invI*impulse*this.m_J.angular2;b1.m_R.Set(b1.m_rotation);b2.m_R.Set(b2.m_rotation);return linearError<b2Settings.b2_linearSlop;},m_ground1:null,m_ground2:null,m_revolute1:null,m_prismatic1:null,m_revolute2:null,m_prismatic2:null,m_groundAnchor1:new b2Vec2(),m_groundAnchor2:new b2Vec2(),m_localAnchor1:new b2Vec2(),m_localAnchor2:new b2Vec2(),m_J:new b2Jacobian(),m_constant:null,m_ratio:null,m_mass:null,m_impulse:null});
-var b2GearJointDef=Class.create();Object.extend(b2GearJointDef.prototype,b2JointDef.prototype);Object.extend(b2GearJointDef.prototype,{initialize:function()
-{this.type=b2Joint.e_gearJoint;this.joint1=null;this.joint2=null;this.ratio=1.0;},joint1:null,joint2:null,ratio:null});
-var b2MouseJoint=Class.create();Object.extend(b2MouseJoint.prototype,b2Joint.prototype);Object.extend(b2MouseJoint.prototype,{GetAnchor1:function(){return this.m_target;},GetAnchor2:function(){var tVec=b2Math.b2MulMV(this.m_body2.m_R,this.m_localAnchor);tVec.Add(this.m_body2.m_position);return tVec;},GetReactionForce:function(invTimeStep)
-{var F=new b2Vec2();F.SetV(this.m_impulse);F.Multiply(invTimeStep);return F;},GetReactionTorque:function(invTimeStep)
-{return 0.0;},SetTarget:function(target){this.m_body2.WakeUp();this.m_target=target;},initialize:function(def){this.m_node1=new b2JointNode();this.m_node2=new b2JointNode();this.m_type=def.type;this.m_prev=null;this.m_next=null;this.m_body1=def.body1;this.m_body2=def.body2;this.m_collideConnected=def.collideConnected;this.m_islandFlag=false;this.m_userData=def.userData;this.K=new b2Mat22();this.K1=new b2Mat22();this.K2=new b2Mat22();this.m_localAnchor=new b2Vec2();this.m_target=new b2Vec2();this.m_impulse=new b2Vec2();this.m_ptpMass=new b2Mat22();this.m_C=new b2Vec2();this.m_target.SetV(def.target);var tX=this.m_target.x-this.m_body2.m_position.x;var tY=this.m_target.y-this.m_body2.m_position.y;this.m_localAnchor.x=(tX*this.m_body2.m_R.col1.x+tY*this.m_body2.m_R.col1.y);this.m_localAnchor.y=(tX*this.m_body2.m_R.col2.x+tY*this.m_body2.m_R.col2.y);this.m_maxForce=def.maxForce;this.m_impulse.SetZero();var mass=this.m_body2.m_mass;var omega=2.0*b2Settings.b2_pi*def.frequencyHz;var d=2.0*mass*def.dampingRatio*omega;var k=mass*omega*omega;this.m_gamma=1.0/(d+def.timeStep*k);this.m_beta=def.timeStep*k/(d+def.timeStep*k);},K:new b2Mat22(),K1:new b2Mat22(),K2:new b2Mat22(),PrepareVelocitySolver:function(){var b=this.m_body2;var tMat;tMat=b.m_R;var rX=tMat.col1.x*this.m_localAnchor.x+tMat.col2.x*this.m_localAnchor.y;var rY=tMat.col1.y*this.m_localAnchor.x+tMat.col2.y*this.m_localAnchor.y;var invMass=b.m_invMass;var invI=b.m_invI;this.K1.col1.x=invMass;this.K1.col2.x=0.0;this.K1.col1.y=0.0;this.K1.col2.y=invMass;this.K2.col1.x=invI*rY*rY;this.K2.col2.x=-invI*rX*rY;this.K2.col1.y=-invI*rX*rY;this.K2.col2.y=invI*rX*rX;this.K.SetM(this.K1);this.K.AddM(this.K2);this.K.col1.x+=this.m_gamma;this.K.col2.y+=this.m_gamma;this.K.Invert(this.m_ptpMass);this.m_C.x=b.m_position.x+rX-this.m_target.x;this.m_C.y=b.m_position.y+rY-this.m_target.y;b.m_angularVelocity*=0.98;var PX=this.m_impulse.x;var PY=this.m_impulse.y;b.m_linearVelocity.x+=invMass*PX;b.m_linearVelocity.y+=invMass*PY;b.m_angularVelocity+=invI*(rX*PY-rY*PX);},SolveVelocityConstraints:function(step){var body=this.m_body2;var tMat;tMat=body.m_R;var rX=tMat.col1.x*this.m_localAnchor.x+tMat.col2.x*this.m_localAnchor.y;var rY=tMat.col1.y*this.m_localAnchor.x+tMat.col2.y*this.m_localAnchor.y;var CdotX=body.m_linearVelocity.x+(-body.m_angularVelocity*rY);var CdotY=body.m_linearVelocity.y+(body.m_angularVelocity*rX);tMat=this.m_ptpMass;var tX=CdotX+(this.m_beta*step.inv_dt)*this.m_C.x+this.m_gamma*this.m_impulse.x;var tY=CdotY+(this.m_beta*step.inv_dt)*this.m_C.y+this.m_gamma*this.m_impulse.y;var impulseX=-(tMat.col1.x*tX+tMat.col2.x*tY);var impulseY=-(tMat.col1.y*tX+tMat.col2.y*tY);var oldImpulseX=this.m_impulse.x;var oldImpulseY=this.m_impulse.y;this.m_impulse.x+=impulseX;this.m_impulse.y+=impulseY;var length=this.m_impulse.Length();if(length>step.dt*this.m_maxForce)
-{this.m_impulse.Multiply(step.dt*this.m_maxForce/length);}
-impulseX=this.m_impulse.x-oldImpulseX;impulseY=this.m_impulse.y-oldImpulseY;body.m_linearVelocity.x+=body.m_invMass*impulseX;body.m_linearVelocity.y+=body.m_invMass*impulseY;body.m_angularVelocity+=body.m_invI*(rX*impulseY-rY*impulseX);},SolvePositionConstraints:function(){return true;},m_localAnchor:new b2Vec2(),m_target:new b2Vec2(),m_impulse:new b2Vec2(),m_ptpMass:new b2Mat22(),m_C:new b2Vec2(),m_maxForce:null,m_beta:null,m_gamma:null});
-var b2MouseJointDef=Class.create();Object.extend(b2MouseJointDef.prototype,b2JointDef.prototype);Object.extend(b2MouseJointDef.prototype,{initialize:function()
-{this.type=b2Joint.e_unknownJoint;this.userData=null;this.body1=null;this.body2=null;this.collideConnected=false;this.target=new b2Vec2();this.type=b2Joint.e_mouseJoint;this.maxForce=0.0;this.frequencyHz=5.0;this.dampingRatio=0.7;this.timeStep=1.0/60.0;},target:new b2Vec2(),maxForce:null,frequencyHz:null,dampingRatio:null,timeStep:null});
-var b2PrismaticJoint=Class.create();Object.extend(b2PrismaticJoint.prototype,b2Joint.prototype);Object.extend(b2PrismaticJoint.prototype,{GetAnchor1:function(){var b1=this.m_body1;var tVec=new b2Vec2();tVec.SetV(this.m_localAnchor1);tVec.MulM(b1.m_R);tVec.Add(b1.m_position);return tVec;},GetAnchor2:function(){var b2=this.m_body2;var tVec=new b2Vec2();tVec.SetV(this.m_localAnchor2);tVec.MulM(b2.m_R);tVec.Add(b2.m_position);return tVec;},GetJointTranslation:function(){var b1=this.m_body1;var b2=this.m_body2;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var p1X=b1.m_position.x+r1X;var p1Y=b1.m_position.y+r1Y;var p2X=b2.m_position.x+r2X;var p2Y=b2.m_position.y+r2Y;var dX=p2X-p1X;var dY=p2Y-p1Y;tMat=b1.m_R;var ax1X=tMat.col1.x*this.m_localXAxis1.x+tMat.col2.x*this.m_localXAxis1.y;var ax1Y=tMat.col1.y*this.m_localXAxis1.x+tMat.col2.y*this.m_localXAxis1.y;var translation=ax1X*dX+ax1Y*dY;return translation;},GetJointSpeed:function(){var b1=this.m_body1;var b2=this.m_body2;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var p1X=b1.m_position.x+r1X;var p1Y=b1.m_position.y+r1Y;var p2X=b2.m_position.x+r2X;var p2Y=b2.m_position.y+r2Y;var dX=p2X-p1X;var dY=p2Y-p1Y;tMat=b1.m_R;var ax1X=tMat.col1.x*this.m_localXAxis1.x+tMat.col2.x*this.m_localXAxis1.y;var ax1Y=tMat.col1.y*this.m_localXAxis1.x+tMat.col2.y*this.m_localXAxis1.y;var v1=b1.m_linearVelocity;var v2=b2.m_linearVelocity;var w1=b1.m_angularVelocity;var w2=b2.m_angularVelocity;var speed=(dX*(-w1*ax1Y)+dY*(w1*ax1X))+(ax1X*(((v2.x+(-w2*r2Y))-v1.x)-(-w1*r1Y))+ax1Y*(((v2.y+(w2*r2X))-v1.y)-(w1*r1X)));return speed;},GetMotorForce:function(invTimeStep){return invTimeStep*this.m_motorImpulse;},SetMotorSpeed:function(speed)
-{this.m_motorSpeed=speed;},SetMotorForce:function(force)
-{this.m_maxMotorForce=force;},GetReactionForce:function(invTimeStep)
-{var tImp=invTimeStep*this.m_limitImpulse;var tMat;tMat=this.m_body1.m_R;var ax1X=tImp*(tMat.col1.x*this.m_localXAxis1.x+tMat.col2.x*this.m_localXAxis1.y);var ax1Y=tImp*(tMat.col1.y*this.m_localXAxis1.x+tMat.col2.y*this.m_localXAxis1.y);var ay1X=tImp*(tMat.col1.x*this.m_localYAxis1.x+tMat.col2.x*this.m_localYAxis1.y);var ay1Y=tImp*(tMat.col1.y*this.m_localYAxis1.x+tMat.col2.y*this.m_localYAxis1.y);return new b2Vec2(ax1X+ay1X,ax1Y+ay1Y);},GetReactionTorque:function(invTimeStep)
-{return invTimeStep*this.m_angularImpulse;},initialize:function(def){this.m_node1=new b2JointNode();this.m_node2=new b2JointNode();this.m_type=def.type;this.m_prev=null;this.m_next=null;this.m_body1=def.body1;this.m_body2=def.body2;this.m_collideConnected=def.collideConnected;this.m_islandFlag=false;this.m_userData=def.userData;this.m_localAnchor1=new b2Vec2();this.m_localAnchor2=new b2Vec2();this.m_localXAxis1=new b2Vec2();this.m_localYAxis1=new b2Vec2();this.m_linearJacobian=new b2Jacobian();this.m_motorJacobian=new b2Jacobian();var tMat;var tX;var tY;tMat=this.m_body1.m_R;tX=(def.anchorPoint.x-this.m_body1.m_position.x);tY=(def.anchorPoint.y-this.m_body1.m_position.y);this.m_localAnchor1.Set((tX*tMat.col1.x+tY*tMat.col1.y),(tX*tMat.col2.x+tY*tMat.col2.y));tMat=this.m_body2.m_R;tX=(def.anchorPoint.x-this.m_body2.m_position.x);tY=(def.anchorPoint.y-this.m_body2.m_position.y);this.m_localAnchor2.Set((tX*tMat.col1.x+tY*tMat.col1.y),(tX*tMat.col2.x+tY*tMat.col2.y));tMat=this.m_body1.m_R;tX=def.axis.x;tY=def.axis.y;this.m_localXAxis1.Set((tX*tMat.col1.x+tY*tMat.col1.y),(tX*tMat.col2.x+tY*tMat.col2.y));this.m_localYAxis1.x=-this.m_localXAxis1.y;this.m_localYAxis1.y=this.m_localXAxis1.x;this.m_initialAngle=this.m_body2.m_rotation-this.m_body1.m_rotation;this.m_linearJacobian.SetZero();this.m_linearMass=0.0;this.m_linearImpulse=0.0;this.m_angularMass=0.0;this.m_angularImpulse=0.0;this.m_motorJacobian.SetZero();this.m_motorMass=0.0;this.m_motorImpulse=0.0;this.m_limitImpulse=0.0;this.m_limitPositionImpulse=0.0;this.m_lowerTranslation=def.lowerTranslation;this.m_upperTranslation=def.upperTranslation;this.m_maxMotorForce=def.motorForce;this.m_motorSpeed=def.motorSpeed;this.m_enableLimit=def.enableLimit;this.m_enableMotor=def.enableMotor;},PrepareVelocitySolver:function(){var b1=this.m_body1;var b2=this.m_body2;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var invMass1=b1.m_invMass;var invMass2=b2.m_invMass;var invI1=b1.m_invI;var invI2=b2.m_invI;tMat=b1.m_R;var ay1X=tMat.col1.x*this.m_localYAxis1.x+tMat.col2.x*this.m_localYAxis1.y;var ay1Y=tMat.col1.y*this.m_localYAxis1.x+tMat.col2.y*this.m_localYAxis1.y;var eX=b2.m_position.x+r2X-b1.m_position.x;var eY=b2.m_position.y+r2Y-b1.m_position.y;this.m_linearJacobian.linear1.x=-ay1X;this.m_linearJacobian.linear1.y=-ay1Y;this.m_linearJacobian.linear2.x=ay1X;this.m_linearJacobian.linear2.y=ay1Y;this.m_linearJacobian.angular1=-(eX*ay1Y-eY*ay1X);this.m_linearJacobian.angular2=r2X*ay1Y-r2Y*ay1X;this.m_linearMass=invMass1+invI1*this.m_linearJacobian.angular1*this.m_linearJacobian.angular1+
-invMass2+invI2*this.m_linearJacobian.angular2*this.m_linearJacobian.angular2;this.m_linearMass=1.0/this.m_linearMass;this.m_angularMass=1.0/(invI1+invI2);if(this.m_enableLimit||this.m_enableMotor)
-{tMat=b1.m_R;var ax1X=tMat.col1.x*this.m_localXAxis1.x+tMat.col2.x*this.m_localXAxis1.y;var ax1Y=tMat.col1.y*this.m_localXAxis1.x+tMat.col2.y*this.m_localXAxis1.y;this.m_motorJacobian.linear1.x=-ax1X;this.m_motorJacobian.linear1.y=-ax1Y;this.m_motorJacobian.linear2.x=ax1X;this.m_motorJacobian.linear2.y=ax1Y;this.m_motorJacobian.angular1=-(eX*ax1Y-eY*ax1X);this.m_motorJacobian.angular2=r2X*ax1Y-r2Y*ax1X;this.m_motorMass=invMass1+invI1*this.m_motorJacobian.angular1*this.m_motorJacobian.angular1+
-invMass2+invI2*this.m_motorJacobian.angular2*this.m_motorJacobian.angular2;this.m_motorMass=1.0/this.m_motorMass;if(this.m_enableLimit)
-{var dX=eX-r1X;var dY=eY-r1Y;var jointTranslation=ax1X*dX+ax1Y*dY;if(b2Math.b2Abs(this.m_upperTranslation-this.m_lowerTranslation)<2.0*b2Settings.b2_linearSlop)
-{this.m_limitState=b2Joint.e_equalLimits;}
-else if(jointTranslation<=this.m_lowerTranslation)
-{if(this.m_limitState!=b2Joint.e_atLowerLimit)
-{this.m_limitImpulse=0.0;}
-this.m_limitState=b2Joint.e_atLowerLimit;}
-else if(jointTranslation>=this.m_upperTranslation)
-{if(this.m_limitState!=b2Joint.e_atUpperLimit)
-{this.m_limitImpulse=0.0;}
-this.m_limitState=b2Joint.e_atUpperLimit;}
-else
-{this.m_limitState=b2Joint.e_inactiveLimit;this.m_limitImpulse=0.0;}}}
-if(this.m_enableMotor==false)
-{this.m_motorImpulse=0.0;}
-if(this.m_enableLimit==false)
-{this.m_limitImpulse=0.0;}
-if(b2World.s_enableWarmStarting)
-{var P1X=this.m_linearImpulse*this.m_linearJacobian.linear1.x+(this.m_motorImpulse+this.m_limitImpulse)*this.m_motorJacobian.linear1.x;var P1Y=this.m_linearImpulse*this.m_linearJacobian.linear1.y+(this.m_motorImpulse+this.m_limitImpulse)*this.m_motorJacobian.linear1.y;var P2X=this.m_linearImpulse*this.m_linearJacobian.linear2.x+(this.m_motorImpulse+this.m_limitImpulse)*this.m_motorJacobian.linear2.x;var P2Y=this.m_linearImpulse*this.m_linearJacobian.linear2.y+(this.m_motorImpulse+this.m_limitImpulse)*this.m_motorJacobian.linear2.y;var L1=this.m_linearImpulse*this.m_linearJacobian.angular1-this.m_angularImpulse+(this.m_motorImpulse+this.m_limitImpulse)*this.m_motorJacobian.angular1;var L2=this.m_linearImpulse*this.m_linearJacobian.angular2+this.m_angularImpulse+(this.m_motorImpulse+this.m_limitImpulse)*this.m_motorJacobian.angular2;b1.m_linearVelocity.x+=invMass1*P1X;b1.m_linearVelocity.y+=invMass1*P1Y;b1.m_angularVelocity+=invI1*L1;b2.m_linearVelocity.x+=invMass2*P2X;b2.m_linearVelocity.y+=invMass2*P2Y;b2.m_angularVelocity+=invI2*L2;}
-else
-{this.m_linearImpulse=0.0;this.m_angularImpulse=0.0;this.m_limitImpulse=0.0;this.m_motorImpulse=0.0;}
-this.m_limitPositionImpulse=0.0;},SolveVelocityConstraints:function(step){var b1=this.m_body1;var b2=this.m_body2;var invMass1=b1.m_invMass;var invMass2=b2.m_invMass;var invI1=b1.m_invI;var invI2=b2.m_invI;var oldLimitImpulse;var linearCdot=this.m_linearJacobian.Compute(b1.m_linearVelocity,b1.m_angularVelocity,b2.m_linearVelocity,b2.m_angularVelocity);var linearImpulse=-this.m_linearMass*linearCdot;this.m_linearImpulse+=linearImpulse;b1.m_linearVelocity.x+=(invMass1*linearImpulse)*this.m_linearJacobian.linear1.x;b1.m_linearVelocity.y+=(invMass1*linearImpulse)*this.m_linearJacobian.linear1.y;b1.m_angularVelocity+=invI1*linearImpulse*this.m_linearJacobian.angular1;b2.m_linearVelocity.x+=(invMass2*linearImpulse)*this.m_linearJacobian.linear2.x;b2.m_linearVelocity.y+=(invMass2*linearImpulse)*this.m_linearJacobian.linear2.y;b2.m_angularVelocity+=invI2*linearImpulse*this.m_linearJacobian.angular2;var angularCdot=b2.m_angularVelocity-b1.m_angularVelocity;var angularImpulse=-this.m_angularMass*angularCdot;this.m_angularImpulse+=angularImpulse;b1.m_angularVelocity-=invI1*angularImpulse;b2.m_angularVelocity+=invI2*angularImpulse;if(this.m_enableMotor&&this.m_limitState!=b2Joint.e_equalLimits)
-{var motorCdot=this.m_motorJacobian.Compute(b1.m_linearVelocity,b1.m_angularVelocity,b2.m_linearVelocity,b2.m_angularVelocity)-this.m_motorSpeed;var motorImpulse=-this.m_motorMass*motorCdot;var oldMotorImpulse=this.m_motorImpulse;this.m_motorImpulse=b2Math.b2Clamp(this.m_motorImpulse+motorImpulse,-step.dt*this.m_maxMotorForce,step.dt*this.m_maxMotorForce);motorImpulse=this.m_motorImpulse-oldMotorImpulse;b1.m_linearVelocity.x+=(invMass1*motorImpulse)*this.m_motorJacobian.linear1.x;b1.m_linearVelocity.y+=(invMass1*motorImpulse)*this.m_motorJacobian.linear1.y;b1.m_angularVelocity+=invI1*motorImpulse*this.m_motorJacobian.angular1;b2.m_linearVelocity.x+=(invMass2*motorImpulse)*this.m_motorJacobian.linear2.x;b2.m_linearVelocity.y+=(invMass2*motorImpulse)*this.m_motorJacobian.linear2.y;b2.m_angularVelocity+=invI2*motorImpulse*this.m_motorJacobian.angular2;}
-if(this.m_enableLimit&&this.m_limitState!=b2Joint.e_inactiveLimit)
-{var limitCdot=this.m_motorJacobian.Compute(b1.m_linearVelocity,b1.m_angularVelocity,b2.m_linearVelocity,b2.m_angularVelocity);var limitImpulse=-this.m_motorMass*limitCdot;if(this.m_limitState==b2Joint.e_equalLimits)
-{this.m_limitImpulse+=limitImpulse;}
-else if(this.m_limitState==b2Joint.e_atLowerLimit)
-{oldLimitImpulse=this.m_limitImpulse;this.m_limitImpulse=b2Math.b2Max(this.m_limitImpulse+limitImpulse,0.0);limitImpulse=this.m_limitImpulse-oldLimitImpulse;}
-else if(this.m_limitState==b2Joint.e_atUpperLimit)
-{oldLimitImpulse=this.m_limitImpulse;this.m_limitImpulse=b2Math.b2Min(this.m_limitImpulse+limitImpulse,0.0);limitImpulse=this.m_limitImpulse-oldLimitImpulse;}
-b1.m_linearVelocity.x+=(invMass1*limitImpulse)*this.m_motorJacobian.linear1.x;b1.m_linearVelocity.y+=(invMass1*limitImpulse)*this.m_motorJacobian.linear1.y;b1.m_angularVelocity+=invI1*limitImpulse*this.m_motorJacobian.angular1;b2.m_linearVelocity.x+=(invMass2*limitImpulse)*this.m_motorJacobian.linear2.x;b2.m_linearVelocity.y+=(invMass2*limitImpulse)*this.m_motorJacobian.linear2.y;b2.m_angularVelocity+=invI2*limitImpulse*this.m_motorJacobian.angular2;}},SolvePositionConstraints:function(){var limitC;var oldLimitImpulse;var b1=this.m_body1;var b2=this.m_body2;var invMass1=b1.m_invMass;var invMass2=b2.m_invMass;var invI1=b1.m_invI;var invI2=b2.m_invI;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var p1X=b1.m_position.x+r1X;var p1Y=b1.m_position.y+r1Y;var p2X=b2.m_position.x+r2X;var p2Y=b2.m_position.y+r2Y;var dX=p2X-p1X;var dY=p2Y-p1Y;tMat=b1.m_R;var ay1X=tMat.col1.x*this.m_localYAxis1.x+tMat.col2.x*this.m_localYAxis1.y;var ay1Y=tMat.col1.y*this.m_localYAxis1.x+tMat.col2.y*this.m_localYAxis1.y;var linearC=ay1X*dX+ay1Y*dY;linearC=b2Math.b2Clamp(linearC,-b2Settings.b2_maxLinearCorrection,b2Settings.b2_maxLinearCorrection);var linearImpulse=-this.m_linearMass*linearC;b1.m_position.x+=(invMass1*linearImpulse)*this.m_linearJacobian.linear1.x;b1.m_position.y+=(invMass1*linearImpulse)*this.m_linearJacobian.linear1.y;b1.m_rotation+=invI1*linearImpulse*this.m_linearJacobian.angular1;b2.m_position.x+=(invMass2*linearImpulse)*this.m_linearJacobian.linear2.x;b2.m_position.y+=(invMass2*linearImpulse)*this.m_linearJacobian.linear2.y;b2.m_rotation+=invI2*linearImpulse*this.m_linearJacobian.angular2;var positionError=b2Math.b2Abs(linearC);var angularC=b2.m_rotation-b1.m_rotation-this.m_initialAngle;angularC=b2Math.b2Clamp(angularC,-b2Settings.b2_maxAngularCorrection,b2Settings.b2_maxAngularCorrection);var angularImpulse=-this.m_angularMass*angularC;b1.m_rotation-=b1.m_invI*angularImpulse;b1.m_R.Set(b1.m_rotation);b2.m_rotation+=b2.m_invI*angularImpulse;b2.m_R.Set(b2.m_rotation);var angularError=b2Math.b2Abs(angularC);if(this.m_enableLimit&&this.m_limitState!=b2Joint.e_inactiveLimit)
-{tMat=b1.m_R;r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;p1X=b1.m_position.x+r1X;p1Y=b1.m_position.y+r1Y;p2X=b2.m_position.x+r2X;p2Y=b2.m_position.y+r2Y;dX=p2X-p1X;dY=p2Y-p1Y;tMat=b1.m_R;var ax1X=tMat.col1.x*this.m_localXAxis1.x+tMat.col2.x*this.m_localXAxis1.y;var ax1Y=tMat.col1.y*this.m_localXAxis1.x+tMat.col2.y*this.m_localXAxis1.y;var translation=(ax1X*dX+ax1Y*dY);var limitImpulse=0.0;if(this.m_limitState==b2Joint.e_equalLimits)
-{limitC=b2Math.b2Clamp(translation,-b2Settings.b2_maxLinearCorrection,b2Settings.b2_maxLinearCorrection);limitImpulse=-this.m_motorMass*limitC;positionError=b2Math.b2Max(positionError,b2Math.b2Abs(angularC));}
-else if(this.m_limitState==b2Joint.e_atLowerLimit)
-{limitC=translation-this.m_lowerTranslation;positionError=b2Math.b2Max(positionError,-limitC);limitC=b2Math.b2Clamp(limitC+b2Settings.b2_linearSlop,-b2Settings.b2_maxLinearCorrection,0.0);limitImpulse=-this.m_motorMass*limitC;oldLimitImpulse=this.m_limitPositionImpulse;this.m_limitPositionImpulse=b2Math.b2Max(this.m_limitPositionImpulse+limitImpulse,0.0);limitImpulse=this.m_limitPositionImpulse-oldLimitImpulse;}
-else if(this.m_limitState==b2Joint.e_atUpperLimit)
-{limitC=translation-this.m_upperTranslation;positionError=b2Math.b2Max(positionError,limitC);limitC=b2Math.b2Clamp(limitC-b2Settings.b2_linearSlop,0.0,b2Settings.b2_maxLinearCorrection);limitImpulse=-this.m_motorMass*limitC;oldLimitImpulse=this.m_limitPositionImpulse;this.m_limitPositionImpulse=b2Math.b2Min(this.m_limitPositionImpulse+limitImpulse,0.0);limitImpulse=this.m_limitPositionImpulse-oldLimitImpulse;}
-b1.m_position.x+=(invMass1*limitImpulse)*this.m_motorJacobian.linear1.x;b1.m_position.y+=(invMass1*limitImpulse)*this.m_motorJacobian.linear1.y;b1.m_rotation+=invI1*limitImpulse*this.m_motorJacobian.angular1;b1.m_R.Set(b1.m_rotation);b2.m_position.x+=(invMass2*limitImpulse)*this.m_motorJacobian.linear2.x;b2.m_position.y+=(invMass2*limitImpulse)*this.m_motorJacobian.linear2.y;b2.m_rotation+=invI2*limitImpulse*this.m_motorJacobian.angular2;b2.m_R.Set(b2.m_rotation);}
-return positionError<=b2Settings.b2_linearSlop&&angularError<=b2Settings.b2_angularSlop;},m_localAnchor1:new b2Vec2(),m_localAnchor2:new b2Vec2(),m_localXAxis1:new b2Vec2(),m_localYAxis1:new b2Vec2(),m_initialAngle:null,m_linearJacobian:new b2Jacobian(),m_linearMass:null,m_linearImpulse:null,m_angularMass:null,m_angularImpulse:null,m_motorJacobian:new b2Jacobian(),m_motorMass:null,m_motorImpulse:null,m_limitImpulse:null,m_limitPositionImpulse:null,m_lowerTranslation:null,m_upperTranslation:null,m_maxMotorForce:null,m_motorSpeed:null,m_enableLimit:null,m_enableMotor:null,m_limitState:0});
-var b2PrismaticJointDef=Class.create();Object.extend(b2PrismaticJointDef.prototype,b2JointDef.prototype);Object.extend(b2PrismaticJointDef.prototype,{initialize:function()
-{this.type=b2Joint.e_unknownJoint;this.userData=null;this.body1=null;this.body2=null;this.collideConnected=false;this.type=b2Joint.e_prismaticJoint;this.anchorPoint=new b2Vec2(0.0,0.0);this.axis=new b2Vec2(0.0,0.0);this.lowerTranslation=0.0;this.upperTranslation=0.0;this.motorForce=0.0;this.motorSpeed=0.0;this.enableLimit=false;this.enableMotor=false;},anchorPoint:null,axis:null,lowerTranslation:null,upperTranslation:null,motorForce:null,motorSpeed:null,enableLimit:null,enableMotor:null});
-var b2PulleyJoint=Class.create();Object.extend(b2PulleyJoint.prototype,b2Joint.prototype);Object.extend(b2PulleyJoint.prototype,{GetAnchor1:function(){var tMat=this.m_body1.m_R;return new b2Vec2(this.m_body1.m_position.x+(tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y),this.m_body1.m_position.y+(tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y));},GetAnchor2:function(){var tMat=this.m_body2.m_R;return new b2Vec2(this.m_body2.m_position.x+(tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y),this.m_body2.m_position.y+(tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y));},GetGroundPoint1:function(){return new b2Vec2(this.m_ground.m_position.x+this.m_groundAnchor1.x,this.m_ground.m_position.y+this.m_groundAnchor1.y);},GetGroundPoint2:function(){return new b2Vec2(this.m_ground.m_position.x+this.m_groundAnchor2.x,this.m_ground.m_position.y+this.m_groundAnchor2.y);},GetReactionForce:function(invTimeStep){return new b2Vec2();},GetReactionTorque:function(invTimeStep){return 0.0;},GetLength1:function(){var tMat;tMat=this.m_body1.m_R;var pX=this.m_body1.m_position.x+(tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y);var pY=this.m_body1.m_position.y+(tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y);var dX=pX-(this.m_ground.m_position.x+this.m_groundAnchor1.x);var dY=pY-(this.m_ground.m_position.y+this.m_groundAnchor1.y);return Math.sqrt(dX*dX+dY*dY);},GetLength2:function(){var tMat;tMat=this.m_body2.m_R;var pX=this.m_body2.m_position.x+(tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y);var pY=this.m_body2.m_position.y+(tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y);var dX=pX-(this.m_ground.m_position.x+this.m_groundAnchor2.x);var dY=pY-(this.m_ground.m_position.y+this.m_groundAnchor2.y);return Math.sqrt(dX*dX+dY*dY);},GetRatio:function(){return this.m_ratio;},initialize:function(def){this.m_node1=new b2JointNode();this.m_node2=new b2JointNode();this.m_type=def.type;this.m_prev=null;this.m_next=null;this.m_body1=def.body1;this.m_body2=def.body2;this.m_collideConnected=def.collideConnected;this.m_islandFlag=false;this.m_userData=def.userData;this.m_groundAnchor1=new b2Vec2();this.m_groundAnchor2=new b2Vec2();this.m_localAnchor1=new b2Vec2();this.m_localAnchor2=new b2Vec2();this.m_u1=new b2Vec2();this.m_u2=new b2Vec2();var tMat;var tX;var tY;this.m_ground=this.m_body1.m_world.m_groundBody;this.m_groundAnchor1.x=def.groundPoint1.x-this.m_ground.m_position.x;this.m_groundAnchor1.y=def.groundPoint1.y-this.m_ground.m_position.y;this.m_groundAnchor2.x=def.groundPoint2.x-this.m_ground.m_position.x;this.m_groundAnchor2.y=def.groundPoint2.y-this.m_ground.m_position.y;tMat=this.m_body1.m_R;tX=def.anchorPoint1.x-this.m_body1.m_position.x;tY=def.anchorPoint1.y-this.m_body1.m_position.y;this.m_localAnchor1.x=tX*tMat.col1.x+tY*tMat.col1.y;this.m_localAnchor1.y=tX*tMat.col2.x+tY*tMat.col2.y;tMat=this.m_body2.m_R;tX=def.anchorPoint2.x-this.m_body2.m_position.x;tY=def.anchorPoint2.y-this.m_body2.m_position.y;this.m_localAnchor2.x=tX*tMat.col1.x+tY*tMat.col1.y;this.m_localAnchor2.y=tX*tMat.col2.x+tY*tMat.col2.y;this.m_ratio=def.ratio;tX=def.groundPoint1.x-def.anchorPoint1.x;tY=def.groundPoint1.y-def.anchorPoint1.y;var d1Len=Math.sqrt(tX*tX+tY*tY);tX=def.groundPoint2.x-def.anchorPoint2.x;tY=def.groundPoint2.y-def.anchorPoint2.y;var d2Len=Math.sqrt(tX*tX+tY*tY);var length1=b2Math.b2Max(0.5*b2PulleyJoint.b2_minPulleyLength,d1Len);var length2=b2Math.b2Max(0.5*b2PulleyJoint.b2_minPulleyLength,d2Len);this.m_constant=length1+this.m_ratio*length2;this.m_maxLength1=b2Math.b2Clamp(def.maxLength1,length1,this.m_constant-this.m_ratio*b2PulleyJoint.b2_minPulleyLength);this.m_maxLength2=b2Math.b2Clamp(def.maxLength2,length2,(this.m_constant-b2PulleyJoint.b2_minPulleyLength)/this.m_ratio);this.m_pulleyImpulse=0.0;this.m_limitImpulse1=0.0;this.m_limitImpulse2=0.0;},PrepareVelocitySolver:function(){var b1=this.m_body1;var b2=this.m_body2;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var p1X=b1.m_position.x+r1X;var p1Y=b1.m_position.y+r1Y;var p2X=b2.m_position.x+r2X;var p2Y=b2.m_position.y+r2Y;var s1X=this.m_ground.m_position.x+this.m_groundAnchor1.x;var s1Y=this.m_ground.m_position.y+this.m_groundAnchor1.y;var s2X=this.m_ground.m_position.x+this.m_groundAnchor2.x;var s2Y=this.m_ground.m_position.y+this.m_groundAnchor2.y;this.m_u1.Set(p1X-s1X,p1Y-s1Y);this.m_u2.Set(p2X-s2X,p2Y-s2Y);var length1=this.m_u1.Length();var length2=this.m_u2.Length();if(length1>b2Settings.b2_linearSlop)
-{this.m_u1.Multiply(1.0/length1);}
-else
-{this.m_u1.SetZero();}
-if(length2>b2Settings.b2_linearSlop)
-{this.m_u2.Multiply(1.0/length2);}
-else
-{this.m_u2.SetZero();}
-if(length1<this.m_maxLength1)
-{this.m_limitState1=b2Joint.e_inactiveLimit;this.m_limitImpulse1=0.0;}
-else
-{this.m_limitState1=b2Joint.e_atUpperLimit;this.m_limitPositionImpulse1=0.0;}
-if(length2<this.m_maxLength2)
-{this.m_limitState2=b2Joint.e_inactiveLimit;this.m_limitImpulse2=0.0;}
-else
-{this.m_limitState2=b2Joint.e_atUpperLimit;this.m_limitPositionImpulse2=0.0;}
-var cr1u1=r1X*this.m_u1.y-r1Y*this.m_u1.x;var cr2u2=r2X*this.m_u2.y-r2Y*this.m_u2.x;this.m_limitMass1=b1.m_invMass+b1.m_invI*cr1u1*cr1u1;this.m_limitMass2=b2.m_invMass+b2.m_invI*cr2u2*cr2u2;this.m_pulleyMass=this.m_limitMass1+this.m_ratio*this.m_ratio*this.m_limitMass2;this.m_limitMass1=1.0/this.m_limitMass1;this.m_limitMass2=1.0/this.m_limitMass2;this.m_pulleyMass=1.0/this.m_pulleyMass;var P1X=(-this.m_pulleyImpulse-this.m_limitImpulse1)*this.m_u1.x;var P1Y=(-this.m_pulleyImpulse-this.m_limitImpulse1)*this.m_u1.y;var P2X=(-this.m_ratio*this.m_pulleyImpulse-this.m_limitImpulse2)*this.m_u2.x;var P2Y=(-this.m_ratio*this.m_pulleyImpulse-this.m_limitImpulse2)*this.m_u2.y;b1.m_linearVelocity.x+=b1.m_invMass*P1X;b1.m_linearVelocity.y+=b1.m_invMass*P1Y;b1.m_angularVelocity+=b1.m_invI*(r1X*P1Y-r1Y*P1X);b2.m_linearVelocity.x+=b2.m_invMass*P2X;b2.m_linearVelocity.y+=b2.m_invMass*P2Y;b2.m_angularVelocity+=b2.m_invI*(r2X*P2Y-r2Y*P2X);},SolveVelocityConstraints:function(step){var b1=this.m_body1;var b2=this.m_body2;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var v1X;var v1Y;var v2X;var v2Y;var P1X;var P1Y;var P2X;var P2Y;var Cdot;var impulse;var oldLimitImpulse;v1X=b1.m_linearVelocity.x+(-b1.m_angularVelocity*r1Y);v1Y=b1.m_linearVelocity.y+(b1.m_angularVelocity*r1X);v2X=b2.m_linearVelocity.x+(-b2.m_angularVelocity*r2Y);v2Y=b2.m_linearVelocity.y+(b2.m_angularVelocity*r2X);Cdot=-(this.m_u1.x*v1X+this.m_u1.y*v1Y)-this.m_ratio*(this.m_u2.x*v2X+this.m_u2.y*v2Y);impulse=-this.m_pulleyMass*Cdot;this.m_pulleyImpulse+=impulse;P1X=-impulse*this.m_u1.x;P1Y=-impulse*this.m_u1.y;P2X=-this.m_ratio*impulse*this.m_u2.x;P2Y=-this.m_ratio*impulse*this.m_u2.y;b1.m_linearVelocity.x+=b1.m_invMass*P1X;b1.m_linearVelocity.y+=b1.m_invMass*P1Y;b1.m_angularVelocity+=b1.m_invI*(r1X*P1Y-r1Y*P1X);b2.m_linearVelocity.x+=b2.m_invMass*P2X;b2.m_linearVelocity.y+=b2.m_invMass*P2Y;b2.m_angularVelocity+=b2.m_invI*(r2X*P2Y-r2Y*P2X);if(this.m_limitState1==b2Joint.e_atUpperLimit)
-{v1X=b1.m_linearVelocity.x+(-b1.m_angularVelocity*r1Y);v1Y=b1.m_linearVelocity.y+(b1.m_angularVelocity*r1X);Cdot=-(this.m_u1.x*v1X+this.m_u1.y*v1Y);impulse=-this.m_limitMass1*Cdot;oldLimitImpulse=this.m_limitImpulse1;this.m_limitImpulse1=b2Math.b2Max(0.0,this.m_limitImpulse1+impulse);impulse=this.m_limitImpulse1-oldLimitImpulse;P1X=-impulse*this.m_u1.x;P1Y=-impulse*this.m_u1.y;b1.m_linearVelocity.x+=b1.m_invMass*P1X;b1.m_linearVelocity.y+=b1.m_invMass*P1Y;b1.m_angularVelocity+=b1.m_invI*(r1X*P1Y-r1Y*P1X);}
-if(this.m_limitState2==b2Joint.e_atUpperLimit)
-{v2X=b2.m_linearVelocity.x+(-b2.m_angularVelocity*r2Y);v2Y=b2.m_linearVelocity.y+(b2.m_angularVelocity*r2X);Cdot=-(this.m_u2.x*v2X+this.m_u2.y*v2Y);impulse=-this.m_limitMass2*Cdot;oldLimitImpulse=this.m_limitImpulse2;this.m_limitImpulse2=b2Math.b2Max(0.0,this.m_limitImpulse2+impulse);impulse=this.m_limitImpulse2-oldLimitImpulse;P2X=-impulse*this.m_u2.x;P2Y=-impulse*this.m_u2.y;b2.m_linearVelocity.x+=b2.m_invMass*P2X;b2.m_linearVelocity.y+=b2.m_invMass*P2Y;b2.m_angularVelocity+=b2.m_invI*(r2X*P2Y-r2Y*P2X);}},SolvePositionConstraints:function(){var b1=this.m_body1;var b2=this.m_body2;var tMat;var s1X=this.m_ground.m_position.x+this.m_groundAnchor1.x;var s1Y=this.m_ground.m_position.y+this.m_groundAnchor1.y;var s2X=this.m_ground.m_position.x+this.m_groundAnchor2.x;var s2Y=this.m_ground.m_position.y+this.m_groundAnchor2.y;var r1X;var r1Y;var r2X;var r2Y;var p1X;var p1Y;var p2X;var p2Y;var length1;var length2;var C;var impulse;var oldLimitPositionImpulse;var linearError=0.0;{tMat=b1.m_R;r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;p1X=b1.m_position.x+r1X;p1Y=b1.m_position.y+r1Y;p2X=b2.m_position.x+r2X;p2Y=b2.m_position.y+r2Y;this.m_u1.Set(p1X-s1X,p1Y-s1Y);this.m_u2.Set(p2X-s2X,p2Y-s2Y);length1=this.m_u1.Length();length2=this.m_u2.Length();if(length1>b2Settings.b2_linearSlop)
-{this.m_u1.Multiply(1.0/length1);}
-else
-{this.m_u1.SetZero();}
-if(length2>b2Settings.b2_linearSlop)
-{this.m_u2.Multiply(1.0/length2);}
-else
-{this.m_u2.SetZero();}
-C=this.m_constant-length1-this.m_ratio*length2;linearError=b2Math.b2Max(linearError,Math.abs(C));C=b2Math.b2Clamp(C,-b2Settings.b2_maxLinearCorrection,b2Settings.b2_maxLinearCorrection);impulse=-this.m_pulleyMass*C;p1X=-impulse*this.m_u1.x;p1Y=-impulse*this.m_u1.y;p2X=-this.m_ratio*impulse*this.m_u2.x;p2Y=-this.m_ratio*impulse*this.m_u2.y;b1.m_position.x+=b1.m_invMass*p1X;b1.m_position.y+=b1.m_invMass*p1Y;b1.m_rotation+=b1.m_invI*(r1X*p1Y-r1Y*p1X);b2.m_position.x+=b2.m_invMass*p2X;b2.m_position.y+=b2.m_invMass*p2Y;b2.m_rotation+=b2.m_invI*(r2X*p2Y-r2Y*p2X);b1.m_R.Set(b1.m_rotation);b2.m_R.Set(b2.m_rotation);}
-if(this.m_limitState1==b2Joint.e_atUpperLimit)
-{tMat=b1.m_R;r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;p1X=b1.m_position.x+r1X;p1Y=b1.m_position.y+r1Y;this.m_u1.Set(p1X-s1X,p1Y-s1Y);length1=this.m_u1.Length();if(length1>b2Settings.b2_linearSlop)
-{this.m_u1.x*=1.0/length1;this.m_u1.y*=1.0/length1;}
-else
-{this.m_u1.SetZero();}
-C=this.m_maxLength1-length1;linearError=b2Math.b2Max(linearError,-C);C=b2Math.b2Clamp(C+b2Settings.b2_linearSlop,-b2Settings.b2_maxLinearCorrection,0.0);impulse=-this.m_limitMass1*C;oldLimitPositionImpulse=this.m_limitPositionImpulse1;this.m_limitPositionImpulse1=b2Math.b2Max(0.0,this.m_limitPositionImpulse1+impulse);impulse=this.m_limitPositionImpulse1-oldLimitPositionImpulse;p1X=-impulse*this.m_u1.x;p1Y=-impulse*this.m_u1.y;b1.m_position.x+=b1.m_invMass*p1X;b1.m_position.y+=b1.m_invMass*p1Y;b1.m_rotation+=b1.m_invI*(r1X*p1Y-r1Y*p1X);b1.m_R.Set(b1.m_rotation);}
-if(this.m_limitState2==b2Joint.e_atUpperLimit)
-{tMat=b2.m_R;r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;p2X=b2.m_position.x+r2X;p2Y=b2.m_position.y+r2Y;this.m_u2.Set(p2X-s2X,p2Y-s2Y);length2=this.m_u2.Length();if(length2>b2Settings.b2_linearSlop)
-{this.m_u2.x*=1.0/length2;this.m_u2.y*=1.0/length2;}
-else
-{this.m_u2.SetZero();}
-C=this.m_maxLength2-length2;linearError=b2Math.b2Max(linearError,-C);C=b2Math.b2Clamp(C+b2Settings.b2_linearSlop,-b2Settings.b2_maxLinearCorrection,0.0);impulse=-this.m_limitMass2*C;oldLimitPositionImpulse=this.m_limitPositionImpulse2;this.m_limitPositionImpulse2=b2Math.b2Max(0.0,this.m_limitPositionImpulse2+impulse);impulse=this.m_limitPositionImpulse2-oldLimitPositionImpulse;p2X=-impulse*this.m_u2.x;p2Y=-impulse*this.m_u2.y;b2.m_position.x+=b2.m_invMass*p2X;b2.m_position.y+=b2.m_invMass*p2Y;b2.m_rotation+=b2.m_invI*(r2X*p2Y-r2Y*p2X);b2.m_R.Set(b2.m_rotation);}
-return linearError<b2Settings.b2_linearSlop;},m_ground:null,m_groundAnchor1:new b2Vec2(),m_groundAnchor2:new b2Vec2(),m_localAnchor1:new b2Vec2(),m_localAnchor2:new b2Vec2(),m_u1:new b2Vec2(),m_u2:new b2Vec2(),m_constant:null,m_ratio:null,m_maxLength1:null,m_maxLength2:null,m_pulleyMass:null,m_limitMass1:null,m_limitMass2:null,m_pulleyImpulse:null,m_limitImpulse1:null,m_limitImpulse2:null,m_limitPositionImpulse1:null,m_limitPositionImpulse2:null,m_limitState1:0,m_limitState2:0});b2PulleyJoint.b2_minPulleyLength=b2Settings.b2_lengthUnitsPerMeter;
-var b2PulleyJointDef=Class.create();Object.extend(b2PulleyJointDef.prototype,b2JointDef.prototype);Object.extend(b2PulleyJointDef.prototype,{initialize:function()
-{this.type=b2Joint.e_unknownJoint;this.userData=null;this.body1=null;this.body2=null;this.collideConnected=false;this.groundPoint1=new b2Vec2();this.groundPoint2=new b2Vec2();this.anchorPoint1=new b2Vec2();this.anchorPoint2=new b2Vec2();this.type=b2Joint.e_pulleyJoint;this.groundPoint1.Set(-1.0,1.0);this.groundPoint2.Set(1.0,1.0);this.anchorPoint1.Set(-1.0,0.0);this.anchorPoint2.Set(1.0,0.0);this.maxLength1=0.5*b2PulleyJoint.b2_minPulleyLength;this.maxLength2=0.5*b2PulleyJoint.b2_minPulleyLength;this.ratio=1.0;this.collideConnected=true;},groundPoint1:new b2Vec2(),groundPoint2:new b2Vec2(),anchorPoint1:new b2Vec2(),anchorPoint2:new b2Vec2(),maxLength1:null,maxLength2:null,ratio:null});
-var b2RevoluteJoint=Class.create();Object.extend(b2RevoluteJoint.prototype,b2Joint.prototype);Object.extend(b2RevoluteJoint.prototype,{GetAnchor1:function(){var tMat=this.m_body1.m_R;return new b2Vec2(this.m_body1.m_position.x+(tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y),this.m_body1.m_position.y+(tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y));},GetAnchor2:function(){var tMat=this.m_body2.m_R;return new b2Vec2(this.m_body2.m_position.x+(tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y),this.m_body2.m_position.y+(tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y));},GetJointAngle:function(){return this.m_body2.m_rotation-this.m_body1.m_rotation;},GetJointSpeed:function(){return this.m_body2.m_angularVelocity-this.m_body1.m_angularVelocity;},GetMotorTorque:function(invTimeStep){return invTimeStep*this.m_motorImpulse;},SetMotorSpeed:function(speed)
-{this.m_motorSpeed=speed;},SetMotorTorque:function(torque)
-{this.m_maxMotorTorque=torque;},GetReactionForce:function(invTimeStep)
-{var tVec=this.m_ptpImpulse.Copy();tVec.Multiply(invTimeStep);return tVec;},GetReactionTorque:function(invTimeStep)
-{return invTimeStep*this.m_limitImpulse;},initialize:function(def){this.m_node1=new b2JointNode();this.m_node2=new b2JointNode();this.m_type=def.type;this.m_prev=null;this.m_next=null;this.m_body1=def.body1;this.m_body2=def.body2;this.m_collideConnected=def.collideConnected;this.m_islandFlag=false;this.m_userData=def.userData;this.K=new b2Mat22();this.K1=new b2Mat22();this.K2=new b2Mat22();this.K3=new b2Mat22();this.m_localAnchor1=new b2Vec2();this.m_localAnchor2=new b2Vec2();this.m_ptpImpulse=new b2Vec2();this.m_ptpMass=new b2Mat22();var tMat;var tX;var tY;tMat=this.m_body1.m_R;tX=def.anchorPoint.x-this.m_body1.m_position.x;tY=def.anchorPoint.y-this.m_body1.m_position.y;this.m_localAnchor1.x=tX*tMat.col1.x+tY*tMat.col1.y;this.m_localAnchor1.y=tX*tMat.col2.x+tY*tMat.col2.y;tMat=this.m_body2.m_R;tX=def.anchorPoint.x-this.m_body2.m_position.x;tY=def.anchorPoint.y-this.m_body2.m_position.y;this.m_localAnchor2.x=tX*tMat.col1.x+tY*tMat.col1.y;this.m_localAnchor2.y=tX*tMat.col2.x+tY*tMat.col2.y;this.m_intialAngle=this.m_body2.m_rotation-this.m_body1.m_rotation;this.m_ptpImpulse.Set(0.0,0.0);this.m_motorImpulse=0.0;this.m_limitImpulse=0.0;this.m_limitPositionImpulse=0.0;this.m_lowerAngle=def.lowerAngle;this.m_upperAngle=def.upperAngle;this.m_maxMotorTorque=def.motorTorque;this.m_motorSpeed=def.motorSpeed;this.m_enableLimit=def.enableLimit;this.m_enableMotor=def.enableMotor;},K:new b2Mat22(),K1:new b2Mat22(),K2:new b2Mat22(),K3:new b2Mat22(),PrepareVelocitySolver:function(){var b1=this.m_body1;var b2=this.m_body2;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var invMass1=b1.m_invMass;var invMass2=b2.m_invMass;var invI1=b1.m_invI;var invI2=b2.m_invI;this.K1.col1.x=invMass1+invMass2;this.K1.col2.x=0.0;this.K1.col1.y=0.0;this.K1.col2.y=invMass1+invMass2;this.K2.col1.x=invI1*r1Y*r1Y;this.K2.col2.x=-invI1*r1X*r1Y;this.K2.col1.y=-invI1*r1X*r1Y;this.K2.col2.y=invI1*r1X*r1X;this.K3.col1.x=invI2*r2Y*r2Y;this.K3.col2.x=-invI2*r2X*r2Y;this.K3.col1.y=-invI2*r2X*r2Y;this.K3.col2.y=invI2*r2X*r2X;this.K.SetM(this.K1);this.K.AddM(this.K2);this.K.AddM(this.K3);this.K.Invert(this.m_ptpMass);this.m_motorMass=1.0/(invI1+invI2);if(this.m_enableMotor==false)
-{this.m_motorImpulse=0.0;}
-if(this.m_enableLimit)
-{var jointAngle=b2.m_rotation-b1.m_rotation-this.m_intialAngle;if(b2Math.b2Abs(this.m_upperAngle-this.m_lowerAngle)<2.0*b2Settings.b2_angularSlop)
-{this.m_limitState=b2Joint.e_equalLimits;}
-else if(jointAngle<=this.m_lowerAngle)
-{if(this.m_limitState!=b2Joint.e_atLowerLimit)
-{this.m_limitImpulse=0.0;}
-this.m_limitState=b2Joint.e_atLowerLimit;}
-else if(jointAngle>=this.m_upperAngle)
-{if(this.m_limitState!=b2Joint.e_atUpperLimit)
-{this.m_limitImpulse=0.0;}
-this.m_limitState=b2Joint.e_atUpperLimit;}
-else
-{this.m_limitState=b2Joint.e_inactiveLimit;this.m_limitImpulse=0.0;}}
-else
-{this.m_limitImpulse=0.0;}
-if(b2World.s_enableWarmStarting)
-{b1.m_linearVelocity.x-=invMass1*this.m_ptpImpulse.x;b1.m_linearVelocity.y-=invMass1*this.m_ptpImpulse.y;b1.m_angularVelocity-=invI1*((r1X*this.m_ptpImpulse.y-r1Y*this.m_ptpImpulse.x)+this.m_motorImpulse+this.m_limitImpulse);b2.m_linearVelocity.x+=invMass2*this.m_ptpImpulse.x;b2.m_linearVelocity.y+=invMass2*this.m_ptpImpulse.y;b2.m_angularVelocity+=invI2*((r2X*this.m_ptpImpulse.y-r2Y*this.m_ptpImpulse.x)+this.m_motorImpulse+this.m_limitImpulse);}
-else{this.m_ptpImpulse.SetZero();this.m_motorImpulse=0.0;this.m_limitImpulse=0.0;}
-this.m_limitPositionImpulse=0.0;},SolveVelocityConstraints:function(step){var b1=this.m_body1;var b2=this.m_body2;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var oldLimitImpulse;var ptpCdotX=b2.m_linearVelocity.x+(-b2.m_angularVelocity*r2Y)-b1.m_linearVelocity.x-(-b1.m_angularVelocity*r1Y);var ptpCdotY=b2.m_linearVelocity.y+(b2.m_angularVelocity*r2X)-b1.m_linearVelocity.y-(b1.m_angularVelocity*r1X);var ptpImpulseX=-(this.m_ptpMass.col1.x*ptpCdotX+this.m_ptpMass.col2.x*ptpCdotY);var ptpImpulseY=-(this.m_ptpMass.col1.y*ptpCdotX+this.m_ptpMass.col2.y*ptpCdotY);this.m_ptpImpulse.x+=ptpImpulseX;this.m_ptpImpulse.y+=ptpImpulseY;b1.m_linearVelocity.x-=b1.m_invMass*ptpImpulseX;b1.m_linearVelocity.y-=b1.m_invMass*ptpImpulseY;b1.m_angularVelocity-=b1.m_invI*(r1X*ptpImpulseY-r1Y*ptpImpulseX);b2.m_linearVelocity.x+=b2.m_invMass*ptpImpulseX;b2.m_linearVelocity.y+=b2.m_invMass*ptpImpulseY;b2.m_angularVelocity+=b2.m_invI*(r2X*ptpImpulseY-r2Y*ptpImpulseX);if(this.m_enableMotor&&this.m_limitState!=b2Joint.e_equalLimits)
-{var motorCdot=b2.m_angularVelocity-b1.m_angularVelocity-this.m_motorSpeed;var motorImpulse=-this.m_motorMass*motorCdot;var oldMotorImpulse=this.m_motorImpulse;this.m_motorImpulse=b2Math.b2Clamp(this.m_motorImpulse+motorImpulse,-step.dt*this.m_maxMotorTorque,step.dt*this.m_maxMotorTorque);motorImpulse=this.m_motorImpulse-oldMotorImpulse;b1.m_angularVelocity-=b1.m_invI*motorImpulse;b2.m_angularVelocity+=b2.m_invI*motorImpulse;}
-if(this.m_enableLimit&&this.m_limitState!=b2Joint.e_inactiveLimit)
-{var limitCdot=b2.m_angularVelocity-b1.m_angularVelocity;var limitImpulse=-this.m_motorMass*limitCdot;if(this.m_limitState==b2Joint.e_equalLimits)
-{this.m_limitImpulse+=limitImpulse;}
-else if(this.m_limitState==b2Joint.e_atLowerLimit)
-{oldLimitImpulse=this.m_limitImpulse;this.m_limitImpulse=b2Math.b2Max(this.m_limitImpulse+limitImpulse,0.0);limitImpulse=this.m_limitImpulse-oldLimitImpulse;}
-else if(this.m_limitState==b2Joint.e_atUpperLimit)
-{oldLimitImpulse=this.m_limitImpulse;this.m_limitImpulse=b2Math.b2Min(this.m_limitImpulse+limitImpulse,0.0);limitImpulse=this.m_limitImpulse-oldLimitImpulse;}
-b1.m_angularVelocity-=b1.m_invI*limitImpulse;b2.m_angularVelocity+=b2.m_invI*limitImpulse;}},SolvePositionConstraints:function(){var oldLimitImpulse;var limitC;var b1=this.m_body1;var b2=this.m_body2;var positionError=0.0;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var p1X=b1.m_position.x+r1X;var p1Y=b1.m_position.y+r1Y;var p2X=b2.m_position.x+r2X;var p2Y=b2.m_position.y+r2Y;var ptpCX=p2X-p1X;var ptpCY=p2Y-p1Y;positionError=Math.sqrt(ptpCX*ptpCX+ptpCY*ptpCY);var invMass1=b1.m_invMass;var invMass2=b2.m_invMass;var invI1=b1.m_invI;var invI2=b2.m_invI;this.K1.col1.x=invMass1+invMass2;this.K1.col2.x=0.0;this.K1.col1.y=0.0;this.K1.col2.y=invMass1+invMass2;this.K2.col1.x=invI1*r1Y*r1Y;this.K2.col2.x=-invI1*r1X*r1Y;this.K2.col1.y=-invI1*r1X*r1Y;this.K2.col2.y=invI1*r1X*r1X;this.K3.col1.x=invI2*r2Y*r2Y;this.K3.col2.x=-invI2*r2X*r2Y;this.K3.col1.y=-invI2*r2X*r2Y;this.K3.col2.y=invI2*r2X*r2X;this.K.SetM(this.K1);this.K.AddM(this.K2);this.K.AddM(this.K3);this.K.Solve(b2RevoluteJoint.tImpulse,-ptpCX,-ptpCY);var impulseX=b2RevoluteJoint.tImpulse.x;var impulseY=b2RevoluteJoint.tImpulse.y;b1.m_position.x-=b1.m_invMass*impulseX;b1.m_position.y-=b1.m_invMass*impulseY;b1.m_rotation-=b1.m_invI*(r1X*impulseY-r1Y*impulseX);b1.m_R.Set(b1.m_rotation);b2.m_position.x+=b2.m_invMass*impulseX;b2.m_position.y+=b2.m_invMass*impulseY;b2.m_rotation+=b2.m_invI*(r2X*impulseY-r2Y*impulseX);b2.m_R.Set(b2.m_rotation);var angularError=0.0;if(this.m_enableLimit&&this.m_limitState!=b2Joint.e_inactiveLimit)
-{var angle=b2.m_rotation-b1.m_rotation-this.m_intialAngle;var limitImpulse=0.0;if(this.m_limitState==b2Joint.e_equalLimits)
-{limitC=b2Math.b2Clamp(angle,-b2Settings.b2_maxAngularCorrection,b2Settings.b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*limitC;angularError=b2Math.b2Abs(limitC);}
-else if(this.m_limitState==b2Joint.e_atLowerLimit)
-{limitC=angle-this.m_lowerAngle;angularError=b2Math.b2Max(0.0,-limitC);limitC=b2Math.b2Clamp(limitC+b2Settings.b2_angularSlop,-b2Settings.b2_maxAngularCorrection,0.0);limitImpulse=-this.m_motorMass*limitC;oldLimitImpulse=this.m_limitPositionImpulse;this.m_limitPositionImpulse=b2Math.b2Max(this.m_limitPositionImpulse+limitImpulse,0.0);limitImpulse=this.m_limitPositionImpulse-oldLimitImpulse;}
-else if(this.m_limitState==b2Joint.e_atUpperLimit)
-{limitC=angle-this.m_upperAngle;angularError=b2Math.b2Max(0.0,limitC);limitC=b2Math.b2Clamp(limitC-b2Settings.b2_angularSlop,0.0,b2Settings.b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*limitC;oldLimitImpulse=this.m_limitPositionImpulse;this.m_limitPositionImpulse=b2Math.b2Min(this.m_limitPositionImpulse+limitImpulse,0.0);limitImpulse=this.m_limitPositionImpulse-oldLimitImpulse;}
-b1.m_rotation-=b1.m_invI*limitImpulse;b1.m_R.Set(b1.m_rotation);b2.m_rotation+=b2.m_invI*limitImpulse;b2.m_R.Set(b2.m_rotation);}
-return positionError<=b2Settings.b2_linearSlop&&angularError<=b2Settings.b2_angularSlop;},m_localAnchor1:new b2Vec2(),m_localAnchor2:new b2Vec2(),m_ptpImpulse:new b2Vec2(),m_motorImpulse:null,m_limitImpulse:null,m_limitPositionImpulse:null,m_ptpMass:new b2Mat22(),m_motorMass:null,m_intialAngle:null,m_lowerAngle:null,m_upperAngle:null,m_maxMotorTorque:null,m_motorSpeed:null,m_enableLimit:null,m_enableMotor:null,m_limitState:0});b2RevoluteJoint.tImpulse=new b2Vec2();
-var b2RevoluteJointDef=Class.create();Object.extend(b2RevoluteJointDef.prototype,b2JointDef.prototype);Object.extend(b2RevoluteJointDef.prototype,{initialize:function()
-{this.type=b2Joint.e_unknownJoint;this.userData=null;this.body1=null;this.body2=null;this.collideConnected=false;this.type=b2Joint.e_revoluteJoint;this.anchorPoint=new b2Vec2(0.0,0.0);this.lowerAngle=0.0;this.upperAngle=0.0;this.motorTorque=0.0;this.motorSpeed=0.0;this.enableLimit=false;this.enableMotor=false;},anchorPoint:null,lowerAngle:null,upperAngle:null,motorTorque:null,motorSpeed:null,enableLimit:null,enableMotor:null});
diff --git a/o3d/samples/box2d-3d/third_party/prototype-1.6.0.2.js b/o3d/samples/box2d-3d/third_party/prototype-1.6.0.2.js
deleted file mode 100644
index 6385503..0000000
--- a/o3d/samples/box2d-3d/third_party/prototype-1.6.0.2.js
+++ /dev/null
@@ -1,4221 +0,0 @@
-/* Prototype JavaScript framework, version 1.6.0.2
- * (c) 2005-2008 Sam Stephenson
- *
- * Prototype is freely distributable under the terms of an MIT-style license.
- * For details, see the Prototype web site: http://www.prototypejs.org/
- *
- *--------------------------------------------------------------------------*/
-
-var Prototype = {
- Version: '1.6.0.2',
-
- Browser: {
- IE: !!(window.attachEvent && !window.opera),
- Opera: !!window.opera,
- WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
- Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
- MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
- },
-
- BrowserFeatures: {
- XPath: !!document.evaluate,
- ElementExtensions: !!window.HTMLElement,
- SpecificElementExtensions:
- document.createElement('div').__proto__ &&
- document.createElement('div').__proto__ !==
- document.createElement('form').__proto__
- },
-
- ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
- JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
-
- emptyFunction: function() { },
- K: function(x) { return x }
-};
-
-if (Prototype.Browser.MobileSafari)
- Prototype.BrowserFeatures.SpecificElementExtensions = false;
-
-
-/* Based on Alex Arnell's inheritance implementation. */
-var Class = {
- create: function() {
- var parent = null, properties = $A(arguments);
- if (Object.isFunction(properties[0]))
- parent = properties.shift();
-
- function klass() {
- this.initialize.apply(this, arguments);
- }
-
- Object.extend(klass, Class.Methods);
- klass.superclass = parent;
- klass.subclasses = [];
-
- if (parent) {
- var subclass = function() { };
- subclass.prototype = parent.prototype;
- klass.prototype = new subclass;
- parent.subclasses.push(klass);
- }
-
- for (var i = 0; i < properties.length; i++)
- klass.addMethods(properties[i]);
-
- if (!klass.prototype.initialize)
- klass.prototype.initialize = Prototype.emptyFunction;
-
- klass.prototype.constructor = klass;
-
- return klass;
- }
-};
-
-Class.Methods = {
- addMethods: function(source) {
- var ancestor = this.superclass && this.superclass.prototype;
- var properties = Object.keys(source);
-
- if (!Object.keys({ toString: true }).length)
- properties.push("toString", "valueOf");
-
- for (var i = 0, length = properties.length; i < length; i++) {
- var property = properties[i], value = source[property];
- if (ancestor && Object.isFunction(value) &&
- value.argumentNames().first() == "$super") {
- var method = value, value = Object.extend((function(m) {
- return function() { return ancestor[m].apply(this, arguments) };
- })(property).wrap(method), {
- valueOf: function() { return method },
- toString: function() { return method.toString() }
- });
- }
- this.prototype[property] = value;
- }
-
- return this;
- }
-};
-
-var Abstract = { };
-
-Object.extend = function(destination, source) {
- for (var property in source)
- destination[property] = source[property];
- return destination;
-};
-
-Object.extend(Object, {
- inspect: function(object) {
- try {
- if (Object.isUndefined(object)) return 'undefined';
- if (object === null) return 'null';
- return object.inspect ? object.inspect() : String(object);
- } catch (e) {
- if (e instanceof RangeError) return '...';
- throw e;
- }
- },
-
- toJSON: function(object) {
- var type = typeof object;
- switch (type) {
- case 'undefined':
- case 'function':
- case 'unknown': return;
- case 'boolean': return object.toString();
- }
-
- if (object === null) return 'null';
- if (object.toJSON) return object.toJSON();
- if (Object.isElement(object)) return;
-
- var results = [];
- for (var property in object) {
- var value = Object.toJSON(object[property]);
- if (!Object.isUndefined(value))
- results.push(property.toJSON() + ': ' + value);
- }
-
- return '{' + results.join(', ') + '}';
- },
-
- toQueryString: function(object) {
- return $H(object).toQueryString();
- },
-
- toHTML: function(object) {
- return object && object.toHTML ? object.toHTML() : String.interpret(object);
- },
-
- keys: function(object) {
- var keys = [];
- for (var property in object)
- keys.push(property);
- return keys;
- },
-
- values: function(object) {
- var values = [];
- for (var property in object)
- values.push(object[property]);
- return values;
- },
-
- clone: function(object) {
- return Object.extend({ }, object);
- },
-
- isElement: function(object) {
- return object && object.nodeType == 1;
- },
-
- isArray: function(object) {
- return object != null && typeof object == "object" &&
- 'splice' in object && 'join' in object;
- },
-
- isHash: function(object) {
- return object instanceof Hash;
- },
-
- isFunction: function(object) {
- return typeof object == "function";
- },
-
- isString: function(object) {
- return typeof object == "string";
- },
-
- isNumber: function(object) {
- return typeof object == "number";
- },
-
- isUndefined: function(object) {
- return typeof object == "undefined";
- }
-});
-
-Object.extend(Function.prototype, {
- argumentNames: function() {
- var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
- return names.length == 1 && !names[0] ? [] : names;
- },
-
- bind: function() {
- if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
- var __method = this, args = $A(arguments), object = args.shift();
- return function() {
- return __method.apply(object, args.concat($A(arguments)));
- }
- },
-
- bindAsEventListener: function() {
- var __method = this, args = $A(arguments), object = args.shift();
- return function(event) {
- return __method.apply(object, [event || window.event].concat(args));
- }
- },
-
- curry: function() {
- if (!arguments.length) return this;
- var __method = this, args = $A(arguments);
- return function() {
- return __method.apply(this, args.concat($A(arguments)));
- }
- },
-
- delay: function() {
- var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
- return window.setTimeout(function() {
- return __method.apply(__method, args);
- }, timeout);
- },
-
- wrap: function(wrapper) {
- var __method = this;
- return function() {
- return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
- }
- },
-
- methodize: function() {
- if (this._methodized) return this._methodized;
- var __method = this;
- return this._methodized = function() {
- return __method.apply(null, [this].concat($A(arguments)));
- };
- }
-});
-
-Function.prototype.defer = Function.prototype.delay.curry(0.01);
-
-Date.prototype.toJSON = function() {
- return '"' + this.getUTCFullYear() + '-' +
- (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
- this.getUTCDate().toPaddedString(2) + 'T' +
- this.getUTCHours().toPaddedString(2) + ':' +
- this.getUTCMinutes().toPaddedString(2) + ':' +
- this.getUTCSeconds().toPaddedString(2) + 'Z"';
-};
-
-var Try = {
- these: function() {
- var returnValue;
-
- for (var i = 0, length = arguments.length; i < length; i++) {
- var lambda = arguments[i];
- try {
- returnValue = lambda();
- break;
- } catch (e) { }
- }
-
- return returnValue;
- }
-};
-
-RegExp.prototype.match = RegExp.prototype.test;
-
-RegExp.escape = function(str) {
- return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
-};
-
-/*--------------------------------------------------------------------------*/
-
-var PeriodicalExecuter = Class.create({
- initialize: function(callback, frequency) {
- this.callback = callback;
- this.frequency = frequency;
- this.currentlyExecuting = false;
-
- this.registerCallback();
- },
-
- registerCallback: function() {
- this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
- },
-
- execute: function() {
- this.callback(this);
- },
-
- stop: function() {
- if (!this.timer) return;
- clearInterval(this.timer);
- this.timer = null;
- },
-
- onTimerEvent: function() {
- if (!this.currentlyExecuting) {
- try {
- this.currentlyExecuting = true;
- this.execute();
- } finally {
- this.currentlyExecuting = false;
- }
- }
- }
-});
-Object.extend(String, {
- interpret: function(value) {
- return value == null ? '' : String(value);
- },
- specialChar: {
- '\b': '\\b',
- '\t': '\\t',
- '\n': '\\n',
- '\f': '\\f',
- '\r': '\\r',
- '\\': '\\\\'
- }
-});
-
-Object.extend(String.prototype, {
- gsub: function(pattern, replacement) {
- var result = '', source = this, match;
- replacement = arguments.callee.prepareReplacement(replacement);
-
- while (source.length > 0) {
- if (match = source.match(pattern)) {
- result += source.slice(0, match.index);
- result += String.interpret(replacement(match));
- source = source.slice(match.index + match[0].length);
- } else {
- result += source, source = '';
- }
- }
- return result;
- },
-
- sub: function(pattern, replacement, count) {
- replacement = this.gsub.prepareReplacement(replacement);
- count = Object.isUndefined(count) ? 1 : count;
-
- return this.gsub(pattern, function(match) {
- if (--count < 0) return match[0];
- return replacement(match);
- });
- },
-
- scan: function(pattern, iterator) {
- this.gsub(pattern, iterator);
- return String(this);
- },
-
- truncate: function(length, truncation) {
- length = length || 30;
- truncation = Object.isUndefined(truncation) ? '...' : truncation;
- return this.length > length ?
- this.slice(0, length - truncation.length) + truncation : String(this);
- },
-
- strip: function() {
- return this.replace(/^\s+/, '').replace(/\s+$/, '');
- },
-
- stripTags: function() {
- return this.replace(/<\/?[^>]+>/gi, '');
- },
-
- stripScripts: function() {
- return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
- },
-
- extractScripts: function() {
- var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
- var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
- return (this.match(matchAll) || []).map(function(scriptTag) {
- return (scriptTag.match(matchOne) || ['', ''])[1];
- });
- },
-
- evalScripts: function() {
- return this.extractScripts().map(function(script) { return eval(script) });
- },
-
- escapeHTML: function() {
- var self = arguments.callee;
- self.text.data = this;
- return self.div.innerHTML;
- },
-
- unescapeHTML: function() {
- var div = new Element('div');
- div.innerHTML = this.stripTags();
- return div.childNodes[0] ? (div.childNodes.length > 1 ?
- $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
- div.childNodes[0].nodeValue) : '';
- },
-
- toQueryParams: function(separator) {
- var match = this.strip().match(/([^?#]*)(#.*)?$/);
- if (!match) return { };
-
- return match[1].split(separator || '&').inject({ }, function(hash, pair) {
- if ((pair = pair.split('='))[0]) {
- var key = decodeURIComponent(pair.shift());
- var value = pair.length > 1 ? pair.join('=') : pair[0];
- if (value != undefined) value = decodeURIComponent(value);
-
- if (key in hash) {
- if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
- hash[key].push(value);
- }
- else hash[key] = value;
- }
- return hash;
- });
- },
-
- toArray: function() {
- return this.split('');
- },
-
- succ: function() {
- return this.slice(0, this.length - 1) +
- String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
- },
-
- times: function(count) {
- return count < 1 ? '' : new Array(count + 1).join(this);
- },
-
- camelize: function() {
- var parts = this.split('-'), len = parts.length;
- if (len == 1) return parts[0];
-
- var camelized = this.charAt(0) == '-'
- ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
- : parts[0];
-
- for (var i = 1; i < len; i++)
- camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
-
- return camelized;
- },
-
- capitalize: function() {
- return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
- },
-
- underscore: function() {
- return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
- },
-
- dasherize: function() {
- return this.gsub(/_/,'-');
- },
-
- inspect: function(useDoubleQuotes) {
- var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
- var character = String.specialChar[match[0]];
- return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
- });
- if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
- return "'" + escapedString.replace(/'/g, '\\\'') + "'";
- },
-
- toJSON: function() {
- return this.inspect(true);
- },
-
- unfilterJSON: function(filter) {
- return this.sub(filter || Prototype.JSONFilter, '#{1}');
- },
-
- isJSON: function() {
- var str = this;
- if (str.blank()) return false;
- str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
- return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
- },
-
- evalJSON: function(sanitize) {
- var json = this.unfilterJSON();
- try {
- if (!sanitize || json.isJSON()) return eval('(' + json + ')');
- } catch (e) { }
- throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
- },
-
- include: function(pattern) {
- return this.indexOf(pattern) > -1;
- },
-
- startsWith: function(pattern) {
- return this.indexOf(pattern) === 0;
- },
-
- endsWith: function(pattern) {
- var d = this.length - pattern.length;
- return d >= 0 && this.lastIndexOf(pattern) === d;
- },
-
- empty: function() {
- return this == '';
- },
-
- blank: function() {
- return /^\s*$/.test(this);
- },
-
- interpolate: function(object, pattern) {
- return new Template(this, pattern).evaluate(object);
- }
-});
-
-if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
- escapeHTML: function() {
- return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
- },
- unescapeHTML: function() {
- return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
- }
-});
-
-String.prototype.gsub.prepareReplacement = function(replacement) {
- if (Object.isFunction(replacement)) return replacement;
- var template = new Template(replacement);
- return function(match) { return template.evaluate(match) };
-};
-
-String.prototype.parseQuery = String.prototype.toQueryParams;
-
-Object.extend(String.prototype.escapeHTML, {
- div: document.createElement('div'),
- text: document.createTextNode('')
-});
-
-with (String.prototype.escapeHTML) div.appendChild(text);
-
-var Template = Class.create({
- initialize: function(template, pattern) {
- this.template = template.toString();
- this.pattern = pattern || Template.Pattern;
- },
-
- evaluate: function(object) {
- if (Object.isFunction(object.toTemplateReplacements))
- object = object.toTemplateReplacements();
-
- return this.template.gsub(this.pattern, function(match) {
- if (object == null) return '';
-
- var before = match[1] || '';
- if (before == '\\') return match[2];
-
- var ctx = object, expr = match[3];
- var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
- match = pattern.exec(expr);
- if (match == null) return before;
-
- while (match != null) {
- var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
- ctx = ctx[comp];
- if (null == ctx || '' == match[3]) break;
- expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
- match = pattern.exec(expr);
- }
-
- return before + String.interpret(ctx);
- });
- }
-});
-Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
-
-var $break = { };
-
-var Enumerable = {
- each: function(iterator, context) {
- var index = 0;
- iterator = iterator.bind(context);
- try {
- this._each(function(value) {
- iterator(value, index++);
- });
- } catch (e) {
- if (e != $break) throw e;
- }
- return this;
- },
-
- eachSlice: function(number, iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var index = -number, slices = [], array = this.toArray();
- while ((index += number) < array.length)
- slices.push(array.slice(index, index+number));
- return slices.collect(iterator, context);
- },
-
- all: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var result = true;
- this.each(function(value, index) {
- result = result && !!iterator(value, index);
- if (!result) throw $break;
- });
- return result;
- },
-
- any: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var result = false;
- this.each(function(value, index) {
- if (result = !!iterator(value, index))
- throw $break;
- });
- return result;
- },
-
- collect: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var results = [];
- this.each(function(value, index) {
- results.push(iterator(value, index));
- });
- return results;
- },
-
- detect: function(iterator, context) {
- iterator = iterator.bind(context);
- var result;
- this.each(function(value, index) {
- if (iterator(value, index)) {
- result = value;
- throw $break;
- }
- });
- return result;
- },
-
- findAll: function(iterator, context) {
- iterator = iterator.bind(context);
- var results = [];
- this.each(function(value, index) {
- if (iterator(value, index))
- results.push(value);
- });
- return results;
- },
-
- grep: function(filter, iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var results = [];
-
- if (Object.isString(filter))
- filter = new RegExp(filter);
-
- this.each(function(value, index) {
- if (filter.match(value))
- results.push(iterator(value, index));
- });
- return results;
- },
-
- include: function(object) {
- if (Object.isFunction(this.indexOf))
- if (this.indexOf(object) != -1) return true;
-
- var found = false;
- this.each(function(value) {
- if (value == object) {
- found = true;
- throw $break;
- }
- });
- return found;
- },
-
- inGroupsOf: function(number, fillWith) {
- fillWith = Object.isUndefined(fillWith) ? null : fillWith;
- return this.eachSlice(number, function(slice) {
- while(slice.length < number) slice.push(fillWith);
- return slice;
- });
- },
-
- inject: function(memo, iterator, context) {
- iterator = iterator.bind(context);
- this.each(function(value, index) {
- memo = iterator(memo, value, index);
- });
- return memo;
- },
-
- invoke: function(method) {
- var args = $A(arguments).slice(1);
- return this.map(function(value) {
- return value[method].apply(value, args);
- });
- },
-
- max: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var result;
- this.each(function(value, index) {
- value = iterator(value, index);
- if (result == null || value >= result)
- result = value;
- });
- return result;
- },
-
- min: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var result;
- this.each(function(value, index) {
- value = iterator(value, index);
- if (result == null || value < result)
- result = value;
- });
- return result;
- },
-
- partition: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var trues = [], falses = [];
- this.each(function(value, index) {
- (iterator(value, index) ?
- trues : falses).push(value);
- });
- return [trues, falses];
- },
-
- pluck: function(property) {
- var results = [];
- this.each(function(value) {
- results.push(value[property]);
- });
- return results;
- },
-
- reject: function(iterator, context) {
- iterator = iterator.bind(context);
- var results = [];
- this.each(function(value, index) {
- if (!iterator(value, index))
- results.push(value);
- });
- return results;
- },
-
- sortBy: function(iterator, context) {
- iterator = iterator.bind(context);
- return this.map(function(value, index) {
- return {value: value, criteria: iterator(value, index)};
- }).sort(function(left, right) {
- var a = left.criteria, b = right.criteria;
- return a < b ? -1 : a > b ? 1 : 0;
- }).pluck('value');
- },
-
- toArray: function() {
- return this.map();
- },
-
- zip: function() {
- var iterator = Prototype.K, args = $A(arguments);
- if (Object.isFunction(args.last()))
- iterator = args.pop();
-
- var collections = [this].concat(args).map($A);
- return this.map(function(value, index) {
- return iterator(collections.pluck(index));
- });
- },
-
- size: function() {
- return this.toArray().length;
- },
-
- inspect: function() {
- return '#<Enumerable:' + this.toArray().inspect() + '>';
- }
-};
-
-Object.extend(Enumerable, {
- map: Enumerable.collect,
- find: Enumerable.detect,
- select: Enumerable.findAll,
- filter: Enumerable.findAll,
- member: Enumerable.include,
- entries: Enumerable.toArray,
- every: Enumerable.all,
- some: Enumerable.any
-});
-function $A(iterable) {
- if (!iterable) return [];
- if (iterable.toArray) return iterable.toArray();
- var length = iterable.length || 0, results = new Array(length);
- while (length--) results[length] = iterable[length];
- return results;
-}
-
-if (Prototype.Browser.WebKit) {
- $A = function(iterable) {
- if (!iterable) return [];
- if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
- iterable.toArray) return iterable.toArray();
- var length = iterable.length || 0, results = new Array(length);
- while (length--) results[length] = iterable[length];
- return results;
- };
-}
-
-Array.from = $A;
-
-Object.extend(Array.prototype, Enumerable);
-
-if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
-
-Object.extend(Array.prototype, {
- _each: function(iterator) {
- for (var i = 0, length = this.length; i < length; i++)
- iterator(this[i]);
- },
-
- clear: function() {
- this.length = 0;
- return this;
- },
-
- first: function() {
- return this[0];
- },
-
- last: function() {
- return this[this.length - 1];
- },
-
- compact: function() {
- return this.select(function(value) {
- return value != null;
- });
- },
-
- flatten: function() {
- return this.inject([], function(array, value) {
- return array.concat(Object.isArray(value) ?
- value.flatten() : [value]);
- });
- },
-
- without: function() {
- var values = $A(arguments);
- return this.select(function(value) {
- return !values.include(value);
- });
- },
-
- reverse: function(inline) {
- return (inline !== false ? this : this.toArray())._reverse();
- },
-
- reduce: function() {
- return this.length > 1 ? this : this[0];
- },
-
- uniq: function(sorted) {
- return this.inject([], function(array, value, index) {
- if (0 == index || (sorted ? array.last() != value : !array.include(value)))
- array.push(value);
- return array;
- });
- },
-
- intersect: function(array) {
- return this.uniq().findAll(function(item) {
- return array.detect(function(value) { return item === value });
- });
- },
-
- clone: function() {
- return [].concat(this);
- },
-
- size: function() {
- return this.length;
- },
-
- inspect: function() {
- return '[' + this.map(Object.inspect).join(', ') + ']';
- },
-
- toJSON: function() {
- var results = [];
- this.each(function(object) {
- var value = Object.toJSON(object);
- if (!Object.isUndefined(value)) results.push(value);
- });
- return '[' + results.join(', ') + ']';
- }
-});
-
-// use native browser JS 1.6 implementation if available
-if (Object.isFunction(Array.prototype.forEach))
- Array.prototype._each = Array.prototype.forEach;
-
-if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
- i || (i = 0);
- var length = this.length;
- if (i < 0) i = length + i;
- for (; i < length; i++)
- if (this[i] === item) return i;
- return -1;
-};
-
-if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
- i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
- var n = this.slice(0, i).reverse().indexOf(item);
- return (n < 0) ? n : i - n - 1;
-};
-
-Array.prototype.toArray = Array.prototype.clone;
-
-function $w(string) {
- if (!Object.isString(string)) return [];
- string = string.strip();
- return string ? string.split(/\s+/) : [];
-}
-
-if (Prototype.Browser.Opera){
- Array.prototype.concat = function() {
- var array = [];
- for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
- for (var i = 0, length = arguments.length; i < length; i++) {
- if (Object.isArray(arguments[i])) {
- for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
- array.push(arguments[i][j]);
- } else {
- array.push(arguments[i]);
- }
- }
- return array;
- };
-}
-Object.extend(Number.prototype, {
- toColorPart: function() {
- return this.toPaddedString(2, 16);
- },
-
- succ: function() {
- return this + 1;
- },
-
- times: function(iterator) {
- $R(0, this, true).each(iterator);
- return this;
- },
-
- toPaddedString: function(length, radix) {
- var string = this.toString(radix || 10);
- return '0'.times(length - string.length) + string;
- },
-
- toJSON: function() {
- return isFinite(this) ? this.toString() : 'null';
- }
-});
-
-$w('abs round ceil floor').each(function(method){
- Number.prototype[method] = Math[method].methodize();
-});
-function $H(object) {
- return new Hash(object);
-};
-
-var Hash = Class.create(Enumerable, (function() {
-
- function toQueryPair(key, value) {
- if (Object.isUndefined(value)) return key;
- return key + '=' + encodeURIComponent(String.interpret(value));
- }
-
- return {
- initialize: function(object) {
- this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
- },
-
- _each: function(iterator) {
- for (var key in this._object) {
- var value = this._object[key], pair = [key, value];
- pair.key = key;
- pair.value = value;
- iterator(pair);
- }
- },
-
- set: function(key, value) {
- return this._object[key] = value;
- },
-
- get: function(key) {
- return this._object[key];
- },
-
- unset: function(key) {
- var value = this._object[key];
- delete this._object[key];
- return value;
- },
-
- toObject: function() {
- return Object.clone(this._object);
- },
-
- keys: function() {
- return this.pluck('key');
- },
-
- values: function() {
- return this.pluck('value');
- },
-
- index: function(value) {
- var match = this.detect(function(pair) {
- return pair.value === value;
- });
- return match && match.key;
- },
-
- merge: function(object) {
- return this.clone().update(object);
- },
-
- update: function(object) {
- return new Hash(object).inject(this, function(result, pair) {
- result.set(pair.key, pair.value);
- return result;
- });
- },
-
- toQueryString: function() {
- return this.map(function(pair) {
- var key = encodeURIComponent(pair.key), values = pair.value;
-
- if (values && typeof values == 'object') {
- if (Object.isArray(values))
- return values.map(toQueryPair.curry(key)).join('&');
- }
- return toQueryPair(key, values);
- }).join('&');
- },
-
- inspect: function() {
- return '#<Hash:{' + this.map(function(pair) {
- return pair.map(Object.inspect).join(': ');
- }).join(', ') + '}>';
- },
-
- toJSON: function() {
- return Object.toJSON(this.toObject());
- },
-
- clone: function() {
- return new Hash(this);
- }
- }
-})());
-
-Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
-Hash.from = $H;
-var ObjectRange = Class.create(Enumerable, {
- initialize: function(start, end, exclusive) {
- this.start = start;
- this.end = end;
- this.exclusive = exclusive;
- },
-
- _each: function(iterator) {
- var value = this.start;
- while (this.include(value)) {
- iterator(value);
- value = value.succ();
- }
- },
-
- include: function(value) {
- if (value < this.start)
- return false;
- if (this.exclusive)
- return value < this.end;
- return value <= this.end;
- }
-});
-
-var $R = function(start, end, exclusive) {
- return new ObjectRange(start, end, exclusive);
-};
-
-var Ajax = {
- getTransport: function() {
- return Try.these(
- function() {return new XMLHttpRequest()},
- function() {return new ActiveXObject('Msxml2.XMLHTTP')},
- function() {return new ActiveXObject('Microsoft.XMLHTTP')}
- ) || false;
- },
-
- activeRequestCount: 0
-};
-
-Ajax.Responders = {
- responders: [],
-
- _each: function(iterator) {
- this.responders._each(iterator);
- },
-
- register: function(responder) {
- if (!this.include(responder))
- this.responders.push(responder);
- },
-
- unregister: function(responder) {
- this.responders = this.responders.without(responder);
- },
-
- dispatch: function(callback, request, transport, json) {
- this.each(function(responder) {
- if (Object.isFunction(responder[callback])) {
- try {
- responder[callback].apply(responder, [request, transport, json]);
- } catch (e) { }
- }
- });
- }
-};
-
-Object.extend(Ajax.Responders, Enumerable);
-
-Ajax.Responders.register({
- onCreate: function() { Ajax.activeRequestCount++ },
- onComplete: function() { Ajax.activeRequestCount-- }
-});
-
-Ajax.Base = Class.create({
- initialize: function(options) {
- this.options = {
- method: 'post',
- asynchronous: true,
- contentType: 'application/x-www-form-urlencoded',
- encoding: 'UTF-8',
- parameters: '',
- evalJSON: true,
- evalJS: true
- };
- Object.extend(this.options, options || { });
-
- this.options.method = this.options.method.toLowerCase();
-
- if (Object.isString(this.options.parameters))
- this.options.parameters = this.options.parameters.toQueryParams();
- else if (Object.isHash(this.options.parameters))
- this.options.parameters = this.options.parameters.toObject();
- }
-});
-
-Ajax.Request = Class.create(Ajax.Base, {
- _complete: false,
-
- initialize: function($super, url, options) {
- $super(options);
- this.transport = Ajax.getTransport();
- this.request(url);
- },
-
- request: function(url) {
- this.url = url;
- this.method = this.options.method;
- var params = Object.clone(this.options.parameters);
-
- if (!['get', 'post'].include(this.method)) {
- // simulate other verbs over post
- params['_method'] = this.method;
- this.method = 'post';
- }
-
- this.parameters = params;
-
- if (params = Object.toQueryString(params)) {
- // when GET, append parameters to URL
- if (this.method == 'get')
- this.url += (this.url.include('?') ? '&' : '?') + params;
- else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
- params += '&_=';
- }
-
- try {
- var response = new Ajax.Response(this);
- if (this.options.onCreate) this.options.onCreate(response);
- Ajax.Responders.dispatch('onCreate', this, response);
-
- this.transport.open(this.method.toUpperCase(), this.url,
- this.options.asynchronous);
-
- if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
-
- this.transport.onreadystatechange = this.onStateChange.bind(this);
- this.setRequestHeaders();
-
- this.body = this.method == 'post' ? (this.options.postBody || params) : null;
- this.transport.send(this.body);
-
- /* Force Firefox to handle ready state 4 for synchronous requests */
- if (!this.options.asynchronous && this.transport.overrideMimeType)
- this.onStateChange();
-
- }
- catch (e) {
- this.dispatchException(e);
- }
- },
-
- onStateChange: function() {
- var readyState = this.transport.readyState;
- if (readyState > 1 && !((readyState == 4) && this._complete))
- this.respondToReadyState(this.transport.readyState);
- },
-
- setRequestHeaders: function() {
- var headers = {
- 'X-Requested-With': 'XMLHttpRequest',
- 'X-Prototype-Version': Prototype.Version,
- 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
- };
-
- if (this.method == 'post') {
- headers['Content-type'] = this.options.contentType +
- (this.options.encoding ? '; charset=' + this.options.encoding : '');
-
- /* Force "Connection: close" for older Mozilla browsers to work
- * around a bug where XMLHttpRequest sends an incorrect
- * Content-length header. See Mozilla Bugzilla #246651.
- */
- if (this.transport.overrideMimeType &&
- (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
- headers['Connection'] = 'close';
- }
-
- // user-defined headers
- if (typeof this.options.requestHeaders == 'object') {
- var extras = this.options.requestHeaders;
-
- if (Object.isFunction(extras.push))
- for (var i = 0, length = extras.length; i < length; i += 2)
- headers[extras[i]] = extras[i+1];
- else
- $H(extras).each(function(pair) { headers[pair.key] = pair.value });
- }
-
- for (var name in headers)
- this.transport.setRequestHeader(name, headers[name]);
- },
-
- success: function() {
- var status = this.getStatus();
- return !status || (status >= 200 && status < 300);
- },
-
- getStatus: function() {
- try {
- return this.transport.status || 0;
- } catch (e) { return 0 }
- },
-
- respondToReadyState: function(readyState) {
- var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
-
- if (state == 'Complete') {
- try {
- this._complete = true;
- (this.options['on' + response.status]
- || this.options['on' + (this.success() ? 'Success' : 'Failure')]
- || Prototype.emptyFunction)(response, response.headerJSON);
- } catch (e) {
- this.dispatchException(e);
- }
-
- var contentType = response.getHeader('Content-type');
- if (this.options.evalJS == 'force'
- || (this.options.evalJS && this.isSameOrigin() && contentType
- && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
- this.evalResponse();
- }
-
- try {
- (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
- Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
- } catch (e) {
- this.dispatchException(e);
- }
-
- if (state == 'Complete') {
- // avoid memory leak in MSIE: clean up
- this.transport.onreadystatechange = Prototype.emptyFunction;
- }
- },
-
- isSameOrigin: function() {
- var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
- return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
- protocol: location.protocol,
- domain: document.domain,
- port: location.port ? ':' + location.port : ''
- }));
- },
-
- getHeader: function(name) {
- try {
- return this.transport.getResponseHeader(name) || null;
- } catch (e) { return null }
- },
-
- evalResponse: function() {
- try {
- return eval((this.transport.responseText || '').unfilterJSON());
- } catch (e) {
- this.dispatchException(e);
- }
- },
-
- dispatchException: function(exception) {
- (this.options.onException || Prototype.emptyFunction)(this, exception);
- Ajax.Responders.dispatch('onException', this, exception);
- }
-});
-
-Ajax.Request.Events =
- ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
-
-Ajax.Response = Class.create({
- initialize: function(request){
- this.request = request;
- var transport = this.transport = request.transport,
- readyState = this.readyState = transport.readyState;
-
- if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
- this.status = this.getStatus();
- this.statusText = this.getStatusText();
- this.responseText = String.interpret(transport.responseText);
- this.headerJSON = this._getHeaderJSON();
- }
-
- if(readyState == 4) {
- var xml = transport.responseXML;
- this.responseXML = Object.isUndefined(xml) ? null : xml;
- this.responseJSON = this._getResponseJSON();
- }
- },
-
- status: 0,
- statusText: '',
-
- getStatus: Ajax.Request.prototype.getStatus,
-
- getStatusText: function() {
- try {
- return this.transport.statusText || '';
- } catch (e) { return '' }
- },
-
- getHeader: Ajax.Request.prototype.getHeader,
-
- getAllHeaders: function() {
- try {
- return this.getAllResponseHeaders();
- } catch (e) { return null }
- },
-
- getResponseHeader: function(name) {
- return this.transport.getResponseHeader(name);
- },
-
- getAllResponseHeaders: function() {
- return this.transport.getAllResponseHeaders();
- },
-
- _getHeaderJSON: function() {
- var json = this.getHeader('X-JSON');
- if (!json) return null;
- json = decodeURIComponent(escape(json));
- try {
- return json.evalJSON(this.request.options.sanitizeJSON ||
- !this.request.isSameOrigin());
- } catch (e) {
- this.request.dispatchException(e);
- }
- },
-
- _getResponseJSON: function() {
- var options = this.request.options;
- if (!options.evalJSON || (options.evalJSON != 'force' &&
- !(this.getHeader('Content-type') || '').include('application/json')) ||
- this.responseText.blank())
- return null;
- try {
- return this.responseText.evalJSON(options.sanitizeJSON ||
- !this.request.isSameOrigin());
- } catch (e) {
- this.request.dispatchException(e);
- }
- }
-});
-
-Ajax.Updater = Class.create(Ajax.Request, {
- initialize: function($super, container, url, options) {
- this.container = {
- success: (container.success || container),
- failure: (container.failure || (container.success ? null : container))
- };
-
- options = Object.clone(options);
- var onComplete = options.onComplete;
- options.onComplete = (function(response, json) {
- this.updateContent(response.responseText);
- if (Object.isFunction(onComplete)) onComplete(response, json);
- }).bind(this);
-
- $super(url, options);
- },
-
- updateContent: function(responseText) {
- var receiver = this.container[this.success() ? 'success' : 'failure'],
- options = this.options;
-
- if (!options.evalScripts) responseText = responseText.stripScripts();
-
- if (receiver = $(receiver)) {
- if (options.insertion) {
- if (Object.isString(options.insertion)) {
- var insertion = { }; insertion[options.insertion] = responseText;
- receiver.insert(insertion);
- }
- else options.insertion(receiver, responseText);
- }
- else receiver.update(responseText);
- }
- }
-});
-
-Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
- initialize: function($super, container, url, options) {
- $super(options);
- this.onComplete = this.options.onComplete;
-
- this.frequency = (this.options.frequency || 2);
- this.decay = (this.options.decay || 1);
-
- this.updater = { };
- this.container = container;
- this.url = url;
-
- this.start();
- },
-
- start: function() {
- this.options.onComplete = this.updateComplete.bind(this);
- this.onTimerEvent();
- },
-
- stop: function() {
- this.updater.options.onComplete = undefined;
- clearTimeout(this.timer);
- (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
- },
-
- updateComplete: function(response) {
- if (this.options.decay) {
- this.decay = (response.responseText == this.lastText ?
- this.decay * this.options.decay : 1);
-
- this.lastText = response.responseText;
- }
- this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
- },
-
- onTimerEvent: function() {
- this.updater = new Ajax.Updater(this.container, this.url, this.options);
- }
-});
-function $(element) {
- if (arguments.length > 1) {
- for (var i = 0, elements = [], length = arguments.length; i < length; i++)
- elements.push($(arguments[i]));
- return elements;
- }
- if (Object.isString(element))
- element = document.getElementById(element);
- return Element.extend(element);
-}
-
-if (Prototype.BrowserFeatures.XPath) {
- document._getElementsByXPath = function(expression, parentElement) {
- var results = [];
- var query = document.evaluate(expression, $(parentElement) || document,
- null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
- for (var i = 0, length = query.snapshotLength; i < length; i++)
- results.push(Element.extend(query.snapshotItem(i)));
- return results;
- };
-}
-
-/*--------------------------------------------------------------------------*/
-
-if (!window.Node) var Node = { };
-
-if (!Node.ELEMENT_NODE) {
- // DOM level 2 ECMAScript Language Binding
- Object.extend(Node, {
- ELEMENT_NODE: 1,
- ATTRIBUTE_NODE: 2,
- TEXT_NODE: 3,
- CDATA_SECTION_NODE: 4,
- ENTITY_REFERENCE_NODE: 5,
- ENTITY_NODE: 6,
- PROCESSING_INSTRUCTION_NODE: 7,
- COMMENT_NODE: 8,
- DOCUMENT_NODE: 9,
- DOCUMENT_TYPE_NODE: 10,
- DOCUMENT_FRAGMENT_NODE: 11,
- NOTATION_NODE: 12
- });
-}
-
-(function() {
- var element = this.Element;
- this.Element = function(tagName, attributes) {
- attributes = attributes || { };
- tagName = tagName.toLowerCase();
- var cache = Element.cache;
- if (Prototype.Browser.IE && attributes.name) {
- tagName = '<' + tagName + ' name="' + attributes.name + '">';
- delete attributes.name;
- return Element.writeAttribute(document.createElement(tagName), attributes);
- }
- if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
- return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
- };
- Object.extend(this.Element, element || { });
-}).call(window);
-
-Element.cache = { };
-
-Element.Methods = {
- visible: function(element) {
- return $(element).style.display != 'none';
- },
-
- toggle: function(element) {
- element = $(element);
- Element[Element.visible(element) ? 'hide' : 'show'](element);
- return element;
- },
-
- hide: function(element) {
- $(element).style.display = 'none';
- return element;
- },
-
- show: function(element) {
- $(element).style.display = '';
- return element;
- },
-
- remove: function(element) {
- element = $(element);
- element.parentNode.removeChild(element);
- return element;
- },
-
- update: function(element, content) {
- element = $(element);
- if (content && content.toElement) content = content.toElement();
- if (Object.isElement(content)) return element.update().insert(content);
- content = Object.toHTML(content);
- element.innerHTML = content.stripScripts();
- content.evalScripts.bind(content).defer();
- return element;
- },
-
- replace: function(element, content) {
- element = $(element);
- if (content && content.toElement) content = content.toElement();
- else if (!Object.isElement(content)) {
- content = Object.toHTML(content);
- var range = element.ownerDocument.createRange();
- range.selectNode(element);
- content.evalScripts.bind(content).defer();
- content = range.createContextualFragment(content.stripScripts());
- }
- element.parentNode.replaceChild(content, element);
- return element;
- },
-
- insert: function(element, insertions) {
- element = $(element);
-
- if (Object.isString(insertions) || Object.isNumber(insertions) ||
- Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
- insertions = {bottom:insertions};
-
- var content, insert, tagName, childNodes;
-
- for (var position in insertions) {
- content = insertions[position];
- position = position.toLowerCase();
- insert = Element._insertionTranslations[position];
-
- if (content && content.toElement) content = content.toElement();
- if (Object.isElement(content)) {
- insert(element, content);
- continue;
- }
-
- content = Object.toHTML(content);
-
- tagName = ((position == 'before' || position == 'after')
- ? element.parentNode : element).tagName.toUpperCase();
-
- childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
-
- if (position == 'top' || position == 'after') childNodes.reverse();
- childNodes.each(insert.curry(element));
-
- content.evalScripts.bind(content).defer();
- }
-
- return element;
- },
-
- wrap: function(element, wrapper, attributes) {
- element = $(element);
- if (Object.isElement(wrapper))
- $(wrapper).writeAttribute(attributes || { });
- else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
- else wrapper = new Element('div', wrapper);
- if (element.parentNode)
- element.parentNode.replaceChild(wrapper, element);
- wrapper.appendChild(element);
- return wrapper;
- },
-
- inspect: function(element) {
- element = $(element);
- var result = '<' + element.tagName.toLowerCase();
- $H({'id': 'id', 'className': 'class'}).each(function(pair) {
- var property = pair.first(), attribute = pair.last();
- var value = (element[property] || '').toString();
- if (value) result += ' ' + attribute + '=' + value.inspect(true);
- });
- return result + '>';
- },
-
- recursivelyCollect: function(element, property) {
- element = $(element);
- var elements = [];
- while (element = element[property])
- if (element.nodeType == 1)
- elements.push(Element.extend(element));
- return elements;
- },
-
- ancestors: function(element) {
- return $(element).recursivelyCollect('parentNode');
- },
-
- descendants: function(element) {
- return $(element).select("*");
- },
-
- firstDescendant: function(element) {
- element = $(element).firstChild;
- while (element && element.nodeType != 1) element = element.nextSibling;
- return $(element);
- },
-
- immediateDescendants: function(element) {
- if (!(element = $(element).firstChild)) return [];
- while (element && element.nodeType != 1) element = element.nextSibling;
- if (element) return [element].concat($(element).nextSiblings());
- return [];
- },
-
- previousSiblings: function(element) {
- return $(element).recursivelyCollect('previousSibling');
- },
-
- nextSiblings: function(element) {
- return $(element).recursivelyCollect('nextSibling');
- },
-
- siblings: function(element) {
- element = $(element);
- return element.previousSiblings().reverse().concat(element.nextSiblings());
- },
-
- match: function(element, selector) {
- if (Object.isString(selector))
- selector = new Selector(selector);
- return selector.match($(element));
- },
-
- up: function(element, expression, index) {
- element = $(element);
- if (arguments.length == 1) return $(element.parentNode);
- var ancestors = element.ancestors();
- return Object.isNumber(expression) ? ancestors[expression] :
- Selector.findElement(ancestors, expression, index);
- },
-
- down: function(element, expression, index) {
- element = $(element);
- if (arguments.length == 1) return element.firstDescendant();
- return Object.isNumber(expression) ? element.descendants()[expression] :
- element.select(expression)[index || 0];
- },
-
- previous: function(element, expression, index) {
- element = $(element);
- if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
- var previousSiblings = element.previousSiblings();
- return Object.isNumber(expression) ? previousSiblings[expression] :
- Selector.findElement(previousSiblings, expression, index);
- },
-
- next: function(element, expression, index) {
- element = $(element);
- if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
- var nextSiblings = element.nextSiblings();
- return Object.isNumber(expression) ? nextSiblings[expression] :
- Selector.findElement(nextSiblings, expression, index);
- },
-
- select: function() {
- var args = $A(arguments), element = $(args.shift());
- return Selector.findChildElements(element, args);
- },
-
- adjacent: function() {
- var args = $A(arguments), element = $(args.shift());
- return Selector.findChildElements(element.parentNode, args).without(element);
- },
-
- identify: function(element) {
- element = $(element);
- var id = element.readAttribute('id'), self = arguments.callee;
- if (id) return id;
- do { id = 'anonymous_element_' + self.counter++ } while ($(id));
- element.writeAttribute('id', id);
- return id;
- },
-
- readAttribute: function(element, name) {
- element = $(element);
- if (Prototype.Browser.IE) {
- var t = Element._attributeTranslations.read;
- if (t.values[name]) return t.values[name](element, name);
- if (t.names[name]) name = t.names[name];
- if (name.include(':')) {
- return (!element.attributes || !element.attributes[name]) ? null :
- element.attributes[name].value;
- }
- }
- return element.getAttribute(name);
- },
-
- writeAttribute: function(element, name, value) {
- element = $(element);
- var attributes = { }, t = Element._attributeTranslations.write;
-
- if (typeof name == 'object') attributes = name;
- else attributes[name] = Object.isUndefined(value) ? true : value;
-
- for (var attr in attributes) {
- name = t.names[attr] || attr;
- value = attributes[attr];
- if (t.values[attr]) name = t.values[attr](element, value);
- if (value === false || value === null)
- element.removeAttribute(name);
- else if (value === true)
- element.setAttribute(name, name);
- else element.setAttribute(name, value);
- }
- return element;
- },
-
- getHeight: function(element) {
- return $(element).getDimensions().height;
- },
-
- getWidth: function(element) {
- return $(element).getDimensions().width;
- },
-
- classNames: function(element) {
- return new Element.ClassNames(element);
- },
-
- hasClassName: function(element, className) {
- if (!(element = $(element))) return;
- var elementClassName = element.className;
- return (elementClassName.length > 0 && (elementClassName == className ||
- new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
- },
-
- addClassName: function(element, className) {
- if (!(element = $(element))) return;
- if (!element.hasClassName(className))
- element.className += (element.className ? ' ' : '') + className;
- return element;
- },
-
- removeClassName: function(element, className) {
- if (!(element = $(element))) return;
- element.className = element.className.replace(
- new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
- return element;
- },
-
- toggleClassName: function(element, className) {
- if (!(element = $(element))) return;
- return element[element.hasClassName(className) ?
- 'removeClassName' : 'addClassName'](className);
- },
-
- // removes whitespace-only text node children
- cleanWhitespace: function(element) {
- element = $(element);
- var node = element.firstChild;
- while (node) {
- var nextNode = node.nextSibling;
- if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
- element.removeChild(node);
- node = nextNode;
- }
- return element;
- },
-
- empty: function(element) {
- return $(element).innerHTML.blank();
- },
-
- descendantOf: function(element, ancestor) {
- element = $(element), ancestor = $(ancestor);
- var originalAncestor = ancestor;
-
- if (element.compareDocumentPosition)
- return (element.compareDocumentPosition(ancestor) & 8) === 8;
-
- if (element.sourceIndex && !Prototype.Browser.Opera) {
- var e = element.sourceIndex, a = ancestor.sourceIndex,
- nextAncestor = ancestor.nextSibling;
- if (!nextAncestor) {
- do { ancestor = ancestor.parentNode; }
- while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
- }
- if (nextAncestor && nextAncestor.sourceIndex)
- return (e > a && e < nextAncestor.sourceIndex);
- }
-
- while (element = element.parentNode)
- if (element == originalAncestor) return true;
- return false;
- },
-
- scrollTo: function(element) {
- element = $(element);
- var pos = element.cumulativeOffset();
- window.scrollTo(pos[0], pos[1]);
- return element;
- },
-
- getStyle: function(element, style) {
- element = $(element);
- style = style == 'float' ? 'cssFloat' : style.camelize();
- var value = element.style[style];
- if (!value) {
- var css = document.defaultView.getComputedStyle(element, null);
- value = css ? css[style] : null;
- }
- if (style == 'opacity') return value ? parseFloat(value) : 1.0;
- return value == 'auto' ? null : value;
- },
-
- getOpacity: function(element) {
- return $(element).getStyle('opacity');
- },
-
- setStyle: function(element, styles) {
- element = $(element);
- var elementStyle = element.style, match;
- if (Object.isString(styles)) {
- element.style.cssText += ';' + styles;
- return styles.include('opacity') ?
- element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
- }
- for (var property in styles)
- if (property == 'opacity') element.setOpacity(styles[property]);
- else
- elementStyle[(property == 'float' || property == 'cssFloat') ?
- (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
- property] = styles[property];
-
- return element;
- },
-
- setOpacity: function(element, value) {
- element = $(element);
- element.style.opacity = (value == 1 || value === '') ? '' :
- (value < 0.00001) ? 0 : value;
- return element;
- },
-
- getDimensions: function(element) {
- element = $(element);
- var display = $(element).getStyle('display');
- if (display != 'none' && display != null) // Safari bug
- return {width: element.offsetWidth, height: element.offsetHeight};
-
- // All *Width and *Height properties give 0 on elements with display none,
- // so enable the element temporarily
- var els = element.style;
- var originalVisibility = els.visibility;
- var originalPosition = els.position;
- var originalDisplay = els.display;
- els.visibility = 'hidden';
- els.position = 'absolute';
- els.display = 'block';
- var originalWidth = element.clientWidth;
- var originalHeight = element.clientHeight;
- els.display = originalDisplay;
- els.position = originalPosition;
- els.visibility = originalVisibility;
- return {width: originalWidth, height: originalHeight};
- },
-
- makePositioned: function(element) {
- element = $(element);
- var pos = Element.getStyle(element, 'position');
- if (pos == 'static' || !pos) {
- element._madePositioned = true;
- element.style.position = 'relative';
- // Opera returns the offset relative to the positioning context, when an
- // element is position relative but top and left have not been defined
- if (window.opera) {
- element.style.top = 0;
- element.style.left = 0;
- }
- }
- return element;
- },
-
- undoPositioned: function(element) {
- element = $(element);
- if (element._madePositioned) {
- element._madePositioned = undefined;
- element.style.position =
- element.style.top =
- element.style.left =
- element.style.bottom =
- element.style.right = '';
- }
- return element;
- },
-
- makeClipping: function(element) {
- element = $(element);
- if (element._overflow) return element;
- element._overflow = Element.getStyle(element, 'overflow') || 'auto';
- if (element._overflow !== 'hidden')
- element.style.overflow = 'hidden';
- return element;
- },
-
- undoClipping: function(element) {
- element = $(element);
- if (!element._overflow) return element;
- element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
- element._overflow = null;
- return element;
- },
-
- cumulativeOffset: function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- element = element.offsetParent;
- } while (element);
- return Element._returnOffset(valueL, valueT);
- },
-
- positionedOffset: function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- element = element.offsetParent;
- if (element) {
- if (element.tagName == 'BODY') break;
- var p = Element.getStyle(element, 'position');
- if (p !== 'static') break;
- }
- } while (element);
- return Element._returnOffset(valueL, valueT);
- },
-
- absolutize: function(element) {
- element = $(element);
- if (element.getStyle('position') == 'absolute') return;
- // Position.prepare(); // To be done manually by Scripty when it needs it.
-
- var offsets = element.positionedOffset();
- var top = offsets[1];
- var left = offsets[0];
- var width = element.clientWidth;
- var height = element.clientHeight;
-
- element._originalLeft = left - parseFloat(element.style.left || 0);
- element._originalTop = top - parseFloat(element.style.top || 0);
- element._originalWidth = element.style.width;
- element._originalHeight = element.style.height;
-
- element.style.position = 'absolute';
- element.style.top = top + 'px';
- element.style.left = left + 'px';
- element.style.width = width + 'px';
- element.style.height = height + 'px';
- return element;
- },
-
- relativize: function(element) {
- element = $(element);
- if (element.getStyle('position') == 'relative') return;
- // Position.prepare(); // To be done manually by Scripty when it needs it.
-
- element.style.position = 'relative';
- var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
- var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
-
- element.style.top = top + 'px';
- element.style.left = left + 'px';
- element.style.height = element._originalHeight;
- element.style.width = element._originalWidth;
- return element;
- },
-
- cumulativeScrollOffset: function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.scrollTop || 0;
- valueL += element.scrollLeft || 0;
- element = element.parentNode;
- } while (element);
- return Element._returnOffset(valueL, valueT);
- },
-
- getOffsetParent: function(element) {
- if (element.offsetParent) return $(element.offsetParent);
- if (element == document.body) return $(element);
-
- while ((element = element.parentNode) && element != document.body)
- if (Element.getStyle(element, 'position') != 'static')
- return $(element);
-
- return $(document.body);
- },
-
- viewportOffset: function(forElement) {
- var valueT = 0, valueL = 0;
-
- var element = forElement;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
-
- // Safari fix
- if (element.offsetParent == document.body &&
- Element.getStyle(element, 'position') == 'absolute') break;
-
- } while (element = element.offsetParent);
-
- element = forElement;
- do {
- if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
- valueT -= element.scrollTop || 0;
- valueL -= element.scrollLeft || 0;
- }
- } while (element = element.parentNode);
-
- return Element._returnOffset(valueL, valueT);
- },
-
- clonePosition: function(element, source) {
- var options = Object.extend({
- setLeft: true,
- setTop: true,
- setWidth: true,
- setHeight: true,
- offsetTop: 0,
- offsetLeft: 0
- }, arguments[2] || { });
-
- // find page position of source
- source = $(source);
- var p = source.viewportOffset();
-
- // find coordinate system to use
- element = $(element);
- var delta = [0, 0];
- var parent = null;
- // delta [0,0] will do fine with position: fixed elements,
- // position:absolute needs offsetParent deltas
- if (Element.getStyle(element, 'position') == 'absolute') {
- parent = element.getOffsetParent();
- delta = parent.viewportOffset();
- }
-
- // correct by body offsets (fixes Safari)
- if (parent == document.body) {
- delta[0] -= document.body.offsetLeft;
- delta[1] -= document.body.offsetTop;
- }
-
- // set position
- if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
- if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
- if (options.setWidth) element.style.width = source.offsetWidth + 'px';
- if (options.setHeight) element.style.height = source.offsetHeight + 'px';
- return element;
- }
-};
-
-Element.Methods.identify.counter = 1;
-
-Object.extend(Element.Methods, {
- getElementsBySelector: Element.Methods.select,
- childElements: Element.Methods.immediateDescendants
-});
-
-Element._attributeTranslations = {
- write: {
- names: {
- className: 'class',
- htmlFor: 'for'
- },
- values: { }
- }
-};
-
-if (Prototype.Browser.Opera) {
- Element.Methods.getStyle = Element.Methods.getStyle.wrap(
- function(proceed, element, style) {
- switch (style) {
- case 'left': case 'top': case 'right': case 'bottom':
- if (proceed(element, 'position') === 'static') return null;
- case 'height': case 'width':
- // returns '0px' for hidden elements; we want it to return null
- if (!Element.visible(element)) return null;
-
- // returns the border-box dimensions rather than the content-box
- // dimensions, so we subtract padding and borders from the value
- var dim = parseInt(proceed(element, style), 10);
-
- if (dim !== element['offset' + style.capitalize()])
- return dim + 'px';
-
- var properties;
- if (style === 'height') {
- properties = ['border-top-width', 'padding-top',
- 'padding-bottom', 'border-bottom-width'];
- }
- else {
- properties = ['border-left-width', 'padding-left',
- 'padding-right', 'border-right-width'];
- }
- return properties.inject(dim, function(memo, property) {
- var val = proceed(element, property);
- return val === null ? memo : memo - parseInt(val, 10);
- }) + 'px';
- default: return proceed(element, style);
- }
- }
- );
-
- Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
- function(proceed, element, attribute) {
- if (attribute === 'title') return element.title;
- return proceed(element, attribute);
- }
- );
-}
-
-else if (Prototype.Browser.IE) {
- // IE doesn't report offsets correctly for static elements, so we change them
- // to "relative" to get the values, then change them back.
- Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
- function(proceed, element) {
- element = $(element);
- var position = element.getStyle('position');
- if (position !== 'static') return proceed(element);
- element.setStyle({ position: 'relative' });
- var value = proceed(element);
- element.setStyle({ position: position });
- return value;
- }
- );
-
- $w('positionedOffset viewportOffset').each(function(method) {
- Element.Methods[method] = Element.Methods[method].wrap(
- function(proceed, element) {
- element = $(element);
- var position = element.getStyle('position');
- if (position !== 'static') return proceed(element);
- // Trigger hasLayout on the offset parent so that IE6 reports
- // accurate offsetTop and offsetLeft values for position: fixed.
- var offsetParent = element.getOffsetParent();
- if (offsetParent && offsetParent.getStyle('position') === 'fixed')
- offsetParent.setStyle({ zoom: 1 });
- element.setStyle({ position: 'relative' });
- var value = proceed(element);
- element.setStyle({ position: position });
- return value;
- }
- );
- });
-
- Element.Methods.getStyle = function(element, style) {
- element = $(element);
- style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
- var value = element.style[style];
- if (!value && element.currentStyle) value = element.currentStyle[style];
-
- if (style == 'opacity') {
- if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
- if (value[1]) return parseFloat(value[1]) / 100;
- return 1.0;
- }
-
- if (value == 'auto') {
- if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
- return element['offset' + style.capitalize()] + 'px';
- return null;
- }
- return value;
- };
-
- Element.Methods.setOpacity = function(element, value) {
- function stripAlpha(filter){
- return filter.replace(/alpha\([^\)]*\)/gi,'');
- }
- element = $(element);
- var currentStyle = element.currentStyle;
- if ((currentStyle && !currentStyle.hasLayout) ||
- (!currentStyle && element.style.zoom == 'normal'))
- element.style.zoom = 1;
-
- var filter = element.getStyle('filter'), style = element.style;
- if (value == 1 || value === '') {
- (filter = stripAlpha(filter)) ?
- style.filter = filter : style.removeAttribute('filter');
- return element;
- } else if (value < 0.00001) value = 0;
- style.filter = stripAlpha(filter) +
- 'alpha(opacity=' + (value * 100) + ')';
- return element;
- };
-
- Element._attributeTranslations = {
- read: {
- names: {
- 'class': 'className',
- 'for': 'htmlFor'
- },
- values: {
- _getAttr: function(element, attribute) {
- return element.getAttribute(attribute, 2);
- },
- _getAttrNode: function(element, attribute) {
- var node = element.getAttributeNode(attribute);
- return node ? node.value : "";
- },
- _getEv: function(element, attribute) {
- attribute = element.getAttribute(attribute);
- return attribute ? attribute.toString().slice(23, -2) : null;
- },
- _flag: function(element, attribute) {
- return $(element).hasAttribute(attribute) ? attribute : null;
- },
- style: function(element) {
- return element.style.cssText.toLowerCase();
- },
- title: function(element) {
- return element.title;
- }
- }
- }
- };
-
- Element._attributeTranslations.write = {
- names: Object.extend({
- cellpadding: 'cellPadding',
- cellspacing: 'cellSpacing'
- }, Element._attributeTranslations.read.names),
- values: {
- checked: function(element, value) {
- element.checked = !!value;
- },
-
- style: function(element, value) {
- element.style.cssText = value ? value : '';
- }
- }
- };
-
- Element._attributeTranslations.has = {};
-
- $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
- 'encType maxLength readOnly longDesc').each(function(attr) {
- Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
- Element._attributeTranslations.has[attr.toLowerCase()] = attr;
- });
-
- (function(v) {
- Object.extend(v, {
- href: v._getAttr,
- src: v._getAttr,
- type: v._getAttr,
- action: v._getAttrNode,
- disabled: v._flag,
- checked: v._flag,
- readonly: v._flag,
- multiple: v._flag,
- onload: v._getEv,
- onunload: v._getEv,
- onclick: v._getEv,
- ondblclick: v._getEv,
- onmousedown: v._getEv,
- onmouseup: v._getEv,
- onmouseover: v._getEv,
- onmousemove: v._getEv,
- onmouseout: v._getEv,
- onfocus: v._getEv,
- onblur: v._getEv,
- onkeypress: v._getEv,
- onkeydown: v._getEv,
- onkeyup: v._getEv,
- onsubmit: v._getEv,
- onreset: v._getEv,
- onselect: v._getEv,
- onchange: v._getEv
- });
- })(Element._attributeTranslations.read.values);
-}
-
-else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
- Element.Methods.setOpacity = function(element, value) {
- element = $(element);
- element.style.opacity = (value == 1) ? 0.999999 :
- (value === '') ? '' : (value < 0.00001) ? 0 : value;
- return element;
- };
-}
-
-else if (Prototype.Browser.WebKit) {
- Element.Methods.setOpacity = function(element, value) {
- element = $(element);
- element.style.opacity = (value == 1 || value === '') ? '' :
- (value < 0.00001) ? 0 : value;
-
- if (value == 1)
- if(element.tagName == 'IMG' && element.width) {
- element.width++; element.width--;
- } else try {
- var n = document.createTextNode(' ');
- element.appendChild(n);
- element.removeChild(n);
- } catch (e) { }
-
- return element;
- };
-
- // Safari returns margins on body which is incorrect if the child is absolutely
- // positioned. For performance reasons, redefine Element#cumulativeOffset for
- // KHTML/WebKit only.
- Element.Methods.cumulativeOffset = function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- if (element.offsetParent == document.body)
- if (Element.getStyle(element, 'position') == 'absolute') break;
-
- element = element.offsetParent;
- } while (element);
-
- return Element._returnOffset(valueL, valueT);
- };
-}
-
-if (Prototype.Browser.IE || Prototype.Browser.Opera) {
- // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
- Element.Methods.update = function(element, content) {
- element = $(element);
-
- if (content && content.toElement) content = content.toElement();
- if (Object.isElement(content)) return element.update().insert(content);
-
- content = Object.toHTML(content);
- var tagName = element.tagName.toUpperCase();
-
- if (tagName in Element._insertionTranslations.tags) {
- $A(element.childNodes).each(function(node) { element.removeChild(node) });
- Element._getContentFromAnonymousElement(tagName, content.stripScripts())
- .each(function(node) { element.appendChild(node) });
- }
- else element.innerHTML = content.stripScripts();
-
- content.evalScripts.bind(content).defer();
- return element;
- };
-}
-
-if ('outerHTML' in document.createElement('div')) {
- Element.Methods.replace = function(element, content) {
- element = $(element);
-
- if (content && content.toElement) content = content.toElement();
- if (Object.isElement(content)) {
- element.parentNode.replaceChild(content, element);
- return element;
- }
-
- content = Object.toHTML(content);
- var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
-
- if (Element._insertionTranslations.tags[tagName]) {
- var nextSibling = element.next();
- var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
- parent.removeChild(element);
- if (nextSibling)
- fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
- else
- fragments.each(function(node) { parent.appendChild(node) });
- }
- else element.outerHTML = content.stripScripts();
-
- content.evalScripts.bind(content).defer();
- return element;
- };
-}
-
-Element._returnOffset = function(l, t) {
- var result = [l, t];
- result.left = l;
- result.top = t;
- return result;
-};
-
-Element._getContentFromAnonymousElement = function(tagName, html) {
- var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
- if (t) {
- div.innerHTML = t[0] + html + t[1];
- t[2].times(function() { div = div.firstChild });
- } else div.innerHTML = html;
- return $A(div.childNodes);
-};
-
-Element._insertionTranslations = {
- before: function(element, node) {
- element.parentNode.insertBefore(node, element);
- },
- top: function(element, node) {
- element.insertBefore(node, element.firstChild);
- },
- bottom: function(element, node) {
- element.appendChild(node);
- },
- after: function(element, node) {
- element.parentNode.insertBefore(node, element.nextSibling);
- },
- tags: {
- TABLE: ['<table>', '</table>', 1],
- TBODY: ['<table><tbody>', '</tbody></table>', 2],
- TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
- TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
- SELECT: ['<select>', '</select>', 1]
- }
-};
-
-(function() {
- Object.extend(this.tags, {
- THEAD: this.tags.TBODY,
- TFOOT: this.tags.TBODY,
- TH: this.tags.TD
- });
-}).call(Element._insertionTranslations);
-
-Element.Methods.Simulated = {
- hasAttribute: function(element, attribute) {
- attribute = Element._attributeTranslations.has[attribute] || attribute;
- var node = $(element).getAttributeNode(attribute);
- return node && node.specified;
- }
-};
-
-Element.Methods.ByTag = { };
-
-Object.extend(Element, Element.Methods);
-
-if (!Prototype.BrowserFeatures.ElementExtensions &&
- document.createElement('div').__proto__) {
- window.HTMLElement = { };
- window.HTMLElement.prototype = document.createElement('div').__proto__;
- Prototype.BrowserFeatures.ElementExtensions = true;
-}
-
-Element.extend = (function() {
- if (Prototype.BrowserFeatures.SpecificElementExtensions)
- return Prototype.K;
-
- var Methods = { }, ByTag = Element.Methods.ByTag;
-
- var extend = Object.extend(function(element) {
- if (!element || element._extendedByPrototype ||
- element.nodeType != 1 || element == window) return element;
-
- var methods = Object.clone(Methods),
- tagName = element.tagName, property, value;
-
- // extend methods for specific tags
- if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
-
- for (property in methods) {
- value = methods[property];
- if (Object.isFunction(value) && !(property in element))
- element[property] = value.methodize();
- }
-
- element._extendedByPrototype = Prototype.emptyFunction;
- return element;
-
- }, {
- refresh: function() {
- // extend methods for all tags (Safari doesn't need this)
- if (!Prototype.BrowserFeatures.ElementExtensions) {
- Object.extend(Methods, Element.Methods);
- Object.extend(Methods, Element.Methods.Simulated);
- }
- }
- });
-
- extend.refresh();
- return extend;
-})();
-
-Element.hasAttribute = function(element, attribute) {
- if (element.hasAttribute) return element.hasAttribute(attribute);
- return Element.Methods.Simulated.hasAttribute(element, attribute);
-};
-
-Element.addMethods = function(methods) {
- var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
-
- if (!methods) {
- Object.extend(Form, Form.Methods);
- Object.extend(Form.Element, Form.Element.Methods);
- Object.extend(Element.Methods.ByTag, {
- "FORM": Object.clone(Form.Methods),
- "INPUT": Object.clone(Form.Element.Methods),
- "SELECT": Object.clone(Form.Element.Methods),
- "TEXTAREA": Object.clone(Form.Element.Methods)
- });
- }
-
- if (arguments.length == 2) {
- var tagName = methods;
- methods = arguments[1];
- }
-
- if (!tagName) Object.extend(Element.Methods, methods || { });
- else {
- if (Object.isArray(tagName)) tagName.each(extend);
- else extend(tagName);
- }
-
- function extend(tagName) {
- tagName = tagName.toUpperCase();
- if (!Element.Methods.ByTag[tagName])
- Element.Methods.ByTag[tagName] = { };
- Object.extend(Element.Methods.ByTag[tagName], methods);
- }
-
- function copy(methods, destination, onlyIfAbsent) {
- onlyIfAbsent = onlyIfAbsent || false;
- for (var property in methods) {
- var value = methods[property];
- if (!Object.isFunction(value)) continue;
- if (!onlyIfAbsent || !(property in destination))
- destination[property] = value.methodize();
- }
- }
-
- function findDOMClass(tagName) {
- var klass;
- var trans = {
- "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
- "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
- "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
- "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
- "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
- "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
- "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
- "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
- "FrameSet", "IFRAME": "IFrame"
- };
- if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
- if (window[klass]) return window[klass];
- klass = 'HTML' + tagName + 'Element';
- if (window[klass]) return window[klass];
- klass = 'HTML' + tagName.capitalize() + 'Element';
- if (window[klass]) return window[klass];
-
- window[klass] = { };
- window[klass].prototype = document.createElement(tagName).__proto__;
- return window[klass];
- }
-
- if (F.ElementExtensions) {
- copy(Element.Methods, HTMLElement.prototype);
- copy(Element.Methods.Simulated, HTMLElement.prototype, true);
- }
-
- if (F.SpecificElementExtensions) {
- for (var tag in Element.Methods.ByTag) {
- var klass = findDOMClass(tag);
- if (Object.isUndefined(klass)) continue;
- copy(T[tag], klass.prototype);
- }
- }
-
- Object.extend(Element, Element.Methods);
- delete Element.ByTag;
-
- if (Element.extend.refresh) Element.extend.refresh();
- Element.cache = { };
-};
-
-document.viewport = {
- getDimensions: function() {
- var dimensions = { };
- var B = Prototype.Browser;
- $w('width height').each(function(d) {
- var D = d.capitalize();
- dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
- (B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
- });
- return dimensions;
- },
-
- getWidth: function() {
- return this.getDimensions().width;
- },
-
- getHeight: function() {
- return this.getDimensions().height;
- },
-
- getScrollOffsets: function() {
- return Element._returnOffset(
- window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
- window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
- }
-};
-/* Portions of the Selector class are derived from Jack Slocum’s DomQuery,
- * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
- * license. Please see http://www.yui-ext.com/ for more information. */
-
-var Selector = Class.create({
- initialize: function(expression) {
- this.expression = expression.strip();
- this.compileMatcher();
- },
-
- shouldUseXPath: function() {
- if (!Prototype.BrowserFeatures.XPath) return false;
-
- var e = this.expression;
-
- // Safari 3 chokes on :*-of-type and :empty
- if (Prototype.Browser.WebKit &&
- (e.include("-of-type") || e.include(":empty")))
- return false;
-
- // XPath can't do namespaced attributes, nor can it read
- // the "checked" property from DOM nodes
- if ((/(\[[\w-]*?:|:checked)/).test(this.expression))
- return false;
-
- return true;
- },
-
- compileMatcher: function() {
- if (this.shouldUseXPath())
- return this.compileXPathMatcher();
-
- var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
- c = Selector.criteria, le, p, m;
-
- if (Selector._cache[e]) {
- this.matcher = Selector._cache[e];
- return;
- }
-
- this.matcher = ["this.matcher = function(root) {",
- "var r = root, h = Selector.handlers, c = false, n;"];
-
- while (e && le != e && (/\S/).test(e)) {
- le = e;
- for (var i in ps) {
- p = ps[i];
- if (m = e.match(p)) {
- this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
- new Template(c[i]).evaluate(m));
- e = e.replace(m[0], '');
- break;
- }
- }
- }
-
- this.matcher.push("return h.unique(n);\n}");
- eval(this.matcher.join('\n'));
- Selector._cache[this.expression] = this.matcher;
- },
-
- compileXPathMatcher: function() {
- var e = this.expression, ps = Selector.patterns,
- x = Selector.xpath, le, m;
-
- if (Selector._cache[e]) {
- this.xpath = Selector._cache[e]; return;
- }
-
- this.matcher = ['.//*'];
- while (e && le != e && (/\S/).test(e)) {
- le = e;
- for (var i in ps) {
- if (m = e.match(ps[i])) {
- this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
- new Template(x[i]).evaluate(m));
- e = e.replace(m[0], '');
- break;
- }
- }
- }
-
- this.xpath = this.matcher.join('');
- Selector._cache[this.expression] = this.xpath;
- },
-
- findElements: function(root) {
- root = root || document;
- if (this.xpath) return document._getElementsByXPath(this.xpath, root);
- return this.matcher(root);
- },
-
- match: function(element) {
- this.tokens = [];
-
- var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
- var le, p, m;
-
- while (e && le !== e && (/\S/).test(e)) {
- le = e;
- for (var i in ps) {
- p = ps[i];
- if (m = e.match(p)) {
- // use the Selector.assertions methods unless the selector
- // is too complex.
- if (as[i]) {
- this.tokens.push([i, Object.clone(m)]);
- e = e.replace(m[0], '');
- } else {
- // reluctantly do a document-wide search
- // and look for a match in the array
- return this.findElements(document).include(element);
- }
- }
- }
- }
-
- var match = true, name, matches;
- for (var i = 0, token; token = this.tokens[i]; i++) {
- name = token[0], matches = token[1];
- if (!Selector.assertions[name](element, matches)) {
- match = false; break;
- }
- }
-
- return match;
- },
-
- toString: function() {
- return this.expression;
- },
-
- inspect: function() {
- return "#<Selector:" + this.expression.inspect() + ">";
- }
-});
-
-Object.extend(Selector, {
- _cache: { },
-
- xpath: {
- descendant: "//*",
- child: "/*",
- adjacent: "/following-sibling::*[1]",
- laterSibling: '/following-sibling::*',
- tagName: function(m) {
- if (m[1] == '*') return '';
- return "[local-name()='" + m[1].toLowerCase() +
- "' or local-name()='" + m[1].toUpperCase() + "']";
- },
- className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
- id: "[@id='#{1}']",
- attrPresence: function(m) {
- m[1] = m[1].toLowerCase();
- return new Template("[@#{1}]").evaluate(m);
- },
- attr: function(m) {
- m[1] = m[1].toLowerCase();
- m[3] = m[5] || m[6];
- return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
- },
- pseudo: function(m) {
- var h = Selector.xpath.pseudos[m[1]];
- if (!h) return '';
- if (Object.isFunction(h)) return h(m);
- return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
- },
- operators: {
- '=': "[@#{1}='#{3}']",
- '!=': "[@#{1}!='#{3}']",
- '^=': "[starts-with(@#{1}, '#{3}')]",
- '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
- '*=': "[contains(@#{1}, '#{3}')]",
- '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
- '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
- },
- pseudos: {
- 'first-child': '[not(preceding-sibling::*)]',
- 'last-child': '[not(following-sibling::*)]',
- 'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
- 'empty': "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
- 'checked': "[@checked]",
- 'disabled': "[@disabled]",
- 'enabled': "[not(@disabled)]",
- 'not': function(m) {
- var e = m[6], p = Selector.patterns,
- x = Selector.xpath, le, v;
-
- var exclusion = [];
- while (e && le != e && (/\S/).test(e)) {
- le = e;
- for (var i in p) {
- if (m = e.match(p[i])) {
- v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
- exclusion.push("(" + v.substring(1, v.length - 1) + ")");
- e = e.replace(m[0], '');
- break;
- }
- }
- }
- return "[not(" + exclusion.join(" and ") + ")]";
- },
- 'nth-child': function(m) {
- return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
- },
- 'nth-last-child': function(m) {
- return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
- },
- 'nth-of-type': function(m) {
- return Selector.xpath.pseudos.nth("position() ", m);
- },
- 'nth-last-of-type': function(m) {
- return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
- },
- 'first-of-type': function(m) {
- m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
- },
- 'last-of-type': function(m) {
- m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
- },
- 'only-of-type': function(m) {
- var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
- },
- nth: function(fragment, m) {
- var mm, formula = m[6], predicate;
- if (formula == 'even') formula = '2n+0';
- if (formula == 'odd') formula = '2n+1';
- if (mm = formula.match(/^(\d+)$/)) // digit only
- return '[' + fragment + "= " + mm[1] + ']';
- if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
- if (mm[1] == "-") mm[1] = -1;
- var a = mm[1] ? Number(mm[1]) : 1;
- var b = mm[2] ? Number(mm[2]) : 0;
- predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
- "((#{fragment} - #{b}) div #{a} >= 0)]";
- return new Template(predicate).evaluate({
- fragment: fragment, a: a, b: b });
- }
- }
- }
- },
-
- criteria: {
- tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
- className: 'n = h.className(n, r, "#{1}", c); c = false;',
- id: 'n = h.id(n, r, "#{1}", c); c = false;',
- attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
- attr: function(m) {
- m[3] = (m[5] || m[6]);
- return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
- },
- pseudo: function(m) {
- if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
- return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
- },
- descendant: 'c = "descendant";',
- child: 'c = "child";',
- adjacent: 'c = "adjacent";',
- laterSibling: 'c = "laterSibling";'
- },
-
- patterns: {
- // combinators must be listed first
- // (and descendant needs to be last combinator)
- laterSibling: /^\s*~\s*/,
- child: /^\s*>\s*/,
- adjacent: /^\s*\+\s*/,
- descendant: /^\s/,
-
- // selectors follow
- tagName: /^\s*(\*|[\w\-]+)(\b|$)?/,
- id: /^#([\w\-\*]+)(\b|$)/,
- className: /^\.([\w\-\*]+)(\b|$)/,
- pseudo:
-/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
- attrPresence: /^\[([\w]+)\]/,
- attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
- },
-
- // for Selector.match and Element#match
- assertions: {
- tagName: function(element, matches) {
- return matches[1].toUpperCase() == element.tagName.toUpperCase();
- },
-
- className: function(element, matches) {
- return Element.hasClassName(element, matches[1]);
- },
-
- id: function(element, matches) {
- return element.id === matches[1];
- },
-
- attrPresence: function(element, matches) {
- return Element.hasAttribute(element, matches[1]);
- },
-
- attr: function(element, matches) {
- var nodeValue = Element.readAttribute(element, matches[1]);
- return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
- }
- },
-
- handlers: {
- // UTILITY FUNCTIONS
- // joins two collections
- concat: function(a, b) {
- for (var i = 0, node; node = b[i]; i++)
- a.push(node);
- return a;
- },
-
- // marks an array of nodes for counting
- mark: function(nodes) {
- var _true = Prototype.emptyFunction;
- for (var i = 0, node; node = nodes[i]; i++)
- node._countedByPrototype = _true;
- return nodes;
- },
-
- unmark: function(nodes) {
- for (var i = 0, node; node = nodes[i]; i++)
- node._countedByPrototype = undefined;
- return nodes;
- },
-
- // mark each child node with its position (for nth calls)
- // "ofType" flag indicates whether we're indexing for nth-of-type
- // rather than nth-child
- index: function(parentNode, reverse, ofType) {
- parentNode._countedByPrototype = Prototype.emptyFunction;
- if (reverse) {
- for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
- var node = nodes[i];
- if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
- }
- } else {
- for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
- if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
- }
- },
-
- // filters out duplicates and extends all nodes
- unique: function(nodes) {
- if (nodes.length == 0) return nodes;
- var results = [], n;
- for (var i = 0, l = nodes.length; i < l; i++)
- if (!(n = nodes[i])._countedByPrototype) {
- n._countedByPrototype = Prototype.emptyFunction;
- results.push(Element.extend(n));
- }
- return Selector.handlers.unmark(results);
- },
-
- // COMBINATOR FUNCTIONS
- descendant: function(nodes) {
- var h = Selector.handlers;
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- h.concat(results, node.getElementsByTagName('*'));
- return results;
- },
-
- child: function(nodes) {
- var h = Selector.handlers;
- for (var i = 0, results = [], node; node = nodes[i]; i++) {
- for (var j = 0, child; child = node.childNodes[j]; j++)
- if (child.nodeType == 1 && child.tagName != '!') results.push(child);
- }
- return results;
- },
-
- adjacent: function(nodes) {
- for (var i = 0, results = [], node; node = nodes[i]; i++) {
- var next = this.nextElementSibling(node);
- if (next) results.push(next);
- }
- return results;
- },
-
- laterSibling: function(nodes) {
- var h = Selector.handlers;
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- h.concat(results, Element.nextSiblings(node));
- return results;
- },
-
- nextElementSibling: function(node) {
- while (node = node.nextSibling)
- if (node.nodeType == 1) return node;
- return null;
- },
-
- previousElementSibling: function(node) {
- while (node = node.previousSibling)
- if (node.nodeType == 1) return node;
- return null;
- },
-
- // TOKEN FUNCTIONS
- tagName: function(nodes, root, tagName, combinator) {
- var uTagName = tagName.toUpperCase();
- var results = [], h = Selector.handlers;
- if (nodes) {
- if (combinator) {
- // fastlane for ordinary descendant combinators
- if (combinator == "descendant") {
- for (var i = 0, node; node = nodes[i]; i++)
- h.concat(results, node.getElementsByTagName(tagName));
- return results;
- } else nodes = this[combinator](nodes);
- if (tagName == "*") return nodes;
- }
- for (var i = 0, node; node = nodes[i]; i++)
- if (node.tagName.toUpperCase() === uTagName) results.push(node);
- return results;
- } else return root.getElementsByTagName(tagName);
- },
-
- id: function(nodes, root, id, combinator) {
- var targetNode = $(id), h = Selector.handlers;
- if (!targetNode) return [];
- if (!nodes && root == document) return [targetNode];
- if (nodes) {
- if (combinator) {
- if (combinator == 'child') {
- for (var i = 0, node; node = nodes[i]; i++)
- if (targetNode.parentNode == node) return [targetNode];
- } else if (combinator == 'descendant') {
- for (var i = 0, node; node = nodes[i]; i++)
- if (Element.descendantOf(targetNode, node)) return [targetNode];
- } else if (combinator == 'adjacent') {
- for (var i = 0, node; node = nodes[i]; i++)
- if (Selector.handlers.previousElementSibling(targetNode) == node)
- return [targetNode];
- } else nodes = h[combinator](nodes);
- }
- for (var i = 0, node; node = nodes[i]; i++)
- if (node == targetNode) return [targetNode];
- return [];
- }
- return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
- },
-
- className: function(nodes, root, className, combinator) {
- if (nodes && combinator) nodes = this[combinator](nodes);
- return Selector.handlers.byClassName(nodes, root, className);
- },
-
- byClassName: function(nodes, root, className) {
- if (!nodes) nodes = Selector.handlers.descendant([root]);
- var needle = ' ' + className + ' ';
- for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
- nodeClassName = node.className;
- if (nodeClassName.length == 0) continue;
- if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
- results.push(node);
- }
- return results;
- },
-
- attrPresence: function(nodes, root, attr, combinator) {
- if (!nodes) nodes = root.getElementsByTagName("*");
- if (nodes && combinator) nodes = this[combinator](nodes);
- var results = [];
- for (var i = 0, node; node = nodes[i]; i++)
- if (Element.hasAttribute(node, attr)) results.push(node);
- return results;
- },
-
- attr: function(nodes, root, attr, value, operator, combinator) {
- if (!nodes) nodes = root.getElementsByTagName("*");
- if (nodes && combinator) nodes = this[combinator](nodes);
- var handler = Selector.operators[operator], results = [];
- for (var i = 0, node; node = nodes[i]; i++) {
- var nodeValue = Element.readAttribute(node, attr);
- if (nodeValue === null) continue;
- if (handler(nodeValue, value)) results.push(node);
- }
- return results;
- },
-
- pseudo: function(nodes, name, value, root, combinator) {
- if (nodes && combinator) nodes = this[combinator](nodes);
- if (!nodes) nodes = root.getElementsByTagName("*");
- return Selector.pseudos[name](nodes, value, root);
- }
- },
-
- pseudos: {
- 'first-child': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++) {
- if (Selector.handlers.previousElementSibling(node)) continue;
- results.push(node);
- }
- return results;
- },
- 'last-child': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++) {
- if (Selector.handlers.nextElementSibling(node)) continue;
- results.push(node);
- }
- return results;
- },
- 'only-child': function(nodes, value, root) {
- var h = Selector.handlers;
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
- results.push(node);
- return results;
- },
- 'nth-child': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, formula, root);
- },
- 'nth-last-child': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, formula, root, true);
- },
- 'nth-of-type': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, formula, root, false, true);
- },
- 'nth-last-of-type': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, formula, root, true, true);
- },
- 'first-of-type': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, "1", root, false, true);
- },
- 'last-of-type': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, "1", root, true, true);
- },
- 'only-of-type': function(nodes, formula, root) {
- var p = Selector.pseudos;
- return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
- },
-
- // handles the an+b logic
- getIndices: function(a, b, total) {
- if (a == 0) return b > 0 ? [b] : [];
- return $R(1, total).inject([], function(memo, i) {
- if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
- return memo;
- });
- },
-
- // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
- nth: function(nodes, formula, root, reverse, ofType) {
- if (nodes.length == 0) return [];
- if (formula == 'even') formula = '2n+0';
- if (formula == 'odd') formula = '2n+1';
- var h = Selector.handlers, results = [], indexed = [], m;
- h.mark(nodes);
- for (var i = 0, node; node = nodes[i]; i++) {
- if (!node.parentNode._countedByPrototype) {
- h.index(node.parentNode, reverse, ofType);
- indexed.push(node.parentNode);
- }
- }
- if (formula.match(/^\d+$/)) { // just a number
- formula = Number(formula);
- for (var i = 0, node; node = nodes[i]; i++)
- if (node.nodeIndex == formula) results.push(node);
- } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
- if (m[1] == "-") m[1] = -1;
- var a = m[1] ? Number(m[1]) : 1;
- var b = m[2] ? Number(m[2]) : 0;
- var indices = Selector.pseudos.getIndices(a, b, nodes.length);
- for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
- for (var j = 0; j < l; j++)
- if (node.nodeIndex == indices[j]) results.push(node);
- }
- }
- h.unmark(nodes);
- h.unmark(indexed);
- return results;
- },
-
- 'empty': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++) {
- // IE treats comments as element nodes
- if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
- results.push(node);
- }
- return results;
- },
-
- 'not': function(nodes, selector, root) {
- var h = Selector.handlers, selectorType, m;
- var exclusions = new Selector(selector).findElements(root);
- h.mark(exclusions);
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- if (!node._countedByPrototype) results.push(node);
- h.unmark(exclusions);
- return results;
- },
-
- 'enabled': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- if (!node.disabled) results.push(node);
- return results;
- },
-
- 'disabled': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- if (node.disabled) results.push(node);
- return results;
- },
-
- 'checked': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- if (node.checked) results.push(node);
- return results;
- }
- },
-
- operators: {
- '=': function(nv, v) { return nv == v; },
- '!=': function(nv, v) { return nv != v; },
- '^=': function(nv, v) { return nv.startsWith(v); },
- '$=': function(nv, v) { return nv.endsWith(v); },
- '*=': function(nv, v) { return nv.include(v); },
- '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
- '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
- },
-
- split: function(expression) {
- var expressions = [];
- expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
- expressions.push(m[1].strip());
- });
- return expressions;
- },
-
- matchElements: function(elements, expression) {
- var matches = $$(expression), h = Selector.handlers;
- h.mark(matches);
- for (var i = 0, results = [], element; element = elements[i]; i++)
- if (element._countedByPrototype) results.push(element);
- h.unmark(matches);
- return results;
- },
-
- findElement: function(elements, expression, index) {
- if (Object.isNumber(expression)) {
- index = expression; expression = false;
- }
- return Selector.matchElements(elements, expression || '*')[index || 0];
- },
-
- findChildElements: function(element, expressions) {
- expressions = Selector.split(expressions.join(','));
- var results = [], h = Selector.handlers;
- for (var i = 0, l = expressions.length, selector; i < l; i++) {
- selector = new Selector(expressions[i].strip());
- h.concat(results, selector.findElements(element));
- }
- return (l > 1) ? h.unique(results) : results;
- }
-});
-
-if (Prototype.Browser.IE) {
- Object.extend(Selector.handlers, {
- // IE returns comment nodes on getElementsByTagName("*").
- // Filter them out.
- concat: function(a, b) {
- for (var i = 0, node; node = b[i]; i++)
- if (node.tagName !== "!") a.push(node);
- return a;
- },
-
- // IE improperly serializes _countedByPrototype in (inner|outer)HTML.
- unmark: function(nodes) {
- for (var i = 0, node; node = nodes[i]; i++)
- node.removeAttribute('_countedByPrototype');
- return nodes;
- }
- });
-}
-
-function $$() {
- return Selector.findChildElements(document, $A(arguments));
-}
-var Form = {
- reset: function(form) {
- $(form).reset();
- return form;
- },
-
- serializeElements: function(elements, options) {
- if (typeof options != 'object') options = { hash: !!options };
- else if (Object.isUndefined(options.hash)) options.hash = true;
- var key, value, submitted = false, submit = options.submit;
-
- var data = elements.inject({ }, function(result, element) {
- if (!element.disabled && element.name) {
- key = element.name; value = $(element).getValue();
- if (value != null && (element.type != 'submit' || (!submitted &&
- submit !== false && (!submit || key == submit) && (submitted = true)))) {
- if (key in result) {
- // a key is already present; construct an array of values
- if (!Object.isArray(result[key])) result[key] = [result[key]];
- result[key].push(value);
- }
- else result[key] = value;
- }
- }
- return result;
- });
-
- return options.hash ? data : Object.toQueryString(data);
- }
-};
-
-Form.Methods = {
- serialize: function(form, options) {
- return Form.serializeElements(Form.getElements(form), options);
- },
-
- getElements: function(form) {
- return $A($(form).getElementsByTagName('*')).inject([],
- function(elements, child) {
- if (Form.Element.Serializers[child.tagName.toLowerCase()])
- elements.push(Element.extend(child));
- return elements;
- }
- );
- },
-
- getInputs: function(form, typeName, name) {
- form = $(form);
- var inputs = form.getElementsByTagName('input');
-
- if (!typeName && !name) return $A(inputs).map(Element.extend);
-
- for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
- var input = inputs[i];
- if ((typeName && input.type != typeName) || (name && input.name != name))
- continue;
- matchingInputs.push(Element.extend(input));
- }
-
- return matchingInputs;
- },
-
- disable: function(form) {
- form = $(form);
- Form.getElements(form).invoke('disable');
- return form;
- },
-
- enable: function(form) {
- form = $(form);
- Form.getElements(form).invoke('enable');
- return form;
- },
-
- findFirstElement: function(form) {
- var elements = $(form).getElements().findAll(function(element) {
- return 'hidden' != element.type && !element.disabled;
- });
- var firstByIndex = elements.findAll(function(element) {
- return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
- }).sortBy(function(element) { return element.tabIndex }).first();
-
- return firstByIndex ? firstByIndex : elements.find(function(element) {
- return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
- });
- },
-
- focusFirstElement: function(form) {
- form = $(form);
- form.findFirstElement().activate();
- return form;
- },
-
- request: function(form, options) {
- form = $(form), options = Object.clone(options || { });
-
- var params = options.parameters, action = form.readAttribute('action') || '';
- if (action.blank()) action = window.location.href;
- options.parameters = form.serialize(true);
-
- if (params) {
- if (Object.isString(params)) params = params.toQueryParams();
- Object.extend(options.parameters, params);
- }
-
- if (form.hasAttribute('method') && !options.method)
- options.method = form.method;
-
- return new Ajax.Request(action, options);
- }
-};
-
-/*--------------------------------------------------------------------------*/
-
-Form.Element = {
- focus: function(element) {
- $(element).focus();
- return element;
- },
-
- select: function(element) {
- $(element).select();
- return element;
- }
-};
-
-Form.Element.Methods = {
- serialize: function(element) {
- element = $(element);
- if (!element.disabled && element.name) {
- var value = element.getValue();
- if (value != undefined) {
- var pair = { };
- pair[element.name] = value;
- return Object.toQueryString(pair);
- }
- }
- return '';
- },
-
- getValue: function(element) {
- element = $(element);
- var method = element.tagName.toLowerCase();
- return Form.Element.Serializers[method](element);
- },
-
- setValue: function(element, value) {
- element = $(element);
- var method = element.tagName.toLowerCase();
- Form.Element.Serializers[method](element, value);
- return element;
- },
-
- clear: function(element) {
- $(element).value = '';
- return element;
- },
-
- present: function(element) {
- return $(element).value != '';
- },
-
- activate: function(element) {
- element = $(element);
- try {
- element.focus();
- if (element.select && (element.tagName.toLowerCase() != 'input' ||
- !['button', 'reset', 'submit'].include(element.type)))
- element.select();
- } catch (e) { }
- return element;
- },
-
- disable: function(element) {
- element = $(element);
- element.blur();
- element.disabled = true;
- return element;
- },
-
- enable: function(element) {
- element = $(element);
- element.disabled = false;
- return element;
- }
-};
-
-/*--------------------------------------------------------------------------*/
-
-var Field = Form.Element;
-var $F = Form.Element.Methods.getValue;
-
-/*--------------------------------------------------------------------------*/
-
-Form.Element.Serializers = {
- input: function(element, value) {
- switch (element.type.toLowerCase()) {
- case 'checkbox':
- case 'radio':
- return Form.Element.Serializers.inputSelector(element, value);
- default:
- return Form.Element.Serializers.textarea(element, value);
- }
- },
-
- inputSelector: function(element, value) {
- if (Object.isUndefined(value)) return element.checked ? element.value : null;
- else element.checked = !!value;
- },
-
- textarea: function(element, value) {
- if (Object.isUndefined(value)) return element.value;
- else element.value = value;
- },
-
- select: function(element, index) {
- if (Object.isUndefined(index))
- return this[element.type == 'select-one' ?
- 'selectOne' : 'selectMany'](element);
- else {
- var opt, value, single = !Object.isArray(index);
- for (var i = 0, length = element.length; i < length; i++) {
- opt = element.options[i];
- value = this.optionValue(opt);
- if (single) {
- if (value == index) {
- opt.selected = true;
- return;
- }
- }
- else opt.selected = index.include(value);
- }
- }
- },
-
- selectOne: function(element) {
- var index = element.selectedIndex;
- return index >= 0 ? this.optionValue(element.options[index]) : null;
- },
-
- selectMany: function(element) {
- var values, length = element.length;
- if (!length) return null;
-
- for (var i = 0, values = []; i < length; i++) {
- var opt = element.options[i];
- if (opt.selected) values.push(this.optionValue(opt));
- }
- return values;
- },
-
- optionValue: function(opt) {
- // extend element because hasAttribute may not be native
- return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
- }
-};
-
-/*--------------------------------------------------------------------------*/
-
-Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
- initialize: function($super, element, frequency, callback) {
- $super(callback, frequency);
- this.element = $(element);
- this.lastValue = this.getValue();
- },
-
- execute: function() {
- var value = this.getValue();
- if (Object.isString(this.lastValue) && Object.isString(value) ?
- this.lastValue != value : String(this.lastValue) != String(value)) {
- this.callback(this.element, value);
- this.lastValue = value;
- }
- }
-});
-
-Form.Element.Observer = Class.create(Abstract.TimedObserver, {
- getValue: function() {
- return Form.Element.getValue(this.element);
- }
-});
-
-Form.Observer = Class.create(Abstract.TimedObserver, {
- getValue: function() {
- return Form.serialize(this.element);
- }
-});
-
-/*--------------------------------------------------------------------------*/
-
-Abstract.EventObserver = Class.create({
- initialize: function(element, callback) {
- this.element = $(element);
- this.callback = callback;
-
- this.lastValue = this.getValue();
- if (this.element.tagName.toLowerCase() == 'form')
- this.registerFormCallbacks();
- else
- this.registerCallback(this.element);
- },
-
- onElementEvent: function() {
- var value = this.getValue();
- if (this.lastValue != value) {
- this.callback(this.element, value);
- this.lastValue = value;
- }
- },
-
- registerFormCallbacks: function() {
- Form.getElements(this.element).each(this.registerCallback, this);
- },
-
- registerCallback: function(element) {
- if (element.type) {
- switch (element.type.toLowerCase()) {
- case 'checkbox':
- case 'radio':
- Event.observe(element, 'click', this.onElementEvent.bind(this));
- break;
- default:
- Event.observe(element, 'change', this.onElementEvent.bind(this));
- break;
- }
- }
- }
-});
-
-Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
- getValue: function() {
- return Form.Element.getValue(this.element);
- }
-});
-
-Form.EventObserver = Class.create(Abstract.EventObserver, {
- getValue: function() {
- return Form.serialize(this.element);
- }
-});
-if (!window.Event) var Event = { };
-
-Object.extend(Event, {
- KEY_BACKSPACE: 8,
- KEY_TAB: 9,
- KEY_RETURN: 13,
- KEY_ESC: 27,
- KEY_LEFT: 37,
- KEY_UP: 38,
- KEY_RIGHT: 39,
- KEY_DOWN: 40,
- KEY_DELETE: 46,
- KEY_HOME: 36,
- KEY_END: 35,
- KEY_PAGEUP: 33,
- KEY_PAGEDOWN: 34,
- KEY_INSERT: 45,
-
- cache: { },
-
- relatedTarget: function(event) {
- var element;
- switch(event.type) {
- case 'mouseover': element = event.fromElement; break;
- case 'mouseout': element = event.toElement; break;
- default: return null;
- }
- return Element.extend(element);
- }
-});
-
-Event.Methods = (function() {
- var isButton;
-
- if (Prototype.Browser.IE) {
- var buttonMap = { 0: 1, 1: 4, 2: 2 };
- isButton = function(event, code) {
- return event.button == buttonMap[code];
- };
-
- } else if (Prototype.Browser.WebKit) {
- isButton = function(event, code) {
- switch (code) {
- case 0: return event.which == 1 && !event.metaKey;
- case 1: return event.which == 1 && event.metaKey;
- default: return false;
- }
- };
-
- } else {
- isButton = function(event, code) {
- return event.which ? (event.which === code + 1) : (event.button === code);
- };
- }
-
- return {
- isLeftClick: function(event) { return isButton(event, 0) },
- isMiddleClick: function(event) { return isButton(event, 1) },
- isRightClick: function(event) { return isButton(event, 2) },
-
- element: function(event) {
- var node = Event.extend(event).target;
- return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
- },
-
- findElement: function(event, expression) {
- var element = Event.element(event);
- if (!expression) return element;
- var elements = [element].concat(element.ancestors());
- return Selector.findElement(elements, expression, 0);
- },
-
- pointer: function(event) {
- return {
- x: event.pageX || (event.clientX +
- (document.documentElement.scrollLeft || document.body.scrollLeft)),
- y: event.pageY || (event.clientY +
- (document.documentElement.scrollTop || document.body.scrollTop))
- };
- },
-
- pointerX: function(event) { return Event.pointer(event).x },
- pointerY: function(event) { return Event.pointer(event).y },
-
- stop: function(event) {
- Event.extend(event);
- event.preventDefault();
- event.stopPropagation();
- event.stopped = true;
- }
- };
-})();
-
-Event.extend = (function() {
- var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
- m[name] = Event.Methods[name].methodize();
- return m;
- });
-
- if (Prototype.Browser.IE) {
- Object.extend(methods, {
- stopPropagation: function() { this.cancelBubble = true },
- preventDefault: function() { this.returnValue = false },
- inspect: function() { return "[object Event]" }
- });
-
- return function(event) {
- if (!event) return false;
- if (event._extendedByPrototype) return event;
-
- event._extendedByPrototype = Prototype.emptyFunction;
- var pointer = Event.pointer(event);
- Object.extend(event, {
- target: event.srcElement,
- relatedTarget: Event.relatedTarget(event),
- pageX: pointer.x,
- pageY: pointer.y
- });
- return Object.extend(event, methods);
- };
-
- } else {
- Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__;
- Object.extend(Event.prototype, methods);
- return Prototype.K;
- }
-})();
-
-Object.extend(Event, (function() {
- var cache = Event.cache;
-
- function getEventID(element) {
- if (element._prototypeEventID) return element._prototypeEventID[0];
- arguments.callee.id = arguments.callee.id || 1;
- return element._prototypeEventID = [++arguments.callee.id];
- }
-
- function getDOMEventName(eventName) {
- if (eventName && eventName.include(':')) return "dataavailable";
- return eventName;
- }
-
- function getCacheForID(id) {
- return cache[id] = cache[id] || { };
- }
-
- function getWrappersForEventName(id, eventName) {
- var c = getCacheForID(id);
- return c[eventName] = c[eventName] || [];
- }
-
- function createWrapper(element, eventName, handler) {
- var id = getEventID(element);
- var c = getWrappersForEventName(id, eventName);
- if (c.pluck("handler").include(handler)) return false;
-
- var wrapper = function(event) {
- if (!Event || !Event.extend ||
- (event.eventName && event.eventName != eventName))
- return false;
-
- Event.extend(event);
- handler.call(element, event);
- };
-
- wrapper.handler = handler;
- c.push(wrapper);
- return wrapper;
- }
-
- function findWrapper(id, eventName, handler) {
- var c = getWrappersForEventName(id, eventName);
- return c.find(function(wrapper) { return wrapper.handler == handler });
- }
-
- function destroyWrapper(id, eventName, handler) {
- var c = getCacheForID(id);
- if (!c[eventName]) return false;
- c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
- }
-
- function destroyCache() {
- for (var id in cache)
- for (var eventName in cache[id])
- cache[id][eventName] = null;
- }
-
- if (window.attachEvent) {
- window.attachEvent("onunload", destroyCache);
- }
-
- return {
- observe: function(element, eventName, handler) {
- element = $(element);
- var name = getDOMEventName(eventName);
-
- var wrapper = createWrapper(element, eventName, handler);
- if (!wrapper) return element;
-
- if (element.addEventListener) {
- element.addEventListener(name, wrapper, false);
- } else {
- element.attachEvent("on" + name, wrapper);
- }
-
- return element;
- },
-
- stopObserving: function(element, eventName, handler) {
- element = $(element);
- var id = getEventID(element), name = getDOMEventName(eventName);
-
- if (!handler && eventName) {
- getWrappersForEventName(id, eventName).each(function(wrapper) {
- element.stopObserving(eventName, wrapper.handler);
- });
- return element;
-
- } else if (!eventName) {
- Object.keys(getCacheForID(id)).each(function(eventName) {
- element.stopObserving(eventName);
- });
- return element;
- }
-
- var wrapper = findWrapper(id, eventName, handler);
- if (!wrapper) return element;
-
- if (element.removeEventListener) {
- element.removeEventListener(name, wrapper, false);
- } else {
- element.detachEvent("on" + name, wrapper);
- }
-
- destroyWrapper(id, eventName, handler);
-
- return element;
- },
-
- fire: function(element, eventName, memo) {
- element = $(element);
- if (element == document && document.createEvent && !element.dispatchEvent)
- element = document.documentElement;
-
- var event;
- if (document.createEvent) {
- event = document.createEvent("HTMLEvents");
- event.initEvent("dataavailable", true, true);
- } else {
- event = document.createEventObject();
- event.eventType = "ondataavailable";
- }
-
- event.eventName = eventName;
- event.memo = memo || { };
-
- if (document.createEvent) {
- element.dispatchEvent(event);
- } else {
- element.fireEvent(event.eventType, event);
- }
-
- return Event.extend(event);
- }
- };
-})());
-
-Object.extend(Event, Event.Methods);
-
-Element.addMethods({
- fire: Event.fire,
- observe: Event.observe,
- stopObserving: Event.stopObserving
-});
-
-Object.extend(document, {
- fire: Element.Methods.fire.methodize(),
- observe: Element.Methods.observe.methodize(),
- stopObserving: Element.Methods.stopObserving.methodize(),
- loaded: false
-});
-
-(function() {
- /* Support for the DOMContentLoaded event is based on work by Dan Webb,
- Matthias Miller, Dean Edwards and John Resig. */
-
- var timer;
-
- function fireContentLoadedEvent() {
- if (document.loaded) return;
- if (timer) window.clearInterval(timer);
- document.fire("dom:loaded");
- document.loaded = true;
- }
-
- if (document.addEventListener) {
- if (Prototype.Browser.WebKit) {
- timer = window.setInterval(function() {
- if (/loaded|complete/.test(document.readyState))
- fireContentLoadedEvent();
- }, 0);
-
- Event.observe(window, "load", fireContentLoadedEvent);
-
- } else {
- document.addEventListener("DOMContentLoaded",
- fireContentLoadedEvent, false);
- }
-
- } else {
- document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
- $("__onDOMContentLoaded").onreadystatechange = function() {
- if (this.readyState == "complete") {
- this.onreadystatechange = null;
- fireContentLoadedEvent();
- }
- };
- }
-})();
-/*------------------------------- DEPRECATED -------------------------------*/
-
-Hash.toQueryString = Object.toQueryString;
-
-var Toggle = { display: Element.toggle };
-
-Element.Methods.childOf = Element.Methods.descendantOf;
-
-var Insertion = {
- Before: function(element, content) {
- return Element.insert(element, {before:content});
- },
-
- Top: function(element, content) {
- return Element.insert(element, {top:content});
- },
-
- Bottom: function(element, content) {
- return Element.insert(element, {bottom:content});
- },
-
- After: function(element, content) {
- return Element.insert(element, {after:content});
- }
-};
-
-var $continue = new Error('"throw $continue" is deprecated, use "return" instead');
-
-// This should be moved to script.aculo.us; notice the deprecated methods
-// further below, that map to the newer Element methods.
-var Position = {
- // set to true if needed, warning: firefox performance problems
- // NOT neeeded for page scrolling, only if draggable contained in
- // scrollable elements
- includeScrollOffsets: false,
-
- // must be called before calling withinIncludingScrolloffset, every time the
- // page is scrolled
- prepare: function() {
- this.deltaX = window.pageXOffset
- || document.documentElement.scrollLeft
- || document.body.scrollLeft
- || 0;
- this.deltaY = window.pageYOffset
- || document.documentElement.scrollTop
- || document.body.scrollTop
- || 0;
- },
-
- // caches x/y coordinate pair to use with overlap
- within: function(element, x, y) {
- if (this.includeScrollOffsets)
- return this.withinIncludingScrolloffsets(element, x, y);
- this.xcomp = x;
- this.ycomp = y;
- this.offset = Element.cumulativeOffset(element);
-
- return (y >= this.offset[1] &&
- y < this.offset[1] + element.offsetHeight &&
- x >= this.offset[0] &&
- x < this.offset[0] + element.offsetWidth);
- },
-
- withinIncludingScrolloffsets: function(element, x, y) {
- var offsetcache = Element.cumulativeScrollOffset(element);
-
- this.xcomp = x + offsetcache[0] - this.deltaX;
- this.ycomp = y + offsetcache[1] - this.deltaY;
- this.offset = Element.cumulativeOffset(element);
-
- return (this.ycomp >= this.offset[1] &&
- this.ycomp < this.offset[1] + element.offsetHeight &&
- this.xcomp >= this.offset[0] &&
- this.xcomp < this.offset[0] + element.offsetWidth);
- },
-
- // within must be called directly before
- overlap: function(mode, element) {
- if (!mode) return 0;
- if (mode == 'vertical')
- return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
- element.offsetHeight;
- if (mode == 'horizontal')
- return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
- element.offsetWidth;
- },
-
- // Deprecation layer -- use newer Element methods now (1.5.2).
-
- cumulativeOffset: Element.Methods.cumulativeOffset,
-
- positionedOffset: Element.Methods.positionedOffset,
-
- absolutize: function(element) {
- Position.prepare();
- return Element.absolutize(element);
- },
-
- relativize: function(element) {
- Position.prepare();
- return Element.relativize(element);
- },
-
- realOffset: Element.Methods.cumulativeScrollOffset,
-
- offsetParent: Element.Methods.getOffsetParent,
-
- page: Element.Methods.viewportOffset,
-
- clone: function(source, target, options) {
- options = options || { };
- return Element.clonePosition(target, source, options);
- }
-};
-
-/*--------------------------------------------------------------------------*/
-
-if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
- function iter(name) {
- return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
- }
-
- instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
- function(element, className) {
- className = className.toString().strip();
- var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
- return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
- } : function(element, className) {
- className = className.toString().strip();
- var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
- if (!classNames && !className) return elements;
-
- var nodes = $(element).getElementsByTagName('*');
- className = ' ' + className + ' ';
-
- for (var i = 0, child, cn; child = nodes[i]; i++) {
- if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
- (classNames && classNames.all(function(name) {
- return !name.toString().blank() && cn.include(' ' + name + ' ');
- }))))
- elements.push(Element.extend(child));
- }
- return elements;
- };
-
- return function(className, parentElement) {
- return $(parentElement || document.body).getElementsByClassName(className);
- };
-}(Element.Methods);
-
-/*--------------------------------------------------------------------------*/
-
-Element.ClassNames = Class.create();
-Element.ClassNames.prototype = {
- initialize: function(element) {
- this.element = $(element);
- },
-
- _each: function(iterator) {
- this.element.className.split(/\s+/).select(function(name) {
- return name.length > 0;
- })._each(iterator);
- },
-
- set: function(className) {
- this.element.className = className;
- },
-
- add: function(classNameToAdd) {
- if (this.include(classNameToAdd)) return;
- this.set($A(this).concat(classNameToAdd).join(' '));
- },
-
- remove: function(classNameToRemove) {
- if (!this.include(classNameToRemove)) return;
- this.set($A(this).without(classNameToRemove).join(' '));
- },
-
- toString: function() {
- return $A(this).join(' ');
- }
-};
-
-Object.extend(Element.ClassNames.prototype, Enumerable);
-
-/*--------------------------------------------------------------------------*/
-
-Element.addMethods(); \ No newline at end of file
diff --git a/o3d/samples/canvas-fonts.html b/o3d/samples/canvas-fonts.html
deleted file mode 100644
index 7f9af5f..0000000
--- a/o3d/samples/canvas-fonts.html
+++ /dev/null
@@ -1,192 +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.
--->
-
-<!--
- Sample demonstrating different fonts used for text rendering using
- the Canvas API.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-O3D Canvas
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.canvas');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = createClients;
-
-// Globals
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_math;
-var g_o3d;
-var g_finished = false; // for selenium testing.
-
-function createClients() {
- o3djs.util.makeClients(init);
-}
-
-function init(clientElements) {
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set the background color to blue.
- g_viewInfo.clearBuffer.clearColor = [0.5, 0.1, 1, 1];
-
- // Setup an orthographic projection camera.
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- 0 + 0.5,
- g_client.width + 0.5,
- g_client.height + 0.5,
- 0 + 0.5,
- 0.001,
- 1000);
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 0, 1], // Eye.
- [0, 0, 0], // Target.
- [0, 1, 0]); // Up.
-
- // Create an instance of the canvas utilities library.
- var canvasLib = o3djs.canvas.create(g_pack, g_client.root, g_viewInfo);
-
- // Create a canvas surface to draw on.
- var canvasQuad = canvasLib.createXYQuad(50, 50, -1, 700, 500, false);
-
- canvasQuad.canvas.clear([1, 1, 1, 1]);
- canvasQuad.updateTexture();
-
- var backgroundPaint = g_pack.createObject('CanvasPaint');
- backgroundPaint.color = [1, 0.94, 0.94, 1];
-
- var textPaint = g_pack.createObject('CanvasPaint');
- textPaint.color = [0, 0, 0, 1];
- textPaint.textSize = 24;
-
- // Set drawTextBox to true to display the box showing the text extents
- // returned by CanvasPaint.measureText()
- var drawTextBox = false;
-
- var typefaceArray = [ 'Arial', 'Arial Black', 'Comic Sans MS', 'Courier New',
- 'Georgia', 'Impact', 'Palatino', 'Verdana',
- 'Webdings' ];
-
- var verticalPosition = 10;
- var horizontalPosition = 50;
- for (var ii = 0; ii < typefaceArray.length; ii++) {
- textPaint.textTypeface = typefaceArray[ii];
- var lineDimensions = textPaint.measureText(typefaceArray[ii]);
-
-
- // Add enough vertical spacing to clear the height of the text.
- verticalPosition += lineDimensions[3] - lineDimensions[1] + 20;
-
- if (drawTextBox) {
- // Add the text origin position.
- textSize[0] += horizontalPosition;
- textSize[1] += verticalPosition;
- textSize[2] += horizontalPosition;
- textSize[3] += verticalPosition;
-
- canvasQuad.canvas.drawRect(lineDimensions[0],
- lineDimensions[1],
- lineDimensions[2],
- lineDimensions[3],
- backgroundPaint);
- }
-
- canvasQuad.canvas.drawText(typefaceArray[ii],
- horizontalPosition,
- verticalPosition,
- textPaint);
-
- }
-
- var internationalText = [ 'ελληνικά', 'Српски' ];
- textPaint.textTypeface = 'Arial';
- horizontalPosition = 400;
- verticalPosition = 10;
- for (var ii = 0; ii < internationalText.length; ii++) {
- var lineDimensions = textPaint.measureText(typefaceArray[ii]);
-
- // Add enough vertical spacing to clear the height of the text.
- verticalPosition += lineDimensions[3] - lineDimensions[1] + 20;
-
- canvasQuad.canvas.drawText(internationalText[ii],
- horizontalPosition,
- verticalPosition,
- textPaint);
- }
-
- // Update the o3d texture associated with the canvas quad object.
- canvasQuad.updateTexture();
-
- g_finished = true;
-}
-
-</script>
-</head>
-
-<body>
-<h1>O3D Canvas Sample: Fonts</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
-
diff --git a/o3d/samples/canvas-texturedraw.html b/o3d/samples/canvas-texturedraw.html
deleted file mode 100644
index 3b51270..0000000
--- a/o3d/samples/canvas-texturedraw.html
+++ /dev/null
@@ -1,263 +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.
--->
-
-<!--
- Sample demonstrating drawing into a Canvas surface using an O3D texture.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-O3D Canvas
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.io');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.canvas');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = createClients;
-window.onunload= unload;
-
-// Globals
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_brushTexture;
-var g_canvasQuad;
-var g_o3dElement;
-var g_finished = false; // for selenium testing.
-var g_canvasWidth = 700;
-var g_canvasHeight = 500;
-var g_borderWidth = 50;
-var g_borderHeight = 50;
-var g_clientWidth;
-var g_clientHeight;
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
-
- // Clear the mouse events.
- onMouseUp();
- }
-}
-
-function createClients() {
- o3djs.util.makeClients(init);
-}
-
-
-/**
- * This method gets called on a mouse move event. If the mouse cursor is inside
- * the canvas quad then it draws a copy of the brush texture onto the canvas
- * surface at the mouse cursor position.
- * @param e The mouse move event object
- */
-function drawCursor(e) {
- if (!g_brushTexture)
- return;
-
- var offset = {
- x: e.x / g_client.width * g_clientWidth,
- y: e.y / g_client.height * g_clientHeight
- };
-
- // Adjust for the top left corner of the canvas.
- offset.x -= g_borderWidth;
- offset.y -= g_borderHeight;
-
- // Setting brushScale to a value other than 1 will draw a scaled copy of
- // the brush bitmap onto the canvas surface. This is achieved by applying
- // a scale transformation before calling drawBitmap(), and restoring the
- // draw matrix immediately after.
- var brushScale = 1;
-
- if (offset.x >= 0 && offset.x < g_canvasWidth &&
- offset.y >= 0 && offset.y < g_canvasHeight) {
- g_canvasQuad.canvas.saveMatrix();
- g_canvasQuad.canvas.scale(brushScale, brushScale);
-
- // Note that the coordinates passed to drawBitmap get scaled by the current
- // canvas drawing matrix and therefore we adjust them by the scale to get
- // the bitmap to follow the mouse position.
- g_canvasQuad.canvas.drawBitmap(
- g_brushTexture,
- (offset.x / brushScale - g_brushTexture.width * 0.5),
- (offset.y / brushScale - g_brushTexture.height * 0.5));
- g_canvasQuad.canvas.restoreMatrix();
- g_canvasQuad.updateTexture();
- }
-}
-
-/**
- * Fetches the bitmap pointed to by the URL supplied by the user, creates
- * an O3D Texture object with it, and resets the value of g_brushTexture
- * to point to the newly created texture.
- */
-function changeBrushTexture() {
- var textureUrl = document.getElementById('url').value;
- o3djs.io.loadTexture(g_pack, textureUrl, function(texture, exception) {
- // Remove the previous brush texture from the pack.
- if (exception) {
- alert(exception);
- } else {
- if (g_brushTexture) {
- g_pack.removeObject(g_brushTexture);
- }
- g_brushTexture = texture;
- }
- }, false, false);
-}
-
-/**
- * Event handler that gets called when a mouse click takes place in the
- * O3D element. It registers a callback for mousemove which handles
- * drawing and one for mouseup which removes the mousemove event.
- * @param e The mouse down event.
- */
-function onMouseDown(e) {
- o3djs.event.addEventListener(g_o3dElement, 'mousemove', drawCursor);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', onMouseUp);
- // Draw the cursor at the clicked spot.
- drawCursor(e);
-}
-
-/**
- * Event handler for mouse up. It clears the mouse move and mouse up event
- * handlers.
- */
-function onMouseUp() {
- o3djs.event.removeEventListener(g_o3dElement, 'mousemove', drawCursor);
- o3djs.event.removeEventListener(g_o3dElement, 'mouseup', onMouseUp);
-}
-
-function init(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3dElement = o3dElement;
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Store the size of the plugin, so that we can adjust coordinates in
- // full-screen mode. This is necessary because we're not adjusting the aspect
- // ratio; we'd rather that the canvas filled the available area, rather than
- // staying a fixed size or aspect ratio.
- g_clientWidth = g_o3dElement.clientWidth;
- g_clientHeight = g_o3dElement.clientHeight;
-
- // Set the texture URL.
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- path = path.substring(0, index+1) + 'assets/brush.png';
- var url = document.getElementById("url").value = path;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set the background color to blue.
- g_viewInfo.clearBuffer.clearColor = [0.5, 0.1, 1, 1];
-
- // Setup an orthographic projection camera.
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- 0 + 0.5,
- g_client.width + 0.5,
- g_client.height + 0.5,
- 0 + 0.5,
- 0.001,
- 1000);
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 0, 1], // Eye.
- [0, 0, 0], // Target.
- [0, 1, 0]); // Up.
-
- // Creates an instance of the canvas utilities library.
- var canvasLib = o3djs.canvas.create(g_pack, g_client.root, g_viewInfo);
-
- // Create a canvas surface to draw on.
- var canvasQuad =
- canvasLib.createXYQuad(g_borderWidth, g_borderHeight, 0, g_canvasWidth,
- g_canvasHeight, false);
-
- canvasQuad.canvas.clear([1, 0, 0, 1]);
- canvasQuad.updateTexture();
-
- // Set the initial brush texture.
- changeBrushTexture();
-
- // Setup the events to track mouse activity.
- o3djs.event.addEventListener(o3dElement, 'mousedown', onMouseDown);
-
- g_canvasQuad = canvasQuad;
-
- g_finished = true; // for selenium testing.
-}
-
-</script>
-</head>
-
-<body>
-<h1>O3D Canvas Sample: Drawing with bitmaps</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<p><p>
-Brush URL: <input type="text" id="url" size="100">
-<input type="button" onclick="changeBrushTexture();" value="Change Brush"><BR>
-
-<p><p>Click and drag to draw onto the red canvas surface.
-</body>
-</html>
-
diff --git a/o3d/samples/canvas.html b/o3d/samples/canvas.html
deleted file mode 100644
index 280608d..0000000
--- a/o3d/samples/canvas.html
+++ /dev/null
@@ -1,339 +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.
--->
-
-<!--
-Sample demonstrating the O3D Canvas API.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-O3D Canvas
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.canvas');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = createClients;
-window.onunload= unload;
-
-// Globals
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_paint;
-var g_counterCanvas;
-var g_clock = 0;
-var g_canvasLib;
-var g_timeMult = 1; // controls how fast the text counter will update
-var g_finished = false; // for selenium testing
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-function createClients() {
- o3djs.util.makeClients(init);
-}
-
-function init(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set the background color to purple.
- g_viewInfo.clearBuffer.clearColor = [0.5, 0.1, 1, 1];
-
- // Setup an orthographic projection camera.
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- 0 + 0.5,
- g_client.width + 0.5,
- g_client.height + 0.5,
- 0 + 0.5,
- 0.001,
- 1000);
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 0, 1], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- // Create the global paint object that's used by multiple draw operations.
- g_paint = g_pack.createObject('CanvasPaint');
-
- // Creates an instance of the canvas utilities library.
- g_canvasLib = o3djs.canvas.create(g_pack, g_client.root, g_viewInfo);
-
- // Create the quads that populate the scene.
- createSceneContents();
-
- g_client.setRenderCallback(updateCounter);
-}
-
-/**
- * Uses a linear gradient that transitions between 5 colors to
- * draw a rectangle of the specified width and height inside the
- * given canvasQuad object.
- */
-function drawStripedRectangle(canvasQuad, width, height) {
- // Initialize the array of colors and relative positions that will be used
- // by the gradient.
- var colors = [[1, 0, 0, 1],
- [0, 1, 0, 1],
- [0, 0, 1, 1],
- [1, 0, 1, 1],
- [0, 1, 1, 1]];
- var numSubdivisions = colors.length;
- var rectWidth = 1 / numSubdivisions;
- var paint = g_paint;
- var positions = [];
- for (var ii = 0; ii < numSubdivisions; ii++)
- positions[ii] = ii / (numSubdivisions-1);
-
- // Create a gradient object that will use the entire width of the rectangle.
- var gradientShader = g_pack.createObject('CanvasLinearGradient');
- gradientShader.startPoint = [0, 0];
- gradientShader.endPoint = [width, 0];
- gradientShader.colors = colors;
- gradientShader.positions = positions;
- paint.shader = gradientShader;
-
- // Draw the rectangle starting from the upper left corner of the canvas quad.
- canvasQuad.canvas.drawRect(0, 0, width, height, paint);
-
- // We don't need the shader anymore so we can delete it.
- g_pack.removeObject(gradientShader);
-
- canvasQuad.updateTexture();
-}
-
-// Updates the counter canvas with the new counter value.
-function updateCounter() {
- var counter = Math.floor(g_clock);
- g_clock += g_timeMult;
- if (g_clock > 99) {
- g_clock = 0;
- }
-
- // Clear to completely transparent.
- g_counterCanvas.canvas.clear([0, 0, 0, 0]);
-
- // Reuse the global paint object
- var paint = g_paint;
- paint.color = [1, 1, 1, 1];
- paint.textSize = 60;
- paint.textTypeface = 'Comic Sans MS';
- paint.textAlign = g_o3d.CanvasPaint.RIGHT;
- paint.shader = null;
- g_counterCanvas.canvas.drawText(counter.toString(), 100, 70, paint);
-
- g_counterCanvas.updateTexture();
-}
-/**
- * Creates the individual quads that demonstrate different features of the
- * Canvas API.
- */
-function createSceneContents() {
- // Creates a Canvas Quad and position it with z = -2 so that it is drawn
- // behind the rest of the elements. Draw a rectangle with a linear gradient
- // going through 5 colors along its width.
- var stripeQuad = g_canvasLib.createXYQuad(50, 50, -2, 700, 500, false);
- drawStripedRectangle(stripeQuad, 700, 500);
-
- // Create a 600 x 400 canvas that can host transparent content.
- var frontCanvas = g_canvasLib.createXYQuad(100, 100, -1, 600, 400, true);
-
- // Clear the canvas with semi-transparent yellow.
- frontCanvas.canvas.clear([1, 1, 0, 0.6]);
-
- // Create a couple of paint objects that will be reused throughout the
- // code. Note that a snapshot of the settings of the paint object is taken
- // at the time the paint is being used for one of the canvas methods.
- // Subsequent changes to the paint object don't affect already drawn elements.
- var paint = g_pack.createObject('CanvasPaint');
- var backgroundPaint = g_pack.createObject('CanvasPaint');
-
- // Create a linear gradient shader that goes diagonally from white to red
- // (and repeats). Use the shader to fill a rectangle.
- var gradientShader = g_pack.createObject('CanvasLinearGradient');
- var colors = [[1, 0, 0, 1], [1, 1, 1, 1]];
- var positions = [0, 1];
- gradientShader.startPoint = [0, 0];
- gradientShader.endPoint = [100, 100];
- gradientShader.colors = colors;
- gradientShader.positions = positions;
- gradientShader.tileMode = g_o3d.CanvasShader.REPEAT;
- backgroundPaint.shader = gradientShader;
- frontCanvas.canvas.drawRect(0, 100, 300, 400, backgroundPaint);
-
- // Modify the previously created gradient shader to go from blue to red
- // vertically and use the shader to draw another rectangle.
- var colors = [[0, 0, 1, 1], [1, 0, 0, 1]];
- var positions = [0, 1];
- gradientShader.startPoint = [0, 0];
- gradientShader.endPoint = [0, 401];
- gradientShader.colors = colors;
- gradientShader.positions = positions;
- gradientShader.tileMode = g_o3d.CanvasShader.REPEAT;
- backgroundPaint.shader = gradientShader;
- frontCanvas.canvas.drawRect(300, 100, 600, 400, backgroundPaint);
-
- // Simple centered text writing, with a shadow.
- paint.color = [1, 1, 1, 1];
- paint.textAlign = g_o3d.CanvasPaint.CENTER;
- paint.textSize = 40;
- paint.setShadow(3, 3, 3, [0, 0, 0, 1]);
- frontCanvas.canvas.drawText('Hello O3D', 300, 60, paint);
-
- // Clear the shadow.
- paint.setShadow(0, 0, 0, [1, 0, 0, 1]);
-
- // Draw text along a circular path defined as a series of (x, y) points.
- var numPathPoints = 30;
- var path = [];
- var circle = { x: 150, y: 250, r: 70 };
- for (var ii = 0; ii < numPathPoints; ii++) {
- var xx = circle.x + circle.r * Math.cos(2.0 * 3.1415 * ii / numPathPoints);
- var yy = circle.y + circle.r * Math.sin(2.0 * 3.1415 * ii / numPathPoints);
- path[ii] = [xx, yy];
- }
- paint.textSize = 64;
- paint.textTypeface = 'Comic Sans MS';
- paint.textAlign = g_o3d.CanvasPaint.LEFT;
-
- frontCanvas.canvas.drawTextOnPath('Hello O3D',
- path,
- 0,
- 0,
- paint);
-
- paint.textTypeface = 'arial';
- paint.textSize = 18;
- var metrics = paint.fontMetrics;
- var ascent = metrics.ascent;
- var stringDimensions = paint.measureText('Hello O3D');
-
- paint.textStyle = g_o3d.CanvasPaint.BOLD;
- paint.textAlign = g_o3d.CanvasPaint.LEFT;
-
- // Use the canvas transformation methods to draw text in 4 different
- // orientations. Notice how we offset the text vertically by -ascent/2
- // in order to center it vertically along the drawing line.
- var textBoxPaint = g_pack.createObject('CanvasPaint');
- var colors = [[1, 0, 0, 1], // red
- [0, 1, 0, 1], // green
- [0, 0, 1, 1], // blue
- [1, 1, 0, 1]] // yellow
-
- for (var ii = 0; ii < 4; ii++) {
- // Save the existing drawing transform so that we can get it back when we're
- // done rendering the text line.
- frontCanvas.canvas.saveMatrix();
-
- // First rotate by the desired angle and then translate to the desired
- // center point. Notice that drawing transforms are pre-multiplied which
- // means that we first need to apply the translate and then the rotate to
- // get the rotation to happen before the translation.
- frontCanvas.canvas.translate(450, 250);
- frontCanvas.canvas.rotate(ii * 90);
-
- textBoxPaint.color = colors[ii];
-
- // Draw a rectangle under the text.
- frontCanvas.canvas.drawRect(10,
- -ascent / 2 + 2,
- stringDimensions[2] - stringDimensions[0] + 10,
- -ascent / 2 + 12,
- textBoxPaint);
-
- paint.color = colors[ii];
-
- // Draw the actual text with a vertical offset which will center it
- // along the text drawing line.
- frontCanvas.canvas.drawText('Hello O3D', 10, -ascent / 2, paint);
-
- // Restore the original drawing transform.
- frontCanvas.canvas.restoreMatrix();
- }
-
- // Copy the contents of the canvas to the o3d texture.
- frontCanvas.updateTexture();
-
- // Create a canvas that will be used to display the counter.
- g_counterCanvas = g_canvasLib.createXYQuad(0, 0, 0, 200, 150, true);
-
- // Display the counter.
- updateCounter();
-
- g_finished = true;
-}
-
-</script>
-</head>
-
-<body>
-<h1>O3D Canvas Sample</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
-
diff --git a/o3d/samples/checkers.html b/o3d/samples/checkers.html
deleted file mode 100644
index a43e1b395..0000000
--- a/o3d/samples/checkers.html
+++ /dev/null
@@ -1,870 +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.
--->
-
-<!--
-Checker Game Example
-
-This sample demonstates usage of primitive functions and simple 3d animation techniques.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-3D Checkers Game
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.arcball');
-o3djs.require('o3djs.picking');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-
-// global variables
-var g_o3dElement;
-var g_client;
-var g_o3d;
-var g_math;
-var g_quaternions;
-var g_pack;
-var g_viewInfo;
-var g_sceneRoot;
-var g_eyeView;
-var g_cubeShape;
-var g_cylinderShape;
-var g_prismShape;
-var g_material;
-var g_aball;
-var g_thisRot;
-var g_lastRot;
-var g_zoomFactor;
-var g_dragging = false;
-var g_pickManager; // information about the transform graph.
-var g_statusInfoElem;
-
-// Animation globals.
-var g_flashTimer;
-var g_moveTimer;
-var g_moveDuration;
-var g_oldFlashTimer;
-
-// Checkers globals.
-var g_board;
-var g_boardSize;
-var g_boardSquare;
-var g_boardHeight;
-var g_pieceHeight;
-var g_selectedPiece;
-var g_selectedSquare;
-var g_player;
-var g_canJump;
-
-/**
- * Creates the client area.
- */
-function initClient() {
- window.g_finished = false; // for selenium testing.
-
- // Runs the sample in V8. Comment out this line to run it in the browser
- // JavaScript engine, for example if you want to debug it.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.util.makeClients(main);
-}
-
-/**
- * Initializes global variables, positions camera, draws the 3D chart.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function main(clientElements) {
- // Init global variables.
- initGlobals(clientElements);
-
- // Set up the view and projection transformations.
- initContext();
-
- // Add the checkers board to the transform hierarchy.
- createCheckersBoard();
-
- // Register mouse events handlers
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', startDragging);
- o3djs.event.addEventListener(g_o3dElement, 'mousemove', drag);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', stopDragging);
- o3djs.event.addEventListener(g_o3dElement, 'wheel', scrollMe);
-
- // Set the rendering callback
- g_client.setRenderCallback(onrender);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Initializes global variables and libraries.
- */
-function initGlobals(clientElements) {
- // init o3d globals.
- g_o3dElement = clientElements[0];
- window.g_client = g_client = g_o3dElement.client;
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_quaternions = o3djs.quaternions;
-
- // Create an arcball.
- g_aball = o3djs.arcball.create(g_client.width, g_client.height);
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create a transform node to act as the 'root' of the scene.
- // Attach it to the root of the transform graph.
- g_sceneRoot = g_pack.createObject('Transform');
- g_sceneRoot.parent = g_client.root;
-
- // Create the render graph for the view.
- var clearColor = [.98, .98, .98, 1];
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot,
- clearColor);
-
- // Create a material for the objects rendered.
- g_material = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [1, 1, 1, 1]);
-
- // Initialize checkers piece and square data.
- g_boardSize = 8;
- g_boardSquare = 10;
- g_boardHeight = g_boardSquare / 5;
- g_pieceHeight = g_boardHeight * 0.75;
- g_selectedPiece = null;
- g_selectedSquare = null;
-
- // Create a cube shape for the board squares.
- g_cubeShape = o3djs.primitives.createCube(
- g_pack,
- g_material,
- 1);
-
- // Create a cylinder shape for the checkers pieces.
- g_cylinderShape = o3djs.primitives.createCylinder(
- g_pack,
- g_material,
- g_boardSquare / 2 - 1, // Radius.
- g_pieceHeight, // Depth.
- 100, // Number of subdivisions.
- 1);
-
- // use an extruded poligon to create a 'crown' for the king piece.
- var polygon = [[0, 0], [1, 0], [1.5, 1.5], [0.5, 0.5],
- [0, 2], [-0.5, 0.5], [-1.5, 1.5], [-1, 0]];
-
- // use the 'prism' primitive for the crown.
- g_prismShape = o3djs.primitives.createPrism(
- g_pack,
- g_material,
- polygon, // The profile polygon to be extruded.
- 1); // The depth of the extrusion.
-
- // Get the status element.
- g_statusInfoElem = o3djs.util.getElementById('statusInfo');
-
- // Initialize player data.
- g_player = 1; // red player starts first.
- g_canJump = false;
-
- // Initialize various animation globals.
- g_flashTimer = 0;
- g_moveTimer = 0;
- g_moveDuration = 1.3;
- g_oldFlashTimer = 0;
-}
-
-/**
- * Initialize the original view of the scene.
- */
-function initContext() {
- g_eyeView = [-5, 120, 100];
- g_zoomFactor = 1.03;
- g_dragging = false;
- g_sceneRoot.identity();
- g_lastRot = g_math.matrix4.identity();
- g_thisRot = g_math.matrix4.identity();
-
- // Set up a perspective transformation for the projection.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- Math.PI * 40 / 180, // 30 degree frustum.
- g_o3dElement.clientWidth / g_o3dElement.clientHeight, // Aspect ratio.
- 1, // Near plane.
- 10000); // Far plane.
-
- // Set up our view transformation to look towards the axes origin.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- g_eyeView, // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Creates a Coord object used to hold a set of 2D coordinates.
- *
- * @private
- * @constructor
- * @param {number} x X coordinate.
- * @param {number} y Y coordinate.
- */
-function Coord(x, y) {
- this.x = x;
- this.y = y;
-}
-
-/**
- * Creates a BoardInfo object to hold board information.
- *
- * @private
- * @constructor
- * @param {number} x X coordinate on the checkers board.
- * @param {number} y Y coordinate on the checkers board.
- */
-function BoardInfo(x, y) {
- this.x = x;
- this.y = y;
- this.square = null;
- this.type = 0;
- this.pieceParent = null;
- this.piece = null;
- this.king = false;
-}
-
-/**
- * Returns the initial settings for a given position on the board.
- *
- * @param {number} x X coordinate on the checkers board.
- * @param {number} y Y coordinate on the checkers board.
- * @return {number} 0 = no piece, 1 = red piece, -1 = white piece
- */
-function getSquarePiece(x, y) {
- // if bad coordinates, no piece.
- if (x >= g_boardSize || x < 0 || y >= g_boardSize || y < 0)
- return 0;
- // if on rows 3 and 4 or on a white square - no piece.
- if (y == 3 || y == 4 || ((x + y) % 2 == 1))
- return 0;
- // if on rows 0-2 it is a red piece, otherwise white piece.
- if (0 <= y && y < 3) return 1;
- if (5 <= y && y < 8) return -1;
- // Any not covered case.
- return 0;
-}
-
-/**
- * Creates the checkers board.
- */
-function createCheckersBoard() {
- g_board = [];
- // Create a checker board (black at 0,0).
- for (var i = 0; i < g_boardSize; i += 1) { // columns.
- g_board[i] = [];
- for (var j = 0; j < g_boardSize; j += 1) { // rows.
- // create the transform for the board squares.
- var square = g_pack.createObject('Transform');
- square.parent = g_sceneRoot;
- square.addShape(g_cubeShape);
- // translate and scale the squares correctly relative to origin.
- var offset = g_boardSquare * (1 - g_boardSize) / 2;
- square.translate(offset + g_boardSquare * i ,
- 0, -(offset + g_boardSquare * j));
- square.scale(g_boardSquare, g_boardHeight, g_boardSquare);
- // set the square color.
- var isBlack = (i + j) % 2 == 0 ? true : false;
- var squareColor = isBlack ?
- [0.15, 0.15, 0.15, 1] : [0.85, 0.85, 0.75, 1];
- square.createParam('diffuse', 'ParamFloat4').value = squareColor;
-
- // add this square and its info to the board.
- g_board[i][j] = new BoardInfo(i, j);
- g_board[i][j].square = square;
-
- // create the piece for this square and update the board position.
- // skip if the square has no piece.
- var pieceType = getSquarePiece(i, j);
- if (pieceType == 0)
- continue;
-
- // create a parent transform for this piece.
- var pieceParent = g_pack.createObject('Transform');
- pieceParent.parent = g_sceneRoot;
-
- // create the checkers piece.
- var piece = g_pack.createObject('Transform');
- piece.parent = pieceParent;
- piece.addShape(g_cylinderShape);
-
- // place the piece on the correct location on the board.
- pieceParent.translate(0, (g_pieceHeight + g_boardHeight) / 2, 0);
- pieceParent.translate(offset + g_boardSquare * i ,
- 0, -(offset + g_boardSquare * j));
-
- // pick the piece color (red or white).
- piece.createParam('diffuse', 'ParamFloat4').value =
- getPieceColor(pieceType);
-
- // update the board info to include this piece.
- g_board[i][j].piece = piece;
- g_board[i][j].pieceParent = pieceParent;
- g_board[i][j].type = pieceType;
- }
- }
-
- // Update our PickManager.
- updatePickManager();
-
- // update status.
- updateStatus('Game starting... RED moves first.', true);
-}
-
-/**
- * Checks if a piece has become a 'king' piece and updates it.
- *
- * @param {number} x X coordinate on the checkers board.
- * @param {number} y Y coordinate on the checkers board.
- */
-function checkAndUpdateKing(x, y) {
- // if the piece is not on the king row, nothing to do.
- if ( y > 0 && y < g_boardSize - 1 ) return;
-
- // ignore if no piece or the piece is already king
- var selSquare = g_board[x][y];
- if (!selSquare.piece || selSquare.king) return;
-
- // change the king piece color.
- selSquare.king = true;
-
- // create the crown shape.
- var crown = g_pack.createObject('Transform');
- crown.parent = selSquare.piece;
- crown.addShape(g_prismShape);
- var crownSize = g_pieceHeight;
- crown.scale(crownSize, crownSize, crownSize);
- crown.translate(0, g_pieceHeight / 2, 0);
- crown.createParam('diffuse', 'ParamFloat4').value = [1, 1, 0, 0];
-}
-
-
-/**
- * Updates the transform tree info.
- */
-function updatePickManager() {
- if (!g_pickManager) {
- g_pickManager = o3djs.picking.createPickManager(g_client.root);
- }
- g_pickManager.update();
-}
-
-/**
- * Check if a player selection is a jump.
- *
- * @param {BoardInfo} piece The board info for the piece.
- * @param {BoardInfo} square The board info for the landing square.
- * @return {boolean} true if this is a jump.
- */
-function isJump(piece, square) {
- return (Math.abs(piece.x - square.x) == 2 &&
- Math.abs(piece.y - square.y) == 2 );
-}
-
-function isLegalMove(piece, square) {
- var orig = new Coord(piece.x, piece.y);
- var dest = new Coord(square.x, square.y);
-
- // it must be this player's turn to make a move.
- if (piece.type != g_player) return false;
-
- // the destination must be un-occupied.
- if (square.type != 0 ) return false;
-
- // must move diagonally.
- var diag = new Coord(dest.x - orig.x, dest.y - orig.y);
- if (Math.abs(diag.x) != Math.abs(diag.y)) return false;
-
- // cannot move more than 2.
- if (Math.abs(diag.x) > 2) return false;
-
- // make sure the piece is moved in the 'forward' direction
- // unless this is a 'king' piece.
- if (!piece.king && g_player * diag.y < 0) return false;
-
- // if a jump check if valid.
- if (Math.abs(diag.x) == 2) {
- var jumpType = g_board[(orig.x + dest.x)/2][(orig.y + dest.y)/2].type;
- if (jumpType == piece.type || jumpType == 0)
- return false;
- }
-
- return true;
-}
-
-/**
- * Update the status message.
- *
- * @param {string} statusMsg The message to display.
- * @param {boolean} opt_hidePlayer Prefix the status with the name of the player.
- */
-function updateStatus(statusMsg, opt_hidePlayer) {
- var status = (g_player == 1) ? 'RED: ' : 'WHITE: ';
- g_statusInfoElem.innerHTML = (opt_hidePlayer ? '' : status) + statusMsg;
-}
-
-
-/**
- * Check if a valid boad coordinate.
- *
- * @param {number} x X coordinate on the checkers board.
- * @param {number} y Y coordinate on the checkers board.
- * @return {boolean} True if a valid coordinate.
- */
-function isValidCoord(x, y) {
- if ( x < 0 || x >= g_boardSize ) return false;
- if ( y < 0 || y >= g_boardSize ) return false;
- return true;
-}
-
-
-/**
- * Check if a piece has a valid sliding move.
- *
- * @param {!BoardInfo} piece The board info for the piece.
- * @return {boolean} True if the piece can slide.
- */
-function pieceCanSlide(piece) {
- var x = piece.x;
- var y = piece.y;
-
- for (var i = -1; i <= 1; i += 2) {
- for (var j = -1; j <= 1; j += 2) {
- if (isValidCoord(x + i, y + j))
- if (isLegalMove(piece, g_board[x + i][y + j]))
- return true;
- }
- }
- return false;
-}
-
-/**
- * Check if a piece has a valid jumping move.
- *
- * @param {!BoardInfo} piece The board info for the piece.
- * @return {boolean} True if the piece can jump.
- */
-function pieceCanJump(piece) {
- var x = piece.x;
- var y = piece.y;
-
- for (var i = -2; i <= 2; i += 4) {
- for (var j = -2; j <= 2; j += 4) {
- if (isValidCoord(x + i, y + j))
- if (isLegalMove(piece, g_board[x + i][y + j]))
- return true;
- }
- }
- return false;
-}
-
-/**
- * Check if the current player has any moves available.
- *
- * @return {boolean} True if the player can move.
- */
-function currentPlayerCanMove() {
- var canSlide = false;
- for (var x = 0; x < g_boardSize; x += 1) {
- for (var y = 0; y < g_boardSize; y += 1) {
- var sel = g_board[x][y];
- if (sel.piece == null) continue;
- // if jump set the canJump variable and return.
- g_canJump = pieceCanJump(sel);
- if (g_canJump) return true;
- if (pieceCanSlide(sel)) {
- canSlide = true;
- }
- }
- }
- return canSlide;
-}
-
-/**
- * Check if a forced jump is required for the current player.
- *
- * @return {boolean} True if a jump is required.
- */
-function checkForcedJump() {
- for (var x = 0; x < g_boardSize; x += 1) {
- for (var y = 0; y < g_boardSize; y += 1) {
- var sel = g_board[x][y];
- if (sel.piece && pieceCanJump(sel)) {
- g_forcedJump = true;
- return true;
- }
- }
- }
- g_forcedJump = false;
- return false;
-}
-
-/**
- * Check if the game is over.
- *
- * @return {boolean} True if the game is over.
- */
-function isGameOver() {
- // the game is over when a player has no pieces left
- // or it cannot make a valid move.
- if (!currentPlayerCanMove()) {
- var statusStr = (g_player == 1) ? 'White Won!' : 'Red Won!';
- updateStatus(statusStr, true);
- return true;
- }
- return false;
-}
-
-/**
- * Detect a mouse click an element of the checkers board.
- *
- * @param {event} e event.
- */
-function detectSelection(e) {
- var worldRay = o3djs.picking.clientPositionToWorldRay(e.x,
- e.y,
- g_viewInfo.drawContext,
- g_client.width,
- g_client.height);
-
- // check if we picked any objects.
- var pickInfo = g_pickManager.pick(worldRay);
- if (pickInfo) {
- // get the parent transform of this object.
- var pickTrans = pickInfo.shapeInfo.parent.transform;
- var pickTransClientId = pickTrans.clientId;
-
- // check if a board square or a piece.
- for (var x = 0; x < g_boardSize; x += 1) {
- for (var y = 0; y < g_boardSize; y += 1) {
- if (g_board[x][y].piece &&
- pickTransClientId == g_board[x][y].piece.clientId) {
- // do not select another player's piece.
- if (g_player != g_board[x][y].type) return;
-
- // if a previous piece selection, clear it.
- if (g_selectedPiece) {
- g_selectedPiece.piece.getParam('diffuse').value =
- getPieceColor(g_selectedPiece.type);
- }
-
- // check if a forced jump.
- if (g_canJump) {
- if (!pieceCanJump(g_board[x][y])) {
- updateStatus('Must jump, incorrect piece!');
- return;
- }
- }
-
- SelectPiece(x, y);
- return;
- } else if (pickTransClientId == g_board[x][y].square.clientId) {
- // selected the landing square if a piece move is pending.
- if (g_selectedPiece) {
- // check if a forced jump.
- if (g_canJump && !isJump(g_selectedPiece, g_board[x][y])) {
- updateStatus('Must jump!');
- return;
- }
- // check if a legal move, then move the piece.
- if (isLegalMove(g_selectedPiece, g_board[x][y])) {
- SelectSquare(x, y);
- } else {
- updateStatus('Illegal move!');
- }
- }
- return;
- }
- }
- }
- }
-}
-
-/**
- * Select a piece on the checkers board.
- */
-function SelectPiece(x, y) {
- g_selectedPiece = g_board[x][y];
- // update status message.
- updateStatus('Selected piece at (' + x + ',' + y + ')');
-}
-
-/**
- * Select a square on the checkers board.
- */
-function SelectSquare(x, y) {
- updateStatus('Moving piece from (' + g_selectedPiece.x + ',' +
- g_selectedPiece.y + ') to (' + x + ',' + y + ')');
- g_selectedSquare = g_board[x][y];
- g_moveTimer = 0;
-}
-
-/**
- * Return the color for the given piece type.
- *
- * @param {number} type Type of the checkers piece.
- * @return {Array} Array representing the color.
- */
-function getPieceColor(type) {
- return (type == 1) ? [1, 0.15, 0.15, 1] : [1, 1, 1, 1];
-}
-
-/**
- * Called every frame.
- * @param {o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onrender(renderEvent) {
- g_flashTimer += renderEvent.elapsedTime;
- g_flashTimer = g_flashTimer % 0.5;
-
- if (g_selectedPiece) {
- var origColor = getPieceColor(g_selectedPiece.type);
- // flash highlight the selected piece as long as selected.
- if (g_oldFlashTimer > g_flashTimer ) {
- g_selectedPiece.piece.getParam('diffuse').value = [0.6, 1, 1, 1];
- } else if (g_flashTimer >= 0.25 && g_oldFlashTimer < 0.25) {
- g_selectedPiece.piece.getParam('diffuse').value = origColor;
- }
-
- // check if we selected a square to move the piece.
- if (g_selectedSquare) {
- moveSelectedPiece(renderEvent.elapsedTime);
- }
- }
- g_oldFlashTimer = g_flashTimer;
-}
-
-
-/**
- * Slides or jumps the selected piece.
- * This method is used to simulate the animation of the moving piece.
- * @param {number} elapsedTime The elapsed time in seconds since the last call.
- */
-function moveSelectedPiece(elapsedTime) {
- g_moveTimer += elapsedTime;
- // animate the piece one iteration at the time.
- var lerp = g_moveTimer / g_moveDuration;
-
- // get the board coordinates of the curent and future position.
- var x0 = g_selectedPiece.x;
- var y0 = g_selectedPiece.y;
- var x1 = g_selectedSquare.x;
- var y1 = g_selectedSquare.y;
-
- // get the coordinates relative to axis origin.
- var offset = g_boardSquare * (1 - g_boardSize) / 2;
- var xc0 = offset + g_boardSquare * x0;
- var zc0 = -(offset + g_boardSquare * y0);
- var xc1 = offset + g_boardSquare * x1;
- var zc1 = -(offset + g_boardSquare * y1);
- var yc = (g_pieceHeight + g_boardHeight) / 2;
-
- // Our piece's position and rotation.
- var px;
- var pz;
- var jump = 0;
- var rotation = 0;
- var done = false;
-
- if (lerp < 1) {
- // check if this is a jump.
- if (isJump(g_selectedPiece, g_selectedSquare)) {
- // compute the jump height.
- jump = Math.sin(Math.PI * lerp) * g_pieceHeight * 13;
- // simulate a spinning of the jumping piece.
- rotation = -lerp * 4 * Math.PI;
- }
- px = xc0 + (xc1 - xc0) * lerp;
- pz = zc0 + (zc1 - zc0) * lerp;
- } else {
- // done with the move.
- px = xc1;
- pz = zc1;
- done = true;
- }
-
- // move the piece to the new position.
- var pieceParent = g_board[x0][y0].pieceParent;
- pieceParent.identity();
- pieceParent.translate(px, yc + jump, pz);
-
- // spin the piece
- g_selectedPiece.piece.identity();
- g_selectedPiece.piece.rotateX(rotation);
-
- if (done) {
- // stop flashing - restore the original color.
- var origColor = getPieceColor(g_selectedPiece.type);
- g_selectedPiece.piece.getParam('diffuse').value = origColor;
-
- // if a jump destroy the jumped piece.
- var wasJump = isJump(g_selectedPiece, g_selectedSquare);
- if (wasJump) {
- var xj = (x0 + x1)/2;
- var yj = (y0 + y1)/2;
- g_board[xj][yj].type = 0;
- g_board[xj][yj].pieceParent.parent = null;
- g_board[xj][yj].pieceParent = null;
- g_board[xj][yj].piece = null;
- }
-
- // the new square has a new piece.
- g_board[x1][y1].type = g_selectedPiece.type;
- g_board[x1][y1].king = g_selectedPiece.king;
- g_board[x1][y1].piece = g_selectedPiece.piece;
- g_board[x1][y1].pieceParent = g_selectedPiece.pieceParent;
-
- // the original square is now empty.
- g_board[x0][y0].type = 0;
- g_board[x0][y0].piece = null;
- g_board[x0][y0].pieceParent = null;
-
- // check if the moved piece became king.
- checkAndUpdateKing(x1, y1);
-
- g_selectedPiece = null;
- g_selectedSquare = null;
- g_moveTimer = 0;
-
- // update the picking info.
- updatePickManager();
-
- // check if current player can jump again.
- if (wasJump && pieceCanJump(g_board[x1][y1])) {
- g_selectedPiece = g_board[x1][y1];
- updateStatus('Must jump again ...');
- } else {
- // this player is done, switch players.
- g_player = -g_player;
- // check if game over; also checks if the current player must jump.
- if (!isGameOver()) {
- updateStatus(g_canJump ? 'Must jump...' : 'Next turn...');
- }
- }
- }
-}
-
-
-/**
- * Zooms the scene in / out by changing the viewpoint.
- * @param {number} zoom zooming factor.
- */
-function ZoomInOut(zoom) {
- for (i = 0; i < g_eyeView.length; i += 1) {
- g_eyeView[i] = g_eyeView[i] / zoom;
- }
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- g_eyeView, // eye.
- [0, 0, 0], // target.
- [0, 1, 0]); // up.
-}
-
-/**
- * Start mouse dragging.
- * @param {event} e event.
- */
-function startDragging(e) {
- detectSelection(e);
- g_lastRot = g_thisRot;
-
- g_aball.click([e.x, e.y]);
- g_dragging = true;
-}
-
-/**
- * Use the arcball to rotate the scene.
- * Computes the rotation matrix.
- * @param {event} e event.
- */
-function drag(e) {
- if (g_dragging) {
- var rotationQuat = g_aball.drag([e.x, e.y]);
- var rot_mat = g_quaternions.quaternionToRotation(rotationQuat);
-
- g_thisRot = g_math.matrix4.mul(g_lastRot, rot_mat);
- var m = g_sceneRoot.localMatrix;
- g_math.matrix4.setUpper3x3(m, g_thisRot);
- g_sceneRoot.localMatrix = m;
- }
-}
-
-/**
- * Stop dragging.
- * @param {event} e event.
- */
-function stopDragging(e) {
- g_dragging = false;
-}
-
-/**
- * Using the mouse wheel zoom in and out of the scene.
- * @param {event} e event.
- */
-function scrollMe(e) {
- var zoom = (e.deltaY < 0) ? 1 / g_zoomFactor : g_zoomFactor;
- ZoomInOut(zoom);
- g_client.render();
-}
-
-</script>
-</head>
-
-<body onload="initClient()">
-<h2>3D Checkers Game</h2>
-<div style="font-size:10;"><span id="statusInfo"></span></div>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-
-</body>
-</html>
diff --git a/o3d/samples/convolution.html b/o3d/samples/convolution.html
deleted file mode 100644
index cada227..0000000
--- a/o3d/samples/convolution.html
+++ /dev/null
@@ -1,397 +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 sample shows how to create a separable convolution shader using
-render targets. The kernel here is a Gaussian blur, but the same code
-could be used for any kernel.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-O3D: Convolution Shader Sample
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-window.onunload = uninit;
-
-// constants.
-var RENDER_TARGET_WIDTH = 512;
-var RENDER_TARGET_HEIGHT = 512;
-
-// global variables
-var g_o3d;
-var g_client;
-var g_math;
-var g_pack;
-var g_teapotRoot;
-var g_renderGraphRoot;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing.
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo whose view and projection will
- * be set from the scene after it's loaded.
- */
-function loadScene(pack, fileName, parent, viewInfo) {
- // Get our full path to the scene.
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the scene given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory from the
- * web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT);
-
- // Copy the view and projection to the passed in viewInfo structure..
- viewInfo.drawContext.view = cameraInfo.view;
- viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, viewInfo);
-
- g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3d = clientElements[0];
- g_o3d = o3d.o3d;
- g_math = o3djs.math;
- g_client = o3d.client;
-
- // Creates a pack to manage our resources/assets.
- g_pack = g_client.createPack();
-
- // Create the texture required for the color render-target.
- var texture1 = g_pack.createTexture2D(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT,
- g_o3d.Texture.XRGB8, 1, true);
-
- // Create the texture required for the color render-target.
- var texture2 = g_pack.createTexture2D(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT,
- g_o3d.Texture.XRGB8, 1, true);
-
- g_teapotRoot = g_pack.createObject('Transform');
-
- var renderGraphRoot = g_client.renderGraphRoot;
-
- var xSigma = 4.0, ySigma = 4.0;
- var xKernel = buildKernel(xSigma);
- var yKernel = buildKernel(ySigma);
-
- var renderSurfaceSet1 = createRenderSurfaceSet(texture1);
- var renderSurfaceSet2 = createRenderSurfaceSet(texture2);
-
- // Create the render graph for the teapot view, drawing the teapot into
- // texture1 (via renderSurfaceSet1).
- var teapotViewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_teapotRoot,
- renderSurfaceSet1,
- [1, 1, 1, 1]);
-
- // Create a Y convolution pass that convolves texture1 into texture2, using
- // the X kernel.
- var renderNode1 = createConvolutionPass(texture1,
- renderSurfaceSet2,
- xKernel,
- 1.0 / texture1.width,
- 0.0);
-
- // Create a Y convolution pass that convolves texture2 into the framebuffer,
- // using the Y kernel.
- var renderNode2 = createConvolutionPass(texture2,
- g_client.renderGraphRoot,
- yKernel,
- 0.0,
- 1.0 / texture2.height);
-
- // Load the scene into the transform graph as a child g_teapotRoot
- loadScene(g_pack, 'assets/teapot.o3dtgz', g_teapotRoot, teapotViewInfo);
-
- // Set a render callback.
- g_client.setRenderCallback(onRender);
-}
-
-// We lop off the sqrt(2 * pi) * sigma term, since we're going to normalize
-// anyway.
-function gauss(x, sigma) {
- return Math.exp(- (x * x) / (2.0 * sigma * sigma));
-}
-
-function buildKernel(sigma) {
- var kMaxKernelSize = 25;
- var kernelSize = 2 * Math.ceil(sigma * 3.0) + 1;
- if (kernelSize > kMaxKernelSize) {
- kernelSize = kMaxKernelSize;
- }
- var halfWidth = (kernelSize - 1) * 0.5
- var values = new Array(kernelSize);
- var sum = 0.0;
- for (var i = 0; i < kernelSize; ++i) {
- values[i] = gauss(i - halfWidth, sigma);
- sum += values[i];
- }
- // Now normalize the kernel.
- for (var i = 0; i < kernelSize; ++i) {
- values[i] /= sum;
- }
- return values;
-}
-
-function createConvolutionMaterial(viewInfo, kernelSize) {
- var convFXString = document.getElementById('convFX').value;
- convFXString = convFXString.replace(/KERNEL_WIDTH/g, kernelSize);
- var convEffect = g_pack.createObject('Effect');
- convEffect.loadFromFXString(convFXString);
-
- var convMaterial = g_pack.createObject('Material');
- convMaterial.drawList = viewInfo.performanceDrawList;
- convMaterial.effect = convEffect;
- convEffect.createUniformParameters(convMaterial);
- return convMaterial;
-}
-
-function createRenderSurfaceSet(texture) {
- var renderSurface = texture.getRenderSurface(0);
-
- // Create the depth-stencil buffer required when rendering this pass.
- var depthSurface = g_pack.createDepthStencilSurface(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT);
-
- var renderSurfaceSet = g_pack.createObject('RenderSurfaceSet');
- renderSurfaceSet.renderSurface = renderSurface;
- renderSurfaceSet.renderDepthStencilSurface = depthSurface;
- renderSurfaceSet.parent = g_client.renderGraphRoot;
- return renderSurfaceSet;
-}
-
-function createConvolutionPass(srcTexture, renderGraphRoot, kernel, x, y) {
- // Create a root Transform for the convolution scene.
- var root = g_pack.createObject('Transform');
-
- // Create a basic view for the convolution scene.
- var viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- root,
- renderGraphRoot,
- [1, 1, 1, 1]);
-
- var material = createConvolutionMaterial(viewInfo, kernel.length);
- var quadShape = o3djs.primitives.createPlane(g_pack,
- material,
- 2.0,
- 2.0,
- 1,
- 1);
-
- // Attach the quad to the root of the convolution graph.
- root.addShape(quadShape);
-
- // Rotate the view so we're looking at the XZ plane (where our quad is)
- // Point the camera along the -Y axis
- var target = [0, -1, 0];
- // Put the camera at the origin.
- var eye = [0, 0, 0];
- // Define the up-vector as +Z
- var up = [0, 0, 1];
- viewInfo.drawContext.view = g_math.matrix4.lookAt(eye, target, up);
-
- // Create an orthographic projection.
- viewInfo.drawContext.projection = g_math.matrix4.orthographic(-1, 1, -1, 1, -1, 1);
-
- // Generate draw elements and setup material draw lists for the
- // convolution scene.
- o3djs.pack.preparePack(g_pack, viewInfo);
-
- setConvolutionParameters(material, srcTexture, kernel, kernel.length, x, y);
- return renderGraphRoot;
-}
-
-function setConvolutionParameters(material, texture, kernel, kernelSize,
- xIncrement, yIncrement) {
- var imageParam = material.getParam('image');
- var kernelParam = material.getParam('kernel');
- var imageIncrement = material.getParam('imageIncrement');
- var sampler = g_pack.createObject('Sampler');
- sampler.texture = texture;
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
- sampler.minFilter = g_o3d.Sampler.POINT;
- sampler.magFilter = g_o3d.Sampler.POINT;
- sampler.mipFilter = g_o3d.Sampler.NONE;
- imageParam.value = sampler;
- imageIncrement.value = [xIncrement, yIncrement];
- var paramArray = g_pack.createObject('ParamArray');
- var halfWidth = (kernelSize - 1) * 0.5;
- for (var i = 0; i < kernelSize; ++i) {
- var element = paramArray.createParam(i, 'ParamFloat');
- element.value = kernel[i];
- }
- kernelParam.value = paramArray;
-}
-
-/**
- * Called every frame.
- * @param {o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- g_teapotRoot.identity();
- g_teapotRoot.rotateX(g_clock);
- g_teapotRoot.rotateY(g_clock * 1.3);
-}
-
-/**
- * Cleanup before exiting.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Convolution Shader Example</h1>
-<p>This sample shows how to do 2D image processing using render targets. This
-sample uses a convolution shader to do a 2D Gaussian blur, but the
-same code could be used for any separable convolution kernel.</p>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 512px; height: 512px;"></div>
-<!-- End of O3D plugin -->
-<!--
- We embed the code for our effect inside this hidden textarea.
- Effects contain the functions that define
- the vertex and pixel shaders used by our shape.
--->
-<!-- Don't render the textarea -->
-<div style="display:none">
-<textarea id="convFX" name="convFX" cols="80" rows="20">
-float4x4 worldViewProjection : WorldViewProjection;
-sampler2D image;
-float kernel[KERNEL_WIDTH];
-float2 imageIncrement;
-
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 imageCoord : TEXCOORD0;
-};
-
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 imageCoord : TEXCOORD0;
-};
-
-PixelShaderInput ConvolutionVS(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(input.position, worldViewProjection);
-
- // Offset image coords by half of kernel width, in image texels
- output.imageCoord = input.imageCoord -
- ((KERNEL_WIDTH - 1) / 2) * imageIncrement;
-
- return output;
-}
-
-float4 ConvolutionPS(PixelShaderInput input) : COLOR {
- float2 imageCoord = input.imageCoord;
- float4 sum = float4(0.0, 0.0, 0.0, 0.0);
- for (int i = 0; i < KERNEL_WIDTH; ++i) {
- sum += tex2D(image, imageCoord) * kernel[i];
- imageCoord += imageIncrement;
- }
- return sum;
-}
-
-// #o3d VertexShaderEntryPoint ConvolutionVS
-// #o3d PixelShaderEntryPoint ConvolutionPS
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
-
-</html>
diff --git a/o3d/samples/culling.html b/o3d/samples/culling.html
deleted file mode 100644
index dbc3606..0000000
--- a/o3d/samples/culling.html
+++ /dev/null
@@ -1,321 +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.
--->
-
-<!--
-O3D Culling.
-
-Make sure things off screen get culled.
-
-By default nothing is culled. If you want object to be culled you must setup
-bounding boxes in the transform graph that fit the needs of your application
-and then turn on culling for those objects you want culled.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Culling.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// global variables
-var g_timeMult = 1.0;
-var g_framesRendered = 0;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_totalTransformsElement;
-var g_transformsProcessedElement;
-var g_transformsCulledElement;
-var g_totalDrawElementsElement;
-var g_totalDrawableThingsElement;
-var g_drawElementsProcessedElement;
-var g_drawElementsCulledElement;
-var g_drawElementsRenderedElement;
-var g_primitivesRenderedElement;
-var g_groupTransforms = [];
-var GROUPS_ACROSS = 2;
-var UNITS_ACROSS_GROUP = 2;
-var TOTAL_ACROSS = GROUPS_ACROSS * UNITS_ACROSS_GROUP;
-var HALF_WIDTH = TOTAL_ACROSS * 0.0;
-var UNIT_SPACING = 200;
-
-function createInstances(pack, shape) {
- // Make a grid of transforms and put a shape instance on each one.
- for (var g = 0; g < GROUPS_ACROSS; g++) {
- for (var h = 0; h < GROUPS_ACROSS; h++) {
- for (var i = 0; i < GROUPS_ACROSS; i++) {
- var groupTransform = pack.createObject('Transform');
- g_groupTransforms[g_groupTransforms.length] = groupTransform;
- groupTransform.parent = g_client.root;
- // Turn on culling for this transform.
- groupTransform.cull = true;
- var boundingBox = g_o3d.BoundingBox([0, 0, 0],
- [0, 0, 0]);
- groupTransform.translate(
- (g * UNITS_ACROSS_GROUP - HALF_WIDTH) * UNIT_SPACING,
- (h * UNITS_ACROSS_GROUP - HALF_WIDTH) * UNIT_SPACING,
- (i * UNITS_ACROSS_GROUP - HALF_WIDTH) * UNIT_SPACING);
-
- for (var x = 0; x < UNITS_ACROSS_GROUP; x++) {
- for (var y = 0; y < UNITS_ACROSS_GROUP; y++) {
- for (var z = 0; z < UNITS_ACROSS_GROUP; z++) {
- var transform = pack.createObject('Transform');
- transform.parent = groupTransform;
- // Turn on culling for this transform.
- transform.cull = true;
- transform.addShape(shape);
- // Add up the bounding boxes of all the elements.
- var elements = shape.elements;
- var box = elements[0].boundingBox;
- for (var ee = 1; ee < elements.length; ee++) {
- box = box.add(elements[ee].boundingBox);
- }
- // Set the transform to have a bounding box that is the sum
- // of all the elements under it.
- transform.boundingBox = box;
- transform.translate(
- (x - UNITS_ACROSS_GROUP * 0.5) * UNIT_SPACING,
- (y - UNITS_ACROSS_GROUP * 0.5) * UNIT_SPACING,
- (z - UNITS_ACROSS_GROUP * 0.5) * UNIT_SPACING);
- transform.createParam('diffuse', 'ParamFloat4').value = [
- (g * UNITS_ACROSS_GROUP + x) * (1 / TOTAL_ACROSS),
- (h * UNITS_ACROSS_GROUP + y) * (1 / TOTAL_ACROSS),
- (i * UNITS_ACROSS_GROUP + z) * (1 / TOTAL_ACROSS),
- 1];
- // Add the box for this bounding box to the box for the group.
- var box = transform.boundingBox.mul(transform.localMatrix);
- boundingBox = boundingBox.add(box);
-
- }
- }
- }
- // Set the bounding box for the group transform to encompass all
- // the transforms below it.
- groupTransform.boundingBox = boundingBox;
- }
- }
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- // These are here so that they are visible to both the browser (so
- // selenium sees them) and the embedded V8 engine.
- window.g_clock = 0;
- window.g_timeMult = 1;
- window.g_finished = false; // for selenium testing.
-
- // Comment out the line below to run the sample in the browser
- // JavaScript engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Set window.g_client as well. Otherwise when the sample runs in
- // V8, selenium won't be able to find this variable (it can only see
- // the browser environment).
- window.g_client = g_client = o3dElement.client;
-
- g_totalDrawableThingsElement =
- o3djs.util.getElementById('totalDrawableThings');
- g_totalTransformsElement =
- o3djs.util.getElementById('totalTransforms');
- g_transformsProcessedElement =
- o3djs.util.getElementById('transformsProcessed');
- g_transformsCulledElement =
- o3djs.util.getElementById('transformsCulled');
- g_totalDrawElementsElement =
- o3djs.util.getElementById('totalDrawElements');
- g_drawElementsProcessedElement =
- o3djs.util.getElementById('drawElementsProcessed');
- g_drawElementsCulledElement =
- o3djs.util.getElementById('drawElementsCulled');
- g_drawElementsRenderedElement =
- o3djs.util.getElementById('drawElementsRendered');
- g_primitivesRenderedElement =
- o3djs.util.getElementById('primitivesRendered');
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create our projection matrix, with a vertical field of view of 45
- // degrees a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 10000);
-
- // Create and load the effect.
- var material = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [1, 1, 1, 1]);
-
- // Create 2 spheres.
- var shape1 = o3djs.primitives.createSphere(
- g_pack,
- material,
- 40,
- 20,
- 20,
- g_math.matrix4.translation([-50, 0, 0]));
-
- var shape2 = o3djs.primitives.createSphere(
- g_pack,
- material,
- 20,
- 20,
- 20,
- g_math.matrix4.translation([50, 0, 0]));
- // Create a shape and move the 2 sphere primitives to the same shape.
- // This is done to show that each of the primitives under the shape
- // will get culled separately.
- var shape = g_pack.createObject('Shape');
- shape1.elements[0].owner = shape;
- shape2.elements[0].owner = shape;
- // delete the old shapes.
- g_pack.removeObject(shape1);
- g_pack.removeObject(shape2);
- var elements = shape.elements;
- // Turn on culling for the two sphere elements.
- elements[0].cull = true;
- elements[1].cull = true;
-
- createInstances(g_pack, shape);
-
- g_totalDrawableThingsElement.innerHTML =
- GROUPS_ACROSS * UNITS_ACROSS_GROUP *
- GROUPS_ACROSS * UNITS_ACROSS_GROUP *
- GROUPS_ACROSS * UNITS_ACROSS_GROUP;
-
- g_totalDrawElementsElement.innerHTML = g_client.getObjectsByClassName(
- 'o3d.DrawElement').length;
- g_totalTransformsElement.innerHTML = g_client.getObjectsByClassName(
- 'o3d.Transform').length;
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- window.g_finished = true; // for selenium testing.
-}
-
-// spin the camera.
-function onrender(renderEvent) {
- g_framesRendered++;
- // Get the number of seconds since the last render.
- var elapsedTime = renderEvent.elapsedTime;
-
- // Update g_clock in the browser and cache a V8 copy that can be
- // accessed efficiently. g_clock must be in the browser for selenium.
- var clock = window.g_clock + elapsedTime * window.g_timeMult;
- window.g_clock = clock;
-
- var x = Math.sin(clock * 0.1) * 300;
- var z = Math.cos(clock * 0.1) * 300;
- var y = Math.sin(clock * 0.2) * 300;
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [x, y, z],
- [0, 0, 0],
- [0, 1, 0]);
-
- g_transformsProcessedElement.innerHTML = renderEvent.transformsProcessed;
- g_transformsCulledElement.innerHTML = renderEvent.transformsCulled;
- g_drawElementsProcessedElement.innerHTML = renderEvent.drawElementsProcessed;
- g_drawElementsCulledElement.innerHTML = renderEvent.drawElementsCulled;
- g_drawElementsRenderedElement.innerHTML = renderEvent.drawElementsRendered;
- g_primitivesRenderedElement.innerHTML = renderEvent.primitivesRendered;
-}
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body onload="init()" onunload="unload()">
-<h1>Culling</h1>
-Objects off screen should get culled.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<table>
-<tr><td>Total Drawable Things:</td><td><span id="totalDrawableThings">-</span></td></tr>
-<tr><td>Total Transforms:</td><td><span id="totalTransforms">-</span></td></tr>
-<tr><td>Transforms Processed:</td><td><span id="transformsProcessed">-</span></td></tr>
-<tr><td>Transforms Culled:</td><td><span id="transformsCulled">-</span></td></tr>
-<tr><td>Total DrawElements:</td><td><span id="totalDrawElements">-</span></td></tr>
-<tr><td>DrawElements Processed:</td><td><span id="drawElementsProcessed">-</span></td></tr>
-<tr><td>DrawElements Culled:</td><td><span id="drawElementsCulled">-</span></td></tr>
-<tr><td>DrawElements Rendered:</td><td><span id="drawElementsRendered">-</span></td></tr>
-<tr><td>Primitives Rendered:</td><td><span id="primitivesRendered">-</span></td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/customcamera.html b/o3d/samples/customcamera.html
deleted file mode 100644
index e3c7538..0000000
--- a/o3d/samples/customcamera.html
+++ /dev/null
@@ -1,405 +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.
--->
-
-<!--
-O3D Tutorial B4
-
-This tutorial shows how we generate a simple cube mesh
-and view it using a dynamically generated camera which can be animated.
-
-We also show how to dynamically change the perspective matrix
-to adjust to the correct aspect ratio as the o3d window is resized.
-
-The cube can be animated along the target's y-axis and the animation is
-done every time a frame is rendered.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Tutorial B4: Cameras and events
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- }
-</style>
-<!-- Our javascript code -->
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Events
-// Run the init() function once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_o3dElement;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-
-// Our view and projection matrices
-// The view matrix transforms objects from world space to view space.
-var g_viewMatrix;
-// The projection matrix projects objects from view space to the screen.
-var g_projMatrix;
-
-// Animation varibles
-
-// Boolean flag that signals whether animation is on.
-var g_animate;
-// Current angle
-var g_animateAngle;
-
-/**
- * Creates our client area by looking for <div>s with an id that starts with
- * "o3d".
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and draws the cube.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Reset animation variables.
- g_animate = false;
- g_animateAngle = 0;
-
- // Create a material.
- var myMaterial = o3djs.material.createMaterialFromFile(
- g_pack,
- 'shaders/vertex-color.shader',
- g_viewInfo.performanceDrawList);
-
- // Create a cube.
- var cube = o3djs.primitives.createRainbowCube(g_pack, myMaterial, 1);
-
- setDefaultCameraValues();
- setCamera();
-
- // Generate the projection and viewProjection matrices based
- // on the plugin size by calling Resize().
- resize();
-
- // Attach the cube to the root of the transform graph.
- var root = g_client.root;
- root.addShape(cube);
-
-
- // Set our render callback for animation.
- // This sets a function to be executed every time a frame is rendered.
- g_client.setRenderCallback(onrender);
-}
-
-// Generates the projection matrix based on the size of the g_o3d plugin
-// and calculates the view-projection matrix.
-function resize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- // Create our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 100.
- g_projMatrix = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_o3dWidth / g_o3dHeight,
- 0.1,
- 100);
-
- // update our view projection matrix
- setViewProjection();
- }
-}
-
-// Sets the view and projection matrices.
-function setViewProjection() {
- g_viewInfo.drawContext.view = g_viewMatrix;
- g_viewInfo.drawContext.projection = g_projMatrix;
-}
-
-// Sets the default camera values and updates the view matrix
-function setDefaultCameraValues() {
- var myForm = document.defaultForm;
-
- // default eye position = (2, 2, 4)
- myForm.eyeX.value = '2.0';
- myForm.eyeY.value = '1.0';
- myForm.eyeZ.value = '4.0';
-
- // default target position = (0, 0, 0)
- // (ie centre of the cube)
- myForm.targetX.value = '0.0';
- myForm.targetY.value = '0.0';
- myForm.targetZ.value = '0.0';
-
- // default up vector = (0, 1, 0)
- // (this tells the renderer which direction is 'up')
- // in this case, we define the positive y-axis to be 'up'.
- myForm.upX.value = '0.0';
- myForm.upY.value = '1.0';
- myForm.upZ.value = '0.0';
-
- // update the view matrix
- setCamera();
-}
-
-// Updates the view matrix using the current camera parameters
-function setCamera() {
- // Create our view matrix using the target, eye, and up vectors in the form
- // and using the lookAt(..)
- // helper function to create the matrix.
- var myForm = document.defaultForm;
-
- // Eye-position, this is where our camera is at.
- var eye = [parseFloat(myForm.eyeX.value),
- parseFloat(myForm.eyeY.value),
- parseFloat(myForm.eyeZ.value)];
-
- // Target, this is where our camera is pointed at.
- var target = [parseFloat(myForm.targetX.value),
- parseFloat(myForm.targetY.value),
- parseFloat(myForm.targetZ.value)];
-
- // Up-vector, this tells the camera which direction is 'up'.
- // We define the positive y-direction to be up in this example.
- var up = [parseFloat(myForm.upX.value),
- parseFloat(myForm.upY.value),
- parseFloat(myForm.upZ.value)];
-
- g_viewMatrix = g_math.matrix4.lookAt(eye, target, up);
-
- // if we already have our projection matrix,
- // update the view projection matrix.
- if (g_projMatrix)
- setViewProjection();
-}
-
-// Validates a field in the form to make sure it contains a float.
-function validateFloat(field) {
- var floatValue = parseFloat(field.value);
- if (isNaN(floatValue))
- field.value = '0.0';
- else
- field.value = floatValue;
-}
-
-// Toggles animation
-function toggleAnimate() {
- // toggle the animate flag.
- g_animate = !g_animate;
-
- if (g_animate) {
- // turn on animation
- document.defaultForm.btnAnimate.value = 'Stop animation';
- } else {
- // turn off animation
- document.defaultForm.btnAnimate.value = 'Animate';
- }
-}
-
-// Animates the camera.
-// This function executes on each frame.
-// It was set using g_client.setRenderCallback(..)
-// in initStep2().
-function onrender(renderEvent) {
- resize();
- if (g_animate) {
- // Update the angle frame rate independently.
- g_animateAngle += 2.0 * renderEvent.elapsedTime;
-
- var myForm = document.defaultForm;
- // Set radius to 1.5
- var radius = 1.5;
- // rotate around the y-axis relative to the target
- myForm.eyeX.value = parseFloat(myForm.targetX.value) +
- Math.sin(g_animateAngle) * radius;
- myForm.eyeZ.value = parseFloat(myForm.targetZ.value) +
- Math.cos(g_animateAngle) * radius;
-
- setCamera();
- }
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<table width="100%" style="height:100%;"><tr><td valign="middle" align="center">
-<table width="100%" style="height:100%;"><tr><td>
-<h1>Cameras and events</h1>
-<p>
-This tutorial shows how we generate a simple cube mesh
-and view it using a dynamically generated camera which can be animated.
-</p>
-<p>
-Press Animate to animate the camera and use the textboxes to manually
-set the position of the camera.
-</p>
-<!-- Centre everything in the div -->
- <table id="container" width="98%" style="height:50%;"><tr><td height="100%">
- <!-- Start of g_o3d plugin -->
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- <!-- End of g_o3d plugin -->
- </td></tr></table>
- <!-- Format input fields nicely in a table -->
- <form action="#" method="get" name="defaultForm">
- <table style="margin-left:auto; margin-right:auto"
- summary="This table contains camera controls.">
- <thead style="font-weight:bold; text-align:center">
- <tr>
- <th></th>
- <th>x</th>
- <th>y</th>
- <th>z</th>
- <th></th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>Eye</td>
- <td><input id="eyeX"
- name="eyeX"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td><input id="eyeY"
- name="eyeY"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td><input id="eyeZ"
- name="eyeZ"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td rowspan="2">
- <input id="btnSet"
- name="btnSet"
- type="button"
- value="Set camera"
- onClick="setCamera()"/>
- </td>
- </tr>
- <tr>
- <td>Target</td>
- <td><input id="targetX"
- name="targetX"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td><input id="targetY"
- name="targetY"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td><input id="targetZ"
- name="targetZ"
- type="text"
- onblur="validateFloat(this)"/></td>
- </tr>
- <tr>
- <td>Up vector</td>
- <td><input id="upX"
- name="upX"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td><input id="upY"
- name="upY"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td><input id="upZ"
- name="upZ"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td>
- <input id="btnDefault"
- name="btnDefault"
- type="button"
- value="Restore default camera"
- onClick="setDefaultCameraValues()"/>
- </td>
- </tr>
- <tr>
- <td colspan="5" style="text-align:center">
- <input id="btnAnimate"
- name="btnAnimate"
- type="button"
- value="Animate"
- onClick="toggleAnimate()"/>
- </td>
- </tr>
- </tbody>
- </table>
- </form>
-</td></tr></table>
-</td></tr></table>
-</body>
-</html>
diff --git a/o3d/samples/debugging.html b/o3d/samples/debugging.html
deleted file mode 100644
index 84af399..0000000
--- a/o3d/samples/debugging.html
+++ /dev/null
@@ -1,246 +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 sample shows examples of using the debug.js utilities.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Debugging.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.debug');
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_transforms = [];
-var g_o3dWidth; // width of our client area.
-var g_o3dHeight; // height of our client area.
-var g_finished = false; // for selenium testing.
-var g_clock = 0;
-var g_lastClock = 0;
-var g_tempAxesOn = false;
-var g_tempLinesOn = false;
-var g_timeMult = 1;
-var g_debugHelper;
-var g_debugLineGroup;
-var g_startEndLine;
-var g_tempLineGroup;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Get the width and height of our client area. We will need this to create
- // a projection matrix.
- g_o3dWidth = o3dElement.clientWidth;
- g_o3dHeight = o3dElement.clientHeight;
-
- // Creates a pack to manage our resources/assets.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set the projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_o3dWidth / g_o3dHeight,
- 0.1,
- 10000);
-
- // Create 11 transforms for the bones and parent them into a chain.
- for (var ii = 0; ii <= 10; ++ii) {
- var transform = g_pack.createObject('Transform');
- g_transforms[ii] = transform;
- if (ii > 0) {
- transform.translate(0, 20, 0);
- }
- transform.parent = ii == 0 ? g_client.root : g_transforms[ii - 1];
- }
-
- // create a debug helper.
- g_debugHelper = o3djs.debug.createDebugHelper(g_client.createPack(),
- g_viewInfo);
-
- // create a debug line group
- g_debugLineGroup = g_debugHelper.createDebugLineGroup(g_client.root);
-
- // draw a few lines.
- g_debugLineGroup.addLine([-20, 0, -20], [-20, 0, +20], [0, 1, 1, 1]);
- g_debugLineGroup.addLine([-20, 0, +20], [+20, 0, +20], [0, 1, 1, 1]);
- g_debugLineGroup.addLine([+20, 0, +20], [+20, 0, -20], [0, 1, 1, 1]);
- g_debugLineGroup.addLine([+20, 0, -20], [-20, 0, -20], [0, 1, 1, 1]);
-
- // create a line for updating.
- g_startEndLine = g_debugLineGroup.addLine();
-
- // Add axes to all the transforms.
- g_debugHelper.addAxes(g_client.root);
-
- // Add a cube to a transform.
- g_debugHelper.addCube(g_transforms[3]);
- g_debugHelper.setCubeScale(g_transforms[3], 10);
- g_debugHelper.setCubeColor(g_transforms[3], [1, 1, 0, 1]); // yellow.
-
- // Add a sphere to a transform.
- g_debugHelper.addSphere(g_transforms[7]);
- g_debugHelper.setSphereScale(g_transforms[7], 20);
- g_debugHelper.setSphereColor(g_transforms[7], [1, 0, 1, 1]); // magenta.
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-// spin the camera.
-function onrender(render_event) {
- // Get the number of seconds since the last render.
- var elapsedTime = render_event.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- var x = Math.sin(g_clock * 0.3) * 400;
- var z = Math.cos(g_clock * 0.3) * 400;
- var y = Math.sin(g_clock * 0.7) * 50 + 100;
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [x, y, z], // eye
- [0, 100, 0], // target
- [0, 1, 0]); // up
-
- // Make our bone chain bend.
- var rotation = Math.PI / g_transforms.length * Math.sin(g_clock * 1);
- for (var ii = 1; ii < g_transforms.length; ++ii) {
- var transform = g_transforms[ii];
- transform.identity();
- transform.translate(0, 20, 0);
- transform.rotateX(rotation);
- }
-
- // change the color of an axis each frame.
- if ((g_clock * 2) % 2 < 1) {
- g_debugHelper.setAxisColor(g_transforms[4], [1, 1, 1, 1]);
- } else {
- g_debugHelper.clearAxisColor(g_transforms[4]);
- }
-
- var start = g_math.matrix4.getTranslation(g_transforms[0].worldMatrix);
- var end = g_math.matrix4.getTranslation(g_transforms[10].worldMatrix);
- g_startEndLine.setEndPoints(start, end);
-
- // Add/Remove some axes.
- var tempAxesOn = (g_clock % 2) < 1;
- if (tempAxesOn != g_tempAxesOn) {
- g_tempAxesOn = tempAxesOn;
- if (tempAxesOn) {
- g_debugHelper.addAxes(g_transforms[7]);
- } else {
- g_debugHelper.removeAxes(g_transforms[7]);
- }
- }
-
- // Create or delete a line group.
- var tempLinesOn = (g_clock * 1.1 % 2) < 1;
- if (tempLinesOn != g_tempLinesOn) {
- g_tempLinesOn = tempLinesOn;
- if (tempLinesOn) {
- g_tempLineGroup = g_debugHelper.createDebugLineGroup(g_transforms[10]);
- g_tempLineGroup.setColor([1, 0.7, 0.7, 1]);
- g_tempLineGroup.addLine([-20, 0, -20], [-20, 0, +20]);
- g_tempLineGroup.addLine([-20, 0, +20], [+20, 0, +20]);
- g_tempLineGroup.addLine([+20, 0, +20], [+20, 0, -20]);
- g_tempLineGroup.addLine([+20, 0, -20], [-20, 0, -20]);
- } else {
- g_tempLineGroup.destroy();
- }
- }
-
- g_lastClock = g_clock;
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Debugging.</h1>
-<p>This sample shows examples of using the debug.js utilities.
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/displayfps.html b/o3d/samples/displayfps.html
deleted file mode 100644
index 2405819..0000000
--- a/o3d/samples/displayfps.html
+++ /dev/null
@@ -1,215 +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.
--->
-
-<!--
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Compute and Display FPS.
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- }
-</style>
-<!-- Our javascript code -->
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.fps');
-
-// Events
-// Run the init() function once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-var g_o3dElement;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-var g_eye;
-var g_fpsManager;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and draws the cube.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create an FPS manager.
- g_fpsManager = o3djs.fps.createFPSManager(g_pack,
- g_client.width,
- g_client.height,
- g_client.renderGraphRoot);
-
- var shaderFilePath = 'shaders/vertex-color.shader';
- if (g_client.clientInfo.glsl) {
- shaderFilePath = 'shaders/vertex-color-glsl.shader'
- }
-
- // Create a material.
- var myMaterial = o3djs.material.createMaterialFromFile(
- g_pack,
- shaderFilePath,
- g_viewInfo.performanceDrawList);
-
- // Draw a cube using the effect we have loaded.
- var myShape = o3djs.primitives.createRainbowCube(g_pack,
- myMaterial,
- 0.5);
-
- // Attach the cube to the root of the transform graph.
- var root = g_client.root;
- root.addShape(myShape);
-
- // Set the projection and viewProjection matrices based
- // on the o3d plugin size by calling resize().
- resize();
-
- // Set our render callback for animation.
- // This sets a function to be executed every time a frame is rendered.
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-// Sets the projection matrix based on the size of the plugin.
-function resize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- // Set the projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 100.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_o3dWidth / g_o3dHeight,
- 0.1,
- 100);
-
- g_fpsManager.resize(g_o3dWidth, g_o3dHeight);
- }
-}
-
-// Animates the cube.
-// This function executes on each frame.
-// @param {!o3d.RenderEvent} renderEvent Info about rendering.
-function onrender(renderEvent) {
- // Get the number of seconds since the last render.
- var elapsedTime = renderEvent.elapsedTime;
-
- g_fpsManager.update(renderEvent);
-
- // Rotate frame rate independently.
- g_clock += 2.0 * elapsedTime * g_timeMult;
-
- // Eye-position, the position of the camera.
- var eye = [
- 0.0 + Math.sin(g_clock) * 1.5,
- 1.0,
- 0.0 + Math.cos(g_clock) * 1.5
- ];
-
- var target = [0, 0, 0];
- var up = [0, 1, 0];
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(eye, target, up);
-
- resize();
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<table width="100%" style="height:100%;">
- <tr><td>
-<h1>Show FPS</h1>
-<p>
-This example shows computing and displaying FPS (Frames Per Second)
-</p></td></tr>
-<tr><td height="100%">
-<div id=o3d" style="width: 100%; height: 100%;"></div>
-</td></tr></table>
-</body>
-</html>
diff --git a/o3d/samples/error-texture.html b/o3d/samples/error-texture.html
deleted file mode 100644
index c6a99e5..0000000
--- a/o3d/samples/error-texture.html
+++ /dev/null
@@ -1,263 +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 sample attempts to show what the error texture is, how to set it and
-how turning it off will generate helpful error information.
--->
-<html>
-<head>
-<title>Error Texture</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.effect');
-
-// Events
-// Run the init() once the page has finished loading.
-// and unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_texture;
-var g_errorMsgElement;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and sets up some quads.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- g_errorMsgElement =
- document.getElementById('errorMsg');
-
- // Turn of the error callback that o3djs.base.init setup.
- g_client.clearErrorCallback();
-
- // Let us render on demand.
- g_client.renderMode = g_o3d.Client.RENDERMODE_ON_DEMAND;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- var clientWidth = g_client.width;
- var clientHeight = g_client.height;
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -clientWidth * 0.5,
- clientWidth * 0.5,
- -clientHeight * 0.5,
- clientHeight * 0.5,
- 0.001,
- 1000);
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 500, 0], // eye
- [0, 0, 0], // target
- [0, 0, -1]); // up
-
- // Create and load the effect.
- var effect = g_pack.createObject('Effect');
- o3djs.effect.loadEffect(effect, 'shaders/texture-only.shader');
-
- // Create a Material for the effect.
- var myMaterial = g_pack.createObject('Material');
-
- // Set the material's drawList
- myMaterial.drawList = g_viewInfo.zOrderedDrawList;
-
- // Apply our effect to this material.
- myMaterial.effect = effect;
-
- // Creates a quad using the effect.
- var shape = o3djs.primitives.createPlane(g_pack,
- myMaterial,
- 1,
- 1,
- 1,
- 1);
-
- var pixels = [];
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 3; // rgb
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = 0; // red
- pixels[offset + 1] = Math.floor(y / 8) % 2; // green
- pixels[offset + 2] = Math.floor(x / 8) % 2; // blue
- }
- }
- var texture = g_pack.createTexture2D(32, 32, g_o3d.Texture.XRGB8, 1, false);
- texture.set(0, pixels);
-
- // display the quad 4 times with situations
- // by overriding the sampler on each instance.
- for (var s = 0; s < 4; ++s) {
- // create a transform for an instance
- var transform = g_pack.createObject('Transform');
- transform.translate((s - 1.5) * 140, 0, 0);
- transform.scale(128, 1, 128),
- transform.parent = g_client.root;
- transform.addShape(shape);
-
- // case 0: Correct Texture.
- // case 1: ParamSampler and Sampler but no Texture
- // case 2: ParamSampler but no Sampler,
- // case 3: No ParamSampler.
- if (s <= 2) {
- // Create a ParamSampler on the transform with the same name as in
- // the effect so this param will be used instead of the one on the
- // material.
- var samplerParam = transform.createParam('texSampler0', 'ParamSampler');
-
- if (s <= 1) {
- var sampler = g_pack.createObject('Sampler');
- sampler.name = "s2d";
- samplerParam.value = sampler;
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
- if (s == 0) {
- sampler.texture = texture;
- }
- }
- }
- }
-
- g_client.setPostRenderCallback(onRender);
-
- // Render once now that things are setup.
- render();
-}
-
-function setToUserTexture() {
- var pixels = [];
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 3; // rgb
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.cos(u); // red
- pixels[offset + 1] = Math.sin(v); // green
- pixels[offset + 2] = Math.sin(u); // blue
- }
- }
- var texture = g_pack.createTexture2D(32, 32, g_o3d.Texture.XRGB8, 1, false);
- texture.set(0, pixels);
-
- g_client.setErrorTexture(texture);
- // Render once now that things are setup.
- render();
-}
-
-function setToNoTexture() {
- g_client.setErrorTexture(null);
- render();
-
-}
-
-function hide0() {
- var child = g_client.root.children[1];
- child.visible = !child.visible;
- render();
-}
-
-function hide1() {
- var child = g_client.root.children[2];
- child.visible = !child.visible;
- render();
-}
-
-function reportError(msg) {
- g_errorMsgElement.innerHTML = g_client.lastError;
- g_client.clearLastError();
- g_client.clearErrorCallback();
-}
-
-function render() {
- // Render once now that things are setup.
- g_client.setErrorCallback(reportError);
- g_client.render();
-}
-
-function onRender() {
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- g_client.cleanup();
-}
-</script>
-</head>
-<body>
-<h1>Error Texture.</h1>
-<br/>
-Demonstrates how missing textures are handled.
-<div>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</div>
-<br/>
-<input type="button" value="User Texture" onClick="setToUserTexture()"/>
-<input type="button" value="No Texture" onClick="setToNoTexture()"/>
-<input type="button" value="hide 0" onClick="hide0()"/>
-<input type="button" value="hide 1" onClick="hide1()"/>
-<table><tr><td>Error: </td><td id="errorMsg">-</td></tr></table>
-</html>
diff --git a/o3d/samples/fullscreen.html b/o3d/samples/fullscreen.html
deleted file mode 100644
index a737c1f..0000000
--- a/o3d/samples/fullscreen.html
+++ /dev/null
@@ -1,367 +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.
--->
-
-<!--
-Full-Screen Mode Example
-
-In this tutorial, we load and display a scene in O3D.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Full-Screen Mode Example
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.scene');
-o3djs.require('o3djs.primitives');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-window.onunload = uninit;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_finished = false; // for selenium testing
-var g_teapotRoot;
-var g_orthoRoot;
-var g_bannerTexture;
-var g_o3dElement;
-
-/**
- * Creates the polygon and texture that will display the fullscreen banner, and
- * makes a clickable region to match that will trigger the transition.
- * @param {!number} clientHeight the height of the plugin region in pixels.
- * @param {!o3djs.rendergraph.viewInfo} viewInfo the view corresponding to the
- * orthographic projection on which we'll be displaying the banner.
- */
-function createBannerSurfaceAndClickableRegion(clientHeight, viewInfo) {
- // Create a material.
- var material = o3djs.material.createMaterialFromFile(
- g_pack,
- 'shaders/texture-only.shader',
- viewInfo.zOrderedDrawList);
-
- // Create a 2d plane for images. createPlane makes an XZ plane by default
- // so we pass in matrix to rotate it to an XY plane. We could do
- // all our manipulations in XZ but most people seem to like XY for 2D.
- var planeShape = o3djs.primitives.createPlane(
- g_pack,
- material,
- 1,
- 1,
- 1,
- 1,
- [[1, 0, 0, 0],
- [0, 0, 1, 0],
- [0,-1, 0, 0],
- [0, 0, 0, 1]]);
-
- // Load our banner.
- var url = o3djs.util.getCurrentURI() + 'assets/fullscreen.png';
- o3djs.io.loadTexture(g_pack, url, function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- var sampler = g_pack.createObject('Sampler');
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
- var paramSampler = g_orthoRoot.createParam('texSampler0', 'ParamSampler');
- paramSampler.value = sampler;
-
- g_bannerTexture = sampler.texture = texture;
- g_orthoRoot.addShape(planeShape);
-
- // Convert to a top-left-corner-based coordinate system from the
- // center-based default.
- g_orthoRoot.translate(texture.width / 2, texture.height / 2, 0);
-
- // Place the banner 10 pixels in from the bottom-left corner.
- g_orthoRoot.translate(10, clientHeight - texture.height - 10, 0);
-
- // Adjust the scale such that the above adjustment is in pixels; we could
- // alternatively make the order work out by doing the scaling and
- // transformation in separate transforms, with the translation in the
- // parent and the scaling in the child.
- g_orthoRoot.scale(texture.width, -texture.height, 1);
-
- o3djs.event.addEventListener(g_o3dElement, 'resize', handleResizeEvent);
- updateBanner();
- }
- g_finished = true; // for selenium testing.
- });
-}
-
-/**
- * Creates an orthographic projection view that will overlay the main display,
- * and places on it the fullscreen banner. Also creates the corresponding
- * clickable region that triggers the fullscreen transition.
- * @param {!number} width the width of the plugin region.
- * @param {!number} height the height of the plugin region.
- * @param {!o3djs.rendergraph.viewInfo} viewInfo the view corresponding to the
- * orthographic projection on which we'll be displaying the banner.
- */
-function setupBanner(width, height, viewInfo) {
- g_orthoRoot = g_pack.createObject('Transform');
-
- // Create a view for the orthographic display of the fullscreen banner.
- var orthoViewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_orthoRoot,
- g_client.renderGraphRoot);
-
- // Make sure the orthographic view gets drawn after the 3d stuff
- orthoViewInfo.root.priority = g_viewInfo.root.priority + 1;
-
- // Turn off clearing the color for the orthographic view, since that would
- // erase the 3d parts. Leave clearing the depth and stencil, so it's
- // unaffected by anything done by the 3d parts.
- orthoViewInfo.clearBuffer.clearColorFlag = false;
-
- // Set culling to none so we can flip images using rotation or negative scale.
- orthoViewInfo.zOrderedState.getStateParam('CullMode').value =
- g_o3d.State.CULL_NONE;
- orthoViewInfo.zOrderedState.getStateParam('ZWriteEnable').value = false;
-
- // Create an orthographic matrix for the banner.
- // The area we're using for display is width by height pixels.
- // If we change the size of the client area after setup, everything will get
- // scaled to match, but we don't have to change any of our code.
- orthoViewInfo.drawContext.projection = g_math.matrix4.orthographic(
- 0 + 0.5,
- width + 0.5,
- height + 0.5,
- 0 + 0.5,
- 0.001,
- 1000);
-
- orthoViewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 0, 1], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- createBannerSurfaceAndClickableRegion(g_client.height, orthoViewInfo);
-}
-
-/**
- * Sets up the view and protection matrices, given a transform holding camera
- * parameters.
- * @param {!o3d.Transform} camera Transform with camera information on it.
- */
-function setupCamera(camera) {
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- camera,
- g_client.width,
- g_client.height);
-
- // Copy the view and projection to the draw context.
- g_viewInfo.drawContext.view = cameraInfo.view;
- g_viewInfo.drawContext.projection = cameraInfo.projection;
-}
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- */
-function loadScene(pack, fileName, parent) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
-
- setupCamera(parent);
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
-
- setupBanner(g_client.width, g_client.height, g_viewInfo);
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Creates a transform to put our data on.
- g_teapotRoot = g_pack.createObject('Transform');
-
- // Connects our root to the client root.
- g_teapotRoot.parent = g_client.root;
-
- // Load the scene into the transform graph as a child g_teapotRoot
- loadScene(g_pack, 'assets/teapot.o3dtgz', g_teapotRoot);
-}
-
-/**
- * Finds a good, large display mode that the current screen supports.
- */
-function getFullscreenModeId() {
- var displayModes = g_client.getDisplayModes();
- var bestMode;
- for (var index in displayModes) {
- var mode = displayModes[index];
- if (!bestMode ||
- (mode.width > bestMode.width && mode.height > bestMode.height)) {
- bestMode = mode;
- }
- }
- if (bestMode) {
- return bestMode.id;
- } else { // getDisplayModes isn't implemented on all platforms yet.
- return g_o3d.Renderer.DISPLAY_MODE_DEFAULT;
- }
-}
-
-var timeoutId;
-function handleResizeEvent(event) {
- // Only show the fullscreen banner if we're in plugin mode.
- g_orthoRoot.visible = !event.fullscreen &&
- document.getElementById("show_banner").checked;
-
- setupCamera(g_teapotRoot);
-
- // Set a timer to pop us back out of full-screen mode, just to show how easy
- // it is to cancel. You need a user action [a mouse click] to get into
- // full-screen mode, but you can revert back to a plugin without asking.
- if (event.fullscreen &&
- document.getElementById("cancel_fullscreen").checked) {
- timeoutId = setTimeout(
- function () {
- g_client.cancelFullscreenDisplay()
- },
- 5000);
- } else {
- if (timeoutId) {
- clearTimeout(timeoutId);
- timeoutId = null;
- }
- }
-}
-
-function updateBanner() {
- if (document.getElementById("show_banner").checked) {
- g_client.setFullscreenClickRegion(10,
- g_client.height - g_bannerTexture.height - 10, g_bannerTexture.width,
- g_bannerTexture.height, getFullscreenModeId());
- g_orthoRoot.visible = true;
- } else {
- g_client.clearFullscreenClickRegion();
- g_orthoRoot.visible = false;
- }
-}
-
-function uninit() {
- if (timeoutId) {
- clearTimeout(timeoutId);
- timeoutId = null;
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Full-screen mode.</h1>
-This tutorial shows how to toggle between plugin and full-screen display.
-<p>It's built on top of helloworld.html; diff the two to see what changes were
-necessary.
-<p>Shortly after transitioning to full-screen mode, the teapot will
-automatically revert back to plugin mode, to demonstrate how programs can cancel
-full-screen mode on demand.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<input type="checkbox" id="show_banner" checked onclick=updateBanner()>
-Show full-screen banner when not full-screen.</input>
-<br>
-<input type="checkbox" id="cancel_fullscreen" checked>
-Revert back to plugin mode automatically after a few seconds of full-screen mode.</input>
-</body>
-</html>
diff --git a/o3d/samples/gadgets/readme.txt b/o3d/samples/gadgets/readme.txt
deleted file mode 100644
index 2ee0f51..0000000
--- a/o3d/samples/gadgets/readme.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-This directory contains Google gadgets samples using the O3D API.
-
-The gadgets can be added to an iGoogle homepage by using the
-"Add feed or gadget" link from the iGoogle gadgets directory:
-http://www.google.com/ig/directory.
-
-More information about creating O3D gadgets can be found in the
-O3D Developer's Guide under "How to Add O3D to a Gadget".
-
-
-
diff --git a/o3d/samples/gadgets/scatter-chart.xml b/o3d/samples/gadgets/scatter-chart.xml
deleted file mode 100644
index b22c7c4..0000000
--- a/o3d/samples/gadgets/scatter-chart.xml
+++ /dev/null
@@ -1,434 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<Module>
- <ModulePrefs title="3D Scatter Chart"
- height="340"
- author="Google O3D Team"
- author_email="o3d-discuss@googlegroups.com"
- />
-
-<Content type="html">
-<![CDATA[
-
-<!-- Include vizualizations - Load the Google AJAX API -->
-<script type="text/javascript" src="http://www.google.com/jsapi"></script>
-
-<!-- The path to the utility libraries. -->
-<script type="text/javascript" src="http://o3d.googlecode.com/svn/trunk/samples/o3djs/base.js"></script>
-
-<script type="text/javascript">
-
-// for gadgets we need to specify the base path of our included utility files.
-o3djs.basePath="http://o3d.googlecode.com/svn/trunk/samples/";
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.arcball');
-o3djs.require('o3djs.event');
-
-// Load the Visualization API.
-google.load('visualization', '1', {'packages':['piechart']});
-
-// The initClient() function runs when the page has finished loading.
-_IG_RegisterOnloadHandler(initClient);
-
-// global variables
-var g_o3dElement;
-var g_client;
-var g_o3d;
-var g_math;
-var g_quaternions;
-var g_pack;
-var g_viewInfo;
-var g_modelRoot;
-var g_eyeView;
-var g_cubeShape;
-var g_material;
-var g_aball;
-var g_thisRot;
-var g_lastRot;
-var g_zoomFactor;
-var g_dragging;
-var g_dataView;
-var g_dataSpreadsheet;
-var g_finished = false; // for selenium testing.
-
-/**
- * Creates the client area.
- */
-function initClient() {
- o3djs.util.makeClients(main);
-}
-
-/**
- * Initializes global variables, positions camera, draws the 3D chart.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function main(clientElements) {
- // Init global variables.
- initGlobals(clientElements);
-
- // Set up the view and projection transformations.
- initContext();
-
- // Setup rendering on demand only.
- g_client.renderMode = g_o3d.Client.RENDERMODE_ON_DEMAND;
-
- // Add the 3D chart model to the transform hierarchy.
- create3dChartModel();
-
- // Query the spreadsheet for the chart data.
- queryChartDataSource();
-
- // Start rendering.
- g_client.render();
-
- // Execute keyPressed(..) when we detect a keypress on the window or
- // on the o3d object.
- window.document.onkeypress = keyPressed;
- g_o3dElement.onkeypress = keyPressed;
-
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', startDragging);
- o3djs.event.addEventListener(g_o3dElement, 'mousemove', drag);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', stopDragging);
- o3djs.event.addEventListener(g_o3dElement, 'wheel', scrollMe);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Initializes global variables and libraries.
- */
-function initGlobals(clientElements) {
- // init o3d globals.
- g_o3dElement = clientElements[0];
- g_client = g_o3dElement.client;
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_quaternions = o3djs.quaternions;
-
- // Create an arcball.
- g_aball = o3djs.arcball.create(g_o3dElement.clientWidth,
- g_o3dElement.clientHeight);
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create a transform node to act as the 'root' of the model.
- // Attach it to the root of the transform graph.
- g_modelRoot = g_pack.createObject('Transform');
- g_modelRoot.parent = g_client.root;
-
- // Create the render graph for the view.
- var clearColor = [.98, .98, .98, 1];
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot,
- clearColor);
-
- // Create a material for the objects rendered.
- g_material = createPhongMaterial([1, 1, 1, 1]);
-
- // Create a cube shape to simulate the scatter points.
- g_cubeShape = o3djs.primitives.createCube(
- g_pack,
- g_material,
- 1);
-
- // set the chart data spreadsheet.
- g_dataSpreadsheet = 'http://spreadsheets.google.com/tq?key=pjdnPsZuqE92yNqA4iqT9Ig&range=A4:C533&gid=0';
-}
-
-/**
- * Initialize the original view of the model.
- */
-function initContext() {
- g_eyeView = [-35, 60, 140];
- g_zoomFactor = 1.03;
- g_dragging = false;
- g_modelRoot.identity();
- g_lastRot = g_math.matrix4.identity();
- g_thisRot = g_math.matrix4.identity();
-
- // Set up a perspective transformation for the projection.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(40), // 30 degree frustum.
- g_o3dElement.clientWidth / g_o3dElement.clientHeight, // Aspect ratio.
- 1, // Near plane.
- 10000); // Far plane.
-
- // Set up our view transformation to look towards the axes origin.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- g_eyeView, // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Reset to the original view of the model.
- */
-function resetView() {
- initContext();
- g_client.render();
-}
-
-/**
- * Creates a phong material based on the given single color.
- * @param {Array} baseColor An array with 4 entries, the R,G,B, and A components
- * of a color.
- * @return {!o3d.Material} A phong material whose overall pigment is baseColor.
- */
-function createPhongMaterial(baseColor) {
- // Create a new, empty Material object.
- var material = g_pack.createObject('Material');
-
- var lightPosition = [1000, 2000, 3000];
- o3djs.effect.attachStandardShader(
- g_pack, material, lightPosition, 'phong');
-
- material.drawList = g_viewInfo.performanceDrawList;
-
- // Assign parameters to the phong material.
- material.getParam('emissive').value = [0, 0, 0, 1];
- material.getParam('ambient').value =
- [.1 * baseColor[0], .1 * baseColor[1], .1 * baseColor[2], 1];
- material.getParam('diffuse').value =
- [.9 * baseColor[0], .9 * baseColor[1], .9 * baseColor[2], 1];
- material.getParam('specular').value = [.5, .5, .5, 1];
- material.getParam('shininess').value = 50;
- material.getParam('lightColor').value = [1, 1, 1, 1];
-
- return material;
-}
-
-/**
- * Initializes and queries the spreadsheet for the chart data.
- * The query is asynchronous and the response is handled by a callback.
- */
-function queryChartDataSource() {
- // Get chart data from the spreadsheet.
- var query = new google.visualization.Query(g_dataSpreadsheet);
-
- // Send the query with a callback function.
- query.send(handleQueryResponse);
-}
-
-/**
- * Handler for the spreadsheet query.
- * Called when the query response is returned.
- */
-function handleQueryResponse(response) {
- if (response.isError()) {
- alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
- return;
- }
-
- // Get the DataTable.
- var dataTable = response.getDataTable();
-
- // Create a DataView.
- g_dataView = new google.visualization.DataView(dataTable);
-
- // Create the scatter chart.
- createScatterObject();
-
- // Start rendering.
- g_client.render();
-}
-
-
-/**
- * Create a 3D Scatter object by plotting each data point on a 3D model.
- */
-function createScatterObject() {
- // size of a scatter point (represented as a small cube).
- var pointSize = 0.5;
-
- for (var i = 0; i < g_dataView.getNumberOfRows(); i += 1) {
- var varX = g_dataView.getValue(i,0);
- var varY = g_dataView.getValue(i,2);
- var varZ = g_dataView.getValue(i,1);
-
- // create the transform for the cube.
- var transform = g_pack.createObject('Transform');
- transform.parent = g_modelRoot;
- transform.addShape(g_cubeShape);
- // translate and scale the point correctly relative to origin
- transform.translate(varX, varY, varZ);
- transform.scale(pointSize, pointSize, pointSize);
- transform.createParam('diffuse', 'ParamFloat4').value = [1, 0, 0, 1];
- }
-}
-
-/**
- * Creates a 3D chart model.
- */
-function create3dChartModel() {
- // create the x,y,z axes - use the cylinder primitive.
- var cylinder_length = 90;
- var cylinder_radius = 0.15;
- var cylinder_subdivisions = 6;
-
- var cylinder = o3djs.primitives.createCylinder(
- g_pack,
- g_material,
- cylinder_radius, // Radius.
- cylinder_length, // Depth.
- cylinder_subdivisions, // Number of subdivisions.
- 1);
-
- var cylinder_x = g_pack.createObject('Transform');
- cylinder_x.parent = g_modelRoot;
- cylinder_x.addShape(cylinder);
- cylinder_x.createParam('diffuse', 'ParamFloat4').value = [1, 0.2, 0.2, 1];
- cylinder_x.rotateZ(Math.PI / 2);
-
- var cylinder_y = g_pack.createObject('Transform');
- cylinder_y.parent = g_modelRoot;
- cylinder_y.addShape(cylinder);
- cylinder_y.createParam('diffuse', 'ParamFloat4').value = [0.2, 1, 0.2, 1];
- cylinder_y.rotateX(Math.PI / 2);
-
- var cylinder_z = g_pack.createObject('Transform');
- cylinder_z.parent = g_modelRoot;
- cylinder_z.addShape(cylinder);
- cylinder_z.createParam('diffuse', 'ParamFloat4').value = [0.2, 0.2, 1, 1];
-}
-
-/**
- * Callback for the keypress event.
- * Rotates the 3D model along the x, y or z-axes based on key pressed.
- * Zooms in and out by moving the viewpoint.
- * @param {event} event keyPress event passed to us by javascript.
- */
-function keyPressed(event) {
- var keyChar = String.fromCharCode(o3djs.event.getEventKeyChar(event));
- keyChar = keyChar.toLowerCase();
-
- var delta = 0.03; // rotation delta.
- // Create an array associating the keystroke to an axis about which to rotate.
- // Then dereference that array to get the axis.
-
- switch(keyChar) {
- case 'a':
- g_modelRoot.localMatrix =
- g_math.mul(g_modelRoot.localMatrix,
- g_math.matrix4.rotationY(-delta));
- break;
- case 'd':
- g_modelRoot.localMatrix =
- g_math.mul(g_modelRoot.localMatrix,
- g_math.matrix4.rotationY(delta));
- break;
- case 'w':
- g_modelRoot.localMatrix =
- g_math.mul(g_modelRoot.localMatrix,
- g_math.matrix4.rotationX(-delta));
- break;
- case 's':
- g_modelRoot.localMatrix =
- g_math.mul(g_modelRoot.localMatrix,
- g_math.matrix4.rotationX(delta));
- break;
- case 'l':
- g_modelRoot.localMatrix =
- g_math.mul(g_modelRoot.localMatrix,
- g_math.matrix4.rotationZ(-delta));
- break;
- case 'k':
- g_modelRoot.localMatrix =
- g_math.mul(g_modelRoot.localMatrix,
- g_math.matrix4.rotationZ(delta));
- break;
- case 'i':
- ZoomInOut(g_zoomFactor);
- break;
- case 'o':
- ZoomInOut(1.0 / g_zoomFactor);
- break;
- }
-
- o3djs.event.cancel(event);
-
- g_client.render();
-}
-
-/**
- * Zooms the model in / out by changing the viewpoint.
- * @param {number} zoom zooming factor.
- */
-function ZoomInOut(zoom) {
- for (i = 0; i < g_eyeView.length; i += 1) {
- g_eyeView[i] = g_eyeView[i] / zoom;
- }
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- g_eyeView, // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Start mouse dragging.
- * @param {event} e event.
- */
-function startDragging(e) {
- g_lastRot = g_thisRot;
- g_aball.click([e.x, e.y]);
- g_dragging = true;
-}
-
-/**
- * Use the arcball to rotate the model.
- * Computes the rotation matrix.
- * @param {event} e event.
- */
-function drag(e) {
- if (g_dragging) {
- var rotationQuat = g_aball.drag([e.x, e.y]);
- var rot_mat = g_quaternions.quaternionToRotation(rotationQuat);
- g_thisRot = g_math.mul(g_lastRot, rot_mat);
- var m = g_modelRoot.localMatrix;
- g_math.matrix4.setUpper3x3(m, g_thisRot);
- g_modelRoot.localMatrix = m;
-
- g_client.render();
- }
-}
-
-/**
- * Stop dragging.
- * @param {event} e event.
- */
-function stopDragging(e) {
- g_dragging = false;
-}
-
-/**
- * Using the mouse wheel zoom in and out of the model.
- * @param {event} e event.
- */
-function scrollMe(e) {
- var zoom = (e.deltaY < 0) ? 1 / g_zoomFactor : g_zoomFactor;
- ZoomInOut(zoom);
- g_client.render();
-}
-
-</script>
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 320px; height: 320px;"></div>
-<!-- End of O3D plugin -->
-
-<form name="default_form" action="#" method="get" >
-<div style="font-size:10">
-Rotate: (W, S), (A, D), (K, L) &nbsp &nbsp &nbsp Zoom: (I, O)&nbsp &nbsp &nbsp
-<input type="button" value="Reset View" onclick="resetView()" style="font-size:10"/>
-</div>
-</form>
-]]>
-</Content>
-</Module>
diff --git a/o3d/samples/generate-texture.html b/o3d/samples/generate-texture.html
deleted file mode 100644
index 18417cc..0000000
--- a/o3d/samples/generate-texture.html
+++ /dev/null
@@ -1,290 +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.
--->
-
-<!--
-How to generate a texture.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Generate Texture.
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_finished = false; // for selenium testing
-var g_samplers = [];
-
-/**
- * Creates the client area.
- */
-function init() {
- // Comment out the line below to run the sample in the browser
- // JavaScript engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.util.makeClients(initStep2, 'FloatingPointTextures');
-}
-
-/**
- * Initializes O3D, loads an effect, creates some textures
- * and quads to display them.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Set window.g_client as well. Otherwise when the sample runs in
- // V8, selenium won't be able to find this variable (it can only see
- // the browser environment).
- window.g_client = g_client = o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- var clientWidth = g_client.width;
- var clientHeight = g_client.height;
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -clientWidth * 0.5,
- clientWidth * 0.5,
- -clientHeight * 0.5,
- clientHeight * 0.5,
- 0.001,
- 1000);
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 500, 0], // eye
- [0, 0, 0], // target
- [0, 0, -1]); // up
-
- // Create and load the effects.
- var effectNames = [
- 'texture-only.shader',
- 'luminance_alpha_texture.shader'];
-
- var effectInfos = {
- texture_only: {name: 'texture-only.shader'},
- one_channel_texture: {name: 'one-channel-texture.shader'}};
- for (var key in effectInfos) {
- var info = effectInfos[key];
- var material = o3djs.material.createMaterialFromFile(
- g_pack,
- 'shaders/' + info.name,
- g_viewInfo.zOrderedDrawList);
-
- // Create a quad.
- var shape = o3djs.primitives.createPlane(g_pack,
- material,
- 1,
- 1,
- 1,
- 1);
- info.shape = shape;
- }
-
- // display our shape 5 times with 5 different textures
- // by overriding the sampler on each instance.
- for (var s = 0; s < 5; ++s) {
- // create a transform for an instance
- var transform = g_pack.createObject('Transform');
- var x = s % 3;
- var z = Math.floor(s / 3);
- transform.translate((x - 1) * 140, 0, (z - 0.5) * 140);
- transform.scale(128, 1, 128);
- transform.parent = g_client.root;
-
- // Create a ParamSampler on the transform with the same name as in
- // the effect so this param will be used instead of the one on the material.
- var samplerParam = transform.createParam('texSampler0', 'ParamSampler');
-
- var sampler = g_pack.createObject('Sampler');
- samplerParam.value = sampler;
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
- g_samplers[s] = sampler;
-
- // Create a texture.
- {
- var pixels = [];
- var format;
-
- switch (s) {
- case 0: { // XRGB8
- transform.addShape(effectInfos.texture_only.shape);
- format = g_o3d.Texture.XRGB8;
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 3; // rgb
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.cos(u); // red
- pixels[offset + 1] = Math.sin(v); // green
- pixels[offset + 2] = Math.sin(u); // blue
- }
- }
- break;
- }
- case 1: { // ARGB8
- transform.addShape(effectInfos.texture_only.shape);
- format = g_o3d.Texture.ARGB8;
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 4; // rgba
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.floor(y / 4) % 2; // red
- pixels[offset + 1] = Math.sin(v); // green
- pixels[offset + 2] = Math.floor(x / 4) % 2; // blue
- pixels[offset + 3] = Math.abs(Math.sin(v * 4)); // alpha
- }
- }
- break;
- }
- case 2: { // ABGR16F
- transform.addShape(effectInfos.texture_only.shape);
- format = g_o3d.Texture.ABGR16F;
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 4; // rgba
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.cos(v); // red
- pixels[offset + 1] = Math.sin(u); // green
- pixels[offset + 2] = Math.sin(v); // blue
- pixels[offset + 3] = Math.abs(Math.sin(u * 8)); // alpha
- }
- }
- break;
- }
- case 3: { // ABGR32F
- transform.addShape(effectInfos.texture_only.shape);
- format = g_o3d.Texture.ABGR32F;
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 4; // rgba
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.cos(v); // red
- pixels[offset + 1] = Math.sin(u); // green
- pixels[offset + 2] = Math.sin(v); // blue
- pixels[offset + 3] = Math.abs(Math.sin(u * 8)); // alpha
- }
- }
- break;
- }
- case 4: { // R32F
- /**
- * NOTE: GL and D3D do NOT share compatible 1 channel texture formats.
- *
- * In D3D the sampler will return
- *
- * R = channel 0
- * G = const 1
- * B = const 1
- * A = const 1
- *
- * In GL the sampler will return
- *
- * R = channel 0
- * G = channel 0
- * B = channel 0
- * A = channel 0
- *
- * What that means is only R works across platforms. G, B and A are
- * undefined and if you use them you'll get the wrong results.
- */
- transform.addShape(effectInfos.one_channel_texture.shape);
- format = g_o3d.Texture.R32F;
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x); // r
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.cos(v * 16); // red
- }
- }
- break;
- }
- }
- var texture = g_pack.createTexture2D(32, 32, format, 1, false);
- texture.set(0, pixels);
- sampler.texture = texture;
- }
- }
- window.o3d_prepForSelenium = prepForSelenium;
- window.g_finished = true; // for selenium testing.
-}
-
-// Turn off all filtering in the samplers to get consistent testing
-// results.
-function prepForSelenium() {
- for (var i = 0; i < g_samplers.length; i++) {
- g_samplers[i].magFilter = g_o3d.Sampler.POINT;
- g_samplers[i].minFilter = g_o3d.Sampler.POINT;
- g_samplers[i].mipFilter = g_o3d.Sampler.NONE;
- }
-}
-
-
-</script>
-</head>
-<body onload="init()">
-<h1>Generate Texture</h1>
-Shows how to create textures in Javascript.
-<br/>
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/gpu2d/Google_Logo.svg b/o3d/samples/gpu2d/Google_Logo.svg
deleted file mode 100644
index e5f0332..0000000
--- a/o3d/samples/gpu2d/Google_Logo.svg
+++ /dev/null
@@ -1,134 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Generator: Adobe Illustrator 12.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 51448) -->
-<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [
- <!ENTITY ns_svg "http://www.w3.org/2000/svg">
- <!ENTITY ns_xlink "http://www.w3.org/1999/xlink">
-]>
-<svg version="1.1" xmlns="&ns_svg;" xmlns:xlink="&ns_xlink;" width="720.002" height="238.598" viewBox="0 0 720.002 238.598"
- overflow="visible" enable-background="new 0 0 720.002 238.598" xml:space="preserve">
-<g id="Grid" display="none">
-</g>
-<g id="Layer_1">
-</g>
-<g id="Desktop">
-</g>
-<g id="Guides">
-</g>
-<g id="Page_1">
- <g id="Layer_1_1_">
-
- <linearGradient id="XMLID_8_" gradientUnits="userSpaceOnUse" x1="242.4595" y1="542.1074" x2="332.2358" y2="542.1074" gradientTransform="matrix(0.6652 0 0 0.6708 371.3542 -281.5009)">
- <stop offset="0.35" style="stop-color:#85C881"/>
- <stop offset="0.503" style="stop-color:#097E3F"/>
- <stop offset="0.65" style="stop-color:#205127"/>
- </linearGradient>
- <path fill-rule="evenodd" clip-rule="evenodd" fill="url(#XMLID_8_)" d="M550.94,0c10.977,0,21.309,0.004,32.281,0.004
- c-4.492,2.91-6,4.117-7.93,7.172c-1.383,2.195-1.738,6.352-1.988,10.098c-1.887,43.109-0.73,86.543-1.008,129.652
- c0.176,11.75,4.793,10.371,20.074,9.922c-2.305,1.953-6.039,5.816-8.938,7.473c-13.781,0-26.945-0.293-40.723-0.293
- c5.195-5.363,7.855-8.82,7.5-22.227c0.273-45.055-1.512-88.285,1.234-131.672c-6.465,0.184-12.332,0.09-18.797,0.277
- C538.745,7.258,544.522,2.828,550.94,0L550.94,0z"/>
- <path fill-rule="evenodd" clip-rule="evenodd" fill="#6B696B" d="M691.01,55.836c1.488,0,9.984,0,11.473,0l-0.77,2.113
- c-0.262,0.109-0.523,0.215-0.781,0.324c0.164-0.777,0.434-1.355-0.16-1.512l-2.691,0.004c-0.148,2.574-0.254,7.293-0.25,10.68
- c-0.133,1.121,1.086,1.051,2.348,1.301l-1.098,0.637c-1.867,0-3.727-0.039-5.594-0.039c0.891-0.469,1.016-1.195,0.969-3.016
- c-0.055-3.031,0.055-6.926,0.215-9.59c-0.902-0.023-1.699,0.012-2.574,0.039c-0.402,0.047-0.711,0.453-0.992,1.16l-0.852,0.355
- L691.01,55.836L691.01,55.836z"/>
-
- <radialGradient id="XMLID_9_" cx="-89.4995" cy="559.8066" r="94.2447" gradientTransform="matrix(0.6875 0 0 0.6652 291.9632 -263.6867)" gradientUnits="userSpaceOnUse">
- <stop offset="0.1124" style="stop-color:#FFFFFF"/>
- <stop offset="0.12" style="stop-color:#F15C49"/>
- <stop offset="0.31" style="stop-color:#4E140E"/>
- <stop offset="0.4772" style="stop-color:#B21F24"/>
- <stop offset="0.5684" style="stop-color:#B21F24"/>
- <stop offset="0.6748" style="stop-color:#F15C49"/>
- <stop offset="0.88" style="stop-color:#4E140E"/>
- </radialGradient>
- <path fill-rule="evenodd" clip-rule="evenodd" fill="url(#XMLID_9_)" d="M236.346,56.355c37.484,0,57.039,24.629,58.791,53.484
- c1.736,28.742-22.246,54.461-51.596,57.543c-35.295,3.699-66.115-20.332-66.115-55.371
- C177.426,81.359,203.895,56.355,236.346,56.355L236.346,56.355z M271.77,113.535c2.146,21.148-5.029,40.781-24.227,45.176
- c-19.643,4.492-40.467-11.613-45.668-38.98c-5.705-30.012,3.725-49.777,22.268-54.637
- C246.108,59.336,268.495,81.25,271.77,113.535L271.77,113.535z"/>
-
- <radialGradient id="XMLID_10_" cx="50.7944" cy="559.8027" r="92.5321" gradientTransform="matrix(0.6794 0 0 0.6652 324.1435 -263.6867)" gradientUnits="userSpaceOnUse">
- <stop offset="0.11" style="stop-color:#FEEE15"/>
- <stop offset="0.305" style="stop-color:#615120"/>
- <stop offset="0.4298" style="stop-color:#B08D2F"/>
- <stop offset="0.5858" style="stop-color:#B38F2F"/>
- <stop offset="0.6794" style="stop-color:#F1E00B"/>
- <stop offset="0.89" style="stop-color:#615120"/>
- </radialGradient>
- <path fill-rule="evenodd" clip-rule="evenodd" fill="url(#XMLID_10_)" d="M363.333,56.355c37.045,0,56.373,24.629,58.104,53.484
- c1.715,28.742-21.988,54.461-50.996,57.543c-34.881,3.699-65.34-20.332-65.34-55.371C305.1,81.359,331.258,56.355,363.333,56.355
- L363.333,56.355z M398.338,113.535c2.125,21.148-4.969,40.781-23.941,45.176c-19.414,4.492-39.992-11.613-45.133-38.98
- c-5.641-30.012,3.68-49.777,22.006-54.637C372.979,59.336,395.104,81.25,398.338,113.535L398.338,113.535z"/>
-
- <radialGradient id="XMLID_11_" cx="397.9761" cy="536.8584" r="115.4805" gradientTransform="matrix(0.6652 0 0 0.6652 404.6628 -255.9006)" gradientUnits="userSpaceOnUse">
- <stop offset="0.08" style="stop-color:#F15C49"/>
- <stop offset="0.0968" style="stop-color:#4E140E"/>
- <stop offset="0.4748" style="stop-color:#B21F24"/>
- <stop offset="0.5756" style="stop-color:#B21F24"/>
- <stop offset="0.6932" style="stop-color:#F15C49"/>
- <stop offset="0.92" style="stop-color:#4E140E"/>
- </radialGradient>
- <path fill-rule="evenodd" clip-rule="evenodd" fill="url(#XMLID_11_)" d="M684.073,88.641c3.609-1.5,3.895-1.762,2.563-5.574
- c-7.629-21.77-36.344-33.523-60.797-23.324c-19.285,8.039-33.25,28.434-33.25,51.246c0,30.734,22.18,58.063,52.32,58.063
- c13.813,0,23.633-1.906,32.383-7.457c1.875-1.738,12.438-10.191,12.539-12.004c0.023-0.418-1.484,0.898-3.781,2.164
- c-6.813,3.586-17.023,4.957-25.023,5.105c-16.203,0.297-29.141-10.742-37.578-23.848c-5.43-8.434-8.938-18.078-9.813-28.434
- c-1.34-15.91,2.547-34.215,20.523-38.707c11.961-2.992,23.289,3.707,27.695,15.23c1.996,5.227,0.789,7.941-4.043,9.938
- l-43.246,18.063l14.746,0.941C646.87,102.762,666.518,95.922,684.073,88.641L684.073,88.641z"/>
-
- <radialGradient id="XMLID_12_" cx="-251.0381" cy="536.7227" r="139.9347" gradientTransform="matrix(0.6652 0 0 0.6652 256.4202 -274.632)" gradientUnits="userSpaceOnUse">
- <stop offset="0.14" style="stop-color:#6584C2"/>
- <stop offset="0.32" style="stop-color:#263573"/>
- <stop offset="0.5648" style="stop-color:#2C50A3"/>
- <stop offset="0.6656" style="stop-color:#6584C2"/>
- <stop offset="0.86" style="stop-color:#263573"/>
- </radialGradient>
- <path fill-rule="evenodd" clip-rule="evenodd" fill="url(#XMLID_12_)" d="M143.196,40.938l16.85-17.18
- C131.444,0.078,82.385-3.027,49.879,13.406C21.606,27.703,1.049,56.098,0.042,87.805c-1.059,33.371,18.338,59.77,38.021,73.047
- c32.492,21.91,88.824,17.031,122.758-0.102l-0.008-3.176l0.004-0.004v-34.973l7.9-9.254h-49.436l-18.309,10.309l35.557-1.055
- c0,9.957,0,20.863,0,30.824c0,4.379,0.057,5.082-7.152,7.406c-10.145,2.668-21.598,3.188-32.063,2.316
- c-35.504-2.961-62.566-31.016-68.979-66.008c-6.082-33.199,9.574-64.605,36.045-77.566c12.928-6.328,28.438-9.297,45.25-3.918
- c10.539,3.375,20.109,9.449,28.449,17.828l-5.809,10.563L143.196,40.938L143.196,40.938z"/>
-
- <radialGradient id="XMLID_13_" cx="190.2485" cy="510.457" r="88.1475" gradientTransform="matrix(0.666 0 0 0.666 353.5035 -242.8212)" gradientUnits="userSpaceOnUse">
- <stop offset="0.08" style="stop-color:#6584C2"/>
- <stop offset="0.248" style="stop-color:#263573"/>
- <stop offset="0.4748" style="stop-color:#6584C2"/>
- <stop offset="0.6596" style="stop-color:#2C50A3"/>
- <stop offset="0.92" style="stop-color:#263573"/>
- </radialGradient>
- <path fill-rule="evenodd" clip-rule="evenodd" fill="url(#XMLID_13_)" d="M507.112,131.16l-29.234,10.438
- c1.09-1.91,0.398-1.254-1.66-0.941c-18.895,2.855-38.363-9.48-42.918-28.121c-2.309-9.461-0.875-19.348,2.727-27.082
- c7.828-16.805,25.23-26.141,44.535-26.141c20.082,0,38.676,0.004,58.363,0.164l-13.805,8.938h-15.715
- c6.641,4.633,11.723,11.313,14.527,18.758c2.988,7.922,3.398,16.707,0.367,24.797C521.44,119.598,515.639,126.168,507.112,131.16
- L507.112,131.16z M504.178,100.457c2.457,14.922-1.332,29.074-14.824,32.805c-13.805,3.82-29.078-6.926-33.988-26.156
- c-5.387-21.09,0.184-34.484,13.191-38.527C483.963,63.789,500.424,77.68,504.178,100.457L504.178,100.457z"/>
-
- <radialGradient id="XMLID_14_" cx="169.6396" cy="660.5957" r="95.1706" gradientTransform="matrix(0.666 0 0 0.666 360.8121 -245.4305)" gradientUnits="userSpaceOnUse">
- <stop offset="0.07" style="stop-color:#6584C2"/>
- <stop offset="0.242" style="stop-color:#263573"/>
- <stop offset="0.4742" style="stop-color:#6584C2"/>
- <stop offset="0.6634" style="stop-color:#2C50A3"/>
- <stop offset="0.93" style="stop-color:#263573"/>
- </radialGradient>
- <path fill-rule="evenodd" clip-rule="evenodd" fill="url(#XMLID_14_)" d="M477.877,141.594l29.234-10.434
- c-4.844,2.84-7.293,6.434-7.563,9.883c-0.789,10.07,11.516,17.391,18.633,22.715c15.563,11.656,21.641,30.773,11.344,49.246
- c-9.84,17.637-33.281,25.504-58.168,25.594c-30.918-0.137-50.418-14.305-51.449-33.586c-1.328-24.922,24.242-36.781,47.344-39.484
- c6.469-0.758,12.25-0.637,17.688-0.254C476.764,159.895,473.706,148.922,477.877,141.594L477.877,141.594z M492.581,171.699
- c2.328,1.695,4.746,3.352,7.234,4.93c13.563,8.586,17.891,19.086,16.785,28.777c-1.328,11.688-12.543,20.902-31.742,22.066
- c-20.496,1.242-48.09-6.875-42.98-33.836c2.719-14.363,21.781-21.781,37.539-22.305
- C483.78,171.191,488.217,171.551,492.581,171.699L492.581,171.699z"/>
- <path fill-rule="evenodd" clip-rule="evenodd" fill="#6B696B" d="M702.94,55.836c0.258,0,0.496,0,0.734,0v-0.004h2.914
- c0.711,0,0.758,0.344,0.996,1.008c1.012,2.809,3.316,9.676,3.34,9.637c0.953-2.594,2.402-6.457,3.523-9.129
- c-0.008-0.309-0.313-0.332-0.707-0.309c-0.523,0-1.043,0-1.566,0c0.008-0.008,0.023-0.016,0.031-0.023
- c-0.016,0.004-0.031,0.012-0.047,0.016c0.164-0.117,0.328-0.238,0.492-0.359c0.363-0.277,0.727-0.559,1.09-0.836
- c0.02,0,0.035,0,0.055,0h0.004c1.488,0,2.695,0,4.188,0l0,0c0.32,0,0.648,0,0.969,0c-0.086,0.199-0.172,0.402-0.258,0.605
- c-0.727,0.457-0.547,1.656-0.48,2.586c0.168,2.43,0.418,4.855,0.629,7.281c0.102,1.16,0.344,2.172,1.156,3.059
- c-0.781,0.223-1.305,0.301-2.352,0.301c-1.688,0-2.156-1.078-2.344-2.961c-0.172-2.629-0.344-5.258-0.516-7.883
- c-1.109,2.777-2.129,5.363-3.148,8.199c-0.219,0.672-0.313,0.742-0.07,1.41l-3.031,1.215l-3.863-11.012
- c-0.254,2.547-0.512,5.852-0.664,8.387c-0.043,1.242,0.141,1.547,2.23,1.652l-1.215,0.707c-1.871,0-1.23-0.039-3.098-0.039
- c0.887-0.609,1.148-1.199,1.227-3.016c0.188-2.797,0.492-6.828,0.84-9.492l-0.027-0.07c-0.762-0.016-1.352-0.129-2.313,0.266
- L702.94,55.836L702.94,55.836z"/>
- </g>
-</g>
-</svg>
diff --git a/o3d/samples/gpu2d/a.svg b/o3d/samples/gpu2d/a.svg
deleted file mode 100644
index aa93f17..0000000
--- a/o3d/samples/gpu2d/a.svg
+++ /dev/null
@@ -1,72 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-
-<svg
- xmlns:dc="http://purl.org/dc/elements/1.1/"
- xmlns:cc="http://creativecommons.org/ns#"
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
- xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
- width="500"
- height="500"
- id="svg3012"
- version="1.1"
- inkscape:version="0.47 r22583"
- sodipodi:docname="a.svg">
- <defs
- id="defs3014">
- <inkscape:perspective
- sodipodi:type="inkscape:persp3d"
- inkscape:vp_x="0 : 526.18109 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_z="744.09448 : 526.18109 : 1"
- inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
- id="perspective3020" />
- </defs>
- <sodipodi:namedview
- id="base"
- pagecolor="#ffffff"
- bordercolor="#666666"
- borderopacity="1.0"
- inkscape:pageopacity="0.0"
- inkscape:pageshadow="2"
- inkscape:zoom="1"
- inkscape:cx="185.77464"
- inkscape:cy="230.99609"
- inkscape:document-units="px"
- inkscape:current-layer="layer1"
- showgrid="false"
- inkscape:window-width="939"
- inkscape:window-height="861"
- inkscape:window-x="723"
- inkscape:window-y="0"
- inkscape:window-maximized="0" />
- <metadata
- id="metadata3017">
- <rdf:RDF>
- <cc:Work
- rdf:about="">
- <dc:format>image/svg+xml</dc:format>
- <dc:type
- rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
- <dc:title></dc:title>
- </cc:Work>
- </rdf:RDF>
- </metadata>
- <g
- inkscape:label="Layer 1"
- inkscape:groupmode="layer"
- id="layer1"
- transform="translate(-189.22536,329.0208)">
- <g
- style="font-size:600px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:start;line-height:125%;writing-mode:lr-tb;text-anchor:start;fill:#000000;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans"
- id="text3078"
- transform="translate(15,9)">
- <path
- d="m 402.88942,-106.96221 c -43.55485,1.7e-4 -73.7306,4.98063 -90.52734,14.941408 -16.79698,9.961078 -25.19541,26.953249 -25.19532,50.976563 -9e-5,19.140705 6.24991,34.3750646 18.75,45.703125 12.69519,11.132855 29.88268,16.699255 51.5625,16.699219 29.88263,3.6e-5 53.80838,-10.546828 71.77735,-31.640625 18.16381,-21.288973 27.24583,-49.511601 27.24609,-84.667969 l 0,-12.011721 -53.61328,0 m 107.51953,-22.26562 0,187.207028 -53.90625,0 0,-49.804687 c -12.30493,19.921905 -27.63695,34.667984 -45.99609,44.238281 -18.35957,9.374996 -40.82049,14.062492 -67.38282,14.0625 -33.59386,-8e-6 -60.35164,-9.374999 -80.27343,-28.125 -19.72661,-18.945274 -29.58988,-44.2382172 -29.58985,-75.878906 -3e-5,-36.91393 12.30464,-64.745936 36.91407,-83.496096 24.80459,-18.7498 61.71861,-28.12479 110.74218,-28.125 l 75.58594,0 0,-5.27344 c -2.6e-4,-24.80445 -8.20338,-43.94505 -24.60937,-57.42187 -16.21116,-13.67159 -39.0627,-20.50752 -68.55469,-20.50781 -18.75015,2.9e-4 -37.01185,2.24638 -54.78516,6.73828 -17.77353,4.49247 -34.86336,11.23074 -51.26953,20.21484 l 0,-49.80469 c 19.72648,-7.61686 38.86709,-13.28092 57.42188,-16.99218 18.55455,-3.90592 36.62094,-5.85904 54.19921,-5.85938 47.46072,3.4e-4 82.90991,12.30501 106.34766,36.91406 23.4372,24.60965 35.15594,61.9143 35.15625,111.91407"
- id="path3083" />
- </g>
- </g>
-</svg>
diff --git a/o3d/samples/gpu2d/basic.html b/o3d/samples/gpu2d/basic.html
deleted file mode 100644
index 8068503..0000000
--- a/o3d/samples/gpu2d/basic.html
+++ /dev/null
@@ -1,229 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<!--
- Sample demonstrating basic 2D vector curve rendering in 3D.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-O3D GPU2D Sample: Basic Vector Shapes
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.cameracontroller');
-o3djs.require('o3djs.gpu2d');
-o3djs.require('o3djs.io');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.util');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = createClients;
-window.onunload = unload;
-
-// Globals
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_o3dElement;
-var g_finished = false; // for selenium testing.
-var g_clientWidth;
-var g_clientHeight;
-var g_path;
-var g_cameraController;
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
-
- // Clear the mouse events.
- onMouseUp();
- }
-}
-
-function createClients() {
- o3djs.util.makeClients(init);
-}
-
-function init(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3dElement = o3dElement;
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Store the size of the plugin, so that we can adjust coordinates in
- // full-screen mode. This is necessary because we're not adjusting the aspect
- // ratio; we'd rather that the canvas filled the available area, rather than
- // staying a fixed size or aspect ratio.
- g_clientWidth = g_o3dElement.clientWidth;
- g_clientHeight = g_o3dElement.clientHeight;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set the background color to light gray.
- g_viewInfo.clearBuffer.clearColor = [0.8, 0.8, 0.8, 1];
-
- // Set up our CameraController.
- g_cameraController = o3djs.cameracontroller.createCameraController(
- [0, 0, 0], // centerPos
- 500, // backpedal
- 0, // heightAngle
- 0, // rotationAngle
- g_math.degToRad(15), // fieldOfViewAngle
- updateViewAndProjectionMatrices); // opt_onChange
- g_cameraController.distancePerUnit = 100.0;
- updateViewAndProjectionMatrices();
-
- // Set up event handlers for mouse interaction.
- o3djs.event.addEventListener(o3dElement, 'mousedown', onMouseDown);
- o3djs.event.addEventListener(o3dElement, 'mousemove', onMouseMove);
- o3djs.event.addEventListener(o3dElement, 'mouseup', onMouseUp);
-
- // Create a Path.
- g_path = o3djs.gpu2d.createPath(g_pack, g_viewInfo.zOrderedDrawList);
- g_client.root.addShape(g_path.shape);
-
- // Set the fill of the path.
- g_path.setFill(o3djs.gpu2d.createColor(g_pack, 0.8, 0.0, 0.3, 1.0));
-
- // Draw something on the path.
- g_path.moveTo(25.0, -50.0);
- g_path.cubicTo(75.0, 50.0, 125.0, 25.0, 175.0, 50.0);
- g_path.cubicTo(125.0, -50.0, 75.0, -25.0, 25.0, -50.0);
-
- g_path.moveTo(-25.0, -50.0);
- g_path.cubicTo(-75.0, 50.0, -125.0, 25.0, -175.0, 50.0);
- g_path.cubicTo(-125.0, -50.0, -75.0, -25.0, -25.0, -50.0);
- g_path.close();
-
- // Force an update.
- g_path.update();
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Event handler that gets called when a mouse click takes place in
- * the O3D element. It changes the state of the camera controller
- * based on which modifier keys are pressed.
- * @param {!Event} e The mouse down event.
- */
-function onMouseDown(e) {
- if (e.button == 0) {
- if (!e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.MOVE_CENTER_IN_VIEW_PLANE, e.x, e.y);
- } else if (e.metaKey || e.altKey) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.SPIN_ABOUT_CENTER, e.x, e.y);
- } else if (!e.shiftKey && e.ctrlKey) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.DOLLY_IN_OUT, e.x, e.y);
- } else if (e.shiftKey && !e.ctrlKey) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.ZOOM_IN_OUT, e.x, e.y);
- } else if (e.shiftKey && e.ctrlKey) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.DOLLY_ZOOM, e.x, e.y);
- }
- }
-}
-
-/**
- * Event handler that gets called when a mouse move event takes place
- * in the O3D element. It tells the camera controller that the mouse
- * has moved.
- * @param {!Event} e The mouse move event.
- */
-function onMouseMove(e) {
- g_cameraController.mouseMoved(e.x, e.y);
-}
-
-/**
- * Event handler that gets called when a mouse up event takes place in
- * the O3D element. It tells the camera controller that the mouse has
- * been released.
- * @param {!Event} e The mouse up event.
- */
-function onMouseUp(e) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.NONE, e.x, e.y);
-}
-
-/**
- * Updates the view and projection matrices.
- */
-function updateViewAndProjectionMatrices() {
- g_viewInfo.drawContext.view = g_cameraController.calculateViewMatrix();
-
- // Set up a perspective transformation for the projection.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_cameraController.fieldOfViewAngle * 2, // Frustum angle.
- g_o3dElement.clientWidth / g_o3dElement.clientHeight, // Aspect ratio.
- 1, // Near plane.
- 5000); // Far plane.
-}
-</script>
-</head>
-
-<body>
-<h1>O3D GPU2D Sample: Basic Vector Shapes</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-
-<p><p>See above for output.
-</body>
-</html>
diff --git a/o3d/samples/gpu2d/butterfly.svg b/o3d/samples/gpu2d/butterfly.svg
deleted file mode 100644
index f2ae583..0000000
--- a/o3d/samples/gpu2d/butterfly.svg
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0"?>
-<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
- "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
-<!-- This is a slightly modified version of a sample that shipped with
- JASC's WebDraw (www.jasc.com) -->
-<svg xmlns="http://www.w3.org/2000/svg"
- xmlns:xlink="http://www.w3.org/1999/xlink">
- <g transform="scale(3)">
- <path style="stroke-width:1;fill:rgb(246,127,0);stroke:none"
- d="M204.33 139.83 C196.33 133.33 206.68 132.82 206.58 132.58 C192.33 97.08 169.35 81.41 167.58 80.58 C162.12 78.02 159.48 78.26 160.45 76.97 C161.41 75.68 167.72 79.72 168.58 80.33 C193.83 98.33 207.58 132.33 207.58 132.33 C207.58 132.33 209.33 133.33 209.58 132.58 C219.58 103.08 239.58 87.58 246.33 81.33 C253.08 75.08 256.63 74.47 247.33 81.58 C218.58 103.58 210.34 132.23 210.83 132.33 C222.33 134.83 211.33 140.33 211.83 139.83 C214.85 136.81 214.83 145.83 214.83 145.83 C214.83 145.83 231.83 110.83 298.33 66.33 C302.43 63.59 445.83 -14.67 395.83 80.83 C393.24 85.79 375.83 105.83 375.83 105.83 C375.83 105.83 377.33 114.33 371.33 121.33 C370.3 122.53 367.83 134.33 361.83 140.83 C360.14 142.67 361.81 139.25 361.83 140.83 C362.33 170.83 337.76 170.17 339.33 170.33 C348.83 171.33 350.19 183.66 350.33 183.83 C355.83 190.33 353.83 191.83 355.83 194.83 C366.63 211.02 355.24 210.05 356.83 212.83 C360.83 219.83 355.99 222.72 357.33 224.83 C360.83 230.33 354.75 233.84 354.83 235.33 C355.33 243.83 349.67 240.73 349.83 244.33 C350.33 255.33 346.33 250.83 343.83 254.83 C336.33 266.83 333.46 262.38 332.83 263.83 C329.83 270.83 325.81 269.15 324.33 270.83 C320.83 274.83 317.33 274.83 315.83 276.33 C308.83 283.33 304.86 278.39 303.83 278.83 C287.83 285.83 280.33 280.17 277.83 280.33 C270.33 280.83 271.48 279.67 269.33 277.83 C237.83 250.83 219.33 211.83 215.83 206.83 C214.4 204.79 211.35 193.12 212.33 195.83 C214.33 201.33 213.33 250.33 207.83 250.33 C202.33 250.33 201.83 204.33 205.33 195.83 C206.43 193.16 204.4 203.72 201.79 206.83 C196.33 213.33 179.5 250.83 147.59 277.83 C145.42 279.67 146.58 280.83 138.98 280.33 C136.46 280.17 128.85 285.83 112.65 278.83 C111.61 278.39 107.58 283.33 100.49 276.33 C98.97 274.83 95.43 274.83 91.88 270.83 C90.39 269.15 86.31 270.83 83.27 263.83 C82.64 262.38 79.73 266.83 72.13 254.83 C69.6 250.83 65.54 255.33 66.05 244.33 C66.22 240.73 60.48 243.83 60.99 235.33 C61.08 233.84 54.91 230.33 58.45 224.83 C59.81 222.72 54.91 219.83 58.96 212.83 C60.57 210.05 49.04 211.02 59.97 194.83 C62 191.83 59.97 190.33 65.54 183.83 C65.69 183.66 67.06 171.33 76.69 170.33 C78.28 170.17 53.39 170.83 53.9 140.83 C53.92 139.25 55.61 142.67 53.9 140.83 C47.82 134.33 45.32 122.53 44.27 121.33 C38.19 114.33 39.71 105.83 39.71 105.83 C39.71 105.83 22.08 85.79 19.46 80.83 C-31.19 -14.67 114.07 63.59 118.22 66.33 C185.58 110.83 202 145.83 202 145.83 C202 145.83 202.36 143.28 203 141.83 C203.64 140.39 204.56 140.02 204.33 139.83 z"/>
- <path style="stroke-width:1;fill:rgb(0,0,0);stroke:none"
- d="M203.62 139.62 C195.62 133.12 205.96 132.6 205.87 132.37 C191.62 96.87 168.64 81.2 166.87 80.37 C161.41 77.81 158.77 78.05 159.73 76.76 C160.69 75.47 167.01 79.51 167.87 80.12 C193.12 98.12 206.87 132.12 206.87 132.12 C206.87 132.12 208.62 133.12 208.87 132.37 C218.87 102.87 238.87 87.37 245.62 81.12 C252.37 74.87 255.92 74.26 246.62 81.37 C217.87 103.37 209.63 132.01 210.12 132.12 C221.62 134.62 210.62 140.12 211.12 139.62 C214.14 136.6 214.12 145.62 214.12 145.62 C214.12 145.62 231.12 110.62 297.62 66.12 C301.71 63.38 445.12 -14.88 395.12 80.62 C392.53 85.57 375.12 105.62 375.12 105.62 C375.12 105.62 376.62 114.12 370.62 121.12 C369.59 122.32 367.12 134.12 361.12 140.62 C359.43 142.46 361.09 139.04 361.12 140.62 C361.62 170.62 337.05 169.96 338.62 170.12 C348.12 171.12 349.47 183.45 349.62 183.62 C355.12 190.12 353.12 191.62 355.12 194.62 C365.91 210.81 354.53 209.84 356.12 212.62 C360.12 219.62 355.28 222.51 356.62 224.62 C360.12 230.12 354.03 233.62 354.12 235.12 C354.62 243.62 348.96 240.52 349.12 244.12 C349.62 255.12 345.62 250.62 343.12 254.62 C335.62 266.62 332.74 262.17 332.12 263.62 C329.12 270.62 325.09 268.94 323.62 270.62 C320.12 274.62 316.62 274.62 315.12 276.12 C308.12 283.12 304.15 278.17 303.12 278.62 C287.12 285.62 279.62 279.95 277.12 280.12 C269.62 280.62 270.77 279.46 268.62 277.62 C237.12 250.62 218.62 211.62 215.12 206.62 C213.69 204.57 210.63 192.91 211.62 195.62 C213.62 201.12 212.62 250.12 207.12 250.12 C201.62 250.12 201.12 204.12 204.62 195.62 C205.72 192.95 203.69 203.5 201.08 206.62 C195.62 213.12 178.79 250.62 146.88 277.62 C144.71 279.46 145.87 280.62 138.27 280.12 C135.75 279.95 128.14 285.62 111.94 278.62 C110.9 278.17 106.87 283.12 99.78 276.12 C98.26 274.62 94.72 274.62 91.17 270.62 C89.68 268.94 85.6 270.62 82.56 263.62 C81.93 262.17 79.01 266.62 71.42 254.62 C68.88 250.62 64.83 255.12 65.34 244.12 C65.51 240.52 59.77 243.62 60.27 235.12 C60.36 233.62 54.2 230.12 57.74 224.62 C59.1 222.51 54.2 219.62 58.25 212.62 C59.86 209.84 48.33 210.81 59.26 194.62 C61.29 191.62 59.26 190.12 64.83 183.62 C64.98 183.45 66.35 171.12 75.98 170.12 C77.57 169.96 52.68 170.62 53.18 140.62 C53.21 139.04 54.9 142.46 53.18 140.62 C47.11 134.12 44.6 122.32 43.56 121.12 C37.48 114.12 39 105.62 39 105.62 C39 105.62 21.37 85.57 18.74 80.62 C-31.9 -14.88 113.36 63.38 117.51 66.12 C184.87 110.62 201.29 145.62 201.29 145.62 C201.29 145.62 201.65 143.07 202.29 141.62 C202.93 140.18 203.85 139.81 203.62 139.62 zM242.12 153.12 C245.16 153.02 251.35 156.17 255.12 155.12 C280.55 148.06 328.44 154.56 331.62 155.62 C343.62 159.62 351.62 131.12 326.12 131.12 C294.59 131.12 301.12 129.12 280.12 126.12 C278.34 125.87 252.6 135.42 228.62 149.12 C225.12 151.12 227.12 153.62 242.12 153.12 zM223.12 148.12 C225.66 148.4 238.12 139.62 277.12 124.12 C279.49 123.18 279.62 118.12 300.62 108.62 C301.99 108 300.12 104.62 314.62 92.62 C321.79 86.69 297.12 87.62 291.62 88.62 C286.12 89.62 272.62 100.62 272.62 100.62 C272.62 100.62 287.8 88.55 282.62 90.12 C271.12 93.62 241.12 126.62 231.12 140.62 C221.12 154.62 247.62 116.62 254.12 110.62 C260.62 104.62 204.62 146.12 223.12 148.12 zM335.62 128.62 C350.14 131.53 348.62 110.12 341.12 109.12 C329.55 107.58 307.51 108.3 301.12 110.62 C284.62 116.62 280.29 122.65 281.62 123.12 C310.12 133.12 330.62 127.62 335.62 128.62 zM335.12 106.62 C341.04 107.36 351.12 109.62 351.62 101.62 C351.87 97.6 365.62 104.62 368.62 105.12 C371.1 105.53 358.12 100.33 353.62 97.12 C350.12 94.62 349.51 91.76 349.12 91.62 C317.12 80.12 303.62 107.12 303.62 107.12 C303.62 107.12 331.12 106.12 335.12 106.62 zM400.62 62.62 C395.62 54.62 386.66 57.08 383.62 53.62 C369.12 37.12 335.54 58.28 363.12 56.12 C395.12 53.62 401.21 63.57 400.62 62.62 zM376.62 66.62 C390.13 66.62 396.12 72.62 395.12 71.62 C388.12 64.62 382.12 66.12 380.62 64.12 C371.7 52.23 345.12 64.62 347.12 67.62 C349.12 70.62 373.12 66.62 376.62 66.62 zM330.12 76.12 C309.12 81.12 318.12 88.62 320.62 88.12 C340.05 84.24 334.5 75.08 330.12 76.12 zM340.62 52.12 C331.12 53.12 330.48 70.43 335.12 67.12 C342.12 62.12 350.12 51.12 340.62 52.12 zM315.62 75.62 C329.62 70.12 319.12 67.62 314.62 68.12 C310.12 68.62 306.79 75.45 308.12 78.12 C311.12 84.12 312.91 76.69 315.62 75.62 zM359.62 121.12 C364.12 118.62 358.62 112.62 354.62 115.12 C350.62 117.62 355.12 123.62 359.62 121.12 zM350.12 78.62 C361.89 90.39 366.62 84.12 369.12 83.12 C377.24 79.87 386.12 88.62 384.62 87.12 C377.34 79.84 372.62 81.12 371.62 79.62 C364.01 68.2 352.66 75.44 350.12 75.62 C343.12 76.12 334.43 81.03 337.62 80.12 C341.12 79.12 348.62 77.12 350.12 78.62 zM383.62 44.12 C390.62 39.12 381.4 37.85 379.62 38.12 C373.12 39.12 376.62 49.12 383.62 44.12 zM224.62 181.12 C230.12 187.62 291.62 285.12 282.12 252.62 C280.83 248.2 285.62 266.12 291.12 256.12 C292.66 253.32 301.27 253.03 274.62 208.62 C273.12 206.12 252.62 198.12 232.12 175.62 C229.02 172.21 220.05 175.72 224.62 181.12 zM280.12 215.62 C284.62 222.62 295.81 246.07 296.62 249.62 C299.12 260.62 306.12 248.12 307.62 248.62 C320.78 253.01 311.12 241.12 310.12 238.12 C300.95 210.62 279.62 213.12 279.62 213.12 C279.62 213.12 275.62 208.62 280.12 215.62 zM253.62 256.12 C266.26 274.09 271.12 267.12 273.62 265.12 C281.32 258.96 232.34 196.14 229.12 192.12 C225.12 187.12 225.12 215.62 253.62 256.12 zM300.12 219.12 C306.62 224.12 313.86 245.19 317.62 244.62 C327.62 243.12 321.62 234.62 324.12 236.12 C326.62 237.62 331.62 234.95 330.12 232.12 C317.62 208.62 298.12 216.12 298.12 216.12 C298.12 216.12 293.62 214.12 300.12 219.12 zM235.62 168.62 C216.12 168.62 282.12 222.62 301.12 212.12 C305.06 209.94 296.12 208.62 297.62 197.12 C297.9 195.02 284.12 191.12 284.12 178.12 C284.12 173.88 276.2 172.12 251.12 172.12 C246.62 172.12 256.03 168.62 235.62 168.62 zM307.62 213.62 C325.89 215.65 330.23 229.8 332.62 228.12 C361.12 208.12 309.89 199.96 300.62 201.12 C296.62 201.62 303.12 213.12 307.62 213.62 zM238.62 164.12 C242.12 166.62 254.12 176.62 292.62 168.12 C294.09 167.8 263.62 167.62 259.62 166.62 C255.62 165.62 236.25 162.43 238.62 164.12 zM305.12 198.62 C342.62 207.62 332.72 201.36 334.12 200.62 C342.62 196.12 333.33 195.23 334.62 193.62 C338.83 188.36 327.62 185.12 304.12 182.62 C298.56 182.03 287.54 179.27 287.12 180.12 C283.62 187.12 300.33 197.47 305.12 198.62 zM311.12 182.12 C343.62 187.62 323.23 177.43 323.62 177.12 C335.12 168.12 297.12 168.12 297.12 168.12 C297.12 168.12 280.79 172 281.12 172.62 C285.62 181.12 307.15 181.45 311.12 182.12 zM249.62 253.62 C249.62 253.62 220.62 207.12 226.62 188.12 C227.83 184.31 213.62 165.62 220.12 197.12 C220.22 197.61 218.89 190.43 216.62 187.12 C214.35 183.81 211.18 184.9 213.12 194.62 C218.01 219.05 249.62 253.62 249.62 253.62 zM289.12 83.62 C296.62 81.62 293.12 79.12 288.62 78.12 C284.12 77.12 281.62 85.62 289.12 83.62 zM187.4 149.12 C163.12 135.42 137.04 125.87 135.23 126.12 C113.96 129.12 120.58 131.12 88.64 131.12 C62.81 131.12 70.91 159.62 83.07 155.62 C86.29 154.56 134.8 148.06 160.56 155.12 C164.37 156.17 170.65 153.02 173.73 153.12 C188.92 153.62 190.95 151.12 187.4 149.12 zM161.57 110.62 C168.15 116.62 195 154.62 184.87 140.62 C174.74 126.62 144.35 93.62 132.7 90.12 C127.46 88.55 142.83 100.62 142.83 100.62 C142.83 100.62 129.16 89.62 123.58 88.62 C118.01 87.62 93.03 86.69 100.29 92.62 C114.97 104.62 113.08 108 114.47 108.62 C135.74 118.12 135.87 123.18 138.27 124.12 C177.78 139.62 190.4 148.4 192.97 148.12 C211.71 146.12 154.99 104.62 161.57 110.62 zM133.71 123.12 C135.07 122.65 130.68 116.62 113.96 110.62 C107.49 108.3 85.16 107.58 73.44 109.12 C65.85 110.12 64.31 131.53 79.01 128.62 C84.08 127.62 104.84 133.12 133.71 123.12 zM111.43 107.12 C111.43 107.12 97.75 80.12 65.34 91.62 C64.95 91.76 64.33 94.62 60.78 97.12 C56.23 100.33 43.08 105.53 45.59 105.12 C48.63 104.62 62.55 97.6 62.81 101.62 C63.31 109.62 73.53 107.36 79.52 106.62 C83.57 106.12 111.43 107.12 111.43 107.12 zM51.16 56.12 C79.09 58.28 45.08 37.12 30.39 53.62 C27.31 57.08 18.24 54.62 13.17 62.62 C12.57 63.57 18.74 53.62 51.16 56.12 zM67.37 67.62 C69.39 64.62 42.47 52.23 33.43 64.12 C31.91 66.12 25.83 64.62 18.74 71.62 C17.73 72.62 23.8 66.62 37.48 66.62 C41.03 66.62 65.34 70.62 67.37 67.62 zM84.59 76.12 C105.86 81.12 96.74 88.62 94.21 88.12 C74.53 84.24 80.15 75.08 84.59 76.12 zM79.52 67.12 C84.22 70.43 83.57 53.12 73.95 52.12 C64.33 51.12 72.43 62.12 79.52 67.12 zM106.87 78.12 C108.22 75.45 104.84 68.62 100.29 68.12 C95.73 67.62 85.09 70.12 99.27 75.62 C102.02 76.69 103.83 84.12 106.87 78.12 zM59.77 115.12 C55.72 112.62 50.14 118.62 54.7 121.12 C59.26 123.62 63.82 117.62 59.77 115.12 zM76.99 80.12 C80.22 81.03 71.42 76.12 64.33 75.62 C61.75 75.44 50.26 68.2 42.55 79.62 C41.53 81.12 36.75 79.84 29.38 87.12 C27.86 88.62 36.85 79.87 45.08 83.12 C47.61 84.12 52.41 90.39 64.33 78.62 C65.85 77.12 73.44 79.12 76.99 80.12 zM34.44 38.12 C32.64 37.85 23.3 39.12 30.39 44.12 C37.48 49.12 41.03 39.12 34.44 38.12 zM183.86 175.62 C163.09 198.12 142.32 206.12 140.8 208.62 C113.81 253.03 122.53 253.32 124.09 256.12 C129.66 266.12 134.52 248.2 133.21 252.62 C123.58 285.12 185.88 187.62 191.45 181.12 C196.08 175.72 187 172.21 183.86 175.62 zM135.74 213.12 C135.74 213.12 114.13 210.62 104.84 238.12 C103.83 241.12 94.05 253.01 107.38 248.62 C108.9 248.12 115.99 260.62 118.52 249.62 C119.34 246.07 130.68 222.62 135.23 215.62 C139.79 208.62 135.74 213.12 135.74 213.12 zM186.89 192.12 C183.64 196.14 134.02 258.96 141.82 265.12 C144.35 267.12 149.27 274.09 162.08 256.12 C190.95 215.62 190.95 187.12 186.89 192.12 zM117 216.12 C117 216.12 97.25 208.62 84.59 232.12 C83.06 234.95 88.13 237.62 90.66 236.12 C93.2 234.62 87.12 243.12 97.25 244.62 C101.06 245.19 108.39 224.12 114.97 219.12 C121.56 214.12 117 216.12 117 216.12 zM164.61 172.12 C139.2 172.12 131.18 173.88 131.18 178.12 C131.18 191.12 117.23 195.02 117.51 197.12 C119.03 208.62 109.97 209.94 113.96 212.12 C133.21 222.62 200.06 168.62 180.31 168.62 C159.64 168.62 169.17 172.12 164.61 172.12 zM114.47 201.12 C105.08 199.96 53.18 208.12 82.05 228.12 C84.47 229.8 88.87 215.65 107.38 213.62 C111.94 213.12 118.52 201.62 114.47 201.12 zM156 166.62 C151.95 167.62 121.09 167.8 122.57 168.12 C161.57 176.62 173.73 166.62 177.27 164.12 C179.67 162.43 160.05 165.62 156 166.62 zM128.14 180.12 C127.71 179.27 116.55 182.03 110.92 182.62 C87.12 185.12 75.76 188.36 80.03 193.62 C81.33 195.23 71.92 196.12 80.53 200.62 C81.95 201.36 71.92 207.62 109.91 198.62 C114.76 197.47 131.69 187.12 128.14 180.12 zM134.22 172.62 C134.56 172 118.01 168.12 118.01 168.12 C118.01 168.12 79.52 168.12 91.17 177.12 C91.57 177.43 70.91 187.62 103.83 182.12 C107.86 181.45 129.66 181.12 134.22 172.62 zM203.1 194.62 C205.07 184.9 201.85 183.81 199.56 187.12 C197.26 190.43 195.91 197.61 196.01 197.12 C202.6 165.62 188.21 184.31 189.43 188.12 C195.5 207.12 166.13 253.62 166.13 253.62 C166.13 253.62 198.15 219.05 203.1 194.62 zM126.62 78.12 C122.06 79.12 118.52 81.62 126.12 83.62 C133.71 85.62 131.18 77.12 126.62 78.12 z"/>
- <path style="stroke-width:1;fill:rgb(255,246,227);stroke:none"
- d="M363.73 85.73 C359.27 86.29 355.23 86.73 354.23 81.23 C353.23 75.73 355.73 73.73 363.23 75.73 C370.73 77.73 375.73 84.23 363.73 85.73 zM327.23 89.23 C327.23 89.23 308.51 93.65 325.73 80.73 C333.73 74.73 334.23 79.73 334.73 82.73 C335.48 87.2 327.23 89.23 327.23 89.23 zM384.23 48.73 C375.88 47.06 376.23 42.23 385.23 40.23 C386.7 39.91 389.23 49.73 384.23 48.73 zM389.23 48.73 C391.73 48.23 395.73 49.23 396.23 52.73 C396.73 56.23 392.73 58.23 390.23 56.23 C387.73 54.23 386.73 49.23 389.23 48.73 zM383.23 59.73 C385.73 58.73 393.23 60.23 392.73 63.23 C392.23 66.23 386.23 66.73 383.73 65.23 C381.23 63.73 380.73 60.73 383.23 59.73 zM384.23 77.23 C387.23 74.73 390.73 77.23 391.73 78.73 C392.73 80.23 387.73 82.23 386.23 82.73 C384.73 83.23 381.23 79.73 384.23 77.23 zM395.73 40.23 C395.73 40.23 399.73 40.23 398.73 41.73 C397.73 43.23 394.73 43.23 394.73 43.23 zM401.73 49.23 C401.73 49.23 405.73 49.23 404.73 50.73 C403.73 52.23 400.73 52.23 400.73 52.23 zM369.23 97.23 C369.23 97.23 374.23 99.23 373.23 100.73 C372.23 102.23 370.73 104.73 367.23 101.23 C363.73 97.73 369.23 97.23 369.23 97.23 zM355.73 116.73 C358.73 114.23 362.23 116.73 363.23 118.23 C364.23 119.73 359.23 121.73 357.73 122.23 C356.23 122.73 352.73 119.23 355.73 116.73 zM357.73 106.73 C360.73 104.23 363.23 107.73 364.23 109.23 C365.23 110.73 361.23 111.73 359.73 112.23 C358.23 112.73 354.73 109.23 357.73 106.73 zM340.73 73.23 C337.16 73.43 331.23 71.73 340.23 65.73 C348.55 60.19 348.23 61.73 348.73 64.73 C349.48 69.2 344.3 73.04 340.73 73.23 zM310.23 82.23 C310.23 82.23 306.73 79.23 313.73 73.23 C321.33 66.73 320.23 69.23 320.73 72.23 C321.48 76.7 310.23 82.23 310.23 82.23 zM341.23 55.73 C341.23 55.73 347.23 54.73 346.23 56.23 C345.23 57.73 342.73 63.23 339.23 59.73 C335.73 56.23 341.23 55.73 341.23 55.73 zM374.73 86.23 C376.11 86.23 377.23 87.36 377.23 88.73 C377.23 90.11 376.11 91.23 374.73 91.23 C373.36 91.23 372.23 90.11 372.23 88.73 C372.23 87.36 373.36 86.23 374.73 86.23 zM369.73 110.73 C371.11 110.73 372.23 111.86 372.23 113.23 C372.23 114.61 371.11 115.73 369.73 115.73 C368.36 115.73 367.23 114.61 367.23 113.23 C367.23 111.86 368.36 110.73 369.73 110.73 zM365.73 120.73 C367.11 120.73 368.23 121.86 368.23 123.23 C368.23 124.61 367.11 125.73 365.73 125.73 C364.36 125.73 363.23 124.61 363.23 123.23 C363.23 121.86 364.36 120.73 365.73 120.73 zM349.73 127.23 C351.11 127.23 352.23 128.36 352.23 129.73 C352.23 131.11 351.11 132.23 349.73 132.23 C348.36 132.23 347.23 131.11 347.23 129.73 C347.23 128.36 348.36 127.23 349.73 127.23 zM358.23 128.73 C359.61 128.73 362.23 130.86 362.23 132.23 C362.23 133.61 359.61 133.73 358.23 133.73 C356.86 133.73 355.73 132.61 355.73 131.23 C355.73 129.86 356.86 128.73 358.23 128.73 zM382.23 89.73 C383.61 89.73 384.73 90.86 384.73 92.23 C384.73 93.61 383.61 94.73 382.23 94.73 C380.86 94.73 379.73 93.61 379.73 92.23 C379.73 90.86 380.86 89.73 382.23 89.73 zM395.73 66.23 C397.11 66.23 398.23 67.36 398.23 68.73 C398.23 70.11 397.11 71.23 395.73 71.23 C394.36 71.23 393.23 70.11 393.23 68.73 C393.23 67.36 394.36 66.23 395.73 66.23 zM300.73 74.23 C303.05 75.16 314.23 67.73 310.73 66.73 C307.23 65.73 298.23 73.23 300.73 74.23 zM319.73 61.23 C322.23 61.73 329.73 58.73 326.23 57.73 C322.73 56.73 317.09 60.71 319.73 61.23 zM271.73 91.73 C277.23 88.73 292.73 81.23 285.23 82.23 C277.73 83.23 267.01 94.31 271.73 91.73 zM364.23 42.23 C366.73 42.73 374.23 39.73 370.73 38.73 C367.23 37.73 361.59 41.71 364.23 42.23 zM292.23 78.73 C294.73 79.23 299.73 76.73 296.23 75.73 C292.73 74.73 289.59 78.21 292.23 78.73 zM355.23 141.23 C356.61 141.23 357.73 142.86 357.73 144.23 C357.73 145.61 357.11 145.73 355.73 145.73 C354.36 145.73 353.23 144.61 353.23 143.23 C353.23 141.86 353.86 141.23 355.23 141.23 zM347.73 140.73 C349.11 140.73 351.23 141.36 351.23 142.73 C351.23 144.11 348.61 143.73 347.23 143.73 C345.86 143.73 344.73 142.61 344.73 141.23 C344.73 139.86 346.36 140.73 347.73 140.73 zM349.73 155.23 C351.11 155.23 353.73 157.36 353.73 158.73 C353.73 160.11 351.11 160.23 349.73 160.23 C348.36 160.23 347.23 159.11 347.23 157.73 C347.23 156.36 348.36 155.23 349.73 155.23 zM337.73 175.73 C341.73 174.73 341.73 176.73 342.73 180.23 C343.73 183.73 350.8 195.11 339.23 181.23 C336.73 178.23 333.73 176.73 337.73 175.73 zM349.73 187.73 C351.11 187.73 352.23 188.86 352.23 190.23 C352.23 191.61 351.11 192.73 349.73 192.73 C348.36 192.73 347.23 191.61 347.23 190.23 C347.23 188.86 348.36 187.73 349.73 187.73 zM352.23 196.73 C353.61 196.73 354.73 197.86 354.73 199.23 C354.73 200.61 353.61 201.73 352.23 201.73 C350.86 201.73 349.73 200.61 349.73 199.23 C349.73 197.86 350.86 196.73 352.23 196.73 zM352.4 205.73 C353.77 205.73 355.73 208.86 355.73 210.23 C355.73 211.61 354.61 212.73 353.23 212.73 C351.86 212.73 349.07 211.11 349.07 209.73 C349.07 208.36 351.02 205.73 352.4 205.73 zM353.73 221.73 C355.11 221.73 354.73 221.86 354.73 223.23 C354.73 224.61 354.61 223.73 353.23 223.73 C351.86 223.73 352.23 224.61 352.23 223.23 C352.23 221.86 352.36 221.73 353.73 221.73 zM340.23 188.73 C341.61 188.73 341.23 188.86 341.23 190.23 C341.23 191.61 341.11 190.73 339.73 190.73 C338.36 190.73 338.73 191.61 338.73 190.23 C338.73 188.86 338.86 188.73 340.23 188.73 zM343.23 201.23 C344.61 201.23 344.23 201.36 344.23 202.73 C344.23 204.11 344.44 207.73 343.07 207.73 C341.69 207.73 341.73 204.11 341.73 202.73 C341.73 201.36 341.86 201.23 343.23 201.23 zM346.73 215.23 C348.11 215.23 347.73 215.36 347.73 216.73 C347.73 218.11 347.61 217.23 346.23 217.23 C344.86 217.23 345.23 218.11 345.23 216.73 C345.23 215.36 345.36 215.23 346.73 215.23 zM340.57 228.73 C341.94 228.73 341.73 228.86 341.73 230.23 C341.73 231.61 341.44 230.73 340.07 230.73 C338.69 230.73 339.23 231.61 339.23 230.23 C339.23 228.86 339.19 228.73 340.57 228.73 zM349.4 232.07 C350.77 232.07 352.07 234.02 352.07 235.4 C352.07 236.77 349.11 239.23 347.73 239.23 C346.36 239.23 346.73 240.11 346.73 238.73 C346.73 237.36 348.02 232.07 349.4 232.07 zM343.73 246.4 C345.11 246.4 347.4 246.02 347.4 247.4 C347.4 248.77 344.11 251.23 342.73 251.23 C341.36 251.23 341.73 252.11 341.73 250.73 C341.73 249.36 342.36 246.4 343.73 246.4 zM335.23 239.23 C336.61 239.23 336.23 239.36 336.23 240.73 C336.23 242.11 336.11 241.23 334.73 241.23 C333.36 241.23 333.73 242.11 333.73 240.73 C333.73 239.36 333.86 239.23 335.23 239.23 zM332.73 258.4 C334.11 258.4 335.4 260.02 335.4 261.4 C335.4 262.77 333.11 262.23 331.73 262.23 C330.36 262.23 330.73 263.11 330.73 261.73 C330.73 260.36 331.36 258.4 332.73 258.4 zM324.4 263.73 C325.77 263.73 325.07 265.36 325.07 266.73 C325.07 268.11 320.11 271.23 318.73 271.23 C317.36 271.23 317.73 272.11 317.73 270.73 C317.73 269.36 323.02 263.73 324.4 263.73 zM325.23 247.73 C326.61 247.73 326.23 247.86 326.23 249.23 C326.23 250.61 326.11 249.73 324.73 249.73 C323.36 249.73 323.73 250.61 323.73 249.23 C323.73 247.86 323.86 247.73 325.23 247.73 zM313.23 256.23 C314.61 256.23 319.07 258.02 319.07 259.4 C319.07 260.77 313.44 263.07 312.07 263.07 C310.69 263.07 309.73 260.77 309.73 259.4 C309.73 258.02 311.86 256.23 313.23 256.23 zM300.23 260.73 C301.61 260.73 301.23 260.86 301.23 262.23 C301.23 263.61 301.11 262.73 299.73 262.73 C298.36 262.73 298.73 263.61 298.73 262.23 C298.73 260.86 298.86 260.73 300.23 260.73 zM308.23 272.73 C309.61 272.73 309.23 272.86 309.23 274.23 C309.23 275.61 309.11 274.73 307.73 274.73 C306.36 274.73 306.73 275.61 306.73 274.23 C306.73 272.86 306.86 272.73 308.23 272.73 zM305.23 273.73 C306.61 273.73 306.23 273.86 306.23 275.23 C306.23 276.61 306.11 275.73 304.73 275.73 C303.36 275.73 303.73 276.61 303.73 275.23 C303.73 273.86 303.86 273.73 305.23 273.73 zM293.73 274.07 C294.65 274.07 295.73 275.48 295.73 276.4 C295.73 277.32 295.65 276.73 294.73 276.73 C293.82 276.73 291.4 277.98 291.4 277.07 C291.4 276.15 292.82 274.07 293.73 274.07 zM296.73 276.73 C297.65 276.73 297.4 276.82 297.4 277.73 C297.4 278.65 297.32 278.07 296.4 278.07 C295.48 278.07 295.73 278.65 295.73 277.73 C295.73 276.82 295.82 276.73 296.73 276.73 zM291.4 263.73 C292.32 263.73 293.73 267.15 293.73 268.07 C293.73 268.98 290.65 268.73 289.73 268.73 C288.82 268.73 287.4 265.98 287.4 265.07 C287.4 264.15 290.48 263.73 291.4 263.73 zM280.07 274.73 C281.44 274.73 281.23 274.86 281.23 276.23 C281.23 277.61 280.94 276.73 279.57 276.73 C278.19 276.73 278.73 277.61 278.73 276.23 C278.73 274.86 278.69 274.73 280.07 274.73 zM277.07 267.73 C278.44 267.73 276.4 271.02 276.4 272.4 C276.4 273.77 271.94 274.23 270.57 274.23 C269.19 274.23 271.73 272.44 271.73 271.07 C271.73 269.69 275.69 267.73 277.07 267.73 zM52.23 84.9 C56.7 85.46 60.73 85.9 61.73 80.4 C62.73 74.9 60.23 72.9 52.73 74.9 C45.23 76.9 40.23 83.4 52.23 84.9 zM88.73 88.4 C88.73 88.4 107.45 92.81 90.23 79.9 C82.23 73.9 81.73 78.9 81.23 81.9 C80.49 86.37 88.73 88.4 88.73 88.4 zM31.73 47.9 C40.08 46.23 39.73 41.4 30.73 39.4 C29.27 39.07 26.73 48.9 31.73 47.9 zM26.73 47.9 C24.23 47.4 20.23 48.4 19.73 51.9 C19.23 55.4 23.23 57.4 25.73 55.4 C28.23 53.4 29.23 48.4 26.73 47.9 zM32.73 58.9 C30.23 57.9 22.73 59.4 23.23 62.4 C23.73 65.4 29.73 65.9 32.23 64.4 C34.73 62.9 35.23 59.9 32.73 58.9 zM31.73 76.4 C28.73 73.9 25.23 76.4 24.23 77.9 C23.23 79.4 28.23 81.4 29.73 81.9 C31.23 82.4 34.73 78.9 31.73 76.4 zM20.23 39.4 C20.23 39.4 16.23 39.4 17.23 40.9 C18.23 42.4 21.23 42.4 21.23 42.4 zM14.23 48.4 C14.23 48.4 10.23 48.4 11.23 49.9 C12.23 51.4 15.23 51.4 15.23 51.4 zM46.73 96.4 C46.73 96.4 41.73 98.4 42.73 99.9 C43.73 101.4 45.23 103.9 48.73 100.4 C52.23 96.9 46.73 96.4 46.73 96.4 zM60.23 115.9 C57.23 113.4 53.73 115.9 52.73 117.4 C51.73 118.9 56.73 120.9 58.23 121.4 C59.73 121.9 63.23 118.4 60.23 115.9 zM58.23 105.9 C55.23 103.4 52.73 106.9 51.73 108.4 C50.73 109.9 54.73 110.9 56.23 111.4 C57.73 111.9 61.23 108.4 58.23 105.9 zM75.23 72.4 C78.8 72.6 84.73 70.9 75.73 64.9 C67.41 59.35 67.73 60.9 67.23 63.9 C66.49 68.37 71.66 72.2 75.23 72.4 zM105.73 81.4 C105.73 81.4 109.23 78.4 102.23 72.4 C94.64 65.89 95.73 68.4 95.23 71.4 C94.49 75.87 105.73 81.4 105.73 81.4 zM74.73 54.9 C74.73 54.9 68.73 53.9 69.73 55.4 C70.73 56.9 73.23 62.4 76.73 58.9 C80.23 55.4 74.73 54.9 74.73 54.9 zM41.23 85.4 C39.86 85.4 38.73 86.53 38.73 87.9 C38.73 89.28 39.86 90.4 41.23 90.4 C42.61 90.4 43.73 89.28 43.73 87.9 C43.73 86.53 42.61 85.4 41.23 85.4 zM46.23 109.9 C44.86 109.9 43.73 111.03 43.73 112.4 C43.73 113.78 44.86 114.9 46.23 114.9 C47.61 114.9 48.73 113.78 48.73 112.4 C48.73 111.03 47.61 109.9 46.23 109.9 zM50.23 119.9 C48.86 119.9 47.73 121.03 47.73 122.4 C47.73 123.78 48.86 124.9 50.23 124.9 C51.61 124.9 52.73 123.78 52.73 122.4 C52.73 121.03 51.61 119.9 50.23 119.9 zM66.23 126.4 C64.86 126.4 63.73 127.53 63.73 128.9 C63.73 130.28 64.86 131.4 66.23 131.4 C67.61 131.4 68.73 130.28 68.73 128.9 C68.73 127.53 67.61 126.4 66.23 126.4 zM57.73 127.9 C56.36 127.9 53.73 130.03 53.73 131.4 C53.73 132.78 56.36 132.9 57.73 132.9 C59.11 132.9 60.23 131.78 60.23 130.4 C60.23 129.03 59.11 127.9 57.73 127.9 zM33.73 88.9 C32.36 88.9 31.23 90.03 31.23 91.4 C31.23 92.78 32.36 93.9 33.73 93.9 C35.11 93.9 36.23 92.78 36.23 91.4 C36.23 90.03 35.11 88.9 33.73 88.9 zM20.23 65.4 C18.86 65.4 17.73 66.53 17.73 67.9 C17.73 69.28 18.86 70.4 20.23 70.4 C21.61 70.4 22.73 69.28 22.73 67.9 C22.73 66.53 21.61 65.4 20.23 65.4 zM115.23 73.4 C112.91 74.33 101.73 66.9 105.23 65.9 C108.73 64.9 117.73 72.4 115.23 73.4 zM96.23 60.4 C93.73 60.9 86.23 57.9 89.73 56.9 C93.23 55.9 98.87 59.87 96.23 60.4 zM144.23 90.9 C138.73 87.9 123.23 80.4 130.73 81.4 C138.23 82.4 148.96 93.48 144.23 90.9 zM51.73 41.4 C49.23 41.9 41.73 38.9 45.23 37.9 C48.73 36.9 54.37 40.87 51.73 41.4 zM123.73 77.9 C121.23 78.4 116.23 75.9 119.73 74.9 C123.23 73.9 126.37 77.37 123.73 77.9 zM60.73 140.4 C59.36 140.4 58.23 142.03 58.23 143.4 C58.23 144.78 58.86 144.9 60.23 144.9 C61.61 144.9 62.73 143.78 62.73 142.4 C62.73 141.03 62.11 140.4 60.73 140.4 zM68.23 139.9 C66.86 139.9 64.73 140.53 64.73 141.9 C64.73 143.28 67.36 142.9 68.73 142.9 C70.11 142.9 71.23 141.78 71.23 140.4 C71.23 139.03 69.61 139.9 68.23 139.9 zM66.23 154.4 C64.86 154.4 62.23 156.53 62.23 157.9 C62.23 159.28 64.86 159.4 66.23 159.4 C67.61 159.4 68.73 158.28 68.73 156.9 C68.73 155.53 67.61 154.4 66.23 154.4 zM78.23 174.9 C74.23 173.9 74.23 175.9 73.23 179.4 C72.23 182.9 65.17 194.28 76.73 180.4 C79.23 177.4 82.23 175.9 78.23 174.9 zM66.23 186.9 C64.86 186.9 63.73 188.02 63.73 189.4 C63.73 190.77 64.86 191.9 66.23 191.9 C67.61 191.9 68.73 190.77 68.73 189.4 C68.73 188.02 67.61 186.9 66.23 186.9 zM63.73 195.9 C62.36 195.9 61.23 197.02 61.23 198.4 C61.23 199.77 62.36 200.9 63.73 200.9 C65.11 200.9 66.23 199.77 66.23 198.4 C66.23 197.02 65.11 195.9 63.73 195.9 zM63.57 204.9 C62.19 204.9 60.23 208.02 60.23 209.4 C60.23 210.77 61.36 211.9 62.73 211.9 C64.11 211.9 66.9 210.27 66.9 208.9 C66.9 207.52 64.94 204.9 63.57 204.9 zM62.23 220.9 C60.86 220.9 61.23 221.02 61.23 222.4 C61.23 223.77 61.36 222.9 62.73 222.9 C64.11 222.9 63.73 223.77 63.73 222.4 C63.73 221.02 63.61 220.9 62.23 220.9 zM75.73 187.9 C74.36 187.9 74.73 188.02 74.73 189.4 C74.73 190.77 74.86 189.9 76.23 189.9 C77.61 189.9 77.23 190.77 77.23 189.4 C77.23 188.02 77.11 187.9 75.73 187.9 zM72.73 200.4 C71.36 200.4 71.73 200.52 71.73 201.9 C71.73 203.27 71.53 206.9 72.9 206.9 C74.28 206.9 74.23 203.27 74.23 201.9 C74.23 200.52 74.11 200.4 72.73 200.4 zM69.23 214.4 C67.86 214.4 68.23 214.52 68.23 215.9 C68.23 217.27 68.36 216.4 69.73 216.4 C71.11 216.4 70.73 217.27 70.73 215.9 C70.73 214.52 70.61 214.4 69.23 214.4 zM75.4 227.9 C74.03 227.9 74.23 228.02 74.23 229.4 C74.23 230.77 74.53 229.9 75.9 229.9 C77.28 229.9 76.73 230.77 76.73 229.4 C76.73 228.02 76.78 227.9 75.4 227.9 zM66.57 231.23 C65.19 231.23 63.9 233.19 63.9 234.57 C63.9 235.94 66.86 238.4 68.23 238.4 C69.61 238.4 69.23 239.27 69.23 237.9 C69.23 236.52 67.94 231.23 66.57 231.23 zM72.23 245.57 C70.86 245.57 68.57 245.19 68.57 246.57 C68.57 247.94 71.86 250.4 73.23 250.4 C74.61 250.4 74.23 251.27 74.23 249.9 C74.23 248.52 73.61 245.57 72.23 245.57 zM80.73 238.4 C79.36 238.4 79.73 238.52 79.73 239.9 C79.73 241.27 79.86 240.4 81.23 240.4 C82.61 240.4 82.23 241.27 82.23 239.9 C82.23 238.52 82.11 238.4 80.73 238.4 zM83.23 257.57 C81.86 257.57 80.57 259.19 80.57 260.57 C80.57 261.94 82.86 261.4 84.23 261.4 C85.61 261.4 85.23 262.27 85.23 260.9 C85.23 259.52 84.61 257.57 83.23 257.57 zM91.57 262.9 C90.19 262.9 90.9 264.52 90.9 265.9 C90.9 267.27 95.86 270.4 97.23 270.4 C98.61 270.4 98.23 271.27 98.23 269.9 C98.23 268.52 92.94 262.9 91.57 262.9 zM90.73 246.9 C89.36 246.9 89.73 247.02 89.73 248.4 C89.73 249.77 89.86 248.9 91.23 248.9 C92.61 248.9 92.23 249.77 92.23 248.4 C92.23 247.02 92.11 246.9 90.73 246.9 zM102.73 255.4 C101.36 255.4 96.9 257.19 96.9 258.57 C96.9 259.94 102.53 262.23 103.9 262.23 C105.28 262.23 106.23 259.94 106.23 258.57 C106.23 257.19 104.11 255.4 102.73 255.4 zM115.73 259.9 C114.36 259.9 114.73 260.02 114.73 261.4 C114.73 262.77 114.86 261.9 116.23 261.9 C117.61 261.9 117.23 262.77 117.23 261.4 C117.23 260.02 117.11 259.9 115.73 259.9 zM107.73 271.9 C106.36 271.9 106.73 272.02 106.73 273.4 C106.73 274.77 106.86 273.9 108.23 273.9 C109.61 273.9 109.23 274.77 109.23 273.4 C109.23 272.02 109.11 271.9 107.73 271.9 zM110.73 272.9 C109.36 272.9 109.73 273.02 109.73 274.4 C109.73 275.77 109.86 274.9 111.23 274.9 C112.61 274.9 112.23 275.77 112.23 274.4 C112.23 273.02 112.11 272.9 110.73 272.9 zM122.23 273.23 C121.32 273.23 120.23 274.65 120.23 275.57 C120.23 276.48 120.32 275.9 121.23 275.9 C122.15 275.9 124.57 277.15 124.57 276.23 C124.57 275.32 123.15 273.23 122.23 273.23 zM119.23 275.9 C118.32 275.9 118.57 275.98 118.57 276.9 C118.57 277.82 118.65 277.23 119.57 277.23 C120.48 277.23 120.23 277.82 120.23 276.9 C120.23 275.98 120.15 275.9 119.23 275.9 zM124.57 262.9 C123.65 262.9 122.23 266.32 122.23 267.23 C122.23 268.15 125.32 267.9 126.23 267.9 C127.15 267.9 128.57 265.15 128.57 264.23 C128.57 263.32 125.48 262.9 124.57 262.9 zM135.9 273.9 C134.53 273.9 134.73 274.02 134.73 275.4 C134.73 276.77 135.03 275.9 136.4 275.9 C137.78 275.9 137.23 276.77 137.23 275.4 C137.23 274.02 137.28 273.9 135.9 273.9 zM138.9 266.9 C137.53 266.9 139.57 270.19 139.57 271.57 C139.57 272.94 144.03 273.4 145.4 273.4 C146.78 273.4 144.23 271.61 144.23 270.23 C144.23 268.86 140.28 266.9 138.9 266.9 zM211 134.8 C209.63 134.8 209.83 134.93 209.83 136.3 C209.83 137.68 210.13 136.8 211.5 136.8 C212.88 136.8 212.33 137.68 212.33 136.3 C212.33 134.93 212.38 134.8 211 134.8 zM205.5 134.8 C204.13 134.8 204.33 134.93 204.33 136.3 C204.33 137.68 204.63 136.8 206 136.8 C207.38 136.8 206.83 137.68 206.83 136.3 C206.83 134.93 206.88 134.8 205.5 134.8 zM211 143.8 C209.63 143.8 209.83 143.93 209.83 145.3 C209.83 146.68 210.13 145.8 211.5 145.8 C212.88 145.8 212.33 146.68 212.33 145.3 C212.33 143.93 212.38 143.8 211 143.8 zM204.9 143.7 C203.53 143.7 203.73 143.83 203.73 145.2 C203.73 146.58 204.03 145.7 205.4 145.7 C206.78 145.7 206.23 146.58 206.23 145.2 C206.23 143.83 206.28 143.7 204.9 143.7 zM213 154.3 C211.63 154.3 212 155.43 212 156.8 C212 158.18 212.42 161.3 213.8 161.3 C215.17 161.3 214.33 157.18 214.33 155.8 C214.33 154.43 214.38 154.3 213 154.3 zM204 154.3 C202.63 154.3 202.6 155.53 202.6 156.9 C202.6 158.28 201.63 161.5 203 161.5 C204.38 161.5 204.8 157.68 204.8 156.3 C204.8 154.93 205.38 154.3 204 154.3 z"/>
- </g>
-<!-- Generated by Jasc WebDraw PR4(tm) on 06/07/01 12:18:39 -->
-</svg>
diff --git a/o3d/samples/gpu2d/crescent.svg b/o3d/samples/gpu2d/crescent.svg
deleted file mode 100644
index 933dbb7..0000000
--- a/o3d/samples/gpu2d/crescent.svg
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-<svg
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- version="1.0"
- width="80mm"
- height="80mm"
- id="svg2">
- <defs
- id="defs4" />
- <g
- id="layer1">
- <path
- d="M 125.13485,36.187753 C 67.60819,37.282014 21.25984,84.307148 21.259843,142.094 C 21.259843,200.56607 68.72535,248.0315 127.19735,248.0315 C 154.53502,248.0315 179.46231,237.64775 198.25985,220.62525 C 185.00691,228.24342 169.63331,232.594 153.25985,232.594 C 103.33007,232.594 62.822343,192.08628 62.822343,142.1565 C 62.822343,92.226718 103.33007,51.719003 153.25985,51.719003 C 169.76352,51.719003 185.24789,56.144299 198.57235,63.875253 C 179.73892,46.68361 154.68725,36.187751 127.19735,36.187753 C 126.51213,36.187753 125.81698,36.174778 125.13485,36.187753 z "
- style="fill:#007f00;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
- id="path1315" />
- </g>
-</svg>
diff --git a/o3d/samples/gpu2d/javalogo.svg b/o3d/samples/gpu2d/javalogo.svg
deleted file mode 100644
index d03cb5b..0000000
--- a/o3d/samples/gpu2d/javalogo.svg
+++ /dev/null
@@ -1,58 +0,0 @@
-<?xml version="1.0"?>
-<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
- "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
-<svg xmlns="http://www.w3.org/2000/svg"
- xmlns:xlink="http://www.w3.org/1999/xlink">
-<path d="M117.151 349.592 C117.151 349.592 99.886 359.641 129.452 363.032 C165.276 367.122 183.582 366.533 223.048 359.073 C223.048 359.073 233.445 365.577 247.940 371.210 C159.439 409.127 47.644 369.013 117.151 349.592 L117.151 349.592 z "
- style="stroke-width:1;fill:rgb(0,116,189);stroke:none"/>
-<path d="M106.331 300.104 C106.331 300.104 86.964 314.443 116.552 317.501 C154.823 321.452 185.035 321.776 237.344 311.709 C237.344 311.709 244.562 319.041 255.929 323.048 C148.943 354.342 29.782 325.510 106.331 300.104 L106.331 300.104 z "
- style="stroke-width:1;fill:rgb(0,116,189);stroke:none"/>
-<path d="M197.494 216.145 C219.312 241.260 191.773 263.842 191.773 263.842 Q247.140 235.265 221.718 199.462 C197.966 166.089 179.756 149.511 278.341 92.338 C278.342 92.338 123.587 130.979 197.494 216.145 L197.494 216.145 z "
- style="stroke-width:1;fill:rgb(234,45,46);stroke:none"/>
-<path d="M314.542 386.202 C314.542 386.202 327.323 396.738 300.465 404.886 C249.394 420.355 87.861 425.021 42.995 405.505 C26.878 398.485 57.116 388.755 66.630 386.700 C76.550 384.554 82.214 384.946 82.214 384.946 C64.277 372.315 -33.721 409.753 32.442 420.490 C212.871 449.736 361.337 407.317 314.542 386.202 L314.542 386.202 z "
- style="stroke-width:1;fill:rgb(0,116,189);stroke:none"/>
-<path d="M125.460 248.822 C125.460 248.822 43.305 268.341 96.368 275.435 C118.780 278.434 163.431 277.744 205.053 274.252 C239.059 271.398 273.186 265.294 273.186 265.294 Q261.204 270.434 252.529 276.354 C169.085 298.301 7.917 288.080 54.322 265.642 C93.549 246.665 125.460 248.822 125.460 248.822 L125.460 248.822 z "
- style="stroke-width:1;fill:rgb(0,116,189);stroke:none"/>
-<path d="M272.846 331.198 C357.664 287.135 318.443 244.786 291.069 250.490 C284.375 251.887 281.372 253.097 281.372 253.097 Q283.866 249.190 288.615 247.509 C342.770 228.479 384.409 303.655 271.151 333.428 C271.150 333.428 272.453 332.248 272.846 331.198 L272.846 331.198 z "
- style="stroke-width:1;fill:rgb(0,116,189);stroke:none"/>
-<path d="M221.719 0.000 C221.719 0.000 268.682 46.990 177.162 119.227 C103.769 177.196 160.428 210.236 177.136 248.005 C134.291 209.352 102.865 175.321 123.944 143.653 C154.898 97.174 240.663 74.632 221.719 0.000 L221.719 0.000 z "
- style="stroke-width:1;fill:rgb(234,45,46);stroke:none"/>
-<path d="M133.799 450.637 C215.196 455.841 340.225 447.741 343.184 409.222 C343.184 409.222 337.496 423.824 275.908 435.410 C206.427 448.491 120.711 446.968 69.892 438.577 C69.892 438.577 80.303 447.194 133.799 450.637 L133.799 450.637 z "
- style="stroke-width:1;fill:rgb(0,116,189);stroke:none"/>
-<path d="M339.426 519.716 L336.947 519.716 L336.947 518.331 L343.623 518.331 L343.623 519.716 L341.154 519.716 L341.154 526.644 L339.425 526.644 L339.425 519.716 L339.426 519.716 L339.426 519.716 z M352.756 520.067 L352.724 520.067 L350.263 526.643 L349.131 526.643 L346.685 520.067 L346.660 520.067 L346.660 526.643 L345.022 526.643 L345.022 518.330 L347.424 518.330 L349.688 524.215 L351.959 518.330 L354.347 518.330 L354.347 526.643 L352.757 526.643 L352.757 520.067 L352.756 520.067 z "
- style="stroke-width:1;fill:rgb(234,45,46);stroke:none"/>
-<path d="M120.461 597.813 C112.785 604.467 104.668 608.209 97.382 608.209 C87.004 608.209 81.375 601.973 81.375 591.993 C81.375 581.190 87.402 573.283 111.538 573.283 L120.461 573.283 L120.461 597.813 L120.461 597.813 L120.461 597.813 z M141.650 621.716 L141.650 547.720 C141.650 528.805 130.863 516.324 104.868 516.324 C89.700 516.324 76.401 520.074 65.590 524.849 L68.701 537.955 C77.216 534.828 88.227 531.924 99.038 531.924 C114.016 531.924 120.461 537.955 120.461 550.429 L120.461 559.785 L112.976 559.785 C76.593 559.785 60.178 573.895 60.178 595.121 C60.178 613.406 70.997 623.803 91.363 623.803 C104.451 623.803 114.233 618.398 123.364 610.488 L125.027 621.716 L141.650 621.716 L141.650 621.716 z "
- style="stroke-width:1;fill:rgb(234,45,46);stroke:none"/>
-<path d="M212.362 621.716 L185.939 621.716 L154.132 518.214 L177.209 518.214 L196.952 581.814 L201.343 600.923 C211.308 573.284 218.375 545.222 221.909 518.214 L244.354 518.214 C238.352 552.294 227.523 589.706 212.362 621.716 L212.362 621.716 z "
- style="stroke-width:1;fill:rgb(234,45,46);stroke:none"/>
-<path d="M313.755 597.813 C306.054 604.467 297.935 608.209 290.669 608.209 C280.287 608.209 274.658 601.973 274.658 591.993 C274.658 581.190 280.697 573.283 304.812 573.283 L313.754 573.283 L313.754 597.813 L313.755 597.813 L313.755 597.813 z M334.951 621.716 L334.951 547.720 C334.951 528.805 324.133 516.324 298.162 516.324 C282.974 516.324 269.678 520.074 258.867 524.849 L261.983 537.955 C270.502 534.828 281.528 531.924 292.338 531.924 C307.298 531.924 313.754 537.955 313.754 550.429 L313.754 559.785 L306.269 559.785 C269.878 559.785 253.468 573.895 253.468 595.121 C253.468 613.406 264.272 623.803 284.637 623.803 C297.736 623.803 307.499 618.398 316.655 610.488 L318.329 621.716 L334.951 621.716 L334.951 621.716 z "
- style="stroke-width:1;fill:rgb(234,45,46);stroke:none"/>
-<path d="M36.941 639.306 C30.904 648.127 21.141 655.115 10.462 659.055 L0.000 646.731 C8.135 642.553 15.103 635.819 18.345 629.549 C21.141 623.960 22.305 616.776 22.305 599.578 L22.305 481.398 L44.824 481.398 L44.824 597.949 C44.824 620.950 42.988 630.249 36.941 639.306 L36.941 639.306 z "
- style="stroke-width:1;fill:rgb(234,45,46);stroke:none"/>
-<path d="M117.151 349.592 C117.151 349.592 99.886 359.641 129.452 363.032 C165.276 367.122 183.582 366.533 223.048 359.073 C223.048 359.073 233.445 365.577 247.940 371.210 C159.439 409.127 47.644 369.013 117.151 349.592 L117.151 349.592 z "
- style="stroke-width:1;fill:rgb(0,116,189);stroke:none"/>
-<path d="M106.331 300.104 C106.331 300.104 86.964 314.443 116.552 317.501 C154.823 321.452 185.035 321.776 237.344 311.709 C237.344 311.709 244.562 319.041 255.929 323.048 C148.943 354.342 29.782 325.510 106.331 300.104 L106.331 300.104 z "
- style="stroke-width:1;fill:rgb(0,116,189);stroke:none"/>
-<path d="M197.494 216.145 C219.312 241.260 191.773 263.842 191.773 263.842 Q247.140 235.265 221.718 199.462 C197.966 166.089 179.756 149.511 278.341 92.338 C278.342 92.338 123.587 130.979 197.494 216.145 L197.494 216.145 z "
- style="stroke-width:1;fill:rgb(234,45,46);stroke:none"/>
-<path d="M314.542 386.202 C314.542 386.202 327.323 396.738 300.465 404.886 C249.394 420.355 87.861 425.021 42.995 405.505 C26.878 398.485 57.116 388.755 66.630 386.700 C76.550 384.554 82.214 384.946 82.214 384.946 C64.277 372.315 -33.721 409.753 32.442 420.490 C212.871 449.736 361.337 407.317 314.542 386.202 L314.542 386.202 z "
- style="stroke-width:1;fill:rgb(0,116,189);stroke:none"/>
-<path d="M125.460 248.822 C125.460 248.822 43.305 268.341 96.368 275.435 C118.780 278.434 163.431 277.744 205.053 274.252 C239.059 271.398 273.186 265.294 273.186 265.294 Q261.204 270.434 252.529 276.354 C169.085 298.301 7.917 288.080 54.322 265.642 C93.549 246.665 125.460 248.822 125.460 248.822 L125.460 248.822 z "
- style="stroke-width:1;fill:rgb(0,116,189);stroke:none"/>
-<path d="M272.846 331.198 C357.664 287.135 318.443 244.786 291.069 250.490 C284.375 251.887 281.372 253.097 281.372 253.097 Q283.866 249.190 288.615 247.509 C342.770 228.479 384.409 303.655 271.151 333.428 C271.150 333.428 272.453 332.248 272.846 331.198 L272.846 331.198 z "
- style="stroke-width:1;fill:rgb(0,116,189);stroke:none"/>
-<path d="M221.719 0.000 C221.719 0.000 268.682 46.990 177.162 119.227 C103.769 177.196 160.428 210.236 177.136 248.005 C134.291 209.352 102.865 175.321 123.944 143.653 C154.898 97.174 240.663 74.632 221.719 0.000 L221.719 0.000 z "
- style="stroke-width:1;fill:rgb(234,45,46);stroke:none"/>
-<path d="M133.799 450.637 C215.196 455.841 340.225 447.741 343.184 409.222 C343.184 409.222 337.496 423.824 275.908 435.410 C206.427 448.491 120.711 446.968 69.892 438.577 C69.892 438.577 80.303 447.194 133.799 450.637 L133.799 450.637 z "
- style="stroke-width:1;fill:rgb(0,116,189);stroke:none"/>
-<path d="M339.426 519.716 L336.947 519.716 L336.947 518.331 L343.623 518.331 L343.623 519.716 L341.154 519.716 L341.154 526.644 L339.425 526.644 L339.425 519.716 L339.426 519.716 L339.426 519.716 z M352.756 520.067 L352.724 520.067 L350.263 526.643 L349.131 526.643 L346.685 520.067 L346.660 520.067 L346.660 526.643 L345.022 526.643 L345.022 518.330 L347.424 518.330 L349.688 524.215 L351.959 518.330 L354.347 518.330 L354.347 526.643 L352.757 526.643 L352.757 520.067 L352.756 520.067 z "
- style="stroke-width:1;fill:rgb(234,45,46);stroke:none"/>
-<path d="M120.461 597.813 C112.785 604.467 104.668 608.209 97.382 608.209 C87.004 608.209 81.375 601.973 81.375 591.993 C81.375 581.190 87.402 573.283 111.538 573.283 L120.461 573.283 L120.461 597.813 L120.461 597.813 L120.461 597.813 z M141.650 621.716 L141.650 547.720 C141.650 528.805 130.863 516.324 104.868 516.324 C89.700 516.324 76.401 520.074 65.590 524.849 L68.701 537.955 C77.216 534.828 88.227 531.924 99.038 531.924 C114.016 531.924 120.461 537.955 120.461 550.429 L120.461 559.785 L112.976 559.785 C76.593 559.785 60.178 573.895 60.178 595.121 C60.178 613.406 70.997 623.803 91.363 623.803 C104.451 623.803 114.233 618.398 123.364 610.488 L125.027 621.716 L141.650 621.716 L141.650 621.716 z "
- style="stroke-width:1;fill:rgb(234,45,46);stroke:none"/>
-<path d="M212.362 621.716 L185.939 621.716 L154.132 518.214 L177.209 518.214 L196.952 581.814 L201.343 600.923 C211.308 573.284 218.375 545.222 221.909 518.214 L244.354 518.214 C238.352 552.294 227.523 589.706 212.362 621.716 L212.362 621.716 z "
- style="stroke-width:1;fill:rgb(234,45,46);stroke:none"/>
-<path d="M313.755 597.813 C306.054 604.467 297.935 608.209 290.669 608.209 C280.287 608.209 274.658 601.973 274.658 591.993 C274.658 581.190 280.697 573.283 304.812 573.283 L313.754 573.283 L313.754 597.813 L313.755 597.813 L313.755 597.813 z M334.951 621.716 L334.951 547.720 C334.951 528.805 324.133 516.324 298.162 516.324 C282.974 516.324 269.678 520.074 258.867 524.849 L261.983 537.955 C270.502 534.828 281.528 531.924 292.338 531.924 C307.298 531.924 313.754 537.955 313.754 550.429 L313.754 559.785 L306.269 559.785 C269.878 559.785 253.468 573.895 253.468 595.121 C253.468 613.406 264.272 623.803 284.637 623.803 C297.736 623.803 307.499 618.398 316.655 610.488 L318.329 621.716 L334.951 621.716 L334.951 621.716 z "
- style="stroke-width:1;fill:rgb(234,45,46);stroke:none"/>
-<path d="M36.941 639.306 C30.904 648.127 21.141 655.115 10.462 659.055 L0.000 646.731 C8.135 642.553 15.103 635.819 18.345 629.549 C21.141 623.960 22.305 616.776 22.305 599.578 L22.305 481.398 L44.824 481.398 L44.824 597.949 C44.824 620.950 42.988 630.249 36.941 639.306 L36.941 639.306 z "
- style="stroke-width:1;fill:rgb(234,45,46);stroke:none"/>
-</svg>
diff --git a/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-1.html b/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-1.html
deleted file mode 100644
index 43d3cea..0000000
--- a/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-1.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<html>
-<head>
-<title>
-Curve Subdivision Bug 1
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../o3djs/base.js"></script>
-<!-- Include SVG sample and dependencies -->
-<script type="text/javascript" src="../../third_party/xmljs/tinyxmlsax.js"></script>
-<script type="text/javascript" src="../svgloader.js"></script>
-<script type="text/javascript" src="../svgsample.js"></script>
-</head>
-<body onload="init('curve-subdivision-bug-1.svg');" onunload="unload();">
-<h1>Curve Subdivision Bug 1</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 500px; height: 200px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-1.svg b/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-1.svg
deleted file mode 100644
index d174e74..0000000
--- a/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-1.svg
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-
-<svg
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- version="1.1"
- width="500"
- height="500"
- id="svg4764">
- <defs
- id="defs4820" />
- <path
- d="M 460.70202,26.83982 C 460.70202,26.83982 480.58076,43.22683 438.80757,55.8997 359.37505,79.959179 108.13711,87.21637 38.355451,56.862453 L 21.942,80.169149 C 302.56955,125.65648 533.48393,59.68072 460.70202,26.83982 L 460.70202,26.83982 z"
- id="path4772"
- style="fill:#0074bd;stroke:none" />
-</svg>
diff --git a/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-2.html b/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-2.html
deleted file mode 100644
index 12ee88f..0000000
--- a/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-2.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<html>
-<head>
-<title>
-Curve Subdivision Bug 2
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../o3djs/base.js"></script>
-<!-- Include SVG sample and dependencies -->
-<script type="text/javascript" src="../../third_party/xmljs/tinyxmlsax.js"></script>
-<script type="text/javascript" src="../svgloader.js"></script>
-<script type="text/javascript" src="../svgsample.js"></script>
-</head>
-<body onload="init('curve-subdivision-bug-2.svg');" onunload="unload();">
-<h1>Curve Subdivision Bug 2</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 500px; height: 200px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-2.svg b/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-2.svg
deleted file mode 100644
index 4479506..0000000
--- a/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-2.svg
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-
-<svg
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- version="1.1"
- width="500"
- height="500"
- id="svg4764">
- <defs
- id="defs4820" />
- <path
- d="M 460.70202,26.83982 C 460.70202,26.83982 480.58076,43.22683 438.80757,55.8997 359.37505,79.959179 108.13711,87.21637 38.355451,56.862453 L 21.942,80.169149 C 302.56955,125.65648 533.48393,59.68072 460.70202,26.83982 z"
- id="path4772"
- style="fill:#0074bd;stroke:none" />
-</svg>
diff --git a/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-3.html b/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-3.html
deleted file mode 100644
index a9b17f2..0000000
--- a/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-3.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<html>
-<head>
-<title>
-Curve Subdivision Bug 3
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../o3djs/base.js"></script>
-<!-- Include SVG sample and dependencies -->
-<script type="text/javascript" src="../../third_party/xmljs/tinyxmlsax.js"></script>
-<script type="text/javascript" src="../svgloader.js"></script>
-<script type="text/javascript" src="../svgsample.js"></script>
-</head>
-<body onload="init('curve-subdivision-bug-3.svg');" onunload="unload();">
-<h1>Curve Subdivision Bug 3</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 500px; height: 200px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-3.svg b/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-3.svg
deleted file mode 100644
index 590709c..0000000
--- a/o3d/samples/gpu2d/regression-tests/curve-subdivision-bug-3.svg
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-
-<svg
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- version="1.1"
- width="500"
- height="500"
- id="svg4764">
- <defs
- id="defs4820" />
- <path
- d="M 224.66972,14.854959 C 224.66972,14.854959 270.94528,53.002149 173.7018,82.503222 -11.208535,138.5111 -596.06334,155.40506 -758.50751,84.744408 L -796.71625,138.99988 C -143.44562,244.88947 394.09814,91.305029 224.66972,14.854959 L 224.66972,14.854959 z"
- id="path4772"
- style="fill:#0074bd;stroke:none" />
-</svg>
diff --git a/o3d/samples/gpu2d/regression-tests/orientation-bug-1.html b/o3d/samples/gpu2d/regression-tests/orientation-bug-1.html
deleted file mode 100644
index 3790d61..0000000
--- a/o3d/samples/gpu2d/regression-tests/orientation-bug-1.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<html>
-<head>
-<title>
-Orientation Determination Bug
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../o3djs/base.js"></script>
-<!-- Include SVG sample and dependencies -->
-<script type="text/javascript" src="../../third_party/xmljs/tinyxmlsax.js"></script>
-<script type="text/javascript" src="../svgloader.js"></script>
-<script type="text/javascript" src="../svgsample.js"></script>
-</head>
-<body onload="init('orientation-bug-1.svg');" onunload="unload();">
-<h1>Orientation Determination Bug</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 800px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/gpu2d/regression-tests/orientation-bug-1.svg b/o3d/samples/gpu2d/regression-tests/orientation-bug-1.svg
deleted file mode 100644
index aa93f17..0000000
--- a/o3d/samples/gpu2d/regression-tests/orientation-bug-1.svg
+++ /dev/null
@@ -1,72 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-
-<svg
- xmlns:dc="http://purl.org/dc/elements/1.1/"
- xmlns:cc="http://creativecommons.org/ns#"
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
- xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
- width="500"
- height="500"
- id="svg3012"
- version="1.1"
- inkscape:version="0.47 r22583"
- sodipodi:docname="a.svg">
- <defs
- id="defs3014">
- <inkscape:perspective
- sodipodi:type="inkscape:persp3d"
- inkscape:vp_x="0 : 526.18109 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_z="744.09448 : 526.18109 : 1"
- inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
- id="perspective3020" />
- </defs>
- <sodipodi:namedview
- id="base"
- pagecolor="#ffffff"
- bordercolor="#666666"
- borderopacity="1.0"
- inkscape:pageopacity="0.0"
- inkscape:pageshadow="2"
- inkscape:zoom="1"
- inkscape:cx="185.77464"
- inkscape:cy="230.99609"
- inkscape:document-units="px"
- inkscape:current-layer="layer1"
- showgrid="false"
- inkscape:window-width="939"
- inkscape:window-height="861"
- inkscape:window-x="723"
- inkscape:window-y="0"
- inkscape:window-maximized="0" />
- <metadata
- id="metadata3017">
- <rdf:RDF>
- <cc:Work
- rdf:about="">
- <dc:format>image/svg+xml</dc:format>
- <dc:type
- rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
- <dc:title></dc:title>
- </cc:Work>
- </rdf:RDF>
- </metadata>
- <g
- inkscape:label="Layer 1"
- inkscape:groupmode="layer"
- id="layer1"
- transform="translate(-189.22536,329.0208)">
- <g
- style="font-size:600px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:start;line-height:125%;writing-mode:lr-tb;text-anchor:start;fill:#000000;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans"
- id="text3078"
- transform="translate(15,9)">
- <path
- d="m 402.88942,-106.96221 c -43.55485,1.7e-4 -73.7306,4.98063 -90.52734,14.941408 -16.79698,9.961078 -25.19541,26.953249 -25.19532,50.976563 -9e-5,19.140705 6.24991,34.3750646 18.75,45.703125 12.69519,11.132855 29.88268,16.699255 51.5625,16.699219 29.88263,3.6e-5 53.80838,-10.546828 71.77735,-31.640625 18.16381,-21.288973 27.24583,-49.511601 27.24609,-84.667969 l 0,-12.011721 -53.61328,0 m 107.51953,-22.26562 0,187.207028 -53.90625,0 0,-49.804687 c -12.30493,19.921905 -27.63695,34.667984 -45.99609,44.238281 -18.35957,9.374996 -40.82049,14.062492 -67.38282,14.0625 -33.59386,-8e-6 -60.35164,-9.374999 -80.27343,-28.125 -19.72661,-18.945274 -29.58988,-44.2382172 -29.58985,-75.878906 -3e-5,-36.91393 12.30464,-64.745936 36.91407,-83.496096 24.80459,-18.7498 61.71861,-28.12479 110.74218,-28.125 l 75.58594,0 0,-5.27344 c -2.6e-4,-24.80445 -8.20338,-43.94505 -24.60937,-57.42187 -16.21116,-13.67159 -39.0627,-20.50752 -68.55469,-20.50781 -18.75015,2.9e-4 -37.01185,2.24638 -54.78516,6.73828 -17.77353,4.49247 -34.86336,11.23074 -51.26953,20.21484 l 0,-49.80469 c 19.72648,-7.61686 38.86709,-13.28092 57.42188,-16.99218 18.55455,-3.90592 36.62094,-5.85904 54.19921,-5.85938 47.46072,3.4e-4 82.90991,12.30501 106.34766,36.91406 23.4372,24.60965 35.15594,61.9143 35.15625,111.91407"
- id="path3083" />
- </g>
- </g>
-</svg>
diff --git a/o3d/samples/gpu2d/regression-tests/orientation-bug-2.html b/o3d/samples/gpu2d/regression-tests/orientation-bug-2.html
deleted file mode 100644
index 4838178..0000000
--- a/o3d/samples/gpu2d/regression-tests/orientation-bug-2.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<html>
-<head>
-<title>
-Orientation Bug 2 (Butterfly Spots)
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../o3djs/base.js"></script>
-<!-- Include SVG sample and dependencies -->
-<script type="text/javascript" src="../../third_party/xmljs/tinyxmlsax.js"></script>
-<script type="text/javascript" src="../svgloader.js"></script>
-<script type="text/javascript" src="../svgsample.js"></script>
-</head>
-<body onload="init('orientation-bug-2.svg');" onunload="unload();">
-<h1>Orientation Bug 2 (Butterfly Spots)</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 1024px; height: 768px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/gpu2d/regression-tests/orientation-bug-2.svg b/o3d/samples/gpu2d/regression-tests/orientation-bug-2.svg
deleted file mode 100644
index 8611b43..0000000
--- a/o3d/samples/gpu2d/regression-tests/orientation-bug-2.svg
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-
-<svg
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- version="1.1"
- width="100%"
- height="100%"
- id="svg3331">
- <defs
- id="defs3343" />
- <path
- d="M 1127.0498,42.514488 C 1101.9998,37.504488 1103.0498,23.014488 1130.0498,17.014488 1134.4598,16.054488 1142.0498,45.514488 1127.0498,42.514488 z M 1142.0498,42.514488 C 1149.5498,41.014488 1161.5498,44.014488 1163.0498,54.514488 1164.5498,65.014488 1152.5498,71.014488 1145.0498,65.014488 1137.5498,59.014488 1134.5498,44.014488 1142.0498,42.514488 z M 1161.5498,17.014488 C 1161.5498,17.014488 1173.5498,17.014488 1170.5498,21.514488 1167.5498,26.014488 1158.5498,26.014488 1158.5498,26.014488 L 1161.5498,17.014488 z M 1179.5498,44.014488 C 1179.5498,44.014488 1191.5498,44.014488 1188.5498,48.514488 1185.5498,53.014488 1176.5498,53.014488 1176.5498,53.014488 L 1179.5498,44.014488 z M 1067.0498,23.014488 C 1074.5498,24.514488 1097.0498,15.514488 1086.5498,12.514488 1076.0498,9.5144883 1059.1298,21.454488 1067.0498,23.014488 z M 69.54982,40.024488 C 94.59982,35.014488 93.54982,20.524488 66.54982,14.524488 62.16982,13.534488 54.54982,43.024488 69.54982,40.024488 z M 54.54982,40.024488 C 47.04982,38.524488 35.04982,41.524488 33.54982,52.024488 32.04982,62.524488 44.04982,68.524488 51.54982,62.524488 59.04982,56.524488 62.04982,41.524488 54.54982,40.024488 z M 35.04982,14.524488 C 35.04982,14.524488 23.04982,14.524488 26.04982,19.024488 29.04982,23.524488 38.04982,23.524488 38.04982,23.524488 L 35.04982,14.524488 z M 17.04982,41.524488 C 17.04982,41.524488 5.0498197,41.524488 8.0498197,46.024488 11.04982,50.524488 20.04982,50.524488 20.04982,50.524488 L 17.04982,41.524488 z M 129.54982,20.524488 C 122.04982,22.024488 99.54982,13.024488 110.04982,10.024488 120.54982,7.0244883 137.46982,18.934488 129.54982,20.524488 z"
- id="path3339"
- style="fill:#fff6e3;stroke:none" />
-</svg>
diff --git a/o3d/samples/gpu2d/regression-tests/orientation-bug-3.html b/o3d/samples/gpu2d/regression-tests/orientation-bug-3.html
deleted file mode 100644
index d8e1e7b..0000000
--- a/o3d/samples/gpu2d/regression-tests/orientation-bug-3.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<html>
-<head>
-<title>
-Orientation Bug 3 (Butterfly's Black Region)
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../o3djs/base.js"></script>
-<!-- Include SVG sample and dependencies -->
-<script type="text/javascript" src="../../third_party/xmljs/tinyxmlsax.js"></script>
-<script type="text/javascript" src="../svgloader.js"></script>
-<script type="text/javascript" src="../svgsample.js"></script>
-</head>
-<body onload="init('orientation-bug-3.svg');" onunload="unload();">
-<h1>Orientation Bug 3 (Butterfly's Black Region)</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 1024px; height: 768px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/gpu2d/regression-tests/orientation-bug-3.svg b/o3d/samples/gpu2d/regression-tests/orientation-bug-3.svg
deleted file mode 100644
index fec711c..0000000
--- a/o3d/samples/gpu2d/regression-tests/orientation-bug-3.svg
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-
-<svg
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- version="1.1"
- width="100%"
- height="100%"
- id="svg3670">
- <defs
- id="defs3682" />
- <path
- d="M 610.86,418.86 C 586.86,399.36 617.88,397.8 617.61,397.11 574.86,290.61 505.92,243.6 500.61,241.11 484.23,233.43 476.31,234.15 479.19,230.28 482.07,226.41 501.03,238.53 503.61,240.36 579.36,294.36 620.61,396.36 620.61,396.36 620.61,396.36 625.86,399.36 626.61,397.11 656.61,308.61 716.61,262.11 736.86,243.36 757.11,224.61 767.76,222.78 739.86,244.11 653.61,310.11 628.89,396.03 630.36,396.36 664.86,403.86 631.86,420.36 633.36,418.86 642.42,409.8 642.36,436.86 642.36,436.86 642.36,436.86 693.36,331.86 892.86,198.36 905.13,190.14 1335.36,-44.64 1185.36,241.86 1177.59,256.71 1125.36,316.86 1125.36,316.86 1125.36,316.86 1129.86,342.36 1111.86,363.36 1108.77,366.96 1101.36,402.36 1083.36,421.86 1078.29,427.38 1083.27,417.12 1083.36,421.86 1084.86,511.86 1011.15,509.88 1015.86,510.36 1044.36,513.36 1048.41,550.35 1048.86,550.86 1065.36,570.36 1059.36,574.86 1065.36,583.86 1097.73,632.43 1063.59,629.52 1068.36,637.86 1080.36,658.86 1065.84,667.53 1069.86,673.86 1080.36,690.36 1062.09,700.86 1062.36,705.36 1063.86,730.86 1046.88,721.56 1047.36,732.36 1048.86,765.36 1036.86,751.86 1029.36,763.86 1006.86,799.86 998.22,786.51 996.36,790.86 987.36,811.86 975.27,806.82 970.86,811.86 960.36,823.86 949.86,823.86 945.36,828.36 924.36,849.36 912.45,834.51 909.36,835.86 861.36,856.86 838.86,839.85 831.36,840.36 808.86,841.86 812.31,838.38 805.86,832.86 711.36,751.86 655.86,634.86 645.36,619.86 641.07,613.71 631.89,578.73 634.86,586.86 640.86,603.36 637.86,750.36 621.36,750.36 574.44968,710.77679 648.61944,539.97251 603.24,619.86 586.86,639.36 536.37,751.86 440.64,832.86 434.13,838.38 437.61,841.86 414.81,840.36 407.25,839.85 384.42,856.86 335.82,835.86 332.7,834.51 320.61,849.36 299.34,828.36 294.78,823.86 284.16,823.86 273.51,811.86 269.04,806.82 256.8,811.86 247.68,790.86 245.79,786.51 237.03,799.86 214.26,763.86 206.64,751.86 194.49,765.36 196.02,732.36 196.53,721.56 179.31,730.86 180.81,705.36 181.08,700.86 162.6,690.36 173.22,673.86 177.3,667.53 162.6,658.86 174.75,637.86 179.58,629.52 144.99,632.43 177.78,583.86 183.87,574.86 177.78,570.36 194.49,550.86 194.94,550.35 199.05,513.36 227.94,510.36 232.71,509.88 158.04,511.86 159.54,421.86 159.63,417.12 164.7,427.38 159.54,421.86 141.33,402.36 133.8,366.96 130.68,363.36 112.44,342.36 117,316.86 117,316.86 117,316.86 64.11,256.71 56.22,241.86 -95.7,-44.64 340.08,190.14 352.53,198.36 554.61,331.86 603.87,436.86 603.87,436.86 603.87,436.86 604.95,429.21 606.87,424.86 608.79,420.54 611.55,419.43 610.86,418.86 z M 253.77,228.36 C 317.58,243.36 290.22,265.86 282.63,264.36 223.59,252.72 240.45,225.24 253.77,228.36 z M 230.97,240.36 C 240.66,243.09 214.26,228.36 192.99,226.86 185.25,226.32 150.78,204.6 127.65,238.86 124.59,243.36 110.25,239.52 88.14,261.36 83.58,265.86 110.55,239.61 135.24,249.36 142.83,252.36 157.23,271.17 192.99,235.86 197.55,231.36 220.32,237.36 230.97,240.36 z"
- id="path3676"
- style="fill:#000000;stroke:none" />
-</svg>
diff --git a/o3d/samples/gpu2d/svg_a.html b/o3d/samples/gpu2d/svg_a.html
deleted file mode 100644
index c770276..0000000
--- a/o3d/samples/gpu2d/svg_a.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<html>
-<head>
-<title>
-SVG Letter A
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<!-- Include SVG sample and dependencies -->
-<script type="text/javascript" src="../third_party/xmljs/tinyxmlsax.js"></script>
-<script type="text/javascript" src="svgloader.js"></script>
-<script type="text/javascript" src="svgsample.js"></script>
-</head>
-<body onload="init('a.svg');" onunload="unload();">
-<h1>SVG Letter A</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 800px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/gpu2d/svg_butterfly.html b/o3d/samples/gpu2d/svg_butterfly.html
deleted file mode 100644
index 0cd4182..0000000
--- a/o3d/samples/gpu2d/svg_butterfly.html
+++ /dev/null
@@ -1,52 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<html>
-<head>
-<title>
-SVG Butterfly
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<!-- Include SVG sample and dependencies -->
-<script type="text/javascript" src="../third_party/xmljs/tinyxmlsax.js"></script>
-<script type="text/javascript" src="svgloader.js"></script>
-<script type="text/javascript" src="svgsample.js"></script>
-</head>
-<body onload="init('butterfly.svg');" onunload="unload();">
-<h1>SVG Butterfly</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 1280px; height: 1024px;"></div>
-<!-- End of O3D plugin -->
-
-</body>
-</html>
diff --git a/o3d/samples/gpu2d/svg_crescent.html b/o3d/samples/gpu2d/svg_crescent.html
deleted file mode 100644
index 324a654..0000000
--- a/o3d/samples/gpu2d/svg_crescent.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<html>
-<head>
-<title>
-SVG Crescent
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<!-- Include SVG sample and dependencies -->
-<script type="text/javascript" src="../third_party/xmljs/tinyxmlsax.js"></script>
-<script type="text/javascript" src="svgloader.js"></script>
-<script type="text/javascript" src="svgsample.js"></script>
-</head>
-<body onload="init('crescent.svg');" onunload="unload();">
-<h1>SVG Crescent</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/gpu2d/svg_google_logo.html b/o3d/samples/gpu2d/svg_google_logo.html
deleted file mode 100644
index 8b29944..0000000
--- a/o3d/samples/gpu2d/svg_google_logo.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<html>
-<head>
-<title>
-SVG Google Logo
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<!-- Include SVG sample and dependencies -->
-<script type="text/javascript" src="../third_party/xmljs/tinyxmlsax.js"></script>
-<script type="text/javascript" src="svgloader.js"></script>
-<script type="text/javascript" src="svgsample.js"></script>
-</head>
-<body onload="init('Google_Logo.svg');" onunload="unload();">
-<h1>SVG Google Logo</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 400px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/gpu2d/svg_java_logo.html b/o3d/samples/gpu2d/svg_java_logo.html
deleted file mode 100644
index b818338..0000000
--- a/o3d/samples/gpu2d/svg_java_logo.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<html>
-<head>
-<title>
-SVG Java Logo
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<!-- Include SVG sample and dependencies -->
-<script type="text/javascript" src="../third_party/xmljs/tinyxmlsax.js"></script>
-<script type="text/javascript" src="svgloader.js"></script>
-<script type="text/javascript" src="svgsample.js"></script>
-</head>
-<body onload="init('javalogo.svg');" onunload="unload();">
-<h1>SVG Java Logo</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 800px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/gpu2d/svg_thin_crescent.html b/o3d/samples/gpu2d/svg_thin_crescent.html
deleted file mode 100644
index b2b9f1f..0000000
--- a/o3d/samples/gpu2d/svg_thin_crescent.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<html>
-<head>
-<title>
-SVG Thin Crescent
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<!-- Include SVG sample and dependencies -->
-<script type="text/javascript" src="../third_party/xmljs/tinyxmlsax.js"></script>
-<script type="text/javascript" src="svgloader.js"></script>
-<script type="text/javascript" src="svgsample.js"></script>
-</head>
-<body onload="init('thincrescent.svg');" onunload="unload();">
-<h1>SVG Thin Crescent</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 800px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/gpu2d/svgloader.js b/o3d/samples/gpu2d/svgloader.js
deleted file mode 100644
index 46e4506..0000000
--- a/o3d/samples/gpu2d/svgloader.js
+++ /dev/null
@@ -1,990 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * @fileoverview Loads SVG files and creates o3djs.gpu2d.Paths from
- * them, inserting all of the associated geometric nodes under the
- * passed Transform.
- * <P>
- * This file depends on the O3D APIs, o3djs.base, o3djs.io, o3djs.math,
- * o3djs.gpu2d, and the XML for &lt;SCRIPT&gt; parser available from
- * http://xmljs.sourceforge.net/ .
- */
-
-/**
- * Constructs a new SVGLoader.
- * @constructor
- */
-function SVGLoader() {
-}
-
-/**
- * Helper function to defer the execution of another function.
- * @param {function(): void} func function to execute later.
- * @private
- */
-function runLater_(func) {
- setTimeout(func, 0);
-}
-
-/**
- * Loads an SVG file at the given URL. The file is downloaded in the
- * background. Graphical objects are allocated in the given Pack, and
- * created materials are registered under the given DrawList,
- * typically the zOrderedDrawList from an
- * o3djs.rendergraph.ViewInfo. The created Shapes are parented under
- * the given Transform. If the optional completion callback is
- * specified, it is called once the file has been downloaded and
- * processed.
- * @param {string} url URL of the SVG file to load.
- * @param {boolean} flipY Whether the Y coordinates should be flipped
- * to better match the 3D coordinate system.
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.DrawList} drawList DrawList to use for created
- * materials.
- * @param {!o3d.Transform} transform Transform under which to place
- * created Shapes.
- * @param {function(string, *): void}
- * opt_completionCallback Optional completion callback which is
- * called after the file has been processed. The URL of the file
- * is passed as the first argument. The second argument indicates
- * whether the file was loaded successfully (true) or not (false).
- * The third argument is an error detail if the file failed to
- * load successfully.
- */
-SVGLoader.prototype.load = function(url,
- flipY,
- pack,
- drawList,
- transform,
- opt_completionCallback) {
- var that = this;
- o3djs.io.loadTextFile(url, function(text, exception) {
- if (exception) {
- runLater_(function() {
- if (opt_completionCallback)
- opt_completionCallback(url,
- false,
- e);
- });
- } else {
- runLater_(function() {
- try {
- that.parse_(text,
- flipY,
- pack,
- drawList,
- transform);
- if (opt_completionCallback)
- opt_completionCallback(url, true, null);
- } catch (e) {
- if (window.console)
- window.console.log(e);
- if (opt_completionCallback)
- opt_completionCallback(url, false, e);
- }
- });
- }
- });
-};
-
-/**
- * Does the parsing of the SVG file.
- * @param {string} svgText the text of the SVG file.
- * @param {boolean} flipY Whether the Y coordinates should be flipped
- * to better match the 3D coordinate system.
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.DrawList} drawList DrawList to use for created
- * materials.
- * @param {!o3d.Transform} transform Transform under which to place
- * created Shapes.
- * @private
- */
-SVGLoader.prototype.parse_ = function(svgText,
- flipY,
- pack,
- drawList,
- transform) {
- /**
- * The pack in which to create shapes, materials, etc.
- * @type {!o3d.Pack}
- * @private
- */
- this.pack_ = pack;
-
- /**
- * Stack of matrices. Entering a new graphics context pushes a new
- * matrix.
- * @type {!Array.<!o3djs.math.Matrix4>}
- * @private
- */
- this.matrixStack_ = [];
-
- /**
- * Stack of transforms. Entering a new graphics context pushes a new
- * transform.
- * @type {!Array.<!o3d.Transform>}
- * @private
- */
- this.transformStack_ = [];
-
- /**
- * The current polygon offset. Each successive path parsed
- * increments this.
- * @type {number}
- * @private
- */
- this.polygonOffset_ = 0;
-
- this.matrixStack_.push(o3djs.math.identity(4));
- this.transformStack_.push(transform);
- var parser = new SAXDriver();
- var eventHandler = new SVGSAXHandler_(this,
- parser,
- flipY,
- pack,
- drawList);
- parser.setDocumentHandler(eventHandler);
- parser.parse(svgText);
-};
-
-/**
- * Returns the current transform.
- * @return {!o3d.Transform}
- * @private
- */
-SVGLoader.prototype.currentTransform_ = function() {
- var len = this.transformStack_.length;
- return this.transformStack_[len - 1];
-};
-
-/**
- * Returns the current matrix.
- * @return {!o3djs.math.Matrix4}
- * @private
- */
-SVGLoader.prototype.currentMatrix_ = function() {
- var len = this.matrixStack_.length;
- return this.matrixStack_[len - 1];
-};
-
-/**
- * Sets the current matrix.
- * @param {!o3djs.math.Matrix4} matrix the new current matrix.
- * @private
- */
-SVGLoader.prototype.setCurrentMatrix_ = function(matrix) {
- var length = this.matrixStack_.length;
- this.matrixStack_[length - 1] = matrix;
- this.transformStack_[length - 1].localMatrix = matrix;
-};
-
-/**
- * Pushes a new transform / matrix pair.
- * @private
- */
-SVGLoader.prototype.pushTransform_ = function() {
- this.matrixStack_.push(o3djs.math.identity(4));
- var xform = this.pack_.createObject('o3d.Transform');
- xform.parent = this.currentTransform_();
- this.transformStack_.push(xform);
-};
-
-/**
- * Pops a transform / matrix pair.
- * @private
- */
-SVGLoader.prototype.popTransform_ = function() {
- this.matrixStack_.pop();
- this.transformStack_.pop();
-};
-
-/**
- * Supports the "matrix" command in the graphics context; not yet
- * implemented.
- * @param {number} a matrix element
- * @param {number} b matrix element
- * @param {number} c matrix element
- * @param {number} d matrix element
- * @param {number} e matrix element
- * @param {number} f matrix element
- * @private
- */
-SVGLoader.prototype.matrix_ = function(a, b, c, d, e, f) {
- // TODO(kbr): implement
- throw 'matrix command not yet implemented';
-};
-
-/**
- * Supports the "translate" command in the graphics context.
- * @param {number} x x translation
- * @param {number} y y translation
- * @private
- */
-SVGLoader.prototype.translate_ = function(x, y) {
- var tmp = o3djs.math.matrix4.translation([x, y, 0]);
- this.setCurrentMatrix_(
- o3djs.math.mulMatrixMatrix(tmp, this.currentMatrix_()));
-};
-
-/**
- * Supports the "scale" command in the graphics context; not yet
- * implemented.
- * @param {number} sx x scale
- * @param {number} sy y scale
- * @private
- */
-SVGLoader.prototype.scale_ = function(sx, sy) {
- var tmp = o3djs.math.matrix4.scaling([sx, sy, 1]);
- this.setCurrentMatrix_(
- o3djs.math.mulMatrixMatrix(tmp, this.currentMatrix_()));
-};
-
-/**
- * Supports the "rotate" command in the graphics context.
- * @param {number} angle angle to rotate, in degrees.
- * @param {number} cx x component of rotation center.
- * @param {number} cy y component of rotation center.
- * @private
- */
-SVGLoader.prototype.rotate_ = function(angle, cx, cy) {
- var rot = o3djs.math.matrix4.rotationZ(o3djs.math.degToRad(angle));
- if (cx || cy) {
- var xlate1 = o3djs.math.matrix4.translation([cx, cy, 0]);
- var xlate2 = o3djs.math.matrix4.translation([-cx, -cy, 0]);
- rot = o3djs.math.mulMatrixMatrix(xlate2, rot);
- rot = o3djs.math.mulMatrixMatrix(rot, xlate1);
- }
- this.setCurrentMatrix_(rot);
-};
-
-/**
- * Supports the "skewX" command in the graphics context; not yet
- * implemented.
- * @param {number} angle skew X angle, in degrees.
- * @private
- */
-SVGLoader.prototype.skewX_ = function(angle) {
- // TODO(kbr): implement
- throw 'skewX command not yet implemented';
-};
-
-/**
- * Supports the "skewY" command in the graphics context; not yet
- * implemented.
- * @param {number} angle skew Y angle, in degrees.
- * @private
- */
-SVGLoader.prototype.skewY_ = function(angle) {
- // TODO(kbr): implement
- throw 'skewY command not yet implemented';
-};
-
-/**
- * Parses the data from an SVG path element, constructing an
- * o3djs.gpu2d.Path from it.
- * @param {string} pathData the path's data (the "d" attribute).
- * @param {number} lineNumber the line number of the current parse,
- * for error reporting.
- * @param {boolean} flipY Whether the Y coordinates should be flipped
- * to better match the 3D coordinate system.
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.DrawList} drawList DrawList to use for created
- * materials.
- * @private
- */
-SVGLoader.prototype.parsePath_ = function(pathData,
- lineNumber,
- flipY,
- pack,
- drawList) {
- var parser = new PathDataParser_(this,
- lineNumber,
- flipY,
- pack,
- drawList);
- var path = parser.parse(pathData);
- if (this.fill_) {
- path.setFill(this.fill_);
- }
- path.setPolygonOffset(-3 * this.polygonOffset_, -4 * this.polygonOffset_);
- ++this.polygonOffset_;
- this.currentTransform_().addShape(path.shape);
-};
-
-/**
- * Parses the style from an SVG path element or graphics context,
- * preparing to set it on the next created o3djs.gpu2d.Path. If it
- * doesn't know how to handle it, the default color of solid black
- * will be used.
- * @param {string} styleData the string containing the "style"
- * attribute.
- * @param {number} lineNumber the line number of the current parse,
- * for error reporting.
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @private
- */
-SVGLoader.prototype.parseStyle_ = function(styleData,
- lineNumber,
- pack) {
- this.fill_ = null;
- var portions = styleData.split(';');
- for (var i = 0; i < portions.length; i++) {
- var keyVal = portions[i].split(':');
- var key = keyVal[0];
- var val = keyVal[1];
- if (key == 'stroke') {
- // TODO(kbr): support strokes
- } else if (key == 'stroke-width') {
- // TODO(kbr): support stroke width
- } else if (key == 'fill') {
- if (val.charAt(0) == '#') {
- var r = parseInt(val.substr(1, 2), 16);
- var g = parseInt(val.substr(3, 2), 16);
- var b = parseInt(val.substr(5, 2), 16);
- var fill = o3djs.gpu2d.createColor(pack,
- r / 255.0,
- g / 255.0,
- b / 255.0,
- 1.0);
- this.fill_ = fill;
- } else if (val.substr(0, 4) == 'rgb(' &&
- val.charAt(val.length - 1) == ')') {
- var rgbStrings = val.substr(4, val.length - 5).split(',');
- var r = parseInt(rgbStrings[0]);
- var g = parseInt(rgbStrings[1]);
- var b = parseInt(rgbStrings[2]);
- var fill = o3djs.gpu2d.createColor(pack,
- r / 255.0,
- g / 255.0,
- b / 255.0,
- 1.0);
- this.fill_ = fill;
- }
- }
- }
-};
-
-/**
- * Parses the data from an SVG transform attribute, storing the result
- * in the current o3d.Transform.
- * @param {string} data the transform's data.
- * @param {number} lineNumber the line number of the current parse,
- * for error reporting.
- * @private
- */
-SVGLoader.prototype.parseTransform_ = function(data,
- lineNumber) {
- var parser = new TransformDataParser_(this,
- lineNumber);
- parser.parse(data);
-};
-
-//----------------------------------------------------------------------
-// BaseDataParser -- base class for parsers dealing with SVG data
-
-/**
- * Base class for parsers dealing with SVG data.
- * @param {SVGLoader} loader The SVG loader.
- * @param {number} lineNumber the line number of the current parse,
- * for error reporting.
- * @constructor
- * @private
- */
-BaseDataParser_ = function(loader,
- lineNumber) {
- this.loader_ = loader;
- this.lineNumber_ = lineNumber;
- this.putBackToken_ = null;
- this.singleLetterWords_ = false;
-}
-
-/**
- * Types of tokens.
- * @enum
- * @private
- */
-BaseDataParser_.TokenTypes = {
- WORD: 1,
- NUMBER: 2,
- LPAREN: 3,
- RPAREN: 4,
- NONE: 5
-};
-
-/**
- * Parses the given SVG data.
- * @param {string} data the SVG data.
- * @private
- */
-BaseDataParser_.prototype.parse = function(data) {
- var parseState = {
- // First index of current token
- firstIndex: 0,
- // Last index of current token (exclusive)
- lastIndex: 0,
- // Line number of the path element
- lineNumber: this.lineNumber_
- };
- var done = false;
- while (!done) {
- var tok = this.nextToken_(parseState, data);
- switch (tok.kind) {
- case BaseDataParser_.TokenTypes.WORD:
- // Allow the parsing to override the specification of the last
- // command
- this.setLastCommand_(tok.val);
- this.parseWord_(parseState, data, tok.val);
- break;
- case BaseDataParser_.TokenTypes.NUMBER:
- // Assume this is a repeat of the last command
- this.putBack_(tok);
- this.parseWord_(parseState, data, this.lastCommand_);
- break;
- default:
- done = true;
- break;
- }
- }
-};
-
-/**
- * Sets the last parsed command.
- * @param {string} command the last parsed command.
- * @private
- */
-BaseDataParser_.prototype.setLastCommand_ = function(command) {
- this.lastCommand_ = command;
-};
-
-/**
- * Returns true if the given character is a whitespace or separator.
- * @param {string} c the character to test.
- * @private
- */
-BaseDataParser_.prototype.isWhitespaceOrSeparator_ = function(c) {
- return (c == ',' ||
- c == ' ' ||
- c == '\t' ||
- c == '\r' ||
- c == '\n');
-};
-
-/**
- * Puts back a token to be consumed during the next iteration. There
- * is only a one-token put back buffer.
- * @param {!{kind: BaseDataParser_TokenTypes, val: string}} tok The
- * token to put back.
- * @private
- */
-BaseDataParser_.prototype.putBack_ = function(tok) {
- this.putBackToken_ = tok;
-};
-
-/**
- * Returns the next token.
- * @param {!{firstIndex: number, lastIndex: number, lineNumber:
- * number}} parseState The parse state.
- * @param {string} data The data being parsed.
- * @private
- */
-BaseDataParser_.prototype.nextToken_ = function(parseState, data) {
- if (this.putBackToken_) {
- var tmp = this.putBackToken_;
- this.putBackToken_ = null;
- return tmp;
- }
- parseState.firstIndex = parseState.lastIndex;
- if (parseState.firstIndex < data.length) {
- // Eat whitespace and separators
- while (true) {
- var curChar = data.charAt(parseState.firstIndex);
- if (this.isWhitespaceOrSeparator_(curChar)) {
- ++parseState.firstIndex;
- if (parseState.firstIndex >= data.length)
- break;
- } else {
- break;
- }
- }
- }
- if (parseState.firstIndex >= data.length)
- return { kind: BaseDataParser_.TokenTypes.NONE, val: null };
- parseState.lastIndex = parseState.firstIndex;
- // Surround the next token
- var curChar = data.charAt(parseState.lastIndex++);
- if (curChar == '-' ||
- curChar == '.' ||
- (curChar >= '0' && curChar <= '9')) {
- while (true) {
- var t = data.charAt(parseState.lastIndex);
- if (t == '.' ||
- (t >= '0' && t <= '9')) {
- ++parseState.lastIndex;
- } else {
- break;
- }
- }
- // See whether an exponential format follows: i.e. 136e-3
- if (data.charAt(parseState.lastIndex) == 'e') {
- ++parseState.lastIndex;
- if (data.charAt(parseState.lastIndex) == '-') {
- ++parseState.lastIndex;
- }
- while (true) {
- var t = data.charAt(parseState.lastIndex);
- if (t >= '0' && t <= '9') {
- ++parseState.lastIndex;
- } else {
- break;
- }
- }
- }
- return { kind: BaseDataParser_.TokenTypes.NUMBER,
- val: parseFloat(data.substring(parseState.firstIndex,
- parseState.lastIndex)) };
- } else if ((curChar >= 'A' && curChar <= 'Z') ||
- (curChar >= 'a' && curChar <= 'z')) {
- if (!this.singleLetterWords_) {
- // Consume all adjacent letters -- this is satisfactory for the
- // grammar of the "transform" attribute, but not the "d"
- // attribute
- while (true) {
- var t = data.charAt(parseState.lastIndex);
- if ((t >= 'A' && t <= 'Z') ||
- (t >= 'a' && t <= 'z')) {
- ++parseState.lastIndex;
- } else {
- break;
- }
- }
- }
- return { kind: BaseDataParser_.TokenTypes.WORD,
- val: data.substring(parseState.firstIndex,
- parseState.lastIndex) };
- } else if (curChar == '(') {
- return { kind: BaseDataParser_.TokenTypes.LPAREN,
- val: data.substring(parseState.firstIndex,
- parseState.lastIndex) };
- } else if (curChar == ')') {
- return { kind: BaseDataParser_.TokenTypes.RPAREN,
- val: data.substring(parseState.firstIndex,
- parseState.lastIndex) };
- }
- throw 'Expected number or word at line ' + parseState.lineNumber;
-};
-
-/**
- * Verifies that the next token is of the given kind, throwing an
- * exception if not.
- * @param {!{firstIndex: number, lastIndex: number, lineNumber:
- * number}} parseState The parse state.
- * @param {string} data The data being parsed.
- * @param {BaseDataParser_TokenTypes} tokenType The expected token
- * type.
- */
-BaseDataParser_.prototype.expect_ = function(parseState, data, tokenType) {
- var tok = this.nextToken_(parseState, data);
- if (tok.kind != tokenType) {
- throw 'At line number ' + parseState.lineNumber +
- ': expected token type ' + tokenType +
- ', got ' + tok.kind;
- }
-};
-
-/**
- * Parses a series of floating-point numbers.
- * @param {!{firstIndex: number, lastIndex: number, lineNumber:
- * number}} parseState The parse state.
- * @param {string} data The data being parsed.
- * @param {number} numFloats The number of floating-point numbers to
- * parse.
- * @return {!Array.<number>}
- * @private
- */
-BaseDataParser_.prototype.parseFloats_ = function(parseState,
- data,
- numFloats) {
- var result = [];
- for (var i = 0; i < numFloats; ++i) {
- var tok = this.nextToken_(parseState, data);
- if (tok.kind != BaseDataParser_.TokenTypes.NUMBER)
- throw "Expected number at line " +
- parseState.lineNumber +
- ", character " +
- parseState.firstIndex +
- "; got \"" + tok.val + "\"";
- result.push(tok.val);
- }
- return result;
-};
-
-//----------------------------------------------------------------------
-// PathDataParser
-
-/**
- * Parser for the data in an SVG path.
- * @param {SVGLoader} loader The SVG loader.
- * @param {number} lineNumber the line number of the current parse,
- * for error reporting.
- * @param {boolean} flipY Whether the Y coordinates should be flipped
- * to better match the 3D coordinate system.
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.DrawList} drawList DrawList to use for created
- * materials.
- * @constructor
- * @extends {BaseDataParser_}
- * @private
- */
-PathDataParser_ = function(loader,
- lineNumber,
- flipY,
- pack,
- drawList) {
- BaseDataParser_.call(this, loader, lineNumber);
- this.flipY_ = flipY;
- this.pack_ = pack;
- this.drawList_ = drawList;
- this.curX_ = 0;
- this.curY_ = 0;
- this.singleLetterWords_ = true;
-};
-
-o3djs.base.inherit(PathDataParser_, BaseDataParser_);
-
-/**
- * Parses data from an SVG path.
- * @param {string} data SVG path data.
- * @private
- */
-PathDataParser_.prototype.parse = function(data) {
- this.path_ = o3djs.gpu2d.createPath(this.pack_, this.drawList_);
- BaseDataParser_.prototype.parse.call(this, data);
- this.path_.update();
- return this.path_;
-};
-
-/**
- * Parses the data for the given word (command) from the path data.
- * @param {!{firstIndex: number, lastIndex: number, lineNumber:
- * number}} parseState The parse state.
- * @param {string} data The data being parsed.
- * @param {string} word The character for the current command.
- * @private
- */
-PathDataParser_.prototype.parseWord_ = function(parseState,
- data,
- word) {
- if (word == 'M' || word == 'm') {
- var absolute = (word == 'M');
- var coords = this.parseFloats_(parseState, data, 2);
- this.doYFlip_(coords);
- if (!absolute) {
- this.makeAbsolute_(coords);
- }
- this.path_.moveTo(coords[0], coords[1]);
- this.curX_ = coords[0];
- this.curY_ = coords[1];
- // This is a horrible portion of the SVG spec
- if (absolute) {
- this.setLastCommand_('L');
- } else {
- this.setLastCommand_('l');
- }
- } else if (word == 'L' || word == 'l') {
- var absolute = (word == 'L');
- var coords = this.parseFloats_(parseState, data, 2);
- this.doYFlip_(coords);
- if (!absolute) {
- this.makeAbsolute_(coords);
- }
- this.path_.lineTo(coords[0], coords[1]);
- this.curX_ = coords[0];
- this.curY_ = coords[1];
- } else if (word == 'H' || word == 'h') {
- var absolute = (word == 'H');
- var coords = this.parseFloats_(parseState, data, 1);
- if (!absolute) {
- coords[0] += this.curX_;
- }
- this.path_.lineTo(coords[0], this.curY_);
- this.curX_ = coords[0];
- } else if (word == 'V' || word == 'v') {
- var absolute = (word == 'V');
- var coords = this.parseFloats_(parseState, data, 1);
- if (this.flipY_) {
- coords[0] = -coords[0];
- }
- if (!absolute) {
- coords[0] += this.curY_;
- }
- this.path_.lineTo(this.curX_, coords[0]);
- this.curY_ = coords[0];
- } else if (word == 'Q' || word == 'q') {
- var absolute = (word == 'Q');
- var coords = this.parseFloats_(parseState, data, 4);
- this.doYFlip_(coords);
- if (!absolute) {
- this.makeAbsolute_(coords);
- }
- this.path_.quadraticTo(coords[0], coords[1], coords[2], coords[3]);
- this.curX_ = coords[2];
- this.curY_ = coords[3];
- // TODO(kbr): support shorthand quadraticTo (T/t)
- } else if (word == 'C' || word == 'c') {
- var absolute = (word == 'C');
- var coords = this.parseFloats_(parseState, data, 6);
- this.doYFlip_(coords);
- if (!absolute) {
- this.makeAbsolute_(coords);
- }
- this.path_.cubicTo(coords[0], coords[1],
- coords[2], coords[3],
- coords[4], coords[5]);
- this.curX_ = coords[4];
- this.curY_ = coords[5];
- // TODO(kbr): support shorthand cubicTo (S/s)
- } else if (word == 'Z' || word == 'z') {
- this.path_.close();
- } else {
- throw 'Unknown word ' + word + ' at line ' + parseState.lineNumber;
- }
-};
-
-/**
- * Negates the Y coordinates of the passed 2D coordinate list if the
- * flipY flag is set on this parser.
- * @param {!Array.<number>} coords Array of 2D coordinates.
- * @private
- */
-
-PathDataParser_.prototype.doYFlip_ = function(coords) {
- if (this.flipY_) {
- for (var i = 0; i < coords.length; i += 2) {
- coords[i+1] = -coords[i+1];
- }
- }
-};
-
-/**
- * Transforms relative coordinates to absolute coordinates.
- * @param {!Array.<number>} coords Array of 2D coordinates.
- * @private
- */
-PathDataParser_.prototype.makeAbsolute_ = function(coords) {
- for (var i = 0; i < coords.length; i += 2) {
- coords[i] += this.curX_;
- coords[i+1] += this.curY_;
- }
-};
-
-//----------------------------------------------------------------------
-// TransformDataParser
-
-/**
- * Parser for the data in an SVG transform.
- * @param {SVGLoader} loader The SVG loader.
- * @param {number} lineNumber the line number of the current parse,
- * for error reporting.
- * @constructor
- * @extends {BaseDataParser_}
- * @private
- */
-TransformDataParser_ = function(loader,
- lineNumber) {
- BaseDataParser_.call(this, loader, lineNumber);
-};
-
-o3djs.base.inherit(TransformDataParser_, BaseDataParser_);
-
-/**
- * Parses the data for the given word (command) from the path data.
- * @param {!{firstIndex: number, lastIndex: number, lineNumber:
- * number}} parseState The parse state.
- * @param {string} data The data being parsed.
- * @param {string} word The character for the current command.
- * @private
- */
-TransformDataParser_.prototype.parseWord_ = function(parseState,
- data,
- word) {
- if (!((word == 'matrix') ||
- (word == 'translate') ||
- (word == 'scale') ||
- (word == 'rotate') ||
- (word == 'skewX') ||
- (word == 'skewY'))) {
- throw 'Unknown transform definition ' + word +
- ' at line ' + parseState.lineNumber;
- }
-
- this.expect_(parseState, data, BaseDataParser_.TokenTypes.LPAREN);
- // Some of the commands take a variable number of arguments
- var floats;
- switch (word) {
- case 'matrix':
- floats = this.parseFloats_(parseState, data, 6);
- this.loader_.matrix_(floats[0], floats[1],
- floats[2], floats[3],
- floats[4], floats[5]);
- break;
- case 'translate':
- floats = this.parseFloats_(parseState, data, 1);
- var tok = this.nextToken_(parseState, data);
- if (tok.kind == BaseDataParser_.TokenTypes.NUMBER) {
- floats.push(tok.val);
- } else {
- this.putBack_(tok);
- floats.push(0);
- }
- this.loader_.translate_(floats[0], floats[1]);
- break;
- case 'scale':
- floats = this.parseFloats_(parseState, data, 1);
- var tok = this.nextToken_(parseState, data);
- if (tok.kind == BaseDataParser_.TokenTypes.NUMBER) {
- floats.push(tok.val);
- } else {
- this.putBack_(tok);
- floats.push(floats[0]);
- }
- this.loader_.scale_(floats[0], floats[1]);
- break;
- case 'rotate':
- floats = this.parseFloats_(parseState, data, 1);
- var tok = this.nextToken_(parseState, data);
- this.putBack_(tok);
- if (tok.kind == BaseDataParser_.TokenTypes.NUMBER) {
- floats = floats.concat(this.parseFloats_(parseState, data, 2));
- } else {
- floats.push(0);
- floats.push(0);
- }
- this.loader_.rotate_(floats[0], floats[1], floats[2]);
- break;
- case 'skewX':
- floats = this.parseFloats_(parseState, data, 1);
- this.loader_.skewX_(floats[0]);
- break;
- case 'skewY':
- floats = this.parseFloats_(parseState, data, 1);
- this.loader_.skewY_(floats[0]);
- break;
- default:
- throw 'Unknown word ' + word + ' at line ' + parseState.lineNumber;
- }
- this.expect_(parseState, data, BaseDataParser_.TokenTypes.RPAREN);
-};
-
-//----------------------------------------------------------------------
-// SVGSaxHandler
-
-/**
- * Handler which integrates with the XMLJS SAX parser.
- * @param {!SVGLoader} loader The SVG loader.
- * @param {Object} parser the XMLJS SAXDriver.
- * @param {boolean} flipY Whether the Y coordinates should be flipped
- * to better match the 3D coordinate system.
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.DrawList} drawList DrawList to use for created
- * materials.
- * @constructor
- * @private
- */
-SVGSAXHandler_ = function(loader, parser, flipY, pack, drawList) {
- this.loader_ = loader;
- this.parser_ = parser;
- this.flipY_ = flipY;
- this.pack_ = pack;
- this.drawList_ = drawList;
-};
-
-/**
- * Handler for the start of an element.
- * @param {string} name the name of the element.
- * @param {Object} attributes the XMLJS attributes object.
- * @private
- */
-SVGSAXHandler_.prototype.startElement = function(name, attributes) {
- switch (name) {
- case 'path':
- var pushed = false;
- var transformData = attributes.getValueByName('transform');
- if (transformData) {
- pushed = true;
- this.loader_.pushTransform_();
- this.loader_.parseTransform_(transformData,
- this.parser_.getLineNumber());
- }
- if (attributes.getValueByName('style')) {
- this.loader_.parseStyle_(attributes.getValueByName('style'),
- this.parser_.getLineNumber(),
- this.pack_);
- }
- this.loader_.parsePath_(attributes.getValueByName('d'),
- this.parser_.getLineNumber(),
- this.flipY_,
- this.pack_,
- this.drawList_);
- if (pushed) {
- this.loader_.popTransform_();
- }
- break;
- case 'g':
- this.loader_.pushTransform_();
- if (attributes.getValueByName('style')) {
- this.loader_.parseStyle_(attributes.getValueByName('style'),
- this.parser_.getLineNumber(),
- this.pack_);
- }
- var data = attributes.getValueByName('transform');
- if (data) {
- this.loader_.parseTransform_(data,
- this.parser_.getLineNumber());
- }
- break;
- default:
- // No other commands supported yet
- break;
- }
-};
-
-/**
- * Handler for the end of an element.
- * @param {string} name the name of the element.
- * @private
- */
-SVGSAXHandler_.prototype.endElement = function(name) {
- if (name == 'g') {
- this.loader_.popTransform_();
- }
-};
-
diff --git a/o3d/samples/gpu2d/svgsample.js b/o3d/samples/gpu2d/svgsample.js
deleted file mode 100644
index c041c74..0000000
--- a/o3d/samples/gpu2d/svgsample.js
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * @fileoverview Framework for samples that load and display SVG files.
- *
- * This is purely *example* code, showing how to use the SVG loader.
- */
-
-o3djs.require('o3djs.cameracontroller');
-o3djs.require('o3djs.event');
-o3djs.require('o3djs.gpu2d');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.picking');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.util');
-// Also requires the following files to be loaded by the containing page:
-// - svgloader.js
-// - ../third_party/xmljs/tinyxmlsax.js
-
-// Globals
-var g_filename;
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_o3dElement;
-var g_finished = false; // for selenium testing.
-var g_clientWidth;
-var g_clientHeight;
-var g_cameraController;
-
-if (!("console" in window)) {
- var logElement = document.getElementById('log');
- window.console =
- { log: function(s) {
- if (logElement) {
- logElement.innerHTML = logElement.innerHTML + "<span>" +
- s.toString() + "</span><br>";
- }
- }
- };
-}
-
-/**
- * Initializes the sample with the given URL.
- * @param {string} filename The URL of the SVG file to load.
- */
-function init(filename) {
- g_filename = filename;
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-/**
- * Completes initialization of the sample.
- * @param {!Array.<!Element>} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3dElement = o3dElement;
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set the background color to light gray.
- g_viewInfo.clearBuffer.clearColor = [0.8, 0.8, 0.8, 1];
-
- // Load the file.
- var loader = new SVGLoader();
- loader.load(g_filename,
- true,
- g_pack,
- g_viewInfo.zOrderedDrawList,
- g_client.root,
- function(url, success, detail) {
- if (!success) {
- window.console.log('Failed to load ' + url + ": " + detail);
- } else {
- var tmpManager =
- o3djs.picking.createPickManager(g_client.root);
- tmpManager.update();
- var bbox = tmpManager.getTransformInfo(g_client.root).
- getBoundingBox();
- g_cameraController.viewAll(bbox,
- g_client.width / g_client.height);
- updateViewAndProjectionMatrices();
- }
- });
-
- // Set up the view and projection transformations.
- initContext();
-
- // Set up event handlers for mouse interaction.
- o3djs.event.addEventListener(o3dElement, 'mousedown', onMouseDown);
- o3djs.event.addEventListener(o3dElement, 'mousemove', onMouseMove);
- o3djs.event.addEventListener(o3dElement, 'mouseup', onMouseUp);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Event handler that gets called when a mouse click takes place in
- * the O3D element. It changes the state of the camera controller
- * based on which modifier keys are pressed.
- * @param {!Event} e The mouse down event.
- */
-function onMouseDown(e) {
- if (e.button == 0) {
- if (!e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.MOVE_CENTER_IN_VIEW_PLANE, e.x, e.y);
- } else if (e.metaKey || e.altKey) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.SPIN_ABOUT_CENTER, e.x, e.y);
- } else if (!e.shiftKey && e.ctrlKey) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.DOLLY_IN_OUT, e.x, e.y);
- } else if (e.shiftKey && !e.ctrlKey) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.ZOOM_IN_OUT, e.x, e.y);
- } else if (e.shiftKey && e.ctrlKey) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.DOLLY_ZOOM, e.x, e.y);
- }
- }
-}
-
-/**
- * Event handler that gets called when a mouse move event takes place
- * in the O3D element. It tells the camera controller that the mouse
- * has moved.
- * @param {!Event} e The mouse move event.
- */
-function onMouseMove(e) {
- g_cameraController.mouseMoved(e.x, e.y);
-}
-
-/**
- * Event handler that gets called when a mouse up event takes place in
- * the O3D element. It tells the camera controller that the mouse has
- * been released.
- * @param {!Event} e The mouse up event.
- */
-function onMouseUp(e) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.NONE, e.x, e.y);
-}
-
-/**
- * Sets up reasonable view and projection matrices.
- */
-function initContext() {
- // Set up our CameraController.
- g_cameraController = o3djs.cameracontroller.createCameraController(
- [0, 0, 0], // centerPos
- 500, // backpedal
- 0, // heightAngle
- 0, // rotationAngle
- g_math.degToRad(15), // fieldOfViewAngle
- updateViewAndProjectionMatrices); // opt_onChange
- g_cameraController.distancePerUnit = 100.0;
-
- updateViewAndProjectionMatrices();
-}
-
-/**
- * Updates the view and projection matrices.
- */
-function updateViewAndProjectionMatrices() {
- g_viewInfo.drawContext.view = g_cameraController.calculateViewMatrix();
-
- // Set up a perspective transformation for the projection.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_cameraController.fieldOfViewAngle * 2, // Frustum angle.
- g_o3dElement.clientWidth / g_o3dElement.clientHeight, // Aspect ratio.
- 1, // Near plane.
- 5000); // Far plane.
-}
-
diff --git a/o3d/samples/gpu2d/thincrescent.svg b/o3d/samples/gpu2d/thincrescent.svg
deleted file mode 100644
index e31717d..0000000
--- a/o3d/samples/gpu2d/thincrescent.svg
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-
-<svg
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- version="1.1"
- width="500"
- height="500"
- id="svg4075">
- <defs
- id="defs4077" />
- <g
- transform="translate(0,-552.36218)"
- id="layer1">
- <path
- d="M 221,60 C -330,318 813.95124,298.69865 237,60 754,300 -275,299 221,60 z"
- transform="translate(0,552.36218)"
- id="path4085"
- style="fill:#000000;fill-opacity:1;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
- </g>
-</svg>
diff --git a/o3d/samples/hellocube-colors-glsl.html b/o3d/samples/hellocube-colors-glsl.html
deleted file mode 100644
index 10cf735..0000000
--- a/o3d/samples/hellocube-colors-glsl.html
+++ /dev/null
@@ -1,343 +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 sample creates an O3D area with a spinning cube. The user
-can change the color of the cube by clicking on one of the buttons that appear
-at the bottom of the page. This sample demonstrates how to use O3D Params
-to change the values of uniform parameters used by shaders.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Hello Square Colors: Getting started with O3D, take 2.
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// Run the init() function once the page has finished loading.
-// Run the uninit() function when the page has is unloaded.
-window.onload = init;
-window.onunload = uninit;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_pack;
-var g_client;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-
-var g_cubeTransform;
-var g_cubeColorParam;
-
-/**
- * Changes the color of the cube.
- * @param red red component of the color
- * @param green green component of the color
- * @param blue blue component of the color
- */
-function changeColor(red, green, blue) {
- // Set the rgb color values and alpha = 1
- g_cubeColorParam.value = [red, green, blue, 1];
-}
-
-/**
- * Creates an O3D shape representing a cube. The shape consists of
- * a single primitive with eight vertices and 12 triangles (two for each face
- * of the cube).
- * @param {o3d.Material} material the material used by the primitive.
- * @return {o3d.Shape} The Shape object created.
- */
-function createCube(material) {
- // Create a Shape object for the mesh.
- var cubeShape = g_pack.createObject('Shape');
-
- // Create the Primitive that will contain the geometry data for
- // the cube.
- var cubePrimitive = g_pack.createObject('Primitive');
-
- // Create a StreamBank to hold the streams of vertex data.
- var streamBank = g_pack.createObject('StreamBank');
-
- // Assign the material that was passed in to the primitive.
- cubePrimitive.material = material;
-
- // Assign the Primitive to the Shape.
- cubePrimitive.owner = cubeShape;
-
- // Assign the StreamBank to the Primitive.
- cubePrimitive.streamBank = streamBank;
-
- // The cube is made of 12 triangles. There's eight vertices in total which
- // are shared between the face triangles.
- cubePrimitive.primitiveType = g_o3d.Primitive.TRIANGLELIST;
- cubePrimitive.numberPrimitives = 12; // 12 triangles
- cubePrimitive.numberVertices = 8; // 8 vertices in total
-
- // Generate the draw element for the cube primitive.
- cubePrimitive.createDrawElement(g_pack, null);
-
- // Create a javascript array that stores the X, Y and Z coordinates of each
- // of the 8 corners of the cube.
- var positionArray = [
- -0.5, -0.5, 0.5, // vertex 0
- 0.5, -0.5, 0.5, // vertex 1
- -0.5, 0.5, 0.5, // vertex 2
- 0.5, 0.5, 0.5, // vertex 3
- -0.5, 0.5, -0.5, // vertex 4
- 0.5, 0.5, -0.5, // vertex 5
- -0.5, -0.5, -0.5, // vertex 6
- 0.5, -0.5, -0.5 // vertex 7
- ];
-
- // The following array defines how vertices are to be put together to form
- // the triangles that make up the cube's faces. In the index array, every
- // three elements define a triangle. So for example vertices 0, 1 and 2
- // make up the first triangle, vertices 2, 1 and 3 the second one, etc.
- var indicesArray = [
- 0, 1, 2, // face 1
- 2, 1, 3,
- 2, 3, 4, // face 2
- 4, 3, 5,
- 4, 5, 6, // face 3
- 6, 5, 7,
- 6, 7, 0, // face 4
- 0, 7, 1,
- 1, 7, 3, // face 5
- 3, 7, 5,
- 6, 0, 4, // face 6
- 4, 0, 2
- ];
-
- // Create buffers containing the vertex data.
- var positionsBuffer = g_pack.createObject('VertexBuffer');
- var positionsField = positionsBuffer.createField('FloatField', 3);
- positionsBuffer.set(positionArray);
-
- var indexBuffer = g_pack.createObject('IndexBuffer');
- indexBuffer.set(indicesArray);
-
- // Associate the positions Buffer with the StreamBank.
- streamBank.setVertexStream(
- g_o3d.Stream.POSITION, // semantic: This stream stores vertex positions
- 0, // semantic index: First (and only) position stream
- positionsField, // field: the field this stream uses.
- 0); // start_index: How many elements to skip in the
- // field.
-
- // Associate the triangle indices Buffer with the primitive.
- cubePrimitive.indexBuffer = indexBuffer;
-
- return cubeShape;
-}
-
-/**
- * This method gets called every time O3D renders a frame. Here's where
- * we update the cube's transform to make it spin.
- * @param {o3d.RenderEvent} renderEvent The render event object that gives
- * us the elapsed time since the last time a frame was rendered.
- */
-function renderCallback(renderEvent) {
- g_clock += renderEvent.elapsedTime * g_timeMult;
- // Rotate the cube around the Y axis.
- g_cubeTransform.identity();
- g_cubeTransform.rotateY(2.0 * g_clock);
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, creates the cube and sets up the transform and
- * render graphs.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_client = o3dElement.client;
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- var viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set up a perspective projection.
- viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree fov.
- g_client.width / g_client.height,
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // cube is located.
- viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 1, 5], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- // Create an Effect object and initialize it using the shaders from the
- // text area.
- var cubeEffect = g_pack.createObject('Effect');
- var shaderString = document.getElementById('effect').value;
- cubeEffect.loadFromFXString(shaderString);
-
- // Create a Material for the mesh.
- var cubeMaterial = g_pack.createObject('Material');
-
- // Set the material's drawList.
- cubeMaterial.drawList = viewInfo.performanceDrawList;
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shaders to use.
- cubeMaterial.effect = cubeEffect;
-
- // Create an O3D Param on the material for every uniform used by the
- // shader.
- cubeEffect.createUniformParameters(cubeMaterial);
-
- // Get the color parameter from the material and set its value to red.
- g_cubeColorParam = cubeMaterial.getParam('color');
- g_cubeColorParam.value = [1, 0, 0, 1];
-
- // Create the Shape for the cube mesh and assign its material.
- var cubeShape = createCube(cubeMaterial);
-
- // Create a new transform and parent the Shape under it.
- g_cubeTransform = g_pack.createObject('Transform');
- g_cubeTransform.addShape(cubeShape);
-
- // Parent the cube's transform to the client root.
- g_cubeTransform.parent = g_client.root;
-
- // Set our render callback for animation.
- // This sets a function to be executed every time a frame is rendered.
- g_client.setRenderCallback(renderCallback);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Hello Square: Colors</h1>
-This example shows how to use parameters to the color output of a shader.
-<br/>
-
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-
-<form name="default_form" action="#" method="get">
- <p>
- Change color:
- <input type="button" value="Red" onclick="changeColor(1,0,0);" />
- <input type="button" value="Green" onclick="changeColor(0,1,0);" />
- <input type="button" value="Blue" onclick="changeColor(0,0,1);" />
- <input type="button" value="Yellow" onclick="changeColor(1,1,0);" />
- <input type="button" value="Cyan" onclick="changeColor(0,1,1);" />
- <input type="button" value="Purple" onclick="changeColor(1,0,1);" />
- <input type="button" value="White" onclick="changeColor(1,1,1);" />
- </p>
-</form>
-
-<!-- Don't render the textarea -->
-<div style="display:none">
-<!-- Start of effect -->
-<textarea id="effect">
- // World View Projection matrix that will transform the input vertices
- // to screen space.
- uniform mat4 worldViewProjection;
-
- // input parameters for our vertex shader
- attribute vec4 position;
-
- /**
- * The vertex shader simply transforms the input vertices to screen space.
- */
- void main() {
- // Multiply the vertex positions by the worldViewProjection matrix to
- // transform them to screen space.
- gl_Position = worldViewProjection * position;
- }
-
-// This hack his here for now since O3D only allows one string
-// to be passed to Effect::loadFromFXString
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
- // Color to draw with.
- uniform vec4 color;
-
- /**
- * This pixel shader just returns the color red.
- */
- void main() {
- gl_FragColor = color;
- }
-
- // Here we tell our effect file *which* functions are
- // our vertex and pixel shaders.
-
-</textarea>
-<!-- End of effect -->
-</div>
-</body>
-</html>
diff --git a/o3d/samples/hellocube-colors.html b/o3d/samples/hellocube-colors.html
deleted file mode 100644
index aa3355f..0000000
--- a/o3d/samples/hellocube-colors.html
+++ /dev/null
@@ -1,352 +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 sample creates an O3D area with a spinning cube. The user
-can change the color of the cube by clicking on one of the buttons that appear
-at the bottom of the page. This sample demonstrates how to use O3D Params
-to change the values of uniform parameters used by shaders.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Hello Square Colors: Getting started with O3D, take 2.
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// Run the init() function once the page has finished loading.
-// Run the uninit() function when the page has is unloaded.
-window.onload = init;
-window.onunload = uninit;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_pack;
-var g_client;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-
-var g_cubeTransform;
-var g_cubeColorParam;
-
-/**
- * Changes the color of the cube.
- * @param red red component of the color
- * @param green green component of the color
- * @param blue blue component of the color
- */
-function changeColor(red, green, blue) {
- // Set the rgb color values and alpha = 1
- g_cubeColorParam.value = [red, green, blue, 1];
-}
-
-/**
- * Creates an O3D shape representing a cube. The shape consists of
- * a single primitive with eight vertices and 12 triangles (two for each face
- * of the cube).
- * @param {o3d.Material} material the material used by the primitive.
- * @return {o3d.Shape} The Shape object created.
- */
-function createCube(material) {
- // Create a Shape object for the mesh.
- var cubeShape = g_pack.createObject('Shape');
-
- // Create the Primitive that will contain the geometry data for
- // the cube.
- var cubePrimitive = g_pack.createObject('Primitive');
-
- // Create a StreamBank to hold the streams of vertex data.
- var streamBank = g_pack.createObject('StreamBank');
-
- // Assign the material that was passed in to the primitive.
- cubePrimitive.material = material;
-
- // Assign the Primitive to the Shape.
- cubePrimitive.owner = cubeShape;
-
- // Assign the StreamBank to the Primitive.
- cubePrimitive.streamBank = streamBank;
-
- // The cube is made of 12 triangles. There's eight vertices in total which
- // are shared between the face triangles.
- cubePrimitive.primitiveType = g_o3d.Primitive.TRIANGLELIST;
- cubePrimitive.numberPrimitives = 12; // 12 triangles
- cubePrimitive.numberVertices = 8; // 8 vertices in total
-
- // Generate the draw element for the cube primitive.
- cubePrimitive.createDrawElement(g_pack, null);
-
- // Create a javascript array that stores the X, Y and Z coordinates of each
- // of the 8 corners of the cube.
- var positionArray = [
- -0.5, -0.5, 0.5, // vertex 0
- 0.5, -0.5, 0.5, // vertex 1
- -0.5, 0.5, 0.5, // vertex 2
- 0.5, 0.5, 0.5, // vertex 3
- -0.5, 0.5, -0.5, // vertex 4
- 0.5, 0.5, -0.5, // vertex 5
- -0.5, -0.5, -0.5, // vertex 6
- 0.5, -0.5, -0.5 // vertex 7
- ];
-
- // The following array defines how vertices are to be put together to form
- // the triangles that make up the cube's faces. In the index array, every
- // three elements define a triangle. So for example vertices 0, 1 and 2
- // make up the first triangle, vertices 2, 1 and 3 the second one, etc.
- var indicesArray = [
- 0, 1, 2, // face 1
- 2, 1, 3,
- 2, 3, 4, // face 2
- 4, 3, 5,
- 4, 5, 6, // face 3
- 6, 5, 7,
- 6, 7, 0, // face 4
- 0, 7, 1,
- 1, 7, 3, // face 5
- 3, 7, 5,
- 6, 0, 4, // face 6
- 4, 0, 2
- ];
-
- // Create buffers containing the vertex data.
- var positionsBuffer = g_pack.createObject('VertexBuffer');
- var positionsField = positionsBuffer.createField('FloatField', 3);
- positionsBuffer.set(positionArray);
-
- var indexBuffer = g_pack.createObject('IndexBuffer');
- indexBuffer.set(indicesArray);
-
- // Associate the positions Buffer with the StreamBank.
- streamBank.setVertexStream(
- g_o3d.Stream.POSITION, // semantic: This stream stores vertex positions
- 0, // semantic index: First (and only) position stream
- positionsField, // field: the field this stream uses.
- 0); // start_index: How many elements to skip in the
- // field.
-
- // Associate the triangle indices Buffer with the primitive.
- cubePrimitive.indexBuffer = indexBuffer;
-
- return cubeShape;
-}
-
-/**
- * This method gets called every time O3D renders a frame. Here's where
- * we update the cube's transform to make it spin.
- * @param {o3d.RenderEvent} renderEvent The render event object that gives
- * us the elapsed time since the last time a frame was rendered.
- */
-function renderCallback(renderEvent) {
- g_clock += renderEvent.elapsedTime * g_timeMult;
- // Rotate the cube around the Y axis.
- g_cubeTransform.identity();
- g_cubeTransform.rotateY(2.0 * g_clock);
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, creates the cube and sets up the transform and
- * render graphs.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_client = o3dElement.client;
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- var viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set up a perspective projection.
- viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree fov.
- g_client.width / g_client.height,
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // cube is located.
- viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 1, 5], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- // Create an Effect object and initialize it using the shaders from the
- // text area.
- var cubeEffect = g_pack.createObject('Effect');
- var shaderString = document.getElementById('effect').value;
- cubeEffect.loadFromFXString(shaderString);
-
- // Create a Material for the mesh.
- var cubeMaterial = g_pack.createObject('Material');
-
- // Set the material's drawList.
- cubeMaterial.drawList = viewInfo.performanceDrawList;
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shaders to use.
- cubeMaterial.effect = cubeEffect;
-
- // Create an O3D Param on the material for every uniform used by the
- // shader.
- cubeEffect.createUniformParameters(cubeMaterial);
-
- // Get the color parameter from the material and set its value to red.
- g_cubeColorParam = cubeMaterial.getParam('color');
- g_cubeColorParam.value = [1, 0, 0, 1];
-
- // Create the Shape for the cube mesh and assign its material.
- var cubeShape = createCube(cubeMaterial);
-
- // Create a new transform and parent the Shape under it.
- g_cubeTransform = g_pack.createObject('Transform');
- g_cubeTransform.addShape(cubeShape);
-
- // Parent the cube's transform to the client root.
- g_cubeTransform.parent = g_client.root;
-
- // Set our render callback for animation.
- // This sets a function to be executed every time a frame is rendered.
- g_client.setRenderCallback(renderCallback);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Hello Square: Colors</h1>
-This example shows how to use parameters to the color output of a shader.
-<br/>
-
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-
-<form name="default_form" action="#" method="get">
- <p>
- Change color:
- <input type="button" value="Red" onclick="changeColor(1,0,0);" />
- <input type="button" value="Green" onclick="changeColor(0,1,0);" />
- <input type="button" value="Blue" onclick="changeColor(0,0,1);" />
- <input type="button" value="Yellow" onclick="changeColor(1,1,0);" />
- <input type="button" value="Cyan" onclick="changeColor(0,1,1);" />
- <input type="button" value="Purple" onclick="changeColor(1,0,1);" />
- <input type="button" value="White" onclick="changeColor(1,1,1);" />
- </p>
-</form>
-
-<!-- Don't render the textarea -->
-<div style="display:none">
-<!-- Start of effect -->
-<textarea id="effect">
- // World View Projection matrix that will transform the input vertices
- // to screen space.
- float4x4 worldViewProjection : WorldViewProjection;
-
- // This specifies the color of the triangles. A Param with the same name will
- // be created on the material using the shader.
- float4 color;
-
- // input parameters for our vertex shader
- struct VertexShaderInput {
- float4 position : POSITION;
- };
-
- // input parameters for our pixel shader
- struct PixelShaderInput {
- float4 position : POSITION;
- };
-
- /**
- * The vertex shader simply transforms the input vertices to screen space.
- */
- PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
-
- // Multiply the vertex positions by the worldViewProjection matrix to
- // transform them to screen space.
- output.position = mul(input.position, worldViewProjection);
- return output;
- }
-
- /**
- * Our pixel shader returns the value of color parameter.
- */
- float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return color;
- }
-
- // Here we tell our effect file *which* functions are
- // our vertex and pixel shaders.
-
- // #o3d VertexShaderEntryPoint vertexShaderFunction
- // #o3d PixelShaderEntryPoint pixelShaderFunction
- // #o3d MatrixLoadOrder RowMajor
-</textarea>
-<!-- End of effect -->
-</div>
-</body>
-</html>
diff --git a/o3d/samples/hellocube-glsl.html b/o3d/samples/hellocube-glsl.html
deleted file mode 100644
index ac89206..0000000
--- a/o3d/samples/hellocube-glsl.html
+++ /dev/null
@@ -1,304 +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 sample shows how to place an O3D area in a page and draw simple
-3D shape in it.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Hello Cube: Getting started with O3D
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// Run the init() function once the page has finished loading.
-// Run the uninit() function when the page has is unloaded.
-window.onload = init;
-window.onunload = uninit;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_cubeTransform;
-var g_finished = false; // for selenium testing
-
-/**
- * Creates an O3D shape representing a cube. The shape consists of
- * a single primitive with eight vertices and 12 triangles (two for each face
- * of the cube).
- * @param {o3d.Material} material the material used by the primitive.
- * @return {o3d.Shape} The Shape object created.
- */
-function createCube(material) {
- // Create a Shape object for the mesh.
- var cubeShape = g_pack.createObject('Shape');
-
- // Create the Primitive that will contain the geometry data for
- // the cube.
- var cubePrimitive = g_pack.createObject('Primitive');
-
- // Create a StreamBank to hold the streams of vertex data.
- var streamBank = g_pack.createObject('StreamBank');
-
- // Assign the material that was passed in to the primitive.
- cubePrimitive.material = material;
-
- // Assign the Primitive to the Shape.
- cubePrimitive.owner = cubeShape;
-
- // Assign the StreamBank to the Primitive.
- cubePrimitive.streamBank = streamBank;
-
- // The cube is made of 12 triangles. There's eight vertices in total which
- // are shared between the face triangles.
- cubePrimitive.primitiveType = g_o3d.Primitive.TRIANGLELIST;
- cubePrimitive.numberPrimitives = 12; // 12 triangles
- cubePrimitive.numberVertices = 8; // 8 vertices in total
-
- // Generate the draw element for the cube primitive.
- cubePrimitive.createDrawElement(g_pack, null);
-
- // Create a javascript array that stores the X, Y and Z coordinates of each
- // of the 8 corners of the cube.
- var positionArray = [
- -0.5, -0.5, 0.5, // vertex 0
- 0.5, -0.5, 0.5, // vertex 1
- -0.5, 0.5, 0.5, // vertex 2
- 0.5, 0.5, 0.5, // vertex 3
- -0.5, 0.5, -0.5, // vertex 4
- 0.5, 0.5, -0.5, // vertex 5
- -0.5, -0.5, -0.5, // vertex 6
- 0.5, -0.5, -0.5 // vertex 7
- ];
-
- // The following array defines how vertices are to be put together to form
- // the triangles that make up the cube's faces. In the index array, every
- // three elements define a triangle. So for example vertices 0, 1 and 2
- // make up the first triangle, vertices 2, 1 and 3 the second one, etc.
- var indicesArray = [
- 0, 1, 2, // face 1
- 2, 1, 3,
- 2, 3, 4, // face 2
- 4, 3, 5,
- 4, 5, 6, // face 3
- 6, 5, 7,
- 6, 7, 0, // face 4
- 0, 7, 1,
- 1, 7, 3, // face 5
- 3, 7, 5,
- 6, 0, 4, // face 6
- 4, 0, 2
- ];
-
- // Create buffers containing the vertex data.
- var positionsBuffer = g_pack.createObject('VertexBuffer');
- var positionsField = positionsBuffer.createField('FloatField', 3);
- positionsBuffer.set(positionArray);
-
- var indexBuffer = g_pack.createObject('IndexBuffer');
- indexBuffer.set(indicesArray);
-
- // Associate the positions Buffer with the StreamBank.
- streamBank.setVertexStream(
- g_o3d.Stream.POSITION, // semantic: This stream stores vertex positions
- 0, // semantic index: First (and only) position stream
- positionsField, // field: the field this stream uses.
- 0); // start_index: How many elements to skip in the
- // field.
-
- // Associate the triangle indices Buffer with the primitive.
- cubePrimitive.indexBuffer = indexBuffer;
-
- return cubeShape;
-}
-
-/**
- * This method gets called every time O3D renders a frame. Here's where
- * we update the cube's transform to make it spin.
- * @param {o3d.RenderEvent} renderEvent The render event object that gives
- * us the elapsed time since the last time a frame was rendered.
- */
-function renderCallback(renderEvent) {
- g_clock += renderEvent.elapsedTime * g_timeMult;
- // Rotate the cube around the Y axis.
- g_cubeTransform.identity();
- g_cubeTransform.rotateY(2.0 * g_clock);
-}
-
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, creates the cube and sets up the transform and
- * render graphs.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_client = o3dElement.client;
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- var viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set up a perspective projection.
- viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree fov.
- g_client.width / g_client.height,
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // cube is located.
- viewInfo.drawContext.view = g_math.matrix4.lookAt([0, 1, 5], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- // Create an Effect object and initialize it using the shaders from the
- // text area.
- var redEffect = g_pack.createObject('Effect');
- var shaderString = document.getElementById('effect').value;
- redEffect.loadFromFXString(shaderString);
-
- // Create a Material for the mesh.
- var redMaterial = g_pack.createObject('Material');
-
- // Set the material's drawList.
- redMaterial.drawList = viewInfo.performanceDrawList;
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shaders to use.
- redMaterial.effect = redEffect;
-
- // Create the Shape for the cube mesh and assign its material.
- var cubeShape = createCube(redMaterial);
-
- // Create a new transform and parent the Shape under it.
- g_cubeTransform = g_pack.createObject('Transform');
- g_cubeTransform.addShape(cubeShape);
-
- // Parent the cube's transform to the client root.
- g_cubeTransform.parent = g_client.root;
-
- // Set our render callback for animation.
- // This sets a function to be executed every time a frame is rendered.
- g_client.setRenderCallback(renderCallback);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Hello Cube</h1>
-This example shows how to display a spinning red cube in O3D.
-<br/>
-
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-
-<!-- Don't render the textarea -->
-<div style="display:none">
-<!-- Start of effect -->
-<textarea id="effect">
- // World View Projection matrix that will transform the input vertices
- // to screen space.
- uniform mat4 worldViewProjection;
-
- // input parameters for our vertex shader
- attribute vec4 position;
-
- /**
- * The vertex shader simply transforms the input vertices to screen space.
- */
- void main() {
- // Multiply the vertex positions by the worldViewProjection matrix to
- // transform them to screen space.
- gl_Position = worldViewProjection * position;
- }
-
-// This hack his here for now since O3D only allows one string
-// to be passed to Effect::loadFromFXString
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
- /**
- * This pixel shader just returns the color red.
- */
- void main() {
- gl_FragColor = vec4(1, 0, 0, 1); // Red.
- }
-
- // Here we tell our effect file *which* functions are
- // our vertex and pixel shaders.
-
-</textarea>
-<!-- End of effect -->
-</div>
-</body>
-</html>
diff --git a/o3d/samples/hellocube-textures-glsl.html b/o3d/samples/hellocube-textures-glsl.html
deleted file mode 100644
index 86b8857..0000000
--- a/o3d/samples/hellocube-textures-glsl.html
+++ /dev/null
@@ -1,433 +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 sample creates an O3D area with a textured cube in the middle. The
-user can specify the URL where the texture image will be picked from.
-This sample is a simple demonstration of texture usage in O3D.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Hello Square Textures: Getting started with O3D, take 3.
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.io');
-
-// Events
-// Run the init() function once the page has finished loading.
-// Run the uninit() function when the page is unloaded.
-window.onload = init;
-window.onunload = uninit;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_pack;
-var g_client;
-var g_cubeTransform;
-var g_sampler;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-var g_textureLoadDenied = false; // also for selenium testing
-
-/**
- * Creates an O3D shape representing a cube.
- * @param {o3d.Material} material the material used by the primitive.
- * @return {o3d.Shape} The Shape object created.
- */
-function createCube(material) {
- // Create a Shape object for the mesh.
- var cubeShape = g_pack.createObject('Shape');
-
- // Create the Primitive that will contain the geometry data for
- // the cube.
- var cubePrimitive = g_pack.createObject('Primitive');
-
- // Create a StreamBank to hold the streams of vertex data.
- var streamBank = g_pack.createObject('StreamBank');
-
- // Assign the material that was passed in to the primitive.
- cubePrimitive.material = material;
-
- // Assign the Primitive to the Shape.
- cubePrimitive.owner = cubeShape;
-
- // Assign the StreamBank to the Primitive.
- cubePrimitive.streamBank = streamBank;
-
- // The cube is made of 12 triangles (6 faces x 2 triangles per face)
- cubePrimitive.primitiveType = g_o3d.Primitive.TRIANGLELIST;
- cubePrimitive.numberPrimitives = 12; // 12 triangles
-
- // Vertices used by each triangle must specify both a position and texture
- // coordinates. We cannot share vertices between adjacent cube faces since
- // while their positions are the same, their texture coordinates are
- // different. We therefore create 24 vertices, 4 for each of the cube's
- // six faces.
- cubePrimitive.numberVertices = 24;
-
- // Generate the draw element for the cube primitive.
- cubePrimitive.createDrawElement(g_pack, null);
-
- // Create a javascript array that stores the X, Y and Z coordinates of each
- // of the 24 vertices used by the cube.
- var positionArray = [
- -0.5, -0.5, 0.5,
- 0.5, -0.5, 0.5,
- 0.5, 0.5, 0.5,
- -0.5, 0.5, 0.5,
- -0.5, 0.5, 0.5,
- 0.5, 0.5, 0.5,
- 0.5, 0.5, -0.5,
- -0.5, 0.5, -0.5,
- -0.5, 0.5, -0.5,
- 0.5, 0.5, -0.5,
- 0.5, -0.5, -0.5,
- -0.5, -0.5, -0.5,
- -0.5, -0.5, -0.5,
- 0.5, -0.5, -0.5,
- 0.5, -0.5, 0.5,
- -0.5, -0.5, 0.5,
- 0.5, -0.5, 0.5,
- 0.5, -0.5, -0.5,
- 0.5, 0.5, -0.5,
- 0.5, 0.5, 0.5,
- -0.5, -0.5, -0.5,
- -0.5, -0.5, 0.5,
- -0.5, 0.5, 0.5,
- -0.5, 0.5, -0.5
- ];
-
- // The following array stores the texture coordinates (u, v) for each vertex.
- // These coordinates are used by the shader when displaying the texture image
- // on the mesh triangles.
- var texCoordsArray = [
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1,
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1,
- 1, 1,
- 0, 1,
- 0, 0,
- 1, 0,
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1,
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1,
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1
- ];
-
- // The following array defines how vertices are to be put together to form
- // the triangles that make up the cube's faces. In the index array, every
- // three elements define a triangle. So for example vertices 0, 1 and 2
- // make up the first triangle, vertices 0, 2 and 3 the second one, etc.
- var indicesArray = [
- 0, 1, 2,
- 0, 2, 3,
- 4, 5, 6,
- 4, 6, 7,
- 8, 9, 10,
- 8, 10, 11,
- 12, 13, 14,
- 12, 14, 15,
- 16, 17, 18,
- 16, 18, 19,
- 20, 21, 22,
- 20, 22, 23
- ];
-
- // Create buffers containing the vertex data.
- var positionsBuffer = g_pack.createObject('VertexBuffer');
- var positionsField = positionsBuffer.createField('FloatField', 3);
- positionsBuffer.set(positionArray);
-
- var texCoordsBuffer = g_pack.createObject('VertexBuffer');
- var texCoordsField = texCoordsBuffer.createField('FloatField', 2);
- texCoordsBuffer.set(texCoordsArray);
-
- var indexBuffer = g_pack.createObject('IndexBuffer');
- indexBuffer.set(indicesArray);
-
- // Associate the positions buffer with the StreamBank.
- streamBank.setVertexStream(
- g_o3d.Stream.POSITION, // semantic: This stream stores vertex positions
- 0, // semantic index: First (and only) position stream
- positionsField, // field: the field this stream uses.
- 0); // start_index: How many elements to skip in the
- // field.
-
- // Associate the texture coordinates buffer with the primitive.
- streamBank.setVertexStream(
- g_o3d.Stream.TEXCOORD, // semantic
- 0, // semantic index
- texCoordsField, // field
- 0); // start_index
-
- // Associate the triangle indices Buffer with the primitive.
- cubePrimitive.indexBuffer = indexBuffer;
-
- return cubeShape;
-}
-
-/**
- * This method gets called every time O3D renders a frame. Here's where
- * we update the cube's transform to make it spin.
- * @param {o3d.RenderEvent} renderEvent The render event object that gives
- * us the elapsed time since the last time a frame was rendered.
- */
-function renderCallback(renderEvent) {
- g_clock += renderEvent.elapsedTime * g_timeMult;
- // Rotate the cube around the Y axis.
- g_cubeTransform.identity();
- g_cubeTransform.rotateY(2.0 * g_clock);
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, creates the quad and sets up the transform and
- * render graphs.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Set the texture URL.
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- path = path.substring(0, index+1) + 'assets/texture_b3.jpg';
- var url = document.getElementById("url").value = path;
-
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_client = o3dElement.client;
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- var viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set up a perspective projection.
- viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree fov.
- g_client.width / g_client.height,
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // cube is located.
- viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 1, 5], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- // Create an Effect object and initialize it using the shaders from the
- // text area.
- var cubeEffect = g_pack.createObject('Effect');
- var shaderString = document.getElementById('effect').value;
- cubeEffect.loadFromFXString(shaderString);
-
- // Create a Material for the mesh.
- var cubeMaterial = g_pack.createObject('Material');
-
- // Set the material's drawList.
- cubeMaterial.drawList = viewInfo.performanceDrawList;
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shaders to use.
- cubeMaterial.effect = cubeEffect;
-
- // Create an O3D Param on the material for every uniform used by the
- // shader.
- cubeEffect.createUniformParameters(cubeMaterial);
-
- // Get the material's sampler parameter so that we can set the texture value
- // to it.
- var samplerParam = cubeMaterial.getParam('texSampler0');
-
- // Create a Sampler object and set the min filtering to ANISOTROPIC. This
- // will improve the quality of the rendered texture when viewed at an angle.
- g_sampler = g_pack.createObject('Sampler');
- g_sampler.minFilter = g_o3d.Sampler.ANISOTROPIC;
- g_sampler.maxAnisotropy = 4;
- samplerParam.value = g_sampler;
-
- // Create the Shape for the cube mesh and assign its material.
- var cubeShape = createCube(cubeMaterial);
-
- // Create a new transform and parent the Shape under it.
- g_cubeTransform = g_pack.createObject('Transform');
- g_cubeTransform.addShape(cubeShape);
-
- // Note that we don't parent the transform until the texture is
- // succesfully loaded because we don't want the system
- // to try the draw the shape without its required texture.
-
- // Set our render callback for animation.
- // This sets a function to be executed every time a frame is rendered.
- g_client.setRenderCallback(renderCallback);
-
- // Set the initial texture.
- changeTexture();
-}
-
-/**
- * Fetches the bitmap pointed to by the URL supplied by the user, creates
- * an O3D Texture object with it updates the Sampler used by the material
- * to point to the newly created texture.
- */
-function changeTexture() {
- var textureUrl = document.getElementById('url').value;
- o3djs.io.loadTexture(g_pack, textureUrl, function(texture, exception) {
- // Remove the currently used texture from the pack so that when it's not
- // referenced anymore, it can get destroyed.
- if (g_sampler.texture)
- g_pack.removeObject(g_sampler.texture);
-
- // Because the loading is asynchronous an exception is not thrown but is
- // instead passed on failure.
- if (exception) {
- g_sampler.texture = null;
-
- g_textureLoadDenied = true; // for selenium testing.
- } else {
- // Set the texture on the sampler object to the newly created texture
- // object returned by the request.
- g_sampler.texture = texture;
-
- // We can now safely add the cube transform to the root of the
- // scenegraph since it now has a valid texture. If the transform
- // is already parented under the root, the call will have no effect.
- g_cubeTransform.parent = g_client.root;
-
- g_finished = true; // for selenium testing.
- }
- });
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Hello Cube: Textures</h1>
-This example shows how texture map a cube using an image fetched from a URL.
-<br/>
-
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<br />
-Image URL: <input type="text" id="url" size="100">
-<input type="button" id="updateButton" onclick="changeTexture();" value="Update Texture"><BR>
-
-<!-- Don't render the textarea -->
-<div style="display:none">
-<!-- Start of effect -->
-<textarea id="effect">
- // World View Projection matrix that will transform the input vertices
- // to screen space.
- uniform mat4 worldViewProjection;
-
- // input parameters for our vertex shader
- attribute vec4 position;
- attribute vec2 texcoords0;
-
- varying vec2 uvs;
-
- /**
- * The vertex shader simply transforms the input vertices to screen space.
- */
- void main() {
- // Multiply the vertex positions by the worldViewProjection matrix to
- // transform them to screen space.
- gl_Position = worldViewProjection * position;
- uvs = texcoords0;
- }
-
-// This hack his here for now since O3D only allows one string
-// to be passed to Effect::loadFromFXString
-// #o3d SplitMarker
-// #o3d MatrixLoadOrder RowMajor
-
- // Color to draw with.
- uniform sampler2D texSampler0;
-
- varying vec2 uvs;
-
- /**
- * This pixel shader just returns the color red.
- */
- void main() {
- gl_FragColor = texture2D(texSampler0, uvs);
- }
-</textarea>
-<!-- End of effect -->
-</div>
-</body>
-</html>
diff --git a/o3d/samples/hellocube-textures.html b/o3d/samples/hellocube-textures.html
deleted file mode 100644
index 44fa47e..0000000
--- a/o3d/samples/hellocube-textures.html
+++ /dev/null
@@ -1,445 +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 sample creates an O3D area with a textured cube in the middle. The
-user can specify the URL where the texture image will be picked from.
-This sample is a simple demonstration of texture usage in O3D.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Hello Square Textures: Getting started with O3D, take 3.
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.io');
-
-// Events
-// Run the init() function once the page has finished loading.
-// Run the uninit() function when the page is unloaded.
-window.onload = init;
-window.onunload = uninit;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_pack;
-var g_client;
-var g_cubeTransform;
-var g_sampler;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-var g_textureLoadDenied = false; // also for selenium testing
-
-/**
- * Creates an O3D shape representing a cube.
- * @param {o3d.Material} material the material used by the primitive.
- * @return {o3d.Shape} The Shape object created.
- */
-function createCube(material) {
- // Create a Shape object for the mesh.
- var cubeShape = g_pack.createObject('Shape');
-
- // Create the Primitive that will contain the geometry data for
- // the cube.
- var cubePrimitive = g_pack.createObject('Primitive');
-
- // Create a StreamBank to hold the streams of vertex data.
- var streamBank = g_pack.createObject('StreamBank');
-
- // Assign the material that was passed in to the primitive.
- cubePrimitive.material = material;
-
- // Assign the Primitive to the Shape.
- cubePrimitive.owner = cubeShape;
-
- // Assign the StreamBank to the Primitive.
- cubePrimitive.streamBank = streamBank;
-
- // The cube is made of 12 triangles (6 faces x 2 triangles per face)
- cubePrimitive.primitiveType = g_o3d.Primitive.TRIANGLELIST;
- cubePrimitive.numberPrimitives = 12; // 12 triangles
-
- // Vertices used by each triangle must specify both a position and texture
- // coordinates. We cannot share vertices between adjacent cube faces since
- // while their positions are the same, their texture coordinates are
- // different. We therefore create 24 vertices, 4 for each of the cube's
- // six faces.
- cubePrimitive.numberVertices = 24;
-
- // Generate the draw element for the cube primitive.
- cubePrimitive.createDrawElement(g_pack, null);
-
- // Create a javascript array that stores the X, Y and Z coordinates of each
- // of the 24 vertices used by the cube.
- var positionArray = [
- -0.5, -0.5, 0.5,
- 0.5, -0.5, 0.5,
- 0.5, 0.5, 0.5,
- -0.5, 0.5, 0.5,
- -0.5, 0.5, 0.5,
- 0.5, 0.5, 0.5,
- 0.5, 0.5, -0.5,
- -0.5, 0.5, -0.5,
- -0.5, 0.5, -0.5,
- 0.5, 0.5, -0.5,
- 0.5, -0.5, -0.5,
- -0.5, -0.5, -0.5,
- -0.5, -0.5, -0.5,
- 0.5, -0.5, -0.5,
- 0.5, -0.5, 0.5,
- -0.5, -0.5, 0.5,
- 0.5, -0.5, 0.5,
- 0.5, -0.5, -0.5,
- 0.5, 0.5, -0.5,
- 0.5, 0.5, 0.5,
- -0.5, -0.5, -0.5,
- -0.5, -0.5, 0.5,
- -0.5, 0.5, 0.5,
- -0.5, 0.5, -0.5
- ];
-
- // The following array stores the texture coordinates (u, v) for each vertex.
- // These coordinates are used by the shader when displaying the texture image
- // on the mesh triangles.
- var texCoordsArray = [
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1,
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1,
- 1, 1,
- 0, 1,
- 0, 0,
- 1, 0,
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1,
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1,
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1
- ];
-
- // The following array defines how vertices are to be put together to form
- // the triangles that make up the cube's faces. In the index array, every
- // three elements define a triangle. So for example vertices 0, 1 and 2
- // make up the first triangle, vertices 0, 2 and 3 the second one, etc.
- var indicesArray = [
- 0, 1, 2,
- 0, 2, 3,
- 4, 5, 6,
- 4, 6, 7,
- 8, 9, 10,
- 8, 10, 11,
- 12, 13, 14,
- 12, 14, 15,
- 16, 17, 18,
- 16, 18, 19,
- 20, 21, 22,
- 20, 22, 23
- ];
-
- // Create buffers containing the vertex data.
- var positionsBuffer = g_pack.createObject('VertexBuffer');
- var positionsField = positionsBuffer.createField('FloatField', 3);
- positionsBuffer.set(positionArray);
-
- var texCoordsBuffer = g_pack.createObject('VertexBuffer');
- var texCoordsField = texCoordsBuffer.createField('FloatField', 2);
- texCoordsBuffer.set(texCoordsArray);
-
- var indexBuffer = g_pack.createObject('IndexBuffer');
- indexBuffer.set(indicesArray);
-
- // Associate the positions buffer with the StreamBank.
- streamBank.setVertexStream(
- g_o3d.Stream.POSITION, // semantic: This stream stores vertex positions
- 0, // semantic index: First (and only) position stream
- positionsField, // field: the field this stream uses.
- 0); // start_index: How many elements to skip in the
- // field.
-
- // Associate the texture coordinates buffer with the primitive.
- streamBank.setVertexStream(
- g_o3d.Stream.TEXCOORD, // semantic
- 0, // semantic index
- texCoordsField, // field
- 0); // start_index
-
- // Associate the triangle indices Buffer with the primitive.
- cubePrimitive.indexBuffer = indexBuffer;
-
- return cubeShape;
-}
-
-/**
- * This method gets called every time O3D renders a frame. Here's where
- * we update the cube's transform to make it spin.
- * @param {o3d.RenderEvent} renderEvent The render event object that gives
- * us the elapsed time since the last time a frame was rendered.
- */
-function renderCallback(renderEvent) {
- g_clock += renderEvent.elapsedTime * g_timeMult;
- // Rotate the cube around the Y axis.
- g_cubeTransform.identity();
- g_cubeTransform.rotateY(2.0 * g_clock);
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, creates the quad and sets up the transform and
- * render graphs.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Set the texture URL.
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- path = path.substring(0, index+1) + 'assets/texture_b3.jpg';
- var url = document.getElementById("url").value = path;
-
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_client = o3dElement.client;
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- var viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set up a perspective projection.
- viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree fov.
- g_client.width / g_client.height,
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // cube is located.
- viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 1, 5], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- // Create an Effect object and initialize it using the shaders from the
- // text area.
- var cubeEffect = g_pack.createObject('Effect');
- var shaderString = document.getElementById('effect').value;
- cubeEffect.loadFromFXString(shaderString);
-
- // Create a Material for the mesh.
- var cubeMaterial = g_pack.createObject('Material');
-
- // Set the material's drawList.
- cubeMaterial.drawList = viewInfo.performanceDrawList;
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shaders to use.
- cubeMaterial.effect = cubeEffect;
-
- // Create an O3D Param on the material for every uniform used by the
- // shader.
- cubeEffect.createUniformParameters(cubeMaterial);
-
- // Get the material's sampler parameter so that we can set the texture value
- // to it.
- var samplerParam = cubeMaterial.getParam('texSampler0');
-
- // Create a Sampler object and set the min filtering to ANISOTROPIC. This
- // will improve the quality of the rendered texture when viewed at an angle.
- g_sampler = g_pack.createObject('Sampler');
- g_sampler.minFilter = g_o3d.Sampler.ANISOTROPIC;
- g_sampler.maxAnisotropy = 4;
- samplerParam.value = g_sampler;
-
- // Create the Shape for the cube mesh and assign its material.
- var cubeShape = createCube(cubeMaterial);
-
- // Create a new transform and parent the Shape under it.
- g_cubeTransform = g_pack.createObject('Transform');
- g_cubeTransform.addShape(cubeShape);
-
- // Note that we don't parent the transform until the texture is
- // succesfully loaded because we don't want the system
- // to try the draw the shape without its required texture.
-
- // Set our render callback for animation.
- // This sets a function to be executed every time a frame is rendered.
- g_client.setRenderCallback(renderCallback);
-
- // Set the initial texture.
- changeTexture();
-}
-
-/**
- * Fetches the bitmap pointed to by the URL supplied by the user, creates
- * an O3D Texture object with it updates the Sampler used by the material
- * to point to the newly created texture.
- */
-function changeTexture() {
- var textureUrl = document.getElementById('url').value;
- o3djs.io.loadTexture(g_pack, textureUrl, function(texture, exception) {
- // Remove the currently used texture from the pack so that when it's not
- // referenced anymore, it can get destroyed.
- if (g_sampler.texture)
- g_pack.removeObject(g_sampler.texture);
-
- // Because the loading is asynchronous an exception is not thrown but is
- // instead passed on failure.
- if (exception) {
- g_sampler.texture = null;
-
- g_textureLoadDenied = true; // for selenium testing.
- } else {
- // Set the texture on the sampler object to the newly created texture
- // object returned by the request.
- g_sampler.texture = texture;
-
- // We can now safely add the cube transform to the root of the
- // scenegraph since it now has a valid texture. If the transform
- // is already parented under the root, the call will have no effect.
- g_cubeTransform.parent = g_client.root;
-
- g_finished = true; // for selenium testing.
- }
- });
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Hello Cube: Textures</h1>
-This example shows how texture map a cube using an image fetched from a URL.
-<br/>
-
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<br />
-Image URL: <input type="text" id="url" size="100">
-<input type="button" id="updateButton" onclick="changeTexture();" value="Update Texture"><BR>
-
-<!-- Don't render the textarea -->
-<div style="display:none">
-<!-- Start of effect -->
-<textarea id="effect">
- // World View Projection matrix that will transform the input vertices
- // to screen space.
- float4x4 worldViewProjection : WorldViewProjection;
-
- // The texture sampler is used to access the texture bitmap in the fragment
- // shader.
- sampler texSampler0;
-
- // input parameters for our vertex shader
- struct VertexShaderInput {
- float4 position : POSITION;
- float2 tex : TEXCOORD0; // Texture coordinates
- };
-
- // input parameters for our pixel shader
- struct PixelShaderInput {
- float4 position : POSITION;
- float2 tex : TEXCOORD0; // Texture coordinates
- };
-
- /**
- * The vertex shader simply transforms the input vertices to screen space.
- */
- PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
-
- // Multiply the vertex positions by the worldViewProjection matrix to
- // transform them to screen space.
- output.position = mul(input.position, worldViewProjection);
-
- output.tex = input.tex;
- return output;
- }
-
- /**
- * Given the texture coordinates, our pixel shader grabs the corresponding
- * color from the texture.
- */
- float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return tex2D(texSampler0, input.tex);
- }
-
- // Here we tell our effect file *which* functions are
- // our vertex and pixel shaders.
-
- // #o3d VertexShaderEntryPoint vertexShaderFunction
- // #o3d PixelShaderEntryPoint pixelShaderFunction
- // #o3d MatrixLoadOrder RowMajor
-</textarea>
-<!-- End of effect -->
-</div>
-</body>
-</html>
diff --git a/o3d/samples/hellocube.html b/o3d/samples/hellocube.html
deleted file mode 100644
index c036d6f..0000000
--- a/o3d/samples/hellocube.html
+++ /dev/null
@@ -1,312 +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 sample shows how to place an O3D area in a page and draw simple
-3D shape in it.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Hello Cube: Getting started with O3D
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// Run the init() function once the page has finished loading.
-// Run the uninit() function when the page has is unloaded.
-window.onload = init;
-window.onunload = uninit;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_cubeTransform;
-var g_finished = false; // for selenium testing
-
-/**
- * Creates an O3D shape representing a cube. The shape consists of
- * a single primitive with eight vertices and 12 triangles (two for each face
- * of the cube).
- * @param {o3d.Material} material the material used by the primitive.
- * @return {o3d.Shape} The Shape object created.
- */
-function createCube(material) {
- // Create a Shape object for the mesh.
- var cubeShape = g_pack.createObject('Shape');
-
- // Create the Primitive that will contain the geometry data for
- // the cube.
- var cubePrimitive = g_pack.createObject('Primitive');
-
- // Create a StreamBank to hold the streams of vertex data.
- var streamBank = g_pack.createObject('StreamBank');
-
- // Assign the material that was passed in to the primitive.
- cubePrimitive.material = material;
-
- // Assign the Primitive to the Shape.
- cubePrimitive.owner = cubeShape;
-
- // Assign the StreamBank to the Primitive.
- cubePrimitive.streamBank = streamBank;
-
- // The cube is made of 12 triangles. There's eight vertices in total which
- // are shared between the face triangles.
- cubePrimitive.primitiveType = g_o3d.Primitive.TRIANGLELIST;
- cubePrimitive.numberPrimitives = 12; // 12 triangles
- cubePrimitive.numberVertices = 8; // 8 vertices in total
-
- // Generate the draw element for the cube primitive.
- cubePrimitive.createDrawElement(g_pack, null);
-
- // Create a javascript array that stores the X, Y and Z coordinates of each
- // of the 8 corners of the cube.
- var positionArray = [
- -0.5, -0.5, 0.5, // vertex 0
- 0.5, -0.5, 0.5, // vertex 1
- -0.5, 0.5, 0.5, // vertex 2
- 0.5, 0.5, 0.5, // vertex 3
- -0.5, 0.5, -0.5, // vertex 4
- 0.5, 0.5, -0.5, // vertex 5
- -0.5, -0.5, -0.5, // vertex 6
- 0.5, -0.5, -0.5 // vertex 7
- ];
-
- // The following array defines how vertices are to be put together to form
- // the triangles that make up the cube's faces. In the index array, every
- // three elements define a triangle. So for example vertices 0, 1 and 2
- // make up the first triangle, vertices 2, 1 and 3 the second one, etc.
- var indicesArray = [
- 0, 1, 2, // face 1
- 2, 1, 3,
- 2, 3, 4, // face 2
- 4, 3, 5,
- 4, 5, 6, // face 3
- 6, 5, 7,
- 6, 7, 0, // face 4
- 0, 7, 1,
- 1, 7, 3, // face 5
- 3, 7, 5,
- 6, 0, 4, // face 6
- 4, 0, 2
- ];
-
- // Create buffers containing the vertex data.
- var positionsBuffer = g_pack.createObject('VertexBuffer');
- var positionsField = positionsBuffer.createField('FloatField', 3);
- positionsBuffer.set(positionArray);
-
- var indexBuffer = g_pack.createObject('IndexBuffer');
- indexBuffer.set(indicesArray);
-
- // Associate the positions Buffer with the StreamBank.
- streamBank.setVertexStream(
- g_o3d.Stream.POSITION, // semantic: This stream stores vertex positions
- 0, // semantic index: First (and only) position stream
- positionsField, // field: the field this stream uses.
- 0); // start_index: How many elements to skip in the
- // field.
-
- // Associate the triangle indices Buffer with the primitive.
- cubePrimitive.indexBuffer = indexBuffer;
-
- return cubeShape;
-}
-
-/**
- * This method gets called every time O3D renders a frame. Here's where
- * we update the cube's transform to make it spin.
- * @param {o3d.RenderEvent} renderEvent The render event object that gives
- * us the elapsed time since the last time a frame was rendered.
- */
-function renderCallback(renderEvent) {
- g_clock += renderEvent.elapsedTime * g_timeMult;
- // Rotate the cube around the Y axis.
- g_cubeTransform.identity();
- g_cubeTransform.rotateY(2.0 * g_clock);
-}
-
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, creates the cube and sets up the transform and
- * render graphs.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_client = o3dElement.client;
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- var viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set up a perspective projection.
- viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree fov.
- g_client.width / g_client.height,
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // cube is located.
- viewInfo.drawContext.view = g_math.matrix4.lookAt([0, 1, 5], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- // Create an Effect object and initialize it using the shaders from the
- // text area.
- var redEffect = g_pack.createObject('Effect');
- var shaderString = document.getElementById('effect').value;
- redEffect.loadFromFXString(shaderString);
-
- // Create a Material for the mesh.
- var redMaterial = g_pack.createObject('Material');
-
- // Set the material's drawList.
- redMaterial.drawList = viewInfo.performanceDrawList;
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shaders to use.
- redMaterial.effect = redEffect;
-
- // Create the Shape for the cube mesh and assign its material.
- var cubeShape = createCube(redMaterial);
-
- // Create a new transform and parent the Shape under it.
- g_cubeTransform = g_pack.createObject('Transform');
- g_cubeTransform.addShape(cubeShape);
-
- // Parent the cube's transform to the client root.
- g_cubeTransform.parent = g_client.root;
-
- // Set our render callback for animation.
- // This sets a function to be executed every time a frame is rendered.
- g_client.setRenderCallback(renderCallback);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Hello Cube</h1>
-This example shows how to display a spinning red cube in O3D.
-<br/>
-
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-
-<!-- Don't render the textarea -->
-<div style="display:none">
-<!-- Start of effect -->
-<textarea id="effect">
- // World View Projection matrix that will transform the input vertices
- // to screen space.
- float4x4 worldViewProjection : WorldViewProjection;
-
- // input parameters for our vertex shader
- struct VertexShaderInput {
- float4 position : POSITION;
- };
-
- // input parameters for our pixel shader
- struct PixelShaderInput {
- float4 position : POSITION;
- };
-
- /**
- * The vertex shader simply transforms the input vertices to screen space.
- */
- PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
-
- // Multiply the vertex positions by the worldViewProjection matrix to
- // transform them to screen space.
- output.position = mul(input.position, worldViewProjection);
- return output;
- }
-
- /**
- * This pixel shader just returns the color red.
- */
- float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return float4(1, 0, 0, 1); // Red.
- }
-
- // Here we tell our effect file *which* functions are
- // our vertex and pixel shaders.
-
- // #o3d VertexShaderEntryPoint vertexShaderFunction
- // #o3d PixelShaderEntryPoint pixelShaderFunction
- // #o3d MatrixLoadOrder RowMajor
-</textarea>
-<!-- End of effect -->
-</div>
-</body>
-</html>
diff --git a/o3d/samples/helloworld.html b/o3d/samples/helloworld.html
deleted file mode 100644
index 7c40262..0000000
--- a/o3d/samples/helloworld.html
+++ /dev/null
@@ -1,171 +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.
--->
-
-<!--
-O3D Tutorial A1
-
-In this tutorial, we load and display a scene in O3D.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Tutorial A1: Loading a scene
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-// unload() when leaving the page.
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_finished = false; // for selenium testing
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- */
-function loadScene(pack, fileName, parent) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- g_client.width,
- g_client.height);
-
- // Copy the view and projection to the draw context.
- g_viewInfo.drawContext.view = cameraInfo.view;
- g_viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
-
- g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Creates a transform to put our data on.
- var myDataRoot = g_pack.createObject('Transform');
-
- // Connects our root to the client root.
- myDataRoot.parent = g_client.root;
-
- // Load the scene into the transform graph as a child myDataRoot
- loadScene(g_pack, 'assets/teapot.o3dtgz', myDataRoot);
-}
-</script>
-</head>
-<body>
-<h1>Loading a scene.</h1>
-This tutorial shows how we load and display a scene in O3D.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/home-configurators/assets/empty.txt b/o3d/samples/home-configurators/assets/empty.txt
deleted file mode 100644
index e69de29..0000000
--- a/o3d/samples/home-configurators/assets/empty.txt
+++ /dev/null
diff --git a/o3d/samples/home-configurators/cb_images/cb_item_thumbnails.jpg b/o3d/samples/home-configurators/cb_images/cb_item_thumbnails.jpg
deleted file mode 100644
index 65a5473..0000000
--- a/o3d/samples/home-configurators/cb_images/cb_item_thumbnails.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/home-configurators/cb_images/toolselector.gif b/o3d/samples/home-configurators/cb_images/toolselector.gif
deleted file mode 100644
index f4d1722..0000000
--- a/o3d/samples/home-configurators/cb_images/toolselector.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/home-configurators/cb_images/unbranded_bg.png b/o3d/samples/home-configurators/cb_images/unbranded_bg.png
deleted file mode 100644
index 94e2747..0000000
--- a/o3d/samples/home-configurators/cb_images/unbranded_bg.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/home-configurators/cbassets/empty.txt b/o3d/samples/home-configurators/cbassets/empty.txt
deleted file mode 100644
index e69de29..0000000
--- a/o3d/samples/home-configurators/cbassets/empty.txt
+++ /dev/null
diff --git a/o3d/samples/home-configurators/craftsmanassets/craftsman_item_thumbnails.jpg b/o3d/samples/home-configurators/craftsmanassets/craftsman_item_thumbnails.jpg
deleted file mode 100644
index 212a01c..0000000
--- a/o3d/samples/home-configurators/craftsmanassets/craftsman_item_thumbnails.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/home-configurators/deletetool.js b/o3d/samples/home-configurators/deletetool.js
deleted file mode 100644
index 022d65f..0000000
--- a/o3d/samples/home-configurators/deletetool.js
+++ /dev/null
@@ -1,88 +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.
- */
-
-/**
- * A tool to move components around in the scene. Will constrain movement to
- * the ground plane.
- *
- * Requires the picking Client 3d Utilities API.
- */
-function DeleteTool(context, root) {
- this.context = context;
- this.root = root;
- this.pickManager = g_pickManager;
- this.selectedObject = null;
-}
-
-DeleteTool.prototype.getPickedObject = function(e) {
- var worldRay = o3djs.picking.clientPositionToWorldRay(e.x,
- e.y,
- this.context,
- g_client.width,
- g_client.height);
- this.pickManager.update();
- var pickInfo = this.pickManager.pick(worldRay);
- var picked_object_root = null;
- if (pickInfo) {
- pickedObject = pickInfo.shapeInfo.parent;
- while (pickedObject.parent != null &&
- pickedObject.parent.transform != this.root) {
- pickedObject = pickedObject.parent;
- }
- picked_object_root = pickedObject.transform;
- }
- return picked_object_root;
-};
-
-DeleteTool.prototype.handleMouseDown = function(e) {
- this.selectedObject = this.getPickedObject(e);
-};
-
-DeleteTool.prototype.handleMouseUp = function(e) {
- if (this.selectedObject != null &&
- this.selectedObject == this.getPickedObject(e)) {
- // Delete the object if the user clicked down and up on the same object.
- this.selectedObject.parent = null;
- }
- this.selectedObject = null;
-};
-
-DeleteTool.prototype.handleMouseMove = function(e) {
-};
-
-DeleteTool.prototype.handleKeyDown = function(e) {
- return false;
-};
-
-DeleteTool.prototype.handleKeyUp = function(e) {
- return false;
-};
-
diff --git a/o3d/samples/home-configurators/homedesigner.html b/o3d/samples/home-configurators/homedesigner.html
deleted file mode 100644
index 387e99a2..0000000
--- a/o3d/samples/home-configurators/homedesigner.html
+++ /dev/null
@@ -1,171 +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.
--->
-
-<html>
-<title>
- O3D Home Designer Demo
-</title>
-<style type="text/css">
-BODY {
- background-image: url(cb_images/unbranded_bg.png);
- background-position: top center;
- background-repeat: no-repeat;
- background-color: white;
-}
-
-#intro {
- font-family: sans-serif;
- color: 666666;
- font-size: 12px;
- padding: 12px 8px 0px 8px;
-}
-
-#toolpanel {
- width: 400px;
- height: 36px;
- padding-top: 1px;
-}
-
-#toolselector {
- width: 38px;
- height: 38px;
- background-image: url(cb_images/toolselector.gif);
- position: relative;
- left: 9px;
- border: 0px;
-}
-
-.catalogItem {
- -moz-user-select:none;
- cursor: pointer;
- width: 62px;
- height: 62px;
- border: 1px solid silver;
- margin: 1px;
- float: left;
- background-image: url(cb_images/cb_item_thumbnails.jpg);
-}
-
-#itemlist {
- padding-left: 8px;
-
-}
-
-</style>
- <script type="text/javascript" src="../o3djs/base.js"></script>
- <script type="text/javascript" src="viewer.js"></script>
- <script type="text/javascript" src="rotatetool.js"></script>
- <script type="text/javascript" src="movetool.js"></script>
- <script type="text/javascript" src="orbittool.js"></script>
- <script type="text/javascript" src="pantool.js"></script>
- <script type="text/javascript" src="zoomtool.js"></script>
- <script type="text/javascript" src="deletetool.js"></script>
-
-<script type="text/javascript" id="o3dscript">
-/**
- * A structure to store our list of catalog items that can be dragged in.
- * If the url doesn't start with 'http:' then we assume it's a local
- * file to be loaded from the /assets subdirectory.
- */
-g_items = [
- { url: 'Agra_Rug.o3dtgz', cost: 100, title: 'Agra Rug' },
- { url: 'Asimi_Rug.o3dtgz', cost: 100, title: 'Asimi Rug' },
- { url: 'Camden_Chair.o3dtgz', cost: 100, title: 'Camden Chair' },
- { url: 'Elements_Bookshelf.o3dtgz', cost: 100, title: 'Elements Bookshelf' },
- { url: 'Ferrara_Rug.o3dtgz', cost: 100, title: 'Ferrara Rug' },
- { url: 'Lounge_Chair.o3dtgz', cost: 100, title: 'Lounge Chair' },
- { url: 'Lounge_Chaise.o3dtgz', cost: 100, title: 'Lounge Chaise' },
- { url: 'Lounge_Sofa.o3dtgz', cost: 100, title: 'Lounge Sofa' },
- { url: 'Lounge_Storage_Ottoman.o3dtgz', cost: 100,
- title: 'Lounge_Storage_Ottoman' },
- { url: 'Madison_Dining_Table.o3dtgz', cost: 100, title: 'Madison Dining Table' },
- { url: 'Miles_Side_Chair.o3dtgz', cost: 100, title: 'Miles Side Chair' },
- { url: 'Pullman_Bar_Stool.o3dtgz', cost: 100, title: 'Pullman Bar Stool' },
- { url: 'Puzzle_TV_Stand.o3dtgz', cost: 100, title: 'Puzzle TV Stand' },
- { url: 'Stow_Leather_Ottoman.o3dtgz', cost: 100, title: 'Stow Leather Ottoman' },
- { url: 'Tivoli_Dining_Table.o3dtgz', cost: 100, title: 'Tivoli Dining Table' },
- { url: 'Tivoli_Miles_Dining_Set.o3dtgz', cost: 100,
- title: 'Tivoli_Miles_Dining_Set' },
- { url: 'Troy_Chair.o3dtgz', cost: 100, title: 'Troy Chair' },
- { url: 'Troy_Ottoman.o3dtgz', cost: 100, title: 'Troy Ottoman' },
- { url: 'Troy_Sofa.o3dtgz', cost: 100, title: 'Troy Sofa' },
- { url: 'Troy_Storage_Ottoman.o3dtgz', cost: 100, title: 'Troy Storage Ottoman' },
- { url: 'Troy_Twin_Sleeper.o3dtgz', cost: 100, title: 'Troy Twin Sleeper' }
-];
-
-var g_assetPath = '/cbassets/';
-var g_buildingAsset = '/cbassets/House_Roofless.o3dtgz';
-
-</script>
-<body onload="init();" onresize="resize();">
-
-<div style="position:absolute;top:104px;left:0px;text-align:center;width:100%">
-
-
-<table style="width:900px;" align="center"><tr>
- <td width="100%" valign="top">
-
- <table id="container" width="676" height="545" border="0"><tr><td>
- <div id="o3d" style="width:100%; height:100%"></div>
- </td></tr></table>
- <div id="toolpanel"><div id="toolselector"></div></div>
- </td>
- <td valign="top" style="padding-right:8px">
- <div id="contentpanel" style="width:222px;height:365px">
- <div id="intro">
- <span style="font-size: 18px">Most Popular Items</span>
- <p>Drag and drop objects into the
- <br>rooms on the left.
- </div>
- <div id="itemlist">
- </div>
-
-
- </div><br>
- </td>
-</tr></table>
-</div>
-
-<!-- hide the old UI -->
-<div style="display:none">
- <input type="text" id="url" size="100">
- <input type="button" onclick="doload();" value="load"><BR>
- <div id="output">
- </div>
- <div style="display:none">
-
- </div>
-</div>
-
-</body>
-</html>
-
-
diff --git a/o3d/samples/home-configurators/movetool.js b/o3d/samples/home-configurators/movetool.js
deleted file mode 100644
index 5d0e190..0000000
--- a/o3d/samples/home-configurators/movetool.js
+++ /dev/null
@@ -1,161 +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.
- */
-
-
-/**
- * A tool to move components around in the scene. Will constrain movement to
- * the ground plane.
- *
- * Requires the picking Client 3d Utilities API.
- */
-function MoveTool(context, root) {
- this.lastMove = null;
- this.context = context;
- this.root = root;
- this.pickManager = g_pickManager;
- this.movePlane = [0.0, 0.0, 1.0];
- this.downPoint = null;
- this.selectedObject = null;
-}
-
-/*
- * transform_node : The shape's root node that should be moving.
- * (the same node as would be found by our picking code)
- */
-MoveTool.prototype.initializeWithShape = function(transform_node) {
- this.pickManager.update();
- translation = g_math.matrix4.getTranslation(
- transform_node.getUpdatedWorldMatrix());
- this.downPoint = translation;
- this.selectedObject = transform_node;
- this.lastMove = null;
-};
-
-MoveTool.prototype.handleMouseDown = function(e) {
- var worldRay = o3djs.picking.clientPositionToWorldRay(e.x,
- e.y,
- this.context,
- g_client.width,
- g_client.height);
- this.pickManager.update();
- this.selectedObject = null;
- var pickInfo = this.pickManager.pick(worldRay);
- if (pickInfo) {
- pickedObject = pickInfo.shapeInfo.parent;
- while (pickedObject.parent != null &&
- pickedObject.parent.transform != this.root) {
- pickedObject = pickedObject.parent;
- }
- this.selectedObject = pickedObject.transform;
- }
- if (this.selectedObject) {
- this.downPoint = pickInfo.worldIntersectionPosition.slice(0, 3);
- this.lastMove = null;
- }
-};
-
-MoveTool.prototype.handleMouseUp = function(e) {
- this.downPoint = null;
-};
-
-MoveTool.prototype.handleMouseMove = function(e) {
- if (this.downPoint == null)
- return;
-
- if (this.selectedObject === null)
- return;
-
- var offset;
-
- if (e.x !== undefined) {
- // An O3D event
- offset = { x: e.x, y: e.y };
- } else {
- // A JS event
- e = e ? e : window.event;
- elem = e.target ? e.target : e.srcElement;
-
- // Check if the cursor is in the O3D area.
- if (elem !== g_o3dElement) {
- return;
- }
- offset = getRelativeCoordinates(e, elem);
- }
-
- var worldRay = o3djs.picking.clientPositionToWorldRay(offset.x,
- offset.y,
- this.context,
- g_client.width,
- g_client.height);
- // Compute the offset from the start point.
- var ray_dir = g_math.subVector(worldRay.far, worldRay.near);
- ray_dir = g_math.normalize(ray_dir);
- var ray_dot_plane = g_math.dot(ray_dir, this.movePlane);
- if (Math.abs(ray_dot_plane) < 0.001) {
- return [0.0, 0.0, 0.0];
- }
- var plane_distance =
- g_math.dot(this.downPoint, this.movePlane) -
- g_math.dot(worldRay.near, this.movePlane);
- t = plane_distance / ray_dot_plane;
- move_position = g_math.addVector(
- g_math.mulVectorScalar(ray_dir, t), worldRay.near);
- var offset = g_math.subVector(move_position, this.downPoint);
- translation = offset;
- if (this.lastMove != null) {
- translation = g_math.subVector(offset, this.lastMove);
- }
- this.lastMove = offset;
-
- if (this.selectedObject) {
- matrix = this.selectedObject.localMatrix;
- transformation = g_math.matrix4.translation(translation);
- matrix = g_math.matrix4.mul(matrix, transformation);
- this.selectedObject.localMatrix = matrix;
- }
-};
-
-MoveTool.prototype.handleKeyDown = function(key) {
- return false;
-};
-
-MoveTool.prototype.handleKeyUp = function(key) {
- // TODO: We should really have a selection instead of this
- // dual-use of the tool's last selected object.
- if (key == DELETE || key == BACKSPACE) {
- if (this.downPoint == null && this.selectedObject != null) {
- this.selectedObject.setParent(null);
- this.selectedObject = null;
- return true;
- }
- }
- return false;
-};
diff --git a/o3d/samples/home-configurators/orbittool.js b/o3d/samples/home-configurators/orbittool.js
deleted file mode 100644
index 0f37242..0000000
--- a/o3d/samples/home-configurators/orbittool.js
+++ /dev/null
@@ -1,94 +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.
- */
-
-
-/**
- * The Orbit tool allows the user to look around the model by click-dragging.
- * The shift key enters a pan mode instead of orbiting.
- */
-function OrbitTool(camera) {
- this.camera = camera;
- this.lastOffset = null;
- this.mouseLeftDown = false;
- this.mouseMiddleDown = false;
-}
-
-OrbitTool.prototype.handleMouseDown = function(e) {
- this.lastOffset = { x: e.x, y: e.y };
- if (e.button == g_o3d.Event.BUTTON_LEFT) {
- this.mouseLeftDown = true;
- } else if (e.button == g_o3d.Event.BUTTON_MIDDLE) {
- this.mouseMiddleDown = true;
- }
-};
-
-OrbitTool.prototype.handleMouseMove = function(e) {
- if (e.x !== undefined && (this.mouseLeftDown || this.mouseMiddleDown)) {
- var offset = { x: e.x, y: e.y };
-
- dY = (offset.y - this.lastOffset.y);
- dX = (offset.x - this.lastOffset.x);
- this.lastOffset = offset;
- panInsteadOfOrbit = (this.mouseLeftDown && this.mouseMiddleDown) ||
- e.shiftKey;
- if (panInsteadOfOrbit) {
- dX *= -1;
- this.camera.target.x -= (dY * Math.cos(this.camera.eye.rotZ) +
- dX * Math.sin(this.camera.eye.rotZ)) /
- (700 / this.camera.eye.distanceFromTarget);
- this.camera.target.y += (-dY * Math.sin(this.camera.eye.rotZ) +
- dX * Math.cos(this.camera.eye.rotZ)) /
- (700 / this.camera.eye.distanceFromTarget);
- } else {
- this.camera.eye.rotZ -= dX / 300;
- this.camera.eye.rotH -= dY / 300;
- this.camera.eye.rotH = peg(this.camera.eye.rotH, 0.1, Math.PI - 0.1);
- document.getElementById('output').innerHTML = this.camera.eye.rotH;
- }
- this.camera.update();
- }
-};
-
-OrbitTool.prototype.handleMouseUp = function(e) {
- if (e.button == g_o3d.Event.BUTTON_LEFT) {
- this.mouseLeftDown = false;
- } else if (e.button == g_o3d.Event.BUTTON_MIDDLE) {
- this.mouseMiddleDown = false;
- }
-};
-
-OrbitTool.prototype.handleKeyDown = function(e) {
- return false;
-};
-
-OrbitTool.prototype.handleKeyUp = function(e) {
- return false;
-};
diff --git a/o3d/samples/home-configurators/pantool.js b/o3d/samples/home-configurators/pantool.js
deleted file mode 100644
index 5caaa59..0000000
--- a/o3d/samples/home-configurators/pantool.js
+++ /dev/null
@@ -1,77 +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.
- */
-
-
-/**
- * The Pan tool allows the user to pan around the view by clicking and dragging.
- */
-function PanTool(camera) {
- this.camera = camera;
- this.dragging = false;
- this.lastOffset = null;
-}
-
-PanTool.prototype.handleMouseDown = function(e) {
- var offset = { x: e.x, y: e.y };
- this.lastOffset = offset;
- this.dragging = true;
-};
-
-PanTool.prototype.handleMouseMove = function(e) {
- if (this.dragging && e.x !== undefined) {
- var offset = { x: e.x, y: e.y };
-
- dY = (offset.y - this.lastOffset.y);
- dX = -(offset.x - this.lastOffset.x);
- this.lastOffset = offset;
-
- this.camera.target.x -= (dY * Math.cos(this.camera.eye.rotZ) +
- dX * Math.sin(this.camera.eye.rotZ)) /
- (700 / this.camera.eye.distanceFromTarget);
- this.camera.target.y += (-dY * Math.sin(this.camera.eye.rotZ) +
- dX * Math.cos(this.camera.eye.rotZ)) /
- (700 / this.camera.eye.distanceFromTarget);
-
- this.camera.update();
- }
-};
-
-PanTool.prototype.handleMouseUp = function(e) {
- this.dragging = false;
-};
-
-PanTool.prototype.handleKeyDown = function(e) {
- return false;
-};
-
-PanTool.prototype.handleKeyUp = function(e) {
- return false;
-};
diff --git a/o3d/samples/home-configurators/rotatetool.js b/o3d/samples/home-configurators/rotatetool.js
deleted file mode 100644
index 2a78a2a4..0000000
--- a/o3d/samples/home-configurators/rotatetool.js
+++ /dev/null
@@ -1,113 +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.
- */
-
-
-/**
- * A tool to move components around in the scene. Will constrain movement to
- * the ground plane.
- *
- * Requires the picking Client 3d Utilities API.
- */
-function RotateTool(context, root) {
- this.downPoint = null;
- this.lastRotation = 0;
- this.context = context;
- this.selectedObject = null;
- this.root = root;
- this.pickManager = g_pickManager;
- this.rotateAxis = [0.0, 0.0, 1.0];
- this.rotateCenter = null;
-}
-
-RotateTool.prototype.handleMouseDown = function(e) {
- this.downPoint = { x: e.x, y: e.y };
- var window_width = g_client.width;
- var window_height = g_client.height;
- var worldRay = o3djs.picking.clientPositionToWorldRay(this.downPoint.x,
- this.downPoint.y,
- this.context,
- window_width,
- window_height);
- this.pickManager.update();
- var pickInfo = this.pickManager.pick(worldRay);
- if (pickInfo) {
- pickedObject = pickInfo.shapeInfo.parent;
- while (pickedObject.parent != null &&
- pickedObject.parent.transform != this.root) {
- dump(pickedObject.transform.name + '\n');
- pickedObject = pickedObject.parent;
- }
- this.selectedObject = pickedObject.transform;
- } else {
- this.selectedObject = null;
- }
- if (this.selectedObject) {
- dump(this.selectedObject.name + '\n');
- this.lastRotation = 0.0;
- } else {
- this.downPoint = null;
- }
-};
-
-RotateTool.prototype.handleMouseUp = function(e) {
- this.downPoint = null;
- this.selectedObject = null;
-};
-
-RotateTool.prototype.handleMouseMove = function(e) {
- if (this.downPoint == null)
- return;
-
- if (e.x === undefined)
- return;
-
- offset = this.downPoint.x - e.x;
- radian_rotation = -10.0 * Math.round(offset / 10.0) * (Math.PI / 180.0);
-
- relative_rotation = radian_rotation - this.lastRotation;
- this.lastRotation = radian_rotation;
-
- if (relative_rotation != 0 && this.selectedObject) {
- matrix = this.selectedObject.localMatrix;
- transformation = g_math.matrix4.axisRotation(this.rotateAxis,
- relative_rotation);
- matrix = g_math.matrix4.mul(transformation, matrix);
- this.selectedObject.localMatrix = matrix;
- }
-};
-
-RotateTool.prototype.handleKeyDown = function(e) {
- return false;
-};
-
-RotateTool.prototype.handleKeyUp = function(e) {
- return false;
-};
diff --git a/o3d/samples/home-configurators/searsassets/sears_bg.png b/o3d/samples/home-configurators/searsassets/sears_bg.png
deleted file mode 100644
index 7842ddf..0000000
--- a/o3d/samples/home-configurators/searsassets/sears_bg.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/home-configurators/searsassets/sears_item_thumbnails.jpg b/o3d/samples/home-configurators/searsassets/sears_item_thumbnails.jpg
deleted file mode 100644
index 428e8fa..0000000
--- a/o3d/samples/home-configurators/searsassets/sears_item_thumbnails.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/home-configurators/viewer.js b/o3d/samples/home-configurators/viewer.js
deleted file mode 100644
index 2e334f4..0000000
--- a/o3d/samples/home-configurators/viewer.js
+++ /dev/null
@@ -1,581 +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 the common functions used by all the home
- * configurator pages.
- */
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.arcball');
-o3djs.require('o3djs.dump');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.shape');
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.picking');
-o3djs.require('o3djs.scene');
-
-var g_root;
-var g_o3d;
-var g_math;
-var g_client;
-var g_thisRot;
-var g_lastRot;
-var g_pack = null;
-var g_mainPack;
-var g_viewInfo;
-var g_pickManager;
-var g_lightPosParam;
-var g_currentTool = null;
-var g_floorplanRoot = null;
-var g_placedModesRoot = null;
-var TOOL_ORBIT = 3;
-var TOOL_MOVE = 1;
-var TOOL_ZOOM_EXTENTS = 6;
-var g_urlToInsert;
-var g_isDraggingItem = false;
-var g_o3dElement = null;
-var g_lastMouseButtonState = 0;
-
-/**
- * Retrieve the absolute position of an element on the screen.
- */
-function getAbsolutePosition(element) {
- var r = { x: element.offsetLeft, y: element.offsetTop };
- if (element.offsetParent) {
- var tmp = getAbsolutePosition(element.offsetParent);
- r.x += tmp.x;
- r.y += tmp.y;
- }
- return r;
-}
-
-/**
- * Retrieve the coordinates of the given event relative to the center
- * of the widget.
- *
- * @param event
- * A mouse-related DOM event.
- * @param reference
- * A DOM element whose position we want to transform the mouse coordinates to.
- * @return
- * An object containing keys 'x' and 'y'.
- */
-function getRelativeCoordinates(event, reference) {
- var x, y;
- event = event || window.event;
- var el = event.target || event.srcElement;
- if (!window.opera && typeof event.offsetX != 'undefined') {
- // Use offset coordinates and find common offsetParent
- var pos = { x: event.offsetX, y: event.offsetY };
- // Send the coordinates upwards through the offsetParent chain.
- var e = el;
- while (e) {
- e.mouseX = pos.x;
- e.mouseY = pos.y;
- pos.x += e.offsetLeft;
- pos.y += e.offsetTop;
- e = e.offsetParent;
- }
- // Look for the coordinates starting from the reference element.
- var e = reference;
- var offset = { x: 0, y: 0 }
- while (e) {
- if (typeof e.mouseX != 'undefined') {
- x = e.mouseX - offset.x;
- y = e.mouseY - offset.y;
- break;
- }
- offset.x += e.offsetLeft;
- offset.y += e.offsetTop;
- e = e.offsetParent;
- }
- // Reset stored coordinates
- e = el;
- while (e) {
- delete e.mouseX;
- delete e.mouseY;
- e = e.offsetParent;
- }
- }
- else {
- // Use absolute coordinates
- var pos = getAbsolutePosition(reference);
- x = event.pageX - pos.x;
- y = event.pageY - pos.y;
- }
-
- return { x: x, y: y };
-}
-
-
-// The target camera has its z and y flipped because that's the way Scott
-// Lininger thinks.
-function TargetCamera() {
- this.eye = {
- rotZ: -Math.PI / 3,
- rotH: Math.PI / 3,
- distanceFromTarget: 700 };
- this.target = { x: 0, y: 0, z: 0 };
-}
-
-TargetCamera.prototype.update = function() {
- var target = [this.target.x, this.target.y, this.target.z];
-
- this.eye.x = this.target.x + Math.cos(this.eye.rotZ) *
- this.eye.distanceFromTarget * Math.sin(this.eye.rotH);
- this.eye.y = this.target.y + Math.sin(this.eye.rotZ) *
- this.eye.distanceFromTarget * Math.sin(this.eye.rotH);
- this.eye.z = this.target.z + Math.cos(this.eye.rotH) *
- this.eye.distanceFromTarget;
-
- var eye = [this.eye.x, this.eye.y, this.eye.z];
- var up = [0, 0, 1];
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(eye, target, up);
- g_lightPosParam.value = eye;
-};
-
-var g_camera = new TargetCamera();
-
-function peg(value, lower, upper) {
- if (value < lower) {
- return lower;
- } else if (value > upper) {
- return upper;
- } else {
- return value;
- }
-}
-
-/**
- * Keyboard constants.
- */
-var BACKSPACE = 8;
-var TAB = 9;
-var ENTER = 13;
-var SHIFT = 16;
-var CTRL = 17;
-var ALT = 18;
-var ESCAPE = 27;
-var PAGEUP = 33;
-var PAGEDOWN = 34;
-var END = 35;
-var HOME = 36;
-var LEFT = 37;
-var UP = 38;
-var RIGHT = 39;
-var DOWN = 40;
-var DELETE = 46;
-var SPACE = 32;
-
-/**
- * Create some global key capturing. Keys that are pressed will be stored in
- * this global array.
- */
-g_keyIsDown = [];
-
-document.onkeydown = function(e) {
- var keycode;
- if (window.event) {
- keycode = window.event.keyCode;
- } else if (e) {
- keycode = e.which;
- }
- g_keyIsDown[keycode] = true;
- if (g_currentTool != null) {
- g_currentTool.handleKeyDown(keycode);
- }
-};
-
-document.onkeyup = function(e) {
- var keycode;
- if (window.event) {
- keycode = window.event.keyCode;
- } else if (e) {
- keycode = e.which;
- }
- g_keyIsDown[keycode] = false;
- if (g_currentTool != null) {
- g_currentTool.handleKeyUp(keycode);
- }
-};
-
-document.onmouseup = function(e) {
- if (g_currentTool != null) {
- g_currentTool.handleMouseUp(e);
- } else {
- cancelInsertDrag();
- }
-};
-
-// NOTE: mouseDown, mouseMove and mouseUp are mouse event handlers for events
-// taking place inside the o3d area. They typically pass the events down
-// to the currently selected tool (e.g. Orbit, Move, etc). Tool and item
-// selection mouse events are registered seperately on their respective DOM
-// elements.
-
-// This function handles the mousedown events that happen inside the o3d
-// area. If a tool is currently selected (e.g. Orbit, Move, etc.) the event
-// is forwarded over to it. If the middle mouse button is pressed then we
-// temporarily switch over to the orbit tool to emulate the SketchUp behavior.
-function mouseDown(e) {
- // If the middle mouse button is used, then switch into the orbit tool,
- // Sketchup-style.
- if (e.button == g_o3d.Event.BUTTON_MIDDLE) {
- g_lastTool = g_currentTool;
- g_lastSelectorLeft = $('toolselector').style.left;
- selectTool(null, TOOL_ORBIT);
- }
-
- if (g_currentTool != null) {
- g_currentTool.handleMouseDown(e);
- }
-}
-
-// This function handles mouse move events inside the o3d area. It simply
-// forwards them down to the currently selected tool.
-function mouseMove(e) {
- if (g_currentTool != null) {
- g_currentTool.handleMouseMove(e);
- }
-}
-
-// This function handles mouse up events that take place in the o3d area.
-// If the middle mouse button is lifted then we switch out of the temporary
-// orbit tool mode.
-function mouseUp(e) {
- // If the middle mouse button was used, then switch out of the orbit tool
- // and reset to their last tool.
- if (e.button == g_o3d.Event.BUTTON_MIDDLE) {
- $('toolselector').style.left = g_lastSelectorLeft;
- g_currentTool = g_lastTool
- }
- if (g_currentTool != null) {
- g_currentTool.handleMouseUp(e);
- }
-}
-
-function scrollMe(e) {
- e = e ? e : window.event;
- var raw = e.detail ? e.detail : -e.wheelDelta;
- if (raw < 0) {
- g_camera.eye.distanceFromTarget *= 11 / 12;
-
- } else {
- g_camera.eye.distanceFromTarget *= (1 + 1 / 12);
- }
- g_camera.update();
-}
-
-function $(name) {
- return document.getElementById(name);
-}
-
-
-// An array of tool objects that will get populated when our base model loads.
-var g_tools = [];
-
-function selectTool(e, opt_toolNumber) {
- var ICON_WIDTH = 32;
- var toolNumber = opt_toolNumber;
-
- if (toolNumber == undefined) {
- // Where you click determines your tool. But since our underlying toolbar
- // graphic isn't perfectly uniform, perform some acrobatics to get the best
- // toolNumber match.
- var pt = getRelativeCoordinates(e, $('toolpanel'));
- if (pt.x < 120) {
- toolNumber = Math.floor((pt.x - 8) / ICON_WIDTH)
- } else {
- toolNumber = Math.floor((pt.x - 26) / ICON_WIDTH)
- }
- toolNumber = peg(toolNumber, 0, 9);
- }
-
- // Now place the selector graphic over the tool we clicked.
- if (toolNumber < 3) {
- $('toolselector').style.left = toolNumber * ICON_WIDTH + 8;
- } else {
- $('toolselector').style.left = toolNumber * ICON_WIDTH + 26;
- }
-
- // Finally, activate the appropriate tool.
- // TODO: Replace this hacky zoom extents tool detection with
- // tools that have an onActivate callback.
- if (toolNumber == TOOL_ZOOM_EXTENTS) {
- // Reset our camera. (Zooming to extents would be better, obviously ;)
- g_camera.eye.distanceFromTarget = 900;
- g_camera.target = { x: -100, y: 0, z: 0 };
- g_camera.update();
-
- // Then reset to the orbit tool, after pausing for a bit so the user
- // sees the zoom extents button depress.
- setTimeout(function() { selectTool(null, TOOL_ORBIT)}, 200);
- } else {
- g_currentTool = g_tools[toolNumber];
- }
-
-}
-
-function loadFile(context, path) {
- function callback(pack, start_move_tool_root, exception) {
- if (exception) {
- alert('Could not load: ' + path + '\n' + exception);
- } else {
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(g_pack, g_viewInfo);
-
- // Manually connect all the materials' lightWorldPos params to the context
- var materials = g_pack.getObjectsByClassName('o3d.Material');
- for (var m = 0; m < materials.length; ++m) {
- var material = materials[m];
- var param = material.getParam('lightWorldPos');
- if (param) {
- param.bind(g_lightPosParam);
- }
- }
-
- /*
- o3djs.dump.dump('---dumping context---\n');
- o3djs.dump.dumpParamObject(context);
-
- o3djs.dump.dump('---dumping root---\n');
- o3djs.dump.dumpTransformTree(g_client.root);
-
- o3djs.dump.dump('---dumping render root---\n');
- o3djs.dump.dumpRenderNodeTree(g_client.renderGraphRoot);
-
- o3djs.dump.dump('---dump g_pack shapes---\n');
- var shapes = g_pack.getObjectsByClassName('o3d.Shape');
- for (var t = 0; t < shapes.length; t++) {
- o3djs.dump.dumpShape(shapes[t]);
- }
-
- o3djs.dump.dump('---dump g_pack materials---\n');
- var materials = g_pack.getObjectsByClassName('o3d.Material');
- for (var t = 0; t < materials.length; t++) {
- o3djs.dump.dump (
- ' ' + t + ' : ' + materials[t].className +
- ' : "' + materials[t].name + '"\n');
- o3djs.dump.dumpParams(materials[t], ' ');
- }
-
- o3djs.dump.dump('---dump g_pack textures---\n');
- var textures = g_pack.getObjectsByClassName('o3d.Texture');
- for (var t = 0; t < textures.length; t++) {
- o3djs.dump.dumpTexture(textures[t]);
- }
-
- o3djs.dump.dump('---dump g_pack effects---\n');
- var effects = g_pack.getObjectsByClassName('o3d.Effect');
- for (var t = 0; t < effects.length; t++) {
- o3djs.dump.dump (' ' + t + ' : ' + effects[t].className +
- ' : "' + effects[t].name + '"\n');
- o3djs.dump.dumpParams(effects[t], ' ');
- }
- */
- }
- if (start_move_tool_root != g_floorplanRoot) {
- selectTool(null, TOOL_MOVE);
- g_tools[TOOL_MOVE].initializeWithShape(start_move_tool_root);
- }
- g_camera.update();
- }
-
- g_pack = g_client.createPack();
- g_pack.name = 'load pack';
-
- new_object_root = null;
- if (g_floorplanRoot == null) {
- // Assign as the floorplan
- g_floorplanRoot = g_pack.createObject('o3d.Transform');
- g_floorplanRoot.name = 'floorplan';
- g_floorplanRoot.parent = g_client.root;
-
- g_placedModelsRoot = g_pack.createObject('o3d.Transform');
- g_placedModelsRoot.name = 'placedModels';
- g_placedModelsRoot.parent = g_floorplanRoot;
-
- // Put the object we're loading on the floorplan.
- new_object_root = g_floorplanRoot;
-
- g_pickManager = o3djs.picking.createPickManager(g_placedModelsRoot);
-
- // Create our set of tools that can be activated.
- // Note: Currently only the Delete, Move, Rotate, Orbit, Pan and Zoom
- // tools are implemented. The last four icons in the toolbar are unused.
- g_tools = [
- new DeleteTool(g_viewInfo.drawContext, g_placedModelsRoot),
- new MoveTool(g_viewInfo.drawContext, g_placedModelsRoot),
- new RotateTool(g_viewInfo.drawContext, g_placedModelsRoot),
- new OrbitTool(g_camera),
- new PanTool(g_camera),
- new ZoomTool(g_camera),
- null,
- null,
- null,
- null
- ]
-
- selectTool(null, TOOL_ORBIT);
- } else {
- // Create a new transform for the loaded file
- new_object_root = g_pack.createObject('o3d.Transform');
- new_object_root.name = 'loaded object';
- new_object_root.parent = g_placedModelsRoot;
-
- }
-
- if (path != null) {
- o3djs.scene.loadScene(g_client, g_pack, new_object_root, path, callback);
- }
-
- return new_object_root;
-}
-
-function setClientSize() {
- // Create a perspective projection matrix
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- 3.14 * 45 / 180, g_client.width / g_client.height, 0.1, 5000);
-}
-
-function resize() {
- setClientSize();
-}
-
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-function initStep2(clientElements) {
- g_o3dElement = clientElements[0];
-
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- path = path.substring(0, index + 1) + g_buildingAsset;
- var url = document.getElementById('url').value = path;
-
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- g_mainPack = g_client.createPack();
- g_mainPack.name = 'simple viewer pack';
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_mainPack,
- g_client.root,
- g_client.renderGraphRoot,
- [1, 1, 1, 1]);
-
- g_lastRot = g_math.identity(3);
- g_thisRot = g_math.identity(3);
-
- var root = g_client.root;
-
- var target = [0, 0, 0];
- var eye = [0, 0, 5];
- var up = [0, 1, 0];
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(eye, target, up);
-
- setClientSize();
-
- var paramObject = g_mainPack.createObject('ParamObject');
- // Set the light at the same position as the camera to create a headlight
- // that illuminates the object straight on.
- g_lightPosParam = paramObject.createParam('lightWorldPos', 'ParamFloat3');
- g_lightPosParam.value = eye;
-
- doload();
-
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', mouseDown);
- o3djs.event.addEventListener(g_o3dElement, 'mousemove', mouseMove);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', mouseUp);
-
- g_o3dElement.addEventListener('mouseover', dragOver, false);
- // for Firefox
- g_o3dElement.addEventListener('DOMMouseScroll', scrollMe, false);
- // for Safari
- g_o3dElement.onmousewheel = scrollMe;
-
- document.getElementById('toolpanel').onmousedown = selectTool;
-
- // Create our catalog list from the global list of items (g_items).
- html = [];
- for (var i = 0; i < g_items.length; i++) {
- html.push('<div class="catalogItem" onmousedown="startInsertDrag(\'',
- g_items[i].url, '\')" style="background-position:-', (i * 62) ,
- 'px 0px" title="', g_items[i].title, '"></div>');
- }
- $('itemlist').innerHTML = html.join('');
-
- // Register a mouse-move event listener to the entire window so that we can
- // catch the click-and-drag events that originate from the list of items
- // and end up in the o3d element.
- document.addEventListener('mousemove', mouseMove, false);
-}
-
-function dragOver(e) {
- if (g_urlToInsert != null) {
- doload(g_urlToInsert);
- }
- g_urlToInsert = null;
-}
-
-function doload(opt_url) {
- var url;
- if (opt_url != null) {
- url = opt_url
- } else if ($('url')) {
- url = $('url').value;
- }
- g_root = loadFile(g_viewInfo.drawContext, url);
-}
-
-function startInsertDrag(url) {
- // If no absolute web path was passed, assume it's a local file
- // coming from the assets directory.
- if (url.indexOf('http') != 0) {
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- g_urlToInsert = path.substring(0, index + 1) + g_assetPath + url;
- } else {
- g_urlToInsert = url;
- }
-}
-
-function cancelInsertDrag() {
- g_urlToInsert = null;
-}
-
diff --git a/o3d/samples/home-configurators/zoomtool.js b/o3d/samples/home-configurators/zoomtool.js
deleted file mode 100644
index 117044e..0000000
--- a/o3d/samples/home-configurators/zoomtool.js
+++ /dev/null
@@ -1,76 +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.
- */
-
-
-/**
- * The Zoom tool allows the user to Zoom around the view by clicking and
- * dragging.
- */
-function ZoomTool(camera) {
- this.camera = camera;
- this.dragging = false;
- this.lastOffsetY = null;
-}
-
-ZoomTool.prototype.handleMouseDown = function(e) {
- this.lastOffsetY = e.y;
- this.dragging = true;
-};
-
-ZoomTool.prototype.handleMouseMove = function(e) {
- if (this.dragging && e.x !== undefined) {
- dY = (e.y - this.lastOffsetY);
- this.lastOffsetY = e.y;
-
- var zoomLevels = Math.abs(dY / 6);
- var zoomChange;
- if (dY < 0) {
- zoomChange = Math.pow(11 / 12, zoomLevels);
- } else {
- zoomChange = Math.pow((1 + 1 / 12), zoomLevels);
- }
- this.camera.eye.distanceFromTarget *= zoomChange;
-
- this.camera.update();
- }
-};
-
-ZoomTool.prototype.handleMouseUp = function(e) {
- this.dragging = false;
-};
-
-ZoomTool.prototype.handleKeyDown = function(e) {
- return false;
-};
-
-ZoomTool.prototype.handleKeyUp = function(e) {
- return false;
-};
diff --git a/o3d/samples/hud-2d-overlay.html b/o3d/samples/hud-2d-overlay.html
deleted file mode 100644
index e22eb7f..0000000
--- a/o3d/samples/hud-2d-overlay.html
+++ /dev/null
@@ -1,491 +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.
--->
-
-<!--
-HUD 2D Overlay.
-
-This example shows implementing a HUD or 2d Overlay
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-HUD 2D Overlay.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.loader');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_3dRoot;
-var g_hudRoot;
-var g_viewInfo;
-var g_hudViewInfo;
-var g_pack;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-var g_cameraRadius = 35;
-var g_cameraSpeed = 0.3;
-var g_gaugeWidth = 145;
-var g_gaugeHeight = 16;
-var g_planeShape;
-var g_groundShape;
-var g_cubeShape;
-var g_materialUrls = [
- 'shaders/texture-colormult.shader', // 0
- 'shaders/phong-with-colormult.shader' // 1
-];
-var g_materials = [];
-var g_textures = [];
-var g_textureUrls = [
- 'assets/purple-flower.png', // 0
- 'assets/orange-flower.png', // 1
- 'assets/egg.png', // 2
- 'assets/gaugeback.png', // 3
- 'assets/gauge.png', // 4
- 'assets/iconback.png', // 5
- 'assets/radar.png', // 6
- 'assets/one-pixel-white.tga' // 7
-];
-var g_radar;
-var g_radarNeedle;
-var g_gaugeBack;
-var g_gauges = [];
-var g_gaugeFrames = [];
-var g_iconBacks = [];
-var g_icons = [];
-var g_selectedIndex = 0;
-var g_randSeed = 0;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create 2 root transforms, one for the 3d parts, one for the 2d parts.
- // This is not strictly neccassary but it is helpful for organization.
- g_3dRoot = g_pack.createObject('Transform');
- g_hudRoot = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_3dRoot,
- g_client.renderGraphRoot);
-
- // Create a second view for the hud. There are other ways to do this but
- // this is the easiest.
- g_hudViewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_hudRoot,
- g_client.renderGraphRoot);
-
- // Make sure the hud gets drawn after the 3d stuff
- g_hudViewInfo.root.priority = g_viewInfo.root.priority + 1;
-
- // Turn off clearing the color for the hud since that would erase the 3d
- // parts but leave clearing the depth and stencil so the HUD is unaffected
- // by anything done by the 3d parts.
- g_hudViewInfo.clearBuffer.clearColorFlag = false;
-
- // Set culling to none so we can flip images using rotation or negative scale.
- g_hudViewInfo.zOrderedState.getStateParam('CullMode').value =
- g_o3d.State.CULL_NONE;
- g_hudViewInfo.zOrderedState.getStateParam('ZWriteEnable').value = false;
-
- // Create an orthographic matrix for 2d stuff in the HUD.
- // We assume the area is 800 pixels by 600 pixels and therefore we can
- // position things using a 0-799, 0-599 coordinate system. If we change the
- // size of the client area everything will get scaled to fix but we don't
- // have to change any of our code. See 2d.html
- g_hudViewInfo.drawContext.projection = g_math.matrix4.orthographic(
- 0 + 0.5,
- 800 + 0.5,
- 600 + 0.5,
- 0 + 0.5,
- 0.001,
- 1000);
-
- g_hudViewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 0, 1], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree fov.
- g_client.width / g_client.height,
- 0.1, // Near plane.
- 5000); // Far plane.
-
- for (var ii = 0; ii < g_materialUrls.length; ++ii) {
- var material = o3djs.material.createMaterialFromFile(
- g_pack,
- g_materialUrls[ii],
- g_viewInfo.performanceDrawList);
-
- // Set the default params. We'll override these with params on transforms.
- material.getParam('colorMult').value = [1, 1, 1, 1];
-
- g_materials[ii] = material;
- }
-
- // Set the materials' drawLists
- g_materials[0].drawList = g_hudViewInfo.zOrderedDrawList;
- g_materials[1].drawList = g_viewInfo.performanceDrawList;
-
- g_materials[1].getParam('lightWorldPos').value = [500, 1000, 0];
- g_materials[1].getParam('lightIntensity').value = [1, 1, 1, 1];
- g_materials[1].getParam('ambientIntensity').value = [0.1, 0.1, 0.1, 1];
- g_materials[1].getParam('ambient').value = [1, 1, 1, 1];
- g_materials[1].getParam('diffuse').value = [1, 1, 1, 1];
- g_materials[1].getParam('specular').value = [0.5, 0.5, 0.5, 1];
- g_materials[1].getParam('shininess').value = 20;
-
- // Create a 2d plane for images. createPlane makes an XZ plane by default
- // so we pass in matrix to rotate it to an XY plane. We could do
- // all our manipluations in XZ but most people seem to like XY for 2D.
- g_planeShape = o3djs.primitives.createPlane(
- g_pack,
- g_materials[0],
- 1,
- 1,
- 1,
- 1,
- [[1, 0, 0, 0],
- [0, 0, 1, 0],
- [0,-1, 0, 0],
- [0, 0, 0, 1]]);
-
- // Create a ground plane
- g_groundShape = o3djs.primitives.createPlane(
- g_pack,
- g_materials[1],
- 30,
- 30,
- 10,
- 10);
-
- // Create a cube with its origin at the bottom center.
- g_cubeShape = o3djs.primitives.createCube(
- g_pack,
- g_materials[1],
- 1,
- [[0.9, 0, 0, 0],
- [0, 1, 0, 0],
- [0, 0, 0.9, 0],
- [0, 0.5, 0, 1]]);
-
- // Load all the textures.
- var loader = o3djs.loader.createLoader(initStep3);
- for (var ii = 0; ii < g_textureUrls.length; ++ii) {
- loadTexture(loader, g_textureUrls[ii], ii);
- }
- loader.finish();
-}
-
-/**
- * Loads a texture and saves it in the g_textures array.
- * @param {Object} loader The loader to load with.
- * @param {stinrg} url of texture to load
- * @param {number} index Index to put texture in g_textures
- */
-function loadTexture(loader, url, index) {
- loader.loadTexture(g_pack, url, function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- g_textures[index] = texture;
- }
- });
-}
-
-/**
- * Now that the textures are loaded continue.
- */
-function initStep3() {
- // Setup the hud images.
- g_radar = new Image(g_textures[6], true);
- g_radar.transform.translate(3, 1, -2);
-
- g_radarNeedle = new Image(g_textures[7], false);
- g_radarNeedle.scaleTransform.translate(0, 0.5, 0);
-
- g_gaugeBack = new Image(g_textures[3], true);
- g_gaugeBack.transform.translate(201, 17, -2);
-
- for (var ii = 0; ii < 3; ++ii) {
- g_gaugeFrames[ii] = new Image(g_textures[4], true);
- g_gaugeFrames[ii].transform.translate(220, 39 + ii * 21, -2);
-
- g_gauges[ii] = new Image(g_textures[7], true);
- g_gauges[ii].setColor((ii == 0) ? 1 : 0,
- (ii == 1) ? 1 : 0,
- (ii == 2) ? 1 : 0,
- 1);
-
- g_iconBacks[ii] = new Image(g_textures[5], true);
- g_iconBacks[ii].transform.translate(634, 17 + ii * 140, -2);
-
- // Make the icons' origin their center so we can easily rotate/scale them.
- g_icons[ii] = new Image(g_textures[ii], false);
- }
-
- resetIcons();
-
- // make the ground plane.
- var transform = g_pack.createObject('Transform');
- transform.addShape(g_groundShape);
- transform.parent = g_3dRoot;
- transform.createParam('colorMult', 'ParamFloat4').value =
- [166 / 255, 124 / 255, 82 / 255, 1];
-
- // Make a random city with 25 blocks.
- for (var bz = -2; bz <= 2; ++bz) {
- for (var bx = -2; bx <= 2; ++bx) {
- for (var xx = 0; xx < 4; ++xx) {
- createBuilding(bx * 5 + 1 + xx - 1.5, bz * 5 + 1 - 1.5);
- createBuilding(bx * 5 + 1 + xx - 1.5, bz * 5 + 4 - 1.5);
- }
- for (var zz = 1; zz < 3; ++zz) {
- createBuilding(bx * 5 + 1 - 1.5, bz * 5 + 1 + zz - 1.5);
- createBuilding(bx * 5 + 4 - 1.5, bz * 5 + 1 + zz - 1.5);
- }
- }
- }
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Creates a building.
- * @param {number} x X coordinate to create building at
- * @param {number} z Y coordinate to create building at
- */
-function createBuilding(x, z) {
- var transform = g_pack.createObject('Transform');
- transform.addShape(g_cubeShape);
- transform.parent = g_3dRoot;
- transform.translate(x, 0, z);
- transform.scale(1, g_math.pseudoRandom() * 3 + 1, 1);
- transform.createParam('colorMult', 'ParamFloat4').value = [
- g_math.pseudoRandom() * 0.6 + 0.4,
- g_math.pseudoRandom() * 0.6 + 0.4,
- g_math.pseudoRandom() * 0.6 + 0.4,
- 1];
-}
-
-/**
- * Resets the orientation of the icons.
- */
-function resetIcons() {
- for (var ii = 0; ii < g_icons.length; ++ii) {
- g_icons[ii].transform.identity();
- g_icons[ii].transform.translate(634 + 6 + 64, 17 + ii * 140 + 5 + 64, -1);
- g_icons[ii].transform.scale(0.8, 0.8, 0);
- }
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onrender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- g_selectedIndex = Math.floor(g_clock / 3) % 3;
-
- // Fly the camera around the city.
- var eye = [
- Math.sin(g_clock * g_cameraSpeed) * g_cameraRadius,
- 10,
- Math.cos(g_clock * g_cameraSpeed) * g_cameraRadius];
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- eye,
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- for (var i = 0; i < g_icons.length; i++) {
- var icon = g_icons[i];
- icon.transform.identity();
- icon.transform.translate(
- 634 + 6 + 64, 17 + i * 140 + 5 + 64, -1);
- if (i == g_selectedIndex) {
- icon.transform.rotateZ(g_clock * -1);
- var scale = Math.sin(g_clock * 15) * 0.1 + 0.7;
- icon.transform.scale(scale, scale, 1);
- } else {
- icon.transform.scale(0.8, 0.8, 0);
- }
- }
-
- // Adjust the gauges
- for (var ii = 0; ii < 3; ++ii) {
- var gauge = g_gauges[ii];
- gauge.transform.identity();
- gauge.transform.translate(220 + 1, 39 + ii * 21 + 1, -1);
- switch (ii) {
- case 0:
- gauge.transform.scale((Math.sin(g_clock) * 0.5 + 0.5) * g_gaugeWidth,
- g_gaugeHeight,
- 1);
- break;
- case 1:
- gauge.transform.scale((Math.cos(g_clock) * 0.5 + 0.5) * g_gaugeWidth,
- g_gaugeHeight,
- 1);
- break;
- case 2:
- gauge.transform.scale(
- (Math.cos(g_clock * 3.2) * 0.2 + 0.6) * g_gaugeWidth,
- g_gaugeHeight,
- 1);
- break;
- }
- }
-
- // Rotate the radar
- g_radarNeedle.transform.identity();
- g_radarNeedle.transform.translate(93, 89, 0);
- g_radarNeedle.transform.rotateZ(g_clock * 3);
- g_radarNeedle.transform.scale(1, 80, 1);
-}
-
-/**
- * Creates an Image object which is a transform and a child scaleTransform
- * scaled to match the texture
- *
- * @constructor
- * @param {!o3d.Texture} texture The texture
- * @param {boolean} opt_topLeft If true the origin of the image will be its
- * topleft corner, the default is the center of the image.
- */
-function Image(texture, opt_topLeft) {
- // create a transform for positioning
- this.transform = g_pack.createObject('Transform');
- this.transform.parent = g_hudRoot;
-
- // create a transform for scaling to the size of the image just so
- // we don't have to manage that manually in the transform above.
- this.scaleTransform = g_pack.createObject('Transform');
- this.scaleTransform.parent = this.transform;
-
- // setup the sampler for the texture
- this.sampler = g_pack.createObject('Sampler');
- this.sampler.addressModeU = g_o3d.Sampler.CLAMP;
- this.sampler.addressModeV = g_o3d.Sampler.CLAMP;
- this.paramSampler = this.scaleTransform.createParam('texSampler0',
- 'ParamSampler');
- this.paramSampler.value = this.sampler;
-
- // Setup our UV offsets and color multiplier
- this.paramColorMult = this.scaleTransform.createParam('colorMult',
- 'ParamFloat4');
-
- this.setColor(1, 1, 1, 1);
-
- this.sampler.texture = texture;
- this.scaleTransform.addShape(g_planeShape);
- if (opt_topLeft) {
- this.scaleTransform.translate(texture.width / 2, texture.height / 2, 0);
- }
- this.scaleTransform.scale(texture.width, -texture.height, 1);
-}
-
-/**
- * Sets the color multiplier for the image.
- * @param {number} r Red component.
- * @param {number} g Green component.
- * @param {number} b Blue component.
- * @param {number} a Alpha component.
- */
-Image.prototype.setColor = function(r, g, b, a) {
- this.paramColorMult.set(r, g, b, a);
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>HUD 2D Overlay</h1>
-HUD = Heads Up Display.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/iframeit.html b/o3d/samples/iframeit.html
deleted file mode 100644
index ad29079..0000000
--- a/o3d/samples/iframeit.html
+++ /dev/null
@@ -1,132 +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.
--->
-
-<style type="text/css" media="screen">
- body {
- background: #FDFCE9;
- }
-</style>
-
-<script type="text/javascript" charset="utf-8">
-var errors = [];
-window.onerror = onError;
-addEvent(window, 'load', load);
-
-// Set focus to this iframe
-this.focus();
-code = parent.codeToRun;
-
-try {
- document.write(code);
-} catch(e) {
- alert(e.message);
-}
-
-
-function addEvent(a,b,c,d) {
- if (a.addEventListener) {
- a.addEventListener(b,c,d?true:false);
- } else if(a.attachEvent) {
- a.attachEvent('on'+b,c);
- } else{
- a['on'+b]=c;
- }
-}
-
-function changeOverlayZIndex() {
- // This is a little hack to fix the overlay covering up <object> tags.
- // TODO: clean this up. Did this because it was fast hack
- var lastZ = parent.iframeZindex;
- var newZ;
- if (typeof lastZ != 'undefined') {
- newZ = parseInt(lastZ) - 1;
- } else {
- newZ = 4999;
- }
-
- parent.iframeZindex = newZ;
-
- var overlay = parent.document.getElementById('overlay');
- overlay.style.zIndex = newZ;
-}
-
-function load() {
- var first = document.getElementsByTagName('body')[0].childNodes[0];
- for (var i=0; i < errors.length; i++) {
- document.body.insertBefore(errors[i], first);
- }
-
- changeOverlayZIndex();
-}
-
-function Stack() { try { throw Error() } catch(ex) { return ex.stack } }
-
-function onError(msg, href, lineNo) {
- var errorDiv = document.createElement('div');
- errorDiv.style.textAlign = 'center';
- errorDiv.style.fontWeight = 'bold';
- errorDiv.style.fontSize = '92%';
- errorDiv.style.width = '100%';
- errorDiv.style.padding = '0.5em 0';
- var html = [];
-
- var lastSlash = href.lastIndexOf("/");
- var fileName = lastSlash == -1 ? href : href.substr(lastSlash+1);
-
- html.push(
- '<span style="display: inline-block;background: #ffd363 url(interactive_sampler_assets/images/tl.gif) top left no-repeat;">',
- '<span style="background: url(interactive_sampler_assets/images/bl.gif) bottom left no-repeat;">',
- '<span style="background: url(interactive_sampler_assets/images/tr.gif) top right no-repeat;">',
- '<span style="background: url(interactive_sampler_assets/images/br.gif) bottom right no-repeat;">',
- '<span style="background: transparent;padding: 0.2em 2em;color: #ce0c0c">',
- 'Error: ' + msg,
- '</span>',
- '</span>',
- '</span>',
- '</span>',
- '</span>'
- );
- errorDiv.innerHTML = html.join('\n');
-
- // In some firefox's, the body tag isn't loaded so we can't print the error.
- // We have to wait until the body tag loads, then we print.
- // In other firefox's, the body loads before errors are fired, so we can add
- // immediately
- var first = document.getElementsByTagName('body')[0];
- if (first && first.childNodes) {
- first = first.childNodes[0];
- document.body.insertBefore(errorDiv, first);
- } else {
- errors.push(errorDiv);
- }
-};
-
-</script>
diff --git a/o3d/samples/instance-override.html b/o3d/samples/instance-override.html
deleted file mode 100644
index 8366a4d..0000000
--- a/o3d/samples/instance-override.html
+++ /dev/null
@@ -1,180 +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.
--->
-
-<!--
-O3D Instancing Override example.
-
-Display a single instanced object but change some shader parameters for each
-instance by putting them on the transform.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Instancing with Overrides.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing.
-
-function createInstances(pack, shape) {
- // make a grid of transforms and put a teapot instance on each one
- for (var x = 0; x < 10; x++) {
- for (var y = 0; y < 10; y++) {
- for (var z = 0; z < 10; z++) {
- var transform = pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.addShape(shape);
- transform.translate((x - 4.5) * 100,
- (y - 4.5) * 100,
- (z - 4.5) * 100);
- transform.createParam('diffuse', 'ParamFloat4').value = [
- x * 0.1,
- y * 0.1,
- z * 0.1,
- 1.0];
- }
- }
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates a sphere.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 10000);
-
- // Create a material.
- var material = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [1, 1, 1, 1]);
-
- // Create a sphere.
- var shape = o3djs.primitives.createSphere(g_pack, material, 25, 10, 12);
-
- createInstances(g_pack, shape);
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-// spin the camera.
-function onrender(render_event) {
- // Get the number of seconds since the last render.
- var elapsedTime = render_event.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- var x = Math.sin(g_clock * 0.3) * 1000;
- var z = Math.cos(g_clock * 0.3) * 1000;
- var y = Math.sin(g_clock * 0.7) * 500;
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [x, y, z], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Instancing with overrides</h1>
-1000 Instances of the same sphere.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/instancing.html b/o3d/samples/instancing.html
deleted file mode 100644
index 9612203..0000000
--- a/o3d/samples/instancing.html
+++ /dev/null
@@ -1,208 +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.
--->
-
-<!--
-O3D Instancing example.
-
-Load the teapot, display it a bunch of times.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Instancing.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- */
-function loadScene(pack, fileName, parent) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
-
- // Find the "shape" for the teapot.
- // I'm going to assume there is only one since I know the contents
- // of the file.
- var shape = pack.getObjectsByClassName('o3d.Shape')[0];
-
- // now make a grid of transforms and put a teapot instance on each one
- for (var x = 0; x < 10; x++) {
- for (var y = 0; y < 10; y++) {
- for (var z = 0; z < 10; z++) {
- var transform = pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.addShape(shape);
- var angles = [
- (x - 4.5) * 0.2,
- (y - 4.5) * 0.2,
- (z - 4.5) * 0.2];
- transform.translate((x - 4.5) * 100,
- (y - 4.5) * 100,
- (z - 4.5) * 100);
- transform.rotateZYX(angles);
- }
- }
- }
-
- g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 10000);
-
- // Creates a transform to put our data on.
- var my_data_root = g_pack.createObject('Transform');
-
- // Load the scene into the transform graph as a child my_data_root
- loadScene(g_pack, 'assets/teapot.o3dtgz', my_data_root);
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-}
-
-// spin the camera.
-function onrender(render_event) {
- // Get the number of seconds since the last render.
- var elapsedTime = render_event.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- var x = Math.sin(g_clock * 0.41) * 400;
- var z = Math.cos(g_clock * 0.31) * 1000;
- var y = Math.sin(g_clock * 0.61) * 200;
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt([x, y, z], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Instancing</h1>
-1000 Teapots
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/interactive_logic.js b/o3d/samples/interactive_logic.js
deleted file mode 100644
index e2f9eed..0000000
--- a/o3d/samples/interactive_logic.js
+++ /dev/null
@@ -1,576 +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.
- */
-
-
-/**
- * @fileoverview This file is the master javascript file for the interactive
- * editor/runner for all the simple samples.
- *
- */
-// For browserFun
-// TODO:
-// Make it so that you can make the code editing window wider...
-// Make it so that you can click links to the documentation of each object
-// Add Ping Pong
-// Fix the spacing in the editor (when u hit tab)
-// Try to see if for the javascript part you can eval line by line so that you
-// can output the line number
-
-var fileTypes = {
- 'js' : 'javascript',
- 'html' : 'html',
- 'php' : 'php'
-};
-
-function InteractiveSample() {
- this.categories = [];
- this.codeTitles = [];
- this.adjustCodeBoxAmount = 50;
- this.selectCode;
- this.codeDiv;
- this.codeLIs = [];
- this.currentCode = new Object();
- this.curI = '';
- this.cleanWindowObj;
-
- // Assume we're offline until we know that file reading doesn't work
- this.online = false;
-}
-
-function sortByCategory(a, b) {
- return a.category > b.category;
-}
-
-function sortByName(a, b) {
- return a.sampleName > b.sampleName;
-}
-
-function nameToHashName(name) {
- var hashName = name.toLowerCase();
- hashName = hashName.replace(/ /g, '_');
- return hashName;
-}
-
-InteractiveSample.prototype.init = function(codeDiv) {
- this.codeDiv = codeDiv;
- this.createCategories();
- this.addShowHideClicks();
-
- // TODO: Sort samples
- // codeArray.sort(sortByCategory);
- //
- // for (var i=0; i < codeArray.length; i++) {
- // codeArray[i].samples.sort(sortByName);
- // }
-
- // Gotta set this for the iFrame to know it and change it
- // This is specific to O3D because a transparent overlay that is
- // under the <object> tag will actually hide the <object> tag
- // unless we muck with the zIndex after the <object> loads
- window.iframeZindex = '4999';
-
- // This is so that we can restore the first level of the window object
- // after we run a sample... so samples can get run a lot and not clutter
- // the window object.
- this.cleanWindowObj = singleLevelKeyCopy(window);
-};
-
-InteractiveSample.prototype.createCategories = function() {
- // codeArray is from interactive_samples.js
- this.selectCode = _gel('selectCode');
-
- for (var i = 0; i < codeArray.length; i++) {
- var container = _cel('span');
- container.className = 'category';
-
- var catName = _cel('span');
-
- var img = _cel('img');
- img.className = 'collapse';
- img.src = 'interactive_sampler_assets/images/cleardot.gif';
- // addEvent(img, 'click', this.toggleExpand(img), false);
-
- catName.appendChild(img);
- catName.innerHTML += codeArray[i].category;
-
- container.appendChild(catName);
-
- var ul = _cel('ul');
- ul.className = 'categoryItems';
-
- container.appendChild(ul);
-
- for (var j = 0; j < codeArray[i].samples.length; j++) {
- var item = codeArray[i].samples[j];
- var li = _cel('li');
-
- li.innerHTML = item.sampleName;
-
- this.codeTitles.push(li);
- var files = []
- for (var index = 0; index < codeArray[i].samples[j].files.length;
- ++index) {
- var dirName = '';
- var baseName = codeArray[i].samples[j].files[index];
- var slashIndex = baseName.lastIndexOf('/');
- if (slashIndex >= 0) {
- dirName = baseName.substring(0, slashIndex + 1);
- baseName = baseName.substring(slashIndex + 1);
- }
- files[index] = dirName + 'sampler_' + baseName;
- }
- //var files = codeArray[i].samples[j].files;
- addEvent(li, 'click', this.showSample(this, item, files, li));
-
- if (i == 0 && j == 0) {
- this.showSample(this, item, files, li, true)();
- }
-
- if (window.location.hash.length > 0) {
- var hashName = nameToHashName(item.sampleName);
- if (window.location.hash.substring(1) == hashName) {
- this.showSample(this, item, files, li)();
- }
- }
-
- this.codeLIs.push(li);
- ul.appendChild(li);
- }
-
- this.selectCode.appendChild(container);
- this.categories.push(container);
- }
-};
-
-InteractiveSample.prototype.toggleShowHide = function(category,
- interactiveSample) {
- return function() {
- var li = category.nextSibling;
- var el = category.childNodes[0];
- if (el.className == 'expand')
- el.className = 'collapse';
- else
- el.className = 'expand';
-
- if (li.style.display == 'none') {
- li.style.display = 'block';
- } else {
- li.style.display = 'none';
- }
- };
-};
-
-InteractiveSample.prototype.addShowHideClicks = function() {
- for (var i = 0; i < this.categories.length; i++) {
- categoryName = this.categories[i].childNodes[0];
- addEvent(categoryName, 'click', this.toggleShowHide(categoryName, this));
- }
-};
-
-InteractiveSample.prototype.loadLocally = function(relativeUrl, filename,
- fileType,
- opt_changeCodeMirror) {
- // readFile is in utils.js
- var data = readFile(relativeUrl);
- if (data == null) {
- this.online = true;
- return false;
- }
- if (fileType == 'javascript') {
- data = this.replaceV8Call(data);
- }
- if (opt_changeCodeMirror == true) {
- this.changeCodeMirror(data, fileType);
- }
- is_instance.currentCode[filename] = {
- code : data
- };
- console.log(relativeUrl + ': loaded locally.');
-
- return true;
-};
-
-InteractiveSample.prototype.loadRemotely = function(relativeUrl, filename,
- fileType,
- opt_changeCodeMirror) {
- is_instance = this;
- downloadUrl(relativeUrl, function(data, status) {
- if (fileType == 'javascript') {
- data = this.replaceV8Call(data);
- }
- if (opt_changeCodeMirror == true) {
- is_instance.changeCodeMirror(data, fileType);
- }
- is_instance.currentCode[filename] = {
- code : data
- };
- });
-};
-
-InteractiveSample.prototype.loadCode = function(filename,
- opt_changeCodeMirror) {
- // If the code is in the currentCode buffer, then grab it there
- // otherwise, load it via XHR
- // If opt_changeCodeMirror is specified, load it into the window
-
- // Get filetype
- var filenameSplit = filename.split('.');
- var extension = filenameSplit[filenameSplit.length - 1];
- var fileType = fileTypes[extension.toLowerCase()];
- var inBuffer = (this.currentCode[filename] &&
- this.currentCode[filename].code) ? true : false;
- if (inBuffer && opt_changeCodeMirror == true) {
- this.changeCodeMirror(this.currentCode[filename].code, fileType);
- } else {
- var relativeUrl = filename;
- is_instance = this;
-
- if (!this.online) {
- this.loadLocally(relativeUrl, filename, fileType, opt_changeCodeMirror);
- }
-
- if (this.online) {
- this.loadRemotely(relativeUrl, filename, fileType, opt_changeCodeMirror);
- }
- }
-};
-
-// TODO: can is_instance just be set as is_instance = this above return
-// function()
-InteractiveSample.prototype.showSample = function(is_instance, codeItem,
- files, thisLI, def) {
- return function() {
- is_instance.refreshInlinePlugin();
-
- var codeDiv = is_instance.codeDiv;
- var codeLIs = is_instance.codeLIs;
- for (var i = 0; i < codeLIs.length; i++) {
- codeLIs[i].className = '';
- }
-
- // turn off the "Run Here" button if this sample should be run in its own
- // window.
- var runHere = document.getElementById('runHere');
- runHere.style.visibility = codeItem.ownWindow ? 'hidden' : 'visible';
-
- // For linking purposes
- if (!def) {
- window.location.hash = nameToHashName(thisLI.innerHTML);
- }
-
- // Make code selected designate this as selected
- thisLI.className = 'selected';
-
- is_instance.currentCode = new Object();
-
-
- // add file names at top
- var tab_bar = _gel('tab_bar');
- tab_bar.innerHTML = '';
-
- // prototype syntax
- files.each(function(file, index) {
-
- var tabClass = 'lb';
- if (index == 0) {
- tabClass = 'db';
- is_instance.loadCode(file, true);
- } else {
- is_instance.loadCode(file, false);
- }
-
-
- var containerDiv = _cel('div');
- containerDiv.className = 'roundedcornr_box';
- addEvent(containerDiv, 'click', is_instance.changeTab(file, is_instance));
-
- var html = '<div class="' + tabClass + '_top" ><div></div></div>';
- html += '<div class="' + tabClass + '_roundedcornr_content" >';
- html += file;
- html += '</div>';
-
- containerDiv.innerHTML = html;
-
- tab_bar.appendChild(containerDiv);
- });
-
- // is_instance.loadCode(files[0], textArea);
- is_instance.curI = files[0];
- };
-};
-
-InteractiveSample.prototype.changeTab = function(i, is_instance) {
- return function() {
- var siblings = this.parentNode.childNodes;
- is_instance.currentCode[is_instance.curI].code = is_instance.getCode();
-
- // Swap the colors of the tabs
- for (var z = 0; z < siblings.length; z++) {
- if (siblings[z].childNodes[1].innerHTML == i) {
- siblings[z].childNodes[0].className = 'db_top';
- siblings[z].childNodes[1].className = 'db_roundedcornr_content';
- } else {
- siblings[z].childNodes[0].className = 'lb_top';
- siblings[z].childNodes[1].className = 'lb_roundedcornr_content';
- }
- }
-
- is_instance.loadCode(i, true);
- is_instance.curI = i;
- };
-};
-
-InteractiveSample.prototype.increaseCodeBoxHeight = function() {
- var curHeight = this.textArea.style.height;
- curHeight = curHeight.substr(0, curHeight.indexOf('px'));
- var newHeight = parseInt(curHeight) + this.adjustCodeBoxAmount;
- newHeight += 'px';
- this.textArea.style.height = newHeight;
-};
-
-InteractiveSample.prototype.decreaseCodeBoxHeight = function() {
- var curHeight = this.textArea.style.height;
- curHeight = curHeight.substr(0, curHeight.indexOf('px'));
- var newHeight = parseInt(curHeight) - this.adjustCodeBoxAmount;
- newHeight += 'px';
- this.textArea.style.height = newHeight;
-};
-
-InteractiveSample.prototype.replaceV8Call = function(code) {
- return code.replace(
- /(o3djs.util.setMainEngine[^;\n]+)[;\n]/,
- "\n // Can't use V8 in the interactive sampler yet.\n //$1");
-}
-
-InteractiveSample.prototype.prepareAllCodeRun = function() {
- // TODO: Change this so it doesn't rely on the first file being HTML
- // TODO: Change this to use REGEX to replace
- this.deleteOldWindowStuff();
-
- this.refreshInlinePlugin();
- this.currentCode[this.curI].code = this.getCode();
-
- var html = '';
- for (var i in this.currentCode) {
- if (i.indexOf('.html') != -1)
- html = this.currentCode[i].code;
- }
- var pattern = /<script\s*(type\s*=\s*"[^"]*"\s*)?src\s*=\s*"/g;
- var result;
- while ((result = pattern.exec(html)) != null) {
- var scriptSrc = pattern.lastIndex;
- var scriptSrcEnd = html.indexOf('"', scriptSrc);
- var script = html.substring(scriptSrc, scriptSrcEnd);
- var endScriptLoc = html.indexOf('</script>', scriptSrcEnd) + 9;
- var found = false;
- for (var z in this.currentCode) {
- if (z == script) {
- var data = this.replaceV8Call(this.currentCode[z].code);
- script = '<script type="text/javascript" charset="utf-8">' + data +
- '</script>';
- found = true;
- break;
- }
- }
- if (found) {
- html = html.substring(0, result.index) + script +
- html.substring(endScriptLoc);
- }
- }
-
- // console.log(html);
- window.codeToRun = html;
-
- // console.log(html.slice(scriptLoc, endScriptLoc));
- // console.log(html);
-};
-
-InteractiveSample.prototype.refreshInlinePlugin = function() {
- var o3dobject = _gel('o3d');
- o3dparent = o3dobject.parentNode;
- o3dparent.removeChild(o3dobject);
-
- var nO3D = _cel('div');
- nO3D.id = 'o3d';
- nO3D.style.width = '300px';
- nO3D.style.height = '300px';
- nO3D.style.backgroundColor = 'gray';
-
- o3dparent.appendChild(nO3D);
-};
-
-InteractiveSample.prototype.runJS = function() {
- // TODO don't assume that we run javascript in any order. Make it so that
- // it checks the HTML for which order JS goes in
- this.refreshInlinePlugin();
-
- // console.log(this.currentCode[0].code.split('\n'));
- window.is.startJS();
-};
-
-InteractiveSample.prototype.deleteOldWindowStuff = function() {
- for (var i in window) {
- if (typeof this.cleanWindowObj[i] == 'boolean' &&
- this.cleanWindowObj[i] == true) {
- } else {
- window[i] = null; // Delete doesn't remove properties created with var.
- delete window[i]; // But just in case we can, we do.
- }
- }
-};
-
-InteractiveSample.prototype.startJS = function() {
- this.deleteOldWindowStuff();
- var topHolder = _gel('HTMLforInlineJavascript');
- topHolder.innerHTML = "";
- var scriptHolder = document.createElement('div');
- topHolder.appendChild(scriptHolder);
- var htmlHolder = document.createElement('div');
- topHolder.appendChild(htmlHolder);
-
- // NOTE: These are ordered such that no file depends on anything after it.
- var forced_includes = [
- "o3djs/base.js",
- "o3djs/error.js",
- "o3djs/dump.js",
- "o3djs/math.js",
- "o3djs/serialization.js",
- "o3djs/element.js",
- "o3djs/shape.js",
- "o3djs/rendergraph.js",
- "o3djs/test.js",
- "o3djs/particles.js",
- "o3djs/primitives.js",
- "o3djs/quaternions.js",
- "o3djs/arcball.js",
- "o3djs/event.js",
- "o3djs/debug.js",
- "o3djs/picking.js",
- "o3djs/io.js",
- "o3djs/util.js",
- "o3djs/effect.js",
- "o3djs/material.js",
- "o3djs/camera.js",
- "o3djs/canvas.js",
- "o3djs/pack.js",
- "o3djs/scene.js",
- "o3djs/loader.js",
- "o3djs/simple.js",
- "o3djs/fps.js" // If fps isn't last on this list, update the check below.
- ];
-
- for (var i = 0; i < forced_includes.length; ++i) {
- var scr = document.createElement('script');
- scr.type = "text/javascript";
- scr.src = forced_includes[i];
- scriptHolder.appendChild(scr);
- }
-
- this.currentCode[this.curI].code = this.getCode();
-
- var sampleJS;
- var sampleHTML;
- for (var i in this.currentCode) {
- if (i.indexOf('.html') != -1) {
- // Change the name and id of the object tag before storing the HTML,
- // otherwise it will override the inline object we actually want the demo
- // to be run in.
- sampleHTML = this.currentCode[i].code;
- sampleHTML = sampleHTML.replace('id="o3d"', 'id="notouchy"');
- sampleHTML = sampleHTML.replace('id=\'o3d\'', 'id="notouchy"');
- sampleHTML = sampleHTML.replace('name="o3d"', 'name="notouchy"');
- sampleHTML = sampleHTML.replace('name=\'o3d\'', 'name="notouchy"');
- }
- if (i.indexOf('.js') != -1) {
- sampleJS = this.currentCode[i].code;
- }
- }
-
- var intervalId;
- var callback = function() {
- // fps is the last on the forced_includes list.
- if (o3djs != undefined && o3djs.fps) {
- clearInterval(intervalId);
- intervalId = null;
- // TODO Is there any chance that the onload could get called before
- // we're done loading the script tag? If so, we'll need to add another
- // stage to the callback.
- htmlHolder.innerHTML = sampleHTML;
- var scr = document.createElement('script');
- scr.type = "text/javascript";
- scr.text = sampleJS;
- scriptHolder.appendChild(scr);
- try {
- if (typeof window.onload == 'function') {
- window.onload()
- } else if (typeof window.init == 'function') {
- window.init();
- } else if (typeof window.initClient == 'function') {
- window.initClient();
- } else if (typeof window.createClients == 'function') {
- window.createClients();
- }
- } catch(e) {
- alert(e.message);
- }
-
- _gel('o3d').focus();
- }
- }
- intervalId = setInterval(callback, 10);
-};
-
-InteractiveSample.prototype.changeCodeMirror = function(content, lang) {
- if (lang == 'javascript') {
- window.jsEditor.setCode(content);
- window.jsEditor.frame.style.display = 'inline';
- window.htmlEditor.frame.style.display = 'none';
- } else if (lang == 'html') {
- window.htmlEditor.setCode(content);
- window.htmlEditor.frame.style.display = 'inline';
- window.jsEditor.frame.style.display = 'none';
- }
-};
-
-InteractiveSample.prototype.getCode = function() {
- if (window.htmlEditor.frame.style.display != 'none') {
- return window.htmlEditor.getCode();
- } else if (window.jsEditor.frame.style.display != 'none') {
- return window.jsEditor.getCode();
- }
-};
-
-// Todo have the window automatically size to the size of the window
-
-InteractiveSample.prototype.increaseWidth = function() {
- var container = document.getElementById('container');
- var curWidth = container.style.maxWidth = '1800px';
-};
diff --git a/o3d/samples/interactive_sampler_assets/images/bl.gif b/o3d/samples/interactive_sampler_assets/images/bl.gif
deleted file mode 100644
index 244627d..0000000
--- a/o3d/samples/interactive_sampler_assets/images/bl.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/interactive_sampler_assets/images/br.gif b/o3d/samples/interactive_sampler_assets/images/br.gif
deleted file mode 100644
index a63a18e..0000000
--- a/o3d/samples/interactive_sampler_assets/images/br.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/interactive_sampler_assets/images/cleardot.gif b/o3d/samples/interactive_sampler_assets/images/cleardot.gif
deleted file mode 100644
index 1d11fa9..0000000
--- a/o3d/samples/interactive_sampler_assets/images/cleardot.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/interactive_sampler_assets/images/corner.png b/o3d/samples/interactive_sampler_assets/images/corner.png
deleted file mode 100644
index 51aa458..0000000
--- a/o3d/samples/interactive_sampler_assets/images/corner.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/interactive_sampler_assets/images/db_tl.png b/o3d/samples/interactive_sampler_assets/images/db_tl.png
deleted file mode 100644
index 381883f..0000000
--- a/o3d/samples/interactive_sampler_assets/images/db_tl.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/interactive_sampler_assets/images/db_tr.png b/o3d/samples/interactive_sampler_assets/images/db_tr.png
deleted file mode 100644
index 230205f..0000000
--- a/o3d/samples/interactive_sampler_assets/images/db_tr.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/interactive_sampler_assets/images/google-small.png b/o3d/samples/interactive_sampler_assets/images/google-small.png
deleted file mode 100644
index e62b8b8..0000000
--- a/o3d/samples/interactive_sampler_assets/images/google-small.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/interactive_sampler_assets/images/lb_tl.png b/o3d/samples/interactive_sampler_assets/images/lb_tl.png
deleted file mode 100644
index 5de27abc..0000000
--- a/o3d/samples/interactive_sampler_assets/images/lb_tl.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/interactive_sampler_assets/images/lb_tr.png b/o3d/samples/interactive_sampler_assets/images/lb_tr.png
deleted file mode 100644
index d29e333..0000000
--- a/o3d/samples/interactive_sampler_assets/images/lb_tr.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/interactive_sampler_assets/images/sprites.gif b/o3d/samples/interactive_sampler_assets/images/sprites.gif
deleted file mode 100644
index 8132129..0000000
--- a/o3d/samples/interactive_sampler_assets/images/sprites.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/interactive_sampler_assets/images/sprites08132008.png b/o3d/samples/interactive_sampler_assets/images/sprites08132008.png
deleted file mode 100644
index 64f70f2..0000000
--- a/o3d/samples/interactive_sampler_assets/images/sprites08132008.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/interactive_sampler_assets/images/sprites2.jpg b/o3d/samples/interactive_sampler_assets/images/sprites2.jpg
deleted file mode 100644
index 5cf26f3..0000000
--- a/o3d/samples/interactive_sampler_assets/images/sprites2.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/interactive_sampler_assets/images/tl.gif b/o3d/samples/interactive_sampler_assets/images/tl.gif
deleted file mode 100644
index 5eb8006..0000000
--- a/o3d/samples/interactive_sampler_assets/images/tl.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/interactive_sampler_assets/images/tr.gif b/o3d/samples/interactive_sampler_assets/images/tr.gif
deleted file mode 100644
index f88810f..0000000
--- a/o3d/samples/interactive_sampler_assets/images/tr.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/interactive_sampler_assets/styles.css b/o3d/samples/interactive_sampler_assets/styles.css
deleted file mode 100644
index 32eb347..0000000
--- a/o3d/samples/interactive_sampler_assets/styles.css
+++ /dev/null
@@ -1,278 +0,0 @@
-body {
- font-family: Arial, sans-serif;
-}
-
-#container {
- width: 100%;
- margin:0pt auto;
- max-width:1024px;
-}
-
-tr {
- vertical-align: top;
-}
-
-div {
-/* border: 1px solid #999;*/
-}
-
-#header {
- height: 50px;
-}
-
-
-#selectSample {
- width: 30%;
- display: inline;
-}
-
-#code {
- width: 70%;
- display: inline;
-}
-
-.codepress {
- width:100%;
- height:550px;
-/* overflow-x: hidden;*/
-}
-
-#codeContainer {
- width:80%;
- height:500px;
- padding-left: 9px;
- padding-right: 9px;
-
-}
-
-#selectContainer {
- width:20%;
- height:100%;
- padding-bottom: 3px;
-}
-
-#selectCode {
- width:100%;
- height: auto;
- overflow: auto;
- overflow-x: hidden;
- margin-bottom: 3px;
- margin-top: 20px;
-}
-
-.category {
- font-size: 85%;
- font-family: Arial, sans-serif;
- font-weight: bold;
- display: block;
-}
-
-.categoryItems {
- margin-top: 0px;
- margin-bottom: 0px;
- list-style-type: none;
- font-size: 80%;
- font-family: Arial, sans-serif;
- padding-left: 0px;
-}
-
-#outputContainer {
- /* width: 400px;*/
- /* height: 400px;*/
- /* width: 70%;*/
-}
-
-#consoleContainer {
- height: 300px;
- width: 30%;
- border: 1px solid #999;
-}
-
-iframe {
-/* overflow-x: hidden;*/
-}
-
-.contentTable {
- width: 100%;
- height: 100%;
-}
-
-#header {
- margin: 0px;
- display: inline;
-}
-
-.bluehr {
- background-color:transparent;
- border:0pt none;
- float:left;
- font-size:1.5em;
- font-weight:bold;
- line-height:1.3em;
- margin:0pt;
- padding:0pt 0pt 0pt 0.3em;
-}
-
-h2 {
- border-bottom:1px solid #CCCCCC;
- font-size:1.3em;
- margin-bottom:0pt;
- font-family:Helvetica,Arial,sans-serif;
-}
-
-.bluediv {
- background-color:#E5ECF9;
- border-top:1px solid #3366CC;
- font-size:1em;
- margin:0pt;
- padding:0.1em 0pt;
- white-space:nowrap;
- width:100%;
-}
-
-li.selected {
- padding:0.2em 0pt 0.2em 15px;
- background-color:#E5ECF9;
- color:#000000;
- position:relative;
- text-decoration:none;
- z-index:2;
- list-style-image:none;
- list-style-position:outside;
- list-style-type:none;
- margin:0pt;
- vertical-align:middle;
- line-height:100%;
- cursor: default;
-}
-
-li {
- padding-left: 15px;
- cursor: pointer;
- text-decoration: underline;
- color: blue;
-}
-
-img.expand, img.collapse {
- border:medium none;
- height:inherit;
- margin-bottom: 4px;
- margin-right: 5px;
- padding:0pt;
- position:relative;
- width:9px;
- background-image:url(interactive_sampler_assets/images/sprites.gif);
- vertical-align:middle;
- cursor: pointer;
-}
-
-img.collapse {
- background-position: -28px -310px; /* The empty Plus */
-}
-
-img.collapse:hover {
- background-position:-28px -508px; /* The filled Plus */
-}
-
-img.expand {
- background-position: -28px -246px; /* The empty Plus */
-}
-
-img.expand:hover {
- background-position:-28px -444px; /* The filled Plus */
-}
-
-/*.separator {
- height: 100%;
- background:#E5ECF9 none repeat scroll 0% 0%;
- border-color:-moz-use-text-color #FFFFFF;
- border-style:1px solid;
- border-width:medium 2px;
- cursor:pointer;
- left:-5px;
- overflow:hidden;
-/* position:absolute;*/
-/* top:0pt;
- margin-top: 63px;
- width:4px;
-}*/
-
-#gc-footer-img {
- background-image:url(interactive_sampler_assets/images/sprites.gif);
- background-position:-28px -28px;
- display:inline;
- float:left;
- height:53px;
- margin:12px 0pt;
- width:143px;
-}
-
-#gc-footer .text {
- margin:0pt 0pt 0pt 170px;
- padding:30px 0pt;
- text-align:center;
-}
-
-#gc-footer {
- color:#666666;
- margin:0pt;
- width:100%;
-}
-
-td.footer {
- padding-top: 60px;
-}
-
-#googleLogoTD {
- text-align:right;
- vertical-align:middle;
- padding-right: 7px;
-}
-
-#tab_bar {
- margin-top:20px;
- cursor: pointer;
-}
-
-#button_bar {
- text-align: right;
-}
-
-.roundedcornr_box {
- float:left;
- margin: 0px 4px;
-}
-
-.db_top div {
- background: url(interactive_sampler_assets/images/db_tl.png) no-repeat top left;
-}
-.db_top {
- background: #92c1f0 url(interactive_sampler_assets/images/db_tr.png) no-repeat top right;
-}
-
-.lb_top div {
- background: url(interactive_sampler_assets/images/lb_tl.png) no-repeat top left;
-}
-
-.lb_top {
- background: #D0E4F6 url(interactive_sampler_assets/images/lb_tr.png) no-repeat top right;
-}
-
-.db_top div, .db_top,
-.lb_top div, .lb_top {
- height: 5px;
- font-size: 1px;
-}
-.lb_roundedcornr_content,
-.db_roundedcornr_content {
- padding: 0px 10px;
- font-size: 80%;
-}
-
-.lb_roundedcornr_content {
- background-color: #D0E4F6;
-}
-
-.db_roundedcornr_content {
- background-color: #92c1f0;
-}
diff --git a/o3d/samples/interactive_sampler_assets/styles_ie.css b/o3d/samples/interactive_sampler_assets/styles_ie.css
deleted file mode 100644
index cdc46cb..0000000
--- a/o3d/samples/interactive_sampler_assets/styles_ie.css
+++ /dev/null
@@ -1,301 +0,0 @@
-body {
- font-family: Arial, sans-serif;
-}
-
-#container {
- width: 100%;
- margin:0pt auto;
- max-width:1024px;
- width:expression(
- document.body.clientWidth > 1024 ?
- "1024px":
- "auto" );
-}
-
-tr {
- vertical-align: top;
-}
-
-div {
-/* border: 1px solid #999;*/
-}
-
-#header {
- height: 50px;
-}
-
-/*#footer {
- width: 100%;
-
-}*/
-
-#selectSample {
- width: 30%;
- display: inline;
-}
-
-#code {
- width: 70%;
- display: inline;
-}
-
-.codepress {
- width:100%;
- height:550px;
-/* overflow-x: hidden;*/
-}
-
-#codeContainer {
- width:80%;
- height:500px;
- padding-left: 9px;
- padding-right: 9px;
-
-}
-
-#selectContainer {
- width:20%;
- height:100%;
- padding-bottom: 3px;
-}
-
-#selectCode {
- width:100%;
- height: auto;
- overflow: auto;
- overflow-x: hidden;
- margin-bottom: 3px;
- margin-top: 20px;
-}
-
-.category {
- font-size: 85%;
- font-family: Arial, sans-serif;
- font-weight: bold;
- display: block;
-}
-
-.categoryItems {
- margin-top: 0px;
- margin-bottom: 0px;
- list-style-type: none;
- font-size: 80%;
- font-family: Arial, sans-serif;
- padding-left: 0px;
-}
-
-#outputContainer {
- /* width: 400px;*/
- /* height: 400px;*/
- /* width: 70%;*/
-}
-
-#consoleContainer {
- height: 300px;
- width: 30%;
- border: 1px solid #999;
-}
-
-iframe {
-/* overflow-x: hidden;*/
-}
-
-.contentTable {
- width: 100%;
- height: 100%;
-}
-
-#header {
- margin: 0px;
- display: inline;
-}
-
-.bluehr {
- background-color:transparent;
- border:0pt none;
- float:left;
- font-size:1.5em;
- font-weight:bold;
- line-height:1.3em;
- margin:0pt;
- padding:0pt 0pt 0pt 0.3em;
-}
-
-h2 {
- border-bottom:1px solid #CCCCCC;
- font-size:1.3em;
- margin-bottom:0pt;
- font-family:Helvetica,Arial,sans-serif;
-}
-
-.bluediv {
- background-color:#E5ECF9;
- border-top:1px solid #3366CC;
- font-size:1em;
- margin:0pt;
- padding:0.1em 0pt;
- white-space:nowrap;
- width:100%;
-}
-
-li.selected {
- padding:0.2em 0pt 0.2em 15px;
- background-color:#E5ECF9;
- color:#000000;
- position:relative;
- text-decoration:none;
- z-index:2;
- list-style-image:none;
- list-style-position:outside;
- list-style-type:none;
- margin:0pt;
- vertical-align:middle;
- line-height:100%;
- cursor: default;
-}
-
-li {
- padding-left: 15px;
- cursor: pointer;
- text-decoration: underline;
- color: blue;
-}
-
-img.expand, img.collapse {
- border:medium none;
- height:inherit;
- margin-bottom: 4px;
- margin-right: 5px;
- padding:0pt;
- position:relative;
- width:9px;
- background-image:url(interactive_sampler_assets/images/sprites.gif);
- vertical-align:middle;
- cursor: pointer;
-}
-
-img.collapse {
- background-position: -28px -310px; /* The empty Plus */
-}
-
-img.collapse:hover {
- background-position:-28px -508px; /* The filled Plus */
-}
-
-img.expand {
- background-position: -28px -246px; /* The empty Plus */
-}
-
-img.expand:hover {
- background-position:-28px -444px; /* The filled Plus */
-}
-
-/*.separator {
- height: 100%;
- background:#E5ECF9 none repeat scroll 0% 0%;
- border-color:-moz-use-text-color #FFFFFF;
- border-style:1px solid;
- border-width:medium 2px;
- cursor:pointer;
- left:-5px;
- overflow:hidden;
-/* position:absolute;*/
-/* top:0pt;
- margin-top: 63px;
- width:4px;
-}*/
-
-#gc-footer-img {
- background-image:url(interactive_sampler_assets/images/sprites.gif);
- background-position:-28px -28px;
- display:inline;
- float:left;
- height:53px;
- margin:12px 0pt;
- width:143px;
-}
-
-#gc-footer .text {
- margin:0pt 0pt 0pt 170px;
- padding:30px 0pt;
- text-align:center;
-}
-
-#gc-footer {
- color:#666666;
- margin:0pt;
- width:100%;
-}
-
-td.footer {
- padding-top: 60px;
-}
-
-#lbinner {
- width:expression(
- document.body.clientWidth > 1100 ?
- "1100px":
- "auto" );
-}
-
-#lightbox {
- position: absolute;
-}
-
-#overlay {
- width: 1000%;
-}
-
-#googleLogoTD {
- text-align:right;
- vertical-align:middle;
-}
-
-#tab_bar {
- margin-top:20px;
- margin-bottom: -2px;
- cursor: pointer;
-}
-
-#button_bar {
- text-align: right;
-}
-
-.roundedcornr_box {
- float:left;
- margin: 0px 4px;
-}
-
-.db_top div {
- background: url(interactive_sampler_assets/images/db_tl.png) no-repeat top left;
-}
-.db_top {
- background: #92c1f0 url(interactive_sampler_assets/images/db_tr.png) no-repeat top right;
-}
-
-.lb_top div {
- background: url(interactive_sampler_assets/images/lb_tl.png) no-repeat top left;
-}
-
-.lb_top {
- background: #D0E4F6 url(interactive_sampler_assets/images/lb_tr.png) no-repeat top right;
-}
-
-.db_top div, .db_top,
-.lb_top div, .lb_top {
- height: 5px;
- font-size: 1px;
-}
-.lb_roundedcornr_content,
-.db_roundedcornr_content {
- padding: 0px 10px;
- font-size: 80%;
-}
-
-.lb_roundedcornr_content {
- background-color: #D0E4F6;
-}
-
-.db_roundedcornr_content {
- background-color: #92c1f0;
-}
diff --git a/o3d/samples/interactive_sampler_assets/utils.js b/o3d/samples/interactive_sampler_assets/utils.js
deleted file mode 100644
index 8132df1..0000000
--- a/o3d/samples/interactive_sampler_assets/utils.js
+++ /dev/null
@@ -1,200 +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.
- */
-
-
-/**
- * @fileoverview This file contains utility functions for the interactive
- * sample runner.
- *
- */
-
-var ie;
-var opera;
-var safari;
-var gecko;
-
-
-if (typeof console == 'undefined') {
- var console = {
- log : function() {}
- };
-}
-
-function readFile(relativePathToFile) {
- var curPath = location.href;
- var fileLoc = curPath.indexOf('file:///');
- var lastSlash = curPath.lastIndexOf('/');
- curPath = curPath.substring(0, lastSlash + 1);
- if (fileLoc != -1) {
- curPath = curPath.substring(fileLoc + 8);
- }
- var filepath = curPath + relativePathToFile;
- filepath = filepath.replace(/\//g, '\\');
- filepath = filepath.replace(/%20/g, ' ');
-
- try {
- netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
- } catch (e) {
- return null;
- }
- var file = Components.classes["@mozilla.org/file/local;1"].createInstance(
- Components.interfaces.nsILocalFile);
- file.initWithPath( filepath );
- if ( file.exists() == false ) {
- alert("File does not exist");
- }
- var is = Components.classes["@mozilla.org/network/file-input-stream;1"].
- createInstance(Components.interfaces.nsIFileInputStream);
- is.init( file,0x01, 00004, null);
- var sis = Components.classes["@mozilla.org/scriptableinputstream;1"].
- createInstance(Components.interfaces.nsIScriptableInputStream);
- sis.init(is);
- var output = sis.read( sis.available() );
- return output;
-}
-
-/**
-* Returns an XMLHttp instance to use for asynchronous
-* downloading. This method will never throw an exception, but will
-* return NULL if the browser does not support XmlHttp for any reason.
-* @return {XMLHttpRequest|Null}
-*/
-function createXmlHttpRequest() {
- try {
- if (typeof ActiveXObject != 'undefined') {
- return new ActiveXObject('Microsoft.XMLHTTP');
- } else if (window["XMLHttpRequest"]) {
- return new XMLHttpRequest();
- }
- } catch (e) {
- changeStatus(e);
- }
- return null;
-};
-
-/**
-* This functions wraps XMLHttpRequest open/send function.
-* It lets you specify a URL and will call the callback if
-* it gets a status code of 200.
-* @param {String} url The URL to retrieve
-* @param {Function} callback The function to call once retrieved.
-*/
-function downloadUrl(url, callback) {
- var status = -1;
- var request = createXmlHttpRequest();
- if (!request) {
- return false;
- }
-
- request.onreadystatechange = function() {
- if (request.readyState == 4) {
- try {
- status = request.status;
- } catch (e) {
- // Usually indicates request timed out in FF.
- }
- if (status == 200) {
- callback(request.responseText, request.status);
- request.onreadystatechange = function() {};
- }
- }
- };
-
- request.open('GET', url, true);
- try {
- request.send(null);
- } catch (e) {
- changeStatus(e);
- }
-}
-
-
-function deepObjCopy(dupeObj) {
- var retObj = new Object();
- if (typeof(dupeObj) == 'object') {
- if (typeof(dupeObj.length) != 'undefined')
- var retObj = new Array();
- for (var objInd in dupeObj) {
- if (typeof(dupeObj[objInd]) == 'object') {
- retObj[objInd] = deepObjCopy(dupeObj[objInd]);
- } else if (typeof(dupeObj[objInd]) == 'string') {
- retObj[objInd] = dupeObj[objInd];
- } else if (typeof(dupeObj[objInd]) == 'number') {
- retObj[objInd] = dupeObj[objInd];
- } else if (typeof(dupeObj[objInd]) == 'boolean') {
- ((dupeObj[objInd] == true) ?
- retObj[objInd] = true : retObj[objInd] = false);
- }
- }
- }
- return retObj;
-}
-
-function singleLevelKeyCopy(dupeObj) {
- var retObj = new Object();
- for (var objInd in dupeObj) {
- retObj[objInd] = true;
- }
- return retObj;
-}
-
-function browserFun() {
- // Browser fun.
- if (window.ActiveXObject) {
- ie = this[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true;
- } else if (window.opera) {
- opera = true;
- } else if (document.childNodes && !document.all && !navigator.taintEnabled) {
- safari = true;
- } else if (document.getBoxObjectFor != null) {
- gecko = true;
- }
-}
-
-function _cel(name) {
- return document.createElement(name);
-}
-
-function _gel(name) {
- return document.getElementById(name);
-}
-
-function addEvent(a,b,c,d) {
- if (a.addEventListener) {
- a.addEventListener(b,c,d?true:false);
- } else if(a.attachEvent) {
- a.attachEvent('on'+b,c);
- } else{
- a['on'+b]=c;
- }
-}
-
-browserFun();
diff --git a/o3d/samples/interactive_samples.js b/o3d/samples/interactive_samples.js
deleted file mode 100644
index eb30c85..0000000
--- a/o3d/samples/interactive_samples.js
+++ /dev/null
@@ -1,189 +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.
- */
-
-// From here on down, please keep the format consistent. This file
-// will be read by the split_samples.py script to determine which files
-// will be split, and it reads all lines below "var codeArray = [" as
-// a python list, which just happens to match the syntax of a
-// javascript list, so please don't violate that assumption.
-// Leave this next line as it is...
-var codeArray = [
- {
- 'category': 'Basic',
- 'samples': [
- {'files':
- ['simple.html', 'simple.js'],
- 'sampleName': 'Simple'},
- {'files':
- ['helloworld.html', 'helloworld.js'],
- 'sampleName': 'Hello World'},
- {'files':
- ['customcamera.html', 'customcamera.js'],
- 'sampleName': 'Custom Camera',
- 'ownWindow': true},
- {'files':
- ['simpletexture.html', 'simpletexture.js'],
- 'sampleName': 'Simple Texture'},
- {'files':
- ['hellocube.html', 'hellocube.js'],
- 'sampleName': 'Simple Cube'},
- {'files':
- ['hellocube-colors.html', 'hellocube-colors.js'],
- 'sampleName': 'Simple Cube With Colors',
- 'ownWindow': true},
- {'files':
- ['hellocube-textures.html', 'hellocube-textures.js'],
- 'sampleName': 'Simple Cube With Textures'}
- ]
- },
- {
- 'category': 'Advanced',
- 'samples': [
- {'files':
- ['2d.html', '2d.js'],
- 'sampleName': '2d'},
- {'files':
- ['culling.html', 'culling.js'],
- 'sampleName': 'Culling',
- 'ownWindow': true},
- {'files':
- ['displayfps.html', 'displayfps.js'],
- 'sampleName': 'Display FPS',
- 'ownWindow': true},
- {'files':
- ['hud-2d-overlay.html', 'hud-2d-overlay.js'],
- 'sampleName': 'HUD 2D Overlay'},
- {'files':
- ['instancing.html', 'instancing.js'],
- 'sampleName': 'Instancing'},
- {'files':
- ['instance-override.html', 'instance-override.js'],
- 'sampleName': 'Instance Override'},
- {'files':
- ['juggler.html', 'juggler.js'],
- 'sampleName': 'Juggler'},
- {'files':
- ['julia.html', 'julia.js'],
- 'sampleName': 'Julia'},
- {'files':
- ['multiple-clients.html', 'multiple-clients.js'],
- 'sampleName': 'Multiple Clients',
- 'ownWindow': true},
- {'files':
- ['multiple-views.html', 'multiple-views.js'],
- 'sampleName': 'Multiple Views'},
- {'files':
- ['phongshading.html', 'phongshading.js'],
- 'sampleName': 'Phong Shading'},
- {'files':
- ['picking.html', 'picking.js'],
- 'sampleName': 'Picking'},
- {'files':
- ['render-mode.html', 'render-mode.js'],
- 'sampleName': 'Render Mode',
- 'ownWindow': true},
- {'files':
- ['render-targets.html', 'render-targets.js'],
- 'sampleName': 'Render Targets'},
- {'files':
- ['convolution.html', 'convolution.js'],
- 'sampleName': 'Convolution Shader'},
- {'files':
- ['sobel.html', 'sobel.js'],
- 'sampleName': 'Sobel Edge Detection'},
- {'files':
- ['rotatemodel.html', 'rotatemodel.js'],
- 'sampleName': 'Rotate Model'},
- {'files':
- ['scatter-chart.html', 'scatter-chart.js'],
- 'sampleName': 'Scatter Chart',
- 'ownWindow': true},
- {'files':
- ['shader-test.html', 'shader-test.js'],
- 'sampleName': 'Shader Test',
- 'ownWindow': true},
- {'files':
- ['stencil_example.html', 'stencil_example.js'],
- 'sampleName': 'Stencil Example'},
- {'files':
- ['error-texture.html', 'error-texture.js'],
- 'sampleName': 'Error Texture',
- 'ownWindow': true},
- {'files':
- ['texturesamplers.html', 'texturesamplers.js'],
- 'sampleName': 'Texture Samplers'},
- {'files':
- ['generate-texture.html', 'generate-texture.js'],
- 'sampleName': 'Generating A Texture'},
- {'files':
- ['procedural-texture.html', 'procedural-texture.js'],
- 'sampleName': 'Procedural Texture'},
- {'files':
- ['zsorting.html', 'zsorting.js'],
- 'sampleName': 'Z-Sorting'},
- {'files':
- ['canvas.html', 'canvas.js'],
- 'sampleName': 'Canvas' },
- {'files':
- ['canvas-texturedraw.html', 'canvas-texturedraw.js'],
- 'sampleName': 'Canvas: Drawing With Bitmaps',
- 'ownWindow': true},
- {'files':
- ['vertex-shader.html', 'vertex-shader.js'],
- 'sampleName': 'Vertex Shader' },
- {'files':
- ['primitives.html', 'primitives.js'],
- 'sampleName': 'Primitives',
- 'ownWindow': true },
- {'files':
- ['tutorial-primitive.html', 'tutorial-primitive.js'],
- 'sampleName': 'Tutorial Primitive',
- 'ownWindow': true },
- {'files':
- ['skinning.html', 'skinning.js'],
- 'sampleName': 'Skinning' },
- {'files':
- ['animation.html', 'animation.js'],
- 'sampleName': 'Animation' },
- {'files':
- ['animated-scene.html', 'animated-scene.js'],
- 'sampleName': 'Animated Scene',
- 'ownWindow': true },
- {'files':
- ['particles.html', 'particles.js'],
- 'sampleName': 'Particles' },
- {'files':
- ['vertex-shader-animation.html', 'vertex-shader-animation.js'],
- 'sampleName': 'Vertex Shader Animation' }
- ]
- }
-];
-
diff --git a/o3d/samples/io/README.txt b/o3d/samples/io/README.txt
deleted file mode 100644
index e6ede03..0000000
--- a/o3d/samples/io/README.txt
+++ /dev/null
@@ -1,29 +0,0 @@
-Steps to Create a level:
-
-1. Install the SketchUp Level Creation tools
-2. Start SU 6
-3. Draw your "world path" using the line tool
-
-- Using the line tool, draw a line from the drawing origin along the solid green axis line (that's your x axis) It can be as long or as short as you want.
-- From there, you can draw lines continuously from the end of your first line segment. Each line is a distinct plane in the world path.
-- Only draw horizontal lines along the Sketchup drawing's ground plane. No slopes or vertical changes in altitude.
-- Your avatar will NOT walk on these lines. They are only used to define the path that the world will run along.
-
-4. Draw your platforms
-- Each horizontal line must be exactly parallel and exactly "above" or "below" one of your "world path" line segments.
-- Good way to do this is to CTRL+MOVE your base lines up or down, and then chop them up from there.
-- Each horizontal line is a platform that your avatar can walk on.
-- Each vertical line is an "obstacle" that your avatar can't walk through.
-
-5. Drag in your actors
-- The installer created a directory under components > Prince IO (or it will, once we're done with it. -SEL)
-- Drag these suckers in. Note that you're going to want to put them on line segments, typically.
-
-6. Draw random geometry only in components and groups.
-
-7. Test everything in SU.
-- Press the "play" button in the Prince IO level designer. You can play the game.
-- Note: Set your field of view to 45 degrees to have approximately the same camera view as in O3D.
-
-8. Press the "export" button and save your myLevelName.js and myLevelName.kmz into your prince IO /levels directory.
-(this will also automatically generate the autoincludes.js file.)
diff --git a/o3d/samples/io/actors/actor.js b/o3d/samples/io/actors/actor.js
deleted file mode 100644
index a0e1e50..0000000
--- a/o3d/samples/io/actors/actor.js
+++ /dev/null
@@ -1,144 +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.
- */
-
-
-/**
- * @fileoverview This file defines the Actor class.
- */
-
-/**
- * Pulls in all names attributes of a source object and applies them to a
- * target object. Handy for pulling in a bunch of name:value pairs that were
- * passed all at once.
- */
-function Actor() {
- // Create some defaults for our "required" attributes.
- this.x = 0;
- this.y = 0;
- this.z = 0;
- this.width = 20;
- this.height = 20;
- this.mapX = 0;
- this.platformID = 0;
- this.rotZ = 0;
- this.frameName = '';
-}
-
-Actor.prototype.absorbNamedValues = function(initObj) {
- for (var key in initObj) {
- this[key] = initObj[key];
- }
-};
-
-/**
- * Note that for collision detection, all actors are envisioned as 2d rectangles
- * inside a single plane. These rectangles have a width and a height, and their
- * "origin" is on the bottom center of the rectangle. So if you create a new
- * actor, be sure to give it a reasonable width and height.
- */
-Actor.prototype.collidesWith = function(otherActor) {
- thisLeft = this.mapX - this.width/2;
- thisRight = this.mapX + this.width/2;
- thisTop = this.z + this.height;
- thisBottom = this.z;
-
- otherLeft = otherActor.mapX - otherActor.width/2;
- otherRight = otherActor.mapX + otherActor.width/2;
- otherTop = otherActor.z + otherActor.height;
- otherBottom = otherActor.z;
-
- // First see if we're not overlapping in any dimension.
- if (thisRight < otherLeft ||
- thisLeft > otherRight ||
- thisBottom > otherTop ||
- thisTop < otherBottom) {
- return false;
- }
-
- // Next check for overlap along X.
- if (thisRight >= otherLeft &&
- thisLeft <= otherRight) {
- // then we're still in the running...
- } else {
- return false;
- }
-
- // Next check for overlap along Y.
- if (thisBottom <= otherTop &&
- thisTop >= otherBottom) {
- return true;
- }
-
- // We're not overlapping in Y, so bomb.
- return false;
-};
-
-Actor.prototype.isHitBySword = function() {
- var isHit = false;
- if (avatar.animation == "Hero_Sword" && avatar.frame > 3) {
- avatar.width += 80;
- avatar.height += avatar.frame * 5;
- if (this.collidesWith(avatar)) {
- var isHit = true;
- }
- avatar.width -= 80;
- avatar.height -= avatar.frame * 5;
- }
- return isHit;
-}
-
-Actor.prototype.isHitByArrow = function() {
- var isHit = false;
- // TODO: Make this allow multiple arrows, perform better, etc.
- if (top.arrowActor != undefined) {
- // If we don't have the same "parentPlatform, meaning we're in different
- // world path space, then we don't collide.
- if (world.platforms[top.arrowActor.platformID].parentID !=
- world.platforms[this.platformID].parentID) {
- return false;
- }
- if (this.collidesWith(top.arrowActor)) {
- var isHit = true;
- }
- }
- return isHit;
-}
-
-Actor.prototype.moveMapX = function(change) {
- var platformAngle = world.platforms[this.platformID].rotZ;
- this.mapX += change;
- this.x += change * Math.cos(platformAngle);
- this.y += change * Math.sin(platformAngle);
-};
-
-
-
-
diff --git a/o3d/samples/io/actors/arrow.js b/o3d/samples/io/actors/arrow.js
deleted file mode 100644
index 0103b5c..0000000
--- a/o3d/samples/io/actors/arrow.js
+++ /dev/null
@@ -1,94 +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.
- */
-
-
-/**
- * @fileoverview This file defines the Arrow class.
- */
-
-/**
- * An arrow that Io can shoot.
- */
-function Arrow(initObj) {
- this.absorbNamedValues(initObj);
-
- // Hide myself by moving way off the screen.
- this.z = -10000;
- this.mapX = -10000;
- this.width = 40;
- this.height = 1;
- this.velX = 0;
-
- // Figure out which arrow number I am.
- this.arrowNumber = parseInt(initObj.name.substr(initObj.name.length-1,1));
-
-}
-Arrow.prototype = new Actor;
-
-Arrow.prototype.onTick = function(timeElapsed) {
- if (this.mapX < avatar.mapX-500 || this.mapX > avatar.mapX+500 &&
- this.z > -10000) {
- // then hide ourselves way off screen.
- this.mapX = -10000;
- this.z = -10000;
- updateActor(this);
- } else {
- // Here's how I move. moveMapX is a handy function that updates both
- // my "virtual 2d world" mapX, as well as my literal x + y values
- this.moveMapX(this.velX * timeElapsed)
- updateActor(this);
- }
-}
-
-Arrow.prototype.shoot = function() {
- this.x = avatar.x;
- this.y = avatar.y;
- this.z = avatar.z + 33; // Approximate height of IO's crossbow.
- this.platformID = avatar.platformID;
- this.parentPlatformID = avatar.parentPlatformID;
- this.rotZ = world.platforms[this.platformID].rotZ;
- this.mapX = avatar.mapX;
-
- if (Math.abs(avatar.rotZ - this.rotZ) < Math.PI/2) {
- this.velX = 50 * 20;
- } else {
- this.velX = -50 * 20;
- this.rotZ -= Math.PI;
- }
- soundPlayer.play('sound/arrow.mp3', 100);
- updateActor(this);
-}
-
-// TODO: This should be a generic concept, not an arrow-specifc
-// thing.
-Arrow.prototype.hide = function() {
- this.mapX = -10000;
-}
diff --git a/o3d/samples/io/actors/avatar.js b/o3d/samples/io/actors/avatar.js
deleted file mode 100644
index aac4f45e..0000000
--- a/o3d/samples/io/actors/avatar.js
+++ /dev/null
@@ -1,67 +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.
- */
-
-/**
- * Our avatar object. Hooray!
- */
-function Avatar(initObj) {
- this.absorbNamedValues(initObj);
-
- this.animation = "Hero_Stand"
- this.velX = 0;
- this.velY = 0;
- this.velZ = 0;
- this.targetRotZ = 0; // Where we'd like to be facing.
- this.targetVelX = 0; // Speed we'd like to be going.
- this.swordRate = .5;
-
- this.width = 30;
- this.height = 50;
-
- this.frame = 1;
- this.framesSinceShot = 0; // If > 0, tack a "#1" onto our instance name.
- this.isJumping = false;
-
- // We always start on platform 0 to fix a placement bug.
- this.platformID = 0;
- this.x = 0;
- this.y = 0;
- this.mapX = 0;
- this.z = 200;
- this.parentPlatformID = 0;
-
-}
-
-Avatar.prototype = new Actor;
-
-Avatar.prototype.onTick = function(timeElapsed) {
- updateActor(this);
-}
diff --git a/o3d/samples/io/actors/coin.js b/o3d/samples/io/actors/coin.js
deleted file mode 100644
index 1124d5e..0000000
--- a/o3d/samples/io/actors/coin.js
+++ /dev/null
@@ -1,68 +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.
- */
-
-
-/**
- * @fileoverview This file defines the Coin class.
- */
-
-/**
- * A Coin to be picked up
- */
-function Coin(initObj) {
- this.absorbNamedValues(initObj);
- this.hasBeenPickedUp = false;
- this.width = 14;
- this.height = 14;
- this.isHidden = false;
-}
-Coin.prototype = new Actor;
-
-Coin.prototype.onTick = function(timeElapsed) {
- if (this.isHidden == true) {
- return;
- } else if (this.hasBeenPickedUp == true) {
- this.z = (this.z*6 + eyeZ+40)/7;
- this.x = (this.x*3 + eyeX)/4;
- this.y = (this.y*3 + eyeY)/4;
- if (Math.abs(this.z - eyeZ+40) < 1) {
- this.isHidden = true;
- this.z = -10000;
- }
- } else {
- if (this.collidesWith(avatar)) {
- soundPlayer.play('sound/coin_3.mp3', 100, 0, true);
- this.hasBeenPickedUp = true;
- }
- }
- this.rotZ += .4 * 20 * timeElapsed;
- updateActor(this);
-}
diff --git a/o3d/samples/io/actors/horizontalpad.js b/o3d/samples/io/actors/horizontalpad.js
deleted file mode 100644
index b2e3f85..0000000
--- a/o3d/samples/io/actors/horizontalpad.js
+++ /dev/null
@@ -1,85 +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.
- */
-
-
-/**
- * @fileoverview This file defines the HorizontalPad class.
- */
-
-/**
- * A Horizontal Floater.
- */
-function HorizontalPad(initObj) {
- this.absorbNamedValues(initObj);
- this.maxSpeed = 4 * 20;
- this.moveAmount = 4 * 20;
- this.width = 42;
- this.height = 1;
-}
-HorizontalPad.prototype = new Actor;
-
-HorizontalPad.prototype.onTick = function(timeElapsed) {
- // When you attach me to a platform, I make it so nobody
- // can stand on it... only me.
- world.platforms[this.platformID].isNotSolid = true;
-
- // I move based off of the platform that I'm on. So get that now.
- var myPlatform = world.platforms[this.platformID];
-
- // I bounce back and forth between the left and right points on my platform.
- if (this.mapX < myPlatform.left.mapX) {
- this.moveAmount += 1;
- } else if (this.mapX > myPlatform.right.mapX) {
- this.moveAmount -= 1;
- } else if (this.moveAmount >= 0) {
- this.moveAmount = this.maxSpeed;
- } else {
- this.moveAmount = -this.maxSpeed;
- }
-
- // I match my rotation to that of my platform.
- this.rotZ = myPlatform.rotZ;
-
- // Here's how I move. moveMapX is a handy function that updates both
- // my "virtual 2d world" mapX, as well as my literal x + y values
- this.moveMapX(this.moveAmount * timeElapsed)
-
- // If I collide with the avatar, then move the avatar along with me,
- // and set his "override" groundZ to be my own Z.
- if (this.collidesWith(avatar)) {
- if (avatar.velZ <= 0 && avatar.z >= this.z - 25) {
- avatar.moveMapX(this.moveAmount * timeElapsed);
- avatar.groundZ = this.z;
- }
- }
-
- updateActor(this);
-}
diff --git a/o3d/samples/io/actors/mover.js b/o3d/samples/io/actors/mover.js
deleted file mode 100644
index 8a36eed..0000000
--- a/o3d/samples/io/actors/mover.js
+++ /dev/null
@@ -1,48 +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.
- */
-
-
-/**
- * @fileoverview This file defines the Mover class.
- */
-
-/**
- * A Horizontal Floater.
- */
-function Mover(initObj) {
- this.absorbNamedValues(initObj);
-}
-Mover.prototype = new Actor;
-
-Mover.prototype.onTick = function(timeElapsed) {
- this.z += 1 * 20 * timeElapsed;
- updateActor(this);
-}
diff --git a/o3d/samples/io/actors/spikem.js b/o3d/samples/io/actors/spikem.js
deleted file mode 100644
index e056c98..0000000
--- a/o3d/samples/io/actors/spikem.js
+++ /dev/null
@@ -1,126 +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.
- */
-
-
-/**
- * @fileoverview This file defines the Spikem class.
- */
-
-/**
- * A Horizontal Floater.
- */
-function Spikem(initObj) {
- this.absorbNamedValues(initObj);
- this.width = 24;
- this.height = 55;
- this.velX = -200;
- this.velZ = 0;
- this.isDead = false;
- this.isHit = false;
- this.pauseFrames = 0;
- this.frameName = "spinning"
-}
-Spikem.prototype = new Actor;
-
-Spikem.prototype.onTick = function(timeElapsed) {
- if (this.isDead == true) {
- return;
- }
-
- if (this.isHit == true) {
- if (this.z < -1000) {
- isDead = true;
- } else {
- this.velX = this.velX*.9;
- // Here's how I move. moveMapX is a handy function that updates both
- // my "virtual 2d world" mapX, as well as my literal x + y values
- this.z -= 20;
- this.moveMapX(this.velX * timeElapsed)
- }
- } else {
- // I move based off of the platform that I'm on. So get that now.
- var myPlatform = world.platforms[this.platformID];
-
- // I stay on my platform
- if (this.mapX - this.width/2 < myPlatform.left.mapX
- && this.velX < 0) {
- this.velX *= -1;
- } else if (this.mapX + this.width/2 > myPlatform.right.mapX
- && this.velX > 0) {
- this.velX *= -1;
- }
-
- this.rotZ += this.velX / 60 * timeElapsed;
-
- if (Math.abs(this.velX) < .1) {
- if (Math.random() > .5) {
- this.velX = -400;
- } else {
- this.velX = 400;
- }
- this.pauseFrames = Math.random() * 0.5 + 1;
- }
-
- if (this.pauseFrames > 0) {
- this.frameName = "spinning"
- this.pauseFrames -= timeElapsed;
- } else {
- this.frameName = "charging"
- this.velX = this.velX*.9;
- // Here's how I move. moveMapX is a handy function that updates both
- // my "virtual 2d world" mapX, as well as my literal x + y values
- this.moveMapX(this.velX * timeElapsed)
- }
-
- if (this.isHitBySword()) {
- this.isHit = true;
- soundPlayer.play('sound/_SMASH.mp3', 100);
- this.velX = 0;
- } else if (this.isHitByArrow()) {
- top.arrowActor.hide();
- this.isHit = true;
- soundPlayer.play('sound/_SMASH.mp3', 100);
- this.velX = top.arrowActor.velX;
- } else if (this.collidesWith(avatar)) {
- // Play an event sound @100% volume, 0 repeats
- soundPlayer.play('sound/ah.mp3', 100);
-
- this.velZ = 0;
- if (avatar.velX < 1) {
- avatar.velX = this.velX * 7;
- } else {
- avatar.velX = avatar.velX * -7;
- }
- }
- }
-
- updateActor(this);
-}
diff --git a/o3d/samples/io/actors/verticalpad.js b/o3d/samples/io/actors/verticalpad.js
deleted file mode 100644
index fd90425..0000000
--- a/o3d/samples/io/actors/verticalpad.js
+++ /dev/null
@@ -1,84 +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.
- */
-
-
-/**
- * @fileoverview This file defines the VerticalPad class.
- */
-
-/**
- * A Vertical Pad you can run on. These things oscillate between their starting
- * position and a z of 350"
- */
-function VerticalPad(initObj) {
- this.absorbNamedValues(initObj);
- this.maxSpeed = 4 * 20;
- this.moveAmount = 4 * 20;
- this.bottomZ = this.z;
- this.topZ = 350;
- this.width = 42;
- this.height = 10;
-}
-VerticalPad.prototype = new Actor;
-
-VerticalPad.prototype.onTick = function(timeElapsed) {
- // I bounce back and forth between the left and right points on my platform.
- if (this.z < this.bottomZ) {
- this.moveAmount += 1;
- } else if (this.z > this.topZ) {
- this.moveAmount -= 1;
- } else if (this.moveAmount >= 0) {
- this.moveAmount = this.maxSpeed;
- } else {
- this.moveAmount = -this.maxSpeed;
- }
-
- // I match my rotation to that of my platform.
- var myPlatform = world.platforms[this.platformID];
- this.rotZ = myPlatform.rotZ;
-
-
- this.z += this.moveAmount * timeElapsed;
-
- // If I collide with the avatar, then move the avatar along with me,
- // and set his "override" groundZ to be my own Z.
- if (this.collidesWith(avatar)) {
- if (avatar.velZ <= 0 && avatar.z >= this.z - 45) {
- avatar.z = this.z
- if (this.moveAmount < 0) {
- avatar.z += this.moveAmount * timeElapsed;
- }
- avatar.groundZ = avatar.z;
- }
- }
-
- updateActor(this);
-}
diff --git a/o3d/samples/io/autoincludes.js b/o3d/samples/io/autoincludes.js
deleted file mode 100644
index be2163f..0000000
--- a/o3d/samples/io/autoincludes.js
+++ /dev/null
@@ -1,49 +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 was auto-generated by a SketchUp ruby script. Include this in your
- * game and everything else will load right in.
- *
- * WARNING: This file will be overwritten when you publish a new level from
- * SketchUp, so if you wan to manually modify it, you've been warned. :)
- */
-document.write('<script type="text/javascript" src="actors/actor.js"></script>');
-document.write('<script type="text/javascript" src="actors/arrow.js"></script>');
-document.write('<script type="text/javascript" src="actors/avatar.js"></script>');
-document.write('<script type="text/javascript" src="actors/coin.js"></script>');
-document.write('<script type="text/javascript" src="actors/horizontalpad.js"></script>');
-document.write('<script type="text/javascript" src="actors/mover.js"></script>');
-document.write('<script type="text/javascript" src="actors/spikem.js"></script>');
-document.write('<script type="text/javascript" src="actors/verticalpad.js"></script>');
-
-document.write('<script type="text/javascript" src="levels/all_actors.js"></script>');
-document.write('<script type="text/javascript" src="levels/map1.js"></script>');
diff --git a/o3d/samples/io/cutscenes.js b/o3d/samples/io/cutscenes.js
deleted file mode 100644
index 376a7845..0000000
--- a/o3d/samples/io/cutscenes.js
+++ /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.
- */
-
-
-/**
- * @fileoverview This file isn't important to the actual game. It just runs
- * pretty animations outside the o3d window.
- */
-
-/**
- * "Opens" the cover. This thing calls itself again and again until it's done.
- * @param {number} lastPercent Number from 0 to 100 representing how "done"
- */
-function animateCover(lastPercent) {
- // Move 10% more toward a 100% animation
- lastPercent = ifEmpty(lastPercent,0);
- lastPercent = lastPercent + 10;
-
- // Play a nice sound.
- if (lastPercent == 10) {
- soundPlayer.play('sound/page.mp3', 100);
- $('innercover-div').style.width = $('book-left').offsetWidth;
- $('book-left').style.width = $('book-left').offsetWidth;
- }
-
- // Transform the cover graphic from "closed" to "open." If we're more than
- // 50% along the way, then this cover gets hidden.
- var cover = $('cover')
- var innerCover = $('innercover')
-
- var factor = Math.abs(Math.cos(lastPercent/50*Math.PI/2));
- if (lastPercent < 50){
- cover.style.width = factor * 1000;
- cover.style.height = 600;
- } else {
- cover.visibility = 'hidden';
- cover.style.width = 1;
- innerCover.style.width = factor * 1000;
- innerCover.style.height = 600;
- }
-
- var shadow = $('cover-shadow');
- if (lastPercent <= 70) {
- factor = Math.abs(Math.cos(lastPercent/70*Math.PI/2));
- shadow.style.width = factor * 1000;
- shadow.style.height = 600;
- shadow.style.opacity = (70 - lastPercent)/70;
- }
-
- if (lastPercent < 100) {
- setTimeout('animateCover(' + lastPercent + ')',100);
- } else {
- shadow.style.visibility = 'hidden';
- }
-}
-
-
-/**
- * "Opens" a page. This thing calls itself again and again until it's done.
- * @param {string} id HTML element ID of the page image that we're animating.
- * @param {number} lastPercent Number from 0 to 100 representing how "done"
- */
-function animatePage(id, lastPercent) {
- // Transform the page graphic from "closed" to "open." If we're more than
- // 50% along the way, then this cover gets hidden.
- var page = $(id)
- page.style.zIndex = 200;
- lastPercent = ifEmpty(lastPercent,0);
-
- // if we've already animated this page... don't do it again.
- if (parseInt(page.style.width) < 900 && lastPercent == 0) {
- return;
- }
-
- // Move 10% more toward a 100% animation
- lastPercent = lastPercent + 10;
-
- // Play a nice sound.
- if (lastPercent == 10) {
- soundPlayer.play('sound/page.mp3', 100);
- }
-
- var factor = Math.abs(Math.cos(lastPercent/50*Math.PI/2));
- if (lastPercent < 50) {
- page.style.width = factor * 951;
- page.style.height = 549;
- } else {
- page.visibility = 'hidden';
- page.style.width = 1;
- }
-
- var shadow = $('cover-shadow')
- var coverDiv = $('cover-div')
-
- if (lastPercent <= 70){
- coverDiv.style.zIndex = 99;
- factor = Math.abs(Math.cos(lastPercent/70*Math.PI/2));
- shadow.style.width = factor * 1000;
- shadow.style.height = 600;
- shadow.style.opacity = (70 - lastPercent)/70;
- shadow.style.visibility = 'visible';
- }
-
- // Fade in a bit for the start of the animated shadow.
- if (lastPercent <= 20) {
- shadow.style.opacity = (lastPercent/30);
- }
-
- if (lastPercent < 100) {
- setTimeout('animatePage("' + id + '",' + lastPercent + ')',100);
- } else {
- shadow.style.visibility = 'hidden';
- if (id == "page2") {
- // We'll fire the animation of page 3 after 2 seconds.
- setTimeout('animatePage("page3")',2000);
- } else if (id == "page3") {
- loadLevel(0);
- }
- }
-}
diff --git a/o3d/samples/io/dynamic_lights.js b/o3d/samples/io/dynamic_lights.js
deleted file mode 100644
index 9a5b1f9..0000000
--- a/o3d/samples/io/dynamic_lights.js
+++ /dev/null
@@ -1,123 +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.
- */
-
-
-/**
- * @fileoverview Manage all the dynamic lights in a level.
- */
-
-
-var s_light_array = new Array();
-var s_number_of_lights_in_scene = 0;
-
-var s_number_of_lights_in_program = 0;
-var s_light_parameter_array = new Array();
-
-// Call this before any UpdateLightsInProgram.
-function InitializeLightParameters(context, number_of_lights) {
- s_number_of_lights_in_program = number_of_lights;
- for (var l = 0; l < number_of_lights; ++l) {
- s_light_parameter_array[l] = {};
- s_light_parameter_array[l].location = context.createParam(
- 'light' + l + '_location', 'ParamFloat3');
- s_light_parameter_array[l].location.value = [0, 0, 0];
-
- // For the light, the final color parameter is the attentuation.
- s_light_parameter_array[l].color = context.createParam(
- 'light' + l + '_color', 'ParamFloat4');
- s_light_parameter_array[l].color.value = [0, 0, 0, 1];
- }
-}
-
-// Returns the index of the new light for future manipulation.
-// World location and color should be arrays.
-// These will be assigned to Param objects.
-function AddLight(world_location, color) {
- var light_index = s_number_of_lights_in_scene++;
- s_light_array[light_index] = {};
- s_light_array[light_index].location = world_location;
- s_light_array[light_index].color = color;
- return light_index;
-}
-
-// Sets the shader parameters to render using the closest lights
-// to the 'focus' (whatever's passed in).
-// |focus_location| must provide .x, .y, and .z for determining the
-// distance to each light.
-function UpdateLightsInProgram(focus_location) {
- // TODO: Modulate the lights' color / add behaviors for the lights.
- var lights_to_render = new Array();
- for (var i = 0; i < s_number_of_lights_in_program; ++i) {
- lights_to_render[i] = {};
- lights_to_render[i].distance = 10000000000000.0; // Arbitrary large number.
- lights_to_render[i].index = -1;
- }
- var number_of_lights = s_number_of_lights_in_scene;
- for (var l = 0; l < number_of_lights; ++l) {
- var x_diff = s_light_array[l].location.x - focus_location.x;
- var y_diff = s_light_array[l].location.y - focus_location.y;
- // TODO: This should be focus_location.z, but the avatar's location that is
- // passed in is offset from the world coordinates. For our relatively flat
- // levels, this works more predictably.
- var z_diff = s_light_array[l].location.z - 0;
- var distance_to_focus = x_diff * x_diff + y_diff * y_diff + z_diff * z_diff;
- // This may change if we assign to an entry early in the list.
- var index_to_assign = l;
- for (var i = 0; i < s_number_of_lights_in_program; ++i) {
- if (distance_to_focus < lights_to_render[i].distance) {
- // Swap the index into this entry. We will percolate the
- // light up.
- var replaced_index = lights_to_render[i].index;
- lights_to_render[i].index = index_to_assign;
- index_to_assign = replaced_index;
-
- var replaced_distance = lights_to_render[i].distance;
- lights_to_render[i].distance = distance_to_focus;
- distance_to_focus = replaced_distance;
- }
- if (index_to_assign < 0) {
- break;
- }
- }
- }
-
- // Finally, assign to the actual shader parameters.
- for (var i = 0; i < s_number_of_lights_in_program; ++i) {
- var light_index = lights_to_render[i].index;
- if (light_index >= 0) {
- s_light_parameter_array[i].location.value =
- s_light_array[light_index].location;
- s_light_parameter_array[i].color.value =
- s_light_array[light_index].color;
- }
- }
-}
-
diff --git a/o3d/samples/io/editor.html b/o3d/samples/io/editor.html
deleted file mode 100644
index a212e58..0000000
--- a/o3d/samples/io/editor.html
+++ /dev/null
@@ -1,126 +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.
--->
-
-<html>
-<head>
- <title>Level Editor - Don't open this is a browser.
- It's only good inside a SketchUp WebDialog</title>
- <script type="text/javascript" src="init.js"></script>
- <script type="text/javascript" src="autoincludes.js"></script>
- <script type="text/javascript" src="gamelogic.js"></script>
- <script type="text/javascript" src="sound/soundplayer.js"></script>
-
-<script>
-function parseWorld() {
- url = 'skp:parse_world';
- window.location.href = url;
-}
-
-function play() {
- $('play-button').disabled = false;
- $('pause-button').disabled = true;
-
- url = 'skp:do_play@';
- window.location.href = url;
-
-}
-
-function pause() {
-
- $('play-button').disabled = false;
- $('pause-button').disabled = true;
- clearTimeout(timerID)
-}
-
-function save() {
- url = 'skp:do_save@';
- window.location.href = url;
-}
-
-function startNew() {
- name = prompt("What do you want to call your new level?\n" +
- "(Choose wisely... you can't rename yet.)","My First Level");
- url = 'skp:do_new@';
- url += 'name=' + name;
- window.location.href = url;
- $('export-button').disabled = false;
- $('play-button').disabled = false;
-}
-
-function setWorldFromName(name) {
- output.innerHTML += '<script type="text/javascript" src="autoincludes.js"><' + '/script>';
- for (i=0;i<levels.length; i++) {
- //alert('looking at ' + levels[i].colladaFile);
- if (levels[i].colladaFile == name + '.o3dtgz') {
- world = levels[i];
- avatar = levels[i].actors[0];
- nextFrame();
- $('pause-button').disabled = false;
- $('play-button').disabled = true;
- break;
- }
- }
-
-}
-
-</script>
-</head>
-<style>
-A { font-family: sans-serif; text-decoration: none; }
-A:link { color: yellow; }
-A:visited { color: yellow; }
-A:active { color: yellow; }
-A:hover { color: yellow; }
-BODY { font-family: sans-serif; }
-INPUT { width: 100%; text-align: left; padding-left: 6px; margin-top: 3px;}
-.head { background-color: black; color: gold; font-weight: bold; padding: 6px; }
-.levellink {
- color: blue;
- text-decoration: underline;
- cursor: pointer;
-
-}
-</style>
-<body style="background-color:threedface;" onload="init()">
- <div class="head">Select an action...</div>
- <input type="button" onclick="startNew()" value="Start a new level from a template">
- <input id="export-button" type="button" onclick="save()" disabled="true" value="Save this file and export to O3D">
- <input id="play-button" type="button" disabled="true" onclick="play();" value="Play the level inside SketchUp">
- <input id="pause-button" type="button" disabled="true" onclick="pause();" value="Pause playback">
-
- <br><div class="head">Or select an existing level to load...</div>
-
- <span id="content">List...</span>
-
- <span id="output"></span>
-</body>
-</html>
-
diff --git a/o3d/samples/io/gamelogic.js b/o3d/samples/io/gamelogic.js
deleted file mode 100644
index 65f5ff6..0000000
--- a/o3d/samples/io/gamelogic.js
+++ /dev/null
@@ -1,578 +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.
- */
-
-
-/**
- * @fileoverview This file sets up the game state JS structures, sets up
- * keyboard handlers, and contains the main game loop.
- */
-
- /**
- * Global constants that drive the game engine.
- */
-var FRAMES_PER_SECOND = 20; // Change for a faster or slower game.
-var FRAME_DELAY = 1000 / FRAMES_PER_SECOND; // Milliseconds between frames.
-var GRAVITY = -2000; // Inches per second per second.
-var JUMP_VELOCITY = 650;
-var RUN_VELOCITY = 200;
-var WORLD_ANGLE = 0;
-var CAMERA_SOFTNESS = 15;
-
-
-/**
- * These are some global pointers that we'll use for to point at our world
- * object (aka "current map" or "current level"), and our happy avatar (aka
- * the protagonist, Prince Io.)
- */
-var world;
-var avatar;
-
-/**
- * Keyboard constants.
- */
-var BACKSPACE = 8;
-var TAB = 9;
-var ENTER = 13;
-var SHIFT = 16;
-var CTRL = 17;
-var ALT = 18;
-var ESCAPE = 27;
-var PAGEUP = 33;
-var PAGEDOWN = 34;
-var END = 35;
-var HOME = 36;
-var LEFT = 37;
-var UP = 38;
-var RIGHT = 39;
-var DOWN = 40;
-var DELETE = 46;
-var SPACE = 32;
-
-/**
- * These variables are special SketchUp constants that aren't really constant.
- * They are updated by SketchUp every frame to indicate what's around the
- * avatar.
- * TODO: ADDENDUM! These vars used to be "special constants,"
- * but now they're leftovers of a time when SU was the main engine, and the
- * game logic below should be cleaned up so we're not using all caps on these.
- */
-var GROUNDZ; // Absolute Z of the obstacle beneath the avatar.
-var OBSTACLE_LEFT; // Distance to nearest obstacle to the left.
-var OBSTACLE_RIGHT; // Distance to nearest obstacle on the right.
-
-/**
- * Camera position stuff.
- * TODO: These are redundant vs. the camera.eye.x stuff in
- * init.js. Clean that outa thar!
- */
-var eyeX = 0;
-var eyeY = -1000;
-var eyeZ = 1000;
-var targetX = 0;
-var targetY = 0;
-var targetZ = 0;
-
-/**
- * If the user presses the swing button while we're showing a swing, then we'll
- * mark the fact that we need to immediately swing again once the current
- * animation is done.
- */
-var swingAgain = false;
-
-/**
- * Way of determining that the user just pressed then unpressed certain keys.
- */
-var upWasJustDown = false;
-var ctrlWasJustUp = false;
-
-/**
- * Identifier for our global game timer. This is only used when SketchUp is the
- * main CG engine.
- */
-var timerID;
-
-/**
- * Code to keep track of the current key state. Since these events can fire at
- * any time but we only want to apply changes to our game state at the start of
- * each game loop, we do this trick so that the nextFrame() function can poll
- * the keyIsDown data structure to determine what's happened since the last
- * frame.
- */
-var keyIsDown = {};
-
-function keyMessage(e, state) {
- keyIsDown[o3djs.event.getEventKeyChar(e ? e : window.event)] = state;
-}
-
-document.onkeydown = function(e) { keyMessage(e, true); };
-
-document.onkeyup = function(e) { keyMessage(e, false); };
-
-
-/**
- * Main Game Loop.... Here's where we actually run the game.
- * @param {number} elapsedTime Number of seconds since we were last called.
- */
-function nextFrame(elapsedTime) {
- // First, let's look at our avatar. If he's jumping, then figure out which
- // platform (if any) he's currently over.
- if (avatar.isJumping) {
- var lowestZFound = -5000;
- for (var i = 0; i < world.platforms.length; i++) {
- platform = world.platforms[i];
- if (platform.parentID == avatar.parentPlatformID ||
- i == avatar.parentPlatformID) {
- if (avatar.z > platform.z &&
- avatar.mapX > platform.left.mapX &&
- avatar.mapX < platform.right.mapX &&
- platform.z > lowestZFound && platform.isNotSolid != true) {
- lowestZFound = world.platforms[i].z
- avatar.platformID = i;
- }
- }
- }
- }
-
- // Create a myPlatform variable for convenience.
- var myPlatform = world.platforms[avatar.platformID]
-
- // Platforms without a parentID aren't really platforms. The actually define
- // the "world path" that meanders through our level. Therefore, if the only
- // platform that Io is over is one of these, then our current GROUNDZ (aka
- // the nearest walkable altitude),
- if (exists(myPlatform.parentID)) {
- GROUNDZ = myPlatform.z
- avatar.parentPlatformID = myPlatform.parentID;
- } else {
- GROUNDZ = -5000;
- avatar.parentPlatformID = avatar.platformID;
- }
-
- // The avatar's mapX is really important. It defines his position in the
- // imaginary 2d platformer that we weave through a 3D world. When he's at
- // mapX of 0, he's at the far left of the level (think super mario.) As
- // he proceeds through the level, his mapX will get bigger. Meanwhile, his
- // actual x, y, and z (aka altitude) values will be kept track of as well.
- // Anyway, every platform that Io can stand on has a "left" and a "right"
- // to them. Let's check to see if we've walked off of it...
- if (avatar.mapX < myPlatform.left.mapX) {
- // Whoa! We've walked off the left of our platform! If there's an adjacent
- // platform to step onto, then do that. Otherwise, it's fallin' time.
- if (exists(myPlatform.left.adjacentID)) {
- // Do some math to ensure that our actual x and y values are corrected
- // so Io stays perfectly in our "world path" plane.
- oldPlatform = myPlatform;
- overshot = avatar.mapX - myPlatform.left.mapX;
- avatar.platformID = myPlatform.left.adjacentID;
- myPlatform = world.platforms[avatar.platformID];
- avatar.x -= Math.cos(oldPlatform.rotZ) * overshot;
- avatar.y -= Math.sin(oldPlatform.rotZ) * overshot;
- avatar.x += Math.cos(myPlatform.rotZ) * overshot;
- avatar.y += Math.sin(myPlatform.rotZ) * overshot;
- } else {
- GROUNDZ = -5000;
- }
- } else if (avatar.mapX > myPlatform.right.mapX) {
- // Whoa! We've walked off the right of our platform!
- if (exists(myPlatform.right.adjacentID)) {
- oldPlatform = myPlatform;
- overshot = avatar.mapX - myPlatform.right.mapX;
- avatar.platformID = myPlatform.right.adjacentID;
- myPlatform = world.platforms[avatar.platformID];
- avatar.x -= Math.cos(oldPlatform.rotZ) * overshot;
- avatar.y -= Math.sin(oldPlatform.rotZ) * overshot;
- avatar.x += Math.cos(myPlatform.rotZ) * overshot;
- avatar.y += Math.sin(myPlatform.rotZ) * overshot;
- } else {
- GROUNDZ = -5000;
- }
- }
-
- // Now it's time to figure out if there's a "obstacle" nearby. Each platform
- // can potentially have a left.obstacleHeight and/or a right.obstableHeight.
- // We'll store how close any of them are in these OBSTABLE_LEFT type
- // "constants."
- OBSTACLE_RIGHT = 9000
- OBSTACLE_RIGHT_HEIGHT = 0
- OBSTACLE_LEFT = 9000
- OBSTACLE_LEFT_HEIGHT = 0
-
- if (myPlatform.right.obstacleHeight > 0) {
- OBSTACLE_RIGHT = myPlatform.right.mapX - avatar.mapX;
- OBSTACLE_RIGHT_HEIGHT = myPlatform.right.obstacleHeight - avatar.velZ + 20;
- }
- if (myPlatform.left.obstacleHeight > 0) {
- OBSTACLE_LEFT = avatar.mapX - myPlatform.left.mapX;
- OBSTACLE_LEFT_HEIGHT = myPlatform.left.obstacleHeight - avatar.velZ + 20;
- }
-
- // So... now that we've figured all of that stuff out, let's store how
- // far *above* the current platform Io is.
- avatar.relativeZ = avatar.z - myPlatform.z;
-
- // This special variable, avatar.groundZ, can be set by moving
- // platforms and other actors to override our actual groundZ. This allows
- // the avatar to "float" in space (or really, to stand on stuff that's
- // not a static platform but a moving one.) So if we find that variable,
- // it trumps the calculated GROUNDZ. However, we *always* clear that
- // variable out after using it. It's up to the Actor who is moving Io to
- // keep this updated inside their onTick event. (See horizontalpad.js for
- // an example of this.)
- if (exists(avatar.groundZ)) {
- GROUNDZ = avatar.groundZ;
- avatar.groundZ = undefined;
- }
-
- // Gah. Another one of our "special constants" that used to be updated
- // by SketchUp but now is done via JS data structures.
- // TODO: Clean 'tup.
- WORLD_ANGLE = myPlatform.rotZ;
-
- // Check for keyboard stuff.
- handleInput();
-
- // Handle falling and gravity.
- avatar.z += avatar.velZ * elapsedTime;
- if (avatar.z - GROUNDZ > 1) {
- avatar.isJumping = true;
- } else {
- if (avatar.isJumping == true) {
- soundPlayer.play('sound/step2.mp3', 100);
- }
- avatar.isJumping = false;
- }
- if (avatar.isJumping == true) {
- avatar.velZ += GRAVITY * elapsedTime;
- }
- if (avatar.z < GROUNDZ) {
- avatar.velZ = 0;
- avatar.z = GROUNDZ + .1;
- avatar.isJumping = false;
- avatar.animation = 'Hero_Run';
-
- }
- if (avatar.z < -1000) {
- avatar.x = 0;
- avatar.y = 0;
- avatar.z = 200;
- avatar.mapX = 0;
- avatar.platformID = 0;
- avatar.parentPlatformID = 0;
- }
-
- // Handle collision with things to the left and right of our avatar.
- // From here is where we start to decide which animation cycle we're on.
- // Now you can see how we're using avatar.relativeZ along with our
- // OBSTACLE_FOO "special constants" to determine not only if we've hit an
- // obstacle, but whether we've jumped high enough to get over it.
- if (OBSTACLE_LEFT < 25 && keyIsDown[LEFT] &&
- OBSTACLE_LEFT_HEIGHT > avatar.relativeZ) {
- avatar.targetVelX = 0;
- avatar.animation = 'Hero_Stand';
- avatar.frame = 1;
- }
- if (OBSTACLE_RIGHT < 25 && keyIsDown[RIGHT] &&
- OBSTACLE_RIGHT_HEIGHT > avatar.relativeZ) {
- avatar.targetVelX = 0;
- avatar.animation = 'Hero_Stand';
- avatar.frame = 1;
- }
-
- // If we're jumping, then use the jumping animation cycle.
- if (avatar.isJumping == true) {
- avatar.animation = 'Hero_Jump';
- if (avatar.velZ > 0) {
- avatar.frame += elapsedTime * 20;
- if (avatar.frame > 3) {
- avatar.frame = 3;
- }
- } else {
- if (avatar.z > GROUNDZ + 20) {
- avatar.frame = 4;
- } else {
- avatar.frame = 5;
- }
- }
- }
-
- // Figure out which frame to display inside our current cycle.
- didSwordStrike = '0';
- if (avatar.animation == 'Hero_Run') {
- avatar.frame += elapsedTime * 20;
- if (avatar.frame > 10) {
- avatar.frame = 1;
- }
- if (Math.floor(avatar.frame % 5) == 0) {
- var soundToPlay = 'sound/step'
- soundToPlay += (Math.floor(Math.random() * 3) + 1);
- soundToPlay += '.mp3'
- soundPlayer.play(soundToPlay, 100);
- }
- } else if (avatar.animation == 'Hero_Sword') {
- avatar.targetVelX = 0;
- avatar.framesSinceShot = 0;
- avatar.frame += avatar.swordRate * 20 * elapsedTime;
- if (avatar.frame < 1) {
- avatar.animation = 'Hero_Stand'
- avatar.frame = 1;
- } else if (avatar.frame > 7) {
- avatar.swordRate = -.5;
- avatar.frame = 6.2;
- didSwordStrike = '1';
- } else if (avatar.frame == 3 && avatar.swordRate < 0) {
- if (swingAgain == true) {
- avatar.swordRate = 1;
- swingAgain = false;
- } else {
- avatar.swordRate = -.5;
- }
- }
-
- if (avatar.frame == 3 && avatar.swordRate > 0) {
- soundPlayer.play('sound/_MISS.mp3', 100);
- }
- }
-
- // Update our position.
- avatar.velX = (avatar.velX + avatar.targetVelX + avatar.targetVelX) / 3;
- if (Math.abs(avatar.velX) < .2) {
- avatar.velX = 0;
- }
- avatar.mapX += avatar.velX * elapsedTime;
- avatar.x += avatar.velX * Math.cos(WORLD_ANGLE) * elapsedTime;
- avatar.y += avatar.velX * Math.sin(WORLD_ANGLE) * elapsedTime;
- avatar.rotZ = (avatar.rotZ + avatar.targetRotZ + avatar.targetRotZ) / 3;
-
- // Calculate our final frameName string to pass to SketchUp (or o3d).
- frameName = avatar.animation;
- if (avatar.frame < 10) {
- frameName += '0';
- }
- frameName += Math.floor(avatar.frame);
- if (avatar.framesSinceShot > 0) {
- frameName += 'Shoot';
- avatar.framesSinceShot--;
- }
- if (avatar.framesSinceShot == 3) {
- // TODO: Make this work with multiple arrows, perform
- // better, and be smart enough to handle level reloads.
- if (top.arrowActor == undefined) {
- for (var actorID = 0; actorID < world.actors.length; actorID++) {
- arrow = world.actors[actorID];
- if (arrow.name.indexOf('Arrow') == 0) {
- top.arrowActor = arrow;
- top.arrowActor.shoot();
- }
- }
- } else {
- top.arrowActor.shoot();
- }
- }
- avatar.frameName = frameName;
-
- // Here's where we send our state down to SketchUp or O3D.
- // Always do our avatar last, since he's the one likely to have
- // been modified by other things in the environment. (Our avatar
- // is guaranteed by the level exporter to be in world.actors[0])
- for (i = world.actors.length - 1; i >= 0; i--) {
- world.actors[i].onTick(elapsedTime);
- }
-
- // Now move the camera in a pleasing motion to float over Io's
- // right shoulder. (Well, it's his right shoulder when he's
- // facing "right" toward the end of the level.)
- newEyeX = avatar.x + 350 * Math.sin(WORLD_ANGLE);
- newEyeY = avatar.y - 350 * Math.cos(WORLD_ANGLE);
- newEyeZ = avatar.z + 150;
- eyeX = (newEyeX + eyeX * CAMERA_SOFTNESS) / (CAMERA_SOFTNESS + 1);
- eyeY = (newEyeY + eyeY * CAMERA_SOFTNESS) / (CAMERA_SOFTNESS + 1);
- eyeZ = (newEyeZ + eyeZ * CAMERA_SOFTNESS) / (CAMERA_SOFTNESS + 1);
- targetX = (avatar.x + targetX) / 2;
- targetY = (avatar.y + targetY) / 2;
- targetZ = (avatar.z + 200 + targetZ * 3) / 5;
-
- // Here's where we send our camera down to SketchUp or O3D.
- updateCamera(targetX, targetY, targetZ, eyeX, eyeY, eyeZ)
-
- // If we're running inside SketchUp, clear out our old timer and set a new
- // one.
- if (isSU) {
- clearTimeout(timerID);
- timerID = self.setTimeout('nextFrame()', FRAME_DELAY);
- }
-}
-
-
-/**
- * Sends our state to our render engine. (See knightgame.rb for the Sketchup
- * ruby handler.)
- * @param {Object} actor An instance of an Actor object.
- */
-function updateActor(actor) {
- var frameName = actor.frameName;
- var x = actor.x;
- var y = actor.y;
- var z = actor.z;
- var rotZ = actor.rotZ;
-
- // Sending stuff to SU vs. to O3D.
- if (isSU == true) {
- url = 'skp:push_frame_js@';
- url += 'name=' + actor.name;
- url += '&frame=' + frameName;
- url += '&x=' + x;
- url += '&y=' + y;
- url += '&z=' + z;
- url += '&rotz=' + rotZ;
- window.location.href = url;
- } else {
- // For performance reasons, we want to cache node pointers directly onto
- // our Actor object, so we don't have to look it all up every time.
- if (actor.nodesHaveBeenCached != true) {
- actor.hasBeenCached = true;
- nodes = client.getObjects(actor.colladaID, 'o3d.Transform');
- actor.node = nodes[0];
-
- var instance = actor.node.children[0];
- actor.children = instance.children;
- actor.nodesHaveBeenCached = true;
- }
-
- var m = math.matrix4.rotationZYX([0, rotZ, 0]);
- math.matrix4.setTranslation(m, [x, z, -y]);
- actor.node.localMatrix = m;
-
- if (!isEmpty(frameName)) {
- for (var c = 0; c < actor.children.length; c++) {
- var child = actor.children[c];
- child_name = child.name;
- child.visible = (child_name == frameName ||
- child_name == frameName + '1' ||
- child_name == frameName + '_1');
- }
- }
- }
-}
-
-/**
- * Sends our state down to SketchUp or o3d. (See knightgame.rb for the handler.)
- * @param {number} targetX Where we want the camera to point at.
- * @param {number} targetY Where we want the camera to point at.
- * @param {number} targetZ Where we want the camera to point at.
- * @param {number} eyeX Where we want the camera to point from.
- * @param {number} eyeY Where we want the camera to point from.
- * @param {number} eyeZ Where we want the camera to point from.
- */
-function updateCamera(targetX, targetY, targetZ, eyeX, eyeY, eyeZ) {
- if (isSU == true) {
- url = 'skp:push_camera@';
- url += 'targetX=' + targetX;
- url += '&targetY=' + targetY;
- url += '&targetZ=' + targetZ;
- url += '&eyeX=' + eyeX;
- url += '&eyeY=' + eyeY;
- url += '&eyeZ=' + eyeZ;
- window.location.href = url;
- } else {
- var target = [targetX, targetZ, -targetY];
- var eye = [eyeX, eyeZ, -eyeY];
- var up = [0, 1, 0];
- var view_matrix = math.matrix4.lookAt(eye, target, up);
-
- drawContext.view = view_matrix;
-
- // !lacz modified!
- camera_eye_param.value = eye;
- camera_target_param.value = target;
- }
-}
-
-/**
- * Checks for keyboard stuff.
- */
-function handleInput() {
- if (keyIsDown[SPACE]) {
- avatar.framesSinceShot = 5;
- }
-
- if (keyIsDown[DOWN]) {
- if (avatar.animation == 'Hero_Sword') {
- if (ctrlWasJustUp == true) {
- swingAgain = true;
- }
- } else {
- avatar.animation = 'Hero_Sword';
- avatar.frame = 1;
- avatar.swordRate = 1;
- ctrlWasJustUp = false;
- }
- } else {
- ctrlWasJustUp = true;
- }
-
- if (keyIsDown[UP] && avatar.isJumping != true && upWasJustDown == false) {
- avatar.velZ = JUMP_VELOCITY;
- avatar.isJumping = true;
- upWasJustDown = true;
- }
- if (keyIsDown[UP]) {
- upWasJustDown = true;
- } else {
- upWasJustDown = false;
- }
-
- if (keyIsDown[RIGHT] || keyIsDown[LEFT]) {
- if (avatar.animation == 'Hero_Stand' && avatar.frame == 1) {
- avatar.frame = 2;
- } else if (avatar.animation == 'Hero_Stand' && avatar.frame == 2) {
- avatar.animation = 'Hero_Run';
- avatar.frame = 1;
- }
-
- } else {
- if (avatar.animation == 'Hero_Run') {
- avatar.animation = 'Hero_Stand';
- avatar.frame = 2;
- } else if (avatar.animation == 'Hero_Stand' && avatar.frame == 2) {
- avatar.frame = 1;
- }
- }
-
- if (keyIsDown[RIGHT]) {
- avatar.targetVelX = RUN_VELOCITY;
- avatar.targetRotZ = WORLD_ANGLE;
- } else if (keyIsDown[LEFT]) {
- avatar.targetVelX = -RUN_VELOCITY;
- avatar.targetRotZ = -(Math.PI) + WORLD_ANGLE;
- } else {
- avatar.targetVelX = 0;
- }
-}
diff --git a/o3d/samples/io/init.js b/o3d/samples/io/init.js
deleted file mode 100644
index e6c145f..0000000
--- a/o3d/samples/io/init.js
+++ /dev/null
@@ -1,395 +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.
- */
-
-
-/**
- * @fileoverview This file creates all of the global o3d stuff that
- * establishes the plugin window, sets its size, creates necessary light
- * and camera parameters, and stuff like that.
- */
-o3djs.require('o3djs.util');
-o3djs.require('O3D.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.scene');
-
-// Create some globals that store our main pointers to o3d objects.
-var o3d;
-var math;
-var math;
-var client;
-var pack;
-var globalParams;
-var g_viewInfo;
-var drawContext;
-var blackSampler;
-var g_loadInfo;
-
-// This variable keeps track of whether a collada file is correctly loaded.
-var isLoaded = false;
-
-// This variable, surprisingly, contains the time since the last frame
-// (in seconds)
-var timeSinceLastFrame = 0;
-var frameCount = 0;
-
-// This is only a handy data structure for storing camera information. It's not
-// actually a core O3D object.
-var camera = {
- eye: [0, 0, 500],
- target: [0, 0, 0]
-};
-
-/**
- * This is a top-level switch that tells us whether we're running inside a
- * SketchUp web dialog. (If not, then we're in O3D.)
- * TODO : Re-enable the SketchUp web-dialog functionality, but through
- * a check different than simply testing if we are running in IE.
- */
-//var isSU = (navigator.appVersion.indexOf('MSIE') != -1) ? true : false;
-var isSU = false;
-
-// Some parameters to pass to the shaders as the camera moves around.
-var camera_eye_param;
-var camera_target_param;
-
-// Keep track of the lights in the level.
-var light_array;
-var max_number_of_lights = 4; // Determined from the GPU effect.
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Gets called at the page's onLoad event. This function sets up our plugin and
- * level selection UI.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Walk across all levels loaded by includes.js and show a list for the user
- // to choose from.
- $('content').innerHTML = 'Choose a level...<br>';
- for (var i = 0; i < levels.length; i++) {
- var level = levels[i];
- var str = '<span class="levellink" onclick="loadLevel(' + i + ')">' +
- level.name + '</span><br>'
- $('content').innerHTML += str;
- }
-
- soundPlayer.play('sound/music.mp3', 100, 999);
-
- // If we're NOT running inside SketchUp, then we need to set up our o3d
- // window.
- if (!isSU) {
- var o3dElement = clientElements[0];
- o3dElement.id = 'o3dObj';
- o3d = o3dElement.o3d;
- math = o3djs.math;
- client = o3dElement.client;
- pack = client.createPack();
- var blackTexture = pack.createTexture2D(1, 1, o3d.Texture.XRGB8, 1, false);
- blackTexture.set(0, [0, 0, 0]);
- blackSampler = pack.createObject('Sampler');
- blackSampler.texture = blackTexture;
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- pack,
- client.root,
- client.renderGraphRoot);
-
- drawContext = g_viewInfo.drawContext;
-
- var target = [0, 0, 0];
- var eye = [0, 0, 5];
- var up = [0, 1, 0];
- var view_matrix = math.matrix4.lookAt(eye, target, up);
-
- drawContext.view = view_matrix;
-
- globalParams = pack.createObject('ParamObject');
-
- // Initialize all the effect's required parameters.
- var ambient_light_color_param = globalParams.createParam(
- 'ambientLightColor',
- 'ParamFloat4');
- ambient_light_color_param.value = [0.27, 0.2, 0.2, 1];
- var sunlight_direction_param = globalParams.createParam('sunlightDirection',
- 'ParamFloat3');
-
- // 20 degrees off.
- sunlight_direction_param.value = [-0.34202, 0.93969262, 0.0];
- var sunlight_color_param = globalParams.createParam('sunlightColor',
- 'ParamFloat4');
-
- sunlight_color_param.value = [0.55, 0.6, 0.7, 1.0];
- // global parameter, this will change as the character moves.
- camera_eye_param = globalParams.createParam('cameraEye', 'ParamFloat3');
- camera_eye_param.value = eye;
- camera_target_param = globalParams.createParam('cameraTarget',
- 'ParamFloat3');
- camera_target_param.value = target;
-
- InitializeLightParameters(globalParams, max_number_of_lights);
-
- var fog_color_param = globalParams.createParam('fog_color', 'ParamFloat4');
- fog_color_param.value = [0.5, 0.5, 0.5, 1.0];
-
- // Create a perspective projection matrix.
- var o3d_width = 845;
- var o3d_height = 549;
-
- var proj_matrix = math.matrix4.perspective(
- 45 * Math.PI / 180, o3d_width / o3d_height, 0.1, 5000);
-
- drawContext.projection = proj_matrix;
-
- o3dElement.onkeydown = document.onkeydown;
- o3dElement.onkeyup = document.onkeyup;
-
- o3djs.event.startKeyboardEventSynthesis(o3dElement);
- }
-}
-
-/**
- * Remove callbacks on the o3d client.
- */
-function uninit() {
- if (client) {
- client.cleanup();
- }
-}
-
-/**
- * Helper function to shorten document.getElementById()
- * @param {string} value The elementID to find.
- * @return {string} The document element with our ID.
- */
-function $(id) {
- return document.getElementById(id);
-}
-
-/**
- * Helper function to tell us if a value is set to something useful.
- * @param {Object} value The thing to check out.
- * @return {boolean} Whether the thing is empty.
- * TODO: 'Tis silly to have both an isEmpty and exists function
- * when they're probably doing the same thing.
- */
-function isEmpty(value) {
- return (value == undefined) || (value == '');
-}
-
-/**
- * Returns the 2nd value if the first is rmpty.
- * @param {Object} val1 The thing to check for emptyness.
- * @param {Object} val2 The thing to maybe pass back.
- * @return {Object} One of the above.
- */
-function ifEmpty(val1, val2) {
- if (val1 == undefined || val1 == '') {
- return val2;
- }
- return val1;
-}
-
-/**
- * Helper function to tell us if a value exists.
- * @param {Object} item The thing to check out.
- * @return {boolean} Whether the thing exists.
- */
-function exists(item) {
- if (item == undefined || item == null) {
- return false;
- } else {
- return true;
- }
-}
-
-/**
- * Takes an index number into our global levels[] array, and it loads up that
- * level.
- * @param {number} levelID The number of the level to load in.
- */
-function loadLevel(levelID) {
- if (isLoaded) {
- return;
- }
- world = levels[levelID];
-
- // If we're running in 'SketchUp mode' inside the level editor, tell SU to
- // do the loading, then bail out of here.
- if (isSU) {
- clearTimeout(timerID)
- url = 'skp:do_open@';
- url += 'level_name=' + world.colladaFile;
- url += '&friendly_name=' + world.name;
- window.location.href = url;
- $('export-button').disabled = false;
- $('play-button').disabled = false;
- $('pause-button').disabled = true;
- isLoaded = true;
- return;
- }
-
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- path = path.substring(0, index + 1) + 'levels/' + world.colladaFile;
- $('o3d').style.width = '845px';
- $('o3d').style.height = '549px';
-
- // Create a callback function to prepare the transform graph once its loaded.
- function callback(exception) {
- if (exception) {
- alert('Could not load: ' + path + '\n' + exception);
- } else {
- var current_light = 0;
- var my_effect = pack.createObject('Effect');
- my_effect.name = 'global_effect';
- var effect_string = $('global_effect').value;
- my_effect.loadFromFXString(effect_string);
-
- var xform_nodes = client.root.getTransformsInTree();
- for (var i = 0; i < xform_nodes.length; ++i) {
- var shape_name = xform_nodes[i].name;
- if (shape_name.indexOf('Light') == 0) {
- var world_transform = xform_nodes[i].getUpdatedWorldMatrix();
- var world_loc = world_transform[3];
- var world_location = world_loc;
- var color = [1.0, 0.7, 0.10, 150.0];
-
- var light_index = AddLight(world_location, color);
- xform_nodes[i].parent = null;
- ++current_light;
- }
- }
-
- {
- var materials = pack.getObjectsByClassName('o3d.Material');
- for (var m = 0; m < materials.length; ++m) {
- var material = materials[m];
- if (!material.getParam('diffuseSampler')) {
- diffuseParam = material.createParam('diffuseSampler',
- 'ParamSampler');
- diffuseParam.value = blackSampler;
- }
- material.effect = my_effect;
- my_effect.createUniformParameters(material);
- // go through each param on the material
- var params = material.params;
- for (var p = 0; p < params.length; ++p) {
- var dst_param = params[p];
- // see if there is one of the same name on the paramObject we're
- // using for global parameters.
- var src_param = globalParams.getParam(dst_param.name);
- if (src_param) {
- // see if they are compatible
- if (src_param.isAClassName(dst_param.className)) {
- // bind them
- dst_param.bind(src_param);
- }
- }
- }
- }
- }
-
- // Remove all line primitives as we don't really want them to render.
- {
- var primitives = pack.getObjectsByClassName('o3d.Primitive');
- for (var p = 0; p < primitives.length; ++p) {
- var primitive = primitives[p];
- if (primitive.primitiveType == o3d.Primitive.LINELIST) {
- primitive.owner = null;
- pack.removeObject(primitive);
- }
- }
- }
-
- o3djs.pack.preparePack(pack, g_viewInfo);
- avatar = world.actors[0];
- isLoaded = true;
- client.setRenderCallback(onRender);
- $('container').style.visibility = 'visible';
- }
- }
-
- // Create a new transform node to attach our world to.
- var world_parent = pack.createObject('Transform');
- world_parent.parent = client.root;
-
- function loadSceneCallback(pack, parent, exception) {
- g_loadInfo = null;
- callback(exception);
- }
- g_loadInfo = o3djs.scene.loadScene(client, pack, world_parent, path,
- loadSceneCallback);
-}
-
-/**
- * This is our little callback handler that o3d calls after each frame.
- * @param {Object} renderEvent An event object.
- */
-function onRender(renderEvent) {
- if (g_loadInfo) {
- $('fps').innerHTML = 'Loading: ' +
- g_loadInfo.getKnownProgressInfoSoFar().percent + '%';
- }
- if (isLoaded == false) {
- return;
- }
-
- var elapsedTime = Math.min(renderEvent.elapsedTime, 1 / 20);
-
- nextFrame(elapsedTime);
- UpdateLightsInProgram(avatar);
-
- // Every 20 frames, update our frame rate display
- frameCount++;
- if (frameCount % 20 == 0) {
- $('fps').innerHTML = Math.floor(1.0 / elapsedTime + 0.5);
- }
-}
-
-/**
- * This cancels scrolling and keeps focus on a hidden element so spacebar
- * doesn't page down.
- */
-function cancelScroll() {
- $('focusHolder').focus();
- var pageWidth = document.body.clientWidth;
- var pageHeight = document.body.clientHeight;
- document.body.scrollTop = 0;
- document.body.scrollLeft = 0;
-}
diff --git a/o3d/samples/io/io.html b/o3d/samples/io/io.html
deleted file mode 100644
index 55c0db3..0000000
--- a/o3d/samples/io/io.html
+++ /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.
--->
-
-<html>
- <title>The Journies of Prince IO: An O3D Adventure</title>
- <link href="ui/io.css" rel="stylesheet" type="text/css"/>
- <script type="text/javascript" src="../o3djs/base.js"></script>
- <script type="text/javascript" src="dynamic_lights.js"></script>
- <script type="text/javascript" src="init.js"></script>
- <script type="text/javascript" src="autoincludes.js"></script>
- <script type="text/javascript" src="gamelogic.js"></script>
- <script type="text/javascript" src="cutscenes.js"></script>
- <script type="text/javascript" src="sound/soundplayer.js"></script>
-</head>
-
-<body onload="init();" onscroll="cancelScroll()" onunload="uninit();">
-
-<table id="table-main"><tr><td valign=center>
-
-<table id="table-middle" cellspacing="0" cellpadding="0" border="0">
- <tr>
- <td id="book-left" width="50%"><div id="innercover-div"><img id="innercover" src="ui/book_innercover.jpg"></div></td>
- <td id="book-center" width="1000"><div id="cover-div"><img id="cover-shadow" src="ui/covershadow.png"><img onclick="animateCover()" id="cover" src="ui/book_cover.jpg"></div><img src="ui/book_captop.jpg" width="988" height="39"><br><div id="cover-seam"></div><div id="content">
-
- Choose a level...
-
- </div><div id="container" name="container" >
- <div id="o3d" style="width: 1px; height: 1px;"></div>
- </div><img id="page1" src="ui/book_page1.jpg" onclick="animatePage('page1')"><img id="page2" src="ui/book_page2.jpg" onclick="animatePage('page2')"><img id="page3" src="ui/book_page3.jpg" onclick="animatePage('page3')"><img src="ui/book_pageblank.jpg" width="951" height="549"><img src="ui/book_capright.jpg" width="37" height="549"><br><img src="ui/book_capbottom.jpg" width="988" height="90"></td>
- <td id="book-right" width="50%">&nbsp;</td>
- </tr>
-</table>
-
-</td></tr></table>
-
-<form>
-<input id="focusHolder" style="position:absolute;top:-100px;">
-</form>
-
-<div id="footer"><div id="output"></div><div id="fps"></div><img src="ui/logo.gif" alt="Google"></div>
-<div id="fx" style="visibility:hidden">
-<textarea id="global_effect">
-struct a2v {
- float4 position : POSITION;
- float3 normal : NORMAL;
- float2 texCoord : TEXCOORD0;
-};
-
-struct v2f {
- float4 position : POSITION;
- float3 worldPosition : TEXCOORD0;
- float2 texCoord : TEXCOORD1;
- float3 n : TEXCOORD2;
- float3 l : TEXCOORD3;
-};
-
-float4x4 worldViewProj : WorldViewProjection;
-float4x4 world : World;
-float4x4 worldIT : WorldInverseTranspose;
-
-uniform float4 ambientLightColor;
-uniform float3 sunlightDirection;
-uniform float4 sunlightColor;
-uniform float3 cameraEye;
-uniform float3 cameraTarget;
-
-uniform float3 light0_location;
-uniform float3 light1_location;
-uniform float3 light2_location;
-uniform float3 light3_location;
-uniform float3 light4_location;
-
-uniform float4 light0_color;
-uniform float4 light1_color;
-uniform float4 light2_color;
-uniform float4 light3_color;
-uniform float4 light4_color;
-uniform float4 fog_color;
-
-// The texture from a sketchup6 file
-// A diffuseTexture and a diffuse color (when there isn't a texture)
-uniform float4 diffuse; // The color, unless texture
-sampler2D diffuseSampler;
-
-v2f vsMain(a2v IN) {
- v2f OUT;
- OUT.position = mul(IN.position, worldViewProj);
- OUT.worldPosition = mul(IN.position, world).xyz;
- OUT.texCoord = IN.texCoord;
-
- OUT.n = mul(float4(IN.normal,0), worldIT).xyz;
- OUT.l = IN.normal;
- return OUT;
-}
-
-float4 fsMain(v2f IN): COLOR {
- float4 textureColor = tex2D(diffuseSampler, IN.texCoord);
- float3 normalDirection = normalize(IN.n);
- float3 viewDirection = normalize(cameraEye - IN.worldPosition.xyz);
- // Only diffuse light until we can get better than face normals.
- float4 litWorld = lit(dot(normalDirection.xyz, sunlightDirection), 0, 0);
- float4 total_color = ambientLightColor + litWorld.yyyy * sunlightColor;
-
- float3 light_direction = light0_location - IN.worldPosition.xyz;
- float attenuation = light0_color.a / length(light_direction);
- light_direction = normalize(light_direction);
- float4 litLight = lit(dot(normalDirection.xyz, light_direction), 0, 0);
- litLight.y *= clamp(attenuation * attenuation, 0, 1);
- total_color.rgb += litLight.yyy * light0_color.rgb;
-
- light_direction = light1_location - IN.worldPosition.xyz;
- attenuation = light1_color.a / length(light_direction);
- light_direction = normalize(light_direction);
- litLight = lit(dot(normalDirection.xyz, light_direction), 0, 0);
- litLight.y *= clamp(attenuation * attenuation, 0, 1);
- total_color.rgb += litLight.yyy * light1_color.rgb;
-
- light_direction = light2_location - IN.worldPosition.xyz;
- attenuation = light2_color.a / length(light_direction);
- light_direction = normalize(light_direction);
- litLight = lit(dot(normalDirection.xyz, light_direction), 0, 0);
- litLight.y *= clamp(attenuation * attenuation, 0, 1);
- total_color.rgb += litLight.yyy * light2_color.rgb;
-
- light_direction = light3_location - IN.worldPosition.xyz;
- attenuation = light3_color.a / length(light_direction);
- light_direction = normalize(light_direction);
- litLight = lit(dot(normalDirection.xyz, light_direction), 0, 0);
- litLight.y *= clamp(attenuation * attenuation, 0, 1);
- total_color.rgb += litLight.yyy * light3_color.rgb;
-
- textureColor.rgb += diffuse.rgb;
- total_color *= textureColor;
-
- // Fog
- float fog = saturate(pow(2.718, -.005 * (length(cameraEye - IN.worldPosition.xyz) - 300)));
- return lerp(fog_color, total_color, fog);
-}
-
-// #o3d VertexShaderEntryPoint vsMain
-// #o3d PixelShaderEntryPoint fsMain
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
diff --git a/o3d/samples/io/levels/all_actors.js b/o3d/samples/io/levels/all_actors.js
deleted file mode 100644
index e630949..0000000
--- a/o3d/samples/io/levels/all_actors.js
+++ /dev/null
@@ -1,383 +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.
- */
-
-/**
- * @fileoverview This file defines one level that our little game can run
- * inside of. This file was auto-generated by io.rb from a SketchUp model.
- */
-if (levels == undefined) {
- var levels = [];
-}
-
-levels.push({
- name: 'All Actors',
- colladaFile: 'all_actors.o3dtgz',
-
- platforms: [
- {'left': {'mapX': 0},
- 'z': 0, 'rotZ': 0.0,
- 'right': {'adjacentID': 1, 'mapX': 1151}},
- {'left': {'adjacentID': 0, 'mapX': 1151},
- 'z': 0, 'rotZ': 0.432710088213842,
- 'right': {'adjacentID': 2, 'mapX': 2588}},
- {'left': {'adjacentID': 1, 'mapX': 2588},
- 'z': 0, 'rotZ': 0.0,
- 'right': {'adjacentID': 3, 'mapX': 3159}},
- {'left': {'adjacentID': 2, 'mapX': 3159},
- 'z': 0, 'rotZ': 5.85194141379659,
- 'right': {'adjacentID': 4, 'mapX': 3474}},
- {'left': {'adjacentID': 3, 'mapX': 3474},
- 'z': 0, 'rotZ': 5.27977245408739,
- 'right': {'adjacentID': 5, 'mapX': 4178}},
- {'left': {'adjacentID': 4, 'mapX': 4178},
- 'z': 0, 'rotZ': 4.97548502987221,
- 'right': {'adjacentID': 6, 'mapX': 4798}},
- {'left': {'adjacentID': 5, 'mapX': 4798},
- 'z': 0, 'rotZ': 4.71238898038469,
- 'right': {'mapX': 6726}},
- {'left': {'mapX': 3960},
- 'z': 397, 'parentID': 4, 'rotZ': 5.27977245408739,
- 'right': {'mapX': 4051}},
- {'left': {'mapX': 1308},
- 'z': 45, 'parentID': 1, 'rotZ': 0.432710088213843,
- 'right': {'obstacleHeight': 15, 'mapX': 1563}},
- {'left': {'mapX': 312},
- 'z': 172, 'parentID': 0, 'rotZ': 0.0,
- 'right': {'mapX': 524}},
- {'left': {'mapX': 2915},
- 'z': 123, 'parentID': 2, 'rotZ': 0.0,
- 'right': {'obstacleHeight': 64, 'mapX': 3066}},
- {'left': {'obstacleHeight': 72, 'mapX': 525},
- 'z': 99, 'parentID': 0, 'rotZ': 0.0,
- 'right': {'mapX': 545}},
- {'left': {'mapX': 2117},
- 'z': 74, 'parentID': 1, 'rotZ': 0.432710088213842,
- 'right': {'obstacleHeight': 76, 'mapX': 2441}},
- {'left': {'mapX': 514},
- 'z': 365, 'parentID': 0, 'rotZ': 0.0,
- 'right': {'mapX': 576}},
- {'left': {'mapX': 1377},
- 'z': 115, 'parentID': 1, 'rotZ': 0.432710088213839,
- 'right': {'mapX': 1433}},
- {'left': {'mapX': 1828},
- 'z': 309, 'parentID': 1, 'rotZ': 0.432710088213842,
- 'right': {'mapX': 1897}},
- {'left': {'obstacleHeight': 37, 'mapX': 6233},
- 'z': 166, 'parentID': 6, 'rotZ': 4.71238898038469,
- 'right': {'mapX': 6327}},
- {'left': {'mapX': 714},
- 'z': 138, 'parentID': 0, 'rotZ': 0.0,
- 'right': {'mapX': 869}},
- {'left': {'mapX': 1505},
- 'z': 233, 'parentID': 1, 'rotZ': 0.432710088213845,
- 'right': {'mapX': 1563}},
- {'left': {'obstacleHeight': 43, 'mapX': 4338},
- 'z': 222, 'parentID': 5, 'rotZ': 4.97548502987221,
- 'right': {'mapX': 4502}},
- {'left': {'mapX': 593},
- 'z': 287, 'parentID': 0, 'rotZ': 0.0,
- 'right': {'obstacleHeight': 24, 'mapX': 717}},
- {'left': {'mapX': 3377},
- 'z': 326, 'parentID': 3, 'rotZ': 5.85194141379659,
- 'right': {'obstacleHeight': 144, 'mapX': 4466}},
- {'left': {'mapX': 3704},
- 'z': 194, 'parentID': 4, 'rotZ': 5.27977245408739,
- 'right': {'mapX': 3862}},
- {'left': {'mapX': 4087},
- 'z': 397, 'parentID': 4, 'rotZ': 5.27977245408739,
- 'right': {'mapX': 4161}},
- {'left': {'mapX': 2699},
- 'z': 351, 'parentID': 2, 'rotZ': 0.0,
- 'right': {'mapX': 2705}},
- {'left': {'obstacleHeight': 22, 'mapX': 545},
- 'z': 76, 'parentID': 0, 'rotZ': 0.0,
- 'right': {'obstacleHeight': 22, 'mapX': 636}},
- {'left': {'mapX': 1678},
- 'z': 309, 'parentID': 1, 'rotZ': 0.432710088213842,
- 'right': {'mapX': 1767}},
- {'left': {'mapX': 4208},
- 'z': 373, 'parentID': 5, 'rotZ': 4.97548502987219,
- 'right': {'mapX': 4232}},
- {'left': {'mapX': 2441},
- 'z': 150, 'parentID': 1, 'rotZ': 0.432710088213842,
- 'right': {'adjacentID': 29, 'mapX': 2587}},
- {'left': {'adjacentID': 28, 'mapX': 2587},
- 'z': 150, 'parentID': 2, 'rotZ': 0.0,
- 'right': {'obstacleHeight': 200, 'mapX': 2705}},
- {'left': {'mapX': 4208},
- 'z': 252, 'parentID': 5, 'rotZ': 4.97548502987219,
- 'right': {'obstacleHeight': 30, 'mapX': 4238}},
- {'left': {'obstacleHeight': 107, 'mapX': -24},
- 'z': 76, 'parentID': 0, 'rotZ': 0.0,
- 'right': {'obstacleHeight': 42, 'mapX': 265}},
- {'left': {'mapX': 4239},
- 'z': 282, 'parentID': 5, 'rotZ': 4.9754850298722,
- 'right': {'mapX': 4301}},
- {'left': {'obstacleHeight': 38, 'mapX': 1433},
- 'z': 76, 'parentID': 1, 'rotZ': 0.432710088213846,
- 'right': {'obstacleHeight': 34, 'mapX': 1477}},
- {'left': {'obstacleHeight': 17, 'mapX': 4302},
- 'z': 265, 'parentID': 5, 'rotZ': 4.97548502987222,
- 'right': {'mapX': 4338}},
- {'left': {'mapX': 1505},
- 'z': 148, 'parentID': 1, 'rotZ': 0.432710088213845,
- 'right': {'mapX': 1563}},
- {'left': {'obstacleHeight': 30, 'mapX': 2441},
- 'z': 43, 'parentID': 1, 'rotZ': 0.432710088213842,
- 'right': {'mapX': 2587}},
- {'left': {'mapX': 1478},
- 'z': 111, 'parentID': 1, 'rotZ': 0.432710088213837,
- 'right': {'obstacleHeight': 37, 'mapX': 1504}},
- {'left': {'mapX': 1927},
- 'z': 290, 'parentID': 1, 'rotZ': 0.432710088213842,
- 'right': {'mapX': 2193}},
- {'left': {'mapX': 2706},
- 'z': 351, 'parentID': 2, 'rotZ': 0.0,
- 'right': {'mapX': 2738}},
- {'left': {'obstacleHeight': 37, 'mapX': 6136},
- 'z': 203, 'parentID': 6, 'rotZ': 4.71238898038469,
- 'right': {'mapX': 6232}},
- {'left': {'mapX': 4843},
- 'z': 240, 'parentID': 6, 'rotZ': 4.71238898038469,
- 'right': {'mapX': 6135}},
- {'left': {'mapX': 3921},
- 'z': 222, 'parentID': 4, 'rotZ': 5.27977245408739,
- 'right': {'adjacentID': 43, 'mapX': 4177}},
- {'left': {'adjacentID': 42, 'mapX': 4177},
- 'z': 222, 'parentID': 5, 'rotZ': 4.97548502987222,
- 'right': {'obstacleHeight': 30, 'mapX': 4207}},
- {'left': {'mapX': 1478},
- 'z': 196, 'parentID': 1, 'rotZ': 0.432710088213837,
- 'right': {'mapX': 1504}},
- {'left': {'obstacleHeight': 61, 'mapX': 870},
- 'z': 76, 'parentID': 0, 'rotZ': 0.0,
- 'right': {'adjacentID': 46, 'mapX': 1151}},
- {'left': {'adjacentID': 45, 'mapX': 1151},
- 'z': 76, 'parentID': 1, 'rotZ': 0.432710088213843,
- 'right': {'obstacleHeight': 38, 'mapX': 1377}},
- {'left': {'mapX': 4665},
- 'z': 222, 'parentID': 5, 'rotZ': 4.97548502987221,
- 'right': {'mapX': 4739}},
- {'left': {'obstacleHeight': 72, 'mapX': 1563},
- 'z': 76, 'parentID': 1, 'rotZ': 0.432710088213843,
- 'right': {'mapX': 2018}},
- {'left': {'mapX': 4769},
- 'z': 222, 'parentID': 5, 'rotZ': 4.97548502987221,
- 'right': {'adjacentID': 50, 'mapX': 4798}},
- {'left': {'adjacentID': 49, 'mapX': 4798},
- 'z': 222, 'parentID': 6, 'rotZ': 4.71238898038469,
- 'right': {'obstacleHeight': 18, 'mapX': 4843}},
- {'left': {'mapX': 312},
- 'z': 234, 'parentID': 0, 'rotZ': 0.0,
- 'right': {'mapX': 362}},
- {'left': {'mapX': 265},
- 'z': 119, 'parentID': 0, 'rotZ': 0.0,
- 'right': {'obstacleHeight': 53, 'mapX': 312}},
- {'left': {'mapX': 2642},
- 'z': 326, 'parentID': 2, 'rotZ': 0.0,
- 'right': {'obstacleHeight': 25, 'mapX': 2699}},
- {'left': {'obstacleHeight': 37, 'mapX': 6327},
- 'z': 129, 'parentID': 6, 'rotZ': 4.71238898038469,
- 'right': {'mapX': 6596}},
- {'left': {'obstacleHeight': 96, 'mapX': 6596},
- 'z': 32, 'parentID': 6, 'rotZ': 4.71238898038469,
- 'right': {'mapX': 6726}},
- {'left': {'mapX': 1352},
- 'z': 155, 'parentID': 1, 'rotZ': 0.432710088213843,
- 'right': {'mapX': 1388}},
- {'left': {'mapX': 4551},
- 'z': 222, 'parentID': 5, 'rotZ': 4.97548502987221,
- 'right': {'mapX': 4595}},
- {'left': {'mapX': 636},
- 'z': 98, 'parentID': 0, 'rotZ': 0.0,
- 'right': {'obstacleHeight': 39, 'mapX': 714}},
- {'left': {'obstacleHeight': 227, 'mapX': 2738},
- 'z': 123, 'parentID': 2, 'rotZ': 0.0,
- 'right': {'mapX': 2762}},
- {'left': {'mapX': 2642},
- 'z': 247, 'parentID': 2, 'rotZ': 0.0,
- 'right': {'obstacleHeight': 78, 'mapX': 2701}},
- {'left': {'mapX': 4401},
- 'z': 394, 'parentID': 3, 'rotZ': 5.85194141379659,
- 'right': {'obstacleHeight': 161, 'mapX': 4463}},
- {'left': {'mapX': 1561},
- 'z': 309, 'parentID': 1, 'rotZ': 0.432710088213842,
- 'right': {'mapX': 1623}},
- {'left': {'mapX': 3248},
- 'z': 222, 'parentID': 3, 'rotZ': 5.85194141379659,
- 'right': {'adjacentID': 64, 'mapX': 3473}},
- {'left': {'adjacentID': 63, 'mapX': 3473},
- 'z': 222, 'parentID': 4, 'rotZ': 5.2797724540874,
- 'right': {'mapX': 3607}},
- {'left': {'mapX': 400},
- 'z': 270, 'parentID': 0, 'rotZ': 0.0,
- 'right': {'mapX': 524}},
- {'left': {'mapX': 3066},
- 'z': 188, 'parentID': 2, 'rotZ': 0.0,
- 'right': {'adjacentID': 67, 'mapX': 3159}},
- {'left': {'adjacentID': 66, 'mapX': 3159},
- 'z': 188, 'parentID': 3, 'rotZ': 5.85194141379659,
- 'right': {'obstacleHeight': 33, 'mapX': 3248}}],
- actors: [
- new Avatar({ name: 'Avatar1', colladaID: 'Avatar1',
- x: 23, y: 0, z: 77, mapX: 24, rotZ: 0.0628318530722379,
-
- platformID: 31}),
- new Spikem({ name: 'Spikem1', colladaID: 'Spikem1',
- x: 186, y: -1, z: 76, mapX: 186, rotZ: 0.0,
- platformID: 31}),
- new Spikem({ name: 'Spikem2', colladaID: 'Spikem2',
- x: 763, y: -2, z: 144, mapX: 762, rotZ: 0.0,
- platformID: 17}),
- new Spikem({ name: 'Spikem3', colladaID: 'Spikem3',
- x: 437, y: -1, z: 178, mapX: 436, rotZ: 0.0,
- platformID: 9}),
- new Spikem({ name: 'Spikem4', colladaID: 'Spikem4',
- x: 1819, y: 311, z: 80, mapX: 1886, rotZ: 0.0,
- platformID: 48}),
- new Spikem({ name: 'Spikem5', colladaID: 'Spikem5',
- x: 2861, y: 602, z: 130, mapX: 2992, rotZ: 0.0,
- platformID: 10}),
- new Spikem({ name: 'Spikem6', colladaID: 'Spikem6',
- x: 3830, y: -631, z: 228, mapX: 4704, rotZ: 0.0,
- platformID: 47}),
- new Spikem({ name: 'Spikem7', colladaID: 'Spikem7',
- x: 3854, y: -1682, z: 246, mapX: 5757, rotZ: 0.0,
- platformID: 41}),
- new Spikem({ name: 'Spikem8', colladaID: 'Spikem8',
- x: 3796, y: -507, z: 228, mapX: 4575, rotZ: 0.0,
- platformID: 57}),
- new Spikem({ name: 'Spikem9', colladaID: 'Spikem9',
- x: 3765, y: -390, z: 228, mapX: 4454, rotZ: 0.0,
- platformID: 19}),
- new Spikem({ name: 'Spikem10', colladaID: 'Spikem10',
- x: 3848, y: -2623, z: 22, mapX: 6699, rotZ: 0.0,
- platformID: 55}),
- new Arrow({ name: 'Arrow1', colladaID: 'Arrow1',
- x: 40, y: 3, z: 99, mapX: 40, rotZ: 0.0,
- platformID: 31}),
- new Arrow({ name: 'Arrow2', colladaID: 'Arrow2',
- x: 37, y: 0, z: 76, mapX: 37, rotZ: 0.0,
- platformID: 31}),
- new Arrow({ name: 'Arrow3', colladaID: 'Arrow3',
- x: 40, y: 3, z: 86, mapX: 40, rotZ: 0.0,
- platformID: 31}),
- new HorizontalPad({ name: 'HorizontalPad1', colladaID: 'HorizontalPad1',
- x: 1692, y: 247, z: 312, mapX: 1745, rotZ: -0.411897703470668,
- platformID: 26}),
- new HorizontalPad({ name: 'HorizontalPad2', colladaID: 'HorizontalPad2',
- x: 1926, y: 355, z: 292, mapX: 2003, rotZ: -0.411897703470668,
- platformID: 38}),
- new Coin({ name: 'Coin1', colladaID: 'Coin1',
- x: 342, y: -2, z: 247, mapX: 341, rotZ: 0.0,
- platformID: 51}),
- new Coin({ name: 'Coin2', colladaID: 'Coin2',
- x: 424, y: -2, z: 299, mapX: 423, rotZ: 0.0,
- platformID: 65}),
- new Coin({ name: 'Coin3', colladaID: 'Coin3',
- x: 461, y: -2, z: 303, mapX: 461, rotZ: 0.0,
- platformID: 65}),
- new Coin({ name: 'Coin4', colladaID: 'Coin4',
- x: 496, y: -2, z: 303, mapX: 495, rotZ: 0.0,
- platformID: 65}),
- new Coin({ name: 'Coin5', colladaID: 'Coin5',
- x: 1426, y: 121, z: 83, mapX: 1450, rotZ: 0.0,
- platformID: 33}),
- new Coin({ name: 'Coin6', colladaID: 'Coin6',
- x: 1659, y: 232, z: 344, mapX: 1709, rotZ: 0.0,
- platformID: 26}),
- new Coin({ name: 'Coin7', colladaID: 'Coin7',
- x: 1697, y: 254, z: 344, mapX: 1753, rotZ: 0.0,
- platformID: 26}),
- new Coin({ name: 'Coin8', colladaID: 'Coin8',
- x: 1971, y: 382, z: 304, mapX: 2055, rotZ: 0.0,
- platformID: 38}),
- new Coin({ name: 'Coin9', colladaID: 'Coin9',
- x: 2053, y: 419, z: 304, mapX: 2145, rotZ: 0.0,
- platformID: 38}),
- new Coin({ name: 'Coin10', colladaID: 'Coin10',
- x: 2015, y: 402, z: 305, mapX: 2103, rotZ: 0.0,
- platformID: 38}),
- new Coin({ name: 'Coin11', colladaID: 'Coin11',
- x: 2184, y: 475, z: 229, mapX: 2287, rotZ: 0.0,
- platformID: 38}),
- new Coin({ name: 'Coin12', colladaID: 'Coin12',
- x: 2184, y: 475, z: 256, mapX: 2287, rotZ: 0.0,
- platformID: 38}),
- new Coin({ name: 'Coin13', colladaID: 'Coin13',
- x: 2184, y: 475, z: 307, mapX: 2287, rotZ: 0.0,
- platformID: 38}),
- new Coin({ name: 'Coin14', colladaID: 'Coin14',
- x: 2184, y: 475, z: 282, mapX: 2287, rotZ: 0.0,
- platformID: 38}),
- new Coin({ name: 'Coin15', colladaID: 'Coin15',
- x: 546, y: -2, z: 422, mapX: 545, rotZ: 0.0,
- platformID: 13}),
- new Coin({ name: 'Coin16', colladaID: 'Coin16',
- x: 2590, y: 607, z: 371, mapX: 2721, rotZ: 0.0,
- platformID: 39}),
- new Coin({ name: 'Coin17', colladaID: 'Coin17',
- x: 2737, y: 606, z: 246, mapX: 2961, rotZ: 0.0,
- platformID: 10}),
- new Coin({ name: 'Coin18', colladaID: 'Coin18',
- x: 2737, y: 606, z: 273, mapX: 2868, rotZ: 0.0,
- platformID: 39}),
- new Coin({ name: 'Coin19', colladaID: 'Coin19',
- x: 3599, y: 21, z: 433, mapX: 4005, rotZ: 0.0,
- platformID: 7}),
- new Coin({ name: 'Coin20', colladaID: 'Coin20',
- x: 3665, y: -78, z: 429, mapX: 4125, rotZ: 0.0,
- platformID: 23}),
- new Coin({ name: 'Coin21', colladaID: 'Coin21',
- x: 4156, y: 77, z: 423, mapX: 4402, rotZ: 0.0,
- platformID: 61}),
- new Coin({ name: 'Coin22', colladaID: 'Coin22',
- x: 4182, y: 71, z: 418, mapX: 4428, rotZ: 0.0,
- platformID: 61}),
- new Coin({ name: 'Coin23', colladaID: 'Coin23',
- x: 4182, y: 71, z: 447, mapX: 4428, rotZ: 0.0,
- platformID: 61}),
- new Coin({ name: 'Coin24', colladaID: 'Coin24',
- x: 4156, y: 77, z: 452, mapX: 4402, rotZ: 0.0,
- platformID: 61}),
- new Coin({ name: 'Coin25', colladaID: 'Coin25',
- x: 4156, y: 77, z: 482, mapX: 4402, rotZ: 0.0,
- platformID: 61}),
- new Coin({ name: 'Coin26', colladaID: 'Coin26',
- x: 4182, y: 71, z: 477, mapX: 4428, rotZ: 0.0,
- platformID: 61}),
- new VerticalPad({ name: 'VerticalPad1', colladaID: 'VerticalPad1',
- x: 2663, y: 603, z: 221, mapX: 2794, rotZ: 0.0,
- platformID: 60}),
- new VerticalPad({ name: 'VerticalPad2', colladaID: 'VerticalPad2',
- x: 2799, y: 603, z: 152, mapX: 2930, rotZ: 0.0,
- platformID: 10})]
-});
diff --git a/o3d/samples/io/levels/all_actors.skp b/o3d/samples/io/levels/all_actors.skp
deleted file mode 100644
index 99e97ee..0000000
--- a/o3d/samples/io/levels/all_actors.skp
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/levels/map1.js b/o3d/samples/io/levels/map1.js
deleted file mode 100644
index 2bd7eee..0000000
--- a/o3d/samples/io/levels/map1.js
+++ /dev/null
@@ -1,156 +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.
- */
-
-/**
- * @fileoverview This file defines one level that our little game can run
- * inside of. This file was auto-generated by io.rb from a SketchUp model.
- */
-if (levels == undefined) {
- var levels = [];
-}
-
-levels.push({
- name: 'Chapter One',
- colladaFile: 'map1.o3dtgz',
-
- platforms: [
- {'left': {'mapX': 0},
- 'z': 0.0, 'rotZ': 0.0,
- 'right': {'adjacentID': 1, 'mapX': 99.9999999999998}},
- {'left': {'adjacentID': 0, 'mapX': 99.9999999999998},
- 'z': 0.0, 'rotZ': 0.785398163397443,
- 'right': {'adjacentID': 2, 'mapX': 399.999999999999}},
- {'left': {'adjacentID': 1, 'mapX': 399.999999999999},
- 'z': 0.0, 'rotZ': 1.5707963267949,
- 'right': {'adjacentID': 3, 'mapX': 561.617965644037}},
- {'left': {'adjacentID': 2, 'mapX': 561.617965644037},
- 'z': 0.0, 'rotZ': 0.0,
- 'right': {'adjacentID': 4, 'mapX': 812.03592686014}},
- {'left': {'adjacentID': 3, 'mapX': 812.03592686014},
- 'z': 0.0, 'rotZ': 5.49970875351729,
- 'right': {'adjacentID': 5, 'mapX': 922.215597985646}},
- {'left': {'adjacentID': 4, 'mapX': 922.215597985646},
- 'z': 0.0, 'rotZ': 4.716232199855,
- 'right': {'adjacentID': 6, 'mapX': 1105.95801639536}},
- {'left': {'adjacentID': 5, 'mapX': 1105.95801639536},
- 'z': 0.0, 'rotZ': 4.04298946008257,
- 'right': {'adjacentID': 7, 'mapX': 1208.29233370876}},
- {'left': {'adjacentID': 6, 'mapX': 1208.29233370876},
- 'z': 0.0, 'rotZ': 4.71238898038469,
- 'right': {'adjacentID': 8, 'mapX': 1367.79233370876}},
- {'left': {'adjacentID': 7, 'mapX': 1367.79233370876},
- 'z': 0.0, 'rotZ': 0.0,
- 'right': {'mapX': 1748.54233370876}},
- {'left': {'mapX': 672.461706167729},
- 'z': 133.25, 'parentID': 3, 'rotZ': 0.0,
- 'right': {'mapX': 725.904505439235}},
- {'left': {'mapX': 70.3557338817432},
- 'z': 58.5, 'parentID': 0, 'rotZ': 0.0,
- 'right': {'adjacentID': 11, 'mapX': 99.9999999999998}},
- {'left': {'adjacentID': 10, 'mapX': 99.9999999999998},
- 'z': 58.5, 'parentID': 1, 'rotZ': 0.785398163397443,
- 'right': {'mapX': 177.235601196938}},
- {'left': {'obstacleHeight': 32.0, 'mapX': 832.589734479398},
- 'z': 65.5, 'parentID': 4, 'rotZ': 5.49970875351729,
- 'right': {'adjacentID': 13, 'mapX': 922.215597985645}},
- {'left': {'adjacentID': 12, 'mapX': 922.215597985645},
- 'z': 65.5, 'parentID': 5, 'rotZ': 4.716232199855,
- 'right': {'mapX': 1025.68972725654}},
- {'left': {'mapX': 1176.12562519989},
- 'z': 133.25, 'parentID': 6, 'rotZ': 4.04298946008257,
- 'right': {'adjacentID': 15, 'mapX': 1208.29233370876}},
- {'left': {'adjacentID': 14, 'mapX': 1208.29233370876},
- 'z': 133.25, 'parentID': 7, 'rotZ': 4.71238898038469,
- 'right': {'adjacentID': 16, 'mapX': 1367.79233370876}},
- {'left': {'adjacentID': 15, 'mapX': 1367.79233370876},
- 'z': 133.25, 'parentID': 8, 'rotZ': 0.0,
- 'right': {'mapX': 1748.54233370876}},
- {'left': {'obstacleHeight': 13.75, 'mapX': -13.0628855147159},
- 'z': 69.5, 'parentID': 0, 'rotZ': 0.0,
- 'right': {'mapX': 31.2499999999998}},
- {'left': {'mapX': 812.03592686014},
- 'z': 47.0, 'parentID': 4, 'rotZ': 5.49970875351729,
- 'right': {'mapX': 922.215597985646}},
- {'left': {'mapX': 177.235601196938},
- 'z': 75.5, 'parentID': 1, 'rotZ': 0.785398163397443,
- 'right': {'obstacleHeight': 28.25, 'mapX': 254.471202393877}},
- {'left': {'mapX': 757.192725889269},
- 'z': 97.5, 'parentID': 3, 'rotZ': 0.0,
- 'right': {'adjacentID': 21, 'mapX': 812.03592686014}},
- {'left': {'adjacentID': 20, 'mapX': 812.03592686014},
- 'z': 97.5, 'parentID': 4, 'rotZ': 5.49970875351729,
- 'right': {'mapX': 832.589734479398}},
- {'left': {'mapX': 254.471202393877},
- 'z': 103.75, 'parentID': 1, 'rotZ': 0.785398163397442,
- 'right': {'mapX': 331.706803590815}},
- {'left': {'mapX': 1091.9536790532},
- 'z': 60.5, 'parentID': 5, 'rotZ': 4.71623219985501,
- 'right': {'adjacentID': 24, 'mapX': 1105.95801639536}},
- {'left': {'adjacentID': 23, 'mapX': 1105.95801639536},
- 'z': 60.5, 'parentID': 6, 'rotZ': 4.04298946008257,
- 'right': {'obstacleHeight': 31.5, 'mapX': 1143.95891669101}},
- {'left': {'mapX': 399.999999999999},
- 'z': 133.25, 'parentID': 2, 'rotZ': 1.5707963267949,
- 'right': {'adjacentID': 26, 'mapX': 561.617965644037}},
- {'left': {'adjacentID': 25, 'mapX': 561.617965644037},
- 'z': 133.25, 'parentID': 3, 'rotZ': 0.0,
- 'right': {'mapX': 621.461706167729}},
- {'left': {'obstacleHeight': 74.25, 'mapX': 621.461706167729},
- 'z': 59.0, 'parentID': 3, 'rotZ': 0.0,
- 'right': {'obstacleHeight': 74.25, 'mapX': 672.461706167729}},
- {'left': {'mapX': 1143.95891669101},
- 'z': 92.0, 'parentID': 6, 'rotZ': 4.04298946008257,
- 'right': {'mapX': 1176.12562519989}},
- {'left': {'obstacleHeight': 21.25, 'mapX': 331.706803590815},
- 'z': 82.5, 'parentID': 1, 'rotZ': 0.785398163397442,
- 'right': {'mapX': 384.382894323691}}],
- actors: [
- new Avatar({
- name: 'Avatar1', colladaID: 'Avatar1',
- x: 8.25548871083476, y: -10.107499431384, z: 70.0761619683742,
- mapX: 8.25548871083476, rotZ: 0.0628318530722379, platformID: 17}),
- new HorizontalPad({
- name: 'HorizontalPad1', colladaID: 'HorizontalPad1',
- x: 69.9999999999999, y: 0.0, z: 0.0,
- mapX: 69.9999999999999, rotZ: 0.0, platformID: 0}),
- new Arrow({
- name: 'Arrow1', colladaID: 'Arrow1',
- x: 24.8151490181853, y: -1.89670669278537, z: 68.75,
- mapX: 24.8151490181853, rotZ: 0.0, platformID: 17}),
- new Arrow({
- name: 'Arrow2', colladaID: 'Arrow2',
- x: 24.8151490181853, y: -1.89670669278537, z: 79.25,
- mapX: 24.8151490181853, rotZ: 0.0, platformID: 17}),
- new Arrow({
- name: 'Arrow3', colladaID: 'Arrow3',
- x: 24.8151490181853, y: -1.89670669278537, z: 92,
- mapX: 24.8151490181853, rotZ: 0.0, platformID: 17})]
-});
diff --git a/o3d/samples/io/levels/map1.skp b/o3d/samples/io/levels/map1.skp
deleted file mode 100644
index 8014334..0000000
--- a/o3d/samples/io/levels/map1.skp
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/levels/starter_level.skp b/o3d/samples/io/levels/starter_level.skp
deleted file mode 100644
index 31869f0..0000000
--- a/o3d/samples/io/levels/starter_level.skp
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/sound/_MISS.mp3 b/o3d/samples/io/sound/_MISS.mp3
deleted file mode 100644
index 7acfc80..0000000
--- a/o3d/samples/io/sound/_MISS.mp3
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/sound/_PUNCH.mp3 b/o3d/samples/io/sound/_PUNCH.mp3
deleted file mode 100644
index abb7277..0000000
--- a/o3d/samples/io/sound/_PUNCH.mp3
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/sound/_SMASH.mp3 b/o3d/samples/io/sound/_SMASH.mp3
deleted file mode 100644
index c655a11..0000000
--- a/o3d/samples/io/sound/_SMASH.mp3
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/sound/_woosh.mp3 b/o3d/samples/io/sound/_woosh.mp3
deleted file mode 100644
index 5687be2..0000000
--- a/o3d/samples/io/sound/_woosh.mp3
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/sound/ah.mp3 b/o3d/samples/io/sound/ah.mp3
deleted file mode 100644
index ff40207..0000000
--- a/o3d/samples/io/sound/ah.mp3
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/sound/arrow.mp3 b/o3d/samples/io/sound/arrow.mp3
deleted file mode 100644
index e106d668..0000000
--- a/o3d/samples/io/sound/arrow.mp3
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/sound/coin_3.mp3 b/o3d/samples/io/sound/coin_3.mp3
deleted file mode 100644
index d8f3ff5..0000000
--- a/o3d/samples/io/sound/coin_3.mp3
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/sound/music.mp3 b/o3d/samples/io/sound/music.mp3
deleted file mode 100644
index 653d191..0000000
--- a/o3d/samples/io/sound/music.mp3
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/sound/page.mp3 b/o3d/samples/io/sound/page.mp3
deleted file mode 100644
index f2c9a08..0000000
--- a/o3d/samples/io/sound/page.mp3
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/sound/soundplayer.js b/o3d/samples/io/sound/soundplayer.js
deleted file mode 100644
index 95c0470..0000000
--- a/o3d/samples/io/sound/soundplayer.js
+++ /dev/null
@@ -1,147 +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.
- */
-
-
-/**
- * @fileoverview This file defines a SoundPlayer object that can be used to
- * play .mp3 files via a tiny soundplayer.swf file.
- *
- * Here's some example javascript for how you'd use this thing:
- * var soundPlayer = new SoundPlayer();
- * soundPlayer.play('songToPlayOnce.mp3')
- * soundPlayer.play('soundToLoopForeverAt50PercentVolume.mp3',50,999)
- * soundPlayer.play('sfxToPlayAsEvent.mp3',100,0,true)
- * soundPlayer.setVolume('soundToTurnOff.mp3',0);
- * soundPlayer.setGlobalVolume(20);
- *
- */
-
-// Write a DIV to the screen that we can later use to embed our flash movie.
- var html = '<div style="position:absolute; top:-1000px; left:-1000px; z-index: 0;width: 200px; height: 200px; ">'
- html = '<OBJECT style="position:absolute; top:-1000px; left:-1000px;" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" '
- html += 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash'
- html += '/swflash.cab#version=6,0,0,0" WIDTH="200" HEIGHT="200" '
- html += 'id="soundPlayer" ALIGN=""> '
- html += '<PARAM NAME=movie VALUE="sound/soundplayer.swf"> '
- html += '<PARAM NAME=quality VALUE=high> '
- html += '<PARAM NAME=allowScriptAccess VALUE=always> '
- html += '<EMBED src="sound/soundplayer.swf" quality=high WIDTH="200" HEIGHT="200" '
- html += 'NAME="soundPlayer" swLiveConnect=true ALIGN="" '
- html += 'TYPE="application/x-shockwave-flash" allowScriptAccess="always" '
- html += 'PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">'
- html += '</EMBED></OBJECT></div>';
- document.write(html);
-
-/**
- * Constructor for our SoundPlayer object.
- */
-function SoundPlayer() {
- // TODO: Make this more generic so it loads at the author's
- // request rather than at include time.
-}
-
-/**
- * This is a helper function to simplify code throughout. Returns a default
- * value if the first is empty.
- * @param {Object} val1 Value to check for emptiness
- * @param {Object} val2 Value to return if va1 is empty
- * @return {Object} One of the above.
- */
-SoundPlayer.prototype.defaultIfEmpty = function(val1,val2) {
- if (val1 == undefined) {
- return val2;
- } else {
- return val1;
- }
-}
-
-/**
- * This is the way to send action calls to the flash plugin. In this case,
- * a string containing our action script that we want to execute. (Note that
- * flash doesn't have a true "eval" function, so this isn't a security hole.)
- * @param {string} callStr The command to have flash execute.
- */
-SoundPlayer.prototype.makeActionScriptCall = function(callStr) {
- try {
- window.document['soundPlayer'].SetVariable('actionScriptCall', callStr);
- } catch (ex) {
- // Catch the exception so that any problems with the sound player don't
- // derail the whle game.
- }
-}
-
-// TODO: Need to clean up these function comments to follow
-// jsdoc standard. Also need to clean up for readability.
-
-/**
- * SoundPlayer.play() : Call this guy to play a sound or music file.
- *
- * fileURL : a url to any mp3 you want to play (required)
- * volumeLevel : a number from 0 (silent) to 100 (optional, defaults to 100)
- * loopCount : How many times to loop the sound (optional, defaults to 0)
- * isNewTrack : Boolean. If true, then a new "track" will be created,
- * allowing you to layer as many sounds as you like
- */
-SoundPlayer.prototype.play = function(fileURL,volumeLevel,loopCount,isNewTrack) {
- volumeLevel = this.defaultIfEmpty(volumeLevel,100);
- loopCount = this.defaultIfEmpty(loopCount,0);
- isNewTrack = this.defaultIfEmpty(isNewTrack,false);
- var actionScriptCall = 'play('+fileURL+',' + volumeLevel + ',' +
- loopCount + ',' + isNewTrack + ')';
- this.makeActionScriptCall(actionScriptCall);
-}
-
-/**
- * SoundPlayer.setVolume() : Call this guy to change the volume on a sound.
- *
- * fileURL : a url to any mp3 or wav file you want to change the volume on
- * volumeLevel : a number from 0 (silent) to 100 (loud)
- */
-SoundPlayer.prototype.setVolume = function(fileURL,volumeLevel,fadeTime) {
- var actionScriptCall = 'setVolume('+fileURL+',' + volumeLevel + ')';
- this.makeActionScriptCall(actionScriptCall);
-}
-
-/**
- * SoundPlayer.setGlobalVolume() : Call this guy to change the global
- * volume on a sound. The global volume "multiplies" each sound's volume,
- * so if your sound is playing at 100% and your global is at 50%, then
- * your sounds will be half as loud.
- *
- * volumeLevel : a number from 0 (silent) to 100 (loud)
- */
-SoundPlayer.prototype.setGlobalVolume = function(volumeLevel) {
- var actionScriptCall = 'setGlobalVolume(' + volumeLevel + ')';
- this.makeActionScriptCall(actionScriptCall);
-}
-
-// Create a global variable for this application to use.
-var soundPlayer = new SoundPlayer();
diff --git a/o3d/samples/io/sound/soundplayer.swf b/o3d/samples/io/sound/soundplayer.swf
deleted file mode 100644
index 4a1f0e0..0000000
--- a/o3d/samples/io/sound/soundplayer.swf
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/sound/step1.mp3 b/o3d/samples/io/sound/step1.mp3
deleted file mode 100644
index 8419591..0000000
--- a/o3d/samples/io/sound/step1.mp3
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/sound/step2.mp3 b/o3d/samples/io/sound/step2.mp3
deleted file mode 100644
index 02895f0..0000000
--- a/o3d/samples/io/sound/step2.mp3
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/sound/step3.mp3 b/o3d/samples/io/sound/step3.mp3
deleted file mode 100644
index 8d7cf61..0000000
--- a/o3d/samples/io/sound/step3.mp3
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/sound/ug.mp3 b/o3d/samples/io/sound/ug.mp3
deleted file mode 100644
index 7297175..0000000
--- a/o3d/samples/io/sound/ug.mp3
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/ui/Thumbs.db b/o3d/samples/io/ui/Thumbs.db
deleted file mode 100644
index 1bb8f7a..0000000
--- a/o3d/samples/io/ui/Thumbs.db
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/ui/bgtile.jpg b/o3d/samples/io/ui/bgtile.jpg
deleted file mode 100644
index d6278f1..0000000
--- a/o3d/samples/io/ui/bgtile.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/ui/book_capbottom.jpg b/o3d/samples/io/ui/book_capbottom.jpg
deleted file mode 100644
index ef07486..0000000
--- a/o3d/samples/io/ui/book_capbottom.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/ui/book_capleft.jpg b/o3d/samples/io/ui/book_capleft.jpg
deleted file mode 100644
index eae6cd9..0000000
--- a/o3d/samples/io/ui/book_capleft.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/ui/book_capright.jpg b/o3d/samples/io/ui/book_capright.jpg
deleted file mode 100644
index 0d7bfad..0000000
--- a/o3d/samples/io/ui/book_capright.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/ui/book_captop.jpg b/o3d/samples/io/ui/book_captop.jpg
deleted file mode 100644
index a1e2705..0000000
--- a/o3d/samples/io/ui/book_captop.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/ui/book_cover.jpg b/o3d/samples/io/ui/book_cover.jpg
deleted file mode 100644
index eaf42a0..0000000
--- a/o3d/samples/io/ui/book_cover.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/ui/book_innercover.jpg b/o3d/samples/io/ui/book_innercover.jpg
deleted file mode 100644
index 7eca9e8..0000000
--- a/o3d/samples/io/ui/book_innercover.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/ui/book_page1.jpg b/o3d/samples/io/ui/book_page1.jpg
deleted file mode 100644
index 3b62f53e..0000000
--- a/o3d/samples/io/ui/book_page1.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/ui/book_page2.jpg b/o3d/samples/io/ui/book_page2.jpg
deleted file mode 100644
index a0bfa1f..0000000
--- a/o3d/samples/io/ui/book_page2.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/ui/book_page3.jpg b/o3d/samples/io/ui/book_page3.jpg
deleted file mode 100644
index 740e8b9..0000000
--- a/o3d/samples/io/ui/book_page3.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/ui/book_pageblank.jpg b/o3d/samples/io/ui/book_pageblank.jpg
deleted file mode 100644
index d266853..0000000
--- a/o3d/samples/io/ui/book_pageblank.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/ui/covershadow.png b/o3d/samples/io/ui/covershadow.png
deleted file mode 100644
index 2409a78..0000000
--- a/o3d/samples/io/ui/covershadow.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/ui/io.css b/o3d/samples/io/ui/io.css
deleted file mode 100644
index 3f2ef61..0000000
--- a/o3d/samples/io/ui/io.css
+++ /dev/null
@@ -1,181 +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.
- */
-
-
-BODY {
- overflow: hidden;
- background-image: url(../ui/bgtile.jpg);
- padding: 0px;
- margin: 0px;
- color: white;
-}
-#content {
- visibility: hidden; /* for now */
- position: absolute;
- color: black;
- text-align: center;
- padding-top: 50px;
- font-size: 25px;
- width: 951px;
- height: 500px;
-}
-#container {
- position: absolute;
- text-align: center;
- width: 882px;
- height: 549px;
- margin-left: 37px;
-}
-#footer {
- position: absolute;
- bottom: 0px;
- height: 70px;
- width: 100%;
- text-align: center;
-}
-#whole-page {
- position: absolute;
- width: 100%;
- height: 100%;
- line-height: 100%;
- border: 1px solid red;
-}
-#table-main {
- position: absolute;
- width: 100%;
- height: 100%;
-}
-#table-middle {
- padding: 0px;
- margin: 0px;
- border: 0px;
-}
-#book-left {
- background-image: url(../ui/scrollwork.gif);
- background-repeat: repeat-x;
- background-position: right 40px;
- text-align: right;
- vertical-align: top;
-}
-#book-center {
- width: 988px;
- height: 662px;
-}
-#book-right {
- background-image: url(../ui/scrollwork.gif);
- background-repeat: repeat-x;
- background-position: left 40px;
-}
-#book-capleft {
- position: absolute;
-}
-#book-captop {
- position: relative;
-}
-#cover-div {
- position: absolute;
- z-index: 100;
- padding-top: 15px;
- margin: 0px;
-}
-#cover-seam {
- position: absolute;
- z-index: 1000;
- border-left: 1px solid #222222;
- height: 575px;
-}
-#cover {
- width: 975px;
- height: 600px;
- position: absolute;
- z-index: 100;
- cursor: pointer;
- border: 0px;
-}
-#page1 {
- position: absolute;
- z-index: 90;
- cursor: pointer;
- border: 0px;
-}
-#page2 {
- position: absolute;
- z-index: 80;
- cursor: pointer;
-}
-#page3 {
- position: absolute;
- z-index: 70;
- cursor: pointer;
-}
-#cover-shadow {
- position: absolute;
- z-index: 99;
-}
-#innercover-div {
- padding-top: 15px;
- width: 20px;
- height: 600px;
- overflow: hidden;
- text-align: right;
- float: right;
-}
-
-#innercover {
- width: 0px;
- height: 600px;
- float: right;
-}
-
-.levellink {
- cursor: pointer;
- text-decoration: underline;
-}
-
-
-#fps {
- font-family: sans-serif;
- text-align: left;
- padding-top: 15px;
- width: 250px;
- float: left;
- padding-left: 25px;
- color: #B87333;
-}
-#output {
- font-family: sans-serif;
- text-align: right;
- padding-top: 15px;
- width: 250px;
- float: right;
- padding-right: 25px;
- color: #222222;
-}
diff --git a/o3d/samples/io/ui/logo.gif b/o3d/samples/io/ui/logo.gif
deleted file mode 100644
index 7c9bae3..0000000
--- a/o3d/samples/io/ui/logo.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/io/ui/scrollwork.gif b/o3d/samples/io/ui/scrollwork.gif
deleted file mode 100644
index 55e2476..0000000
--- a/o3d/samples/io/ui/scrollwork.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/juggler.html b/o3d/samples/juggler.html
deleted file mode 100644
index dd6fc77..0000000
--- a/o3d/samples/juggler.html
+++ /dev/null
@@ -1,463 +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.
--->
-
-<!--
-O3D Juggler
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html style="width: 100%; height: 100%;">
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
- Juggler Shader
-</title>
-
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-
-// Events
-// Run the init() function once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_o3dElement;
-var g_viewInfo;
-var g_pack;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-var g_transform;
-var g_clock = 0.0;
-var g_timeMult = 1; // amount to multiply elapsed time by.
- // Used to make the animation run faster or slower.
-var g_finished = false; // for selenium testing
-var g_thetaParam;
-var g_numParam;
-var g_numBalls; // Must be either 3, 5, 7, or 9 for now.
-var g_speedScale; // Used to make higher numbers of balls animate faster.
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and creates the square.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Create a g_pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot,
- [0, 0, 0, 1]);
-
- var effect = g_pack.createObject('Effect');
- effect.loadFromFXString(document.getElementById('shader').value);
-
- // Create a Material for the effect.
- var myMaterial = g_pack.createObject('Material');
-
- // Apply our effect to this material.
- myMaterial.effect = effect;
-
- // Set the material's drawList for opaque objects.
- myMaterial.drawList = g_viewInfo.performanceDrawList;
-
- // Create the params the effect needs on the material.
- effect.createUniformParameters(myMaterial);
-
- // Create a square.
- var myShape = o3djs.primitives.createPlane(g_pack, myMaterial,
- 1, 1, 1, 1);
-
- // Set up the individual parameters in our effect file.
- g_thetaParam = myMaterial.getParam('theta');
- g_thetaParam.value = 0;
- g_numParam = myMaterial.getParam('num');
- updateNum();
-
- // Set the position of the camera.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 1, 0], //eye
- [0, 0, 0], //target
- [0, 0, -1]); //up
-
- // Generate the projection matrix based
- // on the g_o3d plugin size by calling resize().
- resize();
-
- // Now attach the square to the root of the transform graph.
- g_client.root.addShape(myShape);
-
- toggleRenderCallback();
-
- g_finished = true; // for selenium testing.
-}
-
-function updateNum() {
- var group = document.the_form.radio_group;
- for (var i = 0; i < group.length; ++i) {
- if (group[i].checked) {
- setNumBalls(parseInt(group[i].value));
- }
- }
-}
-
-function toggleRenderCallback() {
- var box = document.the_form.check_box;
- if (box.checked) {
- g_client.setRenderCallback(onrender);
- } else {
- g_client.clearRenderCallback();
- }
-}
-
-function setNumBalls(num) {
- g_numBalls = num;
- g_numParam.value = g_numBalls;
- g_speedScale = Math.sqrt(g_numBalls) * 5;
-}
-
-function onrender(render_event) {
- g_clock += render_event.elapsedTime * g_timeMult;
- g_thetaParam.value = g_clock * g_speedScale;
-
- // If we don't check the size of the client area every frame we don't get a
- // chance to adjust the perspective matrix fast enough to keep up with the
- // browser resizing us, so onrender must call resize.
- resize();
-}
-
-
-// Generates the projection matrix based on the size of the g_o3d plugin
-// and calculates the view-projection matrix.
-function resize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- // Determine what the size of the rendered square within the client should
- // be in pixels.
- var side = g_o3dWidth < g_o3dHeight ?
- g_o3dWidth : g_o3dHeight;
-
- // Convert to the region of world space that must be enclosed by the
- // orthographic projection.
- var worldSize = g_math.divVectorScalar([g_o3dWidth, g_o3dHeight], side);
-
- // Find a projection matrix to transform from world space to screen space.
- g_viewInfo.drawContext.projection = o3djs.math.matrix4.orthographic(
- -0.5 * worldSize[0], 0.5 * worldSize[0],
- -0.5 * worldSize[1], 0.5 * worldSize[1],
- 0.5, 1.5);
- }
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body style="width: 95%; height: 95%;">
-<table style="width: 100%; height: 100%;">
- <tr>
- <td>
- <h1>Juggler</h1>
- <p>
- This sample displays a juggling pattern computed entirely in a shader.
- <form name="the_form">
- <input type="radio" name="radio_group" value="3"
- onclick=updateNum()>3 Balls
- <input type="radio" name="radio_group" value="5"
- onclick=updateNum()>5 Balls
- <input type="radio" name="radio_group" value="7"
- onclick=updateNum()>7 Balls
- <input type="radio" name="radio_group" value="9"
- onclick=updateNum()>9 Balls
- <input type="radio" name="radio_group" value="11" checked
- onclick=updateNum()>11 Balls
- <input type="radio" name="radio_group" value="13"
- onclick=updateNum()>13 Balls
- <input type="radio" name="radio_group" value="15"
- onclick=updateNum()>15 Balls
- <input type="radio" name="radio_group" value="17"
- onclick=updateNum()>17 Balls
- <input type="checkbox" name="check_box" checked
- onclick=toggleRenderCallback()>Animate
- </form>
- </p>
- <table id="container" style="width: 100%; height: 80%;">
- <tr>
- <td height="100%">
- <!-- Start of g_o3d plugin -->
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- <!-- End of g_o3d plugin -->
- </td>
- </tr>
- </table>
- <!-- a simple way to get a multiline string -->
- <textarea id="shader" name="shader" cols="80" rows="20"
- style="display: none;">
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-
-float theta;
-float num;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 texCoord : TEXCOORD0;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texCoord : TEXCOORD0;
- float4 color : COLOR;
-};
-
-/**
- * vertexShaderMain - our vertex shader for the juggling texture
- */
-PixelShaderInput vertexShaderMain(VertexShaderInput input) {
- PixelShaderInput output;
-
- output.position = mul(input.position, worldViewProjection);
- output.texCoord = 4.0 * (input.texCoord - float2(0.5, 0.5));
- output.color = float4(1, 1, 1, 1);
-
- return output;
-}
-
-float length_2(in float2 v) {
- return dot(v, v);
-}
-
-// Draw the balls in a single arc.
-// Returns 1 if the pixel is within a ball, 0 if it isn't, and a value in
-// between for pixels right on the edge, for antialiasing.
-float drawBallsInArc(in float pi,
- in float4 offset,
- in float2 source_hand,
- in float2 dest_hand,
- in float height_factor,
- in float baseline,
- in float ball_radius_2,
- in float hand_throw_offset,
- in float2 Z,
- in float threshold) {
- // Map theta from its current range of [0, 2 * num * pi) onto [0, (num - 1))
- // by scaling, adding offset, and modding, then map that to [0, 1) by scaling.
- // The first mapping tells us where in the repeating cycle we are, and the
- // second mapping simplifies the calculation of the parabola.
-
- // The vector offset is used to distinguish between balls in the same arc, but
- // out of phase. At the beginning of this function, all the operations are
- // vectorized to save instructions; we get to calculate 4 ball positions for
- // the price of 1.
-
- // The reason for the (num - 1) in the expression below is that with num
- // balls, each ball spends (num - 1) beats in the air, then one in the hand.
- // So (num - 1) is the length of time a parabola takes.
-
- float4 time = fmod(theta / pi + offset, (num - 1)) / (num - 1);
- float dx = dest_hand.x - source_hand.x;
- float4 x = time * dx + source_hand.x - hand_throw_offset;
- float4 y = time * (1 - time);
- y = y * height_factor + baseline;
- float4 ZX = Z.x;
- float4 ZY = Z.y;
- float4 len_2 = (ZX - x) * (ZX - x) + (ZY - y) * (ZY - y);
-
- // This antialiasing fuzzes the balls just a bit larger than they would
- // otherwise be.
- float4 temp = clamp((len_2 - ball_radius_2) / threshold, 0, 1);
-
- // One minus the product of all entries in temp.
- temp.xy = temp.xy * temp.zw;
- return 1 - temp.x * temp.y;
-}
-
-float4 drawAirborneBalls(in float pi,
- in float4 offset,
- in float2 right_hand,
- in float2 left_hand,
- in float height_factor,
- in float baseline,
- in float ball_radius_2,
- in float hand_swing_radius,
- in float2 Z,
- in float threshold) {
- float value =
- // balls going right to left
- (drawBallsInArc(pi, offset, right_hand, left_hand, height_factor,
- baseline, ball_radius_2, hand_swing_radius, Z, threshold) +
- // balls going left to right
- drawBallsInArc(pi, offset + 1, left_hand, right_hand, height_factor,
- baseline, ball_radius_2, -hand_swing_radius, Z, threshold));
- return float4(value, value, value, value);
-}
-
-/**
- * pixelShaderMain - pixel shader
- */
-
-float4 pixelShaderMain(PixelShaderInput input) : COLOR {
- const float pi = 3.14159265;
- const float baseline = -1.4;
- const float2 right_hand = float2(0.8, baseline);
- const float2 left_hand = float2(-0.8, baseline);
- const float hand_swing_radius = 0.25;
- const float hand_radius = 0.15;
- const float hand_radius_2 = hand_radius * hand_radius;
- const float ball_radius = 0.08;
- const float ball_radius_2 = ball_radius * ball_radius;
-
- const float4 right_hand_color = float4(1, 0, 0, 1);
- const float4 left_hand_color = float4(0, 0, 1, 1);
- const float4 background_color = float4(0, 0, 0, 0);
-
- const float threshold = 0.002; // Used in clamp for antialiasing.
-
- float height_factor = num * 0.75;
-
- float2 Z = input.texCoord;
-
- // Coerce to the range [0, 2 * Pi * num].
- float2 r_h = hand_swing_radius * float2(-cos(theta), sin(theta)) + right_hand;
- float2 l_h = hand_swing_radius * float2(-cos(theta), -sin(theta)) + left_hand;
-
- // Initialize color of pixel to background_color. Background color has an
- // alpha of 0. Color of objects each have alpha 1, so multiplying by
- // (1-alpha) before adding the color ensures that nothing gets overdrawn.
- // It's kind of like a rudimentary z-buffer.
- float4 result = background_color;
-
- // Draw the hands. The antialiasing here fuzzes the hands just a little bit
- // smaller than they would otherwise be. That's the opposite of what we do
- // for the balls, just because it happens to be cheaper here to do smaller and
- // cheaper in drawBallsInArc to do larger.
- result +=
- clamp((hand_radius_2 - length_2(Z - r_h)) / threshold, 0, 1) *
- (Z.y < r_h.y) * right_hand_color +
- clamp((hand_radius_2 - length_2(Z - l_h)) / threshold, 0, 1) *
- (Z.y < l_h.y) * left_hand_color;
-
- // Draw the ball in the hand. There is always a ball in exactly one hand, and
- // which hand that is alternates.
- float2 hand;
- if (fmod(floor(theta / pi), 2) > 0.5) {
- hand = r_h;
- } else {
- hand = l_h;
- }
- // The antialiasing here fuzzes the balls just a bit bigger than they would
- // otherwise be. This is more work than making them smaller [the extra
- // subtraction in the "1 - clamp..." below], but inverting it in
- // drawBallsInArc would be more expensive, and they have to match so that the
- // balls are all the same size.
- result += (1 - result.a) *
- (1 - clamp((length_2(Z - hand) - ball_radius_2) / threshold, 0, 1));
-
- // Draw airborne balls.
- float4 offset = float4(0, 2, 4, 6);
- result += (1 - result.a) * drawAirborneBalls(pi,
- offset,
- right_hand,
- left_hand,
- height_factor,
- baseline,
- ball_radius_2,
- hand_swing_radius,
- Z,
- threshold);
-
- // For each up-to-4 pairs of balls you want to add, increment offset by
- // (8, 8, 8, 8) and call drawAirborneBalls again.
- offset += 8;
- result += (1 - result.a) * drawAirborneBalls(pi,
- offset,
- right_hand,
- left_hand,
- height_factor,
- baseline,
- ball_radius_2,
- hand_swing_radius,
- Z,
- threshold);
-
- return result;
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderMain
-// #o3d PixelShaderEntryPoint pixelShaderMain
-// #o3d MatrixLoadOrder RowMajor
- </textarea>
- </td>
- </tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/julia.html b/o3d/samples/julia.html
deleted file mode 100644
index e795cfd..0000000
--- a/o3d/samples/julia.html
+++ /dev/null
@@ -1,295 +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.
--->
-
-<!--
-O3D Julia Set
-
-This sample draws an animated julia set in real time using
-the pixel shader for the computation.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html style="width: 100%; height: 100%;">
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Julia Set Pixel Shader
-</title>
-
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-
-// Events
-// Run the init() function once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_o3dElement;
-var g_viewInfo;
-var g_pack;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-var g_clock = 0.0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-var g_seedParam;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes o3d, loads the effect, and creates the square.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Create a g_pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot,
- [0, 0, 0, 1]);
-
- // Load shader code from DOM and use it to build the effect.
- var effect = g_pack.createObject('Effect');
- effect.loadFromFXString(document.getElementById('shader').value);
-
- // Create a Material for the effect.
- var myMaterial = g_pack.createObject('Material');
-
- // Apply our effect to this material.
- myMaterial.effect = effect;
-
- // Set the material's drawList for opaque objects.
- myMaterial.drawList = g_viewInfo.performanceDrawList;
-
- // create the parameters the effect needs to the material.
- effect.createUniformParameters(myMaterial);
-
- // Create a square.
- var myShape = o3djs.primitives.createPlane(g_pack, myMaterial, 1, 1, 1, 1);
-
- // Initialize effect parameters to something reasonable
- g_seedParam = myMaterial.getParam('seed');
- g_seedParam.value = [0.2, 0.5];
-
- // Put the camera somewhere where it has a good view of that square.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 1, 0], //eye
- [0, 0, 0], //target
- [0, 0, -1]); //up
-
- // Generate the projection matrix based
- // on the g_o3d plugin size by calling resize().
- resize();
-
- // Now attach the square to the root of the transform graph.
- g_client.root.addShape(myShape);
-
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-
-/**
- * Render callback. Walks the seed of the Julia set through
- * a parametric path in the complex plane that stays
- * in the neighborhood of the Mandelbrot set.
- */
-function onrender(render_event) {
- g_clock += render_event.elapsedTime * g_timeMult;
-
- var t = 0.1 * g_clock;
- var x = 0.6 * Math.cos(3.0 * t) - 0.3;
- var y = (0.5 * x + 1.7)*(0.2 * Math.sin(7 * t));
-
- g_seedParam.value = [x, y];
-
- resize();
-}
-
-
-/**
- * Generates the projection matrix based on the size of the o3d plugin and
- * calculates the view-projection matrix.
- */
-function resize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- // Determine what the size of the rendered square within the client should
- // be in pixels.
- var side = g_o3dWidth < g_o3dHeight ?
- g_o3dWidth : g_o3dHeight;
-
- // Convert to the region of world space that must be enclosed by the
- // orthographic projection.
- var worldSize = g_math.divVectorScalar([g_o3dWidth, g_o3dHeight], side);
-
- // Find a projection matrix to transform from world space to screen space.
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -0.5 * worldSize[0], 0.5 * worldSize[0],
- -0.5 * worldSize[1], 0.5 * worldSize[1],
- 0.5, 1.5);
- }
-}
-
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-
-</script>
-</head>
-<body style="width: 100%; height: 100%;">
-<table style="width: 100%; height: 100%;">
- <tr>
- <td>
- <h1>Julia Set</h1>
- <p>
- This sample draws an animated julia set in real time using
- the pixel shader for the computation.
- </p>
- <table id="container" style="width: 100%; height: 80%;">
- <tr>
- <td height="100%">
- <!-- Start of g_o3d plugin -->
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- <!-- End of g_o3d plugin -->
- </td>
- </tr>
- </table>
- <!-- a simple way to get a multiline string -->
- <textarea id="shader" name="shader" cols="80" rows="20"
- style="display: none;">
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-
-// The seed for the julia set (c in the expression z(n+1) = z(n)^2+c).
-float2 seed;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 texCoord : TEXCOORD0;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texCoord : TEXCOORD0;
-};
-
-/**
- * vertexShaderMain - Multiplies position by world-view-projection matrix, and
- * passes on texture coordinates scaled to put the origin in the center of the
- * quad and reveal a nicely sized portion of the plane to show the julia set.
- */
-PixelShaderInput vertexShaderMain(VertexShaderInput input) {
- PixelShaderInput output;
-
- output.position = mul(input.position, worldViewProjection);
- output.texCoord = 4.0 * (input.texCoord - float2(0.5, 0.5));
-
- return output;
-}
-
-
-/**
- * pixelShaderMain - Calculates the color of the pixel by iterating on the
- * formula z = z*z + seed. After some number of iterations, the magnitude of z
- * determines the color.
- */
-float4 pixelShaderMain(PixelShaderInput input) : COLOR {
- float2 Z = input.texCoord;
-
- // Number of iterations hardcoded here. The more iterations, the crisper the
- // image.
- for(int i = 0; i < 10; ++i) {
- Z = float2(Z.x * Z.x - Z.y * Z.y, 2.0 * Z.x * Z.y) + seed;
-
- // Some graphics cards and some software renderers don't appreciate large
- // floating point values, so we clamp to prevent Z from getting that big.
- if (i > 7) {
- Z = clamp(Z, -25, 25);
- }
- }
-
- return (1 - length(Z)) * float4(0.5, 1, 2, 1);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderMain
-// #o3d PixelShaderEntryPoint pixelShaderMain
-// #o3d MatrixLoadOrder RowMajor
- </textarea>
- </td>
- </tr>
-</table>
-</body>
-</html>
-
-
diff --git a/o3d/samples/manipulators/manipsample.js b/o3d/samples/manipulators/manipsample.js
deleted file mode 100644
index a63cf8c..0000000
--- a/o3d/samples/manipulators/manipsample.js
+++ /dev/null
@@ -1,297 +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.
- */
-
-/**
- * @fileoverview This file contains code that is common to several of the
- * manipulator samples, such as rotate1.html and translate2.html.
- *
- * This is purely *example* code, showing how to use the manipulators.
- *
- * Requires base.js
- */
-
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.manipulators');
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.cameracontroller');
-
-// global variables
-var g_o3dElement;
-var g_client;
-var g_o3d;
-var g_math;
-var g_mainPack;
-var g_mainViewInfo;
-var g_mainRoot;
-var g_lightPosition = [5, 5, 7]; // TODO(simonrad): Remove this?
-var g_lastCubeTransform;
-var g_primitives = [];
-var g_manager;
-var g_cameraController;
-
-/**
- * Creates the client area.
- */
-function initClient() {
- window.g_finished = false; // for selenium testing.
-
- // Runs the sample in V8. Comment out this line to run it in the browser
- // JavaScript engine, for example if you want to debug it.
- // TODO(kbr): we need to investigate why turning this on is
- // significantly slower than leaving it disabled.
- // o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.util.makeClients(main);
-}
-
-/**
- * Initializes global variables, positions camera, draws shapes.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function main(clientElements) {
- var o3dElement = clientElements[0];
-
- // Init global variables.
- initGlobals(clientElements);
-
- // Add the shapes to the transform hierarchy.
- createShapes();
-
- // Add the manipulators to the transform hierarchy.
- setupManipulators();
-
- // Set up the view and projection transformations.
- initContext();
-
- // Start picking; it won't do anything until the scene finishes loading.
- o3djs.event.addEventListener(o3dElement, 'mousedown', onMouseDown);
- o3djs.event.addEventListener(o3dElement, 'mousemove', onMouseMove);
- o3djs.event.addEventListener(o3dElement, 'mouseup', onMouseUp);
-
- window.g_finished = true; // for selenium testing.
-}
-
-function onMouseDown(e) {
- if(e.button == 2 && !e.shiftKey && !e.ctrlKey) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.SPIN_ABOUT_CENTER, e.x, e.y);
- } else if(e.button == 2 && e.shiftKey && !e.ctrlKey) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.ZOOM_IN_OUT, e.x, e.y);
- } else if(e.button == 2 && !e.shiftKey && e.ctrlKey) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.DOLLY_IN_OUT, e.x, e.y);
- } else if(e.button == 2 && e.shiftKey && e.ctrlKey) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.DOLLY_ZOOM, e.x, e.y);
- } else if(e.button == 1) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.MOVE_CENTER_IN_VIEW_PLANE, e.x, e.y);
- } else if(e.button == 0) {
- g_manager.mousedown(e.x, e.y,
- g_mainViewInfo.drawContext.view,
- g_mainViewInfo.drawContext.projection,
- g_client.width,
- g_client.height);
- }
-}
-
-function onMouseMove(e) {
- g_cameraController.mouseMoved(e.x, e.y);
-
- // You can call this function here, or pass it to the CameraController
- // as the onChange callback.
- //updateViewAndProjectionMatrices();
-
- g_manager.mousemove(e.x, e.y,
- g_mainViewInfo.drawContext.view,
- g_mainViewInfo.drawContext.projection,
- g_client.width,
- g_client.height);
- g_manager.updateInactiveManipulators();
-}
-
-function onMouseUp(e) {
- g_cameraController.setDragMode(
- o3djs.cameracontroller.DragMode.NONE, e.x, e.y);
-
- g_manager.mouseup();
- g_manager.updateInactiveManipulators();
-}
-
-/**
- * Initializes global variables and libraries.
- */
-function initGlobals(clientElements) {
- g_o3dElement = clientElements[0];
- window.g_client = g_client = g_o3dElement.client;
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_mainPack = g_client.createPack();
-
- // Make a root transform for our scene.
- g_mainRoot = g_mainPack.createObject('Transform');
-
- // Create the render graph for the scene view.
- g_mainViewInfo = o3djs.rendergraph.createBasicView(
- g_mainPack,
- g_mainRoot,
- g_client.renderGraphRoot);
-}
-
-/**
- * Sets up reasonable view and projection matrices.
- */
-function initContext() {
- // Set up our CameraController.
- g_cameraController = o3djs.cameracontroller.createCameraController(
- [0, 2, 0], // centerPos
- 23, // backpedal
- 0, // heightAngle
- 0, // rotationAngle
- g_math.degToRad(15), // fieldOfViewAngle
- updateViewAndProjectionMatrices); // opt_onChange
-
- updateViewAndProjectionMatrices();
-}
-
-function updateViewAndProjectionMatrices() {
- g_mainViewInfo.drawContext.view = g_cameraController.calculateViewMatrix();
-
- // Set up a perspective transformation for the projection.
- g_mainViewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_cameraController.fieldOfViewAngle * 2, // Frustum angle.
- g_o3dElement.clientWidth / g_o3dElement.clientHeight, // Aspect ratio.
- 1, // Near plane.
- 5000); // Far plane.
-}
-
-/**
- * Creates shapes using the primitives utility library, and adds them to the
- * transform graph at the root node.
- */
-function createShapes() {
- // Create a little tree-like hierarchy of cubes
- createCubeTree(2, 1.5, [0, 0, 0], g_mainRoot);
- g_lastCubeTransform.scale(3, 1, 1);
-}
-
-/**
- * Creates a small tree of cubes to demonstrate interaction with a
- * hierarchy of shapes.
- */
-function createCubeTree(depth, edgeLength, translation, parent) {
- var cur = createCube(edgeLength, translation, parent);
- if (depth > 0) {
- createCubeTree(depth - 1,
- edgeLength / 1.5,
- o3djs.math.addVector(translation,
- [-1.2 * edgeLength,
- 1.0 * edgeLength,
- 0]),
- cur);
- createCubeTree(depth - 1,
- edgeLength / 1.5,
- o3djs.math.addVector(translation,
- [1.2 * edgeLength,
- 1.0 * edgeLength,
- 0]),
- cur);
- }
- return cur;
-}
-
-/**
- * Creates a cube shape using the primitives utility library, with an
- * optional translation and parent. Returns the newly-created
- * transform for the cube.
- */
-function createCube(edgeLength, opt_translation, opt_parent) {
- var cube = o3djs.primitives.createCube(
- g_mainPack,
- // A green phong-shaded material.
- o3djs.material.createBasicMaterial(g_mainPack,
- g_mainViewInfo,
- [0, 1, 0, 1]),
- edgeLength);
- var transform = g_mainPack.createObject('Transform');
- g_lastCubeTransform = transform;
- transform.addShape(cube);
- if (opt_translation) {
- transform.translate(opt_translation);
- }
- if (opt_parent) {
- transform.parent = opt_parent;
- } else {
- transform.parent = g_mainRoot;
- }
- g_primitives.push(transform);
- return transform;
-}
-
-/**
- * Creates manipulators attached to the objects we've just created.
- */
-function setupManipulators() {
- // Create a separate pack for the manipulators so they don't get mixed in
- // with the main scene's objects.
- var pack = g_client.createPack();
-
- // Create a root transform for the manipulators so they are 100% separate
- // from the scene's transforms.
- var manipulatorRoot = pack.createObject('Transform');
-
- g_manager = o3djs.manipulators.createManager(
- pack,
- manipulatorRoot,
- g_client.renderGraphRoot,
- g_mainViewInfo.root.priority + 1,
- g_mainViewInfo.drawContext);
-
- // Actually construct the manips. This function is implemented in the html
- // sample files that include this file, as it is different for each sample.
- createManipulators();
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
diff --git a/o3d/samples/manipulators/rotate1.html b/o3d/samples/manipulators/rotate1.html
deleted file mode 100644
index b4fc312..0000000
--- a/o3d/samples/manipulators/rotate1.html
+++ /dev/null
@@ -1,85 +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.
--->
-
-<!--
-Rotate1 manipulator
-
-This sample shows how to use the o3djs.manipulators.Rotate1 class
-to interactively drag objects around the scene.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Rotate1 Manipulator
-</title>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" src="manipsample.js"></script>
-
-<script type="text/javascript">
-// This function is used in manipsample.js.
-// We implement it here because it is different for each sample.
-function createManipulators() {
- var jj = 2;
- for (var ii = 0; ii < g_primitives.length; ii++) {
- var manip1 = g_manager.createRotate1();
- var manip2 = g_manager.createRotate1();
- var manip3 = g_manager.createRotate1();
- manip1.attachTo(g_primitives[ii]);
- manip2.attachTo(g_primitives[ii]);
- manip3.attachTo(g_primitives[ii]);
- manip1.setOffsetTranslation([0, -1.5, 0]);
- manip2.setOffsetTranslation([0, -1.5, 0]);
- manip3.setOffsetTranslation([0, -1.5, 0]);
- manip2.setOffsetRotation(o3djs.quaternions.rotationY(Math.PI / 2));
- manip3.setOffsetRotation(o3djs.quaternions.rotationZ(Math.PI / 2));
- // Demonstrate that we can drag along arbitrary directions.
- if ((++jj % 4) == 0) {
- manip1.setOffsetRotation(o3djs.quaternions.rotationY(Math.PI / 4));
- manip2.setOffsetRotation(o3djs.quaternions.rotationY(Math.PI * 3.0 / 4));
- }
- }
-}
-</script>
-
-</head>
-<body onload="initClient()" onunload="unload()">
-<h1>Rotate1 Manipulator Sample</h1>
-This example shows how to move objects around the scene using the
-Rotate1 manipulator.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/manipulators/translate1.html b/o3d/samples/manipulators/translate1.html
deleted file mode 100644
index e6a2ed4..0000000
--- a/o3d/samples/manipulators/translate1.html
+++ /dev/null
@@ -1,76 +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.
--->
-
-<!--
-Translate1 manipulator
-
-This sample shows how to use the o3djs.manipulators.Translate1 class
-to interactively drag objects around the scene.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Translate1 Manipulator
-</title>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" src="manipsample.js"></script>
-
-<script type="text/javascript">
-// This function is used in manipsample.js.
-// We implement it here because it is different for each sample.
-function createManipulators() {
- var jj = 2;
- for (var ii = 0; ii < g_primitives.length; ii++) {
- var manip = g_manager.createTranslate1();
- manip.attachTo(g_primitives[ii]);
- manip.setOffsetTranslation([0, -1.5, 0]);
- // Demonstrate that we can drag along arbitrary directions.
- if ((++jj % 4) == 0) {
- manip.setOffsetRotation(o3djs.quaternions.rotationY(Math.PI / 4));
- }
- }
-}
-</script>
-
-</head>
-<body onload="initClient()" onunload="unload()">
-<h1>Translate1 Manipulator Sample</h1>
-This example shows how to move objects around the scene using the
-Translate1 manipulator.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/manipulators/translate2.html b/o3d/samples/manipulators/translate2.html
deleted file mode 100644
index ab25857..0000000
--- a/o3d/samples/manipulators/translate2.html
+++ /dev/null
@@ -1,76 +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.
--->
-
-<!--
-Translate2 manipulator
-
-This sample shows how to use the o3djs.manipulators.Translate2 class
-to interactively drag objects around the scene.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Translate2 Manipulator
-</title>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" src="manipsample.js"></script>
-
-<script type="text/javascript">
-// This function is used in manipsample.js.
-// We implement it here because it is different for each sample.
-function createManipulators() {
- var jj = 2;
- for (var ii = 0; ii < g_primitives.length; ii++) {
- var manip = g_manager.createTranslate2();
- manip.attachTo(g_primitives[ii]);
- manip.setOffsetTranslation([0, -1.5, 0]);
- // Demonstrate that we can drag along arbitrary directions.
- if ((++jj % 4) == 0) {
- manip.setOffsetRotation(o3djs.quaternions.rotationY(Math.PI / 4));
- }
- }
-}
-</script>
-
-</head>
-<body onload="initClient()" onunload="unload()">
-<h1>Translate2 Manipulator Sample</h1>
-This example shows how to move objects around the scene using the
-Translate2 manipulator.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/multiple-clients.html b/o3d/samples/multiple-clients.html
deleted file mode 100644
index a8993e78..0000000
--- a/o3d/samples/multiple-clients.html
+++ /dev/null
@@ -1,230 +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 sample demonstrates running more than 1 instance of the plugin at
-the same time.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Multiple Clients
-</title>
-<!-- Our javascript code -->
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.io');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-
-// Events
-// Run the init() function once the page has finished loading.
-// uninit() when the page is unloaded.
-window.onload = init;
-window.onunload = uninit;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_clients = [];
-var g_packs = [];
-var g_viewInfos = [];
-var g_num_clients;
-var g_setupDone = false;
-
-var g_animate_angle = [];
-var g_eye;
-
-var NUM_ACROSS = 10;
-var NUM_DOWN = 5;
-
-/**
- * Initializes O3D, loads the effect, and draws the cube.
- */
-function init() {
- // Create a bunch of clients.
- var ii = 0;
- var tbodyElem = document.getElementById('clients');
- for (var row = 0; row < NUM_DOWN; row++) {
- var trElem = document.createElement('tr');
- for (var column = 0; column < NUM_ACROSS; column++) {
- var tdElem = document.createElement('td');
- var objElem = o3djs.util.createClient(tdElem);
- objElem.style.width = '60px';
- objElem.style.height = '60px';
- objElem.id = 'o3d' + ii;
- objElem.name = 'o3d' + ii;
- trElem.appendChild(tdElem);
- ii++;
- }
- tbodyElem.appendChild(trElem);
- }
- g_num_clients = ii;
-
- // wait for the browser to settle down.
- var clearId = window.setInterval(function() {
- var element = document.o3d0
- if (!element.o3d) {
- return;
- }
- window.clearInterval(clearId);
- setup();
- }, 10);
-}
-
-function setup() {
- // Lookup all the clients.
- for (var ii = 0; ii < g_num_clients; ++ii) {
- g_clients[ii] = document.getElementById('o3d' + ii).client;
- }
-
- // Get constants and math functions.
- g_o3d = document.o3d0.o3d;
- g_math = o3djs.math;
-
- // Init our sample helper libraries. We need to call this manually since
- // we did not use o3djs.base.makeClients.
- o3djs.base.init(document.o3d0);
-
- var effectSource =
- o3djs.io.loadTextFileSynchronous('shaders/vertex-color.shader');
-
- // For each client make a cube, context, effect,...
- for (ii = 0; ii < g_num_clients; ii++) {
- // Create a pack to manage our resources/assets
- g_packs[ii] = g_clients[ii].createPack();
-
- // Create the render graph for a view.
- g_viewInfos[ii] = o3djs.rendergraph.createBasicView(
- g_packs[ii],
- g_clients[ii].root,
- g_clients[ii].renderGraphRoot);
-
- g_animate_angle[ii] = 0;
-
- // Create our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 100.
- g_viewInfos[ii].drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- 128 / 128,
- 0.1,
- 100);
-
- // Create and load the effect.
- var effect = g_packs[ii].createObject('Effect');
- effect.loadFromFXString(effectSource);
-
- // Create a material for it.
- var material = g_packs[ii].createObject('Material');
-
- // Set the material's drawList
- material.drawList = g_viewInfos[ii].performanceDrawList;
-
- // Apply our effect to this material.
- material.effect = effect;
- effect.createUniformParameters(material);
-
- // Create a cube using the effect we have loaded.
- createCube(g_clients[ii].root, g_packs[ii], material);
- }
-
- // Set our render callback for animation.
- // This sets a function to be executed every time a frame is rendered.
- g_clients[0].setRenderCallback(onrender);
- g_setupDone = true;
-}
-
-/**
- * Creates a cube with the given effect.
- *
- * @param {!o3d.Transform} parent Transform to parent shape to.
- * @param {!o3d.Pack} pack Pack to use.
- * @param {!o3d.Material} material Material to use.
- */
-function createCube(parent, pack, material) {
- // First, create a 'shape' node to store our sphere.
- var myShape = o3djs.primitives.createRainbowCube(pack, material, 0.5);
-
- // Attach the cube to the root of the transform graph.
- parent.addShape(myShape);
-}
-
-// Animates the cubes.
-// This function executes on each frame.
-// It was set using document.o3d.setEventCallback(..) in setup().
-function onrender(render_event) {
- var elapsedTime = render_event.elapsedTime;
- for (var ii = 0; ii < g_num_clients; ii++) {
- // Rotate frame rate independently.
- g_animate_angle[ii] += (0.1 + 0.1 * ii) * elapsedTime;
-
- // Eye-position, this is where our camera is at.
- var eye = [
- 0.0 + Math.sin(g_animate_angle[ii]) * 1.0,
- 1.0,
- 0.0 + Math.cos(g_animate_angle[ii]) * 1.0
- ];
-
- // Target, this is where our camera is pointed at.
- var target = [0, 0, 0];
-
- // Up-vector, this tells the camera which direction is 'up'.
- // We define the positive y-direction to be up in this example.
- var up = [0, 1, 0];
-
- g_viewInfos[ii].drawContext.view = g_math.matrix4.lookAt(eye, target, up);
- }
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_clients[0]) {
- g_clients[0].cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Multiple Clients</h1>
-<table>
- <tbody id="clients">
- </tbody>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/multiple-lights.html b/o3d/samples/multiple-lights.html
deleted file mode 100644
index 5817ac7..0000000
--- a/o3d/samples/multiple-lights.html
+++ /dev/null
@@ -1,208 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<!--
-O3D Multiple Lights example.
-
-Shows a simple cube with one light on each corner.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Multiple Lights
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-
-//o3djs.base.o3d = o3d;
-
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.primitives');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_transform = null;
-var g_finished = false; // for selenium testing.
-var g_clock = 0;
-var g_timeMult = 1;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 10000);
-
- // Create a material.
- var material = g_pack.createObject('Material');
- material.drawList = g_viewInfo.performanceDrawList;
-
- material.createParam('diffuse', 'ParamFloat4').value = [.5, .5, .5, 1];
-
- // Create some suitable defaults for the material to save the user having
- // to know all this stuff right off the bat.
- material.createParam('emissive', 'ParamFloat4').value = [0, 0, 0, 1];
- material.createParam('ambient', 'ParamFloat4').value = [0, 0, 0, 0];
- material.createParam('specular', 'ParamFloat4').value = [1, 1, 1, 1];
- material.createParam('shininess', 'ParamFloat').value = 10;
- material.createParam('specularFactor', 'ParamFloat').value = 1;
- o3djs.material.attachStandardEffect(
- g_pack,
- material,
- g_viewInfo,
- 'blinn',
- {lights: 8});
- var materialColorParamList = material.getParam('lightColorList');
- var colorParamList = g_pack.createObject('ParamArray');
- var materialLightPositionList = material.getParam('lightWorldPosList');
- var lightPositionParamList = g_pack.createObject('ParamArray');
- // Create a cylinder.
- var shape = o3djs.primitives.createCube(
- g_pack,
- material,
- 150);
-
- g_transform = g_pack.createObject('Transform');
- // Add the cylinder to the root transform.
- g_transform.addShape(shape);
- g_transform.parent = g_client.root;
-
- var colors = [
- [0, 0, 0, 1], // null light
- [1, 0, 0, 1],
- [0, 0, 1, 1],
- [0, 1, 0, 1],
- [1, 1, 1, 1],
- [0, 1, 1, 1],
- [1, 1, 0, 1],
- [1, 0, 1, 1]];
- var lightDist = 150;
- for (var i = 0; i < 8; i++) {
- colorParamList.createParam(i,'ParamFloat4').value = colors[i];
- var position = [
- (i&1)?lightDist:-lightDist,
- (i&2)?lightDist:-lightDist,
- (i&4)?lightDist:-lightDist
- ];
- lightPositionParamList.createParam(i,'ParamFloat3').value = position;
- }
- materialLightPositionList.value = lightPositionParamList;
- materialColorParamList.value = colorParamList;
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Info for rendering.
- */
-function onrender(renderEvent) {
- // Get the number of seconds since the last render.
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- var x = Math.sin(g_clock * 0.3) * 400;
- var z = Math.cos(g_clock * 0.3) * 400;
- var y = Math.sin(g_clock * 0.7) * 200 + 100;
-
- // spin the camera.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [x, y, z], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Multiple Lights</h1>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 400px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/multiple-views.html b/o3d/samples/multiple-views.html
deleted file mode 100644
index 353e625..0000000
--- a/o3d/samples/multiple-views.html
+++ /dev/null
@@ -1,220 +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.
--->
-
-<!--
-Example of multiple views into the same scene.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Multiple Views
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfos = [];
-var g_pack;
-var g_finished = false; // for selenium testing
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- */
-function loadScene(pack, fileName, parent) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a cameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- g_client.width / 2, // because this context is only used 1/2 the area
- g_client.height);
-
- // Copy the view and projection to the draw context.
- g_viewInfos[0].drawContext.view = cameraInfo.view;
- g_viewInfos[0].drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfos[0]);
-
- g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view for the left half of screen.
- g_viewInfos[0] = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot,
- [0.7, 0.2, 0.2, 1],
- 0,
- [0, 0, 0.5, 1]); // left half of screen.
-
- // Setup 3 areas. Each area needs a viewport, a tree traveral, 2 drawpasses
- // and although we could clear the screen once let's do it per viewport just
- // as an example. The original area is already setup except it needs a
- // viewport setting.
-
- // make the 2 right viewports
- for (var yy = 0; yy < 2; yy++) {
- // Set the view extents to the right half, top or bottom.
- var viewExtents = [0.5, yy * 0.5, 0.5, 0.5];
-
- // Give each view a different background color.
- var viewBackgroundColor = [0.5, 0.2 + 0.5 * yy, 0.7 - 0.5 * yy, 1.0];
-
- // Make this view get processes after the first view.
- var viewPriority = yy + 1;
-
- // Create an extra view. We call createExtraView because we want to
- // share DrawLists with the first view so that all 3 views draw the same
- // things.
- var viewInfo = o3djs.rendergraph.createExtraView(
- g_viewInfos[0],
- viewExtents,
- viewBackgroundColor,
- viewPriority);
-
- // Save it off for later.
- g_viewInfos[g_viewInfos.length] = viewInfo;
-
- // Get the DrawContext for this area and set the view and
- // projection matrices.
- var drawContext = viewInfo.drawContext;
-
- if (yy == 0) {
- drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- (g_client.width * 0.5) / (g_client.height * 0.5),
- 0.1,
- 100);
- drawContext.view = g_math.matrix4.lookAt(
- [-10, 3, -15], // eye
- [0, 2, 0], // target
- [0, 1, 0]); // up
- } else {
- // lets make this one orthographic
- var aspect = g_client.width / g_client.height;
- drawContext.projection = g_math.matrix4.orthographic(
- -10,
- 10,
- -10 / aspect,
- 10 / aspect,
- 0,
- 100);
- // look directly from the front
- drawContext.view = g_math.matrix4.lookAt(
- [0, 5, 30], // eye
- [0, 5, 0], // target
- [0, 1, 0]); // up
- }
- }
-
- // Creates a transform to put our data on.
- var my_data_root = g_pack.createObject('Transform');
-
- // Connects our root to the client's root.
- my_data_root.parent = g_client.root;
-
- // Load the scene into the transform graph as a child my_data_root
- loadScene(g_pack, 'assets/yard.o3dtgz', my_data_root);
-}
-</script>
-</head>
-<body>
-<h1>Multiple Views</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/2d.html b/o3d/samples/o3d-webgl-samples/2d.html
deleted file mode 100644
index 2e7bd23..0000000
--- a/o3d/samples/o3d-webgl-samples/2d.html
+++ /dev/null
@@ -1,562 +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.
--->
-
-<!--
-2D in O3D.
-
-2d is easy in o3d.
-
-Things to notice:
-
-*) Pixel perfect alignment with the screen.
-
- The client area is 800x600 pixels. google-square.png is 200x200 pixels.
- There is a 1 pixel border in the google-square.png texture. Notice they line
- up exactly with each other and to the edge of the client area.
-
-*) Screen Top Left = 0,0 vs Center = 0,0
-
- This demo is set so the client area's top left corner is 0,0.
- If you want the center to be 0,0 just call setScreenOriginToCenter.
- You will have to adjust the math below to match.
-
-*) Image Top left = 0,0 vs Center = 0,0
-
- The g_googleSquares are all loaded with their origin set to the top left
- so you can see they rotate around the top left and are positioned from
- the top left
-
- The g_squares and the g_things are loaded with their origin set to the center
- so you can see they rotate and scale around their centers.
-
-*) 2d rotation, scale, fading, color changing
-
- transform.rotateZ rotates in 2d.
- transform.scale(x, y, 1) scales in 2d.
- image.setColor(1, 1, 1, ?) fades out.
- image.setColor(?, ?, ?, 1) sets the color multiplier
-
-*) Setting draw order by setting Z. negative z is more behind.
-
- the g_googleSquares have a Z of -2 so they are the furthest back.
- the g_squares have Z of -1 so they are in the middle
- the g_things have a Z of 0 so they are in the front.
-
- The Z range is -0.998 to 999
-
- That is because the camera is sitting at -1 Z and has the range set
- in the projection matrix from 0.001 to 1000
-
-*) Things to be aware of.
-
- Because we are doing 2d, draw order matters but you can only choose
- the order by setting the Z value. If you don't set the Z values correctly
- you will see issues. For example if 2 images are at the same Z and draw
- so that they overlap there is no guarntee which one will get drawn first.
-
- Note: Right now I think it is which ever one happens to be in the transform
- graph first. Maybe we should enforce this and then you can use insertBefore,
- insertAfter to change the order instead of setting Z.
-
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-2D in O3D.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.loader');
-
-
-// global variables
-var g_coordWidth = 800; // The number of units across our area
-var g_coordHeight = 600; // The number of units down our area
-var g_tileWidth = 64;
-var g_tileHeight = 64;
-var g_pillarWidth = 128;
-var g_pillarHeight = 256;
-var g_playerWidth = 183;
-var g_playerHeight = 198;
-var g_tilesAcross = Math.floor((g_coordWidth + g_tileWidth - 1) /
- g_tileWidth) + 1;
-var g_tilesDown = Math.floor((g_coordHeight + g_tileHeight - 1) /
- g_tileHeight) + 1;
-var g_pixelsAcrossMap = g_tilesAcross * 64;
-var g_pixelsAcrossPillarMap = (Math.floor((g_coordWidth + g_pillarWidth - 1) /
- g_pillarWidth) + 1) * g_pillarWidth;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_planeShape;
-var g_textures = [];
-var g_textureUrls = [
- '../assets/purple-flower.png', // 0
- '../assets/orange-flower.png', // 1
- '../assets/egg.png', // 2
- '../assets/google-square.png', // 3
- '../assets/square.png', // 4
- '../assets/texture_b3.jpg', // 5
- '../assets/pillar.png', // 6
- '../assets/block.png', // 7
- '../assets/android.png' // 8
-];
-var g_googleSquares = [];
-var g_squares = [];
-var g_things = [];
-var g_tiles = [];
-var g_pillars = [];
-var g_pillarScale = [];
-var g_player;
-var g_map = [
- [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
- [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [ 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0],
- [ 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
- [ 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
- [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
- [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
- [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
-];
-var g_randSeed = 0;
-
-/**
- * Creates the client area.
- */
-function init() {
- // These are here so they are visible to both the browser (so selenium sees
- // them) and V8.
- window.g_clock = 0;
- window.g_timeMult = 1;
- window.g_finished = false; // for selenium testing
-
- // Comment out the line below to run the sample in the browser JavaScript
- // engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Sets the origin of the screen to the top left. Assumes the area is 800 pixels
- * by 600 pixels.
- *
- * We have to pick some representation. If we have an image that's 800x600 and
- * we want to display it pixel perfect in an 800x600 area then we set the values
- * below to 800x600. If instead we were to set them to the width and height of
- * the area and say our area was 400x300 it will still be pixel perfect (1 to 1
- * pixels) which would meaning only the top left 400x300 pixels of our 800x600
- * image would show up.
- *
- * Doing it this way, we get pixel perfect at 800x600 and if we change the size
- * of the area, say to 400x300 to 640x480 or any other 4:3 ratio, our program
- * will still work as expected. It won't be 1x1 pixels but it will put things
- * where we want them within our scaled area. If our area is not 4:3 our image
- * will get a little stretched into the new aspect ratio but generally that's
- * still better than having some of our app not appear.
- *
- * The other option is to always set the values below to the width and height of
- * our area and then make all the code that positions things calculate where to
- * put things and how to scale them to fit which is a lot more work though may
- * be appropriate depending on the application.
- */
-function setScreenOriginToTopLeft() {
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- 0 + 0.5,
- g_coordWidth + 0.5,
- g_coordHeight + 0.5,
- 0 + 0.5,
- 0.001,
- 1000);
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 0, 1], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Sets the origin of the screen to the center. Assumes the area is 800 pixels
- * by 600 pixels. See setScreenOriginToTopLeft.
- */
-function setScreenOriginToCenter() {
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -g_coordWidth * 0.5 + 0.5,
- g_coordWidth * 0.5 + 0.5,
- g_coordHeight * 0.5 + 0.5,
- -g_coordHeight * 0.5 + 0.5,
- 0.001,
- 1000);
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 0, 1], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Set window.g_client as well. Otherwise when the sample runs in V8, selenium
- // won't be able to find this variable (it can only see the browser
- // environment).
- window.g_client = g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set the background color to blue.
- g_viewInfo.clearBuffer.clearColor = [0.1, 0.1, 1, 1];
-
- // Set culling to none so we can flip images using rotation or negative scale.
- g_viewInfo.zOrderedState.getStateParam('CullMode').value =
- g_o3d.State.CULL_NONE;
- g_viewInfo.zOrderedState.getStateParam('ZWriteEnable').value = false;
-
- // Create an orthographic matrix for 2d stuff.
- setScreenOriginToTopLeft();
- //setScreenOriginToCenter();
-
- // Load an effect file and create an effect and material with it.
- var material = o3djs.material.createMaterialFromFile(
- g_pack,
- '../shaders/texture-colormult-glsl.shader',
- g_viewInfo.zOrderedDrawList);
-
- // Set the material params which act as the default. We'll override these with
- // params on transforms.
- material.getParam('colorMult').value = [1, 1, 1, 1];
-
- // Create a 2d plane. createPlane makes an XZ plane by default
- // so we pass in matrix to rotate it to an XY plane. We could do
- // all our manipluations in XZ but most people seem to like XY for 2D.
- g_planeShape = o3djs.primitives.createPlane(
- g_pack,
- material,
- 1,
- 1,
- 1,
- 1,
- o3djs.math.makeMatrix4(1, 0, 0, 0,
- 0, 0, 1, 0,
- 0,-1, 0, 0,
- 0, 0, 0, 1));
-
- // Load all the textures.
- var loader = o3djs.loader.createLoader(initStep3);
- for (var ii = 0; ii < g_textureUrls.length; ++ii) {
- loadTexture(loader, g_textureUrls[ii], ii);
- }
- loader.finish();
-}
-
-/**
- * Loads a texture and saves it in the g_textures array.
- * @param {!o3djs.loader.Loader} loader The loader to load with.
- * @param {string} url of texture to load
- * @param {number} index Index to put texture in g_textures
- */
-function loadTexture(loader, url, index) {
- loader.loadTexture(g_pack, url, function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- g_textures[index] = texture;
- }
- });
-}
-
-/**
- * Now that the textures are loaded continue.
- */
-function initStep3() {
- for (var ii = 0; ii < 12; ++ii) {
- g_googleSquares[ii] = new ImageTransform(g_textures[3], true);
- g_squares[ii] = new ImageTransform(g_textures[4], false);
- g_things[ii] = new ImageTransform(g_textures[ii % 3], false);
- g_pillars[ii] = new ImageTransform(g_textures[6], true);
- g_pillarScale[ii] = g_math.pseudoRandom() * 1.5 + 0.5;
- }
-
- for (var yy = 0; yy < g_tilesDown; ++yy) {
- g_tiles[yy] = [];
- for (var xx = 0; xx < g_tilesAcross; ++xx) {
- if (g_map[yy][xx]) {
- g_tiles[yy][xx] = new ImageTransform(g_textures[7], true);
- }
- }
- }
-
- g_player = new ImageTransform(g_textures[8], true);
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onrender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- // Update g_clock in the browser and cache a V8 copy that can be accesse
- // efficiently. g_clock must be in the browser for selenium.
- var clock = window.g_clock + elapsedTime * window.g_timeMult;
- window.g_clock = clock;
-
- var duration = 4;
- var parts = 4;
- var fadeTime = 1;
- var partOffset = duration - fadeTime;
- var cycle = duration * parts - parts;
-
- var computeFade = function(fadeClock) {
- var fade = 1;
- if (fadeClock < fadeTime) {
- fade = fadeClock / fadeTime;
- } else if (fadeClock > duration - fadeTime) {
- fade = Math.max(duration - fadeClock, 0) / fadeTime;
- }
- return fade;
- };
-
- // Position, fade and rotate the google squares and flowers, eggs.
- for (var yy = 0; yy < 3; ++yy) {
- for (var xx = 0; xx < 4; ++xx) {
- var index = yy * 4 + xx;
- var newIndex = (index + Math.floor(clock * 0.5)) % 12
- var offset = (newIndex == 0) ? (clock * 0.5 % 1) : 0;
- var vary = 0.01 * index;
-
- // compute the amount to fade the google squares.
- var fade = computeFade((clock + partOffset * 0) % cycle);
-
- // position and rotate the google squares.
- var image = g_googleSquares[newIndex];
- image.transform.identity();
- image.transform.translate(xx * 200, yy * 200, -2 + vary);
- image.transform.rotateZ(Math.PI * 2 * offset);
- image.setColor(Math.sin(index + clock * 2.2) * 0.2 + 0.6,
- Math.sin(index + clock * 3.3) * 0.2 + 0.6,
- Math.sin(index + clock * 4.4) * 0.2 + 0.6,
- fade);
-
- // compute the amount to fade the squares.
- fade = computeFade((clock + partOffset * 1) % cycle);
-
- // position and rotate the squares.
- var image = g_squares[index];
- image.setColor(1, 1, 1,
- fade * (Math.sin(index + clock) * 0.5 + 0.5));
- image.transform.identity();
- image.transform.translate(xx * 200 + 100, yy * 200 + 100, -1 + vary);
- image.transform.rotateZ(Math.PI * 2 * offset);
- image.transform.scale(1, Math.sin(clock * 2+ index), 1);
-
- // compute the amount to fade the things.
- fade = computeFade((clock + partOffset * 2) % cycle);
-
- // position, rotate and scale the things.
- var image = g_things[index];
- var nx = newIndex % 4;
- var ny = Math.floor(newIndex / 4);
- offset = clock * 0.5 % 1;
- image.transform.identity();
- image.transform.translate(nx * 300 - 200 + offset * 300,
- ny * 200 + 100 +
- Math.sin(clock * 4 + index * 2) * 50,
- 0 + vary);
- image.transform.rotateZ((0.1 + index * 0.1) * clock);
- var scale = Math.sin(index + clock) * 1.0 + 1.7;
- image.transform.scale(scale, scale, 1);
- image.setColor(1, 1, 1, fade);
- }
- }
-
- // Position and fade the 2d tile based game.
- {
- // This is NOT the best way to a 2d platformer but it does at least show
- // displaying the graphics of one.
-
- // compute the amount to fade the tiles and pillars.
- var fade = computeFade((clock + partOffset * 3) % cycle);
-
- // position the pillars
- for (var xx = 0; xx < 12; ++xx) {
- var image = g_pillars[xx];
- image.setColor(1, 1 , 1, fade);
- image.transform.identity();
- var xOffset =
- (g_pixelsAcrossPillarMap - g_pillarWidth * 2) -
- ((((xx + clock * 0.3) * 238) + g_pillarWidth) %
- g_pixelsAcrossPillarMap - g_pillarWidth);
- image.transform.translate(xOffset, 600 - 256 * g_pillarScale[xx],
- -6 + 0.01 * xx);
- image.transform.scale(1, g_pillarScale[xx], 1);
- }
-
- // position the tiles.
- for (var yy = 0; yy < g_tilesDown; ++yy) {
- for (var xx = 0; xx < g_tilesAcross; ++xx) {
- if (g_map[yy][xx]) {
- var image = g_tiles[yy][xx];
- image.setColor(1, 1, 1, fade);
- image.transform.identity();
- var xOffset =
- (g_pixelsAcrossMap - g_tileWidth * 2) -
- ((((xx + clock * 2) * g_tileWidth) + g_tileWidth) %
- g_pixelsAcrossMap - g_tileWidth);
- image.transform.translate(xOffset, yy * g_tileHeight, -5);
- }
- }
- }
-
- {
- // position the player.
- g_player.setColor(1, 1, 1, fade);
- var xOffset =
- (g_pixelsAcrossMap - g_tileWidth * 2) -
- (((((4.0 + clock * 2) * g_tileWidth) + g_tileWidth) %
- g_pixelsAcrossMap + g_tileWidth) - g_tileWidth);
- g_player.transform.identity();
- g_player.transform.translate(xOffset,
- 5 * g_tileHeight - g_playerHeight -
- Math.abs(Math.sin(clock * 5)) * 100,
- -4);
- }
- }
-}
-
-/**
- * Creates an ImageTransform object which is a transform and a child
- * scaleTransform scaled to match the texture
- *
- * @constructor
- * @param {!o3d.Texture} texture The texture
- * @param {boolean} opt_topLeft If true the origin of the image will be it's
- * topleft corner, the default is the center of the image.
- */
-function ImageTransform(texture, opt_topLeft) {
- // create a transform for positioning
- this.transform = g_pack.createObject('Transform');
- this.transform.parent = g_client.root;
-
- // create a transform for scaling to the size of the image just so
- // we don't have to manage that manually in the transform above.
- this.scaleTransform = g_pack.createObject('Transform');
- this.scaleTransform.parent = this.transform;
-
- // setup the sampler for the texture
- this.sampler = g_pack.createObject('Sampler');
- this.sampler.addressModeU = g_o3d.Sampler.CLAMP;
- this.sampler.addressModeV = g_o3d.Sampler.CLAMP;
- this.paramSampler = this.scaleTransform.createParam('texSampler0',
- 'ParamSampler');
- this.paramSampler.value = this.sampler;
-
- // Setup our UV offsets and color multiplier
- this.paramColorMult = this.scaleTransform.createParam('colorMult',
- 'ParamFloat4');
-
- this.setColor(1, 1, 1, 1);
-
- this.sampler.texture = texture;
- this.scaleTransform.addShape(g_planeShape);
- if (opt_topLeft) {
- this.scaleTransform.translate(texture.width / 2, texture.height / 2, 0);
- }
- this.scaleTransform.scale(texture.width, -texture.height, 1);
-}
-
-/**
- * Sets the color multiplier for the image.
- * @param {number} r Red component.
- * @param {number} g Green component.
- * @param {number} b Blue component.
- * @param {number} a Alpha component.
- */
-ImageTransform.prototype.setColor = function(r, g, b, a) {
- this.paramColorMult.value = [r, g, b, a];
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body onload="init()" onunload="unload()">
-<h1>2D In O3D</h1>
-Doing 2D in O3D.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/animation.html b/o3d/samples/o3d-webgl-samples/animation.html
deleted file mode 100644
index f7ffd81..0000000
--- a/o3d/samples/o3d-webgl-samples/animation.html
+++ /dev/null
@@ -1,343 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<!--
-O3D Animation.
-
-Shows various things being animated by O3D.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Animation.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_framesRendered = 0;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_finished = false; // for selenium
-var g_groupTransforms = [];
-var GROUPS_ACROSS = 2;
-var UNITS_ACROSS_GROUP = 2;
-var TOTAL_ACROSS = GROUPS_ACROSS * UNITS_ACROSS_GROUP;
-var HALF_WIDTH = TOTAL_ACROSS * 0.0;
-var UNIT_SPACING = 200;
-// Set this to true to run a semi-automated test of counter callbacks.
-var RUN_COUNTER_TESTS = location.search.indexOf("test")!=-1;
-
-/**
- * Creates an oscillating animation to animate a single float from 0 to
- * endOutput over endInput seconds with a little bit of ease in, ease out.
- *
- * @param {!o3d.Pack} pack Pack to associate created objects with.
- * @param {!o3d.ParamObject} paramObject Object that has param to animate.
- * @param {string} paramName Name of the param to animate.
- * @param {number} endInput Number of seconds to take to get
- * @param {number} endOutput Target value.
- */
-function attachParamFloatAnimation(pack,
- paramObject,
- paramName,
- endInput,
- endOutput) {
- // Create a FunctionEval through which to evaluate the curve.
- var functionEval = pack.createObject('FunctionEval');
-
- // Bind the param we want to get its value from our FunctionEval's output.
- paramObject.getParam(paramName).bind(functionEval.getParam('output'));
-
- // Create a curve
- var curve = pack.createObject('Curve');
-
- // Set the functionEval to use the curve as it's function.
- functionEval.functionObject = curve;
-
- // Create 2 keys for the curve.
- var key1 = curve.createKey('BezierCurveKey');
- key1.input = 0;
- key1.output = 0;
- key1.outTangent = [0, endInput * 2 / 3];
- var key2 = curve.createKey('BezierCurveKey');
- key2.inTangent = [endInput / 3, endOutput];
- key2.input = endInput;
- key2.output = endOutput;
-
- // Set the curve to oscillate.
- curve.postInfinity = g_o3d.Curve.OSCILLATE;
- curve.preInfinity = g_o3d.Curve.LINEAR;
-
- // Make a SecondCounter to provide an input to the functionEval.
- var counter = pack.createObject('SecondCounter');
-
- // Bind the counter's count to the input of the FunctionEval.
- functionEval.getParam('input').bind(counter.getParam('count'));
- return counter;
-}
-
-function runCounterTest(counter) {
- counter.count = 0;
- counter.addCallback(.5, function(){
- document.body.appendChild(document.createTextNode(
- " a="+counter.count));
- counter.count = counter.count;
- counter.countMode = counter.forward?o3d.Counter.CONTINUOUS
- :o3d.Counter.ONCE;
- counter.end = 9.5;
- counter.addCallback(9.5, function(){
- document.body.appendChild(document.createTextNode(" Test finished:"+
- "Stop at 9.5 count="+counter.count+" running="+counter.running));
- if (counter.running == false) {
- counter.running = true;
- counter.multiplier = 1;
- counter.countMode = o3d.Counter.CONTINUOUS;
- counter.removeAllCallbacks();
- counter.setCount(0);
- }
- })
- counter.start = -3;
- });
- counter.addCallback(1, function(){
- document.body.appendChild(document.createTextNode(
- " b="+counter.count));
- counter.count = counter.forward?1.5:.5;
- });
- counter.addCallback(1.5, function(){
- document.body.appendChild(document.createTextNode(
- " c="+counter.count));
- });
- counter.addCallback(2, function(){
- document.body.appendChild(document.createTextNode(
- " d="+counter.count));
- counter.forward = false;
- counter.multiplier = 10;
- });
- counter.addCallback(-2, function(){
- counter.forward = true;
- counter.removeCallback(.5);
- counter.removeCallback(-2);
- counter.removeCallback(2);
- });
- //counter.advance(100);
-}
-
-/**
- * Creates an oscillating animation to animate a single float of a float4 from 0
- * to endOutput over endInput seconds with a little bit of ease in, ease out.
- *
- * @param {!o3d.Pack} pack Pack to associate created objects with.
- * @param {!o3d.ParamObject} paramObject Object that has param to animate.
- * @param {string} paramName Name of the param Float4 to animate.
- * @param {string} innerParamName Name of the individual float to animate.
- * @param {number} endInput Duration of animation.
- * @param {number} endOutput Target value.
- * @return {!o3d.ParamObject} The created ParamOperation.
- */
-function attach1FloatOfFloat4Animation(pack,
- paramObject,
- paramName,
- innerParamName,
- endInput,
- endOutput) {
-
- var paramOp = pack.createObject('ParamOp4FloatsToFloat4');
- paramObject.getParam(paramName).bind(paramOp.getParam('output'));
- attachParamFloatAnimation(pack, paramOp, innerParamName, endInput, endOutput);
- return paramOp;
-}
-
-/**
- * Creates an animation to animate one of the 9 values of a TRSToMatrix4 and
- * binds it to a transform.
- *
- * @param {!o3d.Pack} pack Pack to associate created objects with.
- * @param {!o3d.Transform} transform Transform to animate.
- * @param {number} endInput Duration of animation.
- * @param {number} endOutput Target value.
- * @param {string} paramName Name of param to animate.
- * @return {!o3d.TRSToMatrix4} The created TRSToMatrix4.
- */
-function attachTRSAnimation(pack, transform, endInput, endOutput, paramName) {
- var trs = pack.createObject('TRSToMatrix4');
- transform.getParam('localMatrix').bind(trs.getParam('output'));
- var c = attachParamFloatAnimation(pack, trs, paramName, endInput, endOutput);
- if (RUN_COUNTER_TESTS)
- runCounterTest(c);
- return trs;
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and sets up some shapes with animations.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create our projection matrix, with a vertical field of view of 45
- // degrees a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 10000);
-
- // Set our view
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [100, 50, 400], // Eye.
- [0, 0, 0], // Target.
- [0, 1, 0]); // Up.
-
- // Create a basic material
- var material = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [1, 1, 1, 1],
- true);
-
- var data = [ { paramName: 'translateY',
- endOutput: 50,
- color: [1, 0, 0, 1] },
- { paramName: 'rotateY',
- endOutput: Math.PI,
- color: [0, 1, 0, 1] },
- { paramName: 'scaleY',
- endOutput: 3,
- color: [1, 1, 0, 1] },
- { paramName: '',
- endOutput: Math.PI * 3,
- color: [1, 1, 0, 1] } ];
-
- for (var ii = 0; ii < 4; ++ii) {
- var xPos = (ii - 1.5) * 100;
- // Create a shape.
- var shape;
- switch (ii) {
- case 0:
- case 2:
- shape = o3djs.primitives.createSphere(g_pack, material, 40, 10, 12);
- break;
- case 1:
- case 3:
- shape = o3djs.primitives.createCube(g_pack, material, 60);
- break;
- }
-
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.addShape(shape);
-
- // Change the color of each one
- transform.createParam('diffuse', 'ParamFloat4').value = data[ii].color;
-
- switch (ii) {
- case 0:
- case 1:
- case 2:
- var trs = attachTRSAnimation(g_pack,
- transform,
- ii * 0.6 + 0.5,
- data[ii].endOutput,
- data[ii].paramName);
-
- // space them out.
- trs.translateX = xPos;
- break;
-
- case 3: {
- var paramOp = attach1FloatOfFloat4Animation(g_pack,
- transform,
- 'diffuse',
- 'input3',
- 0.5,
- 1);
- paramOp.input1 = 1;
- paramOp.input2 = 1;
- transform.translate(xPos, 0, 0);
- break;
- }
- }
- }
-
- g_finished = true; // for selenium
-}
-
-</script>
-</head>
-<body>
-<h1>Animation</h1>
-Once the scene is setup no interaction with o3d is needed for the animations
-to run.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/billboards.html b/o3d/samples/o3d-webgl-samples/billboards.html
deleted file mode 100644
index e76b10a..0000000
--- a/o3d/samples/o3d-webgl-samples/billboards.html
+++ /dev/null
@@ -1,257 +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.
--->
-
-<!--
-Billboard example.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Billboard Example
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.io');
-o3djs.require('o3djs.loader');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_globalParams;
-var g_o3dElement;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-var g_cameraRadius = 35;
-var g_cameraSpeed = 0.3;
-var g_randSeed = 0;
-var g_textures = {};
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_client.width / g_client.height, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-
- var loader = o3djs.loader.createLoader(initStep3);
- loadTexture(loader, 'purple-flower.png');
- loadTexture(loader, 'pillar.png');
- loader.finish();
-}
-
-function loadTexture(loader, filename) {
- loader.loadTexture(g_pack,
- o3djs.util.getAbsoluteURI('../assets/' + filename),
- rememberTexture);
-
- function rememberTexture(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- g_textures[filename] = texture;
- }
- }
-}
-
-function initStep3() {
- var redMaterial = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [0.2, 1, 0.2, 1]); // green
-
- var checkerMaterial = o3djs.material.createCheckerMaterial(g_pack,
- g_viewInfo);
-
- var billboardMaterial = o3djs.material.createMaterialFromFile(
- g_pack, '../shaders/billboard-glsl.shader', g_viewInfo.zOrderedDrawList);
-
- var imposterMaterial = o3djs.material.createMaterialFromFile(
- g_pack, '../shaders/imposter-glsl.shader', g_viewInfo.zOrderedDrawList);
-
- // Set the textures.
- var sampler = g_pack.createObject('Sampler');
- sampler.texture = g_textures['purple-flower.png'];
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
- billboardMaterial.getParam('texSampler0').value = sampler;
-
- var sampler2 = g_pack.createObject('Sampler');
- sampler2.texture = g_textures['pillar.png'];
- sampler2.addressModeU = g_o3d.Sampler.CLAMP;
- sampler2.addressModeV = g_o3d.Sampler.CLAMP;
- imposterMaterial.getParam('texSampler0').value = sampler2;
-
- // Create and bind standard params so we can see the light parameters
- // for the standard shaders globably.
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
-
- // Put on a transform.
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Create a cylinder.
- var cylinderShape = o3djs.primitives.createCylinder(
- g_pack, redMaterial, 0.5, 5, 20, 1,
- g_math.matrix4.translation([0, 2.5, 0]));
-
- // Create an XY plane for the billboard.
- var purpleFlowerPlane = o3djs.primitives.createPlane(
- g_pack, billboardMaterial, 5, 5, 1, 1,
- g_math.matrix4.rotationX(g_math.degToRad(90)));
-
- // Create an XY plane for the imposter.
- var pillarPlane = o3djs.primitives.createPlane(
- g_pack, imposterMaterial, 5, 5, 1, 1,
- g_math.matrix4.rotationX(g_math.degToRad(90)));
-
- // Create 30 cylinders and put a billboard or imposter on top of each one.
- for (var ii = 0; ii < 30; ++ii) {
- transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.translate((g_math.pseudoRandom() - 0.5) * 90,
- 0,
- (g_math.pseudoRandom() - 0.5) * 90);
- transform.addShape(cylinderShape);
-
- var topTransform = g_pack.createObject('Transform');
- topTransform.parent = transform;
- topTransform.translate(0, 7, 0);
- if (ii % 4 > 1) {
- topTransform.addShape(purpleFlowerPlane);
- } else {
- topTransform.addShape(pillarPlane);
- }
- }
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- var eye = [
- Math.sin(g_clock * g_cameraSpeed) * g_cameraRadius,
- 20 + 10 * Math.sin(g_clock * g_cameraSpeed * 4),
- Math.cos(g_clock * g_cameraSpeed) * g_cameraRadius];
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- eye,
- [0, 0, 0], // target
- [0, 1, 0]); // up
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Billboards</h1>
-<div>
-Flowers always face the camera.<br/>
-Pillars rotate around Y toward the camera.
-</div>
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/box2d-3d.html b/o3d/samples/o3d-webgl-samples/box2d-3d/box2d-3d.html
deleted file mode 100644
index ab8c86a..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/box2d-3d.html
+++ /dev/null
@@ -1,147 +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.
--->
-
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>Box2DJS in 3D</title>
-
- <!--=============================-->
- <!-- Copy this part to your app. -->
- <!-- START -->
- <!--=============================-->
- <!-- libs -->
- <script type="text/javascript" src="third_party/prototype-1.6.0.2.js"></script>
-
- <!-- box2djs -->
- <script type="text/javascript" src='third_party/box2d/box2d.js'></script>
- <!--=============================-->
- <!-- Copy this part to your app. -->
- <!-- END -->
- <!--=============================-->
- <script type="text/javascript" src="../../o3d-webgl/base.js"></script>
- <script type="text/javascript" src="../../o3djs/base.js"></script>
-
- <!-- demos -->
- <script src='demos/manager.js'></script>
- <script src='demos/draw_world.js'></script>
- <script src='demos/demo_base.js'></script>
- <script src='demos/top.js'></script>
- <script src='demos/stack.js'></script>
- <script src='demos/compound.js'></script>
- <script src='demos/pendulum.js'></script>
- <script src='demos/crank.js'></script>
- <script src='demos/demos.js'></script>
- <style type="text/css">
- html, body {
- border: 0;
- margin: 0;
- height: 100%;
- }
- </style>
- </head>
-<body onload="init()" onunload="uninit()">
-<table style="width: 100%; height: 100%;"><tr valign="top" style="height: 50px;"><td>
-<h1>Box2DJS in 3D</h1>
-<p>Based on <a href="http://box2d-js.sourceforge.net/">box2d-js</a>.<br/>
-Left Click to create a new object.<br/>
-Right Click (shift-click on OSX) to switch to the next demo.
-</p>
-</td></tr>
-<tr style="height: 100%;"><td>
-<div id="o3d" style="width: 100%; height: 100%;"></div>
-</td></tr></table>
-<div style="display:none;">
-<textarea id="shader">
-uniform mat4 worldViewProjection;
-uniform vec3 lightWorldPos;
-uniform mat4 world;
-uniform mat4 view;
-uniform mat4 worldInverseTranspose;
-
-attribute vec4 position;
-attribute vec4 normal;
-attribute vec2 texCoord0;
-
-varying vec2 diffuseUV;
-varying vec3 n;
-varying vec3 l;
-varying vec3 v;
-
-void main() {
- gl_Position = worldViewProjection * position;
- diffuseUV = texCoord0;
- n = (worldInverseTranspose * normal).xyz;
- l = lightWorldPos - (world * position).xyz;
- v = (view[3] - (world * position)).xyz;
-}
-
-// #o3d SplitMarker
-
-uniform vec4 lightColor;
-uniform sampler2D diffuseSampler;
-uniform vec4 specular;
-uniform float shininess;
-
-uniform vec4 emissive;
-uniform vec4 ambient;
-uniform vec4 colorMult;
-
-varying vec2 diffuseUV;
-varying vec3 n;
-varying vec3 l;
-varying vec3 v;
-
-vec4 lit(float l ,float h, float m) {
- return vec4(1.0,
- max(l, 0.0),
- (l > 0.0) ? pow(max(0.0, h), m) : 0.0,
- 1.0);
-}
-
-void main() {
- vec4 diffuse = texture2D(diffuseSampler, diffuseUV) * colorMult;
- vec3 ll = normalize(l);
- vec3 nn = normalize(n);
- vec3 r = normalize(reflect(nn, ll));
- vec3 vv = normalize(v);
- vec4 litR = lit(dot(nn, ll), dot(r, vv), shininess);
- gl_FragColor = vec4((emissive + lightColor *
- (ambient + diffuse * litR.y + specular * litR.z)).rgb,
- diffuse.a);
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/LICENSE.txt b/o3d/samples/o3d-webgl-samples/box2d-3d/demos/LICENSE.txt
deleted file mode 100644
index c224b40..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/LICENSE.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-The zlib/libpng License
-
-Copyright (c) 2008 ANDO Yasushi
-
-This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
-
-Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
-
- 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
-
- 3. This notice may not be removed or altered from any source distribution.
-
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/README.o3d b/o3d/samples/o3d-webgl-samples/box2d-3d/demos/README.o3d
deleted file mode 100644
index 2d3f954..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/README.o3d
+++ /dev/null
@@ -1,5 +0,0 @@
-This directory contains a subset of Box2D-JS, available at
-http://box2d-js.sourceforge.net/ under the zlib/libpng license (see
-License.txt).
-The software was modified in certain places to make it work with O3D.
-Individual files are marked to indicate modifications occured.
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/compound.js b/o3d/samples/o3d-webgl-samples/box2d-3d/demos/compound.js
deleted file mode 100644
index e63b983..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/compound.js
+++ /dev/null
@@ -1,71 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-demos.compound = {};
-demos.compound.createCompoundBall = function(world, x, y) {
- var ballSd1 = new b2CircleDef();
- ballSd1.density = 1.0;
- ballSd1.radius = 20;
- ballSd1.restitution = 0.2;
- ballSd1.localPosition.Set(-20, 0);
- var ballSd2 = new b2CircleDef();
- ballSd2.density = 1.0;
- ballSd2.radius = 20;
- ballSd2.restitution = 0.2;
- ballSd2.localPosition.Set(20, 0);
- var ballBd = new b2BodyDef();
- ballBd.AddShape(ballSd1);
- ballBd.AddShape(ballSd2);
- ballBd.position.Set(x, y);
- // NOTE: Added the following line to create a 3d object to display.
- ballBd.userData = g.mgr.createCompoundCylinder(20, -20, 20, 20);
- return world.CreateBody(ballBd);
-}
-
-demos.compound.createCompoundPoly = function(world, x, y) {
- var points = [[-30, 0], [30, 0], [0, 15]];
- var polySd1 = new b2PolyDef();
- polySd1.vertexCount = points.length;
- for (var i = 0; i < points.length; i++) {
- polySd1.vertices[i].Set(points[i][0], points[i][1]);
- }
- polySd1.localRotation = 0.3524 * Math.PI;
- var R1 = new b2Mat22(polySd1.localRotation);
- polySd1.localPosition = b2Math.b2MulMV(R1, new b2Vec2(30, 0));
- polySd1.density = 1.0;
- var polySd2 = new b2PolyDef();
- polySd2.vertexCount = points.length;
- for (var i = 0; i < points.length; i++) {
- polySd2.vertices[i].Set(points[i][0], points[i][1]);
- }
- polySd2.localRotation = -0.3524 * Math.PI;
- var R2 = new b2Mat22(polySd2.localRotation);
- polySd2.localPosition = b2Math.b2MulMV(R2, new b2Vec2(-30, 0));
- var polyBd = new b2BodyDef();
- polyBd.AddShape(polySd1);
- polyBd.AddShape(polySd2);
- polyBd.position.Set(x,y);
- // NOTE: Added the following line to create a 3d object to display.
- polyBd.userData = g.mgr.createCompoundWedge(points,
- polySd1.localPosition,
- polySd1.localRotation,
- points,
- polySd2.localPosition,
- polySd2.localRotation);
- return world.CreateBody(polyBd)
-}
-
-demos.compound.initWorld = function(world) {
- var i;
- for (i = 1; i <= 4; i++) {
- demos.compound.createCompoundPoly(world, 150 + 3 * Math.random(), 40 * i);
- }
- for (i = 1; i <= 4; i++) {
- demos.compound.createCompoundBall(world, 350 + 3 * Math.random(), 45 * i);
- }
-}
-demos.InitWorlds.push(demos.compound.initWorld);
-
-
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/crank.js b/o3d/samples/o3d-webgl-samples/box2d-3d/demos/crank.js
deleted file mode 100644
index 007c1dc..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/crank.js
+++ /dev/null
@@ -1,79 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-demos.crank = {};
-demos.crank.initWorld = function(world) {
- var ground = world.m_groundBody;
-
- // Define crank.
- var sd = new b2BoxDef();
- sd.extents.Set(5, 25);
- sd.density = 1.0;
-
- var bd = new b2BodyDef();
- bd.userData = g.mgr.createBox(5, 25);
- bd.AddShape(sd);
-
- var rjd = new b2RevoluteJointDef();
-
- var prevBody = ground;
-
- bd.position.Set(500/2, 210);
- bd.userData = g.mgr.createBox(5, 25);
- var body = world.CreateBody(bd);
-
- rjd.anchorPoint.Set(500/2, 235);
- rjd.body1 = prevBody;
- rjd.body2 = body;
- rjd.motorSpeed = -1.0 * Math.PI;
- rjd.motorTorque = 500000000.0;
- rjd.enableMotor = true;
- world.CreateJoint(rjd);
-
- prevBody = body;
-
- // Define follower.
- sd.extents.Set(5, 45);
- bd.position.Set(500/2, 140);
- bd.userData = g.mgr.createBox(5, 45);
- body = world.CreateBody(bd);
-
- rjd.anchorPoint.Set(500/2, 185);
- rjd.body1 = prevBody;
- rjd.body2 = body;
- rjd.enableMotor = false;
- world.CreateJoint(rjd);
-
- prevBody = body;
-
- // Define piston
- sd.extents.Set(20, 20);
- bd.position.Set(500/2, 95);
- bd.userData = g.mgr.createBox(20, 20);
- body = world.CreateBody(bd);
-
- rjd.anchorPoint.Set(500/2, 95);
- rjd.body1 = prevBody;
- rjd.body2 = body;
- world.CreateJoint(rjd);
-
- var pjd = new b2PrismaticJointDef();
- pjd.anchorPoint.Set(500/2, 95);
- pjd.body1 = ground;
- pjd.body2 = body;
- pjd.axis.Set(0.0, 1.0);
- pjd.motorSpeed = 0.0; // joint friction
- pjd.motorForce = 100000.0;
- pjd.enableMotor = true;
-
- world.CreateJoint(pjd);
-
- // Create a payload
- sd.density = 2.0;
- bd.position.Set(500/2, 10);
- bd.userData = g.mgr.createBox(20, 20);
- world.CreateBody(bd);
-}
-demos.InitWorlds.push(demos.crank.initWorld);
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/demo_base.js b/o3d/samples/o3d-webgl-samples/box2d-3d/demos/demo_base.js
deleted file mode 100644
index 3379691..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/demo_base.js
+++ /dev/null
@@ -1,59 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-function createWorld() {
- var worldAABB = new b2AABB();
- worldAABB.minVertex.Set(-1000, -1000);
- worldAABB.maxVertex.Set(1000, 1000);
- var gravity = new b2Vec2(0, 300);
- var doSleep = true;
- var world = new b2World(worldAABB, gravity, doSleep);
- createGround(world);
- createBox(world, 0, 125, 10, 250);
- createBox(world, 500, 125, 10, 250);
- return world;
-}
-
-function createGround(world) {
- var groundSd = new b2BoxDef();
- groundSd.extents.Set(250, 50);
- groundSd.restitution = 0.2;
- var groundBd = new b2BodyDef();
- groundBd.AddShape(groundSd);
- groundBd.position.Set(250, 340);
- // NOTE: Added the following line to create a 3d object to display.
- groundBd.userData = g.mgr.createBox(250, 50);
- return world.CreateBody(groundBd)
-}
-
-function createBall(world, x, y) {
- var ballSd = new b2CircleDef();
- ballSd.density = 1.0;
- ballSd.radius = 20;
- ballSd.restitution = 1.0;
- ballSd.friction = 0;
- var ballBd = new b2BodyDef();
- ballBd.AddShape(ballSd);
- ballBd.position.Set(x,y);
- // NOTE: Added the following line to create a 3d object to display.
- ballBd.userData = g.mgr.createCylinder(ballSd.radius);
- return world.CreateBody(ballBd);
-}
-
-function createBox(world, x, y, width, height, fixed) {
- if (typeof(fixed) == 'undefined') fixed = true;
- var boxSd = new b2BoxDef();
- if (!fixed) boxSd.density = 1.0;
- boxSd.extents.Set(width, height);
- var boxBd = new b2BodyDef();
- // NOTE: Added the following line to create a 3d object to display.
- boxBd.userData = g.mgr.createBox(width, height);
- boxBd.AddShape(boxSd);
- boxBd.position.Set(x,y);
- return world.CreateBody(boxBd)
-}
-
-var demos = {};
-demos.InitWorlds = [];
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/demos.js b/o3d/samples/o3d-webgl-samples/box2d-3d/demos/demos.js
deleted file mode 100644
index ac64cc7..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/demos.js
+++ /dev/null
@@ -1,274 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-o3djs.base.o3d = o3d;
-
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.picking');
-
-var initId = 0;
-var world;
-var canvasWidth;
-var canvasHeight;
-var canvasTop;
-var canvasLeft;
-
-function setupWorld(did) {
- var transforms = g.client.getObjectsByClassName('o3d.Transform');
- for (var tt = 0; tt < transforms.length; ++tt) {
- var transform = transforms[tt];
- if (transform.clientId != g.root.clientId &&
- transform.clientId != g.client.root.clientId) {
- transform.parent = null;
- g.pack.removeObject(transform);
- }
- }
- if (!did) did = 0;
- world = createWorld();
- initId += did;
- initId %= demos.InitWorlds.length;
- if (initId < 0) initId = demos.InitWorlds.length + initId;
- demos.InitWorlds[initId](world);
-}
-function setupNextWorld() { setupWorld(1); }
-function setupPrevWorld() { setupWorld(-1); }
-function step(elapsedTime) {
- // NOTE: changed to use the renderEvent's elapsed time instead of
- // javascript timers. The check below makes the physics never do a time step
- // slower that 1/30th of a second because collision bugs will happen.
- if (elapsedTime > 1 / 30) {
- elapsedTime = 1 / 30;
- }
- var stepping = false;
- var timeStep = elapsedTime;
- var iteration = 1;
- if (world) {
- world.Step(timeStep, iteration);
- drawWorld(world);
- }
-}
-
-// When the sample is running in V8, window.g is the browser's global object and
-// g is v8's. When the sample is running only in the browser, they are the same
-// object.
-window.g = {};
-
-// A global object to track stuff with.
-var g = {
- o3dWidth: -1, // width of our client area
- o3dHeight: -1, // height of our client area
- materials: [], // all our materials
- shapes: [] // all our shapes
-};
-
-/**
- * Sets up the o3d stuff.
- * @param {HTML element} o3dElement The o3d object element.
- */
-function setupO3D(o3dElement) {
- // Initializes global variables and libraries.
- g.o3dElement = o3dElement;
- g.o3d = o3dElement.o3d;
- g.math = o3djs.math;
- g.client = o3dElement.client;
- g.mgr = new O3DManager();
-
- // The browser needs to be able to see these globals so that it can
- // call unload later.
- window.g.client = g.client;
-
- // Get the width and height of our client area.
- g.o3dWidth = g.client.width;
- g.o3dHeight = g.client.height;
-
- // Creates a pack to manage our resources/assets
- g.pack = g.client.createPack();
-
- // Create the render graph for a view.
- g.viewInfo = o3djs.rendergraph.createBasicView(
- g.pack,
- g.client.root,
- g.client.renderGraphRoot);
-
- // Create an object to hold global params.
- g.globalParamObject = g.pack.createObject('ParamObject');
- g.lightWorldPosParam = g.globalParamObject.createParam('lightWorldPos',
- 'ParamFloat3');
- g.lightColorParam = g.globalParamObject.createParam('lightColor',
- 'ParamFloat4');
- g.lightWorldPosParam.value = [200, -1500, -1000];
- g.lightColorParam.value = [1, 1, 1.0, 1.0];
-
- // Create Materials.
- g.materials = [];
- var material = g.pack.createObject('Material');
- var effect = g.pack.createObject('Effect');
- effect.loadFromFXString(document.getElementById('shader').value);
- material.effect = effect;
- effect.createUniformParameters(material);
- material.getParam('lightWorldPos').bind(g.lightWorldPosParam);
- material.getParam('lightColor').bind(g.lightColorParam);
- material.getParam('emissive').value = [0, 0, 0, 1];
- material.getParam('ambient').value = [0, 0, 0, 1];
- material.getParam('specular').value = [1, 1, 1, 1];
- material.getParam('shininess').value = 20;
- material.drawList = g.viewInfo.performanceDrawList;
- g.materials[0] = material;
-
- // Create a kind of checkboardish texture.
- var pixels = [];
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 3; // rgb
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = 1;//Math.sin(Math.PI * 32 / x) * 0.2 + 0.8; // red
- pixels[offset + 1] = Math.floor(x / 8) % 2 * 0.2 + 0.8; // green
- pixels[offset + 2] = Math.floor(y / 8) % 2 * 0.5 + 0.5; // blue
- }
- }
- var texture = g.pack.createTexture2D(32, 32, g.o3d.Texture.XRGB8, 1, false);
- texture.set(0, pixels);
- var samplerParam = material.getParam('diffuseSampler');
- var sampler = g.pack.createObject('Sampler');
- samplerParam.value = sampler;
- sampler.texture = texture;
-
- // Creates a transform to put our data on.
- g.root = g.pack.createObject('Transform');
- g.root.parent = g.client.root;
-
- // make a cube for drawing lines
- g.lineShape = o3djs.primitives.createRainbowCube(
- g.pack,
- g.materials[0],
- 1,
- g.math.matrix4.translation([0, 0.5, 0]));
-
- // Set the projection matrix
- g.viewInfo.drawContext.projection = g.math.matrix4.perspective(
- g.math.degToRad(45),
- g.o3dWidth / g.o3dHeight,
- 0.1,
- 10000);
-
- // Set the view matrix.
- g.viewInfo.drawContext.view = g.math.matrix4.lookAt(
- [100, -50, -600],
- [250, 80, 0],
- [0, -1, 0]);
-
- // Make copies of the view and projection matrix to get fast access to them.
- g.projectionMatrix = g.math.matrix4.copy(g.viewInfo.drawContext.projection);
- g.viewMatrix = g.math.matrix4.copy(g.viewInfo.drawContext.view);
-
- // Make a bounding box to use for picking.
- g.worldBox = new g.o3d.BoundingBox([0, -100, 0],
- [500, 250, 5]);
-
- // Steps the physics with a time of zero. This is left over from the orignial
- // code.
- step(0);
-
- g.client.setRenderCallback(o3dOnRender);
-}
-
-/**
- * Called just before rendering each frame.
- * @param {o3d.RenderEvent} renderEvent The render event passed by
- * o3d.
- */
-function o3dOnRender(renderEvent) {
- var newWidth = g.client.width;
- var newHeight = g.client.height;
- if (newWidth != g.o3dWidth || newHeight != g.o3dHeight) {
- g.o3dWidth = newWidth;
- g.o3dHeight = newHeight;
-
- // Adjust the projection matrix.
- var projectionMatrix = g.math.matrix4.perspective(g.math.degToRad(45),
- g.o3dWidth / g.o3dHeight,
- 0.1,
- 10000);
- g.viewInfo.drawContext.projection = projectionMatrix;
- g.projectionMatrix = projectionMatrix;
- }
- step(renderEvent.elapsedTime);
-}
-
-/**
- * This is the original setup code modified to work with o3d.
- * @param {Array} clientElements Array of o3d objects.
- */
-function setupStep2(clientElements) {
- var canvasElm = clientElements[0];
- canvasElm.id = 'canvas';
- setupO3D(canvasElm);
- setupWorld();
- canvasWidth = g.client.width;
- canvasHeight = g.client.height;
- canvasTop = parseInt(canvasElm.style.top);
- canvasLeft = parseInt(canvasElm.style.left);
- o3djs.event.addEventListener(canvasElm, 'mousedown', function(e) {
- if (e.shiftKey || e.button == g.o3d.Event.BUTTON_RIGHT) {
- setupPrevWorld();
- } else {
- createNewRandomObject(world, e);
- }
- });
-
- window.g_finished = true; // for selenium
-}
-
-/**
- * Creates a new random object using 3d picking to figure out where to start it.
- * @param {Object} world A B2World object.
- * @param {Object} offset Mouse position relative to o3d area.
- */
-function createNewRandomObject(world, offset) {
- var worldRay = o3djs.picking.clientPositionToWorldRayEx(
- offset.x,
- offset.y,
- g.viewMatrix,
- g.projectionMatrix,
- g.o3dWidth,
- g.o3dHeight);
- var rayIntersectionInfo = g.worldBox.intersectRay(worldRay.near,
- worldRay.far);
- if (rayIntersectionInfo.intersected) {
- var position = rayIntersectionInfo.position;
- if (Math.random() < 0.5) {
- demos.top.createBall(world, position[0], position[1]);
- } else {
- createBox(world, position[0], position[1], 10, 10, false);
- }
- }
-}
-
-function init() {
- window.g_finished = false; // for selenium.
-
- // Runs the sample in V8. Comment out this line to run it in the browser
- // JavaScript engine, for example if you want to debug it. This sample cannot
- // currently run in V8 on IE because it access the DOM.
- if (!o3djs.base.IsMSIE()) {
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
- o3djs.util.addScriptUri('third_party');
- o3djs.util.addScriptUri('demos');
- o3djs.util.addScriptUri('style');
- }
-
- o3djs.webgl.makeClients(setupStep2);
-}
-
-function uninit() {
- if (g.client) {
- g.client.cleanup();
- }
-}
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/draw_world.js b/o3d/samples/o3d-webgl-samples/box2d-3d/demos/draw_world.js
deleted file mode 100644
index b49ef1a..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/draw_world.js
+++ /dev/null
@@ -1,90 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-// NOTE: Changed this file pretty significantly. The original uses a
-// canvas element and drew lines on it. This one just updates the positions and
-// orientations of o3d objects to match the physics as well as using a
-// scaled box to stand in for joints.
-
-/**
- * Draws all the object in the world.
- * @param {Object} world A B2World object managing the physics world.
- */
-function drawWorld(world) {
- for (var j = world.m_jointList; j; j = j.m_next) {
- drawJoint(j);
- }
- for (var b = world.m_bodyList; b; b = b.m_next) {
- var o3dShape = b.GetUserData();
- if (o3dShape) {
- o3dShape.updateTransform(b);
- }
- }
-}
-/**
- * Scales a joint transform to represnet a line.
- * @param {Object} transformInfo An object with o3d information for the
- * joint.
- * @param {Object} p1 An object with x and y fields that specify the origin of
- * the joint in 2d.
- * @param {Object} p2 An object with x an dy fields that specify the far end of
- * the joint in 2d.
- */
-function scaleJointTransform(transformInfo, p1, p2) {
- var dx = p2.x - p1.x;
- var dy = p2.y - p1.y;
- var length = Math.sqrt(dx * dx + dy * dy);
- var transform = transformInfo.transform;
- transform.identity();
- transform.translate(p1.x, p1.y, 0);
- transform.rotateZ(Math.atan2(-dx, dy));
- transform.scale(2, length, 2);
-}
-
-/**
- * Draws a joint
- * @param {Object} joint A b2Joint object representing a joint.
- */
-function drawJoint(joint) {
- var transformInfo = joint.m_o3dTransformInfo;
- if (!transformInfo) {
- // This joint did not already have something in o3d to represent it
- // so we create one here.
- var transform = g.pack.createObject('Transform');
- transform.parent = g.root;
- transform.addShape(g.lineShape);
- transformInfo = {
- transform: transform
- };
- joint.m_o3dTransformInfo = transformInfo;
- }
- var b1 = joint.m_body1;
- var b2 = joint.m_body2;
- var x1 = b1.m_position;
- var x2 = b2.m_position;
- var p1 = joint.GetAnchor1();
- var p2 = joint.GetAnchor2();
- switch (joint.m_type) {
- case b2Joint.e_distanceJoint:
- scaleJointTransform(transformInfo, p1, p2);
- break;
-
- case b2Joint.e_pulleyJoint:
- break;
-
- default:
- if (b1 == world.m_groundBody) {
- scaleJointTransform(transformInfo, p1, x2);
- }
- else if (b2 == world.m_groundBody) {
- scaleJointTransform(transformInfo, p1, x1);
- }
- else {
- scaleJointTransform(transformInfo, x1, x2);
- }
- break;
- }
-}
-
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/manager.js b/o3d/samples/o3d-webgl-samples/box2d-3d/demos/manager.js
deleted file mode 100644
index c8bb604..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/manager.js
+++ /dev/null
@@ -1,210 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-/**
- * O3DManager manages o3d objects for this demo.
- * @constructor
- */
-function O3DManager() {
- this.shapes = {};
-}
-
-/**
- * Gets or creates a cylinder shape. If a cylinder of the same radius already
- * exists that one will be returned, otherwise a new one will be created.
- * @param {number} radius Radius of cylinder to create.
- * @return {o3d.Shape} The shape.
- */
-O3DManager.prototype.createCylinder = function(radius) {
- var id = 'cylinder-' + radius;
- var shape = this.shapes[id];
- if (!shape) {
- shape = o3djs.primitives.createCylinder(g.pack,
- g.materials[0],
- radius, 40, 20, 1,
- o3djs.math.makeMatrix4(1, 0, 0, 0,
- 0, 0, 1, 0,
- 0, -1, 0, 0,
- 0, 0, 0, 1));
- this.shapes[id] = shape;
- }
- return new O3DShape({shape: shape});
-};
-
-/**
- * Gets or creates a compound cylinder shape. If a compound cylinder shape of
- * the same parameters already exists that one will be returned, otherwise a new
- * one will be created.
- * @param {number} radius1 Radius of first cylinder.
- * @param {number} offset1 X Offset for first cylinder.
- * @param {number} radius2 Radius of second cylinder.
- * @param {number} offset2 X Offset for second cylinder.
- * @return {o3d.Shape} The shape.
- */
-O3DManager.prototype.createCompoundCylinder = function(radius1,
- offset1,
- radius2,
- offset2) {
- var id = 'compoundCylinder-' + radius1 + '-' + offset1 +
- '-' + radius2 + '-' + offset2;
- var shape = this.shapes[id];
- if (!shape) {
- shape = o3djs.primitives.createCylinder(
- g.pack, g.materials[0], radius1, 40, 20, 1,
- o3djs.math.makeMatrix4(1, 0, 0, 0,
- 0, 0, 1, 0,
- 0, -1, 0, 0,
- offset1, 0, 0, 1));
- shape2 = o3djs.primitives.createCylinder(
- g.pack, g.materials[0], radius2, 40, 20, 1,
- o3djs.math.makeMatrix4(1, 0, 0, 0,
- 0, 0, 1, 0,
- 0, -1, 0, 0,
- offset2, 0, 0, 1));
- shape2.elements[0].owner = shape;
- g.pack.removeObject(shape2);
- this.shapes[id] = shape;
- }
- return new O3DShape({shape: shape});
-};
-
-/**
- * Gets or creates a box shape. If a box of the same width and height already
- * exists that one will be returned, otherwise a new one will be created.
- * @param {number} width Width of box.
- * @param {number} height Height of box.
- * @return {o3d.Shape} The shape.
- */
-O3DManager.prototype.createBox = function(width, height) {
- var name = 'box-' + width + '-' + height;
- var shape = this.shapes[name];
- if (!shape) {
- shape = o3djs.primitives.createBox(g.pack,
- g.materials[0],
- width * 2, height * 2, 40);
- this.shapes[name] = shape;
- }
- return new O3DShape({shape: shape});
-};
-
-/**
- * Gets or creates a wedge shape. If a wedge of the same parametrs already
- * exists that one will be returned, otherwise a new one will be created.
- * @param {Array} points Array of points in the format
- * [[x1, y1], [x2, y2], [x3, y3]] that describe a 2d triangle.
- * @return {o3d.Shape} The shape.
- */
-O3DManager.prototype.createWedge = function(points) {
- var name = 'wedge';
- for (var pp = 0; pp < points.length; ++pp) {
- name += '-' + points[pp][0] + '-' + points[pp][1];
- }
- var shape = this.shapes[name];
- if (!shape) {
- shape = o3djs.primitives.createPrism(g.pack,
- g.materials[0],
- points, 40);
- this.shapes[name] = shape;
- }
- return new O3DShape({shape: shape});
-};
-
-/**
- * Gets or creates a compound wedge shape (2 wedges). If a compound wedge of the
- * same parametrs already exists that one will be returned, otherwise a new one
- * will be created.
- * @param {Array} points1 Array of points that describe a 2d triangle for the
- * first wedge in the format [[x1, y1], [x2, y2], [x3, y3]] .
- * @param {Object} position1 An object with x and y properties used to offset
- * the first wedge.
- * @param {number} rotation1 Rotation in radians to rotate the first wedge on
- * the z axis.
- * @param {Array} points2 Array of points that describe a 2d triangle for the
- * second wedge in the format [[x1, y1], [x2, y2], [x3, y3]] .
- * @param {Object} position2 An object with x and y properties used to offset
- * the second wedge.
- * @param {number} rotation2 Rotation in radians to rotate the second wedge on
- * the z axis.
- * @return {o3d.Shape} The shape.
- */
-O3DManager.prototype.createCompoundWedge = function(points1,
- position1,
- rotation1,
- points2,
- position2,
- rotation2) {
- var name = 'compoundWedge';
- for (var pp = 0; pp < points1.length; ++pp) {
- name += '-' + points1[pp][0] + '-' + points1[pp][1];
- }
- name += '-' + position1.x + '-' + position1.y + '-' + rotation1;
- for (var pp = 0; pp < points2.length; ++pp) {
- name += '-' + points2[pp][0] + '-' + points2[pp][1];
- }
- name += '-' + position2.x + '-' + position2.y + '-' + rotation2;
- var shape = this.shapes[name];
- if (!shape) {
- shape = o3djs.primitives.createPrism(
- g.pack,
- g.materials[0],
- points1,
- 40,
- g.math.matrix4.mul(
- g.math.matrix4.rotationZ(rotation1),
- g.math.matrix4.translation([position1.x, position1.y, 0])));
- shape2 = o3djs.primitives.createPrism(
- g.pack,
- g.materials[0],
- points2,
- 40,
- g.math.matrix4.mul(
- g.math.matrix4.rotationZ(rotation2),
- g.math.matrix4.translation([position2.x, position2.y, 0])));
- shape2.elements[0].owner = shape;
- g.pack.removeObject(shape2);
- this.shapes[name] = shape;
- }
- return new O3DShape({shape: shape});
-};
-
-/**
- * An O3DShape manages an O3D shape for the demo.
- * @constructor
- * @param {Object} spec An object that contains the fields needed to create the
- * O3DShape. Currently only the field "shape" is needed.
- */
-function O3DShape(spec) {
- this.init(spec);
-}
-
-/**
- * Initializes an O3DShape
- * @param {Object} spec An object that contains the fields needed to create the
- * O3DShape. Currently only the field "shape" is needed.
- */
-O3DShape.prototype.init = function(spec) {
- this.transform = g.pack.createObject('Transform');
- this.transform.parent = g.root;
- this.transform.addShape(spec.shape);
- this.transform.createParam('colorMult', 'ParamFloat4').value =
- [Math.random() * 0.8 + 0.2,
- Math.random() * 0.8 + 0.2,
- Math.random() * 0.8 + 0.2,
- 1];
-};
-
-/**
- * Updates the position and orientation of an O3DShape.
- * @param {Object} body A B2Body object from the Box2djs library.
- */
-O3DShape.prototype.updateTransform = function(body) {
- var transform = this.transform;
- var position = body.GetOriginPosition();
- transform.identity();
- transform.translate(position.x, position.y, 0);
- transform.rotateZ(body.GetRotation());
-};
-
-
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/pendulum.js b/o3d/samples/o3d-webgl-samples/box2d-3d/demos/pendulum.js
deleted file mode 100644
index 730d039..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/pendulum.js
+++ /dev/null
@@ -1,25 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-demos.pendulum = {};
-demos.pendulum.initWorld = function(world) {
- var i;
- var ground = world.GetGroundBody();
- var jointDef = new b2RevoluteJointDef();
- var L = 150;
- for (i = 0; i < 4; i++) {
- jointDef.anchorPoint.Set(250 + 40 * i, 200 - L);
- jointDef.body1 = ground;
- jointDef.body2 = createBall(world, 250 + 40 * i, 200);
- world.CreateJoint(jointDef);
- }
- jointDef.anchorPoint.Set(250 - 40, 200 - L);
- jointDef.body1 = ground;
- jointDef.body2 = createBall(world, 250 - 40 - L, 200 - L);
- world.CreateJoint(jointDef);
-}
-demos.InitWorlds.push(demos.pendulum.initWorld);
-
-
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/stack.js b/o3d/samples/o3d-webgl-samples/box2d-3d/demos/stack.js
deleted file mode 100644
index ffee25b..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/stack.js
+++ /dev/null
@@ -1,37 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-demos.stack = {};
-demos.stack.initWorld = function(world) {
- var sd = new b2BoxDef();
- var bd = new b2BodyDef();
- bd.AddShape(sd);
- sd.density = 1.0;
- sd.friction = 0.5;
- sd.extents.Set(10, 10);
-
- var i;
- for (i = 0; i < 8; i++) {
- bd.position.Set(500/2-Math.random()*2-1, (250-5-i*22));
- // NOTE: Added the following line to create a 3d object to display.
- bd.userData = g.mgr.createBox(10, 10);
- world.CreateBody(bd);
- }
- for (i = 0; i < 8; i++) {
- bd.position.Set(500/2-100-Math.random()*5+i, (250-5-i*22));
- // NOTE: Added the following line to create a 3d object to display.
- bd.userData = g.mgr.createBox(10, 10);
- world.CreateBody(bd);
- }
- for (i = 0; i < 8; i++) {
- bd.position.Set(500/2+100+Math.random()*5-i, (250-5-i*22));
- // NOTE: Added the following line to create a 3d object to display.
- bd.userData = g.mgr.createBox(10, 10);
- world.CreateBody(bd);
- }
-}
-demos.InitWorlds.push(demos.stack.initWorld);
-
-
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/top.js b/o3d/samples/o3d-webgl-samples/box2d-3d/demos/top.js
deleted file mode 100644
index e569e7e..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/demos/top.js
+++ /dev/null
@@ -1,53 +0,0 @@
-// This file comes from Box2D-JS, Copyright (c) 2008 ANDO Yasushi.
-// The original version is available at http://box2d-js.sourceforge.net/ under the
-// zlib/libpng license (see License.txt).
-// This version has been modified to make it work with O3D.
-
-demos.top = {};
-demos.top.createBall = function(world, x, y, rad, fixed) {
- var ballSd = new b2CircleDef();
- if (!fixed) ballSd.density = 1.0;
- ballSd.radius = rad || 10;
- ballSd.restitution = 0.2;
- var ballBd = new b2BodyDef();
- ballBd.AddShape(ballSd);
- ballBd.position.Set(x,y);
- // NOTE: Added the following line to create a 3d object to display.
- ballBd.userData = g.mgr.createCylinder(ballSd.radius);
- return world.CreateBody(ballBd);
-};
-demos.top.createPoly = function(world, x, y, points, fixed) {
- var polySd = new b2PolyDef();
- if (!fixed) polySd.density = 1.0;
- polySd.vertexCount = points.length;
- for (var i = 0; i < points.length; i++) {
- polySd.vertices[i].Set(points[i][0], points[i][1]);
- }
- var polyBd = new b2BodyDef();
- if (points.length == 3) {
- // NOTE: Added the following line to create a 3d object to display.
- polyBd.userData = g.mgr.createWedge(points);
- }
- polyBd.AddShape(polySd);
- polyBd.position.Set(x,y);
- return world.CreateBody(polyBd)
-};
-demos.top.initWorld = function(world) {
- demos.top.createBall(world, 350, 100, 50, true);
- demos.top.createPoly(world, 100, 100, [[0, 0], [10, 30], [-10, 30]], true);
- demos.top.createPoly(world, 150, 150, [[0, 0], [10, 30], [-10, 30]], true);
- var pendulum = createBox(world, 150, 100, 20, 20, false);
- var jointDef = new b2RevoluteJointDef();
- jointDef.body1 = pendulum;
- jointDef.body2 = world.GetGroundBody();
- jointDef.anchorPoint = pendulum.GetCenterPosition();
- world.CreateJoint(jointDef);
-
- var seesaw = demos.top.createPoly(world, 300, 200, [[0, 0], [100, 30], [-100, 30]]);
- jointDef.body1 = seesaw;
- jointDef.anchorPoint = seesaw.GetCenterPosition();
- world.CreateJoint(jointDef);
-};
-demos.InitWorlds.push(demos.top.initWorld);
-
-
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/third_party/box2d/LICENSE.txt b/o3d/samples/o3d-webgl-samples/box2d-3d/third_party/box2d/LICENSE.txt
deleted file mode 100644
index c224b40..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/third_party/box2d/LICENSE.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-The zlib/libpng License
-
-Copyright (c) 2008 ANDO Yasushi
-
-This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
-
-Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
-
- 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
-
- 3. This notice may not be removed or altered from any source distribution.
-
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/third_party/box2d/README.o3d b/o3d/samples/o3d-webgl-samples/box2d-3d/third_party/box2d/README.o3d
deleted file mode 100644
index 0f3fdc7..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/third_party/box2d/README.o3d
+++ /dev/null
@@ -1,5 +0,0 @@
-This directory contains a subset of Box2D-JS, available at
-http://box2d-js.sourceforge.net/ under the zlib/libpng license (see
-License.txt).
-The software was not modified, but only the portions under js/box2d in the
-original distribution are here.
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/third_party/box2d/box2d.js b/o3d/samples/o3d-webgl-samples/box2d-3d/third_party/box2d/box2d.js
deleted file mode 100644
index 6e35c2b..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/third_party/box2d/box2d.js
+++ /dev/null
@@ -1,1037 +0,0 @@
-/*
- * Box2Djs (port of Box2DFlash 1.4.3.1) - http://box2d-js.sourceforge.net/
- * Single-filed and jsmined ( http://code.google.com/p/jsmin-php/ ) by Mr.doob
- */
-
-var b2Settings=Class.create();b2Settings.prototype={initialize:function(){}}
-b2Settings.USHRT_MAX=0x0000ffff;b2Settings.b2_pi=Math.PI;b2Settings.b2_massUnitsPerKilogram=1.0;b2Settings.b2_timeUnitsPerSecond=1.0;b2Settings.b2_lengthUnitsPerMeter=30.0;b2Settings.b2_maxManifoldPoints=2;b2Settings.b2_maxShapesPerBody=64;b2Settings.b2_maxPolyVertices=8;b2Settings.b2_maxProxies=1024;b2Settings.b2_maxPairs=8*b2Settings.b2_maxProxies;b2Settings.b2_linearSlop=0.005*b2Settings.b2_lengthUnitsPerMeter;b2Settings.b2_angularSlop=2.0/180.0*b2Settings.b2_pi;b2Settings.b2_velocityThreshold=1.0*b2Settings.b2_lengthUnitsPerMeter/b2Settings.b2_timeUnitsPerSecond;b2Settings.b2_maxLinearCorrection=0.2*b2Settings.b2_lengthUnitsPerMeter;b2Settings.b2_maxAngularCorrection=8.0/180.0*b2Settings.b2_pi;b2Settings.b2_contactBaumgarte=0.2;b2Settings.b2_timeToSleep=0.5*b2Settings.b2_timeUnitsPerSecond;b2Settings.b2_linearSleepTolerance=0.01*b2Settings.b2_lengthUnitsPerMeter/b2Settings.b2_timeUnitsPerSecond;b2Settings.b2_angularSleepTolerance=2.0/180.0/b2Settings.b2_timeUnitsPerSecond;b2Settings.b2Assert=function(a)
-{if(!a){var nullVec;nullVec.x++;}};
-var b2Vec2=Class.create();b2Vec2.prototype={initialize:function(x_,y_){this.x=x_;this.y=y_;},SetZero:function(){this.x=0.0;this.y=0.0;},Set:function(x_,y_){this.x=x_;this.y=y_;},SetV:function(v){this.x=v.x;this.y=v.y;},Negative:function(){return new b2Vec2(-this.x,-this.y);},Copy:function(){return new b2Vec2(this.x,this.y);},Add:function(v)
-{this.x+=v.x;this.y+=v.y;},Subtract:function(v)
-{this.x-=v.x;this.y-=v.y;},Multiply:function(a)
-{this.x*=a;this.y*=a;},MulM:function(A)
-{var tX=this.x;this.x=A.col1.x*tX+A.col2.x*this.y;this.y=A.col1.y*tX+A.col2.y*this.y;},MulTM:function(A)
-{var tX=b2Math.b2Dot(this,A.col1);this.y=b2Math.b2Dot(this,A.col2);this.x=tX;},CrossVF:function(s)
-{var tX=this.x;this.x=s*this.y;this.y=-s*tX;},CrossFV:function(s)
-{var tX=this.x;this.x=-s*this.y;this.y=s*tX;},MinV:function(b)
-{this.x=this.x<b.x?this.x:b.x;this.y=this.y<b.y?this.y:b.y;},MaxV:function(b)
-{this.x=this.x>b.x?this.x:b.x;this.y=this.y>b.y?this.y:b.y;},Abs:function()
-{this.x=Math.abs(this.x);this.y=Math.abs(this.y);},Length:function()
-{return Math.sqrt(this.x*this.x+this.y*this.y);},Normalize:function()
-{var length=this.Length();if(length<Number.MIN_VALUE)
-{return 0.0;}
-var invLength=1.0/length;this.x*=invLength;this.y*=invLength;return length;},IsValid:function()
-{return b2Math.b2IsValid(this.x)&&b2Math.b2IsValid(this.y);},x:null,y:null};b2Vec2.Make=function(x_,y_)
-{return new b2Vec2(x_,y_);};
-var b2Mat22=Class.create();b2Mat22.prototype={initialize:function(angle,c1,c2)
-{if(angle==null)angle=0;this.col1=new b2Vec2();this.col2=new b2Vec2();if(c1!=null&&c2!=null){this.col1.SetV(c1);this.col2.SetV(c2);}
-else{var c=Math.cos(angle);var s=Math.sin(angle);this.col1.x=c;this.col2.x=-s;this.col1.y=s;this.col2.y=c;}},Set:function(angle)
-{var c=Math.cos(angle);var s=Math.sin(angle);this.col1.x=c;this.col2.x=-s;this.col1.y=s;this.col2.y=c;},SetVV:function(c1,c2)
-{this.col1.SetV(c1);this.col2.SetV(c2);},Copy:function(){return new b2Mat22(0,this.col1,this.col2);},SetM:function(m)
-{this.col1.SetV(m.col1);this.col2.SetV(m.col2);},AddM:function(m)
-{this.col1.x+=m.col1.x;this.col1.y+=m.col1.y;this.col2.x+=m.col2.x;this.col2.y+=m.col2.y;},SetIdentity:function()
-{this.col1.x=1.0;this.col2.x=0.0;this.col1.y=0.0;this.col2.y=1.0;},SetZero:function()
-{this.col1.x=0.0;this.col2.x=0.0;this.col1.y=0.0;this.col2.y=0.0;},Invert:function(out)
-{var a=this.col1.x;var b=this.col2.x;var c=this.col1.y;var d=this.col2.y;var det=a*d-b*c;det=1.0/det;out.col1.x=det*d;out.col2.x=-det*b;out.col1.y=-det*c;out.col2.y=det*a;return out;},Solve:function(out,bX,bY)
-{var a11=this.col1.x;var a12=this.col2.x;var a21=this.col1.y;var a22=this.col2.y;var det=a11*a22-a12*a21;det=1.0/det;out.x=det*(a22*bX-a12*bY);out.y=det*(a11*bY-a21*bX);return out;},Abs:function()
-{this.col1.Abs();this.col2.Abs();},col1:new b2Vec2(),col2:new b2Vec2()};
-var b2Math=Class.create();b2Math.prototype={initialize:function(){}}
-b2Math.b2IsValid=function(x)
-{return isFinite(x);};b2Math.b2Dot=function(a,b)
-{return a.x*b.x+a.y*b.y;};b2Math.b2CrossVV=function(a,b)
-{return a.x*b.y-a.y*b.x;};b2Math.b2CrossVF=function(a,s)
-{var v=new b2Vec2(s*a.y,-s*a.x);return v;};b2Math.b2CrossFV=function(s,a)
-{var v=new b2Vec2(-s*a.y,s*a.x);return v;};b2Math.b2MulMV=function(A,v)
-{var u=new b2Vec2(A.col1.x*v.x+A.col2.x*v.y,A.col1.y*v.x+A.col2.y*v.y);return u;};b2Math.b2MulTMV=function(A,v)
-{var u=new b2Vec2(b2Math.b2Dot(v,A.col1),b2Math.b2Dot(v,A.col2));return u;};b2Math.AddVV=function(a,b)
-{var v=new b2Vec2(a.x+b.x,a.y+b.y);return v;};b2Math.SubtractVV=function(a,b)
-{var v=new b2Vec2(a.x-b.x,a.y-b.y);return v;};b2Math.MulFV=function(s,a)
-{var v=new b2Vec2(s*a.x,s*a.y);return v;};b2Math.AddMM=function(A,B)
-{var C=new b2Mat22(0,b2Math.AddVV(A.col1,B.col1),b2Math.AddVV(A.col2,B.col2));return C;};b2Math.b2MulMM=function(A,B)
-{var C=new b2Mat22(0,b2Math.b2MulMV(A,B.col1),b2Math.b2MulMV(A,B.col2));return C;};b2Math.b2MulTMM=function(A,B)
-{var c1=new b2Vec2(b2Math.b2Dot(A.col1,B.col1),b2Math.b2Dot(A.col2,B.col1));var c2=new b2Vec2(b2Math.b2Dot(A.col1,B.col2),b2Math.b2Dot(A.col2,B.col2));var C=new b2Mat22(0,c1,c2);return C;};b2Math.b2Abs=function(a)
-{return a>0.0?a:-a;};b2Math.b2AbsV=function(a)
-{var b=new b2Vec2(b2Math.b2Abs(a.x),b2Math.b2Abs(a.y));return b;};b2Math.b2AbsM=function(A)
-{var B=new b2Mat22(0,b2Math.b2AbsV(A.col1),b2Math.b2AbsV(A.col2));return B;};b2Math.b2Min=function(a,b)
-{return a<b?a:b;};b2Math.b2MinV=function(a,b)
-{var c=new b2Vec2(b2Math.b2Min(a.x,b.x),b2Math.b2Min(a.y,b.y));return c;};b2Math.b2Max=function(a,b)
-{return a>b?a:b;};b2Math.b2MaxV=function(a,b)
-{var c=new b2Vec2(b2Math.b2Max(a.x,b.x),b2Math.b2Max(a.y,b.y));return c;};b2Math.b2Clamp=function(a,low,high)
-{return b2Math.b2Max(low,b2Math.b2Min(a,high));};b2Math.b2ClampV=function(a,low,high)
-{return b2Math.b2MaxV(low,b2Math.b2MinV(a,high));};b2Math.b2Swap=function(a,b)
-{var tmp=a[0];a[0]=b[0];b[0]=tmp;};b2Math.b2Random=function()
-{return Math.random()*2-1;};b2Math.b2NextPowerOfTwo=function(x)
-{x|=(x>>1)&0x7FFFFFFF;x|=(x>>2)&0x3FFFFFFF;x|=(x>>4)&0x0FFFFFFF;x|=(x>>8)&0x00FFFFFF;x|=(x>>16)&0x0000FFFF;return x+1;};b2Math.b2IsPowerOfTwo=function(x)
-{var result=x>0&&(x&(x-1))==0;return result;};b2Math.tempVec2=new b2Vec2();b2Math.tempVec3=new b2Vec2();b2Math.tempVec4=new b2Vec2();b2Math.tempVec5=new b2Vec2();b2Math.tempMat=new b2Mat22();
-var b2AABB=Class.create();b2AABB.prototype={IsValid:function(){var dX=this.maxVertex.x;var dY=this.maxVertex.y;dX=this.maxVertex.x;dY=this.maxVertex.y;dX-=this.minVertex.x;dY-=this.minVertex.y;var valid=dX>=0.0&&dY>=0.0;valid=valid&&this.minVertex.IsValid()&&this.maxVertex.IsValid();return valid;},minVertex:new b2Vec2(),maxVertex:new b2Vec2(),initialize:function(){this.minVertex=new b2Vec2();this.maxVertex=new b2Vec2();}};
-var b2Bound=Class.create();b2Bound.prototype={IsLower:function(){return(this.value&1)==0;},IsUpper:function(){return(this.value&1)==1;},Swap:function(b){var tempValue=this.value;var tempProxyId=this.proxyId;var tempStabbingCount=this.stabbingCount;this.value=b.value;this.proxyId=b.proxyId;this.stabbingCount=b.stabbingCount;b.value=tempValue;b.proxyId=tempProxyId;b.stabbingCount=tempStabbingCount;},value:0,proxyId:0,stabbingCount:0,initialize:function(){}}
-
-var b2BoundValues=Class.create();b2BoundValues.prototype={lowerValues:[0,0],upperValues:[0,0],initialize:function(){this.lowerValues=[0,0];this.upperValues=[0,0];}}
-
-var b2Pair=Class.create();b2Pair.prototype={SetBuffered:function(){this.status|=b2Pair.e_pairBuffered;},ClearBuffered:function(){this.status&=~b2Pair.e_pairBuffered;},IsBuffered:function(){return(this.status&b2Pair.e_pairBuffered)==b2Pair.e_pairBuffered;},SetRemoved:function(){this.status|=b2Pair.e_pairRemoved;},ClearRemoved:function(){this.status&=~b2Pair.e_pairRemoved;},IsRemoved:function(){return(this.status&b2Pair.e_pairRemoved)==b2Pair.e_pairRemoved;},SetFinal:function(){this.status|=b2Pair.e_pairFinal;},IsFinal:function(){return(this.status&b2Pair.e_pairFinal)==b2Pair.e_pairFinal;},userData:null,proxyId1:0,proxyId2:0,next:0,status:0,initialize:function(){}};b2Pair.b2_nullPair=b2Settings.USHRT_MAX;b2Pair.b2_nullProxy=b2Settings.USHRT_MAX;b2Pair.b2_tableCapacity=b2Settings.b2_maxPairs;b2Pair.b2_tableMask=b2Pair.b2_tableCapacity-1;b2Pair.e_pairBuffered=0x0001;b2Pair.e_pairRemoved=0x0002;b2Pair.e_pairFinal=0x0004;
-var b2PairCallback=Class.create();b2PairCallback.prototype={PairAdded:function(proxyUserData1,proxyUserData2){return null},PairRemoved:function(proxyUserData1,proxyUserData2,pairUserData){},initialize:function(){}};
-var b2BufferedPair=Class.create();b2BufferedPair.prototype={proxyId1:0,proxyId2:0,initialize:function(){}}
-
-var b2PairManager=Class.create();b2PairManager.prototype={initialize:function(){var i=0;this.m_hashTable=new Array(b2Pair.b2_tableCapacity);for(i=0;i<b2Pair.b2_tableCapacity;++i)
-{this.m_hashTable[i]=b2Pair.b2_nullPair;}
-this.m_pairs=new Array(b2Settings.b2_maxPairs);for(i=0;i<b2Settings.b2_maxPairs;++i)
-{this.m_pairs[i]=new b2Pair();}
-this.m_pairBuffer=new Array(b2Settings.b2_maxPairs);for(i=0;i<b2Settings.b2_maxPairs;++i)
-{this.m_pairBuffer[i]=new b2BufferedPair();}
-for(i=0;i<b2Settings.b2_maxPairs;++i)
-{this.m_pairs[i].proxyId1=b2Pair.b2_nullProxy;this.m_pairs[i].proxyId2=b2Pair.b2_nullProxy;this.m_pairs[i].userData=null;this.m_pairs[i].status=0;this.m_pairs[i].next=(i+1);}
-this.m_pairs[b2Settings.b2_maxPairs-1].next=b2Pair.b2_nullPair;this.m_pairCount=0;},Initialize:function(broadPhase,callback){this.m_broadPhase=broadPhase;this.m_callback=callback;},AddBufferedPair:function(proxyId1,proxyId2){var pair=this.AddPair(proxyId1,proxyId2);if(pair.IsBuffered()==false)
-{pair.SetBuffered();this.m_pairBuffer[this.m_pairBufferCount].proxyId1=pair.proxyId1;this.m_pairBuffer[this.m_pairBufferCount].proxyId2=pair.proxyId2;++this.m_pairBufferCount;}
-pair.ClearRemoved();if(b2BroadPhase.s_validate)
-{this.ValidateBuffer();}},RemoveBufferedPair:function(proxyId1,proxyId2){var pair=this.Find(proxyId1,proxyId2);if(pair==null)
-{return;}
-if(pair.IsBuffered()==false)
-{pair.SetBuffered();this.m_pairBuffer[this.m_pairBufferCount].proxyId1=pair.proxyId1;this.m_pairBuffer[this.m_pairBufferCount].proxyId2=pair.proxyId2;++this.m_pairBufferCount;}
-pair.SetRemoved();if(b2BroadPhase.s_validate)
-{this.ValidateBuffer();}},Commit:function(){var i=0;var removeCount=0;var proxies=this.m_broadPhase.m_proxyPool;for(i=0;i<this.m_pairBufferCount;++i)
-{var pair=this.Find(this.m_pairBuffer[i].proxyId1,this.m_pairBuffer[i].proxyId2);pair.ClearBuffered();var proxy1=proxies[pair.proxyId1];var proxy2=proxies[pair.proxyId2];if(pair.IsRemoved())
-{if(pair.IsFinal()==true)
-{this.m_callback.PairRemoved(proxy1.userData,proxy2.userData,pair.userData);}
-this.m_pairBuffer[removeCount].proxyId1=pair.proxyId1;this.m_pairBuffer[removeCount].proxyId2=pair.proxyId2;++removeCount;}
-else
-{if(pair.IsFinal()==false)
-{pair.userData=this.m_callback.PairAdded(proxy1.userData,proxy2.userData);pair.SetFinal();}}}
-for(i=0;i<removeCount;++i)
-{this.RemovePair(this.m_pairBuffer[i].proxyId1,this.m_pairBuffer[i].proxyId2);}
-this.m_pairBufferCount=0;if(b2BroadPhase.s_validate)
-{this.ValidateTable();}},AddPair:function(proxyId1,proxyId2){if(proxyId1>proxyId2){var temp=proxyId1;proxyId1=proxyId2;proxyId2=temp;}
-var hash=b2PairManager.Hash(proxyId1,proxyId2)&b2Pair.b2_tableMask;var pair=pair=this.FindHash(proxyId1,proxyId2,hash);if(pair!=null)
-{return pair;}
-var pIndex=this.m_freePair;pair=this.m_pairs[pIndex];this.m_freePair=pair.next;pair.proxyId1=proxyId1;pair.proxyId2=proxyId2;pair.status=0;pair.userData=null;pair.next=this.m_hashTable[hash];this.m_hashTable[hash]=pIndex;++this.m_pairCount;return pair;},RemovePair:function(proxyId1,proxyId2){if(proxyId1>proxyId2){var temp=proxyId1;proxyId1=proxyId2;proxyId2=temp;}
-var hash=b2PairManager.Hash(proxyId1,proxyId2)&b2Pair.b2_tableMask;var node=this.m_hashTable[hash];var pNode=null;while(node!=b2Pair.b2_nullPair)
-{if(b2PairManager.Equals(this.m_pairs[node],proxyId1,proxyId2))
-{var index=node;if(pNode){pNode.next=this.m_pairs[node].next;}
-else{this.m_hashTable[hash]=this.m_pairs[node].next;}
-var pair=this.m_pairs[index];var userData=pair.userData;pair.next=this.m_freePair;pair.proxyId1=b2Pair.b2_nullProxy;pair.proxyId2=b2Pair.b2_nullProxy;pair.userData=null;pair.status=0;this.m_freePair=index;--this.m_pairCount;return userData;}
-else
-{pNode=this.m_pairs[node];node=pNode.next;}}
-return null;},Find:function(proxyId1,proxyId2){if(proxyId1>proxyId2){var temp=proxyId1;proxyId1=proxyId2;proxyId2=temp;}
-var hash=b2PairManager.Hash(proxyId1,proxyId2)&b2Pair.b2_tableMask;return this.FindHash(proxyId1,proxyId2,hash);},FindHash:function(proxyId1,proxyId2,hash){var index=this.m_hashTable[hash];while(index!=b2Pair.b2_nullPair&&b2PairManager.Equals(this.m_pairs[index],proxyId1,proxyId2)==false)
-{index=this.m_pairs[index].next;}
-if(index==b2Pair.b2_nullPair)
-{return null;}
-return this.m_pairs[index];},ValidateBuffer:function(){},ValidateTable:function(){},m_broadPhase:null,m_callback:null,m_pairs:null,m_freePair:0,m_pairCount:0,m_pairBuffer:null,m_pairBufferCount:0,m_hashTable:null};b2PairManager.Hash=function(proxyId1,proxyId2)
-{var key=((proxyId2<<16)&0xffff0000)|proxyId1;key=~key+((key<<15)&0xFFFF8000);key=key^((key>>12)&0x000fffff);key=key+((key<<2)&0xFFFFFFFC);key=key^((key>>4)&0x0fffffff);key=key*2057;key=key^((key>>16)&0x0000ffff);return key;};b2PairManager.Equals=function(pair,proxyId1,proxyId2)
-{return(pair.proxyId1==proxyId1&&pair.proxyId2==proxyId2);};b2PairManager.EqualsPair=function(pair1,pair2)
-{return pair1.proxyId1==pair2.proxyId1&&pair1.proxyId2==pair2.proxyId2;};
-var b2BroadPhase=Class.create();b2BroadPhase.prototype={initialize:function(worldAABB,callback){this.m_pairManager=new b2PairManager();this.m_proxyPool=new Array(b2Settings.b2_maxPairs);this.m_bounds=new Array(2*b2Settings.b2_maxProxies);this.m_queryResults=new Array(b2Settings.b2_maxProxies);this.m_quantizationFactor=new b2Vec2();var i=0;this.m_pairManager.Initialize(this,callback);this.m_worldAABB=worldAABB;this.m_proxyCount=0;for(i=0;i<b2Settings.b2_maxProxies;i++){this.m_queryResults[i]=0;}
-this.m_bounds=new Array(2);for(i=0;i<2;i++){this.m_bounds[i]=new Array(2*b2Settings.b2_maxProxies);for(var j=0;j<2*b2Settings.b2_maxProxies;j++){this.m_bounds[i][j]=new b2Bound();}}
-var dX=worldAABB.maxVertex.x;var dY=worldAABB.maxVertex.y;dX-=worldAABB.minVertex.x;dY-=worldAABB.minVertex.y;this.m_quantizationFactor.x=b2Settings.USHRT_MAX/dX;this.m_quantizationFactor.y=b2Settings.USHRT_MAX/dY;var tProxy;for(i=0;i<b2Settings.b2_maxProxies-1;++i)
-{tProxy=new b2Proxy();this.m_proxyPool[i]=tProxy;tProxy.SetNext(i+1);tProxy.timeStamp=0;tProxy.overlapCount=b2BroadPhase.b2_invalid;tProxy.userData=null;}
-tProxy=new b2Proxy();this.m_proxyPool[b2Settings.b2_maxProxies-1]=tProxy;tProxy.SetNext(b2Pair.b2_nullProxy);tProxy.timeStamp=0;tProxy.overlapCount=b2BroadPhase.b2_invalid;tProxy.userData=null;this.m_freeProxy=0;this.m_timeStamp=1;this.m_queryResultCount=0;},InRange:function(aabb){var dX;var dY;var d2X;var d2Y;dX=aabb.minVertex.x;dY=aabb.minVertex.y;dX-=this.m_worldAABB.maxVertex.x;dY-=this.m_worldAABB.maxVertex.y;d2X=this.m_worldAABB.minVertex.x;d2Y=this.m_worldAABB.minVertex.y;d2X-=aabb.maxVertex.x;d2Y-=aabb.maxVertex.y;dX=b2Math.b2Max(dX,d2X);dY=b2Math.b2Max(dY,d2Y);return b2Math.b2Max(dX,dY)<0.0;},GetProxy:function(proxyId){if(proxyId==b2Pair.b2_nullProxy||this.m_proxyPool[proxyId].IsValid()==false)
-{return null;}
-return this.m_proxyPool[proxyId];},CreateProxy:function(aabb,userData){var index=0;var proxy;var proxyId=this.m_freeProxy;proxy=this.m_proxyPool[proxyId];this.m_freeProxy=proxy.GetNext();proxy.overlapCount=0;proxy.userData=userData;var boundCount=2*this.m_proxyCount;var lowerValues=new Array();var upperValues=new Array();this.ComputeBounds(lowerValues,upperValues,aabb);for(var axis=0;axis<2;++axis)
-{var bounds=this.m_bounds[axis];var lowerIndex=0;var upperIndex=0;var lowerIndexOut=[lowerIndex];var upperIndexOut=[upperIndex];this.Query(lowerIndexOut,upperIndexOut,lowerValues[axis],upperValues[axis],bounds,boundCount,axis);lowerIndex=lowerIndexOut[0];upperIndex=upperIndexOut[0];var tArr=new Array();var j=0;var tEnd=boundCount-upperIndex
-var tBound1;var tBound2;for(j=0;j<tEnd;j++){tArr[j]=new b2Bound();tBound1=tArr[j];tBound2=bounds[upperIndex+j];tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-tEnd=tArr.length;var tIndex=upperIndex+2;for(j=0;j<tEnd;j++){tBound2=tArr[j];tBound1=bounds[tIndex+j]
-tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-tArr=new Array();tEnd=upperIndex-lowerIndex;for(j=0;j<tEnd;j++){tArr[j]=new b2Bound();tBound1=tArr[j];tBound2=bounds[lowerIndex+j];tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-tEnd=tArr.length;tIndex=lowerIndex+1;for(j=0;j<tEnd;j++){tBound2=tArr[j];tBound1=bounds[tIndex+j]
-tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-++upperIndex;bounds[lowerIndex].value=lowerValues[axis];bounds[lowerIndex].proxyId=proxyId;bounds[upperIndex].value=upperValues[axis];bounds[upperIndex].proxyId=proxyId;bounds[lowerIndex].stabbingCount=lowerIndex==0?0:bounds[lowerIndex-1].stabbingCount;bounds[upperIndex].stabbingCount=bounds[upperIndex-1].stabbingCount;for(index=lowerIndex;index<upperIndex;++index)
-{bounds[index].stabbingCount++;}
-for(index=lowerIndex;index<boundCount+2;++index)
-{var proxy2=this.m_proxyPool[bounds[index].proxyId];if(bounds[index].IsLower())
-{proxy2.lowerBounds[axis]=index;}
-else
-{proxy2.upperBounds[axis]=index;}}}
-++this.m_proxyCount;for(var i=0;i<this.m_queryResultCount;++i)
-{this.m_pairManager.AddBufferedPair(proxyId,this.m_queryResults[i]);}
-this.m_pairManager.Commit();this.m_queryResultCount=0;this.IncrementTimeStamp();return proxyId;},DestroyProxy:function(proxyId){var proxy=this.m_proxyPool[proxyId];var boundCount=2*this.m_proxyCount;for(var axis=0;axis<2;++axis)
-{var bounds=this.m_bounds[axis];var lowerIndex=proxy.lowerBounds[axis];var upperIndex=proxy.upperBounds[axis];var lowerValue=bounds[lowerIndex].value;var upperValue=bounds[upperIndex].value;var tArr=new Array();var j=0;var tEnd=upperIndex-lowerIndex-1;var tBound1;var tBound2;for(j=0;j<tEnd;j++){tArr[j]=new b2Bound();tBound1=tArr[j];tBound2=bounds[lowerIndex+1+j];tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-tEnd=tArr.length;var tIndex=lowerIndex;for(j=0;j<tEnd;j++){tBound2=tArr[j];tBound1=bounds[tIndex+j]
-tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-tArr=new Array();tEnd=boundCount-upperIndex-1;for(j=0;j<tEnd;j++){tArr[j]=new b2Bound();tBound1=tArr[j];tBound2=bounds[upperIndex+1+j];tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-tEnd=tArr.length;tIndex=upperIndex-1;for(j=0;j<tEnd;j++){tBound2=tArr[j];tBound1=bounds[tIndex+j]
-tBound1.value=tBound2.value;tBound1.proxyId=tBound2.proxyId;tBound1.stabbingCount=tBound2.stabbingCount;}
-tEnd=boundCount-2;for(var index=lowerIndex;index<tEnd;++index)
-{var proxy2=this.m_proxyPool[bounds[index].proxyId];if(bounds[index].IsLower())
-{proxy2.lowerBounds[axis]=index;}
-else
-{proxy2.upperBounds[axis]=index;}}
-tEnd=upperIndex-1;for(var index2=lowerIndex;index2<tEnd;++index2)
-{bounds[index2].stabbingCount--;}
-this.Query([0],[0],lowerValue,upperValue,bounds,boundCount-2,axis);}
-for(var i=0;i<this.m_queryResultCount;++i)
-{this.m_pairManager.RemoveBufferedPair(proxyId,this.m_queryResults[i]);}
-this.m_pairManager.Commit();this.m_queryResultCount=0;this.IncrementTimeStamp();proxy.userData=null;proxy.overlapCount=b2BroadPhase.b2_invalid;proxy.lowerBounds[0]=b2BroadPhase.b2_invalid;proxy.lowerBounds[1]=b2BroadPhase.b2_invalid;proxy.upperBounds[0]=b2BroadPhase.b2_invalid;proxy.upperBounds[1]=b2BroadPhase.b2_invalid;proxy.SetNext(this.m_freeProxy);this.m_freeProxy=proxyId;--this.m_proxyCount;},MoveProxy:function(proxyId,aabb){var axis=0;var index=0;var bound;var prevBound
-var nextBound
-var nextProxyId=0;var nextProxy;if(proxyId==b2Pair.b2_nullProxy||b2Settings.b2_maxProxies<=proxyId)
-{return;}
-if(aabb.IsValid()==false)
-{return;}
-var boundCount=2*this.m_proxyCount;var proxy=this.m_proxyPool[proxyId];var newValues=new b2BoundValues();this.ComputeBounds(newValues.lowerValues,newValues.upperValues,aabb);var oldValues=new b2BoundValues();for(axis=0;axis<2;++axis)
-{oldValues.lowerValues[axis]=this.m_bounds[axis][proxy.lowerBounds[axis]].value;oldValues.upperValues[axis]=this.m_bounds[axis][proxy.upperBounds[axis]].value;}
-for(axis=0;axis<2;++axis)
-{var bounds=this.m_bounds[axis];var lowerIndex=proxy.lowerBounds[axis];var upperIndex=proxy.upperBounds[axis];var lowerValue=newValues.lowerValues[axis];var upperValue=newValues.upperValues[axis];var deltaLower=lowerValue-bounds[lowerIndex].value;var deltaUpper=upperValue-bounds[upperIndex].value;bounds[lowerIndex].value=lowerValue;bounds[upperIndex].value=upperValue;if(deltaLower<0)
-{index=lowerIndex;while(index>0&&lowerValue<bounds[index-1].value)
-{bound=bounds[index];prevBound=bounds[index-1];var prevProxyId=prevBound.proxyId;var prevProxy=this.m_proxyPool[prevBound.proxyId];prevBound.stabbingCount++;if(prevBound.IsUpper()==true)
-{if(this.TestOverlap(newValues,prevProxy))
-{this.m_pairManager.AddBufferedPair(proxyId,prevProxyId);}
-prevProxy.upperBounds[axis]++;bound.stabbingCount++;}
-else
-{prevProxy.lowerBounds[axis]++;bound.stabbingCount--;}
-proxy.lowerBounds[axis]--;bound.Swap(prevBound);--index;}}
-if(deltaUpper>0)
-{index=upperIndex;while(index<boundCount-1&&bounds[index+1].value<=upperValue)
-{bound=bounds[index];nextBound=bounds[index+1];nextProxyId=nextBound.proxyId;nextProxy=this.m_proxyPool[nextProxyId];nextBound.stabbingCount++;if(nextBound.IsLower()==true)
-{if(this.TestOverlap(newValues,nextProxy))
-{this.m_pairManager.AddBufferedPair(proxyId,nextProxyId);}
-nextProxy.lowerBounds[axis]--;bound.stabbingCount++;}
-else
-{nextProxy.upperBounds[axis]--;bound.stabbingCount--;}
-proxy.upperBounds[axis]++;bound.Swap(nextBound);index++;}}
-if(deltaLower>0)
-{index=lowerIndex;while(index<boundCount-1&&bounds[index+1].value<=lowerValue)
-{bound=bounds[index];nextBound=bounds[index+1];nextProxyId=nextBound.proxyId;nextProxy=this.m_proxyPool[nextProxyId];nextBound.stabbingCount--;if(nextBound.IsUpper())
-{if(this.TestOverlap(oldValues,nextProxy))
-{this.m_pairManager.RemoveBufferedPair(proxyId,nextProxyId);}
-nextProxy.upperBounds[axis]--;bound.stabbingCount--;}
-else
-{nextProxy.lowerBounds[axis]--;bound.stabbingCount++;}
-proxy.lowerBounds[axis]++;bound.Swap(nextBound);index++;}}
-if(deltaUpper<0)
-{index=upperIndex;while(index>0&&upperValue<bounds[index-1].value)
-{bound=bounds[index];prevBound=bounds[index-1];prevProxyId=prevBound.proxyId;prevProxy=this.m_proxyPool[prevProxyId];prevBound.stabbingCount--;if(prevBound.IsLower()==true)
-{if(this.TestOverlap(oldValues,prevProxy))
-{this.m_pairManager.RemoveBufferedPair(proxyId,prevProxyId);}
-prevProxy.lowerBounds[axis]++;bound.stabbingCount--;}
-else
-{prevProxy.upperBounds[axis]++;bound.stabbingCount++;}
-proxy.upperBounds[axis]--;bound.Swap(prevBound);index--;}}}},Commit:function(){this.m_pairManager.Commit();},QueryAABB:function(aabb,userData,maxCount){var lowerValues=new Array();var upperValues=new Array();this.ComputeBounds(lowerValues,upperValues,aabb);var lowerIndex=0;var upperIndex=0;var lowerIndexOut=[lowerIndex];var upperIndexOut=[upperIndex];this.Query(lowerIndexOut,upperIndexOut,lowerValues[0],upperValues[0],this.m_bounds[0],2*this.m_proxyCount,0);this.Query(lowerIndexOut,upperIndexOut,lowerValues[1],upperValues[1],this.m_bounds[1],2*this.m_proxyCount,1);var count=0;for(var i=0;i<this.m_queryResultCount&&count<maxCount;++i,++count)
-{var proxy=this.m_proxyPool[this.m_queryResults[i]];userData[i]=proxy.userData;}
-this.m_queryResultCount=0;this.IncrementTimeStamp();return count;},Validate:function(){var pair;var proxy1;var proxy2;var overlap;for(var axis=0;axis<2;++axis)
-{var bounds=this.m_bounds[axis];var boundCount=2*this.m_proxyCount;var stabbingCount=0;for(var i=0;i<boundCount;++i)
-{var bound=bounds[i];if(bound.IsLower()==true)
-{stabbingCount++;}
-else
-{stabbingCount--;}}}},ComputeBounds:function(lowerValues,upperValues,aabb)
-{var minVertexX=aabb.minVertex.x;var minVertexY=aabb.minVertex.y;minVertexX=b2Math.b2Min(minVertexX,this.m_worldAABB.maxVertex.x);minVertexY=b2Math.b2Min(minVertexY,this.m_worldAABB.maxVertex.y);minVertexX=b2Math.b2Max(minVertexX,this.m_worldAABB.minVertex.x);minVertexY=b2Math.b2Max(minVertexY,this.m_worldAABB.minVertex.y);var maxVertexX=aabb.maxVertex.x;var maxVertexY=aabb.maxVertex.y;maxVertexX=b2Math.b2Min(maxVertexX,this.m_worldAABB.maxVertex.x);maxVertexY=b2Math.b2Min(maxVertexY,this.m_worldAABB.maxVertex.y);maxVertexX=b2Math.b2Max(maxVertexX,this.m_worldAABB.minVertex.x);maxVertexY=b2Math.b2Max(maxVertexY,this.m_worldAABB.minVertex.y);lowerValues[0]=(this.m_quantizationFactor.x*(minVertexX-this.m_worldAABB.minVertex.x))&(b2Settings.USHRT_MAX-1);upperValues[0]=((this.m_quantizationFactor.x*(maxVertexX-this.m_worldAABB.minVertex.x))&0x0000ffff)|1;lowerValues[1]=(this.m_quantizationFactor.y*(minVertexY-this.m_worldAABB.minVertex.y))&(b2Settings.USHRT_MAX-1);upperValues[1]=((this.m_quantizationFactor.y*(maxVertexY-this.m_worldAABB.minVertex.y))&0x0000ffff)|1;},TestOverlapValidate:function(p1,p2){for(var axis=0;axis<2;++axis)
-{var bounds=this.m_bounds[axis];if(bounds[p1.lowerBounds[axis]].value>bounds[p2.upperBounds[axis]].value)
-return false;if(bounds[p1.upperBounds[axis]].value<bounds[p2.lowerBounds[axis]].value)
-return false;}
-return true;},TestOverlap:function(b,p)
-{for(var axis=0;axis<2;++axis)
-{var bounds=this.m_bounds[axis];if(b.lowerValues[axis]>bounds[p.upperBounds[axis]].value)
-return false;if(b.upperValues[axis]<bounds[p.lowerBounds[axis]].value)
-return false;}
-return true;},Query:function(lowerQueryOut,upperQueryOut,lowerValue,upperValue,bounds,boundCount,axis){var lowerQuery=b2BroadPhase.BinarySearch(bounds,boundCount,lowerValue);var upperQuery=b2BroadPhase.BinarySearch(bounds,boundCount,upperValue);for(var j=lowerQuery;j<upperQuery;++j)
-{if(bounds[j].IsLower())
-{this.IncrementOverlapCount(bounds[j].proxyId);}}
-if(lowerQuery>0)
-{var i=lowerQuery-1;var s=bounds[i].stabbingCount;while(s)
-{if(bounds[i].IsLower())
-{var proxy=this.m_proxyPool[bounds[i].proxyId];if(lowerQuery<=proxy.upperBounds[axis])
-{this.IncrementOverlapCount(bounds[i].proxyId);--s;}}
---i;}}
-lowerQueryOut[0]=lowerQuery;upperQueryOut[0]=upperQuery;},IncrementOverlapCount:function(proxyId){var proxy=this.m_proxyPool[proxyId];if(proxy.timeStamp<this.m_timeStamp)
-{proxy.timeStamp=this.m_timeStamp;proxy.overlapCount=1;}
-else
-{proxy.overlapCount=2;this.m_queryResults[this.m_queryResultCount]=proxyId;++this.m_queryResultCount;}},IncrementTimeStamp:function(){if(this.m_timeStamp==b2Settings.USHRT_MAX)
-{for(var i=0;i<b2Settings.b2_maxProxies;++i)
-{this.m_proxyPool[i].timeStamp=0;}
-this.m_timeStamp=1;}
-else
-{++this.m_timeStamp;}},m_pairManager:new b2PairManager(),m_proxyPool:new Array(b2Settings.b2_maxPairs),m_freeProxy:0,m_bounds:new Array(2*b2Settings.b2_maxProxies),m_queryResults:new Array(b2Settings.b2_maxProxies),m_queryResultCount:0,m_worldAABB:null,m_quantizationFactor:new b2Vec2(),m_proxyCount:0,m_timeStamp:0};b2BroadPhase.s_validate=false;b2BroadPhase.b2_invalid=b2Settings.USHRT_MAX;b2BroadPhase.b2_nullEdge=b2Settings.USHRT_MAX;b2BroadPhase.BinarySearch=function(bounds,count,value)
-{var low=0;var high=count-1;while(low<=high)
-{var mid=Math.floor((low+high)/2);if(bounds[mid].value>value)
-{high=mid-1;}
-else if(bounds[mid].value<value)
-{low=mid+1;}
-else
-{return(mid);}}
-return(low);};
-var b2Collision=Class.create();b2Collision.prototype={initialize:function(){}}
-b2Collision.b2_nullFeature=0x000000ff;b2Collision.ClipSegmentToLine=function(vOut,vIn,normal,offset)
-{var numOut=0;var vIn0=vIn[0].v;var vIn1=vIn[1].v;var distance0=b2Math.b2Dot(normal,vIn[0].v)-offset;var distance1=b2Math.b2Dot(normal,vIn[1].v)-offset;if(distance0<=0.0)vOut[numOut++]=vIn[0];if(distance1<=0.0)vOut[numOut++]=vIn[1];if(distance0*distance1<0.0)
-{var interp=distance0/(distance0-distance1);var tVec=vOut[numOut].v;tVec.x=vIn0.x+interp*(vIn1.x-vIn0.x);tVec.y=vIn0.y+interp*(vIn1.y-vIn0.y);if(distance0>0.0)
-{vOut[numOut].id=vIn[0].id;}
-else
-{vOut[numOut].id=vIn[1].id;}
-++numOut;}
-return numOut;};b2Collision.EdgeSeparation=function(poly1,edge1,poly2)
-{var vert1s=poly1.m_vertices;var count2=poly2.m_vertexCount;var vert2s=poly2.m_vertices;var normalX=poly1.m_normals[edge1].x;var normalY=poly1.m_normals[edge1].y;var tX=normalX;var tMat=poly1.m_R;normalX=tMat.col1.x*tX+tMat.col2.x*normalY;normalY=tMat.col1.y*tX+tMat.col2.y*normalY;var normalLocal2X=normalX;var normalLocal2Y=normalY;tMat=poly2.m_R;tX=normalLocal2X*tMat.col1.x+normalLocal2Y*tMat.col1.y;normalLocal2Y=normalLocal2X*tMat.col2.x+normalLocal2Y*tMat.col2.y;normalLocal2X=tX;var vertexIndex2=0;var minDot=Number.MAX_VALUE;for(var i=0;i<count2;++i)
-{var tVec=vert2s[i];var dot=tVec.x*normalLocal2X+tVec.y*normalLocal2Y;if(dot<minDot)
-{minDot=dot;vertexIndex2=i;}}
-tMat=poly1.m_R;var v1X=poly1.m_position.x+(tMat.col1.x*vert1s[edge1].x+tMat.col2.x*vert1s[edge1].y)
-var v1Y=poly1.m_position.y+(tMat.col1.y*vert1s[edge1].x+tMat.col2.y*vert1s[edge1].y)
-tMat=poly2.m_R;var v2X=poly2.m_position.x+(tMat.col1.x*vert2s[vertexIndex2].x+tMat.col2.x*vert2s[vertexIndex2].y)
-var v2Y=poly2.m_position.y+(tMat.col1.y*vert2s[vertexIndex2].x+tMat.col2.y*vert2s[vertexIndex2].y)
-v2X-=v1X;v2Y-=v1Y;var separation=v2X*normalX+v2Y*normalY;return separation;};b2Collision.FindMaxSeparation=function(edgeIndex,poly1,poly2,conservative)
-{var count1=poly1.m_vertexCount;var dX=poly2.m_position.x-poly1.m_position.x;var dY=poly2.m_position.y-poly1.m_position.y;var dLocal1X=(dX*poly1.m_R.col1.x+dY*poly1.m_R.col1.y);var dLocal1Y=(dX*poly1.m_R.col2.x+dY*poly1.m_R.col2.y);var edge=0;var maxDot=-Number.MAX_VALUE;for(var i=0;i<count1;++i)
-{var dot=(poly1.m_normals[i].x*dLocal1X+poly1.m_normals[i].y*dLocal1Y);if(dot>maxDot)
-{maxDot=dot;edge=i;}}
-var s=b2Collision.EdgeSeparation(poly1,edge,poly2);if(s>0.0&&conservative==false)
-{return s;}
-var prevEdge=edge-1>=0?edge-1:count1-1;var sPrev=b2Collision.EdgeSeparation(poly1,prevEdge,poly2);if(sPrev>0.0&&conservative==false)
-{return sPrev;}
-var nextEdge=edge+1<count1?edge+1:0;var sNext=b2Collision.EdgeSeparation(poly1,nextEdge,poly2);if(sNext>0.0&&conservative==false)
-{return sNext;}
-var bestEdge=0;var bestSeparation;var increment=0;if(sPrev>s&&sPrev>sNext)
-{increment=-1;bestEdge=prevEdge;bestSeparation=sPrev;}
-else if(sNext>s)
-{increment=1;bestEdge=nextEdge;bestSeparation=sNext;}
-else
-{edgeIndex[0]=edge;return s;}
-while(true)
-{if(increment==-1)
-edge=bestEdge-1>=0?bestEdge-1:count1-1;else
-edge=bestEdge+1<count1?bestEdge+1:0;s=b2Collision.EdgeSeparation(poly1,edge,poly2);if(s>0.0&&conservative==false)
-{return s;}
-if(s>bestSeparation)
-{bestEdge=edge;bestSeparation=s;}
-else
-{break;}}
-edgeIndex[0]=bestEdge;return bestSeparation;};b2Collision.FindIncidentEdge=function(c,poly1,edge1,poly2)
-{var count1=poly1.m_vertexCount;var vert1s=poly1.m_vertices;var count2=poly2.m_vertexCount;var vert2s=poly2.m_vertices;var vertex11=edge1;var vertex12=edge1+1==count1?0:edge1+1;var tVec=vert1s[vertex12];var normal1Local1X=tVec.x;var normal1Local1Y=tVec.y;tVec=vert1s[vertex11];normal1Local1X-=tVec.x;normal1Local1Y-=tVec.y;var tX=normal1Local1X;normal1Local1X=normal1Local1Y;normal1Local1Y=-tX;var invLength=1.0/Math.sqrt(normal1Local1X*normal1Local1X+normal1Local1Y*normal1Local1Y);normal1Local1X*=invLength;normal1Local1Y*=invLength;var normal1X=normal1Local1X;var normal1Y=normal1Local1Y;tX=normal1X;var tMat=poly1.m_R;normal1X=tMat.col1.x*tX+tMat.col2.x*normal1Y;normal1Y=tMat.col1.y*tX+tMat.col2.y*normal1Y;var normal1Local2X=normal1X;var normal1Local2Y=normal1Y;tMat=poly2.m_R;tX=normal1Local2X*tMat.col1.x+normal1Local2Y*tMat.col1.y;normal1Local2Y=normal1Local2X*tMat.col2.x+normal1Local2Y*tMat.col2.y;normal1Local2X=tX;var vertex21=0;var vertex22=0;var minDot=Number.MAX_VALUE;for(var i=0;i<count2;++i)
-{var i1=i;var i2=i+1<count2?i+1:0;tVec=vert2s[i2];var normal2Local2X=tVec.x;var normal2Local2Y=tVec.y;tVec=vert2s[i1];normal2Local2X-=tVec.x;normal2Local2Y-=tVec.y;tX=normal2Local2X;normal2Local2X=normal2Local2Y;normal2Local2Y=-tX;invLength=1.0/Math.sqrt(normal2Local2X*normal2Local2X+normal2Local2Y*normal2Local2Y);normal2Local2X*=invLength;normal2Local2Y*=invLength;var dot=normal2Local2X*normal1Local2X+normal2Local2Y*normal1Local2Y;if(dot<minDot)
-{minDot=dot;vertex21=i1;vertex22=i2;}}
-var tClip;tClip=c[0];tVec=tClip.v;tVec.SetV(vert2s[vertex21]);tVec.MulM(poly2.m_R);tVec.Add(poly2.m_position);tClip.id.features.referenceFace=edge1;tClip.id.features.incidentEdge=vertex21;tClip.id.features.incidentVertex=vertex21;tClip=c[1];tVec=tClip.v;tVec.SetV(vert2s[vertex22]);tVec.MulM(poly2.m_R);tVec.Add(poly2.m_position);tClip.id.features.referenceFace=edge1;tClip.id.features.incidentEdge=vertex21;tClip.id.features.incidentVertex=vertex22;};b2Collision.b2CollidePolyTempVec=new b2Vec2();b2Collision.b2CollidePoly=function(manifold,polyA,polyB,conservative)
-{manifold.pointCount=0;var edgeA=0;var edgeAOut=[edgeA];var separationA=b2Collision.FindMaxSeparation(edgeAOut,polyA,polyB,conservative);edgeA=edgeAOut[0];if(separationA>0.0&&conservative==false)
-return;var edgeB=0;var edgeBOut=[edgeB];var separationB=b2Collision.FindMaxSeparation(edgeBOut,polyB,polyA,conservative);edgeB=edgeBOut[0];if(separationB>0.0&&conservative==false)
-return;var poly1;var poly2;var edge1=0;var flip=0;var k_relativeTol=0.98;var k_absoluteTol=0.001;if(separationB>k_relativeTol*separationA+k_absoluteTol)
-{poly1=polyB;poly2=polyA;edge1=edgeB;flip=1;}
-else
-{poly1=polyA;poly2=polyB;edge1=edgeA;flip=0;}
-var incidentEdge=[new ClipVertex(),new ClipVertex()];b2Collision.FindIncidentEdge(incidentEdge,poly1,edge1,poly2);var count1=poly1.m_vertexCount;var vert1s=poly1.m_vertices;var v11=vert1s[edge1];var v12=edge1+1<count1?vert1s[edge1+1]:vert1s[0];var dvX=v12.x-v11.x;var dvY=v12.y-v11.y;var sideNormalX=v12.x-v11.x;var sideNormalY=v12.y-v11.y;var tX=sideNormalX;var tMat=poly1.m_R;sideNormalX=tMat.col1.x*tX+tMat.col2.x*sideNormalY;sideNormalY=tMat.col1.y*tX+tMat.col2.y*sideNormalY;var invLength=1.0/Math.sqrt(sideNormalX*sideNormalX+sideNormalY*sideNormalY);sideNormalX*=invLength;sideNormalY*=invLength;var frontNormalX=sideNormalX;var frontNormalY=sideNormalY;tX=frontNormalX;frontNormalX=frontNormalY;frontNormalY=-tX;var v11X=v11.x;var v11Y=v11.y;tX=v11X;tMat=poly1.m_R;v11X=tMat.col1.x*tX+tMat.col2.x*v11Y;v11Y=tMat.col1.y*tX+tMat.col2.y*v11Y;v11X+=poly1.m_position.x;v11Y+=poly1.m_position.y;var v12X=v12.x;var v12Y=v12.y;tX=v12X;tMat=poly1.m_R;v12X=tMat.col1.x*tX+tMat.col2.x*v12Y;v12Y=tMat.col1.y*tX+tMat.col2.y*v12Y;v12X+=poly1.m_position.x;v12Y+=poly1.m_position.y;var frontOffset=frontNormalX*v11X+frontNormalY*v11Y;var sideOffset1=-(sideNormalX*v11X+sideNormalY*v11Y);var sideOffset2=sideNormalX*v12X+sideNormalY*v12Y;var clipPoints1=[new ClipVertex(),new ClipVertex()];var clipPoints2=[new ClipVertex(),new ClipVertex()];var np=0;b2Collision.b2CollidePolyTempVec.Set(-sideNormalX,-sideNormalY);np=b2Collision.ClipSegmentToLine(clipPoints1,incidentEdge,b2Collision.b2CollidePolyTempVec,sideOffset1);if(np<2)
-return;b2Collision.b2CollidePolyTempVec.Set(sideNormalX,sideNormalY);np=b2Collision.ClipSegmentToLine(clipPoints2,clipPoints1,b2Collision.b2CollidePolyTempVec,sideOffset2);if(np<2)
-return;if(flip){manifold.normal.Set(-frontNormalX,-frontNormalY);}
-else{manifold.normal.Set(frontNormalX,frontNormalY);}
-var pointCount=0;for(var i=0;i<b2Settings.b2_maxManifoldPoints;++i)
-{var tVec=clipPoints2[i].v;var separation=(frontNormalX*tVec.x+frontNormalY*tVec.y)-frontOffset;if(separation<=0.0||conservative==true)
-{var cp=manifold.points[pointCount];cp.separation=separation;cp.position.SetV(clipPoints2[i].v);cp.id.Set(clipPoints2[i].id);cp.id.features.flip=flip;++pointCount;}}
-manifold.pointCount=pointCount;};b2Collision.b2CollideCircle=function(manifold,circle1,circle2,conservative)
-{manifold.pointCount=0;var dX=circle2.m_position.x-circle1.m_position.x;var dY=circle2.m_position.y-circle1.m_position.y;var distSqr=dX*dX+dY*dY;var radiusSum=circle1.m_radius+circle2.m_radius;if(distSqr>radiusSum*radiusSum&&conservative==false)
-{return;}
-var separation;if(distSqr<Number.MIN_VALUE)
-{separation=-radiusSum;manifold.normal.Set(0.0,1.0);}
-else
-{var dist=Math.sqrt(distSqr);separation=dist-radiusSum;var a=1.0/dist;manifold.normal.x=a*dX;manifold.normal.y=a*dY;}
-manifold.pointCount=1;var tPoint=manifold.points[0];tPoint.id.set_key(0);tPoint.separation=separation;tPoint.position.x=circle2.m_position.x-(circle2.m_radius*manifold.normal.x);tPoint.position.y=circle2.m_position.y-(circle2.m_radius*manifold.normal.y);};b2Collision.b2CollidePolyAndCircle=function(manifold,poly,circle,conservative)
-{manifold.pointCount=0;var tPoint;var dX;var dY;var xLocalX=circle.m_position.x-poly.m_position.x;var xLocalY=circle.m_position.y-poly.m_position.y;var tMat=poly.m_R;var tX=xLocalX*tMat.col1.x+xLocalY*tMat.col1.y;xLocalY=xLocalX*tMat.col2.x+xLocalY*tMat.col2.y;xLocalX=tX;var dist;var normalIndex=0;var separation=-Number.MAX_VALUE;var radius=circle.m_radius;for(var i=0;i<poly.m_vertexCount;++i)
-{var s=poly.m_normals[i].x*(xLocalX-poly.m_vertices[i].x)+poly.m_normals[i].y*(xLocalY-poly.m_vertices[i].y);if(s>radius)
-{return;}
-if(s>separation)
-{separation=s;normalIndex=i;}}
-if(separation<Number.MIN_VALUE)
-{manifold.pointCount=1;var tVec=poly.m_normals[normalIndex];manifold.normal.x=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;manifold.normal.y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tPoint=manifold.points[0];tPoint.id.features.incidentEdge=normalIndex;tPoint.id.features.incidentVertex=b2Collision.b2_nullFeature;tPoint.id.features.referenceFace=b2Collision.b2_nullFeature;tPoint.id.features.flip=0;tPoint.position.x=circle.m_position.x-radius*manifold.normal.x;tPoint.position.y=circle.m_position.y-radius*manifold.normal.y;tPoint.separation=separation-radius;return;}
-var vertIndex1=normalIndex;var vertIndex2=vertIndex1+1<poly.m_vertexCount?vertIndex1+1:0;var eX=poly.m_vertices[vertIndex2].x-poly.m_vertices[vertIndex1].x;var eY=poly.m_vertices[vertIndex2].y-poly.m_vertices[vertIndex1].y;var length=Math.sqrt(eX*eX+eY*eY);eX/=length;eY/=length;if(length<Number.MIN_VALUE)
-{dX=xLocalX-poly.m_vertices[vertIndex1].x;dY=xLocalY-poly.m_vertices[vertIndex1].y;dist=Math.sqrt(dX*dX+dY*dY);dX/=dist;dY/=dist;if(dist>radius)
-{return;}
-manifold.pointCount=1;manifold.normal.Set(tMat.col1.x*dX+tMat.col2.x*dY,tMat.col1.y*dX+tMat.col2.y*dY);tPoint=manifold.points[0];tPoint.id.features.incidentEdge=b2Collision.b2_nullFeature;tPoint.id.features.incidentVertex=vertIndex1;tPoint.id.features.referenceFace=b2Collision.b2_nullFeature;tPoint.id.features.flip=0;tPoint.position.x=circle.m_position.x-radius*manifold.normal.x;tPoint.position.y=circle.m_position.y-radius*manifold.normal.y;tPoint.separation=dist-radius;return;}
-var u=(xLocalX-poly.m_vertices[vertIndex1].x)*eX+(xLocalY-poly.m_vertices[vertIndex1].y)*eY;tPoint=manifold.points[0];tPoint.id.features.incidentEdge=b2Collision.b2_nullFeature;tPoint.id.features.incidentVertex=b2Collision.b2_nullFeature;tPoint.id.features.referenceFace=b2Collision.b2_nullFeature;tPoint.id.features.flip=0;var pX,pY;if(u<=0.0)
-{pX=poly.m_vertices[vertIndex1].x;pY=poly.m_vertices[vertIndex1].y;tPoint.id.features.incidentVertex=vertIndex1;}
-else if(u>=length)
-{pX=poly.m_vertices[vertIndex2].x;pY=poly.m_vertices[vertIndex2].y;tPoint.id.features.incidentVertex=vertIndex2;}
-else
-{pX=eX*u+poly.m_vertices[vertIndex1].x;pY=eY*u+poly.m_vertices[vertIndex1].y;tPoint.id.features.incidentEdge=vertIndex1;}
-dX=xLocalX-pX;dY=xLocalY-pY;dist=Math.sqrt(dX*dX+dY*dY);dX/=dist;dY/=dist;if(dist>radius)
-{return;}
-manifold.pointCount=1;manifold.normal.Set(tMat.col1.x*dX+tMat.col2.x*dY,tMat.col1.y*dX+tMat.col2.y*dY);tPoint.position.x=circle.m_position.x-radius*manifold.normal.x;tPoint.position.y=circle.m_position.y-radius*manifold.normal.y;tPoint.separation=dist-radius;};b2Collision.b2TestOverlap=function(a,b)
-{var t1=b.minVertex;var t2=a.maxVertex;var d1X=t1.x-t2.x;var d1Y=t1.y-t2.y;t1=a.minVertex;t2=b.maxVertex;var d2X=t1.x-t2.x;var d2Y=t1.y-t2.y;if(d1X>0.0||d1Y>0.0)
-return false;if(d2X>0.0||d2Y>0.0)
-return false;return true;};
-var Features=Class.create();Features.prototype={set_referenceFace:function(value){this._referenceFace=value;this._m_id._key=(this._m_id._key&0xffffff00)|(this._referenceFace&0x000000ff)},get_referenceFace:function(){return this._referenceFace;},_referenceFace:0,set_incidentEdge:function(value){this._incidentEdge=value;this._m_id._key=(this._m_id._key&0xffff00ff)|((this._incidentEdge<<8)&0x0000ff00)},get_incidentEdge:function(){return this._incidentEdge;},_incidentEdge:0,set_incidentVertex:function(value){this._incidentVertex=value;this._m_id._key=(this._m_id._key&0xff00ffff)|((this._incidentVertex<<16)&0x00ff0000)},get_incidentVertex:function(){return this._incidentVertex;},_incidentVertex:0,set_flip:function(value){this._flip=value;this._m_id._key=(this._m_id._key&0x00ffffff)|((this._flip<<24)&0xff000000)},get_flip:function(){return this._flip;},_flip:0,_m_id:null,initialize:function(){}};
-var b2ContactID=Class.create();b2ContactID.prototype={initialize:function(){this.features=new Features();this.features._m_id=this;},Set:function(id){this.set_key(id._key);},Copy:function(){var id=new b2ContactID();id.set_key(this._key);return id;},get_key:function(){return this._key;},set_key:function(value){this._key=value;this.features._referenceFace=this._key&0x000000ff;this.features._incidentEdge=((this._key&0x0000ff00)>>8)&0x000000ff;this.features._incidentVertex=((this._key&0x00ff0000)>>16)&0x000000ff;this.features._flip=((this._key&0xff000000)>>24)&0x000000ff;},features:new Features(),_key:0};
-var b2ContactPoint=Class.create();b2ContactPoint.prototype={position:new b2Vec2(),separation:null,normalImpulse:null,tangentImpulse:null,id:new b2ContactID(),initialize:function(){this.position=new b2Vec2();this.id=new b2ContactID();}};var b2Distance=Class.create();b2Distance.prototype={initialize:function(){}};b2Distance.ProcessTwo=function(p1Out,p2Out,p1s,p2s,points)
-{var rX=-points[1].x;var rY=-points[1].y;var dX=points[0].x-points[1].x;var dY=points[0].y-points[1].y;var length=Math.sqrt(dX*dX+dY*dY);dX/=length;dY/=length;var lambda=rX*dX+rY*dY;if(lambda<=0.0||length<Number.MIN_VALUE)
-{p1Out.SetV(p1s[1]);p2Out.SetV(p2s[1]);p1s[0].SetV(p1s[1]);p2s[0].SetV(p2s[1]);points[0].SetV(points[1]);return 1;}
-lambda/=length;p1Out.x=p1s[1].x+lambda*(p1s[0].x-p1s[1].x);p1Out.y=p1s[1].y+lambda*(p1s[0].y-p1s[1].y);p2Out.x=p2s[1].x+lambda*(p2s[0].x-p2s[1].x);p2Out.y=p2s[1].y+lambda*(p2s[0].y-p2s[1].y);return 2;};b2Distance.ProcessThree=function(p1Out,p2Out,p1s,p2s,points)
-{var aX=points[0].x;var aY=points[0].y;var bX=points[1].x;var bY=points[1].y;var cX=points[2].x;var cY=points[2].y;var abX=bX-aX;var abY=bY-aY;var acX=cX-aX;var acY=cY-aY;var bcX=cX-bX;var bcY=cY-bY;var sn=-(aX*abX+aY*abY);var sd=(bX*abX+bY*abY);var tn=-(aX*acX+aY*acY);var td=(cX*acX+cY*acY);var un=-(bX*bcX+bY*bcY);var ud=(cX*bcX+cY*bcY);if(td<=0.0&&ud<=0.0)
-{p1Out.SetV(p1s[2]);p2Out.SetV(p2s[2]);p1s[0].SetV(p1s[2]);p2s[0].SetV(p2s[2]);points[0].SetV(points[2]);return 1;}
-var n=abX*acY-abY*acX;var vc=n*(aX*bY-aY*bX);var va=n*(bX*cY-bY*cX);if(va<=0.0&&un>=0.0&&ud>=0.0)
-{var lambda=un/(un+ud);p1Out.x=p1s[1].x+lambda*(p1s[2].x-p1s[1].x);p1Out.y=p1s[1].y+lambda*(p1s[2].y-p1s[1].y);p2Out.x=p2s[1].x+lambda*(p2s[2].x-p2s[1].x);p2Out.y=p2s[1].y+lambda*(p2s[2].y-p2s[1].y);p1s[0].SetV(p1s[2]);p2s[0].SetV(p2s[2]);points[0].SetV(points[2]);return 2;}
-var vb=n*(cX*aY-cY*aX);if(vb<=0.0&&tn>=0.0&&td>=0.0)
-{var lambda=tn/(tn+td);p1Out.x=p1s[0].x+lambda*(p1s[2].x-p1s[0].x);p1Out.y=p1s[0].y+lambda*(p1s[2].y-p1s[0].y);p2Out.x=p2s[0].x+lambda*(p2s[2].x-p2s[0].x);p2Out.y=p2s[0].y+lambda*(p2s[2].y-p2s[0].y);p1s[1].SetV(p1s[2]);p2s[1].SetV(p2s[2]);points[1].SetV(points[2]);return 2;}
-var denom=va+vb+vc;denom=1.0/denom;var u=va*denom;var v=vb*denom;var w=1.0-u-v;p1Out.x=u*p1s[0].x+v*p1s[1].x+w*p1s[2].x;p1Out.y=u*p1s[0].y+v*p1s[1].y+w*p1s[2].y;p2Out.x=u*p2s[0].x+v*p2s[1].x+w*p2s[2].x;p2Out.y=u*p2s[0].y+v*p2s[1].y+w*p2s[2].y;return 3;};b2Distance.InPoinsts=function(w,points,pointCount)
-{for(var i=0;i<pointCount;++i)
-{if(w.x==points[i].x&&w.y==points[i].y)
-{return true;}}
-return false;};b2Distance.Distance=function(p1Out,p2Out,shape1,shape2)
-{var p1s=new Array(3);var p2s=new Array(3);var points=new Array(3);var pointCount=0;p1Out.SetV(shape1.m_position);p2Out.SetV(shape2.m_position);var vSqr=0.0;var maxIterations=20;for(var iter=0;iter<maxIterations;++iter)
-{var vX=p2Out.x-p1Out.x;var vY=p2Out.y-p1Out.y;var w1=shape1.Support(vX,vY);var w2=shape2.Support(-vX,-vY);vSqr=(vX*vX+vY*vY);var wX=w2.x-w1.x;var wY=w2.y-w1.y;var vw=(vX*wX+vY*wY);if(vSqr-b2Dot(vX*wX+vY*wY)<=0.01*vSqr)
-{if(pointCount==0)
-{p1Out.SetV(w1);p2Out.SetV(w2);}
-b2Distance.g_GJK_Iterations=iter;return Math.sqrt(vSqr);}
-switch(pointCount)
-{case 0:p1s[0].SetV(w1);p2s[0].SetV(w2);points[0]=w;p1Out.SetV(p1s[0]);p2Out.SetV(p2s[0]);++pointCount;break;case 1:p1s[1].SetV(w1);p2s[1].SetV(w2);points[1].x=wX;points[1].y=wY;pointCount=b2Distance.ProcessTwo(p1Out,p2Out,p1s,p2s,points);break;case 2:p1s[2].SetV(w1);p2s[2].SetV(w2);points[2].x=wX;points[2].y=wY;pointCount=b2Distance.ProcessThree(p1Out,p2Out,p1s,p2s,points);break;}
-if(pointCount==3)
-{b2Distance.g_GJK_Iterations=iter;return 0.0;}
-var maxSqr=-Number.MAX_VALUE;for(var i=0;i<pointCount;++i)
-{maxSqr=b2Math.b2Max(maxSqr,(points[i].x*points[i].x+points[i].y*points[i].y));}
-if(pointCount==3||vSqr<=100.0*Number.MIN_VALUE*maxSqr)
-{b2Distance.g_GJK_Iterations=iter;return Math.sqrt(vSqr);}}
-b2Distance.g_GJK_Iterations=maxIterations;return Math.sqrt(vSqr);};b2Distance.g_GJK_Iterations=0;
-var b2Manifold=Class.create();b2Manifold.prototype={initialize:function(){this.points=new Array(b2Settings.b2_maxManifoldPoints);for(var i=0;i<b2Settings.b2_maxManifoldPoints;i++){this.points[i]=new b2ContactPoint();}
-this.normal=new b2Vec2();},points:null,normal:null,pointCount:0};
-var b2OBB=Class.create();b2OBB.prototype={R:new b2Mat22(),center:new b2Vec2(),extents:new b2Vec2(),initialize:function(){this.R=new b2Mat22();this.center=new b2Vec2();this.extents=new b2Vec2();}};
-var b2Proxy=Class.create();b2Proxy.prototype={GetNext:function(){return this.lowerBounds[0];},SetNext:function(next){this.lowerBounds[0]=next;},IsValid:function(){return this.overlapCount!=b2BroadPhase.b2_invalid;},lowerBounds:[(0),(0)],upperBounds:[(0),(0)],overlapCount:0,timeStamp:0,userData:null,initialize:function(){this.lowerBounds=[(0),(0)];this.upperBounds=[(0),(0)];}}
-
-var ClipVertex=Class.create();ClipVertex.prototype={v:new b2Vec2(),id:new b2ContactID(),initialize:function(){this.v=new b2Vec2();this.id=new b2ContactID();}};var b2Shape=Class.create();b2Shape.prototype={TestPoint:function(p){return false},GetUserData:function(){return this.m_userData;},GetType:function(){return this.m_type;},GetBody:function(){return this.m_body;},GetPosition:function(){return this.m_position;},GetRotationMatrix:function(){return this.m_R;},ResetProxy:function(broadPhase){},GetNext:function(){return this.m_next;},initialize:function(def,body){this.m_R=new b2Mat22();this.m_position=new b2Vec2();this.m_userData=def.userData;this.m_friction=def.friction;this.m_restitution=def.restitution;this.m_body=body;this.m_proxyId=b2Pair.b2_nullProxy;this.m_maxRadius=0.0;this.m_categoryBits=def.categoryBits;this.m_maskBits=def.maskBits;this.m_groupIndex=def.groupIndex;},DestroyProxy:function()
-{if(this.m_proxyId!=b2Pair.b2_nullProxy)
-{this.m_body.m_world.m_broadPhase.DestroyProxy(this.m_proxyId);this.m_proxyId=b2Pair.b2_nullProxy;}},Synchronize:function(position1,R1,position2,R2){},QuickSync:function(position,R){},Support:function(dX,dY,out){},GetMaxRadius:function(){return this.m_maxRadius;},m_next:null,m_R:new b2Mat22(),m_position:new b2Vec2(),m_type:0,m_userData:null,m_body:null,m_friction:null,m_restitution:null,m_maxRadius:null,m_proxyId:0,m_categoryBits:0,m_maskBits:0,m_groupIndex:0};b2Shape.Create=function(def,body,center){switch(def.type)
-{case b2Shape.e_circleShape:{return new b2CircleShape(def,body,center);}
-case b2Shape.e_boxShape:case b2Shape.e_polyShape:{return new b2PolyShape(def,body,center);}}
-return null;};b2Shape.Destroy=function(shape)
-{if(shape.m_proxyId!=b2Pair.b2_nullProxy)
-shape.m_body.m_world.m_broadPhase.DestroyProxy(shape.m_proxyId);};b2Shape.e_unknownShape=-1;b2Shape.e_circleShape=0;b2Shape.e_boxShape=1;b2Shape.e_polyShape=2;b2Shape.e_meshShape=3;b2Shape.e_shapeTypeCount=4;b2Shape.PolyMass=function(massData,vs,count,rho)
-{var center=new b2Vec2();center.SetZero();var area=0.0;var I=0.0;var pRef=new b2Vec2(0.0,0.0);var inv3=1.0/3.0;for(var i=0;i<count;++i)
-{var p1=pRef;var p2=vs[i];var p3=i+1<count?vs[i+1]:vs[0];var e1=b2Math.SubtractVV(p2,p1);var e2=b2Math.SubtractVV(p3,p1);var D=b2Math.b2CrossVV(e1,e2);var triangleArea=0.5*D;area+=triangleArea;var tVec=new b2Vec2();tVec.SetV(p1);tVec.Add(p2);tVec.Add(p3);tVec.Multiply(inv3*triangleArea);center.Add(tVec);var px=p1.x;var py=p1.y;var ex1=e1.x;var ey1=e1.y;var ex2=e2.x;var ey2=e2.y;var intx2=inv3*(0.25*(ex1*ex1+ex2*ex1+ex2*ex2)+(px*ex1+px*ex2))+0.5*px*px;var inty2=inv3*(0.25*(ey1*ey1+ey2*ey1+ey2*ey2)+(py*ey1+py*ey2))+0.5*py*py;I+=D*(intx2+inty2);}
-massData.mass=rho*area;center.Multiply(1.0/area);massData.center=center;I=rho*(I-area*b2Math.b2Dot(center,center));massData.I=I;};b2Shape.PolyCentroid=function(vs,count,out)
-{var cX=0.0;var cY=0.0;var area=0.0;var pRefX=0.0;var pRefY=0.0;var inv3=1.0/3.0;for(var i=0;i<count;++i)
-{var p1X=pRefX;var p1Y=pRefY;var p2X=vs[i].x;var p2Y=vs[i].y;var p3X=i+1<count?vs[i+1].x:vs[0].x;var p3Y=i+1<count?vs[i+1].y:vs[0].y;var e1X=p2X-p1X;var e1Y=p2Y-p1Y;var e2X=p3X-p1X;var e2Y=p3Y-p1Y;var D=(e1X*e2Y-e1Y*e2X);var triangleArea=0.5*D;area+=triangleArea;cX+=triangleArea*inv3*(p1X+p2X+p3X);cY+=triangleArea*inv3*(p1Y+p2Y+p3Y);}
-cX*=1.0/area;cY*=1.0/area;out.Set(cX,cY);};
-var b2ShapeDef=Class.create();b2ShapeDef.prototype={initialize:function()
-{this.type=b2Shape.e_unknownShape;this.userData=null;this.localPosition=new b2Vec2(0.0,0.0);this.localRotation=0.0;this.friction=0.2;this.restitution=0.0;this.density=0.0;this.categoryBits=0x0001;this.maskBits=0xFFFF;this.groupIndex=0;},ComputeMass:function(massData)
-{massData.center=new b2Vec2(0.0,0.0)
-if(this.density==0.0)
-{massData.mass=0.0;massData.center.Set(0.0,0.0);massData.I=0.0;};switch(this.type)
-{case b2Shape.e_circleShape:{var circle=this;massData.mass=this.density*b2Settings.b2_pi*circle.radius*circle.radius;massData.center.Set(0.0,0.0);massData.I=0.5*(massData.mass)*circle.radius*circle.radius;}
-break;case b2Shape.e_boxShape:{var box=this;massData.mass=4.0*this.density*box.extents.x*box.extents.y;massData.center.Set(0.0,0.0);massData.I=massData.mass/3.0*b2Math.b2Dot(box.extents,box.extents);}
-break;case b2Shape.e_polyShape:{var poly=this;b2Shape.PolyMass(massData,poly.vertices,poly.vertexCount,this.density);}
-break;default:massData.mass=0.0;massData.center.Set(0.0,0.0);massData.I=0.0;break;}},type:0,userData:null,localPosition:null,localRotation:null,friction:null,restitution:null,density:null,categoryBits:0,maskBits:0,groupIndex:0};
-var b2BoxDef=Class.create();Object.extend(b2BoxDef.prototype,b2ShapeDef.prototype);Object.extend(b2BoxDef.prototype,{initialize:function()
-{this.type=b2Shape.e_unknownShape;this.userData=null;this.localPosition=new b2Vec2(0.0,0.0);this.localRotation=0.0;this.friction=0.2;this.restitution=0.0;this.density=0.0;this.categoryBits=0x0001;this.maskBits=0xFFFF;this.groupIndex=0;this.type=b2Shape.e_boxShape;this.extents=new b2Vec2(1.0,1.0);},extents:null});
-var b2CircleDef=Class.create();Object.extend(b2CircleDef.prototype,b2ShapeDef.prototype);Object.extend(b2CircleDef.prototype,{initialize:function()
-{this.type=b2Shape.e_unknownShape;this.userData=null;this.localPosition=new b2Vec2(0.0,0.0);this.localRotation=0.0;this.friction=0.2;this.restitution=0.0;this.density=0.0;this.categoryBits=0x0001;this.maskBits=0xFFFF;this.groupIndex=0;this.type=b2Shape.e_circleShape;this.radius=1.0;},radius:null});var b2CircleShape=Class.create();Object.extend(b2CircleShape.prototype,b2Shape.prototype);Object.extend(b2CircleShape.prototype,{TestPoint:function(p){var d=new b2Vec2();d.SetV(p);d.Subtract(this.m_position);return b2Math.b2Dot(d,d)<=this.m_radius*this.m_radius;},initialize:function(def,body,localCenter){this.m_R=new b2Mat22();this.m_position=new b2Vec2();this.m_userData=def.userData;this.m_friction=def.friction;this.m_restitution=def.restitution;this.m_body=body;this.m_proxyId=b2Pair.b2_nullProxy;this.m_maxRadius=0.0;this.m_categoryBits=def.categoryBits;this.m_maskBits=def.maskBits;this.m_groupIndex=def.groupIndex;this.m_localPosition=new b2Vec2();var circle=def;this.m_localPosition.Set(def.localPosition.x-localCenter.x,def.localPosition.y-localCenter.y);this.m_type=b2Shape.e_circleShape;this.m_radius=circle.radius;this.m_R.SetM(this.m_body.m_R);var rX=this.m_R.col1.x*this.m_localPosition.x+this.m_R.col2.x*this.m_localPosition.y;var rY=this.m_R.col1.y*this.m_localPosition.x+this.m_R.col2.y*this.m_localPosition.y;this.m_position.x=this.m_body.m_position.x+rX;this.m_position.y=this.m_body.m_position.y+rY;this.m_maxRadius=Math.sqrt(rX*rX+rY*rY)+this.m_radius;var aabb=new b2AABB();aabb.minVertex.Set(this.m_position.x-this.m_radius,this.m_position.y-this.m_radius);aabb.maxVertex.Set(this.m_position.x+this.m_radius,this.m_position.y+this.m_radius);var broadPhase=this.m_body.m_world.m_broadPhase;if(broadPhase.InRange(aabb))
-{this.m_proxyId=broadPhase.CreateProxy(aabb,this);}
-else
-{this.m_proxyId=b2Pair.b2_nullProxy;}
-if(this.m_proxyId==b2Pair.b2_nullProxy)
-{this.m_body.Freeze();}},Synchronize:function(position1,R1,position2,R2){this.m_R.SetM(R2);this.m_position.x=(R2.col1.x*this.m_localPosition.x+R2.col2.x*this.m_localPosition.y)+position2.x;this.m_position.y=(R2.col1.y*this.m_localPosition.x+R2.col2.y*this.m_localPosition.y)+position2.y;if(this.m_proxyId==b2Pair.b2_nullProxy)
-{return;}
-var p1X=position1.x+(R1.col1.x*this.m_localPosition.x+R1.col2.x*this.m_localPosition.y);var p1Y=position1.y+(R1.col1.y*this.m_localPosition.x+R1.col2.y*this.m_localPosition.y);var lowerX=Math.min(p1X,this.m_position.x);var lowerY=Math.min(p1Y,this.m_position.y);var upperX=Math.max(p1X,this.m_position.x);var upperY=Math.max(p1Y,this.m_position.y);var aabb=new b2AABB();aabb.minVertex.Set(lowerX-this.m_radius,lowerY-this.m_radius);aabb.maxVertex.Set(upperX+this.m_radius,upperY+this.m_radius);var broadPhase=this.m_body.m_world.m_broadPhase;if(broadPhase.InRange(aabb))
-{broadPhase.MoveProxy(this.m_proxyId,aabb);}
-else
-{this.m_body.Freeze();}},QuickSync:function(position,R){this.m_R.SetM(R);this.m_position.x=(R.col1.x*this.m_localPosition.x+R.col2.x*this.m_localPosition.y)+position.x;this.m_position.y=(R.col1.y*this.m_localPosition.x+R.col2.y*this.m_localPosition.y)+position.y;},ResetProxy:function(broadPhase)
-{if(this.m_proxyId==b2Pair.b2_nullProxy)
-{return;}
-var proxy=broadPhase.GetProxy(this.m_proxyId);broadPhase.DestroyProxy(this.m_proxyId);proxy=null;var aabb=new b2AABB();aabb.minVertex.Set(this.m_position.x-this.m_radius,this.m_position.y-this.m_radius);aabb.maxVertex.Set(this.m_position.x+this.m_radius,this.m_position.y+this.m_radius);if(broadPhase.InRange(aabb))
-{this.m_proxyId=broadPhase.CreateProxy(aabb,this);}
-else
-{this.m_proxyId=b2Pair.b2_nullProxy;}
-if(this.m_proxyId==b2Pair.b2_nullProxy)
-{this.m_body.Freeze();}},Support:function(dX,dY,out)
-{var len=Math.sqrt(dX*dX+dY*dY);dX/=len;dY/=len;out.Set(this.m_position.x+this.m_radius*dX,this.m_position.y+this.m_radius*dY);},m_localPosition:new b2Vec2(),m_radius:null});
-var b2MassData=Class.create();b2MassData.prototype={mass:0.0,center:new b2Vec2(0,0),I:0.0,initialize:function(){this.center=new b2Vec2(0,0);}}
-
-var b2PolyDef=Class.create();Object.extend(b2PolyDef.prototype,b2ShapeDef.prototype);Object.extend(b2PolyDef.prototype,{initialize:function()
-{this.type=b2Shape.e_unknownShape;this.userData=null;this.localPosition=new b2Vec2(0.0,0.0);this.localRotation=0.0;this.friction=0.2;this.restitution=0.0;this.density=0.0;this.categoryBits=0x0001;this.maskBits=0xFFFF;this.groupIndex=0;this.vertices=new Array(b2Settings.b2_maxPolyVertices);this.type=b2Shape.e_polyShape;this.vertexCount=0;for(var i=0;i<b2Settings.b2_maxPolyVertices;i++){this.vertices[i]=new b2Vec2();}},vertices:new Array(b2Settings.b2_maxPolyVertices),vertexCount:0});var b2PolyShape=Class.create();Object.extend(b2PolyShape.prototype,b2Shape.prototype);Object.extend(b2PolyShape.prototype,{TestPoint:function(p){var pLocal=new b2Vec2();pLocal.SetV(p);pLocal.Subtract(this.m_position);pLocal.MulTM(this.m_R);for(var i=0;i<this.m_vertexCount;++i)
-{var tVec=new b2Vec2();tVec.SetV(pLocal);tVec.Subtract(this.m_vertices[i]);var dot=b2Math.b2Dot(this.m_normals[i],tVec);if(dot>0.0)
-{return false;}}
-return true;},initialize:function(def,body,newOrigin){this.m_R=new b2Mat22();this.m_position=new b2Vec2();this.m_userData=def.userData;this.m_friction=def.friction;this.m_restitution=def.restitution;this.m_body=body;this.m_proxyId=b2Pair.b2_nullProxy;this.m_maxRadius=0.0;this.m_categoryBits=def.categoryBits;this.m_maskBits=def.maskBits;this.m_groupIndex=def.groupIndex;this.syncAABB=new b2AABB();this.syncMat=new b2Mat22();this.m_localCentroid=new b2Vec2();this.m_localOBB=new b2OBB();var i=0;var hX;var hY;var tVec;var aabb=new b2AABB();this.m_vertices=new Array(b2Settings.b2_maxPolyVertices);this.m_coreVertices=new Array(b2Settings.b2_maxPolyVertices);this.m_normals=new Array(b2Settings.b2_maxPolyVertices);this.m_type=b2Shape.e_polyShape;var localR=new b2Mat22(def.localRotation);if(def.type==b2Shape.e_boxShape)
-{this.m_localCentroid.x=def.localPosition.x-newOrigin.x;this.m_localCentroid.y=def.localPosition.y-newOrigin.y;var box=def;this.m_vertexCount=4;hX=box.extents.x;hY=box.extents.y;var hcX=Math.max(0.0,hX-2.0*b2Settings.b2_linearSlop);var hcY=Math.max(0.0,hY-2.0*b2Settings.b2_linearSlop);tVec=this.m_vertices[0]=new b2Vec2();tVec.x=localR.col1.x*hX+localR.col2.x*hY;tVec.y=localR.col1.y*hX+localR.col2.y*hY;tVec=this.m_vertices[1]=new b2Vec2();tVec.x=localR.col1.x*-hX+localR.col2.x*hY;tVec.y=localR.col1.y*-hX+localR.col2.y*hY;tVec=this.m_vertices[2]=new b2Vec2();tVec.x=localR.col1.x*-hX+localR.col2.x*-hY;tVec.y=localR.col1.y*-hX+localR.col2.y*-hY;tVec=this.m_vertices[3]=new b2Vec2();tVec.x=localR.col1.x*hX+localR.col2.x*-hY;tVec.y=localR.col1.y*hX+localR.col2.y*-hY;tVec=this.m_coreVertices[0]=new b2Vec2();tVec.x=localR.col1.x*hcX+localR.col2.x*hcY;tVec.y=localR.col1.y*hcX+localR.col2.y*hcY;tVec=this.m_coreVertices[1]=new b2Vec2();tVec.x=localR.col1.x*-hcX+localR.col2.x*hcY;tVec.y=localR.col1.y*-hcX+localR.col2.y*hcY;tVec=this.m_coreVertices[2]=new b2Vec2();tVec.x=localR.col1.x*-hcX+localR.col2.x*-hcY;tVec.y=localR.col1.y*-hcX+localR.col2.y*-hcY;tVec=this.m_coreVertices[3]=new b2Vec2();tVec.x=localR.col1.x*hcX+localR.col2.x*-hcY;tVec.y=localR.col1.y*hcX+localR.col2.y*-hcY;}
-else
-{var poly=def;this.m_vertexCount=poly.vertexCount;b2Shape.PolyCentroid(poly.vertices,poly.vertexCount,b2PolyShape.tempVec);var centroidX=b2PolyShape.tempVec.x;var centroidY=b2PolyShape.tempVec.y;this.m_localCentroid.x=def.localPosition.x+(localR.col1.x*centroidX+localR.col2.x*centroidY)-newOrigin.x;this.m_localCentroid.y=def.localPosition.y+(localR.col1.y*centroidX+localR.col2.y*centroidY)-newOrigin.y;for(i=0;i<this.m_vertexCount;++i)
-{this.m_vertices[i]=new b2Vec2();this.m_coreVertices[i]=new b2Vec2();hX=poly.vertices[i].x-centroidX;hY=poly.vertices[i].y-centroidY;this.m_vertices[i].x=localR.col1.x*hX+localR.col2.x*hY;this.m_vertices[i].y=localR.col1.y*hX+localR.col2.y*hY;var uX=this.m_vertices[i].x;var uY=this.m_vertices[i].y;var length=Math.sqrt(uX*uX+uY*uY);if(length>Number.MIN_VALUE)
-{uX*=1.0/length;uY*=1.0/length;}
-this.m_coreVertices[i].x=this.m_vertices[i].x-2.0*b2Settings.b2_linearSlop*uX;this.m_coreVertices[i].y=this.m_vertices[i].y-2.0*b2Settings.b2_linearSlop*uY;}}
-var minVertexX=Number.MAX_VALUE;var minVertexY=Number.MAX_VALUE;var maxVertexX=-Number.MAX_VALUE;var maxVertexY=-Number.MAX_VALUE;this.m_maxRadius=0.0;for(i=0;i<this.m_vertexCount;++i)
-{var v=this.m_vertices[i];minVertexX=Math.min(minVertexX,v.x);minVertexY=Math.min(minVertexY,v.y);maxVertexX=Math.max(maxVertexX,v.x);maxVertexY=Math.max(maxVertexY,v.y);this.m_maxRadius=Math.max(this.m_maxRadius,v.Length());}
-this.m_localOBB.R.SetIdentity();this.m_localOBB.center.Set((minVertexX+maxVertexX)*0.5,(minVertexY+maxVertexY)*0.5);this.m_localOBB.extents.Set((maxVertexX-minVertexX)*0.5,(maxVertexY-minVertexY)*0.5);var i1=0;var i2=0;for(i=0;i<this.m_vertexCount;++i)
-{this.m_normals[i]=new b2Vec2();i1=i;i2=i+1<this.m_vertexCount?i+1:0;this.m_normals[i].x=this.m_vertices[i2].y-this.m_vertices[i1].y;this.m_normals[i].y=-(this.m_vertices[i2].x-this.m_vertices[i1].x);this.m_normals[i].Normalize();}
-for(i=0;i<this.m_vertexCount;++i)
-{i1=i;i2=i+1<this.m_vertexCount?i+1:0;}
-this.m_R.SetM(this.m_body.m_R);this.m_position.x=this.m_body.m_position.x+(this.m_R.col1.x*this.m_localCentroid.x+this.m_R.col2.x*this.m_localCentroid.y);this.m_position.y=this.m_body.m_position.y+(this.m_R.col1.y*this.m_localCentroid.x+this.m_R.col2.y*this.m_localCentroid.y);b2PolyShape.tAbsR.col1.x=this.m_R.col1.x*this.m_localOBB.R.col1.x+this.m_R.col2.x*this.m_localOBB.R.col1.y;b2PolyShape.tAbsR.col1.y=this.m_R.col1.y*this.m_localOBB.R.col1.x+this.m_R.col2.y*this.m_localOBB.R.col1.y;b2PolyShape.tAbsR.col2.x=this.m_R.col1.x*this.m_localOBB.R.col2.x+this.m_R.col2.x*this.m_localOBB.R.col2.y;b2PolyShape.tAbsR.col2.y=this.m_R.col1.y*this.m_localOBB.R.col2.x+this.m_R.col2.y*this.m_localOBB.R.col2.y;b2PolyShape.tAbsR.Abs()
-hX=b2PolyShape.tAbsR.col1.x*this.m_localOBB.extents.x+b2PolyShape.tAbsR.col2.x*this.m_localOBB.extents.y;hY=b2PolyShape.tAbsR.col1.y*this.m_localOBB.extents.x+b2PolyShape.tAbsR.col2.y*this.m_localOBB.extents.y;var positionX=this.m_position.x+(this.m_R.col1.x*this.m_localOBB.center.x+this.m_R.col2.x*this.m_localOBB.center.y);var positionY=this.m_position.y+(this.m_R.col1.y*this.m_localOBB.center.x+this.m_R.col2.y*this.m_localOBB.center.y);aabb.minVertex.x=positionX-hX;aabb.minVertex.y=positionY-hY;aabb.maxVertex.x=positionX+hX;aabb.maxVertex.y=positionY+hY;var broadPhase=this.m_body.m_world.m_broadPhase;if(broadPhase.InRange(aabb))
-{this.m_proxyId=broadPhase.CreateProxy(aabb,this);}
-else
-{this.m_proxyId=b2Pair.b2_nullProxy;}
-if(this.m_proxyId==b2Pair.b2_nullProxy)
-{this.m_body.Freeze();}},syncAABB:new b2AABB(),syncMat:new b2Mat22(),Synchronize:function(position1,R1,position2,R2){this.m_R.SetM(R2);this.m_position.x=this.m_body.m_position.x+(R2.col1.x*this.m_localCentroid.x+R2.col2.x*this.m_localCentroid.y);this.m_position.y=this.m_body.m_position.y+(R2.col1.y*this.m_localCentroid.x+R2.col2.y*this.m_localCentroid.y);if(this.m_proxyId==b2Pair.b2_nullProxy)
-{return;}
-var hX;var hY;var v1=R1.col1;var v2=R1.col2;var v3=this.m_localOBB.R.col1;var v4=this.m_localOBB.R.col2;this.syncMat.col1.x=v1.x*v3.x+v2.x*v3.y;this.syncMat.col1.y=v1.y*v3.x+v2.y*v3.y;this.syncMat.col2.x=v1.x*v4.x+v2.x*v4.y;this.syncMat.col2.y=v1.y*v4.x+v2.y*v4.y;this.syncMat.Abs();hX=this.m_localCentroid.x+this.m_localOBB.center.x;hY=this.m_localCentroid.y+this.m_localOBB.center.y;var centerX=position1.x+(R1.col1.x*hX+R1.col2.x*hY);var centerY=position1.y+(R1.col1.y*hX+R1.col2.y*hY);hX=this.syncMat.col1.x*this.m_localOBB.extents.x+this.syncMat.col2.x*this.m_localOBB.extents.y;hY=this.syncMat.col1.y*this.m_localOBB.extents.x+this.syncMat.col2.y*this.m_localOBB.extents.y;this.syncAABB.minVertex.x=centerX-hX;this.syncAABB.minVertex.y=centerY-hY;this.syncAABB.maxVertex.x=centerX+hX;this.syncAABB.maxVertex.y=centerY+hY;v1=R2.col1;v2=R2.col2;v3=this.m_localOBB.R.col1;v4=this.m_localOBB.R.col2;this.syncMat.col1.x=v1.x*v3.x+v2.x*v3.y;this.syncMat.col1.y=v1.y*v3.x+v2.y*v3.y;this.syncMat.col2.x=v1.x*v4.x+v2.x*v4.y;this.syncMat.col2.y=v1.y*v4.x+v2.y*v4.y;this.syncMat.Abs();hX=this.m_localCentroid.x+this.m_localOBB.center.x;hY=this.m_localCentroid.y+this.m_localOBB.center.y;centerX=position2.x+(R2.col1.x*hX+R2.col2.x*hY);centerY=position2.y+(R2.col1.y*hX+R2.col2.y*hY);hX=this.syncMat.col1.x*this.m_localOBB.extents.x+this.syncMat.col2.x*this.m_localOBB.extents.y;hY=this.syncMat.col1.y*this.m_localOBB.extents.x+this.syncMat.col2.y*this.m_localOBB.extents.y;this.syncAABB.minVertex.x=Math.min(this.syncAABB.minVertex.x,centerX-hX);this.syncAABB.minVertex.y=Math.min(this.syncAABB.minVertex.y,centerY-hY);this.syncAABB.maxVertex.x=Math.max(this.syncAABB.maxVertex.x,centerX+hX);this.syncAABB.maxVertex.y=Math.max(this.syncAABB.maxVertex.y,centerY+hY);var broadPhase=this.m_body.m_world.m_broadPhase;if(broadPhase.InRange(this.syncAABB))
-{broadPhase.MoveProxy(this.m_proxyId,this.syncAABB);}
-else
-{this.m_body.Freeze();}},QuickSync:function(position,R){this.m_R.SetM(R);this.m_position.x=position.x+(R.col1.x*this.m_localCentroid.x+R.col2.x*this.m_localCentroid.y);this.m_position.y=position.y+(R.col1.y*this.m_localCentroid.x+R.col2.y*this.m_localCentroid.y);},ResetProxy:function(broadPhase){if(this.m_proxyId==b2Pair.b2_nullProxy)
-{return;}
-var proxy=broadPhase.GetProxy(this.m_proxyId);broadPhase.DestroyProxy(this.m_proxyId);proxy=null;var R=b2Math.b2MulMM(this.m_R,this.m_localOBB.R);var absR=b2Math.b2AbsM(R);var h=b2Math.b2MulMV(absR,this.m_localOBB.extents);var position=b2Math.b2MulMV(this.m_R,this.m_localOBB.center);position.Add(this.m_position);var aabb=new b2AABB();aabb.minVertex.SetV(position);aabb.minVertex.Subtract(h);aabb.maxVertex.SetV(position);aabb.maxVertex.Add(h);if(broadPhase.InRange(aabb))
-{this.m_proxyId=broadPhase.CreateProxy(aabb,this);}
-else
-{this.m_proxyId=b2Pair.b2_nullProxy;}
-if(this.m_proxyId==b2Pair.b2_nullProxy)
-{this.m_body.Freeze();}},Support:function(dX,dY,out)
-{var dLocalX=(dX*this.m_R.col1.x+dY*this.m_R.col1.y);var dLocalY=(dX*this.m_R.col2.x+dY*this.m_R.col2.y);var bestIndex=0;var bestValue=(this.m_coreVertices[0].x*dLocalX+this.m_coreVertices[0].y*dLocalY);for(var i=1;i<this.m_vertexCount;++i)
-{var value=(this.m_coreVertices[i].x*dLocalX+this.m_coreVertices[i].y*dLocalY);if(value>bestValue)
-{bestIndex=i;bestValue=value;}}
-out.Set(this.m_position.x+(this.m_R.col1.x*this.m_coreVertices[bestIndex].x+this.m_R.col2.x*this.m_coreVertices[bestIndex].y),this.m_position.y+(this.m_R.col1.y*this.m_coreVertices[bestIndex].x+this.m_R.col2.y*this.m_coreVertices[bestIndex].y));},m_localCentroid:new b2Vec2(),m_localOBB:new b2OBB(),m_vertices:null,m_coreVertices:null,m_vertexCount:0,m_normals:null});b2PolyShape.tempVec=new b2Vec2();b2PolyShape.tAbsR=new b2Mat22();
-var b2Body=Class.create();b2Body.prototype={SetOriginPosition:function(position,rotation){if(this.IsFrozen())
-{return;}
-this.m_rotation=rotation;this.m_R.Set(this.m_rotation);this.m_position=b2Math.AddVV(position,b2Math.b2MulMV(this.m_R,this.m_center));this.m_position0.SetV(this.m_position);this.m_rotation0=this.m_rotation;for(var s=this.m_shapeList;s!=null;s=s.m_next)
-{s.Synchronize(this.m_position,this.m_R,this.m_position,this.m_R);}
-this.m_world.m_broadPhase.Commit();},GetOriginPosition:function(){return b2Math.SubtractVV(this.m_position,b2Math.b2MulMV(this.m_R,this.m_center));},SetCenterPosition:function(position,rotation){if(this.IsFrozen())
-{return;}
-this.m_rotation=rotation;this.m_R.Set(this.m_rotation);this.m_position.SetV(position);this.m_position0.SetV(this.m_position);this.m_rotation0=this.m_rotation;for(var s=this.m_shapeList;s!=null;s=s.m_next)
-{s.Synchronize(this.m_position,this.m_R,this.m_position,this.m_R);}
-this.m_world.m_broadPhase.Commit();},GetCenterPosition:function(){return this.m_position;},GetRotation:function(){return this.m_rotation;},GetRotationMatrix:function(){return this.m_R;},SetLinearVelocity:function(v){this.m_linearVelocity.SetV(v);},GetLinearVelocity:function(){return this.m_linearVelocity;},SetAngularVelocity:function(w){this.m_angularVelocity=w;},GetAngularVelocity:function(){return this.m_angularVelocity;},ApplyForce:function(force,point)
-{if(this.IsSleeping()==false)
-{this.m_force.Add(force);this.m_torque+=b2Math.b2CrossVV(b2Math.SubtractVV(point,this.m_position),force);}},ApplyTorque:function(torque)
-{if(this.IsSleeping()==false)
-{this.m_torque+=torque;}},ApplyImpulse:function(impulse,point)
-{if(this.IsSleeping()==false)
-{this.m_linearVelocity.Add(b2Math.MulFV(this.m_invMass,impulse));this.m_angularVelocity+=(this.m_invI*b2Math.b2CrossVV(b2Math.SubtractVV(point,this.m_position),impulse));}},GetMass:function(){return this.m_mass;},GetInertia:function(){return this.m_I;},GetWorldPoint:function(localPoint){return b2Math.AddVV(this.m_position,b2Math.b2MulMV(this.m_R,localPoint));},GetWorldVector:function(localVector){return b2Math.b2MulMV(this.m_R,localVector);},GetLocalPoint:function(worldPoint){return b2Math.b2MulTMV(this.m_R,b2Math.SubtractVV(worldPoint,this.m_position));},GetLocalVector:function(worldVector){return b2Math.b2MulTMV(this.m_R,worldVector);},IsStatic:function(){return(this.m_flags&b2Body.e_staticFlag)==b2Body.e_staticFlag;},IsFrozen:function()
-{return(this.m_flags&b2Body.e_frozenFlag)==b2Body.e_frozenFlag;},IsSleeping:function(){return(this.m_flags&b2Body.e_sleepFlag)==b2Body.e_sleepFlag;},AllowSleeping:function(flag)
-{if(flag)
-{this.m_flags|=b2Body.e_allowSleepFlag;}
-else
-{this.m_flags&=~b2Body.e_allowSleepFlag;this.WakeUp();}},WakeUp:function(){this.m_flags&=~b2Body.e_sleepFlag;this.m_sleepTime=0.0;},GetShapeList:function(){return this.m_shapeList;},GetContactList:function()
-{return this.m_contactList;},GetJointList:function()
-{return this.m_jointList;},GetNext:function(){return this.m_next;},GetUserData:function(){return this.m_userData;},initialize:function(bd,world){this.sMat0=new b2Mat22();this.m_position=new b2Vec2();this.m_R=new b2Mat22(0);this.m_position0=new b2Vec2();var i=0;var sd;var massData;this.m_flags=0;this.m_position.SetV(bd.position);this.m_rotation=bd.rotation;this.m_R.Set(this.m_rotation);this.m_position0.SetV(this.m_position);this.m_rotation0=this.m_rotation;this.m_world=world;this.m_linearDamping=b2Math.b2Clamp(1.0-bd.linearDamping,0.0,1.0);this.m_angularDamping=b2Math.b2Clamp(1.0-bd.angularDamping,0.0,1.0);this.m_force=new b2Vec2(0.0,0.0);this.m_torque=0.0;this.m_mass=0.0;var massDatas=new Array(b2Settings.b2_maxShapesPerBody);for(i=0;i<b2Settings.b2_maxShapesPerBody;i++){massDatas[i]=new b2MassData();}
-this.m_shapeCount=0;this.m_center=new b2Vec2(0.0,0.0);for(i=0;i<b2Settings.b2_maxShapesPerBody;++i)
-{sd=bd.shapes[i];if(sd==null)break;massData=massDatas[i];sd.ComputeMass(massData);this.m_mass+=massData.mass;this.m_center.x+=massData.mass*(sd.localPosition.x+massData.center.x);this.m_center.y+=massData.mass*(sd.localPosition.y+massData.center.y);++this.m_shapeCount;}
-if(this.m_mass>0.0)
-{this.m_center.Multiply(1.0/this.m_mass);this.m_position.Add(b2Math.b2MulMV(this.m_R,this.m_center));}
-else
-{this.m_flags|=b2Body.e_staticFlag;}
-this.m_I=0.0;for(i=0;i<this.m_shapeCount;++i)
-{sd=bd.shapes[i];massData=massDatas[i];this.m_I+=massData.I;var r=b2Math.SubtractVV(b2Math.AddVV(sd.localPosition,massData.center),this.m_center);this.m_I+=massData.mass*b2Math.b2Dot(r,r);}
-if(this.m_mass>0.0)
-{this.m_invMass=1.0/this.m_mass;}
-else
-{this.m_invMass=0.0;}
-if(this.m_I>0.0&&bd.preventRotation==false)
-{this.m_invI=1.0/this.m_I;}
-else
-{this.m_I=0.0;this.m_invI=0.0;}
-this.m_linearVelocity=b2Math.AddVV(bd.linearVelocity,b2Math.b2CrossFV(bd.angularVelocity,this.m_center));this.m_angularVelocity=bd.angularVelocity;this.m_jointList=null;this.m_contactList=null;this.m_prev=null;this.m_next=null;this.m_shapeList=null;for(i=0;i<this.m_shapeCount;++i)
-{sd=bd.shapes[i];var shape=b2Shape.Create(sd,this,this.m_center);shape.m_next=this.m_shapeList;this.m_shapeList=shape;}
-this.m_sleepTime=0.0;if(bd.allowSleep)
-{this.m_flags|=b2Body.e_allowSleepFlag;}
-if(bd.isSleeping)
-{this.m_flags|=b2Body.e_sleepFlag;}
-if((this.m_flags&b2Body.e_sleepFlag)||this.m_invMass==0.0)
-{this.m_linearVelocity.Set(0.0,0.0);this.m_angularVelocity=0.0;}
-this.m_userData=bd.userData;},Destroy:function(){var s=this.m_shapeList;while(s)
-{var s0=s;s=s.m_next;b2Shape.Destroy(s0);}},sMat0:new b2Mat22(),SynchronizeShapes:function(){this.sMat0.Set(this.m_rotation0);for(var s=this.m_shapeList;s!=null;s=s.m_next)
-{s.Synchronize(this.m_position0,this.sMat0,this.m_position,this.m_R);}},QuickSyncShapes:function(){for(var s=this.m_shapeList;s!=null;s=s.m_next)
-{s.QuickSync(this.m_position,this.m_R);}},IsConnected:function(other){for(var jn=this.m_jointList;jn!=null;jn=jn.next)
-{if(jn.other==other)
-return jn.joint.m_collideConnected==false;}
-return false;},Freeze:function(){this.m_flags|=b2Body.e_frozenFlag;this.m_linearVelocity.SetZero();this.m_angularVelocity=0.0;for(var s=this.m_shapeList;s!=null;s=s.m_next)
-{s.DestroyProxy();}},m_flags:0,m_position:new b2Vec2(),m_rotation:null,m_R:new b2Mat22(0),m_position0:new b2Vec2(),m_rotation0:null,m_linearVelocity:null,m_angularVelocity:null,m_force:null,m_torque:null,m_center:null,m_world:null,m_prev:null,m_next:null,m_shapeList:null,m_shapeCount:0,m_jointList:null,m_contactList:null,m_mass:null,m_invMass:null,m_I:null,m_invI:null,m_linearDamping:null,m_angularDamping:null,m_sleepTime:null,m_userData:null};b2Body.e_staticFlag=0x0001;b2Body.e_frozenFlag=0x0002;b2Body.e_islandFlag=0x0004;b2Body.e_sleepFlag=0x0008;b2Body.e_allowSleepFlag=0x0010;b2Body.e_destroyFlag=0x0020;
-var b2BodyDef=Class.create();b2BodyDef.prototype={initialize:function()
-{this.shapes=new Array();this.userData=null;for(var i=0;i<b2Settings.b2_maxShapesPerBody;i++){this.shapes[i]=null;}
-this.position=new b2Vec2(0.0,0.0);this.rotation=0.0;this.linearVelocity=new b2Vec2(0.0,0.0);this.angularVelocity=0.0;this.linearDamping=0.0;this.angularDamping=0.0;this.allowSleep=true;this.isSleeping=false;this.preventRotation=false;},userData:null,shapes:new Array(),position:null,rotation:null,linearVelocity:null,angularVelocity:null,linearDamping:null,angularDamping:null,allowSleep:null,isSleeping:null,preventRotation:null,AddShape:function(shape)
-{for(var i=0;i<b2Settings.b2_maxShapesPerBody;++i)
-{if(this.shapes[i]==null)
-{this.shapes[i]=shape;break;}}}};
-var b2CollisionFilter=Class.create();b2CollisionFilter.prototype={ShouldCollide:function(shape1,shape2){if(shape1.m_groupIndex==shape2.m_groupIndex&&shape1.m_groupIndex!=0)
-{return shape1.m_groupIndex>0;}
-var collide=(shape1.m_maskBits&shape2.m_categoryBits)!=0&&(shape1.m_categoryBits&shape2.m_maskBits)!=0;return collide;},initialize:function(){}};b2CollisionFilter.b2_defaultFilter=new b2CollisionFilter;
-var b2Island=Class.create();b2Island.prototype={initialize:function(bodyCapacity,contactCapacity,jointCapacity,allocator)
-{var i=0;this.m_bodyCapacity=bodyCapacity;this.m_contactCapacity=contactCapacity;this.m_jointCapacity=jointCapacity;this.m_bodyCount=0;this.m_contactCount=0;this.m_jointCount=0;this.m_bodies=new Array(bodyCapacity);for(i=0;i<bodyCapacity;i++)
-this.m_bodies[i]=null;this.m_contacts=new Array(contactCapacity);for(i=0;i<contactCapacity;i++)
-this.m_contacts[i]=null;this.m_joints=new Array(jointCapacity);for(i=0;i<jointCapacity;i++)
-this.m_joints[i]=null;this.m_allocator=allocator;},Clear:function()
-{this.m_bodyCount=0;this.m_contactCount=0;this.m_jointCount=0;},Solve:function(step,gravity)
-{var i=0;var b;for(i=0;i<this.m_bodyCount;++i)
-{b=this.m_bodies[i];if(b.m_invMass==0.0)
-continue;b.m_linearVelocity.Add(b2Math.MulFV(step.dt,b2Math.AddVV(gravity,b2Math.MulFV(b.m_invMass,b.m_force))));b.m_angularVelocity+=step.dt*b.m_invI*b.m_torque;b.m_linearVelocity.Multiply(b.m_linearDamping);b.m_angularVelocity*=b.m_angularDamping;b.m_position0.SetV(b.m_position);b.m_rotation0=b.m_rotation;}
-var contactSolver=new b2ContactSolver(this.m_contacts,this.m_contactCount,this.m_allocator);contactSolver.PreSolve();for(i=0;i<this.m_jointCount;++i)
-{this.m_joints[i].PrepareVelocitySolver();}
-for(i=0;i<step.iterations;++i)
-{contactSolver.SolveVelocityConstraints();for(var j=0;j<this.m_jointCount;++j)
-{this.m_joints[j].SolveVelocityConstraints(step);}}
-for(i=0;i<this.m_bodyCount;++i)
-{b=this.m_bodies[i];if(b.m_invMass==0.0)
-continue;b.m_position.x+=step.dt*b.m_linearVelocity.x;b.m_position.y+=step.dt*b.m_linearVelocity.y;b.m_rotation+=step.dt*b.m_angularVelocity;b.m_R.Set(b.m_rotation);}
-for(i=0;i<this.m_jointCount;++i)
-{this.m_joints[i].PreparePositionSolver();}
-if(b2World.s_enablePositionCorrection)
-{for(b2Island.m_positionIterationCount=0;b2Island.m_positionIterationCount<step.iterations;++b2Island.m_positionIterationCount)
-{var contactsOkay=contactSolver.SolvePositionConstraints(b2Settings.b2_contactBaumgarte);var jointsOkay=true;for(i=0;i<this.m_jointCount;++i)
-{var jointOkay=this.m_joints[i].SolvePositionConstraints();jointsOkay=jointsOkay&&jointOkay;}
-if(contactsOkay&&jointsOkay)
-{break;}}}
-contactSolver.PostSolve();for(i=0;i<this.m_bodyCount;++i)
-{b=this.m_bodies[i];if(b.m_invMass==0.0)
-continue;b.m_R.Set(b.m_rotation);b.SynchronizeShapes();b.m_force.Set(0.0,0.0);b.m_torque=0.0;}},UpdateSleep:function(dt)
-{var i=0;var b;var minSleepTime=Number.MAX_VALUE;var linTolSqr=b2Settings.b2_linearSleepTolerance*b2Settings.b2_linearSleepTolerance;var angTolSqr=b2Settings.b2_angularSleepTolerance*b2Settings.b2_angularSleepTolerance;for(i=0;i<this.m_bodyCount;++i)
-{b=this.m_bodies[i];if(b.m_invMass==0.0)
-{continue;}
-if((b.m_flags&b2Body.e_allowSleepFlag)==0)
-{b.m_sleepTime=0.0;minSleepTime=0.0;}
-if((b.m_flags&b2Body.e_allowSleepFlag)==0||b.m_angularVelocity*b.m_angularVelocity>angTolSqr||b2Math.b2Dot(b.m_linearVelocity,b.m_linearVelocity)>linTolSqr)
-{b.m_sleepTime=0.0;minSleepTime=0.0;}
-else
-{b.m_sleepTime+=dt;minSleepTime=b2Math.b2Min(minSleepTime,b.m_sleepTime);}}
-if(minSleepTime>=b2Settings.b2_timeToSleep)
-{for(i=0;i<this.m_bodyCount;++i)
-{b=this.m_bodies[i];b.m_flags|=b2Body.e_sleepFlag;}}},AddBody:function(body)
-{this.m_bodies[this.m_bodyCount++]=body;},AddContact:function(contact)
-{this.m_contacts[this.m_contactCount++]=contact;},AddJoint:function(joint)
-{this.m_joints[this.m_jointCount++]=joint;},m_allocator:null,m_bodies:null,m_contacts:null,m_joints:null,m_bodyCount:0,m_jointCount:0,m_contactCount:0,m_bodyCapacity:0,m_contactCapacity:0,m_jointCapacity:0,m_positionError:null};b2Island.m_positionIterationCount=0;
-var b2TimeStep=Class.create();b2TimeStep.prototype={dt:null,inv_dt:null,iterations:0,initialize:function(){}};
-var b2ContactNode=Class.create();b2ContactNode.prototype={other:null,contact:null,prev:null,next:null,initialize:function(){}};
-var b2Contact=Class.create();b2Contact.prototype={GetManifolds:function(){return null},GetManifoldCount:function()
-{return this.m_manifoldCount;},GetNext:function(){return this.m_next;},GetShape1:function(){return this.m_shape1;},GetShape2:function(){return this.m_shape2;},initialize:function(s1,s2)
-{this.m_node1=new b2ContactNode();this.m_node2=new b2ContactNode();this.m_flags=0;if(!s1||!s2){this.m_shape1=null;this.m_shape2=null;return;}
-this.m_shape1=s1;this.m_shape2=s2;this.m_manifoldCount=0;this.m_friction=Math.sqrt(this.m_shape1.m_friction*this.m_shape2.m_friction);this.m_restitution=b2Math.b2Max(this.m_shape1.m_restitution,this.m_shape2.m_restitution);this.m_prev=null;this.m_next=null;this.m_node1.contact=null;this.m_node1.prev=null;this.m_node1.next=null;this.m_node1.other=null;this.m_node2.contact=null;this.m_node2.prev=null;this.m_node2.next=null;this.m_node2.other=null;},Evaluate:function(){},m_flags:0,m_prev:null,m_next:null,m_node1:new b2ContactNode(),m_node2:new b2ContactNode(),m_shape1:null,m_shape2:null,m_manifoldCount:0,m_friction:null,m_restitution:null};b2Contact.e_islandFlag=0x0001;b2Contact.e_destroyFlag=0x0002;b2Contact.AddType=function(createFcn,destroyFcn,type1,type2)
-{b2Contact.s_registers[type1][type2].createFcn=createFcn;b2Contact.s_registers[type1][type2].destroyFcn=destroyFcn;b2Contact.s_registers[type1][type2].primary=true;if(type1!=type2)
-{b2Contact.s_registers[type2][type1].createFcn=createFcn;b2Contact.s_registers[type2][type1].destroyFcn=destroyFcn;b2Contact.s_registers[type2][type1].primary=false;}};b2Contact.InitializeRegisters=function(){b2Contact.s_registers=new Array(b2Shape.e_shapeTypeCount);for(var i=0;i<b2Shape.e_shapeTypeCount;i++){b2Contact.s_registers[i]=new Array(b2Shape.e_shapeTypeCount);for(var j=0;j<b2Shape.e_shapeTypeCount;j++){b2Contact.s_registers[i][j]=new b2ContactRegister();}}
-b2Contact.AddType(b2CircleContact.Create,b2CircleContact.Destroy,b2Shape.e_circleShape,b2Shape.e_circleShape);b2Contact.AddType(b2PolyAndCircleContact.Create,b2PolyAndCircleContact.Destroy,b2Shape.e_polyShape,b2Shape.e_circleShape);b2Contact.AddType(b2PolyContact.Create,b2PolyContact.Destroy,b2Shape.e_polyShape,b2Shape.e_polyShape);};b2Contact.Create=function(shape1,shape2,allocator){if(b2Contact.s_initialized==false)
-{b2Contact.InitializeRegisters();b2Contact.s_initialized=true;}
-var type1=shape1.m_type;var type2=shape2.m_type;var createFcn=b2Contact.s_registers[type1][type2].createFcn;if(createFcn)
-{if(b2Contact.s_registers[type1][type2].primary)
-{return createFcn(shape1,shape2,allocator);}
-else
-{var c=createFcn(shape2,shape1,allocator);for(var i=0;i<c.GetManifoldCount();++i)
-{var m=c.GetManifolds()[i];m.normal=m.normal.Negative();}
-return c;}}
-else
-{return null;}};b2Contact.Destroy=function(contact,allocator){if(contact.GetManifoldCount()>0)
-{contact.m_shape1.m_body.WakeUp();contact.m_shape2.m_body.WakeUp();}
-var type1=contact.m_shape1.m_type;var type2=contact.m_shape2.m_type;var destroyFcn=b2Contact.s_registers[type1][type2].destroyFcn;destroyFcn(contact,allocator);};b2Contact.s_registers=null;b2Contact.s_initialized=false;
-var b2ContactConstraint=Class.create();b2ContactConstraint.prototype={initialize:function(){this.normal=new b2Vec2();this.points=new Array(b2Settings.b2_maxManifoldPoints);for(var i=0;i<b2Settings.b2_maxManifoldPoints;i++){this.points[i]=new b2ContactConstraintPoint();}},points:null,normal:new b2Vec2(),manifold:null,body1:null,body2:null,friction:null,restitution:null,pointCount:0};
-var b2ContactConstraintPoint=Class.create();b2ContactConstraintPoint.prototype={localAnchor1:new b2Vec2(),localAnchor2:new b2Vec2(),normalImpulse:null,tangentImpulse:null,positionImpulse:null,normalMass:null,tangentMass:null,separation:null,velocityBias:null,initialize:function(){this.localAnchor1=new b2Vec2();this.localAnchor2=new b2Vec2();}};
-var b2ContactRegister=Class.create();b2ContactRegister.prototype={createFcn:null,destroyFcn:null,primary:null,initialize:function(){}};
-var b2ContactSolver=Class.create();b2ContactSolver.prototype={initialize:function(contacts,contactCount,allocator){this.m_constraints=new Array();this.m_allocator=allocator;var i=0;var tVec;var tMat;this.m_constraintCount=0;for(i=0;i<contactCount;++i)
-{this.m_constraintCount+=contacts[i].GetManifoldCount();}
-for(i=0;i<this.m_constraintCount;i++){this.m_constraints[i]=new b2ContactConstraint();}
-var count=0;for(i=0;i<contactCount;++i)
-{var contact=contacts[i];var b1=contact.m_shape1.m_body;var b2=contact.m_shape2.m_body;var manifoldCount=contact.GetManifoldCount();var manifolds=contact.GetManifolds();var friction=contact.m_friction;var restitution=contact.m_restitution;var v1X=b1.m_linearVelocity.x;var v1Y=b1.m_linearVelocity.y;var v2X=b2.m_linearVelocity.x;var v2Y=b2.m_linearVelocity.y;var w1=b1.m_angularVelocity;var w2=b2.m_angularVelocity;for(var j=0;j<manifoldCount;++j)
-{var manifold=manifolds[j];var normalX=manifold.normal.x;var normalY=manifold.normal.y;var c=this.m_constraints[count];c.body1=b1;c.body2=b2;c.manifold=manifold;c.normal.x=normalX;c.normal.y=normalY;c.pointCount=manifold.pointCount;c.friction=friction;c.restitution=restitution;for(var k=0;k<c.pointCount;++k)
-{var cp=manifold.points[k];var ccp=c.points[k];ccp.normalImpulse=cp.normalImpulse;ccp.tangentImpulse=cp.tangentImpulse;ccp.separation=cp.separation;var r1X=cp.position.x-b1.m_position.x;var r1Y=cp.position.y-b1.m_position.y;var r2X=cp.position.x-b2.m_position.x;var r2Y=cp.position.y-b2.m_position.y;tVec=ccp.localAnchor1;tMat=b1.m_R;tVec.x=r1X*tMat.col1.x+r1Y*tMat.col1.y;tVec.y=r1X*tMat.col2.x+r1Y*tMat.col2.y;tVec=ccp.localAnchor2;tMat=b2.m_R;tVec.x=r2X*tMat.col1.x+r2Y*tMat.col1.y;tVec.y=r2X*tMat.col2.x+r2Y*tMat.col2.y;var r1Sqr=r1X*r1X+r1Y*r1Y;var r2Sqr=r2X*r2X+r2Y*r2Y;var rn1=r1X*normalX+r1Y*normalY;var rn2=r2X*normalX+r2Y*normalY;var kNormal=b1.m_invMass+b2.m_invMass;kNormal+=b1.m_invI*(r1Sqr-rn1*rn1)+b2.m_invI*(r2Sqr-rn2*rn2);ccp.normalMass=1.0/kNormal;var tangentX=normalY
-var tangentY=-normalX;var rt1=r1X*tangentX+r1Y*tangentY;var rt2=r2X*tangentX+r2Y*tangentY;var kTangent=b1.m_invMass+b2.m_invMass;kTangent+=b1.m_invI*(r1Sqr-rt1*rt1)+b2.m_invI*(r2Sqr-rt2*rt2);ccp.tangentMass=1.0/kTangent;ccp.velocityBias=0.0;if(ccp.separation>0.0)
-{ccp.velocityBias=-60.0*ccp.separation;}
-var tX=v2X+(-w2*r2Y)-v1X-(-w1*r1Y);var tY=v2Y+(w2*r2X)-v1Y-(w1*r1X);var vRel=c.normal.x*tX+c.normal.y*tY;if(vRel<-b2Settings.b2_velocityThreshold)
-{ccp.velocityBias+=-c.restitution*vRel;}}
-++count;}}},PreSolve:function(){var tVec;var tVec2;var tMat;for(var i=0;i<this.m_constraintCount;++i)
-{var c=this.m_constraints[i];var b1=c.body1;var b2=c.body2;var invMass1=b1.m_invMass;var invI1=b1.m_invI;var invMass2=b2.m_invMass;var invI2=b2.m_invI;var normalX=c.normal.x;var normalY=c.normal.y;var tangentX=normalY;var tangentY=-normalX;var j=0;var tCount=0;if(b2World.s_enableWarmStarting)
-{tCount=c.pointCount;for(j=0;j<tCount;++j)
-{var ccp=c.points[j];var PX=ccp.normalImpulse*normalX+ccp.tangentImpulse*tangentX;var PY=ccp.normalImpulse*normalY+ccp.tangentImpulse*tangentY;tMat=b1.m_R;tVec=ccp.localAnchor1;var r1X=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var r1Y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=b2.m_R;tVec=ccp.localAnchor2;var r2X=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;var r2Y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;b1.m_angularVelocity-=invI1*(r1X*PY-r1Y*PX);b1.m_linearVelocity.x-=invMass1*PX;b1.m_linearVelocity.y-=invMass1*PY;b2.m_angularVelocity+=invI2*(r2X*PY-r2Y*PX);b2.m_linearVelocity.x+=invMass2*PX;b2.m_linearVelocity.y+=invMass2*PY;ccp.positionImpulse=0.0;}}
-else{tCount=c.pointCount;for(j=0;j<tCount;++j)
-{var ccp2=c.points[j];ccp2.normalImpulse=0.0;ccp2.tangentImpulse=0.0;ccp2.positionImpulse=0.0;}}}},SolveVelocityConstraints:function(){var j=0;var ccp;var r1X;var r1Y;var r2X;var r2Y;var dvX;var dvY;var lambda;var newImpulse;var PX;var PY;var tMat;var tVec;for(var i=0;i<this.m_constraintCount;++i)
-{var c=this.m_constraints[i];var b1=c.body1;var b2=c.body2;var b1_angularVelocity=b1.m_angularVelocity;var b1_linearVelocity=b1.m_linearVelocity;var b2_angularVelocity=b2.m_angularVelocity;var b2_linearVelocity=b2.m_linearVelocity;var invMass1=b1.m_invMass;var invI1=b1.m_invI;var invMass2=b2.m_invMass;var invI2=b2.m_invI;var normalX=c.normal.x;var normalY=c.normal.y;var tangentX=normalY;var tangentY=-normalX;var tCount=c.pointCount;for(j=0;j<tCount;++j)
-{ccp=c.points[j];tMat=b1.m_R;tVec=ccp.localAnchor1;r1X=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y
-r1Y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y
-tMat=b2.m_R;tVec=ccp.localAnchor2;r2X=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y
-r2Y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y
-dvX=b2_linearVelocity.x+(-b2_angularVelocity*r2Y)-b1_linearVelocity.x-(-b1_angularVelocity*r1Y);dvY=b2_linearVelocity.y+(b2_angularVelocity*r2X)-b1_linearVelocity.y-(b1_angularVelocity*r1X);var vn=dvX*normalX+dvY*normalY;lambda=-ccp.normalMass*(vn-ccp.velocityBias);newImpulse=b2Math.b2Max(ccp.normalImpulse+lambda,0.0);lambda=newImpulse-ccp.normalImpulse;PX=lambda*normalX;PY=lambda*normalY;b1_linearVelocity.x-=invMass1*PX;b1_linearVelocity.y-=invMass1*PY;b1_angularVelocity-=invI1*(r1X*PY-r1Y*PX);b2_linearVelocity.x+=invMass2*PX;b2_linearVelocity.y+=invMass2*PY;b2_angularVelocity+=invI2*(r2X*PY-r2Y*PX);ccp.normalImpulse=newImpulse;dvX=b2_linearVelocity.x+(-b2_angularVelocity*r2Y)-b1_linearVelocity.x-(-b1_angularVelocity*r1Y);dvY=b2_linearVelocity.y+(b2_angularVelocity*r2X)-b1_linearVelocity.y-(b1_angularVelocity*r1X);var vt=dvX*tangentX+dvY*tangentY;lambda=ccp.tangentMass*(-vt);var maxFriction=c.friction*ccp.normalImpulse;newImpulse=b2Math.b2Clamp(ccp.tangentImpulse+lambda,-maxFriction,maxFriction);lambda=newImpulse-ccp.tangentImpulse;PX=lambda*tangentX;PY=lambda*tangentY;b1_linearVelocity.x-=invMass1*PX;b1_linearVelocity.y-=invMass1*PY;b1_angularVelocity-=invI1*(r1X*PY-r1Y*PX);b2_linearVelocity.x+=invMass2*PX;b2_linearVelocity.y+=invMass2*PY;b2_angularVelocity+=invI2*(r2X*PY-r2Y*PX);ccp.tangentImpulse=newImpulse;}
-b1.m_angularVelocity=b1_angularVelocity;b2.m_angularVelocity=b2_angularVelocity;}},SolvePositionConstraints:function(beta){var minSeparation=0.0;var tMat;var tVec;for(var i=0;i<this.m_constraintCount;++i)
-{var c=this.m_constraints[i];var b1=c.body1;var b2=c.body2;var b1_position=b1.m_position;var b1_rotation=b1.m_rotation;var b2_position=b2.m_position;var b2_rotation=b2.m_rotation;var invMass1=b1.m_invMass;var invI1=b1.m_invI;var invMass2=b2.m_invMass;var invI2=b2.m_invI;var normalX=c.normal.x;var normalY=c.normal.y;var tangentX=normalY;var tangentY=-normalX;var tCount=c.pointCount;for(var j=0;j<tCount;++j)
-{var ccp=c.points[j];tMat=b1.m_R;tVec=ccp.localAnchor1;var r1X=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y
-var r1Y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y
-tMat=b2.m_R;tVec=ccp.localAnchor2;var r2X=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y
-var r2Y=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y
-var p1X=b1_position.x+r1X;var p1Y=b1_position.y+r1Y;var p2X=b2_position.x+r2X;var p2Y=b2_position.y+r2Y;var dpX=p2X-p1X;var dpY=p2Y-p1Y;var separation=(dpX*normalX+dpY*normalY)+ccp.separation;minSeparation=b2Math.b2Min(minSeparation,separation);var C=beta*b2Math.b2Clamp(separation+b2Settings.b2_linearSlop,-b2Settings.b2_maxLinearCorrection,0.0);var dImpulse=-ccp.normalMass*C;var impulse0=ccp.positionImpulse;ccp.positionImpulse=b2Math.b2Max(impulse0+dImpulse,0.0);dImpulse=ccp.positionImpulse-impulse0;var impulseX=dImpulse*normalX;var impulseY=dImpulse*normalY;b1_position.x-=invMass1*impulseX;b1_position.y-=invMass1*impulseY;b1_rotation-=invI1*(r1X*impulseY-r1Y*impulseX);b1.m_R.Set(b1_rotation);b2_position.x+=invMass2*impulseX;b2_position.y+=invMass2*impulseY;b2_rotation+=invI2*(r2X*impulseY-r2Y*impulseX);b2.m_R.Set(b2_rotation);}
-b1.m_rotation=b1_rotation;b2.m_rotation=b2_rotation;}
-return minSeparation>=-b2Settings.b2_linearSlop;},PostSolve:function(){for(var i=0;i<this.m_constraintCount;++i)
-{var c=this.m_constraints[i];var m=c.manifold;for(var j=0;j<c.pointCount;++j)
-{var mPoint=m.points[j];var cPoint=c.points[j];mPoint.normalImpulse=cPoint.normalImpulse;mPoint.tangentImpulse=cPoint.tangentImpulse;}}},m_allocator:null,m_constraints:new Array(),m_constraintCount:0};
-var b2CircleContact=Class.create();Object.extend(b2CircleContact.prototype,b2Contact.prototype);Object.extend(b2CircleContact.prototype,{initialize:function(s1,s2){this.m_node1=new b2ContactNode();this.m_node2=new b2ContactNode();this.m_flags=0;if(!s1||!s2){this.m_shape1=null;this.m_shape2=null;return;}
-this.m_shape1=s1;this.m_shape2=s2;this.m_manifoldCount=0;this.m_friction=Math.sqrt(this.m_shape1.m_friction*this.m_shape2.m_friction);this.m_restitution=b2Math.b2Max(this.m_shape1.m_restitution,this.m_shape2.m_restitution);this.m_prev=null;this.m_next=null;this.m_node1.contact=null;this.m_node1.prev=null;this.m_node1.next=null;this.m_node1.other=null;this.m_node2.contact=null;this.m_node2.prev=null;this.m_node2.next=null;this.m_node2.other=null;this.m_manifold=[new b2Manifold()];this.m_manifold[0].pointCount=0;this.m_manifold[0].points[0].normalImpulse=0.0;this.m_manifold[0].points[0].tangentImpulse=0.0;},Evaluate:function(){b2Collision.b2CollideCircle(this.m_manifold[0],this.m_shape1,this.m_shape2,false);if(this.m_manifold[0].pointCount>0)
-{this.m_manifoldCount=1;}
-else
-{this.m_manifoldCount=0;}},GetManifolds:function()
-{return this.m_manifold;},m_manifold:[new b2Manifold()]});b2CircleContact.Create=function(shape1,shape2,allocator){return new b2CircleContact(shape1,shape2);};b2CircleContact.Destroy=function(contact,allocator){};
-var b2Conservative=Class.create();b2Conservative.prototype={initialize:function(){}}
-b2Conservative.R1=new b2Mat22();b2Conservative.R2=new b2Mat22();b2Conservative.x1=new b2Vec2();b2Conservative.x2=new b2Vec2();b2Conservative.Conservative=function(shape1,shape2){var body1=shape1.GetBody();var body2=shape2.GetBody();var v1X=body1.m_position.x-body1.m_position0.x;var v1Y=body1.m_position.y-body1.m_position0.y;var omega1=body1.m_rotation-body1.m_rotation0;var v2X=body2.m_position.x-body2.m_position0.x;var v2Y=body2.m_position.y-body2.m_position0.y;var omega2=body2.m_rotation-body2.m_rotation0;var r1=shape1.GetMaxRadius();var r2=shape2.GetMaxRadius();var p1StartX=body1.m_position0.x;var p1StartY=body1.m_position0.y;var a1Start=body1.m_rotation0;var p2StartX=body2.m_position0.x;var p2StartY=body2.m_position0.y;var a2Start=body2.m_rotation0;var p1X=p1StartX;var p1Y=p1StartY;var a1=a1Start;var p2X=p2StartX;var p2Y=p2StartY;var a2=a2Start;b2Conservative.R1.Set(a1);b2Conservative.R2.Set(a2);shape1.QuickSync(p1,b2Conservative.R1);shape2.QuickSync(p2,b2Conservative.R2);var s1=0.0;var maxIterations=10;var dX;var dY;var invRelativeVelocity=0.0;var hit=true;for(var iter=0;iter<maxIterations;++iter)
-{var distance=b2Distance.Distance(b2Conservative.x1,b2Conservative.x2,shape1,shape2);if(distance<b2Settings.b2_linearSlop)
-{if(iter==0)
-{hit=false;}
-else
-{hit=true;}
-break;}
-if(iter==0)
-{dX=b2Conservative.x2.x-b2Conservative.x1.x;dY=b2Conservative.x2.y-b2Conservative.x1.y;var dLen=Math.sqrt(dX*dX+dY*dY);var relativeVelocity=(dX*(v1X-v2X)+dY*(v1Y-v2Y))+Math.abs(omega1)*r1+Math.abs(omega2)*r2;if(Math.abs(relativeVelocity)<Number.MIN_VALUE)
-{hit=false;break;}
-invRelativeVelocity=1.0/relativeVelocity;}
-var ds=distance*invRelativeVelocity;var s2=s1+ds;if(s2<0.0||1.0<s2)
-{hit=false;break;}
-if(s2<(1.0+100.0*Number.MIN_VALUE)*s1)
-{hit=true;break;}
-s1=s2;p1X=p1StartX+s1*v1.x;p1Y=p1StartY+s1*v1.y;a1=a1Start+s1*omega1;p2X=p2StartX+s1*v2.x;p2Y=p2StartY+s1*v2.y;a2=a2Start+s1*omega2;b2Conservative.R1.Set(a1);b2Conservative.R2.Set(a2);shape1.QuickSync(p1,b2Conservative.R1);shape2.QuickSync(p2,b2Conservative.R2);}
-if(hit)
-{dX=b2Conservative.x2.x-b2Conservative.x1.x;dY=b2Conservative.x2.y-b2Conservative.x1.y;var length=Math.sqrt(dX*dX+dY*dY);if(length>FLT_EPSILON)
-{d*=b2_linearSlop/length;}
-if(body1.IsStatic())
-{body1.m_position.x=p1X;body1.m_position.y=p1Y;}
-else
-{body1.m_position.x=p1X-dX;body1.m_position.y=p1Y-dY;}
-body1.m_rotation=a1;body1.m_R.Set(a1);body1.QuickSyncShapes();if(body2.IsStatic())
-{body2.m_position.x=p2X;body2.m_position.y=p2Y;}
-else
-{body2.m_position.x=p2X+dX;body2.m_position.y=p2Y+dY;}
-body2.m_position.x=p2X+dX;body2.m_position.y=p2Y+dY;body2.m_rotation=a2;body2.m_R.Set(a2);body2.QuickSyncShapes();return true;}
-shape1.QuickSync(body1.m_position,body1.m_R);shape2.QuickSync(body2.m_position,body2.m_R);return false;};
-var b2NullContact=Class.create();Object.extend(b2NullContact.prototype,b2Contact.prototype);Object.extend(b2NullContact.prototype,{initialize:function(s1,s2){this.m_node1=new b2ContactNode();this.m_node2=new b2ContactNode();this.m_flags=0;if(!s1||!s2){this.m_shape1=null;this.m_shape2=null;return;}
-this.m_shape1=s1;this.m_shape2=s2;this.m_manifoldCount=0;this.m_friction=Math.sqrt(this.m_shape1.m_friction*this.m_shape2.m_friction);this.m_restitution=b2Math.b2Max(this.m_shape1.m_restitution,this.m_shape2.m_restitution);this.m_prev=null;this.m_next=null;this.m_node1.contact=null;this.m_node1.prev=null;this.m_node1.next=null;this.m_node1.other=null;this.m_node2.contact=null;this.m_node2.prev=null;this.m_node2.next=null;this.m_node2.other=null;},Evaluate:function(){},GetManifolds:function(){return null;}});
-var b2PolyAndCircleContact=Class.create();Object.extend(b2PolyAndCircleContact.prototype,b2Contact.prototype);Object.extend(b2PolyAndCircleContact.prototype,{initialize:function(s1,s2){this.m_node1=new b2ContactNode();this.m_node2=new b2ContactNode();this.m_flags=0;if(!s1||!s2){this.m_shape1=null;this.m_shape2=null;return;}
-this.m_shape1=s1;this.m_shape2=s2;this.m_manifoldCount=0;this.m_friction=Math.sqrt(this.m_shape1.m_friction*this.m_shape2.m_friction);this.m_restitution=b2Math.b2Max(this.m_shape1.m_restitution,this.m_shape2.m_restitution);this.m_prev=null;this.m_next=null;this.m_node1.contact=null;this.m_node1.prev=null;this.m_node1.next=null;this.m_node1.other=null;this.m_node2.contact=null;this.m_node2.prev=null;this.m_node2.next=null;this.m_node2.other=null;this.m_manifold=[new b2Manifold()];b2Settings.b2Assert(this.m_shape1.m_type==b2Shape.e_polyShape);b2Settings.b2Assert(this.m_shape2.m_type==b2Shape.e_circleShape);this.m_manifold[0].pointCount=0;this.m_manifold[0].points[0].normalImpulse=0.0;this.m_manifold[0].points[0].tangentImpulse=0.0;},Evaluate:function(){b2Collision.b2CollidePolyAndCircle(this.m_manifold[0],this.m_shape1,this.m_shape2,false);if(this.m_manifold[0].pointCount>0)
-{this.m_manifoldCount=1;}
-else
-{this.m_manifoldCount=0;}},GetManifolds:function()
-{return this.m_manifold;},m_manifold:[new b2Manifold()]})
-b2PolyAndCircleContact.Create=function(shape1,shape2,allocator){return new b2PolyAndCircleContact(shape1,shape2);};b2PolyAndCircleContact.Destroy=function(contact,allocator){};
-var b2PolyContact=Class.create();Object.extend(b2PolyContact.prototype,b2Contact.prototype);Object.extend(b2PolyContact.prototype,{initialize:function(s1,s2){this.m_node1=new b2ContactNode();this.m_node2=new b2ContactNode();this.m_flags=0;if(!s1||!s2){this.m_shape1=null;this.m_shape2=null;return;}
-this.m_shape1=s1;this.m_shape2=s2;this.m_manifoldCount=0;this.m_friction=Math.sqrt(this.m_shape1.m_friction*this.m_shape2.m_friction);this.m_restitution=b2Math.b2Max(this.m_shape1.m_restitution,this.m_shape2.m_restitution);this.m_prev=null;this.m_next=null;this.m_node1.contact=null;this.m_node1.prev=null;this.m_node1.next=null;this.m_node1.other=null;this.m_node2.contact=null;this.m_node2.prev=null;this.m_node2.next=null;this.m_node2.other=null;this.m0=new b2Manifold();this.m_manifold=[new b2Manifold()];this.m_manifold[0].pointCount=0;},m0:new b2Manifold(),Evaluate:function(){var tMani=this.m_manifold[0];var tPoints=this.m0.points;for(var k=0;k<tMani.pointCount;k++){var tPoint=tPoints[k];var tPoint0=tMani.points[k];tPoint.normalImpulse=tPoint0.normalImpulse;tPoint.tangentImpulse=tPoint0.tangentImpulse;tPoint.id=tPoint0.id.Copy();}
-this.m0.pointCount=tMani.pointCount;b2Collision.b2CollidePoly(tMani,this.m_shape1,this.m_shape2,false);if(tMani.pointCount>0)
-{var match=[false,false];for(var i=0;i<tMani.pointCount;++i)
-{var cp=tMani.points[i];cp.normalImpulse=0.0;cp.tangentImpulse=0.0;var idKey=cp.id.key;for(var j=0;j<this.m0.pointCount;++j)
-{if(match[j]==true)
-continue;var cp0=this.m0.points[j];var id0=cp0.id;if(id0.key==idKey)
-{match[j]=true;cp.normalImpulse=cp0.normalImpulse;cp.tangentImpulse=cp0.tangentImpulse;break;}}}
-this.m_manifoldCount=1;}
-else
-{this.m_manifoldCount=0;}},GetManifolds:function()
-{return this.m_manifold;},m_manifold:[new b2Manifold()]});b2PolyContact.Create=function(shape1,shape2,allocator){return new b2PolyContact(shape1,shape2);};b2PolyContact.Destroy=function(contact,allocator){};
-var b2ContactManager=Class.create();Object.extend(b2ContactManager.prototype,b2PairCallback.prototype);Object.extend(b2ContactManager.prototype,{initialize:function(){this.m_nullContact=new b2NullContact();this.m_world=null;this.m_destroyImmediate=false;},PairAdded:function(proxyUserData1,proxyUserData2){var shape1=proxyUserData1;var shape2=proxyUserData2;var body1=shape1.m_body;var body2=shape2.m_body;if(body1.IsStatic()&&body2.IsStatic())
-{return this.m_nullContact;}
-if(shape1.m_body==shape2.m_body)
-{return this.m_nullContact;}
-if(body2.IsConnected(body1))
-{return this.m_nullContact;}
-if(this.m_world.m_filter!=null&&this.m_world.m_filter.ShouldCollide(shape1,shape2)==false)
-{return this.m_nullContact;}
-if(body2.m_invMass==0.0)
-{var tempShape=shape1;shape1=shape2;shape2=tempShape;var tempBody=body1;body1=body2;body2=tempBody;}
-var contact=b2Contact.Create(shape1,shape2,this.m_world.m_blockAllocator);if(contact==null)
-{return this.m_nullContact;}
-else
-{contact.m_prev=null;contact.m_next=this.m_world.m_contactList;if(this.m_world.m_contactList!=null)
-{this.m_world.m_contactList.m_prev=contact;}
-this.m_world.m_contactList=contact;this.m_world.m_contactCount++;}
-return contact;},PairRemoved:function(proxyUserData1,proxyUserData2,pairUserData){if(pairUserData==null)
-{return;}
-var c=pairUserData;if(c!=this.m_nullContact)
-{if(this.m_destroyImmediate==true)
-{this.DestroyContact(c);c=null;}
-else
-{c.m_flags|=b2Contact.e_destroyFlag;}}},DestroyContact:function(c)
-{if(c.m_prev)
-{c.m_prev.m_next=c.m_next;}
-if(c.m_next)
-{c.m_next.m_prev=c.m_prev;}
-if(c==this.m_world.m_contactList)
-{this.m_world.m_contactList=c.m_next;}
-if(c.GetManifoldCount()>0)
-{var body1=c.m_shape1.m_body;var body2=c.m_shape2.m_body;var node1=c.m_node1;var node2=c.m_node2;body1.WakeUp();body2.WakeUp();if(node1.prev)
-{node1.prev.next=node1.next;}
-if(node1.next)
-{node1.next.prev=node1.prev;}
-if(node1==body1.m_contactList)
-{body1.m_contactList=node1.next;}
-node1.prev=null;node1.next=null;if(node2.prev)
-{node2.prev.next=node2.next;}
-if(node2.next)
-{node2.next.prev=node2.prev;}
-if(node2==body2.m_contactList)
-{body2.m_contactList=node2.next;}
-node2.prev=null;node2.next=null;}
-b2Contact.Destroy(c,this.m_world.m_blockAllocator);--this.m_world.m_contactCount;},CleanContactList:function()
-{var c=this.m_world.m_contactList;while(c!=null)
-{var c0=c;c=c.m_next;if(c0.m_flags&b2Contact.e_destroyFlag)
-{this.DestroyContact(c0);c0=null;}}},Collide:function()
-{var body1;var body2;var node1;var node2;for(var c=this.m_world.m_contactList;c!=null;c=c.m_next)
-{if(c.m_shape1.m_body.IsSleeping()&&c.m_shape2.m_body.IsSleeping())
-{continue;}
-var oldCount=c.GetManifoldCount();c.Evaluate();var newCount=c.GetManifoldCount();if(oldCount==0&&newCount>0)
-{body1=c.m_shape1.m_body;body2=c.m_shape2.m_body;node1=c.m_node1;node2=c.m_node2;node1.contact=c;node1.other=body2;node1.prev=null;node1.next=body1.m_contactList;if(node1.next!=null)
-{node1.next.prev=c.m_node1;}
-body1.m_contactList=c.m_node1;node2.contact=c;node2.other=body1;node2.prev=null;node2.next=body2.m_contactList;if(node2.next!=null)
-{node2.next.prev=node2;}
-body2.m_contactList=node2;}
-else if(oldCount>0&&newCount==0)
-{body1=c.m_shape1.m_body;body2=c.m_shape2.m_body;node1=c.m_node1;node2=c.m_node2;if(node1.prev)
-{node1.prev.next=node1.next;}
-if(node1.next)
-{node1.next.prev=node1.prev;}
-if(node1==body1.m_contactList)
-{body1.m_contactList=node1.next;}
-node1.prev=null;node1.next=null;if(node2.prev)
-{node2.prev.next=node2.next;}
-if(node2.next)
-{node2.next.prev=node2.prev;}
-if(node2==body2.m_contactList)
-{body2.m_contactList=node2.next;}
-node2.prev=null;node2.next=null;}}},m_world:null,m_nullContact:new b2NullContact(),m_destroyImmediate:null});
-var b2World=Class.create();b2World.prototype={initialize:function(worldAABB,gravity,doSleep){this.step=new b2TimeStep();this.m_contactManager=new b2ContactManager();this.m_listener=null;this.m_filter=b2CollisionFilter.b2_defaultFilter;this.m_bodyList=null;this.m_contactList=null;this.m_jointList=null;this.m_bodyCount=0;this.m_contactCount=0;this.m_jointCount=0;this.m_bodyDestroyList=null;this.m_allowSleep=doSleep;this.m_gravity=gravity;this.m_contactManager.m_world=this;this.m_broadPhase=new b2BroadPhase(worldAABB,this.m_contactManager);var bd=new b2BodyDef();this.m_groundBody=this.CreateBody(bd);},SetListener:function(listener){this.m_listener=listener;},SetFilter:function(filter){this.m_filter=filter;},CreateBody:function(def){var b=new b2Body(def,this);b.m_prev=null;b.m_next=this.m_bodyList;if(this.m_bodyList)
-{this.m_bodyList.m_prev=b;}
-this.m_bodyList=b;++this.m_bodyCount;return b;},DestroyBody:function(b)
-{if(b.m_flags&b2Body.e_destroyFlag)
-{return;}
-if(b.m_prev)
-{b.m_prev.m_next=b.m_next;}
-if(b.m_next)
-{b.m_next.m_prev=b.m_prev;}
-if(b==this.m_bodyList)
-{this.m_bodyList=b.m_next;}
-b.m_flags|=b2Body.e_destroyFlag;--this.m_bodyCount;b.m_prev=null;b.m_next=this.m_bodyDestroyList;this.m_bodyDestroyList=b;},CleanBodyList:function()
-{this.m_contactManager.m_destroyImmediate=true;var b=this.m_bodyDestroyList;while(b)
-{var b0=b;b=b.m_next;var jn=b0.m_jointList;while(jn)
-{var jn0=jn;jn=jn.next;if(this.m_listener)
-{this.m_listener.NotifyJointDestroyed(jn0.joint);}
-this.DestroyJoint(jn0.joint);}
-b0.Destroy();}
-this.m_bodyDestroyList=null;this.m_contactManager.m_destroyImmediate=false;},CreateJoint:function(def){var j=b2Joint.Create(def,this.m_blockAllocator);j.m_prev=null;j.m_next=this.m_jointList;if(this.m_jointList)
-{this.m_jointList.m_prev=j;}
-this.m_jointList=j;++this.m_jointCount;j.m_node1.joint=j;j.m_node1.other=j.m_body2;j.m_node1.prev=null;j.m_node1.next=j.m_body1.m_jointList;if(j.m_body1.m_jointList)j.m_body1.m_jointList.prev=j.m_node1;j.m_body1.m_jointList=j.m_node1;j.m_node2.joint=j;j.m_node2.other=j.m_body1;j.m_node2.prev=null;j.m_node2.next=j.m_body2.m_jointList;if(j.m_body2.m_jointList)j.m_body2.m_jointList.prev=j.m_node2;j.m_body2.m_jointList=j.m_node2;if(def.collideConnected==false)
-{var b=def.body1.m_shapeCount<def.body2.m_shapeCount?def.body1:def.body2;for(var s=b.m_shapeList;s;s=s.m_next)
-{s.ResetProxy(this.m_broadPhase);}}
-return j;},DestroyJoint:function(j)
-{var collideConnected=j.m_collideConnected;if(j.m_prev)
-{j.m_prev.m_next=j.m_next;}
-if(j.m_next)
-{j.m_next.m_prev=j.m_prev;}
-if(j==this.m_jointList)
-{this.m_jointList=j.m_next;}
-var body1=j.m_body1;var body2=j.m_body2;body1.WakeUp();body2.WakeUp();if(j.m_node1.prev)
-{j.m_node1.prev.next=j.m_node1.next;}
-if(j.m_node1.next)
-{j.m_node1.next.prev=j.m_node1.prev;}
-if(j.m_node1==body1.m_jointList)
-{body1.m_jointList=j.m_node1.next;}
-j.m_node1.prev=null;j.m_node1.next=null;if(j.m_node2.prev)
-{j.m_node2.prev.next=j.m_node2.next;}
-if(j.m_node2.next)
-{j.m_node2.next.prev=j.m_node2.prev;}
-if(j.m_node2==body2.m_jointList)
-{body2.m_jointList=j.m_node2.next;}
-j.m_node2.prev=null;j.m_node2.next=null;b2Joint.Destroy(j,this.m_blockAllocator);--this.m_jointCount;if(collideConnected==false)
-{var b=body1.m_shapeCount<body2.m_shapeCount?body1:body2;for(var s=b.m_shapeList;s;s=s.m_next)
-{s.ResetProxy(this.m_broadPhase);}}},GetGroundBody:function(){return this.m_groundBody;},step:new b2TimeStep(),Step:function(dt,iterations){var b;var other;this.step.dt=dt;this.step.iterations=iterations;if(dt>0.0)
-{this.step.inv_dt=1.0/dt;}
-else
-{this.step.inv_dt=0.0;}
-this.m_positionIterationCount=0;this.m_contactManager.CleanContactList();this.CleanBodyList();this.m_contactManager.Collide();var island=new b2Island(this.m_bodyCount,this.m_contactCount,this.m_jointCount,this.m_stackAllocator);for(b=this.m_bodyList;b!=null;b=b.m_next)
-{b.m_flags&=~b2Body.e_islandFlag;}
-for(var c=this.m_contactList;c!=null;c=c.m_next)
-{c.m_flags&=~b2Contact.e_islandFlag;}
-for(var j=this.m_jointList;j!=null;j=j.m_next)
-{j.m_islandFlag=false;}
-var stackSize=this.m_bodyCount;var stack=new Array(this.m_bodyCount);for(var k=0;k<this.m_bodyCount;k++)
-stack[k]=null;for(var seed=this.m_bodyList;seed!=null;seed=seed.m_next)
-{if(seed.m_flags&(b2Body.e_staticFlag|b2Body.e_islandFlag|b2Body.e_sleepFlag|b2Body.e_frozenFlag))
-{continue;}
-island.Clear();var stackCount=0;stack[stackCount++]=seed;seed.m_flags|=b2Body.e_islandFlag;;while(stackCount>0)
-{b=stack[--stackCount];island.AddBody(b);b.m_flags&=~b2Body.e_sleepFlag;if(b.m_flags&b2Body.e_staticFlag)
-{continue;}
-for(var cn=b.m_contactList;cn!=null;cn=cn.next)
-{if(cn.contact.m_flags&b2Contact.e_islandFlag)
-{continue;}
-island.AddContact(cn.contact);cn.contact.m_flags|=b2Contact.e_islandFlag;other=cn.other;if(other.m_flags&b2Body.e_islandFlag)
-{continue;}
-stack[stackCount++]=other;other.m_flags|=b2Body.e_islandFlag;}
-for(var jn=b.m_jointList;jn!=null;jn=jn.next)
-{if(jn.joint.m_islandFlag==true)
-{continue;}
-island.AddJoint(jn.joint);jn.joint.m_islandFlag=true;other=jn.other;if(other.m_flags&b2Body.e_islandFlag)
-{continue;}
-stack[stackCount++]=other;other.m_flags|=b2Body.e_islandFlag;}}
-island.Solve(this.step,this.m_gravity);this.m_positionIterationCount=b2Math.b2Max(this.m_positionIterationCount,b2Island.m_positionIterationCount);if(this.m_allowSleep)
-{island.UpdateSleep(dt);}
-for(var i=0;i<island.m_bodyCount;++i)
-{b=island.m_bodies[i];if(b.m_flags&b2Body.e_staticFlag)
-{b.m_flags&=~b2Body.e_islandFlag;}
-if(b.IsFrozen()&&this.m_listener)
-{var response=this.m_listener.NotifyBoundaryViolated(b);if(response==b2WorldListener.b2_destroyBody)
-{this.DestroyBody(b);b=null;island.m_bodies[i]=null;}}}}
-this.m_broadPhase.Commit();},Query:function(aabb,shapes,maxCount){var results=new Array();var count=this.m_broadPhase.QueryAABB(aabb,results,maxCount);for(var i=0;i<count;++i)
-{shapes[i]=results[i];}
-return count;},GetBodyList:function(){return this.m_bodyList;},GetJointList:function(){return this.m_jointList;},GetContactList:function(){return this.m_contactList;},m_blockAllocator:null,m_stackAllocator:null,m_broadPhase:null,m_contactManager:new b2ContactManager(),m_bodyList:null,m_contactList:null,m_jointList:null,m_bodyCount:0,m_contactCount:0,m_jointCount:0,m_bodyDestroyList:null,m_gravity:null,m_allowSleep:null,m_groundBody:null,m_listener:null,m_filter:null,m_positionIterationCount:0};b2World.s_enablePositionCorrection=1;b2World.s_enableWarmStarting=1;
-var b2WorldListener=Class.create();b2WorldListener.prototype={NotifyJointDestroyed:function(joint){},NotifyBoundaryViolated:function(body)
-{return b2WorldListener.b2_freezeBody;},initialize:function(){}};b2WorldListener.b2_freezeBody=0;b2WorldListener.b2_destroyBody=1;
-var b2JointNode=Class.create();b2JointNode.prototype={other:null,joint:null,prev:null,next:null,initialize:function(){}}
-
-var b2Joint=Class.create();b2Joint.prototype={GetType:function(){return this.m_type;},GetAnchor1:function(){return null},GetAnchor2:function(){return null},GetReactionForce:function(invTimeStep){return null},GetReactionTorque:function(invTimeStep){return 0.0},GetBody1:function()
-{return this.m_body1;},GetBody2:function()
-{return this.m_body2;},GetNext:function(){return this.m_next;},GetUserData:function(){return this.m_userData;},initialize:function(def){this.m_node1=new b2JointNode();this.m_node2=new b2JointNode();this.m_type=def.type;this.m_prev=null;this.m_next=null;this.m_body1=def.body1;this.m_body2=def.body2;this.m_collideConnected=def.collideConnected;this.m_islandFlag=false;this.m_userData=def.userData;},PrepareVelocitySolver:function(){},SolveVelocityConstraints:function(step){},PreparePositionSolver:function(){},SolvePositionConstraints:function(){return false},m_type:0,m_prev:null,m_next:null,m_node1:new b2JointNode(),m_node2:new b2JointNode(),m_body1:null,m_body2:null,m_islandFlag:null,m_collideConnected:null,m_userData:null};b2Joint.Create=function(def,allocator){var joint=null;switch(def.type)
-{case b2Joint.e_distanceJoint:{joint=new b2DistanceJoint(def);}
-break;case b2Joint.e_mouseJoint:{joint=new b2MouseJoint(def);}
-break;case b2Joint.e_prismaticJoint:{joint=new b2PrismaticJoint(def);}
-break;case b2Joint.e_revoluteJoint:{joint=new b2RevoluteJoint(def);}
-break;case b2Joint.e_pulleyJoint:{joint=new b2PulleyJoint(def);}
-break;case b2Joint.e_gearJoint:{joint=new b2GearJoint(def);}
-break;default:break;}
-return joint;};b2Joint.Destroy=function(joint,allocator){};b2Joint.e_unknownJoint=0;b2Joint.e_revoluteJoint=1;b2Joint.e_prismaticJoint=2;b2Joint.e_distanceJoint=3;b2Joint.e_pulleyJoint=4;b2Joint.e_mouseJoint=5;b2Joint.e_gearJoint=6;b2Joint.e_inactiveLimit=0;b2Joint.e_atLowerLimit=1;b2Joint.e_atUpperLimit=2;b2Joint.e_equalLimits=3;
-var b2JointDef=Class.create();b2JointDef.prototype={initialize:function()
-{this.type=b2Joint.e_unknownJoint;this.userData=null;this.body1=null;this.body2=null;this.collideConnected=false;},type:0,userData:null,body1:null,body2:null,collideConnected:null}
-
-var b2DistanceJoint=Class.create();Object.extend(b2DistanceJoint.prototype,b2Joint.prototype);Object.extend(b2DistanceJoint.prototype,{initialize:function(def){this.m_node1=new b2JointNode();this.m_node2=new b2JointNode();this.m_type=def.type;this.m_prev=null;this.m_next=null;this.m_body1=def.body1;this.m_body2=def.body2;this.m_collideConnected=def.collideConnected;this.m_islandFlag=false;this.m_userData=def.userData;this.m_localAnchor1=new b2Vec2();this.m_localAnchor2=new b2Vec2();this.m_u=new b2Vec2();var tMat;var tX;var tY;tMat=this.m_body1.m_R;tX=def.anchorPoint1.x-this.m_body1.m_position.x;tY=def.anchorPoint1.y-this.m_body1.m_position.y;this.m_localAnchor1.x=tX*tMat.col1.x+tY*tMat.col1.y;this.m_localAnchor1.y=tX*tMat.col2.x+tY*tMat.col2.y;tMat=this.m_body2.m_R;tX=def.anchorPoint2.x-this.m_body2.m_position.x;tY=def.anchorPoint2.y-this.m_body2.m_position.y;this.m_localAnchor2.x=tX*tMat.col1.x+tY*tMat.col1.y;this.m_localAnchor2.y=tX*tMat.col2.x+tY*tMat.col2.y;tX=def.anchorPoint2.x-def.anchorPoint1.x;tY=def.anchorPoint2.y-def.anchorPoint1.y;this.m_length=Math.sqrt(tX*tX+tY*tY);this.m_impulse=0.0;},PrepareVelocitySolver:function(){var tMat;tMat=this.m_body1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=this.m_body2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;this.m_u.x=this.m_body2.m_position.x+r2X-this.m_body1.m_position.x-r1X;this.m_u.y=this.m_body2.m_position.y+r2Y-this.m_body1.m_position.y-r1Y;var length=Math.sqrt(this.m_u.x*this.m_u.x+this.m_u.y*this.m_u.y);if(length>b2Settings.b2_linearSlop)
-{this.m_u.Multiply(1.0/length);}
-else
-{this.m_u.SetZero();}
-var cr1u=(r1X*this.m_u.y-r1Y*this.m_u.x);var cr2u=(r2X*this.m_u.y-r2Y*this.m_u.x);this.m_mass=this.m_body1.m_invMass+this.m_body1.m_invI*cr1u*cr1u+this.m_body2.m_invMass+this.m_body2.m_invI*cr2u*cr2u;this.m_mass=1.0/this.m_mass;if(b2World.s_enableWarmStarting)
-{var PX=this.m_impulse*this.m_u.x;var PY=this.m_impulse*this.m_u.y;this.m_body1.m_linearVelocity.x-=this.m_body1.m_invMass*PX;this.m_body1.m_linearVelocity.y-=this.m_body1.m_invMass*PY;this.m_body1.m_angularVelocity-=this.m_body1.m_invI*(r1X*PY-r1Y*PX);this.m_body2.m_linearVelocity.x+=this.m_body2.m_invMass*PX;this.m_body2.m_linearVelocity.y+=this.m_body2.m_invMass*PY;this.m_body2.m_angularVelocity+=this.m_body2.m_invI*(r2X*PY-r2Y*PX);}
-else
-{this.m_impulse=0.0;}},SolveVelocityConstraints:function(step){var tMat;tMat=this.m_body1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=this.m_body2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var v1X=this.m_body1.m_linearVelocity.x+(-this.m_body1.m_angularVelocity*r1Y);var v1Y=this.m_body1.m_linearVelocity.y+(this.m_body1.m_angularVelocity*r1X);var v2X=this.m_body2.m_linearVelocity.x+(-this.m_body2.m_angularVelocity*r2Y);var v2Y=this.m_body2.m_linearVelocity.y+(this.m_body2.m_angularVelocity*r2X);var Cdot=(this.m_u.x*(v2X-v1X)+this.m_u.y*(v2Y-v1Y));var impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;var PX=impulse*this.m_u.x;var PY=impulse*this.m_u.y;this.m_body1.m_linearVelocity.x-=this.m_body1.m_invMass*PX;this.m_body1.m_linearVelocity.y-=this.m_body1.m_invMass*PY;this.m_body1.m_angularVelocity-=this.m_body1.m_invI*(r1X*PY-r1Y*PX);this.m_body2.m_linearVelocity.x+=this.m_body2.m_invMass*PX;this.m_body2.m_linearVelocity.y+=this.m_body2.m_invMass*PY;this.m_body2.m_angularVelocity+=this.m_body2.m_invI*(r2X*PY-r2Y*PX);},SolvePositionConstraints:function(){var tMat;tMat=this.m_body1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=this.m_body2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var dX=this.m_body2.m_position.x+r2X-this.m_body1.m_position.x-r1X;var dY=this.m_body2.m_position.y+r2Y-this.m_body1.m_position.y-r1Y;var length=Math.sqrt(dX*dX+dY*dY);dX/=length;dY/=length;var C=length-this.m_length;C=b2Math.b2Clamp(C,-b2Settings.b2_maxLinearCorrection,b2Settings.b2_maxLinearCorrection);var impulse=-this.m_mass*C;this.m_u.Set(dX,dY);var PX=impulse*this.m_u.x;var PY=impulse*this.m_u.y;this.m_body1.m_position.x-=this.m_body1.m_invMass*PX;this.m_body1.m_position.y-=this.m_body1.m_invMass*PY;this.m_body1.m_rotation-=this.m_body1.m_invI*(r1X*PY-r1Y*PX);this.m_body2.m_position.x+=this.m_body2.m_invMass*PX;this.m_body2.m_position.y+=this.m_body2.m_invMass*PY;this.m_body2.m_rotation+=this.m_body2.m_invI*(r2X*PY-r2Y*PX);this.m_body1.m_R.Set(this.m_body1.m_rotation);this.m_body2.m_R.Set(this.m_body2.m_rotation);return b2Math.b2Abs(C)<b2Settings.b2_linearSlop;},GetAnchor1:function(){return b2Math.AddVV(this.m_body1.m_position,b2Math.b2MulMV(this.m_body1.m_R,this.m_localAnchor1));},GetAnchor2:function(){return b2Math.AddVV(this.m_body2.m_position,b2Math.b2MulMV(this.m_body2.m_R,this.m_localAnchor2));},GetReactionForce:function(invTimeStep)
-{var F=new b2Vec2();F.SetV(this.m_u);F.Multiply(this.m_impulse*invTimeStep);return F;},GetReactionTorque:function(invTimeStep)
-{return 0.0;},m_localAnchor1:new b2Vec2(),m_localAnchor2:new b2Vec2(),m_u:new b2Vec2(),m_impulse:null,m_mass:null,m_length:null});
-var b2DistanceJointDef=Class.create();Object.extend(b2DistanceJointDef.prototype,b2JointDef.prototype);Object.extend(b2DistanceJointDef.prototype,{initialize:function()
-{this.type=b2Joint.e_unknownJoint;this.userData=null;this.body1=null;this.body2=null;this.collideConnected=false;this.anchorPoint1=new b2Vec2();this.anchorPoint2=new b2Vec2();this.type=b2Joint.e_distanceJoint;},anchorPoint1:new b2Vec2(),anchorPoint2:new b2Vec2()});
-var b2Jacobian=Class.create();b2Jacobian.prototype={linear1:new b2Vec2(),angular1:null,linear2:new b2Vec2(),angular2:null,SetZero:function(){this.linear1.SetZero();this.angular1=0.0;this.linear2.SetZero();this.angular2=0.0;},Set:function(x1,a1,x2,a2){this.linear1.SetV(x1);this.angular1=a1;this.linear2.SetV(x2);this.angular2=a2;},Compute:function(x1,a1,x2,a2){return(this.linear1.x*x1.x+this.linear1.y*x1.y)+this.angular1*a1+(this.linear2.x*x2.x+this.linear2.y*x2.y)+this.angular2*a2;},initialize:function(){this.linear1=new b2Vec2();this.linear2=new b2Vec2();}};
-var b2GearJoint=Class.create();Object.extend(b2GearJoint.prototype,b2Joint.prototype);Object.extend(b2GearJoint.prototype,{GetAnchor1:function(){var tMat=this.m_body1.m_R;return new b2Vec2(this.m_body1.m_position.x+(tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y),this.m_body1.m_position.y+(tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y));},GetAnchor2:function(){var tMat=this.m_body2.m_R;return new b2Vec2(this.m_body2.m_position.x+(tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y),this.m_body2.m_position.y+(tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y));},GetReactionForce:function(invTimeStep){return new b2Vec2();},GetReactionTorque:function(invTimeStep){return 0.0;},GetRatio:function(){return this.m_ratio;},initialize:function(def){this.m_node1=new b2JointNode();this.m_node2=new b2JointNode();this.m_type=def.type;this.m_prev=null;this.m_next=null;this.m_body1=def.body1;this.m_body2=def.body2;this.m_collideConnected=def.collideConnected;this.m_islandFlag=false;this.m_userData=def.userData;this.m_groundAnchor1=new b2Vec2();this.m_groundAnchor2=new b2Vec2();this.m_localAnchor1=new b2Vec2();this.m_localAnchor2=new b2Vec2();this.m_J=new b2Jacobian();this.m_revolute1=null;this.m_prismatic1=null;this.m_revolute2=null;this.m_prismatic2=null;var coordinate1;var coordinate2;this.m_ground1=def.joint1.m_body1;this.m_body1=def.joint1.m_body2;if(def.joint1.m_type==b2Joint.e_revoluteJoint)
-{this.m_revolute1=def.joint1;this.m_groundAnchor1.SetV(this.m_revolute1.m_localAnchor1);this.m_localAnchor1.SetV(this.m_revolute1.m_localAnchor2);coordinate1=this.m_revolute1.GetJointAngle();}
-else
-{this.m_prismatic1=def.joint1;this.m_groundAnchor1.SetV(this.m_prismatic1.m_localAnchor1);this.m_localAnchor1.SetV(this.m_prismatic1.m_localAnchor2);coordinate1=this.m_prismatic1.GetJointTranslation();}
-this.m_ground2=def.joint2.m_body1;this.m_body2=def.joint2.m_body2;if(def.joint2.m_type==b2Joint.e_revoluteJoint)
-{this.m_revolute2=def.joint2;this.m_groundAnchor2.SetV(this.m_revolute2.m_localAnchor1);this.m_localAnchor2.SetV(this.m_revolute2.m_localAnchor2);coordinate2=this.m_revolute2.GetJointAngle();}
-else
-{this.m_prismatic2=def.joint2;this.m_groundAnchor2.SetV(this.m_prismatic2.m_localAnchor1);this.m_localAnchor2.SetV(this.m_prismatic2.m_localAnchor2);coordinate2=this.m_prismatic2.GetJointTranslation();}
-this.m_ratio=def.ratio;this.m_constant=coordinate1+this.m_ratio*coordinate2;this.m_impulse=0.0;},PrepareVelocitySolver:function(){var g1=this.m_ground1;var g2=this.m_ground2;var b1=this.m_body1;var b2=this.m_body2;var ugX;var ugY;var rX;var rY;var tMat;var tVec;var crug;var K=0.0;this.m_J.SetZero();if(this.m_revolute1)
-{this.m_J.angular1=-1.0;K+=b1.m_invI;}
-else
-{tMat=g1.m_R;tVec=this.m_prismatic1.m_localXAxis1;ugX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;ugY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=b1.m_R;rX=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;rY=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;crug=rX*ugY-rY*ugX;this.m_J.linear1.Set(-ugX,-ugY);this.m_J.angular1=-crug;K+=b1.m_invMass+b1.m_invI*crug*crug;}
-if(this.m_revolute2)
-{this.m_J.angular2=-this.m_ratio;K+=this.m_ratio*this.m_ratio*b2.m_invI;}
-else
-{tMat=g2.m_R;tVec=this.m_prismatic2.m_localXAxis1;ugX=tMat.col1.x*tVec.x+tMat.col2.x*tVec.y;ugY=tMat.col1.y*tVec.x+tMat.col2.y*tVec.y;tMat=b2.m_R;rX=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;rY=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;crug=rX*ugY-rY*ugX;this.m_J.linear2.Set(-this.m_ratio*ugX,-this.m_ratio*ugY);this.m_J.angular2=-this.m_ratio*crug;K+=this.m_ratio*this.m_ratio*(b2.m_invMass+b2.m_invI*crug*crug);}
-this.m_mass=1.0/K;b1.m_linearVelocity.x+=b1.m_invMass*this.m_impulse*this.m_J.linear1.x;b1.m_linearVelocity.y+=b1.m_invMass*this.m_impulse*this.m_J.linear1.y;b1.m_angularVelocity+=b1.m_invI*this.m_impulse*this.m_J.angular1;b2.m_linearVelocity.x+=b2.m_invMass*this.m_impulse*this.m_J.linear2.x;b2.m_linearVelocity.y+=b2.m_invMass*this.m_impulse*this.m_J.linear2.y;b2.m_angularVelocity+=b2.m_invI*this.m_impulse*this.m_J.angular2;},SolveVelocityConstraints:function(step){var b1=this.m_body1;var b2=this.m_body2;var Cdot=this.m_J.Compute(b1.m_linearVelocity,b1.m_angularVelocity,b2.m_linearVelocity,b2.m_angularVelocity);var impulse=-this.m_mass*Cdot;this.m_impulse+=impulse;b1.m_linearVelocity.x+=b1.m_invMass*impulse*this.m_J.linear1.x;b1.m_linearVelocity.y+=b1.m_invMass*impulse*this.m_J.linear1.y;b1.m_angularVelocity+=b1.m_invI*impulse*this.m_J.angular1;b2.m_linearVelocity.x+=b2.m_invMass*impulse*this.m_J.linear2.x;b2.m_linearVelocity.y+=b2.m_invMass*impulse*this.m_J.linear2.y;b2.m_angularVelocity+=b2.m_invI*impulse*this.m_J.angular2;},SolvePositionConstraints:function(){var linearError=0.0;var b1=this.m_body1;var b2=this.m_body2;var coordinate1;var coordinate2;if(this.m_revolute1)
-{coordinate1=this.m_revolute1.GetJointAngle();}
-else
-{coordinate1=this.m_prismatic1.GetJointTranslation();}
-if(this.m_revolute2)
-{coordinate2=this.m_revolute2.GetJointAngle();}
-else
-{coordinate2=this.m_prismatic2.GetJointTranslation();}
-var C=this.m_constant-(coordinate1+this.m_ratio*coordinate2);var impulse=-this.m_mass*C;b1.m_position.x+=b1.m_invMass*impulse*this.m_J.linear1.x;b1.m_position.y+=b1.m_invMass*impulse*this.m_J.linear1.y;b1.m_rotation+=b1.m_invI*impulse*this.m_J.angular1;b2.m_position.x+=b2.m_invMass*impulse*this.m_J.linear2.x;b2.m_position.y+=b2.m_invMass*impulse*this.m_J.linear2.y;b2.m_rotation+=b2.m_invI*impulse*this.m_J.angular2;b1.m_R.Set(b1.m_rotation);b2.m_R.Set(b2.m_rotation);return linearError<b2Settings.b2_linearSlop;},m_ground1:null,m_ground2:null,m_revolute1:null,m_prismatic1:null,m_revolute2:null,m_prismatic2:null,m_groundAnchor1:new b2Vec2(),m_groundAnchor2:new b2Vec2(),m_localAnchor1:new b2Vec2(),m_localAnchor2:new b2Vec2(),m_J:new b2Jacobian(),m_constant:null,m_ratio:null,m_mass:null,m_impulse:null});
-var b2GearJointDef=Class.create();Object.extend(b2GearJointDef.prototype,b2JointDef.prototype);Object.extend(b2GearJointDef.prototype,{initialize:function()
-{this.type=b2Joint.e_gearJoint;this.joint1=null;this.joint2=null;this.ratio=1.0;},joint1:null,joint2:null,ratio:null});
-var b2MouseJoint=Class.create();Object.extend(b2MouseJoint.prototype,b2Joint.prototype);Object.extend(b2MouseJoint.prototype,{GetAnchor1:function(){return this.m_target;},GetAnchor2:function(){var tVec=b2Math.b2MulMV(this.m_body2.m_R,this.m_localAnchor);tVec.Add(this.m_body2.m_position);return tVec;},GetReactionForce:function(invTimeStep)
-{var F=new b2Vec2();F.SetV(this.m_impulse);F.Multiply(invTimeStep);return F;},GetReactionTorque:function(invTimeStep)
-{return 0.0;},SetTarget:function(target){this.m_body2.WakeUp();this.m_target=target;},initialize:function(def){this.m_node1=new b2JointNode();this.m_node2=new b2JointNode();this.m_type=def.type;this.m_prev=null;this.m_next=null;this.m_body1=def.body1;this.m_body2=def.body2;this.m_collideConnected=def.collideConnected;this.m_islandFlag=false;this.m_userData=def.userData;this.K=new b2Mat22();this.K1=new b2Mat22();this.K2=new b2Mat22();this.m_localAnchor=new b2Vec2();this.m_target=new b2Vec2();this.m_impulse=new b2Vec2();this.m_ptpMass=new b2Mat22();this.m_C=new b2Vec2();this.m_target.SetV(def.target);var tX=this.m_target.x-this.m_body2.m_position.x;var tY=this.m_target.y-this.m_body2.m_position.y;this.m_localAnchor.x=(tX*this.m_body2.m_R.col1.x+tY*this.m_body2.m_R.col1.y);this.m_localAnchor.y=(tX*this.m_body2.m_R.col2.x+tY*this.m_body2.m_R.col2.y);this.m_maxForce=def.maxForce;this.m_impulse.SetZero();var mass=this.m_body2.m_mass;var omega=2.0*b2Settings.b2_pi*def.frequencyHz;var d=2.0*mass*def.dampingRatio*omega;var k=mass*omega*omega;this.m_gamma=1.0/(d+def.timeStep*k);this.m_beta=def.timeStep*k/(d+def.timeStep*k);},K:new b2Mat22(),K1:new b2Mat22(),K2:new b2Mat22(),PrepareVelocitySolver:function(){var b=this.m_body2;var tMat;tMat=b.m_R;var rX=tMat.col1.x*this.m_localAnchor.x+tMat.col2.x*this.m_localAnchor.y;var rY=tMat.col1.y*this.m_localAnchor.x+tMat.col2.y*this.m_localAnchor.y;var invMass=b.m_invMass;var invI=b.m_invI;this.K1.col1.x=invMass;this.K1.col2.x=0.0;this.K1.col1.y=0.0;this.K1.col2.y=invMass;this.K2.col1.x=invI*rY*rY;this.K2.col2.x=-invI*rX*rY;this.K2.col1.y=-invI*rX*rY;this.K2.col2.y=invI*rX*rX;this.K.SetM(this.K1);this.K.AddM(this.K2);this.K.col1.x+=this.m_gamma;this.K.col2.y+=this.m_gamma;this.K.Invert(this.m_ptpMass);this.m_C.x=b.m_position.x+rX-this.m_target.x;this.m_C.y=b.m_position.y+rY-this.m_target.y;b.m_angularVelocity*=0.98;var PX=this.m_impulse.x;var PY=this.m_impulse.y;b.m_linearVelocity.x+=invMass*PX;b.m_linearVelocity.y+=invMass*PY;b.m_angularVelocity+=invI*(rX*PY-rY*PX);},SolveVelocityConstraints:function(step){var body=this.m_body2;var tMat;tMat=body.m_R;var rX=tMat.col1.x*this.m_localAnchor.x+tMat.col2.x*this.m_localAnchor.y;var rY=tMat.col1.y*this.m_localAnchor.x+tMat.col2.y*this.m_localAnchor.y;var CdotX=body.m_linearVelocity.x+(-body.m_angularVelocity*rY);var CdotY=body.m_linearVelocity.y+(body.m_angularVelocity*rX);tMat=this.m_ptpMass;var tX=CdotX+(this.m_beta*step.inv_dt)*this.m_C.x+this.m_gamma*this.m_impulse.x;var tY=CdotY+(this.m_beta*step.inv_dt)*this.m_C.y+this.m_gamma*this.m_impulse.y;var impulseX=-(tMat.col1.x*tX+tMat.col2.x*tY);var impulseY=-(tMat.col1.y*tX+tMat.col2.y*tY);var oldImpulseX=this.m_impulse.x;var oldImpulseY=this.m_impulse.y;this.m_impulse.x+=impulseX;this.m_impulse.y+=impulseY;var length=this.m_impulse.Length();if(length>step.dt*this.m_maxForce)
-{this.m_impulse.Multiply(step.dt*this.m_maxForce/length);}
-impulseX=this.m_impulse.x-oldImpulseX;impulseY=this.m_impulse.y-oldImpulseY;body.m_linearVelocity.x+=body.m_invMass*impulseX;body.m_linearVelocity.y+=body.m_invMass*impulseY;body.m_angularVelocity+=body.m_invI*(rX*impulseY-rY*impulseX);},SolvePositionConstraints:function(){return true;},m_localAnchor:new b2Vec2(),m_target:new b2Vec2(),m_impulse:new b2Vec2(),m_ptpMass:new b2Mat22(),m_C:new b2Vec2(),m_maxForce:null,m_beta:null,m_gamma:null});
-var b2MouseJointDef=Class.create();Object.extend(b2MouseJointDef.prototype,b2JointDef.prototype);Object.extend(b2MouseJointDef.prototype,{initialize:function()
-{this.type=b2Joint.e_unknownJoint;this.userData=null;this.body1=null;this.body2=null;this.collideConnected=false;this.target=new b2Vec2();this.type=b2Joint.e_mouseJoint;this.maxForce=0.0;this.frequencyHz=5.0;this.dampingRatio=0.7;this.timeStep=1.0/60.0;},target:new b2Vec2(),maxForce:null,frequencyHz:null,dampingRatio:null,timeStep:null});
-var b2PrismaticJoint=Class.create();Object.extend(b2PrismaticJoint.prototype,b2Joint.prototype);Object.extend(b2PrismaticJoint.prototype,{GetAnchor1:function(){var b1=this.m_body1;var tVec=new b2Vec2();tVec.SetV(this.m_localAnchor1);tVec.MulM(b1.m_R);tVec.Add(b1.m_position);return tVec;},GetAnchor2:function(){var b2=this.m_body2;var tVec=new b2Vec2();tVec.SetV(this.m_localAnchor2);tVec.MulM(b2.m_R);tVec.Add(b2.m_position);return tVec;},GetJointTranslation:function(){var b1=this.m_body1;var b2=this.m_body2;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var p1X=b1.m_position.x+r1X;var p1Y=b1.m_position.y+r1Y;var p2X=b2.m_position.x+r2X;var p2Y=b2.m_position.y+r2Y;var dX=p2X-p1X;var dY=p2Y-p1Y;tMat=b1.m_R;var ax1X=tMat.col1.x*this.m_localXAxis1.x+tMat.col2.x*this.m_localXAxis1.y;var ax1Y=tMat.col1.y*this.m_localXAxis1.x+tMat.col2.y*this.m_localXAxis1.y;var translation=ax1X*dX+ax1Y*dY;return translation;},GetJointSpeed:function(){var b1=this.m_body1;var b2=this.m_body2;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var p1X=b1.m_position.x+r1X;var p1Y=b1.m_position.y+r1Y;var p2X=b2.m_position.x+r2X;var p2Y=b2.m_position.y+r2Y;var dX=p2X-p1X;var dY=p2Y-p1Y;tMat=b1.m_R;var ax1X=tMat.col1.x*this.m_localXAxis1.x+tMat.col2.x*this.m_localXAxis1.y;var ax1Y=tMat.col1.y*this.m_localXAxis1.x+tMat.col2.y*this.m_localXAxis1.y;var v1=b1.m_linearVelocity;var v2=b2.m_linearVelocity;var w1=b1.m_angularVelocity;var w2=b2.m_angularVelocity;var speed=(dX*(-w1*ax1Y)+dY*(w1*ax1X))+(ax1X*(((v2.x+(-w2*r2Y))-v1.x)-(-w1*r1Y))+ax1Y*(((v2.y+(w2*r2X))-v1.y)-(w1*r1X)));return speed;},GetMotorForce:function(invTimeStep){return invTimeStep*this.m_motorImpulse;},SetMotorSpeed:function(speed)
-{this.m_motorSpeed=speed;},SetMotorForce:function(force)
-{this.m_maxMotorForce=force;},GetReactionForce:function(invTimeStep)
-{var tImp=invTimeStep*this.m_limitImpulse;var tMat;tMat=this.m_body1.m_R;var ax1X=tImp*(tMat.col1.x*this.m_localXAxis1.x+tMat.col2.x*this.m_localXAxis1.y);var ax1Y=tImp*(tMat.col1.y*this.m_localXAxis1.x+tMat.col2.y*this.m_localXAxis1.y);var ay1X=tImp*(tMat.col1.x*this.m_localYAxis1.x+tMat.col2.x*this.m_localYAxis1.y);var ay1Y=tImp*(tMat.col1.y*this.m_localYAxis1.x+tMat.col2.y*this.m_localYAxis1.y);return new b2Vec2(ax1X+ay1X,ax1Y+ay1Y);},GetReactionTorque:function(invTimeStep)
-{return invTimeStep*this.m_angularImpulse;},initialize:function(def){this.m_node1=new b2JointNode();this.m_node2=new b2JointNode();this.m_type=def.type;this.m_prev=null;this.m_next=null;this.m_body1=def.body1;this.m_body2=def.body2;this.m_collideConnected=def.collideConnected;this.m_islandFlag=false;this.m_userData=def.userData;this.m_localAnchor1=new b2Vec2();this.m_localAnchor2=new b2Vec2();this.m_localXAxis1=new b2Vec2();this.m_localYAxis1=new b2Vec2();this.m_linearJacobian=new b2Jacobian();this.m_motorJacobian=new b2Jacobian();var tMat;var tX;var tY;tMat=this.m_body1.m_R;tX=(def.anchorPoint.x-this.m_body1.m_position.x);tY=(def.anchorPoint.y-this.m_body1.m_position.y);this.m_localAnchor1.Set((tX*tMat.col1.x+tY*tMat.col1.y),(tX*tMat.col2.x+tY*tMat.col2.y));tMat=this.m_body2.m_R;tX=(def.anchorPoint.x-this.m_body2.m_position.x);tY=(def.anchorPoint.y-this.m_body2.m_position.y);this.m_localAnchor2.Set((tX*tMat.col1.x+tY*tMat.col1.y),(tX*tMat.col2.x+tY*tMat.col2.y));tMat=this.m_body1.m_R;tX=def.axis.x;tY=def.axis.y;this.m_localXAxis1.Set((tX*tMat.col1.x+tY*tMat.col1.y),(tX*tMat.col2.x+tY*tMat.col2.y));this.m_localYAxis1.x=-this.m_localXAxis1.y;this.m_localYAxis1.y=this.m_localXAxis1.x;this.m_initialAngle=this.m_body2.m_rotation-this.m_body1.m_rotation;this.m_linearJacobian.SetZero();this.m_linearMass=0.0;this.m_linearImpulse=0.0;this.m_angularMass=0.0;this.m_angularImpulse=0.0;this.m_motorJacobian.SetZero();this.m_motorMass=0.0;this.m_motorImpulse=0.0;this.m_limitImpulse=0.0;this.m_limitPositionImpulse=0.0;this.m_lowerTranslation=def.lowerTranslation;this.m_upperTranslation=def.upperTranslation;this.m_maxMotorForce=def.motorForce;this.m_motorSpeed=def.motorSpeed;this.m_enableLimit=def.enableLimit;this.m_enableMotor=def.enableMotor;},PrepareVelocitySolver:function(){var b1=this.m_body1;var b2=this.m_body2;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var invMass1=b1.m_invMass;var invMass2=b2.m_invMass;var invI1=b1.m_invI;var invI2=b2.m_invI;tMat=b1.m_R;var ay1X=tMat.col1.x*this.m_localYAxis1.x+tMat.col2.x*this.m_localYAxis1.y;var ay1Y=tMat.col1.y*this.m_localYAxis1.x+tMat.col2.y*this.m_localYAxis1.y;var eX=b2.m_position.x+r2X-b1.m_position.x;var eY=b2.m_position.y+r2Y-b1.m_position.y;this.m_linearJacobian.linear1.x=-ay1X;this.m_linearJacobian.linear1.y=-ay1Y;this.m_linearJacobian.linear2.x=ay1X;this.m_linearJacobian.linear2.y=ay1Y;this.m_linearJacobian.angular1=-(eX*ay1Y-eY*ay1X);this.m_linearJacobian.angular2=r2X*ay1Y-r2Y*ay1X;this.m_linearMass=invMass1+invI1*this.m_linearJacobian.angular1*this.m_linearJacobian.angular1+
-invMass2+invI2*this.m_linearJacobian.angular2*this.m_linearJacobian.angular2;this.m_linearMass=1.0/this.m_linearMass;this.m_angularMass=1.0/(invI1+invI2);if(this.m_enableLimit||this.m_enableMotor)
-{tMat=b1.m_R;var ax1X=tMat.col1.x*this.m_localXAxis1.x+tMat.col2.x*this.m_localXAxis1.y;var ax1Y=tMat.col1.y*this.m_localXAxis1.x+tMat.col2.y*this.m_localXAxis1.y;this.m_motorJacobian.linear1.x=-ax1X;this.m_motorJacobian.linear1.y=-ax1Y;this.m_motorJacobian.linear2.x=ax1X;this.m_motorJacobian.linear2.y=ax1Y;this.m_motorJacobian.angular1=-(eX*ax1Y-eY*ax1X);this.m_motorJacobian.angular2=r2X*ax1Y-r2Y*ax1X;this.m_motorMass=invMass1+invI1*this.m_motorJacobian.angular1*this.m_motorJacobian.angular1+
-invMass2+invI2*this.m_motorJacobian.angular2*this.m_motorJacobian.angular2;this.m_motorMass=1.0/this.m_motorMass;if(this.m_enableLimit)
-{var dX=eX-r1X;var dY=eY-r1Y;var jointTranslation=ax1X*dX+ax1Y*dY;if(b2Math.b2Abs(this.m_upperTranslation-this.m_lowerTranslation)<2.0*b2Settings.b2_linearSlop)
-{this.m_limitState=b2Joint.e_equalLimits;}
-else if(jointTranslation<=this.m_lowerTranslation)
-{if(this.m_limitState!=b2Joint.e_atLowerLimit)
-{this.m_limitImpulse=0.0;}
-this.m_limitState=b2Joint.e_atLowerLimit;}
-else if(jointTranslation>=this.m_upperTranslation)
-{if(this.m_limitState!=b2Joint.e_atUpperLimit)
-{this.m_limitImpulse=0.0;}
-this.m_limitState=b2Joint.e_atUpperLimit;}
-else
-{this.m_limitState=b2Joint.e_inactiveLimit;this.m_limitImpulse=0.0;}}}
-if(this.m_enableMotor==false)
-{this.m_motorImpulse=0.0;}
-if(this.m_enableLimit==false)
-{this.m_limitImpulse=0.0;}
-if(b2World.s_enableWarmStarting)
-{var P1X=this.m_linearImpulse*this.m_linearJacobian.linear1.x+(this.m_motorImpulse+this.m_limitImpulse)*this.m_motorJacobian.linear1.x;var P1Y=this.m_linearImpulse*this.m_linearJacobian.linear1.y+(this.m_motorImpulse+this.m_limitImpulse)*this.m_motorJacobian.linear1.y;var P2X=this.m_linearImpulse*this.m_linearJacobian.linear2.x+(this.m_motorImpulse+this.m_limitImpulse)*this.m_motorJacobian.linear2.x;var P2Y=this.m_linearImpulse*this.m_linearJacobian.linear2.y+(this.m_motorImpulse+this.m_limitImpulse)*this.m_motorJacobian.linear2.y;var L1=this.m_linearImpulse*this.m_linearJacobian.angular1-this.m_angularImpulse+(this.m_motorImpulse+this.m_limitImpulse)*this.m_motorJacobian.angular1;var L2=this.m_linearImpulse*this.m_linearJacobian.angular2+this.m_angularImpulse+(this.m_motorImpulse+this.m_limitImpulse)*this.m_motorJacobian.angular2;b1.m_linearVelocity.x+=invMass1*P1X;b1.m_linearVelocity.y+=invMass1*P1Y;b1.m_angularVelocity+=invI1*L1;b2.m_linearVelocity.x+=invMass2*P2X;b2.m_linearVelocity.y+=invMass2*P2Y;b2.m_angularVelocity+=invI2*L2;}
-else
-{this.m_linearImpulse=0.0;this.m_angularImpulse=0.0;this.m_limitImpulse=0.0;this.m_motorImpulse=0.0;}
-this.m_limitPositionImpulse=0.0;},SolveVelocityConstraints:function(step){var b1=this.m_body1;var b2=this.m_body2;var invMass1=b1.m_invMass;var invMass2=b2.m_invMass;var invI1=b1.m_invI;var invI2=b2.m_invI;var oldLimitImpulse;var linearCdot=this.m_linearJacobian.Compute(b1.m_linearVelocity,b1.m_angularVelocity,b2.m_linearVelocity,b2.m_angularVelocity);var linearImpulse=-this.m_linearMass*linearCdot;this.m_linearImpulse+=linearImpulse;b1.m_linearVelocity.x+=(invMass1*linearImpulse)*this.m_linearJacobian.linear1.x;b1.m_linearVelocity.y+=(invMass1*linearImpulse)*this.m_linearJacobian.linear1.y;b1.m_angularVelocity+=invI1*linearImpulse*this.m_linearJacobian.angular1;b2.m_linearVelocity.x+=(invMass2*linearImpulse)*this.m_linearJacobian.linear2.x;b2.m_linearVelocity.y+=(invMass2*linearImpulse)*this.m_linearJacobian.linear2.y;b2.m_angularVelocity+=invI2*linearImpulse*this.m_linearJacobian.angular2;var angularCdot=b2.m_angularVelocity-b1.m_angularVelocity;var angularImpulse=-this.m_angularMass*angularCdot;this.m_angularImpulse+=angularImpulse;b1.m_angularVelocity-=invI1*angularImpulse;b2.m_angularVelocity+=invI2*angularImpulse;if(this.m_enableMotor&&this.m_limitState!=b2Joint.e_equalLimits)
-{var motorCdot=this.m_motorJacobian.Compute(b1.m_linearVelocity,b1.m_angularVelocity,b2.m_linearVelocity,b2.m_angularVelocity)-this.m_motorSpeed;var motorImpulse=-this.m_motorMass*motorCdot;var oldMotorImpulse=this.m_motorImpulse;this.m_motorImpulse=b2Math.b2Clamp(this.m_motorImpulse+motorImpulse,-step.dt*this.m_maxMotorForce,step.dt*this.m_maxMotorForce);motorImpulse=this.m_motorImpulse-oldMotorImpulse;b1.m_linearVelocity.x+=(invMass1*motorImpulse)*this.m_motorJacobian.linear1.x;b1.m_linearVelocity.y+=(invMass1*motorImpulse)*this.m_motorJacobian.linear1.y;b1.m_angularVelocity+=invI1*motorImpulse*this.m_motorJacobian.angular1;b2.m_linearVelocity.x+=(invMass2*motorImpulse)*this.m_motorJacobian.linear2.x;b2.m_linearVelocity.y+=(invMass2*motorImpulse)*this.m_motorJacobian.linear2.y;b2.m_angularVelocity+=invI2*motorImpulse*this.m_motorJacobian.angular2;}
-if(this.m_enableLimit&&this.m_limitState!=b2Joint.e_inactiveLimit)
-{var limitCdot=this.m_motorJacobian.Compute(b1.m_linearVelocity,b1.m_angularVelocity,b2.m_linearVelocity,b2.m_angularVelocity);var limitImpulse=-this.m_motorMass*limitCdot;if(this.m_limitState==b2Joint.e_equalLimits)
-{this.m_limitImpulse+=limitImpulse;}
-else if(this.m_limitState==b2Joint.e_atLowerLimit)
-{oldLimitImpulse=this.m_limitImpulse;this.m_limitImpulse=b2Math.b2Max(this.m_limitImpulse+limitImpulse,0.0);limitImpulse=this.m_limitImpulse-oldLimitImpulse;}
-else if(this.m_limitState==b2Joint.e_atUpperLimit)
-{oldLimitImpulse=this.m_limitImpulse;this.m_limitImpulse=b2Math.b2Min(this.m_limitImpulse+limitImpulse,0.0);limitImpulse=this.m_limitImpulse-oldLimitImpulse;}
-b1.m_linearVelocity.x+=(invMass1*limitImpulse)*this.m_motorJacobian.linear1.x;b1.m_linearVelocity.y+=(invMass1*limitImpulse)*this.m_motorJacobian.linear1.y;b1.m_angularVelocity+=invI1*limitImpulse*this.m_motorJacobian.angular1;b2.m_linearVelocity.x+=(invMass2*limitImpulse)*this.m_motorJacobian.linear2.x;b2.m_linearVelocity.y+=(invMass2*limitImpulse)*this.m_motorJacobian.linear2.y;b2.m_angularVelocity+=invI2*limitImpulse*this.m_motorJacobian.angular2;}},SolvePositionConstraints:function(){var limitC;var oldLimitImpulse;var b1=this.m_body1;var b2=this.m_body2;var invMass1=b1.m_invMass;var invMass2=b2.m_invMass;var invI1=b1.m_invI;var invI2=b2.m_invI;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var p1X=b1.m_position.x+r1X;var p1Y=b1.m_position.y+r1Y;var p2X=b2.m_position.x+r2X;var p2Y=b2.m_position.y+r2Y;var dX=p2X-p1X;var dY=p2Y-p1Y;tMat=b1.m_R;var ay1X=tMat.col1.x*this.m_localYAxis1.x+tMat.col2.x*this.m_localYAxis1.y;var ay1Y=tMat.col1.y*this.m_localYAxis1.x+tMat.col2.y*this.m_localYAxis1.y;var linearC=ay1X*dX+ay1Y*dY;linearC=b2Math.b2Clamp(linearC,-b2Settings.b2_maxLinearCorrection,b2Settings.b2_maxLinearCorrection);var linearImpulse=-this.m_linearMass*linearC;b1.m_position.x+=(invMass1*linearImpulse)*this.m_linearJacobian.linear1.x;b1.m_position.y+=(invMass1*linearImpulse)*this.m_linearJacobian.linear1.y;b1.m_rotation+=invI1*linearImpulse*this.m_linearJacobian.angular1;b2.m_position.x+=(invMass2*linearImpulse)*this.m_linearJacobian.linear2.x;b2.m_position.y+=(invMass2*linearImpulse)*this.m_linearJacobian.linear2.y;b2.m_rotation+=invI2*linearImpulse*this.m_linearJacobian.angular2;var positionError=b2Math.b2Abs(linearC);var angularC=b2.m_rotation-b1.m_rotation-this.m_initialAngle;angularC=b2Math.b2Clamp(angularC,-b2Settings.b2_maxAngularCorrection,b2Settings.b2_maxAngularCorrection);var angularImpulse=-this.m_angularMass*angularC;b1.m_rotation-=b1.m_invI*angularImpulse;b1.m_R.Set(b1.m_rotation);b2.m_rotation+=b2.m_invI*angularImpulse;b2.m_R.Set(b2.m_rotation);var angularError=b2Math.b2Abs(angularC);if(this.m_enableLimit&&this.m_limitState!=b2Joint.e_inactiveLimit)
-{tMat=b1.m_R;r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;p1X=b1.m_position.x+r1X;p1Y=b1.m_position.y+r1Y;p2X=b2.m_position.x+r2X;p2Y=b2.m_position.y+r2Y;dX=p2X-p1X;dY=p2Y-p1Y;tMat=b1.m_R;var ax1X=tMat.col1.x*this.m_localXAxis1.x+tMat.col2.x*this.m_localXAxis1.y;var ax1Y=tMat.col1.y*this.m_localXAxis1.x+tMat.col2.y*this.m_localXAxis1.y;var translation=(ax1X*dX+ax1Y*dY);var limitImpulse=0.0;if(this.m_limitState==b2Joint.e_equalLimits)
-{limitC=b2Math.b2Clamp(translation,-b2Settings.b2_maxLinearCorrection,b2Settings.b2_maxLinearCorrection);limitImpulse=-this.m_motorMass*limitC;positionError=b2Math.b2Max(positionError,b2Math.b2Abs(angularC));}
-else if(this.m_limitState==b2Joint.e_atLowerLimit)
-{limitC=translation-this.m_lowerTranslation;positionError=b2Math.b2Max(positionError,-limitC);limitC=b2Math.b2Clamp(limitC+b2Settings.b2_linearSlop,-b2Settings.b2_maxLinearCorrection,0.0);limitImpulse=-this.m_motorMass*limitC;oldLimitImpulse=this.m_limitPositionImpulse;this.m_limitPositionImpulse=b2Math.b2Max(this.m_limitPositionImpulse+limitImpulse,0.0);limitImpulse=this.m_limitPositionImpulse-oldLimitImpulse;}
-else if(this.m_limitState==b2Joint.e_atUpperLimit)
-{limitC=translation-this.m_upperTranslation;positionError=b2Math.b2Max(positionError,limitC);limitC=b2Math.b2Clamp(limitC-b2Settings.b2_linearSlop,0.0,b2Settings.b2_maxLinearCorrection);limitImpulse=-this.m_motorMass*limitC;oldLimitImpulse=this.m_limitPositionImpulse;this.m_limitPositionImpulse=b2Math.b2Min(this.m_limitPositionImpulse+limitImpulse,0.0);limitImpulse=this.m_limitPositionImpulse-oldLimitImpulse;}
-b1.m_position.x+=(invMass1*limitImpulse)*this.m_motorJacobian.linear1.x;b1.m_position.y+=(invMass1*limitImpulse)*this.m_motorJacobian.linear1.y;b1.m_rotation+=invI1*limitImpulse*this.m_motorJacobian.angular1;b1.m_R.Set(b1.m_rotation);b2.m_position.x+=(invMass2*limitImpulse)*this.m_motorJacobian.linear2.x;b2.m_position.y+=(invMass2*limitImpulse)*this.m_motorJacobian.linear2.y;b2.m_rotation+=invI2*limitImpulse*this.m_motorJacobian.angular2;b2.m_R.Set(b2.m_rotation);}
-return positionError<=b2Settings.b2_linearSlop&&angularError<=b2Settings.b2_angularSlop;},m_localAnchor1:new b2Vec2(),m_localAnchor2:new b2Vec2(),m_localXAxis1:new b2Vec2(),m_localYAxis1:new b2Vec2(),m_initialAngle:null,m_linearJacobian:new b2Jacobian(),m_linearMass:null,m_linearImpulse:null,m_angularMass:null,m_angularImpulse:null,m_motorJacobian:new b2Jacobian(),m_motorMass:null,m_motorImpulse:null,m_limitImpulse:null,m_limitPositionImpulse:null,m_lowerTranslation:null,m_upperTranslation:null,m_maxMotorForce:null,m_motorSpeed:null,m_enableLimit:null,m_enableMotor:null,m_limitState:0});
-var b2PrismaticJointDef=Class.create();Object.extend(b2PrismaticJointDef.prototype,b2JointDef.prototype);Object.extend(b2PrismaticJointDef.prototype,{initialize:function()
-{this.type=b2Joint.e_unknownJoint;this.userData=null;this.body1=null;this.body2=null;this.collideConnected=false;this.type=b2Joint.e_prismaticJoint;this.anchorPoint=new b2Vec2(0.0,0.0);this.axis=new b2Vec2(0.0,0.0);this.lowerTranslation=0.0;this.upperTranslation=0.0;this.motorForce=0.0;this.motorSpeed=0.0;this.enableLimit=false;this.enableMotor=false;},anchorPoint:null,axis:null,lowerTranslation:null,upperTranslation:null,motorForce:null,motorSpeed:null,enableLimit:null,enableMotor:null});
-var b2PulleyJoint=Class.create();Object.extend(b2PulleyJoint.prototype,b2Joint.prototype);Object.extend(b2PulleyJoint.prototype,{GetAnchor1:function(){var tMat=this.m_body1.m_R;return new b2Vec2(this.m_body1.m_position.x+(tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y),this.m_body1.m_position.y+(tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y));},GetAnchor2:function(){var tMat=this.m_body2.m_R;return new b2Vec2(this.m_body2.m_position.x+(tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y),this.m_body2.m_position.y+(tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y));},GetGroundPoint1:function(){return new b2Vec2(this.m_ground.m_position.x+this.m_groundAnchor1.x,this.m_ground.m_position.y+this.m_groundAnchor1.y);},GetGroundPoint2:function(){return new b2Vec2(this.m_ground.m_position.x+this.m_groundAnchor2.x,this.m_ground.m_position.y+this.m_groundAnchor2.y);},GetReactionForce:function(invTimeStep){return new b2Vec2();},GetReactionTorque:function(invTimeStep){return 0.0;},GetLength1:function(){var tMat;tMat=this.m_body1.m_R;var pX=this.m_body1.m_position.x+(tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y);var pY=this.m_body1.m_position.y+(tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y);var dX=pX-(this.m_ground.m_position.x+this.m_groundAnchor1.x);var dY=pY-(this.m_ground.m_position.y+this.m_groundAnchor1.y);return Math.sqrt(dX*dX+dY*dY);},GetLength2:function(){var tMat;tMat=this.m_body2.m_R;var pX=this.m_body2.m_position.x+(tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y);var pY=this.m_body2.m_position.y+(tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y);var dX=pX-(this.m_ground.m_position.x+this.m_groundAnchor2.x);var dY=pY-(this.m_ground.m_position.y+this.m_groundAnchor2.y);return Math.sqrt(dX*dX+dY*dY);},GetRatio:function(){return this.m_ratio;},initialize:function(def){this.m_node1=new b2JointNode();this.m_node2=new b2JointNode();this.m_type=def.type;this.m_prev=null;this.m_next=null;this.m_body1=def.body1;this.m_body2=def.body2;this.m_collideConnected=def.collideConnected;this.m_islandFlag=false;this.m_userData=def.userData;this.m_groundAnchor1=new b2Vec2();this.m_groundAnchor2=new b2Vec2();this.m_localAnchor1=new b2Vec2();this.m_localAnchor2=new b2Vec2();this.m_u1=new b2Vec2();this.m_u2=new b2Vec2();var tMat;var tX;var tY;this.m_ground=this.m_body1.m_world.m_groundBody;this.m_groundAnchor1.x=def.groundPoint1.x-this.m_ground.m_position.x;this.m_groundAnchor1.y=def.groundPoint1.y-this.m_ground.m_position.y;this.m_groundAnchor2.x=def.groundPoint2.x-this.m_ground.m_position.x;this.m_groundAnchor2.y=def.groundPoint2.y-this.m_ground.m_position.y;tMat=this.m_body1.m_R;tX=def.anchorPoint1.x-this.m_body1.m_position.x;tY=def.anchorPoint1.y-this.m_body1.m_position.y;this.m_localAnchor1.x=tX*tMat.col1.x+tY*tMat.col1.y;this.m_localAnchor1.y=tX*tMat.col2.x+tY*tMat.col2.y;tMat=this.m_body2.m_R;tX=def.anchorPoint2.x-this.m_body2.m_position.x;tY=def.anchorPoint2.y-this.m_body2.m_position.y;this.m_localAnchor2.x=tX*tMat.col1.x+tY*tMat.col1.y;this.m_localAnchor2.y=tX*tMat.col2.x+tY*tMat.col2.y;this.m_ratio=def.ratio;tX=def.groundPoint1.x-def.anchorPoint1.x;tY=def.groundPoint1.y-def.anchorPoint1.y;var d1Len=Math.sqrt(tX*tX+tY*tY);tX=def.groundPoint2.x-def.anchorPoint2.x;tY=def.groundPoint2.y-def.anchorPoint2.y;var d2Len=Math.sqrt(tX*tX+tY*tY);var length1=b2Math.b2Max(0.5*b2PulleyJoint.b2_minPulleyLength,d1Len);var length2=b2Math.b2Max(0.5*b2PulleyJoint.b2_minPulleyLength,d2Len);this.m_constant=length1+this.m_ratio*length2;this.m_maxLength1=b2Math.b2Clamp(def.maxLength1,length1,this.m_constant-this.m_ratio*b2PulleyJoint.b2_minPulleyLength);this.m_maxLength2=b2Math.b2Clamp(def.maxLength2,length2,(this.m_constant-b2PulleyJoint.b2_minPulleyLength)/this.m_ratio);this.m_pulleyImpulse=0.0;this.m_limitImpulse1=0.0;this.m_limitImpulse2=0.0;},PrepareVelocitySolver:function(){var b1=this.m_body1;var b2=this.m_body2;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var p1X=b1.m_position.x+r1X;var p1Y=b1.m_position.y+r1Y;var p2X=b2.m_position.x+r2X;var p2Y=b2.m_position.y+r2Y;var s1X=this.m_ground.m_position.x+this.m_groundAnchor1.x;var s1Y=this.m_ground.m_position.y+this.m_groundAnchor1.y;var s2X=this.m_ground.m_position.x+this.m_groundAnchor2.x;var s2Y=this.m_ground.m_position.y+this.m_groundAnchor2.y;this.m_u1.Set(p1X-s1X,p1Y-s1Y);this.m_u2.Set(p2X-s2X,p2Y-s2Y);var length1=this.m_u1.Length();var length2=this.m_u2.Length();if(length1>b2Settings.b2_linearSlop)
-{this.m_u1.Multiply(1.0/length1);}
-else
-{this.m_u1.SetZero();}
-if(length2>b2Settings.b2_linearSlop)
-{this.m_u2.Multiply(1.0/length2);}
-else
-{this.m_u2.SetZero();}
-if(length1<this.m_maxLength1)
-{this.m_limitState1=b2Joint.e_inactiveLimit;this.m_limitImpulse1=0.0;}
-else
-{this.m_limitState1=b2Joint.e_atUpperLimit;this.m_limitPositionImpulse1=0.0;}
-if(length2<this.m_maxLength2)
-{this.m_limitState2=b2Joint.e_inactiveLimit;this.m_limitImpulse2=0.0;}
-else
-{this.m_limitState2=b2Joint.e_atUpperLimit;this.m_limitPositionImpulse2=0.0;}
-var cr1u1=r1X*this.m_u1.y-r1Y*this.m_u1.x;var cr2u2=r2X*this.m_u2.y-r2Y*this.m_u2.x;this.m_limitMass1=b1.m_invMass+b1.m_invI*cr1u1*cr1u1;this.m_limitMass2=b2.m_invMass+b2.m_invI*cr2u2*cr2u2;this.m_pulleyMass=this.m_limitMass1+this.m_ratio*this.m_ratio*this.m_limitMass2;this.m_limitMass1=1.0/this.m_limitMass1;this.m_limitMass2=1.0/this.m_limitMass2;this.m_pulleyMass=1.0/this.m_pulleyMass;var P1X=(-this.m_pulleyImpulse-this.m_limitImpulse1)*this.m_u1.x;var P1Y=(-this.m_pulleyImpulse-this.m_limitImpulse1)*this.m_u1.y;var P2X=(-this.m_ratio*this.m_pulleyImpulse-this.m_limitImpulse2)*this.m_u2.x;var P2Y=(-this.m_ratio*this.m_pulleyImpulse-this.m_limitImpulse2)*this.m_u2.y;b1.m_linearVelocity.x+=b1.m_invMass*P1X;b1.m_linearVelocity.y+=b1.m_invMass*P1Y;b1.m_angularVelocity+=b1.m_invI*(r1X*P1Y-r1Y*P1X);b2.m_linearVelocity.x+=b2.m_invMass*P2X;b2.m_linearVelocity.y+=b2.m_invMass*P2Y;b2.m_angularVelocity+=b2.m_invI*(r2X*P2Y-r2Y*P2X);},SolveVelocityConstraints:function(step){var b1=this.m_body1;var b2=this.m_body2;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var v1X;var v1Y;var v2X;var v2Y;var P1X;var P1Y;var P2X;var P2Y;var Cdot;var impulse;var oldLimitImpulse;v1X=b1.m_linearVelocity.x+(-b1.m_angularVelocity*r1Y);v1Y=b1.m_linearVelocity.y+(b1.m_angularVelocity*r1X);v2X=b2.m_linearVelocity.x+(-b2.m_angularVelocity*r2Y);v2Y=b2.m_linearVelocity.y+(b2.m_angularVelocity*r2X);Cdot=-(this.m_u1.x*v1X+this.m_u1.y*v1Y)-this.m_ratio*(this.m_u2.x*v2X+this.m_u2.y*v2Y);impulse=-this.m_pulleyMass*Cdot;this.m_pulleyImpulse+=impulse;P1X=-impulse*this.m_u1.x;P1Y=-impulse*this.m_u1.y;P2X=-this.m_ratio*impulse*this.m_u2.x;P2Y=-this.m_ratio*impulse*this.m_u2.y;b1.m_linearVelocity.x+=b1.m_invMass*P1X;b1.m_linearVelocity.y+=b1.m_invMass*P1Y;b1.m_angularVelocity+=b1.m_invI*(r1X*P1Y-r1Y*P1X);b2.m_linearVelocity.x+=b2.m_invMass*P2X;b2.m_linearVelocity.y+=b2.m_invMass*P2Y;b2.m_angularVelocity+=b2.m_invI*(r2X*P2Y-r2Y*P2X);if(this.m_limitState1==b2Joint.e_atUpperLimit)
-{v1X=b1.m_linearVelocity.x+(-b1.m_angularVelocity*r1Y);v1Y=b1.m_linearVelocity.y+(b1.m_angularVelocity*r1X);Cdot=-(this.m_u1.x*v1X+this.m_u1.y*v1Y);impulse=-this.m_limitMass1*Cdot;oldLimitImpulse=this.m_limitImpulse1;this.m_limitImpulse1=b2Math.b2Max(0.0,this.m_limitImpulse1+impulse);impulse=this.m_limitImpulse1-oldLimitImpulse;P1X=-impulse*this.m_u1.x;P1Y=-impulse*this.m_u1.y;b1.m_linearVelocity.x+=b1.m_invMass*P1X;b1.m_linearVelocity.y+=b1.m_invMass*P1Y;b1.m_angularVelocity+=b1.m_invI*(r1X*P1Y-r1Y*P1X);}
-if(this.m_limitState2==b2Joint.e_atUpperLimit)
-{v2X=b2.m_linearVelocity.x+(-b2.m_angularVelocity*r2Y);v2Y=b2.m_linearVelocity.y+(b2.m_angularVelocity*r2X);Cdot=-(this.m_u2.x*v2X+this.m_u2.y*v2Y);impulse=-this.m_limitMass2*Cdot;oldLimitImpulse=this.m_limitImpulse2;this.m_limitImpulse2=b2Math.b2Max(0.0,this.m_limitImpulse2+impulse);impulse=this.m_limitImpulse2-oldLimitImpulse;P2X=-impulse*this.m_u2.x;P2Y=-impulse*this.m_u2.y;b2.m_linearVelocity.x+=b2.m_invMass*P2X;b2.m_linearVelocity.y+=b2.m_invMass*P2Y;b2.m_angularVelocity+=b2.m_invI*(r2X*P2Y-r2Y*P2X);}},SolvePositionConstraints:function(){var b1=this.m_body1;var b2=this.m_body2;var tMat;var s1X=this.m_ground.m_position.x+this.m_groundAnchor1.x;var s1Y=this.m_ground.m_position.y+this.m_groundAnchor1.y;var s2X=this.m_ground.m_position.x+this.m_groundAnchor2.x;var s2Y=this.m_ground.m_position.y+this.m_groundAnchor2.y;var r1X;var r1Y;var r2X;var r2Y;var p1X;var p1Y;var p2X;var p2Y;var length1;var length2;var C;var impulse;var oldLimitPositionImpulse;var linearError=0.0;{tMat=b1.m_R;r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;p1X=b1.m_position.x+r1X;p1Y=b1.m_position.y+r1Y;p2X=b2.m_position.x+r2X;p2Y=b2.m_position.y+r2Y;this.m_u1.Set(p1X-s1X,p1Y-s1Y);this.m_u2.Set(p2X-s2X,p2Y-s2Y);length1=this.m_u1.Length();length2=this.m_u2.Length();if(length1>b2Settings.b2_linearSlop)
-{this.m_u1.Multiply(1.0/length1);}
-else
-{this.m_u1.SetZero();}
-if(length2>b2Settings.b2_linearSlop)
-{this.m_u2.Multiply(1.0/length2);}
-else
-{this.m_u2.SetZero();}
-C=this.m_constant-length1-this.m_ratio*length2;linearError=b2Math.b2Max(linearError,Math.abs(C));C=b2Math.b2Clamp(C,-b2Settings.b2_maxLinearCorrection,b2Settings.b2_maxLinearCorrection);impulse=-this.m_pulleyMass*C;p1X=-impulse*this.m_u1.x;p1Y=-impulse*this.m_u1.y;p2X=-this.m_ratio*impulse*this.m_u2.x;p2Y=-this.m_ratio*impulse*this.m_u2.y;b1.m_position.x+=b1.m_invMass*p1X;b1.m_position.y+=b1.m_invMass*p1Y;b1.m_rotation+=b1.m_invI*(r1X*p1Y-r1Y*p1X);b2.m_position.x+=b2.m_invMass*p2X;b2.m_position.y+=b2.m_invMass*p2Y;b2.m_rotation+=b2.m_invI*(r2X*p2Y-r2Y*p2X);b1.m_R.Set(b1.m_rotation);b2.m_R.Set(b2.m_rotation);}
-if(this.m_limitState1==b2Joint.e_atUpperLimit)
-{tMat=b1.m_R;r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;p1X=b1.m_position.x+r1X;p1Y=b1.m_position.y+r1Y;this.m_u1.Set(p1X-s1X,p1Y-s1Y);length1=this.m_u1.Length();if(length1>b2Settings.b2_linearSlop)
-{this.m_u1.x*=1.0/length1;this.m_u1.y*=1.0/length1;}
-else
-{this.m_u1.SetZero();}
-C=this.m_maxLength1-length1;linearError=b2Math.b2Max(linearError,-C);C=b2Math.b2Clamp(C+b2Settings.b2_linearSlop,-b2Settings.b2_maxLinearCorrection,0.0);impulse=-this.m_limitMass1*C;oldLimitPositionImpulse=this.m_limitPositionImpulse1;this.m_limitPositionImpulse1=b2Math.b2Max(0.0,this.m_limitPositionImpulse1+impulse);impulse=this.m_limitPositionImpulse1-oldLimitPositionImpulse;p1X=-impulse*this.m_u1.x;p1Y=-impulse*this.m_u1.y;b1.m_position.x+=b1.m_invMass*p1X;b1.m_position.y+=b1.m_invMass*p1Y;b1.m_rotation+=b1.m_invI*(r1X*p1Y-r1Y*p1X);b1.m_R.Set(b1.m_rotation);}
-if(this.m_limitState2==b2Joint.e_atUpperLimit)
-{tMat=b2.m_R;r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;p2X=b2.m_position.x+r2X;p2Y=b2.m_position.y+r2Y;this.m_u2.Set(p2X-s2X,p2Y-s2Y);length2=this.m_u2.Length();if(length2>b2Settings.b2_linearSlop)
-{this.m_u2.x*=1.0/length2;this.m_u2.y*=1.0/length2;}
-else
-{this.m_u2.SetZero();}
-C=this.m_maxLength2-length2;linearError=b2Math.b2Max(linearError,-C);C=b2Math.b2Clamp(C+b2Settings.b2_linearSlop,-b2Settings.b2_maxLinearCorrection,0.0);impulse=-this.m_limitMass2*C;oldLimitPositionImpulse=this.m_limitPositionImpulse2;this.m_limitPositionImpulse2=b2Math.b2Max(0.0,this.m_limitPositionImpulse2+impulse);impulse=this.m_limitPositionImpulse2-oldLimitPositionImpulse;p2X=-impulse*this.m_u2.x;p2Y=-impulse*this.m_u2.y;b2.m_position.x+=b2.m_invMass*p2X;b2.m_position.y+=b2.m_invMass*p2Y;b2.m_rotation+=b2.m_invI*(r2X*p2Y-r2Y*p2X);b2.m_R.Set(b2.m_rotation);}
-return linearError<b2Settings.b2_linearSlop;},m_ground:null,m_groundAnchor1:new b2Vec2(),m_groundAnchor2:new b2Vec2(),m_localAnchor1:new b2Vec2(),m_localAnchor2:new b2Vec2(),m_u1:new b2Vec2(),m_u2:new b2Vec2(),m_constant:null,m_ratio:null,m_maxLength1:null,m_maxLength2:null,m_pulleyMass:null,m_limitMass1:null,m_limitMass2:null,m_pulleyImpulse:null,m_limitImpulse1:null,m_limitImpulse2:null,m_limitPositionImpulse1:null,m_limitPositionImpulse2:null,m_limitState1:0,m_limitState2:0});b2PulleyJoint.b2_minPulleyLength=b2Settings.b2_lengthUnitsPerMeter;
-var b2PulleyJointDef=Class.create();Object.extend(b2PulleyJointDef.prototype,b2JointDef.prototype);Object.extend(b2PulleyJointDef.prototype,{initialize:function()
-{this.type=b2Joint.e_unknownJoint;this.userData=null;this.body1=null;this.body2=null;this.collideConnected=false;this.groundPoint1=new b2Vec2();this.groundPoint2=new b2Vec2();this.anchorPoint1=new b2Vec2();this.anchorPoint2=new b2Vec2();this.type=b2Joint.e_pulleyJoint;this.groundPoint1.Set(-1.0,1.0);this.groundPoint2.Set(1.0,1.0);this.anchorPoint1.Set(-1.0,0.0);this.anchorPoint2.Set(1.0,0.0);this.maxLength1=0.5*b2PulleyJoint.b2_minPulleyLength;this.maxLength2=0.5*b2PulleyJoint.b2_minPulleyLength;this.ratio=1.0;this.collideConnected=true;},groundPoint1:new b2Vec2(),groundPoint2:new b2Vec2(),anchorPoint1:new b2Vec2(),anchorPoint2:new b2Vec2(),maxLength1:null,maxLength2:null,ratio:null});
-var b2RevoluteJoint=Class.create();Object.extend(b2RevoluteJoint.prototype,b2Joint.prototype);Object.extend(b2RevoluteJoint.prototype,{GetAnchor1:function(){var tMat=this.m_body1.m_R;return new b2Vec2(this.m_body1.m_position.x+(tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y),this.m_body1.m_position.y+(tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y));},GetAnchor2:function(){var tMat=this.m_body2.m_R;return new b2Vec2(this.m_body2.m_position.x+(tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y),this.m_body2.m_position.y+(tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y));},GetJointAngle:function(){return this.m_body2.m_rotation-this.m_body1.m_rotation;},GetJointSpeed:function(){return this.m_body2.m_angularVelocity-this.m_body1.m_angularVelocity;},GetMotorTorque:function(invTimeStep){return invTimeStep*this.m_motorImpulse;},SetMotorSpeed:function(speed)
-{this.m_motorSpeed=speed;},SetMotorTorque:function(torque)
-{this.m_maxMotorTorque=torque;},GetReactionForce:function(invTimeStep)
-{var tVec=this.m_ptpImpulse.Copy();tVec.Multiply(invTimeStep);return tVec;},GetReactionTorque:function(invTimeStep)
-{return invTimeStep*this.m_limitImpulse;},initialize:function(def){this.m_node1=new b2JointNode();this.m_node2=new b2JointNode();this.m_type=def.type;this.m_prev=null;this.m_next=null;this.m_body1=def.body1;this.m_body2=def.body2;this.m_collideConnected=def.collideConnected;this.m_islandFlag=false;this.m_userData=def.userData;this.K=new b2Mat22();this.K1=new b2Mat22();this.K2=new b2Mat22();this.K3=new b2Mat22();this.m_localAnchor1=new b2Vec2();this.m_localAnchor2=new b2Vec2();this.m_ptpImpulse=new b2Vec2();this.m_ptpMass=new b2Mat22();var tMat;var tX;var tY;tMat=this.m_body1.m_R;tX=def.anchorPoint.x-this.m_body1.m_position.x;tY=def.anchorPoint.y-this.m_body1.m_position.y;this.m_localAnchor1.x=tX*tMat.col1.x+tY*tMat.col1.y;this.m_localAnchor1.y=tX*tMat.col2.x+tY*tMat.col2.y;tMat=this.m_body2.m_R;tX=def.anchorPoint.x-this.m_body2.m_position.x;tY=def.anchorPoint.y-this.m_body2.m_position.y;this.m_localAnchor2.x=tX*tMat.col1.x+tY*tMat.col1.y;this.m_localAnchor2.y=tX*tMat.col2.x+tY*tMat.col2.y;this.m_intialAngle=this.m_body2.m_rotation-this.m_body1.m_rotation;this.m_ptpImpulse.Set(0.0,0.0);this.m_motorImpulse=0.0;this.m_limitImpulse=0.0;this.m_limitPositionImpulse=0.0;this.m_lowerAngle=def.lowerAngle;this.m_upperAngle=def.upperAngle;this.m_maxMotorTorque=def.motorTorque;this.m_motorSpeed=def.motorSpeed;this.m_enableLimit=def.enableLimit;this.m_enableMotor=def.enableMotor;},K:new b2Mat22(),K1:new b2Mat22(),K2:new b2Mat22(),K3:new b2Mat22(),PrepareVelocitySolver:function(){var b1=this.m_body1;var b2=this.m_body2;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var invMass1=b1.m_invMass;var invMass2=b2.m_invMass;var invI1=b1.m_invI;var invI2=b2.m_invI;this.K1.col1.x=invMass1+invMass2;this.K1.col2.x=0.0;this.K1.col1.y=0.0;this.K1.col2.y=invMass1+invMass2;this.K2.col1.x=invI1*r1Y*r1Y;this.K2.col2.x=-invI1*r1X*r1Y;this.K2.col1.y=-invI1*r1X*r1Y;this.K2.col2.y=invI1*r1X*r1X;this.K3.col1.x=invI2*r2Y*r2Y;this.K3.col2.x=-invI2*r2X*r2Y;this.K3.col1.y=-invI2*r2X*r2Y;this.K3.col2.y=invI2*r2X*r2X;this.K.SetM(this.K1);this.K.AddM(this.K2);this.K.AddM(this.K3);this.K.Invert(this.m_ptpMass);this.m_motorMass=1.0/(invI1+invI2);if(this.m_enableMotor==false)
-{this.m_motorImpulse=0.0;}
-if(this.m_enableLimit)
-{var jointAngle=b2.m_rotation-b1.m_rotation-this.m_intialAngle;if(b2Math.b2Abs(this.m_upperAngle-this.m_lowerAngle)<2.0*b2Settings.b2_angularSlop)
-{this.m_limitState=b2Joint.e_equalLimits;}
-else if(jointAngle<=this.m_lowerAngle)
-{if(this.m_limitState!=b2Joint.e_atLowerLimit)
-{this.m_limitImpulse=0.0;}
-this.m_limitState=b2Joint.e_atLowerLimit;}
-else if(jointAngle>=this.m_upperAngle)
-{if(this.m_limitState!=b2Joint.e_atUpperLimit)
-{this.m_limitImpulse=0.0;}
-this.m_limitState=b2Joint.e_atUpperLimit;}
-else
-{this.m_limitState=b2Joint.e_inactiveLimit;this.m_limitImpulse=0.0;}}
-else
-{this.m_limitImpulse=0.0;}
-if(b2World.s_enableWarmStarting)
-{b1.m_linearVelocity.x-=invMass1*this.m_ptpImpulse.x;b1.m_linearVelocity.y-=invMass1*this.m_ptpImpulse.y;b1.m_angularVelocity-=invI1*((r1X*this.m_ptpImpulse.y-r1Y*this.m_ptpImpulse.x)+this.m_motorImpulse+this.m_limitImpulse);b2.m_linearVelocity.x+=invMass2*this.m_ptpImpulse.x;b2.m_linearVelocity.y+=invMass2*this.m_ptpImpulse.y;b2.m_angularVelocity+=invI2*((r2X*this.m_ptpImpulse.y-r2Y*this.m_ptpImpulse.x)+this.m_motorImpulse+this.m_limitImpulse);}
-else{this.m_ptpImpulse.SetZero();this.m_motorImpulse=0.0;this.m_limitImpulse=0.0;}
-this.m_limitPositionImpulse=0.0;},SolveVelocityConstraints:function(step){var b1=this.m_body1;var b2=this.m_body2;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var oldLimitImpulse;var ptpCdotX=b2.m_linearVelocity.x+(-b2.m_angularVelocity*r2Y)-b1.m_linearVelocity.x-(-b1.m_angularVelocity*r1Y);var ptpCdotY=b2.m_linearVelocity.y+(b2.m_angularVelocity*r2X)-b1.m_linearVelocity.y-(b1.m_angularVelocity*r1X);var ptpImpulseX=-(this.m_ptpMass.col1.x*ptpCdotX+this.m_ptpMass.col2.x*ptpCdotY);var ptpImpulseY=-(this.m_ptpMass.col1.y*ptpCdotX+this.m_ptpMass.col2.y*ptpCdotY);this.m_ptpImpulse.x+=ptpImpulseX;this.m_ptpImpulse.y+=ptpImpulseY;b1.m_linearVelocity.x-=b1.m_invMass*ptpImpulseX;b1.m_linearVelocity.y-=b1.m_invMass*ptpImpulseY;b1.m_angularVelocity-=b1.m_invI*(r1X*ptpImpulseY-r1Y*ptpImpulseX);b2.m_linearVelocity.x+=b2.m_invMass*ptpImpulseX;b2.m_linearVelocity.y+=b2.m_invMass*ptpImpulseY;b2.m_angularVelocity+=b2.m_invI*(r2X*ptpImpulseY-r2Y*ptpImpulseX);if(this.m_enableMotor&&this.m_limitState!=b2Joint.e_equalLimits)
-{var motorCdot=b2.m_angularVelocity-b1.m_angularVelocity-this.m_motorSpeed;var motorImpulse=-this.m_motorMass*motorCdot;var oldMotorImpulse=this.m_motorImpulse;this.m_motorImpulse=b2Math.b2Clamp(this.m_motorImpulse+motorImpulse,-step.dt*this.m_maxMotorTorque,step.dt*this.m_maxMotorTorque);motorImpulse=this.m_motorImpulse-oldMotorImpulse;b1.m_angularVelocity-=b1.m_invI*motorImpulse;b2.m_angularVelocity+=b2.m_invI*motorImpulse;}
-if(this.m_enableLimit&&this.m_limitState!=b2Joint.e_inactiveLimit)
-{var limitCdot=b2.m_angularVelocity-b1.m_angularVelocity;var limitImpulse=-this.m_motorMass*limitCdot;if(this.m_limitState==b2Joint.e_equalLimits)
-{this.m_limitImpulse+=limitImpulse;}
-else if(this.m_limitState==b2Joint.e_atLowerLimit)
-{oldLimitImpulse=this.m_limitImpulse;this.m_limitImpulse=b2Math.b2Max(this.m_limitImpulse+limitImpulse,0.0);limitImpulse=this.m_limitImpulse-oldLimitImpulse;}
-else if(this.m_limitState==b2Joint.e_atUpperLimit)
-{oldLimitImpulse=this.m_limitImpulse;this.m_limitImpulse=b2Math.b2Min(this.m_limitImpulse+limitImpulse,0.0);limitImpulse=this.m_limitImpulse-oldLimitImpulse;}
-b1.m_angularVelocity-=b1.m_invI*limitImpulse;b2.m_angularVelocity+=b2.m_invI*limitImpulse;}},SolvePositionConstraints:function(){var oldLimitImpulse;var limitC;var b1=this.m_body1;var b2=this.m_body2;var positionError=0.0;var tMat;tMat=b1.m_R;var r1X=tMat.col1.x*this.m_localAnchor1.x+tMat.col2.x*this.m_localAnchor1.y;var r1Y=tMat.col1.y*this.m_localAnchor1.x+tMat.col2.y*this.m_localAnchor1.y;tMat=b2.m_R;var r2X=tMat.col1.x*this.m_localAnchor2.x+tMat.col2.x*this.m_localAnchor2.y;var r2Y=tMat.col1.y*this.m_localAnchor2.x+tMat.col2.y*this.m_localAnchor2.y;var p1X=b1.m_position.x+r1X;var p1Y=b1.m_position.y+r1Y;var p2X=b2.m_position.x+r2X;var p2Y=b2.m_position.y+r2Y;var ptpCX=p2X-p1X;var ptpCY=p2Y-p1Y;positionError=Math.sqrt(ptpCX*ptpCX+ptpCY*ptpCY);var invMass1=b1.m_invMass;var invMass2=b2.m_invMass;var invI1=b1.m_invI;var invI2=b2.m_invI;this.K1.col1.x=invMass1+invMass2;this.K1.col2.x=0.0;this.K1.col1.y=0.0;this.K1.col2.y=invMass1+invMass2;this.K2.col1.x=invI1*r1Y*r1Y;this.K2.col2.x=-invI1*r1X*r1Y;this.K2.col1.y=-invI1*r1X*r1Y;this.K2.col2.y=invI1*r1X*r1X;this.K3.col1.x=invI2*r2Y*r2Y;this.K3.col2.x=-invI2*r2X*r2Y;this.K3.col1.y=-invI2*r2X*r2Y;this.K3.col2.y=invI2*r2X*r2X;this.K.SetM(this.K1);this.K.AddM(this.K2);this.K.AddM(this.K3);this.K.Solve(b2RevoluteJoint.tImpulse,-ptpCX,-ptpCY);var impulseX=b2RevoluteJoint.tImpulse.x;var impulseY=b2RevoluteJoint.tImpulse.y;b1.m_position.x-=b1.m_invMass*impulseX;b1.m_position.y-=b1.m_invMass*impulseY;b1.m_rotation-=b1.m_invI*(r1X*impulseY-r1Y*impulseX);b1.m_R.Set(b1.m_rotation);b2.m_position.x+=b2.m_invMass*impulseX;b2.m_position.y+=b2.m_invMass*impulseY;b2.m_rotation+=b2.m_invI*(r2X*impulseY-r2Y*impulseX);b2.m_R.Set(b2.m_rotation);var angularError=0.0;if(this.m_enableLimit&&this.m_limitState!=b2Joint.e_inactiveLimit)
-{var angle=b2.m_rotation-b1.m_rotation-this.m_intialAngle;var limitImpulse=0.0;if(this.m_limitState==b2Joint.e_equalLimits)
-{limitC=b2Math.b2Clamp(angle,-b2Settings.b2_maxAngularCorrection,b2Settings.b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*limitC;angularError=b2Math.b2Abs(limitC);}
-else if(this.m_limitState==b2Joint.e_atLowerLimit)
-{limitC=angle-this.m_lowerAngle;angularError=b2Math.b2Max(0.0,-limitC);limitC=b2Math.b2Clamp(limitC+b2Settings.b2_angularSlop,-b2Settings.b2_maxAngularCorrection,0.0);limitImpulse=-this.m_motorMass*limitC;oldLimitImpulse=this.m_limitPositionImpulse;this.m_limitPositionImpulse=b2Math.b2Max(this.m_limitPositionImpulse+limitImpulse,0.0);limitImpulse=this.m_limitPositionImpulse-oldLimitImpulse;}
-else if(this.m_limitState==b2Joint.e_atUpperLimit)
-{limitC=angle-this.m_upperAngle;angularError=b2Math.b2Max(0.0,limitC);limitC=b2Math.b2Clamp(limitC-b2Settings.b2_angularSlop,0.0,b2Settings.b2_maxAngularCorrection);limitImpulse=-this.m_motorMass*limitC;oldLimitImpulse=this.m_limitPositionImpulse;this.m_limitPositionImpulse=b2Math.b2Min(this.m_limitPositionImpulse+limitImpulse,0.0);limitImpulse=this.m_limitPositionImpulse-oldLimitImpulse;}
-b1.m_rotation-=b1.m_invI*limitImpulse;b1.m_R.Set(b1.m_rotation);b2.m_rotation+=b2.m_invI*limitImpulse;b2.m_R.Set(b2.m_rotation);}
-return positionError<=b2Settings.b2_linearSlop&&angularError<=b2Settings.b2_angularSlop;},m_localAnchor1:new b2Vec2(),m_localAnchor2:new b2Vec2(),m_ptpImpulse:new b2Vec2(),m_motorImpulse:null,m_limitImpulse:null,m_limitPositionImpulse:null,m_ptpMass:new b2Mat22(),m_motorMass:null,m_intialAngle:null,m_lowerAngle:null,m_upperAngle:null,m_maxMotorTorque:null,m_motorSpeed:null,m_enableLimit:null,m_enableMotor:null,m_limitState:0});b2RevoluteJoint.tImpulse=new b2Vec2();
-var b2RevoluteJointDef=Class.create();Object.extend(b2RevoluteJointDef.prototype,b2JointDef.prototype);Object.extend(b2RevoluteJointDef.prototype,{initialize:function()
-{this.type=b2Joint.e_unknownJoint;this.userData=null;this.body1=null;this.body2=null;this.collideConnected=false;this.type=b2Joint.e_revoluteJoint;this.anchorPoint=new b2Vec2(0.0,0.0);this.lowerAngle=0.0;this.upperAngle=0.0;this.motorTorque=0.0;this.motorSpeed=0.0;this.enableLimit=false;this.enableMotor=false;},anchorPoint:null,lowerAngle:null,upperAngle:null,motorTorque:null,motorSpeed:null,enableLimit:null,enableMotor:null});
diff --git a/o3d/samples/o3d-webgl-samples/box2d-3d/third_party/prototype-1.6.0.2.js b/o3d/samples/o3d-webgl-samples/box2d-3d/third_party/prototype-1.6.0.2.js
deleted file mode 100644
index 6385503..0000000
--- a/o3d/samples/o3d-webgl-samples/box2d-3d/third_party/prototype-1.6.0.2.js
+++ /dev/null
@@ -1,4221 +0,0 @@
-/* Prototype JavaScript framework, version 1.6.0.2
- * (c) 2005-2008 Sam Stephenson
- *
- * Prototype is freely distributable under the terms of an MIT-style license.
- * For details, see the Prototype web site: http://www.prototypejs.org/
- *
- *--------------------------------------------------------------------------*/
-
-var Prototype = {
- Version: '1.6.0.2',
-
- Browser: {
- IE: !!(window.attachEvent && !window.opera),
- Opera: !!window.opera,
- WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
- Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
- MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
- },
-
- BrowserFeatures: {
- XPath: !!document.evaluate,
- ElementExtensions: !!window.HTMLElement,
- SpecificElementExtensions:
- document.createElement('div').__proto__ &&
- document.createElement('div').__proto__ !==
- document.createElement('form').__proto__
- },
-
- ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
- JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
-
- emptyFunction: function() { },
- K: function(x) { return x }
-};
-
-if (Prototype.Browser.MobileSafari)
- Prototype.BrowserFeatures.SpecificElementExtensions = false;
-
-
-/* Based on Alex Arnell's inheritance implementation. */
-var Class = {
- create: function() {
- var parent = null, properties = $A(arguments);
- if (Object.isFunction(properties[0]))
- parent = properties.shift();
-
- function klass() {
- this.initialize.apply(this, arguments);
- }
-
- Object.extend(klass, Class.Methods);
- klass.superclass = parent;
- klass.subclasses = [];
-
- if (parent) {
- var subclass = function() { };
- subclass.prototype = parent.prototype;
- klass.prototype = new subclass;
- parent.subclasses.push(klass);
- }
-
- for (var i = 0; i < properties.length; i++)
- klass.addMethods(properties[i]);
-
- if (!klass.prototype.initialize)
- klass.prototype.initialize = Prototype.emptyFunction;
-
- klass.prototype.constructor = klass;
-
- return klass;
- }
-};
-
-Class.Methods = {
- addMethods: function(source) {
- var ancestor = this.superclass && this.superclass.prototype;
- var properties = Object.keys(source);
-
- if (!Object.keys({ toString: true }).length)
- properties.push("toString", "valueOf");
-
- for (var i = 0, length = properties.length; i < length; i++) {
- var property = properties[i], value = source[property];
- if (ancestor && Object.isFunction(value) &&
- value.argumentNames().first() == "$super") {
- var method = value, value = Object.extend((function(m) {
- return function() { return ancestor[m].apply(this, arguments) };
- })(property).wrap(method), {
- valueOf: function() { return method },
- toString: function() { return method.toString() }
- });
- }
- this.prototype[property] = value;
- }
-
- return this;
- }
-};
-
-var Abstract = { };
-
-Object.extend = function(destination, source) {
- for (var property in source)
- destination[property] = source[property];
- return destination;
-};
-
-Object.extend(Object, {
- inspect: function(object) {
- try {
- if (Object.isUndefined(object)) return 'undefined';
- if (object === null) return 'null';
- return object.inspect ? object.inspect() : String(object);
- } catch (e) {
- if (e instanceof RangeError) return '...';
- throw e;
- }
- },
-
- toJSON: function(object) {
- var type = typeof object;
- switch (type) {
- case 'undefined':
- case 'function':
- case 'unknown': return;
- case 'boolean': return object.toString();
- }
-
- if (object === null) return 'null';
- if (object.toJSON) return object.toJSON();
- if (Object.isElement(object)) return;
-
- var results = [];
- for (var property in object) {
- var value = Object.toJSON(object[property]);
- if (!Object.isUndefined(value))
- results.push(property.toJSON() + ': ' + value);
- }
-
- return '{' + results.join(', ') + '}';
- },
-
- toQueryString: function(object) {
- return $H(object).toQueryString();
- },
-
- toHTML: function(object) {
- return object && object.toHTML ? object.toHTML() : String.interpret(object);
- },
-
- keys: function(object) {
- var keys = [];
- for (var property in object)
- keys.push(property);
- return keys;
- },
-
- values: function(object) {
- var values = [];
- for (var property in object)
- values.push(object[property]);
- return values;
- },
-
- clone: function(object) {
- return Object.extend({ }, object);
- },
-
- isElement: function(object) {
- return object && object.nodeType == 1;
- },
-
- isArray: function(object) {
- return object != null && typeof object == "object" &&
- 'splice' in object && 'join' in object;
- },
-
- isHash: function(object) {
- return object instanceof Hash;
- },
-
- isFunction: function(object) {
- return typeof object == "function";
- },
-
- isString: function(object) {
- return typeof object == "string";
- },
-
- isNumber: function(object) {
- return typeof object == "number";
- },
-
- isUndefined: function(object) {
- return typeof object == "undefined";
- }
-});
-
-Object.extend(Function.prototype, {
- argumentNames: function() {
- var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
- return names.length == 1 && !names[0] ? [] : names;
- },
-
- bind: function() {
- if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
- var __method = this, args = $A(arguments), object = args.shift();
- return function() {
- return __method.apply(object, args.concat($A(arguments)));
- }
- },
-
- bindAsEventListener: function() {
- var __method = this, args = $A(arguments), object = args.shift();
- return function(event) {
- return __method.apply(object, [event || window.event].concat(args));
- }
- },
-
- curry: function() {
- if (!arguments.length) return this;
- var __method = this, args = $A(arguments);
- return function() {
- return __method.apply(this, args.concat($A(arguments)));
- }
- },
-
- delay: function() {
- var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
- return window.setTimeout(function() {
- return __method.apply(__method, args);
- }, timeout);
- },
-
- wrap: function(wrapper) {
- var __method = this;
- return function() {
- return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
- }
- },
-
- methodize: function() {
- if (this._methodized) return this._methodized;
- var __method = this;
- return this._methodized = function() {
- return __method.apply(null, [this].concat($A(arguments)));
- };
- }
-});
-
-Function.prototype.defer = Function.prototype.delay.curry(0.01);
-
-Date.prototype.toJSON = function() {
- return '"' + this.getUTCFullYear() + '-' +
- (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
- this.getUTCDate().toPaddedString(2) + 'T' +
- this.getUTCHours().toPaddedString(2) + ':' +
- this.getUTCMinutes().toPaddedString(2) + ':' +
- this.getUTCSeconds().toPaddedString(2) + 'Z"';
-};
-
-var Try = {
- these: function() {
- var returnValue;
-
- for (var i = 0, length = arguments.length; i < length; i++) {
- var lambda = arguments[i];
- try {
- returnValue = lambda();
- break;
- } catch (e) { }
- }
-
- return returnValue;
- }
-};
-
-RegExp.prototype.match = RegExp.prototype.test;
-
-RegExp.escape = function(str) {
- return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
-};
-
-/*--------------------------------------------------------------------------*/
-
-var PeriodicalExecuter = Class.create({
- initialize: function(callback, frequency) {
- this.callback = callback;
- this.frequency = frequency;
- this.currentlyExecuting = false;
-
- this.registerCallback();
- },
-
- registerCallback: function() {
- this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
- },
-
- execute: function() {
- this.callback(this);
- },
-
- stop: function() {
- if (!this.timer) return;
- clearInterval(this.timer);
- this.timer = null;
- },
-
- onTimerEvent: function() {
- if (!this.currentlyExecuting) {
- try {
- this.currentlyExecuting = true;
- this.execute();
- } finally {
- this.currentlyExecuting = false;
- }
- }
- }
-});
-Object.extend(String, {
- interpret: function(value) {
- return value == null ? '' : String(value);
- },
- specialChar: {
- '\b': '\\b',
- '\t': '\\t',
- '\n': '\\n',
- '\f': '\\f',
- '\r': '\\r',
- '\\': '\\\\'
- }
-});
-
-Object.extend(String.prototype, {
- gsub: function(pattern, replacement) {
- var result = '', source = this, match;
- replacement = arguments.callee.prepareReplacement(replacement);
-
- while (source.length > 0) {
- if (match = source.match(pattern)) {
- result += source.slice(0, match.index);
- result += String.interpret(replacement(match));
- source = source.slice(match.index + match[0].length);
- } else {
- result += source, source = '';
- }
- }
- return result;
- },
-
- sub: function(pattern, replacement, count) {
- replacement = this.gsub.prepareReplacement(replacement);
- count = Object.isUndefined(count) ? 1 : count;
-
- return this.gsub(pattern, function(match) {
- if (--count < 0) return match[0];
- return replacement(match);
- });
- },
-
- scan: function(pattern, iterator) {
- this.gsub(pattern, iterator);
- return String(this);
- },
-
- truncate: function(length, truncation) {
- length = length || 30;
- truncation = Object.isUndefined(truncation) ? '...' : truncation;
- return this.length > length ?
- this.slice(0, length - truncation.length) + truncation : String(this);
- },
-
- strip: function() {
- return this.replace(/^\s+/, '').replace(/\s+$/, '');
- },
-
- stripTags: function() {
- return this.replace(/<\/?[^>]+>/gi, '');
- },
-
- stripScripts: function() {
- return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
- },
-
- extractScripts: function() {
- var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
- var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
- return (this.match(matchAll) || []).map(function(scriptTag) {
- return (scriptTag.match(matchOne) || ['', ''])[1];
- });
- },
-
- evalScripts: function() {
- return this.extractScripts().map(function(script) { return eval(script) });
- },
-
- escapeHTML: function() {
- var self = arguments.callee;
- self.text.data = this;
- return self.div.innerHTML;
- },
-
- unescapeHTML: function() {
- var div = new Element('div');
- div.innerHTML = this.stripTags();
- return div.childNodes[0] ? (div.childNodes.length > 1 ?
- $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
- div.childNodes[0].nodeValue) : '';
- },
-
- toQueryParams: function(separator) {
- var match = this.strip().match(/([^?#]*)(#.*)?$/);
- if (!match) return { };
-
- return match[1].split(separator || '&').inject({ }, function(hash, pair) {
- if ((pair = pair.split('='))[0]) {
- var key = decodeURIComponent(pair.shift());
- var value = pair.length > 1 ? pair.join('=') : pair[0];
- if (value != undefined) value = decodeURIComponent(value);
-
- if (key in hash) {
- if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
- hash[key].push(value);
- }
- else hash[key] = value;
- }
- return hash;
- });
- },
-
- toArray: function() {
- return this.split('');
- },
-
- succ: function() {
- return this.slice(0, this.length - 1) +
- String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
- },
-
- times: function(count) {
- return count < 1 ? '' : new Array(count + 1).join(this);
- },
-
- camelize: function() {
- var parts = this.split('-'), len = parts.length;
- if (len == 1) return parts[0];
-
- var camelized = this.charAt(0) == '-'
- ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
- : parts[0];
-
- for (var i = 1; i < len; i++)
- camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
-
- return camelized;
- },
-
- capitalize: function() {
- return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
- },
-
- underscore: function() {
- return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
- },
-
- dasherize: function() {
- return this.gsub(/_/,'-');
- },
-
- inspect: function(useDoubleQuotes) {
- var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
- var character = String.specialChar[match[0]];
- return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
- });
- if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
- return "'" + escapedString.replace(/'/g, '\\\'') + "'";
- },
-
- toJSON: function() {
- return this.inspect(true);
- },
-
- unfilterJSON: function(filter) {
- return this.sub(filter || Prototype.JSONFilter, '#{1}');
- },
-
- isJSON: function() {
- var str = this;
- if (str.blank()) return false;
- str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
- return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
- },
-
- evalJSON: function(sanitize) {
- var json = this.unfilterJSON();
- try {
- if (!sanitize || json.isJSON()) return eval('(' + json + ')');
- } catch (e) { }
- throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
- },
-
- include: function(pattern) {
- return this.indexOf(pattern) > -1;
- },
-
- startsWith: function(pattern) {
- return this.indexOf(pattern) === 0;
- },
-
- endsWith: function(pattern) {
- var d = this.length - pattern.length;
- return d >= 0 && this.lastIndexOf(pattern) === d;
- },
-
- empty: function() {
- return this == '';
- },
-
- blank: function() {
- return /^\s*$/.test(this);
- },
-
- interpolate: function(object, pattern) {
- return new Template(this, pattern).evaluate(object);
- }
-});
-
-if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
- escapeHTML: function() {
- return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
- },
- unescapeHTML: function() {
- return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
- }
-});
-
-String.prototype.gsub.prepareReplacement = function(replacement) {
- if (Object.isFunction(replacement)) return replacement;
- var template = new Template(replacement);
- return function(match) { return template.evaluate(match) };
-};
-
-String.prototype.parseQuery = String.prototype.toQueryParams;
-
-Object.extend(String.prototype.escapeHTML, {
- div: document.createElement('div'),
- text: document.createTextNode('')
-});
-
-with (String.prototype.escapeHTML) div.appendChild(text);
-
-var Template = Class.create({
- initialize: function(template, pattern) {
- this.template = template.toString();
- this.pattern = pattern || Template.Pattern;
- },
-
- evaluate: function(object) {
- if (Object.isFunction(object.toTemplateReplacements))
- object = object.toTemplateReplacements();
-
- return this.template.gsub(this.pattern, function(match) {
- if (object == null) return '';
-
- var before = match[1] || '';
- if (before == '\\') return match[2];
-
- var ctx = object, expr = match[3];
- var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
- match = pattern.exec(expr);
- if (match == null) return before;
-
- while (match != null) {
- var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
- ctx = ctx[comp];
- if (null == ctx || '' == match[3]) break;
- expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
- match = pattern.exec(expr);
- }
-
- return before + String.interpret(ctx);
- });
- }
-});
-Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
-
-var $break = { };
-
-var Enumerable = {
- each: function(iterator, context) {
- var index = 0;
- iterator = iterator.bind(context);
- try {
- this._each(function(value) {
- iterator(value, index++);
- });
- } catch (e) {
- if (e != $break) throw e;
- }
- return this;
- },
-
- eachSlice: function(number, iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var index = -number, slices = [], array = this.toArray();
- while ((index += number) < array.length)
- slices.push(array.slice(index, index+number));
- return slices.collect(iterator, context);
- },
-
- all: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var result = true;
- this.each(function(value, index) {
- result = result && !!iterator(value, index);
- if (!result) throw $break;
- });
- return result;
- },
-
- any: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var result = false;
- this.each(function(value, index) {
- if (result = !!iterator(value, index))
- throw $break;
- });
- return result;
- },
-
- collect: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var results = [];
- this.each(function(value, index) {
- results.push(iterator(value, index));
- });
- return results;
- },
-
- detect: function(iterator, context) {
- iterator = iterator.bind(context);
- var result;
- this.each(function(value, index) {
- if (iterator(value, index)) {
- result = value;
- throw $break;
- }
- });
- return result;
- },
-
- findAll: function(iterator, context) {
- iterator = iterator.bind(context);
- var results = [];
- this.each(function(value, index) {
- if (iterator(value, index))
- results.push(value);
- });
- return results;
- },
-
- grep: function(filter, iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var results = [];
-
- if (Object.isString(filter))
- filter = new RegExp(filter);
-
- this.each(function(value, index) {
- if (filter.match(value))
- results.push(iterator(value, index));
- });
- return results;
- },
-
- include: function(object) {
- if (Object.isFunction(this.indexOf))
- if (this.indexOf(object) != -1) return true;
-
- var found = false;
- this.each(function(value) {
- if (value == object) {
- found = true;
- throw $break;
- }
- });
- return found;
- },
-
- inGroupsOf: function(number, fillWith) {
- fillWith = Object.isUndefined(fillWith) ? null : fillWith;
- return this.eachSlice(number, function(slice) {
- while(slice.length < number) slice.push(fillWith);
- return slice;
- });
- },
-
- inject: function(memo, iterator, context) {
- iterator = iterator.bind(context);
- this.each(function(value, index) {
- memo = iterator(memo, value, index);
- });
- return memo;
- },
-
- invoke: function(method) {
- var args = $A(arguments).slice(1);
- return this.map(function(value) {
- return value[method].apply(value, args);
- });
- },
-
- max: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var result;
- this.each(function(value, index) {
- value = iterator(value, index);
- if (result == null || value >= result)
- result = value;
- });
- return result;
- },
-
- min: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var result;
- this.each(function(value, index) {
- value = iterator(value, index);
- if (result == null || value < result)
- result = value;
- });
- return result;
- },
-
- partition: function(iterator, context) {
- iterator = iterator ? iterator.bind(context) : Prototype.K;
- var trues = [], falses = [];
- this.each(function(value, index) {
- (iterator(value, index) ?
- trues : falses).push(value);
- });
- return [trues, falses];
- },
-
- pluck: function(property) {
- var results = [];
- this.each(function(value) {
- results.push(value[property]);
- });
- return results;
- },
-
- reject: function(iterator, context) {
- iterator = iterator.bind(context);
- var results = [];
- this.each(function(value, index) {
- if (!iterator(value, index))
- results.push(value);
- });
- return results;
- },
-
- sortBy: function(iterator, context) {
- iterator = iterator.bind(context);
- return this.map(function(value, index) {
- return {value: value, criteria: iterator(value, index)};
- }).sort(function(left, right) {
- var a = left.criteria, b = right.criteria;
- return a < b ? -1 : a > b ? 1 : 0;
- }).pluck('value');
- },
-
- toArray: function() {
- return this.map();
- },
-
- zip: function() {
- var iterator = Prototype.K, args = $A(arguments);
- if (Object.isFunction(args.last()))
- iterator = args.pop();
-
- var collections = [this].concat(args).map($A);
- return this.map(function(value, index) {
- return iterator(collections.pluck(index));
- });
- },
-
- size: function() {
- return this.toArray().length;
- },
-
- inspect: function() {
- return '#<Enumerable:' + this.toArray().inspect() + '>';
- }
-};
-
-Object.extend(Enumerable, {
- map: Enumerable.collect,
- find: Enumerable.detect,
- select: Enumerable.findAll,
- filter: Enumerable.findAll,
- member: Enumerable.include,
- entries: Enumerable.toArray,
- every: Enumerable.all,
- some: Enumerable.any
-});
-function $A(iterable) {
- if (!iterable) return [];
- if (iterable.toArray) return iterable.toArray();
- var length = iterable.length || 0, results = new Array(length);
- while (length--) results[length] = iterable[length];
- return results;
-}
-
-if (Prototype.Browser.WebKit) {
- $A = function(iterable) {
- if (!iterable) return [];
- if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
- iterable.toArray) return iterable.toArray();
- var length = iterable.length || 0, results = new Array(length);
- while (length--) results[length] = iterable[length];
- return results;
- };
-}
-
-Array.from = $A;
-
-Object.extend(Array.prototype, Enumerable);
-
-if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
-
-Object.extend(Array.prototype, {
- _each: function(iterator) {
- for (var i = 0, length = this.length; i < length; i++)
- iterator(this[i]);
- },
-
- clear: function() {
- this.length = 0;
- return this;
- },
-
- first: function() {
- return this[0];
- },
-
- last: function() {
- return this[this.length - 1];
- },
-
- compact: function() {
- return this.select(function(value) {
- return value != null;
- });
- },
-
- flatten: function() {
- return this.inject([], function(array, value) {
- return array.concat(Object.isArray(value) ?
- value.flatten() : [value]);
- });
- },
-
- without: function() {
- var values = $A(arguments);
- return this.select(function(value) {
- return !values.include(value);
- });
- },
-
- reverse: function(inline) {
- return (inline !== false ? this : this.toArray())._reverse();
- },
-
- reduce: function() {
- return this.length > 1 ? this : this[0];
- },
-
- uniq: function(sorted) {
- return this.inject([], function(array, value, index) {
- if (0 == index || (sorted ? array.last() != value : !array.include(value)))
- array.push(value);
- return array;
- });
- },
-
- intersect: function(array) {
- return this.uniq().findAll(function(item) {
- return array.detect(function(value) { return item === value });
- });
- },
-
- clone: function() {
- return [].concat(this);
- },
-
- size: function() {
- return this.length;
- },
-
- inspect: function() {
- return '[' + this.map(Object.inspect).join(', ') + ']';
- },
-
- toJSON: function() {
- var results = [];
- this.each(function(object) {
- var value = Object.toJSON(object);
- if (!Object.isUndefined(value)) results.push(value);
- });
- return '[' + results.join(', ') + ']';
- }
-});
-
-// use native browser JS 1.6 implementation if available
-if (Object.isFunction(Array.prototype.forEach))
- Array.prototype._each = Array.prototype.forEach;
-
-if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
- i || (i = 0);
- var length = this.length;
- if (i < 0) i = length + i;
- for (; i < length; i++)
- if (this[i] === item) return i;
- return -1;
-};
-
-if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
- i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
- var n = this.slice(0, i).reverse().indexOf(item);
- return (n < 0) ? n : i - n - 1;
-};
-
-Array.prototype.toArray = Array.prototype.clone;
-
-function $w(string) {
- if (!Object.isString(string)) return [];
- string = string.strip();
- return string ? string.split(/\s+/) : [];
-}
-
-if (Prototype.Browser.Opera){
- Array.prototype.concat = function() {
- var array = [];
- for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
- for (var i = 0, length = arguments.length; i < length; i++) {
- if (Object.isArray(arguments[i])) {
- for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
- array.push(arguments[i][j]);
- } else {
- array.push(arguments[i]);
- }
- }
- return array;
- };
-}
-Object.extend(Number.prototype, {
- toColorPart: function() {
- return this.toPaddedString(2, 16);
- },
-
- succ: function() {
- return this + 1;
- },
-
- times: function(iterator) {
- $R(0, this, true).each(iterator);
- return this;
- },
-
- toPaddedString: function(length, radix) {
- var string = this.toString(radix || 10);
- return '0'.times(length - string.length) + string;
- },
-
- toJSON: function() {
- return isFinite(this) ? this.toString() : 'null';
- }
-});
-
-$w('abs round ceil floor').each(function(method){
- Number.prototype[method] = Math[method].methodize();
-});
-function $H(object) {
- return new Hash(object);
-};
-
-var Hash = Class.create(Enumerable, (function() {
-
- function toQueryPair(key, value) {
- if (Object.isUndefined(value)) return key;
- return key + '=' + encodeURIComponent(String.interpret(value));
- }
-
- return {
- initialize: function(object) {
- this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
- },
-
- _each: function(iterator) {
- for (var key in this._object) {
- var value = this._object[key], pair = [key, value];
- pair.key = key;
- pair.value = value;
- iterator(pair);
- }
- },
-
- set: function(key, value) {
- return this._object[key] = value;
- },
-
- get: function(key) {
- return this._object[key];
- },
-
- unset: function(key) {
- var value = this._object[key];
- delete this._object[key];
- return value;
- },
-
- toObject: function() {
- return Object.clone(this._object);
- },
-
- keys: function() {
- return this.pluck('key');
- },
-
- values: function() {
- return this.pluck('value');
- },
-
- index: function(value) {
- var match = this.detect(function(pair) {
- return pair.value === value;
- });
- return match && match.key;
- },
-
- merge: function(object) {
- return this.clone().update(object);
- },
-
- update: function(object) {
- return new Hash(object).inject(this, function(result, pair) {
- result.set(pair.key, pair.value);
- return result;
- });
- },
-
- toQueryString: function() {
- return this.map(function(pair) {
- var key = encodeURIComponent(pair.key), values = pair.value;
-
- if (values && typeof values == 'object') {
- if (Object.isArray(values))
- return values.map(toQueryPair.curry(key)).join('&');
- }
- return toQueryPair(key, values);
- }).join('&');
- },
-
- inspect: function() {
- return '#<Hash:{' + this.map(function(pair) {
- return pair.map(Object.inspect).join(': ');
- }).join(', ') + '}>';
- },
-
- toJSON: function() {
- return Object.toJSON(this.toObject());
- },
-
- clone: function() {
- return new Hash(this);
- }
- }
-})());
-
-Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
-Hash.from = $H;
-var ObjectRange = Class.create(Enumerable, {
- initialize: function(start, end, exclusive) {
- this.start = start;
- this.end = end;
- this.exclusive = exclusive;
- },
-
- _each: function(iterator) {
- var value = this.start;
- while (this.include(value)) {
- iterator(value);
- value = value.succ();
- }
- },
-
- include: function(value) {
- if (value < this.start)
- return false;
- if (this.exclusive)
- return value < this.end;
- return value <= this.end;
- }
-});
-
-var $R = function(start, end, exclusive) {
- return new ObjectRange(start, end, exclusive);
-};
-
-var Ajax = {
- getTransport: function() {
- return Try.these(
- function() {return new XMLHttpRequest()},
- function() {return new ActiveXObject('Msxml2.XMLHTTP')},
- function() {return new ActiveXObject('Microsoft.XMLHTTP')}
- ) || false;
- },
-
- activeRequestCount: 0
-};
-
-Ajax.Responders = {
- responders: [],
-
- _each: function(iterator) {
- this.responders._each(iterator);
- },
-
- register: function(responder) {
- if (!this.include(responder))
- this.responders.push(responder);
- },
-
- unregister: function(responder) {
- this.responders = this.responders.without(responder);
- },
-
- dispatch: function(callback, request, transport, json) {
- this.each(function(responder) {
- if (Object.isFunction(responder[callback])) {
- try {
- responder[callback].apply(responder, [request, transport, json]);
- } catch (e) { }
- }
- });
- }
-};
-
-Object.extend(Ajax.Responders, Enumerable);
-
-Ajax.Responders.register({
- onCreate: function() { Ajax.activeRequestCount++ },
- onComplete: function() { Ajax.activeRequestCount-- }
-});
-
-Ajax.Base = Class.create({
- initialize: function(options) {
- this.options = {
- method: 'post',
- asynchronous: true,
- contentType: 'application/x-www-form-urlencoded',
- encoding: 'UTF-8',
- parameters: '',
- evalJSON: true,
- evalJS: true
- };
- Object.extend(this.options, options || { });
-
- this.options.method = this.options.method.toLowerCase();
-
- if (Object.isString(this.options.parameters))
- this.options.parameters = this.options.parameters.toQueryParams();
- else if (Object.isHash(this.options.parameters))
- this.options.parameters = this.options.parameters.toObject();
- }
-});
-
-Ajax.Request = Class.create(Ajax.Base, {
- _complete: false,
-
- initialize: function($super, url, options) {
- $super(options);
- this.transport = Ajax.getTransport();
- this.request(url);
- },
-
- request: function(url) {
- this.url = url;
- this.method = this.options.method;
- var params = Object.clone(this.options.parameters);
-
- if (!['get', 'post'].include(this.method)) {
- // simulate other verbs over post
- params['_method'] = this.method;
- this.method = 'post';
- }
-
- this.parameters = params;
-
- if (params = Object.toQueryString(params)) {
- // when GET, append parameters to URL
- if (this.method == 'get')
- this.url += (this.url.include('?') ? '&' : '?') + params;
- else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
- params += '&_=';
- }
-
- try {
- var response = new Ajax.Response(this);
- if (this.options.onCreate) this.options.onCreate(response);
- Ajax.Responders.dispatch('onCreate', this, response);
-
- this.transport.open(this.method.toUpperCase(), this.url,
- this.options.asynchronous);
-
- if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
-
- this.transport.onreadystatechange = this.onStateChange.bind(this);
- this.setRequestHeaders();
-
- this.body = this.method == 'post' ? (this.options.postBody || params) : null;
- this.transport.send(this.body);
-
- /* Force Firefox to handle ready state 4 for synchronous requests */
- if (!this.options.asynchronous && this.transport.overrideMimeType)
- this.onStateChange();
-
- }
- catch (e) {
- this.dispatchException(e);
- }
- },
-
- onStateChange: function() {
- var readyState = this.transport.readyState;
- if (readyState > 1 && !((readyState == 4) && this._complete))
- this.respondToReadyState(this.transport.readyState);
- },
-
- setRequestHeaders: function() {
- var headers = {
- 'X-Requested-With': 'XMLHttpRequest',
- 'X-Prototype-Version': Prototype.Version,
- 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
- };
-
- if (this.method == 'post') {
- headers['Content-type'] = this.options.contentType +
- (this.options.encoding ? '; charset=' + this.options.encoding : '');
-
- /* Force "Connection: close" for older Mozilla browsers to work
- * around a bug where XMLHttpRequest sends an incorrect
- * Content-length header. See Mozilla Bugzilla #246651.
- */
- if (this.transport.overrideMimeType &&
- (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
- headers['Connection'] = 'close';
- }
-
- // user-defined headers
- if (typeof this.options.requestHeaders == 'object') {
- var extras = this.options.requestHeaders;
-
- if (Object.isFunction(extras.push))
- for (var i = 0, length = extras.length; i < length; i += 2)
- headers[extras[i]] = extras[i+1];
- else
- $H(extras).each(function(pair) { headers[pair.key] = pair.value });
- }
-
- for (var name in headers)
- this.transport.setRequestHeader(name, headers[name]);
- },
-
- success: function() {
- var status = this.getStatus();
- return !status || (status >= 200 && status < 300);
- },
-
- getStatus: function() {
- try {
- return this.transport.status || 0;
- } catch (e) { return 0 }
- },
-
- respondToReadyState: function(readyState) {
- var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
-
- if (state == 'Complete') {
- try {
- this._complete = true;
- (this.options['on' + response.status]
- || this.options['on' + (this.success() ? 'Success' : 'Failure')]
- || Prototype.emptyFunction)(response, response.headerJSON);
- } catch (e) {
- this.dispatchException(e);
- }
-
- var contentType = response.getHeader('Content-type');
- if (this.options.evalJS == 'force'
- || (this.options.evalJS && this.isSameOrigin() && contentType
- && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
- this.evalResponse();
- }
-
- try {
- (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
- Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
- } catch (e) {
- this.dispatchException(e);
- }
-
- if (state == 'Complete') {
- // avoid memory leak in MSIE: clean up
- this.transport.onreadystatechange = Prototype.emptyFunction;
- }
- },
-
- isSameOrigin: function() {
- var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
- return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
- protocol: location.protocol,
- domain: document.domain,
- port: location.port ? ':' + location.port : ''
- }));
- },
-
- getHeader: function(name) {
- try {
- return this.transport.getResponseHeader(name) || null;
- } catch (e) { return null }
- },
-
- evalResponse: function() {
- try {
- return eval((this.transport.responseText || '').unfilterJSON());
- } catch (e) {
- this.dispatchException(e);
- }
- },
-
- dispatchException: function(exception) {
- (this.options.onException || Prototype.emptyFunction)(this, exception);
- Ajax.Responders.dispatch('onException', this, exception);
- }
-});
-
-Ajax.Request.Events =
- ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
-
-Ajax.Response = Class.create({
- initialize: function(request){
- this.request = request;
- var transport = this.transport = request.transport,
- readyState = this.readyState = transport.readyState;
-
- if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
- this.status = this.getStatus();
- this.statusText = this.getStatusText();
- this.responseText = String.interpret(transport.responseText);
- this.headerJSON = this._getHeaderJSON();
- }
-
- if(readyState == 4) {
- var xml = transport.responseXML;
- this.responseXML = Object.isUndefined(xml) ? null : xml;
- this.responseJSON = this._getResponseJSON();
- }
- },
-
- status: 0,
- statusText: '',
-
- getStatus: Ajax.Request.prototype.getStatus,
-
- getStatusText: function() {
- try {
- return this.transport.statusText || '';
- } catch (e) { return '' }
- },
-
- getHeader: Ajax.Request.prototype.getHeader,
-
- getAllHeaders: function() {
- try {
- return this.getAllResponseHeaders();
- } catch (e) { return null }
- },
-
- getResponseHeader: function(name) {
- return this.transport.getResponseHeader(name);
- },
-
- getAllResponseHeaders: function() {
- return this.transport.getAllResponseHeaders();
- },
-
- _getHeaderJSON: function() {
- var json = this.getHeader('X-JSON');
- if (!json) return null;
- json = decodeURIComponent(escape(json));
- try {
- return json.evalJSON(this.request.options.sanitizeJSON ||
- !this.request.isSameOrigin());
- } catch (e) {
- this.request.dispatchException(e);
- }
- },
-
- _getResponseJSON: function() {
- var options = this.request.options;
- if (!options.evalJSON || (options.evalJSON != 'force' &&
- !(this.getHeader('Content-type') || '').include('application/json')) ||
- this.responseText.blank())
- return null;
- try {
- return this.responseText.evalJSON(options.sanitizeJSON ||
- !this.request.isSameOrigin());
- } catch (e) {
- this.request.dispatchException(e);
- }
- }
-});
-
-Ajax.Updater = Class.create(Ajax.Request, {
- initialize: function($super, container, url, options) {
- this.container = {
- success: (container.success || container),
- failure: (container.failure || (container.success ? null : container))
- };
-
- options = Object.clone(options);
- var onComplete = options.onComplete;
- options.onComplete = (function(response, json) {
- this.updateContent(response.responseText);
- if (Object.isFunction(onComplete)) onComplete(response, json);
- }).bind(this);
-
- $super(url, options);
- },
-
- updateContent: function(responseText) {
- var receiver = this.container[this.success() ? 'success' : 'failure'],
- options = this.options;
-
- if (!options.evalScripts) responseText = responseText.stripScripts();
-
- if (receiver = $(receiver)) {
- if (options.insertion) {
- if (Object.isString(options.insertion)) {
- var insertion = { }; insertion[options.insertion] = responseText;
- receiver.insert(insertion);
- }
- else options.insertion(receiver, responseText);
- }
- else receiver.update(responseText);
- }
- }
-});
-
-Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
- initialize: function($super, container, url, options) {
- $super(options);
- this.onComplete = this.options.onComplete;
-
- this.frequency = (this.options.frequency || 2);
- this.decay = (this.options.decay || 1);
-
- this.updater = { };
- this.container = container;
- this.url = url;
-
- this.start();
- },
-
- start: function() {
- this.options.onComplete = this.updateComplete.bind(this);
- this.onTimerEvent();
- },
-
- stop: function() {
- this.updater.options.onComplete = undefined;
- clearTimeout(this.timer);
- (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
- },
-
- updateComplete: function(response) {
- if (this.options.decay) {
- this.decay = (response.responseText == this.lastText ?
- this.decay * this.options.decay : 1);
-
- this.lastText = response.responseText;
- }
- this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
- },
-
- onTimerEvent: function() {
- this.updater = new Ajax.Updater(this.container, this.url, this.options);
- }
-});
-function $(element) {
- if (arguments.length > 1) {
- for (var i = 0, elements = [], length = arguments.length; i < length; i++)
- elements.push($(arguments[i]));
- return elements;
- }
- if (Object.isString(element))
- element = document.getElementById(element);
- return Element.extend(element);
-}
-
-if (Prototype.BrowserFeatures.XPath) {
- document._getElementsByXPath = function(expression, parentElement) {
- var results = [];
- var query = document.evaluate(expression, $(parentElement) || document,
- null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
- for (var i = 0, length = query.snapshotLength; i < length; i++)
- results.push(Element.extend(query.snapshotItem(i)));
- return results;
- };
-}
-
-/*--------------------------------------------------------------------------*/
-
-if (!window.Node) var Node = { };
-
-if (!Node.ELEMENT_NODE) {
- // DOM level 2 ECMAScript Language Binding
- Object.extend(Node, {
- ELEMENT_NODE: 1,
- ATTRIBUTE_NODE: 2,
- TEXT_NODE: 3,
- CDATA_SECTION_NODE: 4,
- ENTITY_REFERENCE_NODE: 5,
- ENTITY_NODE: 6,
- PROCESSING_INSTRUCTION_NODE: 7,
- COMMENT_NODE: 8,
- DOCUMENT_NODE: 9,
- DOCUMENT_TYPE_NODE: 10,
- DOCUMENT_FRAGMENT_NODE: 11,
- NOTATION_NODE: 12
- });
-}
-
-(function() {
- var element = this.Element;
- this.Element = function(tagName, attributes) {
- attributes = attributes || { };
- tagName = tagName.toLowerCase();
- var cache = Element.cache;
- if (Prototype.Browser.IE && attributes.name) {
- tagName = '<' + tagName + ' name="' + attributes.name + '">';
- delete attributes.name;
- return Element.writeAttribute(document.createElement(tagName), attributes);
- }
- if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
- return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
- };
- Object.extend(this.Element, element || { });
-}).call(window);
-
-Element.cache = { };
-
-Element.Methods = {
- visible: function(element) {
- return $(element).style.display != 'none';
- },
-
- toggle: function(element) {
- element = $(element);
- Element[Element.visible(element) ? 'hide' : 'show'](element);
- return element;
- },
-
- hide: function(element) {
- $(element).style.display = 'none';
- return element;
- },
-
- show: function(element) {
- $(element).style.display = '';
- return element;
- },
-
- remove: function(element) {
- element = $(element);
- element.parentNode.removeChild(element);
- return element;
- },
-
- update: function(element, content) {
- element = $(element);
- if (content && content.toElement) content = content.toElement();
- if (Object.isElement(content)) return element.update().insert(content);
- content = Object.toHTML(content);
- element.innerHTML = content.stripScripts();
- content.evalScripts.bind(content).defer();
- return element;
- },
-
- replace: function(element, content) {
- element = $(element);
- if (content && content.toElement) content = content.toElement();
- else if (!Object.isElement(content)) {
- content = Object.toHTML(content);
- var range = element.ownerDocument.createRange();
- range.selectNode(element);
- content.evalScripts.bind(content).defer();
- content = range.createContextualFragment(content.stripScripts());
- }
- element.parentNode.replaceChild(content, element);
- return element;
- },
-
- insert: function(element, insertions) {
- element = $(element);
-
- if (Object.isString(insertions) || Object.isNumber(insertions) ||
- Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
- insertions = {bottom:insertions};
-
- var content, insert, tagName, childNodes;
-
- for (var position in insertions) {
- content = insertions[position];
- position = position.toLowerCase();
- insert = Element._insertionTranslations[position];
-
- if (content && content.toElement) content = content.toElement();
- if (Object.isElement(content)) {
- insert(element, content);
- continue;
- }
-
- content = Object.toHTML(content);
-
- tagName = ((position == 'before' || position == 'after')
- ? element.parentNode : element).tagName.toUpperCase();
-
- childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
-
- if (position == 'top' || position == 'after') childNodes.reverse();
- childNodes.each(insert.curry(element));
-
- content.evalScripts.bind(content).defer();
- }
-
- return element;
- },
-
- wrap: function(element, wrapper, attributes) {
- element = $(element);
- if (Object.isElement(wrapper))
- $(wrapper).writeAttribute(attributes || { });
- else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
- else wrapper = new Element('div', wrapper);
- if (element.parentNode)
- element.parentNode.replaceChild(wrapper, element);
- wrapper.appendChild(element);
- return wrapper;
- },
-
- inspect: function(element) {
- element = $(element);
- var result = '<' + element.tagName.toLowerCase();
- $H({'id': 'id', 'className': 'class'}).each(function(pair) {
- var property = pair.first(), attribute = pair.last();
- var value = (element[property] || '').toString();
- if (value) result += ' ' + attribute + '=' + value.inspect(true);
- });
- return result + '>';
- },
-
- recursivelyCollect: function(element, property) {
- element = $(element);
- var elements = [];
- while (element = element[property])
- if (element.nodeType == 1)
- elements.push(Element.extend(element));
- return elements;
- },
-
- ancestors: function(element) {
- return $(element).recursivelyCollect('parentNode');
- },
-
- descendants: function(element) {
- return $(element).select("*");
- },
-
- firstDescendant: function(element) {
- element = $(element).firstChild;
- while (element && element.nodeType != 1) element = element.nextSibling;
- return $(element);
- },
-
- immediateDescendants: function(element) {
- if (!(element = $(element).firstChild)) return [];
- while (element && element.nodeType != 1) element = element.nextSibling;
- if (element) return [element].concat($(element).nextSiblings());
- return [];
- },
-
- previousSiblings: function(element) {
- return $(element).recursivelyCollect('previousSibling');
- },
-
- nextSiblings: function(element) {
- return $(element).recursivelyCollect('nextSibling');
- },
-
- siblings: function(element) {
- element = $(element);
- return element.previousSiblings().reverse().concat(element.nextSiblings());
- },
-
- match: function(element, selector) {
- if (Object.isString(selector))
- selector = new Selector(selector);
- return selector.match($(element));
- },
-
- up: function(element, expression, index) {
- element = $(element);
- if (arguments.length == 1) return $(element.parentNode);
- var ancestors = element.ancestors();
- return Object.isNumber(expression) ? ancestors[expression] :
- Selector.findElement(ancestors, expression, index);
- },
-
- down: function(element, expression, index) {
- element = $(element);
- if (arguments.length == 1) return element.firstDescendant();
- return Object.isNumber(expression) ? element.descendants()[expression] :
- element.select(expression)[index || 0];
- },
-
- previous: function(element, expression, index) {
- element = $(element);
- if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
- var previousSiblings = element.previousSiblings();
- return Object.isNumber(expression) ? previousSiblings[expression] :
- Selector.findElement(previousSiblings, expression, index);
- },
-
- next: function(element, expression, index) {
- element = $(element);
- if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
- var nextSiblings = element.nextSiblings();
- return Object.isNumber(expression) ? nextSiblings[expression] :
- Selector.findElement(nextSiblings, expression, index);
- },
-
- select: function() {
- var args = $A(arguments), element = $(args.shift());
- return Selector.findChildElements(element, args);
- },
-
- adjacent: function() {
- var args = $A(arguments), element = $(args.shift());
- return Selector.findChildElements(element.parentNode, args).without(element);
- },
-
- identify: function(element) {
- element = $(element);
- var id = element.readAttribute('id'), self = arguments.callee;
- if (id) return id;
- do { id = 'anonymous_element_' + self.counter++ } while ($(id));
- element.writeAttribute('id', id);
- return id;
- },
-
- readAttribute: function(element, name) {
- element = $(element);
- if (Prototype.Browser.IE) {
- var t = Element._attributeTranslations.read;
- if (t.values[name]) return t.values[name](element, name);
- if (t.names[name]) name = t.names[name];
- if (name.include(':')) {
- return (!element.attributes || !element.attributes[name]) ? null :
- element.attributes[name].value;
- }
- }
- return element.getAttribute(name);
- },
-
- writeAttribute: function(element, name, value) {
- element = $(element);
- var attributes = { }, t = Element._attributeTranslations.write;
-
- if (typeof name == 'object') attributes = name;
- else attributes[name] = Object.isUndefined(value) ? true : value;
-
- for (var attr in attributes) {
- name = t.names[attr] || attr;
- value = attributes[attr];
- if (t.values[attr]) name = t.values[attr](element, value);
- if (value === false || value === null)
- element.removeAttribute(name);
- else if (value === true)
- element.setAttribute(name, name);
- else element.setAttribute(name, value);
- }
- return element;
- },
-
- getHeight: function(element) {
- return $(element).getDimensions().height;
- },
-
- getWidth: function(element) {
- return $(element).getDimensions().width;
- },
-
- classNames: function(element) {
- return new Element.ClassNames(element);
- },
-
- hasClassName: function(element, className) {
- if (!(element = $(element))) return;
- var elementClassName = element.className;
- return (elementClassName.length > 0 && (elementClassName == className ||
- new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
- },
-
- addClassName: function(element, className) {
- if (!(element = $(element))) return;
- if (!element.hasClassName(className))
- element.className += (element.className ? ' ' : '') + className;
- return element;
- },
-
- removeClassName: function(element, className) {
- if (!(element = $(element))) return;
- element.className = element.className.replace(
- new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
- return element;
- },
-
- toggleClassName: function(element, className) {
- if (!(element = $(element))) return;
- return element[element.hasClassName(className) ?
- 'removeClassName' : 'addClassName'](className);
- },
-
- // removes whitespace-only text node children
- cleanWhitespace: function(element) {
- element = $(element);
- var node = element.firstChild;
- while (node) {
- var nextNode = node.nextSibling;
- if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
- element.removeChild(node);
- node = nextNode;
- }
- return element;
- },
-
- empty: function(element) {
- return $(element).innerHTML.blank();
- },
-
- descendantOf: function(element, ancestor) {
- element = $(element), ancestor = $(ancestor);
- var originalAncestor = ancestor;
-
- if (element.compareDocumentPosition)
- return (element.compareDocumentPosition(ancestor) & 8) === 8;
-
- if (element.sourceIndex && !Prototype.Browser.Opera) {
- var e = element.sourceIndex, a = ancestor.sourceIndex,
- nextAncestor = ancestor.nextSibling;
- if (!nextAncestor) {
- do { ancestor = ancestor.parentNode; }
- while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
- }
- if (nextAncestor && nextAncestor.sourceIndex)
- return (e > a && e < nextAncestor.sourceIndex);
- }
-
- while (element = element.parentNode)
- if (element == originalAncestor) return true;
- return false;
- },
-
- scrollTo: function(element) {
- element = $(element);
- var pos = element.cumulativeOffset();
- window.scrollTo(pos[0], pos[1]);
- return element;
- },
-
- getStyle: function(element, style) {
- element = $(element);
- style = style == 'float' ? 'cssFloat' : style.camelize();
- var value = element.style[style];
- if (!value) {
- var css = document.defaultView.getComputedStyle(element, null);
- value = css ? css[style] : null;
- }
- if (style == 'opacity') return value ? parseFloat(value) : 1.0;
- return value == 'auto' ? null : value;
- },
-
- getOpacity: function(element) {
- return $(element).getStyle('opacity');
- },
-
- setStyle: function(element, styles) {
- element = $(element);
- var elementStyle = element.style, match;
- if (Object.isString(styles)) {
- element.style.cssText += ';' + styles;
- return styles.include('opacity') ?
- element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
- }
- for (var property in styles)
- if (property == 'opacity') element.setOpacity(styles[property]);
- else
- elementStyle[(property == 'float' || property == 'cssFloat') ?
- (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
- property] = styles[property];
-
- return element;
- },
-
- setOpacity: function(element, value) {
- element = $(element);
- element.style.opacity = (value == 1 || value === '') ? '' :
- (value < 0.00001) ? 0 : value;
- return element;
- },
-
- getDimensions: function(element) {
- element = $(element);
- var display = $(element).getStyle('display');
- if (display != 'none' && display != null) // Safari bug
- return {width: element.offsetWidth, height: element.offsetHeight};
-
- // All *Width and *Height properties give 0 on elements with display none,
- // so enable the element temporarily
- var els = element.style;
- var originalVisibility = els.visibility;
- var originalPosition = els.position;
- var originalDisplay = els.display;
- els.visibility = 'hidden';
- els.position = 'absolute';
- els.display = 'block';
- var originalWidth = element.clientWidth;
- var originalHeight = element.clientHeight;
- els.display = originalDisplay;
- els.position = originalPosition;
- els.visibility = originalVisibility;
- return {width: originalWidth, height: originalHeight};
- },
-
- makePositioned: function(element) {
- element = $(element);
- var pos = Element.getStyle(element, 'position');
- if (pos == 'static' || !pos) {
- element._madePositioned = true;
- element.style.position = 'relative';
- // Opera returns the offset relative to the positioning context, when an
- // element is position relative but top and left have not been defined
- if (window.opera) {
- element.style.top = 0;
- element.style.left = 0;
- }
- }
- return element;
- },
-
- undoPositioned: function(element) {
- element = $(element);
- if (element._madePositioned) {
- element._madePositioned = undefined;
- element.style.position =
- element.style.top =
- element.style.left =
- element.style.bottom =
- element.style.right = '';
- }
- return element;
- },
-
- makeClipping: function(element) {
- element = $(element);
- if (element._overflow) return element;
- element._overflow = Element.getStyle(element, 'overflow') || 'auto';
- if (element._overflow !== 'hidden')
- element.style.overflow = 'hidden';
- return element;
- },
-
- undoClipping: function(element) {
- element = $(element);
- if (!element._overflow) return element;
- element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
- element._overflow = null;
- return element;
- },
-
- cumulativeOffset: function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- element = element.offsetParent;
- } while (element);
- return Element._returnOffset(valueL, valueT);
- },
-
- positionedOffset: function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- element = element.offsetParent;
- if (element) {
- if (element.tagName == 'BODY') break;
- var p = Element.getStyle(element, 'position');
- if (p !== 'static') break;
- }
- } while (element);
- return Element._returnOffset(valueL, valueT);
- },
-
- absolutize: function(element) {
- element = $(element);
- if (element.getStyle('position') == 'absolute') return;
- // Position.prepare(); // To be done manually by Scripty when it needs it.
-
- var offsets = element.positionedOffset();
- var top = offsets[1];
- var left = offsets[0];
- var width = element.clientWidth;
- var height = element.clientHeight;
-
- element._originalLeft = left - parseFloat(element.style.left || 0);
- element._originalTop = top - parseFloat(element.style.top || 0);
- element._originalWidth = element.style.width;
- element._originalHeight = element.style.height;
-
- element.style.position = 'absolute';
- element.style.top = top + 'px';
- element.style.left = left + 'px';
- element.style.width = width + 'px';
- element.style.height = height + 'px';
- return element;
- },
-
- relativize: function(element) {
- element = $(element);
- if (element.getStyle('position') == 'relative') return;
- // Position.prepare(); // To be done manually by Scripty when it needs it.
-
- element.style.position = 'relative';
- var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
- var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
-
- element.style.top = top + 'px';
- element.style.left = left + 'px';
- element.style.height = element._originalHeight;
- element.style.width = element._originalWidth;
- return element;
- },
-
- cumulativeScrollOffset: function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.scrollTop || 0;
- valueL += element.scrollLeft || 0;
- element = element.parentNode;
- } while (element);
- return Element._returnOffset(valueL, valueT);
- },
-
- getOffsetParent: function(element) {
- if (element.offsetParent) return $(element.offsetParent);
- if (element == document.body) return $(element);
-
- while ((element = element.parentNode) && element != document.body)
- if (Element.getStyle(element, 'position') != 'static')
- return $(element);
-
- return $(document.body);
- },
-
- viewportOffset: function(forElement) {
- var valueT = 0, valueL = 0;
-
- var element = forElement;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
-
- // Safari fix
- if (element.offsetParent == document.body &&
- Element.getStyle(element, 'position') == 'absolute') break;
-
- } while (element = element.offsetParent);
-
- element = forElement;
- do {
- if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
- valueT -= element.scrollTop || 0;
- valueL -= element.scrollLeft || 0;
- }
- } while (element = element.parentNode);
-
- return Element._returnOffset(valueL, valueT);
- },
-
- clonePosition: function(element, source) {
- var options = Object.extend({
- setLeft: true,
- setTop: true,
- setWidth: true,
- setHeight: true,
- offsetTop: 0,
- offsetLeft: 0
- }, arguments[2] || { });
-
- // find page position of source
- source = $(source);
- var p = source.viewportOffset();
-
- // find coordinate system to use
- element = $(element);
- var delta = [0, 0];
- var parent = null;
- // delta [0,0] will do fine with position: fixed elements,
- // position:absolute needs offsetParent deltas
- if (Element.getStyle(element, 'position') == 'absolute') {
- parent = element.getOffsetParent();
- delta = parent.viewportOffset();
- }
-
- // correct by body offsets (fixes Safari)
- if (parent == document.body) {
- delta[0] -= document.body.offsetLeft;
- delta[1] -= document.body.offsetTop;
- }
-
- // set position
- if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
- if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
- if (options.setWidth) element.style.width = source.offsetWidth + 'px';
- if (options.setHeight) element.style.height = source.offsetHeight + 'px';
- return element;
- }
-};
-
-Element.Methods.identify.counter = 1;
-
-Object.extend(Element.Methods, {
- getElementsBySelector: Element.Methods.select,
- childElements: Element.Methods.immediateDescendants
-});
-
-Element._attributeTranslations = {
- write: {
- names: {
- className: 'class',
- htmlFor: 'for'
- },
- values: { }
- }
-};
-
-if (Prototype.Browser.Opera) {
- Element.Methods.getStyle = Element.Methods.getStyle.wrap(
- function(proceed, element, style) {
- switch (style) {
- case 'left': case 'top': case 'right': case 'bottom':
- if (proceed(element, 'position') === 'static') return null;
- case 'height': case 'width':
- // returns '0px' for hidden elements; we want it to return null
- if (!Element.visible(element)) return null;
-
- // returns the border-box dimensions rather than the content-box
- // dimensions, so we subtract padding and borders from the value
- var dim = parseInt(proceed(element, style), 10);
-
- if (dim !== element['offset' + style.capitalize()])
- return dim + 'px';
-
- var properties;
- if (style === 'height') {
- properties = ['border-top-width', 'padding-top',
- 'padding-bottom', 'border-bottom-width'];
- }
- else {
- properties = ['border-left-width', 'padding-left',
- 'padding-right', 'border-right-width'];
- }
- return properties.inject(dim, function(memo, property) {
- var val = proceed(element, property);
- return val === null ? memo : memo - parseInt(val, 10);
- }) + 'px';
- default: return proceed(element, style);
- }
- }
- );
-
- Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
- function(proceed, element, attribute) {
- if (attribute === 'title') return element.title;
- return proceed(element, attribute);
- }
- );
-}
-
-else if (Prototype.Browser.IE) {
- // IE doesn't report offsets correctly for static elements, so we change them
- // to "relative" to get the values, then change them back.
- Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
- function(proceed, element) {
- element = $(element);
- var position = element.getStyle('position');
- if (position !== 'static') return proceed(element);
- element.setStyle({ position: 'relative' });
- var value = proceed(element);
- element.setStyle({ position: position });
- return value;
- }
- );
-
- $w('positionedOffset viewportOffset').each(function(method) {
- Element.Methods[method] = Element.Methods[method].wrap(
- function(proceed, element) {
- element = $(element);
- var position = element.getStyle('position');
- if (position !== 'static') return proceed(element);
- // Trigger hasLayout on the offset parent so that IE6 reports
- // accurate offsetTop and offsetLeft values for position: fixed.
- var offsetParent = element.getOffsetParent();
- if (offsetParent && offsetParent.getStyle('position') === 'fixed')
- offsetParent.setStyle({ zoom: 1 });
- element.setStyle({ position: 'relative' });
- var value = proceed(element);
- element.setStyle({ position: position });
- return value;
- }
- );
- });
-
- Element.Methods.getStyle = function(element, style) {
- element = $(element);
- style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
- var value = element.style[style];
- if (!value && element.currentStyle) value = element.currentStyle[style];
-
- if (style == 'opacity') {
- if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
- if (value[1]) return parseFloat(value[1]) / 100;
- return 1.0;
- }
-
- if (value == 'auto') {
- if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
- return element['offset' + style.capitalize()] + 'px';
- return null;
- }
- return value;
- };
-
- Element.Methods.setOpacity = function(element, value) {
- function stripAlpha(filter){
- return filter.replace(/alpha\([^\)]*\)/gi,'');
- }
- element = $(element);
- var currentStyle = element.currentStyle;
- if ((currentStyle && !currentStyle.hasLayout) ||
- (!currentStyle && element.style.zoom == 'normal'))
- element.style.zoom = 1;
-
- var filter = element.getStyle('filter'), style = element.style;
- if (value == 1 || value === '') {
- (filter = stripAlpha(filter)) ?
- style.filter = filter : style.removeAttribute('filter');
- return element;
- } else if (value < 0.00001) value = 0;
- style.filter = stripAlpha(filter) +
- 'alpha(opacity=' + (value * 100) + ')';
- return element;
- };
-
- Element._attributeTranslations = {
- read: {
- names: {
- 'class': 'className',
- 'for': 'htmlFor'
- },
- values: {
- _getAttr: function(element, attribute) {
- return element.getAttribute(attribute, 2);
- },
- _getAttrNode: function(element, attribute) {
- var node = element.getAttributeNode(attribute);
- return node ? node.value : "";
- },
- _getEv: function(element, attribute) {
- attribute = element.getAttribute(attribute);
- return attribute ? attribute.toString().slice(23, -2) : null;
- },
- _flag: function(element, attribute) {
- return $(element).hasAttribute(attribute) ? attribute : null;
- },
- style: function(element) {
- return element.style.cssText.toLowerCase();
- },
- title: function(element) {
- return element.title;
- }
- }
- }
- };
-
- Element._attributeTranslations.write = {
- names: Object.extend({
- cellpadding: 'cellPadding',
- cellspacing: 'cellSpacing'
- }, Element._attributeTranslations.read.names),
- values: {
- checked: function(element, value) {
- element.checked = !!value;
- },
-
- style: function(element, value) {
- element.style.cssText = value ? value : '';
- }
- }
- };
-
- Element._attributeTranslations.has = {};
-
- $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
- 'encType maxLength readOnly longDesc').each(function(attr) {
- Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
- Element._attributeTranslations.has[attr.toLowerCase()] = attr;
- });
-
- (function(v) {
- Object.extend(v, {
- href: v._getAttr,
- src: v._getAttr,
- type: v._getAttr,
- action: v._getAttrNode,
- disabled: v._flag,
- checked: v._flag,
- readonly: v._flag,
- multiple: v._flag,
- onload: v._getEv,
- onunload: v._getEv,
- onclick: v._getEv,
- ondblclick: v._getEv,
- onmousedown: v._getEv,
- onmouseup: v._getEv,
- onmouseover: v._getEv,
- onmousemove: v._getEv,
- onmouseout: v._getEv,
- onfocus: v._getEv,
- onblur: v._getEv,
- onkeypress: v._getEv,
- onkeydown: v._getEv,
- onkeyup: v._getEv,
- onsubmit: v._getEv,
- onreset: v._getEv,
- onselect: v._getEv,
- onchange: v._getEv
- });
- })(Element._attributeTranslations.read.values);
-}
-
-else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
- Element.Methods.setOpacity = function(element, value) {
- element = $(element);
- element.style.opacity = (value == 1) ? 0.999999 :
- (value === '') ? '' : (value < 0.00001) ? 0 : value;
- return element;
- };
-}
-
-else if (Prototype.Browser.WebKit) {
- Element.Methods.setOpacity = function(element, value) {
- element = $(element);
- element.style.opacity = (value == 1 || value === '') ? '' :
- (value < 0.00001) ? 0 : value;
-
- if (value == 1)
- if(element.tagName == 'IMG' && element.width) {
- element.width++; element.width--;
- } else try {
- var n = document.createTextNode(' ');
- element.appendChild(n);
- element.removeChild(n);
- } catch (e) { }
-
- return element;
- };
-
- // Safari returns margins on body which is incorrect if the child is absolutely
- // positioned. For performance reasons, redefine Element#cumulativeOffset for
- // KHTML/WebKit only.
- Element.Methods.cumulativeOffset = function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- if (element.offsetParent == document.body)
- if (Element.getStyle(element, 'position') == 'absolute') break;
-
- element = element.offsetParent;
- } while (element);
-
- return Element._returnOffset(valueL, valueT);
- };
-}
-
-if (Prototype.Browser.IE || Prototype.Browser.Opera) {
- // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
- Element.Methods.update = function(element, content) {
- element = $(element);
-
- if (content && content.toElement) content = content.toElement();
- if (Object.isElement(content)) return element.update().insert(content);
-
- content = Object.toHTML(content);
- var tagName = element.tagName.toUpperCase();
-
- if (tagName in Element._insertionTranslations.tags) {
- $A(element.childNodes).each(function(node) { element.removeChild(node) });
- Element._getContentFromAnonymousElement(tagName, content.stripScripts())
- .each(function(node) { element.appendChild(node) });
- }
- else element.innerHTML = content.stripScripts();
-
- content.evalScripts.bind(content).defer();
- return element;
- };
-}
-
-if ('outerHTML' in document.createElement('div')) {
- Element.Methods.replace = function(element, content) {
- element = $(element);
-
- if (content && content.toElement) content = content.toElement();
- if (Object.isElement(content)) {
- element.parentNode.replaceChild(content, element);
- return element;
- }
-
- content = Object.toHTML(content);
- var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
-
- if (Element._insertionTranslations.tags[tagName]) {
- var nextSibling = element.next();
- var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
- parent.removeChild(element);
- if (nextSibling)
- fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
- else
- fragments.each(function(node) { parent.appendChild(node) });
- }
- else element.outerHTML = content.stripScripts();
-
- content.evalScripts.bind(content).defer();
- return element;
- };
-}
-
-Element._returnOffset = function(l, t) {
- var result = [l, t];
- result.left = l;
- result.top = t;
- return result;
-};
-
-Element._getContentFromAnonymousElement = function(tagName, html) {
- var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
- if (t) {
- div.innerHTML = t[0] + html + t[1];
- t[2].times(function() { div = div.firstChild });
- } else div.innerHTML = html;
- return $A(div.childNodes);
-};
-
-Element._insertionTranslations = {
- before: function(element, node) {
- element.parentNode.insertBefore(node, element);
- },
- top: function(element, node) {
- element.insertBefore(node, element.firstChild);
- },
- bottom: function(element, node) {
- element.appendChild(node);
- },
- after: function(element, node) {
- element.parentNode.insertBefore(node, element.nextSibling);
- },
- tags: {
- TABLE: ['<table>', '</table>', 1],
- TBODY: ['<table><tbody>', '</tbody></table>', 2],
- TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
- TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
- SELECT: ['<select>', '</select>', 1]
- }
-};
-
-(function() {
- Object.extend(this.tags, {
- THEAD: this.tags.TBODY,
- TFOOT: this.tags.TBODY,
- TH: this.tags.TD
- });
-}).call(Element._insertionTranslations);
-
-Element.Methods.Simulated = {
- hasAttribute: function(element, attribute) {
- attribute = Element._attributeTranslations.has[attribute] || attribute;
- var node = $(element).getAttributeNode(attribute);
- return node && node.specified;
- }
-};
-
-Element.Methods.ByTag = { };
-
-Object.extend(Element, Element.Methods);
-
-if (!Prototype.BrowserFeatures.ElementExtensions &&
- document.createElement('div').__proto__) {
- window.HTMLElement = { };
- window.HTMLElement.prototype = document.createElement('div').__proto__;
- Prototype.BrowserFeatures.ElementExtensions = true;
-}
-
-Element.extend = (function() {
- if (Prototype.BrowserFeatures.SpecificElementExtensions)
- return Prototype.K;
-
- var Methods = { }, ByTag = Element.Methods.ByTag;
-
- var extend = Object.extend(function(element) {
- if (!element || element._extendedByPrototype ||
- element.nodeType != 1 || element == window) return element;
-
- var methods = Object.clone(Methods),
- tagName = element.tagName, property, value;
-
- // extend methods for specific tags
- if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
-
- for (property in methods) {
- value = methods[property];
- if (Object.isFunction(value) && !(property in element))
- element[property] = value.methodize();
- }
-
- element._extendedByPrototype = Prototype.emptyFunction;
- return element;
-
- }, {
- refresh: function() {
- // extend methods for all tags (Safari doesn't need this)
- if (!Prototype.BrowserFeatures.ElementExtensions) {
- Object.extend(Methods, Element.Methods);
- Object.extend(Methods, Element.Methods.Simulated);
- }
- }
- });
-
- extend.refresh();
- return extend;
-})();
-
-Element.hasAttribute = function(element, attribute) {
- if (element.hasAttribute) return element.hasAttribute(attribute);
- return Element.Methods.Simulated.hasAttribute(element, attribute);
-};
-
-Element.addMethods = function(methods) {
- var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
-
- if (!methods) {
- Object.extend(Form, Form.Methods);
- Object.extend(Form.Element, Form.Element.Methods);
- Object.extend(Element.Methods.ByTag, {
- "FORM": Object.clone(Form.Methods),
- "INPUT": Object.clone(Form.Element.Methods),
- "SELECT": Object.clone(Form.Element.Methods),
- "TEXTAREA": Object.clone(Form.Element.Methods)
- });
- }
-
- if (arguments.length == 2) {
- var tagName = methods;
- methods = arguments[1];
- }
-
- if (!tagName) Object.extend(Element.Methods, methods || { });
- else {
- if (Object.isArray(tagName)) tagName.each(extend);
- else extend(tagName);
- }
-
- function extend(tagName) {
- tagName = tagName.toUpperCase();
- if (!Element.Methods.ByTag[tagName])
- Element.Methods.ByTag[tagName] = { };
- Object.extend(Element.Methods.ByTag[tagName], methods);
- }
-
- function copy(methods, destination, onlyIfAbsent) {
- onlyIfAbsent = onlyIfAbsent || false;
- for (var property in methods) {
- var value = methods[property];
- if (!Object.isFunction(value)) continue;
- if (!onlyIfAbsent || !(property in destination))
- destination[property] = value.methodize();
- }
- }
-
- function findDOMClass(tagName) {
- var klass;
- var trans = {
- "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
- "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
- "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
- "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
- "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
- "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
- "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
- "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
- "FrameSet", "IFRAME": "IFrame"
- };
- if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
- if (window[klass]) return window[klass];
- klass = 'HTML' + tagName + 'Element';
- if (window[klass]) return window[klass];
- klass = 'HTML' + tagName.capitalize() + 'Element';
- if (window[klass]) return window[klass];
-
- window[klass] = { };
- window[klass].prototype = document.createElement(tagName).__proto__;
- return window[klass];
- }
-
- if (F.ElementExtensions) {
- copy(Element.Methods, HTMLElement.prototype);
- copy(Element.Methods.Simulated, HTMLElement.prototype, true);
- }
-
- if (F.SpecificElementExtensions) {
- for (var tag in Element.Methods.ByTag) {
- var klass = findDOMClass(tag);
- if (Object.isUndefined(klass)) continue;
- copy(T[tag], klass.prototype);
- }
- }
-
- Object.extend(Element, Element.Methods);
- delete Element.ByTag;
-
- if (Element.extend.refresh) Element.extend.refresh();
- Element.cache = { };
-};
-
-document.viewport = {
- getDimensions: function() {
- var dimensions = { };
- var B = Prototype.Browser;
- $w('width height').each(function(d) {
- var D = d.capitalize();
- dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
- (B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
- });
- return dimensions;
- },
-
- getWidth: function() {
- return this.getDimensions().width;
- },
-
- getHeight: function() {
- return this.getDimensions().height;
- },
-
- getScrollOffsets: function() {
- return Element._returnOffset(
- window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
- window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
- }
-};
-/* Portions of the Selector class are derived from Jack Slocum’s DomQuery,
- * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
- * license. Please see http://www.yui-ext.com/ for more information. */
-
-var Selector = Class.create({
- initialize: function(expression) {
- this.expression = expression.strip();
- this.compileMatcher();
- },
-
- shouldUseXPath: function() {
- if (!Prototype.BrowserFeatures.XPath) return false;
-
- var e = this.expression;
-
- // Safari 3 chokes on :*-of-type and :empty
- if (Prototype.Browser.WebKit &&
- (e.include("-of-type") || e.include(":empty")))
- return false;
-
- // XPath can't do namespaced attributes, nor can it read
- // the "checked" property from DOM nodes
- if ((/(\[[\w-]*?:|:checked)/).test(this.expression))
- return false;
-
- return true;
- },
-
- compileMatcher: function() {
- if (this.shouldUseXPath())
- return this.compileXPathMatcher();
-
- var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
- c = Selector.criteria, le, p, m;
-
- if (Selector._cache[e]) {
- this.matcher = Selector._cache[e];
- return;
- }
-
- this.matcher = ["this.matcher = function(root) {",
- "var r = root, h = Selector.handlers, c = false, n;"];
-
- while (e && le != e && (/\S/).test(e)) {
- le = e;
- for (var i in ps) {
- p = ps[i];
- if (m = e.match(p)) {
- this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
- new Template(c[i]).evaluate(m));
- e = e.replace(m[0], '');
- break;
- }
- }
- }
-
- this.matcher.push("return h.unique(n);\n}");
- eval(this.matcher.join('\n'));
- Selector._cache[this.expression] = this.matcher;
- },
-
- compileXPathMatcher: function() {
- var e = this.expression, ps = Selector.patterns,
- x = Selector.xpath, le, m;
-
- if (Selector._cache[e]) {
- this.xpath = Selector._cache[e]; return;
- }
-
- this.matcher = ['.//*'];
- while (e && le != e && (/\S/).test(e)) {
- le = e;
- for (var i in ps) {
- if (m = e.match(ps[i])) {
- this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
- new Template(x[i]).evaluate(m));
- e = e.replace(m[0], '');
- break;
- }
- }
- }
-
- this.xpath = this.matcher.join('');
- Selector._cache[this.expression] = this.xpath;
- },
-
- findElements: function(root) {
- root = root || document;
- if (this.xpath) return document._getElementsByXPath(this.xpath, root);
- return this.matcher(root);
- },
-
- match: function(element) {
- this.tokens = [];
-
- var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
- var le, p, m;
-
- while (e && le !== e && (/\S/).test(e)) {
- le = e;
- for (var i in ps) {
- p = ps[i];
- if (m = e.match(p)) {
- // use the Selector.assertions methods unless the selector
- // is too complex.
- if (as[i]) {
- this.tokens.push([i, Object.clone(m)]);
- e = e.replace(m[0], '');
- } else {
- // reluctantly do a document-wide search
- // and look for a match in the array
- return this.findElements(document).include(element);
- }
- }
- }
- }
-
- var match = true, name, matches;
- for (var i = 0, token; token = this.tokens[i]; i++) {
- name = token[0], matches = token[1];
- if (!Selector.assertions[name](element, matches)) {
- match = false; break;
- }
- }
-
- return match;
- },
-
- toString: function() {
- return this.expression;
- },
-
- inspect: function() {
- return "#<Selector:" + this.expression.inspect() + ">";
- }
-});
-
-Object.extend(Selector, {
- _cache: { },
-
- xpath: {
- descendant: "//*",
- child: "/*",
- adjacent: "/following-sibling::*[1]",
- laterSibling: '/following-sibling::*',
- tagName: function(m) {
- if (m[1] == '*') return '';
- return "[local-name()='" + m[1].toLowerCase() +
- "' or local-name()='" + m[1].toUpperCase() + "']";
- },
- className: "[contains(concat(' ', @class, ' '), ' #{1} ')]",
- id: "[@id='#{1}']",
- attrPresence: function(m) {
- m[1] = m[1].toLowerCase();
- return new Template("[@#{1}]").evaluate(m);
- },
- attr: function(m) {
- m[1] = m[1].toLowerCase();
- m[3] = m[5] || m[6];
- return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
- },
- pseudo: function(m) {
- var h = Selector.xpath.pseudos[m[1]];
- if (!h) return '';
- if (Object.isFunction(h)) return h(m);
- return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
- },
- operators: {
- '=': "[@#{1}='#{3}']",
- '!=': "[@#{1}!='#{3}']",
- '^=': "[starts-with(@#{1}, '#{3}')]",
- '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
- '*=': "[contains(@#{1}, '#{3}')]",
- '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
- '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
- },
- pseudos: {
- 'first-child': '[not(preceding-sibling::*)]',
- 'last-child': '[not(following-sibling::*)]',
- 'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
- 'empty': "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
- 'checked': "[@checked]",
- 'disabled': "[@disabled]",
- 'enabled': "[not(@disabled)]",
- 'not': function(m) {
- var e = m[6], p = Selector.patterns,
- x = Selector.xpath, le, v;
-
- var exclusion = [];
- while (e && le != e && (/\S/).test(e)) {
- le = e;
- for (var i in p) {
- if (m = e.match(p[i])) {
- v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
- exclusion.push("(" + v.substring(1, v.length - 1) + ")");
- e = e.replace(m[0], '');
- break;
- }
- }
- }
- return "[not(" + exclusion.join(" and ") + ")]";
- },
- 'nth-child': function(m) {
- return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
- },
- 'nth-last-child': function(m) {
- return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
- },
- 'nth-of-type': function(m) {
- return Selector.xpath.pseudos.nth("position() ", m);
- },
- 'nth-last-of-type': function(m) {
- return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
- },
- 'first-of-type': function(m) {
- m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
- },
- 'last-of-type': function(m) {
- m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
- },
- 'only-of-type': function(m) {
- var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
- },
- nth: function(fragment, m) {
- var mm, formula = m[6], predicate;
- if (formula == 'even') formula = '2n+0';
- if (formula == 'odd') formula = '2n+1';
- if (mm = formula.match(/^(\d+)$/)) // digit only
- return '[' + fragment + "= " + mm[1] + ']';
- if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
- if (mm[1] == "-") mm[1] = -1;
- var a = mm[1] ? Number(mm[1]) : 1;
- var b = mm[2] ? Number(mm[2]) : 0;
- predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
- "((#{fragment} - #{b}) div #{a} >= 0)]";
- return new Template(predicate).evaluate({
- fragment: fragment, a: a, b: b });
- }
- }
- }
- },
-
- criteria: {
- tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;',
- className: 'n = h.className(n, r, "#{1}", c); c = false;',
- id: 'n = h.id(n, r, "#{1}", c); c = false;',
- attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
- attr: function(m) {
- m[3] = (m[5] || m[6]);
- return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
- },
- pseudo: function(m) {
- if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
- return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
- },
- descendant: 'c = "descendant";',
- child: 'c = "child";',
- adjacent: 'c = "adjacent";',
- laterSibling: 'c = "laterSibling";'
- },
-
- patterns: {
- // combinators must be listed first
- // (and descendant needs to be last combinator)
- laterSibling: /^\s*~\s*/,
- child: /^\s*>\s*/,
- adjacent: /^\s*\+\s*/,
- descendant: /^\s/,
-
- // selectors follow
- tagName: /^\s*(\*|[\w\-]+)(\b|$)?/,
- id: /^#([\w\-\*]+)(\b|$)/,
- className: /^\.([\w\-\*]+)(\b|$)/,
- pseudo:
-/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
- attrPresence: /^\[([\w]+)\]/,
- attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
- },
-
- // for Selector.match and Element#match
- assertions: {
- tagName: function(element, matches) {
- return matches[1].toUpperCase() == element.tagName.toUpperCase();
- },
-
- className: function(element, matches) {
- return Element.hasClassName(element, matches[1]);
- },
-
- id: function(element, matches) {
- return element.id === matches[1];
- },
-
- attrPresence: function(element, matches) {
- return Element.hasAttribute(element, matches[1]);
- },
-
- attr: function(element, matches) {
- var nodeValue = Element.readAttribute(element, matches[1]);
- return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
- }
- },
-
- handlers: {
- // UTILITY FUNCTIONS
- // joins two collections
- concat: function(a, b) {
- for (var i = 0, node; node = b[i]; i++)
- a.push(node);
- return a;
- },
-
- // marks an array of nodes for counting
- mark: function(nodes) {
- var _true = Prototype.emptyFunction;
- for (var i = 0, node; node = nodes[i]; i++)
- node._countedByPrototype = _true;
- return nodes;
- },
-
- unmark: function(nodes) {
- for (var i = 0, node; node = nodes[i]; i++)
- node._countedByPrototype = undefined;
- return nodes;
- },
-
- // mark each child node with its position (for nth calls)
- // "ofType" flag indicates whether we're indexing for nth-of-type
- // rather than nth-child
- index: function(parentNode, reverse, ofType) {
- parentNode._countedByPrototype = Prototype.emptyFunction;
- if (reverse) {
- for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
- var node = nodes[i];
- if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
- }
- } else {
- for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
- if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
- }
- },
-
- // filters out duplicates and extends all nodes
- unique: function(nodes) {
- if (nodes.length == 0) return nodes;
- var results = [], n;
- for (var i = 0, l = nodes.length; i < l; i++)
- if (!(n = nodes[i])._countedByPrototype) {
- n._countedByPrototype = Prototype.emptyFunction;
- results.push(Element.extend(n));
- }
- return Selector.handlers.unmark(results);
- },
-
- // COMBINATOR FUNCTIONS
- descendant: function(nodes) {
- var h = Selector.handlers;
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- h.concat(results, node.getElementsByTagName('*'));
- return results;
- },
-
- child: function(nodes) {
- var h = Selector.handlers;
- for (var i = 0, results = [], node; node = nodes[i]; i++) {
- for (var j = 0, child; child = node.childNodes[j]; j++)
- if (child.nodeType == 1 && child.tagName != '!') results.push(child);
- }
- return results;
- },
-
- adjacent: function(nodes) {
- for (var i = 0, results = [], node; node = nodes[i]; i++) {
- var next = this.nextElementSibling(node);
- if (next) results.push(next);
- }
- return results;
- },
-
- laterSibling: function(nodes) {
- var h = Selector.handlers;
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- h.concat(results, Element.nextSiblings(node));
- return results;
- },
-
- nextElementSibling: function(node) {
- while (node = node.nextSibling)
- if (node.nodeType == 1) return node;
- return null;
- },
-
- previousElementSibling: function(node) {
- while (node = node.previousSibling)
- if (node.nodeType == 1) return node;
- return null;
- },
-
- // TOKEN FUNCTIONS
- tagName: function(nodes, root, tagName, combinator) {
- var uTagName = tagName.toUpperCase();
- var results = [], h = Selector.handlers;
- if (nodes) {
- if (combinator) {
- // fastlane for ordinary descendant combinators
- if (combinator == "descendant") {
- for (var i = 0, node; node = nodes[i]; i++)
- h.concat(results, node.getElementsByTagName(tagName));
- return results;
- } else nodes = this[combinator](nodes);
- if (tagName == "*") return nodes;
- }
- for (var i = 0, node; node = nodes[i]; i++)
- if (node.tagName.toUpperCase() === uTagName) results.push(node);
- return results;
- } else return root.getElementsByTagName(tagName);
- },
-
- id: function(nodes, root, id, combinator) {
- var targetNode = $(id), h = Selector.handlers;
- if (!targetNode) return [];
- if (!nodes && root == document) return [targetNode];
- if (nodes) {
- if (combinator) {
- if (combinator == 'child') {
- for (var i = 0, node; node = nodes[i]; i++)
- if (targetNode.parentNode == node) return [targetNode];
- } else if (combinator == 'descendant') {
- for (var i = 0, node; node = nodes[i]; i++)
- if (Element.descendantOf(targetNode, node)) return [targetNode];
- } else if (combinator == 'adjacent') {
- for (var i = 0, node; node = nodes[i]; i++)
- if (Selector.handlers.previousElementSibling(targetNode) == node)
- return [targetNode];
- } else nodes = h[combinator](nodes);
- }
- for (var i = 0, node; node = nodes[i]; i++)
- if (node == targetNode) return [targetNode];
- return [];
- }
- return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
- },
-
- className: function(nodes, root, className, combinator) {
- if (nodes && combinator) nodes = this[combinator](nodes);
- return Selector.handlers.byClassName(nodes, root, className);
- },
-
- byClassName: function(nodes, root, className) {
- if (!nodes) nodes = Selector.handlers.descendant([root]);
- var needle = ' ' + className + ' ';
- for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
- nodeClassName = node.className;
- if (nodeClassName.length == 0) continue;
- if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
- results.push(node);
- }
- return results;
- },
-
- attrPresence: function(nodes, root, attr, combinator) {
- if (!nodes) nodes = root.getElementsByTagName("*");
- if (nodes && combinator) nodes = this[combinator](nodes);
- var results = [];
- for (var i = 0, node; node = nodes[i]; i++)
- if (Element.hasAttribute(node, attr)) results.push(node);
- return results;
- },
-
- attr: function(nodes, root, attr, value, operator, combinator) {
- if (!nodes) nodes = root.getElementsByTagName("*");
- if (nodes && combinator) nodes = this[combinator](nodes);
- var handler = Selector.operators[operator], results = [];
- for (var i = 0, node; node = nodes[i]; i++) {
- var nodeValue = Element.readAttribute(node, attr);
- if (nodeValue === null) continue;
- if (handler(nodeValue, value)) results.push(node);
- }
- return results;
- },
-
- pseudo: function(nodes, name, value, root, combinator) {
- if (nodes && combinator) nodes = this[combinator](nodes);
- if (!nodes) nodes = root.getElementsByTagName("*");
- return Selector.pseudos[name](nodes, value, root);
- }
- },
-
- pseudos: {
- 'first-child': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++) {
- if (Selector.handlers.previousElementSibling(node)) continue;
- results.push(node);
- }
- return results;
- },
- 'last-child': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++) {
- if (Selector.handlers.nextElementSibling(node)) continue;
- results.push(node);
- }
- return results;
- },
- 'only-child': function(nodes, value, root) {
- var h = Selector.handlers;
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
- results.push(node);
- return results;
- },
- 'nth-child': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, formula, root);
- },
- 'nth-last-child': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, formula, root, true);
- },
- 'nth-of-type': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, formula, root, false, true);
- },
- 'nth-last-of-type': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, formula, root, true, true);
- },
- 'first-of-type': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, "1", root, false, true);
- },
- 'last-of-type': function(nodes, formula, root) {
- return Selector.pseudos.nth(nodes, "1", root, true, true);
- },
- 'only-of-type': function(nodes, formula, root) {
- var p = Selector.pseudos;
- return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
- },
-
- // handles the an+b logic
- getIndices: function(a, b, total) {
- if (a == 0) return b > 0 ? [b] : [];
- return $R(1, total).inject([], function(memo, i) {
- if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
- return memo;
- });
- },
-
- // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
- nth: function(nodes, formula, root, reverse, ofType) {
- if (nodes.length == 0) return [];
- if (formula == 'even') formula = '2n+0';
- if (formula == 'odd') formula = '2n+1';
- var h = Selector.handlers, results = [], indexed = [], m;
- h.mark(nodes);
- for (var i = 0, node; node = nodes[i]; i++) {
- if (!node.parentNode._countedByPrototype) {
- h.index(node.parentNode, reverse, ofType);
- indexed.push(node.parentNode);
- }
- }
- if (formula.match(/^\d+$/)) { // just a number
- formula = Number(formula);
- for (var i = 0, node; node = nodes[i]; i++)
- if (node.nodeIndex == formula) results.push(node);
- } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
- if (m[1] == "-") m[1] = -1;
- var a = m[1] ? Number(m[1]) : 1;
- var b = m[2] ? Number(m[2]) : 0;
- var indices = Selector.pseudos.getIndices(a, b, nodes.length);
- for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
- for (var j = 0; j < l; j++)
- if (node.nodeIndex == indices[j]) results.push(node);
- }
- }
- h.unmark(nodes);
- h.unmark(indexed);
- return results;
- },
-
- 'empty': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++) {
- // IE treats comments as element nodes
- if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
- results.push(node);
- }
- return results;
- },
-
- 'not': function(nodes, selector, root) {
- var h = Selector.handlers, selectorType, m;
- var exclusions = new Selector(selector).findElements(root);
- h.mark(exclusions);
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- if (!node._countedByPrototype) results.push(node);
- h.unmark(exclusions);
- return results;
- },
-
- 'enabled': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- if (!node.disabled) results.push(node);
- return results;
- },
-
- 'disabled': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- if (node.disabled) results.push(node);
- return results;
- },
-
- 'checked': function(nodes, value, root) {
- for (var i = 0, results = [], node; node = nodes[i]; i++)
- if (node.checked) results.push(node);
- return results;
- }
- },
-
- operators: {
- '=': function(nv, v) { return nv == v; },
- '!=': function(nv, v) { return nv != v; },
- '^=': function(nv, v) { return nv.startsWith(v); },
- '$=': function(nv, v) { return nv.endsWith(v); },
- '*=': function(nv, v) { return nv.include(v); },
- '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
- '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
- },
-
- split: function(expression) {
- var expressions = [];
- expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
- expressions.push(m[1].strip());
- });
- return expressions;
- },
-
- matchElements: function(elements, expression) {
- var matches = $$(expression), h = Selector.handlers;
- h.mark(matches);
- for (var i = 0, results = [], element; element = elements[i]; i++)
- if (element._countedByPrototype) results.push(element);
- h.unmark(matches);
- return results;
- },
-
- findElement: function(elements, expression, index) {
- if (Object.isNumber(expression)) {
- index = expression; expression = false;
- }
- return Selector.matchElements(elements, expression || '*')[index || 0];
- },
-
- findChildElements: function(element, expressions) {
- expressions = Selector.split(expressions.join(','));
- var results = [], h = Selector.handlers;
- for (var i = 0, l = expressions.length, selector; i < l; i++) {
- selector = new Selector(expressions[i].strip());
- h.concat(results, selector.findElements(element));
- }
- return (l > 1) ? h.unique(results) : results;
- }
-});
-
-if (Prototype.Browser.IE) {
- Object.extend(Selector.handlers, {
- // IE returns comment nodes on getElementsByTagName("*").
- // Filter them out.
- concat: function(a, b) {
- for (var i = 0, node; node = b[i]; i++)
- if (node.tagName !== "!") a.push(node);
- return a;
- },
-
- // IE improperly serializes _countedByPrototype in (inner|outer)HTML.
- unmark: function(nodes) {
- for (var i = 0, node; node = nodes[i]; i++)
- node.removeAttribute('_countedByPrototype');
- return nodes;
- }
- });
-}
-
-function $$() {
- return Selector.findChildElements(document, $A(arguments));
-}
-var Form = {
- reset: function(form) {
- $(form).reset();
- return form;
- },
-
- serializeElements: function(elements, options) {
- if (typeof options != 'object') options = { hash: !!options };
- else if (Object.isUndefined(options.hash)) options.hash = true;
- var key, value, submitted = false, submit = options.submit;
-
- var data = elements.inject({ }, function(result, element) {
- if (!element.disabled && element.name) {
- key = element.name; value = $(element).getValue();
- if (value != null && (element.type != 'submit' || (!submitted &&
- submit !== false && (!submit || key == submit) && (submitted = true)))) {
- if (key in result) {
- // a key is already present; construct an array of values
- if (!Object.isArray(result[key])) result[key] = [result[key]];
- result[key].push(value);
- }
- else result[key] = value;
- }
- }
- return result;
- });
-
- return options.hash ? data : Object.toQueryString(data);
- }
-};
-
-Form.Methods = {
- serialize: function(form, options) {
- return Form.serializeElements(Form.getElements(form), options);
- },
-
- getElements: function(form) {
- return $A($(form).getElementsByTagName('*')).inject([],
- function(elements, child) {
- if (Form.Element.Serializers[child.tagName.toLowerCase()])
- elements.push(Element.extend(child));
- return elements;
- }
- );
- },
-
- getInputs: function(form, typeName, name) {
- form = $(form);
- var inputs = form.getElementsByTagName('input');
-
- if (!typeName && !name) return $A(inputs).map(Element.extend);
-
- for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
- var input = inputs[i];
- if ((typeName && input.type != typeName) || (name && input.name != name))
- continue;
- matchingInputs.push(Element.extend(input));
- }
-
- return matchingInputs;
- },
-
- disable: function(form) {
- form = $(form);
- Form.getElements(form).invoke('disable');
- return form;
- },
-
- enable: function(form) {
- form = $(form);
- Form.getElements(form).invoke('enable');
- return form;
- },
-
- findFirstElement: function(form) {
- var elements = $(form).getElements().findAll(function(element) {
- return 'hidden' != element.type && !element.disabled;
- });
- var firstByIndex = elements.findAll(function(element) {
- return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
- }).sortBy(function(element) { return element.tabIndex }).first();
-
- return firstByIndex ? firstByIndex : elements.find(function(element) {
- return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
- });
- },
-
- focusFirstElement: function(form) {
- form = $(form);
- form.findFirstElement().activate();
- return form;
- },
-
- request: function(form, options) {
- form = $(form), options = Object.clone(options || { });
-
- var params = options.parameters, action = form.readAttribute('action') || '';
- if (action.blank()) action = window.location.href;
- options.parameters = form.serialize(true);
-
- if (params) {
- if (Object.isString(params)) params = params.toQueryParams();
- Object.extend(options.parameters, params);
- }
-
- if (form.hasAttribute('method') && !options.method)
- options.method = form.method;
-
- return new Ajax.Request(action, options);
- }
-};
-
-/*--------------------------------------------------------------------------*/
-
-Form.Element = {
- focus: function(element) {
- $(element).focus();
- return element;
- },
-
- select: function(element) {
- $(element).select();
- return element;
- }
-};
-
-Form.Element.Methods = {
- serialize: function(element) {
- element = $(element);
- if (!element.disabled && element.name) {
- var value = element.getValue();
- if (value != undefined) {
- var pair = { };
- pair[element.name] = value;
- return Object.toQueryString(pair);
- }
- }
- return '';
- },
-
- getValue: function(element) {
- element = $(element);
- var method = element.tagName.toLowerCase();
- return Form.Element.Serializers[method](element);
- },
-
- setValue: function(element, value) {
- element = $(element);
- var method = element.tagName.toLowerCase();
- Form.Element.Serializers[method](element, value);
- return element;
- },
-
- clear: function(element) {
- $(element).value = '';
- return element;
- },
-
- present: function(element) {
- return $(element).value != '';
- },
-
- activate: function(element) {
- element = $(element);
- try {
- element.focus();
- if (element.select && (element.tagName.toLowerCase() != 'input' ||
- !['button', 'reset', 'submit'].include(element.type)))
- element.select();
- } catch (e) { }
- return element;
- },
-
- disable: function(element) {
- element = $(element);
- element.blur();
- element.disabled = true;
- return element;
- },
-
- enable: function(element) {
- element = $(element);
- element.disabled = false;
- return element;
- }
-};
-
-/*--------------------------------------------------------------------------*/
-
-var Field = Form.Element;
-var $F = Form.Element.Methods.getValue;
-
-/*--------------------------------------------------------------------------*/
-
-Form.Element.Serializers = {
- input: function(element, value) {
- switch (element.type.toLowerCase()) {
- case 'checkbox':
- case 'radio':
- return Form.Element.Serializers.inputSelector(element, value);
- default:
- return Form.Element.Serializers.textarea(element, value);
- }
- },
-
- inputSelector: function(element, value) {
- if (Object.isUndefined(value)) return element.checked ? element.value : null;
- else element.checked = !!value;
- },
-
- textarea: function(element, value) {
- if (Object.isUndefined(value)) return element.value;
- else element.value = value;
- },
-
- select: function(element, index) {
- if (Object.isUndefined(index))
- return this[element.type == 'select-one' ?
- 'selectOne' : 'selectMany'](element);
- else {
- var opt, value, single = !Object.isArray(index);
- for (var i = 0, length = element.length; i < length; i++) {
- opt = element.options[i];
- value = this.optionValue(opt);
- if (single) {
- if (value == index) {
- opt.selected = true;
- return;
- }
- }
- else opt.selected = index.include(value);
- }
- }
- },
-
- selectOne: function(element) {
- var index = element.selectedIndex;
- return index >= 0 ? this.optionValue(element.options[index]) : null;
- },
-
- selectMany: function(element) {
- var values, length = element.length;
- if (!length) return null;
-
- for (var i = 0, values = []; i < length; i++) {
- var opt = element.options[i];
- if (opt.selected) values.push(this.optionValue(opt));
- }
- return values;
- },
-
- optionValue: function(opt) {
- // extend element because hasAttribute may not be native
- return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
- }
-};
-
-/*--------------------------------------------------------------------------*/
-
-Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
- initialize: function($super, element, frequency, callback) {
- $super(callback, frequency);
- this.element = $(element);
- this.lastValue = this.getValue();
- },
-
- execute: function() {
- var value = this.getValue();
- if (Object.isString(this.lastValue) && Object.isString(value) ?
- this.lastValue != value : String(this.lastValue) != String(value)) {
- this.callback(this.element, value);
- this.lastValue = value;
- }
- }
-});
-
-Form.Element.Observer = Class.create(Abstract.TimedObserver, {
- getValue: function() {
- return Form.Element.getValue(this.element);
- }
-});
-
-Form.Observer = Class.create(Abstract.TimedObserver, {
- getValue: function() {
- return Form.serialize(this.element);
- }
-});
-
-/*--------------------------------------------------------------------------*/
-
-Abstract.EventObserver = Class.create({
- initialize: function(element, callback) {
- this.element = $(element);
- this.callback = callback;
-
- this.lastValue = this.getValue();
- if (this.element.tagName.toLowerCase() == 'form')
- this.registerFormCallbacks();
- else
- this.registerCallback(this.element);
- },
-
- onElementEvent: function() {
- var value = this.getValue();
- if (this.lastValue != value) {
- this.callback(this.element, value);
- this.lastValue = value;
- }
- },
-
- registerFormCallbacks: function() {
- Form.getElements(this.element).each(this.registerCallback, this);
- },
-
- registerCallback: function(element) {
- if (element.type) {
- switch (element.type.toLowerCase()) {
- case 'checkbox':
- case 'radio':
- Event.observe(element, 'click', this.onElementEvent.bind(this));
- break;
- default:
- Event.observe(element, 'change', this.onElementEvent.bind(this));
- break;
- }
- }
- }
-});
-
-Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
- getValue: function() {
- return Form.Element.getValue(this.element);
- }
-});
-
-Form.EventObserver = Class.create(Abstract.EventObserver, {
- getValue: function() {
- return Form.serialize(this.element);
- }
-});
-if (!window.Event) var Event = { };
-
-Object.extend(Event, {
- KEY_BACKSPACE: 8,
- KEY_TAB: 9,
- KEY_RETURN: 13,
- KEY_ESC: 27,
- KEY_LEFT: 37,
- KEY_UP: 38,
- KEY_RIGHT: 39,
- KEY_DOWN: 40,
- KEY_DELETE: 46,
- KEY_HOME: 36,
- KEY_END: 35,
- KEY_PAGEUP: 33,
- KEY_PAGEDOWN: 34,
- KEY_INSERT: 45,
-
- cache: { },
-
- relatedTarget: function(event) {
- var element;
- switch(event.type) {
- case 'mouseover': element = event.fromElement; break;
- case 'mouseout': element = event.toElement; break;
- default: return null;
- }
- return Element.extend(element);
- }
-});
-
-Event.Methods = (function() {
- var isButton;
-
- if (Prototype.Browser.IE) {
- var buttonMap = { 0: 1, 1: 4, 2: 2 };
- isButton = function(event, code) {
- return event.button == buttonMap[code];
- };
-
- } else if (Prototype.Browser.WebKit) {
- isButton = function(event, code) {
- switch (code) {
- case 0: return event.which == 1 && !event.metaKey;
- case 1: return event.which == 1 && event.metaKey;
- default: return false;
- }
- };
-
- } else {
- isButton = function(event, code) {
- return event.which ? (event.which === code + 1) : (event.button === code);
- };
- }
-
- return {
- isLeftClick: function(event) { return isButton(event, 0) },
- isMiddleClick: function(event) { return isButton(event, 1) },
- isRightClick: function(event) { return isButton(event, 2) },
-
- element: function(event) {
- var node = Event.extend(event).target;
- return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
- },
-
- findElement: function(event, expression) {
- var element = Event.element(event);
- if (!expression) return element;
- var elements = [element].concat(element.ancestors());
- return Selector.findElement(elements, expression, 0);
- },
-
- pointer: function(event) {
- return {
- x: event.pageX || (event.clientX +
- (document.documentElement.scrollLeft || document.body.scrollLeft)),
- y: event.pageY || (event.clientY +
- (document.documentElement.scrollTop || document.body.scrollTop))
- };
- },
-
- pointerX: function(event) { return Event.pointer(event).x },
- pointerY: function(event) { return Event.pointer(event).y },
-
- stop: function(event) {
- Event.extend(event);
- event.preventDefault();
- event.stopPropagation();
- event.stopped = true;
- }
- };
-})();
-
-Event.extend = (function() {
- var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
- m[name] = Event.Methods[name].methodize();
- return m;
- });
-
- if (Prototype.Browser.IE) {
- Object.extend(methods, {
- stopPropagation: function() { this.cancelBubble = true },
- preventDefault: function() { this.returnValue = false },
- inspect: function() { return "[object Event]" }
- });
-
- return function(event) {
- if (!event) return false;
- if (event._extendedByPrototype) return event;
-
- event._extendedByPrototype = Prototype.emptyFunction;
- var pointer = Event.pointer(event);
- Object.extend(event, {
- target: event.srcElement,
- relatedTarget: Event.relatedTarget(event),
- pageX: pointer.x,
- pageY: pointer.y
- });
- return Object.extend(event, methods);
- };
-
- } else {
- Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__;
- Object.extend(Event.prototype, methods);
- return Prototype.K;
- }
-})();
-
-Object.extend(Event, (function() {
- var cache = Event.cache;
-
- function getEventID(element) {
- if (element._prototypeEventID) return element._prototypeEventID[0];
- arguments.callee.id = arguments.callee.id || 1;
- return element._prototypeEventID = [++arguments.callee.id];
- }
-
- function getDOMEventName(eventName) {
- if (eventName && eventName.include(':')) return "dataavailable";
- return eventName;
- }
-
- function getCacheForID(id) {
- return cache[id] = cache[id] || { };
- }
-
- function getWrappersForEventName(id, eventName) {
- var c = getCacheForID(id);
- return c[eventName] = c[eventName] || [];
- }
-
- function createWrapper(element, eventName, handler) {
- var id = getEventID(element);
- var c = getWrappersForEventName(id, eventName);
- if (c.pluck("handler").include(handler)) return false;
-
- var wrapper = function(event) {
- if (!Event || !Event.extend ||
- (event.eventName && event.eventName != eventName))
- return false;
-
- Event.extend(event);
- handler.call(element, event);
- };
-
- wrapper.handler = handler;
- c.push(wrapper);
- return wrapper;
- }
-
- function findWrapper(id, eventName, handler) {
- var c = getWrappersForEventName(id, eventName);
- return c.find(function(wrapper) { return wrapper.handler == handler });
- }
-
- function destroyWrapper(id, eventName, handler) {
- var c = getCacheForID(id);
- if (!c[eventName]) return false;
- c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
- }
-
- function destroyCache() {
- for (var id in cache)
- for (var eventName in cache[id])
- cache[id][eventName] = null;
- }
-
- if (window.attachEvent) {
- window.attachEvent("onunload", destroyCache);
- }
-
- return {
- observe: function(element, eventName, handler) {
- element = $(element);
- var name = getDOMEventName(eventName);
-
- var wrapper = createWrapper(element, eventName, handler);
- if (!wrapper) return element;
-
- if (element.addEventListener) {
- element.addEventListener(name, wrapper, false);
- } else {
- element.attachEvent("on" + name, wrapper);
- }
-
- return element;
- },
-
- stopObserving: function(element, eventName, handler) {
- element = $(element);
- var id = getEventID(element), name = getDOMEventName(eventName);
-
- if (!handler && eventName) {
- getWrappersForEventName(id, eventName).each(function(wrapper) {
- element.stopObserving(eventName, wrapper.handler);
- });
- return element;
-
- } else if (!eventName) {
- Object.keys(getCacheForID(id)).each(function(eventName) {
- element.stopObserving(eventName);
- });
- return element;
- }
-
- var wrapper = findWrapper(id, eventName, handler);
- if (!wrapper) return element;
-
- if (element.removeEventListener) {
- element.removeEventListener(name, wrapper, false);
- } else {
- element.detachEvent("on" + name, wrapper);
- }
-
- destroyWrapper(id, eventName, handler);
-
- return element;
- },
-
- fire: function(element, eventName, memo) {
- element = $(element);
- if (element == document && document.createEvent && !element.dispatchEvent)
- element = document.documentElement;
-
- var event;
- if (document.createEvent) {
- event = document.createEvent("HTMLEvents");
- event.initEvent("dataavailable", true, true);
- } else {
- event = document.createEventObject();
- event.eventType = "ondataavailable";
- }
-
- event.eventName = eventName;
- event.memo = memo || { };
-
- if (document.createEvent) {
- element.dispatchEvent(event);
- } else {
- element.fireEvent(event.eventType, event);
- }
-
- return Event.extend(event);
- }
- };
-})());
-
-Object.extend(Event, Event.Methods);
-
-Element.addMethods({
- fire: Event.fire,
- observe: Event.observe,
- stopObserving: Event.stopObserving
-});
-
-Object.extend(document, {
- fire: Element.Methods.fire.methodize(),
- observe: Element.Methods.observe.methodize(),
- stopObserving: Element.Methods.stopObserving.methodize(),
- loaded: false
-});
-
-(function() {
- /* Support for the DOMContentLoaded event is based on work by Dan Webb,
- Matthias Miller, Dean Edwards and John Resig. */
-
- var timer;
-
- function fireContentLoadedEvent() {
- if (document.loaded) return;
- if (timer) window.clearInterval(timer);
- document.fire("dom:loaded");
- document.loaded = true;
- }
-
- if (document.addEventListener) {
- if (Prototype.Browser.WebKit) {
- timer = window.setInterval(function() {
- if (/loaded|complete/.test(document.readyState))
- fireContentLoadedEvent();
- }, 0);
-
- Event.observe(window, "load", fireContentLoadedEvent);
-
- } else {
- document.addEventListener("DOMContentLoaded",
- fireContentLoadedEvent, false);
- }
-
- } else {
- document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
- $("__onDOMContentLoaded").onreadystatechange = function() {
- if (this.readyState == "complete") {
- this.onreadystatechange = null;
- fireContentLoadedEvent();
- }
- };
- }
-})();
-/*------------------------------- DEPRECATED -------------------------------*/
-
-Hash.toQueryString = Object.toQueryString;
-
-var Toggle = { display: Element.toggle };
-
-Element.Methods.childOf = Element.Methods.descendantOf;
-
-var Insertion = {
- Before: function(element, content) {
- return Element.insert(element, {before:content});
- },
-
- Top: function(element, content) {
- return Element.insert(element, {top:content});
- },
-
- Bottom: function(element, content) {
- return Element.insert(element, {bottom:content});
- },
-
- After: function(element, content) {
- return Element.insert(element, {after:content});
- }
-};
-
-var $continue = new Error('"throw $continue" is deprecated, use "return" instead');
-
-// This should be moved to script.aculo.us; notice the deprecated methods
-// further below, that map to the newer Element methods.
-var Position = {
- // set to true if needed, warning: firefox performance problems
- // NOT neeeded for page scrolling, only if draggable contained in
- // scrollable elements
- includeScrollOffsets: false,
-
- // must be called before calling withinIncludingScrolloffset, every time the
- // page is scrolled
- prepare: function() {
- this.deltaX = window.pageXOffset
- || document.documentElement.scrollLeft
- || document.body.scrollLeft
- || 0;
- this.deltaY = window.pageYOffset
- || document.documentElement.scrollTop
- || document.body.scrollTop
- || 0;
- },
-
- // caches x/y coordinate pair to use with overlap
- within: function(element, x, y) {
- if (this.includeScrollOffsets)
- return this.withinIncludingScrolloffsets(element, x, y);
- this.xcomp = x;
- this.ycomp = y;
- this.offset = Element.cumulativeOffset(element);
-
- return (y >= this.offset[1] &&
- y < this.offset[1] + element.offsetHeight &&
- x >= this.offset[0] &&
- x < this.offset[0] + element.offsetWidth);
- },
-
- withinIncludingScrolloffsets: function(element, x, y) {
- var offsetcache = Element.cumulativeScrollOffset(element);
-
- this.xcomp = x + offsetcache[0] - this.deltaX;
- this.ycomp = y + offsetcache[1] - this.deltaY;
- this.offset = Element.cumulativeOffset(element);
-
- return (this.ycomp >= this.offset[1] &&
- this.ycomp < this.offset[1] + element.offsetHeight &&
- this.xcomp >= this.offset[0] &&
- this.xcomp < this.offset[0] + element.offsetWidth);
- },
-
- // within must be called directly before
- overlap: function(mode, element) {
- if (!mode) return 0;
- if (mode == 'vertical')
- return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
- element.offsetHeight;
- if (mode == 'horizontal')
- return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
- element.offsetWidth;
- },
-
- // Deprecation layer -- use newer Element methods now (1.5.2).
-
- cumulativeOffset: Element.Methods.cumulativeOffset,
-
- positionedOffset: Element.Methods.positionedOffset,
-
- absolutize: function(element) {
- Position.prepare();
- return Element.absolutize(element);
- },
-
- relativize: function(element) {
- Position.prepare();
- return Element.relativize(element);
- },
-
- realOffset: Element.Methods.cumulativeScrollOffset,
-
- offsetParent: Element.Methods.getOffsetParent,
-
- page: Element.Methods.viewportOffset,
-
- clone: function(source, target, options) {
- options = options || { };
- return Element.clonePosition(target, source, options);
- }
-};
-
-/*--------------------------------------------------------------------------*/
-
-if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
- function iter(name) {
- return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
- }
-
- instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
- function(element, className) {
- className = className.toString().strip();
- var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
- return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
- } : function(element, className) {
- className = className.toString().strip();
- var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
- if (!classNames && !className) return elements;
-
- var nodes = $(element).getElementsByTagName('*');
- className = ' ' + className + ' ';
-
- for (var i = 0, child, cn; child = nodes[i]; i++) {
- if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
- (classNames && classNames.all(function(name) {
- return !name.toString().blank() && cn.include(' ' + name + ' ');
- }))))
- elements.push(Element.extend(child));
- }
- return elements;
- };
-
- return function(className, parentElement) {
- return $(parentElement || document.body).getElementsByClassName(className);
- };
-}(Element.Methods);
-
-/*--------------------------------------------------------------------------*/
-
-Element.ClassNames = Class.create();
-Element.ClassNames.prototype = {
- initialize: function(element) {
- this.element = $(element);
- },
-
- _each: function(iterator) {
- this.element.className.split(/\s+/).select(function(name) {
- return name.length > 0;
- })._each(iterator);
- },
-
- set: function(className) {
- this.element.className = className;
- },
-
- add: function(classNameToAdd) {
- if (this.include(classNameToAdd)) return;
- this.set($A(this).concat(classNameToAdd).join(' '));
- },
-
- remove: function(classNameToRemove) {
- if (!this.include(classNameToRemove)) return;
- this.set($A(this).without(classNameToRemove).join(' '));
- },
-
- toString: function() {
- return $A(this).join(' ');
- }
-};
-
-Object.extend(Element.ClassNames.prototype, Enumerable);
-
-/*--------------------------------------------------------------------------*/
-
-Element.addMethods(); \ No newline at end of file
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/blaster/extra/shadow-map.js b/o3d/samples/o3d-webgl-samples/bubbles/blaster/extra/shadow-map.js
deleted file mode 100644
index 35f0161..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/blaster/extra/shadow-map.js
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * Represents the surface area that has been hit on a texture map by creating
- * a same-sized canvas composed of uniquely colored pixels.
- *
- * The original intention was to render the target from a single bubble's point
- * of view using this as the texture map in place of the original texture. With
- * stenciling, you render only the pixels that the bubble occludes and thus
- * intersects with when it hits the block. Since each pixel in the rendered
- * buffer has a unique color, it can be reverse mapped to the corresponding
- * texel position and marked off as "hit".
- *
- * @param {number} width The width of the texture to track hits for.
- * @param {number} height The height of the texture to track hits for.
- * @param {o3d.Pack} pack A pack to create objects with.
- * @constructor
- */
-var ShadowMap = function(width, height, pack) {
- this.width = width;
- this.height = height;
- this.canvas = document.createElement("canvas");
- this.canvas.width = width;
- this.canvas.height = height;
-
- this.cached_percent_ = 0;
- this.dirty_cache_ = true;
-
- this.texture = pack.createTexture2D(width, height,
- g.o3d.Texture.XRGB8,
- 1,
- false);
-
- ShadowMap.init(this.canvas);
- this.redrawTexture();
-};
-
-/**
- * Updates the texture object to reflect the most recent values in the canvas.
- */
-ShadowMap.prototype.redrawTexture = function() {
- this.texture.setFromCanvas_(this.canvas, true, false, false);
-};
-
-/**
- * Calculates the percent of the shadow map covered of the entire map.
- * @private
- */
-ShadowMap.prototype.calculatePercent_ = function() {
- var context = this.canvas.getContext("2d");
- var imageData = context.getImageData(0, 0, this.width, this.height);
- var count = 0;
- for (var i = 0; i < this.width * this.height; i++) {
- if (imageData.data[i * 4 + 3] != ShadowMap.ALPHA_START) {
- count++;
- }
- }
- this.cached_percent_ =
- Math.round(count * 100.0 / (this.width * this.height));
-};
-
-
-/**
- * Returns the percentage of the texture that is currently covered as a value
- * from 0 to 100. Caching is used so this value is not recomputed if no changes
- * have been made to the texture (via the apply method).
- *
- * @return {number} The percent, or -1 if the block has not been initialized.
- */
-ShadowMap.prototype.percentCovered = function() {
- if (this.dirty_cache_) {
- this.dirty_cache_ = false;
- this.calculatePercent_();
- }
- return this.cached_percent_;
-};
-
-/**
- * Given a canvas whose pixels contain the "hit" pixels, marks off the
- * corresponding pixels in the original texture. Any pixels in the canvas with
- * an alpha of 0 are ignored.
- *
- * @param {Canvas} renderedCanvas
- */
-ShadowMap.prototype.apply = function(renderedCanvas) {
- var data = this.canvas.getContext("2d").getImageData(0, 0,
- this.width, this.height);
- var rWidth = renderedCanvas.width;
- var rHeight = renderedCanvas.height;
- var rContext = renderedCanvas.getContext("2d");
- var rData = rContext.getImageData(0, 0, rWidth, rHeight);
-
- for (var i = 0; i < rWidth * rHeight; i++) {
- if (rData.data[i * 4 + 3] > 0) { // Alpha of the rendered canvas > 0.
- ShadowMap.updatePixel_(data, rData.data[i * 4],
- rData.data[i * 4 + 1], rData.data[i * 4 + 2]);
- }
- }
- this.canvas.getContext("2d").putImageData(data, 0, 0);
-};
-
-/**
- * Number of values per channel.
- * @type {number}
- */
-ShadowMap.base = 256;
-
-/**
- * The alpha value of unhit pixels in this map. In [0, 255] range.
- * @type {number}
- */
-ShadowMap.ALPHA_START = 127;
-
-/**
- * The alpha value of hit pixels in this map. In [0, 255] range.
- * @type {number}
- */
-ShadowMap.ALPHA_PUT = 255;
-
-/**
- * Given the index of a pixel in an image, computes the RGB color of that pixel
- * based on the pattern we used to initialize the map.
- * @param {number} index
- * @return {!Array.<number>}
- */
-ShadowMap.indexToRGB_ = function(index) {
- var base = ShadowMap.base;
- var r = Math.floor(index / (base * base));
- var g = Math.floor((index % (base * base)) / base);
- var b = index % base;
- return [r, g, b];
-}
-
-/**
- * Given an array [r, g, b] of colors, computes the index of that pixel based on
- * the pattern we used to initialize the map.
- * @param {!Array.<number>} colors
- * @return {number}
- */
-ShadowMap.rgbToIndex_ = function(colors) {
- var r = colors[0];
- var g = colors[1];
- var b = colors[2];
- var base = ShadowMap.base;
- return b + (g * base) + (r * base * base);
-};
-
-/**
- * Given a color, marks off the corresponding location in this map.
- * @param {ImageData} the canvas' ImageData object
- * @param {number} r
- * @param {number} g
- * @param {number} b
- * @return {ImageData} a modified ImageData object
- */
-ShadowMap.updatePixel_ = function(imageData, r, g, b) {
- var index = ShadowMap.rgbToIndex_([r, g, b]);
- imageData.data[index * 4 + 3] = ShadowMap.ALPHA_PUT;
- return imageData;
-};
-
-/**
- * Initializes this map so each pixel is a unique color, where the channels are
- * incremented iteratively in B-G-R order.
- * @param {Canvas} canvas The canvas object to initialize to unique colors.
- */
-ShadowMap.init = function(canvas) {
- var width = canvas.width;
- var height = canvas.height;
- var context = canvas.getContext("2d");
- var imageData = context.getImageData(0, 0, width, height);
- for (var h = 0; h < height; h++) {
- for (var w = 0; w < width; w++) {
- var pixelNum = w + h * width;
- var index = pixelNum * 4;
- var color = ShadowMap.indexToRGB_(pixelNum);
- imageData.data[index] = color[0];
- imageData.data[index + 1] = color[1];
- imageData.data[index + 2] = color[2];
- imageData.data[index + 3] = ShadowMap.ALPHA_START;
- }
- }
- context.putImageData(imageData, 0, 0);
-};
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/blaster/index.html b/o3d/samples/o3d-webgl-samples/bubbles/blaster/index.html
deleted file mode 100644
index 284fcb3..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/blaster/index.html
+++ /dev/null
@@ -1,165 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<title>
-Bubble Blaster (Experimental)
-</title>
-
-<!-- CSS -->
-<link href='http://fonts.googleapis.com/css?family=Inconsolata'
- rel='stylesheet' type='text/css'>
-<link href='resources/style.css' rel='stylesheet' type='text/css'>
-
-<!-- jQuery -->
-<script type="text/javascript"
- src="../third_party/jquery/jquery-1.4.2.min.js"></script>
-
-<!-- O3D -->
-<script type="text/javascript" src="../../../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../../../o3djs/base.js"></script>
-
-<!-- Demo files -->
-<script type="text/javascript" src="js/camera.js"></script>
-<script type="text/javascript" src="js/bubble.js"></script>
-<script type="text/javascript" src="js/bubble-manager.js"></script>
-<script type="text/javascript" src="js/block.js"></script>
-<script type="text/javascript" src="js/level.js"></script>
-<script type="text/javascript" src="js/game.js"></script>
-<script type="text/javascript" src="js/main.js"></script>
-</head>
-<body onload="init();" onunload="uninit();" id="body">
-
-<!-- Contains the level name and number. -->
-<div id="level-description" class="main-container"></div>
-
-<!-- Bubble listing on the left. -->
-<div id="bubble-manager" class="main-container">
- <div id="bubble-count">
- <div id="bubble-count-span"></div> bubbles remaining
- </div>
- <div id="bubble-bubbles"></div>
-</div>
-
-<!-- Links in the upper right. -->
-<div id="options" class="main-container">
- <ul>
- <li><a id="link-help" href="#help">help</a></li>
- <li><a id="link-restart" href="#restart">restart</a></li>
- </ul>
-</div>
-
-<!-- Progress bar at the bottom -->
-<div id="progress">
- <div id="goal" style="width: 0%"></div>
-</div>
-
-<!-- Help dialog. -->
-<div id="help" style="display:none;">
- <b>Goal</b>
- <p>Your mission is to use bubble "splats" to cover as much of the surface
- area of the center target as possible.
- </p>
- <br />
- <b>Controls</b>
- <ul>
- <li> <b>SPACE</b> :: releases the next bubble in your queue.</li>
- <li> <b>wasd</b> :: rotates your position around the model.</li>
- </ul>
- <br />
- <p>
- <a href="#close-help" id="close-help">close</a>
- </p>
-</div>
-
-<!-- Final result -->
-<div id="finalResult" style="display:none;">
- <b>Game over!</b>
- <p>You successfully covered <span id="final"></span> of the target.</p>
-</div>
-
-<!-- The o3d container -->
-<div id="o3d-main" style="width: 100%; height: 100%;"></div>
-
-<!-- Shader for the block. -->
-<textarea style="display:none;" id="blockShader">
- attribute vec4 position;
- attribute vec2 texCoord0;
- uniform mat4 worldViewProjection;
- varying vec4 pos;
- varying vec2 tex;
-
- /**
- * The vertex shader simply transforms the input vertices to screen space.
- */
- void main() {
- // Multiply the vertex positions by the worldViewProjection matrix to
- // transform them to screen space.
- gl_Position = worldViewProjection * position;
- pos = position;
- tex = texCoord0;
- }
-
- // #o3d SplitMarker
- varying vec4 pos;
- varying vec2 tex;
- uniform sampler2D myTexture;
- uniform vec4 bubblePosition[SIZE];
-
- bool insideABubble(vec3 pos) {
- bool count = false;
- for (int i = 0; i < SIZE; i++) {
- vec4 bubble = bubblePosition[i];
- if (length(abs(pos.xyz - bubble.xyz)) < bubble.w) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * The fragment shader derives color based on the position.
- */
- void main() {
- vec4 color = texture2D(myTexture, tex);
- if (insideABubble(pos.xyz)) {
- // inside the bubble
- gl_FragColor = vec4((color.xyz / 2.0), 1.0);
- } else {
- gl_FragColor = vec4(color.xyz, 1.0);
- }
- }
-</textarea>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/block.js b/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/block.js
deleted file mode 100644
index a2102df1..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/block.js
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * Represents the rotating target that is the focus of each level.
- * @param {string} src The path to the json scene.
- * @constructor
- */
-var Block = function(src) {
- this.src = src;
- this.load_();
-};
-
-/**
- * The URL of the scene.json file the target uses.
- * @type {string}
- */
-Block.prototype.src = '';
-
-/**
- * The top level transform that contains this block. Beneath this transform
- * sits a custom transform for intermediate scaling, then the geometry.
- * @type {o3d.Transform}
- */
-Block.prototype.transform = null;
-
-/**
- * A pack just for components belonging to this block.
- * @type {o3d.Pack}
- */
-Block.prototype.pack = null;
-
-/**
- * A pick manager that helps computes intersections between the block and
- * bubbles.
- *
- * @type {o3d.PickManager}
- */
-Block.prototype.pickManager = null;
-
-/**
- * Advances the block one time step.
- * @param {number} elapsedTime
- */
-Block.prototype.step = function(elapsedTime) {
- // No op. Could potentially advance a clock to rotate the model.
-};
-
-/**
- * Returns the overridden effect that the model should use.
- * @return {o3d.Effect}
- */
-Block.prototype.getOverrideEffect = function() {
- var shader = document.getElementById('blockShader').value;
- shader = shader.replace(/SIZE/g,
- g_game.level.bubbleManager_.bubbleQueue_.length);
- var effect = this.pack.createObject('Effect');
- effect.loadFromFXString(shader);
- return effect;
-};
-
-/**
- * Loads the scene.json file and adds it to the scene. Also binds the eye and
- * bubble position parameters.
- */
-Block.prototype.load_ = function() {
- var that = this;
- this.pack = g_client.createPack();
- this.transform = this.pack.createObject('Transform');
-
- var parentTransform = this.transform;
- function callback(pack, parent, exception) {
- if (exception) {
- alert("Could not load: \n" + exception);
- } else {
- o3djs.pack.preparePack(that.pack, g_viewInfo);
- parent.parent = g_client.root;
- // Create the pick manager.
- that.pickManager = o3djs.picking.createPickManager(parent);
- that.pickManager.update();
-
- // TODO: Create a generic sampler with IO-loaded image texture that will
- // be used for all models.
- var samplers = pack.getObjectsByClassName('o3d.Sampler');
- var materials = pack.getObjectsByClassName('o3d.Material');
- for (var m = 0; m < materials.length; ++m) {
- var material = materials[m];
- var effect = that.getOverrideEffect();
- effect.createUniformParameters(material);
- material.effect = effect;
- if (material.getParam('myTexture')) {
- material.getParam('myTexture').value = samplers[0];
- }
- if (material.getParam('bubblePosition')) {
- material.getParam('bubblePosition').value = g_paramArray;
- }
-
- // TODO: Not all materials will use this parameter, or it may be
- // called something different.
- if (material.getParam('lightWorldPos')) {
- material.getParam('lightWorldPos').bind(g_lightWorldPosParam);
- }
- }
-
- }
- }
-
- // Inner transform for scaling and adjustment.
- var child = this.pack.createObject('Transform');
- child.parent = this.transform;
-
- try {
- o3djs.scene.loadScene(g_client, this.pack, child, this.src, callback);
- } catch (e) {
- alert("loading failed : " + e);
- }
-};
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/bubble-manager.js b/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/bubble-manager.js
deleted file mode 100644
index e37eae7..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/bubble-manager.js
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * Manages a sequence of bubble objects.
- *
- * @constructor
- * @param {!Array<!Bubble.BubbleType>} requestedSequence
- * @param {o3d.Pack} pack
- */
-var BubbleManager = function(requestedSequence, pack) {
- this.bubbleQueue_ = [];
- this.nextIndex_ = 0;
- this.pack_ = pack;
-
- this.container_ = $('#bubble-bubbles');
- this.container_.html(" "); // reset
- this.counter_ = $('#bubble-count-span');
-
- for (var i = 0; i < requestedSequence.length; i++) {
- var bubble = new Bubble(requestedSequence[i], this.pack_);
- var el = g_paramArray.createParam(i, 'ParamFloat4');
- el.bind(bubble.param);
-
- this.bubbleQueue_.push(bubble);
- var img = new Image();
- var imageSrc;
- var type = requestedSequence[i];
- switch (type) {
- case Bubble.SMALL:
- imageSrc = "resources/bubble3.png";
- break;
- case Bubble.MEDIUM:
- imageSrc = "resources/bubble2.png";
- break;
- case Bubble.LARGE:
- imageSrc = "resources/bubble1.png";
- break;
- }
- img.src = imageSrc;
- img.alt = "Bubble " + i;
- this.container_.append(img);
- this.counter_.text("" + requestedSequence.length);
- }
-};
-
-/**
- * The bubbles queued to be released.
- * @type {!Array<!Bubble>}
- * @private
- */
-BubbleManager.prototype.bubbleQueue_ = [];
-
-/**
- * The DOM container to show the queue of bubbles.
- * @type {DOM.Element}
- * @private
- */
-BubbleManager.prototype.container_ = null;
-
-/**
- * The DOM container that keeps the count of bubbles remaining.
- * @type {DOM.Element}
- * @private
- */
-BubbleManager.prototype.counter_ = null;
-
-/**
- * A pointer to the current position in the bubble queue.
- * @type {number}
- * @private
- */
-BubbleManager.prototype.nextIndex_ = 0;
-
-/**
- * A pack contains all the transforms, geometry and shaders of the bubbles it
- * manages.
- * @type {o3d.Pack}
- * @private
- */
-BubbleManager.prototype.pack_ = 0;
-
-/**
- * Moves a bubble from the head of the queue to the tail of the bubblesInPlay
- * list and returns that bubble.
- *
- * If the queue is empty, returns null.
- *
- * @return {Bubble}
- */
-BubbleManager.prototype.pop = function() {
- if (this.nextIndex_ == this.bubbleQueue_.length) {
- return null;
- }
- var children = this.container_.children();
- var img = children[this.nextIndex_];
- img.className = "used";
- $(img).slideUp();
- this.counter_.text(this.bubbleQueue_.length - this.nextIndex_ - 1) + "";
- return this.bubbleQueue_[this.nextIndex_++];
-};
-
-/**
- * Returns the bubble at the head of the queue, but does not pop it.
- * If the queue is empty, returns null.
- *
- * @return {Bubble}
- */
-BubbleManager.prototype.peek = function() {
- return (this.bubbleQueue_.length == this.nextIndex_) ? null :
- this.bubbleQueue_[this.nextIndex_];
-};
-
-/**
- * Advances each bubble in the active queue by one timestep.
- */
-BubbleManager.prototype.step = function() {
- for (var i = 0; i < this.nextIndex_; i++) {
- var bubble = this.bubbleQueue_[i];
- bubble.step();
- }
-};
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/bubble.js b/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/bubble.js
deleted file mode 100644
index fef0107..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/bubble.js
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * A bubble object.
- * @param {Bubble.BubbleType} type
- * @param {o3d.Pack} pack
- * @constructor
- */
-var Bubble = function(type, pack) {
- this.kind = type;
- this.position = [0, 0, 0];
- this.velocity = [0, 0, 0];
- this.alive = false;
- this.position = [2 * globals.playerRadius, 0, 0];
- this.param = pack.createObject('ParamFloat4');
- this.param.value = [0, 0, 0, 0];
-
- switch (this.kind) {
- case Bubble.SMALL:
- this.scale = 0.2;
- this.color = [0, 0.4, 0.7, 0.7];
- this.speed = 0.05;
- break;
- case Bubble.MEDIUM:
- this.scale = 0.3;
- this.color = [0, 0.6, 0.2, 0.7];
- this.speed = 0.08;
- break;
- case Bubble.LARGE:
- this.scale = 0.45; // This is the radius.
- this.color = [0.8, 0.2, 0.3, 0.7];
- this.speed = 0.1;
- break;
- default:
- throw 'Invalid type of Bubble';
- }
-
- this.transform = pack.createObject('Transform');
- if (!Bubble.defaultShape) {
- Bubble.createDefaultShape(pack);
- }
- this.transform.addShape(Bubble.defaultShape);
- this.transform.visible = false;
- this.transform.createParam('diffuse', 'ParamFloat4').value = this.color;
-};
-
-
-/**
- * BubbleType,
- * SMALL
- * MEDIUM
- * LARGE
- */
-Bubble.SMALL = 0;
-Bubble.MEDIUM = 1;
-Bubble.LARGE = 2;
-
-/**
- * The type of a bubble.
- * @type {number}
- */
-Bubble.BubbleType = goog.typedef;
-
-/**
- * The type of bubble.
- * @type {Bubble.BubbleType}
- */
-Bubble.prototype.kind = -1;
-
-/**
- * The bubble's position.
- * @type {!Array.<number>}
- */
-Bubble.prototype.position = [];
-
-/**
- * The bubble's velocity.
- * @type {!Array.<number>}
- */
-Bubble.prototype.velocity = [];
-
-
-/**
- * The bubble's color.
- * @type {!Array.<number>}
- */
-Bubble.prototype.color = [1, 1, 1];
-
-/**
- * The bubble's speed. Higher = faster.
- * @type {number}
- */
-Bubble.prototype.speed = 1.0;
-
-/**
- * The bubble's relative size.
- * @type {!Array.<number>}
- */
-Bubble.prototype.scale = 1.0;
-
-/**
- * If bubble is in bounds.
- * @type {boolean}
- */
-Bubble.prototype.alive = false;
-
-/**
- * The bubble's parent transform.
- * @type {o3d.Transform}
- */
-Bubble.prototype.transform = null;
-
-/**
- * A param that will pass this bubble's position and radius to the shader.
- * @type {o3d.ParamFloat4}
- */
-Bubble.prototype.param = null;
-
-/**
- * A shared primitive used by all the bubbles.
- * @type {o3d.Shape}
- */
-Bubble.defaultShape = null;
-
-/**
- * An initializer that creates the default shape.
- * @param {o3d.Pack} pack
- */
-Bubble.createDefaultShape = function(pack) {
- var shader = o3djs.material.createBasicMaterial(
- pack,
- g_viewInfo,
- [1, 1, 1, 1],
- true);
- Bubble.defaultShape = o3djs.primitives.createSphere(pack, shader, 1, 20, 20);
-};
-
-/**
- * Initializes a bubble at given position. The velocity is inferred to be
- * towards the origin and is scaled based on this bubble's speed.
- *
- * @param {!Array.<number>} position
- */
-Bubble.prototype.launch = function(position) {
- this.transform.visible = true;
- this.alive = true;
- this.position = position;
- this.velocity = g_math.mulScalarVector(this.speed,
- g_math.negativeVector(g_math.normalize(position)));
- this.updateTransforms_();
- this.transform.parent = g_client.root;
-};
-
-
-/**
- * Updates the transforms so the bubble draws in the correct position.
- * @private
- */
-Bubble.prototype.updateTransforms_ = function() {
- this.transform.identity();
- this.transform.translate(this.position);
- this.transform.scale([this.scale, this.scale, this.scale]);
-};
-
-/**
- * Updates the values of the uniform param associated with this bubble.
- */
-Bubble.prototype.updateParam = function() {
- this.param.value = [this.position[0], this.position[1], this.position[2],
- this.scale];
-};
-
-/**
- * Advances the bubble by one timestep to its new location.
- */
-Bubble.prototype.step = function() {
- if (!this.alive) {
- return;
- }
-
- this.position[0] += this.velocity[0];
- this.position[1] += this.velocity[1];
- this.position[2] += this.velocity[2];
- this.updateParam();
- this.updateTransforms_();
-
- // Compute the point furthest from the origin along the velocity ray.
- var back = g_math.addVector(g_math.mulScalarVector(-this.scale,
- g_math.normalize(this.velocity)), this.position);
- var worldRay = {near: back, far: [0, 0, 0]};
-
- // Use picking to determine if the origin has intersected the block.
- var result = g_game.level.block.pickManager.pick(worldRay);
- if (result) {
- var ray = g_math.subVector(result.worldIntersectionPosition, back);
- if (g_math.length(ray) <= this.scale) {
- // Bubble intersected, so stop its movement.
- this.alive = false;
- this.transform.visible = false;
- }
- }
-};
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/camera.js b/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/camera.js
deleted file mode 100644
index a9005d0..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/camera.js
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * A camera represents the view of the player. This class has a dependency on
- * g_math.
- *
- * @param {number} fov
- * @param {number} distance
- * @param {o3d.DrawContext} context
- */
-var Camera = function(fov, distance, context) {
- this.eye_ = [0, 0, distance, 1];
- this.fov_ = fov;
- this.target_ = [0, 0, 0, 1];
- this.up_ = [0, 1, 0, 0];
- this.context_ = context;
-};
-
-/**
- * The camera's eye (position).
- * @type {!Array.<number>}
- * @private
- */
-Camera.prototype.eye_ = [0, 0, 0, 1];
-
-/**
- * The camera's field of vision, in degrees.
- * @type {number}
- * @private
- */
-Camera.prototype.fov_ = 45;
-
-/**
- * The camera's target (lookAt).
- * @type {!Array.<number>}
- * @private
- */
-Camera.prototype.target_ = [0, 0, 0, 1];
-
-/**
- * The up vector.
- * @type {!Array.<number>}
- * @private
- */
-Camera.prototype.up_ = [0, 0, 0, 0];
-
-/**
- * The near plane.
- * @type {number}
- * @private
- */
-Camera.prototype.nearPlane_ = 0.1;
-
-/**
- * The far plane.
- * @type {number}
- * @private
- */
-Camera.prototype.farPlane_ = 5000;
-
-/**
- * The drawContext which this camera's position and perspective affects.
- * @type {o3d.DrawContext}
- * @private
- */
-Camera.prototype.context_ = null;
-
-/**
- * Returns the eye position of the camera as a 3-vector.
- * @type {!Array.<number>}
- */
-Camera.prototype.__defineGetter__('eye',
- function() {
- return [this.eye_[0], this.eye_[1], this.eye_[2]];
- }
-);
-
-/**
- * Returns the up vector of the camera as a 3-vector.
- * @type {!Array.<number>}
- */
-Camera.prototype.__defineGetter__('up',
- function() {
- return [this.up_[0], this.up_[1], this.up_[2]];
- }
-);
-
-/**
- * Returns the target/focal point of the camera as a 3-vector.
- * @type {!Array.<number>}
- */
-Camera.prototype.__defineGetter__('target',
- function() {
- return [this.target_[0], this.target_[1], this.target_[2]];
- }
-);
-
-/**
- * Camera.Dir
- * UP,
- * DOWN,
- * LEFT,
- * RIGHT,
- */
-Camera.UP = 0;
-Camera.DOWN = 1;
-Camera.LEFT = 2;
-Camera.RIGHT = 3;
-
-/**
- * Updates the projection matrix to correspond to the new width and height of
- * the canvas.
- * @param {number} width The width of the screen/canvas.
- * @param {number} height The height of the screen/canvas.
- */
-Camera.prototype.updateProjection = function(width, height) {
- this.context_.projection = g_math.matrix4.perspective(
- g_math.degToRad(this.fov_),
- width / height,
- this.nearPlane_,
- this.farPlane_);
-};
-
-
-/**
- * Updates the view matrix using this Camera's eye, target, and up vectors.
- */
-Camera.prototype.updateView = function() {
- this.context_.view = g_math.matrix4.lookAt(this.eye, this.target, this.up);
-};
-
-/**
- * Rotates the Camera by delta radians in the given direction and updates the
- * view.
- *
- * @param {Camera.Dir} direction
- * @param {number} delta
- */
-Camera.prototype.rotate = function(direction, delta) {
- var axis;
- switch(direction) {
- case Camera.LEFT:
- case Camera.RIGHT:
- axis = this.up_;
- break;
- case Camera.UP:
- case Camera.DOWN:
- axis = g_math.cross(this.up_, g_math.negativeVector(this.eye));
- break;
- }
- switch(direction) {
- case Camera.LEFT:
- case Camera.DOWN:
- delta *= -1;
- break;
- }
- var matrix = g_math.matrix4.axisRotation(axis, delta);
- this.up_ = g_math.rowMajor.mulMatrixVector(matrix, this.up_);
- this.eye_ = g_math.rowMajor.mulMatrixVector(matrix, this.eye_);
- this.updateView();
-};
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/game.js b/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/game.js
deleted file mode 100644
index d7f818c..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/game.js
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * Represents a game entity. There should be a single game object.
- * @constructor
- */
-var Game = function() {
-};
-
-/**
- * Initializes the game object and populates its fields.
- * @param {o3d.Pack} pack The pack that this game should create objects in.
- */
-Game.prototype.init = function(pack) {
- this.camera = new Camera(globals.fov, globals.playerRadius,
- g_viewInfo.drawContext);
- this.level = new Level(''); // TODO: This will eventually be a .json path.
- this.level.start();
- g_lightWorldPosParam.value = this.camera.eye;
- this.camera.updateView();
-};
-
-/**
- * The game's camera.
- * @type {Camera}
- */
-Game.prototype.camera = null;
-
-/**
- * The current level.
- * @type {Level}
- */
-Game.prototype.level = null;
-
-/**
- * An action handler to address key presses in the game.
- * @param {Event} event
- */
-Game.prototype.onKeyPress = function(event) {
- event = event || window.event;
- if (event.metaKey)
- return;
-
- var keyChar = String.fromCharCode(o3djs.event.getEventKeyChar(event));
- keyChar = keyChar.toLowerCase();
-
- var dir;
- switch(keyChar) {
- case 'a':
- dir = Camera.LEFT;
- break;
- case 'd':
- dir = Camera.RIGHT;
- break;
- case 'w':
- dir = Camera.UP;
- break;
- case 's':
- dir = Camera.DOWN;
- break;
- case ' ':
- this.level.launchBubble();
- // fall through
- default:
- return;
- }
- this.camera.rotate(dir, globals.keyPressDelta);
- g_lightWorldPosParam.value = this.camera.eye;
-};
-
-/**
- * Ends the game and displays the score screen.
- * @param {string} amount Coverage achieved, as a string.
- */
-Game.prototype.endGame = function(amount) {
- $("#final").text(amount);
- $("#finalResult").fadeIn()
-};
-
-/**
- * Steps the game forward one timestep (elapsedTime).
- * @param {number} elapsedTime The seconds passed since the last call.
- */
-Game.prototype.step = function(elapsedTime) {
- this.level.step(elapsedTime);
-};
-
-
-/**
- * An action handler to address when the o3d container is resized.
- * @param {number} newWidth
- * @param {number} newHeight
- */
-Game.prototype.onClientResize = function(newWidth, newHeight) {
- this.camera.updateProjection(newWidth, newHeight);
-};
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/level.js b/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/level.js
deleted file mode 100644
index c8aaebc..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/level.js
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * Represents a currently active level that is being played.
- * @param config
- */
-var Level = function(config) {
- this.load_(config);
- this.pack_ = g_client.createPack();
-};
-
-/**
- * This level's bubble manager.
- * @type {BubbleManager}
- * @private
- */
-Level.prototype.bubbleManager_ = null;
-
-/**
- * This level's block.
- * @type {Block}
- */
-Level.prototype.block = null;
-
-/**
- * A pack for assets belonging to this level.
- * @type {o3d.Pack}
- * @private
- */
-Level.prototype.pack_ = null;
-
-/**
- * The current percent of surface area covered, as a percent value in the range
- * 0 to 100.
- * @type {number}
- * @private
- */
-Level.prototype.progress_ = 0;
-
-/**
- * The name of the level.
- * @type {string}
- */
-Level.prototype.levelName = '';
-
-/**
- * The level number.
- * @type {number}
- */
-Level.prototype.levelNumber = 0;
-
-/**
- * The sequence of bubbles alloted for this level.
- * @type {!Array.<Bubble.BubbleType>}
- */
-Level.prototype.bubbles = [];
-
-/**
- * The target coverage goal for this level, in the range [0, 100].
- * @type {number}
- */
-Level.prototype.goal = -1;
-
-/**
- * The path to the resource used to load the block model.
- * @type {string}
- */
-Level.prototype.sceneSrc = '';
-
-/**
- * Launches a bubble into the game, if possible. Ends the game if no bubbles
- * are remaining in the queue.
- */
-Level.prototype.launchBubble = function() {
- var bubble = this.bubbleManager_.pop();
- if (bubble) {
- bubble.launch(g_game.camera.eye);
- // TODO: We arbitrarily advance the progress counter. This should later
- // compute the covered surface area and adjust appropriately.
- this.progress_ += Math.floor(Math.random() * 10);
- this.progress_ = Math.min(this.progress_, 99);
- $("#goal").css("width", this.progress_ + "%");
- } else {
- g_game.endGame($("#goal").css("width"));
- }
-};
-
-/**
- * Advances the level by a time duration of elapsedTime.
- * @param {number} elapsedTime The seconds passed since the last call.
- */
-Level.prototype.step = function(elapsedTime) {
- this.bubbleManager_.step(elapsedTime);
- this.block.step(elapsedTime);
-};
-
-/**
- * Starts the level. Should be called after the configurations have loaded.
- */
-Level.prototype.start = function() {
- $('#level-description').text(this.levelNumber + ' ' + this.levelName);
- this.bubbleManager_ = new BubbleManager(this.bubbles, this.pack_);
- this.block = new Block(this.sceneSrc);
-};
-
-/**
- * Loads a JSON-encoded configuration file and populates this level with its
- * values.
- * @param {string} config The path to the JSON file.
- * @private
- */
-Level.prototype.load_ = function(config) {
- // TODO: This will eventually load config, a json path, and populate the
- // fields below.
- this.levelNumber = 12;
- this.levelName = 'Crate';
- this.bubbles = [Bubble.SMALL, Bubble.LARGE, Bubble.SMALL, Bubble.MEDIUM,
- Bubble.SMALL, Bubble.LARGE, Bubble.SMALL, Bubble.MEDIUM,
- Bubble.SMALL, Bubble.LARGE, Bubble.SMALL, Bubble.MEDIUM,
- Bubble.SMALL, Bubble.LARGE, Bubble.SMALL, Bubble.MEDIUM,
- Bubble.SMALL, Bubble.LARGE, Bubble.SMALL, Bubble.MEDIUM,
- Bubble.SMALL, Bubble.LARGE, Bubble.SMALL, Bubble.MEDIUM];
- this.goal = 90;
- this.sceneSrc = "../../../simpleviewer/assets/cube/scene.json";
-};
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/main.js b/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/main.js
deleted file mode 100644
index 7ec99c6..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/blaster/js/main.js
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.arcball');
-o3djs.require('o3djs.scene');
-o3djs.require('o3djs.io');
-o3djs.require('o3djs.picking');
-
-/**
- * Some global settings.
- */
-var globals = {
- playerRadius: 5,
- fov: 45,
- keyPressDelta: 0.1,
- bubbleCullDistance: 5,
-};
-
-/**
- * Some global objects.
- */
-var g_root;
-var g_o3d;
-var g_client;
-var g_viewInfo;
-var g_game;
-var g_pack;
-var g_o3dHeight, g_o3dWidth;
-var g_paramArray;
-
-/**
- * Run once the body is loaded.
- */
-function init() {
- o3djs.webgl.makeClients(init2);
-}
-
-function init2(clientElements) {
- var g_o3dElement = clientElements[0]; // A canvas element.
- g_o3d = g_o3dElement.o3d;
- g_client = g_o3dElement.client;
-
- g_client.normalizeClearColorAlpha = false;
- g_math = o3djs.math;
-
- g_pack = g_client.createPack();
- var rootPack = g_client.createPack();
- g_viewInfo = o3djs.rendergraph.createBasicView(
- rootPack,
- g_client.root,
- g_client.renderGraphRoot,
- [0, 0, 0, 0]);
-
- var paramObject = rootPack.createObject('ParamObject');
- g_clockParam = paramObject.createParam('time', 'ParamFloat');
- g_clockParam.value = 0;
- g_lightWorldPosParam =
- paramObject.createParam('lightWorldPos', 'ParamFloat4');
- g_lightWorldPosParam.value = [0, 0, 5];
-
- g_paramArray = rootPack.createObject('ParamArray');
-
- g_game = new Game();
- g_game.init(g_pack);
- checkClientSize();
-
- // Pass the key press to the game's handler.
- o3djs.event.addEventListener(g_o3dElement, 'keypress', function(e) {
- g_game.onKeyPress(e);
- });
-
- // Attach click handlers to the level links.
- $("#link-help").bind('click', function(e) {
- $("#finalResult").hide();
- showHelpMenu(true);
- return false;
- });
-
- $("#close-help").bind('click', function(e) {
- showHelpMenu(false);
- return false;
- });
-
- $("#link-restart").bind('click', function(e) {
- $("#finalResult").hide();
- $("#help").hide();
- g_game = new Game();
- g_game.init();
- var children = g_client.root.children();
- for (var i = 0; i < children.length; ++i) {
- children[i].parent = null; // remove from tree
- }
- return false;
- });
-
- g_client.setRenderCallback(onRender);
-}
-
-/**
- * Shows or hides the help menu.
- * @param doShow
- */
-function showHelpMenu(doShow) {
- doShow ? $("#help").slideDown() : $("#help").slideUp();
-}
-
-
-/**
- * Called every frame.
- */
-function onRender(renderEvent) {
- g_clockParam.value += renderEvent.elapsedTime;
- g_game.step(renderEvent.elapsedTime);
- checkClientSize();
-}
-
-/**
- * Checks if the window size has changed and updates the matrices if so.
- * @return
- */
-function checkClientSize() {
- var newWidth = parseInt(g_client.width);
- var newHeight = parseInt(g_client.height);
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- g_game.onClientResize(newWidth, newHeight);
- }
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/bubble1.png b/o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/bubble1.png
deleted file mode 100644
index 9fb84c6..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/bubble1.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/bubble2.png b/o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/bubble2.png
deleted file mode 100644
index 570fc7f..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/bubble2.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/bubble3.png b/o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/bubble3.png
deleted file mode 100644
index 732d192..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/bubble3.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/style.css b/o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/style.css
deleted file mode 100644
index b5e8a55..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/blaster/resources/style.css
+++ /dev/null
@@ -1,188 +0,0 @@
-/**
- Copyright 2010, 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.
-*/
-
-* {
- margin: 0;
- padding: 0;
- border: 0;
-}
-
-html, body {
- height: 100%;
-}
-
-body {
- position: relative;
-}
-
-body, p, td, a {
- font-family: 'Inconsolata', Verdana, Arial, Tahoma;
- color: #FFF;
-}
-
-a {
- text-decoration: none;
-}
-
-a:hover {
- color: yellow;
-}
-
-p {
- margin: 5px 0;
-}
-
-ul {
- margin-left: 15px;
-}
-
-/** The left hand side bubble viewer. */
-#bubble-manager {
- min-width: 50px;
- min-height: 300px;
- height: 95%;
- overflow: hidden;
- padding: 10px;
- position: absolute;
- margin: 10px;
- text-align: center;
-}
-
-/** The bubble images within */
-#bubble-bubbles img {
- display: block;
- margin: 3px auto;
-}
-
-/** Text div describing bubbles */
-#bubble-count {
- font-size: 8pt;
-}
-
-/** Number of bubbles left */
-#bubble-count-span {
- font-size: 18pt;
-}
-
-/** For bubbles that have been placed. */
-.used {
- opacity: 0.5;
- -moz-opacity: 0.5;
-}
-
-body {
- background: -webkit-gradient(radial, center center, 0, center center,
- 400, from(#89EAF5), to(black));
- background: -moz-radial-gradient(#89EAF5, black);
-}
-
-/** Links that float upper right corner */
-#options {
- position: absolute;
- top: 0;
- right: 0;
- padding: 15px;
- font-size: 12pt;
- z-index: 2;
-}
-
-#options ul {
- list-style-type: none;
-}
-
-#options li {
- margin: 5px;
-}
-
-/** Links and transitions */
-#options a {
- padding: 3px 6px;
- -webkit-transition: all 0.5s ease-in-out;
- -moz-transition: all 0.5s ease-in-out;
- -o-transition: all 0.5s ease-in-out;
- -webkit-transition: all 0.5s ease-in-out;
- transition: all 0.5s ease-in-out;
-}
-
-#options a:hover {
- background: #333;
- color: #FFF;
- border-radius: 5px;
-}
-
-#level-description {
- position: absolute;
- bottom: 0;
- width: 100%;
- text-align: center;
- padding-bottom: 30px;
- font-size: 20pt;
- font-weight: bold;
-}
-
-.main-container {
- border: 0px solid red;
-}
-
-#progress {
- position: absolute;
- bottom: 0;
- height: 10px;
- width: 100%;
- background: rgba(255, 0, 0, 0.2);
- border-top: 1px solid #333;
-}
-
-#goal {
- height: 100%;
- background: rgba(0, 255, 0, 0.5);
- border-right: 3px solid rgba(0, 200, 0, 0.5);
-}
-
-#help, #finalResult {
- position: absolute;
- z-index: 5;
- border: 5px solid #888;
- background: #FFF;
- color: #000;
- border-radius: 10px;
- padding: 15px;
- width: 400px;
- left: 50%;
- margin-left: -200px;
- margin-top: 20%;
-}
-
-#help, #help *, #finalResult, #finalResult * {
- font-family: Verdana, Arial, Tahoma, sans-serif;
- font-size: 8pt;
- color: #000;
-}
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/bubble.html b/o3d/samples/o3d-webgl-samples/bubbles/bubble.html
deleted file mode 100644
index 60b664f..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/bubble.html
+++ /dev/null
@@ -1,250 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>Bubbles Demo</title>
-
-<link type="text/css" href="css/style.css" rel="stylesheet" />
-
-<!-- Use jQuery UI for the sliders. -->
-<link type="text/css"
- href="third_party/jquery/css/jquery-ui-1.8.4.custom.css" rel="stylesheet" />
-<script type="text/javascript"
- src="third_party/jquery/jquery-1.4.2.min.js"></script>
-<script type="text/javascript"
- src="third_party/jquery/jquery-ui-1.8.4.custom.min.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" src="../../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../../o3djs/base.js"></script>
-<script type="text/javascript" src="js/bubbledemo.js"></script>
-<script type="text/javascript" src="js/environment.js"></script>
-<script type="text/javascript" src="js/noise.js"></script>
-<script type="text/javascript" src="js/iridescence.js"></script>
-<script type="text/javascript" src="js/modulation.js"></script>
-<script type="text/javascript" src="js/controls.js"></script>
-<script type="text/javascript" src="js/main.js"></script>
-
-<!--
-
-This demo is based off of the bubble demo created for o3d command buffers:
-http://code.google.com/p/o3d/source/browse/trunk/googleclient/o3d/?r=55#o3d/command_buffer/samples/bubble
-
-The wish list of things that could be added:
-
-* Ability to change environment maps.
-* Dynamic image backgrounds instead of solid colors.
-* Pop bubbles (picking), or bubbles become thinner over time and self pop.
-
- -->
-
-</head>
-<body>
- <!-- The o3d container. -->
- <div id="o3d"></div>
-
- <div id="floatControls">
- <b>Options:</b>
- <ul>
- <li>
- <label>
- Bubble Options?
- <input type="checkbox" onclick="toggle(0, this); void(0);" />
- </label>
- </li>
- <li>
- <label>
- Iridescence Texture?
- <input type="checkbox" onclick="toggle(1, this); void(0);" />
- </label>
- </li>
- <li>
- <label>
- Noise Texture?
- <input type="checkbox" onclick="toggle(2, this); void(0);" />
- </label>
- </li>
- <li>
- <label>Modulation Texture?
- <input type="checkbox" onclick="toggle(3, this); void(0);" />
- </label>
- </li>
- <li>
- <label>Environment Map?
- <input type="checkbox" onclick="toggle(4, this); void(0);" />
- </label>
- </li>
- </ul>
- <br />
- <b>Background Color (0-255, rgb):</b>
- <p></p>
- <form onSubmit="updateClearColor(); void(0); return false;">
- <input type="text" id="bg-red" size="3" maxLength="3" value="0" />
- <input type="text" id="bg-green" size="3" maxLength="3" value="0" />
- <input type="text" id="bg-blue" size="3" maxLength="3" value="0" />
- <input type="submit" value="Go!" />
- </form>
- <br />
- <b>Controls:</b>
- Drag to rotate. Mousewheel to zoom. 'q' to exit all options.
- <p id="loading">Loading...</p>
- </div>
-
- <!-- The option panels. -->
- <div id="controls">
- <div id="opt-bubble" class="option">
- <a href="#close" class="closer">close</a>
- </div>
- <div id="tex-iridescence" class="option">
- <a href="#close" class="closer">close</a>
- </div>
- <div id="tex-perlin" class="option">
- <a href="#close" class="closer">close</a>
- </div>
- <div id="tex-modulation" class="option">
- <a href="#close" class="closer">close</a>
- </div>
- <div id="tex-environment" class="option">
- <img src="cubemap/posx.png" />
- <img src="cubemap/negx.png" />
- <img src="cubemap/posy.png" />
- <img src="cubemap/negy.png" />
- <img src="cubemap/posz.png" />
- <img src="cubemap/negz.png" />
- <p>Using environment map:
- <a id="toggle-env" href="#toggle-env">On. Turn off?</a>
- </p>
- <a href="#close" class="closer">close</a>
- </div>
- </div>
-
- <!-- Define the vertex shader -->
- <textarea id="shader" name="shader" style="display: none;">
- #ifdef GL_ES
- precision highp float;
- #endif
-
- attribute vec3 position;
- attribute vec3 normal;
- attribute vec2 texCoord0;
- attribute float texCoord1;
-
-
- varying vec4 v_position;
- varying vec2 v_uv;
- varying vec2 v_params;
- varying vec3 v_reflected;
-
- uniform mat4 worldViewProjection;
- uniform mat4 world;
- uniform mat4 worldInverseTranspose;
- uniform vec3 eye;
- uniform vec4 thickness_params;
- uniform float timer;
- uniform float bubbleNumber;
- uniform float distortion;
-
- void main() {
- vec4 object_position = vec4(position.xyz, 1);
- vec4 object_normal = vec4(normal.xyz, 0);
-
- // texCoord1 is the sampled value from the modulation texture.
- float modulation_factor = sin(timer + bubbleNumber) *
- (distortion * texCoord1);
- vec4 unit_normal = normalize(object_normal);
- object_position.xyz += unit_normal.xyz * modulation_factor;
-
- vec3 tmp_normal = normalize((worldInverseTranspose * object_normal).xyz);
- vec4 tmp_position = world * object_position;
- vec4 center = world * vec4(0, 0, 0, 1);
- vec3 eye_vector = normalize(tmp_position.xyz - eye);
-
- // Absolute value for the back faces.
- float cos_i = abs(dot(tmp_normal, eye_vector));
- float thickness = exp(-(tmp_position.y - center.y) * thickness_params.x) *
- thickness_params.y / 2.0;
-
- gl_Position = worldViewProjection * object_position;
- v_position = world * object_position;
- v_uv = texCoord0;
- v_params = vec2(cos_i, thickness);
- v_reflected = reflect(eye_vector, tmp_normal);
- }
-
- // #o3d SplitMarker
-
- #ifdef GL_ES
- precision highp float;
- #endif
-
- uniform sampler2D noise_sampler;
- uniform sampler2D iridescence_sampler;
- uniform samplerCube env_sampler;
- uniform vec4 thickness_params;
- uniform bool useCubeMap;
- uniform bool blendTwice;
-
- varying vec4 v_position;
- varying vec2 v_uv;
- varying vec2 v_params;
- varying vec3 v_reflected;
-
- void main() {
- // Noise: remap [0.. 1] to [-0.5, -.5]
- float noise = (texture2D(noise_sampler, v_uv).x - 0.5);
- float thickness = v_params.y - noise * thickness_params.z;
- float cos_i = v_params.x;
-
- // Modulate iridescence color by the environment looked up along the
- // reflected ray.
- vec4 color = texture2D(iridescence_sampler, vec2(cos_i, thickness));
-
- if (useCubeMap) {
- color.xyz *= textureCube(env_sampler, v_reflected).xyz;
- }
-
- // Modulate by per-face attenuation
- color.rgb *= thickness_params.w;
-
- if (blendTwice) {
- // Apply color effect a second time for more vibrant, visible bubbles.
- color.rgb = color.rgb * (1.0 + color.a);
- color.a *= color.a;
- }
-
- gl_FragColor = color;
- }
- </textarea>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/css/style.css b/o3d/samples/o3d-webgl-samples/bubbles/css/style.css
deleted file mode 100644
index b6f0efa..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/css/style.css
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-* {
- margin: 0;
- padding: 0;
-}
-
-body {
- background-color: #000;
-}
-
-body, b, a, td, p {
- font-family: Verdana, Arial, Tahoma, sans-serif;
- font-size: 8pt;
-}
-
-#o3d {
- height: 100%;
- width: 100%;
-}
-
-p {
- margin: 5px 0;
-}
-
-/** Parent to all the option divs. **/
-#controls {
- left: 30%;
- margin: 30px auto;
- min-width: 50%;
- position: absolute;
- top: 0;
-}
-
-#controls > div {
- display: none;
-}
-
-/** Applies to all the options divs. **/
-.option {
- background-color: rgba(0, 0, 0, 0.8);
- border-radius: 10px;
- -moz-border-radius: 10px;
- margin: 10px;
- padding: 20px;
-}
-
-.slider-set {
- padding: 15px;
-}
-
-.slider-set span {
- color: #FFF;
- font-size: 10pt;
-}
-
-.slider-set .value {
- color: #F5CA84;
- float: right;
- font-weight: bold;
- font-size: 14pt;
-}
-
-/** Closes an option block. **/
-a.closer {
- color: #FFF;
- display: block;
- margin-top: 15px;
-}
-
-.slider-wrap {
- margin-top: 15px;
-}
-
-/** Floating box on the top left **/
-#floatControls {
- background-color: rgba(255, 255, 255, 0.5);
- border-radius: 10px;
- -moz-border-radius: 10px;
- left: 15px;
- padding: 10px;
- position: absolute;
- top: 15px;
- width: 25%;
- z-index: 1;
-}
-
-/** Space out the environment maps a little. */
-#tex-environment img {
- margin: 15px 10px;
-}
-
-#tex-environment p {
- color: #F5CA84;
- font-size: 14pt;
- font-weight: bold;
-}
-
-/** Toggle environment map link. */
-#tex-environment a#toggle-env {
- color: #FFF;
- font-size: 14pt;
- padding: 4px;
- text-decoration: none;
-}
-
-#tex-environment a#toggle-env:hover {
- color: #666;
-}
-
-ul {
- list-style-type: none;
-}
-
-li {
- margin-top: 5px;
-}
-
-#bg-red {
- background-color: rgb(255, 200, 200);
-}
-
-#bg-green {
- background-color: rgb(200, 255, 200);
-}
-
-#bg-blue {
- background-color: rgb(200, 200, 255);
-}
-
-#loading {
- color: red;
- font-size: 18pt;
-}
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/cubemap/negx.png b/o3d/samples/o3d-webgl-samples/bubbles/cubemap/negx.png
deleted file mode 100644
index 3dabb64..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/cubemap/negx.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/cubemap/negy.png b/o3d/samples/o3d-webgl-samples/bubbles/cubemap/negy.png
deleted file mode 100644
index 9fdc1ff..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/cubemap/negy.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/cubemap/negz.png b/o3d/samples/o3d-webgl-samples/bubbles/cubemap/negz.png
deleted file mode 100644
index 5e71d3e..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/cubemap/negz.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/cubemap/posx.png b/o3d/samples/o3d-webgl-samples/bubbles/cubemap/posx.png
deleted file mode 100644
index ddf4afc..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/cubemap/posx.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/cubemap/posy.png b/o3d/samples/o3d-webgl-samples/bubbles/cubemap/posy.png
deleted file mode 100644
index b46330d..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/cubemap/posy.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/cubemap/posz.png b/o3d/samples/o3d-webgl-samples/bubbles/cubemap/posz.png
deleted file mode 100644
index 0efd837..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/cubemap/posz.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/js/bubbledemo.js b/o3d/samples/o3d-webgl-samples/bubbles/js/bubbledemo.js
deleted file mode 100644
index 9ed249b..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/js/bubbledemo.js
+++ /dev/null
@@ -1,620 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * A namespace to contain all the BubbleShader related methods and functions.
- */
-var bsh = bsh || {};
-
-/**
- * Define pi globally.
- * @type {number}
- */
-var kPi = 3.14159265359;
-
-/**
- * Generates a random number between min and max.
- * @param {number} min
- * @param {number} max
- * @return {number}
- */
-function randf(min, max) {
- return min + (Math.random() * (max - min));
-}
-
-/**
- * Clamps a decimal value to [0, 1] and then converts it to range [0, 255].
- * @param {number} x Input value.
- * @return {number}
- */
-bsh.clamp = function(x) {
- x = Math.min(1.0, Math.max(0.0, x));
- return Math.floor(x == 1.0 ? 255 : x * 256.0);
-}
-
-/**
- * Applies a cubic Hermite interpolation: x^2 * (3 - 2x)
- * @param {number} x
- * @return {number}
- */
-bsh.smoothStep = function(x) {
- return (3.0 - (2.0 * x)) * x * x;
-}
-
-/**
- * Does a linear interpolation between a and b at time t.
- * @param {number} t
- * @param {number} a
- * @param {number} b
- * @return {number}
- */
-bsh.lerp = function(t, a, b) {
- return a + ((b - a) * t);
-}
-
-/**
- * Samples a canvas at the given (u, v) coordinates and returns the red value
- * of that pixel as a float in range [0, 1]. Wraps the texture coordinates (u,v)
- * if they exceed the range [0, 1].
- * @param {Canvas} canvas The canvas to sample from.
- * @param {number} u The u texture coordinate.
- * @param {number} v The v texture coordinate.
- */
-bsh.Sample = function(canvas, u, v) {
- var width = canvas.width;
- var height = canvas.height;
- var x = Math.floor((u % 1.0) * width);
- var y = Math.floor((v % 1.0) * height);
- var pixel = canvas.getContext('2d').getImageData(x, y, 1, 1);
- return pixel.data[0] / 255; // Return the red value of the pixel in [0, 1].
-}
-
-/**
- * Computes the vertices and indices for a sphere shape. The vertices and
- * indices array will be overwritten with the computed values. Assumes that all
- * bubbles share the same sphere shape.
- *
- * @param {number} rows Number of rows to subdivide the sphere in to.
- * @param {number} cols Number of cols to subdivide the sphere in to.
- * @param {Canvas} canvas A canvas to sample modulation from.
- * @param {!Array.<Object>} vertices Array of vertices (as objects).
- * @param {!Array.<number>} indices The index buffer array for the triangles.
- */
-bsh.MakeSphereCoordinates = function(rows, cols, canvas, vertices, indices) {
- var counter = 0;
- for (var y = 0; y < rows + 1; ++y) {
- var phi = y * kPi / rows;
- var y1 = Math.cos(phi);
- var r = Math.sin(phi);
- for (var x = 0; x < cols + 1; ++x) {
- var theta = x * 2.0 * kPi / cols;
- var x1 = Math.cos(theta) * r;
- var z1 = Math.sin(theta) * r;
- var index = x + y * (cols + 1);
- var vertex = {};
- vertices.push(vertex);
- vertex.x = x1;
- vertex.y = y1;
- vertex.z = z1;
- vertex.nx = x1;
- vertex.ny = y1;
- vertex.nz = z1;
- vertex.u = x * 1.0 / cols;
- vertex.v = y * 1.0 / rows;
- vertex.mod = bsh.Sample(canvas, vertex.u, vertex.v);
-
- if (x != cols && y != rows) {
- // For each vertex, we add indices for 2 triangles representing the
- // quad using this vertex as the upper left corner:
- // [(x, y), (x+1, y), (x+1, y+1)] and
- // [(x, y), (x+1, y+1), (x, y+1)].
- // Note that we don't create triangles for the last row and the last
- // column of vertices.
- indices[counter++] = index;
- indices[counter++] = index + 1;
- indices[counter++] = index + cols + 2;
- indices[counter++] = index;
- indices[counter++] = index + cols + 2;
- indices[counter++] = index + cols + 1;
- }
- }
- }
-}
-
-/**
- * Globals values.
- * @type {Object}
- */
-bsh.Globals = {
- kRows: 50,
- kCols: 100,
- kTexWidth: 512,
- kTexHeight: 512,
- kRefractionIndex: 1.33,
- kBubbleCount: 10,
- kRedWavelength: 680,
- kGreenWavelength: 530,
- kBlueWavelength: 440,
- kMaxWavelength: 680,
- kFrequency: 8,
- kNoiseRatio: [0.2, 0.5],
- kBubbleThickness: [0.3, 0.6],
- kBubbleScale: [0.5, 2.0],
- kBubbleSpin: 0.05,
- kNumBlips: 4,
- kBlipSize: [150, 200],
- kBlipDistortion: 0.25,
- kMaxBlips: 15
-};
-
-/**
- * An instance of the demo.
- * @param {string} shaderString The bubble's shader string.
- */
-var BubbleDemo = function(shaderString) {
- this.indices_ = [];
- this.vertices_ = [];
-
- var g = bsh.Globals;
-
- // Make the modulation canvas before making sphere coordinates.
- this.mod_source = new bsh.Modulation(g.kTexWidth, g.kTexHeight, g.kBlipSize,
- g.kNumBlips);
-
- bsh.MakeSphereCoordinates(g.kRows, g.kCols, this.mod_source.canvas,
- this.vertices_, this.indices_);
-
- var noise_sampler = this.makeNoiseTexture_();
- var iridescence_sampler = this.makeIridescenceTexture_();
- var cubemap = this.makeCubeMap_();
-
- var frontMaterial = this.createMaterial_(shaderString, noise_sampler,
- iridescence_sampler, cubemap);
-
- // This material will cull the front faces instead of the back.
- var backMaterial = this.createMaterial_(shaderString, noise_sampler,
- iridescence_sampler, cubemap);
- backMaterial.state = g_pack.createObject('State');
- backMaterial.state.getStateParam('CullMode').value = g_o3d.State.CULL_CCW;
-
- this.frontShape = this.makeShape_(frontMaterial);
- this.backShape = this.makeShape_(backMaterial);
- this.bubbles_ = [];
- this.regenerateBubbles();
-}
-
-/**
- * Creates a material with the given effect and assigns its uniform parameters.
- * @param {string} shaderString The shader source.
- * @param {o3d.Sampler} noise_sampler
- * @param {o3d.Sampler} iridescence_sampler
- * @param {o3d.TextureCUBE} cubemap
- * @return {o3d.Material}
- * @private
- */
-BubbleDemo.prototype.createMaterial_ = function(shaderString, noise_sampler,
- iridescence_sampler, cubemap) {
- var effect = g_pack.createObject('Effect');
- effect.loadFromFXString(shaderString);
- var material = g_pack.createObject('Material');
- material.drawList = g_viewInfo.performanceDrawList;
- material.effect = effect;
- effect.createUniformParameters(material);
-
- material.getParam("noise_sampler").value = noise_sampler;
- material.getParam("iridescence_sampler").value = iridescence_sampler;
- material.getParam("env_sampler").value = cubemap;
- material.getParam("eye").bind(g_eyeParam);
- material.getParam("timer").bind(g_clock);
- material.getParam("useCubeMap").bind(g_useCubeMap);
- material.getParam("blendTwice").bind(g_blendTwice);
- material.getParam("distortion").bind(g_blipDistortion);
- return material;
-}
-
-/**
- * Creates the perlin noise texture.
- * @return {o3d.Sampler}
- * @private
- */
-BubbleDemo.prototype.makeNoiseTexture_ = function() {
- var g = bsh.Globals;
- this.noise_source = new bsh.Perlin(g.kFrequency,
- 98576, // This is supposed to be a random \cough seed.
- g.kTexWidth,
- g.kTexHeight);
- this.noise_texture = g_pack.createTexture2D(g.kTexWidth,
- g.kTexHeight,
- g_o3d.Texture.ARGB8,
- 1,
- false);
- this.noise_source.refresh(this.noise_texture);
- var noise_sampler = g_pack.createObject('Sampler');
- noise_sampler.name = "noise";
- noise_sampler.addressModeU = g_o3d.Sampler.WRAP;
- noise_sampler.addressModeV = g_o3d.Sampler.WRAP;
- noise_sampler.addressModeW = g_o3d.Sampler.WRAP;
- noise_sampler.magFilter = g_o3d.Sampler.LINEAR;
- noise_sampler.minFilter = g_o3d.Sampler.LINEAR;
- noise_sampler.mipFilter = g_o3d.Sampler.NONE;
- noise_sampler.maxAnisotropy = 1;
- noise_sampler.texture = this.noise_texture;
- return noise_sampler;
-}
-
-/**
- * Creates the iridescence texture.
- * @return {o3d.Sampler}
- * @private
- */
-BubbleDemo.prototype.makeIridescenceTexture_ = function() {
- var g = bsh.Globals;
- this.iridescence_source = new bsh.Iridescence(g.kTexWidth,
- g.kTexHeight,
- g.kRefractionIndex,
- g.kMaxWavelength);
- this.iridescence_texture = g_pack.createTexture2D(g.kTexWidth,
- g.kTexHeight,
- g_o3d.Texture.ARGB8,
- 1,
- false);
- this.iridescence_source.refresh(this.iridescence_texture);
- var iri_sampler = g_pack.createObject('Sampler');
- iri_sampler.name = "iridescence";
- iri_sampler.addressModeU = g_o3d.Sampler.CLAMP;
- iri_sampler.addressModeV = g_o3d.Sampler.CLAMP;
- iri_sampler.addressModeW = g_o3d.Sampler.CLAMP;
- iri_sampler.magFilter = g_o3d.Sampler.LINEAR;
- iri_sampler.minFilter = g_o3d.Sampler.LINEAR;
- iri_sampler.mipFilter = g_o3d.Sampler.NONE;
- iri_sampler.maxAnisotropy = 1;
- iri_sampler.texture = this.iridescence_texture;
- return iri_sampler;
-}
-
-
-/**
- * Creates a cube/environment map.
- * @return {o3d.TextureCUBE}
- * @private
- */
-BubbleDemo.prototype.makeCubeMap_ = function() {
- this.env_source = new bsh.Environment($("#tex-environment img"));
- return this.env_source.texture;
-}
-
-
-/**
- * A list of indices used to create geometry.
- * @type {!Array.<number>}
- * @private
- */
-BubbleDemo.prototype.indices_ = [];
-
-/**
- * A list of vertices used to create geometry.
- * @type {!Array.<number>}
- * @private
- */
-BubbleDemo.prototype.vertices_ = [];
-
-/**
- * The noise texture source.
- * @type {bsh.Perlin}
- */
-BubbleDemo.prototype.noise_source = null;
-
-/**
- * The noise texture object.
- * @type {o3d.Texture}
- */
-BubbleDemo.prototype.noise_texture = null;
-
-/**
- * The iridescence texture source.
- * @type {bsh.Iridescence}
- */
-BubbleDemo.prototype.iridescence_source = null;
-
-/**
- * The iridescence texture object.
- * @type {o3d.Texture}
- */
-BubbleDemo.prototype.iridescence_texture = null;
-
-/**
- * The modulation texture source.
- * @type {bsh.Modulation}
- */
-BubbleDemo.prototype.mod_source = null;
-
-/**
- * The environment map source.
- * @type {bsh.Environment}
- */
-BubbleDemo.prototype.env_source = null;
-
-/**
- * A list of bubbles in the demo.
- * @type {!Array.<Object>}
- */
-BubbleDemo.prototype.bubbles_ = [];
-
-/**
- * The shape object shared by all bubble instances.
- * @type {o3d.Shape}
- */
-BubbleDemo.prototype.shape = null;
-
-/**
- * An array of streambanks backing the shape primitives used.
- * @type {!Array.<o3d.StreamBank>}
- */
-BubbleDemo.prototype.streamBanks = [];
-
-
-/**
- * Updates the iridescence texture using the latest global parameters.
- */
-BubbleDemo.prototype.regenerateIridescence = function() {
- var g = bsh.Globals;
- this.iridescence_source.init(g.kRefractionIndex, g.kMaxWavelength);
- this.iridescence_source.refresh(this.iridescence_texture);
-}
-
-/**
- * Updates the noise texture using the latest global parameters.
- */
-BubbleDemo.prototype.regenerateNoise = function() {
- var g = bsh.Globals;
- var seed = Math.floor(new Date().getTime() % 100000);
- this.noise_source.init(g.kFrequency, seed);
- this.noise_source.refresh(this.noise_texture);
-}
-
-/**
- * Updates the modulation vertex stream using the latest global parameters.
- */
-BubbleDemo.prototype.regenerateModulation = function() {
- var g = bsh.Globals;
- this.mod_source.init(g.kBlipSize, g.kNumBlips);
-
- // Update the stream to sample from the new texture.
- var newModulationCoords = [];
- for (var i = 0; i < this.vertices_.length; ++i) {
- var vertex = this.vertices_[i];
- var value = bsh.Sample(this.mod_source.canvas, vertex.u, vertex.v);
- vertex.mod = value;
- newModulationCoords.push(value);
- }
-
- for (var i = 0; i < this.streamBanks.length; i++) {
- var modulationStream =
- this.streamBanks[i].getVertexStream(g_o3d.Stream.TEXCOORD, 1);
- modulationStream.field.setAt(0, newModulationCoords);
- }
-}
-
-/**
-* Toggles whether bubbles are rendered with a second thin-film layer, making
-* it easier to see their surface.
-* @param {boolean} doRender True if bubbles should be rendered with a duplicate
-* blending effect.
-*/
-BubbleDemo.prototype.renderThickerBubbles = function(doRender) {
- g_blendTwice.value = doRender;
-}
-
-/**
- * Updates the set of bubbles to use the latest global parameters.
- */
-BubbleDemo.prototype.regenerateBubbles = function() {
- var g = bsh.Globals;
- var i = 0;
-
- // Update existing bubbles and create new ones if necessary.
- for (i = 0; i < g.kBubbleCount; ++i) {
- var bubble = this.bubbles_[i] || {};
- bubble.position = [randf(-6, 6), randf(-6, 6), randf(-6, 6)];
- bubble.rotation_speed = [randf(-g.kBubbleSpin, g.kBubbleSpin),
- randf(-g.kBubbleSpin, g.kBubbleSpin),
- randf(-g.kBubbleSpin, g.kBubbleSpin)];
- bubble.scale = randf(g.kBubbleScale[0], g.kBubbleScale[1]);
-
- var max_thickness = randf(g.kBubbleThickness[0], g.kBubbleThickness[1]);
- var min_thickness = randf(g.kBubbleThickness[0], max_thickness);
-
- // thickness = base * e^(-y*falloff) for y in [-scale..scale].
- bubble.thickness_falloff =
- Math.log(max_thickness / min_thickness) / (2 * bubble.scale);
- bubble.base_thickness =
- max_thickness * Math.exp(-bubble.scale * bubble.thickness_falloff);
- bubble.noise_ratio = randf(g.kNoiseRatio[0], g.kNoiseRatio[1]);
-
- if (!bubble.transform) {
- // The parent transform for this one bubble.
- bubble.transform = g_pack.createObject("Transform");
- bubble.transform.name = "Bubble" + i;
-
- // One draw for back face, another for front.
- bubble.back = g_pack.createObject("Transform");
- bubble.back.createParam('thickness_params', 'ParamFloat4');
- bubble.back.parent = bubble.transform;
- bubble.back.addShape(this.backShape);
-
- bubble.front = g_pack.createObject("Transform");
- bubble.front.createParam('thickness_params', 'ParamFloat4');
- bubble.front.parent = bubble.transform;
- bubble.front.addShape(this.frontShape);
-
- // This adds a little modulation so that the bubbles grow/shrink at
- // different rates and times.
- var bNumber = kPi * i * 0.5;
- bubble.back.createParam('bubbleNumber', 'ParamFloat').value = bNumber;
- bubble.front.createParam('bubbleNumber', 'ParamFloat').value = bNumber;
- }
-
- bubble.transform.visible = true;
- this.bubbles_[i] = bubble;
- this.updateParams_(bubble);
- }
-
- // Hide the rest of the bubbles.
- for (i; i < this.bubbles_.length; ++i) {
- this.bubbles_[i].transform.visible = false;
- }
-}
-
-/**
- * Updates the uniform parameters for a bubble.
- * @param {Object} bubble
- * @private
- */
-BubbleDemo.prototype.updateParams_ = function(bubble) {
- bubble.back.getParam('thickness_params').value =
- [bubble.thickness_falloff, bubble.base_thickness, bubble.noise_ratio, 0.5];
- bubble.front.getParam('thickness_params').value =
- [bubble.thickness_falloff, bubble.base_thickness, bubble.noise_ratio, 1.0];
-}
-
-/**
- * Creates a bubble shape that uses the material. Also adds to the streambank
- * variable the bank that was used for the primitive that was created.
- * @param {o3d.Material} material
- * @return {o3d.Shape}
- * @private
- */
-BubbleDemo.prototype.makeShape_ = function(material) {
- var shape = g_pack.createObject('Shape');
- var shapePrimitive = g_pack.createObject('Primitive');
- var streamBank = g_pack.createObject('StreamBank');
-
- shapePrimitive.owner = shape;
- shapePrimitive.material = material;
- shapePrimitive.streamBank = streamBank;
- this.streamBanks.push(streamBank);
-
- var g = bsh.Globals;
- shapePrimitive.primitiveType = g_o3d.Primitive.TRIANGLELIST;
- shapePrimitive.numberPrimitives = this.indices_.length / 3;
- shapePrimitive.numberVertices = this.vertices_.length;
- shapePrimitive.createDrawElement(g_pack, null);
-
- var positionArray = [];
- var normalArray = [];
- var uvArray = [];
- var modulationArray = [];
-
- for (var i = 0; i < this.vertices_.length; ++i) {
- var vertex = this.vertices_[i];
- positionArray.push(vertex.x, vertex.y, vertex.z);
- normalArray.push(vertex.nx, vertex.ny, vertex.nz);
- uvArray.push(vertex.u, vertex.v);
- modulationArray.push(vertex.mod);
- }
-
- var indicesArray = this.indices_;
-
- // Create buffers containing the vertex data.
- var positionsBuffer = g_pack.createObject('VertexBuffer');
- var positionsField = positionsBuffer.createField('FloatField', 3);
- positionsBuffer.set(positionArray);
-
- var texCoordsBuffer = g_pack.createObject('VertexBuffer');
- var texCoordsField = texCoordsBuffer.createField('FloatField', 2);
- texCoordsBuffer.set(uvArray);
-
- var modulationBuffer = g_pack.createObject('VertexBuffer');
- var modulationField = modulationBuffer.createField('FloatField', 1);
- modulationBuffer.set(modulationArray);
-
- var normalBuffer = g_pack.createObject('VertexBuffer');
- var normalField = normalBuffer.createField('FloatField', 3);
- normalBuffer.set(normalArray);
-
- var indexBuffer = g_pack.createObject('IndexBuffer');
- indexBuffer.set(indicesArray);
-
- // Add buffers to the StreamBank.
- streamBank.setVertexStream(
- g_o3d.Stream.POSITION,
- 0,
- positionsField,
- 0);
- streamBank.setVertexStream(
- g_o3d.Stream.TEXCOORD,
- 0,
- texCoordsField,
- 0);
- streamBank.setVertexStream(
- g_o3d.Stream.TEXCOORD,
- 1,
- modulationField,
- 0);
- streamBank.setVertexStream(
- g_o3d.Stream.NORMAL,
- 0,
- normalField,
- 0);
- shapePrimitive.indexBuffer = indexBuffer;
- return shape;
-}
-
-/**
- * Updates all the bubbles managed by this demo object.
- */
-BubbleDemo.prototype.update = function() {
- for (var i = 0; i < this.bubbles_.length; ++i) {
- this.updateBubble_(this.bubbles_[i]);
- }
-}
-
-/**
- * Updates the position and scale of a single bubble.
- * @param {Object} bubble
- * @private
- */
-BubbleDemo.prototype.updateBubble_ = function(bubble) {
- if (!bubble.transform.parent) {
- bubble.transform.parent = g_dataroot;
- }
-
- // TODO: potentially do a priority-order pass and manually sort the bubbles
- // to ensure back face is drawn prior to front?
-
- bubble.transform.identity();
- var rotation = bubble.rotation_speed;
- bubble.transform.rotateX(rotation[0] * 2 * kPi * g_clock.value);
- bubble.transform.rotateY(rotation[1] * 2 * kPi * g_clock.value);
- bubble.transform.rotateZ(rotation[2] * 2 * kPi * g_clock.value);
- bubble.transform.scale(bubble.scale, bubble.scale, bubble.scale);
- bubble.transform.translate(bubble.position);
-}
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/js/controls.js b/o3d/samples/o3d-webgl-samples/bubbles/js/controls.js
deleted file mode 100644
index 77db8a3..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/js/controls.js
+++ /dev/null
@@ -1,341 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * Creates a jQuery UI Slider and stores associated options and callbacks.
- * @param {Object} options Options for the slider. See jQuery documentation.
- * @param {function} cb Callback to run when value is changed.
- */
-var SliderSet = function(options, cb) {
- this.parent = $('<div class="slider-set"></div>');
-
- // Span for the title of this option.
- this.parent.append('<span>' + options.name + '</span>');
-
- // Span for the value of this option.
- this.valueWrite = $('<span class="value"></span>');
- this.parent.append(this.valueWrite);
-
- // Make the slider.
- var slider = $('<div></div>');
- var that = this;
- options.slide = function(ev, ui) {
- that.updateValue(ui.values ? ui.values : ui.value);
- };
- options.stop = function(ev, ui) {
- cb(ui.values ? ui.values : ui.value);
- }
- slider.slider(options);
-
- // Wrap slider in div and append to parent.
- var sliderWrapper = $('<div class="slider-wrap" />');
- sliderWrapper.append(slider);
- this.parent.append(sliderWrapper);
-}
-
-/**
- * The parent div of this particular option set.
- * @type {DOMElement}
- */
-SliderSet.prototype.parent = null;
-
-/**
- * Container the displays the current value of the slider.
- * @type {DOMElement}
- */
-SliderSet.prototype.valueWrite = null;
-
-
-/**
- * Updates the value being shown to the user.
- * @param {Number|!Array.<number>} values The value(s) of the slider.
- */
-SliderSet.prototype.updateValue = function(values) {
- var print = '';
- if (values.length) { // is Array
- print = 'Range: ' + values[0] + ' to ' + values[1];
- } else {
- print = values + '';
- }
- this.valueWrite.html(print);
-}
-
-
-/**
- * Creates and appends the controls.
- */
-function buildControls() {
- var bubblePanel = $("#opt-bubble");
- var iridescencePanel = $("#tex-iridescence");
- var noisePanel = $("#tex-perlin");
- var modPanel = $("#tex-modulation")
- var g = bsh.Globals;
-
- var sliders = [
- { name: 'Number of Bubbles',
- min: 1,
- max: 15,
- value: g.kBubbleCount,
- step: 1,
- range: false,
- parent: bubblePanel,
- cb: function(values) {
- bsh.Globals.kBubbleCount = values;
- g_demo.regenerateBubbles();
- }
- },
- { name: 'Bubble Size Range',
- min: 0.1,
- max: 2.5,
- step: 0.1,
- values: g.kBubbleScale,
- range: true,
- parent: bubblePanel,
- cb: function(values) {
- bsh.Globals.kBubbleScale = values;
- g_demo.regenerateBubbles();
- }
- },
- { name: 'Bubble Thickness Range',
- min: 0.1,
- max: 1.0,
- step: 0.1,
- values: g.kBubbleThickness,
- range: true,
- parent: bubblePanel,
- cb: function(values) {
- bsh.Globals.kBubbleThickness = values;
- g_demo.regenerateBubbles();
- }
- },
- { name: 'Bubble Movement',
- min: 0,
- max: 0.2,
- step: 0.01,
- value: g.kBubbleSpin,
- range: false,
- parent: bubblePanel,
- cb: function(values) {
- bsh.Globals.kBubbleSpin = values;
- g_demo.regenerateBubbles();
- }
- },
- { name: 'Pattern Distortion',
- min: 0,
- max: 1.5,
- step: 0.1,
- values: g.kNoiseRatio,
- range: true,
- parent: bubblePanel,
- cb: function(values) {
- bsh.Globals.kNoiseRatio = values;
- g_demo.regenerateBubbles();
- }
- },
- { name: 'Iridescence Frequency',
- min: 500,
- max: 1000,
- step: 20,
- value: g.kMaxWavelength,
- range: false,
- parent: iridescencePanel,
- cb: function(values) {
- bsh.Globals.kMaxWavelength = values;
- g_demo.regenerateIridescence();
- }
- },
- { name: 'Iridescence Refraction Index',
- min: 1,
- max: 2,
- step: 0.01,
- value: g.kRefractionIndex,
- range: false,
- parent: iridescencePanel,
- cb: function(values) {
- bsh.Globals.kRefractionIndex = values;
- g_demo.regenerateIridescence();
- }
- },
- { name: 'Noise Frequency',
- min: 4,
- max: 12,
- step: 1,
- value: g.kFrequency,
- range: false,
- parent: noisePanel,
- cb: function(values) {
- bsh.Globals.kFrequency = values;
- g_demo.regenerateNoise();
- }
- },
- { name: 'Blip Radius Range',
- min: 50,
- max: 400,
- step: 25,
- values: g.kBlipSize,
- range: true,
- parent: modPanel,
- cb: function(values) {
- bsh.Globals.kBlipSize = values;
- g_demo.regenerateModulation();
- }
- },
- { name: 'Number of Blips',
- min: 0,
- max: g.kMaxBlips,
- step: 1,
- value: g.kNumBlips,
- range: false,
- parent: modPanel,
- cb: function(values) {
- bsh.Globals.kNumBlips = values;
- g_demo.regenerateModulation();
- }
- },
- { name: 'Distortion Factor',
- min: 0,
- max: 1,
- step: 0.05,
- value: g.kBlipDistortion,
- range: false,
- parent: modPanel,
- cb: function(values) {
- g_blipDistortion.value = values;
- }
- }
- ];
-
- // Append textures to their divs.
- $("#tex-iridescence").prepend(g_demo.iridescence_source.canvas);
- $("#tex-perlin").prepend(g_demo.noise_source.canvas);
- $("#tex-modulation").prepend(g_demo.mod_source.canvas);
-
- // Make the sliders.
- for (var i = 0; i < sliders.length; i++) {
- var specs = sliders[i];
- var s = new SliderSet(specs, specs.cb);
- specs.parent.prepend(s.parent);
- s.updateValue(specs.value ? specs.value : specs.values);
- }
-
- // Add event listeners to specific links.
- $("#toggle-env").click(function() {
- g_useCubeMap.value = !g_useCubeMap.value;
- if (g_useCubeMap.value) {
- $(this).html("On. Turn off?");
- } else {
- $(this).html("Off. Turn on?");
- }
- return false;
- });
-
- $(".closer").each(function(i) {
- var index = i;
- $(this).click(function() {
- $(this).parent().slideUp();
- var checkboxes = $("input[type=checkbox]");
- $(checkboxes[index]).attr("checked", false);
- return false;
- });
- });
-
- // 'q' closes all the open panels.
- // 1/2 toggle whether the color effect is doubled for more visible bubbles.
- window.document.onkeypress = function(e) {
- var event = e || window.event;
- if (event.metaKey)
- return;
- var keyChar = String.fromCharCode(o3djs.event.getEventKeyChar(event));
- keyChar = keyChar.toLowerCase();
- if (keyChar == 'q') {
- hideAll();
- } else if (keyChar == '1') {
- g_demo.renderThickerBubbles(false);
- } else if (keyChar == '2'){
- g_demo.renderThickerBubbles(true);
- }
- };
-}
-
-/**
- * Hides any open option panels.
- */
-function hideAll() {
- $(".closer").click();
-}
-
-/**
- * Toggles which option panel is being shown.
- * @param {number} type Index of the associated option panel in #controls.
- * @param {DOMElement} checkbox The checkbox element.
- */
-function toggle(type, checkbox) {
- var options = $("#controls").children();
-
- if (! $(checkbox).attr('checked')) {
- $(options[type]).slideUp();
- } else {
- var target = $(options[type]);
- if (target.css("display") == "block") {
- return; // Already showing.
- }
- $("#controls").children().slideUp();
- target.slideDown();
- $("#floatControls input").each(function(i) {
- if (i != type) {
- $(this).attr("checked", false);
- }
- });
- }
-}
-
-/**
- * Changes the background color of the o3d container based on the current values
- * of the input fields bg-red, bg-green and bg-blue.
- */
-function updateClearColor() {
- function to255(a) {
- a = parseInt(a);
- if (isNaN(a)) {
- a = 0;
- }
- return Math.max(0, Math.min(255, a));
- }
- var red = to255($("#bg-red").val());
- var green = to255($("#bg-green").val());
- var blue = to255($("#bg-blue").val());
- $("#bg-red").val(red);
- $("#bg-green").val(green);
- $("#bg-blue").val(blue);
-
- // Convert back to [0, 1] for o3d.
- g_viewInfo.clearBuffer.clearColor = [red / 255, green / 255, blue / 255, 1.0];
-}
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/js/environment.js b/o3d/samples/o3d-webgl-samples/bubbles/js/environment.js
deleted file mode 100644
index 773f625..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/js/environment.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-var bsh = bsh || {};
-
-/**
- * Creates a cubemap texture object given six faces of the cube.
- * @param {!Array.<HTMLElementImage>} images An array of 6 HTML image elements,
- * representing the six faces of the cubemap. Should be in X+, X-, Y+, Y-, Z+,
- * Z- order.
- * @constructor
- */
-bsh.Environment = function(images) {
- if (images.length != 6) {
- throw 'Expecting six cube map faces.';
- }
- var rawDataArray = [];
- for (var i = 0; i < 6; ++i) {
- var rawData = g_pack.createObject('RawData');
- // TODO(luchen): Change this once textureCUBE set() is implemented
- rawData.image_ = images[i];
- rawData.width = 64;
- rawData.height = 64;
- rawDataArray.push(rawData);
- }
- this.texture =
- o3djs.texture.createTextureFromRawDataArray(g_pack, rawDataArray, true);
-}
-
-/**
- * The created texture.
- * @type {o3d.TextureCUBE}
- */
-bsh.Environment.prototype.texture = null;
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/js/iridescence.js b/o3d/samples/o3d-webgl-samples/bubbles/js/iridescence.js
deleted file mode 100644
index 61eee5b..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/js/iridescence.js
+++ /dev/null
@@ -1,223 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-var bsh = bsh || {};
-
-
-/**
- * Creates a canvas element that contains the interference pattern colors, to
- * be used as a texture. Once set, the width and height cannot be changed.
- *
- * @param {number} width The width of the texture (should be power-of-two).
- * @param {number} height The height of the texture (should be power-of-two).
- * @param {number} refraction_index The refraction index of the medium.
- * @param {number} thickness The thickness of the medium between the interfaces.
- * @constructor
- */
-bsh.Iridescence = function(width, height, refraction_index, thickness) {
- this.canvas = document.createElement('canvas');
- this.canvas.width = width;
- this.canvas.height = height;
- this.init(refraction_index, thickness);
-};
-
-
-/**
- * The canvas element that is written to.
- * @type {Canvas}
- */
-bsh.Iridescence.prototype.canvas = null;
-
-
-/**
- * Computes the fresnel coefficients for amplitude.
- * http://physics.tamuk.edu/~suson/html/4323/prop-em.html has them.
- * @param {number} n
- * @param {number} cos_i
- * @param {number} cos_t
- * @return {Object} object containing reflection and transmitted values.
- */
-bsh.Iridescence.ComputeFresnel = function(n, cos_i, cos_t) {
- var coeff = {};
- coeff.reflected_perp = (cos_i - n*cos_t)/(cos_i + n*cos_t);
- coeff.transmitted_perp = 2.0*cos_i/(cos_i + n*cos_t);
- coeff.reflected_para = (n*cos_i - cos_t)/(n*cos_i + cos_t);
- coeff.transmitted_para = 2.0*cos_i/(n*cos_i + cos_t);
- return coeff;
-}
-
-
-/**
- * Uses Snell-Descartes' Law: sin_i = n * sin_t
- * @param {number} n
- * @param {number} cos_i
- * @return {number}
- */
-bsh.Iridescence.RefractedRay = function(n, cos_i) {
- var sin2_i = 1 - cos_i * cos_i;
- var sin2_t = sin2_i / (n*n);
- var cos2_t = 1 - sin2_t;
- var cos_t = Math.sqrt(Math.max(0, cos2_t));
- return cos_t;
-}
-
-
-/**
- * Understanding the notations in the following two functions.
- *
- * \ A \ A' / B i = incident angle.
- * incident ray \ \ / t = transmitted angle.
- * \ i| \ i|i /
- * \| \|/ air (n = 1) outside the bubble
- * -outer-interface----P---------R---------------------------------------
- * |\ /| ^
- * |t\ /t| |thin layer (e.g. water, n > 1)
- * transmitted ray \t|t/ |thickness
- * \|/ v
- * -inner-interface---------Q--------------------------------------------
- * |\ air (n = 1) inside the bubble
- * |i \
- * \ C
- *
- * Incident ray A gets refracted by the outer interface at point P, then
- * reflected by the inner interface at point Q, then refracted into B at point
- * R ("trt" ray). At the same time, incident ray A', coherent with A, gets
- * directly reflected into B ("r" ray) at point R, so it interferes with the
- * "trt" ray.
- * At point Q the ray also gets refracted inside the bubble, leading to the
- * "tt" ray C.
- */
-
-/**
- * Computes the interference between the reflected ray ('r' - one reflection
- * one the outer interface) and the reflection of the transmitted ray ('trt' -
- * transmitted through the outer interface, reflected on the inner interface,
- * then transmitted again through the outer interface).
- * @param {number} thickness The thickness of the medium between the interfaces.
- * @param {number} wavelength The wavelength of the incident light.
- * @param {number} n The refraction index of the medium (relative to the outer
- * medium).
- * @param {number} r_perp The amplitude coefficient for the r ray for
- * perpendicular polarization.
- * @param {number} r_para The amplitude coefficient for the r ray for parallel
- * polarization.
- * @param {number} trt_perp The amplitude coefficient for the trt ray for
- * perpendicular polarization.
- * @param {number} trt_para The amplitude coefficient for the trt ray for
- * parallel polarization.
- * @param {number} cos_t The cosine of the refracted angle.
- * @return {number} The reflected power after interference.
- */
-bsh.Iridescence.Interference = function(thickness,
- wavelength,
- n,
- r_perp,
- r_para,
- trt_perp,
- trt_para,
- cos_t) {
- // Difference in wave propagation between the trt ray and the r ray.
- var delta_phase = 2.0 * thickness/wavelength * n * cos_t;
- // For a given polarization, power = ||r + trt * e^(i*2*pi*delta_phase)||^2
- var cos_delta = Math.cos(2.0 * kPi * delta_phase);
- var power_perp =
- r_perp*r_perp + trt_perp*trt_perp + 2.0 * r_perp*trt_perp*cos_delta;
- var power_para =
- r_para*r_para + trt_para*trt_para + 2.0 * r_para*trt_para*cos_delta;
- // Total power is the average between 2 polarization modes (for non-polarized
- // light).
- return (power_perp+power_para)/2.0;
-}
-
-
-/**
- * Regenerates and writes iridescence map to the canvas element.
- * @param {number} refraction_index The refraction index of the medium.
- * @param {number} thickness The thickness of the medium between the interfaces.
- */
-bsh.Iridescence.prototype.init = function(refraction_index, thickness) {
- var kRedWavelength = bsh.Globals.kRedWavelength;
- var kGreenWavelength = bsh.Globals.kGreenWavelength;
- var kBlueWavelength = bsh.Globals.kBlueWavelength;
- var width = this.canvas.width;
- var height = this.canvas.height;
- var n = refraction_index;
- var max_thickness = thickness * 1.5;
- var ctx = this.canvas.getContext('2d');
-
- var counter = 0;
- var imageData = ctx.getImageData(0, 0, width, height);
- for (var y = 0; y < height; ++y) {
- var thickness = (y + .5) * max_thickness / height;
- for (var x = 0; x < width; ++x) {
- var cos_i = (x + .5) * 1.0 / width;
- var cos_t = bsh.Iridescence.RefractedRay(n, cos_i);
- // Fresnel coefficient for the "outer" interface (outside->inside).
- var outer = bsh.Iridescence.ComputeFresnel(n, cos_i, cos_t);
- // Fresnel coefficient for the "inner" interface (inside->outside).
- var inner = bsh.Iridescence.ComputeFresnel(1.0/n, cos_t, cos_i);
- var r_perp = outer.reflected_perp;
- var r_para = outer.reflected_para;
- var trt_perp = outer.transmitted_perp * inner.reflected_perp *
- inner.transmitted_perp;
- var trt_para = outer.transmitted_para * inner.reflected_para *
- inner.transmitted_para;
- var red = bsh.Iridescence.Interference(thickness, kRedWavelength, n,
- r_perp, r_para, trt_perp, trt_para, cos_t);
- var green = bsh.Iridescence.Interference(thickness, kGreenWavelength, n,
- r_perp, r_para, trt_perp, trt_para, cos_t);
- var blue = bsh.Iridescence.Interference(thickness, kBlueWavelength, n,
- r_perp, r_para, trt_perp, trt_para, cos_t);
- var tt_perp = outer.transmitted_perp * inner.transmitted_perp;
- var tt_para = outer.transmitted_para * inner.transmitted_para;
- var alpha = (tt_perp*tt_perp + tt_para*tt_para)/2.0;
- imageData.data[counter++] = bsh.clamp(red);
- imageData.data[counter++] = bsh.clamp(green);
- imageData.data[counter++] = bsh.clamp(blue);
- imageData.data[counter++] = bsh.clamp(alpha);
- }
- }
- ctx.putImageData(imageData, 0, 0);
-}
-
-
-/**
- * Copies the data from the canvas into the texture.
- * @param {o3d.Texture} texture The texture to write to. Should be same size.
- */
-bsh.Iridescence.prototype.refresh = function(texture) {
- var data = this.canvas.getContext('2d').getImageData(0, 0, this.canvas.width,
- this.canvas.height).data;
- var pixels = [];
- for (var i = 0; i < data.length; ++i) {
- pixels[i] = data[i] / 255.0;
- }
- texture.set(0, pixels);
-}
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/js/main.js b/o3d/samples/o3d-webgl-samples/bubbles/js/main.js
deleted file mode 100644
index f7500f3e48..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/js/main.js
+++ /dev/null
@@ -1,270 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.arcball');
-
-// Events
-// Run the init() function once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// Global variables.
-var g_o3d;
-var g_math;
-var g_quaternions;
-var g_client;
-var g_o3dElement;
-var g_viewInfo;
-var g_pack;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-var g_dataroot;
-var g_camera = {};
-var g_aball;
-var g_demo;
-var g_clock = null;
-var g_dragging = false;
-var g_eyeParam;
-var g_controls;
-var g_done = false;
-var g_useCubeMap;
-var g_blipDistortion;
-var g_blendTwice;
-
-/**
- * Initializes the o3d clients.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-
-/**
- * Initializes O3D and sets up an instance of BubbleDemo.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Create a g_pack to manage our resources/assets
- g_pack = g_client.createPack();
- g_quaternions = o3djs.quaternions;
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot,
- [0.93, 0.93, 0.93, 1]
- );
-
- // Set the clear color to the default set in the HTML input fields.
- updateClearColor();
-
- // Sort method for the draw pass.
- g_viewInfo.performanceDrawPass.sortMethod = g_o3d.DrawList.BY_Z_ORDER;
-
- // Set some blending states.
- var state = g_viewInfo.performanceDrawPassInfo.state;
- state.getStateParam('SourceBlendFunction').value = g_o3d.State.BLENDFUNC_ONE;
- state.getStateParam('DestinationBlendFunction').value =
- g_o3d.State.BLENDFUNC_SOURCE_ALPHA;
- state.getStateParam('BlendEquation').value = g_o3d.State.BLEND_ADD;
- state.getStateParam('SeparateAlphaBlendEnable').value = false;
- state.getStateParam('AlphaBlendEnable').value = true;
-
- state.getStateParam('ZEnable').value = false;
- state.getStateParam('ZWriteEnable').value = false;
-
- // By default, cull all the back faces.
- state.getStateParam('CullMode').value = g_o3d.State.CULL_CW;
-
- // Creates a transform to put our data in.
- g_dataroot = g_pack.createObject('Transform');
- g_dataroot.parent = g_client.root;
-
- // Create some of the uniforms for the shaders.
- var paramObject = g_pack.createObject('ParamObject');
- g_eyeParam = paramObject.createParam('eye', 'ParamFloat4');
- g_camera.target = [0, 0, 0];
- g_camera.eye = [0, 0, 5];
- updateCamera();
- // Create a timer/clock.
- g_clock = paramObject.createParam('timer', 'ParamFloat');
- g_clock.value = 0;
- // Use the environment map?
- g_useCubeMap = paramObject.createParam('useCubeMap', 'ParamBoolean');
- g_useCubeMap.value = true;
- // Should shader effect be amplified for more vibrant bubbles?
- g_blendTwice = paramObject.createParam('blendTwice', 'ParamBoolean');
- g_blendTwice.value = true;
- // Number, location and overall effect of the modulation map.
- g_blipDistortion = paramObject.createParam('distortion', 'ParamFloat');
- g_blipDistortion.value = bsh.Globals.kBlipDistortion;
-
- // Create an arcball for scene rotations.
- g_lastRot = g_math.matrix4.identity();
- g_thisRot = g_math.matrix4.identity();
- g_aball = o3djs.arcball.create(100, 100);
- setClientSize();
-
- // Create the demo - all the geometry and shaders get set up here.
- var shaderString = document.getElementById('shader').value;
- g_demo = new BubbleDemo(shaderString);
- buildControls();
-
- // Add event listeners.
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', startDragging);
- o3djs.event.addEventListener(g_o3dElement, 'mousemove', drag);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', stopDragging);
- o3djs.event.addEventListener(g_o3dElement, 'wheel', scrollMe);
-
- g_client.setRenderCallback(onRender);
-}
-
-
-/**
- * Generates the projection matrix based on the size of the o3d plugin
- * and calculates the view-projection matrix.
- */
-function onRender(event) {
- g_clock.value += (event.elapsedTime);
- g_demo.update();
- setClientSize();
- if (!g_done) {
- g_done = true;
- // Hide the loading label.
- $("#loading").slideUp(1000);
- }
-}
-
-
-/**
- * Checks to see if the o3d container size has changed, and if so, adjusts
- * the projection matrix accordingaly.
- */
-function setClientSize() {
- var newWidth = parseInt(g_client.width);
- var newHeight = parseInt(g_client.height);
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- // Update the projection matrix.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), g_o3dWidth / g_o3dHeight, 0.1, 1000);
-
- // Sets a new area size for arcball.
- g_aball.setAreaSize(g_o3dWidth, g_o3dHeight);
- }
-}
-
-
-/**
- * Called on mousedown to signify a drag.
- */
-function startDragging(e) {
- g_lastRot = g_thisRot;
- g_aball.click([e.x, e.y]);
- g_dragging = true;
-}
-
-
-/**
- * Rotates the scene as the user is dragging the mouse.
- */
-function drag(e) {
- if (g_dragging) {
- var rotationQuat = g_aball.drag([e.x, e.y]);
- var rot_mat = g_quaternions.quaternionToRotation(rotationQuat);
- g_thisRot = g_math.matrix4.mul(g_lastRot, rot_mat);
-
- var m = g_dataroot.localMatrix;
- g_math.matrix4.setUpper3x3(m, g_thisRot);
- g_dataroot.localMatrix = m;
- }
-}
-
-
-/**
- * Called on mouseup.
- */
-function stopDragging(e) {
- g_dragging = false;
-}
-
-
-/**
- * Zooms in and out of the scene on scrollwheel event.
- */
-function scrollMe(e) {
- var t = (e.deltaY > 0) ? 11 / 12 : 13 /12;
- if (e.deltaY) {
- var t = (e.deltaY > 0) ? 11 / 12 : 13 /12;
- g_camera.eye = g_math.lerpVector(g_camera.target, g_camera.eye, t);
- updateCamera();
- }
-}
-
-
-/**
- * Updates the view matrix. Should be called whenever the camera position or
- * target has changed.
- */
-function updateCamera() {
- var up = [0, 1, 0];
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(g_camera.eye,
- g_camera.target,
- up);
- g_eyeParam.value = g_camera.eye;
-}
-
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/js/modulation.js b/o3d/samples/o3d-webgl-samples/bubbles/js/modulation.js
deleted file mode 100644
index bb9ce3a..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/js/modulation.js
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-var bsh = bsh || {};
-
-/**
- * Creates a canvas element that contains the geometry modulations. Modulations
- * are represented as radial gradient "blips" drawn on the canvas. Once set,
- * the width and height of the texture cannot be changed.
- *
- * @param {number} width The width of the texture (should be power-of-two).
- * @param {number} height The height of the texture (should be power-of-two).
- * @param {!Array.<number>} bounds An array [min, max] for blip radius.
- * @param {number} blips The number of spots to modulate.
- * @constructor
- */
-bsh.Modulation = function(width, height, bounds, blips) {
- this.canvas = document.createElement('canvas');
- this.canvas.width = width;
- this.canvas.height = height;
- this.init(bounds, blips);
-};
-
-/**
- * The canvas element that is written to.
- * @type {Canvas}
- */
-bsh.Modulation.prototype.canvas = null;
-
-/**
- * Creates a gradient with the provided position and radius.
- * @param {number} x x-coordinate of the blip center.
- * @param {number} y y-coordinate of the blip center.
- * @param {number} r Radius of the blip.
- * @param {CanvasRenderingContext2D} ctx The 2d drawing context.
- * @return {CanvasGradient}
- */
-bsh.Modulation.makeGradient = function(x, y, r, ctx) {
- var radgrad = ctx.createRadialGradient(x, y, 0, x, y, r);
- radgrad.addColorStop(0, '#FFFFFF');
- radgrad.addColorStop(1, 'rgba(0, 0, 0, 0)');
- return radgrad;
-}
-
-/**
- * Regenerates the texture and writes to the canvas element.
- * @param {!Array.<number>} bounds An array containing [min, max] of the radius
- * of the blips.
- * @param {number} blips Number of blips.
- */
-bsh.Modulation.prototype.init = function(bounds, blips) {
- var ctx = this.canvas.getContext('2d');
- var width = this.canvas.width;
- var height = this.canvas.height;
-
- // Reset to opaque black first.
- ctx.fillStyle = "rgba(0, 0, 0, 1)";
- ctx.fillRect(0, 0, width, height);
- var r = bounds;
- var x = [r[1] / 1.5, width - r[1] / 1.5];
- var y = x;
-
- for (var i = 0; i < blips; ++i) {
- var posX = randf(x[0], x[1]);
- var posY = randf(y[0], y[1]);
- var radius = randf(r[0], r[1]);
- ctx.fillStyle = bsh.Modulation.makeGradient(posX, posY, radius, ctx);
- ctx.fillRect(0, 0, width, height);
- }
-}
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/js/noise.js b/o3d/samples/o3d-webgl-samples/bubbles/js/noise.js
deleted file mode 100644
index add6934..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/js/noise.js
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-var bsh = bsh || {};
-
-
-/**
- * Generates a perlin noise texture. The width and height cannot be changed
- * after construction.
- *
- * @param {number} frequency Frequency of the texture.
- * @param {number} seed A seed for random values.
- * @param {number} width The width of the texture (should be power-of-two).
- * @param {number} height The height of the texture (should be power-of-two).
- * @constructor
- */
-bsh.Perlin = function(frequency, seed, width, height) {
- this.canvas = document.createElement('canvas');
- this.canvas.width = width;
- this.canvas.height = height;
- this.init(frequency, seed);
-}
-
-
-/**
- * The canvas that stores the texture.
- * @type {Canvas}
- */
-bsh.Perlin.prototype.canvas = null;
-
-
-/**
- * The frequency
- * @type {number}
- */
-bsh.Perlin.prototype.frequency = null;
-
-
-/**
- * An array that contains the perlin noise values before adding attenuation at
- * the poles.
- * @type {!Array.<number>}
- * @private
- */
-bsh.Perlin.prototype.values_ = [];
-
-
-/**
- * Permutation array.
- * @type {!Array.<number>}
- * @private
- */
-bsh.Perlin.prototype.permutation_ = [];
-
-
-/**
- * Gradient array.
- * @type {!Array.<number>}
- * @private
- */
-bsh.Perlin.prototype.gradients_ = [];
-
-
-/**
- * Generates and writes the perlin noise into the canvas element.
- * @param {number} frequency Frequency of the texture.
- * @param {number} seed A seed for random values.
- */
-bsh.Perlin.prototype.init = function(frequency, seed) {
- this.frequency = frequency;
- this.values_ = [];
- this.permutation_ = [];
- this.gradients_ = [];
-
- this.prep_(seed);
- this.generate_();
-
- var ctx = this.canvas.getContext('2d');
- var width = this.canvas.width;
- var height = this.canvas.height;
- var imageData = ctx.getImageData(0, 0, width, height);
- var counter = 0;
- for (var y = 0; y < height; ++y) {
- // Attenuate the noise value with a function that goes to 0 on the poles to
- // avoid discontinuities.
- // Note: it'd be better to have a 3D noise texture, but they are way
- // too expensive.
- var attenuation = Math.sin(y * kPi / height);
- for (var x = 0; x < width; ++x) {
- var attenuated_value = this.values_[y * width + x] * attenuation;
- // remap [-1..1] to [0..1] and convert to color values.
- var value = bsh.clamp(attenuated_value * 0.5 + 0.5);
- imageData.data[counter++] = value;
- imageData.data[counter++] = value;
- imageData.data[counter++] = value;
- imageData.data[counter++] = value;
- }
- }
- ctx.putImageData(imageData, 0, 0);
-}
-
-
-/**
- * Initializes the values, permutation and gradients arrays that are used by the
- * generate method.
- * @param {number} seed A seed for random values.
- * @private
- */
-bsh.Perlin.prototype.prep_ = function(seed) {
- //Initialize the gradients table with a random unit direction.
- // Initialize the permutation table to be the identity.
- for (var i = 0; i < this.frequency; ++i) {
- var theta = Math.random() * (2.0 * kPi);
- this.gradients_[i] = [Math.cos(theta), Math.sin(theta)];
- this.permutation_[i] = i;
- }
- // Generate the permutation table by switching each element with a further
- // element. Also duplicate the permutation table so that constructs like
- // permutation[x + permutation[y]] work without additional modulo.
- for (var i = 0; i < this.frequency; ++i) {
- var j = i + (Math.floor(Math.random() * seed) % (this.frequency - i));
- var tmp = this.permutation_[j];
- this.permutation_[j] = this.permutation_[i];
- this.permutation_[i] = tmp;
- this.permutation_[i + this.frequency] = tmp;
- }
-}
-
-/**
- * Generates the perlin noise texture into the values_ array.
- * @private
- */
-bsh.Perlin.prototype.generate_ = function() {
- var width = this.canvas.width;
- var height = this.canvas.height;
- var counter = 0;
- for (var y = 0; y < height; ++y) {
- for (var x = 0; x < width; ++x) {
- // The texture is decomposed into a lattice of frequency_ points in each
- // direction. A (x, y) point falls between 4 lattice vertices.
- // (xx, yy) are the coordinate of the bottom left lattice vertex
- // corresponding to an (x, y) image point.
- var xx = Math.floor((x * this.frequency) / width);
- var yy = Math.floor((y * this.frequency) / height);
- // xt and yt are the barycentric coordinates of the (x, y) point relative
- // to the vertices (between 0 and 1).
- var xt = 1.0/width * ((x * this.frequency) % width);
- var yt = 1.0/height * ((y * this.frequency) % height);
- // contribution of each lattice vertex to the point value.
- var contrib = [];
- for (var y_offset = 0; y_offset < 2; ++y_offset) {
- for (var x_offset = 0; x_offset < 2; ++x_offset) {
- var index = this.permutation_[xx + x_offset] + y_offset + yy;
- var gradient = this.gradients_[this.permutation_[index]];
- contrib[y_offset*2+x_offset] = gradient[0] * (xt - x_offset) +
- gradient[1] * (yt - y_offset);
- }
- }
- // We interpolate between the vertex contributions using a smooth step
- // function of the barycentric coordinates.
- var xt_smooth = bsh.smoothStep(xt);
- var yt_smooth = bsh.smoothStep(yt);
- var contrib_bottom = bsh.lerp(xt_smooth, contrib[0], contrib[1]);
- var contrib_top = bsh.lerp(xt_smooth, contrib[2], contrib[3]);
- var sq = bsh.lerp(yt_smooth, contrib_bottom, contrib_top);
- this.values_[counter++] = sq;
- }
- }
-}
-
-/**
- * Copies the data from the canvas into the texture.
- * @param {o3d.Texture} texture The texture to. Should be same size.
- */
-bsh.Perlin.prototype.refresh = function(texture) {
- var data = this.canvas.getContext('2d').getImageData(0, 0, this.canvas.width,
- this.canvas.height).data;
- var pixels = [];
- for (var i = 0; i < data.length; ++i) {
- pixels[i] = data[i] / 255.0;
- }
- texture.set(0, pixels);
-}
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/AUTHORS.txt b/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/AUTHORS.txt
deleted file mode 100644
index b216865..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/AUTHORS.txt
+++ /dev/null
@@ -1,30 +0,0 @@
-jQuery UI Authors (http://jqueryui.com/about)
-
-This software consists of voluntary contributions made by many
-individuals. For exact contribution history, see the revision history
-and logs, available at http://github.com/jquery/jquery-ui
-
-Brandon Aaron
-Paul Bakaus (paulbakaus.com)
-David Bolter
-Rich Caloggero
-Chi Cheng (cloudream@gmail.com)
-Colin Clark (http://colin.atrc.utoronto.ca/)
-Michelle D'Souza
-Aaron Eisenberger (aaronchi@gmail.com)
-Ariel Flesler
-Bohdan Ganicky
-Scott González
-Marc Grabanski (m@marcgrabanski.com)
-Klaus Hartl (stilbuero.de)
-Scott Jehl
-Cody Lindley
-Eduardo Lundgren (eduardolundgren@gmail.com)
-Todd Parker
-John Resig
-Patty Toland
-Ca-Phun Ung (yelotofu.com)
-Keith Wood (kbwood@virginbroadband.com.au)
-Maggie Costello Wachs
-Richard D. Worth (rdworth.org)
-Jörn Zaefferer (bassistance.de)
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/MIT-LICENSE.txt b/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/MIT-LICENSE.txt
deleted file mode 100644
index 2585de2..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/MIT-LICENSE.txt
+++ /dev/null
@@ -1,25 +0,0 @@
-Copyright (c) 2010 Paul Bakaus, http://jqueryui.com/
-
-This software consists of voluntary contributions made by many
-individuals (AUTHORS.txt, http://jqueryui.com/about) For exact
-contribution history, see the revision history and logs, available
-at http://jquery-ui.googlecode.com/svn/
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/README.o3d b/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/README.o3d
deleted file mode 100644
index 949a42a..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/README.o3d
+++ /dev/null
@@ -1,7 +0,0 @@
-This directory contains the jQuery library and a customized subset of the
-jQuery UI library, available at http://jquery.com and http://jqueryui.com/,
-licensed under the General Public License (GPL) Version 2 and MIT licenses.
-
-The provided CSS stylesheet(s) (css/*.css) have been modified to remove
-unneeded style rules and image dependencies. The remaining code is otherwise
-unmodified.
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/css/jquery-ui-1.8.4.custom.css b/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/css/jquery-ui-1.8.4.custom.css
deleted file mode 100644
index 550eb93..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/css/jquery-ui-1.8.4.custom.css
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * jQuery UI CSS Framework @VERSION
- *
- * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
- * Dual licensed under the MIT or GPL Version 2 licenses.
- * http://jquery.org/license
- *
- * http://docs.jquery.com/UI/Theming/API
- */
-
-/* Layout helpers
-----------------------------------*/
-.ui-helper-hidden { display: none; }
-.ui-helper-hidden-accessible { position: absolute; left: -99999999px; }
-.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; }
-.ui-helper-clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
-.ui-helper-clearfix { display: inline-block; }
-/* required comment for clearfix to work in Opera \*/
-* html .ui-helper-clearfix { height:1%; }
-.ui-helper-clearfix { display:block; }
-/* end clearfix */
-.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); }
-
-
-/* Interaction Cues
-----------------------------------*/
-.ui-state-disabled { cursor: default !important; }
-
-
-/* Icons
-----------------------------------*/
-
-/* states and images */
-.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; }
-
-
-/* Misc visuals
-----------------------------------*/
-
-/* Overlays */
-.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
-
-
-/*
- * jQuery UI CSS Framework @VERSION
- *
- * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
- * Dual licensed under the MIT or GPL Version 2 licenses.
- * http://jquery.org/license
- *
- * http://docs.jquery.com/UI/Theming/API
- *
- * To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Trebuchet%20MS,%20Tahoma,%20Verdana,%20Arial,%20sans-serif&fwDefault=bold&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=f6a828&bgTextureHeader=12_gloss_wave.png&bgImgOpacityHeader=35&borderColorHeader=e78f08&fcHeader=ffffff&iconColorHeader=ffffff&bgColorContent=eeeeee&bgTextureContent=03_highlight_soft.png&bgImgOpacityContent=100&borderColorContent=dddddd&fcContent=333333&iconColorContent=222222&bgColorDefault=f6f6f6&bgTextureDefault=02_glass.png&bgImgOpacityDefault=100&borderColorDefault=cccccc&fcDefault=1c94c4&iconColorDefault=ef8c08&bgColorHover=fdf5ce&bgTextureHover=02_glass.png&bgImgOpacityHover=100&borderColorHover=fbcb09&fcHover=c77405&iconColorHover=ef8c08&bgColorActive=ffffff&bgTextureActive=02_glass.png&bgImgOpacityActive=65&borderColorActive=fbd850&fcActive=eb8f00&iconColorActive=ef8c08&bgColorHighlight=ffe45c&bgTextureHighlight=03_highlight_soft.png&bgImgOpacityHighlight=75&borderColorHighlight=fed22f&fcHighlight=363636&iconColorHighlight=228ef1&bgColorError=b81900&bgTextureError=08_diagonals_thick.png&bgImgOpacityError=18&borderColorError=cd0a0a&fcError=ffffff&iconColorError=ffd27a&bgColorOverlay=666666&bgTextureOverlay=08_diagonals_thick.png&bgImgOpacityOverlay=20&opacityOverlay=50&bgColorShadow=000000&bgTextureShadow=01_flat.png&bgImgOpacityShadow=10&opacityShadow=20&thicknessShadow=5px&offsetTopShadow=-5px&offsetLeftShadow=-5px&cornerRadiusShadow=5px
- */
-
-
-/* Component containers
-----------------------------------*/
-.ui-widget { font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; font-size: 1.1em; }
-.ui-widget .ui-widget { font-size: 1em; }
-.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; font-size: 1em; }
-.ui-widget-content { border: 1px solid #dddddd; background: #eeeeee; color: #333333; }
-.ui-widget-content a { color: #333333; }
-.ui-widget-header { border: 1px solid #e78f08; background: #f6a828; color: #ffffff; font-weight: bold; }
-.ui-widget-header a { color: #ffffff; }
-
-/* Interaction states
-----------------------------------*/
-.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; background: #f6f6f6; font-weight: bold; color: #1c94c4; }
-.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #1c94c4; text-decoration: none; }
-.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #fbcb09; background: #fdf5ce; font-weight: bold; color: #c77405; }
-.ui-state-hover a, .ui-state-hover a:hover { color: #c77405; text-decoration: none; }
-.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #fbd850; background: #ffffff; font-weight: bold; color: #eb8f00; }
-.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #eb8f00; text-decoration: none; }
-.ui-widget :active { outline: none; }
-
-/* Interaction Cues
-----------------------------------*/
-.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {border: 1px solid #fed22f; background: #ffe45c url(images/ui-bg_highlight-soft_75_ffe45c_1x100.png) 50% top repeat-x; color: #363636; }
-.ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #363636; }
-.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #cd0a0a; background: #b81900 url(images/ui-bg_diagonals-thick_18_b81900_40x40.png) 50% 50% repeat; color: #ffffff; }
-.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #ffffff; }
-.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #ffffff; }
-.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; }
-.ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; }
-.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; }
-
-/* Misc visuals
-----------------------------------*/
-
-/* Corner radius */
-.ui-corner-tl { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; border-top-left-radius: 4px; }
-.ui-corner-tr { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; border-top-right-radius: 4px; }
-.ui-corner-bl { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; border-bottom-left-radius: 4px; }
-.ui-corner-br { -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; border-bottom-right-radius: 4px; }
-.ui-corner-top { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; border-top-left-radius: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; border-top-right-radius: 4px; }
-.ui-corner-bottom { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; border-bottom-left-radius: 4px; -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; border-bottom-right-radius: 4px; }
-.ui-corner-right { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; border-top-right-radius: 4px; -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; border-bottom-right-radius: 4px; }
-.ui-corner-left { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; border-top-left-radius: 4px; -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; border-bottom-left-radius: 4px; }
-.ui-corner-all { -moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px; }
-/*
- * jQuery UI Slider @VERSION
- *
- * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
- * Dual licensed under the MIT or GPL Version 2 licenses.
- * http://jquery.org/license
- *
- * http://docs.jquery.com/UI/Slider#theming
- */
-.ui-slider { position: relative; text-align: left; }
-.ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; }
-.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; }
-
-.ui-slider-horizontal { height: .8em; }
-.ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; }
-.ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; }
-.ui-slider-horizontal .ui-slider-range-min { left: 0; }
-.ui-slider-horizontal .ui-slider-range-max { right: 0; }
-
-.ui-slider-vertical { width: .8em; height: 100px; }
-.ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; }
-.ui-slider-vertical .ui-slider-range { left: 0; width: 100%; }
-.ui-slider-vertical .ui-slider-range-min { bottom: 0; }
-.ui-slider-vertical .ui-slider-range-max { top: 0; }
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/jquery-1.4.2.min.js b/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/jquery-1.4.2.min.js
deleted file mode 100644
index 7c24308..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/jquery-1.4.2.min.js
+++ /dev/null
@@ -1,154 +0,0 @@
-/*!
- * jQuery JavaScript Library v1.4.2
- * http://jquery.com/
- *
- * Copyright 2010, John Resig
- * Dual licensed under the MIT or GPL Version 2 licenses.
- * http://jquery.org/license
- *
- * Includes Sizzle.js
- * http://sizzlejs.com/
- * Copyright 2010, The Dojo Foundation
- * Released under the MIT, BSD, and GPL Licenses.
- *
- * Date: Sat Feb 13 22:33:48 2010 -0500
- */
-(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i?
-e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r=
-j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g,
-"&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e=
-true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/,
-Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&&
-(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this,
-a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b===
-"find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,
-function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)||
-c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded",
-L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype,
-"isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+
-a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f],
-d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]===
-a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&&
-!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari=
-true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
-var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected,
-parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent=
-false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n=
-s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true,
-applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando];
-else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,
-a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===
-w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i,
-cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ",
-i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ",
-" ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=
-this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i=
-e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected=
-c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");
-a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g,
-function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split(".");
-k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a),
-C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!=
-null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=
-e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&&
-f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;
-if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
-fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
-d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this,
-"events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=
-a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y,
-isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit=
-{setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};
-if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",
-e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,
-"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a,
-d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&
-!a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}},
-toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector,
-u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),
-function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];
-if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
-e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift();
-t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D||
-g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[];
-for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length-
-1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
-CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},
-relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]=
-l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[];
-h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},
-CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m,
-g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},
-text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},
-setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h=
-h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m=
-m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m===
-"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g,
-h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition||
-!h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m=
-h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&&
-q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>";
-if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}();
-(function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}:
-function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/,
-gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length;
-c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j=
-{},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a===
-"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",
-d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?
-a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType===
-1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)?
-a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=
-c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},
-wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},
-prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,
-this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild);
-return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja,
-""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&
-this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]||
-u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length===
-1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]);
-return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["",
-""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e=
-c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]?
-c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja=
-function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=
-Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,
-"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=
-a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=
-a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!==
-"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this},
-serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),
-function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,
-global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&
-e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)?
-"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===
-false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B=
-false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since",
-c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E||
-d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x);
-g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===
-1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b===
-"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional;
-if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");
-this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],
-"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},
-animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing=
-j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);
-this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration===
-"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||
-c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;
-this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=
-this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,
-e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||
-c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement?
-function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=
-this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle;
-k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&&
-f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
-a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b);
-c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,
-d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-
-f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset":
-"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in
-e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);
diff --git a/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/jquery-ui-1.8.4.custom.min.js b/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/jquery-ui-1.8.4.custom.min.js
deleted file mode 100644
index 6cab644..0000000
--- a/o3d/samples/o3d-webgl-samples/bubbles/third_party/jquery/jquery-ui-1.8.4.custom.min.js
+++ /dev/null
@@ -1,83 +0,0 @@
-/*!
- * jQuery UI 1.8.4
- *
- * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
- * Dual licensed under the MIT or GPL Version 2 licenses.
- * http://jquery.org/license
- *
- * http://docs.jquery.com/UI
- */
-(function(c,j){function k(a){return!c(a).parents().andSelf().filter(function(){return c.curCSS(this,"visibility")==="hidden"||c.expr.filters.hidden(this)}).length}c.ui=c.ui||{};if(!c.ui.version){c.extend(c.ui,{version:"1.8.4",plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e=0;e<b.length;e++)a.options[b[e][0]]&&b[e][1].apply(a.element,d)}},contains:function(a,
-b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(a,b){if(c(a).css("overflow")==="hidden")return false;b=b&&b==="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a<b+d},isOver:function(a,b,d,e,h,i){return c.ui.isOverAxis(a,d,h)&&c.ui.isOverAxis(b,e,i)},keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,
-CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});c.fn.extend({_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus();b&&b.call(d)},a)}):this._focus.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable",
-"off").css("MozUserSelect","")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect","none")},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this,"position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this,
-"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==j)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position");if(b==="absolute"||b==="relative"||b==="fixed"){b=parseInt(a.css("zIndex"));if(!isNaN(b)&&b!=0)return b}a=a.parent()}}return 0}});c.each(["Width","Height"],function(a,b){function d(f,g,l,m){c.each(e,function(){g-=
-parseFloat(c.curCSS(f,"padding"+this,true))||0;if(l)g-=parseFloat(c.curCSS(f,"border"+this+"Width",true))||0;if(m)g-=parseFloat(c.curCSS(f,"margin"+this,true))||0});return g}var e=b==="Width"?["Left","Right"]:["Top","Bottom"],h=b.toLowerCase(),i={innerWidth:c.fn.innerWidth,innerHeight:c.fn.innerHeight,outerWidth:c.fn.outerWidth,outerHeight:c.fn.outerHeight};c.fn["inner"+b]=function(f){if(f===j)return i["inner"+b].call(this);return this.each(function(){c.style(this,h,d(this,f)+"px")})};c.fn["outer"+
-b]=function(f,g){if(typeof f!=="number")return i["outer"+b].call(this,f);return this.each(function(){c.style(this,h,d(this,f,true,g)+"px")})}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){var b=a.nodeName.toLowerCase(),d=c.attr(a,"tabindex");if("area"===b){b=a.parentNode;d=b.name;if(!a.href||!d||b.nodeName.toLowerCase()!=="map")return false;a=c("img[usemap=#"+d+"]")[0];return!!a&&k(a)}return(/input|select|textarea|button|object/.test(b)?!a.disabled:"a"==
-b?a.href||!isNaN(d):!isNaN(d))&&k(a)},tabbable:function(a){var b=c.attr(a,"tabindex");return(isNaN(b)||b>=0)&&c(a).is(":focusable")}})}})(jQuery);
-;/*!
- * jQuery UI Widget 1.8.4
- *
- * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
- * Dual licensed under the MIT or GPL Version 2 licenses.
- * http://jquery.org/license
- *
- * http://docs.jquery.com/UI/Widget
- */
-(function(b,j){var k=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add([this]).each(function(){b(this).triggerHandler("remove")});return k.call(b(this),a,c)})};b.widget=function(a,c,d){var e=a.split(".")[0],f;a=a.split(".")[1];f=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][f]=function(h){return!!b.data(h,a)};b[e]=b[e]||{};b[e][a]=function(h,g){arguments.length&&this._createWidget(h,g)};c=new c;c.options=b.extend(true,{},c.options);
-b[e][a].prototype=b.extend(true,c,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:f},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",f=Array.prototype.slice.call(arguments,1),h=this;d=!e&&f.length?b.extend.apply(null,[true,d].concat(f)):d;if(e&&d.substring(0,1)==="_")return h;e?this.each(function(){var g=b.data(this,a),i=g&&b.isFunction(g[d])?g[d].apply(g,f):g;if(i!==g&&i!==j){h=i;return false}}):
-this.each(function(){var g=b.data(this,a);if(g){d&&g.option(d);g._init()}else b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){b.data(c,this.widgetName,this);this.element=b(c);this.options=b.extend(true,{},this.options,b.metadata&&b.metadata.get(c)[this.widgetName],a);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()});
-this._create();this._init()},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(a,c){var d=a,e=this;if(arguments.length===0)return b.extend({},e.options);if(typeof a==="string"){if(c===j)return this.options[a];d={};d[a]=c}b.each(d,function(f,
-h){e._setOption(f,h)});return e},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=
-b.event.props.length;for(var f;a;){f=b.event.props[--a];c[f]=c.originalEvent[f]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery);
-;/*!
- * jQuery UI Mouse 1.8.4
- *
- * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
- * Dual licensed under the MIT or GPL Version 2 licenses.
- * http://jquery.org/license
- *
- * http://docs.jquery.com/UI/Mouse
- *
- * Depends:
- * jquery.ui.widget.js
- */
-(function(c){c.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var a=this;this.element.bind("mousedown."+this.widgetName,function(b){return a._mouseDown(b)}).bind("click."+this.widgetName,function(b){if(a._preventClickEvent){a._preventClickEvent=false;b.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName)},_mouseDown:function(a){a.originalEvent=a.originalEvent||{};if(!a.originalEvent.mouseHandled){this._mouseStarted&&
-this._mouseUp(a);this._mouseDownEvent=a;var b=this,e=a.which==1,f=typeof this.options.cancel=="string"?c(a.target).parents().add(a.target).filter(this.options.cancel).length:false;if(!e||f||!this._mouseCapture(a))return true;this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet)this._mouseDelayTimer=setTimeout(function(){b.mouseDelayMet=true},this.options.delay);if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a)){this._mouseStarted=this._mouseStart(a)!==false;if(!this._mouseStarted){a.preventDefault();
-return true}}this._mouseMoveDelegate=function(d){return b._mouseMove(d)};this._mouseUpDelegate=function(d){return b._mouseUp(d)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);c.browser.safari||a.preventDefault();return a.originalEvent.mouseHandled=true}},_mouseMove:function(a){if(c.browser.msie&&!a.button)return this._mouseUp(a);if(this._mouseStarted){this._mouseDrag(a);return a.preventDefault()}if(this._mouseDistanceMet(a)&&
-this._mouseDelayMet(a))(this._mouseStarted=this._mouseStart(this._mouseDownEvent,a)!==false)?this._mouseDrag(a):this._mouseUp(a);return!this._mouseStarted},_mouseUp:function(a){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=a.target==this._mouseDownEvent.target;this._mouseStop(a)}return false},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-
-a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return true}})})(jQuery);
-;/*
- * jQuery UI Slider 1.8.4
- *
- * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
- * Dual licensed under the MIT or GPL Version 2 licenses.
- * http://jquery.org/license
- *
- * http://docs.jquery.com/UI/Slider
- *
- * Depends:
- * jquery.ui.core.js
- * jquery.ui.mouse.js
- * jquery.ui.widget.js
- */
-(function(d){d.widget("ui.slider",d.ui.mouse,{widgetEventPrefix:"slide",options:{animate:false,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null},_create:function(){var a=this,b=this.options;this._mouseSliding=this._keySliding=false;this._animateOff=true;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all");b.disabled&&this.element.addClass("ui-slider-disabled ui-disabled");
-this.range=d([]);if(b.range){if(b.range===true){this.range=d("<div></div>");if(!b.values)b.values=[this._valueMin(),this._valueMin()];if(b.values.length&&b.values.length!==2)b.values=[b.values[0],b.values[0]]}else this.range=d("<div></div>");this.range.appendTo(this.element).addClass("ui-slider-range");if(b.range==="min"||b.range==="max")this.range.addClass("ui-slider-range-"+b.range);this.range.addClass("ui-widget-header")}d(".ui-slider-handle",this.element).length===0&&d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle");
-if(b.values&&b.values.length)for(;d(".ui-slider-handle",this.element).length<b.values.length;)d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle");this.handles=d(".ui-slider-handle",this.element).addClass("ui-state-default ui-corner-all");this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(c){c.preventDefault()}).hover(function(){b.disabled||d(this).addClass("ui-state-hover")},function(){d(this).removeClass("ui-state-hover")}).focus(function(){if(b.disabled)d(this).blur();
-else{d(".ui-slider .ui-state-focus").removeClass("ui-state-focus");d(this).addClass("ui-state-focus")}}).blur(function(){d(this).removeClass("ui-state-focus")});this.handles.each(function(c){d(this).data("index.ui-slider-handle",c)});this.handles.keydown(function(c){var e=true,f=d(this).data("index.ui-slider-handle"),h,g,i;if(!a.options.disabled){switch(c.keyCode){case d.ui.keyCode.HOME:case d.ui.keyCode.END:case d.ui.keyCode.PAGE_UP:case d.ui.keyCode.PAGE_DOWN:case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:e=
-false;if(!a._keySliding){a._keySliding=true;d(this).addClass("ui-state-active");h=a._start(c,f);if(h===false)return}break}i=a.options.step;h=a.options.values&&a.options.values.length?(g=a.values(f)):(g=a.value());switch(c.keyCode){case d.ui.keyCode.HOME:g=a._valueMin();break;case d.ui.keyCode.END:g=a._valueMax();break;case d.ui.keyCode.PAGE_UP:g=a._trimAlignValue(h+(a._valueMax()-a._valueMin())/5);break;case d.ui.keyCode.PAGE_DOWN:g=a._trimAlignValue(h-(a._valueMax()-a._valueMin())/5);break;case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:if(h===
-a._valueMax())return;g=a._trimAlignValue(h+i);break;case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:if(h===a._valueMin())return;g=a._trimAlignValue(h-i);break}a._slide(c,f,g);return e}}).keyup(function(c){var e=d(this).data("index.ui-slider-handle");if(a._keySliding){a._keySliding=false;a._stop(c,e);a._change(c,e);d(this).removeClass("ui-state-active")}});this._refreshValue();this._animateOff=false},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider");
-this._mouseDestroy();return this},_mouseCapture:function(a){var b=this.options,c,e,f,h,g;if(b.disabled)return false;this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();c=this._normValueFromMouse({x:a.pageX,y:a.pageY});e=this._valueMax()-this._valueMin()+1;h=this;this.handles.each(function(i){var j=Math.abs(c-h.values(i));if(e>j){e=j;f=d(this);g=i}});if(b.range===true&&this.values(1)===b.min){g+=1;f=d(this.handles[g])}if(this._start(a,
-g)===false)return false;this._mouseSliding=true;h._handleIndex=g;f.addClass("ui-state-active").focus();b=f.offset();this._clickOffset=!d(a.target).parents().andSelf().is(".ui-slider-handle")?{left:0,top:0}:{left:a.pageX-b.left-f.width()/2,top:a.pageY-b.top-f.height()/2-(parseInt(f.css("borderTopWidth"),10)||0)-(parseInt(f.css("borderBottomWidth"),10)||0)+(parseInt(f.css("marginTop"),10)||0)};this._slide(a,g,c);return this._animateOff=true},_mouseStart:function(){return true},_mouseDrag:function(a){var b=
-this._normValueFromMouse({x:a.pageX,y:a.pageY});this._slide(a,this._handleIndex,b);return false},_mouseStop:function(a){this.handles.removeClass("ui-state-active");this._mouseSliding=false;this._stop(a,this._handleIndex);this._change(a,this._handleIndex);this._clickOffset=this._handleIndex=null;return this._animateOff=false},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(a){var b;if(this.orientation==="horizontal"){b=
-this.elementSize.width;a=a.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{b=this.elementSize.height;a=a.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}b=a/b;if(b>1)b=1;if(b<0)b=0;if(this.orientation==="vertical")b=1-b;a=this._valueMax()-this._valueMin();return this._trimAlignValue(this._valueMin()+b*a)},_start:function(a,b){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b);
-c.values=this.values()}return this._trigger("start",a,c)},_slide:function(a,b,c){var e;if(this.options.values&&this.options.values.length){e=this.values(b?0:1);if(this.options.values.length===2&&this.options.range===true&&(b===0&&c>e||b===1&&c<e))c=e;if(c!==this.values(b)){e=this.values();e[b]=c;a=this._trigger("slide",a,{handle:this.handles[b],value:c,values:e});this.values(b?0:1);a!==false&&this.values(b,c,true)}}else if(c!==this.value()){a=this._trigger("slide",a,{handle:this.handles[b],value:c});
-a!==false&&this.value(c)}},_stop:function(a,b){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b);c.values=this.values()}this._trigger("stop",a,c)},_change:function(a,b){if(!this._keySliding&&!this._mouseSliding){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b);c.values=this.values()}this._trigger("change",a,c)}},value:function(a){if(arguments.length){this.options.value=
-this._trimAlignValue(a);this._refreshValue();this._change(null,0)}return this._value()},values:function(a,b){var c,e,f;if(arguments.length>1){this.options.values[a]=this._trimAlignValue(b);this._refreshValue();this._change(null,a)}if(arguments.length)if(d.isArray(arguments[0])){c=this.options.values;e=arguments[0];for(f=0;f<c.length;f+=1){c[f]=this._trimAlignValue(e[f]);this._change(null,f)}this._refreshValue()}else return this.options.values&&this.options.values.length?this._values(a):this.value();
-else return this._values()},_setOption:function(a,b){var c,e=0;if(d.isArray(this.options.values))e=this.options.values.length;d.Widget.prototype._setOption.apply(this,arguments);switch(a){case "disabled":if(b){this.handles.filter(".ui-state-focus").blur();this.handles.removeClass("ui-state-hover");this.handles.attr("disabled","disabled");this.element.addClass("ui-disabled")}else{this.handles.removeAttr("disabled");this.element.removeClass("ui-disabled")}break;case "orientation":this._detectOrientation();
-this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation);this._refreshValue();break;case "value":this._animateOff=true;this._refreshValue();this._change(null,0);this._animateOff=false;break;case "values":this._animateOff=true;this._refreshValue();for(c=0;c<e;c+=1)this._change(null,c);this._animateOff=false;break}},_value:function(){var a=this.options.value;return a=this._trimAlignValue(a)},_values:function(a){var b,c;if(arguments.length){b=this.options.values[a];
-return b=this._trimAlignValue(b)}else{b=this.options.values.slice();for(c=0;c<b.length;c+=1)b[c]=this._trimAlignValue(b[c]);return b}},_trimAlignValue:function(a){if(a<this._valueMin())return this._valueMin();if(a>this._valueMax())return this._valueMax();var b=this.options.step>0?this.options.step:1,c=a%b;a=a-c;if(Math.abs(c)*2>=b)a+=c>0?b:-b;return parseFloat(a.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var a=
-this.options.range,b=this.options,c=this,e=!this._animateOff?b.animate:false,f,h={},g,i,j,l;if(this.options.values&&this.options.values.length)this.handles.each(function(k){f=(c.values(k)-c._valueMin())/(c._valueMax()-c._valueMin())*100;h[c.orientation==="horizontal"?"left":"bottom"]=f+"%";d(this).stop(1,1)[e?"animate":"css"](h,b.animate);if(c.options.range===true)if(c.orientation==="horizontal"){if(k===0)c.range.stop(1,1)[e?"animate":"css"]({left:f+"%"},b.animate);if(k===1)c.range[e?"animate":"css"]({width:f-
-g+"%"},{queue:false,duration:b.animate})}else{if(k===0)c.range.stop(1,1)[e?"animate":"css"]({bottom:f+"%"},b.animate);if(k===1)c.range[e?"animate":"css"]({height:f-g+"%"},{queue:false,duration:b.animate})}g=f});else{i=this.value();j=this._valueMin();l=this._valueMax();f=l!==j?(i-j)/(l-j)*100:0;h[c.orientation==="horizontal"?"left":"bottom"]=f+"%";this.handle.stop(1,1)[e?"animate":"css"](h,b.animate);if(a==="min"&&this.orientation==="horizontal")this.range.stop(1,1)[e?"animate":"css"]({width:f+"%"},
-b.animate);if(a==="max"&&this.orientation==="horizontal")this.range[e?"animate":"css"]({width:100-f+"%"},{queue:false,duration:b.animate});if(a==="min"&&this.orientation==="vertical")this.range.stop(1,1)[e?"animate":"css"]({height:f+"%"},b.animate);if(a==="max"&&this.orientation==="vertical")this.range[e?"animate":"css"]({height:100-f+"%"},{queue:false,duration:b.animate})}}});d.extend(d.ui.slider,{version:"1.8.4"})})(jQuery);
-; \ No newline at end of file
diff --git a/o3d/samples/o3d-webgl-samples/checkers.html b/o3d/samples/o3d-webgl-samples/checkers.html
deleted file mode 100644
index 7548174..0000000
--- a/o3d/samples/o3d-webgl-samples/checkers.html
+++ /dev/null
@@ -1,873 +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.
--->
-
-<!--
-Checker Game Example
-
-This sample demonstates usage of primitive functions and simple 3d animation techniques.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-3D Checkers Game
-</title>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.arcball');
-o3djs.require('o3djs.picking');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-
-// global variables
-var g_o3dElement;
-var g_client;
-var g_o3d;
-var g_math;
-var g_quaternions;
-var g_pack;
-var g_viewInfo;
-var g_sceneRoot;
-var g_eyeView;
-var g_cubeShape;
-var g_cylinderShape;
-var g_prismShape;
-var g_material;
-var g_aball;
-var g_thisRot;
-var g_lastRot;
-var g_zoomFactor;
-var g_dragging = false;
-var g_pickManager; // information about the transform graph.
-var g_statusInfoElem;
-
-// Animation globals.
-var g_flashTimer;
-var g_moveTimer;
-var g_moveDuration;
-var g_oldFlashTimer;
-
-// Checkers globals.
-var g_board;
-var g_boardSize;
-var g_boardSquare;
-var g_boardHeight;
-var g_pieceHeight;
-var g_selectedPiece;
-var g_selectedSquare;
-var g_player;
-var g_canJump;
-
-/**
- * Creates the client area.
- */
-function initClient() {
- window.g_finished = false; // for selenium testing.
-
- // Runs the sample in V8. Comment out this line to run it in the browser
- // JavaScript engine, for example if you want to debug it.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.webgl.makeClients(main);
-}
-
-/**
- * Initializes global variables, positions camera, draws the 3D chart.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function main(clientElements) {
- // Init global variables.
- initGlobals(clientElements);
-
- // Set up the view and projection transformations.
- initContext();
-
- // Add the checkers board to the transform hierarchy.
- createCheckersBoard();
-
- // Register mouse events handlers
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', startDragging);
- o3djs.event.addEventListener(g_o3dElement, 'mousemove', drag);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', stopDragging);
- o3djs.event.addEventListener(g_o3dElement, 'wheel', scrollMe);
-
- // Set the rendering callback
- g_client.setRenderCallback(onrender);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Initializes global variables and libraries.
- */
-function initGlobals(clientElements) {
- // init o3d globals.
- g_o3dElement = clientElements[0];
- window.g_client = g_client = g_o3dElement.client;
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_quaternions = o3djs.quaternions;
-
- // Create an arcball.
- g_aball = o3djs.arcball.create(g_client.width, g_client.height);
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create a transform node to act as the 'root' of the scene.
- // Attach it to the root of the transform graph.
- g_sceneRoot = g_pack.createObject('Transform');
- g_sceneRoot.parent = g_client.root;
-
- // Create the render graph for the view.
- var clearColor = [.98, .98, .98, 1];
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot,
- clearColor);
-
- // Create a material for the objects rendered.
- g_material = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [1, 1, 1, 1]);
-
- // Initialize checkers piece and square data.
- g_boardSize = 8;
- g_boardSquare = 10;
- g_boardHeight = g_boardSquare / 5;
- g_pieceHeight = g_boardHeight * 0.75;
- g_selectedPiece = null;
- g_selectedSquare = null;
-
- // Create a cube shape for the board squares.
- g_cubeShape = o3djs.primitives.createCube(
- g_pack,
- g_material,
- 1);
-
- // Create a cylinder shape for the checkers pieces.
- g_cylinderShape = o3djs.primitives.createCylinder(
- g_pack,
- g_material,
- g_boardSquare / 2 - 1, // Radius.
- g_pieceHeight, // Depth.
- 100, // Number of subdivisions.
- 1);
-
- // use an extruded poligon to create a 'crown' for the king piece.
- var polygon = [[0, 0], [1, 0], [1.5, 1.5], [0.5, 0.5],
- [0, 2], [-0.5, 0.5], [-1.5, 1.5], [-1, 0]];
-
- // use the 'prism' primitive for the crown.
- g_prismShape = o3djs.primitives.createPrism(
- g_pack,
- g_material,
- polygon, // The profile polygon to be extruded.
- 1); // The depth of the extrusion.
-
- // Get the status element.
- g_statusInfoElem = o3djs.util.getElementById('statusInfo');
-
- // Initialize player data.
- g_player = 1; // red player starts first.
- g_canJump = false;
-
- // Initialize various animation globals.
- g_flashTimer = 0;
- g_moveTimer = 0;
- g_moveDuration = 1.3;
- g_oldFlashTimer = 0;
-}
-
-/**
- * Initialize the original view of the scene.
- */
-function initContext() {
- g_eyeView = [-5, 120, 100];
- g_zoomFactor = 1.03;
- g_dragging = false;
- g_sceneRoot.identity();
- g_lastRot = g_math.matrix4.identity();
- g_thisRot = g_math.matrix4.identity();
-
- // Set up a perspective transformation for the projection.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- Math.PI * 40 / 180, // 30 degree frustum.
- g_o3dElement.clientWidth / g_o3dElement.clientHeight, // Aspect ratio.
- 1, // Near plane.
- 10000); // Far plane.
-
- // Set up our view transformation to look towards the axes origin.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- g_eyeView, // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Creates a Coord object used to hold a set of 2D coordinates.
- *
- * @private
- * @constructor
- * @param {number} x X coordinate.
- * @param {number} y Y coordinate.
- */
-function Coord(x, y) {
- this.x = x;
- this.y = y;
-}
-
-/**
- * Creates a BoardInfo object to hold board information.
- *
- * @private
- * @constructor
- * @param {number} x X coordinate on the checkers board.
- * @param {number} y Y coordinate on the checkers board.
- */
-function BoardInfo(x, y) {
- this.x = x;
- this.y = y;
- this.square = null;
- this.type = 0;
- this.pieceParent = null;
- this.piece = null;
- this.king = false;
-}
-
-/**
- * Returns the initial settings for a given position on the board.
- *
- * @param {number} x X coordinate on the checkers board.
- * @param {number} y Y coordinate on the checkers board.
- * @return {number} 0 = no piece, 1 = red piece, -1 = white piece
- */
-function getSquarePiece(x, y) {
- // if bad coordinates, no piece.
- if (x >= g_boardSize || x < 0 || y >= g_boardSize || y < 0)
- return 0;
- // if on rows 3 and 4 or on a white square - no piece.
- if (y == 3 || y == 4 || ((x + y) % 2 == 1))
- return 0;
- // if on rows 0-2 it is a red piece, otherwise white piece.
- if (0 <= y && y < 3) return 1;
- if (5 <= y && y < 8) return -1;
- // Any not covered case.
- return 0;
-}
-
-/**
- * Creates the checkers board.
- */
-function createCheckersBoard() {
- g_board = [];
- // Create a checker board (black at 0,0).
- for (var i = 0; i < g_boardSize; i += 1) { // columns.
- g_board[i] = [];
- for (var j = 0; j < g_boardSize; j += 1) { // rows.
- // create the transform for the board squares.
- var square = g_pack.createObject('Transform');
- square.parent = g_sceneRoot;
- square.addShape(g_cubeShape);
- // translate and scale the squares correctly relative to origin.
- var offset = g_boardSquare * (1 - g_boardSize) / 2;
- square.translate(offset + g_boardSquare * i ,
- 0, -(offset + g_boardSquare * j));
- square.scale(g_boardSquare, g_boardHeight, g_boardSquare);
- // set the square color.
- var isBlack = (i + j) % 2 == 0 ? true : false;
- var squareColor = isBlack ?
- [0.15, 0.15, 0.15, 1] : [0.85, 0.85, 0.75, 1];
- square.createParam('diffuse', 'ParamFloat4').value = squareColor;
-
- // add this square and its info to the board.
- g_board[i][j] = new BoardInfo(i, j);
- g_board[i][j].square = square;
-
- // create the piece for this square and update the board position.
- // skip if the square has no piece.
- var pieceType = getSquarePiece(i, j);
- if (pieceType == 0)
- continue;
-
- // create a parent transform for this piece.
- var pieceParent = g_pack.createObject('Transform');
- pieceParent.parent = g_sceneRoot;
-
- // create the checkers piece.
- var piece = g_pack.createObject('Transform');
- piece.parent = pieceParent;
- piece.addShape(g_cylinderShape);
-
- // place the piece on the correct location on the board.
- pieceParent.translate(0, (g_pieceHeight + g_boardHeight) / 2, 0);
- pieceParent.translate(offset + g_boardSquare * i ,
- 0, -(offset + g_boardSquare * j));
-
- // pick the piece color (red or white).
- piece.createParam('diffuse', 'ParamFloat4').value =
- getPieceColor(pieceType);
-
- // update the board info to include this piece.
- g_board[i][j].piece = piece;
- g_board[i][j].pieceParent = pieceParent;
- g_board[i][j].type = pieceType;
- }
- }
-
- // Update our PickManager.
- updatePickManager();
-
- // update status.
- updateStatus('Game starting... RED moves first.', true);
-}
-
-/**
- * Checks if a piece has become a 'king' piece and updates it.
- *
- * @param {number} x X coordinate on the checkers board.
- * @param {number} y Y coordinate on the checkers board.
- */
-function checkAndUpdateKing(x, y) {
- // if the piece is not on the king row, nothing to do.
- if ( y > 0 && y < g_boardSize - 1 ) return;
-
- // ignore if no piece or the piece is already king
- var selSquare = g_board[x][y];
- if (!selSquare.piece || selSquare.king) return;
-
- // change the king piece color.
- selSquare.king = true;
-
- // create the crown shape.
- var crown = g_pack.createObject('Transform');
- crown.parent = selSquare.piece;
- crown.addShape(g_prismShape);
- var crownSize = g_pieceHeight;
- crown.scale(crownSize, crownSize, crownSize);
- crown.translate(0, g_pieceHeight / 2, 0);
- crown.createParam('diffuse', 'ParamFloat4').value = [1, 1, 0, 0];
-}
-
-
-/**
- * Updates the transform tree info.
- */
-function updatePickManager() {
- if (!g_pickManager) {
- g_pickManager = o3djs.picking.createPickManager(g_client.root);
- }
- g_pickManager.update();
-}
-
-/**
- * Check if a player selection is a jump.
- *
- * @param {BoardInfo} piece The board info for the piece.
- * @param {BoardInfo} square The board info for the landing square.
- * @return {boolean} true if this is a jump.
- */
-function isJump(piece, square) {
- return (Math.abs(piece.x - square.x) == 2 &&
- Math.abs(piece.y - square.y) == 2 );
-}
-
-function isLegalMove(piece, square) {
- var orig = new Coord(piece.x, piece.y);
- var dest = new Coord(square.x, square.y);
-
- // it must be this player's turn to make a move.
- if (piece.type != g_player) return false;
-
- // the destination must be un-occupied.
- if (square.type != 0 ) return false;
-
- // must move diagonally.
- var diag = new Coord(dest.x - orig.x, dest.y - orig.y);
- if (Math.abs(diag.x) != Math.abs(diag.y)) return false;
-
- // cannot move more than 2.
- if (Math.abs(diag.x) > 2) return false;
-
- // make sure the piece is moved in the 'forward' direction
- // unless this is a 'king' piece.
- if (!piece.king && g_player * diag.y < 0) return false;
-
- // if a jump check if valid.
- if (Math.abs(diag.x) == 2) {
- var jumpType = g_board[(orig.x + dest.x)/2][(orig.y + dest.y)/2].type;
- if (jumpType == piece.type || jumpType == 0)
- return false;
- }
-
- return true;
-}
-
-/**
- * Update the status message.
- *
- * @param {string} statusMsg The message to display.
- * @param {boolean} opt_hidePlayer Prefix the status with the name of the player.
- */
-function updateStatus(statusMsg, opt_hidePlayer) {
- var status = (g_player == 1) ? 'RED: ' : 'WHITE: ';
- g_statusInfoElem.innerHTML = (opt_hidePlayer ? '' : status) + statusMsg;
-}
-
-
-/**
- * Check if a valid boad coordinate.
- *
- * @param {number} x X coordinate on the checkers board.
- * @param {number} y Y coordinate on the checkers board.
- * @return {boolean} True if a valid coordinate.
- */
-function isValidCoord(x, y) {
- if ( x < 0 || x >= g_boardSize ) return false;
- if ( y < 0 || y >= g_boardSize ) return false;
- return true;
-}
-
-
-/**
- * Check if a piece has a valid sliding move.
- *
- * @param {!BoardInfo} piece The board info for the piece.
- * @return {boolean} True if the piece can slide.
- */
-function pieceCanSlide(piece) {
- var x = piece.x;
- var y = piece.y;
-
- for (var i = -1; i <= 1; i += 2) {
- for (var j = -1; j <= 1; j += 2) {
- if (isValidCoord(x + i, y + j))
- if (isLegalMove(piece, g_board[x + i][y + j]))
- return true;
- }
- }
- return false;
-}
-
-/**
- * Check if a piece has a valid jumping move.
- *
- * @param {!BoardInfo} piece The board info for the piece.
- * @return {boolean} True if the piece can jump.
- */
-function pieceCanJump(piece) {
- var x = piece.x;
- var y = piece.y;
-
- for (var i = -2; i <= 2; i += 4) {
- for (var j = -2; j <= 2; j += 4) {
- if (isValidCoord(x + i, y + j))
- if (isLegalMove(piece, g_board[x + i][y + j]))
- return true;
- }
- }
- return false;
-}
-
-/**
- * Check if the current player has any moves available.
- *
- * @return {boolean} True if the player can move.
- */
-function currentPlayerCanMove() {
- var canSlide = false;
- for (var x = 0; x < g_boardSize; x += 1) {
- for (var y = 0; y < g_boardSize; y += 1) {
- var sel = g_board[x][y];
- if (sel.piece == null) continue;
- // if jump set the canJump variable and return.
- g_canJump = pieceCanJump(sel);
- if (g_canJump) return true;
- if (pieceCanSlide(sel)) {
- canSlide = true;
- }
- }
- }
- return canSlide;
-}
-
-/**
- * Check if a forced jump is required for the current player.
- *
- * @return {boolean} True if a jump is required.
- */
-function checkForcedJump() {
- for (var x = 0; x < g_boardSize; x += 1) {
- for (var y = 0; y < g_boardSize; y += 1) {
- var sel = g_board[x][y];
- if (sel.piece && pieceCanJump(sel)) {
- g_forcedJump = true;
- return true;
- }
- }
- }
- g_forcedJump = false;
- return false;
-}
-
-/**
- * Check if the game is over.
- *
- * @return {boolean} True if the game is over.
- */
-function isGameOver() {
- // the game is over when a player has no pieces left
- // or it cannot make a valid move.
- if (!currentPlayerCanMove()) {
- var statusStr = (g_player == 1) ? 'White Won!' : 'Red Won!';
- updateStatus(statusStr, true);
- return true;
- }
- return false;
-}
-
-/**
- * Detect a mouse click an element of the checkers board.
- *
- * @param {event} e event.
- */
-function detectSelection(e) {
- var worldRay = o3djs.picking.clientPositionToWorldRay(e.x,
- e.y,
- g_viewInfo.drawContext,
- g_client.width,
- g_client.height);
-
- // check if we picked any objects.
- var pickInfo = g_pickManager.pick(worldRay);
- if (pickInfo) {
- // get the parent transform of this object.
- var pickTrans = pickInfo.shapeInfo.parent.transform;
- var pickTransClientId = pickTrans.clientId;
-
- // check if a board square or a piece.
- for (var x = 0; x < g_boardSize; x += 1) {
- for (var y = 0; y < g_boardSize; y += 1) {
- if (g_board[x][y].piece &&
- pickTransClientId == g_board[x][y].piece.clientId) {
- // do not select another player's piece.
- if (g_player != g_board[x][y].type) return;
-
- // if a previous piece selection, clear it.
- if (g_selectedPiece) {
- g_selectedPiece.piece.getParam('diffuse').value =
- getPieceColor(g_selectedPiece.type);
- }
-
- // check if a forced jump.
- if (g_canJump) {
- if (!pieceCanJump(g_board[x][y])) {
- updateStatus('Must jump, incorrect piece!');
- return;
- }
- }
-
- SelectPiece(x, y);
- return;
- } else if (pickTransClientId == g_board[x][y].square.clientId) {
- // selected the landing square if a piece move is pending.
- if (g_selectedPiece) {
- // check if a forced jump.
- if (g_canJump && !isJump(g_selectedPiece, g_board[x][y])) {
- updateStatus('Must jump!');
- return;
- }
- // check if a legal move, then move the piece.
- if (isLegalMove(g_selectedPiece, g_board[x][y])) {
- SelectSquare(x, y);
- } else {
- updateStatus('Illegal move!');
- }
- }
- return;
- }
- }
- }
- }
-}
-
-/**
- * Select a piece on the checkers board.
- */
-function SelectPiece(x, y) {
- g_selectedPiece = g_board[x][y];
- // update status message.
- updateStatus('Selected piece at (' + x + ',' + y + ')');
-}
-
-/**
- * Select a square on the checkers board.
- */
-function SelectSquare(x, y) {
- updateStatus('Moving piece from (' + g_selectedPiece.x + ',' +
- g_selectedPiece.y + ') to (' + x + ',' + y + ')');
- g_selectedSquare = g_board[x][y];
- g_moveTimer = 0;
-}
-
-/**
- * Return the color for the given piece type.
- *
- * @param {number} type Type of the checkers piece.
- * @return {Array} Array representing the color.
- */
-function getPieceColor(type) {
- return (type == 1) ? [1, 0.15, 0.15, 1] : [1, 1, 1, 1];
-}
-
-/**
- * Called every frame.
- * @param {o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onrender(renderEvent) {
- g_flashTimer += renderEvent.elapsedTime;
- g_flashTimer = g_flashTimer % 0.5;
-
- if (g_selectedPiece) {
- var origColor = getPieceColor(g_selectedPiece.type);
- // flash highlight the selected piece as long as selected.
- if (g_oldFlashTimer > g_flashTimer ) {
- g_selectedPiece.piece.getParam('diffuse').value = [0.6, 1, 1, 1];
- } else if (g_flashTimer >= 0.25 && g_oldFlashTimer < 0.25) {
- g_selectedPiece.piece.getParam('diffuse').value = origColor;
- }
-
- // check if we selected a square to move the piece.
- if (g_selectedSquare) {
- moveSelectedPiece(renderEvent.elapsedTime);
- }
- }
- g_oldFlashTimer = g_flashTimer;
-}
-
-
-/**
- * Slides or jumps the selected piece.
- * This method is used to simulate the animation of the moving piece.
- * @param {number} elapsedTime The elapsed time in seconds since the last call.
- */
-function moveSelectedPiece(elapsedTime) {
- g_moveTimer += elapsedTime;
- // animate the piece one iteration at the time.
- var lerp = g_moveTimer / g_moveDuration;
-
- // get the board coordinates of the curent and future position.
- var x0 = g_selectedPiece.x;
- var y0 = g_selectedPiece.y;
- var x1 = g_selectedSquare.x;
- var y1 = g_selectedSquare.y;
-
- // get the coordinates relative to axis origin.
- var offset = g_boardSquare * (1 - g_boardSize) / 2;
- var xc0 = offset + g_boardSquare * x0;
- var zc0 = -(offset + g_boardSquare * y0);
- var xc1 = offset + g_boardSquare * x1;
- var zc1 = -(offset + g_boardSquare * y1);
- var yc = (g_pieceHeight + g_boardHeight) / 2;
-
- // Our piece's position and rotation.
- var px;
- var pz;
- var jump = 0;
- var rotation = 0;
- var done = false;
-
- if (lerp < 1) {
- // check if this is a jump.
- if (isJump(g_selectedPiece, g_selectedSquare)) {
- // compute the jump height.
- jump = Math.sin(Math.PI * lerp) * g_pieceHeight * 13;
- // simulate a spinning of the jumping piece.
- rotation = -lerp * 4 * Math.PI;
- }
- px = xc0 + (xc1 - xc0) * lerp;
- pz = zc0 + (zc1 - zc0) * lerp;
- } else {
- // done with the move.
- px = xc1;
- pz = zc1;
- done = true;
- }
-
- // move the piece to the new position.
- var pieceParent = g_board[x0][y0].pieceParent;
- pieceParent.identity();
- pieceParent.translate(px, yc + jump, pz);
-
- // spin the piece
- g_selectedPiece.piece.identity();
- g_selectedPiece.piece.rotateX(rotation);
-
- if (done) {
- // stop flashing - restore the original color.
- var origColor = getPieceColor(g_selectedPiece.type);
- g_selectedPiece.piece.getParam('diffuse').value = origColor;
-
- // if a jump destroy the jumped piece.
- var wasJump = isJump(g_selectedPiece, g_selectedSquare);
- if (wasJump) {
- var xj = (x0 + x1)/2;
- var yj = (y0 + y1)/2;
- g_board[xj][yj].type = 0;
- g_board[xj][yj].pieceParent.parent = null;
- g_board[xj][yj].pieceParent = null;
- g_board[xj][yj].piece = null;
- }
-
- // the new square has a new piece.
- g_board[x1][y1].type = g_selectedPiece.type;
- g_board[x1][y1].king = g_selectedPiece.king;
- g_board[x1][y1].piece = g_selectedPiece.piece;
- g_board[x1][y1].pieceParent = g_selectedPiece.pieceParent;
-
- // the original square is now empty.
- g_board[x0][y0].type = 0;
- g_board[x0][y0].piece = null;
- g_board[x0][y0].pieceParent = null;
-
- // check if the moved piece became king.
- checkAndUpdateKing(x1, y1);
-
- g_selectedPiece = null;
- g_selectedSquare = null;
- g_moveTimer = 0;
-
- // update the picking info.
- updatePickManager();
-
- // check if current player can jump again.
- if (wasJump && pieceCanJump(g_board[x1][y1])) {
- g_selectedPiece = g_board[x1][y1];
- updateStatus('Must jump again ...');
- } else {
- // this player is done, switch players.
- g_player = -g_player;
- // check if game over; also checks if the current player must jump.
- if (!isGameOver()) {
- updateStatus(g_canJump ? 'Must jump...' : 'Next turn...');
- }
- }
- }
-}
-
-
-/**
- * Zooms the scene in / out by changing the viewpoint.
- * @param {number} zoom zooming factor.
- */
-function ZoomInOut(zoom) {
- for (i = 0; i < g_eyeView.length; i += 1) {
- g_eyeView[i] = g_eyeView[i] / zoom;
- }
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- g_eyeView, // eye.
- [0, 0, 0], // target.
- [0, 1, 0]); // up.
-}
-
-/**
- * Start mouse dragging.
- * @param {event} e event.
- */
-function startDragging(e) {
- detectSelection(e);
- g_lastRot = g_thisRot;
-
- g_aball.click([e.x, e.y]);
- g_dragging = true;
-}
-
-/**
- * Use the arcball to rotate the scene.
- * Computes the rotation matrix.
- * @param {event} e event.
- */
-function drag(e) {
- if (g_dragging) {
- var rotationQuat = g_aball.drag([e.x, e.y]);
- var rot_mat = g_quaternions.quaternionToRotation(rotationQuat);
-
- g_thisRot = g_math.matrix4.mul(g_lastRot, rot_mat);
- var m = g_sceneRoot.localMatrix;
- g_math.matrix4.setUpper3x3(m, g_thisRot);
- g_sceneRoot.localMatrix = m;
- }
-}
-
-/**
- * Stop dragging.
- * @param {event} e event.
- */
-function stopDragging(e) {
- g_dragging = false;
-}
-
-/**
- * Using the mouse wheel zoom in and out of the scene.
- * @param {event} e event.
- */
-function scrollMe(e) {
- var zoom = (e.deltaY < 0) ? 1 / g_zoomFactor : g_zoomFactor;
- ZoomInOut(zoom);
- g_client.render();
-}
-
-</script>
-</head>
-
-<body onload="initClient()">
-<h2>3D Checkers Game</h2>
-<div style="font-size:10;"><span id="statusInfo"></span></div>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/convolution.html b/o3d/samples/o3d-webgl-samples/convolution.html
deleted file mode 100644
index bc09031..0000000
--- a/o3d/samples/o3d-webgl-samples/convolution.html
+++ /dev/null
@@ -1,398 +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 sample shows how to create a separable convolution shader using
-render targets. The kernel here is a Gaussian blur, but the same code
-could be used for any kernel.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-O3D: Convolution Shader Sample
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-window.onunload = uninit;
-
-// constants.
-var RENDER_TARGET_WIDTH = 512;
-var RENDER_TARGET_HEIGHT = 512;
-
-// global variables
-var g_o3d;
-var g_client;
-var g_math;
-var g_pack;
-var g_teapotRoot;
-var g_renderGraphRoot;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing.
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo whose view and projection will
- * be set from the scene after it's loaded.
- */
-function loadScene(pack, fileName, parent, viewInfo) {
- // Get our full path to the scene.
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the scene given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory from the
- * web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT);
-
- // Copy the view and projection to the passed in viewInfo structure..
- viewInfo.drawContext.view = cameraInfo.view;
- viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, viewInfo);
-
- g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3d = clientElements[0];
- g_o3d = o3d.o3d;
- g_math = o3djs.math;
- g_client = o3d.client;
-
- // Creates a pack to manage our resources/assets.
- g_pack = g_client.createPack();
-
- // Create the texture required for the color render-target.
- var texture1 = g_pack.createTexture2D(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT,
- g_o3d.Texture.XRGB8, 1, true);
-
- // Create the texture required for the color render-target.
- var texture2 = g_pack.createTexture2D(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT,
- g_o3d.Texture.XRGB8, 1, true);
-
- g_teapotRoot = g_pack.createObject('Transform');
-
- var renderGraphRoot = g_client.renderGraphRoot;
-
- var xSigma = 4.0, ySigma = 4.0;
- var xKernel = buildKernel(xSigma);
- var yKernel = buildKernel(ySigma);
-
- var renderSurfaceSet1 = createRenderSurfaceSet(texture1);
- var renderSurfaceSet2 = createRenderSurfaceSet(texture2);
-
- // Create the render graph for the teapot view, drawing the teapot into
- // texture1 (via renderSurfaceSet1).
- var teapotViewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_teapotRoot,
- renderSurfaceSet1,
- [1, 1, 1, 1]);
-
- // Create a Y convolution pass that convolves texture1 into texture2, using
- // the X kernel.
- var renderNode1 = createConvolutionPass(texture1,
- renderSurfaceSet2,
- xKernel,
- 1.0 / texture1.width,
- 0.0);
-
- // Create a Y convolution pass that convolves texture2 into the framebuffer,
- // using the Y kernel.
- var renderNode2 = createConvolutionPass(texture2,
- g_client.renderGraphRoot,
- yKernel,
- 0.0,
- 1.0 / texture2.height);
-
- // Load the scene into the transform graph as a child g_teapotRoot
- loadScene(g_pack, '../assets/teapot/scene.json', g_teapotRoot,
- teapotViewInfo);
-
- // Set a render callback.
- g_client.setRenderCallback(onRender);
-}
-
-// We lop off the sqrt(2 * pi) * sigma term, since we're going to normalize
-// anyway.
-function gauss(x, sigma) {
- return Math.exp(- (x * x) / (2.0 * sigma * sigma));
-}
-
-function buildKernel(sigma) {
- var kMaxKernelSize = 25;
- var kernelSize = 2 * Math.ceil(sigma * 3.0) + 1;
- if (kernelSize > kMaxKernelSize) {
- kernelSize = kMaxKernelSize;
- }
- var halfWidth = (kernelSize - 1) * 0.5
- var values = new Array(kernelSize);
- var sum = 0.0;
- for (var i = 0; i < kernelSize; ++i) {
- values[i] = gauss(i - halfWidth, sigma);
- sum += values[i];
- }
- // Now normalize the kernel.
- for (var i = 0; i < kernelSize; ++i) {
- values[i] /= sum;
- }
- return values;
-}
-
-function createConvolutionMaterial(viewInfo, kernelSize) {
- var convFXString = document.getElementById('convFX').value;
- convFXString = convFXString.replace(/KERNEL_WIDTH/g, kernelSize);
- var convEffect = g_pack.createObject('Effect');
- convEffect.loadFromFXString(convFXString);
-
- var convMaterial = g_pack.createObject('Material');
- convMaterial.drawList = viewInfo.performanceDrawList;
- convMaterial.effect = convEffect;
- convEffect.createUniformParameters(convMaterial);
- return convMaterial;
-}
-
-function createRenderSurfaceSet(texture) {
- var renderSurface = texture.getRenderSurface(0);
-
- // Create the depth-stencil buffer required when rendering this pass.
- var depthSurface = g_pack.createDepthStencilSurface(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT);
-
- var renderSurfaceSet = g_pack.createObject('RenderSurfaceSet');
- renderSurfaceSet.renderSurface = renderSurface;
- renderSurfaceSet.renderDepthStencilSurface = depthSurface;
- renderSurfaceSet.parent = g_client.renderGraphRoot;
- return renderSurfaceSet;
-}
-
-function createConvolutionPass(srcTexture, renderGraphRoot, kernel, x, y) {
- // Create a root Transform for the convolution scene.
- var root = g_pack.createObject('Transform');
-
- // Create a basic view for the convolution scene.
- var viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- root,
- renderGraphRoot,
- [1, 1, 1, 1]);
-
- var material = createConvolutionMaterial(viewInfo, kernel.length);
- var quadShape = o3djs.primitives.createPlane(g_pack,
- material,
- 2.0,
- 2.0,
- 1,
- 1);
-
- // Attach the quad to the root of the convolution graph.
- root.addShape(quadShape);
-
- // Rotate the view so we're looking at the XZ plane (where our quad is)
- // Point the camera along the -Y axis
- var target = [0, -1, 0];
- // Put the camera at the origin.
- var eye = [0, 0, 0];
- // Define the up-vector as +Z
- var up = [0, 0, 1];
- viewInfo.drawContext.view = g_math.matrix4.lookAt(eye, target, up);
-
- // Create an orthographic projection.
- viewInfo.drawContext.projection =
- g_math.matrix4.orthographic(-1, 1, -1, 1, -1, 1);
-
- // Generate draw elements and setup material draw lists for the
- // convolution scene.
- o3djs.pack.preparePack(g_pack, viewInfo);
-
- setConvolutionParameters(material, srcTexture, kernel, kernel.length, x, y);
- return renderGraphRoot;
-}
-
-function setConvolutionParameters(material, texture, kernel, kernelSize,
- xIncrement, yIncrement) {
- var imageParam = material.getParam('image');
- var kernelParam = material.getParam('kernel');
- var imageIncrement = material.getParam('imageIncrement');
- var sampler = g_pack.createObject('Sampler');
- sampler.texture = texture;
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
- sampler.minFilter = g_o3d.Sampler.POINT;
- sampler.magFilter = g_o3d.Sampler.POINT;
- sampler.mipFilter = g_o3d.Sampler.NONE;
- imageParam.value = sampler;
- imageIncrement.value = [xIncrement, yIncrement];
- var paramArray = g_pack.createObject('ParamArray');
- var halfWidth = (kernelSize - 1) * 0.5;
- for (var i = 0; i < kernelSize; ++i) {
- var element = paramArray.createParam(i, 'ParamFloat');
- element.value = kernel[i];
- }
- kernelParam.value = paramArray;
-}
-
-/**
- * Called every frame.
- * @param {o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- g_teapotRoot.identity();
- g_teapotRoot.rotateX(g_clock);
- g_teapotRoot.rotateY(g_clock * 1.3);
-}
-
-/**
- * Cleanup before exiting.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Convolution Shader Example</h1>
-<p>This sample shows how to do 2D image processing using render targets. This
-sample uses a convolution shader to do a 2D Gaussian blur, but the
-same code could be used for any separable convolution kernel.</p>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 512px; height: 512px;"></div>
-<!-- End of O3D plugin -->
-<!--
- We embed the code for our effect inside this hidden textarea.
- Effects contain the functions that define
- the vertex and pixel shaders used by our shape.
--->
-<!-- Don't render the textarea -->
-<div style="display:none">
-<textarea id="convFX" name="convFX" cols="80" rows="20">
-uniform mat4 worldViewProjection;
-uniform vec2 imageIncrement;
-
-attribute vec4 position;
-attribute vec2 texCoord0;
-
-varying vec2 v_imageCoord;
-
-void main() {
- gl_Position = worldViewProjection * position;
-
- // Offset image coords by half of kernel width, in image texels
- v_imageCoord = texCoord0 -
- (float(KERNEL_WIDTH - 1) / 2.0) * imageIncrement;
-}
-
-// #o3d SplitMarker
-
-uniform sampler2D image;
-uniform float kernel[ KERNEL_WIDTH ];
-uniform vec2 imageIncrement;
-
-varying vec2 v_imageCoord;
-
-void main() {
- vec2 imageCoordTmp = v_imageCoord;
- vec4 sum = vec4(0.0, 0.0, 0.0, 0.0);
- for (int i = 0; i < KERNEL_WIDTH; ++i) {
- sum += texture2D(image, imageCoordTmp) * kernel[i];
- imageCoordTmp += imageIncrement;
- }
- gl_FragColor = sum;
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
-
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/culling.html b/o3d/samples/o3d-webgl-samples/culling.html
deleted file mode 100644
index af1031c..0000000
--- a/o3d/samples/o3d-webgl-samples/culling.html
+++ /dev/null
@@ -1,320 +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.
--->
-
-<!--
-O3D Culling.
-
-Make sure things off screen get culled.
-
-By default nothing is culled. If you want object to be culled you must setup
-bounding boxes in the transform graph that fit the needs of your application
-and then turn on culling for those objects you want culled.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Culling.
-</title>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// global variables
-var g_timeMult = 1.0;
-var g_framesRendered = 0;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_totalTransformsElement;
-var g_transformsProcessedElement;
-var g_transformsCulledElement;
-var g_totalDrawElementsElement;
-var g_totalDrawableThingsElement;
-var g_drawElementsProcessedElement;
-var g_drawElementsCulledElement;
-var g_drawElementsRenderedElement;
-var g_primitivesRenderedElement;
-var g_groupTransforms = [];
-var GROUPS_ACROSS = 2;
-var UNITS_ACROSS_GROUP = 2;
-var TOTAL_ACROSS = GROUPS_ACROSS * UNITS_ACROSS_GROUP;
-var HALF_WIDTH = TOTAL_ACROSS * 0.0;
-var UNIT_SPACING = 200;
-
-function createInstances(pack, shape) {
- // Make a grid of transforms and put a shape instance on each one.
- for (var g = 0; g < GROUPS_ACROSS; g++) {
- for (var h = 0; h < GROUPS_ACROSS; h++) {
- for (var i = 0; i < GROUPS_ACROSS; i++) {
- var groupTransform = pack.createObject('Transform');
- g_groupTransforms[g_groupTransforms.length] = groupTransform;
- groupTransform.parent = g_client.root;
- // Turn on culling for this transform.
- groupTransform.cull = true;
- var boundingBox = new g_o3d.BoundingBox([0, 0, 0],
- [0, 0, 0]);
- groupTransform.translate(
- (g * UNITS_ACROSS_GROUP - HALF_WIDTH) * UNIT_SPACING,
- (h * UNITS_ACROSS_GROUP - HALF_WIDTH) * UNIT_SPACING,
- (i * UNITS_ACROSS_GROUP - HALF_WIDTH) * UNIT_SPACING);
-
- for (var x = 0; x < UNITS_ACROSS_GROUP; x++) {
- for (var y = 0; y < UNITS_ACROSS_GROUP; y++) {
- for (var z = 0; z < UNITS_ACROSS_GROUP; z++) {
- var transform = pack.createObject('Transform');
- transform.parent = groupTransform;
- // Turn on culling for this transform.
- transform.cull = true;
- transform.addShape(shape);
- // Add up the bounding boxes of all the elements.
- var elements = shape.elements;
- var box = elements[0].boundingBox;
- for (var ee = 1; ee < elements.length; ee++) {
- box = box.add(elements[ee].boundingBox);
- }
-
- // Set the transform to have a bounding box that is the sum
- // of all the elements under it.
- transform.boundingBox = box;
- transform.translate(
- (x - UNITS_ACROSS_GROUP * 0.5) * UNIT_SPACING,
- (y - UNITS_ACROSS_GROUP * 0.5) * UNIT_SPACING,
- (z - UNITS_ACROSS_GROUP * 0.5) * UNIT_SPACING);
- transform.createParam('diffuse', 'ParamFloat4').value = [
- (g * UNITS_ACROSS_GROUP + x) * (1 / TOTAL_ACROSS),
- (h * UNITS_ACROSS_GROUP + y) * (1 / TOTAL_ACROSS),
- (i * UNITS_ACROSS_GROUP + z) * (1 / TOTAL_ACROSS),
- 1];
- // Add the box for this bounding box to the box for the group.
- var box = transform.boundingBox.mul(transform.localMatrix);
- boundingBox = boundingBox.add(box);
- }
- }
- }
- // Set the bounding box for the group transform to encompass all
- // the transforms below it.
- groupTransform.boundingBox = boundingBox;
- }
- }
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- // These are here so that they are visible to both the browser (so
- // selenium sees them) and the embedded V8 engine.
- window.g_clock = 0;
- window.g_finished = false; // for selenium testing.
-
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Set window.g_client as well. Otherwise when the sample runs in
- // V8, selenium won't be able to find this variable (it can only see
- // the browser environment).
- window.g_client = g_client = o3dElement.client;
-
- g_totalDrawableThingsElement =
- o3djs.util.getElementById('totalDrawableThings');
- g_totalTransformsElement =
- o3djs.util.getElementById('totalTransforms');
- g_transformsProcessedElement =
- o3djs.util.getElementById('transformsProcessed');
- g_transformsCulledElement =
- o3djs.util.getElementById('transformsCulled');
- g_totalDrawElementsElement =
- o3djs.util.getElementById('totalDrawElements');
- g_drawElementsProcessedElement =
- o3djs.util.getElementById('drawElementsProcessed');
- g_drawElementsCulledElement =
- o3djs.util.getElementById('drawElementsCulled');
- g_drawElementsRenderedElement =
- o3djs.util.getElementById('drawElementsRendered');
- g_primitivesRenderedElement =
- o3djs.util.getElementById('primitivesRendered');
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create our projection matrix, with a vertical field of view of 45
- // degrees a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 10000);
-
- // Create and load the effect.
- var material = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [1, 1, 1, 1]);
-
- // Create 2 spheres.
- var shape1 = o3djs.primitives.createSphere(
- g_pack,
- material,
- 40,
- 20,
- 20,
- g_math.matrix4.translation([-50, 0, 0]));
-
- var shape2 = o3djs.primitives.createSphere(
- g_pack,
- material,
- 20,
- 20,
- 20,
- g_math.matrix4.translation([50, 0, 0]));
-
- // Create a shape and move the 2 sphere primitives to the same shape.
- // This is done to show that each of the primitives under the shape
- // will get culled separately.
- var shape = g_pack.createObject('Shape');
- shape1.elements[0].owner = shape;
- shape2.elements[0].owner = shape;
- // delete the old shapes.
- g_pack.removeObject(shape1);
- g_pack.removeObject(shape2);
- var elements = shape.elements;
- // Turn on culling for the two sphere elements.
- elements[0].cull = true;
- elements[1].cull = true;
-
- createInstances(g_pack, shape);
-
- g_totalDrawableThingsElement.innerHTML =
- GROUPS_ACROSS * UNITS_ACROSS_GROUP *
- GROUPS_ACROSS * UNITS_ACROSS_GROUP *
- GROUPS_ACROSS * UNITS_ACROSS_GROUP;
-
- g_totalDrawElementsElement.innerHTML = g_client.getObjectsByClassName(
- 'o3d.DrawElement').length;
- g_totalTransformsElement.innerHTML = g_client.getObjectsByClassName(
- 'o3d.Transform').length;
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- window.g_finished = true; // for selenium testing.
-}
-
-var g_flag = false;
-
-// spin the camera.
-function onrender(renderEvent) {
- g_framesRendered++;
- // Get the number of seconds since the last render.
- var elapsedTime = renderEvent.elapsedTime;
-
- // Update g_clock in the browser and cache a V8 copy that can be
- // accessed efficiently. g_clock must be in the browser for selenium.
- var clock = window.g_clock + elapsedTime * window.g_timeMult;
- window.g_clock = clock;
-
- var x = Math.sin(clock * 0.1) * 300;
- var z = Math.cos(clock * 0.1) * 300;
- var y = Math.sin(clock * 0.2) * 300;
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [x, y, z],
- [0, 0, 0],
- [0, 1, 0]);
-
- g_transformsProcessedElement.innerHTML = renderEvent.transformsProcessed;
- g_transformsCulledElement.innerHTML = renderEvent.transformsCulled;
- g_drawElementsProcessedElement.innerHTML = renderEvent.drawElementsProcessed;
- g_drawElementsCulledElement.innerHTML = renderEvent.drawElementsCulled;
- g_drawElementsRenderedElement.innerHTML = renderEvent.drawElementsRendered;
- g_primitivesRenderedElement.innerHTML = renderEvent.primitivesRendered;
-}
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body onload="init()" onunload="unload()">
-<h1>Culling</h1>
-Objects off screen should get culled.
-<br/>
-<!-- Start of O3D client area -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D client area -->
-
-<table>
-<tr><td>Total Drawable Things:</td><td><span id="totalDrawableThings">-</span></td></tr>
-<tr><td>Total Transforms:</td><td><span id="totalTransforms">-</span></td></tr>
-<tr><td>Transforms Processed:</td><td><span id="transformsProcessed">-</span></td></tr>
-<tr><td>Transforms Culled:</td><td><span id="transformsCulled">-</span></td></tr>
-<tr><td>Total DrawElements:</td><td><span id="totalDrawElements">-</span></td></tr>
-<tr><td>DrawElements Processed:</td><td><span id="drawElementsProcessed">-</span></td></tr>
-<tr><td>DrawElements Culled:</td><td><span id="drawElementsCulled">-</span></td></tr>
-<tr><td>DrawElements Rendered:</td><td><span id="drawElementsRendered">-</span></td></tr>
-<tr><td>Primitives Rendered:</td><td><span id="primitivesRendered">-</span></td></tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/customcamera.html b/o3d/samples/o3d-webgl-samples/customcamera.html
deleted file mode 100644
index 6bb6f595..0000000
--- a/o3d/samples/o3d-webgl-samples/customcamera.html
+++ /dev/null
@@ -1,456 +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.
--->
-
-<!--
-O3D Tutorial B4
-
-This tutorial shows how we generate a simple cube mesh
-and view it using a dynamically generated camera which can be animated.
-
-We also show how to dynamically change the perspective matrix
-to adjust to the correct aspect ratio as the o3d window is resized.
-
-The cube can be animated along the target's y-axis and the animation is
-done every time a frame is rendered.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Tutorial B4: Cameras and events
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- }
-</style>
-<!-- Our javascript code -->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Events
-// Run the init() function once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_o3dElement;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-
-// Our view and projection matrices
-// The view matrix transforms objects from world space to view space.
-var g_viewMatrix;
-// The projection matrix projects objects from view space to the screen.
-var g_projMatrix;
-
-// Animation varibles
-
-// Boolean flag that signals whether animation is on.
-var g_animate;
-// Current angle
-var g_animateAngle;
-
-/**
- * Creates our client area by looking for <div>s with an id that starts with
- * "o3d".
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and draws the cube.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Reset animation variables.
- g_animate = false;
- g_animateAngle = 0;
-
- // Create a material.
- var myEffect = g_pack.createObject('Effect');
- var vertexShaderString = document.getElementById('vshader').value;
- var pixelShaderString = document.getElementById('pshader').value;
- myEffect.loadVertexShaderFromString(vertexShaderString);
- myEffect.loadPixelShaderFromString(pixelShaderString);
-
- // Create a Material for the mesh.
- var myMaterial = g_pack.createObject('Material');
-
- // Set the material's drawList.
- myMaterial.drawList = g_viewInfo.performanceDrawList;
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shaders to use.
- myMaterial.effect = myEffect;
-
- // Create a cube.
- var cube = o3djs.primitives.createRainbowCube(g_pack, myMaterial, 1);
-
- setDefaultCameraValues();
- setCamera();
-
- // Generate the projection and viewProjection matrices based
- // on the plugin size by calling Resize().
- resize();
-
- // Attach the cube to the root of the transform graph.
- var root = g_client.root;
- root.addShape(cube);
-
-
- // Set our render callback for animation.
- // This sets a function to be executed every time a frame is rendered.
- g_client.setRenderCallback(onrender);
-}
-
-// Generates the projection matrix based on the size of the g_o3d plugin
-// and calculates the view-projection matrix.
-function resize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- // Create our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 100.
- g_projMatrix = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_o3dWidth / g_o3dHeight,
- 0.1,
- 100);
-
- // update our view projection matrix
- setViewProjection();
- }
-}
-
-// Sets the view and projection matrices.
-function setViewProjection() {
- g_viewInfo.drawContext.view = g_viewMatrix;
- g_viewInfo.drawContext.projection = g_projMatrix;
-}
-
-// Sets the default camera values and updates the view matrix
-function setDefaultCameraValues() {
- var myForm = document.defaultForm;
-
- // default eye position = (2, 1, 4)
- myForm.eyeX.value = '2.0';
- myForm.eyeY.value = '1.0';
- myForm.eyeZ.value = '4.0';
-
- // default target position = (0, 0, 0)
- // (ie centre of the cube)
- myForm.targetX.value = '0.0';
- myForm.targetY.value = '0.0';
- myForm.targetZ.value = '0.0';
-
- // default up vector = (0, 1, 0)
- // (this tells the renderer which direction is 'up')
- // in this case, we define the positive y-axis to be 'up'.
- myForm.upX.value = '0.0';
- myForm.upY.value = '1.0';
- myForm.upZ.value = '0.0';
-
- // update the view matrix
- setCamera();
-}
-
-// Updates the view matrix using the current camera parameters
-function setCamera() {
- // Create our view matrix using the target, eye, and up vectors in the form
- // and using the lookAt(..)
- // helper function to create the matrix.
- var myForm = document.defaultForm;
-
- // Eye-position, this is where our camera is at.
- var eye = [parseFloat(myForm.eyeX.value),
- parseFloat(myForm.eyeY.value),
- parseFloat(myForm.eyeZ.value)];
-
- // Target, this is where our camera is pointed at.
- var target = [parseFloat(myForm.targetX.value),
- parseFloat(myForm.targetY.value),
- parseFloat(myForm.targetZ.value)];
-
- // Up-vector, this tells the camera which direction is 'up'.
- // We define the positive y-direction to be up in this example.
- var up = [parseFloat(myForm.upX.value),
- parseFloat(myForm.upY.value),
- parseFloat(myForm.upZ.value)];
-
- g_viewMatrix = g_math.matrix4.lookAt(eye, target, up);
-
- // if we already have our projection matrix,
- // update the view projection matrix.
- if (g_projMatrix)
- setViewProjection();
-}
-
-// Validates a field in the form to make sure it contains a float.
-function validateFloat(field) {
- var floatValue = parseFloat(field.value);
- if (isNaN(floatValue))
- field.value = '0.0';
- else
- field.value = floatValue;
-}
-
-// Toggles animation
-function toggleAnimate() {
- // toggle the animate flag.
- g_animate = !g_animate;
-
- if (g_animate) {
- // turn on animation
- document.defaultForm.btnAnimate.value = 'Stop animation';
- } else {
- // turn off animation
- document.defaultForm.btnAnimate.value = 'Animate';
- }
-}
-
-// Animates the camera.
-// This function executes on each frame.
-// It was set using g_client.setRenderCallback(..)
-// in initStep2().
-function onrender(renderEvent) {
- resize();
- if (g_animate) {
- // Update the angle frame rate independently.
- g_animateAngle += 2.0 * renderEvent.elapsedTime;
-
- var myForm = document.defaultForm;
- // Set radius to 1.5
- var radius = 1.5;
- // rotate around the y-axis relative to the target
- myForm.eyeX.value = parseFloat(myForm.targetX.value) +
- Math.sin(g_animateAngle) * radius;
- myForm.eyeZ.value = parseFloat(myForm.targetZ.value) +
- Math.cos(g_animateAngle) * radius;
-
- setCamera();
- }
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<table width="100%" style="height:100%;"><tr><td valign="middle" align="center">
-<table width="100%" style="height:100%;"><tr><td>
-<h1>Cameras and events</h1>
-<p>
-This tutorial shows how we generate a simple cube mesh
-and view it using a dynamically generated camera which can be animated.
-</p>
-<p>
-Press Animate to animate the camera and use the textboxes to manually
-set the position of the camera.
-</p>
-<!-- Centre everything in the div -->
- <table id="container" width="98%" style="height:50%;"><tr><td height="100%">
- <!-- Start of g_o3d plugin -->
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- <!-- End of g_o3d plugin -->
- </td></tr></table>
-
- <!-- Don't render the textarea -->
- <div style="display:none">
- <!-- Start of effect -->
- <textarea id="vshader">
- // World View Projection matrix that will transform the input vertices
- // to screen space.
- uniform mat4 worldViewProjection;
-
- // input parameters for our vertex shader
- attribute vec4 position;
- attribute vec4 color;
-
- // passing color to the fragment shader
- varying vec4 fragmentColor;
-
- /**
- * The vertex shader simply transforms the input vertices to screen space.
- */
- void main() {
- // Multiply the vertex positions by the worldViewProjection matrix to
- // transform them to screen space.
- gl_Position = worldViewProjection * position;
- fragmentColor = color;
- }
- </textarea>
- <textarea id="pshader">
- varying vec4 fragmentColor;
- /**
- * This pixel shader just returns the color.
- */
- void main() {
- gl_FragColor = fragmentColor;
- }
- </textarea>
- </div>
- <!-- End of effect -->
-
- <!-- Format input fields nicely in a table -->
- <form action="#" method="get" name="defaultForm">
- <table style="margin-left:auto; margin-right:auto"
- summary="This table contains camera controls.">
- <thead style="font-weight:bold; text-align:center">
- <tr>
- <th></th>
- <th>x</th>
- <th>y</th>
- <th>z</th>
- <th></th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>Eye</td>
- <td><input id="eyeX"
- name="eyeX"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td><input id="eyeY"
- name="eyeY"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td><input id="eyeZ"
- name="eyeZ"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td rowspan="2">
- <input id="btnSet"
- name="btnSet"
- type="button"
- value="Set camera"
- onClick="setCamera()"/>
- </td>
- </tr>
- <tr>
- <td>Target</td>
- <td><input id="targetX"
- name="targetX"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td><input id="targetY"
- name="targetY"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td><input id="targetZ"
- name="targetZ"
- type="text"
- onblur="validateFloat(this)"/></td>
- </tr>
- <tr>
- <td>Up vector</td>
- <td><input id="upX"
- name="upX"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td><input id="upY"
- name="upY"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td><input id="upZ"
- name="upZ"
- type="text"
- onblur="validateFloat(this)"/></td>
- <td>
- <input id="btnDefault"
- name="btnDefault"
- type="button"
- value="Restore default camera"
- onClick="setDefaultCameraValues()"/>
- </td>
- </tr>
- <tr>
- <td colspan="5" style="text-align:center">
- <input id="btnAnimate"
- name="btnAnimate"
- type="button"
- value="Animate"
- onClick="toggleAnimate()"/>
- </td>
- </tr>
- </tbody>
- </table>
- </form>
-</td></tr></table>
-</td></tr></table>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/debugging.html b/o3d/samples/o3d-webgl-samples/debugging.html
deleted file mode 100644
index 216b051..0000000
--- a/o3d/samples/o3d-webgl-samples/debugging.html
+++ /dev/null
@@ -1,248 +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 sample shows examples of using the debug.js utilities.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Debugging.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.debug');
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_transforms = [];
-var g_o3dWidth; // width of our client area.
-var g_o3dHeight; // height of our client area.
-var g_finished = false; // for selenium testing.
-var g_clock = 0;
-var g_lastClock = 0;
-var g_tempAxesOn = false;
-var g_tempLinesOn = false;
-var g_timeMult = 1;
-var g_debugHelper;
-var g_debugLineGroup;
-var g_startEndLine;
-var g_tempLineGroup;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Get the width and height of our client area. We will need this to create
- // a projection matrix.
- g_o3dWidth = o3dElement.clientWidth;
- g_o3dHeight = o3dElement.clientHeight;
-
- // Creates a pack to manage our resources/assets.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set the projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_o3dWidth / g_o3dHeight,
- 0.1,
- 10000);
-
- // Create 11 transforms for the bones and parent them into a chain.
- for (var ii = 0; ii <= 10; ++ii) {
- var transform = g_pack.createObject('Transform');
- g_transforms[ii] = transform;
- if (ii > 0) {
- transform.translate(0, 20, 0);
- }
- transform.parent = ii == 0 ? g_client.root : g_transforms[ii - 1];
- }
-
- // create a debug helper.
- g_debugHelper = o3djs.debug.createDebugHelper(g_client.createPack(),
- g_viewInfo);
-
- // create a debug line group
- g_debugLineGroup = g_debugHelper.createDebugLineGroup(g_client.root);
-
- // draw a few lines.
- g_debugLineGroup.addLine([-20, 0, -20], [-20, 0, +20], [0, 1, 1, 1]);
- g_debugLineGroup.addLine([-20, 0, +20], [+20, 0, +20], [0, 1, 1, 1]);
- g_debugLineGroup.addLine([+20, 0, +20], [+20, 0, -20], [0, 1, 1, 1]);
- g_debugLineGroup.addLine([+20, 0, -20], [-20, 0, -20], [0, 1, 1, 1]);
-
- // create a line for updating.
- g_startEndLine = g_debugLineGroup.addLine();
-
- // Add axes to all the transforms.
- g_debugHelper.addAxes(g_client.root);
-
- // Add a cube to a transform.
- g_debugHelper.addCube(g_transforms[3]);
- g_debugHelper.setCubeScale(g_transforms[3], 10);
- g_debugHelper.setCubeColor(g_transforms[3], [1, 1, 0, 1]); // yellow.
-
- // Add a sphere to a transform.
- g_debugHelper.addSphere(g_transforms[7]);
- g_debugHelper.setSphereScale(g_transforms[7], 20);
- g_debugHelper.setSphereColor(g_transforms[7], [1, 0, 1, 1]); // magenta.
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-// spin the camera.
-function onrender(render_event) {
- // Get the number of seconds since the last render.
- var elapsedTime = render_event.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- var x = Math.sin(g_clock * 0.3) * 400;
- var z = Math.cos(g_clock * 0.3) * 400;
- var y = Math.sin(g_clock * 0.7) * 50 + 100;
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [x, y, z], // eye
- [0, 100, 0], // target
- [0, 1, 0]); // up
-
- // Make our bone chain bend.
- var rotation = Math.PI / g_transforms.length * Math.sin(g_clock * 1);
- for (var ii = 1; ii < g_transforms.length; ++ii) {
- var transform = g_transforms[ii];
- transform.identity();
- transform.translate(0, 20, 0);
- transform.rotateX(rotation);
- }
-
- // change the color of an axis each frame.
- if ((g_clock * 2) % 2 < 1) {
- g_debugHelper.setAxisColor(g_transforms[4], [1, 1, 1, 1]);
- } else {
- g_debugHelper.clearAxisColor(g_transforms[4]);
- }
-
- var start = g_math.matrix4.getTranslation(g_transforms[0].worldMatrix);
- var end = g_math.matrix4.getTranslation(g_transforms[10].worldMatrix);
- g_startEndLine.setEndPoints(start, end);
-
- // Add/Remove some axes.
- var tempAxesOn = (g_clock % 2) < 1;
- if (tempAxesOn != g_tempAxesOn) {
- g_tempAxesOn = tempAxesOn;
- if (tempAxesOn) {
- g_debugHelper.addAxes(g_transforms[7]);
- } else {
- g_debugHelper.removeAxes(g_transforms[7]);
- }
- }
-
- // Create or delete a line group.
- var tempLinesOn = (g_clock * 1.1 % 2) < 1;
- if (tempLinesOn != g_tempLinesOn) {
- g_tempLinesOn = tempLinesOn;
- if (tempLinesOn) {
- g_tempLineGroup = g_debugHelper.createDebugLineGroup(g_transforms[10]);
- g_tempLineGroup.setColor([1, 0.7, 0.7, 1]);
- g_tempLineGroup.addLine([-20, 0, -20], [-20, 0, +20]);
- g_tempLineGroup.addLine([-20, 0, +20], [+20, 0, +20]);
- g_tempLineGroup.addLine([+20, 0, +20], [+20, 0, -20]);
- g_tempLineGroup.addLine([+20, 0, -20], [-20, 0, -20]);
- } else {
- g_tempLineGroup.destroy();
- }
- }
-
- g_lastClock = g_clock;
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Debugging.</h1>
-<p>This sample shows examples of using the debug.js utilities.
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/error-texture.html b/o3d/samples/o3d-webgl-samples/error-texture.html
deleted file mode 100644
index b415f44..0000000
--- a/o3d/samples/o3d-webgl-samples/error-texture.html
+++ /dev/null
@@ -1,265 +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 sample attempts to show what the error texture is, how to set it and
-how turning it off will generate helpful error information.
--->
-<html>
-<head>
-<title>Error Texture</title>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.effect');
-
-// Events
-// Run the init() once the page has finished loading.
-// and unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_texture;
-var g_errorMsgElement;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and sets up some quads.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- g_errorMsgElement =
- document.getElementById('errorMsg');
-
- // Turn of the error callback that o3djs.base.init setup.
- g_client.clearErrorCallback();
-
- // Let us render on demand.
- g_client.renderMode = g_o3d.Client.RENDERMODE_ON_DEMAND;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- var clientWidth = g_client.width;
- var clientHeight = g_client.height;
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -clientWidth * 0.5,
- clientWidth * 0.5,
- -clientHeight * 0.5,
- clientHeight * 0.5,
- 0.001,
- 1000);
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 500, 0], // eye
- [0, 0, 0], // target
- [0, 0, -1]); // up
-
- // Create and load the effect.
- var effect = g_pack.createObject('Effect');
- o3djs.effect.loadEffect(effect, '../shaders/texture-only-glsl.shader');
-
- // Create a Material for the effect.
- var myMaterial = g_pack.createObject('Material');
-
- // Set the material's drawList
- myMaterial.drawList = g_viewInfo.zOrderedDrawList;
-
- // Apply our effect to this material.
- myMaterial.effect = effect;
-
- // Creates a quad using the effect.
- var shape = o3djs.primitives.createPlane(g_pack,
- myMaterial,
- 1,
- 1,
- 1,
- 1);
-
- var pixels = [];
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 3; // rgb
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = 0; // red
- pixels[offset + 1] = Math.floor(y / 8) % 2; // green
- pixels[offset + 2] = Math.floor(x / 8) % 2; // blue
- }
- }
- var texture = g_pack.createTexture2D(32, 32, g_o3d.Texture.XRGB8, 1, false);
- texture.set(0, pixels);
-
- // display the quad 4 times with situations
- // by overriding the sampler on each instance.
- for (var s = 0; s < 4; ++s) {
- // create a transform for an instance
- var transform = g_pack.createObject('Transform');
- transform.translate((s - 1.5) * 140, 0, 0);
- transform.scale(128, 1, 128),
- transform.parent = g_client.root;
- transform.addShape(shape);
-
- // case 0: Correct Texture.
- // case 1: ParamSampler and Sampler but no Texture
- // case 2: ParamSampler but no Sampler,
- // case 3: No ParamSampler.
- if (s <= 2) {
- // Create a ParamSampler on the transform with the same name as in
- // the effect so this param will be used instead of the one on the
- // material.
- var samplerParam = transform.createParam('texSampler0', 'ParamSampler');
-
- if (s <= 1) {
- var sampler = g_pack.createObject('Sampler');
- sampler.name = "s2d";
- samplerParam.value = sampler;
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
- if (s == 0) {
- sampler.texture = texture;
- }
- }
- }
- }
-
- g_client.setPostRenderCallback(onRender);
-
- // Render once now that things are setup.
- render();
-}
-
-function setToUserTexture() {
- var pixels = [];
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 3; // rgb
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.cos(u); // red
- pixels[offset + 1] = Math.sin(v); // green
- pixels[offset + 2] = Math.sin(u); // blue
- }
- }
- var texture = g_pack.createTexture2D(32, 32, g_o3d.Texture.XRGB8, 1, false);
- texture.set(0, pixels);
-
- g_client.setErrorTexture(texture);
- // Render once now that things are setup.
- render();
-}
-
-function setToNoTexture() {
- g_client.setErrorTexture(null);
- render();
-
-}
-
-function hide0() {
- var child = g_client.root.children[1];
- child.visible = !child.visible;
- render();
-}
-
-function hide1() {
- var child = g_client.root.children[2];
- child.visible = !child.visible;
- render();
-}
-
-function reportError(msg) {
- g_errorMsgElement.innerHTML = g_client.lastError;
- g_client.clearLastError();
- g_client.clearErrorCallback();
-}
-
-function render() {
- // Render once now that things are setup.
- g_client.setErrorCallback(reportError);
- g_client.render();
-}
-
-function onRender() {
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- g_client.cleanup();
-}
-</script>
-</head>
-<body>
-<h1>Error Texture.</h1>
-<br/>
-Demonstrates how missing textures are handled.
-<div>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</div>
-<br/>
-<input type="button" value="User Texture" onClick="setToUserTexture()"/>
-<input type="button" value="No Texture" onClick="setToNoTexture()"/>
-<input type="button" value="hide 0" onClick="hide0()"/>
-<input type="button" value="hide 1" onClick="hide1()"/>
-<table><tr><td>Error: </td><td id="errorMsg">-</td></tr></table>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/generate-texture.html b/o3d/samples/o3d-webgl-samples/generate-texture.html
deleted file mode 100644
index 7e10e51..0000000
--- a/o3d/samples/o3d-webgl-samples/generate-texture.html
+++ /dev/null
@@ -1,259 +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.
--->
-
-<!--
-How to generate a texture.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Generate Texture.
-</title>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_finished = false; // for selenium testing
-var g_samplers = [];
-
-/**
- * Creates the client area.
- */
-function init() {
- // Comment out the line below to run the sample in the browser
- // JavaScript engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
- o3djs.webgl.makeClients(initStep2, 'FloatingPointTextures');
-}
-
-/**
- * Initializes O3D, loads an effect, creates some textures
- * and quads to display them.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Set window.g_client as well. Otherwise when the sample runs in
- // V8, selenium won't be able to find this variable (it can only see
- // the browser environment).
- window.g_client = g_client = o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- var clientWidth = g_client.width;
- var clientHeight = g_client.height;
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -clientWidth * 0.5,
- clientWidth * 0.5,
- -clientHeight * 0.5,
- clientHeight * 0.5,
- 0.001,
- 1000);
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 500, 0], // eye
- [0, 0, 0], // target
- [0, 0, -1]); // up
-
- // Create and load the effects.
- var effectInfos = {
- texture_only: {name: 'texture-only-glsl.shader'}
- };
- for (var key in effectInfos) {
- var info = effectInfos[key];
- var material = o3djs.material.createMaterialFromFile(
- g_pack,
- '../shaders/' + info.name,
- g_viewInfo.zOrderedDrawList);
-
- // Create a quad.
- var shape = o3djs.primitives.createPlane(g_pack,
- material,
- 1,
- 1,
- 1,
- 1);
- info.shape = shape;
- }
-
- // display our shape 4 times with 4 different textures
- // by overriding the sampler on each instance.
- for (var s = 0; s < 4; ++s) {
- // create a transform for an instance
- var transform = g_pack.createObject('Transform');
- var x = s % 3;
- var z = Math.floor(s / 3);
- transform.translate((x - 1) * 140, 0, (z - 0.5) * 140);
- transform.scale(128, 1, 128);
- transform.parent = g_client.root;
-
- // Create a ParamSampler on the transform with the same name as in
- // the effect so this param will be used instead of the one on the material.
- var samplerParam = transform.createParam('texSampler0', 'ParamSampler');
-
- var sampler = g_pack.createObject('Sampler');
- samplerParam.value = sampler;
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
- g_samplers[s] = sampler;
-
- // Create a texture.
- {
- var pixels = [];
- var format;
-
- switch (s) {
- case 0: { // XRGB8
- transform.addShape(effectInfos.texture_only.shape);
- format = g_o3d.Texture.XRGB8;
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 3; // rgb
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.cos(u); // red
- pixels[offset + 1] = Math.sin(v); // green
- pixels[offset + 2] = Math.sin(u); // blue
- }
- }
- break;
- }
- case 1: { // ARGB8
- transform.addShape(effectInfos.texture_only.shape);
- format = g_o3d.Texture.ARGB8;
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 4; // rgba
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.floor(y / 4) % 2; // red
- pixels[offset + 1] = Math.sin(v); // green
- pixels[offset + 2] = Math.floor(x / 4) % 2; // blue
- pixels[offset + 3] = Math.abs(Math.sin(v * 4)); // alpha
- }
- }
- break;
- }
- case 2: { // ABGR16F
- transform.addShape(effectInfos.texture_only.shape);
- format = g_o3d.Texture.ABGR16F;
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 4; // rgba
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.cos(v); // red
- pixels[offset + 1] = Math.sin(u); // green
- pixels[offset + 2] = Math.sin(v); // blue
- pixels[offset + 3] = Math.abs(Math.sin(u * 8)); // alpha
- }
- }
- break;
- }
- case 3: { // ABGR32F
- transform.addShape(effectInfos.texture_only.shape);
- format = g_o3d.Texture.ABGR32F;
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 4; // rgba
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.cos(v); // red
- pixels[offset + 1] = Math.sin(u); // green
- pixels[offset + 2] = Math.sin(v); // blue
- pixels[offset + 3] = Math.abs(Math.sin(u * 8)); // alpha
- }
- }
- break;
- }
-
- /**
- * Note that R32F is not supported in WebGL.
- */
- }
- var texture = g_pack.createTexture2D(32, 32, format, 1, false);
- texture.set(0, pixels);
- sampler.texture = texture;
- }
- }
- window.o3d_prepForSelenium = prepForSelenium;
- window.g_finished = true; // for selenium testing.
-}
-
-// Turn off all filtering in the samplers to get consistent testing
-// results.
-function prepForSelenium() {
- for (var i = 0; i < g_samplers.length; i++) {
- g_samplers[i].magFilter = g_o3d.Sampler.POINT;
- g_samplers[i].minFilter = g_o3d.Sampler.POINT;
- g_samplers[i].mipFilter = g_o3d.Sampler.NONE;
- }
-}
-
-
-</script>
-</head>
-<body onload="init()">
-<h1>Generate Texture</h1>
-Shows how to create textures in Javascript.
-<br/>
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/hellocube-colors.html b/o3d/samples/o3d-webgl-samples/hellocube-colors.html
deleted file mode 100644
index db707fd..0000000
--- a/o3d/samples/o3d-webgl-samples/hellocube-colors.html
+++ /dev/null
@@ -1,343 +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 sample creates an O3D area with a spinning cube. The user
-can change the color of the cube by clicking on one of the buttons that appear
-at the bottom of the page. This sample demonstrates how to use O3D Params
-to change the values of uniform parameters used by shaders.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Hello Square Colors: Getting started with O3D, take 2.
-</title>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// Run the init() function once the page has finished loading.
-// Run the uninit() function when the page has is unloaded.
-window.onload = init;
-window.onunload = uninit;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_pack;
-var g_client;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-
-var g_cubeTransform;
-var g_cubeColorParam;
-
-/**
- * Changes the color of the cube.
- * @param red red component of the color
- * @param green green component of the color
- * @param blue blue component of the color
- */
-function changeColor(red, green, blue) {
- // Set the rgb color values and alpha = 1
- g_cubeColorParam.value = [red, green, blue, 1];
-}
-
-/**
- * Creates an O3D shape representing a cube. The shape consists of
- * a single primitive with eight vertices and 12 triangles (two for each face
- * of the cube).
- * @param {o3d.Material} material the material used by the primitive.
- * @return {o3d.Shape} The Shape object created.
- */
-function createCube(material) {
- // Create a Shape object for the mesh.
- var cubeShape = g_pack.createObject('Shape');
-
- // Create the Primitive that will contain the geometry data for
- // the cube.
- var cubePrimitive = g_pack.createObject('Primitive');
-
- // Create a StreamBank to hold the streams of vertex data.
- var streamBank = g_pack.createObject('StreamBank');
-
- // Assign the material that was passed in to the primitive.
- cubePrimitive.material = material;
-
- // Assign the Primitive to the Shape.
- cubePrimitive.owner = cubeShape;
-
- // Assign the StreamBank to the Primitive.
- cubePrimitive.streamBank = streamBank;
-
- // The cube is made of 12 triangles. There's eight vertices in total which
- // are shared between the face triangles.
- cubePrimitive.primitiveType = g_o3d.Primitive.TRIANGLELIST;
- cubePrimitive.numberPrimitives = 12; // 12 triangles
- cubePrimitive.numberVertices = 8; // 8 vertices in total
-
- // Generate the draw element for the cube primitive.
- cubePrimitive.createDrawElement(g_pack, null);
-
- // Create a javascript array that stores the X, Y and Z coordinates of each
- // of the 8 corners of the cube.
- var positionArray = [
- -0.5, -0.5, 0.5, // vertex 0
- 0.5, -0.5, 0.5, // vertex 1
- -0.5, 0.5, 0.5, // vertex 2
- 0.5, 0.5, 0.5, // vertex 3
- -0.5, 0.5, -0.5, // vertex 4
- 0.5, 0.5, -0.5, // vertex 5
- -0.5, -0.5, -0.5, // vertex 6
- 0.5, -0.5, -0.5 // vertex 7
- ];
-
- // The following array defines how vertices are to be put together to form
- // the triangles that make up the cube's faces. In the index array, every
- // three elements define a triangle. So for example vertices 0, 1 and 2
- // make up the first triangle, vertices 2, 1 and 3 the second one, etc.
- var indicesArray = [
- 0, 1, 2, // face 1
- 2, 1, 3,
- 2, 3, 4, // face 2
- 4, 3, 5,
- 4, 5, 6, // face 3
- 6, 5, 7,
- 6, 7, 0, // face 4
- 0, 7, 1,
- 1, 7, 3, // face 5
- 3, 7, 5,
- 6, 0, 4, // face 6
- 4, 0, 2
- ];
-
- // Create buffers containing the vertex data.
- var positionsBuffer = g_pack.createObject('VertexBuffer');
- var positionsField = positionsBuffer.createField('FloatField', 3);
- positionsBuffer.set(positionArray);
-
- var indexBuffer = g_pack.createObject('IndexBuffer');
- indexBuffer.set(indicesArray);
-
- // Associate the positions Buffer with the StreamBank.
- streamBank.setVertexStream(
- g_o3d.Stream.POSITION, // semantic: This stream stores vertex positions
- 0, // semantic index: First (and only) position stream
- positionsField, // field: the field this stream uses.
- 0); // start_index: How many elements to skip in the
- // field.
-
- // Associate the triangle indices Buffer with the primitive.
- cubePrimitive.indexBuffer = indexBuffer;
-
- return cubeShape;
-}
-
-/**
- * This method gets called every time O3D renders a frame. Here's where
- * we update the cube's transform to make it spin.
- * @param {o3d.RenderEvent} renderEvent The render event object that gives
- * us the elapsed time since the last time a frame was rendered.
- */
-function renderCallback(renderEvent) {
- g_clock += renderEvent.elapsedTime * g_timeMult;
- // Rotate the cube around the Y axis.
- g_cubeTransform.identity();
- g_cubeTransform.rotateY(2.0 * g_clock);
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, creates the cube and sets up the transform and
- * render graphs.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_client = o3dElement.client;
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- var viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set up a perspective projection.
- viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree fov.
- g_client.width / g_client.height,
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // cube is located.
- viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 1, 5], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- // Create an Effect object and initialize it using the shaders from the
- // text area.
- var cubeEffect = g_pack.createObject('Effect');
- var vertexShaderString = document.getElementById('vshader').value;
- var pixelShaderString = document.getElementById('pshader').value;
- cubeEffect.loadVertexShaderFromString(vertexShaderString);
- cubeEffect.loadPixelShaderFromString(pixelShaderString);
-
- // Create a Material for the mesh.
- var cubeMaterial = g_pack.createObject('Material');
-
- // Set the material's drawList.
- cubeMaterial.drawList = viewInfo.performanceDrawList;
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shaders to use.
- cubeMaterial.effect = cubeEffect;
-
- // Create an O3D Param on the material for every uniform used by the
- // shader.
- cubeEffect.createUniformParameters(cubeMaterial);
-
- // Get the color parameter from the material and set its value to red.
- g_cubeColorParam = cubeMaterial.getParam('color');
- g_cubeColorParam.value = [1, 0, 0, 1];
-
- // Create the Shape for the cube mesh and assign its material.
- var cubeShape = createCube(cubeMaterial);
-
- // Create a new transform and parent the Shape under it.
- g_cubeTransform = g_pack.createObject('Transform');
- g_cubeTransform.addShape(cubeShape);
-
- // Parent the cube's transform to the client root.
- g_cubeTransform.parent = g_client.root;
-
- // Set our render callback for animation.
- // This sets a function to be executed every time a frame is rendered.
- g_client.setRenderCallback(renderCallback);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Hello Square: Colors</h1>
-This example shows how to use parameters to the color output of a shader.
-<br/>
-
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-
-<form name="default_form" action="#" method="get">
- <p>
- Change color:
- <input type="button" value="Red" onclick="changeColor(1,0,0);" />
- <input type="button" value="Green" onclick="changeColor(0,1,0);" />
- <input type="button" value="Blue" onclick="changeColor(0,0,1);" />
- <input type="button" value="Yellow" onclick="changeColor(1,1,0);" />
- <input type="button" value="Cyan" onclick="changeColor(0,1,1);" />
- <input type="button" value="Purple" onclick="changeColor(1,0,1);" />
- <input type="button" value="White" onclick="changeColor(1,1,1);" />
- </p>
-</form>
-
-<!-- Don't render the textarea -->
-<div style="display:none">
-<!-- Start of effect -->
-<textarea id="vshader">
- // World View Projection matrix that will transform the input vertices
- // to screen space.
- uniform mat4 worldViewProjection;
-
- // input parameters for our vertex shader
- attribute vec4 position;
-
- /**
- * The vertex shader simply transforms the input vertices to screen space.
- */
- void main() {
- // Multiply the vertex positions by the worldViewProjection matrix to
- // transform them to screen space.
- gl_Position = worldViewProjection * position;
- }
-
-</textarea>
-<textarea id="pshader">
- // Color to draw with.
- uniform vec4 color;
-
- /**
- * This pixel shader just returns the color red.
- */
- void main() {
- gl_FragColor = color;
- }
-
- // Here we tell our effect file *which* functions are
- // our vertex and pixel shaders.
-</textarea>
-<!-- End of effect -->
-</div>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/hellocube-textures.html b/o3d/samples/o3d-webgl-samples/hellocube-textures.html
deleted file mode 100644
index c7b7201..0000000
--- a/o3d/samples/o3d-webgl-samples/hellocube-textures.html
+++ /dev/null
@@ -1,433 +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 sample creates an O3D area with a textured cube in the middle. The
-user can specify the URL where the texture image will be picked from.
-This sample is a simple demonstration of texture usage in O3D.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Hello Square Textures: Getting started with O3D, take 3.
-</title>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.io');
-
-// Events
-// Run the init() function once the page has finished loading.
-// Run the uninit() function when the page is unloaded.
-window.onload = init;
-window.onunload = uninit;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_pack;
-var g_client;
-var g_cubeTransform;
-var g_sampler;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-var g_textureLoadDenied = false; // also for selenium testing
-
-/**
- * Creates an O3D shape representing a cube.
- * @param {o3d.Material} material the material used by the primitive.
- * @return {o3d.Shape} The Shape object created.
- */
-function createCube(material) {
- // Create a Shape object for the mesh.
- var cubeShape = g_pack.createObject('Shape');
-
- // Create the Primitive that will contain the geometry data for
- // the cube.
- var cubePrimitive = g_pack.createObject('Primitive');
-
- // Create a StreamBank to hold the streams of vertex data.
- var streamBank = g_pack.createObject('StreamBank');
-
- // Assign the material that was passed in to the primitive.
- cubePrimitive.material = material;
-
- // Assign the Primitive to the Shape.
- cubePrimitive.owner = cubeShape;
-
- // Assign the StreamBank to the Primitive.
- cubePrimitive.streamBank = streamBank;
-
- // The cube is made of 12 triangles (6 faces x 2 triangles per face)
- cubePrimitive.primitiveType = g_o3d.Primitive.TRIANGLELIST;
- cubePrimitive.numberPrimitives = 12; // 12 triangles
-
- // Vertices used by each triangle must specify both a position and texture
- // coordinates. We cannot share vertices between adjacent cube faces since
- // while their positions are the same, their texture coordinates are
- // different. We therefore create 24 vertices, 4 for each of the cube's
- // six faces.
- cubePrimitive.numberVertices = 24;
-
- // Generate the draw element for the cube primitive.
- cubePrimitive.createDrawElement(g_pack, null);
-
- // Create a javascript array that stores the X, Y and Z coordinates of each
- // of the 24 vertices used by the cube.
- var positionArray = [
- -0.5, -0.5, 0.5,
- 0.5, -0.5, 0.5,
- 0.5, 0.5, 0.5,
- -0.5, 0.5, 0.5,
- -0.5, 0.5, 0.5,
- 0.5, 0.5, 0.5,
- 0.5, 0.5, -0.5,
- -0.5, 0.5, -0.5,
- -0.5, 0.5, -0.5,
- 0.5, 0.5, -0.5,
- 0.5, -0.5, -0.5,
- -0.5, -0.5, -0.5,
- -0.5, -0.5, -0.5,
- 0.5, -0.5, -0.5,
- 0.5, -0.5, 0.5,
- -0.5, -0.5, 0.5,
- 0.5, -0.5, 0.5,
- 0.5, -0.5, -0.5,
- 0.5, 0.5, -0.5,
- 0.5, 0.5, 0.5,
- -0.5, -0.5, -0.5,
- -0.5, -0.5, 0.5,
- -0.5, 0.5, 0.5,
- -0.5, 0.5, -0.5
- ];
-
- // The following array stores the texture coordinates (u, v) for each vertex.
- // These coordinates are used by the shader when displaying the texture image
- // on the mesh triangles.
- var texCoordsArray = [
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1,
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1,
- 1, 1,
- 0, 1,
- 0, 0,
- 1, 0,
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1,
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1,
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1
- ];
-
- // The following array defines how vertices are to be put together to form
- // the triangles that make up the cube's faces. In the index array, every
- // three elements define a triangle. So for example vertices 0, 1 and 2
- // make up the first triangle, vertices 0, 2 and 3 the second one, etc.
- var indicesArray = [
- 0, 1, 2,
- 0, 2, 3,
- 4, 5, 6,
- 4, 6, 7,
- 8, 9, 10,
- 8, 10, 11,
- 12, 13, 14,
- 12, 14, 15,
- 16, 17, 18,
- 16, 18, 19,
- 20, 21, 22,
- 20, 22, 23
- ];
-
- // Create buffers containing the vertex data.
- var positionsBuffer = g_pack.createObject('VertexBuffer');
- var positionsField = positionsBuffer.createField('FloatField', 3);
- positionsBuffer.set(positionArray);
-
- var texCoordsBuffer = g_pack.createObject('VertexBuffer');
- var texCoordsField = texCoordsBuffer.createField('FloatField', 2);
- texCoordsBuffer.set(texCoordsArray);
-
- var indexBuffer = g_pack.createObject('IndexBuffer');
- indexBuffer.set(indicesArray);
-
- // Associate the positions buffer with the StreamBank.
- streamBank.setVertexStream(
- g_o3d.Stream.POSITION, // semantic: This stream stores vertex positions
- 0, // semantic index: First (and only) position stream
- positionsField, // field: the field this stream uses.
- 0); // start_index: How many elements to skip in the
- // field.
-
- // Associate the texture coordinates buffer with the primitive.
- streamBank.setVertexStream(
- g_o3d.Stream.TEXCOORD, // semantic
- 0, // semantic index
- texCoordsField, // field
- 0); // start_index
-
- // Associate the triangle indices Buffer with the primitive.
- cubePrimitive.indexBuffer = indexBuffer;
-
- return cubeShape;
-}
-
-/**
- * This method gets called every time O3D renders a frame. Here's where
- * we update the cube's transform to make it spin.
- * @param {o3d.RenderEvent} renderEvent The render event object that gives
- * us the elapsed time since the last time a frame was rendered.
- */
-function renderCallback(renderEvent) {
- g_clock += renderEvent.elapsedTime * g_timeMult;
- // Rotate the cube around the Y axis.
- g_cubeTransform.identity();
- g_cubeTransform.rotateY(2.0 * g_clock);
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, creates the quad and sets up the transform and
- * render graphs.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Set the texture URL.
- path = '../assets/texture_b3.jpg';
- var url = document.getElementById("url").value = path;
-
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_client = o3dElement.client;
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- var viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set up a perspective projection.
- viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree fov.
- g_client.width / g_client.height,
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // cube is located.
- viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 1, 5], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- // Create an Effect object and initialize it using the shaders from the
- // text area.
- var cubeEffect = g_pack.createObject('Effect');
- var vertexShaderString = document.getElementById('vshader').value;
- var pixelShaderString = document.getElementById('pshader').value;
- cubeEffect.loadVertexShaderFromString(vertexShaderString);
- cubeEffect.loadPixelShaderFromString(pixelShaderString);
-
- // Create a Material for the mesh.
- var cubeMaterial = g_pack.createObject('Material');
-
- // Set the material's drawList.
- cubeMaterial.drawList = viewInfo.performanceDrawList;
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shaders to use.
- cubeMaterial.effect = cubeEffect;
-
- // Create an O3D Param on the material for every uniform used by the
- // shader.
- cubeEffect.createUniformParameters(cubeMaterial);
-
- // Get the material's sampler parameter so that we can set the texture value
- // to it.
- var samplerParam = cubeMaterial.getParam('texSampler0');
-
- // Create a Sampler object and set the min filtering to ANISOTROPIC. This
- // will improve the quality of the rendered texture when viewed at an angle.
- g_sampler = g_pack.createObject('Sampler');
- g_sampler.minFilter = g_o3d.Sampler.ANISOTROPIC;
- g_sampler.maxAnisotropy = 4;
- samplerParam.value = g_sampler;
-
- // Create the Shape for the cube mesh and assign its material.
- var cubeShape = createCube(cubeMaterial);
-
- // Create a new transform and parent the Shape under it.
- g_cubeTransform = g_pack.createObject('Transform');
- g_cubeTransform.addShape(cubeShape);
-
- // Note that we don't parent the transform until the texture is
- // succesfully loaded because we don't want the system
- // to try the draw the shape without its required texture.
-
- // Set our render callback for animation.
- // This sets a function to be executed every time a frame is rendered.
- g_client.setRenderCallback(renderCallback);
-
- // Set the initial texture.
- changeTexture();
-}
-
-/**
- * Fetches the bitmap pointed to by the URL supplied by the user, creates
- * an O3D Texture object with it updates the Sampler used by the material
- * to point to the newly created texture.
- */
-function changeTexture() {
- var textureUrl = document.getElementById('url').value;
- o3djs.io.loadTexture(g_pack, textureUrl, function(texture, exception) {
- // Remove the currently used texture from the pack so that when it's not
- // referenced anymore, it can get destroyed.
- if (g_sampler.texture)
- g_pack.removeObject(g_sampler.texture);
-
- // Because the loading is asynchronous an exception is not thrown but is
- // instead passed on failure.
- if (exception) {
- g_sampler.texture = null;
-
- g_textureLoadDenied = true; // for selenium testing.
- } else {
- // Set the texture on the sampler object to the newly created texture
- // object returned by the request.
- g_sampler.texture = texture;
-
- // We can now safely add the cube transform to the root of the
- // scenegraph since it now has a valid texture. If the transform
- // is already parented under the root, the call will have no effect.
- g_cubeTransform.parent = g_client.root;
-
- g_finished = true; // for selenium testing.
- }
- });
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Hello Cube: Textures</h1>
-This example shows how texture map a cube using an image fetched from a URL.
-<br/>
-
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<br />
-Image URL: <input type="text" id="url" size="100">
-<input type="button" id="updateButton" onclick="changeTexture();" value="Update Texture"><BR>
-
-<!-- Don't render the textarea -->
-<div style="display:none">
-<!-- Start of effect -->
-<textarea id="vshader">
- // World View Projection matrix that will transform the input vertices
- // to screen space.
- uniform mat4 worldViewProjection;
-
- // input parameters for our vertex shader
- attribute vec4 position;
- attribute vec2 texCoord0;
-
- varying vec2 uvs;
-
- /**
- * The vertex shader simply transforms the input vertices to screen space.
- */
- void main() {
- // Multiply the vertex positions by the worldViewProjection matrix to
- // transform them to screen space.
- gl_Position = worldViewProjection * position;
- uvs = texCoord0;
- }
-
-</textarea>
-<textarea id="pshader">
-
- // Color to draw with.
- uniform sampler2D texSampler0;
-
- varying vec2 uvs;
-
- /**
- * This pixel shader just returns the color red.
- */
- void main() {
- gl_FragColor = texture2D(texSampler0, uvs);
- }
-</textarea>
-<!-- End of effect -->
-</div>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/hellocube-wireframe.html b/o3d/samples/o3d-webgl-samples/hellocube-wireframe.html
deleted file mode 100644
index e4d19cd..0000000
--- a/o3d/samples/o3d-webgl-samples/hellocube-wireframe.html
+++ /dev/null
@@ -1,534 +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 sample shows how to place an O3D area in a page and draw simple
-3D shape in it.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Hello Cube: Primitives
-</title>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// Run the init() function once the page has finished loading.
-// Run the uninit() function when the page has is unloaded.
-window.onload = init;
-window.onunload = uninit;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_cubeTransform;
-var g_cubePrimitive;
-var g_currentPrimitiveType;
-var g_currentIndexed;
-var g_positionArray;
-var g_positionBuffer;
-var g_indexBuffer;
-var g_material;
-var g_finished = false; // for selenium testing
-
-
-/**
- * Changes the primitive type of the displayed cube. Some primitive types will
- * only draw a partial cube.
- * @param {string} type The desired primitive type.
- * @param {string} indexed 'Yes' or 'No' whether or not to generate an indexed
- * primitive.
- */
-function changePrimitive(type, indexed) {
- var indicesArray;
- var primitiveType;
- var numberPrimitives;
-
- var indicesPerLine = 1;
-
- // All of the indices arrays below reference the same set of 8 vertices,
- // defined below in the createCube method.
- switch (type) {
- case 'PointList':
- primitiveType = g_o3d.Primitive.POINTLIST;
- numberPrimitives = 8;
- indicesArray = [0, 1, 2, 3, 4, 5, 6, 7];
- indicesPerLine = 0;
- break;
- case 'LineList':
- primitiveType = g_o3d.Primitive.LINELIST;
- numberPrimitives = 12;
- indicesArray = [
- 0, 1,
- 1, 3,
- 3, 2,
- 2, 0,
- 6, 7,
- 7, 5,
- 5, 4,
- 4, 6,
- 2, 4,
- 3, 5,
- 0, 6,
- 1, 7
- ];
- indicesPerLine = 2;
- break;
- case 'LineStrip':
- primitiveType = g_o3d.Primitive.LINESTRIP;
- numberPrimitives = 8;
- // Forms an incomplete cube, where indices 0 and 1 are the first segment,
- // 1 and 3 are the second segement, 3 and 5 are the third, and so forth.
- indicesArray = [0, 1, 3, 5, 7, 6, 4, 2, 0];
- indicesPerLine = 0;
- break;
- case 'TriangleList':
- primitiveType = g_o3d.Primitive.TRIANGLELIST;
- numberPrimitives = 12;
- indicesArray = [
- 0, 1, 2, // face 1
- 2, 1, 3,
- 2, 3, 4, // face 2
- 4, 3, 5,
- 4, 5, 6, // face 3
- 6, 5, 7,
- 6, 7, 0, // face 4
- 0, 7, 1,
- 1, 7, 3, // face 5
- 3, 7, 5,
- 6, 0, 4, // face 6
- 4, 0, 2
- ];
- indicesPerLine = 3;
- break;
- case 'TriangleStrip':
- primitiveType = g_o3d.Primitive.TRIANGLESTRIP;
- numberPrimitives = 8;
- // Forms a cube missing two faces. Indices (0, 1, 2) forms the first
- // triangle, (1, 2, 3) forms the second triangle, and so forth.
- indicesArray = [0, 1, 2, 3, 4, 5, 6, 7, 0, 1];
- indicesPerLine = 0;
- break;
- case 'TriangleFan':
- primitiveType = g_o3d.Primitive.TRIANGLEFAN;
- numberPrimitives = 6;
- // Forms a half cube, missing three faces. Indices (2, 0, 1) forms the
- // first triangle, (2, 1, 3) is the second, (2, 3, 5) is the third, etc.
- indicesArray = [2, 0, 1, 3, 5, 4, 6, 0];
- indicesPerLine = 0;
- break;
- default:
- alert('Invalid selection type!');
- return;
- }
-
- g_cubePrimitive.primitiveType = primitiveType;
- g_cubePrimitive.numberPrimitives = numberPrimitives;
-
- var verticesString = '';
- var indicesString = '';
-
- if (indexed == 'Yes') {
- g_cubePrimitive.indexBuffer = g_indexBuffer;
- g_indexBuffer.set(indicesArray);
- g_positionBuffer.set(g_positionArray);
- verticesString = numberArrayToString(g_positionArray, 3);
- indicesString = numberArrayToString(indicesArray, indicesPerLine);
- } else {
- g_cubePrimitive.indexBuffer = null;
- var positionArray = createPositionArray(g_positionArray, indicesArray)
- g_positionBuffer.set(positionArray);
- verticesString = numberArrayToString(positionArray, 3);
- indicesString = 'null';
- }
-
- document.getElementById('vertices').value = verticesString;
- document.getElementById('indices').value = indicesString;
-}
-
-
-/**
- * Creates an array of vertex coordinates by indexing into the given array of
- * position coordinates according to the indices provided.
- * @param {!Array.<number>} positions The positions array to be indexed into.
- * @param {!Array.<number>} indices The indices.
- * @return {!Array.<number>} A new array of positions.
- */
-function createPositionArray(positions, indices) {
- var newPositions = [];
- for (var i = 0; i < indices.length; ++i) {
- var t = 3 * indices[i];
- newPositions.push(positions[t], positions[t + 1], positions[t + 2]);
- }
- return newPositions;
-}
-
-
-/**
- * Converts an array of numbers to a string.
- * @param {!Array.<number>} a An array of numbers.
- * @param {number} numbersPerLine The number of numbers per line
- * @return {string} A string representation of that array.
- */
-function numberArrayToString(a, numbersPerLine) {
- var s = ''
- var n = a.length;
- for (var i = 0; i < n; i++) {
- s += '' + a[i];
-
- if (i != n-1) {
- s += ','
- }
-
- if ((i + 1) % numbersPerLine == 0 || i == n-1) {
- s += '\n'
- } else {
- s += ' ';
- }
- }
- return s;
-}
-
-
-/**
- * Changes the fill mode on the state associated with the cube material.
- * @param {string} type The desired fill mode.
- */
-function changeFillMode(mode_string) {
- var mode = o3d.State.SOLID;
- switch (mode_string) {
- case 'Point':
- mode = o3d.State.POINT;
- break;
- case 'Wireframe':
- mode = o3d.State.WIREFRAME;
- break;
- case 'Solid':
- default:
- mode = o3d.State.SOLID;
- break;
- }
-
- g_material.state.getStateParam('FillMode').value = mode;
-}
-
-
-/**
- * Creates an O3D shape representing a cube. The shape consists of
- * a single primitive with eight vertices.
- *
- * @param {o3d.Material} material the material used by the primitive.
- * @return {o3d.Shape} The Shape object created.
- */
-function createCube(material) {
- // Create a Shape object for the mesh.
- var cubeShape = g_pack.createObject('Shape');
-
- // Create the Primitive that will contain the geometry data for
- // the cube.
- g_cubePrimitive = g_pack.createObject('Primitive');
-
- // Create a StreamBank to hold the streams of vertex data.
- var streamBank = g_pack.createObject('StreamBank');
-
- // Assign the material that was passed in to the primitive.
- g_cubePrimitive.material = material;
-
- // Assign the Primitive to the Shape.
- g_cubePrimitive.owner = cubeShape;
-
- // Assign the StreamBank to the Primitive.
- g_cubePrimitive.streamBank = streamBank;
-
- // Generate the draw element for the cube primitive.
- g_cubePrimitive.createDrawElement(g_pack, null);
-
- // Create a javascript array that stores the X, Y and Z coordinates of each
- // of the 8 corners of the cube.
- g_positionArray = [
- -0.5, -0.5, 0.5,
- 0.5, -0.5, 0.5,
- -0.5, 0.5, 0.5,
- 0.5, 0.5, 0.5,
- -0.5, 0.5, -0.5,
- 0.5, 0.5, -0.5,
- -0.5, -0.5, -0.5,
- 0.5, -0.5, -0.5
- ];
-
- // Create buffer containing the vertex data.
- g_positionBuffer = g_pack.createObject('VertexBuffer');
- var positionField = g_positionBuffer.createField('FloatField', 3);
-
- g_positionBuffer.set(g_positionArray);
- g_indexBuffer = g_pack.createObject('IndexBuffer');
- g_cubePrimitive.indexBuffer = g_indexBuffer;
-
- // Associate the positions field with the StreamBank.
- streamBank.setVertexStream(
- g_o3d.Stream.POSITION, // semantic: This stream stores vertex positions
- 0, // semantic index: First (and only) position stream
- positionField, // field: the field this stream uses.
- 0); // start_index: How many elements to skip in the
- // field.
-
- return cubeShape;
-}
-
-
-/**
- * This method gets called every time O3D renders a frame. Here's where
- * we update the cube's transform to make it spin.
- * @param {o3d.RenderEvent} renderEvent The render event object that gives
- * us the elapsed time since the last time a frame was rendered.
- */
-function renderCallback(renderEvent) {
- g_clock += renderEvent.elapsedTime * g_timeMult;
- // Rotate the cube around the Y axis.
- g_cubeTransform.identity();
- g_cubeTransform.rotateY(2.0 * g_clock);
-}
-
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-
-/**
- * Initializes O3D, creates the cube and sets up the transform and
- * render graphs.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_client = o3dElement.client;
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- var viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot,
- [1, 1, 1, 1]);
-
- // Set up a perspective projection.
- viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree fov.
- g_client.width / g_client.height,
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // cube is located.
- viewInfo.drawContext.view = g_math.matrix4.lookAt([0, 1, 5], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- // Create an Effect object and initialize it using the shaders from the
- // text area.
- var myEffect = g_pack.createObject('Effect');
- var vertexShaderString = document.getElementById('vshader').value;
- var pixelShaderString = document.getElementById('pshader').value;
- myEffect.loadVertexShaderFromString(vertexShaderString);
- myEffect.loadPixelShaderFromString(pixelShaderString);
-
- // Create a Material for the mesh.
- g_material = g_pack.createObject('Material');
-
- // Set the material's drawList.
- g_material.drawList = viewInfo.performanceDrawList;
-
- g_material.state = g_pack.createObject('State');
-
- // Turn off culling.
- viewInfo.performanceDrawPassInfo.state.getStateParam('CullMode').value =
- g_o3d.State.CULL_NONE;
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shaders to use.
- g_material.effect = myEffect;
-
- // Create the Shape for the cube mesh and assign its material.
- var cubeShape = createCube(g_material);
-
- // Render with line lists to begin with.
- changePrimitive('LineList', 'Yes');
- changeFillMode('Solid');
-
- // Create a new transform and parent the Shape under it.
- g_cubeTransform = g_pack.createObject('Transform');
- g_cubeTransform.addShape(cubeShape);
-
- // Parent the cube's transform to the client root.
- g_cubeTransform.parent = g_client.root;
-
- // Set our render callback for animation.
- // This sets a function to be executed every time a frame is rendered.
- g_client.setRenderCallback(renderCallback);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Hello Cube - Primitives</h1>
-This example shows how to display a cube in O3D using different primitive types.
-<br/>
-
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-
-<form name="default_form" action="#" method="get">
- <p>
- Indexed:
- <select onchange="changePrimitive(
- g_currentPrimitiveType, this.options[this.selectedIndex].value);">
- <option value="Yes" selected>Yes</option>
- <option value="No">No</option>
- </select>
- </p>
-
- <p>
- Primitive type:
- <select onchange="changePrimitive(
- this.options[this.selectedIndex].value, g_currentIndexed);">
- <option value="PointList">PointList</option>
- <option value="LineList" selected>LineList</option>
- <option value="LineStrip">LineStrip</option>
- <option value="TriangleList">TriangleList</option>
- <option value="TriangleStrip">TriangleStrip</option>
- <option value="TriangleFan">TriangleFan</option>
- </select>
- </p>
-
- <p>
- Fill mode:
- <select onchange="changeFillMode(this.options[this.selectedIndex].value);">
- <option value="Point">Point</option>
- <option value="Wireframe">Wireframe</option>
- <option value="Solid" selected>Solid</option>
- </select>
- </p>
-</form>
-
-<table>
- <tr>
- <td>
- <center>Vertex Buffer</center>
- </td>
- <td>
- <center>Index Buffer</center>
- </td>
- </tr>
- <tr>
- <td>
- <textarea id="vertices" cols=30 rows=15> </textarea>
- </td>
- <td>
- <textarea id="indices" cols=30 rows=15> </textarea>
- </td>
- </tr>
-</table>
-
-<!-- End of O3D plugin -->
-
-<!-- Don't render the textarea -->
-<div style="display:none">
-<!-- Start of effect -->
-<textarea id="vshader">
- attribute vec4 position;
-
- uniform mat4 world;
- uniform mat4 view;
- uniform mat4 projection;
-
- varying vec4 pos;
-
- /**
- * The vertex shader simply transforms the input vertices to screen space.
- */
- void main() {
- // Multiply the vertex positions by the worldViewProjection matrix to
- // transform them to screen space.
- gl_Position = projection * view * world * position;
- // Make points larger, so they can been seen.
- gl_PointSize = 5.0;
- pos = position;
- }
-</textarea>
-<textarea id="pshader">
- varying vec4 pos;
-
- /**
- * The fragment shader derives color based on the position.
- */
- void main() {
- gl_FragColor = pos;
- }
-</textarea>
-<!-- End of effect -->
-</div>
-</body>
-</html>
-
diff --git a/o3d/samples/o3d-webgl-samples/hellocube.html b/o3d/samples/o3d-webgl-samples/hellocube.html
deleted file mode 100644
index 8655b62..0000000
--- a/o3d/samples/o3d-webgl-samples/hellocube.html
+++ /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.
--->
-
-<!--
-This sample shows how to place an O3D area in a page and draw simple
-3D shape in it.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Hello Cube: Getting started with O3D
-</title>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// Run the init() function once the page has finished loading.
-// Run the uninit() function when the page has is unloaded.
-window.onload = init;
-window.onunload = uninit;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_cubeTransform = null;
-var g_finished = false; // for selenium testing
-
-/**
- * Creates an O3D shape representing a cube. The shape consists of
- * a single primitive with eight vertices and 12 triangles (two for each face
- * of the cube).
- * @param {o3d.Material} material the material used by the primitive.
- * @return {o3d.Shape} The Shape object created.
- */
-function createCube(material) {
- // Create a Shape object for the mesh.
- var cubeShape = g_pack.createObject('Shape');
-
- // Create the Primitive that will contain the geometry data for
- // the cube.
- var cubePrimitive = g_pack.createObject('Primitive');
-
- // Create a StreamBank to hold the streams of vertex data.
- var streamBank = g_pack.createObject('StreamBank');
-
- // Assign the material that was passed in to the primitive.
- cubePrimitive.material = material;
-
- // Assign the Primitive to the Shape.
- cubePrimitive.owner = cubeShape;
-
- // Assign the StreamBank to the Primitive.
- cubePrimitive.streamBank = streamBank;
-
- // The cube is made of 12 triangles. There's eight vertices in total which
- // are shared between the face triangles.
- cubePrimitive.primitiveType = g_o3d.Primitive.TRIANGLELIST;
- cubePrimitive.numberPrimitives = 12; // 12 triangles
- cubePrimitive.numberVertices = 8; // 8 vertices in total
-
- // Generate the draw element for the cube primitive.
- cubePrimitive.createDrawElement(g_pack, null);
-
- // Create a javascript array that stores the X, Y and Z coordinates of each
- // of the 8 corners of the cube.
- var positionArray = [
- -0.5, -0.5, 0.5, // vertex 0
- 0.5, -0.5, 0.5, // vertex 1
- -0.5, 0.5, 0.5, // vertex 2
- 0.5, 0.5, 0.5, // vertex 3
- -0.5, 0.5, -0.5, // vertex 4
- 0.5, 0.5, -0.5, // vertex 5
- -0.5, -0.5, -0.5, // vertex 6
- 0.5, -0.5, -0.5 // vertex 7
- ];
-
- // The following array defines how vertices are to be put together to form
- // the triangles that make up the cube's faces. In the index array, every
- // three elements define a triangle. So for example vertices 0, 1 and 2
- // make up the first triangle, vertices 2, 1 and 3 the second one, etc.
- var indicesArray = [
- 0, 1, 2, // face 1
- 2, 1, 3,
- 2, 3, 4, // face 2
- 4, 3, 5,
- 4, 5, 6, // face 3
- 6, 5, 7,
- 6, 7, 0, // face 4
- 0, 7, 1,
- 1, 7, 3, // face 5
- 3, 7, 5,
- 6, 0, 4, // face 6
- 4, 0, 2
- ];
-
- // Create buffers containing the vertex data.
- var positionsBuffer = g_pack.createObject('VertexBuffer');
- var positionsField = positionsBuffer.createField('FloatField', 3);
- positionsBuffer.set(positionArray);
-
- var indexBuffer = g_pack.createObject('IndexBuffer');
- indexBuffer.set(indicesArray);
-
- // Associate the positions Buffer with the StreamBank.
- streamBank.setVertexStream(
- g_o3d.Stream.POSITION, // semantic: This stream stores vertex positions
- 0, // semantic index: First (and only) position stream
- positionsField, // field: the field this stream uses.
- 0); // start_index: How many elements to skip in the
- // field.
-
- // Associate the triangle indices Buffer with the primitive.
- cubePrimitive.indexBuffer = indexBuffer;
-
- return cubeShape;
-}
-
-/**
- * This method gets called every time O3D renders a frame. Here's where
- * we update the cube's transform to make it spin.
- * @param {o3d.RenderEvent} renderEvent The render event object that gives
- * us the elapsed time since the last time a frame was rendered.
- */
-function renderCallback(renderEvent) {
- g_clock += renderEvent.elapsedTime * g_timeMult;
- // Rotate the cube around the Y axis.
- g_cubeTransform.identity();
- g_cubeTransform.rotateY(2.0 * g_clock);
-}
-
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, creates the cube and sets up the transform and
- * render graphs.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_client = o3dElement.client;
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- var viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set up a perspective projection.
- viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree fov.
- g_client.width / g_client.height,
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // cube is located.
- viewInfo.drawContext.view = g_math.matrix4.lookAt([0, 1, 5], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- // Create an Effect object and initialize it using the shaders from the
- // text area.
- var redEffect = g_pack.createObject('Effect');
- var vertexShaderString = document.getElementById('vshader').value;
- var pixelShaderString = document.getElementById('pshader').value;
- redEffect.loadVertexShaderFromString(vertexShaderString);
- redEffect.loadPixelShaderFromString(pixelShaderString);
-
- // Create a Material for the mesh.
- var redMaterial = g_pack.createObject('Material');
-
- // Set the material's drawList.
- redMaterial.drawList = viewInfo.performanceDrawList;
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shaders to use.
- redMaterial.effect = redEffect;
-
- // Create the Shape for the cube mesh and assign its material.
- var cubeShape = createCube(redMaterial);
-
- // Create a new transform and parent the Shape under it.
- g_cubeTransform = g_pack.createObject('Transform');
- g_cubeTransform.addShape(cubeShape);
-
- // Parent the cube's transform to the client root.
- g_cubeTransform.parent = g_client.root;
-
- // Set our render callback for animation.
- // This sets a function to be executed every time a frame is rendered.
- g_client.setRenderCallback(renderCallback);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Hello Cube</h1>
-This example shows how to display a spinning red cube in O3D.
-<br/>
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-
-<!-- Don't render the textarea -->
-<div style="display:none">
-<!-- Start of effect -->
-<textarea id="vshader">
- // World View Projection matrix that will transform the input vertices
- // to screen space.
- attribute vec4 position;
-
- uniform mat4 world;
- uniform mat4 view;
- uniform mat4 projection;
-
- /**
- * The vertex shader simply transforms the input vertices to screen space.
- */
- void main() {
- // Multiply the vertex positions by the worldViewProjection matrix to
- // transform them to screen space.
- gl_Position = projection * view * world * position;
- }
-</textarea>
-<textarea id="pshader">
- /**
- * This pixel shader just returns the color red.
- */
- void main() {
- gl_FragColor = vec4(1, 0, 0, 1); // Red.
- }
-</textarea>
-<!-- End of effect -->
-</div>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/helloworld.html b/o3d/samples/o3d-webgl-samples/helloworld.html
deleted file mode 100644
index c2ce678..0000000
--- a/o3d/samples/o3d-webgl-samples/helloworld.html
+++ /dev/null
@@ -1,177 +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.
--->
-
-<!--
-O3D Tutorial A1
-
-In this tutorial, we load and display a scene in O3D.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Tutorial A1: Loading a scene
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-// unload() when leaving the page.
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_finished = false; // for selenium testing
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- */
-function loadScene(pack, fileName, parent) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- g_client.width,
- g_client.height);
-
- // Copy the view and projection to the draw context.
- g_viewInfo.drawContext.view = cameraInfo.view;
- g_viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
-
- g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
- // The following call enables a debug WebGL context, which makes
- // debugging much easier.
- // o3djs.webgl.makeClients(initStep2, undefined, undefined, undefined, undefined, undefined, true);
-}
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Creates a transform to put our data on.
- var myDataRoot = g_pack.createObject('Transform');
-
- // Connects our root to the client root.
- myDataRoot.parent = g_client.root;
-
- // Load the scene into the transform graph as a child myDataRoot
- loadScene(g_pack, '../assets/teapot/scene.json', myDataRoot);
-}
-</script>
-</head>
-<body>
-<h1>Loading a scene.</h1>
-This tutorial shows how we load and display a scene in O3D.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/hud-2d-overlay.html b/o3d/samples/o3d-webgl-samples/hud-2d-overlay.html
deleted file mode 100644
index 9d7b967..0000000
--- a/o3d/samples/o3d-webgl-samples/hud-2d-overlay.html
+++ /dev/null
@@ -1,493 +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.
--->
-
-<!--
-HUD 2D Overlay.
-
-This example shows implementing a HUD or 2d Overlay
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-HUD 2D Overlay.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.loader');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_3dRoot;
-var g_hudRoot;
-var g_viewInfo;
-var g_hudViewInfo;
-var g_pack;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-var g_cameraRadius = 35;
-var g_cameraSpeed = 0.3;
-var g_gaugeWidth = 145;
-var g_gaugeHeight = 16;
-var g_planeShape;
-var g_groundShape;
-var g_cubeShape;
-var g_materialUrls = [
- '../shaders/texture-colormult-glsl.shader', // 0
- '../shaders/phong-with-colormult-glsl.shader' // 1
-];
-var g_materials = [];
-var g_textures = [];
-var g_textureUrls = [
- '../assets/purple-flower.png', // 0
- '../assets/orange-flower.png', // 1
- '../assets/egg.png', // 2
- '../assets/gaugeback.png', // 3
- '../assets/gauge.png', // 4
- '../assets/iconback.png', // 5
- '../assets/radar.png', // 6
- '../assets/one-pixel-white.png' // 7
-];
-var g_radar;
-var g_radarNeedle;
-var g_gaugeBack;
-var g_gauges = [];
-var g_gaugeFrames = [];
-var g_iconBacks = [];
-var g_icons = [];
-var g_selectedIndex = 0;
-var g_randSeed = 0;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create 2 root transforms, one for the 3d parts, one for the 2d parts.
- // This is not strictly neccassary but it is helpful for organization.
- g_3dRoot = g_pack.createObject('Transform');
- g_hudRoot = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_3dRoot,
- g_client.renderGraphRoot);
-
- // Create a second view for the hud. There are other ways to do this but
- // this is the easiest.
- g_hudViewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_hudRoot,
- g_client.renderGraphRoot);
-
- // Make sure the hud gets drawn after the 3d stuff
- g_hudViewInfo.root.priority = g_viewInfo.root.priority + 1;
-
- // Turn off clearing the color for the hud since that would erase the 3d
- // parts but leave clearing the depth and stencil so the HUD is unaffected
- // by anything done by the 3d parts.
- g_hudViewInfo.clearBuffer.clearColorFlag = false;
-
- // Set culling to none so we can flip images using rotation or negative scale.
- g_hudViewInfo.zOrderedState.getStateParam('CullMode').value =
- g_o3d.State.CULL_NONE;
- g_hudViewInfo.zOrderedState.getStateParam('ZWriteEnable').value = false;
-
- // Create an orthographic matrix for 2d stuff in the HUD.
- // We assume the area is 800 pixels by 600 pixels and therefore we can
- // position things using a 0-799, 0-599 coordinate system. If we change the
- // size of the client area everything will get scaled to fix but we don't
- // have to change any of our code. See 2d.html
- g_hudViewInfo.drawContext.projection = g_math.matrix4.orthographic(
- 0 + 0.5,
- 800 + 0.5,
- 600 + 0.5,
- 0 + 0.5,
- 0.001,
- 1000);
-
- g_hudViewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 0, 1], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree fov.
- g_client.width / g_client.height,
- 0.1, // Near plane.
- 5000); // Far plane.
-
- for (var ii = 0; ii < g_materialUrls.length; ++ii) {
- var material = o3djs.material.createMaterialFromFile(
- g_pack,
- g_materialUrls[ii],
- g_viewInfo.performanceDrawList);
-
- // Set the default params. We'll override these with params on transforms.
- material.getParam('colorMult').value = [1, 1, 1, 1];
-
- g_materials[ii] = material;
- }
-
- // Set the materials' drawLists
- g_materials[0].drawList = g_hudViewInfo.zOrderedDrawList;
- g_materials[1].drawList = g_viewInfo.performanceDrawList;
-
- g_materials[1].getParam('lightWorldPos').value = [500, 1000, 0];
- g_materials[1].getParam('lightIntensity').value = [1, 1, 1, 1];
- g_materials[1].getParam('ambientIntensity').value = [0.1, 0.1, 0.1, 1];
- g_materials[1].getParam('ambient').value = [1, 1, 1, 1];
- g_materials[1].getParam('diffuse').value = [1, 1, 1, 1];
- g_materials[1].getParam('specular').value = [0.5, 0.5, 0.5, 1];
- g_materials[1].getParam('shininess').value = 20;
-
- // Create a 2d plane for images. createPlane makes an XZ plane by default
- // so we pass in matrix to rotate it to an XY plane. We could do
- // all our manipluations in XZ but most people seem to like XY for 2D.
- g_planeShape = o3djs.primitives.createPlane(
- g_pack,
- g_materials[0],
- 1,
- 1,
- 1,
- 1,
- o3djs.math.makeMatrix4(1, 0, 0, 0,
- 0, 0, 1, 0,
- 0,-1, 0, 0,
- 0, 0, 0, 1));
-
- // Create a ground plane
- g_groundShape = o3djs.primitives.createPlane(
- g_pack,
- g_materials[1],
- 30,
- 30,
- 10,
- 10);
-
- // Create a cube with its origin at the bottom center.
- g_cubeShape = o3djs.primitives.createCube(
- g_pack,
- g_materials[1],
- 1,
- o3djs.math.makeMatrix4(0.9, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 0.9, 0,
- 0, 0.5, 0, 1));
-
- // Load all the textures.
- var loader = o3djs.loader.createLoader(initStep3);
- for (var ii = 0; ii < g_textureUrls.length; ++ii) {
- loadTexture(loader, g_textureUrls[ii], ii);
- }
- loader.finish();
-}
-
-/**
- * Loads a texture and saves it in the g_textures array.
- * @param {Object} loader The loader to load with.
- * @param {stinrg} url of texture to load
- * @param {number} index Index to put texture in g_textures
- */
-function loadTexture(loader, url, index) {
- loader.loadTexture(g_pack, url, function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- g_textures[index] = texture;
- }
- });
-}
-
-/**
- * Now that the textures are loaded continue.
- */
-function initStep3() {
- // Setup the hud images.
- g_radar = new ImageTransform(g_textures[6], true);
- g_radar.transform.translate(3, 1, -2);
-
- g_radarNeedle = new ImageTransform(g_textures[7], false);
- g_radarNeedle.scaleTransform.translate(0, 0.5, 0);
-
- g_gaugeBack = new ImageTransform(g_textures[3], true);
- g_gaugeBack.transform.translate(201, 17, -2);
-
- for (var ii = 0; ii < 3; ++ii) {
- g_gaugeFrames[ii] = new ImageTransform(g_textures[4], true);
- g_gaugeFrames[ii].transform.translate(220, 39 + ii * 21, -2);
-
- g_gauges[ii] = new ImageTransform(g_textures[7], true);
- g_gauges[ii].setColor((ii == 0) ? 1 : 0,
- (ii == 1) ? 1 : 0,
- (ii == 2) ? 1 : 0,
- 1);
-
- g_iconBacks[ii] = new ImageTransform(g_textures[5], true);
- g_iconBacks[ii].transform.translate(634, 17 + ii * 140, -2);
-
- // Make the icons' origin their center so we can easily rotate/scale them.
- g_icons[ii] = new ImageTransform(g_textures[ii], false);
- }
-
- resetIcons();
-
- // make the ground plane.
- var transform = g_pack.createObject('Transform');
- transform.addShape(g_groundShape);
- transform.parent = g_3dRoot;
- transform.createParam('colorMult', 'ParamFloat4').value =
- [166 / 255, 124 / 255, 82 / 255, 1];
-
- // Make a random city with 25 blocks.
- for (var bz = -2; bz <= 2; ++bz) {
- for (var bx = -2; bx <= 2; ++bx) {
- for (var xx = 0; xx < 4; ++xx) {
- createBuilding(bx * 5 + 1 + xx - 1.5, bz * 5 + 1 - 1.5);
- createBuilding(bx * 5 + 1 + xx - 1.5, bz * 5 + 4 - 1.5);
- }
- for (var zz = 1; zz < 3; ++zz) {
- createBuilding(bx * 5 + 1 - 1.5, bz * 5 + 1 + zz - 1.5);
- createBuilding(bx * 5 + 4 - 1.5, bz * 5 + 1 + zz - 1.5);
- }
- }
- }
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Creates a building.
- * @param {number} x X coordinate to create building at
- * @param {number} z Y coordinate to create building at
- */
-function createBuilding(x, z) {
- var transform = g_pack.createObject('Transform');
- transform.addShape(g_cubeShape);
- transform.parent = g_3dRoot;
- transform.translate(x, 0, z);
- transform.scale(1, g_math.pseudoRandom() * 3 + 1, 1);
- transform.createParam('colorMult', 'ParamFloat4').value = [
- g_math.pseudoRandom() * 0.6 + 0.4,
- g_math.pseudoRandom() * 0.6 + 0.4,
- g_math.pseudoRandom() * 0.6 + 0.4,
- 1];
-}
-
-/**
- * Resets the orientation of the icons.
- */
-function resetIcons() {
- for (var ii = 0; ii < g_icons.length; ++ii) {
- g_icons[ii].transform.identity();
- g_icons[ii].transform.translate(634 + 6 + 64, 17 + ii * 140 + 5 + 64, -1);
- g_icons[ii].transform.scale(0.8, 0.8, 0);
- }
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onrender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- g_selectedIndex = Math.floor(g_clock / 3) % 3;
-
- // Fly the camera around the city.
- var eye = [
- Math.sin(g_clock * g_cameraSpeed) * g_cameraRadius,
- 10,
- Math.cos(g_clock * g_cameraSpeed) * g_cameraRadius];
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- eye,
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- for (var i = 0; i < g_icons.length; i++) {
- var icon = g_icons[i];
- icon.transform.identity();
- icon.transform.translate(
- 634 + 6 + 64, 17 + i * 140 + 5 + 64, -1);
- if (i == g_selectedIndex) {
- icon.transform.rotateZ(g_clock * -1);
- var scale = Math.sin(g_clock * 15) * 0.1 + 0.7;
- icon.transform.scale(scale, scale, 1);
- } else {
- icon.transform.scale(0.8, 0.8, 0);
- }
- }
-
- // Adjust the gauges
- for (var ii = 0; ii < 3; ++ii) {
- var gauge = g_gauges[ii];
- gauge.transform.identity();
- gauge.transform.translate(220 + 1, 39 + ii * 21 + 1, -1);
- switch (ii) {
- case 0:
- gauge.transform.scale((Math.sin(g_clock) * 0.5 + 0.5) * g_gaugeWidth,
- g_gaugeHeight,
- 1);
- break;
- case 1:
- gauge.transform.scale((Math.cos(g_clock) * 0.5 + 0.5) * g_gaugeWidth,
- g_gaugeHeight,
- 1);
- break;
- case 2:
- gauge.transform.scale(
- (Math.cos(g_clock * 3.2) * 0.2 + 0.6) * g_gaugeWidth,
- g_gaugeHeight,
- 1);
- break;
- }
- }
-
- // Rotate the radar
- g_radarNeedle.transform.identity();
- g_radarNeedle.transform.translate(93, 89, 0);
- g_radarNeedle.transform.rotateZ(g_clock * 3);
- g_radarNeedle.transform.scale(1, 80, 1);
-}
-
-/**
- * Creates an ImageTransform object which is a transform and a child
- * scaleTransform scaled to match the texture
- *
- * @constructor
- * @param {!o3d.Texture} texture The texture
- * @param {boolean} opt_topLeft If true the origin of the image will be its
- * topleft corner, the default is the center of the image.
- */
-function ImageTransform(texture, opt_topLeft) {
- // create a transform for positioning
- this.transform = g_pack.createObject('Transform');
- this.transform.parent = g_hudRoot;
-
- // create a transform for scaling to the size of the image just so
- // we don't have to manage that manually in the transform above.
- this.scaleTransform = g_pack.createObject('Transform');
- this.scaleTransform.parent = this.transform;
-
- // setup the sampler for the texture
- this.sampler = g_pack.createObject('Sampler');
- this.sampler.addressModeU = g_o3d.Sampler.CLAMP;
- this.sampler.addressModeV = g_o3d.Sampler.CLAMP;
- this.paramSampler = this.scaleTransform.createParam('texSampler0',
- 'ParamSampler');
- this.paramSampler.value = this.sampler;
-
- // Setup our UV offsets and color multiplier
- this.paramColorMult = this.scaleTransform.createParam('colorMult',
- 'ParamFloat4');
-
- this.setColor(1, 1, 1, 1);
-
- this.sampler.texture = texture;
- this.scaleTransform.addShape(g_planeShape);
- if (opt_topLeft) {
- this.scaleTransform.translate(texture.width / 2, texture.height / 2, 0);
- }
- this.scaleTransform.scale(texture.width, -texture.height, 1);
-}
-
-/**
- * Sets the color multiplier for the image.
- * @param {number} r Red component.
- * @param {number} g Green component.
- * @param {number} b Blue component.
- * @param {number} a Alpha component.
- */
-ImageTransform.prototype.setColor = function(r, g, b, a) {
- this.paramColorMult.value = [r, g, b, a];
-};
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>HUD 2D Overlay</h1>
-HUD = Heads Up Display.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/instance-override.html b/o3d/samples/o3d-webgl-samples/instance-override.html
deleted file mode 100644
index 37132fe..0000000
--- a/o3d/samples/o3d-webgl-samples/instance-override.html
+++ /dev/null
@@ -1,182 +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.
--->
-
-<!--
-O3D Instancing Override example.
-
-Display a single instanced object but change some shader parameters for each
-instance by putting them on the transform.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Instancing with Overrides.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing.
-
-function createInstances(pack, shape) {
- // make a grid of transforms and put a sphere instance on each one
- for (var x = 0; x < 10; x++) {
- for (var y = 0; y < 10; y++) {
- for (var z = 0; z < 10; z++) {
- var transform = pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.addShape(shape);
- transform.translate((x - 4.5) * 100,
- (y - 4.5) * 100,
- (z - 4.5) * 100);
- transform.createParam('diffuse', 'ParamFloat4').value = [
- x * 0.1,
- y * 0.1,
- z * 0.1,
- 1.0];
- }
- }
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates a sphere.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 10000);
-
- // Create a material.
- var material = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [1, 1, 1, 1]);
-
- // Create a sphere.
- var shape = o3djs.primitives.createSphere(g_pack, material, 25, 10, 12);
-
- createInstances(g_pack, shape);
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-// spin the camera.
-function onrender(render_event) {
- // Get the number of seconds since the last render.
- var elapsedTime = render_event.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- var x = Math.sin(g_clock * 0.3) * 1000;
- var z = Math.cos(g_clock * 0.3) * 1000;
- var y = Math.sin(g_clock * 0.7) * 500;
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [x, y, z], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Instancing with overrides</h1>
-1000 Instances of the same sphere.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/instancing.html b/o3d/samples/o3d-webgl-samples/instancing.html
deleted file mode 100644
index 2ddad3c..0000000
--- a/o3d/samples/o3d-webgl-samples/instancing.html
+++ /dev/null
@@ -1,211 +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.
--->
-
-<!--
-O3D Instancing example.
-
-Load the teapot, display it a bunch of times.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Instancing.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- */
-function loadScene(pack, fileName, parent) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
-
- // Find the "shape" for the teapot.
- // I'm going to assume there is only one since I know the contents
- // of the file.
- var shape = pack.getObjectsByClassName('o3d.Shape')[0];
-
- // now make a grid of transforms and put a teapot instance on each one
- for (var x = 0; x < 10; x++) {
- for (var y = 0; y < 10; y++) {
- for (var z = 0; z < 10; z++) {
- var transform = pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.addShape(shape);
- var angles = [
- (x - 4.5) * 0.2,
- (y - 4.5) * 0.2,
- (z - 4.5) * 0.2];
- transform.translate((x - 4.5) * 100,
- (y - 4.5) * 100,
- (z - 4.5) * 100);
- transform.rotateZYX(angles);
- }
- }
- }
-
- g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 10000);
-
- // Creates a transform to put our data on.
- var my_data_root = g_pack.createObject('Transform');
-
- // Load the scene into the transform graph as a child my_data_root
- loadScene(g_pack, '../assets/teapot/scene.json', my_data_root);
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-}
-
-// spin the camera.
-function onrender(render_event) {
- // Get the number of seconds since the last render.
- var elapsedTime = render_event.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- var x = Math.sin(g_clock * 0.41) * 400;
- var z = Math.cos(g_clock * 0.31) * 1000;
- var y = Math.sin(g_clock * 0.61) * 200;
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt([x, y, z], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Instancing</h1>
-1000 Teapots
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/juggler.html b/o3d/samples/o3d-webgl-samples/juggler.html
deleted file mode 100644
index 133e6c8..0000000
--- a/o3d/samples/o3d-webgl-samples/juggler.html
+++ /dev/null
@@ -1,453 +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.
--->
-
-<!--
-O3D Juggler
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html style="width: 100%; height: 100%;">
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
- Juggler Shader
-</title>
-
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-
-// Events
-// Run the init() function once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_o3dElement;
-var g_viewInfo;
-var g_pack;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-var g_transform;
-var g_clock = 0.0;
-var g_timeMult = 1; // amount to multiply elapsed time by.
- // Used to make the animation run faster or slower.
-var g_finished = false; // for selenium testing
-var g_thetaParam;
-var g_numParam;
-var g_numBalls; // Must be either 3, 5, 7, or 9 for now.
-var g_speedScale; // Used to make higher numbers of balls animate faster.
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and creates the square.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Create a g_pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot,
- [0, 0, 0, 1]);
-
- var effect = g_pack.createObject('Effect');
- effect.loadFromFXString(document.getElementById('shader').value);
-
- // Create a Material for the effect.
- var myMaterial = g_pack.createObject('Material');
-
- // Apply our effect to this material.
- myMaterial.effect = effect;
-
- // Set the material's drawList for opaque objects.
- myMaterial.drawList = g_viewInfo.performanceDrawList;
-
- // Create the params the effect needs on the material.
- effect.createUniformParameters(myMaterial);
-
- // Create a square.
- var myShape = o3djs.primitives.createPlane(g_pack, myMaterial,
- 1, 1, 1, 1);
-
- // Set up the individual parameters in our effect file.
- g_thetaParam = myMaterial.getParam('theta');
- g_thetaParam.value = 0.0;
- g_numParam = myMaterial.getParam('num');
- updateNum();
-
- // Set the position of the camera.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 1, 0], //eye
- [0, 0, 0], //target
- [0, 0, -1]); //up
-
- // Generate the projection matrix based
- // on the g_o3d plugin size by calling resize().
- resize();
-
- // Now attach the square to the root of the transform graph.
- g_client.root.addShape(myShape);
-
- toggleRenderCallback();
-
- g_finished = true; // for selenium testing.
-}
-
-function updateNum() {
- var group = document.the_form.radio_group;
- for (var i = 0; i < group.length; ++i) {
- if (group[i].checked) {
- setNumBalls(parseInt(group[i].value));
- }
- }
-}
-
-function toggleRenderCallback() {
- var box = document.the_form.check_box;
- if (box.checked) {
- g_client.setRenderCallback(onrender);
- } else {
- g_client.clearRenderCallback();
- }
-}
-
-function setNumBalls(num) {
- g_numBalls = num;
- g_numParam.value = g_numBalls;
- g_speedScale = Math.sqrt(g_numBalls) * 5;
-}
-
-function onrender(render_event) {
- g_clock += render_event.elapsedTime * g_timeMult;
- g_thetaParam.value = g_clock * g_speedScale;
-
- // If we don't check the size of the client area every frame we don't get a
- // chance to adjust the perspective matrix fast enough to keep up with the
- // browser resizing us, so onrender must call resize.
- resize();
-}
-
-
-// Generates the projection matrix based on the size of the g_o3d plugin
-// and calculates the view-projection matrix.
-function resize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- // Determine what the size of the rendered square within the client should
- // be in pixels.
- var side = g_o3dWidth < g_o3dHeight ?
- g_o3dWidth : g_o3dHeight;
-
- // Convert to the region of world space that must be enclosed by the
- // orthographic projection.
- var worldSize = g_math.divVectorScalar([g_o3dWidth, g_o3dHeight], side);
-
- // Find a projection matrix to transform from world space to screen space.
- g_viewInfo.drawContext.projection = o3djs.math.matrix4.orthographic(
- -0.5 * worldSize[0], 0.5 * worldSize[0],
- -0.5 * worldSize[1], 0.5 * worldSize[1],
- 0.5, 1.5);
- }
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body style="width: 95%; height: 95%;">
-<table style="width: 100%; height: 100%;">
- <tr>
- <td>
- <h1>Juggler</h1>
- <p>
- This sample displays a juggling pattern computed entirely in a shader.
- <form name="the_form">
- <input type="radio" name="radio_group" value="3"
- onclick=updateNum()>3 Balls
- <input type="radio" name="radio_group" value="5"
- onclick=updateNum()>5 Balls
- <input type="radio" name="radio_group" value="7"
- onclick=updateNum()>7 Balls
- <input type="radio" name="radio_group" value="9"
- onclick=updateNum()>9 Balls
- <input type="radio" name="radio_group" value="11" checked
- onclick=updateNum()>11 Balls
- <input type="radio" name="radio_group" value="13"
- onclick=updateNum()>13 Balls
- <input type="radio" name="radio_group" value="15"
- onclick=updateNum()>15 Balls
- <input type="radio" name="radio_group" value="17"
- onclick=updateNum()>17 Balls
- <input type="checkbox" name="check_box" checked
- onclick=toggleRenderCallback()>Animate
- </form>
- </p>
- <table id="container" style="width: 100%; height: 80%;">
- <tr>
- <td height="100%">
- <!-- Start of g_o3d plugin -->
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- <!-- End of g_o3d plugin -->
- </td>
- </tr>
- </table>
- <!-- a simple way to get a multiline string -->
- <textarea id="shader" name="shader" cols="80" rows="20"
- style="display: none;">
-// The 4x4 world view projection matrix.
-uniform mat4 worldViewProjection;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec2 texCoord0;
-
-// input parameters for our pixel shader
-varying vec2 v_texCoord;
-
-/**
- * vertexShaderMain - our vertex shader for the juggling texture
- */
-void main() {
- gl_Position = worldViewProjection * position;
- v_texCoord = 4.0 * (texCoord0 - vec2(0.5, 0.5));
-}
-
-// #o3d SplitMarker
-
-varying vec2 v_texCoord;
-
-uniform float theta;
-uniform float num;
-
-float length_2(vec2 v) {
- return dot(v, v);
-}
-
-// Draw the balls in a single arc.
-// Returns 1 if the pixel is within a ball, 0 if it isn't, and a value in
-// between for pixels right on the edge, for antialiasing.
-float drawBallsInArc(float pi,
- vec4 offset,
- vec2 source_hand,
- vec2 dest_hand,
- float height_factor,
- float baseline,
- float ball_radius_2,
- float hand_throw_offset,
- vec2 Z,
- float threshold) {
- // Map theta from its current range of [0, 2 * num * pi) onto [0, (num - 1))
- // by scaling, adding offset, and modding, then map that to [0, 1) by scaling.
- // The first mapping tells us where in the repeating cycle we are, and the
- // second mapping simplifies the calculation of the parabola.
-
- // The vector offset is used to distinguish between balls in the same arc, but
- // out of phase. At the beginning of this function, all the operations are
- // vectorized to save instructions; we get to calculate 4 ball positions for
- // the price of 1.
-
- // The reason for the (num - 1) in the expression below is that with num
- // balls, each ball spends (num - 1) beats in the air, then one in the hand.
- // So (num - 1) is the length of time a parabola takes.
-
- vec4 time = mod(theta / pi + offset, (num - 1.0)) / (num - 1.0);
- float dx = dest_hand.x - source_hand.x;
- vec4 x = time * dx + source_hand.x - hand_throw_offset;
- vec4 y = time * (1.0 - time);
- y = y * height_factor + baseline;
- vec4 ZX = vec4(Z.x);
- vec4 ZY = vec4(Z.y);
- vec4 len_2 = (ZX - x) * (ZX - x) + (ZY - y) * (ZY - y);
-
- // This antialiasing fuzzes the balls just a bit larger than they would
- // otherwise be.
- vec4 temp = clamp((len_2 - ball_radius_2) / threshold, 0.0, 1.0);
-
- // One minus the product of all entries in temp.
- temp.xy = temp.xy * temp.zw;
- return 1.0 - temp.x * temp.y;
-}
-
-vec4 drawAirborneBalls(float pi,
- vec4 offset,
- vec2 right_hand,
- vec2 left_hand,
- float height_factor,
- float baseline,
- float ball_radius_2,
- float hand_swing_radius,
- vec2 Z,
- float threshold) {
- float value =
- // balls going right to left
- (drawBallsInArc(pi, offset, right_hand, left_hand, height_factor,
- baseline, ball_radius_2, hand_swing_radius, Z, threshold) +
- // balls going left to right
- drawBallsInArc(pi, offset + 1.0, left_hand, right_hand, height_factor,
- baseline, ball_radius_2, -hand_swing_radius, Z, threshold));
- return vec4(value, value, value, value);
-}
-
-
-/**
- * pixelShaderMain - pixel shader
- */
-
-void main() {
- float pi = 3.14159265;
- float baseline = -1.4;
- vec2 right_hand = vec2(0.8, baseline);
- vec2 left_hand = vec2(-0.8, baseline);
- float hand_swing_radius = 0.25;
- float hand_radius = 0.15;
- float hand_radius_2 = hand_radius * hand_radius;
- float ball_radius = 0.08;
- float ball_radius_2 = ball_radius * ball_radius;
-
- vec4 right_hand_color = vec4(1, 0, 0, 1);
- vec4 left_hand_color = vec4(0, 0, 1, 1);
- vec4 background_color = vec4(0, 0, 0, 0);
-
- float threshold = 0.002; // Used in clamp for antialiasing.
-
- float height_factor = num * 0.75;
-
- vec2 Z = v_texCoord;
-
- // Coerce to the range [0, 2 * Pi * num].
- vec2 r_h = hand_swing_radius * vec2(-cos(theta), sin(theta)) + right_hand;
- vec2 l_h = hand_swing_radius * vec2(-cos(theta), -sin(theta)) + left_hand;
-
- // Initialize color of pixel to background_color. Background color has an
- // alpha of 0. Color of objects each have alpha 1, so multiplying by
- // (1-alpha) before adding the color ensures that nothing gets overdrawn.
- // It's kind of like a rudimentary z-buffer.
- vec4 result = background_color;
-
- // Draw the hands. The antialiasing here fuzzes the hands just a little bit
- // smaller than they would otherwise be. That's the opposite of what we do
- // for the balls, just because it happens to be cheaper here to do smaller and
- // cheaper in drawBallsInArc to do larger.
- result +=
- clamp((hand_radius_2 - length_2(Z - r_h)) / threshold, 0.0, 1.0) *
- (Z.y < r_h.y ? 1.0 : 0.0) * right_hand_color +
- clamp((hand_radius_2 - length_2(Z - l_h)) / threshold, 0.0, 1.0) *
- (Z.y < l_h.y ? 1.0 : 0.0) * left_hand_color;
- // Draw the ball in the hand. There is always a ball in exactly one hand, and
- // which hand that is alternates.
- vec2 hand;
- if (mod(floor(theta / pi), 2.0) > 0.5) {
- hand = r_h;
- } else {
- hand = l_h;
- }
-
- // The antialiasing here fuzzes the balls just a bit bigger than they would
- // otherwise be. This is more work than making them smaller [the extra
- // subtraction in the "1 - clamp..." below], but inverting it in
- // drawBallsInArc would be more expensive, and they have to match so that the
- // balls are all the same size.
- result += (1.0 - result.a) *
- (1.0 - clamp((length_2(Z - hand) - ball_radius_2) / threshold, 0.0, 1.0));
-
- // Draw airborne balls.
- vec4 offset = vec4(0, 2, 4, 6);
- result += (1.0 - result.a) * drawAirborneBalls(pi,
- offset,
- right_hand,
- left_hand,
- height_factor,
- baseline,
- ball_radius_2,
- hand_swing_radius,
- Z,
- threshold);
-
- // For each up-to-4 pairs of balls you want to add, increment offset by
- // (8, 8, 8, 8) and call drawAirborneBalls again.
- offset += 8.0;
- result += (1.0 - result.a) * drawAirborneBalls(pi,
- offset,
- right_hand,
- left_hand,
- height_factor,
- baseline,
- ball_radius_2,
- hand_swing_radius,
- Z,
- threshold);
-
- gl_FragColor = result;
-}
-
-// #o3d MatrixLoadOrder RowMajor
- </textarea>
- </td>
- </tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/julia.html b/o3d/samples/o3d-webgl-samples/julia.html
deleted file mode 100644
index 30dbaf4..0000000
--- a/o3d/samples/o3d-webgl-samples/julia.html
+++ /dev/null
@@ -1,285 +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.
--->
-
-<!--
-O3D Julia Set
-
-This sample draws an animated julia set in real time using
-the pixel shader for the computation.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html style="width: 100%; height: 100%;">
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Julia Set Pixel Shader
-</title>
-
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-
-// Events
-// Run the init() function once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_o3dElement;
-var g_viewInfo;
-var g_pack;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-var g_clock = 0.0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-var g_seedParam;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes o3d, loads the effect, and creates the square.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Create a g_pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot,
- [0, 0, 0, 1]);
-
- // Load shader code from DOM and use it to build the effect.
- var effect = g_pack.createObject('Effect');
- effect.loadFromFXString(document.getElementById('shader').value);
-
- // Create a Material for the effect.
- var myMaterial = g_pack.createObject('Material');
-
- // Apply our effect to this material.
- myMaterial.effect = effect;
-
- // Set the material's drawList for opaque objects.
- myMaterial.drawList = g_viewInfo.performanceDrawList;
-
- // create the parameters the effect needs to the material.
- effect.createUniformParameters(myMaterial);
-
- // Create a square.
- var myShape = o3djs.primitives.createPlane(g_pack, myMaterial, 1, 1, 1, 1);
-
- // Initialize effect parameters to something reasonable
- g_seedParam = myMaterial.getParam('seed');
- g_seedParam.value = [0.2, 0.5];
-
- // Put the camera somewhere where it has a good view of that square.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 1, 0], //eye
- [0, 0, 0], //target
- [0, 0, -1]); //up
-
- // Generate the projection matrix based
- // on the g_o3d plugin size by calling resize().
- resize();
-
- // Now attach the square to the root of the transform graph.
- g_client.root.addShape(myShape);
-
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-
-/**
- * Render callback. Walks the seed of the Julia set through
- * a parametric path in the complex plane that stays
- * in the neighborhood of the Mandelbrot set.
- */
-function onrender(render_event) {
- g_clock += render_event.elapsedTime * g_timeMult;
-
- var t = 0.1 * g_clock;
- var x = 0.6 * Math.cos(3.0 * t) - 0.3;
- var y = (0.5 * x + 1.7)*(0.2 * Math.sin(7 * t));
-
- g_seedParam.value = [x, y];
-
- resize();
-}
-
-
-/**
- * Generates the projection matrix based on the size of the o3d plugin and
- * calculates the view-projection matrix.
- */
-function resize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- // Determine what the size of the rendered square within the client should
- // be in pixels.
- var side = g_o3dWidth < g_o3dHeight ?
- g_o3dWidth : g_o3dHeight;
-
- // Convert to the region of world space that must be enclosed by the
- // orthographic projection.
- var worldSize = g_math.divVectorScalar([g_o3dWidth, g_o3dHeight], side);
-
- // Find a projection matrix to transform from world space to screen space.
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -0.5 * worldSize[0], 0.5 * worldSize[0],
- -0.5 * worldSize[1], 0.5 * worldSize[1],
- 0.5, 1.5);
- }
-}
-
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-
-</script>
-</head>
-<body style="width: 100%; height: 100%;">
-<table style="width: 100%; height: 100%;">
- <tr>
- <td>
- <h1>Julia Set</h1>
- <p>
- This sample draws an animated julia set in real time using
- the pixel shader for the computation.
- </p>
- <table id="container" style="width: 100%; height: 80%;">
- <tr>
- <td height="100%">
- <!-- Start of g_o3d plugin -->
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- <!-- End of g_o3d plugin -->
- </td>
- </tr>
- </table>
- <!-- a simple way to get a multiline string -->
- <textarea id="shader" name="shader" cols="80" rows="20"
- style="display: none;">
-// The 4x4 world view projection matrix.
-uniform mat4 worldViewProjection;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec2 texCoord0;
-
-// input parameters for our pixel shader
-varying vec2 texCoord;
-
-/**
- * vertexShaderMain - Multiplies position by world-view-projection matrix, and
- * passes on texture coordinates scaled to put the origin in the center of the
- * quad and reveal a nicely sized portion of the plane to show the julia set.
- */
-void main() {
- gl_Position = worldViewProjection * position;
- texCoord = 4.0 * (texCoord0 - vec2(0.5, 0.5));
-}
-
-
-// #o3d SplitMarker
-
-varying vec2 texCoord;
-
-// The seed for the julia set (c in the expression z(n+1) = z(n)^2+c).
-uniform vec2 seed;
-
-/**
- * pixelShaderMain - Calculates the color of the pixel by iterating on the
- * formula z = z*z + seed. After some number of iterations, the magnitude of z
- * determines the color.
- */
-void main() {
- vec2 Z = texCoord;
-
- // Number of iterations hardcoded here. The more iterations, the crisper the
- // image.
- for(int i = 0; i < 10; ++i) {
- Z = vec2(Z.x * Z.x - Z.y * Z.y, 2.0 * Z.x * Z.y) + seed;
-
- // Some graphics cards and some software renderers don't appreciate large
- // floating point values, so we clamp to prevent Z from getting that big.
- if (i > 7) {
- Z = clamp(Z, -25.0, 25.0);
- }
- }
-
- gl_FragColor = (1.0 - length(Z)) * vec4(0.5, 1, 2, 1);
-}
-// #o3d MatrixLoadOrder RowMajor
- </textarea>
- </td>
- </tr>
-</table>
-</body>
-</html>
-
-
diff --git a/o3d/samples/o3d-webgl-samples/multiple-clients.html b/o3d/samples/o3d-webgl-samples/multiple-clients.html
deleted file mode 100644
index ec6d5c8..0000000
--- a/o3d/samples/o3d-webgl-samples/multiple-clients.html
+++ /dev/null
@@ -1,229 +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 sample demonstrates running more than 1 instance of the plugin at
-the same time.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Multiple Clients
-</title>
-<!-- Our javascript code -->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.io');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-
-// Events
-// Run the init() function once the page has finished loading.
-// uninit() when the page is unloaded.
-window.onload = init;
-window.onunload = uninit;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_clients = [];
-var g_packs = [];
-var g_viewInfos = [];
-var g_num_clients;
-var g_setupDone = false;
-
-var g_animate_angle = [];
-var g_eye;
-
-var NUM_ACROSS = 10;
-var NUM_DOWN = 5;
-
-/**
- * Initializes O3D, loads the effect, and draws the cube.
- */
-function init() {
- // Create a bunch of clients.
- var ii = 0;
- var tbodyElem = document.getElementById('clients');
- for (var row = 0; row < NUM_DOWN; row++) {
- var trElem = document.createElement('tr');
- for (var column = 0; column < NUM_ACROSS; column++) {
- var tdElem = document.createElement('td');
- var objElem = o3djs.webgl.createClient(tdElem);
- objElem.style.width = '60px';
- objElem.style.height = '60px';
- objElem.id = 'o3d' + ii;
- objElem.name = 'o3d' + ii;
- trElem.appendChild(tdElem);
- ii++;
- }
- tbodyElem.appendChild(trElem);
- }
- g_num_clients = ii;
-
- // wait for the browser to settle down.
- var clearId = window.setInterval(function() {
- var lastClient = NUM_ACROSS * NUM_DOWN - 1;
- var element = document.getElementById('o3d' + lastClient);
- if (!element || element && !element.o3d) {
- return;
- }
- window.clearInterval(clearId);
- setup();
- }, 10);
-}
-
-function setup() {
- // Lookup all the clients.
- for (var ii = 0; ii < g_num_clients; ++ii) {
- g_clients[ii] = document.getElementById('o3d' + ii).client;
- }
-
- // Get constants and math functions.
- g_o3d = document.getElementById('o3d0').o3d;
- g_math = o3djs.math;
-
- var effectSource =
- o3djs.io.loadTextFileSynchronous('../shaders/vertex-color-glsl.shader');
-
- // For each client make a cube, context, effect,...
- for (ii = 0; ii < g_num_clients; ii++) {
- // Create a pack to manage our resources/assets
- g_packs[ii] = g_clients[ii].createPack();
-
- // Create the render graph for a view.
- g_viewInfos[ii] = o3djs.rendergraph.createBasicView(
- g_packs[ii],
- g_clients[ii].root,
- g_clients[ii].renderGraphRoot);
-
- g_animate_angle[ii] = 0;
-
- // Create our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 100.
- g_viewInfos[ii].drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- 128 / 128,
- 0.1,
- 100);
-
- // Create and load the effect.
- var effect = g_packs[ii].createObject('Effect');
- effect.loadFromFXString(effectSource);
-
- // Create a material for it.
- var material = g_packs[ii].createObject('Material');
-
- // Set the material's drawList
- material.drawList = g_viewInfos[ii].performanceDrawList;
-
- // Apply our effect to this material.
- material.effect = effect;
- effect.createUniformParameters(material);
-
- // Create a cube using the effect we have loaded.
- createCube(g_clients[ii].root, g_packs[ii], material);
- }
-
- // Set our render callback for animation.
- // This sets a function to be executed every time a frame is rendered.
- g_clients[0].setRenderCallback(onrender);
- g_setupDone = true;
-}
-
-/**
- * Creates a cube with the given effect.
- *
- * @param {!o3d.Transform} parent Transform to parent shape to.
- * @param {!o3d.Pack} pack Pack to use.
- * @param {!o3d.Material} material Material to use.
- */
-function createCube(parent, pack, material) {
- // First, create a 'shape' node to store our sphere.
- var myShape = o3djs.primitives.createRainbowCube(pack, material, 0.5);
-
- // Attach the cube to the root of the transform graph.
- parent.addShape(myShape);
-}
-
-// Animates the cubes.
-// This function executes on each frame.
-// It was set using document.o3d.setEventCallback(..) in setup().
-function onrender(render_event) {
- var elapsedTime = render_event.elapsedTime;
- for (var ii = 0; ii < g_num_clients; ii++) {
- // Rotate frame rate independently.
- g_animate_angle[ii] += (0.1 + 0.1 * ii) * elapsedTime;
-
- // Eye-position, this is where our camera is at.
- var eye = [
- 0.0 + Math.sin(g_animate_angle[ii]) * 1.0,
- 1.0,
- 0.0 + Math.cos(g_animate_angle[ii]) * 1.0
- ];
-
- // Target, this is where our camera is pointed at.
- var target = [0, 0, 0];
-
- // Up-vector, this tells the camera which direction is 'up'.
- // We define the positive y-direction to be up in this example.
- var up = [0, 1, 0];
-
- g_viewInfos[ii].drawContext.view = g_math.matrix4.lookAt(eye, target, up);
- }
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_clients[0]) {
- g_clients[0].cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Multiple Clients</h1>
-<table>
- <tbody id="clients">
- </tbody>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/multiple-lights.html b/o3d/samples/o3d-webgl-samples/multiple-lights.html
deleted file mode 100644
index e0f4ef5..0000000
--- a/o3d/samples/o3d-webgl-samples/multiple-lights.html
+++ /dev/null
@@ -1,209 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<!--
-O3D Multiple Lights example.
-
-Shows a simple cube with one light on each corner.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Multiple Lights
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-
-o3djs.base.o3d = o3d;
-
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.primitives');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_transform = null;
-var g_finished = false; // for selenium testing.
-var g_clock = 0;
-var g_timeMult = 1;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 10000);
-
- // Create a material.
- var material = g_pack.createObject('Material');
- material.drawList = g_viewInfo.performanceDrawList;
-
- material.createParam('diffuse', 'ParamFloat4').value = [.5, .5, .5, 1];
-
- // Create some suitable defaults for the material to save the user having
- // to know all this stuff right off the bat.
- material.createParam('emissive', 'ParamFloat4').value = [0, 0, 0, 1];
- material.createParam('ambient', 'ParamFloat4').value = [0, 0, 0, 0];
- material.createParam('specular', 'ParamFloat4').value = [1, 1, 1, 1];
- material.createParam('shininess', 'ParamFloat').value = 10;
- material.createParam('specularFactor', 'ParamFloat').value = 1;
- o3djs.material.attachStandardEffect(
- g_pack,
- material,
- g_viewInfo,
- 'blinn',
- {lights: 8});
- var materialColorParamList = material.getParam('lightColorList');
- var colorParamList = g_pack.createObject('ParamArray');
- var materialLightPositionList = material.getParam('lightWorldPosList');
- var lightPositionParamList = g_pack.createObject('ParamArray');
- // Create a cylinder.
- var shape = o3djs.primitives.createCube(
- g_pack,
- material,
- 150);
-
- g_transform = g_pack.createObject('Transform');
- // Add the cylinder to the root transform.
- g_transform.addShape(shape);
- g_transform.parent = g_client.root;
-
- var colors = [
- [0, 0, 0, 1], // null light
- [1, 0, 0, 1],
- [0, 0, 1, 1],
- [0, 1, 0, 1],
- [1, 1, 1, 1],
- [0, 1, 1, 1],
- [1, 1, 0, 1],
- [1, 0, 1, 1]];
- var lightDist = 150;
- for (var i = 0; i < 8; i++) {
- colorParamList.createParam(i,'ParamFloat4').value = colors[i];
- var position = [
- (i&1)?lightDist:-lightDist,
- (i&2)?lightDist:-lightDist,
- (i&4)?lightDist:-lightDist
- ];
- lightPositionParamList.createParam(i,'ParamFloat3').value = position;
- }
- materialLightPositionList.value = lightPositionParamList;
- materialColorParamList.value = colorParamList;
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Info for rendering.
- */
-function onrender(renderEvent) {
- // Get the number of seconds since the last render.
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- var x = Math.sin(g_clock * 0.3) * 400;
- var z = Math.cos(g_clock * 0.3) * 400;
- var y = Math.sin(g_clock * 0.7) * 200 + 100;
-
- // spin the camera.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [x, y, z], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Multiple Lights</h1>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 400px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/multiple-views.html b/o3d/samples/o3d-webgl-samples/multiple-views.html
deleted file mode 100644
index bd1f222..0000000
--- a/o3d/samples/o3d-webgl-samples/multiple-views.html
+++ /dev/null
@@ -1,222 +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.
--->
-
-<!--
-Example of multiple views into the same scene.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Multiple Views
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfos = [];
-var g_pack;
-var g_finished = false; // for selenium testing
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- */
-function loadScene(pack, fileName, parent) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a cameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- g_client.width / 2, // because this context is only used 1/2 the area
- g_client.height);
-
- // Copy the view and projection to the draw context.
- g_viewInfos[0].drawContext.view = cameraInfo.view;
- g_viewInfos[0].drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfos[0]);
-
- g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view for the left half of screen.
- g_viewInfos[0] = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot,
- [0.7, 0.2, 0.2, 1],
- 0,
- [0, 0, 0.5, 1]); // left half of screen.
-
- // Setup 3 areas. Each area needs a viewport, a tree traveral, 2 drawpasses
- // and although we could clear the screen once let's do it per viewport just
- // as an example. The original area is already setup except it needs a
- // viewport setting.
-
- // make the 2 right viewports
- for (var yy = 0; yy < 2; yy++) {
- // Set the view extents to the right half, top or bottom.
- var viewExtents = [0.5, yy * 0.5, 0.5, 0.5];
-
- // Give each view a different background color.
- var viewBackgroundColor = [0.5, 0.2 + 0.5 * yy, 0.7 - 0.5 * yy, 1.0];
-
- // Make this view get processes after the first view.
- var viewPriority = yy + 1;
-
- // Create an extra view. We call createExtraView because we want to
- // share DrawLists with the first view so that all 3 views draw the same
- // things.
- var viewInfo = o3djs.rendergraph.createExtraView(
- g_viewInfos[0],
- viewExtents,
- viewBackgroundColor,
- viewPriority);
-
- // Save it off for later.
- g_viewInfos[g_viewInfos.length] = viewInfo;
-
- // Get the DrawContext for this area and set the view and
- // projection matrices.
- var drawContext = viewInfo.drawContext;
-
- if (yy == 0) {
- drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- (g_client.width * 0.5) / (g_client.height * 0.5),
- 0.1,
- 100);
- drawContext.view = g_math.matrix4.lookAt(
- [-10, 3, -15], // eye
- [0, 2, 0], // target
- [0, 1, 0]); // up
- } else {
- // lets make this one orthographic
- var aspect = g_client.width / g_client.height;
- drawContext.projection = g_math.matrix4.orthographic(
- -10,
- 10,
- -10 / aspect,
- 10 / aspect,
- 0,
- 100);
- // look directly from the front
- drawContext.view = g_math.matrix4.lookAt(
- [0, 5, 30], // eye
- [0, 5, 0], // target
- [0, 1, 0]); // up
- }
- }
-
- // Creates a transform to put our data on.
- var my_data_root = g_pack.createObject('Transform');
-
- // Connects our root to the client's root.
- my_data_root.parent = g_client.root;
-
- // Load the scene into the transform graph as a child my_data_root
- loadScene(g_pack, '../assets/yard/scene.json', my_data_root);
-}
-</script>
-</head>
-<body>
-<h1>Multiple Views</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/old-school-shadows.html b/o3d/samples/o3d-webgl-samples/old-school-shadows.html
deleted file mode 100644
index 18a85af..0000000
--- a/o3d/samples/o3d-webgl-samples/old-school-shadows.html
+++ /dev/null
@@ -1,277 +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 sample shows how to use simple circle texture for shadows.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Old School Shadows.
-</title>
-<link rel="stylesheet" type="text/css" href="../assets/style.css" />
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Constants
-var SHADOW_SIZE = 5;
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_globalParams;
-var g_shadowDrawPassInfo;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_transforms = [];
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- // Make another draw pass just for the shadows so they get
- // drawn last. We don't need to pass any extra info to createDrawPass
- // because we are using the same drawContext and because we want it to
- // happen last, both of which are the default.
- g_shadowDrawPassInfo = g_viewInfo.createDrawPass(
- g_o3d.DrawList.BY_PERFORMANCE);
-
- // Get the state object the shadow draw pass and set states for the shadows.
- var state = g_shadowDrawPassInfo.state;
-
- // The following settings turn on blending for all objects using the
- // shadow DrawList
- state.getStateParam('AlphaBlendEnable').value = true;
- state.getStateParam('SourceBlendFunction').value =
- o3djs.base.o3d.State.BLENDFUNC_SOURCE_ALPHA;
- state.getStateParam('DestinationBlendFunction').value =
- o3djs.base.o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA;
- state.getStateParam('AlphaTestEnable').value = true;
- state.getStateParam('AlphaComparisonFunction').value =
- o3djs.base.o3d.State.CMP_GREATER;
-
- // Make the shadow not write to the ZBuffer, otherwise they will interfere
- // with each other. Try commenting this line out to see what happens. Look
- // closely when 2 shadows overlap. It's easier to see the problem
- // if you make the shadows larger. Set the shadow size to 15
- state.getStateParam('ZWriteEnable').value = false;
-
- // This setting pulls the shadow in front of the ground plane even though
- // they are at the same position in space. Comment this 2 lines out
- // to see what happens if you don't use this setting.
- state.getStateParam('PolygonOffset1').value = -1;
- state.getStateParam('PolygonOffset2').value = -1;
-
- // Setup the view and projection matrices.
- var eye = [15, 25, 50];
- var target = [0, 10, 0];
- var up = [0, 1, 0];
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(eye, target, up);
-
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_client.width / g_client.height, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-
- // Load a small circle texture.
- o3djs.io.loadTexture(
- g_pack,
- o3djs.util.getAbsoluteURI('../assets/old-school-shadow.png'),
- initStep3);
-}
-
-function initStep3(texture, exception) {
- if (exception) {
- alert(exception);
- return;
- }
-
- // This material is used for the spheres.
- var sphereMaterial = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [1, 1, 1, 1]);
- sphereMaterial.getParam('specularFactor').value = 0.4;
-
- // The material for the ground.
- var checkerMaterial = o3djs.material.createCheckerMaterial(
- g_pack,
- g_viewInfo);
-
- // Make a material to use for the shadow. A standard constant shader will
- // be fine.
- var shadowMaterial = o3djs.material.createConstantMaterial(
- g_pack,
- g_viewInfo,
- texture,
- true);
- shadowMaterial.drawList = g_shadowDrawPassInfo.drawList;
-
- // Setup the lighting for the ground and spheres.
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Create a sphere.
- var sphere = o3djs.primitives.createSphere(
- g_pack, sphereMaterial, 2.5, 24, 48,
- g_math.matrix4.translation([0, 2.5, 0]));
-
- // Create a plane for the shadow.
- var shadow = o3djs.primitives.createPlane(g_pack, shadowMaterial,
- SHADOW_SIZE, SHADOW_SIZE, 1, 1);
-
- // Instance 100 spheres with shadows.
- for (var ii = 0; ii < 100; ++ii) {
- var transform = g_pack.createObject('Transform');
- g_transforms.push(transform);
- transform.parent = g_root;
- transform.addShape(sphere);
- // Give each sphere a pseudo random color.
- transform.createParam('diffuse', 'ParamFloat4').value = [
- (ii * 1.71) % 1,
- (ii * 2.09) % 1,
- (ii * 6.31) % 1,
- 1];
- var shadowTransform = g_pack.createObject('Transform');
- shadowTransform.parent = transform;
- shadowTransform.addShape(shadow);
- }
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- moveThings();
-};
-
-/**
- * Moves all the sphere transforms in some pattern that is a function of
- * g_clock so we can force it to a predictable state for testing.
- */
-function moveThings() {
- for (var ii = 0; ii < g_transforms.length; ++ii) {
- var transform = g_transforms[ii];
- var xSpeed = g_clock * 0.25 + ii * 1.1;
- var ySpeed = g_clock * 0.27 + ii * 0.5;
- transform.identity();
- transform.translate(40 * Math.sin(xSpeed),
- 0,
- 40 * Math.cos(ySpeed));
- var scale = (Math.sin(g_clock * 0.29 + ii * 20.7) + 1) * 0.5 + 0.3;
- transform.scale(scale, scale, scale);
- }
-}
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Old School Shadows</h1>
-<div id="o3d" style="width: 800px; height: 600px"></div>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/particles.html b/o3d/samples/o3d-webgl-samples/particles.html
deleted file mode 100644
index 71938c3..0000000
--- a/o3d/samples/o3d-webgl-samples/particles.html
+++ /dev/null
@@ -1,591 +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.
--->
-
-<!--
-Particles.
-
-This example shows using the javascript particle library.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Particles.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.particles');
-o3djs.require('o3djs.loader');
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_particleSystem;
-var g_clockParam;
-var g_textures = [];
-var g_emitters = []; // so we can find in the debugger to edit in real time.
-var g_poofs = [];
-var g_keyDown = [];
-var g_poofIndex = 0;
-var g_trail;
-var g_trailParameters;
-
-var MAX_POOFS = 3;
-
-/**
- * Loads a texture.
- * @param {!o3djs.loader.Loader} loader Loader to use to load texture.
- * @param {string} url relativel url of texture.
- * @param {number} index Index at which to record texture.
- */
-function loadTexture(loader, url, index) {
- loader.loadTexture(
- g_pack,
- o3djs.util.getAbsoluteURI(url),
- function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- g_textures[index] = texture;
- }
- });
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- // These are here so they are shared by both V8 and the browser.
- window.g_finished = false; // for selenium
- window.g_timeMult = 1;
- window.g_clock = 0;
-
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- window.g_client = g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree fov.
- g_client.width / g_client.height,
- 0.1, // Near plane.
- 5000); // Far plane.
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [500, 1000, 1000], // eye
- [0, 200, 0], // target
- [0, 1, 0]); // up
-
- // Load textures. This happens asynchronously.
- var loader = o3djs.loader.createLoader(initStep3);
- loadTexture(loader, '../assets/particle-anim.png', 0);
- loadTexture(loader, '../assets/ripple.png', 1);
- loader.finish();
-}
-
-function initStep3() {
- // Normally we wouldn't pass in a clock and the particle system would handle
- // this for me but for selenium testing we need to be able to control the
- // clock so we're passing in our own clock param.
- var paramObject = g_pack.createObject('ParamObject');
- g_clockParam = paramObject.createParam('clock', 'ParamFloat');
-
- // Normally we wouldn't pass in a random function but for selenium we need
- // the particle system to produce the exact same results each time so
- // we're passing in a predictable random function.
- g_particleSystem = o3djs.particles.createParticleSystem(
- g_pack,
- g_viewInfo,
- g_clockParam,
- g_math.pseudoRandom);
- setupFlame();
- setupNaturalGasFlame();
- setupSmoke();
- setupWhiteEnergy();
- setupGoogle();
- setupRain();
- setupRipples();
- setupAnim();
- setupBall();
- setupCube();
- setupPoof();
- setupTrail();
-
- window.document.onkeypress = onKeyPress;
- window.document.onkeydown = onKeyDown;
- window.document.onkeyup = onKeyUp;
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- window.g_finished = true; // for selenium testing.
-}
-
-function onKeyPress(event) {
- event = event || window.event;
-
- var keyChar = String.fromCharCode(o3djs.event.getEventKeyChar(event));
- // Just in case they have capslock on.
- keyChar = keyChar.toLowerCase();
-
- switch (keyChar) {
- case 'p':
- triggerPoof();
- break;
- }
-}
-
-function onKeyDown(event) {
- event = event || window.event;
- g_keyDown[o3djs.event.getEventKeyChar(event)] = true;
-}
-
-function onKeyUp(event) {
- event = event || window.event;
- g_keyDown[o3djs.event.getEventKeyChar(event)] = false;
-}
-
-function setupFlame() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(-300, 0, 0);
-
- var emitter = g_particleSystem.createParticleEmitter();
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.ADD);
- emitter.setColorRamp(
- [1, 1, 0, 1,
- 1, 0, 0, 1,
- 0, 0, 0, 1,
- 0, 0, 0, 0.5,
- 0, 0, 0, 0]);
- emitter.setParameters({
- numParticles: 20,
- lifeTime: 2,
- timeRange: 2,
- startSize: 50,
- endSize: 90,
- velocity:[0, 60, 0], velocityRange: [15, 15, 15],
- worldAcceleration: [0, -20, 0],
- spinSpeedRange: 4});
- transform.addShape(emitter.shape);
-}
-
-function setupNaturalGasFlame() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(-200, 0, 0);
-
- var emitter = g_particleSystem.createParticleEmitter();
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.ADD);
- emitter.setColorRamp(
- [0.2, 0.2, 1, 1,
- 0, 0, 1, 1,
- 0, 0, 1, 0.5,
- 0, 0, 1, 0]);
- emitter.setParameters({
- numParticles: 20,
- lifeTime: 2,
- timeRange: 2,
- startSize: 50,
- endSize: 20,
- velocity:[0, 60, 0],
- worldAcceleration: [0, -20, 0],
- spinSpeedRange: 4});
- transform.addShape(emitter.shape);
-}
-
-function setupSmoke() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(-100, 0, 0);
-
- var emitter = g_particleSystem.createParticleEmitter();
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.BLEND);
- emitter.setColorRamp(
- [0, 0, 0, 1,
- 0, 0, 0, 0]);
- emitter.setParameters({
- numParticles: 20,
- lifeTime: 2,
- timeRange: 2,
- startSize: 100,
- endSize: 150,
- velocity: [0, 200, 0], velocityRange: [20, 0, 20],
- worldAcceleration: [0, -25, 0],
- spinSpeedRange: 4});
- transform.addShape(emitter.shape);
-}
-
-function setupWhiteEnergy() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(0, 0, 0);
-
- var emitter = g_particleSystem.createParticleEmitter();
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.ADD);
- emitter.setColorRamp(
- [1, 1, 1, 1,
- 1, 1, 1, 0]);
- emitter.setParameters({
- numParticles: 80,
- lifeTime: 2,
- timeRange: 2,
- startSize: 100,
- endSize: 100,
- positionRange: [100, 0, 100],
- velocityRange: [20, 0, 20]});
- transform.addShape(emitter.shape);
-}
-
-function setupRipples() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(-200, 0, 300);
-
- var emitter = g_particleSystem.createParticleEmitter(g_textures[1]);
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.BLEND);
- emitter.setColorRamp(
- [0.7, 0.8, 1, 1,
- 1, 1, 1, 0]);
- emitter.setParameters({
- numParticles: 20,
- lifeTime: 2,
- timeRange: 2,
- startSize: 50,
- endSize: 200,
- positionRange: [100, 0, 100],
- billboard: false});
- transform.addShape(emitter.shape);
-}
-
-function setupGoogle() {
- var image = [
- '.XXXX...XXXXX...XXXXX.',
- 'X....X.......X..X....X',
- 'X....X...XXXXX..X....X',
- 'X....X.......X..X....X',
- '.XXXX...XXXXX...XXXXX.'];
- var height = image.length;
- var width = image[0].length;
-
- // Make an array of positions based on the text image.
- var positions = [];
- for (var yy = 0; yy < height; ++yy) {
- for (var xx = 0; xx < width; ++xx) {
- if (image[yy].substring(xx, xx + 1) == 'X') {
- positions.push([(xx - width * 0.5) * 10,
- -(yy - height * 0.5) * 10]);
- }
- }
- }
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(100, 200, 0);
-
- var emitter = g_particleSystem.createParticleEmitter();
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.ADD);
- emitter.setColorRamp(
- [1, 0, 0, 1,
- 0, 1, 0, 1,
- 0, 0, 1, 1,
- 1, 1, 0, 0]);
- emitter.setParameters({
- numParticles: positions.length * 4,
- lifeTime: 2,
- timeRange: 2,
- startSize: 25,
- endSize: 50,
- positionRange: [2, 0, 2],
- velocity: [1, 0, 1]},
- function(particleIndex, parameters) {
- //var index = particleIndex;
- var index = Math.floor(g_math.pseudoRandom() * positions.length);
- index = Math.min(index, positions.length - 1);
- parameters.position[0] = positions[index][0];
- parameters.position[1] = positions[index][1];
- });
- transform.addShape(emitter.shape);
-}
-
-function setupRain() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(200, 200, 0);
-
- var emitter = g_particleSystem.createParticleEmitter();
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.BLEND);
- emitter.setColorRamp(
- [0.2, 0.2, 1, 1]);
- emitter.setParameters({
- numParticles: 80,
- lifeTime: 2,
- timeRange: 2,
- startSize: 5,
- endSize: 5,
- positionRange: [100, 0, 100],
- velocity: [0,-150,0]});
- transform.addShape(emitter.shape);
-}
-
-function setupAnim(texture) {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(300, 0, 0);
-
- var emitter = g_particleSystem.createParticleEmitter(g_textures[0]);
- g_emitters.push(emitter);
- emitter.setColorRamp(
- [1, 1, 1, 1,
- 1, 1, 1, 1,
- 1, 1, 1, 0]);
- emitter.setParameters({
- numParticles: 20,
- numFrames: 8,
- frameDuration: 0.25,
- frameStartRange: 8,
- lifeTime: 2,
- timeRange: 2,
- startSize: 50,
- endSize: 90,
- positionRange: [10, 10, 10],
- velocity:[0, 200, 0], velocityRange: [75, 15, 75],
- acceleration: [0, -150, 0],
- spinSpeedRange: 1});
- transform.addShape(emitter.shape);
-}
-
-function setupBall() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(-400, 0, -200);
-
- var emitter = g_particleSystem.createParticleEmitter(g_textures[1]);
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.BLEND);
- emitter.setColorRamp(
- [1, 1, 1, 1,
- 1, 1, 1, 0]);
- emitter.setParameters({
- numParticles: 300,
- lifeTime: 2,
- timeRange: 2,
- startSize: 10,
- endSize: 50,
- colorMult: [1, 1, 0.5, 1], colorMultRange: [0, 0, 0.5, 0],
- billboard: false},
- function(particleIndex, parameters) {
- var matrix = g_math.matrix4.rotationY(
- g_math.pseudoRandom() * Math.PI * 2);
- g_math.matrix4.rotateX(matrix, g_math.pseudoRandom() * Math.PI);
- var position = g_math.matrix4.transformDirection(matrix, [0, 100, 0]);
- parameters.position = position;
- parameters.orientation = o3djs.quaternions.rotationToQuaternion(matrix);
- });
- transform.addShape(emitter.shape);
-}
-
-function setupCube() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(200, 0, -300);
-
- var emitter = g_particleSystem.createParticleEmitter(g_textures[1]);
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.ADD);
- emitter.setColorRamp(
- [1, 1, 1, 1,
- 0, 0, 1, 1,
- 1, 1, 1, 0]);
- emitter.setParameters({
- numParticles: 300,
- lifeTime: 2,
- timeRange: 2,
- startSize: 10,
- endSize: 50,
- colorMult: [0.8, 0.9, 1, 1],
- billboard: false},
- function(particleIndex, parameters) {
- var matrix = g_math.matrix4.rotationY(
- Math.floor(g_math.pseudoRandom() * 4) * Math.PI * 0.5);
- g_math.matrix4.rotateX(
- matrix,
- Math.floor(g_math.pseudoRandom() * 3) * Math.PI * 0.5);
- parameters.orientation = o3djs.quaternions.rotationToQuaternion(matrix);
- var position = g_math.matrix4.transformDirection(
- matrix,
- [g_math.pseudoRandom() * 200 - 100,
- 100,
- g_math.pseudoRandom() * 200 - 100]);
- parameters.position = position;
- });
- transform.addShape(emitter.shape);
-}
-
-function setupPoof() {
- var emitter = g_particleSystem.createParticleEmitter();
- emitter.setState(o3djs.particles.ParticleStateIds.ADD);
- emitter.setColorRamp(
- [1, 1, 1, 0.3,
- 1, 1, 1, 0]);
- emitter.setParameters({
- numParticles: 30,
- lifeTime: 1.5,
- startTime: 0,
- startSize: 50,
- endSize: 200,
- spinSpeedRange: 10},
- function(index, parameters) {
- var angle = Math.random() * 2 * Math.PI;
- parameters.velocity = g_math.matrix4.transformPoint(
- g_math.matrix4.rotationY(angle), [300, 0, 0]);
- parameters.acceleration = g_math.mulVectorVector(
- parameters.velocity, [-0.3, 0, -0.3]);
- });
- // make 3 poofs one shots
- for (var ii = 0; ii < MAX_POOFS; ++ii) {
- g_poofs[ii] = emitter.createOneShot(g_client.root);
- }
-}
-
-function triggerPoof() {
- // We have multiple poofs because if you only have one and it is still going
- // when you trigger it a second time it will immediately start over.
- g_poofs[g_poofIndex].trigger([100 + 100 * g_poofIndex, 0, 300]);
- g_poofIndex++;
- if (g_poofIndex == MAX_POOFS) {
- g_poofIndex = 0;
- }
-}
-
-function setupTrail() {
- g_trailParameters = {
- numParticles: 2,
- lifeTime: 2,
- startSize: 10,
- endSize: 90,
- velocityRange: [20, 20, 20],
- spinSpeedRange: 4};
- g_trail = g_particleSystem.createTrail(
- g_client.root,
- 1000,
- g_trailParameters);
- g_trail.setState(o3djs.particles.ParticleStateIds.ADD);
- g_trail.setColorRamp(
- [1, 0, 0, 1,
- 1, 1, 0, 1,
- 1, 1, 1, 0]);
-}
-
-function leaveTrail() {
- var trailClock = window.g_clock * -0.8;
- g_trail.birthParticles(
- [Math.sin(trailClock) * 400, 200, Math.cos(trailClock) * 400]);
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onrender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- window.g_clock += elapsedTime * window.g_timeMult;
-
- if (g_keyDown[84]) { // 'T' key.
- leaveTrail();
- }
-
- var cameraClock = window.g_clock * 0.3;
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [Math.sin(cameraClock) * 1500, 500, Math.cos(cameraClock) * 1500], // eye
- [0, 100, 0], // target
- [0, 1, 0]); // up
-
- g_clockParam.value = window.g_clock;
-}
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body onload="init();" onunload="unload();">
-<h1>Particles</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-Press 'P' to make a poof.<br/>
-Hold 'T' to make a trail.
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/phongshading.html b/o3d/samples/o3d-webgl-samples/phongshading.html
deleted file mode 100644
index dffe27f..0000000
--- a/o3d/samples/o3d-webgl-samples/phongshading.html
+++ /dev/null
@@ -1,345 +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.
--->
-
-<!--
-O3D Tutorial B5
-
-In this tutorial, we generate a simple spherical mesh using Javascript and
-shade it using Phong illumination.
-
-We calculate the various lighting components (ambient,diffuse,specular)
-and combine them in our vertex/pixel shaders to draw the correct color for each
-pixel in the scene.
-
-The scene is illuminated by a single red light and the sphere is white.
-(ie ambient, diffuse, and specular reflection constants of the material = 1)
-
-In this sample, we generate the projection matrix dynamically from the size
-of the o3d plugin.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Tutorial B5: Phong Shading
-</title>
-<!-- Our javascript code -->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-
-// Events
-// Run the init() function once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_o3dElement;
-var g_viewInfo;
-var g_pack;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-
-// Our view and projection matrices
-// The view matrix transforms objects from world space to view space.
-var g_view_matrix;
-// The projection matrix projects objects from view space to the screen.
-var g_proj_matrix;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and draws the sphere.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Create a g_pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- /* Load the effect for our sphere from our file.
- Effects, stored in a hidden textarea for simplicity, contain the
- functions that define the vertex and pixel shaders used by our shape.
-
- Here, we calculate phong illumination in our vertex shader and pass the
- resultant color to our pixel shader, which does nothing except output its
- given (input) color.
- */
- var effect = g_pack.createObject('Effect');
- effect.loadVertexShaderFromString(document.getElementById('vshader').value);
- effect.loadPixelShaderFromString(document.getElementById('pshader').value);
-
- // Create a Material for the effect.
- var myMaterial = g_pack.createObject('Material');
-
- // Apply our effect to this material.
- myMaterial.effect = effect;
-
- // Set the material's drawList
- myMaterial.drawList = g_viewInfo.performanceDrawList;
-
- // Create the params the effect needs on the material.
- effect.createUniformParameters(myMaterial);
-
- // Create a sphere at the origin with radius 1.
- var myShape = o3djs.primitives.createSphere(g_pack,
- myMaterial,
- 1,
- 70,
- 70);
-
- // Set up the individual parameters in our effect file.
-
- // Light position
- var light_pos_param = myMaterial.getParam('light_pos');
- light_pos_param.value = [10, 10, 20];
-
- // Phong components of the light source
- var light_ambient_param = myMaterial.getParam('light_ambient');
- var light_diffuse_param = myMaterial.getParam('light_diffuse');
- var light_specular_param = myMaterial.getParam('light_specular');
-
- // White ambient light
- light_ambient_param.value = [0.04, 0.04, 0.04, 1];
- // Reddish diffuse light
- light_diffuse_param.value = [0.8, 0, 0, 1];
- // White specular light
- light_specular_param.value = [0.5, 0.5, 0.5, 1];
-
- // Shininess of the material (for specular lighting)
- var shininess_param = myMaterial.getParam('shininess');
- shininess_param.value = 30.0;
-
- // Position of the camera.
- // (should be the same as the 'eye' position given below)
- var camera_pos_param = myMaterial.getParam('camera_pos');
- // Camera is at (0, 0, 3).
- camera_pos_param.value = [0, 0, 3];
-
- // Now create our view matrix by defining coordinates for the
- // target, eye, and up vectors and using the g_math.matrix4.lookAt(..)
- // helper function to create the matrix.
-
- // Eye-position, this is where our camera is at.
- var eye = [0, 0, 3];
-
- // Target, this is where our camera is pointed at.
- var target = [0, 0, 0];
-
- // Up-vector, this tells the camera which direction is 'up'.
- // We define the positive y-direction to be up in this example.
- var up = [0, 1, 0];
-
- g_view_matrix = g_math.matrix4.lookAt(eye, target, up);
-
- // Generate the projection and viewProjection matrices based
- // on the g_o3d plugin size by calling resize().
- resize();
-
- // Now attach the sphere to the root of the transform graph.
- var root = g_client.root;
- root.addShape(myShape);
-
- // If we don't check the size of the client area every frame we don't get a
- // chance to adjust the perspective matrix fast enough to keep up with the
- // browser resizing us.
- g_client.setRenderCallback(resize);
-}
-
-// Generates the projection matrix based on the size of the o3d plugin
-// and calculates the view-projection matrix.
-function resize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- // Create our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 100.
- g_proj_matrix = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_o3dWidth / g_o3dHeight,
- 0.1,
- 100);
-
- // Set the view and projection matrix
- g_viewInfo.drawContext.view = g_view_matrix;
- g_viewInfo.drawContext.projection = g_proj_matrix;
- }
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table width="100%" style="height:100%;">
- <tr><td>
-<h1>Phong shading</h1>
-<p>
-This tutorial shows how we generate a custom mesh and
-perform Phong illumination using a shader.
-</p>
-<p>
-This sample displays a Phong shaded white sphere lit by a single red light.
-</p>
-<table id="container" width="90%" style="height:60%;"><tr><td height="100%">
-<!-- Start of g_o3d plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of g_o3d plugin -->
-</td></tr></table>
-<!-- Define the vertex shader -->
-<textarea id="vshader" name="vshader" cols="80" rows="20"
- style="display: none;">
- // The 4x4 world view projection matrix.
- uniform mat4 worldViewProjection;
-
- // positions of the light and camera
- uniform vec3 light_pos;
- uniform vec3 camera_pos;
-
- // input parameters for our vertex shader
- attribute vec4 position;
- attribute vec4 color;
- attribute vec3 normal;
-
- // pass to the fragment shader
- varying vec4 pColor;
- varying vec3 pViewPosition;
- varying vec3 pLightVector;
- varying vec3 pNormal;
-
- void main() {
-
- // NOTE: In this case we do not need to multiply by any matrices since the
- // WORLD transformation matrix is the identity. If you were moving the
- // object such that the WORLD transform matrix was not the identity, you
- // would need to multiply the normal by the WORLDINVERSETTRANSFORM matrix
- // since the normal is in object space. Other values (light_pos, camera_pos)
- // are already in world space.
-
- vec3 lightVector = light_pos - position.xyz;
- vec3 viewPosition = camera_pos - position.xyz;
-
- pLightVector = lightVector;
- pNormal = normal;
- pViewPosition = viewPosition;
- pColor = color;
-
- gl_Position = worldViewProjection * position;
- }
-</textarea>
-<!-- Define the fragment shader -->
-<textarea id="pshader" name="pshader" cols="80" rows="20"
- style="display: none;">
- // phong lighting components of the light source
- uniform vec4 light_ambient;
- uniform vec4 light_diffuse;
- uniform vec4 light_specular;
-
- // shininess of the material. (for specular lighting)
- uniform float shininess;
-
- // passed from the vertex shader
- varying vec4 pColor;
- varying vec3 pViewPosition;
- varying vec3 pLightVector;
- varying vec3 pNormal;
-
- /**
- * We use the standard phong illumination equation here.
- * We restrict (clamp) the dot products so that we
- * don't get any negative values.
- * All vectors are normalized for proper calculations.
- *
- * The output color is the summation of the
- * ambient, diffuse, and specular contributions.
- */
- void main() {
- vec3 lightVector = normalize(pLightVector);
- vec3 normal = normalize(pNormal);
- vec3 viewPosition = normalize(pViewPosition);
- vec3 halfVector = normalize(pLightVector + pViewPosition);
-
- // NOTE: This is actually Blinn-Phong shading, not Phong shading
- // which would use the reflection vector instead of the half vector
- float dotNormalHalf = dot(normal, halfVector);
-
- float ambientComp = 1.0;
- float diffuseComp = max(dot(normal, lightVector), 0.0);
- float specularComp = dot(normal, lightVector) < 0.0 ||
- dotNormalHalf < 0.0 ? 0.0 : pow(dotNormalHalf, shininess);
-
- vec4 ambient = light_ambient * ambientComp * pColor;
- vec4 diffuse = light_diffuse * diffuseComp * pColor;
- vec4 specular = light_specular * specularComp * pColor;
-
- gl_FragColor = ambient + diffuse + specular;
- }
-</textarea>
-</td></tr></table>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/picking-more.html b/o3d/samples/o3d-webgl-samples/picking-more.html
deleted file mode 100644
index b158603..0000000
--- a/o3d/samples/o3d-webgl-samples/picking-more.html
+++ /dev/null
@@ -1,384 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Picking and IndexBuffers
-</title>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.picking');
-
-// global variables
-var g_o3dElement;
-var g_client;
-var g_o3d;
-var g_math;
-var g_pack;
-var g_viewInfo;
-var g_eyePosition = [0, 0, 10];
-var g_dataroot;
-var g_pickManager;
-
-/**
- * Creates the client area.
- */
-function initClient() {
- window.g_finished = false; // for selenium testing.
- o3djs.webgl.makeClients(main);
-}
-
-/**
- * Updates the span with the name of the shape that was picked, if anything.
- * @param {event} e
- */
-function pick(e) {
- var worldRay = o3djs.picking.clientPositionToWorldRay(
- e.x,
- e.y,
- g_viewInfo.drawContext,
- g_client.width,
- g_client.height);
- var pickInfo = g_pickManager.pick(worldRay);
- var picked = 'nothing';
- if (pickInfo) {
- picked = pickInfo.shapeInfo.shape.name;
- }
- document.getElementById('picked').innerHTML = picked;
-}
-
-/**
- * Rotates the scene if key is one of 'wasd'.
- * @param {event} event
- */
-function rotateScene(event) {
- // Ignore accelerator key messages.
- if (event.metaKey)
- return;
-
- var keyChar = String.fromCharCode(o3djs.event.getEventKeyChar(event));
- // Just in case they have capslock on.
- keyChar = keyChar.toLowerCase();
-
- var actionTaken = false;
- var delta = 0.1;
- switch(keyChar) {
- case 'a':
- g_dataroot.localMatrix =
- g_math.matrix4.mul(g_dataroot.localMatrix,
- g_math.matrix4.rotationY(-delta));
- actionTaken = true;
- break;
- case 'd':
- g_dataroot.localMatrix =
- g_math.matrix4.mul(g_dataroot.localMatrix,
- g_math.matrix4.rotationY(delta));
- actionTaken = true;
- break;
- case 'w':
- g_dataroot.localMatrix =
- g_math.matrix4.mul(g_dataroot.localMatrix,
- g_math.matrix4.rotationX(-delta));
- actionTaken = true;
- break;
- case 's':
- g_dataroot.localMatrix =
- g_math.matrix4.mul(g_dataroot.localMatrix,
- g_math.matrix4.rotationX(delta));
- actionTaken = true;
- break;
- }
- if (actionTaken) {
- g_pickManager.update();
- }
-}
-
-/**
- * Initializes global variables, positions camera, draws shapes.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function main(clientElements) {
- // Init global variables.
- initGlobals(clientElements);
-
- // Set up the view and projection transformations.
- initContext();
-
- // Add the shapes to the transform heirarchy.
- createShapes();
-
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', pick);
- o3djs.event.addEventListener(g_o3dElement, 'keypress', rotateScene);
-
- // Create the pick manager.
- g_pickManager = o3djs.picking.createPickManager(g_client.root);
- g_pickManager.update();
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Initializes global variables and libraries.
- */
-function initGlobals(clientElements) {
- g_o3dElement = clientElements[0];
- window.g_client = g_client = g_o3dElement.client;
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Creates a transform to put our data on.
- g_dataroot = g_pack.createObject('Transform');
- g_dataroot.parent = g_client.root;
- g_dataroot.rotateY(-0.3);
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-}
-/**
- * Sets up reasonable view and projection matrices.
- */
-function initContext() {
- // Set up a perspective transformation for the projection.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree frustum.
- g_o3dElement.clientWidth / g_o3dElement.clientHeight, // Aspect ratio.
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // primitives are located.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- g_eyePosition, // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Creates shapes using the primitives utility library, and adds them to the
- * transform graph at the root node.
- */
-function createShapes() {
- var triangleFan = createShape(g_o3d.Primitive.TRIANGLEFAN);
- triangleFan.name = 'triangle-fan';
- var triangleStrip = createShape(g_o3d.Primitive.TRIANGLESTRIP);
- triangleStrip.name = 'triangle-strip';
- var triangleList = createShape(g_o3d.Primitive.TRIANGLELIST);
- triangleList.name = 'triangle-list';
- var noIndexBuffer = createShape(-1);
- noIndexBuffer.name = 'bufferless';
-
- // Add the shapes to the transforms.
- var transformTable = [
- {shape: noIndexBuffer, translation: [-0.5, 1.25, 0]},
- {shape: triangleFan, translation: [-1.0, -1.0, 0]},
- {shape: triangleStrip, translation: [1.0, -1.0, 0]},
- {shape: triangleList, translation: [0, 0, 0]}
- ];
-
- for (var tt = 0; tt < transformTable.length; ++tt) {
- var transform = g_pack.createObject('Transform');
- transform.addShape(transformTable[tt].shape);
- transform.translate(transformTable[tt].translation);
- transform.parent = g_dataroot;
- }
-}
-
-/**
- * Creates a shape that uses the requested indexing type.
- * @param {o3d.Primitive.Type} indexType
- */
-function createShape(indexType) {
- var material = g_pack.createObject('Material');
- var effect = g_pack.createObject('Effect');
- var shaderString = document.getElementById('shader').value;
- effect.loadFromFXString(shaderString);
- material.effect = effect;
- material.drawList = g_viewInfo.performanceDrawList;
- effect.createUniformParameters(material);
-
- var shape = g_pack.createObject('Shape');
- var primitive = g_pack.createObject('Primitive');
- var streamBank = g_pack.createObject('StreamBank');
-
- primitive.material = material;
- primitive.owner = shape;
- primitive.streamBank = streamBank;
- primitive.primitiveType = indexType;
- primitive.createDrawElement(g_pack, null);
-
- var positionArray = [];
-
- switch (indexType) {
- case g_o3d.Primitive.TRIANGLEFAN:
- positionArray = [
- 0.5, 0.0, 0.5, // 0
- 0.5, 0.0, -0.5, // 1
- -0.5, 0.0, -0.5, // 2
- -0.5, 0.0, 0.5, // 3
- 0.0, -1.0, 0.0 // 4
- ];
- indices = [4, 3, 2, 1, 0, 3]; // Square pyramid w/o the bottom.
- primitive.numberPrimitives = 4;
- primitive.numberVertices = 5;
- break;
- case g_o3d.Primitive.TRIANGLESTRIP:
- positionArray = [
- 0.0, 0.0, 0.0, // 0
- 1.0, 0.0, 0.0, // 1
- 0.5, 0.0, -0.866, // 2
- 0.5, 0.866, -0.433 // 3
- ];
- indices = [0, 1, 3, 2, 0, 1]; // Triangular pyramid sort of shape.
- primitive.numberPrimitives = 4;
- primitive.numberVertices = 4;
- break;
- case g_o3d.Primitive.TRIANGLELIST:
- positionArray = [
- -0.5, -0.5, 0.5, // vertex 0
- 0.5, -0.5, 0.5, // vertex 1
- -0.5, 0.5, 0.5, // vertex 2
- 0.5, 0.5, 0.5, // vertex 3
- -0.5, 0.5, -0.5, // vertex 4
- 0.5, 0.5, -0.5, // vertex 5
- -0.5, -0.5, -0.5, // vertex 6
- 0.5, -0.5, -0.5 // vertex 7
- ];
- indices = [
- 0, 1, 2, // face 1
- 2, 1, 3,
- 2, 3, 4, // face 2
- 4, 3, 5,
- 4, 5, 6, // face 3
- 6, 5, 7,
- 6, 7, 0, // face 4
- 0, 7, 1,
- 1, 7, 3, // face 5
- 3, 7, 5,
- 6, 0, 4, // face 6
- 4, 0, 2
- ];
- primitive.numberPrimitives = 12;
- primitive.numberVertices = 8;
- break;
- default:
- // No index buffer. Vertex data contains triples of triangles.
- positionArray = [
- -0.5, -0.5, 0.5,
- 0.5, -0.5, 0.5,
- -0.5, 0.5, 0.5,
- 0.5, -0.5, 0.5,
- 1.5, -0.5, 0.5, // vertex 1
- 1.5, 0.5, 0.5 // vertex 3
- ];
- indices = null;
- primitive.numberPrimitives = 2;
- primitive.numberVertices = 6;
- break;
- }
-
- // Create buffers containing the vertex data.
- var positionsBuffer = g_pack.createObject('VertexBuffer');
- var positionsField = positionsBuffer.createField('FloatField', 3);
- positionsBuffer.set(positionArray);
-
- if (indices) {
- var indexBuffer = g_pack.createObject('IndexBuffer');
- indexBuffer.set(indices);
- primitive.indexBuffer = indexBuffer;
- }
-
- // Associate the positions Buffer with the StreamBank.
- streamBank.setVertexStream(
- g_o3d.Stream.POSITION, // semantic: This stream stores vertex positions
- 0, // semantic index: First (and only) position stream
- positionsField, // field: the field this stream uses.
- 0); // start_index: How many elements to skip in the
- // field.
- return shape;
-}
-</script>
-</head>
-<body onload="initClient()">
-<h1>More Picking</h1>
-<p>This example demonstrates picking with custom shapes that use a variety of
-index buffer formats. Back faces are culled (hidden) and cannot be picked.</p>
-<p>
- You picked: <span id="picked" style="color: red;">nothing</span>
-</p>
-<p>Rotate in the scene with WASD.</p>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-
-<textarea id="shader" style="display: none;">
- attribute vec4 position;
- uniform mat4 worldViewProjection;
- varying vec4 pos;
-
- /**
- * The vertex shader simply transforms the input vertices to screen space.
- */
- void main() {
- // Multiply the vertex positions by the worldViewProjection matrix to
- // transform them to screen space.
- gl_Position = worldViewProjection * position;
- pos = position;
- }
-
- // #o3d SplitMarker
- varying vec4 pos;
-
- /**
- * The fragment shader derives color based on the position.
- */
- void main() {
- gl_FragColor = vec4(pos.xyz, 1.0);
- }
-</textarea>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/picking.html b/o3d/samples/o3d-webgl-samples/picking.html
deleted file mode 100644
index c6b6de1..0000000
--- a/o3d/samples/o3d-webgl-samples/picking.html
+++ /dev/null
@@ -1,345 +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.
--->
-
-<!--
-O3D Picking Example.
-
-This example shows one way to implement picking. Because O3D is shader
-agnostic we can't handle picking automatically since we have no way of knowing
-what the developer is going to do with their shaders. On the other hand, we can
-provide various functions that make it possible to do your own picking. Only you
-know which objects are pickable and which are not. For example if you are
-making an RTS game, only you would know that units are pickable but ground and
-explosions are not and that neither is your HUD.
-
-It's possible that someone, maybe us, will create an engine to use o3d
-that given a bunch of restrictions and flags on the data it excepts can
-do picking in a more automatic way but that is not the goal of the o3d api.
-Its goal is to provide a LOW-LEVEL shader agnostic API.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-O3D Picking Example.
-</title>
-<!-- Include default javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.picking');
-o3djs.require('o3djs.scene');
-o3djs.require('o3djs.debug');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// constants
-var NORMAL_SCALE_FACTOR = 2.0;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_pickManager; // information about the transform graph.
-var g_pickInfoElem;
-var g_debugHelper;
-var g_debugLineGroup;
-var g_debugLine;
-var g_selectedInfo = null;
-var g_flashTimer = 0;
-var g_highlightMaterial;
-var g_highlightShape;
-var g_finished = false; // for selenium testing.
-
-function updateInfo() {
- if (!g_pickManager) {
- g_pickManager = o3djs.picking.createPickManager(g_client.root);
- }
- g_pickManager.update();
-}
-
-function unSelectAll() {
- if (g_selectedInfo) {
- // Remove it from the transform of the selected object.
- g_selectedInfo.shapeInfo.parent.transform.removeShape(g_highlightShape);
- // Remove everything related to it.
- o3djs.shape.deleteDuplicateShape(g_highlightShape, g_pack);
- g_highlightShape = null;
- g_selectedInfo = null;
- // Turn off the debug line.
- g_debugLine.setVisible(false);
- }
-}
-
-function select(pickInfo) {
- unSelectAll();
- if (pickInfo) {
- g_selectedInfo = pickInfo;
- // make a copy of the selected shape so we can use it to highlight.
- g_highlightShape = o3djs.shape.duplicateShape(
- g_pack,
- g_selectedInfo.shapeInfo.shape,
- 'highlight_');
- // Set all of it's elements to use the highlight material.
- var elements = g_highlightShape.elements;
- for (var ee = 0; ee < elements.length; ee++) {
- elements[ee].material = g_highlightMaterial;
- }
-
- // Add it to the same transform
- g_selectedInfo.shapeInfo.parent.transform.addShape(g_highlightShape);
- g_flashTimer = 0.0; // make it change color immediately.
- }
-}
-
-function pick(e) {
- var worldRay = o3djs.picking.clientPositionToWorldRay(
- e.x,
- e.y,
- g_viewInfo.drawContext,
- g_client.width,
- g_client.height);
- unSelectAll();
-
- // Update the entire tree in case anything moved.
- // NOTE: This function is very SLOW!
- // If you really want to use picking you should manually update only those
- // transforms and shapes that moved, were added, or deleted by writing your
- // own picking library. You should also make sure that you are only
- // considering things that are pickable. By that I mean if you have a scene of
- // a meadow with trees, grass, bushes, and animals and the only thing the user
- // can pick is the animals then put the animals on their own sub branch of the
- // transform graph and only pick against that subgraph.
- // Even better, make a separate transform graph with only cubes on it to
- // represent the animals and use that instead of the actual animals.
- g_pickManager.update();
-
- var pickInfo = g_pickManager.pick(worldRay);
- if (pickInfo) {
- select(pickInfo);
- g_pickInfoElem.innerHTML = pickInfo.shapeInfo.shape.name;
-
- // Display the normal
- // NOTE: Lookup the normal with this function is very SLOW!!
- // If you need performance, for a game or something, you should consider
- // other methods.
- var normal = o3djs.element.getNormalForTriangle(
- pickInfo.element,
- pickInfo.rayIntersectionInfo.primitiveIndex);
-
- // Convert the normal from local to world space.
- normal = g_math.matrix4.transformNormal(
- pickInfo.shapeInfo.parent.transform.worldMatrix,
- normal);
-
- // Remove the scale from the normal.
- normal = g_math.normalize(normal);
-
- // Get the world position of the collision.
- var worldPosition = pickInfo.worldIntersectionPosition;
-
- // Add the normal to it to get a point in space above it with some
- // multiplier to scale it.
- var normalSpot = g_math.addVector(
- worldPosition,
- g_math.mulVectorScalar(normal, NORMAL_SCALE_FACTOR));
-
- // Move our debug line to show the normal
- g_debugLine.setVisible(true);
- g_debugLine.setEndPoints(worldPosition, normalSpot);
- } else {
- g_pickInfoElem.innerHTML = '--nothing--';
- }
-}
-
-function onrender(renderEvent) {
- g_flashTimer += renderEvent.elapsedTime;
- g_flashTimer = g_flashTimer % 0.5;
- if (g_selectedInfo) {
- if (g_flashTimer < 0.25) {
- g_highlightMaterial.getParam('emissive').value = [1, 1, 1, 1];
- } else {
- g_highlightMaterial.getParam('emissive').value = [0, 0, 0, 1];
- }
- }
-}
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- */
-function loadScene(pack, fileName, parent) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a cameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- g_client.width,
- g_client.height);
-
- // Copy the one from the file to ours.
- g_viewInfo.drawContext.view = cameraInfo.view;
- g_viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
-
- // Update our info
- updateInfo();
-
- g_pickManager.dump('');
-
- g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- o3dElement.name = 'o3dObj'; // This is only for our selenium tests.
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- g_pickInfoElem = document.getElementById('pickInfo');
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Use the debug library to create a line we can position to show
- // the normal.
- g_debugHelper = o3djs.debug.createDebugHelper(g_client.createPack(),
- g_viewInfo);
- g_debugLineGroup = g_debugHelper.createDebugLineGroup(g_client.root);
- g_debugLine = g_debugLineGroup.addLine();
- g_debugLine.setColor([0,1,0,1]);
- g_debugLine.setVisible(false);
-
- // Create a material for highlighting.
- g_highlightMaterial = o3djs.material.createConstantMaterial(
- g_pack,
- g_viewInfo,
- [1, 1, 1, 1]);
- // Setup a state to bring the lines forward.
- var state = g_pack.createObject('State');
- state.getStateParam('PolygonOffset2').value = -1.0;
- state.getStateParam('FillMode').value = g_o3d.State.WIREFRAME;
- g_highlightMaterial.state = state;
-
- // Creates a transform to put our data on.
- var my_data_root = g_pack.createObject('Transform');
-
- // Connects our root to the client's root.
- my_data_root.parent = g_client.root;
-
- // Load the scene into the transform graph as a child of my_data_root
- loadScene(g_pack, '../assets/seven_shapes/scene.json', my_data_root);
-
- g_client.setRenderCallback(onrender);
-
- // Start picking; it won't do anything until the scene finishes loading.
- o3djs.event.addEventListener(o3dElement, 'mousedown', pick);
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Picking</h1>
-Click on an object
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<div style="font-family: sans-serif; font-size: large;">PICKED: <span id="pickInfo"></span></div>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/pingpong/instructions.gif b/o3d/samples/o3d-webgl-samples/pingpong/instructions.gif
deleted file mode 100644
index d142083..0000000
--- a/o3d/samples/o3d-webgl-samples/pingpong/instructions.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/pingpong/logo.gif b/o3d/samples/o3d-webgl-samples/pingpong/logo.gif
deleted file mode 100644
index 379d196..0000000
--- a/o3d/samples/o3d-webgl-samples/pingpong/logo.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/pingpong/pingpong.html b/o3d/samples/o3d-webgl-samples/pingpong/pingpong.html
deleted file mode 100644
index 443d824..0000000
--- a/o3d/samples/o3d-webgl-samples/pingpong/pingpong.html
+++ /dev/null
@@ -1,846 +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.
--->
-
-<title>o3dPingPong</title>
-
-<script type="text/javascript" src="../../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.event');
-
-var camera = {};
-camera.eye = {};
-camera.target = {};
-camera.eye.x = 0;
-camera.eye.y = -100;
-camera.eye.z = 100;
-camera.target.x = 0;
-camera.target.y = 0;
-camera.target.z = 0;
-
-var on = false;
-var cube;
-var none;
-var view;
-var viewInfo;
-var g_material;
-var angleY=0;
-var angleX=0;
-var o3d;
-var math;
-var client;
-var pack;
-var g_finished = false; // for selenium
-
-var game = {};
-
-function updateView() {
- var matrix = math.matrix4.identity();
- math.matrix4.rotateZYX(matrix, [angleX, angleY, 0]);
- math.matrix4.scale(matrix, math.mulScalarVector(.25, [1, 1, 1]));
- view.localMatrix = matrix;
-}
-
-var key = {};
-key.LEFT = 37;
-key.UP = 38;
-key.RIGHT = 39;
-key.DOWN = 40;
-
-
-key.A = 65
-key.S = 83
-key.D = 68
-key.W = 87
-
-function keyPressed(e) {
- /*if (e.keyCode == key.A) rotateY(-0.1);
- else if (e.keyCode == key.D) rotateY(0.1)
- else if (e.keyCode == key.W) rotateX(-0.1)
- else if (e.keyCode == key.S) rotateX(0.1)*/
-}
-
-function move_instance(node, x, y, z, h) {
- node.identity();
- node.translate(x, y, z);
-}
-
-var entityID = 0;
-var transformNodes = new Array();
-var meshNodes = new Array();
-
-function createBox(x, y, z, w, d, h, color, parentNode, fadeToColor) {
-
- var boxVerts = [
- 0, 0, 0, // 0
- w, 0, 0, // 1
- w, 0, h, // 2
- 0, 0, h, // 3
- 0, d, 0, // 4
- w, d, 0, // 5
- w, d, h, // 6
- 0, d, h, // 7
- 0, 0, 0, // 0b
- w, 0, 0, // 1b
- w, 0, h, // 2b
- 0, 0, h, // 3b
- 0, d, 0, // 4b
- w, d, 0, // 5b
- w, d, h, // 6b
- 0, d, h // 7b
- ];
-
- var boxIndices = [
- 0, 1, 3, 1, 2, 3, // front
- 0+8, 3+8, 1+8, 1+8, 3+8, 2+8, // frontb
-
- 5+8, 4+8, 6+8, 4+8, 7+8, 6+8, // back
- 5+8, 6+8, 4+8, 4+8, 6+8, 7+8, // backb
-
- 4, 0, 7, 0, 3, 7, // left
- 4+8, 7+8, 0+8, 0+8, 7+8, 3+8, // leftb
-
- 1+8, 5+8, 2+8, 5+8, 6+8, 2+8, // right
- 1, 2+8, 5+8, 5+8, 2+8, 6+8, // rightb
-
- 4, 5, 0, 5, 1, 0, // top
- 4+8, 0+8, 5+8, 5+8, 0+8, 1+8, // top2
-
- 6+8, 7+8, 2+8, 7+8, 3+8, 2+8, // bottom
- 6+8, 2+8, 7+8, 7+8, 2+8, 3+8 // bottom2
- ];
-
-
- var boxIndicesOneSided = [
- 0, 1, 3, 1, 2, 3, // front
- 5+8, 4+8, 6+8, 4+8, 7+8, 6+8, // back
- 4, 0, 7, 0, 3, 7, // left
- 1+8, 5+8, 2+8, 5+8, 6+8, 2+8, // right
- 4, 5, 0, 5, 1, 0, // top
- 6+8, 7+8, 2+8, 7+8, 3+8, 2+8 // bottom
- ];
-
- if (color != undefined) {
- var r = color.r;
- var g = color.g;
- var b = color.b;
- var a = color.a;
- if (fadeToColor == color) {
- var boxColors = [
- r, g, b, a, // 0
- r, g, b, a, // 1
- r, g, b, a, // 2
- r, g, b, a, // 3
- r, g, b, a, // 4
- r, g, b, a, // 5
- r, g, b, a, // 6
- r, g, b, a, // 7
- r, g, b, a, // 0b
- r, g, b, a, // 1b
- r, g, b, a, // 2b
- r, g, b, a, // 3b
- r, g, b, a, // 4b
- r, g, b, a, // 5b
- r, g, b, a, // 6b
- r, g, b, a // 7b
- ];
-
- } else if (fadeToColor != undefined) {
- r2 = fadeToColor.r;
- g2 = fadeToColor.g;
- b2 = fadeToColor.b;
- var boxColors = [
- r2, g2, b2, a, // 0
- r2, g2, b2, a, // 1
- r, g, b, a, //
- r, g, b, a, // 3
- r2, g2, b2, a, // 4
- r2, g2, b2, a, // 5
- r, g, b, a, // 6
- r, g, b, a, // 7
- r2, g2, b2, a, // 0b
- r2, g2, b2, a, // 1b
- r, g, b, a, // 2b
- r, g, b, a, // 3b
- r2, g2, b2, a, // 4b
- r2, g2, b2, a, // 5b
- r, g, b, a, // 6b
- r, g, b, a // 7b
- ];
-
- } else {
- var boxColors = [
- r, g, b, a, // 0
- r, g, b, a, // 1
- r*.7, g*.7, b*.7, a, // 2
- r*.7, g*.7, b*.7, a, // 3
- r, g, b, a, // 4
- r, g, b, a, // 5
- r*.7, g*.7, b*.7, a, // 6
- r*.7, g*.7, b*.7, a, // 7
- r*.8, g*.8, b*.8, a, // 0b
- r*.8, g*.8, b*.8, a, // 1b
- r*.8, g*.8, b*.8, a, // 2b
- r*.8, g*.8, b*.8, a, // 3b
- r*.4, g*.4, b*.4, a, // 4b
- r*.4, g*.4, b*.4, a, // 5b
- r*.4, g*.4, b*.4, a, // 6b
- r*.4, g*.4, b*.4, a // 7b
- ];
- }
- } else {
- var boxColors = [
- 1, 0, 0, 1, // 0
- 1, 0, 0, 1, // 1
- 1, 0, 0, 1, // 2
- 1, 0, 0, 1, // 3
- 0, 1, 0, 1, // 4
- 0, 1, 0, 1, // 5
- 0, 1, 0, 1, // 6
- 0, 1, 0, 1, // 7
- .5, 0, 0, 1, // 0b
- .5, 0, 0, 1, // 1b
- .5, 0, 0, 1, // 2b
- .5, 0, 0, 1, // 3b
- 0, .5, 0, 1, // 4b
- 0, .5, 0, 1, // 5b
- 0, .5, 0, 1, // 6b
- 0, .5, 0, 1 // 7b
- ];
- }
-
- entityID++;
-
- transformName = 'transform' + entityID;
- shapeName = 'shape' + entityID;
- meshName = 'mesh' + entityID;
- transformNodes[entityID] = pack.createObject('Transform');
-
- transformNodes[entityID].translate(x, y, z);
-
- meshNodes[entityID] = pack.createObject('Shape');
- transformNodes[entityID].addShape(meshNodes[entityID])
- var primitive = pack.createObject('Primitive');
- var streamBank = pack.createObject('StreamBank');
- primitive.owner = meshNodes[entityID];
- primitive.streamBank = streamBank;
-
- primitive.material = g_material;
-
- var vertBuffer = pack.createObject('VertexBuffer');
- var positionField = vertBuffer.createField('FloatField', 3);
- vertBuffer.set(boxVerts);
-
- var colorBuffer = pack.createObject('VertexBuffer');
- var colorField = colorBuffer.createField('FloatField', 4);
- colorBuffer.set(boxColors);
-
- var indexBuffer = pack.createObject('IndexBuffer');
- indexBuffer.set(boxIndices);
-
- streamBank.setVertexStream(o3d.Stream.POSITION,
- 0,
- positionField,
- 0);
- streamBank.setVertexStream(o3d.Stream.COLOR,
- 0,
- colorField,
- 0);
- primitive.indexBuffer = indexBuffer;
-
- primitive.primitiveType = o3d.Primitive.TRIANGLELIST;
- primitive.numberPrimitives = 24;
- primitive.numberVertices = 16;
-
- if (parentNode != undefined) {
- transformNodes[entityID].parent = parentNode;
- } else {
- transformNodes[entityID].parent = view;
- }
-
- primitive.createDrawElement(pack, null);
-
- return transformNodes[entityID];
-}
-
-var Color = function(r, g, b, a) {
- if (r>1 || g>1 || b>1) {
- r = r/255;
- g = g/255;
- b = b/255;
- }
- this.r = r;
- this.g = g;
- this.b = b;
- this.a = a;
-}
-function scrollMe(e) {
- if (e.deltaY < 0) {
- camera.eye.x *= 11/12;
- camera.eye.y *= 11/12;
- camera.eye.z *= 11/12;
-
- } else {
- camera.eye.x *= (1+1/12);
- camera.eye.y *= (1+1/12);
- camera.eye.z *= (1+1/12);
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- var o3dElement = clientElements[0];
- o3dElement.id = 'o3dObj';
- o3d = o3dElement.o3d;
- math = o3djs.math;
- client = o3dElement.client;
-
- pack = client.createPack();
-
- // Create the render graph for a view.
- viewInfo = o3djs.rendergraph.createBasicView(
- pack,
- client.root,
- client.renderGraphRoot);
-
- var shader = document.getElementById('shader').value;
- var effect = pack.createObject('Effect');
- effect.loadFromFXString(shader);
- g_material = pack.createObject('Material');
- g_material.drawList = viewInfo.performanceDrawList;
- g_material.effect = effect;
- effect.createUniformParameters(g_material);
-
- view = pack.createObject('Transform');
- view.parent = client.root;
-
- var root = client.root;
-
- var o3d_width = client.width;
- var o3d_height = client.height;
-
- viewInfo.drawContext.projection=math.matrix4.perspective(
- math.degToRad(30), o3d_width / o3d_height, 1, 5000);
- target = [0, 0, 0];
- eye = [0, -100, 0];
- up = [0, 0, 1];
- viewInfo.drawContext.view = math.matrix4.lookAt(eye, target, up);
-
- bg = pack.createObject('Transform');
- bg.translate(0, 0, 1);
- bg.parent = client.root;
-
- red = new Color(1, 0, 0, 1);
- blue = new Color(0, 0, 1, 1);
- wallColor = new Color(0, .8, .4, 1);
- green = new Color(0, .5, 0, 1);
- lineColor = new Color(0, .7, 0, 1);
- shadow = new Color(0, .3, 0, .5);
- silver = new Color(.8, .8, .8, 1);
- pink = new Color(1, .8, .8, 1);
-
- window.field = createBox(-120, -80, -10, 240, 160, 10, green)
- window.centerline = createBox(-3, -80, 0, 6, 160, .5, lineColor)
- window.paddle1 = createBox(-110, 0, 5, 10, 30, 30, silver);
- window.shadow1 = createBox(-107, 3, 1, 10, 30, 0, shadow);
-
- window.paddle2 = createBox(-110, 0, 5, 10, 30, 30, silver);
- window.shadow2 = createBox(-107, 3, 1, 10, 30, 0, shadow);
-
- window.ball = createBox(0, 0, 2, 10, 10, 10, pink);
- window.ballShadow = createBox(0, 0, 1, 10, 10, 0, shadow);
-
- window.bottomWall = createBox(-120, -90, -10, 240, 10, 15, wallColor);
- window.topWall = createBox(-120, 80, -10, 240, 10, 15, wallColor);
-
- suRed = new Color(.7, 0, 0, 1)
- suGreen = new Color(0, .7, 0, 1)
- suBlue = new Color(0, 0, .7, 1)
- suGround = new Color(210, 208, 185, 1);
- suSky = new Color(212*.8, 225*.8, 225*.8, 1);
-
- window.xaxis = createBox(0, 0, 0, 5000, .25, .25, suRed, undefined);
- window.yaxis = createBox(0, 0, 0, .25, 5000, .25, suGreen, undefined);
- window.zaxis = createBox(0, 0, 0, .25, .25, 5000, suBlue, undefined);
-
- white = new Color(1, 1, 1, 1);
-
- mybox3 = createBox(-1500, -1500, -1500, 3000, 3000, 3000, suSky, bg, suGround);
- bg_Ground1 = createBox(-1500, 1490, -1500, 3000, 10, 1500, suGround, bg, suGround);
- bg_GroundR = createBox(1490, -1500, -1500, 10, 3000, 1500, suGround, bg, suGround);
- bg_GroundL = createBox(-1490, -1500, -1500, 10, 3000, 1500, suGround, bg, suGround);
- bg_Sky = createBox(-1500, 1490, 0, 3000, 10, 1500, suSky, bg, white);
- bg_SkyR = createBox(1490, -1500, 0, 10, 3000, 1500, suSky, bg, white);
- bg_SkyL = createBox(-1490, -1500, 0, 10, 3000, 1500, suSky, bg, white);
-
- on=true;
- updateView();
-
- o3djs.event.addEventListener(o3dElement, 'wheel', scrollMe);
-
- updateLayout();
-
- g_finished = true; // for selenium
-}
-
-function rotateX(delta) {
- angleX=angleX+delta;
- updateView();
-}
-
-function rotateY(delta) {
- angleY=angleY+delta;
- updateView();
-}
-
-function toggle() {
- if (on) {
- cube.parentNode = none;
- } else {
- cube.parentNode = view;
- }
-
- on = !on;
-}
-
-function startGame() {
- if (window.gameStarted == true) {
- return
- }
- window.gameStarted = true;
- document.getElementById('o3d').style.visibility = 'visible';
-
- // Wait until the plug-in has initialized before starting the game.
- var clearId = window.setInterval(function() {
- if (client) {
- client.setRenderCallback(nextFrame);
- } else {
- return;
- }
- window.clearInterval(clearId);
- }, 10);
-}
-
-function updateLayout() {
- document.getElementById('focusHolder').focus();
- document.body.scrollTop = 0;
-
-}
-
-function uninit() {
- if (client) {
- client.cleanup();
- }
-}
-
-window.onload = init;
-window.onunload = uninit;
-
-</script>
-<body style="overflow:hidden" onscroll="updateLayout();">
-
-<table border=0 width=100% height=100% style="overflow:hidden" >
-<tr><td id="clientBanner" align=center style="cursor:pointer;background-image:url(logo.gif);background-position:center center;background-repeat:no-repeat" onclick="startGame();">
-<div id="client" name="client" >
-<div id="o3d" style="width: 800px; height: 600px; visibility: hidden;"></div>
-<br/><img src="instructions.gif"></div>
-<form>
-<input id="focusHolder" style="position:absolute;top:-100px;">
-</form>
-</td></tr></table>
-
-<textarea style="display: none;" id="shader" name="shader">
-uniform mat4 worldViewProjection;
-attribute vec4 position;
-attribute vec4 color;
-varying vec4 pcolor;
-void main() {
- gl_Position = worldViewProjection * position;
- pcolor = color;
-}
-// #o3d SplitMarker
-varying vec4 pcolor;
-void main() {
- gl_FragColor = pcolor;
-}
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-
-</body>
-
-<script>
-
-keyIsDown = new Array();
-
-document.onkeydown = function(e) {
- var keyChar = o3djs.event.getEventKeyChar(e);
- keyIsDown[keyChar] = true;
-}
-
-document.onkeyup = function(e) {
- var keyChar = o3djs.event.getEventKeyChar(e);
- keyIsDown[keyChar] = false;
-}
-
-
-var x = 1000+10;
-var y = 1000+20;
-var z = 1;
-
-var BACKSPACE=8
-var TAB=9
-var ENTER=13
-var SHIFT=16
-var CTRL=17
-var ALT=18
-var ESCAPE=27
-var PAGEUP=33
-var PAGEDOWN=34
-var END=35
-var HOME=36
-var LEFT=37
-var UP=38
-var RIGHT=39
-var DOWN=40
-var DELETE=46
-var SPACE=32
-
-var spriteInfo = new Array();
-
-
-var leftID = 0
-var rightID = 1
-var ballID = 2
-var myPaddleID = leftID
-var enemyPaddleID = rightID
-var nextServeDirection = -1
-var isServing = true;
-var loop = 0;
-
-
-
-spriteInfo[leftID] = new Array();
-spriteInfo[rightID] = new Array();
-spriteInfo[ballID] = new Array();
-
-spriteInfo[leftID].velocityY = 0;
-spriteInfo[leftID].velocityX = 0;
-spriteInfo[leftID].x = 10;
-spriteInfo[leftID].y = 80;
-
-spriteInfo[rightID].velocityY = 0;
-spriteInfo[rightID].velocityX = 0;
-spriteInfo[rightID].x = 230;
-spriteInfo[rightID].y = 80;
-
-spriteInfo[ballID].velocityY = 0;
-spriteInfo[ballID].velocityX = 0;
-spriteInfo[ballID].x = 120;
-spriteInfo[ballID].y = 80;
-
-var SCREENHEIGHT = 160;
-var SCREENWIDTH = 240;
-var PADDLE
-
-var BALLWIDTH = 30
-var BALLHEIGHT = 32
-
-var BALLPAD = 20
-var PADDLEHEIGHT = 30
-var PADDLEWIDTH = 10
-var PADDLEACCELY = 10 // acceleration rate of the paddle
-var PADDLEACCELX = 10 // acceleration rate of the paddle
-var SCREENWIDTH = 240
-var SCREENHEIGHT = 160
-var SCREENCENTERX = 120
-var SCREENCENTERY = 80
-
-var COMPUTERACCURACYX=90 // accuracy in pixels that the computer tries to get its paddle within
-var COMPUTERACCURACYY=10
-
-var points = [0, 0, 0];
-function ScorePoint(playerNumber) {
-
- if (playerNumber == myPaddleID) {
- //alert('You Score!');
- } else {
- //alert('You Suck!');
- }
- spriteInfo[ballID].velocityX = 0;
- spriteInfo[ballID].velocityY = 0;
-
- spriteInfo[ballID].x = SCREENWIDTH/2;
- spriteInfo[ballID].y = SCREENHEIGHT/2;
- points[playerNumber]++;
- pts = points[playerNumber];
-
- ptBox = createBox(-140 + playerNumber*280, -80+pts*15, 0, 10, 10, 3, red);
-
-
-}
-
-
-function nextFrame(render_event) {
-
- var elapsedTime = render_event.elapsedTime;
-
- spriteInfo[ballID].x += spriteInfo[ballID].velocityX * elapsedTime;
- spriteInfo[ballID].y += spriteInfo[ballID].velocityY * elapsedTime;
-
- spriteInfo[leftID].x += spriteInfo[leftID].velocityX * elapsedTime;
- spriteInfo[leftID].y += spriteInfo[leftID].velocityY * elapsedTime;
-
- spriteInfo[rightID].x += spriteInfo[rightID].velocityX * elapsedTime;
- spriteInfo[rightID].y += spriteInfo[rightID].velocityY * elapsedTime;
-
- // move my paddle
- if (keyIsDown[UP]) {
- spriteInfo[myPaddleID].velocityY -= PADDLEACCELY;
- } else if (keyIsDown[DOWN]) {
- spriteInfo[myPaddleID].velocityY += PADDLEACCELY;
- } else {
- spriteInfo[myPaddleID].velocityY -= spriteInfo[myPaddleID].velocityY * elapsedTime;
- }
-
- if (keyIsDown[LEFT]) {
- spriteInfo[myPaddleID].velocityX -= PADDLEACCELX;
- } else if (keyIsDown[RIGHT]) {
- spriteInfo[myPaddleID].velocityX += PADDLEACCELX;
- } else {
- spriteInfo[myPaddleID].velocityX -= spriteInfo[myPaddleID].velocityX * elapsedTime;
- }
-
- if (keyIsDown[key.A]) camera.eye.x -= 100 * elapsedTime;
- if (keyIsDown[key.D]) camera.eye.x += 100 * elapsedTime;
- if (keyIsDown[key.W]) camera.eye.z += 100 * elapsedTime;
- if (keyIsDown[key.S]) camera.eye.z -= 100 * elapsedTime;
-
- target = [0, 0, 0];
- eye = [camera.eye.x, camera.eye.y, camera.eye.z];
- up = [0, 0, 1];
- viewInfo.drawContext.view = math.matrix4.lookAt(eye, target, up);
-
- // make sure my paddle can't go off the top & bottom of screen
- if (spriteInfo[myPaddleID].y < PADDLEHEIGHT/2) {
- spriteInfo[myPaddleID].y = PADDLEHEIGHT/2;
- spriteInfo[myPaddleID].velocityY = 0;
- } else if (spriteInfo[myPaddleID].y > SCREENHEIGHT-PADDLEHEIGHT/2) {
- spriteInfo[myPaddleID].y = SCREENHEIGHT-PADDLEHEIGHT/2;
- spriteInfo[myPaddleID].velocityY = 0;
- }
-
- if (spriteInfo[myPaddleID].x < PADDLEWIDTH) {
- spriteInfo[myPaddleID].x = PADDLEWIDTH;
- spriteInfo[myPaddleID].velocityX = 0;
- } else if (spriteInfo[myPaddleID].x > SCREENWIDTH/2-BALLPAD) {
- spriteInfo[myPaddleID].x = SCREENWIDTH/2-BALLPAD;
- spriteInfo[myPaddleID].velocityX = 0;
- }
-
- // handle bouncing
- MoveComputer();
-
- if ( spriteInfo[ballID].x + BALLWIDTH/2 > spriteInfo[rightID].x &&
- spriteInfo[ballID].x + BALLWIDTH/2 < spriteInfo[rightID].x + PADDLEWIDTH &&
- spriteInfo[ballID].y > spriteInfo[rightID].y-PADDLEHEIGHT/2 &&
- spriteInfo[ballID].y < spriteInfo[rightID].y+PADDLEHEIGHT/2
- && spriteInfo[ballID].velocityX > 0) {
-
- spriteInfo[ballID].velocityX *= -1;
- spriteInfo[ballID].velocityY += spriteInfo[rightID].velocityY/2
- if (spriteInfo[rightID].velocityX < 0) {
- spriteInfo[ballID].velocityX += spriteInfo[rightID].velocityX;
- }
-
-
- } else if (spriteInfo[ballID].x - BALLWIDTH/2 < spriteInfo[leftID].x &&
- spriteInfo[ballID].x - BALLWIDTH/2 > spriteInfo[leftID].x - PADDLEWIDTH &&
- spriteInfo[ballID].y > spriteInfo[leftID].y-PADDLEHEIGHT/2 &&
- spriteInfo[ballID].y < spriteInfo[leftID].y+PADDLEHEIGHT/2
- && spriteInfo[ballID].velocityX < 0) {
-
- spriteInfo[ballID].velocityX *= -1;
- spriteInfo[ballID].velocityY += spriteInfo[leftID].velocityY/2;
- if (spriteInfo[leftID].velocityX > 0) {
- spriteInfo[ballID].velocityX += spriteInfo[leftID].velocityX;
- }
-
- }
-
-
-
- if (isServing) {
- loop++;
- if (loop > 20) {
- loop=0;
- spriteInfo[ballID].isVisible = true;
- spriteInfo[ballID].velocityY = ((Math.random()*4)-2)*20;
- spriteInfo[ballID].velocityX = (((Math.random()*1)+2) * nextServeDirection)*20;
- isServing = false;
- }
- }
-
-
-
- // bounce along top or bottom
- if ((spriteInfo[ballID].y > SCREENHEIGHT-10 || spriteInfo[ballID].y < 10) && isServing == false) {
- spriteInfo[ballID].velocityY *= -1;
- }
-
-
- if (spriteInfo[ballID].x < -50) {
- // right player scores a point!
- ScorePoint(rightID);
- nextServeDirection = -1;
- isServing = true;
- }
-
- if (spriteInfo[ballID].x > SCREENWIDTH+50) {
- // left player scores a point!
- ScorePoint(leftID);
- nextServeDirection = -1;
- isServing = true;
- }
-
-
- move_instance(paddle1, -120+spriteInfo[myPaddleID].x-PADDLEWIDTH/2, 80-spriteInfo[myPaddleID].y-PADDLEHEIGHT/2, 5, 30);
- move_instance(shadow1, -120+spriteInfo[myPaddleID].x+5-PADDLEWIDTH/2, 80-spriteInfo[myPaddleID].y-PADDLEHEIGHT/2+5, 1, 0);
-
- move_instance(paddle2, -120+spriteInfo[rightID].x-PADDLEWIDTH/2, 80-spriteInfo[rightID].y-PADDLEHEIGHT/2, 5, 30);
- move_instance(shadow2, -120+spriteInfo[rightID].x+5-PADDLEWIDTH/2, 80-spriteInfo[rightID].y-PADDLEHEIGHT/2+5, 1, 0);
-
- move_instance(ball, -120+spriteInfo[ballID].x-5, 80-(spriteInfo[ballID].y+5), 10, 10);
- move_instance(ballShadow, -120+spriteInfo[ballID].x-5+5, 80-(spriteInfo[ballID].y+0), 1, 0);
-}
-
-function MoveComputer() {
-// calculate where the AI wants to be
- if (spriteInfo[ballID].velocityX > 0) {
-
- // if the ball is coming our way, calculate where it will go
- targetX = spriteInfo[ballID].x;
- targetY = spriteInfo[ballID].y;
-
- } else {
-
- // else return to center
- targetX = 220;
- targetY = 80;
-
- }
-
- if (ComputerDistanceX() < COMPUTERACCURACYX) {
-
- spriteInfo[rightID].velocityX = spriteInfo[rightID].velocityX/2;
-
- } else {
-
- if (targetX < spriteInfo[rightID].x) {
- spriteInfo[rightID].velocityX -= PADDLEACCELX;
- } else if (targetX > spriteInfo[rightID].x) {
- spriteInfo[rightID].velocityX += PADDLEACCELX;
- } else {
- spriteInfo[rightID].velocityX = spriteInfo[rightID].velocityX/2;
- }
- }
-
- if (ComputerDistanceY() < COMPUTERACCURACYY) {
-
- spriteInfo[rightID].velocityY = spriteInfo[rightID].velocityY/2;
-
- } else {
-
- if (targetY < spriteInfo[rightID].y) {
- spriteInfo[rightID].velocityY -= PADDLEACCELY;
- } else if (targetY > spriteInfo[rightID].y) {
- spriteInfo[rightID].velocityY += PADDLEACCELY;
- } else {
- spriteInfo[rightID].velocityY = spriteInfo[rightID].velocityY/2;
- }
-
- }
-
- // make sure paddle can't go off the top & bottom of screen
- if (spriteInfo[rightID].y < PADDLEHEIGHT/2) {
- spriteInfo[rightID].y = PADDLEHEIGHT/2;
- spriteInfo[rightID].velocityY = 0;
- } else if (spriteInfo[rightID].y > SCREENHEIGHT-PADDLEHEIGHT/2) {
- spriteInfo[rightID].y = SCREENHEIGHT-PADDLEHEIGHT/2;
- spriteInfo[rightID].velocityY = 0;
- }
-
- if (spriteInfo[rightID].x > SCREENWIDTH) {
- spriteInfo[rightID].x = SCREENWIDTH-PADDLEWIDTH;
- spriteInfo[rightID].velocityX = 0;
- } else if (spriteInfo[rightID].x < SCREENWIDTH/2+BALLPAD) {
- spriteInfo[rightID].x = SCREENWIDTH/2+BALLPAD;
- spriteInfo[rightID].velocityX = 0;
- }
-
-
-}
-
-function ComputerDistanceX() {
- var distanceX;
- distanceX = spriteInfo[rightID].x - spriteInfo[ballID].x;
- if (distanceX < 0) {
- distanceX = distanceX * -1;
- }
- return distanceX;
-}
-
-function ComputerDistanceY() {
- var distanceY;
- distanceY = spriteInfo[ballID].y - spriteInfo[rightID].y;
- if (distanceY < 0) {
- distanceY = distanceY * -1;
- }
- return distanceY;
-}
-
-
-
-</script>
-
diff --git a/o3d/samples/o3d-webgl-samples/pool.html b/o3d/samples/o3d-webgl-samples/pool.html
deleted file mode 100644
index f9e983f0..0000000
--- a/o3d/samples/o3d-webgl-samples/pool.html
+++ /dev/null
@@ -1,2187 +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 sample is a pool game engine with a 3D physics model. All models
-are procedurally generated. Textures for the balls are loaded from a
-single image file and then split up using Bitmaps.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<style>
- html, body {
- border: 0;
- margin: 0;
- width: 100%;
- height: 100%;
- }
- div#container {
- position:relative; /* Needed for footer positioning. */
- margin:0 auto; /* Center, not in IE5. */
-
- height:auto !important; /* For browsers other than IE. */
- min-height:100%;
-
- height:100%; /* For IE6. */
- }
- div#footer {
- position:absolute;
- width:100%;
- bottom:0; /* Stick to bottom. */
- background: #111111;
- }
-</style>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Pool
-</title>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.event');
-
-
-var SHADOWPOV = false; // Shows the rendertarget where the shadows get drawn.
-
-// global variables
-var g_o3dElement;
-var g_client;
-var g_o3d;
-var g_math;
-var g_quat;
-var g_pack;
-var g_viewInfo;
-var g_clock = 0;
-var g_shadowPassViewInfo;
-var g_ballTransforms = [];
-var g_centers = [];
-
-var g_ballTextures = [];
-var g_ballTextureSamplers = [];
-var g_ballTextureSamplerParams = [];
-var g_shadowOnParams = [];
-
-var g_shadowSampler;
-var g_shadowTexture;
-
-var g_tableRoot;
-var g_shadowRoot;
-var g_hudRoot;
-var g_barRoot;
-
-var g_physics;
-
-var g_target = [0, 0, 0];
-var g_light = [0, 0, 50];
-
-var g_materials;
-var g_solidMaterial;
-
-var RENDER_TARGET_WIDTH = 512;
-var RENDER_TARGET_HEIGHT = 512;
-
-var g_queueClock = 0;
-
-var g_rolling = false;
-var g_shooting = false;
-
-var g_table = null;
-
-
-g_queue = [];
-
-// g_queue is a list of commands to run at various time intervals,
-// it is supposed to be used one day to implement an opponent. For now,
-// comment this in to allow the AI to play.
-/*
-var g_queue = [
- {condition: '!(g_shooting || g_rolling)',
- action: 'cueNewShot(.9);'}
-];
-*/
-
-
-var pool = {};
-
-function myMod(n, m) {
- return ((n % m) + m) % m;
-}
-
-pool.Ball = function() {
- this.mass = 1.0;
- this.angularInertia = 0.4;
- this.center = [0, 0, 0];
- this.velocity = [0, 0, 0];
- this.verticalAcceleration = 0;
- this.orientation = [0, 0, 0, 1];
- this.angularVelocity = [0, 0, 0];
- this.active = true;
- this.sunkInPocket = -1;
-};
-
-pool.Physics = function() {
- this.record = [];
-
- this.speedFactor = 0;
- this.maxSpeed = 1;
-
- this.balls = [];
- for (var i = 0; i < 16; ++i) {
- this.balls.push(new pool.Ball());
- }
-
- // The cue ball is slightly heavier
- // than the rest of the balls.
- // 6 ounces versus 5.5.
- this.balls[0].mass *= 6.0 / 5.5;
- this.balls[0].rotationalInertia *= 6.0 / 5.5;
-
- this.walls = [];
- this.collisions = [];
- this.wallCollisions = [];
-
- this.placeBalls = function() {
- for (var i = 0; i < 16; ++i) {
- var ball = this.balls[i];
- if (!ball.active) {
- g_shadowOnParams[i].value = 0;
- continue;
- }
- var p = ball.center;
- placeBall(i, p[0], p[1], p[2], ball.orientation);
- }
- };
-
- this.step = function() {
- for (var i = 0; i < 5; ++i) {
- this.ballsLoseEnergy();
- this.ballsImpactFloor();
- this.move(1);
- while (this.collide()) {
- this.move(-1);
- this.handleCollisions();
- this.move(1);
- }
- }
- this.sink();
- this.handleFalling();
- this.placeBalls();
- };
-
- this.move = function(timeStep) {
- for (var i = 0; i < 16; ++i) {
- var ball = this.balls[i];
- if (!ball.active)
- continue;
- var p = ball.center;
- var v = ball.velocity;
- p[0] += timeStep * v[0];
- p[1] += timeStep * v[1];
- p[2] += timeStep * v[2];
- ball.orientation = this.quat.normalize(this.quat.mul(
- vectorToQuaternion(this.math.mulScalarVector(
- timeStep, ball.angularVelocity)), ball.orientation));
- v[2] += ball.verticalAcceleration;
- }
- };
-
- this.impartSpeed = function(i, direction) {
- var ball = this.balls[i];
- ball.velocity[0] += direction[0] * this.maxSpeed * this.speedFactor;
- ball.velocity[1] += direction[1] * this.maxSpeed * this.speedFactor;
- };
-
- this.stopAllBalls = function() {
- for (var i = 0; i < 16; ++i) {
- var ball = this.balls[i];
- var v = ball.velocity;
- var w = ball.angularVelocity;
- v[0] = 0;
- v[1] = 0;
- v[2] = 0;
- w[0] = 0;
- w[1] = 0;
- w[2] = 0;
- }
- };
-
- this.stopSlowBalls = function() {
- var epsilon = 0.0001;
- for (var i = 0; i < 16; ++i) {
- var ball = this.balls[i];
- if (!ball.active)
- continue;
- var v = ball.velocity;
- var w = ball.angularVelocity;
- if (this.math.length(v) < epsilon) {
- v[0] = 0;
- v[1] = 0;
- v[2] = 0;
- }
- if (this.math.length(w) < epsilon) {
- w[0] = 0;
- w[1] = 0;
- w[2] = 0;
- }
- }
- };
-
- this.someBallsMoving = function() {
- for (var i = 0; i < 16; ++i) {
- var ball = this.balls[i];
- if (!ball.active)
- continue;
- var v = ball.velocity;
- var w = ball.angularVelocity;
- if (v[0] != 0 || v[1] != 0 || v[2] != 0 ||
- w[0] != 0 || w[1] != 0 || w[2] != 0)
- return true;
- }
- return false;
- };
-
- this.sink = function() {
- for (var i = 0; i < 16; ++i) {
- var ball = this.balls[i];
- if (!ball.active)
- continue;
- var p = this.balls[i].center;
- for (var j = 0; j < this.pocketCenters.length; ++j) {
- var pocketCenter = this.pocketCenters[j];
- var dx = p[0] - pocketCenter[0];
- var dy = p[1] - pocketCenter[1];
- if (dx * dx + dy * dy <
- this.pocketRadius * this.pocketRadius) {
- ball.verticalAcceleration = -0.005;
- ball.sunkInPocket = j;
- }
- }
- }
- };
-
- this.handleFalling = function() {
- for (var i = 0; i < 16; ++i) {
- var ball = this.balls[i];
- if (!ball.active)
- continue;
- if (ball.sunkInPocket >= 0) {
- var p = ball.center;
- var z = p[2];
- var pocketCenter = this.pocketCenters[ball.sunkInPocket];
- var dx = p[0] - pocketCenter[0];
- var dy = p[1] - pocketCenter[1];
-
- // Once the ball is sunk, it must not escape the pocket.
- var norm = Math.sqrt(dx * dx + dy * dy);
- var maxNorm =
- this.pocketRadius - Math.sqrt(Math.max(0, 1 - (z + 1) * (z + 1)));
- if (norm > maxNorm) {
- p[0] = pocketCenter[0] + dx * maxNorm / norm;
- p[1] = pocketCenter[1] + dy * maxNorm / norm;
- }
- }
- if (ball.center[2] < -3) {
- var v = ball.velocity;
- var w = ball.angularVelocity;
- v[0] = 0;
- v[1] = 0;
- v[2] = 0;
- w[0] = 0;
- w[1] = 0;
- w[2] = 0;
- ball.verticalAcceleration = 0;
- ball.active = false;
- ballOff(i);
- }
- }
- };
-
- this.boundCueBall = function() {
- var c = this.balls[0].center;
- if (c[0] < this.left)
- c[0] = this.left;
- if (c[0] > this.right)
- c[0] = this.right;
- if (c[1] < this.bottom)
- c[1] = this.bottom;
- if (c[1] > this.top)
- c[1] = this.top;
- this.pushOut();
- this.placeBalls();
- };
-
- this.collide = function() {
- this.collideBalls();
- this.collideWithWalls();
- return this.collisions.length != 0 || this.wallCollisions.length != 0;
- };
-
- this.pushOut = function() {
- while (this.collide()) {
- this.pushCollisions();
- }
- }
-
- this.collideBalls = function() {
- this.collisions = [];
- for (var i = 0; i < 16; ++i) {
- if (!this.balls[i].active)
- continue;
- var p1 = this.balls[i].center;
- for (var j = 0; j < i; ++j) {
- if (!this.balls[j].active)
- continue;
- var p2 = this.balls[j].center;
-
- var dx = p1[0] - p2[0];
- var dy = p1[1] - p2[1];
-
- var normSquared = dx * dx + dy * dy;
- if (normSquared < 3.99) {
- var norm = Math.sqrt(normSquared)
- this.collisions.push({i: i, j: j, ammt: 2 - norm});
- }
- }
- }
- };
-
- this.initWalls = function() {
- var r = this.pocketRadius;
- var w = this.tableWidth;
-
- // Three walls connecting the points in this list get put around each
- // cushion.
- var path = [[0, -w / 2 + r, 0],
- [r, -w / 2 + 2 * r, 0],
- [r, w / 2 - 2 * r, 0],
- [0, w / 2 - r, 0]];
-
- var angles = [0, Math.PI/2, Math.PI, Math.PI, 3 * Math.PI / 2, 0];
- var translations = this.math.generalizedMulMatrixMatrix(
- [[-1, -1, 0], [0, -2, 0], [1, -1, 0], [1, 1, 0], [0, 2, 0], [-1, 1, 0]],
- [[w / 2, 0, 0], [0, w / 2, 0], [0, 0, 1]]);
-
- for (var i = 0; i < 6; ++i) {
- var newPath = [];
- for (var j = 0; j < path.length; ++j) {
- newPath.push(
- this.math.matrix4.transformPoint(this.math.matrix4.composition(
- this.math.matrix4.translation(translations[i]),
- this.math.matrix4.rotationZ(angles[i])), path[j]));
- }
-
- for (var j = 0; j < newPath.length - 1; ++j) {
- this.walls.push({p: [newPath[j][0], newPath[j][1]],
- q: [newPath[j + 1][0], newPath[j + 1][1]]});
- }
- }
-
- this.computeWallNormals(this.walls);
- };
-
- this.computeWallNormals = function(walls) {
- for (var i = 0; i < walls.length; ++i) {
- var wall = walls[i];
- var tangent = this.math.normalize(this.math.subVector(wall.q, wall.p));
- wall.nx = tangent[1];
- wall.ny = -tangent[0];
- wall.k = wall.nx * wall.p[0] + wall.ny * wall.p[1];
- wall.a = wall.p[1] * wall.nx - wall.p[0] * wall.ny;
- wall.b = wall.q[1] * wall.nx - wall.q[0] * wall.ny;
- }
- }
-
- this.collideWithWalls =
- function(opt_wallList, opt_collisionList, opt_radius) {
- var radius = opt_radius || 1.0;
- var walls = opt_wallList || this.walls;
- var wallCollisions = opt_collisionList || this.wallCollisions;
- while(wallCollisions.length) {
- wallCollisions.pop();
- }
-
- for (var i = 0; i < 16; ++i) {
- var ball = this.balls[i];
- if (!ball.active)
- continue;
- var p = ball.center;
- var x = p[0];
- var y = p[1];
-
- if (!opt_wallList &&
- x > this.left &&
- x < this.right &&
- y > this.bottom &&
- y < this.top) {
- continue;
- }
-
- for (var j = 0; j < walls.length; ++j) {
- var wall = walls[j];
- var norm = Math.abs(x * wall.nx + y * wall.ny - wall.k);
- if (norm < radius) {
- var t = y * wall.nx - x * wall.ny;
- if (t > wall.a && t < wall.b) {
- wallCollisions.push({i: i, x: wall.nx, y: wall.ny, ammt: 1 - norm});
- break;
- } else {
- var dx = x - wall.p[0];
- var dy = y - wall.p[1];
- var normSquared = dx * dx + dy * dy;
- if (normSquared < radius*radius) {
- var norm = Math.sqrt(normSquared);
- wallCollisions.push(
- {i: i, x: dx / norm, y: dy / norm, ammt: 1 - norm});
- break;
- }
- var dx = x - wall.q[0];
- var dy = y - wall.q[1];
- var normSquared = dx * dx + dy * dy;
- if (normSquared < radius*radius) {
- var norm = Math.sqrt(normSquared);
- wallCollisions.push(
- {i: i, x: dx / norm, y: dy / norm, n: 1 - norm});
- break;
- }
- }
- }
- }
- }
- };
-
- this.pushCollisions = function() {
- var l = this.wallCollisions.length;
- for (var i = 0; i < l; ++i) {
- var c = this.wallCollisions[i];
- var p = this.balls[c.i].center;
-
- p[0] += c.ammt * c.x;
- p[1] += c.ammt * c.y;
- }
-
- var l = this.collisions.length;
- for (var i = 0; i < l; ++i) {
- var c = this.collisions[i];
- var pi = this.balls[c.i].center;
- var pj = this.balls[c.j].center;
-
- var dx = pj[0] - pi[0];
- var dy = pj[1] - pi[1];
- var norm = Math.sqrt(dx * dx + dy * dy);
-
- var r = [c.ammt * dx / norm / 2, c.ammt * dy / norm / 2];
-
- pi[0] -= r[0];
- pi[1] -= r[1];
- pj[0] += r[0];
- pj[1] += r[1];
- }
- }
-
- this.handleCollisions = function() {
- var l = this.wallCollisions.length;
- for (var i = 0; i < l; ++i) {
- var c = this.wallCollisions[i];
- var ball = this.balls[c.i];
- var v = ball.velocity;
- var w = ball.angularVelocity;
- var r1 = [-c.x, -c.y, 0];
- var r2 = [c.x, c.y, 0];
-
- var impulse = this.impulse(
- v, w, ball.mass, ball.angularInertia, r1,
- [0, 0, 0], [0, 0, 0], 1e100, 1e100, r2,
- r1, 0.99, 1, 1);
-
- this.applyImpulse(c.i, impulse, r1);
- }
-
- var l = this.collisions.length;
- for (var i = 0; i < l; ++i) {
- var c = this.collisions[i];
- var bi = this.balls[c.i];
- var bj = this.balls[c.j];
- var vi = bi.velocity;
- var wi = bi.angularVelocity;
- var vj = bj.velocity;
- var wj = bj.angularVelocity;
-
- var ri = this.math.normalize(this.math.subVector(bj.center, bi.center));
- var rj = this.math.negativeVector(ri);
-
- var impulse = this.impulse(
- vi, wi, bi.mass, bi.angularInertia, ri,
- vj, wj, bj.mass, bj.angularInertia, rj,
- ri, 0.99, .2, .1);
-
- this.applyImpulse(c.i, impulse, ri);
- this.applyImpulse(c.j, this.math.negativeVector(impulse), rj);
- }
- };
-
- this.randomOrientations = function() {
- for (var i = 0; i < 16; ++i) {
- this.balls[i].orientation =
- this.math.normalize([Math.random() - 0.5,
- Math.random() - 0.5,
- Math.random() - 0.5,
- Math.random() - 0.5]);
- }
- };
-
- this.impulse = function(v1, w1, m1, I1, r1,
- v2, w2, m2, I2, r2,
- N, e, u_s, u_d) {
- // Just to be safe, make N unit-length.
- N = this.math.normalize(N);
-
- // Vr is the relative velocity at the point of impact.
- // Vrn and Vrt are the normal and tangential parts of Vr.
- var Vr =
- this.math.subVector(
- this.math.addVector(this.math.cross(w2, r2), v2),
- this.math.addVector(this.math.cross(w1, r1), v1));
-
- var Vrn = this.math.mulScalarVector(this.math.dot(Vr, N), N);
- var Vrt = this.math.subVector(Vr, Vrn);
-
- var K = this.math.addMatrix(
- this.intertialTensor(m1, I1, r1), this.intertialTensor(m2, I2, r2));
- var Kinverse = this.math.inverse(K);
-
- // Compute the impulse assuming 0 tangential velocity.
- var j0 = this.math.mulMatrixVector(Kinverse,
- this.math.subVector(Vr, this.math.mulScalarVector(-e, Vrn)));
-
- // If j0 is in the static friction cone, we return that.
- // If the length of Vrt is 0, then we cannot normalize it,
- // so we return j0 in that case, too.
- var j0n = this.math.mulScalarVector(this.math.dot(j0, N), N);
- var j0t = this.math.subVector(j0, j0n);
-
- if (this.math.lengthSquared(j0t) <=
- u_s * u_s * this.math.lengthSquared(j0n) ||
- this.math.lengthSquared(Vrt) == 0.0) {
- return j0;
- }
-
- // Get a unit-length tangent vector by normalizing the tangent velocity.
- // The friction impulse acts in the opposite direction.
- var T = this.math.normalize(Vrt);
-
- // Compute the current impulse in the normal direction.
- var jn = this.math.dot(this.math.mulMatrixVector(Kinverse, Vr), N);
-
- // Compute the impulse assuming no friction.
- var js = this.math.mulMatrixVector(Kinverse,
- this.math.mulScalarVector(1 + e, Vrn));
-
- // Return the frictionless impulse plus the impulse due to friction.
- return this.math.addVector(js, this.math.mulScalarVector(-u_d * jn, T));
- };
-
- this.intertialTensor = function(m, I, r) {
- var a = r[0];
- var b = r[1];
- var c = r[2];
-
- return o3djs.math
- .makeMatrix3(1 / m + (b * b + c * c) / I, (-a * b) / I, (-a * c) / I,
- (-a * b) / I, 1 / m + (a * a + c * c) / I, (-b * c) / I,
- (-a * c) / I, (-b * c) / I, 1 / m + (a * a + b * b) / I);
- };
-
- this.applyImpulse = function(i, impulse, r) {
- var ball = this.balls[i];
- var v = ball.velocity;
- var w = ball.angularVelocity;
-
- // v += impulse / mass
- v[0] += impulse[0] / ball.mass;
- v[1] += impulse[1] / ball.mass;
-
- // w += r x impulse / angularInertia
- w[0] += (-r[2] * impulse[1]) / ball.angularInertia;
- w[1] += (impulse[0] * r[2]) / ball.angularInertia;
- w[2] += (r[0] * impulse[1] - r[1] * impulse[0]) / ball.angularInertia;
- };
-
- this.ballsImpactFloor = function() {
- for (var i = 0; i < 16; ++i) {
- var ball = this.balls[i];
- if (!ball.active)
- continue;
- var v = ball.velocity;
- v = [v[0], v[1], -0.1];
- var w = ball.angularVelocity;
-
- var impulse = this.impulse(
- v, w, ball.mass, ball.angularInertia, [0, 0, -1],
- [0, 0, 0], [0, 0, 0], 1e100, 1e100, [0, 0, 1],
- [0, 0, -1], 0.1, 0.1, 0.02);
-
- this.applyImpulse(i, impulse, [0, 0, -1]);
- }
- };
-
- this.ballsLoseEnergy = function() {
- for (var i = 0; i < 16; ++i) {
- var ball = this.balls[i];
- if (!ball.active)
- continue;
- var v = ball.velocity;
- var w = ball.angularVelocity;
-
- this.loseEnergy(v, 0.00004);
- this.loseEnergy(w, 0.00006);
- }
- };
-
- this.loseEnergy = function(v, epsilon) {
- var vLength = this.math.length(v);
- if (vLength < epsilon) {
- v[0] = 0;
- v[1] = 0;
- v[2] = 0;
- } else {
- var t = epsilon / vLength;
- v[0] -= t * v[0];
- v[1] -= t * v[1];
- v[2] -= t * v[2];
- }
- };
-};
-
-
-function vectorToQuaternion(r) {
- var theta = g_math.length(r);
- var stot = (theta < 1.0e-6)?1:(Math.sin(theta/2) / theta);
- return [stot * r[0], stot * r[1], stot * r[2], Math.cos(theta)];
-}
-
-
-CameraPosition = function() {
- this.center = [0, 0, 0];
- this.theta = 0;
- this.phi = 0;
- this.radius = 1;
-};
-
-
-CameraInfo = function() {
- this.lastX = 0;
- this.lastY = 0;
- this.position = new CameraPosition();
- this.targetPosition = new CameraPosition();
- this.vector_ = [0, 0, 0];
- this.lerpCoefficient = 1;
- this.startingTime = 0;
-
- this.begin = function(x, y) {
- this.lastX = x;
- this.lastY = y;
- };
-
- this.update = function(x, y) {
- this.targetPosition.theta -= (x - this.lastX) / 200;
- this.targetPosition.phi += (y - this.lastY) / 200;
- this.bound();
- this.lastX = x;
- this.lastY = y;
- };
-
- this.bound = function() {
- if (this.position.phi < 0.01) this.position.phi = 0.01;
- if (this.position.phi > Math.PI / 2 - 0.01)
- this.position.phi = Math.PI / 2 - 0.01;
-
- if (this.targetPosition.phi < 0.01) this.targetPosition.phi = 0.01;
- if (this.targetPosition.phi > Math.PI / 2 - 0.01)
- this.targetPosition.phi = Math.PI / 2 - 0.01;
- };
-
- this.getCurrentPosition = function() {
- var t = this.lerpCoefficient;
- t = 3 * t * t - 2 * t * t * t;
- var a = this.position;
- var b = this.targetPosition;
-
- return {center: [(1 - t) * a.center[0] + t * b.center[0],
- (1 - t) * a.center[1] + t * b.center[1],
- (1 - t) * a.center[2] + t * b.center[2]],
- radius: (1 - t) * a.radius + t * b.radius,
- theta: (1 - t) * a.theta + t * b.theta,
- phi: (1 - t) * a.phi + t * b.phi};
- }
-
- this.getEyeAndTarget = function(eye, target) {
- var p = this.getCurrentPosition();
-
- var cosPhi = Math.cos(p.phi);
- target[0] = p.center[0];
- target[1] = p.center[1];
- target[2] = p.center[2];
- eye[0] = target[0] + p.radius * cosPhi * Math.cos(p.theta);
- eye[1] = target[1] + p.radius * cosPhi * Math.sin(p.theta);
- eye[2] = target[2] + p.radius * Math.sin(p.phi);
- };
-
- this.goTo = function(center, theta, phi, radius) {
- if (!center) {
- center = this.targetPosition.center;
- }
- if (!theta) {
- theta = this.targetPosition.theta;
- }
- if (!phi) {
- phi = this.targetPosition.phi;
- }
- if (!radius) {
- radius = this.targetPosition.radius;
- }
-
- var p = this.getCurrentPosition();
-
- this.position.center[0] = p.center[0];
- this.position.center[1] = p.center[1];
- this.position.center[2] = p.center[2];
- this.position.theta = p.theta;
- this.position.phi = p.phi;
- this.position.radius = p.radius;
-
- this.targetPosition.center = center;
- this.targetPosition.theta = theta;
- this.targetPosition.phi = phi;
- this.targetPosition.radius = radius;
-
- this.lerpCoefficient = 0;
- this.startingTime = g_clock;
-
- var k = 3 * Math.PI / 2;
- this.position.theta =
- myMod(this.position.theta + k, 2.0 * Math.PI) - k;
- this.targetPosition.theta =
- myMod(this.targetPosition.theta + k, 2.0 * Math.PI) - k;
- };
-
- this.backUp = function() {
- var c = this.targetPosition.center;
- this.goTo([c[0], c[1], c[2]],
- null,
- Math.PI / 6,
- 100);
- };
-
- this.zoomToPoint = function(center) {
- this.goTo(center,
- this.targetPosition.theta,
- Math.PI / 20,
- 20);
- };
-
- this.updateClock = function() {
- this.lerpCoefficient = Math.min(1, g_clock - this.startingTime);
- if (this.lerpCoefficient == 1) {
- this.position.center[0] = this.targetPosition.center[0];
- this.position.center[1] = this.targetPosition.center[1];
- this.position.center[2] = this.targetPosition.center[2];
- this.position.theta = this.targetPosition.theta;
- this.position.phi = this.targetPosition.phi;
- this.position.radius = this.targetPosition.radius;
- }
- };
-
- this.lookingAt = function(center) {
- return this.targetPosition.center == center;
- }
-
- this.goTo([0, 0, 0],
- -Math.PI / 2,
- Math.PI / 6,
- 140);
-};
-
-var g_cameraInfo = new CameraInfo();
-var g_dragging = false;
-
-function startDragging(e) {
- g_cameraInfo.begin(e.x, e.y);
- g_dragging = true;
-}
-
-function drag(e) {
- if (g_dragging) {
- g_cameraInfo.update(e.x, e.y);
- updateContext();
- }
-}
-
-function stopDragging(e) {
- if (g_dragging) {
- g_cameraInfo.update(e.x, e.y);
- updateContext();
- }
- g_dragging = false;
-}
-
-/**
- * Initializes global variables, positions eye, draws shapes.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function main(clientElements) {
- initPhysics();
- initGlobals(clientElements);
- initRenderGraph();
- updateContext();
- initMaterials();
- initShadowPlane();
- initTable();
- initHud();
-
- rack(8);
-
- setRenderCallback();
- registerEventCallbacks();
-}
-
-
-/**
- * Registers event handlers.
- */
-function registerEventCallbacks() {
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', startDragging);
- o3djs.event.addEventListener(g_o3dElement, 'mousemove', drag);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', stopDragging);
-
- o3djs.event.addEventListener(g_o3dElement, 'keypress', keyPressed);
- o3djs.event.addEventListener(g_o3dElement, 'keyup', keyUp);
- o3djs.event.addEventListener(g_o3dElement, 'keydown', keyDown);
-
- o3djs.event.addEventListener(g_o3dElement, 'wheel', scrollWheel);
-}
-
-
-/**
- * Creates the client area.
- */
-function initClient() {
- o3djs.webgl.makeClients(main);
-}
-
-
-/**
- * Initializes global variables and libraries.
- */
-function initGlobals(clientElements) {
- g_o3dElement = clientElements[0];
- window.g_client = g_client = g_o3dElement.client;
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_quat = o3djs.quaternions;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-}
-
-
-/**
- * Initalizes the render graph.
- */
-function initRenderGraph() {
- // Need separate roots for the table, shadow and heads-up display.
- g_tableRoot = g_pack.createObject('Transform');
- g_tableRoot.parent = g_client.root;
- g_shadowRoot = g_pack.createObject('Transform');
- g_shadowRoot.parent = g_client.root;
- g_hudRoot = g_pack.createObject('Transform');
- g_hudRoot.parent = g_client.root;
-
- // Create the render graph for a view.
- var viewRoot = g_pack.createObject('RenderNode');
- viewRoot.priority = 1;
- if (!SHADOWPOV)
- viewRoot.parent = g_client.renderGraphRoot;
-
- var shadowPassRoot = g_pack.createObject('RenderNode');
- shadowPassRoot.priority = 0;
- shadowPassRoot.parent = g_client.renderGraphRoot;
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_tableRoot,
- viewRoot,
- [0, 0, 0, 1]);
-
- var hudRenderRoot = g_client.renderGraphRoot;
- if (SHADOWPOV)
- hudRenderRoot = null;
-
- g_hudViewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_hudRoot,
- hudRenderRoot);
-
- // Make sure the hud gets drawn after the 3d scene.
- g_hudViewInfo.root.priority = g_viewInfo.root.priority + 1;
-
- // Turn off clearing the color for the hud.
- g_hudViewInfo.clearBuffer.clearColorFlag = false;
-
- // Set culling to none so we can flip images using rotation or negative scale.
- g_hudViewInfo.zOrderedState.getStateParam('CullMode').value =
- g_o3d.State.CULL_NONE;
- g_hudViewInfo.zOrderedState.getStateParam('ZWriteEnable').value = false;
-
- // Create an orthographic matrix for 2d stuff in the HUD.
- g_hudViewInfo.drawContext.projection = g_math.matrix4.orthographic(
- 0, 1, 0, 1, -10, 10);
-
- g_hudViewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 0, 1], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- // Create the texture required for the render-target.
- g_shadowTexture = g_pack.createTexture2D(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT,
- g_o3d.Texture.XRGB8, 1, true);
-
- var renderSurface = g_shadowTexture.getRenderSurface(0);
-
- var depthSurface = g_pack.createDepthStencilSurface(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT);
-
- var renderSurfaceSet = g_pack.createObject('RenderSurfaceSet');
- renderSurfaceSet.renderSurface = renderSurface;
- renderSurfaceSet.renderDepthStencilSurface = depthSurface;
- renderSurfaceSet.parent = shadowPassRoot;
-
- var shadowPassParent = renderSurfaceSet;
- if (SHADOWPOV)
- shadowPassParent = g_client.renderGraphRoot;
-
- g_shadowPassViewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_shadowRoot,
- shadowPassParent,
- [0, 0, 0, 1]);
-
- g_shadowPassViewInfo.zOrderedState.
- getStateParam('ZComparisonFunction').value =
- o3djs.base.o3d.State.CMP_ALWAYS;
-}
-
-function handleResizeEvent(event) {
- updateContext();
-}
-
-/**
- * Sets up reasonable view and projection matrices.
- */
-function updateContext() {
- // Set up a perspective transformation for the projection.
- g_shadowPassViewInfo.drawContext.projection =
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree frustum.
- g_client.width / g_client.height, // Aspect ratio.
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set the view transformation.
- var eye = [0, 0, 0];
- var target = [0, 0, 0];
- g_cameraInfo.getEyeAndTarget(eye, target);
- g_shadowPassViewInfo.drawContext.view =
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(eye, target, [0, 0, 1]);
-
- updateMaterials();
-}
-
-
-function setOptionalParam(material, name, value) {
- var param = material.getParam(name);
- if (param) {
- param.value = value;
- }
-}
-
-
-function initMaterials() {
- g_materials = {
- 'solid':{},
- 'felt':{},
- 'wood':{},
- 'cushion':{},
- 'billiard':{},
- 'ball':{},
- 'shadowPlane':{}};
-
- var vertexShaderString = document.getElementById('vshader').value;
- var pixelShaderString = document.getElementById('pshader').value;
-
- for (name in g_materials) {
- var material = g_pack.createObject('Material');
- g_materials[name] = material;
- var effect = g_pack.createObject('Effect');
-
- var mainString =
- 'void main() {' +
- ' gl_FragColor = ' + name + 'PixelShader();' +
- '}';
-
- effect.loadVertexShaderFromString(vertexShaderString);
- effect.loadPixelShaderFromString(pixelShaderString + mainString);
-
- material.effect = effect;
- effect.createUniformParameters(material);
- material.drawList = g_viewInfo.performanceDrawList;
-
- var eye = [0, 0, 0];
- var target = [0, 0, 0];
- g_cameraInfo.getEyeAndTarget(eye, target);
-
- setOptionalParam(material, 'factor', 2 / g_tableWidth);
- setOptionalParam(material, 'lightWorldPosition', g_light);
- setOptionalParam(material, 'eyeWorldPosition', eye);
- }
-
- g_solidMaterial = g_materials['solid'];
- g_solidMaterial.drawList = g_hudViewInfo.zOrderedDrawList;
-
- g_materials['shadowPlane'].drawList = g_shadowPassViewInfo.zOrderedDrawList;
-
- g_shadowSampler = g_pack.createObject('Sampler');
- g_shadowSampler.texture = g_shadowTexture;
- g_materials['felt'].getParam('textureSampler').value = g_shadowSampler;
-
- o3djs.io.loadBitmaps(g_pack,
- o3djs.util.getAbsoluteURI('../assets/poolballs.png'),
- finishLoadingBitmaps);
-}
-
-
-function updateMaterials() {
- for (name in g_materials) {
- var eye = [0, 0, 0];
- var target = [0, 0, 0];
- g_cameraInfo.getEyeAndTarget(eye, target);
- setOptionalParam(g_materials[name], 'eyeWorldPosition', eye);
- }
-}
-
-
-/**
- * Gets called back when the bitmap has loaded.
- */
-function finishLoadingBitmaps(bitmaps, exception) {
- var bitmap = bitmaps[0];
-
- bitmap.flipVertically();
-
- var width = bitmaps[0].width / 4;
- var height = bitmaps[0].height / 4;
- var levels = o3djs.texture.computeNumLevels(width, height);
-
- for (var i = 0; i < 16; ++i) {
- g_ballTextures[i] = g_pack.createTexture2D(
- width, height, g_o3d.Texture.XRGB8, 0, false);
- g_ballTextureSamplers[i] = g_pack.createObject('Sampler');
- g_ballTextureSamplers[i].texture = g_ballTextures[i];
- }
-
- for (var i = 0; i < 16; ++i) {
- var u = i % 4;
- var v = Math.floor(i / 4);
- g_ballTextures[i].drawImage(bitmap,
- 0, u * width, v * height, width, height,
- 0, 0, 0, width, height);
- g_ballTextures[i].generateMips(0, levels - 1);
- }
-
- for (var i = 0; i < 16; ++i) {
- g_ballTextureSamplerParams[i].value = g_ballTextureSamplers[i];
- }
-}
-
-
-function flatMesh(material, vertexPositions, faceIndices) {
- var vertexInfo = o3djs.primitives.createVertexInfo();
- var positionStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.POSITION);
- var normalStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.NORMAL);
-
- var vertexCount = 0;
- for (var i = 0; i < faceIndices.length; ++i) {
- var face = faceIndices[i];
-
- var n = g_math.normalize(g_math.cross(
- g_math.subVector(vertexPositions[face[1]],
- vertexPositions[face[0]]),
- g_math.subVector(vertexPositions[face[2]],
- vertexPositions[face[0]])));
-
- var faceFirstIndex = vertexCount;
-
- for (var j = 0; j < face.length; ++j) {
- var v = vertexPositions[face[j]];
- positionStream.addElement(v[0], v[1], v[2]);
- normalStream.addElement(n[0], n[1], n[2]);
- ++vertexCount;
- }
-
- for (var j = 1; j < face.length - 1; ++j)
- vertexInfo.addTriangle(faceFirstIndex,
- faceFirstIndex + j,
- faceFirstIndex + j + 1);
- }
-
- return vertexInfo.createShape(g_pack, material);
-}
-
-function arc(center, radius, start, end, steps) {
- var r = [];
-
- for (var i = 0; i <= steps; ++i) {
- var theta = start + i * (end - start) / steps;
- r.push([center[0] + radius * Math.cos(theta),
- center[1] + radius * Math.sin(theta)]);
- }
- return r;
-}
-
-function myreverse(l) {
- var r = [l[0]];
- var n = l.length;
- for (var i = 0; i < n - 1; ++i) {
- r.push(l[n - i - 1]);
- }
- return r;
-}
-
-function flip(a, b) {
- r = [];
- for (var i = 0; i < a.length; ++i)
- r.push([b[0] * a[i][0], b[1] * a[i][1]]);
- if (b[0] * b[1] < 0)
- return myreverse(r);
- return r;
-}
-
-
-var g_pocketRadius = 2.3;
-var g_woodBreadth = 3.2;
-var g_tableThickness = 5;
-var g_tableWidth = 45;
-var g_woodHeight = 1.1;
-
-function initTable() {
- var feltMaterial = g_materials.felt;
- var woodMaterial = g_materials.wood;
- var cushionMaterial = g_materials.cushion;
- var billiardMaterial = g_materials.billiard;
-
- var shapes = [];
-
- var root = g_pack.createObject('Transform');
- root.parent = g_tableRoot;
- var tableRoot = g_pack.createObject('Transform');
- tableRoot.translate(0, 0, -g_tableThickness / 2 - 1);
- var cushionRoot = g_pack.createObject('Transform');
- var ballRoot = g_pack.createObject('Transform');
- tableRoot.parent = root;
- cushionRoot.parent = tableRoot;
- ballRoot.parent = root;
-
- var root2 = Math.sqrt(2);
-
- var scaledPocketRadius = 2 * g_pocketRadius / g_tableWidth;
- var scaledWoodBreadth = 2 * g_woodBreadth / g_tableWidth;
-
- var felt_polygon_A =
- [[0, -2], [0, (1 + .5 * root2) * scaledPocketRadius - 2]].concat(
- arc([.5 * root2 * scaledPocketRadius - 1,
- .5 * root2 * scaledPocketRadius - 2],
- scaledPocketRadius, Math.PI / 2, -.25 * Math.PI, 15));
-
- var felt_polygon_B =
- [[-1, (1 + .5 * root2) * scaledPocketRadius - 2]].concat(
- arc([.5 * root2 * scaledPocketRadius - 1,
- .5 * root2 * scaledPocketRadius - 2],
- scaledPocketRadius, .75 * Math.PI, .5 * Math.PI, 15));
-
- var felt_polygon_C =
- [[0, (1 + .5 * root2) * scaledPocketRadius - 2], [0, 0]].concat(
- arc([-1, 0], scaledPocketRadius, 0, -.5 * Math.PI, 15)).concat(
- [[-1, (1 + .5 * root2) * scaledPocketRadius - 2]]);
-
- var wood_polygon =
- [[-scaledWoodBreadth - 1, -scaledWoodBreadth - 2],
- [0, -scaledWoodBreadth - 2],
- [0, -2]].concat(
- arc([.5 * root2 * scaledPocketRadius - 1,
- .5 * root2 * scaledPocketRadius - 2],
- scaledPocketRadius,
- -.25 * Math.PI,
- -1.25 * Math.PI,
- 15)).concat(
- arc([-1, 0],
- scaledPocketRadius,
- 1.5 * Math.PI,
- Math.PI,
- 15)).concat([[-scaledWoodBreadth - 1, 0]]);
-
- var m = [[g_tableWidth / 2, 0],[0,g_tableWidth / 2]];
- felt_polygon_A = g_math.generalizedMulMatrixMatrix(felt_polygon_A, m);
- felt_polygon_B = g_math.generalizedMulMatrixMatrix(felt_polygon_B, m);
- felt_polygon_C = g_math.generalizedMulMatrixMatrix(felt_polygon_C, m);
- wood_polygon = g_math.generalizedMulMatrixMatrix(wood_polygon, m);
-
- var felt_polygons = [];
- var wood_polygons = [];
- for (var i = -1; i < 2; i+=2) {
- for (var j = -1; j < 2; j+=2) {
- felt_polygons.push(flip(felt_polygon_A, [i, j]),
- flip(felt_polygon_B, [i, j]),
- flip(felt_polygon_C, [i, j]));
- wood_polygons.push(flip(wood_polygon, [i, j]));
- }
- }
-
- for (var i = 0; i < felt_polygons.length; ++i) {
- shapes.push(o3djs.primitives.createPrism(
- g_pack,
- feltMaterial,
- felt_polygons[i], g_tableThickness));
- }
-
- for (var i = 0; i < wood_polygons.length; ++i) {
- shapes.push(o3djs.primitives.createPrism(
- g_pack,
- woodMaterial,
- wood_polygons[i], g_tableThickness + 2 * g_woodHeight));
- }
-
- for (var i = 0; i < 1; i++) {
- var t = g_pack.createObject('Transform');
- t.parent = tableRoot;
- for (var j = 0; j < shapes.length; ++j) {
- t.addShape(shapes[j]);
- }
- }
-
- var cushionHeight = 1.1 * g_woodHeight;
- var cushionUp = g_tableThickness / 2;
- var cushionProp = .9 * g_woodHeight;
- var cushionDepth = g_tableWidth;
- var cushionBreadth = g_pocketRadius;
- var cushionSwoop = g_pocketRadius;
-
- var angles = [0, Math.PI/2, Math.PI, Math.PI, 3 * Math.PI / 2, 0];
- var translations = g_math.generalizedMulMatrixMatrix(
- [[-1, -1, 0], [0, -2, 0], [1, -1, 0], [1, 1, 0], [0, 2, 0], [-1, 1, 0]],
- [[g_tableWidth / 2, 0, 0], [0, g_tableWidth / 2, 0], [0, 0, 1]]);
- var shortenings =
- [[g_pocketRadius, g_pocketRadius*root2],
- [g_pocketRadius*root2, g_pocketRadius*root2],
- [g_pocketRadius*root2, g_pocketRadius]];
-
- var billiardThickness = 0.1;
- var billiardBreadth = 1;
- var billiardDepth = .309;
- var billiardOut = -g_woodBreadth / 2;
- var billiardSpacing = g_tableWidth / 4;
-
- var billiards = [];
-
- for (var i = -1; i < 2; ++i) {
- billiards.push(o3djs.primitives.createPrism(
- g_pack,
- billiardMaterial,
- [[billiardOut + billiardBreadth / 2, i * billiardSpacing],
- [billiardOut, billiardDepth + i * billiardSpacing],
- [billiardOut - billiardBreadth / 2, i * billiardSpacing],
- [billiardOut, -billiardDepth + i * billiardSpacing]],
- g_tableThickness + 2 * g_woodHeight + billiardThickness));
- }
-
- for (var i = 0; i < 6; ++i) {
- var backShortening = shortenings[i % 3][1];
- var frontShortening = shortenings[i % 3][0];
-
- var vertexPositions = [
- [0, -cushionDepth / 2 + backShortening, cushionUp],
- [cushionBreadth, -cushionDepth / 2 + cushionSwoop + backShortening,
- cushionUp + cushionProp],
- [cushionBreadth, -cushionDepth / 2 + cushionSwoop + backShortening,
- cushionUp + cushionHeight],
- [0, -cushionDepth / 2 + backShortening, cushionUp + cushionHeight],
- [0, cushionDepth / 2 - frontShortening, cushionUp],
- [cushionBreadth, cushionDepth / 2 - cushionSwoop - frontShortening,
- cushionUp + cushionProp],
- [cushionBreadth, cushionDepth / 2 - cushionSwoop - frontShortening,
- cushionUp + cushionHeight],
- [0, cushionDepth / 2 - frontShortening, cushionUp + cushionHeight]
- ];
-
- var faceIndices = [
- [0, 1, 2, 3], // front
- [7, 6, 5, 4], // back
- [1, 0, 4, 5], // bottom
- [2, 1, 5, 6], // right
- [3, 2, 6, 7], // top
- [0, 3, 7, 4] // left
- ];
-
- var cushion = flatMesh(cushionMaterial, vertexPositions, faceIndices);
- shapes.push(cushion);
-
- var t = g_pack.createObject('Transform');
- t.localMatrix = g_math.mulMatrixMatrix(
- g_math.matrix4.rotationZ(angles[i]),
- g_math.matrix4.translation(translations[i]));
-
- t.parent = cushionRoot;
- t.addShape(cushion);
- for (var j = 0; j < billiards.length; ++j)
- t.addShape(billiards[j]);
- }
-
- for (var j = 0; j < billiards.length; ++j)
- shapes.push(billiards[j]);
-
- var ball =
- o3djs.primitives.createSphere(g_pack, g_materials.ball, 1, 50, 70);
- shapes.push(ball);
-
- for(var i = 0; i < 16; ++i) {
- var transform = g_pack.createObject('Transform');
- g_ballTextureSamplerParams[i] =
- transform.createParam('textureSampler', 'ParamSampler');
- transform.parent = ballRoot;
- g_ballTransforms[i] = transform;
- transform.addShape(ball);
- }
-}
-
-
-function initHud() {
- var barT1 = g_pack.createObject('Transform');
- g_barScaling = g_pack.createObject('Transform');
- var barT2 = g_pack.createObject('Transform');
- var backT2 = g_pack.createObject('Transform');
-
- g_barRoot = barT1;
- barT1.parent = g_hudRoot;
- g_barScaling.parent = barT1;
- barT2.parent = g_barScaling;
- backT2.parent = barT1;
-
- var plane = o3djs.primitives.createPlane(
- g_pack, g_solidMaterial, 1, 1, 1, 1,
- o3djs.math.makeMatrix4(
- 1, 0, 0, 0,
- 0, 0, 1, 0,
- 0,-1, 0, 0,
- 0, 0, 0, 1));
-
- var backPlane = o3djs.primitives.createPlane(
- g_pack, g_solidMaterial, 1, 1, 1, 1,
- o3djs.math.makeMatrix4(
- 1, 0, 0, 0,
- 0, 0, 1, 0,
- 0,-1, 0, 0,
- 0, 0, 0, 1));
-
- barT2.addShape(plane);
- //backT2.addShape(backPlane);
-
- barT1.translate([0.05, 0.05, 0]);
- barT1.scale([0.05, 0.9, 1]);
- g_barScaling.localMatrix = g_math.matrix4.scaling([1, 0.0, 1]);
- barT2.translate([.5, .5, 0]);
- backT2.translate([.5, .5, 0.1]);
-}
-
-function setBarScale(t) {
- g_barScaling.localMatrix = g_math.matrix4.scaling([1, t, 1]);
-}
-
-
-function onrender(event) {
- g_clock += event.elapsedTime;
-
- g_queueClock += event.elapsedTime;
- var clock = g_queueClock;
-
- if (g_queue.length) {
- if (eval(g_queue[0].condition)) {
- var action = g_queue[0].action;
- for (var i = 0; i < g_queue.length - 1; ++i) {
- g_queue[i] = g_queue[i + 1];
- }
- g_queue.pop();
- eval(action);
- g_queueClock = 0;
- }
- }
-
- if (g_cameraInfo) {
- g_cameraInfo.updateClock();
- }
-
- if (g_physics) {
- if (g_physics.someBallsMoving()) {
- g_physics.step();
- g_physics.stopSlowBalls();
- } else {
- if (g_rolling) {
- g_rolling = false;
- var cueBall = g_physics.balls[0];
- if (g_cameraInfo.lookingAt(cueBall.center))
- g_barRoot.visible = true;
- if (!cueBall.active) {
- ballOn(0);
- cueBall.center[0] = 0;
- cueBall.center[1] = 0;
- cueBall.center[2] = 0;
- g_physics.boundCueBall();
- }
- }
- }
- }
-
- updateContext();
-}
-
-
-function setRenderCallback() {
- g_client.setRenderCallback(onrender);
-}
-
-
-function initPhysics() {
- g_physics = new pool.Physics();
- g_physics.math = o3djs.math;
- g_physics.quat = o3djs.quaternions;
-
- g_physics.left = -g_tableWidth / 2 + g_pocketRadius + 1;
- g_physics.right = g_tableWidth / 2 - g_pocketRadius - 1;
- g_physics.top = g_tableWidth - g_pocketRadius - 1;
- g_physics.bottom = - g_tableWidth + g_pocketRadius + 1;
-
- var w = g_tableWidth / 2;
- var r = g_pocketRadius;
- var root2 = Math.sqrt(2);
- var x = .5 * root2 * r - w;
- var y = .5 * root2 * r - 2 * w;
-
- g_physics.pocketCenters = [
- [w, 0], [-w, 0], [x, y], [-x, y], [x, -y], [-x, -y]];
-
- g_physics.pocketRadius = g_pocketRadius;
- g_physics.tableWidth = g_tableWidth;
- g_physics.initWalls();
-}
-
-
-function rack(game, yOffset, cueYOffset) {
- var root3 = Math.sqrt(3);
-
- if (!yOffset)
- yOffset = 6.0 * g_tableWidth / 12.0;
-
- if (!cueYOffset)
- cueYOffset = -g_tableWidth / 2;
-
- for (var i = 0; i < 16; ++i)
- ballOn(i);
-
- g_physics.stopAllBalls();
-
- switch(game) {
- case 8:
- placeBall(1, 0, 0 + yOffset);
- placeBall(9, -1, root3 + yOffset);
- placeBall(2, 1, root3 + yOffset);
- placeBall(10, 2, 2 * root3 + yOffset);
- placeBall(8, 0, 2 * root3 + yOffset);
- placeBall(3, -2, 2 * root3 + yOffset);
- placeBall(11, -3, 3 * root3 + yOffset);
- placeBall(4, -1, 3 * root3 + yOffset);
- placeBall(12, 1, 3 * root3 + yOffset);
- placeBall(5, 3, 3 * root3 + yOffset);
- placeBall(13, 4, 4 * root3 + yOffset);
- placeBall(6, 2, 4 * root3 + yOffset);
- placeBall(14, 0, 4 * root3 + yOffset);
- placeBall(15, -2, 4 * root3 + yOffset);
- placeBall(7, -4, 4 * root3 + yOffset);
-
- placeBall(0, 0, cueYOffset);
- break;
-
- case 9:
- placeBall(1, 0, 0 + yOffset);
- placeBall(2, 1, root3 + yOffset);
- placeBall(3, -1, root3 + yOffset);
- placeBall(9, 0, 2 * root3 + yOffset);
- placeBall(4, 2, 2 * root3 + yOffset);
- placeBall(5, -2, 2 * root3 + yOffset);
- placeBall(6, 1, 3 * root3 + yOffset);
- placeBall(7, -1, 3 * root3 + yOffset);
- placeBall(8, 0, 4 * root3 + yOffset);
-
- for (var i = 10; i < 16; ++i) {
- placeBall(i, 0, 0, -5);
- ballOff(i);
- }
-
- placeBall(0, 0, cueYOffset);
- break;
-
- case 0:
- for (var i = 1; i < 16; ++i) {
- placeBall(i, 0, 0, -5);
- ballOff(i);
- }
- placeBall(0, 0, cueYOffset);
- break;
-
- case 1:
- for (var i = 1; i < 16; ++i) {
- placeBall(i, 0, 0, -5);
- ballOff(i);
- }
- placeBall(0, 0, cueYOffset);
- placeBall(1, -g_tableWidth/4, cueYOffset/2);
- placeBall(2, -3*g_tableWidth/8, cueYOffset/4);
- placeBall(3, g_tableWidth/4, 0);
-
- ballOn(0);
- ballOn(1);
- ballOn(2);
- ballOn(3);
- break;
- }
-
- g_physics.randomOrientations();
- g_physics.placeBalls();
- g_cameraInfo.goTo([0, 0, 0], -Math.PI / 2, Math.PI / 6, 140);
-}
-
-
-function ballOn(i) {
- g_physics.balls[i].active = true;
- g_physics.balls[i].sunkInPocket = -1;
- g_ballTransforms[i].visible = true;
- g_shadowOnParams[i].value = 1;
-}
-
-
-function ballOff(i) {
- g_physics.balls[i].active = false;
- g_ballTransforms[i].visible = false;
- g_shadowOnParams[i].value = 0;
-}
-
-
-function placeBall(i, x, y, z, q) {
- if (!q) {
- q = [0, 0, 0, 1];
- }
- if (!z) {
- z = 0;
- }
- g_physics.balls[i].center[0] = x;
- g_physics.balls[i].center[1] = y;
- g_physics.balls[i].center[2] = z;
- g_ballTransforms[i].localMatrix = g_math.matrix4.translation([x, y, z]);
- g_ballTransforms[i].quaternionRotate(q);
- g_centers[i].value = [x, y];
-}
-
-
-function initShadowPlane() {
- var root = g_pack.createObject('Transform');
- root.parent = g_shadowRoot;
-
- var plane = o3djs.primitives.createPlane(g_pack,
- g_materials.shadowPlane,
- g_tableWidth,
- g_tableWidth * 2,
- 1,
- 1);
- root.translate([0, 0, -1]);
- root.rotateX(Math.PI / 2);
-
- for (var i = 0; i < 16; ++i) {
- var transform = g_pack.createObject('Transform');
- transform.parent = root;
- g_centers.push(transform.createParam('ballCenter', 'ParamFloat2'));
- g_shadowOnParams[i] =
- transform.createParam('shadowOn', 'ParamFloat');
- g_shadowOnParams[i].value = 1;
- transform.addShape(plane);
- }
-}
-
-
-// To avoid problem where user just taps space bar instead of holding for
-// more thrust: If the user doesn't hold the button down for a few ticks
-// showing 'seriousness' the stroke doesn't take.
-var g_seriousness = 0;
-
-var g_shooting_timers = [];
-
-
-function computeShot(i, j, cueCenter, objectCenter, pocketCenter) {
- // The vector from the object ball to the pocket, I'm calling "second".
- // The vector from the cue ball to the "ghost ball" behind the object
- // ball I'm calling "first"
- var secondX = pocketCenter[0] - objectCenter[0];
- var secondY = pocketCenter[1] - objectCenter[1];
- var secondDistance = Math.sqrt(secondX * secondX + secondY * secondY);
-
- var toPocket = [secondX / secondDistance, secondY / secondDistance];
- var toObject =
- [objectCenter[0] - cueCenter[0], objectCenter[0] - cueCenter[0]];
- var d = Math.sqrt(toObject[0] * toObject[0] + toObject[1] * toObject[1]);
- toObject = [toObject[0] / d, toObject[1] / d];
-
- // Cut correction.
- var cc = (toObject[0] * toPocket[0] + toObject[1] * toPocket[1]);
- cc = cc > 0.8 ? .4 : 0 ;
-
- var cut = [(2.0 + cc) * toPocket[0], (2.0 + cc) * toPocket[1]];
- var target = [objectCenter[0] - cut[0], objectCenter[1] - cut[1]];
-
- var firstX = target[0] - cueCenter[0];
- var firstY = target[1] - cueCenter[1];
- var firstDistance = Math.sqrt(firstX * firstX + firstY * firstY);
-
- var cutAmmount = 1.0 - (firstX * secondX + firstY * secondY) /
- (firstDistance * secondDistance);
-
- var power = 0.12 * (firstDistance + secondDistance / (1.01-cutAmmount)) /
- g_tableWidth;
-
- var difficulty = cutAmmount * cutAmmount - 0.5 / (1 + secondDistance/2);
-
- if (difficulty < 1) {
- // Determine if the shot is occluded.
- var walls = [
- {p:cueCenter, q:target},
- {p:objectCenter, q:pocketCenter}
- ];
-
- var collisions = [];
- g_physics.computeWallNormals(walls);
- g_physics.collideWithWalls(walls, collisions, 1.99);
- if (collisions.length > 2)
- difficulty += 10;
- }
-
- return {target: target,
- power: Math.min(1, Math.max(0.1, power)),
- difficulty: difficulty};
-}
-
-
-function cueNewShot(opt_power) {
- g_queue.push(
- {condition: 'clock > 1',
- action: 'g_cameraInfo.zoomToPoint(g_physics.balls[0].center);'});
-
- var cue = g_physics.balls[0];
-
- var current = null;
-
- var objectBalls = [];
-
- for (var i = 1; i < 8; ++i) {
- var ball = g_physics.balls[i];
- if (ball.active) {
- objectBalls.push(ball);
- }
- }
-
- var eight = g_physics.balls[i];
- if (objectBalls.length == 0 && eight.active) {
- objectBalls.push(eight);
- }
-
- for (var i = 0; i < objectBalls.length; ++i) {
- var ball = objectBalls[i];
-
- for (var j = 0; j < g_physics.pocketCenters.length; ++j) {
- var pocketCenter = g_physics.pocketCenters[j];
- pocketCenter = [pocketCenter[0], pocketCenter[1]];
- var k = g_pocketRadius;
- if (pocketCenter[0] > 1)
- pocketCenter[0] -= k;
- if (pocketCenter[0] < -1)
- pocketCenter[0] += k;
- if (pocketCenter[1] > 1)
- pocketCenter[1] -= k;
- if (pocketCenter[1] < -1)
- pocketCenter[1] += k;
- var shot = computeShot(i, j, cue.center, ball.center, pocketCenter);
- if (!current || shot.difficulty < current.difficulty)
- current = shot;
- }
- }
-
- if (current) {
- var theta = Math.atan2(cue.center[1] - current.target[1],
- cue.center[0] - current.target[0]);
- var power = current.power;
- if (opt_power)
- power = opt_power;
-
- g_queue.push(
- {condition: 'true',
- action: 'g_cameraInfo.goTo(null, ' + theta + ', null, 0);'});
-
- g_queue.push(
- {condition: 'clock > 1.5',
- action: 'startShooting();'});
-
- g_queue.push(
- {condition: 'g_physics.speedFactor >= ' + power,
- action: 'g_physics.speedFactor = ' + power +
- '; finishShooting();'});
-
- g_queue.push(
- {condition: '!(g_shooting || g_rolling)',
- action: 'cueNewShot();'});
- }
-}
-
-
-var g_phi = 0.0;
-
-function cueNewTestShot() {
- var cue = g_physics.balls[0];
-
- placeBall(0, 0, -20);
- placeBall(1, 0, 0);
-
- ballOn(0);
- ballOn(1);
-
- var current = {target: [0, 0], power: 0.1};
-
- var phi = g_phi;
- g_phi += 0.1;
- current.target[0] = - 2.0 * Math.cos(phi);
- current.target[1] = - 2.0 * Math.sin(phi);
-
- if (current) {
- var theta = Math.atan2(cue.center[1] - current.target[1],
- cue.center[0] - current.target[0]);
-
- var power = current.power;
-
- g_queue.push(
- {condition: 'true',
- action: 'g_cameraInfo.goTo(null, ' + theta + ', null, 0);'});
-
- g_queue.push(
- {condition: 'clock > 1.5',
- action: 'startShooting();'});
-
- g_queue.push(
- {condition: 'g_physics.speedFactor >= ' + power,
- action: 'g_physics.speedFactor = ' + power +
- '; finishShooting();'});
-
- g_queue.push(
- {condition: '!(g_shooting || g_rolling)',
- action: 'printResult(' + phi + '); cueNewTestShot();'});
- }
-}
-
-
-function startShooting() {
- g_shooting = true;
- g_shooting_timers.push(
- setInterval('increaseFactor()', 1000.0 / 60.0));
-}
-
-
-function increaseFactor() {
- g_physics.speedFactor += 0.01;
- setBarScale(g_physics.speedFactor);
- if (g_physics.speedFactor > 1)
- g_physics.speedFactor = 1;
-}
-
-
-function finishShooting() {
- while (g_shooting_timers.length > 0)
- clearTimeout(g_shooting_timers.pop())
- if (g_physics.speedFactor > 0.0) {
- var eye = [0, 0, 0];
- var target = [0, 0, 0];
- g_cameraInfo.getEyeAndTarget(eye, target);
- var dx = target[0] - eye[0];
- var dy = target[1] - eye[1];
- var norm = Math.sqrt(dx * dx + dy * dy);
- g_physics.impartSpeed(0, [dx / norm, dy / norm]);
- g_cameraInfo.backUp();
- g_rolling = true;
- g_barRoot.visible = false;
- }
- g_physics.speedFactor = 0;
- g_seriousness = 0;
- setBarScale(g_physics.speedFactor);
- g_shooting = false;
-}
-
-
-function keyUp(event) {
- switch (event.keyCode) {
- case 32:
- finishShooting();
- break;
- }
-}
-
-function keyDown(event) {
- switch (event.keyCode) {
- }
-}
-
-function zoomIn() {
- g_cameraInfo.targetPosition.radius *= 0.9;
-}
-
-function zoomOut() {
- g_cameraInfo.targetPosition.radius /= 0.9;
-}
-
-function scrollWheel(event) {
- if (event.deltaY > 0) {
- zoomIn();
- } else {
- zoomOut();
- }
-}
-
-function keyPressed(event) {
- var keyChar = String.fromCharCode(o3djs.event.getEventKeyChar(event));
- keyChar = keyChar.toLowerCase();
- var identifier = o3djs.event.getKeyIdentifier(event.charCode, event.keyCode);
-
- var spotDelta = 1;
- var cueBall = g_physics.balls[0];
- var x = cueBall.center[0];
- var y = cueBall.center[1];
-
- switch(keyChar) {
- case '*':
- rack(8);
- break;
-
- case '(':
- rack(9);
- break;
-
- case ')':
- rack(0);
- break;
-
- case 'd':
- ballOn(0);
- placeBall(0, x + spotDelta, y);
- g_physics.boundCueBall();
- break;
-
- case 'a':
- ballOn(0);
- placeBall(0, x - spotDelta, y);
- g_physics.boundCueBall();
- break;
-
- case 's':
- ballOn(0);
- placeBall(0, x, y - spotDelta);
- g_physics.boundCueBall();
- break;
-
- case 'w':
- ballOn(0);
- placeBall(0, x, y + spotDelta);
- g_physics.boundCueBall();
- break;
-
- case 'c':
- g_cameraInfo.zoomToPoint(g_physics.balls[0].center);
- if (!g_rolling)
- g_barRoot.visible = true;
- break;
-
- case 't':
- g_cameraInfo.goTo([0, 0, 0], null, null, 100);
- break;
-
- case '=':
- case '+':
- zoomIn();
- break;
-
- case '-':
- case '_':
- zoomOut();
- break;
-
- case ' ':
- if (!g_cameraInfo.lookingAt(g_physics.balls[0].center)) {
- g_cameraInfo.zoomToPoint(g_physics.balls[0].center);
- if (!g_rolling)
- g_barRoot.visible = true;
- } else {
- if (g_seriousness > 1) {
- if (!(g_rolling || g_shooting)) {
- startShooting();
- }
- }
- g_seriousness++;
- }
- break;
- }
-
- updateContext();
-}
-
-</script>
-</head>
-<body onload="initClient()" style="background-color: #111111">
-<div id="container">
-<!-- Start of O3D client area -->
-<div id="o3d" style="width: 100%; height:100%;"> </div>
-<!-- End of O3D plugin -->
-
-<div id="footer">
-<center>
-<table width = 800 style="color: gray">
-<tr>
-<td> Click and drag to move the view. </td>
-<td> spacebar : Hold down to shoot.</td>
-<td> t : Table view mode.</td>
-<td> * : Rack for 8-Ball. </td>
-</tr>
-<tr>
-<td> +/- : Zoom in / out. </td>
-<td> asdw : Position the cue ball.</td>
-<td> c : Cue ball view mode.</td>
-<td> ( : Rack for 9-Ball. </td>
-</tr>
-</table>
-</center>
-</div>
-</div>
-
-<div style="display:none">
-<!-- Start of effect -->
-<textarea id="vshader">
- uniform mat4 worldViewProjection;
- uniform mat4 worldInverseTranspose;
- uniform mat4 world;
-
- attribute vec4 position;
- attribute vec3 normal;
-
- varying vec4 vposition;
- varying vec4 vobjectPosition;
- varying vec3 vworldPosition;
- varying vec4 vscreenPosition;
- varying vec3 vnormal;
-
- void main() {
- vposition = worldViewProjection * position;
- vec4 temp = vposition;
- temp += temp.w * vec4(1.0, 1.0, 0.0, 0.0);
- temp.xyz /= 2.0;
- vscreenPosition = temp;
- vnormal = (worldInverseTranspose * vec4(normal, 0.0)).xyz;
- vworldPosition = (world * vec4(position.xyz, 1.0)).xyz;
- vobjectPosition = position;
- gl_Position = vposition;
- }
-
-</textarea>
-<textarea id="pshader">
- uniform vec3 lightWorldPosition;
- uniform vec3 eyeWorldPosition;
- uniform float factor;
- uniform float shadowOn;
-
- uniform sampler2D textureSampler;
-
- uniform vec2 ballCenter;
-
- varying vec4 vposition;
- varying vec4 vobjectPosition;
- varying vec3 vworldPosition;
- varying vec4 vscreenPosition;
- varying vec3 vnormal;
-
- vec4 roomColor(vec3 p, vec3 r) {
- vec2 c = vec2(1.0 / 15.0, 1.0 / 30.0) *
- (p.xy + r.xy * (lightWorldPosition.z - p.z) / r.z);
-
- float temp = (abs(c.x + c.y) + abs(c.y - c.x));
- float t = min(0.15 * max(7.0 - temp, 0.0) +
- ((temp < 5.0) ? 1.0 : 0.0), 1.0);
- return vec4(t, t, t, 1.0);
- }
-
- vec4 lighting(vec4 pigment, float shininess) {
- vec3 p = vworldPosition;
- vec3 l = normalize(lightWorldPosition - p); // Toward light.
- vec3 n = normalize(vnormal); // Normal.
- vec3 v = normalize(eyeWorldPosition - p); // Toward eye.
- vec3 r = normalize(-reflect(v, n)); // Reflection of v across n.
-
- return vec4(max(dot(l, n), 0.0) * pigment.xyz +
- 0.2 * pow(max(dot(l, r), 0.0), shininess) * vec3(1, 1, 1), 1.0);
- }
-
- vec4 woodPigment(vec3 p) {
- vec3 core = normalize(
- (abs(p.y) > abs(p.x) + 1.0) ?
- vec3(1.0, 0.2, 0.3) : vec3(0.2, 1.0, 0.3));
- float grainThickness = 0.02;
- float t =
- mod(length(p - dot(p,core)*core), grainThickness) / grainThickness;
-
- return mix(vec4(0.15, 0.05, 0.0, 0.1), vec4(0.1, 0.0, 0.0, 0.1), t);
- }
-
- vec4 feltPigment(vec3 p) {
- return vec4(0.1, 0.45, 0.15, 1.0);
- }
-
- vec4 environmentColor(vec3 p, vec3 r) {
- vec4 upColor = 0.1 * roomColor(p, r);
- vec4 downColor = -r.z * 0.3 * feltPigment(p);
- float t = smoothstep(0.0, 0.05, r.z);
- return mix(downColor, upColor, t);
- }
-
- vec4 solidPixelShader() {
- return vec4(1.0, 1.0, 1.0, 0.2);
- }
-
- vec4 feltPixelShader() {
- vec2 tex = vscreenPosition.xy / vscreenPosition.w;
-
- vec3 p = factor * vworldPosition;
- vec3 c = factor * eyeWorldPosition.xyz;
- float width = 0.3;
- float height = 0.3;
- float d =
- 1.0 * (smoothstep(1.0 - width, 1.0 + width, abs(p.x)) +
- smoothstep(2.0 - height, 2.0 + height, abs(p.y)));
- p = vworldPosition;
-
- return (1.0 - texture2D(textureSampler, tex).x - d) *
- lighting(feltPigment(p), 4.0);
- }
-
- vec4 woodPixelShader() {
- vec3 p = factor * vworldPosition;
- return lighting(woodPigment(p), 50.0);
- }
-
- vec4 cushionPixelShader() {
- vec3 p = factor * vworldPosition;
- return lighting(feltPigment(p), 4.0);
- }
-
- vec4 billiardPixelShader() {
- vec3 p = factor * vworldPosition;
- return lighting(vec4(0.5, 0.5, 0.2, 1), 30.0);
- }
-
- vec4 ballPixelShader() {
- vec3 p = normalize(vobjectPosition.xyz);
- vec4 u = 0.5 * vec4(p.x, p.y, p.x, -p.y);
- u = clamp(u, -0.45, 0.45);
- u += vec4(0.5, 0.5, 0.5, 0.5);
-
- float t = clamp(5.0 * p.z, 0.0, 1.0);
-
- p = vworldPosition;
- vec3 l = normalize(lightWorldPosition - p); // Toward light.
- vec3 n = normalize(vnormal); // Normal.
- vec3 v = normalize(eyeWorldPosition - p); // Toward eye.
- vec3 r = normalize(-reflect(v, n)); // Reflection of v across n.
-
- vec4 pigment =
- mix(texture2D(textureSampler, u.zw),
- texture2D(textureSampler, u.xy), t);
-
- return 0.4 * environmentColor(p, r) +
- pigment * (0.3 * smoothstep(0.0, 1.1, dot(n, l)) +
- 0.3 * (p.z + 1.0));
- }
-
- vec4 shadowPlanePixelShader() {
- vec2 p = vworldPosition.xy - ballCenter;
- vec2 q = (vworldPosition.xy / lightWorldPosition.z);
-
- vec2 offset = (1.0 - 1.0 / (vec2(1.0, 1.0) + abs(q))) * sign(q);
- float t = mix(smoothstep(0.9, 0.0, length(p - length(p) * offset) / 2.0),
- smoothstep(1.0, 0.0, length(p) / 10.0), 0.15);
- return shadowOn * vec4(t, t, t, t);
- }
-
-</textarea>
-<!-- End of effect -->
-</div>
-
-</body>
-</html>
-
-
diff --git a/o3d/samples/o3d-webgl-samples/primitives.html b/o3d/samples/o3d-webgl-samples/primitives.html
deleted file mode 100644
index 1b3e1c0..0000000
--- a/o3d/samples/o3d-webgl-samples/primitives.html
+++ /dev/null
@@ -1,247 +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.
--->
-
-<!--
-O3D Primitives
-
-This sample shows how to use the functions in the primitives utility library
-to make various shapes.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Primitives
-</title>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// global variables
-var g_o3dElement;
-var g_client;
-var g_o3d;
-var g_math;
-var g_pack;
-var g_viewInfo;
-var g_eyePosition = [3, 4, 14];
-
-/**
- * Creates the client area.
- */
-function initClient() {
- window.g_finished = false; // for selenium testing.
- o3djs.webgl.makeClients(main);
-}
-
-/**
- * Initializes global variables, positions camera, draws shapes.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function main(clientElements) {
- // Init global variables.
- initGlobals(clientElements);
-
- // Set up the view and projection transformations.
- initContext();
-
- // Add the shapes to the transform heirarchy.
- createShapes();
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Initializes global variables and libraries.
- */
-function initGlobals(clientElements) {
- g_o3dElement = clientElements[0];
- window.g_client = g_client = g_o3dElement.client;
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-}
-
-/**
- * Sets up reasonable view and projection matrices.
- */
-function initContext() {
- // Set up a perspective transformation for the projection.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree frustum.
- g_o3dElement.clientWidth / g_o3dElement.clientHeight, // Aspect ratio.
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // primitives are located.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- g_eyePosition, // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Creates a material based on the given single color.
- * @param {!o3djs.math.Vector4} baseColor A 4-component vector with
- * the R,G,B, and A components of a color.
- * @return {!o3d.Material} A phong material whose overall pigment is
- * baseColor.
- */
-function createMaterial(baseColor) {
- // Create a new, empty Material object.
- return o3djs.material.createBasicMaterial(g_pack, g_viewInfo, baseColor);
-}
-
-/**
- * Creates shapes using the primitives utility library, and adds them to the
- * transform graph at the root node.
- */
-function createShapes() {
- var cube = o3djs.primitives.createCube(
- g_pack,
- createMaterial([0,1,0,1]), // A green phong-shaded material.
- Math.sqrt(2)); // The length of each side of the cube.
-
- var sphere = o3djs.primitives.createSphere(
- g_pack,
- createMaterial([1,0,0,1]),
- 1.0, // Radius of the sphere.
- 30, // Number of meridians.
- 20); // Number of parallels.
-
- var cylinder = o3djs.primitives.createCylinder(
- g_pack,
- createMaterial([1,0,1,1]),
- 0.5, // Radius.
- 1.5, // Height.
- 20, // Number of radial subdivisions.
- 20); // Number of vertical subdivisions.
-
- var truncatedCone = o3djs.primitives.createTruncatedCone(
- g_pack,
- createMaterial([0,0,1,1]),
- 0.3, // Bottom radius.
- 0.5, // Top radius.
- 1.5, // Height.
- 20, // Number of radial subdivisions.
- 20); // Number of vertical subdivisions.
-
- var cone = o3djs.primitives.createTruncatedCone(
- g_pack,
- createMaterial([0,1,0,1]),
- 0.5, // Bottom radius.
- 0.0, // Top radius.
- 1.5, // Height.
- 20, // Number of radial subdivisions.
- 20); // Number of vertical subdivisions.
-
- var plane = o3djs.primitives.createPlane(
- g_pack,
- createMaterial([0,1,1,1]),
- 1, // Width.
- 1.618, // Depth.
- 3, // Horizontal subdivisions.
- 3); // Vertical subdivisions.
-
- // Make a polygon to extrude for the prism.
- var polygon = [];
- var n = 10;
- for (var i = 0; i < n; ++i) {
- var theta = 2.0 * i * Math.PI / n;
- var radius = (i % 2) ? 1 : 0.382;
- polygon.push([radius * Math.cos(theta), radius * Math.sin(theta)]);
- }
-
- var prism = o3djs.primitives.createPrism(
- g_pack,
- createMaterial([1,1,0,1]),
- polygon, // The profile polygon to be extruded.
- 1); // The depth of the extrusion.
-
- var disc = o3djs.primitives.createDisc(
- g_pack,
- createMaterial([1,0,0,1]),
- 1, // Radius.
- 7, // Divisions.
- 2, // Stacks (optional).
- 0, // Start Stack (optional).
- 2); // Stack Power (optional).
-
- // Add the shapes to the transforms.
- var transformTable = [
- {shape: cube, translation: [-3, 1, 0]},
- {shape: sphere, translation: [-1, 1, 0]},
- {shape: cylinder, translation: [1, 1, 0]},
- {shape: truncatedCone, translation: [3, 1, 0]},
- {shape: plane, translation: [-3, -1, 0]},
- {shape: prism, translation: [-1, -1, 0]},
- {shape: disc, translation: [1, -1, 0]},
- {shape: cone, translation: [3, -1, 0]},
- ];
-
- for (var tt = 0; tt < transformTable.length; ++tt) {
- var transform = g_pack.createObject('Transform');
- transform.addShape(transformTable[tt].shape);
- transform.translate(transformTable[tt].translation);
- transform.parent = g_client.root;
- }
-}
-
-
-</script>
-</head>
-<body onload="initClient()">
-<h1>Primitives</h1>
-This example shows how to use the primitives utility library to make various
-shapes.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/procedural-texture.html b/o3d/samples/o3d-webgl-samples/procedural-texture.html
deleted file mode 100644
index abd31df..0000000
--- a/o3d/samples/o3d-webgl-samples/procedural-texture.html
+++ /dev/null
@@ -1,255 +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.
--->
-
-<!--
-O3D Tutorial
-
-In this tutorial, we load and display a scene in O3D and then
-apply a procedural texture to it.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Applying a Procedural Texture to a scene
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_finished = false; // for selenium testing
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- */
-function loadScene(pack, fileName, parent) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- g_client.width,
- g_client.height);
-
- // Copy the view and projection to the draw context.
- g_viewInfo.drawContext.view = cameraInfo.view;
- g_viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Add our checker pattern
- createCheckerBoard(pack, 'Material__26');
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
-
- g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * In order to apply the texture you must know the material name which you wish
- * to change. The bulk of the calculation takes place in the shader itself.
- * Alternatively, you could change the first or all the materials if you don't
- * know the material name.
- * @param {!o3d.Pack} pack The pack the scene was loaded into.
- * @param {string} materialName Name of material you wish to turn into checkers.
- */
-function createCheckerBoard(pack, materialName) {
- var effectString = document.getElementById('checkerShader').value;
- var effect = g_pack.createObject('Effect');
- effect.loadFromFXString(effectString);
- var materials = pack.getObjects(materialName, 'o3d.Material');
- for (var m = 0; m < materials.length; m++) {
- var material = materials[m];
- // Set the material to use the checker effect.
- material.effect = effect;
- // Create any parameters the effect needs on the material.
- effect.createUniformParameters(material);
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Creates a transform to put our data on.
- var myDataRoot = g_pack.createObject('Transform');
-
- // Connects our root to the client's root.
- myDataRoot.parent = g_client.root;
-
- // Load the scene into the transform graph as a child myDataRoot
- loadScene(g_pack, '../assets/teapot/scene.json', myDataRoot);
-}
-</script>
-</head>
-<body>
-<h1>Applying a Procedural Texture to a scene</h1>
-This tutorial shows how to apply a procedural texture to a scene.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<!-- Don't render the textarea -->
-<textarea id="checkerShader" style="display: none;">
-// The 4x4 world view projection matrix.
-uniform mat4 worldViewProjection;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec3 normal;
-attribute vec2 texCoord0;
-
-// input parameters for our pixel shader
-varying vec4 col;
-varying vec2 texcoord;
-
-/**
- * Our vertex shader. In the vertex shader, we calculate the lighting.
- * Then we'll combine it with our checker pattern in the pixel shader.
- */
-void main() {
- gl_Position = worldViewProjection * position;
-
- /**
- * lightVector - light vector
- * normal - normal vector
- * We put the light such that it illuminates our model.
- */
- vec4 diffuseColor = vec4(1, 1, 1, 1);
- vec3 lightPos = vec3(1000, -1000, 1000);
-
- vec3 lightVector = normalize(lightPos - position.xyz);
- vec3 normal = normalize(normal);
- vec4 diffuse = dot(normal, lightVector) * diffuseColor;
-
- col = diffuse;
- texcoord = texCoord0;
-}
-
-// #o3d SplitMarker
-
-// function for getting the checker pattern
-
-vec4 checker(vec2 uv) {
- float checkSize = 4.0;
- float fmodResult = mod(floor(checkSize * uv.x) + floor(checkSize * uv.y),
- 2.0);
- if (fmodResult < 1.0) {
- return vec4(0, 1, 1, 1);
- } else {
- return vec4(1, 0, 1, 1);
- }
-}
-
-// input parameters for our pixel shader
-varying vec4 col;
-varying vec2 texcoord;
-
-
-/**
- * Our pixel shader. We take the lighting color we got from the vertex sahder
- * and combine it with our checker pattern.
- */
-void main() {
- vec4 check = checker(texcoord);
- vec4 color = col * check;
- gl_FragColor = color;
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/render-mode.html b/o3d/samples/o3d-webgl-samples/render-mode.html
deleted file mode 100644
index 8d1c4e0..0000000
--- a/o3d/samples/o3d-webgl-samples/render-mode.html
+++ /dev/null
@@ -1,287 +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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<title>
- Render Mode Example.
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- }
-</style>
-</head>
-<body onload="init();" onunload="uninit();">
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.arcball');
-o3djs.require('o3djs.event');
-o3djs.require('o3djs.scene');
-
-var g_root;
-var g_o3d;
-var g_o3dElement
-var g_math;
-var g_quaternions;
-var g_client;
-var g_aball;
-var g_thisRot;
-var g_lastRot;
-var g_pack;
-var g_viewInfo;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-var g_framesRendered = 0;
-
-var g_camera = {
- eye: [0, 0, 5],
- target: [0, 0, 0]
-};
-
-var g_dragging = false;
-
-function startDragging(e) {
- g_lastRot = g_thisRot;
- g_aball.click([e.x, e.y]);
- g_dragging = true;
-}
-
-function drag(e) {
- if (g_dragging) {
- var rotationQuat = g_aball.drag([e.x, e.y]);
- var rot_mat = g_quaternions.quaternionToRotation(rotationQuat);
- g_thisRot = g_math.matrix4.mul(g_lastRot, rot_mat);
- var m = g_root.localMatrix;
- g_math.matrix4.setUpper3x3(m, g_thisRot);
- g_root.localMatrix = m;
-
- updateClient();
- }
-}
-
-function stopDragging(e) {
- g_dragging = false;
-}
-
-function updateClient() {
- // If we are in RENDERMODE_ON_DEMAND mode then set the render mode again
- // which will cause the client re-render the display.
- if (g_client.renderMode == g_o3d.Client.RENDERMODE_ON_DEMAND) {
- g_client.render();
- }
-}
-
-function scrollMe(e) {
- if (e.deltaY) {
- g_camera.eye =
- g_math.mulScalarVector((e.deltaY < 0 ? 11 : 13) / 12, g_camera.eye);
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(g_camera.eye,
- g_camera.target,
- [0, 1, 0]);
- updateClient();
- }
-}
-
-function loadFile(path) {
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + path + '\n' + exception);
- return;
- }
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
- }
- // Create a new transform for the loaded file
- var parent = g_pack.createObject('Transform');
- parent.parent = g_client.root;
-
- if (path != null) {
- o3djs.scene.loadScene(g_client, g_pack, parent, path, callback);
- }
-
- return parent;
-}
-
-function setClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- // Set the perspective projection matrix
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), g_o3dWidth / g_o3dHeight, 0.1, 100);
-
- // Sets a new area size for arcball.
- g_aball.setAreaSize(g_o3dWidth, g_o3dHeight);
-
- //o3djs.dump.dump("areaWidth: " + g_o3dWidth + "\n");
- //o3djs.dump.dump("areaHeight: " + g_o3dHeight + "\n");
- }
-}
-
-function resize() {
- setClientSize();
-}
-
-function setRenderMode(event) {
- var mode = (event) ? event.target.value : window.event.srcElement.value;
- switch (mode) {
- case 'continuous':
- g_client.renderMode = g_o3d.Client.RENDERMODE_CONTINUOUS;
- break;
- case 'ondemand':
- g_client.renderMode = g_o3d.Client.RENDERMODE_ON_DEMAND;
- break;
- }
-}
-
-function onRender() {
- g_framesRendered++;
- g_viewInfo.clearBuffer.clearColor = [
- 1 / 38 * (g_framesRendered % 38),
- 1 / 39 * (g_framesRendered % 39),
- 1 / 41 * (g_framesRendered % 41),
- 1];
- resize();
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- path = path.substring(0, index + 1) + '../assets/teapot/scene.json';
-
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_quaternions = o3djs.quaternions;
- g_client = g_o3dElement.client;
-
- g_pack = g_client.createPack();
- g_lastRot = g_math.matrix4.identity();
- g_thisRot = g_math.matrix4.identity();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- var root = g_client.root;
-
- var target = [0, 0, 0];
- var eye = [0, 0, 5];
- var up = [0, 1, 0];
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(eye, target, up);
-
- g_aball = o3djs.arcball.create(100, 100);
- setClientSize();
-
- g_root = loadFile(path);
-
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', startDragging);
- o3djs.event.addEventListener(g_o3dElement, 'mousemove', drag);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', stopDragging);
- o3djs.event.addEventListener(g_o3dElement, 'wheel', scrollMe);
- document.getElementById('rendermode0').onclick = setRenderMode;
- document.getElementById('rendermode1').onclick = setRenderMode;
-
- g_client.setRenderCallback(onRender);
-
- window.onresize = updateClient;
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-<table width="100%" style="height:100%;">
-<tr width="100%" style="height:100%;"><td valign="middle" align="center">
-<h1>
-Render Mode Example.
-</h1>
-<p>The point of this demo is to show that for certain kinds of 3d applications
- that don't have animation, for example a map viewer, you can set the client's
-render mode to RENDERMODE_ON_DEMAND which will render the 3d one time and then
-stop rendering. This has the advantage of not wasting CPU cycles rendering
-something that does not change over and over.</p>
-<p>The background changes color each time the scene is rendered. The sample
-should start with the scene being constantly rendered but click
-RENDERMODE_ON_DEMAND and you'll see it rendered only when it needs to be
-as determined by the sample. </p>
-<table id="container" width="90%" height="60%" border="2">
-<tr height="100%"><td>
-<div id="o3d" style="width: 100%; height: 100%;"></div>
-</td></tr>
-</table>
-<input type="radio" id="rendermode0" name="rendermode" value="continuous" checked="true"><label for="rendermode0">RENDERMODE_CONTINUOUS (draw as often as possible)</label><br/>
-<input type="radio" id="rendermode1" name="rendermode" value="ondemand"><label for="rendermode1">RENDERMODE_ON_DEMAND (draw once then as the OS requests it like when a window is uncovered)</label><br/>
-<p>
-Drag The Mouse To Rotate<br/>
-Scrollwheel To Zoom<br/>
-Resize The Window To Resize The View
-</p>
-</td></tr></table>
-</body>
-</html>
-
-
diff --git a/o3d/samples/o3d-webgl-samples/render-targets.html b/o3d/samples/o3d-webgl-samples/render-targets.html
deleted file mode 100644
index 4dd9d06..0000000
--- a/o3d/samples/o3d-webgl-samples/render-targets.html
+++ /dev/null
@@ -1,333 +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 sample shows how to setup a basic render graph making use of RenderSurface
-nodes to implement render-target functionality.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-O3D: Render-Target Sample
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.scene');
-
-// constants.
-var RENDER_TARGET_WIDTH = 512;
-var RENDER_TARGET_HEIGHT = 512;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_teapotPack;
-var g_teapotRoot;
-var g_cubeRoot;
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo who's view and projection will
- * be set from the scene after it's loaded.
- */
-function loadScene(pack, fileName, parent, viewInfo) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT);
-
- // Copy the view and projection to the passed in viewInfo structure..
- viewInfo.drawContext.view = cameraInfo.view;
- viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, viewInfo);
-
- window.g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- // These are here so that they are visible to both the browser (so
- // selenium sees them) and the embedded V8 engine.
- window.g_clock = 0;
- window.g_timeMult = 1;
- window.g_finished = false; // for selenium testing.
-
- // Comment out the line below to run the sample in the browser
- // JavaScript engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3d = clientElements[0];
- g_o3d = o3d.o3d;
- g_math = o3djs.math;
-
- // Set window.g_client as well. Otherwise when the sample runs in
- // V8, selenium won't be able to find this variable (it can only see
- // the browser environment).
- window.g_client = g_client = o3d.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create a sub-pack to manage the resources required for the teapot.
- g_teapotPack = g_client.createPack();
-
- // Create the texture required for the color render-target.
- var texture2d = g_pack.createTexture2D(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT,
- g_o3d.Texture.XRGB8, 1, true);
- var renderSurface = texture2d.getRenderSurface(0);
-
- // Create the depth-stencil buffer required when rendering the teapot.
- var depthSurface = g_pack.createDepthStencilSurface(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT);
-
- g_cubeRoot = g_pack.createObject('Transform');
- g_teapotRoot = g_pack.createObject('Transform');
- g_cubeRoot.parent = g_client.root;
- g_teapotRoot.parent = g_client.root;
-
- var teapotRenderRoot = g_pack.createObject('RenderNode');
- teapotRenderRoot.priority = 0;
- var cubeRenderRoot = g_pack.createObject('RenderNode');
- cubeRenderRoot.priority = 1;
-
- teapotRenderRoot.parent = g_client.renderGraphRoot;
- cubeRenderRoot.parent = g_client.renderGraphRoot;
-
- var renderSurfaceSet = g_pack.createObject('RenderSurfaceSet');
- renderSurfaceSet.renderSurface = renderSurface;
- renderSurfaceSet.renderDepthStencilSurface = depthSurface;
- renderSurfaceSet.parent = teapotRenderRoot;
-
- // Create the render graph for a view.
- var teapotViewInfo = o3djs.rendergraph.createBasicView(
- g_teapotPack,
- g_teapotRoot,
- renderSurfaceSet);
-
- var cubeViewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_cubeRoot,
- cubeRenderRoot);
-
- var myMaterial = g_pack.createObject('Material');
- myMaterial.drawList = cubeViewInfo.performanceDrawList;
-
- var effect = g_pack.createObject('Effect');
- var fxString = o3djs.util.getElementContentById('fx');
- effect.loadFromFXString(fxString);
-
- // Apply our effect to this material.
- myMaterial.effect = effect;
- effect.createUniformParameters(myMaterial);
-
- var samplerParam = myMaterial.getParam('texSampler0');
- var sampler = g_pack.createObject('Sampler');
- sampler.texture = texture2d;
- samplerParam.value = sampler;
-
- // Create a transform to put our data on.
- var myDataRoot = g_pack.createObject('Transform');
-
- // Connect our root to the client.
- myDataRoot.parent = g_teapotRoot;
- var vec3 = [0.5, 0.5, 0.5];
-
- var cubeShape = o3djs.primitives.createCube(g_pack,
- myMaterial,
- 300.0);
-
- // Attach the cube to the root of the transform graph.
- g_cubeRoot.addShape(cubeShape);
-
- o3djs.pack.preparePack(g_pack, cubeViewInfo);
-
- // Points at the origin.
- var target = [0, 0, 0];
- // Puts the camera outside the origin.
- var eye = [500, 500, 500];
- // Defines UP as Y up.
- var up = [0, 1, 0];
- cubeViewInfo.drawContext.view = g_math.matrix4.lookAt(eye,
- target,
- up);
-
- cubeViewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30),
- g_client.width / g_client.height, 1, 5000);
-
- // Load the scene into the transform graph as a child myDataRoot
- loadScene(g_teapotPack, '../assets/teapot/scene.json', myDataRoot,
- teapotViewInfo);
-
- // Set a render callback.
- g_client.setRenderCallback(onRender);
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- // Update g_clock in the browser and cache a V8 copy that can be
- // accessed efficiently. g_clock must be in the browser for selenium.
- var clock = window.g_clock + elapsedTime * window.g_timeMult;
- window.g_clock = clock;
-
- g_teapotRoot.identity();
- g_teapotRoot.rotateX(clock);
- g_teapotRoot.rotateY(clock * 1.3);
-
- g_cubeRoot.identity();
- g_cubeRoot.rotateX(clock * 0.4);
- g_cubeRoot.rotateY(clock * 0.1);
-}
-
-/**
- * Cleanup before exiting.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body onload="init()" onunload="unload()">
-<h1>Basic Render-Target Example</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<!--
- We embed the code for our effect inside this hidden textarea.
- Effects contain the functions that define
- the vertex and pixel shaders used by our shape.
--->
-<!-- Don't render the textarea -->
-<div style="display:none">
-<textarea id="fx" name="fx" cols="80" rows="20">
- // The 4x4 world view projection matrix.
- uniform mat4 worldViewProjection;
-
- attribute vec4 position;
- attribute vec2 texCoord0;
- varying vec2 texcoord;
-
- /**
- * Vertex Shader performing basic viewing transformation.
- */
- void main() {
- /**
- * We transform each vertex by the view projection matrix to bring
- * it from world space to projection space.
- *
- * We return its color unchanged.
- */
- gl_Position = worldViewProjection * position;
- texcoord = texCoord0;
- }
-
- // #o3d SplitMarker
-
- uniform sampler2D texSampler0;
- varying vec2 texcoord;
-
- /**
- * Pixel Shader
- */
- void main() {
- gl_FragColor = texture2D(texSampler0, texcoord * 5.0) +
- vec4(0.2, 0.2, 0.0, 1.0);
- }
-
- // #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
-
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/rotatemodel.html b/o3d/samples/o3d-webgl-samples/rotatemodel.html
deleted file mode 100644
index d361218..0000000
--- a/o3d/samples/o3d-webgl-samples/rotatemodel.html
+++ /dev/null
@@ -1,250 +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.
--->
-
-<!--
-O3D Tutorial A2
-
-In this tutorial, we show how to perform transformations on a scene that
-we have loaded.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Tutorial A2: Transformations
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.scene');
-
-// Events
-// Run the init() function once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_keyPressDelta = 0.05;
-var g_finished = false; // for selenium testing
-
-// root node of scene
-var g_sceneRoot;
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- */
-function loadScene(pack, fileName, parent) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- g_client.width,
- g_client.height);
-
- // Copy the view and projection to the draw context.
- g_viewInfo.drawContext.view = cameraInfo.view;
- g_viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
-
- g_finished = true; // for selenium testing
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create a transform node to act as the 'root' of the scene
- g_sceneRoot = g_pack.createObject('Transform');
- // Attach it to the root of the transform graph.
- g_sceneRoot.parent = g_client.root;
-
- // Load the scene into the transform graph as a child of the g_sceneRoot.
- loadScene(g_pack, '../assets/teapot/scene.json', g_sceneRoot);
-
- // Execute keyPressedCallback(..) when we detect a keypress on the document.
- window.document.onkeypress = keyPressedCallback;
-}
-
-/**
- * Function performing the rotate action in response to a key-press.
- * Rotates the scene based on key pressed. (w ,s, a, d). Note that the x and
- * y-axis referenced here are relative to the current view of the scene.
- * @param {keyPressed} The letter pressed, in lower case.
- * @param {delta} The angle by which the scene should be rotated.
- * @return true if an action was taken.
- */
-function keyPressedAction(keyPressed, delta) {
- var actionTaken = false;
- switch(keyPressed) {
- case 'a':
- g_sceneRoot.localMatrix =
- g_math.matrix4.mul(g_sceneRoot.localMatrix,
- g_math.matrix4.rotationY(-delta));
- actionTaken = true;
- break;
- case 'd':
- g_sceneRoot.localMatrix =
- g_math.matrix4.mul(g_sceneRoot.localMatrix,
- g_math.matrix4.rotationY(delta));
- actionTaken = true;
- break;
- case 'w':
- g_sceneRoot.localMatrix =
- g_math.matrix4.mul(g_sceneRoot.localMatrix,
- g_math.matrix4.rotationX(-delta));
- actionTaken = true;
- break;
- case 's':
- g_sceneRoot.localMatrix =
- g_math.matrix4.mul(g_sceneRoot.localMatrix,
- g_math.matrix4.rotationX(delta));
- actionTaken = true;
- break;
- }
- return actionTaken;
-}
-
-/**
- * Callback for the keypress event.
- * Invokes the action to be performed for the key pressed.
- * @param {event} keyPress event passed to us by javascript.
- */
-function keyPressedCallback(event) {
- event = event || window.event;
-
- // Ignore accelerator key messages.
- if (event.metaKey)
- return;
-
- var keyChar = String.fromCharCode(o3djs.event.getEventKeyChar(event));
- // Just in case they have capslock on.
- keyChar = keyChar.toLowerCase();
-
- if (keyPressedAction(keyChar, g_keyPressDelta)) {
- o3djs.event.cancel(event);
- }
-}
-
-/**
- * Resets the view of the scene by resetting its local matrix to the identity
- * matrix.
- */
-function resetView() {
- g_sceneRoot.identity();
-}
-
-</script>
-</head>
-<body>
-<h1>Transformations</h1>
-This tutorial shows how to perform transformations on a scene that
-has been loaded.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<p>Use W, S, A, D to rotate.</p>
-<form name="default_form" action="#" method="get">
-<input type="button" value="Reset view" onclick="resetView()" />
-<input type="button" value="W" id="W"
- onclick="keyPressedAction('w', g_keyPressDelta);" />
-<input type="button" value="S" id="S"
- onclick="keyPressedAction('s', g_keyPressDelta);" />
-<input type="button" value="A" id="A"
- onclick="keyPressedAction('a', g_keyPressDelta);" />
-<input type="button" value="D" id="D"
- onclick="keyPressedAction('d', g_keyPressDelta);" />
-</form>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/shader-test.html b/o3d/samples/o3d-webgl-samples/shader-test.html
deleted file mode 100644
index 021c1c9..0000000
--- a/o3d/samples/o3d-webgl-samples/shader-test.html
+++ /dev/null
@@ -1,407 +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.
--->
-
-<!--
-O3D Tutorial
-
-In this tutorial, we load a scene file and then apply various shaders to it.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Shader Test
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.loader');
-
-/**
- * NOTE: O3D-WebGL is unable to load bump maps in .dds format. We omit the
- * bump map examples here.
- */
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_client;
-var g_viewInfo;
-var g_o3dElement;
-var g_pack;
-var g_root;
-var g_math;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-var g_currentTimeParam;
-var g_clock = 0;
-var g_shaderSelection = 0;
-var g_rotateOn = true;
-var g_o3dWidth; // width of our client area
-var g_o3dHeight; // height of our client area
-var g_shaders = [
- {file: 'diffuse', name: 'Diffuse'},
- {file: 'checker', name: 'Checker'},
- {file: 'texture-only', name: 'Texture'},
- {file: 'texture-colormult', name: 'Texture with Color Multiplier'},
- {file: 'tangent', name: 'Tangent'},
- {file: 'binormal', name: 'Binormal'},
- {file: 'normal', name: 'Normal'},
- {file: 'solid-color', name: 'Solid Color'},
- {file: 'vertex-color', name: 'Vertex Color'},
- {file: 'phong-with-colormult', name: 'Blinn-Phong with Color Multiplier'},
- {file: 'toon', name: 'Toon'}
- ];
-var g_effects = [];
-var g_bumpTextureSampler;
-var g_colorRampSampler;
-
-// Our view and projection matrices
-// The view matrix transforms objects from world space to view space.
-var g_viewMatrix;
-// The projection matrix projects objects from view space to the screen.
-var g_projMatrix;
-
-/**
- * Returns the path of where the file is located
- * with the trailing slash
- */
-function getCurrentPath() {
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- return path.substring(0, index + 1);
-}
-
-/**
- * Turn rotation on.
- */
-function turnRotateOn() {
- g_rotateOn = true;
-}
-
-/**
- * Turn rotation off.
- */
-function turnRotateOff() {
- g_rotateOn = false;
-}
-
-/**
- * This is the code to animate the rotation.
- * @param {o3d.RenderEvent} render_event The render event.
- */
-function onrender(render_event) {
- var elapsedTime = render_event.elapsedTime * g_timeMult;
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- setupCamera(g_pack, g_root);
- }
-
- g_clock += elapsedTime * (g_rotateOn ? 1 : 0);
- g_root.identity();
- g_root.rotateY(g_clock);
-
- g_currentTimeParam.value = g_clock;
-}
-
-/**
- * Sets the camera based on the imported file.
- * @param {!o3d.Pack} pack Pack to create context in.
- * @param {!o3d.Transform} root Root of tree to search for camera info.
- */
-function setupCamera(pack, root) {
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(root,
- g_o3dWidth,
- g_o3dHeight);
-
- // Copy the view and projection to the draw context.
- g_viewInfo.drawContext.view = cameraInfo.view;
- g_viewInfo.drawContext.projection = cameraInfo.projection;
-}
-
-/**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack Variable referring to the scene's pack.
- * @param {!o3d.Transform} parent Transform parent.
- * @param {*} exception null if loading succeeded.
- */
-function sceneCallback(pack, parent, exception) {
- if (exception) {
- alert('Could not load scene\n' + exception);
- return;
- }
- setupCamera(pack, parent);
-
- // Start with diffuse as default
- applyShader(pack, 0);
-
- // Add some vertex colors because the teapot does not have any
- // and yet the vertex color shader requires them.
- var streamBanks = pack.getObjectsByClassName('o3d.StreamBank');
- for (var ss = 0; ss < streamBanks.length; ++ss) {
- var streamBank = streamBanks[ss];
- if (!streamBank.getVertexStream(g_o3d.Stream.COLOR, 0)) {
- var positionField = streamBank.getVertexStream(g_o3d.Stream.POSITION,
- 0).field;
- var buffer = positionField.buffer;
- var numElements = buffer.numElements;
- var colorField = buffer.createField('FloatField', 4);
- var colors = [];
- for (var nn = 0; nn < numElements; ++nn) {
- colors.push((nn * 40 / numElements) % 1,
- (nn * 61 / numElements) % 1,
- (nn * 83 / numElements) % 1,
- 1);
- }
- colorField.setAt(0, colors);
- streamBank.setVertexStream(g_o3d.Stream.COLOR, 0, colorField, 0);
- }
- }
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
-}
-
-/**
- * Looks up a Param and if it exists sets its value.
- * @param {!o3d.ParamObject} object object to look for param on.
- * @param {string} name name of Param to look up.
- * @param {*} value Value to set param.
- */
-function setParam(object, paramName, value) {
- var param = object.getParam(paramName);
- if (param) {
- param.value = value;
- }
-}
-
-/**
- * Apply the desired shader to our scene.
- * @param {!o3d.Pack} pack Variable referring to the scene's pack.
- * @param {number} shaderNumber Index into g_effects of which shader to use.
- */
-function applyShader(pack, shaderNumber) {
- var materials = pack.getObjectsByClassName('o3d.Material');
- // Make the change to each material. For our teapot, there is only one
- // material.
- for (var m = 0; m < materials.length; m++) {
- var material = materials[m];
- g_effects[shaderNumber].createUniformParameters(material);
- material.effect = g_effects[shaderNumber];
-
- // Set our shader values
- var colorParamValue = [0.8, 0.8, 0.8, 1];
- var lightPosParamValue = [600, 600, 1000];
-
- setParam(material, 'lightPos', lightPosParamValue);
- setParam(material, 'lightWorldPos', lightPosParamValue);
- setParam(material, 'cameraEye', [197.58, -63.5702, 0]);
- setParam(material, 'color', colorParamValue);
- setParam(material, 'colorMult', [.75, .75, 75., 1]);
- setParam(material, 'useTexture', 0);
- setParam(material, 'lightIntensity', [0.8, 0.8, 0.8, 1]);
- setParam(material, 'ambientIntensity', [0.2, 0.2, 0.2, 1]);
- setParam(material, 'emissive', [0, 0, 0, 1]);
- setParam(material, 'ambient', [1, 1, 1, 1]);
- setParam(material, 'diffuse', colorParamValue);
- setParam(material, 'specular', [0.5, 0.5, 0.5, 1]);
- setParam(material, 'shininess', 50);
- setParam(material, 'AmbientSampler', g_bumpTextureSampler);
- setParam(material, 'DiffuseSampler', g_bumpTextureSampler);
- setParam(material, 'texSampler0', g_bumpTextureSampler);
- setParam(material, 'colorRamp', g_colorRampSampler);
-
- var timeParam = material.getParam('inputTime');
- if (timeParam) {
- timeParam.bind(g_currentTimeParam);
- }
- }
-}
-
-/**
- * Creates our client area by looking for <div>s with an id that starts with
- * "o3d".
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Get the width and height of our client area. We will need this to create
- // a projection matrix.
- g_o3dWidth = g_client.width;
- g_o3dHeight = g_client.height;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Creates a transform to put our data on.
- g_root = g_pack.createObject('Transform');
-
- // Connects our root to the client's root.
- g_root.parent = g_client.root;
-
- var paramObject = g_pack.createObject('ParamObject');
- g_currentTimeParam = paramObject.createParam('timeParam','ParamFloat');
-
- // Load effects and fill out options.
- options = '<select id="shaderSelect" name="shaderSelect"' +
- ' onChange="changeShader()">'
- for(var s = 0; s < g_shaders.length; s++) {
- g_effects[s] = g_pack.createObject('Effect');
- var shaderString = '../shaders/' + g_shaders[s].file + '-glsl.shader';
- o3djs.effect.loadEffect(g_effects[s], shaderString);
- options += '<option value="' + s + '"' + (s == 0 ? ' selected' : '') +
- '>' + g_shaders[s].name + '</option>';
- }
- options += '</select>';
- document.getElementById('shaderDiv').innerHTML = options;
-
- var loader = o3djs.loader.createLoader(initStep3);
-
- var rampWidth = 64;
- var texture = g_pack.createTexture2D(
- rampWidth, 1, g_o3d.Texture.XRGB8, 1, false);
- var pixels = [];
- for (var ii = 0; ii < rampWidth; ++ii) {
- var level = ii > rampWidth * 0.5 ? 1 : 0.3;
- pixels.push(level, level, level);
- }
- texture.set(0, pixels);
- g_colorRampSampler = g_pack.createObject('Sampler');
- g_colorRampSampler.texture = texture;
- g_colorRampSampler.addressModeU = g_o3d.Sampler.CLAMP;
-
- loader.loadTexture(g_pack, '../assets/rock_texture.jpg',
- function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- g_bumpTextureSampler = g_pack.createObject('Sampler');
- g_bumpTextureSampler.texture = texture;
- g_bumpTextureSampler.mipFilter = g_o3d.Sampler.LINEAR;
- }
- });
- var scenePath = getCurrentPath() + '../assets/teapot/scene.json';
- loader.loadScene(g_client, g_pack, g_root, scenePath, sceneCallback);
- loader.finish();
-}
-
-function initStep3() {
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', turnRotateOff);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', turnRotateOn);
-
- g_rotateOn = true;
-
- // Tell our example to rotate.
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Swaps which shader we are using and applies it.
- */
-function changeShader() {
- var shaderNumber = document.getElementById("shaderSelect").value;
- g_shaderSelection = parseFloat(shaderNumber);
- applyShader(g_pack, g_shaderSelection);
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<h1 id="h">Shader Test</h1>
-This example is useful for testing a shader or checking a scene. Clicking on the scene will temporarily stop rotation.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 100%; height: 80%;"></div>
-<!-- End of O3D plugin -->
-<p>
-<div id='shaderDiv'></div>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/shadow-map.html b/o3d/samples/o3d-webgl-samples/shadow-map.html
deleted file mode 100644
index 77fca20..0000000
--- a/o3d/samples/o3d-webgl-samples/shadow-map.html
+++ /dev/null
@@ -1,620 +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 sample uses a custom render graph to implement a basic shadow map
-algorithm.
-
-The technique works by rendering the scene in two passes. The first pass
-renders the geometry in the scene with a shader that colors each pixel a shade
-of gray representing how far the rendered point is from the light source. That
-image, the shadow map, is rendered to a texture, and then the second (visible)
-render pass samples it to determine which points in the scene are in shaodow.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Shadow Mapping
-</title>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.debug');
-o3djs.require('o3djs.material');
-
-// The initClient() function runs when the page has finished loading.
-window.onload = initClient;
-
-// global variables
-var g_o3dElement;
-var g_client;
-var g_o3d;
-var g_math;
-var g_pack;
-var g_colorViewInfo;
-var g_shadowViewInfo;
-var g_shadowTexture;
-var g_shadowMaterial;
-var g_colorEffect;
-var g_shadowSampler;
-var g_lightViewProjection;
-var g_lightFrustumTransform;
-var g_globalParams = { };
-var g_viewFromLight = false;
-
-var g_renderSurfaceSet;
-var g_colorPassRenderRoot;
-
-var g_lightWorldPos = [5, 10, 0];
-var g_lightColor = [1, 1, 1, 1];
-var g_eyePosition = [1, 6, 20];
-var g_targetPosition = [0, 2, 0];
-
-// constants.
-var SHADOW_MAP_WIDTH = 512;
-var SHADOW_MAP_HEIGHT = 512;
-
-var g_finished = false; // for selenium testing.
-
-
-/**
- * Creates the client area.
- */
-function initClient() {
- o3djs.webgl.makeClients(main, 'FloatingPointTextures', true);
-}
-
-
-/**
- * Initializes global variables, positions camera, draws shapes.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function main(clientElements) {
- // Init global variables.
- initGlobals(clientElements);
-
- // Set up the rendergraph.
- initRenderGraph();
-
- // Load effects, bind material parameters.
- initMaterials();
-
- // Add the shapes to the transform graph.
- createShapes();
-
- // Set up the view and projection transformations for the camera.
- updateCamera();
-
- // Init global parameters. initGlobalParams() searches all materials in order
- // to bind parameters, so it must be called after initMaterials()
- initGlobalParams();
-
- // Set the view and projection transformations for the light.
- updateLightMatrix();
-
- // Create the light that gets drawn.
- createLightShape();
-
- // Execute keyPressed() when we detect a keypress on the window or
- // on the o3d object.
- window.document.onkeypress = keyPressed;
- g_o3dElement.onkeypress = keyPressed;
-
- //toggleView();
-
- g_finished = true; // for selenium testing.
-}
-
-
-/**
- * Initializes global variables and libraries.
- */
-function initGlobals(clientElements) {
- g_o3dElement = clientElements[0];
- g_client = g_o3dElement.client;
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-}
-
-
-/**
- * Sets up the render graph. Builds a basic view for the camera and the light
- * point of view, arranges for the view from the light to be rendered to a
- * texture for the shadow map. Unlike the basic render graph created by the
- * the utility function o3djs.rendergraph.createBasicView, to render the shadow
- * map and then render the scene, we need two subtrees of the render graph, one
- * for shadow map render pass and one to draw the scene.
- */
-function initRenderGraph() {
- // The children of any one node in the render graph get traversed in order by
- // priority. Here, we're forcing the shadow map to get rendered first by
- // by giving its render root lower priority.
- var shadowPassRenderRoot = g_pack.createObject('RenderNode');
- shadowPassRenderRoot.priority = 0;
-
- g_colorPassRenderRoot = g_pack.createObject('RenderNode');
- g_colorPassRenderRoot.priority = 1;
-
- g_colorPassRenderRoot.parent = g_client.renderGraphRoot;
-
- // Create the texture that will store the depth information.
- g_shadowTexture = g_pack.createTexture2D(SHADOW_MAP_WIDTH,
- SHADOW_MAP_HEIGHT,
- g_o3d.Texture.ABGR32F,
- 1,
- true);
- var renderSurface = g_shadowTexture.getRenderSurface(0);
-
- // Create the depth-stencil buffer required when rendering the teapot.
- var depthSurface = g_pack.createDepthStencilSurface(SHADOW_MAP_WIDTH,
- SHADOW_MAP_HEIGHT);
-
- shadowPassRenderRoot.parent = g_client.renderGraphRoot;
-
- g_renderSurfaceSet = g_pack.createObject('RenderSurfaceSet');
- g_renderSurfaceSet.renderSurface = renderSurface;
- g_renderSurfaceSet.renderDepthStencilSurface = depthSurface;
-
- g_renderSurfaceSet.parent = shadowPassRenderRoot;
-
- // Create a render sub-graph for the shadow map generation.
- g_shadowViewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_renderSurfaceSet,
- [1, 1, 1, 1]);
-
- // Create a render sub-graph for the regular pass.
- g_colorViewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_colorPassRenderRoot,
- [0, 0, 0, 1]);
-}
-
-
-/**
- * Switches between the camera and light point of view.
- */
-function toggleView() {
- if (g_viewFromLight) {
- g_shadowViewInfo.root.parent = g_renderSurfaceSet;
- g_colorPassRenderRoot.parent = g_client.renderGraphRoot;
- g_viewFromLight = false;
- } else {
- g_shadowViewInfo.root.parent = g_client.renderGraphRoot;
- g_colorPassRenderRoot.parent = null;
- g_viewFromLight = true;
- }
-}
-
-/**
- * Creates a material to be put on all shapes in the scene for the shadow pass,
- * and loads effects for materials in the scene. Other materials are created
- * on the fly as the shapes are created.
- */
-function initMaterials() {
- var colorVertexShader = document.getElementById('colorVertexShader').text;
- var colorPixelShader = document.getElementById('colorPixelShader').text;
-
- g_colorEffect = g_pack.createObject('Effect');
- g_colorEffect.loadVertexShaderFromString(colorVertexShader);
- g_colorEffect.loadPixelShaderFromString(colorPixelShader);
-
- var shadowVertexShader = document.getElementById('shadowVertexShader').text;
- var shadowPixelShader = document.getElementById('shadowPixelShader').text;
-
- g_shadowMaterial = g_pack.createObject('Material');
- g_shadowMaterial.drawList = g_shadowViewInfo.performanceDrawList;
-
- var shadowEffect = g_pack.createObject('Effect');
- shadowEffect.loadVertexShaderFromString(shadowVertexShader);
- shadowEffect.loadPixelShaderFromString(shadowPixelShader);
-
- g_shadowMaterial.effect = shadowEffect;
- shadowEffect.createUniformParameters(g_shadowMaterial);
-
- g_shadowSampler = g_pack.createObject('Sampler');
- g_shadowSampler.texture = g_shadowTexture;
- g_shadowSampler.minFilter = g_o3d.Sampler.POINT;
- g_shadowSampler.magFilter = g_o3d.Sampler.POINT;
- g_shadowSampler.mipFilter = g_o3d.Sampler.POINT;
- // Note: The o3d-plugin used BORDER as address mode, but that is not available
- // in WebGL so use WRAP instead.
- g_shadowSampler.addressModeU = g_o3d.Sampler.WRAP;
- g_shadowSampler.addressModeV = g_o3d.Sampler.WRAP;
- //g_shadowSampler.borderColor = [1, 1, 1, 1];
-}
-
-
-/**
- * Sets up reasonable view and projection matrices.
- */
-function updateCamera() {
- // Set up a perspective transformation for the projection.
- g_colorViewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree frustum.
- g_o3dElement.clientWidth / g_o3dElement.clientHeight, // Aspect ratio.
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // cube is located.
- g_colorViewInfo.drawContext.view = g_math.matrix4.lookAt(
- g_eyePosition, // eye
- g_targetPosition, // target
- [0, 1, 0]); // up
-}
-
-
-/**
- * Computes the view and projection matrices from the point of view of the
- * light. Sets the lightViewProjection parameter so the color shader can access
- * it.
- */
-function updateLightMatrix() {
- // The perspective projection matrix for the light.
- var lightProjection = g_math.matrix4.perspective(
- g_math.degToRad(45), // 45 degree fov.
- SHADOW_MAP_WIDTH / SHADOW_MAP_HEIGHT, // Aspect ratio.
- 4, // Near plane.
- 20); // Far plane.
-
- // Make the light point toward the origin
- var lightView = g_math.matrix4.lookAt(
- g_lightWorldPos, // light
- [0, 0, 0], // target
- [1, 0, 0]); // up
-
- g_lightViewProjection = g_math.matrix4.composition(
- lightProjection, lightView);
-
- g_shadowViewInfo.drawContext.projection = lightProjection;
- g_shadowViewInfo.drawContext.view = lightView;
- g_globalParams.lightViewProjection.value = g_lightViewProjection;
-}
-
-
-/**
- * Creates shapes using the primitives utility library, and adds them to the
- * transform graph at the root node.
- */
-function createShapes() {
- // A green phong-shaded material for the cube.
- var cubeMaterial = createColorMaterial([0.2, 0.5, 0, 1]);
-
- // The cube shape.
- var cube = o3djs.primitives.createCube(
- g_pack,
- cubeMaterial,
- 2); // The length of each side of the cube.
-
- // A red phong-shaded material for the sphere.
- var sphereMaterial = createColorMaterial([0.7, 0.2, 0.1, 1]);
-
- // The sphere shape.
- var sphere = o3djs.primitives.createSphere(
- g_pack, sphereMaterial, 0.5, 50, 50);
-
- // A blue phong-shaded material for the plane.
- var planeMaterial = createColorMaterial([0, 0.3, 0.5, 1]);
-
- // The plane shape.
- var plane = o3djs.primitives.createPlane(
- g_pack,
- planeMaterial,
- 20, // Width.
- 20, // Depth.
- 1, // Horizontal subdivisions.
- 1); // Vertical subdivisions.
-
- // Associate to each shape, a translation vector.
- var transformTable = [
- {shape: cube, translation: [0, 1, 0]},
- {shape: sphere, translation: [0.5, 2.5, 0]},
- {shape: plane, translation: [0, 0, 0]}
- ];
-
- // Add the shapes to the transform graph with the translation.
- var modelRoot = g_pack.createObject('Transform');
- modelRoot.parent = g_client.root;
- for (var tt = 0; tt < transformTable.length; ++tt) {
- var transform = g_pack.createObject('Transform');
- transform.addShape(transformTable[tt].shape);
- // The shadow material is bound to a DrawList in the subtree of the
- // rendergraph that handles the shadow map generation, so it gets drawn in
- // that render pass only.
- transformTable[tt].shape.createDrawElements(g_pack, g_shadowMaterial);
-
- transform.translate(transformTable[tt].translation);
- transform.parent = modelRoot;
- }
-}
-
-
-/**
- * Creates the wireframe frustum showing the shadow map's render volume.
- */
-function createLightShape() {
- var inverseMatrix = g_math.matrix4.inverse(g_lightViewProjection);
-
- var shape = o3djs.lineprimitives.createLineCube(
- g_pack, o3djs.material.createConstantMaterial(g_pack, g_colorViewInfo,
- [1, 0, 0, 1]), 2);
-
- g_lightFrustumTransform = g_pack.createObject('Transform');
- g_lightFrustumTransform.localMatrix = inverseMatrix;
- g_lightFrustumTransform.parent = g_client.root;
- g_lightFrustumTransform.addShape(shape);
-}
-
-
-/**
- * Creates a Phong-shaded, shadowed material based on the given color.
- */
-function createColorMaterial(baseColor) {
- var material = g_pack.createObject('Material');
- material.drawList = g_colorViewInfo.performanceDrawList;
-
- material.effect = g_colorEffect;
- g_colorEffect.createUniformParameters(material);
-
- material.getParam('shadowMapSampler').value = g_shadowSampler;
-
- material.getParam('ambient').value = g_math.mulScalarVector(0.1, baseColor);
- material.getParam('diffuse').value = g_math.mulScalarVector(0.8, baseColor);
- material.getParam('specular').value = [1, 1, 1, 1];
- material.getParam('shininess').value = 20;
-
- return material;
-}
-
-/**
- * Binds params for light position, light color and the light view-projection
- * matrix to all materials in the scene where they apply.
- */
-function initGlobalParams() {
- var paramSpec = {
- 'lightColor': 'ParamFloat4',
- 'lightWorldPos': 'ParamFloat3',
- 'lightViewProjection': 'ParamMatrix4'};
-
- g_globalParams = o3djs.material.createParams(g_pack, paramSpec);
- o3djs.material.bindParams(g_pack, g_globalParams);
-
- g_globalParams.lightWorldPos.value = g_lightWorldPos;
- g_globalParams.lightColor.value = g_lightColor;
-}
-
-
-/**
- * The keyboard event handler.
- */
-function keyPressed(event) {
- var keyChar = String.fromCharCode(o3djs.event.getEventKeyChar(event));
- keyChar = keyChar.toLowerCase();
-
- var delta = 0.2;
- switch(keyChar) {
- case 'a':
- moveLight([-delta, 0, 0]);
- break;
- case 'd':
- moveLight([delta, 0, 0]);
- break;
- case 's':
- moveLight([0, -delta, 0]);
- break;
- case 'w':
- moveLight([0, delta, 0]);
- break;
- case 'i':
- moveLight([0, 0, delta]);
- break;
- case 'o':
- moveLight([0, 0, -delta]);
- break;
-
- case ' ':
- toggleView();
- break;
- }
-}
-
-/**
- * Moves the light by the given vector delta, and updates params so the light
- * draws in the right spot and the shadows move.
- */
-function moveLight(delta) {
- g_lightWorldPos = g_math.addVector(g_lightWorldPos, delta);
- g_globalParams.lightWorldPos.value = g_lightWorldPos;
- updateLightMatrix();
- g_lightFrustumTransform.localMatrix =
- g_math.matrix4.inverse(g_lightViewProjection);
-}
-
-
-</script>
-
-
-
-<script id="shadowVertexShader" type="text/glsl">
- /**
- * This shader is for the effect applied in the first render pass, when the
- * shadow map is created. The scene is rendered from the perspective of the
- * light, the grayscale value of each pixel in the rendered image represents
- * how far away the rendered point is from the light (the lighter, the
- * farther) This image gets rendered to a texture, and that texture gets
- * sampled in the second render pass, when the geometry is drawn to the
- * screen.
- */
- attribute vec4 position;
- uniform mat4 worldViewProjection;
-
- varying vec4 vposition;
-
- void main() {
- vposition = worldViewProjection * position;
- gl_Position = vposition;
- }
-</script>
-<script id="shadowPixelShader" type="text/glsl">
- varying vec4 vposition;
-
- void main() {
- vec4 color;
- vec3 q = vposition.xyz / vposition.w;
-
- float depth = 0.5*(q.z + 1.0);
- color.r = fract(16777216.0 * depth);
- color.g = fract(65536.0 * depth);
- color.b = fract(256.0 * depth);
- color.a = depth;
-
- gl_FragColor = color;
- }
-</script>
-
-
-<script id="colorVertexShader" type="text/glsl">
- attribute vec4 position;
- attribute vec3 normal;
-
- uniform mat4 worldViewProjection;
- uniform mat4 world;
- uniform mat4 worldInverseTranspose;
- uniform mat4 lightViewProjection;
-
- varying vec4 vposition;
- varying vec3 vnormal;
- varying vec4 vprojTextureCoords;
- varying vec4 vworldPosition;
-
- /**
- * The vertex shader simply transforms the input vertices to screen space.
- */
- void main() {
- vworldPosition = world * position;
- vnormal = vec3(worldInverseTranspose * vec4(normal, 0));
- vposition = worldViewProjection * position;
- vprojTextureCoords = lightViewProjection * world * position;
- gl_Position = vposition;
- }
-</script>
-<script id="colorPixelShader" type="text/glsl">
- uniform vec4 ambient;
- uniform vec4 diffuse;
- uniform vec4 specular;
- uniform float shininess;
-
- varying vec4 vposition;
- varying vec4 vworldPosition;
- varying vec3 vnormal;
- varying vec4 vprojTextureCoords;
-
- uniform sampler2D shadowMapSampler;
-
- uniform vec3 lightWorldPos;
- uniform mat4 viewInverse;
-
- vec3 lighting(vec3 position, vec3 normal, vec4 pigment, vec4 specular, float shininess) {
- vec3 l = normalize(vec3(lightWorldPos) - position); // Toward light.
- vec3 n = normalize(normal); // Normal.
- vec3 v = normalize(vec3(viewInverse * vec4(0,0,0,1)) - position); // Toward eye.
- vec3 r = normalize(-reflect(v, n));
-
- return clamp(dot(n,l), 0.0, 1.0) * diffuse.rgb +
- 0.2 * specular.rgb * pow(max(dot(l, r), 0.0), shininess);
- }
-
- void main() {
- vec3 outColor = ambient.rgb;
- vec4 projCoords = vprojTextureCoords;
-
- // Convert texture coords to [0, 1] range.
- projCoords /= projCoords.w;
- projCoords = 0.5 * projCoords + 0.5;
-
- float depth = projCoords.z;
- float light;
-
- // If the rednered point is farther from the light than the distance encoded
- // in the shadow map, we give it a light coefficient of 0.
- vec4 color = texture2D(shadowMapSampler, projCoords.xy);
-
- light = (color.a +
- color.b / 256.0 +
- color.g / 65536.0 +
- color.r / 16777216.0) + 0.008 > depth ? 1.0 : 0.0;
-
- // Make the illuninated area a round spotlight shape just for fun.
- // Comment this line out to see just the shadows.
- light *= 1.0 - smoothstep(0.45, 0.5,
- length(projCoords.xy - vec2(0.5, 0.5)));
-
- outColor += light * lighting(
- vec3(vworldPosition),
- vnormal,
- diffuse,
- specular,
- shininess);
-
- gl_FragColor = vec4(outColor, 1.0);
- }
-</script>
-
-
-
-</head>
-<body>
-<h1>Shadow Maps</h1>
-This sample implements a basic shadow map.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-Use A, S, D, W, I and O to move the light.
-Press spacebar to see the shadow map.
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/simpleviewer/simpleviewer.html b/o3d/samples/o3d-webgl-samples/simpleviewer/simpleviewer.html
deleted file mode 100644
index 81264c1..0000000
--- a/o3d/samples/o3d-webgl-samples/simpleviewer/simpleviewer.html
+++ /dev/null
@@ -1,377 +0,0 @@
-<!--
-Copyright 2010, 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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
- <title>
- Simple Scene Viewer
- </title>
-<style type="text/css">
-html, body {
- margin: 0;
- padding: 0;
- border: 0;
- height: 100%;
-}
-</style>
-</head>
-<body onload="init();" onunload="uninit();">
-<script type="text/javascript" src="../../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.arcball');
-o3djs.require('o3djs.scene');
-
-var g_root;
-var g_o3d;
-var g_math;
-var g_quaternions;
-var g_client;
-var g_aball;
-var g_thisRot;
-var g_lastRot;
-var g_pack = null;
-var g_mainPack;
-var g_viewInfo;
-var g_lightPosParam;
-var g_loadingElement;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-var g_o3dElement;
-var g_finished = false; // for selenium
-
-var g_camera = {
- farPlane: 5000,
- nearPlane:0.1
-};
-
-var g_dragging = false;
-
-
-function startDragging(e) {
- g_lastRot = g_thisRot;
-
- g_aball.click([e.x, e.y]);
-
- g_dragging = true;
-}
-
-function drag(e) {
- if (g_dragging) {
- var rotationQuat = g_aball.drag([e.x, e.y]);
- var rot_mat = g_quaternions.quaternionToRotation(rotationQuat);
- g_thisRot = g_math.matrix4.mul(g_lastRot, rot_mat);
-
- var m = g_root.localMatrix;
- g_math.matrix4.setUpper3x3(m, g_thisRot);
- g_root.localMatrix = m;
- }
-}
-
-function stopDragging(e) {
- g_dragging = false;
-}
-
-function updateCamera() {
- var up = [0, 1, 0];
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(g_camera.eye,
- g_camera.target,
- up);
- g_lightPosParam.value = g_camera.eye;
-}
-
-function updateProjection() {
- // Create a perspective projection matrix.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), g_o3dWidth / g_o3dHeight, g_camera.nearPlane,
- g_camera.farPlane);
-}
-
-function scrollMe(e) {
- if (e.deltaY) {
- var t = 1;
- if (e.deltaY > 0)
- t = 11 / 12;
- else
- t = 13 / 12;
- g_camera.eye = g_math.lerpVector(g_camera.target, g_camera.eye, t);
-
- updateCamera();
- }
-}
-
-function enableInput(enable) {
- document.getElementById("url").disabled = !enable;
- document.getElementById("load").disabled = !enable;
-}
-
-function loadFile(context, path) {
- function callback(pack, parent, exception) {
- enableInput(true);
- if (exception) {
- alert("Could not load: " + path + "\n" + exception);
- g_loadingElement.innerHTML = "loading failed.";
- } else {
- g_loadingElement.innerHTML = "loading finished.";
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
- var bbox = o3djs.util.getBoundingBoxOfTree(g_client.root);
- g_camera.target = g_math.lerpVector(bbox.minExtent, bbox.maxExtent, 0.5);
- var diag = g_math.length(g_math.subVector(bbox.maxExtent,
- bbox.minExtent));
- g_camera.eye = g_math.addVector(g_camera.target, [0, 0, 1.5 * diag]);
- g_camera.nearPlane = diag / 1000;
- g_camera.farPlane = diag * 10;
- setClientSize();
- updateCamera();
- updateProjection();
-
- // Manually connect all the materials' lightWorldPos params to the context
- var materials = pack.getObjectsByClassName('o3d.Material');
- for (var m = 0; m < materials.length; ++m) {
- var material = materials[m];
- var param = material.getParam('lightWorldPos');
- if (param) {
- param.bind(g_lightPosParam);
- }
- }
-
- g_finished = true; // for selenium
-
- // Comment out the next line to dump lots of info.
- if (false) {
- o3djs.dump.dump('---dumping context---\n');
- o3djs.dump.dumpParamObject(context);
-
- o3djs.dump.dump('---dumping root---\n');
- o3djs.dump.dumpTransformTree(g_client.root);
-
- o3djs.dump.dump('---dumping render root---\n');
- o3djs.dump.dumpRenderNodeTree(g_client.renderGraphRoot);
-
- o3djs.dump.dump('---dump g_pack shapes---\n');
- var shapes = pack.getObjectsByClassName('o3d.Shape');
- for (var t = 0; t < shapes.length; t++) {
- o3djs.dump.dumpShape(shapes[t]);
- }
-
- o3djs.dump.dump('---dump g_pack materials---\n');
- var materials = pack.getObjectsByClassName('o3d.Material');
- for (var t = 0; t < materials.length; t++) {
- o3djs.dump.dump (
- ' ' + t + ' : ' + materials[t].className +
- ' : "' + materials[t].name + '"\n');
- o3djs.dump.dumpParams(materials[t], ' ');
- }
-
- o3djs.dump.dump('---dump g_pack textures---\n');
- var textures = pack.getObjectsByClassName('o3d.Texture');
- for (var t = 0; t < textures.length; t++) {
- o3djs.dump.dumpTexture(textures[t]);
- }
-
- o3djs.dump.dump('---dump g_pack effects---\n');
- var effects = pack.getObjectsByClassName('o3d.Effect');
- for (var t = 0; t < effects.length; t++) {
- o3djs.dump.dump (' ' + t + ' : ' + effects[t].className +
- ' : "' + effects[t].name + '"\n');
- o3djs.dump.dumpParams(effects[t], ' ');
- }
- }
- }
- }
-
- g_pack = g_client.createPack();
-
- // Create a new transform for the loaded file
- var parent = g_pack.createObject('Transform');
- parent.parent = g_client.root;
- if (path != null) {
- g_loadingElement.innerHTML = "Loading: " + path;
- enableInput(false);
- try {
- var secondCounter = g_pack.createObject('SecondCounter');
- secondCounter.countMode = o3d.Counter.CYCLE;
- secondCounter.start = 0;
- secondCounter.end = 1;
- o3djs.scene.loadScene(g_client, g_pack, parent, path, callback,
- {opt_animSource: secondCounter.getParam('count')});
- } catch (e) {
- enableInput(true);
- g_loadingElement.innerHTML = "loading failed : " + e;
- }
- }
- return parent;
-}
-
-function setClientSize() {
- var newWidth = parseInt(g_client.width);
- var newHeight = parseInt(g_client.height);
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- updateProjection();
-
- // Sets a new area size for arcball.
- g_aball.setAreaSize(g_o3dWidth, g_o3dHeight);
- }
-}
-
-/**
- * Called every frame.
- */
-function onRender() {
- // If we don't check the size of the client area every frame we don't get a
- // chance to adjust the perspective matrix fast enough to keep up with the
- // browser resizing us.
- setClientSize();
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
- // The following call enables a debug WebGL context, which makes
- // debugging much easier.
- // o3djs.webgl.makeClients(initStep2, undefined, undefined, undefined, undefined, undefined, true);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- // Point at the parent directory's assets directory for the moment
- path = path.substring(0, index+1) + '../../simpleviewer/assets/cube/scene.json';
- var url = document.getElementById("url").value = path;
- g_loadingElement = document.getElementById('loading');
-
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_quaternions = o3djs.quaternions;
- g_client = g_o3dElement.client;
-
- g_mainPack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_mainPack,
- g_client.root,
- g_client.renderGraphRoot);
-
- g_lastRot = g_math.matrix4.identity();
- g_thisRot = g_math.matrix4.identity();
-
- var root = g_client.root;
-
- g_aball = o3djs.arcball.create(100, 100);
- setClientSize();
-
- // Set the light at the same position as the camera to create a headlight
- // that illuminates the object straight on.
- var paramObject = g_mainPack.createObject('ParamObject');
- g_lightPosParam = paramObject.createParam('lightWorldPos', 'ParamFloat3');
- g_camera.target = [0, 0, 0];
- g_camera.eye = [0, 0, 5];
- updateCamera();
-
- doload()
-
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', startDragging);
- o3djs.event.addEventListener(g_o3dElement, 'mousemove', drag);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', stopDragging);
- o3djs.event.addEventListener(g_o3dElement, 'wheel', scrollMe);
-
- g_client.setRenderCallback(onRender);
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-function doload() {
- if (g_root) {
- g_root.parent = null;
- g_root = null;
- }
- if (g_pack) {
- g_pack.destroy();
- g_pack = null;
- }
- var url = document.getElementById('url').value;
- g_root = loadFile(g_viewInfo.drawContext, url);
-}
-</script>
-<table width="100%" style="height:100%;">
- <tr><td valign="middle" align="center" height="100%">
-<table width="100%" style="height:100%;"><tr><td height="100%">
-<h1>
-Simple Scene Viewer
-</h1>
-<table id="container" width="90%" style="height:60%;" border="2"><tr><td height="100%">
-<div id="o3d" style="width: 100%; height: 100%;"></div>
-</td></tr></table>
-<p>
-</p>
-
-<input type="text" id="url" size="100">
-<input type="button" id="load" onclick="doload();" value="load"><BR>
-
-Drag The Mouse To Rotate<br/>
-Scrollwheel To Zoom<br/>
-Resize The Window To Resize The View
-<div style="color: red;" id="loading"></div>
-</td></tr></table>
-</td></tr></table>
-</body>
-</html>
-
-
diff --git a/o3d/samples/o3d-webgl-samples/skinning.html b/o3d/samples/o3d-webgl-samples/skinning.html
deleted file mode 100644
index 0b4e91e..0000000
--- a/o3d/samples/o3d-webgl-samples/skinning.html
+++ /dev/null
@@ -1,278 +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.
--->
-
-<!--
-O3D Skinning example.
-
-Shows a simple skinned cylinder.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Skinning.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-
-o3djs.base.o3d = o3d;
-
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.primitives');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// constants
-var NUM_BONES = 11;
-var BONE_SPACING = 20;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_transforms = [];
-var g_finished = false; // for selenium testing.
-var g_clock = 0;
-var g_timeMult = 1;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 10000);
-
- // Create a material.
- var material = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [1, 0.2, 1, 1]);
-
- // Create a cylinder.
- var vertexInfo = o3djs.primitives.createCylinderVertices(
- 40, 200, 120, 200,
- o3djs.math.makeMatrix4(
- 1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 1, 0,
- 0, 100, 0, 1));
- var shape = vertexInfo.createShape(g_pack, material);
-
- // Create an ParamArray to hold matrices for skinning.
- var matrices = g_pack.createObject('ParamArray');
-
- // Create a Skin to hold the influences and bind pose.
- var skin = g_pack.createObject('Skin');
-
- // Create a SkinEval to use the Skin.
- var skinEval = g_pack.createObject('SkinEval');
-
- // Tell the SkinEval which matrices and Skin to use.
- skinEval.matrices = matrices;
- skinEval.skin = skin;
-
- // Create matrices on our ParamArray.
- matrices.resize(NUM_BONES, 'o3d.ParamMatrix4');
-
- // Create 11 transforms for the bones and parent them into a chain.
- for (var ii = 0; ii < NUM_BONES; ++ii) {
- var transform = g_pack.createObject('Transform');
- g_transforms[ii] = transform;
- if (ii > 0) {
- transform.translate(0, BONE_SPACING, 0);
- }
- transform.parent = ii == 0 ? g_client.root : g_transforms[ii - 1];
- // Bind the world matrix of the transform to the corresponding matrix in the
- // ParamArray.
- matrices.getParam(ii).bind(transform.getParam('worldMatrix'));
- // Store the inverse world matrix of each transform as the bind pose for the
- // skin.
- skin.setInverseBindPoseMatrix(ii, g_math.inverse(
- transform.getUpdatedWorldMatrix()));
- }
-
- // Add the cylinder to the root transform.
- g_transforms[0].addShape(shape);
-
- // Skinning happens in world space so bind the transform of the shape
- // to the SkinEval so it can put our skin in object space.
- skinEval.getParam('base').bind(g_transforms[0].getParam('worldMatrix'));
-
- // Make our source data for skinning and setup the influences for each bone.
- // We only need the position and normals.
- var positions = [];
- var normals = [];
- var positionStream = vertexInfo.findStream(g_o3d.Stream.POSITION);
- var normalStream = vertexInfo.findStream(g_o3d.Stream.NORMAL);
- var numVertices = positionStream.numElements();
- for (var ii = 0; ii < numVertices; ++ii) {
- // Choose the bones to influence the vertex based on its height.
- // boneArea will be a fractional value between 2 bones based on the Y
- // position of the vertex. In other words, if the y Position of the vertex
- // 63 and the bones are 20 units apart then boneArea will = 6.15 meaning
- // it's between bones 6 and 7
- var boneArea = positionStream.getElementVector(ii)[1] / BONE_SPACING;
-
- // Pull out the fractional part of boneArea
- var influence = boneArea % 1;
-
- // Compute the bone indicies
- var bone1 = Math.floor(boneArea);
- var bone2 = bone1 + 1;
- if (bone2 >= NUM_BONES) {
- bone2 = NUM_BONES - 1;
- }
-
- // Now make each vertex be influenced by these two bones. In the example
- // above where boneArea was 6.15 we let bone1 influence the vertex by
- // (1 - 0.15) or 0.85 and bone2 influence it by 0.15.
- skin.setVertexInfluences(ii, [bone1, 1 - influence, bone2, influence]);
- }
-
- // Create a SourceBuffer for the Skin and set the vertices on it.
- var sourceBuffer = g_pack.createObject('SourceBuffer');
- var positionField = sourceBuffer.createField('FloatField', 3);
- var normalField = sourceBuffer.createField('FloatField', 3);
- sourceBuffer.allocateElements(numVertices);
- positionField.setAt(0, positionStream.elements);
- normalField.setAt(0, normalStream.elements);
-
- // Tell the skinEval how to use the SourceBuffer
- skinEval.setVertexStream(g_o3d.Stream.POSITION,
- 0,
- positionField,
- 0);
- skinEval.setVertexStream(g_o3d.Stream.NORMAL,
- 0,
- normalField,
- 0);
-
- // Bind the Primitive's position and normal streams
- // to the SkinEval so the SkinEval will fill them in each frame.
- var streamBank = shape.elements[0].streamBank;
- streamBank.bindStream(skinEval, g_o3d.Stream.POSITION, 0);
- streamBank.bindStream(skinEval, g_o3d.Stream.NORMAL, 0);
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Info for rendering.
- */
-function onrender(renderEvent) {
- // Get the number of seconds since the last render.
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- var x = Math.sin(g_clock * 0.3) * 400;
- var z = Math.cos(g_clock * 0.3) * 400;
- var y = Math.sin(g_clock * 0.7) * 50 + 100;
-
- // spin the camera.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [x, y, z], // eye
- [0, 100, 0], // target
- [0, 1, 0]); // up
-
- // Make our bone chain bend.
- var rotation = Math.PI / g_transforms.length * Math.sin(g_clock * 1);
- for (var ii = 1; ii < g_transforms.length; ++ii) {
- var transform = g_transforms[ii];
- transform.identity();
- transform.translate(0, BONE_SPACING, 0);
- transform.rotateX(rotation);
- }
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Skinning</h1>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/sobel.html b/o3d/samples/o3d-webgl-samples/sobel.html
deleted file mode 100644
index b7105d3..0000000
--- a/o3d/samples/o3d-webgl-samples/sobel.html
+++ /dev/null
@@ -1,339 +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 sample shows how to create a Sobel edge-detect image processing shader,
-using render targets.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-O3D: Sobel Shader Sample
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-window.onunload = uninit;
-
-// constants.
-var RENDER_TARGET_WIDTH = 512;
-var RENDER_TARGET_HEIGHT = 512;
-
-// global variables
-var g_o3d;
-var g_client;
-var g_math;
-var g_pack;
-var g_teapotRoot;
-var g_renderGraphRoot;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-
-/**
- * Loads a scene into the transform graph, and prepares its elements for
- * insertion into the render graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo who's view and projection will
- * be set from the scene after it's loaded.
- */
-function loadScene(pack, fileName, parent, viewInfo) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the scene given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT);
-
- // Copy the view and projection to the passed in viewInfo structure..
- viewInfo.drawContext.view = cameraInfo.view;
- viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, viewInfo);
-
- g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3d = clientElements[0];
- g_o3d = o3d.o3d;
- g_math = o3djs.math;
- g_client = o3d.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the texture required for the color render-target.
- var texture = g_pack.createTexture2D(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT,
- g_o3d.Texture.XRGB8, 1, true);
-
- g_teapotRoot = g_pack.createObject('Transform');
-
- var renderGraphRoot = g_client.renderGraphRoot;
-
- var renderSurfaceSet = createRenderSurfaceSet(texture);
-
- // Create the render graph for the teapot view, drawing the teapot into
- // texture (via renderSurfaceSet).
- var teapotViewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_teapotRoot,
- renderSurfaceSet,
- [1, 1, 1, 1]);
-
- var renderNode = createSobelPass(texture, g_client.renderGraphRoot);
-
- // Load the scene into the transform graph as a child g_teapotRoot
- loadScene(g_pack, '../assets/teapot/scene.json', g_teapotRoot, teapotViewInfo);
-
- // Set a render callback.
- g_client.setRenderCallback(onRender);
-}
-
-function createSobelMaterial(viewInfo, kernelSize) {
- var convFXString = document.getElementById('convFX').value;
- var convEffect = g_pack.createObject('Effect');
- convEffect.loadFromFXString(convFXString);
-
- var convMaterial = g_pack.createObject('Material');
- convMaterial.drawList = viewInfo.performanceDrawList;
- convMaterial.effect = convEffect;
- convEffect.createUniformParameters(convMaterial);
- return convMaterial;
-}
-
-function createRenderSurfaceSet(texture) {
- var renderSurface = texture.getRenderSurface(0);
-
- // Create the depth-stencil buffer required when rendering this pass.
- var depthSurface = g_pack.createDepthStencilSurface(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT);
-
- var renderSurfaceSet = g_pack.createObject('RenderSurfaceSet');
- renderSurfaceSet.renderSurface = renderSurface;
- renderSurfaceSet.renderDepthStencilSurface = depthSurface;
- renderSurfaceSet.parent = g_client.renderGraphRoot;
- return renderSurfaceSet;
-}
-
-function createSobelPass(srcTexture, renderGraphRoot) {
- // Create a root Transform for the image processing scene.
- var root = g_pack.createObject('Transform');
-
- // Create a basic view for the image processing scene.
- var viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- root,
- renderGraphRoot,
- [1, 1, 1, 1]);
-
- var material = createSobelMaterial(viewInfo);
- var quadShape = o3djs.primitives.createPlane(g_pack,
- material,
- 2.0,
- 2.0,
- 1,
- 1);
-
- // Attach the quad to the image processing scene.
- root.addShape(quadShape);
-
- // Rotate the view so we're looking at the XZ plane (where our quad is)
- // Point the camera along the -Y axis
- var target = [0, -1, 0];
- // Put the camera at the origin.
- var eye = [0, 0, 0];
- // Define the up-vector as +Z
- var up = [0, 0, 1];
- viewInfo.drawContext.view = g_math.matrix4.lookAt(eye, target, up);
-
- // Create an orthographic projection.
- viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -1, 1, -1, 1, -1, 1);
-
- // Generate draw elements and setup material draw lists for the
- // image processing scene.
- o3djs.pack.preparePack(g_pack, viewInfo);
-
- setSobelParameters(material, srcTexture);
- return renderGraphRoot;
-}
-
-function setSobelParameters(material, texture) {
- var imageParam = material.getParam('image');
- var imageIncrement = material.getParam('imageIncrement');
- var sampler = g_pack.createObject('Sampler');
- sampler.texture = texture;
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
- sampler.minFilter = g_o3d.Sampler.POINT;
- sampler.magFilter = g_o3d.Sampler.POINT;
- sampler.mipFilter = g_o3d.Sampler.NONE;
- imageParam.value = sampler;
- imageIncrement.value = [1.0 / texture.width, 1.0 / texture.height];
-}
-
-/**
- * Called every frame.
- * @param {o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- g_teapotRoot.identity();
- g_teapotRoot.rotateX(g_clock);
- g_teapotRoot.rotateY(g_clock * 1.3);
-}
-
-/**
- * Cleanup before exiting.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Sobel Edge Detection Shader Example</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 512px; height: 512px;"></div>
-<!-- End of O3D plugin -->
-<!--
- We embed the code for our effect inside this hidden textarea.
- Effects contain the functions that define
- the vertex and pixel shaders used by our shape.
--->
-<!-- Don't render the textarea -->
-<div style="display:none">
-<textarea id="convFX" name="convFX" cols="80" rows="20">
-uniform mat4 worldViewProjection;
-
-attribute vec4 position;
-attribute vec2 texCoord0;
-
-varying vec2 v_imageCoord;
-
-void main() {
- gl_Position = worldViewProjection * position;
- v_imageCoord = texCoord0;
-}
-
-// #o3d SplitMarker
-uniform sampler2D image;
-uniform vec2 imageIncrement;
-
-varying vec2 v_imageCoord;
-
-float lum(vec4 c) {
- return dot(c.xyz, vec3(0.3, 0.59, 0.11));
-}
-
-void main() {
- vec2 imageCoord = v_imageCoord;
- float t00 = lum(texture2D(image, imageCoord + imageIncrement * vec2(-1, -1)));
- float t10 = lum(texture2D(image, imageCoord + imageIncrement * vec2( 0, -1)));
- float t20 = lum(texture2D(image, imageCoord + imageIncrement * vec2( 1, -1)));
- float t01 = lum(texture2D(image, imageCoord + imageIncrement * vec2(-1, 0)));
- float t21 = lum(texture2D(image, imageCoord + imageIncrement * vec2( 1, 0)));
- float t02 = lum(texture2D(image, imageCoord + imageIncrement * vec2(-1, 1)));
- float t12 = lum(texture2D(image, imageCoord + imageIncrement * vec2( 0, 1)));
- float t22 = lum(texture2D(image, imageCoord + imageIncrement * vec2( 1, 1)));
- vec2 grad;
- grad.x = t00 + 2.0 * t01 + t02 - t20 - 2.0 * t21 - t22;
- grad.y = t00 + 2.0 * t10 + t20 - t02 - 2.0 * t12 - t22;
- float len = length(grad);
- gl_FragColor = vec4(len, len, len, 1.0);
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
-
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/texturesamplers.html b/o3d/samples/o3d-webgl-samples/texturesamplers.html
deleted file mode 100644
index bbf810e..0000000
--- a/o3d/samples/o3d-webgl-samples/texturesamplers.html
+++ /dev/null
@@ -1,272 +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.
--->
-
-<!--
-O3D Texture Samplers example.
-
-Demonstrates how to create samplers and set their various states.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Texture Samplers
-</title>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.event');
-o3djs.require('o3djs.io');
-
-// Events
-// Run the init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_eye;
-var g_target;
-var g_up;
-var g_finished = false; // for selenium testing
-
-function scrollMe(e) {
- g_eye = g_math.mulScalarVector((e.deltaY < 0 ? 11 : 13) / 12, g_eye);
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(g_eye, g_target, g_up);
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and draws the quads.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 100.
- var proj_matrix = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 100);
-
- // Create the view matrix which tells the camera which way to point to.
- g_eye = [0, 4, 0];
- g_target = [0, 0, 0];
- g_up = [0, 0, -1];
- var view_matrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
-
- g_viewInfo.drawContext.view = view_matrix;
- g_viewInfo.drawContext.projection = proj_matrix;
-
- var samplers = [];
- var transforms = [];
-
- for (var xx = 0; xx < 3; xx++) {
- for (var yy = 0; yy < 2; yy++) {
- var index = yy * 3 + xx;
-
- //Create effect for shaders.
- var effect = g_pack.createObject('Effect');
- var vertexShaderString = document.getElementById('vshader').value;
- var pixelShaderString = document.getElementById('pshader').value;
- effect.loadVertexShaderFromString(vertexShaderString);
- effect.loadPixelShaderFromString(pixelShaderString);
-
- // Create a new Material for the quad.
- var material = g_pack.createObject('Material');
- material.drawList = g_viewInfo.performanceDrawList;
- material.effect = effect;
-
- effect.createUniformParameters(material);
-
- // Create a quad and position it.
- var verts = o3djs.primitives.createPlaneVertices(1, 1, 1, 1);
- var texCoordStream = verts.findStream(g_o3d.Stream.TEXCOORD, 0);
- // make the UVs go from 0 to 2 instead of 0 to 1
- for (var v = 0; v < texCoordStream.elements.length; ++v) {
- texCoordStream.elements[v] *= 2;
- }
- var shape = verts.createShape(g_pack, material);
-
- // Make a transform for each quad.
- var transform = g_pack.createObject('Transform');
- transform.translate([(xx - 1) * 1.2, 0, (0.5 - yy) * -1.2]);
- transform.addShape(shape);
-
-
- // Get the sampler on the sampler param.
- var sampler = g_pack.createObject('Sampler');
- samplers[index] = sampler;
- transforms[index] = transform;
- material.getParam('texSampler').value = sampler;
- }
- }
-
- // Set the sampler states on each sampler.
- // Looking at the generated image, the samplers correspond to the
- // following quads:
- // [0] [1] [2]
- // [3] [4] [5]
- // Sampler states not specified assume their default values which are:
- // addressModeU = Sampler.WRAP
- // addressModeV = Sampler.WRAP
- // minFilter = Sampler.LINEAR
- // magFilter = Sampler.LINEAR
- // mipFilter = Sampler.POINT
- // borderColor = Float4(0, 0, 0, 0)
- // maxAnisotropy = 1
-
- // Rotates quad and uses anisotropic filtering.
- transforms[1].rotateZ(-Math.PI / 2.5);
- samplers[1].addressModeU = g_o3d.Sampler.WRAP;
- samplers[1].addressModeV = g_o3d.Sampler.WRAP;
- samplers[1].minFilter = g_o3d.Sampler.ANISOTROPIC;
- samplers[1].maxAnisotropy = 4;
-
- // Note: BORDER addressing is not supported in WebGL.
- //samplers[2].addressModeU = g_o3d.Sampler.BORDER;
- //samplers[2].addressModeV = g_o3d.Sampler.BORDER;
- //samplers[2].borderColor = [1, 0, 0, 1];
-
- // Uses POINT sampling for minification.
- samplers[3].addressModeU = g_o3d.Sampler.WRAP;
- samplers[3].addressModeV = g_o3d.Sampler.WRAP;
- samplers[3].minFilter = g_o3d.Sampler.POINT;
-
- // Rotates quad and uses default (linear) filtering.
- // Compare results to quad #1.
- transforms[4].rotateZ(-Math.PI / 2.5);
- samplers[4].addressModeU = g_o3d.Sampler.WRAP;
- samplers[4].addressModeV = g_o3d.Sampler.WRAP;
- samplers[4].minFilter = g_o3d.Sampler.LINEAR;
- samplers[4].magFilter = g_o3d.Sampler.LINEAR;
-
- // Uses MIRROR addressing mode to mirror the texture on both axes.
- samplers[5].addressModeU = g_o3d.Sampler.MIRROR;
- samplers[5].addressModeV = g_o3d.Sampler.MIRROR;
-
- // Load our texture!
- var url = o3djs.util.getCurrentURI() + '../assets/texture_b3.jpg';
- o3djs.io.loadTexture(g_pack, url, function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- // Use the same texture for all the samplers.
- for (var ii = 0; ii < samplers.length; ii++) {
- samplers[ii].texture = texture;
- }
- // Parent the transforms. We do this here because until the texture
- // is loaded our quads are not ready to display.
- for (var ii = 0; ii < transforms.length; ii++) {
- transforms[ii].parent = g_client.root;
- }
- g_finished = true; // for selenium testing.
- }
- });
-
- o3djs.event.addEventListener(o3dElement, 'wheel', scrollMe);
-}
-</script>
-</head>
-<body>
-<h1>Texture Sampler Example</h1>
-This tutorial demonstrates various texture sampler settings.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 700px; height: 600px"></div>
-<p>Scrollwheel To Zoom</p><br/>
-<!-- End of O3D plugin -->
-
-<textarea id="vshader" style="display: none;">
-uniform mat4 worldViewProjection;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec2 texCoord0;
-
-// input parameters for our pixel shader
-varying vec2 texCoord;
-
-/**
- * Our vertex shader
- */
-void main() {
- gl_Position = worldViewProjection * position;
- texCoord = texCoord0;
-}
-</textarea>
-<textarea id="pshader" style="display: none;">
-varying vec2 texCoord;
-uniform sampler2D texSampler;
-
-/* Given the texture coordinates, our pixel shader grabs the corresponding
- * color from the texture.
- */
-void main() {
- gl_FragColor = texture2D(texSampler, texCoord);
-}
-</textarea>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/trends/assets/clouds.jpg b/o3d/samples/o3d-webgl-samples/trends/assets/clouds.jpg
deleted file mode 100644
index 8767681..0000000
--- a/o3d/samples/o3d-webgl-samples/trends/assets/clouds.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/trends/assets/earth-large-with-ocean-mask.png b/o3d/samples/o3d-webgl-samples/trends/assets/earth-large-with-ocean-mask.png
deleted file mode 100644
index 850d0ff..0000000
--- a/o3d/samples/o3d-webgl-samples/trends/assets/earth-large-with-ocean-mask.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/trends/assets/earth-large.jpg b/o3d/samples/o3d-webgl-samples/trends/assets/earth-large.jpg
deleted file mode 100644
index ce797dc..0000000
--- a/o3d/samples/o3d-webgl-samples/trends/assets/earth-large.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/trends/assets/earth.jpg b/o3d/samples/o3d-webgl-samples/trends/assets/earth.jpg
deleted file mode 100644
index f04b09d..0000000
--- a/o3d/samples/o3d-webgl-samples/trends/assets/earth.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/trends/assets/energy.png b/o3d/samples/o3d-webgl-samples/trends/assets/energy.png
deleted file mode 100644
index 576ddbb..0000000
--- a/o3d/samples/o3d-webgl-samples/trends/assets/energy.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/trends/assets/moon.jpg b/o3d/samples/o3d-webgl-samples/trends/assets/moon.jpg
deleted file mode 100644
index f916c70..0000000
--- a/o3d/samples/o3d-webgl-samples/trends/assets/moon.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/trends/assets/night-large.jpg b/o3d/samples/o3d-webgl-samples/trends/assets/night-large.jpg
deleted file mode 100644
index 4979d6e..0000000
--- a/o3d/samples/o3d-webgl-samples/trends/assets/night-large.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/trends/assets/night.jpg b/o3d/samples/o3d-webgl-samples/trends/assets/night.jpg
deleted file mode 100644
index 2bfb99e..0000000
--- a/o3d/samples/o3d-webgl-samples/trends/assets/night.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/o3d-webgl-samples/trends/trends-with-particles.html b/o3d/samples/o3d-webgl-samples/trends/trends-with-particles.html
deleted file mode 100644
index 61b9cf1..0000000
--- a/o3d/samples/o3d-webgl-samples/trends/trends-with-particles.html
+++ /dev/null
@@ -1,803 +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.
--->
-
-<!--
-TODO:
- O Set Sun to correct location for time.
- O Put in moon
- O Put in Google satellite
- O Put in Star Shader that uses star data from a texture
- O Add Halo
- O Add Sun Model
- O with glowing rays.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<title>
-Google Trends Visualizer
-</title>
-<style>
- html, body {
- border: 0;
- margin: 0;
- height: 100%;
- height: 100%;
- text-align: center;
- }
-</style>
-</head>
-<body onload="init();" onunload="uninit();">
-<script type="text/javascript" src="../../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.arcball');
-o3djs.require('o3djs.io');
-o3djs.require('o3djs.particles');
-
-var g = {
- EARTH_RADIUS: 25,
- ENERGY_WIDTH: 0.5,
- ENERGY_HEIGHT: 10
-};
-
-g.camera = {
- eye: [0, 0, 75],
- target: [0, 0, 0]
-};
-
-var g_finished = false; // for selenium.
-var dragging = false;
-
-function startDragging(e) {
- g.lastRot = g.thisRot;
- g.aball.click([e.x, e.y]);
- dragging = true;
-}
-
-function drag(e) {
- if (dragging) {
- var rotationQuat = g.aball.drag([e.x, e.y]);
- var rot_mat = g.quaternions.quaternionToRotation(rotationQuat);
- g.thisRot = g.math.matrix4.mul(g.lastRot, rot_mat);
-
- var m = g.root.localMatrix;
- g.math.matrix4.setUpper3x3(m, g.thisRot);
- g.root.localMatrix = m;
- }
-}
-
-function stopDragging(e) {
- dragging = false;
-}
-
-function updateViewFromCamera() {
- var target = g.camera.target;
- var eye = g.camera.eye;
- var up = [0, 1, 0];
- g.viewInfo.drawContext.view = g.math.matrix4.lookAt(eye, target, up);
- g.eyePosParam.value = eye;
-}
-
-function scrollMe(e) {
- if (e.deltaY > 0) {
- g.camera.eye[0] *= 11 / 12;
- g.camera.eye[1] *= 11 / 12;
- g.camera.eye[2] *= 11 / 12;
-
- } else {
- g.camera.eye[0] *= (1 + 1 / 12);
- g.camera.eye[1] *= (1 + 1 / 12);
- g.camera.eye[2] *= (1 + 1 / 12);
- }
- updateViewFromCamera();
-}
-
-function getURL(path) {
- var base = window.location.href;
- var index = base.lastIndexOf('/');
- base = base.substring(0, index + 1);
- return base + path;
-}
-
-function setClientSize() {
- var newWidth = g.client.width;
- var newHeight = g.client.height;
-
- if (newWidth != g.o3dWidth || newHeight != g.o3dHeight) {
- g.o3dWidth = newWidth;
- g.o3dHeight = newHeight;
-
- // Create a perspective projection matrix
- g.viewInfo.drawContext.projection = g.math.matrix4.perspective(
- g.math.degToRad(45), g.o3dWidth / g.o3dHeight, 0.1, 5000);
-
- // Sets a new area size for arcball.
- g.aball.setAreaSize(g.o3dWidth, g.o3dHeight);
- }
-}
-
-function onRender() {
- setClientSize();
-}
-
-// A geo is a float where the integer part is in degrees and the fractional
-// part is in 60ths
-function geoToRad(geo) {
- var sign = geo >= 0 ? 1 : -1;
- geo = Math.abs(geo);
- var integerPart = Math.floor(geo);
- var fractionalPart = (geo % 1) * 100;
- fractionalPart = fractionalPart / 60;
- return g.math.degToRad(integerPart + fractionalPart);
-}
-
-function addEnergyShard(latitude, longitude, energy, height, color) {
- // Decide how many particles we want in this shard.
- g.trailParameters.numParticles = Math.floor(Math.random() * 10) + 1;
- // Set the color for the shard's particles.
- g.trailParameters.colorMult = color;
- // Compute a base position for the shard and a velocity for the particles.
- var matrix = g.math.matrix4.rotationZ(geoToRad(latitude));
- g.math.matrix4.rotateY(matrix, geoToRad(-longitude));
- g.math.matrix4.rotateZ(matrix, g.math.degToRad(90));
- g.shardStartPosition =
- g.math.matrix4.transformDirection(matrix, [0, g.EARTH_RADIUS, 0]);
- g.shardVelocity = g.math.matrix4.transformDirection(matrix, [0, 2.5, 0]);
- // Birth the particles. NOTE: the position passed in here is overridden by
- // our per particle function.
- g.trail.birthParticles([0, 0, 0]);
-}
-
-function shardPerParticleFunc(particleIndex, parameters) {
- // This function sets parameters for each individual particle that is
- // birthed. We'll calculate these in addEneryShard so all the
- // particles genearted come out of the same position going in the
- // same direction
- parameters.position = g.shardStartPosition;
- parameters.velocity = g.shardVelocity;
- // Pick a random time for the particle to appear.
- parameters.startTime = Math.random() * parameters.timeRange;
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-/**
- * Initializes o3d
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- var path = window.location.href;
- var index = path.lastIndexOf('/');
-
- g.o3dElement = clientElements[0];
- g.o3d = g.o3dElement.o3d;
- g.math = o3djs.math;
- g.quaternions = o3djs.quaternions;
- g.client = g.o3dElement.client;
-
- g.pack = g.client.createPack();
-
- // Create the render graph for a view.
- g.viewInfo = o3djs.rendergraph.createBasicView(
- g.pack,
- g.client.root,
- g.client.renderGraphRoot);
-
- // Set the background color to black.
- g.viewInfo.clearBuffer.clearColor = [0, 0, 0, 0];
-
- // Set states for shards.
- g.viewInfo.zOrderedState.getStateParam('CullMode').value =
- g.o3d.State.CULL_NONE;
- g.viewInfo.zOrderedState.getStateParam('DestinationBlendFunction').value =
- g.o3d.State.BLENDFUNC_ONE;
- g.viewInfo.zOrderedState.getStateParam('ZWriteEnable').value = false;
-
- g.viewInfo.performanceDrawPass.sortMethod = g.o3d.DrawList.BY_PRIORITY;
-
- g.lastRot = g.math.matrix4.identity();
- g.thisRot = g.math.matrix4.identity();
-
- var root = g.client.root;
-
- // Create a param for the sun and eye positions that we can bind
- // to auto update a bunch of materials.
- g.globalParams = g.pack.createObject('ParamObject');
- g.sunPosParam = g.globalParams.createParam('sunPos', 'ParamFloat3');
- g.sunPosParam.value = [1000, 200, 100];
- g.eyePosParam = g.globalParams.createParam('eyePos', 'ParamFloat3');
-
- updateViewFromCamera();
-
- g.aball = o3djs.arcball.create(100, 100);
- setClientSize();
-
- g.client.setRenderCallback(onRender);
-
-
- // Create Materials.
- var effectNames = [
- "noTexture",
- "dayOnly",
- "nightAndDay",
- "mask",
- "atmosphere"
- ];
- g.materials = [];
- for (var ii = 0; ii < effectNames.length; ++ii) {
- var effectName = effectNames[ii];
- var effect = g.pack.createObject('Effect');
- effect.loadFromFXString(document.getElementById(effectName).value);
-
- // Create a Material for the effect.
- var material = g.pack.createObject('Material');
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shader to use.
- material.effect = effect;
-
- // Set the material's drawList
- material.drawList = g.viewInfo.performanceDrawList;
-
- // This will create the effects's params on the material.
- effect.createUniformParameters(material);
-
- // Bind the sun position to a global value so we can easily change it
- // globally.
- var sunParam = material.getParam('sunPos');
- if (sunParam) {
- sunParam.bind(g.sunPosParam);
- }
-
- // Save off the material.
- g.materials.push(material);
- }
- g.noTextureMaterial = g.materials[0];
- g.dayOnlyMaterial = g.materials[1];
- g.nightAndDayMaterial = g.materials[2];
- g.maskMaterial = g.materials[3];
- g.atmosphereMaterial = g.materials[4];
-
- // create samplers
- g.samplers = [];
- for (var ii = 0; ii < 4; ++ii) {
- var sampler = g.pack.createObject('Sampler');
- g.samplers[ii] = sampler;
- }
-
- g.daySampler = g.samplers[0];
- g.nightSampler = g.samplers[1];
- g.maskSampler = g.samplers[2];
-
- // set the material samplers.
- g.dayOnlyMaterial.getParam('daySampler').value = g.daySampler;
- g.nightAndDayMaterial.getParam('daySampler').value = g.daySampler;
- g.nightAndDayMaterial.getParam('nightSampler').value = g.nightSampler;
- g.maskMaterial.getParam('daySampler').value = g.daySampler;
- g.maskMaterial.getParam('maskSampler').value = g.maskSampler;
- g.maskMaterial.getParam('nightSampler').value = g.nightSampler;
-
- // Setup counters for shard animation.
- g.shardCounter = g.pack.createObject('SecondCounter');
-
- // Setup counters to fade in textures.
- g.flatToDayCounter = g.pack.createObject('SecondCounter');
- g.flatToDayCounter.end = 1;
- g.flatToDayCounter.multiplier = 0.5;
- g.flatToDayCounter.countMode = g.o3d.Counter.ONCE;
- g.flatToDayCounter.running = false;
- g.flatToDayCounter.addCallback(1, loadNightTexture);
- g.dayOnlyMaterial.getParam('time').bind(
- g.flatToDayCounter.getParam('count'));
-
- g.dayOnlyToNightCounter = g.pack.createObject('SecondCounter');
- g.dayOnlyToNightCounter.end = 1;
- g.dayOnlyToNightCounter.multiplier = 0.5;
- g.dayOnlyToNightCounter.countMode = g.o3d.Counter.ONCE;
- g.dayOnlyToNightCounter.running = false;
- g.dayOnlyToNightCounter.addCallback(1, loadMaskTexture);
- g.nightAndDayMaterial.getParam('time').bind(
- g.dayOnlyToNightCounter.getParam('count'));
-
- g.noMaskToMaskCounter = g.pack.createObject('SecondCounter');
- g.noMaskToMaskCounter.end = 1;
- g.noMaskToMaskCounter.multiplier = 0.5;
- g.noMaskToMaskCounter.countMode = g.o3d.Counter.ONCE;
- g.noMaskToMaskCounter.running = false;
- g.maskMaterial.getParam('time').bind(
- g.noMaskToMaskCounter.getParam('count'));
-
- // Create a sphere at the origin for the earth.
- var earth = o3djs.primitives.createSphere(g.pack,
- g.noTextureMaterial,
- 25,
- 50,
- 50);
-
- // Get a the element so we can set its material later.
- g.earthPrimitive = earth.elements[0];
- g.atmosphereState = g.pack.createObject('State');
- g.atmosphereState.getStateParam('AlphaBlendEnable').value = true;
- g.atmosphereState.getStateParam('SourceBlendFunction').value =
- g.o3d.State.BLENDFUNC_SOURCE_ALPHA;
- g.atmosphereState.getStateParam('DestinationBlendFunction').value =
- g.o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA;
- g.atmosphereState.getStateParam('ZWriteEnable').value = false;
- g.atmosphereMaterial.state = g.atmosphereState;
-
- g.root = g.pack.createObject('Transform');
- g.root.parent = g.client.root;
- g.earth = g.pack.createObject('Transform');
- g.earth.addShape(earth);
- g.earth.parent = g.root;
-
- // Create a sphere at the origin for the atmosphere.
- var atmosphere = o3djs.primitives.createSphere(g.pack,
- g.atmosphereMaterial,
- 26,
- 50,
- 50);
- g.atmospherePrimitive = atmosphere.elements[0];
- g.atmospherePrimitive.priority = 1;
- g.atmosphere = g.pack.createObject('Transform');
- g.atmosphere.addShape(atmosphere);
- g.atmosphere.parent = g.root;
-
- // Set shading language.
- o3djs.particles.setLanguage('glsl');
-
- // Make a particle system
- g.particleSystem = o3djs.particles.createParticleSystem(
- g.pack,
- g.viewInfo,
- g.shardCounter.getParam('count'),
- g.math.pseudoRandom);
-
- // Make a transform for the particle emitter.
- var transform = g.pack.createObject('Transform');
- transform.parent = g.root;
- // Make a single pixel white texture as our particle.
- var texture = g.pack.createTexture2D(1, 1, g.o3d.Texture.ARGB8, 1, false);
- texture.set(0, [1, 1, 1, 1]);
-
- // Setup some basic parameters for our particles.
- g.trailParameters = {
- lifeTime: 4, // each particle lasts 4 seconds
- timeRange: 4, // The clock is modded by this so the *world* clock repeats
- // every 4 seconds making each particle reappear
- startSize: 0.1, // Size to start a particle
- endSize: 0.1, // Size to end a particle
- // (the particle lerps in side between start and end)
- };
-
- // Create a trail. Trails are just a particle system that lets us more
- // easily birth individual particles.
- g.trail = g.particleSystem.createTrail(
- transform, // Transform for particles.
- 10000, // Total number of particles in system. If 10001
- // particles are birthed, the oldest particle is
- // reused.
- g.trailParameters, // Our static birth parameters.
- texture, // The texture to use.
- shardPerParticleFunc); // A function to set parameters per particle.
- g.trail.setState(o3djs.particles.ParticleStateIds.BLEND);
- // This ramp makes the particles full bright for 4/5ths of their lifespan
- // and they fade out during the last 1/5th.
- g.trail.setColorRamp(
- [1, 1, 1, 1,
- 1, 1, 1, 1,
- 1, 1, 1, 1,
- 1, 1, 1, 1,
- 1, 1, 1, 0]);
-
-
- addEnergyShard(0, 0, 1, 1, [1, 1, 1, 1]);
-
- // Honolulu, Hawaii, 21, 18, 157, 50
- addEnergyShard(21.18, 157.50, 1, 1, [0, 1, 0, 1]);
- // San Francisco, Calif. 37 47 122 26
- addEnergyShard(37.47, 122.26, 1, 1, [1, 0.5, 0.5, 1]);
-
- for (var ii = 0; ii < 24; ++ii) {
- var longitude = Math.random() * 360;
- var latitude = Math.random() * 360 - 180;
- var color = [ Math.random() * 0.5 + 0.2,
- Math.random() * 0.5 + 0.2,
- Math.random() * 0.5 + 0.2,
- 1 ];
- // Make a least 1 color component full bright.
- color[Math.floor(Math.random() * 2.99)] = 1;
- for (var jj = 0; jj < 24; ++jj) {
- addEnergyShard(latitude + (Math.random() - 0.5) * 10,
- longitude + (Math.random() - 0.5) * 10,
- 1,
- 1,
- color);
- }
- }
-
- o3djs.event.addEventListener(g.o3dElement, 'mousedown', startDragging);
- o3djs.event.addEventListener(g.o3dElement, 'mousemove', drag);
- o3djs.event.addEventListener(g.o3dElement, 'mouseup', stopDragging);
- o3djs.event.addEventListener(g.o3dElement, 'wheel', scrollMe);
-
- loadDayTexture();
-}
-
-function loadTexture(path, callback) {
- var url = getURL(path);
- o3djs.io.loadTexture(g.pack, url, function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- callback(texture);
- }
- });
-}
-
-function loadDayTexture() {
- loadTexture('assets/earth.jpg', function(texture) {
- g.daySampler.texture = texture;
- g.earthPrimitive.material = g.dayOnlyMaterial;
- g.flatToDayCounter.running = true;
- });
-}
-
-function loadNightTexture() {
- loadTexture('assets/night.jpg', function(texture) {
- g.nightSampler.texture = texture;
- g.earthPrimitive.material = g.nightAndDayMaterial;
- g.dayOnlyToNightCounter.running = true;
- });
-}
-
-function loadMaskTexture() {
- loadTexture('assets/earth-large-with-ocean-mask.png', function(texture) {
- g.maskSampler.texture = texture;
- g.earthPrimitive.material = g.maskMaterial;
- g.noMaskToMaskCounter.running = true;
- g_finished = true; // for selenium
- });
-}
-
-function uninit() {
- // TODO: We should clean up any counters that have callbacks here.
- if (g.client) {
- g.client.cleanup();
- }
-}
-</script>
-<!--<h1>
-Google Trends Visualizer.
-</h1>-->
-<div id="o3d" style="width:100%; height: 100%;"></div>
-<div style="display:none">
-<textarea id="noTexture" name="fx" cols="80" rows="20">
-uniform mat4 worldViewProjection;
-uniform mat4 world;
-uniform mat4 view;
-
-uniform vec3 sunPos;
-
-attribute vec4 position;
-attribute vec3 normal;
-
-varying vec4 v_pos;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-void main() {
- gl_Position = worldViewProjection * position;
- v_normal = (world * vec4(normal, 0)).xyz;
- vec3 worldPos = (world * position).xyz;
- v_sun = sunPos - worldPos;
- v_view = (view[3].xyz- worldPos);
- v_pos = gl_Position;
-}
-
-// #o3d SplitMarker
-
-varying vec4 v_pos;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-vec4 lit(float l, float h, float m) {
- return vec4(1.0,
- max(l, 0.0),
- (l > 0.0) ? pow(max(0.0, h), m) : 0.0,
- 1.0);
-}
-
-void main() {
- vec3 norm = normalize(v_normal);
- vec3 sun = normalize(v_sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1.0 - sqrt(abs(light));
- dayNight = dayNight * dayNight;
- dayNight = (1.0 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0.0, 1.0);
- vec3 view = normalize(v_view);
- vec3 r = normalize(reflect(norm, sun));
- vec4 litR = vec4(lit(light, dot(r, view), 0.0).y);
- vec3 day = vec3(0.5, 0.5, 1.0) * litR.y + vec3(1,1,1) * litR.z;
- vec3 night = vec3(0.2, 0.2, 0.5);
- gl_FragColor = vec4(mix(night, day, dayNight),1);
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<textarea id="dayOnly" name="fx" cols="80" rows="20">
-uniform mat4 worldViewProjection;
-uniform mat4 world;
-uniform mat4 view;
-
-uniform vec3 sunPos;
-
-attribute vec4 position;
-attribute vec3 normal;
-attribute vec2 texCoord0;
-
-varying vec2 v_uv;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-void main() {
- gl_Position = (worldViewProjection * position);
- v_uv = texCoord0;
- v_normal = (world * vec4(normal, 0)).xyz;
- vec3 worldPos = (world * position).xyz;
- v_sun = sunPos - worldPos;
- v_view = (view[3].xyz - worldPos);
-}
-
-// #o3d SplitMarker
-
-uniform float time;
-
-uniform sampler2D daySampler;
-
-varying vec2 v_uv;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-vec4 lit(float l, float h, float m) {
- return vec4(1.0,
- max(l, 0.0),
- (l > 0.0) ? pow(max(0.0, h), m) : 0.0,
- 1.0);
-}
-
-void main() {
- vec3 norm = normalize(v_normal);
- vec3 sun = normalize(v_sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1.0 - sqrt(abs(light));
- dayNight = dayNight * dayNight;
- dayNight = (1.0 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0.0, 1.0);
- vec3 view = normalize(v_view);
- vec3 r = normalize(reflect(norm, sun));
- vec4 litR = vec4(lit(light, dot(r, view), 0.0).y);
- vec3 earth = texture2D(daySampler, v_uv).xyz;
- vec3 day = mix(vec3(0.5, 0.5, 1.0), earth, time);
- day = day * litR.y + vec3(1,1,1) * litR.z;
- vec3 night = mix(vec3(0.2, 0.2, 0.5), earth * 0.3, time);
- gl_FragColor = vec4(mix(night, day, dayNight),1);
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<textarea id="nightAndDay" name="fx" cols="80" rows="20">
-uniform mat4 worldViewProjection;
-uniform mat4 world;
-uniform mat4 view;
-
-uniform vec3 sunPos;
-
-attribute vec4 position;
-attribute vec3 normal;
-attribute vec2 texCoord0;
-
-varying vec2 v_uv;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-void main() {
- gl_Position = worldViewProjection * position;
- v_uv = texCoord0;
- v_normal = (world * vec4(normal, 0)).xyz;
- vec3 worldPos = (world * position).xyz;
- v_sun = sunPos - worldPos;
- v_view = (view[3].xyz - worldPos);
-}
-
-// #o3d SplitMarker
-
-uniform float time;
-
-uniform sampler2D daySampler;
-uniform sampler2D nightSampler;
-
-varying vec2 v_uv;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-vec4 lit(float l, float h, float m) {
- return vec4(1.0,
- max(l, 0.0),
- (l > 0.0) ? pow(max(0.0, h), m) : 0.0,
- 1.0);
-}
-
-void main() {
- vec3 norm = normalize(v_normal);
- vec3 sun = normalize(v_sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1.0 - sqrt(abs(light));
- dayNight = dayNight * dayNight;
- dayNight = (1.0 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0.0, 1.0);
- vec3 view = normalize(v_view);
- vec3 r = normalize(reflect(norm, sun));
- vec4 litR = vec4(lit(light, dot(r, view), 0.0).y);
- vec3 earth = texture2D(daySampler, v_uv).xyz;
- vec3 day = texture2D(daySampler, v_uv).xyz;
- vec3 night = mix(day * 0.3, texture2D(nightSampler, v_uv).xyz, time);
- day = day * litR.y + vec3(1,1,1) * litR.z;
- gl_FragColor = vec4(mix(night, day, dayNight),1);
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<!--
-This shader renders the ocean different then the non-ocean using a mask
-stored in the alpha channel of the maskSampler
--->
-<textarea id="mask" name="fx" cols="80" rows="20">
-uniform mat4 worldViewProjection;
-uniform mat4 world;
-uniform mat4 view;
-
-uniform vec3 sunPos;
-
-attribute vec4 position;
-attribute vec3 normal;
-attribute vec2 texCoord0;
-
-varying vec2 v_uv;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-void main() {
- gl_Position = worldViewProjection * position;
- v_uv = texCoord0;
- v_normal = (world * vec4(normal, 0)).xyz;
- vec3 worldPos = (world * position).xyz;
- v_sun = sunPos - worldPos;
- v_view = (view[3].xyz - worldPos);
-}
-
-// #o3d SplitMarker
-
-uniform float time;
-
-uniform sampler2D daySampler;
-uniform sampler2D nightSampler;
-uniform sampler2D maskSampler;
-
-varying vec2 v_uv;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-vec4 lit(float l, float h, float m) {
- return vec4(1.0,
- max(l, 0.0),
- (l > 0.0) ? pow(max(0.0, h), m) : 0.0,
- 1.0);
-}
-
-void main() {
- vec3 norm = normalize(v_normal);
- vec3 sun = normalize(v_sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1.0 - sqrt(abs(light));
- dayNight = dayNight * dayNight;
- dayNight = (1.0 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0.0, 1.0);
- vec3 view = normalize(v_view);
- vec3 r = normalize(reflect(norm, sun));
- vec4 litR = vec4(lit(light, dot(r, view), 0.0).y);
- vec3 earth = texture2D(daySampler, v_uv).xyz;
- vec4 mask = texture2D(maskSampler, v_uv);
- vec3 day = mix(texture2D(daySampler, v_uv).xyz,
- mask.xyz, time);
- vec3 night = texture2D(nightSampler, v_uv).xyz;
- day = day * litR.y + vec3(1,1,1) * litR.z * (1.0 - mask.w * time);
- vec3 color = mix(night, day, dayNight);
- gl_FragColor = vec4(color, 1);
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<textarea id="atmosphere" name="fx" cols="80" rows="20">
-uniform mat4 worldViewProjection;
-uniform mat4 worldView;
-
-attribute vec4 position;
-attribute vec3 normal;
-
-varying vec3 v_normal;
-
-void main() {
- gl_Position = worldViewProjection * position;
- v_normal = normalize((worldView * vec4(normal,0)).xyz);
-}
-
-// #o3d SplitMarker
-
-varying vec3 v_normal;
-
-void main() {
- float n = 1.0 - log(2.0 * normalize(v_normal).z);
- gl_FragColor = vec4(0.3, 0.3, 1, n * n * n * n);
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
-</html>
-
-
diff --git a/o3d/samples/o3d-webgl-samples/trends/trends.html b/o3d/samples/o3d-webgl-samples/trends/trends.html
deleted file mode 100644
index d5eb1a9..0000000
--- a/o3d/samples/o3d-webgl-samples/trends/trends.html
+++ /dev/null
@@ -1,869 +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.
--->
-
-<!--
-TODO:
- O Set Sun to correct location for time.
- O Put in moon
- O Put in Google satellite
- O Put in Star Shader that uses star data from a texture
- O Add Halo
- O Add Sun Model
- O with glowing rays.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<title>
-Google Trends Visualizer
-</title>
-<style>
- html, body {
- border: 0;
- margin: 0;
- height: 100%;
- height: 100%;
- text-align: center;
- }
-</style>
-</head>
-<body onload="init();" onunload="uninit();">
-<script type="text/javascript" src="../../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.arcball');
-o3djs.require('o3djs.io');
-
-var g = {
- EARTH_RADIUS: 25,
- ENERGY_WIDTH: 0.3,
- ENERGY_HEIGHT: 10
-};
-
-g.camera = {
- eye: [0, 0, 75],
- target: [0, 0, 0]
-};
-
-var g_finished = false; // for selenium.
-var dragging = false;
-
-function startDragging(e) {
- g.lastRot = g.thisRot;
- g.aball.click([e.x, e.y]);
- dragging = true;
-}
-
-function drag(e) {
- if (dragging) {
- var rotationQuat = g.aball.drag([e.x, e.y]);
- var rot_mat = g.quaternions.quaternionToRotation(rotationQuat);
- g.thisRot = g.math.matrix4.mul(g.lastRot, rot_mat);
-
- var m = g.root.localMatrix;
- g.math.matrix4.setUpper3x3(m, g.thisRot);
- g.root.localMatrix = m;
- }
-}
-
-function stopDragging(e) {
- dragging = false;
-}
-
-function updateViewFromCamera() {
- var target = g.camera.target;
- var eye = g.camera.eye;
- var up = [0, 1, 0];
- g.viewInfo.drawContext.view = g.math.matrix4.lookAt(eye, target, up);
- g.eyePosParam.value = eye;
-}
-
-function scrollMe(e) {
- if (e.deltaY > 0) {
- g.camera.eye[0] *= 11 / 12;
- g.camera.eye[1] *= 11 / 12;
- g.camera.eye[2] *= 11 / 12;
-
- } else {
- g.camera.eye[0] *= (1 + 1 / 12);
- g.camera.eye[1] *= (1 + 1 / 12);
- g.camera.eye[2] *= (1 + 1 / 12);
- }
- updateViewFromCamera();
-}
-
-function getURL(path) {
- var base = window.location.href;
- var index = base.lastIndexOf('/');
- base = base.substring(0, index + 1);
- return base + path;
-}
-
-function setClientSize() {
- var newWidth = g.client.width;
- var newHeight = g.client.height;
-
- if (newWidth != g.o3dWidth || newHeight != g.o3dHeight) {
- g.o3dWidth = newWidth;
- g.o3dHeight = newHeight;
-
- // Create a perspective projection matrix
- g.viewInfo.drawContext.projection = g.math.matrix4.perspective(
- g.math.degToRad(45), g.o3dWidth / g.o3dHeight, 0.1, 5000);
-
- // Sets a new area size for arcball.
- g.aball.setAreaSize(g.o3dWidth, g.o3dHeight);
- }
-}
-
-function onRender() {
- setClientSize();
-}
-
-function createEnergyShape(pack, material, width, height) {
- var vertexInfo = o3djs.primitives.createVertexInfo();
- var positionStream = vertexInfo.addStream(
- 3, g.o3d.Stream.POSITION);
- var normalStream = vertexInfo.addStream(
- 3, g.o3d.Stream.NORMAL);
- var colorStream = vertexInfo.addStream(
- 4, g.o3d.Stream.COLOR);
- var texCoordStream = vertexInfo.addStream(
- 2, g.o3d.Stream.TEXCOORD, 0);
-
- var vScale = 1;
- positionStream.addElement(width * -0.5, height, 0);
- normalStream.addElement(0, 0, 1);
- colorStream.addElement(1, 1, 1, 0);
- texCoordStream.addElement(0, 0);
- positionStream.addElement(width * 0.5, height, 0);
- normalStream.addElement(0, 0, 1);
- colorStream.addElement(1, 1, 1, 0);
- texCoordStream.addElement(1, 0);
- positionStream.addElement(width * -0.5, 0, 0);
- normalStream.addElement(0, 0, 1);
- colorStream.addElement(1, 1, 1, 1);
- texCoordStream.addElement(0, vScale);
- positionStream.addElement(width * 0.5, 0, 0);
- normalStream.addElement(0, 0, 1);
- colorStream.addElement(1, 1, 1, 1);
- texCoordStream.addElement(1, vScale);
- positionStream.addElement(0, height, width * -0.5);
- normalStream.addElement(1, 0, 0);
- colorStream.addElement(1, 1, 1, 0);
- texCoordStream.addElement(0, 0);
- positionStream.addElement(0, height, width * 0.5);
- normalStream.addElement(1, 0, 0);
- colorStream.addElement(1, 1, 1, 0);
- texCoordStream.addElement(1, 0);
- positionStream.addElement(0, 0, width * -0.5);
- normalStream.addElement(1, 0, 0);
- colorStream.addElement(1, 1, 1, 1);
- texCoordStream.addElement(0, vScale);
- positionStream.addElement(0, 0, width * 0.5);
- normalStream.addElement(1, 0, 0);
- colorStream.addElement(1, 1, 1, 1);
- texCoordStream.addElement(1, vScale);
-
- vertexInfo.addTriangle(0, 1, 2);
- vertexInfo.addTriangle(1, 2, 3);
- vertexInfo.addTriangle(4, 5, 6);
- vertexInfo.addTriangle(5, 6, 7);
-
- return vertexInfo.createShape(pack, material);
-}
-
-// A geo is a float where the integer part is in degrees and the fractional
-// part is in 60ths
-function geoToRad(geo) {
- var sign = geo >= 0 ? 1 : -1;
- geo = Math.abs(geo);
- var integerPart = Math.floor(geo);
- var fractionalPart = (geo % 1) * 100;
- fractionalPart = fractionalPart / 60;
- return g.math.degToRad(integerPart + fractionalPart);
-}
-
-function addEnergyShard(latitude, longitude, energy, height, color) {
- var transform = g.pack.createObject('Transform');
- transform.rotateZ(geoToRad(latitude));
- transform.rotateY(geoToRad(-longitude));
- transform.rotateZ(g.math.degToRad(90));
- transform.translate(0, g.EARTH_RADIUS, 0);
- transform.parent = g.root;
- transform.addShape(g.energyShape);
- transform.createParam('colorMult', 'ParamFloat4').value = color;
- transform.createParam('offset', 'ParamFloat').value = Math.random();
- return transform;
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-/**
- * Initializes o3d
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- var path = window.location.href;
- var index = path.lastIndexOf('/');
-
- g.o3dElement = clientElements[0];
- g.o3d = g.o3dElement.o3d;
- g.math = o3djs.math;
- g.quaternions = o3djs.quaternions;
- g.client = g.o3dElement.client;
-
- g.pack = g.client.createPack();
-
- // Create the render graph for a view.
- g.viewInfo = o3djs.rendergraph.createBasicView(
- g.pack,
- g.client.root,
- g.client.renderGraphRoot);
-
- // Set the background color to black.
- g.viewInfo.clearBuffer.clearColor = [0, 0, 0, 0];
-
- // Set states for shards.
- g.viewInfo.zOrderedState.getStateParam('CullMode').value =
- g.o3d.State.CULL_NONE;
- g.viewInfo.zOrderedState.getStateParam('DestinationBlendFunction').value =
- g.o3d.State.BLENDFUNC_ONE;
- g.viewInfo.zOrderedState.getStateParam('ZWriteEnable').value = false;
-
- g.viewInfo.performanceDrawPass.sortMethod = g.o3d.DrawList.BY_PRIORITY;
-
- g.lastRot = g.math.matrix4.identity();
- g.thisRot = g.math.matrix4.identity();
-
- var root = g.client.root;
-
- // Create a param for the sun and eye positions that we can bind
- // to auto update a bunch of materials.
- g.globalParams = g.pack.createObject('ParamObject');
- g.sunPosParam = g.globalParams.createParam('sunPos', 'ParamFloat3');
- g.sunPosParam.value = [1000, 200, 100];
- g.eyePosParam = g.globalParams.createParam('eyePos', 'ParamFloat3');
-
- updateViewFromCamera();
-
- g.aball = o3djs.arcball.create(100, 100);
- setClientSize();
-
- g.client.setRenderCallback(onRender);
-
-
- // Create Materials.
- var effectNames = [
- "noTexture",
- "dayOnly",
- "nightAndDay",
- "mask",
- "energy",
- "atmosphere"
- ];
- g.materials = [];
- for (var ii = 0; ii < effectNames.length; ++ii) {
- var effectName = effectNames[ii];
- var effect = g.pack.createObject('Effect');
- effect.loadFromFXString(document.getElementById(effectName).value);
-
- // Create a Material for the effect.
- var material = g.pack.createObject('Material');
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shader to use.
- material.effect = effect;
-
- // Set the material's drawList
- material.drawList = g.viewInfo.performanceDrawList;
-
- // This will create the effects's params on the material.
- effect.createUniformParameters(material);
-
- // Bind the sun position to a global value so we can easily change it
- // globally.
- var sunParam = material.getParam('sunPos');
- if (sunParam) {
- sunParam.bind(g.sunPosParam);
- }
-
- // Save off the material.
- g.materials.push(material);
- }
- g.noTextureMaterial = g.materials[0];
- g.dayOnlyMaterial = g.materials[1];
- g.nightAndDayMaterial = g.materials[2];
- g.maskMaterial = g.materials[3];
- g.energyMaterial = g.materials[4];
- g.energyMaterial.drawList = g.viewInfo.zOrderedDrawList;
- g.atmosphereMaterial = g.materials[5];
-
- // create samplers
- g.samplers = [];
- for (var ii = 0; ii < 4; ++ii) {
- var sampler = g.pack.createObject('Sampler');
- g.samplers[ii] = sampler;
- }
-
- g.daySampler = g.samplers[0];
- g.nightSampler = g.samplers[1];
- g.maskSampler = g.samplers[2];
- g.energySampler = g.samplers[3];
-
- // set the material samplers.
- g.dayOnlyMaterial.getParam('daySampler').value = g.daySampler;
- g.nightAndDayMaterial.getParam('daySampler').value = g.daySampler;
- g.nightAndDayMaterial.getParam('nightSampler').value = g.nightSampler;
- g.maskMaterial.getParam('daySampler').value = g.daySampler;
- g.maskMaterial.getParam('maskSampler').value = g.maskSampler;
- g.maskMaterial.getParam('nightSampler').value = g.nightSampler;
- g.energyMaterial.getParam('energySampler').value = g.energySampler;
-
- // Create energy texture(s)
- {
- // WebGL expects power-of-two textures, so use 4x32 instead of 3x32.
- var dots = [ 0, 1, 0, 1, 0, 0, 1, 0,
- 1, 0, 0, 1, 0, 1, 0, 0,
- 1, 0, 1, 0, 0, 0, 1, 0,
- 0, 1, 0, 1, 0, 0, 1, 0 ];
- var texture = g.pack.createTexture2D(4,
- dots.length,
- g.o3d.Texture.XRGB8,
- 1,
- false);
- var pixels = [];
- for (var yy = 0; yy < dots.length; ++yy) {
- for (var xx = 0; xx < 4; ++xx) {
- var pixelOffset = (yy * 4 + xx) * 3;
- var color = (xx == 1 || xx == 2) ? dots[yy] : 0;
- for (var cc = 0; cc < 3; ++cc) {
- pixels[pixelOffset + cc] = color;
- }
- }
- }
- texture.set(0, pixels);
- g.energySampler.texture = texture;
- }
-
- // Setup counters for shard animation.
- g.shardCounter = g.pack.createObject('SecondCounter');
- g.shardCounter.multiplier = 0.1;
- g.energyMaterial.getParam('time').bind(
- g.shardCounter.getParam('count'));
-
- // Setup counters to fade in textures.
- g.flatToDayCounter = g.pack.createObject('SecondCounter');
- g.flatToDayCounter.end = 1;
- g.flatToDayCounter.multiplier = 0.5;
- g.flatToDayCounter.countMode = g.o3d.Counter.ONCE;
- g.flatToDayCounter.running = false;
- g.flatToDayCounter.addCallback(1, loadNightTexture);
- g.dayOnlyMaterial.getParam('time').bind(
- g.flatToDayCounter.getParam('count'));
-
- g.dayOnlyToNightCounter = g.pack.createObject('SecondCounter');
- g.dayOnlyToNightCounter.end = 1;
- g.dayOnlyToNightCounter.multiplier = 0.5;
- g.dayOnlyToNightCounter.countMode = g.o3d.Counter.ONCE;
- g.dayOnlyToNightCounter.running = false;
- g.dayOnlyToNightCounter.addCallback(1, loadMaskTexture);
- g.nightAndDayMaterial.getParam('time').bind(
- g.dayOnlyToNightCounter.getParam('count'));
-
- g.noMaskToMaskCounter = g.pack.createObject('SecondCounter');
- g.noMaskToMaskCounter.end = 1;
- g.noMaskToMaskCounter.multiplier = 0.5;
- g.noMaskToMaskCounter.countMode = g.o3d.Counter.ONCE;
- g.noMaskToMaskCounter.running = false;
- g.maskMaterial.getParam('time').bind(
- g.noMaskToMaskCounter.getParam('count'));
-
- // Create a sphere at the origin for the earth.
- var earth = o3djs.primitives.createSphere(g.pack,
- g.noTextureMaterial,
- 25,
- 50,
- 50);
-
- // Get a the element so we can set its material later.
- g.earthPrimitive = earth.elements[0];
- g.atmosphereState = g.pack.createObject('State');
- g.atmosphereState.getStateParam('AlphaBlendEnable').value = true;
- g.atmosphereState.getStateParam('SourceBlendFunction').value =
- g.o3d.State.BLENDFUNC_SOURCE_ALPHA;
- g.atmosphereState.getStateParam('DestinationBlendFunction').value =
- g.o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA;
- g.atmosphereState.getStateParam('ZWriteEnable').value = false;
- g.atmosphereMaterial.state = g.atmosphereState;
-
- g.root = g.pack.createObject('Transform');
- g.root.parent = g.client.root;
- g.earth = g.pack.createObject('Transform');
- g.earth.addShape(earth);
- g.earth.parent = g.root;
-
- // Create a sphere at the origin for the atmosphere.
- var atmosphere = o3djs.primitives.createSphere(g.pack,
- g.atmosphereMaterial,
- 26,
- 50,
- 50);
- g.atmospherePrimitive = atmosphere.elements[0];
- g.atmospherePrimitive.priority = 1;
- g.atmosphere = g.pack.createObject('Transform');
- g.atmosphere.addShape(atmosphere);
- g.atmosphere.parent = g.root;
-
- g.energyShape = createEnergyShape(g.pack,
- g.energyMaterial,
- g.ENERGY_WIDTH,
- g.ENERGY_HEIGHT);
-
- addEnergyShard(0, 0, 1, 1, [1, 1, 1, 1]);
-
- // Honolulu, Hawaii, 21, 18, 157, 50
- addEnergyShard(21.18, 157.50, 1, 1, [0, 1, 0, 1]);
- // San Francisco, Calif. 37 47 122 26
- addEnergyShard(37.47, 122.26, 1, 1, [1, 0.5, 0.5, 1]);
-
- for (var ii = 0; ii < 24; ++ii) {
- var longitude = Math.random() * 360;
- var latitude = Math.random() * 360 - 180;
- var color = [ Math.random() * 0.5 + 0.2,
- Math.random() * 0.5 + 0.2,
- Math.random() * 0.5 + 0.2,
- 1 ];
- for (var jj = 0; jj < 24; ++jj) {
- addEnergyShard(latitude + (Math.random() - 0.5) * 10,
- longitude + (Math.random() - 0.5) * 10,
- 1,
- 1,
- color);
- }
- }
-
- o3djs.event.addEventListener(g.o3dElement, 'mousedown', startDragging);
- o3djs.event.addEventListener(g.o3dElement, 'mousemove', drag);
- o3djs.event.addEventListener(g.o3dElement, 'mouseup', stopDragging);
- o3djs.event.addEventListener(g.o3dElement, 'wheel', scrollMe);
-
- loadDayTexture();
-}
-
-function loadTexture(path, callback) {
- var url = getURL(path);
- o3djs.io.loadTexture(g.pack, url, function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- callback(texture);
- }
- });
-}
-
-function loadDayTexture() {
- loadTexture('assets/earth.jpg', function(texture) {
- g.daySampler.texture = texture;
- g.earthPrimitive.material = g.dayOnlyMaterial;
- g.flatToDayCounter.running = true;
- });
-}
-
-function loadNightTexture() {
- loadTexture('assets/night.jpg', function(texture) {
- g.nightSampler.texture = texture;
- g.earthPrimitive.material = g.nightAndDayMaterial;
- g.dayOnlyToNightCounter.running = true;
- });
-}
-
-function loadMaskTexture() {
- loadTexture('assets/earth-large-with-ocean-mask.png', function(texture) {
- g.maskSampler.texture = texture;
- g.earthPrimitive.material = g.maskMaterial;
- g.noMaskToMaskCounter.running = true;
- g_finished = true; // for selenium
- });
-}
-
-function uninit() {
- // TODO: We should clean up any counters that have callbacks here.
- if (g.client) {
- g.client.cleanup();
- }
-}
-</script>
-<!--<h1>
-Google Trends Visualizer.
-</h1>-->
-<div id="o3d" style="width:100%; height: 100%;"></div>
-<div style="display:none">
-<textarea id="noTexture" name="fx" cols="80" rows="20">
-uniform mat4 worldViewProjection;
-uniform mat4 world;
-uniform mat4 view;
-
-uniform vec3 sunPos;
-
-attribute vec4 position;
-attribute vec3 normal;
-
-varying vec4 v_pos;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-void main() {
- gl_Position = worldViewProjection * position;
- v_normal = (world * vec4(normal, 0)).xyz;
- vec3 worldPos = (world * position).xyz;
- v_sun = sunPos - worldPos;
- v_view = (view[3].xyz- worldPos);
- v_pos = gl_Position;
-}
-
-// #o3d SplitMarker
-
-varying vec4 v_pos;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-vec4 lit(float l, float h, float m) {
- return vec4(1.0,
- max(l, 0.0),
- (l > 0.0) ? pow(max(0.0, h), m) : 0.0,
- 1.0);
-}
-
-void main() {
- vec3 norm = normalize(v_normal);
- vec3 sun = normalize(v_sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1.0 - sqrt(abs(light));
- dayNight = dayNight * dayNight;
- dayNight = (1.0 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0.0, 1.0);
- vec3 view = normalize(v_view);
- vec3 r = normalize(reflect(norm, sun));
- vec4 litR = vec4(lit(light, dot(r, view), 0.0).y);
- vec3 day = vec3(0.5, 0.5, 1.0) * litR.y + vec3(1,1,1) * litR.z;
- vec3 night = vec3(0.2, 0.2, 0.5);
- gl_FragColor = vec4(mix(night, day, dayNight),1);
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<textarea id="dayOnly" name="fx" cols="80" rows="20">
-uniform mat4 worldViewProjection;
-uniform mat4 world;
-uniform mat4 view;
-
-uniform vec3 sunPos;
-
-attribute vec4 position;
-attribute vec3 normal;
-attribute vec2 texCoord0;
-
-varying vec2 v_uv;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-void main() {
- gl_Position = (worldViewProjection * position);
- v_uv = texCoord0;
- v_normal = (world * vec4(normal, 0)).xyz;
- vec3 worldPos = (world * position).xyz;
- v_sun = sunPos - worldPos;
- v_view = (view[3].xyz - worldPos);
-}
-
-// #o3d SplitMarker
-
-uniform float time;
-
-uniform sampler2D daySampler;
-
-varying vec2 v_uv;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-vec4 lit(float l, float h, float m) {
- return vec4(1.0,
- max(l, 0.0),
- (l > 0.0) ? pow(max(0.0, h), m) : 0.0,
- 1.0);
-}
-
-void main() {
- vec3 norm = normalize(v_normal);
- vec3 sun = normalize(v_sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1.0 - sqrt(abs(light));
- dayNight = dayNight * dayNight;
- dayNight = (1.0 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0.0, 1.0);
- vec3 view = normalize(v_view);
- vec3 r = normalize(reflect(norm, sun));
- vec4 litR = vec4(lit(light, dot(r, view), 0.0).y);
- vec3 earth = texture2D(daySampler, v_uv).xyz;
- vec3 day = mix(vec3(0.5, 0.5, 1.0), earth, time);
- day = day * litR.y + vec3(1,1,1) * litR.z;
- vec3 night = mix(vec3(0.2, 0.2, 0.5), earth * 0.3, time);
- gl_FragColor = vec4(mix(night, day, dayNight),1);
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<textarea id="nightAndDay" name="fx" cols="80" rows="20">
-uniform mat4 worldViewProjection;
-uniform mat4 world;
-uniform mat4 view;
-
-uniform vec3 sunPos;
-
-attribute vec4 position;
-attribute vec3 normal;
-attribute vec2 texCoord0;
-
-varying vec2 v_uv;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-void main() {
- gl_Position = worldViewProjection * position;
- v_uv = texCoord0;
- v_normal = (world * vec4(normal, 0)).xyz;
- vec3 worldPos = (world * position).xyz;
- v_sun = sunPos - worldPos;
- v_view = (view[3].xyz - worldPos);
-}
-
-// #o3d SplitMarker
-
-uniform float time;
-
-uniform sampler2D daySampler;
-uniform sampler2D nightSampler;
-
-varying vec2 v_uv;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-vec4 lit(float l, float h, float m) {
- return vec4(1.0,
- max(l, 0.0),
- (l > 0.0) ? pow(max(0.0, h), m) : 0.0,
- 1.0);
-}
-
-void main() {
- vec3 norm = normalize(v_normal);
- vec3 sun = normalize(v_sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1.0 - sqrt(abs(light));
- dayNight = dayNight * dayNight;
- dayNight = (1.0 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0.0, 1.0);
- vec3 view = normalize(v_view);
- vec3 r = normalize(reflect(norm, sun));
- vec4 litR = vec4(lit(light, dot(r, view), 0.0).y);
- vec3 earth = texture2D(daySampler, v_uv).xyz;
- vec3 day = texture2D(daySampler, v_uv).xyz;
- vec3 night = mix(day * 0.3, texture2D(nightSampler, v_uv).xyz, time);
- day = day * litR.y + vec3(1,1,1) * litR.z;
- gl_FragColor = vec4(mix(night, day, dayNight),1);
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<!--
-This shader renders the ocean different then the non-ocean using a mask
-stored in the alpha channel of the maskSampler
--->
-<textarea id="mask" name="fx" cols="80" rows="20">
-uniform mat4 worldViewProjection;
-uniform mat4 world;
-uniform mat4 view;
-
-uniform vec3 sunPos;
-
-attribute vec4 position;
-attribute vec3 normal;
-attribute vec2 texCoord0;
-
-varying vec2 v_uv;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-void main() {
- gl_Position = worldViewProjection * position;
- v_uv = texCoord0;
- v_normal = (world * vec4(normal, 0)).xyz;
- vec3 worldPos = (world * position).xyz;
- v_sun = sunPos - worldPos;
- v_view = (view[3].xyz - worldPos);
-}
-
-// #o3d SplitMarker
-
-uniform float time;
-
-uniform sampler2D daySampler;
-uniform sampler2D nightSampler;
-uniform sampler2D maskSampler;
-
-varying vec2 v_uv;
-varying vec3 v_normal;
-varying vec3 v_sun;
-varying vec3 v_view;
-
-vec4 lit(float l, float h, float m) {
- return vec4(1.0,
- max(l, 0.0),
- (l > 0.0) ? pow(max(0.0, h), m) : 0.0,
- 1.0);
-}
-
-void main() {
- vec3 norm = normalize(v_normal);
- vec3 sun = normalize(v_sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1.0 - sqrt(abs(light));
- dayNight = dayNight * dayNight;
- dayNight = (1.0 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0.0, 1.0);
- vec3 view = normalize(v_view);
- vec3 r = normalize(reflect(norm, sun));
- vec4 litR = vec4(lit(light, dot(r, view), 0.0).y);
- vec3 earth = texture2D(daySampler, v_uv).xyz;
- vec4 mask = texture2D(maskSampler, v_uv);
- vec3 day = mix(texture2D(daySampler, v_uv).xyz,
- mask.xyz, time);
- vec3 night = texture2D(nightSampler, v_uv).xyz;
- day = day * litR.y + vec3(1,1,1) * litR.z * (1.0 - mask.w * time);
- vec3 color = mix(night, day, dayNight);
- gl_FragColor = vec4(color, 1);
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<textarea id="energy" name="fx" cols="80" rows="20">
-uniform mat4 worldViewProjection;
-
-// time is used to scroll the UV coords
-uniform float time;
-
-// offset is used to allow each shard to scroll over a different part of the
-// texture.
-uniform float offset;
-
-attribute vec4 position;
-attribute vec4 color;
-attribute vec2 texCoord0;
-
-varying vec4 v_color;
-varying vec2 v_uv;
-
-void main() {
- gl_Position = worldViewProjection * position;
- v_uv = vec2(texCoord0.x, texCoord0.y + time + offset);
- v_color = color;
-}
-
-// #o3d SplitMarker
-
-// Sets the color of the shard.
-uniform vec4 colorMult;
-
-// Provides the dots on the shard.
-uniform sampler2D energySampler;
-
-varying vec4 v_color;
-varying vec2 v_uv;
-
-void main() {
- gl_FragColor = texture2D(energySampler, v_uv) * v_color * colorMult;
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<textarea id="atmosphere" name="fx" cols="80" rows="20">
-uniform mat4 worldViewProjection;
-uniform mat4 worldView;
-
-attribute vec4 position;
-attribute vec3 normal;
-
-varying vec3 v_normal;
-
-void main() {
- gl_Position = worldViewProjection * position;
- v_normal = normalize((worldView * vec4(normal,0)).xyz);
-}
-
-// #o3d SplitMarker
-
-varying vec3 v_normal;
-
-void main() {
- float n = 1.0 - log(2.0 * normalize(v_normal).z);
- gl_FragColor = vec4(0.3, 0.3, 1, n * n * n * n);
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
-</html>
-
-
diff --git a/o3d/samples/o3d-webgl-samples/vertex-shader-animation.html b/o3d/samples/o3d-webgl-samples/vertex-shader-animation.html
deleted file mode 100644
index 331011c..0000000
--- a/o3d/samples/o3d-webgl-samples/vertex-shader-animation.html
+++ /dev/null
@@ -1,203 +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.
--->
-
-<!--
-O3D Vertex Shader Animation Example.
-
-Demonstrates using a vertex shader for simple animation. The shader moves the
-vertices in a sin wave based on the parameter "time" and the world position
-of the vertices.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Vertex Shader Animation
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- }
-</style>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// global variables
-var g_o3d;
-var g_o3dElement;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_timeParam;
-
-/**
- * Creates the client area.
- */
-function init() {
- // These are here so that they are visible to both the browser (so
- // selenium sees them) and the embedded V8 engine.
- window.g_clock = 0;
- window.g_timeMult = 1;
- window.g_finished = false; // for selenium testing.
-
- // Comment out the line below to run the sample in the browser
- // JavaScript engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and creates the quads.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
-
- // Set window.g_client as well. Otherwise when the sample runs in
- // V8, selenium won't be able to find this variable (it can only see
- // the browser environment).
- window.g_client = g_client = g_o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create a material.
- var material = o3djs.material.createMaterialFromFile(
- g_pack,
- '../shaders/phong-vertex-anim-glsl.shader',
- g_viewInfo.performanceDrawList);
-
- // Set the material parameters.
- material.getParam('lightWorldPos').value = [-40, 100, 0];
- material.getParam('lightIntensity').value = [1, 1, 1, 1];
- material.getParam('ambientIntensity').value = [0.1, 0.1, 0.1, 1];
- material.getParam('ambient').value = [1, 1, 1, 1];
- material.getParam('diffuse').value = [1, 1, 1, 1];
- material.getParam('specular').value = [1, 1, 1, 1];
- material.getParam('shininess').value = 50;
-
- g_timeParam = material.getParam('time');
-
- // Create the view matrix which tells the camera which way to point to.
- var eye = [10, 50, 20];
- var target = [2, 0, -2];
- var up = [0, 0, -1];
- var view_matrix = g_math.matrix4.lookAt(eye, target, up);
-
- g_viewInfo.drawContext.view = view_matrix;
-
- var shape = o3djs.primitives.createPlane(g_pack, material,
- 10, 10, 100, 100);
- for (var xx = 0; xx < 5; xx++) {
- for (var yy = 0; yy < 4; yy++) {
- var index = yy * 3 + xx;
-
- // Make a transform for each quad.
- var transform = g_pack.createObject('Transform');
- transform.translate((xx - 2) * 12, 0, (2 - yy) * -12);
- transform.addShape(shape);
- transform.parent = g_client.root;
- transform.createParam('diffuse', 'ParamFloat4').value = [xx * 0.2,
- yy * 0.25,
- 0.5,
- 1];
- }
- }
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- window.g_finished = true; // for selenium testing.
-}
-
-function updateProjectionMatrix() {
- // Create our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 100.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 100);
-}
-
-// spin the camera.
-function onrender(render_event) {
- // Get the number of seconds since the last render.
- var elapsedTime = render_event.elapsedTime;
- // Update g_clock in the browser and cache a V8 copy that can be
- // accessed efficiently. g_clock must be in the browser for selenium.
- var clock = window.g_clock + elapsedTime * window.g_timeMult;
- window.g_clock = clock;
-
- updateProjectionMatrix();
-
- g_timeParam.value = clock * 4;
-}
-
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body onload="init()" onunload="unload()">
-<h1>Vertex Shader Animation Example</h1>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 100%; height: 80%"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/vertex-shader.html b/o3d/samples/o3d-webgl-samples/vertex-shader.html
deleted file mode 100644
index 526736e..0000000
--- a/o3d/samples/o3d-webgl-samples/vertex-shader.html
+++ /dev/null
@@ -1,334 +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.
--->
-
-<!--
-O3D Vertex Shader Demo
-
-This sample uses a custom vertex shader to quickly adjust the positions and
-normals of many vertices in a plane to achieve a ripple effect without iterating
-through the vertices in javascript.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Vertex Shader
-</title>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.effect');
-
-// global variables
-var g_o3dElement;
-var g_client;
-var g_o3d;
-var g_math;
-var g_pack;
-var g_viewInfo;
-var g_clockParam;
-
-/**
- * Creates the client area.
- */
-function init() {
- // These are here so that they are visible to both the browser (so
- // selenium sees them) and the embedded V8 engine.
- window.g_clock = 0;
- window.g_timeMult = 1;
- window.g_finished = false; // for selenium testing.
-
- // Comment out the line below to run the sample in the browser
- // JavaScript engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.webgl.makeClients(initStep2, 'LargeGeometry');
-}
-
-
-/**
- * Initializes global variables, positions camera, creates the material, and
- * draws the plane.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Init global variables.
- initGlobals(clientElements);
-
- // Set up the view and projection transformations.
- initContext();
-
- // Add the shapes to the transform hierarchy.
- createPlane();
-
- // Setup render callback.
- g_client.setRenderCallback(onRender);
-
- window.g_finished = true; // for selenium testing.
-}
-
-
-/**
- * Initializes global variables and libraries.
- * @param {Array} clientElements An array of o3d object elements assumed
- * to have one entry.
- */
-function initGlobals(clientElements) {
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
-
- // Set window.g_client as well. Otherwise when the sample runs in
- // V8, selenium won't be able to find this variable (it can only see
- // the browser environment).
- window.g_client = g_client = g_o3dElement.client;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-}
-
-
-/**
- * Sets up reasonable view and projection matrices.
- */
-function initContext() {
- // Set up a perspective transformation for the projection.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree frustum.
- g_client.width / g_client.height, // Aspect ratio.
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // cube is located.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [4, 4, 4], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-
-/**
- * Creates an effect using the shaders in the textarea in the document, applies
- * the effect to a new material, binds the uniform parameters of the shader
- * to parameters of the material, and sets certain parameters: the light and
- * camera position.
- * @return {Material} The material.
- */
-function createMaterial() {
- // Create a new, empty Material and Effect object.
- var material = g_pack.createObject('Material');
- var effect = g_pack.createObject('Effect');
-
- // Load shader string from document.
- var shaderString = document.getElementById('effect').value;
- effect.loadFromFXString(shaderString);
-
- // Apply the effect to this material.
- material.effect = effect;
-
- // Bind uniform parameters declared in shader to parameters of material.
- effect.createUniformParameters(material);
-
- // Set the material's drawList.
- material.drawList = g_viewInfo.performanceDrawList;
-
- // Set light and camera positions for the pixel shader.
- material.getParam('lightWorldPos').value = [3, 10, 0];
- material.getParam('cameraWorldPos').value = [1, 3, 12];
-
- // Look up clock param.
- g_clockParam = material.getParam('clock');
-
- return material;
-}
-
-
-/**
- * Creates the plane using the primitives utility library, and adds it to the
- * transform graph at the root node.
- */
-function createPlane() {
- // This will create a plane subdivided into 80,000 triangles.
- var plane = o3djs.primitives.createPlane(
- g_pack, createMaterial(), 4, 4, 200, 200);
-
- // Add the shape to the transform hierarchy.
- g_client.root.addShape(plane);
-}
-
-
-/**
- * Updates the clock for the animation.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- // Update g_clock in the browser and cache a V8 copy that can be
- // accessed efficiently. g_clock must be in the browser for selenium.
- var clock = window.g_clock + elapsedTime * window.g_timeMult;
- window.g_clock = clock;
-
- g_clockParam.value = clock;
-}
-
-
-/**
- * Cleanup before exiting.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body onload="init()" onunload="unload()">
-<h1>Vertex Shader</h1>
-This sample uses a custom vertex shader to quickly adjust the positions and
-normals of many vertices in a plane to achieve a ripple effect without iterating
-through the vertices in javascript.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-
-<!-- Text area to hold the shaders -->
-<textarea id="effect" name="effect" cols="80" rows="20"
- style="display: none;">
-uniform mat4 world;
-uniform mat4 worldViewProjection;
-uniform mat4 worldInverseTranspose;
-
-uniform float clock;
-
-// Input parameters for the vertex shader.
-attribute vec4 position;
-attribute vec3 normal;
-attribute vec4 color;
-
-// Input parameters for the pixel shader (also the output parameters for the
-// vertex shader.)
-varying vec3 v_objectPosition;
-varying vec3 v_normal;
-varying vec4 v_color;
-
-/**
- * A function defining the shape of the wave. Takes a single vec2 as an
- * argument the entries of which are the x and z components of a point in the
- * plane. Returns the height of that point.
- *
- * @param {vec2} v The x and z components of the point in a single vec2.
- */
-float wave(vec2 v) {
- float d = length(v);
- return 0.15 * sin(15.0 * d - 5.0 * clock) / (1.0 + d * d);
-}
-
-
-/**
- * vertexShaderFunction - The vertex shader perturbs the vertices of the plane
- * to achieve the ripples. Then it applies the worldViewProjection matrix.
- *
- * @param input.position Position vector of vertex in object coordinates.
- * @param input.normal Normal of vertex in object coordinates.
- * @param input.color Color of vertex.
- */
-void main() {
- vec4 p = position;
-
- // The height of the point p is adjusted according to the wave function.
- p.y = wave(p.xz);
-
- // Step size used to approximate the partial derivatives of the wave function.
- float h = 0.001;
-
- // We take the derivative numerically so that the wave function can be
- // modified and the normal will still be correct.
- vec3 n = normalize(vec3(
- wave(vec2(p.x - h, p.z)) - wave(vec2(p.x + h, p.z)), 2.0 * h,
- wave(vec2(p.x, p.z - h)) - wave(vec2(p.x, p.z + h))));
-
- gl_Position = worldViewProjection * p;
- v_objectPosition = (world * p).xyz;
- v_normal = (worldInverseTranspose * vec4(n, 1.0)).xyz;
- v_color = color;
-}
-
-// #o3d SplitMarker
-
-uniform float clock;
-uniform vec3 lightWorldPos;
-uniform vec3 cameraWorldPos;
-
-varying vec3 v_objectPosition;
-varying vec3 v_normal;
-varying vec4 v_color;
-
-/**
- * This pixel shader is meant to be minimal since the vertex shader is
- * the focus of the sample.
- */
-void main() {
- vec3 p = v_objectPosition; // The point in question.
- vec3 l = normalize(lightWorldPos - p); // Unit-length vector toward light.
- vec3 n = normalize(v_normal); // Unit-length normal vector.
- vec3 v = normalize(cameraWorldPos - p); // Unit-length vector toward camera.
- vec3 r = normalize(-reflect(v, n)); // Reflection of v across n.
-
- vec3 q = (lightWorldPos - p);
- float ldotr = dot(r, l);
- float specular = clamp(ldotr, 0.0, 1.0) /
- (1.0 + length(q - length(q) * ldotr * r));
-
- // Fixed color to be a blue-green; could use v_color instead below.
- gl_FragColor = vec4(0, 0.6, 0.7, 1) * dot(n, l) + specular;
-}
-
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/yuv2rgb.html b/o3d/samples/o3d-webgl-samples/yuv2rgb.html
deleted file mode 100644
index 64b4035..0000000
--- a/o3d/samples/o3d-webgl-samples/yuv2rgb.html
+++ /dev/null
@@ -1,203 +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.
--->
-
-<!--
-
-O3D YUV to RGB conversion Tutorial
-
-In this sample we convert from a Y'UV420p encoded video frame to an
-RGB texture using a shader to do the conversion on the video hardware.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>YUV to RGB Conversion in a shader.</title>
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.io');
-
-// Events
-// Run the init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_finished = false; // for selenium testing
-
-/**
- * Creates the client area and sets up the secondary init entry point.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and draws the quad that
- * will display the texture.
- *
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Setup an orthographic projection
- // Offset by half a pixel to avoid roundoff errors.
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -g_client.width * 0.5 + 0.5,
- g_client.width * 0.5 + 0.5,
- -g_client.height * 0.5 - 0.5,
- g_client.height * 0.5 - 0.5,
- 0.1,
- 1000);
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 500, 0],
- [0, 0, 0],
- [0, 0, -1]);
-
- // Create a material.
- var myMaterial = o3djs.material.createMaterialFromFile(
- g_pack,
- '../shaders/yuv2rgb-glsl.shader',
- g_viewInfo.performanceDrawList);
-
- // Creates a quad using the effect that has a 1:1 aspect ratio.
- var myShape = o3djs.primitives.createPlane(g_pack,
- myMaterial,
- 720, // width
- 720, // height
- 1, // quads across
- 1); // quads down
-
-
- // Get the material's sampler parameter
- var sampler_param = myMaterial.getParam('textureSampler');
- var sampler = g_pack.createObject('Sampler');
- sampler.addressModeU = g_o3d.Sampler.WRAP;
- sampler.addressModeV = g_o3d.Sampler.WRAP;
- sampler.magFilter = g_o3d.Sampler.POINT;
- sampler.minFilter = g_o3d.Sampler.POINT;
-
- // Be sure to turn off MIP-mapping, since that causes problems when
- // jumping around the image the way we are.
- sampler.mipFilter = g_o3d.Sampler.NONE;
- sampler_param.value = sampler;
-
- // Set the source image width
- var width_param = myMaterial.getParam('imageWidth');
- width_param.value = 720.0;
-
- // Set the source image height
- var height_param = myMaterial.getParam('imageHeight');
- height_param.value = 486.0;
-
- // Load our Y'UV420p texture, encoded as a greyscale PNG image. This
- // happens asynchronously.
- var url = o3djs.util.getCurrentURI() + '../assets/shaving_cream.png';
- o3djs.io.loadTexture(g_pack, url, function(texture, exception) {
- if (exception) {
- alert(exception);
- return;
- }
- sampler.texture = texture;
- // adjust the scale of our transform to match the aspect ratio of
- // the texture. Of course we could also have waited until now to build
- // our quad and set its width and height to match instead of scaling
- // here.
- var textureWidth = texture.width;
-
- // Account for additional data on bottom of image.
- var textureHeight = texture.height * 2.0 / 3.0;
- var hScale = 1;
- var vScale = 1;
- if (textureWidth > textureHeight) {
- vScale = textureHeight / textureWidth;
- } else if (textureHeight > textureWidth) {
- hScale = textureWidth / textureHeight;
- }
- // We now attach our quad to the root of the transform graph. We do
- // this after the texture has loaded, otherwise we'd be attempting
- // to display something invalid.
- var root = g_client.root;
- root.addShape(myShape);
- root.scale(hScale, 1, vScale);
-
- g_finished = true; // for selenium testing.
- });
-}
-</script>
-</head>
-<body>
-<h1>YUV to RGB Conversion</h1>
-<p>This how to do image colorspace and format conversion in a shader.</p>
-<p>Here is the YUV encoded image (treated as an 8-bit greyscale image):</p>
-<p><img src="../assets/shaving_cream.png" style="width: 720px; height: 729px"
- alt="YUV encoded image"/></p>
-<p>Here is the original image, encoded as a JPEG image:</p>
-<p><img src="../assets/shaving_cream.jpg" style="width: 720px; height: 486px"
- alt="Original JPG encoded image"/></p>
-<p>Here is the O3D plugin loading the YUV image, and converting it
-to RGB in the shader on the fly.</p>
-<p>Note: With O3D-WebGL, we cannot get an exact translation back to the original
-image due to WebGL behavior that does not occur in the plugin. See shader for
-more details.</p>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 720px; height: 486px"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl-samples/zsorting.html b/o3d/samples/o3d-webgl-samples/zsorting.html
deleted file mode 100644
index 36a7658..0000000
--- a/o3d/samples/o3d-webgl-samples/zsorting.html
+++ /dev/null
@@ -1,203 +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.
--->
-
-<!--
-O3D ZSorting.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-ZSorting.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../o3d-webgl/base.js"></script>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.base.o3d = o3d;
-o3djs.require('o3djs.webgl');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_timeMult = 1.0;
-var g_framesRendered = 0;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_clock = 0;
-var g_finished = false; // for selenium testing
-var g_groupTransforms = [];
-var GROUPS_ACROSS = 2;
-var UNITS_ACROSS_GROUP = 2;
-var TOTAL_ACROSS = GROUPS_ACROSS * UNITS_ACROSS_GROUP;
-var HALF_WIDTH = TOTAL_ACROSS * 0.0;
-var UNIT_SPACING = 100;
-
-/**
- * Make a grid of transforms and put a teapot instance on each one
- * @param {!o3d.Pack} pack Pack to create transforms in.
- * @param {!o3d.Shape} shape Shape to instance.
- */
-function createInstances(pack, shape) {
- for (var g = 0; g < GROUPS_ACROSS; g++) {
- for (var h = 0; h < GROUPS_ACROSS; h++) {
- for (var i = 0; i < GROUPS_ACROSS; i++) {
- var groupTransform = pack.createObject('Transform');
- g_groupTransforms[g_groupTransforms.length] = groupTransform;
- groupTransform.parent = g_client.root;
- groupTransform.translate(
- (g * UNITS_ACROSS_GROUP - HALF_WIDTH) * UNIT_SPACING,
- (h * UNITS_ACROSS_GROUP - HALF_WIDTH) * UNIT_SPACING,
- (i * UNITS_ACROSS_GROUP - HALF_WIDTH) * UNIT_SPACING);
- for (var x = 0; x < UNITS_ACROSS_GROUP; x++) {
- for (var y = 0; y < UNITS_ACROSS_GROUP; y++) {
- for (var z = 0; z < UNITS_ACROSS_GROUP; z++) {
- var transform = pack.createObject('Transform');
- transform.parent = groupTransform;
- transform.addShape(shape);
- transform.translate(
- (x - UNITS_ACROSS_GROUP * 0.5) * UNIT_SPACING,
- (y - UNITS_ACROSS_GROUP * 0.5) * UNIT_SPACING,
- (z - UNITS_ACROSS_GROUP * 0.5) * UNIT_SPACING);
- transform.createParam('diffuse', 'ParamFloat4').value = [
- (g * UNITS_ACROSS_GROUP + x) * (1 / TOTAL_ACROSS),
- (h * UNITS_ACROSS_GROUP + y) * (1 / TOTAL_ACROSS),
- (i * UNITS_ACROSS_GROUP + z) * (1 / TOTAL_ACROSS),
- 0.5];
- }
- }
- }
- }
- }
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.webgl.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create our projection matrix, with a vertical field of view of 45
- // degrees a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 10000);
-
- // Create a Material.
- var material = o3djs.material.createBasicMaterial(
- g_pack, g_viewInfo, [1, 1, 1, 1], true);
-
- // Create a sphere.
- var shape = o3djs.primitives.createSphere(g_pack, material, 30, 20, 20);
-
- createInstances(g_pack, shape);
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-// spin the camera.
-function onrender(renderEvent) {
- g_framesRendered++;
- // Get the number of seconds since the last render.
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- var x = Math.sin(g_clock * 0.1) * 400;
- var z = Math.cos(g_clock * 0.1) * 400;
- var y = Math.sin(g_clock * 0.2) * 400;
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [x, y, z], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>ZSorting</h1>
-Objects get zsorted for transparency.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/o3d-webgl/archive_request.js b/o3d/samples/o3d-webgl/archive_request.js
deleted file mode 100644
index ca2c95e..0000000
--- a/o3d/samples/o3d-webgl/archive_request.js
+++ /dev/null
@@ -1,275 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-// TODO(kbr): figure out how we can reuse the o3djs.io package from
-// within here.
-// o3djs.require('o3djs.io');
-
-// TODO(kbr): factor this out into e.g. o3djs.json and require
-// o3djs.json here.
-if(!this.JSON){this.JSON={};}
-(function(){function f(n){return n<10?'0'+n:n;}
-if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+
-f(this.getUTCMonth()+1)+'-'+
-f(this.getUTCDate())+'T'+
-f(this.getUTCHours())+':'+
-f(this.getUTCMinutes())+':'+
-f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
-var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
-function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
-if(typeof rep==='function'){value=rep.call(holder,key,value);}
-switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
-gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
-v=partial.length===0?'[]':gap?'[\n'+gap+
-partial.join(',\n'+gap)+'\n'+
-mind+']':'['+partial.join(',')+']';gap=mind;return v;}
-if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
-v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
-mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
-if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
-rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
-return str('',{'':value});};}
-if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
-return reviver.call(holder,key,value);}
-text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
-('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
-if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
-throw new SyntaxError('JSON.parse');};}}());
-
-
-/**
- An ArchiveRequest object is used to carry out an asynchronous request for a
- compressed archive (containing multiple files).
-
- Note: The archive must have as its first file a file named 'aaaaaaaa.o3d'
- who's contents is 'o3d'. This is to prevent O3D being used to open
- archive files that were not meant for it.
-
- \code
- var request = pack.createArchiveRequest();
- request.open("GET", url);
-
- request.onfileavailable = myFileAvailableCallback;
- request.onreadystatechange = myReadyStateChangeCallback;
- request.send();
-
- function myFileAvailableCallback(rawData) {
- dump("uri: " + rawData.uri + "\n");
- dump("content: " + rawData.stringValue + "\n");
-
- // You can pass a RawData to various creation functions. Note: rawData
- // is only valid until you remove the request.
- // Examples:
- if (rawData.uri == 'mytexture.jpg')
- pack.createTexture2d(rawData, makeMips);
- if (rawData.uri == 'myvertices.bin')
- vertexBuffer.set(rawData);
- if (rawData.uri == 'myAudio.mp3')
- audioSystem.createSound(rawData);
- }
-
- function myReadyStateChangeCallback() {
- if (request.done) {
- if (request.success) {
- // there were no errors trying to read the archive
- } else {
- dump(request.error);
- }
- }
- }
-
- // When you are done with the RawDatas loaded by the request, remove
- // the request from the pack to free them.
- pack.removeObject(request);
-*/
-
-o3d.ArchiveRequest = function() {
- o3d.ObjectBase.call(this);
- this.method_ = null;
-};
-o3d.inherit('ArchiveRequest', 'ObjectBase');
-
-/**
- * The URI this request is for.
- * @type {string}
- */
-o3d.ArchiveRequest.prototype.uri = '';
-
-/**
- * Set up several of the request fields.
- * @param {string} method "GET" is the only supported method at this time
- * @param {string} uri the location of the file to fetch
- * @param {boolean} async true is the only legal value at this time.
- */
-o3d.ArchiveRequest.prototype.open =
- function(method, uri) {
- this.uri = uri;
-
- // Compute the parent directory of this URI.
- var parentURI = uri;
- var lastSlash = uri.lastIndexOf('/');
- if (lastSlash != -1) {
- parentURI = parentURI.substring(0, lastSlash + 1);
- }
-
- this.parentURI_ = parentURI;
-};
-
-/**
- * Sends the request. In this implementation, this function sets up a callback
- * which searches the json it loads for more files to load. It then sends
- * requests for each of those files. When the last of those files has loaded,
- * the onreadystatechange callback will get called. Unlike XMLHttpRequest the
- * onreadystatechange callback will be called no matter what, with success or
- * failure.
- */
-o3d.ArchiveRequest.prototype.send = function() {
- var that = this;
- this.done = false;
- this.success = true;
- this.error = null;
- var callback = function(sourceJSON, exc) {
- // Don't send down the original scene.json because 'eval' is used
- // elsewhere to reconstitute it, which is risky.
- var filteredJSON = JSON.stringify(JSON.parse(sourceJSON));
-
- var rawData = new o3d.RawData();
- rawData.uri = 'scene.json';
- rawData.stringValue = filteredJSON;
-
- // In o3d-webgl, the "archive" is really just the top-level
- // scene.json. We run a regexp on it to find URIs for certain
- // well-known file types (.fx, .png, .jpg) and issue file requests
- // for them.
- var uriRegex = /\"([^\"]*\.(fx|png|jpg))\"/g;
- var matchArray;
- var uris = [];
- while ((matchArray = uriRegex.exec(sourceJSON)) != null) {
- uris.push(matchArray[1]);
- }
-
- // Plus one for the current request.
- that.pendingRequests_ = uris.length + 1;
-
- // Issue requests for each of these URIs.
- for (var ii = 0; ii < uris.length; ++ii) {
- if (that.stringEndsWith_(uris[ii], ".fx")) {
- var func = function(uri) {
- var completion = function(value, exc) {
- var rawData = null;
- if (exc == null) {
- rawData = new o3d.RawData();
- rawData.uri = uri;
- rawData.stringValue = value;
- }
- that.resolvePendingRequest_(rawData, exc);
- };
- o3djs.io.loadTextFile(that.relativeToAbsoluteURI_(uri),
- completion);
- };
- func(uris[ii]);
- } else if (that.stringEndsWith_(uris[ii], ".png") ||
- that.stringEndsWith_(uris[ii], ".jpg")) {
- var func = function(uri) {
- var image = new Image();
- image.onload = function() {
- var rawData = new o3d.RawData();
- rawData.uri = uri;
- rawData.image_ = image;
- that.resolvePendingRequest_(rawData, exc);
- };
- image.onerror = function() {
- that.resolvePendingRequest_(null, exc);
- }
- image.src = that.relativeToAbsoluteURI_(uri);
- };
- func(uris[ii]);
- }
- }
-
- that.resolvePendingRequest_(rawData);
- };
-
- o3djs.io.loadTextFile(this.uri, callback);
-};
-
-/**
- * A callback to call whenever the ready state of the request changes.
- * @type {function(): void}
- */
-o3d.ArchiveRequest.prototype.onreadystatechange = null;
-
-/**
- * A callback to call when each file comes in.
- * @type {function(!o3d.RawData): void}
- */
-o3d.ArchiveRequest.prototype.onfileavailable = null;
-
-/**
- * Converts a local URI to an absolute URI.
- * @private
- */
-o3d.ArchiveRequest.prototype.relativeToAbsoluteURI_ = function(relativeURI) {
- return this.parentURI_ + relativeURI;
-};
-
-/**
- * Indicates whether one string ends with another.
- * @private
- */
-o3d.ArchiveRequest.prototype.stringEndsWith_ = function(string, suffix) {
- return string.substring(string.length - suffix.length) == suffix;
-};
-
-/**
- * Decrements the number of pending requests. Calls onfileavailable callback
- * if one is provided, calls onreadystatechange if this is the last of the
- * requests.
- * @param {o3d.RawData} rawData The current raw data object.
- * @param {Object} opt_exc An optional exception.
- * @private
- */
-o3d.ArchiveRequest.prototype.resolvePendingRequest_ =
- function(rawData, opt_exc) {
- this.success = this.success && rawData && (!opt_exc);
- if (opt_exc != null) {
- this.error = "" + opt_exc;
- }
- if (rawData && this.onfileavailable) {
- this.onfileavailable(rawData);
- }
- if (--this.pendingRequests_ == 0) {
- this.done = true;
- if (this.onreadystatechange) {
- this.onreadystatechange();
- }
- }
-};
diff --git a/o3d/samples/o3d-webgl/base.js b/o3d/samples/o3d-webgl/base.js
deleted file mode 100644
index 3572a25..0000000
--- a/o3d/samples/o3d-webgl/base.js
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * @fileoverview Base for all o3d classes implemented in javscript.
- * Include just this file in a script tag and it will include all other
- * source files needed by o3d.
- * For more information about o3d see
- * http://code.google.com/p/o3d.
- */
-
-/**
- * A namespace for all the o3d classes.
- * @namespace
- */
-var o3d = o3d || {};
-
-/**
- * Define this because the Google internal JSCompiler needs goog.typedef below.
- */
-var goog = goog || {};
-
-/**
- * A macro for defining composite types.
- *
- * By assigning goog.typedef to a name, this tells Google internal JSCompiler
- * that this is not the name of a class, but rather it's the name of a composite
- * type.
- *
- * For example,
- * /** @type {Array|NodeList} / goog.ArrayLike = goog.typedef;
- * will tell JSCompiler to replace all appearances of goog.ArrayLike in type
- * definitions with the union of Array and NodeList.
- *
- * Does nothing in uncompiled code.
- */
-goog.typedef = true;
-
-/**
- * Reference to the global context. In most cases this will be 'window'.
- */
-o3d.global = this;
-
-/**
- * Path for included scripts.
- * @type {string}
- */
-o3d.basePath = '';
-
-/**
- * Some javascripts don't support __defineGetter__ or __defineSetter__
- * so we define some here so at least we don't get compile errors.
- * We expect the initialzation code will check and complain. This stubs
- * are just here to make sure we can actually get to the initialization code.
- */
-if (!Object.prototype.__defineSetter__) {
- Object.prototype.__defineSetter__ = function() {}
- Object.prototype.__defineGetter__ = function() {}
-}
-
-/**
- * Tries to detect the base path of the base.js script that
- * bootstraps the o3d libraries.
- * @private
- */
-o3d.findBasePath_ = function() {
- var doc = o3d.global.document;
- if (typeof doc == 'undefined') {
- return;
- }
- if (o3d.global.BASE_PATH) {
- o3d.basePath = o3d.global.BASE_PATH;
- return;
- } else {
- // HACK to hide compiler warnings :(
- o3d.global.BASE_PATH = null;
- }
- var scripts = doc.getElementsByTagName('script');
- for (var script, i = 0; script = scripts[i]; i++) {
- var src = script.src;
- var l = src.length;
- var s = 'o3d-webgl/base.js';
- var sl = s.length;
- if (src.substr(l - sl) == s) {
- o3d.basePath = src.substr(0, l - sl) + 'o3d-webgl/';
- return;
- }
- }
-};
-
-/**
- * Writes a script tag for the given o3d source file name
- * to the document. (Must be called at execution time.)
- * @param {string} src The full path to the source file.
- * @private
- */
-o3d.writeScriptTag_ = function(src) {
- var doc = o3d.global.document;
- if (typeof doc != 'undefined') {
- doc.write('<script type="text/javascript" src="' +
- src + '"></' + 'script>');
- }
-};
-
-/**
- * Filters any "o3d." prefix from the given type name.
- * @param {string} type_name The type name to filter.
- * @return {string} Filtered type name.
- * @private
- */
-o3d.filterTypeName_ = function(type_name) {
- if (type_name.length >= 4 && type_name.substr(0, 4) == 'o3d.') {
- type_name = type_name.substr(4);
- }
- return type_name;
-};
-
-/**
- * Includes the file indicated by the rule by adding a script tag.
- * @param {string} rule Rule to include, in the form o3d.package.part.
- */
-o3d.include = function(rule) {
- var parts = rule.split('.');
- var path = parts[parts.length - 1] + '.js';
- o3d.writeScriptTag_(o3d.basePath + path);
-};
-
-
-/**
- * Makes one class inherit from another. Adds the member variables superClass
- * and superClassName to the prototype of the sub class.
- * @param {string} subClass Class that wants to inherit.
- * @param {string} superClass Class to inherit from.
- */
-o3d.inherit = function(subClassName, superClassName) {
- var superClass = o3d.global.o3d[superClassName];
- var subClass = o3d.global.o3d[subClassName];
-
- if (!superClass)
- throw ('Invalid superclass: ' + superClassName);
- if (!subClass)
- throw ('Invalid subclass: ' + subClassName);
-
- subClass.prototype = new superClass;
- subClass.prototype.superClassName = superClassName;
- subClass.prototype.superClass = superClass;
- subClass.prototype.className = subClassName;
-};
-
-
-/**
- * Utility function to remove an object from an array.
- * @param {!Array} array The array.
- * @param {Object} object The thing to be removed.
- */
-o3d.removeFromArray = function(array, object) {
- var i = array.indexOf(object);
- if (i >= 0) {
- array.splice(i, 1);
- }
-};
-
-
-/**
- * Determine whether a value is an array. Do not use instanceof because that
- * will not work for V8 arrays (the browser thinks they are Objects).
- * @param {*} value A value.
- * @return {boolean} Whether the value is an array.
- */
-o3d.isArray_ = function(value) {
- var valueAsObject = /** @type {!Object} **/ (value);
- return typeof(value) === 'object' && value !== null &&
- 'length' in valueAsObject && 'splice' in valueAsObject;
-};
-
-
-/**
- * Utility function to clone an object.
- *
- * @param {Object} object The object to clone.
- * @return {Object} A clone of that object.
- */
-o3d.clone = function(object) {
- var result = o3d.isArray_(object) ? [] : {};
- for (var name in object) {
- var property = object[name];
- if (typeof property == 'Object') {
- result[name] = o3d.clone(property);
- } else {
- result[name] = property;
- }
- }
- return result;
-};
-
-
-/**
- * If an o3d function has not been implemented in javascript yet, it should
- * call this function to throw an error because it's better than doing
- * nothing.
- */
-o3d.notImplemented = function() {
- debugger;
- throw 'Not implemented.';
-};
-
-
-// First find the path to the directory where all o3d-webgl sources live.
-o3d.findBasePath_();
-
-
-// Unlike o3djs, we include all o3d-webgl files at once, this way, an o3d
-// developer converting to use these classes only has to include this
-// javascript file.
-o3d.include('object_base');
-o3d.include('named_object_base');
-o3d.include('named_object');
-o3d.include('param_object');
-o3d.include('param_array');
-o3d.include('transform');
-o3d.include('param');
-o3d.include('event');
-o3d.include('raw_data');
-o3d.include('texture');
-o3d.include('bitmap');
-o3d.include('file_request');
-o3d.include('client');
-o3d.include('render_node');
-o3d.include('clear_buffer');
-o3d.include('state_set');
-o3d.include('viewport');
-o3d.include('tree_traversal');
-o3d.include('draw_list');
-o3d.include('draw_pass');
-o3d.include('render_surface_set');
-o3d.include('render_surface');
-o3d.include('state');
-o3d.include('draw_context');
-o3d.include('ray_intersection_info');
-o3d.include('sampler');
-o3d.include('pack');
-o3d.include('bounding_box');
-o3d.include('draw_element');
-o3d.include('element');
-o3d.include('field');
-o3d.include('buffer');
-o3d.include('stream');
-o3d.include('vertex_source');
-o3d.include('stream_bank');
-o3d.include('primitive');
-o3d.include('shape');
-o3d.include('effect');
-o3d.include('material');
-o3d.include('archive_request');
-o3d.include('param_operation');
-o3d.include('function');
-o3d.include('counter');
-o3d.include('curve');
-o3d.include('skin');
-
-
diff --git a/o3d/samples/o3d-webgl/bitmap.js b/o3d/samples/o3d-webgl/bitmap.js
deleted file mode 100644
index 444fc0c..0000000
--- a/o3d/samples/o3d-webgl/bitmap.js
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * Bitmap provides an interface for basic image operations on bitmap,
- * including scale and crop. A Bitmap can be created from RawData via
- * pack.createBitmapsFromRawData(), and also can be transferred to mip of a
- * Texure2D or a specific face of TextureCUBE via methods in Texture.
- * @constructor
- */
-o3d.Bitmap = function() {
- o3d.ParamObject.call(this);
-};
-o3d.inherit('Bitmap', 'ParamObject');
-
-
-/**
- * @type {number}
- */
-o3d.Bitmap.Semantic = goog.typedef;
-
-/**
- * After loading an array of Bitmaps with pack.createBitmapsFromRawData
- * you can inspect their semantic to see what they were intended for. This is
- * mostly to distinguish between 6 bitmaps that are faces of a cubemap and 6
- * bitmaps that are slices of a 3d texture.
- *
- * FACE_POSITIVE_X, 1 face of a cubemap
- * FACE_NEGATIVE_X, 1 face of a cubemap
- * FACE_POSITIVE_Y, 1 face of a cubemap
- * FACE_NEGATIVE_Y, 1 face of a cubemap
- * FACE_POSITIVE_Z, 1 face of a cubemap
- * FACE_NEGATIVE_Z, 1 face of a cubemap
- * IMAGE, normal 2d image
- * SLICE, a slice of a 3d texture.
- */
-o3d.Bitmap.FACE_POSITIVE_X = 0;
-o3d.Bitmap.FACE_NEGATIVE_X = 1;
-o3d.Bitmap.FACE_POSITIVE_Y = 2;
-o3d.Bitmap.FACE_NEGATIVE_Y = 3;
-o3d.Bitmap.FACE_POSITIVE_Z = 4;
-o3d.Bitmap.FACE_NEGATIVE_Z = 5;
-o3d.Bitmap.IMAGE = 6;
-o3d.Bitmap.SLICE = 7;
-
-
-/**
- * The scratch canvas object.
- * @private
- */
-o3d.Bitmap.scratch_canvas_ = null;
-
-
-/**
- * Gets a canvas to use for scratch work.
- * @return {Canvas} The canvas.
- * @private
- */
-o3d.Bitmap.getScratchCanvas_ = function() {
- if (!o3d.Bitmap.scratch_canvas_)
- o3d.Bitmap.scratch_canvas_ = document.createElement('CANVAS');
- return o3d.Bitmap.scratch_canvas_;
-}
-
-
-/**
- * In webgl the bitmap object is represented by an offscreen canvas.
- * @type {Canvas}
- * @private
- */
-o3d.Bitmap.prototype.canvas_ = null;
-
-
-/**
- * Flips a bitmap vertically in place.
- */
-o3d.Bitmap.prototype.flipVertically = function() {
- var temp_canvas = document.createElement('CANVAS');
- temp_canvas.width = this.width;
- temp_canvas.height = this.height;
- var context = temp_canvas.getContext('2d');
- // Flip it.
- context.translate(0, this.height);
- context.scale(1, -1);
- context.drawImage(this.canvas_,
- 0, 0, this.width, this.height);
- this.canvas_ = temp_canvas;
-};
-
-
-/**
- * Flips a bitmap vertically in place lazily.
- * @private
- */
-o3d.Bitmap.prototype.flipVerticallyLazily_ = function() {
- this.defer_flip_vertically_to_texture_ = true;
-};
-
-
-/**
- * Generates mip maps from the source level to lower levels.
- *
- * You can not currently generate mips for DXT textures although you can load
- * them from dds files.
- *
- * @param {number} source_level The level to use as the source of the mips.
- * @param {number} num_levels The number of levels to generate below the
- * source level.
- */
-o3d.Bitmap.prototype.generateMips =
- function(source_level, num_levels) {
- this.defer_mipmaps_to_texture_ = true;
-};
-
-
-/**
- * The width of the bitmap (read only).
- * @type {number}
- */
-o3d.Bitmap.prototype.width = 0;
-
-
-
-/**
- * The height of the bitmap (read only).
- * @type {number}
- */
-o3d.Bitmap.prototype.height = 0;
-
-
-/**
- * Instead of generating mipmaps in the bitmap object, just set this boolean
- * to true, then the texture will generate mipmaps when it loads the bitmap.
- * @type {boolean}
- * @private
- */
-o3d.Bitmap.prototype.defer_mipmaps_to_texture_ = false;
-
-
-/**
- * Instead of flipping vertically in the bitmap object, just set this boolean
- * to true, then the texture will generate mipmaps when it loads the bitmap.
- * @type {boolean}
- * @private
- */
-o3d.Bitmap.prototype.defer_flip_vertically_to_texture_ = false;
-
-
-/**
- * The format of the bitmap (read only).
- * @type {!o3d.Texture.Format}
- */
-o3d.Bitmap.prototype.format = o3d.Texture.UNKNOWN_FORMAT;
-
-
-
-/**
- * Number mip-maps (read only)
- * @type {number}
- */
-o3d.Bitmap.prototype.numMipmaps = 1;
-
-
-
-/**
- * The Semantic of the bitmap.
- * @type {!o3d.Bitmap.Semantic}
- */
-o3d.Bitmap.prototype.semantic = o3d.Bitmap.UNKNOWN_SEMANTIC;
-
-
-
diff --git a/o3d/samples/o3d-webgl/bounding_box.js b/o3d/samples/o3d-webgl/bounding_box.js
deleted file mode 100644
index 8a88d78..0000000
--- a/o3d/samples/o3d-webgl/bounding_box.js
+++ /dev/null
@@ -1,301 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * Creates BoundingBox from minExtent and maxExtent
- * @param {!o3d.math.Point3} opt_minExtent optional minimum extent of the box.
- * @param {!o3d.math.Point3} opt_maxExtent optional maximum extent of the box.
- * @constructor
- */
-o3d.BoundingBox =
- function(opt_minExtent, opt_maxExtent) {
- o3d.ParamObject.call(this);
- var minExtent = opt_minExtent || [0, 0, 0];
- var maxExtent = opt_maxExtent || [0, 0, 0];
-
- this.minExtent = [minExtent[0], minExtent[1], minExtent[2]];
- this.maxExtent = [maxExtent[0], maxExtent[1], maxExtent[2]];
-
- // If there were extents passed in, that validates the box.
- if (opt_minExtent && opt_maxExtent) {
- this.valid = true;
- }
-};
-o3d.inherit('BoundingBox', 'ParamObject');
-
-
-/**
- * Computes a list of 8 3-dimensional vectors for the corners of the box.
- * @return {!Array.<Array<numbers>>} The list of corners.
- */
-o3d.BoundingBox.prototype.corners_ = function() {
- var result = [];
- var m = [this.minExtent, this.maxExtent];
- for (var i = 0; i < 2; ++i) {
- for (var j = 0; j < 2; ++j) {
- for (var k = 0; k < 2; ++k) {
- result.push([m[i][0], m[j][1], m[k][2]]);
- }
- }
- }
-
- return result;
-};
-
-
-/**
- * Computes the smallest bounding box containing all the points in the given
- * list, and either modifies the optional box passed in to match, or returns
- * that box as a new box.
- * @param {!Array.<Array<numbers>>} points A non-empty list of points.
- * @param {o3d.BoundingBox} opt_targetBox Optional box to modify instead of
- * returning a new box.
- * @private
- */
-o3d.BoundingBox.fitBoxToPoints_ = function(points, opt_targetBox) {
- var target = opt_targetBox || new o3d.BoundingBox();
- for (var index = 0; index < 3; ++index) {
- target.maxExtent[index] = target.minExtent[index] = points[0][index];
- for (var i = 1; i < points.length; ++i) {
- var point = points[i];
- target.minExtent[index] = Math.min(target.minExtent[index], point[index]);
- target.maxExtent[index] = Math.max(target.maxExtent[index], point[index]);
- }
- }
- target.valid = true;
- return target;
-};
-
-
-/**
- * True if this boundingbox has been initialized.
- * @type {boolean}
- */
-o3d.BoundingBox.prototype.valid = false;
-
-
-/**
- * The min extent of the box.
- * @type {!o3d.math.Point3}
- */
-o3d.BoundingBox.prototype.minExtent = [0, 0, 0];
-
-
-/**
- * The max extent of the box.
- * @type {!o3d.math.Point3}
- */
-o3d.BoundingBox.prototype.maxExtent = [0, 0, 0];
-
-
-/**
- * Multiplies the bounding box by the given matrix returning a new bounding
- * box.
- * @param {!o3d.math.Matrix4} matrix The matrix to multiply by.
- * @return {!o3d.BoundingBox} The new bounding box.
- */
-o3d.BoundingBox.prototype.mul =
- function(matrix) {
- var corners = this.corners_();
- var new_corners = [];
-
- for (var i = 0; i < corners.length; ++i) {
- new_corners.push(o3d.Transform.transformPoint_(matrix, corners[i]));
- }
-
- return o3d.BoundingBox.fitBoxToPoints_(new_corners);
-};
-
-
-/**
- * Adds a bounding box to this bounding box returning a bounding box that
- * encompases both.
- * @param {!o3d.BoundingBox} box BoundingBox to add to this BoundingBox.
- * @return {!o3d.BoundingBox} The new bounding box.
- */
-o3d.BoundingBox.prototype.add =
- function(box) {
- return new o3d.BoundingBox(
- [Math.min(box.minExtent[0], this.minExtent[0]),
- Math.min(box.minExtent[1], this.minExtent[1]),
- Math.min(box.minExtent[2], this.minExtent[2])],
- [Math.max(box.maxExtent[0], this.maxExtent[0]),
- Math.max(box.maxExtent[1], this.maxExtent[1]),
- Math.max(box.maxExtent[2], this.maxExtent[2])]);
-};
-
-
-/**
- * Checks if a ray defined in same coordinate system as this box intersects
- * this bounding box.
- * @param {!o3d.math.Point3} start position of start of ray in local space.
- * @param {!o3d.math.Point3} end position of end of ray in local space.
- * @return {!o3d.RayIntersectionInfo} RayIntersectionInfo. If result.value
- * is false then something was wrong like using this function with an
- * uninitialized bounding box. If result.intersected is true then the ray
- * intersected the box and result.position is the exact point of
- * intersection.
- */
-o3d.BoundingBox.prototype.intersectRay =
- function(start, end) {
- // If there are six arguments, assume they are the coordinates of two points.
- if (arguments.length == 6) {
- start = [arguments[0], arguments[1], arguments[2]];
- end = [arguments[3], arguments[4], arguments[5]];
- }
-
- var result = new o3d.RayIntersectionInfo;
-
- if (this.valid) {
- result.valid = true;
- result.intersected = true; // True until proven false.
-
- var kNumberOfDimensions = 3;
- var kRight = 0;
- var kLeft = 1;
- var kMiddle = 2;
-
- var direction = [end[0] - start[0], end[1] - start[1], end[2] - start[2]];
- var coord = [0, 0, 0];
- var inside = true;
-
- var quadrant = [];
- var max_t = [];
- var candidate_plane = [];
-
- for (var i = 0; i < kNumberOfDimensions; ++i) {
- quadrant.push(0.0);
- max_t.push(0.0);
- candidate_plane.push(0,0);
- }
-
- var which_plane;
-
- // Find candidate planes; this loop can be avoided if rays cast all from
- // the eye (assumes perpsective view).
- for (var i = 0; i < kNumberOfDimensions; ++i) {
- if (start[i] < this.minExtent[i]) {
- quadrant[i] = kLeft;
- candidate_plane[i] = this.minExtent[i];
- inside = false;
- } else if (start[i] > this.maxExtent[i]) {
- quadrant[i] = kRight;
- candidate_plane[i] = this.maxExtent[i];
- inside = false;
- } else {
- quadrant[i] = kMiddle;
- }
- }
-
- // Ray origin inside bounding box.
- if (inside) {
- result.position = start;
- result.inside = true;
- } else {
- // Calculate T distances to candidate planes.
- for (var i = 0; i < kNumberOfDimensions; ++i) {
- if (quadrant[i] != kMiddle && direction[i] != 0.0) {
- max_t[i] = (candidate_plane[i] - start[i]) / direction[i];
- } else {
- max_t[i] = -1.0;
- }
- }
-
- // Get largest of the max_t's for final choice of intersection.
- which_plane = 0;
- for (var i = 1; i < kNumberOfDimensions; ++i) {
- if (max_t[which_plane] < max_t[i]) {
- which_plane = i;
- }
- }
-
- // Check final candidate actually inside box.
- if (max_t[which_plane] < 0.0) {
- result.intersected = false;
- } else {
- for (var i = 0; i < kNumberOfDimensions; ++i) {
- if (which_plane != i) {
- coord[i] = start[i] + max_t[which_plane] * direction[i];
- if (coord[i] < this.minExtent[i] || coord[i] > this.maxExtent[i]) {
- result.intersected = false;
- break;
- }
- } else {
- coord[i] = candidate_plane[i];
- }
- }
-
- // Ray hits box.
- result.position = coord;
- }
- }
- }
-
- return result;
-};
-
-
-/**
- * Returns true if the bounding box is inside the frustum matrix.
- * It checks all 8 corners of the bounding box against the 6 frustum planes
- * and determines whether there's at least one plane for which all 6 points lie
- * on the outside side of it. In that case it reports that the bounding box
- * is outside the frustum. Note that this is a conservative check in that
- * it in certain cases it will report that a box is in the frustum even if it
- * really isn't. However if it reports that the box is outside then it's
- * guaranteed to be outside.
- * @param {!o3d.math.Matrix4} matrix Matrix to transform the box from its
- * local space to view frustum space.
- * @return {boolean} True if the box is in the frustum.
- */
-o3d.BoundingBox.prototype.inFrustum =
- function(matrix) {
- var corners = this.corners_();
- var bb_test = 0x3f;
- for (var i = 0; i < corners.length; ++i) {
- var corner = corners[i];
- var p = o3d.Transform.transformPoint_(matrix, corner);
- bb_test &= (((p[0] > 1.0) << 0) |
- ((p[0] < -1.0) << 1) |
- ((p[1] > 1.0) << 2) |
- ((p[1] < -1.0) << 3) |
- ((p[2] > 1.0) << 4) |
- ((p[2] < 0.0) << 5));
- if (bb_test == 0) {
- return true;
- }
- }
-
- return (bb_test == 0);
-};
-
-
diff --git a/o3d/samples/o3d-webgl/buffer.js b/o3d/samples/o3d-webgl/buffer.js
deleted file mode 100644
index f8dad1a..0000000
--- a/o3d/samples/o3d-webgl/buffer.js
+++ /dev/null
@@ -1,337 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * The Buffer object is a low level container for a flat list of
- * floating point or integer values. These are currently used to define
- * geometry.
- * @constructor
- */
-o3d.Buffer = function() {
- this.fields = [];
- this.array_ = null;
-};
-o3d.inherit('Buffer', 'NamedObject');
-
-
-/**
- * The fields currently set on the buffer.
- * @type {!Array.<o3d.Field>}
- */
-o3d.Buffer.prototype.fields = [];
-
-
-/**
- * Total number of components.
- * @type {number}
- */
-o3d.Buffer.prototype.totalComponents = 0;
-
-/**
- * Index of the corresponding gl buffer object.
- * @type {number}
- */
-o3d.Buffer.prototype.gl_buffer_ = 0;
-
-/**
- * Function to create an array for the buffer.
- * @param {number} numElements
- * @return {!Float32Array}
- */
-o3d.Buffer.prototype.createArray = function(numElements) {
- return new Float32Array(numElements);
-};
-
-o3d.Buffer.prototype.__defineGetter__('numElements',
- function() {
- return (!this.array_) ? 0 : this.array_.length / this.totalComponents;
- }
-);
-
-/**
- * Computes and stores the correct total components from the
- * fields so far.
- */
-o3d.Buffer.prototype.updateTotalComponents_ = function() {
- var total = 0;
- for (var i = 0; i < this.fields.length; ++i) {
- this.fields[i].offset_ = total;
- total += this.fields[i].numComponents;
- }
- this.totalComponents = total;
-};
-
-/**
- * Allocates memory for the data to be stored in the buffer based on
- * the types of fields set on the buffer.
- *
- * @param {number} numElements Number of elements to allocate..
- * @return {boolean} True if operation was successful.
- */
-o3d.Buffer.prototype.allocateElements =
- function(numElements) {
- this.updateTotalComponents_();
- this.resize(numElements * this.totalComponents);
-};
-
-/**
- * Reallocate the array element to have the given number of elements.
- * @param {number} numElements The new number of elements.
- */
-o3d.Buffer.prototype.resize = function(numElements) {
- this.gl_buffer_ = this.gl.createBuffer();
- // Callers (in particular the deserializer) occasionally call this
- // with floating-point numbers.
- this.array_ = this.createArray(Math.floor(numElements));
-};
-
-/**
- * Defines a field on this buffer.
- *
- * Note: Creating a field after having allocated the buffer is an expensive
- * operation as the data currently in the buffer has to be shuffled around
- * to make room for the new field.
- *
- * @param {string} field_type type of data in the field. Valid types
- * are "FloatField", "UInt32Field", and "UByteNField".
- * @param {number} num_components number of components in the field.
- * @return {!o3d.Field} The created field.
- */
-o3d.Buffer.prototype.createField =
- function(fieldType, numComponents) {
- // Check if array has already been allocated. If so, we need to reshuffle
- // the data currently stored.
- var alreadyAllocated = this.array_ && this.array_.length > 0;
- var savedData = [];
- var numElements = this.numElements;
-
- // Make copies of the existing field data.
- if (alreadyAllocated) {
- for (var i = 0; i < this.fields.length; i++) {
- savedData[i] = this.fields[i].getAt(0, numElements);
- }
- }
-
- // Create the new field.
- var f = new o3d.Field();
- f.buffer = this;
- f.numComponents = numComponents;
- f.size = numComponents * (fieldType=='UByteNField' ? 1 : 4);
- this.fields.push(f);
- this.updateTotalComponents_();
-
- // Resize the buffer with the new field, and replace data.
- if (alreadyAllocated) {
- this.allocateElements(numElements);
- for (var i = 0; i < this.fields.length; i++) {
- var fieldData = savedData[i];
- if (fieldData) {
- this.fields[i].setAt(0, fieldData);
- }
- }
- }
-
- return f;
-};
-
-
-/**
- * Removes a field from this buffer.
- *
- * Note: Removing a field after having allocated the buffer is an expensive
- * operation as the data currently in the buffer has to be shuffled around
- * to remove the old field.
- *
- * @param {!o3d.Field} field field to remove.
- */
-o3d.Buffer.prototype.removeField =
- function(field) {
- o3d.removeFromArray(this.fields, field);
- // TODO(petersont): Have this function actually shuffle the buffer around to
- // remove the field properly.
- this.updateTotalComponents_();
-};
-
-
-/**
- * Helper function for buffer's and field's getAt functions. Gets elements in
- * the buffer as an array.
- * @param {number} start_index Index of the first element value to get.
- * @param {number} num_elements the number of elements to get.
- * @return {!Array.<number>} An array of values.
- */
-o3d.Buffer.prototype.getAtHelper_ =
- function(start_index, num_elements, offset, num_components) {
- var values = [];
- for (var i = 0; i < num_elements; ++i) {
- for (var c = 0; c < num_components; ++c) {
- values.push(this.array_[(start_index + i) *
- this.totalComponents + offset + c]);
- }
- }
- return values;
-};
-
-
-/**
- * Prepares the buffer for read/write.
- */
-o3d.Buffer.prototype.lock = function() {
- // For now, this doesn't need to do anything.
-};
-
-
-/**
- * Delivers the buffer to the graphics hardware when read/write is finished.
- */
-o3d.Buffer.prototype.unlock = function() {
- this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.gl_buffer_);
- this.gl.bufferData(this.gl.ARRAY_BUFFER, this.array_, this.gl.STATIC_DRAW);
-};
-
-
-/**
- * Sets the values in the buffer given array.
- *
- * @param {!Array.<number>} values contains data to assign to the Buffer
- * data itself.
- * @return {boolean} True if operation was successful.
- */
-o3d.Buffer.prototype.set =
- function(values) {
- if (!values.length) {
- o3d.notImplemented();
- }
- if (this.array_ == null || this.array_.length != values.length) {
- this.resize(values.length);
- }
- this.lock();
- for (var i = 0; i < values.length; ++i) {
- this.array_[i] = values[i];
- }
- this.unlock();
-};
-
-
-/**
- * VertexBufferBase is a the base class for both VertexBuffer and SourceBuffer
- * @constructor
- */
-o3d.VertexBufferBase = function() {
- o3d.Buffer.call(this);
-};
-o3d.inherit('VertexBufferBase', 'Buffer');
-
-
-/**
- * Gets a copy of the values of the data stored in the buffer.
- * Modifying this copy has no effect on the buffer.
- */
-o3d.VertexBufferBase.prototype.get = function() {
- return this.getAtHelper_(0, this.numElements,
- 0, this.totalComponents);
-};
-
-
-/**
- * Gets a copy of a sub range of the values in the data stored in the buffer.
- * Modifying this copy has no effect on the buffer.
- *
- * @param {number} start_index index of the element value to get.
- * @param {number} num_elements the number of elements to get.
- * @return {!Array.<number>} An array of values.
- */
-o3d.VertexBufferBase.prototype.getAt =
- function(start_index, num_elements) {
- return this.getAtHelper_(start_index, num_elements, 0, this.totalComponents);
-};
-
-
-/**
- * VertexBuffer is a Buffer object used for storing vertex data for geometry.
- * (e.g. vertex positions, normals, colors, etc).
- * A VertexBuffer can be rendered directly by the GPU.
- * @constructor
- */
-o3d.VertexBuffer = function() {
- o3d.Buffer.call(this);
-};
-o3d.inherit('VertexBuffer', 'Buffer');
-
-/**
- * The name of the class as a string.
- * @type {string}
- */
-o3d.VertexBuffer.prototype.className = "o3d.VertexBuffer";
-
-
-/**
- * SourceBuffer is a Buffer object used for storing vertex data for
- * geometry. (e.g. vertex positions, normals, colors, etc).
- *
- * A SourceBuffer is the source for operations like skinning and morph
- * targets. It can not be directly rendered by the GPU.
- * @constructor
- */
-o3d.SourceBuffer = function() {
- o3d.Buffer.call(this);
-};
-o3d.inherit('SourceBuffer', 'Buffer');
-
-
-/**
- * IndexBuffer is a buffer object used for storing geometry index data (e.g.
- * triangle indices).
- * @constructor
- */
-o3d.IndexBuffer = function() {
- o3d.Buffer.call(this);
-};
-o3d.inherit('IndexBuffer', 'Buffer');
-
-
-/**
- * Type of the array element.
- * @type {!Uint16Array}
- */
-o3d.IndexBuffer.prototype.createArray = function(numElements) {
- return new Uint16Array(numElements);
-};
-
-/**
- * Delivers the buffer to the graphics hardware when read/write is finished.
- */
-o3d.IndexBuffer.prototype.unlock = function() {
- this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, this.gl_buffer_);
- this.gl.bufferData(
- this.gl.ELEMENT_ARRAY_BUFFER, this.array_, this.gl.STATIC_DRAW);
-};
diff --git a/o3d/samples/o3d-webgl/clear_buffer.js b/o3d/samples/o3d-webgl/clear_buffer.js
deleted file mode 100644
index f4f82aa..0000000
--- a/o3d/samples/o3d-webgl/clear_buffer.js
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A ClearBuffer is a render node that clears the color buffer, zbuffer and/or
- * stencil buffer of the current render target.
- *
- * @constructor
- */
-o3d.ClearBuffer = function() {
- o3d.RenderNode.call(this);
- /**
- * The color to clear the buffer in RGBA Float4 format.
- * @type {!o3d.Float4}
- */
- this.clearColor = [0, 0, 0, 1];
-
- /**
- * true clears the current render target's color buffer to the clear color.
- * false does not clear the color buffer.
- * @type {boolean}
- */
- this.clearColorFlag = true;
-
- /**
- * The value to clear the depth buffer (0.0 - 1.0)
- * @type {number}
- */
- this.clearDepth = 1;
-
- /**
- * true clears the current render target's depth buffer to the clear depth
- * value. false does not clear the depth buffer.
- * @type {boolean}
- */
- this.clearDepthFlag = true;
-
- /**
- * The value to clear the stencil buffer to (0 - 255).
- * @type {number}
- */
- this.clearStencil = 0;
-
- /**
- * true clears the current render target's stencil buffer to the clear stencil
- * value. false does not clear the stencil buffer
- * @type {boolean}
- */
- this.clearStencilFlag = true;
-};
-o3d.inherit('ClearBuffer', 'RenderNode');
-
-o3d.ParamObject.setUpO3DParam_(o3d.ClearBuffer, 'clearColor', 'ParamFloat4');
-o3d.ParamObject.setUpO3DParam_(o3d.ClearBuffer,
- 'clearColorFlag', 'ParamBoolean');
-o3d.ParamObject.setUpO3DParam_(o3d.ClearBuffer, 'clearDepth', 'ParamFloat');
-o3d.ParamObject.setUpO3DParam_(o3d.ClearBuffer,
- 'clearDepthFlag', 'ParamBoolean');
-o3d.ParamObject.setUpO3DParam_(o3d.ClearBuffer,
- 'clearStencil', 'ParamInteger');
-o3d.ParamObject.setUpO3DParam_(o3d.ClearBuffer,
- 'clearStencilFlag', 'ParamBoolean');
-
-/**
- * Function called in the render graph traversal before the children are
- * rendered.
- */
-o3d.ClearBuffer.prototype.before = function() {
- var flags = 0;
-
- this.gl.clearColor(
- this.clearColor[0],
- this.clearColor[1],
- this.clearColor[2],
- this.clearColor[3]);
-
- this.gl.clearDepth(this.clearDepth);
- this.gl.clearStencil(this.clearStencil);
-
- if (this.clearColorFlag)
- flags = flags | this.gl.COLOR_BUFFER_BIT;
- if (this.clearDepthFlag)
- flags = flags | this.gl.DEPTH_BUFFER_BIT;
- if (this.clearStencilFlag)
- flags = flags | this.gl.STENCIL_BUFFER_BIT;
-
- this.gl.clear(flags);
-};
-
-
-
diff --git a/o3d/samples/o3d-webgl/client.js b/o3d/samples/o3d-webgl/client.js
deleted file mode 100644
index 5e940a6..0000000
--- a/o3d/samples/o3d-webgl/client.js
+++ /dev/null
@@ -1,1354 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * A namespace to hold the list of all clients.
- * @namespace
- */
-o3d.Renderer = {};
-
-
-/**
- * @type {number}
- */
-o3d.Renderer.InitStatus = goog.typedef;
-
-/**
- * The initialization status of the renderer.
- *
- * InitStatus,
- * UNINITIALIZED,
- * SUCCESS, The renderer is initialized.
- * GPU_NOT_UP_TO_SPEC, The renderer determined the user's machine cannot
- * run O3D.
- * OUT_OF_RESOURCES, The user's machine does not have enough graphic
- * resources available to start another instance of the O3D renderer.
- * INITIALIZATION_ERROR, Some unknown error such as e.g. drivers not
- * being installed correctly.
- */
-o3d.Renderer.UNINITIALIZED = 0;
-o3d.Renderer.SUCCESS = 1;
-o3d.Renderer.GPU_NOT_UP_TO_SPEC = 2;
-o3d.Renderer.OUT_OF_RESOURCES = 3;
-o3d.Renderer.INITIALIZATION_ERROR = 4;
-
-
-/**
- * @type {number}
- */
-o3d.Renderer.DisplayMode = goog.typedef;
-
-/**
- * This is used in SetFullscreenClickRegion to request the current display
- * mode, such that the change to full-screen mode won't change the screen
- * resolution or refresh rate.
- *
- * DisplayModes,
- * DISPLAY_MODE_DEFAULT
- */
-o3d.Renderer.DISPLAY_MODE_DEFAULT = 0;
-
-
-/**
- * The interval timer for the render callback.
- * @type {Object}
- */
-o3d.Renderer.render_callback_interval_ = null;
-
-
-/**
- * Global private list of all clients to be rendered every frame.
- * @type {!Array.<!o3d.Client>}
- */
-o3d.Renderer.clients_ = [];
-
-
-/**
- * Renders all clients associated with this renderer.
- */
-o3d.Renderer.renderClients = function() {
- for (var i = 0; i < o3d.Renderer.clients_.length; ++i) {
- var client = o3d.Renderer.clients_[i];
- client.counter_manager_.tick();
- if (client.renderMode == o3d.Client.RENDERMODE_CONTINUOUS) {
- client.render();
- }
- }
-};
-
-
-/**
- * Sets a timer to traverse the rendergraph every sixtieth of a second.
- */
-o3d.Renderer.installRenderInterval = function() {
- o3d.Renderer.render_callback_interval_ = setInterval(
- "o3d.Renderer.renderClients()", 1000.0 / 60.0);
-};
-
-
-/**
- * The ClientInfo is used to get information about the client.
- * @constructor
- */
-o3d.ClientInfo = function() {
- o3d.NamedObject.call(this);
-};
-o3d.inherit('ClientInfo', 'NamedObject');
-
-
-/**
- * The number of objects the client is currently tracking.
- * You can use this to check that you are correctly freeing resources.
- * @type {number}
- */
-o3d.ClientInfo.prototype.num_objects = 0;
-
-
-
-/**
- * The amount of texture memory used.
- * @type {number}
- */
-o3d.ClientInfo.prototype.texture_memory_used = 0;
-
-
-
-/**
- * The amount of texture memory used.
- * @type {number}
- */
-o3d.ClientInfo.prototype.buffer_memory_used = 0;
-
-
-
-/**
- * Whether or not O3D is using the software renderer.
- *
- * For testing purposes you can force O3D to use the software renderer
- * by setting the environment variable O3D_FORCE_SOFTWARE_RENDERER to
- * anything.
- *
- *
- * set O3D_FORCE_SOFTWARE_RENDERER=foo
- *
- * or
- *
- * export O3D_FORCE_SOFTWARE_RENDERER=foo
- *
- *
- * You can set it at a system level if you want to set it for all
- * browser instances or set it from a command line and start your
- * browser from that same command line if you want to effect just
- * that instance of the browser.
- *
- * Note that many browers require special command line options to
- * run in a separate process, otherwise they default to finding
- * the browser process already running and using that. For example
- * firefox requires the option -no-remote.
- *
- * @type {boolean}
- */
-o3d.ClientInfo.prototype.software_renderer = false;
-
-
-
-/**
- * Whether or not the GPU supports non power of two textures.
- * NOTE: O3D always allows non power of two textures.
- *
- * The only reason to look at this flag is for things like video that are
- * updating the texture every frame. In that case, you might want to know
- * that you could run faster if you used a power of 2 texture instead of
- * a non power of 2 texture.
- *
- * @type {boolean}
- */
-o3d.ClientInfo.prototype.non_power_of_two_textures = true;
-
-
-
-/**
- * True if shaders need to be GLSL instead of Cg/HLSL.
- * In this implementation of o3d, that is true by default.
- **/
-o3d.ClientInfo.prototype.glsl = true;
-
-
-
-/**
- * The Client class is the main point of entry to O3D. It defines methods
- * for creating and deleting packs. Each new object created by the Client is
- * assigned a unique ID.
- *
- * The Client has a root transform for the transform graph and a root render
- * node for the render graph.
- * @constructor
- */
-o3d.Client = function() {
- o3d.NamedObject.call(this);
-
- var tempPack = this.createPack();
- this.root = tempPack.createObject('Transform');
- this.renderGraphRoot = tempPack.createObject('RenderNode');
- this.clientId = o3d.Client.nextId++;
- this.packs_ = [tempPack];
- this.clientInfo = tempPack.createObject('ClientInfo');
- this.counter_manager_ = new o3d.CounterManager;
-
- if (o3d.Renderer.clients_.length == 0)
- o3d.Renderer.installRenderInterval();
-
- o3d.Renderer.clients_.push(this);
-
- /**
- * Stack of objects showing how the state has changed.
- * @type {!Array.<!Object>}
- * @private
- */
- this.stateMapStack_ = [];
-
- /**
- * An object containing an entry for each state variable that has changed.
- * @type {Object}
- * @private
- */
- this.stateVariableStacks_ = {};
-};
-o3d.inherit('Client', 'NamedObject');
-
-/**
- * @type {function(!o3d.RenderEvent): void}
- */
-o3d.Client.RenderCallback = goog.typedef;
-
-/**
- * @type {function(!o3d.TickEvent): void}
- */
-o3d.Client.TickCallback = goog.typedef;
-
-/**
- * @type {function(string): void}
- */
-o3d.Client.ErrorCallback = goog.typedef;
-
-/**
- * The root of the render graph.
- * @type {o3d.RenderNode}
- */
-o3d.Client.prototype.renderGraphRoot = null;
-
-
-/**
- * Global counter to give the client a unique ID number.
- * @type {number}
- */
-o3d.Client.nextId = 0;
-
-
-/**
- * The time of the last render in seconds.
- * @type {number}
- */
-o3d.Client.prototype.then_ = 0;
-
-
-/**
- * The transform graph root.
- * @type {o3d.Transform}
- */
-o3d.Client.prototype.root = null;
-
-
-/**
- * A list of all packs for this client.
- * @type {!Array.<!o3d.Pack>}
- */
-o3d.Client.prototype.packs_ = [];
-
-/**
- * Keeps track of all counters associated with this client.
- * @type {o3d.CounterManager}
- */
-o3d.Client.prototype.counter_manager_ = null;
-
-/**
- * Whether or not the client sets the alpha channel of all pixels to 1 in the
- * final stage of rendering.
- *
- * By default, this is set to true to mimic the plugin's behavior. If
- * a transparent canvas background is desirable, this should be set to false.
- *
- * @type {boolean}
- */
-o3d.Client.prototype.normalizeClearColorAlpha = true;
-
-/**
- * Function that gets called when the client encounters an error.
- */
-o3d.Client.prototype.error_callback = function(error_message) {
- alert(error_message);
-};
-
-
-/**
- * Function that gets called right before the client renders.
- */
-o3d.Client.prototype.render_callback = function(render_event) {};
-
-
-/**
- * Function that gets called every tick.
- */
-o3d.Client.prototype.tick_callback = function(tick_event) {};
-
-
-/**
- * Call this function from window.onunload to ensure the browser does not
- * continue to call callbacks (like the render callback) after the page is
- * unloaded. It is possible that during unload the browser unloads all the
- * javascript code, but then, after that, still asks the plugin to render. The
- * browser then calls javascript functions that no longer exist which causes an
- * error. To prevent that situation you need to clear all your callbacks on
- * unload. cleanup handles that for you so you don't have to dispose each and
- * every callback by hand.
- */
-o3d.Client.prototype.cleanup = function () {
- this.clearRenderCallback();
- this.clearTickCallback();
- this.clearErrorCallback();
-};
-
-
-/**
- * Creates a pack object.
- * A pack object.
- * @return {!o3d.Pack} A new pack object.
- */
-o3d.Client.prototype.createPack =
- function() {
- var pack = new o3d.Pack;
- pack.client = this;
- pack.gl = this.gl;
- this.packs_.push(pack);
- return pack;
-};
-
-
-/**
- * Creates a pack object.
- * A pack object.
- * @param {!o3d.Pack} pack The pack to remove.
- */
-o3d.Client.prototype.destroyPack =
- function(pack) {
- o3d.removeFromArray(this.packs_, pack);
-};
-
-
-
-/**
- * Searches the Client for an object matching the given id.
- *
- * @param {number} id The id of the object to look for.
- * @return {o3d.ObjectBase} The object or null if a object
- * with the given id is not found.
- */
-o3d.Client.prototype.getObjectById =
- function(id) {
- o3d.notImplemented();
-};
-
-
-/**
- * Searches the Client for objects of a particular name and type.
- * @param {string} name name of object to look for.
- * @param {string} class_name name of class to look for.
- * @return {!Array.<!o3d.ObjectBase>} Array of objects found.
- */
-o3d.Client.prototype.getObjects =
- function(name, class_name) {
- var objects = [];
-
- for (var i = 0; i < this.packs_.length; ++i) {
- var pack = this.packs_[i];
- objects = objects.concat(pack.getObjects(name, class_name));
- }
-
- return objects;
-};
-
-
-/**
- * Searches the Client for objects of a particular type.
- * @param {string} class_name name of class to look for.
- * @return {!Array.<!Object>} Array of objects found.
- */
-o3d.Client.prototype.getObjectsByClassName =
- function(class_name) {
- var objects = [];
-
- for (var i = 0; i < this.packs_.length; ++i) {
- var pack = this.packs_[i];
- objects = objects.concat(pack.getObjectsByClassName(class_name));
- }
-
- return objects;
-};
-
-
-/**
- * @type {number}
- */
-o3d.Client.RenderMode = goog.typedef;
-
-/**
- * RENDERMODE_CONTINUOUS, Draw as often as possible up to refresh rate.
- * RENDERMODE_ON_DEMAND, Draw once then only when the OS requests it
- * (like uncovering part of a window.)
- */
-o3d.Client.RENDERMODE_CONTINUOUS = 0;
-o3d.Client.RENDERMODE_ON_DEMAND = 1;
-
-
-/**
- * The current render mode. The default mode is RENDERMODE_CONTINUOUS.\n
- * Valid values are:
- * RENDERMODE_CONTINUOUS, Draw as often as possible up to refresh rate.
- * RENDERMODE_ON_DEMAND, Draw when the OS requests it (like uncovering
- * part of a window.)
- * @type {o3d.Client.RenderMode}
- */
-o3d.Client.prototype.renderMode = o3d.Client.RENDERMODE_CONTINUOUS;
-
-
-/**
- * Forces a render of the current scene if the current render mode is
- * RENDERMODE_ON_DEMAND.
- */
-o3d.Client.prototype.render = function() {
- if (!this.gl) {
- return;
- }
- // Synthesize a render event.
- var render_event = new o3d.RenderEvent;
- this.counter_manager_.advanceRenderFrameCounters();
-
- this.clearStateStack_();
-
- var now = (new Date()).getTime() * 0.001;
- if(this.then_ == 0.0)
- render_event.elapsedTime = 0.0;
- else
- render_event.elapsedTime = now - this.then_;
-
- if (this.render_callback) {
- for (var stat in this.render_stats_) {
- render_event[stat] = this.render_stats_[stat];
- }
- this.render_callback(render_event);
- }
- this.then_ = now;
-
- this.gl.colorMask(true, true, true, true);
-
- this.renderTree(this.renderGraphRoot);
-
- // When o3d finally draws to the webpage, the alpha channel should be all 1's
- // So we clear with a color mask to set all alpha bytes to 1 before drawing.
- // Before we draw again, the color mask gets set back to all true (above).
- if (this.normalizeClearColorAlpha) {
- this.gl.colorMask(false, false, false, true);
- this.gl.clearColor(0.0, 0.0, 0.0, 1.0);
- this.gl.clear(this.gl.COLOR_BUFFER_BIT);
- }
-};
-
-
-/**
- * An object for various statistics that are gather during the render tree
- * tranversal.
- *
- * @type {Object}
- */
-o3d.Client.prototype.render_stats = {}
-
-
-/**
- * Renders a render graph.
- *
- * Normally the client calls this function automatically for you effectively
- * doing a client.renderTree(client.renderGraphRoot) but there are cases
- * where it is beneficial to be able to call this yourself and pass it
- * different roots when you need to manipulate something between calls.
- *
- * This function can only be called from inside a render callback. If you call
- * it the client will not do its default call as mentioned above.
- *
- * @param {!o3d.RenderNode} render_node root RenderNode to start rendering from.
- */
-o3d.Client.prototype.renderTree =
- function(render_node) {
- this.render_stats_ = {
- drawElementsCulled: 0,
- drawElementsProcessed: 0,
- drawElementsRendered: 0,
- primitivesRendered: 0,
- transformsCulled: 0,
- transformsProcessed: 0
- };
-
- render_node.render();
-};
-
-
-/**
- * Returns an array of DisplayModes which are available for use in full-screen
- * mode.
- * An array of DisplayModes.
- * @type {!Array.<!o3d.Client.DispalyMode>}
- */
-o3d.Client.prototype.getDisplayModes = [];
-
-
-/**
- * Makes a region of the plugin area that will invoke full-screen mode if
- * clicked. The developer is responsible for communicating this to the user,
- * as this region has no visible marker. The developer is also responsible for
- * updating this region if the plugin gets resized, as we don't know whether or
- * how to scale it. There can be only one full-screen click region at a time;
- * calling this again will override any previous call.
- *
- * @param {number} x x position in pixels.
- * @param {number} y y position in pixels.
- * @param {number} width width in pixels.
- * @param {number} height height in pixels.
- * @param {number} mode_id Id of mode to use.
- */
-o3d.Client.prototype.setFullscreenClickRegion =
- function(x, y, width, height, mode_id) {
- o3d.notImplemented();
-};
-
-
-/**
- * Deactivates the plugin click region that was previously created with
- * SetFullscreenClickRegion().
- */
-o3d.Client.prototype.clearFullscreenClickRegion = function() {
- o3d.notImplemented();
-};
-
-
-
-/**
- * Cancels full-screen display, reverting to displaying content only in the
- * plugin region. If the plugin is already not in full-screen mode, this has
- * no effect. This does not deactivate the plugin click region--if the user
- * clicks there again, we'll go back to full-screen display.
- */
-o3d.Client.prototype.cancelFullscreenDisplay = function() {
- render_node.render();
-};
-
-
-
-/**
- * Gets info about the client.
- * @type {!o3d.ClientInfo}
- */
-o3d.Client.prototype.client_info = null;
-
-
-
-/**
- * Whether content is displayed in full-screen mode or in a plugin window. The
- * default is false [not full-screen].
- * @type {boolean}
- */
-o3d.Client.prototype.fullscreen = false;
-
-
-/**
- * Returns the width of the current drawing area [plugin or full-screen] in
- * pixels.
- */
-o3d.Client.prototype.__defineGetter__('width',
- function() {
- return this.gl.hack_canvas.width;
- }
-);
-
-o3d.Client.prototype.__defineSetter__('width',
- function(x) {
- this.gl.hack_canvas.width = x;
- }
-);
-
-
-/**
- * Returns the height of the current drawing area [plugin or full-screen] in
- * pixels.
- */
-o3d.Client.prototype.__defineGetter__('height',
- function() {
- return this.gl.hack_canvas.height;
- }
-);
-
-o3d.Client.prototype.__defineSetter__('height',
- function(x) {
- this.gl.hack_canvas.height = x;
- }
-);
-
-
-/**
- * Initializes this client using the canvas.
- * @param {Canvas}
- * @return {boolean} Success.
- */
-o3d.Client.prototype.initWithCanvas = function(canvas) {
- var gl;
-
- var standard_attributes = {
- alpha : true,
- depth : true,
- stencil : true,
- antialias : true,
- premultipliedAlpha : true
- };
-
- if (!canvas || !canvas.getContext) {
- return false;
- }
-
- var names = ["webgl", "experimental-webgl", "moz-webgl"];
- for (var ii = 0; ii < names.length; ++ii) {
- try {
- gl = canvas.getContext(names[ii], standard_attributes)
- } catch(e) { }
- if (gl) {
- break;
- }
- }
-
- if (!gl) {
- return false;
- }
-
- // TODO(petersont): Remove this workaround once WebGLRenderingContext.canvas
- // is implemented in Firefox.
- gl.hack_canvas = canvas;
- this.gl = gl;
- this.root.gl = gl;
- this.renderGraphRoot.gl = gl;
-
- gl.client = this;
- gl.displayInfo = {width: canvas.width,
- height: canvas.height};
- o3d.State.createDefaultState_(gl).push_();
-
- this.initErrorTextures_();
-
- return true;
-}
-
-
-/**
- * Creates the yellow-and-red 8x8 error textures.
- * @private
- */
-o3d.Client.prototype.initErrorTextures_ = function() {
- // First create the yellow-and-red pattern.
- var r = [1, 0, 0, 1];
- var Y = [1, 1, 0, 1];
- var error = [r, r, r, r, r, r, r, r,
- r, r, Y, Y, Y, Y, r, r,
- r, Y, r, r, r, Y, Y, r,
- r, Y, r, r, Y, r, Y, r,
- r, Y, r, Y, r, r, Y, r,
- r, Y, Y, r, r, r, Y, r,
- r, r, Y, Y, Y, Y, r, r,
- r, r, r, r, r, r, r, r];
- var pixels = [];
- for (var i = 0; i < error.length; i++) {
- for (var j = 0; j < 4; j++) {
- pixels[i * 4 + j] = error[i][j];
- }
- }
-
- // Create the default error cube map using the same data.
- var defaultTextureCube = new o3d.TextureCUBE();
-
- defaultTextureCube.gl = this.gl;
- defaultTextureCube.init_(8, o3d.Texture.ARGB8, 1, false, true);
-
- for (var i = 0; i < 6; ++i) {
- defaultTextureCube.set(i, 0, pixels);
- }
- defaultTextureCube.name = 'DefaultTextureCube';
- this.error_texture_cube_ = defaultTextureCube;
- this.fallback_error_texture_cube_ = defaultTextureCube;
-
- // Create the default error texture.
- var defaultTexture = new o3d.Texture2D();
- defaultTexture.gl = this.gl;
- defaultTexture.init_(8, 8, o3d.Texture.ARGB8, 1, false);
-
- defaultTexture.set(0, pixels);
- defaultTexture.name = 'DefaultTexture';
- this.error_texture_ = defaultTexture;
- this.fallback_error_texture_ = defaultTexture;
-};
-
-
-/**
- * Sets the per frame render callback.
- *
- * Note: The callback will not be called recursively. When your callback is
- * called if you somehow manage to cause the client to render more frames
- * before you've returned from the callback you will not be called for those
- * frames.
- *
- * g_client.setRenderCallback(onrender);
- *
- * function onrender(render_event) {
- * var elapsedTime = render_event.elapsedTime;
- * }
- *
- * @param {!o3d.RenderCallback} render_callback The callback to call
- * each frame.
- */
-o3d.Client.prototype.setRenderCallback =
- function(render_callback) {
- if (this.render_callback) {
- this.clearRenderCallback();
- }
- this.render_callback = render_callback;
-};
-
-
-/**
- * Clears the per frame render callback.
- */
-o3d.Client.prototype.clearRenderCallback = function() {
- clearInterval(this.render_callback_interval_);
- this.render_callback = null;
-};
-
-
-/**
- * Sets a render callback to be called at the end of the
- * rendering cycle of each frame.
- *
- * Note: The callback will not be called recursively. When your callback is
- * called if you somehow manage to cause the client to render more frames
- * before you've returned from the callback you will not be called for those
- * frames.
- *
- *
- * g_client.setPostRenderCallback(onpostrender);
- *
- * function onpostrender(render_event) {
- * var elapsedTime = render_event.elapsedTime;
- * }
- *
- * @param {!o3d.RenderCallback} post_render_callback The callback to call
- * each frame.
- */
-o3d.Client.prototype.setPostRenderCallback =
- function(post_render_callback) {
- this.postRenderCallback = post_render_callback;
-};
-
-
-/**
- * Clears the post render callback.
- */
-o3d.Client.prototype.clearPostRenderCallback = function() {
- this.postRenderCallback = null;
-};
-
-
-
-/**
- * Sets the lost resources callback.
- *
- * The contents of certain resources, RenderSurfaces, can get discarded by the
- * system under certain circumstances. If you application needs that contents
- * to be in a certain state then you can set a callback giving your program the
- * opportunity to restore that state if and when it is lost.
- *
- * @param {!o3d.LostResourcesCallback} lost_resources_callback The callback when
- * resources are lost.
- */
-o3d.Client.prototype.setLostResourcesCallback =
- function(lost_resources_callback) {
- this.lostResourcesCallback = lost_resources_callback;
-};
-
-
-/**
- * Clears the lost resources callback.
- */
-o3d.Client.prototype.clearLostResourcesCallback =
- function() {
- this.lostResourcesCallback = null;
-};
-
-
-/**
- * Returns the event object for processing.
- * @param {Event} event A mouse-related DOM event.
- * @private
- */
-o3d.Client.getEvent_ = function(event) {
- return event ? event : window.event;
-};
-
-
-/**
- * Returns an object with event, element, name and wheel in a semi cross
- * browser way. Note: this can only be called from since an event because
- * depending on the browser it expects that window.event is valid.
- * @param {!Event} event A mouse-related DOM event.
- * @return {!EventInfo} Info about the event.
- * @private
- */
-o3d.Client.getEventInfo_ = function(event) {
- var elem = event.target ? event.target : event.srcElement;
- var name = elem.id ? elem.id : ('->' + elem.toString());
- var wheel = event.detail ? event.detail : -event.wheelDelta;
- return { event: event,
- element: elem,
- name: name,
- wheel: wheel };
-};
-
-
-/**
- * Returns the absolute position of an element.
- * @param {!HTMLElement} element The element to get a position for.
- * @return {!Object} An object containing x and y as the absolute position
- * of the given element.
- * @private
- */
-o3d.Client.getAbsolutePosition_ = function(element) {
- var r = {x: 0, y: 0};
- for (var e = element; e; e = e.offsetParent) {
- r.x += e.offsetLeft;
- r.y += e.offsetTop;
- }
- return r;
-};
-
-/**
- * Compute the x and y of an event with respect to the element which received
- * the event.
- *
- * @param {!Object} eventInfo As returned from
- * o3d.Client.getEventInfo.
- * @return {!Object} An object containing keys 'x' and 'y'.
- * @private
- */
-o3d.Client.getLocalXY_ = function(eventInfo) {
- var event = eventInfo.event;
- var p = o3d.Client.getAbsolutePosition_(eventInfo.element);
- return {x: event.pageX - p.x, y: event.pageY - p.y};
-};
-
-
-/**
- * Wraps a user's event callback with one that properly computes
- * relative coordinates for the event.
- * @param {!o3d.EventCallback} handler Function to call on event.
- * @param {boolean} doCancelEvent If event should be canceled after callback.
- * @return {!o3d.EventCallback} Wrapped handler function.
- * @private
- */
-o3d.Client.wrapEventCallback_ = function(handler, doCancelEvent) {
- return function(event) {
- event = o3d.Client.getEvent_(event);
- var originalEvent = event;
- var info = o3d.Client.getEventInfo_(event);
- var relativeCoords = o3d.Client.getLocalXY_(info);
- // In a proper event, there are read only properties, so we clone it.
- event = o3d.clone(event);
- event.x = relativeCoords.x;
- event.y = relativeCoords.y;
- // Invert value to meet contract for deltaY. @see event.js.
- event.deltaY = -info.wheel;
- handler(event);
- if (doCancelEvent) {
- // Need to cancel the original, un-cloned event.
- o3djs.event.cancel(originalEvent);
- }
- };
-};
-
-
-/**
- * Sets a callback for a given event type.
- * types.
- * There can be only one callback for a given event type at a time; setting a
- * new one deletes the old one.
- *
- * @param {string} type Type of event to set callback for.
- * @param {!o3d.EventCallback} handler Function to call on event.
- */
-o3d.Client.prototype.setEventCallback =
- function(type, handler) {
- var listener = this.gl.hack_canvas;
- // TODO(petersont): Figure out a way for a canvas to listen to a key event
- // directly.
-
- var isWheelEvent = type == 'wheel';
- var forKeyEvent = type.substr(0, 3) == 'key';
- if (forKeyEvent) {
- listener = document;
- } else {
- handler = o3d.Client.wrapEventCallback_(handler, isWheelEvent);
- }
- if (isWheelEvent) {
- listener.addEventListener('DOMMouseScroll', handler, true);
- listener.addEventListener('mousewheel', handler, true);
- } else {
- listener.addEventListener(type, handler, true);
- }
-};
-
-
-/**
- * Removes the previously-registered callback for an event of the given type.
- * @param {string} type Type of event to clear callback for.
- */
-o3d.Client.prototype.clearEventCallback =
- function(type) {
- //TODO(petersont): Same as TODO in setEventCallback above.
- var listener = this.gl.hack_canvas;
-
- var isWheelEvent = type == 'wheel';
- var forKeyEvent = type.substr(0, 3) == 'key';
- if (forKeyEvent) {
- listener = document;
- }
-
- if (isWheelEvent) {
- listener.removeEventListener('DOMMouseScroll');
- listener.removeEventListener('mousewheel');
- } else {
- listener.removeEventListener(type);
- }
-};
-
-
-/**
- * Sets the texture to use when a Texture or Sampler is missing while
- * rendering. The default is a red texture with a yellow no symbol.
- * <span style="color:yellow; background-color: red;">&Oslash;.
- * If you set it to null you'll get an error if you try to render something
- * that is missing a needed Texture, Sampler or ParamSampler.
- *
- * For example if you don't care about missing textures, setting it to a black
- * texture would be one option. Another example is if you want to write all
- * your shaders to expect a texture then set this to a white texture. If you
- * want to make sure you are not missing any textures set it null and see if
- * you get any errors using Client.setErrorCallback or Client.lastError.
- *
- * var t = g_pack.createTexture2D('', 1, 1, g_o3d.Texture.XRGB8, 1);
- * t.set(0, [0, 0, 0]);
- * g_client.setErrorTexture(t);
- *
- * @param {o3d.Texture} texture texture to use for missing textures or null.
- */
-o3d.Client.prototype.setErrorTexture =
- function(texture) {
- this.error_texture_ = texture;
-};
-
-
-/**
- * Sets the cubemap texture to use when a Texture or Sampler is missing while
- * rendering. The default is a red texture with a yellow no symbol.
- * <span style="color:yellow; background-color: red;">&Oslash;.
- * If you set it to null you'll get an error if you try to render something
- * that is missing a needed Texture, Sampler or ParamSampler.
- *
- * @param {o3d.Texture} texture Texture to use for missing textures or null.
- */
-o3d.Client.prototype.setErrorTextureCube =
- function(texture) {
- this.error_texture_cube_map_ = texture;
-};
-
-
-/**
- * Sets a callback for when the client ticks. The client processes some things
- * like animation timers at up to 100hz. This callback will get called before
- * each of those process ticks.
- *
- * NOTE: The client takes ownership of the TickCallback you
- * pass in. It will be deleted if you call SetTickCallback a
- * second time or if you call clearTickCallback.
- *
- * Note: The callback will not be called recursively.
- *
- * @param {o3d.TickCallback} tick_callback TickCallback to call when the
- * Client ticks.
- */
-o3d.Client.prototype.setTickCallback =
- function(tick_callback) {
- this.tickCallback = tick_callback;
-};
-
-
-/**
- * Clears the tick callback
- *
- * NOTE: The client takes ownership of the TickCallback you
- * pass in. It will be deleted if you call SetTickCallback a second
- * time or if you call clearTickCallback
- */
-o3d.Client.prototype.clearTickCallback = function() {
- this.tickCallback = null;
-};
-
-
-/**
- * Sets a callback for when the client gets an error. For example when a shader
- * is compiled and there is an error or if you attempt to bind a param to a
- * param of an incompatible type.
- *
- * NOTE: The client takes ownership of the ErrorCallback you
- * pass in. It will be deleted if you call SetErrorCallback a
- * second time or if you call ClearErrorCallback.
- *
- * NOTE: The callback will not be called recursively. If you are in a
- * callback, and do something that causes another error before you have
- * returned from the callback, your callback will not be called a second time.
- *
- * NOTE: If you put up an alert in response to an error it is best if you
- * clear the error callback before you put up the alert. Otherwise you'll get
- * an alert everytime the client tries to render which is every time you close
- * the current alert which means you'll be in an infinite loop of alerts.
- *
- * @param {o3d.ErrorCallback} error_callback ErrorCallback to call when the
- * Client gets an error.
- */
-o3d.Client.prototype.setErrorCallback =
- function(error_callback) {
- // Other code expects to not see a null error callback.
- if (error_callback) {
- this.error_callback = this.wrapErrorCallback_(error_callback);
- } else {
- this.error_callback = function(string) {
- this.last_error_ = string;
- };
- }
-};
-
-
-/**
- * Wraps a callback function, saving the error string so that the
- * lastError variable can access it.
- *
- * @param {function} error_callback User-defined error callback.
- * @return {function} Wrapped error callback.
- * @private
- */
-o3d.Client.prototype.wrapErrorCallback_ = function(error_callback) {
- return function(string) {
- this.last_error_ = string;
- error_callback(string);
- }
-}
-
-
-/**
- * Clears the Error callback
- *
- * NOTE: The client takes ownership of the ErrorCallback you
- * pass in. It will be deleted if you call SetErrorCallback a second
- * time or if you call ClearErrorCallback.
- */
-o3d.Client.prototype.clearErrorCallback = function() {
- this.setErrorCallback(null);
-};
-
-
-
-/**
- * Makes all parameters get re-evaluated.
- */
-o3d.Client.prototype.invalidateAllParameters = function() {
- o3d.notImplemented();
-};
-
-
-/**
- * Gets a copy of the current backbuffer of O3D as a data: url.
- * @param {string} mime_type The type of data url you want.
- * Currently O3D only supports image/png. See HTML5 canvas tag
- * for info about toDataURL.
- * @return {string} A Data URL for the backbuffer.
- */
-o3d.Client.prototype.toDataURL =
- function(opt_mime_type) {
- o3d.notImplemented();
-};
-
-
-/**
- * Saves data needed to return state to current, then sets the state according
- * to the given object.
- * @private
- */
-o3d.Client.prototype.clearStateStack_ = function() {
- this.stateMapStack_ = [];
- for (var name in this.stateVariableStacks_) {
- var l = this.stateVariableStacks_[name];
- // Recall there is a default value at the bottom of each of these stacks.
- if (l.length != 1) {
- this.stateVariableStacks_[name] = l.slice(0, 1);
- }
- }
-};
-
-
-/**
- * Saves data needed to return state to current, then sets the state according
- * to the given object.
- * @param {Object} variable_map A map linking names to values.
- * @private
- */
-o3d.Client.prototype.pushState_ = function(variable_map) {
- // Save the variable map itself in a stack.
- this.stateMapStack_.push(variable_map);
-
- // Save each of the state's variable's value in its own stack.
- for (var name in variable_map) {
- var value = variable_map[name];
- if (this.stateVariableStacks_[name] == undefined) {
- this.stateVariableStacks_[name] = [];
- }
- this.stateVariableStacks_[name].push(value);
- }
-
- // The value on the top of the stack in stateVariableStacks_
- // is current at this point.
- o3d.State.setVariables_(this.gl, variable_map);
-};
-
-
-/**
- * Returns the state to the way it was before the current state
- * @private
- */
-o3d.Client.prototype.popState_ = function() {
- var variable_map = this.stateMapStack_.pop();
-
- for (var name in variable_map) {
- var stack = this.stateVariableStacks_[name];
- stack.pop();
- variable_map[name] = stack.length ? stack[stack.length - 1] :
- o3d.State.stateVariableInfos_[name]['defaultValue'];
- }
-
- o3d.State.setVariables_(this.gl, variable_map);
-};
-
-
-/**
- * Gets the current value of the state variable with the give name.
- * @param {string} name The name of the state variable in question.
- * @private
- */
-o3d.Client.prototype.getState_ = function(name) {
- var stack = this.stateVariableStacks_[name];
- return stack.length ? stack[stack.length - 1] :
- o3d.State.stateVariableInfos_[name]['defaultValue'];
-};
-
-
-/**
- * Returns the status of initializing the renderer so we can display the
- * appropriate message. We require a certain minimum set of graphics
- * capabilities. If the user's computer does not have his minimum
- * set this will be GPU_NOT_UP_TO_SPEC. If the user is out of graphics
- * resources this will be OUT_OF_RESOURCES. If some other error happened this
- * will be INITIALIZATION_ERROR. Otherwise it will be SUCCESS.
- */
-o3d.Client.prototype.renderer_init_status = 0;
-
-
-/**
- * Gets / Sets the cursor's shape.
- *
- * @type {o3d.Cursor}
- */
-o3d.Client.prototype.cursor = null;
-
-
-/**
- * The current error texture.
- *
- * @type {o3d.Texture2D}
- * @private
- */
-o3d.Client.prototype.error_texture_ = null;
-
-
-/**
- * The current error cube texture.
- *
- * @type {o3d.TextureCUBE}
- * @private
- */
-o3d.Client.prototype.error_texture_cube_ = null;
-
-
-/**
- * The fallback error texture. Should only be initialized once per client and
- * is read-only.
- *
- * @type {!o3d.Texture2D}
- * @private
- */
-o3d.Client.prototype.fallback_error_texture_ = null;
-
-
-/**
- * The fallback error texture. Should only be initialized once per client and
- * is read-only.
- *
- * @type {!o3d.TextureCUBE}
- * @private
- */
-o3d.Client.prototype.fallback_error_texture_cube_ = null;
-
-
-/**
- * The last error reported by the plugin.
- *
- * @type {string}
- * @private
- */
-o3d.Client.prototype.last_error_ = '';
-o3d.Client.prototype.__defineGetter__('lastError',
- function() {
- return this.last_error_;
- }
-);
-
-/**
- * Returns true if missing textures, samplers or ParamSamplers should be
- * reported by calling the error callback. We assume that if the user
- * explicitly sets the error texture to null, then they want such errors to
- * trigger the error callback.
- *
- * @return {boolean}
- * @private
- */
-o3d.Client.prototype.reportErrors_ = function() {
- return (this.error_texture_ == null);
-}
-
-
-/**
- * All the objects managed by this client.
- *
- * Each access to this field gets the entire list so it is best to get it
- * just once. For example:
- *
- * var objects = client.objects;
- * for (var i = 0; i < objects.length; i++) {
- * var object = objects[i];
- * }
- *
- *
- * Note that modifications to this array [e.g. push()] will not affect
- * the underlying Client, while modifications to the array's members
- * will affect them.
- *
- * @type {!Array.<!o3d.ObjectBase>}
- */
-o3d.Client.prototype.objects = [];
-
-
-
-/**
- * Clears the error returned in lastError.
- */
-o3d.Client.prototype.clearLastError = function () {
- this.last_error_ = '';
-};
-
-
-
-/**
- * Resets the profiling information.
- */
-o3d.Client.prototype.profileReset = function() {
- o3d.notImplemented();
-};
-
-
-
-/**
- * Returns the profiling information as a string.
- * The profiling info.
- * @return {string}
- */
-o3d.Client.prototype.profileToString = function() {
- o3d.notImplemented();
-};
-
-
-
-/**
- * A unique id for this client.
- * @type {number}
- */
-o3d.Client.prototype.clientId = 0;
-
-
-
-/**
- * Gets info about the client.
- */
-o3d.Client.prototype.clientInfo = null;
-
-
-/**
- * The canvas associated with this client.
- * @type {Element}
- */
-o3d.Client.prototype.canvas = null;
diff --git a/o3d/samples/o3d-webgl/counter.js b/o3d/samples/o3d-webgl/counter.js
deleted file mode 100644
index b3c3190..0000000
--- a/o3d/samples/o3d-webgl/counter.js
+++ /dev/null
@@ -1,814 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * Per-client list of counters/timers.
- * @constructor
- */
-o3d.CounterManager = function() {
- /**
- * Map from counter type to list of counters in this client.
- * @private
- * @type {!Object}
- */
- this.counterMap_ = {};
-};
-
-/**
- * Contains the time of the last call to tick, so we know the amount to pass
- * into advanceCounters_
- * lastUpdated is initialized on the first call to tick().
- * @type {Date}
- */
-o3d.CounterManager.prototype.lastUpdated = null;
-
-/**
- * @param {string} type Which counter_type_ to advance.
- * @param {number} amount Amount to advance counters.
- */
-o3d.CounterManager.prototype.advanceCounters = function(type, amount) {
- var counterArrayRef = this.counterMap_[type];
- if (!counterArrayRef)
- return;
- var length = counterArrayRef.length;
- var counterArray = [];
- for (var i = 0; i < length; i++) {
- counterArray[i] = counterArrayRef[i];
- }
- for (var i = 0; i < length; ++i) {
- if (counterArray[i].running) {
- counterArray[i].advance(amount);
- }
- }
-};
-
-/**
- * Static method to increments all global counters. RenderFrameCounter should
- * not get updated here.
- */
-o3d.CounterManager.prototype.tick = function() {
- this.advanceCounters("TickCounter", 1.0);
- var now = new Date();
- var deltaSeconds = 0;
- if (this.lastUpdated != null) {
- deltaSeconds = (now - this.lastUpdated) / 1000.0;
- }
- this.lastUpdated = now;
- this.advanceCounters("SecondCounter", deltaSeconds);
-};
-
-/**
- * Updates RenderFrameCounter objects by 1.0, similarly to TickCounter.
- * As opposed to tick(), this should only be when the canvas is rendered, so
- * any canvases which are not automatically rendererd may not advance this.
- */
-o3d.CounterManager.prototype.advanceRenderFrameCounters = function() {
- this.advanceCounters("RenderFrameCounter", 1.0);
-};
-
-/**
- * Register a counter, using its className to decide which type of counter.
- * @param {!o3d.Counter} counter Instance of some sub-type of o3d.Counter
- */
-o3d.CounterManager.prototype.registerCounter = function(counter) {
- var type = counter.counter_type_;
- var arr = this.counterMap_[type];
- if (!arr) {
- arr = this.counterMap_[type] = [];
- }
- arr.push(counter);
-};
-
-/**
- * Unregister a counter previously registered by registerCounter.
- * @param {!o3d.Counter} counter Instance of some sub-type of o3d.Counter
- */
-o3d.CounterManager.prototype.unregisterCounter = function(counter) {
- var type = counter.counter_type_;
- var arr = this.counterMap_[type];
- if (arr) {
- o3d.removeFromArray(arr, counter);
- }
-};
-
-/**
- * A Counter counts seconds, ticks or render frames depending on the type of
- * counter. You can set where it starts counting from and where it stops
- * counting at, whether or not it is running or paused and how it loops or does
- * not loop. You can also give it callbacks to call at specific count values.
- * @constructor
- * @extends {o3d.ParamObject}
- */
-o3d.Counter = function() {
- o3d.ParamObject.call(this);
-
- /**
- * Last called callback in the forward direction (start_count > end_count)
- * @type {number}
- * @private
- */
- this.next_callback_ = -1;
-
- /**
- * Last called callback in the backward direction (start_count < end_count)
- * @type {number}
- * @private
- */
- this.prev_callback_ = -1;
-
- /**
- * Keeps track of last count in case this.count_ is bound to another param.
- * @type {number}
- * @private
- */
- this.old_count_ = 0;
-
- /**
- * Keeps track of last end_count to prevent double-firing of callbacks if
- * start_count is the same.
- * @type {number}
- * @private
- */
- this.last_call_callbacks_end_count_ = 0;
-
- /**
- * List of callbacks for this counter, in sorted order.
- * There can only be one callback per timer value.
- * @type {Array.<o3d.Counter.CallbackInfo>}
- * @private
- */
- this.callbacks_ = [];
-
- /**
- * Pointer to CounterManager which owns this counter, so it can be added
- * to the list of counters by setting this.running = true.
- * @type {o3d.CounterManager}
- */
- this.counter_manager_ = null;
-
- /**
- * Cached copy of this.getParam('running')
- * @type {o3d.ParamBoolean}
- * @private
- */
- this.running_param_ = this.createParam("running", "ParamBoolean");
-
- /**
- * Cached copy of this.getParam('count')
- * @type {o3d.ParamFloat}
- * @private
- */
- this.count_param_ = this.createParam("count", "ParamFloat");
-
- this.multiplier = 1.0;
-
- this.forward = true;
-
- this.countMode = o3d.Counter.CONTINUOUS;
-
- // this.running must be set in the sub class due to how o3d.inherit works.
-};
-o3d.inherit('Counter', 'ParamObject');
-
-/**
- * Controls the direction of the counter. If false, Counter.callCallbacks_
- * will be called with start_count > end_count.
- * @default true
- * @type {boolean}
- */
-o3d.ParamObject.setUpO3DParam_(o3d.Counter, "forward", "ParamBoolean");
-
-/**
- * The start value for this counter.
- * @default 0
- * @type {number}
- */
-o3d.ParamObject.setUpO3DParam_(o3d.Counter, "start", "ParamFloat");
-
-/**
- * The end value for this counter.
- * @default 0
- * @type {number}
- */
-o3d.ParamObject.setUpO3DParam_(o3d.Counter, "end", "ParamFloat");
-
-/**
- * Can be used to switch the direction of the counter or control what happens
- * when end_count is reached.
- * @see o3d.Counter.CONTINUOUS
- * @see o3d.Counter.ONCE
- * @see o3d.Counter.CYCLE
- * @see o3d.Counter.OSCILLATE
- * @default o3d.Counter.CONTINUOUS
- * @type {o3d.Counter.CountMode}
- */
-o3d.ParamObject.setUpO3DParam_(o3d.Counter, "countMode", "ParamInteger");
-
-/**
- * The time multiplier for this counter.
- * @default 1
- * @type {number}
- */
-o3d.ParamObject.setUpO3DParam_(o3d.Counter, "multiplier", "ParamFloat");
-
-/**
- * Whether or not this counter is running.
- * Special setter to allow destroying a stopped Counter without leaking mem.
- * Defaults to true in SecondCounter, TickCounter and RenderFrameCounter.
- * @default false
- * @type {boolean}
- */
-o3d.Counter.prototype.__defineSetter__("running",
- function(newRunning) {
- var oldRunning = this.running_param_.value;
- if (this.counter_manager_ && oldRunning != newRunning) {
- if (newRunning == false) {
- this.counter_manager_.unregisterCounter(this);
- } else {
- this.counter_manager_.registerCounter(this);
- }
- }
- this.running_param_.value = newRunning;
- }
-);
-o3d.Counter.prototype.__defineGetter__("running",
- function() {
- return this.running_param_.value;
- }
-);
-
-/**
- * The current count for this counter. The setter is equivalent to calling
- * setCount(value)
- * @default 0
- * @type {number}
- */
-o3d.Counter.prototype.__defineSetter__("count",
- function(value) {
- this.setCount(value);
- }
-);
-o3d.Counter.prototype.__defineGetter__("count",
- function() {
- return this.count_param_.value;
- }
-);
-
-o3d.Counter.prototype.__defineSetter__("gl",
- function(new_gl) {
- var old_running = this.running;
- this.running = false;
- this.gl_ = new_gl;
- if (this.gl_ && this.gl_.client) {
- this.counter_manager_ = this.gl_.client.counter_manager_;
- }
- this.running = old_running;
- }
-);
-
-o3d.Counter.prototype.__defineGetter__("gl",
- function() {
- return this.gl_;
- }
-);
-
-/**
- * @type {number}
- */
-o3d.Counter.CountMode = goog.typedef;
-
-/**
- * Continiuously goes up, ignoring the value of end_count. This is the default.
- * @type {o3d.Counter.CountMode}
- */
-o3d.Counter.CONTINUOUS = 0;
-/**
- * Sets running=false when end is reached and stops.
- * @type {o3d.Counter.CountMode}
- */
-o3d.Counter.ONCE = 1;
-/**
- * Resets count to start_count whenever end is reached.
- * @type {o3d.Counter.CountMode}
- */
-o3d.Counter.CYCLE = 2;
-/**
- * Switches direction whenever end or start is reached.
- * @type {o3d.Counter.CountMode}
- * @see direction
- */
-o3d.Counter.OSCILLATE = 3;
-
-/**
- * The counter type is used by o3d.CounterManager to decide which array to
- * put the counter in, and how much to call advanceAmount by during each call
- * to o3d.CounterManager.tick() or advanceRenderFrameCounters().
- * "Counter" means that it will only be advanced manually.
- * @type {string}
- */
-o3d.Counter.prototype.counter_type_ = "Counter";
-
-/**
- * Resets the counter back to the start or end time depending on the forward
- * setting and also resets the Callback state.
- * Note: Reset does not change the running state of the counter.
- */
-o3d.Counter.prototype.reset = function() {
- this.setCount(this.forward ? this.start : this.end);
-};
-
-/**
- * Sets the current count value for this counter as well as the resetting the
- * state of the callbacks.
- * @param {number} count The current value of the counter
- */
-o3d.Counter.prototype.setCount = function(value) {
- this.count_param_.value = value;
- this.old_count_ = value;
- this.next_callback_ = -1;
- this.prev_callback_ = -1;
-};
-
-
-/**
- * Advances the counter the given amount. The actual amount advanced depends on
- * the forward and multiplier settings. The formula is
- * new_count = count + advance_amount * multiplier * (forward ? 1.0 : -1.0);
- *
- * Any callbacks that fall in the range between the counter's current count and
- * the amount advanced will be called. This function is normally called
- * automatically by the client if the counter is set to running = true. but you
- * can call it manually.
- *
- * @param {number} advance_amount Amount to advance count.
- */
-o3d.Counter.prototype.advance = function(advance_amount) {
- var queue = [];
- var old_count = this.count_param_.value;
-
- // Update the count.
- if (this.count_param_.inputConnection) {
- this.callCallbacks_(this.old_count_, old_count, queue);
- } else {
- var direction = this.forward;
- var start_count = this.start;
- var end_count = this.end;
- var multiplier = this.multiplier;
- var delta = (direction ? advance_amount : -advance_amount) * multiplier;
- var period = end_count - start_count;
-
- var mode = this.countMode;
- if (period >= 0.0) {
- // end > start
- var new_count = old_count + delta;
- if (delta >= 0.0) {
- switch (mode) {
- case o3d.Counter.ONCE: {
- if (new_count >= end_count) {
- new_count = end_count;
- this.running = false;
- }
- break;
- }
- case o3d.Counter.CYCLE: {
- while (new_count >= end_count) {
- this.callCallbacks_(old_count, end_count, queue);
- if (period == 0.0) {
- break;
- }
- old_count = start_count;
- new_count -= period;
- }
- break;
- }
- case o3d.Counter.OSCILLATE: {
- while (delta > 0.0) {
- new_count = old_count + delta;
- if (new_count < end_count) {
- break;
- }
- this.callCallbacks_(old_count, end_count, queue);
- direction = !direction;
- var amount = end_count - old_count;
- delta -= amount;
- old_count = end_count;
- new_count = end_count;
- if (delta <= 0.0 || period == 0.0) {
- break;
- }
- new_count -= delta;
- if (new_count > start_count) {
- break;
- }
- this.callCallbacks_(old_count, start_count, queue);
- direction = !direction;
- amount = old_count - start_count;
- delta -= amount;
- old_count = start_count;
- new_count = start_count;
- }
- this.forward = direction;
- break;
- }
- case o3d.Counter.CONTINUOUS:
- default:
- break;
- }
- this.callCallbacks_(old_count, new_count, queue);
- this.count_param_.value = new_count;
- } else if (delta < 0.0) {
- switch (mode) {
- case o3d.Counter.ONCE: {
- if (new_count <= start_count) {
- new_count = start_count;
- this.running = false ;
- }
- break;
- }
- case o3d.Counter.CYCLE: {
- while (new_count <= start_count) {
- this.callCallbacks_(old_count, start_count, queue);
- if (period == 0.0) {
- break;
- }
- old_count = end_count;
- new_count += period;
- }
- break;
- }
- case o3d.Counter.OSCILLATE: {
- while (delta < 0.0) {
- new_count = old_count + delta;
- if (new_count > start_count) {
- break;
- }
- this.callCallbacks_(old_count, start_count, queue);
- direction = !direction;
- var amount = old_count - start_count;
- delta += amount;
- old_count = start_count;
- new_count = start_count;
- if (delta >= 0.0 || period == 0.0) {
- break;
- }
- new_count -= delta;
- if (new_count < end_count) {
- break;
- }
- this.callCallbacks_(old_count, end_count, queue);
- direction = !direction;
- amount = end_count - old_count;
- delta += amount;
- old_count = end_count;
- new_count = end_count;
- }
- this.forward = direction;
- break;
- }
- case o3d.Counter.CONTINUOUS:
- default:
- break;
- }
- this.callCallbacks_(old_count, new_count, queue);
- this.count_param_.value = new_count;
- }
- } else if (period < 0.0) {
- // start > end
- period = -period;
- var new_count = old_count - delta;
- if (delta > 0.0) {
- switch (mode) {
- case o3d.Counter.ONCE: {
- if (new_count <= end_count) {
- new_count = end_count;
- this.running = false;
- }
- break;
- }
- case o3d.Counter.CYCLE: {
- while (new_count <= end_count) {
- this.callCallbacks_(old_count, end_count, queue);
- old_count = start_count;
- new_count += period;
- }
- break;
- }
- case o3d.Counter.OSCILLATE: {
- while (delta > 0.0) {
- new_count = old_count - delta;
- if (new_count > end_count) {
- break;
- }
- this.callCallbacks_(old_count, end_count, queue);
- direction = !direction;
- var amount = old_count - end_count;
- delta -= amount;
- old_count = end_count;
- new_count = end_count;
- if (delta <= 0.0) {
- break;
- }
- new_count += delta;
- if (new_count < start_count) {
- break;
- }
- this.callCallbacks_(old_count, start_count, queue);
- direction = !direction;
- amount = start_count - old_count;
- delta -= amount;
- old_count = start_count;
- new_count = start_count;
- }
- this.forward = direction;
- break;
- }
- case o3d.Counter.CONTINUOUS:
- default:
- break;
- }
- this.callCallbacks_(old_count, new_count, queue);
- this.count_param_.value = new_count;
- } else if (delta < 0.0) {
- switch (mode) {
- case o3d.Counter.ONCE: {
- if (new_count >= start_count) {
- new_count = start_count;
- this.running = false;
- }
- break;
- }
- case o3d.Counter.CYCLE: {
- while (new_count >= start_count) {
- this.callCallbacks_(old_count, start_count, queue);
- old_count = end_count;
- new_count -= period;
- }
- break;
- }
- case o3d.Counter.OSCILLATE: {
- while (delta < 0.0) {
- new_count = old_count - delta;
- if (new_count < start_count) {
- break;
- }
- this.callCallbacks_(old_count, start_count, queue);
- direction = !direction;
- var amount = start_count - old_count;
- delta += amount;
- old_count = start_count;
- new_count = start_count;
- if (delta >= 0.0) {
- break;
- }
- new_count += delta;
- if (new_count > end_count) {
- break;
- }
- this.callCallbacks_(old_count, end_count, queue);
- direction = !direction;
- amount = old_count - end_count;
- delta += amount;
- old_count = end_count;
- new_count = end_count;
- }
- this.forward = direction;
- break;
- }
- case o3d.Counter.CONTINUOUS:
- default:
- break;
- }
- this.callCallbacks_(old_count, new_count, queue);
- this.count_param_.value = new_count;
- }
- }
- }
- this.old_count_ = old_count;
- for (var i = 0; i < queue.length; i++) {
- queue[i]();
- }
-};
-
-/**
- * @param {number} start_count Starts exactly at this count.
- * @param {number} end_count Calls callbacks up to but not including this.
- * @private
- */
-o3d.Counter.prototype.callCallbacks_ = function(start_count, end_count, queue) {
- if (end_count > start_count) {
- // Going forward.
- // If next_callback is not valid, find the first possible callback.
- if (this.next_callback_ < 0 ||
- start_count != this.last_call_callbacks_end_count_) {
- this.next_callback_ = 0;
- while (this.next_callback_ != this.callbacks_.length &&
- this.callbacks_[this.next_callback_].count < start_count) {
- ++this.next_callback_;
- }
- }
-
- // add callbacks until we get to some callback past end_count.
- while (this.next_callback_ < this.callbacks_.length) {
- if (this.callbacks_[this.next_callback_].count > end_count) {
- break;
- }
- queue.push(this.callbacks_[this.next_callback_].callback);
- ++this.next_callback_;
- }
- this.prev_callback_ = -1;
- this.last_call_callbacks_end_count_ = end_count;
- } else if (end_count < start_count) {
- // Going backward.
- // If prev_callback is not valid, find the first possible callback.
- if (this.prev_callback_ < 0 ||
- start_count != this.last_call_callbacks_end_count_) {
- this.prev_callback_ = this.callbacks_.length - 1;
- while (this.prev_callback_ >= 0 &&
- this.callbacks_[this.prev_callback_].count > start_count) {
- --this.prev_callback_;
- }
- }
-
- // add callbacks until we get to some callback past end_count.
- while (this.prev_callback_ >= 0) {
- if (this.callbacks_[this.prev_callback_].count < end_count) {
- break;
- }
- queue.push(this.callbacks_[this.prev_callback_].callback);
- --this.prev_callback_;
- }
-
- this.next_callback_ = -1;
- this.last_call_callbacks_end_count_ = end_count;
- }
-};
-
-/**
- * Adds a callback for a given count value. Only one callback can be added to a
- * specific count value. If another callback is added with the same count value
- * the previous callback for that value will be replaced. Note: A callback at
- * start will only get called when counting backward, a callback at end will
- * only get called counting forward.
- * @param {number} count Count at which to call callback.
- * @param {function()} callback Callback to call at given count.
- */
-o3d.Counter.prototype.addCallback = function(count, callback) {
- this.next_callback_ = -1;
- this.prev_callback_ = -1;
- var end = this.callbacks_.length;
- var iter = 0;
- while (iter != end) {
- var current = this.callbacks_[iter];
- if (current.count == count) {
- // Did the o3d plugin overwrite existing callbacks here?
- current.callback = callback;
- return;
- } else if (current.count > count) {
- break;
- }
- ++iter;
- }
- var rest = this.callbacks_.splice(iter, this.callbacks_.length - iter);
- this.callbacks_.push(new o3d.Counter.CallbackInfo(count, callback));
- this.callbacks_.push.apply(this.callbacks_, rest);
-};
-
-/**
- * Removes a callback for a given count value.
- * @param {number} count Count to remove callback for.
- * @return {boolean} true if there was a callback for that count, false if
- * there was not a callback for that count.
- */
-o3d.Counter.prototype.removeCallback = function(count) {
- var end = this.callbacks_.length;
- for (var iter = 0; iter != end; ++iter) {
- if (this.callbacks_[iter].count == count) {
- this.next_callback_ = -1;
- this.prev_callback_ = -1;
- this.callbacks_.splice(iter, 1);
- return true;
- }
- }
- return false;
-};
-
-/**
- * Removes all the callbacks on this counter.
- * Does not affect running state: set running=false to allow this counter to be
- * garbage collected.
- */
-o3d.Counter.prototype.removeAllCallbacks = function() {
- this.callbacks_ = [];
- this.next_callback_ = -1;
- this.prev_callback_ = -1;
-};
-
-/**
- * Class to hold onto the state of a callback function at a specific count.
- * @constructor
- * @param {number} count Count at which this callback will get called.
- * @param {function()} callback Function to call when count is reached.
- */
-o3d.Counter.CallbackInfo = function(count, callback) {
- /**
- * Count at which this callback will get called.
- * @type {number}
- */
- this.count = count;
-
- /**
- * Function to call when count is reached.
- * @type {function()}
- */
- this.callback = callback;
-
- /**
- * Prevents recursion of the same callback, in case it decides to advance
- * the counter.
- * @type {boolean}
- * @private
- */
- this.called_ = false;
-};
-
-/**
- * Run this callback without the possibility for recursion.
- */
-o3d.Counter.CallbackInfo.prototype.run = function() {
- if (!this.called_) {
- this.called_ = true;
- this.callback();
- this.called_ = false;
- }
-};
-
-/**
- * Counter to count seconds. Logic is implemented in CounterManager.tick()
- * @constructor
- * @extends {o3d.Counter}
- */
-o3d.SecondCounter = function() {
- o3d.Counter.call(this);
- this.running = true;
-};
-
-o3d.inherit("SecondCounter", "Counter");
-
-o3d.SecondCounter.prototype.counter_type_ = "SecondCounter";
-
-/**
- * Counter to count frames. Logic is implemented in
- * CounterManager.advanceRenderFrameCounters()
- * @constructor
- * @extends {o3d.Counter}
- */
-o3d.RenderFrameCounter = function() {
- o3d.Counter.call(this);
- this.running = true;
-};
-
-o3d.inherit("RenderFrameCounter", "Counter");
-
-o3d.RenderFrameCounter.prototype.counter_type_ = "RenderFrameCounter";
-
-/**
- * Counter to count ticks. Logic is implemented in CounterManager.tick()
- * @constructor
- * @extends {o3d.Counter}
- */
-o3d.TickCounter = function() {
- o3d.Counter.call(this);
- this.running = true;
-};
-
-o3d.inherit("TickCounter", "Counter");
-
-o3d.TickCounter.prototype.counter_type_ = "TickCounter";
diff --git a/o3d/samples/o3d-webgl/curve.js b/o3d/samples/o3d-webgl/curve.js
deleted file mode 100644
index 6425fbb..0000000
--- a/o3d/samples/o3d-webgl/curve.js
+++ /dev/null
@@ -1,912 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * A CurveKey prepresents a key on an Curve.
- *
- * @constructor
- * @extends {o3d.ObjectBase}
- */
-o3d.CurveKey = function(owner) {
- o3d.ObjectBase.call(this);
- /**
- * The only owner of this CurveKey (cannot be shared).
- * @private
- * @type {!o3d.Curve}
- */
- this.owner_ = owner;
-
- /**
- * See input setter.
- * @private
- * @type {number}
- */
- this.input_ = 0;
-
- /**
- * See input setter.
- * @private
- * @type {number}
- */
- this.output_ = 0;
-};
-o3d.inherit('CurveKey', 'ObjectBase');
-
-/**
- * Destroys this key, removing it from its owner.
- *
- */
-o3d.CurveKey.prototype.destroy = function() {
- o3d.removeFromArray(this.owner_.keys, this);
- this.owner_.invalidateCache_();
-};
-
-/**
- * Computes the value within the range from this.input to next_key.input.
- * Defaults to the LinearCurveKey implementation which is continuous.
- * @param {number} offset Offset within the key (function input - this.input)
- * @param {o3d.CurveKey} next_key The next key in the set, can not be null.
- * @return {number} return
- */
-o3d.CurveKey.prototype.getOutputAtOffset = function(offset, next_key) {
- var input_span = next_key.input - this.input;
- var output_span = next_key.output - this.output;
- return this.output + offset / input_span * output_span;
-};
-
-/**
- * Input for this key. This curve key will apply until the next key's input.
- * @type {number}
- */
-o3d.CurveKey.prototype.__defineGetter__("input", function() {
- return this.input_;
-});
-o3d.CurveKey.prototype.__defineSetter__("input", function(new_input) {
- if (new_input != this.input_) {
- this.input_ = new_input;
- this.owner_.invalidateCache_();
- }
-});
-
-/**
- * Output corresponding to input.
- * @type {number}
- */
-o3d.CurveKey.prototype.__defineGetter__("output", function() {
- return this.output_;
-});
-o3d.CurveKey.prototype.__defineSetter__("output", function(new_output) {
- if (new_output != this.output_) {
- this.output_ = new_output;
- this.owner_.invalidateCache_();
- }
-});
-
-/**
- * An CurveKey that holds its output (is not interpolated between this key
- * and the next.)
- *
- * Other discontinuous CurveKey classes must be derived from StepCurveKey.
- *
- * @constructor
- * @extends {o3d.CurveKey}
- */
-o3d.StepCurveKey = function(owner) {
- o3d.CurveKey.call(this, owner);
- owner.num_step_keys_++;
-};
-o3d.inherit('StepCurveKey', 'CurveKey');
-
-/**
- * Simple discontinuous implementation.
- * @param {number} offset Ignored: constant output within a StepCurveKey
- * @param {o3d.CurveKey} next_key Ignored: discontinuous
- * @return {number} output
- */
-o3d.StepCurveKey.prototype.getOutputAtOffset = function(offset, next_key) {
- return this.output;
-};
-
-/**
- * Specialized destroy method to update the num_step_keys_ of the owner_.
- */
-o3d.StepCurveKey.prototype.destroy = function() {
- o3d.CurveKey.prototype.destroy.call(this);
- this.owner_.num_step_keys_--;
-};
-
-/**
- * An CurveKey that linearly interpolates between this key and the next key.
- *
- * @constructor
- * @extends {o3d.CurveKey}
- */
-o3d.LinearCurveKey = function(owner) {
- o3d.CurveKey.call(this, owner);
-};
-o3d.inherit('LinearCurveKey', 'CurveKey');
-
-/**
- * An CurveKey that uses a bezier curve for interpolation between this key
- * and the next.
- *
- * @constructor
- * @extends {o3d.CurveKey}
- */
-o3d.BezierCurveKey = function(owner) {
- o3d.CurveKey.call(this, owner);
-
- /**
- * See input setter.
- * @private
- * @type {Array.<number>}
- */
- this.in_tangent_ = [0, 0];
-
- /**
- * See input setter.
- * @private
- * @type {Array.<number>}
- */
- this.out_tangent_ = [0, 0];
-};
-o3d.inherit('BezierCurveKey', 'CurveKey');
-
-/**
- * Tangent for values approaching this key. Do not set elements in the array
- * directly as that will prevent calling invalidateCache_.
- * @type {Array.<number>}
- */
-o3d.BezierCurveKey.prototype.__defineGetter__("inTangent", function() {
- return this.in_tangent_;
-});
-o3d.BezierCurveKey.prototype.__defineSetter__("inTangent", function(new_t) {
- if (new_t != this.in_tangent_) {
- this.in_tangent_ = new_t;
- this.owner_.invalidateCache_();
- }
-});
-
-/**
- * Tangent for values approaching the next key. Do not set elements in the array
- * directly as that will prevent calling invalidateCache_.
- * @type {Array.<number>}
- */
-o3d.BezierCurveKey.prototype.__defineGetter__("outTangent", function() {
- return this.out_tangent_;
-});
-o3d.BezierCurveKey.prototype.__defineSetter__("outTangent", function(new_t) {
- if (new_t != this.out_tangent_) {
- this.out_tangent_ = new_t;
- this.owner_.invalidateCache_();
- }
-});
-
-/**
- * Uses iterative method to accurately pin-point the 't' of the Bezier
- * equation that corresponds to the current time.
- * @param {number} control_point_0_x this.input
- * @param {number} control_point_1_x this.outTangent
- * @param {number} control_point_2_x next.inTangent
- * @param {number} control_point_3_x next.input
- * @param {number} input Absolute input value relative to span
- * @param {number} initial_guess Starting point assuming mostly linear.
- * @private
- */
-o3d.BezierCurveKey.findT_ = function(control_point_0_x,
- control_point_1_x,
- control_point_2_x,
- control_point_3_x,
- input,
- initial_guess) {
- var local_tolerance = 0.001;
- var high_t = 1.0;
- var low_t = 0.0;
-
- // TODO: Optimize here, start with a more intuitive value than 0.5
- // (comment left over from original code)
- var mid_t = 0.5;
- if (initial_guess <= 0.1) {
- mid_t = 0.1; // clamp to 10% or 90%, because if miss, the cost is
- // too high.
- } else if (initial_guess >= 0.9) {
- mid_t = 0.9;
- } else {
- mid_t = initial_guess;
- }
- var once = true;
- while ((high_t-low_t) > local_tolerance) {
- if (once) {
- once = false;
- } else {
- mid_t = (high_t - low_t) / 2.0 + low_t;
- }
- var ti = 1.0 - mid_t; // (1 - t)
- var calculated_time = control_point_0_x * ti * ti * ti +
- 3 * control_point_1_x * mid_t * ti * ti +
- 3 * control_point_2_x * mid_t * mid_t * ti +
- control_point_3_x * mid_t * mid_t * mid_t;
- if (Math.abs(calculated_time - input) <= local_tolerance) {
- break; // If we 'fall' very close, we like it and break.
- }
- if (calculated_time > input) {
- high_t = mid_t;
- } else {
- low_t = mid_t;
- }
- }
- return mid_t;
-};
-
-/**
- * Computes the value of the Bezier curve within the range from this.input
- * to next_key.input.
- * @param {number} offset Offset within the key (function input - this.input)
- * @param {o3d.CurveKey} next_key The next key in the set, can not be null.
- * @return {number} return
- */
-o3d.BezierCurveKey.prototype.getOutputAtOffset = function(offset, next_key) {
- var input_span = next_key.input - this.input;
- var output_span = next_key.output - this.output;
- var in_tangent;
-
- // We check bezier first because it's the most likely match for another
- // bezier key.
- if (next_key.inTangent) {
- in_tangent = next_key.inTangent;
- } else {
- in_tangent = [next_key.input - input_span / 3.0,
- next_key.output - output_span / 3.0];
- }
-
- // Do a bezier calculation.
- var t = offset / input_span;
- t = o3d.BezierCurveKey.findT_(this.input,
- this.outTangent[0],
- in_tangent[0],
- next_key.input,
- this.input + offset,
- t);
- var b = this.outTangent[1];
- var c = in_tangent[1];
- var ti = 1.0 - t;
- var br = 3.0;
- var cr = 3.0;
- return this.output * ti * ti * ti + br * b * ti * ti * t +
- cr * c * ti * t * t + next_key.output * t * t * t;
-};
-
-/**
- * A Curve stores a bunch of CurveKeys and given a value
- * representing an input point on a curve returns the output of the curve for
- * that input. Curve is data only. It is used by 1 or more
- * FunctionEval objects or by direct use from javascript.
- *
- * @constructor
- * @extends {o3d.Function}
- */
-o3d.Curve = function() {
- o3d.Function.call(this, this.evaluate);
-
- /**
- * The behavior of the curve before the first key.
- * @see o3d.Curve.CONSTANT
- * @see o3d.Curve.LINEAR
- * @see o3d.Curve.CYCLE
- * @see o3d.Curve.CYCLE_RELATIVE
- * @see o3d.Curve.OSCILLATE
- * @type {o3d.Curve.Infinity}
- * @default CONSTANT
- */
- this.preInfinity = o3d.Curve.CONSTANT;
-
- /**
- * The behavior of the curve before the first key.
- * @see o3d.Curve.CONSTANT
- * @see o3d.Curve.LINEAR
- * @see o3d.Curve.CYCLE
- * @see o3d.Curve.CYCLE_RELATIVE
- * @see o3d.Curve.OSCILLATE
- * @type {o3d.Curve.Infinity}
- * @default CONSTANT
- */
- this.postInfinity = o3d.Curve.CONSTANT;
-
- /**
- * Whether or not a cache is used to speed up evaluation of this Curve.
- */
- this.useCache = true;
-
- /**
- * Data for sampleRate setter.
- * @type {number}
- * @private
- */
- this.sample_rate_ = o3d.Curve.kDefaultSampleRate;
-
- /**
- * The keys for this curve.
- *
- * This property is read-only.
- * @type {!Array.<!o3d.CurveKey>}
- */
- this.keys = [];
-
- /**
- * Keep track if a new key has been added which hasn't been sorted.
- * @type {boolean}
- * @private
- */
- this.sorted_ = true;
-
- /**
- * True if the curve needs to checks for discontinuity errors before the next
- * evauluation.
- * @see updateCurveInfo_
- * @type {boolean}
- * @private
- */
- this.check_discontinuity_ = false;
-
- /**
- * Keep track if any discontinuous (steps or gaps) keys are in the mix.
- * Call isDiscontinuous to access this value, which updates it if necessary.
- * @type {boolean}
- * @private
- */
- this.discontinuous_= false;
-
- /**
- * @type {number} Number of step keys--used to speed up updateCurveInfo_
- * discontinuity check if it's non-zero.
- * @private
- */
- this.num_step_keys_ = 0;
-
-};
-
-o3d.inherit('Curve', 'Function');
-
-/**
- * Constant representing the fastest possible sample period. More samples take
- * more computation initially and more memroy.
- */
-o3d.Curve.kMinimumSampleRate = 1.0 / 240.0;
-
-/**
- * By default, sample 30 times per curve key.
- */
-o3d.Curve.kDefaultSampleRate = 1.0 / 30.0;
-
-/**
- * Gets the sample rate for the cache. By default Animation data is
- * cached so that using the animation is fast. To do this the keys that
- * represent the animation are sampled. The higher the frequency of the
- * samples the closer the cache will match the actual keys.
- * The default is 1/30 (30hz). You can set it anywhere from 1/240th (240hz) to
- * any larger value. Note: Setting the sample rate has the side effect of
- * invalidating the cache thereby causing it to get rebuilt.
- * Must be 1/240 or greater. Default = 1/30.
- *
- * @type {number}
- */
-o3d.Curve.prototype.__defineGetter__("sampleRate", function() {
- return this.sample_rate_;
-});
-
-o3d.Curve.prototype.__defineSetter__("sampleRate", function(rate) {
- if (rate < o3d.Curve.kMinimumSampleRate) {
- rate = o3d.Curve.kMinimumSampleRate;
- this.gl.client.error_callback(
- "attempt to set sample rate to " + rate +
- " which is lower than the minimum of " + o3d.Curve.kMinimumSampleRate);
- } else if (rate != this.sample_rate_) {
- this.sample_rate_ = rate;
- this.invalidateCache_();
- }
-});
-
-/**
- * @type {number}
- */
-o3d.Curve.Infinity = goog.typedef;
-
-/**
- * Uses the output value of the first or last animation key.
- * @type {o3d.Curve.Infinity}
- */
-o3d.Curve.CONSTANT = 0;
-
-/**
- * Takes the distance between the closest animation key input value and the
- * evaluation time. Multiplies this distance against the instant slope at the
- * closest animation key and offsets the result with the closest animation key
- * output value.
- * @type {o3d.Curve.Infinity}
- */
-o3d.Curve.LINEAR = 1;
-
-/**
- * Cycles over the first and last keys using:
- * input = (input - first) % (last - first) + first;
- * Note that in CYCLE mode you can never get the end output because a cycle
- * goes from start to end exclusive of end.
- * @type {o3d.Curve.Infinity}
- */
-o3d.Curve.CYCLE = 2;
-
-/**
- * Same as cycle except the offset of the entire cycle is added to each
- * consecutive cycle.
- * @type {o3d.Curve.Infinity}
- */
-o3d.Curve.CYCLE_RELATIVE = 3;
-
-/**
- * Ping Pongs between the first and last keys.
- * @type {o3d.Curve.Infinity}
- */
-o3d.Curve.OSCILLATE = 4;
-
-/**
- * Deserializes from the curve data given a RawData object.
- *
- * @param {!o3d.RawData} rawData contains curve data
- * @param {number} opt_offset is a byte offset from the start of raw_data
- * @param {number} opt_length is the byte length of the data to set
- * @return {boolean} True if operation was successful.
- *
- */
-o3d.Curve.prototype.set = function(rawData, opt_offset, opt_length) {
- o3d.notImplemented();
-};
-
-/**
- * Creates a new key for this curve.
- * @param {string} keyType name of key class to create. Valid type names are:
- * <li> 'StepCurveKey',
- * <li> 'LinearCurveKey',
- * <li> 'BezierCurveKey',
- * @return {!o3d.CurveKey} The created key.
- *
- */
-o3d.Curve.prototype.createKey = function(keyType) {
- var newKey = new (o3d[keyType]) (this);
- this.keys.push(newKey);
- return newKey;
-};
-
-/**
- * Adds 1 or more LinearKeys to this Curve.
- *
- * Example:
- * <pre>
- * // Creates 2 keys.
- * // 1 key at 0 with an output of 10
- * // 1 key at 20 with an output of 30
- * curve.addLinearKeys([0,10,20,30]);
- * </pre>.
- *
- * @param {!Array.<number>} values Array of input, output pairs.
- * Length must be a multiple of 2
- */
-o3d.Curve.prototype.addLinearKeys = function(values) {
- var kNumLinearKeyValues = 2;
- if (values.length % kNumLinearKeyValues != 0) {
- this.gl.client.error_callback(
- "addLinearKeys: expected multiple of 2 values got "+values.size());
- return;
- }
- for (var i = 0; i < values.length; i += kNumLinearKeyValues) {
- var newKey = this.createKey("LinearCurveKey");
- newKey.input = values[i];
- newKey.output = values[i+1];
- }
- this.sorted_ = false;
-};
-
-/**
- * Adds 1 or more StepKeys to this Curve.
- *
- * Example:
- * <pre>
- * // Creates 2 keys.
- * // 1 key at 0 with an output of 10
- * // 1 key at 20 with an output of 30
- * curve.addStepKeys([0,10,20,30]);
- * </pre>.
- *
- * @param {!Array.<number>} values Array of input, output pairs.
- * Length must be a multiple of 2
- */
-o3d.Curve.prototype.addStepKeys = function(values) {
- var kNumStepKeyValues = 2;
- if (values.length % kNumStepKeyValues != 0) {
- this.gl.client.error_callback(
- "addStepKeys: expected multiple of 2 values got "+values.size());
- return;
- }
- for (var i = 0; i < values.length; i += kNumStepKeyValues) {
- var newKey = this.createKey("StepCurveKey");
- newKey.input = values[i];
- newKey.output = values[i+1];
- }
- this.sorted_ = false;
-};
-
-/**
- * Adds 1 or more BezierKeys to this Curve.
- *
- * Example:
- * <pre>
- * // Creates 2 keys.
- * // 1 key at 0 with an output of 10, in tangent of 1,9, out tangent 9,0.5
- * // 1 key at 20 with an output of 30, in tangent of 30, 3, out tangent 4, 28
- * curve.addBezierKeys([0,10,1,9,9,0.5,2,30,3,4,28]);
- * </pre>.
- *
- * @param {!Array.<number>} values Array of tuples of the form (input, output,
- * inTangent[0], inTangent[1], outTangent[0], outTangent[1]).
- * Length must be a multiple of 6.
- */
-o3d.Curve.prototype.addBezierKeys = function(values) {
- var kNumBezierKeyValues = 6;
- if (values.length % kNumBezierKeyValues != 0) {
- this.gl.client.error_callback(
- "addBezierKeys: expected multiple of 6 values got "+values.size());
- return;
- }
- for (var i = 0; i < values.length; i += kNumBezierKeyValues) {
- var newKey = this.createKey("BezierCurveKey");
- newKey.input = values[i];
- newKey.output = values[i+1];
- newKey.inTangent[0] = values[i+2];
- newKey.inTangent[1] = values[i+3];
- newKey.outTangent[0] = values[i+4];
- newKey.outTangent[1] = values[i+5];
- }
- this.sorted_ = false;
-};
-
-/**
- * Force updating the cache or checking discontinuity.
- * @private
- */
-o3d.Curve.prototype.invalidateCache_ = function() {
- this.check_valid_ = false;
- this.check_discontinuity_ = true;
-};
-
-/**
- * Returns whether or not the curve is discontinuous. A discontinuous curve
- * takes more time to evaluate.
- * @return {boolean} True if the curve is discontinuous.
- */
-o3d.Curve.prototype.isDiscontinuous = function() {
- this.updateCurveInfo_();
- return this.discontinuous_;
-};
-
-/**
- * Comparator to allow sorting by keys by their input value.
- * @param {o3d.CurveKey} a First input to compare.
- * @param {o3d.CurveKey} b Second input to compare.
- * @return {number} positive, zero, or negative (see Array.sort)
- */
-o3d.Curve.compareInputs_ = function(a, b) {
- return a.input - b.input;
-};
-
-/**
- * Sorts keys (if sorted_ is false) and updates discontinuous_
- * (if check_discontinuity_ is true).
- * Called automatically when necessary in evaluate and isDiscontinuous.
- * @private
- */
-o3d.Curve.prototype.updateCurveInfo_ = function() {
- if (!this.sorted_) {
- // resort keys
- this.keys.sort(o3d.Curve.compareInputs_);
- this.sorted_ = true;
- this.invalidateCache_();
- }
- if (this.check_discontinuity_) {
- // Mark the curve as discontinuous if any 2 keys share the same input and
- // if their outputs are different.
- this.check_discontinuity_ = false;
- var keys_size = this.keys.length;
- this.discontinuous_ = (this.num_step_keys_ > 0 &&
- this.num_step_keys_ != keys_size);
- if (!this.discontinuous_ && keys_size > 1) {
- for (var ii = 0; ii < keys_size - 1; ++ii) {
- if (this.keys[ii].input == this.keys[ii + 1].input &&
- this.keys[ii].output != this.keys[ii + 1].output) {
- this.discontinuous_ = true;
- break;
- }
- }
- }
- }
-};
-
-/**
- * @param {number} input Guaranteed to be between the first and last key.
- * @param {object} context Generic cache to speed up adjacent computations.
- * @return {number} Final output value
- * @private
- */
-o3d.Curve.prototype.getOutputInSpan_ = function(input, context) {
- var keys = this.keys;
- var keys_size = keys.length;
- if (input < keys[0].input) {
- this.gl.client.error_callback(
- "Curve.getOutputInSpan_: input is lower than any key");
- return 0;
- }
-
- if (input >= keys[keys_size-1].input) {
- return keys[keys_size-1].output;
- }
-
- // use the keys directly.
- var start = 0;
- var end = keys_size;
- var key_index;
- var found = false;
-
- var kKeysToSearch = 3;
-
- // See if the context already has a index to the correct key.
- if (context) {
- key_index = context.curve_last_key_index_;
- // is that index in range.
- if (key_index < end - 1) {
- // Are we between these keys.
- if (keys[key_index].input <= input &&
- keys[key_index + 1].input > input) {
- // Yes!
- found = true;
- } else {
- // No, so check which way we need to go.
- if (input > keys[key_index].input) {
- // search forward a few keys. If it's not within a few keys give up.
- var check_end = key_index + kKeysToSearch;
- if (check_end > end) {
- check_end = end;
- }
- for (++key_index; key_index < check_end; ++key_index) {
- if (keys[key_index].input <= input &&
- keys[key_index + 1].input > input) {
- // Yes!
- found = true;
- break;
- }
- }
- } else if (key_index > 0) {
- // search backward a few keys. If it's not within a few keys give up.
- var check_end = key_index - kKeysToSearch;
- if (check_end < 0) {
- check_end = 0;
- }
- for (--key_index; key_index >= check_end; --key_index) {
- if (keys[key_index].input <= input &&
- keys[key_index + 1].input > input) {
- // Yes!
- found = true;
- break;
- }
- }
- }
- }
- }
- }
-
- if (!found) {
- // TODO: If we assume the most common case is sampled keys and
- // constant intervals we can make a quick guess where that key is.
-
- // Find the current the keys that cover our input.
- while (start <= end) {
- var mid = Math.floor((start + end)/2);
- if (input > keys[mid].input) {
- start = mid + 1;
- } else {
- if (mid == 0) {
- break;
- }
- end = mid - 1;
- }
- }
-
- end = keys_size;
- while (start < end) {
- if (keys[start].input > input) {
- break;
- }
- ++start;
- }
- if (start <= 0 || start >= end) {
- this.gl.client.error_callback(
- "Curve.getOutputInSpan_: start is outside range.");
- }
-
- key_index = start - 1;
- }
-
- var key = keys[key_index];
- if (context) {
- context.curve_last_key_index_ = key_index;
- }
- if (key_index+1 >= keys_size || !keys[key_index+1]) {
- this.gl.client.error_callback(
- "Curve.getOutputInSpan_: next key is null: index is "+key_index+
- "; size is "+keys_size);
- return key.output;
- } else {
- return key.getOutputAtOffset(input - key.input, keys[key_index+1]);
- }
-};
-
-/**
- * Evaluates a point on this bezier curve corresponding to input.
- *
- * @param {number} input Input value to evaluate.
- * @param {number} context Context of the last evaluation.
- * @return {number} output value
- */
-o3d.Curve.prototype.evaluate = function(input, context) {
- var keys = this.keys;
- var keys_size = keys.length;
-
- if (keys_size == 0) {
- return 0.0;
- }
-
- if (keys_size == 1) {
- return keys[0].output;
- }
-
- this.updateCurveInfo_();
-
- var start_input = keys[0].input;
- var end_input = keys[keys_size-1].input;
- var input_span = end_input - start_input;
- var start_output = keys[0].output;
- var end_output = keys[keys_size-1].output;
- var output_delta = end_output - start_output;
-
- var kEpsilon = 0.00001;
-
- var output_offset = 0.0;
- // check for pre-infinity
- if (input < start_input) {
- if (input_span <= 0.0) {
- return start_output;
- }
- var pre_infinity_offset = start_input - input;
- switch (this.preInfinity) {
- case o3d.Curve.CONSTANT:
- return start_output;
- case o3d.Curve.LINEAR: {
- var second_key = keys[1];
- var input_delta = second_key.input - start_input;
- if (input_delta > kEpsilon) {
- return start_output - pre_infinity_offset *
- (second_key.output - start_output) / input_delta;
- } else {
- return start_output;
- }
- }
- case o3d.Curve.CYCLE: {
- var cycle_count = Math.ceil(pre_infinity_offset / input_span);
- input += cycle_count * input_span;
- input = start_input + (input - start_input) % input_span;
- break;
- }
- case o3d.Curve.CYCLE_RELATIVE: {
- var cycle_count = Math.ceil(pre_infinity_offset / input_span);
- input += cycle_count * input_span;
- input = start_input + (input - start_input) % input_span;
- output_offset -= cycle_count * output_delta;
- break;
- }
- case o3d.Curve.OSCILLATE: {
- var cycle_count = Math.ceil(pre_infinity_offset / (2.0 * input_span));
- input += cycle_count * 2.0 * input_span;
- input = end_input - Math.abs(input - end_input);
- break;
- }
- default:
- this.gl.client.error_callback(
- "Curve: invalid value "+this.preInfinity+"for pre-infinity");
- return start_output;
- }
- } else if (input >= end_input) {
- // check for post-infinity
- if (input_span <= 0.0) {
- return end_output;
- }
- var post_infinity_offset = input - end_input;
- switch (this.postInfinity) {
- case o3d.Curve.CONSTANT:
- return end_output;
- case o3d.Curve.LINEAR: {
- var next_to_last_key = keys[keys_size - 2];
- var input_delta = end_input - next_to_last_key.input;
- if (input_delta > kEpsilon) {
- return end_output + post_infinity_offset *
- (end_output - next_to_last_key.output) /
- input_delta;
- } else {
- return end_output;
- }
- }
- case o3d.Curve.CYCLE: {
- var cycle_count = Math.ceil(post_infinity_offset / input_span);
- input -= cycle_count * input_span;
- input = start_input + (input - start_input) % input_span;
- break;
- }
- case o3d.Curve.CYCLE_RELATIVE: {
- var cycle_count = Math.floor((input - start_input) / input_span);
- input -= cycle_count * input_span;
- input = start_input + (input - start_input) % input_span;
- output_offset += cycle_count * output_delta;
- break;
- }
- case o3d.Curve.OSCILLATE: {
- var cycle_count = Math.ceil(post_infinity_offset / (2.0 *
- input_span));
- input -= cycle_count * 2.0 * input_span;
- input = start_input + Math.abs(input - start_input);
- break;
- }
- default:
- this.gl.client.error_callback(
- "Curve.invalid value "+this.postInfinity+"for post-infinity");
- return end_output;
- }
- }
-
- // At this point input should be between start_input and end_input
- // inclusive.
-
- // If we are at end_input then just return end_output since we can't
- // interpolate end_input to anything past it.
- if (input >= end_input) {
- return end_output + output_offset;
- }
-
- // TODO(pathorn): Implement curve cache in javascript.
- // See 'void Curve::CreateCache' in o3d/core/cross/curve.cc
-
- return this.getOutputInSpan_(input, context) + output_offset;
-};
diff --git a/o3d/samples/o3d-webgl/draw_context.js b/o3d/samples/o3d-webgl/draw_context.js
deleted file mode 100644
index dde73e8..0000000
--- a/o3d/samples/o3d-webgl/draw_context.js
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * The DrawContext defines the parameters used for a particular drawing pass.
- * It contains two 4-by-4 matrix params, view and
- * projection. These correspond to the viewing and projection transformation
- * matrices.
- *
- * @param {!o3d.Matrix4} opt_view The view matrix for this DrawContext.
- * @param {!o3d.Matrix4} opt_projection The projection matrix
- * for this DrawContext.
- * @constructor
- */
-o3d.DrawContext = function(opt_view, opt_projection) {
- o3d.ParamObject.call(this);
-
- /**
- * The view matrix represents the viewing transformation, used to
- * take vertices from world space to view space.
- * @type {o3d.Matrix4}
- */
- this.view = opt_view || o3d.Transform.makeIdentityMatrix4_();
-
- /**
- * The projection matrix represents the projection transformation,
- * used to take vertices from view space to screen space. This
- * matrix is usually an orthographic or perspective transformation.
- * @type {o3d.Matrix4}
- */
- this.projection = opt_projection || o3d.Transform.makeIdentityMatrix4_();
-};
-o3d.inherit('DrawContext', 'ParamObject');
-
-o3d.ParamObject.setUpO3DParam_(o3d.DrawContext, 'view', 'ParamMatrix4');
-o3d.ParamObject.setUpO3DParam_(o3d.DrawContext, 'projection', 'ParamMatrix4');
-
diff --git a/o3d/samples/o3d-webgl/draw_element.js b/o3d/samples/o3d-webgl/draw_element.js
deleted file mode 100644
index cb4ac48..0000000
--- a/o3d/samples/o3d-webgl/draw_element.js
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A DrawElement causes an Element to be Drawn with a particular material.
- * You can override other Effect parameters by adding corresponding params to
- * the DrawElement.
- *
- * @param {!o3d.Material} opt_material The material used to render this element.
- * @constructor
- */
-o3d.DrawElement = function(opt_material) {
- o3d.ParamObject.call(this);
-
- /**
- * The Material for this DrawElement. If it is null the material of
- * owner will be used.
- * @type {o3d.Material}
- */
- this.material = opt_material || null;
-
- /**
- * The current owner of this Draw Element. Set to null to stop being owned.
- *
- * Note: DrawElements are referenced by the Pack they are created in
- * and their owner. If the DrawElement is removed from its Pack then
- * setting the owner to null will free the DrawElement. Or, visa
- * versa, if you set the DrawElement's owner to null then removing
- * it from its Pack will free the DrawElement.
- * @type {o3d.Element}
- */
- this.owner_ = null;
-};
-o3d.inherit('DrawElement', 'ParamObject');
-
-o3d.ParamObject.setUpO3DParam_(o3d.DrawElement, 'material', 'ParamMaterial');
-
diff --git a/o3d/samples/o3d-webgl/draw_list.js b/o3d/samples/o3d-webgl/draw_list.js
deleted file mode 100644
index 33cc7fd..0000000
--- a/o3d/samples/o3d-webgl/draw_list.js
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A DrawList gets used during rendering to collect DrawElements to
- * render. Each Material references a DrawList. Depending on the material, as
- * DrawElements get collected they will be put on different DrawLists.
- * @constructor
- */
-o3d.DrawList = function() {
- o3d.NamedObject.call(this);
- this.list_ = [];
-};
-o3d.inherit('DrawList', 'NamedObject');
-
-/**
- * Private list to actually hold the DrawElements
- * @type {!Array.<!Object>}
- */
-this.list_ = [];
-
-
-/**
- * @type {number}
- */
-o3d.DrawList.SortMethod = goog.typedef;
-
-
-/**
- * SortMethod,
- * BY_PERFORMANCE
- * BY_Z_ORDER
- * BY_PRIORITY
- *
- * Method to sort DrawList by.
- */
-o3d.DrawList.BY_PERFORMANCE = 0;
-o3d.DrawList.BY_Z_ORDER = 1;
-o3d.DrawList.BY_PRIORITY = 2;
-
-
-/**
- * Compare function for by-priority sort.
- */
-o3d.DrawList.comparePriority_ = function(drawElementInfoA, drawElementInfoB) {
- return drawElementInfoA.drawElement.owner.priority -
- drawElementInfoB.drawElement.owner.priority;
-};
-
-
-/**
- * Compare function for by-z-coordinate sort.
- * @param {!o3d.DrawElement} drawElementInfoA
- * @param {!o3d.DrawElement} drawElementInfoB
- */
-o3d.DrawList.compareZ_ = function(drawElementInfoA, drawElementInfoB) {
- return o3d.Transform.transformPointZOnly_(
- drawElementInfoB.worldViewProjection,
- drawElementInfoB.drawElement.owner.zSortPoint) -
- o3d.Transform.transformPointZOnly_(
- drawElementInfoA.worldViewProjection,
- drawElementInfoA.drawElement.owner.zSortPoint);
-};
-
-
-/**
- * Sorts this list according to the given sort method.
- * @param {o3d.DrawList.SortMethod} sort_method Which method to use.
- * @private
- */
-o3d.DrawList.prototype.sort_ = function(sort_method) {
- switch (sort_method) {
- case o3d.DrawList.BY_PRIORITY:
- this.list_.sort(o3d.DrawList.comparePriority_);
- break;
-
- case o3d.DrawList.BY_Z_ORDER:
- this.list_.sort(o3d.DrawList.compareZ_);
- break;
-
- case o3d.DrawList.BY_PERFORMANCE:
- default:
- break;
- }
-};
-
-
-/**
- * Renders the draw list.
- */
-o3d.DrawList.prototype.render = function() {
- for (var i = 0; i < this.list_.length; ++i) {
- var drawElementInfo = this.list_[i];
- var world = drawElementInfo.world;
- var view = drawElementInfo.view;
- var viewProjection = drawElementInfo.viewProjection;
- var worldViewProjection = drawElementInfo.worldViewProjection;
- var projection = drawElementInfo.projection;
- var transform = drawElementInfo.transform;
- var drawElement = drawElementInfo.drawElement;
- var element = drawElement.owner;
- var material = drawElement.material || element.material;
- var effect = material.effect;
-
- o3d.Param.SAS.setWorld(world);
- o3d.Param.SAS.setView(view);
- o3d.Param.SAS.setProjection(projection);
- o3d.Param.SAS.setViewProjection(viewProjection);
- o3d.Param.SAS.setWorldViewProjection(worldViewProjection);
-
- var paramObjects = [
- transform,
- drawElement,
- element
- ];
- if (element.streamBank) {
- paramObjects.push(element.streamBank);
- }
- paramObjects.push(
- material,
- effect,
- o3d.Param.SAS);
-
- effect.searchForParams_(paramObjects);
-
- var state_on = (material.state != undefined);
- if (state_on) {
- material.state.push_();
- }
- element.render();
- if (state_on) {
- material.state.pop_();
- }
- }
-};
-
-
diff --git a/o3d/samples/o3d-webgl/draw_pass.js b/o3d/samples/o3d-webgl/draw_pass.js
deleted file mode 100644
index c02601b..0000000
--- a/o3d/samples/o3d-webgl/draw_pass.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A DrawPass renders a DrawList.
- *
- * @param {o3d.DrawList} drawList The DrawList used by this DrawPass.
- * @param {o3d.DrawPass.SortMethod} sortMethod ParamInteger The method
- * of sorting this DrawPass.
- * @constructor
- */
-o3d.DrawPass = function(opt_drawList, opt_sortMethod) {
- o3d.RenderNode.call(this);
-
- /**
- * The DrawList for this DrawPass.
- * @type {o3d.DrawList}
- */
- this.drawList = opt_drawList || null;
-
- /**
- * The sort method for this DrawPass to draw the DrawList by.
- * Default = BY_PERFORMANCE.
- * @type {o3d.DrawList.SortMethod}
- */
- this.sortMethod = opt_sortMethod || o3d.DrawList.BY_PERFORMANCE;
-};
-o3d.inherit('DrawPass', 'RenderNode');
-
-/**
- * @type {number}
- */
-o3d.DrawPass.SortMethod = goog.typedef;
-
-o3d.ParamObject.setUpO3DParam_(o3d.DrawPass, 'drawList', 'ParamDrawList');
-o3d.ParamObject.setUpO3DParam_(o3d.DrawPass, 'sortMethod', 'ParamInteger');
-
-/**
- * Called in rendergraph traversal before children are rendered.
- */
-o3d.DrawPass.prototype.before = function() {
- if (this.drawList) {
- this.drawList.sort_(this.sortMethod);
- this.drawList.render();
- }
-};
-
-
diff --git a/o3d/samples/o3d-webgl/effect.js b/o3d/samples/o3d-webgl/effect.js
deleted file mode 100644
index 7427670..0000000
--- a/o3d/samples/o3d-webgl/effect.js
+++ /dev/null
@@ -1,646 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * EffectParameterInfo holds information about the Parameters an Effect needs.
- * o3d.Effect.getParameterInfo
- * @param {string} name Tne name of the parameter.
- * @param {string} className The param class name.
- * @param {number} numElements The number of Elements if the param is an array.
- * @param {string} sasClassName The sas class name if the param is an sas type.
- * @param {string} semantic The relevant semantic.
- */
-o3d.EffectParameterInfo =
- function(name, className, numElements, semantic, sasClassName) {
- /**
- * The name of the parameter.
- * @type {string}
- */
- this.name = name || '';
-
- /**
- * The type of the parameter.
- * @type {string}
- */
- this.className = className || '';
-
- /**
- * The number of elements. Non-zero for array types, zero for non-array
- * types.
- * @type {number}
- */
- this.numElements = numElements || 0;
-
- /**
- * The semantic of the parameter. This is always in UPPERCASE.
- * @type {string}
- */
- this.semantic = semantic || '';
-
- /**
- * If this is a standard parameter (SAS) this will be the name of the type
- * of Param needed. Otherwise it will be the empty string.
- *
- * Standard Parameters are generally handled automatically by o3d but you
- * can supply your own if you have a unique situation.
- *
- * @type {string}
- */
- this.sasClassName = sasClassName || '';
-};
-o3d.inherit('EffectParameterInfo', 'NamedObject');
-
-
-/**
- * EffectStreamInfo holds information about the Streams an Effect needs.
- * @param {o3d.Stream.Semantic} opt_semantic The semantic of the stream
- * @param {number} opt_semantic_index
- * @constructor
- */
-o3d.EffectStreamInfo = function(opt_semantic, opt_semantic_index) {
- o3d.NamedObject.call(this);
- if (!opt_semantic) {
- opt_semantic = o3d.Stream.UNKNOWN_SEMANTIC;
- }
- if (!opt_semantic_index) {
- opt_semantic_index = 0;
- }
- this.semantic = opt_semantic;
- this.opt_semantic_index = opt_semantic_index;
-};
-o3d.inherit('EffectStreamInfo', 'NamedObject');
-
-
-/**
- * The semantic of the stream.
- * @type {!o3d.Stream.Semantic}
- */
-o3d.EffectStreamInfo.prototype.semantic = o3d.Stream.UNKNOWN_SEMANTIC;
-
-
-
-/**
- * The semantic index of the stream.
- * @type {number}
- */
-o3d.EffectStreamInfo.prototype.semanticIndex = 0;
-
-
-/**
- * An Effect contains a vertex and pixel shader.
- * @constructor
- */
-o3d.Effect = function() {
- o3d.ParamObject.call(this);
- this.program_ = null;
- this.uniforms_ = {};
- this.attributes_ = {};
-};
-o3d.inherit('Effect', 'ParamObject');
-
-o3d.Effect.HELPER_CONSTANT_NAME = 'dx_clipping';
-
-
-/**
- * An object mapping the names of uniform variables to objects containing
- * information about the variable.
- * @type {Object}
- * @private
- */
-o3d.Effect.prototype.uniforms_ = {};
-
-
-/**
- * An object mapping the names of attributes to objects containing
- * information about the attribute.
- * @type {Object}
- * @private
- */
-o3d.Effect.prototype.attributes_ = {};
-
-
-/**
- * Indicates whether the vertex shader has been loaded, so we can
- * postpone linking until both shaders are in.
- *
- * @type {boolean}
- */
-o3d.Effect.prototype.vertexShaderLoaded_ = false;
-
-
-/**
- * Indicates whether the fragment shader has been loaded, so we can
- * postpone linking until both shaders are in.
- *
- * @type {boolean}
- */
-o3d.Effect.prototype.fragmentShaderLoaded_ = false;
-
-
-/**
- * Binds standard attribute locations for the shader.
- */
-o3d.Effect.prototype.bindAttributesAndLinkIfReady = function() {
- if (this.vertexShaderLoaded_ && this.fragmentShaderLoaded_) {
- var semanticMap = o3d.Effect.semanticMap_;
- for (var name in semanticMap) {
- this.gl.bindAttribLocation(
- this.program_, semanticMap[name].gl_index, name);
- }
- this.gl.linkProgram(this.program_);
- if (!this.gl.getProgramParameter(this.program_, this.gl.LINK_STATUS)) {
- var log = this.gl.getShaderInfoLog(this.program_);
- this.gl.client.error_callback(
- 'Program link failed with error log:\n' + log);
- }
- this.getUniforms_();
- this.getAttributes_();
- }
-};
-
-
-/**
- * Helper function for loadVertexShaderFromString and
- * loadPixelShaderFromString that takes the type as an argument.
- * @param {string} shaderString The shader code.
- * @param {number} type The type of the shader: either
- * VERTEX_SHADER or FRAGMENT_SHADER.
- * @return {bool} Success.
- */
-o3d.Effect.prototype.loadShaderFromString = function(shaderString, type) {
- if (!this.program_) {
- this.program_ = this.gl.createProgram();
- }
-
- var success = true;
-
- var shader = this.gl.createShader(type);
- this.gl.shaderSource(
- shader, "#ifdef GL_ES\nprecision highp float;\n#endif\n" + shaderString);
- this.gl.compileShader(shader);
- if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) {
- success = false;
- var log = this.gl.getShaderInfoLog(shader);
- this.gl.client.error_callback(
- 'Shader compile failed with error log:\n' + log);
- }
-
- this.gl.attachShader(this.program_, shader);
-
- return success;
-};
-
-
-/**
- * Loads a glsl vertex shader for this effect from a string.
- * @param {string} shaderString The string.
- * @return {bool} Success.
- */
-o3d.Effect.prototype.loadVertexShaderFromString =
- function(shaderString) {
- var success =
- this.loadShaderFromString(shaderString, this.gl.VERTEX_SHADER);
- this.vertexShaderLoaded_ = success;
- o3d.Effect.prototype.bindAttributesAndLinkIfReady();
- return success;
-};
-
-
-/**
- * Loads a glsl vertex shader for this effect from a string.
- * @param {string} shaderString The string.
- * @return {bool} Success.
- */
-o3d.Effect.prototype.loadPixelShaderFromString =
- function(shaderString) {
- var success =
- this.loadShaderFromString(shaderString, this.gl.FRAGMENT_SHADER);
- this.fragmentShaderLoaded_ = success;
- this.bindAttributesAndLinkIfReady();
- return success;
-};
-
-
-/**
- * Loads a glsl vertex shader and pixel shader from one string.
- * Assumes the vertex shader and pixel shader are separated by
- * the text '// #o3d SplitMarker'.
- * @param {string} shaderString The string.
- * @return {bool} Success.
- */
-o3d.Effect.prototype.loadFromFXString =
- function(shaderString) {
- var splitIndex = shaderString.indexOf('// #o3d SplitMarker');
- return this.loadVertexShaderFromString(shaderString.substr(0, splitIndex)) &&
- this.loadPixelShaderFromString(shaderString.substr(splitIndex));
-};
-
-
-/**
- * Generates an array of indexed strings. For example, given 'arr' and a size
- * of 10, generates 'arr[0]', 'arr[1]', 'arr[2]' up to 'arr[9]'.
- *
- * @param {string} base The name of the array.
- * @param {number} size The number of elements in the array.
- * @return {!Array.<string>}
- * @private
- */
-o3d.Effect.prototype.getParamArrayNames_ = function(base, size) {
- var names = [];
- for (var i = 0; i < size; i++) {
- names[i] = base + '[' + i + ']';
- }
- return names;
-}
-
-
-/**
- * Iterates through the active uniforms of the program and gets the
- * location of each one and stores them by name in the uniforms
- * object.
- * @private
- */
-o3d.Effect.prototype.getUniforms_ =
- function() {
- this.uniforms_ = {};
- var numUniforms = this.gl.getProgramParameter(
- this.program_, this.gl.ACTIVE_UNIFORMS);
- for (var i = 0; i < numUniforms; ++i) {
- var info = this.gl.getActiveUniform(this.program_, i);
- var name = info.name;
- if (name.indexOf('[') != -1) {
- // This is an array param and we need to individually query each item in
- // the array to get its location.
- var baseName = info.name.substring(0, info.name.indexOf('['));
- var names = this.getParamArrayNames_(baseName, info.size);
- var locations = [];
- for (var j = 0; j < names.length; j++) {
- locations[j] = this.gl.getUniformLocation(this.program_, names[j]);
- }
- this.uniforms_[baseName] = {
- info: {name: baseName, size: info.size, type: info.type},
- kind: o3d.Effect.ARRAY,
- locations: locations /* mind the s */
- };
- } else {
- // Not an array param.
- this.uniforms_[name] = {
- info: info,
- kind: o3d.Effect.ELEMENT,
- location: this.gl.getUniformLocation(this.program_, name)
- };
- }
- }
-};
-
-
-/**
- * Iterates through the active attributes of the program and gets the
- * location of each one and stores them by name in the attributes
- * object.
- * @private
- */
-o3d.Effect.prototype.getAttributes_ =
- function() {
- this.attributes_ = {};
- var numAttributes = this.gl.getProgramParameter(
- this.program_, this.gl.ACTIVE_ATTRIBUTES);
- for (var i = 0; i < numAttributes; ++i) {
- var info = this.gl.getActiveAttrib(this.program_, i);
- this.attributes_[info.name] = {info:info,
- location:this.gl.getAttribLocation(this.program_, info.name)};
- }
-};
-
-
-/**
- * A map linking the WebGL type of a uniform to the appropriate param type.
- * This gets memoized in the function createUniformParameters.
- * @private
- */
-o3d.Effect.paramTypes_ = null;
-
-/**
- * Accesses the paramTypes map, builds it if it isn't already built.
- * @private;
- */
-o3d.Effect.getParamTypes_ = function(gl) {
- // Even though these constants should be the same for different webgl
- // contexts, we can't create this table until the context is loaded, so
- // we initialize it here rather than when the file loads.
- if (!o3d.Effect.paramTypes_) {
- o3d.Effect.paramTypes_ = {};
- o3d.Effect.paramTypes_[gl.FLOAT] = 'ParamFloat';
- o3d.Effect.paramTypes_[gl.FLOAT_VEC2] = 'ParamFloat2';
- o3d.Effect.paramTypes_[gl.FLOAT_VEC3] = 'ParamFloat3';
- o3d.Effect.paramTypes_[gl.FLOAT_VEC4] = 'ParamFloat4';
- o3d.Effect.paramTypes_[gl.INT] = 'ParamInteger';
- o3d.Effect.paramTypes_[gl.BOOL] = 'ParamBoolean';
- o3d.Effect.paramTypes_[gl.FLOAT_MAT4] = 'ParamMatrix4';
- o3d.Effect.paramTypes_[gl.SAMPLER_2D] = 'ParamSampler';
- o3d.Effect.paramTypes_[gl.SAMPLER_CUBE] = 'ParamSampler';
- }
-
- return o3d.Effect.paramTypes_;
-}
-
-
-/**
- * A map linking names of certain attributes in the shader to the corresponding
- * semantic and semantic index.
- * @private
- */
-o3d.Effect.semanticMap_ = {
- 'position': {semantic: o3d.Stream.POSITION, index: 0, gl_index: 0},
- 'normal': {semantic: o3d.Stream.NORMAL, index: 0, gl_index: 1},
- 'tangent': {semantic: o3d.Stream.TANGENT, index: 0, gl_index: 2},
- 'binormal': {semantic: o3d.Stream.BINORMAL, index: 0, gl_index: 3},
- 'color': {semantic: o3d.Stream.COLOR, index: 0, gl_index: 4},
- 'texCoord0': {semantic: o3d.Stream.TEXCOORD, index: 0, gl_index: 5},
- 'texCoord1': {semantic: o3d.Stream.TEXCOORD, index: 1, gl_index: 6},
- 'texCoord2': {semantic: o3d.Stream.TEXCOORD, index: 2, gl_index: 7},
- 'texCoord3': {semantic: o3d.Stream.TEXCOORD, index: 3, gl_index: 8},
- 'texCoord4': {semantic: o3d.Stream.TEXCOORD, index: 4, gl_index: 9},
- 'texCoord5': {semantic: o3d.Stream.TEXCOORD, index: 5, gl_index: 10},
- 'texCoord6': {semantic: o3d.Stream.TEXCOORD, index: 6, gl_index: 11},
- 'texCoord7': {semantic: o3d.Stream.TEXCOORD, index: 7, gl_index: 12},
- 'influenceWeights': {semantic: o3d.Stream.INFLUENCE_WEIGHTS, index: 0,
- gl_index: 13},
- 'influenceIndices': {semantic: o3d.Stream.INFLUENCE_INDICES, index: 0,
- gl_index: 14}
-};
-
-o3d.Effect.reverseSemanticMap_ = [];
-(function(){
- var revmap = o3d.Effect.reverseSemanticMap_;
- for (var key in o3d.Effect.semanticMap_) {
- var value = o3d.Effect.semanticMap_[key];
- revmap[value.semantic] = revmap[value.semantic] || [];
- revmap[value.semantic][value.index] = value.gl_index;
- }
-})();
-
-
-/**
- * For each of the effect's uniform parameters, creates corresponding
- * parameters on the given ParamObject. Skips SAS Parameters.
- *
- * If a Param with the same name but the wrong type already exists on the
- * given ParamObject createUniformParameters will attempt to replace it with
- * one of the correct type.
- *
- * Note: The most common thing to pass to this function is a Material but
- * depending on your application it may be more appropriate to pass in a
- * Transform, Effect, Element or DrawElement.
- *
- * @param {!o3d.ParamObject} param_object The param object on which the
- * new paramters will be created.
- */
-o3d.Effect.prototype.createUniformParameters =
- function(param_object) {
- var sasTypes = o3d.Param.sasTypes_;
- var paramTypes = o3d.Effect.getParamTypes_(this.gl);
- for (var name in this.uniforms_) {
- var uniformData = this.uniforms_[name];
- if (!sasTypes[name]) {
- switch (uniformData.kind) {
- case o3d.Effect.ARRAY:
- var param = param_object.createParam(name, 'ParamParamArray');
- var array = new o3d.ParamArray;
- array.gl = this.gl;
- array.resize(uniformData.info.size,
- paramTypes[uniformData.info.type]);
- param.value = array;
- break;
- case o3d.Effect.STRUCT:
- o3d.notImplemented();
- break;
- case o3d.Effect.ELEMENT:
- default:
- param_object.createParam(name, paramTypes[uniformData.info.type]);
- break;
- }
- }
- }
-};
-
-
-/**
- * For each of the effect's uniform parameters, if it is a SAS parameter
- * creates corresponding StandardParamMatrix4 parameters on the given
- * ParamObject. Note that SAS parameters are handled automatically by the
- * rendering system. so except in some rare cases there is no reason to call
- * this function. Also be aware that the StandardParamMatrix4 Paramters like
- * WorldViewProjectionParamMatrix4, etc.. are only valid during rendering.
- * At all other times they will not return valid values.
- *
- * If a Param with the same name but the wrong type already exists on the
- * given ParamObject CreateSASParameters will attempt to replace it with
- * one of the correct type.
- *
- * @param {!o3d.ParamObject} param_object The param object on which the new
- * paramters will be created.
- */
-o3d.Effect.prototype.createSASParameters =
- function(param_object) {
- var sasTypes = o3d.Param.sasTypes_;
- for (var name in this.uniforms_) {
- var info = this.uniforms_[name].info;
- var sasType = sasTypes[name];
- if (sasType) {
- param_object.createParam(info.name, sasType);
- }
- }
-};
-
-
-/**
- * Gets info about the parameters this effect needs.
- * @return {!Array.<!o3d.EffectParameterInfo>} an array of
- * EffectParameterInfo objects.
- */
-o3d.Effect.prototype.getParameterInfo = function() {
- var infoArray = [];
- var sasTypes = o3d.Param.sasTypes_;
- var semanticMap = o3d.Effect.semanticMap_;
- var paramTypes = o3d.Effect.getParamTypes_(this.gl);
-
- for (var name in this.uniforms_) {
- var uniformData = this.uniforms_[name];
- var sasClassName = sasTypes[name] || '';
- var dataType = paramTypes[uniformData.info.type] || '';
- var numElements = (uniformData.kind == o3d.Effect.ARRAY) ?
- uniformData.info.size : 0; // 0 if a non-array type.
- var semantic = semanticMap[name] ? name : '';
- infoArray.push(new o3d.EffectParameterInfo(
- name, dataType, numElements, semantic.toUpperCase(), sasClassName));
- }
-
- return infoArray;
-};
-
-
-/**
- * Gets info about the streams this effect needs.
- * @return {!Array.<!o3d.EffectStreamInfo>} an array of
- * EffectStreamInfo objects.
- */
-o3d.Effect.prototype.getStreamInfo = function() {
- var infoList = [];
-
- for (var name in this.attributes_) {
- var semantic_index_pair = o3d.Effect.semanticMap_[name];
- infoList.push(new o3d.EffectStreamInfo(
- semantic_index_pair.semantic, semantic_index_pair.index));
- }
- return infoList;
-};
-
-
-/**
- * Searches the objects in the given list for parameters to apply to the
- * uniforms defined on this effects program, and applies them, favoring
- * the objects nearer the beginning of the list.
- *
- * @param {!Array.<!o3d.ParamObject>} object_list The param objects to search.
- * @private
- */
-o3d.Effect.prototype.searchForParams_ = function(object_list) {
- var unfilledMap = {};
- for (var uniformName in this.uniforms_) {
- unfilledMap[uniformName] = true;
- }
- this.gl.useProgram(this.program_);
- o3d.Param.texture_index_ = 0;
- var object_list_length = object_list.length;
- for (var i = 0; i < object_list_length; ++i) {
- var obj = object_list[i];
- for (var name in this.uniforms_) {
- if (unfilledMap[name]) {
- var uniformInfo = this.uniforms_[name];
- var param = obj.getParam(name);
- if (param) {
- if (uniformInfo.kind == o3d.Effect.ARRAY) {
- param.applyToLocations(this.gl, uniformInfo.locations);
- } else {
- param.applyToLocation(this.gl, uniformInfo.location);
- }
- delete unfilledMap[name];
- }
- }
- }
- }
-
- this.updateHelperConstants_(this.gl.displayInfo.width,
- this.gl.displayInfo.height);
- delete unfilledMap[o3d.Effect.HELPER_CONSTANT_NAME];
- for (var name in unfilledMap) {
- if (this.uniforms_[name].info.type == this.gl.SAMPLER_2D) {
- if (this.gl.client.reportErrors_()) {
- this.gl.client.error_callback("Missing ParamSampler");
- }
- var defaultParamSampler = o3d.ParamSampler.defaultParamSampler_;
- defaultParamSampler.gl = this.gl;
- defaultParamSampler.applyToLocation(this.gl,
- this.uniforms_[name].location);
- } else {
- throw ('Uniform param not filled: "'+ name + '"');
- }
- }
-};
-
-
-/**
- * Updates certain parameters used to make the GLSL shaders have the
- * same clipping semantics as D3D's.
- * @param {number} width width of the viewport in pixels
- * @param {number} height height of the viewport in pixels
- * @private
- */
-o3d.Effect.prototype.updateHelperConstants_ = function(width, height) {
- var uniformInfo = this.uniforms_[o3d.Effect.HELPER_CONSTANT_NAME];
- var dx_clipping = [ 0.0, 0.0, 0.0, 0.0 ];
- if (uniformInfo) {
- // currentRenderSurfaceSet is set in render_surface_set.js.
- dx_clipping[0] = 1.0 / width;
- dx_clipping[1] = -1.0 / height;
- dx_clipping[2] = 2.0;
- if (this.gl.currentRenderSurfaceSet) {
- dx_clipping[3] = -1.0;
- } else {
- dx_clipping[3] = 1.0;
- }
-
- this.gl.uniform4f(uniformInfo.location,
- dx_clipping[0], dx_clipping[1],
- dx_clipping[2], dx_clipping[3]);
- }
-};
-
-/**
- * @type {number}
- */
-o3d.Effect.MatrixLoadOrder = goog.typedef;
-
-/**
- * MatrixLoadOrder,
- * ROW_MAJOR, Matrix parameters are loaded in row-major order (DX-style).
- * COLUMN_MAJOR, Matrix parameters are loaded in column-major order
- * (OpenGL-style).
- */
-o3d.Effect.ROW_MAJOR = 0;
-o3d.Effect.COLUMN_MAJOR = 1;
-
-
-/**
- * UniformType,
- * ELEMENT, the param is a single gl.* element
- * ARRAY, the param is an array of same-typed elements
- * STRUCT, not implemented
- */
-o3d.Effect.ELEMENT = 0;
-o3d.Effect.ARRAY = 1;
-o3d.Effect.STRUCT = 2;
-
-
-/**
- * The order in which matrix data is loaded to the GPU.
- * @type {o3d.Effect.MatrixLoadOrder}
- */
-o3d.Effect.prototype.matrix_load_order_ = o3d.Effect.ROW_MAJOR;
-
-
-/**
- * The source for the shaders on this Effect.
- * @type {string}
- */
-o3d.Effect.prototype.source_ = '';
diff --git a/o3d/samples/o3d-webgl/element.js b/o3d/samples/o3d-webgl/element.js
deleted file mode 100644
index bf9c6c9..0000000
--- a/o3d/samples/o3d-webgl/element.js
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * An Element manages DrawElements for classes inherited from Element.
- *
- * @param {!o3d.Material} opt_material The Material used by this Element.
- * @param {!o3d.BoundingBox} opt_boundingBox The BoundingBox used by this
- * Element for culling.
- * @param {!o3d.Point3} opt_zSortPoint The point to sort by when rendering
- * this Element in a z ordered DrawPass.
- * @param {boolean} opt_cull Whether or not to attempt to cull this
- * Element based on whether or not its bounding box is in the view
- * frustum.
- * @constructor
- */
-o3d.Element =
- function(opt_material, opt_boundingBox, opt_zSortPoint, opt_cull) {
- o3d.ParamObject.call(this);
-
- /**
- * The Material for this element.
- * @type {o3d.Material}
- */
- this.material = opt_material;
-
- /**
- * The BoundingBox for this element. If culling is on this bounding
- * box will be tested against the view frustum of any draw context
- * used to render this Element.
- * @type {o3d.BoundingBox}
- */
- this.boundingBox = opt_boundingBox ||
- new o3d.BoundingBox([-1, -1, -1], [1, 1, 1]);
-
- /**
- * The z sort point for this element. If this Element is drawn by a DrawPass
- * that is set to sort by z order this value will be multiplied by the
- * worldViewProjection matrix to compute a z value to sort by.
- * @type {o3d.Point3}
- */
- this.zSortPoint = opt_zSortPoint || [0, 0, 0];
-
- /**
- * The priority for this element. Used to sort if this Element is drawn by a
- * DrawPass that is set to sort by priority.
- * @type {number}
- */
- this.priority = 0;
-
- /**
- * The cull settings for this element. If true this Element will be
- * culled by the bounding box above compared to the view frustum it
- * is being rendered with.
- *
- * @type {boolean}
- */
- this.cull = opt_cull || false;
-
- /**
- * The current owner of this Draw Element. Pass in null to stop
- * being owned.
- *
- * Note: Elements are referenced by the Pack they are created in and
- * their owner. If the Element is removed from its Pack, then
- * setting the owner to null will free the Element. Or, visa versa,
- * if you set the Element's owner to null then removing it from its
- * Pack will free the Element.
- *
- * @type {o3d.Element}
- */
- this.owner_ = null;
-
- /**
- * Gets all the DrawElements under this Element.
- *
- * Each access to this field gets the entire list so it is best to get it
- * just once. For example:
- *
- * var drawElements = element.drawElements;
- * for (var i = 0; i < drawElements.length; i++) {
- * var drawElement = drawElements[i];
- * }
- *
- *
- * Note that modifications to this array [e.g. push()] will not affect
- * the underlying Element, while modifications to the members of the array.
- * will affect them.
- *
- * @type {!Array.<!o3d.DrawElement>}
- */
- this.drawElements = [];
-};
-o3d.inherit('Element', 'ParamObject');
-
-o3d.ParamObject.setUpO3DParam_(o3d.Element, 'material', 'ParamMaterial');
-o3d.ParamObject.setUpO3DParam_(o3d.Element, 'boundingBox', 'ParamBoundingBox');
-o3d.ParamObject.setUpO3DParam_(o3d.Element, 'zSortPoint', 'ParamFloat3');
-o3d.ParamObject.setUpO3DParam_(o3d.Element, 'priority', 'ParamFloat');
-o3d.ParamObject.setUpO3DParam_(o3d.Element, 'cull', 'ParamBoolean');
-
-o3d.Element.prototype.__defineSetter__('owner',
- function(o) {
- this.owner_ = o;
- o.addElement(this);
- }
-);
-
-o3d.Element.prototype.__defineGetter__('owner',
- function() {
- return this.owner_;
- }
-);
-
-/**
- * Creates a DrawElement for this Element. Note that unlike
- * Shape.createDrawElements and Transform.createDrawElements this one will
- * create more than one element for the same material.
- *
- * @param {!o3d.Pack} pack pack used to manage created DrawElement.
- * @param {!o3d.Material} material material to use for DrawElement.
- * Note: When a DrawElement with a material of null is rendered, the
- * material on the corresponding Element will get used instead.
- * This allows you to easily setup the default (just draw as is) by passing
- * null or setup a shadow pass by passing in a shadow material.
- * @return {!o3d.DrawElement} The created draw element.
- */
-o3d.Element.prototype.createDrawElement =
- function(pack, material) {
- drawElement = pack.createObject('DrawElement');
- drawElement.owner = this;
- drawElement.material = material;
- this.drawElements.push(drawElement);
- return drawElement;
-};
-
-
-/**
- * Computes the intersection of a ray in the same coordinate system as
- * the specified POSITION stream.
- * @param {number} position_stream_index Index of POSITION stream.
- * @param {o3d.Cull} cull which side of the triangles to ignore.
- * @param {!o3d.math.Point3} start position of start of ray in local space.
- * @param {!o3d.math.Point3} end position of end of ray. in local space.
- * @return {!o3d.RayIntersectionInfo} RayIntersectionInfo class. If valid()
- * is false then something was wrong, Check GetLastError(). If
- * intersected() is true then the ray intersected a something. position()
- * is the exact point of intersection.
- */
-o3d.Element.prototype.intersectRay =
- function(position_stream_index, cull, start, end) {
- o3d.notImplemented();
-};
-
-
-/**
- * Computes the bounding box in same coordinate system as the specified
- * POSITION stream.
- * @param {number} position_stream_index Index of POSITION stream.
- * @return {!o3d.BoundingBox} The boundingbox for this element in local space.
- */
-o3d.Element.prototype.getBoundingBox =
- function(position_stream_index) {
- return this.boundingBox;
-};
-
-
-/**
- * Virtual function that renders the element.
- */
-o3d.Element.prototype.render = function() { };
-
-
diff --git a/o3d/samples/o3d-webgl/event.js b/o3d/samples/o3d-webgl/event.js
deleted file mode 100644
index c928e23..0000000
--- a/o3d/samples/o3d-webgl/event.js
+++ /dev/null
@@ -1,266 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * An Event object contains information describing a JavaScript event; it's used
- * as an argument to event handlers triggered by the plugin.
- * @constructor
- */
-o3d.Event = function() {
- o3d.ObjectBase.call(this);
-};
-o3d.inherit('Event', 'ObjectBase');
-
-
-/**
- * @type {number}
- */
-o3d.Event.Type = goog.typedef;
-
-/**
- * String identifiers for JavaScript events.
- * type
- * invalid
- * click
- * dblclick
- * mousedown
- * mousemove
- * mouseup
- * wheel
- * keydown
- * keypress
- * keyup
- * resize
- */
-o3d.Event.TYPE_INVALID = 0;
-o3d.Event.TYPE_CLICK = 1;
-o3d.Event.TYPE_DBLCLICK = 2;
-o3d.Event.TYPE_MOUSEDOWN = 3;
-o3d.Event.TYPE_MOUSEMOVE = 4;
-o3d.Event.TYPE_MOUSEUP = 5;
-o3d.Event.TYPE_WHEEL = 6;
-o3d.Event.TYPE_KEYDOWN = 7;
-o3d.Event.TYPE_KEYPRESS = 8;
-o3d.Event.TYPE_KEYUP = 9;
-o3d.Event.TYPE_RESIZE = 10;
-
-/**
- * The type of event this object represents.
- * @type {o3d.Event.Type}
- */
-o3d.Event.prototype.type = o3d.Event.TYPE_INVALID;
-
-
-/**
- * @type {number}
- */
-o3d.Event.Button = goog.typedef;
-
-/**
- * Constants used to identify mouse buttons.
- */
-o3d.Event.BUTTON_LEFT = 0;
-o3d.Event.BUTTON_MIDDLE = 1;
-o3d.Event.BUTTON_RIGHT = 2;
-o3d.Event.BUTTON_4 = 3;
-o3d.Event.BUTTON_5 = 4;
-
-
-
-/**
- * Which mouse button caused the event, in the case of mousedown, mouseup,
- * click, and dblclick events. This uses the values in enum Button.
- */
-o3d.Event.prototype.button = o3d.Event.BUTTON_LEFT;
-
-
-
-/**
- * Whether the ctrl key was pressed at the time of the event.
- * @type {boolean}
- */
-o3d.Event.prototype.ctrl_key = false;
-
-
-
-/**
- * Whether the alt [option, on OSX] key was pressed at the time of the event.
- * @type {boolean}
- */
-o3d.Event.prototype.alt_key = false;
-
-
-
-/**
- * Whether the shift key was pressed at the time of the event.
- * @type {boolean}
- */
-o3d.Event.prototype.shift_key = false;
-
-
-
-/**
- * Whether the meta [command, on OSX] key was pressed at the time of the event.
- * @type {boolean}
- */
-o3d.Event.prototype.meta_key = false;
-
-
-
-/**
- * The key code of the key pressed or released.
- * @type {number}
- */
-o3d.Event.prototype.key_code = 0;
-
-
-
-/**
- * The character created by a keypress event.
- * @type {number}
- */
-o3d.Event.prototype.char_code = 0;
-
-
-
-/**
- * The x-coordinate in pixels from the left side of the plugin or fullscreen
- * display region.
- * @type {number}
- */
-o3d.Event.prototype.x = 0;
-
-
-
-/**
- * The y-coordinate in pixels from the top of the plugin or fullscreen
- * display region.
- * @type {number}
- */
-o3d.Event.prototype.y = 0;
-
-
-
-/**
- * The x-coordinate in pixels from the left side of the screen.
- * @type {number}
- */
-o3d.Event.prototype.screenX = 0;
-
-
-
-/**
- * The y-coordinate in pixels from the top of the screen.
- * @type {number}
- */
-o3d.Event.prototype.screenY = 0;
-
-
-
-/**
- * The horizontal scroll offset for wheel events, in arbitrary units.
- * Positive values mean right; negative mean left.
- * @type {number}
- */
-o3d.Event.prototype.deltaX = 0;
-
-
-
-/**
- * The vertical scroll offset for wheel events, in arbitrary units.
- * Positive values mean up or away from the user; negative mean down or toward
- * the user.
- * @type {number}
- */
-o3d.Event.prototype.deltaY = 0;
-
-
-
-/**
- * The width in pixels of the plugin or fullscreen display region as a result
- * of this event.
- * @type {number}
- */
-o3d.Event.prototype.width = 0;
-
-
-
-/**
- * The height in pixels of the plugin or fullscreen display region as a result
- * of this event.
- * @type {number}
- */
-o3d.Event.prototype.height = 0;
-
-
-
-/**
- * Whether we're currently displaying in fullscreen mode.
- * @type {boolean}
- */
-o3d.Event.prototype.fullscreen = false;
-
-
-
-/**
- * An Event that gets sent to the render callback.
- * @constructor
- */
-o3d.RenderEvent = function() {
- o3d.Event.call(this);
-};
-o3d.inherit('RenderEvent', 'Event');
-
-
-/**
- * Time in seconds since the last time the client rendered.
- * @type {number}
- */
-o3d.RenderEvent.prototype.elapsedTime = 0;
-
-
-/**
- * An Event that gets sent to the render callback.
- * @constructor
- */
-o3d.TickEvent = function() {
- o3d.Event.call(this);
-};
-o3d.inherit('RenderEvent', 'Event');
-
-
-/**
- * Time in seconds since the last time the client rendered.
- * @type {number}
- */
-o3d.TickEvent.prototype.elapsedTime = 0;
-
diff --git a/o3d/samples/o3d-webgl/field.js b/o3d/samples/o3d-webgl/field.js
deleted file mode 100644
index 9e29569..0000000
--- a/o3d/samples/o3d-webgl/field.js
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A Field is a base class that manages a set of components in a
- * Buffer of a specific type. Fields are managed by Buffers and can not be
- * directly created. When a Buffer is destroyed or if a Field is removed from a
- * Buffer the Field's buffer property will be set to null.
- * @constructor
- */
-o3d.Field = function() {
- o3d.NamedObject.call(this);
-};
-o3d.inherit('Field', 'NamedObject');
-
-/**
- * The number of components in this field.
- * @type {number}
- */
-o3d.Field.prototype.numComponents = 0;
-
-
-/**
- * The Buffer the field belongs to.
- * @type {o3d.Buffer}
- */
-o3d.Field.prototype.buffer = null;
-
-
-/**
- * The offset of this field in the Buffer.
- * @type {number}
- */
-o3d.Field.prototype.offset_ = 0;
-
-
-/**
- * The size of one element of this field.
- * @type {number}
- */
-o3d.Field.prototype.size = 0;
-
-
-/**
- * Sets the values of the data stored in the field.
- *
- * The buffer for the field must have already been created either through
- * buffer.set or through buffer.allocateElements.
- *
- * The number of values passed in must be a multiple of the number of
- * components needed for the field.
- *
- * @param {number} start_index index of first value to set.
- * @param {!Array.<number>} values Values to be stored in the buffer starting at
- * index.
- */
-o3d.Field.prototype.setAt =
- function(start_index, values) {
- this.buffer.lock();
- var l = values.length / this.numComponents;
- for (var i = 0; i < l; ++i) {
- for (var c = 0; c < this.numComponents; ++c) {
- this.buffer.array_[
- (start_index + i) * this.buffer.totalComponents + this.offset_ + c] =
- values[this.numComponents * i + c];
- }
- }
- this.buffer.unlock();
- return true;
-};
-
-
-/**
- * Gets the values stored in the field.
- *
- * @param {number} start_index index of the first value to get.
- * @param {number} num_elements number of elements to read from field.
- * @return {!Array.<number>} The values of the field.
- */
-o3d.Field.prototype.getAt =
- function(start_index, num_elements) {
- return this.buffer.getAtHelper_(start_index, num_elements, this.offset_,
- this.numComponents);
-};
-
-
-
-/**
- * A field that contains floating point numbers.
- * @constructor
- */
-o3d.FloatField = function() {
- o3d.Field.call(this);
-};
-o3d.inherit('FloatField', 'Field');
-
-/**
- * A field that contains unsigned integers.
- * @constructor
- */
-o3d.UInt32Field = function() {
- o3d.Field.call(this);
-};
-o3d.inherit('UInt32Field', 'Field');
-
-/**
- * A field that contains unsigned bytes.
- * @constructor
- */
-o3d.UByteNField = function() {
- o3d.Field.call(this);
-};
-o3d.inherit('UByteNField', 'Field');
-
-
diff --git a/o3d/samples/o3d-webgl/file_request.js b/o3d/samples/o3d-webgl/file_request.js
deleted file mode 100644
index c0de059..0000000
--- a/o3d/samples/o3d-webgl/file_request.js
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A FileRequest is used to carry out an asynchronous request for a file
- * to be loaded. Its use parallels that of XMLHttpRequest; you create one, call
- * open, set the onreadystatechange callback, and call send.
- * Note that unlike XMLHttpRequests, FileRequests cannot be reused.
- *
- * For RawData loads, on success the RawData will be stored in the data field
- * on the FileRequest itself. It is only valid until the FileRequest is freed by
- * calling pack.removeObject(request).
- *
- * var request = pack.createFileRequest("RAWDATA");
- * request.open("GET", url, true);
- * request.onreadystatechange = function() {
- * if (request.done) {
- * if (request.success) {
- * var rawData = request.data;
- *
- * ...
- * } else {
- * dump('Load of rawdata returned failure.');
- * }
- *
- * pack.removeObject(request);
- * }
- * };
- * request.send();
- */
-o3d.FileRequest = function() {
- this.method_ = "";
- this.async_ = true;
- this.request_ = new XMLHttpRequest();
- var fileRequest = this;
- this.request_.onreadystatechange = function() {
- fileRequest.readyState = this.readyState;
- fileRequest.done = fileRequest.done || this.done;
- if (this.readyState == 4) {
- if (this.responseText) {
- fileRequest.success = true;
- }
- fileRequest.done = true;
- }
- fileRequest.data = this.responseText;
- if (fileRequest.onreadystatechange)
- fileRequest.onreadystatechange.apply(fileRequest, arguments);
- }
-};
-o3d.inherit('FileRequest', 'NamedObject');
-
-
-/**
- * A callback to call whenever the ready state of the request changes.
- * @type {Object}
- */
-o3d.FileRequest.prototype.onreadystatechange = null;
-
-
-
-/**
- * The URI this request is for.
- * @type {string}
- */
-o3d.FileRequest.prototype.uri = '';
-
-
-
-/**
- * On completion of successful RawData file loads, this holds the loaded
- * RawData.
- * @type {o3d.RawData}
- */
-o3d.FileRequest.prototype.data = null;
-
-
-
-/**
- * This holds the same values as in XMLHttpRequest:
- * 0 = uninitialized
- * 1 = opened
- * 2 = sent
- * 3 = receiving
- * 4 = loaded (the file has been downloaded, but may or may not have been
- * parsed yet)
- * @type {number}
- */
-o3d.FileRequest.prototype.readyState = 0;
-
-
-
-/**
- * This indicates whether any further processing will be done on this
- * FileRequest.
- * @type {boolean}
- */
-o3d.FileRequest.prototype.done = false;
-
-
-
-/**
- * This field is only valid if done is true. It indicates whether or not the
- * request succeeded. If it failed error holds an error message.
- * @type {boolean}
- */
-o3d.FileRequest.prototype.success = false;
-
-
-/**
- * The image object if we are opening an image.
- * @type {Image}
- * @private
- */
-o3d.FileRequest.prototype.image_ = null;
-
-
-/**
- * An error message.
- * If done is true and success is false this will be an error message
- * describing what went wrong.
- * @type {string}
- */
-o3d.FileRequest.prototype.error = '';
-
-
-/**
- * Guesses from a url whether the url is an image file.
- * @param {string} url The URL.
- * @private
- */
-o3d.FileRequest.prototype.isImageUrl_ = function(url) {
- var extension = url.substring(url.length - 4);
- return (extension == '.png' || extension == '.jpg');
-};
-
-
-/**
- * Called by the image class when the image file is loaded... if we're
- * loading an image.
- * @private
- */
-o3d.FileRequest.prototype.imageLoaded_ = function() {
- if (this.image_.complete) {
- this.success = true;
- this.done = true;
- this.readyState = 4;
- this.data = new o3d.RawData();
- this.data.image_ = this.image_;
- }
- this.onreadystatechange.apply(this, arguments);
-};
-
-
-/**
- * Set up several of the request fields.
- * @param {string} method "GET" is the only supported method at this time
- * @param {string} uri the location of the file to fetch
- * @param {boolean} async true is the only legal value at this time.
- */
-o3d.FileRequest.prototype.open =
- function(method, uri, async) {
- this.uri = uri;
- this.method_ = method;
- this.async_ = async;
-};
-
-
-/**
- * Send the request.
- * Unlike XMLHttpRequest the onreadystatechange callback will be called no
- * matter what, with success or failure.
- */
-o3d.FileRequest.prototype.send = function() {
- if (this.isImageUrl_(this.uri)) {
- this.image_ = new Image();
- var that = this;
- this.image_.onload = function() {
- that.imageLoaded_.call(that);
- }
- this.image_.src = this.uri;
- } else {
- this.request_.open(this.method_, this.uri, this.async_);
- }
-};
-
-
-
diff --git a/o3d/samples/o3d-webgl/function.js b/o3d/samples/o3d-webgl/function.js
deleted file mode 100644
index 8bde542..0000000
--- a/o3d/samples/o3d-webgl/function.js
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * A Function is a class that has an Evaluate method.
- * Evaluate takes 1 input and returns 1 output.
- * @param {function(number)=} opt_func evaluate function to use (unless this
- * class is extended
- * @constructor
- * @extends {o3d.NamedObject}
- */
-o3d.Function = function(opt_func) {
- o3d.NamedObject.call(this);
- this.func_ = opt_func;
-};
-o3d.inherit('Function', 'NamedObject');
-
-/**
- * Gets an output for this function for the given input.
- * @param {number} input Input to get output at.
- * @param {object=} opt_context Cached state from the previous evaluate call.
- * @return {number} The output for the given input.
- */
-o3d.Function.prototype.evaluate = function(input, opt_context) {
- this.func_.call(this, input, opt_context);
-};
-
-/**
- * A FunctionEval evaluates a Function through parameters.
- * @constructor
- * @extends {o3d.ParamObject}
- */
-o3d.FunctionEval = function() {
- o3d.ParamObject.call(this);
-
- /**
- * Read/write input value to the function.
- * @private
- * @type {o3d.ParamFloat}
- */
- this.input_param_ = this.getParam("input");
-
- /**
- * ParamFunction whose value is a o3d.Function or subclass.
- * @private
- * @type {o3d.ParamFunction}
- */
- this.func_param_ = this.getParam("functionObject");
-
- /**
- * Read-only output value. Value is cached if input does not change.
- * @private
- * @type {o3d.ParamFloatOutput}
- */
- this.output_param_ = this.getParam("output");
-
- /**
- * Context value to allow faster evaluation for adjacent input values.
- * Used by the o3d.Function itself, but stored here to allow multiple
- * FunctionEval objects to share the same Function object.
- * @private
- * @type {object}
- */
- this.func_context_ = {};
-
- /**
- * Last input value to check if cache needs to be invalidated.
- * @private
- * @type {number}
- */
- this.last_input_value_ = null;
-
- /**
- * Cache of the last output value.
- * @private
- * @type {number}
- */
- this.last_output_value_ = null;
-};
-o3d.inherit('FunctionEval', 'ParamObject');
-
-/**
- * Read-only output value. Value is cached if input does not change.
- * @type {number}
- */
-o3d.ParamObject.setUpO3DParam_(o3d.FunctionEval, "output", "ParamFloatOutput");
-
-/**
- * Read/write input value to the function.
- * @type {number}
- */
-o3d.ParamObject.setUpO3DParam_(o3d.FunctionEval, "input", "ParamFloat");
-
-/**
- * o3d.Function object (or subclass) with evaluate function.
- * @type {o3d.Function}
- */
-o3d.ParamObject.setUpO3DParam_(o3d.FunctionEval, "functionObject",
- "ParamFunction");
-
-/**
- * Called by o3d.Param*Output whenever its value gets read.
- * This function should be responsible for caching the last value if necessary.
- * @return {number} The result of evaluating the function.
- */
-o3d.FunctionEval.prototype.updateOutputs = function() {
- var new_input_value = this.input_param_.value;
- if (this.last_input_value_ != new_input_value) {
- this.last_output_value_ =
- this.func_param_.value.evaluate(this.last_input_value_,
- this.func_context_);
- this.last_input_value_ = new_input_value;
- }
- return this.last_output_value_;
-};
diff --git a/o3d/samples/o3d-webgl/material.js b/o3d/samples/o3d-webgl/material.js
deleted file mode 100644
index 1597474..0000000
--- a/o3d/samples/o3d-webgl/material.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A Material holds the various uniform parameters an Effect needs to render.
- * For example a Lambert effect might need "diffuse", "ambient", "emissive".
- * The parameters needed on a Material will vary depending its Effect.
- * Note that a material MUST have its drawList set in order for objects using it
- * to render.
- *
- * @param {!o3d.State} opt_state The State used by this material.
- * @param {!o3d.Effect} opt_effect The Effect used by this material.
- * @param {!o3d.DrawList} opt_draw_list The the DrawList used by this material.
- * @constructor
- */
-o3d.Material = function(opt_state, opt_effect, opt_draw_list) {
- o3d.ParamObject.call(this);
- /**
- * The State for this material.
- * @type {o3d.State}
- */
- this.state = opt_state || null;
-
- /**
- * The Effect for this material.
- * @type {o3d.Effect}
- */
- this.effect = opt_effect || null;
-
- /**
- * The DrawList this material will render on.
- * @type {o3d.DrawList}
- */
- this.drawList = opt_draw_list || null;
-};
-o3d.inherit('Material', 'ParamObject');
-
-o3d.ParamObject.setUpO3DParam_(o3d.Material, 'effect', 'ParamEffect');
-o3d.ParamObject.setUpO3DParam_(o3d.Material, 'state', 'ParamState');
-o3d.ParamObject.setUpO3DParam_(o3d.Material, 'drawList', 'ParamDrawList');
-
diff --git a/o3d/samples/o3d-webgl/named_object.js b/o3d/samples/o3d-webgl/named_object.js
deleted file mode 100644
index c272c1f..0000000
--- a/o3d/samples/o3d-webgl/named_object.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * Base class for all objects that can have their name set.
- * @constructor
- */
-o3d.NamedObject = function() {
- o3d.NamedObjectBase.call(this);
-};
-o3d.inherit('NamedObject', 'NamedObjectBase');
-
-
-/**
- * The object's name.
- *
- * Setting this has no meaning to O3D, but is useful for debugging and for
- * the functions Client.getObjects, Pack.getObject,
- * RenderNode.getRenderNodesByNameInTree and
- * RenderNode.getTransformsByNameInTree
- * which search for objects by name.
- * @type {string}
- */
-o3d.NamedObject.prototype.name = '';
-
-
diff --git a/o3d/samples/o3d-webgl/named_object_base.js b/o3d/samples/o3d-webgl/named_object_base.js
deleted file mode 100644
index b3b6858..0000000
--- a/o3d/samples/o3d-webgl/named_object_base.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * Base class for all objects that are identifiable by a name.
- * @constructor
- */
-o3d.NamedObjectBase = function() {
- o3d.ObjectBase.call(this);
-};
-o3d.inherit('NamedObjectBase', 'ObjectBase');
-
-
-/**
- * The object's name.
- * @type {string}
- */
-o3d.NamedObjectBase.prototype.name = "";
-
-
diff --git a/o3d/samples/o3d-webgl/object_base.js b/o3d/samples/o3d-webgl/object_base.js
deleted file mode 100644
index feb97bc..0000000
--- a/o3d/samples/o3d-webgl/object_base.js
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A ObjectBase is a base class that manages a set of components in a
- * Buffer of a specific type. ObjectBases are managed by Buffers and can
- * not be directly created. When a Buffer is destroyed or if a ObjectBase
- * is removed from a Buffer the ObjectBase's buffer property will be set
- * to null.
- */
-o3d.ObjectBase = function() { };
-
-
-/**
- * Used by isAClassName.
- * @type {string}
- */
-o3d.ObjectBase.prototype.className = 'o3d.ObjectBase';
-
-/**
- * @type {o3d.ObjectBase}
- */
-o3d.ObjectBase.prototype.superClass = null;
-
-/**
- * Traverses the current object's class and all its superclasses and
- * determines if any of them are of the given name.
- * @param {string} class_type_name The name of a class.
- * @return {boolean} Whether this is counts as a className.
- */
-o3d.ObjectBase.prototype.isAClassName = function(class_type_name) {
- class_type_name = o3d.filterTypeName_(class_type_name);
- var object = this;
- while (object != undefined) {
- if (object.className == class_type_name) {
- return true;
- }
- object = object.superClass && object.superClass.prototype;
- }
- return false;
-};
-
-
diff --git a/o3d/samples/o3d-webgl/pack.js b/o3d/samples/o3d-webgl/pack.js
deleted file mode 100644
index f74d196..0000000
--- a/o3d/samples/o3d-webgl/pack.js
+++ /dev/null
@@ -1,403 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A Pack object functions as a container for O3D objects. The Pack
- * is used to control the lifetime scope of a collection of objects in bulk. The
- * Pack object achieves this by simply storing a set of references to its
- * contained objects, which ensures that the ref-counts for those objects never
- * reach zero while the pack is alive.
- * @constructor
- */
-o3d.Pack = function() {
- o3d.NamedObject.call(this);
- this.objects_ = [];
-};
-o3d.inherit('Pack', 'NamedObject');
-
-
-/**
- * Removes all internal references to the Pack from the client.
- * The pack, and all objects contained in it are permitted to be destroyed
- * after the pack's destruction. Objects will only be destroyed after all
- * references to them have been removed.
- *
- * NOTE: Calling pack.destroy does NOT free your resources. It justs releases
- * the pack's reference to those resources. An example should hopefully make
- * it clearer.
- *
- * pack.destroy() is effectively almost the same as this.
- *
- * var objectsInPack = pack.getObjectsByClassName('o3d.ObjectBase');
- * for (var ii = 0; ii < objectsInPack.length; ++ii) {
- * pack.removeObject(objectsInPack[ii]);
- * }
- *
- * The only difference is that after all the objects are removed the pack
- * itself will be released from the client. See documentation on
- * pack.removeObject for why this is important.
- *
- * It's important to note that many objects are only referenced by the pack.
- * Textures, Effects, Materials, for example. That means the moment you call
- * pack.destroy() those objects will be freed. If the client then tries to
- * render and some objects are missing you'll immediately get an error.
- */
-o3d.Pack.prototype.destroy = function() {
- this.objects_ = [];
- this.client.destroyPack(this);
-};
-
-
-
-/**
- * Removes a pack's reference to an object. Any object created from
- * pack.create___ function can be removed. This releases the pack's reference
- * to that object so if nothing else is referencing that object it will be
- * deleted.
- *
- * NOTE: Calling pack.removeObject does NOT automatically free your resource.
- * It just releases the pack's reference to that resource. An example should
- * hopefully make it clearer.
- *
- * Suppose you make a transform like this:
- *
- *
- * var myTransform = pack.createObject('Transform');
- * myTransform.parent = g_client.root;
- * pack.removeObject(myTransform);
- *
- *
- * In the code above, myTransform is referenced twice. Once by the pack, and
- * again by g_client.root So in this case, calling pack.removeObject()
- * only releases the pack's reference leaving the reference by g_client.root.
- *
- *
- * myTransform.parent = null;
- *
- *
- * Now the last reference has been removed and myTransform will be freed.
- *
- * @param {o3d.ObjectBase} object Object to remove.
- * @return {boolean} True if the object was successfully removed.
- * False if the object is not part of this pack.
- */
-o3d.Pack.prototype.removeObject =
- function(object) {
- o3d.removeFromArray(this.objects_, object);
-};
-
-
-/**
- * Creates an Object by Class name.
- *
- * Note: You may omit the 'o3d.'.
- *
- * @param {string} type_name name of Class to create. Valid type names are:
- * Bitmap
- * Canvas
- * CanvasLinearGradient
- * CanvasPaint
- * ClearBuffer
- * Counter
- * Curve
- * DrawContext
- * DrawElement
- * DrawList
- * DrawPass
- * Effect
- * FunctionEval
- * IndexBuffer
- * Material
- * ParamArray
- * ParamObject
- * Primitive
- * RenderFrameCounter
- * RenderNode
- * RenderSurfaceSet
- * Sampler
- * SecondCounter
- * Shape
- * Skin
- * SkinEval
- * SourceBuffer
- * State
- * StateSet
- * StreamBank
- * Texture2D
- * TextureCUBE
- * TickCounter
- * Transform
- * TreeTraversal
- * VertexBuffer
- * Viewport
- * Matrix4AxisRotation
- * Matrix4Composition
- * Matrix4Scale
- * Matrix4Translation
- * ParamOp2FloatsToFloat2
- * ParamOp3FloatsToFloat3
- * ParamOp4FloatsToFloat4
- * ParamOp16FloatsToMatrix4
- * TRSToMatrix4
- * @return {o3d.ObjectBase} The created object.
- */
-o3d.Pack.prototype.createObject =
- function(type_name) {
- var foo = o3d.global.o3d[o3d.filterTypeName_(type_name)];
- if (typeof foo != 'function') {
- throw 'cannot find type in o3d namespace: ' + type_name
- }
- var object = new foo();
- object.gl = this.gl;
- object.clientId = o3d.Client.nextId++;
- this.objects_.push(object);
- return object;
-};
-
-
-/**
- * Creates a new Texture2D object of the specified size and format and
- * reserves the necessary resources for it.
- *
- * Note: If enable_render_surfaces is true, then the dimensions must be a
- * power of two.
- *
- * @param {number} width The width of the texture area in texels (max = 2048)
- * @param {number} height The height of the texture area in texels (max = 2048)
- * @param {o3d.Texture.Format} format The memory format of each texel
- * @param {number} levels The number of mipmap levels. Use zero to create the
- * compelete mipmap chain.
- * @param {boolean} enable_render_surfaces If true, the texture object will
- * expose RenderSurface objects through GetRenderSurface(...).
- * @return {!o3d.Texture2D} The Texture2D object.
- */
-o3d.Pack.prototype.createTexture2D =
- function(width, height, format, levels, enable_render_surfaces) {
- var texture = this.createObject('Texture2D');
- texture.init_(width, height, format, levels, enable_render_surfaces);
- return texture;
-};
-
-
-/**
- * Creates a new TextureCUBE object of the specified size and format and
- * reserves the necessary resources for it.
- * Note: If enable_render_surfaces is true, then the dimensions must be a
- * power of two.
- *
- * @param {number} edgeLength The edge of the texture area in texels
- * (max = 2048)
- * @param {o3d.Texture.Format} format The memory format of each texel.
- * @param {number} levels The number of mipmap levels. Use zero to create
- * the compelete mipmap chain.
- * @param {boolean} enableRenderSurfaces If true, the texture object
- * will expose RenderSurface objects through GetRenderSurface(...).
- * @return {!o3d.TextureCUBE} The TextureCUBE object.
- */
-o3d.Pack.prototype.createTextureCUBE =
- function(edgeLength, format, levels, enableRenderSurfaces) {
- var textureCube = this.createObject('TextureCUBE');
- textureCube.init_(edgeLength, format, levels, enableRenderSurfaces);
- return textureCube;
-};
-
-
-/**
- * Creates a new RenderDepthStencilSurface object of a format suitable for use
- * as a depth-stencil render target.
- * Note: The dimensions of the RenderDepthStencilSurface must be a power of
- * two.
- *
- * @param {number} width The width of the RenderSurface in pixels
- * @param {number} height The height of the RenderSurface in pixels
- * @return {!o3d.RenderDepthStencilSurface} The RenderSurface object.
- */
-o3d.Pack.prototype.createDepthStencilSurface =
- function(width, height) {
- var surface = this.createObject("RenderDepthStencilSurface");
- surface.initWithSize_(width, height);
- return surface;
-};
-
-
-/**
- * Search the pack for all objects of a certain class with a certain name.
- *
- * Note that modifications to this array [e.g. push()] will not affect
- * the underlying Pack, while modifications to the array's members
- * will affect them.
- *
- * @param {string} name Name to look for
- * @param {string} class_type_name the Class of the object. It is okay
- * to pass base types for example "o3d.RenderNode" will return
- * ClearBuffers, DrawPasses, etc...
- * @return {!Array.<!o3d.ObjectBase>} Array of Objects.
- */
-o3d.Pack.prototype.getObjects =
- function(name, class_type_name) {
- class_type_name = o3d.filterTypeName_(class_type_name);
-
- var found = [];
-
- for (var i = 0; i < this.objects_.length; ++i) {
- var object = this.objects_[i];
- if (object.isAClassName(class_type_name) &&
- object.name == name) {
- found.push(object);
- }
- }
-
- return found;
-};
-
-
-/**
- * Search the pack for all objects of a certain class
- *
- * Note that modifications to this array [e.g. push()] will not affect
- * the underlying Pack, while modifications to the array's members
- * will affect them.
- *
- * @param {string} class_type_name the Class of the object. It is
- * okay to pass base types for example "o3d.RenderNode" will return
- * ClearBuffers, DrawPasses, etc...
- * @return {!Array.<!o3d.ObjectBase>} Array of Objects.
- */
-o3d.Pack.prototype.getObjectsByClassName =
- function(class_type_name) {
- class_type_name = o3d.filterTypeName_(class_type_name);
-
- var found = [];
-
- for (var i = 0; i < this.objects_.length; ++i) {
- var object = this.objects_[i];
- if (object.isAClassName(class_type_name)) {
- found.push(object);
- }
- }
-
- return found;
-};
-
-
-/**
- * All the objects managed by this pack.
- *
- * Each access to this field gets the entire list so it is best to get it
- * just once. For example:
- *
- * var objects = pack.objects;
- * for (var i = 0; i < objects.length; i++) {
- * var object = objects[i];
- * }
- *
- *
- * Note that modifications to this array [e.g. push()] will not affect
- * the underlying Pack, while modifications to the array's members
- * will affect them.
- */
-o3d.Pack.prototype.objects_ = [];
-
-
-/**
- * Creates a FileRequest to be used to asynchronously load a Texture or
- * RawData. Note: Loading a "TEXTURE" is deprecated. The recommended way to
- * load a texture is to load a RawData, use that to create Bitmap, Massage
- * the Bitmap to your liking the use that to create a Texture.
- * @param {string} type Must be "TEXTURE" or "RAWDATA"
- * @return {!o3d.FileRequest} a FileRequest
- */
-o3d.Pack.prototype.createFileRequest =
- function(type) {
- return this.createObject('FileRequest');
-};
-
-/**
- * Creates an ArchiveRequest so we can stream in assets from an archive.
- * @return {!o3d.ArchiveRequest} an ArchiveRequest
- */
-o3d.Pack.prototype.createArchiveRequest =
- function() {
- return this.createObject('ArchiveRequest');
-};
-
-/**
- * Create Bitmaps from RawData.
- *
- * If you load a cube map you'll get an array of 6 Bitmaps.
- * If you load a volume map you'll get an array of n Bitmaps.
- * If there is an error you'll get an empty array.
- *
- * @param {!o3d.RawData} raw_data contains the bitmap data in a supported
- * format.
- * @return {!Array.<!o3d.Bitmap>} An Array of Bitmaps object.
- */
-o3d.Pack.prototype.createBitmapsFromRawData =
- function(raw_data) {
- var bitmap = this.createObject('Bitmap')
- if (!raw_data.image_) {
- throw ('Cannot create bitmap from non-image data.');
- return [];
- }
- bitmap.height = raw_data.image_.height;
- bitmap.width = raw_data.image_.width;
-
- var canvas = document.createElement('CANVAS');
-
- canvas.width = bitmap.width;
- canvas.height = bitmap.height;
- var context = canvas.getContext('2d');
- context.drawImage(raw_data.image_,
- 0, 0, bitmap.width, bitmap.height);
-
- bitmap.canvas_ = canvas;
- // Most images require a vertical flip.
- bitmap.flipVerticallyLazily_();
-
- // TODO(petersont): Find out if any other formats are possible at this point.
- bitmap.format = o3d.Texture.ARGB8;
- bitmap.numMipmaps = 1;
-
- return [bitmap];
-};
-
-
-/**
- * Create RawData given a data URL.
- * @param {string} data_url The data URL from which to create the RawData.
- * @return {!o3d.RawData} The RawData.
- */
-o3d.Pack.prototype.createRawDataFromDataURL =
- function(data_url) {
- o3d.notImplemented();
-};
-
diff --git a/o3d/samples/o3d-webgl/param.js b/o3d/samples/o3d-webgl/param.js
deleted file mode 100644
index 66fca29..0000000
--- a/o3d/samples/o3d-webgl/param.js
+++ /dev/null
@@ -1,1018 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * Params store data defined name/value pairs on ParamObjects.
- * Each Param has a name, a type and a value that can be set and queried.
- * One of their uses is to hold "uniform constants" used to parameterize
- * shaders. Params can be connected in a source/destination fashion such
- * that a target Param gets its value from the source param.
- * @constructor
- */
-o3d.Param = function(param_type_name) {
- /**
- * If true, this param will make sure its input param is up to date when
- * using it as a source. Default = true.
- *
- * This is for helping with Param cycles.
- *
- * If paramA gets its value from paramB and paramB gets its value from
- * paramA:
- * If you go paramA.value, paramB will evaluate then copy to paramA.
- * If you go paramB.value, paramA will evaluate then copy to paramB.
- * If you set paramB.updateInput = false, then:
- * If you go paramA.value, paramB will evaluate then copy to paramA.
- * If you go paramB.value, paramB just copy paramA. paramA will NOT evaluate
- * when paramB asks for its value.
- */
- this.updateInput = true;
-
- /**
- * @type {o3d.Param}
- */
- this.inputConnection = null;
-
- /**
- * @type {Array.<!o3d.Param>}
- */
- this.outputConnections = [];
-
- /**
- * The ParamObject that has this param as a param.
- * @type {o3d.ParamObject}
- * @private
- */
- o3d.Param.prototype.owner_ = null;
-
- /**
- * Private variable to store the value of the param.
- * @type {*}
- * @private
- */
- this.value_ = null;
-}
-o3d.inherit('Param', 'NamedObject');
-
-
-o3d.Param.prototype.__defineSetter__('value',
- function(v) {
- if (this.inputConnection) {
- throw ('Tried to set bound parameter.');
- } else {
- if (this.value_ != undefined && (
- typeof this.value_ != typeof v ||
- (this.value_.length_ !== undefined &&
- (this.value_.length_ != v.length)))) {
- this.gl.client.error_callback('Param type error.');
- }
- this.value_ = v;
- }
- }
-);
-
-o3d.Param.prototype.__defineGetter__('value',
- function() {
- if (this.inputConnection) {
- return this.inputConnection.value;
- } else {
- return this.value_;
- }
- }
-);
-
-
-/**
- * Directly binds two Param elements such that this parameter gets its value
- * from the source parameter. The source must be compatible with this
- * parameter.
- *
- * @param {o3d.Param} source_param The parameter that the value originates
- * from. Passing in null will unbind any parameter currently bound.
- * @return {boolean} True if the bind succeeded.
- */
-o3d.Param.prototype.bind =
- function(source_param) {
- source_param.outputConnections.push(this);
- this.inputConnection = source_param;
-};
-
-
-/**
- * Breaks any input connection coming into the Param.
- */
-o3d.Param.prototype.unbindInput =
- function() {
- o3d.notImplemented();
-};
-
-
-/**
- * Breaks a specific param-bind output connection on this param.
- *
- * @param {o3d.Param} destination_param param to unbind.
- */
-o3d.Param.prototype.unbindOutput =
- function(destination_param) {
- o3d.notImplemented();
-};
-
-
-/**
- * Breaks all param-bind output connections on this param.
- */
-o3d.Param.prototype.unbindOutputs = function() {
- o3d.notImplemented();
-};
-
-
-
-/**
- * If true the param is read only. Its value can not be set nor can it be used
- * as the destination in a ParamBind.
- */
-o3d.Param.prototype.read_only_ = false;
-
-
-/**
- * @constructor
- */
-o3d.ParamBoolean = function() {
- o3d.Param.call(this);
- this.value = false;
-};
-o3d.inherit('ParamBoolean', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamBoundingBox = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamBoundingBox', 'Param');
-
-// ParamBoundingBox requires a specialized setter because it must
-// accept arrays of arrays and convert them into BoundingBoxes. It
-// seems that if we define a setter against this prototype we must
-// also define a getter -- it is not inherited.
-o3d.ParamBoundingBox.prototype.__defineSetter__('value',
- function(v) {
- if (this.inputConnection) {
- throw ('Tried to set bound parameter.');
- } else {
- if (!v) {
- v = new o3d.BoundingBox();
- } else if (v.length !== undefined) {
- if (v.length == 0) {
- v = new o3d.BoundingBox();
- } else if (v.length == 2) {
- for (var ii = 0; ii < 2; ++ii) {
- if (v[ii].length != 3) {
- throw ('Expected sub-array of length 3 at index ' + ii +
- ', got ' + v[ii].length);
- }
- }
- v = new o3d.BoundingBox(v[0], v[1]);
- } else {
- throw 'Expected array of length 2';
- }
- }
- this.value_ = v;
- }
- }
-);
-
-o3d.ParamBoundingBox.prototype.__defineGetter__('value',
- function() {
- if (this.inputConnection) {
- return this.inputConnection.value;
- } else {
- return this.value_;
- }
- }
-);
-
-/**
- * @constructor
- */
-o3d.ParamDrawContext = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamDrawContext', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamDrawList = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamDrawList', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamEffect = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamEffect', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamFloat = function() {
- o3d.Param.call(this);
- this.value = 0.0;
-};
-o3d.inherit('ParamFloat', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamFloat2 = function() {
- o3d.Param.call(this);
- this.value = o3d.Transform.makeVector2_(0.0, 0.0);
-};
-o3d.inherit('ParamFloat2', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamFloat3 = function() {
- o3d.Param.call(this);
- this.value = o3d.Transform.makeVector3_(0.0, 0.0, 0.0);
-};
-o3d.inherit('ParamFloat3', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamFloat4 = function() {
- o3d.Param.call(this);
- this.value = o3d.Transform.makeVector4_(0.0, 0.0, 0.0, 0.0);
-};
-o3d.inherit('ParamFloat4', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamFunction = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamFunction', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamInteger = function() {
- o3d.Param.call(this);
- this.value = 0;
-};
-o3d.inherit('ParamInteger', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamMaterial = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamMaterial', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamMatrix4 = function() {
- o3d.Param.call(this);
- this.value = o3d.Transform.makeMatrix4_(1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
-};
-o3d.inherit('ParamMatrix4', 'Param');
-
-/**
- * @constructor
- */
-o3d.ParamParamArray = function() {
- o3d.Param.call(this);
-};
-o3d.inherit('ParamParamArray', 'Param');
-
-/**
- * Acts like ParamParamArray, but asks its owner object to update the array
- * contents every time its value is queried.
- *
- * @constructor
- * @extends {o3d.ParamParamArray}
- */
-o3d.ParamParamArrayOutput = function() {
- o3d.ParamParamArray.call(this);
-};
-o3d.inherit('ParamParamArrayOutput', 'ParamParamArray');
-o3d.ParamParamArrayOutput.prototype.__defineGetter__("value",
- function() {
- this.owner_.updateOutputs(this);
- return this.value_;
- }
-);
-o3d.ParamParamArrayOutput.prototype.__defineSetter__("value",
- function(value) {
- // Creating a new array is fine.
- this.value_ = value;
- }
-);
-
-/**
- * @constructor
- */
-o3d.ParamRenderSurface = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamRenderSurface', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamRenderDepthStencilSurface = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamRenderDepthStencilSurface', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamSampler = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamSampler', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamSkin = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamSkin', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamSteamBank = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamSteamBank', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamState = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamState', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamStreamBank = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamStreamBank', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamString = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamString', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamTexture = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamTexture', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamTransform = function() {
- o3d.Param.call(this);
- this.value = null;
-};
-o3d.inherit('ParamTransform', 'Param');
-
-
-/**
- * @constructor
- */
-o3d.ParamVertexBufferStream = function() {
- o3d.Param.call(this);
- this.stream = null;
-};
-o3d.inherit('ParamVertexBufferStream', 'Param');
-
-/**
- * Base class for the types of matrix4 params that compute their own
- * value when asked (ProjectionParamMatrix4 etc).
- * @constructor
- */
-o3d.CompositionParamMatrix4 = function() {
- o3d.ParamMatrix4.call(this);
- this.matrix_names_ = [];
-};
-
-o3d.inherit('CompositionParamMatrix4', 'ParamMatrix4');
-
-
-/**
- * The array of names of matrix params for the matrices that are to be
- * composed to get the value.
- * @type {Array.<o3d.ParamMatrix4>}
- */
-o3d.CompositionParamMatrix4.prototype.matrix_names_ = [];
-
-/**
- * Whether the inverse is taken right before returning the value.
- * @type {Array.<o3d.ParamMatrix4>}
- */
-o3d.CompositionParamMatrix4.prototype.inverse_ = false;
-
-
-/**
- * Whether the inverse is taken right before returning the value.
- * @type {Array.<o3d.ParamMatrix4>}
- */
-o3d.CompositionParamMatrix4.prototype.transpose_ = false;
-
-o3d.CompositionParamMatrix4.prototype.__defineGetter__('value',
- // TODO(petersont): Cache the result if it hasn't changed.
- function() {
- var product = o3d.Transform.makeIdentityMatrix4_();
- for (var i = 0; i < this.matrix_names_.length; ++i) {
- o3d.Transform.compose_(product, o3d.Param.SAS[this.matrix_names_[i]]);
- }
- if (this.inverse_) {
- o3d.Transform.inverse_(product);
- }
- if (this.transpose_) {
- o3d.Transform.transpose_(product);
- }
- return product;
- }
-);
-
-o3d.CompositionParamMatrix4.prototype.__defineSetter__('value',
- function(value) { }
-);
-
-
-/**
- * @constructor
- */
-o3d.ProjectionParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['projection'];
-};
-o3d.inherit('ProjectionParamMatrix4', 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.ProjectionInverseParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['projection'];
- this.inverse_ = true;
-};
-o3d.inherit('ProjectionInverseParamMatrix4', 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.ProjectionTransposeParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['projection'];
- this.transpose_ = true;
-};
-o3d.inherit('ProjectionTransposeParamMatrix4', 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.ProjectionInverseTransposeParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['projection'];
- this.inverse_ = true;
- this.transpose_ = true;
-};
-o3d.inherit('ProjectionInverseTransposeParamMatrix4',
- 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.ViewParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['view'];
-};
-o3d.inherit('ViewParamMatrix4', 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.ViewInverseParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['view'];
- this.inverse_ = true;
-};
-o3d.inherit('ViewInverseParamMatrix4', 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.ViewTransposeParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['view'];
- this.transpose_ = true;
-};
-o3d.inherit('ViewTransposeParamMatrix4', 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.ViewInverseTransposeParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['view'];
- this.inverse_ = true;
- this.transpose_ = true;
-};
-o3d.inherit('ViewInverseTransposeParamMatrix4', 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.ViewProjectionParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['viewProjection'];
-};
-o3d.inherit('ViewProjectionParamMatrix4', 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.ViewProjectionInverseParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['viewProjection'];
- this.inverse_ = true;
-};
-o3d.inherit('ViewProjectionInverseParamMatrix4', 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.ViewProjectionTransposeParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['viewProjection'];
- this.transpose_ = true;
-};
-o3d.inherit('ViewProjectionTransposeParamMatrix4', 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.ViewProjectionInverseTransposeParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['viewProjection'];
- this.inverse_ = true;
- this.transpose_ = true;
-};
-o3d.inherit('ViewProjectionInverseTransposeParamMatrix4',
- 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.WorldParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['world'];
-};
-o3d.inherit('WorldParamMatrix4', 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.WorldInverseParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['world'];
- this.inverse_ = true;
-};
-o3d.inherit('WorldInverseParamMatrix4', 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.WorldTransposeParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['world'];
- this.transpose_ = true;
-};
-o3d.inherit('WorldTransposeParamMatrix4', 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.WorldInverseTransposeParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['world'];
- this.inverse_ = true;
- this.transpose_ = true;
-};
-o3d.inherit('WorldInverseTransposeParamMatrix4', 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.WorldViewParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['view', 'world'];
-};
-o3d.inherit('WorldViewParamMatrix4', 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.WorldViewInverseParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['view', 'world'];
- this.inverse_ = true;
-};
-o3d.inherit('WorldViewInverseParamMatrix4',
- 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.WorldViewTransposeParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['view', 'world'];
- this.transpose_ = true;
-};
-o3d.inherit('WorldViewTransposeParamMatrix4',
- 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.WorldViewInverseTransposeParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['view', 'world'];
- this.inverse_ = true;
- this.transpose_ = true;
-};
-o3d.inherit('WorldViewInverseTransposeParamMatrix4',
- 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.WorldViewProjectionParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['worldViewProjection'];
-};
-o3d.inherit('WorldViewProjectionParamMatrix4',
- 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.WorldViewProjectionInverseParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['worldViewProjection'];
- this.inverse_ = true;
-};
-o3d.inherit('WorldViewProjectionInverseParamMatrix4',
- 'CompositionParamMatrix4');
-
-
-/**
- * @constructor
- */
-o3d.WorldViewProjectionTransposeParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['worldViewProjection'];
- this.transpose_ = true;
-};
-o3d.inherit('WorldViewProjectionTransposeParamMatrix4',
- 'CompositionParamMatrix4');
-
-/**
- * @constructor
- */
-o3d.WorldViewProjectionInverseTransposeParamMatrix4 = function() {
- o3d.CompositionParamMatrix4.call(this);
- this.matrix_names_ = ['worldViewProjection'];
- this.inverse_ = true;
- this.transpose_ = true;
-};
-o3d.inherit('WorldViewProjectionInverseTransposeParamMatrix4',
- 'CompositionParamMatrix4');
-
-
-/**
- * Called to specify the value of a uniform variable.
- * @param {WebGLContext} gl The current context.
- * @param {WebGLUniformLocation} location The location to which to apply.
- */
-o3d.ParamInteger.prototype.applyToLocation = function(gl, location) {
- gl.uniform1i(location, this.value);
-};
-
-/**
- * Called to specify the value of a uniform variable.
- * @param {WebGLContext} gl The current context.
- * @param {WebGLUniformLocation} location The location to which to apply.
- */
-o3d.ParamBoolean.prototype.applyToLocation = function(gl, location) {
- gl.uniform1i(location, this.value);
-};
-
-/**
- * Called to specify the value of a uniform variable.
- * @param {WebGLContext} gl The current context.
- * @param {WebGLUniformLocation} location The location to which to apply.
- */
-o3d.ParamFloat.prototype.applyToLocation = function(gl, location) {
- gl.uniform1f(location, this.value);
-};
-
-/**
- * Called to specify the value of a uniform variable.
- * @param {WebGLContext} gl The current context.
- * @param {WebGLUniformLocation} location The location to which to apply.
- */
-o3d.ParamFloat2.prototype.applyToLocation = function(gl, location) {
- gl.uniform2fv(location, this.value);
-};
-
-/**
- * Called to specify the value of a uniform variable.
- * @param {WebGLContext} gl The current context.
- * @param {WebGLUniformLocation} location The location to which to apply.
- */
-o3d.ParamFloat3.prototype.applyToLocation = function(gl, location) {
- gl.uniform3fv(location, this.value);
-};
-
-/**
- * Called to specify the value of a uniform variable.
- * @param {WebGLContext} gl The current context.
- * @param {WebGLUniformLocation} location The location to which to apply.
- */
-o3d.ParamFloat4.prototype.applyToLocation = function(gl, location) {
- gl.uniform4fv(location, this.value);
-};
-
-/**
- * Called to specify the value of a uniform variable.
- * @param {WebGLContext} gl The current context.
- * @param {WebGLUniformLocation} location The location to which to apply.
- */
-o3d.ParamMatrix4.prototype.applyToLocation = function(gl, location) {
- gl.uniformMatrix4fv(location,
- false,
- this.value);
-};
-
-/**
- * Called to specify the values of a uniform array.
- * @param {WebGLContext} gl The current context.
- * @param {!Array.<!WebGLUniformLocation>} locationArray An array of locations
- * to which to apply the values.
- */
-o3d.ParamParamArray.prototype.applyToLocations = function(gl, locationArray) {
- var computedValue = this.value;
- if (locationArray.length != computedValue.length) {
- gl.client.error_callback(
- 'Invalid uniform param array: incorrect number of elements.');
- }
- for (var i = 0; i < computedValue.length; i++) {
- // Cannot have a ParamArray of ParamArrays, so safe to call applyToLocation
- computedValue.getParam(i).applyToLocation(gl, locationArray[i]);
- }
-};
-
-/**
- * A counter to ensure each texture sampler gets a unqiue id.
- * @private
- */
-o3d.Param.texture_index_ = 0;
-
-/**
- * Called to specify the value of a uniform variable.
- * @param {WebGLContext} gl The current context.
- * @param {WebGLUniformLocation} location The location to which to apply.
- * @param {boolean} opt_isCube Optional boolean indicating whether the Sampler
- * connects to a samplerCube type uniform. If set to true, and there is an
- * error, we use the error cube map.
- */
-o3d.ParamSampler.prototype.applyToLocation =
- function(gl, location, opt_isCube) {
- // When before the effect object assigns values to parameters,
- // it sets this variable to 0.
- var i = o3d.Param.texture_index_;
- gl.activeTexture(gl.TEXTURE0 + i);
-
- var value = null;
- var target = 0;
- var sampler = null;
-
- if (this.value) {
- sampler = this.value;
- } else {
- o3d.Sampler.defaultSampler_.gl = gl;
- sampler = o3d.Sampler.defaultSampler_;
- if (gl.client.reportErrors_()) {
- gl.client.error_callback("Missing Sampler for ParamSampler " + this.name);
- }
- }
-
- sampler.bindAndSetParameters_(opt_isCube);
- gl.uniform1i(location, i);
- o3d.Param.texture_index_++;
-};
-
-/**
- * A default ParamSampler to be used if client does not assign one.
- *
- * @type {!o3d.ParamSampler}
- * @private
- */
-o3d.ParamSampler.defaultParamSampler_ = new o3d.ParamSampler();
-
-/**
- * Object to compute all combinations of world/view/projection
- * inverse/transpose matrices and provide them as parameters.
- *
- * @type {o3d.ParamObject}
- */
-o3d.Param.SAS = new o3d.ParamObject;
-
-/**
- * A map linking the names of SAS parameters to their standard matrix parameter
- * types.
- * @private
- */
-o3d.Param.sasTypes_ = {
- 'world': 'WorldParamMatrix4',
- 'view': 'ViewParamMatrix4',
- 'projection': 'ProjectionParamMatrix4',
- 'worldView': 'WorldViewParamMatrix4',
- 'viewProjection': 'ViewProjectionParamMatrix4',
- 'worldViewProjection': 'WorldViewProjectionParamMatrix4',
- 'worldInverse': 'WorldInverseParamMatrix4',
- 'viewInverse': 'ViewInverseParamMatrix4',
- 'projectionInverse': 'ProjectionInverseParamMatrix4',
- 'worldViewInverse': 'WorldViewInverseParamMatrix4',
- 'viewProjectionInverse': 'ViewProjectionInverseParamMatrix4',
- 'worldViewProjectionInverse': 'WorldViewProjectionInverseParamMatrix4',
- 'worldTranspose': 'WorldTransposeParamMatrix4',
- 'viewTranspose': 'ViewTransposeParamMatrix4',
- 'projectionTranspose': 'ProjectionTransposeParamMatrix4',
- 'worldViewTranspose': 'WorldViewTransposeParamMatrix4',
- 'viewProjectionTranspose': 'ViewProjectionTransposeParamMatrix4',
- 'worldViewProjectionTranspose': 'WorldViewProjectionTransposeParamMatrix4',
- 'worldInverseTranspose': 'WorldInverseTransposeParamMatrix4',
- 'viewInverseTranspose': 'ViewInverseTransposeParamMatrix4',
- 'projectionInverseTranspose': 'ProjectionInverseTransposeParamMatrix4',
- 'worldViewInverseTranspose': 'WorldViewInverseTransposeParamMatrix4',
- 'viewProjectionInverseTranspose':
- 'ViewProjectionInverseTransposeParamMatrix4',
- 'worldViewProjectionInverseTranspose':
- 'WorldViewProjectionInverseTransposeParamMatrix4'
-};
-
-for (name in o3d.Param.sasTypes_) {
- o3d.Param.SAS.createParam(name, o3d.Param.sasTypes_[name]);
-}
-
-/**
- * Sets the base world matrix that gets use to compute all other products for
- * SAS parameters.
- */
-o3d.Param.SAS.setWorld = function(world) {
- this['world'] = world;
-};
-
-/**
- * Sets the base world matrix that gets use to compute all other products for
- * SAS parameters.
- */
-o3d.Param.SAS.setView = function(view) {
- this['view'] = view;
-};
-
-/**
- * Sets the base world matrix that gets use to compute all other products for
- * SAS parameters.
- */
-o3d.Param.SAS.setProjection = function(projection) {
- this['projection'] = projection;
-};
-
-/**
- * Sets the viewProjection matrix.
- */
-o3d.Param.SAS.setViewProjection = function(viewProjection) {
- this['viewProjection'] = viewProjection;
-};
-
-/**
- * Sets the worldViewProjection matrix.
- */
-o3d.Param.SAS.setWorldViewProjection = function(worldViewProjection) {
- this['worldViewProjection'] = worldViewProjection;
-};
diff --git a/o3d/samples/o3d-webgl/param_array.js b/o3d/samples/o3d-webgl/param_array.js
deleted file mode 100644
index 236c45a..0000000
--- a/o3d/samples/o3d-webgl/param_array.js
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A ParamArray is an object that holds an array of Params.
- * @constructor
- */
-o3d.ParamArray = function() {
- o3d.NamedObject.call(this);
- this.params_ = [];
-};
-o3d.inherit('ParamArray', 'NamedObject');
-
-
-/**
- * Creates a Param of the given type at the index requested. If a Param already
- * exists at that index the new param will be replace it. If the index is past
- * the end of the current array params of the requested type will be created to
- * fill out the array to the requested index.
- *
- * @param {number} index Index at which to create new param.
- * @param {string} param_type_name The type of Param to create. For a list of
- * valid types see ParamObject.createParam
- * @return {!o3d.ParamArray} The newly created Param or null if failure.
- */
-o3d.ParamArray.prototype.createParam = function(index, param_type_name) {
- param_type_name = o3d.filterTypeName_(param_type_name);
- if (!o3d.global.o3d[param_type_name])
- throw ('Invalid param type name: ' + param_type_name);
- if (index >= this.params_.length) {
- this.resize(index + 1, param_type_name);
- } else {
- var param = new o3d.global.o3d[param_type_name];
- param.gl = this.gl;
- param.owner_ = this;
- this.params_[index] = param;
- }
-
- return this.filterResult_(this.params_[index]);
-};
-
-
-/**
- * Gets a Param by index.
- *
- * @param {number} index Index of Param to get.
- * @return {!o3d.Param} The Param at index, or null if out of range.
- */
-o3d.ParamArray.prototype.getParam = function(index) {
- var result = this.params_[index];
- return this.filterResult_(result);
-};
-
-
-/**
- * Removes a range of params. This shrinks the array and affects the indices of
- * later occurring items.
- *
- * @param {number} start_index Index of first param to remove.
- * @param {number} num_to_remove The number of params to remove starting at
- * start_index.
- */
-o3d.ParamArray.prototype.removeParams = function(start_index, num_to_remove) {
- var paramsNew = [];
- var j = 0;
- for (var i = 0; i < this.params_.length; i++) {
- if (i >= start_index && i < start_index + num_to_remove) {
- // Skip these to remove them.
- } else {
- paramsNew[j] = this.params_[i];
- j++;
- }
- }
- this.params_ = paramsNew;
-};
-
-
-/**
- * Resizes the array.
- *
- * @param {number} num_params The number of params to make the array.
- * @param {string} param_type_name The type of Param to create if resizing
- * requires params to be created. For a list of valid types see
- * ParamObject.createParam.
- */
-o3d.ParamArray.prototype.resize = function(num_params, param_type_name) {
- param_type_name = o3d.filterTypeName_(param_type_name);
- if (!o3d.global.o3d[param_type_name])
- throw ('Invalid param type name: ' + param_type_name);
-
- for (var i = this.params_.length; i < num_params; i++) {
- var param = new o3d.global.o3d[param_type_name];
- param.gl = this.gl;
- param.owner_ = this;
- this.params_[i] = param;
- }
-};
-
-/**
- * The params stored in this ParamArray.
- *
- * @type {!Array.<!o3d.Param>}
- * @private
- */
-o3d.ParamArray.prototype.params_ = [];
-
-/**
- * Gets all the param on this param object.
- *
- * Each access to this field gets the entire list, so it is best to get it
- * just once. For example:
- *
- * var params = ParamArray.params;
- * for (var i = 0; i < params.length; i++) {
- * var param = params[i];
- * }
- *
- * Note that modifications to this array [e.g. push()] will not affect
- * the underlying ParamArray, while modifications to the array's members
- * <b>will</b> affect them.
- *
- * @type {!Array.<!o3d.Param>}
- */
-o3d.ParamArray.prototype.__defineGetter__('params',
- function() {
- var params = [];
- for (var i = 0; i < this.length; i++) {
- params[i] = this.params_[i];
- }
- return params;
- }
-);
-
-
-/**
- * Returns the number of parameters in this ParamArray.
- *
- * @type {number}
- */
-o3d.ParamArray.prototype.__defineGetter__('length',
- function() {
- return this.params_.length;
- }
-);
-
-
-/**
- * Filters results, turning 'undefined' into 'null'.
- *
- * @param {*} result
- * @private
- */
-o3d.ParamArray.prototype.filterResult_= function(result) {
- return (result ? result : null);
-};
diff --git a/o3d/samples/o3d-webgl/param_object.js b/o3d/samples/o3d-webgl/param_object.js
deleted file mode 100644
index b57aecb..0000000
--- a/o3d/samples/o3d-webgl/param_object.js
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A ParamObject is the base class for all objects that can have Params.
- * Defines methods to add and remove params, search for params, etc.
- * @constructor
- */
-o3d.ParamObject = function() {
- o3d.NamedObject.call(this);
- this.params_ = {};
-};
-o3d.inherit('ParamObject', 'NamedObject');
-
-o3d.ParamObject.prototype.__defineGetter__('params',
- function() {
- var paramList = [];
- for (name in this.params_) {
- paramList.push(this.params_[name]);
- }
- return paramList;
- });
-
-o3d.ParamObject.prototype.__defineSetter__('params', function() {});
-
-o3d.ParamObject.O3D_PREFIX_ = 'o3d.';
-
-/**
- * Creates a Param with the given name and type on the ParamObject.
- * Will fail if a param with the same name already exists.
- *
- * @param {string} param_name The name of the Param to be created.
- * @param {string} param_type_name The type of Param to create.
- * Valid types are
- * 'ParamBoolean'
- * 'ParamBoundingBox'
- * 'ParamDrawContext'
- * 'ParamDrawList'
- * 'ParamEffect'
- * 'ParamFloat'
- * 'ParamFloat2'
- * 'ParamFloat3'
- * 'ParamFloat4'
- * 'ParamFunction'
- * 'ParamInteger'
- * 'ParamMaterial'
- * 'ParamMatrix4'
- * 'ParamParamArray'
- * 'ParamRenderSurface'
- * 'ParamRenderDepthStencilSurface'
- * 'ParamSampler'
- * 'ParamSkin'
- * 'ParamSteamBank'
- * 'ParamState'
- * 'ParamString'
- * 'ParamTexture'
- * 'ParamTransform'
- * 'ProjectionParamMatrix4'
- * 'ProjectionInverseParamMatrix4'
- * 'ProjectionTransposeParamMatrix4'
- * 'ProjectionInverseTransposeParamMatrix4'
- * 'ViewParamMatrix4'
- * 'ViewInverseParamMatrix4'
- * 'ViewTransposeParamMatrix4'
- * 'ViewInverseTransposeParamMatrix4'
- * 'ViewProjectionParamMatrix4'
- * 'ViewProjectionInverseParamMatrix4'
- * 'ViewProjectionTransposeParamMatrix4'
- * 'ViewProjectionInverseTransposeParamMatrix4'
- * 'WorldParamMatrix4'
- * 'WorldInverseParamMatrix4'
- * 'WorldTransposeParamMatrix4'
- * 'WorldInverseTransposeParamMatrix4'
- * 'WorldViewParamMatrix4'
- * 'WorldViewInverseParamMatrix4'
- * 'WorldViewTransposeParamMatrix4'
- * 'WorldViewInverseTransposeParamMatrix4'
- * 'WorldViewProjectionParamMatrix4'
- * 'WorldViewProjectionInverseParamMatrix4'
- * 'WorldViewProjectionTransposeParamMatrix4'
- * 'WorldViewProjectionInverseTransposeParamMatrix4'
- * @return {!o3d.Param} The newly created Param or null on failure.
- */
-o3d.ParamObject.prototype.createParam =
- function(param_name, param_type_name) {
- if (this.params_[param_name])
- return null;
- param_type_name = o3d.filterTypeName_(param_type_name);
- if (!o3d.global.o3d[param_type_name])
- throw ('Invalid param type name: ' + param_type_name);
- var param = new o3d.global.o3d[param_type_name];
- param.gl = this.gl;
- param.owner_ = this;
- param.name = param_name;
- this.params_[param_name] = param;
- return this.filterResult_(this.params_[param_name]);
-};
-
-
-/**
- * Searches by name for a Param defined in the object.
- *
- * @param {string} param_name Name to search for.
- * @return {!o3d.Param} The Param with the given name, or null otherwise.
- */
-o3d.ParamObject.prototype.getParam =
- function(param_name) {
- var result = this.params_[param_name];
- var o3d_name;
- if (!result) {
- // Try again with O3D prefix.
- o3d_name = o3d.ParamObject.O3D_PREFIX_ + param_name;
- result = this.params_[o3d_name];
- }
-
- if (!result) {
- // See if it's one of the params which needs to be created lazily.
- // If it is, initialize it with the current value in the object.
- var lazyParamMap = this.lazyParamMap_;
- if (lazyParamMap) {
- var name = param_name;
- var param_type = this.lazyParamMap_[name];
- if (!param_type) {
- name = o3d_name;
- param_type = this.lazyParamMap_[name];
- }
- if (param_type) {
- result = this.createParam(name, param_type);
- }
- }
- }
-
- return this.filterResult_(result);
-};
-
-
-/**
- * Removes a Param from a ParamObject.
- *
- * This function will fail if the param does not exist on this ParamObject
- * or if the param is unremovable.
- *
- * @param {!o3d.Param} param param to remove.
- * @return {boolean} True if the param was removed.
- */
-o3d.ParamObject.prototype.removeParam =
- function(param) {
- for (var i in this.params_) {
- if (this.params_[i] == param) {
- delete this.params_[i];
- }
- }
-};
-
-
-/**
- * Gets all the param on this param object.
- *
- * Each access to this field gets the entire list, so it is best to get it
- * just once. For example:
- *
- * var params = paramObject.params;
- * for (var i = 0; i < params.length; i++) {
- * var param = params[i];
- * }
- *
- * Note that modifications to this array [e.g. push()] will not affect
- * the underlying ParamObject, while modifications to the array's members
- * will affect them.
- */
-o3d.ParamObject.prototype.params_ = {};
-
-
-/**
- * Copies all the params from a the given source_param_object to this param
- * object. Does not replace any currently existing params with the same name.
- *
- * @param {o3d.ParamObject} source_param_object param object to copy params
- * from.
- */
-o3d.ParamObject.prototype.copyParams =
- function(source_param_object) {
- for (name in source_param_object.params_) {
- var param = source_param_object.params_[name];
- this.createParam(name, param.className);
- this.getParam(name).value = param.value;
- }
-};
-
-
-/**
- * Filters results, turning 'undefined' into 'null'.
- * @private
- */
-o3d.ParamObject.prototype.filterResult_= function(result) {
- return (result ? result : null);
-};
-
-
-/**
- * Sets up an o3d-scoped parameter against the given constructor
- * function of the given type for the given field.
- * @private
- */
-o3d.ParamObject.setUpO3DParam_ = function(constructor,
- fieldName,
- paramType) {
- var o3dParamName = o3d.ParamObject.O3D_PREFIX_ + fieldName;
-
- // The lazyParamMap primarily handles the case where getParam is
- // called before the getter or setter below. It also simplifies the
- // code below since it can simply call getParam and the param will
- // be created on demand.
- var lazyParamMap = constructor.prototype.lazyParamMap_;
- if (!lazyParamMap) {
- lazyParamMap = {};
- constructor.prototype.lazyParamMap_ = lazyParamMap;
- }
- lazyParamMap[o3dParamName] = paramType;
-
- constructor.prototype.__defineGetter__(fieldName,
- function() {
- var param = this.getParam(o3dParamName);
- return param.value;
- });
- constructor.prototype.__defineSetter__(fieldName,
- function(v) {
- var param = this.getParam(o3dParamName);
- param.value = v;
- });
-};
-
diff --git a/o3d/samples/o3d-webgl/param_operation.js b/o3d/samples/o3d-webgl/param_operation.js
deleted file mode 100644
index 172f537..0000000
--- a/o3d/samples/o3d-webgl/param_operation.js
+++ /dev/null
@@ -1,513 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * Acts like ParamFloat, but has an unsettable value which always calls
- * this.owner_.updateOutputs to find the updated output value.
- * @constructor
- * @extends {o3d.ParamFloat}
- */
-o3d.ParamFloatOutput = function() {
- o3d.ParamFloat.call(this);
-};
-o3d.inherit('ParamFloatOutput', 'ParamFloat');
-o3d.ParamFloatOutput.prototype.__defineGetter__("value",
- function() {
- return this.owner_.updateOutputs();
- }
-);
-o3d.ParamFloatOutput.prototype.__defineSetter__("value",
- function(value) {}
-);
-
-/**
- * Acts like ParamFloat2, but has an unsettable value which always calls
- * this.owner_.updateOutputs to find the updated output value.
- * @constructor
- * @extends {o3d.ParamFloat2}
- */
-o3d.ParamFloat2Output = function() {
- o3d.ParamFloat2.call(this);
-};
-o3d.inherit('ParamFloat2Output', 'ParamFloat2');
-o3d.ParamFloat2Output.prototype.__defineGetter__("value",
- function() {
- return this.owner_.updateOutputs();
- }
-);
-o3d.ParamFloat2Output.prototype.__defineSetter__("value",
- function(value) {}
-);
-
-/**
- * Acts like ParamFloat3, but has an unsettable value which always calls
- * this.owner_.updateOutputs to find the updated output value.
- * @constructor
- * @extends {o3d.ParamFloat3}
- */
-o3d.ParamFloat3Output = function() {
- o3d.ParamFloat3.call(this);
-};
-o3d.inherit('ParamFloat3Output', 'ParamFloat3');
-o3d.ParamFloat3Output.prototype.__defineGetter__("value",
- function() {
- return this.owner_.updateOutputs();
- }
-);
-o3d.ParamFloat3Output.prototype.__defineSetter__("value",
- function(value) {}
-);
-
-/**
- * Acts like ParamFloat4, but has an unsettable value which always calls
- * this.owner_.updateOutputs to find the updated output value.
- * @constructor
- * @extends {o3d.ParamFloat4}
- */
-o3d.ParamFloat4Output = function() {
- o3d.ParamFloat4.call(this);
-};
-o3d.inherit('ParamFloat4Output', 'ParamFloat4');
-o3d.ParamFloat4Output.prototype.__defineGetter__("value",
- function() {
- return this.owner_.updateOutputs();
- }
-);
-o3d.ParamFloat4Output.prototype.__defineSetter__("value",
- function(value) {}
-);
-
-/**
- * Acts like ParamMatrix4, but has an unsettable value which always calls
- * this.owner_.updateOutputs to find the updated output value.
- * @constructor
- * @extends {o3d.ParamMatrix4}
- */
-o3d.ParamMatrix4Output = function() {
- o3d.ParamMatrix4.call(this);
-};
-o3d.inherit('ParamMatrix4Output', 'ParamMatrix4');
-o3d.ParamMatrix4Output.prototype.__defineGetter__("value",
- function() {
- return this.owner_.updateOutputs();
- }
-);
-o3d.ParamMatrix4Output.prototype.__defineSetter__("value",
- function(value) {}
-);
-
-/**
- * A Param operation that takes 2 floats to produce a float2.
- * @constructor
- * @extends {o3d.ParamObject}
- */
-o3d.ParamOp2FloatsToFloat2 = function() {
- o3d.ParamObject.call(this);
- this.last_output_value_ = [0, 0];
-};
-o3d.inherit('ParamOp2FloatsToFloat2', 'ParamObject');
-
-(function(){
- for (var i = 0; i < 2; i++) {
- o3d.ParamObject.setUpO3DParam_(
- o3d.ParamOp2FloatsToFloat2, "input"+i, "ParamFloat");
- }
- o3d.ParamObject.setUpO3DParam_(
- o3d.ParamOp2FloatsToFloat2, "output", "ParamMatrix4Output");
-})();
-
-/**
- * Called by o3d.Param*Output whenever its value gets read.
- * @return {!Array.<number>} 2-element array equal to [input0, input1]
- */
-o3d.ParamOp2FloatsToFloat2.prototype.updateOutputs = function() {
- this.last_output_value_[0] = this.getParam("input0").value;
- this.last_output_value_[1] = this.getParam("input1").value;
- return this.last_output_value_;
-};
-
-/**
- * A Param operation that takes 3 floats to produce a float3.
- * @constructor
- * @extends {o3d.ParamObject}
- */
-o3d.ParamOp3FloatsToFloat3 = function() {
- o3d.ParamObject.call(this);
- this.last_output_value_ = [0, 0, 0];
-};
-o3d.inherit('ParamOp3FloatsToFloat3', 'ParamObject');
-
-(function(){
- for (var i = 0; i < 3; i++) {
- o3d.ParamObject.setUpO3DParam_(
- o3d.ParamOp3FloatsToFloat3, "input"+i, "ParamFloat");
- }
- o3d.ParamObject.setUpO3DParam_(
- o3d.ParamOp3FloatsToFloat3, "output", "ParamMatrix4Output");
-})();
-
-/**
- * Called by o3d.Param*Output whenever its value gets read.
- * @return {!Array.<number>} 3-element array equal to [input0,input1,input2]
- */
-o3d.ParamOp3FloatsToFloat3.prototype.updateOutputs = function() {
- this.last_output_value_[0] = this.getParam("input0").value;
- this.last_output_value_[1] = this.getParam("input1").value;
- this.last_output_value_[2] = this.getParam("input2").value;
- return this.last_output_value_;
-};
-
-/**
- * A Param operation that takes 4 floats to produce a float4.
- * @constructor
- * @extends {o3d.ParamObject}
- */
-o3d.ParamOp4FloatsToFloat4 = function() {
- o3d.ParamObject.call(this);
- this.last_output_value_ = [0, 0, 0, 0];
-};
-o3d.inherit('ParamOp4FloatsToFloat4', 'ParamObject');
-
-(function(){
- for (var i = 0; i < 4; i++) {
- o3d.ParamObject.setUpO3DParam_(
- o3d.ParamOp4FloatsToFloat4, "input"+i, "ParamFloat");
- }
- o3d.ParamObject.setUpO3DParam_(
- o3d.ParamOp4FloatsToFloat4, "output", "ParamMatrix4Output");
-})();
-
-/**
- * Called by o3d.Param*Output whenever its value gets read.
- * @return {!Array.<number>} 4-element array equal to
- * [input0,input1,input2,input3]
- */
-o3d.ParamOp4FloatsToFloat4.prototype.updateOutputs = function() {
- this.last_output_value_[0] = this.getParam("input0").value;
- this.last_output_value_[1] = this.getParam("input1").value;
- this.last_output_value_[2] = this.getParam("input2").value;
- this.last_output_value_[3] = this.getParam("input3").value;
- return this.last_output_value_;
-};
-
-/**
- * A Param operation that takes 16 floats to produce a 4-by-4 matrix.
- * @constructor
- * @extends {o3d.ParamObject}
- */
-o3d.ParamOp16FloatsToMatrix4 = function() {
- o3d.ParamObject.call(this);
- this.last_output_value_ = o3d.Transform.makeIdentityMatrix4_();
-};
-o3d.inherit('ParamOp16FloatsToMatrix4', 'ParamObject');
-
-(function(){
- for (var i = 0; i < 16; i++) {
- o3d.ParamObject.setUpO3DParam_(
- o3d.ParamOp16FloatsToMatrix4, "input"+i, "ParamFloat");
- }
- o3d.ParamObject.setUpO3DParam_(
- o3d.ParamOp16FloatsToMatrix4, "output", "ParamMatrix4Output");
-})();
-
-/**
- * Called by o3d.Param*Output whenever its value gets read.
- * @return {!Array<!Array<number>>} 4x4 array equal to
- * [i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15]
- */
-o3d.ParamOp16FloatsToMatrix4.prototype.updateOutputs = function() {
- for (var i = 0; i < 16; i++) {
- this.last_output_value_[i] =
- this.getParam("input"+i).value;
- }
- return this.last_output_value_;
-};
-
-/**
- * A Param operation that takes 9 floats to produce a 4-by-4 matrix.
- * The 9 floats encode a translation vector, angles of rotation around
- * the x, y, and z axes, and three scaling factors. The resulting
- * transformation scales first, then then rotates around the z-axis,
- * then the y-axis, then the x-axis, then translates.
- * @param {string} name Tne name of the parameter.
- * @param {string} className The param class name.
- * @param {number} numElements The number of Elements if the param is an array.
- * @param {string} sasClassName The sas class name if the param is an sas type.
- * @param {string} semantic The relevant semantic.
- * @constructor
- * @extends {o3d.ParamObject}
- */
-o3d.TRSToMatrix4 = function() {
- o3d.ParamObject.call(this);
-
- this.rotateX = 0;
- this.rotateY = 0;
- this.rotateZ = 0;
-
- this.translateX = 0;
- this.translateY = 0;
- this.translateZ = 0;
-
- this.scaleX = 1;
- this.scaleY = 1;
- this.scaleZ = 1;
-
- this.last_output_value_ = o3d.Transform.makeIdentityMatrix4_();
-};
-o3d.inherit('TRSToMatrix4', 'ParamObject');
-
-(function(){
- var proplist = ["rotateX", "rotateY", "rotateZ",
- "translateX", "translateY", "translateZ",
- "scaleX", "scaleY", "scaleZ"];
- for (var i = 0; i < proplist.length; i++) {
- o3d.ParamObject.setUpO3DParam_(o3d.TRSToMatrix4, proplist[i], "ParamFloat");
- }
- o3d.ParamObject.setUpO3DParam_(
- o3d.TRSToMatrix4, "output", "ParamMatrix4Output");
-})();
-
-/**
- * Called by o3d.Param*Output whenever its value gets read.
- * @return {!Array.<!Array.<number>>} Matrix4 equal to applying the operations
- * in the order Translate * Rotate * Scale.
- */
-o3d.TRSToMatrix4.prototype.updateOutputs = function () {
- var ret = this.last_output_value_;
- var rX = this.rotateX;
- var rY = this.rotateY;
- var rZ = this.rotateZ;
- var sX = this.scaleX;
- var sY = this.scaleY;
- var sZ = this.scaleZ;
- var sinX = Math.sin(rX);
- var cosX = Math.cos(rX);
- var sinY = Math.sin(rY);
- var cosY = Math.cos(rY);
- var sinZ = Math.sin(rZ);
- var cosZ = Math.cos(rZ);
- var cosZSinY = cosZ * sinY;
- var sinZSinY = sinZ * sinY;
-
- ret[0] = cosZ * cosY * sX;
- ret[1] = sinZ * cosY * sX;
- ret[2] = -sinY * sX;
- ret[3] = 0;
- ret[4] = (cosZSinY * sinX - sinZ * cosX) * sY;
- ret[5] = (sinZSinY * sinX + cosZ * cosX) * sY;
- ret[6] = cosY * sinX * sY,
- ret[7] = 0;
- ret[8] = (cosZSinY * cosX + sinZ * sinX) * sZ;
- ret[9] = (sinZSinY * cosX - cosZ * sinX) * sZ;
- ret[10] = cosY * cosX * sZ;
- ret[11] = 0;
- ret[12] = this.translateX;
- ret[13] = this.translateY;
- ret[14] = this.translateZ;
- ret[15] = 1;
- return ret;
-};
-
-/**
- * A Param operation that takes an input matrix and a local matrix
- * to produce an output matrix.
- * @constructor
- * @extends {o3d.ParamObject}
- */
-o3d.Matrix4Composition = function() {
- o3d.ParamObject.call(this);
- this.last_output_value_ = o3d.Transform.makeIdentityMatrix4_();
-};
-o3d.inherit('Matrix4Composition', 'ParamObject');
-
-o3d.ParamObject.setUpO3DParam_(
- o3d.Matrix4Composition, "inputMatrix", "ParamMatrix4");
-
-o3d.ParamObject.setUpO3DParam_(
- o3d.Matrix4Composition, "localMatrix", "ParamMatrix4");
-
-o3d.ParamObject.setUpO3DParam_(
- o3d.Matrix4Composition, "outputMatrix", "ParamMatrix4Output");
-
-/**
- * Called by o3d.Param*Output whenever its value gets read.
- * @return {!Array<!Array<number>>} 4x4 array equal to
- * inputMatrix * localMatrix.
- */
-o3d.Matrix4Composition.prototype.updateOutputs = function() {
- var input = this.getParam("inputMatrix").value;
- var local = this.getParam("localMatrix").value;
- o3d.Transform.compose_(input, local, this.last_output_value_);
- return this.last_output_value_;
-};
-
-
-/**
- * A Param operation that takes an input matrix, a float3 axis and an angle
- * to produce an output matrix.
- * @constructor
- * @extends {o3d.ParamObject}
- */
-o3d.Matrix4AxisRotation = function() {
- o3d.ParamObject.call(this);
- this.last_output_value_ =
- [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
-};
-o3d.inherit('Matrix4AxisRotation', 'ParamObject');
-
-o3d.ParamObject.setUpO3DParam_(
- o3d.Matrix4AxisRotation, "inputMatrix", "ParamMatrix4");
-
-o3d.ParamObject.setUpO3DParam_(
- o3d.Matrix4AxisRotation, "axis", "ParamFloat3");
-
-o3d.ParamObject.setUpO3DParam_(
- o3d.Matrix4AxisRotation, "angle", "ParamFloat");
-
-o3d.ParamObject.setUpO3DParam_(
- o3d.Matrix4AxisRotation, "outputMatrix", "ParamMatrix4Output");
-
-/**
- * Called by o3d.Param*Output whenever its value gets read.
- * @return {!Array.<!Array.<number>>} 4x4 array from rotating inputMatrix around
- * axis by angle.
- */
-o3d.Matrix4AxisRotation.prototype.updateOutputs = function() {
- var input = this.getParam("inputMatrix").value;
- var axis = this.getParam("axis").value;
- var angle = this.getParam("angle").value;
- o3d.Transform.axisRotateMatrix_(input, axis, angle, this.last_output_value_);
- return this.last_output_value_;
-};
-
-
-/**
- * A Param operation that takes an input matrix and a float3 scale
- * to produce an output matrix.
- * @constructor
- * @extends {o3d.ParamObject}
- */
-o3d.Matrix4Scale = function() {
- o3d.ParamObject.call(this);
- this.last_output_value_ =
- [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
-};
-o3d.inherit('Matrix4Scale', 'ParamObject');
-
-o3d.ParamObject.setUpO3DParam_(
- o3d.Matrix4Scale, "inputMatrix", "ParamMatrix4");
-
-o3d.ParamObject.setUpO3DParam_(
- o3d.Matrix4Scale, "scale", "ParamFloat3");
-
-o3d.ParamObject.setUpO3DParam_(
- o3d.Matrix4Scale, "outputMatrix", "ParamMatrix4Output");
-
-/**
- * Called by o3d.Param*Output whenever its value gets read.
- * @return {!Array.<!Array.<number>>} 4x4 array from scaling inputMatrix by
- * scale.
- */
-o3d.Matrix4Scale.prototype.updateOutputs = function() {
- var m = this.getParam("inputMatrix").value;
- var ret = this.last_output_value_;
- var v = this.getParam("scale").value;
-
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
-
- var m0 = m[0];
- var m1 = m[1];
- var m2 = m[2];
- var m3 = m[3];
-
- ret[0].splice(0, 4, v0 * m0[0], v0 * m0[1], v0 * m0[2], v0 * m0[3]);
- ret[1].splice(0, 4, v1 * m1[0], v1 * m1[1], v1 * m1[2], v1 * m1[3]);
- ret[2].splice(0, 4, v2 * m2[0], v2 * m2[1], v2 * m2[2], v2 * m2[3]);
- ret[3] = m3.slice(0);
- return ret;
-};
-
-
-/**
- * A Param operation that takes an input matrix, and a translation
- * to produce an output matrix.
- * @constructor
- * @extends {o3d.ParamObject}
- */
-o3d.Matrix4Translation = function() {
- o3d.ParamObject.call(this);
- this.last_output_value_ =
- [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
-};
-o3d.inherit('Matrix4Translation', 'ParamObject');
-
-o3d.ParamObject.setUpO3DParam_(
- o3d.Matrix4Translation, "inputMatrix", "ParamMatrix4");
-
-o3d.ParamObject.setUpO3DParam_(
- o3d.Matrix4Translation, "translation", "ParamFloat3");
-
-o3d.ParamObject.setUpO3DParam_(
- o3d.Matrix4Translation, "outputMatrix", "ParamMatrix4Output");
-
-/**
- * Called by o3d.Param*Output whenever its value gets read.
- * @return {!Array.<!Array.<number>>} 4x4 array from translating inputMatrix
- * by translation.
- */
-o3d.Matrix4Translation.prototype.updateOutputs = function() {
- var m = this.getParam("inputMatrix").value;
- var ret = this.last_output_value_;
- var v = this.getParam("translation").value;
-
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
-
- var m0 = m[0];
- var m1 = m[1];
- var m2 = m[2];
- var m3 = m[3];
-
- ret[0] = m0.slice(0);
- ret[1] = m1.slice(0);
- ret[2] = m2.slice(0);
- ret[3].splice(0, 4, m0[0] * v0 + m1[0] * v1 + m2[0] * v2 + m3[0],
- m0[1] * v0 + m1[1] * v1 + m2[1] * v2 + m3[1],
- m0[2] * v0 + m1[2] * v1 + m2[2] * v2 + m3[2],
- m0[3] * v0 + m1[3] * v1 + m2[3] * v2 + m3[3]);
- return ret;
-};
-
-
diff --git a/o3d/samples/o3d-webgl/primitive.js b/o3d/samples/o3d-webgl/primitive.js
deleted file mode 100644
index 5bf122b..0000000
--- a/o3d/samples/o3d-webgl/primitive.js
+++ /dev/null
@@ -1,594 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A Primitive is a type of Element that is made from a list of points,
- * lines or triangles that use a single material.
- *
- * @param opt_streamBank o3d.StreamBank The StreamBank used by this
- * Primitive.
- * @constructor
- */
-o3d.Primitive = function(opt_streamBank) {
- o3d.Element.call(this);
-
- /**
- * The index buffer for the primitive. If null the primitive is non-indexed.
- * @type {o3d.IndexBuffer}
- */
- this.indexBuffer = null;
-
- /**
- * The stream bank this primitive uses for vertices.
- * @type {o3d.StreamBank}
- */
- this.streamBank = opt_streamBank || null;
-
- /**
- * The type of primitive the primitive is (i.e., POINTLIST, LINELIST,
- * TRIANGLELIST, etc.)
- *
- * @type {o3d.Primitive.Type}
- */
- this.primitiveType = o3d.Primitive.TRIANGLELIST;
-
- /**
- * The number of vertices the primitive has.
- *
- * @type {number}
- */
- this.numberVertices = 0;
-
- /**
- * The number of rendering primitives (i.e., triangles, points, lines) the
- * primitive has.
- *
- * @type {number}
- */
- this.numberPrimitives = 0;
-
- /**
- * The index of the first vertex to render.
- *
- * @type {number}
- */
- this.startIndex = 0;
-
- /**
- * The index buffer for the wireframe version of the primitive.
- * @type {o3d.IndexBuffer}
- * @private
- */
- this.wireframeIndexBuffer_ = null;
-};
-o3d.inherit('Primitive', 'Element');
-
-
-/**
- * @type {number}
- */
-o3d.Primitive.Type = goog.typedef;
-
-/**
- * Type of geometric primitives used by the Primitive.
- */
-o3d.Primitive.POINTLIST = 1;
-o3d.Primitive.LINELIST = 2;
-o3d.Primitive.LINESTRIP = 3;
-o3d.Primitive.TRIANGLELIST = 4;
-o3d.Primitive.TRIANGLESTRIP = 5;
-o3d.Primitive.TRIANGLEFAN = 6;
-
-o3d.ParamObject.setUpO3DParam_(o3d.Primitive, 'streamBank', 'ParamStreamBank');
-
-/**
- * Binds the vertex and index streams required to draw the shape.
- */
-o3d.Primitive.prototype.render = function() {
- var streamBank = this.streamBank;
- var indexBuffer = this.indexBuffer;
-
- var enabled_attribs = [];
-
- for (var semantic = 0;
- semantic < streamBank.vertex_streams_.length;
- ++semantic) {
- var streams = streamBank.vertex_streams_[semantic];
- if (streams && streams.length) {
- for (var semantic_index = 0;
- semantic_index < streams.length;
- ++semantic_index) {
- var gl_index = o3d.Effect.reverseSemanticMap_[semantic][semantic_index];
- var stream = streams[semantic_index].stream;
- var field = stream.field;
- var buffer = field.buffer;
-
- if (gl_index == undefined) {
- this.gl.client.error_callback('uknown semantic');
- }
-
- var stream_param = streams[semantic_index];
- while (!stream_param.owner_.updateStreams &&
- stream_param.inputConnection) {
- stream_param = stream_param.inputConnection;
- }
- if (stream_param.owner_.updateStreams) {
- // By now, stream_param should point to the SkinEval's streams.
- stream_param.owner_.updateStreams(); // Triggers updating.
- }
-
- this.gl.bindBuffer(this.gl.ARRAY_BUFFER, buffer.gl_buffer_);
- this.gl.enableVertexAttribArray(gl_index);
- enabled_attribs.push(gl_index);
-
- // HACK: Firefox 4.0b4+ missing BYTES_PER_ELEMENT
- var kFloatSize = Float32Array.BYTES_PER_ELEMENT || 4;
-
- this.gl.vertexAttribPointer(
- gl_index, field.numComponents, this.gl.FLOAT, false,
- buffer.totalComponents * kFloatSize, field.offset_ * kFloatSize);
- }
- }
- }
-
- this.gl.client.render_stats_['primitivesRendered'] += this.numberPrimitives;
-
- var glMode;
- var glNumElements;
-
- switch (this.primitiveType) {
- case o3d.Primitive.POINTLIST:
- glMode = this.gl.POINTS;
- glNumElements = this.numberPrimitives;
- break;
- case o3d.Primitive.LINELIST:
- glMode = this.gl.LINES;
- glNumElements = this.numberPrimitives * 2;
- break;
- case o3d.Primitive.LINESTRIP:
- glMode = this.gl.LINE_STRIP;
- glNumElements = this.numberPrimitives + 1;
- break;
- case o3d.Primitive.TRIANGLELIST:
- glMode = this.gl.TRIANGLES;
- glNumElements = this.numberPrimitives * 3;
- break;
- case o3d.Primitive.TRIANGLESTRIP:
- glMode = this.gl.TRIANGLE_STRIP;
- glNumElements = this.numberPrimitives + 2;
- break;
- case o3d.Primitive.TRIANGLEFAN:
- glMode = this.gl.TRIANGLE_FAN;
- glNumElements = this.numberPrimitives + 2;
- break;
- case o3d.Primitive.TRIANGLELIST:
- default:
- glMode = this.gl.TRIANGLES;
- glNumElements = this.numberPrimitives * 3;
- break;
- }
-
- var use_wireframe_indices = false;
-
- if (this.gl.fillMode_ == o3d.State.POINT) {
- // If the fill mode is points, then we just replace the gl primitive type
- // with POINTS and let the (possibly redundant) list of points draw.
- glMode = this.gl.POINTS;
- } else if (this.gl.fillMode_ == o3d.State.WIREFRAME) {
- // If the fill mode is lines, and the primitive type is some kind of
- // triangle, then we need to reorder indices to draw the right thing.
-
- if (this.primitiveType == o3d.Primitive.TRIANGLELIST ||
- this.primitiveType == o3d.Primitive.TRIANGLEFAN ||
- this.primitiveType == o3d.Primitive.TRIANGLESTRIP) {
- use_wireframe_indices = true;
- glMode = this.gl.LINES;
- this.computeWireframeIndices_();
- }
- }
-
- if (use_wireframe_indices) {
- indexBuffer = this.wireframeIndexBuffer_;
-
- switch(this.primitiveType) {
- default:
- case o3d.Primitive.TRIANGLELIST:
- glNumElements = this.numberPrimitives * 6;
- break;
- case o3d.Primitive.TRIANGLESTRIP:
- case o3d.Primitive.TRIANGLEFAN:
- glNumElements = (this.numberPrimitives == 0) ? 0 :
- this.numberPrimitives * 4 + 2;
- break;
- }
- }
-
- if (!indexBuffer) {
- this.gl.drawArrays(glMode, 0, glNumElements);
- } else {
- this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, indexBuffer.gl_buffer_);
- this.gl.drawElements(glMode,
- glNumElements,
- this.gl.UNSIGNED_SHORT,
- 0);
- }
-
- for (var i = 0; i < enabled_attribs.length; ++i) {
- this.gl.disableVertexAttribArray(enabled_attribs[i]);
- }
-};
-
-
-/**
- * Given n, gets index number n in the index buffer if there is an index buffer
- * otherwise returns n.
- * @param {number} n The number of the entry in the index buffer.
- * @return {return} The index.
- * @private
- */
-o3d.Primitive.prototype.getIndex_ = function(n) {
- if (this.indexBuffer) {
- return this.indexBuffer.array_[n]
- }
- return n;
-};
-
-
-/**
- * Generates an index buffer for a wireframe outline of a triangle-based
- * primitive.
- * @private
- */
-o3d.Primitive.prototype.computeWireframeIndices_ = function() {
- this.wireframeIndexBuffer_ = new o3d.IndexBuffer;
- this.wireframeIndexBuffer_.gl = this.gl;
-
- var numTriangles = this.numberPrimitives;
- var numLines = (this.primitiveType == o3d.Primitive.TRIANGLELIST) ?
- (3 * numTriangles) : (2 * numTriangles + 1);
-
- this.wireframeIndexBuffer_.resize(2 * numLines);
-
- var j = 0; // The current index in wireframeIndices.
- switch (this.primitiveType) {
- default:
- case o3d.Primitive.TRIANGLELIST: {
- var wireframeIndices = this.wireframeIndexBuffer_.array_;
- this.wireframeIndexBuffer_.lock();
- // Iterate through triangles.
- for (var i = 0; i < numTriangles; ++i) {
- // Indices the vertices of the triangle a, b, c.
- var a = this.getIndex_(3 * i);
- var b = this.getIndex_(3 * i + 1);
- var c = this.getIndex_(3 * i + 2);
- wireframeIndices[j++] = a;
- wireframeIndices[j++] = b;
- wireframeIndices[j++] = b;
- wireframeIndices[j++] = c;
- wireframeIndices[j++] = c;
- wireframeIndices[j++] = a;
- }
- this.wireframeIndexBuffer_.unlock();
- }
- break;
-
- case o3d.Primitive.TRIANGLEFAN: {
- var wireframeIndices = this.wireframeIndexBuffer_.array_;
- this.wireframeIndexBuffer_.lock();
- // The first two points make a line.
- var z;
- if (numTriangles > 0) {
- z = this.getIndex_(0);
- wireframeIndices[j++] = z;
- wireframeIndices[j++] = this.getIndex_(1);
- }
- // Each additional point forms a new triangle by adding two lines.
- for (var i = 2; i < numTriangles + 2; ++i) {
- var a = this.getIndex_(i);
- wireframeIndices[j++] = z;
- wireframeIndices[j++] = a;
- wireframeIndices[j++] = a;
- wireframeIndices[j++] = this.getIndex_(i - 1);
- }
- this.wireframeIndexBuffer_.unlock();
- }
- break;
-
- case o3d.Primitive.TRIANGLESTRIP: {
- var wireframeIndices = this.wireframeIndexBuffer_.array_;
- this.wireframeIndexBuffer_.lock();
- // The frist two points make a line.
- var a;
- var b;
- if (numTriangles > 0) {
- a = this.getIndex_(0);
- b = this.getIndex_(1);
- wireframeIndices[j++] = a;
- wireframeIndices[j++] = b;
- }
- // Each additional point forms a new triangle by adding two lines.
- for (var i = 2; i < numTriangles + 2; ++i) {
- var c = this.getIndex_(i);
- wireframeIndices[j++] = b;
- wireframeIndices[j++] = c;
- wireframeIndices[j++] = c;
- wireframeIndices[j++] = a;
- a = b;
- b = c;
- }
- this.wireframeIndexBuffer_.unlock();
- }
- break;
- }
-};
-
-/**
- * Returns the three indices of the n-th triangle of this primitive. If the
- * primitive has no index buffer, then the buffer is assumed to be [0 ... n-1].
- * These indices can then be used to reference the vertex buffer and get the
- * triangle vertices' positions.
- *
- * @param {number} n The number of the triangle we want. Zero-indexed.
- * @return {!Array.<Number>} Array containing three indices that correspond to
- * the n-th triangle of this primitive.
- * @private
- */
-o3d.Primitive.prototype.computeTriangleIndices_ = function(n) {
- var indices;
- switch (this.primitiveType) {
- case o3d.Primitive.TRIANGLESTRIP:
- if (n % 2 == 0) {
- indices = [n, n + 1, n + 2];
- } else {
- indices = [n + 1, n, n + 2];
- }
- break;
- case o3d.Primitive.TRIANGLEFAN:
- indices = [0, n + 1, n + 2];
- break;
- case o3d.Primitive.TRIANGLELIST:
- default:
- indices = [3 * n, 3 * n + 1, 3 * n + 2];
- break;
- }
- if (this.indexBuffer) {
- var buffer = this.indexBuffer.array_;
- return [buffer[indices[0]],
- buffer[indices[1]],
- buffer[indices[2]]];
- } else {
- return indices;
- }
-};
-
-/**
- * Computes the intersection of a ray in the coordinate system of
- * the specified POSITION stream.
- * @param {number} position_stream_index Index of POSITION stream.
- * @param {o3d.Cull} cull which side of the triangles to ignore.
- * @param {!o3d.math.Point3} start position of start of ray in local space.
- * @param {!o3d.math.Point3} end position of end of ray. in local space.
- * @return {!o3d.RayIntersectionInfo} RayIntersectionInfo class. If valid()
- * is false then something was wrong, Check GetLastError(). If
- * intersected() is true then the ray intersected a something. position()
- * is the exact point of intersection.
- */
-o3d.Primitive.prototype.intersectRay =
- function(position_stream_index, cull, start, end) {
- var result = new o3d.RayIntersectionInfo;
- result.valid = true;
-
- var streamBank = this.streamBank;
- var indexBuffer = this.indexBuffer;
- var positionStreams = this.streamBank.vertex_streams_[o3d.Stream.POSITION];
- var stream = positionStreams[position_stream_index].stream;
-
- var field = stream.field;
- var buffer = field.buffer;
- var numPoints = buffer.array_.length / buffer.totalComponents;
- var elements = field.getAt(0, numPoints);
-
- // The direction of the vector of the ray.
- var x = end[0] - start[0];
- var y = end[1] - start[1];
- var z = end[2] - start[2];
-
- // Find two vectors orthogonal to direction for use in quickly eliminating
- // triangles which can't possibly intersect the ray.
- var direction = [x, y, z];
-
- // Pick a vector orthogonal to direction called u.
- var ux = -y;
- var uy = x;
- var uz = 0;
- if (x * x + y * y < z * z) {
- ux = -z;
- uy = 0;
- uz = x;
- }
-
- // Cross product direction and u get a third orthogonal vector v.
- var vx = y * uz - z * uy;
- var vy = z * ux - x * uz;
- var vz = x * uy - y * ux;
-
- var udotstart = ux * start[0] + uy * start[1] + uz * start[2];
- var vdotstart = vx * start[0] + vy * start[1] + vz * start[2];
-
- // As we search for an intersection point, we keep track of how far out
- // from the start the point with this variable.
- var min_distance = 0;
-
- // Iterate through the indices and examine triples of indices that each
- // define a triangle. For each triangle, we test for intersection with
- // the ray. We need to find the closest one to start, so we have to
- // check them all.
-
- var numIndices = indexBuffer ? indexBuffer.array_.length : numPoints;
- switch (this.primitiveType) {
- case o3d.Primitive.TRIANGLESTRIP:
- numTriangles = numIndices - 2;
- break;
- case o3d.Primitive.TRIANGLEFAN:
- numTriangles = numIndices - 2;
- break;
- case o3d.Primitive.TRIANGLELIST:
- default:
- numTriangles = numIndices / 3;
- break;
- }
-
- for (var i = 0; i < numTriangles; ++i) {
- var indices = this.computeTriangleIndices_(i);
-
- // Check if the current triangle is too far to one side of the ray
- // to intersect at all. (This is what the orthogonal vectors are for)
- var u_sides = [false, false, false];
- var v_sides = [false, false, false];
- for (var j = 0; j < 3; ++j) {
- var t = 3 * indices[j];
- var r = elements.slice(t, t + 3);
- u_sides[j] = ux * r[0] + uy * r[1] + uz * r[2] - udotstart > 0;
- v_sides[j] = vx * r[0] + vy * r[1] + vz * r[2] - vdotstart > 0;
- }
-
- // All vertices of the triangle are on the same side of the start point,
- // the ray cannot intersect, so we move on.
- if (((u_sides[0] == u_sides[1]) && (u_sides[0] == u_sides[2])) ||
- ((v_sides[0] == v_sides[1]) && (v_sides[0] == v_sides[2]))) {
- continue;
- }
-
- // Compute a matrix that transforms the unit triangle
- // (1, 0, 0)..(0, 1, 0)..(0, 0, 1) into the current triangle.
- var t;
- t = 3 * indices[0];
- var m00 = elements[t] - start[0];
- var m01 = elements[t + 1] - start[1];
- var m02 = elements[t + 2] - start[2];
- t = 3 * indices[1];
- var m10 = elements[t] - start[0];
- var m11 = elements[t + 1] - start[1];
- var m12 = elements[t + 2] - start[2];
- t = 3 * indices[2];
- var m20 = elements[t] - start[0];
- var m21 = elements[t + 1] - start[1];
- var m22 = elements[t + 2] - start[2];
-
- var t00 = m11 * m22 - m12 * m21;
- var t10 = m01 * m22 - m02 * m21;
- var t20 = m01 * m12 - m02 * m11;
-
- // Compute the determinant of the matrix. The sign (+/-) tells us
- // if it's culled.
- var d = m00 * t00 - m10 * t10 + m20 * t20;
-
- if ((cull == o3d.State.CULL_CW && d < 0) ||
- (cull == o3d.State.CULL_CCW && d > 0)) {
- continue;
- }
-
- // Transform the direction vector by the inverse of that matrix.
- // If the end point is in the first octant, it's a hit.
- var v0 = (t00 * x -
- (m10 * m22 - m12 * m20) * y +
- (m10 * m21 - m11 * m20) * z) / d;
- var v1 = (-t10 * x +
- (m00 * m22 - m02 * m20) * y -
- (m00 * m21 - m01 * m20) * z) / d;
- var v2 = (t20 * x -
- (m00 * m12 - m02 * m10) * y +
- (m00 * m11 - m01 * m10) * z) / d;
-
- if (v0 >= 0 && v1 >= 0 && v2 >= 0 && (v0 + v1 + v2 > 0)) {
- // Rescale by the one-norm to find the intersection of the transformed.
- // ray with the unit triangle.
- var one_norm = v0 + v1 + v2;
- v0 /= one_norm;
- v1 /= one_norm;
- v2 /= one_norm;
- // Multiply m to get back to the original triangle.
- var px = m00 * v0 + m10 * v1 + m20 * v2;
- var py = m01 * v0 + m11 * v1 + m21 * v2;
- var pz = m02 * v0 + m12 * v1 + m22 * v2;
- // Compute the distance (actually distance squared) from the start point
- // to the intersection.
- var distance = px * px + py * py + pz * pz;
- if (!result.intersected || distance < min_distance) {
- min_distance = distance;
- result.position[0] = px + start[0];
- result.position[1] = py + start[1];
- result.position[2] = pz + start[2];
- result.primitiveIndex = i;
- }
- result.intersected = true;
- }
- }
-
- return result;
-};
-
-
-/**
- * Computes the bounding box in same coordinate system as the specified
- * POSITION stream.
- * @param {number} position_stream_index Index of POSITION stream.
- * @return {!o3d.BoundingBox} The boundingbox for this element in local space.
- */
-o3d.Primitive.prototype.getBoundingBox =
- function(position_stream_index) {
- var streamBank = this.streamBank;
- var indexBuffer = this.indexBuffer;
- var stream =
- this.streamBank.getVertexStream(o3d.Stream.POSITION, position_stream_index);
-
- var points = [];
- var field = stream.field;
- var buffer = field.buffer;
- var numPoints = buffer.array_.length / buffer.totalComponents;
-
- var elements = field.getAt(0, numPoints);
-
- for (var index = 0; index < numPoints; ++index) {
- var p = [0, 0, 0];
- for (var i = 0; i < field.numComponents; ++i) {
- p[i] = elements[field.numComponents * index + i];
- }
- points.push(p);
- }
-
- o3d.BoundingBox.fitBoxToPoints_(points, this.boundingBox);
- return this.boundingBox;
-};
-
-
-
diff --git a/o3d/samples/o3d-webgl/raw_data.js b/o3d/samples/o3d-webgl/raw_data.js
deleted file mode 100644
index c1b48df..0000000
--- a/o3d/samples/o3d-webgl/raw_data.js
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A RawData object contains raw binary data which could contain
- * image, audio, text, or other information.
- *
- * var request = g_pack.createArchiveRequest();
- *
- * request.onfileavailable = function(rawData) {
- * var texture = g_pack.createTextureFromRawData(rawData, true);
- * ...
- * };
- *
- * request.send();
- * @constructor
- */
-o3d.RawData = function() {
- o3d.NamedObject.call(this);
-};
-o3d.inherit('RawData', 'NamedObject');
-
-
-/**
- * Returns the raw data as a string. The data must be a valid utf-8 string
- * and the uri must end in .json, .txt, .xml, .ini or .csv
- * @type {string}
- */
-o3d.RawData.prototype.stringValue = '';
-
-
-/**
- * The data as an image if it is an image.
- * @type {Image}
- * @private
- */
-o3d.RawData.prototype.image_ = null;
-
-
-/**
- * The uri of the RawData.
- * @type {string}
- */
-o3d.RawData.prototype.uri = '';
-
-
-
-/**
- * The length in bytes of the RawData.
- * @type {number}
- */
-o3d.RawData.prototype.length = 0;
-
-
-
-/**
- * Discards all the resources associated with this data object.
- */
-o3d.RawData.prototype.discard = function() {
- o3d.notImplemented();
-};
-
-
-
-/**
- * Flushes the memory resources associated with this data object,
- * but keeps a cache in case the data object is used later.
- */
-o3d.RawData.prototype.flush = function() {
- o3d.notImplemented();
-};
-
-
-
diff --git a/o3d/samples/o3d-webgl/ray_intersection_info.js b/o3d/samples/o3d-webgl/ray_intersection_info.js
deleted file mode 100644
index ae9f22e..0000000
--- a/o3d/samples/o3d-webgl/ray_intersection_info.js
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A RayIntersectionInfo is used to return the results of ray intersection
- * tests.
- * @constructor
- */
-o3d.RayIntersectionInfo = function() {
- o3d.NamedObject.call(this);
- o3d.RayIntersectionInfo.prototype.position = [0, 0, 0];
-};
-o3d.inherit('RayIntersectionInfo', 'NamedObject');
-
-
-/**
- * True if this ray intersection info is valid. For example if you call
- * element.intersectRay on an element that has no vertex buffers the result
- * will be invalid.
- * @type {boolean}
- */
-o3d.RayIntersectionInfo.prototype.valid = false;
-
-
-/**
- * True if the origin of the ray is found to be inside the box.
- * @type {boolean}
- */
-o3d.RayIntersectionInfo.prototype.inside = false;
-
-
-/**
- * True if this ray intersection intersected something.
- * @type {boolean}
- */
-o3d.RayIntersectionInfo.prototype.intersected = false;
-
-
-
-/**
- * The position the ray intersected something.
- * type {!o3d.Point3}
- */
-o3d.RayIntersectionInfo.prototype.position = [0, 0, 0];
-
-
-
-/**
- * The index of the primitive that was intersected.
- * @type {number}
- */
-o3d.RayIntersectionInfo.prototype.primitiveIndex = -1;
-
-
-
diff --git a/o3d/samples/o3d-webgl/render_node.js b/o3d/samples/o3d-webgl/render_node.js
deleted file mode 100644
index 0c2dc53..0000000
--- a/o3d/samples/o3d-webgl/render_node.js
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * RenderNode is the base of all RenderNodes in the render graph.
- * RenderNodes are rendered in order of priority.
- *
- * @param {number} opt_priority The priority of this render node. Lower
- * priorities are rendered first.
- * @param {boolean} opt_active If true this node is processed. If false
- * it is not.
- * @constructor
- */
-o3d.RenderNode = function(opt_priority, opt_active) {
- o3d.ParamObject.call(this);
-
- /**
- * Sets the priority of this render node. lower priorities are
- * rendered first.
- *
- * @type {number}
- */
- this.priority = opt_priority || 0;
-
- /**
- * The immediate children of this RenderNode.
- *
- * Each access to this field gets the entire list so it is best to get it
- * just once. For example:
- *
- * var children = renderNode.children;
- * for (var i = 0; i < children.length; i++) {
- * var child = children[i];
- * }
- *
- * Note that modifications to this array [e.g. push()] will not affect
- * the underlying RenderNode, while modifications to the array's members
- * will affect them.
- *
- * @type {!Array.<o3d.RenderNode>}
- */
- this.children = [];
-
- /**
- * Setting false skips this render node. Setting true processes this render
- * node. (ie, renders whatever it's supposed to render)
- *
- * @type {boolean}
- */
- this.active = opt_active || true;
-
- /**
- * Sets the parent of the node by re-parenting the node under parent_node.
- * Setting parent_node to null removes the node and the entire subtree below
- * it from the render graph.
- *
- * @type {o3d.RenderNode}
- */
- this.parent = null;
-};
-o3d.inherit('RenderNode','ParamObject');
-
-o3d.ParamObject.setUpO3DParam_(o3d.RenderNode, 'priority', 'ParamFloat');
-o3d.ParamObject.setUpO3DParam_(o3d.RenderNode, 'active', 'ParamBoolean');
-
-o3d.RenderNode.prototype.__defineSetter__('parent',
- function(p) {
- if (this.parent_) {
- this.parent_.removeChild(this);
- }
- this.parent_ = p;
- if (this.parent_) {
- if (!this.parent_.addChild) {
- throw ('Parent of render node must be render node or null.');
- }
- this.parent_.addChild(this);
- }
- }
-);
-
-o3d.RenderNode.prototype.__defineGetter__('parent',
- function(p) {
- return this.parent_;
- }
-);
-
-/**
- * Adds a child node.
- * @param {o3d.RenderNode} child The child to add.
- */
-o3d.RenderNode.prototype.addChild = function(child) {
- this.children.push(child);
-};
-
-
-/**
- * Removes a child node.
- * @param {o3d.RenderNode} child The child to add.
- */
-o3d.RenderNode.prototype.removeChild = function(child) {
- o3d.removeFromArray(this.children, child);
-};
-
-
-/**
- * Returns this render node and all its descendants. Note that this render node
- * might not be in the render graph.
- *
- * Note that modifications to this array [e.g. push()] will not affect
- * the underlying RenderNode, while modifications to the array's members
- * will affect them.
- *
- * An array containing all render nodes of the subtree.
- */
-o3d.RenderNode.prototype.getRenderNodesInTree =
- function() {
- o3d.notImplemented();
-};
-
-
-
-/**
- * Searches for render nodes that match the given name in the hierarchy under
- * and including this render node. Since there can be several render nodes
- * with a given name the results are returned in an array.
- *
- * Note that modifications to this array [e.g. push()] will not affect
- * the underlying RenderNode, while modifications to the array's members
- * will affect them.
- *
- * @param {string} name Rendernode name to look for.
- * @return {Array.<!o3d.RenderNode>} An array containing all nodes among
- * this node and its decendants that have the given name.
- */
-o3d.RenderNode.prototype.getRenderNodesByNameInTree =
- function(name) {
- o3d.notImplemented();
-};
-
-
-/**
- * Searches for render nodes that match the given class name in the hierarchy
- * under and including this render node.
- *
- * Note that modifications to this array [e.g. push()] will not affect
- * the underlying RenderNode, while modifications to the array's members
- * will affect them.
- *
- * @param {string} class_name class name to look for.
- * @return {Array.<!o3d.RenderNode>} An array containing all nodes among
- * this node and its decendants whose type is class_name.
- */
-o3d.RenderNode.prototype.getRenderNodesByClassNameInTree =
- function(class_name) {
- o3d.notImplemented();
-};
-
-
-/**
- * Recursively traverses the render graph starting at this node.
- */
-o3d.RenderNode.prototype.render = function() {
- function compare(a, b) {
- return a.priority - b.priority;
- }
- this.children.sort(compare);
- var children = this.children;
-
- this.before();
- for (var i = 0; i < children.length; ++i) {
- children[i].render();
- }
- this.after();
-};
-
-
-/**
- * Called during the rendergraph traversal before the children are rendered.
- */
-o3d.RenderNode.prototype.before = function() { };
-
-
-/**
- * Called during the rendergraph traversal after the children are rendered.
- */
-o3d.RenderNode.prototype.after = function() { };
-
-
diff --git a/o3d/samples/o3d-webgl/render_surface.js b/o3d/samples/o3d-webgl/render_surface.js
deleted file mode 100644
index 4eefa06..0000000
--- a/o3d/samples/o3d-webgl/render_surface.js
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A RenderSurfaceBase is the base for RenderSurface and
- * RenderDepthStencilSurface.
- *
- * @param {number} width The width of this RenderSurface.
- * @param {number} height The height of this RenderSurface.
- * @param {o3d.Texture} texture The texture of this RenderSurface.
- * @constructor
- */
-o3d.RenderSurfaceBase = function(width, height, texture) {
- o3d.ParamObject.call(this);
-
- /**
- * The width of the surface, in pixels.
- * @type {number}
- */
- this.width = width || 0;
-
- /**
- * The height of the surface, in pixels.
- * @type {number}
- */
- this.height = height || 0;
-
- /**
- * The texture in which this surface is contained.
- */
- this.texture = texture || null;
-
- /**
- * The mip level targeted by this render surface.
- * @type {number}
- */
- this.level = 0;
-
- /**
- * The underlying GL framebuffer object.
- * @type {WebGLFramebuffer}
- * @private
- */
- this.framebuffer_ = null;
-
-};
-o3d.inherit('RenderSurfaceBase', 'ParamObject');
-
-o3d.ParamObject.setUpO3DParam_(o3d.RenderSurfaceBase, 'width', 'ParamInteger');
-o3d.ParamObject.setUpO3DParam_(o3d.RenderSurfaceBase, 'height', 'ParamInteger');
-
-/**
- * A RenderSurface encapsulates the notion of a renderable surface.
- * When used in conjunction with a RenderSurfaceSet node in the render graph,
- * the API allows for rendering of primitives to the given surface.
- * RenderSurface objects are not constructable through the Pack API, they may
- * only be accessed through the texture getRenderSurface(...) interfaces.
- * @constructor
- */
-o3d.RenderSurface = function() {
- o3d.RenderSurfaceBase.call(this);
-};
-o3d.inherit('RenderSurface', 'RenderSurfaceBase');
-
-
-/**
- * Initializes a render surface to render to the given texture.
- * @param {o3d.Texture2D} texture The texture.
- */
-o3d.RenderSurface.prototype.initWithTexture = function(texture, level) {
- this.framebuffer_ = this.gl.createFramebuffer();
- this.texture = texture;
- this.level = level;
- this.width = texture.width;
- this.height = texture.height;
-};
-
-/**
- * A RenderDepthStencilSurface represents a depth stencil render surface.
- * @constructor
- */
-o3d.RenderDepthStencilSurface = function() {
- o3d.RenderSurfaceBase.call(this);
-
- /**
- * The GL renderbuffer object for the depth / stencil buffer.
- * @type {WebGLRenderbuffer}
- * @private
- */
- this.depth_stencil_buffer_ = null;
-};
-o3d.inherit('RenderDepthStencilSurface', 'RenderSurfaceBase');
-
-
-/**
- * Allocates depth and stnecil buffers of the given size.
- * @param {number} width
- * @param {number} height
- * @private
- */
-o3d.RenderDepthStencilSurface.prototype.initWithSize_ =
- function(width, height) {
- this.depth_stencil_buffer_ = this.gl.createRenderbuffer();
- this.gl.bindRenderbuffer(this.gl.RENDERBUFFER, this.depth_stencil_buffer_);
- this.gl.renderbufferStorage(
- this.gl.RENDERBUFFER, this.gl.DEPTH_COMPONENT16, width, height);
- this.width = width;
- this.height = height;
-};
diff --git a/o3d/samples/o3d-webgl/render_surface_set.js b/o3d/samples/o3d-webgl/render_surface_set.js
deleted file mode 100644
index 694e290..0000000
--- a/o3d/samples/o3d-webgl/render_surface_set.js
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A RenderSurfaceSet node will bind depth and color RenderSurface nodes
- * to the current rendering context. All RenderNodes descending
- * from the given RenderSurfaceSet node will operate on the contents of
- * the bound depth and color buffers.
- * Note the following usage constraints of this node:
- * 1) If both a color and depth surface is bound, then they must be of
- * matching dimensions.
- * 2) At least one of render_surface and render_depth_surface must non-null.
- *
- * @param {o3d.RenderSurface} opt_renderSurface The render surface to set.
- * @param {o3d.RenderDepthStencilSurface} opt_renderDepthStencilSurface The
- * depth stencil render surface to set.
- * @constructor
- */
-o3d.RenderSurfaceSet =
- function(opt_renderSurface, opt_renderDepthStencilSurface) {
- o3d.RenderNode.call(this);
-
- /**
- * The render surface to which the color contents of all RenderNode children
- * should be drawn.
- * @type {o3d.RenderSurface}
- */
- this.renderSurface = opt_renderSurface || null;
-
-
- /**
- * The render depth stencil surface to which the depth contents of all
- * RenderNode children should be drawn.
- * @type {o3d.RenderDepthStencilSurface}
- */
- this.renderDepthStencilSurface = opt_renderDepthStencilSurface || null;
-};
-o3d.inherit('RenderSurfaceSet', 'RenderNode');
-
-
-o3d.ParamObject.setUpO3DParam_(o3d.RenderSurfaceSet,
- 'renderSurface', 'ParamRenderSurface');
-o3d.ParamObject.setUpO3DParam_(o3d.RenderSurfaceSet,
- 'renderDepthStencilSurface',
- 'ParamRenderDepthStencilSurface');
-
-/**
- * Helper function to set the framebuffer back to the default one.
- * @private
- */
-o3d.RenderSurfaceSet.prototype.clearFramebufferObjects_ =
- function() {
- this.gl.bindFramebuffer(
- this.gl.FRAMEBUFFER, this.renderSurface.framebuffer_);
-
- this.gl.framebufferRenderbuffer(
- this.gl.FRAMEBUFFER,
- this.gl.COLOR_ATTACHMENT0,
- this.gl.RENDERBUFFER,
- null);
-
- this.gl.framebufferRenderbuffer(
- this.gl.FRAMEBUFFER,
- this.gl.DEPTH_ATTACHMENT,
- this.gl.RENDERBUFFER,
- null);
-
- this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null);
-};
-
-
-/**
- * Helper function to set up both the color and depth-stencil targets.
- * @private
- */
-o3d.RenderSurfaceSet.prototype.installFramebufferObjects_ =
- function() {
- // Reset the bound attachments to the current framebuffer object.
- this.clearFramebufferObjects_();
-
- this.gl.bindFramebuffer(
- this.gl.FRAMEBUFFER, this.renderSurface.framebuffer_);
-
- if (this.renderSurface) {
- var texture = this.renderSurface.texture.texture_;
- var level = this.renderSurface.level;
-
- // TODO(petersont): If it's a cube, this call should be different.
- this.gl.bindTexture(this.gl.TEXTURE_2D, texture);
- this.gl.framebufferTexture2D(
- this.gl.FRAMEBUFFER,
- this.gl.COLOR_ATTACHMENT0,
- this.gl.TEXTURE_2D,
- texture,
- level);
- }
-
- if (this.renderDepthStencilSurface) {
- var depth_stencil_buffer =
- this.renderDepthStencilSurface.depth_stencil_buffer_;
-
- // TODO(petersont): In the WebGL spec, there is a depth-stencil
- // attachment, but it hasn't been implemented yet, once it is,
- // this should use one of those.
- this.gl.bindRenderbuffer(this.gl.RENDERBUFFER, depth_stencil_buffer);
- this.gl.framebufferRenderbuffer(
- this.gl.FRAMEBUFFER,
- this.gl.DEPTH_ATTACHMENT,
- this.gl.RENDERBUFFER,
- depth_stencil_buffer);
- }
-};
-
-
-/**
- * Called during the rendergraph traversal before the children are rendered.
- * @private
- */
-o3d.RenderSurfaceSet.prototype.before = function() {
- this.installFramebufferObjects_();
- this.previousHeight = this.gl.displayInfo.height;
- this.previousWidth = this.gl.displayInfo.width;
- this.previousRenderSurfaceSet = this.gl.currentRenderSurfaceSet;
- this.gl.displayInfo.height = this.renderSurface.height;
- this.gl.displayInfo.width = this.renderSurface.width;
- this.gl.currentRenderSurfaceSet = this;
-};
-
-
-/**
- * Called during the rendergraph traversal after the children are rendered.
- * @private
- */
-o3d.RenderSurfaceSet.prototype.after = function() {
- this.clearFramebufferObjects_();
- this.gl.displayInfo.height = this.previousHeight;
- this.gl.displayInfo.width = this.previousWidth;
- // This is consumed in effect.js.
- this.gl.currentRenderSurfaceSet = this.previousRenderSurfaceSet;
-};
-
-
diff --git a/o3d/samples/o3d-webgl/sampler.js b/o3d/samples/o3d-webgl/sampler.js
deleted file mode 100644
index 60f94c0..0000000
--- a/o3d/samples/o3d-webgl/sampler.js
+++ /dev/null
@@ -1,291 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * Sampler is the base of all texture samplers. Texture samplers encapsulate
- * a texture reference with a set of states that define how the texture
- * gets applied to a surface. Sampler states are set either via Params defined
- * on the Sampler object or directly via one the convenience methods defined
- * on the Sampler. The following states are supported (default values are in
- * parenthesis):
- * \li 'addressModeU' (WRAP)
- * \li 'addressModeV' (WRAP)
- * \li 'addressModeW' (WRAP)
- * \li 'magFilter' (LINEAR)
- * \li 'minFilter' (LINEAR)
- * \li 'mipFilter' (POINT)
- * \li 'borderColor' ([0,0,0,0])
- * \li 'maxAnisotropy' (1)
- */
-o3d.Sampler = function() {
- o3d.ParamObject.call(this);
-
- /**
- * The texture address mode for the u coordinate.
- * @type {!o3d.Sampler.AddressMode}
- */
- this.addressModeU = o3d.Sampler.WRAP;
-
- /**
- * The texture address mode for the v coordinate.
- * @type {!o3d.Sampler.AddressMode}
- */
- this.addressModeV = o3d.Sampler.WRAP;
-
- /**
- * The texture address mode for the w coordinate.
- * @type {!o3d.Sampler.AddressMode}
- */
- this.addressModeW = o3d.Sampler.WRAP;
-
- /**
- * The magnification filter. Valid values for the mag filter are:
- * POINT and LINEAR. Default = LINEAR.
- * @type {!o3d.Sampler.FilterType}
- */
- this.magFilter = o3d.Sampler.LINEAR;
-
- /**
- * The minification filter. Valid values for the min filter are:
- * POINT, LINEAR and ANISOTROPIC. Default = LINEAR.
- * @type {!o3d.Sampler.FilterType}
- */
- this.minFilter = o3d.Sampler.LINEAR;
-
- /**
- * The mipmap filter used during minification. Valid values for the
- * mip filter are: NONE, POINT and LINEAR. Default = LINEAR.
- * @type {!o3d.Sampler.FilterType}
- */
- this.mipFilter = o3d.Sampler.LINEAR;
-
- /**
- * Color returned for texture coordinates outside the [0,1] range when the
- * address mode is set to BORDER.
- * @type {!Array.<number>}
- */
- this.borderColor = [0, 0, 0, 0];
-
- /**
- * Degree of anisotropy used when the ANISOTROPIC filter type is used.
- * @type {number}
- */
- this.maxAnisotropy = 1;
-
- /**
- * The Texture object used by this Sampler.
- * @type {o3d.Texture}
- */
- this.texture = null;
-};
-o3d.inherit('Sampler', 'ParamObject');
-
-
-
-/**
- * @type {number}
- */
-o3d.Sampler.AddressMode = goog.typedef;
-
-
-/**
- * AddressMode,
- * Controls what happens with texture coordinates outside the [0..1] range.
- * WRAP
- * MIRROR
- * CLAMP
- * BORDER
- */
-o3d.Sampler.WRAP = 0;
-o3d.Sampler.MIRROR = 1;
-o3d.Sampler.CLAMP = 2;
-o3d.Sampler.BORDER = 3;
-
-
-/**
- * @type {number}
- */
-o3d.Sampler.FilterType = goog.typedef;
-
-/**
- * FilterType,
- * Texture filtering types.
- * NONE
- * POINT
- * LINEAR
- * ANISOTROPIC
- */
-o3d.Sampler.NONE = 0;
-o3d.Sampler.POINT = 1;
-o3d.Sampler.LINEAR = 2;
-o3d.Sampler.ANISOTROPIC = 3;
-
-
-o3d.ParamObject.setUpO3DParam_(o3d.Sampler, 'addressModeU', 'ParamInteger');
-o3d.ParamObject.setUpO3DParam_(o3d.Sampler, 'addressModeV', 'ParamInteger');
-o3d.ParamObject.setUpO3DParam_(o3d.Sampler, 'addressModeW', 'ParamInteger');
-o3d.ParamObject.setUpO3DParam_(o3d.Sampler, 'magFilter', 'ParamInteger');
-o3d.ParamObject.setUpO3DParam_(o3d.Sampler, 'minFilter', 'ParamInteger');
-o3d.ParamObject.setUpO3DParam_(o3d.Sampler, 'mipFilter', 'ParamInteger');
-o3d.ParamObject.setUpO3DParam_(o3d.Sampler, 'borderColor', 'ParamFloat4');
-o3d.ParamObject.setUpO3DParam_(o3d.Sampler, 'maxAnisotropy', 'ParamInteger');
-o3d.ParamObject.setUpO3DParam_(o3d.Sampler, 'texture', 'ParamTexture');
-
-
-/**
- * Converts the addressing mode of the sampler from an o3d constant to a webgl
- * constant.
- * @param {!o3d.Sampler.AddressMode} o3d_mode, the O3D addressing mode.
- * @return {number} The webgl mode.
- */
-o3d.Sampler.prototype.convertAddressMode_ = function(o3d_mode) {
- var gl_mode = this.gl.REPEAT;
- switch (o3d_mode) {
- case o3d.Sampler.WRAP:
- gl_mode = this.gl.REPEAT;
- break;
- case o3d.Sampler.MIRROR:
- gl_mode = this.gl.MIRRORED_REPEAT;
- break;
- case o3d.Sampler.CLAMP:
- gl_mode = this.gl.CLAMP_TO_EDGE;
- break;
- case o3d.Sampler.BORDER:
- // This is not supported in WebGL.
- default:
- this.gl.client.error_callback("Unknown/Unavailable Address mode");
- break;
- }
- return gl_mode;
-}
-
-
-/**
- * Converts the min filter mode of the sampler from an o3d constant to a webgl
- * constant.
- * @param {!o3d.Sampler.FilterType} o3d_filter, the O3D filter.
- * @param {!o3d.Sampler.FilterType} mip_filter, the O3D mip filter.
- * @return {number} The webgl filter.
- */
-o3d.Sampler.prototype.convertMinFilter_ = function(o3d_filter, mip_filter) {
- switch (o3d_filter) {
- case o3d.Sampler.NONE:
- return this.gl.NEAREST;
- case o3d.Sampler.POINT:
- if (mip_filter == o3d.Sampler.NONE) {
- return this.gl.NEAREST;
- } else if (mip_filter == o3d.Sampler.POINT) {
- return this.gl.NEAREST_MIPMAP_NEAREST;
- } else if (mip_filter == o3d.Sampler.LINEAR) {
- return this.gl.NEAREST_MIPMAP_LINEAR;
- } else if (mip_filter == o3d.Sampler.ANISOTROPIC) {
- return this.gl.NEAREST_MIPMAP_LINEAR;
- }
- case o3d.Sampler.ANISOTROPIC:
- case o3d.Sampler.LINEAR:
- if (mip_filter == o3d.Sampler.NONE) {
- return this.gl.LINEAR;
- } else if (mip_filter == o3d.Sampler.POINT) {
- return this.gl.LINEAR_MIPMAP_NEAREST;
- } else if (mip_filter == o3d.Sampler.LINEAR) {
- return this.gl.LINEAR_MIPMAP_LINEAR;
- } else if (mip_filter == o3d.Sampler.ANISOTROPIC) {
- return this.gl.LINEAR_MIPMAP_LINEAR;
- }
- }
-
- this.gl.client.error_callback("Unknown filter.");
- return this.gl.NONE;
-}
-
-
-/**
- * Converts the mag filter mode of the sampler from an o3d constant to a webgl
- * constant.
- * @param {!o3d.Sampler.FilterType} o3d_filter, the O3D filter.
- * @return {number} The webgl filter.
- */
-o3d.Sampler.prototype.convertMagFilter_ = function(o3d_filter) {
- switch (o3d_filter) {
- case o3d.Sampler.NONE:
- case o3d.Sampler.POINT:
- return this.gl.NEAREST;
- case o3d.Sampler.LINEAR:
- case o3d.Sampler.ANISOTROPIC:
- return this.gl.LINEAR;
- }
- this.gl.client.error_callback("Unknown filter.");
- return this.gl.LINEAR;
-}
-
-
-/**
- * A default Sampler that has no texture, thus uses the client's error texture.
- *
- * @type {!o3d.Sampler}
- * @private
- */
-o3d.Sampler.defaultSampler_ = new o3d.Sampler();
-o3d.Sampler.defaultSampler_.magFilter = o3d.Sampler.POINT;
-
-/**
- * Binds the texture for this sampler and sets texParameters according to the
- * states of the sampler.
- * @param {boolean} opt_isCube Optional boolean indicating if this is a cube
- * map, so we can use the right error texture.
- */
-o3d.Sampler.prototype.bindAndSetParameters_ = function(opt_isCube) {
- var currentTexture = null;
- if (this.texture) {
- currentTexture = this.texture;
- } else if (!this.gl.client.reportErrors_()) {
- if (opt_isCube) {
- currentTexture = this.gl.client.error_texture_cube_;
- } else {
- currentTexture = this.gl.client.error_texture_;
- }
- } else {
- currentTexture = this.gl.client.fallback_error_texture_;
- this.gl.client.error_callback("Missing texture for sampler " + this.name);
- }
-
- var mip_filter = this.mipFilter;
- if (currentTexture.levels == 1) {
- mip_filter = o3d.Sampler.NONE;
- }
- currentTexture.bindAndSetParameters_(
- this.convertAddressMode_(this.addressModeU),
- this.convertAddressMode_(this.addressModeV),
- this.convertMinFilter_(this.minFilter, mip_filter),
- this.convertMagFilter_(this.magFilter));
-}
-
diff --git a/o3d/samples/o3d-webgl/shape.js b/o3d/samples/o3d-webgl/shape.js
deleted file mode 100644
index 8823f83..0000000
--- a/o3d/samples/o3d-webgl/shape.js
+++ /dev/null
@@ -1,191 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * The Shape represents a collection of Elements. The typical example is a
- * cube with 6 faces where each face uses a different material would be
- * represented as 1 Shape with 6 Elements, one for each material.
- * @constructor
- */
-o3d.Shape = function() {
- o3d.ParamObject.call(this);
- this.elements = [];
-};
-o3d.inherit('Shape', 'ParamObject');
-
-
-/**
- * The elements owned by this shape.
- *
- * Each access to this field gets the entire list so it is best to get it
- * just once. For example:
- *
- * var elements = renderNode.elements;
- * for (var i = 0; i < elements.length; i++) {
- * var element = elements[i];
- * }
- *
- * Note that modifications to this array [e.g. push()] will not affect
- * the underlying Shape, while modifications to the array's members
- * will affect them.
- */
-o3d.Shape.prototype.elements = [];
-
-
-/**
- * Finds a draw element in the given list of draw elements that uses the given
- * material if such a draw element exists. Returns null otherwise.
- * @param {Array.<!o3d.DrawElements>} drawElements An array of draw elements.
- * @param {o3d.Material} material A material to search for.
- * @private
- */
-o3d.Shape.findDrawElementWithMaterial_ = function(drawElements, material) {
- for (var j = 0; j < drawElements.length; ++j) {
- if (drawElements[j].material == material) {
- return drawElements[j];
- }
- }
- return null;
-};
-
-
-/**
- * Creates a DrawElement for each Element owned by this Shape.
- * If an Element already has a DrawElement that uses material a new
- * DrawElement will not be created.
- * @param {o3d.Pack} pack pack used to manage created DrawElements.
- * @param {o3d.Material} material material to use for each DrawElement.
- * Note: When a DrawElement with a material of null is rendered, the
- * material on the corresponding Element will get used instead.
- * This allows you to easily setup the default (just draw as is) by
- * passing null or setup a shadow pass by passing in a shadow material.
- */
-o3d.Shape.prototype.createDrawElements =
- function(pack, material) {
- var elements = this.elements;
- for (var i = 0; i < elements.length; ++i) {
- var element = elements[i];
- if (!o3d.Shape.findDrawElementWithMaterial_(element.drawElements,
- material)) {
- element.createDrawElement(pack, material);
- }
- }
-};
-
-
-/**
- * Adds and element to the list of elements for this shape.
- * @param {o3d.Element} element The element to add.
- */
-o3d.Shape.prototype.addElement = function(element) {
- this.elements.push(element);
-};
-
-
-/**
- * Removes and element to the list of elements for this shape.
- * @param {o3d.Element} element The element to add.
- */
-o3d.Shape.prototype.removeElement = function(element) {
- o3d.removeFromArray(this.elements, element);
-};
-
-
-/**
- * Called when the tree traversal finds this shape in the transform tree.
- * Adds objects to the given drawlists if the drawlist of the material matches.
- * @param {Array.<Object>} drawListInfos A list of objects containing
- * drawlists and matrix info.
- * @param {o3d.math.Matrix4} world The world matrix.
- */
-o3d.Shape.prototype.writeToDrawLists =
- function(drawListInfos, world, transform) {
- var elements = this.elements;
-
- // Iterate through elements of this shape.
- for (var i = 0; i < elements.length; ++i) {
- var element = elements[i];
-
- // For each element look at the DrawElements for that element.
- for (var j = 0; j < element.drawElements.length; ++j) {
- this.gl.client.render_stats_['drawElementsProcessed']++;
- var drawElement = element.drawElements[j];
- var material = drawElement.material || drawElement.owner.material;
- var materialDrawList = material.drawList;
- var rendered = false;
-
- // Iterate through the drawlists we might write to.
- for (var k = 0; k < drawListInfos.length; ++k) {
- var drawListInfo = drawListInfos[k];
- var list = drawListInfo.list;
-
- // If any of those drawlists matches the material on the drawElement,
- // add the drawElement to the list.
- if (materialDrawList == list) {
- var context = drawListInfo.context;
- var view = context.view;
- var projection = context.projection;
-
- var worldViewProjection = o3d.Transform.makeIdentityMatrix4_();
- var viewProjection = o3d.Transform.makeIdentityMatrix4_();
- o3d.Transform.compose_(projection, view, viewProjection);
- o3d.Transform.compose_(viewProjection, world, worldViewProjection);
-
- if (element.cull && element.boundingBox) {
- if (!element.boundingBox.inFrustum(worldViewProjection)) {
- continue;
- }
- }
-
- rendered = true;
- list.list_.push({
- view: view,
- projection: projection,
- world: world,
- viewProjection: viewProjection,
- worldViewProjection: worldViewProjection,
- transform: transform,
- drawElement: drawElement
- });
- }
- }
-
- if (rendered) {
- this.gl.client.render_stats_['drawElementsRendered']++;
- } else {
- this.gl.client.render_stats_['drawElementsCulled']++;
- }
- }
- }
-};
-
-
diff --git a/o3d/samples/o3d-webgl/skin.js b/o3d/samples/o3d-webgl/skin.js
deleted file mode 100644
index abd77c6..0000000
--- a/o3d/samples/o3d-webgl/skin.js
+++ /dev/null
@@ -1,931 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A Skin holds an array of matrix indices and influences for vertices in a
- * skin. A Skin is data only and can be used by one or more SkinEvals to
- * implement skinning.
- *
- * @constructor
- * @extends {o3d.NamedObject}
- */
-o3d.Skin = function() {
- o3d.NamedObject.call(this);
-
- /**
- * Set of influences contained in this skin.
- * @type {!Array<!Array<number>>}
- */
- this.influences = [];
-
- /**
- * The array of inverse bone matrices (Array<matrix4>)
- *
- * @type {!Array<!Array<!Array<number>>>}
- */
- this.inverseBindPoseMatrices = [];
-
- /**
- * Whether the getHighestMatrixIndex and getHighestInfluences are up-to-date.
- *
- * @type {boolean}
- * @private
- */
- this.info_valid_ = false;
-
- /**
- * Cache of getHighestMatrixIndex().
- *
- * @type {number}
- * @private
- */
- this.highest_matrix_index_ = 0;
-
- /**
- * Cache of getHighestInfluences().
- *
- * @type {number}
- * @private
- */
- this.highest_influences_ = 0;
-
- /**
- * True if the list of weights and matrix index streams could be downloaded.
- *
- * @type {boolean}
- * @private
- */
- this.supports_vertex_shader_ = false;
-
- /**
- * Whether the WEIGHTS and MATRIX_INDICES buffers are up-to-date.
- *
- * @type {boolean}
- * @private
- */
- this.buffers_valid_ = false;
-
- /**
- * Vertex buffer containing indices and weights for this skin.
- *
- * @type {VertexBuffer}
- */
- this.vertex_buffer_ = null;
-
- /**
- * Buffer in which to store vertex weights.
- * weights_field_ will be passed into the WEIGHTS stream.
- *
- * @type {o3d.Field}
- * @private
- */
- this.weights_field_ = null;
-
- /**
- * Buffer in which to store list of matrix_indices per vertex.
- * matrix_indices_field_ will be passed into the MATRIX_INDICES stream.
- *
- * @type {o3d.Field}
- * @private
- */
- this.matrix_indices_field_ = null;
-};
-o3d.inherit('Skin', 'NamedObject');
-
-/**
- * Updates the weights and indices vertex buffers attached to this skin, only
- * if they have been invalidated by some param change.
- * Also checks if we can support skinning based on the number of bones we need
- * in this skin.
- * @private
- * @return {boolean} true if our mesh is small enough to enable skin shader.
- */
-o3d.Skin.prototype.updateVertexShader = function() {
- if (!this.buffers_valid_) {
- var numcomp = 4;
- var numvert = this.influences.length;
- if (!this.weights_field_ && !this.matrix_indices_field_) {
- var vertex_buffer = new o3d.VertexBuffer;
- vertex_buffer.gl = this.gl;
- this.weights_field_ =
- vertex_buffer.createField("FloatField", numcomp);
- this.matrix_indices_field_ =
- vertex_buffer.createField("FloatField", numcomp);
- vertex_buffer.allocateElements(numvert);
- }
- var ii, jj;
- var weights_field = this.weights_field_;
- var indices_field = this.matrix_indices_field_;
- var highest_influences = this.getHighestInfluences();
-
- this.buffers_valid_ = true;
- weights_field.buffer.lock();
- indices_field.buffer.lock();
- var max_num_bones = o3d.SkinEval.getMaxNumBones(this);
- this.supports_vertex_shader_ = (highest_influences <= numcomp) &&
- (this.inverseBindPoseMatrices.length <= max_num_bones);
- if (this.supports_vertex_shader_) {
- // NOTE: If you make these Array's instead, you must initialize to 0.
- var weights_arr = new Float32Array(numvert * numcomp);
- var indices_arr = new Float32Array(numvert * numcomp);
- // Float32rray is initialized to 0 by default.
- for (ii = 0; ii < numvert; ++ii) {
- var influence = this.influences[ii];
- for (jj = 0; jj < influence.length && jj < numcomp * 2; jj += 2) {
- indices_arr[ii * numcomp + jj / 2] = influence[jj];
- weights_arr[ii * numcomp + jj / 2] = influence[jj + 1];
- }
- }
- weights_field.setAt(0, weights_arr);
- indices_field.setAt(0, indices_arr);
- }
- // Otherwise, weights will be filled with 0's by default.
- weights_field.buffer.unlock();
- indices_field.buffer.unlock();
- }
- return this.supports_vertex_shader_;
-};
-
-/**
- * Sets the influences for an individual vertex.
- *
- * @param {number} vertex_index The index of the vertex to set influences for.
- * @param {!Array<number>} influences An array of pairs of numbers where
- * the first number is the index of the matrix to influence the vertex
- * and the second number is the amount of influence where:
- * 0 = no influence and 1 = 100% influence.
- */
-o3d.Skin.prototype.setVertexInfluences = function(
- vertex_index, influences) {
- if (influences.length % 2 != 0) {
- this.gl.client.error_callback("odd number of values passed into" +
- "SetVertexInfluence. Even number required as they are pairs.");
- return;
- }
- this.influences[vertex_index] = influences;
- this.info_valid_ = false;
- this.buffers_valid_ = false;
-};
-
-/**
- * Gets the influences for an individual vertex.
- *
- * @param {number} vertex_index The index of the vertex to get influences from.
- * @return {!Array<number>} An array of pairs of numbers where the first number
- * of each pair is the index of the matrix that influence this vertex and
- * the second number is the amount of influence where:
- * 0 = no influence and 1 = 100% influence.
- */
-o3d.Skin.prototype.getVertexInfluences = function(vertex_index) {
- return this.influences[vertex_index] || [];
-};
-
-/**
- * Update the highest influences and highest matrix index.
- * @private
- */
-o3d.Skin.prototype.updateInfo_ = function() {
- if (!this.info_valid_) {
- this.info_valid_ = true;
- this.highest_matrix_index_ = 0;
- this.highest_influences_ = 0;
- for (var ii = 0; ii < this.influences.length; ++ii) {
- var influences = this.influences[ii];
- var len = influences.length;
- if (len > this.highest_influences_) {
- this.highest_influences_ = len;
- }
- // Influences array is in pairs: even are vertices, odd are weights
- for (var jj = 0; jj < influences.length; jj += 2) {
- if (influences[jj] > this.highest_matrix_index_) {
- this.highest_matrix_index_ = influences[jj];
- }
- }
- }
- // this.highest_influences_ should be the number of pairs.
- if (this.highest_influences_ % 2) {
- this.gl.client.error_callback(
- "Skin.updateInfo: Influences should not have odd length ");
- }
- this.highest_influences_ = Math.floor(this.highest_influences_/2);
- }
-};
-
-/**
- * Gets the highest matrix index referenced by the influences.
- *
- * @return {number} The highest matrix index referenced by the influences.
- * @private
- */
-o3d.Skin.prototype.getHighestMatrixIndex = function() {
- this.updateInfo_();
- return this.highest_matrix_index_;
-};
-
-/**
- * Gets the highest number of influences on any vertex.
- *
- * @return {number} The highest number of influences on any vertex.
- * @private
- */
-o3d.Skin.prototype.getHighestInfluences = function() {
- this.updateInfo_();
- return this.highest_influences_;
-};
-
-/**
- * Sets the inverse bind pose matrix for a particular joint/bone/transform.
- *
- * @param {number} index Index of bone/joint/transform.
- * @param {!Array<!Array<number>>} matrix Inverse bind pose matrix for this
- * joint.
- */
-o3d.Skin.prototype.setInverseBindPoseMatrix = function(index, matrix) {
- this.inverseBindPoseMatrices[index] = matrix;
-};
-
-/**
- * Deserializes from the skin data given a RawData object.
- *
- * @param {!o3d.RawData} rawData contains skin data
- * @param {number} opt_offset is a byte offset from the start of raw_data
- * @param {number} opt_length is the byte length of the data to set
- * @return {boolean} True if operation was successful.
- *
- */
-o3d.Skin.prototype.set = function(rawData, opt_offset, opt_length) {
- o3d.notImplemented();
-};
-
-
-
-/**
- * A SkinEval is a VertexSource that takes its Streams, a ParamArray of 4-by-4
- * matrices and a Skin and skins the vertices in its streams storing the results
- * in bound output streams.
- *
- * Note: Extends StreamBank, which keeps track of storing vertexStreams objects.
- * The C++ Plugin had this inherit from VertexSource, but reading through the
- * code, I can't find any good reason why.
- *
- * @constructor
- * @extends {o3d.StreamBank}
- */
-o3d.SkinEval = function() {
- o3d.StreamBank.call(this);
-
- /**
- * The base matrix to subtract from the matrices before skinning.
- * @type {!Array<!Array<number>>}
- */
- this.base = o3d.Transform.makeIdentityMatrix4_();
-
- /**
- * Temporary storage for matrix ops.
- * @type {!Array<!Array<number>>}
- * @private
- */
- this.temp_matrix_ = o3d.Transform.makeIdentityMatrix4_();
-
- /**
- * Array of matrices representing each bone.
- * @type {!Array<!Array<!Array<number>>>}
- * @private
- */
- this.bones_ = [];
-
- /**
- * Float32 array containing all matrices in 3x4 format.
- * @type {o3d.ParamArray}
- * @private
- */
- this.bone_array_ = null;
-
- /**
- * Cache of StreamInfo objects for input values. Saved to avoid reallocating.
- * @type {!Array<o3d.SkinEval.StreamInfo>}
- * @private
- */
- this.input_stream_infos_ = [];
-
- /**
- * Cache of StreamInfo objects for output values. Saved to avoid reallocating.
- * @type {!Array<o3d.SkinEval.StreamInfo>}
- * @private
- */
- this.output_stream_infos_ = [];
-
- /**
- * The base matrix to subtract from the matrices before skinning.
- *
- * @type {ParamArray}
- * @private
- */
- this.createParam("boneToWorld3x4", "ParamParamArrayOutput");
-
- this.usingSkinShader = 0.0;
-};
-o3d.inherit('SkinEval', 'StreamBank');
-
-/**
- * The base matrix to subtract from the matrices before skinning.
- *
- * @type {!Array<!Array<number>>}
- */
-o3d.ParamObject.setUpO3DParam_(o3d.SkinEval, "base", "ParamMatrix4");
-
-/**
- * Non-zero if we are using a shader for skinning.
- *
- * Holds state of whether the boneToWorld3x4 uniform is being used. If its
- * value has been read, copy over the original vertex buffers, else we
- * assume the shader does not support skinning.
- *
- * Do not write to this value. Set disableShader to true instead.
- *
- * @type {number}
- * @see disableShader
- */
-o3d.ParamObject.setUpO3DParam_(o3d.SkinEval, "usingSkinShader", "ParamFloat");
-
-/**
- * Set this value to true to force skin not to use a shader.
- *
- * @type {boolean}
- * @default false
- */
-o3d.ParamObject.setUpO3DParam_(o3d.SkinEval, "disableShader", "ParamBoolean");
-
-/**
- * The Skin to use for skinning.
- * @type {Skin}
- */
-o3d.ParamObject.setUpO3DParam_(o3d.SkinEval, "skin", "ParamSkin");
-
-/**
- * The array of matrices to use for skinning.
- * @type {ParamArray}
- */
-o3d.ParamObject.setUpO3DParam_(o3d.SkinEval, "matrices", "ParamArray");
-
-/**
- * Skins use 3 vec4's per matrix, since the last row is redundant.
- * If we don't know, 32 is safe minimum value required by standard = (128-32)/3.
- * @param {!o3d.NamedObject} obj Some object with access to gl.
- * @return {number} Maximum number of bones allowed for shader-based skinning.
- */
-o3d.SkinEval.getMaxNumBones = function(obj) {
- // Quote from spec:
- // GL_MAX_VERTEX_UNIFORM_VECTORS
- // params returns one value, the maximum number of four-element
- // floating-point, integer, or boolean vectors that can be held in
- // uniform variable storage for a vertex shader.
- // The value must be at least 128. See glUniform.
- var gl = obj.gl;
- var maxVertexUniformVectors = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
- if (!maxVertexUniformVectors) {
- maxVertexUniformVectors = 128;
- }
- return Math.floor((maxVertexUniformVectors - 32) / 3);
-};
-
-/**
- * Someone bound a stream to this SkinEval. Enable the shader on the primitive,
- * and bind any additional weights or indices streams if necessary.
- *
- * @param {o3d.VertexSource} dest VertexSource that bound to this VertexSource.
- * @param {o3d.ParamVertexBufferStream} dest_param Other param which was bound.
- * @override
- */
-o3d.SkinEval.prototype.streamWasBound_ = function(
- dest, semantic, semantic_index) {
- this.skin.updateVertexShader();
-
- if (this.skin.weights_field_ && this.skin.matrix_indices_field_) {
- var weights_stream = dest.getVertexStream(o3d.Stream.INFLUENCE_WEIGHTS, 0);
- var indices_stream = dest.getVertexStream(o3d.Stream.INFLUENCE_INDICES, 0);
- if (!weights_stream || !indices_stream ||
- weights_stream.field != this.skin.weights_field_ ||
- indices_stream.field != this.skin.matrix_indices_field_) {
- dest.setVertexStream(o3d.Stream.INFLUENCE_WEIGHTS, 0,
- this.skin.weights_field_, 0);
- dest.setVertexStream(o3d.Stream.INFLUENCE_INDICES, 0,
- this.skin.matrix_indices_field_, 0);
- }
-
- var destParam = dest.getParam("boneToWorld3x4");
- if (!destParam) {
- destParam = dest.createParam("boneToWorld3x4", "ParamParamArray");
- }
- destParam.bind(this.getParam("boneToWorld3x4"));
-
- destParam = dest.getParam("usingSkinShader");
- if (!destParam) {
- destParam = dest.createParam("usingSkinShader", "ParamFloat");
- }
- destParam.bind(this.getParam("usingSkinShader"));
- }
-};
-
-/**
- * Multiplies input by weight, and adds with and returns into output.
- *
- * @param {!Array<!Array<number>>} input Input matrix4 to weight.
- * @param {number} weight Amount to weight input matrix by.
- * @param {!Array<!Array<number>>} output The result of computing
- * output += (input * weight)
- * @private
- */
-o3d.SkinEval.prototype.multiplyAdd_ = function(input, weight, output) {
- for (var i = 0; i < 16; ++i) {
- output[i] += input[i] * weight;
- }
-};
-
-/**
- * Initializes all the input and output streams for this mesh, but does no
- * copying yet. You should follow with uninitStreams_ when you are done.
- *
- * @param {o3d.Skin} skin The skin.
- * @private
- */
-o3d.SkinEval.prototype.initStreams_ = function(skin) {
- var ii, jj, ll, num_streams;
-
- var num_vertices = this.skin.influences.length;
- // Update our inputs, lock all the inputs and outputs and check that we have
- // the same number of vertices as vertex influences.
- for (ii = 0, num_streams = 0; ii < this.vertex_streams_.length; ++ii) {
- var array = this.vertex_streams_[ii];
- if (array) {
- for (jj = 0; jj < array.length; ++jj, ++num_streams) {
- var source_param = array[jj];
-
- // Make sure our upstream streams are ready
- var input = source_param.inputConnection;
- if (input && input.isAClassName("ParamVertexBufferStream")) {
- input.owner_.updateStreams(); // will automatically mark us as valid.
- } else {
- // Mark source_param as valid so we don't evaluate a second time.
- // TODO(pathorn): Caching previous computed values.
- }
-
- var source_stream = source_param.stream;
- if (source_stream.getMaxVertices_() != num_vertices) {
- // TODO: Change semantic below to semantic_name.
- this.gl.client.error_callback("SkinEval.doSkinning_: "
- + "stream " + source_stream.semantic + " index "
- + source_stream.semanticIndex + " in SkinEval '" + this.name
- + " does not have the same number of vertices as Skin '"
- + skin.name + "'");
- return;
- }
-
- // Lock this input.
- if (!this.input_stream_infos_[num_streams]) {
- this.input_stream_infos_[num_streams] = new o3d.SkinEval.StreamInfo;
- }
- if (!this.input_stream_infos_[num_streams].init(source_stream, false)) {
- var buffer_name;
- if (source_stream.field.buffer) {
- buffer_name = source_stream.field.buffer.name;
- }
- this.gl.client.error_callback("SkinEval.doSkinning_: "
- + "unable to lock buffer '" + buffer_name
- + " used by stream " + source_stream.semantic + " index "
- + source_stream.semanticIndex + " in SkinEval '" + this.name
- + "'");
- return;
- }
-
- // Lock the outputs to this input.
- var outputs = source_param.outputConnections; //ParamVector
- if (!this.output_stream_infos_[num_streams]) {
- this.output_stream_infos_[num_streams] = [];
- }
- var output_stream_info = this.output_stream_infos_[num_streams];
- output_stream_info.length = outputs.length;
-
- for (ll = 0; ll < outputs.length; ++ll) {
- var destination_param = outputs[ll];
- if (destination_param.isAClassName('ParamVertexBufferStream')) {
- // Mark destination_param valid so we don't evaluate a second time.
- // TODO(pathorn): Caching previous computed values.
- } else {
- this.gl.client.error_callback("SkinEval.doSkinning: "
- + destination_param.className + " not ParamVertexBufferStream");
- }
- var destination_stream = destination_param.stream;
- if (destination_stream.getMaxVertices_() != num_vertices) {
- this.gl.client.error_callback("SkinEval.doSkinning_: "
- + "stream " + destination_stream.semantic + " index "
- + destination_stream.semanticIndex + " targeted by SkinEval '"
- + this.name + " does not have the same number of vertices as "
- + "Skin '" + skin.name + "'");
- return;
- }
-
- if (!output_stream_info[ll]) {
- output_stream_info[ll] = new o3d.SkinEval.StreamInfo;
- }
- if (!output_stream_info[ll].init(destination_stream,true)) {
- var buffer_name;
- if (destination_stream.field.buffer) {
- buffer_name = destination_stream.field.buffer.name;
- }
- this.gl.client.error_callback("SkinEval.doSkinning_: "
- + "unable to lock buffer '" + buffer_name
- + " used by stream " + destination_stream.semantic + " index "
- + destination_stream.semanticIndex + " targeted by SkinEval '"
- + this.name + "'");
- return;
- }
- }
- }
- }
- }
-
- this.input_stream_infos_.length = num_streams;
- this.output_stream_infos_.length = num_streams;
-};
-
-/**
- * Saves the result of the skinning operation in the graphics hardware.
- *
- * @private
- */
-o3d.SkinEval.prototype.uninitStreams_ = function() {
- // Unlock any buffers that were locked during skinning
- for (ii = 0; ii < this.input_stream_infos_.length; ++ii) {
- this.input_stream_infos_[ii].uninit();
- }
- for (ii = 0; ii < this.output_stream_infos_.length; ++ii) {
- var output_streams = this.output_stream_infos_[ii];
- for (var jj = 0; jj < output_streams.length; ++jj) {
- output_streams[jj].uninit();
- }
- }
-};
-
-/**
- * Does skinning in software. Performs the actual matrix-point mulitplications
- * and saves the result in all the output streams.
- *
- * @private
- */
-o3d.SkinEval.prototype.doSkinning_ = function() {
- this.initStreams_();
-
- var ii, jj, ll;
- var influences_array = this.skin.influences;
- var num_vertices = influences_array.length;
-
- for (ii = 0; ii < num_vertices; ++ii) {
- var influences = influences_array[ii];
- if (influences.length) {
- // Even are vertices, odd are weights
- var this_matrix_index = influences[0];
- // Get the first matrix.
- var this_weight = influences[1];
-
- // combine the matrixes for this vertex.
- var accumulated_matrix =
- o3d.Transform.makeNullMatrix4_();
- this.multiplyAdd_(this.bones_[this_matrix_index],
- this_weight, accumulated_matrix);
- var num_influences = influences.length;
- for (jj = 2; jj < num_influences; jj += 2) {
- var influence_matrix_index = influences[jj];
- var influence_weight = influences[jj + 1];
- this.multiplyAdd_(this.bones_[influence_matrix_index],
- influence_weight, accumulated_matrix);
- }
-
- // for each source, compute and copy to destination.
- for (jj = 0; jj < this.input_stream_infos_.length; ++jj) {
- var input_stream_info = this.input_stream_infos_[jj];
- input_stream_info.compute_function_(accumulated_matrix);
- var output_streams = this.output_stream_infos_[jj];
- var num_output_streams = output_streams.length;
- for (ll = 0; ll < num_output_streams; ++ll) {
- output_streams[ll].copy_function_(input_stream_info);
- }
- }
- }
- }
-
- this.uninitStreams_();
-};
-
-/**
- * Updates the bones from this.matrices.
- *
- * @private
- */
-o3d.SkinEval.prototype.updateBones_ = function() {
- // Get our matrices.
- var param_array = this.matrices;
- if (!param_array) {
- this.gl.client.error_callback("SkinEval.updateBones_: "
- + "no matrices for SkinEval '" + this.name + "'");
- return;
- }
-
- var the_skin = this.skin;
- if (!the_skin) {
- this.gl.client.error_callback("SkinEval.updateBones_: "
- + "no skin specified in SkinEval '" + this.name + "'");
- return;
- }
-
- // Make sure the bone indices are in range.
- if (the_skin.getHighestMatrixIndex() >= param_array.length) {
- this.gl.client.error_callback("SkinEval.updateBones_: "
- + "skin '" + the_skin.name + " specified in SkinEval '"
- + this.name
- + "' references matrices outside the valid range in ParamArray '"
- + param_array.name + "'");
- return;
- }
-
- // Make sure the bind pose array size matches the matrices
- var inverse_bind_pose_array = the_skin.inverseBindPoseMatrices;
- if (inverse_bind_pose_array.length != param_array.length) {
- this.gl.client.error_callback("SkinEval.updateBones_: "
- + "skin '" + the_skin.name + " specified in SkinEval '"
- + this.name + "' and the ParamArray '"
- + param_array.name + "' do not have the same number of matrices.");
- return;
- }
-
- // Get the inverse of our base to remove from the bones.
- var inverse_base = this.temp_matrix_;
- o3d.Transform.inverse_(this.base, inverse_base);
-
- for (var ii = 0; ii < param_array.length; ++ii) {
- var param = param_array.getParam(ii); // ParamMatrix4
- if (!param) {
- this.gl.client.error_callback("SkinEval.updateBones_: "
- + "In SkinEval '" + this.name + "' param at index " + ii
- + " in ParamArray '" + param_array.name
- + " is not a ParamMatrix4");
- return;
- }
- this.bones_[ii] = o3d.Transform.makeIdentityMatrix4_();
- o3d.Transform.compose_(param.value, inverse_bind_pose_array[ii],
- this.bones_[ii]);
- o3d.Transform.compose_(inverse_base, this.bones_[ii], this.bones_[ii]);
- }
-};
-
-/**
- * Updates the VertexBuffers bound to streams on this VertexSource.
- */
-o3d.SkinEval.prototype.updateStreams = function() {
- if (this.disableShader || !this.usingSkinShader ||
- !this.skin.updateVertexShader()) {
- this.updateBones_();
- this.doSkinning_(this.skin);
- this.usingSkinShader = 0.0;
- }
-};
-
-/**
- * Should be called on boneToWorld3x4's get value.
- * Updates ParamArray for bones uniform sent to vertex shader.
- *
- * @param {ParamParamArrayOutput} param The array uniform parameter to update.
- * @return {ParamArray} The array containing all of the float4 params.
- */
-o3d.SkinEval.prototype.updateOutputs = function(param) {
- this.updateBones_();
- if (!this.bone_array_) {
- this.bone_array_ = new o3d.ParamArray;
- this.bone_array_.gl = this.gl;
- var max_num_bones = o3d.SkinEval.getMaxNumBones(this);
- this.bone_array_.resize(max_num_bones * 3, "ParamFloat4");
- param.value = this.bone_array_;
- }
- var boneArray = this.bone_array_;
- var ii, jj;
- if (!this.disableShader && this.skin.updateVertexShader()) {
- // Is this the first time the param has been read?
- if (!this.usingSkinShader) {
- // If so, we disable skinning in software.
- this.usingSkinShader = 1.0;
- // Copy the default positions of all vertex buffers.
- this.initStreams_();
- var num_vertices = this.skin.influences.length;
- for (ii = 0; ii < this.input_stream_infos_.length; ++ii) {
- var input_stream_info = this.input_stream_infos_[ii];
- var output_streams = this.output_stream_infos_[ii];
- for (jj = 0; jj < output_streams.length; ++jj) {
- var values = input_stream_info.field_.getAt(0, num_vertices);
- output_streams[jj].field_.setAt(0, values);
- }
- }
- this.uninitStreams_();
- }
- var row;
- for (ii = 0; ii < this.bones_.length; ++ii) {
- var bone = this.bones_[ii];
- row = boneArray.getParam(ii*3);
- row.value[0] = bone[0];
- row.value[1] = bone[4];
- row.value[2] = bone[8];
- row.value[3] = bone[12];
- row = boneArray.getParam(ii*3 + 1);
- row.value[0] = bone[1];
- row.value[1] = bone[5];
- row.value[2] = bone[9];
- row.value[3] = bone[13];
- row = boneArray.getParam(ii*3 + 2);
- row.value[0] = bone[2];
- row.value[1] = bone[6];
- row.value[2] = bone[10];
- row.value[3] = bone[14];
- }
- }
- return boneArray;
-};
-
-/**
- * This class helps manage each stream. Because allocating memory is slow we
- * keep these around across calls and reuse them in place by calling init.
- *
- * @param {o3d.Stream} stream
- * @param {o3d.Buffer.AccessMode} access_mode
- * @constructor
- * @private
- */
-o3d.SkinEval.StreamInfo = function() {
- this.compute_function_ = null;
- this.copy_function_ = null;
- this.result_ = null;
- this.field_ = null;
- this.values_ = null;
- this.buffer_ = null;
- this.index_ = 0;
- this.writable_ = false;
-};
-
-
-/**
- * Initialize this StreamInfo object from the given Stream.
- *
- * @param {o3d.Stream} stream Stream to lock.
- * @param {boolean} access_mode true if writable, false otherwise.
- * @return {boolean} True if the buffer lock was successful, false if error.
- */
-o3d.SkinEval.StreamInfo.prototype.init = function(stream, access_mode) {
- if (this.values_ || this.buffer_) {
- return false;
- }
- var field = stream.field;
- var buffer = field.buffer;
- // field must be a FloatField, but in o3d-webgl, Field is the same type so
- // we can't check isAClassName.
- if (!buffer) {
- return false;
- }
- switch (field.numComponents) {
- case 3:
- this.copy_function_ = this.copyFloat3;
- this.compute_function_ = (stream.semantic == o3d.Stream.POSITION) ?
- this.computeFloat3AsPoint3 : this.computeFloat3AsVector3;
- break;
- case 4:
- this.compute_function_ = this.computeFloat4AsVector4;
- this.copy_function_ = this.copyFloat4;
- break;
- default:
- return false;
- }
-
- buffer.lock();
- this.field_ = field;
- this.buffer_ = buffer;
- this.values_ = buffer.array_;
- this.index_ = this.field_.offset_;
- this.writable_ = access_mode;
- this.stride_ = buffer.totalComponents;
- return true;
-};
-
-/**
- * Uninitialize this StreamInfo object, and unlock the stream.
- * Can be reused for another init() call.
- */
-o3d.SkinEval.StreamInfo.prototype.uninit = function() {
- if (this.buffer_) {
- if (this.writable_) {
- this.buffer_.unlock();
- }
- this.buffer_ = null;
- this.field_ = null;
- this.values_ = null;
- }
-};
-
-/**
- * Consumes the next 3 values from this.values_.
- * Multiplies the current value by the matrix and stores it in result_ and
- * advances to the next value.
- *
- * @param {!Array<!Array<number>>} matrix matrix4 to apply to the vector3.
- */
-o3d.SkinEval.StreamInfo.prototype.computeFloat3AsVector3 = function(matrix) {
- var ii = this.index_;
- var vec = [this.values_[ii], this.values_[ii + 1], this.values_[ii + 2], 0];
- this.result_ = o3d.Transform.multiplyVector_(matrix, vec);
- this.index_ = ii + this.stride_;
-};
-
-/**
- * Consumes the next 3 values from this.values_.
- * Multiplies the current value by the matrix and stores it in result_ and
- * advances to the next value.
- *
- * @param {!Array<!Array<number>>} matrix matrix4 to apply to the vector3.
- */
-o3d.SkinEval.StreamInfo.prototype.computeFloat3AsPoint3 = function(matrix) {
- var ii = this.index_;
- // TODO: The C++ code just dropped element 3 of the return Vector4, while
- // o3d.Transform.transformPoint_ divides by the last value to make it 1.
- // Which is the right one to use?
- var point = [this.values_[ii], this.values_[ii + 1], this.values_[ii + 2], 1];
- this.result_ = o3d.Transform.multiplyVector_(matrix, point);
- this.index_ = ii + this.stride_;
-};
-
-/**
- * Consumes the next 4 this.values_.
- * Multiplies the current value by the matrix and stores it in result_ and
- * advances to the next value.
- *
- * @param {!Array<!Array<number>>} matrix matrix4 to apply to the vector4.
- */
-o3d.SkinEval.StreamInfo.prototype.computeFloat4AsVector4 = function(matrix) {
- var ii = this.index_;
- var vec = [this.values_[ii], this.values_[ii + 1], this.values_[ii + 2],
- this.values_[ii + 3]];
- this.result_ = o3d.Transform.multiplyVector_(matrix, vec);
- this.index_ = ii + this.stride_;
-};
-
-/**
- * Copies the Float3 result_ from source and advances to the next value.
- *
- * @param {!o3d.SkinEval.StreamInfo} source Source StreamInfo to copy from.
- */
-o3d.SkinEval.StreamInfo.prototype.copyFloat3 = function(source) {
- var ii = this.index_;
- this.values_[ii] = source.result_[0];
- this.values_[ii+1] = source.result_[1];
- this.values_[ii+2] = source.result_[2];
- this.index_ = ii + this.stride_;
-};
-
-/**
- * Copies the Float4 result_ from source and advances to the next value.
- *
- * @param {!o3d.SkinEval.StreamInfo} source Source StreamInfo to copy from.
- */
-o3d.SkinEval.StreamInfo.prototype.copyFloat4 = function(source) {
- var ii = this.index_;
- this.values_[ii] = source.result_[0];
- this.values_[ii+1] = source.result_[1];
- this.values_[ii+2] = source.result_[2];
- this.values_[ii+3] = source.result_[3];
- this.index_ = ii + this.stride_;
-};
-
diff --git a/o3d/samples/o3d-webgl/state.js b/o3d/samples/o3d-webgl/state.js
deleted file mode 100644
index a09ab36..0000000
--- a/o3d/samples/o3d-webgl/state.js
+++ /dev/null
@@ -1,700 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A State object sets the RenderStates for a particular material or StateSet.
- * @constructor
- */
-o3d.State = function() {
- o3d.ParamObject.call(this);
-
- this.state_params_ = {};
-
- /**
- * The names types and default values of all the state variables.
- * @type {Object}
- * @private
- */
- o3d.State.stateVariableInfos_ = o3d.State.stateVariableInfos_ || {
- 'AlphaBlendEnable':
- {paramType: 'ParamBoolean', defaultValue: false},
- 'AlphaComparisonFunction':
- {paramType: 'ParamInteger', defaultValue: o3d.State.CMP_ALWAYS},
- 'AlphaReference':
- {paramType: 'ParamFloat', defaultValue: 0},
- 'AlphaTestEnable':
- {paramType: 'ParamBoolean', defaultValue: false},
- 'BlendAlphaEquation':
- {paramType: 'ParamInteger', defaultValue: o3d.State.BLEND_ADD},
- 'BlendEquation':
- {paramType: 'ParamInteger', defaultValue: o3d.State.BLEND_ADD},
- 'CCWStencilComparisonFunction':
- {paramType: 'ParamInteger', defaultValue: o3d.State.CMP_ALWAYS},
- 'CCWStencilFailOperation':
- {paramType: 'ParamInteger', defaultValue: o3d.State.STENCIL_KEEP},
- 'CCWStencilPassOperation':
- {paramType: 'ParamInteger', defaultValue: o3d.State.STENCIL_KEEP},
- 'CCWStencilZFailOperation':
- {paramType: 'ParamInteger', defaultValue: o3d.State.STENCIL_KEEP},
- 'ColorWriteEnable':
- {paramType: 'ParamInteger', defaultValue: 15},
- 'CullMode':
- {paramType: 'ParamInteger', defaultValue: o3d.State.CULL_CW},
- 'DestinationBlendAlphaFunction':
- {paramType: 'ParamInteger', defaultValue: o3d.State.BLENDFUNC_ZERO},
- 'DestinationBlendFunction':
- {paramType: 'ParamInteger', defaultValue: o3d.State.BLENDFUNC_ZERO},
- 'DitherEnable':
- {paramType: 'ParamBoolean', defaultValue: false},
- 'FillMode':
- {paramType: 'ParamInteger', defaultValue: o3d.State.SOLID},
- 'LineSmoothEnable':
- {paramType: 'ParamBoolean', defaultValue: false},
- 'PointSize':
- {paramType: 'ParamFloat', defaultValue: 0},
- 'PointSpriteEnable':
- {paramType: 'ParamBoolean', defaultValue: false},
- 'PolygonOffset1':
- {paramType: 'ParamFloat', defaultValue: 0},
- 'PolygonOffset2':
- {paramType: 'ParamFloat', defaultValue: 0},
- 'SeparateAlphaBlendEnable':
- {paramType: 'ParamBoolean', defaultValue: false},
- 'SourceBlendAlphaFunction':
- {paramType: 'ParamInteger', defaultValue: o3d.State.BLENDFUNC_ONE},
- 'SourceBlendFunction':
- {paramType: 'ParamInteger', defaultValue: o3d.State.BLENDFUNC_ONE},
- 'StencilComparisonFunction':
- {paramType: 'ParamInteger', defaultValue: o3d.State.CMP_ALWAYS},
- 'StencilEnable':
- {paramType: 'ParamBoolean', defaultValue: false},
- 'StencilFailOperation':
- {paramType: 'ParamInteger', defaultValue: o3d.State.STENCIL_KEEP},
- 'StencilMask':
- {paramType: 'ParamInteger', defaultValue: 255},
- 'StencilPassOperation':
- {paramType: 'ParamInteger', defaultValue: o3d.State.STENCIL_KEEP},
- 'StencilReference':
- {paramType: 'ParamInteger', defaultValue: 0},
- 'StencilWriteMask':
- {paramType: 'ParamInteger', defaultValue: 255},
- 'StencilZFailOperation':
- {paramType: 'ParamInteger', defaultValue: o3d.State.STENCIL_KEEP},
- 'TwoSidedStencilEnable':
- {paramType: 'ParamBoolean', defaultValue: false},
- 'ZComparisonFunction':
- {paramType: 'ParamInteger', defaultValue: o3d.State.CMP_LESS},
- 'ZEnable':
- {paramType: 'ParamBoolean', defaultValue: true},
- 'ZWriteEnable':
- {paramType: 'ParamBoolean', defaultValue: true}
- };
-};
-o3d.inherit('State', 'ParamObject');
-
-
-/**
- * A private object containing the the state params by name.
- */
-o3d.State.prototype.state_params_ = { };
-
-
-/**
- * Comparison
- * CMP_NEVER (Never)
- * CMP_LESS (Less Than)
- * CMP_EQUAL (Equal To)
- * CMP_LEQUAL (Less Than or Equal To)
- * CMP_GREATER (Greater Than)
- * CMP_NOTEQUAL (Not Equal To)
- * CMP_GEQUAL (Greater Than or Equal To)
- * CMP_ALWAYS (Always)
- */
-o3d.State.CMP_NEVER = 0;
-o3d.State.CMP_LESS = 1;
-o3d.State.CMP_EQUAL = 2;
-o3d.State.CMP_LEQUAL = 3;
-o3d.State.CMP_GREATER = 4;
-o3d.State.CMP_NOTEQUAL = 5;
-o3d.State.CMP_GEQUAL = 6;
-o3d.State.CMP_ALWAYS = 7;
-
-
-
-/**
- * type {number}
- */
-o3d.Cull = goog.typedef;
-
-/**
- * Cull
- * CULL_NONE Don't Cull by face
- * CULL_CW Cull clock-wise faces
- * CULL_CCW Cull counter clock-wise faces
- */
-o3d.State.CULL_NONE = 0;
-o3d.State.CULL_CW = 1;
-o3d.State.CULL_CCW = 2;
-
-
-
-
-/**
- * Fill
- * POINT
- * WIREFRAME
- * SOLID
- */
-o3d.State.POINT = 0;
-o3d.State.WIREFRAME = 1;
-o3d.State.SOLID = 2;
-
-
-
-/**
- * BlendingFunction
- * BLENDFUNC_ZERO
- * BLENDFUNC_ONE
- * BLENDFUNC_SOURCE_COLOR
- * BLENDFUNC_INVERSE_SOURCE_COLOR
- * BLENDFUNC_SOURCE_ALPHA
- * BLENDFUNC_INVERSE_SOURCE_ALPHA
- * BLENDFUNC_DESTINATION_ALPHA
- * BLENDFUNC_INVERSE_DESTINATION_ALPHA
- * BLENDFUNC_DESTINATION_COLOR
- * BLENDFUNC_INVERSE_DESTINATION_COLOR
- * BLENDFUNC_SOURCE_ALPHA_SATUTRATE
- */
-o3d.State.BLENDFUNC_ZERO = 0;
-o3d.State.BLENDFUNC_ONE = 1;
-o3d.State.BLENDFUNC_SOURCE_COLOR = 2;
-o3d.State.BLENDFUNC_INVERSE_SOURCE_COLOR = 3;
-o3d.State.BLENDFUNC_SOURCE_ALPHA = 4;
-o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA = 5;
-o3d.State.BLENDFUNC_DESTINATION_ALPHA = 6;
-o3d.State.BLENDFUNC_INVERSE_DESTINATION_ALPHA = 7;
-o3d.State.BLENDFUNC_DESTINATION_COLOR = 8;
-o3d.State.BLENDFUNC_INVERSE_DESTINATION_COLOR = 9;
-o3d.State.BLENDFUNC_SOURCE_ALPHA_SATUTRATE = 10;
-
-
-
-/**
- * BlendingEquation
- * BLEND_ADD
- * BLEND_SUBTRACT
- * BLEND_REVERSE_SUBTRACT
- * BLEND_MIN
- * BLEND_MAX
- */
-o3d.State.BLEND_ADD = 0;
-o3d.State.BLEND_SUBTRACT = 1;
-o3d.State.BLEND_REVERSE_SUBTRACT = 2;
-o3d.State.BLEND_MIN = 3;
-o3d.State.BLEND_MAX = 4;
-
-
-
-/**
- * StencilOperation
- * STENCIL_KEEP
- * STENCIL_ZERO
- * STENCIL_REPLACE
- * STENCIL_INCREMENT_SATURATE
- * STENCIL_DECREMENT_SATURATE
- * STENCIL_INVERT
- * STENCIL_INCREMENT
- * STENCIL_DECREMENT
- */
-o3d.State.STENCIL_KEEP = 0;
-o3d.State.STENCIL_ZERO = 1;
-o3d.State.STENCIL_REPLACE = 2;
-o3d.State.STENCIL_INCREMENT_SATURATE = 3;
-o3d.State.STENCIL_DECREMENT_SATURATE = 4;
-o3d.State.STENCIL_INVERT = 5;
-o3d.State.STENCIL_INCREMENT = 6;
-o3d.State.STENCIL_DECREMENT = 7;
-
-
-
-/**
- * Returns a Param for a given state. If the param does not already exist it
- * will be created. If the state_name is invalid it will return null.
- * @param {string} state_name name of the state
- * @return {o3d.Param} param or null if no matching state.
- *
- * Example:
- *
- *
- * g_o3d = document.o3d.o3d;
- * ...
- *
- * var state = my_pack.createState("my_state");
- *
- *
- * state.getStateParam('StencilEnable').value = true;
- * state.getStateParam('StencilReference').value = 25;
- * state.getStateParam('StencilPassOperation').value =
- * g_o3d.State.STENCIL_REPLACE;
- * state.getStateParam('StencilComparisonFunction').value =
- * g_o3d.State.CMP_ALWAYS;
- * state.getStateParam('ZEnable').value = false;
- * state.getStateParam('ZWriteEnable').value = false;
- * state.getStateParam('ColorWriteEnable').value = 0;
- *
- * Valid states:
- *
- * State NameTypeDefault Value
- * o3d.AlphaBlendEnableParamBoolean
- * default = false
- * o3d.AlphaComparisonFunctionParamInteger,
- * State.Comparisondefault = State.CMP_ALWAYS
- * o3d.AlphaReferenceParamFloat 0-1
- * default = 0
- * o3d.AlphaTestEnableParamBoolean
- * default = false
- * o3d.BlendAlphaEquation
- * ParamInteger, State.BlendingEquation
- * default = State.BLEND_ADD
- * o3d.BlendEquation
- * ParamInteger, State.BlendingEquation
- * default = State.BLEND_ADD
- * o3d.CCWStencilComparisonFunction
- * ParamInteger, State.Comparison
- * default = State.CMP_ALWAYS
- * o3d.CCWStencilFailOperation
- * ParamInteger, State.StencilOperation
- * default = State.STENCIL_KEEP
- * o3d.CCWStencilPassOperation
- * ParamInteger, State.StencilOperation
- * default = State.STENCIL_KEEP
- * o3d.CCWStencilZFailOperation
- * ParamInteger, State.StencilOperation
- * default = State.STENCIL_KEEP
- * o3d.ColorWriteEnable
- * ParamInteger 0-15 bit 0 = red, bit 1 = green,
- * bit 2 = blue, bit 3 = alphadefault = 15
- * o3d.CullModeParamInteger, State.Cull
- * default = State.CULL_CW
- * o3d.DestinationBlendAlphaFunction
- * ParamInteger, State.BlendingFunction
- * default = State.BLENDFUNC_ZERO
- * o3d.DestinationBlendFunction
- * ParamInteger, State.BlendingFunction
- * default = State.BLENDFUNC_ZERO
- * o3d.DitherEnableParamBoolean
- * default = false
- * o3d.FillModeParamInteger, State.Fill
- * default = State.SOLID
- * o3d.LineSmoothEnableParamBoolean
- * default = false
- * o3d.PointSizeParamFloatTBD
- * o3d.PointSpriteEnableParamBoolean
- * default = false
- * o3d.PolygonOffset1
- * ParamFloat, polygon offset slope factor0
- * o3d.PolygonOffset2ParamFloat, polygon offset bias (in
- * resolvable units)0
- * o3d.SeparateAlphaBlendEnableParamBoolean
- * default = false
- * o3d.SourceBlendAlphaFunction
- * ParamInteger, State.BlendingFunction
- * default = State.BLENDFUNC_ONE
- * o3d.SourceBlendFunction
- * ParamInteger, State.BlendingFunction
- * default = State.BLENDFUNC_ONE
- * o3d.StencilComparisonFunction
- * ParamInteger, State.Comparison
- * default = State.CMP_ALWAYS
- * o3d.StencilEnableParamBoolean
- * default = false
- * o3d.StencilFailOperation
- * ParamInteger, State.StencilOperation
- * default = State.STENCIL_KEEP
- * o3d.StencilMaskParamInteger 0-255
- * default = 255
- * o3d.StencilPassOperation
- * ParamInteger, State.StencilOperation
- * default = State.STENCIL_KEEP
- * o3d.StencilReferenceParamInteger 0-255
- * default = 0
- * o3d.StencilWriteMaskParamInteger 0-255
- * default = 255
- * o3d.StencilZFailOperation
- * ParamInteger, State.StencilOperation
- * default = State.STENCIL_KEEP
- * o3d.TwoSidedStencilEnableParamBoolean
- * default = false
- * o3d.ZComparisonFunction
- * ParamInteger, State.Comparison
- * default = State.CMP_LESS
- * o3d.ZEnableParamBoolean
- * default = true
- * o3d.ZWriteEnableParamBoolean
- * default = true
- *
- *
- * Note: Polygon offset is computed with the following formula:
- *
- * totalOffset = PolygonOffset1 * slope + PolygonOffset2 * r
- *
- * Slope is the maximum difference in depth between 2 adjacent pixels of the
- * polygon. r is the smallest value that would fail the NOTEQUAL test against
- * 0.
- * Typical useful values to layer a polygon on top of another one are -1.0 for
- * each of PolygonOffset1 and PolygonOffset2.
- */
-o3d.State.prototype.getStateParam =
- function(state_name) {
- if (!this.state_params_[state_name]) {
- var info = o3d.State.stateVariableInfos_[state_name];
- var param = new o3d.global.o3d[info.paramType];
- param.value = info.defaultValue;
- this.state_params_[state_name] = param;
- }
- return this.state_params_[state_name];
-};
-
-
-/**
- * Constructs a state to set all state variables to their default value.
- * This is meant to be called once at client initialization.
- * @param {WebGLContext} gl The context associated with the calling client.
- * @return {o3d.State} A new state object.
- * @private
- */
-o3d.State.createDefaultState_ = function(gl) {
- var state = new o3d.State;
- state.gl = gl;
- var infos = o3d.State.stateVariableInfos_;
- for (name in infos) {
- var info = infos[name];
- state.getStateParam(name).value = info.defaultValue;
- }
- return state;
-};
-
-
-/**
- * Converts a comparison function type constant from o3d to WebGL.
- * @param {!WebGLContext} gl The current context.
- * @param {number} blend_func The o3d constant.
- * @return {number} The WebGL version of the constant.
- * @private
- */
-o3d.State.convertCmpFunc_ = function(gl, cmp) {
- switch(cmp) {
- case o3d.State.CMP_ALWAYS:
- return gl.ALWAYS;
- case o3d.State.CMP_NEVER:
- return gl.NEVER;
- case o3d.State.CMP_LESS:
- return gl.LESS;
- case o3d.State.CMP_GREATER:
- return gl.GREATER;
- case o3d.State.CMP_LEQUAL:
- return gl.LEQUAL;
- case o3d.State.CMP_GEQUAL:
- return gl.GEQUAL;
- case o3d.State.CMP_EQUAL:
- return gl.EQUAL;
- case o3d.State.CMP_NOTEQUAL:
- return gl.NOTEQUAL;
- default:
- break;
- }
- return gl.ALWAYS;
-};
-
-
-/**
- * Converts a blend function type constant from o3d to WebGL.
- * @param {!WebGLContext} gl The current context.
- * @param {number} blend_func The o3d constant.
- * @return {number} The WebGL version of the constant.
- * @private
- */
-o3d.State.convertBlendFunc_ = function(gl, blend_func) {
- switch (blend_func) {
- case o3d.State.BLENDFUNC_ZERO:
- return gl.ZERO;
- case o3d.State.BLENDFUNC_ONE:
- return gl.ONE;
- case o3d.State.BLENDFUNC_SOURCE_COLOR:
- return gl.SRC_COLOR;
- case o3d.State.BLENDFUNC_INVERSE_SOURCE_COLOR:
- return gl.ONE_MINUS_SRC_COLOR;
- case o3d.State.BLENDFUNC_SOURCE_ALPHA:
- return gl.SRC_ALPHA;
- case o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA:
- return gl.ONE_MINUS_SRC_ALPHA;
- case o3d.State.BLENDFUNC_DESTINATION_ALPHA:
- return gl.DST_ALPHA;
- case o3d.State.BLENDFUNC_INVERSE_DESTINATION_ALPHA:
- return gl.ONE_MINUS_DST_ALPHA;
- case o3d.State.BLENDFUNC_DESTINATION_COLOR:
- return gl.DST_COLOR;
- case o3d.State.BLENDFUNC_INVERSE_DESTINATION_COLOR:
- return gl.ONE_MINUS_DST_COLOR;
- case o3d.State.BLENDFUNC_SOURCE_ALPHA_SATUTRATE:
- return gl.SRC_ALPHA_SATURATE;
- default:
- break;
- }
- return gl.ONE;
-};
-
-
-/**
- * Converts a stencil type constant from o3d to WebGL.
- * @param {!WebGLContext} gl The current context.
- * @param {number} stencil_func The o3d constant.
- * @return {number} The WebGL version of the constant.
- * @private
- */
-o3d.State.convertBlendEquation_ = function(gl, blend_equation) {
- switch (blend_equation) {
- case o3d.State.BLEND_ADD:
- return gl.FUNC_ADD;
- case o3d.State.BLEND_SUBTRACT:
- return gl.FUNC_SUBTRACT;
- case o3d.State.BLEND_REVERSE_SUBTRACT:
- return gl.FUNC_REVERSE_SUBTRACT;
- case o3d.State.BLEND_MIN:
- return gl.MIN;
- case o3d.State.BLEND_MAX:
- return gl.MAX;
- default:
- break;
- }
- return gl.FUNC_ADD;
-};
-
-
-/**
- * Sets the internal state to the this state.
- * @private
- */
-o3d.State.prototype.push_ = function() {
- this.gl.client.pushState_(this.getVariableMap_());
-};
-
-
-/**
- * Recovers the internal state prior to this state gettings set.
- * @private
- */
-o3d.State.prototype.pop_ = function() {
- this.gl.client.popState_();
-};
-
-
-/**
- * Returns a new javascript object of name value pairs indicating
- * what values to set each of the (changing) state variables.
- * @return {!Object} The variable map.
- * @private
- */
-o3d.State.prototype.getVariableMap_ = function() {
- var m = {};
- var stateParams = this.state_params_;
- for (var name in stateParams) {
- m[name] = stateParams[name].value;
- }
- return m;
-};
-
-
-
-/**
- * Helper function for setVariables_, looks for each of the given state
- * variables' names in the given variable map. If any one of them is a key
- * in the map, it fills in the rest in the target_map with the value either
- * from the variable map or from the state if it isn't on the variable map.
- * @param {Array.<!string>} names The names of the variables in question.
- * @param {!Object} variable_map An object connecting names to values.
- * @param {!Object} target_map An object to fill out with the variables from
- * the given array of names.
- * @return {boolean} True if any of the variable names in the given array were
- * found in the variable_map
- * @private
- */
-o3d.State.relevantValues_ =
- function(gl, names, variable_map, target_map) {
- var found = false;
- for (var i = 0; i < names.length; ++i) {
- var name = names[i];
- if (variable_map[name] !== undefined) {
- found = true;
- break;
- }
- }
-
- if (found) {
- for (var i = 0; i < names.length; ++i) {
- var name = names[i];
- var value = variable_map[name];
- if (value === undefined) {
- value = gl.client.getState_(name);
- }
- target_map[name] = value;
- }
- }
- return found;
-};
-
-
-/**
- * Sets the internal state according to the name value pairs in the given
- * object.
- * @param {WebGLContext} gl The gl context to use.
- * @param {Object} variable_map A map linking state variable names to values.
- * @private
- */
-o3d.State.setVariables_ = function(gl, variable_map) {
- // TODO(petersont): Only some of the state variables have been implemented.
- // Others are unavailable in webgl.
-
- // Remember, any state variable might be missing from variable_map. When the
- // key is not present, the state should be left alone.
-
- // Temporary map to hold name value pairs.
- var v = {};
-
- if (this.relevantValues_(gl, ['AlphaBlendEnable'], variable_map, v)) {
- if (v['AlphaBlendEnable']) {
- gl.enable(gl.BLEND);
- } else {
- gl.disable(gl.BLEND);
- }
- }
-
- if (this.relevantValues_(gl, ['SeparateAlphaBlendEnable',
- 'SourceBlendFunction',
- 'SourceBlendAlphaFunction',
- 'DestinationBlendAlphaFunction',
- 'BlendEquation',
- 'BlendAlphaEquation'], variable_map, v)) {
- if (v['SeparateAlphaBlendEnable']) {
- gl.blendFuncSeparate(
- o3d.State.convertBlendFunc_(gl, v['SourceBlendFunction']),
- o3d.State.convertBlendFunc_(gl, v['DestinationBlendFunction']),
- o3d.State.convertBlendFunc_(gl, v['SourceBlendAlphaFunction']),
- o3d.State.convertBlendFunc_(gl, v['DestinationBlendAlphaFunction']));
- gl.blendEquationSeparate(
- o3d.State.convertBlendEquation_(gl, v['BlendEquation']),
- o3d.State.convertBlendEquation_(gl, v['BlendAlphaEquation']));
- }
- }
-
- if (this.relevantValues_(gl, ['SourceBlendFunction',
- 'DestinationBlendFunction'], variable_map, v)) {
- gl.blendFunc(
- o3d.State.convertBlendFunc_(gl, v['SourceBlendFunction']),
- o3d.State.convertBlendFunc_(gl, v['DestinationBlendFunction']));
- }
-
- if (this.relevantValues_(gl, ['BlendEquation'], variable_map, v)) {
- gl.blendEquation(o3d.State.convertBlendEquation_(gl, v['BlendEquation']));
- }
-
- if (this.relevantValues_(gl, ['CullMode'], variable_map, v)) {
- switch (v['CullMode']) {
- case o3d.State.CULL_CW:
- gl.enable(gl.CULL_FACE);
- gl.cullFace(gl.BACK);
- break;
- case o3d.State.CULL_CCW:
- gl.enable(gl.CULL_FACE);
- gl.cullFace(gl.FRONT);
- break;
- default:
- gl.disable(gl.CULL_FACE);
- break;
- }
- }
-
- if (this.relevantValues_(gl, ['DitherEnable'], variable_map, v)) {
- if (v['DitherEnable']) {
- gl.enable(gl.DITHER);
- } else {
- gl.disable(gl.DITHER);
- }
- }
-
- if (this.relevantValues_(gl, ['ZEnable', 'ZComparisonFunction'],
- variable_map, v)) {
- if (v['ZEnable']) {
- gl.enable(gl.DEPTH_TEST);
- gl.depthFunc(
- this.convertCmpFunc_(gl, v['ZComparisonFunction']));
- } else {
- gl.disable(gl.DEPTH_TEST);
- }
- }
-
- if (this.relevantValues_(gl, ['ZWriteEnable'], variable_map, v)) {
- gl.depthMask(v['ZWriteEnable']);
- }
-
- if (this.relevantValues_(gl, ['StencilEnable', 'StencilComparisonFunction'],
- variable_map, v)) {
- if (v['StencilEnable']) {
- gl.enable(gl.STENCIL_TEST);
- gl.stencilFunc(
- this.convertCmpFunc_(gl, v['StencilComparisonFunction']));
- } else {
- gl.disable(gl.STENCIL_TEST);
- }
- }
-
- if (this.relevantValues_(gl, ['PolygonOffset1',
- 'PolygonOffset2'], variable_map, v)) {
- var polygon_offset_factor = v['PolygonOffset1'] || 0;
- var polygon_offset_bias = v['PolygonOffset2'] || 0;
-
- if (polygon_offset_factor || polygon_offset_bias) {
- gl.enable(gl.POLYGON_OFFSET_FILL);
- gl.polygonOffset(polygon_offset_factor, polygon_offset_bias);
- } else {
- gl.disable(gl.POLYGON_OFFSET_FILL);
- }
- }
-
- if (this.relevantValues_(gl, ['FillMode'], variable_map, v)) {
- // We emulate the behavior of the fill mode state in the primitive class.
- gl.fillMode_ = v['FillMode'];
- }
-};
-
-
-
diff --git a/o3d/samples/o3d-webgl/state_set.js b/o3d/samples/o3d-webgl/state_set.js
deleted file mode 100644
index a2b8bdd..0000000
--- a/o3d/samples/o3d-webgl/state_set.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A StateSet is a render node that sets render states of all of its
- * children. You can make this a parent of a part of the render graph to set
- * render states in a more global way.
- *
- * @param {o3d.State} opt_state The State the defines what states to set.
- * @constructor
- */
-o3d.StateSet = function(opt_state) {
- o3d.RenderNode.call(this);
-
- /**
- * The State for this StateSet.
- * @type {o3d.State}
- */
- this.state = opt_state || null;
-};
-o3d.inherit('StateSet', 'RenderNode');
-
-o3d.ParamObject.setUpO3DParam_(o3d.StateSet, 'state', 'ParamState');
-
-/**
- * Sets the current state to the member state.
- */
-o3d.StateSet.prototype.before = function() {
- if (this.state) {
- this.state.push_();
- }
-};
-
-/**
- * Sets the current state to the member state.
- */
-o3d.StateSet.prototype.after = function() {
- if (this.state) {
- this.state.pop_();
- }
-};
diff --git a/o3d/samples/o3d-webgl/stream.js b/o3d/samples/o3d-webgl/stream.js
deleted file mode 100644
index 322b137..0000000
--- a/o3d/samples/o3d-webgl/stream.js
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * Namespace o3d
- * @constructor
- */
-o3d.Stream = function(semantic, semantic_index, field, start_index) {
- o3d.NamedObject.call(this);
- this.semantic = semantic;
- this.semanticIndex = semantic_index;
- this.field = field;
- this.startIndex = start_index;
-};
-o3d.inherit('Stream', 'NamedObject');
-
-/**
- * @type {number}
- */
-o3d.Stream.Semantic = goog.typedef;
-
-/**
- * Semantic,
- * UNKNOWN_SEMANTIC = 0,
- * POSITION,
- * NORMAL,
- * TANGENT,
- * BINORMAL,
- * COLOR,
- * TEXCOORD,
- * INFLUENCE_WEIGHTS,
- * INFLUENCE_INDICES
- *
- * Semantics used when binding buffers to the streambank. They determine how
- * the Stream links up to the shader inputs.
- */
-o3d.Stream.UNKNOWN_SEMANTIC = 0;
-o3d.Stream.POSITION = 1;
-o3d.Stream.NORMAL = 2;
-o3d.Stream.TANGENT = 3;
-o3d.Stream.BINORMAL = 4;
-o3d.Stream.COLOR = 5;
-o3d.Stream.TEXCOORD = 6;
-o3d.Stream.INFLUENCE_WEIGHTS = 7;
-o3d.Stream.INFLUENCE_INDICES = 8;
-
-
-
-/**
- * The associated Field.
- */
-o3d.Stream.prototype.field = null;
-
-
-
-/**
- * The semantic specified for the Stream.
- */
-o3d.Stream.prototype.semantic = o3d.Stream.UNKNOWN_SEMANTIC;
-
-
-
-/**
- * The semantic index specified for the Stream
- * (eg., TEXCOORD1 = 1, BINORMAL7 = 7, etc).
- */
-o3d.Stream.prototype.semanticIndex = 0;
-
-
-
-/**
- * The start index for the Stream.
- */
-o3d.Stream.prototype.startIndex = 0;
-
-
-/**
- * Gets the max number of vertices in this stream.
- *
- * @return {number} The maximum vertices available given the stream's settings
- * and its buffer.
- * @private
- */
-o3d.Stream.prototype.getMaxVertices_ = function() {
- var buffer = this.field.buffer;
- if (!buffer)
- return 0;
-
- var num_elements = buffer.numElements;
- if (this.startIndex > num_elements)
- return 0;
-
- return num_elements - this.startIndex;
-};
-
diff --git a/o3d/samples/o3d-webgl/stream_bank.js b/o3d/samples/o3d-webgl/stream_bank.js
deleted file mode 100644
index 4d223a3..0000000
--- a/o3d/samples/o3d-webgl/stream_bank.js
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * The StreamBank a collection of streams that hold vertices.
- * @constructor
- * @extends {o3d.VertexSource}
- */
-o3d.StreamBank = function() {
- o3d.VertexSource.call(this);
- this.vertex_streams_ = [];
-};
-o3d.inherit('StreamBank', 'VertexSource');
-
-/**
- * Array of streams.
- */
-o3d.StreamBank.prototype.vertex_streams_ = [];
-
-o3d.StreamBank.prototype.__defineGetter__('vertexStreams',
- function() {
- var result = [];
- for (var i = 0; i < this.vertex_streams_.length; ++i) {
- var stream_array = this.vertex_streams_[i];
- if (stream_array && stream_array.length) {
- for (var j = 0; j < stream_array.length; ++j) {
- var stream = stream_array[j];
- if (stream) {
- result.push(stream.stream);
- }
- }
- }
- }
- return result;
- }
-);
-
-
-/**
- * Binds a VertexBuffer field to the StreamBank and defines how the data in
- * the buffer should be interpreted. The field's buffer must be of a
- * compatible type otherwise the binding fails and the function returns false.
- * @param {o3d.Stream.Semantic} semantic The particular use of this stream.
- * @param {number} semantic_index Which index of a particular semantic to use.
- * @param {o3d.Field} field The field containing information for this stream.
- * @param {number} start_index The first element to use.
- * @return {boolean} True if successful.
- */
-o3d.StreamBank.prototype.setVertexStream =
- function(semantic, semantic_index, field, start_index) {
- if (this.vertex_streams_[semantic] == undefined) {
- this.vertex_streams_[semantic] = [];
- }
- var stream = new o3d.Stream(semantic, semantic_index, field, start_index);
- var stream_param = new o3d.ParamVertexBufferStream;
- stream_param.stream = stream;
- stream_param.owner_ = this;
- this.vertex_streams_[semantic][semantic_index] = stream_param;
-};
-
-
-/**
- * Searches the vertex streams bound to the StreamBank for one with the given
- * stream semantic. If a stream is not found then it returns null.
- * @param {o3d.Stream.Semantic} semantic The particular use of this stream.
- * @param {number} semantic_index Which index of a particular semantic to use.
- * @return {o3d.Stream} The found stream or null if it does not exist.
- */
-o3d.StreamBank.prototype.getVertexStream =
- function(semantic, semantic_index) {
- if (this.vertex_streams_[semantic] == undefined) {
- return null;
- }
- if (!this.vertex_streams_[semantic][semantic_index]) {
- return null;
- }
- return this.vertex_streams_[semantic][semantic_index].stream;
-};
-
-
-/**
- * Searches the vertex streams bound to the StreamBank for one with the given
- * stream semantic. If a stream is not found then it returns null.
- * @param {o3d.Stream.Semantic} semantic The particular use of this stream.
- * @param {number} semantic_index Which index of a particular semantic to use.
- * @return {o3d.ParamVertexBufferStream} The found stream param or null if it
- * does not exist.
- * @override
- * @protected
- */
-o3d.StreamBank.prototype.getVertexStreamParam =
- function(semantic, semantic_index) {
- if (this.vertex_streams_[semantic] == undefined) {
- return null;
- }
- return this.vertex_streams_[semantic][semantic_index];
-};
-
-
-/**
- * Removes a vertex stream from this StreamBank.
- * @param {o3d.Stream.Semantic} semantic The particular use of this stream.
- * @param {o3d.Stream.Semantic} semantic_index Which index of a particular
- * semantic to use.
- * @return {boolean} true if the specified stream existed.
- */
-o3d.StreamBank.prototype.removeVertexStream =
- function(semantic, semantic_index) {
- if (this.vertex_streams_[semantic] == undefined) {
- return false;
- }
- delete this.vertex_streams_[semantic][semantic_index];
- return true;
-};
-
-
diff --git a/o3d/samples/o3d-webgl/texture.js b/o3d/samples/o3d-webgl/texture.js
deleted file mode 100644
index ec35293..0000000
--- a/o3d/samples/o3d-webgl/texture.js
+++ /dev/null
@@ -1,965 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * The Texture class is a base class for image data used in texture mapping.
- * @constructor
- */
-o3d.Texture = function() {
- o3d.ParamObject.call(this);
-
- /**
- * The memory format used for storing the bitmap associated with the texture
- * object.
- * @type {o3d.Texture.Format}
- */
- this.format = o3d.Texture.UNKNOWN_FORMAT;
-
- /**
- * The number of mipmap levels used by the texture.
- * @type {number}
- */
- this.levels = 1;
-
- /**
- * True if all the alpha values in the texture are 1.0
- * @type {boolean}
- */
- this.alphaIsOne = true;
-
- /**
- * The associated gl texture.
- * @type {WebGLTexture}
- * @private
- */
- this.texture_ = null;
-
- /**
- * The associated GL texture target: TEXTURE_2D or TEXTURE_CUBE_MAP.
- * This is the argument "target" to calls to bindTeture.
- * NOT THE SAME THING AS the argument "target" to texImage2D.
- * @type {number}
- * @private
- */
- this.texture_target_ = 0;
-
- /**
- * The width of the underlying webgl texture.
- * @type {number}
- * private
- */
- this.texture_width_ = 0;
-
- /**
- * The width of the underlying webgl texture.
- * @type {number}
- * private
- */
- this.texture_height_ = 0;
-
- /**
- * When texParameters get set, this keeps track of what they are so we don't
- * set them again next time if we don't have to.
- * @private
- */
- this.parameter_cache_ = {};
-};
-o3d.inherit('Texture', 'ParamObject');
-
-
-/**
- * @type {number}
- */
-o3d.Texture.Format = goog.typedef;
-
-/**
- * Format,
- * UNKNOWN_FORMAT
- * XRGB8
- * ARGB8
- * ABGR16F
- * R32F
- * ABGR32F
- * DXT1
- * DXT3
- * DXT5
- *
- * The in-memory format of the texture bitmap.
- *
- * NOTE: The R32F format is different on GL vs D3D. If you use it in a shader
- * you must only use the red channel. The green, blue and alpha channels are
- * undefined.
- *
- * For example:
- *
- * ...
- *
- * sampler texSampler0;
- *
- * ...
- *
- * struct PixelShaderInput {
- * float4 position : POSITION;
- * float2 texcoord : TEXCOORD0;
- * };
- *
- * float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- * return tex2D(texSampler0, input.texcoord).rrrr;
- * }
- *
- * @param {number} levels The number of mip levels in this texture.
- */
-o3d.Texture.UNKNOWN_FORMAT = 0;
-o3d.Texture.XRGB8 = 1;
-o3d.Texture.ARGB8 = 2;
-o3d.Texture.ABGR16F = 3;
-o3d.Texture.R32F = 4;
-o3d.Texture.ABGR32F = 5;
-o3d.Texture.DXT1 = 6;
-o3d.Texture.DXT3 = 7;
-o3d.Texture.DXT5 = 8;
-
-
-/**
- * Generates Mips.
- * @param {number} source_level the mip to use as the source.
- * @param {number} num_levels the number of mips from the source to generate.
- */
-o3d.Texture.prototype.generateMips =
- function(source_level, num_levels) {
- this.gl.bindTexture(this.texture_target_, this.texture_);
- this.gl.generateMipmap(this.texture_target_);
- this.levels = num_levels;
-};
-
-
-/**
- * Indicates whether the given number is a power of two.
- * @param {number} value The number.
- * @private
- */
-o3d.Texture.isPowerOfTwo_ = function(value) {
- return (value & (value - 1)) == 0;
-};
-
-
-/**
- * Computes the smallest power of two that is greater than or equal to the
- * the given number.
- * @param {number} value The number.
- * @private
- */
-o3d.Texture.nextHighestPowerOfTwo_ = function(value) {
- var r = 1;
- while (r < value) {
- r *= 2;
- }
- return r;
-};
-
-
-/**
- * Returns the GL texture format that is closest to this texture's O3D texture
- * format. Not all formats specified in o3d.Texture have a webgl equivalent,
- * thus we return the one with the correct number of channels, if such exists.
- *
- * @return {number} A webgl format.
- * @private
- */
-o3d.Texture.prototype.getGLTextureFormat_ = function() {
- switch (this.format) {
- case o3d.Texture.XRGB8:
- return this.gl.RGB;
-
- case o3d.Texture.ARGB8:
- case o3d.Texture.ABGR16F:
- case o3d.Texture.ABGR32F:
- return this.gl.RGBA;
-
- case o3d.Texture.R32F:
- case o3d.Texture.DXT1:
- case o3d.Texture.DXT3:
- case o3d.Texture.DXT5:
- default:
- o3d.notImplemented();
- return 0;
- }
-}
-
-
-/**
- * Helper function to determine the proper argument for the texture target
- * This is either gl.TEXTURE_2D or gl.TEXTURE_CUBE_MAP_POSITIVE_X + face.
- *
- * @param {o3d.TextureCUBE.CubeFace} face The current face if applicable.
- * @return {number} The proper argument for the texture target.
- */
-o3d.Texture.prototype.getTexImage2DTarget_ = function(opt_face) {
- if (this.texture_target_ == this.gl.TEXTURE_CUBE_MAP) {
- return this.gl.TEXTURE_CUBE_MAP_POSITIVE_X + opt_face;
- } else {
- return this.gl.TEXTURE_2D;
- }
-};
-
-
-/**
- * Computes the maximum number of levels of mips a given width and height could
- * use.
- * @param {number} width Width of texture.
- * @param {number} height Height of texture.
- * @return {number} The maximum number of levels for the given width and height.
- */
-o3d.Texture.maxLevels_ = function(width, height) {
- if (width == 0 || height == 0) {
- return 0;
- }
- var max = Math.max(width, height);
- var levels = 0;
- while (max > 0) {
- ++levels;
- max = max >> 1;
- }
- return levels;
-};
-
-
-var g_counter = 0;
-
-
-/**
- * Creates a webgl texture from the given image object rescaling to the
- * smallest power of 2 in each dimension still no smaller than the original
- * size.
- * @param {HTMLCanvas} canvas The canvas to load into the texture.
- * @param {boolean} resize_to_pot Whether or not to resize to a power of two
- * size.
- * @param {boolean} generate_mips Whether or not to generate mips.
- * @param {o3d.TextureCUBE.CubeFace} opt_face The face number, if this is a
- * cube map.
- * @private
- */
-o3d.Texture.prototype.setFromCanvas_ =
- function(canvas, resize_to_pot, flip, generate_mips, opt_face) {
- var gl = this.gl;
-
- if (resize_to_pot && (!o3d.Texture.isPowerOfTwo_(canvas.width) ||
- !o3d.Texture.isPowerOfTwo_(canvas.height))) {
- // Get a scratch canvas.
- var scratch = o3d.Bitmap.getScratchCanvas_();
- // Set the size of the canvas to the power-of-two size.
- scratch.width = o3d.Texture.nextHighestPowerOfTwo_(canvas.width);
- scratch.height = o3d.Texture.nextHighestPowerOfTwo_(canvas.height);
- // Draw the given canvas into that scratch canvas.
- scratch.getContext("2d").drawImage(canvas,
- 0, 0, canvas.width, canvas.height,
- 0, 0, scratch.width, scratch.height);
- canvas = scratch;
- }
-
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flip);
-
- gl.bindTexture(this.texture_target_, this.texture_);
- gl.texImage2D(this.getTexImage2DTarget_(opt_face), 0 /*level*/, gl.RGBA,
- gl.RGBA, gl.UNSIGNED_BYTE, canvas);
-
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
-
-
- this.texture_width_ = canvas.width;
- this.texture_height_ = canvas.height;
-
- if (generate_mips) {
- // The texture target is already bound so why bind it again by calling
- // this.generateMip.
- this.gl.generateMipmap(this.texture_target_);
- this.levels = o3d.Texture.maxLevels_(
- this.texture_width_, this.texture_height_);
- }
-
- g_counter++;
-};
-
-
-/**
- * Copy pixels from source bitmap to certain mip level.
- * Scales if the width and height of source and dest do not match.
- *
- * @param {HTMLCanvas} source_img The source canvas.
- * @param {number} source_x x-coordinate of the starting pixel in the
- * source image.
- * @param {number} source_y y-coordinate of the starting pixel in the
- * source image.
- * @param {number} source_width width of the source image to draw.
- * @param {number} source_height Height of the source image to draw.
- * @param {number} dest_mip on which mip level to draw to.
- * @param {number} dest_x x-coordinate of the starting pixel in the
- * destination texture.
- * @param {number} dest_y y-coordinate of the starting pixel in the
- * destination texture.
- * @param {number} dest_width width of the dest image.
- * @param {number} dest_height height of the dest image.
- * @param {number} opt_face The face number if this is a cube map.
- */
-o3d.Texture.prototype.drawImageFromCanvas_ =
- function(source_canvas, source_x, source_y, source_width, source_height,
- dest_mip, dest_x, dest_y, dest_width, dest_height, opt_face) {
- var canvas = o3d.Bitmap.getScratchCanvas_();
- canvas.width = dest_width;
- canvas.height = dest_height;
-
- // Get a scratch canvas and set its size to that of the source material.
- // Set up transformation so that the draw into the canvas fill it with the
- // source bitmap.
- var context = canvas.getContext('2d');
- context.save();
-
- context.translate(-source_x, -source_y);
- context.scale(dest_width / source_width,
- dest_height / source_height);
-
- // Draw the source image into the canvas, filling it.
- context.drawImage(
- source_canvas, 0, 0, source_canvas.width, source_canvas.height);
-
- // Call texSubImage2D to upload the source image from the scratch canvas
- // to the texture.
- var gl = this.gl;
- gl.bindTexture(this.texture_target_, this.texture_);
- var format = this.getGLTextureFormat_();
-
- //*/
- // TODO(petersont): Replace this with a call to texSubImage2D once
- // browsers support it.
- gl.texImage2D(this.getTexImage2DTarget_(opt_face), dest_mip, gl.RGBA,
- gl.RGBA, gl.UNSIGNED_BYTE, canvas);
- /*/
- gl.texSubImage2D(target, 0, dest_x, dest_y, dest_width, dest_height,
- gl.RGBA, gl.UNSIGNED_BYTE, canvas);
- //*/
- this.texture_width_ = canvas.width;
- this.texture_height_ = canvas.height;
-
- context.restore();
-};
-
-
-/**
- * Sets the values of the data stored in the texture.
- *
- * @param {number} level the mip level to update.
- * @param {number} values Values to be stored in the buffer.
- * @param {o3d.TextureCUBE.CubeFace} opt_face The face to set if this is a cube
- * texture.
- * @private
- */
-o3d.Texture.prototype.setValues_ = function(level, values, opt_face) {
- var pixels = new Uint8Array(values.length);
- for (var i = 0; i < values.length; ++i) {
- pixels[i] = Math.min(255, Math.max(0, values[i] * 256.0));
- }
-
- var format = this.getGLTextureFormat_();
- this.gl.bindTexture(this.texture_target_, this.texture_);
-
- this.gl.texSubImage2D(this.getTexImage2DTarget_(opt_face),
- level, 0, 0, this.texture_width_, this.texture_height_,
- format, this.gl.UNSIGNED_BYTE, pixels);
-};
-
-
-/**
- * Initializes this Texture2D object of the specified size and format and
- * reserves the necessary resources for it.
- *
- * Note: If enable_render_surfaces is true, then the dimensions must be a
- * power of two.
- *
- * @param {number} texture_target The apropriate value for texture_target.
- * @param {number} width The width of the texture area in texels (max = 2048)
- * @param {number} height The height of the texture area in texels (max = 2048)
- * @param {o3d.Texture.Format} format The memory format of each texel
- * @param {number} levels The number of mipmap levels. Use zero to create the
- * compelete mipmap chain.
- * @param {boolean} enable_render_surfaces If true, the texture object will
- * expose RenderSurface objects through GetRenderSurface(...).
- * @return {!o3d.Texture2D} The Texture2D object.
- */
-o3d.Texture.prototype.initWithTarget_ =
- function(texture_target, width, height, format, levels,
- enable_render_surfaces, debug) {
- this.width = width;
- this.height = height;
- this.format = format;
- this.levels = levels;
- this.texture_ = this.gl.createTexture();
- this.texture_target_ = texture_target;
-
- if (width != undefined && height != undefined) {
- this.gl.bindTexture(this.texture_target_, this.texture_);
-
- var format = this.getGLTextureFormat_();
-
- // TODO(petersont): remove this allocation once Firefox supports
- // passing null as argument to this form of ... some function.
- var pixels = new Uint8Array(width * height * 4);
-
- var canvas = o3d.Bitmap.getScratchCanvas_();
- canvas.width = width;
- canvas.height = height;
-
- var numFaces = 1;
- if (this.texture_target_ == this.gl.TEXTURE_CUBE_MAP) {
- numFaces = 6;
- }
-
- for (var face = 0; face < numFaces; ++face) {
- this.gl.texImage2D(this.getTexImage2DTarget_(face), 0, format, width,
- height, 0, format, this.gl.UNSIGNED_BYTE, pixels);
- }
-
- this.texture_width_ = width;
- this.texture_height_ = height;
- }
-};
-
-
-/**
- * A class for 2D textures that defines the interface for getting
- * the dimensions of the texture, its memory format and number of mipmap levels.
- *
- * @param {number} opt_width The width of this texture in pixels.
- * @param {number} opt_height The height of this texture in pixels.
- * @constructor
- */
-o3d.Texture2D = function(opt_width, opt_height) {
- o3d.Texture.call(this);
-
- /**
- * The width of the texture, in texels.
- * @type {number}
- */
- this.width = opt_width || 0;
-
- /**
- * The height of the texture, in texels.
- * @type {number}
- */
- this.height = opt_height || 0;
-
- /**
- * The cache of rendersurface objects.
- * @private
- */
- this.renderSurfaces_ = [];
-};
-o3d.inherit('Texture2D', 'Texture');
-
-o3d.ParamObject.setUpO3DParam_(o3d.Texture2D, 'width', 'ParamInteger');
-o3d.ParamObject.setUpO3DParam_(o3d.Texture2D, 'height', 'ParamInteger');
-
-
-/**
- * Initializes this Texture2D object of the specified size and format and
- * reserves the necessary resources for it.
- *
- * Note: If enable_render_surfaces is true, then the dimensions must be a
- * power of two.
- *
- * @param {number} width The width of the texture area in texels (max = 2048)
- * @param {number} height The height of the texture area in texels (max = 2048)
- * @param {o3d.Texture.Format} format The memory format of each texel
- * @param {number} levels The number of mipmap levels. Use zero to create the
- * compelete mipmap chain.
- * @param {boolean} enable_render_surfaces If true, the texture object will
- * expose RenderSurface objects through GetRenderSurface(...).
- * @return {!o3d.Texture2D} The Texture2D object.
- */
-o3d.Texture2D.prototype.init_ =
- function(width, height, format, levels, enable_render_surfaces) {
- this.initWithTarget_(this.gl.TEXTURE_2D,
- width, height, format, levels, enable_render_surfaces);
-};
-
-
-/**
- * Returns a RenderSurface object associated with a mip_level of a texture.
- *
- * @param {number} mip_level The mip-level of the surface to be returned.
- * @return {o3d.RenderSurface} The RenderSurface object.
- */
-o3d.Texture2D.prototype.getRenderSurface =
- function(mip_level) {
- if (!this.renderSurfaces_[mip_level]) {
- var renderSurface = new o3d.RenderSurface();
- renderSurface.gl = this.gl;
- renderSurface.initWithTexture(this, mip_level);
- this.renderSurfaces_[mip_level] = renderSurface;
- }
-
- return this.renderSurfaces_[mip_level];
-};
-
-
-/**
- * Sets the values of the data stored in the texture.
- *
- * It is not recommend that you call this for large textures but it is useful
- * for making simple ramps or noise textures for shaders.
- *
- * NOTE: the number of values must equal the size of the texture * the number
- * of elements. In other words, for a XRGB8 texture there must be
- * width * height * 3 values. For an ARGB8, ABGR16F or ABGR32F texture there
- * must be width * height * 4 values. For an R32F texture there must be
- * width * height values.
- *
- * NOTE: the order of channels is R G B for XRGB8 textures and R G B A
- * for ARGB8, ABGR16F and ABGR32F textures so for example for XRGB8 textures
- *
- * [1, 0, 0] = a red pixel
- * [0, 0, 1] = a blue pixel
- *
- * For ARGB8, ABGR16F, ABGR32F textures
- *
- * [1, 0, 0, 0] = a red pixel with zero alpha
- * [1, 0, 0, 1] = a red pixel with one alpha
- * [0, 0, 1, 1] = a blue pixel with one alpha
- *
- * @param {number} level the mip level to update.
- * @param {values} values Values to be stored in the buffer.
- */
-o3d.Texture2D.prototype.set =
- function(level, values) {
- this.setValues_(level, values);
-};
-
-
-/**
- * Sets a rectangular area of values in a texture.
- *
- * Does clipping. In other words if you pass in a 10x10 pixel array
- * and give it destination of (-5, -5) it will only use the bottom 5x5
- * pixels of the array you passed in to set the top 5x5 pixels of the
- * texture.
- *
- * See o3d.Texture2D.set for details on formats.
- *
- * @param {number} level the mip level to update.
- * @param {number} destination_x The x coordinate of the area in the texture
- * to affect.
- * @param {number} destination_y The y coordinate of the area in the texture
- * to affect.
- * @param {number} source_width The width of the area to effect. The height is
- * determined by the size of the array passed in.
- * @param {number} values Values to be stored in the buffer.
- */
-o3d.Texture2D.prototype.setRect =
- function(level, destination_x, destination_y, source_width, values) {
- var format = this.getGLTextureFormat_();
- var numChannels = (format == this.gl.RGB ? 3 : 4);
- var source_height = (values.length / numChannels) / source_width;
-
- // If completely clipped off, do nothing and return.
- if (destination_x > this.width || destination_y > this.height ||
- destination_x + source_width < 0 || destination_y + source_height < 0) {
- return;
- }
-
- // Size of the unclipped, remaining rectangle.
- var size_x = source_width;
- if (destination_x < 0) {
- size_x += destination_x;
- }
- if (destination_x + source_width > this.width) {
- size_x -= (destination_x + source_width) - this.width;
- }
-
- var size_y = source_height;
- if (destination_y < 0) {
- size_y += destination_y;
- }
- if (destination_y + source_height > this.height) {
- size_y -= (destination_y + source_height) - this.height;
- }
-
- // The upper left corner of the rectangle that is not clipped and will be
- // copied into the texture.
- var start_x = (destination_x < 0) ? Math.abs(destination_x) : 0;
- var start_y = (destination_y < 0) ? Math.abs(destination_y) : 0;
-
- var keptPixels = new Uint8Array(size_x * size_y * numChannels);
- var count = 0;
- for (var y = 0; y < size_y; ++y) {
- for (var x = 0; x < size_x; ++x) {
- var t = (((start_y + y) * source_width) + (start_x + x)) * numChannels;
- keptPixels[count++] = Math.min(255, Math.max(0, values[t] * 256.0));
- keptPixels[count++] = Math.min(255, Math.max(0, values[t + 1] * 256.0));
- keptPixels[count++] = Math.min(255, Math.max(0, values[t + 2] * 256.0));
- keptPixels[count++] = Math.min(255, Math.max(0, values[t + 3] * 256.0));
- }
- }
-
- // The (x, y) at which to begin drawing the rectangle on the original texture,
- // measured from the *BOTTOM* left hand corner.
- var where_x = Math.max(destination_x, 0);
- var where_y = this.height - (Math.max(destination_y, 0) + size_y);
-
- this.gl.bindTexture(this.texture_target_, this.texture_);
- this.gl.texSubImage2D(this.gl.TEXTURE_2D, level, where_x, where_y,
- size_x, size_y, format, this.gl.UNSIGNED_BYTE, keptPixels);
-};
-
-
-/**
- * Gets a rectangular area of values from a texture.
- *
- * See o3d.Texture2D.set for details on formats.
- * Can not be used for compressed textures.
- *
- * @param {number} level the mip level to get.
- * @param {number} x The x coordinate of the area in the texture to retrieve.
- * @param {number} y The y coordinate of the area in the texture to retrieve.
- * @param {number} width The width of the area to retrieve.
- * @param {number} height The height of the area to retrieve.
- * @return {number} Array of pixel values.
- */
-o3d.Texture2D.prototype.getRect =
- function(level, x, y, width, height) {
- o3d.notImplemented();
-};
-
-
-/**
- * Sets the content of the texture to the content of the bitmap. The texture
- * and the bitmap must be the same dimensions and the same format.
- *
- * @param {o3d.Bitmap} bitmap The bitmap to copy data from.
- */
-o3d.Texture2D.prototype.setFromBitmap = function(bitmap) {
- // Whether to resize the texture to power-of-two size.
- var resize_to_pot = bitmap.defer_mipmaps_to_texture_;
- this.setFromCanvas_(bitmap.canvas_,
- resize_to_pot,
- bitmap.defer_flip_vertically_to_texture_,
- bitmap.defer_mipmaps_to_texture_);
-};
-
-
-/**
- * Copy pixels from source bitmap to certain face and mip level.
- * Scales if the width and height of source and dest do not match.
- *
- * @param {o3d.Bitmap} source_img The source bitmap.
- * @param {number} source_mip which mip of the source to copy from.
- * @param {number} source_x x-coordinate of the starting pixel in the
- * source image.
- * @param {number} source_y y-coordinate of the starting pixel in the
- * source image.
- * @param {number} source_width width of the source image to draw.
- * @param {number} source_height Height of the source image to draw.
- * @param {number} dest_mip on which mip level to draw to.
- * @param {number} dest_x x-coordinate of the starting pixel in the
- * destination texture.
- * @param {number} dest_y y-coordinate of the starting pixel in the
- * destination texture.
- * @param {number} dest_width width of the destination image.
- * @param {number} dest_height height of the destination image.
- */
-o3d.Texture2D.prototype.drawImage =
- function(source_img, source_mip, source_x, source_y, source_width,
- source_height, dest_mip, dest_x, dest_y, dest_width, dest_height) {
- this.drawImageFromCanvas_(source_img.canvas_,
- source_x, source_y, source_width, source_height, dest_mip,
- dest_x, dest_y, dest_width, dest_height);
-};
-
-
-/**
- * TextureCUBE is a class for textures used for cube mapping. A cube texture
- * stores bitmaps for the 6 faces of a cube and is addressed via three texture
- * coordinates.
- *
- * @param {number} edgeLength The length of any edge of this texture
- * @constructor
- */
-o3d.TextureCUBE = function() {
- o3d.Texture.call(this);
-
- /**
- * The length of each edge of the cube, in texels.
- * @type {number}
- */
- this.edgeLength = 0;
-
- /**
- * Keeps track of whether the faces of the cube map have been set to a
- * bitmap of some sort. Used to prolong the generation of mipmaps until the
- * last cube face has been set to something.
- * @type {!Object}
- * @private
- */
- this.faces_set_ = {
- 0: false, 1: false, 2: false, 3: false, 4: false, 5: false
- };
-};
-o3d.inherit('TextureCUBE', 'Texture');
-
-
-/**
- * @type {number}
- */
-o3d.TextureCUBE.CubeFace = goog.typedef;
-
-
-/**
- * CubeFace,
- * FACE_POSITIVE_X
- * FACE_NEGATIVE_X
- * FACE_POSITIVE_Y
- * FACE_NEGATIVE_Y
- * FACE_POSITIVE_Z
- * FACE_NEGATIVE_Z
- *
- * The names of each of the six faces of a cube map texture.
- */
-o3d.TextureCUBE.FACE_POSITIVE_X = 0;
-o3d.TextureCUBE.FACE_NEGATIVE_X = 1;
-o3d.TextureCUBE.FACE_POSITIVE_Y = 2;
-o3d.TextureCUBE.FACE_NEGATIVE_Y = 3;
-o3d.TextureCUBE.FACE_POSITIVE_Z = 4;
-o3d.TextureCUBE.FACE_NEGATIVE_Z = 5;
-
-o3d.ParamObject.setUpO3DParam_(o3d.TextureCUBE, 'edgeLength', 'ParamInteger');
-
-
-/**
- * Initializes this TextureCUBE object of the specified size and format and
- * reserves the necessary resources for it.
- * Note: If enable_render_surfaces is true, then the dimensions must be a
- * power of two.
- *
- * @param {number} edgeLength The edge of the texture area in texels
- * (max = 2048)
- * @param {o3d.Texture.Format} format The memory format of each texel.
- * @param {number} levels The number of mipmap levels. Use zero to create
- * the compelete mipmap chain.
- * @param {boolean} enableRenderSurfaces If true, the texture object
- * will expose RenderSurface objects through GetRenderSurface(...).
- * @private
- */
-o3d.TextureCUBE.prototype.init_ =
- function(edgeLength, format, levels, enable_render_surfaces, debug) {
- this.initWithTarget_(this.gl.TEXTURE_CUBE_MAP,
- edgeLength, edgeLength, format, levels, enable_render_surfaces, debug);
-};
-
-
-/**
- * Returns a RenderSurface object associated with a given cube face and
- * mip_level of a texture.
- *
- * @param {o3d.TextureCUBE.CubeFace} face The cube face from which to extract
- * the surface.
- * @param {o3d.Pack} pack This parameter is no longer used. The surface exists
- * as long as the texture it came from exists.
- * @param {number} mip_level The mip-level of the surface to be returned.
- * @return {o3d.RenderSurface} The RenderSurface object.
- */
-o3d.TextureCUBE.prototype.getRenderSurface =
- function(face, mip_level, opt_pack) {
- o3d.notImplemented();
-};
-
-
-/**
- * Sets the values of the data stored in the texture.
- *
- * It is not recommend that you call this for large textures but it is useful
- * for making simple ramps or noise textures for shaders.
- *
- * See o3d.Texture2D.set for details on formats.
- *
- * @param {o3d.TextureCUBE.CubeFace} face the face to update.
- * @param {number} level the mip level to update.
- * @param {number} values Values to be stored in the buffer.
- */
-o3d.TextureCUBE.prototype.set =
- function(face, level, values) {
- this.setValues_(level, values, face);
- this.faces_set_[face] = true;
-};
-
-
-/**
- * Sets a rectangular area of values in a texture.
- *
- * Does clipping. In other words if you pass in a 10x10 pixel array
- * and give it destination of (-5, -5) it will only use the bottom 5x5
- * pixels of the array you passed in to set the top 5x5 pixels of the
- * texture.
- *
- * See o3d.Texture2D.set for details on formats.
- *
- * @param {o3d.TextureCUBE.CubeFace} face the face to update.
- * @param {number} level the mip level to update.
- * @param {number} destination_x The x coordinate of the area in the texture
- * to affect.
- * @param {number} destination_y The y coordinate of the area in the texture
- * to affect.
- * @param {number} source_width The width of the area to effect. The height is
- * determined by the size of the array passed in.
- * @param {number} values Values to be stored in the buffer.
- */
-o3d.TextureCUBE.prototype.setRect =
- function(face, level, destination_x, destination_y, source_width, values) {
- o3d.notImplemented();
-};
-
-
-/**
- * Gets a rectangular area of values from a texture.
- *
- * See o3d.Texture2D.set for details on formats.
- * Can not be used for compressed textures.
- *
- * @param {o3d.TextureCUBE.CubeFace} face the face to get.
- * @param {number} level the mip level to get.
- * @param {number} x The x coordinate of the area in the texture to retrieve.
- * @param {number} y The y coordinate of the area in the texture to retrieve.
- * @param {number} width The width of the area to retrieve.
- * @param {number} height The height of the area to retrieve.
- * @return {number} Array of pixel values.
- */
-o3d.TextureCUBE.prototype.getRect =
- function(face, level, x, y, width, height) {
- o3d.notImplemented();
-};
-
-
-/**
- * Sets the content of a face of the texture to the content of the bitmap. The
- * texture and the bitmap must be the same dimensions and the same format.
- *
- * @param {o3d.TextureCUBE.CubeFace} face The face to set.
- * @param {o3d.Bitmap} bitmap The bitmap to copy data from.
- */
-o3d.TextureCUBE.prototype.setFromBitmap =
- function(face, bitmap) {
- var generate_mipmaps = bitmap.defer_mipmaps_to_texture_;
- for (var f in this.faces_set_) {
- generate_mipmaps = generate_mipmaps &&
- (this.faces_set_[f] || f == face);
- }
- var resize_to_pot = bitmap.defer_mipmaps_to_texture_;
- this.setFromCanvas_(bitmap.canvas_,
- resize_to_pot,
- false, // Never flip cube maps.
- generate_mipmaps,
- face);
- this.faces_set_[face] = true;
-};
-
-
-/**
- * Copy pixels from source bitmap to certain face and mip level.
- * Scales if the width and height of source and dest do not match.
- * TODO(petersont): Should take optional arguments.
- *
- * @param {o3d.Bitmap} source_img The source bitmap.
- * @param {number} source_mip which mip of the source to copy from.
- * @param {number} source_x x-coordinate of the starting pixel in the
- * source image.
- * @param {number} source_y y-coordinate of the starting pixel in the
- * source image.
- * @param {number} source_width width of the source image to draw.
- * @param {number} source_height Height of the source image to draw.
- * @param {o3d.TextureCUBE.CubeFace} face on which face to draw on.
- * @param {number} dest_mip on which mip level to draw on.
- * @param {number} dest_x x-coordinate of the starting pixel in the
- * destination texture.
- * @param {number} dest_y y-coordinate of the starting pixel in the
- * destination texture.
- * @param {number} dest_width width of the destination image.
- * @param {number} dest_height height of the destination image.
- */
-o3d.TextureCUBE.prototype.drawImage =
- function(source_img, source_mip, source_x, source_y, source_width,
- source_height, face, dest_mip, dest_x, dest_y, dest_width,
- dest_height) {
- this.drawImageFromCanvas_(source_img.canvas_,
- source_x, source_y, source_width, source_height, dest_mip,
- dest_x, dest_y, dest_width, dest_height, face);
-};
-
-
-/**
- * Makes this texture currrent, and sets various texParameters provided they
- * have changed since the last time bindAndSetParameters_ was called for this
- * texture.
- * @param {number} addressModeU The address mode in the U coordinate.
- * @param {number} addressModeV The address mode in the V coordinate.
- * @param {number} minFilter The type of the min filter.
- * @param {number} magFilter The type of the mag filter.
- */
-o3d.Texture.prototype.bindAndSetParameters_ =
- function(addressModeU, addressModeV, minFilter, magFilter) {
- var target = this.texture_target_;
- this.gl.bindTexture(target, this.texture_);
-
- if (!(o3d.Texture.isPowerOfTwo_(this.texture_width_) &&
- o3d.Texture.isPowerOfTwo_(this.texture_height_)) ||
- this.texture_target_ == this.gl.TEXTURE_CUBE_MAP) {
- addressModeU = addressModeV = this.gl.CLAMP_TO_EDGE;
- }
-
- if (this.parameter_cache_.addressModeU != addressModeU) {
- this.gl.texParameteri(target, this.gl.TEXTURE_WRAP_S, addressModeU);
- this.parameter_cache_.addressModeU = addressModeU;
- }
-
- if (this.parameter_cache_.addressModeV != addressModeV) {
- this.gl.texParameteri(target, this.gl.TEXTURE_WRAP_T, addressModeV);
- this.parameter_cache_.addressModeV = addressModeV;
- }
-
- if (this.parameter_cache_.minFilter != minFilter) {
- this.gl.texParameteri(target, this.gl.TEXTURE_MIN_FILTER, minFilter);
- this.parameter_cache_.minFilter = minFilter;
- }
-
- if (this.parameter_cache_.magFilter != magFilter) {
- this.gl.texParameteri(target, this.gl.TEXTURE_MAG_FILTER, magFilter);
- this.parameter_cache_.magFilter = magFilter;
- }
-};
-
-
diff --git a/o3d/samples/o3d-webgl/transform.js b/o3d/samples/o3d-webgl/transform.js
deleted file mode 100644
index 9d1a8f9..0000000
--- a/o3d/samples/o3d-webgl/transform.js
+++ /dev/null
@@ -1,1370 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * The Transform defines parent child relationship and a localMatrix..
- * A Transform can have one or no parents and
- * an arbitrary number of children.
- *
- * @param {o3d.math.Matrix4} opt_localMatrix The local matrix for this
- * transform.
- * @param {o3d.math.Matrix4} opt_worldMatrix ParamMatrix4 The world matrix of
- * this transform.
- * @param {boolean} opt_visible Whether or not this transform and all its
- * children are visible.
- * @param {o3d.BoundingBox} opt_boundingBox ParamBoundingBox The bounding box
- * for this transform and all its children.
- * @param {boolean} opt_cull ParamBoolean Whether or not to attempt to
- * cull this transform and all its children based on whether or not its
- * bounding box is in the view frustum.
- * @constructor
- */
-o3d.Transform =
- function(opt_localMatrix, opt_worldMatrix, opt_visible, opt_boundingBox,
- opt_cull) {
- o3d.ParamObject.call(this);
-
- /**
- * Local transformation matrix.
- * Default = Identity.
- */
- this.localMatrix = opt_localMatrix ||
- o3d.Transform.makeIdentityMatrix4_();
-
- /**
- * World (model) matrix as it was last computed.
- */
- this.worldMatrix = opt_worldMatrix ||
- o3d.Transform.makeIdentityMatrix4_();
-
- /**
- * Sets the parent of the transform by re-parenting the transform under
- * parent. Setting parent to null removes the transform and the
- * entire subtree below it from the transform graph.
- * If the operation would create a cycle it fails.
- */
- this.parent = null;
-
- /**
- * The Visibility for this transform.
- * Default = true.
- */
- this.visible = opt_visible || true;
-
- /**
- * The BoundingBox for this Transform. If culling is on this
- * bounding box will be tested against the view frustum of any draw
- * context used to with this Transform.
- * @type {!o3d.BoundingBox}
- */
- this.boundingBox = opt_boundingBox ||
- new o3d.BoundingBox([-1, -1, -1], [1, 1, 1]);
-
- /**
- * The cull setting for this transform. If true this Transform will
- * be culled by having its bounding box compared to the view frustum
- * of any draw context it is used with.
- * Default = false.
- */
- this.cull = opt_cull || false;
-
- /**
- * The immediate children of this Transform.
- *
- * Each access to this field gets the entire list, so it is best to get it
- * just once. For example:
- *
- * var children = transform.children;
- * for (var i = 0; i < children.length; i++) {
- * var child = children[i];
- * }
- *
- * Note that modifications to this array [e.g. additions to it] will
- * not affect the underlying Transform, while modifications to the
- * members of the array will affect them.
- */
- this.children = [];
-
- /**
- * Gets the shapes owned by this transform.
- *
- * Each access to this field gets the entire list so it is best to get it
- * just once. For example:
- *
- * var shapes = transform.shapes;
- * for (var i = 0; i < shapes.length; i++) {
- * var shape = shapes[i];
- * }
- *
- *
- * Note that modifications to this array [e.g. additions to it] will
- * not affect the underlying Transform, while modifications to the
- * members of the array will affect them.
- */
- this.shapes = [];
-};
-o3d.inherit('Transform', 'ParamObject');
-
-o3d.ParamObject.setUpO3DParam_(o3d.Transform, 'visible', 'ParamBoolean');
-// TODO(petersont): need to better understand and possibly implement
-// the semantics of SlaveParamMatrix4.
-o3d.ParamObject.setUpO3DParam_(o3d.Transform, 'worldMatrix', 'ParamMatrix4');
-o3d.ParamObject.setUpO3DParam_(o3d.Transform, 'localMatrix', 'ParamMatrix4');
-o3d.ParamObject.setUpO3DParam_(o3d.Transform, 'cull', 'ParamBoolean');
-o3d.ParamObject.setUpO3DParam_(o3d.Transform,
- 'boundingBox', 'ParamBoundingBox');
-
-
-o3d.Transform.prototype.__defineSetter__('parent',
- function(p) {
- if (this.parent_ != null) {
- o3d.removeFromArray(this.parent_.children, this);
- }
- this.parent_ = p;
- if (p) {
- p.addChild(this);
- }
- }
-);
-
-o3d.Transform.prototype.__defineGetter__('parent',
- function(p) {
- return this.parent_;
- }
-);
-
-/**
- * Adds a child transform.
- * @param {o3d.Transform} The new child.
- */
-o3d.Transform.prototype.addChild = function(child) {
- this.children.push(child);
-};
-
-
-/**
- * Returns all the transforms under this transform including this one.
- *
- * Note that modifications to this array [e.g. additions to it] will not affect
- * the underlying Transform, while modifications to the members of the array
- * will affect them.
- *
- * An array containing the transforms of the subtree.
- */
-o3d.Transform.prototype.getTransformsInTree =
- function() {
- var result = [];
- o3d.Transform.getTransformInTreeRecursive_(this, result);
- return result;
-};
-
-
-/**
- * Recursive helper function for getTransformInTree.
- * @private
- */
-o3d.Transform.getTransformInTreeRecursive_ =
- function(treeRoot, children) {
- children.push(treeRoot);
- var childrenArray = treeRoot.children;
- for (var ii = 0; ii < childrenArray.length; ++ii) {
- o3d.Transform.getTransformInTreeRecursive_(childrenArray[ii], children);
- }
-};
-
-
-/**
- * Searches for transforms that match the given name in the hierarchy under and
- * including this transform. Since there can be more than one transform with a
- * given name, results are returned in an array.
- *
- * Note that modifications to this array [e.g. additions to it] will not affect
- * the underlying Transform, while modifications to the members of the array
- * will affect them.
- *
- * @param {string} name Transform name to look for.
- * @return {Array.<o3d.Transform>} An array containing the transforms of the
- * under and including this transform matching the given name.
- */
-o3d.Transform.prototype.getTransformsByNameInTree =
- function(name) {
- o3d.notImplemented();
-};
-
-/**
- * Evaluates and returns the current world matrix.
- *
- * The updated world matrix.
- */
-o3d.Transform.prototype.getUpdatedWorldMatrix =
- function() {
- var parentWorldMatrix;
- if (!this.parent) {
- parentWorldMatrix =
- o3d.Transform.makeIdentityMatrix4_();
- } else {
- parentWorldMatrix = this.parent.getUpdatedWorldMatrix();
- }
- o3d.Transform.compose_(parentWorldMatrix, this.localMatrix, this.worldMatrix);
- return this.worldMatrix;
-};
-
-
-/**
- * Adds a shape do this transform.
- * @param {o3d.Shape} shape Shape to add.
- */
-o3d.Transform.prototype.addShape =
- function(shape) {
- this.shapes.push(shape);
-};
-
-
-/**
- * Removes a shape from this transform.
- * @param {o3d.Shape} shape Shape to remove.
- * @return {boolean} true if successful, false if shape was not in
- * this transform.
- */
-o3d.Transform.prototype.removeShape =
- function(shape) {
- o3d.removeFromArray(this.shapes, shape);
-};
-
-
-/**
- * Walks the tree of transforms starting with this transform and creates
- * draw elements. If an Element already has a DrawElement that uses material a
- * new DrawElement will not be created.
- * @param {o3d.Pack} pack Pack used to manage created elements.
- * @param {o3d.Material} material Material to use for each element. If you
- * pass null, it will use the material on the element to which a draw
- * element is being added. In other words, a DrawElement will use the
- * material of the corresponding Element if material is null. This allows
- * you to easily setup the default (just draw as is) by passing null or
- * setup a shadow pass by passing in a shadow material.
- */
-o3d.Transform.prototype.createDrawElements =
- function(pack, material) {
- var children = this.children;
- var shapes = this.shapes;
-
- for (var i = 0; i < shapes.length; ++i) {
- shapes[i].createDrawElements(pack, material);
- }
-
- for (var i = 0; i < children.length; ++i) {
- children[i].createDrawElements(pack, material);
- }
-};
-
-
-/**
- * Sets the local matrix of this transform to the identity matrix.
- */
-o3d.Transform.prototype.identity = function() {
- var m = this.localMatrix;
- for (var i = 0; i < 4; ++i) {
- for (var j = 0; j < 4; ++j) {
- m[i * 4 + j] = i == j ? 1 : 0;
- }
- }
-};
-
-
-/**
- * Pre-composes the local matrix of this Transform with a translation. For
- * example, if the local matrix is a rotation then new local matrix will
- * translate by the given vector and then rotated.
- */
-o3d.Transform.prototype.translate =
- function() {
- var v;
- if (arguments.length == 3) {
- v = arguments;
- } else {
- v = arguments[0];
- }
- var m = this.localMatrix;
-
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
-
- var m00 = m[0];
- var m01 = m[1];
- var m02 = m[2];
- var m03 = m[3];
- var m10 = m[4];
- var m11 = m[5];
- var m12 = m[6];
- var m13 = m[7];
- var m20 = m[8];
- var m21 = m[9];
- var m22 = m[10];
- var m23 = m[11];
- var m30 = m[12];
- var m31 = m[13];
- var m32 = m[14];
- var m33 = m[15];
-
- m[12] = m00 * v0 + m10 * v1 + m20 * v2 + m30,
- m[13] = m01 * v0 + m11 * v1 + m21 * v2 + m31,
- m[14] = m02 * v0 + m12 * v1 + m22 * v2 + m32,
- m[15] = m03 * v0 + m13 * v1 + m23 * v2 + m33;
-};
-
-
-/**
- * Pre-composes the local matrix of this Transform with a rotation about the
- * x-axis. For example, if the local matrix is a tranlsation, the new local
- * matrix will rotate around the x-axis and then translate.
- *
- * @param {number} radians The number of radians to rotate around x-axis.
- */
-o3d.Transform.prototype.rotateX =
- function(angle) {
- var m = this.localMatrix;
-
- var m10 = m[4];
- var m11 = m[5];
- var m12 = m[6];
- var m13 = m[7];
- var m20 = m[8];
- var m21 = m[9];
- var m22 = m[10];
- var m23 = m[11];
-
- var c = Math.cos(angle);
- var s = Math.sin(angle);
-
- m[4] = c * m10 + s * m20;
- m[5] = c * m11 + s * m21;
- m[6] = c * m12 + s * m22;
- m[7] = c * m13 + s * m23;
- m[8] = c * m20 - s * m10;
- m[9] = c * m21 - s * m11;
- m[10] = c * m22 - s * m12;
- m[11] = c * m23 - s * m13;
-};
-
-
-/**
- * Pre-composes the local matrix of this Transform with a rotation about the
- * y-axis. For example, if the local matrix is a translation, the new local
- * matrix will rotate around the y-axis and then translate.
- *
- * @param {number} radians The number of radians to rotate around y-axis.
- */
-o3d.Transform.prototype.rotateY =
- function(angle) {
- var m = this.localMatrix;
-
- var m00 = m[0];
- var m01 = m[1];
- var m02 = m[2];
- var m03 = m[3];
- var m20 = m[8];
- var m21 = m[9];
- var m22 = m[10];
- var m23 = m[11];
- var c = Math.cos(angle);
- var s = Math.sin(angle);
-
- m[0] = c * m00 - s * m20;
- m[1] = c * m01 - s * m21;
- m[2] = c * m02 - s * m22;
- m[3] = c * m03 - s * m23;
- m[8] = c * m20 + s * m00;
- m[9] = c * m21 + s * m01;
- m[10] = c * m22 + s * m02;
- m[11] = c * m23 + s * m03;
-};
-
-
-/**
- * Pre-composes the local matrix of this Transform with a rotation about the
- * z-axis. For example, if the local matrix is a translation, the new local
- * matrix will rotate around the z-axis and then translate.
- *
- * @param {number} radians The number of radians to rotate around z-axis.
- */
-o3d.Transform.prototype.rotateZ =
- function(angle) {
- var m = this.localMatrix;
-
- var m00 = m[0];
- var m01 = m[1];
- var m02 = m[2];
- var m03 = m[3];
- var m10 = m[4];
- var m11 = m[5];
- var m12 = m[6];
- var m13 = m[7];
- var c = Math.cos(angle);
- var s = Math.sin(angle);
-
- m[0] = c * m00 + s * m10;
- m[1] = c * m01 + s * m11;
- m[2] = c * m02 + s * m12;
- m[3] = c * m03 + s * m13;
- m[4] = c * m10 - s * m00;
- m[5] = c * m11 - s * m01;
- m[6] = c * m12 - s * m02;
- m[7] = c * m13 - s * m03;
-};
-
-
-/**
- * Pre-composes the local matrix of this Transform with a rotation.
- * Interprets the three entries of the given vector as angles by which to
- * rotate around the x, y and z axes. Rotates around the x-axis first,
- * then the y-axis, then the z-axis.
- *
- * @param {!o3d.math.Vector3} v A vector of angles (in radians) by which
- * to rotate around the x, y and z axes.
- */
-o3d.Transform.prototype.rotateZYX =
- function(v) {
- var m = this.localMatrix;
-
- var sinX = Math.sin(v[0]);
- var cosX = Math.cos(v[0]);
- var sinY = Math.sin(v[1]);
- var cosY = Math.cos(v[1]);
- var sinZ = Math.sin(v[2]);
- var cosZ = Math.cos(v[2]);
-
- var cosZSinY = cosZ * sinY;
- var sinZSinY = sinZ * sinY;
-
- var r00 = cosZ * cosY;
- var r01 = sinZ * cosY;
- var r02 = -sinY;
- var r10 = cosZSinY * sinX - sinZ * cosX;
- var r11 = sinZSinY * sinX + cosZ * cosX;
- var r12 = cosY * sinX;
- var r20 = cosZSinY * cosX + sinZ * sinX;
- var r21 = sinZSinY * cosX - cosZ * sinX;
- var r22 = cosY * cosX;
-
- var m00 = m[0];
- var m01 = m[1];
- var m02 = m[2];
- var m03 = m[3];
- var m10 = m[4];
- var m11 = m[5];
- var m12 = m[6];
- var m13 = m[7];
- var m20 = m[8];
- var m21 = m[9];
- var m22 = m[10];
- var m23 = m[11];
- var m30 = m[12];
- var m31 = m[13];
- var m32 = m[14];
- var m33 = m[15];
-
- m[0] = r00 * m00 + r01 * m10 + r02 * m20;
- m[1] = r00 * m01 + r01 * m11 + r02 * m21;
- m[2] = r00 * m02 + r01 * m12 + r02 * m22;
- m[3] = r00 * m03 + r01 * m13 + r02 * m23;
-
- m[4] = r10 * m00 + r11 * m10 + r12 * m20;
- m[5] = r10 * m01 + r11 * m11 + r12 * m21;
- m[6] = r10 * m02 + r11 * m12 + r12 * m22;
- m[7] = r10 * m03 + r11 * m13 + r12 * m23;
-
- m[8] = r20 * m00 + r21 * m10 + r22 * m20;
- m[9] = r20 * m01 + r21 * m11 + r22 * m21;
- m[10] = r20 * m02 + r21 * m12 + r22 * m22;
- m[11] = r20 * m03 + r21 * m13 + r22 * m23;
-};
-
-
-/**
- * Pre-composes the local matrix of this Transform with a rotation around the
- * given axis. For example, if the local matrix is a translation, the new
- * local matrix will rotate around the given axis and then translate.
- *
- * @param {number} angle The number of radians to rotate.
- * @param {!o3d.math.Vector3} axis a non-zero vector representing the axis
- * around which to rotate.
- */
-o3d.Transform.prototype.axisRotate =
- function(axis, angle) {
- o3d.Transform.axisRotateMatrix(this.localMatrix, axis, angle);
-};
-
-o3d.Transform.axisRotateMatrix =
- function(m, axis, angle, opt_target) {
- opt_target = opt_target || m;
- var x = axis[0];
- var y = axis[1];
- var z = axis[2];
- var n = Math.sqrt(x * x + y * y + z * z);
- x /= n;
- y /= n;
- z /= n;
- var xx = x * x;
- var yy = y * y;
- var zz = z * z;
- var c = Math.cos(angle);
- var s = Math.sin(angle);
- var oneMinusCosine = 1 - c;
-
- var r00 = xx + (1 - xx) * c;
- var r01 = x * y * oneMinusCosine + z * s;
- var r02 = x * z * oneMinusCosine - y * s;
- var r10 = x * y * oneMinusCosine - z * s;
- var r11 = yy + (1 - yy) * c;
- var r12 = y * z * oneMinusCosine + x * s;
- var r20 = x * z * oneMinusCosine + y * s;
- var r21 = y * z * oneMinusCosine - x * s;
- var r22 = zz + (1 - zz) * c;
-
- var m00 = m[0];
- var m01 = m[1];
- var m02 = m[2];
- var m03 = m[3];
- var m10 = m[4];
- var m11 = m[5];
- var m12 = m[6];
- var m13 = m[7];
- var m20 = m[8];
- var m21 = m[9];
- var m22 = m[10];
- var m23 = m[11];
- var m30 = m[12];
- var m31 = m[13];
- var m32 = m[14];
- var m33 = m[15];
-
- m[0] = r00 * m00 + r01 * m10 + r02 * m20;
- m[1] = r00 * m01 + r01 * m11 + r02 * m21;
- m[2] = r00 * m02 + r01 * m12 + r02 * m22;
- m[3] = r00 * m03 + r01 * m13 + r02 * m23;
- m[4] = r10 * m00 + r11 * m10 + r12 * m20;
- m[5] = r10 * m01 + r11 * m11 + r12 * m21;
- m[6] = r10 * m02 + r11 * m12 + r12 * m22;
- m[7] = r10 * m03 + r11 * m13 + r12 * m23;
-
- m[8] = r20 * m00 + r21 * m10 + r22 * m20;
- m[9] = r20 * m01 + r21 * m11 + r22 * m21;
- m[10] = r20 * m02 + r21 * m12 + r22 * m22;
- m[11] = r20 * m03 + r21 * m13 + r22 * m23;
-};
-
-
-/**
- * Pre-composes the local matrix of this Transform with a rotation defined by
- * the given quaternion.
- *
- * @param {o3d.math.Quat} q A non-zero quaternion to be interpreted as a
- * rotation.
- */
-o3d.Transform.prototype.quaternionRotate =
- function(q) {
- var m = this.localMatrix;
-
- var qX = q[0];
- var qY = q[1];
- var qZ = q[2];
- var qW = q[3];
-
- var qWqW = qW * qW;
- var qWqX = qW * qX;
- var qWqY = qW * qY;
- var qWqZ = qW * qZ;
- var qXqW = qX * qW;
- var qXqX = qX * qX;
- var qXqY = qX * qY;
- var qXqZ = qX * qZ;
- var qYqW = qY * qW;
- var qYqX = qY * qX;
- var qYqY = qY * qY;
- var qYqZ = qY * qZ;
- var qZqW = qZ * qW;
- var qZqX = qZ * qX;
- var qZqY = qZ * qY;
- var qZqZ = qZ * qZ;
-
- var d = qWqW + qXqX + qYqY + qZqZ;
-
- o3d.Transform.compose_(this.localMatrix, o3d.Transform.makeMatrix4_(
- (qWqW + qXqX - qYqY - qZqZ) / d,
- 2 * (qWqZ + qXqY) / d,
- 2 * (qXqZ - qWqY) / d, 0,
- 2 * (qXqY - qWqZ) / d,
- (qWqW - qXqX + qYqY - qZqZ) / d,
- 2 * (qWqX + qYqZ) / d, 0,
- 2 * (qWqY + qXqZ) / d,
- 2 * (qYqZ - qWqX) / d,
- (qWqW - qXqX - qYqY + qZqZ) / d, 0,
- 0, 0, 0, 1));
-};
-
-
-/**
- * Pre-composes the local matrix of this transform by a scaling transformation.
- * For example, if the local matrix is a rotation, the new local matrix will
- * scale and then rotate.
- */
-o3d.Transform.prototype.scale =
- function() {
- var v;
- if (arguments.length == 3) {
- v = arguments;
- } else {
- v = arguments[0];
- }
-
- var m = this.localMatrix;
-
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
-
- m[0] = v0 * m[0];
- m[1] = v0 * m[1];
- m[2] = v0 * m[2];
- m[3] = v0 * m[3];
- m[4] = v1 * m[4];
- m[5] = v1 * m[5];
- m[6] = v1 * m[6];
- m[7] = v1 * m[7];
- m[8] = v2 * m[8];
- m[9] = v2 * m[9];
- m[10] = v2 * m[10];
- m[11] = v2 * m[11];
-};
-
-
-/**
- * Traverses the transform tree starting at this node and adds DrawElements
- * for each shape to DrawList.
- * @param {Array.<Object>} drawListInfos A list of objects containing a draw
- * list and matrix information.
- * @param {o3d.math.Matrix4} opt_parentWorldMatrix
- */
-o3d.Transform.prototype.traverse =
- function(drawListInfos, opt_parentWorldMatrix) {
- this.gl.client.render_stats_['transformsProcessed']++;
- if (drawListInfos.length == 0 || !this.visible) {
- return;
- }
- opt_parentWorldMatrix =
- opt_parentWorldMatrix || o3d.Transform.makeIdentityMatrix4_();
-
- o3d.Transform.compose_(
- opt_parentWorldMatrix, this.localMatrix, this.worldMatrix);
-
- var remainingDrawListInfos = [];
-
- if (this.cull) {
- if (this.boundingBox) {
- for (var i = 0; i < drawListInfos.length; ++i) {
- var drawListInfo = drawListInfos[i];
-
- var worldViewProjection = o3d.Transform.makeNullMatrix4_();
- o3d.Transform.compose_(drawListInfo.context.view,
- this.worldMatrix, worldViewProjection);
- o3d.Transform.compose_(drawListInfo.context.projection,
- worldViewProjection, worldViewProjection);
-
- if (this.boundingBox.inFrustum(worldViewProjection)) {
- remainingDrawListInfos.push(drawListInfo);
- }
- }
- }
- } else {
- remainingDrawListInfos = drawListInfos;
- }
-
- if (remainingDrawListInfos.length == 0) {
- this.gl.client.render_stats_['transformsCulled']++;
- return;
- }
-
- var children = this.children;
- var shapes = this.shapes;
-
- for (var i = 0; i < shapes.length; ++i) {
- shapes[i].writeToDrawLists(remainingDrawListInfos, this.worldMatrix, this);
- }
-
- for (var i = 0; i < children.length; ++i) {
- children[i].traverse(remainingDrawListInfos, this.worldMatrix);
- }
-};
-
-
-/**
- * Tells the o3d-webgl subsection if it should use native javascript
- * arrays or if it should switch to the newer Float32Array, which help the
- * interpreter, once created, but can require a lot of gc work to allocate
- * and deallocate.
- * @type {boolean}
- */
-o3d.Transform.useFloat32Array_ = false;
-
-
-/**
- * This defines the type of any given Matrix4
- * @type {!Array.<number>|!Float32Array}
- */
-o3d.Transform.Matrix4 = goog.typedef;
-
-
-/**
- * This returns an identity 4x4 matrix with
- * the diagonal as 1's and everything else 0
- * @return {!o3d.Transform.Matrix4}
- * @private
- */
-o3d.Transform.makeIdentityMatrix4_ = null;
-
-
-/**
- * This returns a 4x4 matrix with all values set to zero
- * @return {!o3d.Transform.Matrix4} the vector made up of the elements
- * @private
- */
-o3d.Transform.makeNullMatrix4_ = null;
-
-
-/**
- * This returns a length 2 vector with values set to the passed in arguments
- * @param {number} a the x element in the vector
- * @param {number} b the y element in the vector
- * @return {!Float32Array} the vector made up of the elements
- * @private
- */
-o3d.Transform.makeVector2_ = null;
-
-
-/**
- * This returns a length 3 vector with values set to the passed in arguments
- * @param {number} a the x element in the vector
- * @param {number} b the y element in the vector
- * @param {number} c the z element in the vector
- * @return {!Float32Array} the vector made up of the elements
- * @private
- */
-o3d.Transform.makeVector3_ = null;
-
-
-/**
- * This returns a length 4 vector with values set to the passed in arguments
- * @param {number} a the x element in the vector
- * @param {number} b the y element in the vector
- * @param {number} c the z element in the vector
- * @param {number} d the w element in the vector
- * @return {!Float32Array} the vector made up of the elements
- * @private
- */
-o3d.Transform.makeVector4_ = null;
-
-
-/**
- * This returns a 4x4 matrix in row major order
- * with values set to the passed in arguments
- * @param {number} a [0][0] element
- * @param {number} b [0][1] element
- * @param {number} c [0][2] element
- * @param {number} d [0][3] element
- * @param {number} e [1][0] element
- * @param {number} f [1][1] element
- * @param {number} g [1][2] element
- * @param {number} h [1][3] element
- * @param {number} i [2][0] element
- * @param {number} j [2][1] element
- * @param {number} k [2][2] element
- * @param {number} l [2][3] element
- * @param {number} m [3][0] element
- * @param {number} n [3][1] element
- * @param {number} o [3][2] element
- * @param {number} p [3][3] element
- * @return {!o3d.Transform.Matrix4}
- */
-o3d.Transform.makeMatrix4_ = null;
-
-
-// If Float32Array isn't defined we might as well not bother including the
-// Float32Array functions.
-if (window.Float32Array != undefined) {
- /**
- * A namespace to hold Float32Array-specialized functions.
- * @namespace
- * @private
- */
- o3d.Transform.Float32Array_ = {};
-
-
- /**
- * This defines the type of any given Matrix4 in the Float32Array namespace
- * @type {function}
- * @private
- */
- o3d.Transform.Float32Array_.Matrix4 = Float32Array;
-
-
- /**
- * This returns an identity 4x4 matrix with
- * the diagonal as 1's and everything else 0
- * @return {!o3d.Transform.Matrix4}
- * @private
- */
- o3d.Transform.Float32Array_.makeIdentityMatrix4_ = function() {
- var r = new Float32Array(16);
- r[0] = 1;
- r[5] = 1;
- r[10] = 1;
- r[15] = 1;
- return r;
- };
-
-
- /**
- * This returns a 4x4 matrix with all values set to zero
- * @return {!o3d.Transform.Matrix4} the vector made up of the elements
- * @private
- */
- o3d.Transform.Float32Array_.makeNullMatrix4_ = function() {
- return new Float32Array(16);
- };
-
-
- /**
- * This returns a length 2 vector with values set to the passed in arguments
- * @param {number} a the x element in the vector
- * @param {number} b the y element in the vector
- * @return {!Float32Array} the vector made up of the elements
- * @private
- */
- o3d.Transform.Float32Array_.makeVector2_ = function(a, b) {
- var f=new Float32Array(2);
- f[0] = a;
- f[1] = b;
- return f;
- };
-
-
- /**
- * This returns a length 3 vector with values set to the passed in arguments
- * @param {number} a the x element in the vector
- * @param {number} b the y element in the vector
- * @param {number} c the z element in the vector
- * @return {!Float32Array} the vector made up of the elements
- * @private
- */
- o3d.Transform.Float32Array_.makeVector3_ = function(a, b, c) {
- var f=new Float32Array(3);
- f[0] = a;
- f[1] = b;
- f[2] = c;
- return f;
- };
-
-
- /**
- * This returns a length 4 vector with values set to the passed in arguments
- * @param {number} a the x element in the vector
- * @param {number} b the y element in the vector
- * @param {number} c the z element in the vector
- * @param {number} d the w element in the vector
- * @return {!Float32Array} the vector made up of the elements
- * @private
- */
- o3d.Transform.Float32Array_.makeVector4_ = function(a, b, c, d) {
- var f = new Float32Array(4);
- f[0] = a;
- f[1] = b;
- f[2] = c;
- f[3] = d;
- return f;
- };
-
-
- /**
- * This returns a 4x4 matrix in row major order
- * with values set to the passed in arguments
- * @param {number} a [0][0] element
- * @param {number} a [0][0] element
- * @param {number} b [0][1] element
- * @param {number} c [0][2] element
- * @param {number} d [0][3] element
- * @param {number} e [1][0] element
- * @param {number} f [1][1] element
- * @param {number} g [1][2] element
- * @param {number} h [1][3] element
- * @param {number} i [2][0] element
- * @param {number} j [2][1] element
- * @param {number} k [2][2] element
- * @param {number} l [2][3] element
- * @param {number} m [3][0] element
- * @param {number} n [3][1] element
- * @param {number} o [3][2] element
- * @param {number} p [3][3] element
- * @return {!o3d.Transform.Matrix4}
- */
- o3d.Transform.Float32Array_.makeMatrix4_ =
- function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {
- var m = new Float32Array(16);
- m[0] = a;
- m[1] = b;
- m[2] = c;
- m[3] = d;
- m[4] = e;
- m[5] = f;
- m[6] = g;
- m[7] = h;
- m[8] = i;
- m[9] = j;
- m[10] = k;
- m[11] = l;
- m[12] = m;
- m[13] = n;
- m[14] = o;
- m[15] = p;
- return m;
- };
-} else {
- // If Float32Array doesn't exist, we cannot use that library.
- o3d.Transform.useFloat32Array_ = false;
-}
-
-
-/**
- * A namespace for Array specialized Transform functions that depend
- * on what the matrix type of choice is
- * @namespace
- * @private
- */
-o3d.Transform.Array_ = {};
-
-/**
- * This returns a length 3 vector with values set to the passed in arguments
- * @param {number} a the x element in the vector
- * @param {number} b the y element in the vector
- * @return {!Array} the vector made up of the elements
- * @private
- */
-o3d.Transform.Array_.makeVector2_ = function(a, b) {
- return [a,b];
-};
-
-/**
- * This returns a length 3 vector with values set to the passed in arguments
- * @param {number} a the x element in the vector
- * @param {number} b the y element in the vector
- * @param {number} c the z element in the vector
- * @return {!Array} the vector made up of the elements
- * @private
- */
-o3d.Transform.Array_.makeVector3_ = function(a, b, c) {
- return [a, b, c];
-};
-
-/**
- * This returns a length 4 vector with values set to the passed in arguments
- * @param {number} a the x element in the vector
- * @param {number} b the y element in the vector
- * @param {number} c the z element in the vector
- * @param {number} d the w element in the vector
- * @return {!Array} the vector made up of the elements
- * @private
- */
-o3d.Transform.Array_.makeVector4_ = function(a, b, c, d) {
- return [a, b, c, d];
-};
-
-/**
- * This returns a 4x4 matrix in row major order
- * with values set to the passed in arguments
- * @param {number} a [0][0] element
- * @param {number} b [0][1] element
- * @param {number} c [0][2] element
- * @param {number} d [0][3] element
- * @param {number} e [1][0] element
- * @param {number} f [1][1] element
- * @param {number} g [1][2] element
- * @param {number} h [1][3] element
- * @param {number} i [2][0] element
- * @param {number} j [2][1] element
- * @param {number} k [2][2] element
- * @param {number} l [2][3] element
- * @param {number} m [3][0] element
- * @param {number} n [3][1] element
- * @param {number} o [3][2] element
- * @param {number} p [3][3] element
- * @return {!o3d.Transform.Matrix4}
- * @private
- */
-o3d.Transform.Array_.makeMatrix4_ =
- function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {
- return [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p];
-};
-
-o3d.Transform.Array_.Matrix4_ = Array;
-
-/**
- * This returns an identity 4x4 matrix with
- * the diagonal as 1's and everything else 0
- * @return {!o3d.Transform.Matrix4}
- */
-o3d.Transform.Array_.makeIdentityMatrix4_ = function() {
- return [1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1];
-};
-
-
-/**
- * This returns an identity 4x4 matrix with all values as 0
- * @return {!o3d.Transform.Matrix4}
- */
-o3d.Transform.Array_.makeNullMatrix4_ = function() {
- return [0, 0, 0, 0,
- 0, 0, 0, 0,
- 0, 0, 0, 0,
- 0, 0, 0, 0];
-};
-
-
-if (o3d.Transform.useFloat32Array_) {
- for (var i in o3d.Transform.Float32Array_) {
- o3d.Transform[i] = o3d.Transform.Float32Array_[i];
- }
-} else {
- for (var i in o3d.Transform.Array_) {
- o3d.Transform[i] = o3d.Transform.Array_[i];
- }
-}
-
-
-/*
- * Utility function to copose a matrix with another matrix.
- * Precomposes b with a, changing a, or if the target matrix if
- * one is provided.
- *
- * @param {!Array.<!Array.<number>>} a
- * @param {!Array.<!Array.<number>>} b
- * @param {!Array.<!Array.<number>>} opt_target
- * @private
- */
-o3d.Transform.compose_ = function(a, b, opt_target) {
- var t = opt_target || a;
-
- var a00 = a[0];
- var a01 = a[1];
- var a02 = a[2];
- var a03 = a[3];
- var a10 = a[4];
- var a11 = a[5];
- var a12 = a[6];
- var a13 = a[7];
- var a20 = a[8];
- var a21 = a[9];
- var a22 = a[10];
- var a23 = a[11];
- var a30 = a[12];
- var a31 = a[13];
- var a32 = a[14];
- var a33 = a[15];
- var b00 = b[0];
- var b01 = b[1];
- var b02 = b[2];
- var b03 = b[3];
- var b10 = b[4];
- var b11 = b[5];
- var b12 = b[6];
- var b13 = b[7];
- var b20 = b[8];
- var b21 = b[9];
- var b22 = b[10];
- var b23 = b[11];
- var b30 = b[12];
- var b31 = b[13];
- var b32 = b[14];
- var b33 = b[15];
- t[0] = a00 * b00 + a10 * b01 + a20 * b02 + a30 * b03;
- t[1] = a01 * b00 + a11 * b01 + a21 * b02 + a31 * b03;
- t[2] = a02 * b00 + a12 * b01 + a22 * b02 + a32 * b03;
- t[3] = a03 * b00 + a13 * b01 + a23 * b02 + a33 * b03;
- t[4] = a00 * b10 + a10 * b11 + a20 * b12 + a30 * b13;
- t[5] = a01 * b10 + a11 * b11 + a21 * b12 + a31 * b13;
- t[6] = a02 * b10 + a12 * b11 + a22 * b12 + a32 * b13;
- t[7] = a03 * b10 + a13 * b11 + a23 * b12 + a33 * b13;
- t[8] = a00 * b20 + a10 * b21 + a20 * b22 + a30 * b23;
- t[9] = a01 * b20 + a11 * b21 + a21 * b22 + a31 * b23;
- t[10] = a02 * b20 + a12 * b21 + a22 * b22 + a32 * b23;
- t[11] = a03 * b20 + a13 * b21 + a23 * b22 + a33 * b23;
- t[12] = a00 * b30 + a10 * b31 + a20 * b32 + a30 * b33;
- t[13] = a01 * b30 + a11 * b31 + a21 * b32 + a31 * b33;
- t[14] = a02 * b30 + a12 * b31 + a22 * b32 + a32 * b33;
- t[15] = a03 * b30 + a13 * b31 + a23 * b32 + a33 * b33;
-};
-
-
-/**
- * Tests whether two matrices are either equal in the sense that they
- * refer to the same memory, or equal in the sense that they have equal
- * entries.
- *
- * @param {!Array.<!Array.<number>>} a A matrix.
- * @param {!Array.<!Array.<number>>} b Another matrix.
- * @return {boolean} Whether they are equal.
- * @private
- */
-o3d.Transform.matricesEqual_ = function(a, b) {
- if (a==b) {
- return true;
- }
- for (var i = 0; i < 16; ++i) {
- if (a[i] != b[i]) {
- return false;
- }
- }
-
- return true;
-};
-
-
-/**
- * Computes the transpose of the matrix a in place if no target is provided.
- * Or if a target is provided, turns the target into the transpose of a.
- *
- * @param {!Array.<!Array.<number>>} m A matrix.
- * @param {Array.<!Array.<number>>} opt_target
- * The matrix to become the transpose of m.
- * @private
- */
-o3d.Transform.transpose_ = function(m, opt_target) {
- var t = opt_target || m;
-
- var m00 = m[0];
- var m01 = m[1];
- var m02 = m[2];
- var m03 = m[3];
- var m10 = m[4];
- var m11 = m[5];
- var m12 = m[6];
- var m13 = m[7];
- var m20 = m[8];
- var m21 = m[9];
- var m22 = m[10];
- var m23 = m[11];
- var m30 = m[12];
- var m31 = m[13];
- var m32 = m[14];
- var m33 = m[15];
- t[0] = m00;
- t[1] = m10;
- t[2] = m20;
- t[3] = m30;
-
- t[4] = m01;
- t[5] = m11;
- t[6] = m21;
- t[7] = m31;
-
- t[8] = m02;
- t[9] = m12;
- t[10] = m22;
- t[11] = m32;
-
- t[12] = m03;
- t[13] = m13;
- t[14] = m23;
- t[15] = m33;
-};
-
-
-/**
- * Computes the inverse of the matrix a in place if no target is provided.
- * Or if a target is provided, turns the target into the transpose of a.
- *
- * @param {!Array.<!Array.<number>>} m A matrix.
- * @param {Array.<!Array.<number>>} opt_target The matrix to become the
- * inverse of a.
- */
-o3d.Transform.inverse_ = function(m, opt_target) {
- var t = opt_target || m;
-
- var m00 = m[0];
- var m01 = m[1];
- var m02 = m[2];
- var m03 = m[3];
- var m10 = m[4];
- var m11 = m[5];
- var m12 = m[6];
- var m13 = m[7];
- var m20 = m[8];
- var m21 = m[9];
- var m22 = m[10];
- var m23 = m[11];
- var m30 = m[12];
- var m31 = m[13];
- var m32 = m[14];
- var m33 = m[15];
-
- var tmp_0 = m22 * m33;
- var tmp_1 = m32 * m23;
- var tmp_2 = m12 * m33;
- var tmp_3 = m32 * m13;
- var tmp_4 = m12 * m23;
- var tmp_5 = m22 * m13;
- var tmp_6 = m02 * m33;
- var tmp_7 = m32 * m03;
- var tmp_8 = m02 * m23;
- var tmp_9 = m22 * m03;
- var tmp_10 = m02 * m13;
- var tmp_11 = m12 * m03;
- var tmp_12 = m20 * m31;
- var tmp_13 = m30 * m21;
- var tmp_14 = m10 * m31;
- var tmp_15 = m30 * m11;
- var tmp_16 = m10 * m21;
- var tmp_17 = m20 * m11;
- var tmp_18 = m00 * m31;
- var tmp_19 = m30 * m01;
- var tmp_20 = m00 * m21;
- var tmp_21 = m20 * m01;
- var tmp_22 = m00 * m11;
- var tmp_23 = m10 * m01;
-
- var t0 = (tmp_0 * m11 + tmp_3 * m21 + tmp_4 * m31) -
- (tmp_1 * m11 + tmp_2 * m21 + tmp_5 * m31);
- var t1 = (tmp_1 * m01 + tmp_6 * m21 + tmp_9 * m31) -
- (tmp_0 * m01 + tmp_7 * m21 + tmp_8 * m31);
- var t2 = (tmp_2 * m01 + tmp_7 * m11 + tmp_10 * m31) -
- (tmp_3 * m01 + tmp_6 * m11 + tmp_11 * m31);
- var t3 = (tmp_5 * m01 + tmp_8 * m11 + tmp_11 * m21) -
- (tmp_4 * m01 + tmp_9 * m11 + tmp_10 * m21);
-
- var d = 1.0 / (m00 * t0 + m10 * t1 + m20 * t2 + m30 * t3);
-
- t[0] = d * t0;
- t[1] = d * t1;
- t[2] = d * t2;
- t[3] = d * t3;
- t[4] = d * ((tmp_1 * m10 + tmp_2 * m20 + tmp_5 * m30) -
- (tmp_0 * m10 + tmp_3 * m20 + tmp_4 * m30));
- t[5] = d * ((tmp_0 * m00 + tmp_7 * m20 + tmp_8 * m30) -
- (tmp_1 * m00 + tmp_6 * m20 + tmp_9 * m30));
- t[6] = d * ((tmp_3 * m00 + tmp_6 * m10 + tmp_11 * m30) -
- (tmp_2 * m00 + tmp_7 * m10 + tmp_10 * m30));
- t[7] = d * ((tmp_4 * m00 + tmp_9 * m10 + tmp_10 * m20) -
- (tmp_5 * m00 + tmp_8 * m10 + tmp_11 * m20));
- t[8] = d * ((tmp_12 * m13 + tmp_15 * m23 + tmp_16 * m33) -
- (tmp_13 * m13 + tmp_14 * m23 + tmp_17 * m33));
- t[9] = d * ((tmp_13 * m03 + tmp_18 * m23 + tmp_21 * m33) -
- (tmp_12 * m03 + tmp_19 * m23 + tmp_20 * m33));
- t[10] = d * ((tmp_14 * m03 + tmp_19 * m13 + tmp_22 * m33) -
- (tmp_15 * m03 + tmp_18 * m13 + tmp_23 * m33));
- t[11] = d * ((tmp_17 * m03 + tmp_20 * m13 + tmp_23 * m23) -
- (tmp_16 * m03 + tmp_21 * m13 + tmp_22 * m23));
- t[12] = d * ((tmp_14 * m22 + tmp_17 * m32 + tmp_13 * m12) -
- (tmp_16 * m32 + tmp_12 * m12 + tmp_15 * m22));
- t[13] = d * ((tmp_20 * m32 + tmp_12 * m02 + tmp_19 * m22) -
- (tmp_18 * m22 + tmp_21 * m32 + tmp_13 * m02));
- t[14] = d * ((tmp_18 * m12 + tmp_23 * m32 + tmp_15 * m02) -
- (tmp_22 * m32 + tmp_14 * m02 + tmp_19 * m12));
- t[15] = d * ((tmp_22 * m22 + tmp_16 * m02 + tmp_21 * m12) -
- (tmp_20 * m12 + tmp_23 * m22 + tmp_17 * m02));
-};
-
-
-/**
- * Takes a 4-by-4 matrix and a vector with 3 entries,
- * interprets the vector as a point, transforms that point by the matrix, and
- * returns the result as a vector with 3 entries.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @param {!o3djs.math.Vector3} v The point.
- * @return {!o3djs.math.Vector3} The transformed point.
- * @private
- */
-o3d.Transform.transformPoint_ = function(m, v) {
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
-
- var d = v0 * m[3] + v1 * m[7] + v2 * m[11] + m[15];
- return o3d.Transform.makeVector3_(
- (v0 * m[0] + v1 * m[4] + v2 * m[8] + m[12]) / d,
- (v0 * m[1] + v1 * m[5] + v2 * m[9] + m[13]) / d,
- (v0 * m[2] + v1 * m[6] + v2 * m[10] + m[14]) / d);
-};
-
-
-/**
- * Takes a 4-by-4 matrix and a vector with 4 entries,
- * interprets the vector as a point, transforms that point by the matrix, and
- * returns the result as a vector with 4 entries.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @param {!o3djs.math.Vector4} v The vector.
- * @return {!o3djs.math.Vector4} The transformed vector.
- * @private
- */
-o3d.Transform.multiplyVector_ = function(m, v) {
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
- var v3 = v[3];
-
- return o3d.Transform.makeVector4_(
- (v0 * m[0] + v1 * m[4] + v2 * m[8] + v3 * m[12]),
- (v0 * m[1] + v1 * m[5] + v2 * m[9] + v3 * m[13]),
- (v0 * m[2] + v1 * m[6] + v2 * m[10] + v3 * m[14]),
- (v0 * m[3] + v1 * m[7] + v2 * m[11] + v3 * m[15]));
-};
-
-
-/**
- * Takes a 4-by-4 matrix and a vector with 3 entries,
- * interprets the vector as a point, transforms that point by the matrix,
- * returning the z-component of the result only.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @param {!o3djs.math.Vector3} v The point.
- * @return {number} The z coordinate of the transformed point.
- * @private
- */
-o3d.Transform.transformPointZOnly_ = function(m, v) {
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
-
- return (v0 * m[2] + v1 * m[6] + v2 * m[10] + m[14]) /
- (v0 * m[3] + v1 * m[7] + v2 * m[11] + m[15]);
-};
diff --git a/o3d/samples/o3d-webgl/tree_traversal.js b/o3d/samples/o3d-webgl/tree_traversal.js
deleted file mode 100644
index 149b25b..0000000
--- a/o3d/samples/o3d-webgl/tree_traversal.js
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A TreeTraversal has multiple DrawLists registered with it. Each DrawList has
- * a DrawContext registered with it. At render time the TreeTraversal walks the
- * transform graph from the transform it's pointing at and for each DrawElement
- * it finds who's matertial matches one of its registered DrawLists it adds that
- * DrawElement to that DrawList.
- *
- * @param {o3d.Transform} opt_transform The root transform to start traversing
- * by this TreeTraveral.
- * @constructor
- */
-o3d.TreeTraversal = function(opt_transform) {
- o3d.RenderNode.call(this);
-
- /**
- * The root Transform this TreeTraversal will start traversing from.
- */
- this.transform = opt_transform || null;
-
- /**
- * Private list of registered drawlists.
- * @private
- */
- this.drawLists_ = [];
-
- /**
- * Private list of drawlists to reset at render-time before traversal.
- * @private
- */
- this.drawListsToReset_ = [];
-};
-o3d.inherit('TreeTraversal', 'RenderNode');
-
-o3d.ParamObject.setUpO3DParam_(o3d.TreeTraversal,
- 'transform', 'ParamTransform');
-
-/**
- * Registers a DrawList with this TreeTraversal so that when this
- * TreeTraversal traverses its tree, DrawElements using materials that use
- * this DrawList will be added though possibly culled by the view frustum of
- * the DrawContext. Note: passing in the same DrawList more than once will
- * override the previous settings for that DrawList.
- * @param {o3d.DrawList} draw_list DrawList to register.
- * @param {o3d.DrawContext} draw_context DrawContext to use with the DrawList.
- * @param {boolean} reset true if you want the DrawList reset before
- * traversing.
- */
-o3d.TreeTraversal.prototype.registerDrawList =
- function(draw_list, draw_context, reset) {
- if (reset == undefined || reset) {
- this.drawListsToReset_.push(draw_list);
- }
- this.drawLists_.push({
- list:draw_list,
- context:draw_context});
-};
-
-
-/**
- * Unregisters a DrawList with this TreeTraversal.
- * @param {o3d.DrawList} draw_list DrawList to unregister.
- * @return {boolean} true if unregistered. false if this draw_list was
- * not registered.
- */
-o3d.TreeTraversal.prototype.unregisterDrawList =
- function(draw_list) {
- o3d.notImplemented();
-};
-
-
-/**
- * Called in the render graph traversal before the children are rendered.
- */
-o3d.TreeTraversal.prototype.before =
- function() {
- for(var i = 0; i < this.drawListsToReset_.length; ++i) {
- this.drawListsToReset_[i].list_ = [];
- }
- this.transform.traverse(this.drawLists_);
-};
diff --git a/o3d/samples/o3d-webgl/types.js b/o3d/samples/o3d-webgl/types.js
deleted file mode 100644
index 1207059..0000000
--- a/o3d/samples/o3d-webgl/types.js
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * Namespace for math types.
- */
-o3d.math = {}
-
-
-/**
- * An Array of 3 numbers.
- * @type {!Array.<number>}
- */
-o3d.math.Point3 = goog.typedef;
-
-
-/**
- * An Array of 3 numbers.
- * @type {!Array.<number>}
- */
-o3d.math.Vector3 = goog.typedef;
-
-
-/**
- * An Array of 2 numbers.
- * @type {!Array.<number>}
- */
-o3d.Float2 = goog.typedef;
-
-
-/**
- * An Array of 3 numbers.
- * @type {!Array.<number>}
- */
-o3d.Float3 = goog.typedef;
-
-
-/**
- * An Array of 4 numbers.
- * @type {!Array.<number>}
- */
-o3d.Float4 = goog.typedef;
-
-
-/**
- * A 4x4 Matrix of numbers.
- * @type {!Array.<!Array.<number>>}
- */
-o3d.math.Matrix4 = goog.typedef;
-
-/**
- * An array of 4 numbers.
- * @type {!Array.<number>}
- */
-o3d.math.Quat = goog.typedef;
-
-
-/**
- * A function.
- * @type {Object}
- */
-o3d.ErrorCallback = goog.typedef;
-
-
-/**
- * A function.
- * @type {Object}
- */
-o3d.TickCallback = goog.typedef;
-
-
-/**
- * A function.
- * @type {Object}
- */
-o3d.RenderCallback = goog.typedef;
-
-
-/**
- * A function.
- * @type {Object}
- */
-o3d.LostResourcesCallback = goog.typedef;
-
-
-/**
- * A function.
- * @type {Object}
- */
-o3d.EventCallback = goog.typedef;
diff --git a/o3d/samples/o3d-webgl/vertex_source.js b/o3d/samples/o3d-webgl/vertex_source.js
deleted file mode 100644
index 18cccd3..0000000
--- a/o3d/samples/o3d-webgl/vertex_source.js
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-/**
- * A VertexSource is an object that allows binding Streams such that the
- * VertexSource updates the Buffers of the Streams that have been bound to it.
- * An example of a VertexSource object is a SkinEval
- *
- * @constructor
- * @extends ParamObject
- */
-o3d.VertexSource = function() {
- o3d.ParamObject.call(this);
-};
-o3d.inherit('VertexSource', 'ParamObject');
-
-/**
- * Bind the source stream to the corresponding stream in this VertexSource.
- *
- * @param {o3d.VertexSource} source Source to get vertices from.
- * @param {o3d.Stream.Semantic} semantic The semantic of the vertices to get.
- * @param {number} semantic_index The semantic index of the vertices to get.
- * @return {boolean} True if success. False if failure. If the requested
- * semantic or semantic index do not exist on the source or this source
- * the bind will fail.
- */
-o3d.VertexSource.prototype.bindStream = function(
- source, semantic, semantic_index) {
- if (source) {
- var source_param = source.getVertexStreamParam(semantic, semantic_index);
- var dest_param = this.getVertexStreamParam(semantic, semantic_index);
- if (source_param && dest_param &&
- source_param.stream.field.className ==
- dest_param.stream.field.className &&
- source_param.stream.field.numComponents ==
- dest_param.stream.field.numComponents) {
- dest_param.bind(source_param);
- source.streamWasBound_(this, semantic, semantic_index);
- return true;
- }
- }
-
- return false;
-};
-
-/**
- * Unbinds the requested stream.
- *
- * @param {o3d.Stream.Semantic} semantic The semantic of the vertices to unbind.
- * @param {number} semantic_index The semantic index of the vertices to unbind.
- * @return {boolean} True if unbound. False those vertices do not exist or were
- * not bound.
- */
-o3d.VertexSource.prototype.unbindStream = function(semantic, semantic_index) {
- var dest_param = this.getVertexStreamParam(semantic, semantic_index);
- if (dest_param && dest_param.inputConnection != null) {
- dest_param.unbindInput();
- return true;
- }
- return false;
-};
-
-/**
- * Used by bindStream. Each derived class must provide this function.
- *
- * @param {o3d.Stream.Semantic} semantic The semantic of the vertices to get.
- * @param {number} semantic_index The semantic index of the vertices to get.
- * @return {ParamVertexBufferStream} Returns the ParamVertexBufferStream that
- * manages the given stream as an output param for this VertexSource.
- * @protected
- */
-o3d.VertexSource.prototype.getVertexStreamParam = function(
- semantic, semantic_index) {
- o3d.notImplemented();
-};
-
-/**
- * Used by bindStream. Derived classes may override if needed.
- *
- * @param {o3d.VertexSource} dest VertexSource that bound to this VertexSource.
- * @param {o3d.ParamVertexBufferStream} dest_param Other param which was bound.
- * @protected
- */
-o3d.VertexSource.prototype.streamWasBound_ = function(
- dest, semantic, semantic_index) {
-};
-
diff --git a/o3d/samples/o3d-webgl/viewport.js b/o3d/samples/o3d-webgl/viewport.js
deleted file mode 100644
index 36eea87..0000000
--- a/o3d/samples/o3d-webgl/viewport.js
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * A Viewport is a render node that sets the render viewport and depth range
- * for its children. It uses an array in the format [left, top, width, height]
- * where left, top, width and height are in a 0.0 to 1.0 range that represent
- * positions and dimensions relative to the size of the client's rendering
- * area. The depth range is represented by an array in the format
- * [min Z, max Z]. The depth range provides the mapping of the clip space
- * coordinates into normalized z buffer coordinates.
- *
- * @param {o3d.math.Float4} viewport The viewport setting.
- * @param {o3d.math.Float2} depthRange ParamFloat2 The depth range setting.
- * @constructor
- */
-o3d.Viewport = function(opt_viewport, opt_depthRange) {
- o3d.RenderNode.call(this);
-
- /**
- * The position and size to set the viewport in
- * [left, top, width, height] format.
- *
- * Note: These values must describe a rectangle that is 100% inside
- * the client area. In other words, [0.5, 0.0, 1.0, 1.0] would
- * describe an area that is 1/2 off right side of the screen. That
- * is an invalid value and will be clipped to [0.5, 0.0, 0.5, 1.0].
- *
- * Default = [0.0, 0.0, 1.0, 1.0]. In other words, the full area.
- *
- * @type {!Array.<number>}
- */
- this.viewport = opt_viewport || [0.0, 0.0, 1.0, 1.0];
-
- /**
- * The min Z and max Z depth range in [min Z, max Z] format.
- * Default = [0.0, 1.0].
- *
- * @type {!Array.<number>}
- */
- this.depthRange = opt_depthRange || [0.0, 1.0];
-};
-o3d.inherit('Viewport', 'RenderNode');
-
-o3d.ParamObject.setUpO3DParam_(o3d.Viewport, 'viewport', 'ParamFloat4');
-o3d.ParamObject.setUpO3DParam_(o3d.Viewport, 'depthRange', 'ParamFloat2');
-
-/**
- * Called before the children are rendered. Sets up a viewport and
- * scissor region in gl.
- */
-o3d.Viewport.prototype.before = function() {
- var x = this.viewport[0] * this.gl.displayInfo.width;
- var y = (1 - this.viewport[1] - this.viewport[3]) *
- this.gl.displayInfo.height;
- var width = this.viewport[2] * this.gl.displayInfo.width;
- var height = this.viewport[3] * this.gl.displayInfo.height;
-
- this.gl.viewport(x, y, width, height);
- if (x != 0 || y != 0 || this.viewport[2] != 1 || this.viewport[3] != 1) {
- this.gl.enable(this.gl.SCISSOR_TEST);
- this.gl.scissor(x, y, width, height);
- } else {
- this.gl.disable(this.gl.SCISSOR_TEST);
- }
-};
-
diff --git a/o3d/samples/o3djs/arcball.js b/o3d/samples/o3djs/arcball.js
deleted file mode 100644
index ab72be6..0000000
--- a/o3d/samples/o3djs/arcball.js
+++ /dev/null
@@ -1,162 +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.
- */
-
-// A shout out to Terence J. Grant at tatewake.com for his tutorial on arcball
-// implementations.
-
-/**
- * @fileoverview This file contains functions for implementing an arcball
- * calculation. It puts them in the "arcball" module on the o3djs object.
- *
- * Note: This library is only a sample. It is not meant to be some official
- * library. It is provided only as example code.
- *
- */
-
-o3djs.provide('o3djs.arcball');
-
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-
-/**
- * A Module for arcball manipulation.
- *
- * This is useful for rotating a model with the mouse.
- *
- * @namespace
- */
-o3djs.arcball = o3djs.arcball || {};
-
-/**
- * Creates a new arcball.
- * @param {number} areaWidth width of area arcball should cover.
- * @param {number} areaHeight height of area arcball should cover.
- * @return {!o3djs.arcball.ArcBall} The created arcball.
- * @see o3djs.arcball
- */
-o3djs.arcball.create = function(areaWidth, areaHeight) {
- return new o3djs.arcball.ArcBall(areaWidth, areaHeight);
-};
-
-/**
- * A class that implements an arcball.
- * @constructor
- * @param {number} areaWidth width of area arcball should cover.
- * @param {number} areaHeight height of area arcball should cover.
- * @see o3djs.arcball
- */
-o3djs.arcball.ArcBall = function(areaWidth, areaHeight) {
- /**
- * The start vector.
- * @private
- * @type {!o3djs.math.Vector3}
- */
- this.startVector_ = [0, 0, 0];
-
- /**
- * The end vector.
- * @private
- * @type {!o3djs.math.Vector3}
- */
- this.endVector_ = [0, 0, 0];
-
- /**
- * The width of the arcBall area.
- * @private
- * @type {number}
- */
- this.areaWidth_ = areaWidth;
-
- /**
- * The height of the arcBall area.
- * @private
- * @type {number}
- */
- this.areaHeight_ = areaHeight;
-};
-
-
-/**
- * Sets the size of the arcball.
- * @param {number} areaWidth width of area arcball should cover.
- * @param {number} areaHeight height of area arcball should cover.
- */
-o3djs.arcball.ArcBall.prototype.setAreaSize = function(areaWidth, areaHeight) {
- this.areaWidth_ = areaWidth;
- this.areaHeight_ = areaHeight;
-};
-
-/**
- * Converts a 2d point to a point on the sphere of radius 1 sphere.
- * @param {!o3djs.math.Vector2} newPoint A point in 2d.
- * @return {!o3djs.math.Vector3} A point on the sphere of radius 1.
- */
-o3djs.arcball.ArcBall.prototype.mapToSphere = function(newPoint) {
- // Copy parameter into temp
- var tempPoint = o3djs.math.copyVector(newPoint);
-
- // Scale to -1.0 <-> 1.0
- tempPoint[0] = tempPoint[0] / this.areaWidth_ * 2.0 - 1.0;
- tempPoint[1] = 1.0 - tempPoint[1] / this.areaHeight_ * 2.0;
-
- // Compute square of length from center
- var lengthSquared = o3djs.math.lengthSquared(tempPoint);
-
- // If the point is mapped outside of the sphere... (length > radius squared)
- if (lengthSquared > 1.0) {
- return o3djs.math.normalize(tempPoint).concat(0);
- } else {
- // Otherwise it's on the inside.
- return tempPoint.concat(Math.sqrt(1.0 - lengthSquared));
- }
-};
-
-/**
- * Records the starting point on the sphere.
- * @param {!o3djs.math.Vector2} newPoint point in 2d.
- */
-o3djs.arcball.ArcBall.prototype.click = function(newPoint) {
- this.startVector_ = this.mapToSphere(newPoint);
-};
-
-/**
- * Computes the rotation of the sphere based on the initial point clicked as
- * set through Arcball.click and the current point passed in as newPoint
- * @param {!o3djs.math.Vector2} newPoint point in 2d.
- * @return {!o3djs.quaternions.Quaternion} A quaternion representing the new
- * orientation.
- */
-o3djs.arcball.ArcBall.prototype.drag = function(newPoint) {
- this.endVector_ = this.mapToSphere(newPoint);
-
- return o3djs.math.cross(this.startVector_, this.endVector_).concat(
- o3djs.math.dot(this.startVector_, this.endVector_));
-};
diff --git a/o3d/samples/o3djs/base.js b/o3d/samples/o3djs/base.js
deleted file mode 100644
index 00c5af8..0000000
--- a/o3d/samples/o3djs/base.js
+++ /dev/null
@@ -1,809 +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.
- */
-
-
-/**
- * @fileoverview Base for all o3d sample utilties.
- * For more information about o3d see
- * http://code.google.com/p/o3d.
- *
- *
- * The main point of this module is to provide a central place to
- * have an init function to register an o3d namespace object because many other
- * modules need access to it.
- */
-
-/**
- * A namespace for all the o3djs utility libraries.
- * @namespace
- */
-var o3djs = o3djs || {};
-
-/**
- * Define this because the Google internal JSCompiler needs goog.typedef below.
- */
-var goog = goog || {};
-
-/**
- * A macro for defining composite types.
- *
- * By assigning goog.typedef to a name, this tells Google internal JSCompiler
- * that this is not the name of a class, but rather it's the name of a composite
- * type.
- *
- * For example,
- * /** @type {Array|NodeList} / goog.ArrayLike = goog.typedef;
- * will tell JSCompiler to replace all appearances of goog.ArrayLike in type
- * definitions with the union of Array and NodeList.
- *
- * Does nothing in uncompiled code.
- */
-goog.typedef = true;
-
-/**
- * Reference to the global context. In most cases this will be 'window'.
- */
-o3djs.global = this;
-
-/**
- * Flag used to force a function to run in the browser when it is called
- * from V8.
- * @type {boolean}
- */
-o3djs.BROWSER_ONLY = true;
-
-/**
- * Array of namespaces that have been provided.
- * @private
- * @type {!Array.<string>}
- */
-o3djs.provided_ = [];
-
-/**
- * Creates object stubs for a namespace. When present in a file,
- * o3djs.provide also indicates that the file defines the indicated
- * object.
- * @param {string} name Name of the object that this file defines.
- * @param {boolean} opt_replace Whether to replace existing namespace.
- */
-o3djs.provide = function(name, opt_replace) {
- // Ensure that the same namespace isn't provided twice.
- if (!opt_replace) {
- if (o3djs.getObjectByName(name) &&
- !o3djs.implicitNamespaces_[name]) {
- throw 'Namespace "' + name + '" already declared.';
- }
- }
-
- var namespace = name;
- while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {
- o3djs.implicitNamespaces_[namespace] = true;
- }
-
- o3djs.exportPath_(name);
- o3djs.provided_.push(name);
-};
-
-
-/**
- * Namespaces implicitly defined by o3djs.provide. For example,
- * o3djs.provide('o3djs.events.Event') implicitly declares
- * that 'o3djs' and 'o3djs.events' must be namespaces.
- *
- * @type {Object}
- * @private
- */
-o3djs.implicitNamespaces_ = {};
-
-/**
- * Builds an object structure for the provided namespace path,
- * ensuring that names that already exist are not overwritten. For
- * example:
- * "a.b.c" -> a = {};a.b={};a.b.c={};
- * Used by o3djs.provide and o3djs.exportSymbol.
- * @param {string} name name of the object that this file defines.
- * @param {Object} opt_object the object to expose at the end of the path.
- * @param {Object} opt_objectToExportTo The object to add the path to; default
- * is |o3djs.global|.
- * @private
- */
-o3djs.exportPath_ = function(name, opt_object, opt_objectToExportTo) {
- var parts = name.split('.');
- var cur = opt_objectToExportTo || o3djs.global;
- var part;
-
- // Internet Explorer exhibits strange behavior when throwing errors from
- // methods externed in this manner. See the testExportSymbolExceptions in
- // base_test.html for an example.
- if (!(parts[0] in cur) && cur.execScript) {
- cur.execScript('var ' + parts[0]);
- }
-
- // Parentheses added to eliminate strict JS warning in Firefox.
- while (parts.length && (part = parts.shift())) {
- if (!parts.length && o3djs.isDef(opt_object)) {
- // last part and we have an object; use it.
- cur[part] = opt_object;
- } else if (cur[part]) {
- cur = cur[part];
- } else {
- cur = cur[part] = {};
- }
- }
-};
-
-
-/**
- * Returns an object based on its fully qualified external name. If you are
- * using a compilation pass that renames property names beware that using this
- * function will not find renamed properties.
- *
- * @param {string} name The fully qualified name.
- * @param {Object} opt_obj The object within which to look; default is
- * |o3djs.global|.
- * @return {Object} The object or, if not found, null.
- */
-o3djs.getObjectByName = function(name, opt_obj) {
- var parts = name.split('.');
- var cur = opt_obj || o3djs.global;
- for (var pp = 0; pp < parts.length; ++pp) {
- var part = parts[pp];
- if (cur[part]) {
- cur = cur[part];
- } else {
- return null;
- }
- }
- return cur;
-};
-
-
-/**
- * Implements a system for the dynamic resolution of dependencies.
- * @param {string} rule Rule to include, in the form o3djs.package.part.
- */
-o3djs.require = function(rule) {
- // TODO(gman): For some unknown reason, when we call
- // o3djs.util.getScriptTagText_ it calls
- // document.getElementsByTagName('script') and for some reason the scripts do
- // not always show up. Calling it here seems to fix that as long as we
- // actually ask for the length, at least in FF 3.5.1 It would be nice to
- // figure out why.
- var dummy = document.getElementsByTagName('script').length;
-
- // if the object already exists we do not need do do anything
- if (o3djs.getObjectByName(rule)) {
- return;
- }
- var path = o3djs.getPathFromRule_(rule);
- if (path) {
- o3djs.included_[path] = true;
- o3djs.writeScripts_();
- } else {
- throw new Error('o3djs.require could not find: ' + rule);
- }
-};
-
-
-/**
- * Path for included scripts.
- * @type {string}
- */
-o3djs.basePath = '';
-
-
-/**
- * Object used to keep track of urls that have already been added. This
- * record allows the prevention of circular dependencies.
- * @type {Object}
- * @private
- */
-o3djs.included_ = {};
-
-
-/**
- * This object is used to keep track of dependencies and other data that is
- * used for loading scripts.
- * @private
- * @type {Object}
- */
-o3djs.dependencies_ = {
- visited: {}, // used when resolving dependencies to prevent us from
- // visiting the file twice.
- written: {} // used to keep track of script files we have written.
-};
-
-
-/**
- * Tries to detect the base path of the o3djs-base.js script that
- * bootstraps the o3djs libraries.
- * @private
- */
-o3djs.findBasePath_ = function() {
- var doc = o3djs.global.document;
- if (typeof doc == 'undefined') {
- return;
- }
- if (o3djs.global.BASE_PATH) {
- o3djs.basePath = o3djs.global.BASE_PATH;
- return;
- } else {
- // HACKHACK to hide compiler warnings :(
- o3djs.global.BASE_PATH = null;
- }
- var scripts = doc.getElementsByTagName('script');
- for (var script, i = 0; script = scripts[i]; i++) {
- var src = script.src;
- var l = src.length;
- if (src.substr(l - 13) == 'o3djs/base.js') {
- o3djs.basePath = src.substr(0, l - 13);
- return;
- }
- }
-};
-
-
-/**
- * Writes a script tag if, and only if, that script hasn't already been added
- * to the document. (Must be called at execution time.)
- * @param {string} src Script source.
- * @private
- */
-o3djs.writeScriptTag_ = function(src) {
- var doc = o3djs.global.document;
- if (typeof doc != 'undefined' &&
- !o3djs.dependencies_.written[src]) {
- o3djs.dependencies_.written[src] = true;
- doc.write('<script type="text/javascript" src="' +
- src + '"></' + 'script>');
- }
-};
-
-
-/**
- * Resolves dependencies based on the dependencies added using addDependency
- * and calls writeScriptTag_ in the correct order.
- * @private
- */
-o3djs.writeScripts_ = function() {
- // the scripts we need to write this time.
- var scripts = [];
- var seenScript = {};
- var deps = o3djs.dependencies_;
-
- function visitNode(path) {
- if (path in deps.written) {
- return;
- }
-
- // we have already visited this one. We can get here if we have cyclic
- // dependencies.
- if (path in deps.visited) {
- if (!(path in seenScript)) {
- seenScript[path] = true;
- scripts.push(path);
- }
- return;
- }
-
- deps.visited[path] = true;
-
- if (!(path in seenScript)) {
- seenScript[path] = true;
- scripts.push(path);
- }
- }
-
- for (var path in o3djs.included_) {
- if (!deps.written[path]) {
- visitNode(path);
- }
- }
-
- for (var i = 0; i < scripts.length; i++) {
- if (scripts[i]) {
- o3djs.writeScriptTag_(o3djs.basePath + scripts[i]);
- } else {
- throw Error('Undefined script input');
- }
- }
-};
-
-
-/**
- * Looks at the dependency rules and tries to determine the script file that
- * fulfills a particular rule.
- * @param {string} rule In the form o3djs.namespace.Class or
- * project.script.
- * @return {string?} Url corresponding to the rule, or null.
- * @private
- */
-o3djs.getPathFromRule_ = function(rule) {
- var parts = rule.split('.');
- return parts.join('/') + '.js';
-};
-
-o3djs.findBasePath_();
-
-/**
- * Returns true if the specified value is not |undefined|.
- * WARNING: Do not use this to test if an object has a property. Use the in
- * operator instead.
- * @param {*} val Variable to test.
- * @return {boolean} Whether variable is defined.
- */
-o3djs.isDef = function(val) {
- return typeof val != 'undefined';
-};
-
-
-/**
- * Exposes an unobfuscated global namespace path for the given object.
- * Note that fields of the exported object *will* be obfuscated,
- * unless they are exported in turn via this function or
- * o3djs.exportProperty.
- *
- * <p>Also handy for making public items that are defined in anonymous
- * closures.
- *
- * ex. o3djs.exportSymbol('Foo', Foo);
- *
- * ex. o3djs.exportSymbol('public.path.Foo.staticFunction',
- * Foo.staticFunction);
- * public.path.Foo.staticFunction();
- *
- * ex. o3djs.exportSymbol('public.path.Foo.prototype.myMethod',
- * Foo.prototype.myMethod);
- * new public.path.Foo().myMethod();
- *
- * @param {string} publicPath Unobfuscated name to export.
- * @param {Object} object Object the name should point to.
- * @param {Object} opt_objectToExportTo The object to add the path to; default
- * is |o3djs.global|.
- */
-o3djs.exportSymbol = function(publicPath, object, opt_objectToExportTo) {
- o3djs.exportPath_(publicPath, object, opt_objectToExportTo);
-};
-
-/**
- * This string contains JavaScript code to initialize a new V8 instance.
- * @private
- * @type {string}
- */
-o3djs.v8Initializer_ = '';
-
-/**
- * This array contains references to objects that v8 needs to bind to when
- * it initializes.
- * @private
- * @type {!Array.<Object>}
- */
-o3djs.v8InitializerArgs_ = [];
-
-/**
- * Converts any JavaScript value to a string representation that when evaluated
- * will result in an equal value.
- * @param {*} value Any value.
- * @return {string} A string representation for the value.
- * @private
- */
-o3djs.valueToString_ = function(value) {
- switch (typeof(value)) {
- case 'undefined':
- return 'undefined';
- case 'string':
- var escaped = escape(value);
- if (escaped === value) {
- return '"' + value + '"';
- } else {
- return 'unescape("' + escaped + '")';
- }
- case 'object':
- if (value === null) {
- return 'null';
- } else {
- // TODO: all the other builtin JavaScript objects like Date,
- // Number, Boolean, etc.
- if (value instanceof RegExp) {
- var result =
- 'new RegExp(' + o3djs.valueToString_(value.source) + ', "';
- if (value.global) {
- result += 'g';
- }
- if (value.ignoreCase) {
- result += 'i';
- }
- if (value.multiline) {
- result += 'm';
- }
- result += '")';
- return result;
- } else if (o3djs.base.isArray(value)) {
- var valueAsArray = /** @type {!Array} */ (value);
- var result = '[';
- var separator = '';
- for (var i = 0; i < valueAsArray.length; ++i) {
- result += separator + o3djs.valueToString_(valueAsArray[i]);
- separator = ',';
- }
- result += ']\n';
- return result;
- } else {
- var valueAsObject = /** @type {!Object} */ (value);
- var result = '{\n';
- var separator = '';
- for (var propertyName in valueAsObject) {
- result += separator + '"' + propertyName + '": ' +
- o3djs.valueToString_(valueAsObject[propertyName]);
- separator = ',';
- }
- result += '}\n';
- return result;
- }
- }
- default:
- return value.toString()
- }
-};
-
-/**
- * Given an object holding a namespace and the name of that namespace,
- * generates a string that when evaluated will populate the namespace.
- * @param {!Object} namespaceObject An object holding a namespace.
- * @param {string} namespaceName The name of the namespace.
- * @param {!Array.<Object>} opt_args An array of objects that will be used
- * together with the initializer string to populate a namespace. The args
- * may be referenced from initializer code as args_[i] where i is the index
- * in the array.
- * @return {string} A string that will populate the namespace.
- * @private
- */
-o3djs.namespaceInitializer_ = function(namespaceObject,
- namespaceName,
- opt_args) {
- var result = namespaceName + ' = {};\n';
- for (var propertyName in namespaceObject) {
- var propertyNamespaceName = namespaceName + '.' + propertyName;
- var propertyValue = namespaceObject[propertyName];
- if (typeof(propertyValue) === 'object' && propertyValue !== null &&
- !o3djs.base.isArray(propertyValue) &&
- !(propertyValue instanceof RegExp)) {
- result += o3djs.namespaceInitializer_(propertyValue,
- propertyNamespaceName);
- } else {
- var valueAsString = o3djs.valueToString_(propertyValue);
-
- // If this is a browser only function then bind to the browser version
- // of the function rather than create a new function in V8.
- if (typeof(propertyValue) == 'function' &&
- valueAsString.indexOf('o3djs.BROWSER_ONLY') != -1) {
- valueAsString = 'args_[' + opt_args.length + ']';
- opt_args.push(propertyValue);
- }
- result += propertyNamespaceName + ' = ' + valueAsString + ';\n';
-
- if (typeof(propertyValue) === 'function' && propertyValue.prototype) {
- result += o3djs.namespaceInitializer_(
- propertyValue.prototype,
- propertyNamespaceName + '.prototype');
- }
- }
- }
- return result;
-};
-
-o3djs.provide('o3djs.base');
-
-/**
- * The base module for o3djs.
- * @namespace
- */
-o3djs.base = o3djs.base || {};
-
-/**
- * The a Javascript copy of the o3d namespace object. (holds constants, enums,
- * etc...)
- * @type {o3d}
- */
-o3djs.base.o3d = null;
-
-/**
- * Whether or not we need to use GLSL instead of HLSL.
- * @type {boolean}
- */
-o3djs.base.glsl = false;
-
-/**
- * Snapshots the current state of all provided namespaces. This state will be
- * used to initialize future V8 instances. It is automatically
- * called by o3djs.util.makeClients.
- */
-o3djs.base.snapshotProvidedNamespaces = function() {
- // Snapshot the V8 initializer string from the current state of browser
- // JavaScript the first time this is called.
- o3djs.v8Initializer_ = 'function(args_) {\n';
- o3djs.v8InitializerArgs_ = [];
- for (var i = 0; i < o3djs.provided_.length; ++i) {
- var object = o3djs.getObjectByName(o3djs.provided_[i]);
- o3djs.v8Initializer_ += o3djs.namespaceInitializer_(
- /** @type {!Object} */ (object),
- o3djs.provided_[i],
- o3djs.v8InitializerArgs_);
- }
-
- o3djs.v8Initializer_ += '}\n';
-};
-
-/**
- * Initializes the o3djs.sample library in a v8 instance. This should be called
- * for every V8 instance that uses the sample library. It is automatically
- * called by o3djs.util.makeClients.
- * @param {!Element} clientObject O3D.Plugin Object.
- */
-o3djs.base.initV8 = function(clientObject) {
- var v8Init = function(initializer, args) {
- // Set up the o3djs namespace.
- var o3djsBrowser = o3djs;
- o3djs = {};
- o3djs.browser = o3djsBrowser;
- o3djs.global = (function() { return this; })();
-
- o3djs.require = function(rule) {}
- o3djs.provide = function(rule) {}
-
- // Evaluate the initializer string with the arguments containing bindings
- // to browser side objects.
- eval('(' + initializer + ')')(args);
-
- // Make sure this points to the o3d namespace for this particular
- // instance of the plugin.
- o3djs.base.o3d = plugin.o3d;
-
- // Save off if we need GLSL.
- o3djs.base.glsl = plugin.client.clientInfo.glsl;
- };
-
- clientObject.eval(v8Init.toString())(o3djs.v8Initializer_,
- o3djs.v8InitializerArgs_);
-};
-
-/**
- * Initializes the o3djs.sample library.
- * Basically all it does is record the o3djs.namespace object which is used by
- * other functions to look up o3d constants.
- *
- * @param {!Element} clientObject O3D.Plugin Object.
- */
-o3djs.base.init = function(clientObject) {
- function recursivelyCopyProperties(object) {
- var copy = {};
- var hasProperties = false;
- for (var key in object) {
- var property = object[key];
- if (typeof property == 'object' || typeof property == 'function') {
- property = recursivelyCopyProperties(property);
- }
- if (typeof property != 'undefined') {
- copy[key] = property;
- hasProperties = true;
- }
- }
- return hasProperties ? copy : undefined;
- }
- try {
- o3djs.base.o3d = recursivelyCopyProperties(clientObject.o3d);
- } catch (e) {
- // Firefox 2 raises an exception when trying to enumerate a NPObject
- o3djs.base.o3d = clientObject.o3d;
- }
- // Because of a bug in chrome, it is not possible for the browser to enumerate
- // the properties of an NPObject.
- // Chrome bug: http://code.google.com/p/chromium/issues/detail?id=5743
- o3djs.base.o3d = o3djs.base.o3d || clientObject.o3d;
- // Save off if we need GLSL.
- o3djs.base.glsl = clientObject.client.clientInfo.glsl;
-};
-
-/**
- * Determine whether a value is an array. Do not use instanceof because that
- * will not work for V8 arrays (the browser thinks they are Objects).
- * @param {*} value A value.
- * @return {boolean} Whether the value is an array.
- */
-o3djs.base.isArray = function(value) {
- var valueAsObject = /** @type {!Object} */ (value);
- return typeof(value) === 'object' && value !== null &&
- 'length' in valueAsObject && 'splice' in valueAsObject;
-};
-
-/**
- * Check if the o3djs library has been initialized.
- * @return {boolean} true if ready, false if not.
- */
-o3djs.base.ready = function() {
- return o3djs.base.o3d != null;
-};
-
-/**
- * A stub for later optionally converting obfuscated names
- * @private
- * @param {string} name Name to un-obfuscate.
- * @return {string} un-obfuscated name.
- */
-o3djs.base.maybeDeobfuscateFunctionName_ = function(name) {
- return name;
-};
-
-/**
- * Makes one class inherit from another.
- * @param {!Object} subClass Class that wants to inherit.
- * @param {!Object} superClass Class to inherit from.
- */
-o3djs.base.inherit = function(subClass, superClass) {
- /**
- * TmpClass.
- * @ignore
- * @constructor
- */
- var TmpClass = function() { };
- TmpClass.prototype = superClass.prototype;
- subClass.prototype = new TmpClass();
-};
-
-/**
- * Parses an error stack from an exception
- * @param {!Exception} excp The exception to get a stack trace from.
- * @return {!Array.<string>} An array of strings of the stack trace.
- */
-o3djs.base.parseErrorStack = function(excp) {
- var stack = [];
- var name;
- var line;
-
- if (!excp || !excp.stack) {
- return stack;
- }
-
- var stacklist = excp.stack.split('\n');
-
- for (var i = 0; i < stacklist.length - 1; i++) {
- var framedata = stacklist[i];
-
- name = framedata.match(/^([a-zA-Z0-9_$]*)/)[1];
- if (name) {
- name = o3djs.base.maybeDeobfuscateFunctionName_(name);
- } else {
- name = 'anonymous';
- }
-
- var result = framedata.match(/(.*:[0-9]+)$/);
- line = result && result[1];
-
- if (!line) {
- line = '(unknown)';
- }
-
- stack[stack.length] = name + ' : ' + line
- }
-
- // remove top level anonymous functions to match IE
- var omitRegexp = /^anonymous :/;
- while (stack.length && omitRegexp.exec(stack[stack.length - 1])) {
- stack.length = stack.length - 1;
- }
-
- return stack;
-};
-
-/**
- * Gets a function name from a function object.
- * @param {!function(...): *} aFunction The function object to try to get a
- * name from.
- * @return {string} function name or 'anonymous' if not found.
- */
-o3djs.base.getFunctionName = function(aFunction) {
- var regexpResult = aFunction.toString().match(/function(\s*)(\w*)/);
- if (regexpResult && regexpResult.length >= 2 && regexpResult[2]) {
- return o3djs.base.maybeDeobfuscateFunctionName_(regexpResult[2]);
- }
- return 'anonymous';
-};
-
-/**
- * Pretty prints an exception's stack, if it has one.
- * @param {Array.<string>} stack An array of errors.
- * @return {string} The pretty stack.
- */
-o3djs.base.formatErrorStack = function(stack) {
- var result = '';
- for (var i = 0; i < stack.length; i++) {
- result += '> ' + stack[i] + '\n';
- }
- return result;
-};
-
-/**
- * Gets a stack trace as a string.
- * @param {number} stripCount The number of entries to strip from the top of the
- * stack. Example: Pass in 1 to remove yourself from the stack trace.
- * @return {string} The stack trace.
- */
-o3djs.base.getStackTrace = function(stripCount) {
- var result = '';
-
- if (typeof(arguments.caller) != 'undefined') { // IE, not ECMA
- for (var a = arguments.caller; a != null; a = a.caller) {
- result += '> ' + o3djs.base.getFunctionName(a.callee) + '\n';
- if (a.caller == a) {
- result += '*';
- break;
- }
- }
- } else { // Mozilla, not ECMA
- // fake an exception so we can get Mozilla's error stack
- var testExcp;
- try {
- eval('var var;');
- } catch (testExcp) {
- var stack = o3djs.base.parseErrorStack(testExcp);
- result += o3djs.base.formatErrorStack(stack.slice(3 + stripCount,
- stack.length));
- }
- }
-
- return result;
-};
-
-/**
- * Sets the error handler on a client to a handler that displays an alert on the
- * first error.
- * @param {!o3d.Client} client The client object of the plugin.
- */
-o3djs.base.setErrorHandler = function(client) {
- client.setErrorCallback(
- function(msg) {
- // Clear the error callback. Otherwise if the callback is happening
- // during rendering it's possible the user will not be able to
- // get out of an infinite loop of alerts.
- client.clearErrorCallback();
- alert('ERROR: ' + msg + '\n' + o3djs.base.getStackTrace(1));
- });
-};
-
-/**
- * Returns true if the user's browser is Microsoft IE.
- * @return {boolean} true if the user's browser is Microsoft IE.
- */
-o3djs.base.IsMSIE = function() {
- var ua = navigator.userAgent.toLowerCase();
- var msie = /msie/.test(ua) && !/opera/.test(ua);
- return msie;
-};
diff --git a/o3d/samples/o3djs/camera.js b/o3d/samples/o3djs/camera.js
deleted file mode 100644
index 9acf95e..0000000
--- a/o3d/samples/o3djs/camera.js
+++ /dev/null
@@ -1,364 +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.
- */
-
-
-/**
- * @fileoverview This file contains various camera utility functions for
- * o3d. It puts them in the "camera" module on the o3djs object.
- *
- * Note: This library is only a sample. It is not meant to be some official
- * library. It is provided only as example code.
- *
- */
-
-o3djs.provide('o3djs.camera');
-
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-
-/**
- * A Module for camera utilites.
- * @namespace
- */
-o3djs.camera = o3djs.camera || {};
-
-/**
- * Class to hold Camera information.
- * @constructor
- * @param {!o3djs.math.Matrix4} view The 4-by-4 view matrix.
- * @param {number} zNear near z plane.
- * @param {number} zFar far z plane.
- * @param {!o3djs.math.Vector3} opt_eye The eye position.
- * @param {!o3djs.math.Vector3} opt_target The target position.
- * @param {!o3djs.math.Vector3} opt_up The up vector.
- */
-o3djs.camera.CameraInfo = function(view,
- zNear,
- zFar,
- opt_eye,
- opt_target,
- opt_up) {
- /**
- * View Matrix.
- * @type {!o3djs.math.Matrix4}
- */
- this.view = view;
-
- /**
- * Projection Matrix.
- * @type {!o3djs.math.Matrix4}
- */
- this.projection = o3djs.math.matrix4.identity();
-
- /**
- * Projection is orthographic.
- * @type {boolean}
- */
- this.orthographic = false;
-
- /**
- * Near z plane.
- * @type {number}
- */
- this.zNear = zNear;
-
- /**
- * Far z plane.
- * @type {number}
- */
- this.zFar = zFar;
-
- /**
- * Field of view in radians.
- * @type {number}
- */
- this.fieldOfViewRadians = o3djs.math.degToRad(30);
-
- /**
- * Eye position.
- * @type {(!o3djs.math.Vector3|undefined)}
- */
- this.eye = opt_eye;
-
- /**
- * Target position.
- * @type {(!o3djs.math.Vector3|undefined)}
- */
- this.target = opt_target;
-
- /**
- * Up Vector.
- * @type {(!o3djs.math.Vector3|undefined)}
- */
- this.up = opt_up;
-
- /**
- * horizontal magnification for an orthographic view.
- * @type {(number|undefined)}
- */
- this.magX = undefined;
-
- /**
- * vertical magnification for an orthographic view.
- * @type {(number|undefined)}
- */
- this.magY = undefined;
-};
-
-/**
- * Sets the CameraInfo to an orthographic camera.
- * @param {number} magX horizontal magnification.
- * @param {number} magY vertical magnification.
- */
-o3djs.camera.CameraInfo.prototype.setAsOrthographic = function(
- magX, magY) {
- this.orthographic = true
- this.magX = magX;
- this.magY = magY;
-};
-
-/**
- * Sets the CameraInfo to an orthographic camera.
- * @param {number} fieldOfView Field of view in radians.
- */
-o3djs.camera.CameraInfo.prototype.setAsPerspective = function(
- fieldOfView) {
- this.orthographic = false;
- this.fieldOfViewRadians = fieldOfView;
-};
-
-/**
- * Computes a projection matrix for this CameraInfo using the areaWidth
- * and areaHeight passed in.
- *
- * @param {number} areaWidth width of client area.
- * @param {number} areaHeight heigh of client area.
- * @return {!o3djs.math.Matrix4} The computed projection matrix.
- */
-o3djs.camera.CameraInfo.prototype.computeProjection = function(
- areaWidth,
- areaHeight) {
- if (this.orthographic) {
- // TODO: figure out if there is a way to make this take the areaWidth
- // and areaHeight into account. As it is, magX and magY from the
- // collada file are relative to the aspect ratio of Maya's render
- // settings which are not available here.
- // var magX = areaWidth * 0.5 / this.magX;
- // var magY = areaHeight * 0.5 / this.magY;
- var magX = /** @type {number} */ (this.magX);
- var magY = /** @type {number} */ (this.magY);
- this.projection = o3djs.math.matrix4.orthographic(
- -magX, magX, -magY, magY, this.zNear, this.zFar);
- } else {
- this.projection = o3djs.math.matrix4.perspective(
- this.fieldOfViewRadians, // field of view.
- areaWidth / areaHeight, // Aspect ratio.
- this.zNear, // Near plane.
- this.zFar); // Far plane.
- }
- return this.projection;
-};
-
-/**
- * Searches for all nodes with a "o3d.tags" ParamString
- * that contains the word "camera" assuming comma separated
- * words.
- * @param {!o3d.Transform} treeRoot Root of tree to search for cameras.
- * @return {!Array.<!o3d.Transform>} Array of camera transforms.
- */
-o3djs.camera.findCameras = function(treeRoot) {
- return o3djs.util.getTransformsInTreeByTags(treeRoot, 'camera');
-};
-
-/**
- * Creates a object with view and projection matrices using paramters found on
- * the camera 'o3d.projection_near_z', 'o3d.projection_far_z', and
- * 'o3d.perspective_fov_y' as well as the areaWidth and areaHeight passed
- * in.
- * @param {!o3d.Transform} camera Transform with camera information on it.
- * @param {number} areaWidth width of client area.
- * @param {number} areaHeight height of client area.
- * @return {!o3djs.camera.CameraInfo} A CameraInfo object.
- */
-o3djs.camera.getViewAndProjectionFromCamera = function(camera,
- areaWidth,
- areaHeight) {
- var fieldOfView = 30;
- var zNear = 1;
- var zFar = 5000;
- var eye = undefined;
- var target = undefined;
- var up = undefined;
- var view;
- var math = o3djs.math;
- var cameraInfo;
-
- // Check if any LookAt elements were found for the camera and use their
- // values to compute a view matrix.
- var eyeParam = camera.getParam('collada.eyePosition');
- var targetParam = camera.getParam('collada.targetPosition');
- var upParam = camera.getParam('collada.upVector');
- if (eyeParam != null && targetParam != null && upParam != null) {
- eye = eyeParam.value;
- target = targetParam.value;
- up = upParam.value;
- view = math.matrix4.lookAt(eye, target, up);
- } else {
- // Set it to the orientation of the camera.
- view = math.inverse(camera.getUpdatedWorldMatrix());
- }
-
- var projectionType = camera.getParam('collada.projectionType');
- if (projectionType) {
- zNear = camera.getParam('collada.projectionNearZ').value;
- zFar = camera.getParam('collada.projectionFarZ').value;
-
- if (projectionType.value == 'orthographic') {
- var magX = camera.getParam('collada.projectionMagX').value;
- var magY = camera.getParam('collada.projectionMagY').value;
-
- cameraInfo = new o3djs.camera.CameraInfo(view, zNear, zFar);
- cameraInfo.setAsOrthographic(magX, magY);
- } else if (projectionType.value == 'perspective') {
- fieldOfView = camera.getParam('collada.perspectiveFovY').value;
- }
- }
-
- if (!cameraInfo) {
- cameraInfo = new o3djs.camera.CameraInfo(view, zNear, zFar,
- eye, target, up);
- cameraInfo.setAsPerspective(math.degToRad(fieldOfView));
- }
-
- cameraInfo.computeProjection(areaWidth, areaHeight);
- return cameraInfo;
-};
-
-/**
- * Get CameraInfo that represents a view of the bounding box that encompasses
- * a tree of transforms.
- * @param {!o3d.Transform} treeRoot Root of sub tree to get extents from.
- * @param {number} clientWidth width of client area.
- * @param {number} clientHeight height of client area.
- * @return {!o3djs.camera.CameraInfo} A CameraInfo object.
- */
-o3djs.camera.getCameraFitToScene = function(treeRoot,
- clientWidth,
- clientHeight) {
- var math = o3djs.math;
- var box = o3djs.util.getBoundingBoxOfTree(treeRoot);
- var target = math.lerpVector(box.minExtent, box.maxExtent, 0.5);
- var boxDimensions = math.subVector(box.maxExtent, box.minExtent);
- var diag = o3djs.math.distance(box.minExtent, box.maxExtent);
- var eye = math.addVector(target, [boxDimensions[0] * 0.3,
- boxDimensions[1] * 0.7,
- diag * 1.5]);
- var nearPlane = diag / 1000;
- var farPlane = diag * 10;
-
- var up = [0, 1, 0];
- var cameraInfo = new o3djs.camera.CameraInfo(
- math.matrix4.lookAt(eye, target, up),
- nearPlane,
- farPlane);
-
- cameraInfo.setAsPerspective(math.degToRad(45));
- cameraInfo.computeProjection(clientWidth, clientHeight);
- return cameraInfo;
-};
-
-/**
- * Calls findCameras and takes the first camera. Then calls
- * o3djs.camera.getViewAndProjectionFromCamera. If no camera is found it
- * sets up some defaults.
- * @param {!o3d.Transform} treeRoot Root of tree to search for cameras.
- * @param {number} areaWidth Width of client area.
- * @param {number} areaHeight Height of client area.
- * @return {!o3djs.camera.CameraInfo} A CameraInfo object.
- */
-o3djs.camera.getViewAndProjectionFromCameras = function(treeRoot,
- areaWidth,
- areaHeight) {
- var cameras = o3djs.camera.findCameras(treeRoot);
-
- if (cameras.length > 0) {
- return o3djs.camera.getViewAndProjectionFromCamera(cameras[0],
- areaWidth,
- areaHeight);
- } else {
- // There was no camera in the file so make up a hopefully resonable default.
- return o3djs.camera.getCameraFitToScene(treeRoot,
- areaWidth,
- areaHeight);
- }
-};
-
-/**
- * Calls findCameras and creates an array of CameraInfos for each camera found.
- * @param {!o3d.Transform} treeRoot Root of tree to search for cameras.
- * @param {number} areaWidth Width of client area.
- * @param {number} areaHeight Height of client area.
- * @return {!Array.<!o3djs.camera.CameraInfo>} A CameraInfo object.
- */
-o3djs.camera.getCameraInfos = function(treeRoot, areaWidth, areaHeight) {
- var cameras = o3djs.camera.findCameras(treeRoot);
- var cameraInfos = [];
-
- for (var cc = 0; cc < cameras.length; ++cc) {
- cameraInfos.push(o3djs.camera.getViewAndProjectionFromCamera(
- cameras[cc], areaWidth, areaHeight));
- }
- return cameraInfos;
-};
-
-/**
- * Sets the view and projection of a DrawContext to view the bounding box
- * that encompasses the tree of transforms passed.
- *
- * This function is here to help debug a program by providing an easy way to
- * attempt to get your content in front of the camera.
- *
- * @param {!o3d.Transform} treeRoot Root of sub tree to get extents from.
- * @param {number} clientWidth width of client area.
- * @param {number} clientHeight height of client area.
- * @param {!o3d.DrawContext} drawContext DrawContext to set view and
- * projection on.
- */
-o3djs.camera.fitContextToScene = function(treeRoot,
- clientWidth,
- clientHeight,
- drawContext) {
- var cameraInfo = o3djs.camera.getCameraFitToScene(treeRoot,
- clientWidth,
- clientHeight);
- drawContext.view = cameraInfo.view;
- drawContext.projection = cameraInfo.projection;
-};
diff --git a/o3d/samples/o3djs/cameracontroller.js b/o3d/samples/o3djs/cameracontroller.js
deleted file mode 100644
index 69dc100..0000000
--- a/o3d/samples/o3djs/cameracontroller.js
+++ /dev/null
@@ -1,396 +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.
- */
-
-
-/**
- * @fileoverview This file contains sample code for controlling the camera
- * (ie view matrix) using the mouse and keyboard.
- */
-
-o3djs.provide('o3djs.cameracontroller');
-
-o3djs.require('o3djs.math');
-
-/**
- * A Module for user control of the camera / view matrix.
- * @namespace
- */
-o3djs.cameracontroller = o3djs.cameracontroller || {};
-
-/**
- * The possible modes that a CameraController can be in.
- * One of these is usually set when a mouse button is pressed down,
- * and then NONE is set when the mouse button is released.
- * When the mouse is moved, the DragMode determines what effect the mouse move
- * has on the camera parameters (such as position and orientation).
- * If the DragMode is NONE, mouse moves have no effect.
- * @enum {number}
- */
-o3djs.cameracontroller.DragMode = {
- /**
- * Dragging the mouse has no effect.
- */
- NONE: 0,
- /**
- * Dragging left or right changes rotationAngle,
- * dragging up or down changes heightAngle.
- */
- SPIN_ABOUT_CENTER: 1,
- /**
- * Dragging up or down changes the backpedal.
- */
- DOLLY_IN_OUT: 2,
- /**
- * Dragging up or down changes the fieldOfViewAngle.
- */
- ZOOM_IN_OUT: 3,
- /**
- * Dragging up or down changes the amount of perspective.
- * Perspective is focused on the centerPos.
- * If backpedal is negative or zero, there is no effect.
- */
- DOLLY_ZOOM: 4,
- /**
- * Dragging moves the centerPos around the plane perpendicular to
- * the camera view direction.
- */
- MOVE_CENTER_IN_VIEW_PLANE: 5
-};
-
-/**
- * Creates a CameraController.
- * @param {!o3djs.math.Vector3} centerPos The position that the camera is
- * looking at and rotating around; or if backpedal is zero, the location
- * of the camera. In world space.
- * @param {number} backpedal The distance the camera moves back from the
- * centerPos.
- * @param {number} heightAngle The angle the camera rotates up or down
- * (about the x axis that passes through the centerPos). In radians.
- * @param {number} rotationAngle The angle the camera rotates left or right
- * (about the y axis that passes through the centerPos). In radians.
- * @param {number} fieldOfViewAngle The vertical angle of the viewing frustum.
- * In radians, between 0 and PI/2. This does not affect the view matrix,
- * but it can still be useful to let the CameraController control the
- * field of view.
- * @param {function(!o3djs.cameracontroller.CameraController): void}
- * opt_onChange Pointer to a callback to call when the camera changes.
- * @return {!o3djs.cameracontroller.CameraController} The created
- * CameraController.
- */
-o3djs.cameracontroller.createCameraController = function(centerPos,
- backpedal,
- heightAngle,
- rotationAngle,
- fieldOfViewAngle,
- opt_onChange) {
- return new o3djs.cameracontroller.CameraController(centerPos,
- backpedal,
- heightAngle,
- rotationAngle,
- fieldOfViewAngle,
- opt_onChange);
-};
-
-/**
- * Class to hold user-controlled camera information and handle user events.
- * It can control and output a view matrix, and can also control some aspects
- * of a projection matrix.
- *
- * Most of the parameters it controls affect the view matrix, and it can
- * generate a view matrix based on its parameters.
- * It can also control certain parameters that affect the projection matrix,
- * such as field of view. Rather than deal with all the parameters needed for
- * a projection matrix, this class leaves generation of the projection matrix
- * up to the user code, and simply exposes the parameters it has.
- * @constructor
- * @param {!o3djs.math.Vector3} centerPos The position that the camera is
- * looking at and rotating around; or if backpedal is zero, the location
- * of the camera. In world space.
- * @param {number} backpedal The distance the camera moves back from the
- * centerPos.
- * @param {number} heightAngle The angle the camera rotates up or down
- * (about the x axis that passes through the centerPos). In radians.
- * @param {number} rotationAngle The angle the camera rotates left or right
- * (about the y axis that passes through the centerPos). In radians.
- * @param {number} fieldOfViewAngle The vertical angle of the viewing frustum.
- * In radians, between 0 and PI/2. This does not affect the view matrix,
- * but it can still be useful to let this class control the field of view.
- * @param {function(!o3djs.cameracontroller.CameraController): void}
- * opt_onChange Pointer to a callback to call when the camera changes.
- */
-o3djs.cameracontroller.CameraController = function(centerPos,
- backpedal,
- heightAngle,
- rotationAngle,
- fieldOfViewAngle,
- opt_onChange) {
- /**
- * The position that the camera is looking at and rotating around.
- * Or if backpedal is zero, the location of the camera. In world space.
- * @type {!o3djs.math.Vector3}
- */
- this.centerPos = centerPos;
-
- /**
- * The distance the camera moves back from the centerPos.
- * @type {number}
- */
- this.backpedal = backpedal;
-
- /**
- * The angle the camera rotates up or down.
- * @type {number}
- */
- this.heightAngle = heightAngle;
-
- /**
- * The angle the camera rotates left or right.
- * @type {number}
- */
- this.rotationAngle = rotationAngle;
-
- /**
- * The vertical angle of the perspective viewing frustum.
- * In radians, between 0 and PI/2. This does not affect the view matrix.
- * The user code can access this value and use it to construct a
- * projection matrix, or it can simply ignore it.
- * @type {number}
- */
- this.fieldOfViewAngle = fieldOfViewAngle;
-
-
- /**
- * Points to a callback to call when the camera changes.
- * @type {function(!o3djs.cameracontroller.CameraController): void}
- */
- this.onChange = opt_onChange || null;
-
- /**
- * The current mouse-drag mode, ie what happens when you move the mouse.
- * @private
- * @type {o3djs.cameracontroller.DragMode}
- */
- this.dragMode_ = o3djs.cameracontroller.DragMode.NONE;
-
- /**
- * The last X coordinate of the mouse.
- * @private
- * @type {number}
- */
- this.mouseX_ = 0;
-
- /**
- * The last Y coordinate of the mouse.
- * @private
- * @type {number}
- */
- this.mouseY_ = 0;
-
-
- // Some variables to control how quickly the camera changes when you
- // move the mouse a certain distance. Feel free to modify these.
- // Mouse pixels are converted into arbitrary "units" (for lack of
- // a better term), and then "units" are converted into an angle,
- // or a distance, etc as the case may be.
-
- /**
- * Controls how quickly the mouse moves the camera (in general).
- * Used to convert pixels into "units".
- * @type {number}
- */
- this.pixelsPerUnit = 300.0;
-
- /**
- * Controls how quickly the mouse affects rotation angles.
- * Used to convert "units" into radians.
- * @type {number}
- */
- this.radiansPerUnit = 1.0;
-
- /**
- * Controls how quickly the mouse affects camera translation.
- * Used to convert "units" into world space units of distance.
- * @type {number}
- */
- this.distancePerUnit = 10.0;
-
- /**
- * Controls how quickly the mouse affects zooming.
- * Used to convert "units" into zoom factor.
- * @type {number}
- */
- this.zoomPerUnit = 1.0;
-};
-
-/**
- * Calculates the center point and backpedal which will make the
- * camera view the entire supplied bounding box, assuming a symmetric
- * perspective projection. The heightAngle and rotationAngle are
- * unchanged.
- * @param {!o3d.BoundingBox} The bounding box to enclose in the view
- * volume.
- * @param {number} aspectRatio The aspect ratio of the viewing plane.
- */
-o3djs.cameracontroller.CameraController.prototype.viewAll =
- function(boundingBox,
- aspectRatio) {
- // Form a view matrix facing in the correct direction but whose
- // origin is at the center of the bounding box
- var minExtent = boundingBox.minExtent;
- var maxExtent = boundingBox.maxExtent;
- var centerPos = o3djs.math.divVectorScalar(
- o3djs.math.addVector(minExtent, maxExtent), 2.0);
- var viewMatrix = this.calculateViewMatrix_(centerPos, 0);
- var maxBackpedal = 0;
- var vertFOV = this.fieldOfViewAngle;
- var tanVertFOV = Math.tan(vertFOV);
- var horizFOV = Math.atan(aspectRatio * tanVertFOV);
- var tanHorizFOV = Math.tan(horizFOV);
- var extents = [minExtent, maxExtent];
- for (var zi = 0; zi < 2; zi++) {
- for (var yi = 0; yi < 2; yi++) {
- for (var xi = 0; xi < 2; xi++) {
- // Form world space vector of this corner
- var vec = [extents[xi][0], extents[yi][1], extents[zi][2], 1];
- // Transform by the temporary view matrix
- vec = o3djs.math.mulVectorMatrix(vec, viewMatrix);
- // Consider only points on the +z side of the origin
- if (vec[2] >= 0.0) {
- // Figure out the backpedal based on the horizontal and
- // vertical view angles, and the z coordinate of the
- // corner
- maxBackpedal = Math.max(maxBackpedal,
- vec[2] + vec[0] / tanHorizFOV);
- maxBackpedal = Math.max(maxBackpedal,
- vec[2] + vec[1] / tanVertFOV);
- }
- }
- }
- }
- // Now set up the center point, backpedal and distancePerUnit
- this.centerPos = centerPos;
- this.backpedal = maxBackpedal;
- // This is heuristic based on some experimentation
- this.distancePerUnit = maxBackpedal / 5.0;
-};
-
-/**
- * Calculates the view matrix for this camera.
- * @return {!o3djs.math.Matrix4} The view matrix.
- */
-o3djs.cameracontroller.CameraController.prototype.calculateViewMatrix =
- function() {
- return this.calculateViewMatrix_(this.centerPos, this.backpedal);
-};
-
-/**
- * Calculates the view matrix for this camera given the specified
- * center point and backpedal.
- * @param {!o3djs.math.Vector3} centerPoint Center point for the
- * camera.
- * @param {number} backpedal Backpedal from the center point for the
- * camera.
- */
-o3djs.cameracontroller.CameraController.prototype.calculateViewMatrix_ =
- function(centerPoint, backpedal) {
- var matrix4 = o3djs.math.matrix4;
- var view = matrix4.translation(o3djs.math.negativeVector(centerPoint));
- view = matrix4.mul(view, matrix4.rotationY(this.rotationAngle));
- view = matrix4.mul(view, matrix4.rotationX(this.heightAngle));
- view = matrix4.mul(view, matrix4.translation([0, 0, -backpedal]));
- return view;
-};
-
-/**
- * Change the current mouse-drag mode, ie what happens when you move the mouse.
- * Usually you would set it to something when a mouse button is pressed down,
- * and then set it to NONE when the button is released.
- * @param {o3djs.cameracontroller.DragMode} dragMode The new DragMode.
- * @param {number} x The current mouse X coordinate.
- * @param {number} y The current mouse Y coordinate.
- */
-o3djs.cameracontroller.CameraController.prototype.setDragMode =
- function(dragMode, x, y) {
- this.dragMode_ = dragMode;
- this.mouseX_ = x;
- this.mouseY_ = y;
-};
-
-/**
- * Method which should be called by end user code upon receiving a
- * mouse-move event.
- * @param {number} x The new mouse X coordinate.
- * @param {number} y The new mouse Y coordinate.
- */
-o3djs.cameracontroller.CameraController.prototype.mouseMoved = function(x, y) {
- var deltaX = (x - this.mouseX_) / this.pixelsPerUnit;
- var deltaY = (y - this.mouseY_) / this.pixelsPerUnit;
- this.mouseX_ = x;
- this.mouseY_ = y;
-
- if (this.dragMode_ == o3djs.cameracontroller.DragMode.SPIN_ABOUT_CENTER) {
- this.rotationAngle += deltaX * this.radiansPerUnit;
- this.heightAngle += deltaY * this.radiansPerUnit;
- }
- if (this.dragMode_ == o3djs.cameracontroller.DragMode.DOLLY_IN_OUT) {
- this.backpedal += deltaY * this.distancePerUnit;
- }
- if (this.dragMode_ == o3djs.cameracontroller.DragMode.ZOOM_IN_OUT) {
- var width = Math.tan(this.fieldOfViewAngle);
- width *= Math.pow(2, deltaY * this.zoomPerUnit);
- this.fieldOfViewAngle = Math.atan(width);
- }
- if (this.dragMode_ == o3djs.cameracontroller.DragMode.DOLLY_ZOOM) {
- if (this.backpedal > 0) {
- var oldWidth = Math.tan(this.fieldOfViewAngle);
- this.fieldOfViewAngle += deltaY * this.radiansPerUnit;
- this.fieldOfViewAngle = Math.min(this.fieldOfViewAngle, 0.98 * Math.PI/2);
- this.fieldOfViewAngle = Math.max(this.fieldOfViewAngle, 0.02 * Math.PI/2);
- var newWidth = Math.tan(this.fieldOfViewAngle);
- this.backpedal *= oldWidth / newWidth;
- }
- }
- if (this.dragMode_ ==
- o3djs.cameracontroller.DragMode.MOVE_CENTER_IN_VIEW_PLANE) {
- var matrix4 = o3djs.math.matrix4;
- var translationVector = [-deltaX * this.distancePerUnit,
- deltaY * this.distancePerUnit, 0];
- var inverseViewMatrix = matrix4.inverse(this.calculateViewMatrix());
- translationVector = matrix4.transformDirection(
- inverseViewMatrix, translationVector);
- this.centerPos = o3djs.math.addVector(this.centerPos, translationVector);
- }
-
- if (this.onChange != null &&
- this.dragMode_ != o3djs.cameracontroller.DragMode.NONE) {
- this.onChange(this);
- }
-};
diff --git a/o3d/samples/o3djs/canvas.js b/o3d/samples/o3djs/canvas.js
deleted file mode 100644
index fce83b4..0000000
--- a/o3d/samples/o3djs/canvas.js
+++ /dev/null
@@ -1,438 +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.
- */
-
-
-/**
- * @fileoverview This file contains a basic utility library that simplifies the
- * creation of simple 2D Canvas surfaces for the purposes of drawing 2D elements
- * in O3D.
- *
- * Example
- *
- * <pre>
- * &lt;html&gt;&lt;body&gt;
- * &lt;script type="text/javascript" src="o3djs/all.js"&gt;
- * &lt;/script&gt;
- * &lt;script&gt;
- * window.onload = init;
- *
- * function init() {
- * o3djs.base.makeClients(initStep2);
- * }
- *
- * function initStep2(clientElements) {
- * var clientElement = clientElements[0];
- * var client = clientElement.client;
- * var pack = client.createPack();
- * var viewInfo = o3djs.rendergraph.createBasicView(
- * pack,
- * client.root,
- * client.renderGraphRoot);
- *
- * // Create an instance of the canvas utility library.
- * var canvasLib = o3djs.canvas.create(
- * pack, client.root, g_viewInfo);
- *
- * // Create a 700x500 rectangle at (x,y,z) = (4, 10, 0)
- * var canvasQuad = canvasLib.createXYQuad(4, 10, 0, 700, 500, false);
- *
- * // Draw into the canvas.
- * canvasQuad.canvas.clear([1, 0, 0, 1]);
- * canvasQuad.canvas.drawText('Hello', 0, 10, canvasPaint);
- * ...
- * ...
- *
- * // Update the o3d texture associated with the canvas.
- * canvasQuad.updateTexture();
- * }
- * &lt;/script&gt;
- * &lt;div id="o3d" style="width: 600px; height: 600px"&gt;&lt;/div&gt;
- * &lt;/body&gt;&lt;/html&gt;
- * </pre>
- *
- */
-
-o3djs.provide('o3djs.canvas');
-
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.primitives');
-
-/**
- * A Module for using a 2d canvas.
- * @namespace
- */
-o3djs.canvas = o3djs.canvas || {};
-
-/**
- * Creates an o3djs.canvas library object through which CanvasQuad objects
- * can be created.
- * @param {!o3d.Pack} pack to manage objects created by this library.
- * @param {!o3d.Transform} root Default root for visual objects.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo A ViewInfo object as
- * created by o3djs.createView which contains draw lists that the created
- * quads will be placed into.
- * @return {!o3djs.canvas.CanvasInfo} A CanvasInfo object containing
- * references to all the common O3D elements used by this instance
- * of the library.
- */
-o3djs.canvas.create = function(pack, root, viewInfo) {
- return new o3djs.canvas.CanvasInfo(pack, root, viewInfo);
-};
-
-/**
- * The shader code used by the canvas quads. It only does two things:
- * 1. Transforms the shape to screen space via the worldViewProjection matrix.
- * 2. Performs a texture lookup to display the contents of the texture
- * bound to texSampler0.
- * @return {string} The shader used canvas quads.
- */
-o3djs.canvas.buildShaderString = function() {
- var p = o3djs.effect;
- var varyingDecls = p.BEGIN_OUT_STRUCT +
- p.VARYING + p.FLOAT4 + ' ' +
- p.VARYING_DECLARATION_PREFIX + 'position' +
- p.semanticSuffix('POSITION') + ';\n' +
- p.VARYING + p.FLOAT2 + ' ' +
- p.VARYING_DECLARATION_PREFIX + 'texCoord' +
- p.semanticSuffix('TEXCOORD0') + ';\n' +
- p.END_STRUCT;
-
- return 'uniform ' + p.MATRIX4 + ' worldViewProjection' +
- p.semanticSuffix('WORLDVIEWPROJECTION') + ';\n\n' +
- p.BEGIN_IN_STRUCT +
- p.ATTRIBUTE + p.FLOAT4 + ' position' +
- p.semanticSuffix('POSITION') + ';\n' +
- p.ATTRIBUTE + p.FLOAT2 + ' texCoord0' +
- p.semanticSuffix('TEXCOORD0') + ';\n' +
- p.END_STRUCT +
- '\n' +
- varyingDecls +
- '\n' +
- p.beginVertexShaderMain() +
- ' ' + p.VERTEX_VARYING_PREFIX + 'position = ' +
- p.mul(p.ATTRIBUTE_PREFIX + 'position',
- 'worldViewProjection') + ';\n' +
- ' ' + p.VERTEX_VARYING_PREFIX + 'texCoord = ' +
- p.ATTRIBUTE_PREFIX + 'texCoord0;\n' +
- p.endVertexShaderMain() +
- '\n' +
- p.pixelShaderHeader() +
- 'uniform ' + p.SAMPLER + ' texSampler0;\n' +
- p.repeatVaryingDecls(varyingDecls) +
- p.beginPixelShaderMain() +
- p.endPixelShaderMain(p.TEXTURE + '2D' +
- '(texSampler0, ' + p.PIXEL_VARYING_PREFIX + 'texCoord)') +
- p.entryPoints() +
- p.matrixLoadOrder();
-};
-
-
-/**
- * The CanvasInfo object creates and keeps references to the O3D objects
- * that are shared between all CanvasQuad objects created through it.
- * @constructor
- * @param {!o3d.Pack} pack Pack to manage CanvasInfo objects.
- * @param {!o3d.Transform} root Default root for visual objects.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo A ViewInfo object as
- * created by o3djs.createView which contains draw lists that the
- * created quads will be placed into.
- */
-o3djs.canvas.CanvasInfo = function(pack, root, viewInfo) {
- /**
- * The pack being used to manage objects created by this CanvasInfo.
- * @type {!o3d.Pack}
- */
- this.pack = pack;
-
- /**
- * The ViewInfo this CanvasInfo uses for rendering.
- * @type {!o3djs.rendergraph.ViewInfo}
- */
- this.viewInfo = viewInfo;
-
- /**
- * The default root for objects created by this CanvasInfo.
- * @type {!o3d.Transform}
- */
- this.root = root;
-
- /**
- * The Effect object shared by all CanvasQuad instances.
- * @type {!o3d.Effect}
- */
- this.effect_ = this.pack.createObject('Effect');
- this.effect_.loadFromFXString(o3djs.canvas.buildShaderString());
-
- /**
- * Material for canvases with transparent content
- * @type {!o3d.Material}
- */
- this.transparentMaterial_ = this.pack.createObject('Material');
-
- /**
- * Material for canvases with opaque content.
- * @type {!o3d.Material}
- */
- this.opaqueMaterial_ = this.pack.createObject('Material');
-
- this.transparentMaterial_.effect = this.effect_;
- this.opaqueMaterial_.effect = this.effect_;
-
- this.transparentMaterial_.drawList = viewInfo.zOrderedDrawList;
- this.opaqueMaterial_.drawList = viewInfo.performanceDrawList;
-
- /**
- * State object to handle the transparency blending mode
- * for transparent canvas quads.
- * The canvas bitmap already multiplies the color values by alpha. In order
- * to avoid a black halo around text drawn on a transparent background we
- * need to set the blending mode as follows.
- * @type {!o3d.State}
- */
- this.transparentState_ = this.pack.createObject('State');
- this.transparentState_.getStateParam('AlphaBlendEnable').value = true;
- this.transparentState_.getStateParam('SourceBlendFunction').value =
- o3djs.base.o3d.State.BLENDFUNC_ONE;
- this.transparentState_.getStateParam('DestinationBlendFunction').value =
- o3djs.base.o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA;
-
- this.transparentMaterial_.state = this.transparentState_;
-
- // Create 2d plane shapes. createPlane makes an XZ plane by default
- // so we pass in matrix to rotate it to an XY plane. We could do
- // all our manipulations in XZ but most people seem to like XY for 2D.
-
- /**
- * A shape for transparent quads.
- * @type {!o3d.Shape}
- */
- this.transparentQuadShape = o3djs.primitives.createPlane(
- this.pack,
- this.transparentMaterial_,
- 1,
- 1,
- 1,
- 1,
- o3djs.math.makeMatrix4(1, 0, 0, 0,
- 0, 0, 1, 0,
- 0, -1, 0 ,0,
- 0, 0, 0, 1));
-
- /**
- * A shape for opaque quads.
- * @type {!o3d.Shape}
- */
- this.opaqueQuadShape = o3djs.primitives.createPlane(
- this.pack,
- this.opaqueMaterial_,
- 1,
- 1,
- 1,
- 1,
- o3djs.math.makeMatrix4(1, 0, 0, 0,
- 0, 0, 1, 0,
- 0, -1, 0 ,0,
- 0, 0, 0, 1));
-};
-/**
- * The CanvasQuad object encapsulates a Transform, a rectangle Shape,
- * an effect that applies a texture to render the quad, and a matching Canvas
- * object that can render into the texture. The dimensions of the texture and
- * the canvas object match those of the quad in order to get pixel-accurate
- * results with the appropriate orthographic projection.
- * The resulting rectangle Shape is positioned at the origin. It can be moved
- * around by setting the localMatrix on the Transform object referenced to by
- * the canvasQuad.transform property.
- * The Canvas associated with the returned CanvasQuad object can be retrieved
- * from the object's 'canvas' property. After issuing any draw commands on the
- * Canvas, you need to call the updateTexture() method on the CanvasQuad to
- * update the contents of the quad surface.
- * @constructor
- * @param {!o3djs.canvas.CanvasInfo} canvasInfo The CanvasInfo object
- * instance creating this CanvasQuad.
- * @param {number} width The width of the quad.
- * @param {number} height The height of the quad.
- * @param {boolean} transparent Set to true if the canvas will
- * be transparent so that the appropriate blending modes are set.
- * @param {!o3d.Transform} opt_parent parent transform to parent
- * the newly created quad under. If no parent transform is provided then
- * the quad gets parented under the CanvasInfo's root.
- */
-o3djs.canvas.CanvasQuad = function(canvasInfo,
- width,
- height,
- transparent,
- opt_parent) {
- /**
- * The CanvasInfo managing this CanvasQuad
- * @type {!o3djs.canvas.CanvasInfo}
- */
- this.canvasInfo = canvasInfo;
- var parentTransform = opt_parent || canvasInfo.root;
-
- // create a transform for positioning
-
- /**
- * A transform for this quad.
- * @type {!o3d.Transform}
- */
- this.transform = canvasInfo.pack.createObject('Transform');
- this.transform.parent = parentTransform;
-
- // create a transform for scaling to the size of the image just so
- // we don't have to manage that manually in the transform above.
-
- /**
- * A scale transform for this quad.
- * You can change the scale the quad without effecting its positon using
- * this transform.
- * @type {!o3d.Transform}
- */
- this.scaleTransform = canvasInfo.pack.createObject('Transform');
- this.scaleTransform.parent = this.transform;
-
- /**
- * The texture the canvas will draw on.
- * @type {!o3d.Texture2D}
- */
- this.texture = /** @type {!o3d.Texture2D} */ (canvasInfo.pack.createTexture2D(
- width,
- height,
- o3djs.base.o3d.Texture.ARGB8,
- 1, // mipmap levels
- false));
-
- // Create a Canvas object to go with the quad.
-
- /**
- * The Canvas object used to draw on this quad.
- * @type {!o3d.Canvas}
- */
- this.canvas = canvasInfo.pack.createObject('Canvas');
- this.canvas.setSize(width, height);
-
- /**
- * The sampler for the texture.
- * @type {!o3d.Sampler}
- */
- this.sampler = canvasInfo.pack.createObject('Sampler');
- this.sampler.addressModeU = o3djs.base.o3d.Sampler.CLAMP;
- this.sampler.addressModeV = o3djs.base.o3d.Sampler.CLAMP;
-
- /**
- * The param sampler for this transform.
- * @private
- * @type {!o3d.ParamSampler}
- */
- this.paramSampler_ = this.scaleTransform.createParam('texSampler0',
- 'ParamSampler');
- this.paramSampler_.value = this.sampler;
-
- this.sampler.texture = this.texture;
- if (transparent) {
- this.scaleTransform.addShape(canvasInfo.transparentQuadShape);
- } else {
- this.scaleTransform.addShape(canvasInfo.opaqueQuadShape);
- }
- this.scaleTransform.translate(width / 2, height / 2, 0);
- this.scaleTransform.scale(width, -height, 1);
-};
-
-/**
- * Copies the current contents of the Canvas object to the texture associated
- * with the quad. This method should be called after any new draw calls have
- * been issued to the CanvasQuad's Canvas object.
- */
-o3djs.canvas.CanvasQuad.prototype.updateTexture = function() {
- var width = this.texture.width;
- var height = this.texture.height;
- this.texture.drawImage(this.canvas, 0, height - 1, width, -height,
- 0, 0, 0, width, height);
-};
-
-/**
- * Creates a CanvasQuad object on the XY plane at the specified position.
- * @param {number} topX The x coordinate of the top left corner of the quad.
- * @param {number} topY The y coordinate of the top left corner of the quad.
- * @param {number} z The z coordinate of the quad. z values are negative
- * numbers, the smaller the number the further back the quad will be.
- * @param {number} width The width of the quad.
- * @param {number} height The height of the quad.
- * @param {boolean} transparent Set to true if the canvas bitmap uses
- * transparency so that the appropriate blending modes are set.
- * @param {!o3d.Transform} opt_parent parent transform to parent the newly
- * created quad under. If no parent transform is provided then the quad
- * gets parented under the CanvasInfo's root.
- * @return {!o3djs.canvas.CanvasQuad} The newly created CanvasQuad object.
- */
-o3djs.canvas.CanvasInfo.prototype.createXYQuad = function(topX,
- topY,
- z,
- width,
- height,
- transparent,
- opt_parent) {
- var canvasQuad = new o3djs.canvas.CanvasQuad(this,
- width,
- height,
- transparent,
- opt_parent);
-
- canvasQuad.transform.translate(topX, topY, z);
- return canvasQuad;
-};
-
-/**
- * Creates a CanvasQuad object of the given size. The resulting rectangle Shape
- * is centered at the origin. It can be moved around by setting the
- * localMatrix on the Transform object referenced to by the canvasQuad.transform
- * property.
- * @param {number} width The width of the quad.
- * @param {number} height The height of the quad.
- * @param {boolean} transparent Set to true if the canvas bitmap uses
- * transparency so that the appropriate blending modes are set.
- * @param {!o3d.Transform} opt_parent parent transform to parent the newly
- * created quad under. If no parent transform is provided then the quad
- * gets parented under the CanvasInfo's root.
- * @return {!o3djs.canvas.CanvasQuad} The newly created CanvasQuad object.
- */
-o3djs.canvas.CanvasInfo.prototype.createQuad = function(width,
- height,
- transparent,
- opt_parent) {
- return new o3djs.canvas.CanvasQuad(this,
- width,
- height,
- transparent,
- opt_parent);
-};
-
-
diff --git a/o3d/samples/o3djs/debug.js b/o3d/samples/o3djs/debug.js
deleted file mode 100644
index f646d90..0000000
--- a/o3d/samples/o3djs/debug.js
+++ /dev/null
@@ -1,1031 +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.
- */
-
-
-/**
- * @fileoverview This file contains various functions to help debug for o3d
- * applications.
- *
- * Note: This library is only a sample. It is not meant to be some official
- * library. It is provided only as example code.
- *
- */
-
-o3djs.provide('o3djs.debug');
-
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.lineprimitives');
-
-var O3D_DEBUG_PREFIX = 'o3dDebug_';
-var O3D_DEBUG_PREFIX_LENGTH = O3D_DEBUG_PREFIX.length;
-var O3D_DEBUG_COLOR_PARAM_NAME = O3D_DEBUG_PREFIX + 'Color';
-var O3D_DEBUG_VECTOR_SCALE_PARAM_NAME =
- O3D_DEBUG_PREFIX + 'VectorScale';
-var O3D_DEBUG_AXIS_SHAPE_NAME = O3D_DEBUG_PREFIX + 'AxisShape';
-var O3D_DEBUG_LINE_SHAPE_NAME = O3D_DEBUG_PREFIX + 'LineShape';
-var O3D_DEBUG_SPHERE_SHAPE_NAME = O3D_DEBUG_PREFIX + 'SphereShape';
-var O3D_DEBUG_CUBE_SHAPE_NAME = O3D_DEBUG_PREFIX + 'CubeShape';
-
-var O3D_DEBUG_AXIS_INFO_ = [
- {offset: [1, 0, 0], color: [1, 0, 0, 1]},
- {offset: [0, 1, 0], color: [0, 1, 0, 1]},
- {offset: [0, 0, 1], color: [0, 0, 1, 1]}];
-
-/**
- * Checks whether or not a transform is a debug transform.
- * @param {!o3d.Transform} transform Transform to check.
- * @return {boolean} true if this transform is a debug transform.
- */
-o3djs.debug.isDebugTransform = function(transform) {
- var name = transform.name;
- var isDT =
- name.length >= O3D_DEBUG_PREFIX_LENGTH &&
- name.substr(0, O3D_DEBUG_PREFIX_LENGTH) == O3D_DEBUG_PREFIX;
- return isDT;
-};
-
-/**
- * Gets the debug transform.
- * @private
- * @param {!o3d.Transform} transform Transform to get debug Transform
- * from.
- * @param {string} name Name of debug transform to get.
- * @return {o3d.Transform} Debug Transform or null if not found.
- */
-o3djs.debug.getDebugTransform_ = function(transform, name) {
- if (transform.name == name) {
- return transform;
- } else {
- var children = transform.children;
- for (var cc = 0; cc < children.length; ++cc) {
- if (children[cc].name == name) {
- return children[cc];
- }
- }
- }
- return null;
-};
-
-/**
- * Creates shaders that output the constant color from a parameter.
- * @private
- * @param {string} colorParamName Name of color parameter to use.
- * @return {string} Shader string.
- */
-o3djs.debug.createColorShaders_ = function(colorParamName) {
- var p = o3djs.effect;
- var shaders =
- 'uniform ' + p.MATRIX4 + ' worldViewProjection' +
- p.semanticSuffix('WORLDVIEWPROJECTION') + ';\n' +
- p.BEGIN_IN_STRUCT +
- p.ATTRIBUTE + p.FLOAT4 + ' position' +
- p.semanticSuffix('POSITION') + ';\n' +
- p.END_STRUCT +
- p.BEGIN_OUT_STRUCT +
- p.VARYING + p.FLOAT4 + ' ' + p.VARYING_DECLARATION_PREFIX + 'position' +
- p.semanticSuffix('POSITION') + ';\n' +
- p.END_STRUCT +
- p.beginVertexShaderMain() +
- ' ' + p.VERTEX_VARYING_PREFIX + 'position = ' +
- p.mul(p.ATTRIBUTE_PREFIX + 'position', 'worldViewProjection')
- + ';\n' +
- p.endVertexShaderMain() +
- p.pixelShaderHeader() +
- 'uniform ' + p.FLOAT4 + ' ' + colorParamName + ';\n' +
- p.beginPixelShaderMain() +
- p.endPixelShaderMain(colorParamName) +
- p.entryPoints() +
- p.matrixLoadOrder();
- return shaders;
-};
-
-/**
- * Creates shaders that output the constant color from a parameter and scale
- * the vertices in object space.
- * @private
- * @param {string} colorParamName Name of color parameter to use.
- * @param {string} scaleParamName Name of scale parameter to use.
- * @return {string} Shader string.
- */
-o3djs.debug.createScaleShaders_ = function(colorParamName, scaleParamName) {
- var p = o3djs.effect;
- var shaders =
- 'uniform ' + p.FLOAT3 + ' ' + scaleParamName + ';\n' +
- 'uniform ' + p.MATRIX4 + ' worldViewProjection' +
- p.semanticSuffix('WORLDVIEWPROJECTION') + ';\n' +
- p.BEGIN_IN_STRUCT +
- p.ATTRIBUTE + p.FLOAT4 + ' position' + p.semanticSuffix('POSITION') +
- ';\n' +
- p.END_STRUCT +
- p.BEGIN_OUT_STRUCT +
- p.VARYING + p.FLOAT4 + ' ' + p.VARYING_DECLARATION_PREFIX + 'position' +
- p.semanticSuffix('POSITION') + ';\n' +
- p.END_STRUCT +
- p.beginVertexShaderMain() +
- ' ' + p.FLOAT4 + ' position = ' + p.FLOAT4 + '(\n' +
- ' ' + p.ATTRIBUTE_PREFIX + 'position.x * ' + scaleParamName + '.x,\n' +
- ' ' + p.ATTRIBUTE_PREFIX + 'position.y * ' + scaleParamName + '.y,\n' +
- ' ' + p.ATTRIBUTE_PREFIX + 'position.z * ' + scaleParamName + '.z,\n' +
- ' 1);\n' +
- ' ' + p.VERTEX_VARYING_PREFIX + 'position = ' +
- p.mul('position', 'worldViewProjection') + ';\n' +
- p.endVertexShaderMain() +
- p.pixelShaderHeader() +
- 'uniform ' + p.FLOAT4 + ' ' + colorParamName + ';\n' +
- p.beginPixelShaderMain() +
- p.endPixelShaderMain(colorParamName) +
- p.entryPoints() +
- p.matrixLoadOrder();
- return shaders;
-};
-
-
-/**
- * Defines a namespace for o3djs.debug.
- * @namespace
- */
-o3djs.debug = o3djs.debug || {};
-
-/**
- * An object to manage a single debug line.
- * @constructor
- * @param {!o3djs.debug.DebugLineGroup} debugLineGroup DebugLineGroup
- * this line belongs too.
- */
-o3djs.debug.DebugLine = function(debugLineGroup) {
- /**
- * The DebugLineGroup this DebugLine is managed by.
- * @private
- * @type {!o3djs.debug.DebugLineGroup}
- */
- this.debugLineGroup_ = debugLineGroup;
- var pack = debugLineGroup.getPack();
-
- /**
- * The transform for this DebugLine.
- * @private
- * @type {!o3d.Transform}
- */
- this.transform_ = pack.createObject('Transform');
- this.transform_.name = O3D_DEBUG_LINE_SHAPE_NAME;
- this.transform_.addShape(debugLineGroup.getLineShape());
-
- /**
- * The start position of the line.
- * @private
- * @type {!o3djs.math.Vector3}
- */
- this.start_ = [0, 0, 0];
-
- /**
- * The start position of the line.
- * @private
- * @type {!o3djs.math.Vector3}
- */
- this.end_ = [0, 0, 0];
-
- /**
- * The color param for the line.
- * @private
- * @type {!o3d.ParamFloat4}
- */
- this.colorParam_ = this.transform_.createParam(
- O3D_DEBUG_COLOR_PARAM_NAME, 'ParamFloat4');
- this.colorParam_.value = debugLineGroup.getColor();
-};
-
-/**
- * Destroys this line object cleaning up the resources used by it.
- */
-o3djs.debug.DebugLine.prototype.destroy = function() {
- this.transform_.parent = null;
- this.debugLineGroup_.getPack().removeObject(this.transform_);
-};
-
-/**
- * Returns a unique Id for the line.
- * @return {number} the Id of the line.
- */
-o3djs.debug.DebugLine.prototype.getId = function() {
- return this.transform_.clientId;
-};
-
-/**
- * Updates the line with the current start and end settings.
- * @private
- */
-o3djs.debug.DebugLine.prototype.update_ = function() {
- var math = o3djs.math;
- var vector = math.subVector(this.end_, this.start_);
- var direction = math.normalize(vector);
- var dot = math.dot(direction, [0, 1, 0]);
- var perp1;
- var perp2;
- if (dot > 0.99) {
- perp2 = math.cross([1, 0, 0], direction);
- perp1 = math.cross(perp2, direction);
- } else {
- perp1 = math.cross([0, 1, 0], direction);
- perp2 = math.cross(perp1, direction);
- }
- this.transform_.localMatrix =
- o3djs.math.makeMatrix4(perp2[0], perp2[1], perp2[2], 0,
- direction[0], direction[1], direction[2], 0,
- perp1[0], perp1[1], perp1[2], 0,
- this.start_[0], this.start_[1], this.start_[2], 1);
- this.transform_.scale(1, math.length(vector), 1);
-};
-
-/**
- * Sets the end points of the DebugLine.
- * @param {!o3djs.math.Vector3} start Start point for line.
- * @param {!o3djs.math.Vector3} end End point for line.
- */
-o3djs.debug.DebugLine.prototype.setEndPoints = function(start, end) {
- this.start_ = start;
- this.end_ = end;
- this.update_();
-};
-
-/**
- * Sets the start point of the DebugLine.
- * @param {!o3djs.math.Vector3} start Start point for line.
- */
- o3djs.debug.DebugLine.prototype.setStart = function(start) {
- this.start_ = start;
- this.update_();
-};
-
-/**
- * Sets the end point of the DebugLine.
- * @param {!o3djs.math.Vector3} end End point for line.
- */
-o3djs.debug.DebugLine.prototype.setEnd = function(end) {
- this.end_ = end;
- this.update_();
-};
-
-/**
- * Sets the color of the DebugLine.
- * @param {!o3djs.math.Vector4} color The color of the debug line.
- */
-o3djs.debug.DebugLine.prototype.setColor = function(color) {
- this.colorParam_.value = color;
-};
-
-/**
- * Sets the visibility of the DebugLine.
- * @param {boolean} visible True = visible.
- */
-o3djs.debug.DebugLine.prototype.setVisible = function(visible) {
- this.transform_.parent = visible ? this.debugLineGroup_.getRoot() : null;
-};
-
-/**
- * Removes this line.
- */
-o3djs.debug.DebugLine.prototype.remove = function() {
- this.transform_.parent = null;
- this.debugLineGroup_.remove(this);
-};
-
-/**
- * An object to manage debug lines.
- * @constructor
- * @param {!o3djs.debug.DebugHelper} debugHelper The DebugHelper
- * associated with this object.
- * @param {!o3d.Transform} root Transform to put debug lines under.
- */
-o3djs.debug.DebugLineGroup = function(debugHelper, root) {
- /**
- * The default color to make new lines.
- * @private
- * @type {!o3djs.math.Vector4}
- */
- this.currentColor_ = [1, 1, 1, 1];
-
- /**
- * The lines in this group indexed by clientId.
- * @private
- * @type {!Object.<number, !o3djs.debug.DebugLine>}
- */
- this.lineTransforms_ = { };
-
- /**
- * The unused lines in this group indexed by clientId.
- * @private
- * @type {!Object.<number, !o3djs.debug.DebugLine>}
- */
- this.freeLineTransforms_ = { };
-
- /**
- * The DebugHelper managing this DebugLineGroup.
- * @private
- * @type {!o3djs.debug.DebugHelper}
- */
- this.debugHelper_ = debugHelper;
-
- /**
- * The root transform for lines in this group.
- * @private
- * @type {!o3d.Transform}
- */
- this.root_ = root;
-};
-
-/**
- * Gets the root transform for this line group.
- * @return {!o3d.Transform} The root transform for this line group.
- */
-o3djs.debug.DebugLineGroup.prototype.getRoot = function() {
- return this.root_;
-};
-
-/**
- * Gets the pack for this line group.
- * @return {!o3d.Pack} The pack for this line group.
- */
-o3djs.debug.DebugLineGroup.prototype.getPack = function() {
- return this.debugHelper_.getPack();
-};
-
-/**
- * Gets the shape for lines.
- * @return {!o3d.Shape} The shape for lines.
- */
-o3djs.debug.DebugLineGroup.prototype.getLineShape = function() {
- return this.debugHelper_.getLineShape();
-};
-
-/**
- * Gets the current color for this line group.
- * @return {!o3djs.math.Vector4} The current color.
- */
-o3djs.debug.DebugLineGroup.prototype.getColor = function() {
- return this.currentColor_;
-};
-
-/**
- * Sets the current color for this line group. All lines added after
- * setting this will be this color by default.
- * @param {!o3djs.math.Vector4} color The color for this line group.
- */
-o3djs.debug.DebugLineGroup.prototype.setColor = function(color) {
- this.currentColor_ = color;
-};
-
-/**
- * Gets a debug line. If none exist creates a new one.
- * @private
- * @return {!o3djs.debug.DebugLine} The DebugLine.
- */
-o3djs.debug.DebugLineGroup.prototype.getLine_ = function() {
- for (var sid in this.freeLineTransforms_) {
- var id = /** @type {number} */ (sid);
- var line = this.freeLineTransforms_[id];
- delete this.freeLineTransforms_[id];
- return line;
- }
- return new o3djs.debug.DebugLine(this);
-};
-
-/**
- * Adds a debug line.
- * @param {!o3djs.math.Vector3} opt_start Start position for line.
- * @param {!o3djs.math.Vector3} opt_end End position for line.
- * @param {!o3djs.math.Vector4} opt_color Color for line.
- * @return {!o3djs.debug.DebugLine} The DebugLine.
- */
-o3djs.debug.DebugLineGroup.prototype.addLine = function(opt_start,
- opt_end,
- opt_color) {
- var line = this.getLine_();
- line.setEndPoints(opt_start || [0, 0, 0], opt_end || [0, 0, 0]);
- line.setColor(opt_color || this.currentColor_);
- line.setVisible(true);
- this.lineTransforms_[line.getId()] = line;
- return line;
-};
-
-/**
- * Clears all the lines in this group.
- */
-o3djs.debug.DebugLineGroup.prototype.clear = function() {
- for (var sid in this.lineTransforms_) {
- var id = /** @type {number} */ (sid);
- var line = this.lineTransforms_[id];
- line.setVisible(false);
- this.freeLineTransforms_[id] = line;
- }
- this.lineTransforms_ = { };
-};
-
-/**
- * Destroys a DeubgLineGroup, freeing all its lines and resources.
- */
-o3djs.debug.DebugLineGroup.prototype.destroy = function() {
- this.clear();
- for (var sid in this.freeLineTransforms_) {
- var id = /** @type {number} */ (sid);
- this.freeLineTransforms_[id].destroy();
- }
- this.freeLineTransforms_ = { };
-};
-
-/**
- * Removes a line.
- * @param {!o3djs.debug.DebugLine} line Line to remove.
- */
-o3djs.debug.DebugLineGroup.prototype.remove = function(line) {
- var id = line.getId();
- delete this.lineTransforms_[id];
- this.freeLineTransforms_[id] = line;
-};
-
-/**
- * A Debug object to help with debugging o3d apps.
- *
- * A debug helper object provides functions to help debug your o3d
- * application and manages the resources needed to do that for you. For
- * example it can add axes, spheres and boxes to your transforms as well as
- * draw lines in 3d space given 2 points.
- *
- * @constructor
- * @param {!o3d.Pack} pack Pack for this debug object to use to manage
- * its resources.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo ViewInfo for debug
- * visuals.
- */
-o3djs.debug.DebugHelper = function(pack, viewInfo) {
- this.pack_ = pack;
- this.viewInfo_ = viewInfo;
- this.axisPrimitives_ = [];
- this.axisShape_ = pack.createObject('Shape');
- this.axisShape_.name = O3D_DEBUG_AXIS_SHAPE_NAME;
- this.lineShape_ = pack.createObject('Shape');
- this.lineShape_.name = O3D_DEBUG_LINE_SHAPE_NAME;
-
- // Setup shape, material, primitive for axes.
- {
- // create a simple material for the axis.
- var effect = pack.createObject('Effect');
- var shaders = o3djs.debug.createScaleShaders_(
- O3D_DEBUG_COLOR_PARAM_NAME,
- O3D_DEBUG_VECTOR_SCALE_PARAM_NAME);
- effect.loadFromFXString(shaders);
- var material = pack.createObject('Material');
- material.effect = effect;
- material.drawList = viewInfo.performanceDrawList;
- effect.createUniformParameters(material);
-
- // Set the default color to white.
- material.getParam(O3D_DEBUG_COLOR_PARAM_NAME).value = [1, 1, 1, 1];
-
- // Set the default scale.
- material.getParam(O3D_DEBUG_VECTOR_SCALE_PARAM_NAME).value =
- [1, 1, 1];
-
- // Create the axis shape.
- for (var ii = 0; ii < O3D_DEBUG_AXIS_INFO_.length; ++ii) {
- var info = O3D_DEBUG_AXIS_INFO_[ii];
- var cubeShape = o3djs.primitives.createCube(
- pack,
- material,
- 1,
- o3djs.math.makeMatrix4(1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 1, 0,
- info.offset[0] * 0.5,
- info.offset[1] * 0.5,
- info.offset[2] * 0.5,
- 1));
-
- var cube = cubeShape.elements[0];
- cube.owner = this.axisShape_;
- pack.removeObject(cubeShape);
- cube.createParam(O3D_DEBUG_COLOR_PARAM_NAME, 'ParamFloat4').value =
- info.color;
- cube.createParam(O3D_DEBUG_VECTOR_SCALE_PARAM_NAME, 'ParamFloat3');
- this.axisPrimitives_[ii] = cube;
- }
-
- this.axisMaterial_ = material;
- this.setAxisScale(10, 1);
- }
-
- // Setup shape, material, primitive for debug lines.
- {
- // create a simple material for the debug lines.
- var effect = pack.createObject('Effect');
- var shaders = o3djs.debug.createColorShaders_(O3D_DEBUG_COLOR_PARAM_NAME);
- effect.loadFromFXString(shaders);
- var material = pack.createObject('Material');
- material.effect = effect;
- material.drawList = viewInfo.performanceDrawList;
- effect.createUniformParameters(material);
-
- // Set the default color to white.
- material.getParam(O3D_DEBUG_COLOR_PARAM_NAME).value = [1, 1, 1, 1];
-
- // Create the debug line shape.
- var vertices = [0, 0, 0, 0, 1, 0];
- var streamBank = pack.createObject('StreamBank');
- var primitive = pack.createObject('Primitive');
- var shape = pack.createObject('Shape');
- var vertexBuffer = pack.createObject('VertexBuffer');
- var positionField = vertexBuffer.createField('FloatField', 3);
- vertexBuffer.set(vertices);
- primitive.owner = shape;
- primitive.createDrawElement(pack, null);
- primitive.streamBank = streamBank;
- primitive.material = material;
- primitive.numberVertices = 2;
- primitive.numberPrimitives = 1;
- primitive.primitiveType = o3djs.base.o3d.Primitive.LINELIST;
- streamBank.setVertexStream(o3djs.base.o3d.Stream.POSITION,
- 0,
- positionField,
- 0);
- this.lineShape_ = shape;
- this.lineShape_.name = O3D_DEBUG_LINE_SHAPE_NAME;
- this.lineMaterial_ = material;
- }
-
- {
- this.sphereShape_ = o3djs.lineprimitives.createLineSphere(
- pack,
- this.axisMaterial_,
- 0.5, 8, 8);
- this.sphereShape_.name = O3D_DEBUG_SPHERE_SHAPE_NAME;
- var primitive = this.sphereShape_.elements[0];
- this.sphereScaleParam_ = primitive.createParam(
- O3D_DEBUG_VECTOR_SCALE_PARAM_NAME,
- 'ParamFloat3').value = [1, 1, 1];
- }
-
- {
- this.cubeShape_ = o3djs.lineprimitives.createLineCube(
- pack,
- this.axisMaterial_,
- 1);
- this.cubeShape_.name = O3D_DEBUG_CUBE_SHAPE_NAME;
- var primitive = this.cubeShape_.elements[0];
- this.cubeScaleParam_ = primitive.createParam(
- O3D_DEBUG_VECTOR_SCALE_PARAM_NAME,
- 'ParamFloat3').value = [1, 1, 1];
- }
-};
-
-
-/**
- * Gets the pack for this DebugHelper.
- * @return {!o3d.Pack} The pack for this DebugHelper.
- */
-o3djs.debug.DebugHelper.prototype.getPack = function() {
- return this.pack_;
-};
-
-/**
- * Gets the line shape.
- * @return {!o3d.Shape} The shape for debug lines.
- */
-o3djs.debug.DebugHelper.prototype.getLineShape = function() {
- return this.lineShape_;
-};
-
-/**
- * Sets the length and width of the axis lines.
- * @param {number} length Length of an axis in the direction of the axis.
- * @param {number} width Width of the axis or its thickness.
- */
-o3djs.debug.DebugHelper.prototype.setAxisScale = function(length,
- width) {
- for (var ii = 0; ii < O3D_DEBUG_AXIS_INFO_.length; ++ii) {
- var info = O3D_DEBUG_AXIS_INFO_[ii];
- this.axisPrimitives_[ii].getParam(
- O3D_DEBUG_VECTOR_SCALE_PARAM_NAME).value = [
- info.offset[0] ? length : width,
- info.offset[1] ? length : width,
- info.offset[2] ? length : width];
- }
-};
-
-/**
- * Creates a debug shape at a world position.
- * @private
- * @param {!o3djs.math.Vector3} position Position at which to create shape.
- * @param {!o3d.Shape} shape Shape to add to transform.
- * @return {!o3d.Transform} transform for shape.
- */
-o3djs.debug.DebugHelper.prototype.createShape_ = function(position, shape) {
-
- var debugTransform = this.getPack().createObject('Transform');
- debugTransform.name = shape.name;
- debugTransform.addShape(shape);
- debugTransform.parent = this.viewInfo_.treeRoot;
- debugTransform.translate(position);
- return debugTransform;
-};
-
-/**
- * Adds an debug shape to a transform.
- * @private
- * @param {!o3d.Transform} transform Transform to add shape to.
- * @param {!o3d.Shape} shape Shape to add to transform.
- */
-o3djs.debug.DebugHelper.prototype.addShape_ = function(transform,
- shape) {
-
- var debugTransform = o3djs.debug.getDebugTransform_(transform, shape.name);
- if (!debugTransform) {
- var debugTransform = this.getPack().createObject('Transform');
- debugTransform.name = shape.name;
- debugTransform.addShape(shape);
- debugTransform.parent = transform;
- }
-};
-
-/**
- * Removes a debug shape from a transform
- * @private
- * @param {!o3d.Transform} transform Transform to remove shape from.
- * @param {!o3d.Shape} shape Shape to remove from transform.
- */
-o3djs.debug.DebugHelper.prototype.removeShape_ = function(transform,
- shape) {
- var name = shape.name;
- var debugTransform = o3djs.debug.getDebugTransform_(transform, shape.name);
- if (debugTransform) {
- debugTransform.parent = null;
- this.getPack().removeObject(debugTransform);
- }
-};
-
-/**
- * Adds a debug shape to all transform a tree.
- * @private
- * @param {!o3d.Transform} treeRoot root of tree to add shape to.
- * @param {!o3d.Shape} shape Shape to add to transforms.
- */
-o3djs.debug.DebugHelper.prototype.addShapes_ = function(treeRoot,
- shape) {
- this.addShape_(treeRoot, shape);
- var children = treeRoot.children;
- for (var cc = 0; cc < children.length; ++cc) {
- var child = children[cc];
- if (!o3djs.debug.isDebugTransform(child)) {
- this.addShapes_(child, shape);
- }
- }
-};
-
-/**
- * Removes a debug shape from all transforms in a tree.
- * @private
- * @param {!o3d.Transform} treeRoot root of tree to remove axes from.
- * @param {!o3d.Shape} shape Shape to remove from transforms.
- */
-o3djs.debug.DebugHelper.prototype.removeShapes_ = function(treeRoot,
- shape) {
- this.removeShape_(treeRoot, shape);
- var children = treeRoot.children;
- for (var cc = 0; cc < children.length; ++cc) {
- var child = children[cc];
- if (!o3djs.debug.isDebugTransform(child)) {
- this.removeShapes_(child, shape);
- }
- }
-};
-
-/**
- * Sets a param value on a debug transform. If the param does not exist it
- * will be created.
- * @private
- * @param {!o3d.Transform} transform Transform on which debug transform
- * exists.
- * @param {string} name Name of debug transform.
- * @param {string} paramName Name of param to set.
- * @param {string} paramType type of param to set.
- * @param {*} paramValue value to set param.
- */
-o3djs.debug.DebugHelper.prototype.addSetDebugTransformParam_ = function(
- transform,
- name,
- paramName,
- paramType,
- paramValue) {
- var debugTransform = o3djs.debug.getDebugTransform_(transform, name);
- if (debugTransform) {
- var param = debugTransform.getParam(paramName);
- if (!param) {
- param = debugTransform.createParam(paramName, paramType);
- }
- param.value = paramValue;
- }
-};
-
-/**
- * Adds an axis to a transform.
- * @param {!o3d.Transform} transform Transform to add axis to.
- */
-o3djs.debug.DebugHelper.prototype.addAxis = function(transform) {
- this.addShape_(transform, this.axisShape_);
-};
-
-/**
- * Removes an axis from a transform
- * @param {!o3d.Transform} transform Transform to remove axis from.
- */
-o3djs.debug.DebugHelper.prototype.removeAxis = function(transform) {
- this.removeShape_(transform, this.axisShape_);
-};
-
-/**
- * Adds axes to all transform in a tree.
- * @param {!o3d.Transform} treeRoot root of tree to add axes to.
- */
-o3djs.debug.DebugHelper.prototype.addAxes = function(treeRoot) {
- this.addShapes_(treeRoot, this.axisShape_);
-};
-
-/**
- * Removes axes from all transforms in a tree.
- * @param {!o3d.Transform} treeRoot root of tree to remove axes from.
- */
-o3djs.debug.DebugHelper.prototype.removeAxes = function(treeRoot) {
- this.removeShapes_(treeRoot, this.axisShape_);
-};
-
-/**
- * Set axis color.
- * @param {!o3d.Transform} transform Transform on which to change axis
- * color.
- * @param {!o3djs.math.Vector4} color 4 number array in RGBA format.
- */
-o3djs.debug.DebugHelper.prototype.setAxisColor = function(transform,
- color) {
- this.addSetDebugTransformParam_(transform,
- O3D_DEBUG_AXIS_SHAPE_NAME,
- O3D_DEBUG_COLOR_PARAM_NAME,
- 'ParamFloat4',
- color);
-};
-
-/**
- * Removes the color from an axis.
- * @param {!o3d.Transform} transform Transform on which to remove color.
- */
-o3djs.debug.DebugHelper.prototype.clearAxisColor = function(transform) {
- var debugTransform = o3djs.debug.getDebugTransform_(
- transform,
- O3D_DEBUG_AXIS_SHAPE_NAME);
- if (debugTransform) {
- var colorParam = debugTransform.getParam(O3D_DEBUG_COLOR_PARAM_NAME);
- if (colorParam) {
- debugTransform.removeParam(colorParam);
- }
- }
-};
-
-/**
- * Creates a sphere in world space.
- * @param {!o3djs.math.Vector3} position Position at which to create sphere.
- * @param {!o3djs.math.Vector4} opt_color RGBA color for sphere.
- * @param {number} opt_scale of sphere.
- * @return {!o3d.Transform} transform for sphere.
- */
-o3djs.debug.DebugHelper.prototype.createSphere = function(position,
- opt_color,
- opt_scale) {
- var transform = this.createShape_(position, this.sphereShape_);
- if (opt_color) {
- this.setSphereColor(transform, opt_color);
- }
- if (opt_scale) {
- this.setSphereScale(transform, opt_scale);
- }
- return transform;
-};
-
-/**
- * Adds a sphere to a transform.
- * @param {!o3d.Transform} transform Transform to add sphere to.
- * @param {!o3djs.math.Vector4} opt_color RGBA color for sphere.
- * @param {number} opt_scale of sphere.
- */
-o3djs.debug.DebugHelper.prototype.addSphere = function(transform,
- opt_color,
- opt_scale) {
- this.addShape_(transform, this.sphereShape_);
- if (opt_color) {
- this.setSphereColor(transform, opt_color);
- }
- if (opt_scale) {
- this.setSphereScale(transform, opt_scale);
- }
-};
-
-/**
- * Removes a sphere from a transform
- * @param {!o3d.Transform} transform Transform to remove sphere from.
- */
-o3djs.debug.DebugHelper.prototype.removeSphere = function(transform) {
- this.removeShape_(transform, this.sphereShape_);
-};
-
-/**
- * Adds spheres to all transform a tree.
- * @param {!o3d.Transform} treeRoot root of tree to add spheres to.
- */
-o3djs.debug.DebugHelper.prototype.addSpheres = function(treeRoot) {
- this.addShapes_(treeRoot, this.sphereShape_);
-};
-
-/**
- * Removes spheres from all transforms in a tree.
- * @param {!o3d.Transform} treeRoot root of tree to remove spheres from.
- */
-o3djs.debug.DebugHelper.prototype.removeSpheres = function(treeRoot) {
- this.removeShapes_(treeRoot, this.sphereShape_);
-};
-
-/**
- * Set sphere color.
- * @param {!o3d.Transform} transform Transform on which to change sphere
- * color.
- * @param {!o3djs.math.Vector4} color 4 number array in RGBA format.
- */
-o3djs.debug.DebugHelper.prototype.setSphereColor = function(transform,
- color) {
- this.addSetDebugTransformParam_(transform,
- O3D_DEBUG_SPHERE_SHAPE_NAME,
- O3D_DEBUG_COLOR_PARAM_NAME,
- 'ParamFloat4',
- color);
-};
-
-/**
- * Sets the scale of a debug sphere.
- * @param {!o3d.Transform} transform Transform on which to change sphere
- * scale.
- * @param {number} scale Scale to make the sphere.
- */
-o3djs.debug.DebugHelper.prototype.setSphereScale = function(transform,
- scale) {
- this.addSetDebugTransformParam_(transform,
- O3D_DEBUG_SPHERE_SHAPE_NAME,
- O3D_DEBUG_VECTOR_SCALE_PARAM_NAME,
- 'ParamFloat3',
- [scale, scale, scale]);
-};
-
-/**
- * Creates a cube at a world position..
- * @param {!o3djs.math.Vector3} position Position at which to create sphere.
- * @param {!o3djs.math.Vector4} opt_color RGBA color for cube.
- * @param {number} opt_scale of cube.
- * @return {!o3d.Transform} transform for cube.
- */
-o3djs.debug.DebugHelper.prototype.createCube = function(position,
- opt_color,
- opt_scale) {
- var transform = this.createShape_(position, this.cubeShape_);
- if (opt_color) {
- this.setCubeColor(transform, opt_color);
- }
- if (opt_scale) {
- this.setCubeScale(transform, opt_scale);
- }
- return transform;
-};
-
-/**
- * Adds a cube to a transform.
- * @param {!o3d.Transform} transform Transform to add cube to.
- * @param {!o3djs.math.Vector4} opt_color RGBA color for cube.
- * @param {number} opt_scale of cube.
- */
-o3djs.debug.DebugHelper.prototype.addCube = function(transform,
- opt_color,
- opt_scale) {
- this.addShape_(transform, this.cubeShape_);
- if (opt_color) {
- this.setCubeColor(transform, opt_color);
- }
- if (opt_scale) {
- this.setCubeScale(transform, opt_scale);
- }
-};
-
-/**
- * Removes a cube from a transform
- * @param {!o3d.Transform} transform Transform to remove cube from.
- */
-o3djs.debug.DebugHelper.prototype.removeCube = function(transform) {
- this.removeShape_(transform, this.cubeShape_);
-};
-
-/**
- * Adds cubes to all transform in a tree.
- * @param {!o3d.Transform} treeRoot root of tree to add cubes to.
- */
-o3djs.debug.DebugHelper.prototype.addCubes = function(treeRoot) {
- this.addShapes_(treeRoot, this.cubeShape_);
-};
-
-/**
- * Removes cubes from all transforms in a tree.
- * @param {!o3d.Transform} treeRoot root of tree to remove cubes from.
- */
-o3djs.debug.DebugHelper.prototype.removeCubes = function(treeRoot) {
- this.removeShapes_(treeRoot, this.cubeShape_);
-};
-
-/**
- * Set cube color.
- * @param {!o3d.Transform} transform Transform on which to change cube
- * color.
- * @param {!o3djs.math.Vector3} color 4 number array in RGBA format.
- */
-o3djs.debug.DebugHelper.prototype.setCubeColor = function(transform,
- color) {
- this.addSetDebugTransformParam_(transform,
- O3D_DEBUG_CUBE_SHAPE_NAME,
- O3D_DEBUG_COLOR_PARAM_NAME,
- 'ParamFloat4',
- color);
-};
-
-/**
- * Sets the scale of a cubes.
- * @param {!o3d.Transform} transform Transform on which to change cube
- * scale.
- * @param {number} scale Scale to make the cube.
- */
-o3djs.debug.DebugHelper.prototype.setCubeScale = function(transform,
- scale) {
- this.addSetDebugTransformParam_(transform,
- O3D_DEBUG_CUBE_SHAPE_NAME,
- O3D_DEBUG_VECTOR_SCALE_PARAM_NAME,
- 'ParamFloat3',
- [scale, scale, scale]);
-};
-
-/**
- * Creates a debug line group. A Debug line group's purpose is the let you
- * quickly delete a set of lines.
- * @param {!o3d.Transform} root Root transform to use for lines.
- * @return {!o3djs.debug.DebugLineGroup} The debug line group.
- */
-o3djs.debug.DebugHelper.prototype.createDebugLineGroup =
- function(root) {
- return new o3djs.debug.DebugLineGroup(this, root);
-};
-
-/**
- * Creates a debug helper object.
- *
- * A debug helper object provides functions to help debug your o3d
- * application and manages the resources needed to do that for you. For
- * example it can add axes, spheres and boxes to your transforms as well as
- * draw lines in 3d space given 2 points.
- *
- * @param {!o3d.Pack} pack Pack for DebugHelper to manage its resources
- * with.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo ViewInfo for debug
- * visuals.
- * @return {!o3djs.debug.DebugHelper} the DebugHelper object.
- */
-o3djs.debug.createDebugHelper = function(pack, viewInfo) {
- return new o3djs.debug.DebugHelper(pack, viewInfo);
-};
-
diff --git a/o3d/samples/o3djs/dump.js b/o3d/samples/o3djs/dump.js
deleted file mode 100644
index 2486f51..0000000
--- a/o3d/samples/o3djs/dump.js
+++ /dev/null
@@ -1,585 +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.
- */
-
-
-/**
- * @fileoverview This file contains various dumping functions for o3d. It
- * puts them in the "dump" module on the o3djs object.
- *
- * Note: This library is only a sample. It is not meant to be some official
- * library. It is provided only as example code.
- *
- */
-
-o3djs.provide('o3djs.dump');
-
-/**
- * A Module for dumping information about o3d objects.
- * @namespace
- */
-o3djs.dump = o3djs.dump || {};
-
-/**
- * Dump the 3 elements of an array of numbers.
- * @private
- * @param {string} label Label to put in front of dump.
- * @param {!Array.<number>} object Array.
- * @param {string} opt_prefix Optional prefix for indenting.
- */
-o3djs.dump.dumpXYZ_ = function(label, object, opt_prefix) {
- opt_prefix = opt_prefix || '';
- o3djs.dump.dump(opt_prefix + label + ' : ' + object[0] + ', ' +
- object[1] + ', ' + object[2] + '\n');
-};
-
-/**
- * Dump the 4 elements of an array of numbers.
- * @private
- * @param {string} label Label to put in front of dump.
- * @param {!Array.<number>} object Array.
- * @param {string} opt_prefix Optional prefix for indenting.
- */
-o3djs.dump.dumpXYZW_ = function(label, object, opt_prefix) {
- opt_prefix = opt_prefix || '';
- o3djs.dump.dump(opt_prefix + label + ' : ' +
- object[0] + ', ' +
- object[1] + ', ' +
- object[2] + ', ' +
- object[3] + '\n');
-};
-
-/**
- * Get the name of a function.
- * @private
- * @param {!function(...): *} theFunction Function.
- * @return {string} The function name.
- */
-o3djs.dump.getFunctionName_ = function(theFunction) {
- if (theFunction.name) {
- return theFunction.name;
- }
-
- // try to parse the function name from the definition
- var definition = theFunction.toString();
- var name = definition.substring(definition.indexOf('function') + 8,
- definition.indexOf('('));
- if (name) {
- return name;
- }
-
- // sometimes there won't be a function name
- // like for dynamic functions
- return '*anonymous*';
-};
-
-/**
- * Get the signature of a function.
- * @private
- * @param {!function(...): *} theFunction Function.
- * @return {string} The function signature.
- */
-o3djs.dump.getSignature_ = function(theFunction) {
- var signature = o3djs.dump.getFunctionName_(theFunction);
- signature += '(';
- for (var x = 0; x < theFunction.arguments.length; x++) {
- // trim long arguments
- var nextArgument = theFunction.arguments[x];
- if (nextArgument.length > 30) {
- nextArgument = nextArgument.substring(0, 30) + '...';
- }
-
- // apend the next argument to the signature
- signature += "'" + nextArgument + "'";
-
- // comma separator
- if (x < theFunction.arguments.length - 1) {
- signature += ', ';
- }
- }
- signature += ')';
- return signature;
-};
-
-/**
- * Prints a value the console or log or wherever it thinks is appropriate
- * for debugging.
- * @param {string} string String to print.
- */
-o3djs.dump.dump = function(string) {
- o3djs.BROWSER_ONLY = true;
- if (window.dump) {
- window.dump(string);
- } else if (window.console && window.console.log) {
- window.console.log(string);
- }
-};
-
-/**
- * Gets the value of a matrix as a string.
- * @param {!o3djs.math.Matrix4} matrix Matrix4 to get value of.
- * @param {string} opt_prefix Optional prefix for indenting.
- * @return {string} Value of param.
- */
-o3djs.dump.getMatrixAsString = function(matrix, opt_prefix) {
- opt_prefix = opt_prefix || '';
- var result = opt_prefix + '[';
- for (var i = 0; 1; ++i){
- var mi = matrix[i];
- result += '[';
- for (var j = 0; 1; ++j) {
- result += mi[j];
- if (j < mi.length - 1) {
- result += ', ';
- } else {
- result += ']';
- break;
- }
- }
- if (i < matrix.length - 1) {
- result += '\n';
- result += opt_prefix;
- } else {
- break;
- }
- }
- result += ']';
- return result;
-};
-
-/**
- * Dumps a float3
- * @param {string} label Label to put in front of dump.
- * @param {!o3d.Float3} float3 Float3 to dump.
- * @param {string} opt_prefix optional prefix for indenting.
- */
-o3djs.dump.dumpFloat3 = function(label, float3, opt_prefix) {
- opt_prefix = opt_prefix || '';
- o3djs.dump.dumpXYZ_(label, float3, opt_prefix);
-};
-
-/**
- * Dumps a float4
- * @param {string} label Label to put in front of dump.
- * @param {!o3d.Float4} float4 Float4 to dump.
- * @param {string} opt_prefix optional prefix for indenting.
- */
-o3djs.dump.dumpFloat4 = function(label, float4, opt_prefix) {
- opt_prefix = opt_prefix || '';
- o3djs.dump.dumpXYZW_(label, float4, opt_prefix);
-};
-
-/**
- * Dumps a vector4
- * @param {string} label Label to put in front of dump.
- * @param {!Array.<number>} vector4 vector to dump.
- * @param {string} opt_prefix optional prefix for indenting.
- */
-o3djs.dump.dumpVector4 = function(label, vector4, opt_prefix) {
- opt_prefix = opt_prefix || '';
- o3djs.dump.dumpXYZW_(label, vector4, opt_prefix);
-};
-
-/**
- * Dumps a matrix
- * @param {string} label Label to put in front of dump.
- * @param {!o3djs.math.Matrix4} matrix Matrix to dump.
- * @param {string} opt_prefix optional prefix for indenting.
- */
-o3djs.dump.dumpMatrix = function(label, matrix, opt_prefix) {
- opt_prefix = opt_prefix || '';
- o3djs.dump.dump(
- opt_prefix + label + ' :\n' +
- o3djs.dump.getMatrixAsString(matrix, opt_prefix + ' ') +
- '\n');
-};
-
-/**
- * Dump a bounding box.
- * @param {string} label Label to put in front of dump.
- * @param {!o3d.BoundingBox} boundingBox BoundingBox to dump.
- * @param {string} opt_prefix optional prefix for indenting.
- */
-o3djs.dump.dumpBoundingBox = function(label,
- boundingBox,
- opt_prefix) {
- opt_prefix = opt_prefix || '';
- o3djs.dump.dump(opt_prefix + label + ' :\n');
- o3djs.dump.dumpFloat3('min : ',
- boundingBox.minExtent,
- opt_prefix + ' ');
- o3djs.dump.dumpFloat3('max : ',
- boundingBox.maxExtent,
- opt_prefix + ' ');
-};
-
-/**
- * Gets the value of a parameter as a string.
- * @param {!o3d.Param} param Parameter to get value of.
- * @param {string} opt_prefix Optional prefix for indenting.
- * @return {string} Value of param.
- */
-o3djs.dump.getParamValueAsString = function(param, opt_prefix) {
- opt_prefix = opt_prefix || '';
- var value = '*unknown*';
-
- if (param.isAClassName('o3d.ParamFloat')) {
- value = param.value.toString();
- } else if (param.isAClassName('o3d.ParamFloat2')) {
- value = '[' + param.value[0] + ', ' +
- param.value[1] + ']';
- } else if (param.isAClassName('o3d.ParamFloat3')) {
- value = '[' + param.value[0] + ', ' +
- param.value[1] + ', ' +
- param.value[2] + ']';
- } else if (param.isAClassName('o3d.ParamFloat4')) {
- value = '[' + param.value[0] + ', ' +
- param.value[1] + ', ' +
- param.value[2] + ', ' +
- param.value[3] + ']';
- } else if (param.isAClassName('o3d.ParamInteger')) {
- value = param.value.toString();
- } else if (param.isAClassName('o3d.ParamBoolean')) {
- value = param.value.toString();
- } else if (param.isAClassName('o3d.ParamMatrix4')) {
- value = '\n' + o3djs.dump.getMatrixAsString(param.value,
- opt_prefix + ' ');
- } else if (param.isAClassName('o3d.ParamString')) {
- value = param.value;
- } else if (param.isAClassName('o3d.ParamTexture')) {
- value = param.value;
- value = 'texture : "' + (value ? value.name : 'NULL') + '"';
- } else if (param.isAClassName('o3d.ParamSampler')) {
- value = param.value;
- value = 'sampler : "' + (value ? value.name : 'NULL') + '"';
- } else if (param.isAClassName('o3d.ParamMaterial')) {
- value = param.value;
- value = 'material : "' + (value ? value.name : 'NULL') + '"';
- } else if (param.isAClassName('o3d.ParamEffect')) {
- value = param.value;
- value = 'effect : "' + (value ? value.name : 'NULL') + '"';
- } else if (param.isAClassName('o3d.ParamState')) {
- value = param.value;
- value = 'state : "' + (value ? value.name : 'NULL') + '"';
- } else if (param.isAClassName('o3d.ParamTransform')) {
- value = param.value;
- value = 'transform : "' + (value ? value.name : 'NULL') + '"';
- } else if (param.isAClassName('o3d.ParamDrawList')) {
- value = param.value;
- value = 'drawlist : "' + (value ? value.name : 'NULL') + '"';
- } else if (param.isAClassName('o3d.ParamRenderSurface')) {
- value = param.value;
- value = 'renderSurface : "' + (value ? value.name : 'NULL') + '"';
- } else if (param.isAClassName('o3d.ParamRenderDepthStencilSurface')) {
- value = param.value;
- value = 'renderDepthStencilSurface: "' + (value ? value.name : 'NULL') +
- '"';
- } else if (param.isAClassName('o3d.ParamDrawContext')) {
- value = param.value;
- value = 'drawcontext : "' + (value ? value.name : 'NULL') + '"';
- }
-
- return value;
-};
-
-/**
- * Dumps an single parameter
- * @param {!o3d.Param} param Param to dump.
- * @param {string} opt_prefix Optional prefix for indenting.
- */
-o3djs.dump.dumpParam = function(param, opt_prefix) {
- opt_prefix = opt_prefix || '';
- o3djs.dump.dump (
- opt_prefix + param.className + ' : "' + param.name + '" : ' +
- o3djs.dump.getParamValueAsString(param, opt_prefix) + '\n');
-};
-
-/**
- * Given a ParamObject dumps all the Params on it.
- * @param {!o3d.ParamObject} param_object ParamObject to dump Params of.
- * @param {string} opt_prefix Optional prefix for indenting.
- */
-o3djs.dump.dumpParams = function(param_object, opt_prefix) {
- opt_prefix = opt_prefix || '';
- // print params
- var params = param_object.params;
- for (var p = 0; p < params.length; p++) {
- o3djs.dump.dumpParam(params[p], opt_prefix);
- }
-};
-
-/**
- * Given a ParamObject dumps it and all the Params on it.
- * @param {!o3d.ParamObject} param_object ParamObject to dump.
- * @param {string} opt_prefix Optional prefix for indenting.
- */
-o3djs.dump.dumpParamObject = function(param_object, opt_prefix) {
- opt_prefix = opt_prefix || '';
- o3djs.dump.dump (
- opt_prefix + param_object.className + ' : "' +
- param_object.name + '"\n');
- o3djs.dump.dumpParams(param_object, opt_prefix + ' ');
-};
-
-/**
- * Given a Stream dumps it and all the Params on it.
- * @param {!o3d.Stream} stream Stream to dump.
- * @param {string} opt_prefix Optional prefix for indenting.
- */
-o3djs.dump.dumpStream = function(stream, opt_prefix) {
- opt_prefix = opt_prefix || '';
- o3djs.dump.dump(
- opt_prefix + 'semantic: ' + stream.semantic +
- ', index: ' + stream.semanticIndex +
- ', dataType: ' + stream.dataType +
- ', field: ' + stream.field.name + '\n');
-};
-
-/**
- * Given a element dumps its name, all the Params and DrawElements on
- * it.
- * @param {!o3d.Element} element Element to dump.
- * @param {string} opt_prefix Optional prefix for indenting.
- */
-o3djs.dump.dumpElement = function(element, opt_prefix) {
- opt_prefix = opt_prefix || '';
-
- o3djs.dump.dump (opt_prefix + '------------ Element --------------\n');
-
- // get type
- o3djs.dump.dump (
- opt_prefix + 'Element: "' + element.name + '"\n');
-
- // print params
- o3djs.dump.dump (opt_prefix + ' --Params--\n');
- o3djs.dump.dumpParams (element, opt_prefix + ' ');
-
- // print elements.
- o3djs.dump.dump (opt_prefix + ' --DrawElements--\n');
- var drawElements = element.drawElements;
- for (var g = 0; g < drawElements.length; g++) {
- var drawElement = drawElements[g]
- o3djs.dump.dumpParamObject(drawElement, opt_prefix + ' ');
- }
-
- if (element.isAClassName('o3d.Primitive')) {
- o3djs.dump.dump (
- opt_prefix + ' primitive type: ' + element.primitiveType + '\n');
- o3djs.dump.dump (
- opt_prefix + ' number vertices: ' + element.numberVertices + '\n');
- o3djs.dump.dump (
- opt_prefix + ' number primitives: ' + element.numberPrimitives +
- '\n');
- var streamBank = element.streamBank;
- if (streamBank) {
- var streams = streamBank.vertexStreams;
- for (var ss = 0; ss < streams.length; ss++) {
- var stream = streams[ss];
- o3djs.dump.dump(opt_prefix + ' stream ' + ss + ': ');
- o3djs.dump.dumpStream(stream);
- }
- }
- }
-};
-
-/**
- * Given a shape dumps its name, all the Params and Primitves on
- * it.
- * @param {!o3d.Shape} shape Shape to dump.
- * @param {string} opt_prefix Optional prefix for indenting.
- */
-o3djs.dump.dumpShape = function(shape, opt_prefix) {
- opt_prefix = opt_prefix || '';
-
- o3djs.dump.dump (opt_prefix + '------------ Shape --------------\n');
-
- // get type
- o3djs.dump.dump (
- opt_prefix + 'Shape: "' + shape.name + '"\n');
-
- // print params
- o3djs.dump.dump (opt_prefix + ' --Params--\n');
- o3djs.dump.dumpParams (shape, opt_prefix + ' ');
-
- // print elements.
- o3djs.dump.dump (opt_prefix + ' --Elements--\n');
- var elements = shape.elements;
- for (var p = 0; p < elements.length; p++) {
- var element = elements[p];
- o3djs.dump.dumpElement(element, opt_prefix + ' ');
- }
-};
-
-/**
- * Given a texture dumps its name and other info.
- * it.
- * @param {!o3d.Texture} texture Texture to dump.
- * @param {string} opt_prefix Optional prefix for indenting.
- */
-o3djs.dump.dumpTexture = function(texture, opt_prefix) {
- opt_prefix = opt_prefix || '';
- var uri = '';
- var param = texture.getParam('uri');
- if (param) {
- uri = param.value;
- }
- o3djs.dump.dump (
- opt_prefix + texture.className +
- ' : "' + texture.name +
- '" uri : "' + uri +
- '" width: ' + texture.width +
- ' height: ' + texture.height +
- ' alphaIsOne: ' + texture.alphaIsOne +
- '\n');
-};
-
-/**
- * Given a transform dumps its name and all the Params and Shapes on it.
- * @param {!o3d.Transform} transform Transform to dump.
- * @param {string} opt_prefix Optional prefix for indenting.
- */
-o3djs.dump.dumpTransform = function(transform, opt_prefix) {
- opt_prefix = opt_prefix || '';
-
- o3djs.dump.dump (opt_prefix + '----------- Transform -------------\n');
-
- // get type
- o3djs.dump.dump (
- opt_prefix + 'Transform: ' + transform.name + '"\n');
-
- // print params
- o3djs.dump.dump (opt_prefix + ' --Local Matrix--\n');
- o3djs.dump.dump (
- o3djs.dump.getMatrixAsString(transform.localMatrix,
- opt_prefix + ' ') + '\n');
-
- // print params
- o3djs.dump.dump (opt_prefix + ' --Params--\n');
- o3djs.dump.dumpParams (transform, opt_prefix + ' ');
-
- // print shapes.
- o3djs.dump.dump (opt_prefix + ' --Shapes--\n');
- var shapes = transform.shapes;
- for (var s = 0; s < shapes.length; s++) {
- var shape = shapes[s];
- o3djs.dump.dumpNamedObjectName(shape, opt_prefix + ' ');
- }
-};
-
-/**
- * Dumps an entire transform graph tree.
- * @param {!o3d.Transform} transform Transform to start dumping from.
- * @param {string} opt_prefix Optional prefix for indenting.
- */
-o3djs.dump.dumpTransformTree = function(transform, opt_prefix) {
- opt_prefix = opt_prefix || '';
-
- o3djs.dump.dumpTransform(transform, opt_prefix);
-
- var child_prefix = opt_prefix + ' ';
- var children = transform.children;
- for (var c = 0; c < children.length; c++) {
- o3djs.dump.dumpTransformTree(children[c], child_prefix);
- }
-};
-
-/**
- * Dumps a list of Transforms.
- * @param {!Array.<!o3d.Transform>} transform_list Array of Transforms to dump.
- */
-o3djs.dump.dumpTransformList = function(transform_list) {
- o3djs.dump.dump (transform_list.length + ' transforms in list!!!\n');
- for (var i = 0; i < transform_list.length; i++) {
- o3djs.dump.dumpTransform(transform_list[i]);
- }
-};
-
-/**
- * Dumps the name and class of a NamedObject.
- * @param {!o3d.NamedObject} namedObject to use.
- * @param {string} opt_prefix Optional prefix for indenting.
- */
-o3djs.dump.dumpNamedObjectName = function(namedObject, opt_prefix) {
- opt_prefix = opt_prefix || '';
- o3djs.dump.dump (
- opt_prefix + namedObject.className + ' : "' + namedObject.name +
- '"\n');
-};
-
-/**
- * Dumps a RenderNode and all its paramaters.
- * @param {!o3d.RenderNode} render_node RenderNode to use.
- * @param {string} opt_prefix Optional prefix for indenting.
- */
-o3djs.dump.dumpRenderNode = function(render_node, opt_prefix) {
- opt_prefix = opt_prefix || '';
-
- o3djs.dump.dump (opt_prefix + '----------- Render Node -----------\n');
- // get type
- o3djs.dump.dumpNamedObjectName(render_node, opt_prefix);
-
- // print params
- o3djs.dump.dump (opt_prefix + ' --Params--\n');
- o3djs.dump.dumpParams(render_node, opt_prefix + ' ');
-};
-
-/**
- * Dumps an entire RenderGraph tree.
- * @param {!o3d.RenderNode} render_node RenderNode to start dumping from.
- * @param {string} opt_prefix Optional prefix for indenting.
- */
-o3djs.dump.dumpRenderNodeTree = function(render_node, opt_prefix) {
- opt_prefix = opt_prefix || '';
-
- o3djs.dump.dumpRenderNode(render_node, opt_prefix);
-
- var child_prefix = opt_prefix + ' ';
- // Get the list of children sorted by priority.
- var children = render_node.children.sort(function(a, b) {
- return a.priority - b.priority;
- });
- for (var c = 0; c < children.length; c++) {
- o3djs.dump.dumpRenderNodeTree(children[c], child_prefix);
- }
-};
-
-/**
- * Dumps a javascript stack track.
- */
-o3djs.dump.dumpStackTrace = function() {
- o3djs.dump.dump('Stack trace:\n');
- var nextCaller = arguments.callee.caller;
- while (nextCaller) {
- o3djs.dump.dump(o3djs.dump.getSignature_(nextCaller) + '\n');
- nextCaller = nextCaller.caller;
- }
- o3djs.dump.dump('\n\n');
-};
-
diff --git a/o3d/samples/o3djs/effect.js b/o3d/samples/o3djs/effect.js
deleted file mode 100644
index dc16fd4..0000000
--- a/o3d/samples/o3djs/effect.js
+++ /dev/null
@@ -1,1534 +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.
- */
-
-
-/**
- * @fileoverview This file contains various functions related to effects.
- * It puts them in the "effect" module on the o3djs object.
- *
- * Note: This library is only a sample. It is not meant to be some official
- * library. It is provided only as example code.
- *
- */
-
-o3djs.provide('o3djs.effect');
-
-o3djs.require('o3djs.io');
-
-/**
- * A Module for dealing with effects.
- * @namespace
- */
-o3djs.effect = o3djs.effect || {};
-
-/**
- * The name of standard 2 color checker effect.
- * @type {string}
- */
-o3djs.effect.TWO_COLOR_CHECKER_EFFECT_NAME =
- 'o3djs.effect.twoColorCheckerEffect';
-
-
-/**
- * An object containing string constants and functions which are specific to
- * the o3d shading language. When setLanguage gets called the properties of
- * this object get coppied into the o3djs.effect namespace and then get used
- * in shader generation code.
- * @namespace
- */
-o3djs.effect.o3d = {
- LANGUAGE: 'o3d',
- FLOAT2: 'float2',
- FLOAT3: 'float3',
- FLOAT4: 'float4',
- MATRIX4: 'float4x4',
- MATRIX3: 'float3x3',
- MOD: 'fmod',
- ATTRIBUTE: ' ',
- ATTRIBUTE_PREFIX: 'input.',
- VARYING: ' ',
- VARYING_DECLARATION_PREFIX: '',
- VERTEX_VARYING_PREFIX: 'output.',
- PIXEL_VARYING_PREFIX: 'input.',
- TEXTURE: 'tex',
- SAMPLER: 'sampler',
- BEGIN_IN_STRUCT: 'struct InVertex {\n',
- BEGIN_OUT_STRUCT: 'struct OutVertex {\n',
- END_STRUCT: '};\n'
-};
-
-
-/**
- * An object containing string constants and functions which are specific to
- * the o3d shading language. When setLanguage gets called the properties of
- * this object get coppied into the o3djs.effect namespace and then get used
- * in shader generation code.
- * @namespace
- */
-o3djs.effect.glsl = {
- LANGUAGE: 'glsl',
- FLOAT2: 'vec2',
- FLOAT3: 'vec3',
- FLOAT4: 'vec4',
- MATRIX4: 'mat4',
- MATRIX3: 'mat3',
- MOD: 'mod',
- ATTRIBUTE: 'attribute ',
- ATTRIBUTE_PREFIX: '',
- VARYING: 'varying ',
- VARYING_DECLARATION_PREFIX: 'v_',
- VERTEX_VARYING_PREFIX: 'v_',
- PIXEL_VARYING_PREFIX: 'v_',
- TEXTURE: 'texture',
- SAMPLER: 'sampler2D',
- BEGIN_IN_STRUCT: '',
- BEGIN_OUT_STRUCT: '',
- END_STRUCT: '',
- // Only used in GLSL version of getAttributeName_.
- semanticNameMap: {
- 'POSITION' : 'position',
- 'NORMAL' : 'normal',
- 'TANGENT' : 'tangent',
- 'BINORMAL' : 'binormal',
- 'COLOR' : 'color',
- 'TEXCOORD0' : 'texCoord0',
- 'TEXCOORD1' : 'texCoord1',
- 'TEXCOORD2' : 'texCoord2',
- 'TEXCOORD3' : 'texCoord3',
- 'TEXCOORD4' : 'texCoord4',
- 'TEXCOORD5' : 'texCoord5',
- 'TEXCOORD6' : 'texCoord6',
- 'TEXCOORD7' : 'texCoord7'
- }
-};
-
-
-/**
- * The string that goes between the stream name and the semicolon to indicate
- * the semantic.
- * @param {string} name Name of the semantic.
- * @return {string}
- */
-o3djs.effect.glsl.semanticSuffix = function(name) {
- return '';
-};
-
-
-/**
- * The string that goes between the stream name and the semicolon to indicate
- * the semantic.
- * @param {string} name Name of the semantic.
- * @return {string}
- */
-o3djs.effect.o3d.semanticSuffix = function(name) {
- return ' : ' + name;
-};
-
-
-/**
- * Attribute variables in GLSL need to be named by their semantic in
- * order for the implementation to hook them up correctly.
- * @private
- */
-o3djs.effect.glsl.getAttributeName_ = function(name, semantic) {
- var p = o3djs.effect;
- return p.semanticNameMap[semantic];
-};
-
-
-/**
- * This passes through the name in the Cg implementation.
- * @private
- */
-o3djs.effect.o3d.getAttributeName_ = function(name, semantic) {
- return name;
-};
-
-
-/**
- * Generates code to multiply two things.
- * @param {string} a One multiplicand.
- * @param {string} b The other multiplicand.
- * @return {string}
- */
-o3djs.effect.glsl.mul = function(a, b) {
- return '(' + b + ' * ' + a + ')';
-};
-
-
-/**
- * Generates code to multiply two things.
- * @param {string} a One multiplicand.
- * @param {string} b The other multiplicand.
- * @return {string}
- */
-o3djs.effect.o3d.mul = function(a, b) {
- return 'mul(' + a + ', ' + b + ')';
-};
-
-
-/**
- * Generates code for some utility functions
- * (functions defined in cg but not glsl).
- * @return {string} The code for the utility functions.
- */
-o3djs.effect.glsl.utilityFunctions = function() {
- return 'vec4 lit(float l ,float h, float m) {\n' +
- ' return vec4(1.0,\n' +
- ' max(l, 0.0),\n' +
- ' (l > 0.0) ? pow(max(0.0, h), m) : 0.0,\n' +
- ' 1.0);\n' +
- '}\n';
-};
-
-
-/**
- * Generates code for some utility functions
- * (functions defined in cg but not glsl).
- * @return {string} The code for the utility functions.
- */
-o3djs.effect.o3d.utilityFunctions = function() {
- return '';
-}
-
-
-/**
- * The string that starts the vertex shader main function.
- * @return {string} The effect code for the start of the main.
- */
-o3djs.effect.glsl.beginVertexShaderMain = function() {
- return 'void main() {\n';
-};
-
-/**
- * The string that starts the vertex shader main function.
- * @return {string} The effect code for the start of the main.
- */
-o3djs.effect.o3d.beginVertexShaderMain = function() {
- return 'OutVertex vertexShaderFunction(InVertex input) {\n' +
- ' OutVertex output;\n';
-};
-
-/**
- * The string that ends the vertex main function.
- * @return {string}
- */
-o3djs.effect.glsl.endVertexShaderMain = function() {
- return ' gl_Position = ' + o3djs.effect.VERTEX_VARYING_PREFIX +
- 'position;\n}\n';
-};
-
-/**
- * The string that ends the vertex main function.
- * @return {string}
- */
-o3djs.effect.o3d.endVertexShaderMain = function() {
- return ' return output;\n}\n';
-};
-
-
-/**
- * The string that goes infront of the pixel shader main.
- * @param {!o3d.Material} material The material to inspect.
- * @param {boolean} diffuse Whether to include stuff for diffuse calculations.
- * @param {boolean} specular Whether to include stuff for diffuse
- * calculations.
- * @param {boolean} bumpSampler Whether there is a bump sampler.
- * @return {string} The header.
- */
-o3djs.effect.glsl.pixelShaderHeader =
- function(material, diffuse, specular, bumpSampler) {
- return '\n// #o3d SplitMarker\n';
-};
-
-
-/**
- * The string that goes infront of the pixel shader main.
- * @param {!o3d.Material} material The material to inspect.
- * @param {boolean} diffuse Whether to include stuff for diffuse calculations.
- * @param {boolean} specular Whether to include stuff for diffuse
- * calculations.
- * @param {boolean} bumpSampler Whether there is a bump sampler.
- * @return {string} The header.
- */
-o3djs.effect.o3d.pixelShaderHeader =
- function(material, diffuse, specular, bumpSampler) {
- return '';
-};
-
-
-/**
- * Repeats the declarations for the varying parameters if necessary.
- * @param {string} opt_decls The declarations if you know them already.
- * @return {string} Code for the parameter declarations.
- */
-o3djs.effect.glsl.repeatVaryingDecls = function(opt_decls) {
- return (opt_decls ||
- o3djs.effect.varying_decls_ ||
- o3djs.buildVaryingDecls()) +
- '\n';
-};
-
-/**
- * Repeats the declarations for the varying parameters if necessary.
- * @param {string} opt_decls The declarations if you know them already.
- * @return {string} Code for the parameter declarations.
- */
-o3djs.effect.o3d.repeatVaryingDecls = function(opt_decls) {
- return '';
-};
-
-
-/**
- * The string that goes infront of the pixel shader main.
- * @return {string} The effect code for the start of the main.
- */
-o3djs.effect.glsl.beginPixelShaderMain = function() {
- return 'void main() {\n';
-};
-
-
-/**
- * The string that goes infront of the pixel shader main.
- * @return {string} The effect code for the start of the main.
- */
-o3djs.effect.o3d.beginPixelShaderMain = function() {
- return 'float4 pixelShaderFunction(OutVertex input) : COLOR {\n';
-};
-
-
-/**
- * The string that goes at the end of the pixel shader main.
- * @param {string} color The code for the color to return.
- * @return {string} The effect code for the end of the main.
- */
-o3djs.effect.o3d.endPixelShaderMain = function(color) {
- return ' return ' + color + ';\n}\n';
-};
-
-
-/**
- * The string that goes at the end of the pixel shader main.
- * @param {string} color The code for the color to return.
- * @return {string} The effect code for the end of the main.
- */
-o3djs.effect.glsl.endPixelShaderMain = function(color) {
- return ' gl_FragColor = ' + color + ';\n}\n';
-};
-
-
-/**
- * The vertex and fragment shader entry point in the format that
- * o3d parses.
- * @return {string}
- */
-o3djs.effect.o3d.entryPoints = function() {
- return '// #o3d VertexShaderEntryPoint vertexShaderFunction\n' +
- '// #o3d PixelShaderEntryPoint pixelShaderFunction\n';
-};
-
-
-/**
- * The vertex and fragment shader entry points. In glsl, this is unnecessary.
- * @return {string}
- */
-o3djs.effect.glsl.entryPoints = function() {
- return '';
-};
-
-o3djs.effect.glsl.matrixLoadOrder =
-o3djs.effect.o3d.matrixLoadOrder = function() {
- return '// #o3d MatrixLoadOrder RowMajor\n';
-};
-
-
-/**
- * Sets the shader language used. Passing 'glsl' will cause all generated
- * shader code to be in glsl. Passing anything else will result in the
- * default o3d hlsl/cg based shader language.
- * @param {string} language Shader language to use.
- */
-o3djs.effect.setLanguage = function(language) {
- var language_namespace = o3djs.effect.o3d;
- if (language == 'glsl') {
- language_namespace = o3djs.effect.glsl;
- }
- for (var f in o3djs.effect.glsl) {
- o3djs.effect[f] = language_namespace[f];
- }
-
- o3djs.effect.TWO_COLOR_CHECKER_FXSTRING =
- o3djs.effect.buildCheckerShaderString();
-};
-
-/**
- * Gets the language set in the function setLanguage. Returns a string, either
- * 'glsl' or 'o3d'.
- */
-o3djs.effect.getLanguage = function() {
- var language_namespace = o3djs.effect.o3d;
- if (language_namespace == o3djs.effect.glsl) {
- return 'glsl';
- }
- return 'o3d';
-};
-
-
-/**
- * Builds the vertex attribute declarations for a given material.
- * @param {!o3d.Material} material The material to inspect.
- * @param {boolean} diffuse Whether to include stuff for diffuse calculations.
- * @param {boolean} specular Whether to include stuff for diffuse
- * calculations.
- * @param {boolean} bumpSampler Whether there is a bump sampler.
- * @param {boolean} skinning Whether this mesh has a skin.
- * @return {string} The code for the declarations.
- */
-o3djs.effect.buildAttributeDecls =
- function(material, diffuse, specular, bumpSampler, skinning) {
- var str = o3djs.effect.BEGIN_IN_STRUCT +
- o3djs.effect.ATTRIBUTE + o3djs.effect.FLOAT4 + ' ' + 'position' +
- o3djs.effect.semanticSuffix('POSITION') + ';\n';
- if (diffuse || specular) {
- str += o3djs.effect.ATTRIBUTE + o3djs.effect.FLOAT3 + ' ' + 'normal' +
- o3djs.effect.semanticSuffix('NORMAL') + ';\n';
- }
- if (skinning) {
- str += o3djs.effect.ATTRIBUTE + o3djs.effect.FLOAT4 + ' influenceWeights' +
- o3djs.effect.semanticSuffix('BLENDWEIGHT') + ';\n';
- str += o3djs.effect.ATTRIBUTE + o3djs.effect.FLOAT4 + ' influenceIndices' +
- o3djs.effect.semanticSuffix('BLENDINDICES') + ';\n';
- }
- str += o3djs.effect.buildTexCoords(material, false) +
- o3djs.effect.buildBumpInputCoords(bumpSampler) +
- o3djs.effect.END_STRUCT;
- return str;
-};
-
-
-/**
- * Caches the varying parameter declarations to be repeated in the case that
- * we're in glsl and need to declare the varying parameters in both shaders.
- * @type {string}
- */
-o3djs.effect.varying_decls_ = '';
-
-
-/**
- * Builds the varying parameter declarations for a given material.
- * @param {!o3d.Material} material The material to inspect.
- * @param {boolean} diffuse Whether to include stuff for diffuse calculations.
- * @param {boolean} specular Whether to include stuff for diffuse
- * calculations.
- * @param {boolean} bumpSampler Whether there is a bump sampler.
- * @return {string} The code for the declarations.
- */
-o3djs.effect.buildVaryingDecls =
- function(material, diffuse, specular, bumpSampler) {
- var p = o3djs.effect;
- var str = p.BEGIN_OUT_STRUCT +
- p.VARYING + p.FLOAT4 + ' ' +
- p.VARYING_DECLARATION_PREFIX + 'position' +
- p.semanticSuffix('POSITION') + ';\n' +
- p.buildTexCoords(material, true) +
- p.buildBumpOutputCoords(bumpSampler);
- if (diffuse || specular) {
- str += p.VARYING + p.FLOAT3 + ' ' +
- p.VARYING_DECLARATION_PREFIX + 'normal' +
- p.semanticSuffix('TEXCOORD' +
- p.interpolant_++ + '') + ';\n' +
- p.VARYING + p.FLOAT3 + ' ' +
- p.VARYING_DECLARATION_PREFIX + 'surfacePosition' +
- p.semanticSuffix(
- 'TEXCOORD' + p.interpolant_++ + '') + ';\n';
- }
- if (specular) {
- str += p.VARYING + p.FLOAT3 + ' ' +
- p.VARYING_DECLARATION_PREFIX + 'surfaceToView' +
- p.semanticSuffix(
- 'TEXCOORD' + p.interpolant_++ + '') + ';\n';
- }
- str += p.END_STRUCT;
- p.varying_decls_ = str;
- return str;
-};
-
-
-/**
- * An integer value which keeps track of the next available interpolant.
- * @type {number}
- * @private
- */
-o3djs.effect.interpolant_ = 0;
-
-/**
- * Builds the texture coordinate declaration for a given color input
- * (usually emissive, ambient, diffuse or specular). If the color
- * input does not have a sampler, no TEXCOORD declaration is built.
- * @param {!o3d.Material} material The material to inspect.
- * @param {boolean} varying Whether these vertex declarations should
- * be written as varying values.
- * @param {string} name The name of the color input.
- * @return {string} The code for the texture coordinate declaration.
- */
-o3djs.effect.buildTexCoord = function(material, varying, name) {
- var p = o3djs.effect;
- // In the GLSL version we need to name the incoming attributes by
- // the semantic name in order for them to get hooked up correctly.
- if (material.getParam(name + 'Sampler')) {
- if (varying) {
- return ' ' + p.VARYING + p.FLOAT2 + ' ' +
- p.VARYING_DECLARATION_PREFIX + name + 'UV' +
- p.semanticSuffix(
- 'TEXCOORD' + p.interpolant_++ + '') + ';\n';
- } else {
- var desiredName = name + 'UV';
- var semantic = 'TEXCOORD' + p.interpolant_++;
- var outputName = p.getAttributeName_(desiredName, semantic);
- if (p.semanticNameMap) {
- p.nameToSemanticMap_[desiredName] = semantic;
- }
- return ' ' + p.ATTRIBUTE + p.FLOAT2 + ' ' + outputName +
- p.semanticSuffix(semantic) + ';\n';
- }
- } else {
- return '';
- }
-};
-
-/**
- * Builds all the texture coordinate declarations for a vertex attribute
- * declaration.
- * @param {!o3d.Material} material The material to inspect.
- * @param {boolean} varying Whether these vertex declarations should
- * be written as varying values.
- * @return {string} The code for the texture coordinate declarations.
- */
-o3djs.effect.buildTexCoords = function(material, varying) {
- var p = o3djs.effect;
- p.interpolant_ = 0;
- if (!varying) {
- p.nameToSemanticMap_ = {};
- }
- return p.buildTexCoord(material, varying, 'emissive') +
- p.buildTexCoord(material, varying, 'ambient') +
- p.buildTexCoord(material, varying, 'diffuse') +
- p.buildTexCoord(material, varying, 'specular');
-};
-
-
-/**
- * Builds the texture coordinate passthrough statement for a given
- * color input (usually emissive, ambient, diffuse or specular). These
- * assigments are used in the vertex shader to pass the texcoords to be
- * interpolated to the rasterizer. If the color input does not have
- * a sampler, no code is generated.
- * @param {!o3d.Material} material The material to inspect.
- * @param {string} name The name of the color input.
- * @return {string} The code for the texture coordinate passthrough statement.
- */
-o3djs.effect.buildUVPassthrough = function(material, name) {
- var p = o3djs.effect;
- if (material.getParam(name + 'Sampler')) {
- var sourceName = name + 'UV';
- var destName = sourceName;
- var semantic = p.nameToSemanticMap_[sourceName];
- if (semantic) {
- sourceName = p.getAttributeName_(sourceName, semantic);
- }
- return ' ' + p.VERTEX_VARYING_PREFIX + destName + ' = ' +
- p.ATTRIBUTE_PREFIX + sourceName + ';\n';
- } else {
- return '';
- }
-};
-
-
-/**
- * Builds all the texture coordinate passthrough statements for the
- * vertex shader.
- * @param {!o3d.Material} material The material to inspect.
- * @return {string} The code for the texture coordinate passthrough
- * statements.
- */
-o3djs.effect.buildUVPassthroughs = function(material) {
- var p = o3djs.effect;
- // TODO(petersont): in the GLSL implementation we need to generate
- // the code for these attributes before we can pass their values
- // through, because in this implementation their names must be their
- // semantics (i.e., "texCoord4") rather than these chosen names.
- // Currently bumpUV is the only one which does not obey this rule.
- return p.buildUVPassthrough(material, 'emissive') +
- p.buildUVPassthrough(material, 'ambient') +
- p.buildUVPassthrough(material, 'diffuse') +
- p.buildUVPassthrough(material, 'specular') +
- p.buildUVPassthrough(material, 'bump');
-};
-
-
-/**
- * Builds bump input coords if needed.
- * @param {boolean} bumpSampler Whether there is a bump sampler.
- * @return {string} The code for bump input coords.
- */
-o3djs.effect.buildBumpInputCoords = function(bumpSampler) {
- var p = o3djs.effect;
- return bumpSampler ?
- (' ' + p.FLOAT3 + ' tangent' +
- p.semanticSuffix('TANGENT') + ';\n' +
- ' ' + p.FLOAT3 + ' binormal' +
- p.semanticSuffix('BINORMAL') + ';\n' +
- ' ' + p.FLOAT2 + ' bumpUV' +
- p.semanticSuffix(
- 'TEXCOORD' + p.interpolant_++) + ';\n') : '';
-};
-
-
-/**
- * Builds bump output coords if needed.
- * @param {boolean} bumpSampler Whether there is a bump sampler.
- * @return {string} The code for bump input coords.
- */
-o3djs.effect.buildBumpOutputCoords = function(bumpSampler) {
- var p = o3djs.effect;
- return bumpSampler ?
- (' ' + p.FLOAT3 + ' tangent' +
- p.semanticSuffix(
- 'TEXCOORD' + p.interpolant_++) + ';\n' +
- ' ' + p.FLOAT3 + ' binormal' +
- p.semanticSuffix('TEXCOORD' +
- p.interpolant_++) + ';\n' +
- ' ' + p.FLOAT2 + ' bumpUV' +
- p.semanticSuffix(
- 'TEXCOORD' + p.interpolant_++) + ';\n') : '';
-};
-
-
-/**
- * Builds vertex and fragment shader string for a 2-color checker effect.
- * @return {string} The effect code for the shader, ready to be parsed.
- */
-o3djs.effect.buildCheckerShaderString = function() {
- var p = o3djs.effect;
- var varyingDecls = p.BEGIN_OUT_STRUCT +
- p.VARYING + p.FLOAT4 + ' ' +
- p.VARYING_DECLARATION_PREFIX + 'position' +
- p.semanticSuffix('POSITION') + ';\n' +
- p.VARYING + p.FLOAT2 + ' ' +
- p.VARYING_DECLARATION_PREFIX + 'texCoord' +
- p.semanticSuffix('TEXCOORD0') + ';\n' +
- p.VARYING + p.FLOAT3 + ' ' +
- p.VARYING_DECLARATION_PREFIX + 'normal' +
- p.semanticSuffix('TEXCOORD1') + ';\n' +
- p.VARYING + p.FLOAT3 + ' ' +
- p.VARYING_DECLARATION_PREFIX + 'worldPosition' +
- p.semanticSuffix('TEXCOORD2') + ';\n' +
- p.END_STRUCT;
-
- return 'uniform ' + p.MATRIX4 + ' worldViewProjection' +
- p.semanticSuffix('WORLDVIEWPROJECTION') + ';\n' +
- 'uniform ' + p.MATRIX4 + ' worldInverseTranspose' +
- p.semanticSuffix('WORLDINVERSETRANSPOSE') + ';\n' +
- 'uniform ' + p.MATRIX4 + ' world' +
- p.semanticSuffix('WORLD') + ';\n' +
- '\n' +
- p.BEGIN_IN_STRUCT +
- p.ATTRIBUTE + p.FLOAT4 + ' position' +
- p.semanticSuffix('POSITION') + ';\n' +
- p.ATTRIBUTE + p.FLOAT3 + ' normal' +
- p.semanticSuffix('NORMAL') + ';\n' +
- p.ATTRIBUTE + p.FLOAT2 + ' texCoord0' +
- p.semanticSuffix('TEXCOORD0') + ';\n' +
- p.END_STRUCT +
- '\n' +
- varyingDecls +
- '\n' +
- p.beginVertexShaderMain() +
- ' ' + p.VERTEX_VARYING_PREFIX + 'position = ' +
- p.mul(p.ATTRIBUTE_PREFIX + 'position',
- 'worldViewProjection') + ';\n' +
- ' ' + p.VERTEX_VARYING_PREFIX + 'normal = ' +
- p.mul(p.FLOAT4 + '(' +
- p.ATTRIBUTE_PREFIX + 'normal, 0.0)',
- 'worldInverseTranspose') + '.xyz;\n' +
- ' ' + p.VERTEX_VARYING_PREFIX + 'worldPosition = ' +
- p.mul(p.ATTRIBUTE_PREFIX + 'position', 'world') +
- '.xyz;\n' +
- ' ' + p.VERTEX_VARYING_PREFIX + 'texCoord = ' +
- p.ATTRIBUTE_PREFIX + 'texCoord0;\n' +
- p.endVertexShaderMain() +
- '\n' +
- p.pixelShaderHeader() +
- 'uniform ' + p.FLOAT4 + ' color1;\n' +
- 'uniform ' + p.FLOAT4 + ' color2;\n' +
- 'uniform float checkSize;\n' +
- 'uniform ' + p.FLOAT3 + ' lightWorldPos;\n' +
- 'uniform ' + p.FLOAT3 + ' lightColor;\n' +
- '\n' +
- p.repeatVaryingDecls(varyingDecls) +
- p.FLOAT4 + ' checker(' + p.FLOAT2 + ' uv) {\n' +
- ' float fmodResult = ' + p.MOD + '(' +
- ' floor(checkSize * uv.x) + \n' +
- ' floor(checkSize * uv.y), 2.0);\n' +
- ' return (fmodResult < 1.0) ? color1 : color2;\n' +
- '}\n\n' +
- p.beginPixelShaderMain() +
- ' ' + p.FLOAT3 + ' surfaceToLight = \n' +
- ' normalize(lightWorldPos - ' +
- p.PIXEL_VARYING_PREFIX + 'worldPosition);\n' +
- ' ' + p.FLOAT3 + ' worldNormal = normalize(' +
- p.PIXEL_VARYING_PREFIX + 'normal);\n' +
- ' ' + p.FLOAT4 + ' check = checker(' +
- p.PIXEL_VARYING_PREFIX + 'texCoord);\n' +
- ' float directionalIntensity = \n' +
- ' clamp(dot(worldNormal, surfaceToLight), 0.0, 1.0);\n' +
- ' ' + p.FLOAT4 +
- ' outColor = directionalIntensity * check;\n' +
- p.endPixelShaderMain(
- p.FLOAT4 + '(outColor.rgb, check.a)') +
- '\n' +
- p.entryPoints() +
- p.matrixLoadOrder();
-};
-
-
-
-/**
- * The name of the parameter on a material if it's a collada standard
- * material.
- *
- * NOTE: This parameter is just a string attached to a material. It has no
- * meaning to the plugin, it is passed from the conditioner to the
- * javascript libraries so that they can build collada like effects.
- *
- * @type {string}
- */
-o3djs.effect.COLLADA_LIGHTING_TYPE_PARAM_NAME = 'collada.lightingType';
-
-/**
- * The collada standard lighting types.
- * @type {!Object}
- */
-o3djs.effect.COLLADA_LIGHTING_TYPES = {phong: 1,
- lambert: 1,
- blinn: 1,
- constant: 1};
-
-/**
- * The FCollada standard materials sampler parameter name prefixes.
- * @type {!Array.<string>}
- */
-o3djs.effect.COLLADA_SAMPLER_PARAMETER_PREFIXES = ['emissive',
- 'ambient',
- 'diffuse',
- 'specular',
- 'bump'];
-
-/**
- * Check if lighting type is a collada lighting type.
- * @param {string} lightingType Lighting type to check.
- * @return {boolean} true if it's a collada lighting type.
- */
-o3djs.effect.isColladaLightingType = function(lightingType) {
- return o3djs.effect.COLLADA_LIGHTING_TYPES[lightingType.toLowerCase()] == 1;
-};
-
-/**
- * Returns the collada lighting type of a collada standard material.
- * @param {!o3d.Material} material Material to get lighting type from.
- * @return {string} The lighting type or "" if it's not a collada standard
- * material.
- */
-o3djs.effect.getColladaLightingType = function(material) {
- var lightingTypeParam = material.getParam(
- o3djs.effect.COLLADA_LIGHTING_TYPE_PARAM_NAME);
- if (lightingTypeParam) {
- var lightingType = lightingTypeParam.value.toLowerCase();
- if (o3djs.effect.isColladaLightingType(lightingType)) {
- return lightingType;
- }
- }
- return '';
-};
-
-/**
- * Get the number of TEXCOORD streams needed by this material.
- * @param {!o3d.Material} material The material MUST be a standard
- * collada material.
- * @return {number} The number oc TEXCOORD streams needed.
- */
-o3djs.effect.getNumTexCoordStreamsNeeded = function(material) {
- var p = o3djs.effect;
- var lightingType = p.getColladaLightingType(material);
- if (!p.isColladaLightingType(lightingType)) {
- throw 'not a collada standard material';
- }
- var colladaSamplers = p.COLLADA_SAMPLER_PARAMETER_PREFIXES;
- var numTexCoordStreamsNeeded = 0
- for (var cc = 0; cc < colladaSamplers.length; ++cc) {
- var samplerPrefix = colladaSamplers[cc];
- var samplerParam = material.getParam(samplerPrefix + 'Sampler');
- if (samplerParam) {
- ++numTexCoordStreamsNeeded;
- }
- }
- return numTexCoordStreamsNeeded;
-};
-
-/**
- * Loads shader source from an external file and creates shaders for an effect.
- * @param {!o3d.Effect} effect The effect to create the shaders in.
- * @param {string} url The url of the shader source.
- */
-o3djs.effect.loadEffect = function(effect, url) {
- var fxString = o3djs.io.loadTextFileSynchronous(url);
- effect.loadFromFXString(fxString);
-};
-
-/**
- * Creates an effect from a file.
- * If the effect already exists in the pack that effect will be returned.
- * @param {!o3d.Pack} pack Pack to create effect in.
- * @param {string} url Url for effect file.
- * @return {!o3d.Effect} The effect.
- */
-o3djs.effect.createEffectFromFile = function(pack, url) {
- var p = o3djs.effect;
- var effect = pack.getObjects(url, 'o3d.Effect')[0];
- if (!effect) {
- effect = pack.createObject('Effect');
- p.loadEffect(effect, url);
- effect.name = url;
- }
- return effect;
-};
-
-/**
- * Builds a shader string for a given standard COLLADA material type.
- *
- * @param {!o3d.Material} material Material for which to build the shader.
- * @param {string} effectType Type of effect to create ('phong', 'lambert',
- * 'constant', 'blinn').
- * @param {Object} opt_options Parameters to customize shader code generation.
- See o3djs.effect.getStandardShader for details on the possible values.
- * @return {{description: string, shader: string}} A description and the shader
- * string.
- */
-o3djs.effect.buildStandardShaderString = function(material,
- effectType,
- opt_options) {
- if (!opt_options) {
- opt_options = {};
- }
- var numLights = 0;
- var currentLightWorldPos = 'lightWorldPos';
- if (opt_options.lights) {
- numLights = opt_options.lights;
- currentLightWorldPos = 'lightWorldPosList[i]';
- }
- var p = o3djs.effect;
- var bumpSampler = material.getParam('bumpSampler');
- var bumpUVInterpolant;
- var skinning;
-
- var maxSkinInfluences = 4;
-
- // Hardcode reasonable maximum for number of skinning uniforms.
- // glsl: Table 6.19: minimum MAX_VERTEX_UNIFORM_VECTORS is 128.
- // (DX9 requires a minimum of 256, so not a problem in o3d).
- var maxSkinUniforms = 36 * 3;
- if (o3djs.base.o3d && o3djs.base.o3d.SkinEval &&
- o3djs.base.o3d.SkinEval.getMaxNumBones) {
- maxSkinUniforms = o3d.SkinEval.getMaxNumBones(material) * 3;
- skinning = true;
- } else {
- skinning = false;
- }
-
- /**
- * Extracts the texture type from a texture param.
- * @param {!o3d.ParamTexture} textureParam The texture parameter to
- * inspect.
- * @return {string} The texture type (1D, 2D, 3D or CUBE).
- */
- var getTextureType = function(textureParam) {
- var texture = textureParam.value;
- if (!texture) return '2D'; // No texture value, have to make a guess.
- switch (texture.className) {
- case 'o3d.Texture1D' : return '1D';
- case 'o3d.Texture2D' : return '2D';
- case 'o3d.Texture3D' : return '3D';
- case 'o3d.TextureCUBE' : return 'CUBE';
- default : return '2D';
- }
- }
-
- /**
- * Extracts the sampler type from a sampler param. It does it by inspecting
- * the texture associated with the sampler.
- * @param {!o3d.ParamTexture} samplerParam The texture parameter to
- * inspect.
- * @return {string} The texture type (1D, 2D, 3D or CUBE).
- */
- var getSamplerType = function(samplerParam) {
- var sampler = samplerParam.value;
- if (!sampler) return '2D';
- var textureParam = sampler.getParam('Texture');
- if (textureParam)
- return getTextureType(textureParam);
- else
- return '2D';
- };
-
- /**
- * Builds uniform variables common to all standard lighting types.
- * @return {string} The effect code for the common shader uniforms.
- */
- var buildCommonVertexUniforms = function() {
- //var size = numLights ? '['+numLights+']' : '';
- return 'uniform ' + p.MATRIX4 + ' worldViewProjection' +
- p.semanticSuffix('WORLDVIEWPROJECTION') + ';\n';
- };
-
- /**
- * Builds uniform variables common to all standard lighting types.
- * @return {string} The effect code for the common shader uniforms.
- */
- var buildCommonPixelUniforms = function() {
- if (numLights > 0) {
- return 'uniform ' + p.FLOAT4 + ' lightColorList[' + numLights + '];\n' +
- 'uniform ' + p.FLOAT3 + ' lightWorldPosList[' + numLights + '];\n';
- } else {
- return 'uniform ' + p.FLOAT4 + ' lightColor;\n' +
- 'uniform ' + p.FLOAT3 + ' lightWorldPos' + ';\n';
- }
- };
-
- /**
- * Builds uniform variables common to lambert, phong and blinn lighting types.
- * @return {string} The effect code for the common shader uniforms.
- */
- var buildLightingUniforms = function() {
- return 'uniform ' + p.MATRIX4 + ' world' +
- p.semanticSuffix('WORLD') + ';\n' +
- 'uniform ' + p.MATRIX4 +
- ' viewInverse' + p.semanticSuffix('VIEWINVERSE') + ';\n' +
- 'uniform ' + p.MATRIX4 + ' worldInverseTranspose' +
- p.semanticSuffix('WORLDINVERSETRANSPOSE') + ';\n';
- };
-
- /**
- * If skinning is enabled, builds the bone matrix uniform variables needed
- * for skinning. Otherwise, returns the empty string.
- * @return {string} The effect code for skinning uniforms.
- */
- var buildSkinningUniforms = function() {
- return skinning ? 'uniform ' + p.FLOAT4 + ' boneToWorld3x4' +
- '[' + maxSkinUniforms + '];\n' +
- 'uniform float usingSkinShader;\n' : '';
- };
-
- /**
- * Builds uniform parameters for a given color input. If the material
- * has a sampler parameter, a sampler uniform is created, otherwise a
- * float4 color value is created.
- * @param {!o3d.Material} material The material to inspect.
- * @param {!Array.<string>} descriptions Array to add descriptions too.
- * @param {string} name The name of the parameter to look for. Usually
- * emissive, ambient, diffuse or specular.
- * @param {boolean} opt_addColorParam Whether to add a color param if no
- * sampler exists. Default = true.
- * @return {string} The effect code for the uniform parameter.
- */
- var buildColorParam = function(material, descriptions, name,
- opt_addColorParam) {
- if (opt_addColorParam === undefined) {
- opt_addColorParam = true;
- }
- var samplerParam = material.getParam(name + 'Sampler');
- if (samplerParam) {
- var type = getSamplerType(samplerParam);
- descriptions.push(name + type + 'Texture');
- return 'uniform sampler' + type + ' ' + name + 'Sampler;\n'
- } else if (opt_addColorParam) {
- descriptions.push(name + 'Color');
- return 'uniform ' + p.FLOAT4 + ' ' + name + ';\n';
- } else {
- return '';
- }
- };
-
- /**
- * Builds the effect code to retrieve a given color input. If the material
- * has a sampler parameter of that name, a texture lookup is done. Otherwise
- * it's a no-op, since the value is retrieved directly from the color uniform
- * of that name.
- * @param {!o3d.Material} material The material to inspect.
- * @param {string} name The name of the parameter to look for. Usually
- * emissive, ambient, diffuse or specular.
- * @return {string} The effect code for the uniform parameter retrieval.
- */
- var getColorParam = function(material, name) {
- var samplerParam = material.getParam(name + 'Sampler');
- if (samplerParam) {
- var type = getSamplerType(samplerParam);
- return ' ' + p.FLOAT4 + ' ' + name + ' = ' + p.TEXTURE + type +
- '(' + name + 'Sampler, ' +
- p.PIXEL_VARYING_PREFIX + name + 'UV);\n'
- } else {
- return '';
- }
- };
-
- /**
- * Begins a section of code which is to be run once for each light.
- * @return {string} The effect code for the for loop, or the empty string if
- * not using multiple lights.
- */
- var beginLightLoop = function() {
- if (numLights) {
- return ' ' + p.FLOAT4 + ' lightColorDiffuse = ' + p.FLOAT4 + '(0);\n' +
- ' for (int i = 0; i < ' + numLights + '; i++) {\n';
- } else {
- return '';
- }
- };
-
- /**
- * Ends the block of code which is to be run for each light. Adds the current
- * light's color times (diffuseExpression) into lightColorDiffuse.
- * @param {string} diffuseExpression Expression to multiply by light color.
- * @return {string} The effect code to set lightColorDiffuse.
- */
- var endLightLoop = function(diffuseExpression) {
- if (numLights) {
- return ' lightColorDiffuse += ' +
- 'lightColorList[i] * ( ' + diffuseExpression + ');\n' +
- ' }\n';
- } else {
- return ' ' + p.FLOAT4 + ' lightColorDiffuse = ' +
- 'lightColor * (' + diffuseExpression + ');';
- }
- };
-
- /**
- * Builds vertex and fragment shader string for the Constant lighting type.
- * @param {!o3d.Material} material The material for which to build
- * shaders.
- * @param {!Array.<string>} descriptions Array to add descriptions too.
- * @return {string} The effect code for the shader, ready to be parsed.
- */
- var buildConstantShaderString = function(material, descriptions) {
- descriptions.push('constant');
- return buildCommonVertexUniforms() +
- buildSkinningUniforms() +
- buildVertexDecls(material, false, false) +
- p.beginVertexShaderMain() +
- positionVertexShaderCode() +
- p.buildUVPassthroughs(material) +
- p.endVertexShaderMain() +
- p.pixelShaderHeader(material, false, false, bumpSampler) +
- buildCommonPixelUniforms() +
- p.repeatVaryingDecls() +
- buildColorParam(material, descriptions, 'emissive') +
- p.beginPixelShaderMain() +
- getColorParam(material, 'emissive') +
- p.endPixelShaderMain('emissive') +
- p.entryPoints() +
- p.matrixLoadOrder();
- };
-
- /**
- * Builds vertex and fragment shader string for the Lambert lighting type.
- * @param {!o3d.Material} material The material for which to build
- * shaders.
- * @param {!Array.<string>} descriptions Array to add descriptions too.
- * @return {string} The effect code for the shader, ready to be parsed.
- */
- var buildLambertShaderString = function(material, descriptions) {
- descriptions.push('lambert');
- return buildCommonVertexUniforms() +
- buildLightingUniforms() +
- buildSkinningUniforms() +
- buildVertexDecls(material, true, false) +
- p.beginVertexShaderMain() +
- p.buildUVPassthroughs(material) +
- positionVertexShaderCode() +
- normalVertexShaderCode() +
- surfacePositionVertexShaderCode() +
- bumpVertexShaderCode() +
- p.endVertexShaderMain() +
- p.pixelShaderHeader(material, true, false) +
- buildCommonPixelUniforms() +
- p.repeatVaryingDecls() +
- buildColorParam(material, descriptions, 'emissive') +
- buildColorParam(material, descriptions, 'ambient') +
- buildColorParam(material, descriptions, 'diffuse') +
- buildColorParam(material, descriptions, 'bump', false) +
- p.utilityFunctions() +
- p.beginPixelShaderMain() +
- getColorParam(material, 'emissive') +
- getColorParam(material, 'ambient') +
- getColorParam(material, 'diffuse') +
- getNormalShaderCode() +
- beginLightLoop() +
- ' ' + p.FLOAT3 + ' surfaceToLight = normalize(' +
- currentLightWorldPos + ' - ' +
- p.PIXEL_VARYING_PREFIX + 'surfacePosition);\n' +
- ' ' + p.FLOAT4 +
- ' litR = lit(dot(normal, surfaceToLight), 0.0, 0.0);\n' +
- endLightLoop('ambient * diffuse + diffuse * litR.y') +
- p.endPixelShaderMain(p.FLOAT4 +
- '((emissive +\n' +
- ' lightColorDiffuse).rgb,\n' +
- ' diffuse.a)') +
- p.entryPoints() +
- p.matrixLoadOrder();
- };
-
- /**
- * Builds vertex and fragment shader string for the Blinn lighting type.
- * @param {!o3d.Material} material The material for which to build
- * shaders.
- * @param {!Array.<string>} descriptions Array to add descriptions too.
- * @return {string} The effect code for the shader, ready to be parsed.
- * TODO: This is actually just a copy of the Phong code.
- * Change to Blinn.
- */
- var buildBlinnShaderString = function(material, descriptions) {
- descriptions.push('phong');
- return buildCommonVertexUniforms() +
- buildLightingUniforms() +
- buildSkinningUniforms() +
- buildVertexDecls(material, true, true) +
- p.beginVertexShaderMain() +
- p.buildUVPassthroughs(material) +
- positionVertexShaderCode() +
- normalVertexShaderCode() +
- surfacePositionVertexShaderCode() +
- surfaceToViewVertexShaderCode() +
- bumpVertexShaderCode() +
- p.endVertexShaderMain() +
- p.pixelShaderHeader(material, true, true) +
- buildCommonPixelUniforms() +
- p.repeatVaryingDecls() +
- buildColorParam(material, descriptions, 'emissive') +
- buildColorParam(material, descriptions, 'ambient') +
- buildColorParam(material, descriptions, 'diffuse') +
- buildColorParam(material, descriptions, 'specular') +
- buildColorParam(material, descriptions, 'bump', false) +
- 'uniform float shininess;\n' +
- 'uniform float specularFactor;\n' +
- p.utilityFunctions() +
- p.beginPixelShaderMain() +
- getColorParam(material, 'emissive') +
- getColorParam(material, 'ambient') +
- getColorParam(material, 'diffuse') +
- getColorParam(material, 'specular') +
- getNormalShaderCode() +
- ' ' + p.FLOAT3 + ' surfaceToView = normalize(' +
- p.PIXEL_VARYING_PREFIX + 'surfaceToView);\n' +
- beginLightLoop() +
- ' ' + p.FLOAT3 + ' surfaceToLight = normalize(' +
- currentLightWorldPos + ' - ' +
- p.PIXEL_VARYING_PREFIX + 'surfacePosition);\n' +
- ' ' + p.FLOAT3 +
- ' halfVector = normalize(surfaceToLight + surfaceToView);\n' +
- ' ' + p.FLOAT4 +
- ' litR = lit(dot(normal, surfaceToLight), \n' +
- ' dot(normal, halfVector), shininess);\n' +
- endLightLoop('ambient * diffuse + diffuse * litR.y\n' +
- ' + specular * litR.z * specularFactor') +
- p.endPixelShaderMain( p.FLOAT4 +
- '((emissive + lightColorDiffuse).rgb,\n' +
- ' diffuse.a)') +
- p.entryPoints() +
- p.matrixLoadOrder();
- };
-
- /**
- * Builds vertex and fragment shader string for the Phong lighting type.
- * @param {!o3d.Material} material The material for which to build
- * shaders.
- * @param {!Array.<string>} descriptions Array to add descriptions too.
- * @return {string} The effect code for the shader, ready to be parsed.
- */
- var buildPhongShaderString = function(material, descriptions) {
- descriptions.push('phong');
- return buildCommonVertexUniforms() +
- buildLightingUniforms() +
- buildSkinningUniforms() +
- buildVertexDecls(material, true, true) +
- p.beginVertexShaderMain() +
- p.buildUVPassthroughs(material) +
- positionVertexShaderCode() +
- normalVertexShaderCode() +
- surfacePositionVertexShaderCode() +
- surfaceToViewVertexShaderCode() +
- bumpVertexShaderCode() +
- p.endVertexShaderMain() +
- p.pixelShaderHeader(material, true, true) +
- buildCommonPixelUniforms() +
- p.repeatVaryingDecls() +
- buildColorParam(material, descriptions, 'emissive') +
- buildColorParam(material, descriptions, 'ambient') +
- buildColorParam(material, descriptions, 'diffuse') +
- buildColorParam(material, descriptions, 'specular') +
- buildColorParam(material, descriptions, 'bump', false) +
- 'uniform float shininess;\n' +
- 'uniform float specularFactor;\n' +
- p.utilityFunctions() +
- p.beginPixelShaderMain() +
- getColorParam(material, 'emissive') +
- getColorParam(material, 'ambient') +
- getColorParam(material, 'diffuse') +
- getColorParam(material, 'specular') +
- getNormalShaderCode() +
- ' ' + p.FLOAT3 + ' surfaceToView = normalize(' +
- p.PIXEL_VARYING_PREFIX + 'surfaceToView);\n' +
- beginLightLoop() +
- ' ' + p.FLOAT3 + ' surfaceToLight = normalize(' +
- currentLightWorldPos + ' - ' +
- p.PIXEL_VARYING_PREFIX + 'surfacePosition);\n' +
- ' ' + p.FLOAT3 +
- ' halfVector = normalize(surfaceToLight + surfaceToView);\n' +
- ' ' + p.FLOAT4 +
- ' litR = lit(dot(normal, surfaceToLight), \n' +
- ' dot(normal, halfVector), shininess);\n' +
- endLightLoop('ambient * diffuse + diffuse * litR.y +\n' +
- ' + specular * litR.z * specularFactor') +
- p.endPixelShaderMain(p.FLOAT4 +
- '((emissive + lightColorDiffuse).rgb,\n' +
- ' diffuse.a)') +
- p.entryPoints() +
- p.matrixLoadOrder();
- };
-
- /**
- * Builds the position code for the vertex shader.
- * @return {string} The code for the vertex shader.
- */
- var positionVertexShaderCode = function() {
- var attribute_position = p.ATTRIBUTE_PREFIX + 'position';
- if (skinning) {
- return ' ' + p.FLOAT4 + ' weightedpos = ' + attribute_position + ';\n' +
- ' for (int i = 0; i < ' + maxSkinInfluences + '; i++) {\n' +
- ' ' + p.FLOAT4 + ' temp = ' + p.FLOAT4 + '(' +
- 'dot(boneToWorld3x4[int(influenceIndices[i] * 3.0)], ' +
- attribute_position + '),\n' +
- ' dot(boneToWorld3x4[int(influenceIndices[i] * 3.0 + 1.0)], ' +
- attribute_position + '),\n' +
- ' dot(boneToWorld3x4[int(influenceIndices[i] * 3.0 + 2.0)], ' +
- attribute_position + '),\n' +
- ' 1.0);\n' +
- ' weightedpos += usingSkinShader * influenceWeights[i] * ' +
- '(temp - ' + attribute_position + ');\n' +
- ' }\n' +
- ' ' + p.VERTEX_VARYING_PREFIX + 'position = ' +
- p.mul('weightedpos', 'worldViewProjection') + ';\n';
- } else {
- return ' ' + p.VERTEX_VARYING_PREFIX + 'position = ' +
- p.mul(attribute_position, 'worldViewProjection') + ';\n';
- }
- };
-
- /**
- * Builds the normal code for the vertex shader.
- * @return {string} The code for the vertex shader.
- */
- var normalVertexShaderCode = function() {
- var attribute_normal = p.ATTRIBUTE_PREFIX + 'normal';
- if (skinning) {
- return ' ' + p.FLOAT3 + ' weightednorm = ' + attribute_normal + ';\n' +
- ' for (int i = 0; i < ' + maxSkinInfluences + '; i++) {\n' +
- ' ' + p.FLOAT3 + ' temp = ' + p.FLOAT3 + '(' +
- 'dot(boneToWorld3x4[int(influenceIndices[i] * 3.0)].xyz, ' +
- attribute_normal + '),\n' +
- ' dot(boneToWorld3x4[int(influenceIndices[i] * 3.0 + 1.0)].xyz, ' +
- attribute_normal + '),\n' +
- ' dot(boneToWorld3x4[int(influenceIndices[i] * 3.0 + 2.0)].xyz, ' +
- attribute_normal + '));\n' +
- ' weightednorm += usingSkinShader * influenceWeights[i] * ' +
- '(temp - ' + attribute_normal + ');\n' +
- ' }\n' +
- ' ' + p.VERTEX_VARYING_PREFIX + 'normal = ' +
- p.mul(p.FLOAT4 + '(' + 'weightednorm' + ', 0)',
- 'worldInverseTranspose') + '.xyz;\n';
- } else {
- return ' ' + p.VERTEX_VARYING_PREFIX + 'normal = ' +
- p.mul(p.FLOAT4 + '(' +
- attribute_normal + ', 0)', 'worldInverseTranspose') +
- '.xyz;\n';
- }
- };
-
- /**
- * Builds the surface position code for the vertex shader. To support
- * multiple lights, the dot product with each light should then be
- * computed in the fragment shader.
- * @return {string} The code for the vertex shader.
- */
- var surfacePositionVertexShaderCode = function() {
- return ' ' + p.VERTEX_VARYING_PREFIX +
- 'surfacePosition = \n' +
- p.mul(p.ATTRIBUTE_PREFIX + 'position',
- 'world') + '.xyz;\n';
- };
-
- /**
- * Builds the surface to view code for the vertex shader.
- * @return {string} The code for the vertex shader.
- */
- var surfaceToViewVertexShaderCode = function() {
- return ' ' + p.VERTEX_VARYING_PREFIX +
- 'surfaceToView = (viewInverse[3] - ' +
- p.mul(p.ATTRIBUTE_PREFIX + 'position', 'world') + ').xyz;\n';
- };
-
- /**
- * Builds the normal map part of the vertex shader.
- * @param {boolean} opt_bumpSampler Whether there is a bump
- * sampler. Default = false.
- * @return {string} The code for normal mapping in the vertex shader.
- */
- var bumpVertexShaderCode = function(opt_bumpSampler) {
- return bumpSampler ?
- (' ' + p.VERTEX_VARYING_PREFIX + 'binormal = ' +
- p.mul(p.FLOAT4 + '(' +
- p.ATTRIBUTE_PREFIX + 'binormal, 0)',
- 'worldInverseTranspose') + '.xyz;\n' +
- ' ' + p.VERTEX_VARYING_PREFIX + 'tangent = ' +
- p.mul(p.FLOAT4 +
- '(' + p.ATTRIBUTE_PREFIX + 'tangent, 0)',
- 'worldInverseTranspose') + '.xyz;\n') : '';
- };
-
- /**
- * Builds the normal calculation of the pixel shader.
- * @return {string} The code for normal computation in the pixel shader.
- */
- var getNormalShaderCode = function() {
- return bumpSampler ?
- (p.MATRIX3 + ' tangentToWorld = ' + p.MATRIX3 +
- '(' + p.ATTRIBUTE_PREFIX + 'tangent,\n' +
- ' ' +
- p.ATTRIBUTE_PREFIX + 'binormal,\n' +
- ' ' +
- p.ATTRIBUTE_PREFIX + 'normal);\n' +
- p.FLOAT3 + ' tangentNormal = ' + p.TEXTURE + '2D' + '(bumpSampler, ' +
- p.ATTRIBUTE_PREFIX + 'bumpUV.xy).xyz -\n' +
- ' ' + p.FLOAT3 +
- '(0.5, 0.5, 0.5);\n' + p.FLOAT3 + ' normal = ' +
- p.mul('tangentNormal', 'tangentToWorld') + ';\n' +
- 'normal = normalize(' + p.PIXEL_VARYING_PREFIX +
- 'normal);\n') : ' ' + p.FLOAT3 + ' normal = normalize(' +
- p.PIXEL_VARYING_PREFIX + 'normal);\n';
- };
-
- /**
- * Builds the vertex declarations for a given material.
- * @param {!o3d.Material} material The material to inspect.
- * @param {boolean} diffuse Whether to include stuff for diffuse
- * calculations.
- * @param {boolean} specular Whether to include stuff for diffuse
- * calculations.
- * @return {string} The code for the vertex declarations.
- */
- var buildVertexDecls = function(material, diffuse, specular) {
- return p.buildAttributeDecls(
- material, diffuse, specular, bumpSampler, skinning) +
- p.buildVaryingDecls(
- material, diffuse, specular, bumpSampler);
- };
-
-
- // Create a shader string of the appropriate type, based on the
- // effectType.
- var str;
- var descriptions = [];
- if (effectType == 'phong') {
- str = buildPhongShaderString(material, descriptions);
- } else if (effectType == 'lambert') {
- str = buildLambertShaderString(material, descriptions);
- } else if (effectType == 'blinn') {
- str = buildBlinnShaderString(material, descriptions);
- } else if (effectType == 'constant') {
- str = buildConstantShaderString(material, descriptions);
- } else {
- throw ('unknown effect type "' + effectType + '"');
- }
-
- return {description: descriptions.join('_'), shader: str};
-};
-
-/**
- * Gets or builds a shader for given standard COLLADA material type.
- *
- * Looks at the material passed in and assigns it an Effect that matches its
- * Params. If a suitable Effect already exists in pack it will use that Effect.
- *
- * @param {!o3d.Pack} pack Pack in which to create the new Effect.
- * @param {!o3d.Material} material Material for which to build the shader.
- * @param {string} effectType Type of effect to create ('phong', 'lambert',
- * 'constant', 'blinn').
- * @param {Object} opt_options Extra options in the form {lights: number}.
- * If 'lights' is non-zero, creates an array of light params; otherwise
- * only a single light is supported.
- * @return {o3d.Effect} The created effect.
- */
-o3djs.effect.getStandardShader = function(pack,
- material,
- effectType,
- opt_options) {
- var record = o3djs.effect.buildStandardShaderString(material,
- effectType,
- opt_options);
- var effects = pack.getObjectsByClassName('o3d.Effect');
- for (var ii = 0; ii < effects.length; ++ii) {
- if (effects[ii].name == record.description &&
- effects[ii].source == record.shader) {
- return effects[ii];
- }
- }
- var effect = pack.createObject('Effect');
- if (effect) {
- effect.name = record.description;
- if (effect.loadFromFXString(record.shader)) {
- return effect;
- }
- pack.removeObject(effect);
- }
- return null;
-};
-
-/**
- * Attaches a shader for a given standard COLLADA material type to the
- * material.
- *
- * Looks at the material passed in and assigns it an Effect that matches its
- * Params. If a suitable Effect already exists in pack it will use that Effect.
- *
- * @param {!o3d.Pack} pack Pack in which to create the new Effect.
- * @param {!o3d.Material} material Material for which to build the shader.
- * @param {!o3djs.math.Vector3} lightPos Position of the default light.
- * @param {string} effectType Type of effect to create ('phong', 'lambert',
- * 'constant', 'blinn').
- * @param {Object} opt_options Extra options for effect.getStandardShader
- * @return {boolean} True on success.
- */
-o3djs.effect.attachStandardShader = function(pack,
- material,
- lightPos,
- effectType,
- opt_options) {
- var effect = o3djs.effect.getStandardShader(pack,
- material,
- effectType,
- opt_options);
- if (effect) {
- material.effect = effect;
- effect.createUniformParameters(material);
-
- // Set a couple of the default parameters in the hopes that this will
- // help the user get something on the screen. We check to make sure they
- // are not connected to something otherwise we'll get an error.
- var param = material.getParam('lightWorldPos');
- if (param && !param.inputConnection) {
- param.value = lightPos;
- }
- var param = material.getParam('lightColor');
- if (param && !param.inputConnection) {
- param.value = [1, 1, 1, 1];
- }
- return true;
- } else {
- return false;
- }
-};
-
-/**
- * Creates the uniform parameters needed for an Effect on the given ParamObject.
- * @param {!o3d.Pack} pack Pack to create extra objects in like Samplers and
- * ParamArrays.
- * @param {!o3d.Effect} effect Effect.
- * @param {!o3d.ParamObject} paramObject ParamObject on which to create Params.
- */
-o3djs.effect.createUniformParameters = function(pack, effect, paramObject) {
- effect.createUniformParameters(paramObject);
- var infos = effect.getParameterInfo();
- for (var ii = 0; ii < infos.length; ++ii) {
- var info = infos[ii];
- if (info.sasClassName.length == 0) {
- if (info.numElements > 0) {
- var paramArray = pack.createObject('ParamArray');
- var param = paramObject.getParam(info.name);
- param.value = paramArray;
- paramArray.resize(info.numElements, info.className);
- if (info.className == 'o3d.ParamSampler') {
- for (var jj = 0; jj < info.numElements; ++jj) {
- var sampler = pack.createObject('Sampler');
- paramArray.getParam(jj).value = sampler;
- }
- }
- } else if (info.className == 'o3d.ParamSampler') {
- var sampler = pack.createObject('Sampler');
- var param = paramObject.getParam(info.name);
- param.value = sampler;
- }
- }
- }
-};
-
-/**
- * Creates an effect that draws a 2 color procedural checker pattern.
- * @param {!o3d.Pack} pack The pack to create the effect in. If the pack
- * already has an effect with the same name that effect will be returned.
- * @return {!o3d.Effect} The effect.
- */
-o3djs.effect.createCheckerEffect = function(pack) {
- var effects = pack.getObjects(o3djs.effect.TWO_COLOR_CHECKER_EFFECT_NAME,
- 'o3d.Effect');
- if (effects.length > 0) {
- return effects[0];
- }
-
- var effect = pack.createObject('Effect');
- effect.loadFromFXString(o3djs.effect.TWO_COLOR_CHECKER_FXSTRING);
- effect.name = o3djs.effect.TWO_COLOR_CHECKER_EFFECT_NAME;
- return effect;
-};
-
-
-// For compatability with o3d code, the default language is o3d shading
-// language.
-o3djs.effect.setLanguage('o3d');
-
-
diff --git a/o3d/samples/o3djs/element.js b/o3d/samples/o3djs/element.js
deleted file mode 100644
index 0c4593b..0000000
--- a/o3d/samples/o3djs/element.js
+++ /dev/null
@@ -1,212 +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.
- */
-
-
-/**
- * @fileoverview This file contains various functions for helping setup
- * elements for o3d
- */
-
-o3djs.provide('o3djs.element');
-
-o3djs.require('o3djs.math');
-
-/**
- * A Module for element functions.
- * @namespace
- */
-o3djs.element = o3djs.element || {};
-
-/**
- * Sets the bounding box and z sort point of an element.
- * @param {!o3d.Element} element Element to set bounding box and z sort point
- * on.
- */
-o3djs.element.setBoundingBoxAndZSortPoint = function(element) {
- var boundingBox = element.getBoundingBox(0);
- var minExtent = boundingBox.minExtent;
- var maxExtent = boundingBox.maxExtent;
- element.boundingBox = boundingBox;
- element.cull = true;
- element.zSortPoint = o3djs.math.divVectorScalar(
- o3djs.math.addVector(minExtent, maxExtent), 2);
-};
-
-/**
- * Adds missing texture coordinate streams to a primitive.
- *
- * This is very application specific but if it's a primitive
- * and if it uses a collada material the material builder
- * assumes 1 TEXCOORD stream per texture. In other words if you have
- * both a specular texture AND a diffuse texture the builder assumes
- * you have 2 TEXCOORD streams. This assumption is often false.
- *
- * To work around this we check how many streams the material
- * expects and if there are not enough UVs streams we duplicate the
- * last TEXCOORD stream until there are, making a BIG assumption that
- * that will work.
- *
- * The problem is maybe you have 4 textures and each of them share
- * texture coordinates. There is information in the collada file about
- * what stream to connect each texture to.
- *
- * @param {!o3d.Element} element Element to add streams to.
- */
-o3djs.element.addMissingTexCoordStreams = function(element) {
- // TODO: We should store that info. The conditioner should either
- // make streams that way or pass on the info so we can do it here.
- if (element.isAClassName('o3d.Primitive')) {
- var material = /** @type {!o3d.Material} */ (element.material);
- var streamBank = element.streamBank;
- var lightingType = o3djs.effect.getColladaLightingType(material);
- if (lightingType) {
- var numTexCoordStreamsNeeded =
- o3djs.effect.getNumTexCoordStreamsNeeded(material);
- // Count the number of TEXCOORD streams the streamBank has.
- var streams = streamBank.vertexStreams;
- var lastTexCoordStream = null;
- var numTexCoordStreams = 0;
- for (var ii = 0; ii < streams.length; ++ii) {
- var stream = streams[ii];
- if (stream.semantic == o3djs.base.o3d.Stream.TEXCOORD) {
- lastTexCoordStream = stream;
- ++numTexCoordStreams;
- }
- }
- // Add any missing TEXCOORD streams. It might be more efficient for
- // the GPU to create an effect that doesn't need the extra streams
- // but this is a more generic solution because it means we can reuse
- // the same effect.
- for (var ii = numTexCoordStreams;
- ii < numTexCoordStreamsNeeded;
- ++ii) {
- streamBank.setVertexStream(
- lastTexCoordStream.semantic,
- lastTexCoordStream.semanticIndex + ii - numTexCoordStreams + 1,
- lastTexCoordStream.field,
- lastTexCoordStream.startIndex);
- }
- }
- }
-};
-
-/**
- * Copies an element and streambank or buffers so the two will share
- * streambanks, vertex and index buffers.
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.Element} sourceElement The element to copy.
- * @return {!o3d.Element} the new copy of sourceElement.
- */
-o3djs.element.duplicateElement = function(pack, sourceElement) {
- var newElement = pack.createObject(sourceElement.className);
- newElement.copyParams(sourceElement);
- // TODO: If we get the chance to parameterize the primitive's settings
- // we can delete this code since copyParams will handle it.
- // For now it only handles primitives by doing it manually.
- if (sourceElement.isAClassName('o3d.Primitive')) {
- newElement.indexBuffer = sourceElement.indexBuffer;
- newElement.startIndex = sourceElement.startIndex;
- newElement.primitiveType = sourceElement.primitiveType;
- newElement.numberVertices = sourceElement.numberVertices;
- newElement.numberPrimitives = sourceElement.numberPrimitives;
- }
- return newElement;
-};
-
-/**
- * Gets the normal for specific triangle in a Primitive in that Primitive's
- * local space.
- *
- * NOTE: THIS FUNCTION IS SLOW! If you want to do collisions you should use a
- * different solution.
- *
- * @param {!o3d.Primitive} primitive Primitive to get normal from. The
- * primitive MUST be a TRIANGLELIST or a TRIANGLESTRIP and it must have a
- * POSITION,0 stream.
- * @param {number} index Index of triangle.
- * @param {boolean} opt_winding The winding of the triangles of the
- * Primitive. False = Clockwise, True = Counterclockwise. The default is
- * false. This is only used for Primitives that have no normals.
- * @return {!o3djs.math.Vector3} The normal for the triangle.
- */
-o3djs.element.getNormalForTriangle = function(primitive, index, opt_winding) {
- // Check that we can do this
- var primitiveType = primitive.primitiveType;
- if (primitiveType != o3djs.base.o3d.Primitive.TRIANGLELIST &&
- primitiveType != o3djs.base.o3d.Primitive.TRIANGLESTRIP) {
- throw 'primitive is not a TRIANGLELIST or TRIANGLESTRIP';
- }
-
- var indexBuffer = primitive.indexBuffer;
- var vertexIndex = (primitiveType == o3djs.base.o3d.Primitive.TRIANGLELIST) ?
- (index * 3) : (index + 2);
- var vertexIndices;
- if (indexBuffer) {
- var indexField = indexBuffer.fields[0];
- vertexIndices = indexField.getAt(vertexIndex, 3);
- } else {
- vertexIndices = [vertexIndex, vertexIndex + 1, vertexIndex + 2]
- }
-
- var normalStream = primitive.streamBank.getVertexStream(
- o3djs.base.o3d.Stream.NORMAL, 0);
- if (normalStream) {
- var normalField = normalStream.field;
- // Look up the 3 normals that make the triangle.
- var summedNormal = [0, 0, 0];
- for (var ii = 0; ii < 3; ++ii) {
- var normal = normalField.getAt(vertexIndices[ii], 1);
- summedNormal = o3djs.math.addVector(summedNormal, normal);
- }
- return o3djs.math.normalize(summedNormal);
- } else {
- var positionStream = primitive.streamBank.getVertexStream(
- o3djs.base.o3d.Stream.POSITION, 0);
- if (!positionStream) {
- throw 'no POSITION,0 stream in primitive';
- }
- var positionField = positionStream.field;
- // Lookup the 3 positions that make the triangle.
- var positions = [];
- for (var ii = 0; ii < 3; ++ii) {
- positions[ii] = positionField.getAt(vertexIndices[ii], 1);
- }
-
- // Compute a face normal from the positions.
- var v0 = o3djs.math.normalize(o3djs.math.subVector(positions[1],
- positions[0]));
- var v1 = o3djs.math.normalize(o3djs.math.subVector(positions[2],
- positions[1]));
- return opt_winding ? o3djs.math.cross(v1, v0) : o3djs.math.cross(v0, v1);
- }
-};
-
-
diff --git a/o3d/samples/o3djs/error.js b/o3d/samples/o3djs/error.js
deleted file mode 100644
index 8fa16ad..0000000
--- a/o3d/samples/o3djs/error.js
+++ /dev/null
@@ -1,133 +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.
- */
-
-
-/**
- * @fileoverview This file contains various error handing functions for o3d.
- *
- */
-
-o3djs.provide('o3djs.error');
-
-/**
- * A Module with various error handing functions.
- *
- * This module is for helping to manage the client's error callback.
- * Because you can not read the current callback on the client we wrap it with
- * these utilities which track the last callback added so as long as you use
- * o3djs.error.setErrorHandler(client, callback) instead of
- * client.setErrorCallback you'll be able to get and restore the error callback
- * when you need to.
- * @namespace
- */
-o3djs.error = o3djs.error || {};
-
-/**
- * A map of error callbacks by client.
- * @private
- * @type {!Array.<(function(string): void|null)>}
- */
-o3djs.error.callbacks_ = [];
-
-/**
- * Sets the error handler on a client to a handler that manages the client's
- * error callback.
- * displays an alert on the first error.
- * @param {!o3d.Client} client The client object of the plugin.
- * @param {(function(string): void|null)} callback The callack to use, null to
- * clear.
- * @return {(function(string): void|null)} the previous error callback for this
- * client.
- */
-o3djs.error.setErrorHandler = function(client, callback) {
- var clientId = client.clientId;
- var old_callback = o3djs.error.callbacks_[clientId];
- o3djs.error.callbacks_[clientId] = callback;
- if (callback) {
- client.setErrorCallback(callback);
- } else {
- client.clearErrorCallback();
- }
- return old_callback;
-};
-
-/**
- * Sets a default error handler on the client.
- * The default error handler displays an alert on the first error encountered.
- * @param {!o3d.Client} client The client object of the plugin.
- */
-o3djs.error.setDefaultErrorHandler = function(client) {
- o3djs.error.setErrorHandler(
- client,
- function(msg) {
- // Clear the error callback. Otherwise if the callback is happening
- // during rendering it's possible the user will not be able to
- // get out of an infinite loop of alerts.
- o3djs.error.setErrorHandler(client, null);
- alert('ERROR: ' + msg);
- });
-};
-
-/**
- * Creates an ErrorCollector.
- * @param {!o3d.Client} client The client object of the plugin.
- * @return {!o3djs.error.ErrorCollector} The created error collector.
- */
-o3djs.error.createErrorCollector = function(client) {
- return new o3djs.error.ErrorCollector(client);
-};
-
-/**
- * An ErrorCollector takes over the client error callback and continues
- * to collect errors until ErrorCollector.finish() is called.
- * @constructor
- * @param {!o3d.Client} client The client object of the plugin.
- */
-o3djs.error.ErrorCollector = function(client) {
- var that = this;
- this.client_ = client;
- /**
- * The collected errors.
- * @type {!Array.<string>}
- */
- this.errors = [];
- this.oldCallback_ = o3djs.error.setErrorHandler(client, function(msg) {
- that.errors.push(msg);
- });
-};
-
-/**
- * Stops the ErrorCollector from collecting errors and restores the previous
- * error callback.
- */
-o3djs.error.ErrorCollector.prototype.finish = function() {
- o3djs.error.setErrorHandler(this.client_, this.oldCallback_);
-};
diff --git a/o3d/samples/o3djs/event.js b/o3d/samples/o3djs/event.js
deleted file mode 100644
index 333aa0c..0000000
--- a/o3d/samples/o3djs/event.js
+++ /dev/null
@@ -1,360 +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.
- */
-
-
-/**
- * @fileoverview This file contains various event related functions for
- * o3d. It puts them in the 'event' module on the o3djs object.
- *
- * TODO Add selenium tests.
- *
- *
- */
-o3djs.provide('o3djs.event');
-
-/**
- * A Module for handling events related to o3d and various browsers.
- * @namespace
- */
-o3djs.event = o3djs.event || {};
-
-/**
- * @param {string} inStr base string.
- * @param {string} extraStr string to append.
- * @return {string} inStr + ' ' + extraStr, or just inStr if extraStr is ''.
- */
-o3djs.event.appendWithSpace = function(inStr, extraStr) {
- return (inStr.length == 0) ? extraStr : inStr + ' ' + extraStr;
-};
-
-/**
- * @param {boolean} state whether to append or not.
- * @param {string} inStr base string.
- * @param {string} extraStr string to append.
- * @return {string} inStr + ' ' + extraStr, or just inStr if state is false.
- */
-o3djs.event.appendWithSpaceIf = function(state, inStr, extraStr) {
- return (state) ? o3djs.event.appendWithSpace(inStr, extraStr) : inStr;
-};
-
-
-/**
- * Builds a DOM-level 3 modifier string for a KeyboardEvent - see
- * http://www.w3.org/TR/DOM-Level-3-Events/events.html
- * #Events-KeyboardEvents-Interfaces.
- * @param {boolean} control whether the control key is down.
- * @param {boolean} alt whether the alt/option key is down.
- * @param {boolean} shift whether the shift key is down.
- * @param {boolean} meta whether the meta/command key is down.
- * @return {string} space delimited list of keys that are down.
- */
-o3djs.event.getModifierString = function(control, alt, shift, meta) {
- var modStr = o3djs.event.appendWithSpaceIf(control, '', 'Control');
- modStr = o3djs.event.appendWithSpaceIf(alt, modStr, 'Alt');
- modStr = o3djs.event.appendWithSpaceIf(shift, modStr, 'Shift');
- return o3djs.event.appendWithSpaceIf(meta, modStr, 'Meta');
-};
-
-
-/**
- * Pad a string with leading zeroes if needed until it is the length desired.
- * @param {string} str The input string, probably representing a number.
- * @param {number} to_length The desired minimum length of string with padding.
- * @return {string} A string padded with leading zeroes as needed to be the
- * length desired.
- */
-o3djs.event.padWithLeadingZeroes = function(str, to_length) {
- while (str.length < to_length)
- str = '0' + str;
- return str;
-};
-
-/**
- * Creates a keyIdentifer string for a given keystroke as specified in the w3c
- * spec on http://www.w3.org/TR/DOM-Level-3-Events/events.html.
- * @param {number} charCode numeric unicode code point as reported by the OS.
- * @param {number} keyCode numeric keyCode as reported by the OS, currently
- * unused but will probably be necessary in the future.
- * @return {string} eg 'Left' or 'U+0040'.
- */
-o3djs.event.getKeyIdentifier = function(charCode, keyCode) {
- if (!charCode) {
- // TODO: This works for webkit for keydown and keyup, for basic
- // alphanumeric keys, at least. Likely it needs lots of work to handle
- // accented characters, various keyboards, etc., as does the rest of our
- // keyboard event code.
- charCode = keyCode;
- }
- switch (charCode) {
- case 3: case 13: return 'Enter'; // spec merges these.
- case 37: return 'Left';
- case 39: return 'Right';
- case 38: return 'Up';
- case 40: return 'Down';
- }
- charCode = (charCode >= 97 && charCode <= 122) ? charCode - 32 : charCode;
- var keyStr = charCode.toString(16).toUpperCase();
- return 'U+' + o3djs.event.padWithLeadingZeroes(keyStr, 4);
-};
-
-
-/** Takes a keyIdentifier string and remaps it to an ASCII/Unicode value
- * suitable for javascript event handling.
- * @param {string} keyIdent a keyIdentifier string as generated above.
- * @return {number} the numeric Unicode code point represented.
- */
-o3djs.event.keyIdentifierToChar = function(keyIdent) {
- if (keyIdent && typeof(keyIdent) == 'string') {
- switch (keyIdent) {
- case 'Enter': return 13;
- case 'Left': return 37;
- case 'Right': return 39;
- case 'Up': return 38;
- case 'Down': return 40;
- }
- if (keyIdent.indexOf('U+') == 0)
- return parseInt(keyIdent.substr(2).toUpperCase(), 16);
- }
- return 0;
-};
-
-/**
- * Extracts the key char in number form from the event, in a cross-browser
- * manner.
- * @param {!Event} event .
- * @return {number} unicode code point for the key.
- */
-o3djs.event.getEventKeyChar = function(event) {
- if (!event) {
- event = window.event;
- }
- var charCode = 0;
- if (event.keyIdentifier)
- charCode = o3djs.event.keyIdentifierToChar(event.keyIdentifier);
- if (!charCode)
- charCode = (window.event) ? window.event.keyCode : event.charCode;
- if (!charCode)
- charCode = event.keyCode;
- return charCode;
-};
-
-
-/**
- * Cancel an event we've handled so it stops propagating upwards.
- * The cancelBubble is for IE, stopPropagation is for all other browsers.
- * preventDefault ensures that the default action is also canceled.
- * @param {!Event} event - the event to cancel.
- */
-o3djs.event.cancel = function(event) {
- if (!event)
- event = window.event;
- event.cancelBubble = true;
- if (event.stopPropagation)
- event.stopPropagation();
- if (event.preventDefault)
- event.preventDefault();
-};
-
-/**
- * Convenience function to setup synthesizing and dispatching of keyboard events
- * whenever the focussed plug-in calls Javascript to report a keyboard action.
- * @param {!Element} pluginObject the <object> where the o3d plugin lives,
- * which the caller probably obtained by calling getElementById.
- */
-o3djs.event.startKeyboardEventSynthesis = function(pluginObject) {
- var handler = function(event) {
- o3djs.event.onKey(event, pluginObject);
- };
-
- o3djs.event.addEventListener(pluginObject, 'keypress', handler);
- o3djs.event.addEventListener(pluginObject, 'keydown', handler);
- o3djs.event.addEventListener(pluginObject, 'keyup', handler);
-};
-
-/**
- * Dispatches a DOM-level 3 KeyboardEvent when called back by the plugin.
- * see http://www.w3.org/TR/DOM-Level-3-Events/events.html
- * #Events-KeyboardEvents-Interfaces
- * see http://developer.mozilla.org/en/DOM/event.initKeyEvent
- * @param {!Event} event an O3D event object.
- * @param {!Element} pluginObject the plugin object on the page.
- */
-o3djs.event.onKey = function(event, pluginObject) {
- var k_evt = o3djs.event.createKeyEvent(event.type, event.charCode,
- event.keyCode, event.ctrlKey, event.altKey, event.shiftKey,
- event.metaKey);
- if (k_evt) {
- if (pluginObject.parentNode.dispatchEvent) {
- // Using the pluginObject itself fails for non-capturing event listeners
- // on keypress events on Firefox only, as far as I've been able to
- // determine. I have no idea why.
- pluginObject.parentNode.dispatchEvent(k_evt);
- } else if (pluginObject.fireEvent) {
- pluginObject.fireEvent('on' + event.type, k_evt);
- }
- }
-};
-
-/**
- * Creates a DOM-level 3 KeyboardEvent.
- * see http://www.w3.org/TR/DOM-Level-3-Events/events.html
- * #Events-KeyboardEvents-Interfaces.
- * see http://developer.mozilla.org/en/DOM/event.initKeyEvent
- * @param {string} eventName one of 'keypress', 'keydown' or 'keyup'.
- * @param {number} charCode the character code for the key.
- * @param {number} keyCode the key code for the key.
- * @param {boolean} control whether the control key is down.
- * @param {boolean} alt whether the alt/option key is down.
- * @param {boolean} shift whether the shift key is down.
- * @param {boolean} meta whether the meta/command key is down.
- */
-o3djs.event.createKeyEvent = function(eventName, charCode, keyCode,
- control, alt, shift, meta) {
- var k_evt;
- var keyIdentifier = o3djs.event.getKeyIdentifier(charCode, keyCode);
- if (document.createEvent) {
- k_evt = document.createEvent('KeyboardEvent');
- if (k_evt.initKeyboardEvent) { // WebKit.
- k_evt.initKeyboardEvent(eventName, true, true, window,
- keyIdentifier, 0,
- control, alt, shift, meta);
- // TODO: These actually fail to do anything in Chrome; those are
- // read-only fields, and it's not setting them in initKeyboardEvent.
- k_evt.charCode = charCode;
- if (eventName == 'keypress')
- k_evt.keyCode = charCode;
- else
- k_evt.keyCode = keyCode;
- } else if (k_evt.initKeyEvent) { // FF.
- k_evt.initKeyEvent(eventName, true, true, window,
- control, alt, shift, meta, keyCode, charCode);
- k_evt.keyIdentifier = keyIdentifier;
- }
- } else if (document.createEventObject) {
- k_evt = document.createEventObject();
- k_evt.ctrlKey = control;
- k_evt.altKey = alt;
- k_evt.shiftKey = shift;
- k_evt.metaKey = meta;
- k_evt.keyCode = charCode; // Emulate IE charcode-in-the-keycode onkeypress.
- k_evt.keyIdentifier = keyIdentifier;
- }
- k_evt.synthetic = true;
- return k_evt;
-};
-
-/*
- * Function to create a closure that will call each event handler in an array
- * whenever it gets called, passing its single argument through to the
- * sub-handlers. The sub-handlers may either be functions or EventListeners.
- * This is generally expected to be used only through
- * o3djs.event.addEventListener.
- * @param {!Array.<*>} listenerSet an array of handlers.
- * @return {!function(*): void} a closure to be used to multiplex out
- * event-handling.
- */
-o3djs.event.createEventHandler = function(listenerSet) {
- return function(event) {
- var length = listenerSet.length;
- for (var index = 0; index < length; ++index) {
- var handler = listenerSet[index];
- if (typeof(handler.handleEvent) == 'function') {
- handler.handleEvent(event);
- } else {
- handler(event);
- }
- }
- }
-};
-
-/**
- * Convenience function to manage event listeners on the o3d plugin object,
- * intended as a drop-in replacement for the DOM addEventListener [with slightly
- * different arguments, but the same effect].
- * @param {!Element} pluginObject the html object where the o3d plugin lives,
- * which the caller probably obtained by calling getElementById or makeClients.
- * @param {string} type the event type on which to trigger, e.g. 'mousedown',
- * 'mousemove', etc.
- * @param {!Object} handler either a function or an EventListener object.
- */
-o3djs.event.addEventListener = function(pluginObject, type, handler) {
- if (!handler || typeof(type) != 'string' ||
- (typeof(handler) != 'function' &&
- typeof(handler.handleEvent) != 'function')) {
- throw new Error('Invalid argument.');
- }
- pluginObject.o3d_eventRegistry = pluginObject.o3d_eventRegistry || [];
- var registry = pluginObject.o3d_eventRegistry;
- var listenerSet = registry[type];
- if (!listenerSet || listenerSet.length == 0) {
- listenerSet = registry[type] = [];
- pluginObject.client.setEventCallback(type,
- o3djs.event.createEventHandler(listenerSet));
- } else {
- for (var index in listenerSet) {
- if (listenerSet[index] == handler) {
- return; // We're idempotent.
- }
- }
- }
- listenerSet.push(handler);
-};
-
-
-/**
- * Convenience function to manage event listeners on the o3d plugin object,
- * intended as a drop-in replacement for the DOM removeEventListener [with
- * slightly different arguments, but the same effect].
- * @param {!Element} pluginObject the <object> where the o3d plugin lives,
- * which the caller probably obtained by calling getElementById.
- * @param {string} type the event type on which the handler to be removed was to
- * trigger, e.g. 'mousedown', 'mousemove', etc.
- * @param {!Object} handler either a function or an EventListener object.
- */
-o3djs.event.removeEventListener = function(pluginObject, type, handler) {
- var registry = pluginObject.o3d_eventRegistry;
- if (!registry) {
- return;
- }
- var listenerSet = registry[type];
- if (!listenerSet) {
- return;
- }
- for (var index in listenerSet) {
- if (listenerSet[index] == handler) {
- if (listenerSet.length == 1) {
- pluginObject.client.clearEventCallback(type);
- }
- listenerSet.splice(index, 1);
- break;
- }
- }
-};
diff --git a/o3d/samples/o3djs/fps.js b/o3d/samples/o3djs/fps.js
deleted file mode 100644
index 51c233d..0000000
--- a/o3d/samples/o3djs/fps.js
+++ /dev/null
@@ -1,486 +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.
- */
-
-
-/**
- * @fileoverview This file contains a class for displaying frames per second.
- */
-
-o3djs.provide('o3djs.fps');
-
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.canvas');
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.primitives');
-
-/**
- * A Module with a fps class for helping to easily display frames per second.
- * @namespace
- */
-o3djs.fps = o3djs.fps || {};
-
-/**
- * Number of frames to average over for computing FPS.
- * @type {number}
- */
-o3djs.fps.NUM_FRAMES_TO_AVERAGE = 16;
-
-/**
- * Colors used for each second of the performance bar.
- * @type {!Array.<!o3djs.math.Vector4>}
- */
-o3djs.fps.PERF_BAR_COLORS = [
- [0, 0, 1, 1],
- [0, 1, 0, 1],
- [1, 1, 0, 1],
- [1, 0.5, 0, 1],
- [1, 0, 0, 1]];
-
-/**
- * Generate a shader to be used by the pref quads.
- * @return {string}
- */
-o3djs.fps.buildShaderString = function() {
- var p = o3djs.effect;
-
- var varyingDecls = p.BEGIN_OUT_STRUCT +
- p.VARYING + p.FLOAT4 + ' ' +
- p.VARYING_DECLARATION_PREFIX + 'position' +
- p.semanticSuffix('POSITION') + ';\n' +
- p.END_STRUCT;
-
- return '' +
- 'uniform ' + p.MATRIX4 + ' worldViewProjection' +
- p.semanticSuffix('WORLDVIEWPROJECTION') + ';\n' +
- '\n' +
- p.BEGIN_IN_STRUCT +
- p.ATTRIBUTE + p.FLOAT4 + ' position' +
- p.semanticSuffix('POSITION') + ';\n' +
- p.END_STRUCT +
- '\n' +
- varyingDecls +
- '\n' +
- p.beginVertexShaderMain() +
- ' ' + p.VERTEX_VARYING_PREFIX + 'position = ' +
- p.mul(p.ATTRIBUTE_PREFIX + 'position',
- 'worldViewProjection') + ';\n' +
- p.endVertexShaderMain() +
- '\n' +
- p.pixelShaderHeader() +
- 'uniform ' + p.FLOAT4 + ' color;\n' +
- p.repeatVaryingDecls(varyingDecls) +
- p.beginPixelShaderMain() +
- p.endPixelShaderMain('color') +
- p.entryPoints() +
- p.matrixLoadOrder();
-};
-
-
-/**
- * Creates an object for displaying frames per second.
- *
- * You can use it like this.
- * <pre>
- * &lt;html&gt;&lt;body&gt;
- * &lt;script type="text/javascript" src="o3djs/base.js"&gt;
- * &lt;/script&gt;
- * &lt;script type="text/javascript"&gt;
- * o3djs.require('o3djs.util');
- * o3djs.require('o3djs.rendergraph');
- * o3djs.require('o3djs.fps');
- * window.onload = init;
- * window.onunload = uninit;
- *
- * var g_client;
- * var g_fpsManager;
- *
- * function init() {
- * o3djs.base.makeClients(initStep2);
- * }
- *
- * function initStep2(clientElements) {
- * var clientElement = clientElements[0];
- * var g_client = clientElement.client;
- * var pack = g_client.createPack();
- * var viewInfo = o3djs.rendergraph.createBasicView(
- * pack,
- * g_client.root,
- * g_client.renderGraphRoot);
- * g_fpsManager = o3djs.fps.createFPSManager(pack,
- * g_client.width,
- * g_client.height,
- * g_client.renderGraphRoot);
- * g_client.setRenderCallback(onRender);
- * }
- *
- * function onrender(renderEvent) {
- * g_fpsManager.update(renderEvent);
- * }
- *
- * function uninit() {
- * if (g_client) {
- * g_client.cleanup();
- * }
- * }
- * &lt;/script&gt;
- * &lt;div id="o3d" style="width: 600px; height: 600px"&gt;&lt;/div&gt;
- * &lt;/body&gt;&lt;/html&gt;
- * </pre>
- *
- * @param {!o3d.Pack} pack Pack to create objects in.
- * @param {number} clientWidth width of client area.
- * @param {number} clientHeight Height of client area.
- * @param {!o3d.RenderNode} opt_parent RenderNode to use as parent for
- * ViewInfo that will be used to render the FPS with.
- * @return {!o3djs.fps.FPSManager} The created FPSManager.
- */
-o3djs.fps.createFPSManager = function(pack,
- clientWidth,
- clientHeight,
- opt_parent) {
- return new o3djs.fps.FPSManager(pack, clientWidth, clientHeight, opt_parent);
-};
-
-/**
- * A class for displaying frames per second.
- * @constructor
- * @param {!o3d.Pack} pack Pack to create objects in.
- * @param {number} clientWidth width of client area.
- * @param {number} clientHeight Height of client area.
- * @param {!o3d.RenderNode} opt_parent RenderNode to use as parent for
- * ViewInfo that will be used to render the FPS with.
- */
-o3djs.fps.FPSManager = function(pack, clientWidth, clientHeight, opt_parent) {
- // total time spent for last N frames.
- this.totalTime_ = 0.0;
-
- // total active time for last N frames.
- this.totalActiveTime_ = 0.0;
-
- // elapsed time for last N frames.
- this.timeTable_ = [];
-
- // active time for last N frames.
- this.activeTimeTable_ = [];
-
- // where to record next elapsed time.
- this.timeTableCursor_ = 0;
-
- // Initialize the FPS elapsed time history table.
- for (var tt = 0; tt < o3djs.fps.NUM_FRAMES_TO_AVERAGE; ++tt) {
- this.timeTable_[tt] = 0.0;
- this.activeTimeTable_[tt] = 0.0;
- }
-
- // The root transform for this sub graph.
- this.root_ = pack.createObject('Transform');
-
- /**
- * The ViewInfo to display FPS.
- * @type {!o3djs.rendergraph.ViewInfo}
- */
- this.viewInfo = o3djs.rendergraph.createBasicView(pack,
- this.root_,
- opt_parent);
- this.viewInfo.root.priority = 100000;
- this.viewInfo.clearBuffer.clearColorFlag = false;
-
- this.viewInfo.zOrderedState.getStateParam('CullMode').value =
- o3djs.base.o3d.State.CULL_NONE;
-
- this.viewInfo.drawContext.view = o3djs.math.matrix4.lookAt(
- [0, 0, 1], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-
- // create a view just for the FPS. That way it's indepdendent of other views.
- this.canvasLib_ = o3djs.canvas.create(pack,
- this.root_,
- this.viewInfo);
-
- this.paint_ = pack.createObject('CanvasPaint');
-
- /**
- * The quad used to display the FPS.
- *
- */
- this.fpsQuad = this.canvasLib_.createXYQuad(0, 0, -1, 64, 32, true);
-
- // create a unit plane with a const color effect we can use to draw
- // rectangles.
- this.colorEffect_ = pack.createObject('Effect');
- this.colorEffect_.loadFromFXString(o3djs.fps.buildShaderString());
- this.colorMaterial_ = pack.createObject('Material');
- this.colorMaterial_.effect = this.colorEffect_;
- this.colorMaterial_.drawList = this.viewInfo.zOrderedDrawList;
- this.colorEffect_.createUniformParameters(this.colorMaterial_);
- this.colorMaterial_.getParam('color').value = [1, 1, 1, 1];
- this.colorQuadShape_ = o3djs.primitives.createPlane(
- pack,
- this.colorMaterial_,
- 1,
- 1,
- 1,
- 1,
- o3djs.math.makeMatrix4(1, 0, 0, 0,
- 0, 0, 1, 0,
- 0, -1, 0, 0,
- 0.5, 0.5, 0, 1));
-
- var barXOffset = 10;
- var barYOffset = 2;
- var barWidth = clientWidth - barXOffset * 2;
- var barHeight = 7;
- this.numPerfBars_ = o3djs.fps.PERF_BAR_COLORS.length - 1;
- this.perfBarRoot_ = pack.createObject('Transform');
- this.perfBarRoot_.parent = this.root_;
- this.perfBarBack_ = new o3djs.fps.ColorRect(
- pack, this.colorQuadShape_, this.perfBarRoot_,
- barXOffset, barYOffset, -3, barWidth, barHeight,
- [0, 0, 0, 1]);
- this.perfMarker_ = [];
- for (var ii = 0; ii < this.numPerfBars_; ++ii) {
- this.perfMarker_[ii] = new o3djs.fps.ColorRect(
- pack, this.colorQuadShape_, this.perfBarRoot_,
- barXOffset + barWidth / (this.numPerfBars_ + 1) * (ii + 1),
- barYOffset - 1, -1,
- 1, barHeight + 2,
- [1, 1, 1, 1]);
- }
- this.perfBar_ = new o3djs.fps.ColorRect(
- pack, this.colorQuadShape_, this.perfBarRoot_,
- barXOffset + 1, barYOffset + 1, -2, 1, barHeight - 2,
- [1, 1, 0, 1]);
- this.perfBarWidth_ = barWidth - 2;
- this.perfBarHeight_ = barHeight - 2;
- this.perfBarXOffset_ = barXOffset;
- this.perfBarYOffset_ = barYOffset;
-
- // set the size and position.
- this.resize(clientWidth, clientHeight);
- this.setPosition(10, 10);
-};
-
-/**
- * Sets the position of the FPS display
- *
- * The position is in pixels assuming the size of the client matches the size
- * last set either on creation or with FPSManager.resize.
- *
- * @param {number} x The x position.
- * @param {number} y The y position.
- */
-o3djs.fps.FPSManager.prototype.setPosition = function(x, y) {
- this.fpsQuad.transform.identity();
- this.fpsQuad.transform.translate(x, y, -1);
-};
-
-/**
- * Sets the visiblity of the fps display.
- * @param {boolean} visible true = visible.
- */
-o3djs.fps.FPSManager.prototype.setVisible = function(visible) {
- this.viewInfo.root.active = visible;
-};
-
-/**
- * Sets the visibility of the performance bar.
- * @param {boolean} visible true = visible.
- */
-o3djs.fps.FPSManager.prototype.setPerfVisible = function(visible) {
- this.perfBarRoot_.visible = visible;
-};
-
-/**
- * Resizes the area for the FPS display.
- * Note: you must call this if your client area changes size.
- * @param {number} clientWidth width of client area.
- * @param {number} clientHeight height of client area.
- */
-o3djs.fps.FPSManager.prototype.resize = function(clientWidth, clientHeight) {
- this.viewInfo.drawContext.projection = o3djs.math.matrix4.orthographic(
- 0 + 0.5,
- clientWidth + 0.5,
- clientHeight + 0.5,
- 0 + 0.5,
- 0.001,
- 1000);
-
- var barWidth = clientWidth - this.perfBarXOffset_ * 2;
- this.perfBarBack_.setSize(barWidth, this.perfBarHeight_);
- for (var ii = 0; ii < this.numPerfBars_; ++ii) {
- this.perfMarker_[ii].setPosition(
- this.perfBarXOffset_ + barWidth / (this.numPerfBars_ + 1) * (ii + 1),
- this.perfBarYOffset_ - 1);
- }
- this.perfBarWidth_ = barWidth - 2;
-};
-
-/**
- * Updates the fps display.
- * You must call this every frame to update the FPS display.
- *
- * <pre>
- * ...
- * client.setRenderCallback(onRender);
- * ...
- * function onRender(renderEvent) {
- * myFpsManager.update(renderEvent);
- * }
- * </pre>
- *
- * @param {!o3d.RenderEvent} renderEvent The object passed into the render
- * callback.
- */
-o3djs.fps.FPSManager.prototype.update = function(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- var activeTime = renderEvent.activeTime;
- // Keep the total time and total active time for the last N frames.
- this.totalTime_ += elapsedTime - this.timeTable_[this.timeTableCursor_];
- this.totalActiveTime_ +=
- activeTime - this.activeTimeTable_[this.timeTableCursor_];
-
- // Save off the elapsed time for this frame so we can subtract it later.
- this.timeTable_[this.timeTableCursor_] = elapsedTime;
- this.activeTimeTable_[this.timeTableCursor_] = activeTime;
-
- // Wrap the place to store the next time sample.
- ++this.timeTableCursor_;
- if (this.timeTableCursor_ == o3djs.fps.NUM_FRAMES_TO_AVERAGE) {
- this.timeTableCursor_ = 0;
- }
-
- // Print the average frame rate for the last N frames as well as the
- // instantaneous frame rate.
- var fps = '' +
- Math.floor((1.0 / (this.totalTime_ /
- o3djs.fps.NUM_FRAMES_TO_AVERAGE)) + 0.5) +
- ' : ' + Math.floor(1.0 / elapsedTime + 0.5);
-
- var canvas = this.fpsQuad.canvas;
- canvas.clear([0, 0, 0, 0]);
-
- var paint = this.paint_;
-
- canvas.saveMatrix();
- paint.setOutline(3, [0, 0, 0, 1]);
- paint.textAlign = o3djs.base.o3d.CanvasPaint.LEFT;
- paint.textSize = 12;
- paint.textTypeface = 'Arial';
- paint.color = [1, 1, 0, 1];
- canvas.drawText(fps, 2, 16, paint);
- canvas.restoreMatrix();
-
- this.fpsQuad.updateTexture();
-
- var frames = this.totalActiveTime_ / o3djs.fps.NUM_FRAMES_TO_AVERAGE /
- (1 / 60.0);
- var colorIndex = Math.min(frames, o3djs.fps.PERF_BAR_COLORS.length - 1);
- colorIndex = Math.floor(Math.max(colorIndex, 0));
-
- if (!isNaN(colorIndex)) {
- this.perfBar_.setColor(o3djs.fps.PERF_BAR_COLORS[colorIndex]);
- this.perfBar_.setSize(frames * this.perfBarWidth_ / this.numPerfBars_,
- this.perfBarHeight_);
- }
-};
-
-/**
- * A Class the manages a color rect.
- * @constructor
- * @param {!o3d.Pack} pack Pack to create things in.
- * @param {!o3d.Shape} shape Shape to use for rectangle.
- * @param {!o3d.Transform} parent Transform to parent rect under.
- * @param {number} x initial x position.
- * @param {number} y initial y position.
- * @param {number} z initial z position.
- * @param {number} width initial width.
- * @param {number} height initial height.
- * @param {!o3djs.math.Vector4} color initial color.
- */
-o3djs.fps.ColorRect = function(pack, shape, parent,
- x, y, z, width, height, color) {
- this.transform_ = pack.createObject('Transform');
- this.colorParam_ = this.transform_.createParam('color', 'ParamFloat4');
- this.transform_.addShape(shape);
- this.transform_.parent = parent;
- this.width_ = 0;
- this.height_ = 0;
- this.x_ = 0;
- this.y_ = 0;
- this.z_ = z;
- this.setPosition(x, y);
- this.setSize(width, height);
- this.setColor(color);
-};
-
-/**
- * Updates the transform of this ColorRect
- * @private
- */
-o3djs.fps.ColorRect.prototype.updateTransform_ = function() {
- this.transform_.identity();
- this.transform_.translate(this.x_, this.y_, this.z_);
- this.transform_.scale(this.width_, this.height_, 1);
-};
-
-/**
- * Sets the position of this ColorRect.
- * @param {number} x x position.
- * @param {number} y y position.
- */
-o3djs.fps.ColorRect.prototype.setPosition = function(x, y) {
- this.x_ = x;
- this.y_ = y;
- this.updateTransform_();
-};
-
-/**
- * Sets the size of this ColorRect
- * @param {number} width width.
- * @param {number} height height.
- */
-o3djs.fps.ColorRect.prototype.setSize = function(width, height) {
- this.width_ = width;
- this.height_ = height;
- this.updateTransform_();
-};
-
-/**
- * Sets the color of this ColorRect.
- * @param {!o3djs.math.Vector4} color initial color.
- */
-o3djs.fps.ColorRect.prototype.setColor = function(color) {
- this.colorParam_.value = color;
-};
-
-
diff --git a/o3d/samples/o3djs/gpu2d.js b/o3d/samples/o3djs/gpu2d.js
deleted file mode 100644
index e4c65f9..0000000
--- a/o3d/samples/o3djs/gpu2d.js
+++ /dev/null
@@ -1,800 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-/**
- * @fileoverview This file provides GPU-accelerated rendering of 2D
- * vector graphics in 3D.
- */
-o3djs.provide('o3djs.gpu2d');
-
-o3djs.require('o3djs.base');
-
-/**
- * A module providing GPU-accelerated rendering of 2D vector graphics
- * in 3D.
- * @namespace
- */
-o3djs.gpu2d = o3djs.gpu2d || {};
-
-/**
- * Creates a new Path, which holds one or more closed contours
- * composed of 2D primitives like lines, quadratic curves, and cubic
- * curves.
- * @param {!o3d.Pack} pack Pack in which geometry and materials
- * associated with the curves will be created.
- * @param {!o3d.DrawList} drawList The DrawList on which the triangle
- * mesh will be drawn. Typically this will be the
- * zOrderedDrawList from an o3djs.rendergraph.ViewInfo.
- * @return {!o3djs.gpu2d.Path} The created Path.
- */
-o3djs.gpu2d.createPath = function(pack,
- drawList) {
- return new o3djs.gpu2d.Path(pack, drawList);
-};
-
-/**
- * Constructs a new Path. Do not call this directly; use
- * o3djs.gpu2d.createPath instead.
- * @param {!o3d.Pack} pack Pack in which geometry and materials
- * associated with the curves will be created.
- * @param {!o3d.DrawList} drawList The DrawList on which the triangle
- * mesh will be drawn. Typically this will be the
- * zOrderedDrawList.
- * @constructor
- */
-o3djs.gpu2d.Path = function(pack, drawList) {
- /**
- * Pack in which curves' geometry and materials are created.
- * @type {!o3d.Pack}
- * @private
- */
- this.pack_ = pack;
-
- /**
- * DrawList in which curves' geometry and materials will be
- * rendered.
- * @type {!o3d.DrawList}
- * @private
- */
- this.drawList_ = drawList;
-
- /**
- * Internal object which manages the triangle mesh associated with
- * the curves.
- * @type {!o3d.ProcessedPath}
- * @private
- */
- this.path_ = pack.createObject('ProcessedPath');
-
- // Set up the Primitives in the ProcessedPath.
- //
- // The mesh is separated into two different regions. The exterior
- // region of the mesh is the portion containing the cubic curve
- // segments. It is this region whose alpha value is computed using
- // Loop and Blinn's shader. The interior region of the mesh is
- // simply filled with a constant alpha. The reason for the split is
- // that it is difficult to assign texture coordinates to cause Loop
- // and Blinn's shader to fill a region with constant alpha. While
- // there is some cost associated with switching shaders and
- // performing two draw calls, doing so simplifies the logic.
-
- // Create state objects so we can turn on alpha blending for the
- // exterior triangles. We also disable backface culling so that we
- // can view the vector shapes from both sides.
- var exteriorState = pack.createObject('State');
- exteriorState.getStateParam('o3d.AlphaBlendEnable').value = true;
- exteriorState.getStateParam('o3d.SourceBlendFunction').value =
- o3djs.base.o3d.State.BLENDFUNC_SOURCE_ALPHA;
- exteriorState.getStateParam('o3d.DestinationBlendFunction').value =
- o3djs.base.o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA;
- exteriorState.getStateParam('o3d.CullMode').value =
- o3djs.base.o3d.State.CULL_NONE;
-
- var interiorState = pack.createObject('State');
- interiorState.getStateParam('o3d.CullMode').value =
- o3djs.base.o3d.State.CULL_NONE;
-
- // Create the materials for the exterior and interior regions.
-
- /**
- * The material for the exterior triangles, filled with Loop and
- * Blinn's shader.
- * @type {!o3d.Material}
- * @private
- */
- this.exteriorMaterial_ = pack.createObject('Material');
- this.exteriorMaterial_.name = 'ExteriorMaterial';
- this.exteriorMaterial_.state = exteriorState;
- this.exteriorMaterial_.drawList = drawList;
-
- /**
- * The material for the interior triangles, filled with a solid
- * shader.
- * @type {!o3d.Material}
- * @private
- */
- this.interiorMaterial_ = pack.createObject('Material');
- this.interiorMaterial_.name = 'InteriorMaterial';
- this.interiorMaterial_.state = interiorState;
- this.interiorMaterial_.drawList = drawList;
-
- /**
- * The Shape which is the transform graph's view of the Path.
- * @type {!o3d.Shape}
- */
- this.shape = pack.createObject('Shape');
-
- // Create the exterior region.
- var primitive = pack.createObject('Primitive');
- var streamBank = pack.createObject('StreamBank');
- var vertexBuffer = pack.createObject('VertexBuffer');
- // The coordinates of the triangles are 2D
- var vertices = vertexBuffer.createField('FloatField', 2);
- /**
- * The Field for the exterior vertices.
- * @type {!o3d.FloatField}
- * @private
- */
- this.exteriorVertices_ = vertices;
- // The (Loop/Blinn) texture coordinates are 3D
- var texcoords = vertexBuffer.createField('FloatField', 3);
- /**
- * The Field for the exterior texture coordinates.
- * @type {!o3d.FloatField}
- * @private
- */
- this.exteriorTexCoords_ = texcoords;
- streamBank.setVertexStream(o3djs.base.o3d.Stream.POSITION, 0, vertices, 0);
- streamBank.setVertexStream(o3djs.base.o3d.Stream.TEXCOORD, 0, texcoords, 0);
- primitive.streamBank = streamBank;
- primitive.primitiveType = o3djs.base.o3d.Primitive.TRIANGLELIST;
- primitive.material = this.exteriorMaterial_;
- primitive.owner = this.shape;
- /**
- * The Primitive for the exterior triangles.
- * @type {!o3d.Primitive}
- * @private
- */
- this.exteriorTriangles_ = primitive;
-
- // Create the interior region.
- primitive = pack.createObject('Primitive');
- streamBank = pack.createObject('StreamBank');
- vertexBuffer = pack.createObject('VertexBuffer');
- // The coordinates of the triangles are 2D
- vertices = vertexBuffer.createField('FloatField', 2);
- /**
- * The Field for the interior vertices.
- * @type {!o3d.FloatField}
- * @private
- */
- this.interiorVertices_ = vertices;
- streamBank.setVertexStream(o3djs.base.o3d.Stream.POSITION, 0, vertices, 0);
- primitive.streamBank = streamBank;
- primitive.primitiveType = o3djs.base.o3d.Primitive.TRIANGLELIST;
- primitive.material = this.interiorMaterial_;
- primitive.owner = this.shape;
- /**
- * The Primitive for the interior triangles.
- * @type {!o3d.Primitive}
- * @private
- */
- this.interiorTriangles_ = primitive;
-
- // Initialize the fill to a solid color.
- this.setFill(o3djs.gpu2d.createColor(pack, 0.0, 0.0, 0.0, 1.0));
-
- // Create draw elements for the shape.
- this.shape.createDrawElements(pack, null);
-};
-
-/**
- * Clears out any previously added segments or generated triangles
- * from this Path.
- */
-o3djs.gpu2d.Path.prototype.clear = function() {
- this.path_.clear();
-};
-
-/**
- * Moves the pen to the given absolute X,Y coordinates. If a contour
- * isn't currently open on this path, one is opened.
- * @param {number} x the x coordinate to move to.
- * @param {number} y the y coordinate to move to.
- */
-o3djs.gpu2d.Path.prototype.moveTo = function(x, y) {
- this.path_.moveTo(x, y);
-};
-
-/**
- * Draws a line from the current coordinates to the given absolute
- * X,Y coordinates.
- * @param {number} x the x coordinate to draw a line to.
- * @param {number} y the y coordinate to draw a line to.
- */
-o3djs.gpu2d.Path.prototype.lineTo = function(x, y) {
- this.path_.lineTo(x, y);
-};
-
-/**
- * Draws a quadratic curve from the current coordinates through the
- * given control point and end point, specified in absolute
- * coordinates.
- * @param {number} cx the x coordinate of the quadratic's control point
- * @param {number} cy the y coordinate of the quadratic's control point
- * @param {number} x the x coordinate of the quadratic's end point
- * @param {number} y the y coordinate of the quadratic's end point
- */
-o3djs.gpu2d.Path.prototype.quadraticTo = function(cx, cy, x, y) {
- this.path_.quadraticTo(cx, cy, x, y);
-};
-
-/**
- * Draws a cubic curve from the current coordinates through the
- * given control points and end point, specified in absolute
- * coordinates.
- * @param {number} c0x the x coordinate of the cubic's first control point
- * @param {number} c0y the y coordinate of the cubic's first control point
- * @param {number} c1x the x coordinate of the cubic's second control point
- * @param {number} c1y the y coordinate of the cubic's second control point
- * @param {number} x the x coordinate of the cubic's end point
- * @param {number} y the y coordinate of the cubic's end point
- */
-o3djs.gpu2d.Path.prototype.cubicTo = function(c0x, c0y, c1x, c1y, x, y) {
- this.path_.cubicTo(c0x, c0y, c1x, c1y, x, y);
-};
-
-/**
- * Closes the current contour on this Path.
- */
-o3djs.gpu2d.Path.prototype.close = function() {
- this.path_.close();
-};
-
-/**
- * Updates the triangle mesh associated with this Path. Call this
- * after adding any new segments to the Path.
- */
-o3djs.gpu2d.Path.prototype.update = function() {
- this.path_.createMesh(this.exteriorVertices_,
- this.exteriorTexCoords_,
- this.interiorVertices_);
- var numVertices = this.exteriorVertices_.buffer.numElements;
- if (numVertices == 1) {
- this.exteriorTriangles_.numberVertices = 0;
- this.exteriorTriangles_.numberPrimitives = 0;
- } else {
- this.exteriorTriangles_.numberVertices = numVertices;
- this.exteriorTriangles_.numberPrimitives = numVertices / 3;
- }
- numVertices = this.interiorVertices_.buffer.numElements;
- if (numVertices == 1) {
- this.interiorTriangles_.numberVertices = 0;
- this.interiorTriangles_.numberPrimitives = 0;
- } else {
- this.interiorTriangles_.numberVertices = numVertices;
- this.interiorTriangles_.numberPrimitives = numVertices / 3;
- }
-};
-
-/**
- * Sets the polygon offset parameters for the triangles associated
- * with this Path.
- * @param {number} slopeFactor polygon offset slope factor.
- * @param {number} depthBias polygon offset depth bias.
- */
-o3djs.gpu2d.Path.prototype.setPolygonOffset = function(slopeFactor,
- depthBias) {
- this.exteriorMaterial_.state.getStateParam('o3d.PolygonOffset1').value =
- slopeFactor;
- this.exteriorMaterial_.state.getStateParam('o3d.PolygonOffset2').value =
- depthBias;
- this.interiorMaterial_.state.getStateParam('o3d.PolygonOffset1').value =
- slopeFactor;
- this.interiorMaterial_.state.getStateParam('o3d.PolygonOffset2').value =
- depthBias;
-}
-
-//----------------------------------------------------------------------
-// Fills
-
-/**
- * Sets the fill for this Path.
- * @param {!o3djs.gpu2d.Fill} fill the fill for this Path.
- */
-o3djs.gpu2d.Path.prototype.setFill = function(fill) {
- if (this.fill_) {
- this.fill_.detach_(this);
- }
- this.interiorMaterial_.effect = fill.interiorEffect;
- this.exteriorMaterial_.effect = fill.exteriorEffect;
- this.fill_ = fill;
- fill.attach_(this);
-};
-
-/**
- * Base class for all Fills. Do not call this directly; use, for
- * example, o3djs.gpu2d.createColor instead.
- * @param {!o3d.Pack} pack the Pack in which to create materials.
- * @constructor
- */
-o3djs.gpu2d.Fill = function(pack) {
- this.pack_ = pack;
- this.attachedPaths_ = [];
-};
-
-/**
- * Attaches this Fill to the given path.
- * @param {!o3djs.gpu2d.Path} path Path to attach the fill to.
- * @private
- */
-o3djs.gpu2d.Fill.prototype.attach_ = function(path) {
- if (this.attachedPaths_.indexOf(path) < 0)
- this.attachedPaths_.push(path);
- this.apply_(path);
-};
-
-/**
- * Detaches this Fill from the given path.
- * @param {!o3djs.gpu2d.Path} path Path to detach the fill from.
- * @private
- */
-o3djs.gpu2d.Fill.prototype.detach_ = function(path) {
- var idx = this.attachedPaths_.indexOf(path);
- if (idx >= 0)
- this.attachedPaths_.splice(idx, idx);
-};
-
-/**
- * Applies this Fill to all attached paths.
- * @private
- */
-o3djs.gpu2d.Fill.prototype.applyToPaths_ = function() {
- for (var i = 0; i < this.attachedPaths_.length; i++) {
- this.apply_(this.attachedPaths_[i]);
- }
-};
-
-/**
- * Base "apply" operation for fills -- a no-op.
- * @private
- */
-o3djs.gpu2d.Fill.prototype.apply_ = function(path) {
-};
-
-/**
- * A class for a solid color fill. Do not call this directly; use
- * o3djs.gpu2d.createColor instead.
- * @param {!o3d.Pack} pack the Pack in which to create materials.
- * @constructor
- * @extends {o3djs.gpu2d.Fill}
- */
-o3djs.gpu2d.Color = function(pack) {
- o3djs.gpu2d.Fill.call(this, pack);
- this.interiorEffect =
- o3djs.gpu2d.loadEffect_(pack, o3djs.gpu2d.FillTypes_.COLOR, true);
- this.exteriorEffect =
- o3djs.gpu2d.loadEffect_(pack, o3djs.gpu2d.FillTypes_.COLOR, false);
- this.r_ = 0.0;
- this.g_ = 0.0;
- this.b_ = 0.0;
- this.a_ = 1.0;
-};
-
-o3djs.base.inherit(o3djs.gpu2d.Color,
- o3djs.gpu2d.Fill);
-
-/**
- * Sets the color of this fill.
- * @param {number} r Red component (0.0 - 1.0).
- * @param {number} g Green component (0.0 - 1.0).
- * @param {number} b Blue component (0.0 - 1.0).
- * @param {number} a Alpha component (0.0 - 1.0).
- */
-o3djs.gpu2d.Color.prototype.set = function(r, g, b, a) {
- this.r_ = r;
- this.g_ = g;
- this.b_ = b;
- this.a_ = a;
- this.applyToPaths_();
-};
-
-/**
- * Gets the value of the Color fill as an array.
- * @return {!o3d.Float4}
- */
-o3djs.gpu2d.Color.prototype.get = function() {
- return [this.r_, this.g_, this.b_, this.a_];
-};
-
-/**
- * Applies this color to the given path.
- * @param {!o3djs.gpu2d.Path} path to apply the fill to.
- * @private
- */
-o3djs.gpu2d.Color.prototype.apply_ = function(path) {
- this.applyToMaterial_(path.interiorMaterial_);
- this.applyToMaterial_(path.exteriorMaterial_);
-};
-
-/**
- * Applies this color to the given material
- * @param {!o3d.Material} material to apply the fill to.
- * @private
- */
-o3djs.gpu2d.Color.prototype.applyToMaterial_ = function(material) {
- var paramName = 'color';
- var paramType = 'ParamFloat4';
- var param = material.getParam(paramName);
- if (!param) {
- param = material.createParam(paramName, paramType);
- }
- param.set(this.r_, this.g_, this.b_, this.a_);
-};
-
-/**
- * Creates a solid color fill.
- * @param {!o3d.Pack} pack the Pack in which to create materials.
- * @param {number} red Red component (0.0 - 1.0).
- * @param {number} green Green component (0.0 - 1.0).
- * @param {number} blue Blue component (0.0 - 1.0).
- * @param {number} alpha Alpha component (0.0 - 1.0).
- * @return {!o3djs.gpu2d.Color} The created Color.
- */
-o3djs.gpu2d.createColor = function(pack, red, green, blue, alpha) {
- var result = new o3djs.gpu2d.Color(pack);
- result.set(red, green, blue, alpha);
- return result;
-};
-
-//----------------------------------------------------------------------
-// Shaders and effects
-
-// TODO(kbr): antialiasing in the Cg backend is not supported yet
-// because the ddx and ddy instructions are not part of the shader
-// model 2.0. On Windows we could easily upgrade to ps2.0a, but on Mac
-// and Linux there isn't an easy upgrade path from ARBVP1.0 and
-// ARBFP1.0 which incorporates these instructions.
-//
-// The solution within O3D is to compute the gradients using the
-// closed-form solution in Loop and Blinn's SIGGRAPH '05 paper. This
-// requires computation of the Psi matrix per vertex. In GLSL this is
-// not necessary; derivative instructions are always available there.
-
-/**
- * Generates the source for the shader used on the exterior triangles
- * of the shape -- the ones that evaluate the curve function.
- * @param {boolean} antialias whether to enable antialiasing.
- * @param {string} fillUniforms the uniforms for the fill.
- * @param {string} fillSource the source code snippet for the fill.
- * @return {string}
- * @private
- */
-o3djs.gpu2d.generateLoopBlinnShaderSource_ = function(antialias,
- fillUniforms,
- fillSource) {
- if (o3djs.base.glsl) {
- var result = '' +
- '// Vertex shader\n' +
- 'uniform mat4 worldViewProjection;\n' +
- '\n' +
- 'attribute vec2 position;\n' +
- 'attribute vec3 texCoord0;\n' +
- '\n' +
- 'varying vec3 klm;\n' +
- '\n' +
- 'void main() {\n' +
- ' // TODO(kbr): figure out why this multiplication needs to be\n' +
- ' // transposed compared to the Cg version.\n' +
- ' gl_Position = worldViewProjection * vec4(position, 0.0, 1.0);\n' +
- ' klm = texCoord0;\n' +
- '}\n' +
- '// #o3d SplitMarker\n' +
- '// Fragment shader\n' +
- 'varying vec3 klm;\n' +
- fillUniforms +
- 'void main() {\n';
- var alphaComputation;
- if (antialias) {
- alphaComputation = '' +
- ' // Gradients\n' +
- ' vec3 px = dFdx(klm);\n' +
- ' vec3 py = dFdy(klm);\n' +
- '\n' +
- ' // Chain rule\n' +
- ' float k2 = klm.x * klm.x;\n' +
- ' float c = k2 * klm.x - klm.y * klm.z;\n' +
- ' float k23 = 3.0 * k2;\n' +
- ' float cx = k23 * px.x - klm.z * px.y - klm.y * px.z;\n' +
- ' float cy = k23 * py.x - klm.z * py.y - klm.y * py.z;\n' +
- '\n' +
- ' // Signed distance\n' +
- ' float sd = c / sqrt(cx * cx + cy * cy);\n' +
- '\n' +
- ' // Linear alpha\n' +
- ' // TODO(kbr): figure out why this needs to be\n' +
- ' // negated compared to Cg version, and also why\n' +
- ' // we need an adjustment by +1.0 for it to look good.\n' +
- ' // float alpha = clamp(0.5 - sd, 0.0, 1.0);\n' +
- ' float alpha = clamp(sd + 0.5, 0.0, 1.0);\n';
- } else {
- alphaComputation = '' +
- ' float t = klm.x * klm.x * klm.x - klm.y * klm.z;\n' +
- ' float alpha = clamp(sign(t), 0.0, 1.0);\n';
- }
- return result + alphaComputation +
- '\n' +
- fillSource +
- '}\n' +
- '\n' +
- '// #o3d MatrixLoadOrder RowMajor\n';
- } else {
- antialias = false; // See above why
- var result = '' +
- 'uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;\n' +
- fillUniforms +
- '\n' +
- 'struct VertexShaderInput {\n' +
- ' float2 position : POSITION;\n' +
- ' float3 klm : TEXCOORD0;\n' +
- '};\n' +
- '\n' +
- 'struct PixelShaderInput {\n' +
- ' float4 position : POSITION;\n' +
- ' float3 klm : TEXCOORD0;\n' +
- '};\n' +
- '\n' +
- 'PixelShaderInput vertexShaderFunction(VertexShaderInput input) {\n' +
- ' PixelShaderInput output;\n' +
- '\n' +
- ' output.position = mul(float4(input.position, 0, 1),\n' +
- ' worldViewProjection);\n' +
- ' output.klm = input.klm;\n' +
- ' return output;\n' +
- '}\n' +
- '\n' +
- 'float4 pixelShaderFunction(PixelShaderInput input) : COLOR {\n' +
- ' float3 klm = input.klm;\n';
- var alphaComputation;
- if (antialias) {
- alphaComputation = '' +
- ' // Gradients\n' +
- ' float3 px = ddx(input.klm);\n' +
- ' float3 py = ddy(input.klm);\n' +
- '\n' +
- ' // Chain rule\n' +
- ' float k2 = klm.x * klm.x;\n' +
- ' float c = k2 * klm.x - klm.y * klm.z;\n' +
- ' float k23 = 3.0 * k2;\n' +
- ' float cx = k23 * px.x - klm.z * px.y - klm.y * px.z;\n' +
- ' float cy = k23 * py.x - klm.z * py.y - klm.y * py.z;\n' +
- '\n' +
- ' // Signed distance\n' +
- ' float sd = c / sqrt(cx * cx + cy * cy);\n' +
- '\n' +
- ' // Linear alpha\n' +
- ' float alpha = clamp(0.5 - sd, 0.0, 1.0);\n';
- } else {
- alphaComputation = '' +
- ' float t = klm.x * klm.x * klm.x - klm.y * klm.z;\n' +
- ' float alpha = clamp(sign(t), 0.0, 1.0);\n';
- }
-
- return result + alphaComputation +
- '\n' +
- fillSource +
- '}\n' +
- '\n' +
- '// #o3d VertexShaderEntryPoint vertexShaderFunction\n' +
- '// #o3d PixelShaderEntryPoint pixelShaderFunction\n' +
- '// #o3d MatrixLoadOrder RowMajor\n';
- }
-};
-
-/**
- * Generates the source for the shader used on the interior triangles
- * of the shape.
- * @param {string} fillUniforms the uniforms for the fill.
- * @param {string} fillSource the source code snippet for the fill.
- * @return {string}
- * @private
- */
-o3djs.gpu2d.generateSolidShaderSource_ = function(fillUniforms, fillSource) {
- if (o3djs.base.glsl) {
- var result = '' +
- '// Vertex shader\n' +
- 'uniform mat4 worldViewProjection;\n' +
- '\n' +
- 'attribute vec2 position;\n' +
- '\n' +
- 'void main() {\n' +
- ' // TODO(kbr): figure out why this multiplication needs to be\n' +
- ' // transposed compared to the Cg version.\n' +
- ' gl_Position = worldViewProjection * vec4(position, 0.0, 1.0);\n' +
- '}\n' +
- '// #o3d SplitMarker\n' +
- '// Fragment shader\n' +
- fillUniforms +
- 'void main() {\n' +
- ' float alpha = 1.0;\n' +
- fillSource +
- '}\n' +
- '\n' +
- '// #o3d MatrixLoadOrder RowMajor\n';
- return result;
- } else {
- var result = '' +
- 'uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;\n' +
- fillUniforms +
- '\n' +
- 'struct VertexShaderInput {\n' +
- ' float2 position : POSITION;\n' +
- '};\n' +
- '\n' +
- 'struct PixelShaderInput {\n' +
- ' float4 position : POSITION;\n' +
- '};\n' +
- '\n' +
- 'PixelShaderInput vertexShaderFunction(VertexShaderInput input) {\n' +
- ' PixelShaderInput output;\n' +
- '\n' +
- ' output.position = mul(float4(input.position, 0, 1),\n' +
- ' worldViewProjection);\n' +
- ' return output;\n' +
- '}\n' +
- '\n' +
- 'float4 pixelShaderFunction(PixelShaderInput input) : COLOR {\n' +
- ' float alpha = 1.0;\n' +
- fillSource +
- '}\n' +
- '\n' +
- '// #o3d VertexShaderEntryPoint vertexShaderFunction\n' +
- '// #o3d PixelShaderEntryPoint pixelShaderFunction\n' +
- '// #o3d MatrixLoadOrder RowMajor\n';
- return result;
- }
-};
-
-/**
- * Enum for the types of fills.
- * @enum
- * @private
- */
-o3djs.gpu2d.FillTypes_ = {
- COLOR: 0
-};
-
-/**
- * Shader code for the various Cg fills, indexed by FillTypes_.
- * @type {!Array.<{uniforms: string, source: string}>}
- * @private
- */
-o3djs.gpu2d.FILL_CODE_CG_ = [
- { uniforms:
- 'uniform float4 color;\n',
- source:
- 'return float4(color.r, color.g, color.b, color.a * alpha);\n'
- }
-];
-
-/**
- * Shader code for the various fills, indexed by FillTypes_.
- * @type {!Array.<{uniforms: string, source: string}>}
- * @private
- */
-o3djs.gpu2d.FILL_CODE_GLSL_ = [
- { uniforms:
- 'uniform vec4 color;\n',
- source:
- 'gl_FragColor = vec4(color.r, color.g, color.b, color.a * alpha);\n'
- }
-];
-
-/**
- * Cache of effects indexed by pack's client ID. Each entry is an
- * array indexed by fill type.
- * @type {!Array.<!Array.<!o3d.Effect>>}
- * @private
- */
-o3djs.gpu2d.interiorEffectCache_ = [];
-
-/**
- * Cache of effects indexed by pack's client ID. Each entry is an
- * array indexed by fill type.
- * @type {!Array.<!Array.<!o3d.Effect>>}
- * @private
- */
-o3djs.gpu2d.exteriorEffectCache_ = [];
-
-/**
- * Loads a fill effect for a Path.
- * @param {!o3d.Pack} pack the Pack in which to create materials.
- * @param {o3djs.gpu2d.FillTypes_} fillType the fill type to create.
- * @param {boolean} interior whether this effect is filling the solid
- * interior portion of the shape or the exterior region containing
- * the curves.
- * @return {!o3d.Effect}
- * @private
- */
-o3djs.gpu2d.loadEffect_ = function(pack, fillType, interior) {
- var effectCache;
- if (interior) {
- effectCache = o3djs.gpu2d.interiorEffectCache_;
- } else {
- effectCache = o3djs.gpu2d.exteriorEffectCache_;
- }
- var effectList = o3djs.gpu2d.getEffectList_(pack, effectCache);
- var effect = effectList[fillType];
- if (!effect) {
- effect = pack.createObject('Effect');
- var result = false;
- var sourceSnippets;
- if (o3djs.base.glsl) {
- sourceSnippets = o3djs.gpu2d.FILL_CODE_GLSL_[fillType];
- } else {
- sourceSnippets = o3djs.gpu2d.FILL_CODE_CG_[fillType];
- }
- if (interior) {
- result = effect.loadFromFXString(
- o3djs.gpu2d.generateSolidShaderSource_(sourceSnippets.uniforms,
- sourceSnippets.source));
- } else {
- result = effect.loadFromFXString(
- o3djs.gpu2d.generateLoopBlinnShaderSource_(true,
- sourceSnippets.uniforms,
- sourceSnippets.source));
- }
- if (!result) {
- alert('Error loading shader: interior = ' + interior);
- }
- effectList[fillType] = effect;
- }
- return effect;
-};
-
-/**
- * Fetches and/or creates the effect list for a given pack from the
- * passed effect cache.
- * @param {!o3d.Pack} pack the Pack in which to create materials.
- * @param {!Array.<!Array.<!o3d.Effect>>} effectCache the effect cache.
- * @return {!Array.<o3d.Effect>}
- * @private
- */
-o3djs.gpu2d.getEffectList_ = function(pack, effectCache) {
- var list = effectCache[pack.clientId];
- if (!list) {
- list = [];
- effectCache[pack.clientId] = list;
- }
- return list;
-};
-
diff --git a/o3d/samples/o3djs/io.js b/o3d/samples/o3djs/io.js
deleted file mode 100644
index 784e5e0..0000000
--- a/o3d/samples/o3djs/io.js
+++ /dev/null
@@ -1,656 +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.
- */
-
-
-/**
- * @fileoverview This file contains various functions and class for io.
- */
-
-o3djs.provide('o3djs.io');
-
-o3djs.require('o3djs.texture');
-
-
-/**
- * A Module with various io functions and classes.
- * @namespace
- */
-o3djs.io = o3djs.io || {};
-
-/**
- * Creates a LoadInfo object.
- * @param {(!o3d.ArchiveRequest|!o3d.FileRequest|!XMLHttpRequest)} opt_request
- * The request to watch.
- * @param {boolean} opt_hasStatus true if opt_request is a
- * o3d.ArchiveRequest vs for example an o3d.FileRequest or an
- * XMLHttpRequest.
- * @return {!o3djs.io.LoadInfo} The new LoadInfo.
- * @see o3djs.io.LoadInfo
- */
-o3djs.io.createLoadInfo = function(opt_request, opt_hasStatus) {
- return new o3djs.io.LoadInfo(opt_request, opt_hasStatus);
-};
-
-/**
- * A class to help with progress reporting for most loading utilities.
- *
- * Example:
- * <pre>
- * var g_loadInfo = null;
- * g_id = window.setInterval(statusUpdate, 500);
- * g_loadInfo = o3djs.scene.loadScene(client, pack, parent,
- * 'http://google.com/somescene.o3dtgz',
- * callback);
- *
- * function callback(pack, parent, exception) {
- * g_loadInfo = null;
- * window.clearInterval(g_id);
- * if (!exception) {
- * // do something with scene just loaded
- * }
- * }
- *
- * function statusUpdate() {
- * if (g_loadInfo) {
- * var progress = g_loadInfo.getKnownProgressInfoSoFar();
- * document.getElementById('loadstatus').innerHTML = progress.percent;
- * }
- * }
- * </pre>
- *
- * @constructor
- * @param {(!o3d.ArchiveRequest|!o3d.FileRequest|!XMLHttpRequest)} opt_request
- * The request to watch.
- * @param {boolean} opt_hasStatus true if opt_request is a
- * o3d.ArchiveRequest vs for example an o3d.FileRequest or an
- * XMLHttpRequest.
- * @see o3djs.scene.loadScene
- * @see o3djs.io.loadArchive
- * @see o3djs.io.loadTexture
- * @see o3djs.loader.Loader
- */
-o3djs.io.LoadInfo = function(opt_request, opt_hasStatus) {
- this.request_ = opt_request;
- this.hasStatus_ = opt_hasStatus;
- this.streamLength_ = 0; // because the request may have been freed.
- this.children_ = [];
-};
-
-/**
- * Adds another LoadInfo as a child of this LoadInfo so they can be
- * managed as a group.
- * @param {!o3djs.io.LoadInfo} loadInfo The child LoadInfo.
- */
-o3djs.io.LoadInfo.prototype.addChild = function(loadInfo) {
- this.children_.push(loadInfo);
-};
-
-/**
- * Marks this LoadInfo as finished.
- */
-o3djs.io.LoadInfo.prototype.finish = function() {
- if (this.request_) {
- if (this.hasStatus_) {
- this.streamLength_ = this.request_.streamLength;
- }
- this.request_ = null;
- }
-};
-
-/**
- * Gets the total bytes that will be streamed known so far.
- * If you are only streaming 1 file then this will be the info for that file but
- * if you have queued up many files using an o3djs.loader.Loader only a couple of
- * files are streamed at a time meaning that the size is not known for files
- * that have yet started to download.
- *
- * If you are downloading many files for your application and you want to
- * provide a progress status you have about 4 options
- *
- * 1) Use LoadInfo.getTotalBytesDownloaded() /
- * LoadInfo.getTotalKnownBytesToStreamSoFar() and just be aware the bar will
- * grown and then shrink as new files start to download and their lengths
- * become known.
- *
- * 2) Use LoadInfo.getTotalRequestsDownloaded() /
- * LoadInfo.getTotalKnownRequestsToStreamSoFar() and be aware the granularity
- * is not all that great since it only reports fully downloaded files. If you
- * are downloading a bunch of small files this might be ok.
- *
- * 3) Put all your files in one archive. Then there will be only one file and
- * method 1 will work well.
- *
- * 4) Figure out the total size in bytes of the files you will download and put
- * that number in your application, then use LoadInfo.getTotalBytesDownloaded()
- * / MY_APPS_TOTAL_BYTES_TO_DOWNLOAD.
- *
- * @return {number} The total number of currently known bytes to be streamed.
- */
-o3djs.io.LoadInfo.prototype.getTotalKnownBytesToStreamSoFar = function() {
- if (!this.streamLength_ && this.request_ && this.hasStatus_) {
- this.streamLength_ = this.request_.streamLength;
- }
- var total = this.streamLength_;
- for (var cc = 0; cc < this.children_.length; ++cc) {
- total += this.children_[cc].getTotalKnownBytesToStreamSoFar();
- }
- return total;
-};
-
-/**
- * Gets the total bytes downloaded so far.
- * @return {number} The total number of currently known bytes to be streamed.
- */
-o3djs.io.LoadInfo.prototype.getTotalBytesDownloaded = function() {
- var total = (this.request_ && this.hasStatus_) ?
- this.request_.bytesReceived : this.streamLength_;
- for (var cc = 0; cc < this.children_.length; ++cc) {
- total += this.children_[cc].getTotalBytesDownloaded();
- }
- return total;
-};
-
-/**
- * Gets the total streams that will be download known so far.
- * We can't know all the streams since you could use an o3djs.loader.Loader
- * object, request some streams, then call this function, then request some
- * more.
- *
- * See LoadInfo.getTotalKnownBytesToStreamSoFar for details.
- * @return {number} The total number of requests currently known to be streamed.
- * @see o3djs.io.LoadInfo.getTotalKnownBytesToStreamSoFar
- */
-o3djs.io.LoadInfo.prototype.getTotalKnownRequestsToStreamSoFar = function() {
- var total = 1;
- for (var cc = 0; cc < this.children_.length; ++cc) {
- total += this.children_[cc].getTotalKnownRequestToStreamSoFar();
- }
- return total;
-};
-
-/**
- * Gets the total requests downloaded so far.
- * @return {number} The total requests downloaded so far.
- */
-o3djs.io.LoadInfo.prototype.getTotalRequestsDownloaded = function() {
- var total = this.request_ ? 0 : 1;
- for (var cc = 0; cc < this.children_.length; ++cc) {
- total += this.children_[cc].getTotalRequestsDownloaded();
- }
- return total;
-};
-
-/**
- * Gets progress info.
- * This is commonly formatted version of the information available from a
- * LoadInfo.
- *
- * See LoadInfo.getTotalKnownBytesToStreamSoFar for details.
- * @return {{percent: number, downloaded: string, totalBytes: string,
- * base: number, suffix: string}} progress info.
- * @see o3djs.io.LoadInfo.getTotalKnownBytesToStreamSoFar
- */
-o3djs.io.LoadInfo.prototype.getKnownProgressInfoSoFar = function() {
- var percent = 0;
- var bytesToDownload = this.getTotalKnownBytesToStreamSoFar();
- var bytesDownloaded = this.getTotalBytesDownloaded();
- if (bytesToDownload > 0) {
- percent = Math.floor(bytesDownloaded / bytesToDownload * 100);
- }
-
- var base = (bytesToDownload < 1024 * 1024) ? 1024 : (1024 * 1024);
-
- return {
- percent: percent,
- downloaded: (bytesDownloaded / base).toFixed(2),
- totalBytes: (bytesToDownload / base).toFixed(2),
- base: base,
- suffix: (base == 1024 ? 'kb' : 'mb')}
-
-};
-
-/**
- * Loads text from an external file. This function is synchronous.
- * @param {string} url The url of the external file.
- * @return {string} the loaded text if the request is synchronous.
- */
-o3djs.io.loadTextFileSynchronous = function(url) {
- o3djs.BROWSER_ONLY = true;
-
- var error = 'loadTextFileSynchronous failed to load url "' + url + '"';
- var request;
- if (!o3djs.base.IsMSIE() && window.XMLHttpRequest) {
- request = new XMLHttpRequest();
- if (request.overrideMimeType) {
- request.overrideMimeType('text/plain');
- }
- } else if (window.ActiveXObject) {
- request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
- } else {
- throw 'XMLHttpRequest is disabled';
- }
- request.open('GET', url, false);
- request.send(null);
- if (request.readyState != 4) {
- throw error;
- }
- return request.responseText;
-};
-
-/**
- * Loads text from an external file. This function is asynchronous.
- * @param {string} url The url of the external file.
- * @param {function(string, *): void} callback A callback passed the loaded
- * string and an exception which will be null on success.
- * @return {!o3djs.io.LoadInfo} A LoadInfo to track progress.
- */
-o3djs.io.loadTextFile = function(url, callback) {
- o3djs.BROWSER_ONLY = true;
-
- var error = 'loadTextFile failed to load url "' + url + '"';
- var request;
- if (!o3djs.base.IsMSIE() && window.XMLHttpRequest) {
- request = new XMLHttpRequest();
- if (request.overrideMimeType) {
- request.overrideMimeType('text/plain');
- }
- } else if (window.ActiveXObject) {
- request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
- } else {
- throw 'XMLHttpRequest is disabled';
- }
- var loadInfo = o3djs.io.createLoadInfo(request, false);
- request.open('GET', url, true);
- var finish = function() {
- if (request.readyState == 4) {
- var text = '';
- // HTTP reports success with a 200 status. The file protocol reports
- // success with zero. HTTP does not use zero as a status code (they
- // start at 100).
- // https://developer.mozilla.org/En/Using_XMLHttpRequest
- var success = request.status == 200 || request.status == 0;
- if (success) {
- text = request.responseText;
- }
- loadInfo.finish();
- callback(text, success ? null : 'could not load: ' + url);
- }
- };
- request.onreadystatechange = finish;
- request.send(null);
- return loadInfo;
-};
-
-/**
- * A ArchiveInfo object loads and manages an archive of files.
- * There are methods for locating a file by uri and for freeing
- * the archive.
- *
- * You can only read archives that have as their first file a file named
- * 'aaaaaaaa.o3d' the contents of the which is 'o3d'. This is to prevent O3D
- * from being used to read arbitrary tar gz files.
- *
- * Example:
- * <pre>
- * var loadInfo = o3djs.io.loadArchive(pack,
- * 'http://google.com/files.o3dtgz',
- * callback);
- *
- * function callback(archiveInfo, exception) {
- * if (!exception) {
- * o3djs.texture.createTextureFromRawData(
- * pack, archiveInfo.getFileByURI('logo.jpg'), true);
- * o3djs.texture.createTextureFromRawData(
- * pack, archiveInfo.getFileByURI('wood/oak.png'), true);
- * o3djs.texture.createTextureFromRawData(
- * pack, archiveInfo.getFileByURI('wood/maple.dds'), true);
- * archiveInfo.destroy();
- * } else {
- * alert(exception);
- * }
- * }
- * </pre>
- *
- * @constructor
- * @param {!o3d.Pack} pack Pack to create request in.
- * @param {string} url The url of the archive file.
- * @param {!function(!o3djs.io.ArchiveInfo, *): void} onFinished A
- * callback that is called when the archive is finished loading and passed
- * the ArchiveInfo and an exception which is null on success.
- */
-o3djs.io.ArchiveInfo = function(pack, url, onFinished) {
- var that = this;
-
- /**
- * The list of files in the archive by uri.
- * @type {!Object}
- */
- this.files = {};
-
- /**
- * The pack used to create the archive request.
- * @type {!o3d.Pack}
- */
- this.pack = pack;
-
- /**
- * True if this archive has not be destroyed.
- * @type {boolean}
- */
- this.destroyed = false;
-
- this.request_ = null;
-
- /**
- * Records each RawData file as it comes in.
- * @private
- * @param {!o3d.RawData} rawData RawData from archive request.
- */
- function addFile(rawData) {
- that.files[rawData.uri] = rawData;
- }
-
- /**
- * The LoadInfo to track loading progress.
- * @type {!o3djs.io.LoadInfo}
- */
- this.loadInfo = o3djs.io.loadArchiveAdvanced(
- pack,
- url,
- addFile,
- function(request, exception) {
- that.request_ = request;
- onFinished(that, exception);
- });
-};
-
-/**
- * Releases all the RAW data associated with this archive. It does not release
- * any objects created from that RAW data.
- */
-o3djs.io.ArchiveInfo.prototype.destroy = function() {
- if (!this.destroyed) {
- this.pack.removeObject(this.request_);
- this.destroyed = true;
- this.files = {};
- }
-};
-
-/**
- * Gets files by regular expression or wildcards from the archive.
- * @param {(string|!RegExp)} uri of file to get. Can have wildcards '*' and '?'.
- * @param {boolean} opt_caseInsensitive Only valid if it's a wildcard string.
- * @return {!Array.<!o3d.RawData>} An array of the matching RawDatas for
- * the files matching or undefined if it doesn't exist.
- */
-o3djs.io.ArchiveInfo.prototype.getFiles = function(uri,
- opt_caseInsensitive) {
- if (!(uri instanceof RegExp)) {
- uri = uri.replace(/(\W)/g, '\\$&');
- uri = uri.replace(/\\\*/g, '.*');
- uri = uri.replace(/\\\?/g, '.');
- uri = new RegExp(uri, opt_caseInsensitive ? 'i' : '');
- }
- var files = [];
- for (var key in this.files) {
- if (uri.test(key)) {
- files.push(this.files[key]);
- }
- }
-
- return files;
-};
-
-/**
- * Gets a file by URI from the archive.
- * @param {string} uri of file to get.
- * @param {boolean} opt_caseInsensitive True to be case insensitive. Default
- * false.
- * @return {(o3d.RawData|undefined)} The RawData for the file or undefined if
- * it doesn't exist.
- */
-o3djs.io.ArchiveInfo.prototype.getFileByURI = function(
- uri,
- opt_caseInsensitive) {
- if (opt_caseInsensitive) {
- uri = uri.toLowerCase();
- for (var key in this.files) {
- if (key.toLowerCase() == uri) {
- return this.files[key];
- }
- }
- return undefined;
- } else {
- return this.files[uri];
- }
-};
-
-/**
- * Loads an archive file.
- * When the entire archive is ready the onFinished callback will be called
- * with an ArchiveInfo for accessing the archive.
- *
- * @param {!o3d.Pack} pack Pack to create request in.
- * @param {string} url The url of the archive file.
- * @param {!function(!o3djs.io.ArchiveInfo, *): void} onFinished A
- * callback that is called when the archive is successfully loaded and an
- * Exception object which is null on success.
- * @return {!o3djs.io.LoadInfo} The a LoadInfo for tracking progress.
- * @see o3djs.io.ArchiveInfo
- */
-o3djs.io.loadArchive = function(pack,
- url,
- onFinished) {
- var archiveInfo = new o3djs.io.ArchiveInfo(pack, url, onFinished);
- return archiveInfo.loadInfo;
-};
-
-/**
- * Loads an archive file. This function is asynchronous. This is a low level
- * version of o3djs.io.loadArchive which can be used for things like
- * progressive loading.
- *
- * @param {!o3d.Pack} pack Pack to create request in.
- * @param {string} url The url of the archive file.
- * @param {!function(!o3d.RawData): void} onFileAvailable A callback, taking a
- * single argument 'data'. As each file is loaded from the archive, this
- * function is called with the file's data.
- * @param {!function(!o3d.ArchiveRequest, *): void} onFinished
- * A callback that is called when the archive is successfully loaded. It is
- * passed the ArchiveRquest and null on success or a javascript exception on
- * failure.
- * @return {!o3djs.io.LoadInfo} A LoadInfo for tracking progress.
- */
-o3djs.io.loadArchiveAdvanced = function(pack,
- url,
- onFileAvailable,
- onFinished) {
- var error = 'loadArchive failed to load url "' + url + '"';
- var request = pack.createArchiveRequest();
- var loadInfo = o3djs.io.createLoadInfo(request, true);
- request.open('GET', url);
- request.onfileavailable = onFileAvailable;
- /**
- * @ignore
- */
- request.onreadystatechange = function() {
- if (request.done) {
- loadInfo.finish();
- var success = request.success;
- var exception = null;
- if (!success) {
- exception = request.error;
- if (!exception) {
- exception = 'unknown error loading archive';
- }
- }
- onFinished(request, exception);
- }
- };
- request.send();
- return loadInfo;
-};
-
-/**
- * Loads RawData.
- *
- * RawData is loaded asynchronously.
- *
- * @param {!o3d.Pack} pack Pack to create the request in.
- * @param {string} url URL of raw data to load.
- * @param {!function(!o3d.FileRequest, o3d.RawData, *): void} callback Callback
- * when RawData is loaded. It will be passed the FileRequest, a RawData and
- * an exception on error or null on success. The RawData is associated with
- * the request so it will stay in memory until you free with request with
- * pack.removeObject(request).
- * @return {!o3djs.io.LoadInfo} A LoadInfo to track progress.
- * @see o3djs.io.loadTexture
- * @see o3djs.io.loadBitmaps
- * @see o3djs.loader.createLoader
- */
-o3djs.io.loadRawData = function(pack, url, callback) {
- var request = pack.createFileRequest('RAWDATA');
- var loadInfo = o3djs.io.createLoadInfo(
- /** @type {!o3d.FileRequest} */ (request),
- false);
- request.open('GET', url, true);
- /**
- * @ignore
- */
- request.onreadystatechange = function() {
- if (request.done) {
- var data = request.data;
- var success = request.success;
- var exception = request.error;
- loadInfo.finish();
- if (!success && !exception) {
- exception = 'unknown error loading RawData: ' + url;
- }
- callback(request, data, success ? null : exception);
- }
- };
- request.send();
- return loadInfo;
-};
-
-/**
- * Loads bitmaps.
- *
- * Bitmaps are loaded asynchronously.
- *
- * Example:
- * <pre>
- * var loadInfo = o3djs.io.loadBitamps(pack,
- * 'http://google.com/someimage.jpg',
- * callback);
- *
- * function callback(bitmaps, exception) {
- * if (!exception) {
- * o3djs.texture.createTextureFromBitmaps(g_pack, bitmaps, true);
- * } else {
- * alert(exception);
- * }
- * }
- * </pre>
- *
- *
- * @param {!o3d.Pack} pack Pack to load texture into.
- * @param {string} url URL of image to load.
- * @param {!function(!Array.<!o3d.Bitmap>, *): void} callback Callback when
- * image is loaded. It will be passed an array of bitmaps and an exception
- * on error or null on success.
- * @param {boolean} opt_generateMips Generate Mips. Default = true.
- * @return {!o3djs.io.LoadInfo} A LoadInfo to track progress.
- * @see o3djs.io.loadTexture
- * @see o3djs.loader.createLoader
- */
-o3djs.io.loadBitmaps = function(pack, url, callback, opt_generateMips) {
- if (typeof opt_generateMips === 'undefined') {
- opt_generateMips = true;
- }
- return o3djs.io.loadRawData(pack, url, function(request, rawData, exception) {
- var bitmaps = [];
- if (!exception) {
- bitmaps = pack.createBitmapsFromRawData(rawData);
- pack.removeObject(request);
- }
- callback(bitmaps, exception);
- });
-};
-
-/**
- * Loads a texture.
- *
- * Textures are loaded asynchronously.
- *
- * Example:
- * <pre>
- * var loadInfo = o3djs.io.loadTexture(pack,
- * 'http://google.com/someimage.jpg',
- * callback);
- *
- * function callback(texture, exception) {
- * if (!exception) {
- * g_mySampler.texture = texture;
- * } else {
- * alert(exception);
- * }
- * }
- * </pre>
- *
- *
- * @param {!o3d.Pack} pack Pack to load texture into.
- * @param {string} url URL of texture to load.
- * @param {!function(o3d.Texture, *): void} callback Callback when
- * texture is loaded. It will be passed the texture and an exception on
- * error or null on success.
- * @param {boolean} opt_generateMips Generate Mips. Default = true.
- * @param {boolean} opt_flip Flip texture. Default = true.
- * @return {!o3djs.io.LoadInfo} A LoadInfo to track progress.
- * @see o3djs.io.loadBitmaps
- * @see o3djs.loader.createLoader
- */
-o3djs.io.loadTexture = function(
- pack, url, callback, opt_generateMips, opt_flip) {
- function onLoaded(request, rawData, exception) {
- var texture = null;
- if (!exception) {
- texture = o3djs.texture.createTextureFromRawData(
- pack, rawData, opt_generateMips, opt_flip);
- pack.removeObject(request);
- }
- callback(texture, exception);
- };
-
- return o3djs.io.loadRawData(pack, url, onLoaded);
-};
-
-
diff --git a/o3d/samples/o3djs/js_list.manifest b/o3d/samples/o3djs/js_list.manifest
deleted file mode 100644
index 5e7423e..0000000
--- a/o3d/samples/o3djs/js_list.manifest
+++ /dev/null
@@ -1,63 +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.
-
-[ 'arcball.js',
- 'base.js',
- 'camera.js',
- 'canvas.js',
- 'debug.js',
- 'dump.js',
- 'effect.js',
- 'element.js',
- 'error.js',
- 'event.js',
- 'fps.js',
- 'gpu2d.js',
- 'io.js',
- 'loader.js',
- 'material.js',
- 'manipulators.js',
- 'math.js',
- 'pack.js',
- 'particles.js',
- 'performance.js',
- 'picking.js',
- 'primitives.js',
- 'lineprimitives.js', # lineprimitives.js must come after primitives.js
- 'quaternions.js',
- 'rendergraph.js',
- 'scene.js',
- 'serialization.js',
- 'shape.js',
- 'simple.js',
- 'test.js',
- 'texture.js',
- 'util.js',
-]
-
diff --git a/o3d/samples/o3djs/lineprimitives.js b/o3d/samples/o3djs/lineprimitives.js
deleted file mode 100644
index 4078f9c..0000000
--- a/o3d/samples/o3djs/lineprimitives.js
+++ /dev/null
@@ -1,396 +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.
- */
-
-
-/**
- * @fileoverview This file contains various functions to help
- * create line primitives for o3d applications.
- *
- * Note: This library is only a sample. It is not meant to be some official
- * library. It is provided only as example code.
- *
- */
-
-o3djs.provide('o3djs.lineprimitives');
-
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.primitives');
-
-/**
- * Defines a namespace for o3djs.lineprimitives.
- * @namespace
- */
-o3djs.lineprimitives = o3djs.lineprimitives || {};
-
-/**
- * A LineVertexInfo is a specialization of VertexInfoBase for line based
- * geometry.
- * @constructor
- * @extends {o3djs.primitives.VertexInfoBase}
- */
-o3djs.lineprimitives.LineVertexInfo = function() {
- o3djs.primitives.VertexInfoBase.call(this);
-}
-
-o3djs.base.inherit(o3djs.lineprimitives.LineVertexInfo,
- o3djs.primitives.VertexInfoBase);
-
-/**
- * Returns the number of lines represented by the LineVertexInfo.
- * @return {number} The number of lines represented by LineVertexInfo.
- */
-o3djs.lineprimitives.LineVertexInfo.prototype.numLines = function() {
- return this.indices.length / 2;
-};
-
-/**
- * Adds a line.
- * @param {number} index1 The index of the first vertex of the line.
- * @param {number} index2 The index of the second vertex of the line.
- */
-o3djs.lineprimitives.LineVertexInfo.prototype.addLine = function(
- index1, index2) {
- this.indices.push(index1, index2);
-};
-
-/**
- * Gets the vertex indices of the triangle at the given triangle index.
- * @param {number} triangleIndex The index of the triangle.
- * @return {!Array.<number>} An array of three triangle indices.
- */
-o3djs.lineprimitives.LineVertexInfo.prototype.getLine = function(
- triangleIndex) {
- var indexIndex = triangleIndex * 3;
- return [this.indices[indexIndex + 0],
- this.indices[indexIndex + 1],
- this.indices[indexIndex + 2]];
-};
-
-/**
- * Sets the vertex indices of the line at the given line index.
- * @param {number} lineIndex The index of the line.
- * @param {number} index1 The index of the first vertex of the line.
- * @param {number} index2 The index of the second vertex of the line.
- */
-o3djs.lineprimitives.LineVertexInfo.prototype.setLine = function(
- lineIndex, index1, index2) {
- var indexIndex = lineIndex * 2;
- this.indices[indexIndex + 0] = index1;
- this.indices[indexIndex + 1] = index2;
-};
-
-/**
- * Creates a shape from a LineVertexInfo
- * @param {!o3d.Pack} pack Pack to create objects in.
- * @param {!o3d.Material} material to use.
- * @return {!o3d.Shape} The created shape.
- */
-o3djs.lineprimitives.LineVertexInfo.prototype.createShape = function(
- pack,
- material) {
- return this.createShapeByType(
- pack, material, o3djs.base.o3d.Primitive.LINELIST);
-};
-
-/**
- * Creates a new LineVertexInfo.
- * @return {!o3djs.lineprimitives.LineVertexInfo} The new LineVertexInfo.
- */
-o3djs.lineprimitives.createLineVertexInfo = function() {
- return new o3djs.lineprimitives.LineVertexInfo();
-};
-
-/**
- * Creates the vertices and indices for a cube of lines.
- * The cube will be created around the origin (-size / 2, size / 2).
- * The created cube has a position stream only and can therefore only be used
- * with appropriate shaders.
- *
- * @param {number} size Width, height and depth of the cube.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply all
- * the vertices.
- * @return {!o3djs.lineprimitives.LineVertexInfo} The created cube vertices.
- */
-o3djs.lineprimitives.createLineCubeVertices = function(size, opt_matrix) {
- var k = size / 2;
-
- var vertices = [
- [-k, -k, -k],
- [+k, -k, -k],
- [-k, +k, -k],
- [+k, +k, -k],
- [-k, -k, +k],
- [+k, -k, +k],
- [-k, +k, +k],
- [+k, +k, +k]
- ];
-
- var indices = [
- [0, 1],
- [1, 3],
- [3, 2],
- [2, 0],
- [4, 5],
- [5, 7],
- [7, 6],
- [6, 4],
- [0, 4],
- [1, 5],
- [2, 6],
- [3, 7]
- ];
-
- var vertexInfo = o3djs.lineprimitives.createLineVertexInfo();
- var positionStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.POSITION);
-
- for (var v = 0; v < vertices.length; ++v) {
- positionStream.addElementVector(vertices[v]);
- }
-
- for (var i = 0; i < indices.length; ++i) {
- vertexInfo.addLine(indices[i][0], indices[i][1]);
- }
-
- if (opt_matrix) {
- vertexInfo.reorient(opt_matrix);
- }
- return vertexInfo;
-};
-
-/**
- * Creates a cube of lines.
- * The cube will be created around the origin (-size / 2, size / 2).
- * The created cube has a position stream only and can therefore only be used
- * with appropriate shaders.
- *
- * @param {!o3d.Pack} pack Pack to create cube elements in.
- * @param {!o3d.Material} material Material to use.
- * @param {number} size Width, height and depth of the cube.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply all
- * the vertices.
- * @return {!o3d.Shape} The created cube.
- */
-o3djs.lineprimitives.createLineCube = function(
- pack,
- material,
- size,
- opt_matrix) {
- var vertexInfo =
- o3djs.lineprimitives.createLineCubeVertices(size, opt_matrix);
- return vertexInfo.createShape(pack, material);
-};
-
-/**
- * Creates sphere vertices.
- * The created sphere has a position stream only and can therefore only be
- * used with appropriate shaders.
- *
- * @param {number} radius radius of the sphere.
- * @param {number} subdivisionsAxis number of steps around the sphere.
- * @param {number} subdivisionsHeight number of steps vertically on the sphere.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply all
- * the vertices.
- * @return {!o3djs.lineprimitives.LineVertexInfo} The created sphere vertices.
- */
-o3djs.lineprimitives.createLineSphereVertices = function(
- radius,
- subdivisionsAxis,
- subdivisionsHeight,
- opt_matrix) {
- if (subdivisionsAxis <= 0 || subdivisionsHeight <= 0) {
- throw Error('subdivisionAxis and subdivisionHeight must be > 0');
- }
-
- // We are going to generate our sphere by iterating through its
- // spherical coordinates and generating 1 quad for each quad on a
- // ring of the sphere.
-
- var vertexInfo = o3djs.lineprimitives.createLineVertexInfo();
- var positionStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.POSITION);
-
- // Generate the individual vertices in our vertex buffer.
- for (var y = 0; y <= subdivisionsHeight; y++) {
- for (var x = 0; x <= subdivisionsAxis; x++) {
- // Generate a vertex based on its spherical coordinates
- var u = x / subdivisionsAxis
- var v = y / subdivisionsHeight;
- var theta = 2 * Math.PI * u;
- var phi = Math.PI * v;
- var sinTheta = Math.sin(theta);
- var cosTheta = Math.cos(theta);
- var sinPhi = Math.sin(phi);
- var cosPhi = Math.cos(phi);
- var ux = cosTheta * sinPhi;
- var uy = cosPhi;
- var uz = sinTheta * sinPhi;
- positionStream.addElement(radius * ux, radius * uy, radius * uz);
- }
- }
- var numVertsAround = subdivisionsAxis + 1;
-
- for (var x = 0; x < subdivisionsAxis; x++) {
- for (var y = 0; y < subdivisionsHeight; y++) {
- // Make 2 lines per quad.
- vertexInfo.addLine(
- (y + 0) * numVertsAround + x,
- (y + 0) * numVertsAround + x + 1);
- vertexInfo.addLine(
- (y + 0) * numVertsAround + x,
- (y + 1) * numVertsAround + x);
- }
- }
-
- if (opt_matrix) {
- vertexInfo.reorient(opt_matrix);
- }
- return vertexInfo;
-};
-
-/**
- * Creates a sphere.
- * The created sphere has a position stream only and can therefore only be
- * used with appropriate shaders.
- *
- * @param {!o3d.Pack} pack Pack to create sphere elements in.
- * @param {!o3d.Material} material Material to use.
- * @param {number} radius radius of the sphere.
- * @param {number} subdivisionsAxis number of steps around the sphere.
- * @param {number} subdivisionsHeight number of steps vertically on the sphere.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply all
- * the vertices.
- * @return {!o3d.Shape} The created sphere.
- *
- * @see o3d.Pack
- * @see o3d.Shape
- */
-o3djs.lineprimitives.createLineSphere = function(
- pack,
- material,
- radius,
- subdivisionsAxis,
- subdivisionsHeight,
- opt_matrix) {
- var vertexInfo = o3djs.lineprimitives.createLineSphereVertices(
- radius,
- subdivisionsAxis,
- subdivisionsHeight,
- opt_matrix);
-
- return vertexInfo.createShape(pack, material);
-};
-
-/**
- * Creates ring vertices.
- * The ring is a circle in the XZ plane, centered at the origin.
- * The created ring has position, normal, and 1-D texcoord streams.
- * The normals point outwards from the center of the ring.
- * The texture coordinates are based on angle about the center.
- *
- * @param {number} radius Radius of the ring.
- * @param {number} subdivisions Number of steps around the ring.
- * @param {number} maxTexCoord 1-D texture coordinates will range from 0 to
- * this value, based on angle about the center.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply all
- * the vertices.
- * @return {!o3djs.lineprimitives.LineVertexInfo} The created ring vertices.
- */
-o3djs.lineprimitives.createLineRingVertices = function(
- radius,
- subdivisions,
- maxTexCoord,
- opt_matrix) {
- if (subdivisions < 3) {
- throw Error('subdivisions must be >= 3');
- }
-
- var vertexInfo = o3djs.lineprimitives.createLineVertexInfo();
- var positionStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.POSITION);
- var normalStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.NORMAL);
- var texCoordStream = vertexInfo.addStream(
- 1, o3djs.base.o3d.Stream.TEXCOORD, 0);
-
- // Generate the individual vertices in our vertex buffer.
- for (var i = 0; i <= subdivisions; i++) {
- var theta = 2 * Math.PI * i / subdivisions;
- positionStream.addElement(radius * Math.cos(theta), 0,
- radius * Math.sin(theta));
- normalStream.addElement(Math.cos(theta), 0, Math.sin(theta));
- texCoordStream.addElement(maxTexCoord * i / subdivisions);
- }
-
- // Connect the vertices by simple lines.
- for (var i = 0; i < subdivisions; i++) {
- vertexInfo.addLine(i, i+1);
- }
-
- if (opt_matrix) {
- vertexInfo.reorient(opt_matrix);
- }
- return vertexInfo;
-};
-
-/**
- * Creates a ring.
- * The ring is a circle in the XZ plane, centered at the origin.
- * The created ring has position, normal, and 1-D texcoord streams.
- * The normals point outwards from the center of the ring.
- * The texture coordinates are based on angle about the center.
- *
- * @param {!o3d.Pack} pack Pack to create ring elements in.
- * @param {!o3d.Material} material Material to use.
- * @param {number} radius Radius of the ring.
- * @param {number} subdivisions Number of steps around the ring.
- * @param {number} maxTexCoord 1-D texture coordinates will range from 0 to
- * this value, based on angle about the center.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply all
- * the vertices.
- * @return {!o3d.Shape} The created ring.
- */
-o3djs.lineprimitives.createLineRing = function(
- pack,
- material,
- radius,
- subdivisions,
- maxTexCoord,
- opt_matrix) {
- var vertexInfo = o3djs.lineprimitives.createLineRingVertices(
- radius,
- subdivisions,
- maxTexCoord,
- opt_matrix);
-
- return vertexInfo.createShape(pack, material);
-};
-
diff --git a/o3d/samples/o3djs/loader.js b/o3d/samples/o3djs/loader.js
deleted file mode 100644
index fa38e2d..0000000
--- a/o3d/samples/o3djs/loader.js
+++ /dev/null
@@ -1,241 +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.
- */
-
-
-/**
- * @fileoverview This file contains a loader class for helping to load
- * muliple assets in an asynchronous manner.
- */
-
-o3djs.provide('o3djs.loader');
-
-o3djs.require('o3djs.io');
-o3djs.require('o3djs.scene');
-
-/**
- * A Module with a loader class for helping to load muliple assets in an
- * asynchronous manner.
- * @namespace
- */
-o3djs.loader = o3djs.loader || {};
-
-/**
- * A simple Loader class to call some callback when everything has loaded.
- * @constructor
- * @param {!function(): void} onFinished Function to call when final item has
- * loaded.
- */
-o3djs.loader.Loader = function(onFinished) {
- this.count_ = 1;
- this.onFinished_ = onFinished;
-
- /**
- * The LoadInfo for this loader you can use to track progress.
- * @type {!o3djs.io.LoadInfo}
- */
- this.loadInfo = o3djs.io.createLoadInfo();
-};
-
-/**
- * Creates a Loader for helping to load a bunch of items asychronously.
- *
- * The way you use this is as follows.
- *
- * <pre>
- * var loader = o3djs.loader.createLoader(myFinishedCallback);
- * loader.loadTexture(pack, texture1Url, callbackForTexture);
- * loader.loadTexture(pack, texture2Url, callbackForTexture);
- * loader.loadTexture(pack, texture3Url, callbackForTexture);
- * loader.finish();
- * </pre>
- *
- * The loader guarantees that myFinishedCallback will be called after
- * all the items have been loaded.
- *
-* @param {!function(): void} onFinished Function to call when final item has
-* loaded.
-* @return {!o3djs.loader.Loader} A Loader Object.
- */
-o3djs.loader.createLoader = function(onFinished) {
- return new o3djs.loader.Loader(onFinished);
-};
-
-/**
- * Loads a texture.
- * @param {!o3d.Pack} pack Pack to load texture into.
- * @param {string} url URL of texture to load.
- * @param {!function(o3d.Texture, *): void} opt_onTextureLoaded
- * optional callback when texture is loaded. It will be passed the texture
- * and an exception which is null on success.
- */
-o3djs.loader.Loader.prototype.loadTexture = function(pack,
- url,
- opt_onTextureLoaded) {
- var that = this; // so the function below can see "this".
- ++this.count_;
- var loadInfo = o3djs.io.loadTexture(pack, url, function(texture, exception) {
- if (opt_onTextureLoaded) {
- opt_onTextureLoaded(texture, exception);
- }
- that.countDown_();
- });
- this.loadInfo.addChild(loadInfo);
-};
-
-/**
- * Loads a RawData.
- * @param {!o3d.Pack} pack Pack to load texture into.
- * @param {string} url URL of image file to load.
- * @param {!function(!o3d.FileRequest, o3d.RawData, *): void} onLoaded Callback
- * when RawData is loaded. It will be passed the request, a RawData and an
- * exception which is null on success. The RawData is associated with
- * the request so it will stay in memory until you free with request with
- * pack.removeObject(request).
- */
-o3djs.loader.Loader.prototype.loadRawData = function(pack,
- url,
- onLoaded) {
- var that = this; // so the function below can see "this".
- ++this.count_;
- var loadInfo = o3djs.io.loadRawData(
- pack, url, function(request, rawData, exception) {
- onLoaded(request, rawData, exception);
- that.countDown_();
- });
- this.loadInfo.addChild(loadInfo);
-};
-
-/**
- * Loads bitmaps.
- * @param {!o3d.Pack} pack Pack to load texture into.
- * @param {string} url URL of image file to load.
- * @param {!function(!Array.<!o3d.Bitmap>, *): void} onBitmapsLoaded Callback
- * when bitmaps are loaded. It will be passed an array of bitmaps and an
- * exception which is null on success.
- */
-o3djs.loader.Loader.prototype.loadBitmaps = function(pack,
- url,
- onBitmapsLoaded) {
- var that = this; // so the function below can see "this".
- ++this.count_;
- var loadInfo = o3djs.io.loadBitmaps(pack, url, function(bitmaps, exception) {
- onBitmapsLoaded(bitmaps, exception);
- that.countDown_();
- });
- this.loadInfo.addChild(loadInfo);
-};
-
-/**
- * Loads a 3d scene.
- * @param {!o3d.Client} client An O3D client object.
- * @param {!o3d.Pack} pack Pack to load texture into.
- * @param {!o3d.Transform} parent Transform to parent scene under.
- * @param {string} url URL of scene to load.
- * @param {!o3djs.serialization.Options} opt_options Options passed into the
- * loader.
- * @param {!function(!o3d.Pack, !o3d.Transform, *): void}
- * opt_onSceneLoaded optional callback when scene is loaded. It will be
- * passed the pack and parent and an exception which is null on success.
- */
-o3djs.loader.Loader.prototype.loadScene = function(client,
- pack,
- parent,
- url,
- opt_onSceneLoaded,
- opt_options) {
- var that = this; // so the function below can see "this".
- ++this.count_;
- var loadInfo = o3djs.scene.loadScene(
- client, pack, parent, url, function(pack, parent, exception) {
- if (opt_onSceneLoaded) {
- opt_onSceneLoaded(pack, parent, exception);
- }
- that.countDown_();
- },
- opt_options);
- this.loadInfo.addChild(loadInfo);
-};
-
-/**
- * Loads a text file.
- * @param {string} url URL of scene to load.
- * @param {!function(string, *): void} onTextLoaded Function to call when
- * the file is loaded. It will be passed the contents of the file as a
- * string and an exception which is null on success.
- */
-o3djs.loader.Loader.prototype.loadTextFile = function(url, onTextLoaded) {
- var that = this; // so the function below can see "this".
- ++this.count_;
- var loadInfo = o3djs.io.loadTextFile(url, function(string, exception) {
- onTextLoaded(string, exception);
- that.countDown_();
- });
- this.loadInfo.addChild(loadInfo);
-};
-
-/**
- * Creates a loader that is tracked by this loader so that when the new loader
- * is finished it will be reported to this loader.
- * @param {!function(): void} onFinished Function to be called when everything
- * loaded with this loader has finished.
- * @return {!o3djs.loader.Loader} The new Loader.
- */
-o3djs.loader.Loader.prototype.createLoader = function(onFinished) {
- var that = this;
- ++this.count_;
- var loader = o3djs.loader.createLoader(function() {
- onFinished();
- that.countDown_();
- });
- this.loadInfo.addChild(loader.loadInfo);
- return loader;
-};
-
-/**
- * Counts down the internal count and if it gets to zero calls the callback.
- * @private
- */
-o3djs.loader.Loader.prototype.countDown_ = function() {
- --this.count_;
- if (this.count_ === 0) {
- this.onFinished_();
- }
-};
-
-/**
- * Finishes the loading process.
- * Actually this just calls countDown_ to account for the count starting at 1.
- */
-o3djs.loader.Loader.prototype.finish = function() {
- this.countDown_();
-};
-
-
diff --git a/o3d/samples/o3djs/manipulators.js b/o3d/samples/o3djs/manipulators.js
deleted file mode 100644
index 4aa300f..0000000
--- a/o3d/samples/o3djs/manipulators.js
+++ /dev/null
@@ -1,1910 +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.
- */
-
-
-/**
- * @fileoverview This file contains classes that implement several
- * forms of 2D and 3D manipulation.
- */
-
-o3djs.provide('o3djs.manipulators');
-
-o3djs.require('o3djs.lineprimitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.picking');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.quaternions');
-
-/**
- * A module implementing several forms of 2D and 3D manipulation.
- * @namespace
- */
-o3djs.manipulators = o3djs.manipulators || {};
-
-/**
- * Creates a new manipulator manager, which maintains multiple
- * manipulators in the same scene. The manager is implicitly
- * associated with a particular O3D client via the Pack which is
- * passed in, although multiple managers can be created for a given
- * client. The manipulators are positioned in world coordinates and
- * are placed in the scene graph underneath the parent transform which
- * is passed in.
- * @param {!o3d.Pack} pack Pack in which manipulators' geometry and
- * materials will be created.
- * @param {!o3d.Transform} parentTransform The parent transform under
- * which the manipulators' geometry should be parented.
- * @param {!o3d.RenderNode} parentRenderNode The parent render node
- * under which the manipulators' draw elements should be placed.
- * @param {number} renderNodePriority The priority that the
- * manipulators' geometry should use for rendering.
- * @param {!o3d.DrawContext} drawContext The DrawContext to use for the
- * manipulators.
- * @return {!o3djs.manipulators.Manager} The created manipulator
- * manager.
- */
-o3djs.manipulators.createManager = function(pack,
- parentTransform,
- parentRenderNode,
- renderNodePriority,
- drawContext) {
- return new o3djs.manipulators.Manager(pack,
- parentTransform,
- parentRenderNode,
- renderNodePriority,
- drawContext);
-};
-
-//
-// Some linear algebra classes.
-// TODO(kbr): find a better home for these.
-//
-
-/**
- * Creates a new Line object, which implements projection and
- * closest-point operations.
- * @constructor
- * @private
- * @param {!o3djs.math.Vector3} opt_direction The direction of the
- * line. Does not need to be normalized but must not be the zero
- * vector. Defaults to [1, 0, 0] if not specified.
- * @param {!o3djs.math.Vector3} opt_point A point through which the
- * line goes. Defaults to [0, 0, 0] if not specified.
- */
-o3djs.manipulators.Line_ = function(opt_direction,
- opt_point) {
- /**
- * The direction of the line.
- * @private
- * @type {!o3djs.math.Vector3}
- */
- this.direction_ = o3djs.math.copyVector(opt_direction || [1, 0, 0]);
- /**
- * A point through which the line goes.
- * @private
- * @type {!o3djs.math.Vector3}
- */
- this.point_ = o3djs.math.copyVector(opt_point || [0, 0, 0]);
- this.recalc_();
-};
-
-/**
- * Sets the direction of this line.
- * @private
- * @param {!o3djs.math.Vector3} direction The new direction of the
- * line. Does not need to be normalized but must not be the zero
- * vector.
- */
-o3djs.manipulators.Line_.prototype.setDirection = function(direction) {
- this.direction_ = o3djs.math.copyVector(direction);
- this.recalc_();
-};
-
-/**
- * Gets the direction of this line.
- * @private
- * @return {!o3djs.math.Vector3} The direction of the line.
- */
-o3djs.manipulators.Line_.prototype.getDirection = function() {
- return this.direction_;
-};
-
-/**
- * Sets one point through which this line travels.
- * @private
- * @param {!o3djs.math.Vector3} point A point which through the line
- * will travel.
- */
-o3djs.manipulators.Line_.prototype.setPoint = function(point) {
- this.point_ = o3djs.math.copyVector(point);
- this.recalc_();
-};
-
-/**
- * Gets one point through which this line travels.
- * @private
- * @return {!o3djs.math.Vector3} A point which through the line
- * travels.
- */
-o3djs.manipulators.Line_.prototype.getPoint = function() {
- return this.point_;
-};
-
-/**
- * Projects a point onto the line.
- * @private
- * @param {!o3djs.math.Vector3} point Point to be projected.
- * @return {!o3djs.math.Vector3} Point on the line closest to the
- * passed point.
- */
-o3djs.manipulators.Line_.prototype.projectPoint = function(point) {
- var dotp = o3djs.math.dot(this.direction_, point);
- return o3djs.math.addVector(this.alongVec_,
- o3djs.math.mulScalarVector(dotp,
- this.direction_));
-};
-
-/**
- * A threshold / error tolerance for determining if a number should be
- * considered zero.
- * @type {!number}
- */
-o3djs.manipulators.EPSILON = 0.00001;
-
-/**
- * A unit vector pointing along the positive X-axis.
- * @type {!o3djs.math.Vector3}
- */
-o3djs.manipulators.X_AXIS = [1, 0, 0];
-
-/**
- * A unit vector pointing along the positive Z-axis.
- * @type {!o3djs.math.Vector3}
- */
-o3djs.manipulators.Z_AXIS = [0, 0, 1];
-
-/**
- * Returns the closest point on this line to the given ray, which is
- * specified by start and end points. If the ray is parallel to the
- * line, returns null.
- * @private
- * @param {!o3djs.math.Vector3} startPoint Start point of ray.
- * @param {!o3djs.math.Vector3} endPoint End point of ray.
- * @return {o3djs.math.Vector3} The closest point on the line to the
- * ray, or null if the ray is parallel to the line.
- */
-o3djs.manipulators.Line_.prototype.closestPointToRay = function(startPoint,
- endPoint) {
- // Consider a two-sided line and a one-sided ray, both in in 3D
- // space, and assume they are not parallel. Their parametric
- // formulation is:
- //
- // p1 = point + t * dir
- // p2 = raystart + u * raydir
- //
- // Here t and u are scalar parameter values, and the other values
- // are three-dimensional vectors. p1 and p2 are arbitrary points on
- // the line and ray, respectively.
- //
- // At the points cp1 and cp2 on these two lines where the line and
- // the ray are closest together, the line segment between cp1 and
- // cp2 is perpendicular to both of the lines.
- //
- // We can therefore write the following equations:
- //
- // dot( dir, (cp2 - cp1)) = 0
- // dot(raydir, (cp2 - cp1)) = 0
- //
- // Define t' and u' as the parameter values for cp1 and cp2,
- // respectively. Expanding, these equations become
- //
- // dot( dir, ((raystart + u' * raydir) - (point + t' * dir))) = 0
- // dot(raydir, ((raystart + u' * raydir) - (point + t' * dir))) = 0
- //
- // With some reshuffling, these can be expressed in vector/matrix
- // form:
- //
- // [ dot( dir, raystart) - dot( dir, point) ]
- // [ dot(raydir, raystart) - dot(raydir, point) ] + (continued)
- //
- // [ -dot( dir, dir) dot( dir, raydir) ] [ t' ] [0]
- // [ -dot(raydir, dir) dot(raydir, raydir) ] * [ u' ] = [0]
- //
- // u' is the parameter for the world space ray being cast into the
- // screen. We can deduce whether the starting point of the ray is
- // actually the closest point to the infinite 3D line by whether the
- // value of u' is less than zero.
- var rayDirection = o3djs.math.subVector(endPoint, startPoint);
- var ddrd = o3djs.math.dot(this.direction_, rayDirection);
- var A = o3djs.math.makeMatrix2(-o3djs.math.lengthSquared(this.direction_),
- ddrd,
- ddrd,
- -o3djs.math.lengthSquared(rayDirection));
- var det = o3djs.math.det2(A);
- if (Math.abs(det) < o3djs.manipulators.EPSILON) {
- return null;
- }
- var Ainv = o3djs.math.inverse2(A);
- var b = [o3djs.math.dot(this.point_, this.direction_) -
- o3djs.math.dot(startPoint, this.direction_),
- o3djs.math.dot(startPoint, rayDirection) -
- o3djs.math.dot(this.point_, rayDirection)];
- var x = o3djs.math.mulMatrixVector(Ainv, b);
- if (x[1] < 0) {
- // Means that start point is closest point to this line
- return startPoint;
- } else {
- return o3djs.math.addVector(this.point_,
- o3djs.math.mulScalarVector(
- x[0],
- this.direction_));
- }
-};
-
-/**
- * Performs internal recalculations when the parameters of the line change.
- * @private
- */
-o3djs.manipulators.Line_.prototype.recalc_ = function() {
- var denom = o3djs.math.lengthSquared(this.direction_);
- if (denom == 0.0) {
- throw 'Line_.recalc_: ERROR: direction was the zero vector (not allowed)';
- }
-
- /**
- * Helper (internal cache) for computing projections along the line.
- * @private
- * @type {!o3djs.math.Vector3}
- */
- this.alongVec_ =
- o3djs.math.subVector(this.point_,
- o3djs.math.mulScalarVector(
- o3djs.math.dot(this.point_,
- this.direction_),
- this.direction_));
-};
-
-/**
- * The default color for manipulators (used when not highlighted).
- * In [r, g, b, a] format.
- * @type {!o3djs.math.Vector4}
- */
-o3djs.manipulators.DEFAULT_COLOR = [0.8, 0.8, 0.8, 1.0];
-
-/**
- * The color used for manipulators when they are highlighted.
- * In [r, g, b, a] format.
- * @type {!o3djs.math.Vector4}
- */
-o3djs.manipulators.HIGHLIGHTED_COLOR = [0.9, 0.9, 0.0, 1.0];
-
-/**
- * Creates a new Plane object.
- * @constructor
- * @private
- * @param {!o3djs.math.Vector3} opt_normal The normal of the
- * plane. Does not need to be unit length, but must not be the zero
- * vector. Defaults to [0, 1, 0] if not specified.
- * @param {!o3djs.math.Vector3} opt_point A point through which the
- * plane passes. Defaults to [0, 0, 0] if not specified.
- */
-o3djs.manipulators.Plane_ = function(opt_normal,
- opt_point) {
- /**
- * A point through which the plane passes.
- * @private
- * @type {!o3djs.math.Vector3}
- */
- this.point_ = o3djs.math.copyVector(opt_point || [0, 0, 0]);
- this.setNormal(opt_normal || [0, 1, 0]);
-};
-
-/**
- * Sets the normal of this plane.
- * @private
- * @param {!o3djs.math.Vector3} normal The new normal of the
- * plane. Does not need to be unit length, but must not be the zero
- * vector.
- */
-o3djs.manipulators.Plane_.prototype.setNormal = function(normal) {
- // Make sure the normal isn't zero.
- var denom = o3djs.math.lengthSquared(normal);
- if (denom == 0.0) {
- throw 'Plane_.setNormal: ERROR: normal was the zero vector (not allowed)';
- }
-
- /**
- * The normal to the plane. Normalized, cannot be zero.
- * @private
- * @type {!o3djs.math.Vector3}
- */
- this.normal_ = o3djs.math.normalize(normal); // Makes copy.
- this.recalc_();
-};
-
-/**
- * Gets the normal of this plane, as a unit vector.
- * @private
- * @return {!o3djs.math.Vector3} The (normalized) normal of the plane.
- */
-o3djs.manipulators.Plane_.prototype.getNormal = function() {
- return this.normal_;
-};
-
-/**
- * Sets one point through which this plane passes.
- * @private
- * @param {!o3djs.math.Vector3} point A point through which the plane passes.
- */
-o3djs.manipulators.Plane_.prototype.setPoint = function(point) {
- this.point_ = o3djs.math.copyVector(point);
- this.recalc_();
-};
-
-/**
- * Gets one point through which this plane passes.
- * @private
- * @return {!o3djs.math.Vector3} A point which through the plane passes.
- */
-o3djs.manipulators.Plane_.prototype.getPoint = function() {
- return this.point_;
-};
-
-/**
- * Projects a point onto the plane.
- * @private
- * @param {!o3djs.math.Vector3} point Point to be projected.
- * @return {!o3djs.math.Vector3} Point on the plane closest to the
- * passed point.
- */
-o3djs.manipulators.Plane_.prototype.projectPoint = function(point) {
- var distFromPlane =
- o3djs.math.dot(this.normal_, point) - this.normalDotPoint_;
- return o3djs.math.subVector(point,
- o3djs.math.mulScalarVector(distFromPlane,
- this.normal_));
-};
-
-/**
- * Intersects a ray with the plane. Returns the point of intersection.
- * This is a two-sided ray cast. If the ray is parallel to the plane,
- * returns null.
- * @private
- * @param {!o3djs.math.Vector3} rayStart Start point of ray.
- * @param {!o3djs.math.Vector3} rayDirection Direction vector of ray.
- * Does not need to be normalized, but must not be the zero vector.
- * @return {o3djs.math.Vector3} The point of intersection of the ray
- * with the plane, or null if the ray is parallel to the plane.
- */
-o3djs.manipulators.Plane_.prototype.intersectRay = function(rayStart,
- rayDirection) {
- var distFromPlane =
- this.normalDotPoint_ - o3djs.math.dot(this.normal_, rayStart);
- var denom = o3djs.math.dot(this.normal_, rayDirection);
- if (denom == 0) {
- return null;
- }
- var t = distFromPlane / denom;
- return o3djs.math.addVector(rayStart,
- o3djs.math.mulScalarVector(t, rayDirection));
-};
-
-/**
- * Performs internal recalculations when the parameters of the plane change.
- * @private
- */
-o3djs.manipulators.Plane_.prototype.recalc_ = function() {
- /**
- * Helper (internal cache) for computing projections into the plane.
- * The dot product between normal_ and point_.
- * @private
- * @type {!number}
- */
- this.normalDotPoint_ = o3djs.math.dot(this.normal_, this.point_);
-};
-
-/**
- * Constructs a new manipulator manager. Do not call this directly;
- * use o3djs.manipulators.createManager instead.
- * @constructor
- * @param {!o3d.Pack} pack Pack in which manipulators' geometry and
- * materials will be created.
- * @param {!o3d.Transform} parentTransform The parent transform under
- * which the manipulators' geometry should be parented.
- * @param {!o3d.RenderNode} parentRenderNode The parent render node
- * under which the manipulators' draw elements should be placed.
- * @param {number} renderNodePriority The priority that the
- * manipulators' geometry should use for rendering.
- * @param {!o3d.DrawContext} drawContext The DrawContext to use for the
- * manipulators.
- */
-o3djs.manipulators.Manager = function(pack,
- parentTransform,
- parentRenderNode,
- renderNodePriority,
- drawContext) {
- /**
- * Pack in which manipulators' geometry and materials are created.
- * @type {!o3d.Pack}
- */
- this.pack = pack;
- /**
- * The ViewInfo used to render the manipulators.
- * @type {!o3djs.rendergraph.ViewInfo}
- */
- this.viewInfo = o3djs.rendergraph.createView(
- pack,
- parentTransform,
- parentRenderNode,
- undefined, // clearColor
- renderNodePriority, // priority
- undefined, // viewport
- undefined, // performanceDrawList
- undefined, // zOrderedDrawList
- drawContext);
-
- // Turn off clearing the color for the manipulators.
- this.viewInfo.clearBuffer.active = false;
-
- // Set the ZComparisonFunction to the opposite of normal so we only
- // draw when we should be obscured for the obscured DrawList.
- var state = this.viewInfo.zOrderedState;
- state.getStateParam('ZComparisonFunction').value =
- o3djs.base.o3d.State.CMP_GREATER;
- // Disable depth writing, otherwise the second pass will have a
- // screwed up depth buffer, and will draw when it shouldn't.
- state.getStateParam('ZWriteEnable').value = false;
-
- // Swap the priorities of the DrawPasses so they get drawn in the
- // opposite order
- var temp = this.viewInfo.performanceDrawPassInfo.root.priority;
- this.viewInfo.performanceDrawPassInfo.root.priority =
- this.viewInfo.zOrderedDrawPassInfo.root.priority
- this.viewInfo.zOrderedDrawPassInfo.root.priority = temp;
-
- // The following two DrawLists are used to render manipulators. We give each
- // manipulator 2 DrawElements so they get drawn twice. Once they are
- // drawn with the reverse of the normal zBuffer test so that only the parts
- // of the manipulator that would be obscured by zbuffering are drawn. Then we
- // draw them again with normal zBuffering test so that the parts that are not
- // obscured get drawn as normal. This allows the obscured parts
- // of the manipulators to be rendered with a different material.
-
- // POTENTIAL PROBLEM: Since we reverse the depth comparison function (and
- // disable depth writing) for the obscured rendering pass, those objects will
- // not have their proper faces showing. So they will look wrong unless we use
- // a constant shader. One possible solution would be to set the stencil
- // buffer to indicate obscured/unobscured, so that we are free to use the
- // depth buffer normally.
-
- /**
- * The DrawList we use to render manipulators that are unobscured by the main
- * scene.
- * @private
- * @type {!o3d.DrawList}
- */
- this.unobscuredDrawList_ = this.viewInfo.performanceDrawList;
-
- /**
- * The DrawList we use to render manipulators that are obscured by the main
- * scene.
- * @private
- * @type {!o3d.DrawList}
- */
- this.obscuredDrawList_ = this.viewInfo.zOrderedDrawList;
-
- /**
- * The parent transform under which the manipulators' geometry
- * shall be parented.
- * @type {!o3d.Transform}
- */
- this.parentTransform = parentTransform;
-
- /**
- * A map from the manip's parent Transform clientId to the manip.
- * @type {!Array.<!o3djs.manipulators.Manip>}
- */
- this.manipsByClientId = [];
-
- /**
- * A PickManager to manage picking for the manipulators.
- * @type {!o3djs.picking.PickManager}
- */
- this.pickManager = o3djs.picking.createPickManager(this.parentTransform);
-
- /**
- * The currently-highlighted manipulator.
- * @type {o3djs.manipulators.Manip}
- */
- this.highlightedManip = null;
-
- /**
- * The manipulator currently being dragged.
- * @private
- * @type {o3djs.manipulators.Manip}
- */
- this.draggedManip_ = null;
-};
-
-/**
- * Gets the constant-color material used for the parts of manipulators that are
- * in front of other objects in the scene.
- * @return {!o3d.Material} A material.
- */
-o3djs.manipulators.Manager.prototype.getUnobscuredConstantMaterial = function() {
- if (!this.unobscuredConstantMaterial_) {
- this.unobscuredConstantMaterial_ =
- o3djs.manipulators.createConstantMaterial(
- this.pack, this.unobscuredDrawList_, [1, 1, 1, 0.8]);
- }
- return this.unobscuredConstantMaterial_;
-};
-
-/**
- * Gets the constant-color material used for the parts of manipulators that are
- * behind other objects in the scene.
- * @return {!o3d.Material} A material.
- */
-o3djs.manipulators.Manager.prototype.getObscuredConstantMaterial = function() {
- if (!this.obscuredConstantMaterial_) {
- this.obscuredConstantMaterial_ =
- o3djs.manipulators.createConstantMaterial(
- this.pack, this.obscuredDrawList_, [1, 1, 1, 0.3]);
- }
- return this.obscuredConstantMaterial_;
-};
-
-/**
- * Gets the material used for the parts of line ring manipulators that are
- * in front of other objects in the scene.
- * @return {!o3d.Material} A material.
- */
-o3djs.manipulators.Manager.prototype.getUnobscuredLineRingMaterial =
- function() {
- if (!this.unobscuredLineRingMaterial_) {
- this.unobscuredLineRingMaterial_ =
- o3djs.manipulators.createLineRingMaterial(
- this.pack, this.unobscuredDrawList_,
- [1, 1, 1, 1], [1, 1, 1, 0.6], false);
- }
- return this.unobscuredLineRingMaterial_;
-};
-
-/**
- * Gets the material used for the parts of line ring manipulators that are
- * behind other objects in the scene.
- * @return {!o3d.Material} A material.
- */
-o3djs.manipulators.Manager.prototype.getObscuredLineRingMaterial = function() {
- if (!this.obscuredLineRingMaterial_) {
- this.obscuredLineRingMaterial_ = o3djs.manipulators.createLineRingMaterial(
- this.pack, this.obscuredDrawList_,
- [1, 1, 1, 0.5], [1, 1, 1, 0.3], true);
- }
- return this.obscuredLineRingMaterial_;
-};
-
-/**
- * Creates a new Translate1 manipulator. A Translate1 moves along the
- * X axis in its local coordinate system.
- * @return {!o3djs.manipulators.Translate1} A new Translate1 manipulator.
- */
-o3djs.manipulators.Manager.prototype.createTranslate1 = function() {
- var manip = new o3djs.manipulators.Translate1(this);
- this.add_(manip);
- return manip;
-};
-
-/**
- * Creates a new Translate2 manipulator. A Translate2 moves around the
- * XY plane in its local coordinate system.
- * @return {!o3djs.manipulators.Translate2} A new Translate2 manipulator.
- */
-o3djs.manipulators.Manager.prototype.createTranslate2 = function() {
- var manip = new o3djs.manipulators.Translate2(this);
- this.add_(manip);
- return manip;
-};
-
-/**
- * Creates a new Rotate1 manipulator. A Rotate1 rotates about the
- * X axis in its local coordinate system.
- * @return {!o3djs.manipulators.Rotate1} A new Rotate1 manipulator.
- */
-o3djs.manipulators.Manager.prototype.createRotate1 = function() {
- var manip = new o3djs.manipulators.Rotate1(this);
- this.add_(manip);
- return manip;
-};
-
-/**
- * Adds a manipulator to this manager's set.
- * @private
- * @param {!o3djs.manipulators.Manip} manip The manipulator to add.
- */
-o3djs.manipulators.Manager.prototype.add_ = function(manip) {
- // Generate draw elements for the manipulator's transform
- manip.getTransform().createDrawElements(this.pack, null);
- // Add the manipulator into our managed list
- this.manipsByClientId[manip.getTransform().clientId] = manip;
-};
-
-/**
- * Event handler for multiple kinds of mouse events.
- * @private
- * @param {number} x The x coordinate of the mouse event.
- * @param {number} y The y coordinate of the mouse event.
- * @param {!o3djs.math.Matrix4} view The current view matrix.
- * @param {!o3djs.math.Matrix4} projection The current projection matrix.
- * @param {number} width The width of the viewport.
- * @param {number} height The height of the viewport.
- * @param {!function(!o3djs.manipulators.Manager,
- * o3djs.picking.PickInfo, o3djs.manipulators.Manip): void} func
- * Callback function. Always receives the manager as argument; if
- * a manipulator was picked, receives non-null PickInfo and Manip
- * arguments, otherwise receives null for both of these arguments.
- */
-o3djs.manipulators.Manager.prototype.handleMouse_ = function(x,
- y,
- view,
- projection,
- width,
- height,
- func) {
- this.pickManager.update();
-
- // Create the world ray
- var worldRay =
- o3djs.picking.clientPositionToWorldRayEx(x, y,
- view, projection,
- width, height);
-
- // Pick against all of the manipulators' geometry
- var pickResult = this.pickManager.pick(worldRay);
- if (pickResult != null) {
- // Find which manipulator we picked.
- // NOTE this assumes some things about the transform graph
- // structure of the manipulators.
- // We may need to index by the parent-parent transform instead, since the
- // shape could be attached to the manip's invisibleTransform_, which is a
- // child of the localTransform_.
- var manip =
- this.manipsByClientId[pickResult.shapeInfo.parent.transform.clientId] ||
- this.manipsByClientId[
- pickResult.shapeInfo.parent.parent.transform.clientId];
- func(this, pickResult, manip);
- } else {
- func(this, null, null);
- }
-};
-
-/**
- * Callback handling the mouse-down event on a manipulator.
- * @private
- * @param {!o3djs.manipulators.Manager} manager The manipulator
- * manager owning the given manipulator.
- * @param {o3djs.picking.PickInfo} pickResult The picking information
- * associated with the mouse-down event.
- * @param {o3djs.manipulators.Manip} manip The manipulator to be
- * selected.
- */
-o3djs.manipulators.mouseDownCallback_ = function(manager,
- pickResult,
- manip) {
- if (manip != null) {
- manager.draggedManip_ = manip;
- manip.makeActive(pickResult);
- }
-};
-
-/**
- * Callback handling the mouse-over event on a manipulator.
- * @private
- * @param {!o3djs.manipulators.Manager} manager The manipulator
- * manager owning the given manipulator.
- * @param {o3djs.picking.PickInfo} pickResult The picking information
- * associated with the mouse-over event.
- * @param {o3djs.manipulators.Manip} manip The manipulator to be
- * highlighted.
- */
-o3djs.manipulators.hoverCallback_ = function(manager,
- pickResult,
- manip) {
- if (manager.highlightedManip != null &&
- manager.highlightedManip != manip) {
- // Un-highlight the previously highlighted manipulator
- manager.highlightedManip.clearHighlight();
- manager.highlightedManip = null;
- }
-
- if (manip != null) {
- manip.highlight(pickResult);
- manager.highlightedManip = manip;
- }
-};
-
-/**
- * Method which should be called by end user code upon receiving a
- * mouse-down event.
- * @param {number} x The x coordinate of the mouse event.
- * @param {number} y The y coordinate of the mouse event.
- * @param {!o3djs.math.Matrix4} view The current view matrix.
- * @param {!o3djs.math.Matrix4} projection The current projection matrix.
- * @param {number} width The width of the viewport.
- * @param {number} height The height of the viewport.
- */
-o3djs.manipulators.Manager.prototype.mousedown = function(x,
- y,
- view,
- projection,
- width,
- height) {
- this.handleMouse_(x, y, view, projection, width, height,
- o3djs.manipulators.mouseDownCallback_);
-};
-
-/**
- * Method which should be called by end user code upon receiving a
- * mouse motion event.
- * @param {number} x The x coordinate of the mouse event.
- * @param {number} y The y coordinate of the mouse event.
- * @param {!o3djs.math.Matrix4} view The current view matrix.
- * @param {!o3djs.math.Matrix4} projection The current projection matrix.
- * @param {number} width The width of the viewport.
- * @param {number} height The height of the viewport.
- */
-o3djs.manipulators.Manager.prototype.mousemove = function(x,
- y,
- view,
- projection,
- width,
- height) {
- if (this.draggedManip_ != null) {
- var worldRay =
- o3djs.picking.clientPositionToWorldRayEx(x, y,
- view, projection,
- width, height);
- this.draggedManip_.drag(worldRay.near, worldRay.far,
- x, y, view, projection, width, height);
- } else {
- this.handleMouse_(x, y, view, projection, width, height,
- o3djs.manipulators.hoverCallback_);
- }
-};
-
-/**
- * Method which should be called by end user code upon receiving a
- * mouse-up event.
- */
-o3djs.manipulators.Manager.prototype.mouseup = function() {
- if (this.draggedManip_ != null) {
- this.draggedManip_.makeInactive();
- this.draggedManip_ = null;
- }
-};
-
-/**
- * Method which should be called by end user code, typically in
- * response to mouse move events, to update the transforms of
- * manipulators which might have been moved either because of
- * manipulators further up the hierarchy, or programmatic changes to
- * transforms.
- */
-o3djs.manipulators.Manager.prototype.updateInactiveManipulators = function() {
- for (var ii in this.manipsByClientId) {
- var manip = this.manipsByClientId[ii];
- if (!manip.isActive()) {
- manip.updateBaseTransformFromAttachedTransform_();
- }
- }
-};
-
-/**
- * Base class for all manipulators.
- * @constructor
- * @param {!o3djs.manipulators.Manager} manager The manager of this
- * manipulator.
- */
-o3djs.manipulators.Manip = function(manager) {
- /**
- * The manager of this manipulator.
- * @private
- * @type {!o3djs.manipulators.Manager}
- */
- this.manager_ = manager;
- var pack = manager.pack;
-
- /**
- * This transform holds the local transformation of the manipulator,
- * which is either applied to the transform to which it is attached,
- * or (see below) consumed by the user in the manipulator's
- * callbacks. After each interaction, if there is an attached
- * transform, this local transform is added in to it and reset to
- * the identity.
- * TODO(kbr): add support for user callbacks on manipulators.
- * @private
- * @type {!o3d.Transform}
- */
- this.localTransform_ = pack.createObject('Transform');
-
- /**
- * This transform provides an offset, if desired, between the
- * manipulator's geometry and the transform (and, implicitly, the
- * shape) to which it is attached. This allows the manipulator to be
- * easily placed below an object, for example.
- * @private
- * @type {!o3d.Transform}
- */
- this.offsetTransform_ = pack.createObject('Transform');
-
- /**
- * This transform is the one which is actually parented to the
- * manager's parentTransform. It is used to place the manipulator in
- * world space, regardless of the world space location of the
- * parentTransform supplied to the manager. If this manipulator is
- * attached to a given transform, then upon completion of a
- * particular drag interaction, this transform is adjusted to take
- * into account the attached transform's new value.
- * @private
- * @type {!o3d.Transform}
- */
- this.baseTransform_ = pack.createObject('Transform');
-
- /**
- * This child transform is used only to hold any invisible shapes
- * we may want. Invisible shapes can be useful for picking. Visibility is
- * controlled by the transform, which is why we need this transform.
- * The local matrix of this transform should only be the identity matrix.
- * @private
- * @type {!o3d.Transform}
- */
- this.invisibleTransform_ = pack.createObject('Transform');
- this.invisibleTransform_.visible = false;
-
- // Hook up these transforms
- this.invisibleTransform_.parent = this.localTransform_;
- this.localTransform_.parent = this.offsetTransform_;
- this.offsetTransform_.parent = this.baseTransform_;
- this.baseTransform_.parent = manager.parentTransform;
-
- // Make the invisible transform pickable even though it's invisible
- manager.pickManager.update();
- var invisibleTransformInfo = manager.pickManager.getTransformInfo(
- this.invisibleTransform_);
- invisibleTransformInfo.pickableEvenIfInvisible = true;
-
- /**
- * This is the transform in the scene graph to which this
- * manipulator is conceptually "attached", and whose local transform
- * we are modifying.
- * @private
- * @type {o3d.Transform}
- */
- this.attachedTransform_ = null;
-
- /**
- * Whether this manipulator is active (ie being dragged).
- * @private
- * @type {boolean}
- */
- this.active_ = false;
-};
-
-/**
- * Adds shapes to the internal transform of this manipulator.
- * @private
- * @param {!Array.<!o3d.Shape>} shapes Array of shapes to add.
- * @param {boolean} opt_visible Whether the added shapes should be visible.
- * Default = true. Invisible geometry can be useful for picking.
- */
-o3djs.manipulators.Manip.prototype.addShapes_ = function(shapes, opt_visible) {
- if (opt_visible == undefined) {
- opt_visible = true;
- }
- for (var ii = 0; ii < shapes.length; ii++) {
- if(opt_visible) {
- this.localTransform_.addShape(shapes[ii]);
- } else {
- this.invisibleTransform_.addShape(shapes[ii]);
- }
- }
-};
-
-/**
- * Returns the "base" transform of this manipulator, which places the
- * origin of the manipulator at the local origin of the attached
- * transform.
- * @private
- * @return {!o3d.Transform} The base transform of this manipulator.
- */
-o3djs.manipulators.Manip.prototype.getBaseTransform_ = function() {
- return this.baseTransform_;
-};
-
-/**
- * Returns the "offset" transform of this manipulator, which allows
- * the manipulator's geometry to be moved or rotated with respect to
- * the local origin of the attached transform.
- * @return {!o3d.Transform} The offset transform of this manipulator.
- */
-o3djs.manipulators.Manip.prototype.getOffsetTransform = function() {
- return this.offsetTransform_;
-};
-
-/**
- * Returns the local transform of this manipulator, which contains the
- * changes that have been made in response to the current drag
- * operation. Upon completion of the drag, this transform's effects
- * are composed in to the attached transform, and this transform is
- * reset to the identity.
- * @return {!o3d.Transform} The local transform of this manipulator.
- */
-o3djs.manipulators.Manip.prototype.getTransform = function() {
- return this.localTransform_;
-};
-
-/**
- * Sets the translation component of the offset transform. This is
- * useful for moving the manipulator's geometry with respect to the
- * local origin of the attached transform.
- * @param {!o3djs.math.Vector3} translation The offset translation for
- * this manipulator.
- */
-o3djs.manipulators.Manip.prototype.setOffsetTranslation =
- function(translation) {
- this.getOffsetTransform().localMatrix =
- o3djs.math.matrix4.setTranslation(this.getOffsetTransform().localMatrix,
- translation);
-};
-
-/**
- * Sets the rotation component of the offset transform. This is useful
- * for orienting the manipulator's geometry with respect to the local
- * origin of the attached transform.
- * @param {!o3djs.quaternions.Quaternion} quaternion The offset
- * rotation for this manipulator.
- */
-o3djs.manipulators.Manip.prototype.setOffsetRotation = function(quaternion) {
- var rot = o3djs.quaternions.quaternionToRotation(quaternion);
- this.getOffsetTransform().localMatrix =
- o3djs.math.matrix4.setUpper3x3(this.getOffsetTransform().localMatrix,
- rot);
-};
-
-/**
- * Explicitly sets the local translation of this manipulator.
- * (TODO(kbr): it is not clear that this capability should be in the
- * API.)
- * @param {!o3djs.math.Vector3} translation The local translation for
- * this manipulator.
- */
-o3djs.manipulators.Manip.prototype.setTranslation = function(translation) {
- this.getTransform().localMatrix =
- o3djs.math.matrix4.setTranslation(this.getTransform().localMatrix,
- translation);
-};
-
-/**
- * Explicitly sets the local rotation of this manipulator. (TODO(kbr):
- * it is not clear that this capability should be in the API.)
- * @param {!o3djs.quaternions.Quaternion} quaternion The local
- * rotation for this manipulator.
- */
-o3djs.manipulators.Manip.prototype.setRotation = function(quaternion) {
- var rot = o3djs.quaternions.quaternionToRotation(quaternion);
- this.getTransform().localMatrix =
- o3djs.math.matrix4.setUpper3x3(this.getTransform().localMatrix,
- rot);
-};
-
-/**
- * Attaches this manipulator to the given transform. Interactions with
- * the manipulator will cause this transform's local matrix to be
- * modified appropriately.
- * @param {!o3d.Transform} transform The transform to which this
- * manipulator should be attached.
- */
-o3djs.manipulators.Manip.prototype.attachTo = function(transform) {
- this.attachedTransform_ = transform;
- // Update our base transform to place the manipulator at exactly the
- // location of the attached transform.
- this.updateBaseTransformFromAttachedTransform_();
-};
-
-/**
- * Highlights this manipulator according to the given pick result.
- * @param {o3djs.picking.PickInfo} pickResult The pick result which
- * caused this manipulator to become highlighted.
- */
-o3djs.manipulators.Manip.prototype.highlight = function(pickResult) {
-};
-
-/**
- * Clears any highlight for this manipulator.
- */
-o3djs.manipulators.Manip.prototype.clearHighlight = function() {
-};
-
-/**
- * Activates this manipulator according to the given pick result. In
- * complex manipulators, picking different portions of the manipulator
- * may result in different forms of interaction.
- * @param {o3djs.picking.PickInfo} pickResult The pick result which
- * caused this manipulator to become active.
- */
-o3djs.manipulators.Manip.prototype.makeActive = function(pickResult) {
- this.active_ = true;
-};
-
-/**
- * Deactivates this manipulator.
- */
-o3djs.manipulators.Manip.prototype.makeInactive = function() {
- this.active_ = false;
-};
-
-/**
- * Drags this manipulator according to the world-space ray specified
- * by startPoint and endPoint, or alternatively the screen space mouse
- * coordinate specified by x and y. makeActive must already have been
- * called with the initial pick result causing this manipulator to
- * become active.
- * @param {!o3djs.math.Vector3} startPoint Start point of the
- * world-space ray through the current mouse position.
- * @param {!o3djs.math.Vector3} endPoint End point of the world-space
- * ray through the current mouse position.
- * @param {number} x The x coordinate of the current mouse position.
- * @param {number} y The y coordinate of the current mouse position.
- * @param {!o3djs.math.Matrix4} view The current view matrix.
- * @param {!o3djs.math.Matrix4} projection The current projection matrix.
- * @param {number} width The width of the viewport.
- * @param {number} height The height of the viewport.
- */
-o3djs.manipulators.Manip.prototype.drag = function(startPoint,
- endPoint,
- x,
- y,
- view,
- projection,
- width,
- height) {
-};
-
-/**
- * Indicates whether this manipulator is active.
- * @return {boolean} Whether this manipulator is active.
- */
-o3djs.manipulators.Manip.prototype.isActive = function() {
- return this.active_;
-};
-
-/**
- * Updates the base transform of this manipulator from the state of
- * its attached transform, resetting the local transform of this
- * manipulator to the identity.
- * @private
- */
-o3djs.manipulators.Manip.prototype.updateBaseTransformFromAttachedTransform_ =
- function() {
- if (this.attachedTransform_ != null) {
- var attWorld = this.attachedTransform_.worldMatrix;
- var parWorld = this.manager_.parentTransform.worldMatrix;
- var parWorldInv = o3djs.math.matrix4.inverse(parWorld);
- this.baseTransform_.localMatrix =
- o3djs.math.matrix4.mul(attWorld, parWorldInv);
- // Reset the manipulator's local matrix to the identity.
- this.localTransform_.localMatrix = o3djs.math.matrix4.identity();
- }
-};
-
-/**
- * Updates this manipulator's attached transform based on the values
- * in the local transform.
- * @private
- */
-o3djs.manipulators.Manip.prototype.updateAttachedTransformFromLocalTransform_ =
- function() {
- if (this.attachedTransform_ != null) {
- // Compute the composition of the base and local transforms.
- // The offset transform is skipped except for transforming the
- // effect of the local matrix through the offset transform.
- var base = this.baseTransform_.worldMatrix;
- var offset = this.offsetTransform_.localMatrix;
- var local = this.localTransform_.localMatrix;
- var offsetInv = o3djs.math.matrix4.inverse(offset);
- // We want totalMat = offsetInv * local * offset * base.
- var totalMat = o3djs.math.matrix4.mul(offsetInv, local);
- totalMat = o3djs.math.matrix4.mul(totalMat, offset);
- totalMat = o3djs.math.matrix4.mul(totalMat, base);
-
- // Set this into the attached transform, taking into account its
- // parent's transform, if any.
- // Note that we can not query the parent's transform directly, so
- // we compute it using a little trick.
- var attWorld = this.attachedTransform_.worldMatrix;
- var attLocal = this.attachedTransform_.localMatrix;
- var attParentMat =
- o3djs.math.matrix4.mul(o3djs.math.matrix4.inverse(attLocal),
- attWorld);
- // Now we can take the inverse of this matrix
- var attParentMatInv = o3djs.math.matrix4.inverse(attParentMat);
- totalMat = o3djs.math.matrix4.mul(totalMat, attParentMatInv);
- this.attachedTransform_.localMatrix = totalMat;
- }
-};
-
-/**
- * Sets the material of the given shape's draw elements.
- * TODO(simonrad): This function is not used, remove it?
- * @private
- * @param {!o3d.Shape} shape Shape to modify the material of.
- * @param {!o3d.Material} material Material to set.
- */
-o3djs.manipulators.Manip.prototype.setMaterial_ = function(shape, material) {
- var elements = shape.elements;
- for (var ii = 0; ii < elements.length; ii++) {
- var drawElements = elements[ii].drawElements;
- for (var jj = 0; jj < drawElements.length; jj++) {
- drawElements[jj].material = material;
- }
- }
-};
-
-/**
- * Sets the materials of the given shapes' draw elements.
- * TODO(simonrad): This function is not used, remove it?
- * @private
- * @param {!Array.<!o3d.Shape>} shapes Array of shapes to modify the materials of.
- * @param {!o3d.Material} material Material to set.
- */
-o3djs.manipulators.Manip.prototype.setMaterials_ = function(shapes, material) {
- for (var ii = 0; ii < shapes.length; ii++) {
- this.setMaterial_(shapes[ii], material);
- }
-};
-
-/**
- * Create the geometry for a double-ended arrow going from
- * (0, -1, 0) to (0, 1, 0), transformed by the given matrix.
- * @private
- * @param {!o3djs.math.Matrix4} matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3djs.primitives.VertexInfo} The created vertices.
- */
-o3djs.manipulators.createArrowVertices_ = function(matrix) {
- var matrix4 = o3djs.math.matrix4;
-
- var verts = o3djs.primitives.createTruncatedConeVertices(
- 0.15, // Bottom radius.
- 0.0, // Top radius.
- 0.3, // Height.
- 4, // Number of radial subdivisions.
- 1, // Number of vertical subdivisions.
- matrix4.mul(matrix4.translation([0, 0.85, 0]), matrix));
-
- verts.append(o3djs.primitives.createCylinderVertices(
- 0.06, // Radius.
- 1.4, // Height.
- 4, // Number of radial subdivisions.
- 1, // Number of vertical subdivisions.
- matrix));
-
- verts.append(o3djs.primitives.createTruncatedConeVertices(
- 0.0, // Bottom radius.
- 0.15, // Top radius.
- 0.3, // Height.
- 4, // Number of radial subdivisions.
- 1, // Number of vertical subdivisions.
- matrix4.mul(matrix4.translation([0, -0.85, 0]), matrix)));
-
- return verts;
-};
-
-/**
- * A manipulator allowing an object to be dragged along a line.
- * A Translate1 moves along the X axis in its local coordinate system.
- * @constructor
- * @extends {o3djs.manipulators.Manip}
- * @param {!o3djs.manipulators.Manager} manager The manager for the
- * new Translate1 manipulator.
- */
-o3djs.manipulators.Translate1 = function(manager) {
- o3djs.manipulators.Manip.call(this, manager);
-
- var pack = manager.pack;
-
- var shape = manager.translate1Shape_;
- if (!shape) {
- // Create the geometry for the manipulator, which looks like a
- // two-way arrow going from (-1, 0, 0) to (1, 0, 0).
- var verts = o3djs.manipulators.createArrowVertices_(
- o3djs.math.matrix4.rotationZ(Math.PI / 2));
- shape = verts.createShape(pack, manager.getUnobscuredConstantMaterial());
- // Add a second DrawElement to this shape to draw it a second time
- // with a different material when it's obscured.
- shape.createDrawElements(pack, manager.getObscuredConstantMaterial());
- manager.translate1Shape_ = shape;
- }
-
- this.addShapes_([ shape ]);
-
- /**
- * A parameter added to our transform to be able to change the
- * material's color for highlighting.
- * @private
- * @type {!o3d.ParamFloat4}
- */
- this.colorParam_ = this.getTransform().createParam('highlightColor',
- 'ParamFloat4');
- this.clearHighlight();
-
- /**
- * Line along which we are dragging.
- * @private
- * @type {!o3djs.manipulators.Line_}
- */
- this.dragLine_ = new o3djs.manipulators.Line_();
-};
-
-o3djs.base.inherit(o3djs.manipulators.Translate1, o3djs.manipulators.Manip);
-
-o3djs.manipulators.Translate1.prototype.highlight = function(pickResult) {
- // We can use instanced geometry for the entire Translate1 since its
- // entire color changes during highlighting.
- // TODO(kbr): support custom user geometry and associated callbacks.
- this.colorParam_.value = o3djs.manipulators.HIGHLIGHTED_COLOR;
-};
-
-o3djs.manipulators.Translate1.prototype.clearHighlight = function() {
- this.colorParam_.value = o3djs.manipulators.DEFAULT_COLOR;
-};
-
-o3djs.manipulators.Translate1.prototype.makeActive = function(pickResult) {
- o3djs.manipulators.Manip.prototype.makeActive.call(this, pickResult);
- this.highlight(pickResult);
- var localToWorld = this.getTransform().worldMatrix;
- this.dragLine_.setDirection(
- o3djs.math.matrix4.transformDirection(localToWorld,
- o3djs.manipulators.X_AXIS));
- this.dragLine_.setPoint(pickResult.worldIntersectionPosition);
-};
-
-o3djs.manipulators.Translate1.prototype.makeInactive = function() {
- o3djs.manipulators.Manip.prototype.makeInactive.call(this);
- this.clearHighlight();
- this.updateAttachedTransformFromLocalTransform_();
- this.updateBaseTransformFromAttachedTransform_();
-};
-
-o3djs.manipulators.Translate1.prototype.drag = function(startPoint,
- endPoint,
- x,
- y,
- view,
- projection,
- width,
- height) {
- // Algorithm: Find closest point of ray to dragLine_. Subtract this
- // point from the line's point to find difference vector; transform
- // from world to local coordinates to find new local offset of
- // manipulator.
- var closestPoint = this.dragLine_.closestPointToRay(startPoint, endPoint);
- if (closestPoint == null) {
- // Drag axis is parallel to ray. Punt.
- return;
- }
- // Need to do a world-to-local transformation on the difference vector.
- // Note that we also incorporate the translation portion of the matrix.
- var diffVector =
- o3djs.math.subVector(closestPoint, this.dragLine_.getPoint());
- var worldToLocal =
- o3djs.math.matrix4.inverse(this.getTransform().worldMatrix);
- this.getTransform().localMatrix =
- o3djs.math.matrix4.setTranslation(
- this.getTransform().localMatrix,
- o3djs.math.matrix4.transformDirection(worldToLocal,
- diffVector));
- this.updateAttachedTransformFromLocalTransform_();
-};
-
-/**
- * A manipulator allowing an object to be dragged around a plane.
- * A Translate2 moves around the XY plane in its local coordinate system.
- * @constructor
- * @extends {o3djs.manipulators.Manip}
- * @param {!o3djs.manipulators.Manager} manager The manager for the
- * new Translate2 manipulator.
- */
-o3djs.manipulators.Translate2 = function(manager) {
- o3djs.manipulators.Manip.call(this, manager);
-
- var pack = manager.pack;
-
- var shape = manager.Translate2Shape_;
- if (!shape) {
- // Create the geometry for the manipulator, which looks like
- // a two-way arrow going from (-1, 0, 0) to (1, 0, 0),
- // and another one going from (0, -1, 0) to (0, 1, 0).
- var verts = o3djs.manipulators.createArrowVertices_(
- o3djs.math.matrix4.rotationZ(Math.PI / 2));
- verts.append(o3djs.manipulators.createArrowVertices_(
- o3djs.math.matrix4.rotationZ(0)));
- shape = verts.createShape(pack, manager.getUnobscuredConstantMaterial());
- // Add a second DrawElement to this shape to draw it a second time
- // with a different material when it's obscured.
- shape.createDrawElements(pack, manager.getObscuredConstantMaterial());
- manager.Translate2Shape_ = shape;
- }
-
- this.addShapes_([ shape ]);
-
- /**
- * A parameter added to our transform to be able to change the
- * material's color for highlighting.
- * @private
- * @type {!o3d.ParamFloat4}
- */
- this.colorParam_ = this.getTransform().createParam('highlightColor',
- 'ParamFloat4');
- this.clearHighlight();
-
- /**
- * Plane through which we are dragging.
- * @private
- * @type {!o3djs.manipulators.Plane_}
- */
- this.dragPlane_ = new o3djs.manipulators.Plane_();
-};
-
-o3djs.base.inherit(o3djs.manipulators.Translate2, o3djs.manipulators.Manip);
-
-o3djs.manipulators.Translate2.prototype.highlight = function(pickResult) {
- // We can use instanced geometry for the entire Translate2 since its
- // entire color changes during highlighting.
- // TODO(kbr): support custom user geometry and associated callbacks.
- this.colorParam_.value = o3djs.manipulators.HIGHLIGHTED_COLOR;
-};
-
-o3djs.manipulators.Translate2.prototype.clearHighlight = function() {
- this.colorParam_.value = o3djs.manipulators.DEFAULT_COLOR;
-};
-
-o3djs.manipulators.Translate2.prototype.makeActive = function(pickResult) {
- o3djs.manipulators.Manip.prototype.makeActive.call(this, pickResult);
- this.highlight(pickResult);
- var localToWorld = this.getTransform().worldMatrix;
- this.dragPlane_.setNormal(
- o3djs.math.matrix4.transformDirection(localToWorld,
- o3djs.manipulators.Z_AXIS));
- this.dragPlane_.setPoint(pickResult.worldIntersectionPosition);
-};
-
-o3djs.manipulators.Translate2.prototype.makeInactive = function() {
- o3djs.manipulators.Manip.prototype.makeInactive.call(this);
- this.clearHighlight();
- this.updateAttachedTransformFromLocalTransform_();
- this.updateBaseTransformFromAttachedTransform_();
-};
-
-o3djs.manipulators.Translate2.prototype.drag = function(startPoint,
- endPoint,
- x,
- y,
- view,
- projection,
- width,
- height) {
- // Algorithm: Find intersection of ray with dragPlane_. Subtract this
- // point from the plane's point to find difference vector; transform
- // from world to local coordinates to find new local offset of
- // manipulator.
- var intersectPoint = this.dragPlane_.intersectRay(startPoint,
- o3djs.math.subVector(endPoint, startPoint));
- if (intersectPoint == null) {
- // Drag plane is parallel to ray. Punt.
- return;
- }
- // Need to do a world-to-local transformation on the difference vector.
- // Note that we also incorporate the translation portion of the matrix.
- var diffVector =
- o3djs.math.subVector(intersectPoint, this.dragPlane_.getPoint());
- var worldToLocal =
- o3djs.math.matrix4.inverse(this.getTransform().worldMatrix);
- this.getTransform().localMatrix =
- o3djs.math.matrix4.setTranslation(
- this.getTransform().localMatrix,
- o3djs.math.matrix4.transformDirection(worldToLocal,
- diffVector));
- this.updateAttachedTransformFromLocalTransform_();
-};
-
-/**
- * A manipulator allowing an object to be rotated about a single axis.
- * A Rotate1 rotates about the X axis in its local coordinate system.
- * @constructor
- * @extends {o3djs.manipulators.Manip}
- * @param {!o3djs.manipulators.Manager} manager The manager for the
- * new Rotate1 manipulator.
- */
-o3djs.manipulators.Rotate1 = function(manager) {
- o3djs.manipulators.Manip.call(this, manager);
-
- var pack = manager.pack;
-
- var pickShape = manager.Rotate1PickShape_;
- if (!pickShape) {
- // Create the polygon geometry for picking the manipulator, which looks like
- // a torus centered at the origin, with the X axis as its vertical axis.
- var verts = o3djs.primitives.createTorusVertices(
- 1.0,
- 0.1,
- 16,
- 6,
- o3djs.math.matrix4.rotationZ(Math.PI / 2));
- pickShape = verts.createShape(pack, manager.getUnobscuredConstantMaterial());
- manager.Rotate1PickShape_ = pickShape;
- }
-
- var visibleShape = manager.Rotate1VisibleShape_;
- if (!visibleShape) {
- // Create the line geometry for displaying the manipulator, which looks like
- // a ring centered at the origin, with the X axis as its vertical axis.
- var verts = o3djs.lineprimitives.createLineRingVertices(
- 1.0, // radius
- 32, // subdivisions
- 120, // maxTexCoord (this determines the number of stipples)
- o3djs.math.matrix4.rotationZ(Math.PI / 2)); // opt_matrix
- visibleShape = verts.createShape(pack,
- manager.getUnobscuredLineRingMaterial());
- // Add a second DrawElement to this shape to draw it a second time
- // with a different material when it's obscured.
- visibleShape.createDrawElements(
- pack, manager.getObscuredLineRingMaterial());
- manager.Rotate1VisibleShape_ = visibleShape;
- }
-
- this.addShapes_([ pickShape ], false); // Invisible
- this.addShapes_([ visibleShape ]);
-
- /**
- * A parameter added to our transform to be able to change the
- * material's color for highlighting.
- * @private
- * @type {!o3d.ParamFloat4}
- */
- this.colorParam_ = this.getTransform().createParam('highlightColor',
- 'ParamFloat4');
- this.clearHighlight();
-
- /**
- * Line along which we are dragging.
- * We just use this to store the point and direction, not to do any math.
- * @private
- * @type {!o3djs.manipulators.Line_}
- */
- this.dragLine_ = new o3djs.manipulators.Line_();
-};
-
-o3djs.base.inherit(o3djs.manipulators.Rotate1, o3djs.manipulators.Manip);
-
-o3djs.manipulators.Rotate1.prototype.highlight = function(pickResult) {
- // We can use instanced geometry for the entire Rotate1 since its
- // entire color changes during highlighting.
- // TODO(kbr): support custom user geometry and associated callbacks.
- this.colorParam_.value = o3djs.manipulators.HIGHLIGHTED_COLOR;
-};
-
-o3djs.manipulators.Rotate1.prototype.clearHighlight = function() {
- this.colorParam_.value = o3djs.manipulators.DEFAULT_COLOR;
-};
-
-o3djs.manipulators.Rotate1.prototype.makeActive = function(pickResult) {
- o3djs.manipulators.Manip.prototype.makeActive.call(this, pickResult);
- this.highlight(pickResult);
- var localToWorld = this.getTransform().worldMatrix;
- var worldToLocal = o3djs.math.matrix4.inverse(localToWorld);
-
- // Set up the line. The line is tangent to the circle of rotation
- // and passes through the initial pickResult.
- // Do the math in local space.
- // The rotation axis is the X axis, centered at the origin.
- var localIntersectionPosition =
- o3djs.math.matrix4.transformPoint(worldToLocal,
- pickResult.worldIntersectionPosition);
- var localLineDirection = o3djs.math.cross(localIntersectionPosition,
- o3djs.manipulators.X_AXIS);
- this.dragLine_.setDirection(
- o3djs.math.matrix4.transformDirection(localToWorld,
- localLineDirection));
- this.dragLine_.setPoint(pickResult.worldIntersectionPosition);
-
- // TODO(simonrad): It would be nice to draw an arrow on the screen
- // at the click position, indicating the direction of the line.
-};
-
-o3djs.manipulators.Rotate1.prototype.makeInactive = function() {
- o3djs.manipulators.Manip.prototype.makeInactive.call(this);
- this.clearHighlight();
- this.updateAttachedTransformFromLocalTransform_();
- this.updateBaseTransformFromAttachedTransform_();
-};
-
-/**
- * Convert the specified frustum-space position into
- * client coordinates (ie pixels).
- * @private
- * @param {!o3djs.math.Vector3} frustumPoint The point in frustum coordinates
- * to transform.
- * @param {number} width The width of the viewport.
- * @param {number} height The height of the viewport.
- * @return {!o3djs.math.Vector2} The location of frustumPoint on the screen,
- * in client coordinates.
- */
-o3djs.manipulators.frustumPositionToClientPosition_ = function(frustumPoint,
- width,
- height) {
- return [(frustumPoint[0] + 1) * width / 2,
- (-frustumPoint[1] + 1) * height / 2];
-};
-
-o3djs.manipulators.Rotate1.prototype.drag = function(startPoint,
- endPoint,
- x,
- y,
- view,
- projection,
- width,
- height) {
- // Use a simple linear mouse mapping based on distance along the tangent line.
- // Do the dragging in client (screen space) coordinates. This eliminates any
- // degenerate cases involved with a 3D line.
-
- // Compute the position and direction of the line in screen coordinates.
- var viewProjectionMatrix = o3djs.math.matrix4.mul(view, projection);
- var linePoint1 = o3djs.manipulators.frustumPositionToClientPosition_(
- o3djs.math.matrix4.transformPoint(viewProjectionMatrix,
- this.dragLine_.getPoint()),
- width, height);
- var linePoint2 = o3djs.manipulators.frustumPositionToClientPosition_(
- o3djs.math.matrix4.transformPoint(viewProjectionMatrix,
- o3djs.math.addVector(
- this.dragLine_.getPoint(),
- this.dragLine_.getDirection()
- )),
- width, height);
- var lineDirection = o3djs.math.normalize(o3djs.math.subVector(linePoint2,
- linePoint1));
- var mousePoint = [x, y];
-
- // The distance *along the line* that we have dragged, in pixels.
- var dragDistance = o3djs.math.dot(lineDirection, mousePoint) -
- o3djs.math.dot(lineDirection, linePoint1);
-
- // Determine rotation angle based on drag distance relative to
- // the size of the client area.
- var angle = (dragDistance / Math.max(width, height)) * 2 * Math.PI;
- this.getTransform().localMatrix = o3djs.math.matrix4.rotationX(-angle);
- this.updateAttachedTransformFromLocalTransform_();
-};
-
-// The shaders and materials for the manipulators.
-// TODO(simonrad): Find a better place for these?
-
-// The main reason for using custom shader code instead of using standard
-// shaders from the effect library is that we want to do highlighting.
-// We want to supply two color parameters, and have them combined by the shader.
-// One parameter is defined on the material itself, so that we can have
-// different colored materials for obscured vs. unobscured geometry. The other
-// parameter is the highlightColor, which could switch between white and yellow
-// (for example). The highlightColor is usually defined on the transform
-// directly above the manipulator shapes. We want to be able to change the
-// highlightColor for all materials of the manipulator, but still maintain
-// different colors on each individual material.
-// An alternative would be to use standard shaders, and change the colors of
-// each material individually in the highlight() and clearHighlight() methods.
-// If you do this however, you would have to use different materials on each
-// manipulator, so that you can highlight only one.
-// Another alternative would be to do highlighting by swapping materials on
-// the shapes. That is, you would have obscuredHighlightedMaterial and
-// obscuredNonHighlightedMaterial. This might be best.
-
-/**
- * An effect string for the polygon geometry of manipulators.
- * This is the same as the shader returned by buildPhongShaderString(),
- * except that it uses an additional highlightColor uniform parameter
- * to do manipulator highlighting.
- * TODO(simonrad): Make the highlighting easier to see, especially when the
- * shapes are dark and obscured.
- * @private
- * @type {string}
- */
-o3djs.manipulators.phongFXString_ = '' +
- 'uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;\n' +
- 'uniform float3 lightWorldPos;\n' +
- 'uniform float4 lightColor;\n' +
- 'uniform float4x4 world : WORLD;\n' +
- 'uniform float4x4 viewInverse : VIEWINVERSE;\n' +
- 'uniform float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;\n' +
- 'uniform float4 emissive;\n' +
- 'uniform float4 ambient;\n' +
- 'uniform float4 diffuse;\n' +
- 'uniform float4 highlightColor;\n' +
- 'uniform float4 specular;\n' +
- 'uniform float shininess;\n' +
- 'uniform float specularFactor;\n' +
- 'struct InVertex {\n' +
- ' float4 position : POSITION;\n' +
- ' float3 normal : NORMAL;\n' +
- '};\n' +
- 'struct OutVertex {\n' +
- ' float4 position : POSITION;\n' +
- ' float3 normal : TEXCOORD0;\n' +
- ' float3 surfaceToLight: TEXCOORD1;\n' +
- ' float3 surfaceToView : TEXCOORD2;\n' +
- '};\n' +
- 'OutVertex vertexShaderFunction(InVertex input) {\n' +
- ' OutVertex output;\n' +
- ' output.position = mul(input.position, worldViewProjection);\n' +
- ' output.normal = mul(float4(input.normal, 0),\n' +
- ' worldInverseTranspose).xyz;\n' +
- ' output.surfaceToLight = lightWorldPos - \n' +
- ' mul(input.position, world).xyz;\n' +
- ' output.surfaceToView = (viewInverse[3] - mul(input.position,\n' +
- ' world)).xyz;\n' +
- ' return output;\n' +
- '}\n' +
- 'float4 pixelShaderFunction(OutVertex input) : COLOR {\n' +
- ' float4 newDiffuse = diffuse * highlightColor;\n' +
- ' float3 normal = normalize(input.normal);\n' +
- ' float3 surfaceToLight = normalize(input.surfaceToLight);\n' +
- ' float3 surfaceToView = normalize(input.surfaceToView);\n' +
- ' float3 halfVector = normalize(surfaceToLight + surfaceToView);\n' +
- ' float4 litR = lit(dot(normal, surfaceToLight), \n' +
- ' dot(normal, halfVector), shininess);\n' +
- ' return float4((emissive +\n' +
- ' lightColor * (ambient * newDiffuse + newDiffuse * litR.y +\n' +
- ' + specular * litR.z * specularFactor)).rgb, newDiffuse.a);\n' +
- '}\n' +
- '\n' +
- '// #o3d VertexShaderEntryPoint vertexShaderFunction\n' +
- '// #o3d PixelShaderEntryPoint pixelShaderFunction\n' +
- '// #o3d MatrixLoadOrder RowMajor\n';
-
-/**
- * An constant-color effect string.
- * @private
- * @type {string}
- */
-o3djs.manipulators.constantFXString_ = '' +
- 'uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;\n' +
- 'uniform float4 color;\n' +
- 'uniform float4 highlightColor;\n' +
- '\n' +
- 'struct VertexShaderInput {\n' +
- ' float4 position : POSITION;\n' +
- '};\n' +
- '\n' +
- 'struct PixelShaderInput {\n' +
- ' float4 position : POSITION;\n' +
- '};\n' +
- '\n' +
- 'PixelShaderInput vertexShaderFunction(VertexShaderInput input) {\n' +
- ' PixelShaderInput output;\n' +
- '\n' +
- ' output.position = mul(input.position, worldViewProjection);\n' +
- ' return output;\n' +
- '}\n' +
- '\n' +
- 'float4 pixelShaderFunction(PixelShaderInput input): COLOR {\n' +
- ' return color * highlightColor;\n' +
- '}\n' +
- '\n' +
- '// #o3d VertexShaderEntryPoint vertexShaderFunction\n' +
- '// #o3d PixelShaderEntryPoint pixelShaderFunction\n' +
- '// #o3d MatrixLoadOrder RowMajor\n';
-
-
-/**
- * Returns an effect string for the Rotate1 manipulator's line ring.
- * @private
- * @param {boolean} enableStipple Whether line stippling should be enabled
- * in the shader.
- * @return {string} The created shader source / effect string.
- */
-o3djs.manipulators.getLineRingFXString_ = function(enableStipple) {
- var stippleCode = '';
- if (enableStipple) {
- stippleCode = '' +
- ' // Use the texCoord to do stippling.\n' +
- ' if (input.texCoord.x % 2 > 1) return float4(0, 0, 0, 0);\n';
- }
- return '' +
- 'uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;\n' +
- '// NOTE: We transform the normals through the\n' +
- '// worldViewProjectionInverseTranspose instead of the\n' +
- '// worldViewInverseTranspose. The projection matrix warps the\n' +
- '// normals in strange ways. One result of this is that the "front\n' +
- '// face" color of the ring can extend around more than 50% of the\n' +
- '// ring. This may be good or bad. If we dont include the projection\n' +
- '// matrix, we always get a 50% split, but we do not account for\n' +
- '// perspective. An alternative would be to get a little more\n' +
- '// complicated, using the positions of the camera and the center\n' +
- '// of the ring.\n' +
- 'uniform float4x4 worldViewProjectionInverseTranspose :\n' +
- ' WORLDVIEWPROJECTIONINVERSETRANSPOSE;\n' +
- 'uniform float4 color1;\n' +
- 'uniform float4 color2;\n' +
- 'uniform float4 highlightColor;\n' +
- '\n' +
- 'struct VertexShaderInput {\n' +
- ' float4 position : POSITION;\n' +
- ' float4 normal : NORMAL;\n' +
- ' float1 texCoord : TEXCOORD0;\n' +
- '};\n' +
- '\n' +
- 'struct PixelShaderInput {\n' +
- ' float4 position : POSITION;\n' +
- ' float3 normal : TEXCOORD0;\n' +
- ' float1 texCoord : TEXCOORD1;\n' +
- '};\n' +
- '\n' +
- 'PixelShaderInput vertexShaderFunction(VertexShaderInput input) {\n' +
- ' PixelShaderInput output;\n' +
- '\n' +
- ' output.position = mul(input.position, worldViewProjection);\n' +
- ' output.normal = mul(input.normal,\n' +
- ' worldViewProjectionInverseTranspose).xyz;\n' +
- ' output.texCoord = input.texCoord;\n' +
- ' return output;\n' +
- '}\n' +
- '\n' +
- 'float4 pixelShaderFunction(PixelShaderInput input): COLOR {\n' +
- stippleCode +
- ' if (input.normal.z < 0) {\n' +
- ' return color1 * highlightColor; // Front face of the ring.\n' +
- ' } else {\n' +
- ' return color2 * highlightColor; // Back face of the ring.\n' +
- ' }\n' +
- '}\n' +
- '\n' +
- '// #o3d VertexShaderEntryPoint vertexShaderFunction\n' +
- '// #o3d PixelShaderEntryPoint pixelShaderFunction\n' +
- '// #o3d MatrixLoadOrder RowMajor\n';
-};
-
-/**
- * Set up the state of a material to allow alpha blending.
- *
- * @param {!o3d.Pack} pack The pack to create the state object in.
- * @param {!o3d.Material} material The material to modify.
- * @param {boolean} discardZeroAlphaPixels Whether incoming pixels that have
- * zero alpha should be discarded.
- */
-o3djs.manipulators.enableAlphaBlendingOnMaterial =
- function(pack, material, discardZeroAlphaPixels) {
- if (!material.state) {
- material.state = pack.createObject('State');
- }
- var state = material.state;
- state.getStateParam('AlphaBlendEnable').value = true;
- state.getStateParam('SourceBlendFunction').value =
- o3djs.base.o3d.State.BLENDFUNC_SOURCE_ALPHA;
- state.getStateParam('DestinationBlendFunction').value =
- o3djs.base.o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA;
- state.getStateParam('AlphaTestEnable').value = discardZeroAlphaPixels;
- state.getStateParam('AlphaComparisonFunction').value =
- o3djs.base.o3d.State.CMP_GREATER;
- state.getStateParam('AlphaReference').value = 0;
-};
-
-/**
- * Creates the Rotate1 manipulator's line ring material.
- *
- * @param {!o3d.Pack} pack The pack to create the effect and material in.
- * @param {!o3d.DrawList} drawList The draw list against which
- * the material is created.
- * @param {!o3djs.math.Vector4} color1 A color in the format [r, g, b, a].
- * @param {!o3djs.math.Vector4} color2 A color in the format [r, g, b, a].
- * @param {boolean} enableStipple Whether line stippling should be enabled
- * in the shader.
- * @return {!o3d.Material} The created material.
- */
-o3djs.manipulators.createLineRingMaterial = function(pack,
- drawList,
- color1,
- color2,
- enableStipple) {
- var material = pack.createObject('Material');
- material.effect = pack.createObject('Effect');
- material.effect.loadFromFXString(
- o3djs.manipulators.getLineRingFXString_(enableStipple));
- material.drawList = drawList;
- material.createParam('color1', 'ParamFloat4').value = color1;
- material.createParam('color2', 'ParamFloat4').value = color2;
- o3djs.manipulators.enableAlphaBlendingOnMaterial(pack, material, true);
- return material;
-};
-
-/**
- * Creates a constant-shaded material based on the given single color.
- *
- * @param {!o3d.Pack} pack The pack to create the effect and material in.
- * @param {!o3d.DrawList} drawList The draw list against which
- * the material is created.
- * @param {!o3djs.math.Vector4} color A color in the format [r, g, b, a].
- * @return {!o3d.Material} The created material.
- */
-o3djs.manipulators.createConstantMaterial = function(pack,
- drawList,
- color) {
- var material = pack.createObject('Material');
- material.effect = pack.createObject('Effect');
- material.effect.loadFromFXString(o3djs.manipulators.constantFXString_);
- material.drawList = drawList;
- material.createParam('color', 'ParamFloat4').value = color;
- o3djs.manipulators.enableAlphaBlendingOnMaterial(pack, material, false);
- return material;
-};
-
-/**
- * Creates a phong-shaded material based on the given color.
- *
- * @param {!o3d.Pack} pack The pack to create the effect and material in.
- * @param {!o3d.DrawList} drawList The draw list against which
- * the material is created.
- * @param {!o3djs.math.Vector4} color A color in the format [r, g, b, a].
- * @return {!o3d.Material} The created material.
- */
-o3djs.manipulators.createPhongMaterial = function(pack,
- drawList,
- color) {
- var material = pack.createObject('Material');
- material.effect = pack.createObject('Effect');
- material.effect.loadFromFXString(o3djs.manipulators.phongFXString_);
- material.drawList = drawList;
- material.createParam('diffuse', 'ParamFloat4').value = color;
-
- // Create some suitable defaults for the material.
- material.createParam('emissive', 'ParamFloat4').value = [0, 0, 0, 1];
- material.createParam('ambient', 'ParamFloat4').value = [0.5, 0.5, 0.5, 1];
- material.createParam('specular', 'ParamFloat4').value = [1, 1, 1, 1];
- material.createParam('shininess', 'ParamFloat').value = 50;
- material.createParam('specularFactor', 'ParamFloat').value = 1;
- material.createParam('lightColor', 'ParamFloat4').value = [1, 1, 1, 1];
- material.createParam('lightWorldPos', 'ParamFloat3').value =
- [1000, 2000, 3000];
- // TODO(simonrad): Allow modifying the lightPosition, and/or make it fit in
- // with the surrounding world. We could put the lightWorldPos parameter on
- // the transform or somewhere else.
-
- o3djs.manipulators.enableAlphaBlendingOnMaterial(pack, material, false);
- return material;
-}; \ No newline at end of file
diff --git a/o3d/samples/o3djs/material.js b/o3d/samples/o3djs/material.js
deleted file mode 100644
index e0f89e0..0000000
--- a/o3d/samples/o3djs/material.js
+++ /dev/null
@@ -1,593 +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.
- */
-
-
-/**
- * @fileoverview This file contains various functions for helping setup
- * materials for o3d. It puts them in the "material" module on the
- * o3djs object.
- *
- * Note: This library is only a sample. It is not meant to be some official
- * library. It is provided only as example code.
- *
- */
-
-o3djs.provide('o3djs.material');
-
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.effect');
-
-/**
- * A Module for materials.
- * @namespace
- */
-o3djs.material = o3djs.material || {};
-
-/**
- * Checks a material's params by name to see if it possibly has non 1.0 alpha.
- * Given a name, checks for a ParamTexture called 'nameTexture' and if that
- * fails, checks for a ParamFloat4 'name'.
- * @private
- * @param {!o3d.Material} material Materal to check.
- * @param {string} name name of color params to check.
- * @return {{found: boolean, nonOneAlpha: boolean}} found is true if one of
- * the params was found, nonOneAlpha is true if that param had non 1.0
- * alpha.
- */
-o3djs.material.hasNonOneAlpha_ = function(material, name) {
- var found = false;
- var nonOneAlpha = false;
- var texture = null;
- var samplerParam = material.getParam(name + 'Sampler');
- if (samplerParam && samplerParam.isAClassName('o3d.ParamSampler')) {
- found = true;
- var sampler = samplerParam.value;
- if (sampler) {
- texture = sampler.texture;
- }
- } else {
- var textureParam = material.getParam(name + 'Texture');
- if (textureParam && textureParam.isAClassName('o3d.ParamTexture')) {
- found = true;
- texture = textureParam.value;
- }
- }
-
- if (texture && !texture.alphaIsOne) {
- nonOneAlpha = true;
- }
-
- if (!found) {
- var colorParam = material.getParam(name);
- if (colorParam && colorParam.isAClassName('o3d.ParamFloat4')) {
- found = true;
- // TODO: this check does not work. We need to check for the
- // <transparency> and <transparent> elements or something.
- // if (colorParam.value[3] < 1) {
- // nonOneAlpha = true;
- // }
- }
- }
- return {found: found, nonOneAlpha: nonOneAlpha};
-};
-
-/**
- * Prepares a material by setting their drawList and possibly creating
- * an standard effect if one does not already exist.
- *
- * This function is very specific to our sample importer. It expects that if
- * no Effect exists on a material that certain extra Params have been created
- * on the Material to give us instructions on what to Effects to create.
- *
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo as returned from
- * o3djs.rendergraph.createView.
- * @param {!o3d.Material} material to prepare.
- * @param {string} opt_effectType type of effect to create ('phong',
- * 'lambert', 'constant').
- * @param {Object} opt_options Extra options for effect.getStandardShader
- *
- * @see o3djs.material.attachStandardEffect
- */
-o3djs.material.prepareMaterial = function(pack,
- viewInfo,
- material,
- opt_effectType,
- opt_options) {
- // Assume we want the performance list
- var drawList = viewInfo.performanceDrawList;
- // First check if we have a tag telling us that it is or is not
- // transparent
- if (!material.drawList) {
- var param = material.getParam('collada.transparent');
- if (param && param.className == 'o3d.ParamBoolean') {
- material.drawList = param.value ? viewInfo.zOrderedDrawList :
- viewInfo.performanceDrawList;
- }
- }
- // If the material has no effect, try to build shaders for it.
- if (!material.effect) {
- // If the user didn't pass an effect type in see if one was stored there
- // by our importer.
- if (!opt_effectType) {
- // Retrieve the lightingType parameter from the material, if any.
- var lightingType = o3djs.effect.getColladaLightingType(material);
- if (lightingType) {
- opt_effectType = lightingType;
- }
- }
- if (opt_effectType) {
- o3djs.material.attachStandardEffect(pack,
- material,
- viewInfo,
- opt_effectType,
- opt_options);
- // For collada common profile stuff guess what drawList to use. Note: We
- // can only do this for collada common profile stuff because we supply
- // the shaders and therefore now the inputs and how they are used.
- // For other shaders you've got to do this stuff yourself. On top of
- // that this is a total guess. Just because a texture has no alpha
- // it does not follow that you don't want it in the zOrderedDrawList.
- // That is application specific. Here we are just making a guess and
- // hoping that it covers most cases.
- if (material.drawList == null) {
- // Check the common profile params.
- var result = o3djs.material.hasNonOneAlpha_(material, 'diffuse');
- if (!result.found) {
- result = o3djs.material.hasNonOneAlpha_(material, 'emissive');
- }
- if (result.nonOneAlpha) {
- drawList = viewInfo.zOrderedDrawList;
- }
- }
- }
- }
- if (!material.drawList) {
- material.drawList = drawList;
- }
-};
-
-/**
- * Prepares all the materials in the given pack by setting their drawList and
- * if they don't have an Effect, creating one for them.
- *
- * This function is very specific to our sample importer. It expects that if
- * no Effect exists on a material that certain extra Params have been created
- * on the Material to give us instructions on what to Effects to create.
- *
- * @param {!o3d.Pack} pack Pack to prepare.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo as returned from
- * o3djs.rendergraph.createView.
- * @param {!o3d.Pack} opt_effectPack Pack to create effects in. If this
- * is not specifed the pack to prepare above will be used.
- * @param {Object} opt_options Extra options for effect.getStandardShader
- *
- * @see o3djs.material.prepareMaterial
- */
-o3djs.material.prepareMaterials = function(pack,
- viewInfo,
- opt_effectPack,
- opt_options) {
- var materials = pack.getObjectsByClassName('o3d.Material');
- for (var mm = 0; mm < materials.length; mm++) {
- o3djs.material.prepareMaterial(opt_effectPack || pack,
- viewInfo,
- materials[mm],
- undefined,
- opt_options);
- }
-};
-
-/**
- * Builds a standard effect for a given material.
- * If the material already has an effect, none is created.
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.Material} material The material for which to create an
- * effect.
- * @param {string} effectType Type of effect to create ('phong', 'lambert',
- * 'constant').
- * @param {Object} opt_options Extra options for effect.getStandardShader
- *
- * @see o3djs.effect.attachStandardShader
- */
-o3djs.material.attachStandardEffectEx = function(pack,
- material,
- effectType,
- opt_options) {
- if (!material.effect) {
- if (!o3djs.effect.attachStandardShader(pack,
- material,
- [0, 0, 0],
- effectType,
- opt_options)) {
- throw 'Could not attach a standard effect';
- }
- }
-};
-
-/**
- * Builds a standard effect for a given material. The position of the
- * default light is set to the view position. If the material already has
- * an effect, none is created.
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.Material} material The material for which to create an
- * effect.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo as returned from
- * o3djs.rendergraph.createView.
- * @param {string} effectType Type of effect to create ('phong', 'lambert',
- * 'constant').
- * @param {Object} opt_options Extra options for effect.getStandardShader
- *
- * @see o3djs.effect.attachStandardShader
- */
-o3djs.material.attachStandardEffect = function(pack,
- material,
- viewInfo,
- effectType,
- opt_options) {
- if (!material.effect) {
- var lightPos =
- o3djs.math.matrix4.getTranslation(
- o3djs.math.inverse(viewInfo.drawContext.view));
- if (!o3djs.effect.attachStandardShader(pack,
- material,
- lightPos, // TODO(gman): remove this
- effectType,
- opt_options)) {
- throw 'Could not attach a standard effect';
- }
- }
-};
-
-/**
- * Prepares all the materials in the given pack by setting their
- * drawList.
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.DrawList} drawList DrawList to assign to materials.
- */
-o3djs.material.setDrawListOnMaterials = function(pack, drawList) {
- var materials = pack.getObjectsByClassName('o3d.Material');
- for (var mm = 0; mm < materials.length; mm++) {
- var material = materials[mm];
- // TODO: look at flags on the material left by the importer
- // to decide which draw list to use.
- material.drawList = drawList;
- }
-};
-
-/**
- * This function creates a basic material for when you just want to get
- * something on the screen quickly without having to manually setup shaders.
- * You can call this function something like.
- *
- * <pre>
- * &lt;html&gt;&lt;body&gt;
- * &lt;script type="text/javascript" src="o3djs/all.js"&gt;
- * &lt;/script&gt;
- * &lt;script&gt;
- * window.onload = init;
- *
- * function init() {
- * o3djs.base.makeClients(initStep2);
- * }
- *
- * function initStep2(clientElements) {
- * var clientElement = clientElements[0];
- * var client = clientElement.client;
- * var pack = client.createPack();
- * var viewInfo = o3djs.rendergraph.createBasicView(
- * pack,
- * client.root,
- * client.renderGraphRoot);
- * var material = o3djs.material.createBasicMaterial(
- * pack,
- * viewInfo,
- * [1, 0, 0, 1]); // red
- * var shape = o3djs.primitives.createCube(pack, material, 10);
- * var transform = pack.createObject('Transform');
- * transform.parent = client.root;
- * transform.addShape(shape);
- * o3djs.camera.fitContextToScene(client.root,
- * client.width,
- * client.height,
- * viewInfo.drawContext);
- * }
- * &lt;/script&gt;
- * &lt;div id="o3d" style="width: 600px; height: 600px"&gt;&lt;/div&gt;
- * &lt;/body&gt;&lt;/html&gt;
- * </pre>
- *
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo as returned from
- * o3djs.rendergraph.createBasicView.
- * @param {(!o3djs.math.Vector4|!o3d.Texture)} colorOrTexture Either a color in
- * the format [r, g, b, a] or an O3D texture.
- * @param {boolean} opt_transparent Whether or not the material is transparent.
- * Defaults to false.
- * @return {!o3d.Material} The created material.
- */
-o3djs.material.createBasicMaterial = function(pack,
- viewInfo,
- colorOrTexture,
- opt_transparent) {
- var material = pack.createObject('Material');
- material.drawList = opt_transparent ? viewInfo.zOrderedDrawList :
- viewInfo.performanceDrawList;
-
- // If it has a length assume it's a color, otherwise assume it's a texture.
- if (colorOrTexture.length) {
- material.createParam('diffuse', 'ParamFloat4').value = colorOrTexture;
- } else {
- var paramSampler = material.createParam('diffuseSampler', 'ParamSampler');
- var sampler = pack.createObject('Sampler');
- paramSampler.value = sampler;
- sampler.texture = colorOrTexture;
- }
-
- // Create some suitable defaults for the material to save the user having
- // to know all this stuff right off the bat.
- material.createParam('emissive', 'ParamFloat4').value = [0, 0, 0, 1];
- material.createParam('ambient', 'ParamFloat4').value = [0, 0, 0, 1];
- material.createParam('specular', 'ParamFloat4').value = [1, 1, 1, 1];
- material.createParam('shininess', 'ParamFloat').value = 50;
- material.createParam('specularFactor', 'ParamFloat').value = 1;
- material.createParam('lightColor', 'ParamFloat4').value = [1, 1, 1, 1];
- var lightPositionParam = material.createParam('lightWorldPos',
- 'ParamFloat3');
-
- o3djs.material.attachStandardEffect(pack, material, viewInfo, 'phong');
-
- // We have to set the light position after calling attachStandardEffect
- // because attachStandardEffect sets it based on the view.
- lightPositionParam.value = [1000, 2000, 3000];
-
- return material;
-};
-
-/**
- * This function creates a constant material. No lighting. It is especially
- * useful for debugging shapes and 2d UI elements.
- *
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.DrawList} drawList The DrawList for the material.
- * @param {(!o3djs.math.Vector4|!o3d.Texture)} colorOrTexture Either a color in
- * the format [r, g, b, a] or an O3D texture.
- * @return {!o3d.Material} The created material.
- */
-o3djs.material.createConstantMaterialEx = function(pack,
- drawList,
- colorOrTexture) {
- var material = pack.createObject('Material');
- material.drawList = drawList;
-
- // If it has a length assume it's a color, otherwise assume it's a texture.
- if (colorOrTexture.length) {
- material.createParam('emissive', 'ParamFloat4').value = colorOrTexture;
- } else {
- var paramSampler = material.createParam('emissiveSampler', 'ParamSampler');
- var sampler = pack.createObject('Sampler');
- paramSampler.value = sampler;
- sampler.texture = colorOrTexture;
- }
-
- o3djs.material.attachStandardEffectEx(pack, material, 'constant');
-
- return material;
-};
-
-/**
- * This function creates a constant material. No lighting. It is especially
- * useful for debugging shapes and 2d UI elements.
- *
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo as returned from
- * o3djs.rendergraph.createBasicView.
- * @param {(!o3djs.math.Vector4|!o3d.Texture)} colorOrTexture Either a color in
- * the format [r, g, b, a] or an O3D texture.
- * @param {boolean} opt_transparent Whether or not the material is transparent.
- * Defaults to false.
- * @return {!o3d.Material} The created material.
- */
-o3djs.material.createConstantMaterial = function(pack,
- viewInfo,
- colorOrTexture,
- opt_transparent) {
- return o3djs.material.createConstantMaterialEx(
- pack,
- opt_transparent ? viewInfo.zOrderedDrawList :
- viewInfo.performanceDrawList,
- colorOrTexture)
-};
-
-/**
- * This function creates 2 color procedureal texture material.
- *
- * @see o3djs.material.createBasicMaterial
- *
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo as returned from
- * o3djs.rendergraph.createBasicView.
- * @param {!o3djs.math.Vector4} opt_color1 a color in the format [r, g, b, a].
- * Defaults to a medium blue-green.
- * @param {!o3djs.math.Vector4} opt_color2 a color in the format [r, g, b, a].
- * Defaults to a light blue-green.
- * @param {boolean} opt_transparent Whether or not the material is transparent.
- * Defaults to false.
- * @param {number} opt_checkSize Defaults to 10 units.
- * @return {!o3d.Material} The created material.
- */
-o3djs.material.createCheckerMaterial = function(pack,
- viewInfo,
- opt_color1,
- opt_color2,
- opt_transparent,
- opt_checkSize) {
- opt_color1 = opt_color1 || [0.4, 0.5, 0.5, 1];
- opt_color2 = opt_color2 || [0.6, 0.8, 0.8, 1];
- opt_checkSize = opt_checkSize || 10;
-
- var effect = o3djs.effect.createCheckerEffect(pack);
- var material = pack.createObject('Material');
- material.effect = effect;
- material.drawList = opt_transparent ? viewInfo.zOrderedDrawList :
- viewInfo.performanceDrawList;
- o3djs.effect.createUniformParameters(pack, effect, material);
-
- material.getParam('color1').value = opt_color1;
- material.getParam('color2').value = opt_color2;
- material.getParam('checkSize').value = opt_checkSize;
-
- return material;
-};
-
-/**
- * Creates a material for an effect loaded from a file.
- * If the effect has already been loaded in the pack it will be reused.
- * @param {!o3d.Pack} pack Pack to create effect in.
- * @param {string} url Url for effect file.
- * @param {!o3d.DrawList} drawList DrawList to assign effect to.
- * @return {!o3d.Material} The material.
- */
-o3djs.material.createMaterialFromFile = function(pack, url, drawList) {
- var effect = o3djs.effect.createEffectFromFile(pack, url);
-
- var material = pack.createObject('Material');
- material.effect = effect;
- material.drawList = drawList;
- o3djs.effect.createUniformParameters(pack, effect, material);
-
- return material;
-};
-
-/**
- * Binds params to all materials in a pack by name.
- * @param {!o3d.Material} material Material to bind params on.
- * @param {!Object} params A object where each property is the name of a param
- * and its value is that param.
- */
-o3djs.material.bindParamsOnMaterial = function(material, params) {
- for (var paramName in params) {
- var sourceParam = params[paramName];
- var param = material.getParam(paramName);
- if (param && sourceParam.isAClassName(param.className)) {
- param.bind(sourceParam);
- }
- }
-};
-
-/**
- * Binds params to all materials in a pack by name.
- * @param {!o3d.Pack} pack Pack with materials to bind.
- * @param {!Object} params A object where each property is the name of a param
- * and its value is that param.
- */
-o3djs.material.bindParams = function(pack, params) {
- var materials = pack.getObjectsByClassName('o3d.Material');
- for (var mm = 0; mm < materials.length; ++mm) {
- o3djs.material.bindParamsOnMaterial(materials[mm], params);
- }
-};
-
-/**
- * Creates params from a param spec.
- * @param {!o3d.Pack} pack Pack to create params in.
- * @param {!Object} paramSpec An object where each property is the name of a
- * param and its value is the type of param.
- * @return {!Object} params A object where each property is the name of a param
- * and its value is that param.
- */
-o3djs.material.createParams = function(pack, paramSpec) {
- var paramObject = pack.createObject('ParamObject');
- var params = { };
- for (var paramName in paramSpec) {
- params[paramName] = paramObject.createParam(paramName,
- paramSpec[paramName]);
- }
- return params;
-};
-
-/**
- * Creates the global params need by the shaders built in effect.js
- *
- * The params currently created are 'lightColor' which is a ParamFloat4 and
- * 'lightWorldPos' which is a ParamFloat3. You can set their values like this
- *
- * <pre>
- * var params = o3djs.material.createStandardParams(pack);
- * param.lightColor.value = [1, 0, 0, 1]; // red
- * param.lightWorldPos.value = [1000, 2000, 3000]; // set light position.
- * </pre>
- *
- * Note: This function just creates the params. It does not connect them to
- * anything. See o3djs.material.createAndBindStandardParams,
- * o3djs.material.createParams and o3djs.material.bindParams
- *
- * @see o3djs.material.createAndBindStandardParams
- * @see o3djs.material.createParams
- * @see o3djs.material.bindParams
- *
- * @param {!o3d.Pack} pack Pack to create params in.
- * @return {!Object} params A object where each property is the name of a param
- * and its value is that param.
- */
-o3djs.material.createStandardParams = function(pack) {
- var paramSpec = {
- 'lightColor': 'ParamFloat4',
- 'lightWorldPos': 'ParamFloat3'};
- return o3djs.material.createParams(pack, paramSpec);
-};
-
-/**
- * Creates the global params need by the shaders built in effect.js then binds
- * all the matching params on materials in pack to these global params.
- *
- * The params currently created are 'lightColor' which is a ParamFloat4 and
- * 'lightWorldPos' which is a ParamFloat3. You can set their values like this
- *
- * <pre>
- * var params = o3djs.material.createAndBindStandardParams(pack);
- * param.lightColor.value = [1, 0, 0, 1]; // red
- * param.lightWorldPos.value = [1000, 2000, 3000]; // set light position.
- * </pre>
- *
- * @see o3djs.material.createParams
- * @see o3djs.material.bindParams
- *
- * @param {!o3d.Pack} pack Pack to create params in.
- * @return {!Object} params A object where each property is the name of a param
- * and its value is that param.
- */
-o3djs.material.createAndBindStandardParams = function(pack) {
- var params = o3djs.material.createStandardParams(pack);
- o3djs.material.bindParams(pack, params);
- return params;
-};
-
diff --git a/o3d/samples/o3djs/math.js b/o3d/samples/o3djs/math.js
deleted file mode 100644
index ba07048..0000000
--- a/o3d/samples/o3djs/math.js
+++ /dev/null
@@ -1,3168 +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.
- */
-
-
-/**
- * @fileoverview This file contains matrix/vector math functions.
- * It adds them to the "math" module on the o3djs object.
- *
- * o3djs.math supports a row-major and a column-major mode. In both
- * modes, vectors are stored as arrays of numbers, and matrices are also.
- *
- * In row-major mode:
- *
- * - Rows of a matrix are neighboring <dimension> elements in the array.
- * - Entries of a matrix M get accessed in M[row*dimension+column] fashion.
- * - Tuples of coordinates adjacent are interpreted as row-vectors.
- * - A vector v gets transformed by a matrix M by multiplying in the order v*M.
- *
- * In column-major mode:
- *
- * - Columns of a matrix are neighboring <dimension> elements in the array.
- * - Entries of a matrix M get accessed in M[column*dimension+row] fashion.
- * - Tuples of coordinates adjacent are interpreted as column-vectors.
- * - A matrix M transforms a vector v by multiplying in the order M*v.
- *
- * When a function in o3djs.math requires separate row-major and
- * column-major versions, a function with the same name gets added to each of
- * the namespaces o3djs.math.rowMajor and o3djs.math.columnMajor. The
- * function installRowMajorFunctions() or the function
- * installColumnMajorFunctions() should get called during initialization to
- * establish the mode. installRowMajorFunctions() works by iterating through
- * the o3djs.math.rowMajor namespace and for each function foo, setting
- * o3djs.math.foo equal to o3djs.math.rowMajor.foo.
- * installRowMajorFunctions() works the same way, iterating over the columnMajor
- * namespace. At the end of this file, we call installRowMajorFunctions().
- *
- * Switching modes changes two things. It changes how a matrix is encoded as an
- * array, and it changes how the entries of a matrix get interpreted. Because
- * those two things change together, the matrix representing a given
- * transformation of space is the same JavaScript object in either mode.
- * One consequence of this is that very few functions require separate row-major
- * and column-major versions. Typically, a function requires separate versions
- * only if it makes matrix multiplication order explicit, like
- * mulMatrixMatrix(), mulMatrixVector(), or mulVectorMatrix(). Functions which
- * create a new matrix, like scaling(), rotationZYX(), and translation() return
- * the same JavaScript object in either mode, and functions which implicitly
- * multiply like scale(), rotateZYX() and translate() modify the matrix in the
- * same way in either mode.
- *
- * The convention choice made for math functions in this library is independent
- * of the convention choice for how matrices get loaded into shaders. That
- * convention is determined on a per-shader basis.
- *
- * Other utilities in o3djs should avoid making calls to functions that make
- * multiplication order explicit. Instead they should appeal to functions like:
- *
- * o3djs.math.matrix4.transformPoint
- * o3djs.math.matrix4.transformDirection
- * o3djs.math.matrix4.transformNormal
- * o3djs.math.matrix4.transformVector4
- * o3djs.math.matrix4.composition
- * o3djs.math.matrix4.compose
- *
- * These functions multiply matrices implicitly and internally choose the
- * multiplication order to get the right result. That way, utilities which use
- * o3djs.math work in either major mode. Note that this does not necessarily
- * mean all sample code will work even if a line is added which switches major
- * modes, but it does mean that calls to o3djs still do what they are supposed
- * to.
- */
-
-
-var use_plugin_math = false;
-
-if ((typeof o3d != 'undefined') && o3d && o3d.Transform &&
- o3d.Transform.makeIdentityMatrix4_) {
- o3djs.provide('o3djs.math');
-} else {
- use_plugin_math = true;
- o3djs.require('o3djs.plugin_math');
-}
-
-o3djs.provide("o3djs.flat_math");
-
-
-/**
- * A module for math for o3djs.math.
- * @namespace
- */
-o3djs.math = o3djs.math || {};
-
-/**
- * Functions which deal with 4-by-4 transformation matrices are kept in their
- * own namespsace.
- * @namespace
- */
-o3djs.math.matrix4 = o3djs.math.matrix4 || {};
-
-/**
- * Functions that are specifically row major are kept in their own namespace.
- * @namespace
- */
-o3djs.math.rowMajor = o3djs.math.rowMajor || {};
-
-/**
- * Functions that are specifically column major are kept in their own namespace.
- * @namespace
- */
-o3djs.math.columnMajor = o3djs.math.columnMajor || {};
-
-/**
- * Functions that do error checking are stored in their own namespace.
- * @namespace
- */
-o3djs.math.errorCheck = o3djs.math.errorCheck || {};
-
-/**
- * Functions that do no error checking and have a separate version that does in
- * o3djs.math.errorCheck are stored in their own namespace.
- * @namespace
- */
-o3djs.math.errorCheckFree = o3djs.math.errorCheckFree || {};
-
-/**
- * An Array of 2 floats
- * @type {(!Array.<number>|!o3d.Float2)}
- */
-o3djs.math.Vector2 = goog.typedef;
-
-/**
- * An Array of 3 floats
- * @type {(!Array.<number>|!o3d.Float3)}
- */
-o3djs.math.Vector3 = goog.typedef;
-
-/**
- * An Array of 4 floats
- * @type {(!Array.<number>|!o3d.Float4)}
- */
-o3djs.math.Vector4 = goog.typedef;
-
-/**
- * An Array of floats.
- * @type {!Array.<number>}
- */
-o3djs.math.Vector = goog.typedef;
-
-/**
- * A 1x1 Matrix of floats
- * @type {!Array.<!Array.<number>>}
- */
-o3djs.math.Matrix1 = goog.typedef;
-
-/**
- * A 2x2 Matrix of floats
- * @type {!Array.<!Array.<number>>}
- */
-o3djs.math.Matrix2 = goog.typedef;
-
-/**
- * A 3x3 Matrix of floats
- * @type {!Array.<!Array.<number>>}
- */
-o3djs.math.Matrix3 = goog.typedef;
-
-/**
- * A 4x4 Matrix of floats
- * @type {(!Array.<!Array.<number>>|!o3d.Matrix4)}
- */
-o3djs.math.Matrix4 = goog.typedef;
-
-/**
- * A arbitrary size Matrix of floats
- * @type {(!Array.<!Array.<number>>|!o3d.Matrix4)}
- */
-o3djs.math.Matrix = goog.typedef;
-
-
-/**
- * A module for math functions where a matrix is represented as a flat
- * (1-dimensional) array.
- * @namespace
- */
-o3djs.flat_math = o3djs.flat_math || {};
-
-/**
- * A random seed for the pseudoRandom function.
- * @private
- * @type {number}
- */
-o3djs.flat_math.randomSeed_ = 0;
-
-/**
- * A constant for the pseudoRandom function
- * @private
- * @type {number}
- */
-o3djs.flat_math.RANDOM_RANGE_ = Math.pow(2, 32);
-
-/**
- * Functions which deal with 4-by-4 transformation matrices are kept in their
- * own namespsace.
- * @namespace
- */
-o3djs.flat_math.matrix4 = o3djs.flat_math.matrix4 || {};
-
-/**
- * Functions that are specifically row major are kept in their own namespace.
- * @namespace
- */
-o3djs.flat_math.rowMajor = o3djs.flat_math.rowMajor || {};
-
-/**
- * Functions that are specifically column major are kept in their own namespace.
- * @namespace
- */
-o3djs.flat_math.columnMajor = o3djs.flat_math.columnMajor || {};
-
-/**
- * Functions that do error checking are stored in their own namespace.
- * @namespace
- */
-o3djs.flat_math.errorCheck = o3djs.flat_math.errorCheck || {};
-
-/**
- * Functions that do no error checking and have a separate version that does in
- * o3djs.flat_math.errorCheck are stored in their own namespace.
- * @namespace
- */
-o3djs.flat_math.errorCheckFree = o3djs.flat_math.errorCheckFree || {};
-
-/**
- * An Float32Array of 2 floats
- * @type {!Array.<number>}
- */
-o3djs.flat_math.Vector2 = goog.typedef;
-
-/**
- * An Float32Array of 3 floats
- * @type {!Array.<number>}
- */
-o3djs.flat_math.Vector3 = goog.typedef;
-
-/**
- * An Float32Array of 4 floats
- * @type {!Array.<number>}
- */
-o3djs.flat_math.Vector4 = goog.typedef;
-
-
-/**
- * A 1x1 Matrix of floats
- * @type {(!Array.<number>|Float32Array)}
- */
-o3djs.flat_math.Matrix1 = goog.typedef;
-
-/**
- * A 2x2 Matrix of floats
- * @type {(!Array.<number>|Float32Array)}
- */
-o3djs.flat_math.Matrix2 = goog.typedef;
-
-/**
- * A 3x3 Matrix of floats
- * @type {(!Array.<number>|Float32Array)}
- */
-o3djs.flat_math.Matrix3 = goog.typedef;
-
-/**
- * A 4x4 Matrix of floats
- * @type {(!Array.<number>|Float32Array)}
- */
-o3djs.flat_math.Matrix4 = goog.typedef;
-
-o3djs.flat_math.useFloat32Array_ = false;
-
-/**
- * A arbitrary size Matrix of floats
- * @type {(!Array.<number>|Float32Array|o3djs.flat_math.Matrix1|
- * o3djs.flat_math.Matrix2|o3djs.flat_math.Matrix3|o3djs.flat_math.Matrix4)}
- */
-o3djs.flat_math.Matrix = goog.typedef;
-
-/**
- * A arbitrary size Matrix of floats
- * @type {!Array.<number>}
- */
-o3djs.flat_math.Vector = goog.typedef;
-
-
-/**
- * Namespace for Float32Array specific math functions.
- * @namespace
- */
-o3djs.flat_math.Float32Array = {};
-
-/**
- * A arbitrary size Matrix of floats
- * @constructor
- */
-o3djs.flat_math.Float32Array.Matrix = Float32Array;
-
-/**
- * A Float32Array.
- * @constructor
- */
-o3djs.flat_math.Float32Array.Vector = Float32Array;
-
-/**
- * If 16 arguments, this returns a 4x4 matrix
- * with values set to the passed in arguments
- * If 9 arguments returns a 3x3 matrix, if 4 arguments returns a 2x2 matrix.
- * @param {number} a [0][0] element
- * @param {number} b [0][1] element
- * @param {number} c [0][2] element
- * @param {number} d [0][3] element
- * @param {number} e [1][0] element
- * @param {number} f [1][1] element
- * @param {number} g [1][2] element
- * @param {number} h [1][3] element
- * @param {number} i [2][0] element
- * @param {number} j [2][1] element
- * @param {number} k [2][2] element
- * @param {number} l [2][3] element
- * @param {number} m [3][0] element
- * @param {number} n [3][1] element
- * @param {number} o [3][2] element
- * @param {number} p [3][3] element
- * @returns {!o3djs.flat_math.Matrix}
- */
-o3djs.flat_math.Float32Array.makeMatrix = function(
- a, b, c, d,
- e, f, g, h,
- i, j, k, l,
- m, n, o, p) {
- if (p === undefined) {
- if (i === undefined) {
- var retval = new Float32Array(4);
- retval[0] = a;
- retval[1] = b;
- retval[2] = c;
- retval[3] = d;
- return retval;
- }
- var retval = new Float32Array(9);
- retval[0] = a;
- retval[1] = b;
- retval[2] = c;
- retval[3] = d;
- retval[4] = e;
- retval[5] = f;
- retval[6] = g;
- retval[7] = h;
- retval[8] = i;
- return retval;
- }
- var retval = new Float32Array(16);
- retval[0] = a;
- retval[1] = b;
- retval[2] = c;
- retval[3] = d;
- retval[4] = e;
- retval[5] = f;
- retval[6] = g;
- retval[7] = h;
- retval[8] = i;
- retval[9] = j;
- retval[10] = k;
- retval[11] = l;
- retval[12] = m;
- retval[13] = n;
- retval[14] = o;
- retval[15] = p;
- return retval;
-};
-
-/**
- * returns a 2x2 matrix
- * @param {number} a [0][0] element
- * @param {number} b [0][1] element
- * @param {number} c [1][0] element
- * @param {number} d [1][1] element
- * @returns {!o3djs.flat_math.Matrix}
- */
-o3djs.flat_math.Float32Array.makeMatrix2 = function(a,b,
- c,d) {
- var retval = new Float32Array(4);
- retval[0] = a;
- retval[1] = b;
- retval[2] = c;
- retval[3] = d;
- return retval;
-};
-
-/**
- * If returns a 3x3 matrix
- * @param {number} a [0][0] element
- * @param {number} b [0][1] element
- * @param {number} c [0][2] element
- * @param {number} d [1][0] element
- * @param {number} e [1][1] element
- * @param {number} f [1][2] element
- * @param {number} g [2][0] element
- * @param {number} h [2][1] element
- * @param {number} i [2][2] element
- * @return {!o3djs.flat_math.Matrix} the matrix of the above elements
- */
-o3djs.flat_math.Float32Array.makeMatrix3 = function(
- a, b, c,
- d, e, f,
- g, h, i) {
- var retval = new Float32Array(9);
- retval[0] = a;
- retval[1] = b;
- retval[2] = c;
- retval[3] = d;
- retval[4] = e;
- retval[5] = f;
- retval[6] = g;
- retval[7] = h;
- retval[8] = i;
- return retval;
-};
-
-/**
- * returns a 4x4 matrix
- * with values set to the passed in arguments
- * @param {number} a [0][0] element
- * @param {number} b [0][1] element
- * @param {number} c [0][2] element
- * @param {number} d [0][3] element
- * @param {number} e [1][0] element
- * @param {number} f [1][1] element
- * @param {number} g [1][2] element
- * @param {number} h [1][3] element
- * @param {number} i [2][0] element
- * @param {number} j [2][1] element
- * @param {number} k [2][2] element
- * @param {number} l [2][3] element
- * @param {number} m [3][0] element
- * @param {number} n [3][1] element
- * @param {number} o [3][2] element
- * @param {number} p [3][3] element
- * @returns {o3djs.flat_math.Matrix} comprised of the above elements
- */
-o3djs.flat_math.Float32Array.makeMatrix4 = function(
- a, b, c, d,
- e, f, g, h,
- i, j, k, l,
- m, n, o, p) {
- var retval = new Float32Array(16);
- retval[0] = a;
- retval[1] = b;
- retval[2] = c;
- retval[3] = d;
- retval[4] = e;
- retval[5] = f;
- retval[6] = g;
- retval[7] = h;
- retval[8] = i;
- retval[9] = j;
- retval[10] = k;
- retval[11] = l;
- retval[12] = m;
- retval[13] = n;
- retval[14] = o;
- retval[15] = p;
- return retval;
-};
-
-/**
- * Namespace for Array specific math functions
- */
-o3djs.flat_math.Array={};
-
-/**
- * A arbitrary size Matrix of floats
- * @constructor
- */
-o3djs.flat_math.Array.Matrix = Array;
-
-/**
- * An Float32Array of floats.
- * @constructor
- */
-o3djs.flat_math.Array.Vector = Array;
-
-/**
- * If 16 arguments, this returns a 4x4 matrix with values set to the passed
- * in arguments. If 9 arguments returns a 3x3 matrix, if 4 arguments returns
- * a 2x2 matrix
- * @param {number} a [0][0] element
- * @param {number} b [0][1] element
- * @param {number} c [0][2] element
- * @param {number} d [0][3] element
- * @param {number} e [1][0] element
- * @param {number} f [1][1] element
- * @param {number} g [1][2] element
- * @param {number} h [1][3] element
- * @param {number} i [2][0] element
- * @param {number} j [2][1] element
- * @param {number} k [2][2] element
- * @param {number} l [2][3] element
- * @param {number} m [3][0] element
- * @param {number} n [3][1] element
- * @param {number} o [3][2] element
- * @param {number} p [3][3] element
- */
-o3djs.flat_math.Array.makeMatrix = function(
- a, b, c, d,
- e, f, g, h,
- i, j, k, l,
- m, n, o, p) {
- if (p === undefined) {
- if (i === undefined) {
- return [a,b,c,d];
- }
- return [a, b, c, d, e, f, g, h, i];
- }
- return [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p];
-};
-
-/**
- * returns a 2x2 matrix
- * @param {number} a [0][0] element
- * @param {number} b [0][1] element
- * @param {number} c [1][0] element
- * @param {number} d [1][1] element
- * @returns {!o3djs.flat_math.Matrix}
- */
-o3djs.flat_math.Array.makeMatrix2 = function(a, b, c, d) {
- return [a, b, c, d];
-};
-
-/**
- * If returns a 3x3 matrix
- * @param {number} a [0][0] element
- * @param {number} b [0][1] element
- * @param {number} c [0][2] element
- * @param {number} d [1][0] element
- * @param {number} e [1][1] element
- * @param {number} f [1][2] element
- * @param {number} g [2][0] element
- * @param {number} h [2][1] element
- * @param {number} i [2][2] element
- * @return {!o3djs.flat_math.Matrix} the matrix of the above elements
- */
-o3djs.flat_math.Array.makeMatrix3 = function(
- a, b, c,
- d, e, f,
- g, h, i) {
- return [a, b, c, d, e, f, g, h, i];
-};
-
-/**
- * returns a 4x4 matrix
- * with values set to the passed in arguments
- * @param {number} a [0][0] element
- * @param {number} b [0][1] element
- * @param {number} c [0][2] element
- * @param {number} d [0][3] element
- * @param {number} e [1][0] element
- * @param {number} f [1][1] element
- * @param {number} g [1][2] element
- * @param {number} h [1][3] element
- * @param {number} i [2][0] element
- * @param {number} j [2][1] element
- * @param {number} k [2][2] element
- * @param {number} l [2][3] element
- * @param {number} m [3][0] element
- * @param {number} n [3][1] element
- * @param {number} o [3][2] element
- * @param {number} p [3][3] element
- * @returns {o3djs.flat_math.Matrix} comprised of the above elements
- */
-o3djs.flat_math.Array.makeMatrix4 = function(
- a, b, c, d,
- e, f, g, h,
- i, j, k, l,
- m, n, o, p) {
- return [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p];
-};
-
-
-/**
- * Helper function to copy functions from one namespace into another.
- * @param {Object} source The source namespace.
- * @param {Object} target The target namespace.
- */
-o3djs.copyFunctions_ = function(source, target) {
- for (var i in source) {
- var value = source[i];
- // If it's a function, copy it.
- if (value.call) {
- target[i] = value;
- }
- }
-};
-
-
-if (o3djs.flat_math.useFloat32Array_) {
- o3djs.flat_math.Matrix = o3djs.flat_math.Float32Array.Matrix;
- o3djs.flat_math.Vector = o3djs.flat_math.Float32Array.Vector;
- o3djs.copyFunctions_(o3djs.flat_math.Float32Array, o3djs.flat_math);
-} else {
- o3djs.flat_math.Matrix = o3djs.flat_math.Array.Matrix;
- o3djs.flat_math.Vector = o3djs.flat_math.Array.Vector;
- o3djs.copyFunctions_(o3djs.flat_math.Array, o3djs.flat_math);
-}
-
-
-/**
- * Returns a deterministic pseudorandom number between 0 and 1
- * @return {number} a random number between 0 and 1
- */
-o3djs.flat_math.pseudoRandom = function() {
- var math = o3djs.flat_math;
- return (math.randomSeed_ =
- (134775813 * math.randomSeed_ + 1) %
- math.RANDOM_RANGE_) / math.RANDOM_RANGE_;
-};
-
-/**
- * Resets the pseudoRandom function sequence.
- */
-o3djs.flat_math.resetPseudoRandom = function() {
- o3djs.flat_math.randomSeed_ = 0;
-};
-
-/**
- * Converts degrees to radians.
- * @param {number} degrees A value in degrees.
- * @return {number} the value in radians.
- */
-o3djs.flat_math.degToRad = function(degrees) {
- return degrees * Math.PI / 180;
-};
-
-/**
- * Converts radians to degrees.
- * @param {number} radians A value in radians.
- * @return {number} the value in degrees.
- */
-o3djs.flat_math.radToDeg = function(radians) {
- return radians * 180 / Math.PI;
-};
-
-/**
- * Performs linear interpolation on two scalars.
- * Given scalars a and b and interpolation coefficient t, returns
- * (1 - t) * a + t * b.
- * @param {number} a Operand scalar.
- * @param {number} b Operand scalar.
- * @param {number} t Interpolation coefficient.
- * @return {number} The weighted sum of a and b.
- */
-o3djs.flat_math.lerpScalar = function(a, b, t) {
- return (1 - t) * a + t * b;
-};
-
-/**
- * Adds two vectors; assumes a and b have the same dimension.
- * @param {!o3djs.flat_math.Vector} a Operand vector.
- * @param {!o3djs.flat_math.Vector} b Operand vector.
- * @return {!o3djs.flat_math.Vector} The sum of a and b.
- */
-o3djs.flat_math.addVector = function(a, b) {
- var aLength = a.length;
- var r = new o3djs.flat_math.Vector(aLength);
- for (var i = 0; i < aLength; ++i)
- r[i] = a[i] + b[i];
- return r;
-};
-
-/**
- * Subtracts two vectors.
- * @param {!o3djs.flat_math.Vector} a Operand vector.
- * @param {!o3djs.flat_math.Vector} b Operand vector.
- * @return {!o3djs.flat_math.Vector} The difference of a and b.
- */
-o3djs.flat_math.subVector = function(a, b) {
- var aLength = a.length;
- var r = new o3djs.flat_math.Vector(aLength);
- for (var i = 0; i < aLength; ++i)
- r[i] = a[i] - b[i];
- return r;
-};
-
-/**
- * Subtracts two 3d vectors.
- * @param {!o3djs.flat_math.Vector3} a Operand vector.
- * @param {!o3djs.flat_math.Vector3} b Operand vector.
- * @return {!o3djs.flat_math.Vector3} The difference of a and b.
- */
-o3djs.flat_math.subVector3 = function(a, b) {
- var r = new o3djs.flat_math.Vector(3);
- for (var i = 0; i < 3; ++i)
- r[i] = a[i] - b[i];
- return r;
-};
-
-/**
- * Performs linear interpolation on two vectors.
- * Given vectors a and b and interpolation coefficient t, returns
- * (1 - t) * a + t * b.
- * @param {!o3djs.flat_math.Vector} a Operand vector.
- * @param {!o3djs.flat_math.Vector} b Operand vector.
- * @param {number} t Interpolation coefficient.
- * @return {!o3djs.flat_math.Vector} The weighted sum of a and b.
- */
-o3djs.flat_math.lerpVector = function(a, b, t) {
- var aLength = a.length;
- var r = new o3djs.flat_math.Vector(aLength);
- for (var i = 0; i < aLength; ++i)
- r[i] = (1 - t) * a[i] + t * b[i];
- return r;
-};
-
-/**
- * Clamps a value between 0 and range using a modulo.
- * @param {number} v Value to clamp mod.
- * @param {number} range Range to clamp to.
- * @param {number} opt_rangeStart start of range. Default = 0.
- * @return {number} Clamp modded value.
- */
-o3djs.flat_math.modClamp = function(v, range, opt_rangeStart) {
- var start = opt_rangeStart || 0;
- if (range < 0.00001) {
- return start;
- }
- v -= start;
- if (v < 0) {
- v -= Math.floor(v / range) * range;
- } else {
- v = v % range;
- }
- return v + start;
-};
-
-/**
- * Lerps in a circle.
- * Does a lerp between a and b but inside range so for example if
- * range is 100, a is 95 and b is 5 lerping will go in the positive direction.
- * @param {number} a Start value.
- * @param {number} b Target value.
- * @param {number} t Amount to lerp (0 to 1).
- * @param {number} range Range of circle.
- * @return {number} lerped result.
- */
-o3djs.flat_math.lerpCircular = function(a, b, t, range) {
- a = o3djs.flat_math.modClamp(a, range);
- b = o3djs.flat_math.modClamp(b, range);
- var delta = b - a;
- if (Math.abs(delta) > range * 0.5) {
- if (delta > 0) {
- b -= range;
- } else {
- b += range;
- }
- }
- return o3djs.flat_math.modClamp(o3djs.flat_math.lerpScalar(a, b, t), range);
-};
-
-/**
- * Lerps radians.
- * @param {number} a Start value.
- * @param {number} b Target value.
- * @param {number} t Amount to lerp (0 to 1).
- * @return {number} lerped result.
- */
-o3djs.flat_math.lerpRadian = function(a, b, t) {
- return o3djs.flat_math.lerpCircular(a, b, t, Math.PI * 2);
-};
-
-/**
- * Divides a vector by a scalar.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @param {number} k The scalar.
- * @return {!o3djs.flat_math.Vector} v The vector v divided by k.
- */
-o3djs.flat_math.divVectorScalar = function(v, k) {
- var r = [];
- var vLength = v.length;
- for (var i = 0; i < vLength; ++i)
- r[i] = v[i] / k;
- return r;
-};
-
-/**
- * Computes the dot product of two vectors; assumes that a and b have
- * the same dimension.
- * @param {!o3djs.flat_math.Vector} a Operand vector.
- * @param {!o3djs.flat_math.Vector} b Operand vector.
- * @return {number} The dot product of a and b.
- */
-o3djs.flat_math.dot = function(a, b) {
- var r = 0.0;
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i)
- r += a[i] * b[i];
- return r;
-};
-
-/**
- * Computes the cross product of two vectors; assumes both vectors have
- * three entries.
- * @param {!o3djs.flat_math.Vector} a Operand vector.
- * @param {!o3djs.flat_math.Vector} b Operand vector.
- * @return {!o3djs.flat_math.Vector} The vector a cross b.
- */
-o3djs.flat_math.cross = function(a, b) {
- var r = new o3djs.flat_math.Vector(3);
- r[0] = a[1] * b[2] - a[2] * b[1];
- r[1] = a[2] * b[0] - a[0] * b[2];
- r[2] = a[0] * b[1] - a[1] * b[0];
- return r;
-};
-
-/**
- * Computes the Euclidean length of a vector, i.e. the square root of the
- * sum of the squares of the entries.
- * @param {!o3djs.flat_math.Vector} a The vector.
- * @return {number} The length of a.
- */
-o3djs.flat_math.length = function(a) {
- var r = 0.0;
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i)
- r += a[i] * a[i];
- return Math.sqrt(r);
-};
-
-/**
- * Computes the square of the Euclidean length of a vector, i.e. the sum
- * of the squares of the entries.
- * @param {!o3djs.flat_math.Vector} a The vector.
- * @return {number} The square of the length of a.
- */
-o3djs.flat_math.lengthSquared = function(a) {
- var r = 0.0;
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i)
- r += a[i] * a[i];
- return r;
-};
-
-/**
- * Computes the Euclidean distance between two vectors.
- * @param {!o3djs.flat_math.Vector} a A vector.
- * @param {!o3djs.flat_math.Vector} b A vector.
- * @return {number} The distance between a and b.
- */
-o3djs.flat_math.distance = function(a, b) {
- var r = 0.0;
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i) {
- var t = a[i] - b[i];
- r += t * t;
- }
- return Math.sqrt(r);
-};
-
-/**
- * Computes the square of the Euclidean distance between two vectors.
- * @param {!o3djs.flat_math.Vector} a A vector.
- * @param {!o3djs.flat_math.Vector} b A vector.
- * @return {number} The distance between a and b.
- */
-o3djs.flat_math.distanceSquared = function(a, b) {
- var r = 0.0;
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i) {
- var t = a[i] - b[i];
- r += t * t;
- }
- return r;
-};
-
-/**
- * Divides a vector by its Euclidean length and returns the quotient.
- * @param {!o3djs.flat_math.Vector} a The vector.
- * @return {!o3djs.flat_math.Vector} The normalized vector.
- */
-o3djs.flat_math.normalize = function(a) {
- var aLength = a.length;
- var r = new o3djs.flat_math.Vector(aLength);
- var n = 0.0;
- var i;
- for (i = 0; i < aLength; ++i)
- n += a[i] * a[i];
- n = Math.sqrt(n);
- for (i = 0; i < aLength; ++i)
- r[i] = a[i] / n;
- return r;
-};
-
-/**
- * Adds two matrices; assumes a and b are the same size.
- * @param {!o3djs.flat_math.Matrix} a Operand matrix.
- * @param {!o3djs.flat_math.Matrix} b Operand matrix.
- * @return {!o3djs.flat_math.Matrix} The sum of a and b.
- */
-o3djs.flat_math.addMatrix = function(a, b) {
- var aLength = a.length;
- var r = new o3djs.flat_math.Matrix(aLength);
- for (var i = 0; i < aLength; ++i) {
- r[i] = a[i] + b[i];
- }
- return r;
-};
-
-/**
- * Subtracts two matrices; assumes a and b are the same size.
- * @param {!o3djs.flat_math.Matrix} a Operand matrix.
- * @param {!o3djs.flat_math.Matrix} b Operand matrix.
- * @return {!o3djs.flat_math.Matrix} The sum of a and b.
- */
-o3djs.flat_math.subMatrix = function(a, b) {
- var aLength = a.length;
- var r = new o3djs.flat_math.Matrix(aLength);
- for (var i = 0; i < aLength; ++i) {
- r[i] = a[i] - b[i];
- }
- return r;
-};
-
-/**
- * Performs linear interpolation on two matrices.
- * Given matrices a and b and interpolation coefficient t, returns
- * (1 - t) * a + t * b.
- * @param {!o3djs.flat_math.Matrix} a Operand matrix.
- * @param {!o3djs.flat_math.Matrix} b Operand matrix.
- * @param {number} t Interpolation coefficient.
- * @return {!o3djs.flat_math.Matrix} Interpolated a and b.
- */
-o3djs.flat_math.lerpMatrix = function(a, b, t) {
- var aLength = a.length;
- var r = new o3djs.flat_math.Matrix(aLength);
- for (var i = 0; i < aLength; ++i) {
- r[i] = (1 - t) * a[i] + t * b[i];
- }
- return r;
-};
-
-/**
- * Divides a matrix by a scalar; assumes a and b are the same size.
- * @param {!o3djs.flat_math.Matrix} a Operand matrix.
- * @param {number} b scalar
- * @return {!o3djs.flat_math.Matrix} The division of a by b.
- */
-o3djs.flat_math.divMatrixScalar = function(a, b) {
- var aLength = a.length;
- var r = new o3djs.flat_math.Matrix(aLength);
- for (var i = 0; i < aLength; ++i) {
- r[i] = a[i] / b;
- }
- return r;
-};
-
-/**
- * Negates a scalar.
- * @param {number} a The scalar.
- * @return {number} -a.
- */
-o3djs.flat_math.negativeScalar = function(a) {
- return -a;
-};
-
-/**
- * Negates a vector.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @return {!o3djs.flat_math.Vector} -v.
- */
-o3djs.flat_math.negativeVector = function(v) {
- var vLength = v.length;
- var r = new o3djs.flat_math.Vector(vLength);
- for (var i = 0; i < vLength; ++i) {
- r[i] = -v[i];
- }
- return r;
-};
-
-/**
- * Negates a matrix.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {!o3djs.flat_math.Matrix} -m.
- */
-o3djs.flat_math.negativeMatrix = function(m) {
- var mLength = m.length;
- var r = new o3djs.flat_math.Matrix(mLength);
- for (var i = 0; i < mLength; ++i) {
- r[i] = -m[i];
- }
- return r;
-};
-
-/**
- * Copies a scalar.
- * @param {number} a The scalar.
- * @return {number} a.
- */
-o3djs.flat_math.copyScalar = function(a) {
- return a;
-};
-
-/**
- * Copies a vector.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @return {!o3djs.flat_math.Vector} A copy of v.
- */
-o3djs.flat_math.copyVector = function(v) {
- var vLength = v.length;
- var r = new o3djs.flat_math.Vector(vLength);
- for (var i = 0; i < vLength; i++)
- r[i] = v[i];
- return r;
-};
-
-/**
- * Copies a vector.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @param {!o3djs.flat_math.Vector} r Set to a copy of v.
- */
-o3djs.flat_math.copyVectorTo = function(v, r) {
- var vLength = v.length;
- for (var i = 0; i < vLength; i++)
- r[i] = v[i];
-};
-
-/**
- * Copies a matrix.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {!o3djs.flat_math.Matrix} A copy of m.
- */
-o3djs.flat_math.copyMatrix = o3djs.flat_math.copyVector;
-
-/**
- * Copies a matrix.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {!o3djs.flat_math.Matrix} A copy of m.
- */
-o3djs.flat_math.copyMatrixTo = o3djs.flat_math.copyVectorTo;
-
-/**
- * Returns the elements of a matrix as a copied one-dimensional array. The
- * rows or columns (depending on whether the matrix is row-major or
- * column-major) are concatenated.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {!Array.<number>} The matrix's elements as a one-dimensional array.
- */
-o3djs.flat_math.getMatrixElements = o3djs.flat_math.copyMatrix;
-
-/**
- * Multiplies two scalars.
- * @param {number} a Operand scalar.
- * @param {number} b Operand scalar.
- * @return {number} The product of a and b.
- */
-o3djs.flat_math.mulScalarScalar = function(a, b) {
- return a * b;
-};
-
-/**
- * Multiplies a scalar by a vector.
- * @param {number} k The scalar.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @return {!o3djs.flat_math.Vector} The product of k and v.
- */
-o3djs.flat_math.mulScalarVector = function(k, v) {
- var vLength = v.length;
- var r = new o3djs.flat_math.Vector(vLength);
- for (var i = 0; i < vLength; ++i) {
- r[i] = k * v[i];
- }
- return r;
-};
-
-/**
- * Multiplies a vector by a scalar.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @param {number} k The scalar.
- * @return {!o3djs.flat_math.Vector} The product of k and v.
- */
-o3djs.flat_math.mulVectorScalar = function(v, k) {
- return o3djs.flat_math.mulScalarVector(k, v);
-};
-
-/**
- * Multiplies a scalar by a matrix.
- * @param {number} k The scalar.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {!o3djs.flat_math.Matrix} The product of m and k.
- */
-o3djs.flat_math.mulScalarMatrix = o3djs.flat_math.mulScalarVector;
-
-/**
- * Multiplies a matrix by a scalar.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @param {number} k The scalar.
- * @return {!o3djs.flat_math.Matrix} The product of m and k.
- */
-o3djs.flat_math.mulMatrixScalar = o3djs.flat_math.mulVectorScalar;
-
-/**
- * Multiplies a vector by another vector (component-wise); assumes a and
- * b have the same length.
- * @param {!o3djs.flat_math.Vector} a Operand vector.
- * @param {!o3djs.flat_math.Vector} b Operand vector.
- * @return {!o3djs.flat_math.Vector} The vector of products of entries of a and
- * b.
- */
-o3djs.flat_math.mulVectorVector = function(a, b) {
- var aLength = a.length;
- var r = new o3djs.flat_math.Vector(aLength);
- for (var i = 0; i < aLength; ++i)
- r[i] = a[i] * b[i];
- return r;
-};
-
-/**
- * Divides a vector by another vector (component-wise); assumes a and
- * b have the same length.
- * @param {!o3djs.flat_math.Vector} a Operand vector.
- * @param {!o3djs.flat_math.Vector} b Operand vector.
- * @return {!o3djs.flat_math.Vector} The vector of quotients of entries of a and
- * b.
- */
-o3djs.flat_math.divVectorVector = function(a, b) {
- var aLength = a.length;
- var r = new o3djs.flat_math.Vector(aLength);
- for (var i = 0; i < aLength; ++i)
- r[i] = a[i] / b[i];
- return r;
-};
-
-/**
- * Multiplies a vector by a matrix; treats the vector as a row vector; assumes
- * matrix entries are accessed in [row*4+column] fashion.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {!o3djs.flat_math.Vector} The product of v and m as a row vector.
- */
-o3djs.flat_math.rowMajor.mulVectorMatrix4 = function(v, m) {
- var r = new o3djs.flat_math.Vector(16);
- for (var i = 0; i < 4; ++i) {
- r[i] = 0.0;
- for (var j = 0; j < 4; ++j)
- r[i] += v[j] * m[j * 4 + i];
- }
- return r;
-};
-
-/**
- * Multiplies a vector by a matrix; treats the vector as a row vector; assumes
- * matrix entries are accessed in [row*2+column] fashion.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @returns {!o3djs.flat_math.Vector} The product of v and m as a row vector.
- */
-o3djs.flat_math.rowMajor.mulVectorMatrix2 = function(v, m) {
- var r = new o3djs.flat_math.Vector(4);
- for (var i = 0; i < 2; ++i) {
- r[i] = 0.0;
- for (var j = 0; j < 2; ++j)
- r[i] += v[j] * m[j * 2 + i];
- }
- return r;
-};
-
-
-/**
- * Multiplies a vector by a matrix; treats the vector as a row vector; assumes
- * matrix entries are accessed in [row*3+column] fashion.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @returns {!o3djs.flat_math.Vector} The product of v and m as a row vector.
- */
-o3djs.flat_math.rowMajor.mulVectorMatrix3 = function(v, m) {
- var r = new o3djs.flat_math.Vector(9);
- for (var i = 0; i < 3; ++i) {
- r[i] = 0.0;
- for (var j = 0; j < 3; ++j)
- r[i] += v[j] * m[j * 3 + i];
- }
- return r;
-};
-
-
-/**
- * Multiplies a vector by a matrix; treats the vector as a row vector; assumes
- * matrix entries are accessed in [row*dimension+column] fashion.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {!o3djs.flat_math.Vector} The product of v and m as a row vector.
- */
-o3djs.flat_math.rowMajor.mulVectorMatrix = function(v, m) {
- switch(m.length) {
- case 4:
- return o3djs.flat_math.rowMajor.mulVectorMatrix2(v, m);
- case 9:
- return o3djs.flat_math.rowMajor.mulVectorMatrix3(v, m);
- case 16:
- return o3djs.flat_math.rowMajor.mulVectorMatrix4(v, m);
- default:
- throw "Cannot handle matrices of size other than 3x3 or 4x4";
- }
-};
-
-
-
-/**
- * Multiplies a vector by a matrix; treats the vector as a row vector; assumes
- * matrix entries are accessed in [column*4+row] fashion.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {!o3djs.flat_math.Vector} The product of v and m as a row vector.
- */
-o3djs.flat_math.rowMajor.mulMatrixVector4 = function(m, v) {
- var r = new o3djs.flat_math.Vector(4);
- var vLength = v.length;
- for (var i = 0; i < 4; ++i) {
- r[i] = 0.0;
- for (var j = 0; j < 4; ++j)
- r[i] += v[j] * m[i * 4 + j];
- }
- return r;
-};
-
-
-/**
- * Multiplies a vector by a matrix; treats the vector as a row vector; assumes
- * matrix entries are accessed in [column*3+row] fashion.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {!o3djs.flat_math.Vector} The product of v and m as a row vector.
- */
-o3djs.flat_math.rowMajor.mulMatrixVector3 = function(m, v) {
- var r = new o3djs.flat_math.Vector(3);
- var vLength = v.length;
- for (var i = 0; i < 3; ++i) {
- r[i] = 0.0;
- for (var j = 0; j < 3; ++j)
- r[i] += v[j] * m[i * 3 + j];
- }
- return r;
-};
-
-/**
- * Multiplies a vector by a matrix; treats the vector as a row vector; assumes
- * matrix entries are accessed in [column*2+row] fashion.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {!o3djs.flat_math.Vector} The product of v and m as a row vector.
- */
-o3djs.flat_math.rowMajor.mulMatrixVector2 = function(m, v) {
- var r = new o3djs.flat_math.Vector(2);
-
- var vLength = v.length;
- for (var i = 0; i < 2; ++i) {
- r[i] = 0.0;
- for (var j = 0; j < 2; ++j)
- r[i] += v[j] * m[i * 2 + j];
- }
- return r;
-};
-
-
-/**
- * Multiplies a vector by a matrix; treats the vector as a row vector; assumes
- * matrix entries are accessed in [column*dimension+row] fashion.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {!o3djs.flat_math.Vector} The product of v and m as a row vector.
- */
-o3djs.flat_math.rowMajor.mulMatrixVector = function(m, v) {
- switch(m.length) {
- case 4:
- return o3djs.flat_math.rowMajor.mulMatrixVector2(m, v);
- case 9:
- return o3djs.flat_math.rowMajor.mulMatrixVector3(m, v);
- case 16:
- return o3djs.flat_math.rowMajor.mulMatrixVector4(m, v);
- default:
- throw "Cannot handle matrices of size other than 3x3 or 4x4";
- }
-};
-
-/**
- * Multiplies a vector by a matrix; treats the vector as a row vector.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @return {!o3djs.flat_math.Vector} The product of m and v as a row vector.
- */
-o3djs.flat_math.mulVectorMatrix = null;
-
-/**
- * Multiplies a matrix by a vector; treats the vector as a column vector.
- * assumes matrix entries are accessed in [row][column] fashion.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @return {!o3djs.flat_math.Vector} The product of m and v as a column vector.
- */
-o3djs.flat_math.columnMajor.mulVectorMatrix = function (v, m) {
- return o3djs.flat_math.rowMajor.mulMatrixVector(m, v);
-};
-
-/**
- * Multiplies a matrix by a vector; treats the vector as a column vector;
- * assumes matrix entries are accessed in [column][row] fashion.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @return {!o3djs.flat_math.Vector} The product of m and v as a column vector.
- */
-o3djs.flat_math.columnMajor.mulMatrixVector = function(m, v) {
- return o3djs.flat_math.rowMajor.mulVectorMatrix(v, m);
-};
-
-/**
- * Multiplies a matrix by a vector; treats the vector as a column vector.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @param {!o3djs.flat_math.Vector} v The vector.
- * @return {!o3djs.flat_math.Vector} The product of m and v as a column vector.
- */
-o3djs.flat_math.mulMatrixVector = null;
-
-/**
- * Multiplies two 2-by-2 matrices; assumes that the given matrices are 2-by-2;
- * assumes matrix entries are accessed in [row][column] fashion.
- * @param {!o3djs.flat_math.Matrix2} a The matrix on the left.
- * @param {!o3djs.flat_math.Matrix2} b The matrix on the right.
- * @return {!o3djs.flat_math.Matrix2} The matrix product of a and b.
- */
-o3djs.flat_math.rowMajor.mulMatrixMatrix2 = function(a, b) {
- var a0 = a[0];
- var a1 = a[1];
- var b0 = b[0];
- var b1 = b[1];
- var a00 = a[0];
- var a01 = a[1];
- var a10 = a[2];
- var a11 = a[3];
- var b00 = b[0];
- var b01 = b[1];
- var b10 = b[2];
- var b11 = b[3];
- return o3djs.flat_math.makeMatrix2(a00 * b00 + a01 * b10, a00 * b01 + a01 * b11,
- a10 * b00 + a11 * b10, a10 * b01 + a11 * b11);
-};
-
-/**
- * Multiplies two 2-by-2 matrices; assumes that the given matrices are 2-by-2;
- * assumes matrix entries are accessed in [column][row] fashion.
- * @param {!o3djs.flat_math.Matrix2} a The matrix on the left.
- * @param {!o3djs.flat_math.Matrix2} b The matrix on the right.
- * @return {!o3djs.flat_math.Matrix2} The matrix product of a and b.
- */
-o3djs.flat_math.columnMajor.mulMatrixMatrix2 = function(a, b) {
- var a0 = a[0];
- var a1 = a[1];
- var b0 = b[0];
- var b1 = b[1];
- var a00 = a[0];
- var a01 = a[1];
- var a10 = a[2];
- var a11 = a[3];
- var b00 = b[0];
- var b01 = b[1];
- var b10 = b[2];
- var b11 = b[3];
- return o3djs.flat_math.makeMatrix2(a00 * b00 + a10 * b01, a01 * b00 + a11 * b01,
- a00 * b10 + a10 * b11, a01 * b10 + a11 * b11);
-};
-
-/**
- * Multiplies two 2-by-2 matrices.
- * @param {!o3djs.flat_math.Matrix2} a The matrix on the left.
- * @param {!o3djs.flat_math.Matrix2} b The matrix on the right.
- * @return {!o3djs.flat_math.Matrix2} The matrix product of a and b.
- */
-o3djs.flat_math.mulMatrixMatrix2 = null;
-
-
-/**
- * Multiplies two 3-by-3 matrices; assumes that the given matrices are 3-by-3;
- * assumes matrix entries are accessed in [row][column] fashion.
- * @param {!o3djs.flat_math.Matrix3} a The matrix on the left.
- * @param {!o3djs.flat_math.Matrix3} b The matrix on the right.
- * @return {!o3djs.flat_math.Matrix3} The matrix product of a and b.
- */
-o3djs.flat_math.rowMajor.mulMatrixMatrix3 = function(a, b) {
- var a0 = a[0];
- var a1 = a[1];
- var a2 = a[2];
- var b0 = b[0];
- var b1 = b[1];
- var b2 = b[2];
- var a00 = a[0];
- var a01 = a[1];
- var a02 = a[2];
- var a10 = a[3];
- var a11 = a[4];
- var a12 = a[5];
- var a20 = a[6];
- var a21 = a[7];
- var a22 = a[8];
- var b00 = b[0];
- var b01 = b[1];
- var b02 = b[2];
- var b10 = b[3];
- var b11 = b[4];
- var b12 = b[5];
- var b20 = b[6];
- var b21 = b[7];
- var b22 = b[8];
- return o3djs.flat_math.makeMatrix3(a00 * b00 + a01 * b10 + a02 * b20,
- a00 * b01 + a01 * b11 + a02 * b21,
- a00 * b02 + a01 * b12 + a02 * b22,
- a10 * b00 + a11 * b10 + a12 * b20,
- a10 * b01 + a11 * b11 + a12 * b21,
- a10 * b02 + a11 * b12 + a12 * b22,
- a20 * b00 + a21 * b10 + a22 * b20,
- a20 * b01 + a21 * b11 + a22 * b21,
- a20 * b02 + a21 * b12 + a22 * b22);
-};
-
-/**
- * Multiplies two 3-by-3 matrices; assumes that the given matrices are 3-by-3;
- * assumes matrix entries are accessed in [column][row] fashion.
- * @param {!o3djs.flat_math.Matrix3} a The matrix on the left.
- * @param {!o3djs.flat_math.Matrix3} b The matrix on the right.
- * @return {!o3djs.flat_math.Matrix3} The matrix product of a and b.
- */
-o3djs.flat_math.columnMajor.mulMatrixMatrix3 = function(a, b) {
-
- var a00 = a[0];
- var a01 = a[1];
- var a02 = a[2];
- var a10 = a[3];
- var a11 = a[4];
- var a12 = a[5];
- var a20 = a[6];
- var a21 = a[7];
- var a22 = a[8];
- var b00 = b[0];
- var b01 = b[1];
- var b02 = b[2];
- var b10 = b[3];
- var b11 = b[4];
- var b12 = b[5];
- var b20 = b[6];
- var b21 = b[7];
- var b22 = b[8];
-
- return o3djs.flat_math.makeMatrix4(a00 * b00 + a10 * b01 + a20 * b02,
- a01 * b00 + a11 * b01 + a21 * b02,
- a02 * b00 + a12 * b01 + a22 * b02,
- a00 * b10 + a10 * b11 + a20 * b12,
- a01 * b10 + a11 * b11 + a21 * b12,
- a02 * b10 + a12 * b11 + a22 * b12,
- a00 * b20 + a10 * b21 + a20 * b22,
- a01 * b20 + a11 * b21 + a21 * b22,
- a02 * b20 + a12 * b21 + a22 * b22);
-};
-
-/**
- * Multiplies two 3-by-3 matrices; assumes that the given matrices are 3-by-3.
- * @param {!o3djs.flat_math.Matrix3} a The matrix on the left.
- * @param {!o3djs.flat_math.Matrix3} b The matrix on the right.
- * @return {!o3djs.flat_math.Matrix3} The matrix product of a and b.
- */
-o3djs.flat_math.mulMatrixMatrix3 = null;
-
-/**
- * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4;
- * assumes matrix entries are accessed in [row][column] fashion.
- * @param {!o3djs.flat_math.Matrix4} a The matrix on the left.
- * @param {!o3djs.flat_math.Matrix4} b The matrix on the right.
- * @return {!o3djs.flat_math.Matrix4} The matrix product of a and b.
- */
-o3djs.flat_math.rowMajor.mulMatrixMatrix4 = function(a, b) {
-
- var a00 = a[0];
- var a01 = a[1];
- var a02 = a[2];
- var a03 = a[3];
- var a10 = a[4];
- var a11 = a[5];
- var a12 = a[6];
- var a13 = a[7];
- var a20 = a[8];
- var a21 = a[9];
- var a22 = a[10];
- var a23 = a[11];
- var a30 = a[12];
- var a31 = a[13];
- var a32 = a[14];
- var a33 = a[15];
- var b00 = b[0];
- var b01 = b[1];
- var b02 = b[2];
- var b03 = b[3];
- var b10 = b[4];
- var b11 = b[5];
- var b12 = b[6];
- var b13 = b[7];
- var b20 = b[8];
- var b21 = b[9];
- var b22 = b[10];
- var b23 = b[11];
- var b30 = b[12];
- var b31 = b[13];
- var b32 = b[14];
- var b33 = b[15];
- return o3djs.flat_math.makeMatrix4(a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30,
- a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31,
- a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32,
- a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33,
- a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30,
- a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31,
- a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32,
- a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33,
- a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30,
- a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31,
- a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32,
- a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33,
- a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30,
- a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31,
- a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32,
- a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33);
-};
-
-/**
- * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4;
- * assumes matrix entries are accessed in [column][row] fashion.
- * @param {!o3djs.flat_math.Matrix4} a The matrix on the left.
- * @param {!o3djs.flat_math.Matrix4} b The matrix on the right.
- * @return {!o3djs.flat_math.Matrix4} The matrix product of a and b.
- */
-o3djs.flat_math.columnMajor.mulMatrixMatrix4 = function(a, b) {
-
- var a00 = a[0];
- var a01 = a[1];
- var a02 = a[2];
- var a03 = a[3];
- var a10 = a[4];
- var a11 = a[5];
- var a12 = a[6];
- var a13 = a[7];
- var a20 = a[8];
- var a21 = a[9];
- var a22 = a[10];
- var a23 = a[11];
- var a30 = a[12];
- var a31 = a[13];
- var a32 = a[14];
- var a33 = a[15];
- var b00 = b[0];
- var b01 = b[1];
- var b02 = b[2];
- var b03 = b[3];
- var b10 = b[4];
- var b11 = b[5];
- var b12 = b[6];
- var b13 = b[7];
- var b20 = b[8];
- var b21 = b[9];
- var b22 = b[10];
- var b23 = b[11];
- var b30 = b[12];
- var b31 = b[13];
- var b32 = b[14];
- var b33 = b[15];
- return o3djs.flat_math.makeMatrix4(
- a00 * b00 + a10 * b01 + a20 * b02 + a30 * b03,
- a01 * b00 + a11 * b01 + a21 * b02 + a31 * b03,
- a02 * b00 + a12 * b01 + a22 * b02 + a32 * b03,
- a03 * b00 + a13 * b01 + a23 * b02 + a33 * b03,
- a00 * b10 + a10 * b11 + a20 * b12 + a30 * b13,
- a01 * b10 + a11 * b11 + a21 * b12 + a31 * b13,
- a02 * b10 + a12 * b11 + a22 * b12 + a32 * b13,
- a03 * b10 + a13 * b11 + a23 * b12 + a33 * b13,
- a00 * b20 + a10 * b21 + a20 * b22 + a30 * b23,
- a01 * b20 + a11 * b21 + a21 * b22 + a31 * b23,
- a02 * b20 + a12 * b21 + a22 * b22 + a32 * b23,
- a03 * b20 + a13 * b21 + a23 * b22 + a33 * b23,
- a00 * b30 + a10 * b31 + a20 * b32 + a30 * b33,
- a01 * b30 + a11 * b31 + a21 * b32 + a31 * b33,
- a02 * b30 + a12 * b31 + a22 * b32 + a32 * b33,
- a03 * b30 + a13 * b31 + a23 * b32 + a33 * b33);
-};
-
-/**
- * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4.
- * @param {!o3djs.flat_math.Matrix4} a The matrix on the left.
- * @param {!o3djs.flat_math.Matrix4} b The matrix on the right.
- * @return {!o3djs.flat_math.Matrix4} The matrix product of a and b.
- */
-o3djs.flat_math.mulMatrixMatrix4 = null;
-
-/**
- * Multiplies two matrices; assumes the matrices are square of size 2, 3 or 4;
- * assumes matrix entries are accessed in row-major fashion.
- * @param {!o3djs.flat_math.Matrix} a The matrix on the left.
- * @param {!o3djs.flat_math.Matrix} b The matrix on the right.
- * @return {!o3djs.flat_math.Matrix} The matrix product of a and b.
- */
-o3djs.flat_math.rowMajor.mulMatrixMatrix = function(a, b) {
- switch(a.length) {
- case 4:
- return o3djs.flat_math.rowMajor.mulMatrixMatrix2(a, b);
- case 9:
- return o3djs.flat_math.rowMajor.mulMatrixMatrix3(a, b);
- case 16:
- return o3djs.flat_math.rowMajor.mulMatrixMatrix4(a, b);
- default:
- throw "Unable to handle irregular matrices or matrices of dim > 4 or < 2";
- }
-};
-
-
-/**
- * Multiplies two matrices; assumes the matrices are square of size 2, 3 or 4;
- * assumes matrix entries are accessed in column-major fashion.
- * @param {!o3djs.flat_math.Matrix} a The matrix on the left.
- * @param {!o3djs.flat_math.Matrix} b The matrix on the right.
- * @return {!o3djs.flat_math.Matrix} The matrix product of a and b.
- */
-o3djs.flat_math.columnMajor.mulMatrixMatrix = function(a, b) {
- switch(a.length) {
- case 4:
- return o3djs.flat_math.columnMajor.mulMatrixMatrix2(a, b);
- case 9:
- return o3djs.flat_math.columnMajor.mulMatrixMatrix3(a, b);
- case 16:
- return o3djs.flat_math.columnMajor.mulMatrixMatrix4(a, b);
- default:
- throw "Unable to handle irregular matrices or matrices of dim > 4 or < 2";
- }
-};
-
-
-/**
- * Multiplies two matrices; assumes that the sizes of the matrices are
- * appropriately compatible; assumes matrix entries are accessed in
- * [column][row] fashion.
- * @param {!o3djs.flat_math.Matrix} a The matrix on the left.
- * @param {!o3djs.flat_math.Matrix} b The matrix on the right.
- * @return {!o3djs.flat_math.Matrix} The matrix product of a and b.
- */
-o3djs.flat_math.rowMajor.generalizedMulMatrixMatrix= function(a, b) {
- var r = [];
- var aRows = a.length;
- var bColumns = b[0].length;
- var bRows = b.length;
- for (var i = 0; i < aRows; ++i) {
- var v = []; // v becomes a row of the answer.
- var ai = a[i]; // ith row of a.
- for (var j = 0; j < bColumns; ++j) {
- v[j] = 0.0;
- for (var k = 0; k < bRows; ++k)
- v[j] += ai[k] * b[k][j]; // kth row, jth column.
- }
- r[i] = v;
- }
- return r;
-};
-
-/**
- * Multiplies two matrices; assumes that the sizes of the matrices are
- * appropriately compatible.
- * @param {!o3djs.flat_math.Matrix} a The matrix on the left.
- * @param {!o3djs.flat_math.Matrix} b The matrix on the right.
- * @return {!o3djs.flat_math.Matrix} The matrix product of a and b.
- */
-o3djs.flat_math.mulMatrixMatrix = null;
-
-/**
- * Gets the jth column of the given matrix m; assumes matrix entries are
- * accessed in [row*dimension+column] fashion.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @param {number} j The index of the desired column.
- * @return {!o3djs.flat_math.Vector} The jth column of m as a vector.
- */
-o3djs.flat_math.rowMajor.column = function(m, j) {
- var mLength = m.length;
- var dimension;
- switch (mLength){
- case 4:
- dimension = 2;
- break;
- case 9:
- dimension = 3;
- break;
- case 16:
- dimension = 4;
- break;
- }
- var r = new o3djs.flat_math.Vector(dimension);
- for (var i = 0; i < dimension; ++i) {
- r[i] = m[i * dimension + j];
- }
- return r;
-};
-
-/**
- * Gets the jth column of the given matrix m; assumes matrix entries are
- * accessed in [column][row] fashion.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @param {number} j The index of the desired column.
- * @return {!o3djs.flat_math.Vector} The jth column of m as a vector.
- */
-o3djs.flat_math.columnMajor.column = function(m, j) {
- var dimension;
- var mLength = m.length;
- switch (mLength){
- case 4:
- dimension = 2;
- break;
- case 9:
- dimension = 3;
- break;
- case 16:
- dimension = 4;
- break;
- default:
- dimension = Math.sqrt(dimension);
- if (Math.round(dimension) * Math.round(dimension) != mLength) {
- throw "Calling column on nonsquare matrix";
- }
- }
- return m.slice(j * dimension, j * dimension + dimension);
-};
-
-/**
- * Gets the jth column of the given matrix m.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @param {number} j The index of the desired column.
- * @return {!o3djs.flat_math.Vector} The jth column of m as a vector.
- */
-o3djs.flat_math.column = null;
-
-/**
- * Gets the ith row of the given matrix m; assumes matrix entries are
- * accessed in [row][column] fashion.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @param {number} i The index of the desired row.
- * @return {!o3djs.flat_math.Vector} The ith row of m.
- */
-o3djs.flat_math.rowMajor.row = o3djs.flat_math.columnMajor.column;
-
-/**
- * Gets the ith row of the given matrix m; assumes matrix entries are
- * accessed in [column][row] fashion.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @param {number} i The index of the desired row.
- * @return {!o3djs.flat_math.Vector} The ith row of m.
- */
-o3djs.flat_math.columnMajor.row = o3djs.flat_math.rowMajor.column;
-
-/**
- * Gets the ith row of the given matrix m.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @param {number} i The index of the desired row.
- * @return {!o3djs.flat_math.Vector} The ith row of m.
- */
-o3djs.flat_math.row = null;
-
-/**
- * Creates an n-by-n identity matrix.
- * @param {number} n The dimension of the identity matrix required.
- * @return {!o3djs.flat_math.Matrix} An n-by-n identity matrix.
- */
-o3djs.flat_math.identity = function(n) {
- var r = new o3djs.flat_math.Matrix(n*n);
-
- for (var j = 0; j < n; ++j) {
- for (var i = 0; i < n; ++i)
- r[j * n + i] = (i == j) ? 1 : 0;
- }
- return r;
-};
-
-/**
- * Takes the transpose of a matrix.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {!o3djs.flat_math.Matrix} The transpose of m.
- */
-o3djs.flat_math.transpose = function(m) {
- var mLength = m.length;
- var r = new o3djs.flat_math.Matrix(mLength);
- var dimension;
- switch (mLength){
- case 4:
- dimension = 2;
- break;
- case 9:
- dimension = 3;
- break;
- case 16:
- dimension = 4;
- break;
- default:
- dimension = Math.sqrt(dimension);
- if (Math.round(dimension) * Math.round(dimension) != mLength) {
- throw "Calling transpose on nonsquare matrix";
- }
- }
-
- for (var j = 0; j < dimension; ++j) {
- for (var i = 0; i < dimension; ++i)
- r[j * dimension + i] = m[i * dimension + j];
- }
- return r;
-};
-
-/**
- * Computes the trace (sum of the diagonal entries) of a square matrix;
- * assumes m is square.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {number} The trace of m.
- */
-o3djs.flat_math.trace = function(m) {
- var r = 0.0;
- var dimension;
- switch (mLength){
- case 4:
- dimension = 2;
- break;
- case 9:
- dimension = 3;
- break;
- case 16:
- dimension = 4;
- break;
- }
- var mLength = dimension;
- for (var i = 0; i < mLength; ++i)
- r += m[i * dimension + i];
- return r;
-};
-
-/**
- * Computes the determinant of a 1-by-1 matrix.
- * @param {!o3djs.flat_math.Matrix1} m The matrix.
- * @return {number} The determinant of m.
- */
-o3djs.flat_math.det1 = function(m) {
- return m[0];
-};
-
-/**
- * Computes the determinant of a 2-by-2 matrix.
- * @param {!o3djs.flat_math.Matrix2} m The matrix.
- * @return {number} The determinant of m.
- */
-o3djs.flat_math.det2 = function(m) {
- return m[0] * m[3] - m[1] * m[2];
-};
-
-/**
- * Computes the determinant of a 3-by-3 matrix.
- * @param {!o3djs.flat_math.Matrix3} m The matrix.
- * @return {number} The determinant of m.
- */
-o3djs.flat_math.det3 = function(m) {
- return m[8] * (m[0 * 3] * m[4] - m[1] * m[1 * 3]) -
- m[7] * (m[0 * 3] * m[5] - m[2] * m[1 * 3]) +
- m[2 * 3] * (m[1] * m[5] - m[2] * m[4]);
-};
-
-/**
- * Computes the determinant of a 4-by-4 matrix.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @return {number} The determinant of m.
- */
-o3djs.flat_math.det4 = function(m) {
- var t01 = m[0] * m[5] - m[1] * m[4];
- var t02 = m[0] * m[6] - m[2] * m[4];
- var t03 = m[0] * m[7] - m[3] * m[4];
- var t12 = m[1] * m[6] - m[2] * m[5];
- var t13 = m[1] * m[7] - m[3] * m[5];
- var t23 = m[2] * m[7] - m[3] * m[6];
- return m[15] * (m[10] * t01 - m[9] * t02 + m[8] * t12) -
- m[14] * (m[11] * t01 - m[9] * t03 + m[8] * t13) +
- m[13] * (m[11] * t02 - m[10] * t03 + m[8] * t23) -
- m[12] * (m[11] * t12 - m[10] * t13 + m[9] * t23);
-};
-
-/**
- * Computes the inverse of a 1-by-1 matrix.
- * @param {!o3djs.flat_math.Matrix1} m The matrix.
- * @return {!o3djs.flat_math.Matrix1} The inverse of m.
- */
-o3djs.flat_math.inverse1 = function(m) {
- var retval = new o3djs.flat_math.Matrix(1);
- retval[0] = 1.0 / m[0];
- return retval;
-};
-
-/**
- * Computes the inverse of a 2-by-2 matrix.
- * @param {!o3djs.flat_math.Matrix2} m The matrix.
- * @return {!o3djs.flat_math.Matrix2} The inverse of m.
- */
-o3djs.flat_math.inverse2 = function(m) {
- var d = 1.0 / (m[0] * m[3] - m[1] * m[2]);
- return o3djs.flat_math.makeMatrix2(d * m[3], -d * m[1],
- -d * m[2], d * m[0]);
-};
-
-/**
- * Computes the inverse of a 3-by-3 matrix.
- * @param {!o3djs.flat_math.Matrix3} m The matrix.
- * @return {!o3djs.flat_math.Matrix3} The inverse of m.
- */
-o3djs.flat_math.inverse3 = function(m) {
- var t00 = m[4] * m[8] - m[5] * m[7];
- var t10 = m[1] * m[8] - m[2] * m[7];
- var t20 = m[1] * m[5] - m[2] * m[4];
- var d = 1.0 / (m[0] * t00 - m[3] * t10 + m[6] * t20);
- return o3djs.flat_math.makeMatrix3(d * t00, -d * t10, d * t20,
- -d * (m[3] * m[8] - m[5] * m[6]),
- d * (m[0] * m[8] - m[2] * m[6]),
- -d * (m[0] * m[5] - m[2] * m[3]),
- d * (m[3] * m[7] - m[4] * m[6]),
- -d * (m[0] * m[7] - m[1] * m[6]),
- d * (m[0] * m[4] - m[1] * m[3]));
-};
-
-/**
- * Computes the inverse of a 4-by-4 matrix.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @return {!o3djs.flat_math.Matrix4} The inverse of m.
- */
-o3djs.flat_math.inverse4 = function(m) {
- var tmp_0 = m[10] * m[15];
- var tmp_1 = m[14] * m[11];
- var tmp_2 = m[6] * m[15];
- var tmp_3 = m[14] * m[7];
- var tmp_4 = m[6] * m[11];
- var tmp_5 = m[10] * m[7];
- var tmp_6 = m[2] * m[15];
- var tmp_7 = m[14] * m[3];
- var tmp_8 = m[2] * m[11];
- var tmp_9 = m[10] * m[3];
- var tmp_10 = m[2] * m[7];
- var tmp_11 = m[6] * m[3];
- var tmp_12 = m[8] * m[13];
- var tmp_13 = m[12] * m[9];
- var tmp_14 = m[4] * m[13];
- var tmp_15 = m[12] * m[5];
- var tmp_16 = m[4] * m[9];
- var tmp_17 = m[8] * m[5];
- var tmp_18 = m[0] * m[13];
- var tmp_19 = m[12] * m[1];
- var tmp_20 = m[0] * m[9];
- var tmp_21 = m[8] * m[1];
- var tmp_22 = m[0] * m[5];
- var tmp_23 = m[4] * m[1];
-
- var t0 = tmp_0 * m[5] + tmp_3 * m[9] + tmp_4 * m[13] -
- (tmp_1 * m[5] + tmp_2 * m[9] + tmp_5 * m[13]);
- var t1 = tmp_1 * m[1] + tmp_6 * m[9] + tmp_9 * m[13] -
- (tmp_0 * m[1] + tmp_7 * m[9] + tmp_8 * m[13]);
- var t2 = tmp_2 * m[1] + tmp_7 * m[5] + tmp_10 * m[13] -
- (tmp_3 * m[1] + tmp_6 * m[5] + tmp_11 * m[13]);
- var t3 = (tmp_5 * m[1] + tmp_8 * m[5] + tmp_11 * m[9]) -
- (tmp_4 * m[1] + tmp_9 * m[5] + tmp_10 * m[9]);
-
- var d = 1.0 / (m[0] * t0 + m[1 * 4] * t1 + m[8] * t2 + m[12] * t3);
-
- return o3djs.flat_math.makeMatrix4(d * t0, d * t1, d * t2, d * t3,
- d * ((tmp_1 * m[1 * 4] + tmp_2 * m[8] + tmp_5 * m[12]) -
- (tmp_0 * m[1 * 4] + tmp_3 * m[8] + tmp_4 * m[12])),
- d * ((tmp_0 * m[0 * 4] + tmp_7 * m[8] + tmp_8 * m[12]) -
- (tmp_1 * m[0 * 4] + tmp_6 * m[8] + tmp_9 * m[12])),
- d * ((tmp_3 * m[0 * 4] + tmp_6 * m[1 * 4] + tmp_11 * m[12]) -
- (tmp_2 * m[0 * 4] + tmp_7 * m[1 * 4] + tmp_10 * m[12])),
- d * ((tmp_4 * m[0 * 4] + tmp_9 * m[1 * 4] + tmp_10 * m[8]) -
- (tmp_5 * m[0 * 4] + tmp_8 * m[1 * 4] + tmp_11 * m[8])),
- d * ((tmp_12 * m[4 + 3] + tmp_15 * m[11] + tmp_16 * m[15]) -
- (tmp_13 * m[4 + 3] + tmp_14 * m[11] + tmp_17 * m[15])),
- d * ((tmp_13 * m[3] + tmp_18 * m[11] + tmp_21 * m[15]) -
- (tmp_12 * m[3] + tmp_19 * m[11] + tmp_20 * m[15])),
- d * ((tmp_14 * m[3] + tmp_19 * m[7] + tmp_22 * m[15]) -
- (tmp_15 * m[3] + tmp_18 * m[7] + tmp_23 * m[15])),
- d * ((tmp_17 * m[3] + tmp_20 * m[7] + tmp_23 * m[11]) -
- (tmp_16 * m[3] + tmp_21 * m[7] + tmp_22 * m[11])),
- d * ((tmp_14 * m[10] + tmp_17 * m[14] + tmp_13 * m[4 + 2]) -
- (tmp_16 * m[14] + tmp_12 * m[4 + 2] + tmp_15 * m[10])),
- d * ((tmp_20 * m[14] + tmp_12 * m[2] + tmp_19 * m[10]) -
- (tmp_18 * m[10] + tmp_21 * m[14] + tmp_13 * m[2])),
- d * ((tmp_18 * m[6] + tmp_23 * m[14] + tmp_15 * m[2]) -
- (tmp_22 * m[14] + tmp_14 * m[2] + tmp_19 * m[6])),
- d * ((tmp_22 * m[10] + tmp_16 * m[2] + tmp_21 * m[6]) -
- (tmp_20 * m[6] + tmp_23 * m[10] + tmp_17 * m[2])));
-};
-
-/**
- * Computes the determinant of the cofactor matrix obtained by removal
- * of a specified row and column. This is a helper function for the general
- * determinant and matrix inversion functions.
- * @param {!o3djs.flat_math.Matrix} a The original matrix.
- * @param {number} x The row to be removed.
- * @param {number} y The column to be removed.
- * @return {number} The determinant of the matrix obtained by removing
- * row x and column y from a.
- */
-o3djs.flat_math.codet = function(a, x, y) {
- var aLength = a.length;
- var size;
- switch (aLength) {
- case 4:
- size = 2;
- break;
- case 9:
- size = 3;
- break;
- case 16:
- size = 4;
- break;
- default:
- size=Math.sqrt(aLength);
- if (Math.round(size) * Math.round(size) != aLength) {
- throw "Calling codet on nonsquare matrix";
- }
- }
- var b = new o3djs.flat_math.Matrix(aLength);
- var ai = 0;
- for (var bi = 0; bi < size - 1; ++bi) {
- if (ai == x)
- ai++;
- var aj = 0;
- for (var bj = 0; bj < size - 1; ++bj) {
- if (aj == y)
- aj++;
- b[bi*size+bj] = a[ai*size+aj];
- aj++;
- }
- ai++;
- }
- return o3djs.flat_math.det(b);
-};
-
-/**
- * Computes the determinant of an arbitrary square matrix.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {number} the determinant of m.
- */
-o3djs.flat_math.det = function(m) {
- var d = m.length;
- switch (d) {
- case 4:
- return o3djs.flat_math.det2(m);
- case 9:
- return o3djs.flat_math.det3(m);
- case 16:
- return o3djs.flat_math.det4(m);
- default:
- d = Math.sqrt(d);
- if (Math.round(d) * Math.round(d) != m.length) {
- throw "Calling det on nonsquare matrix";
- }
- break;
- }
- var r = 0.0;
- var sign = 1;
- var row = m;
- var mLength = m.length;
- for (var y = 0; y < mLength; y++) {
- r += sign * m[0] * o3djs.flat_math.codet(m, 0, y);
- sign *= -1;
- }
- return r;
-};
-
-/**
- * Computes the inverse of an arbitrary square matrix.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {!o3djs.flat_math.Matrix} The inverse of m.
- */
-o3djs.flat_math.inverse = function(m) {
- var d = m.length;
- switch (d) {
- case 4:
- return o3djs.flat_math.inverse2(m);
- case 9:
- return o3djs.flat_math.inverse3(m);
- case 16:
- return o3djs.flat_math.inverse4(m);
- default:
- d = Math.sqrt(d);
- if (Math.round(d) * Math.round(d) != m.length) {
- throw "Calling inverse on nonsquare matrix";
- }
- break;
- }
- var r = new o3djs.flat_math.Matrix(m.length);
- var size = m.length;
- var det = o3djs.flat_math.det(m);
- for (var j = 0; j < size; ++j) {
- for (var i = 0; i < size; ++i)
- r[j * d + i] =
- ((i + j) % 2 ? -1 : 1) * o3djs.flat_math.codet(m, i, j) / det;
- }
- return r;
-};
-
-/**
- * Performs Graham-Schmidt orthogonalization on the vectors which make up the
- * given matrix and returns the result in the rows of a new matrix. When
- * multiplying many orthogonal matrices together, errors can accumulate causing
- * the product to fail to be orthogonal. This function can be used to correct
- * that.
- * @param {!o3djs.flat_math.Matrix} m The matrix.
- * @return {!o3djs.flat_math.Matrix} A matrix whose rows are obtained from the
- * rows of m by the Graham-Schmidt process.
- */
-o3djs.flat_math.orthonormalize = function(m) {
- var d = m.length;
- var r = new o3djs.flat_math.Matrix(d);
- switch (d) {
- case 4:
- d = 2; break;
- case 9:
- d = 3; break;
- case 16:
- d = 4; break;
- default:
- d = Math.sqrt(d);
- if (Math.round(d) * Math.round(d) != m.length) {
- throw "Calling orthonormalize on nonsquare matrix";
- }
- break;
- }
- for (var i = 0; i < d; ++i) {
- var v = m.slice(i*d,i*d+d);
- for (var j = 0; j < i; ++j) {
- v = o3djs.flat_math.subVector(v, o3djs.flat_math.mulScalarVector(
- o3djs.flat_math.dot(r[j], v), r[j]));
- }
- var ri = o3djs.flat_math.normalize(v);
- for (var k = 0; k < d; ++ k) {
- r[i * d +k ] = ri[k];
- }
- }
- return r;
-};
-
-/**
- * Computes the inverse of a 4-by-4 matrix.
- * Note: It is faster to call this than o3djs.flat_math.inverse.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @return {!o3djs.flat_math.Matrix4} The inverse of m.
- */
-o3djs.flat_math.matrix4.inverse = function(m) {
- return o3djs.flat_math.inverse4(m);
-};
-
-/**
- * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4.
- * Note: It is faster to call this than o3djs.flat_math.mul.
- * @param {!o3djs.flat_math.Matrix4} a The matrix on the left.
- * @param {!o3djs.flat_math.Matrix4} b The matrix on the right.
- * @return {!o3djs.flat_math.Matrix4} The matrix product of a and b.
- */
-o3djs.flat_math.matrix4.mul = function(a, b) {
- return o3djs.flat_math.mulMatrixMatrix4(a, b);
-};
-
-/**
- * Computes the determinant of a 4-by-4 matrix.
- * Note: It is faster to call this than o3djs.flat_math.det.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @return {number} The determinant of m.
- */
-o3djs.flat_math.matrix4.det = function(m) {
- return o3djs.flat_math.det4(m);
-};
-
-/**
- * Copies a Matrix4.
- * Note: It is faster to call this than o3djs.flat_math.copy.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @return {!o3djs.flat_math.Matrix4} A copy of m.
- */
-o3djs.flat_math.matrix4.copy = function(m) {
- return o3djs.flat_math.copyMatrix(m);
-};
-
-/**
- * Sets the upper 3-by-3 block of matrix a to the upper 3-by-3 block of matrix
- * b; assumes that a and b are big enough to contain an upper 3-by-3 block.
- * @param {!o3djs.flat_math.Matrix4} a A matrix.
- * @param {!o3djs.flat_math.Matrix3} b A 3-by-3 matrix.
- * @return {!o3djs.flat_math.Matrix4} a once modified.
- */
-o3djs.flat_math.matrix4.setUpper3x3 = function(a, b) {
- a[0] = b[0];
- a[1] = b[1];
- a[2] = b[2];
- a[4] = b[4];
- a[5] = b[5];
- a[6] = b[6];
- a[8] = b[8];
- a[9] = b[9];
- a[10] = b[10];
-
- return a;
-};
-
-/**
- * Returns a 3-by-3 matrix mimicking the upper 3-by-3 block of m; assumes m
- * is big enough to contain an upper 3-by-3 block.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @return {!o3djs.flat_math.Matrix3} The upper 3-by-3 block of m.
- */
-o3djs.flat_math.matrix4.getUpper3x3 = function(m) {
- return o3djs.flat_math.makeMatrix3(
- m[0], m[1], m[2],
- m[4], m[5], m[6],
- m[8], m[9], m[10]);
-};
-
-/**
- * Sets the translation component of a 4-by-4 matrix to the given
- * vector.
- * @param {!o3djs.flat_math.Matrix4} a The matrix.
- * @param {(!o3djs.flat_math.Vector3|!o3djs.flat_math.Vector4)} v The vector.
- * @return {!o3djs.flat_math.Matrix4} a once modified.
- */
-o3djs.flat_math.matrix4.setTranslation = function(a, v) {
- a[12] = v[0];
- a[13] = v[1];
- a[14] = v[2];
- return a;
-};
-
-/**
- * Returns the translation component of a 4-by-4 matrix as a vector with 3
- * entries.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @return {!o3djs.flat_math.Vector3} The translation component of m.
- */
-o3djs.flat_math.matrix4.getTranslation = function(m) {
- var retval =new o3djs.flat_math.Vector(3);
- retval[0] = m[12];
- retval[1] = m[13];
- retval[2] = m[14];
- return retval;
-};
-
-/**
- * Takes a 4-by-4 matrix and a vector with 3 entries,
- * interprets the vector as a point, transforms that point by the matrix, and
- * returns the result as a vector with 3 entries.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @param {!o3djs.flat_math.Vector3} v The point.
- * @return {!o3djs.flat_math.Vector3} The transformed point.
- */
-o3djs.flat_math.matrix4.transformPoint = function(m, v) {
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
-
- var d = v0 * m[3] +
- v1 * m[7] +
- v2 * m[11] +
- m[15];
- var retval = new o3djs.flat_math.Vector(3);
- retval[0] = (v0 * m[0] +
- v1 * m[4] +
- v2 * m[8] +
- m[12]) / d;
- retval[1] = (v0 * m[1] +
- v1 * m[5] +
- v2 * m[9] +
- m[13]) / d;
- retval[2] = (v0 * m[2] +
- v1 * m[6] +
- v2 * m[10] +
- m[14]) / d;
- return retval;
-};
-
-/**
- * Takes a 4-by-4 matrix and a vector with 4 entries, transforms that vector by
- * the matrix, and returns the result as a vector with 4 entries.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @param {!o3djs.flat_math.Vector4} v The point in homogenous coordinates.
- * @return {!o3djs.flat_math.Vector4} The transformed point in homogenous
- * coordinates.
- */
-o3djs.flat_math.matrix4.transformVector4 = function(m, v) {
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
- var v3 = v[3];
-
- return [v0 * m[0] +
- v1 * m[4] +
- v2 * m[8] +
- v3 * m[12],
- v0 * m[1] +
- v1 * m[5] +
- v2 * m[9] +
- v3 * m[13],
- v0 * m[2] +
- v1 * m[6] +
- v2 * m[10] +
- v3 * m[14],
- v0 * m[3] +
- v1 * m[7] +
- v2 * m[11] +
- v3 * m[15]];
-};
-
-/**
- * Takes a 4-by-4 matrix and a vector with 3 entries, interprets the vector as a
- * direction, transforms that direction by the matrix, and returns the result;
- * assumes the transformation of 3-dimensional space represented by the matrix
- * is parallel-preserving, i.e. any combination of rotation, scaling and
- * translation, but not a perspective distortion. Returns a vector with 3
- * entries.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @param {!o3djs.flat_math.Vector3} v The direction.
- * @return {!o3djs.flat_math.Vector3} The transformed direction.
- */
-o3djs.flat_math.matrix4.transformDirection = function(m, v) {
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
-
- return [v0 * m[0] +
- v1 * m[4] +
- v2 * m[8],
- v0 * m[1] +
- v1 * m[5] +
- v2 * m[9],
- v0 * m[2] +
- v1 * m[6] +
- v2 * m[10]];
-};
-
-/**
- * Takes a 4-by-4 matrix m and a vector v with 3 entries, interprets the vector
- * as a normal to a surface, and computes a vector which is normal upon
- * transforming that surface by the matrix. The effect of this function is the
- * same as transforming v (as a direction) by the inverse-transpose of m. This
- * function assumes the transformation of 3-dimensional space represented by the
- * matrix is parallel-preserving, i.e. any combination of rotation, scaling and
- * translation, but not a perspective distortion. Returns a vector with 3
- * entries.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @param {!o3djs.flat_math.Vector3} v The normal.
- * @return {!o3djs.flat_math.Vector3} The transformed normal.
- */
-o3djs.flat_math.matrix4.transformNormal = function(m, v) {
- var mInverse = o3djs.flat_math.inverse4(m);
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
-
- return [v0 * mInverse[0] + v1 * mInverse[1] + v2 * mInverse[2],
- v0 * mInverse[4] +
- v1 * mInverse[5] +
- v2 * mInverse[6],
- v0 * mInverse[8] +
- v1 * mInverse[9] +
- v2 * mInverse[10]];
-};
-
-/**
- * Creates a 4-by-4 identity matrix.
- * @return {!o3djs.flat_math.Matrix4} The 4-by-4 identity.
- */
-o3djs.flat_math.matrix4.identity = function() {
- return o3djs.flat_math.makeMatrix4(
- 1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
-};
-
-/**
- * Sets the given 4-by-4 matrix to the identity matrix.
- * @param {!o3djs.flat_math.Matrix4} m The matrix to set to identity.
- * @return {!o3djs.flat_math.Matrix4} m once modified.
- */
-o3djs.flat_math.matrix4.setIdentity = function(m) {
- for (var i = 0; i < 4; i++) {
- for (var j = 0; j < 4; j++) {
- if (i == j) {
- m[i * 4 + j] = 1;
- } else {
- m[i * 4 + j] = 0;
- }
- }
- }
- return m;
-};
-
-/**
- * Computes a 4-by-4 perspective transformation matrix given the angular height
- * of the frustum, the aspect ratio, and the near and far clipping planes. The
- * arguments define a frustum extending in the negative z direction. The given
- * angle is the vertical angle of the frustum, and the horizontal angle is
- * determined to produce the given aspect ratio. The arguments near and far are
- * the distances to the near and far clipping planes. Note that near and far
- * are not z coordinates, but rather they are distances along the negative
- * z-axis. The matrix generated sends the viewing frustum to the unit box.
- * We assume a unit box extending from -1 to 1 in the x and y dimensions and
- * from 0 to 1 in the z dimension.
- * @param {number} angle The camera angle from top to bottom (in radians).
- * @param {number} aspect The aspect ratio width / height.
- * @param {number} near The depth (negative z coordinate)
- * of the near clipping plane.
- * @param {number} far The depth (negative z coordinate)
- * of the far clipping plane.
- * @return {!o3djs.flat_math.Matrix4} The perspective matrix.
- */
-o3djs.flat_math.matrix4.perspective = function(angle, aspect, near, far) {
- var f = Math.tan(0.5 * (Math.PI - angle));
- var range = near - far;
-
- return o3djs.flat_math.makeMatrix4 (
- f / aspect, 0, 0, 0,
- 0, f, 0, 0,
- 0, 0, 2 * far / range + 1, -1,
- 0, 0, 2 * near * far / range, 0
- );
-};
-
-/**
- * Computes a 4-by-4 orthographic projection matrix given the coordinates of the
- * planes defining the axis-aligned, box-shaped viewing volume. The matrix
- * generated sends that box to the unit box. Note that although left and right
- * are x coordinates and bottom and top are y coordinates, near and far
- * are not z coordinates, but rather they are distances along the negative
- * z-axis. We assume a unit box extending from -1 to 1 in the x and y
- * dimensions and from 0 to 1 in the z dimension.
- * @param {number} left The x coordinate of the left plane of the box.
- * @param {number} right The x coordinate of the right plane of the box.
- * @param {number} bottom The y coordinate of the bottom plane of the box.
- * @param {number} top The y coordinate of the right plane of the box.
- * @param {number} near The negative z coordinate of the near plane of the box.
- * @param {number} far The negative z coordinate of the far plane of the box.
- * @return {!o3djs.flat_math.Matrix4} The orthographic projection matrix.
- */
-o3djs.flat_math.matrix4.orthographic =
- function(left, right, bottom, top, near, far) {
- return o3djs.flat_math.makeMatrix4 (
- 2 / (right - left), 0, 0, 0,
- 0, 2 / (top - bottom), 0, 0,
- 0, 0, 2 / (near - far), 0,
- (left + right) / (left - right),
- (bottom + top) / (bottom - top),
- (near + far) / (near - far), 1);
-};
-
-/**
- * Computes a 4-by-4 perspective transformation matrix given the left, right,
- * top, bottom, near and far clipping planes. The arguments define a frustum
- * extending in the negative z direction. The arguments near and far are the
- * distances to the near and far clipping planes. Note that near and far are not
- * z coordinates, but rather they are distances along the negative z-axis. The
- * matrix generated sends the viewing frustum to the unit box. We assume a unit
- * box extending from -1 to 1 in the x and y dimensions and from 0 to 1 in the z
- * dimension.
- * @param {number} left The x coordinate of the left plane of the box.
- * @param {number} right The x coordinate of the right plane of the box.
- * @param {number} bottom The y coordinate of the bottom plane of the box.
- * @param {number} top The y coordinate of the right plane of the box.
- * @param {number} near The negative z coordinate of the near plane of the box.
- * @param {number} far The negative z coordinate of the far plane of the box.
- * @return {!o3djs.flat_math.Matrix4} The perspective projection matrix.
- */
-o3djs.flat_math.matrix4.frustum = function(left, right, bottom, top, near, far) {
- var dx = (right - left);
- var dy = (top - bottom);
- var dz = (near - far);
- return o3djs.flat_math.makeMatrix4(
- 2 * near / dx, 0, 0, 0,
- 0, 2 * near / dy, 0, 0,
- (left + right) / dx, (top + bottom) / dy, far / dz, -1,
- 0, 0, near * far / dz, 0);
-};
-
-/**
- * Computes a 4-by-4 look-at transformation. The transformation generated is
- * an orthogonal rotation matrix with translation component. The translation
- * component sends the eye to the origin. The rotation component sends the
- * vector pointing from the eye to the target to a vector pointing in the
- * negative z direction, and also sends the up vector into the upper half of
- * the yz plane.
- * @param {(!o3djs.flat_math.Vector3|!o3djs.flat_math.Vector4)} eye The position
- * of the eye.
- * @param {(!o3djs.flat_math.Vector3|!o3djs.flat_math.Vector4)} target The
- * position meant to be viewed.
- * @param {(!o3djs.flat_math.Vector3|!o3djs.flat_math.Vector4)} up A vector
- * pointing up.
- * @return {!o3djs.flat_math.Matrix4} The look-at matrix.
- */
-o3djs.flat_math.matrix4.lookAt = function(eye, target, up) {
- var vz = o3djs.flat_math.normalize(
- o3djs.flat_math.subVector(eye, target).slice(0, 3));
- var vx = o3djs.flat_math.normalize(
- o3djs.flat_math.cross(up, vz));
- var vy = o3djs.flat_math.cross(vz, vx);
- return o3djs.flat_math.inverse4(o3djs.flat_math.makeMatrix4(
- vx[0], vx[1], vx[2], 0,
- vy[0], vy[1], vy[2], 0,
- vz[0], vz[1], vz[2], 0,
- eye[0], eye[1], eye[2], 1));
-};
-
-/**
- * Takes two 4-by-4 matrices, a and b, and computes the product in the order
- * that pre-composes b with a. In other words, the matrix returned will
- * transform by b first and then a. Note this is subtly different from just
- * multiplying the matrices together. For given a and b, this function returns
- * the same object in both row-major and column-major mode.
- * @param {!o3djs.flat_math.Matrix4} a A 4-by-4 matrix.
- * @param {!o3djs.flat_math.Matrix4} b A 4-by-4 matrix.
- * @return {!o3djs.flat_math.Matrix4} the composition of a and b, b first then a.
- */
-o3djs.flat_math.matrix4.composition = function(a, b) {
- var a00 = a[0];
- var a01 = a[1];
- var a02 = a[2];
- var a03 = a[3];
- var a10 = a[4];
- var a11 = a[5];
- var a12 = a[6];
- var a13 = a[7];
- var a20 = a[8];
- var a21 = a[9];
- var a22 = a[10];
- var a23 = a[11];
- var a30 = a[12];
- var a31 = a[13];
- var a32 = a[14];
- var a33 = a[15];
- var b00 = b[0];
- var b01 = b[1];
- var b02 = b[2];
- var b03 = b[3];
- var b10 = b[4];
- var b11 = b[5];
- var b12 = b[6];
- var b13 = b[7];
- var b20 = b[8];
- var b21 = b[9];
- var b22 = b[10];
- var b23 = b[11];
- var b30 = b[12];
- var b31 = b[13];
- var b32 = b[14];
- var b33 = b[15];
- return o3djs.flat_math.makeMatrix(
- a00 * b00 + a10 * b01 + a20 * b02 + a30 * b03,
- a01 * b00 + a11 * b01 + a21 * b02 + a31 * b03,
- a02 * b00 + a12 * b01 + a22 * b02 + a32 * b03,
- a03 * b00 + a13 * b01 + a23 * b02 + a33 * b03,
- a00 * b10 + a10 * b11 + a20 * b12 + a30 * b13,
- a01 * b10 + a11 * b11 + a21 * b12 + a31 * b13,
- a02 * b10 + a12 * b11 + a22 * b12 + a32 * b13,
- a03 * b10 + a13 * b11 + a23 * b12 + a33 * b13,
- a00 * b20 + a10 * b21 + a20 * b22 + a30 * b23,
- a01 * b20 + a11 * b21 + a21 * b22 + a31 * b23,
- a02 * b20 + a12 * b21 + a22 * b22 + a32 * b23,
- a03 * b20 + a13 * b21 + a23 * b22 + a33 * b23,
- a00 * b30 + a10 * b31 + a20 * b32 + a30 * b33,
- a01 * b30 + a11 * b31 + a21 * b32 + a31 * b33,
- a02 * b30 + a12 * b31 + a22 * b32 + a32 * b33,
- a03 * b30 + a13 * b31 + a23 * b32 + a33 * b33);
-};
-
-/**
- * Takes two 4-by-4 matrices, a and b, and modifies a to be the product in the
- * order that pre-composes b with a. The matrix a, upon modification will
- * transform by b first and then a. Note this is subtly different from just
- * multiplying the matrices together. For given a and b, a, upon modification,
- * will be the same object in both row-major and column-major mode.
- * @param {!o3djs.flat_math.Matrix4} a A 4-by-4 matrix.
- * @param {!o3djs.flat_math.Matrix4} b A 4-by-4 matrix.
- * @return {!o3djs.flat_math.Matrix4} a once modified.
- */
-o3djs.flat_math.matrix4.compose = function(a, b) {
- var a00 = a[0];
- var a01 = a[1];
- var a02 = a[2];
- var a03 = a[3];
- var a10 = a[4];
- var a11 = a[5];
- var a12 = a[6];
- var a13 = a[7];
- var a20 = a[8];
- var a21 = a[9];
- var a22 = a[10];
- var a23 = a[11];
- var a30 = a[12];
- var a31 = a[13];
- var a32 = a[14];
- var a33 = a[15];
- var b00 = b[0];
- var b01 = b[1];
- var b02 = b[2];
- var b03 = b[3];
- var b10 = b[4];
- var b11 = b[5];
- var b12 = b[6];
- var b13 = b[7];
- var b20 = b[8];
- var b21 = b[9];
- var b22 = b[10];
- var b23 = b[11];
- var b30 = b[12];
- var b31 = b[13];
- var b32 = b[14];
- var b33 = b[15];
- a[0] = a00 * b00 + a10 * b01 + a20 * b02 + a30 * b03;
- a[1] = a01 * b00 + a11 * b01 + a21 * b02 + a31 * b03;
- a[2] = a02 * b00 + a12 * b01 + a22 * b02 + a32 * b03;
- a[3] = a03 * b00 + a13 * b01 + a23 * b02 + a33 * b03;
- a[4] = a00 * b10 + a10 * b11 + a20 * b12 + a30 * b13;
- a[5] = a01 * b10 + a11 * b11 + a21 * b12 + a31 * b13;
- a[6] = a02 * b10 + a12 * b11 + a22 * b12 + a32 * b13;
- a[7] = a03 * b10 + a13 * b11 + a23 * b12 + a33 * b13;
- a[8] = a00 * b20 + a10 * b21 + a20 * b22 + a30 * b23;
- a[9] = a01 * b20 + a11 * b21 + a21 * b22 + a31 * b23;
- a[10] = a02 * b20 + a12 * b21 + a22 * b22 + a32 * b23;
- a[11] = a03 * b20 + a13 * b21 + a23 * b22 + a33 * b23;
- a[12] = a00 * b30 + a10 * b31 + a20 * b32 + a30 * b33;
- a[13] = a01 * b30 + a11 * b31 + a21 * b32 + a31 * b33;
- a[14] = a02 * b30 + a12 * b31 + a22 * b32 + a32 * b33;
- a[15] = a03 * b30 + a13 * b31 + a23 * b32 + a33 * b33;
- return a;
-};
-
-/**
- * Creates a 4-by-4 matrix which translates by the given vector v.
- * @param {(!o3djs.flat_math.Vector3|!o3djs.flat_math.Vector4)} v The vector by
- * which to translate.
- * @return {!o3djs.flat_math.Matrix4} The translation matrix.
- */
-o3djs.flat_math.matrix4.translation = function(v) {
- return o3djs.flat_math.makeMatrix4(
- 1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 1, 0,
- v[0], v[1], v[2], 1);
-};
-
-/**
- * Modifies the given 4-by-4 matrix by translation by the given vector v.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @param {(!o3djs.flat_math.Vector3|!o3djs.flat_math.Vector4)} v The vector by
- * which to translate.
- * @return {!o3djs.flat_math.Matrix4} m once modified.
- */
-o3djs.flat_math.matrix4.translate = function(m, v) {
- var m00 = m[0];
- var m01 = m[1];
- var m02 = m[2];
- var m03 = m[3];
- var m10 = m[4];
- var m11 = m[5];
- var m12 = m[6];
- var m13 = m[7];
- var m20 = m[8];
- var m21 = m[9];
- var m22 = m[10];
- var m23 = m[11];
- var m30 = m[12];
- var m31 = m[13];
- var m32 = m[14];
- var m33 = m[15];
-
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
- var v3 = v[3];
-
- m[12] = m00 * v0 + m10 * v1 + m20 * v2 + m30;
- m[13] = m01 * v0 + m11 * v1 + m21 * v2 + m31;
- m[14] = m02 * v0 + m12 * v1 + m22 * v2 + m32;
- m[15] = m03 * v0 + m13 * v1 + m23 * v2 + m33;
-
- return m;
-};
-
-/**
- * Creates a 4-by-4 matrix which scales in each dimension by an amount given by
- * the corresponding entry in the given vector; assumes the vector has three
- * entries.
- * @param {!o3djs.flat_math.Vector3} v A vector of
- * three entries specifying the factor by which to scale in each dimension.
- * @return {!o3djs.flat_math.Matrix4} The scaling matrix.
- */
-o3djs.flat_math.matrix4.scaling = function(v) {
- return o3djs.flat_math.makeMatrix(
- v[0], 0, 0, 0,
- 0, v[1], 0, 0,
- 0, 0, v[2], 0,
- 0, 0, 0, 1
- );
-};
-
-/**
- * Modifies the given 4-by-4 matrix, scaling in each dimension by an amount
- * given by the corresponding entry in the given vector; assumes the vector has
- * three entries.
- * @param {!o3djs.flat_math.Matrix4} m The matrix to be modified.
- * @param {!o3djs.flat_math.Vector3} v A vector of three entries specifying the
- * factor by which to scale in each dimension.
- * @return {!o3djs.flat_math.Matrix4} m once modified.
- */
-o3djs.flat_math.matrix4.scale = function(m, v) {
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
-
- for (var i = 0; i < 4; ++i) {
- m[i] *= v0;
- m[4 + i] *= v1;
- m[8 + i] *= v2;
- }
-
- return m;
-};
-
-/**
- * Creates a 4-by-4 matrix which rotates around the x-axis by the given angle.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.flat_math.Matrix4} The rotation matrix.
- */
-o3djs.flat_math.matrix4.rotationX = function(angle) {
- var c = Math.cos(angle);
- var s = Math.sin(angle);
-
- return o3djs.flat_math.makeMatrix(
- 1, 0, 0, 0,
- 0, c, s, 0,
- 0, -s, c, 0,
- 0, 0, 0, 1);
-};
-
-/**
- * Modifies the given 4-by-4 matrix by a rotation around the x-axis by the given
- * angle.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.flat_math.Matrix4} m once modified.
- */
-o3djs.flat_math.matrix4.rotateX = function(m, angle) {
- var m10 = m[4];
- var m11 = m[5];
- var m12 = m[6];
- var m13 = m[7];
- var m20 = m[8];
- var m21 = m[9];
- var m22 = m[10];
- var m23 = m[11];
- var c = Math.cos(angle);
- var s = Math.sin(angle);
-
- m[4] = c * m10 + s * m20;
- m[5] = c * m11 + s * m21;
- m[6] = c * m12 + s * m22;
- m[7] = c * m13 + s * m23;
- m[8] = c * m20 - s * m10;
- m[9] = c * m21 - s * m11;
- m[10] = c * m22 - s * m12;
- m[11] = c * m23 - s * m13;
-
- return m;
-};
-
-/**
- * Creates a 4-by-4 matrix which rotates around the y-axis by the given angle.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.flat_math.Matrix4} The rotation matrix.
- */
-o3djs.flat_math.matrix4.rotationY = function(angle) {
- var c = Math.cos(angle);
- var s = Math.sin(angle);
-
- return o3djs.flat_math.makeMatrix(
- c, 0, -s, 0,
- 0, 1, 0, 0,
- s, 0, c, 0,
- 0, 0, 0, 1);
-};
-
-/**
- * Modifies the given 4-by-4 matrix by a rotation around the y-axis by the given
- * angle.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.flat_math.Matrix4} m once modified.
- */
-o3djs.flat_math.matrix4.rotateY = function(m, angle) {
- var m00 = m[0];
- var m01 = m[1];
- var m02 = m[2];
- var m03 = m[3];
- var m20 = m[8];
- var m21 = m[9];
- var m22 = m[10];
- var m23 = m[11];
- var c = Math.cos(angle);
- var s = Math.sin(angle);
-
- m[0] = c * m00 - s * m20;
- m[1] = c * m01 - s * m21;
- m[2] = c * m02 - s * m22;
- m[3] = c * m03 - s * m23;
- m[8] = c * m20 + s * m00;
- m[9] = c * m21 + s * m01;
- m[10] = c * m22 + s * m02;
- m[11] = c * m23 + s * m03;
-
- return m;
-};
-
-/**
- * Creates a 4-by-4 matrix which rotates around the z-axis by the given angle.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.flat_math.Matrix4} The rotation matrix.
- */
-o3djs.flat_math.matrix4.rotationZ = function(angle) {
- var c = Math.cos(angle);
- var s = Math.sin(angle);
-
- return o3djs.flat_math.makeMatrix(
- c, s, 0, 0,
- -s, c, 0, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
-};
-
-/**
- * Modifies the given 4-by-4 matrix by a rotation around the z-axis by the given
- * angle.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.flat_math.Matrix4} m once modified.
- */
-o3djs.flat_math.matrix4.rotateZ = function(m, angle) {
- var m00 = m[0];
- var m01 = m[1];
- var m02 = m[2];
- var m03 = m[3];
- var m10 = m[4];
- var m11 = m[5];
- var m12 = m[6];
- var m13 = m[7];
- var c = Math.cos(angle);
- var s = Math.sin(angle);
-
- m[0] = c * m00 + s * m10;
- m[1] = c * m01 + s * m11;
- m[2] = c * m02 + s * m12;
- m[3] = c * m03 + s * m13;
- m[4] = c * m10 - s * m00;
- m[5] = c * m11 - s * m01;
- m[6] = c * m12 - s * m02;
- m[7] = c * m13 - s * m03;
-
- return m;
-};
-
-/**
- * Creates a 4-by-4 rotation matrix. Interprets the entries of the given
- * vector as angles by which to rotate around the x, y and z axes, returns a
- * a matrix which rotates around the x-axis first, then the y-axis, then the
- * z-axis.
- * @param {!o3djs.flat_math.Vector3} v A vector of angles (in radians).
- * @return {!o3djs.flat_math.Matrix4} The rotation matrix.
- */
-o3djs.flat_math.matrix4.rotationZYX = function(v) {
- var sinx = Math.sin(v[0]);
- var cosx = Math.cos(v[0]);
- var siny = Math.sin(v[1]);
- var cosy = Math.cos(v[1]);
- var sinz = Math.sin(v[2]);
- var cosz = Math.cos(v[2]);
-
- var coszsiny = cosz * siny;
- var sinzsiny = sinz * siny;
-
- return o3djs.flat_math.makeMatrix(
- cosz * cosy, sinz * cosy, -siny, 0, coszsiny * sinx - sinz * cosx,
- sinzsiny * sinx + cosz * cosx, cosy * sinx, 0,
- coszsiny * cosx + sinz * sinx, sinzsiny * cosx - cosz * sinx, cosy * cosx,
- 0, 0, 0, 0, 1);
-};
-
-/**
- * Modifies a 4-by-4 matrix by a rotation. Interprets the coordinates of the
- * given vector as angles by which to rotate around the x, y and z axes, rotates
- * around the x-axis first, then the y-axis, then the z-axis.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @param {!o3djs.flat_math.Vector3} v A vector of angles (in radians).
- * @return {!o3djs.flat_math.Matrix4} m once modified.
- */
-o3djs.flat_math.matrix4.rotateZYX = function(m, v) {
- var sinX = Math.sin(v[0]);
- var cosX = Math.cos(v[0]);
- var sinY = Math.sin(v[1]);
- var cosY = Math.cos(v[1]);
- var sinZ = Math.sin(v[2]);
- var cosZ = Math.cos(v[2]);
-
- var cosZSinY = cosZ * sinY;
- var sinZSinY = sinZ * sinY;
-
- var r00 = cosZ * cosY;
- var r01 = sinZ * cosY;
- var r02 = -sinY;
- var r10 = cosZSinY * sinX - sinZ * cosX;
- var r11 = sinZSinY * sinX + cosZ * cosX;
- var r12 = cosY * sinX;
- var r20 = cosZSinY * cosX + sinZ * sinX;
- var r21 = sinZSinY * cosX - cosZ * sinX;
- var r22 = cosY * cosX;
-
- var m00 = m[0];
- var m01 = m[1];
- var m02 = m[2];
- var m03 = m[3];
- var m10 = m[4];
- var m11 = m[5];
- var m12 = m[6];
- var m13 = m[7];
- var m20 = m[8];
- var m21 = m[9];
- var m22 = m[10];
- var m23 = m[11];
- var m30 = m[12];
- var m31 = m[13];
- var m32 = m[14];
- var m33 = m[15];
-
- m[0] = r00 * m00 + r01 * m10 + r02 * m20;
- m[1] = r00 * m01 + r01 * m11 + r02 * m21;
- m[2] = r00 * m02 + r01 * m12 + r02 * m22;
- m[3] = r00 * m03 + r01 * m13 + r02 * m23;
-
- m[4] = r10 * m00 + r11 * m10 + r12 * m20;
- m[5] = r10 * m01 + r11 * m11 + r12 * m21;
- m[6] = r10 * m02 + r11 * m12 + r12 * m22;
- m[7] = r10 * m03 + r11 * m13 + r12 * m23;
-
- m[8] = r20 * m00 + r21 * m10 + r22 * m20;
- m[9] = r20 * m01 + r21 * m11 + r22 * m21;
- m[10] = r20 * m02 + r21 * m12 + r22 * m22;
- m[11] = r20 * m03 + r21 * m13 + r22 * m23;
-
- return m;
-};
-
-/**
- * Creates a 4-by-4 matrix which rotates around the given axis by the given
- * angle.
- * @param {(!o3djs.flat_math.Vector3|!o3djs.flat_math.Vector4)} axis The axis
- * about which to rotate.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.flat_math.Matrix4} A matrix which rotates angle radians
- * around the axis.
- */
-o3djs.flat_math.matrix4.axisRotation = function(axis, angle) {
- var x = axis[0];
- var y = axis[1];
- var z = axis[2];
- var n = Math.sqrt(x * x + y * y + z * z);
- x /= n;
- y /= n;
- z /= n;
- var xx = x * x;
- var yy = y * y;
- var zz = z * z;
- var c = Math.cos(angle);
- var s = Math.sin(angle);
- var oneMinusCosine = 1 - c;
-
- return o3djs.flat_math.makeMatrix(
- xx + (1 - xx) * c,
- x * y * oneMinusCosine + z * s,
- x * z * oneMinusCosine - y * s,
- 0,
- x * y * oneMinusCosine - z * s,
- yy + (1 - yy) * c,
- y * z * oneMinusCosine + x * s,
- 0,
- x * z * oneMinusCosine + y * s,
- y * z * oneMinusCosine - x * s,
- zz + (1 - zz) * c,
- 0,
- 0, 0, 0, 1
- );
-};
-
-/**
- * Modifies the given 4-by-4 matrix by rotation around the given axis by the
- * given angle.
- * @param {!o3djs.flat_math.Matrix4} m The matrix.
- * @param {(!o3djs.flat_math.Vector3|!o3djs.flat_math.Vector4)} axis The axis
- * about which to rotate.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.flat_math.Matrix4} m once modified.
- */
-o3djs.flat_math.matrix4.axisRotate = function(m, axis, angle) {
- var x = axis[0];
- var y = axis[1];
- var z = axis[2];
- var n = Math.sqrt(x * x + y * y + z * z);
- x /= n;
- y /= n;
- z /= n;
- var xx = x * x;
- var yy = y * y;
- var zz = z * z;
- var c = Math.cos(angle);
- var s = Math.sin(angle);
- var oneMinusCosine = 1 - c;
-
- var r00 = xx + (1 - xx) * c;
- var r01 = x * y * oneMinusCosine + z * s;
- var r02 = x * z * oneMinusCosine - y * s;
- var r10 = x * y * oneMinusCosine - z * s;
- var r11 = yy + (1 - yy) * c;
- var r12 = y * z * oneMinusCosine + x * s;
- var r20 = x * z * oneMinusCosine + y * s;
- var r21 = y * z * oneMinusCosine - x * s;
- var r22 = zz + (1 - zz) * c;
-
- var m00 = m[0];
- var m01 = m[1];
- var m02 = m[2];
- var m03 = m[3];
- var m10 = m[4];
- var m11 = m[5];
- var m12 = m[6];
- var m13 = m[7];
- var m20 = m[8];
- var m21 = m[9];
- var m22 = m[10];
- var m23 = m[11];
- var m30 = m[12];
- var m31 = m[13];
- var m32 = m[14];
- var m33 = m[15];
-
- m[0] = r00 * m00 + r01 * m10 + r02 * m20;
- m[1] = r00 * m01 + r01 * m11 + r02 * m21;
- m[2] = r00 * m02 + r01 * m12 + r02 * m22;
- m[3] = r00 * m03 + r01 * m13 + r02 * m23;
-
- m[4] = r10 * m00 + r11 * m10 + r12 * m20;
- m[5] = r10 * m01 + r11 * m11 + r12 * m21;
- m[6] = r10 * m02 + r11 * m12 + r12 * m22;
- m[7] = r10 * m03 + r11 * m13 + r12 * m23;
-
- m[8] = r20 * m00 + r21 * m10 + r22 * m20;
- m[9] = r20 * m01 + r21 * m11 + r22 * m21;
- m[10] = r20 * m02 + r21 * m12 + r22 * m22;
- m[11] = r20 * m03 + r21 * m13 + r22 * m23;
-
- return m;
-};
-
-/**
- * Sets each function in the namespace o3djs.flat_math to the row major
- * version in o3djs.flat_math.rowMajor (provided such a function exists in
- * o3djs.flat_math.rowMajor). Call this function to establish the row major
- * convention.
- */
-o3djs.flat_math.installRowMajorFunctions = function() {
- for (var f in o3djs.flat_math.rowMajor) {
- o3djs.flat_math[f] = o3djs.flat_math.rowMajor[f];
- }
-};
-
-/**
- * Sets each function in the namespace o3djs.flat_math to the column major
- * version in o3djs.flat_math.columnMajor (provided such a function exists in
- * o3djs.flat_math.columnMajor). Call this function to establish the column
- * major convention.
- */
-o3djs.flat_math.installColumnMajorFunctions = function() {
- for (var f in o3djs.flat_math.columnMajor) {
- o3djs.flat_math[f] = o3djs.flat_math.columnMajor[f];
- }
-};
-
-/**
- * Sets each function in the namespace o3djs.flat_math to the error checking
- * version in o3djs.flat_math.errorCheck (provided such a function exists in
- * o3djs.flat_math.errorCheck).
- */
-o3djs.flat_math.installErrorCheckFunctions = function() {
- for (var f in o3djs.flat_math.errorCheck) {
- o3djs.flat_math[f] = o3djs.flat_math.errorCheck[f];
- }
-};
-
-/**
- * Sets each function in the namespace o3djs.flat_math to the error checking free
- * version in o3djs.flat_math.errorCheckFree (provided such a function exists in
- * o3djs.flat_math.errorCheckFree).
- */
-o3djs.flat_math.installErrorCheckFreeFunctions = function() {
- for (var f in o3djs.flat_math.errorCheckFree) {
- o3djs.flat_math[f] = o3djs.flat_math.errorCheckFree[f];
- }
-};
-
-// By default, install the row-major functions.
-o3djs.flat_math.installRowMajorFunctions();
-
-// By default, install prechecking.
-o3djs.flat_math.installErrorCheckFunctions();
-
-if (!use_plugin_math) {
- for (var f in o3djs.flat_math) {
- o3djs.math[f] = o3djs.flat_math[f];
- }
-
- /**
- * True if we are using the plugin math library in which matrices are
- * represented by 2-dimensional arrays.
- * @type {boolean}
- * @private
- */
- o3djs.math.usePluginMath_ = false;
-}
-
-
diff --git a/o3d/samples/o3djs/pack.js b/o3d/samples/o3djs/pack.js
deleted file mode 100644
index 183b315..0000000
--- a/o3d/samples/o3djs/pack.js
+++ /dev/null
@@ -1,71 +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.
- */
-
-
-/**
- * @fileoverview This file contains various functions for helping setup
- * packs for o3d. It puts them in the "pack" module on the o3djs
- * object.
- *
- * Note: This library is only a sample. It is not meant to be some official
- * library. It is provided only as example code.
- *
- */
-
-o3djs.provide('o3djs.pack');
-
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.shape');
-
-/**
- * A Module with utilities for dealing with packs..
- * @namespace
- */
-o3djs.pack = o3djs.pack || {};
-
-/**
- * Prepares a pack for rendering.
- *
- * @param {!o3d.Pack} pack Pack to prepare.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo as returned from
- * o3djs.rendergraph.createView.
- * @param {!o3d.Pack} opt_effectPack Pack to create effects in. If this is
- * not specifed the pack to prepare above will be used.
- * @param {Object} opt_options Extra options for effect.getStandardShader
- *
- * @see o3djs.material.prepareMaterials
- * @see o3djs.shape.prepareShapes
- */
-o3djs.pack.preparePack = function(pack, viewInfo, opt_effectPack, opt_options) {
- o3djs.material.prepareMaterials(pack, viewInfo, opt_effectPack, opt_options);
- o3djs.shape.prepareShapes(pack);
-};
-
diff --git a/o3d/samples/o3djs/particles.js b/o3d/samples/o3djs/particles.js
deleted file mode 100644
index 3874e30..0000000
--- a/o3d/samples/o3djs/particles.js
+++ /dev/null
@@ -1,1510 +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.
- */
-
-
-/**
- * @fileoverview This file contains various functions and classes for rendering
- * gpu based particles.
- *
- * TODO: Add 3d oriented particles.
- */
-
-o3djs.provide('o3djs.particles');
-
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.math');
-
-/**
- * A Module with various GPU particle functions and classes.
- * Note: GPU particles have the issue that they are not sorted per particle
- * but rather per emitter.
- * @namespace
- */
-o3djs.particles = o3djs.particles || {};
-
-/**
- * Enum for pre-made particle states.
- * @enum
- */
-o3djs.particles.ParticleStateIds = {
- BLEND: 0,
- ADD: 1,
- BLEND_PREMULTIPLY: 2,
- BLEND_NO_ALPHA: 3,
- SUBTRACT: 4,
- INVERSE: 5};
-
-/**
- * Particle Effect strings
- * @type {!Array.<{name: string, fxString: string}>}
- */
-o3djs.particles.FX_STRINGS_CG = [
- { name: 'particle3d', fxString: '' +
- 'float4x4 worldViewProjection : WORLDVIEWPROJECTION;\n' +
- 'float4x4 world : WORLD;\n' +
- 'float3 worldVelocity;\n' +
- 'float3 worldAcceleration;\n' +
- 'float timeRange;\n' +
- 'float time;\n' +
- 'float timeOffset;\n' +
- 'float frameDuration;\n' +
- 'float numFrames;\n' +
- '\n' +
- '// We need to implement 1D!\n' +
- 'sampler rampSampler;\n' +
- 'sampler colorSampler;\n' +
- '\n' +
- 'struct VertexShaderInput {\n' +
- ' float4 uvLifeTimeFrameStart : POSITION; // uv, lifeTime, frameStart\n' +
- ' float4 positionStartTime : TEXCOORD0; // position.xyz, startTime\n' +
- ' float4 velocityStartSize : TEXCOORD1; // velocity.xyz, startSize\n' +
- ' float4 accelerationEndSize : TEXCOORD2; // acceleration.xyz, endSize\n' +
- ' float4 spinStartSpinSpeed : TEXCOORD3; // spinStart.x, spinSpeed.y\n' +
- ' float4 orientation : TEXCOORD4; // orientation\n' +
- ' float4 colorMult : COLOR; //\n' +
- '};\n' +
- '\n' +
- 'struct PixelShaderInput {\n' +
- ' float4 position : POSITION;\n' +
- ' float2 texcoord : TEXCOORD0;\n' +
- ' float1 percentLife : TEXCOORD1;\n' +
- ' float4 colorMult: TEXCOORD2;\n' +
- '};\n' +
- '\n' +
- 'PixelShaderInput vertexShaderFunction(VertexShaderInput input) {\n' +
- ' PixelShaderInput output;\n' +
- '\n' +
- ' float2 uv = input.uvLifeTimeFrameStart.xy;\n' +
- ' float lifeTime = input.uvLifeTimeFrameStart.z;\n' +
- ' float frameStart = input.uvLifeTimeFrameStart.w;\n' +
- ' float3 position = input.positionStartTime.xyz;\n' +
- ' float startTime = input.positionStartTime.w;\n' +
- ' float3 velocity = mul(float4(input.velocityStartSize.xyz, 0),\n' +
- ' world).xyz + worldVelocity;\n' +
- ' float startSize = input.velocityStartSize.w;\n' +
- ' float3 acceleration = mul(float4(input.accelerationEndSize.xyz, 0),\n' +
- ' world).xyz + worldAcceleration;\n' +
- ' float endSize = input.accelerationEndSize.w;\n' +
- ' float spinStart = input.spinStartSpinSpeed.x;\n' +
- ' float spinSpeed = input.spinStartSpinSpeed.y;\n' +
- '\n' +
- ' float localTime = fmod((time - timeOffset - startTime), timeRange);\n' +
- ' float percentLife = localTime / lifeTime;\n' +
- '\n' +
- ' float frame = fmod(floor(localTime / frameDuration + frameStart),\n' +
- ' numFrames);\n' +
- ' float uOffset = frame / numFrames;\n' +
- ' float u = uOffset + (uv.x + 0.5) * (1 / numFrames);\n' +
- '\n' +
- ' output.texcoord = float2(u, uv.y + 0.5);\n' +
- ' output.colorMult = input.colorMult;\n' +
- '\n' +
- ' float size = lerp(startSize, endSize, percentLife);\n' +
- ' size = (percentLife < 0 || percentLife > 1) ? 0 : size;\n' +
- ' float s = sin(spinStart + spinSpeed * localTime);\n' +
- ' float c = cos(spinStart + spinSpeed * localTime);\n' +
- '\n' +
- ' float4 rotatedPoint = float4((uv.x * c + uv.y * s) * size, 0,\n' +
- ' (uv.x * s - uv.y * c) * size, 1);\n' +
- ' float3 center = velocity * localTime +\n' +
- ' acceleration * localTime * localTime + \n' +
- ' position;\n' +
- ' \n' +
- ' float4 q2 = input.orientation + input.orientation;\n' +
- ' float4 qx = input.orientation.xxxw * q2.xyzx;\n' +
- ' float4 qy = input.orientation.xyyw * q2.xyzy;\n' +
- ' float4 qz = input.orientation.xxzw * q2.xxzz;\n' +
- ' \n' +
- ' float4x4 localMatrix = float4x4(\n' +
- ' (1.0f - qy.y) - qz.z, \n' +
- ' qx.y + qz.w, \n' +
- ' qx.z - qy.w,\n' +
- ' 0,\n' +
- ' \n' +
- ' qx.y - qz.w, \n' +
- ' (1.0f - qx.x) - qz.z, \n' +
- ' qy.z + qx.w,\n' +
- ' 0,\n' +
- ' \n' +
- ' qx.z + qy.w, \n' +
- ' qy.z - qx.w, \n' +
- ' (1.0f - qx.x) - qy.y,\n' +
- ' 0,\n' +
- ' \n' +
- ' center.x, center.y, center.z, 1);\n' +
- ' rotatedPoint = mul(rotatedPoint, localMatrix);\n' +
- ' output.position = mul(rotatedPoint, worldViewProjection);\n' +
- ' output.percentLife = percentLife;\n' +
- ' return output;\n' +
- '}\n' +
- '\n' +
- 'float4 pixelShaderFunction(PixelShaderInput input): COLOR {\n' +
- ' float4 colorMult = tex2D(rampSampler, \n' +
- ' float2(input.percentLife, 0.5)) *\n' +
- ' input.colorMult;\n' +
- ' float4 color = tex2D(colorSampler, input.texcoord) * colorMult;\n' +
- ' return color;\n' +
- '}\n' +
- '\n' +
- '// #o3d VertexShaderEntryPoint vertexShaderFunction\n' +
- '// #o3d PixelShaderEntryPoint pixelShaderFunction\n' +
- '// #o3d MatrixLoadOrder RowMajor\n'},
- { name: 'particle2d', fxString: '' +
- 'float4x4 viewProjection : VIEWPROJECTION;\n' +
- 'float4x4 world : WORLD;\n' +
- 'float4x4 viewInverse : VIEWINVERSE;\n' +
- 'float3 worldVelocity;\n' +
- 'float3 worldAcceleration;\n' +
- 'float timeRange;\n' +
- 'float time;\n' +
- 'float timeOffset;\n' +
- 'float frameDuration;\n' +
- 'float numFrames;\n' +
- '\n' +
- '// We need to implement 1D!\n' +
- 'sampler rampSampler;\n' +
- 'sampler colorSampler;\n' +
- '\n' +
- 'struct VertexShaderInput {\n' +
- ' float4 uvLifeTimeFrameStart : POSITION; // uv, lifeTime, frameStart\n' +
- ' float4 positionStartTime : TEXCOORD0; // position.xyz, startTime\n' +
- ' float4 velocityStartSize : TEXCOORD1; // velocity.xyz, startSize\n' +
- ' float4 accelerationEndSize : TEXCOORD2; // acceleration.xyz, endSize\n' +
- ' float4 spinStartSpinSpeed : TEXCOORD3; // spinStart.x, spinSpeed.y\n' +
- ' float4 colorMult : COLOR; //\n' +
- '};\n' +
- '\n' +
- 'struct PixelShaderInput {\n' +
- ' float4 position : POSITION;\n' +
- ' float2 texcoord : TEXCOORD0;\n' +
- ' float1 percentLife : TEXCOORD1;\n' +
- ' float4 colorMult: TEXCOORD2;\n' +
- '};\n' +
- '\n' +
- 'PixelShaderInput vertexShaderFunction(VertexShaderInput input) {\n' +
- ' PixelShaderInput output;\n' +
- '\n' +
- ' float2 uv = input.uvLifeTimeFrameStart.xy;\n' +
- ' float lifeTime = input.uvLifeTimeFrameStart.z;\n' +
- ' float frameStart = input.uvLifeTimeFrameStart.w;\n' +
- ' float3 position = mul(float4(input.positionStartTime.xyz, 1),\n' +
- ' world).xyz;\n' +
- ' float startTime = input.positionStartTime.w;\n' +
- ' float3 velocity = mul(float4(input.velocityStartSize.xyz, 0),\n' +
- ' world).xyz + worldVelocity;\n' +
- ' float startSize = input.velocityStartSize.w;\n' +
- ' float3 acceleration = mul(float4(input.accelerationEndSize.xyz, 0),\n' +
- ' world).xyz + worldAcceleration;\n' +
- ' float endSize = input.accelerationEndSize.w;\n' +
- ' float spinStart = input.spinStartSpinSpeed.x;\n' +
- ' float spinSpeed = input.spinStartSpinSpeed.y;\n' +
- '\n' +
- ' float localTime = fmod((time - timeOffset - startTime), timeRange);\n' +
- ' float percentLife = localTime / lifeTime;\n' +
- '\n' +
- ' float frame = fmod(floor(localTime / frameDuration + frameStart),\n' +
- ' numFrames);\n' +
- ' float uOffset = frame / numFrames;\n' +
- ' float u = uOffset + (uv.x + 0.5) * (1 / numFrames);\n' +
- '\n' +
- ' output.texcoord = float2(u, uv.y + 0.5);\n' +
- ' output.colorMult = input.colorMult;\n' +
- '\n' +
- ' float3 basisX = viewInverse[0].xyz;\n' +
- ' float3 basisZ = viewInverse[1].xyz;\n' +
- '\n' +
- ' float size = lerp(startSize, endSize, percentLife);\n' +
- ' size = (percentLife < 0 || percentLife > 1) ? 0 : size;\n' +
- ' float s = sin(spinStart + spinSpeed * localTime);\n' +
- ' float c = cos(spinStart + spinSpeed * localTime);\n' +
- '\n' +
- ' float2 rotatedPoint = float2(uv.x * c + uv.y * s, \n' +
- ' -uv.x * s + uv.y * c);\n' +
- ' float3 localPosition = float3(basisX * rotatedPoint.x +\n' +
- ' basisZ * rotatedPoint.y) * size +\n' +
- ' velocity * localTime +\n' +
- ' acceleration * localTime * localTime + \n' +
- ' position;\n' +
- '\n' +
- ' output.position = mul(float4(localPosition, 1), \n' +
- ' viewProjection);\n' +
- ' output.percentLife = percentLife;\n' +
- ' return output;\n' +
- '}\n' +
- '\n' +
- 'float4 pixelShaderFunction(PixelShaderInput input): COLOR {\n' +
- ' float4 colorMult = tex2D(rampSampler, \n' +
- ' float2(input.percentLife, 0.5)) *\n' +
- ' input.colorMult;\n' +
- ' float4 color = tex2D(colorSampler, input.texcoord) * colorMult;\n' +
- ' return color;\n' +
- '}\n' +
- '\n' +
- '// #o3d VertexShaderEntryPoint vertexShaderFunction\n' +
- '// #o3d PixelShaderEntryPoint pixelShaderFunction\n' +
- '// #o3d MatrixLoadOrder RowMajor\n'}];
-
-o3djs.particles.FX_STRINGS_GLSL = [
- { name: 'particle3d', fxString: '' +
- 'uniform mat4 world;\n' +
- 'uniform mat4 worldViewProjection;\n' +
- 'uniform vec3 worldVelocity;\n' +
- 'uniform vec3 worldAcceleration;\n' +
- 'uniform float timeRange;\n' +
- 'uniform float time;\n' +
- 'uniform float timeOffset;\n' +
- 'uniform float frameDuration;\n' +
- 'uniform float numFrames;\n' +
- '\n' +
- 'attribute vec4 position; // uv, lifeTime, frameStart\n' +
- 'attribute vec4 texCoord0; // position.xyz, startTime\n' +
- 'attribute vec4 texCoord1; // velocity.xyz, startSize\n' +
- 'attribute vec4 texCoord2; // acceleration.xyz, endSize\n' +
- 'attribute vec4 texCoord3; // spinStart.x, spinSpeed.y\n' +
- 'attribute vec4 texCoord4; // orientation\n' +
- 'attribute vec4 color; //\n' +
- '\n' +
- 'varying vec4 v_position;\n' +
- 'varying vec2 v_texcoord;\n' +
- 'varying float v_percentLife;\n' +
- 'varying vec4 v_colorMult;\n' +
- '\n' +
- 'void main() {\n' +
- ' vec4 uvLifeTimeFrameStart = position;\n' +
- ' vec4 positionStartTime = texCoord0;\n' +
- ' vec4 velocityStartSize = texCoord1;\n' +
- ' vec4 accelerationEndSize = texCoord2;\n' +
- ' vec4 spinStartSpinSpeed = texCoord3;\n' +
- ' vec4 orientation = texCoord4;\n' +
- ' vec4 colorMult = color;\n' +
- ' vec2 uv = uvLifeTimeFrameStart.xy;\n' +
- ' float lifeTime = uvLifeTimeFrameStart.z;\n' +
- ' float frameStart = uvLifeTimeFrameStart.w;\n' +
- ' vec3 position = positionStartTime.xyz;\n' +
- ' float startTime = positionStartTime.w;\n' +
- ' vec3 velocity = (world * vec4(velocityStartSize.xyz, 0)).xyz\n' +
- ' + worldVelocity;\n' +
- ' float startSize = velocityStartSize.w;\n' +
- ' vec3 acceleration = (world *\n' +
- ' vec4(accelerationEndSize.xyz, 0)).xyz + worldAcceleration;\n' +
- ' float endSize = accelerationEndSize.w;\n' +
- ' float spinStart = spinStartSpinSpeed.x;\n' +
- ' float spinSpeed = spinStartSpinSpeed.y;\n' +
- '\n' +
- ' float localTime = mod((time - timeOffset - startTime),\n' +
- ' timeRange);\n' +
- ' float percentLife = localTime / lifeTime;\n' +
- '\n' +
- ' float frame = mod(floor(localTime / frameDuration + frameStart),\n' +
- ' numFrames);\n' +
- ' float uOffset = frame / numFrames;\n' +
- ' float u = uOffset + (uv.x + 0.5) * (1.0 / numFrames);\n' +
- '\n' +
- ' v_texcoord = vec2(u, uv.y + 0.5);\n' +
- ' v_colorMult = colorMult;\n' +
- '\n' +
- ' float size = mix(startSize, endSize, percentLife);\n' +
- ' size = (percentLife < 0.0 || percentLife > 1.0) ? 0.0 : size;\n' +
- ' float s = sin(spinStart + spinSpeed * localTime);\n' +
- ' float c = cos(spinStart + spinSpeed * localTime);\n' +
- '\n' +
- ' vec4 rotatedPoint = vec4((uv.x * c + uv.y * s) * size, 0.0,\n' +
- ' (uv.x * s - uv.y * c) * size, 1.0);\n' +
- ' vec3 center = velocity * localTime +\n' +
- ' acceleration * localTime * localTime + \n' +
- ' position;\n' +
- ' \n' +
- ' vec4 q2 = orientation + orientation;\n' +
- ' vec4 qx = orientation.xxxw * q2.xyzx;\n' +
- ' vec4 qy = orientation.xyyw * q2.xyzy;\n' +
- ' vec4 qz = orientation.xxzw * q2.xxzz;\n' +
- ' \n' +
- ' mat4 localMatrix = mat4(\n' +
- ' (1.0 - qy.y) - qz.z, \n' +
- ' qx.y + qz.w, \n' +
- ' qx.z - qy.w,\n' +
- ' 0,\n' +
- ' \n' +
- ' qx.y - qz.w, \n' +
- ' (1.0 - qx.x) - qz.z, \n' +
- ' qy.z + qx.w,\n' +
- ' 0,\n' +
- ' \n' +
- ' qx.z + qy.w, \n' +
- ' qy.z - qx.w, \n' +
- ' (1.0 - qx.x) - qy.y,\n' +
- ' 0,\n' +
- ' \n' +
- ' center.x, center.y, center.z, 1.0);\n' +
- ' rotatedPoint = localMatrix * rotatedPoint;\n' +
- ' gl_Position = worldViewProjection * rotatedPoint;\n' +
- ' v_percentLife = percentLife;\n' +
- '}\n' +
- '\n' +
- '// #o3d SplitMarker\n' +
- '\n' +
- 'varying vec4 v_position;\n' +
- 'varying vec2 v_texcoord;\n' +
- 'varying float v_percentLife;\n' +
- 'varying vec4 v_colorMult;\n' +
- '\n' +
- '// We need to implement 1D!\n' +
- 'uniform sampler2D rampSampler;\n' +
- 'uniform sampler2D colorSampler;\n' +
- '\n' +
- 'void main() {\n' +
- ' vec4 colorMult = texture2D(rampSampler, \n' +
- ' vec2(v_percentLife, 0.5)) * v_colorMult;\n' +
- ' vec4 color = texture2D(colorSampler, v_texcoord) * colorMult;\n' +
- ' gl_FragColor = color;\n' +
- '}\n' +
- '\n' +
- '// #o3d MatrixLoadOrder RowMajor\n'},
- { name: 'particle2d', fxString: '' +
- 'uniform mat4 viewProjection;\n' +
- 'uniform mat4 world;\n' +
- 'uniform mat4 viewInverse;\n' +
- 'uniform vec3 worldVelocity;\n' +
- 'uniform vec3 worldAcceleration;\n' +
- 'uniform float timeRange;\n' +
- 'uniform float time;\n' +
- 'uniform float timeOffset;\n' +
- 'uniform float frameDuration;\n' +
- 'uniform float numFrames;\n' +
- '\n' +
- 'attribute vec4 position; // uv, lifeTime, frameStart\n' +
- 'attribute vec4 texCoord0; // position.xyz, startTime\n' +
- 'attribute vec4 texCoord1; // velocity.xyz, startSize\n' +
- 'attribute vec4 texCoord2; // acceleration.xyz, endSize\n' +
- 'attribute vec4 texCoord3; // spinStart.x, spinSpeed.y\n' +
- 'attribute vec4 color; //\n' +
- '\n' +
- 'varying vec4 v_position;\n' +
- 'varying vec2 v_texcoord;\n' +
- 'varying float v_percentLife;\n' +
- 'varying vec4 v_colorMult;\n' +
- '\n' +
- 'void main() {\n' +
- ' vec4 uvLifeTimeFrameStart = position;\n' +
- ' vec4 positionStartTime = texCoord0;\n' +
- ' vec4 velocityStartSize = texCoord1;\n' +
- ' vec4 accelerationEndSize = texCoord2;\n' +
- ' vec4 spinStartSpinSpeed = texCoord3;\n' +
- ' vec4 colorMult = color;\n' +
- ' vec2 uv = uvLifeTimeFrameStart.xy;\n' +
- ' float lifeTime = uvLifeTimeFrameStart.z;\n' +
- ' float frameStart = uvLifeTimeFrameStart.w;\n' +
- ' vec3 position = (world * vec4(positionStartTime.xyz, 1.0)).xyz;\n' +
- ' float startTime = positionStartTime.w;\n' +
- ' vec3 velocity = (world * vec4(velocityStartSize.xyz, 0)).xyz \n' +
- ' + worldVelocity;\n' +
- ' float startSize = velocityStartSize.w;\n' +
- ' vec3 acceleration = (world *\n' +
- ' vec4(accelerationEndSize.xyz, 0)).xyz + worldAcceleration;\n' +
- ' float endSize = accelerationEndSize.w;\n' +
- ' float spinStart = spinStartSpinSpeed.x;\n' +
- ' float spinSpeed = spinStartSpinSpeed.y;\n' +
- '\n' +
- ' float localTime = mod((time - timeOffset - startTime),\n' +
- ' timeRange);\n' +
- ' float percentLife = localTime / lifeTime;\n' +
- '\n' +
- ' float frame = mod(floor(localTime / frameDuration + frameStart),\n' +
- ' numFrames);\n' +
- ' float uOffset = frame / numFrames;\n' +
- ' float u = uOffset + (uv.x + 0.5) * (1.0 / numFrames);\n' +
- '\n' +
- ' v_texcoord = vec2(u, uv.y + 0.5);\n' +
- ' v_colorMult = colorMult;\n' +
- '\n' +
- ' vec3 basisX = viewInverse[0].xyz;\n' +
- ' vec3 basisZ = viewInverse[1].xyz;\n' +
- '\n' +
- ' float size = mix(startSize, endSize, percentLife);\n' +
- ' size = (percentLife < 0.0 || percentLife > 1.0) ? 0.0 : size;\n' +
- ' float s = sin(spinStart + spinSpeed * localTime);\n' +
- ' float c = cos(spinStart + spinSpeed * localTime);\n' +
- '\n' +
- ' vec2 rotatedPoint = vec2(uv.x * c + uv.y * s, \n' +
- ' -uv.x * s + uv.y * c);\n' +
- ' vec3 localPosition = vec3(basisX * rotatedPoint.x +\n' +
- ' basisZ * rotatedPoint.y) * size +\n' +
- ' velocity * localTime +\n' +
- ' acceleration * localTime * localTime + \n' +
- ' position;\n' +
- '\n' +
- ' gl_Position = (viewProjection * vec4(localPosition, 1.0));\n' +
- ' v_percentLife = percentLife;\n' +
- '}\n' +
- '\n' +
- '// #o3d SplitMarker\n' +
- '\n' +
- 'varying vec4 v_position;\n' +
- 'varying vec2 v_texcoord;\n' +
- 'varying float v_percentLife;\n' +
- 'varying vec4 v_colorMult;\n' +
- '\n' +
- '// We need to implement 1D!\n' +
- 'uniform sampler2D rampSampler;\n' +
- 'uniform sampler2D colorSampler;\n' +
- '\n' +
- 'void main() {\n' +
- ' vec4 colorMult = texture2D(rampSampler, \n' +
- ' vec2(v_percentLife, 0.5)) * v_colorMult;\n' +
- ' vec4 color = texture2D(colorSampler, v_texcoord) * colorMult;\n' +
- ' gl_FragColor = color;\n' +
- '}\n' +
- '\n' +
- '// #o3d MatrixLoadOrder RowMajor\n'}];
-
-
-/**
- * Sets the current shaders language to be in accordance with effect.js.
- */
-o3djs.particles.useCorrectShaders_ = function() {
- o3djs.particles.FX_STRINGS = o3djs.particles.FX_STRINGS_CG;
- if (o3djs.effect.LANGUAGE == 'glsl') {
- o3djs.particles.FX_STRINGS = o3djs.particles.FX_STRINGS_GLSL;
- }
-};
-
-
-/**
- * Corner values.
- * @private
- * @type {!Array.<!Array.<number>>}
- */
-o3djs.particles.CORNERS_ = [
- [-0.5, -0.5],
- [+0.5, -0.5],
- [+0.5, +0.5],
- [-0.5, +0.5]];
-
-
-/**
- * Creates a particle system.
- * You only need one of these to run multiple emitters of different types
- * of particles.
- * @param {!o3d.Pack} pack The pack for the particle system to manage resources.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo A viewInfo so the particle
- * system can do the default setup. The only thing used from viewInfo
- * is the zOrderedDrawList. If that is not where you want your particles,
- * after you create the particleEmitter use
- * particleEmitter.material.drawList = myDrawList to set it to something
- * else.
- * @param {!o3d.ParamFloat} opt_clockParam A ParamFloat to be the default
- * clock for emitters of this particle system.
- * @param {!function(): number} opt_randomFunction A function that returns
- * a random number between 0.0 and 1.0. This allows you to pass in a
- * pseudo random function if you need particles that are reproducable.
- * @return {!o3djs.particles.ParticleSystem} The created particle system.
- */
-o3djs.particles.createParticleSystem = function(pack,
- viewInfo,
- opt_clockParam,
- opt_randomFunction) {
- return new o3djs.particles.ParticleSystem(pack,
- viewInfo,
- opt_clockParam,
- opt_randomFunction);
-};
-
-/**
- * An Object to manage Particles.
- * @constructor
- * @param {!o3d.Pack} pack The pack for the particle system to manage resources.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo A viewInfo so the particle
- * system can do the default setup. The only thing used from viewInfo
- * is the zOrderedDrawList. If that is not where you want your particles,
- * after you create the particleEmitter use
- * particleEmitter.material.drawList = myDrawList to set it to something
- * else.
- * @param {!o3d.ParamFloat} opt_clockParam A ParamFloat to be the default
- * clock for emitters of this particle system.
- * @param {!function(): number} opt_randomFunction A function that returns
- * a random number between 0.0 and 1.0. This allows you to pass in a
- * pseudo random function if you need particles that are reproducable.
- */
-o3djs.particles.ParticleSystem = function(pack,
- viewInfo,
- opt_clockParam,
- opt_randomFunction) {
- var o3d = o3djs.base.o3d;
- var particleStates = [];
- var effects = [];
- o3djs.particles.useCorrectShaders_();
- for (var ee = 0; ee < o3djs.particles.FX_STRINGS.length; ++ee) {
- var info = o3djs.particles.FX_STRINGS[ee];
- var effect = pack.createObject('Effect');
- effect.name = info.name;
- effect.loadFromFXString(info.fxString);
- effects.push(effect);
- }
-
- var stateInfos = {};
- stateInfos[o3djs.particles.ParticleStateIds.BLEND] = {
- 'SourceBlendFunction':
- o3djs.base.o3d.State.BLENDFUNC_SOURCE_ALPHA,
- 'DestinationBlendFunction':
- o3djs.base.o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA};
-
- stateInfos[o3djs.particles.ParticleStateIds.ADD] = {
- 'SourceBlendFunction':
- o3djs.base.o3d.State.BLENDFUNC_SOURCE_ALPHA,
- 'DestinationBlendFunction':
- o3djs.base.o3d.State.BLENDFUNC_ONE};
-
- stateInfos[o3djs.particles.ParticleStateIds.BLEND_PREMULTIPLY] = {
- 'SourceBlendFunction':
- o3djs.base.o3d.State.BLENDFUNC_ONE,
- 'DestinationBlendFunction':
- o3djs.base.o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA};
-
- stateInfos[o3djs.particles.ParticleStateIds.BLEND_NO_ALPHA] = {
- 'SourceBlendFunction':
- o3djs.base.o3d.State.BLENDFUNC_SOURCE_COLOR,
- 'DestinationBlendFunction':
- o3djs.base.o3d.State.BLENDFUNC_INVERSE_SOURCE_COLOR};
-
- stateInfos[o3djs.particles.ParticleStateIds.SUBTRACT] = {
- 'SourceBlendFunction':
- o3djs.base.o3d.State.BLENDFUNC_SOURCE_ALPHA,
- 'DestinationBlendFunction':
- o3djs.base.o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA,
- 'BlendEquation':
- o3djs.base.o3d.State.BLEND_REVERSE_SUBTRACT};
-
- stateInfos[o3djs.particles.ParticleStateIds.INVERSE] = {
- 'SourceBlendFunction':
- o3djs.base.o3d.State.BLENDFUNC_INVERSE_DESTINATION_COLOR,
- 'DestinationBlendFunction':
- o3djs.base.o3d.State.BLENDFUNC_INVERSE_SOURCE_COLOR};
-
- for (var key in o3djs.particles.ParticleStateIds) {
- var state = pack.createObject('State');
- var id = o3djs.particles.ParticleStateIds[key];
- particleStates[id] = state;
- state.getStateParam('ZWriteEnable').value = false;
- state.getStateParam('CullMode').value = o3d.State.CULL_NONE;
-
- var info = stateInfos[id];
- for (var stateName in info) {
- state.getStateParam(stateName).value = info[stateName];
- }
- }
-
- var colorTexture = pack.createTexture2D(8, 8, o3d.Texture.ARGB8, 1, false);
- var pixelBase = [0, 0.20, 0.70, 1, 0.70, 0.20, 0, 0];
- var pixels = [];
- for (var yy = 0; yy < 8; ++yy) {
- for (var xx = 0; xx < 8; ++xx) {
- var pixel = pixelBase[xx] * pixelBase[yy];
- pixels.push(pixel, pixel, pixel, pixel);
- }
- }
- colorTexture.set(0, pixels);
- var rampTexture = pack.createTexture2D(3, 1, o3d.Texture.ARGB8, 1, false);
- rampTexture.set(0, [1, 1, 1, 1,
- 1, 1, 1, 0.5,
- 1, 1, 1, 0]);
-
- if (!opt_clockParam) {
- this.counter_ = pack.createObject('SecondCounter');
- opt_clockParam = this.counter_.getParam('count');
- }
-
- this.randomFunction_ = opt_randomFunction || function() {
- return Math.random();
- };
-
- /**
- * The states for the various blend modes.
- * @type {!Array.<!o3d.State>}
- */
- this.particleStates = particleStates;
-
- /**
- * The default ParamFloat to use as the clock for emitters created by
- * this system.
- * @type {!o3d.ParamFloat}
- */
- this.clockParam = opt_clockParam;
-
- /**
- * The pack used to manage particle system resources.
- * @type {!o3d.Pack}
- */
- this.pack = pack;
-
- /**
- * The viewInfo that is used to get drawLists.
- * @type {!o3djs.rendergraph.ViewInfo}
- */
- this.viewInfo = viewInfo;
-
- /**
- * The effects for particles.
- * @type {!Array.<!o3d.Effect>}
- */
- this.effects = effects;
-
-
- /**
- * The default color texture for particles.
- * @type {!o3d.Texture2D}
- */
- this.defaultColorTexture = colorTexture;
-
-
- /**
- * The default ramp texture for particles.
- * @type {!o3d.Texture2D}
- */
- this.defaultRampTexture = rampTexture;
-};
-
-/**
- * A ParticleSpec specifies how to emit particles.
- *
- * NOTE: For all particle functions you can specific a ParticleSpec as a
- * Javascript object, only specifying the fields that you care about.
- *
- * <pre>
- * emitter.setParameters({
- * numParticles: 40,
- * lifeTime: 2,
- * timeRange: 2,
- * startSize: 50,
- * endSize: 90,
- * positionRange: [10, 10, 10],
- * velocity:[0, 0, 60], velocityRange: [15, 15, 15],
- * acceleration: [0, 0, -20],
- * spinSpeedRange: 4}
- * );
- * </pre>
- *
- * Many of these parameters are in pairs. For paired paramters each particle
- * specfic value is set like this
- *
- * particle.field = value + Math.random() - 0.5 * valueRange * 2;
- *
- * or in English
- *
- * particle.field = value plus or minus valueRange.
- *
- * So for example, if you wanted a value from 10 to 20 you'd pass 15 for value
- * and 5 for valueRange because
- *
- * 15 + or - 5 = (10 to 20)
- *
- * @constructor
- */
-o3djs.particles.ParticleSpec = function() {
- /**
- * The number of particles to emit.
- * @type {number}
- */
- this.numParticles = 1;
-
- /**
- * The number of frames in the particle texture.
- * @type {number}
- */
- this.numFrames = 1;
-
- /**
- * The frame duration at which to animate the particle texture in seconds per
- * frame.
- * @type {number}
- */
- this.frameDuration = 1;
-
- /**
- * The initial frame to display for a particular particle.
- * @type {number}
- */
- this.frameStart = 0;
-
- /**
- * The frame start range.
- * @type {number}
- */
- this.frameStartRange = 0;
-
- /**
- * The life time of the entire particle system.
- * To make a particle system be continuous set this to match the lifeTime.
- * @type {number}
- */
- this.timeRange = 99999999;
-
- /**
- * The startTime of a particle.
- * @type {?number}
- */
- this.startTime = null;
- // TODO: Describe what happens if this is not set. I still have some
- // work to do there.
-
- /**
- * The lifeTime of a particle.
- * @type {number}
- */
- this.lifeTime = 1;
-
- /**
- * The lifeTime range.
- * @type {number}
- */
- this.lifeTimeRange = 0;
-
- /**
- * The starting size of a particle.
- * @type {number}
- */
- this.startSize = 1;
-
- /**
- * The starting size range.
- * @type {number}
- */
- this.startSizeRange = 0;
-
- /**
- * The ending size of a particle.
- * @type {number}
- */
- this.endSize = 1;
-
- /**
- * The ending size range.
- * @type {number}
- */
- this.endSizeRange = 0;
-
- /**
- * The starting position of a particle in local space.
- * @type {!o3djs.math.Vector3}
- */
- this.position = [0, 0, 0];
-
- /**
- * The starting position range.
- * @type {!o3djs.math.Vector3}
- */
- this.positionRange = [0, 0, 0];
-
- /**
- * The velocity of a paritcle in local space.
- * @type {!o3djs.math.Vector3}
- */
- this.velocity = [0, 0, 0];
-
- /**
- * The velocity range.
- * @type {!o3djs.math.Vector3}
- */
- this.velocityRange = [0, 0, 0];
-
- /**
- * The acceleration of a particle in local space.
- * @type {!o3djs.math.Vector3}
- */
- this.acceleration = [0, 0, 0];
-
- /**
- * The accleration range.
- * @type {!o3djs.math.Vector3}
- */
- this.accelerationRange = [0, 0, 0];
-
- /**
- * The starting spin value for a particle in radians.
- * @type {number}
- */
- this.spinStart = 0;
-
- /**
- * The spin start range.
- * @type {number}
- */
- this.spinStartRange = 0;
-
- /**
- * The spin speed of a particle in radians.
- * @type {number}
- */
- this.spinSpeed = 0;
-
- /**
- * The spin speed range.
- * @type {number}
- */
- this.spinSpeedRange = 0;
-
- /**
- * The color multiplier of a particle.
- * @type {!o3djs.math.Vector4}
- */
- this.colorMult = [1, 1, 1, 1];
-
- /**
- * The color multiplier range.
- * @type {!o3djs.math.Vector4}
- */
- this.colorMultRange = [0, 0, 0, 0];
-
- /**
- * The velocity of all paritcles in world space.
- * @type {!o3djs.math.Vector3}
- */
- this.worldVelocity = [0, 0, 0];
-
- /**
- * The acceleration of all paritcles in world space.
- * @type {!o3djs.math.Vector3}
- */
- this.worldAcceleration = [0, 0, 0];
-
- /**
- * Whether these particles are oriented in 2d or 3d. true = 2d, false = 3d.
- * @type {boolean}
- */
- this.billboard = true;
-
- /**
- * The orientation of a particle. This is only used if billboard is false.
- * @type {!o3djs.quaternions.Quaternion}
- */
- this.orientation = [0, 0, 0, 1];
-};
-
-/**
- * Creates a particle emitter.
- * @param {!o3d.Texture} opt_texture The texture to use for the particles.
- * If you don't supply a texture a default is provided.
- * @param {!o3d.ParamFloat} opt_clockParam A ParamFloat to be the clock for
- * the emitter.
- * @return {!o3djs.particles.ParticleEmitter} The new emitter.
- */
-o3djs.particles.ParticleSystem.prototype.createParticleEmitter =
- function(opt_texture, opt_clockParam) {
- return new o3djs.particles.ParticleEmitter(this, opt_texture, opt_clockParam);
-};
-
-/**
- * Creates a Trail particle emitter.
- * You can use this for jet exhaust, etc...
- * @param {!o3d.Transform} parent Transform to put emitter on.
- * @param {number} maxParticles Maximum number of particles to appear at once.
- * @param {!o3djs.particles.ParticleSpec} parameters The parameters used to
- * generate particles.
- * @param {!o3d.Texture} opt_texture The texture to use for the particles.
- * If you don't supply a texture a default is provided.
- * @param {!function(number, !o3djs.particles.ParticleSpec): void}
- * opt_perParticleParamSetter A function that is called for each particle to
- * allow it's parameters to be adjusted per particle. The number is the
- * index of the particle being created, in other words, if numParticles is
- * 20 this value will be 0 to 19. The ParticleSpec is a spec for this
- * particular particle. You can set any per particle value before returning.
- * @param {!o3d.ParamFloat} opt_clockParam A ParamFloat to be the clock for
- * the emitter.
- * @return {!o3djs.particles.Trail} A Trail object.
- */
-o3djs.particles.ParticleSystem.prototype.createTrail = function(
- parent,
- maxParticles,
- parameters,
- opt_texture,
- opt_perParticleParamSetter,
- opt_clockParam) {
- return new o3djs.particles.Trail(
- this,
- parent,
- maxParticles,
- parameters,
- opt_texture,
- opt_perParticleParamSetter,
- opt_clockParam);
-};
-
-/**
- * A ParticleEmitter
- * @constructor
- * @param {!o3djs.particles.ParticleSystem} particleSystem The particle system
- * to manage this emitter.
- * @param {!o3d.Texture} opt_texture The texture to use for the particles.
- * If you don't supply a texture a default is provided.
- * @param {!o3d.ParamFloat} opt_clockParam A ParamFloat to be the clock for
- * the emitter.
- */
-o3djs.particles.ParticleEmitter = function(particleSystem,
- opt_texture,
- opt_clockParam) {
- opt_clockParam = opt_clockParam || particleSystem.clockParam;
-
- var o3d = o3djs.base.o3d;
- var pack = particleSystem.pack;
- var viewInfo = particleSystem.viewInfo;
- var material = pack.createObject('Material');
- material.name = 'particles';
- material.drawList = viewInfo.zOrderedDrawList;
- material.effect = particleSystem.effects[1];
- particleSystem.effects[1].createUniformParameters(material);
- material.getParam('time').bind(opt_clockParam);
-
- var rampSampler = pack.createObject('Sampler');
- rampSampler.texture = particleSystem.defaultRampTexture;
- rampSampler.addressModeU = o3d.Sampler.CLAMP;
-
- var colorSampler = pack.createObject('Sampler');
- colorSampler.texture = opt_texture || particleSystem.defaultColorTexture;
- colorSampler.addressModeU = o3d.Sampler.CLAMP;
- colorSampler.addressModeV = o3d.Sampler.CLAMP;
-
- material.getParam('rampSampler').value = rampSampler;
- material.getParam('colorSampler').value = colorSampler;
-
- var vertexBuffer = pack.createObject('VertexBuffer');
- var uvLifeTimeFrameStartField = vertexBuffer.createField('FloatField', 4);
- var positionStartTimeField = vertexBuffer.createField('FloatField', 4);
- var velocityStartSizeField = vertexBuffer.createField('FloatField', 4);
- var accelerationEndSizeField = vertexBuffer.createField('FloatField', 4);
- var spinStartSpinSpeedField = vertexBuffer.createField('FloatField', 4);
- var orientationField = vertexBuffer.createField('FloatField', 4);
- var colorMultField = vertexBuffer.createField('FloatField', 4);
-
- var indexBuffer = pack.createObject('IndexBuffer');
-
- var streamBank = pack.createObject('StreamBank');
- streamBank.setVertexStream(o3d.Stream.POSITION, 0,
- uvLifeTimeFrameStartField, 0);
- streamBank.setVertexStream(o3d.Stream.TEXCOORD, 0,
- positionStartTimeField, 0);
- streamBank.setVertexStream(o3d.Stream.TEXCOORD, 1,
- velocityStartSizeField, 0);
- streamBank.setVertexStream(o3d.Stream.TEXCOORD, 2,
- accelerationEndSizeField, 0);
- streamBank.setVertexStream(o3d.Stream.TEXCOORD, 3,
- spinStartSpinSpeedField, 0);
- streamBank.setVertexStream(o3d.Stream.TEXCOORD, 4,
- orientationField, 0);
- streamBank.setVertexStream(o3d.Stream.COLOR, 0,
- colorMultField, 0);
-
- var shape = pack.createObject('Shape');
- var primitive = pack.createObject('Primitive');
- primitive.material = material;
- primitive.owner = shape;
- primitive.streamBank = streamBank;
- primitive.indexBuffer = indexBuffer;
- primitive.primitiveType = o3d.Primitive.TRIANGLELIST;
- primitive.createDrawElement(pack, null);
-
- this.vertexBuffer_ = vertexBuffer;
- this.uvLifeTimeFrameStartField_ = uvLifeTimeFrameStartField;
- this.positionStartTimeField_ = positionStartTimeField;
- this.velocityStartSizeField_ = velocityStartSizeField;
- this.accelerationEndSizeField_ = accelerationEndSizeField;
- this.spinStartSpinSpeedField_ = spinStartSpinSpeedField;
- this.orientationField_ = orientationField;
- this.colorMultField_ = colorMultField;
- this.indexBuffer_ = indexBuffer;
- this.streamBank_ = streamBank;
- this.primitive_ = primitive;
- this.rampSampler_ = rampSampler;
- this.rampTexture_ = particleSystem.defaultRampTexture;
- this.colorSampler_ = colorSampler;
-
- /**
- * The particle system managing this emitter.
- * @type {!o3djs.particles.ParticleSystem}
- */
- this.particleSystem = particleSystem;
-
- /**
- * The Shape used to render these particles.
- * @type {!o3d.Shape}
- */
- this.shape = shape;
-
- /**
- * The material used by this emitter.
- * @type {!o3d.Material}
- */
- this.material = material;
-
- /**
- * The param that is the source for the time for this emitter.
- * @type {!o3d.ParamFloat}
- */
- this.clockParam = opt_clockParam;
-};
-
-/**
- * Sets the blend state for the particles.
- * You can use this to set the emitter to draw with BLEND, ADD, SUBTRACT, etc.
- * @param {o3djs.particles.ParticleStateIds} stateId The state you want.
- */
-o3djs.particles.ParticleEmitter.prototype.setState = function(stateId) {
- this.material.state = this.particleSystem.particleStates[stateId];
-};
-
-/**
- * Sets the colorRamp for the particles.
- * The colorRamp is used as a multiplier for the texture. When a particle
- * starts it is multiplied by the first color, as it ages to progressed
- * through the colors in the ramp.
- *
- * <pre>
- * particleEmitter.setColorRamp([
- * 1, 0, 0, 1, // red
- * 0, 1, 0, 1, // green
- * 1, 0, 1, 0]); // purple but with zero alpha
- * </pre>
- *
- * The code above sets the particle to start red, change to green then
- * fade out while changing to purple.
- *
- * @param {!Array.<number>} colorRamp An array of color values in
- * the form RGBA.
- */
-o3djs.particles.ParticleEmitter.prototype.setColorRamp = function(colorRamp) {
- var width = colorRamp.length / 4;
- if (width % 1 != 0) {
- throw 'colorRamp must have multiple of 4 entries';
- }
-
- if (this.rampTexture_ == this.particleSystem.defaultRampTexture) {
- this.rampTexture_ = null;
- }
-
- if (this.rampTexture_ && this.rampTexture_.width != width) {
- this.particleSystem.pack.removeObject(this.rampTexture_);
- this.rampTexture_ = null;
- }
-
- if (!this.rampTexture_) {
- this.rampTexture_ = this.particleSystem.pack.createTexture2D(
- width, 1, o3djs.base.o3d.Texture.ARGB8, 1, false);
- }
-
- this.rampTexture_.set(0, colorRamp);
- this.rampSampler_.texture = this.rampTexture_;
-};
-
-/**
- * Validates and adds missing particle parameters.
- * @param {!o3djs.particles.ParticleSpec} parameters The parameters to validate.
- */
-o3djs.particles.ParticleEmitter.prototype.validateParameters = function(
- parameters) {
- var defaults = new o3djs.particles.ParticleSpec();
- for (var key in parameters) {
- if (typeof defaults[key] === 'undefined') {
- throw 'unknown particle parameter "' + key + '"';
- }
- }
- for (var key in defaults) {
- if (typeof parameters[key] === 'undefined') {
- parameters[key] = defaults[key];
- }
- }
-};
-
-/**
- * Creates particles.
- * @private
- * @param {number} firstParticleIndex Index of first particle to create.
- * @param {number} numParticles The number of particles to create.
- * @param {!o3djs.particles.ParticleSpec} parameters The parameters for the
- * emitters.
- * @param {!function(number, !o3djs.particles.ParticleSpec): void}
- * opt_perParticleParamSetter A function that is called for each particle to
- * allow it's parameters to be adjusted per particle. The number is the
- * index of the particle being created, in other words, if numParticles is
- * 20 this value will be 0 to 19. The ParticleSpec is a spec for this
- * particular particle. You can set any per particle value before returning.
- */
-o3djs.particles.ParticleEmitter.prototype.createParticles_ = function(
- firstParticleIndex,
- numParticles,
- parameters,
- opt_perParticleParamSetter) {
- var uvLifeTimeFrameStart = this.uvLifeTimeFrameStart_;
- var positionStartTime = this.positionStartTime_;
- var velocityStartSize = this.velocityStartSize_;
- var accelerationEndSize = this.accelerationEndSize_;
- var spinStartSpinSpeed = this.spinStartSpinSpeed_;
- var orientation = this.orientation_;
- var colorMults = this.colorMults_;
-
- // Set the globals.
- this.material.effect =
- this.particleSystem.effects[parameters.billboard ? 1 : 0];
- this.material.getParam('timeRange').value = parameters.timeRange;
- this.material.getParam('numFrames').value = parameters.numFrames;
- this.material.getParam('frameDuration').value = parameters.frameDuration;
- this.material.getParam('worldVelocity').value = parameters.worldVelocity;
- this.material.getParam('worldAcceleration').value =
- parameters.worldAcceleration;
-
- var random = this.particleSystem.randomFunction_;
-
- var plusMinus = function(range) {
- return (random() - 0.5) * range * 2;
- };
-
- // TODO: change to not allocate.
- var plusMinusVector = function(range) {
- var v = [];
- for (var ii = 0; ii < range.length; ++ii) {
- v.push(plusMinus(range[ii]));
- }
- return v;
- };
-
- for (var ii = 0; ii < numParticles; ++ii) {
- if (opt_perParticleParamSetter) {
- opt_perParticleParamSetter(ii, parameters);
- }
- var pLifeTime = parameters.lifeTime;
- var pStartTime = (parameters.startTime === null) ?
- (ii * parameters.lifeTime / numParticles) : parameters.startTime;
- var pFrameStart =
- parameters.frameStart + plusMinus(parameters.frameStartRange);
- var pPosition = o3djs.math.addVector(
- parameters.position, plusMinusVector(parameters.positionRange));
- var pVelocity = o3djs.math.addVector(
- parameters.velocity, plusMinusVector(parameters.velocityRange));
- var pAcceleration = o3djs.math.addVector(
- parameters.acceleration,
- plusMinusVector(parameters.accelerationRange));
- var pColorMult = o3djs.math.addVector(
- parameters.colorMult, plusMinusVector(parameters.colorMultRange));
- var pSpinStart =
- parameters.spinStart + plusMinus(parameters.spinStartRange);
- var pSpinSpeed =
- parameters.spinSpeed + plusMinus(parameters.spinSpeedRange);
- var pStartSize =
- parameters.startSize + plusMinus(parameters.startSizeRange);
- var pEndSize = parameters.endSize + plusMinus(parameters.endSizeRange);
- var pOrientation = parameters.orientation;
-
- // make each corner of the particle.
- for (var jj = 0; jj < 4; ++jj) {
- var offset0 = (ii * 4 + jj) * 4;
- var offset1 = offset0 + 1;
- var offset2 = offset0 + 2;
- var offset3 = offset0 + 3;
-
- uvLifeTimeFrameStart[offset0] = o3djs.particles.CORNERS_[jj][0];
- uvLifeTimeFrameStart[offset1] = o3djs.particles.CORNERS_[jj][1];
- uvLifeTimeFrameStart[offset2] = pLifeTime;
- uvLifeTimeFrameStart[offset3] = pFrameStart;
-
- positionStartTime[offset0] = pPosition[0];
- positionStartTime[offset1] = pPosition[1];
- positionStartTime[offset2] = pPosition[2];
- positionStartTime[offset3] = pStartTime;
-
- velocityStartSize[offset0] = pVelocity[0];
- velocityStartSize[offset1] = pVelocity[1];
- velocityStartSize[offset2] = pVelocity[2];
- velocityStartSize[offset3] = pStartSize;
-
- accelerationEndSize[offset0] = pAcceleration[0];
- accelerationEndSize[offset1] = pAcceleration[1];
- accelerationEndSize[offset2] = pAcceleration[2];
- accelerationEndSize[offset3] = pEndSize;
-
- spinStartSpinSpeed[offset0] = pSpinStart;
- spinStartSpinSpeed[offset1] = pSpinSpeed;
- spinStartSpinSpeed[offset2] = 0;
- spinStartSpinSpeed[offset3] = 0;
-
- orientation[offset0] = pOrientation[0];
- orientation[offset1] = pOrientation[1];
- orientation[offset2] = pOrientation[2];
- orientation[offset3] = pOrientation[3];
-
- colorMults[offset0] = pColorMult[0];
- colorMults[offset1] = pColorMult[1];
- colorMults[offset2] = pColorMult[2];
- colorMults[offset3] = pColorMult[3];
- }
- }
-
- firstParticleIndex *= 4;
- this.uvLifeTimeFrameStartField_.setAt(
- firstParticleIndex,
- uvLifeTimeFrameStart);
- this.positionStartTimeField_.setAt(
- firstParticleIndex,
- positionStartTime);
- this.velocityStartSizeField_.setAt(
- firstParticleIndex,
- velocityStartSize);
- this.accelerationEndSizeField_.setAt(
- firstParticleIndex,
- accelerationEndSize);
- this.spinStartSpinSpeedField_.setAt(
- firstParticleIndex,
- spinStartSpinSpeed);
- this.orientationField_.setAt(
- firstParticleIndex,
- orientation);
- this.colorMultField_.setAt(
- firstParticleIndex,
- colorMults);
-};
-
-/**
- * Allocates particles.
- * @private
- * @param {number} numParticles Number of particles to allocate.
- */
-o3djs.particles.ParticleEmitter.prototype.allocateParticles_ = function(
- numParticles) {
- if (this.vertexBuffer_.numElements != numParticles * 4) {
- this.vertexBuffer_.allocateElements(numParticles * 4);
-
- var indices = [];
- for (var ii = 0; ii < numParticles; ++ii) {
- // Make 2 triangles for the quad.
- var startIndex = ii * 4
- indices.push(startIndex + 0, startIndex + 1, startIndex + 2);
- indices.push(startIndex + 0, startIndex + 2, startIndex + 3);
- }
- this.indexBuffer_.set(indices);
-
- // We keep these around to avoid memory allocations for trails.
- this.uvLifeTimeFrameStart_ = [];
- this.positionStartTime_ = [];
- this.velocityStartSize_ = [];
- this.accelerationEndSize_ = [];
- this.spinStartSpinSpeed_ = [];
- this.orientation_ = [];
- this.colorMults_ = [];
- }
-
- this.primitive_.numberPrimitives = numParticles * 2;
- this.primitive_.numberVertices = numParticles * 4;
-};
-
-/**
- * Sets the parameters of the particle emitter.
- *
- * Each of these parameters are in pairs. The used to create a table
- * of particle parameters. For each particle a specfic value is
- * set like this
- *
- * particle.field = value + Math.random() - 0.5 * valueRange * 2;
- *
- * or in English
- *
- * particle.field = value plus or minus valueRange.
- *
- * So for example, if you wanted a value from 10 to 20 you'd pass 15 for value
- * and 5 for valueRange because
- *
- * 15 + or - 5 = (10 to 20)
- *
- * @param {!o3djs.particles.ParticleSpec} parameters The parameters for the
- * emitters.
- * @param {!function(number, !o3djs.particles.ParticleSpec): void}
- * opt_perParticleParamSetter A function that is called for each particle to
- * allow it's parameters to be adjusted per particle. The number is the
- * index of the particle being created, in other words, if numParticles is
- * 20 this value will be 0 to 19. The ParticleSpec is a spec for this
- * particular particle. You can set any per particle value before returning.
- */
-o3djs.particles.ParticleEmitter.prototype.setParameters = function(
- parameters,
- opt_perParticleParamSetter) {
- this.validateParameters(parameters);
-
- var numParticles = parameters.numParticles;
-
- this.allocateParticles_(numParticles);
-
- this.createParticles_(
- 0,
- numParticles,
- parameters,
- opt_perParticleParamSetter);
-};
-
-/**
- * Creates a OneShot particle emitter instance.
- * You can use this for dust puffs, explosions, fireworks, etc...
- * @param {!o3d.Transform} opt_parent The parent for the oneshot.
- * @return {!o3djs.particles.OneShot} A OneShot object.
- */
-o3djs.particles.ParticleEmitter.prototype.createOneShot = function(opt_parent) {
- return new o3djs.particles.OneShot(this, opt_parent);
-};
-
-/**
- * An object to manage a particle emitter instance as a one shot. Examples of
- * one shot effects are things like an explosion, some fireworks.
- * @constructor
- * @param {!o3djs.particles.ParticleEmitter} emitter The emitter to use for the
- * one shot.
- * @param {!o3d.Transform} opt_parent The parent for this one shot.
- */
-o3djs.particles.OneShot = function(emitter, opt_parent) {
- var pack = emitter.particleSystem.pack;
- this.emitter_ = emitter;
-
- /**
- * Transform for OneShot.
- * @type {!o3d.Transform}
- */
- this.transform = pack.createObject('Transform');
- this.transform.visible = false;
- this.transform.addShape(emitter.shape);
- this.timeOffsetParam_ =
- this.transform.createParam('timeOffset', 'ParamFloat');
- if (opt_parent) {
- this.setParent(opt_parent);
- }
-};
-
-/**
- * Sets the parent transform for this OneShot.
- * @param {!o3d.Transform} parent The parent for this one shot.
- */
-o3djs.particles.OneShot.prototype.setParent = function(parent) {
- this.transform.parent = parent;
-};
-
-/**
- * Triggers the oneshot.
- *
- * Note: You must have set the parent either at creation, with setParent, or by
- * passing in a parent here.
- *
- * @param {!o3djs.math.Vector3} opt_position The position of the one shot
- * relative to its parent.
- * @param {!o3d.Transform} opt_parent The parent for this one shot.
- */
-o3djs.particles.OneShot.prototype.trigger = function(opt_position, opt_parent) {
- if (opt_parent) {
- this.setParent(opt_parent);
- }
- if (opt_position) {
- this.transform.identity();
- this.transform.translate(opt_position);
- }
- this.transform.visible = true;
- this.timeOffsetParam_.value = this.emitter_.clockParam.value;
-};
-
-/**
- * A type of emitter to use for particle effects that leave trails like exhaust.
- * @constructor
- * @extends {o3djs.particles.ParticleEmitter}
- * @param {!o3djs.particles.ParticleSystem} particleSystem The particle system
- * to manage this emitter.
- * @param {!o3d.Transform} parent Transform to put emitter on.
- * @param {number} maxParticles Maximum number of particles to appear at once.
- * @param {!o3djs.particles.ParticleSpec} parameters The parameters used to
- * generate particles.
- * @param {!o3d.Texture} opt_texture The texture to use for the particles.
- * If you don't supply a texture a default is provided.
- * @param {!function(number, !o3djs.particles.ParticleSpec): void}
- * opt_perParticleParamSetter A function that is called for each particle to
- * allow it's parameters to be adjusted per particle. The number is the
- * index of the particle being created, in other words, if numParticles is
- * 20 this value will be 0 to 19. The ParticleSpec is a spec for this
- * particular particle. You can set any per particle value before returning.
- * @param {!o3d.ParamFloat} opt_clockParam A ParamFloat to be the clock for
- * the emitter.
- */
-o3djs.particles.Trail = function(
- particleSystem,
- parent,
- maxParticles,
- parameters,
- opt_texture,
- opt_perParticleParamSetter,
- opt_clockParam) {
- o3djs.particles.ParticleEmitter.call(
- this, particleSystem, opt_texture, opt_clockParam);
-
- var pack = particleSystem.pack;
-
- this.allocateParticles_(maxParticles);
- this.validateParameters(parameters);
-
- this.parameters = parameters;
- this.perParticleParamSetter = opt_perParticleParamSetter;
- this.birthIndex_ = 0;
- this.maxParticles_ = maxParticles;
-
- /**
- * Transform for OneShot.
- * @type {!o3d.Transform}
- */
- this.transform = pack.createObject('Transform');
- this.transform.addShape(this.shape);
-
- this.transform.parent = parent;
-};
-
-o3djs.base.inherit(o3djs.particles.Trail, o3djs.particles.ParticleEmitter);
-
-/**
- * Births particles from this Trail.
- * @param {!o3djs.math.Vector3} position Position to birth particles at.
- */
-o3djs.particles.Trail.prototype.birthParticles = function(position) {
- var numParticles = this.parameters.numParticles;
- this.parameters.startTime = this.clockParam.value;
- this.parameters.position = position;
- while (this.birthIndex_ + numParticles >= this.maxParticles_) {
- var numParticlesToEnd = this.maxParticles_ - this.birthIndex_;
- this.createParticles_(this.birthIndex_,
- numParticlesToEnd,
- this.parameters,
- this.perParticleParamSetter);
- numParticles -= numParticlesToEnd;
- this.birthIndex_ = 0;
- }
- this.createParticles_(this.birthIndex_,
- numParticles,
- this.parameters,
- this.perParticleParamSetter);
- this.birthIndex_ += numParticles;
-};
-
-
diff --git a/o3d/samples/o3djs/performance.js b/o3d/samples/o3djs/performance.js
deleted file mode 100644
index c5faeaa..0000000
--- a/o3d/samples/o3djs/performance.js
+++ /dev/null
@@ -1,202 +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.
- */
-
-
-/**
- * @fileoverview This file contains a utility that helps adjust rendering
- * quality [or any other setting, really] based on rendering performance.
- *
- */
-
-o3djs.provide('o3djs.performance');
-
-/**
- * A Module to help with adjusting performance.
- * @namespace
- */
-o3djs.performance = o3djs.performance || {};
-
-/**
- * Creates a utility that monitors performance [in terms of FPS] and helps to
- * adjust the rendered scene accordingly.
- * @param {number} targetFPSMin the minimum acceptable frame rate; if we're
- * under this, try to decrease quality to improve performance.
- * @param {number} targetFPSMax if we're over this, try to increase quality.
- * @param {!function(): void} increaseQuality a function to increase
- * quality because we're rendering at high-enough FPS to afford it.
- * @param {!function(): void} decreaseQuality a function to decrease
- * quality to try to raise our rendering speed.
- * @param {!o3djs.performance.PerformanceMonitor.Options} opt_options Options.
- * @return {!o3djs.performance.PerformanceMonitor} The created
- * PerformanceMonitor.
- */
-o3djs.performance.createPerformanceMonitor = function(
- targetFPSMin, targetFPSMax, increaseQuality, decreaseQuality, opt_options) {
- return new o3djs.performance.PerformanceMonitor(targetFPSMin, targetFPSMax,
- increaseQuality, decreaseQuality, opt_options);
-};
-
-/**
- * A class that monitors performance [in terms of FPS] and helps to adjust the
- * rendered scene accordingly.
- * @constructor
- * @param {number} targetFPSMin the minimum acceptable frame rate; if we're
- * under this, try to decrease quality to improve performance.
- * @param {number} targetFPSMax if we're over this, try to increase quality.
- * @param {function(): void} increaseQuality a function to increase
- * quality/lower FPS.
- * @param {function(): void} decreaseQuality a function to decrease
- * quality/raise FPS.
- * @param {!o3djs.performance.PerformanceMonitor.Options} opt_options Options.
- */
-o3djs.performance.PerformanceMonitor = function(
- targetFPSMin, targetFPSMax, increaseQuality, decreaseQuality, opt_options) {
- opt_options = opt_options || {};
-
- /**
- * A function to increase quality/lower FPS.
- * @type {function(): void}
- */
- this.increaseQuality = increaseQuality;
-
- /**
- * A function to decrease quality/raise FPS.
- * @type {function(): void}
- */
- this.decreaseQuality = decreaseQuality;
-
- /**
- * The mean time taken per frame so far, in seconds. This is only valid once
- * we've collected at least minSamples samples.
- * @type {number}
- */
- this.meanFrameTime = 0;
-
- /**
- * The number of samples we've collected so far, when that number is less than
- * or equal to this.damping. After that point, we no longer update
- * this.sampleCount, so it will clip at this.damping.
- *
- * @type {number}
- */
- this.sampleCount = 0;
-
- /**
- * The minimum number of samples to collect before trying to adjust quality.
- *
- * @type {number}
- */
- this.minSamples = opt_options.opt_minSamples || 60;
-
- /**
- * A number that controls the rate at which the effects of any given sample
- * fade away. Higher is slower, but also means that each individual sample
- * counts for less at its most-influential. Damping defaults to 120; anywhere
- * between 60 and 600 are probably reasonable values, depending on your needs,
- * but the number must be no less than minSamples.
- *
- * @type {number}
- */
- this.damping = opt_options.opt_damping || 120;
-
- /**
- * The minimum number of samples to take in between adjustments, to cut down
- * on overshoot. It defaults to 2 * minSamples.
- *
- * @type {number}
- */
- this.delayCycles = opt_options.opt_delayCycles || 2 * this.minSamples;
-
- this.targetFrameTimeMax_ = 1 / targetFPSMin;
- this.targetFrameTimeMin_ = 1 / targetFPSMax;
- this.scaleInput_ = 1 / this.minSamples;
- this.scaleMean_ = 1;
- this.delayCyclesLeft_ = 0;
- if (this.damping < this.minSamples) {
- throw Error('Damping must be at least minSamples.');
- }
-};
-
-/**
- * Options for the PerformanceMonitor.
- *
- * opt_minSamples is the minimum number of samples to take before making any
- * performance adjustments.
- * opt_damping is a number that controls the rate at which the effects of any
- * given sample fade away. Higher is slower, but also means that each
- * individual sample counts for less at its most-influential. Damping
- * defaults to 120; anywhere between 60 and 600 are probably reasonable values,
- * depending on your needs, but the number must be no less than minSamples.
- * opt_delayCycles is the minimum number of samples to take in between
- * adjustments, to cut down on overshoot. It defaults to 2 * opt_minSamples.
- *
- * @type {{
- * opt_minSamples: number,
- * opt_damping: number,
- * opt_delayCycles: number
- * }}
- */
-o3djs.performance.PerformanceMonitor.Options = goog.typedef;
-
-/**
- * Call this once per frame with the elapsed time since the last call, and it
- * will attempt to adjust your rendering quality as needed.
- *
- * @param {number} seconds the elapsed time since the last frame was rendered,
- * in seconds.
- */
-o3djs.performance.PerformanceMonitor.prototype.onRender = function(seconds) {
- var test = true;
- if (this.sampleCount < this.damping) {
- if (this.sampleCount >= this.minSamples) {
- this.scaleInput_ = 1 / (this.sampleCount + 1);
- this.scaleMean_ = this.sampleCount * this.scaleInput_;
- } else {
- test = false;
- }
- this.sampleCount += 1;
- }
- this.meanFrameTime = this.meanFrameTime * this.scaleMean_ +
- seconds * this.scaleInput_;
- if (this.delayCyclesLeft_ > 0) {
- this.delayCyclesLeft_ -= 1;
- } else if (test) {
- if (this.meanFrameTime < this.targetFrameTimeMin_) {
- this.increaseQuality();
- this.delayCyclesLeft_ = this.delayCycles;
- } else if (this.meanFrameTime > this.targetFrameTimeMax_) {
- this.decreaseQuality();
- this.delayCyclesLeft_ = this.delayCycles;
- }
- }
-};
-
-
diff --git a/o3d/samples/o3djs/picking.js b/o3d/samples/o3djs/picking.js
deleted file mode 100644
index a67de17..0000000
--- a/o3d/samples/o3djs/picking.js
+++ /dev/null
@@ -1,742 +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.
- */
-
-
-/**
- * @fileoverview This file contains functions for implementing picking.
- * It puts them in the "picking" module on the o3djs object.
- *
- *
- * This example shows one way to implement picking. Because O3D is shader
- * agnostic we can't handle picking automatically since we have no way of
- * knowing what the developer is going to do with their shaders. On the other
- * hand, we can provide various functions that make it possible to do your own
- * picking. Only you know which objects are pickable and which are not. For
- * example if you are making an RTS game, only you would know that units are
- * pickable but ground and explosions are not and that neither is your HUD.
- * Similarly, only you would know how your shaders manipulate the vertices
- * passed to them.
- *
- * It's possible that someone, maybe us, will create an engine to use o3d
- * that given a bunch of restrictions and flags on the data it accepts can
- * do picking in a more automatic way but that is not the goal of the o3d
- * api. Its goal is to provide a LOW-LEVEL shader agnostic API.
- */
-
-o3djs.provide('o3djs.picking');
-
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.dump');
-
-/**
- * A Module for picking.
- * @namespace
- */
-o3djs.picking = o3djs.picking || {};
-
-/**
- * A ray.
- * @type {{near: !o3djs.math.Vector3, far: !o3djs.math.Vector3}}
- */
-o3djs.picking.Ray = goog.typedef;
-
-/**
- * Creates a new PickInfo.
- * @param {!o3d.Element} element The Element that was picked.
- * @param {!o3djs.picking.ShapeInfo} shapeInfo The ShapeInfo that was picked.
- * @param {!o3d.RayIntersectionInfo} rayIntersectionInfo Information about the
- * pick.
- * @param {!o3djs.math.Vector3} worldIntersectionPosition world position of
- * intersection.
- * @return {!o3djs.picking.PickInfo} The new PickInfo.
- */
-o3djs.picking.createPickInfo = function(element,
- shapeInfo,
- rayIntersectionInfo,
- worldIntersectionPosition) {
- return new o3djs.picking.PickInfo(element,
- shapeInfo,
- rayIntersectionInfo,
- worldIntersectionPosition);
-};
-
-/**
- * Convert a pixel position relative to the top left corner of the client area
- * into the corresponding ray through the frustum in world space.
- * @param {number} clientXPosition x position relative to client area.
- * @param {number} clientYPosition y position relative to client area.
- * @param {!o3djs.math.Matrix4} view View matrix to transform with.
- * @param {!o3djs.math.Matrix4} projection Projection matrix to transform
- * with.
- * @param {number} clientWidth width of client area.
- * @param {number} clientHeight height of client area.
- * @return {!o3djs.picking.Ray} ray in world space.
- */
-o3djs.picking.clientPositionToWorldRayEx = function(clientXPosition,
- clientYPosition,
- view,
- projection,
- clientWidth,
- clientHeight) {
- // compute the world position of a ray going through the view frustum
- var inverseViewProjectionMatrix = o3djs.math.inverse(
- o3djs.math.matrix4.composition(projection, view));
- // normScreenX, normScreenY are in frustum coordinates.
- var normScreenX = clientXPosition / (clientWidth * 0.5) - 1;
- var normScreenY = -(clientYPosition / (clientHeight * 0.5) - 1);
-
- // Apply inverse view-projection matrix to get the ray in world coordinates.
- return {
- near: o3djs.math.matrix4.transformPoint(
- inverseViewProjectionMatrix, [normScreenX, normScreenY, 0]),
- far: o3djs.math.matrix4.transformPoint(
- inverseViewProjectionMatrix, [normScreenX, normScreenY, 1])
- };
-};
-
-/**
- * Convert a pixel position relative to the top left corner of the client area
- * into the corresponding ray through the frustum in world space.
- * @param {number} clientXPosition x position relative to client area.
- * @param {number} clientYPosition y position relative to client area.
- * @param {!o3d.DrawContext} drawContext DrawContext to get view and
- * projection matrices from.
- * @param {number} clientWidth width of client area.
- * @param {number} clientHeight height of client area.
- * @return {!o3djs.picking.Ray} ray in world space.
- */
-o3djs.picking.clientPositionToWorldRay = function(clientXPosition,
- clientYPosition,
- drawContext,
- clientWidth,
- clientHeight) {
- return o3djs.picking.clientPositionToWorldRayEx(
- clientXPosition,
- clientYPosition,
- drawContext.view,
- drawContext.projection,
- clientWidth,
- clientHeight);
-};
-
-/**
- * A local dump function so we can easily comment it out.
- * @param {string} msg Message to dump.
- */
-o3djs.picking.dprint = function(msg) {
- //o3djs.dump.dump(msg);
-};
-
-/**
- * A local dump function so we can easily comment it out.
- * @param {string} label Label to print before value.
- * @param {!o3djs.math.Vector3} float3 Value to print.
- * @param {string} prefix optional prefix for indenting.
- */
-o3djs.picking.dprintPoint3 = function(label, float3, prefix) {
- //o3djs.dump.dumpPoint3(label, float3, prefix);
-};
-
-/**
- * A local dump function so we can easily comment it out.
- * @param {string} label Label to put in front of dump.
- * @param {!o3d.BoundingBox} boundingBox BoundingBox to dump.
- * @param {string} opt_prefix optional prefix for indenting.
- */
-o3djs.picking.dprintBoundingBox = function(label,
- boundingBox,
- opt_prefix) {
- //o3djs.dump.dumpBoundingBox(label, boundingBox, opt_prefix);
-};
-
-/**
- * A local dump function so we can easily comment it out.
- * @param {string} label Label to print before value.
- * @param {!o3d.RayIntersectionInfo} rayIntersectionInfo Value to print.
- */
-o3djs.picking.dumpRayIntersectionInfo = function(label,
- rayIntersectionInfo) {
- o3djs.picking.dprint(
- label + ' : valid = ' +
- rayIntersectionInfo.valid + ' : intersected = ' +
- rayIntersectionInfo.intersected);
- if (rayIntersectionInfo.intersected) {
- o3djs.picking.dprint(
- ' : pos: ' +
- rayIntersectionInfo.position[0] + ', ' +
- rayIntersectionInfo.position[1] + ', ' +
- rayIntersectionInfo.position[2] + ', ');
- }
- o3djs.picking.dprint('\n');
-};
-
-/**
- * Creates a new PickInfo. Used to return picking information.
- * @constructor
- * @param {!o3d.Element} element The Element that was picked.
- * @param {!o3djs.picking.ShapeInfo} shapeInfo The ShapeInfo that was picked.
- * @param {!o3d.RayIntersectionInfo} rayIntersectionInfo Information about the
- * pick.
- * @param {!o3djs.math.Vector3} worldIntersectionPosition world position of
- * intersection.
- */
-o3djs.picking.PickInfo = function(element,
- shapeInfo,
- rayIntersectionInfo,
- worldIntersectionPosition) {
- /**
- * The Element that was picked (Primitive).
- * @type {!o3d.Element}
- */
- this.element = element;
-
- /**
- * The ShapeInfo that was picked.
- * @type {!o3djs.picking.ShapeInfo}
- */
- this.shapeInfo = shapeInfo;
-
- /**
- * Information about the pick.
- * @type {!o3d.RayIntersectionInfo}
- */
- this.rayIntersectionInfo = rayIntersectionInfo;
-
- /**
- * The worldIntersectionPosition world position of intersection.
- * @type {!o3djs.math.Vector3}
- */
- this.worldIntersectionPosition = worldIntersectionPosition
-};
-
-/**
- * Creates a new ShapeInfo. Used to store information about Shapes. Note, even
- * though Shapes can be instanced, ShapeInfos can not so if a Shape is instanced
- * there will be more than one ShapeInfo for it.
- * @constructor
- * @param {!o3d.Shape} shape Shape to keep info about.
- * @param {!o3djs.picking.TransformInfo} parent Parent transform of the shape.
- * @param {!o3djs.picking.PickManager} pickManager The PickManager this
- * ShapeInfo belongs to.
- */
-o3djs.picking.ShapeInfo = function(shape, parent, pickManager) {
- /**
- * The Shape for this ShapeInfo
- * @type {!o3d.Shape}
- */
- this.shape = shape;
-
- /**
- * The parent TransformInfo of this Shape.
- * @type {!o3djs.picking.TransformInfo}
- */
- this.parent = parent;
-
- /**
- * The bounding box for this Shape
- * @type {o3d.BoundingBox}
- */
- this.boundingBox = null;
-
- /**
- * The PickManager this ShapeInfo belongs to.
- * @type {!o3djs.picking.PickManager}
- */
- this.pickManager = pickManager;
-
- this.update();
-};
-
-/**
- * Returns whether or not this ShapeInfo is pickable.
- * @return {boolean} Whether or not this ShapeInfo is pickable.
- */
-o3djs.picking.ShapeInfo.prototype.isPickable = function() {
- return true;
-}
-
-/**
- * Gets the BoundingBox of the Shape in this ShapeInfo.
- * @return {o3d.BoundingBox} The Shape's BoundingBox.
- */
-o3djs.picking.ShapeInfo.prototype.getBoundingBox = function() {
- return this.boundingBox;
-};
-
-/**
- * Updates the BoundingBox of the Shape in this ShapeInfo.
- */
-o3djs.picking.ShapeInfo.prototype.update = function() {
- var elements = this.shape.elements;
- if (elements.length > 0) {
- this.boundingBox = elements[0].getBoundingBox(0);
- for (var ee = 1; ee < elements.length; ee++) {
- this.boundingBox = this.boundingBox.add(elements[ee].getBoundingBox(0));
- }
- }
-};
-
-/**
- * Attempts to "pick" this Shape by checking for the intersection of a ray
- * in world space to the triangles this shape uses.
- * @param {!o3djs.picking.Ray} worldRay A ray in world space to pick against.
- * @return {o3djs.picking.PickInfo} Information about the picking.
- * null if the ray did not intersect any triangles.
- */
-o3djs.picking.ShapeInfo.prototype.pick = function(worldRay) {
- if (this.isPickable()) {
- var worldMatrix = this.parent.transform.getUpdatedWorldMatrix()
- var inverseWorldMatrix = o3djs.math.inverse(worldMatrix);
- var relativeNear = o3djs.math.matrix4.transformPoint(
- inverseWorldMatrix, worldRay.near);
- var relativeFar = o3djs.math.matrix4.transformPoint(
- inverseWorldMatrix, worldRay.far);
- var rayIntersectionInfo =
- this.boundingBox.intersectRay(relativeNear,
- relativeFar);
-
- o3djs.picking.dumpRayIntersectionInfo('SHAPE(box): ' + this.shape.name,
- rayIntersectionInfo);
-
- if (rayIntersectionInfo.intersected) {
- var elements = this.shape.elements;
- for (var e = 0; e < elements.length; e++) {
- var element = elements[e];
- rayIntersectionInfo = element.intersectRay(
- 0,
- o3djs.base.o3d.State.CULL_CCW,
- relativeNear,
- relativeFar);
- o3djs.picking.dumpRayIntersectionInfo(
- 'SHAPE(tris): ' + this.shape.name + ' : element ' + element.name,
- rayIntersectionInfo);
-
- // TODO: get closest element not just first element.
- if (rayIntersectionInfo.intersected) {
- var worldIntersectionPosition = o3djs.math.matrix4.transformPoint(
- worldMatrix, rayIntersectionInfo.position);
- return o3djs.picking.createPickInfo(element,
- this,
- rayIntersectionInfo,
- worldIntersectionPosition);
- }
- }
- }
- }
- return null;
-};
-
-/**
- * Dumps info about a ShapeInfo
- * @param {string} opt_prefix optional prefix for indenting.
- */
-o3djs.picking.ShapeInfo.prototype.dump = function(opt_prefix) {
- var prefix = opt_prefix || '';
- o3djs.picking.dprint(prefix + 'SHAPE: ' + this.shape.name + '\n');
- o3djs.picking.dprintPoint3('bb min',
- this.boundingBox.minExtent,
- prefix + ' ');
- o3djs.picking.dprintPoint3('bb max',
- this.boundingBox.maxExtent,
- prefix + ' ');
-};
-
-/**
- * Creates a new TransformInfo. Used to store information about Transforms.
- * @constructor
- * @param {!o3d.Transform} transform Transform to keep info about.
- * @param {o3djs.picking.TransformInfo} parent Parent transformInfo of the
- * transform. Can be null.
- * @param {!o3djs.picking.PickManager} pickManager The PickManager this
- * ShapeInfo belongs to.
- */
-o3djs.picking.TransformInfo = function(transform, parent, pickManager) {
- /**
- * TransformInfos for children by client id.
- * @type {!Object.<number, !o3djs.picking.TransformInfo>}
- */
- this.childTransformInfos = {};
-
- /**
- * ShapeInfos for shape of this transform by client id.
- * @type {!Object.<number, !o3djs.picking.ShapeInfo>}
- */
- this.shapeInfos = {};
-
- /**
- * The transform of this transform info.
- * @type {!o3d.Transform}
- */
- this.transform = transform;
-
- /**
- * The parent of this transform info.
- * @type {o3djs.picking.TransformInfo}
- */
- this.parent = parent;
-
- /**
- * The bounding box of this transform info.
- * @type {o3d.BoundingBox}
- */
- this.boundingBox = null;
-
- /**
- * The PickManager this TransformInfo belongs to.
- * @type {!o3djs.picking.PickManager}
- */
- this.pickManager = pickManager;
-
- /**
- * Whether or not this object is pickable when invisible.
- * This is useful for collision geometry that is not visible.
- * Of course it might argubly be better to store collision geometry
- * in a separate graph from visible geometry but sometimes it's useful
- * to have them in the same graph.
- * @type {boolean}
- */
- this.pickableEvenIfInvisible = false;
-};
-
-/**
- * Gets the BoundingBox of the Transform in this TransformInfo.
- * @return {o3d.BoundingBox} The Transform's BoundingBox.
- */
-o3djs.picking.TransformInfo.prototype.getBoundingBox = function() {
- return this.boundingBox;
-};
-
-/**
- * Returns whether or not this TransformInfo is pickable.
- *
- * If this TransformInfo is not pickable then all child shapes and
- * TransformInfos will be skipped during the picking process.
- *
- * @return {boolean} Whether or not this TransformInfo is pickable.
- */
-o3djs.picking.TransformInfo.prototype.isPickable = function() {
- return this.transform.visible || this.pickableEvenIfInvisible;
-};
-
-/**
- * Updates the shape and child lists for this TransformInfo and recomputes its
- * BoundingBox.
- */
-o3djs.picking.TransformInfo.prototype.update = function() {
- var newChildTransformInfos = {};
- var newShapeInfos = {};
- // We need to add new children and remove old ones so we walk the children
- // and for each one we find, if it already has a TransformInfo or ShapeInfo we
- // add it to our new lists, if not we create one and add it to our new lists.
- var children = this.transform.children;
- for (var c = 0; c < children.length; c++) {
- var child = children[c];
- var transformInfo = this.childTransformInfos[child.clientId];
- if (!transformInfo) {
- transformInfo = this.pickManager.createTransformInfo(child, this);
- } else {
- // clear the boundingBox so we'll regenerate it.
- transformInfo.boundingBox = null;
- }
- transformInfo.update();
- newChildTransformInfos[child.clientId] = transformInfo;
- }
- var shapes = this.transform.shapes;
- for (var s = 0; s < shapes.length; s++) {
- var shape = shapes[s];
- var shapeInfo = this.shapeInfos[shape.clientId];
- if (!shapeInfo) {
- shapeInfo = this.pickManager.createShapeInfo(shape, this);
- } else {
- // unless the vertices or elements change there is no need to
- // recompute this.
- // shapeInfo.update();
- }
- newShapeInfos[shape.clientId] = shapeInfo;
- }
-
- // o3djs.picking.dprint(
- // 'num Children: ' + children.length + '\n');
- // o3djs.picking.dprint(
- // 'num Shapes: ' + shapes.length + '\n');
-
- // Now our new lists have the correct children so replace the old lists.
- // and remove any old children from the PickManager.
- for (var skey in this.childTransformInfos) {
- var key = /** @type {number} */ (skey);
- if (!newChildTransformInfos[key]) {
- this.pickManager.removeTransformInfo(this.childTransformInfos[key]);
- }
- }
-
- this.childTransformInfos = newChildTransformInfos;
- this.shapeInfos = newShapeInfos;
-
- var boundingBox = null;
- for (var key in newShapeInfos) {
- var shapeInfo = newShapeInfos[key];
- if (shapeInfo.isPickable()) {
- var box = shapeInfo.getBoundingBox().mul(this.transform.localMatrix);
- if (!boundingBox) {
- boundingBox = box;
- } else if (box) {
- boundingBox = boundingBox.add(box);
- }
- }
- }
-
- for (var key in newChildTransformInfos) {
- var transformInfo = newChildTransformInfos[key];
- if (transformInfo.isPickable()) {
- // Note: If there is no shape at the leaf on this branch
- // there will be no bounding box.
- var box = transformInfo.getBoundingBox();
- if (box) {
- if (!boundingBox) {
- boundingBox = box.mul(this.transform.localMatrix);
- } else {
- boundingBox = boundingBox.add(box.mul(this.transform.localMatrix));
- }
- }
- }
- }
-
- this.boundingBox = boundingBox;
-};
-
-/**
- * Attempts to "pick" this TransformInfo by checking for the intersection of a
- * ray in world space to the boundingbox of the TransformInfo. If intesection
- * is succesful recursively calls its children and shapes to try to find
- * a single Shape that is hit by the ray.
- * @param {!o3djs.picking.Ray} worldRay A ray in world space to pick against.
- * @return {o3djs.picking.PickInfo} Information about the picking.
- * null if the ray did not intersect any triangles.
- */
-o3djs.picking.TransformInfo.prototype.pick = function(worldRay) {
- if (this.isPickable() && this.boundingBox) {
- var inverseWorldMatrix = o3djs.math.matrix4.identity();
- if (this.parent) {
- inverseWorldMatrix = o3djs.math.inverse(
- this.parent.transform.getUpdatedWorldMatrix());
- }
- var relativeNear =
- o3djs.math.matrix4.transformPoint(inverseWorldMatrix, worldRay.near);
- var relativeFar =
- o3djs.math.matrix4.transformPoint(inverseWorldMatrix, worldRay.far);
- var rayIntersectionInfo =
- this.boundingBox.intersectRay(relativeNear, relativeFar);
- o3djs.picking.dumpRayIntersectionInfo(
- 'TRANSFORM(box): ' + this.transform.name, rayIntersectionInfo);
-
- if (rayIntersectionInfo.intersected) {
- var closestPickInfo = null;
- var minDistance = -1;
- for (var skey in this.childTransformInfos) {
- var key = /** @type {number} */ (skey);
- var transformInfo = this.childTransformInfos[key];
- var pickInfo = transformInfo.pick(worldRay);
- if (pickInfo) {
- // is this closer than the last one?
- var distance = o3djs.math.lengthSquared(
- o3djs.math.subVector(worldRay.near,
- pickInfo.worldIntersectionPosition));
- if (!closestPickInfo || distance < minDistance) {
- minDistance = distance;
- closestPickInfo = pickInfo;
- }
- }
- }
-
- for (var skey in this.shapeInfos) {
- var key = /** @type {number} */ (skey);
- var shapeInfo = this.shapeInfos[key];
- var pickInfo = shapeInfo.pick(worldRay);
- if (pickInfo) {
- // is this closer than the last one?
- var distance = o3djs.math.lengthSquared(
- o3djs.math.subVector(worldRay.near,
- pickInfo.worldIntersectionPosition));
- if (!closestPickInfo || distance < minDistance) {
- minDistance = distance;
- closestPickInfo = pickInfo;
- }
- }
- }
- return closestPickInfo;
- }
- }
- return null;
-};
-
-/**
- * Dumps info about a TransformInfo
- * @param {string} opt_prefix optional prefix for indenting.
- */
-o3djs.picking.TransformInfo.prototype.dump = function(opt_prefix) {
- var prefix = opt_prefix || '';
-
- o3djs.picking.dprint(prefix + 'TRANSFORM: ' + this.transform.name +
- '\n');
-
- if (this.boundingBox) {
- o3djs.picking.dprintPoint3('bb min',
- this.boundingBox.minExtent,
- prefix + ' ');
- o3djs.picking.dprintPoint3('bb max',
- this.boundingBox.maxExtent,
- prefix + ' ');
- } else {
- o3djs.picking.dprint(prefix + ' bb *NA*\n');
- }
-
- o3djs.picking.dprint(prefix + '--Shapes--\n');
- for (var skey in this.shapeInfos) {
- var key = /** @type {number} */ (skey);
- var shapeInfo = this.shapeInfos[key];
- shapeInfo.dump(prefix + ' ');
- }
-
- o3djs.picking.dprint(prefix + '--Children--\n');
- for (var skey in this.childTransformInfos) {
- var key = /** @type {number} */ (skey);
- var transformInfo = this.childTransformInfos[key];
- transformInfo.dump(prefix + ' ');
- }
-};
-
-/**
- * A PickManager manages picking of primitives from a transform graph.
- * @constructor
- * @param {!o3d.Transform} rootTransform The root of the transform graph this
- * PickManager should manage.
- */
-o3djs.picking.PickManager = function(rootTransform) {
- /**
- * TransformInfos for transforms of this PickManager by client id.
- * @type {!Object.<number, !o3djs.picking.TransformInfo>}
- */
- this.transformInfosByClientId = {};
-
- /**
- * The root transform for this PickManager.
- * @type {!o3djs.picking.TransformInfo}
- */
- this.rootTransformInfo = this.createTransformInfo(rootTransform, null);
-};
-
-/**
- * Creates a new ShapeInfo.
- * @param {!o3d.Shape} shape Shape to keep info about.
- * @param {!o3djs.picking.TransformInfo} parent Parent transform of the shape.
- * @return {!o3djs.picking.ShapeInfo} The new ShapeInfo.
- */
-o3djs.picking.PickManager.prototype.createShapeInfo = function(shape, parent) {
- return new o3djs.picking.ShapeInfo(shape, parent, this);
-};
-
-/**
- * Creates a new TransformInfo.
- * @param {!o3d.Transform} transform Transform to keep info about.
- * @param {o3djs.picking.TransformInfo} parent Parent transform of the
- * transform. Can be null.
- * @return {!o3djs.picking.TransformInfo} The new TransformInfo.
- */
-o3djs.picking.PickManager.prototype.createTransformInfo =
- function(transform, parent) {
- var info = new o3djs.picking.TransformInfo(transform, parent, this);
- this.addTransformInfo(info);
- return info;
-};
-
-/**
- * Adds a transform info to this PickManager.
- * @param {!o3djs.picking.TransformInfo} transformInfo The TransformInfo to add.
- */
-o3djs.picking.PickManager.prototype.addTransformInfo = function(transformInfo) {
- this.transformInfosByClientId[transformInfo.transform.clientId] =
- transformInfo;
-};
-
-/**
- * Removes a transform info from this PickManager.
- * @param {!o3djs.picking.TransformInfo} transformInfo The TransformInfo to
- * remove.
- */
-o3djs.picking.PickManager.prototype.removeTransformInfo =
- function(transformInfo) {
- delete this.transformInfosByClientId[transformInfo.transform.clientId];
-};
-
-/**
- * Gets a transform info from this PickManager by transform.
- * @param {!o3d.Transform} transform The Transform to get a TransformInfo for.
- * @return {o3djs.picking.TransformInfo} The TransformInfo for the transform or
- * null if there isn't one.
- */
-o3djs.picking.PickManager.prototype.getTransformInfo = function(transform) {
- return this.transformInfosByClientId[transform.clientId];
-};
-
-/**
- * Updates the picking info to match the transform graph in its current state.
- */
-o3djs.picking.PickManager.prototype.update = function() {
- this.rootTransformInfo.update();
-};
-
-/**
- * Dumps info about a PickManager
- */
-o3djs.picking.PickManager.prototype.dump = function() {
- this.rootTransformInfo.dump();
-};
-
-/**
- * Attempts to "pick" objects managed by this PickManager.
- * @param {!o3djs.picking.Ray} worldRay A ray in world space to pick against.
- * @return {o3djs.picking.PickInfo} Information about the picking.
- * null if the ray did not intersect any triangles.
- */
-o3djs.picking.PickManager.prototype.pick = function(worldRay) {
- return this.rootTransformInfo.pick(worldRay);
-};
-
-/**
- * Creates a PickManager.
- * @param {!o3d.Transform} rootTransform The root of the transform graph this
- * PickManager should manage.
- * @return {!o3djs.picking.PickManager} The created PickManager.
- */
-o3djs.picking.createPickManager = function(rootTransform) {
- return new o3djs.picking.PickManager(rootTransform);
-};
-
diff --git a/o3d/samples/o3djs/plugin_math.js b/o3d/samples/o3djs/plugin_math.js
deleted file mode 100644
index 25ce285..0000000
--- a/o3d/samples/o3djs/plugin_math.js
+++ /dev/null
@@ -1,2536 +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.
- */
-
-
-/**
- * @fileoverview This file contains matrix/vector math functions.
- * It adds them to the "math" module on the o3djs object.
- *
- * o3djs.math supports a row-major and a column-major mode. In both
- * modes, vectors are stored as arrays of numbers, and matrices are stored as
- * arrays of arrays of numbers.
- *
- * In row-major mode:
- *
- * - Rows of a matrix are sub-arrays.
- * - Individual entries of a matrix M get accessed in M[row][column] fashion.
- * - Tuples of coordinates are interpreted as row-vectors.
- * - A vector v gets transformed by a matrix M by multiplying in the order v*M.
- *
- * In column-major mode:
- *
- * - Columns of a matrix are sub-arrays.
- * - Individual entries of a matrix M get accessed in M[column][row] fashion.
- * - Tuples of coordinates are interpreted as column-vectors.
- * - A matrix M transforms a vector v by multiplying in the order M*v.
- *
- * When a function in o3djs.math requires separate row-major and
- * column-major versions, a function with the same name gets added to each of
- * the namespaces o3djs.math.rowMajor and o3djs.math.columnMajor. The
- * function installRowMajorFunctions() or the function
- * installColumnMajorFunctions() should get called during initialization to
- * establish the mode. installRowMajorFunctions() works by iterating through
- * the o3djs.math.rowMajor namespace and for each function foo, setting
- * o3djs.math.foo equal to o3djs.math.rowMajor.foo.
- * installRowMajorFunctions() works the same way, iterating over the columnMajor
- * namespace. At the end of this file, we call installRowMajorFunctions().
- *
- * Switching modes changes two things. It changes how a matrix is encoded as an
- * array, and it changes how the entries of a matrix get interpreted. Because
- * those two things change together, the matrix representing a given
- * transformation of space is the same JavaScript object in either mode.
- * One consequence of this is that very few functions require separate row-major
- * and column-major versions. Typically, a function requires separate versions
- * only if it makes matrix multiplication order explicit, like
- * mulMatrixMatrix(), mulMatrixVector(), or mulVectorMatrix(). Functions which
- * create a new matrix, like scaling(), rotationZYX(), and translation() return
- * the same JavaScript object in either mode, and functions which implicitly
- * multiply like scale(), rotateZYX() and translate() modify the matrix in the
- * same way in either mode.
- *
- * The convention choice made for math functions in this library is independent
- * of the convention choice for how matrices get loaded into shaders. That
- * convention is determined on a per-shader basis.
- *
- * Other utilities in o3djs should avoid making calls to functions that make
- * multiplication order explicit. Instead they should appeal to functions like:
- *
- * o3djs.math.matrix4.transformPoint
- * o3djs.math.matrix4.transformDirection
- * o3djs.math.matrix4.transformNormal
- * o3djs.math.matrix4.transformVector4
- * o3djs.math.matrix4.composition
- * o3djs.math.matrix4.compose
- *
- * These functions multiply matrices implicitly and internally choose the
- * multiplication order to get the right result. That way, utilities which use
- * o3djs.math work in either major mode. Note that this does not necessarily
- * mean all sample code will work even if a line is added which switches major
- * modes, but it does mean that calls to o3djs still do what they are supposed
- * to.
- *
- */
-
-o3djs.provide('o3djs.math', true);
-
-
-/**
- * A module for math for o3djs.math.
- * @namespace
- */
-o3djs.math = o3djs.math || {};
-
-/**
- * A random seed for the pseudoRandom function.
- * @private
- * @type {number}
- */
-o3djs.math.randomSeed_ = 0;
-
-/**
- * A constant for the pseudoRandom function
- * @private
- * @type {number}
- */
-o3djs.math.RANDOM_RANGE_ = Math.pow(2, 32);
-
-
-o3djs.math.makeMatrix = function(a,b,c,d,
- e,f,g,h,
- i,j,k,l,
- m,n,o,p) {
- if (p===undefined) {
- if (i===undefined) {
- return [[a,b],
- [c,d]];
- }
- return [[a,b,c],
- [d,e,f],
- [g,h,i]];
- }
- return [[a,b,c,d],
- [e,f,g,h],
- [i,j,k,l],
- [m,n,o,p]];
-};
-
-o3djs.math.makeMatrix2 = function(a,b,
- c,d) {
- return [[a,b],
- [c,d]];
-};
-o3djs.math.makeMatrix3 = function(a,b,c,
- d,e,f,
- g,h,i) {
- return [[a,b,c],
- [d,e,f],
- [g,h,i]];
-};
-o3djs.math.makeMatrix4 = function(a,b,c,d,
- e,f,g,h,
- i,j,k,l,
- m,n,o,p) {
- return [[a,b,c,d],
- [e,f,g,h],
- [i,j,k,l],
- [m,n,o,p]];
-};
-
-
-
-/**
- * Returns a deterministic pseudorandom number between 0 and 1
- * @return {number} a random number between 0 and 1
- */
-o3djs.math.pseudoRandom = function() {
- var math = o3djs.math;
- return (math.randomSeed_ =
- (134775813 * math.randomSeed_ + 1) %
- math.RANDOM_RANGE_) / math.RANDOM_RANGE_;
-};
-
-/**
- * Resets the pseudoRandom function sequence.
- */
-o3djs.math.resetPseudoRandom = function() {
- o3djs.math.randomSeed_ = 0;
-};
-
-/**
- * Converts degrees to radians.
- * @param {number} degrees A value in degrees.
- * @return {number} the value in radians.
- */
-o3djs.math.degToRad = function(degrees) {
- return degrees * Math.PI / 180;
-};
-
-/**
- * Converts radians to degrees.
- * @param {number} radians A value in radians.
- * @return {number} the value in degrees.
- */
-o3djs.math.radToDeg = function(radians) {
- return radians * 180 / Math.PI;
-};
-
-/**
- * Performs linear interpolation on two scalars.
- * Given scalars a and b and interpolation coefficient t, returns
- * (1 - t) * a + t * b.
- * @param {number} a Operand scalar.
- * @param {number} b Operand scalar.
- * @param {number} t Interpolation coefficient.
- * @return {number} The weighted sum of a and b.
- */
-o3djs.math.lerpScalar = function(a, b, t) {
- return (1 - t) * a + t * b;
-};
-
-/**
- * Adds two vectors; assumes a and b have the same dimension.
- * @param {!o3djs.math.Vector} a Operand vector.
- * @param {!o3djs.math.Vector} b Operand vector.
- * @return {!o3djs.math.Vector} The sum of a and b.
- */
-o3djs.math.addVector = function(a, b) {
- var r = [];
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i)
- r[i] = a[i] + b[i];
- return r;
-};
-
-/**
- * Subtracts two vectors.
- * @param {!o3djs.math.Vector} a Operand vector.
- * @param {!o3djs.math.Vector} b Operand vector.
- * @return {!o3djs.math.Vector} The difference of a and b.
- */
-o3djs.math.subVector = function(a, b) {
- var r = [];
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i)
- r[i] = a[i] - b[i];
- return r;
-};
-
-/**
- * Performs linear interpolation on two vectors.
- * Given vectors a and b and interpolation coefficient t, returns
- * (1 - t) * a + t * b.
- * @param {!o3djs.math.Vector} a Operand vector.
- * @param {!o3djs.math.Vector} b Operand vector.
- * @param {number} t Interpolation coefficient.
- * @return {!o3djs.math.Vector} The weighted sum of a and b.
- */
-o3djs.math.lerpVector = function(a, b, t) {
- var r = [];
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i)
- r[i] = (1 - t) * a[i] + t * b[i];
- return r;
-};
-
-/**
- * Clamps a value between 0 and range using a modulo.
- * @param {number} v Value to clamp mod.
- * @param {number} range Range to clamp to.
- * @param {number} opt_rangeStart start of range. Default = 0.
- * @return {number} Clamp modded value.
- */
-o3djs.math.modClamp = function(v, range, opt_rangeStart) {
- var start = opt_rangeStart || 0;
- if (range < 0.00001) {
- return start;
- }
- v -= start;
- if (v < 0) {
- v -= Math.floor(v / range) * range;
- } else {
- v = v % range;
- }
- return v + start;
-};
-
-/**
- * Lerps in a circle.
- * Does a lerp between a and b but inside range so for example if
- * range is 100, a is 95 and b is 5 lerping will go in the positive direction.
- * @param {number} a Start value.
- * @param {number} b Target value.
- * @param {number} t Amount to lerp (0 to 1).
- * @param {number} range Range of circle.
- * @return {number} lerped result.
- */
-o3djs.math.lerpCircular = function(a, b, t, range) {
- a = o3djs.math.modClamp(a, range);
- b = o3djs.math.modClamp(b, range);
- var delta = b - a;
- if (Math.abs(delta) > range * 0.5) {
- if (delta > 0) {
- b -= range;
- } else {
- b += range;
- }
- }
- return o3djs.math.modClamp(o3djs.math.lerpScalar(a, b, t), range);
-};
-
-/**
- * Lerps radians.
- * @param {number} a Start value.
- * @param {number} b Target value.
- * @param {number} t Amount to lerp (0 to 1).
- * @return {number} lerped result.
- */
-o3djs.math.lerpRadian = function(a, b, t) {
- return o3djs.math.lerpCircular(a, b, t, Math.PI * 2);
-};
-
-/**
- * Divides a vector by a scalar.
- * @param {!o3djs.math.Vector} v The vector.
- * @param {number} k The scalar.
- * @return {!o3djs.math.Vector} v The vector v divided by k.
- */
-o3djs.math.divVectorScalar = function(v, k) {
- var r = [];
- var vLength = v.length;
- for (var i = 0; i < vLength; ++i)
- r[i] = v[i] / k;
- return r;
-};
-
-/**
- * Computes the dot product of two vectors; assumes that a and b have
- * the same dimension.
- * @param {!o3djs.math.Vector} a Operand vector.
- * @param {!o3djs.math.Vector} b Operand vector.
- * @return {number} The dot product of a and b.
- */
-o3djs.math.dot = function(a, b) {
- var r = 0.0;
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i)
- r += a[i] * b[i];
- return r;
-};
-
-/**
- * Computes the cross product of two vectors; assumes both vectors have
- * three entries.
- * @param {!o3djs.math.Vector} a Operand vector.
- * @param {!o3djs.math.Vector} b Operand vector.
- * @return {!o3djs.math.Vector} The vector a cross b.
- */
-o3djs.math.cross = function(a, b) {
- return [a[1] * b[2] - a[2] * b[1],
- a[2] * b[0] - a[0] * b[2],
- a[0] * b[1] - a[1] * b[0]];
-};
-
-/**
- * Computes the Euclidean length of a vector, i.e. the square root of the
- * sum of the squares of the entries.
- * @param {!o3djs.math.Vector} a The vector.
- * @return {number} The length of a.
- */
-o3djs.math.length = function(a) {
- var r = 0.0;
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i)
- r += a[i] * a[i];
- return Math.sqrt(r);
-};
-
-/**
- * Computes the square of the Euclidean length of a vector, i.e. the sum
- * of the squares of the entries.
- * @param {!o3djs.math.Vector} a The vector.
- * @return {number} The square of the length of a.
- */
-o3djs.math.lengthSquared = function(a) {
- var r = 0.0;
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i)
- r += a[i] * a[i];
- return r;
-};
-
-/**
- * Computes the Euclidean distance between two vectors.
- * @param {!o3djs.math.Vector} a A vector.
- * @param {!o3djs.math.Vector} b A vector.
- * @return {number} The distance between a and b.
- */
-o3djs.math.distance = function(a, b) {
- var r = 0.0;
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i) {
- var t = a[i] - b[i];
- r += t * t;
- }
- return Math.sqrt(r);
-};
-
-/**
- * Computes the square of the Euclidean distance between two vectors.
- * @param {!o3djs.math.Vector} a A vector.
- * @param {!o3djs.math.Vector} b A vector.
- * @return {number} The distance between a and b.
- */
-o3djs.math.distanceSquared = function(a, b) {
- var r = 0.0;
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i) {
- var t = a[i] - b[i];
- r += t * t;
- }
- return r;
-};
-
-/**
- * Divides a vector by its Euclidean length and returns the quotient.
- * @param {!o3djs.math.Vector} a The vector.
- * @return {!o3djs.math.Vector} The normalized vector.
- */
-o3djs.math.normalize = function(a) {
- var r = [];
- var n = 0.0;
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i)
- n += a[i] * a[i];
- n = Math.sqrt(n);
- for (var i = 0; i < aLength; ++i)
- r[i] = a[i] / n;
- return r;
-};
-
-/**
- * Adds two matrices; assumes a and b are the same size.
- * @param {!o3djs.math.Matrix} a Operand matrix.
- * @param {!o3djs.math.Matrix} b Operand matrix.
- * @return {!o3djs.math.Matrix} The sum of a and b.
- */
-o3djs.math.addMatrix = function(a, b) {
- var r = [];
- var aLength = a.length;
- var a0Length = a[0].length;
- for (var i = 0; i < aLength; ++i) {
- var row = [];
- var ai = a[i];
- var bi = b[i];
- for (var j = 0; j < a0Length; ++j)
- row[j] = ai[j] + bi[j];
- r[i] = row;
- }
- return r;
-};
-
-/**
- * Subtracts two matrices; assumes a and b are the same size.
- * @param {!o3djs.math.Matrix} a Operand matrix.
- * @param {!o3djs.math.Matrix} b Operand matrix.
- * @return {!o3djs.math.Matrix} The sum of a and b.
- */
-o3djs.math.subMatrix = function(a, b) {
- var r = [];
- var aLength = a.length;
- var a0Length = a[0].length;
- for (var i = 0; i < aLength; ++i) {
- var row = [];
- var ai = a[i];
- var bi = b[i];
- for (var j = 0; j < a0Length; ++j)
- row[j] = ai[j] - bi[j];
- r[i] = row;
- }
- return r;
-};
-
-/**
- * Performs linear interpolation on two matrices.
- * Given matrices a and b and interpolation coefficient t, returns
- * (1 - t) * a + t * b.
- * @param {!o3djs.math.Matrix} a Operand matrix.
- * @param {!o3djs.math.Matrix} b Operand matrix.
- * @param {number} t Interpolation coefficient.
- * @return {!o3djs.math.Matrix} The weighted of a and b.
- */
-o3djs.math.lerpMatrix = function(a, b, t) {
- var r = [];
- var aLength = a.length;
- var a0Length = a[0].length;
- for (var i = 0; i < aLength; ++i) {
- var row = [];
- var ai = a[i];
- var bi = b[i];
- for (var j = 0; j < a0Length; ++j)
- row[j] = (1 - t) * ai[j] + t * bi[j];
- r[i] = row;
- }
- return r;
-};
-
-/**
- * Divides a matrix by a scalar.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @param {number} k The scalar.
- * @return {!o3djs.math.Matrix} The matrix m divided by k.
- */
-o3djs.math.divMatrixScalar = function(m, k) {
- var r = [];
- var mLength = m.length;
- var m0Length = m[0].length;
- for (var i = 0; i < mLength; ++i) {
- r[i] = [];
- for (var j = 0; j < m0Length; ++j)
- r[i][j] = m[i][j] / k;
- }
- return r;
-};
-
-/**
- * Negates a scalar.
- * @param {number} a The scalar.
- * @return {number} -a.
- */
-o3djs.math.negativeScalar = function(a) {
- return -a;
-};
-
-/**
- * Negates a vector.
- * @param {!o3djs.math.Vector} v The vector.
- * @return {!o3djs.math.Vector} -v.
- */
-o3djs.math.negativeVector = function(v) {
- var r = [];
- var vLength = v.length;
- for (var i = 0; i < vLength; ++i) {
- r[i] = -v[i];
- }
- return r;
-};
-
-/**
- * Negates a matrix.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @return {!o3djs.math.Matrix} -m.
- */
-o3djs.math.negativeMatrix = function(m) {
- var r = [];
- var mLength = m.length;
- var m0Length = m[0].length;
- for (var i = 0; i < mLength; ++i) {
- r[i] = [];
- for (var j = 0; j < m0Length; ++j)
- r[i][j] = -m[i][j];
- }
- return r;
-};
-
-/**
- * Copies a scalar.
- * @param {number} a The scalar.
- * @return {number} a.
- */
-o3djs.math.copyScalar = function(a) {
- return a;
-};
-
-/**
- * Copies a vector.
- * @param {!o3djs.math.Vector} v The vector.
- * @return {!o3djs.math.Vector} A copy of v.
- */
-o3djs.math.copyVector = function(v) {
- var r = [];
- for (var i = 0; i < v.length; i++)
- r[i] = v[i];
- return r;
-};
-
-/**
- * Copies a matrix.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @return {!o3djs.math.Matrix} A copy of m.
- */
-o3djs.math.copyMatrix = function(m) {
- var r = [];
- var mLength = m.length;
- for (var i = 0; i < mLength; ++i) {
- r[i] = [];
- for (var j = 0; j < m[i].length; j++) {
- r[i][j] = m[i][j];
- }
- }
- return r;
-};
-
-/**
- * Returns the elements of a matrix as a one-dimensional array. The
- * rows or columns (depending on whether the matrix is row-major or
- * column-major) are concatenated.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @return {!Array.<number>} The matrix's elements as a one-dimensional array.
- */
-o3djs.math.getMatrixElements = function(m) {
- var r = [];
- var mLength = m.length;
- var k = 0;
- for (var i = 0; i < mLength; i++) {
- for (var j = 0; j < m[i].length; j++) {
- r[k++] = m[i][j];
- }
- }
- return r;
-};
-
-/**
- * Multiplies two scalars.
- * @param {number} a Operand scalar.
- * @param {number} b Operand scalar.
- * @return {number} The product of a and b.
- */
-o3djs.math.mulScalarScalar = function(a, b) {
- return a * b;
-};
-
-/**
- * Multiplies a scalar by a vector.
- * @param {number} k The scalar.
- * @param {!o3djs.math.Vector} v The vector.
- * @return {!o3djs.math.Vector} The product of k and v.
- */
-o3djs.math.mulScalarVector = function(k, v) {
- var r = [];
- var vLength = v.length;
- for (var i = 0; i < vLength; ++i) {
- r[i] = k * v[i];
- }
- return r;
-};
-
-/**
- * Multiplies a vector by a scalar.
- * @param {!o3djs.math.Vector} v The vector.
- * @param {number} k The scalar.
- * @return {!o3djs.math.Vector} The product of k and v.
- */
-o3djs.math.mulVectorScalar = function(v, k) {
- return o3djs.math.mulScalarVector(k, v);
-};
-
-/**
- * Multiplies a scalar by a matrix.
- * @param {number} k The scalar.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @return {!o3djs.math.Matrix} The product of m and k.
- */
-o3djs.math.mulScalarMatrix = function(k, m) {
- var r = [];
- var mLength = m.length;
- var m0Length = m[0].length;
- for (var i = 0; i < mLength; ++i) {
- r[i] = [];
- for (var j = 0; j < m0Length; ++j)
- r[i][j] = k * m[i][j];
- }
- return r;
-};
-
-/**
- * Multiplies a matrix by a scalar.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @param {number} k The scalar.
- * @return {!o3djs.math.Matrix} The product of m and k.
- */
-o3djs.math.mulMatrixScalar = function(m, k) {
- return o3djs.math.mulScalarMatrix(k, m);
-};
-
-/**
- * Multiplies a vector by another vector (component-wise); assumes a and
- * b have the same length.
- * @param {!o3djs.math.Vector} a Operand vector.
- * @param {!o3djs.math.Vector} b Operand vector.
- * @return {!o3djs.math.Vector} The vector of products of entries of a and
- * b.
- */
-o3djs.math.mulVectorVector = function(a, b) {
- var r = [];
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i)
- r[i] = a[i] * b[i];
- return r;
-};
-
-/**
- * Divides a vector by another vector (component-wise); assumes a and
- * b have the same length.
- * @param {!o3djs.math.Vector} a Operand vector.
- * @param {!o3djs.math.Vector} b Operand vector.
- * @return {!o3djs.math.Vector} The vector of quotients of entries of a and
- * b.
- */
-o3djs.math.divVectorVector = function(a, b) {
- var r = [];
- var aLength = a.length;
- for (var i = 0; i < aLength; ++i)
- r[i] = a[i] / b[i];
- return r;
-};
-
-/**
- * Multiplies a vector by a matrix; treats the vector as a row vector; assumes
- * matrix entries are accessed in [row][column] fashion.
- * @param {!o3djs.math.Vector} v The vector.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @return {!o3djs.math.Vector} The product of v and m as a row vector.
- */
-o3djs.math.rowMajor.mulVectorMatrix = function(v, m) {
- var r = [];
- var m0Length = m[0].length;
- var vLength = v.length;
- for (var i = 0; i < m0Length; ++i) {
- r[i] = 0.0;
- for (var j = 0; j < vLength; ++j)
- r[i] += v[j] * m[j][i];
- }
- return r;
-};
-
-/**
- * Multiplies a vector by a matrix; treats the vector as a row vector; assumes
- * matrix entries are accessed in [column][row] fashion.
- * @param {!o3djs.math.Vector} v The vector.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @return {!o3djs.math.Vector} The product of v and m as a row vector.
- */
-o3djs.math.columnMajor.mulVectorMatrix = function(v, m) {
- var r = [];
- var mLength = m.length;
- var vLength = v.length;
- for (var i = 0; i < mLength; ++i) {
- r[i] = 0.0;
- var column = m[i];
- for (var j = 0; j < vLength; ++j)
- r[i] += v[j] * column[j];
- }
- return r;
-};
-
-/**
- * Multiplies a vector by a matrix; treats the vector as a row vector.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @param {!o3djs.math.Vector} v The vector.
- * @return {!o3djs.math.Vector} The product of m and v as a row vector.
- */
-o3djs.math.mulVectorMatrix = null;
-
-/**
- * Multiplies a matrix by a vector; treats the vector as a column vector.
- * assumes matrix entries are accessed in [row][column] fashion.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @param {!o3djs.math.Vector} v The vector.
- * @return {!o3djs.math.Vector} The product of m and v as a column vector.
- */
-o3djs.math.rowMajor.mulMatrixVector = function(m, v) {
- var r = [];
- var mLength = m.length;
- var m0Length = m[0].length;
- for (var i = 0; i < mLength; ++i) {
- r[i] = 0.0;
- var row = m[i];
- for (var j = 0; j < m0Length; ++j)
- r[i] += row[j] * v[j];
- }
- return r;
-};
-
-/**
- * Multiplies a matrix by a vector; treats the vector as a column vector;
- * assumes matrix entries are accessed in [column][row] fashion.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @param {!o3djs.math.Vector} v The vector.
- * @return {!o3djs.math.Vector} The product of m and v as a column vector.
- */
-o3djs.math.columnMajor.mulMatrixVector = function(m, v) {
- var r = [];
- var m0Length = m[0].length;
- var vLength = v.length;
- for (var i = 0; i < m0Length; ++i) {
- r[i] = 0.0;
- for (var j = 0; j < vLength; ++j)
- r[i] += v[j] * m[j][i];
- }
- return r;
-};
-
-/**
- * Multiplies a matrix by a vector; treats the vector as a column vector.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @param {!o3djs.math.Vector} v The vector.
- * @return {!o3djs.math.Vector} The product of m and v as a column vector.
- */
-o3djs.math.mulMatrixVector = null;
-
-/**
- * Multiplies two 2-by-2 matrices; assumes that the given matrices are 2-by-2;
- * assumes matrix entries are accessed in [row][column] fashion.
- * @param {!o3djs.math.Matrix2} a The matrix on the left.
- * @param {!o3djs.math.Matrix2} b The matrix on the right.
- * @return {!o3djs.math.Matrix2} The matrix product of a and b.
- */
-o3djs.math.rowMajor.mulMatrixMatrix2 = function(a, b) {
- var a0 = a[0];
- var a1 = a[1];
- var b0 = b[0];
- var b1 = b[1];
- var a00 = a0[0];
- var a01 = a0[1];
- var a10 = a1[0];
- var a11 = a1[1];
- var b00 = b0[0];
- var b01 = b0[1];
- var b10 = b1[0];
- var b11 = b1[1];
- return [[a00 * b00 + a01 * b10, a00 * b01 + a01 * b11],
- [a10 * b00 + a11 * b10, a10 * b01 + a11 * b11]];
-};
-
-/**
- * Multiplies two 2-by-2 matrices; assumes that the given matrices are 2-by-2;
- * assumes matrix entries are accessed in [column][row] fashion.
- * @param {!o3djs.math.Matrix2} a The matrix on the left.
- * @param {!o3djs.math.Matrix2} b The matrix on the right.
- * @return {!o3djs.math.Matrix2} The matrix product of a and b.
- */
-o3djs.math.columnMajor.mulMatrixMatrix2 = function(a, b) {
- var a0 = a[0];
- var a1 = a[1];
- var b0 = b[0];
- var b1 = b[1];
- var a00 = a0[0];
- var a01 = a0[1];
- var a10 = a1[0];
- var a11 = a1[1];
- var b00 = b0[0];
- var b01 = b0[1];
- var b10 = b1[0];
- var b11 = b1[1];
- return [[a00 * b00 + a10 * b01, a01 * b00 + a11 * b01],
- [a00 * b10 + a10 * b11, a01 * b10 + a11 * b11]];
-};
-
-/**
- * Multiplies two 2-by-2 matrices.
- * @param {!o3djs.math.Matrix2} a The matrix on the left.
- * @param {!o3djs.math.Matrix2} b The matrix on the right.
- * @return {!o3djs.math.Matrix2} The matrix product of a and b.
- */
-o3djs.math.mulMatrixMatrix2 = null;
-
-
-/**
- * Multiplies two 3-by-3 matrices; assumes that the given matrices are 3-by-3;
- * assumes matrix entries are accessed in [row][column] fashion.
- * @param {!o3djs.math.Matrix3} a The matrix on the left.
- * @param {!o3djs.math.Matrix3} b The matrix on the right.
- * @return {!o3djs.math.Matrix3} The matrix product of a and b.
- */
-o3djs.math.rowMajor.mulMatrixMatrix3 = function(a, b) {
- var a0 = a[0];
- var a1 = a[1];
- var a2 = a[2];
- var b0 = b[0];
- var b1 = b[1];
- var b2 = b[2];
- var a00 = a0[0];
- var a01 = a0[1];
- var a02 = a0[2];
- var a10 = a1[0];
- var a11 = a1[1];
- var a12 = a1[2];
- var a20 = a2[0];
- var a21 = a2[1];
- var a22 = a2[2];
- var b00 = b0[0];
- var b01 = b0[1];
- var b02 = b0[2];
- var b10 = b1[0];
- var b11 = b1[1];
- var b12 = b1[2];
- var b20 = b2[0];
- var b21 = b2[1];
- var b22 = b2[2];
- return [[a00 * b00 + a01 * b10 + a02 * b20,
- a00 * b01 + a01 * b11 + a02 * b21,
- a00 * b02 + a01 * b12 + a02 * b22],
- [a10 * b00 + a11 * b10 + a12 * b20,
- a10 * b01 + a11 * b11 + a12 * b21,
- a10 * b02 + a11 * b12 + a12 * b22],
- [a20 * b00 + a21 * b10 + a22 * b20,
- a20 * b01 + a21 * b11 + a22 * b21,
- a20 * b02 + a21 * b12 + a22 * b22]];
-};
-
-/**
- * Multiplies two 3-by-3 matrices; assumes that the given matrices are 3-by-3;
- * assumes matrix entries are accessed in [column][row] fashion.
- * @param {!o3djs.math.Matrix3} a The matrix on the left.
- * @param {!o3djs.math.Matrix3} b The matrix on the right.
- * @return {!o3djs.math.Matrix3} The matrix product of a and b.
- */
-o3djs.math.columnMajor.mulMatrixMatrix3 = function(a, b) {
- var a0 = a[0];
- var a1 = a[1];
- var a2 = a[2];
- var b0 = b[0];
- var b1 = b[1];
- var b2 = b[2];
- var a00 = a0[0];
- var a01 = a0[1];
- var a02 = a0[2];
- var a10 = a1[0];
- var a11 = a1[1];
- var a12 = a1[2];
- var a20 = a2[0];
- var a21 = a2[1];
- var a22 = a2[2];
- var b00 = b0[0];
- var b01 = b0[1];
- var b02 = b0[2];
- var b10 = b1[0];
- var b11 = b1[1];
- var b12 = b1[2];
- var b20 = b2[0];
- var b21 = b2[1];
- var b22 = b2[2];
- return [[a00 * b00 + a10 * b01 + a20 * b02,
- a01 * b00 + a11 * b01 + a21 * b02,
- a02 * b00 + a12 * b01 + a22 * b02],
- [a00 * b10 + a10 * b11 + a20 * b12,
- a01 * b10 + a11 * b11 + a21 * b12,
- a02 * b10 + a12 * b11 + a22 * b12],
- [a00 * b20 + a10 * b21 + a20 * b22,
- a01 * b20 + a11 * b21 + a21 * b22,
- a02 * b20 + a12 * b21 + a22 * b22]];
-};
-
-/**
- * Multiplies two 3-by-3 matrices; assumes that the given matrices are 3-by-3.
- * @param {!o3djs.math.Matrix3} a The matrix on the left.
- * @param {!o3djs.math.Matrix3} b The matrix on the right.
- * @return {!o3djs.math.Matrix3} The matrix product of a and b.
- */
-o3djs.math.mulMatrixMatrix3 = null;
-
-/**
- * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4;
- * assumes matrix entries are accessed in [row][column] fashion.
- * @param {!o3djs.math.Matrix4} a The matrix on the left.
- * @param {!o3djs.math.Matrix4} b The matrix on the right.
- * @return {!o3djs.math.Matrix4} The matrix product of a and b.
- */
-o3djs.math.rowMajor.mulMatrixMatrix4 = function(a, b) {
- var a0 = a[0];
- var a1 = a[1];
- var a2 = a[2];
- var a3 = a[3];
- var b0 = b[0];
- var b1 = b[1];
- var b2 = b[2];
- var b3 = b[3];
- var a00 = a0[0];
- var a01 = a0[1];
- var a02 = a0[2];
- var a03 = a0[3];
- var a10 = a1[0];
- var a11 = a1[1];
- var a12 = a1[2];
- var a13 = a1[3];
- var a20 = a2[0];
- var a21 = a2[1];
- var a22 = a2[2];
- var a23 = a2[3];
- var a30 = a3[0];
- var a31 = a3[1];
- var a32 = a3[2];
- var a33 = a3[3];
- var b00 = b0[0];
- var b01 = b0[1];
- var b02 = b0[2];
- var b03 = b0[3];
- var b10 = b1[0];
- var b11 = b1[1];
- var b12 = b1[2];
- var b13 = b1[3];
- var b20 = b2[0];
- var b21 = b2[1];
- var b22 = b2[2];
- var b23 = b2[3];
- var b30 = b3[0];
- var b31 = b3[1];
- var b32 = b3[2];
- var b33 = b3[3];
- return [[a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30,
- a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31,
- a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32,
- a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33],
- [a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30,
- a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31,
- a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32,
- a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33],
- [a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30,
- a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31,
- a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32,
- a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33],
- [a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30,
- a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31,
- a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32,
- a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33]];
-};
-
-/**
- * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4;
- * assumes matrix entries are accessed in [column][row] fashion.
- * @param {!o3djs.math.Matrix4} a The matrix on the left.
- * @param {!o3djs.math.Matrix4} b The matrix on the right.
- * @return {!o3djs.math.Matrix4} The matrix product of a and b.
- */
-o3djs.math.columnMajor.mulMatrixMatrix4 = function(a, b) {
- var a0 = a[0];
- var a1 = a[1];
- var a2 = a[2];
- var a3 = a[3];
- var b0 = b[0];
- var b1 = b[1];
- var b2 = b[2];
- var b3 = b[3];
- var a00 = a0[0];
- var a01 = a0[1];
- var a02 = a0[2];
- var a03 = a0[3];
- var a10 = a1[0];
- var a11 = a1[1];
- var a12 = a1[2];
- var a13 = a1[3];
- var a20 = a2[0];
- var a21 = a2[1];
- var a22 = a2[2];
- var a23 = a2[3];
- var a30 = a3[0];
- var a31 = a3[1];
- var a32 = a3[2];
- var a33 = a3[3];
- var b00 = b0[0];
- var b01 = b0[1];
- var b02 = b0[2];
- var b03 = b0[3];
- var b10 = b1[0];
- var b11 = b1[1];
- var b12 = b1[2];
- var b13 = b1[3];
- var b20 = b2[0];
- var b21 = b2[1];
- var b22 = b2[2];
- var b23 = b2[3];
- var b30 = b3[0];
- var b31 = b3[1];
- var b32 = b3[2];
- var b33 = b3[3];
- return [[a00 * b00 + a10 * b01 + a20 * b02 + a30 * b03,
- a01 * b00 + a11 * b01 + a21 * b02 + a31 * b03,
- a02 * b00 + a12 * b01 + a22 * b02 + a32 * b03,
- a03 * b00 + a13 * b01 + a23 * b02 + a33 * b03],
- [a00 * b10 + a10 * b11 + a20 * b12 + a30 * b13,
- a01 * b10 + a11 * b11 + a21 * b12 + a31 * b13,
- a02 * b10 + a12 * b11 + a22 * b12 + a32 * b13,
- a03 * b10 + a13 * b11 + a23 * b12 + a33 * b13],
- [a00 * b20 + a10 * b21 + a20 * b22 + a30 * b23,
- a01 * b20 + a11 * b21 + a21 * b22 + a31 * b23,
- a02 * b20 + a12 * b21 + a22 * b22 + a32 * b23,
- a03 * b20 + a13 * b21 + a23 * b22 + a33 * b23],
- [a00 * b30 + a10 * b31 + a20 * b32 + a30 * b33,
- a01 * b30 + a11 * b31 + a21 * b32 + a31 * b33,
- a02 * b30 + a12 * b31 + a22 * b32 + a32 * b33,
- a03 * b30 + a13 * b31 + a23 * b32 + a33 * b33]];
-};
-
-/**
- * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4.
- * @param {!o3djs.math.Matrix4} a The matrix on the left.
- * @param {!o3djs.math.Matrix4} b The matrix on the right.
- * @return {!o3djs.math.Matrix4} The matrix product of a and b.
- */
-o3djs.math.mulMatrixMatrix4 = null;
-
-/**
- * Multiplies two matrices; assumes that the sizes of the matrices are
- * appropriately compatible; assumes matrix entries are accessed in
- * [row][column] fashion.
- * @param {!o3djs.math.Matrix} a The matrix on the left.
- * @param {!o3djs.math.Matrix} b The matrix on the right.
- * @return {!o3djs.math.Matrix} The matrix product of a and b.
- */
-o3djs.math.rowMajor.mulMatrixMatrix = function(a, b) {
- var r = [];
- var aRows = a.length;
- var bColumns = b[0].length;
- var bRows = b.length;
- for (var i = 0; i < aRows; ++i) {
- var v = []; // v becomes a row of the answer.
- var ai = a[i]; // ith row of a.
- for (var j = 0; j < bColumns; ++j) {
- v[j] = 0.0;
- for (var k = 0; k < bRows; ++k)
- v[j] += ai[k] * b[k][j]; // kth row, jth column.
- }
- r[i] = v;
- }
- return r;
-};
-
-/**
- * Multiplies two matrices; assumes that the sizes of the matrices are
- * appropriately compatible; assumes matrix entries are accessed in
- * [row][column] fashion.
- * @param {!o3djs.math.Matrix} a The matrix on the left.
- * @param {!o3djs.math.Matrix} b The matrix on the right.
- * @return {!o3djs.math.Matrix} The matrix product of a and b.
- */
-o3djs.math.columnMajor.mulMatrixMatrix = function(a, b) {
- var r = [];
- var bColumns = b.length;
- var aRows = a[0].length;
- var aColumns = a.length;
- for (var i = 0; i < bColumns; ++i) {
- var v = []; // v becomes a column of the answer.
- var bi = b[i]; // ith column of b.
- for (var j = 0; j < aRows; ++j) {
- v[j] = 0.0;
- for (var k = 0; k < aColumns; ++k)
- v[j] += bi[k] * a[k][j]; // kth column, jth row.
- }
- r[i] = v;
- }
- return r;
-};
-
-/**
- * Multiplies two matrices; assumes that the sizes of the matrices are
- * appropriately compatible.
- * @param {!o3djs.math.Matrix} a The matrix on the left.
- * @param {!o3djs.math.Matrix} b The matrix on the right.
- * @return {!o3djs.math.Matrix} The matrix product of a and b.
- */
-o3djs.math.mulMatrixMatrix = null;
-
-/**
- * Gets the jth column of the given matrix m; assumes matrix entries are
- * accessed in [row][column] fashion.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @param {number} j The index of the desired column.
- * @return {!o3djs.math.Vector} The jth column of m as a vector.
- */
-o3djs.math.rowMajor.column = function(m, j) {
- var r = [];
- var mLength = m.length;
- for (var i = 0; i < mLength; ++i) {
- r[i] = m[i][j];
- }
- return r;
-};
-
-/**
- * Gets the jth column of the given matrix m; assumes matrix entries are
- * accessed in [column][row] fashion.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @param {number} j The index of the desired column.
- * @return {!o3djs.math.Vector} The jth column of m as a vector.
- */
-o3djs.math.columnMajor.column = function(m, j) {
- return m[j].slice();
-};
-
-/**
- * Gets the jth column of the given matrix m.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @param {number} j The index of the desired column.
- * @return {!o3djs.math.Vector} The jth column of m as a vector.
- */
-o3djs.math.column = null;
-
-/**
- * Gets the ith row of the given matrix m; assumes matrix entries are
- * accessed in [row][column] fashion.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @param {number} i The index of the desired row.
- * @return {!o3djs.math.Vector} The ith row of m.
- */
-o3djs.math.rowMajor.row = function(m, i) {
- return m[i].slice();
-};
-
-/**
- * Gets the ith row of the given matrix m; assumes matrix entries are
- * accessed in [column][row] fashion.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @param {number} i The index of the desired row.
- * @return {!o3djs.math.Vector} The ith row of m.
- */
-o3djs.math.columnMajor.row = function(m, i) {
- var r = [];
- var mLength = m.length;
- for (var j = 0; j < mLength; ++j) {
- r[j] = m[j][i];
- }
- return r;
-};
-
-/**
- * Gets the ith row of the given matrix m.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @param {number} i The index of the desired row.
- * @return {!o3djs.math.Vector} The ith row of m.
- */
-o3djs.math.row = null;
-
-/**
- * Creates an n-by-n identity matrix.
- * @param {number} n The dimension of the identity matrix required.
- * @return {!o3djs.math.Matrix} An n-by-n identity matrix.
- */
-o3djs.math.identity = function(n) {
- var r = [];
- for (var j = 0; j < n; ++j) {
- r[j] = [];
- for (var i = 0; i < n; ++i)
- r[j][i] = (i == j) ? 1 : 0;
- }
- return r;
-};
-
-/**
- * Takes the transpose of a matrix.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @return {!o3djs.math.Matrix} The transpose of m.
- */
-o3djs.math.transpose = function(m) {
- var r = [];
- var m0Length = m[0].length;
- var mLength = m.length;
- for (var j = 0; j < m0Length; ++j) {
- r[j] = [];
- for (var i = 0; i < mLength; ++i)
- r[j][i] = m[i][j];
- }
- return r;
-};
-
-/**
- * Computes the trace (sum of the diagonal entries) of a square matrix;
- * assumes m is square.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @return {number} The trace of m.
- */
-o3djs.math.trace = function(m) {
- var r = 0.0;
- var mLength = m.length;
- for (var i = 0; i < mLength; ++i)
- r += m[i][i];
- return r;
-};
-
-/**
- * Computes the determinant of a 1-by-1 matrix.
- * @param {!o3djs.math.Matrix1} m The matrix.
- * @return {number} The determinant of m.
- */
-o3djs.math.det1 = function(m) {
- return m[0][0];
-};
-
-/**
- * Computes the determinant of a 2-by-2 matrix.
- * @param {!o3djs.math.Matrix2} m The matrix.
- * @return {number} The determinant of m.
- */
-o3djs.math.det2 = function(m) {
- return m[0][0] * m[1][1] - m[0][1] * m[1][0];
-};
-
-/**
- * Computes the determinant of a 3-by-3 matrix.
- * @param {!o3djs.math.Matrix3} m The matrix.
- * @return {number} The determinant of m.
- */
-o3djs.math.det3 = function(m) {
- return m[2][2] * (m[0][0] * m[1][1] - m[0][1] * m[1][0]) -
- m[2][1] * (m[0][0] * m[1][2] - m[0][2] * m[1][0]) +
- m[2][0] * (m[0][1] * m[1][2] - m[0][2] * m[1][1]);
-};
-
-/**
- * Computes the determinant of a 4-by-4 matrix.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @return {number} The determinant of m.
- */
-o3djs.math.det4 = function(m) {
- var t01 = m[0][0] * m[1][1] - m[0][1] * m[1][0];
- var t02 = m[0][0] * m[1][2] - m[0][2] * m[1][0];
- var t03 = m[0][0] * m[1][3] - m[0][3] * m[1][0];
- var t12 = m[0][1] * m[1][2] - m[0][2] * m[1][1];
- var t13 = m[0][1] * m[1][3] - m[0][3] * m[1][1];
- var t23 = m[0][2] * m[1][3] - m[0][3] * m[1][2];
- return m[3][3] * (m[2][2] * t01 - m[2][1] * t02 + m[2][0] * t12) -
- m[3][2] * (m[2][3] * t01 - m[2][1] * t03 + m[2][0] * t13) +
- m[3][1] * (m[2][3] * t02 - m[2][2] * t03 + m[2][0] * t23) -
- m[3][0] * (m[2][3] * t12 - m[2][2] * t13 + m[2][1] * t23);
-};
-
-/**
- * Computes the inverse of a 1-by-1 matrix.
- * @param {!o3djs.math.Matrix1} m The matrix.
- * @return {!o3djs.math.Matrix1} The inverse of m.
- */
-o3djs.math.inverse1 = function(m) {
- return [[1.0 / m[0][0]]];
-};
-
-/**
- * Computes the inverse of a 2-by-2 matrix.
- * @param {!o3djs.math.Matrix2} m The matrix.
- * @return {!o3djs.math.Matrix2} The inverse of m.
- */
-o3djs.math.inverse2 = function(m) {
- var d = 1.0 / (m[0][0] * m[1][1] - m[0][1] * m[1][0]);
- return [[d * m[1][1], -d * m[0][1]], [-d * m[1][0], d * m[0][0]]];
-};
-
-/**
- * Computes the inverse of a 3-by-3 matrix.
- * @param {!o3djs.math.Matrix3} m The matrix.
- * @return {!o3djs.math.Matrix3} The inverse of m.
- */
-o3djs.math.inverse3 = function(m) {
- var t00 = m[1][1] * m[2][2] - m[1][2] * m[2][1];
- var t10 = m[0][1] * m[2][2] - m[0][2] * m[2][1];
- var t20 = m[0][1] * m[1][2] - m[0][2] * m[1][1];
- var d = 1.0 / (m[0][0] * t00 - m[1][0] * t10 + m[2][0] * t20);
- return [[d * t00, -d * t10, d * t20],
- [-d * (m[1][0] * m[2][2] - m[1][2] * m[2][0]),
- d * (m[0][0] * m[2][2] - m[0][2] * m[2][0]),
- -d * (m[0][0] * m[1][2] - m[0][2] * m[1][0])],
- [d * (m[1][0] * m[2][1] - m[1][1] * m[2][0]),
- -d * (m[0][0] * m[2][1] - m[0][1] * m[2][0]),
- d * (m[0][0] * m[1][1] - m[0][1] * m[1][0])]];
-};
-
-/**
- * Computes the inverse of a 4-by-4 matrix.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @return {!o3djs.math.Matrix4} The inverse of m.
- */
-o3djs.math.inverse4 = function(m) {
- var tmp_0 = m[2][2] * m[3][3];
- var tmp_1 = m[3][2] * m[2][3];
- var tmp_2 = m[1][2] * m[3][3];
- var tmp_3 = m[3][2] * m[1][3];
- var tmp_4 = m[1][2] * m[2][3];
- var tmp_5 = m[2][2] * m[1][3];
- var tmp_6 = m[0][2] * m[3][3];
- var tmp_7 = m[3][2] * m[0][3];
- var tmp_8 = m[0][2] * m[2][3];
- var tmp_9 = m[2][2] * m[0][3];
- var tmp_10 = m[0][2] * m[1][3];
- var tmp_11 = m[1][2] * m[0][3];
- var tmp_12 = m[2][0] * m[3][1];
- var tmp_13 = m[3][0] * m[2][1];
- var tmp_14 = m[1][0] * m[3][1];
- var tmp_15 = m[3][0] * m[1][1];
- var tmp_16 = m[1][0] * m[2][1];
- var tmp_17 = m[2][0] * m[1][1];
- var tmp_18 = m[0][0] * m[3][1];
- var tmp_19 = m[3][0] * m[0][1];
- var tmp_20 = m[0][0] * m[2][1];
- var tmp_21 = m[2][0] * m[0][1];
- var tmp_22 = m[0][0] * m[1][1];
- var tmp_23 = m[1][0] * m[0][1];
-
- var t0 = (tmp_0 * m[1][1] + tmp_3 * m[2][1] + tmp_4 * m[3][1]) -
- (tmp_1 * m[1][1] + tmp_2 * m[2][1] + tmp_5 * m[3][1]);
- var t1 = (tmp_1 * m[0][1] + tmp_6 * m[2][1] + tmp_9 * m[3][1]) -
- (tmp_0 * m[0][1] + tmp_7 * m[2][1] + tmp_8 * m[3][1]);
- var t2 = (tmp_2 * m[0][1] + tmp_7 * m[1][1] + tmp_10 * m[3][1]) -
- (tmp_3 * m[0][1] + tmp_6 * m[1][1] + tmp_11 * m[3][1]);
- var t3 = (tmp_5 * m[0][1] + tmp_8 * m[1][1] + tmp_11 * m[2][1]) -
- (tmp_4 * m[0][1] + tmp_9 * m[1][1] + tmp_10 * m[2][1]);
-
- var d = 1.0 / (m[0][0] * t0 + m[1][0] * t1 + m[2][0] * t2 + m[3][0] * t3);
-
- var row0 = [d * t0, d * t1, d * t2, d * t3];
- var row1 = [d * ((tmp_1 * m[1][0] + tmp_2 * m[2][0] + tmp_5 * m[3][0]) -
- (tmp_0 * m[1][0] + tmp_3 * m[2][0] + tmp_4 * m[3][0])),
- d * ((tmp_0 * m[0][0] + tmp_7 * m[2][0] + tmp_8 * m[3][0]) -
- (tmp_1 * m[0][0] + tmp_6 * m[2][0] + tmp_9 * m[3][0])),
- d * ((tmp_3 * m[0][0] + tmp_6 * m[1][0] + tmp_11 * m[3][0]) -
- (tmp_2 * m[0][0] + tmp_7 * m[1][0] + tmp_10 * m[3][0])),
- d * ((tmp_4 * m[0][0] + tmp_9 * m[1][0] + tmp_10 * m[2][0]) -
- (tmp_5 * m[0][0] + tmp_8 * m[1][0] + tmp_11 * m[2][0]))];
- var row2 =[d * ((tmp_12 * m[1][3] + tmp_15 * m[2][3] + tmp_16 * m[3][3]) -
- (tmp_13 * m[1][3] + tmp_14 * m[2][3] + tmp_17 * m[3][3])),
- d * ((tmp_13 * m[0][3] + tmp_18 * m[2][3] + tmp_21 * m[3][3]) -
- (tmp_12 * m[0][3] + tmp_19 * m[2][3] + tmp_20 * m[3][3])),
- d * ((tmp_14 * m[0][3] + tmp_19 * m[1][3] + tmp_22 * m[3][3]) -
- (tmp_15 * m[0][3] + tmp_18 * m[1][3] + tmp_23 * m[3][3])),
- d * ((tmp_17 * m[0][3] + tmp_20 * m[1][3] + tmp_23 * m[2][3]) -
- (tmp_16 * m[0][3] + tmp_21 * m[1][3] + tmp_22 * m[2][3]))];
- var row3 = [d * ((tmp_14 * m[2][2] + tmp_17 * m[3][2] + tmp_13 * m[1][2]) -
- (tmp_16 * m[3][2] + tmp_12 * m[1][2] + tmp_15 * m[2][2])),
- d * ((tmp_20 * m[3][2] + tmp_12 * m[0][2] + tmp_19 * m[2][2]) -
- (tmp_18 * m[2][2] + tmp_21 * m[3][2] + tmp_13 * m[0][2])),
- d * ((tmp_18 * m[1][2] + tmp_23 * m[3][2] + tmp_15 * m[0][2]) -
- (tmp_22 * m[3][2] + tmp_14 * m[0][2] + tmp_19 * m[1][2])),
- d * ((tmp_22 * m[2][2] + tmp_16 * m[0][2] + tmp_21 * m[1][2]) -
- (tmp_20 * m[1][2] + tmp_23 * m[2][2] + tmp_17 * m[0][2]))];
- return [row0, row1, row2, row3];
-};
-
-/**
- * Computes the determinant of the cofactor matrix obtained by removal
- * of a specified row and column. This is a helper function for the general
- * determinant and matrix inversion functions.
- * @param {!o3djs.math.Matrix} a The original matrix.
- * @param {number} x The row to be removed.
- * @param {number} y The column to be removed.
- * @return {number} The determinant of the matrix obtained by removing
- * row x and column y from a.
- */
-o3djs.math.codet = function(a, x, y) {
- var size = a.length;
- var b = [];
- var ai = 0;
- for (var bi = 0; bi < size - 1; ++bi) {
- if (ai == x)
- ai++;
- b[bi] = [];
- var aj = 0;
- for (var bj = 0; bj < size - 1; ++bj) {
- if (aj == y)
- aj++;
- b[bi][bj] = a[ai][aj];
- aj++;
- }
- ai++;
- }
- return o3djs.math.det(b);
-};
-
-/**
- * Computes the determinant of an arbitrary square matrix.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @return {number} the determinant of m.
- */
-o3djs.math.det = function(m) {
- var d = m.length;
- if (d <= 4) {
- return o3djs.math['det' + d](m);
- }
- var r = 0.0;
- var sign = 1;
- var row = m[0];
- var mLength = m.length;
- for (var y = 0; y < mLength; y++) {
- r += sign * row[y] * o3djs.math.codet(m, 0, y);
- sign *= -1;
- }
- return r;
-};
-
-/**
- * Computes the inverse of an arbitrary square matrix.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @return {!o3djs.math.Matrix} The inverse of m.
- */
-o3djs.math.inverse = function(m) {
- var d = m.length;
- if (d <= 4) {
- return o3djs.math['inverse' + d](m);
- }
- var r = [];
- var size = m.length;
- for (var j = 0; j < size; ++j) {
- r[j] = [];
- for (var i = 0; i < size; ++i)
- r[j][i] = ((i + j) % 2 ? -1 : 1) * o3djs.math.codet(m, i, j);
- }
- return o3djs.math.divMatrixScalar(r, o3djs.math.det(m));
-};
-
-/**
- * Performs Graham-Schmidt orthogonalization on the vectors which make up the
- * given matrix and returns the result in the rows of a new matrix. When
- * multiplying many orthogonal matrices together, errors can accumulate causing
- * the product to fail to be orthogonal. This function can be used to correct
- * that.
- * @param {!o3djs.math.Matrix} m The matrix.
- * @return {!o3djs.math.Matrix} A matrix whose rows are obtained from the
- * rows of m by the Graham-Schmidt process.
- */
-o3djs.math.orthonormalize = function(m) {
- var r = [];
- var mLength = m.length;
- for (var i = 0; i < mLength; ++i) {
- var v = m[i];
- for (var j = 0; j < i; ++j) {
- v = o3djs.math.subVector(v, o3djs.math.mulScalarVector(
- o3djs.math.dot(r[j], m[i]), r[j]));
- }
- r[i] = o3djs.math.normalize(v);
- }
- return r;
-};
-
-/**
- * Computes the inverse of a 4-by-4 matrix.
- * Note: It is faster to call this than o3djs.math.inverse.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @return {!o3djs.math.Matrix4} The inverse of m.
- */
-o3djs.math.matrix4.inverse = function(m) {
- return o3djs.math.inverse4(m);
-};
-
-/**
- * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4.
- * Note: It is faster to call this than o3djs.math.mul.
- * @param {!o3djs.math.Matrix4} a The matrix on the left.
- * @param {!o3djs.math.Matrix4} b The matrix on the right.
- * @return {!o3djs.math.Matrix4} The matrix product of a and b.
- */
-o3djs.math.matrix4.mul = function(a, b) {
- return o3djs.math.mulMatrixMatrix4(a, b);
-};
-
-/**
- * Computes the determinant of a 4-by-4 matrix.
- * Note: It is faster to call this than o3djs.math.det.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @return {number} The determinant of m.
- */
-o3djs.math.matrix4.det = function(m) {
- return o3djs.math.det4(m);
-};
-
-/**
- * Copies a Matrix4.
- * Note: It is faster to call this than o3djs.math.copy.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @return {!o3djs.math.Matrix4} A copy of m.
- */
-o3djs.math.matrix4.copy = function(m) {
- return o3djs.math.copyMatrix(m);
-};
-
-/**
- * Sets the upper 3-by-3 block of matrix a to the upper 3-by-3 block of matrix
- * b; assumes that a and b are big enough to contain an upper 3-by-3 block.
- * @param {!o3djs.math.Matrix4} a A matrix.
- * @param {!o3djs.math.Matrix3} b A 3-by-3 matrix.
- * @return {!o3djs.math.Matrix4} a once modified.
- */
-o3djs.math.matrix4.setUpper3x3 = function(a, b) {
- var b0 = b[0];
- var b1 = b[1];
- var b2 = b[2];
-
- a[0].splice(0, 3, b0[0], b0[1], b0[2]);
- a[1].splice(0, 3, b1[0], b1[1], b1[2]);
- a[2].splice(0, 3, b2[0], b2[1], b2[2]);
-
- return a;
-};
-
-/**
- * Returns a 3-by-3 matrix mimicking the upper 3-by-3 block of m; assumes m
- * is big enough to contain an upper 3-by-3 block.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @return {!o3djs.math.Matrix3} The upper 3-by-3 block of m.
- */
-o3djs.math.matrix4.getUpper3x3 = function(m) {
- return [m[0].slice(0, 3), m[1].slice(0, 3), m[2].slice(0, 3)];
-};
-
-/**
- * Sets the translation component of a 4-by-4 matrix to the given
- * vector.
- * @param {!o3djs.math.Matrix4} a The matrix.
- * @param {(!o3djs.math.Vector3|!o3djs.math.Vector4)} v The vector.
- * @return {!o3djs.math.Matrix4} a once modified.
- */
-o3djs.math.matrix4.setTranslation = function(a, v) {
- a[3].splice(0, 4, v[0], v[1], v[2], 1);
- return a;
-};
-
-/**
- * Returns the translation component of a 4-by-4 matrix as a vector with 3
- * entries.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @return {!o3djs.math.Vector3} The translation component of m.
- */
-o3djs.math.matrix4.getTranslation = function(m) {
- return m[3].slice(0, 3);
-};
-
-/**
- * Takes a 4-by-4 matrix and a vector with 3 entries,
- * interprets the vector as a point, transforms that point by the matrix, and
- * returns the result as a vector with 3 entries.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @param {!o3djs.math.Vector3} v The point.
- * @return {!o3djs.math.Vector3} The transformed point.
- */
-o3djs.math.matrix4.transformPoint = function(m, v) {
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
- var m0 = m[0];
- var m1 = m[1];
- var m2 = m[2];
- var m3 = m[3];
-
- var d = v0 * m0[3] + v1 * m1[3] + v2 * m2[3] + m3[3];
- return [(v0 * m0[0] + v1 * m1[0] + v2 * m2[0] + m3[0]) / d,
- (v0 * m0[1] + v1 * m1[1] + v2 * m2[1] + m3[1]) / d,
- (v0 * m0[2] + v1 * m1[2] + v2 * m2[2] + m3[2]) / d];
-};
-
-/**
- * Takes a 4-by-4 matrix and a vector with 4 entries, transforms that vector by
- * the matrix, and returns the result as a vector with 4 entries.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @param {!o3djs.math.Vector4} v The point in homogenous coordinates.
- * @return {!o3djs.math.Vector4} The transformed point in homogenous
- * coordinates.
- */
-o3djs.math.matrix4.transformVector4 = function(m, v) {
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
- var v3 = v[3];
- var m0 = m[0];
- var m1 = m[1];
- var m2 = m[2];
- var m3 = m[3];
-
- return [v0 * m0[0] + v1 * m1[0] + v2 * m2[0] + v3 * m3[0],
- v0 * m0[1] + v1 * m1[1] + v2 * m2[1] + v3 * m3[1],
- v0 * m0[2] + v1 * m1[2] + v2 * m2[2] + v3 * m3[2],
- v0 * m0[3] + v1 * m1[3] + v2 * m2[3] + v3 * m3[3]];
-};
-
-/**
- * Takes a 4-by-4 matrix and a vector with 3 entries, interprets the vector as a
- * direction, transforms that direction by the matrix, and returns the result;
- * assumes the transformation of 3-dimensional space represented by the matrix
- * is parallel-preserving, i.e. any combination of rotation, scaling and
- * translation, but not a perspective distortion. Returns a vector with 3
- * entries.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @param {!o3djs.math.Vector3} v The direction.
- * @return {!o3djs.math.Vector3} The transformed direction.
- */
-o3djs.math.matrix4.transformDirection = function(m, v) {
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
- var m0 = m[0];
- var m1 = m[1];
- var m2 = m[2];
- var m3 = m[3];
-
- return [v0 * m0[0] + v1 * m1[0] + v2 * m2[0],
- v0 * m0[1] + v1 * m1[1] + v2 * m2[1],
- v0 * m0[2] + v1 * m1[2] + v2 * m2[2]];
-};
-
-/**
- * Takes a 4-by-4 matrix m and a vector v with 3 entries, interprets the vector
- * as a normal to a surface, and computes a vector which is normal upon
- * transforming that surface by the matrix. The effect of this function is the
- * same as transforming v (as a direction) by the inverse-transpose of m. This
- * function assumes the transformation of 3-dimensional space represented by the
- * matrix is parallel-preserving, i.e. any combination of rotation, scaling and
- * translation, but not a perspective distortion. Returns a vector with 3
- * entries.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @param {!o3djs.math.Vector3} v The normal.
- * @return {!o3djs.math.Vector3} The transformed normal.
- */
-o3djs.math.matrix4.transformNormal = function(m, v) {
- var mInverse = o3djs.math.inverse4(m);
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
- var mi0 = mInverse[0];
- var mi1 = mInverse[1];
- var mi2 = mInverse[2];
- var mi3 = mInverse[3];
-
- return [v0 * mi0[0] + v1 * mi0[1] + v2 * mi0[2],
- v0 * mi1[0] + v1 * mi1[1] + v2 * mi1[2],
- v0 * mi2[0] + v1 * mi2[1] + v2 * mi2[2]];
-};
-
-/**
- * Creates a 4-by-4 identity matrix.
- * @return {!o3djs.math.Matrix4} The 4-by-4 identity.
- */
-o3djs.math.matrix4.identity = function() {
- return [
- [1, 0, 0, 0],
- [0, 1, 0, 0],
- [0, 0, 1, 0],
- [0, 0, 0, 1]
- ];
-};
-
-/**
- * Sets the given 4-by-4 matrix to the identity matrix.
- * @param {!o3djs.math.Matrix4} m The matrix to set to identity.
- * @return {!o3djs.math.Matrix4} m once modified.
- */
-o3djs.math.matrix4.setIdentity = function(m) {
- for (var i = 0; i < 4; i++) {
- for (var j = 0; j < 4; j++) {
- if (i == j) {
- m[i][j] = 1;
- } else {
- m[i][j] = 0;
- }
- }
- }
- return m;
-};
-
-/**
- * Computes a 4-by-4 perspective transformation matrix given the angular height
- * of the frustum, the aspect ratio, and the near and far clipping planes. The
- * arguments define a frustum extending in the negative z direction. The given
- * angle is the vertical angle of the frustum, and the horizontal angle is
- * determined to produce the given aspect ratio. The arguments near and far are
- * the distances to the near and far clipping planes. Note that near and far
- * are not z coordinates, but rather they are distances along the negative
- * z-axis. The matrix generated sends the viewing frustum to the unit box.
- * We assume a unit box extending from -1 to 1 in the x and y dimensions and
- * from 0 to 1 in the z dimension.
- * @param {number} angle The camera angle from top to bottom (in radians).
- * @param {number} aspect The aspect ratio width / height.
- * @param {number} near The depth (negative z coordinate)
- * of the near clipping plane.
- * @param {number} far The depth (negative z coordinate)
- * of the far clipping plane.
- * @return {!o3djs.math.Matrix4} The perspective matrix.
- */
-o3djs.math.matrix4.perspective = function(angle, aspect, near, far) {
- var f = Math.tan(0.5 * (Math.PI - angle));
- var range = near - far;
-
- return [
- [f / aspect, 0, 0, 0],
- [0, f, 0, 0],
- [0, 0, far / range, -1],
- [0, 0, near * far / range, 0]
- ];
-};
-
-/**
- * Computes a 4-by-4 orthographic projection matrix given the coordinates of the
- * planes defining the axis-aligned, box-shaped viewing volume. The matrix
- * generated sends that box to the unit box. Note that although left and right
- * are x coordinates and bottom and top are y coordinates, near and far
- * are not z coordinates, but rather they are distances along the negative
- * z-axis. We assume a unit box extending from -1 to 1 in the x and y
- * dimensions and from 0 to 1 in the z dimension.
- * @param {number} left The x coordinate of the left plane of the box.
- * @param {number} right The x coordinate of the right plane of the box.
- * @param {number} bottom The y coordinate of the bottom plane of the box.
- * @param {number} top The y coordinate of the right plane of the box.
- * @param {number} near The negative z coordinate of the near plane of the box.
- * @param {number} far The negative z coordinate of the far plane of the box.
- * @return {!o3djs.math.Matrix4} The orthographic projection matrix.
- */
-o3djs.math.matrix4.orthographic =
- function(left, right, bottom, top, near, far) {
- return [
- [2 / (right - left), 0, 0, 0],
- [0, 2 / (top - bottom), 0, 0],
- [0, 0, 1 / (near - far), 0],
- [(left + right) / (left - right),
- (bottom + top) / (bottom - top),
- near / (near - far), 1]
- ];
-};
-
-/**
- * Computes a 4-by-4 perspective transformation matrix given the left, right,
- * top, bottom, near and far clipping planes. The arguments define a frustum
- * extending in the negative z direction. The arguments near and far are the
- * distances to the near and far clipping planes. Note that near and far are not
- * z coordinates, but rather they are distances along the negative z-axis. The
- * matrix generated sends the viewing frustum to the unit box. We assume a unit
- * box extending from -1 to 1 in the x and y dimensions and from 0 to 1 in the z
- * dimension.
- * @param {number} left The x coordinate of the left plane of the box.
- * @param {number} right The x coordinate of the right plane of the box.
- * @param {number} bottom The y coordinate of the bottom plane of the box.
- * @param {number} top The y coordinate of the right plane of the box.
- * @param {number} near The negative z coordinate of the near plane of the box.
- * @param {number} far The negative z coordinate of the far plane of the box.
- * @return {!o3djs.math.Matrix4} The perspective projection matrix.
- */
-o3djs.math.matrix4.frustum = function(left, right, bottom, top, near, far) {
- var dx = (right - left);
- var dy = (top - bottom);
- var dz = (near - far);
- return [
- [2 * near / dx, 0, 0, 0],
- [0, 2 * near / dy, 0, 0],
- [(left + right) / dx, (top + bottom) / dy, far / dz, -1],
- [0, 0, near * far / dz, 0]];
-};
-
-/**
- * Computes a 4-by-4 look-at transformation. The transformation generated is
- * an orthogonal rotation matrix with translation component. The translation
- * component sends the eye to the origin. The rotation component sends the
- * vector pointing from the eye to the target to a vector pointing in the
- * negative z direction, and also sends the up vector into the upper half of
- * the yz plane.
- * @param {(!o3djs.math.Vector3|!o3djs.math.Vector4)} eye The position
- * of the eye.
- * @param {(!o3djs.math.Vector3|!o3djs.math.Vector4)} target The
- * position meant to be viewed.
- * @param {(!o3djs.math.Vector3|!o3djs.math.Vector4)} up A vector
- * pointing up.
- * @return {!o3djs.math.Matrix4} The look-at matrix.
- */
-o3djs.math.matrix4.lookAt = function(eye, target, up) {
- var vz = o3djs.math.normalize(
- o3djs.math.subVector(eye, target).slice(0, 3)).concat(0);
- var vx = o3djs.math.normalize(
- o3djs.math.cross(up, vz)).concat(0);
- var vy = o3djs.math.cross(vz, vx).concat(0);
-
- return o3djs.math.inverse([vx, vy, vz, eye.concat(1)]);
-};
-
-/**
- * Takes two 4-by-4 matrices, a and b, and computes the product in the order
- * that pre-composes b with a. In other words, the matrix returned will
- * transform by b first and then a. Note this is subtly different from just
- * multiplying the matrices together. For given a and b, this function returns
- * the same object in both row-major and column-major mode.
- * @param {!o3djs.math.Matrix4} a A 4-by-4 matrix.
- * @param {!o3djs.math.Matrix4} b A 4-by-4 matrix.
- * @return {!o3djs.math.Matrix4} the composition of a and b, b first then a.
- */
-o3djs.math.matrix4.composition = function(a, b) {
- var a0 = a[0];
- var a1 = a[1];
- var a2 = a[2];
- var a3 = a[3];
- var b0 = b[0];
- var b1 = b[1];
- var b2 = b[2];
- var b3 = b[3];
- var a00 = a0[0];
- var a01 = a0[1];
- var a02 = a0[2];
- var a03 = a0[3];
- var a10 = a1[0];
- var a11 = a1[1];
- var a12 = a1[2];
- var a13 = a1[3];
- var a20 = a2[0];
- var a21 = a2[1];
- var a22 = a2[2];
- var a23 = a2[3];
- var a30 = a3[0];
- var a31 = a3[1];
- var a32 = a3[2];
- var a33 = a3[3];
- var b00 = b0[0];
- var b01 = b0[1];
- var b02 = b0[2];
- var b03 = b0[3];
- var b10 = b1[0];
- var b11 = b1[1];
- var b12 = b1[2];
- var b13 = b1[3];
- var b20 = b2[0];
- var b21 = b2[1];
- var b22 = b2[2];
- var b23 = b2[3];
- var b30 = b3[0];
- var b31 = b3[1];
- var b32 = b3[2];
- var b33 = b3[3];
- return [[a00 * b00 + a10 * b01 + a20 * b02 + a30 * b03,
- a01 * b00 + a11 * b01 + a21 * b02 + a31 * b03,
- a02 * b00 + a12 * b01 + a22 * b02 + a32 * b03,
- a03 * b00 + a13 * b01 + a23 * b02 + a33 * b03],
- [a00 * b10 + a10 * b11 + a20 * b12 + a30 * b13,
- a01 * b10 + a11 * b11 + a21 * b12 + a31 * b13,
- a02 * b10 + a12 * b11 + a22 * b12 + a32 * b13,
- a03 * b10 + a13 * b11 + a23 * b12 + a33 * b13],
- [a00 * b20 + a10 * b21 + a20 * b22 + a30 * b23,
- a01 * b20 + a11 * b21 + a21 * b22 + a31 * b23,
- a02 * b20 + a12 * b21 + a22 * b22 + a32 * b23,
- a03 * b20 + a13 * b21 + a23 * b22 + a33 * b23],
- [a00 * b30 + a10 * b31 + a20 * b32 + a30 * b33,
- a01 * b30 + a11 * b31 + a21 * b32 + a31 * b33,
- a02 * b30 + a12 * b31 + a22 * b32 + a32 * b33,
- a03 * b30 + a13 * b31 + a23 * b32 + a33 * b33]];
-};
-
-/**
- * Takes two 4-by-4 matrices, a and b, and modifies a to be the product in the
- * order that pre-composes b with a. The matrix a, upon modification will
- * transform by b first and then a. Note this is subtly different from just
- * multiplying the matrices together. For given a and b, a, upon modification,
- * will be the same object in both row-major and column-major mode.
- * @param {!o3djs.math.Matrix4} a A 4-by-4 matrix.
- * @param {!o3djs.math.Matrix4} b A 4-by-4 matrix.
- * @return {!o3djs.math.Matrix4} a once modified.
- */
-o3djs.math.matrix4.compose = function(a, b) {
- var a0 = a[0];
- var a1 = a[1];
- var a2 = a[2];
- var a3 = a[3];
- var b0 = b[0];
- var b1 = b[1];
- var b2 = b[2];
- var b3 = b[3];
- var a00 = a0[0];
- var a01 = a0[1];
- var a02 = a0[2];
- var a03 = a0[3];
- var a10 = a1[0];
- var a11 = a1[1];
- var a12 = a1[2];
- var a13 = a1[3];
- var a20 = a2[0];
- var a21 = a2[1];
- var a22 = a2[2];
- var a23 = a2[3];
- var a30 = a3[0];
- var a31 = a3[1];
- var a32 = a3[2];
- var a33 = a3[3];
- var b00 = b0[0];
- var b01 = b0[1];
- var b02 = b0[2];
- var b03 = b0[3];
- var b10 = b1[0];
- var b11 = b1[1];
- var b12 = b1[2];
- var b13 = b1[3];
- var b20 = b2[0];
- var b21 = b2[1];
- var b22 = b2[2];
- var b23 = b2[3];
- var b30 = b3[0];
- var b31 = b3[1];
- var b32 = b3[2];
- var b33 = b3[3];
- a[0].splice(0, 4, a00 * b00 + a10 * b01 + a20 * b02 + a30 * b03,
- a01 * b00 + a11 * b01 + a21 * b02 + a31 * b03,
- a02 * b00 + a12 * b01 + a22 * b02 + a32 * b03,
- a03 * b00 + a13 * b01 + a23 * b02 + a33 * b03);
- a[1].splice(0, 4, a00 * b10 + a10 * b11 + a20 * b12 + a30 * b13,
- a01 * b10 + a11 * b11 + a21 * b12 + a31 * b13,
- a02 * b10 + a12 * b11 + a22 * b12 + a32 * b13,
- a03 * b10 + a13 * b11 + a23 * b12 + a33 * b13);
- a[2].splice(0, 4, a00 * b20 + a10 * b21 + a20 * b22 + a30 * b23,
- a01 * b20 + a11 * b21 + a21 * b22 + a31 * b23,
- a02 * b20 + a12 * b21 + a22 * b22 + a32 * b23,
- a03 * b20 + a13 * b21 + a23 * b22 + a33 * b23),
- a[3].splice(0, 4, a00 * b30 + a10 * b31 + a20 * b32 + a30 * b33,
- a01 * b30 + a11 * b31 + a21 * b32 + a31 * b33,
- a02 * b30 + a12 * b31 + a22 * b32 + a32 * b33,
- a03 * b30 + a13 * b31 + a23 * b32 + a33 * b33);
- return a;
-};
-
-/**
- * Creates a 4-by-4 matrix which translates by the given vector v.
- * @param {(!o3djs.math.Vector3|!o3djs.math.Vector4)} v The vector by
- * which to translate.
- * @return {!o3djs.math.Matrix4} The translation matrix.
- */
-o3djs.math.matrix4.translation = function(v) {
- return [
- [1, 0, 0, 0],
- [0, 1, 0, 0],
- [0, 0, 1, 0],
- [v[0], v[1], v[2], 1]
- ];
-};
-
-/**
- * Modifies the given 4-by-4 matrix by translation by the given vector v.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @param {(!o3djs.math.Vector3|!o3djs.math.Vector4)} v The vector by
- * which to translate.
- * @return {!o3djs.math.Matrix4} m once modified.
- */
-o3djs.math.matrix4.translate = function(m, v) {
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
- var m0 = m[0];
- var m1 = m[1];
- var m2 = m[2];
- var m3 = m[3];
- var m00 = m0[0];
- var m01 = m0[1];
- var m02 = m0[2];
- var m03 = m0[3];
- var m10 = m1[0];
- var m11 = m1[1];
- var m12 = m1[2];
- var m13 = m1[3];
- var m20 = m2[0];
- var m21 = m2[1];
- var m22 = m2[2];
- var m23 = m2[3];
- var m30 = m3[0];
- var m31 = m3[1];
- var m32 = m3[2];
- var m33 = m3[3];
-
- m3.splice(0, 4, m00 * v0 + m10 * v1 + m20 * v2 + m30,
- m01 * v0 + m11 * v1 + m21 * v2 + m31,
- m02 * v0 + m12 * v1 + m22 * v2 + m32,
- m03 * v0 + m13 * v1 + m23 * v2 + m33);
-
- return m;
-};
-
-/**
- * Creates a 4-by-4 matrix which scales in each dimension by an amount given by
- * the corresponding entry in the given vector; assumes the vector has three
- * entries.
- * @param {!o3djs.math.Vector3} v A vector of
- * three entries specifying the factor by which to scale in each dimension.
- * @return {!o3djs.math.Matrix4} The scaling matrix.
- */
-o3djs.math.matrix4.scaling = function(v) {
- return [
- [v[0], 0, 0, 0],
- [0, v[1], 0, 0],
- [0, 0, v[2], 0],
- [0, 0, 0, 1]
- ];
-};
-
-/**
- * Modifies the given 4-by-4 matrix, scaling in each dimension by an amount
- * given by the corresponding entry in the given vector; assumes the vector has
- * three entries.
- * @param {!o3djs.math.Matrix4} m The matrix to be modified.
- * @param {!o3djs.math.Vector3} v A vector of three entries specifying the
- * factor by which to scale in each dimension.
- * @return {!o3djs.math.Matrix4} m once modified.
- */
-o3djs.math.matrix4.scale = function(m, v) {
- var v0 = v[0];
- var v1 = v[1];
- var v2 = v[2];
-
- var m0 = m[0];
- var m1 = m[1];
- var m2 = m[2];
- var m3 = m[3];
-
- m0.splice(0, 4, v0 * m0[0], v0 * m0[1], v0 * m0[2], v0 * m0[3]);
- m1.splice(0, 4, v1 * m1[0], v1 * m1[1], v1 * m1[2], v1 * m1[3]);
- m2.splice(0, 4, v2 * m2[0], v2 * m2[1], v2 * m2[2], v2 * m2[3]);
-
- return m;
-};
-
-/**
- * Creates a 4-by-4 matrix which rotates around the x-axis by the given angle.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.math.Matrix4} The rotation matrix.
- */
-o3djs.math.matrix4.rotationX = function(angle) {
- var c = Math.cos(angle);
- var s = Math.sin(angle);
-
- return [
- [1, 0, 0, 0],
- [0, c, s, 0],
- [0, -s, c, 0],
- [0, 0, 0, 1]
- ];
-};
-
-/**
- * Modifies the given 4-by-4 matrix by a rotation around the x-axis by the given
- * angle.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.math.Matrix4} m once modified.
- */
-o3djs.math.matrix4.rotateX = function(m, angle) {
- var m0 = m[0];
- var m1 = m[1];
- var m2 = m[2];
- var m3 = m[3];
- var m10 = m1[0];
- var m11 = m1[1];
- var m12 = m1[2];
- var m13 = m1[3];
- var m20 = m2[0];
- var m21 = m2[1];
- var m22 = m2[2];
- var m23 = m2[3];
- var c = Math.cos(angle);
- var s = Math.sin(angle);
-
- m1.splice(0, 4, c * m10 + s * m20,
- c * m11 + s * m21,
- c * m12 + s * m22,
- c * m13 + s * m23);
- m2.splice(0, 4, c * m20 - s * m10,
- c * m21 - s * m11,
- c * m22 - s * m12,
- c * m23 - s * m13);
-
- return m;
-};
-
-/**
- * Creates a 4-by-4 matrix which rotates around the y-axis by the given angle.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.math.Matrix4} The rotation matrix.
- */
-o3djs.math.matrix4.rotationY = function(angle) {
- var c = Math.cos(angle);
- var s = Math.sin(angle);
-
- return [
- [c, 0, -s, 0],
- [0, 1, 0, 0],
- [s, 0, c, 0],
- [0, 0, 0, 1]
- ];
-};
-
-/**
- * Modifies the given 4-by-4 matrix by a rotation around the y-axis by the given
- * angle.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.math.Matrix4} m once modified.
- */
-o3djs.math.matrix4.rotateY = function(m, angle) {
- var m0 = m[0];
- var m1 = m[1];
- var m2 = m[2];
- var m3 = m[3];
- var m00 = m0[0];
- var m01 = m0[1];
- var m02 = m0[2];
- var m03 = m0[3];
- var m20 = m2[0];
- var m21 = m2[1];
- var m22 = m2[2];
- var m23 = m2[3];
- var c = Math.cos(angle);
- var s = Math.sin(angle);
-
- m0.splice(0, 4, c * m00 - s * m20,
- c * m01 - s * m21,
- c * m02 - s * m22,
- c * m03 - s * m23);
- m2.splice(0, 4, c * m20 + s * m00,
- c * m21 + s * m01,
- c * m22 + s * m02,
- c * m23 + s * m03);
-
- return m;
-};
-
-/**
- * Creates a 4-by-4 matrix which rotates around the z-axis by the given angle.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.math.Matrix4} The rotation matrix.
- */
-o3djs.math.matrix4.rotationZ = function(angle) {
- var c = Math.cos(angle);
- var s = Math.sin(angle);
-
- return [
- [c, s, 0, 0],
- [-s, c, 0, 0],
- [0, 0, 1, 0],
- [0, 0, 0, 1]
- ];
-};
-
-/**
- * Modifies the given 4-by-4 matrix by a rotation around the z-axis by the given
- * angle.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.math.Matrix4} m once modified.
- */
-o3djs.math.matrix4.rotateZ = function(m, angle) {
- var m0 = m[0];
- var m1 = m[1];
- var m2 = m[2];
- var m3 = m[3];
- var m00 = m0[0];
- var m01 = m0[1];
- var m02 = m0[2];
- var m03 = m0[3];
- var m10 = m1[0];
- var m11 = m1[1];
- var m12 = m1[2];
- var m13 = m1[3];
- var c = Math.cos(angle);
- var s = Math.sin(angle);
-
- m0.splice(0, 4, c * m00 + s * m10,
- c * m01 + s * m11,
- c * m02 + s * m12,
- c * m03 + s * m13);
- m1.splice(0, 4, c * m10 - s * m00,
- c * m11 - s * m01,
- c * m12 - s * m02,
- c * m13 - s * m03);
-
- return m;
-};
-
-/**
- * Creates a 4-by-4 rotation matrix. Interprets the entries of the given
- * vector as angles by which to rotate around the x, y and z axes, returns a
- * a matrix which rotates around the x-axis first, then the y-axis, then the
- * z-axis.
- * @param {!o3djs.math.Vector3} v A vector of angles (in radians).
- * @return {!o3djs.math.Matrix4} The rotation matrix.
- */
-o3djs.math.matrix4.rotationZYX = function(v) {
- var sinx = Math.sin(v[0]);
- var cosx = Math.cos(v[0]);
- var siny = Math.sin(v[1]);
- var cosy = Math.cos(v[1]);
- var sinz = Math.sin(v[2]);
- var cosz = Math.cos(v[2]);
-
- var coszsiny = cosz * siny;
- var sinzsiny = sinz * siny;
-
- return [
- [cosz * cosy, sinz * cosy, -siny, 0],
- [coszsiny * sinx - sinz * cosx,
- sinzsiny * sinx + cosz * cosx,
- cosy * sinx,
- 0],
- [coszsiny * cosx + sinz * sinx,
- sinzsiny * cosx - cosz * sinx,
- cosy * cosx,
- 0],
- [0, 0, 0, 1]
- ];
-};
-
-/**
- * Modifies a 4-by-4 matrix by a rotation. Interprets the coordinates of the
- * given vector as angles by which to rotate around the x, y and z axes, rotates
- * around the x-axis first, then the y-axis, then the z-axis.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @param {!o3djs.math.Vector3} v A vector of angles (in radians).
- * @return {!o3djs.math.Matrix4} m once modified.
- */
-o3djs.math.matrix4.rotateZYX = function(m, v) {
- var sinX = Math.sin(v[0]);
- var cosX = Math.cos(v[0]);
- var sinY = Math.sin(v[1]);
- var cosY = Math.cos(v[1]);
- var sinZ = Math.sin(v[2]);
- var cosZ = Math.cos(v[2]);
-
- var cosZSinY = cosZ * sinY;
- var sinZSinY = sinZ * sinY;
-
- var r00 = cosZ * cosY;
- var r01 = sinZ * cosY;
- var r02 = -sinY;
- var r10 = cosZSinY * sinX - sinZ * cosX;
- var r11 = sinZSinY * sinX + cosZ * cosX;
- var r12 = cosY * sinX;
- var r20 = cosZSinY * cosX + sinZ * sinX;
- var r21 = sinZSinY * cosX - cosZ * sinX;
- var r22 = cosY * cosX;
-
- var m0 = m[0];
- var m1 = m[1];
- var m2 = m[2];
- var m3 = m[3];
-
- var m00 = m0[0];
- var m01 = m0[1];
- var m02 = m0[2];
- var m03 = m0[3];
- var m10 = m1[0];
- var m11 = m1[1];
- var m12 = m1[2];
- var m13 = m1[3];
- var m20 = m2[0];
- var m21 = m2[1];
- var m22 = m2[2];
- var m23 = m2[3];
- var m30 = m3[0];
- var m31 = m3[1];
- var m32 = m3[2];
- var m33 = m3[3];
-
- m0.splice(0, 4,
- r00 * m00 + r01 * m10 + r02 * m20,
- r00 * m01 + r01 * m11 + r02 * m21,
- r00 * m02 + r01 * m12 + r02 * m22,
- r00 * m03 + r01 * m13 + r02 * m23);
-
- m1.splice(0, 4,
- r10 * m00 + r11 * m10 + r12 * m20,
- r10 * m01 + r11 * m11 + r12 * m21,
- r10 * m02 + r11 * m12 + r12 * m22,
- r10 * m03 + r11 * m13 + r12 * m23);
-
- m2.splice(0, 4,
- r20 * m00 + r21 * m10 + r22 * m20,
- r20 * m01 + r21 * m11 + r22 * m21,
- r20 * m02 + r21 * m12 + r22 * m22,
- r20 * m03 + r21 * m13 + r22 * m23);
-
- return m;
-};
-
-/**
- * Creates a 4-by-4 matrix which rotates around the given axis by the given
- * angle.
- * @param {(!o3djs.math.Vector3|!o3djs.math.Vector4)} axis The axis
- * about which to rotate.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.math.Matrix4} A matrix which rotates angle radians
- * around the axis.
- */
-o3djs.math.matrix4.axisRotation = function(axis, angle) {
- var x = axis[0];
- var y = axis[1];
- var z = axis[2];
- var n = Math.sqrt(x * x + y * y + z * z);
- x /= n;
- y /= n;
- z /= n;
- var xx = x * x;
- var yy = y * y;
- var zz = z * z;
- var c = Math.cos(angle);
- var s = Math.sin(angle);
- var oneMinusCosine = 1 - c;
-
- return [
- [xx + (1 - xx) * c,
- x * y * oneMinusCosine + z * s,
- x * z * oneMinusCosine - y * s,
- 0],
- [x * y * oneMinusCosine - z * s,
- yy + (1 - yy) * c,
- y * z * oneMinusCosine + x * s,
- 0],
- [x * z * oneMinusCosine + y * s,
- y * z * oneMinusCosine - x * s,
- zz + (1 - zz) * c,
- 0],
- [0, 0, 0, 1]
- ];
-};
-
-/**
- * Modifies the given 4-by-4 matrix by rotation around the given axis by the
- * given angle.
- * @param {!o3djs.math.Matrix4} m The matrix.
- * @param {(!o3djs.math.Vector3|!o3djs.math.Vector4)} axis The axis
- * about which to rotate.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.math.Matrix4} m once modified.
- */
-o3djs.math.matrix4.axisRotate = function(m, axis, angle) {
- var x = axis[0];
- var y = axis[1];
- var z = axis[2];
- var n = Math.sqrt(x * x + y * y + z * z);
- x /= n;
- y /= n;
- z /= n;
- var xx = x * x;
- var yy = y * y;
- var zz = z * z;
- var c = Math.cos(angle);
- var s = Math.sin(angle);
- var oneMinusCosine = 1 - c;
-
- var r00 = xx + (1 - xx) * c;
- var r01 = x * y * oneMinusCosine + z * s;
- var r02 = x * z * oneMinusCosine - y * s;
- var r10 = x * y * oneMinusCosine - z * s;
- var r11 = yy + (1 - yy) * c;
- var r12 = y * z * oneMinusCosine + x * s;
- var r20 = x * z * oneMinusCosine + y * s;
- var r21 = y * z * oneMinusCosine - x * s;
- var r22 = zz + (1 - zz) * c;
-
- var m0 = m[0];
- var m1 = m[1];
- var m2 = m[2];
- var m3 = m[3];
-
- var m00 = m0[0];
- var m01 = m0[1];
- var m02 = m0[2];
- var m03 = m0[3];
- var m10 = m1[0];
- var m11 = m1[1];
- var m12 = m1[2];
- var m13 = m1[3];
- var m20 = m2[0];
- var m21 = m2[1];
- var m22 = m2[2];
- var m23 = m2[3];
- var m30 = m3[0];
- var m31 = m3[1];
- var m32 = m3[2];
- var m33 = m3[3];
-
- m0.splice(0, 4,
- r00 * m00 + r01 * m10 + r02 * m20,
- r00 * m01 + r01 * m11 + r02 * m21,
- r00 * m02 + r01 * m12 + r02 * m22,
- r00 * m03 + r01 * m13 + r02 * m23);
-
- m1.splice(0, 4,
- r10 * m00 + r11 * m10 + r12 * m20,
- r10 * m01 + r11 * m11 + r12 * m21,
- r10 * m02 + r11 * m12 + r12 * m22,
- r10 * m03 + r11 * m13 + r12 * m23);
-
- m2.splice(0, 4,
- r20 * m00 + r21 * m10 + r22 * m20,
- r20 * m01 + r21 * m11 + r22 * m21,
- r20 * m02 + r21 * m12 + r22 * m22,
- r20 * m03 + r21 * m13 + r22 * m23);
-
- return m;
-};
-
-/**
- * Sets each function in the namespace o3djs.math to the row major
- * version in o3djs.math.rowMajor (provided such a function exists in
- * o3djs.math.rowMajor). Call this function to establish the row major
- * convention.
- */
-o3djs.math.installRowMajorFunctions = function() {
- for (var f in o3djs.math.rowMajor) {
- o3djs.math[f] = o3djs.math.rowMajor[f];
- }
-};
-
-/**
- * Sets each function in the namespace o3djs.math to the column major
- * version in o3djs.math.columnMajor (provided such a function exists in
- * o3djs.math.columnMajor). Call this function to establish the column
- * major convention.
- */
-o3djs.math.installColumnMajorFunctions = function() {
- for (var f in o3djs.math.columnMajor) {
- o3djs.math[f] = o3djs.math.columnMajor[f];
- }
-};
-
-/**
- * Sets each function in the namespace o3djs.math to the error checking
- * version in o3djs.math.errorCheck (provided such a function exists in
- * o3djs.math.errorCheck).
- */
-o3djs.math.installErrorCheckFunctions = function() {
- for (var f in o3djs.math.errorCheck) {
- o3djs.math[f] = o3djs.math.errorCheck[f];
- }
-};
-
-/**
- * Sets each function in the namespace o3djs.math to the error checking free
- * version in o3djs.math.errorCheckFree (provided such a function exists in
- * o3djs.math.errorCheckFree).
- */
-o3djs.math.installErrorCheckFreeFunctions = function() {
- for (var f in o3djs.math.errorCheckFree) {
- o3djs.math[f] = o3djs.math.errorCheckFree[f];
- }
-}
-
-// By default, install the row-major functions.
-o3djs.math.installRowMajorFunctions();
-
-// By default, install prechecking.
-o3djs.math.installErrorCheckFunctions();
-
-
-/**
- * True if we are using the plugin math library in which matrices are
- * represented by 2-dimensional arrays.
- * @type {boolean}
- * @private
- */
-o3djs.math.usePluginMath_ = true;
diff --git a/o3d/samples/o3djs/primitives.js b/o3d/samples/o3djs/primitives.js
deleted file mode 100644
index 34d058d..0000000
--- a/o3d/samples/o3djs/primitives.js
+++ /dev/null
@@ -1,2016 +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.
- */
-
-
-/**
- * @fileoverview This file contains functions to create geometric primitives for
- * o3d. It puts them in the "primitives" module on the o3djs object.
- *
- * For more information about o3d see http://code.google.com/p/o3d
- *
- *
- * Requires base.js
- */
-
-o3djs.provide('o3djs.primitives');
-
-o3djs.require('o3djs.math');
-
-/**
- * A Module for creating primitives.
- * @namespace
- */
-o3djs.primitives = o3djs.primitives || {};
-
-
-/**
- * Sets the bounding box and zSortPoint for a primitive based on its vertices
- *
- * @param {!o3d.Primitive} primitive Primitive to set culling info for.
- */
-o3djs.primitives.setCullingInfo = function(primitive) {
- var box = primitive.getBoundingBox(0);
- primitive.boundingBox = box;
- var minExtent = box.minExtent;
- var maxExtent = box.maxExtent;
- primitive.zSortPoint = o3djs.math.divVectorScalar(
- o3djs.math.addVector(minExtent, maxExtent), 2);
-};
-
-/**
- * Used to store the elements of a stream.
- * @param {number} numComponents The number of numerical components per
- * element.
- * @param {!o3d.Stream.Semantic} semantic The semantic of the stream.
- * @param {number} opt_semanticIndex The semantic index of the stream.
- * Defaults to zero.
- * @constructor
- */
-o3djs.primitives.VertexStreamInfo = function(numComponents,
- semantic,
- opt_semanticIndex) {
- /**
- * The number of numerical components per element.
- * @type {number}
- */
- this.numComponents = numComponents;
-
- /**
- * The semantic of the stream.
- * @type {!o3d.Stream.Semantic}
- */
- this.semantic = semantic;
-
- /**
- * The semantic index of the stream.
- * @type {number}
- */
- this.semanticIndex = opt_semanticIndex || 0;
-
- /**
- * The elements of the stream.
- * @type {!Array.<number>}
- */
- this.elements = [];
-
- /**
- * Adds an element to this VertexStreamInfo. The number of values passed must
- * match the number of components for this VertexStreamInfo.
- * @param {number} value1 First value.
- * @param {number} opt_value2 Second value.
- * @param {number} opt_value3 Third value.
- * @param {number} opt_value4 Fourth value.
- */
- this.addElement = function(value1, opt_value2, opt_value3, opt_value4) { };
-
- /**
- * Sets an element on this VertexStreamInfo. The number of values passed must
- * match the number of components for this VertexStreamInfo.
- * @param {number} index Index of element to set.
- * @param {number} value1 First value.
- * @param {number} opt_value2 Second value.
- * @param {number} opt_value3 Third value.
- * @param {number} opt_value4 Fourth value.
- */
- this.setElement = function(
- index, value1, opt_value2, opt_value3, opt_value4) { };
-
- /**
- * Adds an element to this VertexStreamInfo. The number of values in the
- * vector must match the number of components for this VertexStreamInfo.
- * @param {!Array.<number>} vector Array of values for element.
- */
- this.addElementVector = function(vector) { }; // replaced below.
-
- /**
- * Sets an element on this VertexStreamInfo. The number of values in the
- * vector must match the number of components for this VertexStreamInfo.
- * @param {number} index Index of element to set.
- * @param {!Array.<number>} vector Array of values for element.
- */
- this.setElementVector = function(index, vector) { }; // replaced below.
-
- /**
- * Sets an element on this VertexStreamInfo. The number of values in the
- * vector will match the number of components for this VertexStreamInfo.
- * @param {number} index Index of element to set.
- * @return {!Array.<number>} Array of values for element.
- */
- this.getElementVector = function(index) { return []; }; // replaced below.
-
- switch (numComponents) {
- case 1:
- this.addElement = function(value) {
- this.elements.push(value);
- }
- this.getElement = function(index) {
- return this.elements[index];
- }
- this.setElement = function(index, value) {
- this.elements[index] = value;
- }
- break;
- case 2:
- this.addElement = function(value0, value1) {
- this.elements.push(value0, value1);
- }
- this.addElementVector = function(vector) {
- this.elements.push(vector[0], vector[1]);
- }
- this.getElementVector = function(index) {
- return this.elements.slice(index * numComponents,
- (index + 1) * numComponents);
- }
- this.setElement = function(index, value0, value1) {
- this.elements[index * numComponents + 0] = value0;
- this.elements[index * numComponents + 1] = value1;
- }
- this.setElementVector = function(index, vector) {
- this.elements[index * numComponents + 0] = vector[0];
- this.elements[index * numComponents + 1] = vector[1];
- }
- break;
- case 3:
- this.addElement = function(value0, value1, value2) {
- this.elements.push(value0, value1, value2);
- }
- this.addElementVector = function(vector) {
- this.elements.push(vector[0], vector[1], vector[2]);
- }
- this.getElementVector = function(index) {
- return this.elements.slice(index * numComponents,
- (index + 1) * numComponents);
- }
- this.setElement = function(index, value0, value1, value2) {
- this.elements[index * numComponents + 0] = value0;
- this.elements[index * numComponents + 1] = value1;
- this.elements[index * numComponents + 2] = value2;
- }
- this.setElementVector = function(index, vector) {
- this.elements[index * numComponents + 0] = vector[0];
- this.elements[index * numComponents + 1] = vector[1];
- this.elements[index * numComponents + 2] = vector[2];
- }
- break;
- case 4:
- this.addElement = function(value0, value1, value2, value3) {
- this.elements.push(value0, value1, value2, value3);
- }
- this.addElementVector = function(vector) {
- this.elements.push(vector[0], vector[1], vector[2], vector[3]);
- }
- this.getElementVector = function(index) {
- return this.elements.slice(index * numComponents,
- (index + 1) * numComponents);
- }
- this.setElement = function(index, value0, value1, value2, value3) {
- this.elements[index * numComponents + 0] = value0;
- this.elements[index * numComponents + 1] = value1;
- this.elements[index * numComponents + 2] = value2;
- this.elements[index * numComponents + 3] = value3;
- }
- this.setElementVector = function(index, vector) {
- this.elements[index * numComponents + 0] = vector[0];
- this.elements[index * numComponents + 1] = vector[1];
- this.elements[index * numComponents + 2] = vector[2];
- this.elements[index * numComponents + 3] = vector[3];
- }
- break;
- default:
- throw 'A stream must contain between 1 and 4 components';
- }
-};
-
-/**
- * Get the number of elements in the stream.
- * @return {number} The number of elements in the stream.
- */
-o3djs.primitives.VertexStreamInfo.prototype.numElements = function() {
- return this.elements.length / this.numComponents;
-};
-
-/**
- * Create a VertexStreamInfo.
- * @param {number} numComponents The number of numerical components per
- * element.
- * @param {!o3d.Stream.Semantic} semantic The semantic of the stream.
- * @param {number} opt_semanticIndex The semantic index of the stream.
- * Defaults to zero.
- * @return {!o3djs.primitives.VertexStreamInfo} The new stream.
- */
-o3djs.primitives.createVertexStreamInfo = function(numComponents,
- semantic,
- opt_semanticIndex) {
- return new o3djs.primitives.VertexStreamInfo(numComponents,
- semantic,
- opt_semanticIndex);
-};
-
-/**
- * VertexInfoBase. Used to store vertices and indices.
- * @constructor
- */
-o3djs.primitives.VertexInfoBase = function() {
- this.streams = [];
- this.indices = [];
-};
-
-/**
- * Add a new stream to the VertexInfo, replacing it with a new empty one
- * if it already exists.
- * @param {number} numComponents The number of components per vector.
- * @param {!o3d.Stream.Semantic} semantic The semantic of the stream.
- * @param {number} opt_semanticIndex The semantic index of the stream.
- * Defaults to zero.
- * @return {!o3djs.primitives.VertexStreamInfo} The new stream.
- */
-o3djs.primitives.VertexInfoBase.prototype.addStream = function(
- numComponents,
- semantic,
- opt_semanticIndex) {
- this.removeStream(semantic, opt_semanticIndex);
- var stream = o3djs.primitives.createVertexStreamInfo(
- numComponents,
- semantic,
- opt_semanticIndex);
- this.streams.push(stream);
- return stream;
-};
-
-/**
- * Find a stream in the VertexInfo.
- * @param {!o3d.Stream.Semantic} semantic The semantic of the stream.
- * @param {number} opt_semanticIndex The semantic index of the stream.
- * Defaults to zero.
- * @return {o3djs.primitives.VertexStreamInfo} The stream or null if it
- * is not present.
- */
-o3djs.primitives.VertexInfoBase.prototype.findStream = function(
- semantic,
- opt_semanticIndex) {
- opt_semanticIndex = opt_semanticIndex || 0;
- for (var i = 0; i < this.streams.length; ++i) {
- if (this.streams[i].semantic === semantic &&
- this.streams[i].semanticIndex == opt_semanticIndex) {
- return this.streams[i];
- }
- }
- return null;
-};
-
-/**
- * Remove a stream from the VertexInfo. Does nothing if a matching stream
- * does not exist.
- * @param {!o3d.Stream.Semantic} semantic The semantic of the stream.
- * @param {number} opt_semanticIndex The semantic index of the stream.
- * Defaults to zero.
- */
-o3djs.primitives.VertexInfoBase.prototype.removeStream = function(
- semantic,
- opt_semanticIndex) {
- opt_semanticIndex = opt_semanticIndex || 0;
- for (var i = 0; i < this.streams.length; ++i) {
- if (this.streams[i].semantic === semantic &&
- this.streams[i].semanticIndex == opt_semanticIndex) {
- this.streams.splice(i, 1);
- return;
- }
- }
-};
-
-/**
- * Appends all of the information in the passed VertexInfo on to the
- * end of this one. This is useful for putting multiple primitives'
- * vertices, appropriately transformed, into a single Shape. Both
- * VertexInfo objects must contain the same number of streams, with
- * the same semantics and number of components.
- * @param {!o3djs.primitives.VertexInfoBase} info The VertexInfo whose
- * information should be appended to this one.
- */
-o3djs.primitives.VertexInfoBase.prototype.append = function(info) {
- if (this.streams.length == 0 && info.streams.length != 0) {
- // Special case
- for (var i = 0; i < info.streams.length; i++) {
- var srcStream = info.streams[i];
- var stream = this.addStream(srcStream.numComponents,
- srcStream.semantic,
- srcStream.semanticIndex);
- stream.elements = stream.elements.concat(srcStream.elements);
- }
- this.indices = this.indices.concat(info.indices);
- return;
- }
-
- // First verify that both have the same streams
- if (this.streams.length != info.streams.length) {
- throw 'Number of VertexInfoStreams did not match';
- }
- for (var i = 0; i < this.streams.length; i++) {
- var found = false;
- var semantic = this.streams[i].semantic;
- var numComponents = this.streams[i].numComponents;
- var semanticIndex = this.streams[i].semanticIndex;
- for (var j = 0; j < info.streams.length; j++) {
- var otherStream = info.streams[j];
- if (otherStream.semantic === semantic &&
- otherStream.numComponents == numComponents &&
- otherStream.semanticIndex == semanticIndex) {
- found = true;
- break;
- }
- }
- if (!found) {
- throw 'Did not find stream with semantic=' + semantic +
- ', numComponents=' + numComponents +
- ', and semantic index=' + semanticIndex +
- ' in given VertexInfo';
- }
- }
-
- // Compute the number of vertices currently in the shape
- var positionStream = this.findStream(o3djs.base.o3d.Stream.POSITION);
- if (!positionStream)
- throw 'POSITION stream is missing';
- var numVertices = positionStream.numElements();
-
- // Concatenate all VertexStreamInfos' data
- for (var i = 0; i < this.streams.length; i++) {
- var stream = this.streams[i];
- var srcStream = info.findStream(stream.semantic, stream.semanticIndex);
- stream.elements = stream.elements.concat(srcStream.elements);
- }
-
- // Concatenate and adjust indices
- for (var i = 0; i < info.indices.length; i++) {
- this.indices.push(info.indices[i] + numVertices);
- }
-};
-
-/**
- * Validates that all the streams contain the same number of elements, that
- * all the indices are within range and that a position stream is present.
- */
-o3djs.primitives.VertexInfoBase.prototype.validate = function() {
- // Check the position stream is present.
- var positionStream = this.findStream(o3djs.base.o3d.Stream.POSITION);
- if (!positionStream)
- throw 'POSITION stream is missing';
-
- // Check all the streams have the same number of elements.
- var numElements = positionStream.numElements();
- for (var s = 0; s < this.streams.length; ++s) {
- if (this.streams[s].numElements() !== numElements) {
- throw 'Stream ' + s + ' contains ' + this.streams[s].numElements() +
- ' elements whereas the POSITION stream contains ' + numElements;
- }
- }
-
- // Check all the indices are in range.
- for (var i = 0; i < this.indices.length; ++i) {
- if (this.indices[i] < 0 || this.indices[i] >= numElements) {
- throw 'The index ' + this.indices[i] + ' is out of range [0, ' +
- numElements + ']';
- }
- }
-};
-
-/**
- * Reorients the vertices, positions and normals, of this vertexInfo by the
- * given matrix. In other words, it multiplies each vertex by the given matrix
- * and each normal by the inverse-transpose of the given matrix.
- * @param {!o3djs.math.Matrix4} matrix Matrix by which to multiply.
- */
-o3djs.primitives.VertexInfoBase.prototype.reorient = function(matrix) {
- var math = o3djs.math;
- var matrixInverse = math.inverse(math.matrix4.getUpper3x3(matrix));
-
- for (var s = 0; s < this.streams.length; ++s) {
- var stream = this.streams[s];
- if (stream.numComponents == 3) {
- var numElements = stream.numElements();
- switch (stream.semantic) {
- case o3djs.base.o3d.Stream.POSITION:
- for (var i = 0; i < numElements; ++i) {
- stream.setElementVector(i,
- math.matrix4.transformPoint(matrix,
- stream.getElementVector(i)));
- }
- break;
- case o3djs.base.o3d.Stream.NORMAL:
- for (var i = 0; i < numElements; ++i) {
- stream.setElementVector(i,
- math.matrix4.transformNormal(matrix,
- stream.getElementVector(i)));
- }
- break;
- case o3djs.base.o3d.Stream.TANGENT:
- case o3djs.base.o3d.Stream.BINORMAL:
- for (var i = 0; i < numElements; ++i) {
- stream.setElementVector(i,
- math.matrix4.transformDirection(matrix,
- stream.getElementVector(i)));
- }
- break;
- }
- }
- }
-};
-
-/**
- * Creates a shape from a VertexInfoBase
- * @param {!o3d.Pack} pack Pack to create objects in.
- * @param {!o3d.Material} material to use.
- * @param {!o3d.Primitive.PrimitiveType} primitiveType The type of primitive.
- * @return {!o3d.Shape} The created shape.
- */
-o3djs.primitives.VertexInfoBase.prototype.createShapeByType = function(
- pack,
- material,
- primitiveType) {
- this.validate();
-
- var numIndices = this.indices.length;
- var numPrimitives;
- switch (primitiveType) {
- case o3djs.base.o3d.Primitive.POINTLIST:
- numPrimitives = numIndices / 1;
- break;
- case o3djs.base.o3d.Primitive.LINELIST:
- numPrimitives = numIndices / 2;
- break;
- case o3djs.base.o3d.Primitive.LINESTRIP:
- numPrimitives = numIndices - 1;
- break;
- case o3djs.base.o3d.Primitive.TRIANGLELIST:
- numPrimitives = numIndices / 3;
- break;
- case o3djs.base.o3d.Primitive.TRIANGLESTRIP:
- case o3djs.base.o3d.Primitive.TRIANGLEFAN:
- numPrimitives = numIndices - 2;
- break;
- default:
- throw 'unknown primitive type';
- }
-
- var positionStream = this.findStream(o3djs.base.o3d.Stream.POSITION);
- var numVertices = positionStream.numElements();
-
- // create a shape and primitive for the vertices.
- var shape = pack.createObject('Shape');
- var primitive = pack.createObject('Primitive');
- var streamBank = pack.createObject('StreamBank');
- primitive.owner = shape;
- primitive.streamBank = streamBank;
- primitive.material = material;
- primitive.numberPrimitives = numPrimitives;
- primitive.primitiveType = primitiveType;
- primitive.numberVertices = numVertices;
- primitive.createDrawElement(pack, null);
-
- // Calculate the tangent and binormal or provide defaults or fail if the
- // effect requires either and they are not present.
- var streamInfos = material.effect.getStreamInfo();
- for (var s = 0; s < streamInfos.length; ++s) {
- var semantic = streamInfos[s].semantic;
- var semanticIndex = streamInfos[s].semanticIndex;
-
- var requiredStream = this.findStream(semantic, semanticIndex);
- if (!requiredStream) {
- switch (semantic) {
- case o3djs.base.o3d.Stream.TANGENT:
- case o3djs.base.o3d.Stream.BINORMAL:
- if (primitiveType == o3djs.base.o3d.Primitive.TRIANGLELIST) {
- this.addTangentStreams(semanticIndex);
- } else {
- throw 'Can not create tangents and binormals for primitive type' +
- primitiveType;
- }
- break;
- case o3djs.base.o3d.Stream.COLOR:
- requiredStream = this.addStream(4, semantic, semanticIndex);
- for (var i = 0; i < numVertices; ++i) {
- requiredStream.addElement(1, 1, 1, 1);
- }
- break;
- case o3djs.base.o3d.Stream.INFLUENCE_WEIGHTS:
- case o3djs.base.o3d.Stream.INFLUENCE_INDICES:
- break;
- default:
- throw 'Missing stream for semantic ' + semantic +
- ' with semantic index ' + semanticIndex;
- }
- }
- }
-
- // These next few lines take our javascript streams and load them into a
- // 'buffer' where the 3D hardware can find them. We have to do this
- // because the 3D hardware can't 'see' javascript data until we copy it to
- // a buffer.
- var vertexBuffer = pack.createObject('VertexBuffer');
- var fields = [];
- for (var s = 0; s < this.streams.length; ++s) {
- var stream = this.streams[s];
- var fieldType = (stream.semantic == o3djs.base.o3d.Stream.COLOR &&
- stream.numComponents == 4) ? 'UByteNField' : 'FloatField';
- fields[s] = vertexBuffer.createField(fieldType, stream.numComponents);
- streamBank.setVertexStream(stream.semantic,
- stream.semanticIndex,
- fields[s],
- 0);
- }
- vertexBuffer.allocateElements(numVertices);
- for (var s = 0; s < this.streams.length; ++s) {
- fields[s].setAt(0, this.streams[s].elements);
- }
-
- var indexBuffer = pack.createObject('IndexBuffer');
- indexBuffer.set(this.indices);
- primitive.indexBuffer = indexBuffer;
- o3djs.primitives.setCullingInfo(primitive);
- return shape;
-};
-
-/**
- * A VertexInfo is a specialization of VertexInfoBase for triangle based
- * geometry.
- * @constructor
- * @extends {o3djs.primitives.VertexInfoBase}
- */
-o3djs.primitives.VertexInfo = function() {
- o3djs.primitives.VertexInfoBase.call(this);
-}
-
-o3djs.base.inherit(o3djs.primitives.VertexInfo,
- o3djs.primitives.VertexInfoBase);
-
-/**
- * Returns the number of triangles represented by the VertexInfo.
- * @return {number} The number of triangles represented by VertexInfo.
- */
-o3djs.primitives.VertexInfo.prototype.numTriangles = function() {
- return this.indices.length / 3;
-};
-
-/**
- * Adds a triangle.
- * @param {number} index1 The index of the first vertex of the triangle.
- * @param {number} index2 The index of the second vertex of the triangle.
- * @param {number} index3 The index of the third vertex of the triangle.
- */
-o3djs.primitives.VertexInfo.prototype.addTriangle = function(
- index1, index2, index3) {
- this.indices.push(index1, index2, index3);
-};
-
-/**
- * Gets the vertex indices of the triangle at the given triangle index.
- * @param {number} triangleIndex The index of the triangle.
- * @return {!Array.<number>} An array of three triangle indices.
- */
-o3djs.primitives.VertexInfo.prototype.getTriangle = function(
- triangleIndex) {
- var indexIndex = triangleIndex * 3;
- return [this.indices[indexIndex + 0],
- this.indices[indexIndex + 1],
- this.indices[indexIndex + 2]];
-};
-
-/**
- * Sets the vertex indices of the triangle at the given triangle index.
- * @param {number} triangleIndex The index of the triangle.
- * @param {number} index1 The index of the first vertex of the triangle.
- * @param {number} index2 The index of the second vertex of the triangle.
- * @param {number} index3 The index of the third vertex of the triangle.
- */
-o3djs.primitives.VertexInfo.prototype.setTriangle = function(
- triangleIndex, index1, index2, index3) {
- var indexIndex = triangleIndex * 3;
- this.indices[indexIndex + 0] = index1;
- this.indices[indexIndex + 1] = index2;
- this.indices[indexIndex + 2] = index3;
-};
-
-/**
- * Creates a shape from a VertexInfo
- * @param {!o3d.Pack} pack Pack to create objects in.
- * @param {!o3d.Material} material to use.
- * @return {!o3d.Shape} The created shape.
- */
-o3djs.primitives.VertexInfo.prototype.createShape = function(
- pack,
- material) {
- return this.createShapeByType(
- pack, material, o3djs.base.o3d.Primitive.TRIANGLELIST);
-};
-
-/**
- * Calculate tangents and binormals based on the positions, normals and
- * texture coordinates found in existing streams.
- * @param {number} opt_semanticIndex The semantic index of the texture
- * coordinate to use and the tangent and binormal streams to add. Defaults
- * to zero.
- */
-o3djs.primitives.VertexInfo.prototype.addTangentStreams =
- function(opt_semanticIndex) {
- opt_semanticIndex = opt_semanticIndex || 0;
- var math = o3djs.math;
-
- this.validate();
-
- // Find and validate the position, normal and texture coordinate frames.
- var positionStream = this.findStream(o3djs.base.o3d.Stream.POSITION);
- if (!positionStream)
- throw 'Cannot calculate tangent frame because POSITION stream is missing';
- if (positionStream.numComponents != 3)
- throw 'Cannot calculate tangent frame because POSITION stream is not 3D';
-
- var normalStream = this.findStream(o3djs.base.o3d.Stream.NORMAL);
- if (!normalStream)
- throw 'Cannot calculate tangent frame because NORMAL stream is missing';
- if (normalStream.numComponents != 3)
- throw 'Cannot calculate tangent frame because NORMAL stream is not 3D';
-
- var texCoordStream = this.findStream(o3djs.base.o3d.Stream.TEXCOORD,
- opt_semanticIndex);
- if (!texCoordStream)
- throw 'Cannot calculate tangent frame because TEXCOORD stream ' +
- opt_semanticIndex + ' is missing';
-
- // Maps from position, normal key to tangent and binormal matrix.
- var tangentFrames = {};
-
- // Rounds a vector to integer components.
- function roundVector(v) {
- return [Math.round(v[0]), Math.round(v[1]), Math.round(v[2])];
- }
-
- // Generates a key for the tangentFrames map from a position and normal
- // vector. Rounds position and normal to allow some tolerance.
- function tangentFrameKey(position, normal) {
- return roundVector(math.mulVectorScalar(position, 100)) + ',' +
- roundVector(math.mulVectorScalar(normal, 100));
- }
-
- // Accumulates into the tangent and binormal matrix at the approximate
- // position and normal.
- function addTangentFrame(position, normal, tangent, binormal) {
- var key = tangentFrameKey(position, normal);
- var frame = tangentFrames[key];
- if (!frame) {
- frame = [[0, 0, 0], [0, 0, 0]];
- }
- math.addVector3To(frame[0], tangent, frame[0]);
- math.addVector3To(frame[1], binormal, frame[1]);
- tangentFrames[key] = frame;
- }
-
- // Get the tangent and binormal matrix at the approximate position and
- // normal.
- function getTangentFrame(position, normal) {
- var key = tangentFrameKey(position, normal);
- return tangentFrames[key];
- }
-
- var numTriangles = this.numTriangles();
- for (var triangleIndex = 0; triangleIndex < numTriangles; ++triangleIndex) {
- // Get the vertex indices, uvs and positions for the triangle.
- var vertexIndices = this.getTriangle(triangleIndex);
- var uvs = [];
- var positions = [];
- var normals = [];
- for (var i = 0; i < 3; ++i) {
- var vertexIndex = vertexIndices[i];
- uvs[i] = texCoordStream.getElementVector(vertexIndex);
- positions[i] = positionStream.getElementVector(vertexIndex);
- normals[i] = normalStream.getElementVector(vertexIndex);
- }
-
- // Calculate the tangent and binormal for the triangle using method
- // described in Maya documentation appendix A: tangent and binormal
- // vectors.
- var tangent = [0, 0, 0];
- var binormal = [0, 0, 0];
- for (var axis = 0; axis < 3; ++axis) {
- var edge1 = [positions[1][axis] - positions[0][axis],
- uvs[1][0] - uvs[0][0], uvs[1][1] - uvs[0][1]];
- var edge2 = [positions[2][axis] - positions[0][axis],
- uvs[2][0] - uvs[0][0], uvs[2][1] - uvs[0][1]];
- var edgeCross = math.normalize(math.cross(edge1, edge2));
- if (edgeCross[0] == 0) {
- edgeCross[0] = 1;
- }
- tangent[axis] = -edgeCross[1] / edgeCross[0];
- binormal[axis] = -edgeCross[2] / edgeCross[0];
- }
-
- // Normalize the tangent and binornmal.
- var tangentLength = math.length(tangent);
- if (tangentLength > 0.001) {
- tangent = math.mulVectorScalar(tangent, 1 / tangentLength);
- }
- var binormalLength = math.length(binormal);
- if (binormalLength > 0.001) {
- binormal = math.mulVectorScalar(binormal, 1 / binormalLength);
- }
-
- // Accumulate the tangent and binormal into the tangent frame map.
- for (var i = 0; i < 3; ++i) {
- addTangentFrame(positions[i], normals[i], tangent, binormal);
- }
- }
-
- // Add the tangent and binormal streams.
- var tangentStream = this.addStream(3,
- o3djs.base.o3d.Stream.TANGENT,
- opt_semanticIndex);
- var binormalStream = this.addStream(3,
- o3djs.base.o3d.Stream.BINORMAL,
- opt_semanticIndex);
-
- // Extract the tangent and binormal for each vertex.
- var numVertices = positionStream.numElements();
- for (var vertexIndex = 0; vertexIndex < numVertices; ++vertexIndex) {
- var position = positionStream.getElementVector(vertexIndex);
- var normal = normalStream.getElementVector(vertexIndex);
- var frame = getTangentFrame(position, normal);
-
- // Orthonormalize the tangent with respect to the normal.
- var tangent = frame[0];
- tangent = math.subVector(
- tangent, math.mulVectorScalar(normal, math.dot(normal, tangent)));
- var tangentLength = math.length(tangent);
- if (tangentLength > 0.001) {
- tangent = math.mulVectorScalar(tangent, 1 / tangentLength);
- }
-
- // Orthonormalize the binormal with respect to the normal and the tangent.
- var binormal = frame[1];
- binormal = math.subVector(
- binormal, math.mulVectorScalar(tangent, math.dot(tangent, binormal)));
- binormal = math.subVector(
- binormal, math.mulVectorScalar(normal, math.dot(normal, binormal)));
- var binormalLength = math.length(binormal);
- if (binormalLength > 0.001) {
- binormal = math.mulVectorScalar(binormal, 1 / binormalLength);
- }
-
- tangentStream.setElementVector(vertexIndex, tangent);
- binormalStream.setElementVector(vertexIndex, binormal);
- }
-};
-
-/**
- * Creates a new VertexInfo.
- * @return {!o3djs.primitives.VertexInfo} The new VertexInfo.
- */
-o3djs.primitives.createVertexInfo = function() {
- return new o3djs.primitives.VertexInfo();
-};
-
-/**
- * Creates sphere vertices.
- * The created sphere has position, normal and uv streams.
- *
- * @param {number} radius radius of the sphere.
- * @param {number} subdivisionsAxis number of steps around the sphere.
- * @param {number} subdivisionsHeight number of vertically on the sphere.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3djs.primitives.VertexInfo} The created sphere vertices.
- */
-o3djs.primitives.createSphereVertices = function(radius,
- subdivisionsAxis,
- subdivisionsHeight,
- opt_matrix) {
- if (subdivisionsAxis <= 0 || subdivisionsHeight <= 0) {
- throw Error('subdivisionAxis and subdivisionHeight must be > 0');
- }
-
- // We are going to generate our sphere by iterating through its
- // spherical coordinates and generating 2 triangles for each quad on a
- // ring of the sphere.
-
- var vertexInfo = o3djs.primitives.createVertexInfo();
- var positionStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.POSITION);
- var normalStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.NORMAL);
- var texCoordStream = vertexInfo.addStream(
- 2, o3djs.base.o3d.Stream.TEXCOORD, 0);
-
- // Generate the individual vertices in our vertex buffer.
- for (var y = 0; y <= subdivisionsHeight; y++) {
- for (var x = 0; x <= subdivisionsAxis; x++) {
- // Generate a vertex based on its spherical coordinates
- var u = x / subdivisionsAxis;
- var v = y / subdivisionsHeight;
- var theta = 2 * Math.PI * u;
- var phi = Math.PI * v;
- var sinTheta = Math.sin(theta);
- var cosTheta = Math.cos(theta);
- var sinPhi = Math.sin(phi);
- var cosPhi = Math.cos(phi);
- var ux = cosTheta * sinPhi;
- var uy = cosPhi;
- var uz = sinTheta * sinPhi;
- positionStream.addElement(radius * ux, radius * uy, radius * uz);
- normalStream.addElement(ux, uy, uz);
- texCoordStream.addElement(1 - u, 1 - v);
- }
- }
- var numVertsAround = subdivisionsAxis + 1;
-
- for (var x = 0; x < subdivisionsAxis; x++) {
- for (var y = 0; y < subdivisionsHeight; y++) {
- // Make triangle 1 of quad.
- vertexInfo.addTriangle(
- (y + 0) * numVertsAround + x,
- (y + 0) * numVertsAround + x + 1,
- (y + 1) * numVertsAround + x);
-
- // Make triangle 2 of quad.
- vertexInfo.addTriangle(
- (y + 1) * numVertsAround + x,
- (y + 0) * numVertsAround + x + 1,
- (y + 1) * numVertsAround + x + 1);
- }
- }
-
- if (opt_matrix) {
- vertexInfo.reorient(opt_matrix);
- }
- return vertexInfo;
-};
-
-/**
- * Creates a sphere.
- * The created sphere has position, normal and uv streams.
- *
- * @param {!o3d.Pack} pack Pack to create sphere elements in.
- * @param {!o3d.Material} material to use.
- * @param {number} radius radius of the sphere.
- * @param {number} subdivisionsAxis number of steps around the sphere.
- * @param {number} subdivisionsHeight number of vertically on the sphere.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3d.Shape} The created sphere.
- *
- * @see o3d.Pack
- * @see o3d.Shape
- */
-o3djs.primitives.createSphere = function(pack,
- material,
- radius,
- subdivisionsAxis,
- subdivisionsHeight,
- opt_matrix) {
- var vertexInfo = o3djs.primitives.createSphereVertices(
- radius,
- subdivisionsAxis,
- subdivisionsHeight,
- opt_matrix);
-
- return vertexInfo.createShape(pack, material);
-};
-
-/**
- * Array of the indices of corners of each face of a cube.
- * @private
- * @type {!Array.<!Array.<number>>}
- */
-o3djs.primitives.CUBE_FACE_INDICES_ = [
- [3, 7, 5, 1],
- [0, 4, 6, 2],
- [6, 7, 3, 2],
- [0, 1, 5, 4],
- [5, 7, 6, 4],
- [2, 3, 1, 0]
-];
-
-/**
- * Creates the vertices and indices for a cube. The
- * cube will be created around the origin. (-size / 2, size / 2)
- * The created cube has position, normal and uv streams.
- *
- * @param {number} size Width, height and depth of the cube.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3djs.primitives.VertexInfo} The created cube vertices.
- */
-o3djs.primitives.createCubeVertices = function(size, opt_matrix) {
- var k = size / 2;
-
- var cornerVertices = [
- [-k, -k, -k],
- [+k, -k, -k],
- [-k, +k, -k],
- [+k, +k, -k],
- [-k, -k, +k],
- [+k, -k, +k],
- [-k, +k, +k],
- [+k, +k, +k]
- ];
-
- var faceNormals = [
- [+1, +0, +0],
- [-1, +0, +0],
- [+0, +1, +0],
- [+0, -1, +0],
- [+0, +0, +1],
- [+0, +0, -1]
- ];
-
- var uvCoords = [
- [0, 0],
- [1, 0],
- [1, 1],
- [0, 1]
- ];
-
- var vertexInfo = o3djs.primitives.createVertexInfo();
- var positionStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.POSITION);
- var normalStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.NORMAL);
- var texCoordStream = vertexInfo.addStream(
- 2, o3djs.base.o3d.Stream.TEXCOORD, 0);
-
- for (var f = 0; f < 6; ++f) {
- var faceIndices = o3djs.primitives.CUBE_FACE_INDICES_[f];
- for (var v = 0; v < 4; ++v) {
- var position = cornerVertices[faceIndices[v]];
- var normal = faceNormals[f];
- var uv = uvCoords[v];
-
- // Each face needs all four vertices because the normals and texture
- // coordinates are not all the same.
- positionStream.addElementVector(position);
- normalStream.addElementVector(normal);
- texCoordStream.addElementVector(uv);
-
- // Two triangles make a square face.
- var offset = 4 * f;
- vertexInfo.addTriangle(offset + 0, offset + 1, offset + 2);
- vertexInfo.addTriangle(offset + 0, offset + 2, offset + 3);
- }
- }
-
- if (opt_matrix) {
- vertexInfo.reorient(opt_matrix);
- }
- return vertexInfo;
-};
-
-/**
- * Creates a cube.
- * The cube will be created around the origin. (-size / 2, size / 2)
- * The created cube has position, normal and uv streams.
- *
- * @param {!o3d.Pack} pack Pack to create cube elements in.
- * @param {!o3d.Material} material to use.
- * @param {number} size Width, height and depth of the cube.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3d.Shape} The created cube.
- *
- * @see o3d.Pack
- * @see o3d.Shape
- */
-o3djs.primitives.createCube = function(pack,
- material,
- size,
- opt_matrix) {
- var vertexInfo = o3djs.primitives.createCubeVertices(size, opt_matrix);
- return vertexInfo.createShape(pack, material);
-};
-
-/**
- * Creates a box. The box will be created around the origin.
- * The created box has position, normal and uv streams.
- *
- * @param {!o3d.Pack} pack Pack to create Box elements in.
- * @param {!o3d.Material} material to use.
- * @param {number} width Width of the box.
- * @param {number} height Height of the box.
- * @param {number} depth Depth of the box.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3d.Shape} The created Box.
- *
- * @see o3d.Pack
- * @see o3d.Shape
- */
-o3djs.primitives.createBox = function(pack,
- material,
- width,
- height,
- depth,
- opt_matrix) {
- var vertexInfo = o3djs.primitives.createCubeVertices(1);
- vertexInfo.reorient(o3djs.math.makeMatrix4(width, 0, 0, 0,
- 0, height, 0, 0,
- 0, 0, depth, 0,
- 0, 0, 0, 1));
-
- if (opt_matrix) {
- vertexInfo.reorient(opt_matrix);
- }
- return vertexInfo.createShape(pack, material);
-};
-
-/**
- * Creates a cube with varying vertex colors. The cube will be created
- * around the origin. (-size / 2, size / 2)
- *
- * @param {!o3d.Pack} pack Pack to create cube elements in.
- * @param {!o3d.Material} material to use.
- * @param {number} size Width, height and depth of the cube.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3d.Shape} The created cube.
- *
- * @see o3d.Pack
- * @see o3d.Shape
- */
-o3djs.primitives.createRainbowCube = function(pack,
- material,
- size,
- opt_matrix) {
- var vertexInfo = o3djs.primitives.createCubeVertices(size, opt_matrix);
- var colorStream = vertexInfo.addStream(
- 4, o3djs.base.o3d.Stream.COLOR);
-
- var colors = [
- [1, 0, 0, 1],
- [0, 1, 0, 1],
- [0, 0, 1, 1],
- [1, 1, 0, 1],
- [0, 1, 1, 1],
- [1, 0, 1, 1],
- [0, .5, .3, 1],
- [.3, 0, .5, 1]
- ];
-
- var vertices = vertexInfo.vertices;
- for (var f = 0; f < 6; ++f) {
- var faceIndices = o3djs.primitives.CUBE_FACE_INDICES_[f];
- for (var v = 0; v < 4; ++v) {
- var color = colors[faceIndices[v]];
- colorStream.addElementVector(color);
- }
- }
-
- return vertexInfo.createShape(pack, material);
-};
-
-/**
- * Creates disc vertices. The disc will be in the xz plane, centered
- * at the origin. When creating, at least 3 divisions, or pie pieces, need
- * to be specified, otherwise the triangles making up the disc will be
- * degenerate. You can also specify the number of radial pieces (opt_stacks).
- * A value of 1 for opt_stacks will give you a simple disc of pie pieces. If
- * you want to create an annulus by omitting some of the center stacks, you
- * can specify the stack at which to start creating triangles. Finally,
- * stackPower allows you to have the widths increase or decrease as you move
- * away from the center. This is particularly useful when using the disc as a
- * ground plane with a fixed camera such that you don't need the resolution of
- * small triangles near the perimeter. For example, a value of 2 will produce
- * stacks whose ouside radius increases with the square of the stack index. A
- * value of 1 will give uniform stacks.
- *
- * @param {number} radius Radius of the ground plane.
- * @param {number} divisions Number of triangles in the ground plane
- * (at least 3).
- * @param {number} opt_stacks Number of radial divisions (default=1).
- * @param {number} opt_startStack Which radial division to start dividing at.
- * @param {number} opt_stackPower Power to raise stack size to for decreasing
- * width.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3djs.primitives.VertexInfo} The created plane vertices.
- */
-o3djs.primitives.createDiscVertices = function(radius,
- divisions,
- opt_stacks,
- opt_startStack,
- opt_stackPower,
- opt_matrix) {
- if (divisions < 3) {
- throw Error('divisions must be at least 3');
- }
-
- var stacks = opt_stacks ? opt_stacks : 1;
- var startStack = opt_startStack ? opt_startStack : 0;
- var stackPower = opt_stackPower ? opt_stackPower : 1;
-
- var vertexInfo = o3djs.primitives.createVertexInfo();
- var positionStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.POSITION);
- var normalStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.NORMAL);
- var texCoordStream = vertexInfo.addStream(
- 2, o3djs.base.o3d.Stream.TEXCOORD, 0);
-
- // Initialize the center vertex.
- // x y z nx ny nz r g b a u v
- var firstIndex = 0;
-
- if (startStack == 0) {
- positionStream.addElement(0, 0, 0);
- normalStream.addElement(0, 1, 0);
- texCoordStream.addElement(0, 0);
- firstIndex++;
- }
-
- // Build the disk one stack at a time.
- for (var currentStack = Math.max(startStack, 1);
- currentStack <= stacks;
- ++currentStack) {
- var stackRadius = radius * Math.pow(currentStack / stacks, stackPower);
-
- for (var i = 0; i < divisions; ++i) {
- var theta = 2.0 * Math.PI * i / divisions;
- var x = stackRadius * Math.cos(theta);
- var z = stackRadius * Math.sin(theta);
-
- positionStream.addElement(x, 0, z);
- normalStream.addElement(0, 1, 0);
- texCoordStream.addElement(x, z);
-
- if (currentStack > startStack) {
- // a, b, c and d are the indices of the vertices of a quad. unless
- // the current stack is the one closest to the center, in which case
- // the vertices a and b connect to the center vertex.
- var a = firstIndex + (i + 1) % divisions;
- var b = firstIndex + i;
- if (currentStack > 1) {
- var c = firstIndex + i - divisions;
- var d = firstIndex + (i + 1) % divisions - divisions;
-
- // Make a quad of the vertices a, b, c, d.
- vertexInfo.addTriangle(a, b, c);
- vertexInfo.addTriangle(a, c, d);
- } else {
- // Make a single triangle of a, b and the center.
- vertexInfo.addTriangle(0, a, b);
- }
- }
- }
-
- firstIndex += divisions;
- }
-
- if (opt_matrix) {
- vertexInfo.reorient(opt_matrix);
- }
- return vertexInfo;
-};
-
-/**
- * Creates a disc shape. The disc will be in the xz plane, centered
- * at the origin. When creating, at least 3 divisions, or pie pieces, need
- * to be specified, otherwise the triangles making up the disc will be
- * degenerate. You can also specify the number of radial pieces (opt_stacks).
- * A value of 1 for opt_stacks will give you a simple disc of pie pieces. If
- * you want to create an annulus by omitting some of the center stacks, you
- * can specify the stack at which to start creating triangles. Finally,
- * stackPower allows you to have the widths increase or decrease as you move
- * away from the center. This is particularly useful when using the disc as a
- * ground plane with a fixed camera such that you don't need the resolution of
- * small triangles near the perimeter. For example, a value of 2 will produce
- * stacks whose ouside radius increases with the square of the stack index. A
- * value of 1 will give uniform stacks.
- *
- * @param {!o3d.Pack} pack Pack to create disc elements in.
- * @param {!o3d.Material} material to use.
- * @param {number} radius Radius of the disc.
- * @param {number} divisions Number of triangles in the disc (at least 3).
- * @param {number} stacks Number of radial divisions.
- * @param {number} startStack Which radial division to start dividing at.
- * @param {number} stackPower Power to raise stack size to for decreasing width.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3d.Shape} The created disc.
- *
- * @see o3d.Pack
- * @see o3d.Shape
- */
-o3djs.primitives.createDisc = function(pack, material,
- radius, divisions, stacks,
- startStack, stackPower,
- opt_matrix) {
- var vertexInfo = o3djs.primitives.createDiscVertices(radius, divisions,
- stacks,
- startStack,
- stackPower,
- opt_matrix);
-
- return vertexInfo.createShape(pack, material);
-};
-
-/**
- * Creates cylinder vertices. The cylinder will be created around the origin
- * along the y-axis. The created cylinder has position, normal and uv streams.
- *
- * @param {number} radius Radius of cylinder.
- * @param {number} height Height of cylinder.
- * @param {number} radialSubdivisions The number of subdivisions around the
- * cylinder.
- * @param {number} verticalSubdivisions The number of subdivisions down the
- * cylinder.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3djs.primitives.VertexInfo} The created cylinder vertices.
- */
-o3djs.primitives.createCylinderVertices = function(radius,
- height,
- radialSubdivisions,
- verticalSubdivisions,
- opt_matrix) {
- return o3djs.primitives.createTruncatedConeVertices(radius,
- radius,
- height,
- radialSubdivisions,
- verticalSubdivisions,
- opt_matrix);
-};
-
-/**
- * Creates a cylinder shape. The cylinder will be created around the
- * origin along the y-axis. The created cylinder has position, normal
- * and uv streams.
- *
- * @param {!o3d.Pack} pack Pack to create cylinder elements in.
- * @param {!o3d.Material} material to use.
- * @param {number} radius Radius of cylinder.
- * @param {number} height Height of cylinder.
- * @param {number} radialSubdivisions The number of subdivisions around the
- * cylinder.
- * @param {number} verticalSubdivisions The number of subdivisions down the
- * cylinder.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3d.Shape} The created cylinder.
- */
-o3djs.primitives.createCylinder = function(pack,
- material,
- radius,
- height,
- radialSubdivisions,
- verticalSubdivisions,
- opt_matrix) {
- var vertexInfo = o3djs.primitives.createCylinderVertices(
- radius,
- height,
- radialSubdivisions,
- verticalSubdivisions,
- opt_matrix);
- return vertexInfo.createShape(pack, material);
-};
-
-/**
- * Creates vertices for a truncated cone, which is like a cylinder
- * except that it has different top and bottom radii. A truncated cone
- * can also be used to create cylinders and regular cones. The
- * truncated cone will be created centered about the origin, with the
- * y axis as its vertical axis. The created cone has position, normal
- * and uv streams.
- *
- * @param {number} bottomRadius Bottom radius of truncated cone.
- * @param {number} topRadius Top radius of truncated cone.
- * @param {number} height Height of truncated cone.
- * @param {number} radialSubdivisions The number of subdivisions around the
- * truncated cone.
- * @param {number} verticalSubdivisions The number of subdivisions down the
- * truncated cone.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3djs.primitives.VertexInfo} The created truncated cone vertices.
- */
-o3djs.primitives.createTruncatedConeVertices = function(bottomRadius,
- topRadius,
- height,
- radialSubdivisions,
- verticalSubdivisions,
- opt_matrix) {
- if (radialSubdivisions < 3) {
- throw Error('radialSubdivisions must be 3 or greater');
- }
-
- if (verticalSubdivisions < 1) {
- throw Error('verticalSubdivisions must be 1 or greater');
- }
-
- var vertexInfo = o3djs.primitives.createVertexInfo();
- var positionStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.POSITION);
- var normalStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.NORMAL);
- var texCoordStream = vertexInfo.addStream(
- 2, o3djs.base.o3d.Stream.TEXCOORD, 0);
-
- var vertsAroundEdge = radialSubdivisions + 1;
-
- // The slant of the cone is constant across its surface
- var slant = Math.atan2(bottomRadius - topRadius, height);
- var cosSlant = Math.cos(slant);
- var sinSlant = Math.sin(slant);
-
- for (var yy = -2; yy <= verticalSubdivisions + 2; ++yy) {
- var v = yy / verticalSubdivisions
- var y = height * v;
- var ringRadius;
- if (yy < 0) {
- y = 0;
- v = 1;
- ringRadius = bottomRadius;
- } else if (yy > verticalSubdivisions) {
- y = height;
- v = 1;
- ringRadius = topRadius;
- } else {
- ringRadius = bottomRadius +
- (topRadius - bottomRadius) * (yy / verticalSubdivisions);
- }
- if (yy == -2 || yy == verticalSubdivisions + 2) {
- ringRadius = 0;
- v = 0;
- }
- y -= height / 2;
- for (var ii = 0; ii < vertsAroundEdge; ++ii) {
- var sin = Math.sin(ii * Math.PI * 2 / radialSubdivisions);
- var cos = Math.cos(ii * Math.PI * 2 / radialSubdivisions);
- positionStream.addElement(sin * ringRadius, y, cos * ringRadius);
- normalStream.addElement(
- (yy < 0 || yy > verticalSubdivisions) ? 0 : (sin * cosSlant),
- (yy < 0) ? -1 : (yy > verticalSubdivisions ? 1 : sinSlant),
- (yy < 0 || yy > verticalSubdivisions) ? 0 : (cos * cosSlant));
- texCoordStream.addElement(ii / radialSubdivisions, v);
- }
- }
-
- for (var yy = 0; yy < verticalSubdivisions + 4; ++yy) {
- for (var ii = 0; ii < radialSubdivisions; ++ii) {
- vertexInfo.addTriangle(vertsAroundEdge * (yy + 0) + 0 + ii,
- vertsAroundEdge * (yy + 0) + 1 + ii,
- vertsAroundEdge * (yy + 1) + 1 + ii);
- vertexInfo.addTriangle(vertsAroundEdge * (yy + 0) + 0 + ii,
- vertsAroundEdge * (yy + 1) + 1 + ii,
- vertsAroundEdge * (yy + 1) + 0 + ii);
- }
- }
-
- if (opt_matrix) {
- vertexInfo.reorient(opt_matrix);
- }
- return vertexInfo;
-};
-
-/**
- * Creates a truncated cone shape, which is like a cylinder except
- * that it has different top and bottom radii. A truncated cone can
- * also be used to create cylinders, by setting the bottom and top
- * radii equal, and cones, by setting either the top or bottom radius
- * to 0. The truncated cone will be created centered about the origin,
- * with the y axis as its vertical axis. The created cone has
- * position, normal and uv streams.
- *
- * @param {!o3d.Pack} pack Pack in which to create the truncated cone.
- * @param {!o3d.Material} material to use.
- * @param {number} bottomRadius Bottom radius of truncated cone.
- * @param {number} topRadius Top radius of truncated cone.
- * @param {number} height Height of truncated cone.
- * @param {number} radialSubdivisions The number of subdivisions around the
- * truncated cone.
- * @param {number} verticalSubdivisions The number of subdivisions down the
- * truncated cone.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3d.Shape} The created truncated cone.
- */
-o3djs.primitives.createTruncatedCone = function(pack,
- material,
- bottomRadius,
- topRadius,
- height,
- radialSubdivisions,
- verticalSubdivisions,
- opt_matrix) {
- var vertexInfo = o3djs.primitives.createTruncatedConeVertices(
- bottomRadius,
- topRadius,
- height,
- radialSubdivisions,
- verticalSubdivisions,
- opt_matrix);
- return vertexInfo.createShape(pack, material);
-};
-
-/**
- * Creates vertices for a torus. The torus will be created centered about the
- * origin, with the y axis as its vertical axis. The created torus has
- * position, normal and uv streams.
- *
- * @param {number} torusRadius Distance from the center of the tube to
- * the center of the torus.
- * @param {number} tubeRadius Radius of the tube.
- * @param {number} tubeLengthSubdivisions The number of subdivisions around the
- * vertical axis of the torus, i.e. along the length of the tube.
- * @param {number} circleSubdivisions The number of subdivisions in the circle
- * that is rotated about the vertical axis to create the torus.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3djs.primitives.VertexInfo} The created torus vertices.
- */
-o3djs.primitives.createTorusVertices = function(torusRadius,
- tubeRadius,
- tubeLengthSubdivisions,
- circleSubdivisions,
- opt_matrix) {
- if (tubeLengthSubdivisions < 3) {
- throw Error('tubeLengthSubdivisions must be 3 or greater');
- }
-
- if (circleSubdivisions < 3) {
- throw Error('circleSubdivisions must be 3 or greater');
- }
-
- var vertexInfo = o3djs.primitives.createVertexInfo();
- var positionStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.POSITION);
- var normalStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.NORMAL);
- var texCoordStream = vertexInfo.addStream(
- 2, o3djs.base.o3d.Stream.TEXCOORD, 0);
-
- for (var uu = 0; uu < tubeLengthSubdivisions; ++uu) {
- var u = (uu / tubeLengthSubdivisions) * 2 * Math.PI;
- for (var vv = 0; vv < circleSubdivisions; ++vv) {
- var v = (vv / circleSubdivisions) * 2 * Math.PI;
- var sinu = Math.sin(u);
- var cosu = Math.cos(u);
- var sinv = Math.sin(v);
- var cosv = Math.cos(v);
- positionStream.addElement((torusRadius + tubeRadius * cosv) * cosu,
- tubeRadius * sinv,
- (torusRadius + tubeRadius * cosv) * sinu);
- normalStream.addElement(cosv * cosu,
- sinv,
- cosv * sinu);
- texCoordStream.addElement(uu / tubeLengthSubdivisions,
- vv / circleSubdivisions);
- }
- }
-
- for (var uu = 0; uu < tubeLengthSubdivisions; ++uu) {
- for (var vv = 0; vv < circleSubdivisions; ++vv) {
- // We want to wrap the indices around at the seams.
- var uuPlusOne = (uu + 1) % tubeLengthSubdivisions;
- var vvPlusOne = (vv + 1) % circleSubdivisions;
- // The indices of four points forming a quad.
- var a = circleSubdivisions * uu + vv;
- var b = circleSubdivisions * uuPlusOne + vv;
- var c = circleSubdivisions * uu + vvPlusOne;
- var d = circleSubdivisions * uuPlusOne + vvPlusOne;
- vertexInfo.addTriangle(a, d, b);
- vertexInfo.addTriangle(a, c, d);
- }
- }
-
- if (opt_matrix) {
- vertexInfo.reorient(opt_matrix);
- }
- return vertexInfo;
-};
-
-/**
- * Creates a torus shape. The torus will be created centered about the
- * origin, with the y axis as its vertical axis. The created torus has
- * position, normal and uv streams.
- *
- * @param {!o3d.Pack} pack Pack in which to create the torus.
- * @param {!o3d.Material} material to use.
- * @param {number} torusRadius Distance from the center of the tube to
- * the center of the torus.
- * @param {number} tubeRadius Radius of the tube.
- * @param {number} tubeLengthSubdivisions The number of subdivisions around the
- * vertical axis of the torus, i.e. along the length of the tube.
- * @param {number} circleSubdivisions The number of subdivisions in the circle
- * that is rotated about the vertical axis to create the torus.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3d.Shape} The created torus.
- */
-o3djs.primitives.createTorus = function(pack,
- material,
- torusRadius,
- tubeRadius,
- tubeLengthSubdivisions,
- circleSubdivisions,
- opt_matrix) {
- var vertexInfo = o3djs.primitives.createTorusVertices(
- torusRadius,
- tubeRadius,
- tubeLengthSubdivisions,
- circleSubdivisions,
- opt_matrix);
- return vertexInfo.createShape(pack, material);
-};
-
-/**
- * Creates wedge vertices, wedge being an extruded triangle. The wedge will be
- * created around the 3 2d points passed in and extruded along the z axis. The
- * created wedge has position, normal and uv streams.
- *
- * @param {!Array.<!Array.<number>>} inPoints Array of 2d points in the format
- * [[x1, y1], [x2, y2], [x3, y3]] that describe a 2d triangle.
- * @param {number} depth The depth to extrude the triangle.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3djs.primitives.VertexInfo} The created wedge vertices.
- */
-o3djs.primitives.createWedgeVertices = function(inPoints, depth,
- opt_matrix) {
- var math = o3djs.math;
-
- var vertexInfo = o3djs.primitives.createVertexInfo();
- var positionStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.POSITION);
- var normalStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.NORMAL);
- var texCoordStream = vertexInfo.addStream(
- 2, o3djs.base.o3d.Stream.TEXCOORD, 0);
-
- var z1 = -depth * 0.5;
- var z2 = depth * 0.5;
- var face = [];
- var points = [[inPoints[0][0], inPoints[0][1]],
- [inPoints[1][0], inPoints[1][1]],
- [inPoints[2][0], inPoints[2][1]]];
-
- face[0] = math.cross(
- math.normalize([points[1][0] - points[0][0],
- points[1][1] - points[0][1],
- z1 - z1]),
- math.normalize([points[1][0] - points[1][0],
- points[1][1] - points[1][1],
- z2 - z1]));
- face[1] = math.cross(
- math.normalize([points[2][0] - points[1][0],
- points[2][1] - points[1][1],
- z1 - z1]),
- math.normalize([points[2][0] - points[2][0],
- points[2][1] - points[2][1],
- z2 - z1]));
- face[2] = math.cross(
- [points[0][0] - points[2][0], points[0][1] - points[2][1], z1 - z1],
- [points[0][0] - points[0][0], points[0][1] - points[0][1], z2 - z1]);
-
- positionStream.addElement(points[0][0], points[0][1], z1);
- normalStream.addElement(0, 0, -1);
- texCoordStream.addElement(0, 1);
- positionStream.addElement(points[1][0], points[1][1], z1);
- normalStream.addElement(0, 0, -1);
- texCoordStream.addElement(1, 0);
- positionStream.addElement(points[2][0], points[2][1], z1);
- normalStream.addElement(0, 0, -1);
- texCoordStream.addElement(0, 0);
- // back
- positionStream.addElement(points[0][0], points[0][1], z2);
- normalStream.addElement(0, 0, 1);
- texCoordStream.addElement(0, 1);
- positionStream.addElement(points[1][0], points[1][1], z2);
- normalStream.addElement(0, 0, 1);
- texCoordStream.addElement(1, 0);
- positionStream.addElement(points[2][0], points[2][1], z2);
- normalStream.addElement(0, 0, 1);
- texCoordStream.addElement(0, 0);
- // face 0
- positionStream.addElement(points[0][0], points[0][1], z1);
- normalStream.addElement(face[0][0], face[0][1], face[0][2]);
- texCoordStream.addElement(0, 1);
- positionStream.addElement(points[1][0], points[1][1], z1);
- normalStream.addElement(face[0][0], face[0][1], face[0][2]);
- texCoordStream.addElement(0, 0);
- positionStream.addElement(points[1][0], points[1][1], z2);
- normalStream.addElement(face[0][0], face[0][1], face[0][2]);
- texCoordStream.addElement(1, 0);
- positionStream.addElement(points[0][0], points[0][1], z2);
- normalStream.addElement(face[0][0], face[0][1], face[0][2]);
- texCoordStream.addElement(1, 1);
- // face 1
- positionStream.addElement(points[1][0], points[1][1], z1);
- normalStream.addElement(face[1][0], face[1][1], face[1][2]);
- texCoordStream.addElement(0, 1);
- positionStream.addElement(points[2][0], points[2][1], z1);
- normalStream.addElement(face[1][0], face[1][1], face[1][2]);
- texCoordStream.addElement(0, 0);
- positionStream.addElement(points[2][0], points[2][1], z2);
- normalStream.addElement(face[1][0], face[1][1], face[1][2]);
- texCoordStream.addElement(1, 0);
- positionStream.addElement(points[1][0], points[1][1], z2);
- normalStream.addElement(face[1][0], face[1][1], face[1][2]);
- texCoordStream.addElement(1, 1);
- // face 2
- positionStream.addElement(points[2][0], points[2][1], z1);
- normalStream.addElement(face[2][0], face[2][1], face[2][2]);
- texCoordStream.addElement(0, 1);
- positionStream.addElement(points[0][0], points[0][1], z1);
- normalStream.addElement(face[2][0], face[2][1], face[2][2]);
- texCoordStream.addElement(0, 0);
- positionStream.addElement(points[0][0], points[0][1], z2);
- normalStream.addElement(face[2][0], face[2][1], face[2][2]);
- texCoordStream.addElement(1, 0);
- positionStream.addElement(points[2][0], points[2][1], z2);
- normalStream.addElement(face[2][0], face[2][1], face[2][2]);
- texCoordStream.addElement(1, 1);
-
- vertexInfo.addTriangle(0, 2, 1);
- vertexInfo.addTriangle(3, 4, 5);
- vertexInfo.addTriangle(6, 7, 8);
- vertexInfo.addTriangle(6, 8, 9);
- vertexInfo.addTriangle(10, 11, 12);
- vertexInfo.addTriangle(10, 12, 13);
- vertexInfo.addTriangle(14, 15, 16);
- vertexInfo.addTriangle(14, 16, 17);
-
- if (opt_matrix) {
- vertexInfo.reorient(opt_matrix);
- }
- return vertexInfo;
-};
-
-/**
- * Creates a wedge shape. A wedge being an extruded triangle. The wedge will
- * be created around the 3 2d points passed in and extruded along the z-axis.
- * The created wedge has position, normal and uv streams.
- *
- * @param {!o3d.Pack} pack Pack to create wedge elements in.
- * @param {!o3d.Material} material to use.
- * @param {!Array.<!Array.<number>>} points Array of 2d points in the format
- * [[x1, y1], [x2, y2], [x3, y3]] that describe a 2d triangle.
- * @param {number} depth The depth to extrude the triangle.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3d.Shape} The created wedge.
- */
-o3djs.primitives.createWedge = function(pack,
- material,
- points,
- depth,
- opt_matrix) {
- var vertexInfo = o3djs.primitives.createWedgeVertices(points,
- depth,
- opt_matrix);
- return vertexInfo.createShape(pack, material);
-};
-
-/**
- * Creates prism vertices by extruding a polygon. The prism will be created
- * around the 2d points passed in and extruded along the z axis. The end caps
- * of the prism are constructed using a triangle fan originating at point 0,
- * so a non-convex polygon might not get the desired shape, but it will if it
- * is convex with respect to point 0. Texture coordinates map each face of
- * the wall exactly to the unit square. Texture coordinates on the front
- * and back faces are scaled such that the bounding rectangle of the polygon
- * is mapped to the unit square. The created prism has position, normal,
- * uv streams.
- *
- * @param {!Array.<!Array.<number>>} points Array of 2d points in the format
- * [[x1, y1], [x2, y2], [x3, y3],...] that describe a 2d polygon.
- * @param {number} depth The depth to extrude the polygon.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3djs.primitives.VertexInfo} The created prism vertices.
- */
-o3djs.primitives.createPrismVertices = function(points,
- depth,
- opt_matrix) {
- if (points.length < 3) {
- throw Error('there must be 3 or more points');
- }
-
- var backZ = -0.5 * depth;
- var frontZ = 0.5 * depth;
- var normals = [];
-
- var vertexInfo = o3djs.primitives.createVertexInfo();
- var positionStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.POSITION);
- var normalStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.NORMAL);
- var texCoordStream = vertexInfo.addStream(
- 2, o3djs.base.o3d.Stream.TEXCOORD, 0);
-
- // Normals for the wall faces.
- var n = points.length;
-
- for (var i = 0; i < n; ++i) {
- var j = (i + 1) % n;
- var x = points[j][0] - points[i][0];
- var y = points[j][1] - points[i][1];
- var length = Math.sqrt(x * x + y * y);
- normals[i] = [y / length, -x / length, 0];
- }
-
- // Compute the minimum and maxiumum x and y coordinates of points in the
- // polygon.
- var minX = points[0][0];
- var minY = points[0][1];
- var maxX = points[0][0];
- var maxY = points[0][1];
- for (var i = 1; i < n; ++i) {
- var x = points[i][0];
- var y = points[i][1];
- minX = Math.min(minX, x);
- minY = Math.min(minY, y);
- maxX = Math.max(maxX, x);
- maxY = Math.max(maxY, y);
- }
-
- // Scale the x and y coordinates of the points of the polygon to fit the
- // bounding rectangle, and use the scaled coordinates for the uv
- // of the front and back cap.
- var frontUV = [];
- var backUV = [];
- var rangeX = maxX - minX;
- var rangeY = maxY - minY;
- for (var i = 0; i < n; ++i) {
- frontUV[i] = [
- (points[i][0] - minX) / rangeX,
- (points[i][1] - minY) / rangeY
- ];
- backUV[i] = [
- (maxX - points[i][0]) / rangeX,
- (points[i][1] - minY) / rangeY
- ];
- }
-
- for (var i = 0; i < n; ++i) {
- var j = (i + 1) % n;
- // Vertex on the back face.
- positionStream.addElement(points[i][0], points[i][1], backZ);
- normalStream.addElement(0, 0, -1);
- texCoordStream.addElement(backUV[i][0], backUV[i][1]);
-
- // Vertex on the front face.
- positionStream.addElement(points[i][0], points[i][1], frontZ),
- normalStream.addElement(0, 0, 1);
- texCoordStream.addElement(frontUV[i][0], frontUV[i][1]);
-
- // Vertices for a quad on the wall.
- positionStream.addElement(points[i][0], points[i][1], backZ),
- normalStream.addElement(normals[i][0], normals[i][1], normals[i][2]);
- texCoordStream.addElement(0, 1);
-
- positionStream.addElement(points[j][0], points[j][1], backZ),
- normalStream.addElement(normals[i][0], normals[i][1], normals[i][2]);
- texCoordStream.addElement(0, 0);
-
- positionStream.addElement(points[j][0], points[j][1], frontZ),
- normalStream.addElement(normals[i][0], normals[i][1], normals[i][2]);
- texCoordStream.addElement(1, 0);
-
- positionStream.addElement(points[i][0], points[i][1], frontZ),
- normalStream.addElement(normals[i][0], normals[i][1], normals[i][2]);
- texCoordStream.addElement(1, 1);
-
- if (i > 0 && i < n - 1) {
- // Triangle for the back face.
- vertexInfo.addTriangle(0, 6 * (i + 1), 6 * i);
-
- // Triangle for the front face.
- vertexInfo.addTriangle(1, 6 * i + 1, 6 * (i + 1) + 1);
- }
-
- // Quad on the wall.
- vertexInfo.addTriangle(6 * i + 2, 6 * i + 3, 6 * i + 4);
- vertexInfo.addTriangle(6 * i + 2, 6 * i + 4, 6 * i + 5);
- }
-
- if (opt_matrix) {
- vertexInfo.reorient(opt_matrix);
- }
- return vertexInfo;
-};
-
-/**
- * Creates a prism shape by extruding a polygon. The prism will be created
- * around the 2d points passed in an array and extruded along the z-axis.
- * The end caps of the prism are constructed using a triangle fan originating
- * at the first point, so a non-convex polygon might not get the desired
- * shape, but it will if it is convex with respect to the first point.
- * Texture coordinates map each face of the wall exactly to the unit square.
- * Texture coordinates on the front and back faces are scaled such that the
- * bounding rectangle of the polygon is mapped to the unit square.
- * The created prism has position, normal and uv streams.
- *
- * @param {!o3d.Pack} pack Pack to create wedge elements in.
- * @param {!o3d.Material} material to use.
- * @param {!Array.<!Array.<number>>} points Array of 2d points in the format:
- * [[x1, y1], [x2, y2], [x3, y3],...] that describe a 2d polygon.
- * @param {number} depth The depth to extrude the polygon.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3d.Shape} The created prism.
- */
-o3djs.primitives.createPrism = function(pack,
- material,
- points,
- depth,
- opt_matrix) {
- var vertexInfo = o3djs.primitives.createPrismVertices(points,
- depth,
- opt_matrix);
- return vertexInfo.createShape(pack, material);
-};
-
-/**
- * Creates XZ plane vertices.
- * The created plane has position, normal and uv streams.
- *
- * @param {number} width Width of the plane.
- * @param {number} depth Depth of the plane.
- * @param {number} subdivisionsWidth Number of steps across the plane.
- * @param {number} subdivisionsDepth Number of steps down the plane.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3djs.primitives.VertexInfo} The created plane vertices.
- */
-o3djs.primitives.createPlaneVertices = function(width,
- depth,
- subdivisionsWidth,
- subdivisionsDepth,
- opt_matrix) {
- if (subdivisionsWidth <= 0 || subdivisionsDepth <= 0) {
- throw Error('subdivisionWidth and subdivisionDepth must be > 0');
- }
-
- var vertexInfo = o3djs.primitives.createVertexInfo();
- var positionStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.POSITION);
- var normalStream = vertexInfo.addStream(
- 3, o3djs.base.o3d.Stream.NORMAL);
- var texCoordStream = vertexInfo.addStream(
- 2, o3djs.base.o3d.Stream.TEXCOORD, 0);
-
- // Generate the individual vertices in our vertex buffer.
- for (var z = 0; z <= subdivisionsDepth; z++) {
- for (var x = 0; x <= subdivisionsWidth; x++) {
- var u = x / subdivisionsWidth;
- var v = z / subdivisionsDepth;
- positionStream.addElement(width * u - width * 0.5,
- 0,
- depth * v - depth * 0.5);
- normalStream.addElement(0, 1, 0);
- texCoordStream.addElement(u, 1 - v);
- }
- }
-
- var numVertsAcross = subdivisionsWidth + 1;
-
- for (var z = 0; z < subdivisionsDepth; z++) {
- for (var x = 0; x < subdivisionsWidth; x++) {
- // triangle 1 of quad
- vertexInfo.addTriangle(
- (z + 0) * numVertsAcross + x,
- (z + 1) * numVertsAcross + x,
- (z + 0) * numVertsAcross + x + 1);
-
- // triangle 2 of quad
- vertexInfo.addTriangle(
- (z + 1) * numVertsAcross + x,
- (z + 1) * numVertsAcross + x + 1,
- (z + 0) * numVertsAcross + x + 1);
- }
- }
-
- if (opt_matrix) {
- vertexInfo.reorient(opt_matrix);
- }
- return vertexInfo;
-};
-
-/**
- * Creates an XZ plane.
- * The created plane has position, normal and uv streams.
- *
- * @param {!o3d.Pack} pack Pack to create plane elements in.
- * @param {!o3d.Material} material to use.
- * @param {number} width Width of the plane.
- * @param {number} depth Depth of the plane.
- * @param {number} subdivisionsWidth Number of steps across the plane.
- * @param {number} subdivisionsDepth Number of steps down the plane.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3d.Shape} The created plane.
- *
- * @see o3d.Pack
- * @see o3d.Shape
- */
-o3djs.primitives.createPlane = function(pack,
- material,
- width,
- depth,
- subdivisionsWidth,
- subdivisionsDepth,
- opt_matrix) {
- var vertexInfo = o3djs.primitives.createPlaneVertices(
- width,
- depth,
- subdivisionsWidth,
- subdivisionsDepth,
- opt_matrix);
-
- return vertexInfo.createShape(pack, material);
-};
-
-/**
- * Creates an XZ fade plane, where the alpha channel of the color stream
- * fades from 1 to 0.
- * The created plane has position, normal, uv and vertex color streams.
- *
- * @param {!o3d.Pack} pack Pack to create plane elements in.
- * @param {!o3d.Material} material to use.
- * @param {number} width Width of the plane.
- * @param {number} depth Depth of the plane.
- * @param {number} subdivisionsWidth Number of steps across the plane.
- * @param {number} subdivisionsDepth Number of steps down the plane.
- * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
- * all the vertices.
- * @return {!o3d.Shape} The created plane.
- *
- * @see o3d.Pack
- * @see o3d.Shape
- */
-o3djs.primitives.createFadePlane = function(pack,
- material,
- width,
- depth,
- subdivisionsWidth,
- subdivisionsDepth,
- opt_matrix) {
- var vertexInfo = o3djs.primitives.createPlaneVertices(
- width,
- depth,
- subdivisionsWidth,
- subdivisionsDepth,
- opt_matrix);
- var colorStream = vertexInfo.addStream(4, o3djs.base.o3d.Stream.COLOR);
- for (var z = 0; z <= subdivisionsDepth; z++) {
- var alpha = z / subdivisionsDepth;
- for (var x = 0; x <= subdivisionsWidth; x++) {
- colorStream.addElement(1, 1, 1, alpha);
- }
- }
- return vertexInfo.createShape(pack, material);
-};
-
diff --git a/o3d/samples/o3djs/quaternions.js b/o3d/samples/o3djs/quaternions.js
deleted file mode 100644
index 24d9d65..0000000
--- a/o3d/samples/o3djs/quaternions.js
+++ /dev/null
@@ -1,520 +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.
- */
-
-/**
- * @fileoverview This file contains various functions for quaternion arithmetic
- * and converting between rotation matrices and quaternions. It adds them to
- * the "quaternions" module on the o3djs object. Javascript arrays with
- * four entries are used to represent quaternions, and functions are provided
- * for doing operations on those.
- *
- * Operations are done assuming quaternions are of the form:
- * q[0] + q[1]i + q[2]j + q[3]k and using the hamiltonian rules for
- * multiplication as described on Brougham Bridge:
- * i^2 = j^2 = k^2 = ijk = -1.
- *
- */
-
-o3djs.provide('o3djs.quaternions');
-
-/**
- * A Module for quaternion math.
- * @namespace
- */
-o3djs.quaternions = o3djs.quaternions || {};
-
-/**
- * A Quaternion.
- * @type {!Array.<number>}
- */
-o3djs.quaternions.Quaternion = goog.typedef;
-
-/**
- * Quickly determines if the object a is a scalar or a quaternion;
- * assumes that the argument is either a number (scalar), or an array of
- * numbers.
- * @param {(number|!o3djs.quaternions.Quaternion)} a A number or array the type
- * of which is in question.
- * @return {string} Either the string 'Scalar' or 'Quaternion'.
- */
-o3djs.quaternions.mathType = function(a) {
- if (typeof(a) === 'number')
- return 'Scalar';
- return 'Quaternion';
-};
-
-/**
- * Copies a quaternion.
- * @param {!o3djs.quaternions.Quaternion} q The quaternion.
- * @return {!o3djs.quaternions.Quaternion} A new quaternion identical to q.
- */
-o3djs.quaternions.copy = function(q) {
- return q.slice();
-};
-
-/**
- * Negates a quaternion.
- * @param {!o3djs.quaternions.Quaternion} q The quaternion.
- * @return {!o3djs.quaternions.Quaternion} -q.
- */
-o3djs.quaternions.negative = function(q) {
- return [-q[0], -q[1], -q[2], -q[3]];
-};
-
-/**
- * Adds two Quaternions.
- * @param {!o3djs.quaternions.Quaternion} a Operand Quaternion.
- * @param {!o3djs.quaternions.Quaternion} b Operand Quaternion.
- * @return {!o3djs.quaternions.Quaternion} The sum of a and b.
- */
-o3djs.quaternions.addQuaternionQuaternion = function(a, b) {
- return [a[0] + b[0],
- a[1] + b[1],
- a[2] + b[2],
- a[3] + b[3]];
-};
-
-/**
- * Adds a quaternion to a scalar.
- * @param {!o3djs.quaternions.Quaternion} a Operand Quaternion.
- * @param {number} b Operand Scalar.
- * @return {!o3djs.quaternions.Quaternion} The sum of a and b.
- */
-o3djs.quaternions.addQuaternionScalar = function(a, b) {
- return a.slice(0, 3).concat(a[3] + b);
-};
-
-/**
- * Adds a scalar to a quaternion.
- * @param {number} a Operand scalar.
- * @param {!o3djs.quaternions.Quaternion} b Operand quaternion.
- * @return {!o3djs.quaternions.Quaternion} The sum of a and b.
- */
-o3djs.quaternions.addScalarQuaternion = function(a, b) {
- return b.slice(0, 3).concat(a + b[3]);
-};
-
-/**
- * Subtracts two quaternions.
- * @param {!o3djs.quaternions.Quaternion} a Operand quaternion.
- * @param {!o3djs.quaternions.Quaternion} b Operand quaternion.
- * @return {!o3djs.quaternions.Quaternion} The difference a - b.
- */
-o3djs.quaternions.subQuaternionQuaternion = function(a, b) {
- return [a[0] - b[0],
- a[1] - b[1],
- a[2] - b[2],
- a[3] - b[3]];
-};
-
-/**
- * Subtracts a scalar from a quaternion.
- * @param {!o3djs.quaternions.Quaternion} a Operand quaternion.
- * @param {number} b Operand scalar.
- * @return {!o3djs.quaternions.Quaternion} The difference a - b.
- */
-o3djs.quaternions.subQuaternionScalar = function(a, b) {
- return a.slice(0, 3).concat(a[3] - b);
-};
-
-/**
- * Subtracts a quaternion from a scalar.
- * @param {number} a Operand scalar.
- * @param {!o3djs.quaternions.Quaternion} b Operand quaternion.
- * @return {!o3djs.quaternions.Quaternion} The difference a - b.
- */
-o3djs.quaternions.subScalarQuaternion = function(a, b) {
- return [-b[0], -b[1], -b[2], a - b[3]];
-};
-
-/**
- * Multiplies a scalar by a quaternion.
- * @param {number} k The scalar.
- * @param {!o3djs.quaternions.Quaternion} q The quaternion.
- * @return {!o3djs.quaternions.Quaternion} The product of k and q.
- */
-o3djs.quaternions.mulScalarQuaternion = function(k, q) {
- return [k * q[0], k * q[1], k * q[2], k * q[3]];
-};
-
-/**
- * Multiplies a quaternion by a scalar.
- * @param {!o3djs.quaternions.Quaternion} q The Quaternion.
- * @param {number} k The scalar.
- * @return {!o3djs.quaternions.Quaternion} The product of k and v.
- */
-o3djs.quaternions.mulQuaternionScalar = function(q, k) {
- return [k * q[0], k * q[1], k * q[2], k * q[3]];
-};
-
-/**
- * Multiplies two quaternions.
- * @param {!o3djs.quaternions.Quaternion} a Operand quaternion.
- * @param {!o3djs.quaternions.Quaternion} b Operand quaternion.
- * @return {!o3djs.quaternions.Quaternion} The quaternion product a * b.
- */
-o3djs.quaternions.mulQuaternionQuaternion = function(a, b) {
- var aX = a[0];
- var aY = a[1];
- var aZ = a[2];
- var aW = a[3];
- var bX = b[0];
- var bY = b[1];
- var bZ = b[2];
- var bW = b[3];
-
- return [
- aW * bX + aX * bW + aY * bZ - aZ * bY,
- aW * bY + aY * bW + aZ * bX - aX * bZ,
- aW * bZ + aZ * bW + aX * bY - aY * bX,
- aW * bW - aX * bX - aY * bY - aZ * bZ];
-};
-
-/**
- * Divides two quaternions; assumes the convention that a/b = a*(1/b).
- * @param {!o3djs.quaternions.Quaternion} a Operand quaternion.
- * @param {!o3djs.quaternions.Quaternion} b Operand quaternion.
- * @return {!o3djs.quaternions.Quaternion} The quaternion quotient a / b.
- */
-o3djs.quaternions.divQuaternionQuaternion = function(a, b) {
- var aX = a[0];
- var aY = a[1];
- var aZ = a[2];
- var aW = a[3];
- var bX = b[0];
- var bY = b[1];
- var bZ = b[2];
- var bW = b[3];
-
- var d = 1 / (bW * bW + bX * bX + bY * bY + bZ * bZ);
- return [
- (aX * bW - aW * bX - aY * bZ + aZ * bY) * d,
- (aX * bZ - aW * bY + aY * bW - aZ * bX) * d,
- (aY * bX + aZ * bW - aW * bZ - aX * bY) * d,
- (aW * bW + aX * bX + aY * bY + aZ * bZ) * d];
-};
-
-/**
- * Divides a Quaternion by a scalar.
- * @param {!o3djs.quaternions.Quaternion} q The quaternion.
- * @param {number} k The scalar.
- * @return {!o3djs.quaternions.Quaternion} q The quaternion q divided by k.
- */
-o3djs.quaternions.divQuaternionScalar = function(q, k) {
- return [q[0] / k, q[1] / k, q[2] / k, q[3] / k];
-};
-
-/**
- * Divides a scalar by a quaternion.
- * @param {number} a Operand scalar.
- * @param {!o3djs.quaternions.Quaternion} b Operand quaternion.
- * @return {!o3djs.quaternions.Quaternion} The quaternion product.
- */
-o3djs.quaternions.divScalarQuaternion = function(a, b) {
- var b0 = b[0];
- var b1 = b[1];
- var b2 = b[2];
- var b3 = b[3];
-
- var d = 1 / (b0 * b0 + b1 * b1 + b2 * b2 + b3 * b3);
- return [-a * b0 * d, -a * b1 * d, -a * b2 * d, a * b3 * d];
-};
-
-/**
- * Computes the multiplicative inverse of a quaternion.
- * @param {!o3djs.quaternions.Quaternion} q The quaternion.
- * @return {!o3djs.quaternions.Quaternion} The multiplicative inverse of q.
- */
-o3djs.quaternions.inverse = function(q) {
- var q0 = q[0];
- var q1 = q[1];
- var q2 = q[2];
- var q3 = q[3];
-
- var d = 1 / (q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3);
- return [-q0 * d, -q1 * d, -q2 * d, q3 * d];
-};
-
-/**
- * Multiplies two objects which are either scalars or quaternions.
- * @param {(!o3djs.quaternions.Quaternion|number)} a Operand.
- * @param {(!o3djs.quaternions.Quaternion|number)} b Operand.
- * @return {(!o3djs.quaternions.Quaternion|number)} The product of a and b.
- */
-o3djs.quaternions.mul = function(a, b) {
- return o3djs.quaternions['mul' + o3djs.quaternions.mathType(a) +
- o3djs.quaternions.mathType(b)](a, b);
-};
-
-/**
- * Divides two objects which are either scalars or quaternions.
- * @param {(!o3djs.quaternions.Quaternion|number)} a Operand.
- * @param {(!o3djs.quaternions.Quaternion|number)} b Operand.
- * @return {(!o3djs.quaternions.Quaternion|number)} The quotient of a and b.
- */
-o3djs.quaternions.div = function(a, b) {
- return o3djs.quaternions['div' + o3djs.quaternions.mathType(a) +
- o3djs.quaternions.mathType(b)](a, b);
-};
-
-/**
- * Adds two objects which are either scalars or quaternions.
- * @param {(!o3djs.quaternions.Quaternion|number)} a Operand.
- * @param {(!o3djs.quaternions.Quaternion|number)} b Operand.
- * @return {(!o3djs.quaternions.Quaternion|number)} The sum of a and b.
- */
-o3djs.quaternions.add = function(a, b) {
- return o3djs.quaternions['add' + o3djs.quaternions.mathType(a) +
- o3djs.quaternions.mathType(b)](a, b);
-};
-
-/**
- * Subtracts two objects which are either scalars or quaternions.
- * @param {(!o3djs.quaternions.Quaternion|number)} a Operand.
- * @param {(!o3djs.quaternions.Quaternion|number)} b Operand.
- * @return {(!o3djs.quaternions.Quaternion|number)} The difference of a and b.
- */
-o3djs.quaternions.sub = function(a, b) {
- return o3djs.quaternions['sub' + o3djs.quaternions.mathType(a) +
- o3djs.quaternions.mathType(b)](a, b);
-};
-
-/**
- * Computes the length of a Quaternion, i.e. the square root of the
- * sum of the squares of the coefficients.
- * @param {!o3djs.quaternions.Quaternion} a The Quaternion.
- * @return {number} The length of a.
- */
-o3djs.quaternions.length = function(a) {
- return Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3]);
-};
-
-/**
- * Computes the square of the length of a quaternion, i.e. the sum of the
- * squares of the coefficients.
- * @param {!o3djs.quaternions.Quaternion} a The quaternion.
- * @return {number} The square of the length of a.
- */
-o3djs.quaternions.lengthSquared = function(a) {
- return a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3];
-};
-
-/**
- * Divides a Quaternion by its length and returns the quotient.
- * @param {!o3djs.quaternions.Quaternion} a The Quaternion.
- * @return {!o3djs.quaternions.Quaternion} A unit length quaternion pointing in
- * the same direction as a.
- */
-o3djs.quaternions.normalize = function(a) {
- var d = 1 / Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3]);
- return [a[0] * d, a[1] * d, a[2] * d, a[3] * d];
-};
-
-/**
- * Computes the conjugate of the given quaternion.
- * @param {!o3djs.quaternions.Quaternion} q The quaternion.
- * @return {!o3djs.quaternions.Quaternion} The conjugate of q.
- */
-o3djs.quaternions.conjugate = function(q) {
- return [-q[0], -q[1], -q[2], q[3]];
-};
-
-
-/**
- * Creates a quaternion which rotates around the x-axis by the given angle.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.quaternions.Quaternion} The quaternion.
- */
-o3djs.quaternions.rotationX = function(angle) {
- return [Math.sin(angle / 2), 0, 0, Math.cos(angle / 2)];
-};
-
-/**
- * Creates a quaternion which rotates around the y-axis by the given angle.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.quaternions.Quaternion} The quaternion.
- */
-o3djs.quaternions.rotationY = function(angle) {
- return [0, Math.sin(angle / 2), 0, Math.cos(angle / 2)];
-};
-
-/**
- * Creates a quaternion which rotates around the z-axis by the given angle.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.quaternions.Quaternion} The quaternion.
- */
-o3djs.quaternions.rotationZ = function(angle) {
- return [0, 0, Math.sin(angle / 2), Math.cos(angle / 2)];
-};
-
-/**
- * Creates a quaternion which rotates around the given axis by the given
- * angle.
- * @param {!o3djs.math.Vector3} axis The axis about which to rotate.
- * @param {number} angle The angle by which to rotate (in radians).
- * @return {!o3djs.quaternions.Quaternion} A quaternion which rotates angle
- * radians around the axis.
- */
-o3djs.quaternions.axisRotation = function(axis, angle) {
- var d = 1 / Math.sqrt(axis[0] * axis[0] +
- axis[1] * axis[1] +
- axis[2] * axis[2]);
- var sin = Math.sin(angle / 2);
- var cos = Math.cos(angle / 2);
- return [sin * axis[0] * d, sin * axis[1] * d, sin * axis[2] * d, cos];
-};
-
-/**
- * Computes a 4-by-4 rotation matrix (with trivial translation component)
- * given a quaternion. We assume the convention that to rotate a vector v by
- * a quaternion r means to express that vector as a quaternion q by letting
- * q = [v[0], v[1], v[2], 0] and then obtain the rotated vector by evaluating
- * the expression (r * q) / r.
- * @param {!o3djs.quaternions.Quaternion} q The quaternion.
- * @return {!o3djs.math.Matrix4} A 4-by-4 rotation matrix.
- */
-o3djs.quaternions.quaternionToRotation = function(q) {
- var qX = q[0];
- var qY = q[1];
- var qZ = q[2];
- var qW = q[3];
-
- var qWqW = qW * qW;
- var qWqX = qW * qX;
- var qWqY = qW * qY;
- var qWqZ = qW * qZ;
- var qXqW = qX * qW;
- var qXqX = qX * qX;
- var qXqY = qX * qY;
- var qXqZ = qX * qZ;
- var qYqW = qY * qW;
- var qYqX = qY * qX;
- var qYqY = qY * qY;
- var qYqZ = qY * qZ;
- var qZqW = qZ * qW;
- var qZqX = qZ * qX;
- var qZqY = qZ * qY;
- var qZqZ = qZ * qZ;
-
- var d = qWqW + qXqX + qYqY + qZqZ;
-
- return o3djs.math.makeMatrix4(
- (qWqW + qXqX - qYqY - qZqZ) / d,
- 2 * (qWqZ + qXqY) / d,
- 2 * (qXqZ - qWqY) / d, 0,
- 2 * (qXqY - qWqZ) / d,
- (qWqW - qXqX + qYqY - qZqZ) / d,
- 2 * (qWqX + qYqZ) / d, 0,
- 2 * (qWqY + qXqZ) / d,
- 2 * (qYqZ - qWqX) / d,
- (qWqW - qXqX - qYqY + qZqZ) / d, 0,
- 0, 0, 0, 1);
-};
-
-/**
- * Computes a quaternion whose rotation is equivalent to the given matrix.
- * Based on an algorithm from Shoemake SIGGRAPH 1987.
- * @param {(!o3djs.math.Matrix4|!o3djs.math.Matrix3)} m A 3-by-3 or 4-by-4
- * rotation matrix.
- * @return {!o3djs.quaternions.Quaternion} A quaternion q such that
- * quaternions.quaternionToRotation(q) is m.
- */
-o3djs.quaternions.rotationToQuaternion = function(m) {
- var u;
- var v;
- var w;
-
- var q = [];
- var m0,m1,m2;
- if (m.length==9) {
- m0 = [m[0], m[1], m[2]];
- m1 = [m[3], m[4], m[5]];
- m2 = [m[6], m[7], m[8]];
- }else {
- m0 = [m[0], m[1], m[2]];
- m1 = [m[4], m[5], m[6]];
- m2 = [m[8], m[9], m[10]];
- }
-
- var m00 = m0[0];
- var m11 = m1[1];
- var m22 = m2[2];
-
- var trace = m00 + m11 + m22;
-
- if (trace > 0) {
- var r = Math.sqrt(1 + trace);
- var k = 0.5 / r;
- return [(m1[2] - m2[1]) * k,
- (m2[0] - m0[2]) * k,
- (m0[1] - m1[0]) * k,
- 0.5 * r];
- }
-
- var mu;
- var mv;
- var mw;
-
- // Choose u, v, and w such that u is the index of the biggest diagonal entry
- // of m, and u v w is an even permutation of 0 1 and 2.
- if (m00 > m11 && m00 > m22) {
- u = 0;
- mu = m0;
- v = 1;
- mv = m1;
- w = 2;
- mw = m2;
- } else if (m11 > m00 && m11 > m22) {
- u = 1;
- mu = m1;
- v = 2;
- mv = m2;
- w = 0;
- mw = m0;
- } else {
- u = 2;
- mu = m2;
- v = 0;
- mv = m0;
- w = 1;
- mw = m1;
- }
-
- var r = Math.sqrt(1 + mu[u] - mv[v] - mw[w]);
- var k = 0.5 / r;
- q[u] = 0.5 * r;
- q[v] = (mv[u] + mu[v]) * k;
- q[w] = (mu[w] + mw[u]) * k;
- q[3] = (mv[w] - mw[v]) * k;
-
- return q;
-};
-
diff --git a/o3d/samples/o3djs/rendergraph.js b/o3d/samples/o3djs/rendergraph.js
deleted file mode 100644
index 2457004..0000000
--- a/o3d/samples/o3djs/rendergraph.js
+++ /dev/null
@@ -1,580 +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.
- */
-
-
-/**
- * @fileoverview This file contains various functions for helping create
- * render graphs for o3d. It puts them in the "rendergraph" module on
- * the o3djs object.
- *
- * Note: This library is only a sample. It is not meant to be some official
- * library. It is provided only as example code.
- *
- */
-
-o3djs.provide('o3djs.rendergraph');
-
-/**
- * A Module for creating render graphs.
- * @namespace
- */
-o3djs.rendergraph = o3djs.rendergraph || {};
-
-/**
- * Creates a basic render graph setup to draw opaque and transparent
- * 3d objects.
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.Transform} treeRoot root Transform of tree to render.
- * @param {!o3d.RenderNode} opt_parent RenderNode to build this view under.
- * @param {!o3djs.math.Vector4} opt_clearColor color to clear view.
- * @param {number} opt_priority Optional base priority for created objects.
- * @param {!o3djs.math.Vector4} opt_viewport viewport settings for view.
- * @param {!o3d.DrawList} opt_performanceDrawList Optional DrawList to
- * use for performanceDrawPass.
- * @param {!o3d.DrawList} opt_zOrderedDrawList Optional DrawList to
- * use for zOrderedDrawPass.
- * @param {!o3d.DrawContext} opt_drawContext Optional DrawContext to
- * use. If not passed in one is created.
- * @return {!o3djs.rendergraph.ViewInfo} A ViewInfo object with info about
- * everything created.
- */
-o3djs.rendergraph.createView = function(pack,
- treeRoot,
- opt_parent,
- opt_clearColor,
- opt_priority,
- opt_viewport,
- opt_performanceDrawList,
- opt_zOrderedDrawList,
- opt_drawContext) {
- return new o3djs.rendergraph.ViewInfo(pack,
- treeRoot,
- opt_parent,
- opt_clearColor,
- opt_priority,
- opt_viewport,
- opt_performanceDrawList,
- opt_zOrderedDrawList,
- opt_drawContext);
-};
-
-/**
- * Creates a basic render graph setup to draw opaque and transparent
- * 3d objects.
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.Transform} treeRoot root Transform of tree to render.
- * @param {!o3d.RenderNode} opt_parent RenderNode to build this view under.
- * @param {!o3djs.math.Vector4} opt_clearColor color to clear view.
- * @param {number} opt_priority Optional base priority for created objects.
- * @param {!o3djs.math.Vector4} opt_viewport viewport settings for view.
- * @return {!o3djs.rendergraph.ViewInfo} A ViewInfo object with info about
- * everything created.
- */
-o3djs.rendergraph.createBasicView = function(pack,
- treeRoot,
- opt_parent,
- opt_clearColor,
- opt_priority,
- opt_viewport) {
- return o3djs.rendergraph.createView(pack,
- treeRoot,
- opt_parent,
- opt_clearColor,
- opt_priority,
- opt_viewport);
-};
-
-/**
- * Creates an extra view render graph setup to draw opaque and transparent
- * 3d objects based on a previously created view. It uses the previous view
- * to share draw lists and to set the priority.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo ViewInfo returned from
- * createBasicView.
- * @param {!o3djs.math.Vector4} opt_viewport viewport settings for view.
- * @param {!o3djs.math.Vector4} opt_clearColor color to clear view.
- * @param {number} opt_priority base priority for created objects.
- * @return {!o3djs.rendergraph.ViewInfo} A ViewInfo object with info about
- * everything created.
- */
-o3djs.rendergraph.createExtraView = function(viewInfo,
- opt_viewport,
- opt_clearColor,
- opt_priority) {
- return o3djs.rendergraph.createView(viewInfo.pack,
- viewInfo.treeRoot,
- viewInfo.renderGraphRoot,
- opt_clearColor,
- opt_priority,
- opt_viewport,
- viewInfo.performanceDrawList,
- viewInfo.zOrderedDrawList);
-};
-
-/**
- * A ViewInfo object creates the standard o3d objects needed for
- * a single 3d view. Those include a ClearBuffer followed by a TreeTraveral
- * followed by 2 DrawPasses all of which are children of a Viewport. On top of
- * those a DrawContext and optionally 2 DrawLists although you can pass in your
- * own DrawLists if there is a reason to reuse the same DrawLists such was with
- * mulitple views of the same scene.
- *
- * The render graph created is something like:
- * <pre>
- * [Viewport]
- * |
- * +------+--------+------------------+---------------------+
- * | | | |
- * [ClearBuffer] [TreeTraversal] [Performance StateSet] [ZOrdered StateSet]
- * | |
- * [Performance DrawPass] [ZOrdered DrawPass]
- * </pre>
- *
- * @constructor
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.Transform} treeRoot root Transform of tree to render.
- * @param {!o3d.RenderNode} opt_parent RenderNode to build this view under.
- * @param {!o3djs.math.Vector4} opt_clearColor color to clear view.
- * @param {number} opt_priority Optional base priority for created objects.
- * @param {!o3djs.math.Vector4} opt_viewport viewport settings for view.
- * @param {!o3d.DrawList} opt_performanceDrawList DrawList to use for
- * performanceDrawPass.
- * @param {!o3d.DrawList} opt_zOrderedDrawList DrawList to use for
- * zOrderedDrawPass.
- * @param {!o3d.DrawContext} opt_drawContext Optional DrawContext to
- * use. If not passed in one is created.
- */
-o3djs.rendergraph.ViewInfo = function(pack,
- treeRoot,
- opt_parent,
- opt_clearColor,
- opt_priority,
- opt_viewport,
- opt_performanceDrawList,
- opt_zOrderedDrawList,
- opt_drawContext) {
- var that = this;
- var clearColor = opt_clearColor || [0.5, 0.5, 0.5, 1.0];
- var viewPriority = opt_priority || 0;
- var priority = 0;
-
- // Create Viewport.
- var viewport = pack.createObject('Viewport');
- if (opt_viewport) {
- viewport.viewport = opt_viewport;
- }
- viewport.priority = viewPriority;
-
- // Create a clear buffer.
- var clearBuffer = pack.createObject('ClearBuffer');
- clearBuffer.clearColor = clearColor;
- clearBuffer.priority = priority++;
- clearBuffer.parent = viewport;
-
- // Creates a TreeTraversal and parents it to the root.
- var treeTraversal = pack.createObject('TreeTraversal');
- treeTraversal.priority = priority++;
- treeTraversal.parent = viewport;
- treeTraversal.transform = treeRoot;
-
- this.drawPassInfos_ = [];
-
- /**
- * Pack that manages the objects created for this ViewInfo.
- * @type {!o3d.Pack}
- */
- this.pack = pack;
-
- /**
- * The RenderNode this ViewInfo render graph subtree is parented under.
- * @type {(!o3d.RenderNode|undefined)}
- */
- this.renderGraphRoot = opt_parent;
-
- /**
- * The root node of the transform graph this ViewInfo renders.
- * @type {!o3d.Transform}
- */
- this.treeRoot = treeRoot;
-
- /**
- * The root of the subtree of the render graph this ViewInfo is managing.
- * If you want to set the priority of a ViewInfo's rendergraph subtree use
- * <pre>
- * viewInfo.root.priority = desiredPriority;
- * </pre>
- * @type {!o3d.RenderNode}
- */
- this.root = viewport;
-
- /**
- * The Viewport RenderNode created for this ViewInfo.
- * @type {!o3d.Viewport}
- */
- this.viewport = viewport;
-
- /**
- * The ClearBuffer RenderNode created for this ViewInfo.
- * @type {!o3d.ClearBuffer}
- */
- this.clearBuffer = clearBuffer;
-
- // Create DrawContext.
- var drawContext = opt_drawContext || pack.createObject('DrawContext');
-
- /**
- * The DrawContext used by this ViewInfo.
- * @type {!o3d.DrawContext}
- */
- this.drawContext = drawContext;
-
- /**
- * The TreeTraversal used by this ViewInfo.
- * @type {!o3d.TreeTraversal}
- */
- this.treeTraversal = treeTraversal;
-
- /**
- * The highest priority used for objects under the Viewport RenderNode created
- * by this ViewInfo.
- * @type {number}
- */
- this.priority = priority;
-
- /**
- * This function is here just because the inside use case of
- * ViewInfo.createDrawPass is the less common case.
- * @param {o3d.DrawList.SortMethod} sortMethod how to sort.
- * @param {!o3d.DrawList} opt_drawList DrawList to use.
- */
- function createDrawPass(sortMethod, opt_drawList) {
- return that.createDrawPass(
- sortMethod,
- undefined,
- undefined,
- undefined,
- opt_drawList);
- }
-
- // Setup a Performance Ordered DrawPass
- var performanceDrawPassInfo = createDrawPass(
- o3djs.base.o3d.DrawList.BY_PERFORMANCE,
- opt_performanceDrawList);
-
- var performanceState = performanceDrawPassInfo.state;
-
- // Setup a z Ordered DrawPass
- var zOrderedDrawPassInfo = createDrawPass(
- o3djs.base.o3d.DrawList.BY_Z_ORDER,
- opt_zOrderedDrawList);
-
- var zOrderedState = zOrderedDrawPassInfo.state;
-
- zOrderedState.getStateParam('AlphaBlendEnable').value = true;
- zOrderedState.getStateParam('SourceBlendFunction').value =
- o3djs.base.o3d.State.BLENDFUNC_SOURCE_ALPHA;
- zOrderedState.getStateParam('DestinationBlendFunction').value =
- o3djs.base.o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA;
- zOrderedState.getStateParam('AlphaTestEnable').value = true;
- zOrderedState.getStateParam('AlphaComparisonFunction').value =
- o3djs.base.o3d.State.CMP_GREATER;
-
- // Parent whatever the root is to the parent passed in.
- if (opt_parent) {
- this.root.parent = opt_parent;
- }
-
- /**
- * The DrawPassInfo for the performance draw pass.
- * @type {!o3djs.rendergraph.DrawPassInfo}
- */
- this.performanceDrawPassInfo = performanceDrawPassInfo;
-
- /**
- * The DrawPassInfo for the zOrdered draw pass.
- * @type {!o3djs.rendergraph.DrawPassInfo}
- */
- this.zOrderedDrawPassInfo = zOrderedDrawPassInfo;
-
- // Legacy properties
-
- /**
- * The StateSet RenderNode above the performance DrawPass in this ViewInfo
- * @type {!o3d.StateSet}
- */
- this.performanceStateSet = performanceDrawPassInfo.stateSet;
-
- /**
- * The State object used by the performanceStateSet object in this ViewInfo.
- * By default, no states are set here.
- * @type {!o3d.State}
- */
- this.performanceState = performanceState;
-
- /**
- * The DrawList used for the performance draw pass. Generally for opaque
- * materials.
- * @type {!o3d.DrawList}
- */
- this.performanceDrawList = performanceDrawPassInfo.drawList;
-
- /**
- * The StateSet RenderNode above the ZOrdered DrawPass in this ViewInfo
- * @type {!o3d.StateSet}
- */
- this.zOrderedStateSet = zOrderedDrawPassInfo.stateSet;
-
- /**
- * The State object used by the zOrderedStateSet object in this ViewInfo.
- * By default AlphaBlendEnable is set to true, SourceBlendFucntion is set to
- * State.BLENDFUNC_SOURCE_ALPHA and DestinationBlendFunction is set to
- * State.BLENDFUNC_INVERSE_SOURCE_ALPHA
- * @type {!o3d.State}
- */
- this.zOrderedState = zOrderedState;
-
- /**
- * The DrawList used for the zOrdered draw pass. Generally for transparent
- * materials.
- * @type {!o3d.DrawList}
- */
- this.zOrderedDrawList = zOrderedDrawPassInfo.drawList;
-
- /**
- * The DrawPass used with the performance DrawList created by this ViewInfo.
- * @type {!o3d.DrawPass}
- */
- this.performanceDrawPass = performanceDrawPassInfo.drawPass;
-
- /**
- * The DrawPass used with the zOrdered DrawList created by this ViewInfo.
- * @type {!o3d.DrawPass}
- */
- this.zOrderedDrawPass = zOrderedDrawPassInfo.drawPass;
-
- /**
- * A flag whether or not we created the DrawContext for this DrawPassInfo.
- * @private
- * @type {boolean}
- */
- this.ownDrawContext_ = opt_drawContext ? false : true;
-};
-
-/**
- * Destroys the various objects created for the view.
- *
- * @param {boolean} opt_destroyDrawContext True if you want view's DrawContext
- * destroyed. Default = true.
- * @param {boolean} opt_destroyDrawList True if you want view's DrawLists
- * destroyed. Default = true.
- */
-o3djs.rendergraph.ViewInfo.prototype.destroy = function(
- opt_destroyDrawContext,
- opt_destroyDrawList) {
- if (opt_destroyDrawContext === undefined) {
- opt_destroyDrawContext = true;
- }
-
- for (var ii = 0; ii < this.drawPassInfos_.length; ++ii) {
- this.drawPassInfos_[ii].destroy();
- }
-
- // Remove everything we created from the pack.
- this.pack.removeObject(this.viewport);
- this.pack.removeObject(this.clearBuffer);
- if (opt_destroyDrawContext && this.ownDrawContext_) {
- this.pack.removeObject(this.drawContext);
- }
- this.pack.removeObject(this.treeTraversal);
- // Remove our substree from its parent.
- this.viewport.parent = null;
-
- // At this point, IF nothing else is referencing any of these objects
- // they should get removed.
-};
-
-/**
- * Creates a draw pass in this ViewInfo.
- *
- * @param {o3d.DrawList.SortMethod} sortMethod How to sort this draw pass's
- * DrawElements.
- * @param {!o3d.DrawContext} opt_drawContext The DrawContext for this draw pass.
- * If not passed in the default DrawContext for this ViewInfo will be used.
- * @param {number} opt_priority The priority for this draw pass. If not passed
- * in the priority will be the next priority for this ViewInfo.
- * @param {!o3d.RenderNode} opt_parent The RenderNode to parent this draw pass
- * under. If not passed in the draw pass will be parented under the
- * ViewInfo's viewport RenderNode.
- * @param {!o3d.DrawList} opt_drawList The DrawList for this draw pass. If not
- * passed in one will be created.
- * @return {!o3djs.rendergraph.DrawPassInfo}
- */
-o3djs.rendergraph.ViewInfo.prototype.createDrawPass = function(
- sortMethod,
- opt_drawContext,
- opt_priority,
- opt_parent,
- opt_drawList) {
- opt_drawContext = opt_drawContext || this.drawContext;
- opt_parent = opt_parent || this.viewport;
- opt_priority = (typeof opt_priority !== 'undefined') ? opt_priority :
- this.priority++;
- var drawPassInfo = o3djs.rendergraph.createDrawPassInfo(
- this.pack,
- opt_drawContext,
- sortMethod,
- opt_parent,
- opt_drawList);
- drawPassInfo.root.priority = opt_priority;
- this.treeTraversal.registerDrawList(
- drawPassInfo.drawList, opt_drawContext, true);
-
- this.drawPassInfos_.push(drawPassInfo);
-
- return drawPassInfo;
-};
-
-/**
- * Creates a DrawPassInfo to manage a draw pass.
- *
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.DrawContext} drawContext The DrawContext for this draw pass.
- * @param {o3d.DrawList.SortMethod} sortMethod How to sort this draw pass's
- * DrawElements.
- * @param {!o3d.DrawList} opt_drawList The DrawList for this draw pass. If not
- * passed in one will be created.
- * @param {!o3d.RenderNode} opt_parent The RenderNode to parent this draw pass
- * under. If not passed the draw pass will not be parented.
- * @return {!o3djs.rendergraph.DrawPassInfo}
- */
-o3djs.rendergraph.createDrawPassInfo = function(
- pack,
- drawContext,
- sortMethod,
- opt_parent,
- opt_drawList) {
- return new o3djs.rendergraph.DrawPassInfo(
- pack, drawContext, sortMethod, opt_parent, opt_drawList);
-};
-
-/**
- * A class to manage a draw pass.
- * @constructor
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.DrawContext} drawContext The DrawContext for this draw pass.
- * @param {o3d.DrawList.SortMethod} sortMethod How to sort this draw pass's
- * DrawElements.
- * @param {!o3d.DrawList} opt_drawList The DrawList for this draw pass. If not
- * passed in one will be created.
- * @param {!o3d.RenderNode} opt_parent The RenderNode to parent this draw pass
- * under. If not passed the draw pass will not be parented.
- * @return {!o3djs.rendergraph.DrawPassInfo}
- */
-o3djs.rendergraph.DrawPassInfo = function(pack,
- drawContext,
- sortMethod,
- opt_parent,
- opt_drawList) {
- var ownDrawList = opt_drawList ? false : true;
-
- opt_parent = opt_parent || null;
- opt_drawList = opt_drawList || pack.createObject('DrawList');
-
- var stateSet = pack.createObject('StateSet');
- var state = pack.createObject('State');
- stateSet.state = state;
- stateSet.parent = opt_parent;
-
- var drawPass = pack.createObject('DrawPass');
- drawPass.drawList = opt_drawList;
- drawPass.sortMethod = sortMethod;
- drawPass.parent = stateSet;
-
- /**
- * The pack managing the objects created for this DrawPassInfo.
- * @type {!o3d.Pack}
- */
- this.pack = pack;
-
- /**
- * The State that affects all things drawn in this DrawPassInfo.
- * @type {!o3d.State}
- */
- this.state = state;
-
- /**
- * The StateSet that applies the state for this DrawPassInfo.
- * @type {!o3d.StateSet}
- */
- this.stateSet = stateSet;
-
- /**
- * The DrawPass for this DrawPassInfo.
- * @type {!o3d.DrawPass}
- */
- this.drawPass = drawPass;
-
- /**
- * The DrawList for this DrawPassInfo.
- * @type {!o3d.DrawList}
- */
- this.drawList = opt_drawList;
-
- /**
- * The root RenderNode of this DrawPassInfo. This is the RenderNdoe you should
- * use if you want to turn this draw pass off or reparent it.
- * @type {!o3d.RenderNode}
- */
- this.root = stateSet;
-
- /**
- * A flag whether or not we created the DrawList for this DrawPassInfo.
- * @private
- * @type {boolean}
- */
- this.ownDrawList_ = ownDrawList;
-};
-
-/**
- * Frees the resources created for this DrawPassInfo.
- */
-o3djs.rendergraph.DrawPassInfo.prototype.destroy = function() {
- // Remove everything we created from the pack.
- if (this.ownDrawList_) {
- this.drawPass.drawList = null;
- this.pack.removeObject(this.drawList);
- }
- this.drawPass.parent = null;
- this.stateSet.parent = null;
- this.pack.removeObject(this.drawPass);
- this.pack.removeObject(this.stateSet);
- this.pack.removeObject(this.state);
-};
-
diff --git a/o3d/samples/o3djs/scene.js b/o3d/samples/o3djs/scene.js
deleted file mode 100644
index c17b517..0000000
--- a/o3d/samples/o3djs/scene.js
+++ /dev/null
@@ -1,91 +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.
- */
-
-
-/**
- * @fileoverview This file contains various functions and classes for dealing
- * with 3d scenes.
- */
-
-o3djs.provide('o3djs.scene');
-
-o3djs.require('o3djs.io');
-o3djs.require('o3djs.serialization');
-
-/**
- * A Module with various scene functions and classes.
- * @namespace
- */
-o3djs.scene = o3djs.scene || {};
-
-/**
- * Loads a scene.
- * @param {!o3d.Client} client An O3D client object.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {!o3d.Transform} parent Transform to parent scene under.
- * @param {string} url URL of scene to load.
- * @param {!function(!o3d.Pack, !o3d.Transform, *): void} callback
- * Callback when scene is loaded. It will be passed the pack, the parent and
- * an exception which is null on success.
- * @param {!o3djs.serialization.Options} opt_options Options passed into the
- * loader.
- * @return {!o3djs.io.LoadInfo} A LoadInfo for tracking progress.
- * @see o3djs.loader.createLoader
- */
-o3djs.scene.loadScene = function(client,
- pack,
- parent,
- url,
- callback,
- opt_options) {
- // Starts the deserializer once the entire archive is available.
- function onFinished(archiveInfo, exception) {
- if (!exception) {
- var finishCallback = function(pack, parent, exception) {
- archiveInfo.destroy();
- callback(pack, parent, exception);
- };
- o3djs.serialization.deserializeArchive(archiveInfo,
- 'scene.json',
- client,
- pack,
- parent,
- finishCallback,
- opt_options);
- } else {
- archiveInfo.destroy();
- callback(pack, parent, exception);
- }
- }
- return o3djs.io.loadArchive(pack, url, onFinished);
-};
-
-
diff --git a/o3d/samples/o3djs/serialization.js b/o3d/samples/o3djs/serialization.js
deleted file mode 100644
index c02e405..0000000
--- a/o3d/samples/o3djs/serialization.js
+++ /dev/null
@@ -1,871 +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.
- */
-
-
-/**
- * @fileoverview This file provides support for deserializing (loading)
- * transform graphs from JSON files.
- *
- */
-
-o3djs.provide('o3djs.serialization');
-
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.error');
-o3djs.require('o3djs.texture');
-
-/**
- * A Module for deserializing a scene created by the sample o3dConverter.
- * @namespace
- */
-o3djs.serialization = o3djs.serialization || {};
-
-/**
- * The oldest supported version of the serializer. It isn't necessary to
- * increment this version whenever the format changes. Only change it when the
- * deserializer becomes incapable of deserializing an older version.
- * @type {number}
- */
-o3djs.serialization.supportedVersion = 5;
-
-/**
- * These are the values the sample o3dConverter uses to identify curve key
- * types.
- * @type {!Object}
- */
-o3djs.serialization.CURVE_KEY_TYPES = {
- step: 1,
- linear: 2,
- bezier: 3};
-
-/**
- * Options for deserialization.
- *
- * opt_animSource is an optional ParamFloat that will be bound as the source
- * param for all animation time params in the scene. opt_async is a bool that
- * will make the deserialization process async.
- *
- * @type {{opt_animSource: !o3d.ParamFloat, opt_async: boolean}}
- */
-o3djs.serialization.Options = goog.typedef;
-
-/**
- * A Deserializer incrementally deserializes a transform graph.
- * @constructor
- * @param {!o3d.Pack} pack The pack to deserialize into.
- * @param {!Object} json An object tree conforming to the JSON rules.
- */
-o3djs.serialization.Deserializer = function(pack, json) {
- /**
- * The pack to deserialize into.
- * @type {!o3d.Pack}
- */
- this.pack = pack;
-
- /**
- * An object tree conforming to the JSON rules.
- * @type {!Object}
- */
- this.json = json;
-
- /**
- * The archive from which assets referenced from JSON are retreived.
- * @type {o3djs.io.ArchiveInfo}
- */
- this.archiveInfo = null;
-
- /**
- * Deserializes a Buffer .
- * @param {!o3djs.serialization.Deserializer} deserializer The deserializer.
- * @param {!Object} json The json for this buffer.
- * @param {string} type The type of buffer to create.
- * @param {string} uri The uri of the file containing the binary data.
- */
- function deserializeBuffer(deserializer, json, type, uri) {
- var object = deserializer.pack.createObject(type);
- if ('custom' in json) {
- if ('fieldData' in json.custom) {
- var fieldDataArray = json.custom.fieldData;
- if (fieldDataArray.length > 0) {
- var fields = [];
- // First create all the fields
- for (var ii = 0; ii < fieldDataArray.length; ++ii) {
- var data = fieldDataArray[ii];
- var field = object.createField(data.type, data.numComponents);
- fields.push(field);
- deserializer.addObject(data.id, field);
- }
- var firstData = fieldDataArray[0];
- var numElements = firstData.data.length / firstData.numComponents;
- object.allocateElements(numElements);
- // Now set the data.
- for (var ii = 0; ii < fieldDataArray.length; ++ii) {
- var data = fieldDataArray[ii];
- fields[ii].setAt(0, data.data);
- }
- }
- } else {
- var rawData = deserializer.archiveInfo.getFileByURI(uri);
- object.set(rawData,
- json.custom.binaryRange[0],
- json.custom.binaryRange[1] - json.custom.binaryRange[0]);
- for (var i = 0; i < json.custom.fields.length; ++i) {
- deserializer.addObject(json.custom.fields[i], object.fields[i]);
- }
- }
- }
- return object;
- }
-
- /**
- * A map from classname to a function that will create
- * instances of objects. Add entries to support additional classes.
- * @type {!Object}
- */
- this.createCallbacks = {
- 'o3djs.DestinationBuffer': function(deserializer, json) {
- var object = deserializer.pack.createObject('o3d.VertexBuffer');
- if ('custom' in json) {
- for (var i = 0; i < json.custom.fields.length; ++i) {
- var fieldInfo = json.custom.fields[i]
- var field = object.createField(fieldInfo.type,
- fieldInfo.numComponents);
- deserializer.addObject(fieldInfo.id, field);
- }
- object.allocateElements(json.custom.numElements);
- }
- return object;
- },
-
- 'o3d.VertexBuffer': function(deserializer, json) {
- return deserializeBuffer(
- deserializer, json, 'o3d.VertexBuffer', 'vertex-buffers.bin');
- },
-
- 'o3d.SourceBuffer': function(deserializer, json) {
- return deserializeBuffer(
- deserializer, json, 'o3d.SourceBuffer', 'vertex-buffers.bin');
- },
-
- 'o3d.IndexBuffer': function(deserializer, json) {
- return deserializeBuffer(
- deserializer, json, 'o3d.IndexBuffer', 'index-buffers.bin');
- },
-
- 'o3d.Texture2D': function(deserializer, json) {
- if ('o3d.uri' in json.params) {
- var uri = json.params['o3d.uri'].value;
- var rawData = deserializer.archiveInfo.getFileByURI(uri);
- if (!rawData) {
- throw 'Could not find texture ' + uri + ' in the archive';
- }
- return o3djs.texture.createTextureFromRawData(pack, rawData, true);
- } else {
- return deserializer.pack.createTexture2D(
- json.custom.width,
- json.custom.height,
- json.custom.format,
- json.custom.levels,
- json.custom.renderSurfacesEnabled);
- }
- },
-
- 'o3d.TextureCUBE': function(deserializer, json) {
- if ('o3d.negx_uri' in json.params) {
- // Cube map comprised of six separate textures.
- var param_names = [
- 'o3d.posx_uri',
- 'o3d.negx_uri',
- 'o3d.posy_uri',
- 'o3d.negy_uri',
- 'o3d.posz_uri',
- 'o3d.negz_uri'
- ];
- var rawDataArray = [];
- for (var i = 0; i < param_names.length; i++) {
- var uri = json.params[param_names[i]].value;
- var rawData = deserializer.archiveInfo.getFileByURI(uri);
- if (!rawData) {
- throw 'Could not find texture ' + uri + ' in the archive';
- }
- rawDataArray.push(rawData);
- }
- // Cube map faces should not be flipped.
- return o3djs.texture.createTextureFromRawDataArray(
- pack, rawDataArray, true, false);
- } else if ('o3d.uri' in json.params) {
- var uri = json.params['o3d.uri'].value;
- var rawData = deserializer.archiveInfo.getFileByURI(uri);
- if (!rawData) {
- throw 'Could not find texture ' + uri + ' in the archive';
- }
- return o3djs.texture.createTextureFromRawData(pack, rawData, true);
- } else {
- return deserializer.pack.createTextureCUBE(
- json.custom.edgeLength,
- json.custom.format,
- json.custom.levels,
- json.custom.renderSurfacesEnabled);
- }
- }
- };
-
- /**
- * A map from classname to a function that will initialize
- * instances of the given class from JSON data. Add entries to support
- * additional classes.
- * @type {!Object}
- */
- this.initCallbacks = {
- 'o3d.Curve': function(deserializer, object, json) {
- if ('custom' in json) {
- if ('keys' in json.custom) {
- var keys = json.custom.keys;
- var stepType = o3djs.serialization.CURVE_KEY_TYPES.step;
- var linearType = o3djs.serialization.CURVE_KEY_TYPES.linear;
- var bezierType = o3djs.serialization.CURVE_KEY_TYPES.bezier;
- for (var ii = 0; ii < keys.length; ++ii) {
- var key = keys[ii];
- switch (key[0]) {
- case stepType: // Step
- object.addStepKeys(key.slice(1));
- break;
- case linearType: // Linear
- object.addLinearKeys(key.slice(1));
- break;
- case bezierType: // Bezier
- object.addBezierKeys(key.slice(1));
- break;
- }
- }
- } else {
- var rawData = deserializer.archiveInfo.getFileByURI('curve-keys.bin');
- object.set(rawData,
- json.custom.binaryRange[0],
- json.custom.binaryRange[1] - json.custom.binaryRange[0]);
- }
- }
- },
-
- 'o3d.Effect': function(deserializer, object, json) {
- var uriParam = object.getParam('o3d.uri');
- if (uriParam) {
- var rawData = deserializer.archiveInfo.getFileByURI(uriParam.value);
- if (!rawData) {
- throw 'Cannot find shader ' + uriParam.value + ' in archive.';
- }
- if (!object.loadFromFXString(rawData.stringValue)) {
- throw 'Cannot load shader ' + uriParam.value + ' in archive.';
- }
- }
- },
-
- 'o3d.Skin': function(deserializer, object, json) {
- if ('custom' in json) {
- if ('binaryRange' in json.custom) {
- var rawData = deserializer.archiveInfo.getFileByURI('skins.bin');
- object.set(rawData,
- json.custom.binaryRange[0],
- json.custom.binaryRange[1] - json.custom.binaryRange[0]);
- }
- }
- },
-
- 'o3d.SkinEval': function(deserializer, object, json) {
- if ('custom' in json) {
- for (var i = 0; i < json.custom.vertexStreams.length; ++i) {
- var streamJson = json.custom.vertexStreams[i];
- var field = deserializer.getObjectById(streamJson.stream.field);
- object.setVertexStream(streamJson.stream.semantic,
- streamJson.stream.semanticIndex,
- field,
- streamJson.stream.startIndex);
- if ('bind' in streamJson) {
- var source = deserializer.getObjectById(streamJson.bind);
- object.bindStream(source,
- streamJson.stream.semantic,
- streamJson.stream.semanticIndex);
- }
- }
- }
- },
-
- 'o3d.StreamBank': function(deserializer, object, json) {
- if ('custom' in json) {
- for (var i = 0; i < json.custom.vertexStreams.length; ++i) {
- var streamJson = json.custom.vertexStreams[i];
- var field = deserializer.getObjectById(streamJson.stream.field);
- object.setVertexStream(streamJson.stream.semantic,
- streamJson.stream.semanticIndex,
- field,
- streamJson.stream.startIndex);
- if ('bind' in streamJson) {
- var source = deserializer.getObjectById(streamJson.bind);
- object.bindStream(source,
- streamJson.stream.semantic,
- streamJson.stream.semanticIndex);
- }
- }
- }
- }
- };
-
- if (!('version' in json)) {
- throw 'Version in JSON file was missing.';
- }
-
- if (json.version < o3djs.serialization.supportedVersion) {
- throw 'Version in JSON file was ' + json.version +
- ' but expected at least version ' +
- o3djs.serialization.supportedVersion + '.';
- }
-
- if (!('objects' in json)) {
- throw 'Objects array in JSON file was missing.';
- }
-
- /**
- * An array of all objects deserialized so far, indexed by object id. Id zero
- * means null.
- * @type {!Array.<(Object|undefined)>}
- * @private
- */
- this.objectsById_ = [null];
-
- /**
- * An array of objects deserialized so far, indexed by position in the JSON.
- * @type {!Array.<Object>}
- * @private
- */
- this.objectsByIndex_ = [];
-
- /**
- * Array of all classes present in the JSON.
- * @type {!Array.<string>}
- * @private
- */
- this.classNames_ = [];
- for (var className in json.objects) {
- this.classNames_.push(className);
- }
-
- /**
- * The current phase_ of deserialization. In phase_ 0, objects
- * are created and their ids registered. In phase_ 1, objects are
- * initialized from JSON data.
- * @type {number}
- * @private
- */
- this.phase_ = 0;
-
- /**
- * Index of the next class to be deserialized in classNames_.
- * @type {number}
- * @private
- */
- this.nextClassIndex_ = 0;
-
- /**
- * Index of the next object of the current class to be deserialized.
- * @type {number}
- * @private
- */
- this.nextObjectIndex_ = 0;
-
- /**
- * Index of the next object to be deserialized in objectsByIndex_.
- * @type {number}
- * @private
- */
- this.globalObjectIndex_ = 0;
-};
-
-/**
- * Get the object with the given id.
- * @param {number} id The id to lookup.
- * @return {(Object|undefined)} The object with the given id.
- */
-o3djs.serialization.Deserializer.prototype.getObjectById = function(id) {
- return this.objectsById_[id];
-};
-
-/**
- * When a creation or init callback creates an object that the Deserializer
- * is not aware of, it can associate it with an id using this function, so that
- * references to the object can be resolved.
- * @param {number} id The is of the object.
- * @param {!Object} object The object to register.
- */
-o3djs.serialization.Deserializer.prototype.addObject = function(
- id, object) {
- this.objectsById_[id] = object;
-};
-
-/**
- * Deserialize a value. Identifies reference values and converts
- * their object id into an object reference. Otherwise returns the
- * value unchanged.
- * @param {*} valueJson The JSON representation of the value.
- * @return {*} The JavaScript representation of the value.
- */
-o3djs.serialization.Deserializer.prototype.deserializeValue = function(
- valueJson) {
- if (typeof(valueJson) === 'object') {
- if (valueJson === null) {
- return null;
- }
-
- var valueAsObject = /** @type {!Object} */ (valueJson);
- if ('length' in valueAsObject) {
- for (var i = 0; i != valueAsObject.length; ++i) {
- valueAsObject[i] = this.deserializeValue(valueAsObject[i]);
- }
- if (o3djs.math.usePluginMath_) {
- return valueAsObject;
- }
- return o3djs.serialization.fixMatrices(valueAsObject);
- }
-
- var refId = valueAsObject['ref'];
- if (refId !== undefined) {
- var referenced = this.objectsById_[refId];
- if (referenced === undefined) {
- throw 'Could not find object with id ' + refId + '.';
- }
- return referenced;
- }
- }
-
- return valueJson;
-};
-
-/**
- * Sets the value of a param on an object or binds a param to another.
- * @param {!Object} object The object holding the param.
- * @param {(string|number)} paramName The name of the param.
- * @param {!Object} propertyJson The JSON representation of the value.
- * @private
- */
-o3djs.serialization.Deserializer.prototype.setParamValue_ = function(
- object, paramName, propertyJson) {
- var param = object.getParam(paramName);
- if (param === null)
- return;
-
- var valueJson = propertyJson['value'];
- if (valueJson !== undefined) {
- param.value = this.deserializeValue(valueJson);
- }
-
- var bindId = propertyJson['bind'];
- if (bindId !== undefined) {
- var referenced = this.objectsById_[bindId];
- if (referenced === undefined) {
- throw 'Could not find output param with id ' + bindId + '.';
- }
- param.bind(referenced);
- }
-};
-
-/**
- * Creates a param on an object and adds it's id so that other objects can
- * reference it.
- * @param {!Object} object The object to hold the param.
- * @param {(string|number)} paramName The name of the param.
- * @param {!Object} propertyJson The JSON representation of the value.
- * @private
- */
-o3djs.serialization.Deserializer.prototype.createAndIdentifyParam_ =
- function(object, paramName, propertyJson) {
- var propertyClass = propertyJson['class'];
- var param;
- if (propertyClass !== undefined) {
- param = object.createParam(paramName, propertyClass);
- } else {
- param = object.getParam(paramName);
- }
-
- var paramId = propertyJson['id'];
- if (paramId !== undefined && param !== null) {
- this.objectsById_[paramId] = param;
- }
-};
-
-/**
- * First pass: create all objects and additional params. We need two
- * passes to support references to objects that appear later in the
- * JSON.
- * @param {number} amountOfWork The number of loop iterations to perform of
- * this phase_.
- * @private
- */
-o3djs.serialization.Deserializer.prototype.createObjectsPhase_ =
- function(amountOfWork) {
- for (; this.nextClassIndex_ < this.classNames_.length;
- ++this.nextClassIndex_) {
- var className = this.classNames_[this.nextClassIndex_];
- var classJson = this.json.objects[className];
- var numObjects = classJson.length;
- for (; this.nextObjectIndex_ < numObjects; ++this.nextObjectIndex_) {
- if (amountOfWork-- <= 0)
- return;
-
- var objectJson = classJson[this.nextObjectIndex_];
- var object = undefined;
- if ('id' in objectJson) {
- object = this.objectsById_[objectJson.id];
- }
- if (object === undefined) {
- if (className in this.createCallbacks) {
- object = this.createCallbacks[className](this, objectJson);
- } else {
- object = this.pack.createObject(className);
- }
- }
- this.objectsByIndex_[this.globalObjectIndex_++] = object;
- if ('id' in objectJson) {
- this.objectsById_[objectJson.id] = object;
- }
- if ('params' in objectJson) {
- if ('length' in objectJson.params) {
- for (var paramIndex = 0; paramIndex != objectJson.params.length;
- ++paramIndex) {
- var paramJson = objectJson.params[paramIndex];
- this.createAndIdentifyParam_(object, paramIndex,
- paramJson);
- }
- } else {
- for (var paramName in objectJson.params) {
- var paramJson = objectJson.params[paramName];
- this.createAndIdentifyParam_(object, paramName, paramJson);
- }
- }
- }
- }
- this.nextObjectIndex_ = 0;
- }
-
- if (this.nextClassIndex_ === this.classNames_.length) {
- this.nextClassIndex_ = 0;
- this.nextObjectIndex_ = 0;
- this.globalObjectIndex_ = 0;
- ++this.phase_;
- }
-};
-
-/**
- * Second pass: set property and parameter values and bind parameters.
- * @param {number} amountOfWork The number of loop iterations to perform of
- * this phase_.
- * @private
- */
-o3djs.serialization.Deserializer.prototype.setPropertiesPhase_ = function(
- amountOfWork) {
- for (; this.nextClassIndex_ < this.classNames_.length;
- ++this.nextClassIndex_) {
- var className = this.classNames_[this.nextClassIndex_];
- var classJson = this.json.objects[className];
- var numObjects = classJson.length;
- for (; this.nextObjectIndex_ < numObjects; ++this.nextObjectIndex_) {
- if (amountOfWork-- <= 0)
- return;
-
- var objectJson = classJson[this.nextObjectIndex_];
- var object = this.objectsByIndex_[this.globalObjectIndex_++];
- if ('properties' in objectJson) {
- for (var propertyName in objectJson.properties) {
- if (propertyName in object) {
- var propertyJson = objectJson.properties[propertyName];
- var propertyValue = this.deserializeValue(propertyJson);
- object[propertyName] = propertyValue;
- }
- };
- }
- if ('params' in objectJson) {
- if ('length' in objectJson.params) {
- for (var paramIndex = 0; paramIndex != objectJson.params.length;
- ++paramIndex) {
- var paramJson = objectJson.params[paramIndex];
- this.setParamValue_(/** @type {!Object} */ (object),
- paramIndex,
- paramJson);
- }
- } else {
- for (var paramName in objectJson.params) {
- var paramJson = objectJson.params[paramName];
- this.setParamValue_(/** @type {!Object} */ (object),
- paramName,
- paramJson);
- }
- }
- }
- if (className in this.initCallbacks) {
- this.initCallbacks[className](this, object, objectJson);
- }
- }
- this.nextObjectIndex_ = 0;
- }
-
- if (this.nextClassIndex_ === this.classNames_.length) {
- this.nextClassIndex_ = 0;
- this.nextObjectIndex_ = 0;
- this.globalObjectIndex_ = 0;
- ++this.phase_;
- }
-};
-
-/**
- * Perform a certain number of iterations of the deserializer. Keep calling this
- * function until it returns false.
- * @param {number} opt_amountOfWork The number of loop iterations to run. If
- * not specified, runs the deserialization to completion.
- * @return {boolean} Whether work remains to be done.
- */
-o3djs.serialization.Deserializer.prototype.run = function(
- opt_amountOfWork) {
- if (!opt_amountOfWork) {
- while (this.run(10000)) {
- }
- return false;
- } else {
- switch (this.phase_) {
- case 0:
- this.createObjectsPhase_(opt_amountOfWork);
- break;
- case 1:
- this.setPropertiesPhase_(opt_amountOfWork);
- break;
- }
- return this.phase_ < 2;
- }
-};
-
-/**
- * Deserializes (loads) a transform graph in the background. Invokes
- * a callback function on completion passing the pack and the thrown
- * exception on failure or the pack and a null exception on success.
- * @param {!o3d.Client} client An O3D client object.
- * @param {!o3d.Pack} pack The pack to create the deserialized objects
- * in.
- * @param {number} time The amount of the time (in seconds) the deserializer
- * should aim to complete in.
- * @param {!function(o3d.Pack, *): void} callback The function that
- * is called on completion. The second parameter is null on success or
- * the thrown exception on failure.
- */
-o3djs.serialization.Deserializer.prototype.runBackground = function(
- client, pack, time, callback) {
- // TODO: This seems like it needs to be more granular than the
- // top level.
- // TODO: Passing in the time you want it to take seems counter
- // intuitive. I want pass in a % of CPU so I can effectively say
- // "deserialize this in such a way so as not to affect my app's
- // performance". callbacksRequired = numObjects / amountPerCallback where
- // amountPerCallback = number I can do per frame and not affect performance
- // too much.
- var workToDo = this.json.objects.length * 2;
- var timerCallbacks = time * 60;
- var amountPerCallback = workToDo / timerCallbacks;
- var intervalId;
- var that = this;
- function deserializeMore() {
- var exception = null;
- var finished = false;
- var failed = false;
- var errorCollector = o3djs.error.createErrorCollector(client);
- try {
- finished = !that.run(amountPerCallback);
- } catch(e) {
- failed = true;
- finished = true;
- exception = e;
- }
- if (errorCollector.errors.length > 0) {
- finished = true;
- exception = errorCollector.errors.join('\n') +
- (exception ? ('\n' + exception.toString()) : '');
- }
- errorCollector.finish();
- if (finished) {
- window.clearInterval(intervalId);
- callback(pack, exception);
- }
- }
-
- intervalId = window.setInterval(deserializeMore, 1000 / 60);
-};
-
-/**
- * Creates a deserializer that will incrementally deserialize a
- * transform graph. The deserializer object has a method
- * called run that does a fixed amount of work and returns.
- * It returns true until the transform graph is fully deserialized.
- * It returns false from then on.
- * @param {!o3d.Pack} pack The pack to create the deserialized
- * objects in.
- * @param {!Object} json An object tree conforming to the JSON rules.
- * @return {!o3djs.serialization.Deserializer} A deserializer object.
- */
-o3djs.serialization.createDeserializer = function(pack, json) {
- return new o3djs.serialization.Deserializer(pack, json);
-};
-
-/**
- * Deserializes a transform graph.
- * @param {!o3d.Pack} pack The pack to create the deserialized
- * objects in.
- * @param {!Object} json An object tree conforming to the JSON rules.
- */
-o3djs.serialization.deserialize = function(pack, json) {
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.run();
-};
-
-/**
- * This function looks at a given data type, determines if it is an old style
- * matrix that is a 2d doubly nested array. If so, it flattens the matrix in
- * place so that it may be handled by the code.
- * @param {Object} parsed a potential array that will be repaired
- */
-o3djs.serialization.fixMatrices = function(parsed) {
- function isMatrix(m) {
- var len = m && m.length;
- if (len && len <= 4) {
- for (var i = 0; i < len; ++i) {
- var mi = m[i];
- var mlen = mi.length;
- if (mlen != len) {
- return false;
- }
- for(var j = 0; j < len; ++j) {
- if (Number(mi[j]) == NaN){
- return false;
- }
- }
- }
- return true;
- } else {
- return false;
- }
- }
-
- function flatten(m) {
- var len = m.length;
- var retval = new o3djs.math.makeMatrix4(len * len);
- for (var i = 0; i < len; ++i) {
- for (var j = 0; j < len; ++j) {
- retval[i * len + j] = m[i][j];
- }
- }
- return retval;
- }
- if (isMatrix(parsed)) {
- return flatten(parsed);
- }
- return parsed;
-};
-
-/**
- * Deserializes a single json object named 'scene.json' from a loaded
- * o3djs.io.ArchiveInfo.
- * @param {!o3djs.io.ArchiveInfo} archiveInfo Archive to load from.
- * @param {string} sceneJsonUri The relative URI of the scene JSON file within
- * the archive.
- * @param {!o3d.Client} client An O3D client object.
- * @param {!o3d.Pack} pack The pack to create the deserialized objects
- * in.
- * @param {!o3d.Transform} parent Transform to parent loaded stuff from.
- * @param {!function(!o3d.Pack, !o3d.Transform, *): void} callback A function
- * that will be called when deserialization is finished. It will be passed
- * the pack, the parent transform, and an exception which will be null on
- * success.
- * @param {!o3djs.serialization.Options} opt_options Options.
- */
-o3djs.serialization.deserializeArchive = function(archiveInfo,
- sceneJsonUri,
- client,
- pack,
- parent,
- callback,
- opt_options) {
- opt_options = opt_options || { };
- var jsonFile = archiveInfo.getFileByURI(sceneJsonUri);
- if (!jsonFile) {
- throw 'Could not find ' + sceneJsonUri + ' in archive';
- }
- var parsed = eval('(' + jsonFile.stringValue + ')');
- var deserializer = o3djs.serialization.createDeserializer(pack, parsed);
-
- deserializer.addObject(parsed.o3d_rootObject_root, parent);
- deserializer.archiveInfo = archiveInfo;
-
- var finishCallback = function(pack, exception) {
- if (!exception) {
- var objects = pack.getObjects('o3d.animSourceOwner', 'o3d.ParamObject');
- if (objects.length > 0) {
- // Rebind the output connections of the animSource to the user's param.
- if (opt_options.opt_animSource) {
- var animSource = objects[0].getParam('animSource');
- var outputConnections = animSource.outputConnections;
- for (var ii = 0; ii < outputConnections.length; ++ii) {
- outputConnections[ii].bind(opt_options.opt_animSource);
- }
- }
- // Remove special object from pack.
- for (var ii = 0; ii < objects.length; ++ii) {
- pack.removeObject(objects[ii]);
- }
- }
- }
- callback(pack, parent, exception);
- };
-
- if (opt_options.opt_async) {
- // TODO: Remove the 5. See deserializer.runBackground comments.
- deserializer.runBackground(client, pack, 5, finishCallback);
- } else {
- var exception = null;
- var errorCollector = o3djs.error.createErrorCollector(client);
- try {
- deserializer.run();
- } catch (e) {
- exception = e;
- }
- if (errorCollector.errors.length > 0) {
- exception = errorCollector.errors.join('\n') +
- (exception ? ('\n' + exception.toString()) : '');
- }
- errorCollector.finish();
- finishCallback(pack, exception);
- }
-};
-
-
diff --git a/o3d/samples/o3djs/shape.js b/o3d/samples/o3djs/shape.js
deleted file mode 100644
index 7b36c16..0000000
--- a/o3d/samples/o3djs/shape.js
+++ /dev/null
@@ -1,140 +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.
- */
-
-
-/**
- * @fileoverview This file contains various functions for helping setup
- * shapes for o3d. It puts them in the "shape" module on the o3djs
- * object.
- *
- * Note: This library is only a sample. It is not meant to be some official
- * library. It is provided only as example code.
- *
- */
-
-o3djs.provide('o3djs.shape');
-
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.element');
-
-/**
- * A Module for shapes.
- * @namespace
- */
-o3djs.shape = o3djs.shape || {};
-
-/**
- * Adds missing tex coord streams to a shape's elements.
- * @param {!o3d.Shape} shape Shape to add missing streams to.
- * @see o3djs.element.addMissingTexCoordStreams
- */
-o3djs.shape.addMissingTexCoordStreams = function(shape) {
- var elements = shape.elements;
- for (var ee = 0; ee < elements.length; ++ee) {
- var element = elements[ee];
- o3djs.element.addMissingTexCoordStreams(element);
- }
-};
-
-/**
- * Sets the bounding box and z sort points of a shape's elements.
- * @param {!o3d.Shape} shape Shape to set info on.
- */
-o3djs.shape.setBoundingBoxesAndZSortPoints = function(shape) {
- var elements = shape.elements;
- for (var ee = 0; ee < elements.length; ++ee) {
- var element = elements[ee];
- o3djs.element.setBoundingBoxAndZSortPoint(element);
- }
-};
-
-/**
- * Prepares a shape by setting its boundingBox, zSortPoint and creating
- * DrawElements.
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.Shape} shape Shape to prepare.
- */
-o3djs.shape.prepareShape = function(pack, shape) {
- shape.createDrawElements(pack, null);
- o3djs.shape.setBoundingBoxesAndZSortPoints(shape);
- o3djs.shape.addMissingTexCoordStreams(shape);
-};
-
-/**
- * Prepares all the shapes in the given pack by setting their boundingBox,
- * zSortPoint and creating DrawElements.
- * @param {!o3d.Pack} pack Pack to manage created objects.
- */
-o3djs.shape.prepareShapes = function(pack) {
- var shapes = pack.getObjectsByClassName('o3d.Shape');
- for (var ss = 0; ss < shapes.length; ++ss) {
- o3djs.shape.prepareShape(pack, shapes[ss]);
- }
-};
-
-/**
- * Attempts to delete the parts of a shape that were created by
- * duplicateShape as well as any drawElements attached to it.
- * @param {!o3d.Shape} shape shape to delete.
- * @param {!o3d.Pack} pack Pack to release objects from.
- */
-o3djs.shape.deleteDuplicateShape = function(shape, pack) {
- var elements = shape.elements;
- for (var ee = 0; ee < elements.length; ee++) {
- var element = elements[ee];
- var drawElements = element.drawElements;
- for (var dd = 0; dd < drawElements.length; dd++) {
- var drawElement = drawElements[dd];
- pack.removeObject(drawElement);
- }
- pack.removeObject(element);
- }
- pack.removeObject(shape);
-};
-
-/**
- * Copies a shape's elements and streambank or buffers so the two will share
- * streambanks, vertex and index buffers.
- * @param {!o3d.Pack} pack Pack to manage created objects.
- * @param {!o3d.Shape} source The Shape to copy.
- * @return {!o3d.Shape} the new copy of the shape.
- */
-o3djs.shape.duplicateShape = function(pack, source) {
- var newShape = pack.createObject('Shape');
- var elements = source.elements;
- for (var ee = 0; ee < elements.length; ee++) {
- var newElement = o3djs.element.duplicateElement(pack, elements[ee]);
- newElement.owner = newShape;
- }
- newShape.createDrawElements(pack, null);
- return newShape;
-};
-
diff --git a/o3d/samples/o3djs/simple.js b/o3d/samples/o3djs/simple.js
deleted file mode 100644
index 7252b76..0000000
--- a/o3d/samples/o3djs/simple.js
+++ /dev/null
@@ -1,830 +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.
- */
-
-/**
- * @fileoverview This file contains functions to make it extremely simple
- * to get something on the screen in o3d. The disadvantage is it
- * is less flexible and creates inefficient assets.
- *
- * Example
- *
- * <pre>
- * &lt;html&gt;&lt;body&gt;
- * &lt;script type="text/javascript" src="o3djs/all.js"&gt;
- * &lt;/script&gt;
- * &lt;script type="text/javascript"&gt;
- * window.init = init;
- *
- * function init() {
- * o3djs.base.makeClients(initStep2);
- * }
- *
- * function initStep2(clientElements) {
- * var clientElement = clientElements[0];
- *
- * // Create an o3djs.simple object to manage things in a simple way.
- * g_simple = o3djs.simple.create(clientElement);
- *
- * // Create a cube.
- * g_cube = g_simple.createCube(50);
- *
- * // DONE!
- * }
- * &lt;/script&gt;
- * &lt;div id="o3d" style="width: 600px; height: 600px"&gt;&lt;/div&gt;
- * &lt;/body&gt;&lt;/html&gt;
- * </pre>
- *
- * Some more examples:
- *
- * g_cube.setDiffuseColor(1, 0, 0, 1); // Cube is now red.
- * g_cube.transform.translate(10, 0, 0); // Cube translates.
- * g_cube.loadTexture('http://google.com/someimage.jpg"); // Cube is textured
- *
- *
- * Note: This library is only a sample. It is not meant to be some official
- * library. It is provided only as example code.
- *
- */
-
-o3djs.provide('o3djs.simple');
-
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.shape');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.io');
-o3djs.require('o3djs.scene');
-o3djs.require('o3djs.camera');
-
-/**
- * A Module for using o3d in a very simple way.
- * @namespace
- */
-o3djs.simple = o3djs.simple || {};
-
-/**
- * Creates an o3djs.simple library object that helps manage o3d
- * for the extremely simple cases.
- *
- * <pre>
- * &lt;html&gt;&lt;body&gt;
- * &lt;script type="text/javascript" src="o3djs/all.js"&gt;
- * &lt;/script&gt;
- * &lt;script type="text/javascript"&gt;
- * windows.onload = init;
- *
- * function init() {
- * o3djs.base.makeClients(initStep2);
- * }
- *
- * function initStep2(clientElements) {
- * var clientElement = clientElements[0];
- *
- * // Create an o3djs.simple object to manage things in a simple way.
- * g_simple = o3djs.simple.create(clientElement);
- *
- * // Create a cube.
- * g_cube = g_simple.createCube(50);
- *
- * // DONE!
- * }
- * &lt;/script&gt;
- * &lt;div id="o3d" style="width: 600px; height: 600px"&gt;&lt;/div&gt;
- * &lt;/body&gt;&lt;/html&gt;
- * </pre>
- *
- * @param {!Element} clientObject O3D.Plugin Object.
- * @return {!o3djs.simple.SimpleInfo} Javascript object that hold info for the
- * simple library.
- *
- */
-o3djs.simple.create = function(clientObject) {
- return new o3djs.simple.SimpleInfo(clientObject);
-};
-
-/**
- * A SimpleInfo contains information for the simple library.
- * @constructor
- * @param {!Element} clientObject O3D.Plugin Object.
- */
-o3djs.simple.SimpleInfo = function(clientObject) {
- /**
- * The O3D Element.
- * @type {!Element}
- */
- this.clientObject = clientObject;
-
- /**
- * The O3D namespace object.
- * @type {!o3d}
- */
- this.o3d = clientObject.o3d;
-
- /**
- * The client object used by the SimpleInfo
- * @type {!o3d.Client}
- */
- this.client = clientObject.client;
-
- /**
- * The main pack for this SimpleInfo.
- * @type {!o3d.Pack}
- */
- this.pack = this.client.createPack();
-
- /**
- * The root transform for this SimpleInfo
- * @type {!o3d.Transform}
- */
- this.root = this.pack.createObject('Transform');
-
- /**
- * The ViewInfo created by this SimpleInfo.
- * @type {!o3djs.rendergraph.ViewInfo}
- */
- this.viewInfo = o3djs.rendergraph.createBasicView(
- this.pack,
- this.root,
- this.client.renderGraphRoot);
-
- /**
- * The list of objects that need to have an update function called indexed by
- * id.
- * @private
- * @type {!Object.<number,!o3djs.simple.SimpleObject>}
- */
- this.updateObjects_ = { };
-
- /**
- * The next available id for objects.
- * @private
- * @type {number}
- */
- this.nextId_ = 1;
-
- // Create 1 non-textured material and 1 textured material.
- //
- // TODO: Refactor.
- // This is slightly backward. What we really want is to be able to request
- // an effect of a specific type from our shader builder but the current shader
- // builder expects a material to already exist. So, we create a material here
- // just to pass it to the shader builder, then we keep the effect it created
- // but throw away the material.
- //
- // TODO: Fix shader builder so it creates diffuseColorMult,
- // diffuseColorOffset and diffuseTexture so
- // diffuse = diffuseTexture * diffuseColorMult + diffuseColorOffset.
-
- var material = this.pack.createObject('Material');
-
- o3djs.effect.attachStandardShader(this.pack,
- material,
- [0, 0, 0],
- 'phong');
-
- this.nonTexturedEffect_ = material.effect;
- this.pack.removeObject(material);
-
- var material = this.pack.createObject('Material');
- var samplerParam = material.createParam('diffuseSampler', 'ParamSampler');
- o3djs.effect.attachStandardShader(this.pack,
- material,
- [0, 0, 0],
- 'phong');
-
- this.texturedEffect_ = material.effect;
- this.pack.removeObject(material);
-
- this.globalParamObject = this.pack.createObject('ParamObject');
- this.lightWorldPosParam = this.globalParamObject.createParam('lightWorldPos',
- 'ParamFloat3');
- this.lightColorParam = this.globalParamObject.createParam('lightColor',
- 'ParamFloat4');
- this.setLightColor(1, 1, 1, 1);
- this.setLightPosition(255, 150, 150); // same as camera.
-
- // Attempt to setup a resonable default perspective matrix.
- this.zNear = 0.1;
- this.zFar = 1000;
- this.fieldOfView = o3djs.math.degToRad(45);
- this.setPerspectiveMatrix_();
-
- // Attempt to setup a resonable default view.
- this.cameraPosition = [250, 150, 150];
- this.cameraTarget = [0, 0, 0];
- this.cameraUp = [0, 1, 0];
- this.setViewMatrix_();
-
- var that = this;
-
- this.client.setRenderCallback(function(renderEvent) {
- var elapsedTime = Math.min(renderEvent.elapsedTime, 0.1);
- that.onRender_(elapsedTime);
- });
-};
-
-/**
- * Gets the next available id.
- * @return {number} The next available id.
- */
-o3djs.simple.SimpleInfo.prototype.getNextId = function() {
- return this.nextId_++;
-};
-
-/**
- * Creates a SimpleShape. A SimpleShape manages a transform with 1 shape that
- * holds 1 primitive and 1 unique material.
- * @param {!o3d.Shape} shape that holds 1 primitive and 1 unique material.
- * @return {!o3djs.simple.SimpleShape} the created SimpleShape.
- */
-o3djs.simple.SimpleInfo.prototype.createSimpleShape = function(shape) {
- shape.createDrawElements(this.pack, null);
- var transform = this.pack.createObject('Transform');
- transform.parent = this.root;
- transform.addShape(shape);
- return new o3djs.simple.SimpleShape(this, transform);
-};
-
-/**
- * The on render handler for a SimpleInfo.
- * @private
- * @param {number} elapsedTime Time elapsed since last frame.
- */
-o3djs.simple.SimpleInfo.prototype.onRender_ = function(elapsedTime) {
- for (var sid in this.updateObjects_) {
- var id = /** @type {number} */ (sid);
- this.updateObjects_[id].onUpdate(elapsedTime);
- }
-};
-
-/**
- * Register an object for updating. You should not call this directly.
- * @param {!o3djs.simple.SimpleObject} simpleObject SimpleObject to register.
- */
-o3djs.simple.SimpleInfo.prototype.registerObjectForUpdate =
- function (simpleObject) {
- this.updateObjects_[simpleObject.id] = simpleObject;
-};
-
-/**
- * Unregister an object for updating. You should not call this directly.
- * @param {!o3djs.simple.SimpleObject} simpleObject SimpleObject to register.
- */
-o3djs.simple.SimpleInfo.prototype.unregisterObjectForUpdate =
- function (simpleObject) {
- delete this.updateObjects_[simpleObject.id];
-};
-
-/**
- * Sets the perspective matrix.
- * @private
- */
-o3djs.simple.SimpleInfo.prototype.setPerspectiveMatrix_ = function() {
- this.viewInfo.drawContext.projection = o3djs.math.matrix4.perspective(
- this.fieldOfView,
- this.client.width / this.client.height,
- this.zNear,
- this.zFar);
-};
-
-/**
- * Sets the view matrix.
- * @private
- */
-o3djs.simple.SimpleInfo.prototype.setViewMatrix_ = function() {
- this.viewInfo.drawContext.view = o3djs.math.matrix4.lookAt(
- this.cameraPosition,
- this.cameraTarget,
- this.cameraUp);
-};
-
-/**
- * Sets the field of view
- * @param {number} fieldOfView in Radians.
- *
- * For degrees use setFieldOfView(o3djs.math.degToRad(degrees)).
- */
-o3djs.simple.SimpleInfo.prototype.setFieldOfView =
- function(fieldOfView) {
- this.fieldOfView = fieldOfView;
- this.setPerspectiveMatrix_();
-};
-
-/**
- * Sets the z clip range.
- * @param {number} zNear near z value.
- * @param {number} zFar far z value.
- */
-o3djs.simple.SimpleInfo.prototype.setZClip = function(zNear, zFar) {
- this.zNear = zNear;
- this.zFar = zFar;
- this.setPerspectiveMatrix_();
-};
-
-/**
- * Sets the light position
- * @param {number} x x position.
- * @param {number} y y position.
- * @param {number} z z position.
- */
-o3djs.simple.SimpleInfo.prototype.setLightPosition = function(x, y, z) {
- this.lightWorldPosParam.set(x, y, z);
-};
-
-/**
- * Sets the light color
- * @param {number} r red (0-1).
- * @param {number} g green (0-1).
- * @param {number} b blue (0-1).
- * @param {number} a alpha (0-1).
- */
-o3djs.simple.SimpleInfo.prototype.setLightColor = function(r, g, b, a) {
- this.lightColorParam.set(r, g, b, a);
-};
-
-/**
- * Sets the camera position
- * @param {number} x x position.
- * @param {number} y y position.
- * @param {number} z z position.
- */
-o3djs.simple.SimpleInfo.prototype.setCameraPosition = function(x, y, z) {
- this.cameraPosition = [x, y, z];
- this.setViewMatrix_();
-};
-
-/**
- * Sets the camera target
- * @param {number} x x position.
- * @param {number} y y position.
- * @param {number} z z position.
- */
-o3djs.simple.SimpleInfo.prototype.setCameraTarget = function(x, y, z) {
- this.cameraTarget = [x, y, z];
- this.setViewMatrix_();
-};
-
-/**
- * Sets the camera up
- * @param {number} x x position.
- * @param {number} y y position.
- * @param {number} z z position.
- */
-o3djs.simple.SimpleInfo.prototype.setCameraUp = function(x, y, z) {
- this.cameraUp = [x, y, z];
- this.setViewMatrix_();
-};
-
-/**
- * Create meterial from effect.
- * @param {!o3d.Effect} effect Effect to use for material.
- * @return {!o3d.Material} The created material.
- */
-o3djs.simple.SimpleInfo.prototype.createMaterialFromEffect =
- function(effect) {
- var material = this.pack.createObject('Material');
- material.drawList = this.viewInfo.performanceDrawList;
- material.effect = effect;
- effect.createUniformParameters(material);
- material.getParam('lightWorldPos').bind(this.lightWorldPosParam);
- material.getParam('lightColor').bind(this.lightColorParam);
- return material;
-};
-
-/**
- * Create a new non-textured material.
- * @param {string} type Type of material 'phong', 'lambert', 'constant'.
- * @return {!o3d.Material} The created material.
- */
-o3djs.simple.SimpleInfo.prototype.createNonTexturedMaterial =
- function(type) {
- var material = this.createMaterialFromEffect(this.nonTexturedEffect_);
- material.getParam('diffuse').set(1, 1, 1, 1);
- material.getParam('emissive').set(0, 0, 0, 1);
- material.getParam('ambient').set(0, 0, 0, 1);
- material.getParam('specular').set(1, 1, 1, 1);
- material.getParam('shininess').value = 20;
- return material;
-};
-
-/**
- * @param {string} type Type of material 'phong', 'lambert', 'constant'.
- * @return {!o3d.Material} The created material.
- */
-o3djs.simple.SimpleInfo.prototype.createTexturedMaterial =
- function(type) {
- var material = this.createMaterialFromEffect(this.texturedEffect_);
- var samplerParam = material.getParam('diffuseSampler');
- var sampler = this.pack.createObject('Sampler');
- samplerParam.value = sampler;
- return material;
-};
-
-/**
- * Creates a cube and adds it to the root of this SimpleInfo's transform graph.
- * @param {number} size Width, height and depth of the cube.
- * @return {!o3djs.simple.SimpleShape} A Javascript object to manage the
- * shape.
- */
-o3djs.simple.SimpleInfo.prototype.createCube = function(size) {
- var material = this.createNonTexturedMaterial('phong');
- var shape = o3djs.primitives.createCube(this.pack, material, size);
- return this.createSimpleShape(shape);
-};
-
-/**
- * Creates a box and adds it to the root of this SimpleInfo's transform graph.
- * @param {number} width Width of the box.
- * @param {number} height Height of the box.
- * @param {number} depth Depth of the box.
- * @return {!o3djs.simple.SimpleShape} A Javascript object to manage the
- * shape.
- */
-o3djs.simple.SimpleInfo.prototype.createBox = function(width,
- height,
- depth) {
- var material = this.createNonTexturedMaterial('phong');
- var shape = o3djs.primitives.createBox(this.pack,
- material,
- width,
- height,
- depth);
- return this.createSimpleShape(shape);
-};
-
-/**
- * Creates a sphere and adds it to the root of this SimpleInfo's transform
- * graph.
- * @param {number} radius radius of sphere.
- * @param {number} smoothness determines the number of subdivisions.
- * @return {!o3djs.simple.SimpleShape} A Javascript object to manage the
- * shape.
- */
-o3djs.simple.SimpleInfo.prototype.createSphere = function(radius,
- smoothness) {
- var material = this.createNonTexturedMaterial('phong');
- var shape = o3djs.primitives.createSphere(this.pack,
- material,
- radius,
- smoothness * 2,
- smoothness);
- return this.createSimpleShape(shape);
-};
-
-/**
- * Loads a scene from a URL.
- * @param {string} url Url of scene to load.
- * @param {!function(o3djs.simple.SimpleScene, *): void} callback a callback to
- * call when the scene is loaded. The first argument will be null if the
- * scene failed to load and last object will be an exception.
- * @return {!o3djs.io.LoadInfo}
- */
-o3djs.simple.SimpleInfo.prototype.loadScene = function(url, callback) {
- var pack = this.client.createPack();
- var root = pack.createObject('Transform');
- var paramObject = pack.createObject('ParamObject');
- var animTimeParam = paramObject.createParam('animTime', 'ParamFloat');
- var that = this;
-
- var prepScene = function(pack, root, exception) {
- var simpleScene = null;
- if (exception) {
- pack.destroy();
- } else {
- simpleScene = new o3djs.simple.SimpleScene(
- that, url, pack, root, paramObject);
- }
- callback(simpleScene, exception);
- };
-
- return o3djs.scene.loadScene(
- this.client,
- pack,
- root,
- url,
- prepScene,
- /** @type {!o3djs.serialization.Options} */
- ({opt_animSource: animTimeParam}));
-};
-
-/**
- * Moves the camera so everything in the current scene is visible.
- */
-o3djs.simple.SimpleInfo.prototype.viewAll = function() {
- var bbox = o3djs.util.getBoundingBoxOfTree(this.root);
- var target = o3djs.math.lerpVector(bbox.minExtent, bbox.maxExtent, 0.5);
- this.setCameraTarget(target[0], target[1], target[2]);
- // TODO: Refactor this so it takes a vector from the current camera
- // position to the center of the scene and moves the camera along that
- // vector away from the center of the scene until for the given fieldOfView
- // everything is visible.
- var diag = o3djs.math.distance(bbox.minExtent, bbox.maxExtent);
- var eye = o3djs.math.addVector(target, [
- bbox.maxExtent[0],
- bbox.minExtent[1] + 0.5 * diag,
- bbox.maxExtent[2]]);
- this.setCameraPosition(eye[0], eye[1], eye[2]);
- this.setZClip(diag / 1000, diag * 10);
-};
-
-/**
- * An object for managing things simply.
- * @constructor
- */
-o3djs.simple.SimpleObject = function() {
-};
-
-/**
- * Initializes a SimpleObject.
- * @param {!o3djs.simple.SimpleInfo} simpleInfo The SimpleInfo to manage this
- * object.
- * @param {!o3d.Transform} transform Transform that orients this object.
- */
-o3djs.simple.SimpleObject.prototype.init = function(simpleInfo, transform) {
- /**
- * The SimpleInfo managing this object.
- * @type {!o3djs.simple.SimpleInfo}
- */
- this.simpleInfo = simpleInfo;
-
- /**
- * The Id for this SimpleInfo.
- * @type {number}
- */
- this.id = simpleInfo.getNextId();
-
- /**
- * The Transform that orients this object.
- * @type {!o3d.Transform}
- */
- this.transform = transform;
-
- /**
- * The update callback for this object.
- * @private
- * @type {?function(number): void}
- */
- this.updateCallback_ = null;
-
- /**
- * The pick callback for this object.
- * @private
- * @type {?function(number): void}
- */
- this.pickCallback_ = null;
-};
-
-/**
- * Registers on an on picked callback.
- * @param {!function(!o3djs.simple.SimpleObject): void} onPickedCallback A
- * function called when this object is picked.
- */
-o3djs.simple.SimpleObject.prototype.onPicked = function(onPickedCallback) {
- throw 'not implemented';
-};
-
-/**
- * Used to call the update callback on this object. You should not call this
- * directly. Use o3djs.simple.SimpleObject.setOnUpdate to add your own update
- * callback.
- * @param {number} elapsedTime ElapsedTime in seconds for this frame.
- * @see o3djs.simple.SimpleObject.setOnUpdate
- */
-o3djs.simple.SimpleObject.prototype.onUpdate = function(elapsedTime) {
- if (this.updateCallback_) {
- this.updateCallback_(elapsedTime);
- }
-};
-
-/**
- * Sets a function to be called every frame for this object.
- * @param {function(number): void} onUpdateCallback A function that is passed
- * the elapsed time in seconds. Pass in null to clear the callback function.
- * @return {(function(number): void|null)} The previous callback function.
- */
-o3djs.simple.SimpleObject.prototype.setOnUpdate = function(onUpdateCallback) {
- if (onUpdateCallback) {
- this.simpleInfo.registerObjectForUpdate(this);
- } else {
- this.simpleInfo.unregisterObjectForUpdate(this);
- }
- var oldCallback = this.updateCallback_;
- this.updateCallback_ = onUpdateCallback;
- return oldCallback;
-};
-
-/**
- * A SimpleShape manages a transform with 1 shape that holds 1 primitive
- * and 1 unique material.
- * @constructor
- * @extends {o3djs.simple.SimpleObject}
- * @param {!o3djs.simple.SimpleInfo} simpleInfo The SimpleInfo to manage this
- * shape.
- * @param {!o3d.Transform} transform Transform with 1 shape that holds 1
- * primitive and 1 unique material.
- */
-o3djs.simple.SimpleShape = function(simpleInfo, transform) {
- this.init(simpleInfo, transform);
-};
-
-o3djs.simple.SimpleShape.prototype = new o3djs.simple.SimpleObject();
-
-/**
- * Gets the current material for this shape.
- * @return {o3d.Material} the material for this SimpleShape.
- */
-o3djs.simple.SimpleShape.prototype.getMaterial = function() {
- return this.transform.shapes[0].elements[0].material;
-};
-
-/**
- * Sets the material for this SimpleShape, deleting any old one.
- * @param {!o3d.Material} material new material.
- */
-o3djs.simple.SimpleShape.prototype.setMaterial = function(material) {
- var old_material = this.getMaterial();
- if (old_material != null) {
- this.simpleInfo.pack.removeObject(old_material);
- }
- this.transform.shapes[0].elements[0].material = material;
-};
-
-/**
- * Sets the diffuse color of this shape.
- * @param {number} r Red (0-1).
- * @param {number} g Green (0-1).
- * @param {number} b Blue (0-1).
- * @param {number} a Alpha (0-1).
- */
-o3djs.simple.SimpleShape.prototype.setDiffuseColor =
- function(r, g, b, a) {
- var material = this.getMaterial();
- material.getParam('diffuse').set(r, g, b, a);
- if (a < 1) {
- material.drawList = this.simpleInfo.viewInfo.zOrderedDrawList;
- } else {
- material.drawList = this.simpleInfo.viewInfo.performanceDrawList;
- }
-};
-
-/**
- * Gets the texture on this shape.
- * @return {o3d.Texture} The texture on this shape. May be null.
- */
-o3djs.simple.SimpleShape.prototype.getTexture = function() {
- var material = this.getMaterial();
- var samplerParam = material.getParam('diffuseSampler');
- if (samplerParam.className == 'o3d.ParamSampler') {
- return samplerParam.texture;
- }
- return null;
-};
-
-/**
- * Loads a texture onto the given shape. It will replace the material
- * if it needs to with one that supports a texture. Note that the texture
- * is loaded asynchronously and so the result of this call may appear several
- * seconds after it is called depending on how long it takes to download the
- * texture.
- * @param {string} url Url of texture.
- */
-o3djs.simple.SimpleShape.prototype.loadTexture = function(url) {
- var that = this;
- o3djs.io.loadTexture(
- this.simpleInfo.pack,
- url,
- function(texture, exception) {
- if (!exception) {
- // See if this is a textured material.
- var material = that.getMaterial();
- if (material.effect != that.simpleInfo.texturedEffect_) {
- // replace the material with a textured one.
- var new_material = that.simpleInfo.createTexturedMaterial('phong');
- new_material.copyParams(material);
- // Reset the effect since copy Params just copied the non-textured
- // one.
- new_material.effect = that.simpleInfo.texturedEffect_;
- that.setMaterial(new_material);
- material = new_material;
- }
- var samplerParam = material.getParam('diffuseSampler');
- samplerParam.value.texture = texture;
- } else {
- alert('Load texture file returned failure. \n' + exception);
- }
- });
-};
-
-/**
- * An object to simply manage a scene.
- * @constructor
- * @extends {o3djs.simple.SimpleObject}
- * @param {!o3djs.simple.SimpleInfo} simpleInfo The SimpleInfo to manage this
- * scene.
- * @param {string} url Url scene was loaded from.
- * @param {!o3d.Pack} pack Pack that is managing scene.
- * @param {!o3d.Transform} root Root transform of scene.
- * @param {!o3d.ParamObject} paramObject the holds global parameters.
- */
-o3djs.simple.SimpleScene = function(
- simpleInfo, url, pack, root, paramObject) {
- this.init(simpleInfo, root);
- /**
- * The url this scene was loaded from.
- * @type {string}
- */
- this.url = url;
-
- /**
- * The pack managing this scene.
- * @type {!o3d.Pack}
- */
- this.pack = pack;
-
- /**
- * The param object holding global parameters for this scene.
- * @type {!o3d.ParamObject}
- */
- this.paramObject = paramObject;
-
- /**
- * The animation parameter for this scene.
- * @type {!o3d.ParamFloat}
- */
- this.animTimeParam = paramObject.getParam('animTime');
-
- o3djs.pack.preparePack(pack, simpleInfo.viewInfo);
-
- this.cameraInfos_ = o3djs.camera.getCameraInfos(
- root,
- simpleInfo.client.width,
- simpleInfo.client.height);
-
-
- /**
- * Binds a param if it exists.
- * @param {!o3d.ParamObject} paramObject The object that has the param.
- * @param {string} paramName name of param.
- * @param {!o3d.Param} sourceParam The param to bind to.
- */
- var bindParam = function(paramObject, paramName, sourceParam) {
- var param = paramObject.getParam(paramName);
- if (param) {
- param.bind(sourceParam);
- }
- }
-
- var materials = pack.getObjectsByClassName('o3d.Material');
- for (var m = 0; m < materials.length; ++m) {
- var material = materials[m];
- bindParam(material, 'lightWorldPos', simpleInfo.lightWorldPosParam);
- bindParam(material, 'lightColor', simpleInfo.lightColorParam);
- }
-
- this.transform.parent = this.simpleInfo.root;
-};
-
-o3djs.simple.SimpleScene.prototype = new o3djs.simple.SimpleObject();
-
-/**
- * Sets the animation time for the scene.
- * @param {number} time Animation time in seconds.
- */
-o3djs.simple.SimpleScene.prototype.setAnimTime = function(time) {
- this.animTimeParam.value = time;
-};
-
-
diff --git a/o3d/samples/o3djs/test.js b/o3d/samples/o3djs/test.js
deleted file mode 100644
index 84fd88a..0000000
--- a/o3d/samples/o3djs/test.js
+++ /dev/null
@@ -1,342 +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.
- */
-
-
-/**
- * @fileoverview This is a simple unit testing library used to test the
- * sample utilities
- *
- *
- */
-o3djs.provide('o3djs.test');
-
-/**
- * A unit testing library
- */
-o3djs.test = o3djs.test || {};
-
-/**
- * Class of errors thrown by assertions
- * @param {string} message The assertion message.
- * @this o3djs.test.AssertionError
- */
-o3djs.test.AssertionError = function(message) {
- this.message = message;
-
- /**
- * Returns the error message.
- * @return {String} The error message.
- */
- this.toString = function() {
- return message;
- };
-};
-
-/**
- * Runs all the tests found in the given suite. Every function with a
- * name beginning with 'test' is considered to be a test.
- * @param {!Object} suite The object containing the test suite.
- * @param {!Object} opt_reporter An optional object to which the results
- * of the test run are reported.
- * @return {boolean} Whether all the tests passed.
- */
-o3djs.test.runTests = function(suite, opt_reporter) {
- try {
- opt_reporter = opt_reporter || o3djs.test.documentReporter;
-
- var passCount = 0;
- var failCount = 0;
- for (var propertyName in suite) {
- if (propertyName.substring(0, 4) !== 'test')
- continue;
-
- if (typeof(suite[propertyName]) !== 'function')
- continue;
-
- try {
- suite[propertyName]();
- } catch (e) {
- ++failCount;
- opt_reporter.reportFail(propertyName, String(e));
- continue;
- }
-
- ++passCount;
- opt_reporter.reportPass(propertyName);
- }
-
- opt_reporter.reportSummary(passCount, failCount);
- return failCount == 0;
- }
- catch (e) {
- return false;
- }
-};
-
-/**
- * Converts a value to the string representation used in assertion messages.
- * @private
- * @param {*} value The value to convert.
- * @param {number} opt_depth The depth of references to follow for nested
- * objects. Defaults to 3.
- * @return {string} The string representation.
- */
-o3djs.test.valueToString_ = function(value, opt_depth) {
- if (opt_depth === undefined) {
- opt_depth = 3;
- }
- var string;
- if (typeof(value) === 'object') {
- if (value !== null) {
- if (opt_depth === 0) {
- string = '?';
- } else {
- if (o3djs.base.isArray(value)) {
- var valueAsArray = /** @type {!Array.<*>} */ (value);
- string = '[';
- var separator = '';
- for (var i = 0; i < valueAsArray.length; ++i) {
- string += separator +
- o3djs.test.valueToString_(valueAsArray[i], opt_depth - 1);
- separator = ', ';
- }
- string += ']';
- } else {
- var valueAsObject = /** @type {!Object} */ (value);
- string = '{';
- var separator = '';
- for (var propertyName in valueAsObject) {
- if (typeof(valueAsObject[propertyName]) !== 'function') {
- string += separator + propertyName + ': ' +
- o3djs.test.valueToString_(valueAsObject[propertyName],
- opt_depth - 1);
- separator = ', ';
- }
- }
- string += '}';
- }
- }
- } else {
- string = "null";
- }
- } else if (typeof(value) === 'string') {
- string = '"' + value + '"';
- } else {
- string = String(value);
- }
- return string;
-};
-
-/**
- * Asserts that a value is true from within a test
- * @param {boolean} value The value to test.
- */
-o3djs.test.assertTrue = function(value) {
- if (!value) {
- throw new o3djs.test.AssertionError(
- 'assertTrue failed for ' +
- o3djs.test.valueToString_(value));
- }
-};
-
-/**
- * Asserts that a value is false from within a test
- * @param {boolean} value The value to test.
- */
-o3djs.test.assertFalse = function(value) {
- if (value) {
- throw new o3djs.test.AssertionError(
- 'assertFalse failed for ' +
- o3djs.test.valueToString_(value));
- }
-};
-
-/**
- * Asserts that a value is null from within a test
- * @param {*} value The value to test.
- */
-o3djs.test.assertNull = function(value) {
- if (value !== null) {
- throw new o3djs.test.AssertionError(
- 'assertNull failed for ' +
- o3djs.test.valueToString_(value));
- }
-};
-
-/**
- * Asserts that an expected value is equal to an actual value.
- * @param {*} expected The expected value.
- * @param {*} actual The actual value.
- */
-o3djs.test.assertEquals = function(expected, actual) {
- if (expected !== actual) {
- throw new o3djs.test.AssertionError(
- 'assertEquals failed: expected ' +
- o3djs.test.valueToString_(expected) + ' but got ' +
- o3djs.test.valueToString_(actual));
- }
-};
-
-/**
- * Asserts that an expected value is close to an actual value
- * within a tolerance of 0.001.
- * @param {number} expected The expected value.
- * @param {number} actual The actual value.
- */
-o3djs.test.assertClose = function(expected, actual) {
- if (actual < expected - 0.001 || actual > expected + 0.001) {
- throw new o3djs.test.AssertionError(
- 'assertClose failed: expected ' +
- o3djs.test.valueToString_(expected) + ' but got ' +
- o3djs.test.valueToString_(actual));
- }
-};
-
-/**
- * Determines whether the elements of a pair of arrays are equal.
- * @private
- * @param {!Array.<*>} expected The expected array.
- * @param {!Array.<*>} actual The actual array.
- * @return {boolean} Whether the arrays are equal.
- */
-o3djs.test.compareArrays_ = function(expected, actual) {
- if (expected.length !== actual.length) {
- return false;
- }
- for (var i = 0; i != expected.length; ++i) {
- if (o3djs.base.isArray(expected[i]) && o3djs.base.isArray(actual[i])) {
- var expectedAsArray = /** @type {!Array.<*>} */ (expected[i]);
- var actualAsArray = /** @type {!Array.<*>} */ (actual[i]);
- if (!o3djs.test.compareArrays_(expectedAsArray, actualAsArray)) {
- return false;
- }
- } else if (expected[i] !== actual[i]) {
- return false;
- }
- }
- return true;
-};
-
-/**
- * Asserts that an expected array is equal to an actual array.
- * @param {!Array.<*>} expected The expected array.
- * @param {!Array.<*>} actual The actual array.
- */
-o3djs.test.assertArrayEquals = function(expected, actual) {
- if (!o3djs.base.isArray(expected)) {
- throw new o3djs.test.AssertionError(
- 'assertArrayEquals failed: expected value ' +
- o3djs.test.valueToString_(expected) +
- ' is not an array');
- }
- if (!o3djs.base.isArray(actual)) {
- throw new o3djs.test.AssertionError(
- 'assertArrayEquals failed: actual value ' +
- o3djs.test.valueToString_(actual) +
- ' is not an array');
- }
- if (!o3djs.test.compareArrays_(expected, actual)) {
- throw new o3djs.test.AssertionError(
- 'assertArrayEquals failed: expected ' +
- o3djs.test.valueToString_(expected) + ' but got ' +
- o3djs.test.valueToString_(actual));
- }
-};
-
-/**
- * Creates a DOM paragraph object for the given text and color.
- * @private
- * @param {string} text The text of the message.
- * @param {string} opt_color The optional color of the message.
- * @return {!Element} A DOM paragraph object.
- */
-o3djs.test.createReportParagraph_ = function(text, opt_color) {
- var textNode = document.createTextNode(text);
- var paragraph = document.createElement('p');
- paragraph.appendChild(textNode);
- if (opt_color !== undefined) {
- paragraph.style.color = opt_color;
- }
- return paragraph;
-};
-
-/**
- * A reporter that reports messages to the document (i.e. the DOM).
- * @type {!Object}
- */
-o3djs.test.documentReporter = {
- /**
- * A Report div.
- * @private
- * @this {Object}
- */
- getReportDiv_: function() {
- if (!this.reportDiv_) {
- this.reportDiv_ = document.createElement('div');
- document.body.appendChild(this.reportDiv_);
- }
- return this.reportDiv_;
- },
- /**
- * Reports a test passed.
- * @param {string} testName The name of the test.
- * @this {Object}
- */
- reportPass: function(testName) {
- var paragraph = o3djs.test.createReportParagraph_(
- testName + ' : PASS', 'green');
- this.getReportDiv_().appendChild(paragraph);
- },
- /**
- * Reports a test failed.
- * @param {string} testName The name of the test.
- */
- reportFail: function(testName, message) {
- var paragraph = o3djs.test.createReportParagraph_(
- testName + ' : FAIL : ' + message, 'red');
- var reportDiv = this.getReportDiv_();
- reportDiv.insertBefore(paragraph,
- reportDiv.firstChild);
- },
- /**
- * Reports a test summary.
- * @param {number} passCount The number of tests that passed.
- * @param {number} failCount The number of tests that failed.
- * @this {Object}
- */
- reportSummary: function(passCount, failCount) {
- var paragraph = o3djs.test.createReportParagraph_(
- passCount + ' passed, ' + failCount + ' failed', 'blue');
- var reportDiv = this.getReportDiv_();
- reportDiv.insertBefore(paragraph,
- reportDiv.firstChild);
- }
-};
diff --git a/o3d/samples/o3djs/texture.js b/o3d/samples/o3djs/texture.js
deleted file mode 100644
index 8bb6680..0000000
--- a/o3d/samples/o3djs/texture.js
+++ /dev/null
@@ -1,295 +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.
- */
-
-
-/**
- * @fileoverview This file contains functions helping to manipulate and manage
- * textures.
- */
-
-o3djs.provide('o3djs.texture');
-
-/**
- * A Module for bitmaps.
- * @namespace
- */
-o3djs.texture = o3djs.texture || {};
-
-/**
- * The maximum dimension of a texture.
- * @type {number}
- */
-o3djs.texture.MAX_TEXTURE_DIMENSION = 2048;
-
-/**
- * Computes the maximum number of levels of mips a given width and height could
- * use.
- * @param {number} width Width of texture.
- * @param {number} height Height of texture.
- * @return {number} The maximum number of levels for the given width and height.
- */
-o3djs.texture.computeNumLevels = function(width, height) {
- if (width == 0 || height == 0) {
- return 0;
- }
- var max = Math.max(width, height);
- var levels = 0;
- while (max > 0) {
- ++levels;
- max = max >> 1;
- }
- return levels;
-};
-
-/**
- * Creates a texture from a RawData object.
- * @param {!o3d.Pack} pack The pack to create the texture in.
- * @param {!o3d.RawData} rawData The raw data to create the texture from.
- * @param {boolean} opt_generateMips Whether or not to generate mips. Note, mips
- * can not be generated for DXT textures although they will be loaded if they
- * exist in the RawData.
- * @param {boolean} opt_flip Whether or not to flip the texture. Most DCC tools
- * Like Maya, Max, etc expect the textures to be flipped. Note that only
- * 2D (image) textures will be flipped. Cube textures will not be flipped.
- * Default = true.
- * @param {number} opt_maxWidth The maximum width of the texture. If the RawData
- * is larger than this size it will be scaled down to this size. Note that
- * DXT format textures can not be scaled. Default = 2048.
- * @param {number} opt_maxHeight The maximum width of the texture. If the
- * RawData is larger than this size it will be scaled down to this size. Note
- * that DXT format textures can not be scaled. Default = 2048.
- * @return {!o3d.Texture} The created texture.
- */
-o3djs.texture.createTextureFromRawData = function(
- pack,
- rawData,
- opt_generateMips,
- opt_flip,
- opt_maxWidth,
- opt_maxHeight) {
- // Make a bitmaps from the raw data.
- var bitmaps = pack.createBitmapsFromRawData(rawData);
- if (opt_flip || typeof opt_flip === 'undefined') {
- for (var ii = 0; ii < bitmaps.length; ++ii) {
- var bitmap = bitmaps[ii];
- if (bitmap.semantic == o3djs.base.o3d.Bitmap.IMAGE) {
- bitmaps[ii].flipVertically();
- }
- }
- }
-
- // Create a texture from the bitmaps.
- var texture = o3djs.texture.createTextureFromBitmaps(
- pack, bitmaps, opt_generateMips);
-
- // Delete the bitmaps.
- for (var ii = 0; ii < bitmaps.length; ++ii) {
- pack.removeObject(bitmaps[ii]);
- }
-
- return texture;
-};
-
-/**
- * Creates a texture from an array of RawData objects. This is mainly useful for
- * creating a cube map out of six separate textures.
- * @param {!o3d.Pack} pack The pack to create the texture in.
- * @param {!Array.<!o3d.RawData>} rawDataArray The array of raw data objects to
- * create the texture from. If these represent the six faces of a cube map,
- * they must be in the order FACE_POSITIVE_X, FACE_NEGATIVE_X,
- * FACE_POSITIVE_Y, FACE_NEGATIVE_Y, FACE_POSITIVE_Z, FACE_NEGATIVE_Z
- * @param {boolean} opt_generateMips Whether or not to generate mips. Note, mips
- * can not be generated for DXT textures although they will be loaded if they
- * exist in the RawData.
- * @param {boolean} opt_flip Whether or not to flip the texture. Most DCC tools
- * Like Maya, Max, etc expect the textures to be flipped. Note that only
- * 2D (image) textures will be flipped. Cube textures will not be flipped.
- * Default = true.
- * @param {number} opt_maxWidth The maximum width of the texture. If the RawData
- * is larger than this size it will be scaled down to this size. Note that
- * DXT format textures can not be scaled. Default = 2048.
- * @param {number} opt_maxHeight The maximum width of the texture. If the
- * RawData is larger than this size it will be scaled down to this size. Note
- * that DXT format textures can not be scaled. Default = 2048.
- * @return {!o3d.Texture} The created texture.
- */
-o3djs.texture.createTextureFromRawDataArray = function(
- pack,
- rawDataArray,
- opt_generateMips,
- opt_flip,
- opt_maxWidth,
- opt_maxHeight) {
- // Make bitmaps from the raw data.
- var bitmaps = [];
- for (var ii = 0; ii < rawDataArray.length; ++ii) {
- bitmaps = bitmaps.concat(pack.createBitmapsFromRawData(rawDataArray[ii]));
- }
- if (opt_flip || typeof opt_flip === 'undefined') {
- for (var ii = 0; ii < bitmaps.length; ++ii) {
- var bitmap = bitmaps[ii];
- if (bitmap.semantic == o3djs.base.o3d.Bitmap.IMAGE) {
- bitmaps[ii].flipVertically();
- }
- }
- }
-
- // Create a texture from the bitmaps.
- // TODO(kbr): use createCubeTextureFrom6Bitmaps instead; bugs in the plugin
- // currently prevent this.
- var texture = o3djs.texture.createTextureFromBitmaps(
- pack, bitmaps, opt_generateMips);
-
- // Delete the bitmaps.
- for (var ii = 0; ii < bitmaps.length; ++ii) {
- pack.removeObject(bitmaps[ii]);
- }
-
- return texture;
-};
-
-/**
- * Returns whether or not a given texture format can be scaled.
- * @param {!o3d.Texture.Format} format The format to check.
- * @return {boolean} True if you can scale and make mips for the given format.
- */
-o3djs.texture.canMakeMipsAndScale = function(format) {
- switch (format) {
- case o3djs.base.o3d.Texture.XRGB8:
- case o3djs.base.o3d.Texture.ARGB8:
- case o3djs.base.o3d.Texture.ABGR16F:
- case o3djs.base.o3d.Texture.R32F:
- case o3djs.base.o3d.Texture.ABGR32F:
- return true;
- case o3djs.base.o3d.Texture.DXT1:
- case o3djs.base.o3d.Texture.DXT3:
- case o3djs.base.o3d.Texture.DXT5:
- return false;
- }
- return false;
-};
-
-/**
- * Creates a Texture from an array of bitmaps.
- * @param {!o3d.Pack} pack The pack to create the texture in.
- * @param {!Array.<!o3d.Bitmap>} bitmaps An array of bitmaps to create the
- * texture from. For a 2D texture this would be 1 bitmap. For a cubemap this
- * would be 6 bitmaps.
- * @param {boolean} opt_generateMips Whether or not to generate mips. Note, mips
- * can not be generated for DXT textures although they will be loaded if they
- * exist in the RawData. Default = true.
- * @return {!o3d.Texture} The created texture.
- */
-o3djs.texture.createTextureFromBitmaps = function(
- pack,
- bitmaps,
- opt_generateMips) {
- if (bitmaps.length == 0) {
- throw 'no bitmaps';
- }
-
- var srcWidth = bitmaps[0].width;
- var srcHeight = bitmaps[0].height;
- var format = bitmaps[0].format;
- var mipMaps = bitmaps[0].numMipmaps;
- var maxMips = o3djs.texture.computeNumLevels(srcWidth, srcHeight);
- var targetMips = mipMaps;
- var dstWidth = srcWidth;
- var dstHeight = srcHeight;
- if ((typeof opt_generateMips === 'undefined' || opt_generateMips) &&
- o3djs.texture.canMakeMipsAndScale(format) &&
- mipMaps == 1 && maxMips > 1) {
- targetMips = maxMips;
- }
-
- // Check that all the bitmaps are the same size and make mips
- for (var ii = 0; ii < bitmaps.length; ++ii) {
- var bitmap = bitmaps[ii];
- if (bitmap.width != srcWidth ||
- bitmap.height != srcHeight ||
- bitmap.format != format ||
- bitmap.numMipmaps != mipMaps) {
- throw 'bitmaps must all be the same width, height, mips and format';
- }
- if (targetMips != mipMaps) {
- bitmap.generateMips(0, targetMips - 1);
- }
- }
-
- var levels = bitmap.numMipmaps > 1 ? bitmap.numMipmaps :
- o3djs.texture.computeNumLevels(dstWidth, dstHeight);
- var texture;
- if (bitmaps.length == 6 &&
- bitmaps[0].semantic != o3djs.base.o3d.Bitmap.SLICE) {
- if (srcWidth != srcHeight ||
- srcWidth != dstWidth ||
- srcHeight != dstHeight) {
- throw 'Cubemaps must be square';
- }
- texture = pack.createTextureCUBE(dstWidth, format, targetMips, false);
- for (var ii = 0; ii < 6; ++ii) {
- texture.setFromBitmap(
- /** @type {o3d.TextureCUBE.CubeFace} */ (ii),
- bitmaps[ii]);
- }
- } else if (bitmaps.length == 1) {
- texture = pack.createTexture2D(
- dstWidth, dstHeight, format, targetMips, false);
- texture.setFromBitmap(bitmaps[0]);
- }
-
- return /** @type{!o3d.Texture} */ (texture);
-};
-
-/**
- * Creates a TextureCUBE from 6 bitmaps. The bitmaps do not have to be the same
- * size though they do have to be the same format.
- *
- * @param {!o3d.Pack} pack The pack to create the texture in.
- * @param {number} edgeLength The size of the cubemap.
- * @param {!Array.<!o3d.Bitmap>} bitmaps An array of 6 bitmaps in the order
- * FACE_POSITIVE_X, FACE_NEGATIVE_X, FACE_POSITIVE_Y, FACE_NEGATIVE_Y,
- * FACE_POSITIVE_Z, FACE_NEGATIVE_Z.
- * @return {!o3d.Texture} The created texture.
- */
-o3djs.texture.createCubeTextureFrom6Bitmaps = function(
- pack, edgeLength, bitmaps) {
- var numMips = o3djs.texture.computeNumLevels(edgeLength, edgeLength);
- var texture = pack.createTextureCUBE(
- edgeLength, bitmaps[0].format, numMips, false);
- for (var ii = 0; ii < 6; ++ii) {
- var bitmap = bitmaps[ii];
- texture.setFromBitmap(/** @type{o3d.TextureCUBE.CubeFace} */ (ii), bitmap);
- }
- texture.generateMips(0, numMips - 1);
- return texture;
-};
-
diff --git a/o3d/samples/o3djs/util.js b/o3d/samples/o3djs/util.js
deleted file mode 100644
index 24c09d0..0000000
--- a/o3d/samples/o3djs/util.js
+++ /dev/null
@@ -1,1037 +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.
- */
-
-
-/**
- * @fileoverview This file contains various utility functions for o3d. It
- * puts them in the "util" module on the o3djs object.
- *
- */
-
-o3djs.provide('o3djs.util');
-
-o3djs.require('o3djs.io');
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.event');
-o3djs.require('o3djs.error');
-
-/**
- * A Module with various utilities.
- * @namespace
- */
-o3djs.util = o3djs.util || {};
-
-/**
- * The name of the o3d plugin. Used to find the plugin when checking
- * for its version.
- * @type {string}
- */
-o3djs.util.PLUGIN_NAME = 'O3D Plugin';
-
-/**
- * The version of the plugin needed to use this version of the javascript
- * utility libraries.
- * @type {string}
- */
-o3djs.util.REQUIRED_VERSION = '0.1.42.4';
-
-/**
- * The width an O3D must be to put a failure message inside
- * @type {number}
- */
-o3djs.util.MINIMUM_WIDTH_FOR_MESSAGE = 200;
-
-/**
- * The height an O3D must be to put a failure message inside
- * @type {number}
- */
-o3djs.util.MINIMUM_HEIGHT_FOR_MESSAGE = 200;
-
-/**
- * A URL at which to download the client.
- * @type {string}
- */
-o3djs.util.PLUGIN_DOWNLOAD_URL = 'http://tools.google.com/dlpage/o3d';
-
-/**
- * The Renderer InitStatus constants so we don't need an o3d object to look
- * them up.
- * @enum {number}
- */
-o3djs.util.rendererInitStatus = {
- NO_PLUGIN: -1,
- UNINITIALIZED: 0,
- SUCCESS: 1,
- OUT_OF_RESOURCES: 2,
- GPU_NOT_UP_TO_SPEC: 3,
- INITIALIZATION_ERROR: 4
-};
-
-/**
- * This implements a JavaScript version of currying. Currying allows you to
- * take a function and fix its initial arguments, resulting in a function
- * expecting only the remaining arguments when it is invoked. For example:
- * <pre>
- * function add(a, b) {
- * return a + b;
- * }
- * var increment = o3djs.util.curry(add, 1);
- * var result = increment(10);
- * </pre>
- * Now result equals 11.
- * @param {!function(...): *} func The function to curry.
- * @return {!function(...): *} The curried function.
- */
-o3djs.util.curry = function(func) {
- var outerArgs = [];
- for (var i = 1; i < arguments.length; ++i) {
- outerArgs.push(arguments[i]);
- }
- return function() {
- var innerArgs = outerArgs.slice();
- for (var i = 0; i < arguments.length; ++i) {
- innerArgs.push(arguments[i]);
- }
- return func.apply(this, innerArgs);
- }
-}
-
-/**
- * Gets the URI in which the current page is located, omitting the file name.
- * @return {string} The base URI of the page. If the page is
- * "http://some.com/folder/somepage.html" returns
- * "http://some.com/folder/".
- */
-o3djs.util.getCurrentURI = function() {
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- return path.substring(0, index + 1);
-};
-
-/**
- * Given a URI that is relative to the current page, returns the absolute
- * URI.
- * @param {string} uri URI relative to the current page.
- * @return {string} Absolute uri. If the page is
- * "http://some.com/folder/sompage.html" and you pass in
- * "images/someimage.jpg" will return
- * "http://some.com/folder/images/someimage.jpg".
- */
-o3djs.util.getAbsoluteURI = function(uri) {
- return o3djs.util.getCurrentURI() + uri;
-};
-
-/**
- * Searches an array for a specific value.
- * @param {!Array.<*>} array Array to search.
- * @param {*} value Value to search for.
- * @return {boolean} True if value is in array.
- */
-o3djs.util.arrayContains = function(array, value) {
- for (var i = 0; i < array.length; i++) {
- if (array[i] == value) {
- return true;
- }
- }
- return false;
-};
-
-/**
- * Searches for all transforms with a "o3d.tags" ParamString
- * that contains specific tag keywords assuming comma separated
- * words.
- * @param {!o3d.Transform} treeRoot Root of tree to search for tags.
- * @param {string} searchTags Tags to look for. eg "camera", "ogre,dragon".
- * @return {!Array.<!o3d.Transform>} Array of transforms.
- */
-o3djs.util.getTransformsInTreeByTags = function(treeRoot, searchTags) {
- var splitTags = searchTags.split(',');
- var transforms = treeRoot.getTransformsInTree();
- var found = [];
- for (var n = 0; n < transforms.length; n++) {
- var tagParam = transforms[n].getParam('collada.tags');
- if (tagParam) {
- var tags = tagParam.value.split(',');
- for (var t = 0; t < tags.length; t++) {
- if (o3djs.util.arrayContains(splitTags, tags[t])) {
- found[found.length] = transforms[n];
- break;
- }
- }
- }
- }
- return found;
-};
-
-/**
- * Finds transforms in the tree by prefix.
- * @param {!o3d.Transform} treeRoot Root of tree to search.
- * @param {string} prefix Prefix to look for.
- * @return {!Array.<!o3d.Transform>} Array of transforms matching prefix.
- */
-o3djs.util.getTransformsInTreeByPrefix = function(treeRoot, prefix) {
- var found = [];
- var transforms = treeRoot.getTransformsInTree();
- for (var ii = 0; ii < transforms.length; ii++) {
- var transform = transforms[ii];
- if (transform.name.indexOf(prefix) == 0) {
- found[found.length] = transform;
- }
- }
- return found;
-};
-
-/**
- * Finds the bounding box of all primitives in the tree, in the local space of
- * the tree root. This will use existing bounding boxes on transforms and
- * elements, but not create new ones.
- * @param {!o3d.Transform} treeRoot Root of tree to search.
- * @return {!o3d.BoundingBox} The boundinding box of the tree.
- */
-o3djs.util.getBoundingBoxOfTree = function(treeRoot) {
- // If we already have a bounding box, use that one.
- var box = treeRoot.boundingBox;
- if (box.valid) {
- return box;
- }
- var o3d = o3djs.base.o3d;
- // Otherwise, create it as the union of all the children bounding boxes and
- // all the shape bounding boxes.
- var transforms = treeRoot.children;
- for (var i = 0; i < transforms.length; ++i) {
- var transform = transforms[i];
- var childBox = o3djs.util.getBoundingBoxOfTree(transform);
- if (childBox.valid) {
- // transform by the child local matrix.
- childBox = childBox.mul(transform.localMatrix);
- if (box.valid) {
- box = box.add(childBox);
- } else {
- box = childBox;
- }
- }
- }
- var shapes = treeRoot.shapes;
- for (var i = 0; i < shapes.length; ++i) {
- var elements = shapes[i].elements;
- for (var j = 0; j < elements.length; ++j) {
- var elementBox = elements[j].boundingBox;
- if (!elementBox.valid) {
- elementBox = elements[j].getBoundingBox(0);
- }
- if (box.valid) {
- box = box.add(elementBox);
- } else {
- box = elementBox;
- }
- }
- }
- return box;
-};
-
-/**
- * Returns the smallest power of 2 that is larger than or equal to size.
- * @param {number} size Size to get power of 2 for.
- * @return {number} smallest power of 2 that is larger than or equal to size.
- */
-o3djs.util.getPowerOfTwoSize = function(size) {
- var powerOfTwo = 1;
- size = size - 1;
- while (size) {
- size = size >> 1;
- powerOfTwo = powerOfTwo << 1;
- }
- return powerOfTwo;
-};
-
-/**
- * Gets the version of the installed plugin.
- * @return {?string} version string in 'major.minor.revision.build' format.
- * If the plugin does not exist returns null.
- */
-o3djs.util.getPluginVersion = function() {
- var version = null;
- var description = null;
- if (navigator.plugins != null && navigator.plugins.length > 0) {
- var plugin = navigator.plugins[o3djs.util.PLUGIN_NAME];
- if (plugin) {
- description = plugin.description;
- }
- } else if (o3djs.base.IsMSIE()) {
- try {
- var activeXObject = new ActiveXObject('o3d_host.O3DHostControl');
- description = activeXObject.description;
- } catch (e) {
- // O3D plugin was not found.
- }
- }
- if (description) {
- var re = /.*version:\s*(\d+)\.(\d+)\.(\d+)\.(\d+).*/;
- // Parse the version out of the description.
- var parts = re.exec(description);
- if (parts && parts.length == 5) {
- // make sure the format is #.#.#.# no whitespace, no trailing comments
- version = '' + parseInt(parts[1], 10) + '.' +
- parseInt(parts[2], 10) + '.' +
- parseInt(parts[3], 10) + '.' +
- parseInt(parts[4], 10);
- }
- }
- return version;
-};
-
-/**
- * Checks if the required version of the plugin in available.
- * @param {string} requiredVersion version string in
- * "major.minor.revision.build" format. You can leave out any non-important
- * numbers for example "3" = require major version 3, "2.4" = require major
- * version 2, minor version 4.
- * @return {boolean} True if the required version is available.
- */
-o3djs.util.requiredVersionAvailable = function(requiredVersion) {
- var version = o3djs.util.getPluginVersion();
- if (!version) {
- return false;
- }
- var haveParts = version.split('.');
- var requiredParts = requiredVersion.split('.');
- if (requiredParts.length > 4) {
- throw Error('requiredVersion has more than 4 parts!');
- }
- for (var pp = 0; pp < requiredParts.length; ++pp) {
- var have = parseInt(haveParts[pp], 10);
- var required = parseInt(requiredParts[pp], 10);
- if (have < required) {
- return false;
- }
- if (have > required) {
- return true;
- }
- }
- return true;
-};
-
-/**
- * Gets all the elements of a certain tag that have a certain id.
- * @param {string} tag The tag to look for. (eg. 'div').
- * @param {string} id The id to look for. This can be a regular expression.
- * @return {!Array.<!Element>} An array of the elements found.
- */
-o3djs.util.getElementsByTagAndId = function(tag, id) {
- var elements = [];
- var allElements = document.getElementsByTagName(tag);
- for (var ee = 0; ee < allElements.length; ++ee) {
- var element = allElements[ee];
- if (element.id && element.id.match(id)) {
- elements.push(element);
- }
- }
- return elements;
-};
-
-/**
- * Gets all the Elements that contain or would contain O3D plugin objects.
- * @param {string} opt_id The id to look for. This can be a regular
- * expression. The default is "^o3d".
- * @param {string} opt_tag The type of tag to look for. The default is "div".
- */
-o3djs.util.getO3DContainerElements = function(opt_id, opt_tag) {
- var tag = opt_tag || 'div';
- var id = opt_id || '^o3d';
- return o3djs.util.getElementsByTagAndId(tag, id);
-}
-
-/**
- * Offers the user the option to download the plugin.
- *
- * Finds all divs with the id "^o3d" and inserts a message and link
- * inside to download the plugin. If no areas exist OR if none of them are
- * large enough for the message then displays an alert.
- *
- * @param {string} opt_id The id to look for. This can be a regular
- * expression. The default is "^o3d".
- * @param {string} opt_tag The type of tag to look for. The default is "div".
- */
-o3djs.util.offerPlugin = function(opt_id, opt_tag) {
- var havePlugin = o3djs.util.requiredVersionAvailable('');
- var elements = o3djs.util.getO3DContainerElements(opt_id, opt_tag);
- var addedMessage = false;
- // TODO: This needs to be localized OR we could insert a html like
- // <script src="http://google.com/o3d_plugin_dl"></script>
- // in which case google could serve the message localized and update the
- // link.
- var subMessage =
- (havePlugin ?
- 'This page requires a newer version of the O3D plugin.' :
- 'This page requires the O3D plugin to be installed.');
- var message =
- '<div style="background: lightblue; width: 100%; height: 100%; ' +
- 'text-align:center;">' +
- '<br/><br/>' + subMessage + '<br/>' +
- '<a href="' + o3djs.util.PLUGIN_DOWNLOAD_URL +
- '">Click here to download.</a>' +
- '</div>'
- for (var ee = 0; ee < elements.length; ++ee) {
- var element = elements[ee];
- if (element.clientWidth >= o3djs.util.MINIMUM_WIDTH_FOR_MESSAGE &&
- element.clientHeight >= o3djs.util.MINIMUM_HEIGHT_FOR_MESSAGE &&
- element.style.display.toLowerCase() != 'none' &&
- element.style.visibility.toLowerCase() != 'hidden') {
- addedMessage = true;
- element.innerHTML = message;
- }
- }
- if (!addedMessage) {
- if (confirm(subMessage + '\n\nClick OK to download.')) {
- window.location = o3djs.util.PLUGIN_DOWNLOAD_URL;
- }
- }
-};
-
-/**
- * Tells the user their graphics card is not able to run the plugin or is out
- * of resources etc.
- *
- * Finds all divs with the id "^o3d" and inserts a message. If no areas
- * exist OR if none of them are large enough for the message then displays an
- * alert.
- *
- * @param {!o3d.Renderer.InitStatus} initStatus The initializaion status of
- * the renderer.
- * @param {string} error An error message. Will be '' if there is no message.
- * @param {string} opt_id The id to look for. This can be a regular
- * expression. The default is "^o3d".
- * @param {string} opt_tag The type of tag to look for. The default is "div".
- */
-o3djs.util.informNoGraphics = function(initStatus, error, opt_id, opt_tag) {
- var elements = o3djs.util.getO3DContainerElements(opt_id, opt_tag);
- var addedMessage = false;
- var subMessage;
- var message;
- var alertMessage = '';
- var alertFunction = function() { };
-
- var moreInfo = function(error) {
- var html = '';
- if (error.length > 0) {
- html = '' +
- '<br/><br/><div>More Info:<br/>' + error + '</div>';
- }
- return html;
- };
-
- // TODO: This needs to be localized OR we could insert a html like
- // <script src="http://google.com/o3d_plugin_dl"></script>
- // in which case google could serve the message localized and update the
- // link.
- if (initStatus == o3djs.util.rendererInitStatus.GPU_NOT_UP_TO_SPEC) {
- subMessage =
- 'We are terribly sorry but it appears your graphics card is not ' +
- 'able to run o3d. We are working on a solution.';
- message =
- '<div style="background: lightgray; width: 100%; height: 100%; ' +
- 'text-align: center;">' +
- '<br/><br/>' + subMessage +
- '<br/><br/><a href="' + o3djs.util.PLUGIN_DOWNLOAD_URL +
- '">Click Here to go the O3D website</a>' +
- moreInfo(error) +
- '</div>';
- alertMessage = '\n\nClick OK to go to the o3d website.';
- alertFunction = function() {
- window.location = o3djs.util.PLUGIN_DOWNLOAD_URL;
- };
- } else if (initStatus == o3djs.util.rendererInitStatus.OUT_OF_RESOURCES) {
- subMessage =
- 'Your graphics system appears to be out of resources. Try closing ' +
- 'some applications and then refreshing this page.';
- message =
- '<div style="background: lightgray; width: 100%; height: 100%; ' +
- 'text-align: center;">' +
- '<br/><br/>' + subMessage +
- moreInfo(error) +
- '</div>';
- } else {
- subMessage =
- 'A unknown error has prevented O3D from starting. Try downloading ' +
- 'new drivers or checking for OS updates.';
- message =
- '<div style="background: lightgray; width: 100%; height: 100%; ' +
- 'text-align: center;">' +
- '<br/><br/>' + subMessage +
- moreInfo(error) +
- '</div>';
- }
- for (var ee = 0; ee < elements.length; ++ee) {
- var element = elements[ee];
- if (element.clientWidth >= o3djs.util.MINIMUM_WIDTH_FOR_MESSAGE &&
- element.clientHeight >= o3djs.util.MINIMUM_HEIGHT_FOR_MESSAGE &&
- element.style.display.toLowerCase() != 'none' &&
- element.style.visibility.toLowerCase() != 'hidden') {
- addedMessage = true;
- element.innerHTML = message;
- }
- }
- if (!addedMessage) {
- if (confirm(subMessage + alertMessage)) {
- alertFunction();
- }
- }
-};
-
-/**
- * Handles failure to create the plugin.
- *
- * @param {!o3d.Renderer.InitStatus} initStatus The initializaion status of
- * the renderer.
- * @param {string} error An error message. Will be '' if there is no message.
- * @param {string} opt_id The id to look for. This can be a regular
- * expression. The default is "^o3d".
- * @param {string} opt_tag The type of tag to look for. The default is "div".
- */
-o3djs.util.informPluginFailure = function(initStatus, error, opt_id, opt_tag) {
- if (initStatus == o3djs.util.rendererInitStatus.NO_PLUGIN) {
- o3djs.util.offerPlugin(opt_id, opt_tag);
- } else {
- o3djs.util.informNoGraphics(initStatus, error, opt_id, opt_tag);
- }
-};
-
-/**
- * Utility to get the text contents of a DOM element with a particular ID.
- * Currently only supports textarea and script nodes.
- * @param {string} id The Node id.
- * @return {string} The text content.
- */
-o3djs.util.getElementContentById = function(id) {
- // DOM manipulation is not currently supported in IE.
- o3djs.BROWSER_ONLY = true;
-
- var node = document.getElementById(id);
- if (!node) {
- throw 'getElementContentById could not find node with id ' + id;
- }
- switch (node.tagName) {
- case 'TEXTAREA':
- return node.value;
- case 'SCRIPT':
- return node.text;
- default:
- throw 'getElementContentById does not no how to get content from a ' +
- node.tagName + ' element';
- }
-};
-
-/**
- * Utility to get an element from the DOM by ID. This must be used from V8
- * in preference to document.getElementById because we do not currently
- * support invoking methods on DOM objects in IE.
- * @param {string} id The Element id.
- * @return {Element} The Element or null if not found.
- */
-o3djs.util.getElementById = function(id) {
- o3djs.BROWSER_ONLY = true;
- return document.getElementById(id);
-};
-
-/**
- * Identifies a JavaScript engine.
- * @enum {number}
- */
-o3djs.util.Engine = {
- /**
- * The JavaScript engine provided by the browser.
- */
- BROWSER: 0,
- /**
- * The V8 JavaScript engine embedded in the plugin.
- */
- V8: 1
-};
-
-/**
- * The engine selected as the main engine (the one the makeClients callback
- * will be invoked on).
- * @private
- * @type {o3djs.util.Engine}
- */
-o3djs.util.mainEngine_ = o3djs.util.Engine.BROWSER;
-
-/**
- * Checks the user agent string for substring s, returning true if it appears.
- * @return {boolean} Whether the browser's user-agent string contains string s.
- */
-function o3djs_navHas(s) {
- return navigator.userAgent.indexOf(s) != -1;
-}
-
-/**
- * Checks for V8 support. This is to cope with environments where our V8 is
- * known to be problematic, eg Safari on 10.6.
- * @return {boolean} Whether the environment supports V8.
- */
-function o3djs_isV8Supported() {
- if (o3djs_navHas('Chrome'))
- return true;
- if (!o3djs_navHas('Safari'))
- return true;
- return !o3djs_navHas('Intel Mac OS X 10_6');
-}
-
-/**
- * Select an engine to use as the main engine (the one the makeClients
- * callback will be invoked on). If an embedded engine is requested, one
- * element must be identified with the id 'o3d'. The callback will be invoked
- * in this element.
- * Ignores attempts to choose V8 if it is not supported in this host.
- * @param {o3djs.util.Engine} engine The engine.
- */
-o3djs.util.setMainEngine = function(engine) {
- if ((engine == o3djs.util.Engine.V8) && !o3djs_isV8Supported()) {
- engine = o3djs.util.Engine.BROWSER;
- }
- o3djs.util.mainEngine_ = engine;
-};
-
-/**
- * A regex used to cleanup the string representation of a function before
- * it is evaled.
- * @private
- * @type {!RegExp}
- */
-o3djs.util.fixFunctionString_ = /^\s*function\s+[^\s]+\s*\(([^)]*)\)/
-
-/**
- * Evaluate a callback function in the V8 engine.
- * @param {!Object} clientElement The plugin containing the V8 engine.
- * @param {!function(...): *} callback A function to call.
- * @param {!Object} thisArg The value to be bound to "this".
- * @param {!Array.<*>} args The arguments to pass to the callback.
- * @return {*} The result of calling the callback.
- */
-o3djs.util.callV8 = function(clientElement, callback, thisArg, args) {
- // Sometimes a function will be converted to a string like this:
- // function foo(a, b) { ... }
- // In this case, convert to this form:
- // function(a, b) { ... }
- var functionString = callback.toString();
- functionString = functionString.replace(o3djs.util.fixFunctionString_,
- 'function($1)');
-
- // Make a V8 function that will invoke the callback.
- var v8Code =
- 'function(thisArg, args) {\n' +
- ' var localArgs = [];\n' +
- ' var numArgs = args.length;\n' +
- ' for (var i = 0; i < numArgs; ++i) {\n' +
- ' localArgs.push(args[i]);\n' +
- ' }\n' +
- ' var func = ' + functionString + ';\n' +
- ' return func.apply(thisArg, localArgs);\n' +
- '}\n';
-
- // Evaluate the function in V8.
- var v8Function = clientElement.eval(v8Code);
- return v8Function(thisArg, args);
-};
-
-/**
- * A regex to remove .. from a URI.
- * @private
- * @type {!RegExp}
- */
-o3djs.util.stripDotDot_ = /\/[^\/]+\/\.\./;
-
-/**
- * Turn a URI into an absolute URI.
- * @param {string} uri The URI.
- * @return {string} The absolute URI.
- */
-o3djs.util.toAbsoluteUri = function(uri) {
- if (uri.indexOf('://') == -1) {
- var baseUri = document.location.toString();
- var lastSlash = baseUri.lastIndexOf('/');
- if (lastSlash != -1) {
- baseUri = baseUri.substring(0, lastSlash);
- }
- uri = baseUri + '/' + uri;
- }
-
- do {
- var lastUri = uri;
- uri = uri.replace(o3djs.util.stripDotDot_, '');
- } while (lastUri !== uri);
-
- return uri;
-};
-
-/**
- * The script URIs.
- * @private
- * @type {!Array.<string>}
- */
-o3djs.util.scriptUris_ = [];
-
-/**
- * Add a script URI. Scripts that are referenced from script tags that are
- * within this URI are automatically loaded into the alternative JavaScript
- * main JavaScript engine. Do not include directories of scripts that are
- * included with o3djs.require. These are always available. This mechanism
- * is not able to load scripts in a different domain from the document.
- * @param {string} uri The URI.
- */
-o3djs.util.addScriptUri = function(uri) {
- o3djs.util.scriptUris_.push(o3djs.util.toAbsoluteUri(uri));
-};
-
-/**
- * Determine whether a URI is a script URI that should be loaded into the
- * alternative main JavaScript engine.
- * @param {string} uri The URI.
- * @return {boolean} Whether it is a script URI.
- */
-o3djs.util.isScriptUri = function(uri) {
- uri = o3djs.util.toAbsoluteUri(uri);
- for (var i = 0; i < o3djs.util.scriptUris_.length; ++i) {
- var scriptUri = o3djs.util.scriptUris_[i];
- if (uri.substring(0, scriptUri.length) === scriptUri) {
- return true;
- }
- }
- return false;
-};
-
-/**
- * Returns whether or not this is a script tag we want. Currently that is
- * only script tags with an id that starts with "o3d".
- * @private
- * @param {!Element} scriptElement The script element to check.
- * @return {boolean} True if we want this script tag.
- */
-o3djs.util.isWantedScriptTag_ = function(scriptElement) {
- return scriptElement.id && scriptElement.id.match(/^o3dscript/);
-};
-
-/**
- * Concatenate the text of all the script tags in the document and invokes
- * the callback when complete. This function is asynchronous if any of the
- * script tags reference JavaScript through a URI.
- * @private
- * @return {string} The script tag text.
- */
-o3djs.util.getScriptTagText_ = function() {
- var scriptTagText = '';
- var scriptElements = document.getElementsByTagName('script');
- for (var i = 0; i < scriptElements.length; ++i) {
- var scriptElement = scriptElements[i];
- if (scriptElement.type === '' ||
- scriptElement.type === 'text/javascript') {
- if ('text' in scriptElement && scriptElement.text &&
- o3djs.util.isWantedScriptTag_(scriptElement)) {
- scriptTagText += scriptElement.text;
- }
- if ('src' in scriptElement && scriptElement.src &&
- o3djs.util.isScriptUri(scriptElement.src)) {
- // It would be better to make this an asynchronous load but the script
- // file is very likely to be in the browser cache because it should
- // have just been loaded via the browser script tag.
- scriptTagText += o3djs.io.loadTextFileSynchronous(scriptElement.src);
- }
- }
- }
- return scriptTagText;
-};
-
-/**
- * Creates a client element. In other words it creates an <OBJECT> tag for o3d.
- * <b>Note that the browser may not have initialized the plugin before
- * returning.</b>
- * @param {!Element} element The DOM element under which the client element
- * will be appended.
- * @param {string} opt_features A comma separated list of the
- * features you need for your application. The current list of features:
- * <li>FloatingPointTextures: Includes the formats R32F, ABGR16F and
- * ABGR32F</li>
- * The features are case sensitive.
- * @param {string} opt_requestVersion version string in
- * "major.minor.revision.build" format. You can leave out any non-important
- * numbers for example "3" = request major version 3, "2.4" = request major
- * version 2, minor version 4. If no string is passed in the newest version
- * of the plugin will be created.
- * @return {Element} O3D element or null if requested version is not
- * available.
- */
-o3djs.util.createClient = function(element, opt_features, opt_requestVersion) {
- opt_features = opt_features || '';
- opt_requestVersion = opt_requestVersion || o3djs.util.REQUIRED_VERSION;
- if (!o3djs.util.requiredVersionAvailable(opt_requestVersion)) {
- return null;
- }
- opt_features += (opt_features ? ',' : '') + 'APIVersion=' +
- opt_requestVersion;
- var objElem;
- // TODO: Use opt_requiredVersion to set a version so the plugin
- // can make sure it offers that version of the API.
- // Note: The IE version of the plug-in does not receive attributes during
- // construction, unless the innerHTML construction style is used.
- if (o3djs.base.IsMSIE()) {
- element.innerHTML =
- '<OBJECT ' +
- 'WIDTH="100%" HEIGHT="100%"' +
- 'CLASSID="CLSID:9666A772-407E-4F90-BC37-982E8160EB2D">' +
- '<PARAM name="o3d_features" value="' + opt_features + '"/>' +
- '</OBJECT>';
- objElem = element.childNodes[0];
- } else {
- objElem = document.createElement('object');
- objElem.type = 'application/vnd.o3d.auto';
- objElem.style.width = '100%';
- objElem.style.height = '100%';
- objElem.setAttribute('o3d_features', opt_features);
- element.appendChild(objElem);
- }
-
- if (objElem.client.clientInfo.glsl) {
- o3djs.effect.setLanguage('glsl');
- }
-
- return objElem;
-};
-
-/**
- * Finds all divs with the an id that starts with "o3d" and inserts a client
- * area inside.
- *
- * NOTE: the size of the client area is always set to 100% which means the div
- * must have its size set or managed by the browser. Examples:
- *
- * -- A div of a specific size --
- * &lt;div id="o3d" style="width:800px; height:600px">&lt;/div>
- *
- * -- A div that fills its containing element --
- * &lt;div id="o3d" style="width:100%; height:100%">&lt;/div>
- *
- * In both cases, a DOCTYPE is probably required.
- *
- * You can also request certain features by adding the attribute
- * 'o3d_features' as in
- *
- * &lt;div id="o3d" o3d_features="FloatingPointTextures">&lt;/div>
- *
- * This allows you to specify different features per area. Otherwise you can
- * request features as an argument to this function.
- *
- * Normally this function handles failure for you but if you want to handle
- * failure in your own way you can supply a failure callback. Here is an example
- * of using this function with your own failure callback.
- *
- * <pre>
- * &lt;script type="text/javascript" id="o3dscript"&gt;
- * o3djs.require('o3djs.util');
- *
- * window.onload = init;
- *
- * function init() {
- * o3djs.util.makeClients(onSuccess, '', undefined, onFailure);
- * }
- *
- * function onFailure(initStatus, error, id, tag) {
- * // Get a list of the elements that would have had an O3D plugin object
- * // inserted if it had succeed.
- * var elements = o3djs.util.getO3DContainerElements(id, tag);
- *
- * switch (initStatus) {
- * case o3djs.util.rendererInitStatus.NO_PLUGIN:
- * // Tell the user there is no plugin
- * ...
- * break;
- * case o3djs.util.rendererInitStatus.OUT_OF_RESOURCES:
- * case o3djs.util.rendererInitStatus.GPU_NOT_UP_TO_SPEC:,
- * case o3djs.util.rendererInitStatus.INITIALIZATION_ERROR:
- * default:
- * // Tell the user there are other issues
- * ...
- * break;
- * }
- * }
- *
- * function onSuccess(o3dElementsArray) {
- * // Run your app.
- * ...
- * }
- * &lt;/script&gt;
- * </pre>
- *
- * @param {!function(Array.<!Element>): void} callback Function to call when
- * client objects have been created.
- * @param {string} opt_features A comma separated list of the
- * features you need for your application. The current list of features:
- *
- * <li>FloatingPointTextures: Includes the formats R32F, ABGR16F and
- * ABGR32F</li>
- * <li>LargeGeometry: Allows buffers to have more than 65534 elements.</li>
- * <li>NotAntiAliased: Turns off anti-aliasing</li>
- * <li>InitStatus=X: Where X is a number. Allows simulatation of the plugin
- * failing</li>
- *
- * The features are case sensitive.
- * @param {string} opt_requiredVersion version string in
- * "major.minor.revision.build" format. You can leave out any
- * non-important numbers for example "3" = require major version 3,
- * "2.4" = require major version 2, minor version 4. If no string is
- * passed in the version of the needed by this version of the javascript
- * libraries will be created.
- * @param {!function(!o3d.Renderer.InitStatus, string, (string|undefined),
- * (string|undefined)): void} opt_failureCallback Function to call if the
- * plugin does not exist, if the required version is not installed, or if
- * for some other reason the plugin can not start. If this function is not
- * specified or is null the default behavior of leading the user to the
- * download page will be provided. See o3djs.util.informPluginFailure for an
- * example of this type of callback.
- * @param {string} opt_id The id to look for. This can be a regular
- * expression. The default is "^o3d".
- * @param {string} opt_tag The type of tag to look for. The default is "div".
- * @see o3djs.util.informPluginFailure
- */
-o3djs.util.makeClients = function(callback,
- opt_features,
- opt_requiredVersion,
- opt_failureCallback,
- opt_id,
- opt_tag) {
- opt_failureCallback = opt_failureCallback || o3djs.util.informPluginFailure;
- opt_requiredVersion = opt_requiredVersion || o3djs.util.REQUIRED_VERSION;
- if (!o3djs.util.requiredVersionAvailable(opt_requiredVersion)) {
- opt_failureCallback(o3djs.util.rendererInitStatus.NO_PLUGIN, '',
- opt_id, opt_tag);
- } else {
- var clientElements = [];
- var elements = o3djs.util.getO3DContainerElements(opt_id, opt_tag);
- var mainClientElement = null;
- for (var ee = 0; ee < elements.length; ++ee) {
- var element = elements[ee];
- var features = opt_features;
- if (!features) {
- var o3d_features = element.getAttribute('o3d_features');
- if (o3d_features) {
- features = o3d_features;
- } else {
- features = '';
- }
- }
-
- var objElem = o3djs.util.createClient(element, features);
- clientElements.push(objElem);
-
- // If the callback is to be invoked in an embedded JavaScript engine,
- // one element must be identified with the id 'o3d'. This callback
- // will be invoked in the element identified as such.
- if (element.id === 'o3d') {
- mainClientElement = objElem;
- }
- }
-
- // Wait for the browser to initialize the clients.
- var clearId = window.setInterval(function() {
- var initStatus = 0;
- var error = '';
- var o3d;
- for (var cc = 0; cc < clientElements.length; ++cc) {
- var element = clientElements[cc];
- o3d = element.o3d;
- var ready = o3d &&
- element.client &&
- element.client.rendererInitStatus >
- o3djs.util.rendererInitStatus.UNINITIALIZED;
- if (!ready) {
- return;
- }
- var status = clientElements[cc].client.rendererInitStatus;
- // keep the highest status. This is the worst status.
- if (status > initStatus) {
- initStatus = status;
- error = clientElements[cc].client.lastError;
- }
- }
-
- window.clearInterval(clearId);
-
- // If the plugin could not initialize the graphics delete all of
- // the plugin objects
- if (initStatus > 0 && initStatus != o3d.Renderer.SUCCESS) {
- for (var cc = 0; cc < clientElements.length; ++cc) {
- var clientElement = clientElements[cc];
- clientElement.parentNode.removeChild(clientElement);
- }
- opt_failureCallback(initStatus, error, opt_id, opt_tag);
- } else {
- o3djs.base.snapshotProvidedNamespaces();
-
- // TODO: Is this needed with the new event code?
- for (var cc = 0; cc < clientElements.length; ++cc) {
- // Based on v8 support test, not on current engine, as V8
- // still needs to be initialized even with o3djs.util.Engine.BROWSER
- // on some configs.
- if (o3djs_isV8Supported())
- o3djs.base.initV8(clientElements[cc]);
- o3djs.event.startKeyboardEventSynthesis(clientElements[cc]);
- o3djs.error.setDefaultErrorHandler(clientElements[cc].client);
- }
- o3djs.base.init(clientElements[0]);
-
- switch (o3djs.util.mainEngine_) {
- case o3djs.util.Engine.BROWSER:
- callback(clientElements);
- break;
- case o3djs.util.Engine.V8:
- if (!mainClientElement) {
- throw 'V8 engine was requested but there is no element with' +
- ' the id "o3d"';
- }
-
- // Retreive the code from the script tags and eval it in V8 to
- // duplicate the browser environment.
- var scriptTagText = o3djs.util.getScriptTagText_();
- mainClientElement.eval(scriptTagText);
-
- // Invoke the callback in V8.
- o3djs.util.callV8(mainClientElement,
- callback,
- o3djs.global,
- [clientElements]);
- break;
- default:
- throw 'Unknown engine ' + o3djs.util.mainEngine_;
- }
- }
- }, 10);
- }
-};
-
diff --git a/o3d/samples/o3djs/webgl.js b/o3d/samples/o3djs/webgl.js
deleted file mode 100644
index b7c4111..0000000
--- a/o3d/samples/o3djs/webgl.js
+++ /dev/null
@@ -1,283 +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.
- */
-
-
-/**
- * @fileoverview This file contains utility functions for o3d running on
- * top of webgl. The function o3djs.webgl.makeClients replaces the
- * function o3djs.util.makeClients.
- */
-
-o3djs.provide('o3djs.webgl');
-
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.util');
-
-
-/**
- * A Module with various utilities.
- * @namespace
- */
-o3djs.webgl = o3djs.webgl || {};
-
-
-/**
- * Takes a javascript object containing name-value pairs of options to
- * makeClients or createClient and adds options to the default value if they
- * aren't already there setting them to the default value.
- * @param {Object} The obejct containing options.
- */
-o3djs.webgl.setUndefinedOptionsToDefaults_ = function(options) {
- /**
- * Whether to install debugging functions, and selectable
- * @type {boolean}
- */
- options.debug = options.debug || false;
-
- /**
- * Whether to allow the canvas object created to remain selectable.
- * @type {boolean}
- */
- options.selectable = options.selectable || false;
-};
-
-
-/**
- * Finds all divs with an id that starts with "o3d" and inits a canvas
- * under them with o3d client object and the o3d namespace.
- * @param {!function(Array.<!Element>): void} callback Function to call when
- * client objects have been created.
- * @param {Object} opt_options An object mapping various options to their values
- * See comment for o3djs.webgl.setUndefinedOptionsToDefaults_ to see what
- * options there are.
- * @param {string} opt_requiredVersion Ignored in o3d-webgl.
- * @param {!function(!o3d.Renderer.InitStatus, string, (string|undefined),
- * (string|undefined)): void} opt_failureCallback Called with an error
- * string if the client fails to create.
- * @param {string} opt_id The id to look for. This can be a regular
- * expression. The default is "^o3d".
- * @param {string} opt_tag The type of tag to look for. The default is "div".
- * @see o3djs.util.informPluginFailure
- */
-o3djs.webgl.makeClients = function(callback,
- opt_options,
- opt_requiredVersion,
- opt_failureCallback,
- opt_id,
- opt_tag) {
- opt_failureCallback = opt_failureCallback || o3djs.util.informPluginFailure;
- var options = opt_options;
-
- // If opt_options is a string, we assume it's coming from formerly plugin
- // code and ignore it. If it's an object, we assume it's the name-value-pair
- // object describing the optional arguments to this function.
- if (options == undefined || typeof options == 'string') {
- options = {};
- }
- o3djs.webgl.setUndefinedOptionsToDefaults_(options);
-
- var clientElements = [];
- var elements = o3djs.util.getO3DContainerElements(opt_id, opt_tag);
-
- for (var ee = 0; ee < elements.length; ++ee) {
- var element = elements[ee];
- var objElem = o3djs.webgl.createClient(element, options, options.debug);
- if (!objElem) {
- opt_failureCallback('Failed to create o3d-webgl client object.');
- return;
- }
- clientElements.push(objElem);
- }
-
- // Wait for the client elements to be fully initialized. This
- // involves waiting for the page to fully layout and the initial
- // resize event to be processed.
- var clearId = window.setInterval(function() {
- for (var cc = 0; cc < clientElements.length; ++cc) {
- var element = clientElements[cc];
- if (!element.sizeInitialized_) {
- return;
- }
- }
- window.clearInterval(clearId);
- callback(clientElements);
- });
-};
-
-
-/**
- * Adds a wrapper object to single gl function context that checks for errors
- * before the call.
- * @param {WebGLContext} context
- * @param {string} fname The name of the function.
- * @return {}
- */
-o3djs.webgl.createGLErrorWrapper = function(context, fname) {
- return function() {
- var rv = context[fname].apply(context, arguments);
- var err = context.getError();
- if (err != 0) {
- throw "GL error " + err + " in " + fname;
- }
- return rv;
- };
-};
-
-
-/**
- * Adds a wrapper object to a webgl context that checks for errors
- * before each function call.
- */
-o3djs.webgl.addDebuggingWrapper = function(context) {
- // Thanks to Ilmari Heikkinen for the idea on how to implement this
- // so elegantly.
- var wrap = {};
- for (var i in context) {
- if (typeof context[i] == 'function') {
- wrap[i] = o3djs.webgl.createGLErrorWrapper(context, i);
- } else {
- wrap[i] = context[i];
- }
- }
- wrap.getError = function() {
- return context.getError();
- };
- return wrap;
-};
-
-
-/**
- * Inserts text indicating that a WebGL context could not be created under
- * the given node and links to the site about WebGL capable browsers.
- */
-o3djs.webgl.webGlCanvasError = function(parentNode, unavailableElement) {
- var background = document.createElement('div');
- background.style.backgroundColor = '#ccffff';
- background.style.textAlign = 'center';
- background.style.margin = '10px';
- background.style.width = '100%';
- background.style.height = '100%';
-
- var messageHTML = '<br/><br/><a href="http://get.webgl.org">' +
- 'Your browser does not appear to support WebGL.<br/><br/>' +
- 'Check that WebGL is enabled or click here to upgrade your browser:' +
- '</a><br/>';
-
- background.innerHTML = messageHTML;
-
- parentNode.appendChild(background);
-};
-
-
-/**
- * Creates a canvas under the given parent element and an o3d.Client
- * under that.
- *
- * @param {!Element} element The element under which to insert the client.
- * @param {Object} opt_options A javascript object containing
- * @param {boolean} opt_debug Whether gl debugging features should be
- * enabled.
- * @return {HTMLCanvas} The canvas element, or null if initializaton failed.
- */
-o3djs.webgl.createClient = function(element, opt_options, opt_debug) {
- var options = opt_options;
-
- // If opt_options is a string, we assume it's coming from formerly plugin
- // code and ignore it. If it's an object, we assume it's the name-value-pair
- // object describing the optional arguments to this function.
- if (opt_options == undefined || typeof opt_options == 'string') {
- options = {};
- options.debug = opt_debug;
- }
- o3djs.webgl.setUndefinedOptionsToDefaults_(options);
-
- opt_debug = opt_debug || false;
-
- // If we're creating a webgl client, the assumption is we're using webgl,
- // in which case the only acceptable shader language is glsl. So, here
- // we set the shader language to glsl.
- o3djs.effect.setLanguage('glsl');
-
- // Make the canvas automatically resize to fill the containing
- // element (div), and initialize its size correctly.
- var canvas;
- canvas = document.createElement('canvas');
-
- if (!canvas || !canvas.getContext) {
- o3djs.webgl.webGlCanvasError(element, 'HTMLCanvas');
- return null;
- }
-
- canvas.style.width = "100%";
- canvas.style.height = "100%";
-
- var client = new o3d.Client;
-
- var resizeHandler = function() {
- var width = Math.max(1, canvas.clientWidth);
- var height = Math.max(1, canvas.clientHeight);
- canvas.width = width;
- canvas.height = height;
- canvas.sizeInitialized_ = true;
- if (client.gl) {
- client.gl.displayInfo = {width: canvas.width, height: canvas.height};
- }
- };
- window.addEventListener('resize', resizeHandler, false);
- setTimeout(resizeHandler, 0);
-
- if (!client.initWithCanvas(canvas)) {
- o3djs.webgl.webGlCanvasError(element, 'WebGL context');
- return null;
- }
-
- if (!options.selectable) {
- // This keeps the cursor from changing to an I-beam when the user clicks
- // and drags. It's easier on the eyes.
- function returnFalse() {
- return false;
- }
- canvas.onselectstart = returnFalse;
- canvas.onmousedown = returnFalse;
- }
-
- canvas.client = client;
- canvas.o3d = o3d;
-
- if (options.debug) {
- client.gl = o3djs.webgl.addDebuggingWrapper(client.gl);
- }
-
- element.appendChild(canvas);
- return canvas;
-};
-
-
diff --git a/o3d/samples/old-school-shadows.html b/o3d/samples/old-school-shadows.html
deleted file mode 100644
index bcdc7cc..0000000
--- a/o3d/samples/old-school-shadows.html
+++ /dev/null
@@ -1,274 +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 sample shows how to use simple circle texture for shadows.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Old School Shadows.
-</title>
-<link rel="stylesheet" type="text/css" href="assets/style.css" />
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Constants
-var SHADOW_SIZE = 5;
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_globalParams;
-var g_shadowDrawPassInfo;
-var g_o3dWidth;
-var g_o3dHeight;
-var g_o3dElement;
-var g_transforms = [];
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot);
-
- // Make another draw pass just for the shadows so they get
- // drawn last. We don't need to pass any extra info to createDrawPass
- // because we are using the same drawContext and because we want it to
- // happen last, both of which are the default.
- g_shadowDrawPassInfo = g_viewInfo.createDrawPass(
- g_o3d.DrawList.BY_PERFORMANCE);
-
- // Get the state object the shadow draw pass and set states for the shadows.
- var state = g_shadowDrawPassInfo.state;
-
- // The following settings turn on blending for all objects using the
- // shadow DrawList
- state.getStateParam('AlphaBlendEnable').value = true;
- state.getStateParam('SourceBlendFunction').value =
- o3djs.base.o3d.State.BLENDFUNC_SOURCE_ALPHA;
- state.getStateParam('DestinationBlendFunction').value =
- o3djs.base.o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA;
- state.getStateParam('AlphaTestEnable').value = true;
- state.getStateParam('AlphaComparisonFunction').value =
- o3djs.base.o3d.State.CMP_GREATER;
-
- // Make the shadow not write to the ZBuffer, otherwise they will interfere
- // with each other. Try commenting this line out to see what happens. Look
- // closely when 2 shadows overlap. It's easier to see the problem
- // if you make the shadows larger. Set the shadow size to 15
- state.getStateParam('ZWriteEnable').value = false;
-
- // This setting pulls the shadow in front of the ground plane even though
- // they are at the same position in space. Comment this 2 lines out
- // to see what happens if you don't use this setting.
- state.getStateParam('PolygonOffset1').value = -1;
- state.getStateParam('PolygonOffset2').value = -1;
-
- // Setup the view and projection matrices.
- var eye = [15, 25, 50];
- var target = [0, 10, 0];
- var up = [0, 1, 0];
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(eye, target, up);
-
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), // field of view.
- g_client.width / g_client.height, // aspect ratio
- 0.1, // Near plane.
- 5000); // Far plane.
-
- // Load a small circle texture.
- o3djs.io.loadTexture(
- g_pack,
- o3djs.util.getAbsoluteURI('assets/old-school-shadow.png'),
- initStep3);
-}
-
-function initStep3(texture, exception) {
- if (exception) {
- alert(exception);
- return;
- }
-
- // This material is used for the spheres.
- var sphereMaterial = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [1, 1, 1, 1]);
- sphereMaterial.getParam('specularFactor').value = 0.4;
-
- // The material for the ground.
- var checkerMaterial = o3djs.material.createCheckerMaterial(
- g_pack,
- g_viewInfo);
-
- // Make a material to use for the shadow. A standard constant shader will
- // be fine.
- var shadowMaterial = o3djs.material.createConstantMaterial(
- g_pack,
- g_viewInfo,
- texture,
- true);
- shadowMaterial.drawList = g_shadowDrawPassInfo.drawList;
-
- // Setup the lighting for the ground and spheres.
- g_globalParams = o3djs.material.createAndBindStandardParams(g_pack);
- g_globalParams.lightWorldPos.value = [30, 60, 40];
- g_globalParams.lightColor.value = [1, 1, 1, 1];
-
- // Create a ground plane.
- var shape = o3djs.primitives.createPlane(
- g_pack, checkerMaterial, 100, 100, 10, 10);
- var transform = g_pack.createObject('Transform');
- transform.parent = g_root;
- transform.addShape(shape);
-
- // Create a sphere.
- var sphere = o3djs.primitives.createSphere(
- g_pack, sphereMaterial, 2.5, 24, 48,
- g_math.matrix4.translation([0, 2.5, 0]));
-
- // Create a plane for the shadow.
- var shadow = o3djs.primitives.createPlane(g_pack, shadowMaterial,
- SHADOW_SIZE, SHADOW_SIZE, 1, 1);
-
- // Instance 100 spheres with shadows.
- for (var ii = 0; ii < 100; ++ii) {
- var transform = g_pack.createObject('Transform');
- g_transforms.push(transform);
- transform.parent = g_root;
- transform.addShape(sphere);
- // Give each sphere a pseudo random color.
- transform.createParam('diffuse', 'ParamFloat4').value = [
- (ii * 1.71) % 1,
- (ii * 2.09) % 1,
- (ii * 6.31) % 1,
- 1];
- var shadowTransform = g_pack.createObject('Transform');
- shadowTransform.parent = transform;
- shadowTransform.addShape(shadow);
- }
-
- // Setup a render callback for per frame processing.
- g_client.setRenderCallback(onRender);
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- moveThings();
-};
-
-/**
- * Moves all the sphere transforms in some pattern that is a function of
- * g_clock so we can force it to a predictable state for testing.
- */
-function moveThings() {
- for (var ii = 0; ii < g_transforms.length; ++ii) {
- var transform = g_transforms[ii];
- var xSpeed = g_clock * 0.25 + ii * 1.1;
- var ySpeed = g_clock * 0.27 + ii * 0.5;
- transform.identity();
- transform.translate(40 * Math.sin(xSpeed),
- 0,
- 40 * Math.cos(ySpeed));
- var scale = (Math.sin(g_clock * 0.29 + ii * 20.7) + 1) * 0.5 + 0.3;
- transform.scale(scale, scale, scale);
- }
-}
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Old School Shadows</h1>
-<div id="o3d" style="width: 800px; height: 600px"></div>
-</body>
-</html>
diff --git a/o3d/samples/particles.html b/o3d/samples/particles.html
deleted file mode 100644
index bc28344..0000000
--- a/o3d/samples/particles.html
+++ /dev/null
@@ -1,593 +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.
--->
-
-<!--
-Particles.
-
-This example shows using the javascript particle library.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Particles.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.particles');
-o3djs.require('o3djs.loader');
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_particleSystem;
-var g_clockParam;
-var g_textures = [];
-var g_emitters = []; // so we can find in the debugger to edit in real time.
-var g_poofs = [];
-var g_keyDown = [];
-var g_poofIndex = 0;
-var g_trail;
-var g_trailParameters;
-
-var MAX_POOFS = 3;
-
-/**
- * Loads a texture.
- * @param {!o3djs.loader.Loader} loader Loader to use to load texture.
- * @param {string} url relativel url of texture.
- * @param {number} index Index at which to record texture.
- */
-function loadTexture(loader, url, index) {
- loader.loadTexture(
- g_pack,
- o3djs.util.getAbsoluteURI(url),
- function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- g_textures[index] = texture;
- }
- });
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- // These are here so they are shared by both V8 and the browser.
- window.g_finished = false; // for selenium
- window.g_timeMult = 1;
- window.g_clock = 0;
-
- // Comment out the line below to run the sample in the browser JavaScript
- // engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- window.g_client = g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree fov.
- g_client.width / g_client.height,
- 0.1, // Near plane.
- 5000); // Far plane.
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [500, 1000, 1000], // eye
- [0, 200, 0], // target
- [0, 1, 0]); // up
-
- // Load textures. This happens asynchronously.
- var loader = o3djs.loader.createLoader(initStep3);
- loadTexture(loader, 'assets/particle-anim.png', 0);
- loadTexture(loader, 'assets/ripple.png', 1);
- loader.finish();
-}
-
-function initStep3() {
- // Normally we wouldn't pass in a clock and the particle system would handle
- // this for me but for selenium testing we need to be able to control the
- // clock so we're passing in our own clock param.
- var paramObject = g_pack.createObject('ParamObject');
- g_clockParam = paramObject.createParam('clock', 'ParamFloat');
-
- // Normally we wouldn't pass in a random function but for selenium we need
- // the particle system to produce the exact same results each time so
- // we're passing in a predictable random function.
- g_particleSystem = o3djs.particles.createParticleSystem(
- g_pack,
- g_viewInfo,
- g_clockParam,
- g_math.pseudoRandom);
- setupFlame();
- setupNaturalGasFlame();
- setupSmoke();
- setupWhiteEnergy();
- setupGoogle();
- setupRain();
- setupRipples();
- setupAnim();
- setupBall();
- setupCube();
- setupPoof();
- setupTrail();
-
- window.document.onkeypress = onKeyPress;
- window.document.onkeydown = onKeyDown;
- window.document.onkeyup = onKeyUp;
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- window.g_finished = true; // for selenium testing.
-}
-
-function onKeyPress(event) {
- event = event || window.event;
-
- var keyChar = String.fromCharCode(o3djs.event.getEventKeyChar(event));
- // Just in case they have capslock on.
- keyChar = keyChar.toLowerCase();
-
- switch (keyChar) {
- case 'p':
- triggerPoof();
- break;
- }
-}
-
-function onKeyDown(event) {
- event = event || window.event;
- g_keyDown[o3djs.event.getEventKeyChar(event)] = true;
-}
-
-function onKeyUp(event) {
- event = event || window.event;
- g_keyDown[o3djs.event.getEventKeyChar(event)] = false;
-}
-
-function setupFlame() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(-300, 0, 0);
-
- var emitter = g_particleSystem.createParticleEmitter();
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.ADD);
- emitter.setColorRamp(
- [1, 1, 0, 1,
- 1, 0, 0, 1,
- 0, 0, 0, 1,
- 0, 0, 0, 0.5,
- 0, 0, 0, 0]);
- emitter.setParameters({
- numParticles: 20,
- lifeTime: 2,
- timeRange: 2,
- startSize: 50,
- endSize: 90,
- velocity:[0, 60, 0], velocityRange: [15, 15, 15],
- worldAcceleration: [0, -20, 0],
- spinSpeedRange: 4});
- transform.addShape(emitter.shape);
-}
-
-function setupNaturalGasFlame() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(-200, 0, 0);
-
- var emitter = g_particleSystem.createParticleEmitter();
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.ADD);
- emitter.setColorRamp(
- [0.2, 0.2, 1, 1,
- 0, 0, 1, 1,
- 0, 0, 1, 0.5,
- 0, 0, 1, 0]);
- emitter.setParameters({
- numParticles: 20,
- lifeTime: 2,
- timeRange: 2,
- startSize: 50,
- endSize: 20,
- velocity:[0, 60, 0],
- worldAcceleration: [0, -20, 0],
- spinSpeedRange: 4});
- transform.addShape(emitter.shape);
-}
-
-function setupSmoke() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(-100, 0, 0);
-
- var emitter = g_particleSystem.createParticleEmitter();
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.BLEND);
- emitter.setColorRamp(
- [0, 0, 0, 1,
- 0, 0, 0, 0]);
- emitter.setParameters({
- numParticles: 20,
- lifeTime: 2,
- timeRange: 2,
- startSize: 100,
- endSize: 150,
- velocity: [0, 200, 0], velocityRange: [20, 0, 20],
- worldAcceleration: [0, -25, 0],
- spinSpeedRange: 4});
- transform.addShape(emitter.shape);
-}
-
-function setupWhiteEnergy() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(0, 0, 0);
-
- var emitter = g_particleSystem.createParticleEmitter();
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.ADD);
- emitter.setColorRamp(
- [1, 1, 1, 1,
- 1, 1, 1, 0]);
- emitter.setParameters({
- numParticles: 80,
- lifeTime: 2,
- timeRange: 2,
- startSize: 100,
- endSize: 100,
- positionRange: [100, 0, 100],
- velocityRange: [20, 0, 20]});
- transform.addShape(emitter.shape);
-}
-
-function setupRipples() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(-200, 0, 300);
-
- var emitter = g_particleSystem.createParticleEmitter(g_textures[1]);
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.BLEND);
- emitter.setColorRamp(
- [0.7, 0.8, 1, 1,
- 1, 1, 1, 0]);
- emitter.setParameters({
- numParticles: 20,
- lifeTime: 2,
- timeRange: 2,
- startSize: 50,
- endSize: 200,
- positionRange: [100, 0, 100],
- billboard: false});
- transform.addShape(emitter.shape);
-}
-
-function setupGoogle() {
- var image = [
- '.XXXX...XXXXX...XXXXX.',
- 'X....X.......X..X....X',
- 'X....X...XXXXX..X....X',
- 'X....X.......X..X....X',
- '.XXXX...XXXXX...XXXXX.'];
- var height = image.length;
- var width = image[0].length;
-
- // Make an array of positions based on the text image.
- var positions = [];
- for (var yy = 0; yy < height; ++yy) {
- for (var xx = 0; xx < width; ++xx) {
- if (image[yy].substring(xx, xx + 1) == 'X') {
- positions.push([(xx - width * 0.5) * 10,
- -(yy - height * 0.5) * 10]);
- }
- }
- }
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(100, 200, 0);
-
- var emitter = g_particleSystem.createParticleEmitter();
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.ADD);
- emitter.setColorRamp(
- [1, 0, 0, 1,
- 0, 1, 0, 1,
- 0, 0, 1, 1,
- 1, 1, 0, 0]);
- emitter.setParameters({
- numParticles: positions.length * 4,
- lifeTime: 2,
- timeRange: 2,
- startSize: 25,
- endSize: 50,
- positionRange: [2, 0, 2],
- velocity: [1, 0, 1]},
- function(particleIndex, parameters) {
- //var index = particleIndex;
- var index = Math.floor(g_math.pseudoRandom() * positions.length);
- index = Math.min(index, positions.length - 1);
- parameters.position[0] = positions[index][0];
- parameters.position[1] = positions[index][1];
- });
- transform.addShape(emitter.shape);
-}
-
-function setupRain() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(200, 200, 0);
-
- var emitter = g_particleSystem.createParticleEmitter();
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.BLEND);
- emitter.setColorRamp(
- [0.2, 0.2, 1, 1]);
- emitter.setParameters({
- numParticles: 80,
- lifeTime: 2,
- timeRange: 2,
- startSize: 5,
- endSize: 5,
- positionRange: [100, 0, 100],
- velocity: [0,-150,0]});
- transform.addShape(emitter.shape);
-}
-
-function setupAnim(texture) {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(300, 0, 0);
-
- var emitter = g_particleSystem.createParticleEmitter(g_textures[0]);
- g_emitters.push(emitter);
- emitter.setColorRamp(
- [1, 1, 1, 1,
- 1, 1, 1, 1,
- 1, 1, 1, 0]);
- emitter.setParameters({
- numParticles: 20,
- numFrames: 8,
- frameDuration: 0.25,
- frameStartRange: 8,
- lifeTime: 2,
- timeRange: 2,
- startSize: 50,
- endSize: 90,
- positionRange: [10, 10, 10],
- velocity:[0, 200, 0], velocityRange: [75, 15, 75],
- acceleration: [0, -150, 0],
- spinSpeedRange: 1});
- transform.addShape(emitter.shape);
-}
-
-function setupBall() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(-400, 0, -200);
-
- var emitter = g_particleSystem.createParticleEmitter(g_textures[1]);
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.BLEND);
- emitter.setColorRamp(
- [1, 1, 1, 1,
- 1, 1, 1, 0]);
- emitter.setParameters({
- numParticles: 300,
- lifeTime: 2,
- timeRange: 2,
- startSize: 10,
- endSize: 50,
- colorMult: [1, 1, 0.5, 1], colorMultRange: [0, 0, 0.5, 0],
- billboard: false},
- function(particleIndex, parameters) {
- var matrix = g_math.matrix4.rotationY(
- g_math.pseudoRandom() * Math.PI * 2);
- g_math.matrix4.rotateX(matrix, g_math.pseudoRandom() * Math.PI);
- var position = g_math.matrix4.transformDirection(matrix, [0, 100, 0]);
- parameters.position = position;
- parameters.orientation = o3djs.quaternions.rotationToQuaternion(matrix);
- });
- transform.addShape(emitter.shape);
-}
-
-function setupCube() {
- var transform = g_pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.translate(200, 0, -300);
-
- var emitter = g_particleSystem.createParticleEmitter(g_textures[1]);
- g_emitters.push(emitter);
- emitter.setState(o3djs.particles.ParticleStateIds.ADD);
- emitter.setColorRamp(
- [1, 1, 1, 1,
- 0, 0, 1, 1,
- 1, 1, 1, 0]);
- emitter.setParameters({
- numParticles: 300,
- lifeTime: 2,
- timeRange: 2,
- startSize: 10,
- endSize: 50,
- colorMult: [0.8, 0.9, 1, 1],
- billboard: false},
- function(particleIndex, parameters) {
- var matrix = g_math.matrix4.rotationY(
- Math.floor(g_math.pseudoRandom() * 4) * Math.PI * 0.5);
- g_math.matrix4.rotateX(
- matrix,
- Math.floor(g_math.pseudoRandom() * 3) * Math.PI * 0.5);
- parameters.orientation = o3djs.quaternions.rotationToQuaternion(matrix);
- var position = g_math.matrix4.transformDirection(
- matrix,
- [g_math.pseudoRandom() * 200 - 100,
- 100,
- g_math.pseudoRandom() * 200 - 100]);
- parameters.position = position;
- });
- transform.addShape(emitter.shape);
-}
-
-function setupPoof() {
- var emitter = g_particleSystem.createParticleEmitter();
- emitter.setState(o3djs.particles.ParticleStateIds.ADD);
- emitter.setColorRamp(
- [1, 1, 1, 0.3,
- 1, 1, 1, 0]);
- emitter.setParameters({
- numParticles: 30,
- lifeTime: 1.5,
- startTime: 0,
- startSize: 50,
- endSize: 200,
- spinSpeedRange: 10},
- function(index, parameters) {
- var angle = Math.random() * 2 * Math.PI;
- parameters.velocity = g_math.matrix4.transformPoint(
- g_math.matrix4.rotationY(angle), [300, 0, 0]);
- parameters.acceleration = g_math.mulVectorVector(
- parameters.velocity, [-0.3, 0, -0.3]);
- });
- // make 3 poofs one shots
- for (var ii = 0; ii < MAX_POOFS; ++ii) {
- g_poofs[ii] = emitter.createOneShot(g_client.root);
- }
-}
-
-function triggerPoof() {
- // We have multiple poofs because if you only have one and it is still going
- // when you trigger it a second time it will immediately start over.
- g_poofs[g_poofIndex].trigger([100 + 100 * g_poofIndex, 0, 300]);
- g_poofIndex++;
- if (g_poofIndex == MAX_POOFS) {
- g_poofIndex = 0;
- }
-}
-
-function setupTrail() {
- g_trailParameters = {
- numParticles: 2,
- lifeTime: 2,
- startSize: 10,
- endSize: 90,
- velocityRange: [20, 20, 20],
- spinSpeedRange: 4};
- g_trail = g_particleSystem.createTrail(
- g_client.root,
- 1000,
- g_trailParameters);
- g_trail.setState(o3djs.particles.ParticleStateIds.ADD);
- g_trail.setColorRamp(
- [1, 0, 0, 1,
- 1, 1, 0, 1,
- 1, 1, 1, 0]);
-}
-
-function leaveTrail() {
- var trailClock = window.g_clock * -0.8;
- g_trail.birthParticles(
- [Math.sin(trailClock) * 400, 200, Math.cos(trailClock) * 400]);
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onrender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- window.g_clock += elapsedTime * window.g_timeMult;
-
- if (g_keyDown[84]) { // 'T' key.
- leaveTrail();
- }
-
- var cameraClock = window.g_clock * 0.3;
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [Math.sin(cameraClock) * 1500, 500, Math.cos(cameraClock) * 1500], // eye
- [0, 100, 0], // target
- [0, 1, 0]); // up
-
- g_clockParam.value = window.g_clock;
-}
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body onload="init();" onunload="unload();">
-<h1>Particles</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-Press 'P' to make a poof.<br/>
-Hold 'T' to make a trail.
-</body>
-</html>
diff --git a/o3d/samples/phongshading.html b/o3d/samples/phongshading.html
deleted file mode 100644
index b26f654..0000000
--- a/o3d/samples/phongshading.html
+++ /dev/null
@@ -1,367 +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.
--->
-
-<!--
-O3D Tutorial B5
-
-In this tutorial, we generate a simple spherical mesh using Javascript and
-shade it using Phong illumination.
-
-We calculate the various lighting components (ambient,diffuse,specular)
-and combine them in our vertex/pixel shaders to draw the correct color for each
-pixel in the scene.
-
-The scene is illuminated by a single red light and the sphere is white.
-(ie ambient, diffuse, and specular reflection constants of the material = 1)
-
-In this sample, we generate the projection matrix dynamically from the size
-of the o3d plugin.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Tutorial B5: Phong Shading
-</title>
-<!-- Our javascript code -->
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-
-// Events
-// Run the init() function once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_o3dElement;
-var g_viewInfo;
-var g_pack;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-
-// Our view and projection matrices
-// The view matrix transforms objects from world space to view space.
-var g_view_matrix;
-// The projection matrix projects objects from view space to the screen.
-var g_proj_matrix;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and draws the sphere.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Create a g_pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- /* Load the effect for our sphere from our file.
- Effects, stored in a hidden textarea for simplicity, contain the
- functions that define the vertex and pixel shaders used by our shape.
-
- Here, we calculate phong illumination in our vertex shader and pass the
- resultant color to our pixel shader, which does nothing except output its
- given (input) color.
- */
- var effect = g_pack.createObject('Effect');
- effect.loadFromFXString(document.getElementById('shader').value);
-
- // Create a Material for the effect.
- var myMaterial = g_pack.createObject('Material');
-
- // Apply our effect to this material.
- myMaterial.effect = effect;
-
- // Set the material's drawList
- myMaterial.drawList = g_viewInfo.performanceDrawList;
-
- // Create the params the effect needs on the material.
- effect.createUniformParameters(myMaterial);
-
- // Create a sphere at the origin with radius 1.
- var myShape = o3djs.primitives.createSphere(g_pack,
- myMaterial,
- 1,
- 70,
- 70);
-
- // Set up the individual parameters in our effect file.
-
- // Light position
- var light_pos_param = myMaterial.getParam('light_pos');
- light_pos_param.value = [10, 10, 20];
-
- // Phong components of the light source
- var light_ambient_param = myMaterial.getParam('light_ambient');
- var light_diffuse_param = myMaterial.getParam('light_diffuse');
- var light_specular_param = myMaterial.getParam('light_specular');
-
- // White ambient light
- light_ambient_param.value = [0.04, 0.04, 0.04, 1];
- // Reddish diffuse light
- light_diffuse_param.value = [0.8, 0, 0, 1];
- // White specular light
- light_specular_param.value = [0.5, 0.5, 0.5, 1];
-
- // Shininess of the material (for specular lighting)
- var shininess_param = myMaterial.getParam('shininess');
- shininess_param.value = 30.0;
-
- // Position of the camera.
- // (should be the same as the 'eye' position given below)
- var camera_pos_param = myMaterial.getParam('camera_pos');
- // Camera is at (0, 0, 3).
- camera_pos_param.value = [0, 0, 3];
-
- // Now create our view matrix by defining coordinates for the
- // target, eye, and up vectors and using the g_math.matrix4.lookAt(..)
- // helper function to create the matrix.
-
- // Eye-position, this is where our camera is at.
- var eye = [0, 0, 3];
-
- // Target, this is where our camera is pointed at.
- var target = [0, 0, 0];
-
- // Up-vector, this tells the camera which direction is 'up'.
- // We define the positive y-direction to be up in this example.
- var up = [0, 1, 0];
-
- g_view_matrix = g_math.matrix4.lookAt(eye, target, up);
-
- // Generate the projection and viewProjection matrices based
- // on the g_o3d plugin size by calling resize().
- resize();
-
- // Now attach the sphere to the root of the transform graph.
- var root = g_client.root;
- root.addShape(myShape);
-
- // If we don't check the size of the client area every frame we don't get a
- // chance to adjust the perspective matrix fast enough to keep up with the
- // browser resizing us.
- g_client.setRenderCallback(resize);
-}
-
-// Generates the projection matrix based on the size of the o3d plugin
-// and calculates the view-projection matrix.
-function resize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- // Create our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 100.
- g_proj_matrix = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_o3dWidth / g_o3dHeight,
- 0.1,
- 100);
-
- // Set the view and projection matrix
- g_viewInfo.drawContext.view = g_view_matrix;
- g_viewInfo.drawContext.projection = g_proj_matrix;
- }
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<table width="100%" style="height:100%;">
- <tr><td>
-<h1>Phong shading</h1>
-<p>
-This tutorial shows how we generate a custom mesh and
-perform Phong illumination using a shader.
-</p>
-<p>
-This sample displays a Phong shaded white sphere lit by a single red light.
-</p>
-<table id="container" width="90%" style="height:60%;"><tr><td height="100%">
-<!-- Start of g_o3d plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of g_o3d plugin -->
-</td></tr></table>
-<!-- a simple way to get a multiline string -->
-<textarea id="shader" name="shader" cols="80" rows="20"
- style="display: none;">
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WorldViewProjection;
-
-// positions of the light and camera
-float3 light_pos;
-float3 camera_pos;
-
-// phong lighting components of the light source
-float4 light_ambient;
-float4 light_diffuse;
-float4 light_specular;
-
-// shininess of the material. (for specular lighting)
-float shininess;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 postion : POSITION;
- float3 normal : NORMAL;
- float4 color : COLOR;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct PixelShaderInput {
- float4 postion : POSITION;
- float3 lightVector : TEXCOORD0;
- float3 normal : TEXCOORD1;
- float3 viewPosition : TEXCOORD2;
- float4 color : COLOR;
-};
-
-/**
- * Vertex Shader - vertex shader for phong illumination
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- /**
- * We use the standard phong illumination equation here.
- * We restrict (clamp) the dot products so that we
- * don't get any negative values.
- * All vectors are normalized for proper calculations.
- *
- * The output color is the summation of the
- * ambient, diffuse, and specular contributions.
- *
- * Note that we have to transform each vertex and normal
- * by the world view projection matrix first.
- */
- PixelShaderInput output;
-
- output.postion = mul(input.postion, worldViewProjection);
-
- /**
- * lightVector - light vector
- * normal - normal vector
- * viewPosition - view vector (from camera)
- */
-
- // NOTE: In this case we do not need to multiply by any matrices since the
- // WORLD transformation matrix is the identity. If you were moving the
- // object such that the WORLD transform matrix was not the identity, you
- // would need to multiply the normal by the WORLDINVERSETTRANSFORM matrix
- // since the normal is in object space. Other values (light_pos, camera_pos)
- // are already in world space.
- float3 lightVector = light_pos - input.postion.xyz;
- float3 normal = input.normal;
- float3 viewPosition = camera_pos - input.postion.xyz;
-
- output.lightVector = lightVector;
- output.normal = normal;
- output.viewPosition = viewPosition;
- output.color = input.color;
- return output;
-}
-
-/**
- * Pixel Shader
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- float3 lightVector = normalize(input.lightVector);
- float3 normal = normalize(input.normal);
- float3 viewPosition = normalize(input.viewPosition);
- float3 halfVector = normalize(lightVector + viewPosition);
-
- // use lit function to calculate phong shading
- // x component contains the ambient coefficient
- // y component contains the diffuse coefficient:
- // max(dot(normal, lightVector),0)
- // z component contains the specular coefficient:
- // dot(normal, lightVector) < 0 || dot(normal, halfVector) < 0 ?
- // 0 : pow(dot(normal, halfVector), shininess)
- // NOTE: This is actually Blinn-Phong shading, not Phong shading
- // which would use the reflection vector instead of the half vector
-
- float4 phong_coeff = lit(dot(normal, lightVector),
- dot(normal, halfVector), shininess);
-
- float4 ambient = light_ambient * phong_coeff.x * input.color;
- float4 diffuse = light_diffuse * phong_coeff.y * input.color;
- float4 specular = light_specular * phong_coeff.z * input.color;
-
- return ambient + diffuse + specular;
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</td></tr></table>
-</body>
-</html>
diff --git a/o3d/samples/picking.html b/o3d/samples/picking.html
deleted file mode 100644
index 3466ff5..0000000
--- a/o3d/samples/picking.html
+++ /dev/null
@@ -1,342 +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.
--->
-
-<!--
-O3D Picking Example.
-
-This example shows one way to implement picking. Because O3D is shader
-agnostic we can't handle picking automatically since we have no way of knowing
-what the developer is going to do with their shaders. On the other hand, we can
-provide various functions that make it possible to do your own picking. Only you
-know which objects are pickable and which are not. For example if you are
-making an RTS game, only you would know that units are pickable but ground and
-explosions are not and that neither is your HUD.
-
-It's possible that someone, maybe us, will create an engine to use o3d
-that given a bunch of restrictions and flags on the data it excepts can
-do picking in a more automatic way but that is not the goal of the o3d api.
-Its goal is to provide a LOW-LEVEL shader agnostic API.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-O3D Picking Example.
-</title>
-<!-- Include default javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.picking');
-o3djs.require('o3djs.scene');
-o3djs.require('o3djs.debug');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// constants
-var NORMAL_SCALE_FACTOR = 2.0;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_pickManager; // information about the transform graph.
-var g_pickInfoElem;
-var g_debugHelper;
-var g_debugLineGroup;
-var g_debugLine;
-var g_selectedInfo = null;
-var g_flashTimer = 0;
-var g_highlightMaterial;
-var g_highlightShape;
-var g_finished = false; // for selenium testing.
-
-function updateInfo() {
- if (!g_pickManager) {
- g_pickManager = o3djs.picking.createPickManager(g_client.root);
- }
- g_pickManager.update();
-}
-
-function unSelectAll() {
- if (g_selectedInfo) {
- // Remove it from the transform of the selected object.
- g_selectedInfo.shapeInfo.parent.transform.removeShape(g_highlightShape);
- // Remove everything related to it.
- o3djs.shape.deleteDuplicateShape(g_highlightShape, g_pack);
- g_highlightShape = null;
- g_selectedInfo = null;
- // Turn off the debug line.
- g_debugLine.setVisible(false);
- }
-}
-
-function select(pickInfo) {
- unSelectAll();
- if (pickInfo) {
- g_selectedInfo = pickInfo;
- // make a copy of the selected shape so we can use it to highlight.
- g_highlightShape = o3djs.shape.duplicateShape(
- g_pack,
- g_selectedInfo.shapeInfo.shape,
- 'highlight_');
- // Set all of it's elements to use the highlight material.
- var elements = g_highlightShape.elements;
- for (var ee = 0; ee < elements.length; ee++) {
- elements[ee].material = g_highlightMaterial;
- }
-
- // Add it to the same transform
- g_selectedInfo.shapeInfo.parent.transform.addShape(g_highlightShape);
- g_flashTimer = 0.0; // make it change color immediately.
- }
-}
-
-function pick(e) {
- var worldRay = o3djs.picking.clientPositionToWorldRay(
- e.x,
- e.y,
- g_viewInfo.drawContext,
- g_client.width,
- g_client.height);
- unSelectAll();
-
- // Update the entire tree in case anything moved.
- // NOTE: This function is very SLOW!
- // If you really want to use picking you should manually update only those
- // transforms and shapes that moved, were added, or deleted by writing your
- // own picking library. You should also make sure that you are only
- // considering things that are pickable. By that I mean if you have a scene of
- // a meadow with trees, grass, bushes, and animals and the only thing the user
- // can pick is the animals then put the animals on their own sub branch of the
- // transform graph and only pick against that subgraph.
- // Even better, make a separate transform graph with only cubes on it to
- // represent the animals and use that instead of the actual animals.
- g_pickManager.update();
-
- var pickInfo = g_pickManager.pick(worldRay);
- if (pickInfo) {
- select(pickInfo);
- g_pickInfoElem.innerHTML = pickInfo.shapeInfo.shape.name;
-
- // Display the normal
- // NOTE: Lookup the normal with this function is very SLOW!!
- // If you need performance, for a game or something, you should consider
- // other methods.
- var normal = o3djs.element.getNormalForTriangle(
- pickInfo.element,
- pickInfo.rayIntersectionInfo.primitiveIndex);
-
- // Convert the normal from local to world space.
- normal = g_math.matrix4.transformNormal(
- pickInfo.shapeInfo.parent.transform.worldMatrix,
- normal);
-
- // Remove the scale from the normal.
- normal = g_math.normalize(normal);
-
- // Get the world position of the collision.
- var worldPosition = pickInfo.worldIntersectionPosition;
-
- // Add the normal to it to get a point in space above it with some
- // multiplier to scale it.
- var normalSpot = g_math.addVector(
- worldPosition,
- g_math.mulVectorScalar(normal, NORMAL_SCALE_FACTOR));
-
- // Move our debug line to show the normal
- g_debugLine.setVisible(true);
- g_debugLine.setEndPoints(worldPosition, normalSpot);
- } else {
- g_pickInfoElem.innerHTML = '--nothing--';
- }
-}
-
-function onrender(renderEvent) {
- g_flashTimer += renderEvent.elapsedTime;
- g_flashTimer = g_flashTimer % 0.5;
- if (g_selectedInfo) {
- if (g_flashTimer < 0.25) {
- g_highlightMaterial.getParam('emissive').value = [1, 1, 1, 1];
- } else {
- g_highlightMaterial.getParam('emissive').value = [0, 0, 0, 1];
- }
- }
-}
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- */
-function loadScene(pack, fileName, parent) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a cameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- g_client.width,
- g_client.height);
-
- // Copy the one from the file to ours.
- g_viewInfo.drawContext.view = cameraInfo.view;
- g_viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
-
- // Update our info
- updateInfo();
-
- g_pickManager.dump('');
-
- g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- o3dElement.name = 'o3dObj'; // This is only for our selenium tests.
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- g_pickInfoElem = document.getElementById('pickInfo');
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Use the debug library to create a line we can position to show
- // the normal.
- g_debugHelper = o3djs.debug.createDebugHelper(g_client.createPack(),
- g_viewInfo);
- g_debugLineGroup = g_debugHelper.createDebugLineGroup(g_client.root);
- g_debugLine = g_debugLineGroup.addLine();
- g_debugLine.setColor([0,1,0,1]);
- g_debugLine.setVisible(false);
-
- // Create a material for highlighting.
- g_highlightMaterial = o3djs.material.createConstantMaterial(
- g_pack,
- g_viewInfo,
- [1, 1, 1, 1]);
- // Setup a state to bring the lines forward.
- var state = g_pack.createObject('State');
- state.getStateParam('PolygonOffset2').value = -1.0;
- state.getStateParam('FillMode').value = g_o3d.State.WIREFRAME;
- g_highlightMaterial.state = state;
-
- // Creates a transform to put our data on.
- var my_data_root = g_pack.createObject('Transform');
-
- // Connects our root to the client's root.
- my_data_root.parent = g_client.root;
-
- // Load the scene into the transform graph as a child of my_data_root
- loadScene(g_pack, 'assets/seven_shapes.o3dtgz', my_data_root);
-
- g_client.setRenderCallback(onrender);
-
- // Start picking; it won't do anything until the scene finishes loading.
- o3djs.event.addEventListener(o3dElement, 'mousedown', pick);
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Picking</h1>
-Click on an object
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<div style="font-family: sans-serif; font-size: large;">PICKED: <span id="pickInfo"></span></div>
-</body>
-</html>
diff --git a/o3d/samples/pingpong/instructions.gif b/o3d/samples/pingpong/instructions.gif
deleted file mode 100644
index d142083..0000000
--- a/o3d/samples/pingpong/instructions.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/pingpong/logo.gif b/o3d/samples/pingpong/logo.gif
deleted file mode 100644
index 379d196..0000000
--- a/o3d/samples/pingpong/logo.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/pingpong/o3dPingPong.html b/o3d/samples/pingpong/o3dPingPong.html
deleted file mode 100644
index b0e3bf0..0000000
--- a/o3d/samples/pingpong/o3dPingPong.html
+++ /dev/null
@@ -1,851 +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.
--->
-
-<title>o3dPingPong</title>
-
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.event');
-
-var shader='uniform float4x4 worldViewProjMatrix : WORLDVIEWPROJECTION;\n'+
-'void vs(\n'+
-' float4 pos: POSITION,\n'+
-' float4 col: COLOR,\n'+
-'\n'+
-' out float4 oPos: POSITION,\n'+
-' out float4 color : COLOR0)\n'+
-'{\n'+
-' oPos = mul(pos,worldViewProjMatrix);\n'+
-'\n'+
-' color=col; //float4(1,0,0,1);\n'+
-'}\n'+
-'\n'+
-'void fs(\n'+
-' float4 color: COLOR,\n'+
-' out float4 oCol: COLOR)\n'+
-'{\n'+
-' oCol=color;\n'+
-'}\n'+
-'// #o3d VertexShaderEntryPoint vs\n'+
-'// #o3d PixelShaderEntryPoint fs\n'+
-'// #o3d MatrixLoadOrder RowMajor\n';
-
-var camera = {};
-camera.eye = {};
-camera.target = {};
-camera.eye.x = 0;
-camera.eye.y = -100;
-camera.eye.z = 100;
-camera.target.x = 0;
-camera.target.y = 0;
-camera.target.z = 0;
-
-var on = false;
-var cube;
-var none;
-var view;
-var viewInfo;
-var g_material;
-var angleY=0;
-var angleX=0;
-var o3d;
-var math;
-var client;
-var pack;
-var g_finished = false; // for selenium
-
-var game = {};
-
-function updateView() {
- var matrix = math.matrix4.identity();
- math.matrix4.rotateZYX(matrix, [angleX, angleY, 0]);
- math.matrix4.scale(matrix, math.mulScalarVector(.25, [1, 1, 1]));
- view.localMatrix = matrix;
-}
-
-var key = {};
-key.LEFT = 37;
-key.UP = 38;
-key.RIGHT = 39;
-key.DOWN = 40;
-
-
-key.A = 65
-key.S = 83
-key.D = 68
-key.W = 87
-
-function keyPressed(e) {
- /*if (e.keyCode == key.A) rotateY(-0.1);
- else if (e.keyCode == key.D) rotateY(0.1)
- else if (e.keyCode == key.W) rotateX(-0.1)
- else if (e.keyCode == key.S) rotateX(0.1)*/
-}
-
-function move_instance(node, x, y, z, h) {
- node.identity();
- node.translate(x, y, z);
-}
-
-var entityID = 0;
-var transformNodes = new Array();
-var meshNodes = new Array();
-
-function createBox(x, y, z, w, d, h, color, parentNode, fadeToColor) {
-
- var boxVerts = [
- 0, 0, 0, // 0
- w, 0, 0, // 1
- w, 0, h, // 2
- 0, 0, h, // 3
- 0, d, 0, // 4
- w, d, 0, // 5
- w, d, h, // 6
- 0, d, h, // 7
- 0, 0, 0, // 0b
- w, 0, 0, // 1b
- w, 0, h, // 2b
- 0, 0, h, // 3b
- 0, d, 0, // 4b
- w, d, 0, // 5b
- w, d, h, // 6b
- 0, d, h // 7b
- ];
-
- var boxIndices = [
- 0, 1, 3, 1, 2, 3, // front
- 0+8, 3+8, 1+8, 1+8, 3+8, 2+8, // frontb
-
- 5+8, 4+8, 6+8, 4+8, 7+8, 6+8, // back
- 5+8, 6+8, 4+8, 4+8, 6+8, 7+8, // backb
-
- 4, 0, 7, 0, 3, 7, // left
- 4+8, 7+8, 0+8, 0+8, 7+8, 3+8, // leftb
-
- 1+8, 5+8, 2+8, 5+8, 6+8, 2+8, // right
- 1, 2+8, 5+8, 5+8, 2+8, 6+8, // rightb
-
- 4, 5, 0, 5, 1, 0, // top
- 4+8, 0+8, 5+8, 5+8, 0+8, 1+8, // top2
-
- 6+8, 7+8, 2+8, 7+8, 3+8, 2+8, // bottom
- 6+8, 2+8, 7+8, 7+8, 2+8, 3+8 // bottom2
- ];
-
-
- var boxIndicesOneSided = [
- 0, 1, 3, 1, 2, 3, // front
- 5+8, 4+8, 6+8, 4+8, 7+8, 6+8, // back
- 4, 0, 7, 0, 3, 7, // left
- 1+8, 5+8, 2+8, 5+8, 6+8, 2+8, // right
- 4, 5, 0, 5, 1, 0, // top
- 6+8, 7+8, 2+8, 7+8, 3+8, 2+8 // bottom
- ];
-
- if (color != undefined) {
- var r = color.r;
- var g = color.g;
- var b = color.b;
- var a = color.a;
- if (fadeToColor == color) {
- var boxColors = [
- r, g, b, a, // 0
- r, g, b, a, // 1
- r, g, b, a, // 2
- r, g, b, a, // 3
- r, g, b, a, // 4
- r, g, b, a, // 5
- r, g, b, a, // 6
- r, g, b, a, // 7
- r, g, b, a, // 0b
- r, g, b, a, // 1b
- r, g, b, a, // 2b
- r, g, b, a, // 3b
- r, g, b, a, // 4b
- r, g, b, a, // 5b
- r, g, b, a, // 6b
- r, g, b, a // 7b
- ];
-
- } else if (fadeToColor != undefined) {
- r2 = fadeToColor.r;
- g2 = fadeToColor.g;
- b2 = fadeToColor.b;
- var boxColors = [
- r2, g2, b2, a, // 0
- r2, g2, b2, a, // 1
- r, g, b, a, //
- r, g, b, a, // 3
- r2, g2, b2, a, // 4
- r2, g2, b2, a, // 5
- r, g, b, a, // 6
- r, g, b, a, // 7
- r2, g2, b2, a, // 0b
- r2, g2, b2, a, // 1b
- r, g, b, a, // 2b
- r, g, b, a, // 3b
- r2, g2, b2, a, // 4b
- r2, g2, b2, a, // 5b
- r, g, b, a, // 6b
- r, g, b, a // 7b
- ];
-
- } else {
- var boxColors = [
- r, g, b, a, // 0
- r, g, b, a, // 1
- r*.7, g*.7, b*.7, a, // 2
- r*.7, g*.7, b*.7, a, // 3
- r, g, b, a, // 4
- r, g, b, a, // 5
- r*.7, g*.7, b*.7, a, // 6
- r*.7, g*.7, b*.7, a, // 7
- r*.8, g*.8, b*.8, a, // 0b
- r*.8, g*.8, b*.8, a, // 1b
- r*.8, g*.8, b*.8, a, // 2b
- r*.8, g*.8, b*.8, a, // 3b
- r*.4, g*.4, b*.4, a, // 4b
- r*.4, g*.4, b*.4, a, // 5b
- r*.4, g*.4, b*.4, a, // 6b
- r*.4, g*.4, b*.4, a // 7b
- ];
- }
- } else {
- var boxColors = [
- 1, 0, 0, 1, // 0
- 1, 0, 0, 1, // 1
- 1, 0, 0, 1, // 2
- 1, 0, 0, 1, // 3
- 0, 1, 0, 1, // 4
- 0, 1, 0, 1, // 5
- 0, 1, 0, 1, // 6
- 0, 1, 0, 1, // 7
- .5, 0, 0, 1, // 0b
- .5, 0, 0, 1, // 1b
- .5, 0, 0, 1, // 2b
- .5, 0, 0, 1, // 3b
- 0, .5, 0, 1, // 4b
- 0, .5, 0, 1, // 5b
- 0, .5, 0, 1, // 6b
- 0, .5, 0, 1 // 7b
- ];
- }
-
- entityID++;
-
- transformName = 'transform' + entityID;
- shapeName = 'shape' + entityID;
- meshName = 'mesh' + entityID;
- transformNodes[entityID] = pack.createObject('Transform');
-
- transformNodes[entityID].translate(x, y, z);
-
- meshNodes[entityID] = pack.createObject('Shape');
- transformNodes[entityID].addShape(meshNodes[entityID])
- var primitive = pack.createObject('Primitive');
- var streamBank = pack.createObject('StreamBank');
- primitive.owner = meshNodes[entityID];
- primitive.streamBank = streamBank;
-
- primitive.material = g_material;
-
- var vertBuffer = pack.createObject('VertexBuffer');
- var positionField = vertBuffer.createField('FloatField', 3);
- vertBuffer.set(boxVerts);
-
- var colorBuffer = pack.createObject('VertexBuffer');
- var colorField = colorBuffer.createField('FloatField', 4);
- colorBuffer.set(boxColors);
-
- var indexBuffer = pack.createObject('IndexBuffer');
- indexBuffer.set(boxIndices);
-
- streamBank.setVertexStream(o3d.Stream.POSITION,
- 0,
- positionField,
- 0);
- streamBank.setVertexStream(o3d.Stream.COLOR,
- 0,
- colorField,
- 0);
- primitive.indexBuffer = indexBuffer;
-
- primitive.primitiveType = o3d.Primitive.TRIANGLELIST;
- primitive.numberPrimitives = 24;
- primitive.numberVertices = 16;
-
- if (parentNode != undefined) {
- transformNodes[entityID].parent = parentNode;
- } else {
- transformNodes[entityID].parent = view;
- }
-
- primitive.createDrawElement(pack, null);
-
- return transformNodes[entityID];
-}
-
-var Color = function(r, g, b, a) {
- if (r>1 || g>1 || b>1) {
- r = r/255;
- g = g/255;
- b = b/255;
- }
- this.r = r;
- this.g = g;
- this.b = b;
- this.a = a;
-}
-function scrollMe(e) {
- if (e.deltaY < 0) {
- camera.eye.x *= 11/12;
- camera.eye.y *= 11/12;
- camera.eye.z *= 11/12;
-
- } else {
- camera.eye.x *= (1+1/12);
- camera.eye.y *= (1+1/12);
- camera.eye.z *= (1+1/12);
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- var o3dElement = clientElements[0];
- o3dElement.id = 'o3dObj';
- o3d = o3dElement.o3d;
- math = o3djs.math;
- client = o3dElement.client;
-
- pack = client.createPack();
-
- // Create the render graph for a view.
- viewInfo = o3djs.rendergraph.createBasicView(
- pack,
- client.root,
- client.renderGraphRoot);
-
- var effect = pack.createObject('Effect');
- effect.loadFromFXString(shader);
- g_material = pack.createObject('Material');
- g_material.drawList = viewInfo.performanceDrawList;
- g_material.effect = effect;
- effect.createUniformParameters(g_material);
-
- view = pack.createObject('Transform');
- view.parent = client.root;
-
- var root = client.root;
-
- var o3d_width = client.width;
- var o3d_height = client.height;
-
- viewInfo.drawContext.projection=math.matrix4.perspective(
- math.degToRad(30), o3d_width / o3d_height, 1, 5000);
- target = [0, 0, 0];
- eye = [0, -100, 0];
- up = [0, 0, 1];
- viewInfo.drawContext.view = math.matrix4.lookAt(eye, target, up);
-
- bg = pack.createObject('Transform');
- bg.translate(0, 0, 1);
- bg.parent = client.root;
-
- red = new Color(1, 0, 0, 1);
- blue = new Color(0, 0, 1, 1);
- wallColor = new Color(0, .8, .4, 1);
- green = new Color(0, .5, 0, 1);
- lineColor = new Color(0, .7, 0, 1);
- shadow = new Color(0, .3, 0, .5);
- silver = new Color(.8, .8, .8, 1);
- pink = new Color(1, .8, .8, 1);
-
- window.field = createBox(-120, -80, -10, 240, 160, 10, green)
- window.centerline = createBox(-3, -80, 0, 6, 160, .5, lineColor)
- window.paddle1 = createBox(-110, 0, 5, 10, 30, 30, silver);
- window.shadow1 = createBox(-107, 3, 1, 10, 30, 0, shadow);
-
- window.paddle2 = createBox(-110, 0, 5, 10, 30, 30, silver);
- window.shadow2 = createBox(-107, 3, 1, 10, 30, 0, shadow);
-
- window.ball = createBox(0, 0, 2, 10, 10, 10, pink);
- window.ballShadow = createBox(0, 0, 1, 10, 10, 0, shadow);
-
- window.bottomWall = createBox(-120, -90, -10, 240, 10, 15, wallColor);
- window.topWall = createBox(-120, 80, -10, 240, 10, 15, wallColor);
-
- suRed = new Color(.7, 0, 0, 1)
- suGreen = new Color(0, .7, 0, 1)
- suBlue = new Color(0, 0, .7, 1)
- suGround = new Color(210, 208, 185, 1);
- suSky = new Color(212*.8, 225*.8, 225*.8, 1);
-
- window.xaxis = createBox(0, 0, 0, 5000, .25, .25, suRed, undefined);
- window.yaxis = createBox(0, 0, 0, .25, 5000, .25, suGreen, undefined);
- window.zaxis = createBox(0, 0, 0, .25, .25, 5000, suBlue, undefined);
-
- white = new Color(1, 1, 1, 1);
-
- mybox3 = createBox(-1500, -1500, -1500, 3000, 3000, 3000, suSky, bg, suGround);
- bg_Ground1 = createBox(-1500, 1490, -1500, 3000, 10, 1500, suGround, bg, suGround);
- bg_GroundR = createBox(1490, -1500, -1500, 10, 3000, 1500, suGround, bg, suGround);
- bg_GroundL = createBox(-1490, -1500, -1500, 10, 3000, 1500, suGround, bg, suGround);
- bg_Sky = createBox(-1500, 1490, 0, 3000, 10, 1500, suSky, bg, white);
- bg_SkyR = createBox(1490, -1500, 0, 10, 3000, 1500, suSky, bg, white);
- bg_SkyL = createBox(-1490, -1500, 0, 10, 3000, 1500, suSky, bg, white);
-
- on=true;
- updateView();
-
- o3djs.event.addEventListener(o3dElement, 'wheel', scrollMe);
-
- updateLayout();
-
- g_finished = true; // for selenium
-}
-
-function rotateX(delta) {
- angleX=angleX+delta;
- updateView();
-}
-
-function rotateY(delta) {
- angleY=angleY+delta;
- updateView();
-}
-
-function toggle() {
- if (on) {
- cube.parentNode = none;
- } else {
- cube.parentNode = view;
- }
-
- on = !on;
-}
-
-function startGame() {
- if (window.gameStarted == true) {
- return
- }
- window.gameStarted = true;
- document.getElementById('o3d').style.visibility = 'visible';
-
- // Wait until the plug-in has initialized before starting the game.
- var clearId = window.setInterval(function() {
- if (client) {
- client.setRenderCallback(nextFrame);
- } else {
- return;
- }
- window.clearInterval(clearId);
- }, 10);
-}
-
-function updateLayout() {
- document.getElementById('focusHolder').focus();
- document.body.scrollTop = 0;
-
-}
-
-function uninit() {
- if (client) {
- client.cleanup();
- }
-}
-
-window.onload = init;
-window.onunload = uninit;
-
-</script>
-<body style="overflow:hidden" onscroll="updateLayout();">
-
-<table border=0 width=100% height=100% style="overflow:hidden" >
-<tr><td id="clientBanner" align=center style="cursor:pointer;background-image:url(logo.gif);background-position:center center;background-repeat:no-repeat" onclick="startGame();">
-<div id="client" name="client" >
-<div id="o3d" style="width: 800px; height: 600px; visibility: hidden;"></div>
-<br/><img src="instructions.gif"></div>
-<form>
-<input id="focusHolder" style="position:absolute;top:-100px;">
-</form>
-
-</td></tr></table>
-
-
-</body>
-
-<script>
-
-keyIsDown = new Array();
-
-document.onkeydown = function(e) {
- var keyChar = o3djs.event.getEventKeyChar(e);
- keyIsDown[keyChar] = true;
-}
-
-document.onkeyup = function(e) {
- var keyChar = o3djs.event.getEventKeyChar(e);
- keyIsDown[keyChar] = false;
-}
-
-
-var x = 1000+10;
-var y = 1000+20;
-var z = 1;
-
-var BACKSPACE=8
-var TAB=9
-var ENTER=13
-var SHIFT=16
-var CTRL=17
-var ALT=18
-var ESCAPE=27
-var PAGEUP=33
-var PAGEDOWN=34
-var END=35
-var HOME=36
-var LEFT=37
-var UP=38
-var RIGHT=39
-var DOWN=40
-var DELETE=46
-var SPACE=32
-
-var spriteInfo = new Array();
-
-
-var leftID = 0
-var rightID = 1
-var ballID = 2
-var myPaddleID = leftID
-var enemyPaddleID = rightID
-var nextServeDirection = -1
-var isServing = true;
-var loop = 0;
-
-
-
-spriteInfo[leftID] = new Array();
-spriteInfo[rightID] = new Array();
-spriteInfo[ballID] = new Array();
-
-spriteInfo[leftID].velocityY = 0;
-spriteInfo[leftID].velocityX = 0;
-spriteInfo[leftID].x = 10;
-spriteInfo[leftID].y = 80;
-
-spriteInfo[rightID].velocityY = 0;
-spriteInfo[rightID].velocityX = 0;
-spriteInfo[rightID].x = 230;
-spriteInfo[rightID].y = 80;
-
-spriteInfo[ballID].velocityY = 0;
-spriteInfo[ballID].velocityX = 0;
-spriteInfo[ballID].x = 120;
-spriteInfo[ballID].y = 80;
-
-var SCREENHEIGHT = 160;
-var SCREENWIDTH = 240;
-var PADDLE
-
-var BALLWIDTH = 30
-var BALLHEIGHT = 32
-
-var BALLPAD = 20
-var PADDLEHEIGHT = 30
-var PADDLEWIDTH = 10
-var PADDLEACCELY = 10 // acceleration rate of the paddle
-var PADDLEACCELX = 10 // acceleration rate of the paddle
-var SCREENWIDTH = 240
-var SCREENHEIGHT = 160
-var SCREENCENTERX = 120
-var SCREENCENTERY = 80
-
-var COMPUTERACCURACYX=90 // accuracy in pixels that the computer tries to get its paddle within
-var COMPUTERACCURACYY=10
-
-var points = [0, 0, 0];
-function ScorePoint(playerNumber) {
-
- if (playerNumber == myPaddleID) {
- //alert('You Score!');
- } else {
- //alert('You Suck!');
- }
- spriteInfo[ballID].velocityX = 0;
- spriteInfo[ballID].velocityY = 0;
-
- spriteInfo[ballID].x = SCREENWIDTH/2;
- spriteInfo[ballID].y = SCREENHEIGHT/2;
- points[playerNumber]++;
- pts = points[playerNumber];
-
- ptBox = createBox(-140 + playerNumber*280, -80+pts*15, 0, 10, 10, 3, red);
-
-
-}
-
-
-function nextFrame(render_event) {
-
- var elapsedTime = render_event.elapsedTime;
-
- spriteInfo[ballID].x += spriteInfo[ballID].velocityX * elapsedTime;
- spriteInfo[ballID].y += spriteInfo[ballID].velocityY * elapsedTime;
-
- spriteInfo[leftID].x += spriteInfo[leftID].velocityX * elapsedTime;
- spriteInfo[leftID].y += spriteInfo[leftID].velocityY * elapsedTime;
-
- spriteInfo[rightID].x += spriteInfo[rightID].velocityX * elapsedTime;
- spriteInfo[rightID].y += spriteInfo[rightID].velocityY * elapsedTime;
-
- // move my paddle
- if (keyIsDown[UP]) {
- spriteInfo[myPaddleID].velocityY -= PADDLEACCELY;
- } else if (keyIsDown[DOWN]) {
- spriteInfo[myPaddleID].velocityY += PADDLEACCELY;
- } else {
- spriteInfo[myPaddleID].velocityY -= spriteInfo[myPaddleID].velocityY * elapsedTime;
- }
-
- if (keyIsDown[LEFT]) {
- spriteInfo[myPaddleID].velocityX -= PADDLEACCELX;
- } else if (keyIsDown[RIGHT]) {
- spriteInfo[myPaddleID].velocityX += PADDLEACCELX;
- } else {
- spriteInfo[myPaddleID].velocityX -= spriteInfo[myPaddleID].velocityX * elapsedTime;
- }
-
- if (keyIsDown[key.A]) camera.eye.x -= 100 * elapsedTime;
- if (keyIsDown[key.D]) camera.eye.x += 100 * elapsedTime;
- if (keyIsDown[key.W]) camera.eye.z += 100 * elapsedTime;
- if (keyIsDown[key.S]) camera.eye.z -= 100 * elapsedTime;
-
- target = [0, 0, 0];
- eye = [camera.eye.x, camera.eye.y, camera.eye.z];
- up = [0, 0, 1];
- viewInfo.drawContext.view = math.matrix4.lookAt(eye, target, up);
-
- // make sure my paddle can't go off the top & bottom of screen
- if (spriteInfo[myPaddleID].y < PADDLEHEIGHT/2) {
- spriteInfo[myPaddleID].y = PADDLEHEIGHT/2;
- spriteInfo[myPaddleID].velocityY = 0;
- } else if (spriteInfo[myPaddleID].y > SCREENHEIGHT-PADDLEHEIGHT/2) {
- spriteInfo[myPaddleID].y = SCREENHEIGHT-PADDLEHEIGHT/2;
- spriteInfo[myPaddleID].velocityY = 0;
- }
-
- if (spriteInfo[myPaddleID].x < PADDLEWIDTH) {
- spriteInfo[myPaddleID].x = PADDLEWIDTH;
- spriteInfo[myPaddleID].velocityX = 0;
- } else if (spriteInfo[myPaddleID].x > SCREENWIDTH/2-BALLPAD) {
- spriteInfo[myPaddleID].x = SCREENWIDTH/2-BALLPAD;
- spriteInfo[myPaddleID].velocityX = 0;
- }
-
- // handle bouncing
- MoveComputer();
-
- if ( spriteInfo[ballID].x + BALLWIDTH/2 > spriteInfo[rightID].x &&
- spriteInfo[ballID].x + BALLWIDTH/2 < spriteInfo[rightID].x + PADDLEWIDTH &&
- spriteInfo[ballID].y > spriteInfo[rightID].y-PADDLEHEIGHT/2 &&
- spriteInfo[ballID].y < spriteInfo[rightID].y+PADDLEHEIGHT/2
- && spriteInfo[ballID].velocityX > 0) {
-
- spriteInfo[ballID].velocityX *= -1;
- spriteInfo[ballID].velocityY += spriteInfo[rightID].velocityY/2
- if (spriteInfo[rightID].velocityX < 0) {
- spriteInfo[ballID].velocityX += spriteInfo[rightID].velocityX;
- }
-
-
- } else if (spriteInfo[ballID].x - BALLWIDTH/2 < spriteInfo[leftID].x &&
- spriteInfo[ballID].x - BALLWIDTH/2 > spriteInfo[leftID].x - PADDLEWIDTH &&
- spriteInfo[ballID].y > spriteInfo[leftID].y-PADDLEHEIGHT/2 &&
- spriteInfo[ballID].y < spriteInfo[leftID].y+PADDLEHEIGHT/2
- && spriteInfo[ballID].velocityX < 0) {
-
- spriteInfo[ballID].velocityX *= -1;
- spriteInfo[ballID].velocityY += spriteInfo[leftID].velocityY/2;
- if (spriteInfo[leftID].velocityX > 0) {
- spriteInfo[ballID].velocityX += spriteInfo[leftID].velocityX;
- }
-
- }
-
-
-
- if (isServing) {
- loop++;
- if (loop > 20) {
- loop=0;
- spriteInfo[ballID].isVisible = true;
- spriteInfo[ballID].velocityY = ((Math.random()*4)-2)*20;
- spriteInfo[ballID].velocityX = (((Math.random()*1)+2) * nextServeDirection)*20;
- isServing = false;
- }
- }
-
-
-
- // bounce along top or bottom
- if ((spriteInfo[ballID].y > SCREENHEIGHT-10 || spriteInfo[ballID].y < 10) && isServing == false) {
- spriteInfo[ballID].velocityY *= -1;
- }
-
-
- if (spriteInfo[ballID].x < -50) {
- // right player scores a point!
- ScorePoint(rightID);
- nextServeDirection = -1;
- isServing = true;
- }
-
- if (spriteInfo[ballID].x > SCREENWIDTH+50) {
- // left player scores a point!
- ScorePoint(leftID);
- nextServeDirection = -1;
- isServing = true;
- }
-
-
- move_instance(paddle1, -120+spriteInfo[myPaddleID].x-PADDLEWIDTH/2, 80-spriteInfo[myPaddleID].y-PADDLEHEIGHT/2, 5, 30);
- move_instance(shadow1, -120+spriteInfo[myPaddleID].x+5-PADDLEWIDTH/2, 80-spriteInfo[myPaddleID].y-PADDLEHEIGHT/2+5, 1, 0);
-
- move_instance(paddle2, -120+spriteInfo[rightID].x-PADDLEWIDTH/2, 80-spriteInfo[rightID].y-PADDLEHEIGHT/2, 5, 30);
- move_instance(shadow2, -120+spriteInfo[rightID].x+5-PADDLEWIDTH/2, 80-spriteInfo[rightID].y-PADDLEHEIGHT/2+5, 1, 0);
-
- move_instance(ball, -120+spriteInfo[ballID].x-5, 80-(spriteInfo[ballID].y+5), 10, 10);
- move_instance(ballShadow, -120+spriteInfo[ballID].x-5+5, 80-(spriteInfo[ballID].y+0), 1, 0);
-}
-
-function MoveComputer() {
-// calculate where the AI wants to be
- if (spriteInfo[ballID].velocityX > 0) {
-
- // if the ball is coming our way, calculate where it will go
- targetX = spriteInfo[ballID].x;
- targetY = spriteInfo[ballID].y;
-
- } else {
-
- // else return to center
- targetX = 220;
- targetY = 80;
-
- }
-
- if (ComputerDistanceX() < COMPUTERACCURACYX) {
-
- spriteInfo[rightID].velocityX = spriteInfo[rightID].velocityX/2;
-
- } else {
-
- if (targetX < spriteInfo[rightID].x) {
- spriteInfo[rightID].velocityX -= PADDLEACCELX;
- } else if (targetX > spriteInfo[rightID].x) {
- spriteInfo[rightID].velocityX += PADDLEACCELX;
- } else {
- spriteInfo[rightID].velocityX = spriteInfo[rightID].velocityX/2;
- }
- }
-
- if (ComputerDistanceY() < COMPUTERACCURACYY) {
-
- spriteInfo[rightID].velocityY = spriteInfo[rightID].velocityY/2;
-
- } else {
-
- if (targetY < spriteInfo[rightID].y) {
- spriteInfo[rightID].velocityY -= PADDLEACCELY;
- } else if (targetY > spriteInfo[rightID].y) {
- spriteInfo[rightID].velocityY += PADDLEACCELY;
- } else {
- spriteInfo[rightID].velocityY = spriteInfo[rightID].velocityY/2;
- }
-
- }
-
- // make sure paddle can't go off the top & bottom of screen
- if (spriteInfo[rightID].y < PADDLEHEIGHT/2) {
- spriteInfo[rightID].y = PADDLEHEIGHT/2;
- spriteInfo[rightID].velocityY = 0;
- } else if (spriteInfo[rightID].y > SCREENHEIGHT-PADDLEHEIGHT/2) {
- spriteInfo[rightID].y = SCREENHEIGHT-PADDLEHEIGHT/2;
- spriteInfo[rightID].velocityY = 0;
- }
-
- if (spriteInfo[rightID].x > SCREENWIDTH) {
- spriteInfo[rightID].x = SCREENWIDTH-PADDLEWIDTH;
- spriteInfo[rightID].velocityX = 0;
- } else if (spriteInfo[rightID].x < SCREENWIDTH/2+BALLPAD) {
- spriteInfo[rightID].x = SCREENWIDTH/2+BALLPAD;
- spriteInfo[rightID].velocityX = 0;
- }
-
-
-}
-
-function ComputerDistanceX() {
- var distanceX;
- distanceX = spriteInfo[rightID].x - spriteInfo[ballID].x;
- if (distanceX < 0) {
- distanceX = distanceX * -1;
- }
- return distanceX;
-}
-
-function ComputerDistanceY() {
- var distanceY;
- distanceY = spriteInfo[ballID].y - spriteInfo[rightID].y;
- if (distanceY < 0) {
- distanceY = distanceY * -1;
- }
- return distanceY;
-}
-
-
-
-</script>
-
diff --git a/o3d/samples/primitives.html b/o3d/samples/primitives.html
deleted file mode 100644
index 6c2021e..0000000
--- a/o3d/samples/primitives.html
+++ /dev/null
@@ -1,250 +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.
--->
-
-<!--
-O3D Primitives
-
-This sample shows how to use the functions in the primitives utility library
-to make various shapes.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Primitives
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// global variables
-var g_o3dElement;
-var g_client;
-var g_o3d;
-var g_math;
-var g_pack;
-var g_viewInfo;
-var g_eyePosition = [3, 4, 14];
-
-/**
- * Creates the client area.
- */
-function initClient() {
- window.g_finished = false; // for selenium testing.
-
- // Runs the sample in V8. Comment out this line to run it in the browser
- // JavaScript engine, for example if you want to debug it.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.util.makeClients(main);
-}
-
-/**
- * Initializes global variables, positions camera, draws shapes.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function main(clientElements) {
- // Init global variables.
- initGlobals(clientElements);
-
- // Set up the view and projection transformations.
- initContext();
-
- // Add the shapes to the transform hierarchy.
- createShapes();
-
- window.g_finished = true; // for selenium testing.
-}
-
-/**
- * Initializes global variables and libraries.
- */
-function initGlobals(clientElements) {
- g_o3dElement = clientElements[0];
- window.g_client = g_client = g_o3dElement.client;
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-}
-
-/**
- * Sets up reasonable view and projection matrices.
- */
-function initContext() {
- // Set up a perspective transformation for the projection.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree frustum.
- g_o3dElement.clientWidth / g_o3dElement.clientHeight, // Aspect ratio.
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // primitives are located.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- g_eyePosition, // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Creates a material based on the given single color.
- * @param {!o3djs.math.Vector4} baseColor A 4-component vector with
- * the R,G,B, and A components of a color.
- * @return {!o3d.Material} A phong material whose overall pigment is
- * baseColor.
- */
-function createMaterial(baseColor) {
- // Create a new, empty Material object.
- return o3djs.material.createBasicMaterial(g_pack, g_viewInfo, baseColor);
-}
-
-/**
- * Creates shapes using the primitives utility library, and adds them to the
- * transform graph at the root node.
- */
-function createShapes() {
- var cube = o3djs.primitives.createCube(
- g_pack,
- createMaterial([0,1,0,1]), // A green phong-shaded material.
- Math.sqrt(2)); // The length of each side of the cube.
-
- var sphere = o3djs.primitives.createSphere(
- g_pack,
- createMaterial([1,0,0,1]),
- 1.0, // Radius of the sphere.
- 30, // Number of meridians.
- 20); // Number of parallels.
-
- var cylinder = o3djs.primitives.createCylinder(
- g_pack,
- createMaterial([1,0,1,1]),
- 0.5, // Radius.
- 1.5, // Height.
- 20, // Number of radial subdivisions.
- 20); // Number of vertical subdivisions.
-
- var truncatedCone = o3djs.primitives.createTruncatedCone(
- g_pack,
- createMaterial([0,0,1,1]),
- 0.3, // Bottom radius.
- 0.5, // Top radius.
- 1.5, // Height.
- 20, // Number of radial subdivisions.
- 20); // Number of vertical subdivisions.
-
- var cone = o3djs.primitives.createTruncatedCone(
- g_pack,
- createMaterial([0,1,0,1]),
- 0.5, // Bottom radius.
- 0.0, // Top radius.
- 1.5, // Height.
- 20, // Number of radial subdivisions.
- 20); // Number of vertical subdivisions.
-
- var plane = o3djs.primitives.createPlane(
- g_pack,
- createMaterial([0,1,1,1]),
- 1, // Width.
- 1.618, // Depth.
- 3, // Horizontal subdivisions.
- 3); // Vertical subdivisions.
-
- // Make a polygon to extrude for the prism.
- var polygon = [];
- var n = 10;
- for (var i = 0; i < n; ++i) {
- var theta = 2.0 * i * Math.PI / n;
- var radius = (i % 2) ? 1 : 0.382;
- polygon.push([radius * Math.cos(theta), radius * Math.sin(theta)]);
- }
-
- var prism = o3djs.primitives.createPrism(
- g_pack,
- createMaterial([1,1,0,1]),
- polygon, // The profile polygon to be extruded.
- 1); // The depth of the extrusion.
-
- var disc = o3djs.primitives.createDisc(
- g_pack,
- createMaterial([1,0,0,1]),
- 1, // Radius.
- 7, // Divisions.
- 2, // Stacks (optional).
- 0, // Start Stack (optional).
- 2); // Stack Power (optional).
-
- // Add the shapes to the transforms.
- var transformTable = [
- {shape: cube, translation: [-3, 1, 0]},
- {shape: sphere, translation: [-1, 1, 0]},
- {shape: cylinder, translation: [1, 1, 0]},
- {shape: truncatedCone, translation: [3, 1, 0]},
- {shape: plane, translation: [-3, -1, 0]},
- {shape: prism, translation: [-1, -1, 0]},
- {shape: disc, translation: [1, -1, 0]},
- {shape: cone, translation: [3, -1, 0]},
- ];
-
- for (var tt = 0; tt < transformTable.length; ++tt) {
- var transform = g_pack.createObject('Transform');
- transform.addShape(transformTable[tt].shape);
- transform.translate(transformTable[tt].translation);
- transform.parent = g_client.root;
- }
-}
-
-
-</script>
-</head>
-<body onload="initClient()">
-<h1>Primitives</h1>
-This example shows how to use the primitives utility library to make various
-shapes.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/procedural-texture.html b/o3d/samples/procedural-texture.html
deleted file mode 100644
index 312c62c..0000000
--- a/o3d/samples/procedural-texture.html
+++ /dev/null
@@ -1,258 +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.
--->
-
-<!--
-O3D Tutorial
-
-In this tutorial, we load and display a scene in O3D and then
-apply a procedural texture to it.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Applying a Procedural Texture to a scene
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_finished = false; // for selenium testing
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- */
-function loadScene(pack, fileName, parent) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- g_client.width,
- g_client.height);
-
- // Copy the view and projection to the draw context.
- g_viewInfo.drawContext.view = cameraInfo.view;
- g_viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Add our checker pattern
- createCheckerBoard(pack, 'Material__26');
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
-
- g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * In order to apply the texture you must know the material name which you wish
- * to change. The bulk of the calculation takes place in the shader itself.
- * Alternatively, you could change the first or all the materials if you don't
- * know the material name.
- * @param {!o3d.Pack} pack The pack the scene was loaded into.
- * @param {string} materialName Name of material you wish to turn into checkers.
- */
-function createCheckerBoard(pack, materialName) {
- var effectString = document.getElementById('checkerShader').value;
- var effect = g_pack.createObject('Effect');
- effect.loadFromFXString(effectString);
- var materials = pack.getObjects(materialName, 'o3d.Material');
- for (var m = 0; m < materials.length; m++) {
- var material = materials[m];
- // Set the material to use the checker effect.
- material.effect = effect;
- // Create any parameters the effect needs on the material.
- effect.createUniformParameters(material);
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Creates a transform to put our data on.
- var myDataRoot = g_pack.createObject('Transform');
-
- // Connects our root to the client's root.
- myDataRoot.parent = g_client.root;
-
- // Load the scene into the transform graph as a child myDataRoot
- loadScene(g_pack, 'assets/teapot.o3dtgz', myDataRoot);
-}
-</script>
-</head>
-<body>
-<h1>Applying a Procedural Texture to a scene</h1>
-This tutorial shows how to apply a procedural texture to a scene.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<!-- Don't render the textarea -->
-<div style="display:none">
-<textarea id="checkerShader" name="checkerShader" cols="80" rows="20">
- // The 4x4 world view projection matrix.
- float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-
- // input parameters for our vertex shader
- struct a2v {
- float4 position : POSITION;
- float3 normal : NORMAL;
- float2 texcoord : TEXCOORD0;
- };
-
- // input parameters for our pixel shader
- struct v2f {
- float4 position : POSITION;
- float4 col : COLOR;
- float2 texcoord : TEXCOORD0;
- };
-
- // function for getting the checker pattern
- float4 checker(float2 uv) {
- float checkSize = 4;
- float fmodResult = fmod(floor(checkSize * uv.x) + floor(checkSize * uv.y),
- 2.0);
- if (fmodResult < 1) {
- return float4(0, 1, 1, 1);
- } else {
- return float4(1, 0, 1, 1);
- }
- }
-
- /**
- * Our vertex shader. In the vertex shader, we calculate the lighting.
- * Then we'll combine it with our checker pattern in the pixel shader.
- */
- v2f vertexShaderFunction(a2v input) {
- v2f output;
- output.position = mul(input.position, worldViewProjection);
- /**
- * lightVector - light vector
- * normal - normal vector
- * We put the light such that it illuminates our model.
- */
-
- float4 diffuseColor = float4(1, 1, 1, 1);
- float3 lightPos = float3(1000, -1000, 1000);
-
- float3 lightVector = normalize(lightPos - input.position.xyz);
- float3 normal = normalize(input.normal);
- float4 diffuse = dot(normal, lightVector) * diffuseColor;
-
- output.col = diffuse;
- output.texcoord = input.texcoord;
- return output;
- }
-
- /**
- * Our pixel shader. We take the lighting color we got from the vertex sahder
- * and combine it with our checker pattern.
- */
- float4 pixelShaderFunction(v2f input): COLOR {
- float4 check = checker(input.texcoord);
- float4 color = input.col * check;
- return color;
- }
-
- // Here we tell our effect file *which* functions are
- // our vertex and pixel shaders.
-
- // #o3d VertexShaderEntryPoint vertexShaderFunction
- // #o3d PixelShaderEntryPoint pixelShaderFunction
- // #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
-</html>
diff --git a/o3d/samples/render-mode.html b/o3d/samples/render-mode.html
deleted file mode 100644
index 2af091b..0000000
--- a/o3d/samples/render-mode.html
+++ /dev/null
@@ -1,283 +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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<title>
- Render Mode Example.
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- }
-</style>
-</head>
-<body onload="init();" onunload="uninit();">
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.arcball');
-o3djs.require('o3djs.event');
-o3djs.require('o3djs.scene');
-
-var g_root;
-var g_o3d;
-var g_o3dElement
-var g_math;
-var g_quaternions;
-var g_client;
-var g_aball;
-var g_thisRot;
-var g_lastRot;
-var g_pack;
-var g_viewInfo;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-var g_framesRendered = 0;
-
-var g_camera = {
- eye: [0, 0, 5],
- target: [0, 0, 0]
-};
-
-var g_dragging = false;
-
-function startDragging(e) {
- g_lastRot = g_thisRot;
- g_aball.click([e.x, e.y]);
- g_dragging = true;
-}
-
-function drag(e) {
- if (g_dragging) {
- var rotationQuat = g_aball.drag([e.x, e.y]);
- var rot_mat = g_quaternions.quaternionToRotation(rotationQuat);
- g_thisRot = g_math.matrix4.mul(g_lastRot, rot_mat);
- var m = g_root.localMatrix;
- g_math.matrix4.setUpper3x3(m, g_thisRot);
- g_root.localMatrix = m;
-
- updateClient();
- }
-}
-
-function stopDragging(e) {
- g_dragging = false;
-}
-
-function updateClient() {
- // If we are in RENDERMODE_ON_DEMAND mode then set the render mode again
- // which will cause the client re-render the display.
- if (g_client.renderMode == g_o3d.Client.RENDERMODE_ON_DEMAND) {
- g_client.render();
- }
-}
-
-function scrollMe(e) {
- if (e.deltaY) {
- g_camera.eye =
- g_math.mulScalarVector((e.deltaY < 0 ? 11 : 13) / 12, g_camera.eye);
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(g_camera.eye,
- g_camera.target,
- [0, 1, 0]);
- updateClient();
- }
-}
-
-function loadFile(path) {
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + path + '\n' + exception);
- return;
- }
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
- }
- // Create a new transform for the loaded file
- var parent = g_pack.createObject('Transform');
- parent.parent = g_client.root;
-
- if (path != null) {
- o3djs.scene.loadScene(g_client, g_pack, parent, path, callback);
- }
-
- return parent;
-}
-
-function setClientSize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- // Set the perspective projection matrix
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), g_o3dWidth / g_o3dHeight, 0.1, 100);
-
- // Sets a new area size for arcball.
- g_aball.setAreaSize(g_o3dWidth, g_o3dHeight);
-
- //o3djs.dump.dump("areaWidth: " + g_o3dWidth + "\n");
- //o3djs.dump.dump("areaHeight: " + g_o3dHeight + "\n");
- }
-}
-
-function resize() {
- setClientSize();
-}
-
-function setRenderMode(event) {
- var mode = (event) ? event.target.value : window.event.srcElement.value;
- switch (mode) {
- case 'continuous':
- g_client.renderMode = g_o3d.Client.RENDERMODE_CONTINUOUS;
- break;
- case 'ondemand':
- g_client.renderMode = g_o3d.Client.RENDERMODE_ON_DEMAND;
- break;
- }
-}
-
-function onRender() {
- g_framesRendered++;
- g_viewInfo.clearBuffer.clearColor = [
- 1 / 38 * (g_framesRendered % 38),
- 1 / 39 * (g_framesRendered % 39),
- 1 / 41 * (g_framesRendered % 41),
- 1];
- resize();
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- path = path.substring(0, index + 1) + 'assets/teapot.o3dtgz';
-
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_quaternions = o3djs.quaternions;
- g_client = g_o3dElement.client;
-
- g_pack = g_client.createPack();
- g_lastRot = g_math.matrix4.identity();
- g_thisRot = g_math.matrix4.identity();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- var root = g_client.root;
-
- var target = [0, 0, 0];
- var eye = [0, 0, 5];
- var up = [0, 1, 0];
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(eye, target, up);
-
- g_aball = o3djs.arcball.create(100, 100);
- setClientSize();
-
- g_root = loadFile(path);
-
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', startDragging);
- o3djs.event.addEventListener(g_o3dElement, 'mousemove', drag);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', stopDragging);
- o3djs.event.addEventListener(g_o3dElement, 'wheel', scrollMe);
- document.getElementById('rendermode0').onclick = setRenderMode;
- document.getElementById('rendermode1').onclick = setRenderMode;
-
- g_client.setRenderCallback(onRender);
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-<table width="100%" style="height:100%;">
-<tr width="100%" style="height:100%;"><td valign="middle" align="center">
-<h1>
-Render Mode Example.
-</h1>
-<p>The point of this demo is to show that for certain kinds of 3d applications
- that don't have animation, for example a map viewer, you can set the client's
-render mode to RENDERMODE_ON_DEMAND which will render the 3d one time and then
-stop rendering. This has the advantage of not wasting CPU cycles rendering
-something that does not change over and over.</p>
-<p>The background changes color each time the scene is rendered. The sample
-should start with the scene being constantly rendered but click
-RENDERMODE_ON_DEMAND and you'll see it rendered only when it needs to be
-as determined by the sample. </p>
-<table id="container" width="90%" height="60%" border="2">
-<tr height="100%"><td>
-<div id="o3d" style="width: 100%; height: 100%;"></div>
-</td></tr>
-</table>
-<input type="radio" id="rendermode0" name="rendermode" value="continuous" checked="true"><label for="rendermode0">RENDERMODE_CONTINUOUS (draw as often as possible)</label><br/>
-<input type="radio" id="rendermode1" name="rendermode" value="ondemand"><label for="rendermode1">RENDERMODE_ON_DEMAND (draw once then as the OS requests it like when a window is uncovered)</label><br/>
-<p>
-Drag The Mouse To Rotate<br/>
-Scrollwheel To Zoom<br/>
-Resize The Window To Resize The View
-</p>
-</td></tr></table>
-</body>
-</html>
-
-
diff --git a/o3d/samples/render-targets.html b/o3d/samples/render-targets.html
deleted file mode 100644
index 11abc0b..0000000
--- a/o3d/samples/render-targets.html
+++ /dev/null
@@ -1,340 +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 sample shows how to setup a basic render graph making use of RenderSurface
-nodes to implement render-target functionality.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-O3D: Render-Target Sample
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.scene');
-
-// constants.
-var RENDER_TARGET_WIDTH = 512;
-var RENDER_TARGET_HEIGHT = 512;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_teapotPack;
-var g_teapotRoot;
-var g_cubeRoot;
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo who's view and projection will
- * be set from the scene after it's loaded.
- */
-function loadScene(pack, fileName, parent, viewInfo) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT);
-
- // Copy the view and projection to the passed in viewInfo structure..
- viewInfo.drawContext.view = cameraInfo.view;
- viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, viewInfo);
-
- window.g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- // These are here so that they are visible to both the browser (so
- // selenium sees them) and the embedded V8 engine.
- window.g_clock = 0;
- window.g_timeMult = 1;
- window.g_finished = false; // for selenium testing.
-
- // Comment out the line below to run the sample in the browser
- // JavaScript engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3d = clientElements[0];
- g_o3d = o3d.o3d;
- g_math = o3djs.math;
-
- // Set window.g_client as well. Otherwise when the sample runs in
- // V8, selenium won't be able to find this variable (it can only see
- // the browser environment).
- window.g_client = g_client = o3d.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create a sub-pack to manage the resources required for the teapot.
- g_teapotPack = g_client.createPack();
-
- // Create the texture required for the color render-target.
- var texture2d = g_pack.createTexture2D(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT,
- g_o3d.Texture.XRGB8, 1, true);
- var renderSurface = texture2d.getRenderSurface(0);
-
- // Create the depth-stencil buffer required when rendering the teapot.
- var depthSurface = g_pack.createDepthStencilSurface(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT);
-
- g_cubeRoot = g_pack.createObject('Transform');
- g_teapotRoot = g_pack.createObject('Transform');
- g_cubeRoot.parent = g_client.root;
- g_teapotRoot.parent = g_client.root;
-
- var teapotRenderRoot = g_pack.createObject('RenderNode');
- teapotRenderRoot.priority = 0;
- var cubeRenderRoot = g_pack.createObject('RenderNode');
- cubeRenderRoot.priority = 1;
-
- teapotRenderRoot.parent = g_client.renderGraphRoot;
- cubeRenderRoot.parent = g_client.renderGraphRoot;
-
- var renderSurfaceSet = g_pack.createObject('RenderSurfaceSet');
- renderSurfaceSet.renderSurface = renderSurface;
- renderSurfaceSet.renderDepthStencilSurface = depthSurface;
- renderSurfaceSet.parent = teapotRenderRoot;
-
- // Create the render graph for a view.
- var teapotViewInfo = o3djs.rendergraph.createBasicView(
- g_teapotPack,
- g_teapotRoot,
- renderSurfaceSet);
-
- var cubeViewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_cubeRoot,
- cubeRenderRoot);
-
- var myMaterial = g_pack.createObject('Material');
- myMaterial.drawList = cubeViewInfo.performanceDrawList;
-
- var effect = g_pack.createObject('Effect');
- var fxString = o3djs.util.getElementContentById('fx');
- effect.loadFromFXString(fxString);
-
- // Apply our effect to this material.
- myMaterial.effect = effect;
- effect.createUniformParameters(myMaterial);
-
- var samplerParam = myMaterial.getParam('texSampler0');
- var sampler = g_pack.createObject('Sampler');
- sampler.texture = texture2d;
- samplerParam.value = sampler;
-
- // Create a transform to put our data on.
- var myDataRoot = g_pack.createObject('Transform');
-
- // Connect our root to the client.
- myDataRoot.parent = g_teapotRoot;
- var vec3 = [0.5, 0.5, 0.5];
-
- var cubeShape = o3djs.primitives.createCube(g_pack,
- myMaterial,
- 300.0);
-
- // Attach the cube to the root of the transform graph.
- g_cubeRoot.addShape(cubeShape);
-
- o3djs.pack.preparePack(g_pack, cubeViewInfo);
-
- // Points at the origin.
- var target = [0, 0, 0];
- // Puts the camera outside the origin.
- var eye = [500, 500, 500];
- // Defines UP as Y up.
- var up = [0, 1, 0];
- cubeViewInfo.drawContext.view = g_math.matrix4.lookAt(eye,
- target,
- up);
-
- cubeViewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30),
- g_client.width / g_client.height, 1, 5000);
-
- // Load the scene into the transform graph as a child myDataRoot
- loadScene(g_teapotPack, 'assets/teapot.o3dtgz', myDataRoot, teapotViewInfo);
-
- // Set a render callback.
- g_client.setRenderCallback(onRender);
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- // Update g_clock in the browser and cache a V8 copy that can be
- // accessed efficiently. g_clock must be in the browser for selenium.
- var clock = window.g_clock + elapsedTime * window.g_timeMult;
- window.g_clock = clock;
-
- g_teapotRoot.identity();
- g_teapotRoot.rotateX(clock);
- g_teapotRoot.rotateY(clock * 1.3);
-
- g_cubeRoot.identity();
- g_cubeRoot.rotateX(clock * 0.4);
- g_cubeRoot.rotateY(clock * 0.1);
-}
-
-/**
- * Cleanup before exiting.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body onload="init()" onunload="unload()">
-<h1>Basic Render-Target Example</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<!--
- We embed the code for our effect inside this hidden textarea.
- Effects contain the functions that define
- the vertex and pixel shaders used by our shape.
--->
-<!-- Don't render the textarea -->
-<div style="display:none">
-<textarea id="fx" name="fx" cols="80" rows="20">
- // The 4x4 world view projection matrix.
- float4x4 viewProjection : WorldViewProjection;
-
- sampler texSampler0;
-
- // input parameters for our vertex shader
- struct VertexShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0;
- };
-
- // input parameters for our pixel shader
- // also the output parameters for our vertex shader
- struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0;
- };
-
- /**
- * Vertex Shader performing basic viewing transformation.
- */
- PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- /**
- * We transform each vertex by the view projection matrix to bring
- * it from world space to projection space.
- *
- * We return its color unchanged.
- */
- PixelShaderInput output;
-
- output.position = mul(input.position, viewProjection);
- output.texcoord = input.texcoord;
- return output;
- }
- /**
- * Pixel Shader
- */
- float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return tex2D(texSampler0, input.texcoord * 5) + float4(0.2, 0.2, 0.0, 1.0);
- }
-
- // Here we tell our effect file the functions which specify our vertex
- // and pixel shaders.
- // #o3d VertexShaderEntryPoint vertexShaderFunction
- // #o3d PixelShaderEntryPoint pixelShaderFunction
- // #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
-
-</html>
diff --git a/o3d/samples/rotatemodel.html b/o3d/samples/rotatemodel.html
deleted file mode 100644
index 9cc8143..0000000
--- a/o3d/samples/rotatemodel.html
+++ /dev/null
@@ -1,247 +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.
--->
-
-<!--
-O3D Tutorial A2
-
-In this tutorial, we show how to perform transformations on a scene that
-we have loaded.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Tutorial A2: Transformations
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.scene');
-
-// Events
-// Run the init() function once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_keyPressDelta = 0.05;
-var g_finished = false; // for selenium testing
-
-// root node of scene
-var g_sceneRoot;
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- */
-function loadScene(pack, fileName, parent) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- g_client.width,
- g_client.height);
-
- // Copy the view and projection to the draw context.
- g_viewInfo.drawContext.view = cameraInfo.view;
- g_viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
-
- g_finished = true; // for selenium testing
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create a transform node to act as the 'root' of the scene
- g_sceneRoot = g_pack.createObject('Transform');
- // Attach it to the root of the transform graph.
- g_sceneRoot.parent = g_client.root;
-
- // Load the scene into the transform graph as a child of the g_sceneRoot.
- loadScene(g_pack, 'assets/teapot.o3dtgz', g_sceneRoot);
-
- // Execute keyPressedCallback(..) when we detect a keypress on the document.
- window.document.onkeypress = keyPressedCallback;
-}
-
-/**
- * Function performing the rotate action in response to a key-press.
- * Rotates the scene based on key pressed. (w ,s, a, d). Note that the x and
- * y-axis referenced here are relative to the current view of the scene.
- * @param {keyPressed} The letter pressed, in lower case.
- * @param {delta} The angle by which the scene should be rotated.
- * @return true if an action was taken.
- */
-function keyPressedAction(keyPressed, delta) {
- var actionTaken = false;
- switch(keyPressed) {
- case 'a':
- g_sceneRoot.localMatrix =
- g_math.matrix4.mul(g_sceneRoot.localMatrix,
- g_math.matrix4.rotationY(-delta));
- actionTaken = true;
- break;
- case 'd':
- g_sceneRoot.localMatrix =
- g_math.matrix4.mul(g_sceneRoot.localMatrix,
- g_math.matrix4.rotationY(delta));
- actionTaken = true;
- break;
- case 'w':
- g_sceneRoot.localMatrix =
- g_math.matrix4.mul(g_sceneRoot.localMatrix,
- g_math.matrix4.rotationX(-delta));
- actionTaken = true;
- break;
- case 's':
- g_sceneRoot.localMatrix =
- g_math.matrix4.mul(g_sceneRoot.localMatrix,
- g_math.matrix4.rotationX(delta));
- actionTaken = true;
- break;
- }
- return actionTaken;
-}
-
-/**
- * Callback for the keypress event.
- * Invokes the action to be performed for the key pressed.
- * @param {event} keyPress event passed to us by javascript.
- */
-function keyPressedCallback(event) {
- event = event || window.event;
-
- // Ignore accelerator key messages.
- if (event.metaKey)
- return;
-
- var keyChar = String.fromCharCode(o3djs.event.getEventKeyChar(event));
- // Just in case they have capslock on.
- keyChar = keyChar.toLowerCase();
-
- if (keyPressedAction(keyChar, g_keyPressDelta)) {
- o3djs.event.cancel(event);
- }
-}
-
-/**
- * Resets the view of the scene by resetting its local matrix to the identity
- * matrix.
- */
-function resetView() {
- g_sceneRoot.identity();
-}
-
-</script>
-</head>
-<body>
-<h1>Transformations</h1>
-This tutorial shows how to perform transformations on a scene that
-has been loaded.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<p>Use W, S, A, D to rotate.</p>
-<form name="default_form" action="#" method="get">
-<input type="button" value="Reset view" onclick="resetView()" />
-<input type="button" value="W" id="W"
- onclick="keyPressedAction('w', g_keyPressDelta);" />
-<input type="button" value="S" id="S"
- onclick="keyPressedAction('s', g_keyPressDelta);" />
-<input type="button" value="A" id="A"
- onclick="keyPressedAction('a', g_keyPressDelta);" />
-<input type="button" value="D" id="D"
- onclick="keyPressedAction('d', g_keyPressDelta);" />
-</form>
-</body>
-</html>
diff --git a/o3d/samples/sampler_index.html b/o3d/samples/sampler_index.html
deleted file mode 100644
index b080a7c..0000000
--- a/o3d/samples/sampler_index.html
+++ /dev/null
@@ -1,187 +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.
--->
-
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
- <meta http-equiv="content-type" content="text/html; charset=UTF-8">
-
- <script src="interactive_sampler_assets/utils.js" type="text/javascript" charset="utf-8"></script>
-
- <!-- CSS -->
- <link rel="stylesheet" href="third_party/lightbox/lightbox.css"
- media="screen,projection" type="text/css" />
-
- <!--[if !IE]><!-->
- <link rel="stylesheet" href="interactive_sampler_assets/styles.css" media="screen,projection" type="text/css" />
- <!-- <![endif]-->
- <!--[if IE]>
- <link rel="stylesheet" href="interactive_sampler_assets/styles_ie.css" media="screen,projection" type="text/css" />
- <![endif]-->
-
- <!-- JavaScript -->
-
- <title>O3D Interactive Sampler</title>
-
- <script type="text/javascript"
- src="third_party/lightbox/prototype.js"></script>
- <script type="text/javascript"
- src="third_party/lightbox/lightbox-iframe.js"></script>
- <script src="third_party/codemirror/js/codemirror.js" type="text/javascript"
- charset="utf-8"></script>
- <link rel="stylesheet" type="text/css"
- href="third_party/codemirror/css/docs.css"/>
-
- <script type="text/javascript" charset="utf-8">
-
- var is;
-
- function init() {
-
- is = new InteractiveSample();
- is.init(document.getElementById('editor'));
- }
-
- function showInline() {
- _gel('outputContainer').style.display = 'table-cell';
- var codeContainer = _gel('codeContainer');
- var codeIframe = codeContainer.getElementsByTagName('iframe')[0];
- codeIframe.style.width = "100%";
- }
-
-
- addEvent(window, 'load', init);
- </script>
-</head>
-<body>
- <div id="container">
- <div class="bluediv">
- <table style="width:100%;">
- <tr>
- <td>
- <h1 id="header">Client 3D Interactive Samples</h1>
- </td>
- <td id="googleLogoTD">
- <img src="interactive_sampler_assets/images/google-small.png" />
- </td>
- </tr>
- </table>
-
- </div>
-
- <div id="content">
- <table class="contentTable">
- <tr>
-
- <td id="selectContainer">
- <h2>Pick</h2>
- <div id="selectCode">
- </div>
-
- </td>
-
- <td id="codeContainer">
- <h2>Edit</h2>
-
- <div id="tab_bar">
- </div>
-
- <div id="button_bar">
- &nbsp;
- <!-- <input type="button" value="<- | ->" onclick="is.increaseWidth();" /> -->
- <!-- <input type="button" value="-" onclick="is.decreaseCodeBoxHeight();" />
- <input type="button" value="+" onclick="is.increaseCodeBoxHeight();"/> -->
- </div>
-
- <!-- todo check styles on here -->
- <div id="editor" style="border: 1px solid black; margin-top: 2px"></div>
- </td>
- <script type="text/javascript" charset="utf-8">
- var htmlEditor = new CodeMirror(document.getElementById('editor'), {
- parserfile : 'parsexml.js',
- stylesheet : 'third_party/codemirror/css/xmlcolors.css',
- path : 'third_party/codemirror/js/',
- height : '550px',
- content: ''
- });
-
- var jsEditor = new CodeMirror(document.getElementById('editor'), {
- parserfile : ["tokenizejavascript.js", "parsejavascript.js"],
- stylesheet : 'third_party/codemirror/css/jscolors.css',
- autoMatchParens : true,
- path : 'third_party/codemirror/js/',
- height : '550px',
- content: ''
- });
-
- jsEditor.frame.style.display = 'none';
-
- </script>
- <td id="outputContainer">
- <h2>Run</h2>
- <div style="width: 300px;margin-top:18px;">
- <a href="iframeit.html" style="text-decoration: none"
- class="lbOn"><input type="button" value="Run In New Window" onclick="is.prepareAllCodeRun();" /></a>
- <input type="button" id="runHere" value="Run Here" onclick="is.runJS();" />
- <div id="o3d" style="width: 300px; height: 300px; background: gray;"></div></div>
- </td>
-
-
- </tr>
-
-
-
- <tr>
- <td class="footer">
- <div style="background-image: url(interactive_sampler_assets/images/sprites.gif);background-position: -28px -28px;height:53px;margin:12px 0pt;width:143px;"></div>
- </td>
- <td class="footer" style="vertical-align: middle; font-size:80%; text-align: center">
- ©2008 Google -
- <a href="http://code.google.com/">Code Home</a> - <a href="http://www.google.com/accounts/TOS">Site Terms of Service</a> -
- <a href="http://www.google.com/privacy.html">Privacy Policy</a> -
- <a href="http://code.google.com/more/">Site Directory</a>
- </td>
- </tr>
- </table>
- </div>
-</div>
-
-<div id="HTMLforInlineJavascript" style="display:none;"></div>
-
-
-<!-- Scripts at bottom means better loading time ! -->
-<!-- <script src="codepress/codepress.js" type="text/javascript"></script> -->
-<script src="interactive_samples.js" type="text/javascript" charset="utf-8"></script>
-<script src="interactive_logic.js" type="text/javascript" charset="utf-8"></script>
-</body>
-</html>
diff --git a/o3d/samples/samples.gyp b/o3d/samples/samples.gyp
deleted file mode 100644
index 57a3f87..0000000
--- a/o3d/samples/samples.gyp
+++ /dev/null
@@ -1,131 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- },
- 'includes': [
- '../build/common.gypi',
- ],
- 'targets': [
- {
- 'target_name': 'install_samples',
- 'type': 'none',
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)/samples',
- 'files': [
- '2d.html',
- 'animated-scene.html',
- 'animation.html',
- 'bitmap-draw-image.html',
- 'billboards.html',
- 'canvas-texturedraw.html',
- 'canvas.html',
- 'convolution.html',
- 'culling.html',
- 'customcamera.html',
- 'displayfps.html',
- 'error-texture.html',
- 'generate-texture.html',
- 'hellocube-colors.html',
- 'hellocube-textures.html',
- 'hellocube.html',
- 'helloworld.html',
- 'hud-2d-overlay.html',
- 'instance-override.html',
- 'instancing.html',
- 'juggler.html',
- 'julia.html',
- 'multiple-clients.html',
- 'multiple-views.html',
- 'old-school-shadows.html',
- 'particles.html',
- 'phongshading.html',
- 'picking.html',
- 'primitives.html',
- 'procedural-texture.html',
- 'render-mode.html',
- 'render-targets.html',
- 'rotatemodel.html',
- 'scatter-chart.html',
- 'shader-test.html',
- 'simple.html',
- 'simpletexture.html',
- 'skinning.html',
- 'sobel.html',
- 'stencil_example.html',
- 'texturesamplers.html',
- 'tutorial-primitive.html',
- 'vertex-shader.html',
- 'vertex-shader-animation.html',
- 'zsorting.html'
- ]
- },
- ],
- },
- {
- # TODO(petersont): tie in the copying of this to the doc
- # generation process, compile the sources, etc.
- 'target_name': 'install_webgl_js',
- 'type': 'none',
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)/samples/o3djs',
- 'files': [
- 'o3djs/webgl.js',
- ]
- },
- ],
- },
- {
- # TODO(petersont): tie in the copying of these to the doc
- # generation process, compile the sources, etc.
- 'target_name': 'install_o3d_webgl',
- 'type': 'none',
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)/samples',
- 'files': [
- 'o3d-webgl/',
- ]
- },
- ],
- },
- {
- # TODO(petersont): consider picking and choosing the files taken
- # from this directory. Note that some of the samples are copied
- # via the list above, and some are copied by virtue of being in
- # the MANIFEST file in this directory (see samples_gen.py).
- 'target_name': 'install_o3d_webgl_samples',
- 'type': 'none',
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)/samples',
- 'files': [
- 'o3d-webgl-samples/',
- ]
- },
- ],
- },
- {
- 'target_name': 'samples',
- 'type': 'none',
- 'dependencies': [
- 'install_samples',
- 'install_webgl_js',
- 'install_o3d_webgl',
- 'install_o3d_webgl_samples',
- '<!(python samples_gen.py):build_samples',
- ],
- },
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/samples/samples_gen.py b/o3d/samples/samples_gen.py
deleted file mode 100644
index 7184811..0000000
--- a/o3d/samples/samples_gen.py
+++ /dev/null
@@ -1,240 +0,0 @@
-#!/usr/bin/env python
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# This script generates gyp code to build the contents of the assets directory.
-
-import posixpath
-import sys
-import os.path
-
-output_filename = 'samples_gen.gyp'
-
-# Set to true to make json output more human readable.
-pretty_print = False
-
-try:
- output_file = open(output_filename, "w+")
-except IOError:
- sys.stderr.write('Unable to write to generated gyp file %s\n',
- output_filename)
-
-x_up = '1,0,0'
-y_up = '0,1,0'
-z_up = '0,0,1'
-
-names = {
- x_up : 'x_up',
- y_up : 'y_up',
- z_up : 'z_up',
-}
-
-assets = [
- {'path': 'GoogleIO-2009/convert_assets/background.zip', 'up': y_up},
- {'path': 'GoogleIO-2009/convert_assets/character.zip', 'up': y_up},
- {'path': 'beachdemo/convert_assets/beach-low-poly.dae', 'up': z_up},
- {'path': 'beachdemo/convert_assets/beachdemo.zip', 'up': z_up},
- {'path': 'convert_assets/dome1.zip', 'up': y_up},
- {'path': 'convert_assets/dome2.zip', 'up': y_up},
- {'path': 'convert_assets/dome3.zip', 'up': y_up},
- {'path': 'convert_assets/dome4.zip', 'up': y_up},
- {'path': 'convert_assets/kitty_151_idle_stand05_cff1.zip', 'up': y_up},
- {'path': 'convert_assets/part1.zip', 'up': y_up},
- {'path': 'convert_assets/part2.zip', 'up': y_up},
- {'path': 'convert_assets/part3.zip', 'up': y_up},
- {'path': 'convert_assets/seven_shapes.zip', 'up': y_up, 'webgl': True},
- {'path': 'convert_assets/stencil_frame.zip', 'up': y_up},
- {'path': 'convert_assets/teapot.zip', 'up': y_up, 'webgl': True},
- {'path': 'convert_assets/yard.zip', 'up': y_up, 'webgl': True},
- {'path': 'home-configurators/convert_cbassets/Agra_Rug.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Asimi_Rug.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Camden_Chair.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Elements_Bookshelf.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Ferrara_Rug.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/House_Roofless.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Lounge_Chair.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Lounge_Chaise.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Lounge_Sofa.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Lounge_Storage_Ottoman.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Madison_Dining_Table.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Miles_Side_Chair.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Pullman_Bar_Stool.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Puzzle_TV_Stand.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Stow_Leather_Ottoman.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Tivoli_Dining_Table.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Tivoli_Miles_Dining_Set.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Troy_Chair.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Troy_Ottoman.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Troy_Sofa.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Troy_Storage_Ottoman.kmz', 'up': z_up},
- {'path': 'home-configurators/convert_cbassets/Troy_Twin_Sleeper.kmz', 'up': z_up},
- {'path': 'io/convert_levels/all_actors.kmz', 'up': y_up},
- {'path': 'io/convert_levels/map1.kmz', 'up': y_up},
- {'path': 'simpleviewer/convert_assets/cube.zip', 'up': y_up, 'webgl': True}
-]
-
-output_file.write("""# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# THIS FILE IS AUTOMATICALLY GENERATED by the script samples_gen.py Do not
-# edit this file. Instead edit samples_gen.py.
-
-{
- 'variables': {
- 'chromium_code': 1,
- },
- 'includes': [
- '../build/common.gypi',
- ],
- 'targets': [
- {
- 'target_name': 'convert_samples',
- 'type': 'none',
- 'dependencies': [
- '../converter/converter.gyp:o3dConverter',
- ],
- 'actions': [\n""")
-
-def write_action(asset, webgl_mode):
- filename = posixpath.splitext(posixpath.basename(asset['path']))[0]
- filename = filename.replace('.','_')
- filename = filename.replace('-','_')
- filename = filename.lower()
- name = "convert_" + filename
- if webgl_mode:
- name = name + "_webgl"
- output = asset['path'].replace('convert_', '')
- output_base = posixpath.splitext(output)[0]
- output_tgz = output_base + ".o3dtgz"
- output_json = output_base + "/scene.json"
-
- output = output_tgz
- if webgl_mode:
- output = output_json
- output_dir = posixpath.dirname(output)
-
- output_file.write(" {\n")
- output_file.write(" 'action_name': '%s',\n" % name)
- output_file.write(" 'inputs': [\n")
- output_file.write(" '<(PRODUCT_DIR)/o3dConverter',\n")
- # TODO(kbr): there are a couple of problems with gyp's MSVC
- # generator which require this workaround right now. First, if two
- # actions have the same inputs then gyp will arbitrarily hang the
- # custom build rule off the second input, and the collision will
- # currently cause one or the other rule to be dropped. Second, if we
- # just insert a fake second input, without removing the .zip, then
- # for some reason the .zip ends up in an "_excluded_files" folder in
- # the project and the non-WebGL version of the asset won't be built.
- # Here we use a different input for the WebGL version of the assets.
- if webgl_mode:
- output_file.write(" '../o3d_assets/samples/%s.fake_webgl_input.txt',\n" % asset['path'])
- else:
- output_file.write(" '../o3d_assets/samples/%s',\n" % asset['path'])
- output_file.write(" ],\n")
- output_file.write(" 'outputs': [\n")
- if sys.platform[:5] == 'linux':
- # TODO(gspencer): This is a HACK! We shouldn't need to put the
- # absolute path here, but currently on Linux (scons), it is unable
- # to copy generated items out of the source tree (because the
- # repository mojo fails to find it and puts in the wrong path).
- output_file.write(" '%s',\n" % posixpath.abspath(output))
- else:
- output_file.write(" '../samples/%s',\n" % output)
- output_file.write(" ],\n")
- output_file.write(" 'action': [\n")
- output_file.write(" '<(PRODUCT_DIR)/o3dConverter',\n")
- output_file.write(" '--no-condition',\n")
- output_file.write(" '--up-axis=%s',\n" % asset['up'])
- if pretty_print:
- output_file.write(" '--pretty-print',\n")
- if webgl_mode:
- output_file.write(" '--no-binary',\n")
- output_file.write(" '--no-archive',\n")
- output_file.write(" '--convert-dds-to-png',\n")
- output_file.write(" '--convert-cg-to-glsl',\n")
- output_file.write(" '../o3d_assets/samples/%s',\n" % asset['path'])
- if webgl_mode:
- output_file.write(" '../samples/%s',\n" % output_tgz)
- else:
- output_file.write(" '<(_outputs)',\n")
- output_file.write(" ],\n")
- output_file.write(" },\n")
-
-for asset in assets:
- write_action(asset, False)
- if asset.has_key('webgl'):
- write_action(asset, True)
-
-output_file.write(""" ],
- },
- {
- 'target_name': 'copy_samples',
- 'type': 'none',
- 'dependencies': [
- 'convert_samples',
- ],
- 'copies': [\n""")
-
-# Coalesce copies by directory so we don't have tons of copies rules
-# to parse.
-copies = {}
-for asset in assets:
- output = asset['path'].replace('convert_', '')
- output = posixpath.splitext(output)[0] + ".o3dtgz"
- output_dir = posixpath.dirname(output)
- if output_dir in copies:
- # Make sure we don't add any twice.
- if not output in copies[output_dir]:
- copies[output_dir] += [output]
- else:
- copies[output_dir] = [output]
-
-# Add in all the MANIFEST files to be copied,
-# Skipping the ones in the assets above (if any).
-items = eval(open("MANIFEST", "r").read())
-if not os.path.exists("../../o3d-internal/jscomp/JSCompiler_deploy.jar"):
- # add in the o3djs files.
- js_files = eval(open("o3djs/js_list.manifest", "r").read())
- js_files = ["o3djs/" + f for f in js_files]
- items = items + js_files
-for item in items:
- item_dir = posixpath.dirname(item)
- if item_dir in copies:
- if not item in copies[item_dir]:
- copies[item_dir] += [item]
- else:
- copies[item_dir] = [item]
-
-for (dir, paths) in copies.items():
- output_file.write(" {\n")
- output_file.write(" 'destination': " \
- "'<(PRODUCT_DIR)/samples/%s',\n" % dir)
- output_file.write(" 'files': [\n")
- for path in paths:
- if sys.platform[:5] == 'linux':
- # TODO(gspencer): This is a HACK! We shouldn't need to put the
- # absolute path here, but currently on Linux (scons), it is unable
- # to copy generated items out of the source tree (because the
- # repository mojo fails to find it and puts in the wrong path).
- output_file.write(" '%s',\n" % posixpath.abspath(path))
- else:
- output_file.write(" '../samples/%s',\n" % path)
- output_file.write(" ],\n")
- output_file.write(" },\n")
-
-output_file.write(" ],\n")
-output_file.write(" },\n")
-output_file.write(""" {
- 'target_name': 'build_samples',
- 'type': 'none',
- 'dependencies': [
- 'copy_samples',
- ],
- },\n""")
-output_file.write(" ],\n")
-output_file.write("}\n")
-
-print output_filename
-sys.exit(0)
diff --git a/o3d/samples/scatter-chart.html b/o3d/samples/scatter-chart.html
deleted file mode 100644
index 6aa7743..0000000
--- a/o3d/samples/scatter-chart.html
+++ /dev/null
@@ -1,398 +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.
--->
-
-<!--
-Scatter Chart Example
-
-This sample demonstrates how to plot a 3d scatter chart and how to rotate and zoom it
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-3D Scatter Chart
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" src="assets/teapot_vertices.js"></script>
-
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.arcball');
-o3djs.require('o3djs.event');
-
-// The initClient() function runs when the page has finished loading.
-window.onload = initClient;
-
-// global variables
-var g_o3dElement;
-var g_client;
-var g_o3d;
-var g_math;
-var g_quaternions;
-var g_pack;
-var g_viewInfo;
-var g_modelRoot;
-var g_eyeView;
-var g_cubeShape;
-var g_material;
-var g_aball;
-var g_thisRot;
-var g_lastRot;
-var g_zoomFactor;
-var g_dragging;
-var g_finished = false; // for selenium testing.
-
-/**
- * Creates the client area.
- */
-function initClient() {
- o3djs.util.makeClients(main);
-}
-
-/**
- * Initializes global variables, positions camera, draws the 3D chart.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function main(clientElements) {
- // Init global variables.
- initGlobals(clientElements);
-
- // Set up the view and projection transformations.
- initContext();
-
- // Setup rendering on demand only.
- g_client.renderMode = g_o3d.Client.RENDERMODE_ON_DEMAND;
-
- // Add the 3D chart model to the transform hierarchy.
- create3dChartModel();
-
- // Start rendering.
- g_client.render();
-
- // Execute keyPressed(..) when we detect a keypress on the window or
- // on the o3d object.
- window.document.onkeypress = keyPressed;
- g_o3dElement.onkeypress = keyPressed;
-
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', startDragging);
- o3djs.event.addEventListener(g_o3dElement, 'mousemove', drag);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', stopDragging);
- o3djs.event.addEventListener(g_o3dElement, 'wheel', scrollMe);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Initializes global variables and libraries.
- */
-function initGlobals(clientElements) {
- // init o3d globals.
- g_o3dElement = clientElements[0];
- g_client = g_o3dElement.client;
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_quaternions = o3djs.quaternions;
-
- // Create an arcball.
- g_aball = o3djs.arcball.create(g_o3dElement.clientWidth,
- g_o3dElement.clientHeight);
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create a transform node to act as the 'root' of the model.
- // Attach it to the root of the transform graph.
- g_modelRoot = g_pack.createObject('Transform');
- g_modelRoot.parent = g_client.root;
-
- // Create the render graph for the view.
- var clearColor = [.98, .98, .98, 1];
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot,
- clearColor);
-
- // Create a material for the objects rendered.
- g_material = o3djs.material.createBasicMaterial(
- g_pack, g_viewInfo, [1, 1, 1, 1]);
-
- // Create a cube shape to simulate the scatter points.
- g_cubeShape = o3djs.primitives.createCube(
- g_pack,
- g_material,
- 1);
-}
-
-/**
- * Initialize the original view of the model.
- */
-function initContext() {
- g_eyeView = [-35, 60, 140];
- g_zoomFactor = 1.03;
- g_dragging = false;
- g_modelRoot.identity();
- g_lastRot = g_math.matrix4.identity();
- g_thisRot = g_math.matrix4.identity();
-
- // Set up a perspective transformation for the projection.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(40), // 30 degree frustum.
- g_o3dElement.clientWidth / g_o3dElement.clientHeight, // Aspect ratio.
- 1, // Near plane.
- 10000); // Far plane.
-
- // Set up our view transformation to look towards the axes origin.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- g_eyeView, // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Reset to the original view of the model.
- */
-function resetView() {
- initContext();
- g_client.render();
-}
-
-/**
- * Create a 3D Scatter object by plotting each data point on a 3D model.
- */
-function createScatterObject() {
- // size of a scatter point (represented as a small cube).
- var pointSize = 0.5;
-
- for (var i = 0; i < g_teapotVertices.length; i += 3) {
- var varX = g_teapotVertices[i];
- var varY = g_teapotVertices[i+2];
- var varZ = g_teapotVertices[i+1];
-
- // create the transform for the cube.
- var transform = g_pack.createObject('Transform');
- transform.parent = g_modelRoot;
- transform.addShape(g_cubeShape);
- // translate and scale the point correctly relative to origin
- transform.translate(varX, varY, varZ);
- transform.scale(pointSize, pointSize, pointSize);
- transform.createParam('diffuse', 'ParamFloat4').value = [1, 0, 0, 1];
- }
-}
-
-/**
- * Creates a 3D chart model.
- */
-function create3dChartModel() {
- // create the x,y,z axes - use the cylinder primitive.
- var cylinder_length = 90;
- var cylinder_radius = 0.15;
- var cylinder_subdivisions = 6;
-
- var cylinder = o3djs.primitives.createCylinder(
- g_pack,
- g_material,
- cylinder_radius, // Radius.
- cylinder_length, // Depth.
- cylinder_subdivisions, // Number of subdivisions.
- 1);
-
- var cylinder_x = g_pack.createObject('Transform');
- cylinder_x.parent = g_modelRoot;
- cylinder_x.addShape(cylinder);
- cylinder_x.createParam('diffuse', 'ParamFloat4').value = [1, 0.2, 0.2, 1];
- cylinder_x.rotateZ(Math.PI / 2);
-
- var cylinder_y = g_pack.createObject('Transform');
- cylinder_y.parent = g_modelRoot;
- cylinder_y.addShape(cylinder);
- cylinder_y.createParam('diffuse', 'ParamFloat4').value = [0.2, 1, 0.2, 1];
- cylinder_y.rotateX(Math.PI / 2);
-
- var cylinder_z = g_pack.createObject('Transform');
- cylinder_z.parent = g_modelRoot;
- cylinder_z.addShape(cylinder);
- cylinder_z.createParam('diffuse', 'ParamFloat4').value = [0.2, 0.2, 1, 1];
-
- // Create the scatter object.
- createScatterObject();
-}
-
-/**
- * Callback for the keypress event.
- * Rotates the 3D model along the x, y or z-axes based on key pressed.
- * Zooms in and out by moving the viewpoint.
- * @param {event} event keyPress event passed to us by javascript.
- */
-function keyPressed(event) {
- event = event || window.event;
-
- // Ignore accelerator key messages.
- if (event.metaKey)
- return;
- var keyChar = String.fromCharCode(o3djs.event.getEventKeyChar(event));
- keyChar = keyChar.toLowerCase();
-
- var delta = 0.03; // rotation delta.
- // Create an array associating the keystroke to an axis about which to rotate.
- // Then dereference that array to get the axis.
-
- switch(keyChar) {
- case 'a':
- g_modelRoot.localMatrix =
- g_math.matrix4.mul(g_modelRoot.localMatrix,
- g_math.matrix4.rotationY(-delta));
- break;
- case 'd':
- g_modelRoot.localMatrix =
- g_math.matrix4.mul(g_modelRoot.localMatrix,
- g_math.matrix4.rotationY(delta));
- break;
- case 'w':
- g_modelRoot.localMatrix =
- g_math.matrix4.mul(g_modelRoot.localMatrix,
- g_math.matrix4.rotationX(-delta));
- break;
- case 's':
- g_modelRoot.localMatrix =
- g_math.matrix4.mul(g_modelRoot.localMatrix,
- g_math.matrix4.rotationX(delta));
- break;
- case 'l':
- g_modelRoot.localMatrix =
- g_math.matrix4.mul(g_modelRoot.localMatrix,
- g_math.matrix4.rotationZ(-delta));
- break;
- case 'k':
- g_modelRoot.localMatrix =
- g_math.matrix4.mul(g_modelRoot.localMatrix,
- g_math.matrix4.rotationZ(delta));
- break;
- case 'i':
- ZoomInOut(g_zoomFactor);
- break;
- case 'o':
- ZoomInOut(1.0 / g_zoomFactor);
- break;
- }
-
- o3djs.event.cancel(event);
-
- g_client.render();
-}
-
-/**
- * Zooms the model in / out by changing the viewpoint.
- * @param {number} zoom zooming factor.
- */
-function ZoomInOut(zoom) {
- for (i = 0; i < g_eyeView.length; i += 1) {
- g_eyeView[i] = g_eyeView[i] / zoom;
- }
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- g_eyeView, // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Start mouse dragging.
- * @param {event} e event.
- */
-function startDragging(e) {
- g_lastRot = g_thisRot;
- g_aball.click([e.x, e.y]);
- g_dragging = true;
-}
-
-/**
- * Use the arcball to rotate the model.
- * Computes the rotation matrix.
- * @param {event} e event.
- */
-function drag(e) {
- if (g_dragging) {
- var rotationQuat = g_aball.drag([e.x, e.y]);
- var rot_mat = g_quaternions.quaternionToRotation(rotationQuat);
- g_thisRot = g_math.matrix4.mul(g_lastRot, rot_mat);
- var m = g_modelRoot.localMatrix;
- g_math.matrix4.setUpper3x3(m, g_thisRot);
- g_modelRoot.localMatrix = m;
-
- g_client.render();
- }
-}
-
-/**
- * Stop dragging.
- * @param {event} e event.
- */
-function stopDragging(e) {
- g_dragging = false;
-}
-
-/**
- * Using the mouse wheel zoom in and out of the model.
- * @param {event} e event.
- */
-function scrollMe(e) {
- var zoom = (e.deltaY < 0) ? 1 / g_zoomFactor : g_zoomFactor;
- ZoomInOut(zoom);
- g_client.render();
-}
-
-</script>
-</head>
-
-<body>
-<h2>Scatter Chart - rotate &amp; zoom with mouse or keyboard</h2>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<form name="default_form" action="#" method="get" >
-<div style="font-size:10">
-Rotate: (W, S), (A, D), (K, L) &nbsp; &nbsp; &nbsp;
-Zoom: (I, O)&nbsp; &nbsp; &nbsp;
-<input type="button" value="Reset View" onclick="resetView()"
-style="font-size:10"/>
-</div>
-</form>
-
-</body>
-</html>
diff --git a/o3d/samples/shader-test.html b/o3d/samples/shader-test.html
deleted file mode 100644
index 9c49939..0000000
--- a/o3d/samples/shader-test.html
+++ /dev/null
@@ -1,413 +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.
--->
-
-<!--
-O3D Tutorial
-
-In this tutorial, we load a scene file and then apply various shaders to it.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Shader Test
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- }
-</style>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.loader');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_client;
-var g_viewInfo;
-var g_o3dElement;
-var g_pack;
-var g_root;
-var g_math;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-var g_currentTimeParam;
-var g_clock = 0;
-var g_shaderSelection = 0;
-var g_rotateOn = true;
-var g_o3dWidth; // width of our client area
-var g_o3dHeight; // height of our client area
-var g_shaders = [
- {file: 'diffuse', name: 'Diffuse'},
- {file: 'checker', name: 'Checker'},
- {file: 'bump', name: 'Bump'},
- {file: 'bump', name: 'Bump With Texture'},
- {file: 'texture-only', name: 'Texture Only'},
- {file: 'texture-colormult', name: 'Texture with Color Multiplier'},
- {file: 'tangent', name: 'Tangent'},
- {file: 'binormal', name: 'Binormal'},
- {file: 'normal', name: 'Normal'},
- {file: 'solid-color', name: 'Solid Color'},
- {file: 'vertex-color', name: 'Vertex Color'},
- {file: 'phong-with-colormult', name: 'Blinn-Phong with Color Multiplier'},
- {file: 'toon', name: 'Toon'}];
-var g_effects = [];
-var g_bumpTextureSampler;
-var g_bumpBumpsSampler;
-var g_colorRampSampler;
-
-// Our view and projection matrices
-// The view matrix transforms objects from world space to view space.
-var g_viewMatrix;
-// The projection matrix projects objects from view space to the screen.
-var g_projMatrix;
-
-/**
- * Returns the path of where the file is located
- * with the trailing slash
- */
-function getCurrentPath() {
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- return path.substring(0, index + 1);
-}
-
-/**
- * Turn rotation on.
- */
-function turnRotateOn() {
- g_rotateOn = true;
-}
-
-/**
- * Turn rotation off.
- */
-function turnRotateOff() {
- g_rotateOn = false;
-}
-
-/**
- * This is the code to animate the rotation.
- * @param {o3d.RenderEvent} render_event The render event.
- */
-function onrender(render_event) {
- var elapsedTime = render_event.elapsedTime * g_timeMult;
- var newWidth = g_client.width;
- var newHeight = g_client.height;
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
- setupCamera(g_pack, g_root);
- }
-
- g_clock += elapsedTime * (g_rotateOn ? 1 : 0);
- g_root.identity();
- g_root.rotateY(g_clock);
-
- g_currentTimeParam.value = g_clock;
-}
-
-/**
- * Sets the camera based on the imported file.
- * @param {!o3d.Pack} pack Pack to create context in.
- * @param {!o3d.Transform} root Root of tree to search for camera info.
- */
-function setupCamera(pack, root) {
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(root,
- g_o3dWidth,
- g_o3dHeight);
-
- // Copy the view and projection to the draw context.
- g_viewInfo.drawContext.view = cameraInfo.view;
- g_viewInfo.drawContext.projection = cameraInfo.projection;
-}
-
-/**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack Variable referring to the scene's pack.
- * @param {!o3d.Transform} parent Transform parent.
- * @param {*} exception null if loading succeeded.
- */
-function sceneCallback(pack, parent, exception) {
- if (exception) {
- alert('Could not load scene\n' + exception);
- return;
- }
- setupCamera(pack, parent);
-
- // Start with diffuse as default
- applyShader(pack, 0);
-
- // Add some vertex colors because the teapot does not have any
- // and yet the vertex color shader requires them.
- var streamBanks = pack.getObjectsByClassName('o3d.StreamBank');
- for (var ss = 0; ss < streamBanks.length; ++ss) {
- var streamBank = streamBanks[ss];
- if (!streamBank.getVertexStream(g_o3d.Stream.COLOR, 0)) {
- var positionField = streamBank.getVertexStream(g_o3d.Stream.POSITION,
- 0).field;
- var buffer = positionField.buffer;
- var numElements = buffer.numElements;
- var colorField = buffer.createField('FloatField', 4);
-
- var colors = [];
- for (var nn = 0; nn < numElements; ++nn) {
- colors.push((nn * 40 / numElements) % 1,
- (nn * 61 / numElements) % 1,
- (nn * 83 / numElements) % 1,
- 1);
- }
- colorField.setAt(0, colors);
- streamBank.setVertexStream(g_o3d.Stream.COLOR, 0, colorField, 0);
- }
- }
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
-}
-
-/**
- * Looks up a Param and if it exists sets its value.
- * @param {!o3d.ParamObject} object object to look for param on.
- * @param {string} name name of Param to look up.
- * @param {*} value Value to set param.
- */
-function setParam(object, paramName, value) {
- var param = object.getParam(paramName);
- if (param) {
- param.value = value;
- }
-}
-
-/**
- * Apply the desired shader to our scene.
- * @param {!o3d.Pack} pack Variable referring to the scene's pack.
- * @param {number} shaderNumber Index into g_effects of which shader to use.
- */
-function applyShader(pack, shaderNumber) {
- var materials = pack.getObjectsByClassName('o3d.Material');
- // Make the change to each material. For our teapot, there is only one
- // material.
- for (var m = 0; m < materials.length; m++) {
- var material = materials[m];
- g_effects[shaderNumber].createUniformParameters(material);
- material.effect = g_effects[shaderNumber];
-
- // Set our shader values
- var colorParamValue = [0.8, 0.8, 0.8, 1];
- var lightPosParamValue = [600, 600, 1000];
-
- setParam(material, 'lightPos', lightPosParamValue);
- setParam(material, 'lightWorldPos', lightPosParamValue);
- setParam(material, 'cameraEye', [197.58, -63.5702, 0]);
- setParam(material, 'color', colorParamValue);
- setParam(material, 'colorMult', [.75, .75, 75., 1]);
- // only use the texture input addition to bump mapping if on selection 3
- setParam(material, 'useTexture', (g_shaderSelection == 3) ? 1 : 0);
- setParam(material, 'lightIntensity', [0.8, 0.8, 0.8, 1]);
- setParam(material, 'ambientIntensity', [0.2, 0.2, 0.2, 1]);
- setParam(material, 'emissive', [0, 0, 0, 1]);
- setParam(material, 'ambient', [1, 1, 1, 1]);
- setParam(material, 'diffuse', colorParamValue);
- setParam(material, 'specular', [0.5, 0.5, 0.5, 1]);
- setParam(material, 'shininess', 50);
- setParam(material, 'BumpSampler', g_bumpBumpsSampler);
- setParam(material, 'AmbientSampler', g_bumpTextureSampler);
- setParam(material, 'DiffuseSampler', g_bumpTextureSampler);
- setParam(material, 'texSampler0', g_bumpTextureSampler);
- setParam(material, 'colorRamp', g_colorRampSampler);
-
- var timeParam = material.getParam('inputTime');
- if (timeParam) {
- timeParam.bind(g_currentTimeParam);
- }
- }
-}
-
-/**
- * Creates our client area by looking for <div>s with an id that starts with
- * "o3d".
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Get the width and height of our client area. We will need this to create
- // a projection matrix.
- g_o3dWidth = g_client.width;
- g_o3dHeight = g_client.height;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Creates a transform to put our data on.
- g_root = g_pack.createObject('Transform');
-
- // Connects our root to the client's root.
- g_root.parent = g_client.root;
-
- var paramObject = g_pack.createObject('ParamObject');
- g_currentTimeParam = paramObject.createParam('timeParam','ParamFloat');
-
- // Load effects and fill out options.
- options = '<select id="shaderSelect" name="shaderSelect"' +
- ' onChange="changeShader()">'
- for(var s = 0; s < g_shaders.length; s++) {
- g_effects[s] = g_pack.createObject('Effect');
- var shaderString = 'shaders/' + g_shaders[s].file + '.shader';
- o3djs.effect.loadEffect(g_effects[s], shaderString);
- options += '<option value="' + s + '"' + (s == 0 ? ' selected' : '') +
- '>' + g_shaders[s].name + '</option>';
- }
- options += '</select>';
- document.getElementById('shaderDiv').innerHTML = options;
-
- var rampWidth = 64;
- var texture = g_pack.createTexture2D(
- rampWidth, 1, g_o3d.Texture.XRGB8, 1, false);
- var pixels = [];
- for (var ii = 0; ii < rampWidth; ++ii) {
- var level = ii > rampWidth * 0.5 ? 1 : 0.3;
- pixels.push(level, level, level);
- }
- texture.set(0, pixels);
- g_colorRampSampler = g_pack.createObject('Sampler');
- g_colorRampSampler.texture = texture;
- g_colorRampSampler.addressModeU = g_o3d.Sampler.CLAMP;
-
- var loader = o3djs.loader.createLoader(initStep3);
- loader.loadTexture(g_pack, 'assets/normalmap.dds',
- function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- g_bumpBumpsSampler = g_pack.createObject('Sampler');
- g_bumpBumpsSampler.texture = texture;
- g_bumpBumpsSampler.mipFilter = g_o3d.Sampler.LINEAR;
- }
- });
- loader.loadTexture(g_pack, 'assets/rock_texture.jpg',
- function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- g_bumpTextureSampler = g_pack.createObject('Sampler');
- g_bumpTextureSampler.texture = texture;
- g_bumpTextureSampler.mipFilter = g_o3d.Sampler.LINEAR;
- }
- });
- var scenePath = getCurrentPath() + 'assets/teapot.o3dtgz';
- loader.loadScene(g_client, g_pack, g_root, scenePath, sceneCallback);
- loader.finish();
-}
-
-function initStep3() {
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', turnRotateOff);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', turnRotateOn);
-
- g_rotateOn = true;
-
- // Tell our example to rotate.
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Swaps which shader we are using and applies it.
- */
-function changeShader() {
- var shaderNumber = document.getElementById("shaderSelect").value;
- g_shaderSelection = parseFloat(shaderNumber);
- applyShader(g_pack, g_shaderSelection);
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Shader Test</h1>
-This example is useful for testing a shader or checking a scene. Clicking on the scene will temporarily stop rotation.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 100%; height: 80%;"></div>
-<!-- End of O3D plugin -->
-<p>
-<div id='shaderDiv'></div>
-</body>
-</html>
diff --git a/o3d/samples/shaders/README b/o3d/samples/shaders/README
deleted file mode 100644
index d5367d4d..0000000
--- a/o3d/samples/shaders/README
+++ /dev/null
@@ -1,16 +0,0 @@
-README for samples/shaders
-
-This directory contains files of shader code. In order to use them, they should
-be loaded into an html textarea in your application or loaded using
-o3djs.effect.loadEffect. NOTE: o3djs.effect.loadEffect can only load
-files from the same domain as the application webpage and the files must be at
-or below the current directory of the webpage
-
-The purpose of this directory is not to be *the* library of shaders, but to
-provide some sample shaders as examples and starting points for people to build
-their own.
-
-Each shader has its own requirements. Some shaders need different streams or
-require certain types of texture samplers so a shader will not work with just
-any 3d object. Look at the shader and determine what its requirements are before
-using it in your application.
diff --git a/o3d/samples/shaders/billboard-glsl.shader b/o3d/samples/shaders/billboard-glsl.shader
deleted file mode 100644
index 3385014..0000000
--- a/o3d/samples/shaders/billboard-glsl.shader
+++ /dev/null
@@ -1,67 +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 Billboard shader always faces the screen. It doesn't have any lighting.
-uniform mat4 projection;
-uniform mat4 worldView;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec2 texCoord0;
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-varying vec2 v_texcoord;
-
-/**
- * Vertex Shader - vertex shader for phong illumination
- */
-void main() {
- // Just add the world position of the transform to input position
- // and then multiple by the projection.
- gl_Position = projection * (position + vec4(worldView[3].xyz, 0));
- v_texcoord = texCoord0;
-}
-
-// #o3d SplitMarker
-
-uniform sampler2D texSampler0;
-varying vec2 v_texcoord;
-
-/**
- * Pixel Shader
- */
-void main() {
- gl_FragColor = texture2D(texSampler0, v_texcoord);
-}
-
-// #o3d MatrixLoadOrder RowMajor
-
diff --git a/o3d/samples/shaders/billboard.shader b/o3d/samples/shaders/billboard.shader
deleted file mode 100644
index 8402b78..0000000
--- a/o3d/samples/shaders/billboard.shader
+++ /dev/null
@@ -1,80 +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 Billboard shader always faces the screen. It doesn't have any lighting.
-
-float4x4 worldView : WorldView;
-float4x4 projection : Projection;
-
-sampler texSampler0;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD;
-};
-
-/**
- * Vertex Shader - vertex shader for phong illumination
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
-
- // Just add the world position of the transform to input position
- // and then multiple by the projection.
- output.position = mul(input.position + float4(worldView[3].xyz, 0),
- projection);
-
- output.texcoord = input.texcoord;
- return output;
-}
-
-/**
- * Pixel Shader
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return tex2D(texSampler0, input.texcoord);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
-
diff --git a/o3d/samples/shaders/binormal-glsl.shader b/o3d/samples/shaders/binormal-glsl.shader
deleted file mode 100644
index 58fbb27..0000000
--- a/o3d/samples/shaders/binormal-glsl.shader
+++ /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.
- */
-
-// The 4x4 world view projection matrix.
-uniform mat4 worldViewProjection;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec3 binormal;
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-varying vec3 v_binormal;
-
-void main() {
- gl_Position = worldViewProjection * position;
- v_binormal = binormal;
-}
-
-// #o3d SplitMarker
-
-varying vec3 v_binormal;
-
-void main() {
- gl_FragColor = vec4(normalize(v_binormal) * 0.5 + vec3(0.5, 0.5, 0.5), 1.0);
-}
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/binormal.shader b/o3d/samples/shaders/binormal.shader
deleted file mode 100644
index 1be9416..0000000
--- a/o3d/samples/shaders/binormal.shader
+++ /dev/null
@@ -1,64 +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.
- */
-
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WorldViewProjection;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float3 position : POSITION;
- float3 binormal : BINORMAL;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float3 binormal : TEXCOORD1;
-};
-
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(float4(input.position, 1.0), worldViewProjection);
- output.binormal = input.binormal;
- return output;
-}
-
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return float4(normalize(input.binormal) * 0.5 + float3(0.5, 0.5, 0.5), 1);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/bump-glsl.shader b/o3d/samples/shaders/bump-glsl.shader
deleted file mode 100644
index 0144923..0000000
--- a/o3d/samples/shaders/bump-glsl.shader
+++ /dev/null
@@ -1,140 +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.
- */
-
-// The 4x4 world view projection matrix.
-uniform mat4 worldViewProjection;
-uniform mat4 worldInverseTranspose;
-uniform mat4 world;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec4 normal;
-attribute vec4 tangent;
-attribute vec4 binormal;
-attribute vec2 texCoord0;
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-varying vec2 v_texCoord;
-varying vec3 v_normal;
-varying vec3 v_binormal;
-varying vec3 v_tangent;
-varying vec3 v_worldPosition;
-
-void main() {
-
- // Transform position into clip space.
- gl_Position = worldViewProjection * position;
-
- // Transform the tangent frame into world space.
- v_tangent = (worldInverseTranspose * tangent).xyz;
- v_binormal = (worldInverseTranspose * binormal).xyz;
- v_normal = (worldInverseTranspose * normal).xyz;
-
- // Pass through the texture coordinates.
- v_texCoord = texCoord0;
-
- // Calculate surface position in world space. Used for lighting.
- v_worldPosition = (world * position).xyz;
-}
-
-// #o3d SplitMarker
-
-// whether to use texture
-uniform float useTexture;
-
-uniform mat4 viewInverse;
-
-uniform vec3 lightWorldPos;
-uniform vec4 lightIntensity;
-uniform vec4 ambientIntensity;
-uniform vec4 emissive;
-uniform vec4 ambient;
-uniform vec4 diffuse;
-uniform vec4 specular;
-uniform float shininess;
-
-uniform sampler2D AmbientSampler;
-uniform sampler2D DiffuseSampler;
-uniform sampler2D BumpSampler;
-
-varying vec2 v_texCoord;
-varying vec3 v_normal;
-varying vec3 v_binormal;
-varying vec3 v_tangent;
-varying vec3 v_worldPosition;
-
-vec4 lit(float l ,float h, float m) {
- return vec4(1.0,
- max(l, 0.0),
- (l > 0.0) ? pow(max(0.0, h), m) : 0.0,
- 1.0);
-}
-
-void main() {
- // Construct a transform from tangent space into world space.
- mat3 tangentToWorld = mat3(v_tangent,
- v_binormal,
- v_normal);
-
- // Read the tangent space normal from the normal map and remove the bias so
- // they are in the range [-0.5,0.5]. There is no need to scale by 2 because
- // the vector will soon be normalized.
- vec3 tangentNormal = texture2D(BumpSampler, v_texCoord.xy).xyz -
- vec3(0.5, 0.5, 0.5);
-
- // Transform the normal into world space.
- vec3 worldNormal =(tangentToWorld * tangentNormal);
- worldNormal = normalize(worldNormal);
-
- // Read the diffuse and ambient colors.
- vec4 textureAmbient = vec4(1, 1, 1, 1);
- vec4 textureDiffuse = vec4(1, 1, 1, 1);
- if (useTexture == 1.0) {
- textureAmbient = texture2D(AmbientSampler, v_texCoord.xy);
- textureDiffuse = texture2D(DiffuseSampler, v_texCoord.xy);
- }
-
- // Apply lighting in world space in case the world transform contains scaling.
- vec3 surfaceToLight = normalize(lightWorldPos.xyz -
- v_worldPosition.xyz);
- vec3 surfaceToView = normalize(viewInverse[3].xyz - v_worldPosition);
- vec3 halfVector = normalize(surfaceToLight + surfaceToView);
- vec4 litResult = lit(dot(worldNormal, surfaceToLight),
- dot(worldNormal, halfVector), shininess);
- vec4 outColor = ambientIntensity * ambient * textureAmbient;
- outColor += lightIntensity * (diffuse * textureDiffuse * litResult.y +
- specular * litResult.z);
- outColor += emissive;
- gl_FragColor = vec4(outColor.rgb, diffuse.a * textureDiffuse.a);
-}
-
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/bump.shader b/o3d/samples/shaders/bump.shader
deleted file mode 100644
index 4d9eefa..0000000
--- a/o3d/samples/shaders/bump.shader
+++ /dev/null
@@ -1,137 +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.
- */
-
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WorldViewProjection;
-float4x4 worldInverseTranspose : WorldInverseTranspose;
-float4x4 world : World;
-float4x4 viewInverse : ViewInverse;
-
-// whether to use texture
-float useTexture;
-
-float3 lightWorldPos;
-float4 lightIntensity;
-float4 ambientIntensity;
-float4 emissive;
-float4 ambient;
-float4 diffuse;
-float4 specular;
-float shininess;
-
-sampler2D AmbientSampler;
-sampler2D DiffuseSampler;
-sampler2D BumpSampler;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float4 normal : NORMAL;
- float4 tangent : TANGENT;
- float4 binormal : BINORMAL;
- float2 texcoord0 : TEXCOORD0;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord0 : TEXCOORD0;
- float3 normal : TEXCOORD1;
- float3 binormal : TEXCOORD2;
- float3 tangent : TEXCOORD3;
- float3 worldPosition : TEXCOORD4;
-};
-
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
-
- // Transform position into clip space.
- output.position = mul(input.position, worldViewProjection);
-
- // Transform the tangent frame into world space.
- output.tangent = mul(input.tangent, worldInverseTranspose).xyz;
- output.binormal = mul(input.binormal, worldInverseTranspose).xyz;
- output.normal = mul(input.normal, worldInverseTranspose).xyz;
-
- // Pass through the texture coordinates.
- output.texcoord0 = input.texcoord0;
-
- // Calculate surface position in world space. Used for lighting.
- output.worldPosition = mul(input.position, world).xyz;
-
- return output;
-}
-
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- // Construct a transform from tangent space into world space.
- float3x3 tangentToWorld = float3x3(input.tangent,
- input.binormal,
- input.normal);
-
- // Read the tangent space normal from the normal map and remove the bias so
- // they are in the range [-0.5,0.5]. There is no need to scale by 2 because
- // the vector will soon be normalized.
- float3 tangentNormal = tex2D(BumpSampler, input.texcoord0.xy).xyz -
- float3(0.5, 0.5, 0.5);
-
- // Transform the normal into world space.
- float3 worldNormal = mul(tangentNormal, tangentToWorld);
- worldNormal = normalize(worldNormal);
-
- // Read the diffuse and ambient colors.
- float4 textureAmbient = float4(1, 1, 1, 1);
- float4 textureDiffuse = float4(1, 1, 1, 1);
- if (useTexture == 1) {
- textureAmbient = tex2D(AmbientSampler, input.texcoord0.xy);
- textureDiffuse = tex2D(DiffuseSampler, input.texcoord0.xy);
- }
-
- // Apply lighting in world space in case the world transform contains scaling.
- float3 surfaceToLight = normalize(lightWorldPos.xyz -
- input.worldPosition.xyz);
- float3 surfaceToView = normalize(viewInverse[3].xyz - input.worldPosition);
- float3 halfVector = normalize(surfaceToLight + surfaceToView);
- float4 litResult = lit(dot(worldNormal, surfaceToLight),
- dot(worldNormal, halfVector), shininess);
- float4 outColor = ambientIntensity * ambient * textureAmbient;
- outColor += lightIntensity * (diffuse * textureDiffuse * litResult.y +
- specular * litResult.z);
- outColor += emissive;
- return float4(outColor.rgb, diffuse.a * textureDiffuse.a);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/checker-glsl.shader b/o3d/samples/shaders/checker-glsl.shader
deleted file mode 100644
index bb143e9..0000000
--- a/o3d/samples/shaders/checker-glsl.shader
+++ /dev/null
@@ -1,107 +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.
- */
-
-// The 4x4 world view projection matrix.
-uniform mat4 worldViewProjection;
-uniform mat4 worldInverseTranspose;
-uniform mat4 world;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec4 normal;
-attribute vec2 texCoord0;
-
-// input parameters for our pixel shader
-varying vec2 v_texcoord;
-varying vec3 v_normal;
-varying vec3 v_worldPosition;
-
-/**
- * Our vertex shader. In the vertex shader, we calculate the lighting.
- * Then we'll combine it with our checker pattern input the pixel shader.
- */
-void main() {
- gl_Position = worldViewProjection * position;
-
- // Transform normal into world space, where we can do lighting
- // calculations even if the world transform contains scaling.
- v_normal = (worldInverseTranspose * normal).xyz;
-
- // Calculate surface position in world space.
- v_worldPosition = (world * position).xyz;
- v_texcoord = texCoord0;
-}
-
-// #o3d SplitMarker
-
-varying vec2 v_texcoord;
-varying vec3 v_normal;
-varying vec3 v_worldPosition;
-
-// Default and light position
-uniform vec4 ambientIntensity;
-uniform vec4 ambient;
-uniform vec4 diffuse;
-uniform vec3 lightWorldPos;
-uniform vec3 cameraEye;
-
-// function for getting the checker pattern
-vec4 checker(vec2 uv) {
- float checkSize = 4.0;
- float fmodResult = mod(floor(checkSize * uv.x) + floor(checkSize * uv.y),
- 2.0);
- if (fmodResult < 1.0) {
- return vec4(0, 1, 1, 1); // turquiose
- } else {
- return vec4(1, 0, 1, 1); // magenta
- }
-}
-
-/**
- * Our pixel shader. We take the lighting color we got from the vertex shader
- * and combine it with our checker pattern. We only need to use the x
- * coordinate of our input.col because we gave it uniform color
- */
-void main() {
- vec3 surfaceToLight = normalize(lightWorldPos - v_worldPosition);
- vec3 worldNormal = normalize(v_normal);
-
- // Apply diffuse lighting in world space in case the world transform
- // contains scaling.
- vec4 check = checker(v_texcoord);
- float directionalIntensity = clamp(dot(worldNormal, surfaceToLight), 0.0,
- 1.0);
- vec4 outColor = (ambientIntensity * ambient +
- directionalIntensity * diffuse) * check;
- gl_FragColor = vec4(outColor.rgb, diffuse.a);
-}
-
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/checker.shader b/o3d/samples/shaders/checker.shader
deleted file mode 100644
index d47c954..0000000
--- a/o3d/samples/shaders/checker.shader
+++ /dev/null
@@ -1,117 +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.
- */
-
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-float4x4 world : WORLD;
-
-// Default and light position
-float4 ambientIntensity;
-float4 ambient;
-float4 diffuse;
-float3 lightWorldPos;
-float3 cameraEye;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float4 normal : NORMAL;
- float2 texcoord : TEXCOORD0;
-};
-
-// input parameters for our pixel shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0;
- float3 normal : TEXCOORD1;
- float3 worldPosition : TEXCOORD2;
-};
-
-// function for getting the checker pattern
-float4 checker(float2 uv) {
- float checkSize = 4;
- float fmodResult = fmod(floor(checkSize * uv.x) + floor(checkSize * uv.y),
- 2.0);
- if (fmodResult < 1) {
- return float4(0, 1, 1, 1); // turquiose
- } else {
- return float4(1, 0, 1, 1); // magenta
- }
-}
-
-/**
- * Our vertex shader. In the vertex shader, we calculate the lighting.
- * Then we'll combine it with our checker pattern input the pixel shader.
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
-
- // Transform position into clip space.
- output.position = mul(input.position, worldViewProjection);
-
- // Transform normal into world space, where we can do lighting
- // calculations even if the world transform contains scaling.
- output.normal = mul(input.normal, worldInverseTranspose).xyz;
-
- // Calculate surface position in world space.
- output.worldPosition = mul(input.position, world).xyz;
-
- output.texcoord = input.texcoord;
-
- return output;
-}
-
-/**
- * Our pixel shader. We take the lighting color we got from the vertex sahder
- * and combine it with our checker pattern. We only need to use the x
- * coordinate of our input.col because we gave it uniform color
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
-
- float3 worldNormal = normalize(input.normal);
-
- // Apply diffuse lighting in world space in case the world transform
- // contains scaling.
- float4 check = checker(input.texcoord);
- float4 directionalIntensity = saturate(dot(worldNormal, surfaceToLight));
- float4 outColor = (ambientIntensity * ambient +
- directionalIntensity * diffuse) * check;
- return float4(outColor.rgb, diffuse.a);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/diffuse-glsl.shader b/o3d/samples/shaders/diffuse-glsl.shader
deleted file mode 100644
index 3ad9c23..0000000
--- a/o3d/samples/shaders/diffuse-glsl.shader
+++ /dev/null
@@ -1,87 +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.
- */
-
-// The 4x4 world view projection matrix.
-uniform mat4 worldViewProjection;
-uniform mat4 worldInverseTranspose;
-uniform mat4 world;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec4 normal;
-
-// input parameters for our pixel shader
-varying vec3 v_normal;
-varying vec3 v_worldPosition;
-
-/**
- * Our vertex shader.
- */
-void main() {
- // Transform position into clip space.
- gl_Position = worldViewProjection * position;
-
- // Transform normal into world space, where we can do lighting
- // calculations even if the world transform contains scaling.
- v_normal = (worldInverseTranspose * normal).xyz;
-
- // Calculate surface position in world space.
- v_worldPosition = (world * position).xyz;
-}
-
-// #o3d SplitMarker
-
-uniform vec4 ambientIntensity;
-uniform vec4 lightIntensity;
-uniform vec4 ambient;
-uniform vec4 diffuse;
-uniform vec3 lightWorldPos;
-
-varying vec3 v_normal;
-varying vec3 v_worldPosition;
-
-/**
- * Our pixel shader.
- */
-void main() {
- vec3 surfaceToLight = normalize(lightWorldPos - v_worldPosition);
-
- vec3 worldNormal = normalize(v_normal);
-
- // Apply diffuse lighting in world space in case the world transform
- // contains scaling.
- vec4 directionalIntensity = lightIntensity *
- clamp(dot(worldNormal, surfaceToLight), 0.0, 1.0);
- vec4 outColor = ambientIntensity * ambient + directionalIntensity * diffuse;
- gl_FragColor = vec4(outColor.rgb, diffuse.a);
-}
-
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/diffuse.shader b/o3d/samples/shaders/diffuse.shader
deleted file mode 100644
index fcd03eb..0000000
--- a/o3d/samples/shaders/diffuse.shader
+++ /dev/null
@@ -1,96 +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.
- */
-
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WorldViewProjection;
-float4x4 worldInverseTranspose : WorldInverseTranspose;
-float4x4 world : World;
-
-float4 ambientIntensity;
-float4 lightIntensity;
-float4 ambient;
-float4 diffuse;
-float3 lightWorldPos;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION; // Position vector of vertex
- float4 normal : NORMAL;
-};
-
-// input parameters for our pixel shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float3 normal : TEXCOORD0;
- float3 worldPosition : TEXCOORD1;
-};
-
-/**
- * Our vertex shader.
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
-
- // Transform position into clip space.
- output.position = mul(input.position, worldViewProjection);
-
- // Transform normal into world space, where we can do lighting
- // calculations even if the world transform contains scaling.
- output.normal = mul(input.normal, worldInverseTranspose).xyz;
-
- // Calculate surface position in world space.
- output.worldPosition = mul(input.position, world).xyz;
-
- return output;
-}
-
-/**
- * Our pixel shader.
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
-
- float3 worldNormal = normalize(input.normal);
-
- // Apply diffuse lighting in world space in case the world transform
- // contains scaling.
- float4 directionalIntensity = lightIntensity *
- saturate(dot(worldNormal, surfaceToLight));
- float4 outColor = ambientIntensity * ambient + directionalIntensity * diffuse;
- return float4(outColor.rgb, diffuse.a);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/green-blue-checker.shader b/o3d/samples/shaders/green-blue-checker.shader
deleted file mode 100644
index 41c2436..0000000
--- a/o3d/samples/shaders/green-blue-checker.shader
+++ /dev/null
@@ -1,110 +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.
- */
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-float4x4 world : WORLD;
-
-// light position
-float3 lightWorldPos;
-float3 lightColor;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float4 normal : NORMAL;
- float2 texcoord : TEXCOORD0;
-};
-
-// input parameters for our pixel shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0;
- float3 normal : TEXCOORD1;
- float3 worldPosition : TEXCOORD2;
-};
-
-// function for getting the checker pattern
-float4 checker(float2 uv) {
- float checkSize = 10;
- float fmodResult = fmod(floor(checkSize * uv.x) + floor(checkSize * uv.y),
- 2.0);
- return (fmodResult < 1) ?
- float4(0.4, 0.5, 0.5, 1) :
- float4(0.6, 0.8, 0.8, 1);
-}
-
-/**
- * Our vertex shader. In the vertex shader, we calculate the lighting.
- * Then we'll combine it with our checker pattern input the pixel shader.
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
-
- // Transform position into clip space.
- output.position = mul(input.position, worldViewProjection);
-
- // Transform normal into world space, where we can do lighting
- // calculations even if the world transform contains scaling.
- output.normal = mul(input.normal, worldInverseTranspose).xyz;
-
- // Calculate surface position in world space.
- output.worldPosition = mul(input.position, world).xyz;
-
- output.texcoord = input.texcoord;
-
- return output;
-}
-
-/**
- * Our pixel shader. We take the lighting color we got from the vertex sahder
- * and combine it with our checker pattern. We only need to use the x
- * coordinate of our input.col because we gave it uniform color
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
-
- float3 worldNormal = normalize(input.normal);
-
- // Apply diffuse lighting in world space in case the world transform
- // contains scaling.
- float4 check = checker(input.texcoord);
- float4 directionalIntensity = saturate(dot(worldNormal, surfaceToLight));
- float4 outColor = directionalIntensity * check;
- return float4(outColor.rgb, 1);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/imposter-glsl.shader b/o3d/samples/shaders/imposter-glsl.shader
deleted file mode 100644
index 1363d7ae..0000000
--- a/o3d/samples/shaders/imposter-glsl.shader
+++ /dev/null
@@ -1,77 +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 Imposter shader rotates around Y to face the camera.
-// It doesn't have any lighting.
-
-uniform mat4 world;
-uniform mat4 viewInverse;
-uniform mat4 viewProjection;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec2 texCoord0;
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-varying vec2 v_texcoord;
-
-/**
- * Vertex Shader - vertex shader for phong illumination
- */
-void main() {
- vec3 toCamera = normalize(viewInverse[3].xyz - world[3].xyz);
- vec3 yAxis = vec3(0, 1, 0);
- vec3 xAxis = cross(yAxis, toCamera);
- vec3 zAxis = cross(xAxis, yAxis);
-
- mat4 newWorld = mat4(
- vec4(xAxis, 0),
- vec4(yAxis, 0),
- vec4(xAxis, 0),
- world[3]);
- gl_Position = (viewProjection * newWorld) * position;
- v_texcoord = texCoord0;
-}
-
-// #o3d SplitMarker
-
-uniform sampler2D texSampler0;
-varying vec2 v_texcoord;
-
-/**
- * Pixel Shader
- */
-void main() {
- gl_FragColor = texture2D(texSampler0, v_texcoord);
-}
-
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/imposter.shader b/o3d/samples/shaders/imposter.shader
deleted file mode 100644
index 5540b31..0000000
--- a/o3d/samples/shaders/imposter.shader
+++ /dev/null
@@ -1,89 +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 Imposter shader rotates around Y to face the camera.
-// It doesn't have any lighting.
-
-float4x4 world : World;
-float4x4 viewInverse : ViewInverse;
-float4x4 viewProjection : ViewProjection;
-
-sampler texSampler0;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD;
-};
-
-/**
- * Vertex Shader - vertex shader for phong illumination
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
-
- float3 toCamera = normalize(viewInverse[3].xyz - world[3].xyz);
- float3 yAxis = float3(0, 1, 0);
- float3 xAxis = cross(yAxis, toCamera);
- float3 zAxis = cross(xAxis, yAxis);
-
- float4x4 newWorld = float4x4(
- float4(xAxis, 0),
- float4(yAxis, 0),
- float4(xAxis, 0),
- world[3]);
- output.position = mul(input.position, mul(newWorld, viewProjection));
-
- output.texcoord = input.texcoord;
- return output;
-}
-
-/**
- * Pixel Shader
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return tex2D(texSampler0, input.texcoord);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
-
diff --git a/o3d/samples/shaders/normal-glsl.shader b/o3d/samples/shaders/normal-glsl.shader
deleted file mode 100644
index bb60a12..0000000
--- a/o3d/samples/shaders/normal-glsl.shader
+++ /dev/null
@@ -1,56 +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.
- */
-
-// The 4x4 world view projection matrix.
-uniform mat4 worldViewProjection;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec3 normal;
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-varying vec3 v_normal;
-
-void main() {
- gl_Position = worldViewProjection * position;
- v_normal = normal;
-}
-
-// #o3d SplitMarker
-
-varying vec3 v_normal;
-
-void main() {
- gl_FragColor = vec4(normalize(v_normal) * 0.5 + vec3(0.5, 0.5, 0.5), 1);
-}
-
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/normal.shader b/o3d/samples/shaders/normal.shader
deleted file mode 100644
index 24d52a8..0000000
--- a/o3d/samples/shaders/normal.shader
+++ /dev/null
@@ -1,64 +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.
- */
-
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WorldViewProjection;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float3 position : POSITION;
- float3 normal : NORMAL;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float3 normal : TEXCOORD0;
-};
-
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(float4(input.position, 1.0), worldViewProjection);
- output.normal = input.normal;
- return output;
-}
-
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return float4(normalize(input.normal) * 0.5 + float3(0.5, 0.5, 0.5), 1);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/one-channel-texture.shader b/o3d/samples/shaders/one-channel-texture.shader
deleted file mode 100644
index f012b6d..0000000
--- a/o3d/samples/shaders/one-channel-texture.shader
+++ /dev/null
@@ -1,94 +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.
- */
-
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-
-// The texture sampler is used to access the texture bitmap in the fragment
-// shader.
-sampler texSampler0;
-
-// input parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-// input parameters for our pixel shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-/**
- * Our vertex shader
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(input.position, worldViewProjection);
- output.texcoord = input.texcoord;
- return output;
-}
-
-/**
- * Given the texture coordinates, our pixel shader grabs the corresponding
- * color from the texture.
- *
- * NOTE: GL and D3D do NOT share compatible 1 channel texture formats.
- *
- * In D3D the sampler will return
- *
- * R = channel 0
- * G = const 1
- * B = const 1
- * A = const 1
- *
- * In GL the sampler will return
- *
- * R = channel 0
- * G = channel 0
- * B = channel 0
- * A = channel 0
- *
- * What that means is only R works across platforms. G, B and A are undefined
- * and if you use them you'll get the wrong results.
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- // ** Use only valid channels. ** ---------+
- // |
- // V
- return tex2D(texSampler0, input.texcoord).rrrr;
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/phong-vertex-anim-glsl.shader b/o3d/samples/shaders/phong-vertex-anim-glsl.shader
deleted file mode 100644
index 1a45b47..0000000
--- a/o3d/samples/shaders/phong-vertex-anim-glsl.shader
+++ /dev/null
@@ -1,100 +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 shader expects to be passed vertices that are part of an x-z plane mesh
-// because it assumes the normal for each vertex before being offset by the
-// animation is 0, 1, 0.
-
-uniform mat4 viewProjection;
-uniform mat4 world;
-uniform mat4 worldInverseTranspose;
-uniform float time;
-
-attribute vec4 position;
-
-varying vec3 v_normal;
-varying vec3 v_worldPosition;
-
-void main() {
- vec3 worldPosition = (world * position).xyz;
-
- float animValue = time + (worldPosition.x + worldPosition.z) * 0.4;
- float animSin = sin(animValue);
- float animCos = cos(animValue);
- vec4 position = vec4(
- worldPosition.x,
- worldPosition.y + animSin,
- worldPosition.z,
- 1);
- gl_Position = viewProjection * position;
- vec3 normalTmp = normalize(vec3(animCos, abs(animSin), animCos));
- v_normal = (worldInverseTranspose * vec4(normalTmp, 0)).xyz;
- v_worldPosition = position.xyz;
-}
-
-// #o3d SplitMarker
-
-uniform vec3 lightWorldPos;
-uniform vec4 lightIntensity;
-uniform vec4 ambientIntensity;
-uniform vec4 emissive;
-uniform vec4 ambient;
-uniform vec4 diffuse;
-uniform vec4 specular;
-uniform float shininess;
-uniform float time;
-uniform mat4 viewInverse;
-
-varying vec3 v_normal;
-varying vec3 v_worldPosition;
-
-vec4 lit(float l ,float h, float m) {
- return vec4(1.0,
- max(l, 0.0),
- (l > 0.0) ? pow(max(0.0, h), m) : 0.0,
- 1.0);
-}
-
-void main() {
- vec3 surfaceToLight = normalize(lightWorldPos - v_worldPosition);
- vec3 worldNormal = normalize(v_normal);
- vec3 surfaceToView = normalize(viewInverse[3].xyz - v_worldPosition);
- vec3 halfVector = normalize(surfaceToLight + surfaceToView);
- vec4 litResult = lit(dot(worldNormal, surfaceToLight),
- dot(worldNormal, halfVector), shininess);
- vec4 outColor = ambientIntensity * ambient;
- outColor += lightIntensity * (diffuse * litResult.y +
- specular * litResult.z);
- outColor += emissive;
- gl_FragColor = vec4(outColor.rgb, diffuse.a);
-}
-
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/phong-vertex-anim.shader b/o3d/samples/shaders/phong-vertex-anim.shader
deleted file mode 100644
index b3da37f..0000000
--- a/o3d/samples/shaders/phong-vertex-anim.shader
+++ /dev/null
@@ -1,95 +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 shader expects to be passed vertices that are part of an x-z plane mesh
-// because it assumes the normal for each vertex before being offset by the
-// animation is 0, 1, 0.
-
-uniform float4x4 viewProjection : VIEWPROJECTION;
-uniform float3 lightWorldPos;
-uniform float4 lightIntensity;
-uniform float4x4 world : WORLD;
-uniform float4x4 viewInverse : VIEWINVERSE;
-uniform float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-uniform float4 ambientIntensity;
-uniform float4 emissive;
-uniform float4 ambient;
-uniform float4 diffuse;
-uniform float4 specular;
-uniform float shininess;
-uniform float time;
-
-struct VertexShaderInput {
- float4 position : POSITION;
-};
-
-struct PixelShaderInput {
- float4 position : POSITION;
- float3 normal : TEXCOORD1;
- float3 worldPosition : TEXCOORD4;
-};
-
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- float4 worldPosition = mul(input.position, world);
- float animValue = time + (worldPosition.x + worldPosition.z) * 0.4;
- float animSin = sin(animValue);
- float animCos = cos(animValue);
- float4 position = float4(
- worldPosition.x,
- worldPosition.y + animSin,
- worldPosition.z,
- 1);
- output.position = mul(position, viewProjection);
- float3 normal = normalize(float3(animCos, abs(animSin), animCos));
- output.normal = mul(float4(normal, 0), worldInverseTranspose).xyz;
- output.worldPosition = position.xyz;
-
- return output;
-}
-
-float4 pixelShaderFunction(PixelShaderInput input) : COLOR {
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
- float3 worldNormal = normalize(input.normal);
- float3 surfaceToView = normalize(viewInverse[3].xyz - input.worldPosition);
- float3 halfVector = normalize(surfaceToLight + surfaceToView);
- float4 litResult = lit(dot(worldNormal, surfaceToLight),
- dot(worldNormal, halfVector), shininess);
- float4 outColor = ambientIntensity * ambient;
- outColor += lightIntensity * (diffuse * litResult.y +
- specular * litResult.z);
- outColor += emissive;
- return float4(outColor.rgb, diffuse.a);
-}
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/phong-with-colormult-glsl.shader b/o3d/samples/shaders/phong-with-colormult-glsl.shader
deleted file mode 100644
index 5f6568a..0000000
--- a/o3d/samples/shaders/phong-with-colormult-glsl.shader
+++ /dev/null
@@ -1,88 +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.
- */
-
-uniform mat4 worldViewProjection;
-uniform mat4 world;
-uniform mat4 worldInverseTranspose;
-
-attribute vec4 position;
-attribute vec4 normal;
-
-varying vec3 v_normal;
-varying vec3 v_worldPosition;
-
-void main() {
- gl_Position = worldViewProjection * position;
-
- vec3 worldPosition = (world * position).xyz;
- v_normal = (worldInverseTranspose * normal).xyz;
- v_worldPosition = worldPosition;
-}
-
-// #o3d SplitMarker
-
-uniform mat4 viewInverse;
-uniform vec3 lightWorldPos;
-uniform vec4 ambientIntensity;
-uniform vec4 lightIntensity;
-uniform vec4 emissive;
-uniform vec4 ambient;
-uniform vec4 colorMult;
-uniform vec4 diffuse;
-uniform vec4 specular;
-uniform float shininess;
-
-varying vec3 v_normal;
-varying vec3 v_worldPosition;
-
-vec4 lit(float l ,float h, float m) {
- return vec4(1.0,
- max(l, 0.0),
- (l > 0.0) ? pow(max(0.0, h), m) : 0.0,
- 1.0);
-}
-
-void main() {
- vec3 surfaceToLight = normalize(lightWorldPos - v_worldPosition);
- vec3 worldNormal = normalize(v_normal);
- vec3 surfaceToView = normalize(viewInverse[3].xyz - v_worldPosition);
- vec3 halfVector = normalize(surfaceToLight + surfaceToView);
- vec4 litResult = lit(dot(worldNormal, surfaceToLight),
- dot(worldNormal, halfVector), shininess);
-
- vec4 outColor = ambientIntensity * ambient * colorMult;
- outColor += lightIntensity * (diffuse * colorMult * litResult.y +
- specular * litResult.z);
- outColor += emissive;
- gl_FragColor = vec4(outColor.rgb, diffuse.a * colorMult.a);
-}
-
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/phong-with-colormult.shader b/o3d/samples/shaders/phong-with-colormult.shader
deleted file mode 100644
index 756b6bb..0000000
--- a/o3d/samples/shaders/phong-with-colormult.shader
+++ /dev/null
@@ -1,83 +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.
- */
-
-uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-uniform float4x4 world : WORLD;
-uniform float4x4 viewInverse : VIEWINVERSE;
-uniform float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-uniform float3 lightWorldPos;
-uniform float4 ambientIntensity;
-uniform float4 lightIntensity;
-uniform float4 emissive;
-uniform float4 ambient;
-uniform float4 colorMult;
-uniform float4 diffuse;
-uniform float4 specular;
-uniform float shininess;
-
-struct VertexShaderInput {
- float4 position : POSITION;
- float4 normal : NORMAL;
-};
-
-struct PixelShaderInput {
- float4 position : POSITION;
- float3 normal : TEXCOORD1;
- float3 worldPosition : TEXCOORD4;
-};
-
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(input.position, worldViewProjection);
- float3 worldPosition = mul(input.position, world).xyz;
- output.normal = mul(input.normal, worldInverseTranspose).xyz;
- output.worldPosition = worldPosition;
-
- return output;
-}
-
-float4 pixelShaderFunction(PixelShaderInput input) : COLOR {
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
- float3 worldNormal = normalize(input.normal);
- float3 surfaceToView = normalize(viewInverse[3].xyz - input.worldPosition);
- float3 halfVector = normalize(surfaceToLight + surfaceToView);
- float4 litResult = lit(dot(worldNormal, surfaceToLight),
- dot(worldNormal, halfVector), shininess);
- float4 outColor = ambientIntensity * ambient * colorMult;
- outColor += lightIntensity * (diffuse * colorMult * litResult.y +
- specular * litResult.z);
- outColor += emissive;
- return float4(outColor.rgb, diffuse.a * colorMult.a);
-}
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/solid-color-glsl.shader b/o3d/samples/shaders/solid-color-glsl.shader
deleted file mode 100644
index 63d6e96..0000000
--- a/o3d/samples/shaders/solid-color-glsl.shader
+++ /dev/null
@@ -1,62 +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.
- */
-
-// The 4x4 world view projection matrix.
-uniform mat4 worldViewProjection;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-
-/**
- * Vertex Shader
- */
-void main() {
- /**
- * We transform each vertex by the world view projection matrix to bring
- * it from world space to projection space.
- *
- * We return its color unchanged.
- */
- gl_Position = worldViewProjection * position;
-}
-
-// #o3d SplitMarker
-
-uniform vec4 color;
-
-/**
- * Pixel Shader - pixel shader does nothing but return the color.
- */
-void main() {
- gl_FragColor = color;
-}
-
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/solid-color.shader b/o3d/samples/shaders/solid-color.shader
deleted file mode 100644
index 78d662f..0000000
--- a/o3d/samples/shaders/solid-color.shader
+++ /dev/null
@@ -1,74 +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.
- */
-
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-float4 color;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
-};
-
-/**
- * Vertex Shader
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- /**
- * We transform each vertex by the world view projection matrix to bring
- * it from world space to projection space.
- *
- * We return its color unchanged.
- */
- PixelShaderInput output;
-
- output.position = mul(input.position, worldViewProjection);
- return output;
-}
-/**
- * Pixel Shader - pixel shader does nothing but return the color.
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return color;
-}
-
-// Here we tell our effect file the functions
-// which specify our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/tangent-glsl.shader b/o3d/samples/shaders/tangent-glsl.shader
deleted file mode 100644
index ece63db..0000000
--- a/o3d/samples/shaders/tangent-glsl.shader
+++ /dev/null
@@ -1,56 +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.
- */
-
-// The 4x4 world view projection matrix.
-uniform mat4 worldViewProjection;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec3 tangent;
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-varying vec3 v_tangent;
-
-void main() {
- gl_Position = worldViewProjection * position;
- v_tangent = tangent;
-}
-
-// #o3d SplitMarker
-
-varying vec3 v_tangent;
-
-void main() {
- gl_FragColor = vec4(normalize(v_tangent) * 0.5 + vec3(0.5, 0.5, 0.5), 1);
-}
-
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/tangent.shader b/o3d/samples/shaders/tangent.shader
deleted file mode 100644
index c0e953f..0000000
--- a/o3d/samples/shaders/tangent.shader
+++ /dev/null
@@ -1,64 +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.
- */
-
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WorldViewProjection;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float3 position : POSITION;
- float3 tangent : TANGENT;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float3 tangent : TEXCOORD2;
-};
-
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(float4(input.position, 1.0), worldViewProjection);
- output.tangent = input.tangent;
- return output;
-}
-
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return float4(normalize(input.tangent) * 0.5 + float3(0.5, 0.5, 0.5), 1);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/texture-colormult-glsl.shader b/o3d/samples/shaders/texture-colormult-glsl.shader
deleted file mode 100644
index eb2d2f1..0000000
--- a/o3d/samples/shaders/texture-colormult-glsl.shader
+++ /dev/null
@@ -1,67 +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.
- */
-
-uniform mat4 worldViewProjection;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec2 texCoord0;
-
-// input parameters for our pixel shader
-varying vec2 v_texCoord;
-
-/**
- * Our vertex shader.
- */
-void main() {
- gl_Position = worldViewProjection * position;
- v_texCoord = texCoord0;
-}
-
-// #o3d SplitMarker
-
-// This parameter lets us adjust the color and fade things in or out.
-uniform vec4 colorMult;
-
-// The texture sampler is used to access the texture bitmap in the fragment
-// shader.
-uniform sampler2D texSampler0;
-
-varying vec2 v_texCoord;
-
-/* Given the texture coordinates, our pixel shader grabs the corresponding
- * color from the texture.
- */
-void main() {
- gl_FragColor = texture2D(texSampler0, v_texCoord) * colorMult;
-}
-
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/texture-colormult.shader b/o3d/samples/shaders/texture-colormult.shader
deleted file mode 100644
index b253e48..0000000
--- a/o3d/samples/shaders/texture-colormult.shader
+++ /dev/null
@@ -1,74 +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.
- */
-
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-
-// This parameter lets us adjust the color and fade things in or out.
-float4 colorMult;
-
-// The texture sampler is used to access the texture bitmap in the fragment
-// shader.
-sampler texSampler0;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-// input parameters for our pixel shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-/**
- * Our vertex shader.
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(input.position, worldViewProjection);
- output.texcoord = input.texcoord;
- return output;
-}
-
-/* Given the texture coordinates, our pixel shader grabs the corresponding
- * color from the texture.
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return tex2D(texSampler0, input.texcoord) * colorMult;
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/texture-only-glsl.shader b/o3d/samples/shaders/texture-only-glsl.shader
deleted file mode 100644
index ffea320..0000000
--- a/o3d/samples/shaders/texture-only-glsl.shader
+++ /dev/null
@@ -1,64 +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.
- */
-
-uniform mat4 worldViewProjection;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec2 texCoord0;
-
-// input parameters for our pixel shader
-varying vec2 v_texCoord;
-
-/**
- * Our vertex shader.
- */
-void main() {
- gl_Position = worldViewProjection * position;
- v_texCoord = texCoord0;
-}
-
-// #o3d SplitMarker
-
-// The texture sampler is used to access the texture bitmap in the fragment
-// shader.
-uniform sampler2D texSampler0;
-
-varying vec2 v_texCoord;
-
-/* Given the texture coordinates, our pixel shader grabs the corresponding
- * color from the texture.
- */
-void main() {
- gl_FragColor = texture2D(texSampler0, v_texCoord);
-}
-
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/texture-only.shader b/o3d/samples/shaders/texture-only.shader
deleted file mode 100644
index 2f09dfe..0000000
--- a/o3d/samples/shaders/texture-only.shader
+++ /dev/null
@@ -1,71 +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.
- */
-
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-
-// The texture sampler is used to access the texture bitmap in the fragment
-// shader.
-sampler texSampler0;
-
-// input parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-// input parameters for our pixel shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-/**
- * Our vertex shader
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(input.position, worldViewProjection);
- output.texcoord = input.texcoord;
- return output;
-}
-
-/* Given the texture coordinates, our pixel shader grabs the corresponding
- * color from the texture.
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return tex2D(texSampler0, input.texcoord);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/toon-glsl.shader b/o3d/samples/shaders/toon-glsl.shader
deleted file mode 100644
index 69a521c..0000000
--- a/o3d/samples/shaders/toon-glsl.shader
+++ /dev/null
@@ -1,89 +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.
- */
-
-// The 4x4 world view projection matrix.
-uniform mat4 worldViewProjection;
-uniform mat4 worldInverseTranspose;
-uniform mat4 world;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec4 normal;
-
-// input parameters for our pixel shader
-varying vec3 v_normal;
-varying vec3 v_worldPosition;
-
-/**
- * Our vertex shader.
- */
-void main() {
- // Transform position into clip space.
- gl_Position = worldViewProjection * position;
-
- // calculations even if the world transform contains scaling.
- v_normal = (worldInverseTranspose * normal).xyz;
-
- // Calculate surface position in world space.
- v_worldPosition = (world * position).xyz;
-}
-
-// #o3d SplitMarker
-
-varying vec3 v_normal;
-varying vec3 v_worldPosition;
-
-uniform vec4 ambientIntensity;
-uniform vec4 lightIntensity;
-uniform vec4 ambient;
-uniform vec4 diffuse;
-uniform vec3 lightWorldPos;
-
-uniform sampler2D colorRamp;
-
-/**
- * Our pixel shader.
- */
-void main() {
- vec3 surfaceToLight = normalize(lightWorldPos - v_worldPosition);
-
- vec3 worldNormal = normalize(v_normal);
-
- // Apply diffuse lighting in world space in case the world transform
- // contains scaling.
- vec4 directionalIntensity = lightIntensity *
- texture2D(colorRamp,
- vec2(clamp(dot(worldNormal, surfaceToLight), 0.0, 1.0), 0.5));
- vec4 outColor = ambientIntensity * ambient + directionalIntensity * diffuse;
- gl_FragColor = vec4(outColor.rgb, diffuse.a);
-}
-
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/toon.shader b/o3d/samples/shaders/toon.shader
deleted file mode 100755
index 8f2caec..0000000
--- a/o3d/samples/shaders/toon.shader
+++ /dev/null
@@ -1,98 +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.
- */
-
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WorldViewProjection;
-float4x4 worldInverseTranspose : WorldInverseTranspose;
-float4x4 world : World;
-
-float4 ambientIntensity;
-float4 lightIntensity;
-float4 ambient;
-float4 diffuse;
-float3 lightWorldPos;
-
-sampler colorRamp;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION; // Position vector of vertex
- float4 normal : NORMAL;
-};
-
-// input parameters for our pixel shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float3 normal : TEXCOORD0;
- float3 worldPosition : TEXCOORD1;
-};
-
-/**
- * Our vertex shader.
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
-
- // Transform position into clip space.
- output.position = mul(input.position, worldViewProjection);
-
- // Transform normal into world space, where we can do lighting
- // calculations even if the world transform contains scaling.
- output.normal = mul(input.normal, worldInverseTranspose).xyz;
-
- // Calculate surface position in world space.
- output.worldPosition = mul(input.position, world).xyz;
-
- return output;
-}
-
-/**
- * Our pixel shader.
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
-
- float3 worldNormal = normalize(input.normal);
-
- // Apply diffuse lighting in world space in case the world transform
- // contains scaling.
- float4 directionalIntensity = lightIntensity *
- tex2D(colorRamp, float2(saturate(dot(worldNormal, surfaceToLight)), 0.5));
- float4 outColor = ambientIntensity * ambient + directionalIntensity * diffuse;
- return float4(outColor.rgb, diffuse.a);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/vertex-color-glsl.shader b/o3d/samples/shaders/vertex-color-glsl.shader
deleted file mode 100644
index 9569387..0000000
--- a/o3d/samples/shaders/vertex-color-glsl.shader
+++ /dev/null
@@ -1,59 +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.
- */
-
-// The 4x4 world view projection matrix.
-uniform mat4 worldViewProjection;
-
-// input parameters for our vertex shader
-attribute vec4 position;
-attribute vec4 color;
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-varying vec4 v_color;
-
-/**
- * Vertex Shader - our vertex shader
- */
-void main() {
- gl_Position = worldViewProjection * position;
- v_color = color;
-}
-
-// #o3d SplitMarker
-varying vec4 v_color;
-/**
- * pixel shader does nothing but return whatever color it was given.
- */
-void main() {
- gl_FragColor = v_color;
-}
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/vertex-color.shader b/o3d/samples/shaders/vertex-color.shader
deleted file mode 100644
index 216f554..0000000
--- a/o3d/samples/shaders/vertex-color.shader
+++ /dev/null
@@ -1,75 +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.
- */
-
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-
-// input parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float4 color : COLOR;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float4 color: COLOR;
-};
-
-/**
- * Vertex Shader - our vertex shader
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- /**
- * Our vertex shader projects the vertices onto the screen.
- * We return its color unchanged.
- */
- PixelShaderInput output;
-
- output.position = mul(input.position, worldViewProjection);
- output.color = input.color;
- return output;
-}
-
-/**
- * pixel shader does nothing but return whatever color it was given.
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return input.color;
-}
-
-// Here we tell our effect file the functions
-// which specify our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shaders/yuv2rgb-glsl.shader b/o3d/samples/shaders/yuv2rgb-glsl.shader
deleted file mode 100644
index 8efcdb6..0000000
--- a/o3d/samples/shaders/yuv2rgb-glsl.shader
+++ /dev/null
@@ -1,230 +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 shader takes a Y'UV420p image as a single greyscale plane, and
-// converts it to RGB by sampling the correct parts of the image, and
-// by converting the colorspace to RGB on the fly.
-
-// Projection matrix for the camera.
-uniform mat4 worldViewProjection;
-
-// These are the input/output parameters for our vertex shader
-attribute vec4 position;
-attribute vec2 texCoord0;
-
-// These are the input/output parameters for our pixel shader.
-varying vec2 v_texcoord;
-
-/**
- * The vertex shader does nothing but returns the position of the
- * vertex using the world view projection matrix.
- */
-void main() {
- gl_Position = worldViewProjection * position;
- v_texcoord = texCoord0;
-}
-
-// #o3d SplitMarker
-
-// These represent the image dimensions of the SOURCE IMAGE (not the
-// Y'UV420p image). This is the same as the dimensions of the Y'
-// portion of the Y'UV420p image. They are set from JavaScript.
-uniform float imageWidth;
-uniform float imageHeight;
-
-// This is the texture sampler where the greyscale Y'UV420p image is
-// accessed.
-uniform sampler2D textureSampler;
-
-varying vec2 v_texcoord;
-
-/**
- * This fetches an individual Y pixel from the image, given the current
- * texture coordinates (which range from 0 to 1 on the source texture
- * image). They are mapped to the portion of the image that contains
- * the Y component.
- *
- * @param position This is the position of the main image that we're
- * trying to render, in parametric coordinates.
- */
-float getYPixel(vec2 position) {
- position.y = (position.y * 2.0 / 3.0) + (1.0 / 3.0);
- return texture2D(textureSampler, position).x;
-}
-
-/**
- * This does the crazy work of calculating the planar position (the
- * position in the byte stream of the image) of the U or V pixel, and
- * then converting that back to x and y coordinates, so that we can
- * account for the fact that V is appended to U in the image, and the
- * complications that causes (see below for a diagram).
- *
- * @param position This is the position of the main image that we're
- * trying to render, in pixels.
- *
- * @param planarOffset This is an offset to add to the planar address
- * we calculate so that we can find the U image after the V
- * image.
- */
-vec2 mapCommon(vec2 position, float planarOffset) {
- planarOffset += (imageWidth * floor(position.y / 2.0)) / 2.0 +
- floor((imageWidth - 1.0 - position.x) / 2.0);
- float x = floor(imageWidth - 1.0 - floor(mod(planarOffset, imageWidth)));
- float y = floor(floor(planarOffset / imageWidth));
- return vec2((x + 0.5) / imageWidth, (y + 0.5) / (1.5 * imageHeight));
-}
-
-/**
- * This is a helper function for mapping pixel locations to a texture
- * coordinate for the U plane.
- *
- * @param position This is the position of the main image that we're
- * trying to render, in pixels.
- */
-vec2 mapU(vec2 position) {
- float planarOffset = (imageWidth * imageHeight) / 4.0;
- return mapCommon(position, planarOffset);
-}
-
-/**
- * This is a helper function for mapping pixel locations to a texture
- * coordinate for the V plane.
- *
- * @param position This is the position of the main image that we're
- * trying to render, in pixels.
- */
-vec2 mapV(vec2 position) {
- return mapCommon(position, 0.0);
-}
-
-/**
- * Given the texture coordinates, our pixel shader grabs the right
- * value from each channel of the source image, converts it from Y'UV
- * to RGB, and returns the result.
- *
- * Each U and V pixel provides color information for a 2x2 block of Y
- * pixels. The U and V planes are just appended to the Y image.
- *
- * For images that have a height divisible by 4, things work out nicely.
- * For images that are merely divisible by 2, it's not so nice
- * (and YUV420 doesn't work for image sizes not divisible by 2).
- *
- * Here is a 6x6 image, with the layout of the planes of U and V.
- * Notice that the V plane starts halfway through the last scanline
- * that has U on it.
- *
- * 1 +---+---+---+---+---+---+
- * | Y | Y | Y | Y | Y | Y |
- * +---+---+---+---+---+---+
- * | Y | Y | Y | Y | Y | Y |
- * +---+---+---+---+---+---+
- * | Y | Y | Y | Y | Y | Y |
- * +---+---+---+---+---+---+
- * | Y | Y | Y | Y | Y | Y |
- * +---+---+---+---+---+---+
- * | Y | Y | Y | Y | Y | Y |
- * +---+---+---+---+---+---+
- * | Y | Y | Y | Y | Y | Y |
- * .3 +---+---+---+---+---+---+
- * | U | U | U | U | U | U |
- * +---+---+---+---+---+---+
- * | U | U | U | V | V | V |
- * +---+---+---+---+---+---+
- * | V | V | V | V | V | V |
- * 0 +---+---+---+---+---+---+
- * 0 1
- *
- * Here is a 4x4 image, where the U and V planes are nicely split into
- * separable blocks.
- *
- * 1 +---+---+---+---+
- * | Y | Y | Y | Y |
- * +---+---+---+---+
- * | Y | Y | Y | Y |
- * +---+---+---+---+
- * | Y | Y | Y | Y |
- * +---+---+---+---+
- * | Y | Y | Y | Y |
- * .3 +---+---+---+---+
- * | U | U | U | U |
- * +---+---+---+---+
- * | V | V | V | V |
- * 0 +---+---+---+---+
- * 0 1
- *
- */
-void main() {
- // Calculate what image pixel we're on, since we have to calculate
- // the location in the image stream, using floor in several places
- // which makes it hard to use parametric coordinates.
- vec2 pixelPosition = vec2(floor(imageWidth * v_texcoord.x),
- floor(imageHeight * v_texcoord.y));
- pixelPosition -= vec2(0.5, 0.5);
- // We can use the parametric coordinates to get the Y channel, since it's
- // a relatively normal image.
- float yChannel = getYPixel(v_texcoord);
-
- // As noted above, the U and V planes are smashed onto the end of
- // the image in an odd way (in our 2D texture mapping, at least), so
- // these mapping functions take care of that oddness.
- float uChannel = texture2D(textureSampler, mapU(pixelPosition)).x;
- float vChannel = texture2D(textureSampler, mapV(pixelPosition)).x;
-
- // This does the colorspace conversion from Y'UV to RGB as a matrix
- // multiply. It also does the offset of the U and V channels from
- // [0,1] to [-.5,.5] as part of the transform.
- vec4 channels = vec4(yChannel, uChannel, vChannel, 1.0);
-
- mat4 conversion = mat4(1.0, 0.0, 1.402, -0.701,
- 1.0, -0.344, -0.714, 0.529,
- 1.0, 1.772, 0.0, -0.886,
- 0, 0, 0, 0);
- vec3 rgb = (channels * conversion).xyz;
-
- // This is another Y'UV transform that can be used, but it doesn't
- // accurately transform my source image. Your images may well fare
- // better with it, however, considering they come from a different
- // source, and because I'm not sure that my original was converted
- // to Y'UV420p with the same RGB->YUV (or YCrCb) conversion as
- // yours.
- //
- // vec4 channels = vec4(yChannel, uChannel, vChannel, 1.0);
- // float3x4 conversion = float3x4(1.0, 0.0, 1.13983, -0.569915,
- // 1.0, -0.39465, -0.58060, 0.487625,
- // 1.0, 2.03211, 0.0, -1.016055);
- // float3 rgb = mul(conversion, channels);
-
- // Note: The output cannot fully replicate the original image. This is partly
- // because WebGL has limited NPOT (non-power-of-two) texture support and also
- // due to sRGB color conversions that occur in WebGL but not in the plugin.
- gl_FragColor = vec4(rgb, 1.0);
-}
-// #o3d MatrixLoadOrder RowMajor \ No newline at end of file
diff --git a/o3d/samples/shaders/yuv2rgb.shader b/o3d/samples/shaders/yuv2rgb.shader
deleted file mode 100644
index 359c2bc..0000000
--- a/o3d/samples/shaders/yuv2rgb.shader
+++ /dev/null
@@ -1,235 +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 shader takes a Y'UV420p image as a single greyscale plane, and
-// converts it to RGB by sampling the correct parts of the image, and
-// by converting the colorspace to RGB on the fly.
-
-// Projection matrix for the camera.
-float4x4 worldViewProjection : WorldViewProjection;
-
-// These represent the image dimensions of the SOURCE IMAGE (not the
-// Y'UV420p image). This is the same as the dimensions of the Y'
-// portion of the Y'UV420p image. They are set from JavaScript.
-float imageWidth;
-float imageHeight;
-
-// This is the texture sampler where the greyscale Y'UV420p image is
-// accessed.
-sampler textureSampler;
-
-// These are the input/output parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-// These are the input/output parameters for our pixel shader.
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-/**
- * This fetches an individual Y pixel from the image, given the current
- * texture coordinates (which range from 0 to 1 on the source texture
- * image). They are mapped to the portion of the image that contains
- * the Y component.
- *
- * @param position This is the position of the main image that we're
- * trying to render, in parametric coordinates.
- */
-float getYPixel(float2 position) {
- position.y = (position.y * 2.0 / 3.0) + (1.0 / 3.0);
- return tex2D(textureSampler, position).x;
-}
-
-/**
- * This does the crazy work of calculating the planar position (the
- * position in the byte stream of the image) of the U or V pixel, and
- * then converting that back to x and y coordinates, so that we can
- * account for the fact that V is appended to U in the image, and the
- * complications that causes (see below for a diagram).
- *
- * @param position This is the position of the main image that we're
- * trying to render, in pixels.
- *
- * @param planarOffset This is an offset to add to the planar address
- * we calculate so that we can find the U image after the V
- * image.
- */
-float2 mapCommon(float2 position, float planarOffset) {
- planarOffset += (imageWidth * floor(position.y / 2.0)) / 2.0 +
- floor((imageWidth - 1.0 - position.x) / 2.0);
- float x = int(imageWidth - 1.0 - floor(fmod(planarOffset, imageWidth)));
- float y = int(floor(planarOffset / imageWidth));
- return float2((x + 0.5) / imageWidth, (y + 0.5) / (1.5 * imageHeight));
-}
-
-/**
- * This is a helper function for mapping pixel locations to a texture
- * coordinate for the U plane.
- *
- * @param position This is the position of the main image that we're
- * trying to render, in pixels.
- */
-float2 mapU(float2 position) {
- float planarOffset = (imageWidth * imageHeight) / 4.0;
- return mapCommon(position, planarOffset);
-}
-
-/**
- * This is a helper function for mapping pixel locations to a texture
- * coordinate for the V plane.
- *
- * @param position This is the position of the main image that we're
- * trying to render, in pixels.
- */
-float2 mapV(float2 position) {
- return mapCommon(position, 0.0);
-}
-
-/**
- * The vertex shader does nothing but returns the position of the
- * vertex using the world view projection matrix.
- */
-PixelShaderInput vertexShaderMain(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(input.position, worldViewProjection);
-
- output.texcoord = input.texcoord;
- return output;
-}
-
-/**
- * Given the texture coordinates, our pixel shader grabs the right
- * value from each channel of the source image, converts it from Y'UV
- * to RGB, and returns the result.
- *
- * Each U and V pixel provides color information for a 2x2 block of Y
- * pixels. The U and V planes are just appended to the Y image.
- *
- * For images that have a height divisible by 4, things work out nicely.
- * For images that are merely divisible by 2, it's not so nice
- * (and YUV420 doesn't work for image sizes not divisible by 2).
- *
- * Here is a 6x6 image, with the layout of the planes of U and V.
- * Notice that the V plane starts halfway through the last scanline
- * that has U on it.
- *
- * 1 +---+---+---+---+---+---+
- * | Y | Y | Y | Y | Y | Y |
- * +---+---+---+---+---+---+
- * | Y | Y | Y | Y | Y | Y |
- * +---+---+---+---+---+---+
- * | Y | Y | Y | Y | Y | Y |
- * +---+---+---+---+---+---+
- * | Y | Y | Y | Y | Y | Y |
- * +---+---+---+---+---+---+
- * | Y | Y | Y | Y | Y | Y |
- * +---+---+---+---+---+---+
- * | Y | Y | Y | Y | Y | Y |
- * .3 +---+---+---+---+---+---+
- * | U | U | U | U | U | U |
- * +---+---+---+---+---+---+
- * | U | U | U | V | V | V |
- * +---+---+---+---+---+---+
- * | V | V | V | V | V | V |
- * 0 +---+---+---+---+---+---+
- * 0 1
- *
- * Here is a 4x4 image, where the U and V planes are nicely split into
- * separable blocks.
- *
- * 1 +---+---+---+---+
- * | Y | Y | Y | Y |
- * +---+---+---+---+
- * | Y | Y | Y | Y |
- * +---+---+---+---+
- * | Y | Y | Y | Y |
- * +---+---+---+---+
- * | Y | Y | Y | Y |
- * .3 +---+---+---+---+
- * | U | U | U | U |
- * +---+---+---+---+
- * | V | V | V | V |
- * 0 +---+---+---+---+
- * 0 1
- *
- */
-float4 pixelShaderMain(PixelShaderInput input): COLOR {
- // Calculate what image pixel we're on, since we have to calculate
- // the location in the image stream, using floor in several places
- // which makes it hard to use parametric coordinates.
- float2 pixelPosition = float2(floor(imageWidth * input.texcoord.x),
- floor(imageHeight * input.texcoord.y));
-
- // We can use the parametric coordinates to get the Y channel, since it's
- // a relatively normal image.
- float yChannel = getYPixel(input.texcoord);
-
- // As noted above, the U and V planes are smashed onto the end of
- // the image in an odd way (in our 2D texture mapping, at least), so
- // these mapping functions take care of that oddness.
- float uChannel = tex2D(textureSampler, mapU(pixelPosition)).x;
- float vChannel = tex2D(textureSampler, mapV(pixelPosition)).x;
-
- // This does the colorspace conversion from Y'UV to RGB as a matrix
- // multiply. It also does the offset of the U and V channels from
- // [0,1] to [-.5,.5] as part of the transform.
- float4 channels = float4(yChannel, uChannel, vChannel, 1.0);
- float3x4 conversion = float3x4(1.0, 0.0, 1.402, -0.701,
- 1.0, -0.344, -0.714, 0.529,
- 1.0, 1.772, 0.0, -0.886);
- float3 rgb = mul(conversion, channels);
-
- // This is another Y'UV transform that can be used, but it doesn't
- // accurately transform my source image. Your images may well fare
- // better with it, however, considering they come from a different
- // source, and because I'm not sure that my original was converted
- // to Y'UV420p with the same RGB->YUV (or YCrCb) conversion as
- // yours.
- //
- // float4 channels = float4(yChannel, uChannel, vChannel, 1.0);
- // float3x4 conversion = float3x4(1.0, 0.0, 1.13983, -0.569915,
- // 1.0, -0.39465, -0.58060, 0.487625,
- // 1.0, 2.03211, 0.0, -1.016055);
- // float3 rgb = mul(conversion, channels);
-
- return float4(rgb, 1.0);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-// #o3d VertexShaderEntryPoint vertexShaderMain
-// #o3d PixelShaderEntryPoint pixelShaderMain
-// #o3d MatrixLoadOrder RowMajor
diff --git a/o3d/samples/shadow-map.html b/o3d/samples/shadow-map.html
deleted file mode 100644
index 5b9b442..0000000
--- a/o3d/samples/shadow-map.html
+++ /dev/null
@@ -1,628 +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 sample uses a custom render graph to implement a basic shadow map
-algorithm.
-
-The technique works by rendering the scene in two passes. The first pass
-renders the geometry in the scene with a shader that colors each pixel a shade
-of gray representing how far the rendered point is from the light source. That
-image, the shadow map, is rendered to a texture, and then the second (visible)
-render pass samples it to determine which points in the scene are in shaodow.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Shadow Mapping
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.debug');
-o3djs.require('o3djs.material');
-
-// The initClient() function runs when the page has finished loading.
-window.onload = initClient;
-
-// global variables
-var g_o3dElement;
-var g_client;
-var g_o3d;
-var g_math;
-var g_pack;
-var g_colorViewInfo;
-var g_shadowViewInfo;
-var g_shadowTexture;
-var g_shadowMaterial;
-var g_shadowColorEffect;
-var g_shadowSampler;
-var g_lightViewProjection;
-var g_lightFrustumTransform;
-var g_globalParams = { };
-var g_viewFromLight = false;
-
-var g_renderSurfaceSet;
-var g_colorPassRenderRoot;
-
-var g_lightWorldPos = [5, 10, 0];
-var g_lightColor = [1, 1, 1, 1];
-var g_eyePosition = [1, 6, 20];
-var g_targetPosition = [0, 2, 0];
-
-// constants.
-var SHADOW_MAP_WIDTH = 512;
-var SHADOW_MAP_HEIGHT = 512;
-
-var g_finished = false; // for selenium testing.
-
-
-/**
- * Creates the client area.
- */
-function initClient() {
- o3djs.util.makeClients(main, 'FloatingPointTextures');
-}
-
-
-/**
- * Initializes global variables, positions camera, draws shapes.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function main(clientElements) {
- // Init global variables.
- initGlobals(clientElements);
-
- // Set up the rendergraph.
- initRenderGraph();
-
- // Load effects, bind material parameters.
- initMaterials();
-
- // Add the shapes to the transform graph.
- createShapes();
-
- // Set up the view and projection transformations for the camera.
- updateCamera();
-
- // Init global parameters. initGlobalParams() searches all materials in order
- // to bind parameters, so it must be called after initMaterials()
- initGlobalParams();
-
- // Set the view and projection transformations for the light.
- updateLightMatrix();
-
- // Create the light that gets drawn.
- createLightShape();
-
- // Execute keyPressed() when we detect a keypress on the window or
- // on the o3d object.
- window.document.onkeypress = keyPressed;
- g_o3dElement.onkeypress = keyPressed;
-
- g_finished = true; // for selenium testing.
-}
-
-
-/**
- * Initializes global variables and libraries.
- */
-function initGlobals(clientElements) {
- g_o3dElement = clientElements[0];
- g_client = g_o3dElement.client;
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-}
-
-
-/**
- * Sets up the render graph. Builds a basic view for the camera and the light
- * point of view, arranges for the view from the light to be rendered to a
- * texture for the shadow map. Unlike the basic render graph created by the
- * the utility function o3djs.rendergraph.createBasicView, to render the shadow
- * map and then render the scene, we need two subtrees of the render graph, one
- * for shadow map render pass and one to draw the scene.
- */
-function initRenderGraph() {
- // Create the texture that will store the depth information.
- g_shadowTexture = g_pack.createTexture2D(SHADOW_MAP_WIDTH,
- SHADOW_MAP_HEIGHT,
- g_o3d.Texture.ABGR32F,
- 1,
- true);
- var renderSurface = g_shadowTexture.getRenderSurface(0);
-
- // Create the depth-stencil buffer required when rendering the teapot.
- var depthSurface = g_pack.createDepthStencilSurface(SHADOW_MAP_WIDTH,
- SHADOW_MAP_HEIGHT);
-
- // The children of any one node in the render graph get traversed in order by
- // priority. Here, we're forcing the shadow map to get rendered first by
- // by giving its render root lower priority.
- var shadowPassRenderRoot = g_pack.createObject('RenderNode');
- shadowPassRenderRoot.priority = 0;
-
- g_colorPassRenderRoot = g_pack.createObject('RenderNode');
- g_colorPassRenderRoot.priority = 1;
-
- shadowPassRenderRoot.parent = g_client.renderGraphRoot;
- g_colorPassRenderRoot.parent = g_client.renderGraphRoot;
-
- g_renderSurfaceSet = g_pack.createObject('RenderSurfaceSet');
- g_renderSurfaceSet.renderSurface = renderSurface;
- g_renderSurfaceSet.renderDepthStencilSurface = depthSurface;
- g_renderSurfaceSet.parent = shadowPassRenderRoot;
-
- // Create a render sub-graph for the shadow map generation.
- g_shadowViewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_renderSurfaceSet,
- [1, 1, 1, 1]);
-
- // Create a render sub-graph for the regular pass.
- g_colorViewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_colorPassRenderRoot,
- [0, 0, 0, 1]);
-}
-
-
-/**
- * Switches between the camera and light point of view.
- */
-function toggleView() {
- if (g_viewFromLight) {
- g_shadowViewInfo.root.parent = g_renderSurfaceSet;
- g_colorPassRenderRoot.parent = g_client.renderGraphRoot;
- g_viewFromLight = false;
- } else {
- g_shadowViewInfo.root.parent = g_client.renderGraphRoot;
- g_colorPassRenderRoot.parent = null;
- g_viewFromLight = true;
- }
-}
-
-/**
- * Creates a material to be put on all shapes in the scene for the shadow pass,
- * and loads effects for materials in the scene. Other materials are created
- * on the fly as the shapes are created.
- */
-function initMaterials() {
- g_shadowMaterial = g_pack.createObject('Material');
- g_shadowMaterial.drawList = g_shadowViewInfo.performanceDrawList;
-
- var shadowEffect = g_pack.createObject('Effect');
- var shadowEffectString = document.getElementById('shadowShader').text;
- shadowEffect.loadFromFXString(shadowEffectString);
- g_shadowMaterial.effect = shadowEffect;
- shadowEffect.createUniformParameters(g_shadowMaterial);
-
- g_shadowColorEffect = g_pack.createObject('Effect');
- var colorEffectString = document.getElementById('shadowColorShader').text;
- g_shadowColorEffect.loadFromFXString(colorEffectString);
-
- g_shadowSampler = g_pack.createObject('Sampler');
- g_shadowSampler.texture = g_shadowTexture;
- g_shadowSampler.minFilter = g_o3d.Sampler.POINT;
- g_shadowSampler.magFilter = g_o3d.Sampler.POINT;
- g_shadowSampler.mipFilter = g_o3d.Sampler.POINT;
- g_shadowSampler.addressModeU = g_o3d.Sampler.BORDER;
- g_shadowSampler.addressModeV = g_o3d.Sampler.BORDER;
- g_shadowSampler.borderColor = [1, 1, 1, 1];
-}
-
-
-/**
- * Sets up reasonable view and projection matrices.
- */
-function updateCamera() {
- // Set up a perspective transformation for the projection.
- g_colorViewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree frustum.
- g_o3dElement.clientWidth / g_o3dElement.clientHeight, // Aspect ratio.
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // cube is located.
- g_colorViewInfo.drawContext.view = g_math.matrix4.lookAt(
- g_eyePosition, // eye
- g_targetPosition, // target
- [0, 1, 0]); // up
-}
-
-
-/**
- * Computes the view and projection matrices from the point of view of the
- * light. Sets the lightViewProjection parameter so the color shader can access
- * it.
- */
-function updateLightMatrix() {
- // The perspective projection matrix for the light.
- var lightProjection = g_math.matrix4.perspective(
- g_math.degToRad(45), // 45 degree fov.
- SHADOW_MAP_WIDTH / SHADOW_MAP_HEIGHT, // Aspect ratio.
- 4, // Near plane.
- 20); // Far plane.
-
- // Make the light point toward the origin
- var lightView = g_math.matrix4.lookAt(
- g_lightWorldPos, // light
- [0, 0, 0], // target
- [1, 0, 0]); // up
-
- g_lightViewProjection = g_math.matrix4.composition(
- lightProjection, lightView);
-
- g_shadowViewInfo.drawContext.projection = lightProjection;
- g_shadowViewInfo.drawContext.view = lightView;
-
- g_globalParams.lightViewProjection.value = g_lightViewProjection;
-}
-
-
-/**
- * Creates shapes using the primitives utility library, and adds them to the
- * transform graph at the root node.
- */
-function createShapes() {
- // A green phong-shaded material for the cube.
- var cubeMaterial = createShadowColorMaterial([0.2, 0.5, 0, 1]);
-
- // The cube shape.
- var cube = o3djs.primitives.createCube(
- g_pack,
- cubeMaterial,
- 2); // The length of each side of the cube.
-
- // A red phong-shaded material for the sphere.
- var sphereMaterial = createShadowColorMaterial([0.7, 0.2, 0.1, 1]);
-
- // The sphere shape.
- var sphere = o3djs.primitives.createSphere(
- g_pack, sphereMaterial, 0.5, 50, 50);
-
- // A blue phong-shaded material for the plane.
- var planeMaterial = createShadowColorMaterial([0, 0.3, 0.5, 1]);
-
- // The plane shape.
- var plane = o3djs.primitives.createPlane(
- g_pack,
- planeMaterial,
- 20, // Width.
- 20, // Depth.
- 1, // Horizontal subdivisions.
- 1); // Vertical subdivisions.
-
- // Associate to each shape, a translation vector.
- var transformTable = [
- {shape: cube, translation: [0, 1, 0]},
- {shape: sphere, translation: [0.5, 2.5, 0]},
- {shape: plane, translation: [0, 0, 0]}
- ];
-
- // Add the shapes to the transform graph with the translation.
- var modelRoot = g_pack.createObject('Transform');
- modelRoot.parent = g_client.root;
- for (var tt = 0; tt < transformTable.length; ++tt) {
- var transform = g_pack.createObject('Transform');
- transform.addShape(transformTable[tt].shape);
- // The shadow material is bound to a DrawList in the subtree of the
- // rendergraph that handles the shadow map generation, so it gets drawn in
- // that render pass only.
- transformTable[tt].shape.createDrawElements(g_pack, g_shadowMaterial);
-
- transform.translate(transformTable[tt].translation);
- transform.parent = modelRoot;
- }
-}
-
-
-/**
- * Creates the wireframe frustum showing the shadow map's render volume.
- */
-function createLightShape() {
- var inverseMatrix = g_math.matrix4.inverse(g_lightViewProjection);
-
- // Scale and translate a cube of side length 2 to get a box
- // that extends from [-1, -1, 0] to [1, 1, 1].
- var shape = o3djs.lineprimitives.createLineCube(
- g_pack,
- o3djs.material.createConstantMaterial(g_pack,
- g_colorViewInfo,
- [1, 0, 0, 1]),
- 2,
- g_math.matrix4.compose(
- g_math.matrix4.translation([0, 0, 0.5]),
- g_math.matrix4.scaling([1, 1, 0.5])));
-
- g_lightFrustumTransform = g_pack.createObject('Transform');
- g_lightFrustumTransform.localMatrix = inverseMatrix;
- g_lightFrustumTransform.parent = g_client.root;
- g_lightFrustumTransform.addShape(shape);
-}
-
-
-/**
- * Creates a Phong-shaded, shadowed material based on the given color.
- */
-function createShadowColorMaterial(baseColor) {
- var material = g_pack.createObject('Material');
- material.drawList = g_colorViewInfo.performanceDrawList;
-
- material.effect = g_shadowColorEffect;
- g_shadowColorEffect.createUniformParameters(material);
-
- material.getParam('shadowMapSampler').value = g_shadowSampler;
-
- material.getParam('ambient').value = g_math.mulScalarVector(0.1, baseColor);
- material.getParam('diffuse').value = g_math.mulScalarVector(0.8, baseColor);
- material.getParam('specular').value = [1, 1, 1, 1];
- material.getParam('shininess').value = 80;
-
- return material;
-}
-
-/**
- * Binds params for light position, light color and the light view-projection
- * matrix to all materials in the scene where they apply.
- */
-function initGlobalParams() {
- var paramSpec = {
- 'lightColor': 'ParamFloat4',
- 'lightWorldPos': 'ParamFloat3',
- 'lightViewProjection': 'ParamMatrix4'};
-
- g_globalParams = o3djs.material.createParams(g_pack, paramSpec);
- o3djs.material.bindParams(g_pack, g_globalParams);
-
- g_globalParams.lightWorldPos.value = g_lightWorldPos;
- g_globalParams.lightColor.value = g_lightColor;
-}
-
-
-/**
- * The keyboard event handler.
- */
-function keyPressed(event) {
- var keyChar = String.fromCharCode(o3djs.event.getEventKeyChar(event));
- keyChar = keyChar.toLowerCase();
-
- var delta = 0.2;
- switch(keyChar) {
- case 'a':
- moveLight([-delta, 0, 0]);
- break;
- case 'd':
- moveLight([delta, 0, 0]);
- break;
- case 's':
- moveLight([0, -delta, 0]);
- break;
- case 'w':
- moveLight([0, delta, 0]);
- break;
- case 'i':
- moveLight([0, 0, delta]);
- break;
- case 'o':
- moveLight([0, 0, -delta]);
- break;
-
- case ' ':
- toggleView();
- break;
- }
-}
-
-
-/**
- * Moves the light by the given vector delta, and updates params so the light
- * draws in the right spot and the shadows move.
- */
-function moveLight(delta) {
- g_lightWorldPos = g_math.addVector(g_lightWorldPos, delta);
- g_globalParams.lightWorldPos.value = g_lightWorldPos;
- updateLightMatrix();
- g_lightFrustumTransform.localMatrix =
- g_math.matrix4.inverse(g_lightViewProjection);
-}
-
-
-</script>
-<script id="shadowShader" type="text/O3DShader">
- /**
- * This shader is for the effect applied in the first render pass, when the
- * shadow map is created. The scene is rendered from the perspective of the
- * light, the grayscale value of each pixel in the rendered image represents
- * how far away the rendered point is from the light (the lighter, the
- * farther) This image gets rendered to a texture, and that texture gets
- * sampled in the second render pass, when the geometry is drawn to the
- * screen.
- */
-
- // The light's wvp matrix
- float4x4 worldViewProjection : WorldViewProjection;
-
- // Input parameters for our vertex shader.
- struct VertexShaderInput {
- float4 position : POSITION;
- };
-
- // Input parameters for our pixel shader.
- struct PixelShaderInput {
- float4 position : POSITION;
- float2 depth : TEXCOORD0;
- };
-
- /**
- * The vertex shader simply transforms the input vertices to screen space.
- */
- PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- // Render from the light's perspective.
- output.position = mul(input.position, worldViewProjection);
- output.depth = output.position.zw;
- return output;
- }
-
- /**
- * The pixel shader returns a shade of gray. The lighter the shade the
- * farther that fragment is from the light.
- */
- float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- // Pixels in the shadowmap store the pixel depth from the light's
- // perspective in normalized device coordinates.
- float t = input.depth.x / input.depth.y;
- return float4(t, t, t, 1);
- }
-
- // #o3d VertexShaderEntryPoint vertexShaderFunction
- // #o3d PixelShaderEntryPoint pixelShaderFunction
- // #o3d MatrixLoadOrder RowMajor
-</script>
-
-
-<script id="shadowColorShader" type="text/O3DShader">
- /**
- * This shader is for the effect applied in the second render pass when the
- * shadowed shapes are drawn to the screen. In the pixel shader, the distance
- * from the rendered point to the camera is compared to the distance encoded
- * in the shadow map. If the distance is much greater, the rendered point is
- * considered to be in shadow and is given a light coefficient of 0.
- */
-
- float4x4 world : World;
- float4x4 worldViewProjection : WorldViewProjection;
- float4x4 worldInverseTranspose : WorldInverseTranspose;
- float4x4 viewInverse : ViewInverse;
- float4x4 lightViewProjection;
- sampler shadowMapSampler;
-
- // Parameters for the phong shader.
- uniform float3 lightWorldPos;
- uniform float4 lightColor;
- uniform float4 ambient;
- uniform float4 diffuse;
- uniform float4 specular;
- uniform float shininess;
-
- // input parameters for our vertex shader
- struct VertexShaderInput {
- float4 position : POSITION;
- float3 normal : NORMAL;
- };
-
- // input parameters for our pixel shader
- struct PixelShaderInput {
- float4 position : POSITION;
- float4 projTextureCoords : TEXCOORD0;
- float4 worldPosition : TEXCOORD1;
- float3 normal : TEXCOORD2;
- };
-
- PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
-
- // Transform to homogeneous clip space.
- output.position = mul(input.position, worldViewProjection);
-
- // Compute the projective texture coordinates to project the shadow map
- // onto the scene.
- float4x4 worldLightViewProjection = mul(world, lightViewProjection);
- output.projTextureCoords = mul(input.position, worldLightViewProjection);
- output.worldPosition = mul(input.position, world);
- output.normal = mul(float4(input.normal, 0), worldInverseTranspose).xyz;
-
- return output;
- }
-
- float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- float3 surfaceToLight = normalize(lightWorldPos - input.worldPosition);
- float3 surfaceToView = normalize(viewInverse[3].xyz - input.worldPosition);
- float3 normal = normalize(input.normal);
- float3 halfVector = normalize(surfaceToLight + surfaceToView);
- float4 litResult = lit(dot(normal, surfaceToLight),
- dot(normal, halfVector), shininess);
- float4 outColor = ambient;
- float4 projCoords = input.projTextureCoords;
-
- // Convert texture coords to [0, 1] range.
- projCoords.xy /= projCoords.w;
- projCoords.x = 0.5 * projCoords.x + 0.5;
- projCoords.y = -0.5 * projCoords.y + 0.5;
-
- // Compute the pixel depth for shadowing.
- float depth = projCoords.z / projCoords.w;
-
- // If the rednered point is farter from the light than the distance encoded
- // in the shadow map, we give it a light coefficient of 0.
- float light = tex2D(shadowMapSampler, projCoords.xy).r + 0.008 > depth;
-
- // Make the illuninated area a round spotlight shape just for fun.
- // Comment this line out to see just the shadows.
- light *= 1 - smoothstep(0.45, 0.5, length(projCoords - float2(0.5, 0.5)));
-
- outColor += light * lightColor *
- (diffuse * litResult.y + specular * litResult.z);
- return outColor;
- }
-
- // #o3d VertexShaderEntryPoint vertexShaderFunction
- // #o3d PixelShaderEntryPoint pixelShaderFunction
- // #o3d MatrixLoadOrder RowMajor
-</script>
-
-
-</head>
-<body>
-<h1>Shadow Maps</h1>
-This sample implements a basic shadow map.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-Use A, S, D, W, I and O to move the light.
-Press spacebar to see the shadow map.
-</body>
-</html>
diff --git a/o3d/samples/simple.html b/o3d/samples/simple.html
deleted file mode 100644
index 0b58ba1..0000000
--- a/o3d/samples/simple.html
+++ /dev/null
@@ -1,108 +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.
--->
-
-<!--
-Simple. This example uses the simple.js library which is an example of a wrapper
-library that attempts to make O3D super simple to use. See the comments below.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Simple
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.simple');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-// we make these global so we can easily access them from the debugger.
-var g_simple;
-var g_cube;
-var g_finished = false; // for selenium testing
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes our app.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
-
- // Create an o3djs.simple object to manage things in a simple way.
- g_simple = o3djs.simple.create(o3dElement);
-
- // Create a cube.
- g_cube = g_simple.createCube(50);
-
- // You should now have a cube on the screen!
- // Examples of other commands you can issue (live from firebug if you want)
- //
- // g_cube.transform.translate(0, 0, -50); // translate the cube.
- // g_cube.setDiffuseColor(1, 0, 0, 1); // make the cube red.
- // g_cube.loadTexture("http://someplace.org/somefile.jpg"); // now textured.
- // g_simple.setCameraPosition(200, 100, -50); // move the camera
- // g_simple.setCameraTarget(0, 10, 0); // move the camera's target
- // g_simple.setFieldOfView(30 * Math.PI / 180); // change the field of view.
- // g_sphere = g_simple.createSphere(20, 10); // create a sphere.
- //
- // Try typing these commands from firebug live!
-
- g_finished = true; // for selenium testing.
-}
-
-</script>
-</head>
-<body>
-<h1>Simple</h1>
-Using the simple library.<br/>
-View the source of this sample to see the point.<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/simpletexture.html b/o3d/samples/simpletexture.html
deleted file mode 100644
index efd1734..0000000
--- a/o3d/samples/simpletexture.html
+++ /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.
--->
-
-<!--
-O3D Tutorial B3
-
-In this tutorial, we show how to use textures in o3d.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Tutorial B3: Textures
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.io');
-
-// Events
-// Run the init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_finished = false; // for selenium testing
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and draws the quad.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Setup an orthographic projection
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -g_client.width * 0.5,
- g_client.width * 0.5,
- -g_client.height * 0.5,
- g_client.height * 0.5,
- 0.1,
- 1000);
-
- // move the camera above the origin looking down.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 500, 0], // eye
- [0, 0, 0], // target
- [0, 0, -1]); // up
-
- // Create a material.
- var myMaterial = o3djs.material.createMaterialFromFile(
- g_pack,
- 'shaders/texture-only.shader',
- g_viewInfo.performanceDrawList);
-
- // Create a quad.
- var myShape = o3djs.primitives.createPlane(g_pack,
- myMaterial,
- 300, // width
- 300, // height
- 1, // quads across
- 1); // quads down
-
- // Get the material's sampler parameter
- var sampler_param = myMaterial.getParam('texSampler0');
- var sampler = g_pack.createObject('Sampler');
- sampler_param.value = sampler;
-
- // Load our texture. This happens asynchronously.
- var url = o3djs.util.getCurrentURI() + 'assets/texture_b3.jpg';
- o3djs.io.loadTexture(g_pack, url, function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- sampler.texture = texture;
- // adjust the scale of our transform to match the aspect ratio of
- // the texture. Of course we could also have waited until now to build
- // our plane and set its width and height to match instead of scaling
- // here.
- var textureWidth = texture.width;
- var textureHeight = texture.height;
- var hScale = 1;
- var vScale = 1;
- if (textureWidth > textureHeight) {
- vScale = textureHeight / textureWidth;
- } else if (textureHeight > textureWidth) {
- hScale = textureWidth / textureHeight;
- }
- // We now attach our quad to the root of the transform graph.
- // We do this after the texture has loaded, otherwise we'd be attempting
- // to display something invalid.
- var root = g_client.root;
- root.addShape(myShape);
- root.scale(hScale, 1, vScale);
-
- g_finished = true; // for selenium testing.
- }
- });
-}
-</script>
-</head>
-<body>
-<h1>Simple texturing</h1>
-This tutorial shows how we use textures in O3D.
-<br/>
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/simpleviewer/assets/empty.txt b/o3d/samples/simpleviewer/assets/empty.txt
deleted file mode 100644
index e69de29..0000000
--- a/o3d/samples/simpleviewer/assets/empty.txt
+++ /dev/null
diff --git a/o3d/samples/simpleviewer/simpleviewer.html b/o3d/samples/simpleviewer/simpleviewer.html
deleted file mode 100644
index 582cacd..0000000
--- a/o3d/samples/simpleviewer/simpleviewer.html
+++ /dev/null
@@ -1,365 +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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
- <title>
- Simple Scene Viewer
- </title>
-<style type="text/css">
-html, body {
- margin: 0;
- padding: 0;
- border: 0;
- height: 100%;
-}
-</style>
-</head>
-<body onload="init();" onunload="uninit();">
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.arcball');
-o3djs.require('o3djs.scene');
-
-var g_root;
-var g_o3d;
-var g_math;
-var g_quaternions;
-var g_client;
-var g_aball;
-var g_thisRot;
-var g_lastRot;
-var g_pack = null;
-var g_mainPack;
-var g_viewInfo;
-var g_lightPosParam;
-var g_loadingElement;
-var g_o3dWidth = -1;
-var g_o3dHeight = -1;
-var g_o3dElement;
-var g_finished = false; // for selenium
-
-var g_camera = {
- farPlane: 5000,
- nearPlane:0.1
-};
-
-var g_dragging = false;
-
-function startDragging(e) {
- g_lastRot = g_thisRot;
-
- g_aball.click([e.x, e.y]);
-
- g_dragging = true;
-}
-
-function drag(e) {
- if (g_dragging) {
- var rotationQuat = g_aball.drag([e.x, e.y]);
- var rot_mat = g_quaternions.quaternionToRotation(rotationQuat);
- g_thisRot = g_math.matrix4.mul(g_lastRot, rot_mat);
-
- var m = g_root.localMatrix;
- g_math.matrix4.setUpper3x3(m, g_thisRot);
- g_root.localMatrix = m;
- }
-}
-
-function stopDragging(e) {
- g_dragging = false;
-}
-
-function updateCamera() {
- var up = [0, 1, 0];
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(g_camera.eye,
- g_camera.target,
- up);
- g_lightPosParam.value = g_camera.eye;
-}
-
-function updateProjection() {
- // Create a perspective projection matrix.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45), g_o3dWidth / g_o3dHeight, g_camera.nearPlane,
- g_camera.farPlane);
-}
-
-function scrollMe(e) {
- if (e.deltaY) {
- var t = 1;
- if (e.deltaY > 0)
- t = 11 / 12;
- else
- t = 13 / 12;
- g_camera.eye = g_math.lerpVector(g_camera.target, g_camera.eye, t);
-
- updateCamera();
- }
-}
-
-function enableInput(enable) {
- document.getElementById("url").disabled = !enable;
- document.getElementById("load").disabled = !enable;
-}
-
-function loadFile(context, path) {
- function callback(pack, parent, exception) {
- enableInput(true);
- if (exception) {
- alert("Could not load: " + path + "\n" + exception);
- g_loadingElement.innerHTML = "loading failed.";
- } else {
- g_loadingElement.innerHTML = "loading finished.";
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
- var bbox = o3djs.util.getBoundingBoxOfTree(g_client.root);
- g_camera.target = g_math.lerpVector(bbox.minExtent, bbox.maxExtent, 0.5);
- var diag = g_math.length(g_math.subVector(bbox.maxExtent,
- bbox.minExtent));
- g_camera.eye = g_math.addVector(g_camera.target, [0, 0, 1.5 * diag]);
- g_camera.nearPlane = diag / 1000;
- g_camera.farPlane = diag * 10;
- setClientSize();
- updateCamera();
- updateProjection();
-
- // Manually connect all the materials' lightWorldPos params to the context
- var materials = pack.getObjectsByClassName('o3d.Material');
- for (var m = 0; m < materials.length; ++m) {
- var material = materials[m];
- var param = material.getParam('lightWorldPos');
- if (param) {
- param.bind(g_lightPosParam);
- }
- }
-
- g_finished = true; // for selenium
-
- // Comment out the next line to dump lots of info.
- if (false) {
- o3djs.dump.dump('---dumping context---\n');
- o3djs.dump.dumpParamObject(context);
-
- o3djs.dump.dump('---dumping root---\n');
- o3djs.dump.dumpTransformTree(g_client.root);
-
- o3djs.dump.dump('---dumping render root---\n');
- o3djs.dump.dumpRenderNodeTree(g_client.renderGraphRoot);
-
- o3djs.dump.dump('---dump g_pack shapes---\n');
- var shapes = pack.getObjectsByClassName('o3d.Shape');
- for (var t = 0; t < shapes.length; t++) {
- o3djs.dump.dumpShape(shapes[t]);
- }
-
- o3djs.dump.dump('---dump g_pack materials---\n');
- var materials = pack.getObjectsByClassName('o3d.Material');
- for (var t = 0; t < materials.length; t++) {
- o3djs.dump.dump (
- ' ' + t + ' : ' + materials[t].className +
- ' : "' + materials[t].name + '"\n');
- o3djs.dump.dumpParams(materials[t], ' ');
- }
-
- o3djs.dump.dump('---dump g_pack textures---\n');
- var textures = pack.getObjectsByClassName('o3d.Texture');
- for (var t = 0; t < textures.length; t++) {
- o3djs.dump.dumpTexture(textures[t]);
- }
-
- o3djs.dump.dump('---dump g_pack effects---\n');
- var effects = pack.getObjectsByClassName('o3d.Effect');
- for (var t = 0; t < effects.length; t++) {
- o3djs.dump.dump (' ' + t + ' : ' + effects[t].className +
- ' : "' + effects[t].name + '"\n');
- o3djs.dump.dumpParams(effects[t], ' ');
- }
- }
- }
- }
-
- g_pack = g_client.createPack();
-
- // Create a new transform for the loaded file
- var parent = g_pack.createObject('Transform');
- parent.parent = g_client.root;
- if (path != null) {
- g_loadingElement.innerHTML = "Loading: " + path;
- enableInput(false);
- try {
- o3djs.scene.loadScene(g_client, g_pack, parent, path, callback);
- } catch (e) {
- enableInput(true);
- g_loadingElement.innerHTML = "loading failed : " + e;
- }
- }
-
- return parent;
-}
-
-function setClientSize() {
- var newWidth = parseInt(g_client.width);
- var newHeight = parseInt(g_client.height);
-
- if (newWidth != g_o3dWidth || newHeight != g_o3dHeight) {
- g_o3dWidth = newWidth;
- g_o3dHeight = newHeight;
-
- updateProjection();
-
- // Sets a new area size for arcball.
- g_aball.setAreaSize(g_o3dWidth, g_o3dHeight);
- }
-}
-
-/**
- * Called every frame.
- */
-function onRender() {
- // If we don't check the size of the client area every frame we don't get a
- // chance to adjust the perspective matrix fast enough to keep up with the
- // browser resizing us.
- setClientSize();
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- path = path.substring(0, index+1) + 'assets/cube.o3dtgz';
- var url = document.getElementById("url").value = path;
- g_loadingElement = document.getElementById('loading');
-
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_quaternions = o3djs.quaternions;
- g_client = g_o3dElement.client;
-
- g_mainPack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_mainPack,
- g_client.root,
- g_client.renderGraphRoot);
-
- g_lastRot = g_math.matrix4.identity();
- g_thisRot = g_math.matrix4.identity();
-
- var root = g_client.root;
-
- g_aball = o3djs.arcball.create(100, 100);
- setClientSize();
-
- // Set the light at the same position as the camera to create a headlight
- // that illuminates the object straight on.
- var paramObject = g_mainPack.createObject('ParamObject');
- g_lightPosParam = paramObject.createParam('lightWorldPos', 'ParamFloat3');
- g_camera.target = [0, 0, 0];
- g_camera.eye = [0, 0, 5];
- updateCamera();
-
- doload()
-
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', startDragging);
- o3djs.event.addEventListener(g_o3dElement, 'mousemove', drag);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', stopDragging);
- o3djs.event.addEventListener(g_o3dElement, 'wheel', scrollMe);
-
- g_client.setRenderCallback(onRender);
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-function doload() {
- if (g_root) {
- g_root.parent = null;
- g_root = null;
- }
- if (g_pack) {
- g_pack.destroy();
- g_pack = null;
- }
- var url = document.getElementById('url').value;
- g_root = loadFile(g_viewInfo.drawContext, url);
-}
-</script>
-<table width="100%" style="height:100%;">
- <tr><td valign="middle" align="center" height="100%">
-<table width="100%" style="height:100%;"><tr><td height="100%">
-<h1>
-Simple Scene Viewer
-</h1>
-<table id="container" width="90%" style="height:60%;" border="2"><tr><td height="100%">
-<div id="o3d" style="width: 100%; height: 100%;"></div>
-</td></tr></table>
-<p>
-</p>
-
-<input type="text" id="url" size="100">
-<input type="button" id="load" onclick="doload();" value="load"><BR>
-
-Drag The Mouse To Rotate<br/>
-Scrollwheel To Zoom<br/>
-Resize The Window To Resize The View
-<div style="color: red;" id="loading"></div>
-</td></tr></table>
-</td></tr></table>
-</body>
-</html>
-
-
diff --git a/o3d/samples/siteswap/animation.js b/o3d/samples/siteswap/animation.js
deleted file mode 100644
index c9aa80a..0000000
--- a/o3d/samples/siteswap/animation.js
+++ /dev/null
@@ -1,198 +0,0 @@
-// @@REWRITE(insert js-copyright)
-// @@REWRITE(delete-start)
-// Copyright 2009 Google Inc. All Rights Reserved
-// @@REWRITE(delete-end)
-
-/**
- * This file contains the animation-management code for the siteswap animator.
- * This is encapsulated in the EventQueue and QueueEvent classes, the event
- * handler, and startAnimation, the main external interface to the animation.
- */
-
-/**
- * A record, held in the EventQueue, that describes the curve that should be
- * given to a shape at a time.
- * @constructor
- * @param {!number} time base time at which the event occurs/the curve starts.
- * @param {!o3d.Shape} shape the shape to be updated.
- * @param {Curve} curve the path for the shape to follow.
- */
-function QueueEvent(time, shape, curve) {
- this.time = time;
- this.shape = shape;
- this.curve = curve;
- return this;
-}
-
-/**
- * A circular queue of events that will happen during the course of an animation
- * that's duration beats long. The queue is ordered by the time each curve
- * starts. Note that a curve may start after it ends, since time loops
- * endlessly. The nextEvent field is the index of the next event to occur; it
- * keeps track of how far we've gotten in the queue.
- * @constructor
- * @param {!number} duration the length of the animation in beats.
- */
-function EventQueue(duration) {
- this.events = [];
- this.nextEvent = 0;
- this.duration = duration;
- this.timeCorrection = 0; // Corrects from queue entry time to real time.
- return this;
-}
-
-/**
- * Add an event to the queue, inserting into order by its time field.
- * A heap-based priority queue would be faster, but likely overkill, as this
- * won't ever contain that many items, and isn't likely to be speed-critical.
- * @param {!QueueEvent} event the event to add.
- */
-EventQueue.prototype.addEvent = function(event) {
- var i = 0;
- while (i < this.events.length && event.time > this.events[i].time) {
- ++i;
- }
- this.events.splice(i, 0, event);
-};
-
-/**
- * Pull the next event off the queue.
- * @return {!QueueEvent} the event.
- */
-EventQueue.prototype.shift = function() {
- var e = this.events[this.nextEvent];
- if (++this.nextEvent >= this.events.length) {
- assert(this.nextEvent > 0);
- this.nextEvent = 0;
- this.timeCorrection += this.duration;
- }
- return e;
-};
-
-/**
- * Process all current events, updating all animated objects with their new
- * curves, until we find that the next event in the queue is in the future.
- * @param {!number} time the current time in beats. This number is an absolute,
- * not locked to the range of the duration of the pattern, so getNextTime()
- * returns a doctored number to add in the offset from in-pattern time to real
- * time.
- * @return {!number} the time of the next future event.
- */
-EventQueue.prototype.processEvents = function(time) {
- while (this.getNextTime() <= time) {
- var e = this.shift();
- setParamCurveInfo(e.curve, e.shape, time);
- }
- return this.getNextTime(); // In case you want to set a callback.
-};
-
-/**
- * Look up the initial curve for a shape [the curve that it'll be starting or in
- * the middle of at time 0].
- * @param {!CurveSet} curveSet the complete set of curves for a Shape.
- * @return {!Object} the curve and the time at which it would have started.
- */
-function getInitialCurveInfo(curveSet) {
- var curve = curveSet.getCurveForUnsafeTime(0);
- var curveBaseTime;
- if (!curve.startTime) {
- curveBaseTime = 0;
- } else {
- // If the curve isn't starting now, it must have wrapped around.
- assert(curve.startTime + curve.duration > curveSet.duration);
- // So subtract off one wrap so that its startTime is in the right space of
- // numbers. We assume here that no curve duration is longer than the
- // pattern, which must be guaranteed by the code that generates patterns.
- assert(curve.duration <= curveSet.duration);
- curveBaseTime = curve.startTime - curveSet.duration;
- }
- return { curve: curve, curveBaseTime: curveBaseTime };
-}
-
-/**
- * Set up the event queue with a complete pattern starting at time 0.
- * @param {!Array.CurveSet} curveSets the curve sets for all shapes.
- * @param {!Array.o3d.Shape} shapes all the shapes to animate.
- */
-EventQueue.prototype.setUp = function(curveSets, shapes) {
- assert(curveSets.length == shapes.length);
- for (var i = 0; i < shapes.length; ++i) {
- var curveSet = curveSets[i];
- assert(this.duration % curveSet.duration == 0);
- var shape = shapes[i];
- var record = getInitialCurveInfo(curveSet);
- var curveBaseTime = record.curveBaseTime;
- var curve = record.curve;
- setParamCurveInfo(curve, shape, curveBaseTime);
- do {
- curveBaseTime += curve.duration;
- curve = curveSet.getCurveForTime(curveBaseTime);
- var e = new QueueEvent(curveBaseTime % this.duration, shape, curve);
- this.addEvent(e);
- } while (curveBaseTime + curve.duration <= this.duration);
- }
-};
-
-/**
- * Return the time of the next future event.
- * @return {!number} the time.
- */
-EventQueue.prototype.getNextTime = function() {
- return this.events[this.nextEvent].time + this.timeCorrection;
-};
-
-/**
- * This is the event handler that runs the whole animation. When triggered by
- * the counter, it updates the curves on all objects whose curves have expired.
- *
- * The current time will be some time around when we wanted to be called. It
- * might be exact, but it might be a bit off due to floating point error, or a
- * lot off due to the system getting bogged down somewhere for a second or
- * two. e.g. if we wanted to get a call at time 7, it's likely to be
- * something like 7.04, but might even be 11. We then use 7, not 7.04, as the
- * start time for each of the curves set, so as to remove clock drift. Since
- * the time we wanted to be called is stored in the next item in the queue, we
- * can just pull that out and use it. However, if we then find that we're
- * setting our callback in the past, we repeat the process until our callback
- * is set safely in the future. We may get some visual artifacts, but at
- * least we won't drop any events [leading to stuff drifting endlessly off
- * into the distance].
- */
-function handler() {
- var eventTime = g.eventQueue.getNextTime();
- var trueCurrentTime;
- do {
- g.counter.removeCallback(eventTime);
- eventTime = g.eventQueue.processEvents(eventTime);
- g.counter.addCallback(eventTime, handler);
- trueCurrentTime = g.counter.count;
- } while (eventTime < trueCurrentTime);
-}
-
-/**
- * Given a precomputed juggling pattern, this sets up the O3D objects,
- * EventQueue, and callback necessary to start an animation, then calls
- * updateAnimating to kick it off if enabled.
- *
- * @param {!number} numBalls the number of balls in the animation.
- * @param {!number} numHands the number of hands in the animation.
- * @param {!number} duration the length of the full animation cycle in beats.
- * @param {!Array.CurveSet} ballCurveSets one CurveSet per ball.
- * @param {!Array.CurveSet} handCurveSets one CurveSet per hand.
- */
-function startAnimation(numBalls, numHands, duration, ballCurveSets,
- handCurveSets) {
- g.counter.running = false;
- g.counter.reset();
-
- setNumBalls(numBalls);
- setNumHands(numHands);
-
- g.eventQueue = new EventQueue(duration);
- g.eventQueue.setUp(handCurveSets, g.handShapes);
- g.eventQueue.setUp(ballCurveSets, g.ballShapes);
- g.counter.addCallback(g.eventQueue.getNextTime(), handler);
-
- updateAnimating();
-}
-
diff --git a/o3d/samples/siteswap/math.js b/o3d/samples/siteswap/math.js
deleted file mode 100644
index e584744..0000000
--- a/o3d/samples/siteswap/math.js
+++ /dev/null
@@ -1,1492 +0,0 @@
-// @@REWRITE(insert js-copyright)
-// @@REWRITE(delete-start)
-// Copyright 2009 Google Inc. All Rights Reserved
-// @@REWRITE(delete-end)
-
-/**
- * @fileoverview This file contains all the math for the siteswap animator. It
- * handles all of the site-swap-related stuff [converting a sequence of integers
- * into a more-useful representation of a pattern, pattern validation, etc.] as
- * well as all the physics used for the simulation.
- */
-
-/**
- * This is a container class that holds the coefficients of an equation
- * describing the motion of an object.
- * The basic equation is:
- * f(x) := a t^2 + b t + c + d sin (f t) + e cos (f t).
- * However, sometimes we LERP between that function and this one:
- * g(x) := lA t^2 + lB t + lC
- * lerpRate [so far] is always either 1 [LERP from f to g over 1 beat] or -1,
- * [LERP from g to f over one beat].
- *
- * Just plug in t to evaluate the equation. There's no JavaScript function to
- * do this because it's always done on the GPU.
- *
- * @constructor
- */
-EquationCoefficients = function(a, b, c, d, e, f, lA, lB, lC, lerpRate) {
- assert(!isNaN(a) && !isNaN(b) && !isNaN(c));
- d = d || 0;
- e = e || 0;
- f = f || 0;
- assert(!isNaN(d) && !isNaN(e) && !isNaN(f));
- lA = lA || 0;
- lB = lB || 0;
- lC = lC || 0;
- assert(!isNaN(lA) && !isNaN(lB) && !isNaN(lC));
- lerpRate = lerpRate || 0;
- this.a = a;
- this.b = b;
- this.c = c;
- this.d = d;
- this.e = e;
- this.f = f;
- this.lA = lA;
- this.lB = lB;
- this.lC = lC;
- this.lerpRate = lerpRate;
-}
-
-/**
- * Create a new equation that's equivalent to this equation's coefficients a-f
- * with a LERP to the polynomial portion of the supplied equation.
- * @param {!EquationCoefficients} eqn the source of coefficients.
- * @param {!number} lerpRate the rate and direction of the LERP; positive for
- * "from this equation to the new one" and vice-versa.
- * @return {!EquationCoefficients} a new set of coefficients.
- */
-EquationCoefficients.prototype.lerpIn = function(eqn, lerpRate) {
- assert(!this.lerpRate);
- return new EquationCoefficients(this.a, this.b, this.c, this.d, this.e,
- this.f, eqn.a, eqn.b, eqn.c, lerpRate);
-};
-
-/**
- * Convert the EquationCoefficients to a string for debugging.
- * @return {String} debugging output.
- */
-EquationCoefficients.prototype.toString = function() {
- return 'F(t) := ' + this.a.toFixed(2) + ' t^2 + ' + this.b.toFixed(2) +
- ' t + ' + this.c.toFixed(2) + ' + ' +
- this.d.toFixed(2) + ' sin(' + this.f.toFixed(2) + ' t) + ' +
- this.e.toFixed(2) + ' cos(' + this.f.toFixed(2) + ' t) + LERP(' +
- this.lerpRate.toFixed(2) + ') of ' +
- this.lA.toFixed(2) + ' t^2 + ' + this.lB.toFixed(2) +
- ' t + ' + this.lC.toFixed(2);
-};
-
-/**
- * A set of equations which describe the motion of an object over time.
- * The three equations each supply one dimension of the motion, and the curve is
- * valid from startTime to startTime + duration.
- * @param {!number} startTime the initial time at which the curve is valid.
- * @param {!number} duration how long [in beats] the curve is valid.
- * @param {!EquationCoefficients} xEqn the equation for motion in x.
- * @param {!EquationCoefficients} yEqn the equation for motion in y.
- * @param {!EquationCoefficients} zEqn the equation for motion in z.
- * @constructor
- */
-Curve = function(startTime, duration, xEqn, yEqn, zEqn) {
- this.startTime = startTime;
- this.duration = duration;
- this.xEqn = xEqn;
- this.yEqn = yEqn;
- this.zEqn = zEqn;
-}
-
-/**
- * Convert the Curve to a string for debugging.
- * @return {String} debugging output.
- */
-Curve.prototype.toString = function() {
- var s = 'startTime: ' + this.startTime + '\n';
- s += 'duration: ' + this.duration + '\n';
- s += this.xEqn + '\n';
- s += this.yEqn + '\n';
- s += this.zEqn + '\n';
- return s;
-};
-
-/**
- * Modify this curve's coefficients to include a LERP to the polynomial
- * portion of the supplied curve.
- * @param {!Curve} curve the source of coefficients.
- * @param {!number} lerpRate the rate and direction of the LERP; positive for
- * "from this equation to the new one" and vice-versa.
- * @return {!Curve} a new curve.
- */
-Curve.prototype.lerpIn = function(curve, lerpRate) {
- assert(this.startTime == curve.startTime);
- assert(this.duration == curve.duration);
- var xEqn = this.xEqn.lerpIn(curve.xEqn, lerpRate);
- var yEqn = this.yEqn.lerpIn(curve.yEqn, lerpRate);
- var zEqn = this.zEqn.lerpIn(curve.zEqn, lerpRate);
- return new Curve(this.startTime, this.duration, xEqn, yEqn, zEqn);
-};
-
-/**
- * Produce a set of polynomial coefficients that describe linear motion between
- * two points in 1 dimension.
- * @param {!number} startPos the starting position.
- * @param {!number} endPos the ending position.
- * @param {!number} duration how long the motion takes.
- * @return {!EquationCoefficients} the equation for the motion.
- */
-Curve.computeLinearCoefficients = function(startPos, endPos, duration) {
- return new EquationCoefficients(
- 0, (endPos - startPos) / duration, startPos);
-}
-
-var GRAVITY = 1; // Higher means higher throws for the same duration.
-/**
- * Produce a set of polynomial coefficients that describe parabolic motion
- * between two points in 1 dimension.
- * @param {!number} startPos the starting position.
- * @param {!number} endPos the ending position.
- * @param {!number} duration how long the motion takes.
- * @return {!EquationCoefficients} the equation for the motion.
- */
-Curve.computeParabolicCoefficients = function(startPos, endPos, duration) {
- var dY = endPos - startPos;
- return new EquationCoefficients(-GRAVITY / 2,
- dY / duration + GRAVITY * duration / 2,
- startPos);
-}
-
-/**
- * Compute the curve taken by a ball given its throw and catch positions, the
- * time it was thrown, and how long it stayed in the air.
- *
- * We use duration rather than throwTime and catchTime because, what
- * with the modular arithmetic used in our records, catchTime might be before
- * throwTime, and in some representations the pattern could wrap around a few
- * times while the ball's in the air. When the parabola computed here is used,
- * time must be supplied as an offset from the time of the throw, and must of
- * course not wrap at all. That is, these coefficients work for f(0) ==
- * throwPos, f(duration) == catchPos.
- *
- * We treat the y axis as vertical and thus affected by gravity.
- *
- * @param {!EquationCoefficients} throwPos
- * @param {!EquationCoefficients} catchPos
- * @param {!number} startTime
- * @param {!number} duration
- * @return {!Curve}
- */
-Curve.computeThrowCurve = function(throwPos, catchPos, startTime, duration) {
- var xEqn = Curve.computeLinearCoefficients(throwPos.x, catchPos.x, duration);
- var yEqn = Curve.computeParabolicCoefficients(throwPos.y, catchPos.y,
- duration);
- var zEqn = Curve.computeLinearCoefficients(throwPos.z, catchPos.z, duration);
- return new Curve(startTime, duration, xEqn, yEqn, zEqn);
-}
-
-/**
- * Compute a straight line Curve given start and end positions, the start time,
- * and the duration of the motion.
- *
- * @param {!EquationCoefficients} startPos
- * @param {!EquationCoefficients} endPos
- * @param {!number} startTime
- * @param {!number} duration
- * @return {!Curve}
- */
-Curve.computeStraightLineCurve =
- function(startPos, endPos, startTime, duration) {
- var xEqn = Curve.computeLinearCoefficients(startPos.x, endPos.x, duration);
- var yEqn = Curve.computeLinearCoefficients(startPos.y, endPos.y, duration);
- var zEqn = Curve.computeLinearCoefficients(startPos.z, endPos.z, duration);
- return new Curve(startTime, duration, xEqn, yEqn, zEqn);
-}
-
-/**
- * Threshold horizontal distance below which computeCircularCurve won't bother
- * trying to approximate a circular curve. See the comment above
- * computeCircularCurve for more info.
- * @type {number}
- */
-Curve.EPSILON = .0001;
-
-/**
- * Compute a circular curve, used as an approximation for the motion of a hand
- * between a catch and its following throw.
- *
- * Assumes a lot of stuff about this looking like a "normal" throw: the catch is
- * moving roughly the opposite direction as the throw, the throw and catch
- * aren't at the same place, and such. Otherwise this looks very odd at best.
- * This is used for the height of the curve.
- * This produces coefficients for d sin(f t) + e cos(f t) for each of x, y, z.
- * It produces a vertical-ish circular curve from the start to the end, going
- * down, then up. So if dV [the distance from the start to finish in the x-z
- * plane, ignoring y] is less than Curve.EPSILON, it doesn't know which way down
- * is, and it bails by returning a straight line instead.
- */
-Curve.computeCircularCurve = function(startPos, endPos, startTime, duration) {
- var dX = endPos.x - startPos.x;
- var dY = endPos.y - startPos.y;
- var dZ = endPos.z - startPos.z;
- var dV = Math.sqrt(dX * dX + dZ * dZ);
- if (dV < Curve.EPSILON) {
- return Curve.computeStraightLineCurve(startPos, endPos, startTime,
- duration);
- }
- var negHalfdV = -0.5 * dV;
- var negHalfdY = -0.5 * dY;
- var f = Math.PI / duration;
- var yEqn = new EquationCoefficients(
- 0, 0, startPos.y + dY / 2,
- negHalfdV, negHalfdY, f);
- var ratio = dX / dV;
- var xEqn = new EquationCoefficients(
- 0, 0, startPos.x + dX / 2,
- negHalfdY * ratio, negHalfdV * ratio, f);
- ratio = dZ / dV;
- var zEqn = new EquationCoefficients(
- 0, 0, startPos.z + dZ / 2,
- negHalfdY * ratio, negHalfdV * ratio, f);
- return new Curve(startTime, duration, xEqn, yEqn, zEqn);
-}
-
-/**
- * This is the abstract base class for an object that describes a throw, catch,
- * or empty hand [placeholder] in a site-swap pattern.
- * @constructor
- */
-Descriptor = function() {
-}
-
-/**
- * Create an otherwise-identical copy of this descriptor at a given time offset.
- * Note that offset may put time past patternLength; the caller will have to fix
- * this up manually.
- * @param {number} offset how many beats to offset the new descriptor.
- * Derived classes must override this function.
- */
-Descriptor.prototype.clone = function(offset) {
- throw new Error('Unimplemented.');
-};
-
-/**
- * Generate the Curve implied by this descriptor and the supplied hand
- * positions.
- * @param {!Array.HandPositionRecord} handPositions where the hands will be.
- * Derived classes must override this function.
- */
-Descriptor.prototype.generateCurve = function(handPositions) {
- throw new Error('Unimplemented.');
-};
-
-/**
- * Adjust the start time of this Descriptor to be in [0, pathLength).
- * @param {!number} pathLength the duration of a path, in beats.
- * @return {!Descriptor} this.
- */
-Descriptor.prototype.fixUpModPathLength = function(pathLength) {
- this.time = this.time % pathLength;
- return this;
-};
-
-/**
- * This describes a throw in a site-swap pattern.
- * @param {!number} throwNum the site-swap number of the throw.
- * @param {!number} throwTime the time this throw occurs.
- * @param {!number} sourceHand the index of the throwing hand.
- * @param {!number} destHand the index of the catching hand.
- * @constructor
- */
-ThrowDescriptor = function(throwNum, throwTime, sourceHand, destHand) {
- this.throwNum = throwNum;
- this.sourceHand = sourceHand;
- this.destHand = destHand;
- this.time = throwTime;
-}
-
-/**
- * This is a subclass of Descriptor.
- */
-ThrowDescriptor.prototype = new Descriptor();
-
-/**
- * Set up the constructor, just to be neat.
- */
-ThrowDescriptor.prototype.constructor = ThrowDescriptor;
-
-/**
- * We label each Descriptor subclass with a type for debugging.
- */
-ThrowDescriptor.prototype.type = 'THROW';
-
-/**
- * Create an otherwise-identical copy of this descriptor at a given time offset.
- * Note that offset may put time past patternLength; the caller will have to fix
- * this up manually.
- * @param {number} offset how many beats to offset the new descriptor.
- * @return {!Descriptor} the new copy.
- */
-ThrowDescriptor.prototype.clone = function(offset) {
- offset = offset || 0; // Turn null into 0.
- return new ThrowDescriptor(this.throwNum, this.time + offset,
- this.sourceHand, this.destHand);
-};
-
-/**
- * Convert the ThrowDescriptor to a string for debugging.
- * @return {String} debugging output.
- */
-ThrowDescriptor.prototype.toString = function() {
- return '(' + this.throwNum + ' from hand ' + this.sourceHand + ' to hand ' +
- this.destHand + ')';
-};
-
-/**
- * Generate the Curve implied by this descriptor and the supplied hand
- * positions.
- * @param {!Array.HandPositionRecord} handPositions where the hands will be.
- * @return {!Curve} the curve.
- */
-ThrowDescriptor.prototype.generateCurve = function(handPositions) {
- var startPos = handPositions[this.sourceHand].throwPositions[this.destHand];
- var endPos = handPositions[this.destHand].catchPosition;
- return Curve.computeThrowCurve(startPos, endPos, this.time,
- this.throwNum - 1); };
-
-/**
- * This describes a catch in a site-swap pattern.
- * @param {!number} hand the index of the catching hand.
- * @param {!number} sourceThrowNum the site-swap number of the preceeding throw.
- * @param {!number} destThrowNum the site-swap number of the following throw.
- * @param {!number} sourceHand the index of the hand throwing the source throw.
- * @param {!number} destHand the index of the hand catching the following throw.
- * @param {!number} catchTime the time at which the catch occurs.
- * @constructor
- */
-CarryDescriptor = function(hand, sourceThrowNum, destThrowNum, sourceHand,
- destHand, catchTime) {
- this.hand = hand;
- this.sourceThrowNum = sourceThrowNum;
- this.destThrowNum = destThrowNum;
- this.sourceHand = sourceHand;
- this.destHand = destHand;
- this.time = catchTime;
-}
-
-/**
- * This is a subclass of Descriptor.
- */
-CarryDescriptor.prototype = new Descriptor();
-
-/**
- * Set up the constructor, just to be neat.
- */
-CarryDescriptor.prototype.constructor = CarryDescriptor;
-
-/**
- * We label each Descriptor subclass with a type for debugging.
- */
-CarryDescriptor.prototype.type = 'CARRY';
-
-/**
- * Since this gets pathLength, not patternLength, we'll have to collapse sets
- * of CarryDescriptors later, as they may be spread sparsely through the full
- * animation and we'll only want them to be distributed over the full pattern
- * length. We may have dupes to throw away as well.
- * @param {!ThrowDescriptor} inThrowDescriptor
- * @param {!ThrowDescriptor} outThrowDescriptor
- * @param {!number} pathLength
- * @return {!CarryDescriptor}
- */
-CarryDescriptor.fromThrowDescriptors = function(inThrowDescriptor,
- outThrowDescriptor, pathLength) {
- assert(inThrowDescriptor.destHand == outThrowDescriptor.sourceHand);
- assert((inThrowDescriptor.time + inThrowDescriptor.throwNum) %
- pathLength == outThrowDescriptor.time);
- return new CarryDescriptor(inThrowDescriptor.destHand,
- inThrowDescriptor.throwNum, outThrowDescriptor.throwNum,
- inThrowDescriptor.sourceHand, outThrowDescriptor.destHand,
- (outThrowDescriptor.time + pathLength - 1) % pathLength);
-};
-
-/**
- * Create an otherwise-identical copy of this descriptor at a given time offset.
- * Note that offset may put time past patternLength; the caller will have to fix
- * this up manually.
- * @param {number} offset how many beats to offset the new descriptor.
- * @return {!Descriptor} the new copy.
- */
-CarryDescriptor.prototype.clone = function(offset) {
- offset = offset || 0; // Turn null into 0.
- return new CarryDescriptor(this.hand, this.sourceThrowNum,
- this.destThrowNum, this.sourceHand, this.destHand, this.time + offset);
-};
-
-/**
- * Convert the CarryDescriptor to a string for debugging.
- * @return {String} debugging output.
- */
-CarryDescriptor.prototype.toString = function() {
- return 'time: ' + this.time + ' (hand ' + this.hand + ' catches ' +
- this.sourceThrowNum + ' from hand ' + this.sourceHand + ' then throws ' +
- this.destThrowNum + ' to hand ' + this.destHand + ')';
-};
-
-/**
- * Test if this CarryDescriptor is equivalent to another, mod patternLength.
- * @param {!CarryDescriptor} cd the other CarryDescriptor.
- * @param {!number} patternLength the length of the pattern.
- * @return {!bool}
- */
-CarryDescriptor.prototype.equalsWithMod = function(cd, patternLength) {
- if (!(cd instanceof CarryDescriptor)) {
- return false;
- }
- if (this.hand != cd.hand) {
- return false;
- }
- if (this.sourceThrowNum != cd.sourceThrowNum) {
- return false;
- }
- if (this.destThrowNum != cd.destThrowNum) {
- return false;
- }
- if (this.sourceHand != cd.sourceHand) {
- return false;
- }
- if (this.destHand != cd.destHand) {
- return false;
- }
- if (this.time % patternLength != cd.time % patternLength) {
- return false;
- }
- return true;
-};
-
-/**
- * Generate the Curve implied by this descriptor and the supplied hand
- * positions.
- * @param {!Array.HandPositionRecord} handPositions where the hands will be.
- * @return {!Curve} the curve.
- */
-CarryDescriptor.prototype.generateCurve = function(handPositions) {
- var startPos = handPositions[this.hand].catchPosition;
- var endPos = handPositions[this.hand].throwPositions[this.destHand];
- return Curve.computeCircularCurve(startPos, endPos, this.time, 1);
-};
-
-/**
- * This describes a carry of a "1" in a site-swap pattern.
- * The flags isThrow and isCatch tell whether this is the actual 1 [isThrow] or
- * the carry that receives the handoff [isCatch]. It's legal for both to be
- * true, which happens when there are two 1s in a row.
- * @param {!number} sourceThrowNum the site-swap number of the prev throw
- * [including this one if isCatch].
- * @param {!number} sourceHand the index of the hand throwing sourceThrowNum.
- * @param {!number} destThrowNum the site-swap number of the next throw
- * [including this one if isThrow].
- * @param {!number} destHand the index of the hand catching destThrowNum.
- * @param {!number} hand the index of the hand doing this carry.
- * @param {!number} time the time at which the carry starts.
- * @param {!bool} isThrow whether this is a 1.
- * @param {!bool} isCatch whether this is the carry after a 1.
- * @constructor
- */
-CarryOneDescriptor = function(sourceThrowNum, sourceHand, destThrowNum,
- destHand, hand, time, isThrow, isCatch) {
- // It's possible to have !isCatch with sourceThrowNum == 1 temporarily, if we
- // just haven't handled that 1 yet [we're doing the throw of this one, and
- // will later get to the previous one, due to wraparound], and vice-versa.
- assert(isThrow || (sourceThrowNum == 1));
- assert(isCatch || (destThrowNum == 1));
- this.sourceThrowNum = sourceThrowNum;
- this.sourceHand = sourceHand;
- this.destHand = destHand;
- this.destThrowNum = destThrowNum;
- this.hand = hand;
- this.time = time;
- this.isThrow = isThrow;
- this.isCatch = isCatch;
- return this;
-}
-
-/**
- * This is a subclass of Descriptor.
- */
-CarryOneDescriptor.prototype = new Descriptor();
-
-/**
- * Set up the constructor, just to be neat.
- */
-CarryOneDescriptor.prototype.constructor = CarryOneDescriptor;
-
-/**
- * We label each Descriptor subclass with a type for debugging.
- */
-CarryOneDescriptor.prototype.type = 'CARRY_ONE';
-
-/**
- * Create a pair of CarryOneDescriptors to describe the carry that is a throw of
- * 1. A 1 spends all its time being carried, so these two carries surrounding
- * it represent [and therefore don't have] a throw between them.
- * Prev and post are generally the ordinary CarryDescriptors surrounding the
- * throw of 1 that we're trying to implement. However, they could each [or
- * both] independently be CarryOneDescriptors implementing other 1 throws.
- * @param {!Descriptor} prev the carry descriptor previous to the 1.
- * @param {!Descriptor} post the carry descriptor subsequent to the 1.
- * @return {!Array.CarryOneDescriptor} a pair of CarryOneDescriptors.
- */
-CarryOneDescriptor.getDescriptorPair = function(prev, post) {
- assert(prev instanceof CarryDescriptor || prev instanceof CarryOneDescriptor);
- assert(post instanceof CarryDescriptor || post instanceof CarryOneDescriptor);
- assert(prev.destHand == post.hand);
- assert(prev.hand == post.sourceHand);
- var newPrev;
- var newPost;
- if (prev instanceof CarryOneDescriptor) {
- assert(prev.isCatch && !prev.isThrow);
- newPrev = prev;
- newPrev.isThrow = true;
- assert(newPrev.destHand == post.hand);
- } else {
- newPrev = new CarryOneDescriptor(prev.sourceThrowNum, prev.sourceHand, 1,
- post.hand, prev.hand, prev.time, true, false);
- }
- if (post instanceof CarryOneDescriptor) {
- assert(post.isThrow && !post.isCatch);
- newPost = post;
- newPost.isCatch = true;
- assert(newPost.sourceHand == prev.hand);
- assert(newPost.sourceThrowNum == 1);
- } else {
- newPost = new CarryOneDescriptor(1, prev.hand, post.destThrowNum,
- post.destHand, post.hand, post.time, false, true);
- }
- return [newPrev, newPost];
-};
-
-/**
- * Convert the CarryOneDescriptor to a string for debugging.
- * @return {String} debugging output.
- */
-CarryOneDescriptor.prototype.toString = function() {
- var s;
- if (this.isThrow) {
- s = 'Hand ' + this.hand + ' catches a ' + this.sourceThrowNum + ' from ' +
- this.sourceHand + ' at time ' + this.time + ' and then passes a 1 to ' +
- this.destHand + '.';
- } else {
- assert(this.isCatch && this.sourceThrowNum == 1);
- s = 'Hand ' + this.hand + ' catches a 1 from ' + this.sourceHand +
- ' at time ' + this.time + ' and then passes a ' + this.destThrowNum +
- ' to ' + this.destHand + '.';
- }
- return s;
-};
-
-/**
- * Compute the curve taken by a ball during the carry representing a 1, as long
- * as it's not both a catch and a throw of a 1, which is handled elsewhere.
- * It's either a LERP from a circular curve [a catch of a throw > 1] to a
- * straight line to the handoff point [for isThrow] or a LERP from a straight
- * line from the handoff to a circular curve for the next throw > 1 [for
- * isCatch].
- *
- * @param {!EquationCoefficients} catchPos
- * @param {!EquationCoefficients} throwPos
- * @param {!EquationCoefficients} handoffPos
- * @param {!number} startTime
- * @param {!bool} isCatch whether this is the carry after a 1.
- * @param {!bool} isThrow whether this is a 1.
- * @return {!Curve}
- */
-Curve.computeCarryOneCurve = function(catchPos, throwPos, handoffPos, startTime,
- isCatch, isThrow) {
- assert(!isCatch != !isThrow);
- var curve = Curve.computeCircularCurve(catchPos, throwPos, startTime, 1);
- var curve2 = Curve.computeStraightLineCurve(handoffPos, handoffPos,
- startTime, 1);
- return curve.lerpIn(curve2, isThrow ? 1 : -1);
-}
-
-/**
- * Compute the curve taken by a ball during the carry representing a 1 that is
- * both the catch of one 1 and the immediately-following throw of another 1.
- *
- * @param {!EquationCoefficients} leadingHandoffPos
- * @param {!EquationCoefficients} trailingHandoffPos
- * @param {!Array.HandPositionRecord} handPositions where the hands will be.
- * @param {!number} hand
- * @param {!number} time the time at which the first 1's catch takes place.
- * @return {!Curve}
- */
-Curve.computeConsecutiveCarryOneCurve = function(leadingHandoffPos,
- trailingHandoffPos, handPositions, hand, time) {
- var curve = Curve.computeStraightLineCurve(leadingHandoffPos,
- handPositions[hand].basePosition, time, 1);
- var curve2 =
- Curve.computeStraightLineCurve(handPositions[hand].basePosition,
- trailingHandoffPos, time, 1);
- return curve.lerpIn(curve2, 1);
-}
-
-/**
- * Generate the Curve implied by this descriptor and the supplied hand
- * positions.
- * @param {!Array.HandPositionRecord} handPositions where the hands will be.
- * @return {!Curve} the curve.
- */
-CarryOneDescriptor.prototype.generateCurve = function(handPositions) {
- var leadingHandoffPos, trailingHandoffPos;
- if (this.isCatch) {
- var p0 = handPositions[this.hand].basePosition;
- var p1 = handPositions[this.sourceHand].basePosition;
- handoffPos = leadingHandoffPos = p0.add(p1).scale(0.5);
- }
- if (this.isThrow) {
- var p0 = handPositions[this.hand].basePosition;
- var p1 = handPositions[this.destHand].basePosition;
- handoffPos = trailingHandoffPos = p0.add(p1).scale(0.5);
- }
- if (!this.isCatch || !this.isThrow) {
- return Curve.computeCarryOneCurve(handPositions[this.hand].catchPosition,
- handPositions[this.hand].throwPositions[this.destHand], handoffPos,
- this.time, this.isCatch, this.isThrow);
- } else {
- return Curve.computeConsecutiveCarryOneCurve(leadingHandoffPos,
- trailingHandoffPos, handPositions, this.hand, this.time);
- }
-};
-
-/**
- * Create an otherwise-identical copy of this descriptor at a given time offset.
- * Note that offset may put time past patternLength; the caller will have to fix
- * this up manually.
- * @param {number} offset how many beats to offset the new descriptor.
- * @return {!Descriptor} the new copy.
- */
-CarryOneDescriptor.prototype.clone = function(offset) {
- offset = offset || 0; // Turn null into 0.
- return new CarryOneDescriptor(this.sourceThrowNum, this.sourceHand,
- this.destThrowNum, this.destHand, this.hand, this.time + offset,
- this.isThrow, this.isCatch);
-};
-
-/**
- * Test if this CarryOneDescriptor is equivalent to another, mod patternLength.
- * @param {!CarryOneDescriptor} cd the other CarryOneDescriptor.
- * @param {!number} patternLength the length of the pattern.
- * @return {!bool}
- */
-CarryOneDescriptor.prototype.equalsWithMod = function(cd, patternLength) {
- if (!(cd instanceof CarryOneDescriptor)) {
- return false;
- }
- if (this.hand != cd.hand) {
- return false;
- }
- if (this.sourceThrowNum != cd.sourceThrowNum) {
- return false;
- }
- if (this.destThrowNum != cd.destThrowNum) {
- return false;
- }
- if (this.sourceHand != cd.sourceHand) {
- return false;
- }
- if (this.destHand != cd.destHand) {
- return false;
- }
- if (this.isCatch != cd.isCatch) {
- return false;
- }
- if (this.isThrow != cd.isThrow) {
- return false;
- }
- if (this.time % patternLength != cd.time % patternLength) {
- return false;
- }
- return true;
-};
-
-/**
- * This describes an empty hand in a site-swap pattern.
- * @param {!Descriptor} cd0 the CarryDescriptor or CarryOneDescriptor describing
- * this hand immediately before it was emptied.
- * @param {!Descriptor} cd1 the CarryDescriptor or CarryOneDescriptor describing
- * this hand immediately after it's done being empty.
- * @param {!number} patternLength the length of the pattern.
- * @constructor
- */
-EmptyHandDescriptor = function(cd0, cd1, patternLength) {
- assert(cd0.hand == cd1.hand);
- this.hand = cd0.hand;
- this.prevThrowDest = cd0.destHand;
- this.sourceThrowNum = cd0.destThrowNum;
- this.nextCatchSource = cd1.sourceHand;
- this.destThrowNum = cd1.sourceThrowNum;
- // This code assumes that each CarryDescriptor and CarryOneDescriptor always
- // has a duration of 1 beat. If we want to be able to allow long-held balls
- // [instead of thrown twos, for example], we'll have to fix that here and a
- // number of other places.
- this.time = (cd0.time + 1) % patternLength;
- this.duration = cd1.time - this.time;
- if (this.duration < 0) {
- this.duration += patternLength;
- assert(this.duration > 0);
- }
-}
-
-/**
- * This is a subclass of Descriptor.
- */
-EmptyHandDescriptor.prototype = new Descriptor();
-
-/**
- * Set up the constructor, just to be neat.
- */
-EmptyHandDescriptor.prototype.constructor = EmptyHandDescriptor;
-
-/**
- * We label each Descriptor subclass with a type for debugging.
- */
-EmptyHandDescriptor.prototype.type = 'EMPTY';
-
-/**
- * Convert the EmptyHandDescriptor to a string for debugging.
- * @return {String} debugging output.
- */
-EmptyHandDescriptor.prototype.toString = function() {
- return 'time: ' + this.time + ' for ' + this.duration + ' (hand ' +
- this.hand + ', after throwing a ' + this.sourceThrowNum + ' to hand ' +
- this.prevThrowDest + ' then catches a ' + this.destThrowNum +
- ' from hand ' + this.nextCatchSource + ')';
-};
-
-/**
- * Generate the Curve implied by this descriptor and the supplied hand
- * positions.
- * @param {!Array.HandPositionRecord} handPositions where the hands will be.
- * @return {!Curve} the curve.
- */
-EmptyHandDescriptor.prototype.generateCurve = function(handPositions) {
- var startPos, endPos;
- if (this.sourceThrowNum == 1) {
- var p0 = handPositions[this.hand].basePosition;
- var p1 = handPositions[this.prevThrowDest].basePosition;
- startPos = p0.add(p1).scale(0.5);
- } else {
- startPos = handPositions[this.hand].throwPositions[this.prevThrowDest];
- }
- if (this.destThrowNum == 1) {
- var p0 = handPositions[this.hand].basePosition;
- var p1 = handPositions[this.nextCatchSource].basePosition;
- endPos = p0.add(p1).scale(0.5);
- } else {
- endPos = handPositions[this.hand].catchPosition;
- }
- // TODO: Replace with a good empty-hand curve.
- return Curve.computeStraightLineCurve(startPos, endPos, this.time,
- this.duration);
-};
-
-/**
- * A series of descriptors that describes the full path of an object during a
- * pattern.
- * @param {!Array.Descriptor} descriptors all descriptors for the object.
- * @param {!number} pathLength the length of the path in beats.
- * @constructor
- */
-Path = function(descriptors, pathLength) {
- this.descriptors = descriptors;
- this.pathLength = pathLength;
-}
-
-/**
- * Create a Path representing a ball, filling in the gaps between the throws
- * with carry descriptors. Since it's a ball's path, there are no
- * EmptyHandDescriptors in the output.
- * @param {!Array.ThrowDescriptor} throwDescriptors the ball's part of the
- * pattern.
- * @param {!number} pathLength the length of the pattern in beats.
- * @return {!Path} the ball's full path.
- */
-Path.ballPathFromThrowDescriptors = function(throwDescriptors, pathLength) {
- return new Path(
- Path.createDescriptorList(throwDescriptors, pathLength), pathLength);
-};
-
-/**
- * Create the sequence of ThrowDescriptors, CarryDescriptors, and
- * CarryOneDescriptor describing the path of a ball through a pattern.
- * A sequence such as (h j k) generally maps to an alternating series of throw
- * and carry descriptors [Th Chj Tj Cjk Tk Ck? ...]. However, when j is a 1,
- * you remove the throw descriptor and modify the previous and subsequent carry
- * descriptors, since the throw descriptor has zero duration and the carry
- * descriptors need to take into account the handoff.
- * @param {!Array.ThrowDescriptor} throwDescriptors the ball's part of the
- * pattern.
- * @param {!number} pathLength the length of the pattern in beats.
- * @return {!Array.Descriptor} the full set of descriptors for the ball.
- */
-Path.createDescriptorList = function(throwDescriptors, pathLength) {
- var descriptors = [];
- var prevThrow;
- for (var index in throwDescriptors) {
- var td = throwDescriptors[index];
- if (prevThrow) {
- descriptors.push(
- CarryDescriptor.fromThrowDescriptors(prevThrow, td, pathLength));
- } // Else it's handled after the loop.
- descriptors.push(td);
- prevThrow = td;
- }
- descriptors.push(
- CarryDescriptor.fromThrowDescriptors(prevThrow, throwDescriptors[0],
- pathLength));
- // Now post-process to take care of throws of 1. It's easier to do it here
- // than during construction since we can now assume that the previous and
- // subsequent carry descriptors are already in place [modulo pathLength].
- for (var i = 0; i < descriptors.length; ++i) {
- var descriptor = descriptors[i];
- if (descriptor instanceof ThrowDescriptor) {
- if (descriptor.throwNum == 1) {
- var prevIndex = (i + descriptors.length - 1) % descriptors.length;
- var postIndex = (i + 1) % descriptors.length;
- var replacements = CarryOneDescriptor.getDescriptorPair(
- descriptors[prevIndex], descriptors[postIndex]);
- descriptors[prevIndex] = replacements[0];
- descriptors[postIndex] = replacements[1];
- descriptors.splice(i, 1);
- // We've removed a descriptor from the array, but since we can never
- // have 2 ThrowDescriptors in a row, we don't need to decrement i.
- }
- }
- }
- return descriptors;
-};
-
-/**
- * Convert the Path to a string for debugging.
- * @return {String} debugging output.
- */
-Path.prototype.toString = function() {
- var ret = 'pathLength is ' + this.pathLength + '; [';
- for (var index in this.descriptors) {
- ret += this.descriptors[index].toString();
- }
- ret += ']';
- return ret;
-};
-
-/**
- * Create an otherwise-identical copy of this path at a given time offset.
- * Note that offset may put time references in the Path past the length of the
- * pattern. The caller must fix this up manually.
- * @param {number} offset how many beats to offset the new Path.
- * @return {!Path} the new copy.
- */
-Path.prototype.clone = function(offset) {
- offset = offset || 0; // Turn null into 0.
- var descriptors = [];
- for (var index in this.descriptors) {
- descriptors.push(this.descriptors[index].clone(offset));
- }
- return new Path(descriptors, this.pathLength);
-};
-
-/**
- * Adjust the start time of all descriptors to be in [0, pathLength) via modular
- * arithmetic. Reorder the array such that they're sorted in increasing order
- * of time.
- * @return {!Path} this.
- */
-Path.prototype.fixUpModPathLength = function() {
- var splitIndex;
- var prevTime = 0;
- for (var index in this.descriptors) {
- var d = this.descriptors[index];
- d.fixUpModPathLength(this.pathLength);
- if (d.time < prevTime) {
- assert(null == splitIndex);
- splitIndex = index; // From here to the end should move to the start.
- }
- prevTime = d.time;
- }
- if (null != splitIndex) {
- var temp = this.descriptors.slice(splitIndex);
- this.descriptors.length = splitIndex;
- this.descriptors = temp.concat(this.descriptors);
- }
- return this;
-};
-
-/**
- * Take a standard asynch siteswap pattern [expressed as an array of ints] and
- * a number of hands, and expand it into a 2D grid of ThrowDescriptors with one
- * row per hand.
- * Non-asynch patterns are more complicated, since their linear forms aren't
- * fully-specified, so we don't handle them here.
- * You'll want to expand your pattern to the LCM of numHands and minimal pattern
- * length before calling this.
- * The basic approach doesn't really work for one-handed patterns. It ends up
- * with catches and throws happening at the same time [having removed all
- * empty-hand time in between them]. To fix this, we double all throw heights
- * and space them out, as if doing a two-handed pattern with all zeroes from the
- * other hand. Yes, this points out that the overall approach we're taking is a
- * bit odd [since you end up with hands empty for time proportional to the
- * number of hands], but you have to make some sort of assumptions to generalize
- * siteswaps to N hands, and that's what I chose.
- * @param {!Array.number} pattern an asynch siteswap pattern.
- * @param {!number} numHands the number of hands.
- * @return {!Array.Array.ThrowDescriptor} the expanded pattern.
- */
-function expandPattern(pattern, numHands) {
- var fullPattern = [];
- assert(numHands > 0);
- if (numHands == 1) {
- numHands = 2;
- var temp = [];
- for (var i = 0; i < pattern.length; ++i) {
- temp[2 * i] = 2 * pattern[i];
- temp[2 * i + 1] = 0;
- }
- pattern = temp;
- }
- for (var hand = 0; hand < numHands; ++hand) {
- fullPattern[hand] = [];
- }
- for (var time = 0; time < pattern.length; ++time) {
- for (var hand = 0; hand < numHands; ++hand) {
- var t;
- if (hand == time % numHands) {
- t = new ThrowDescriptor(pattern[time], time, hand,
- (hand + pattern[time]) % numHands);
- } else {
- // These are ignored during analysis, so they don't appear in BallPaths.
- t = new ThrowDescriptor(0, time, hand, hand);
- }
- fullPattern[hand].push(t);
- }
- }
- return fullPattern;
-}
-
-// TODO: Wrap the final pattern in a class, then make the remaining few global
-// functions be members of that class to clean up the global namespace.
-
-/**
- * Given a valid site-swap for a nonzero number of balls, stored as an expanded
- * pattern array-of-arrays, with pattern length the LCM of hands and minimal
- * pattern length, produce Paths for all the balls.
- * @param {!Array.Array.ThrowDescriptor} pattern a valid pattern.
- * @return {!Array.Path} the paths of all the balls.
- */
-function generateBallPaths(pattern) {
- var numHands = pattern.length;
- assert(numHands > 0);
- var patternLength = pattern[0].length;
- assert(patternLength > 0);
- var sum = 0;
- for (var hand in pattern) {
- for (var time in pattern[hand]) {
- sum += pattern[hand][time].throwNum;
- }
- }
- var numBalls = sum / patternLength;
- assert(numBalls == Math.round(numBalls));
- assert(numBalls > 0);
-
- var ballsToAllocate = numBalls;
- var ballPaths = [];
- // NOTE: The indices of locationsChecked are reversed from those of pattern
- // for simplicity of allocation. This might be worth flipping to match.
- var locationsChecked = [];
- for (var time = 0; time < patternLength && ballsToAllocate; ++time) {
- locationsChecked[time] = locationsChecked[time] || [];
- for (var hand = 0; hand < numHands && ballsToAllocate; ++hand) {
- if (locationsChecked[time][hand]) {
- continue;
- }
- var curThrowDesc = pattern[hand][time];
- var curThrow = curThrowDesc.throwNum;
- if (!curThrow) {
- assert(curThrow === 0);
- continue;
- }
- var throwDescriptors = [];
- var curTime = time;
- var curHand = hand;
- var wraps = 0;
- do {
- if (!locationsChecked[curTime]) {
- locationsChecked[curTime] = [];
- }
- assert(!locationsChecked[curTime][curHand]);
- locationsChecked[curTime][curHand] = true;
- // We copy curThrowDesc here, adding wraps * patternLength, to get
- // the true throw time relative to offset. Later we'll add in offset
- // when we clone again, then mod by pathLength.
- throwDescriptors.push(curThrowDesc.clone(wraps * patternLength));
- var nextThrowTime = curThrow + curTime;
- wraps += Math.floor(nextThrowTime / patternLength);
- curTime = nextThrowTime % patternLength;
- assert(curTime >= time); // Else we'd have covered it earlier.
- curHand = curThrowDesc.destHand;
- var tempThrowDesc = curThrowDesc;
- curThrowDesc = pattern[curHand][curTime];
- curThrow = curThrowDesc.throwNum;
- assert(tempThrowDesc.destHand == curThrowDesc.sourceHand);
- assert(curThrowDesc.time ==
- (tempThrowDesc.throwNum + tempThrowDesc.time) % patternLength);
- } while (curTime != time || curHand != hand);
- var pathLength = wraps * patternLength;
- var ballPath =
- Path.ballPathFromThrowDescriptors(throwDescriptors, pathLength);
- for (var i = 0; i < wraps; ++i) {
- var offset = i * patternLength % pathLength;
- ballPaths.push(ballPath.clone(offset, pathLength).fixUpModPathLength());
- }
- ballsToAllocate -= wraps;
- assert(ballsToAllocate >= 0);
- }
- }
- return ballPaths;
-}
-
-/**
- * Given an array of ball paths, produce the corresponding set of hand paths.
- * @param {!Array.Path} ballPaths the Paths of all the balls in the pattern.
- * @param {!number} numHands how many hands to use in the pattern.
- * @param {!number} patternLength the length, in beats, of the pattern.
- * @return {!Array.Path} the paths of all the hands.
- */
-function generateHandPaths(ballPaths, numHands, patternLength) {
- assert(numHands > 0);
- assert(patternLength > 0);
- var handRecords = []; // One record per hand.
- for (var idxBR in ballPaths) {
- var descriptors = ballPaths[idxBR].descriptors;
- for (var idxD in descriptors) {
- var descriptor = descriptors[idxD];
- // TODO: Fix likely needed for throws of 1.
- if (!(descriptor instanceof ThrowDescriptor)) {
- // It's a CarryDescriptor or a CarryOneDescriptor.
- var hand = descriptor.hand;
- if (!handRecords[hand]) {
- handRecords[hand] = [];
- }
- // TODO: Should we not shorten stuff here if we're going to lengthen
- // everything later anyway? Is there a risk of inconsistency due to
- // ball paths of different lengths?
- var catchTime = descriptor.time % patternLength;
- if (!handRecords[hand][catchTime]) {
- // We pass in this offset to set the new descriptor's time to
- // catchTime, so as to keep it within [0, patternLength).
- handRecords[hand][catchTime] =
- descriptor.clone(catchTime - descriptor.time);
- } else {
- assert(
- handRecords[hand][catchTime].equalsWithMod(
- descriptor, patternLength));
- }
- }
- }
- }
- var handPaths = [];
- for (var hand in handRecords) {
- var outDescriptors = [];
- var inDescriptors = handRecords[hand];
- var prevDescriptor = null;
- var descriptor;
- for (var idxD in inDescriptors) {
- descriptor = inDescriptors[idxD];
- assert(descriptor); // Enumeration should skip array holes.
- assert(descriptor.hand == hand);
- if (prevDescriptor) {
- outDescriptors.push(new EmptyHandDescriptor(prevDescriptor, descriptor,
- patternLength));
- }
- outDescriptors.push(descriptor.clone());
- prevDescriptor = descriptor;
- }
- // Note that this EmptyHandDescriptor that wraps around the end lives at the
- // end of the array, not the beginning, despite the fact that it may be the
- // active one at time zero. This is the same behavior as with Paths for
- // balls.
- descriptor = new EmptyHandDescriptor(prevDescriptor, outDescriptors[0],
- patternLength);
- if (descriptor.time < outDescriptors[0].time) {
- assert(descriptor.time + descriptor.duration == outDescriptors[0].time);
- outDescriptors.unshift(descriptor);
- } else {
- assert(descriptor.time ==
- outDescriptors[outDescriptors.length - 1].time + 1);
- outDescriptors.push(descriptor);
- }
- handPaths[hand] =
- new Path(outDescriptors, patternLength).fixUpModPathLength();
- }
- return handPaths;
-}
-
-// NOTE: All this Vector stuff does lots of object allocations. If that's a
-// problem for your browser [e.g. IE6], you'd better stick with the embedded V8.
-// This code predates the creation of o3djs/math.js; I should probably switch it
-// over at some point, but for now it's not worth the trouble.
-
-/**
- * A simple 3-dimensional vector.
- * @constructor
- */
-Vector = function(x, y, z) {
- this.x = x;
- this.y = y;
- this.z = z;
-}
-
-Vector.prototype.sub = function(v) {
- return new Vector(this.x - v.x, this.y - v.y, this.z - v.z);
-};
-
-Vector.prototype.add = function(v) {
- return new Vector(this.x + v.x, this.y + v.y, this.z + v.z);
-};
-
-Vector.prototype.dot = function(v) {
- return this.x * v.x + this.y * v.y + this.z * v.z;
-};
-
-Vector.prototype.length = function() {
- return Math.sqrt(this.dot(this));
-};
-
-Vector.prototype.scale = function(s) {
- return new Vector(this.x * s, this.y * s, this.z * s);
-};
-
-Vector.prototype.set = function(v) {
- this.x = v.x;
- this.y = v.y;
- this.z = v.z;
-};
-
-Vector.prototype.normalize = function() {
- var length = this.length();
- assert(length);
- this.set(this.scale(1 / length));
- return this;
-};
-
-/**
- * Convert the Vector to a string for debugging.
- * @return {String} debugging output.
- */
-Vector.prototype.toString = function() {
- return '{' + this.x.toFixed(3) + ', ' + this.y.toFixed(3) + ', ' +
- this.z.toFixed(3) + '}';
-};
-
-/**
- * A container class that holds the positions relevant to a hand: where it is
- * when it's not doing anything, where it likes to catch balls, and where it
- * likes to throw balls to each of the other hands.
- * @param {!Vector} basePosition the centroid of throw and catch positions when
- * the hand throws to itself.
- * @param {!Vector} catchPosition where the hand likes to catch balls.
- * @constructor
- */
-HandPositionRecord = function(basePosition, catchPosition) {
- this.basePosition = basePosition;
- this.catchPosition = catchPosition;
- this.throwPositions = [];
-}
-
-/**
- * Convert the HandPositionRecord to a string for debugging.
- * @return {String} debugging output.
- */
-HandPositionRecord.prototype.toString = function() {
- var s = 'base: ' + this.basePosition.toString() + ';\n';
- s += 'catch: ' + this.catchPosition.toString() + ';\n';
- s += 'throws:\n';
- for (var i = 0; i < this.throwPositions.length; ++i) {
- s += '[' + i + '] ' + this.throwPositions[i].toString() + '\n';
- }
- return s;
-};
-
-/**
- * Compute all the hand positions used in a pattern given a number of hands and
- * a grouping style ["even" for evenly-spaced hands, "pairs" to group them in
- * pairs, as with 2-handed jugglers].
- * @param {!number} numHands the number of hands to use.
- * @param {!String} style the grouping style.
- * @return {!Array.HandPositionRecord} a full set of hand positions.
- */
-function computeHandPositions(numHands, style) {
- assert(numHands > 0);
- var majorRadiusScale = 0.75;
- var majorRadius = majorRadiusScale * (numHands - 1);
- var throwCatchOffset = 0.45;
- var catchRadius = majorRadius + throwCatchOffset;
- var handPositionRecords = [];
- for (var hand = 0; hand < numHands; ++hand) {
- var circleFraction;
- if (style == 'even') {
- circleFraction = hand / numHands;
- } else {
- assert(style == 'pairs');
- circleFraction = (hand + Math.floor(hand / 2)) / (1.5 * numHands);
- }
- var cos = Math.cos(Math.PI * 2 * circleFraction);
- var sin = Math.sin(Math.PI * 2 * circleFraction);
- var cX = catchRadius * cos;
- var cY = 0;
- var cZ = catchRadius * sin;
- var bX = majorRadius * cos;
- var bY = 0;
- var bZ = majorRadius * sin;
- handPositionRecords[hand] = new HandPositionRecord(
- new Vector(bX, bY, bZ), new Vector(cX, cY, cZ));
- }
- // Now that we've got all the hands' base and catch positions, we need to
- // compute the appropriate throw positions for each hand pair.
- for (var source = 0; source < numHands; ++source) {
- var throwHand = handPositionRecords[source];
- for (var target = 0; target < numHands; ++target) {
- var catchHand = handPositionRecords[target];
- if (throwHand == catchHand) {
- var baseV = throwHand.basePosition;
- throwHand.throwPositions[target] =
- baseV.add(baseV.sub(throwHand.catchPosition));
- } else {
- var directionV =
- catchHand.catchPosition.sub(throwHand.basePosition).normalize();
- var offsetV = directionV.scale(throwCatchOffset);
- throwHand.throwPositions[target] =
- throwHand.basePosition.add(offsetV);
- }
- }
- }
- return handPositionRecords;
-}
-
-/**
- * Convert an array of HandPositionRecord to a string for debugging.
- * @param {!Array.HandPositionRecord} positions the positions to display.
- * @return {String} debugging output.
- */
-function getStringFromHandPositions(positions) {
- var s = '';
- for (index in positions) {
- s += positions[index].toString();
- }
- return s;
-}
-
-/**
- * The set of curves an object passes through throughout a full animation cycle.
- * @param {!number} duration the length of the animation in beats.
- * @param {!Array.Curve} curves the full set of Curves.
- * @constructor
- */
-CurveSet = function(duration, curves) {
- this.duration = duration;
- this.curves = curves;
-}
-
-/**
- * Looks up what curve is active at a particular time. This is slower than
- * getCurveForTime, but can be used even if no Curve starts precisely at
- * unsafeTime % this.duration.
- * @param {!number} unsafeTime the time at which to check.
- * @return {!Curve} the curve active at unsafeTime.
- */
-CurveSet.prototype.getCurveForUnsafeTime = function(unsafeTime) {
- unsafeTime %= this.duration;
- time = Math.floor(unsafeTime);
- if (this.curves[time]) {
- return this.curves[time];
- }
- var curve;
- for (var i = time; i >= 0; --i) {
- curve = this.curves[i];
- if (curve) {
- assert(i + curve.duration >= unsafeTime);
- return curve;
- }
- }
- // We must want the last one. There's always a last one, given how we
- // construct the CurveSets; they're sparse, but the length gets set by adding
- // elements at the end.
- curve = this.curves[this.curves.length - 1];
- unsafeTime += this.duration;
- assert(curve.startTime <= unsafeTime);
- assert(curve.startTime + curve.duration > unsafeTime);
- return curve;
-};
-
-/**
- * Looks up what curve is active at a particular time. This is faster than
- * getCurveForUnsafeTime, but can only be used if if a Curve starts precisely at
- * unsafeTime % this.duration.
- * @param {!number} time the time at which to check.
- * @return {!Curve} the curve starting at time.
- */
-CurveSet.prototype.getCurveForTime = function(time) {
- return this.curves[time % this.duration];
-};
-
-/**
- * Convert the CurveSet to a string for debugging.
- * @return {String} debugging output.
- */
-CurveSet.prototype.toString = function() {
- var s = 'Duration: ' + this.duration + '\n';
- for (var c in this.curves) {
- s += this.curves[c].toString();
- }
- return s;
-};
-
-/**
- * Namespace object to hold the pure math functions.
- * TODO: Consider just rolling these into the Pattern object, when it gets
- * created.
- */
-var JugglingMath = {};
-
-/**
- * Computes the greatest common devisor of integers a and b.
- * @param {!number} a an integer.
- * @param {!number} b an integer.
- * @return {!number} the GCD of a and b.
- */
-JugglingMath.computeGCD = function(a, b) {
- assert(Math.round(a) == a);
- assert(Math.round(b) == b);
- assert(a >= 0);
- assert(b >= 0);
- if (!b) {
- return a;
- } else {
- return JugglingMath.computeGCD(b, a % b);
- }
-}
-
-/**
- * Computes the least common multiple of integers a and b, by making use of the
- * fact that LCM(a, b) * GCD(a, b) == a * b.
- * @param {!number} a an integer.
- * @param {!number} b an integer.
- * @return {!number} the LCM of a and b.
- */
-JugglingMath.computeLCM = function(a, b) {
- assert(Math.round(a) == a);
- assert(Math.round(b) == b);
- assert(a >= 0);
- assert(b >= 0);
- var ret = a * b / JugglingMath.computeGCD(a, b);
- assert(Math.round(ret) == ret);
- return ret;
-}
-
-/**
- * Given a Path and a set of hand positions, compute the corresponding set of
- * Curves.
- * @param {!Path} path the path of an object.
- * @param {!Array.HandPositionRecord} handPositions the positions of the hands
- * juggling the pattern containing the path.
- * @return {!CurveSet} the full set of curves.
- */
-CurveSet.getCurveSetFromPath = function(path, handPositions) {
- var curves = [];
- var pathLength = path.pathLength;
- for (var index in path.descriptors) {
- var descriptor = path.descriptors[index];
- var curve = descriptor.generateCurve(handPositions);
- assert(!curves[curve.startTime]);
- assert(curve.startTime < pathLength);
- curves[curve.startTime] = curve;
- }
- return new CurveSet(pathLength, curves);
-}
-
-/**
- * Given a set of Paths and a set of hand positions, compute the corresponding
- * CurveSets.
- * @param {!Array.Path} paths the paths of a number of objects.
- * @param {!Array.HandPositionRecord} handPositions the positions of the hands
- * juggling the pattern containing the paths.
- * @return {!Array.CurveSet} the CurveSets.
- */
-CurveSet.getCurveSetsFromPaths = function(paths, handPositions) {
- var curveSets = [];
- for (var index in paths) {
- var path = paths[index];
- curveSets[index] = CurveSet.getCurveSetFromPath(path, handPositions);
- }
- return curveSets;
-}
-
-/**
- * This is a temporary top-level calculation function that converts a standard
- * asynchronous siteswap, expressed as a string of digits, into a full
- * ready-to-animate set of CurveSets. Later on we'll be using an interface that
- * can create a richer set of patterns than those expressable in the traditional
- * string-of-ints format.
- * @param {!String} patternString the siteswap.
- * @param {!number} numHands the number of hands to use for the pattern.
- * @param {!String} style how to space the hands ["pairs" or "even"].
- * @return {!Object} a fully-analyzed pattern as CurveSets and associated data.
- */
-function computeFullPatternFromString(patternString, numHands, style) {
- var patternAsStrings = patternString.split(/[ ,]+ */);
- var patternSegment = [];
- for (var index in patternAsStrings) {
- if (patternAsStrings[index]) { // Beware extra whitespace at the ends.
- patternSegment.push(parseInt(patternAsStrings[index]));
- }
- }
- var pattern = [];
- // Now expand the pattern out to the length of the LCM of pattern length and
- // number of hands, so that each throw gets done in each of its incarnations.
- var multiple = JugglingMath.computeLCM(patternSegment.length, numHands) /
- patternSegment.length;
- for (var i = 0; i < multiple; ++i) {
- pattern = pattern.concat(patternSegment);
- }
-
- var fullPattern = expandPattern(pattern, numHands);
- var patternLength = fullPattern[0].length;
-
- var ballPaths = generateBallPaths(fullPattern);
- var handPaths = generateHandPaths(ballPaths, numHands, patternLength);
-
- var handPositions = computeHandPositions(numHands, style);
- var ballCurveSets = CurveSet.getCurveSetsFromPaths(ballPaths, handPositions);
- var handCurveSets = CurveSet.getCurveSetsFromPaths(handPaths, handPositions);
-
- // Find the LCM of all the curveSet durations. This will be the length of the
- // fully-expanded queue. We could expand to this before computing the
- // CurveSets, but this way's probably just a little cheaper.
- var lcmDuration = 1;
- for (var i in ballCurveSets) {
- var duration = ballCurveSets[i].duration;
- if (duration > lcmDuration || lcmDuration % duration) {
- lcmDuration = JugglingMath.computeLCM(lcmDuration, duration);
- }
- }
- for (var i in handCurveSets) {
- var duration = handCurveSets[i].duration;
- if (duration > lcmDuration || lcmDuration % duration) {
- lcmDuration = JugglingMath.computeLCM(lcmDuration, duration);
- }
- }
- return {
- numBalls: ballPaths.length,
- numHands: handPaths.length,
- duration: lcmDuration,
- handCurveSets: handCurveSets,
- ballCurveSets: ballCurveSets
- }
-}
diff --git a/o3d/samples/siteswap/siteswap.html b/o3d/samples/siteswap/siteswap.html
deleted file mode 100644
index 06656eb..0000000
--- a/o3d/samples/siteswap/siteswap.html
+++ /dev/null
@@ -1,323 +0,0 @@
-<!-- @@REWRITE(insert html-copyright) -->
-<!--
-O3D Siteswap animator
-@@REWRITE(delete-start)
-Author: Eric Uhrhane (ericu@google.com)
-@@REWRITE(delete-end)
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
- Site Swap Simulator
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- }
-</style>
-<!-- Our javascript code -->
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" src="siteswap.js"></script>
-<script type="text/javascript" src="math.js"></script>
-<script type="text/javascript" src="animation.js"></script>
-<script type="text/javascript" id="o3dscript">
-
-o3djs.require('o3djs.util');
-
-// Set up the client area.
-function init() {
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
- o3djs.util.addScriptUri(''); // Allow V8 to load scripts in the cwd.
- o3djs.util.makeClients(initStep2);
- setUpSelection();
-}
-
-// Select the entire input pattern, so that the user can just type.
-function setUpSelection() {
- var input_pattern = document.getElementById('input_pattern');
- input_pattern.focus();
- input_pattern.selectionStart = 0;
- input_pattern.selectionEnd = input_pattern.value.length;
-}
-
-/*
- * Wrappers to enable button presses to call through to the embedded V8 engine.
- */
-
-// Update whether we're animating or frozen based on the value of the checkbox.
-function updateAnimatingWrapper() {
- g.o3dElement.eval('updateAnimating()');
-}
-
-// Compute a new pattern.
-function onComputePatternWrapper() {
- g.o3dElement.eval('onComputePattern()');
-}
-
-// Adjust the view matrix to the new proportions of the plugin window.
-// TODO: Switch to using the resize event once that's checked in.
-function onResizeWrapper() {
- g.o3dElement.eval('onResize()');
-}
-window.onresize = onResizeWrapper;
-
-// Clean up all our callbacks, etc.
-function cleanupWrapper() {
- if (g && g.o3dElement) {
- g.o3dElement.eval('cleanup()');
- }
-}
-
-// The point of this function is to suppress form submit; we want to use the
-// pattern entered when the user hits return, not submit the page to the
-// webserver.
-function suppressSubmit(event) {
- onComputePatternWrapper(); // TODO: This suppresses form autocomplete storage.
- return false;
-}
-
-</script>
-</head>
-<body onload="init()" onunload="cleanupWrapper()">
-<table width="100%" style="height:100%;">
- <tr>
- <td>
- <h1>Juggler</h1>
- This sample displays a site-swap juggling pattern with animation done by
- a vertex shader.
- <form name="the_form" onsubmit="return suppressSubmit(event)">
- <table>
- <tr>
- <td>
- <table>
- <tr>
- <td>
- <input
- type="radio"
- name="radio_group_hands"
- value="1"
- onclick=onComputePatternWrapper()>
- 1 Hand<br>
- <input
- type="radio"
- name="radio_group_hands"
- value="2"
- onclick=onComputePatternWrapper()
- checked>
- 2 Hands<br>
- <input
- type="radio"
- name="radio_group_hands"
- value="3"
- onclick=onComputePatternWrapper()>
- 3 Hands<br>
- <input
- type="radio"
- name="radio_group_hands"
- value="4"
- onclick=onComputePatternWrapper()>
- 4 Hands<br>
- </td>
- <td>
- <input type="text" name="input_pattern" id="input_pattern"
- value="3 4 5">
- </td>
- <td>
- <input type="checkbox" name="check_box" checked
- onclick=updateAnimatingWrapper()>Animate
- <input
- type="checkbox"
- name="pair_hands"
- onclick=onComputePatternWrapper();
- >Pair Hands
- </td>
- <td>
- <input type="button" name="computePattern"
- value="Compute Pattern"
- onclick=onComputePatternWrapper()>
- </td>
- </tr>
- </table>
- </td>
- <td>
- </td>
- </tr>
- </table>
- </form>
- <table id="container" width="90%" style="height:70%;">
- <tr>
- <td height="100%">
- <!-- Start of g.o3d plugin -->
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- <!-- End of g.o3d plugin -->
- </td>
- </tr>
- </table>
- <!-- a simple way to get a multiline string -->
- <textarea id="shader" name="shader" cols="80" rows="20"
- style="display: none;">
-// the 4x4 world view projection matrix
-float4x4 worldViewProjection : WorldViewProjection;
-
-// positions of the light and camera
-float3 light_pos;
-float3 camera_pos;
-
-// phong lighting properties of the material
-float4 light_ambient;
-float4 light_diffuse;
-float4 light_specular;
-
-// shininess of the material (for specular lighting)
-float shininess;
-
-// time for animation
-float time;
-
-// coefficients for a t^2 + b t + c for each of x, y, z
-float3 coeff_a;
-float3 coeff_b;
-float3 coeff_c;
-
-// flag and coefficient for optional LERP with rate t * coeff_lerp;
-float coeff_lerp;
-
-// coefficients for a t^2 + b t + c for each of x, y, z, for optional LERP
-float3 coeff_l_a;
-float3 coeff_l_b;
-float3 coeff_l_c;
-
-// coefficients for d sin(f t) + e cos(e t) for each of x, y, z
-float3 coeff_d;
-float3 coeff_e;
-float3 coeff_f;
-
-// to be subtracted from time to get the t for the above equation
-float time_base;
-
-// input parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float3 normal : NORMAL;
- float4 color : COLOR;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float3 lightVector : TEXCOORD0;
- float3 normal : TEXCOORD1;
- float3 viewPosition : TEXCOORD2;
- float4 color : COLOR;
-};
-
-/**
- * Vertex Shader - vertex shader for phong illumination
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- /**
- * We use the standard phong illumination equation here.
- * We restrict (clamp) the dot products so that we
- * don't get any negative values.
- * All vectors are normalized for proper calculations.
- *
- * The output color is the summation of the
- * ambient, diffuse, and specular contributions.
- *
- * Note that we have to transform each vertex and normal
- * by the world view projection matrix first.
- */
- PixelShaderInput output;
-
- float t = time - time_base;
- float3 offset = float3(0, 0, 0);
- offset += t * t * coeff_a + t * coeff_b + coeff_c;
- offset += coeff_d * sin(t * coeff_f);
- offset += coeff_e * cos(t * coeff_f);
-
- float3 lerpOffset = t * t * coeff_l_a + t * coeff_l_b + coeff_l_c;
- if (coeff_lerp > 0) {
- float rate = min(coeff_lerp * t, 1);
- float3 lerpVector = float3(rate, rate, rate);
- offset = lerp(offset, lerpOffset, lerpVector);
- } else if (coeff_lerp < 0) {
- float rate = min(-coeff_lerp * t, 1);
- float3 lerpVector = float3(rate, rate, rate);
- offset = lerp(lerpOffset, offset, lerpVector);
- }
-
- input.position = input.position + float4(offset.xyz, 0);
-
- output.position = mul(input.position, worldViewProjection);
-
- /**
- * lightVector - light vector
- * normal - normal vector
- * viewPosition - view vector (from camera)
- */
-
- // NOTE: In this case we do not need to multiply by any matrices since the
- // WORLD transformation matrix is the identity. If you were moving the
- // object such that the WORLD transform matrix was not the identity, you
- // would need to multiply the normal by the WORLDINVERSETTRANSFORM matrix
- // since the normal is in object space. Other values (light_pos, camera_pos)
- // are already in world space.
- float3 lightVector = light_pos - input.position.xyz;
- float3 normal = input.normal;
- float3 viewPosition = camera_pos - input.position.xyz;
-
- output.lightVector = lightVector;
- output.normal = normal;
- output.viewPosition = viewPosition;
- output.color = input.color;
- return output;
-}
-
-/**
- * Pixel Shader
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- float3 lightVector = normalize(input.lightVector);
- float3 normal = normalize(input.normal);
- float3 viewPosition = normalize(input.viewPosition);
- float3 halfVector = normalize(lightVector + viewPosition);
-
- // use lit function to calculate phong shading
- // x component contains the ambient coefficient
- // y component contains the diffuse coefficient:
- // max(dot(normal, lightVector),0)
- // z component contains the specular coefficient:
- // dot(normal, lightVector) < 0 || dot(normal, halfVector) < 0 ?
- // 0 : pow(dot(normal, halfVector), shininess)
- // NOTE: This is actually Blinn-Phong shading, not Phong shading
- // which would use the reflection vector instead of the half vector
-
- float4 phong_coeff = lit(dot(normal, lightVector),
- dot(normal, halfVector), shininess);
-
- float4 ambient = light_ambient * phong_coeff.x * input.color;
- float4 diffuse = light_diffuse * phong_coeff.y * input.color;
- float4 specular = light_specular * phong_coeff.z * input.color;
-
- return ambient + diffuse + specular;
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
- </textarea>
- </td>
- </tr>
-</table>
-</body>
-</html>
diff --git a/o3d/samples/siteswap/siteswap.js b/o3d/samples/siteswap/siteswap.js
deleted file mode 100644
index 6b77aff..0000000
--- a/o3d/samples/siteswap/siteswap.js
+++ /dev/null
@@ -1,415 +0,0 @@
-// @@REWRITE(insert js-copyright)
-// @@REWRITE(delete-start)
-// Copyright 2009 Google Inc. All Rights Reserved
-// @@REWRITE(delete-end)
-
-/**
- * This file contains the top-level logic and o3d-related code for the siteswap
- * animator.
- */
-
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.dump');
-
-// Global variables are all referenced via g, so that either interpreter can
-// find them easily.
-var g = {};
-
-/**
- * Creates a color based on an input index as a seed.
- * @param {!number} index the seed value to select the color.
- * @return {!Array.number} an [r g b a] color.
- */
-function createColor(index) {
- var N = 12; // Number of distinct colors.
- var root3 = Math.sqrt(3);
- var theta = 2 * Math.PI * index / N;
- var sin = Math.sin(theta);
- var cos = Math.cos(theta);
- return [(1 / 3 + 2 / 3 * cos) + (1 / 3 - cos / 3 - sin / root3),
- (1 / 3 - cos / 3 + sin / root3) + (1 / 3 + 2 / 3 * cos),
- (1 / 3 - cos / 3 - sin / root3) + (1 / 3 - cos / 3 + sin / root3),
- 1];
-}
-
-/**
- * Creates a material, given the index as a seed to make it distinguishable.
- * @param {number} index an integer used to create a distinctive color.
- * @return {!o3d.Material} the material.
- */
-function createMaterial(index) {
- var material = g.pack.createObject('Material');
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shader to use.
- material.effect = g.effect;
-
- // Set the material's drawList
- material.drawList = g.viewInfo.performanceDrawList;
-
- // This will create our quadColor parameter on the material.
- g.effect.createUniformParameters(material);
-
- // Set up the individual parameters in our effect file.
-
- // Light position
- var light_pos_param = material.getParam('light_pos');
- light_pos_param.value = [10, 10, 20];
-
- // Phong components of the light source
- var light_ambient_param = material.getParam('light_ambient');
- var light_diffuse_param = material.getParam('light_diffuse');
- var light_specular_param = material.getParam('light_specular');
-
- // White ambient light
- light_ambient_param.value = [0.04, 0.04, 0.04, 1];
-
- light_diffuse_param.value = createColor(index);
- // White specular light
- light_specular_param.value = [0.5, 0.5, 0.5, 1];
-
- // Shininess of the material (for specular lighting)
- var shininess_param = material.getParam('shininess');
- shininess_param.value = 30.0;
-
- // Bind the counter's count to the input of the FunctionEval.
- var paramTime = material.getParam('time');
- paramTime.bind(g.counter.getParam('count'));
-
- material.getParam('camera_pos').value = g.eye;
-
- return material;
-}
-
-/**
- * Gets a material from our cache, creating it if it's not yet been made.
- * Uses index as a seed to make the material distinguishable.
- * @param {number} index an integer used to create/fetch a distinctive color.
- * @return {!o3d.Material} the material.
- */
-function getMaterial(index) {
- g.materials = g.materials || []; // See initStep2 for a comment.
- if (!g.materials[index]) {
- g.materials[index] = createMaterial(index);
- }
- return g.materials[index];
-}
-
-/**
- * Initializes g.o3d.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- window.g = g;
-
- // Used to tell whether we need to recompute our view on resize.
- g.o3dWidth = -1;
- g.o3dHeight = -1;
-
- // We create a different material for each color of object.
- //g.materials = []; // TODO(ericu): If this is executed, we fail. Why?
-
- // We hold on to all the shapes here so that we can clean them up when we want
- // to change patterns.
- g.ballShapes = [];
- g.handShapes = [];
-
- g.o3dElement = clientElements[0];
- g.o3d = g.o3dElement.o3d;
- g.math = o3djs.math;
- g.client = g.o3dElement.client;
-
- // Initialize client sample libraries.
- o3djs.base.init(g.o3dElement);
-
- // Create a g.pack to manage our resources/assets
- g.pack = g.client.createPack();
-
- // Create the render graph for a view.
- g.viewInfo = o3djs.rendergraph.createBasicView(
- g.pack,
- g.client.root,
- g.client.renderGraphRoot);
-
- // Get the default context to hold view/projection matrices.
- g.context = g.viewInfo.drawContext;
-
- // Load a simple effect from a textarea.
- g.effect = g.pack.createObject('Effect');
- g.effect.loadFromFXString(document.getElementById('shader').value);
-
- // Eye-position: this is where our camera is located.
- // Global because each material we create must also know where it is, so that
- // the shader works properly.
- g.eye = [1, 6, 10];
-
- // Target, this is the point at which our camera is pointed.
- var target = [0, 2, 0];
-
- // Up-vector, this tells the camera which direction is 'up'.
- // We define the positive y-direction to be up in this example.
- var up = [0, 1, 0];
-
- g.context.view = g.math.matrix4.lookAt(g.eye, target, up);
-
- // Make a SecondCounter to provide the time for our animation.
- g.counter = g.pack.createObject('SecondCounter');
- g.counter.multiplier = 3; // Speed up time; this is in throws per second.
-
- // Generate the projection and viewProjection matrices based
- // on the g.o3d plugin size by calling onResize().
- onResize();
-
- // If we don't check the size of the client area every frame we don't get a
- // chance to adjust the perspective matrix fast enough to keep up with the
- // browser resizing us.
- // TODO(ericu): Switch to using the resize event once it's checked in.
- g.client.setRenderCallback(onResize);
-}
-
-/**
- * Stops or starts the animation based on the state of an html checkbox.
- */
-function updateAnimating() {
- var box = document.the_form.check_box;
- g.counter.running = box.checked;
-}
-
-/**
- * Generates the projection matrix based on the size of the g.o3d plugin
- * and calculates the view-projection matrix.
- */
-function onResize() {
- var newWidth = g.client.width;
- var newHeight = g.client.height;
-
- if (newWidth != g.o3dWidth || newHeight != g.o3dHeight) {
- debug('resizing');
- g.o3dWidth = newWidth;
- g.o3dHeight = newHeight;
-
- // Create our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 100.
- g.context.projection = g.math.matrix4.perspective(
- 45 * Math.PI / 180,
- g.o3dWidth / g.o3dHeight,
- 0.1,
- 100);
- }
-}
-
-/**
- * Computes and prepares animation of the pattern input via the html form. If
- * the box is checked, this will immediately begin animation as well.
- */
-function onComputePattern() {
- try {
- g.counter.removeAllCallbacks();
- var group = document.the_form.radio_group_hands;
- var numHands = -1;
- for (var i = 0; i < group.length; ++i) {
- if (group[i].checked) {
- numHands = parseInt(group[i].value);
- }
- }
- var style = 'even';
- if (document.the_form.pair_hands.checked) {
- style = 'pairs';
- }
- var patternString = document.getElementById('input_pattern').value;
- var patternData =
- computeFullPatternFromString(patternString, numHands, style);
- startAnimation(
- patternData.numBalls,
- patternData.numHands,
- patternData.duration,
- patternData.ballCurveSets,
- patternData.handCurveSets);
- } catch (ex) {
- popup(stringifyObj(ex));
- throw ex;
- }
- setUpSelection();
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function cleanup() {
- g.client.cleanup();
-}
-
-
-/**
- * Dump out a newline-terminated string to the debug console, if available.
- * @param {!string} s the string to output.
- */
-function debug(s) {
- o3djs.dump.dump(s + '\n');
-}
-
-/**
- * Dump out a newline-terminated string to the debug console, if available,
- * then display it via an alert.
- * @param {!string} s the string to output.
- */
-function popup(s) {
- debug(s);
- window.alert(s);
-}
-
-/**
- * If t, throw an exception.
- * @param {!bool} t the value to test.
- */
-function assert(t) {
- if (!t) {
- throw new Error('Assertion failed!');
- }
-}
-
-/**
- * Convert an object to a string containing a full one-level-deep property
- * listing, with values.
- * @param {!Object} o the object to convert.
- * @return {!string} the converted object.
- */
-function stringifyObj(o) {
- var s = '';
- for (var i in o) {
- s += i + ':' + o[i] + '\n';
- }
- return s;
-}
-
-/**
- * Add the information in a curve to the params on a shape, such that the vertex
- * shader will move the shape along the curve at times after timeBase.
- * @param {!Curve} curve the curve the shape should follow.
- * @param {!o3d.Shape} shape the shape being moved.
- * @param {!number} timeBase the base to subtract from the current time when
- * giving the curve calculation its time input.
- */
-function setParamCurveInfo(curve, shape, timeBase) {
- assert(curve);
- assert(shape);
- try {
- shape.elements[0].getParam('time_base').value = timeBase;
- shape.elements[0].getParam('coeff_a').value =
- [curve.xEqn.a, curve.yEqn.a, curve.zEqn.a];
- shape.elements[0].getParam('coeff_b').value =
- [curve.xEqn.b, curve.yEqn.b, curve.zEqn.b];
- shape.elements[0].getParam('coeff_c').value =
- [curve.xEqn.c, curve.yEqn.c, curve.zEqn.c];
- shape.elements[0].getParam('coeff_d').value =
- [curve.xEqn.d, curve.yEqn.d, curve.zEqn.d];
- shape.elements[0].getParam('coeff_e').value =
- [curve.xEqn.e, curve.yEqn.e, curve.zEqn.e];
- shape.elements[0].getParam('coeff_f').value =
- [curve.xEqn.f, curve.yEqn.f, curve.zEqn.f];
-
- assert(curve.xEqn.lerpRate == curve.yEqn.lerpRate);
- assert(curve.xEqn.lerpRate == curve.zEqn.lerpRate);
- shape.elements[0].getParam('coeff_lerp').value = curve.xEqn.lerpRate;
- if (curve.xEqn.lerpRate) {
- shape.elements[0].getParam('coeff_l_a').value =
- [curve.xEqn.lA, curve.yEqn.lA, curve.zEqn.lA];
- shape.elements[0].getParam('coeff_l_b').value =
- [curve.xEqn.lB, curve.yEqn.lB, curve.zEqn.lB];
- shape.elements[0].getParam('coeff_l_c').value =
- [curve.xEqn.lC, curve.yEqn.lC, curve.zEqn.lC];
- }
- } catch (ex) {
- debug(ex);
- throw ex;
- }
-}
-
-/**
- * Create the params that the shader expects on the supplied shape's first
- * element.
- * @param {!o3d.Shape} shape the shape on whose first element to create params.
- */
-function createParams(shape) {
- shape.elements[0].createParam('coeff_a', 'ParamFloat3').value = [0, 0, 0];
- shape.elements[0].createParam('coeff_b', 'ParamFloat3').value = [0, 0, 0];
- shape.elements[0].createParam('coeff_c', 'ParamFloat3').value = [0, 0, 0];
- shape.elements[0].createParam('coeff_d', 'ParamFloat3').value = [0, 0, 0];
- shape.elements[0].createParam('coeff_e', 'ParamFloat3').value = [0, 0, 0];
- shape.elements[0].createParam('coeff_f', 'ParamFloat3').value = [0, 0, 0];
- shape.elements[0].createParam('coeff_l_a', 'ParamFloat3').value = [0, 0, 0];
- shape.elements[0].createParam('coeff_l_b', 'ParamFloat3').value = [0, 0, 0];
- shape.elements[0].createParam('coeff_l_c', 'ParamFloat3').value = [0, 0, 0];
- shape.elements[0].createParam('coeff_lerp', 'ParamFloat').value = 0;
- shape.elements[0].createParam('time_base', 'ParamFloat').value = 0;
-}
-
-/**
- * Adjust the number of ball shapes in g.pack.
- * @param {!number} numBalls the number of balls desired.
- */
-function setNumBalls(numBalls) {
- for (var i = 0; i < g.ballShapes.length; ++i) {
- g.pack.removeObject(g.ballShapes[i]);
- g.client.root.removeShape(g.ballShapes[i]);
- }
- g.ballShapes = [];
-
- for (var i = 0; i < numBalls; ++i) {
- var shape = o3djs.primitives.createSphere(g.pack,
- getMaterial(5 * i),
- 0.10,
- 70,
- 70);
- shape.name = 'Ball ' + i;
-
- // generate the draw elements.
- shape.createDrawElements(g.pack, null);
-
- // Now attach the sphere to the root of the scene graph.
- g.client.root.addShape(shape);
-
- // Create the material params for the shader.
- createParams(shape);
-
- g.ballShapes[i] = shape;
- }
-}
-
-/**
- * Adjust the number of hand shapes in g.pack.
- * @param {!number} numHands the number of hands desired.
- */
-function setNumHands(numHands) {
- g.counter.removeAllCallbacks();
-
- for (var i = 0; i < g.handShapes.length; ++i) {
- g.pack.removeObject(g.handShapes[i]);
- g.client.root.removeShape(g.handShapes[i]);
- }
- g.handShapes = [];
-
- for (var i = 0; i < numHands; ++i) {
- var shape = o3djs.primitives.createBox(g.pack,
- getMaterial(3 * (i + 1)),
- 0.25,
- 0.05,
- 0.25);
- shape.name = 'Hand ' + i;
-
- // generate the draw elements.
- shape.createDrawElements(g.pack, null);
-
- // Now attach the sphere to the root of the scene graph.
- g.client.root.addShape(shape);
-
- // Create the material params for the shader.
- createParams(shape);
-
- g.handShapes[i] = shape;
- }
-}
-
diff --git a/o3d/samples/skinning.html b/o3d/samples/skinning.html
deleted file mode 100644
index 64c7954..0000000
--- a/o3d/samples/skinning.html
+++ /dev/null
@@ -1,272 +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.
--->
-
-<!--
-O3D Skinning example.
-
-Shows a simple skinned cylinder.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Skinning.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.primitives');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// constants
-var NUM_BONES = 11;
-var BONE_SPACING = 20;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_transforms = [];
-var g_finished = false; // for selenium testing.
-var g_clock = 0;
-var g_timeMult = 1;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 10000);
-
- // Create a material.
- var material = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- [1, 0.2, 1, 1]);
-
- // Create a cylinder.
- var vertexInfo = o3djs.primitives.createCylinderVertices(
- 40, 200, 12, 20,
- [[1, 0, 0, 0],
- [0, 1, 0, 0],
- [0, 0, 1, 0],
- [0, 100, 0, 1]]);
- var shape = vertexInfo.createShape(g_pack, material);
-
- // Create an ParamArray to hold matrices for skinning.
- var matrices = g_pack.createObject('ParamArray');
-
- // Create a Skin to hold the influences and bind pose.
- var skin = g_pack.createObject('Skin');
-
- // Create a SkinEval to use the Skin.
- var skinEval = g_pack.createObject('SkinEval');
-
- // Tell the SkinEval which matrices and Skin to use.
- skinEval.matrices = matrices;
- skinEval.skin = skin;
-
- // Create matrices on our ParamArray.
- matrices.resize(NUM_BONES, 'o3d.ParamMatrix4');
-
- // Create 11 transforms for the bones and parent them into a chain.
- for (var ii = 0; ii < NUM_BONES; ++ii) {
- var transform = g_pack.createObject('Transform');
- g_transforms[ii] = transform;
- if (ii > 0) {
- transform.translate(0, BONE_SPACING, 0);
- }
- transform.parent = ii == 0 ? g_client.root : g_transforms[ii - 1];
- // Bind the world matrix of the transform to the corresponding matrix in the
- // ParamArray.
- matrices.getParam(ii).bind(transform.getParam('worldMatrix'));
- // Store the inverse world matrix of each transform as the bind pose for the
- // skin.
- skin.setInverseBindPoseMatrix(ii, g_math.inverse(transform.worldMatrix));
- }
-
- // Add the cylinder to the root transform.
- g_transforms[0].addShape(shape);
-
- // Skinning happens in world space so bind the transform of the shape
- // to the SkinEval so it can put our skin in object space.
- skinEval.getParam('base').bind(g_transforms[0].getParam('worldMatrix'));
-
- // Make our source data for skinning and setup the influences for each bone.
- // We only need the position and normals.
- var positions = [];
- var normals = [];
- var positionStream = vertexInfo.findStream(g_o3d.Stream.POSITION);
- var normalStream = vertexInfo.findStream(g_o3d.Stream.NORMAL);
- var numVertices = positionStream.numElements();
- for (var ii = 0; ii < numVertices; ++ii) {
- // Choose the bones to influence the vertex based on its height.
- // boneArea will be a fractional value between 2 bones based on the Y
- // position of the vertex. In other words, if the y Position of the vertex
- // 63 and the bones are 20 units apart then boneArea will = 6.15 meaning
- // it's between bones 6 and 7
- var boneArea = positionStream.getElementVector(ii)[1] / BONE_SPACING;
-
- // Pull out the fractional part of boneArea
- var influence = boneArea % 1;
-
- // Compute the bone indicies
- var bone1 = Math.floor(boneArea);
- var bone2 = bone1 + 1;
- if (bone2 >= NUM_BONES) {
- bone2 = NUM_BONES - 1;
- }
-
- // Now make each vertex be influenced by these two bones. In the example
- // above where boneArea was 6.15 we let bone1 influence the vertex by
- // (1 - 0.15) or 0.85 and bone2 influence it by 0.15.
- skin.setVertexInfluences(ii, [bone1, 1 - influence, bone2, influence]);
- }
-
- // Create a SourceBuffer for the Skin and set the vertices on it.
- var sourceBuffer = g_pack.createObject('SourceBuffer');
- var positionField = sourceBuffer.createField('FloatField', 3);
- var normalField = sourceBuffer.createField('FloatField', 3);
- sourceBuffer.allocateElements(numVertices);
- positionField.setAt(0, positionStream.elements);
- normalField.setAt(0, normalStream.elements);
-
- // Tell the skinEval how to use the SourceBuffer
- skinEval.setVertexStream(g_o3d.Stream.POSITION,
- 0,
- positionField,
- 0);
- skinEval.setVertexStream(g_o3d.Stream.NORMAL,
- 0,
- normalField,
- 0);
-
- // Bind the Primitive's position and normal streams
- // to the SkinEval so the SkinEval will fill them in each frame.
- var streamBank = shape.elements[0].streamBank;
- streamBank.bindStream(skinEval, g_o3d.Stream.POSITION, 0);
- streamBank.bindStream(skinEval, g_o3d.Stream.NORMAL, 0);
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-/**
- * Called every frame.
- * @param {!o3d.RenderEvent} renderEvent Info for rendering.
- */
-function onrender(renderEvent) {
- // Get the number of seconds since the last render.
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- var x = Math.sin(g_clock * 0.3) * 400;
- var z = Math.cos(g_clock * 0.3) * 400;
- var y = Math.sin(g_clock * 0.7) * 50 + 100;
-
- // spin the camera.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [x, y, z], // eye
- [0, 100, 0], // target
- [0, 1, 0]); // up
-
- // Make our bone chain bend.
- var rotation = Math.PI / g_transforms.length * Math.sin(g_clock * 1);
- for (var ii = 1; ii < g_transforms.length; ++ii) {
- var transform = g_transforms[ii];
- transform.identity();
- transform.translate(0, BONE_SPACING, 0);
- transform.rotateX(rotation);
- }
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Skinning</h1>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/sobel.html b/o3d/samples/sobel.html
deleted file mode 100644
index 9f5576b..0000000
--- a/o3d/samples/sobel.html
+++ /dev/null
@@ -1,342 +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 sample shows how to create a Sobel edge-detect image processing shader,
-using render targets.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-O3D: Sobel Shader Sample
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-window.onunload = uninit;
-
-// constants.
-var RENDER_TARGET_WIDTH = 512;
-var RENDER_TARGET_HEIGHT = 512;
-
-// global variables
-var g_o3d;
-var g_client;
-var g_math;
-var g_pack;
-var g_teapotRoot;
-var g_renderGraphRoot;
-var g_clock = 0;
-var g_timeMult = 1;
-var g_finished = false; // for selenium testing
-
-/**
- * Loads a scene into the transform graph, and prepares its elements for
- * insertion into the render graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- * @param {!o3djs.rendergraph.ViewInfo} viewInfo who's view and projection will
- * be set from the scene after it's loaded.
- */
-function loadScene(pack, fileName, parent, viewInfo) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the scene given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a CameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT);
-
- // Copy the view and projection to the passed in viewInfo structure..
- viewInfo.drawContext.view = cameraInfo.view;
- viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, viewInfo);
-
- g_finished = true; // for selenium testing.
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scene into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3d = clientElements[0];
- g_o3d = o3d.o3d;
- g_math = o3djs.math;
- g_client = o3d.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the texture required for the color render-target.
- var texture = g_pack.createTexture2D(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT,
- g_o3d.Texture.XRGB8, 1, true);
-
- g_teapotRoot = g_pack.createObject('Transform');
-
- var renderGraphRoot = g_client.renderGraphRoot;
-
- var renderSurfaceSet = createRenderSurfaceSet(texture);
-
- // Create the render graph for the teapot view, drawing the teapot into
- // texture (via renderSurfaceSet).
- var teapotViewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_teapotRoot,
- renderSurfaceSet,
- [1, 1, 1, 1]);
-
- var renderNode = createSobelPass(texture, g_client.renderGraphRoot);
-
- // Load the scene into the transform graph as a child g_teapotRoot
- loadScene(g_pack, 'assets/teapot.o3dtgz', g_teapotRoot, teapotViewInfo);
-
- // Set a render callback.
- g_client.setRenderCallback(onRender);
-}
-
-function createSobelMaterial(viewInfo, kernelSize) {
- var convFXString = document.getElementById('convFX').value;
- var convEffect = g_pack.createObject('Effect');
- convEffect.loadFromFXString(convFXString);
-
- var convMaterial = g_pack.createObject('Material');
- convMaterial.drawList = viewInfo.performanceDrawList;
- convMaterial.effect = convEffect;
- convEffect.createUniformParameters(convMaterial);
- return convMaterial;
-}
-
-function createRenderSurfaceSet(texture) {
- var renderSurface = texture.getRenderSurface(0);
-
- // Create the depth-stencil buffer required when rendering this pass.
- var depthSurface = g_pack.createDepthStencilSurface(RENDER_TARGET_WIDTH,
- RENDER_TARGET_HEIGHT);
-
- var renderSurfaceSet = g_pack.createObject('RenderSurfaceSet');
- renderSurfaceSet.renderSurface = renderSurface;
- renderSurfaceSet.renderDepthStencilSurface = depthSurface;
- renderSurfaceSet.parent = g_client.renderGraphRoot;
- return renderSurfaceSet;
-}
-
-function createSobelPass(srcTexture, renderGraphRoot) {
- // Create a root Transform for the image processing scene.
- var root = g_pack.createObject('Transform');
-
- // Create a basic view for the image processing scene.
- var viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- root,
- renderGraphRoot,
- [1, 1, 1, 1]);
-
- var material = createSobelMaterial(viewInfo);
- var quadShape = o3djs.primitives.createPlane(g_pack,
- material,
- 2.0,
- 2.0,
- 1,
- 1);
-
- // Attach the quad to the image processing scene.
- root.addShape(quadShape);
-
- // Rotate the view so we're looking at the XZ plane (where our quad is)
- // Point the camera along the -Y axis
- var target = [0, -1, 0];
- // Put the camera at the origin.
- var eye = [0, 0, 0];
- // Define the up-vector as +Z
- var up = [0, 0, 1];
- viewInfo.drawContext.view = g_math.matrix4.lookAt(eye, target, up);
-
- // Create an orthographic projection.
- viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -1, 1, -1, 1, -1, 1);
-
- // Generate draw elements and setup material draw lists for the
- // image processing scene.
- o3djs.pack.preparePack(g_pack, viewInfo);
-
- setSobelParameters(material, srcTexture);
- return renderGraphRoot;
-}
-
-function setSobelParameters(material, texture) {
- var imageParam = material.getParam('image');
- var imageIncrement = material.getParam('imageIncrement');
- var sampler = g_pack.createObject('Sampler');
- sampler.texture = texture;
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
- sampler.minFilter = g_o3d.Sampler.POINT;
- sampler.magFilter = g_o3d.Sampler.POINT;
- sampler.mipFilter = g_o3d.Sampler.NONE;
- imageParam.value = sampler;
- imageIncrement.value = [1.0 / texture.width, 1.0 / texture.height];
- var paramArray = g_pack.createObject('ParamArray');
-}
-
-/**
- * Called every frame.
- * @param {o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- g_teapotRoot.identity();
- g_teapotRoot.rotateX(g_clock);
- g_teapotRoot.rotateY(g_clock * 1.3);
-}
-
-/**
- * Cleanup before exiting.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Sobel Edge Detection Shader Example</h1>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 512px; height: 512px;"></div>
-<!-- End of O3D plugin -->
-<!--
- We embed the code for our effect inside this hidden textarea.
- Effects contain the functions that define
- the vertex and pixel shaders used by our shape.
--->
-<!-- Don't render the textarea -->
-<div style="display:none">
-<textarea id="convFX" name="convFX" cols="80" rows="20">
-float4x4 worldViewProj : WorldViewProjection;
-sampler2D image;
-float2 imageIncrement;
-
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 imageCoord : TEXCOORD0;
-};
-
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 imageCoord : TEXCOORD0;
-};
-
-PixelShaderInput SobelVS(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(input.position, worldViewProj);
- output.imageCoord = input.imageCoord;
- return output;
-}
-
-float lum(float4 c) {
- return dot(c.rgb, float3(0.3, 0.59, 0.11));
-}
-
-float4 SobelPS(PixelShaderInput input) : COLOR {
- float2 imageCoord = input.imageCoord;
- float t00 = lum(tex2D(image, imageCoord + imageIncrement * float2(-1, -1)));
- float t10 = lum(tex2D(image, imageCoord + imageIncrement * float2( 0, -1)));
- float t20 = lum(tex2D(image, imageCoord + imageIncrement * float2( 1, -1)));
- float t01 = lum(tex2D(image, imageCoord + imageIncrement * float2(-1, 0)));
- float t21 = lum(tex2D(image, imageCoord + imageIncrement * float2( 1, 0)));
- float t02 = lum(tex2D(image, imageCoord + imageIncrement * float2(-1, 1)));
- float t12 = lum(tex2D(image, imageCoord + imageIncrement * float2( 0, 1)));
- float t22 = lum(tex2D(image, imageCoord + imageIncrement * float2( 1, 1)));
- float2 grad;
- grad.x = t00 + 2.0 * t01 + t02 - t20 - 2.0 * t21 - t22;
- grad.y = t00 + 2.0 * t10 + t20 - t02 - 2.0 * t12 - t22;
- float len = length(grad);
- return float4(len, len, len, 1.0);
-}
-
-// #o3d VertexShaderEntryPoint SobelVS
-// #o3d PixelShaderEntryPoint SobelPS
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
-
-</html>
diff --git a/o3d/samples/stencil_example.html b/o3d/samples/stencil_example.html
deleted file mode 100644
index 8d52e2b..0000000
--- a/o3d/samples/stencil_example.html
+++ /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.
--->
-
-<!--
-O3D Stencil Example
-
-In this example I load 9 scene files. One file contains 3 rings and 3 circles.
-I find the circles and draw them into the stencil buffer with different Ids.
-The rings and the circles are drawn with an orthographic camera. The circles
-are manually added to a separate DrawList used by a separate DrawPass so that
-they get drawn last. Then I load 4 scenes, the teapot, torus, pyramid and pipe
-and for each one a skydome. I set a state on each of those so they will get
-masked by the stencils and for each pair I give them a different
-drawContext(viewand projection matrix)
-
-The result is 4 separate 3d scenes on the same screen with irregular shaped
-"windows" into them.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD
-HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Stencil Example
-</title>
-<!-- Include sample javascript library functions -->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_stencilPack;
-var g_stencilRoot;
-var g_treeTraversal;
-var g_scenePack = new Array();
-var g_o3dWidth; // width of our client area
-var g_o3dHeight; // height of our client area
-var g_sceneStates = new Array(); // States of stuff inside the stencils
-var G_NUM_SCENES = 4;
-var g_clock = 0;
-var g_timeMult = 1
-var g_finished = false; // for selenium testing
-
-var g_locators = new Array(); // the locator for each shape
-
-/**
- * Loads a scene into the transform graph.
- * @param {!o3d.Pack} pack Pack to load scene into.
- * @param {string} fileName filename of the scene.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the scene into.
- * @param {function(!o3d.Pack, !o3d.Transform, boolean): void} callback Function
- * to call when scene loads.
- */
-function loadScene(pack, fileName, parent, callback) {
- // Get our full path to the scene
- var scenePath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the scene given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, scenePath, callback);
-}
-
-function onrender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- g_clock += elapsedTime * g_timeMult;
-
- for (var ii = 0; ii < g_locators.length; ii++) {
- var locator = g_locators[ii];
- var rotation =
- g_math.matrix4.rotationX(Math.sin(g_clock * (ii + 1)) * 0.5);
- var translation = g_math.matrix4.getTranslation(locator.localMatrix);
-
- locator.localMatrix =
- g_math.matrix4.setTranslation(rotation, translation);
- }
-
- var rotation = g_math.matrix4.rotationZ(g_clock);
- var translation = g_stencilRoot.localMatrix[3];
-
- g_stencilRoot.localMatrix =
- g_math.matrix4.setTranslation(rotation, translation);
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the scenes.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates packs to manage our resources/assets
- g_stencilPack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_stencilPack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Get the tree traversal so we can register more DrawLists.
- g_treeTraversal = g_viewInfo.treeTraversal;
-
- // Get the width and height of our client area. We will need this to create
- // a projection matrix.
- g_o3dWidth = g_client.width;
- g_o3dHeight = g_client.height;
-
- // Set clear color to blue
- g_viewInfo.clearBuffer.clearColor = [0.1, 0.1, 1.0, 1.0];
-
- // Creates transforms to put our data on.
- g_stencilRoot = g_stencilPack.createObject('Transform');
- // Connects our roots to the client's root.
- g_stencilRoot.parent = g_client.root;
-
- var mySceneRoot = new Array();
- var myLocalDrawPass = new Array();
- for (var mm = 0; mm < G_NUM_SCENES; mm++) {
- g_scenePack[mm] = g_client.createPack();
- mySceneRoot[mm] = g_scenePack[mm].createObject('Transform');
- mySceneRoot[mm].parent = g_client.root;
- var localDrawList = g_scenePack[mm].createObject('DrawList');
- var localDrawPass = g_stencilPack.createObject('DrawPass');
- var localStateSet = g_stencilPack.createObject('StateSet');
- var localState = g_stencilPack.createObject('State');
- localStateSet.priority = 4;
- localStateSet.state = localState;
- // make a state that passes only for a particular stencil value
- localState.getStateParam('StencilEnable').value = true;
- localState.getStateParam('StencilReference').value = mm;
- localState.getStateParam('StencilComparisonFunction').value =
- g_o3d.State.CMP_EQUAL;
- localStateSet.parent = g_viewInfo.viewport;
- localDrawPass.drawList = localDrawList;
- localDrawPass.parent = localStateSet;
- myLocalDrawPass[mm] = localDrawPass;
- }
-
- // Load the scene into the transform graph as a child my_data_root
- loadScene(g_stencilPack, 'assets/stencil_frame.o3dtgz', g_stencilRoot,
- setupStencilsAndOverlay);
-
- /**
- * Our callback is called once the scene has been loaded into memory
- * from the web or locally.
- */
- function setupStencilsAndOverlay() {
- // Get a cameraInfo (a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- g_stencilRoot,
- g_o3dWidth,
- g_o3dHeight);
-
- var backDrawContext = g_stencilPack.createObject('DrawContext');
- backDrawContext.view = cameraInfo.view;
- backDrawContext.projection = cameraInfo.projection;
-
- // create 2 DrawPasses that uses this context to draw things as in the
- // stencil_frame.o3dtgz file which I already setup with an orthographic
- // projection matrix. Each one needs a draw list as well. Also create a
- // StateSet to set the stencil render states for everything drawn
- // by the back DrawPass.
-
- // first one to draw the 3 circles into the stencil.
- var backDrawList = g_stencilPack.createObject('DrawList');
- var backDrawPass = g_stencilPack.createObject('DrawPass');
- var backStateSet = g_stencilPack.createObject('StateSet');
- var backState = g_stencilPack.createObject('State');
- backDrawPass.parent = backStateSet;
- backDrawPass.drawList = backDrawList;
- // after tree_traversal, before opaque
- backStateSet.priority = g_viewInfo.treeTraversal.priority + 0.5;
- backStateSet.parent = g_viewInfo.viewport;
- backStateSet.state = backState;
- g_treeTraversal.registerDrawList(backDrawList, backDrawContext, true);
- backState.getStateParam('StencilEnable').value = true;
- backState.getStateParam('StencilPassOperation').value =
- g_o3d.State.STENCIL_REPLACE;
- backState.getStateParam('StencilComparisonFunction').value =
- g_o3d.State.CMP_ALWAYS;
- backState.getStateParam('ZEnable').value = false;
- backState.getStateParam('ZWriteEnable').value = false;
- backState.getStateParam('ColorWriteEnable').value = 0;
-
- // Next one to draw the 3 rings in front of everything
- var frontDrawList = g_stencilPack.createObject('DrawList');
- var frontDrawPass = g_stencilPack.createObject('DrawPass');
- frontDrawPass.drawList = frontDrawList;
- frontDrawPass.priority = 9001; // after our special clear.
- frontDrawPass.parent = g_viewInfo.viewport;
- g_treeTraversal.registerDrawList(frontDrawList, backDrawContext, true);
-
- // find all the pCylinder1 Transforms (the stencil discs)
- var stencils = g_stencilRoot.getTransformsByNameInTree('pCylinder1');
-
- // put each stencils at the beginning of the render graph
- for (var ss = 0; ss < stencils.length; ss++) {
- // there should be only one shape under each pCylinder1
- var shape = stencils[ss].shapes[0];
-
- // make a new material.
- var material = g_stencilPack.createObject('Material');
-
- // copy the old material's params.
- material.copyParams(shape.elements[0].material);
-
- // tell things drawn with this material to get drawn in the back draw
- // list.
- material.drawList = backDrawList;
-
- // create DrawElements using this material.
- shape.createDrawElements(g_stencilPack, material);
-
- o3djs.material.attachStandardEffect(g_stencilPack,
- material,
- g_viewInfo,
- 'phong');
-
- // make state that renders into the stencil only
- var state = g_stencilPack.createObject('State');
- material.state = state;
- state.getStateParam('StencilReference').value = ss + 1;
- }
-
- // clear the zbuffer before drawing the circles
- var clearBuffer = g_stencilPack.createObject('ClearBuffer');
- clearBuffer.clearColorFlag = false;
- clearBuffer.clearStencilFlag = false;
- clearBuffer.priority = 9000;
- clearBuffer.parent = g_viewInfo.viewport;
-
- // put each circle at the end of the render graph
-
- // find all the pPipe? Transforms
- var circles = o3djs.util.getTransformsInTreeByPrefix(g_stencilRoot,
- 'pPipe');
- for (var cc = 0; cc < circles.length; cc++) {
- var transform = circles[cc];
- // there should be only one shape under each pPipe
- var shape = transform.shapes[0];
- // there should be only one element in each shape.
- var primitive = shape.elements[0];
- // set it's material to draw in the front draw list.
- primitive.material.drawList = frontDrawList;
- o3djs.material.attachStandardEffect(g_stencilPack,
- primitive.material,
- g_viewInfo,
- 'phong');
-
- // generate draw elements for it.
- shape.createDrawElements(g_stencilPack,
- null);
- }
-
- loadScene(g_scenePack[0], 'assets/teapot.o3dtgz', mySceneRoot[0],
- setupScene0);
- }
-
- function setupScene0() {
- loadScene(g_scenePack[0], 'assets/dome1.o3dtgz', mySceneRoot[0],
- setupDome0);
- }
-
- function setupDome0() {
- // Stencil 0 is the center.
- setupScene(g_scenePack[0], mySceneRoot[0], 0);
- loadScene(g_scenePack[1], 'assets/part1.o3dtgz', mySceneRoot[1],
- setupScene1);
- }
-
- function setupScene1() {
- loadScene(g_scenePack[1], 'assets/dome2.o3dtgz', mySceneRoot[1],
- setupDome1);
- }
-
- function setupDome1() {
- // stencil 3 is the top left.
- setupScene(g_scenePack[1], mySceneRoot[1], 3);
- loadScene(g_scenePack[2], 'assets/part2.o3dtgz', mySceneRoot[2],
- setupScene2);
- }
-
- function setupScene2() {
- loadScene(g_scenePack[2], 'assets/dome3.o3dtgz', mySceneRoot[2],
- setupDome2);
- }
-
- function setupDome2() {
- // stencil 2 is the top right.
- setupScene(g_scenePack[2], mySceneRoot[2], 2);
- loadScene(g_scenePack[3], 'assets/part3.o3dtgz', mySceneRoot[3],
- setupScene3);
- }
-
- function setupScene3() {
- loadScene(g_scenePack[3], 'assets/dome4.o3dtgz', mySceneRoot[3],
- setupDome3);
- }
-
- function setupDome3() {
- // stencil 1 is the bottom.
- setupScene(g_scenePack[3], mySceneRoot[3], 1);
-
- g_client.setRenderCallback(onrender);
- g_finished = true; // for selenium testing.
- }
-
- function setupScene(pack, root, stencil_id) {
- // Get a cameraInfo (a Transform with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- root,
- g_o3dWidth,
- g_o3dHeight);
-
- // Create a new draw context and set it to use the camera from the scene
- // we just loaded.
- var sceneContext = pack.createObject('DrawContext');
- sceneContext.view = cameraInfo.view;
- sceneContext.projection = cameraInfo.projection;
-
- g_treeTraversal.registerDrawList(myLocalDrawPass[stencil_id].drawList,
- sceneContext,
- true);
-
- // save off the locators. Our shapes are parented to the so we can rotate
- // them for animation
- var locators = o3djs.util.getTransformsInTreeByPrefix(root,
- 'locator');
- g_locators[g_locators.length] = root;
-
- // get all the shapes in the pack we just loaded.
- var shapes = pack.getObjectsByClassName('o3d.Shape');
- for (var ss = 0; ss < shapes.length; ss++) {
- var shape = shapes[ss];
- var elements = shape.elements;
- for (var ee = 0; ee < elements.length; ++ee) {
- var element = elements[ee];
- element.material.drawList = myLocalDrawPass[stencil_id].drawList;
- o3djs.material.attachStandardEffect(g_stencilPack,
- element.material,
- g_viewInfo,
- 'phong');
- }
- }
-
- root.createDrawElements(pack, null);
- }
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Stencil Example</h1>
-Shows 4 &quot;Views&quot; using 4 stencils, and 9 scene files.
-4 shapes, 4 skydomes, 1 frame drawn with an orthographic projection.
-<br/>
-<!-- Start of O3D plugin -->
-<!--
-NOTE: Because we are using cameras directly from the loaded scene and
-beacuse we are using an orthographic camera the dimensions of our client
-area must have the same aspect ratio as the original scene in Maya otherwise
-we will not get the same results.
-
-The original scene size was 1280x720
--->
-<div id="o3d" style="width: 800px; height: 450px"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/texturesamplers.html b/o3d/samples/texturesamplers.html
deleted file mode 100644
index c64d827..0000000
--- a/o3d/samples/texturesamplers.html
+++ /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.
--->
-
-<!--
-O3D Texture Samplers example.
-
-Demonstrates how to create samplers and set their various states.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Texture Samplers
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.event');
-o3djs.require('o3djs.io');
-
-// Events
-// Run the init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_eye;
-var g_target;
-var g_up;
-var g_finished = false; // for selenium testing
-
-function scrollMe(e) {
- g_eye = g_math.mulScalarVector((e.deltaY < 0 ? 11 : 13) / 12, g_eye);
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(g_eye, g_target, g_up);
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and draws the quads.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 100.
- var proj_matrix = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 100);
-
- // Create the view matrix which tells the camera which way to point to.
- g_eye = [0, 4, 0];
- g_target = [0, 0, 0];
- g_up = [0, 0, -1];
- var view_matrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);
-
- g_viewInfo.drawContext.view = view_matrix;
- g_viewInfo.drawContext.projection = proj_matrix;
-
- var samplers = [];
- var transforms = [];
- for (var xx = 0; xx < 3; xx++) {
- for (var yy = 0; yy < 2; yy++) {
- var index = yy * 3 + xx;
-
- // Create a new Material for the quad.
- var material = o3djs.material.createMaterialFromFile(
- g_pack,
- 'shaders/texture-only.shader',
- g_viewInfo.performanceDrawList);
-
- // Create a quad and position it.
- var verts = o3djs.primitives.createPlaneVertices(1, 1, 1, 1);
- var texCoordStream = verts.findStream(g_o3d.Stream.TEXCOORD, 0);
- // make the UVs go from 0 to 2 instead of 0 to 1
- for (var v = 0; v < texCoordStream.elements.length; ++v) {
- texCoordStream.elements[v] *= 2;
- }
- var shape = verts.createShape(g_pack, material);
-
- // Make a transform for each quad.
- var transform = g_pack.createObject('Transform');
- transform.translate([(xx - 1) * 1.2, 0, (0.5 - yy) * -1.2]);
- transform.addShape(shape);
-
- // Get the sampler param on the material.
- var samplerParam = material.getParam('texSampler0');
-
- // Get the sampler on the sampler param.
- var sampler = samplerParam.value;
- samplers[index] = sampler;
- transforms[index] = transform;
- }
- }
-
- // Set the sampler states on each sampler.
- // Looking at the generated image, the samplers correspond to the
- // following quads:
- // [0] [1] [2]
- // [3] [4] [5]
- // Sampler states not specified assume their default values which are:
- // addressModeU = Sampler.WRAP
- // addressModeV = Sampler.WRAP
- // minFilter = Sampler.LINEAR
- // magFilter = Sampler.LINEAR
- // mipFilter = Sampler.POINT
- // borderColor = Float4(0, 0, 0, 0)
- // maxAnisotropy = 1
-
- // Rotates quad and uses anisotropic filtering.
- transforms[1].rotateZ(-Math.PI / 2.5);
- samplers[1].addressModeU = g_o3d.Sampler.WRAP;
- samplers[1].addressModeV = g_o3d.Sampler.WRAP;
- samplers[1].minFilter = g_o3d.Sampler.ANISOTROPIC;
- samplers[1].maxAnisotropy = 4;
-
- // Uses BORDER addressing mode with a red border.
- samplers[2].addressModeU = g_o3d.Sampler.BORDER;
- samplers[2].addressModeV = g_o3d.Sampler.BORDER;
- samplers[2].borderColor = [1, 0, 0, 1];
-
- // Uses POINT sampling for minification.
- samplers[3].addressModeU = g_o3d.Sampler.WRAP;
- samplers[3].addressModeV = g_o3d.Sampler.WRAP;
- samplers[3].minFilter = g_o3d.Sampler.POINT;
-
- // Rotates quad and uses default (linear) filtering.
- // Compare results to quad #1.
- transforms[4].rotateZ(-Math.PI / 2.5);
- samplers[4].addressModeU = g_o3d.Sampler.WRAP;
- samplers[4].addressModeV = g_o3d.Sampler.WRAP;
- samplers[4].minFilter = g_o3d.Sampler.LINEAR;
- samplers[4].magFilter = g_o3d.Sampler.LINEAR;
-
- // Uses MIRROR addressing mode to mirror the texture on both axes.
- samplers[5].addressModeU = g_o3d.Sampler.MIRROR;
- samplers[5].addressModeV = g_o3d.Sampler.MIRROR;
-
- // Load our texture!
- var url = o3djs.util.getCurrentURI() + 'assets/texture_b3.jpg';
- o3djs.io.loadTexture(g_pack, url, function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- // Use the same texture for all the samplers.
- for (var ii = 0; ii < samplers.length; ii++) {
- samplers[ii].texture = texture;
- }
- // Parent the transforms. We do this here because until the texture
- // is loaded our quads are not ready to display.
- for (var ii = 0; ii < transforms.length; ii++) {
- transforms[ii].parent = g_client.root;
- }
- g_finished = true; // for selenium testing.
- }
- });
-
- o3djs.event.addEventListener(o3dElement, 'wheel', scrollMe);
-}
-</script>
-</head>
-<body>
-<h1>Texture Sampler Example</h1>
-This tutorial demonstrates various texture sampler settings.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 700px; height: 600px"></div>
-<p>Scrollwheel To Zoom</p><br/>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/third_party/codemirror/LICENSE b/o3d/samples/third_party/codemirror/LICENSE
deleted file mode 100644
index 12134c0..0000000
--- a/o3d/samples/third_party/codemirror/LICENSE
+++ /dev/null
@@ -1,23 +0,0 @@
- Copyright (c) 2007 Marijn Haverbeke
-
- This software is provided 'as-is', without any express or implied
- warranty. In no event will the authors be held liable for any
- damages arising from the use of this software.
-
- Permission is granted to anyone to use this software for any
- purpose, including commercial applications, and to alter it and
- redistribute it freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented; you must
- not claim that you wrote the original software. If you use this
- software in a product, an acknowledgment in the product
- documentation would be appreciated but is not required.
-
- 2. Altered source versions must be plainly marked as such, and must
- not be misrepresented as being the original software.
-
- 3. This notice may not be removed or altered from any source
- distribution.
-
- Marijn Haverbeke
- marijnh at gmail
diff --git a/o3d/samples/third_party/codemirror/README.o3d b/o3d/samples/third_party/codemirror/README.o3d
deleted file mode 100644
index dcee190..0000000
--- a/o3d/samples/third_party/codemirror/README.o3d
+++ /dev/null
@@ -1,5 +0,0 @@
-This is the CodeMirror tool, Copyright (c) 2007 Marijn Haverbeke, version 0.58.
-Please see the LICENSE file. None of the code was modified, but some files
-haven't been included for simplicity.
-The originally version is available at:
-http://marijn.haverbeke.nl/codemirror/codemirror-0.58.zip
diff --git a/o3d/samples/third_party/codemirror/css/csscolors.css b/o3d/samples/third_party/codemirror/css/csscolors.css
deleted file mode 100644
index 100c93f..0000000
--- a/o3d/samples/third_party/codemirror/css/csscolors.css
+++ /dev/null
@@ -1,47 +0,0 @@
-.editbox {
- margin: .4em;
- padding: 0;
- font-family: monospace;
- font-size: 10pt;
- color: black;
-}
-
-pre.code, .editbox {
- color: #666666;
-}
-
-.editbox p {
- margin: 0;
-}
-
-span.css-at {
- color: #770088;
-}
-
-span.css-unit {
- color: #228811;
-}
-
-span.css-value {
- color: #770088;
-}
-
-span.css-identifier {
- color: black;
-}
-
-span.css-important {
- color: #0000FF;
-}
-
-span.css-colorcode {
- color: #004499;
-}
-
-span.css-comment {
- color: #AA7700;
-}
-
-span.css-string {
- color: #AA2222;
-}
diff --git a/o3d/samples/third_party/codemirror/css/docs.css b/o3d/samples/third_party/codemirror/css/docs.css
deleted file mode 100644
index 4906d0b..0000000
--- a/o3d/samples/third_party/codemirror/css/docs.css
+++ /dev/null
@@ -1,38 +0,0 @@
-body {
- margin: 0;
- font-family: tahoma, arial, sans-serif;
- padding: 3em 6em;
- color: black;
-}
-
-h1 {
- font-size: 22pt;
-}
-
-h2 {
- font-size: 14pt;
-}
-
-p.rel {
- padding-left: 2em;
- text-indent: -2em;
-}
-
-div.border {
- border: 1px solid black;
- padding: 3px;
-}
-
-code {
- font-family: courier, monospace;
- font-size: 90%;
- color: #277;
-}
-
-pre.code {
- margin: 1.1em 12px;
- border: 1px solid #CCCCCC;
- color: black;
- padding: .4em;
- font-family: courier, monospace;
-}
diff --git a/o3d/samples/third_party/codemirror/css/jscolors.css b/o3d/samples/third_party/codemirror/css/jscolors.css
deleted file mode 100644
index 950b440..0000000
--- a/o3d/samples/third_party/codemirror/css/jscolors.css
+++ /dev/null
@@ -1,47 +0,0 @@
-.editbox {
- margin: .4em;
- padding: 0;
- font-family: monospace;
- font-size: 10pt;
- color: black;
-}
-
-pre.code, .editbox {
- color: #666666;
-}
-
-.editbox p {
- margin: 0;
-}
-
-span.js-keyword {
- color: #770088;
-}
-
-span.js-atom {
- color: #228811;
-}
-
-span.js-variable {
- color: black;
-}
-
-span.js-variabledef {
- color: #0000FF;
-}
-
-span.js-localvariable {
- color: #004499;
-}
-
-span.js-property {
- color: black;
-}
-
-span.js-comment {
- color: #AA7700;
-}
-
-span.js-string {
- color: #AA2222;
-}
diff --git a/o3d/samples/third_party/codemirror/css/xmlcolors.css b/o3d/samples/third_party/codemirror/css/xmlcolors.css
deleted file mode 100644
index aa26579..0000000
--- a/o3d/samples/third_party/codemirror/css/xmlcolors.css
+++ /dev/null
@@ -1,51 +0,0 @@
-.editbox {
- margin: .4em;
- padding: 0;
- font-family: monospace;
- font-size: 10pt;
- color: black;
-}
-
-.editbox p {
- margin: 0;
-}
-
-span.xml-tagname {
- color: #A0B;
-}
-
-span.xml-attribute {
- color: #281;
-}
-
-span.xml-punctuation {
- color: black;
-}
-
-span.xml-attname {
- color: #00F;
-}
-
-span.xml-comment {
- color: #A70;
-}
-
-span.xml-cdata {
- color: #48A;
-}
-
-span.xml-processing {
- color: #999;
-}
-
-span.xml-entity {
- color: #A22;
-}
-
-span.xml-error {
- color: #F00;
-}
-
-span.xml-text {
- color: black;
-}
diff --git a/o3d/samples/third_party/codemirror/js/codemirror.js b/o3d/samples/third_party/codemirror/js/codemirror.js
deleted file mode 100644
index 9b7b5db..0000000
--- a/o3d/samples/third_party/codemirror/js/codemirror.js
+++ /dev/null
@@ -1,189 +0,0 @@
-/* CodeMirror main module
- *
- * Implements the CodeMirror constructor and prototype, which take care
- * of initializing the editor frame, and providing the outside interface.
- */
-
-// The CodeMirrorConfig object is used to specify a default
-// configuration. If you specify such an object before loading this
-// file, the values you put into it will override the defaults given
-// below. You can also assign to it after loading.
-var CodeMirrorConfig = window.CodeMirrorConfig || {};
-
-var CodeMirror = (function(){
- function setDefaults(object, defaults) {
- for (var option in defaults) {
- if (!object.hasOwnProperty(option))
- object[option] = defaults[option];
- }
- }
- function forEach(array, action) {
- for (var i = 0; i < array.length; i++)
- action(array[i]);
- }
-
- // These default options can be overridden by passing a set of
- // options to a specific CodeMirror constructor. See manual.html for
- // their meaning.
- setDefaults(CodeMirrorConfig, {
- stylesheet: "",
- path: "",
- parserfile: [],
- basefiles: ["util.js", "stringstream.js", "select.js", "undo.js", "editor.js", "tokenize.js"],
- linesPerPass: 15,
- passDelay: 200,
- continuousScanning: false,
- saveFunction: null,
- onChange: null,
- undoDepth: 20,
- undoDelay: 800,
- disableSpellcheck: true,
- textWrapping: true,
- readOnly: false,
- width: "100%",
- height: "300px",
- autoMatchParens: false,
- parserConfig: null,
- dumbTabs: false
- });
-
- function CodeMirror(place, options) {
- // Use passed options, if any, to override defaults.
- this.options = options = options || {};
- setDefaults(options, CodeMirrorConfig);
-
- var frame = this.frame = document.createElement("IFRAME");
- frame.style.border = "0";
- frame.style.width = options.width;
- frame.style.height = options.height;
- // display: block occasionally suppresses some Firefox bugs, so we
- // always add it, redundant as it sounds.
- frame.style.display = "block";
-
- if (place.appendChild)
- place.appendChild(frame);
- else
- place(frame);
-
- // Link back to this object, so that the editor can fetch options
- // and add a reference to itself.
- frame.CodeMirror = this;
- this.win = frame.contentWindow;
-
- if (typeof options.parserfile == "string")
- options.parserfile = [options.parserfile];
- if (typeof options.stylesheet == "string")
- options.stylesheet = [options.stylesheet];
-
- var html = ["<html><head>"];
- forEach(options.stylesheet, function(file) {
- html.push("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + file + "\"/>");
- });
- forEach(options.basefiles.concat(options.parserfile), function(file) {
- html.push("<script type=\"text/javascript\" src=\"" + options.path + file + "\"></script>");
- });
- html.push("</head><body style=\"border-width: 0;\" class=\"editbox\" spellcheck=\"" +
- (options.disableSpellcheck ? "false" : "true") + "\"></body></html>");
-
- var doc = this.win.document;
- doc.open();
- doc.write(html.join(""));
- doc.close();
- }
-
- CodeMirror.prototype = {
- getCode: function() {
- return this.editor.getCode();
- },
- setCode: function(code) {
- this.editor.importCode(code);
- },
- focus: function() {
- this.win.focus();
- },
- jumpToChar: function(start, end) {
- this.editor.jumpToChar(start, end);
- this.focus();
- },
- jumpToLine: function(line) {
- this.editor.jumpToLine(line);
- this.focus();
- },
- currentLine: function() {
- return this.editor.currentLine();
- },
- selection: function() {
- return this.editor.selectedText();
- },
- reindent: function() {
- this.editor.reindent();
- },
- replaceSelection: function(text, focus) {
- var result = this.editor.replaceSelection(text);
- if (focus) this.focus();
- return result;
- },
- replaceChars: function(text, start, end) {
- this.editor.replaceChars(text, start, end);
- },
- getSearchCursor: function(string, fromCursor) {
- return this.editor.getSearchCursor(string, fromCursor);
- }
- };
-
- CodeMirror.replace = function(element) {
- if (typeof element == "string")
- element = document.getElementById(element);
- return function(newElement) {
- element.parentNode.replaceChild(newElement, element);
- };
- };
-
- CodeMirror.fromTextArea = function(area, options) {
- if (typeof area == "string")
- area = document.getElementById(area);
-
- options = options || {};
- if (area.style.width) options.width = area.style.width;
- if (area.style.height) options.height = area.style.height;
- if (options.content == null) options.content = area.value;
-
- if (area.form) {
- function updateField() {
- area.value = mirror.getCode();
- }
- if (typeof area.form.addEventListener == "function")
- area.form.addEventListener("submit", updateField, false);
- else
- area.form.attachEvent("onsubmit", updateField);
- }
-
- function insert(frame) {
- if (area.nextSibling)
- area.parentNode.insertBefore(frame, area.nextSibling);
- else
- area.parentNode.appendChild(frame);
- }
-
- area.style.display = "none";
- var mirror = new CodeMirror(insert, options);
- return mirror;
- };
-
- CodeMirror.isProbablySupported = function() {
- // This is rather awful, but can be useful.
- var match;
- if (window.opera)
- return Number(window.opera.version()) >= 9.52;
- else if (/Apple Computers, Inc/.test(navigator.vendor) && (match = navigator.userAgent.match(/Version\/(\d+(?:\.\d+)?)\./)))
- return Number(match[1]) >= 3;
- else if (document.selection && window.ActiveXObject && (match = navigator.userAgent.match(/MSIE (\d+(?:\.\d*)?)\b/)))
- return Number(match[1]) >= 6;
- else if (match = navigator.userAgent.match(/gecko\/(\d{8})/i))
- return Number(match[1]) >= 20050901;
- else
- return null;
- };
-
- return CodeMirror;
-})();
diff --git a/o3d/samples/third_party/codemirror/js/editor.js b/o3d/samples/third_party/codemirror/js/editor.js
deleted file mode 100644
index d963025..0000000
--- a/o3d/samples/third_party/codemirror/js/editor.js
+++ /dev/null
@@ -1,1052 +0,0 @@
-/* The Editor object manages the content of the editable frame. It
- * catches events, colours nodes, and indents lines. This file also
- * holds some functions for transforming arbitrary DOM structures into
- * plain sequences of <span> and <br> elements
- */
-
-var Editor = (function(){
- // The HTML elements whose content should be suffixed by a newline
- // when converting them to flat text.
- var newlineElements = {"P": true, "DIV": true, "LI": true};
-
- // Create a set of white-space characters that will not be collapsed
- // by the browser, but will not break text-wrapping either.
- function safeWhiteSpace(n) {
- var buffer = [], nb = true;
- for (; n > 0; n--) {
- buffer.push((nb || n == 1) ? nbsp : " ");
- nb = !nb;
- }
- return buffer.join("");
- }
-
- function splitSpaces(string) {
- if (string == " ") return nbsp;
- else return string.replace(/[\t \u00a0]{2,}/g, function(s) {return safeWhiteSpace(s.length);});
- }
- function asEditorLines(string) {
- return splitSpaces(string.replace(/\u00a0/g, " ")).replace(/\r\n?/g, "\n").split("\n");
- }
-
- var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent);
-
- // Helper function for traverseDOM. Flattens an arbitrary DOM node
- // into an array of textnodes and <br> tags.
- function simplifyDOM(root) {
- var doc = root.ownerDocument;
- var result = [];
- var leaving = false;
-
- function simplifyNode(node) {
- if (node.nodeType == 3) {
- var text = node.nodeValue = splitSpaces(node.nodeValue.replace(/[\n\r]/g, ""));
- if (text.length) leaving = false;
- result.push(node);
- }
- else if (node.nodeName == "BR" && node.childNodes.length == 0) {
- leaving = true;
- result.push(node);
- }
- else {
- forEach(node.childNodes, simplifyNode);
- if (!leaving && newlineElements.hasOwnProperty(node.nodeName)) {
- leaving = true;
- result.push(doc.createElement("BR"));
- }
- }
- }
-
- simplifyNode(root);
- return result;
- }
-
- // Creates a MochiKit-style iterator that goes over a series of DOM
- // nodes. The values it yields are strings, the textual content of
- // the nodes. It makes sure that all nodes up to and including the
- // one whose text is being yielded have been 'normalized' to be just
- // <span> and <br> elements.
- // See the story.html file for some short remarks about the use of
- // continuation-passing style in this iterator.
- function traverseDOM(start){
- function yield(value, c){cc = c; return value;}
- function push(fun, arg, c){return function(){return fun(arg, c);};}
- function stop(){cc = stop; throw StopIteration;};
- var cc = push(scanNode, start, stop);
- var owner = start.ownerDocument;
- var nodeQueue = [];
-
- // Create a function that can be used to insert nodes after the
- // one given as argument.
- function pointAt(node){
- var parent = node.parentNode;
- var next = node.nextSibling;
- return function(newnode) {
- parent.insertBefore(newnode, next);
- };
- }
- var point = null;
-
- // Insert a normalized node at the current point. If it is a text
- // node, wrap it in a <span>, and give that span a currentText
- // property -- this is used to cache the nodeValue, because
- // directly accessing nodeValue is horribly slow on some browsers.
- // The dirty property is used by the highlighter to determine
- // which parts of the document have to be re-highlighted.
- function insertPart(part){
- var text = "\n";
- if (part.nodeType == 3) {
- text = part.nodeValue;
- var span = owner.createElement("SPAN");
- span.className = "part";
- span.appendChild(part);
- part = span;
- part.currentText = text;
- }
- part.dirty = true;
- nodeQueue.push(part);
- point(part);
- return text;
- }
-
- // Extract the text and newlines from a DOM node, insert them into
- // the document, and yield the textual content. Used to replace
- // non-normalized nodes.
- function writeNode(node, c){
- var toYield = [];
- forEach(simplifyDOM(node), function(part) {
- toYield.push(insertPart(part));
- });
- return yield(toYield.join(""), c);
- }
-
- // Check whether a node is a normalized <span> element.
- function partNode(node){
- if (node.nodeName == "SPAN" && node.childNodes.length == 1 && node.firstChild.nodeType == 3){
- node.currentText = node.firstChild.nodeValue;
- return true;
- }
- return false;
- }
-
- // Handle a node. Add its successor to the continuation if there
- // is one, find out whether the node is normalized. If it is,
- // yield its content, otherwise, normalize it (writeNode will take
- // care of yielding).
- function scanNode(node, c){
- if (node.nextSibling)
- c = push(scanNode, node.nextSibling, c);
-
- if (partNode(node)){
- nodeQueue.push(node);
- return yield(node.currentText, c);
- }
- else if (node.nodeName == "BR") {
- nodeQueue.push(node);
- return yield("\n", c);
- }
- else {
- point = pointAt(node);
- removeElement(node);
- return writeNode(node, c);
- }
- }
-
- // MochiKit iterators are objects with a next function that
- // returns the next value or throws StopIteration when there are
- // no more values.
- return {next: function(){return cc();}, nodes: nodeQueue};
- }
-
- // Determine the text size of a processed node.
- function nodeSize(node) {
- if (node.nodeName == "BR")
- return 1;
- else
- return node.currentText.length;
- }
-
- // Search backwards through the top-level nodes until the next BR or
- // the start of the frame.
- function startOfLine(node) {
- while (node && node.nodeName != "BR")
- node = node.previousSibling;
- return node;
- }
-
- function cleanText(text) {
- return text.replace(/\u00a0/g, " ");
- }
-
- // Client interface for searching the content of the editor. Create
- // these by calling CodeMirror.getSearchCursor. To use, call
- // findNext on the resulting object -- this returns a boolean
- // indicating whether anything was found, and can be called again to
- // skip to the next find. Use the select and replace methods to
- // actually do something with the found locations.
- function SearchCursor(editor, string, fromCursor) {
- this.editor = editor;
- this.history = editor.history;
- this.history.commit();
-
- // Are we currently at an occurrence of the search string?
- this.atOccurrence = false;
- // The object stores a set of nodes coming after its current
- // position, so that when the current point is taken out of the
- // DOM tree, we can still try to continue.
- this.fallbackSize = 15;
- var cursor;
- // Start from the cursor when specified and a cursor can be found.
- if (fromCursor && (cursor = select.cursorPos(this.editor.container))) {
- this.line = cursor.node;
- this.offset = cursor.offset;
- }
- else {
- this.line = null;
- this.offset = 0;
- }
- this.valid = !!string;
-
- // Create a matcher function based on the kind of string we have.
- var target = string.split("\n"), self = this;;
- this.matches = (target.length == 1) ?
- // For one-line strings, searching can be done simply by calling
- // indexOf on the current line.
- function() {
- var match = cleanText(self.history.textAfter(self.line).slice(self.offset)).indexOf(string);
- if (match > -1)
- return {from: {node: self.line, offset: self.offset + match},
- to: {node: self.line, offset: self.offset + match + string.length}};
- } :
- // Multi-line strings require internal iteration over lines, and
- // some clunky checks to make sure the first match ends at the
- // end of the line and the last match starts at the start.
- function() {
- var firstLine = cleanText(self.history.textAfter(self.line).slice(self.offset));
- var match = firstLine.lastIndexOf(target[0]);
- if (match == -1 || match != firstLine.length - target[0].length)
- return false;
- var startOffset = self.offset + match;
-
- var line = self.history.nodeAfter(self.line);
- for (var i = 1; i < target.length - 1; i++) {
- if (cleanText(self.history.textAfter(line)) != target[i])
- return false;
- line = self.history.nodeAfter(line);
- }
-
- if (cleanText(self.history.textAfter(line)).indexOf(target[target.length - 1]) != 0)
- return false;
-
- return {from: {node: self.line, offset: startOffset},
- to: {node: line, offset: target[target.length - 1].length}};
- };
- }
-
- SearchCursor.prototype = {
- findNext: function() {
- if (!this.valid) return false;
- this.atOccurrence = false;
- var self = this;
-
- // Go back to the start of the document if the current line is
- // no longer in the DOM tree.
- if (this.line && !this.line.parentNode) {
- this.line = null;
- this.offset = 0;
- }
-
- // Set the cursor's position one character after the given
- // position.
- function saveAfter(pos) {
- if (self.history.textAfter(pos.node).length < pos.offset) {
- self.line = pos.node;
- self.offset = pos.offset + 1;
- }
- else {
- self.line = self.history.nodeAfter(pos.node);
- self.offset = 0;
- }
- }
-
- while (true) {
- var match = this.matches();
- // Found the search string.
- if (match) {
- this.atOccurrence = match;
- saveAfter(match.from);
- return true;
- }
- this.line = this.history.nodeAfter(this.line);
- this.offset = 0;
- // End of document.
- if (!this.line) {
- this.valid = false;
- return false;
- }
- }
- },
-
- select: function() {
- if (this.atOccurrence) {
- select.setCursorPos(this.editor.container, this.atOccurrence.from, this.atOccurrence.to);
- select.scrollToCursor(this.editor.container);
- }
- },
-
- replace: function(string) {
- if (this.atOccurrence) {
- var end = this.editor.replaceRange(this.atOccurrence.from, this.atOccurrence.to, string);
- this.line = end.node;
- this.offset = end.offset;
- this.atOccurrence = false;
- }
- }
- };
-
- // The Editor object is the main inside-the-iframe interface.
- function Editor(options) {
- this.options = options;
- this.parent = parent;
- this.doc = document;
- this.container = this.doc.body;
- this.win = window;
- this.history = new History(this.container, this.options.undoDepth, this.options.undoDelay,
- this, options.onChange);
-
- if (!Editor.Parser)
- throw "No parser loaded.";
- if (options.parserConfig && Editor.Parser.configure)
- Editor.Parser.configure(options.parserConfig);
-
- if (!options.textWrapping)
- this.container.style.whiteSpace = "pre";
-
- select.setCursorPos(this.container, {node: null, offset: 0});
-
- this.dirty = [];
- if (options.content)
- this.importCode(options.content);
- else // FF acts weird when the editable document is completely empty
- this.container.appendChild(this.doc.createElement("BR"));
-
- if (!options.readOnly) {
- if (options.continuousScanning !== false) {
- this.scanner = this.documentScanner(options.linesPerPass);
- this.delayScanning();
- }
-
- function setEditable() {
- // In IE, designMode frames can not run any scripts, so we use
- // contentEditable instead.
- if (document.body.contentEditable != undefined && /MSIE/.test(navigator.userAgent))
- document.body.contentEditable = "true";
- else
- document.designMode = "on";
- }
-
- // If setting the frame editable fails, try again when the user
- // focus it (happens when the frame is not visible on
- // initialisation, in Firefox).
- try {
- setEditable();
- }
- catch(e) {
- var focusEvent = addEventHandler(document, "focus", function() {
- removeEventHandler(focusEvent);
- setEditable();
- });
- }
-
- addEventHandler(document, "keydown", method(this, "keyDown"));
- addEventHandler(document, "keypress", method(this, "keyPress"));
- addEventHandler(document, "keyup", method(this, "keyUp"));
- addEventHandler(document.body, "paste", method(this, "markCursorDirty"));
- addEventHandler(document.body, "cut", method(this, "markCursorDirty"));
- if (this.options.autoMatchParens)
- addEventHandler(document.body, "click", method(this, "scheduleParenBlink"));
- }
- }
-
- function isSafeKey(code) {
- return (code >= 16 && code <= 18) || // shift, control, alt
- (code >= 33 && code <= 40); // arrows, home, end
- }
-
- Editor.prototype = {
- // Import a piece of code into the editor.
- importCode: function(code) {
- this.history.push(null, null, asEditorLines(code));
- this.history.reset();
- },
-
- // Extract the code from the editor.
- getCode: function() {
- if (!this.container.firstChild)
- return "";
-
- var accum = [];
- forEach(traverseDOM(this.container.firstChild), method(accum, "push"));
- return cleanText(accum.join(""));
- },
-
- // Move the cursor to the start of a specific line (counting from 1).
- jumpToLine: function(line) {
- if (line <= 1 || !this.container.firstChild) {
- select.focusAfterNode(null, this.container);
- }
- else {
- var pos = this.container.firstChild;
- while (true) {
- if (pos.nodeName == "BR") line--;
- if (line <= 1 || !pos.nextSibling) break;
- pos = pos.nextSibling;
- }
- select.focusAfterNode(pos, this.container);
- }
- select.scrollToCursor(this.container);
- },
-
- // Find the line that the cursor is currently on.
- currentLine: function() {
- var pos = select.cursorPos(this.container, true), line = 1;
- if (!pos) return 1;
- for (cursor = pos.node; cursor; cursor = cursor.previousSibling)
- if (cursor.nodeName == "BR") line++;
- return line;
- },
-
- // Retrieve the selected text.
- selectedText: function() {
- var h = this.history;
- h.commit();
-
- var start = select.cursorPos(this.container, true),
- end = select.cursorPos(this.container, false);
- if (!start || !end) return "";
-
- if (start.node == end.node)
- return h.textAfter(start.node).slice(start.offset, end.offset);
-
- var text = [h.textAfter(start.node).slice(start.offset)];
- for (pos = h.nodeAfter(start.node); pos != end.node; pos = h.nodeAfter(pos))
- text.push(h.textAfter(pos));
- text.push(h.textAfter(end.node).slice(0, end.offset));
- return cleanText(text.join("\n"));
- },
-
- // Replace the selection with another piece of text.
- replaceSelection: function(text) {
- this.history.commit();
- var start = select.cursorPos(this.container, true),
- end = select.cursorPos(this.container, false);
- if (!start || !end) return false;
-
- end = this.replaceRange(start, end, text);
- select.setCursorPos(this.container, start, end);
- return true;
- },
-
- replaceRange: function(from, to, text) {
- var lines = asEditorLines(text);
- lines[0] = this.history.textAfter(from.node).slice(0, from.offset) + lines[0];
- var lastLine = lines[lines.length - 1];
- lines[lines.length - 1] = lastLine + this.history.textAfter(to.node).slice(to.offset);
- var end = this.history.nodeAfter(to.node);
- this.history.push(from.node, end, lines);
- return {node: this.history.nodeBefore(end),
- offset: lastLine.length};
- },
-
- getSearchCursor: function(string, fromCursor) {
- return new SearchCursor(this, string, fromCursor);
- },
-
- // Re-indent the whole buffer
- reindent: function() {
- if (this.container.firstChild)
- this.indentRegion(null, this.container.lastChild);
- },
-
- // Intercept enter and tab, and assign their new functions.
- keyDown: function(event) {
- // Don't scan when the user is typing.
- this.delayScanning();
- // Schedule a paren-highlight event, if configured.
- if (this.options.autoMatchParens)
- this.scheduleParenBlink();
-
- if (event.keyCode == 13) { // enter
- if (event.ctrlKey) {
- this.reparseBuffer();
- }
- else {
- select.insertNewlineAtCursor(this.win);
- this.indentAtCursor();
- select.scrollToCursor(this.container);
- }
- event.stop();
- }
- else if (event.keyCode == 9) { // tab
- this.handleTab();
- event.stop();
- }
- else if (event.ctrlKey) {
- if (event.keyCode == 90 || event.keyCode == 8) { // Z, backspace
- this.history.undo();
- event.stop();
- }
- else if (event.keyCode == 89) { // Y
- this.history.redo();
- event.stop();
- }
- else if (event.keyCode == 83 && this.options.saveFunction) { // S
- this.options.saveFunction();
- event.stop();
- }
- }
- },
-
- // Check for characters that should re-indent the current line,
- // and prevent Opera from handling enter and tab anyway.
- keyPress: function(event) {
- var electric = Editor.Parser.electricChars;
- // Hack for Opera, and Firefox on OS X, in which stopping a
- // keydown event does not prevent the associated keypress event
- // from happening, so we have to cancel enter and tab again
- // here.
- if (event.code == 13 || event.code == 9)
- event.stop();
- else if ((event.character == "[" || event.character == "]") && event.ctrlKey)
- event.stop(), this.blinkParens();
- else if (electric && electric.indexOf(event.character) != -1)
- this.parent.setTimeout(method(this, "indentAtCursor"), 0);
- },
-
- // Mark the node at the cursor dirty when a non-safe key is
- // released.
- keyUp: function(event) {
- if (internetExplorer)
- this.container.createTextRange().execCommand("unlink");
-
- if (!isSafeKey(event.keyCode))
- this.markCursorDirty();
- },
-
- // Indent the line following a given <br>, or null for the first
- // line. If given a <br> element, this must have been highlighted
- // so that it has an indentation method. Returns the whitespace
- // element that has been modified or created (if any).
- indentLineAfter: function(start) {
- // whiteSpace is the whitespace span at the start of the line,
- // or null if there is no such node.
- var whiteSpace = start ? start.nextSibling : this.container.firstChild;
- if (whiteSpace && !hasClass(whiteSpace, "whitespace"))
- whiteSpace = null;
-
- // Sometimes the start of the line can influence the correct
- // indentation, so we retrieve it.
- var firstText = whiteSpace ? whiteSpace.nextSibling : (start ? start.nextSibling : this.container.firstChild);
- var nextChars = (start && firstText && firstText.currentText) ? firstText.currentText : "";
-
- // Ask the lexical context for the correct indentation, and
- // compute how much this differs from the current indentation.
- var indent = start ? start.indentation(nextChars) : 0;
- var indentDiff = indent - (whiteSpace ? whiteSpace.currentText.length : 0);
-
- // If there is too much, this is just a matter of shrinking a span.
- if (indentDiff < 0) {
- if (indent == 0) {
- removeElement(whiteSpace);
- whiteSpace = null;
- }
- else {
- whiteSpace.currentText = safeWhiteSpace(indent);
- whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
- }
- }
- // Not enough...
- else if (indentDiff > 0) {
- // If there is whitespace, we grow it.
- if (whiteSpace) {
- whiteSpace.currentText = safeWhiteSpace(indent);
- whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
- }
- // Otherwise, we have to add a new whitespace node.
- else {
- whiteSpace = this.doc.createElement("SPAN");
- whiteSpace.className = "part whitespace";
- whiteSpace.appendChild(this.doc.createTextNode(safeWhiteSpace(indent)));
- if (start)
- insertAfter(whiteSpace, start);
- else
- this.container.insertBefore(whiteSpace, this.container.firstChild);
- }
- }
- return whiteSpace;
- },
-
- // Re-highlight the selected part of the document.
- highlightAtCursor: function() {
- var pos = select.selectionTopNode(this.container, true);
- var to = select.selectionTopNode(this.container, false);
- if (pos === false || !to) return;
- // Skip one node ahead to make sure the cursor itself is
- // *inside* a highlighted line.
- if (to.nextSibling) to = to.nextSibling;
-
- var sel = select.markSelection(this.win);
- var toIsText = to.nodeType == 3;
- if (!toIsText) to.dirty = true;
-
- // Highlight lines as long as to is in the document and dirty.
- while (to.parentNode == this.container && (toIsText || to.dirty)) {
- var result = this.highlight(pos, 1, true);
- if (result) pos = result.node;
- if (!result || result.left) break;
- }
- select.selectMarked(sel);
- },
-
- // When tab is pressed with text selected, the whole selection is
- // re-indented, when nothing is selected, the line with the cursor
- // is re-indented.
- handleTab: function() {
- if (this.options.dumbTabs) {
- select.insertTabAtCursor(this.win);
- }
- else {
- var start = select.selectionTopNode(this.container, true),
- end = select.selectionTopNode(this.container, false);
- if (start === false || end === false) return;
-
- if (start == end)
- this.indentAtCursor();
- else
- this.indentRegion(start, end);
- }
- },
-
- // Delay (or initiate) the next paren blink event.
- scheduleParenBlink: function() {
- if (this.parenEvent) this.parent.clearTimeout(this.parenEvent);
- this.parenEvent = this.parent.setTimeout(method(this, "blinkParens"), 300);
- },
-
- // Take the token before the cursor. If it contains a character in
- // '()[]{}', search for the matching paren/brace/bracket, and
- // highlight them in green for a moment, or red if no proper match
- // was found.
- blinkParens: function() {
- // Clear the event property.
- if (this.parenEvent) this.parent.clearTimeout(this.parenEvent);
- this.parenEvent = null;
-
- // Extract a 'paren' from a piece of text.
- function paren(node) {
- if (node.currentText) {
- var match = node.currentText.match(/^[\s\u00a0]*([\(\)\[\]{}])[\s\u00a0]*$/);
- return match && match[1];
- }
- }
- // Determine the direction a paren is facing.
- function forward(ch) {
- return /[\(\[\{]/.test(ch);
- }
-
- this.highlightAtCursor();
- var cursor = select.selectionTopNode(this.container, true), ch, self = this;
- if (!cursor || !(ch = paren(cursor))) return;
- // We only look for tokens with the same className.
- var className = cursor.className, dir = forward(ch), match = matching[ch];
-
- // Since parts of the document might not have been properly
- // highlighted, and it is hard to know in advance which part we
- // have to scan, we just try, and when we find dirty nodes we
- // abort, parse them, and re-try.
- function tryFindMatch() {
- var stack = [], ch, ok = true;;
- for (var runner = cursor; runner; runner = dir ? runner.nextSibling : runner.previousSibling) {
- if (runner.className == className && runner.nodeName == "SPAN" && (ch = paren(runner))) {
- if (forward(ch) == dir)
- stack.push(ch);
- else if (!stack.length)
- ok = false;
- else if (stack.pop() != matching[ch])
- ok = false;
- if (!stack.length) break;
- }
- else if (runner.dirty || runner.nodeName != "SPAN" && runner.nodeName != "BR") {
- return {node: runner, status: "dirty"};
- }
- }
- return {node: runner, status: runner && ok};
- }
- // Temporarily give the relevant nodes a colour.
- function blink(node, ok) {
- node.style.fontWeight = "bold";
- node.style.color = ok ? "#8F8" : "#F88";
- self.parent.setTimeout(function() {node.style.fontWeight = ""; node.style.color = "";}, 500);
- }
-
- while (true) {
- var found = tryFindMatch();
- if (found.status == "dirty") {
- this.highlight(found.node, 1);
- // Needed because in some corner cases a highlight does not
- // reach a node.
- found.node.dirty = false;
- continue;
- }
- else {
- blink(cursor, found.status);
- if (found.node) blink(found.node, found.status);
- break;
- }
- }
- },
-
- // Adjust the amount of whitespace at the start of the line that
- // the cursor is on so that it is indented properly.
- indentAtCursor: function() {
- if (!this.container.firstChild) return;
- // The line has to have up-to-date lexical information, so we
- // highlight it first.
- this.highlightAtCursor();
- var cursor = select.selectionTopNode(this.container, false);
- // If we couldn't determine the place of the cursor,
- // there's nothing to indent.
- if (cursor === false)
- return;
- var lineStart = startOfLine(cursor);
- var whiteSpace = this.indentLineAfter(lineStart);
- if (cursor == lineStart && whiteSpace)
- cursor = whiteSpace;
- // This means the indentation has probably messed up the cursor.
- if (cursor == whiteSpace)
- select.focusAfterNode(cursor, this.container);
- },
-
- // Indent all lines whose start falls inside of the current
- // selection.
- indentRegion: function(current, end) {
- var sel = select.markSelection(this.win);
- if (!current)
- this.indentLineAfter(current);
- else
- current = startOfLine(current.previousSibling);
- end = startOfLine(end);
-
- while (true) {
- var result = this.highlight(current, 1);
- var next = result ? result.node : null;
-
- while (current != next)
- current = current ? current.nextSibling : this.container.firstChild;
- if (next)
- this.indentLineAfter(next);
- if (current == end)
- break;
- }
- select.selectMarked(sel);
- },
-
- // Find the node that the cursor is in, mark it as dirty, and make
- // sure a highlight pass is scheduled.
- markCursorDirty: function() {
- var cursor = select.selectionTopNode(this.container, false);
- if (cursor !== false && this.container.firstChild) {
- this.scheduleHighlight();
- this.addDirtyNode(cursor || this.container.firstChild);
- }
- },
-
- reparseBuffer: function() {
- forEach(this.container.childNodes, function(node) {node.dirty = true;});
- if (this.container.firstChild)
- this.addDirtyNode(this.container.firstChild);
- },
-
- // Add a node to the set of dirty nodes, if it isn't already in
- // there.
- addDirtyNode: function(node) {
- node = node || this.container.firstChild;
- if (!node) return;
-
- for (var i = 0; i < this.dirty.length; i++)
- if (this.dirty[i] == node) return;
-
- if (node.nodeType != 3)
- node.dirty = true;
- this.dirty.push(node);
- },
-
- // Cause a highlight pass to happen in options.passDelay
- // milliseconds. Clear the existing timeout, if one exists. This
- // way, the passes do not happen while the user is typing, and
- // should as unobtrusive as possible.
- scheduleHighlight: function() {
- // Timeouts are routed through the parent window, because on
- // some browsers designMode windows do not fire timeouts.
- var self = this;
- this.parent.clearTimeout(this.highlightTimeout);
- this.highlightTimeout = this.parent.setTimeout(function(){self.highlightDirty();}, this.options.passDelay);
- },
-
- // Fetch one dirty node, and remove it from the dirty set.
- getDirtyNode: function() {
- while (this.dirty.length > 0) {
- var found = this.dirty.pop();
- // IE8 sometimes throws an unexplainable 'invalid argument'
- // exception for found.parentNode
- try {
- // If the node has been coloured in the meantime, or is no
- // longer in the document, it should not be returned.
- if ((found.dirty || found.nodeType == 3) && found.parentNode)
- return found;
- } catch (e) {}
- }
- return null;
- },
-
- // Pick dirty nodes, and highlight them, until
- // options.linesPerPass lines have been highlighted. The highlight
- // method will continue to next lines as long as it finds dirty
- // nodes. It returns an object indicating the amount of lines
- // left, and information about the place where it stopped. If
- // there are dirty nodes left after this function has spent all
- // its lines, it shedules another highlight to finish the job.
- highlightDirty: function(force) {
- var lines = force ? Infinity : this.options.linesPerPass;
- var sel = select.markSelection(this.win);
- var start;
- while (lines > 0 && (start = this.getDirtyNode())){
- var result = this.highlight(start, lines);
- if (result) {
- lines = result.left;
- if (result.node && result.dirty)
- this.addDirtyNode(result.node);
- }
- }
- select.selectMarked(sel);
- if (start)
- this.scheduleHighlight();
- return this.dirty.length == 0;
- },
-
- // Creates a function that, when called through a timeout, will
- // continuously re-parse the document.
- documentScanner: function(linesPer) {
- var self = this, pos = null;
- return function() {
- // If the current node is no longer in the document... oh
- // well, we start over.
- if (pos && pos.parentNode != self.container)
- pos = null;
- var sel = select.markSelection(self.win);
- var result = self.highlight(pos, linesPer, true);
- select.selectMarked(sel);
- pos = result ? (result.node && result.node.nextSibling) : null;
- self.delayScanning();
- };
- },
-
- // Starts the continuous scanning process for this document after
- // a given interval.
- delayScanning: function() {
- if (this.scanner) {
- this.parent.clearTimeout(this.documentScan);
- this.documentScan = this.parent.setTimeout(this.scanner, this.options.continuousScanning);
- }
- },
-
- // The function that does the actual highlighting/colouring (with
- // help from the parser and the DOM normalizer). Its interface is
- // rather overcomplicated, because it is used in different
- // situations: ensuring that a certain line is highlighted, or
- // highlighting up to X lines starting from a certain point. The
- // 'from' argument gives the node at which it should start. If
- // this is null, it will start at the beginning of the frame. When
- // a number of lines is given with the 'lines' argument, it will
- // colour no more than that amount. If at any time it comes across
- // a 'clean' line (no dirty nodes), it will stop, except when
- // 'cleanLines' is true.
- highlight: function(from, lines, cleanLines){
- var container = this.container, self = this;
-
- if (!container.firstChild)
- return;
- // Backtrack to the first node before from that has a partial
- // parse stored.
- while (from && (!from.parserFromHere || from.dirty))
- from = from.previousSibling;
- // If we are at the end of the document, do nothing.
- if (from && !from.nextSibling)
- return;
-
- // Check whether a part (<span> node) and the corresponding token
- // match.
- function correctPart(token, part){
- return !part.reduced && part.currentText == token.value && part.className == "part " + token.style;
- }
- // Shorten the text associated with a part by chopping off
- // characters from the front. Note that only the currentText
- // property gets changed. For efficiency reasons, we leave the
- // nodeValue alone -- we set the reduced flag to indicate that
- // this part must be replaced.
- function shortenPart(part, minus){
- part.currentText = part.currentText.substring(minus);
- part.reduced = true;
- }
- // Create a part corresponding to a given token.
- function tokenPart(token){
- var part = self.doc.createElement("SPAN");
- part.className = "part " + token.style;
- part.appendChild(self.doc.createTextNode(token.value));
- part.currentText = token.value;
- return part;
- }
-
- // Get the token stream. If from is null, we start with a new
- // parser from the start of the frame, otherwise a partial parse
- // is resumed.
- var traversal = traverseDOM(from ? from.nextSibling : container.firstChild),
- stream = stringStream(traversal),
- parsed = from ? from.parserFromHere(stream) : Editor.Parser.make(stream);
-
- // parts is an interface to make it possible to 'delay' fetching
- // the next DOM node until we are completely done with the one
- // before it. This is necessary because often the next node is
- // not yet available when we want to proceed past the current
- // one.
- var parts = {
- current: null,
- // Fetch current node.
- get: function(){
- if (!this.current)
- this.current = traversal.nodes.shift();
- return this.current;
- },
- // Advance to the next part (do not fetch it yet).
- next: function(){
- this.current = null;
- },
- // Remove the current part from the DOM tree, and move to the
- // next.
- remove: function(){
- container.removeChild(this.get());
- this.current = null;
- },
- // Advance to the next part that is not empty, discarding empty
- // parts.
- getNonEmpty: function(){
- var part = this.get();
- // Allow empty nodes when they are alone on a line, needed
- // for the FF cursor bug workaround (see select.js,
- // insertNewlineAtCursor).
- while (part && part.nodeName == "SPAN" && part.currentText == ""){
- var old = part;
- this.remove();
- part = this.get();
- // Adjust selection information, if any. See select.js for details.
- select.replaceSelection(old.firstChild, part.firstChild || part, 0, 0);
- }
- return part;
- }
- };
-
- var lineDirty = false, lineNodes = 0;
-
- // This forEach loops over the tokens from the parsed stream, and
- // at the same time uses the parts object to proceed through the
- // corresponding DOM nodes.
- forEach(parsed, function(token){
- var part = parts.getNonEmpty();
-
- if (token.value == "\n"){
- // The idea of the two streams actually staying synchronized
- // is such a long shot that we explicitly check.
- if (part.nodeName != "BR")
- throw "Parser out of sync. Expected BR.";
-
- if (part.dirty || !part.indentation) lineDirty = true;
- if (lineDirty) self.history.touch(from);
- from = part;
-
- // Every <br> gets a copy of the parser state and a lexical
- // context assigned to it. The first is used to be able to
- // later resume parsing from this point, the second is used
- // for indentation.
- part.parserFromHere = parsed.copy();
- part.indentation = token.indentation;
- part.dirty = false;
- // A clean line with more than one node means we are done.
- // Throwing a StopIteration is the way to break out of a
- // MochiKit forEach loop.
- if ((lines !== undefined && --lines <= 0) || (!lineDirty && lineNodes > 1 && !cleanLines))
- throw StopIteration;
- lineDirty = false; lineNodes = 0;
- parts.next();
- }
- else {
- if (part.nodeName != "SPAN")
- throw "Parser out of sync. Expected SPAN.";
- if (part.dirty)
- lineDirty = true;
- lineNodes++;
-
- // If the part matches the token, we can leave it alone.
- if (correctPart(token, part)){
- part.dirty = false;
- parts.next();
- }
- // Otherwise, we have to fix it.
- else {
- lineDirty = true;
- // Insert the correct part.
- var newPart = tokenPart(token);
- container.insertBefore(newPart, part);
- var tokensize = token.value.length;
- var offset = 0;
- // Eat up parts until the text for this token has been
- // removed, adjusting the stored selection info (see
- // select.js) in the process.
- while (tokensize > 0) {
- part = parts.get();
- var partsize = part.currentText.length;
- select.replaceSelection(part.firstChild, newPart.firstChild, tokensize, offset);
- if (partsize > tokensize){
- shortenPart(part, tokensize);
- tokensize = 0;
- }
- else {
- tokensize -= partsize;
- offset += partsize;
- parts.remove();
- }
- }
- }
- }
- });
- if (lineDirty) this.history.touch(from);
-
- // The function returns some status information that is used by
- // hightlightDirty to determine whether and where it has to
- // continue.
- return {left: lines,
- node: parts.get(),
- dirty: lineDirty};
- }
- };
-
- return Editor;
-})();
-
-addEventHandler(window, "load", function() {
- var CodeMirror = window.frameElement.CodeMirror;
- CodeMirror.editor = new Editor(CodeMirror.options);
- if (CodeMirror.options.initCallback) {
- this.parent.setTimeout(function(){
- CodeMirror.options.initCallback(CodeMirror);
- }, 0);
- }
-});
diff --git a/o3d/samples/third_party/codemirror/js/mirrorframe.js b/o3d/samples/third_party/codemirror/js/mirrorframe.js
deleted file mode 100644
index 56a6c42..0000000
--- a/o3d/samples/third_party/codemirror/js/mirrorframe.js
+++ /dev/null
@@ -1,83 +0,0 @@
-/* Demonstration of embedding CodeMirror in a bigger application. The
- * interface defined here is a mess of prompts and confirms, and
- * should probably not be used in a real project.
- */
-
-function MirrorFrame(place, options) {
- this.home = document.createElement("DIV");
- if (place.appendChild)
- place.appendChild(this.home);
- else
- place(this.home);
-
- var self = this;
- function makeButton(name, action) {
- var button = document.createElement("INPUT");
- button.type = "button";
- button.value = name;
- self.home.appendChild(button);
- button.onclick = function(){self[action].call(self);};
- }
-
- makeButton("Search", "search");
- makeButton("Replace", "replace");
- makeButton("Current line", "line");
- makeButton("Jump to line", "jump");
- makeButton("Insert constructor", "macro");
- makeButton("Indent all", "reindent");
-
- this.mirror = new CodeMirror(this.home, options);
-}
-
-MirrorFrame.prototype = {
- search: function() {
- var text = prompt("Enter search term:", "");
- if (!text) return;
-
- var first = true;
- do {
- var cursor = this.mirror.getSearchCursor(text, first);
- first = false;
- while (cursor.findNext()) {
- cursor.select();
- if (!confirm("Search again?"))
- return;
- }
- } while (confirm("End of document reached. Start over?"));
- },
-
- replace: function() {
- // This is a replace-all, but it is possible to implement a
- // prompting replace.
- var from = prompt("Enter search string:", ""), to;
- if (from) to = prompt("What should it be replaced with?", "");
- if (!to) return;
-
- var cursor = this.mirror.getSearchCursor(from, false);
- while (cursor.findNext())
- cursor.replace(to);
- },
-
- jump: function() {
- var line = prompt("Jump to line:", "");
- if (line && !isNaN(Number(line)))
- this.mirror.jumpToLine(Number(line));
- },
-
- line: function() {
- alert("The cursor is currently at line " + this.mirror.currentLine());
- this.mirror.focus();
- },
-
- macro: function() {
- var name = prompt("Name your constructor:", "");
- if (name) {
- if (!this.mirror.replaceSelection("function " + name + "() {\n \n}\n\n" + name + ".prototype = {\n \n};\n", true))
- alert("Place the cursor in the document first.");
- }
- },
-
- reindent: function() {
- this.mirror.reindent();
- }
-};
diff --git a/o3d/samples/third_party/codemirror/js/parsecss.js b/o3d/samples/third_party/codemirror/js/parsecss.js
deleted file mode 100644
index a49a8b0..0000000
--- a/o3d/samples/third_party/codemirror/js/parsecss.js
+++ /dev/null
@@ -1,155 +0,0 @@
-/* Simple parser for CSS */
-
-var CSSParser = Editor.Parser = (function() {
- var tokenizeCSS = (function() {
- function normal(source, setState) {
- var ch = source.next();
- if (ch == "@") {
- source.nextWhile(matcher(/\w/));
- return "css-at";
- }
- else if (ch == "/" && source.equals("*")) {
- setState(inCComment);
- return null;
- }
- else if (ch == "<" && source.equals("!")) {
- setState(inSGMLComment);
- return null;
- }
- else if (ch == "=") {
- return "css-compare";
- }
- else if (source.equals("=") && (ch == "~" || ch == "|")) {
- source.next();
- return "css-compare";
- }
- else if (ch == "\"" || ch == "'") {
- setState(inString(ch));
- return null;
- }
- else if (ch == "#") {
- source.nextWhile(matcher(/\w/));
- return "css-hash";
- }
- else if (ch == "!") {
- source.nextWhile(matcher(/[ \t]/));
- source.nextWhile(matcher(/\w/));
- return "css-important";
- }
- else if (/\d/.test(ch)) {
- source.nextWhile(matcher(/[\w.%]/));
- return "css-unit";
- }
- else if (/[,.+>*\/]/.test(ch)) {
- return "css-select-op";
- }
- else if (/[;{}:\[\]]/.test(ch)) {
- return "css-punctuation";
- }
- else {
- source.nextWhile(matcher(/[\w\\\-_]/));
- return "css-identifier";
- }
- }
-
- function inCComment(source, setState) {
- var maybeEnd = false;
- while (!source.endOfLine()) {
- var ch = source.next();
- if (maybeEnd && ch == "/") {
- setState(normal);
- break;
- }
- maybeEnd = (ch == "*");
- }
- return "css-comment";
- }
-
- function inSGMLComment(source, setState) {
- var dashes = 0;
- while (!source.endOfLine()) {
- var ch = source.next();
- if (dashes >= 2 && ch == ">") {
- setState(normal);
- break;
- }
- dashes = (ch == "-") ? dashes + 1 : 0;
- }
- return "css-comment";
- }
-
- function inString(quote) {
- return function(source, setState) {
- var escaped = false;
- while (!source.endOfLine()) {
- var ch = source.next();
- if (ch == quote && !escaped)
- break;
- escaped = ch == "\\";
- }
- if (!escaped)
- setState(normal);
- return "css-string";
- };
- }
-
- return function(source, startState) {
- return tokenizer(source, startState || normal);
- };
- })();
-
- function indentCSS(inBraces, inRule, base) {
- return function(nextChars) {
- if (!inBraces || /^\}/.test(nextChars)) return base;
- else if (inRule) return base + 4;
- else return base + 2;
- };
- }
-
- // This is a very simplistic parser -- since CSS does not really
- // nest, it works acceptably well, but some nicer colouroing could
- // be provided with a more complicated parser.
- function parseCSS(source, basecolumn) {
- basecolumn = basecolumn || 0;
- var tokens = tokenizeCSS(source);
- var inBraces = false, inRule = false;
-
- var iter = {
- next: function() {
- var token = tokens.next(), style = token.style, content = token.content;
-
- if (style == "css-identifier" && inRule)
- token.style = "css-value";
- if (style == "css-hash")
- token.style = inRule ? "css-colorcode" : "css-identifier";
-
- if (content == "\n")
- token.indentation = indentCSS(inBraces, inRule, basecolumn);
-
- if (content == "{")
- inBraces = true;
- else if (content == "}")
- inBraces = inRule = false;
- else if (inBraces && content == ";")
- inRule = false;
- else if (inBraces && style != "css-comment" && style != "whitespace")
- inRule = true;
-
- return token;
- },
-
- copy: function() {
- var _inBraces = inBraces, _inRule = inRule, _tokenState = tokens.state;
- return function(source) {
- tokens = tokenizeCSS(source, _tokenState);
- inBraces = _inBraces;
- inRule = _inRule;
- return iter;
- };
- }
- };
- return iter;
- }
-
- return {make: parseCSS, electricChars: "}"};
-})();
diff --git a/o3d/samples/third_party/codemirror/js/parsehtmlmixed.js b/o3d/samples/third_party/codemirror/js/parsehtmlmixed.js
deleted file mode 100644
index f093b63..0000000
--- a/o3d/samples/third_party/codemirror/js/parsehtmlmixed.js
+++ /dev/null
@@ -1,66 +0,0 @@
-var HTMLMixedParser = Editor.Parser = (function() {
- if (!(CSSParser && JSParser && XMLParser))
- throw new Error("CSS, JS, and XML parsers must be loaded for HTML mixed mode to work.");
- XMLParser.configure({useHTMLKludges: true});
-
- function stringAhead(stream, string) {
- stream.nextWhile(matcher(/[\s\u00a0]/));
- var found = stream.matches(string, false);
- stream.reset();
- return found;
- }
-
- function parseMixed(stream) {
- var htmlParser = XMLParser.make(stream), localParser = null, inTag = false;
- var iter = {next: top, copy: copy};
-
- function top() {
- var token = htmlParser.next();
- if (token.content == "<")
- inTag = true;
- else if (token.style == "xml-tagname" && inTag === true)
- inTag = token.content.toLowerCase();
- else if (token.content == ">") {
- if (inTag == "script")
- iter.next = local(JSParser, "</script");
- else if (inTag == "style")
- iter.next = local(CSSParser, "</style");
- inTag = false;
- }
- return token;
- }
- function local(parser, tag) {
- localParser = parser.make(stream, htmlParser.indentation() + 2);
- return function() {
- if (stringAhead(stream, tag)) {
- localParser = null;
- iter.next = top;
- return top();
- }
- var token = localParser.next();
- var lt = token.value.lastIndexOf("<"), sz = Math.min(token.value.length - lt, tag.length);
- if (lt != -1 && token.value.slice(lt, lt + sz).toLowerCase() == tag.slice(0, sz) && stringAhead(stream, tag.slice(sz))) {
- stream.push(token.value.slice(lt));
- token.value = token.value.slice(0, lt);
- }
- return token;
- };
- }
-
- function copy() {
- var _html = htmlParser.copy(), _local = localParser && localParser.copy(),
- _next = iter.next, _inTag = inTag;
- return function(_stream) {
- stream = _stream;
- htmlParser = _html(_stream);
- localParser = _local && _local(_stream);
- iter.next = _next;
- inTag = _inTag;
- return iter;
- };
- }
- return iter;
- }
-
- return {make: parseMixed, electricChars: "{}/"};
-})();
diff --git a/o3d/samples/third_party/codemirror/js/parsejavascript.js b/o3d/samples/third_party/codemirror/js/parsejavascript.js
deleted file mode 100644
index 412977f..0000000
--- a/o3d/samples/third_party/codemirror/js/parsejavascript.js
+++ /dev/null
@@ -1,322 +0,0 @@
-/* Parse function for JavaScript. Makes use of the tokenizer from
- * tokenizejavascript.js. Note that your parsers do not have to be
- * this complicated -- if you don't want to recognize local variables,
- * in many languages it is enough to just look for braces, semicolons,
- * parentheses, etc, and know when you are inside a string or comment.
- *
- * See manual.html for more info about the parser interface.
- */
-
-var JSParser = Editor.Parser = (function() {
- // Token types that can be considered to be atoms.
- var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
- // Constructor for the lexical context objects.
- function JSLexical(indented, column, type, align, prev) {
- // indentation at start of this line
- this.indented = indented;
- // column at which this scope was opened
- this.column = column;
- // type of scope ('vardef', 'stat' (statement), 'form' (special form), '[', '{', or '(')
- this.type = type;
- // '[', '{', or '(' blocks that have any text after their opening
- // character are said to be 'aligned' -- any lines below are
- // indented all the way to the opening character.
- if (align != null)
- this.align = align;
- // Parent scope, if any.
- this.prev = prev;
- }
- // My favourite JavaScript indentation rules.
- function indentJS(lexical) {
- return function(firstChars) {
- var firstChar = firstChars && firstChars.charAt(0);
- var closing = firstChar == lexical.type;
- if (lexical.type == "vardef")
- return lexical.indented + 4;
- else if (lexical.type == "form" && firstChar == "{")
- return lexical.indented;
- else if (lexical.type == "stat" || lexical.type == "form")
- return lexical.indented + 2;
- else if (lexical.align)
- return lexical.column - (closing ? 1 : 0);
- else
- return lexical.indented + (closing ? 0 : 2);
- };
- }
-
- // The parser-iterator-producing function itself.
- function parseJS(input, basecolumn) {
- // Wrap the input in a token stream
- var tokens = tokenizeJavaScript(input);
- // The parser state. cc is a stack of actions that have to be
- // performed to finish the current statement. For example we might
- // know that we still need to find a closing parenthesis and a
- // semicolon. Actions at the end of the stack go first. It is
- // initialized with an infinitely looping action that consumes
- // whole statements.
- var cc = [statements];
- // Context contains information about the current local scope, the
- // variables defined in that, and the scopes above it.
- var context = null;
- // The lexical scope, used mostly for indentation.
- var lexical = new JSLexical((basecolumn || 0) - 2, 0, "block", false);
- // Current column, and the indentation at the start of the current
- // line. Used to create lexical scope objects.
- var column = 0;
- var indented = 0;
- // Variables which are used by the mark, cont, and pass functions
- // below to communicate with the driver loop in the 'next'
- // function.
- var consume, marked;
-
- // The iterator object.
- var parser = {next: next, copy: copy};
-
- function next(){
- // Start by performing any 'lexical' actions (adjusting the
- // lexical variable), or the operations below will be working
- // with the wrong lexical state.
- while(cc[cc.length - 1].lex)
- cc.pop()();
-
- // Fetch a token.
- var token = tokens.next();
-
- // Adjust column and indented.
- if (token.type == "whitespace" && column == 0)
- indented = token.value.length;
- column += token.value.length;
- if (token.content == "\n"){
- indented = column = 0;
- // If the lexical scope's align property is still undefined at
- // the end of the line, it is an un-aligned scope.
- if (!("align" in lexical))
- lexical.align = false;
- // Newline tokens get an indentation function associated with
- // them.
- token.indentation = indentJS(lexical);
- }
- // No more processing for meaningless tokens.
- if (token.type == "whitespace" || token.type == "comment")
- return token;
- // When a meaningful token is found and the lexical scope's
- // align is undefined, it is an aligned scope.
- if (!("align" in lexical))
- lexical.align = true;
-
- // Execute actions until one 'consumes' the token and we can
- // return it. Marked is used to
- while(true){
- consume = marked = false;
- // Take and execute the topmost action.
- cc.pop()(token.type, token.content);
- if (consume){
- // Marked is used to change the style of the current token.
- if (marked)
- token.style = marked;
- // Here we differentiate between local and global variables.
- else if (token.type == "variable" && inScope(token.content))
- token.style = "js-localvariable";
- return token;
- }
- }
- }
-
- // This makes a copy of the parser state. It stores all the
- // stateful variables in a closure, and returns a function that
- // will restore them when called with a new input stream. Note
- // that the cc array has to be copied, because it is contantly
- // being modified. Lexical objects are not mutated, and context
- // objects are not mutated in a harmful way, so they can be shared
- // between runs of the parser.
- function copy(){
- var _context = context, _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state;
-
- return function(input){
- context = _context;
- lexical = _lexical;
- cc = _cc.concat([]); // copies the array
- column = indented = 0;
- tokens = tokenizeJavaScript(input, _tokenState);
- return parser;
- };
- }
-
- // Helper function for pushing a number of actions onto the cc
- // stack in reverse order.
- function push(fs){
- for (var i = fs.length - 1; i >= 0; i--)
- cc.push(fs[i]);
- }
- // cont and pass are used by the action functions to add other
- // actions to the stack. cont will cause the current token to be
- // consumed, pass will leave it for the next action.
- function cont(){
- push(arguments);
- consume = true;
- }
- function pass(){
- push(arguments);
- consume = false;
- }
- // Used to change the style of the current token.
- function mark(style){
- marked = style;
- }
-
- // Push a new scope. Will automatically link the the current
- // scope.
- function pushcontext(){
- context = {prev: context, vars: {"this": true, "arguments": true}};
- }
- // Pop off the current scope.
- function popcontext(){
- context = context.prev;
- }
- // Register a variable in the current scope.
- function register(varname){
- if (context){
- mark("js-variabledef");
- context.vars[varname] = true;
- }
- }
- // Check whether a variable is defined in the current scope.
- function inScope(varname){
- var cursor = context;
- while (cursor) {
- if (cursor.vars[varname])
- return true;
- cursor = cursor.prev;
- }
- return false;
- }
-
- // Push a new lexical context of the given type.
- function pushlex(type){
- var result = function(){
- lexical = new JSLexical(indented, column, type, null, lexical)
- };
- result.lex = true;
- return result;
- }
- // Pop off the current lexical context.
- function poplex(){
- lexical = lexical.prev;
- }
- poplex.lex = true;
- // The 'lex' flag on these actions is used by the 'next' function
- // to know they can (and have to) be ran before moving on to the
- // next token.
-
- // Creates an action that discards tokens until it finds one of
- // the given type.
- function expect(wanted){
- return function(type){
- if (type == wanted) cont();
- else cont(arguments.callee);
- };
- }
-
- // Looks for a statement, and then calls itself.
- function statements(type){
- return pass(statement, statements);
- }
- // Dispatches various types of statements based on the type of the
- // current token.
- function statement(type){
- if (type == "var") cont(pushlex("vardef"), vardef1, expect(";"), poplex);
- else if (type == "keyword a") cont(pushlex("form"), expression, statement, poplex);
- else if (type == "keyword b") cont(pushlex("form"), statement, poplex);
- else if (type == "{") cont(pushlex("}"), block, poplex);
- else if (type == "function") cont(functiondef);
- else if (type == "for") cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), poplex, statement, poplex);
- else if (type == "variable") cont(pushlex("stat"), maybelabel);
- else if (type == "case") cont(expression, expect(":"));
- else if (type == "catch") cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), statement, poplex, popcontext);
- else pass(pushlex("stat"), expression, expect(";"), poplex);
- }
- // Dispatch expression types.
- function expression(type){
- if (atomicTypes.hasOwnProperty(type)) cont(maybeoperator);
- else if (type == "function") cont(functiondef);
- else if (type == "keyword c") cont(expression);
- else if (type == "(") cont(pushlex(")"), expression, expect(")"), poplex);
- else if (type == "operator") cont(expression);
- else if (type == "[") cont(pushlex("]"), commasep(expression), expect("]"), poplex);
- else if (type == "{") cont(pushlex("}"), commasep(objprop), expect("}"), poplex);
- }
- // Called for places where operators, function calls, or
- // subscripts are valid. Will skip on to the next action if none
- // is found.
- function maybeoperator(type){
- if (type == "operator") cont(expression);
- else if (type == "(") cont(pushlex(")"), expression, commasep(expression), expect(")"), poplex);
- else if (type == ".") cont(property, maybeoperator);
- else if (type == "[") cont(pushlex("]"), expression, expect("]"), poplex);
- }
- // When a statement starts with a variable name, it might be a
- // label. If no colon follows, it's a regular statement.
- function maybelabel(type){
- if (type == ":") cont(poplex, statement);
- else pass(maybeoperator, expect(";"), poplex);
- }
- // Property names need to have their style adjusted -- the
- // tokenizer think they are variables.
- function property(type){
- if (type == "variable") {mark("js-property"); cont();}
- }
- // This parses a property and its value in an object literal.
- function objprop(type){
- if (type == "variable") mark("js-property");
- if (atomicTypes.hasOwnProperty(type)) cont(expect(":"), expression);
- }
- // Parses a comma-separated list of the things that are recognized
- // by the 'what' argument.
- function commasep(what){
- function proceed(type) {
- if (type == ",") cont(what, proceed);
- };
- return function() {
- pass(what, proceed);
- };
- }
- // Look for statements until a closing brace is found.
- function block(type){
- if (type == "}") cont();
- else pass(statement, block);
- }
- // Variable definitions are split into two actions -- 1 looks for
- // a name or the end of the definition, 2 looks for an '=' sign or
- // a comma.
- function vardef1(type, value){
- if (type == "variable"){register(value); cont(vardef2);}
- else cont();
- }
- function vardef2(type){
- if (type == "operator") cont(expression, vardef2);
- else if (type == ",") cont(vardef1);
- }
- // For loops.
- function forspec1(type, value){
- if (type == "var") cont(vardef1, forspec2);
- else cont(expression, forspec2);
- }
- function forspec2(type){
- if (type == ",") cont(forspec1);
- if (type == ";") cont(expression, expect(";"), expression);
- }
- // A function definition creates a new context, and the variables
- // in its argument list have to be added to this context.
- function functiondef(type, value){
- if (type == "variable"){register(value); cont(functiondef);}
- else if (type == "(") cont(pushcontext, commasep(funarg), expect(")"), statement, popcontext);
- }
- function funarg(type, value){
- if (type == "variable"){register(value); cont();}
- }
-
- return parser;
- }
-
- return {make: parseJS, electricChars: "{}"};
-})();
diff --git a/o3d/samples/third_party/codemirror/js/parsesparql.js b/o3d/samples/third_party/codemirror/js/parsesparql.js
deleted file mode 100644
index f1414d8..0000000
--- a/o3d/samples/third_party/codemirror/js/parsesparql.js
+++ /dev/null
@@ -1,162 +0,0 @@
-Editor.Parser = (function() {
- function wordRegexp(words) {
- return new RegExp("^(?:" + words.join("|") + ")$", "i");
- }
- var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri",
- "isblank", "isliteral", "union", "a"]);
- var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe",
- "ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional",
- "graph", "by", "asc", "desc", ]);
- var operatorChars = /[*+\-<>=&|]/;
-
- var tokenizeSparql = (function() {
- function normal(source, setState) {
- var ch = source.next();
- if (ch == "$" || ch == "?") {
- source.nextWhile(matcher(/[\w\d]/));
- return "sp-var";
- }
- else if (ch == "<" && !source.applies(matcher(/[\s\u00a0=]/))) {
- source.nextWhile(matcher(/[^\s\u00a0>]/));
- if (source.equals(">")) source.next();
- return "sp-uri";
- }
- else if (ch == "\"" || ch == "'") {
- setState(inLiteral(ch));
- return null;
- }
- else if (/[{}\(\),\.;\[\]]/.test(ch)) {
- return "sp-punc";
- }
- else if (ch == "#") {
- while (!source.endOfLine()) source.next();
- return "sp-comment";
- }
- else if (operatorChars.test(ch)) {
- source.nextWhile(matcher(operatorChars));
- return "sp-operator";
- }
- else if (ch == ":") {
- source.nextWhile(matcher(/[\w\d\._\-]/));
- return "sp-prefixed";
- }
- else {
- source.nextWhile(matcher(/[_\w\d]/));
- if (source.equals(":")) {
- source.next();
- source.nextWhile(matcher(/[\w\d_\-]/));
- return "sp-prefixed";
- }
- var word = source.get(), type;
- if (ops.test(word))
- type = "sp-operator";
- else if (keywords.test(word))
- type = "sp-keyword";
- else
- type = "sp-word";
- return {style: type, content: word};
- }
- }
-
- function inLiteral(quote) {
- return function(source, setState) {
- var escaped = false;
- while (!source.endOfLine()) {
- var ch = source.next();
- if (ch == quote && !escaped) {
- setState(normal);
- break;
- }
- escaped = ch == "\\";
- }
- return "sp-literal";
- };
- }
-
- return function(source, startState) {
- return tokenizer(source, startState || normal);
- };
- })();
-
- function indentSparql(context) {
- return function(nextChars) {
- var firstChar = nextChars && nextChars.charAt(0);
- if (/[\]\}]/.test(firstChar))
- while (context && context.type == "pattern") context = context.prev;
-
- var closing = context && firstChar == matching[context.type];
- if (!context)
- return 0;
- else if (context.type == "pattern")
- return context.col;
- else if (context.align)
- return context.col - (closing ? context.width : 0);
- else
- return context.indent + (closing ? 0 : 2);
- }
- }
-
- function parseSparql(source) {
- var tokens = tokenizeSparql(source);
- var context = null, indent = 0, col = 0;
- function pushContext(type, width) {
- context = {prev: context, indent: indent, col: col, type: type, width: width};
- }
- function popContext() {
- context = context.prev;
- }
-
- var iter = {
- next: function() {
- var token = tokens.next(), type = token.style, content = token.content, width = token.value.length;
-
- if (content == "\n") {
- token.indentation = indentSparql(context);
- indent = col = 0;
- if (context && context.align == null) context.align = false;
- }
- else if (type == "whitespace" && col == 0) {
- indent = width;
- }
- else if (type != "sp-comment" && context && context.align == null) {
- context.align = true;
- }
-
- if (content != "\n") col += width;
-
- if (/[\[\{\(]/.test(content)) {
- pushContext(content, width);
- }
- else if (/[\]\}\)]/.test(content)) {
- while (context && context.type == "pattern")
- popContext();
- if (context && content == matching[context.type])
- popContext();
- }
- else if (content == "." && context && context.type == "pattern") {
- popContext();
- }
- else if ((type == "sp-word" || type == "sp-prefixed" || type == "sp-uri" || type == "sp-var" || type == "sp-literal") &&
- context && /[\{\[]/.test(context.type)) {
- pushContext("pattern", width);
- }
-
- return token;
- },
-
- copy: function() {
- var _context = context, _indent = indent, _col = col, _tokenState = tokens.state;
- return function(source) {
- tokens = tokenizeSparql(source, _tokenState);
- context = _context;
- indent = _indent;
- col = _col;
- return iter;
- };
- }
- };
- return iter;
- }
-
- return {make: parseSparql, electricChars: "}]"};
-})();
diff --git a/o3d/samples/third_party/codemirror/js/parsexml.js b/o3d/samples/third_party/codemirror/js/parsexml.js
deleted file mode 100644
index d38fa12..0000000
--- a/o3d/samples/third_party/codemirror/js/parsexml.js
+++ /dev/null
@@ -1,292 +0,0 @@
-/* This file defines an XML parser, with a few kludges to make it
- * useable for HTML. autoSelfClosers defines a set of tag names that
- * are expected to not have a closing tag, and doNotIndent specifies
- * the tags inside of which no indentation should happen (see Config
- * object). These can be disabled by passing the editor an object like
- * {useHTMLKludges: false} as parserConfig option.
- */
-
-var XMLParser = Editor.Parser = (function() {
- var Kludges = {
- autoSelfClosers: {"br": true, "img": true, "hr": true, "link": true, "input": true,
- "meta": true, "col": true, "frame": true, "base": true, "area": true},
- doNotIndent: {"pre": true}
- };
- var NoKludges = {autoSelfClosers: {}, doNotIndent: {}};
- var UseKludges = Kludges;
-
- // Simple stateful tokenizer for XML documents. Returns a
- // MochiKit-style iterator, with a state property that contains a
- // function encapsulating the current state. See tokenize.js.
- var tokenizeXML = (function() {
- function inText(source, setState) {
- var ch = source.next();
- if (ch == "<") {
- if (source.equals("!")) {
- source.next();
- if (source.equals("[")) {
- if (source.matches("[CDATA[", true)) {
- setState(inBlock("xml-cdata", "]]>"));
- return null;
- }
- else {
- return "xml-text";
- }
- }
- else if (source.matches("--", true)) {
- setState(inBlock("xml-comment", "-->"));
- return null;
- }
- else {
- return "xml-text";
- }
- }
- else if (source.equals("?")) {
- source.next();
- setState(inBlock("xml-processing", "?>"));
- return null;
- }
- else {
- if (source.equals("/")) source.next();
- setState(inTag);
- return "xml-punctuation";
- }
- }
- else if (ch == "&") {
- while (!source.endOfLine()) {
- if (source.next() == ";")
- break;
- }
- return "xml-entity";
- }
- else {
- source.nextWhile(matcher(/[^&<\n]/));
- return "xml-text";
- }
- }
-
- function inTag(source, setState) {
- var ch = source.next();
- if (ch == ">") {
- setState(inText);
- return "xml-punctuation";
- }
- else if (/[?\/]/.test(ch) && source.equals(">")) {
- source.next();
- setState(inText);
- return "xml-punctuation";
- }
- else if (ch == "=") {
- return "xml-punctuation";
- }
- else if (/[\'\"]/.test(ch)) {
- setState(inAttribute(ch));
- return null;
- }
- else {
- source.nextWhile(matcher(/[^\s\u00a0=<>\"\'\/?]/));
- return "xml-name";
- }
- }
-
- function inAttribute(quote) {
- return function(source, setState) {
- while (!source.endOfLine()) {
- if (source.next() == quote) {
- setState(inTag);
- break;
- }
- }
- return "xml-attribute";
- };
- }
-
- function inBlock(style, terminator) {
- return function(source, setState) {
- var matches = [];
- while (!source.endOfLine()) {
- var ch = source.next(), newMatches = [];
- if (ch == terminator.charAt(0))
- matches.push(terminator);
- for (var i = 0; i < matches.length; i++) {
- var match = matches[i];
- if (match.charAt(0) == ch) {
- if (match.length == 1) {setState(inText); break;}
- else newMatches.push(match.slice(1));
- }
- }
- matches = newMatches;
- }
- return style;
- };
- }
-
- return function(source, startState) {
- return tokenizer(source, startState || inText);
- };
- })();
-
- // The parser. The structure of this function largely follows that of
- // parseJavaScript in parsejavascript.js (there is actually a bit more
- // shared code than I'd like), but it is quite a bit simpler.
- function parseXML(source) {
- var tokens = tokenizeXML(source);
- var cc = [base];
- var tokenNr = 0, indented = 0;
- var currentTag = null, context = null;
- var consume, marked;
-
- function push(fs) {
- for (var i = fs.length - 1; i >= 0; i--)
- cc.push(fs[i]);
- }
- function cont() {
- push(arguments);
- consume = true;
- }
- function pass() {
- push(arguments);
- consume = false;
- }
-
- function mark(style) {
- marked = style;
- }
- function expect(text) {
- return function(style, content) {
- if (content == text) cont();
- else mark("xml-error") || cont(arguments.callee);
- };
- }
-
- function pushContext(tagname, startOfLine) {
- var noIndent = UseKludges.doNotIndent.hasOwnProperty(tagname) || (context && context.noIndent);
- context = {prev: context, name: tagname, indent: indented, startOfLine: startOfLine, noIndent: noIndent};
- }
- function popContext() {
- context = context.prev;
- }
- function computeIndentation(baseContext) {
- return function(nextChars) {
- var context = baseContext;
- if (context && context.noIndent)
- return 0;
- if (context && /^<\//.test(nextChars))
- context = context.prev;
- while (context && !context.startOfLine)
- context = context.prev;
- if (context)
- return context.indent + 2;
- else
- return 0;
- };
- }
-
- function base() {
- return pass(element, base);
- }
- var harmlessTokens = {"xml-text": true, "xml-entity": true, "xml-comment": true,
- "xml-cdata": true, "xml-processing": true};
- function element(style, content) {
- if (content == "<") cont(tagname, attributes, endtag(tokenNr == 1));
- else if (content == "</") cont(closetagname, expect(">"));
- else if (content == "<?") cont(tagname, attributes, expect("?>"));
- else if (harmlessTokens.hasOwnProperty(style)) cont();
- else mark("xml-error") || cont();
- }
- function tagname(style, content) {
- if (style == "xml-name") {
- currentTag = content.toLowerCase();
- mark("xml-tagname");
- cont();
- }
- else {
- currentTag = null;
- pass();
- }
- }
- function closetagname(style, content) {
- if (style == "xml-name" && context && content.toLowerCase() == context.name) {
- popContext();
- mark("xml-tagname");
- }
- else {
- mark("xml-error");
- }
- cont();
- }
- function endtag(startOfLine) {
- return function(style, content) {
- if (content == "/>" || (content == ">" && UseKludges.autoSelfClosers.hasOwnProperty(currentTag))) cont();
- else if (content == ">") pushContext(currentTag, startOfLine) || cont();
- else mark("xml-error") || cont(arguments.callee);
- };
- }
- function attributes(style) {
- if (style == "xml-name") mark("xml-attname") || cont(attribute, attributes);
- else pass();
- }
- function attribute(style, content) {
- if (content == "=") cont(value);
- else if (content == ">" || content == "/>") pass(endtag);
- else pass();
- }
- function value(style) {
- if (style == "xml-attribute") cont(value);
- else pass();
- }
-
- return {
- indentation: function() {return indented;},
-
- next: function(){
- var token = tokens.next();
- if (token.style == "whitespace" && tokenNr == 0)
- indented = token.value.length;
- else
- tokenNr++;
- if (token.content == "\n") {
- indented = tokenNr = 0;
- token.indentation = computeIndentation(context);
- }
-
- if (token.style == "whitespace" || token.type == "xml-comment")
- return token;
-
- while(true){
- consume = marked = false;
- cc.pop()(token.style, token.content);
- if (consume){
- if (marked)
- token.style = marked;
- return token;
- }
- }
- },
-
- copy: function(){
- var _cc = cc.concat([]), _tokenState = tokens.state, _context = context;
- var parser = this;
-
- return function(input){
- cc = _cc.concat([]);
- tokenNr = indented = 0;
- context = _context;
- tokens = tokenizeXML(input, _tokenState);
- return parser;
- };
- }
- };
- }
-
- return {
- make: parseXML,
- electricChars: "/",
- configure: function(config) {
- if (config.useHTMLKludges)
- UseKludges = Kludges;
- else
- UseKludges = NoKludges;
- }
- };
-})();
diff --git a/o3d/samples/third_party/codemirror/js/select.js b/o3d/samples/third_party/codemirror/js/select.js
deleted file mode 100644
index 4c6cb96..0000000
--- a/o3d/samples/third_party/codemirror/js/select.js
+++ /dev/null
@@ -1,500 +0,0 @@
-/* Functionality for finding, storing, and restoring selections
- *
- * This does not provide a generic API, just the minimal functionality
- * required by the CodeMirror system.
- */
-
-// Namespace object.
-var select = {};
-
-(function() {
- var ie_selection = document.selection && document.selection.createRangeCollection;
-
- // Find the 'top-level' (defined as 'a direct child of the node
- // passed as the top argument') node that the given node is
- // contained in. Return null if the given node is not inside the top
- // node.
- function topLevelNodeAt(node, top) {
- while (node && node.parentNode != top)
- node = node.parentNode;
- return node;
- }
-
- // Find the top-level node that contains the node before this one.
- function topLevelNodeBefore(node, top) {
- while (!node.previousSibling && node.parentNode != top)
- node = node.parentNode;
- return topLevelNodeAt(node.previousSibling, top);
- }
-
- // Used to prevent restoring a selection when we do not need to.
- var documentChanged = false;
-
- var fourSpaces = "\u00a0\u00a0\u00a0\u00a0";
-
- // Most functions are defined in two ways, one for the IE selection
- // model, one for the W3C one.
- if (ie_selection) {
- // Store the current selection in such a way that it can be
- // restored after we manipulated the DOM tree. For IE, we store
- // pixel coordinates.
- select.markSelection = function (win) {
- var selection = win.document.selection;
- var start = selection.createRange(), end = start.duplicate();
- var bookmark = start.getBookmark();
- start.collapse(true);
- end.collapse(false);
-
- documentChanged = false;
- var body = win.document.body;
- // And we better hope no fool gave this window a padding or a
- // margin, or all these computations will be in vain.
- return {start: {x: start.boundingLeft + body.scrollLeft - 1,
- y: start.boundingTop + body.scrollTop},
- end: {x: end.boundingLeft + body.scrollLeft - 1,
- y: end.boundingTop + body.scrollTop},
- window: win,
- bookmark: bookmark};
- };
-
- // Restore a stored selection.
- select.selectMarked = function(sel) {
- if (!sel || !documentChanged)
- return;
-
- documentChanged = false;
- var range1 = sel.window.document.body.createTextRange(), range2 = range1.duplicate();
- var done = false;
- if (sel.start.y >= 0 && sel.end.y < sel.window.document.body.clientHeight) {
- // This can fail for various hard-to-handle reasons, so we
- // fall back to moveToBookmark when it throws.
- try {
- range1.moveToPoint(sel.start.x, sel.start.y);
- range2.moveToPoint(sel.end.x, sel.end.y);
- range1.setEndPoint("EndToStart", range2);
- done = true;
- } catch(e) {}
- }
- if (!done) done = range1.moveToBookmark(sel.bookmark);
- if (done) range1.select();
- };
-
-
- // See W3C model for the actual role of this function. Here it
- // just sets a flag indicating the selection should be restored.
- select.replaceSelection = function(){
- documentChanged = true;
- };
-
- // Get the top-level node that one end of the cursor is inside or
- // after. Note that this returns false for 'no cursor', and null
- // for 'start of document'.
- select.selectionTopNode = function(container, start) {
- var selection = container.ownerDocument.selection;
- if (!selection) return false;
-
- var range = selection.createRange();
- range.collapse(start);
- var around = range.parentElement();
- if (around && isAncestor(container, around)) {
- // Only use this node if the selection is not at its start.
- var range2 = range.duplicate();
- range2.moveToElementText(around);
- if (range.compareEndPoints("StartToStart", range2) == -1)
- return topLevelNodeAt(around, container);
- }
- // Fall-back hack
- range.pasteHTML("<span id='xxx-temp-xxx'></span>");
- var temp = container.ownerDocument.getElementById("xxx-temp-xxx");
- if (temp) {
- var result = topLevelNodeBefore(temp, container);
- removeElement(temp);
- return result;
- }
- return false;
- };
-
- // Place the cursor after this.start. This is only useful when
- // manually moving the cursor instead of restoring it to its old
- // position.
- select.focusAfterNode = function(node, container) {
- var range = container.ownerDocument.body.createTextRange();
- range.moveToElementText(node || container);
- range.collapse(!node);
- range.select();
- };
-
- function insertAtCursor(window, html) {
- var selection = window.document.selection;
- if (selection) {
- var range = selection.createRange();
- range.pasteHTML(html);
- range.collapse(false);
- range.select();
- }
- }
-
- // Used to normalize the effect of the enter key, since browsers
- // do widely different things when pressing enter in designMode.
- select.insertNewlineAtCursor = function(window) {
- insertAtCursor(window, "<br/>");
- };
-
- select.insertTabAtCursor = function(window) {
- insertAtCursor(window, fourSpaces);
- };
-
- // Get the BR node at the start of the line on which the cursor
- // currently is, and the offset into the line. Returns null as
- // node if cursor is on first line.
- select.cursorPos = function(container, start) {
- var selection = container.ownerDocument.selection;
- if (!selection) return null;
-
- var topNode = select.selectionTopNode(container, start);
- while (topNode && topNode.nodeName != "BR")
- topNode = topNode.previousSibling;
-
- var range = selection.createRange(), range2 = range.duplicate();
- range.collapse(start);
- if (topNode) {
- range2.moveToElementText(topNode);
- range2.collapse(false);
- }
- else {
- // When nothing is selected, we can get all kinds of funky errors here.
- try { range2.moveToElementText(container); }
- catch (e) { return null; }
- range2.collapse(true);
- }
- range.setEndPoint("StartToStart", range2);
-
- return {node: topNode, offset: range.text.length};
- };
-
- select.setCursorPos = function(container, from, to) {
- function rangeAt(pos) {
- var range = container.ownerDocument.body.createTextRange();
- if (!pos.node) {
- range.moveToElementText(container);
- range.collapse(true);
- }
- else {
- range.moveToElementText(pos.node);
- range.collapse(false);
- }
- range.move("character", pos.offset);
- return range;
- }
-
- var range = rangeAt(from);
- if (to && to != from)
- range.setEndPoint("EndToEnd", rangeAt(to));
- range.select();
- }
-
- // Make sure the cursor is visible.
- select.scrollToCursor = function(container) {
- var selection = container.ownerDocument.selection;
- if (!selection) return null;
- selection.createRange().scrollIntoView();
- };
- }
- // W3C model
- else {
- // This is used to fix an issue with getting the scroll position
- // in Opera.
- var opera_scroll = !window.scrollX && !window.scrollY;
-
- // Store start and end nodes, and offsets within these, and refer
- // back to the selection object from those nodes, so that this
- // object can be updated when the nodes are replaced before the
- // selection is restored.
- select.markSelection = function (win) {
- documentChanged = false;
- var selection = win.getSelection();
- if (!selection || selection.rangeCount == 0)
- return null;
- var range = selection.getRangeAt(0);
-
- var result = {start: {node: range.startContainer, offset: range.startOffset},
- end: {node: range.endContainer, offset: range.endOffset},
- window: win,
- scrollX: opera_scroll && win.document.body.scrollLeft,
- scrollY: opera_scroll && win.document.body.scrollTop};
-
- // We want the nodes right at the cursor, not one of their
- // ancestors with a suitable offset. This goes down the DOM tree
- // until a 'leaf' is reached (or is it *up* the DOM tree?).
- function normalize(point){
- while (point.node.nodeType != 3 && point.node.nodeName != "BR") {
- var newNode = point.node.childNodes[point.offset] || point.node.nextSibling;
- point.offset = 0;
- while (!newNode && point.node.parentNode) {
- point.node = point.node.parentNode;
- newNode = point.node.nextSibling;
- }
- point.node = newNode;
- if (!newNode)
- break;
- }
- }
-
- normalize(result.start);
- normalize(result.end);
- // Make the links back to the selection object (see
- // replaceSelection).
- if (result.start.node)
- result.start.node.selectStart = result.start;
- if (result.end.node)
- result.end.node.selectEnd = result.end;
-
- return result;
- };
-
- select.selectMarked = function (sel) {
- if (!sel || !documentChanged)
- return;
- var win = sel.window;
- var range = win.document.createRange();
-
- function setPoint(point, which) {
- if (point.node) {
- // Remove the link back to the selection.
- delete point.node["select" + which];
- // Some magic to generalize the setting of the start and end
- // of a range.
- if (point.offset == 0)
- range["set" + which + "Before"](point.node);
- else
- range["set" + which](point.node, point.offset);
- }
- else {
- range.setStartAfter(win.document.body.lastChild || win.document.body);
- }
- }
-
- // Have to restore the scroll position of the frame in Opera.
- if (opera_scroll){
- sel.window.document.body.scrollLeft = sel.scrollX;
- sel.window.document.body.scrollTop = sel.scrollY;
- }
- setPoint(sel.end, "End");
- setPoint(sel.start, "Start");
- selectRange(range, win);
- };
-
- // This is called by the code in codemirror.js whenever it is
- // replacing a part of the DOM tree. The function sees whether the
- // given oldNode is part of the current selection, and updates
- // this selection if it is. Because nodes are often only partially
- // replaced, the length of the part that gets replaced has to be
- // taken into account -- the selection might stay in the oldNode
- // if the newNode is smaller than the selection's offset. The
- // offset argument is needed in case the selection does move to
- // the new object, and the given length is not the whole length of
- // the new node (part of it might have been used to replace
- // another node).
- select.replaceSelection = function(oldNode, newNode, length, offset) {
- documentChanged = true;
- function replace(which) {
- var selObj = oldNode["select" + which];
- if (selObj) {
- if (selObj.offset > length) {
- selObj.offset -= length;
- }
- else {
- newNode["select" + which] = selObj;
- delete oldNode["select" + which];
- selObj.node = newNode;
- selObj.offset += (offset || 0);
- }
- }
- }
- replace("Start");
- replace("End");
- };
-
- // Helper for selecting a range object.
- function selectRange(range, window) {
- var selection = window.getSelection();
- selection.removeAllRanges();
- selection.addRange(range);
- };
- function selectionRange(window) {
- var selection = window.getSelection();
- if (!selection || selection.rangeCount == 0)
- return false;
- else
- return selection.getRangeAt(0);
- }
-
- // Finding the top-level node at the cursor in the W3C is, as you
- // can see, quite an involved process.
- select.selectionTopNode = function(container, start) {
- var range = selectionRange(container.ownerDocument.defaultView);
- if (!range) return false;
-
- var node = start ? range.startContainer : range.endContainer;
- var offset = start ? range.startOffset : range.endOffset;
- // Work around (yet another) bug in Opera's selection model.
- if (window.opera && !start && range.endContainer == container && range.endOffset == range.startOffset + 1 &&
- container.childNodes[range.startOffset] && container.childNodes[range.startOffset].nodeName == "BR")
- offset--;
-
- // For text nodes, we look at the node itself if the cursor is
- // inside, or at the node before it if the cursor is at the
- // start.
- if (node.nodeType == 3){
- if (offset > 0)
- return topLevelNodeAt(node, container);
- else
- return topLevelNodeBefore(node, container);
- }
- // Occasionally, browsers will return the HTML node as
- // selection. If the offset is 0, we take the start of the frame
- // ('after null'), otherwise, we take the last node.
- else if (node.nodeName == "HTML") {
- return (offset == 1 ? null : container.lastChild);
- }
- // If the given node is our 'container', we just look up the
- // correct node by using the offset.
- else if (node == container) {
- return (offset == 0) ? null : node.childNodes[offset - 1];
- }
- // In any other case, we have a regular node. If the cursor is
- // at the end of the node, we use the node itself, if it is at
- // the start, we use the node before it, and in any other
- // case, we look up the child before the cursor and use that.
- else {
- if (offset == node.childNodes.length)
- return topLevelNodeAt(node, container);
- else if (offset == 0)
- return topLevelNodeBefore(node, container);
- else
- return topLevelNodeAt(node.childNodes[offset - 1], container);
- }
- };
-
- select.focusAfterNode = function(node, container) {
- var win = container.ownerDocument.defaultView,
- range = win.document.createRange();
- range.setStartBefore(container.firstChild || container);
- // In Opera, setting the end of a range at the end of a line
- // (before a BR) will cause the cursor to appear on the next
- // line, so we set the end inside of the start node when
- // possible.
- if (node && !node.firstChild)
- range.setEndAfter(node);
- else if (node)
- range.setEnd(node, node.childNodes.length);
- else
- range.setEndBefore(container.firstChild || container);
- range.collapse(false);
- selectRange(range, win);
- };
-
- insertNodeAtCursor = function(window, node) {
- var range = selectionRange(window);
- if (!range) return;
-
- range.deleteContents();
- range.insertNode(node);
- range.setEndAfter(node);
- range.collapse(false);
- selectRange(range, window);
- return node;
- }
-
- select.insertNewlineAtCursor = function(window) {
- insertNodeAtCursor(window, window.document.createElement("BR"));
- };
-
- select.insertTabAtCursor = function(window) {
- insertNodeAtCursor(window, window.document.createTextNode(fourSpaces));
- };
-
- select.cursorPos = function(container, start) {
- var range = selectionRange(window);
- if (!range) return;
-
- var topNode = select.selectionTopNode(container, start);
- while (topNode && topNode.nodeName != "BR")
- topNode = topNode.previousSibling;
-
- range = range.cloneRange();
- range.collapse(start);
- if (topNode)
- range.setStartAfter(topNode);
- else
- range.setStartBefore(container);
- return {node: topNode, offset: range.toString().length};
- };
-
- select.setCursorPos = function(container, from, to) {
- var win = container.ownerDocument.defaultView,
- range = win.document.createRange();
-
- function setPoint(node, offset, side) {
- if (!node)
- node = container.firstChild;
- else
- node = node.nextSibling;
-
- if (!node)
- return;
-
- if (offset == 0) {
- range["set" + side + "Before"](node);
- return true;
- }
-
- var backlog = []
- function decompose(node) {
- if (node.nodeType == 3)
- backlog.push(node);
- else
- forEach(node.childNodes, decompose);
- }
- while (true) {
- while (node && !backlog.length) {
- decompose(node);
- node = node.nextSibling;
- }
- var cur = backlog.shift();
- if (!cur) return false;
-
- var length = cur.nodeValue.length;
- if (length >= offset) {
- range["set" + side](cur, offset);
- return true;
- }
- offset -= length;
- }
- }
-
- to = to || from;
- if (setPoint(to.node, to.offset, "End") && setPoint(from.node, from.offset, "Start"))
- selectRange(range, win);
- };
-
- select.scrollToCursor = function(container) {
- var body = container.ownerDocument.body, win = container.ownerDocument.defaultView;
- var element = select.selectionTopNode(container, true) || container.firstChild;
-
- // In Opera, BR elements *always* have a scrollTop property of zero. Go Opera.
- while (element && !element.offsetTop)
- element = element.previousSibling;
-
- var y = 0, pos = element;
- while (pos && pos.offsetParent) {
- y += pos.offsetTop;
- pos = pos.offsetParent;
- }
-
- var screen_y = y - body.scrollTop;
- if (screen_y < 0 || screen_y > win.innerHeight - 10)
- win.scrollTo(0, y);
- };
- }
-}());
diff --git a/o3d/samples/third_party/codemirror/js/stringstream.js b/o3d/samples/third_party/codemirror/js/stringstream.js
deleted file mode 100644
index 17ff8a5..0000000
--- a/o3d/samples/third_party/codemirror/js/stringstream.js
+++ /dev/null
@@ -1,111 +0,0 @@
-/* String streams are the things fed to parsers (which can feed them
- * to a tokenizer if they want). They provide peek and next methods
- * for looking at the current character (next 'consumes' this
- * character, peek does not), and a get method for retrieving all the
- * text that was consumed since the last time get was called.
- *
- * An easy mistake to make is to let a StopIteration exception finish
- * the token stream while there are still characters pending in the
- * string stream (hitting the end of the buffer while parsing a
- * token). To make it easier to detect such errors, the strings throw
- * an exception when this happens.
- */
-
-(function(){
- // Generic operations that apply to stringstreams.
- var base = {
- more: function() {
- return this.peek() !== null;
- },
- applies: function(test) {
- var next = this.peek();
- return (next !== null && test(next));
- },
- nextWhile: function(test) {
- while (this.applies(test))
- this.next();
- },
- equals: function(ch) {
- return ch === this.peek();
- },
- endOfLine: function() {
- var next = this.peek();
- return next == null || next == "\n";
- },
- matches: function(string, caseSensitive) {
- for (var i = 0; i < string.length; i++) {
- var ch = this.peek();
- if (!ch || string.charAt(i) != (caseSensitive ? ch : ch.toLowerCase()))
- return false;
- this.next();
- }
- return true;
- }
- };
-
- // Make a string stream out of an iterator that returns strings. This
- // is applied to the result of traverseDOM (see codemirror.js), and
- // the resulting stream is fed to the parser.
- window.stringStream = function(source){
- source = iter(source);
- var current = "", pos = 0;
- var peeked = null, accum = "";
-
- return update({
- peek: function() {
- if (!peeked) {
- try {peeked = this.step();}
- catch (e) {
- if (e != StopIteration) throw e;
- else peeked = null;
- }
- }
- return peeked;
- },
- step: function() {
- if (peeked) {
- var temp = peeked;
- peeked = null;
- return temp;
- }
- while (pos == current.length) {
- accum += current;
- current = ""; // In case source.next() throws
- pos = 0;
- current = source.next();
- }
- return current.charAt(pos++);
-
- },
- next: function() {
- try {return this.step();}
- catch (e) {
- if (e == StopIteration && accum.length > 0)
- throw "End of stringstream reached without emptying buffer ('" + accum + "').";
- else
- throw e;
- }
- },
- get: function() {
- var temp = accum;
- var realPos = peeked ? pos - 1 : pos;
- accum = "";
- if (realPos > 0){
- temp += current.slice(0, realPos);
- current = current.slice(realPos);
- pos = peeked ? 1 : 0;
- }
- return temp;
- },
- reset: function() {
- current = accum + current;
- accum = "";
- pos = 0;
- peeked = null;
- },
- push: function(str) {
- current = current.slice(0, pos) + str + current.slice(pos);
- }
- }, base);
- };
-})();
diff --git a/o3d/samples/third_party/codemirror/js/tokenize.js b/o3d/samples/third_party/codemirror/js/tokenize.js
deleted file mode 100644
index 8bb700e..0000000
--- a/o3d/samples/third_party/codemirror/js/tokenize.js
+++ /dev/null
@@ -1,57 +0,0 @@
-// A frame for simple tokenizers. Takes care of newlines and
-// white-space, and of getting the text from the source stream into
-// the token object. A state is a function of two arguments -- a
-// string stream and a setState function. The second can be used to
-// change the tokenizer's state, and can be ignored for stateless
-// tokenizers. This function should advance the stream over a token
-// and return a string or object containing information about the next
-// token, or null to pass and have the (new) state be called to finish
-// the token. When a string is given, it is wrapped in a {style, type}
-// object. In the resulting object, the characters consumed are stored
-// under the content property. Any whitespace following them is also
-// automatically consumed, and added to the value property. (Thus,
-// content is the actual meaningful part of the token, while value
-// contains all the text it spans.)
-
-function tokenizer(source, state) {
- // Newlines are always a separate token.
- function isWhiteSpace(ch) {
- // The messy regexp is because IE's regexp matcher is of the
- // opinion that non-breaking spaces are no whitespace.
- return ch != "\n" && /^[\s\u00a0]*$/.test(ch);
- }
-
- var tokenizer = {
- state: state,
-
- take: function(type) {
- if (typeof(type) == "string")
- type = {style: type, type: type};
-
- type.content = (type.content || "") + source.get();
- if (!/\n$/.test(type.content))
- source.nextWhile(isWhiteSpace);
- type.value = type.content + source.get();
- return type;
- },
-
- next: function () {
- if (!source.more()) throw StopIteration;
-
- var type;
- if (source.equals("\n")) {
- source.next();
- return this.take("whitespace");
- }
-
- if (source.applies(isWhiteSpace))
- type = "whitespace";
- else
- while (!type)
- type = this.state(source, function(s) {tokenizer.state = s;});
-
- return this.take(type);
- }
- };
- return tokenizer;
-}
diff --git a/o3d/samples/third_party/codemirror/js/tokenizejavascript.js b/o3d/samples/third_party/codemirror/js/tokenizejavascript.js
deleted file mode 100644
index 24d0529..0000000
--- a/o3d/samples/third_party/codemirror/js/tokenizejavascript.js
+++ /dev/null
@@ -1,168 +0,0 @@
-/* Tokenizer for JavaScript code */
-
-var tokenizeJavaScript = (function() {
- // Advance the stream until the given character (not preceded by a
- // backslash) is encountered, or the end of the line is reached.
- function nextUntilUnescaped(source, end, result){
- var escaped = false;
- var next;
- while(!source.endOfLine()){
- var next = source.next();
- if (next == end && !escaped)
- break;
- escaped = next == "\\";
- }
- return result;
- }
-
- // A map of JavaScript's keywords. The a/b/c keyword distinction is
- // very rough, but it gives the parser enough information to parse
- // correct code correctly (we don't care that much how we parse
- // incorrect code). The style information included in these objects
- // is used by the highlighter to pick the correct CSS style for a
- // token.
- var keywords = function(){
- function result(type, style){
- return {type: type, style: style};
- }
- // keywords that take a parenthised expression, and then a
- // statement (if)
- var keywordA = result("keyword a", "js-keyword");
- // keywords that take just a statement (else)
- var keywordB = result("keyword b", "js-keyword");
- // keywords that optionally take an expression, and form a
- // statement (return)
- var keywordC = result("keyword c", "js-keyword");
- var operator = result("operator", "js-keyword");
- var atom = result("atom", "js-atom");
- return {
- "if": keywordA, "switch": keywordA, "while": keywordA, "with": keywordA,
- "else": keywordB, "do": keywordB, "try": keywordB, "finally": keywordB,
- "return": keywordC, "break": keywordC, "continue": keywordC, "new": keywordC, "delete": keywordC, "throw": keywordC,
- "in": operator, "typeof": operator, "instanceof": operator,
- "var": result("var", "js-keyword"), "function": result("function", "js-keyword"), "catch": result("catch", "js-keyword"),
- "for": result("for", "js-keyword"), "case": result("case", "js-keyword"),
- "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom
- };
- }();
-
- // Some helper regexp matchers.
- var isOperatorChar = matcher(/[\+\-\*\&\%\/=<>!\?]/);
- var isDigit = matcher(/[0-9]/);
- var isHexDigit = matcher(/[0-9A-Fa-f]/);
- var isWordChar = matcher(/[\w\$_]/);
-
- // Wrapper around jsToken that helps maintain parser state (whether
- // we are inside of a multi-line comment and whether the next token
- // could be a regular expression).
- function jsTokenState(inComment, regexp) {
- return function(source, setState) {
- var newInComment = inComment;
- var type = jsToken(inComment, regexp, source, function(c) {newInComment = c;});
- var newRegexp = type.type == "operator" || type.type == "keyword c" || type.type.match(/^[\[{}\(,;:]$/);
- if (newRegexp != regexp || newInComment != inComment)
- setState(jsTokenState(newInComment, newRegexp));
- return type;
- };
- }
-
- // The token reader, inteded to be used by the tokenizer from
- // tokenize.js (through jsTokenState). Advances the source stream
- // over a token, and returns an object containing the type and style
- // of that token.
- function jsToken(inComment, regexp, source, setComment) {
- function readHexNumber(){
- source.next(); // skip the 'x'
- source.nextWhile(isHexDigit);
- return {type: "number", style: "js-atom"};
- }
-
- function readNumber() {
- source.nextWhile(isDigit);
- if (source.equals(".")){
- source.next();
- source.nextWhile(isDigit);
- }
- if (source.equals("e") || source.equals("E")){
- source.next();
- if (source.equals("-"))
- source.next();
- source.nextWhile(isDigit);
- }
- return {type: "number", style: "js-atom"};
- }
- // Read a word, look it up in keywords. If not found, it is a
- // variable, otherwise it is a keyword of the type found.
- function readWord() {
- source.nextWhile(isWordChar);
- var word = source.get();
- var known = keywords.hasOwnProperty(word) && keywords.propertyIsEnumerable(word) && keywords[word];
- return known ? {type: known.type, style: known.style, content: word} :
- {type: "variable", style: "js-variable", content: word};
- }
- function readRegexp() {
- nextUntilUnescaped(source, "/");
- source.nextWhile(matcher(/[gi]/));
- return {type: "regexp", style: "js-string"};
- }
- // Mutli-line comments are tricky. We want to return the newlines
- // embedded in them as regular newline tokens, and then continue
- // returning a comment token for every line of the comment. So
- // some state has to be saved (inComment) to indicate whether we
- // are inside a /* */ sequence.
- function readMultilineComment(start){
- var newInComment = true;
- var maybeEnd = (start == "*");
- while (true) {
- if (source.endOfLine())
- break;
- var next = source.next();
- if (next == "/" && maybeEnd){
- newInComment = false;
- break;
- }
- maybeEnd = (next == "*");
- }
- setComment(newInComment);
- return {type: "comment", style: "js-comment"};
- }
- function readOperator() {
- source.nextWhile(isOperatorChar);
- return {type: "operator", style: "js-operator"};
- }
-
- // Fetch the next token. Dispatches on first character in the
- // stream, or first two characters when the first is a slash.
- var ch = source.next();
- if (inComment)
- return readMultilineComment(ch);
- else if (ch == "\"" || ch == "'")
- return nextUntilUnescaped(source, ch, {type: "string", style: "js-string"});
- // with punctuation, the type of the token is the symbol itself
- else if (/[\[\]{}\(\),;\:\.]/.test(ch))
- return {type: ch, style: "js-punctuation"};
- else if (ch == "0" && (source.equals("x") || source.equals("X")))
- return readHexNumber();
- else if (isDigit(ch))
- return readNumber();
- else if (ch == "/"){
- if (source.equals("*"))
- { source.next(); return readMultilineComment(ch); }
- else if (source.equals("/"))
- return nextUntilUnescaped(source, null, {type: "comment", style: "js-comment"});
- else if (regexp)
- return readRegexp();
- else
- return readOperator();
- }
- else if (isOperatorChar(ch))
- return readOperator();
- else
- return readWord();
- }
-
- // The external interface to the tokenizer.
- return function(source, startState) {
- return tokenizer(source, startState || jsTokenState(false, true));
- };
-})();
diff --git a/o3d/samples/third_party/codemirror/js/undo.js b/o3d/samples/third_party/codemirror/js/undo.js
deleted file mode 100644
index a8edc51..0000000
--- a/o3d/samples/third_party/codemirror/js/undo.js
+++ /dev/null
@@ -1,386 +0,0 @@
-/**
- * Storage and control for undo information within a CodeMirror
- * editor. 'Why on earth is such a complicated mess required for
- * that?', I hear you ask. The goal, in implementing this, was to make
- * the complexity of storing and reverting undo information depend
- * only on the size of the edited or restored content, not on the size
- * of the whole document. This makes it necessary to use a kind of
- * 'diff' system, which, when applied to a DOM tree, causes some
- * complexity and hackery.
- *
- * In short, the editor 'touches' BR elements as it parses them, and
- * the History stores these. When nothing is touched in commitDelay
- * milliseconds, the changes are committed: It goes over all touched
- * nodes, throws out the ones that did not change since last commit or
- * are no longer in the document, and assembles the rest into zero or
- * more 'chains' -- arrays of adjacent lines. Links back to these
- * chains are added to the BR nodes, while the chain that previously
- * spanned these nodes is added to the undo history. Undoing a change
- * means taking such a chain off the undo history, restoring its
- * content (text is saved per line) and linking it back into the
- * document.
- */
-
-// A history object needs to know about the DOM container holding the
-// document, the maximum amount of undo levels it should store, the
-// delay (of no input) after which it commits a set of changes, and,
-// unfortunately, the 'parent' window -- a window that is not in
-// designMode, and on which setTimeout works in every browser.
-function History(container, maxDepth, commitDelay, editor, onChange) {
- this.container = container;
- this.maxDepth = maxDepth; this.commitDelay = commitDelay;
- this.editor = editor; this.parent = editor.parent;
- this.onChange = onChange;
- // This line object represents the initial, empty editor.
- var initial = {text: "", from: null, to: null};
- // As the borders between lines are represented by BR elements, the
- // start of the first line and the end of the last one are
- // represented by null. Since you can not store any properties
- // (links to line objects) in null, these properties are used in
- // those cases.
- this.first = initial; this.last = initial;
- // Similarly, a 'historyTouched' property is added to the BR in
- // front of lines that have already been touched, and 'firstTouched'
- // is used for the first line.
- this.firstTouched = false;
- // History is the set of committed changes, touched is the set of
- // nodes touched since the last commit.
- this.history = []; this.redoHistory = []; this.touched = [];
-}
-
-History.prototype = {
- // Schedule a commit (if no other touches come in for commitDelay
- // milliseconds).
- scheduleCommit: function() {
- this.parent.clearTimeout(this.commitTimeout);
- this.commitTimeout = this.parent.setTimeout(method(this, "tryCommit"), this.commitDelay);
- },
-
- // Mark a node as touched. Null is a valid argument.
- touch: function(node) {
- this.setTouched(node);
- this.scheduleCommit();
- },
-
- // Undo the last change.
- undo: function() {
- // Make sure pending changes have been committed.
- this.commit();
-
- if (this.history.length) {
- // Take the top diff from the history, apply it, and store its
- // shadow in the redo history.
- this.redoHistory.push(this.updateTo(this.history.pop(), "applyChain"));
- if (this.onChange) this.onChange();
- }
- },
-
- // Redo the last undone change.
- redo: function() {
- this.commit();
- if (this.redoHistory.length) {
- // The inverse of undo, basically.
- this.addUndoLevel(this.updateTo(this.redoHistory.pop(), "applyChain"));
- if (this.onChange) this.onChange();
- }
- },
-
- // Push a changeset into the document.
- push: function(from, to, lines) {
- var chain = [];
- for (var i = 0; i < lines.length; i++) {
- var end = (i == lines.length - 1) ? to : this.container.ownerDocument.createElement("BR");
- chain.push({from: from, to: end, text: lines[i]});
- from = end;
- }
- this.pushChains([chain], from == null && to == null);
- },
-
- pushChains: function(chains, doNotHighlight) {
- this.commit(doNotHighlight);
- this.addUndoLevel(this.updateTo(chains, "applyChain"));
- this.redoHistory = [];
- },
-
- // Clear the undo history, make the current document the start
- // position.
- reset: function() {
- this.history = []; this.redoHistory = [];
- },
-
- textAfter: function(br) {
- return this.after(br).text;
- },
-
- nodeAfter: function(br) {
- return this.after(br).to;
- },
-
- nodeBefore: function(br) {
- return this.before(br).from;
- },
-
- // Commit unless there are pending dirty nodes.
- tryCommit: function() {
- if (this.editor.highlightDirty()) this.commit();
- else this.scheduleCommit();
- },
-
- // Check whether the touched nodes hold any changes, if so, commit
- // them.
- commit: function(doNotHighlight) {
- this.parent.clearTimeout(this.commitTimeout);
- // Make sure there are no pending dirty nodes.
- if (!doNotHighlight) this.editor.highlightDirty(true);
- // Build set of chains.
- var chains = this.touchedChains(), self = this;
-
- if (chains.length) {
- this.addUndoLevel(this.updateTo(chains, "linkChain"));
- this.redoHistory = [];
- if (this.onChange) this.onChange();
- }
- },
-
- // [ end of public interface ]
-
- // Update the document with a given set of chains, return its
- // shadow. updateFunc should be "applyChain" or "linkChain". In the
- // second case, the chains are taken to correspond the the current
- // document, and only the state of the line data is updated. In the
- // first case, the content of the chains is also pushed iinto the
- // document.
- updateTo: function(chains, updateFunc) {
- var shadows = [], dirty = [];
- for (var i = 0; i < chains.length; i++) {
- shadows.push(this.shadowChain(chains[i]));
- dirty.push(this[updateFunc](chains[i]));
- }
- if (updateFunc == "applyChain")
- this.notifyDirty(dirty);
- return shadows;
- },
-
- // Notify the editor that some nodes have changed.
- notifyDirty: function(nodes) {
- forEach(nodes, method(this.editor, "addDirtyNode"))
- this.editor.scheduleHighlight();
- },
-
- // Link a chain into the DOM nodes (or the first/last links for null
- // nodes).
- linkChain: function(chain) {
- for (var i = 0; i < chain.length; i++) {
- var line = chain[i];
- if (line.from) line.from.historyAfter = line;
- else this.first = line;
- if (line.to) line.to.historyBefore = line;
- else this.last = line;
- }
- },
-
- // Get the line object after/before a given node.
- after: function(node) {
- return node ? node.historyAfter : this.first;
- },
- before: function(node) {
- return node ? node.historyBefore : this.last;
- },
-
- // Mark a node as touched if it has not already been marked.
- setTouched: function(node) {
- if (node) {
- if (!node.historyTouched) {
- this.touched.push(node);
- node.historyTouched = true;
- }
- }
- else {
- this.firstTouched = true;
- }
- },
-
- // Store a new set of undo info, throw away info if there is more of
- // it than allowed.
- addUndoLevel: function(diffs) {
- this.history.push(diffs);
- if (this.history.length > this.maxDepth)
- this.history.shift();
- },
-
- // Build chains from a set of touched nodes.
- touchedChains: function() {
- var self = this;
- // Compare two strings, treating nbsps as spaces.
- function compareText(a, b) {
- return a.replace(/\u00a0/g, " ") == b.replace(/\u00a0/g, " ");
- }
-
- // The temp system is a crummy hack to speed up determining
- // whether a (currently touched) node has a line object associated
- // with it. nullTemp is used to store the object for the first
- // line, other nodes get it stored in their historyTemp property.
- var nullTemp = null;
- function temp(node) {return node ? node.historyTemp : nullTemp;}
- function setTemp(node, line) {
- if (node) node.historyTemp = line;
- else nullTemp = line;
- }
-
- // Filter out unchanged lines and nodes that are no longer in the
- // document. Build up line objects for remaining nodes.
- var lines = [];
- if (self.firstTouched) self.touched.push(null);
- forEach(self.touched, function(node) {
- if (node) {
- node.historyTouched = false;
- if (node.parentNode != self.container)
- return;
- }
- else {
- self.firstTouched = false;
- }
-
- var text = [];
- for (var cur = node ? node.nextSibling : self.container.firstChild;
- cur && cur.nodeName != "BR"; cur = cur.nextSibling)
- if (cur.currentText) text.push(cur.currentText);
-
- var line = {from: node, to: cur, text: text.join("")};
- var shadow = self.after(node);
- if (!shadow || !compareText(shadow.text, line.text) || shadow.to != line.to) {
- lines.push(line);
- setTemp(node, line);
- }
- });
-
- // Get the BR element after/before the given node.
- function nextBR(node, dir) {
- var link = dir + "Sibling", search = node[link];
- while (search && search.nodeName != "BR")
- search = search[link];
- return search;
- }
-
- // Assemble line objects into chains by scanning the DOM tree
- // around them.
- var chains = []; self.touched = [];
- forEach(lines, function(line) {
- // Note that this makes the loop skip line objects that have
- // been pulled into chains by lines before them.
- if (!temp(line.from)) return;
-
- var chain = [], curNode = line.from;
- // Put any line objects (referred to by temp info) before this
- // one on the front of the array.
- while (true) {
- var curLine = temp(curNode);
- if (!curLine) break;
- chain.unshift(curLine);
- setTemp(curNode, null);
- if (!curNode) break;
- curNode = nextBR(curNode, "previous");
- }
- curNode = line.to;
- // Add lines after this one at end of array.
- while (true) {
- var curLine = temp(curNode);
- if (!curLine || !curNode) break;
- chain.push(curLine);
- setTemp(curNode, null);
- curNode = nextBR(curNode, "next");
- }
-
- // Chains that can not determine a valid 'shadow' -- a chain
- // currently stored in the DOM tree that has the same start and
- // end point -- are put back into the touched set, hoping they
- // will be valid next time.
- if (self.after(chain[0].from) && self.before(chain[chain.length - 1].to))
- chains.push(chain);
- else
- forEach(chain, function(line) {self.setTouched(line.from);});
- });
-
- return chains;
- },
-
- // Find the 'shadow' of a given chain by following the links in the
- // DOM nodes at its start and end.
- shadowChain: function(chain) {
- var shadows = [], next = this.after(chain[0].from), end = chain[chain.length - 1].to;
- while (true) {
- shadows.push(next);
- var nextNode = next.to;
- if (!nextNode || nextNode == end)
- break;
- else
- next = nextNode.historyAfter;
- }
- return shadows;
- },
-
- // Update the DOM tree to contain the lines specified in a given
- // chain, link this chain into the DOM nodes.
- applyChain: function(chain) {
- // Some attempt is made to prevent the cursor from jumping
- // randomly when an undo or redo happens. It still behaves a bit
- // strange sometimes.
- var cursor = select.cursorPos(this.container, false), self = this;
-
- // Remove all nodes in the DOM tree between from and to (null for
- // start/end of container).
- function removeRange(from, to) {
- var pos = from ? from.nextSibling : self.container.firstChild;
- while (pos != to) {
- var temp = pos.nextSibling;
- removeElement(pos);
- pos = temp;
- }
- }
-
- var start = chain[0].from, end = chain[chain.length - 1].to;
- // Clear the space where this change has to be made.
- removeRange(start, end);
-
- // Build a function that will insert nodes before the end node of
- // this chain.
- var insert = end ?
- function(node) {self.container.insertBefore(node, end);}
- : function(node) {self.container.appendChild(node);};
-
- // Insert the content specified by the chain into the DOM tree.
- for (var i = 0; i < chain.length; i++) {
- var line = chain[i];
- // The start and end of the space are already correct, but BR
- // tags inside it have to be put back.
- if (i > 0)
- insert(line.from);
- // Add the text.
- var textNode = this.container.ownerDocument.createTextNode(line.text);
- insert(textNode);
- // See if the cursor was on this line. Put it back, adjusting
- // for changed line length, if it was.
- if (cursor && cursor.node == line.from) {
- var cursordiff = 0;
- var prev = this.after(line.from);
- if (prev && i == chain.length - 1) {
- // Only adjust if the cursor is after the unchanged part of
- // the line.
- for (var match = 0; match < cursor.offset &&
- line.text.charAt(match) == prev.text.charAt(match); match++);
- if (cursor.offset > match)
- cursordiff = line.text.length - prev.text.length;
- }
- select.setCursorPos(this.container, {node: line.from, offset: Math.max(0, cursor.offset + cursordiff)});
- }
- // Cursor was in removed line, this is last new line.
- else if (cursor && (i == chain.length - 1) && cursor.node && cursor.node.parentNode != this.container) {
- select.setCursorPos(this.container, {node: line.from, offset: line.text.length});
- }
- }
-
- // Anchor the chain in the DOM tree.
- this.linkChain(chain);
- return start;
- }
-};
diff --git a/o3d/samples/third_party/codemirror/js/util.js b/o3d/samples/third_party/codemirror/js/util.js
deleted file mode 100644
index f866a29..0000000
--- a/o3d/samples/third_party/codemirror/js/util.js
+++ /dev/null
@@ -1,134 +0,0 @@
-/* A few useful utility functions. */
-
-// Capture a method on an object.
-function method(obj, name) {
- return function() {obj[name].apply(obj, arguments);};
-}
-
-// Write properties from an object into another object.
-function update(obj, from) {
- for (var name in from)
- obj[name] = from[name];
- return obj;
-}
-
-// The value used to signal the end of a sequence in iterators.
-var StopIteration = {toString: function() {return "StopIteration"}};
-
-// Checks whether the argument is an iterator or a regular sequence,
-// turns it into an iterator.
-function iter(seq) {
- var i = 0;
- if (seq.next) return seq;
- else return {
- next: function() {
- if (i >= seq.length) throw StopIteration;
- else return seq[++i];
- }
- };
-}
-
-// Apply a function to each element in a sequence.
-function forEach(iter, f) {
- if (iter.next) {
- try {while (true) f(iter.next());}
- catch (e) {if (e != StopIteration) throw e;}
- }
- else {
- for (var i = 0; i < iter.length; i++)
- f(iter[i]);
- }
-}
-
-// Map a function over a sequence, producing an array of results.
-function map(iter, f) {
- var accum = [];
- forEach(iter, function(val) {accum.push(f(val));});
- return accum;
-}
-
-// Create a predicate function that tests a string againsts a given
-// regular expression.
-function matcher(regexp){
- return function(value){return regexp.test(value);};
-}
-
-// Test whether a DOM node has a certain CSS class. Much faster than
-// the MochiKit equivalent, for some reason.
-function hasClass(element, className){
- var classes = element.className;
- return classes && new RegExp("(^| )" + className + "($| )").test(classes);
-}
-
-// Insert a DOM node after another node.
-function insertAfter(newNode, oldNode) {
- var parent = oldNode.parentNode;
- parent.insertBefore(newNode, oldNode.nextSibling);
- return newNode;
-}
-
-function removeElement(node) {
- if (node.parentNode)
- node.parentNode.removeChild(node);
-}
-
-function clearElement(node) {
- while (node.firstChild)
- node.removeChild(node.firstChild);
-}
-
-// Check whether a node is contained in another one.
-function isAncestor(node, child) {
- while (child = child.parentNode) {
- if (node == child)
- return true;
- }
- return false;
-}
-
-// The non-breaking space character.
-var nbsp = "\u00a0";
-var matching = {"{": "}", "[": "]", "(": ")",
- "}": "{", "]": "[", ")": "("};
-
-// Standardize a few unportable event properties.
-function normalizeEvent(event) {
- if (!event.stopPropagation) {
- event.stopPropagation = function() {this.cancelBubble = true;};
- event.preventDefault = function() {this.returnValue = false;};
- }
- if (!event.stop) {
- event.stop = function() {
- this.stopPropagation();
- this.preventDefault();
- };
- }
-
- if (event.type == "keypress") {
- if (event.charCode === 0 || event.charCode == undefined)
- event.code = event.keyCode;
- else
- event.code = event.charCode;
- event.character = String.fromCharCode(event.code);
- }
- return event;
-}
-
-// Portably register event handlers.
-function addEventHandler(node, type, handler) {
- function wrapHandler(event) {
- handler(normalizeEvent(event || window.event));
- }
- if (typeof node.addEventListener == "function") {
- node.addEventListener(type, wrapHandler, false);
- return function() { node.removeEventListener(type, wrapHandler, false); };
- }
- else {
- node.attachEvent("on" + type, wrapHandler);
- return function() { node.detachEvent("on" + type, wrapHandler); };
- }
-}
-
-function removeEventHandler(handler) {
- handler();
-}
diff --git a/o3d/samples/third_party/json/json2-min.js b/o3d/samples/third_party/json/json2-min.js
deleted file mode 100644
index a2c7769..0000000
--- a/o3d/samples/third_party/json/json2-min.js
+++ /dev/null
@@ -1,29 +0,0 @@
-
-if(!this.JSON){this.JSON={};}
-(function(){function f(n){return n<10?'0'+n:n;}
-if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+
-f(this.getUTCMonth()+1)+'-'+
-f(this.getUTCDate())+'T'+
-f(this.getUTCHours())+':'+
-f(this.getUTCMinutes())+':'+
-f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
-var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
-function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
-if(typeof rep==='function'){value=rep.call(holder,key,value);}
-switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
-gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
-v=partial.length===0?'[]':gap?'[\n'+gap+
-partial.join(',\n'+gap)+'\n'+
-mind+']':'['+partial.join(',')+']';gap=mind;return v;}
-if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
-v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
-mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
-if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
-rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
-return str('',{'':value});};}
-if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
-return reviver.call(holder,key,value);}
-text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
-('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
-if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
-throw new SyntaxError('JSON.parse');};}}()); \ No newline at end of file
diff --git a/o3d/samples/third_party/json/json2.js b/o3d/samples/third_party/json/json2.js
deleted file mode 100644
index a1a3b17..0000000
--- a/o3d/samples/third_party/json/json2.js
+++ /dev/null
@@ -1,482 +0,0 @@
-/*
- http://www.JSON.org/json2.js
- 2010-03-20
-
- Public Domain.
-
- NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
-
- See http://www.JSON.org/js.html
-
-
- This code should be minified before deployment.
- See http://javascript.crockford.com/jsmin.html
-
- USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
- NOT CONTROL.
-
-
- This file creates a global JSON object containing two methods: stringify
- and parse.
-
- JSON.stringify(value, replacer, space)
- value any JavaScript value, usually an object or array.
-
- replacer an optional parameter that determines how object
- values are stringified for objects. It can be a
- function or an array of strings.
-
- space an optional parameter that specifies the indentation
- of nested structures. If it is omitted, the text will
- be packed without extra whitespace. If it is a number,
- it will specify the number of spaces to indent at each
- level. If it is a string (such as '\t' or '&nbsp;'),
- it contains the characters used to indent at each level.
-
- This method produces a JSON text from a JavaScript value.
-
- When an object value is found, if the object contains a toJSON
- method, its toJSON method will be called and the result will be
- stringified. A toJSON method does not serialize: it returns the
- value represented by the name/value pair that should be serialized,
- or undefined if nothing should be serialized. The toJSON method
- will be passed the key associated with the value, and this will be
- bound to the value
-
- For example, this would serialize Dates as ISO strings.
-
- Date.prototype.toJSON = function (key) {
- function f(n) {
- // Format integers to have at least two digits.
- return n < 10 ? '0' + n : n;
- }
-
- return this.getUTCFullYear() + '-' +
- f(this.getUTCMonth() + 1) + '-' +
- f(this.getUTCDate()) + 'T' +
- f(this.getUTCHours()) + ':' +
- f(this.getUTCMinutes()) + ':' +
- f(this.getUTCSeconds()) + 'Z';
- };
-
- You can provide an optional replacer method. It will be passed the
- key and value of each member, with this bound to the containing
- object. The value that is returned from your method will be
- serialized. If your method returns undefined, then the member will
- be excluded from the serialization.
-
- If the replacer parameter is an array of strings, then it will be
- used to select the members to be serialized. It filters the results
- such that only members with keys listed in the replacer array are
- stringified.
-
- Values that do not have JSON representations, such as undefined or
- functions, will not be serialized. Such values in objects will be
- dropped; in arrays they will be replaced with null. You can use
- a replacer function to replace those with JSON values.
- JSON.stringify(undefined) returns undefined.
-
- The optional space parameter produces a stringification of the
- value that is filled with line breaks and indentation to make it
- easier to read.
-
- If the space parameter is a non-empty string, then that string will
- be used for indentation. If the space parameter is a number, then
- the indentation will be that many spaces.
-
- Example:
-
- text = JSON.stringify(['e', {pluribus: 'unum'}]);
- // text is '["e",{"pluribus":"unum"}]'
-
-
- text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
- // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
-
- text = JSON.stringify([new Date()], function (key, value) {
- return this[key] instanceof Date ?
- 'Date(' + this[key] + ')' : value;
- });
- // text is '["Date(---current time---)"]'
-
-
- JSON.parse(text, reviver)
- This method parses a JSON text to produce an object or array.
- It can throw a SyntaxError exception.
-
- The optional reviver parameter is a function that can filter and
- transform the results. It receives each of the keys and values,
- and its return value is used instead of the original value.
- If it returns what it received, then the structure is not modified.
- If it returns undefined then the member is deleted.
-
- Example:
-
- // Parse the text. Values that look like ISO date strings will
- // be converted to Date objects.
-
- myData = JSON.parse(text, function (key, value) {
- var a;
- if (typeof value === 'string') {
- a =
-/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
- if (a) {
- return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
- +a[5], +a[6]));
- }
- }
- return value;
- });
-
- myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
- var d;
- if (typeof value === 'string' &&
- value.slice(0, 5) === 'Date(' &&
- value.slice(-1) === ')') {
- d = new Date(value.slice(5, -1));
- if (d) {
- return d;
- }
- }
- return value;
- });
-
-
- This is a reference implementation. You are free to copy, modify, or
- redistribute.
-*/
-
-/*jslint evil: true, strict: false */
-
-/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
- call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
- getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
- lastIndex, length, parse, prototype, push, replace, slice, stringify,
- test, toJSON, toString, valueOf
-*/
-
-
-// Create a JSON object only if one does not already exist. We create the
-// methods in a closure to avoid creating global variables.
-
-if (!this.JSON) {
- this.JSON = {};
-}
-
-(function () {
-
- function f(n) {
- // Format integers to have at least two digits.
- return n < 10 ? '0' + n : n;
- }
-
- if (typeof Date.prototype.toJSON !== 'function') {
-
- Date.prototype.toJSON = function (key) {
-
- return isFinite(this.valueOf()) ?
- this.getUTCFullYear() + '-' +
- f(this.getUTCMonth() + 1) + '-' +
- f(this.getUTCDate()) + 'T' +
- f(this.getUTCHours()) + ':' +
- f(this.getUTCMinutes()) + ':' +
- f(this.getUTCSeconds()) + 'Z' : null;
- };
-
- String.prototype.toJSON =
- Number.prototype.toJSON =
- Boolean.prototype.toJSON = function (key) {
- return this.valueOf();
- };
- }
-
- var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
- escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
- gap,
- indent,
- meta = { // table of character substitutions
- '\b': '\\b',
- '\t': '\\t',
- '\n': '\\n',
- '\f': '\\f',
- '\r': '\\r',
- '"' : '\\"',
- '\\': '\\\\'
- },
- rep;
-
-
- function quote(string) {
-
-// If the string contains no control characters, no quote characters, and no
-// backslash characters, then we can safely slap some quotes around it.
-// Otherwise we must also replace the offending characters with safe escape
-// sequences.
-
- escapable.lastIndex = 0;
- return escapable.test(string) ?
- '"' + string.replace(escapable, function (a) {
- var c = meta[a];
- return typeof c === 'string' ? c :
- '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
- }) + '"' :
- '"' + string + '"';
- }
-
-
- function str(key, holder) {
-
-// Produce a string from holder[key].
-
- var i, // The loop counter.
- k, // The member key.
- v, // The member value.
- length,
- mind = gap,
- partial,
- value = holder[key];
-
-// If the value has a toJSON method, call it to obtain a replacement value.
-
- if (value && typeof value === 'object' &&
- typeof value.toJSON === 'function') {
- value = value.toJSON(key);
- }
-
-// If we were called with a replacer function, then call the replacer to
-// obtain a replacement value.
-
- if (typeof rep === 'function') {
- value = rep.call(holder, key, value);
- }
-
-// What happens next depends on the value's type.
-
- switch (typeof value) {
- case 'string':
- return quote(value);
-
- case 'number':
-
-// JSON numbers must be finite. Encode non-finite numbers as null.
-
- return isFinite(value) ? String(value) : 'null';
-
- case 'boolean':
- case 'null':
-
-// If the value is a boolean or null, convert it to a string. Note:
-// typeof null does not produce 'null'. The case is included here in
-// the remote chance that this gets fixed someday.
-
- return String(value);
-
-// If the type is 'object', we might be dealing with an object or an array or
-// null.
-
- case 'object':
-
-// Due to a specification blunder in ECMAScript, typeof null is 'object',
-// so watch out for that case.
-
- if (!value) {
- return 'null';
- }
-
-// Make an array to hold the partial results of stringifying this object value.
-
- gap += indent;
- partial = [];
-
-// Is the value an array?
-
- if (Object.prototype.toString.apply(value) === '[object Array]') {
-
-// The value is an array. Stringify every element. Use null as a placeholder
-// for non-JSON values.
-
- length = value.length;
- for (i = 0; i < length; i += 1) {
- partial[i] = str(i, value) || 'null';
- }
-
-// Join all of the elements together, separated with commas, and wrap them in
-// brackets.
-
- v = partial.length === 0 ? '[]' :
- gap ? '[\n' + gap +
- partial.join(',\n' + gap) + '\n' +
- mind + ']' :
- '[' + partial.join(',') + ']';
- gap = mind;
- return v;
- }
-
-// If the replacer is an array, use it to select the members to be stringified.
-
- if (rep && typeof rep === 'object') {
- length = rep.length;
- for (i = 0; i < length; i += 1) {
- k = rep[i];
- if (typeof k === 'string') {
- v = str(k, value);
- if (v) {
- partial.push(quote(k) + (gap ? ': ' : ':') + v);
- }
- }
- }
- } else {
-
-// Otherwise, iterate through all of the keys in the object.
-
- for (k in value) {
- if (Object.hasOwnProperty.call(value, k)) {
- v = str(k, value);
- if (v) {
- partial.push(quote(k) + (gap ? ': ' : ':') + v);
- }
- }
- }
- }
-
-// Join all of the member texts together, separated with commas,
-// and wrap them in braces.
-
- v = partial.length === 0 ? '{}' :
- gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
- mind + '}' : '{' + partial.join(',') + '}';
- gap = mind;
- return v;
- }
- }
-
-// If the JSON object does not yet have a stringify method, give it one.
-
- if (typeof JSON.stringify !== 'function') {
- JSON.stringify = function (value, replacer, space) {
-
-// The stringify method takes a value and an optional replacer, and an optional
-// space parameter, and returns a JSON text. The replacer can be a function
-// that can replace values, or an array of strings that will select the keys.
-// A default replacer method can be provided. Use of the space parameter can
-// produce text that is more easily readable.
-
- var i;
- gap = '';
- indent = '';
-
-// If the space parameter is a number, make an indent string containing that
-// many spaces.
-
- if (typeof space === 'number') {
- for (i = 0; i < space; i += 1) {
- indent += ' ';
- }
-
-// If the space parameter is a string, it will be used as the indent string.
-
- } else if (typeof space === 'string') {
- indent = space;
- }
-
-// If there is a replacer, it must be a function or an array.
-// Otherwise, throw an error.
-
- rep = replacer;
- if (replacer && typeof replacer !== 'function' &&
- (typeof replacer !== 'object' ||
- typeof replacer.length !== 'number')) {
- throw new Error('JSON.stringify');
- }
-
-// Make a fake root object containing our value under the key of ''.
-// Return the result of stringifying the value.
-
- return str('', {'': value});
- };
- }
-
-
-// If the JSON object does not yet have a parse method, give it one.
-
- if (typeof JSON.parse !== 'function') {
- JSON.parse = function (text, reviver) {
-
-// The parse method takes a text and an optional reviver function, and returns
-// a JavaScript value if the text is a valid JSON text.
-
- var j;
-
- function walk(holder, key) {
-
-// The walk method is used to recursively walk the resulting structure so
-// that modifications can be made.
-
- var k, v, value = holder[key];
- if (value && typeof value === 'object') {
- for (k in value) {
- if (Object.hasOwnProperty.call(value, k)) {
- v = walk(value, k);
- if (v !== undefined) {
- value[k] = v;
- } else {
- delete value[k];
- }
- }
- }
- }
- return reviver.call(holder, key, value);
- }
-
-
-// Parsing happens in four stages. In the first stage, we replace certain
-// Unicode characters with escape sequences. JavaScript handles many characters
-// incorrectly, either silently deleting them, or treating them as line endings.
-
- text = String(text);
- cx.lastIndex = 0;
- if (cx.test(text)) {
- text = text.replace(cx, function (a) {
- return '\\u' +
- ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
- });
- }
-
-// In the second stage, we run the text against regular expressions that look
-// for non-JSON patterns. We are especially concerned with '()' and 'new'
-// because they can cause invocation, and '=' because it can cause mutation.
-// But just to be safe, we want to reject all unexpected forms.
-
-// We split the second stage into 4 regexp operations in order to work around
-// crippling inefficiencies in IE's and Safari's regexp engines. First we
-// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
-// replace all simple value tokens with ']' characters. Third, we delete all
-// open brackets that follow a colon or comma or that begin the text. Finally,
-// we look to see that the remaining characters are only whitespace or ']' or
-// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
-
- if (/^[\],:{}\s]*$/.
-test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
-replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
-replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
-
-// In the third stage we use the eval function to compile the text into a
-// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
-// in JavaScript: it can begin a block or an object literal. We wrap the text
-// in parens to eliminate the ambiguity.
-
- j = eval('(' + text + ')');
-
-// In the optional fourth stage, we recursively walk the new structure, passing
-// each name/value pair to a reviver function for possible transformation.
-
- return typeof reviver === 'function' ?
- walk({'': j}, '') : j;
- }
-
-// If the text is not JSON parseable, then a SyntaxError is thrown.
-
- throw new SyntaxError('JSON.parse');
- };
- }
-}());
diff --git a/o3d/samples/third_party/lightbox/LICENSE-lightbox-iframe.txt b/o3d/samples/third_party/lightbox/LICENSE-lightbox-iframe.txt
deleted file mode 100644
index b4fe311..0000000
--- a/o3d/samples/third_party/lightbox/LICENSE-lightbox-iframe.txt
+++ /dev/null
@@ -1,66 +0,0 @@
-According to particletree.com, everything they publish is under the following
-Creative Commons license. This version of lightbox-iframe is a derivative of
-the one from particletree.com, as stated in the source files.
-
-
-http://creativecommons.org/licenses/by/2.5/
-
-
-Attribution 2.5
-
-CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM ITS USE.
-License
-
-THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
-
-BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
-
-1. Definitions
-
-"Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License.
-"Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License.
-"Licensor" means the individual or entity that offers the Work under the terms of this License.
-"Original Author" means the individual or entity who created the Work.
-"Work" means the copyrightable work of authorship offered under the terms of this License.
-"You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
-2. Fair Use Rights. Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws.
-
-3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:
-
-to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works;
-to create and reproduce Derivative Works;
-to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works;
-to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works.
-For the avoidance of doubt, where the work is a musical composition:
-
-Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work.
-Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights agency or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions).
-Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions).
-The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved.
-
-4. Restrictions.The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:
-
-You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(b), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(b), as requested.
-If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit.
-5. Representations, Warranties and Disclaimer
-
-UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
-
-6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-7. Termination
-
-This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
-Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.
-8. Miscellaneous
-
-Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
-Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
-If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
-No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
-This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.
-Creative Commons is not a party to this License, and makes no warranty whatsoever in connection with the Work. Creative Commons will not be liable to You or any party on any legal theory for any damages whatsoever, including without limitation any general, special, incidental or consequential damages arising in connection to this license. Notwithstanding the foregoing two (2) sentences, if Creative Commons has expressly identified itself as the Licensor hereunder, it shall have all rights and obligations of Licensor.
-
-Except for the limited purpose of indicating to the public that the Work is licensed under the CCPL, neither party will use the trademark "Creative Commons" or any related trademark or logo of Creative Commons without the prior written consent of Creative Commons. Any permitted use will be in compliance with Creative Commons' then-current trademark usage guidelines, as may be published on its website or otherwise made available upon request from time to time.
-
-Creative Commons may be contacted at http://creativecommons.org/.
diff --git a/o3d/samples/third_party/lightbox/LICENSE-prototype.txt b/o3d/samples/third_party/lightbox/LICENSE-prototype.txt
deleted file mode 100644
index 61e4918..0000000
--- a/o3d/samples/third_party/lightbox/LICENSE-prototype.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-Copyright (c) 2005-2008 Sam Stephenson
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/o3d/samples/third_party/lightbox/lightbox-iframe.js b/o3d/samples/third_party/lightbox/lightbox-iframe.js
deleted file mode 100644
index bcf492f..0000000
--- a/o3d/samples/third_party/lightbox/lightbox-iframe.js
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
-Created By: Chris Campbell
-Modified By: Noah Winecoff (http://www.findmotive.com)
-Website: http://particletree.com
-Date: 2/1/2006
-
-Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
-*/
-
-/*-------------------------------GLOBAL VARIABLES------------------------------------*/
-
-var detect = navigator.userAgent.toLowerCase();
-var OS,browser,version,total,thestring;
-
-/*-----------------------------------------------------------------------------------------------*/
-
-//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/
-
-function getBrowserInfo() {
- if (checkIt('konqueror')) {
- browser = "Konqueror";
- OS = "Linux";
- }
- else if (checkIt('safari')) browser = "Safari"
- else if (checkIt('omniweb')) browser = "OmniWeb"
- else if (checkIt('opera')) browser = "Opera"
- else if (checkIt('webtv')) browser = "WebTV";
- else if (checkIt('icab')) browser = "iCab"
- else if (checkIt('msie')) browser = "Internet Explorer"
- else if (!checkIt('compatible')) {
- browser = "Netscape Navigator"
- version = detect.charAt(8);
- }
- else browser = "An unknown browser";
-
- if (!version) version = detect.charAt(place + thestring.length);
-
- if (!OS) {
- if (checkIt('linux')) OS = "Linux";
- else if (checkIt('x11')) OS = "Unix";
- else if (checkIt('mac')) OS = "Mac"
- else if (checkIt('win')) OS = "Windows"
- else OS = "an unknown operating system";
- }
-}
-
-function checkIt(string) {
- place = detect.indexOf(string) + 1;
- thestring = string;
- return place;
-}
-
-/*-----------------------------------------------------------------------------------------------*/
-
-Event.observe(window, 'load', initialize, false);
-Event.observe(window, 'load', getBrowserInfo, false);
-Event.observe(window, 'unload', Event.unloadCache, false);
-
-var lightbox = Class.create();
-
-lightbox.prototype = {
-
- yPos : 0,
- xPos : 0,
-
- initialize: function(ctrl) {
- this.content = ctrl.href;
- Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
- ctrl.onclick = function(){return false;};
- },
-
- // Turn everything on - mainly the IE fixes
- activate: function(){
- if (browser == 'Internet Explorer'){
- this.getScroll();
- this.prepareIE('100%', 'hidden');
- this.setScroll(0,0);
- this.hideSelects('hidden');
- }
- this.displayLightbox("block");
- },
-
- // Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
- prepareIE: function(height, overflow){
- bod = document.getElementsByTagName('body')[0];
- bod.style.height = height;
- bod.style.overflow = overflow;
-
- htm = document.getElementsByTagName('html')[0];
- htm.style.height = height;
- htm.style.overflow = overflow;
- },
-
- // In IE, select elements hover on top of the lightbox
- hideSelects: function(visibility){
- selects = document.getElementsByTagName('select');
- for(i = 0; i < selects.length; i++) {
- selects[i].style.visibility = visibility;
- }
- },
-
- // Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
- getScroll: function(){
- if (self.pageYOffset) {
- this.yPos = self.pageYOffset;
- } else if (document.documentElement && document.documentElement.scrollTop){
- this.yPos = document.documentElement.scrollTop;
- } else if (document.body) {
- this.yPos = document.body.scrollTop;
- }
- },
-
- setScroll: function(x, y){
- window.scrollTo(x, y);
- },
-
- displayLightbox: function(display){
- $('overlay').style.display = display;
- $('lightbox').style.display = display;
- if(display != 'none') this.loadInfo();
- },
-
- // Write an iFrame instead of using an AJAX call to pull the content
- loadInfo: function() {
- info = "<div id='lbContent'><center><a href='#' class='lbAction' rel='deactivate'>close (x)</a></center><iframe frameborder=\"0\" width=\"100%\" height=\"100%\" src=\"" + this.content + "\"</iframe></div>";
- new Insertion.Before($('lbLoadMessage'), info)
- $('lightbox').className = "done";
- this.actions();
-
- },
-
- // Search through new links within the lightbox, and attach click event
- actions: function(){
- lbActions = document.getElementsByClassName('lbAction');
-
- for(i = 0; i < lbActions.length; i++) {
- Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
- lbActions[i].onclick = function(){return false;};
- }
-
- },
-
- // Example of creating your own functionality once lightbox is initiated
- insert: function(e){
- link = Event.element(e).parentNode;
- Element.remove($('lbContent'));
-
- var myAjax = new Ajax.Request(
- link.href,
- {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
- );
-
- },
-
- // Example of creating your own functionality once lightbox is initiated
- deactivate: function(){
- Element.remove($('lbContent'));
-
- if (browser == "Internet Explorer"){
- this.setScroll(0,this.yPos);
- this.prepareIE("auto", "auto");
- this.hideSelects("visible");
- }
-
- this.displayLightbox("none");
- }
-}
-
-/*-----------------------------------------------------------------------------------------------*/
-
-// Onload, make all links that need to trigger a lightbox active
-function initialize(){
- addLightboxMarkup();
- lbox = document.getElementsByClassName('lbOn');
- for(i = 0; i < lbox.length; i++) {
- valid = new lightbox(lbox[i]);
- }
-}
-
-// Add in markup necessary to make this work. Basically two divs:
-// Overlay holds the shadow
-// Lightbox is the centered square that the content is put into.
-function addLightboxMarkup() {
- bod = document.getElementsByTagName('body')[0];
- overlay = document.createElement('div');
- overlay.id = 'overlay';
- lb = document.createElement('div');
- lb.id = 'lbinner';
- // lb.className = 'loading';
- lb.innerHTML = '<div id="lbLoadMessage">' +
- 'loading' +
- '</div>';
- lbcontainer = document.createElement('div');
- lbcontainer.id = 'lightbox';
- lb.className = 'loading';
- lbcontainer.appendChild(lb);
- bod.appendChild(overlay);
- bod.appendChild(lbcontainer);
-}
diff --git a/o3d/samples/third_party/lightbox/lightbox.css b/o3d/samples/third_party/lightbox/lightbox.css
deleted file mode 100644
index 363969b..0000000
--- a/o3d/samples/third_party/lightbox/lightbox.css
+++ /dev/null
@@ -1,74 +0,0 @@
-/* - - - - - - - - - - - - - - - - - - - - -
-
-Title : Lightbox CSS
-Author : Kevin Hale
-Modified By: Noah Winecoff (http://www.findmotive.com)
-URL : http://particletree.com/features/lightbox-gone-wild/
-
-Created : January 13, 2006
-Modified : February 1, 2006
-
-- - - - - - - - - - - - - - - - - - - - - */
-
-#lightbox{
- display:none;
-/* position: absolute;*/
- top:0%;
-/* left:50%;*/
- z-index:9999;
- width:100%;
- height:100%;
-}
-#lightbox[id]{
- position:fixed;
-}
-
-#lbinner {
- margin: 0 auto;
- border:10px solid #555555;
- background:#FDFCE9;
- text-align:left;
- max-width: 900px;
- width:100%;
- height:90%;
- margin-top: 10px;
- z-index:9999;
- padding-bottom: 20px;
-}
-
-#overlay{
- display:none;
- position:absolute;
- top:0;
- left:0;
- width:100%;
- height:100%;
- z-index:5000;
- background-color:#000;
- -moz-opacity: 0.8;
- opacity:.80;
- filter: alpha(opacity=80);
-}
-#overlay[id]{
- position:fixed;
-}
-
-#lightbox.done #lbLoadMessage{
- display:none;
-}
-#lightbox.done #lbContent{
- display:block;
- width: 100%;
- height: 100%;
-}
-#lightbox.loading #lbContent{
- display:none;
-}
-#lightbox.loading #lbLoadMessage{
- display:block;
-}
-
-#lightbox.done img{
- width:100%;
- height:100%;
-} \ No newline at end of file
diff --git a/o3d/samples/third_party/lightbox/prototype.js b/o3d/samples/third_party/lightbox/prototype.js
deleted file mode 100644
index b19bf53..0000000
--- a/o3d/samples/third_party/lightbox/prototype.js
+++ /dev/null
@@ -1,1785 +0,0 @@
-/* Prototype JavaScript framework, version 1.4.0
- * (c) 2005 Sam Stephenson <sam@conio.net>
- *
- * THIS FILE IS AUTOMATICALLY GENERATED. When sending patches, please diff
- * against the source tree, available from the Prototype darcs repository.
- *
- * Prototype is freely distributable under the terms of an MIT-style license.
- *
- * For details, see the Prototype web site: http://prototype.conio.net/
- *
-/*--------------------------------------------------------------------------*/
-
-var Prototype = {
- Version: '1.4.0',
- ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
-
- emptyFunction: function() {},
- K: function(x) {return x}
-}
-
-var Class = {
- create: function() {
- return function() {
- this.initialize.apply(this, arguments);
- }
- }
-}
-
-var Abstract = new Object();
-
-Object.extend = function(destination, source) {
- for (property in source) {
- destination[property] = source[property];
- }
- return destination;
-}
-
-Object.inspect = function(object) {
- try {
- if (object == undefined) return 'undefined';
- if (object == null) return 'null';
- return object.inspect ? object.inspect() : object.toString();
- } catch (e) {
- if (e instanceof RangeError) return '...';
- throw e;
- }
-}
-
-Function.prototype.bind = function() {
- var __method = this, args = $A(arguments), object = args.shift();
- return function() {
- return __method.apply(object, args.concat($A(arguments)));
- }
-}
-
-Function.prototype.bindAsEventListener = function(object) {
- var __method = this;
- return function(event) {
- return __method.call(object, event || window.event);
- }
-}
-
-Object.extend(Number.prototype, {
- toColorPart: function() {
- var digits = this.toString(16);
- if (this < 16) return '0' + digits;
- return digits;
- },
-
- succ: function() {
- return this + 1;
- },
-
- times: function(iterator) {
- $R(0, this, true).each(iterator);
- return this;
- }
-});
-
-var Try = {
- these: function() {
- var returnValue;
-
- for (var i = 0; i < arguments.length; i++) {
- var lambda = arguments[i];
- try {
- returnValue = lambda();
- break;
- } catch (e) {}
- }
-
- return returnValue;
- }
-}
-
-/*--------------------------------------------------------------------------*/
-
-var PeriodicalExecuter = Class.create();
-PeriodicalExecuter.prototype = {
- initialize: function(callback, frequency) {
- this.callback = callback;
- this.frequency = frequency;
- this.currentlyExecuting = false;
-
- this.registerCallback();
- },
-
- registerCallback: function() {
- setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
- },
-
- onTimerEvent: function() {
- if (!this.currentlyExecuting) {
- try {
- this.currentlyExecuting = true;
- this.callback();
- } finally {
- this.currentlyExecuting = false;
- }
- }
- }
-}
-
-/*--------------------------------------------------------------------------*/
-
-function $() {
- var elements = new Array();
-
- for (var i = 0; i < arguments.length; i++) {
- var element = arguments[i];
- if (typeof element == 'string')
- element = document.getElementById(element);
-
- if (arguments.length == 1)
- return element;
-
- elements.push(element);
- }
-
- return elements;
-}
-Object.extend(String.prototype, {
- stripTags: function() {
- return this.replace(/<\/?[^>]+>/gi, '');
- },
-
- stripScripts: function() {
- return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
- },
-
- extractScripts: function() {
- var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
- var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
- return (this.match(matchAll) || []).map(function(scriptTag) {
- return (scriptTag.match(matchOne) || ['', ''])[1];
- });
- },
-
- evalScripts: function() {
- return this.extractScripts().map(eval);
- },
-
- escapeHTML: function() {
- var div = document.createElement('div');
- var text = document.createTextNode(this);
- div.appendChild(text);
- return div.innerHTML;
- },
-
- unescapeHTML: function() {
- var div = document.createElement('div');
- div.innerHTML = this.stripTags();
- return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
- },
-
- toQueryParams: function() {
- var pairs = this.match(/^\??(.*)$/)[1].split('&');
- return pairs.inject({}, function(params, pairString) {
- var pair = pairString.split('=');
- params[pair[0]] = pair[1];
- return params;
- });
- },
-
- toArray: function() {
- return this.split('');
- },
-
- camelize: function() {
- var oStringList = this.split('-');
- if (oStringList.length == 1) return oStringList[0];
-
- var camelizedString = this.indexOf('-') == 0
- ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
- : oStringList[0];
-
- for (var i = 1, len = oStringList.length; i < len; i++) {
- var s = oStringList[i];
- camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
- }
-
- return camelizedString;
- },
-
- inspect: function() {
- return "'" + this.replace('\\', '\\\\').replace("'", '\\\'') + "'";
- }
-});
-
-String.prototype.parseQuery = String.prototype.toQueryParams;
-
-var $break = new Object();
-var $continue = new Object();
-
-var Enumerable = {
- each: function(iterator) {
- var index = 0;
- try {
- this._each(function(value) {
- try {
- iterator(value, index++);
- } catch (e) {
- if (e != $continue) throw e;
- }
- });
- } catch (e) {
- if (e != $break) throw e;
- }
- },
-
- all: function(iterator) {
- var result = true;
- this.each(function(value, index) {
- result = result && !!(iterator || Prototype.K)(value, index);
- if (!result) throw $break;
- });
- return result;
- },
-
- any: function(iterator) {
- var result = true;
- this.each(function(value, index) {
- if (result = !!(iterator || Prototype.K)(value, index))
- throw $break;
- });
- return result;
- },
-
- collect: function(iterator) {
- var results = [];
- this.each(function(value, index) {
- results.push(iterator(value, index));
- });
- return results;
- },
-
- detect: function (iterator) {
- var result;
- this.each(function(value, index) {
- if (iterator(value, index)) {
- result = value;
- throw $break;
- }
- });
- return result;
- },
-
- findAll: function(iterator) {
- var results = [];
- this.each(function(value, index) {
- if (iterator(value, index))
- results.push(value);
- });
- return results;
- },
-
- grep: function(pattern, iterator) {
- var results = [];
- this.each(function(value, index) {
- var stringValue = value.toString();
- if (stringValue.match(pattern))
- results.push((iterator || Prototype.K)(value, index));
- })
- return results;
- },
-
- include: function(object) {
- var found = false;
- this.each(function(value) {
- if (value == object) {
- found = true;
- throw $break;
- }
- });
- return found;
- },
-
- inject: function(memo, iterator) {
- this.each(function(value, index) {
- memo = iterator(memo, value, index);
- });
- return memo;
- },
-
- invoke: function(method) {
- var args = $A(arguments).slice(1);
- return this.collect(function(value) {
- return value[method].apply(value, args);
- });
- },
-
- max: function(iterator) {
- var result;
- this.each(function(value, index) {
- value = (iterator || Prototype.K)(value, index);
- if (value >= (result || value))
- result = value;
- });
- return result;
- },
-
- min: function(iterator) {
- var result;
- this.each(function(value, index) {
- value = (iterator || Prototype.K)(value, index);
- if (value <= (result || value))
- result = value;
- });
- return result;
- },
-
- partition: function(iterator) {
- var trues = [], falses = [];
- this.each(function(value, index) {
- ((iterator || Prototype.K)(value, index) ?
- trues : falses).push(value);
- });
- return [trues, falses];
- },
-
- pluck: function(property) {
- var results = [];
- this.each(function(value, index) {
- results.push(value[property]);
- });
- return results;
- },
-
- reject: function(iterator) {
- var results = [];
- this.each(function(value, index) {
- if (!iterator(value, index))
- results.push(value);
- });
- return results;
- },
-
- sortBy: function(iterator) {
- return this.collect(function(value, index) {
- return {value: value, criteria: iterator(value, index)};
- }).sort(function(left, right) {
- var a = left.criteria, b = right.criteria;
- return a < b ? -1 : a > b ? 1 : 0;
- }).pluck('value');
- },
-
- toArray: function() {
- return this.collect(Prototype.K);
- },
-
- zip: function() {
- var iterator = Prototype.K, args = $A(arguments);
- if (typeof args.last() == 'function')
- iterator = args.pop();
-
- var collections = [this].concat(args).map($A);
- return this.map(function(value, index) {
- iterator(value = collections.pluck(index));
- return value;
- });
- },
-
- inspect: function() {
- return '#<Enumerable:' + this.toArray().inspect() + '>';
- }
-}
-
-Object.extend(Enumerable, {
- map: Enumerable.collect,
- find: Enumerable.detect,
- select: Enumerable.findAll,
- member: Enumerable.include,
- entries: Enumerable.toArray
-});
-var $A = Array.from = function(iterable) {
- if (!iterable) return [];
- if (iterable.toArray) {
- return iterable.toArray();
- } else {
- var results = [];
- for (var i = 0; i < iterable.length; i++)
- results.push(iterable[i]);
- return results;
- }
-}
-
-Object.extend(Array.prototype, Enumerable);
-
-Array.prototype._reverse = Array.prototype.reverse;
-
-Object.extend(Array.prototype, {
- _each: function(iterator) {
- for (var i = 0; i < this.length; i++)
- iterator(this[i]);
- },
-
- clear: function() {
- this.length = 0;
- return this;
- },
-
- first: function() {
- return this[0];
- },
-
- last: function() {
- return this[this.length - 1];
- },
-
- compact: function() {
- return this.select(function(value) {
- return value != undefined || value != null;
- });
- },
-
- flatten: function() {
- return this.inject([], function(array, value) {
- return array.concat(value.constructor == Array ?
- value.flatten() : [value]);
- });
- },
-
- without: function() {
- var values = $A(arguments);
- return this.select(function(value) {
- return !values.include(value);
- });
- },
-
- indexOf: function(object) {
- for (var i = 0; i < this.length; i++)
- if (this[i] == object) return i;
- return -1;
- },
-
- reverse: function(inline) {
- return (inline !== false ? this : this.toArray())._reverse();
- },
-
- shift: function() {
- var result = this[0];
- for (var i = 0; i < this.length - 1; i++)
- this[i] = this[i + 1];
- this.length--;
- return result;
- },
-
- inspect: function() {
- return '[' + this.map(Object.inspect).join(', ') + ']';
- }
-});
-var Hash = {
- _each: function(iterator) {
- for (key in this) {
- var value = this[key];
- if (typeof value == 'function') continue;
-
- var pair = [key, value];
- pair.key = key;
- pair.value = value;
- iterator(pair);
- }
- },
-
- keys: function() {
- return this.pluck('key');
- },
-
- values: function() {
- return this.pluck('value');
- },
-
- merge: function(hash) {
- return $H(hash).inject($H(this), function(mergedHash, pair) {
- mergedHash[pair.key] = pair.value;
- return mergedHash;
- });
- },
-
- toQueryString: function() {
- return this.map(function(pair) {
- return pair.map(encodeURIComponent).join('=');
- }).join('&');
- },
-
- inspect: function() {
- return '#<Hash:{' + this.map(function(pair) {
- return pair.map(Object.inspect).join(': ');
- }).join(', ') + '}>';
- }
-}
-
-function $H(object) {
- var hash = Object.extend({}, object || {});
- Object.extend(hash, Enumerable);
- Object.extend(hash, Hash);
- return hash;
-}
-ObjectRange = Class.create();
-Object.extend(ObjectRange.prototype, Enumerable);
-Object.extend(ObjectRange.prototype, {
- initialize: function(start, end, exclusive) {
- this.start = start;
- this.end = end;
- this.exclusive = exclusive;
- },
-
- _each: function(iterator) {
- var value = this.start;
- do {
- iterator(value);
- value = value.succ();
- } while (this.include(value));
- },
-
- include: function(value) {
- if (value < this.start)
- return false;
- if (this.exclusive)
- return value < this.end;
- return value <= this.end;
- }
-});
-
-var $R = function(start, end, exclusive) {
- return new ObjectRange(start, end, exclusive);
-}
-
-var Ajax = {
- getTransport: function() {
- return Try.these(
- function() {return new ActiveXObject('Msxml2.XMLHTTP')},
- function() {return new ActiveXObject('Microsoft.XMLHTTP')},
- function() {return new XMLHttpRequest()}
- ) || false;
- },
-
- activeRequestCount: 0
-}
-
-Ajax.Responders = {
- responders: [],
-
- _each: function(iterator) {
- this.responders._each(iterator);
- },
-
- register: function(responderToAdd) {
- if (!this.include(responderToAdd))
- this.responders.push(responderToAdd);
- },
-
- unregister: function(responderToRemove) {
- this.responders = this.responders.without(responderToRemove);
- },
-
- dispatch: function(callback, request, transport, json) {
- this.each(function(responder) {
- if (responder[callback] && typeof responder[callback] == 'function') {
- try {
- responder[callback].apply(responder, [request, transport, json]);
- } catch (e) {}
- }
- });
- }
-};
-
-Object.extend(Ajax.Responders, Enumerable);
-
-Ajax.Responders.register({
- onCreate: function() {
- Ajax.activeRequestCount++;
- },
-
- onComplete: function() {
- Ajax.activeRequestCount--;
- }
-});
-
-Ajax.Base = function() {};
-Ajax.Base.prototype = {
- setOptions: function(options) {
- this.options = {
- method: 'post',
- asynchronous: true,
- parameters: ''
- }
- Object.extend(this.options, options || {});
- },
-
- responseIsSuccess: function() {
- return this.transport.status == undefined
- || this.transport.status == 0
- || (this.transport.status >= 200 && this.transport.status < 300);
- },
-
- responseIsFailure: function() {
- return !this.responseIsSuccess();
- }
-}
-
-Ajax.Request = Class.create();
-Ajax.Request.Events =
- ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
-
-Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
- initialize: function(url, options) {
- this.transport = Ajax.getTransport();
- this.setOptions(options);
- this.request(url);
- },
-
- request: function(url) {
- var parameters = this.options.parameters || '';
- if (parameters.length > 0) parameters += '&_=';
-
- try {
- this.url = url;
- if (this.options.method == 'get' && parameters.length > 0)
- this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;
-
- Ajax.Responders.dispatch('onCreate', this, this.transport);
-
- this.transport.open(this.options.method, this.url,
- this.options.asynchronous);
-
- if (this.options.asynchronous) {
- this.transport.onreadystatechange = this.onStateChange.bind(this);
- setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10);
- }
-
- this.setRequestHeaders();
-
- var body = this.options.postBody ? this.options.postBody : parameters;
- this.transport.send(this.options.method == 'post' ? body : null);
-
- } catch (e) {
- this.dispatchException(e);
- }
- },
-
- setRequestHeaders: function() {
- var requestHeaders =
- ['X-Requested-With', 'XMLHttpRequest',
- 'X-Prototype-Version', Prototype.Version];
-
- if (this.options.method == 'post') {
- requestHeaders.push('Content-type',
- 'application/x-www-form-urlencoded');
-
- /* Force "Connection: close" for Mozilla browsers to work around
- * a bug where XMLHttpReqeuest sends an incorrect Content-length
- * header. See Mozilla Bugzilla #246651.
- */
- if (this.transport.overrideMimeType)
- requestHeaders.push('Connection', 'close');
- }
-
- if (this.options.requestHeaders)
- requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);
-
- for (var i = 0; i < requestHeaders.length; i += 2)
- this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
- },
-
- onStateChange: function() {
- var readyState = this.transport.readyState;
- if (readyState != 1)
- this.respondToReadyState(this.transport.readyState);
- },
-
- header: function(name) {
- try {
- return this.transport.getResponseHeader(name);
- } catch (e) {}
- },
-
- evalJSON: function() {
- try {
- return eval(this.header('X-JSON'));
- } catch (e) {}
- },
-
- evalResponse: function() {
- try {
- return eval(this.transport.responseText);
- } catch (e) {
- this.dispatchException(e);
- }
- },
-
- respondToReadyState: function(readyState) {
- var event = Ajax.Request.Events[readyState];
- var transport = this.transport, json = this.evalJSON();
-
- if (event == 'Complete') {
- try {
- (this.options['on' + this.transport.status]
- || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
- || Prototype.emptyFunction)(transport, json);
- } catch (e) {
- this.dispatchException(e);
- }
-
- if ((this.header('Content-type') || '').match(/^text\/javascript/i))
- this.evalResponse();
- }
-
- try {
- (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
- Ajax.Responders.dispatch('on' + event, this, transport, json);
- } catch (e) {
- this.dispatchException(e);
- }
-
- /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
- if (event == 'Complete')
- this.transport.onreadystatechange = Prototype.emptyFunction;
- },
-
- dispatchException: function(exception) {
- (this.options.onException || Prototype.emptyFunction)(this, exception);
- Ajax.Responders.dispatch('onException', this, exception);
- }
-});
-
-Ajax.Updater = Class.create();
-
-Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
- initialize: function(container, url, options) {
- this.containers = {
- success: container.success ? $(container.success) : $(container),
- failure: container.failure ? $(container.failure) :
- (container.success ? null : $(container))
- }
-
- this.transport = Ajax.getTransport();
- this.setOptions(options);
-
- var onComplete = this.options.onComplete || Prototype.emptyFunction;
- this.options.onComplete = (function(transport, object) {
- this.updateContent();
- onComplete(transport, object);
- }).bind(this);
-
- this.request(url);
- },
-
- updateContent: function() {
- var receiver = this.responseIsSuccess() ?
- this.containers.success : this.containers.failure;
- var response = this.transport.responseText;
-
- if (!this.options.evalScripts)
- response = response.stripScripts();
-
- if (receiver) {
- if (this.options.insertion) {
- new this.options.insertion(receiver, response);
- } else {
- Element.update(receiver, response);
- }
- }
-
- if (this.responseIsSuccess()) {
- if (this.onComplete)
- setTimeout(this.onComplete.bind(this), 10);
- }
- }
-});
-
-Ajax.PeriodicalUpdater = Class.create();
-Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
- initialize: function(container, url, options) {
- this.setOptions(options);
- this.onComplete = this.options.onComplete;
-
- this.frequency = (this.options.frequency || 2);
- this.decay = (this.options.decay || 1);
-
- this.updater = {};
- this.container = container;
- this.url = url;
-
- this.start();
- },
-
- start: function() {
- this.options.onComplete = this.updateComplete.bind(this);
- this.onTimerEvent();
- },
-
- stop: function() {
- this.updater.onComplete = undefined;
- clearTimeout(this.timer);
- (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
- },
-
- updateComplete: function(request) {
- if (this.options.decay) {
- this.decay = (request.responseText == this.lastText ?
- this.decay * this.options.decay : 1);
-
- this.lastText = request.responseText;
- }
- this.timer = setTimeout(this.onTimerEvent.bind(this),
- this.decay * this.frequency * 1000);
- },
-
- onTimerEvent: function() {
- this.updater = new Ajax.Updater(this.container, this.url, this.options);
- }
-});
-document.getElementsByClassName = function(className, parentElement) {
- var children = ($(parentElement) || document.body).getElementsByTagName('*');
- return $A(children).inject([], function(elements, child) {
- if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
- elements.push(child);
- return elements;
- });
-}
-
-/*--------------------------------------------------------------------------*/
-
-if (!window.Element) {
- var Element = new Object();
-}
-
-Object.extend(Element, {
- visible: function(element) {
- return $(element).style.display != 'none';
- },
-
- toggle: function() {
- for (var i = 0; i < arguments.length; i++) {
- var element = $(arguments[i]);
- Element[Element.visible(element) ? 'hide' : 'show'](element);
- }
- },
-
- hide: function() {
- for (var i = 0; i < arguments.length; i++) {
- var element = $(arguments[i]);
- element.style.display = 'none';
- }
- },
-
- show: function() {
- for (var i = 0; i < arguments.length; i++) {
- var element = $(arguments[i]);
- element.style.display = '';
- }
- },
-
- remove: function(element) {
- element = $(element);
- element.parentNode.removeChild(element);
- },
-
- update: function(element, html) {
- $(element).innerHTML = html.stripScripts();
- setTimeout(function() {html.evalScripts()}, 10);
- },
-
- getHeight: function(element) {
- element = $(element);
- return element.offsetHeight;
- },
-
- classNames: function(element) {
- return new Element.ClassNames(element);
- },
-
- hasClassName: function(element, className) {
- if (!(element = $(element))) return;
- return Element.classNames(element).include(className);
- },
-
- addClassName: function(element, className) {
- if (!(element = $(element))) return;
- return Element.classNames(element).add(className);
- },
-
- removeClassName: function(element, className) {
- if (!(element = $(element))) return;
- return Element.classNames(element).remove(className);
- },
-
- // removes whitespace-only text node children
- cleanWhitespace: function(element) {
- element = $(element);
- for (var i = 0; i < element.childNodes.length; i++) {
- var node = element.childNodes[i];
- if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
- Element.remove(node);
- }
- },
-
- empty: function(element) {
- return $(element).innerHTML.match(/^\s*$/);
- },
-
- scrollTo: function(element) {
- element = $(element);
- var x = element.x ? element.x : element.offsetLeft,
- y = element.y ? element.y : element.offsetTop;
- window.scrollTo(x, y);
- },
-
- getStyle: function(element, style) {
- element = $(element);
- var value = element.style[style.camelize()];
- if (!value) {
- if (document.defaultView && document.defaultView.getComputedStyle) {
- var css = document.defaultView.getComputedStyle(element, null);
- value = css ? css.getPropertyValue(style) : null;
- } else if (element.currentStyle) {
- value = element.currentStyle[style.camelize()];
- }
- }
-
- if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
- if (Element.getStyle(element, 'position') == 'static') value = 'auto';
-
- return value == 'auto' ? null : value;
- },
-
- setStyle: function(element, style) {
- element = $(element);
- for (name in style)
- element.style[name.camelize()] = style[name];
- },
-
- getDimensions: function(element) {
- element = $(element);
- if (Element.getStyle(element, 'display') != 'none')
- return {width: element.offsetWidth, height: element.offsetHeight};
-
- // All *Width and *Height properties give 0 on elements with display none,
- // so enable the element temporarily
- var els = element.style;
- var originalVisibility = els.visibility;
- var originalPosition = els.position;
- els.visibility = 'hidden';
- els.position = 'absolute';
- els.display = '';
- var originalWidth = element.clientWidth;
- var originalHeight = element.clientHeight;
- els.display = 'none';
- els.position = originalPosition;
- els.visibility = originalVisibility;
- return {width: originalWidth, height: originalHeight};
- },
-
- makePositioned: function(element) {
- element = $(element);
- var pos = Element.getStyle(element, 'position');
- if (pos == 'static' || !pos) {
- element._madePositioned = true;
- element.style.position = 'relative';
- // Opera returns the offset relative to the positioning context, when an
- // element is position relative but top and left have not been defined
- if (window.opera) {
- element.style.top = 0;
- element.style.left = 0;
- }
- }
- },
-
- undoPositioned: function(element) {
- element = $(element);
- if (element._madePositioned) {
- element._madePositioned = undefined;
- element.style.position =
- element.style.top =
- element.style.left =
- element.style.bottom =
- element.style.right = '';
- }
- },
-
- makeClipping: function(element) {
- element = $(element);
- if (element._overflow) return;
- element._overflow = element.style.overflow;
- if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
- element.style.overflow = 'hidden';
- },
-
- undoClipping: function(element) {
- element = $(element);
- if (element._overflow) return;
- element.style.overflow = element._overflow;
- element._overflow = undefined;
- }
-});
-
-var Toggle = new Object();
-Toggle.display = Element.toggle;
-
-/*--------------------------------------------------------------------------*/
-
-Abstract.Insertion = function(adjacency) {
- this.adjacency = adjacency;
-}
-
-Abstract.Insertion.prototype = {
- initialize: function(element, content) {
- this.element = $(element);
- this.content = content.stripScripts();
-
- if (this.adjacency && this.element.insertAdjacentHTML) {
- try {
- this.element.insertAdjacentHTML(this.adjacency, this.content);
- } catch (e) {
- if (this.element.tagName.toLowerCase() == 'tbody' || this.element.tagName.toLowerCase() == 'tr') {
- this.insertContent(this.contentFromAnonymousTable());
- } else {
- throw e;
- }
- }
- } else {
- this.range = this.element.ownerDocument.createRange();
- if (this.initializeRange) this.initializeRange();
- this.insertContent([this.range.createContextualFragment(this.content)]);
- }
-
- setTimeout(function() {content.evalScripts()}, 10);
- },
-
- contentFromAnonymousTable: function() {
- var div = document.createElement('div');
- div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
- return $A(div.childNodes[0].childNodes[0].childNodes);
- }
-}
-
-var Insertion = new Object();
-
-Insertion.Before = Class.create();
-Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
- initializeRange: function() {
- this.range.setStartBefore(this.element);
- },
-
- insertContent: function(fragments) {
- fragments.each((function(fragment) {
- this.element.parentNode.insertBefore(fragment, this.element);
- }).bind(this));
- }
-});
-
-Insertion.Top = Class.create();
-Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
- initializeRange: function() {
- this.range.selectNodeContents(this.element);
- this.range.collapse(true);
- },
-
- insertContent: function(fragments) {
- fragments.reverse(false).each((function(fragment) {
- this.element.insertBefore(fragment, this.element.firstChild);
- }).bind(this));
- }
-});
-
-Insertion.Bottom = Class.create();
-Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
- initializeRange: function() {
- this.range.selectNodeContents(this.element);
- this.range.collapse(this.element);
- },
-
- insertContent: function(fragments) {
- fragments.each((function(fragment) {
- this.element.appendChild(fragment);
- }).bind(this));
- }
-});
-
-Insertion.After = Class.create();
-Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
- initializeRange: function() {
- this.range.setStartAfter(this.element);
- },
-
- insertContent: function(fragments) {
- fragments.each((function(fragment) {
- this.element.parentNode.insertBefore(fragment,
- this.element.nextSibling);
- }).bind(this));
- }
-});
-
-/*--------------------------------------------------------------------------*/
-
-Element.ClassNames = Class.create();
-Element.ClassNames.prototype = {
- initialize: function(element) {
- this.element = $(element);
- },
-
- _each: function(iterator) {
- this.element.className.split(/\s+/).select(function(name) {
- return name.length > 0;
- })._each(iterator);
- },
-
- set: function(className) {
- this.element.className = className;
- },
-
- add: function(classNameToAdd) {
- if (this.include(classNameToAdd)) return;
- this.set(this.toArray().concat(classNameToAdd).join(' '));
- },
-
- remove: function(classNameToRemove) {
- if (!this.include(classNameToRemove)) return;
- this.set(this.select(function(className) {
- return className != classNameToRemove;
- }).join(' '));
- },
-
- toString: function() {
- return this.toArray().join(' ');
- }
-}
-
-Object.extend(Element.ClassNames.prototype, Enumerable);
-var Field = {
- clear: function() {
- for (var i = 0; i < arguments.length; i++)
- $(arguments[i]).value = '';
- },
-
- focus: function(element) {
- $(element).focus();
- },
-
- present: function() {
- for (var i = 0; i < arguments.length; i++)
- if ($(arguments[i]).value == '') return false;
- return true;
- },
-
- select: function(element) {
- $(element).select();
- },
-
- activate: function(element) {
- element = $(element);
- element.focus();
- if (element.select)
- element.select();
- }
-}
-
-/*--------------------------------------------------------------------------*/
-
-var Form = {
- serialize: function(form) {
- var elements = Form.getElements($(form));
- var queryComponents = new Array();
-
- for (var i = 0; i < elements.length; i++) {
- var queryComponent = Form.Element.serialize(elements[i]);
- if (queryComponent)
- queryComponents.push(queryComponent);
- }
-
- return queryComponents.join('&');
- },
-
- getElements: function(form) {
- form = $(form);
- var elements = new Array();
-
- for (tagName in Form.Element.Serializers) {
- var tagElements = form.getElementsByTagName(tagName);
- for (var j = 0; j < tagElements.length; j++)
- elements.push(tagElements[j]);
- }
- return elements;
- },
-
- getInputs: function(form, typeName, name) {
- form = $(form);
- var inputs = form.getElementsByTagName('input');
-
- if (!typeName && !name)
- return inputs;
-
- var matchingInputs = new Array();
- for (var i = 0; i < inputs.length; i++) {
- var input = inputs[i];
- if ((typeName && input.type != typeName) ||
- (name && input.name != name))
- continue;
- matchingInputs.push(input);
- }
-
- return matchingInputs;
- },
-
- disable: function(form) {
- var elements = Form.getElements(form);
- for (var i = 0; i < elements.length; i++) {
- var element = elements[i];
- element.blur();
- element.disabled = 'true';
- }
- },
-
- enable: function(form) {
- var elements = Form.getElements(form);
- for (var i = 0; i < elements.length; i++) {
- var element = elements[i];
- element.disabled = '';
- }
- },
-
- findFirstElement: function(form) {
- return Form.getElements(form).find(function(element) {
- return element.type != 'hidden' && !element.disabled &&
- ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
- });
- },
-
- focusFirstElement: function(form) {
- Field.activate(Form.findFirstElement(form));
- },
-
- reset: function(form) {
- $(form).reset();
- }
-}
-
-Form.Element = {
- serialize: function(element) {
- element = $(element);
- var method = element.tagName.toLowerCase();
- var parameter = Form.Element.Serializers[method](element);
-
- if (parameter) {
- var key = encodeURIComponent(parameter[0]);
- if (key.length == 0) return;
-
- if (parameter[1].constructor != Array)
- parameter[1] = [parameter[1]];
-
- return parameter[1].map(function(value) {
- return key + '=' + encodeURIComponent(value);
- }).join('&');
- }
- },
-
- getValue: function(element) {
- element = $(element);
- var method = element.tagName.toLowerCase();
- var parameter = Form.Element.Serializers[method](element);
-
- if (parameter)
- return parameter[1];
- }
-}
-
-Form.Element.Serializers = {
- input: function(element) {
- switch (element.type.toLowerCase()) {
- case 'submit':
- case 'hidden':
- case 'password':
- case 'text':
- return Form.Element.Serializers.textarea(element);
- case 'checkbox':
- case 'radio':
- return Form.Element.Serializers.inputSelector(element);
- }
- return false;
- },
-
- inputSelector: function(element) {
- if (element.checked)
- return [element.name, element.value];
- },
-
- textarea: function(element) {
- return [element.name, element.value];
- },
-
- select: function(element) {
- return Form.Element.Serializers[element.type == 'select-one' ?
- 'selectOne' : 'selectMany'](element);
- },
-
- selectOne: function(element) {
- var value = '', opt, index = element.selectedIndex;
- if (index >= 0) {
- opt = element.options[index];
- value = opt.value;
- if (!value && !('value' in opt))
- value = opt.text;
- }
- return [element.name, value];
- },
-
- selectMany: function(element) {
- var value = new Array();
- for (var i = 0; i < element.length; i++) {
- var opt = element.options[i];
- if (opt.selected) {
- var optValue = opt.value;
- if (!optValue && !('value' in opt))
- optValue = opt.text;
- value.push(optValue);
- }
- }
- return [element.name, value];
- }
-}
-
-/*--------------------------------------------------------------------------*/
-
-var $F = Form.Element.getValue;
-
-/*--------------------------------------------------------------------------*/
-
-Abstract.TimedObserver = function() {}
-Abstract.TimedObserver.prototype = {
- initialize: function(element, frequency, callback) {
- this.frequency = frequency;
- this.element = $(element);
- this.callback = callback;
-
- this.lastValue = this.getValue();
- this.registerCallback();
- },
-
- registerCallback: function() {
- setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
- },
-
- onTimerEvent: function() {
- var value = this.getValue();
- if (this.lastValue != value) {
- this.callback(this.element, value);
- this.lastValue = value;
- }
- }
-}
-
-Form.Element.Observer = Class.create();
-Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
- getValue: function() {
- return Form.Element.getValue(this.element);
- }
-});
-
-Form.Observer = Class.create();
-Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
- getValue: function() {
- return Form.serialize(this.element);
- }
-});
-
-/*--------------------------------------------------------------------------*/
-
-Abstract.EventObserver = function() {}
-Abstract.EventObserver.prototype = {
- initialize: function(element, callback) {
- this.element = $(element);
- this.callback = callback;
-
- this.lastValue = this.getValue();
- if (this.element.tagName.toLowerCase() == 'form')
- this.registerFormCallbacks();
- else
- this.registerCallback(this.element);
- },
-
- onElementEvent: function() {
- var value = this.getValue();
- if (this.lastValue != value) {
- this.callback(this.element, value);
- this.lastValue = value;
- }
- },
-
- registerFormCallbacks: function() {
- var elements = Form.getElements(this.element);
- for (var i = 0; i < elements.length; i++)
- this.registerCallback(elements[i]);
- },
-
- registerCallback: function(element) {
- if (element.type) {
- switch (element.type.toLowerCase()) {
- case 'checkbox':
- case 'radio':
- Event.observe(element, 'click', this.onElementEvent.bind(this));
- break;
- case 'password':
- case 'text':
- case 'textarea':
- case 'select-one':
- case 'select-multiple':
- Event.observe(element, 'change', this.onElementEvent.bind(this));
- break;
- }
- }
- }
-}
-
-Form.Element.EventObserver = Class.create();
-Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
- getValue: function() {
- return Form.Element.getValue(this.element);
- }
-});
-
-Form.EventObserver = Class.create();
-Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
- getValue: function() {
- return Form.serialize(this.element);
- }
-});
-if (!window.Event) {
- var Event = new Object();
-}
-
-Object.extend(Event, {
- KEY_BACKSPACE: 8,
- KEY_TAB: 9,
- KEY_RETURN: 13,
- KEY_ESC: 27,
- KEY_LEFT: 37,
- KEY_UP: 38,
- KEY_RIGHT: 39,
- KEY_DOWN: 40,
- KEY_DELETE: 46,
-
- element: function(event) {
- return event.target || event.srcElement;
- },
-
- isLeftClick: function(event) {
- return (((event.which) && (event.which == 1)) ||
- ((event.button) && (event.button == 1)));
- },
-
- pointerX: function(event) {
- return event.pageX || (event.clientX +
- (document.documentElement.scrollLeft || document.body.scrollLeft));
- },
-
- pointerY: function(event) {
- return event.pageY || (event.clientY +
- (document.documentElement.scrollTop || document.body.scrollTop));
- },
-
- stop: function(event) {
- if (event.preventDefault) {
- event.preventDefault();
- event.stopPropagation();
- } else {
- event.returnValue = false;
- event.cancelBubble = true;
- }
- },
-
- // find the first node with the given tagName, starting from the
- // node the event was triggered on; traverses the DOM upwards
- findElement: function(event, tagName) {
- var element = Event.element(event);
- while (element.parentNode && (!element.tagName ||
- (element.tagName.toUpperCase() != tagName.toUpperCase())))
- element = element.parentNode;
- return element;
- },
-
- observers: false,
-
- _observeAndCache: function(element, name, observer, useCapture) {
- if (!this.observers) this.observers = [];
- if (element.addEventListener) {
- this.observers.push([element, name, observer, useCapture]);
- element.addEventListener(name, observer, useCapture);
- } else if (element.attachEvent) {
- this.observers.push([element, name, observer, useCapture]);
- element.attachEvent('on' + name, observer);
- }
- },
-
- unloadCache: function() {
- if (!Event.observers) return;
- for (var i = 0; i < Event.observers.length; i++) {
- Event.stopObserving.apply(this, Event.observers[i]);
- Event.observers[i][0] = null;
- }
- Event.observers = false;
- },
-
- observe: function(element, name, observer, useCapture) {
- var element = $(element);
- useCapture = useCapture || false;
-
- if (name == 'keypress' &&
- (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
- || element.attachEvent))
- name = 'keydown';
-
- this._observeAndCache(element, name, observer, useCapture);
- },
-
- stopObserving: function(element, name, observer, useCapture) {
- var element = $(element);
- useCapture = useCapture || false;
-
- if (name == 'keypress' &&
- (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
- || element.detachEvent))
- name = 'keydown';
-
- if (element.removeEventListener) {
- element.removeEventListener(name, observer, useCapture);
- } else if (element.detachEvent) {
- element.detachEvent('on' + name, observer);
- }
- }
-});
-
-/* prevent memory leaks in IE */
-Event.observe(window, 'unload', Event.unloadCache, false);
-var Position = {
- // set to true if needed, warning: firefox performance problems
- // NOT neeeded for page scrolling, only if draggable contained in
- // scrollable elements
- includeScrollOffsets: false,
-
- // must be called before calling withinIncludingScrolloffset, every time the
- // page is scrolled
- prepare: function() {
- this.deltaX = window.pageXOffset
- || document.documentElement.scrollLeft
- || document.body.scrollLeft
- || 0;
- this.deltaY = window.pageYOffset
- || document.documentElement.scrollTop
- || document.body.scrollTop
- || 0;
- },
-
- realOffset: function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.scrollTop || 0;
- valueL += element.scrollLeft || 0;
- element = element.parentNode;
- } while (element);
- return [valueL, valueT];
- },
-
- cumulativeOffset: function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- element = element.offsetParent;
- } while (element);
- return [valueL, valueT];
- },
-
- positionedOffset: function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- element = element.offsetParent;
- if (element) {
- p = Element.getStyle(element, 'position');
- if (p == 'relative' || p == 'absolute') break;
- }
- } while (element);
- return [valueL, valueT];
- },
-
- offsetParent: function(element) {
- if (element.offsetParent) return element.offsetParent;
- if (element == document.body) return element;
-
- while ((element = element.parentNode) && element != document.body)
- if (Element.getStyle(element, 'position') != 'static')
- return element;
-
- return document.body;
- },
-
- // caches x/y coordinate pair to use with overlap
- within: function(element, x, y) {
- if (this.includeScrollOffsets)
- return this.withinIncludingScrolloffsets(element, x, y);
- this.xcomp = x;
- this.ycomp = y;
- this.offset = this.cumulativeOffset(element);
-
- return (y >= this.offset[1] &&
- y < this.offset[1] + element.offsetHeight &&
- x >= this.offset[0] &&
- x < this.offset[0] + element.offsetWidth);
- },
-
- withinIncludingScrolloffsets: function(element, x, y) {
- var offsetcache = this.realOffset(element);
-
- this.xcomp = x + offsetcache[0] - this.deltaX;
- this.ycomp = y + offsetcache[1] - this.deltaY;
- this.offset = this.cumulativeOffset(element);
-
- return (this.ycomp >= this.offset[1] &&
- this.ycomp < this.offset[1] + element.offsetHeight &&
- this.xcomp >= this.offset[0] &&
- this.xcomp < this.offset[0] + element.offsetWidth);
- },
-
- // within must be called directly before
- overlap: function(mode, element) {
- if (!mode) return 0;
- if (mode == 'vertical')
- return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
- element.offsetHeight;
- if (mode == 'horizontal')
- return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
- element.offsetWidth;
- },
-
- clone: function(source, target) {
- source = $(source);
- target = $(target);
- target.style.position = 'absolute';
- var offsets = this.cumulativeOffset(source);
- target.style.top = offsets[1] + 'px';
- target.style.left = offsets[0] + 'px';
- target.style.width = source.offsetWidth + 'px';
- target.style.height = source.offsetHeight + 'px';
- },
-
- page: function(forElement) {
- var valueT = 0, valueL = 0;
-
- var element = forElement;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
-
- // Safari fix
- if (element.offsetParent==document.body)
- if (Element.getStyle(element,'position')=='absolute') break;
-
- } while (element = element.offsetParent);
-
- element = forElement;
- do {
- valueT -= element.scrollTop || 0;
- valueL -= element.scrollLeft || 0;
- } while (element = element.parentNode);
-
- return [valueL, valueT];
- },
-
- clone: function(source, target) {
- var options = Object.extend({
- setLeft: true,
- setTop: true,
- setWidth: true,
- setHeight: true,
- offsetTop: 0,
- offsetLeft: 0
- }, arguments[2] || {})
-
- // find page position of source
- source = $(source);
- var p = Position.page(source);
-
- // find coordinate system to use
- target = $(target);
- var delta = [0, 0];
- var parent = null;
- // delta [0,0] will do fine with position: fixed elements,
- // position:absolute needs offsetParent deltas
- if (Element.getStyle(target,'position') == 'absolute') {
- parent = Position.offsetParent(target);
- delta = Position.page(parent);
- }
-
- // correct by body offsets (fixes Safari)
- if (parent == document.body) {
- delta[0] -= document.body.offsetLeft;
- delta[1] -= document.body.offsetTop;
- }
-
- // set position
- if(options.setLeft) target.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
- if(options.setTop) target.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
- if(options.setWidth) target.style.width = source.offsetWidth + 'px';
- if(options.setHeight) target.style.height = source.offsetHeight + 'px';
- },
-
- absolutize: function(element) {
- element = $(element);
- if (element.style.position == 'absolute') return;
- Position.prepare();
-
- var offsets = Position.positionedOffset(element);
- var top = offsets[1];
- var left = offsets[0];
- var width = element.clientWidth;
- var height = element.clientHeight;
-
- element._originalLeft = left - parseFloat(element.style.left || 0);
- element._originalTop = top - parseFloat(element.style.top || 0);
- element._originalWidth = element.style.width;
- element._originalHeight = element.style.height;
-
- element.style.position = 'absolute';
- element.style.top = top + 'px';;
- element.style.left = left + 'px';;
- element.style.width = width + 'px';;
- element.style.height = height + 'px';;
- },
-
- relativize: function(element) {
- element = $(element);
- if (element.style.position == 'relative') return;
- Position.prepare();
-
- element.style.position = 'relative';
- var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
- var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
-
- element.style.top = top + 'px';
- element.style.left = left + 'px';
- element.style.height = element._originalHeight;
- element.style.width = element._originalWidth;
- }
-}
-
-// Safari returns margins on body which is incorrect if the child is absolutely
-// positioned. For performance reasons, redefine Position.cumulativeOffset for
-// KHTML/WebKit only.
-if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
- Position.cumulativeOffset = function(element) {
- var valueT = 0, valueL = 0;
- do {
- valueT += element.offsetTop || 0;
- valueL += element.offsetLeft || 0;
- if (element.offsetParent == document.body)
- if (Element.getStyle(element, 'position') == 'absolute') break;
-
- element = element.offsetParent;
- } while (element);
-
- return [valueL, valueT];
- }
-} \ No newline at end of file
diff --git a/o3d/samples/third_party/xmljs/COPYING b/o3d/samples/third_party/xmljs/COPYING
deleted file mode 100644
index 9875504..0000000
--- a/o3d/samples/third_party/xmljs/COPYING
+++ /dev/null
@@ -1,491 +0,0 @@
- GNU LIBRARY GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1991 Free Software Foundation, Inc.
- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-[This is the first released version of the library GPL. It is
- numbered 2 because it goes with version 2 of the ordinary GPL.]
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-Licenses are intended to guarantee your freedom to share and change
-free software--to make sure the software is free for all its users.
-
- This license, the Library General Public License, applies to some
-specially designated Free Software Foundation software, and to any
-other libraries whose authors decide to use it. You can use it for
-your libraries, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if
-you distribute copies of the library, or if you modify it.
-
- For example, if you distribute copies of the library, whether gratis
-or for a fee, you must give the recipients all the rights that we gave
-you. You must make sure that they, too, receive or can get the source
-code. If you link a program with the library, you must provide
-complete object files to the recipients so that they can relink them
-with the library, after making changes to the library and recompiling
-it. And you must show them these terms so they know their rights.
-
- Our method of protecting your rights has two steps: (1) copyright
-the library, and (2) offer you this license which gives you legal
-permission to copy, distribute and/or modify the library.
-
- Also, for each distributor's protection, we want to make certain
-that everyone understands that there is no warranty for this free
-library. If the library is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original
-version, so that any problems introduced by others will not reflect on
-the original authors' reputations.
-
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that companies distributing free
-software will individually obtain patent licenses, thus in effect
-transforming the program into proprietary software. To prevent this,
-we have made it clear that any patent must be licensed for everyone's
-free use or not licensed at all.
-
- Most GNU software, including some libraries, is covered by the ordinary
-GNU General Public License, which was designed for utility programs. This
-license, the GNU Library General Public License, applies to certain
-designated libraries. This license is quite different from the ordinary
-one; be sure to read it in full, and don't assume that anything in it is
-the same as in the ordinary license.
-
- The reason we have a separate public license for some libraries is that
-they blur the distinction we usually make between modifying or adding to a
-program and simply using it. Linking a program with a library, without
-changing the library, is in some sense simply using the library, and is
-analogous to running a utility program or application program. However, in
-a textual and legal sense, the linked executable is a combined work, a
-derivative of the original library, and the ordinary General Public License
-treats it as such.
-
- Because of this blurred distinction, using the ordinary General
-Public License for libraries did not effectively promote software
-sharing, because most developers did not use the libraries. We
-concluded that weaker conditions might promote sharing better.
-
- However, unrestricted linking of non-free programs would deprive the
-users of those programs of all benefit from the free status of the
-libraries themselves. This Library General Public License is intended to
-permit developers of non-free programs to use free libraries, while
-preserving your freedom as a user of such programs to change the free
-libraries that are incorporated in them. (We have not seen how to achieve
-this as regards changes in header files, but we have achieved it as regards
-changes in the actual functions of the Library.) The hope is that this
-will lead to faster development of free libraries.
-
- The precise terms and conditions for copying, distribution and
-modification follow. Pay close attention to the difference between a
-"work based on the library" and a "work that uses the library". The
-former contains code derived from the library, while the latter only
-works together with the library.
-
- Note that it is possible for a library to be covered by the ordinary
-General Public License rather than by this special one.
-
-
- GNU LIBRARY GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License Agreement applies to any software library which
-contains a notice placed by the copyright holder or other authorized
-party saying it may be distributed under the terms of this Library
-General Public License (also called "this License"). Each licensee is
-addressed as "you".
-
- A "library" means a collection of software functions and/or data
-prepared so as to be conveniently linked with application programs
-(which use some of those functions and data) to form executables.
-
- The "Library", below, refers to any such software library or work
-which has been distributed under these terms. A "work based on the
-Library" means either the Library or any derivative work under
-copyright law: that is to say, a work containing the Library or a
-portion of it, either verbatim or with modifications and/or translated
-straightforwardly into another language. (Hereinafter, translation is
-included without limitation in the term "modification".)
-
- "Source code" for a work means the preferred form of the work for
-making modifications to it. For a library, complete source code means
-all the source code for all modules it contains, plus any associated
-interface definition files, plus the scripts used to control compilation
-and installation of the library.
-
- Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running a program using the Library is not restricted, and output from
-such a program is covered only if its contents constitute a work based
-on the Library (independent of the use of the Library in a tool for
-writing it). Whether that is true depends on what the Library does
-and what the program that uses the Library does.
-
- 1. You may copy and distribute verbatim copies of the Library's
-complete source code as you receive it, in any medium, provided that
-you conspicuously and appropriately publish on each copy an
-appropriate copyright notice and disclaimer of warranty; keep intact
-all the notices that refer to this License and to the absence of any
-warranty; and distribute a copy of this License along with the
-Library.
-
- You may charge a fee for the physical act of transferring a copy,
-and you may at your option offer warranty protection in exchange for a
-fee.
-
-
- 2. You may modify your copy or copies of the Library or any portion
-of it, thus forming a work based on the Library, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) The modified work must itself be a software library.
-
- b) You must cause the files modified to carry prominent notices
- stating that you changed the files and the date of any change.
-
- c) You must cause the whole of the work to be licensed at no
- charge to all third parties under the terms of this License.
-
- d) If a facility in the modified Library refers to a function or a
- table of data to be supplied by an application program that uses
- the facility, other than as an argument passed when the facility
- is invoked, then you must make a good faith effort to ensure that,
- in the event an application does not supply such function or
- table, the facility still operates, and performs whatever part of
- its purpose remains meaningful.
-
- (For example, a function in a library to compute square roots has
- a purpose that is entirely well-defined independent of the
- application. Therefore, Subsection 2d requires that any
- application-supplied function or table used by this function must
- be optional: if the application does not supply it, the square
- root function must still compute square roots.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Library,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Library, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote
-it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Library.
-
-In addition, mere aggregation of another work not based on the Library
-with the Library (or with a work based on the Library) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may opt to apply the terms of the ordinary GNU General Public
-License instead of this License to a given copy of the Library. To do
-this, you must alter all the notices that refer to this License, so
-that they refer to the ordinary GNU General Public License, version 2,
-instead of to this License. (If a newer version than version 2 of the
-ordinary GNU General Public License has appeared, then you can specify
-that version instead if you wish.) Do not make any other change in
-these notices.
-
-
- Once this change is made in a given copy, it is irreversible for
-that copy, so the ordinary GNU General Public License applies to all
-subsequent copies and derivative works made from that copy.
-
- This option is useful when you wish to copy part of the code of
-the Library into a program that is not a library.
-
- 4. You may copy and distribute the Library (or a portion or
-derivative of it, under Section 2) in object code or executable form
-under the terms of Sections 1 and 2 above provided that you accompany
-it with the complete corresponding machine-readable source code, which
-must be distributed under the terms of Sections 1 and 2 above on a
-medium customarily used for software interchange.
-
- If distribution of object code is made by offering access to copy
-from a designated place, then offering equivalent access to copy the
-source code from the same place satisfies the requirement to
-distribute the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 5. A program that contains no derivative of any portion of the
-Library, but is designed to work with the Library by being compiled or
-linked with it, is called a "work that uses the Library". Such a
-work, in isolation, is not a derivative work of the Library, and
-therefore falls outside the scope of this License.
-
- However, linking a "work that uses the Library" with the Library
-creates an executable that is a derivative of the Library (because it
-contains portions of the Library), rather than a "work that uses the
-library". The executable is therefore covered by this License.
-Section 6 states terms for distribution of such executables.
-
- When a "work that uses the Library" uses material from a header file
-that is part of the Library, the object code for the work may be a
-derivative work of the Library even though the source code is not.
-Whether this is true is especially significant if the work can be
-linked without the Library, or if the work is itself a library. The
-threshold for this to be true is not precisely defined by law.
-
- If such an object file uses only numerical parameters, data
-structure layouts and accessors, and small macros and small inline
-functions (ten lines or less in length), then the use of the object
-file is unrestricted, regardless of whether it is legally a derivative
-work. (Executables containing this object code plus portions of the
-Library will still fall under Section 6.)
-
- Otherwise, if the work is a derivative of the Library, you may
-distribute the object code for the work under the terms of Section 6.
-Any executables containing that work also fall under Section 6,
-whether or not they are linked directly with the Library itself.
-
-
- 6. As an exception to the Sections above, you may also compile or
-link a "work that uses the Library" with the Library to produce a
-work containing portions of the Library, and distribute that work
-under terms of your choice, provided that the terms permit
-modification of the work for the customer's own use and reverse
-engineering for debugging such modifications.
-
- You must give prominent notice with each copy of the work that the
-Library is used in it and that the Library and its use are covered by
-this License. You must supply a copy of this License. If the work
-during execution displays copyright notices, you must include the
-copyright notice for the Library among them, as well as a reference
-directing the user to the copy of this License. Also, you must do one
-of these things:
-
- a) Accompany the work with the complete corresponding
- machine-readable source code for the Library including whatever
- changes were used in the work (which must be distributed under
- Sections 1 and 2 above); and, if the work is an executable linked
- with the Library, with the complete machine-readable "work that
- uses the Library", as object code and/or source code, so that the
- user can modify the Library and then relink to produce a modified
- executable containing the modified Library. (It is understood
- that the user who changes the contents of definitions files in the
- Library will not necessarily be able to recompile the application
- to use the modified definitions.)
-
- b) Accompany the work with a written offer, valid for at
- least three years, to give the same user the materials
- specified in Subsection 6a, above, for a charge no more
- than the cost of performing this distribution.
-
- c) If distribution of the work is made by offering access to copy
- from a designated place, offer equivalent access to copy the above
- specified materials from the same place.
-
- d) Verify that the user has already received a copy of these
- materials or that you have already sent this user a copy.
-
- For an executable, the required form of the "work that uses the
-Library" must include any data and utility programs needed for
-reproducing the executable from it. However, as a special exception,
-the source code distributed need not include anything that is normally
-distributed (in either source or binary form) with the major
-components (compiler, kernel, and so on) of the operating system on
-which the executable runs, unless that component itself accompanies
-the executable.
-
- It may happen that this requirement contradicts the license
-restrictions of other proprietary libraries that do not normally
-accompany the operating system. Such a contradiction means you cannot
-use both them and the Library together in an executable that you
-distribute.
-
-
- 7. You may place library facilities that are a work based on the
-Library side-by-side in a single library together with other library
-facilities not covered by this License, and distribute such a combined
-library, provided that the separate distribution of the work based on
-the Library and of the other library facilities is otherwise
-permitted, and provided that you do these two things:
-
- a) Accompany the combined library with a copy of the same work
- based on the Library, uncombined with any other library
- facilities. This must be distributed under the terms of the
- Sections above.
-
- b) Give prominent notice with the combined library of the fact
- that part of it is a work based on the Library, and explaining
- where to find the accompanying uncombined form of the same work.
-
- 8. You may not copy, modify, sublicense, link with, or distribute
-the Library except as expressly provided under this License. Any
-attempt otherwise to copy, modify, sublicense, link with, or
-distribute the Library is void, and will automatically terminate your
-rights under this License. However, parties who have received copies,
-or rights, from you under this License will not have their licenses
-terminated so long as such parties remain in full compliance.
-
- 9. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Library or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Library (or any work based on the
-Library), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Library or works based on it.
-
- 10. Each time you redistribute the Library (or any work based on the
-Library), the recipient automatically receives a license from the
-original licensor to copy, distribute, link with or modify the Library
-subject to these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
-
- 11. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Library at all. For example, if a patent
-license would not permit royalty-free redistribution of the Library by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Library.
-
-If any portion of this section is held invalid or unenforceable under any
-particular circumstance, the balance of the section is intended to apply,
-and the section as a whole is intended to apply in other circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 12. If the distribution and/or use of the Library is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Library under this License may add
-an explicit geographical distribution limitation excluding those countries,
-so that distribution is permitted only in or among countries not thus
-excluded. In such case, this License incorporates the limitation as if
-written in the body of this License.
-
- 13. The Free Software Foundation may publish revised and/or new
-versions of the Library General Public License from time to time.
-Such new versions will be similar in spirit to the present version,
-but may differ in detail to address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Library
-specifies a version number of this License which applies to it and
-"any later version", you have the option of following the terms and
-conditions either of that version or of any later version published by
-the Free Software Foundation. If the Library does not specify a
-license version number, you may choose any version ever published by
-the Free Software Foundation.
-
-
- 14. If you wish to incorporate parts of the Library into other free
-programs whose distribution conditions are incompatible with these,
-write to the author to ask for permission. For software which is
-copyrighted by the Free Software Foundation, write to the Free
-Software Foundation; we sometimes make exceptions for this. Our
-decision will be guided by the two goals of preserving the free status
-of all derivatives of our free software and of promoting the sharing
-and reuse of software generally.
-
- NO WARRANTY
-
- 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
-WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
-EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
-OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
-KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
-LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
-THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
-WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
-AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
-FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
-CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
-LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
-RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
-FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
-SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
-DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
-
- How to Apply These Terms to Your New Libraries
-
- If you develop a new library, and you want it to be of the greatest
-possible use to the public, we recommend making it free software that
-everyone can redistribute and change. You can do so by permitting
-redistribution under these terms (or, alternatively, under the terms of the
-ordinary General Public License).
-
- To apply these terms, attach the following notices to the library. It is
-safest to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least the
-"copyright" line and a pointer to where the full notice is found.
-
- <one line to give the library's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public
- License along with this library; if not, write to the
- Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- Boston, MA 02111-1307 USA.
-
-Also add information on how to contact you by electronic and paper mail.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the library, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the
- library `Frob' (a library for tweaking knobs) written by James Random Hacker.
-
- <signature of Ty Coon>, 1 April 1990
- Ty Coon, President of Vice
-
-That's all there is to it!
diff --git a/o3d/samples/third_party/xmljs/tinyxmlsax.js b/o3d/samples/third_party/xmljs/tinyxmlsax.js
deleted file mode 100644
index f45ba51..0000000
--- a/o3d/samples/third_party/xmljs/tinyxmlsax.js
+++ /dev/null
@@ -1,245 +0,0 @@
-// =========================================================================
-//
-// tinyxmlsax.js - an XML SAX parser in JavaScript compressed for downloading
-//
-// version 3.1
-//
-// =========================================================================
-//
-// Copyright (C) 2000 - 2002, 2003 Michael Houghton (mike@idle.org), Raymond Irving and David Joham (djoham@yahoo.com)
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// Visit the XML for <SCRIPT> home page at http://xmljs.sourceforge.net
-//
-
-
-var whitespace = "\n\r\t "; XMLP = function(strXML) { strXML = SAXStrings.replace(strXML, null, null, "\r\n", "\n"); strXML = SAXStrings.replace(strXML, null, null, "\r", "\n"); this.m_xml = strXML; this.m_iP = 0; this.m_iState = XMLP._STATE_PROLOG; this.m_stack = new Stack(); this._clearAttributes();}
-XMLP._NONE = 0; XMLP._ELM_B = 1; XMLP._ELM_E = 2; XMLP._ELM_EMP = 3; XMLP._ATT = 4; XMLP._TEXT = 5; XMLP._ENTITY = 6; XMLP._PI = 7; XMLP._CDATA = 8; XMLP._COMMENT = 9; XMLP._DTD = 10; XMLP._ERROR = 11; XMLP._CONT_XML = 0; XMLP._CONT_ALT = 1; XMLP._ATT_NAME = 0; XMLP._ATT_VAL = 1; XMLP._STATE_PROLOG = 1; XMLP._STATE_DOCUMENT = 2; XMLP._STATE_MISC = 3; XMLP._errs = new Array(); XMLP._errs[XMLP.ERR_CLOSE_PI = 0 ] = "PI: missing closing sequence"; XMLP._errs[XMLP.ERR_CLOSE_DTD = 1 ] = "DTD: missing closing sequence"; XMLP._errs[XMLP.ERR_CLOSE_COMMENT = 2 ] = "Comment: missing closing sequence"; XMLP._errs[XMLP.ERR_CLOSE_CDATA = 3 ] = "CDATA: missing closing sequence"; XMLP._errs[XMLP.ERR_CLOSE_ELM = 4 ] = "Element: missing closing sequence"; XMLP._errs[XMLP.ERR_CLOSE_ENTITY = 5 ] = "Entity: missing closing sequence"; XMLP._errs[XMLP.ERR_PI_TARGET = 6 ] = "PI: target is required"; XMLP._errs[XMLP.ERR_ELM_EMPTY = 7 ] = "Element: cannot be both empty and closing"; XMLP._errs[XMLP.ERR_ELM_NAME = 8 ] = "Element: name must immediatly follow \"<\""; XMLP._errs[XMLP.ERR_ELM_LT_NAME = 9 ] = "Element: \"<\" not allowed in element names"; XMLP._errs[XMLP.ERR_ATT_VALUES = 10] = "Attribute: values are required and must be in quotes"; XMLP._errs[XMLP.ERR_ATT_LT_NAME = 11] = "Element: \"<\" not allowed in attribute names"; XMLP._errs[XMLP.ERR_ATT_LT_VALUE = 12] = "Attribute: \"<\" not allowed in attribute values"; XMLP._errs[XMLP.ERR_ATT_DUP = 13] = "Attribute: duplicate attributes not allowed"; XMLP._errs[XMLP.ERR_ENTITY_UNKNOWN = 14] = "Entity: unknown entity"; XMLP._errs[XMLP.ERR_INFINITELOOP = 15] = "Infininte loop"; XMLP._errs[XMLP.ERR_DOC_STRUCTURE = 16] = "Document: only comments, processing instructions, or whitespace allowed outside of document element"; XMLP._errs[XMLP.ERR_ELM_NESTING = 17] = "Element: must be nested correctly"; XMLP.prototype._addAttribute = function(name, value) { this.m_atts[this.m_atts.length] = new Array(name, value);}
-XMLP.prototype._checkStructure = function(iEvent) { if(XMLP._STATE_PROLOG == this.m_iState) { if((XMLP._TEXT == iEvent) || (XMLP._ENTITY == iEvent)) { if(SAXStrings.indexOfNonWhitespace(this.getContent(), this.getContentBegin(), this.getContentEnd()) != -1) { return this._setErr(XMLP.ERR_DOC_STRUCTURE);}
-}
-if((XMLP._ELM_B == iEvent) || (XMLP._ELM_EMP == iEvent)) { this.m_iState = XMLP._STATE_DOCUMENT;}
-}
-if(XMLP._STATE_DOCUMENT == this.m_iState) { if((XMLP._ELM_B == iEvent) || (XMLP._ELM_EMP == iEvent)) { this.m_stack.push(this.getName());}
-if((XMLP._ELM_E == iEvent) || (XMLP._ELM_EMP == iEvent)) { var strTop = this.m_stack.pop(); if((strTop == null) || (strTop != this.getName())) { return this._setErr(XMLP.ERR_ELM_NESTING);}
-}
-if(this.m_stack.count() == 0) { this.m_iState = XMLP._STATE_MISC; return iEvent;}
-}
-if(XMLP._STATE_MISC == this.m_iState) { if((XMLP._ELM_B == iEvent) || (XMLP._ELM_E == iEvent) || (XMLP._ELM_EMP == iEvent) || (XMLP.EVT_DTD == iEvent)) { return this._setErr(XMLP.ERR_DOC_STRUCTURE);}
-if((XMLP._TEXT == iEvent) || (XMLP._ENTITY == iEvent)) { if(SAXStrings.indexOfNonWhitespace(this.getContent(), this.getContentBegin(), this.getContentEnd()) != -1) { return this._setErr(XMLP.ERR_DOC_STRUCTURE);}
-}
-}
-return iEvent;}
-XMLP.prototype._clearAttributes = function() { this.m_atts = new Array();}
-XMLP.prototype._findAttributeIndex = function(name) { for(var i = 0; i < this.m_atts.length; i++) { if(this.m_atts[i][XMLP._ATT_NAME] == name) { return i;}
-}
-return -1;}
-XMLP.prototype.getAttributeCount = function() { return this.m_atts ? this.m_atts.length : 0;}
-XMLP.prototype.getAttributeName = function(index) { return ((index < 0) || (index >= this.m_atts.length)) ? null : this.m_atts[index][XMLP._ATT_NAME];}
-XMLP.prototype.getAttributeValue = function(index) { return ((index < 0) || (index >= this.m_atts.length)) ? null : __unescapeString(this.m_atts[index][XMLP._ATT_VAL]);}
-XMLP.prototype.getAttributeValueByName = function(name) { return this.getAttributeValue(this._findAttributeIndex(name));}
-XMLP.prototype.getColumnNumber = function() { return SAXStrings.getColumnNumber(this.m_xml, this.m_iP);}
-XMLP.prototype.getContent = function() { return (this.m_cSrc == XMLP._CONT_XML) ? this.m_xml : this.m_cAlt;}
-XMLP.prototype.getContentBegin = function() { return this.m_cB;}
-XMLP.prototype.getContentEnd = function() { return this.m_cE;}
-XMLP.prototype.getLineNumber = function() { return SAXStrings.getLineNumber(this.m_xml, this.m_iP);}
-XMLP.prototype.getName = function() { return this.m_name;}
-XMLP.prototype.next = function() { return this._checkStructure(this._parse());}
-XMLP.prototype._parse = function() { if(this.m_iP == this.m_xml.length) { return XMLP._NONE;}
-if(this.m_iP == this.m_xml.indexOf("<?", this.m_iP)) { return this._parsePI (this.m_iP + 2);}
-else if(this.m_iP == this.m_xml.indexOf("<!DOCTYPE", this.m_iP)) { return this._parseDTD (this.m_iP + 9);}
-else if(this.m_iP == this.m_xml.indexOf("<!--", this.m_iP)) { return this._parseComment(this.m_iP + 4);}
-else if(this.m_iP == this.m_xml.indexOf("<![CDATA[", this.m_iP)) { return this._parseCDATA (this.m_iP + 9);}
-else if(this.m_iP == this.m_xml.indexOf("<", this.m_iP)) { return this._parseElement(this.m_iP + 1);}
-else if(this.m_iP == this.m_xml.indexOf("&", this.m_iP)) { return this._parseEntity (this.m_iP + 1);}
-else{ return this._parseText (this.m_iP);}
-}
-XMLP.prototype._parseAttribute = function(iB, iE) { var iNB, iNE, iEq, iVB, iVE; var cQuote, strN, strV; this.m_cAlt = ""; iNB = SAXStrings.indexOfNonWhitespace(this.m_xml, iB, iE); if((iNB == -1) ||(iNB >= iE)) { return iNB;}
-iEq = this.m_xml.indexOf("=", iNB); if((iEq == -1) || (iEq > iE)) { return this._setErr(XMLP.ERR_ATT_VALUES);}
-iNE = SAXStrings.lastIndexOfNonWhitespace(this.m_xml, iNB, iEq); iVB = SAXStrings.indexOfNonWhitespace(this.m_xml, iEq + 1, iE); if((iVB == -1) ||(iVB > iE)) { return this._setErr(XMLP.ERR_ATT_VALUES);}
-cQuote = this.m_xml.charAt(iVB); if(SAXStrings.QUOTES.indexOf(cQuote) == -1) { return this._setErr(XMLP.ERR_ATT_VALUES);}
-iVE = this.m_xml.indexOf(cQuote, iVB + 1); if((iVE == -1) ||(iVE > iE)) { return this._setErr(XMLP.ERR_ATT_VALUES);}
-strN = this.m_xml.substring(iNB, iNE + 1); strV = this.m_xml.substring(iVB + 1, iVE); if(strN.indexOf("<") != -1) { return this._setErr(XMLP.ERR_ATT_LT_NAME);}
-if(strV.indexOf("<") != -1) { return this._setErr(XMLP.ERR_ATT_LT_VALUE);}
-strV = SAXStrings.replace(strV, null, null, "\n", " "); strV = SAXStrings.replace(strV, null, null, "\t", " "); iRet = this._replaceEntities(strV); if(iRet == XMLP._ERROR) { return iRet;}
-strV = this.m_cAlt; if(this._findAttributeIndex(strN) == -1) { this._addAttribute(strN, strV);}
-else { return this._setErr(XMLP.ERR_ATT_DUP);}
-this.m_iP = iVE + 2; return XMLP._ATT;}
-XMLP.prototype._parseCDATA = function(iB) { var iE = this.m_xml.indexOf("]]>", iB); if (iE == -1) { return this._setErr(XMLP.ERR_CLOSE_CDATA);}
-this._setContent(XMLP._CONT_XML, iB, iE); this.m_iP = iE + 3; return XMLP._CDATA;}
-XMLP.prototype._parseComment = function(iB) { var iE = this.m_xml.indexOf("-" + "->", iB); if (iE == -1) { return this._setErr(XMLP.ERR_CLOSE_COMMENT);}
-this._setContent(XMLP._CONT_XML, iB, iE); this.m_iP = iE + 3; return XMLP._COMMENT;}
-XMLP.prototype._parseDTD = function(iB) { var iE, strClose, iInt, iLast; iE = this.m_xml.indexOf(">", iB); if(iE == -1) { return this._setErr(XMLP.ERR_CLOSE_DTD);}
-iInt = this.m_xml.indexOf("[", iB); strClose = ((iInt != -1) && (iInt < iE)) ? "]>" : ">"; while(true) { if(iE == iLast) { return this._setErr(XMLP.ERR_INFINITELOOP);}
-iLast = iE; iE = this.m_xml.indexOf(strClose, iB); if(iE == -1) { return this._setErr(XMLP.ERR_CLOSE_DTD);}
-if (this.m_xml.substring(iE - 1, iE + 2) != "]]>") { break;}
-}
-this.m_iP = iE + strClose.length; return XMLP._DTD;}
-XMLP.prototype._parseElement = function(iB) { var iE, iDE, iNE, iRet; var iType, strN, iLast; iDE = iE = this.m_xml.indexOf(">", iB); if(iE == -1) { return this._setErr(XMLP.ERR_CLOSE_ELM);}
-if(this.m_xml.charAt(iB) == "/") { iType = XMLP._ELM_E; iB++;} else { iType = XMLP._ELM_B;}
-if(this.m_xml.charAt(iE - 1) == "/") { if(iType == XMLP._ELM_E) { return this._setErr(XMLP.ERR_ELM_EMPTY);}
-iType = XMLP._ELM_EMP; iDE--;}
-iDE = SAXStrings.lastIndexOfNonWhitespace(this.m_xml, iB, iDE); if (iE - iB != 1 ) { if(SAXStrings.indexOfNonWhitespace(this.m_xml, iB, iDE) != iB) { return this._setErr(XMLP.ERR_ELM_NAME);}
-}
-this._clearAttributes(); iNE = SAXStrings.indexOfWhitespace(this.m_xml, iB, iDE); if(iNE == -1) { iNE = iDE + 1;}
-else { this.m_iP = iNE; while(this.m_iP < iDE) { if(this.m_iP == iLast) return this._setErr(XMLP.ERR_INFINITELOOP); iLast = this.m_iP; iRet = this._parseAttribute(this.m_iP, iDE); if(iRet == XMLP._ERROR) return iRet;}
-}
-strN = this.m_xml.substring(iB, iNE); if(strN.indexOf("<") != -1) { return this._setErr(XMLP.ERR_ELM_LT_NAME);}
-this.m_name = strN; this.m_iP = iE + 1; return iType;}
-XMLP.prototype._parseEntity = function(iB) { var iE = this.m_xml.indexOf(";", iB); if(iE == -1) { return this._setErr(XMLP.ERR_CLOSE_ENTITY);}
-this.m_iP = iE + 1; return this._replaceEntity(this.m_xml, iB, iE);}
-XMLP.prototype._parsePI = function(iB) { var iE, iTB, iTE, iCB, iCE; iE = this.m_xml.indexOf("?>", iB); if(iE == -1) { return this._setErr(XMLP.ERR_CLOSE_PI);}
-iTB = SAXStrings.indexOfNonWhitespace(this.m_xml, iB, iE); if(iTB == -1) { return this._setErr(XMLP.ERR_PI_TARGET);}
-iTE = SAXStrings.indexOfWhitespace(this.m_xml, iTB, iE); if(iTE == -1) { iTE = iE;}
-iCB = SAXStrings.indexOfNonWhitespace(this.m_xml, iTE, iE); if(iCB == -1) { iCB = iE;}
-iCE = SAXStrings.lastIndexOfNonWhitespace(this.m_xml, iCB, iE); if(iCE == -1) { iCE = iE - 1;}
-this.m_name = this.m_xml.substring(iTB, iTE); this._setContent(XMLP._CONT_XML, iCB, iCE + 1); this.m_iP = iE + 2; return XMLP._PI;}
-XMLP.prototype._parseText = function(iB) { var iE, iEE; iE = this.m_xml.indexOf("<", iB); if(iE == -1) { iE = this.m_xml.length;}
-iEE = this.m_xml.indexOf("&", iB); if((iEE != -1) && (iEE <= iE)) { iE = iEE;}
-this._setContent(XMLP._CONT_XML, iB, iE); this.m_iP = iE; return XMLP._TEXT;}
-XMLP.prototype._replaceEntities = function(strD, iB, iE) { if(SAXStrings.isEmpty(strD)) return ""; iB = iB || 0; iE = iE || strD.length; var iEB, iEE, strRet = ""; iEB = strD.indexOf("&", iB); iEE = iB; while((iEB > 0) && (iEB < iE)) { strRet += strD.substring(iEE, iEB); iEE = strD.indexOf(";", iEB) + 1; if((iEE == 0) || (iEE > iE)) { return this._setErr(XMLP.ERR_CLOSE_ENTITY);}
-iRet = this._replaceEntity(strD, iEB + 1, iEE - 1); if(iRet == XMLP._ERROR) { return iRet;}
-strRet += this.m_cAlt; iEB = strD.indexOf("&", iEE);}
-if(iEE != iE) { strRet += strD.substring(iEE, iE);}
-this._setContent(XMLP._CONT_ALT, strRet); return XMLP._ENTITY;}
-XMLP.prototype._replaceEntity = function(strD, iB, iE) { if(SAXStrings.isEmpty(strD)) return -1; iB = iB || 0; iE = iE || strD.length; switch(strD.substring(iB, iE)) { case "amp": strEnt = "&"; break; case "lt": strEnt = "<"; break; case "gt": strEnt = ">"; break; case "apos": strEnt = "'"; break; case "quot": strEnt = "\""; break; default:
-if(strD.charAt(iB) == "#") { strEnt = String.fromCharCode(parseInt(strD.substring(iB + 1, iE)));} else { return this._setErr(XMLP.ERR_ENTITY_UNKNOWN);}
-break;}
-this._setContent(XMLP._CONT_ALT, strEnt); return XMLP._ENTITY;}
-XMLP.prototype._setContent = function(iSrc) { var args = arguments; if(XMLP._CONT_XML == iSrc) { this.m_cAlt = null; this.m_cB = args[1]; this.m_cE = args[2];} else { this.m_cAlt = args[1]; this.m_cB = 0; this.m_cE = args[1].length;}
-this.m_cSrc = iSrc;}
-XMLP.prototype._setErr = function(iErr) { var strErr = XMLP._errs[iErr]; this.m_cAlt = strErr; this.m_cB = 0; this.m_cE = strErr.length; this.m_cSrc = XMLP._CONT_ALT; return XMLP._ERROR;}
-SAXDriver = function() { this.m_hndDoc = null; this.m_hndErr = null; this.m_hndLex = null;}
-SAXDriver.DOC_B = 1; SAXDriver.DOC_E = 2; SAXDriver.ELM_B = 3; SAXDriver.ELM_E = 4; SAXDriver.CHARS = 5; SAXDriver.PI = 6; SAXDriver.CD_B = 7; SAXDriver.CD_E = 8; SAXDriver.CMNT = 9; SAXDriver.DTD_B = 10; SAXDriver.DTD_E = 11; SAXDriver.prototype.parse = function(strD) { var parser = new XMLP(strD); if(this.m_hndDoc && this.m_hndDoc.setDocumentLocator) { this.m_hndDoc.setDocumentLocator(this);}
-this.m_parser = parser; this.m_bErr = false; if(!this.m_bErr) { this._fireEvent(SAXDriver.DOC_B);}
-this._parseLoop(); if(!this.m_bErr) { this._fireEvent(SAXDriver.DOC_E);}
-this.m_xml = null; this.m_iP = 0;}
-SAXDriver.prototype.setDocumentHandler = function(hnd) { this.m_hndDoc = hnd;}
-SAXDriver.prototype.setErrorHandler = function(hnd) { this.m_hndErr = hnd;}
-SAXDriver.prototype.setLexicalHandler = function(hnd) { this.m_hndLex = hnd;}
-SAXDriver.prototype.getColumnNumber = function() { return this.m_parser.getColumnNumber();}
-SAXDriver.prototype.getLineNumber = function() { return this.m_parser.getLineNumber();}
-SAXDriver.prototype.getMessage = function() { return this.m_strErrMsg;}
-SAXDriver.prototype.getPublicId = function() { return null;}
-SAXDriver.prototype.getSystemId = function() { return null;}
-SAXDriver.prototype.getLength = function() { return this.m_parser.getAttributeCount();}
-SAXDriver.prototype.getName = function(index) { return this.m_parser.getAttributeName(index);}
-SAXDriver.prototype.getValue = function(index) { return this.m_parser.getAttributeValue(index);}
-SAXDriver.prototype.getValueByName = function(name) { return this.m_parser.getAttributeValueByName(name);}
-SAXDriver.prototype._fireError = function(strMsg) { this.m_strErrMsg = strMsg; this.m_bErr = true; if(this.m_hndErr && this.m_hndErr.fatalError) { this.m_hndErr.fatalError(this);}
-}
-SAXDriver.prototype._fireEvent = function(iEvt) { var hnd, func, args = arguments, iLen = args.length - 1; if(this.m_bErr) return; if(SAXDriver.DOC_B == iEvt) { func = "startDocument"; hnd = this.m_hndDoc;}
-else if (SAXDriver.DOC_E == iEvt) { func = "endDocument"; hnd = this.m_hndDoc;}
-else if (SAXDriver.ELM_B == iEvt) { func = "startElement"; hnd = this.m_hndDoc;}
-else if (SAXDriver.ELM_E == iEvt) { func = "endElement"; hnd = this.m_hndDoc;}
-else if (SAXDriver.CHARS == iEvt) { func = "characters"; hnd = this.m_hndDoc;}
-else if (SAXDriver.PI == iEvt) { func = "processingInstruction"; hnd = this.m_hndDoc;}
-else if (SAXDriver.CD_B == iEvt) { func = "startCDATA"; hnd = this.m_hndLex;}
-else if (SAXDriver.CD_E == iEvt) { func = "endCDATA"; hnd = this.m_hndLex;}
-else if (SAXDriver.CMNT == iEvt) { func = "comment"; hnd = this.m_hndLex;}
-if(hnd && hnd[func]) { if(0 == iLen) { hnd[func]();}
-else if (1 == iLen) { hnd[func](args[1]);}
-else if (2 == iLen) { hnd[func](args[1], args[2]);}
-else if (3 == iLen) { hnd[func](args[1], args[2], args[3]);}
-}
-}
-SAXDriver.prototype._parseLoop = function(parser) { var iEvent, parser; parser = this.m_parser; while(!this.m_bErr) { iEvent = parser.next(); if(iEvent == XMLP._ELM_B) { this._fireEvent(SAXDriver.ELM_B, parser.getName(), this);}
-else if(iEvent == XMLP._ELM_E) { this._fireEvent(SAXDriver.ELM_E, parser.getName());}
-else if(iEvent == XMLP._ELM_EMP) { this._fireEvent(SAXDriver.ELM_B, parser.getName(), this); this._fireEvent(SAXDriver.ELM_E, parser.getName());}
-else if(iEvent == XMLP._TEXT) { this._fireEvent(SAXDriver.CHARS, parser.getContent(), parser.getContentBegin(), parser.getContentEnd() - parser.getContentBegin());}
-else if(iEvent == XMLP._ENTITY) { this._fireEvent(SAXDriver.CHARS, parser.getContent(), parser.getContentBegin(), parser.getContentEnd() - parser.getContentBegin());}
-else if(iEvent == XMLP._PI) { this._fireEvent(SAXDriver.PI, parser.getName(), parser.getContent().substring(parser.getContentBegin(), parser.getContentEnd()));}
-else if(iEvent == XMLP._CDATA) { this._fireEvent(SAXDriver.CD_B); this._fireEvent(SAXDriver.CHARS, parser.getContent(), parser.getContentBegin(), parser.getContentEnd() - parser.getContentBegin()); this._fireEvent(SAXDriver.CD_E);}
-else if(iEvent == XMLP._COMMENT) { this._fireEvent(SAXDriver.CMNT, parser.getContent(), parser.getContentBegin(), parser.getContentEnd() - parser.getContentBegin());}
-else if(iEvent == XMLP._DTD) { }
-else if(iEvent == XMLP._ERROR) { this._fireError(parser.getContent());}
-else if(iEvent == XMLP._NONE) { return;}
-}
-}
-SAXStrings = function() { }
-SAXStrings.WHITESPACE = " \t\n\r"; SAXStrings.QUOTES = "\"'"; SAXStrings.getColumnNumber = function(strD, iP) { if(SAXStrings.isEmpty(strD)) { return -1;}
-iP = iP || strD.length; var arrD = strD.substring(0, iP).split("\n"); var strLine = arrD[arrD.length - 1]; arrD.length--; var iLinePos = arrD.join("\n").length; return iP - iLinePos;}
-SAXStrings.getLineNumber = function(strD, iP) { if(SAXStrings.isEmpty(strD)) { return -1;}
-iP = iP || strD.length; return strD.substring(0, iP).split("\n").length
-}
-SAXStrings.indexOfNonWhitespace = function(strD, iB, iE) { if(SAXStrings.isEmpty(strD)) { return -1;}
-iB = iB || 0; iE = iE || strD.length; for(var i = iB; i < iE; i++){ if(SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) == -1) { return i;}
-}
-return -1;}
-SAXStrings.indexOfWhitespace = function(strD, iB, iE) { if(SAXStrings.isEmpty(strD)) { return -1;}
-iB = iB || 0; iE = iE || strD.length; for(var i = iB; i < iE; i++) { if(SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) != -1) { return i;}
-}
-return -1;}
-SAXStrings.isEmpty = function(strD) { return (strD == null) || (strD.length == 0);}
-SAXStrings.lastIndexOfNonWhitespace = function(strD, iB, iE) { if(SAXStrings.isEmpty(strD)) { return -1;}
-iB = iB || 0; iE = iE || strD.length; for(var i = iE - 1; i >= iB; i--){ if(SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) == -1){ return i;}
-}
-return -1;}
-SAXStrings.replace = function(strD, iB, iE, strF, strR) { if(SAXStrings.isEmpty(strD)) { return "";}
-iB = iB || 0; iE = iE || strD.length; return strD.substring(iB, iE).split(strF).join(strR);}
-Stack = function() { this.m_arr = new Array();}
-Stack.prototype.clear = function() { this.m_arr = new Array();}
-Stack.prototype.count = function() { return this.m_arr.length;}
-Stack.prototype.destroy = function() { this.m_arr = null;}
-Stack.prototype.peek = function() { if(this.m_arr.length == 0) { return null;}
-return this.m_arr[this.m_arr.length - 1];}
-Stack.prototype.pop = function() { if(this.m_arr.length == 0) { return null;}
-var o = this.m_arr[this.m_arr.length - 1]; this.m_arr.length--; return o;}
-Stack.prototype.push = function(o) { this.m_arr[this.m_arr.length] = o;}
-function isEmpty(str) { return (str==null) || (str.length==0);}
-function trim(trimString, leftTrim, rightTrim) { if (isEmpty(trimString)) { return "";}
-if (leftTrim == null) { leftTrim = true;}
-if (rightTrim == null) { rightTrim = true;}
-var left=0; var right=0; var i=0; var k=0; if (leftTrim == true) { while ((i<trimString.length) && (whitespace.indexOf(trimString.charAt(i++))!=-1)) { left++;}
-}
-if (rightTrim == true) { k=trimString.length-1; while((k>=left) && (whitespace.indexOf(trimString.charAt(k--))!=-1)) { right++;}
-}
-return trimString.substring(left, trimString.length - right);}
-function __escapeString(str) { var escAmpRegEx = /&/g; var escLtRegEx = /</g; var escGtRegEx = />/g; var quotRegEx = /"/g;
- var aposRegEx = /'/g;
-
- str = str.replace(escAmpRegEx, "&amp;");
- str = str.replace(escLtRegEx, "&lt;");
- str = str.replace(escGtRegEx, "&gt;");
- str = str.replace(quotRegEx, "&quot;");
- str = str.replace(aposRegEx, "&apos;");
-
- return str;
-}
-
-/**
- * function __unescapeString
- *
- * author: David Joham djoham@yahoo.com
- *
- * @param str : string - The string to be unescaped
- *
- * @return : string - The unescaped string
- */
-function __unescapeString(str) {
-
- var escAmpRegEx = /&amp;/g;
- var escLtRegEx = /&lt;/g;
- var escGtRegEx = /&gt;/g;
- var quotRegEx = /&quot;/g;
- var aposRegEx = /&apos;/g;
-
- str = str.replace(escAmpRegEx, "&");
- str = str.replace(escLtRegEx, "<");
- str = str.replace(escGtRegEx, ">");
- str = str.replace(quotRegEx, "\"");
- str = str.replace(aposRegEx, "'");
- return str;
-}
diff --git a/o3d/samples/trends/assets/clouds.jpg b/o3d/samples/trends/assets/clouds.jpg
deleted file mode 100644
index 8767681..0000000
--- a/o3d/samples/trends/assets/clouds.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/trends/assets/earth-large-with-ocean-mask.png b/o3d/samples/trends/assets/earth-large-with-ocean-mask.png
deleted file mode 100644
index 850d0ff..0000000
--- a/o3d/samples/trends/assets/earth-large-with-ocean-mask.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/trends/assets/earth-large.jpg b/o3d/samples/trends/assets/earth-large.jpg
deleted file mode 100644
index ce797dc..0000000
--- a/o3d/samples/trends/assets/earth-large.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/trends/assets/earth.jpg b/o3d/samples/trends/assets/earth.jpg
deleted file mode 100644
index f04b09d..0000000
--- a/o3d/samples/trends/assets/earth.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/trends/assets/energy.png b/o3d/samples/trends/assets/energy.png
deleted file mode 100644
index 576ddbb..0000000
--- a/o3d/samples/trends/assets/energy.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/trends/assets/moon.jpg b/o3d/samples/trends/assets/moon.jpg
deleted file mode 100644
index f916c70..0000000
--- a/o3d/samples/trends/assets/moon.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/trends/assets/night-large.jpg b/o3d/samples/trends/assets/night-large.jpg
deleted file mode 100644
index 4979d6e..0000000
--- a/o3d/samples/trends/assets/night-large.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/trends/assets/night.jpg b/o3d/samples/trends/assets/night.jpg
deleted file mode 100644
index 2bfb99e..0000000
--- a/o3d/samples/trends/assets/night.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/trends/trends-with-particles.html b/o3d/samples/trends/trends-with-particles.html
deleted file mode 100644
index e80aa6a2..0000000
--- a/o3d/samples/trends/trends-with-particles.html
+++ /dev/null
@@ -1,791 +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.
--->
-
-<!--
-TODO:
- O Set Sun to correct location for time.
- O Put in moon
- O Put in Google satellite
- O Put in Star Shader that uses star data from a texture
- O Add Halo
- O Add Sun Model
- O with glowing rays.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<title>
-Google Trends Visualizer
-</title>
-<style>
- html, body {
- border: 0;
- margin: 0;
- height: 100%;
- height: 100%;
- text-align: center;
- }
-</style>
-</head>
-<body onload="init();" onunload="uninit();">
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.arcball');
-o3djs.require('o3djs.io');
-o3djs.require('o3djs.particles');
-
-var g = {
- EARTH_RADIUS: 25,
- ENERGY_WIDTH: 0.5,
- ENERGY_HEIGHT: 10
-};
-
-g.camera = {
- eye: [0, 0, 75],
- target: [0, 0, 0]
-};
-
-var g_finished = false; // for selenium.
-var dragging = false;
-
-function startDragging(e) {
- g.lastRot = g.thisRot;
- g.aball.click([e.x, e.y]);
- dragging = true;
-}
-
-function drag(e) {
- if (dragging) {
- var rotationQuat = g.aball.drag([e.x, e.y]);
- var rot_mat = g.quaternions.quaternionToRotation(rotationQuat);
- g.thisRot = g.math.matrix4.mul(g.lastRot, rot_mat);
-
- var m = g.root.localMatrix;
- g.math.matrix4.setUpper3x3(m, g.thisRot);
- g.root.localMatrix = m;
- }
-}
-
-function stopDragging(e) {
- dragging = false;
-}
-
-function updateViewFromCamera() {
- var target = g.camera.target;
- var eye = g.camera.eye;
- var up = [0, 1, 0];
- g.viewInfo.drawContext.view = g.math.matrix4.lookAt(eye, target, up);
- g.eyePosParam.value = eye;
-}
-
-function scrollMe(e) {
- if (e.deltaY > 0) {
- g.camera.eye[0] *= 11 / 12;
- g.camera.eye[1] *= 11 / 12;
- g.camera.eye[2] *= 11 / 12;
-
- } else {
- g.camera.eye[0] *= (1 + 1 / 12);
- g.camera.eye[1] *= (1 + 1 / 12);
- g.camera.eye[2] *= (1 + 1 / 12);
- }
- updateViewFromCamera();
-}
-
-function getURL(path) {
- var base = window.location.href;
- var index = base.lastIndexOf('/');
- base = base.substring(0, index + 1);
- return base + path;
-}
-
-function setClientSize() {
- var newWidth = g.client.width;
- var newHeight = g.client.height;
-
- if (newWidth != g.o3dWidth || newHeight != g.o3dHeight) {
- g.o3dWidth = newWidth;
- g.o3dHeight = newHeight;
-
- // Create a perspective projection matrix
- g.viewInfo.drawContext.projection = g.math.matrix4.perspective(
- g.math.degToRad(45), g.o3dWidth / g.o3dHeight, 0.1, 5000);
-
- // Sets a new area size for arcball.
- g.aball.setAreaSize(g.o3dWidth, g.o3dHeight);
- }
-}
-
-function onRender() {
- setClientSize();
-}
-
-// A geo is a float where the integer part is in degrees and the fractional
-// part is in 60ths
-function geoToRad(geo) {
- var sign = geo >= 0 ? 1 : -1;
- geo = Math.abs(geo);
- var integerPart = Math.floor(geo);
- var fractionalPart = (geo % 1) * 100;
- fractionalPart = fractionalPart / 60;
- return g.math.degToRad(integerPart + fractionalPart);
-}
-
-function addEnergyShard(latitude, longitude, energy, height, color) {
- // Decide how many particles we want in this shard.
- g.trailParameters.numParticles = Math.floor(Math.random() * 10) + 1;
- // Set the color for the shard's particles.
- g.trailParameters.colorMult = color;
- // Compute a base position for the shard and a velocity for the particles.
- var matrix = g.math.matrix4.rotationZ(geoToRad(latitude));
- g.math.matrix4.rotateY(matrix, geoToRad(-longitude));
- g.math.matrix4.rotateZ(matrix, g.math.degToRad(90));
- g.shardStartPosition =
- g.math.matrix4.transformDirection(matrix, [0, g.EARTH_RADIUS, 0]);
- g.shardVelocity = g.math.matrix4.transformDirection(matrix, [0, 2.5, 0]);
- // Birth the particles. NOTE: the position passed in here is overridden by
- // our per particle function.
- g.trail.birthParticles([0, 0, 0]);
-}
-
-function shardPerParticleFunc(particleIndex, parameters) {
- // This function sets parameters for each individual particle that is
- // birthed. We'll calculate these in addEneryShard so all the
- // particles genearted come out of the same position going in the
- // same direction
- parameters.position = g.shardStartPosition;
- parameters.velocity = g.shardVelocity;
- // Pick a random time for the particle to appear.
- parameters.startTime = Math.random() * parameters.timeRange;
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-/**
- * Initializes o3d
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- var path = window.location.href;
- var index = path.lastIndexOf('/');
-
- g.o3dElement = clientElements[0];
- g.o3d = g.o3dElement.o3d;
- g.math = o3djs.math;
- g.quaternions = o3djs.quaternions;
- g.client = g.o3dElement.client;
-
- g.pack = g.client.createPack();
-
- // Create the render graph for a view.
- g.viewInfo = o3djs.rendergraph.createBasicView(
- g.pack,
- g.client.root,
- g.client.renderGraphRoot);
-
- // Set the background color to black.
- g.viewInfo.clearBuffer.clearColor = [0, 0, 0, 0];
-
- // Set states for shards.
- g.viewInfo.zOrderedState.getStateParam('CullMode').value =
- g.o3d.State.CULL_NONE;
- g.viewInfo.zOrderedState.getStateParam('DestinationBlendFunction').value =
- g.o3d.State.BLENDFUNC_ONE;
- g.viewInfo.zOrderedState.getStateParam('ZWriteEnable').value = false;
-
- g.viewInfo.performanceDrawPass.sortMethod = g.o3d.DrawList.BY_PRIORITY;
-
- g.lastRot = g.math.matrix4.identity();
- g.thisRot = g.math.matrix4.identity();
-
- var root = g.client.root;
-
- // Create a param for the sun and eye positions that we can bind
- // to auto update a bunch of materials.
- g.globalParams = g.pack.createObject('ParamObject');
- g.sunPosParam = g.globalParams.createParam('sunPos', 'ParamFloat3');
- g.sunPosParam.value = [1000, 200, 100];
- g.eyePosParam = g.globalParams.createParam('eyePos', 'ParamFloat3');
-
- updateViewFromCamera();
-
- g.aball = o3djs.arcball.create(100, 100);
- setClientSize();
-
- g.client.setRenderCallback(onRender);
-
-
- // Create Materials.
- var effectNames = [
- "noTexture",
- "dayOnly",
- "nightAndDay",
- "mask",
- "atmosphere"
- ];
- g.materials = [];
- for (var ii = 0; ii < effectNames.length; ++ii) {
- var effectName = effectNames[ii];
- var effect = g.pack.createObject('Effect');
- effect.loadFromFXString(document.getElementById(effectName).value);
-
- // Create a Material for the effect.
- var material = g.pack.createObject('Material');
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shader to use.
- material.effect = effect;
-
- // Set the material's drawList
- material.drawList = g.viewInfo.performanceDrawList;
-
- // This will create the effects's params on the material.
- effect.createUniformParameters(material);
-
- // Bind the sun position to a global value so we can easily change it
- // globally.
- var sunParam = material.getParam('sunPos');
- if (sunParam) {
- sunParam.bind(g.sunPosParam);
- }
-
- // Save off the material.
- g.materials.push(material);
- }
- g.noTextureMaterial = g.materials[0];
- g.dayOnlyMaterial = g.materials[1];
- g.nightAndDayMaterial = g.materials[2];
- g.maskMaterial = g.materials[3];
- g.atmosphereMaterial = g.materials[4];
-
- // create samplers
- g.samplers = [];
- for (var ii = 0; ii < 4; ++ii) {
- var sampler = g.pack.createObject('Sampler');
- g.samplers[ii] = sampler;
- }
-
- g.daySampler = g.samplers[0];
- g.nightSampler = g.samplers[1];
- g.maskSampler = g.samplers[2];
-
- // set the material samplers.
- g.dayOnlyMaterial.getParam('daySampler').value = g.daySampler;
- g.nightAndDayMaterial.getParam('daySampler').value = g.daySampler;
- g.nightAndDayMaterial.getParam('nightSampler').value = g.nightSampler;
- g.maskMaterial.getParam('daySampler').value = g.daySampler;
- g.maskMaterial.getParam('maskSampler').value = g.maskSampler;
- g.maskMaterial.getParam('nightSampler').value = g.nightSampler;
-
- // Setup counters for shard animation.
- g.shardCounter = g.pack.createObject('SecondCounter');
-
- // Setup counters to fade in textures.
- g.flatToDayCounter = g.pack.createObject('SecondCounter');
- g.flatToDayCounter.end = 1;
- g.flatToDayCounter.multiplier = 0.5;
- g.flatToDayCounter.countMode = g.o3d.Counter.ONCE;
- g.flatToDayCounter.running = false;
- g.flatToDayCounter.addCallback(1, loadNightTexture);
- g.dayOnlyMaterial.getParam('mix').bind(
- g.flatToDayCounter.getParam('count'));
-
- g.dayOnlyToNightCounter = g.pack.createObject('SecondCounter');
- g.dayOnlyToNightCounter.end = 1;
- g.dayOnlyToNightCounter.multiplier = 0.5;
- g.dayOnlyToNightCounter.countMode = g.o3d.Counter.ONCE;
- g.dayOnlyToNightCounter.running = false;
- g.dayOnlyToNightCounter.addCallback(1, loadMaskTexture);
- g.nightAndDayMaterial.getParam('mix').bind(
- g.dayOnlyToNightCounter.getParam('count'));
-
- g.noMaskToMaskCounter = g.pack.createObject('SecondCounter');
- g.noMaskToMaskCounter.end = 1;
- g.noMaskToMaskCounter.multiplier = 0.5;
- g.noMaskToMaskCounter.countMode = g.o3d.Counter.ONCE;
- g.noMaskToMaskCounter.running = false;
- g.maskMaterial.getParam('mix').bind(
- g.noMaskToMaskCounter.getParam('count'));
-
- // Create a sphere at the origin for the earth.
- var earth = o3djs.primitives.createSphere(g.pack,
- g.noTextureMaterial,
- 25,
- 50,
- 50);
-
- // Get a the element so we can set its material later.
- g.earthPrimitive = earth.elements[0];
- g.atmosphereState = g.pack.createObject('State');
- g.atmosphereState.getStateParam('AlphaBlendEnable').value = true;
- g.atmosphereState.getStateParam('SourceBlendFunction').value =
- g.o3d.State.BLENDFUNC_SOURCE_ALPHA;
- g.atmosphereState.getStateParam('DestinationBlendFunction').value =
- g.o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA;
- g.atmosphereState.getStateParam('ZWriteEnable').value = false;
- g.atmosphereMaterial.state = g.atmosphereState;
-
- g.root = g.pack.createObject('Transform');
- g.root.parent = g.client.root;
- g.earth = g.pack.createObject('Transform');
- g.earth.addShape(earth);
- g.earth.parent = g.root;
-
- // Create a sphere at the origin for the atmosphere.
- var atmosphere = o3djs.primitives.createSphere(g.pack,
- g.atmosphereMaterial,
- 26,
- 50,
- 50);
- g.atmospherePrimitive = atmosphere.elements[0];
- g.atmospherePrimitive.priority = 1;
- g.atmosphere = g.pack.createObject('Transform');
- g.atmosphere.addShape(atmosphere);
- g.atmosphere.parent = g.root;
-
- // Make a particle system
- g.particleSystem = o3djs.particles.createParticleSystem(
- g.pack,
- g.viewInfo,
- g.shardCounter.getParam('count'),
- g.math.pseudoRandom);
-
- // Make a transform for the particle emitter.
- var transform = g.pack.createObject('Transform');
- transform.parent = g.root;
- // Make a single pixel white texture as our particle.
- var texture = g.pack.createTexture2D(1, 1, g.o3d.Texture.ARGB8, 1, false);
- texture.set(0, [1, 1, 1, 1]);
-
- // Setup some basic parameters for our particles.
- g.trailParameters = {
- lifeTime: 4, // each particle lasts 4 seconds
- timeRange: 4, // The clock is modded by this so the *world* clock repeats
- // every 4 seconds making each particle reappear
- startSize: 0.1, // Size to start a particle
- endSize: 0.1, // Size to end a particle
- // (the particle lerps in side between start and end)
- };
-
- // Create a trail. Trails are just a particle system that lets us more
- // easily birth individual particles.
- g.trail = g.particleSystem.createTrail(
- transform, // Transform for particles.
- 10000, // Total number of particles in system. If 10001
- // particles are birthed, the oldest particle is
- // reused.
- g.trailParameters, // Our static birth parameters.
- texture, // The texture to use.
- shardPerParticleFunc); // A function to set parameters per particle.
- g.trail.setState(o3djs.particles.ParticleStateIds.BLEND);
- // This ramp makes the particles full bright for 4/5ths of their lifespan
- // and they fade out during the last 1/5th.
- g.trail.setColorRamp(
- [1, 1, 1, 1,
- 1, 1, 1, 1,
- 1, 1, 1, 1,
- 1, 1, 1, 1,
- 1, 1, 1, 0]);
-
-
- addEnergyShard(0, 0, 1, 1, [1, 1, 1, 1]);
-
- // Honolulu, Hawaii, 21, 18, 157, 50
- addEnergyShard(21.18, 157.50, 1, 1, [0, 1, 0, 1]);
- // San Francisco, Calif. 37 47 122 26
- addEnergyShard(37.47, 122.26, 1, 1, [1, 0.5, 0.5, 1]);
-
- for (var ii = 0; ii < 24; ++ii) {
- var longitude = Math.random() * 360;
- var latitude = Math.random() * 360 - 180;
- var color = [ Math.random() * 0.5 + 0.2,
- Math.random() * 0.5 + 0.2,
- Math.random() * 0.5 + 0.2,
- 1 ];
- // Make a least 1 color component full bright.
- color[Math.floor(Math.random() * 2.99)] = 1;
- for (var jj = 0; jj < 24; ++jj) {
- addEnergyShard(latitude + (Math.random() - 0.5) * 10,
- longitude + (Math.random() - 0.5) * 10,
- 1,
- 1,
- color);
- }
- }
-
- o3djs.event.addEventListener(g.o3dElement, 'mousedown', startDragging);
- o3djs.event.addEventListener(g.o3dElement, 'mousemove', drag);
- o3djs.event.addEventListener(g.o3dElement, 'mouseup', stopDragging);
- o3djs.event.addEventListener(g.o3dElement, 'wheel', scrollMe);
-
- loadDayTexture();
-}
-
-function loadTexture(path, callback) {
- var url = getURL(path);
- o3djs.io.loadTexture(g.pack, url, function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- callback(texture);
- }
- });
-}
-
-function loadDayTexture() {
- loadTexture('assets/earth.jpg', function(texture) {
- g.daySampler.texture = texture;
- g.earthPrimitive.material = g.dayOnlyMaterial;
- g.flatToDayCounter.running = true;
- });
-}
-
-function loadNightTexture() {
- loadTexture('assets/night.jpg', function(texture) {
- g.nightSampler.texture = texture;
- g.earthPrimitive.material = g.nightAndDayMaterial;
- g.dayOnlyToNightCounter.running = true;
- });
-}
-
-function loadMaskTexture() {
- loadTexture('assets/earth-large-with-ocean-mask.png', function(texture) {
- g.maskSampler.texture = texture;
- g.earthPrimitive.material = g.maskMaterial;
- g.noMaskToMaskCounter.running = true;
- g_finished = true; // for selenium
- });
-}
-
-function uninit() {
- // TODO: We should clean up any counters that have callbacks here.
- if (g.client) {
- g.client.cleanup();
- }
-}
-
-</script>
-<!--<h1>
-Google Trends Visualizer.
-</h1>-->
-<div id="o3d" style="width:100%; height: 100%;"></div>
-<div style="display:none">
-<textarea id="noTexture" name="fx" cols="80" rows="20">
-float4x4 worldViewProjection : WorldViewProjection;
-float4x4 world : World;
-float4x4 view : View;
-
-float3 sunPos;
-
-struct a2v {
- float4 pos : POSITION;
- float3 normal : NORMAL;
-};
-
-struct v2f {
- float4 pos : POSITION;
- float3 normal : TEXCOORD0;
- float3 sun : TEXCOORD1;
- float3 view : TEXCOORD2;
-};
-
-v2f vsMain(a2v IN) {
- v2f OUT;
-
- OUT.pos = mul(IN.pos, worldViewProjection);
- OUT.normal = mul(float4(IN.normal, 0), world).xyz;
- float3 worldPos = mul(IN.pos, world).xyz;
- OUT.sun = sunPos - worldPos;
- OUT.view = (view[3] - worldPos);
-
- return OUT;
-}
-
-float4 psMain(v2f IN): COLOR {
- float3 norm = normalize(IN.normal);
- float3 sun = normalize(IN.sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1 - sqrt(light);
- dayNight = dayNight * dayNight;
- dayNight = (1 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0, 1);
- float3 view = normalize(IN.view);
- float3 r = normalize(reflect(norm, sun));
- float4 litR = lit(light, dot(r, view), 0.0).y;
- float3 day = float3(0.5, 0.5, 1.0) * litR.y + float3(1,1,1) * litR.z;
- float3 night = float3(0.2, 0.2, 0.5);
- return float4(lerp(night, day, dayNight),1);
-}
-
-// #o3d VertexShaderEntryPoint vsMain
-// #o3d PixelShaderEntryPoint psMain
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<textarea id="dayOnly" name="fx" cols="80" rows="20">
-float4x4 worldViewProjection : WorldViewProjection;
-float4x4 world : World;
-float4x4 view : View;
-
-float3 sunPos;
-float mix;
-
-sampler2D daySampler;
-
-struct a2v {
- float4 pos : POSITION;
- float3 normal : NORMAL;
- float2 uv : TEXCOORD0;
-};
-
-struct v2f {
- float4 pos : POSITION;
- float2 uv : TEXCOORD0;
- float3 normal : TEXCOORD1;
- float3 sun : TEXCOORD2;
- float3 view : TEXCOORD3;
-};
-
-v2f vsMain(a2v IN) {
- v2f OUT;
-
- OUT.pos = mul(IN.pos, worldViewProjection);
- OUT.uv = IN.uv;
- OUT.normal = mul(float4(IN.normal, 0), world).xyz;
- float3 worldPos = mul(IN.pos, world).xyz;
- OUT.sun = sunPos - worldPos;
- OUT.view = (view[3] - worldPos);
-
- return OUT;
-}
-
-float4 psMain(v2f IN): COLOR {
- float3 norm = normalize(IN.normal);
- float3 sun = normalize(IN.sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1 - sqrt(light);
- dayNight = dayNight * dayNight;
- dayNight = (1 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0, 1);
- float3 view = normalize(IN.view);
- float3 r = normalize(reflect(norm, sun));
- float4 litR = lit(light, dot(r, view), 0.0).y;
- float3 earth = tex2D(daySampler, IN.uv).xyz;
- float3 day = lerp(float3(0.5, 0.5, 1.0), earth, mix);
- day = day * litR.y + float3(1,1,1) * litR.z;
- float3 night = lerp(float3(0.2, 0.2, 0.5), earth * 0.3, mix);
- return float4(lerp(night, day, dayNight),1);
-}
-
-// #o3d VertexShaderEntryPoint vsMain
-// #o3d PixelShaderEntryPoint psMain
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<textarea id="nightAndDay" name="fx" cols="80" rows="20">
-float4x4 worldViewProjection : WorldViewProjection;
-float4x4 world : World;
-float4x4 view : View;
-
-float3 sunPos;
-float mix;
-
-sampler2D daySampler;
-sampler2D nightSampler;
-
-struct a2v {
- float4 pos : POSITION;
- float3 normal : NORMAL;
- float2 uv : TEXCOORD0;
-};
-
-struct v2f {
- float4 pos : POSITION;
- float2 uv : TEXCOORD0;
- float3 normal : TEXCOORD1;
- float3 sun : TEXCOORD2;
- float3 view : TEXCOORD3;
-};
-
-v2f vsMain(a2v IN) {
- v2f OUT;
-
- OUT.pos = mul(IN.pos, worldViewProjection);
- OUT.uv = IN.uv;
- OUT.normal = mul(float4(IN.normal, 0), world).xyz;
- float3 worldPos = mul(IN.pos, world).xyz;
- OUT.sun = sunPos - worldPos;
- OUT.view = (view[3] - worldPos);
-
- return OUT;
-}
-
-float4 psMain(v2f IN): COLOR {
- float3 norm = normalize(IN.normal);
- float3 sun = normalize(IN.sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1 - sqrt(light);
- dayNight = dayNight * dayNight;
- dayNight = (1 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0, 1);
- float3 view = normalize(IN.view);
- float3 r = normalize(reflect(norm, sun));
- float4 litR = lit(light, dot(r, view), 0.0).y;
- float3 earth = tex2D(daySampler, IN.uv).xyz;
- float3 day = tex2D(daySampler, IN.uv).xyz;
- float3 night = lerp(day * 0.3, tex2D(nightSampler, IN.uv).xyz, mix);
- day = day * litR.y + float3(1,1,1) * litR.z;
- return float4(lerp(night, day, dayNight),1);
-}
-
-// #o3d VertexShaderEntryPoint vsMain
-// #o3d PixelShaderEntryPoint psMain
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<!--
-This shader renders the ocean different then the non-ocean using a mask
-stored in the alpha channel of the maskSampler
--->
-<textarea id="mask" name="fx" cols="80" rows="20">
-float4x4 worldViewProjection : WorldViewProjection;
-float4x4 world : World;
-float4x4 view : View;
-
-float3 sunPos;
-float mix;
-
-sampler2D daySampler;
-sampler2D nightSampler;
-sampler2D maskSampler;
-
-struct a2v {
- float4 pos : POSITION;
- float3 normal : NORMAL;
- float2 uv : TEXCOORD0;
-};
-
-struct v2f {
- float4 pos : POSITION;
- float2 uv : TEXCOORD0;
- float3 normal : TEXCOORD1;
- float3 sun : TEXCOORD2;
- float3 view : TEXCOORD3;
-};
-
-v2f vsMain(a2v IN) {
- v2f OUT;
-
- OUT.pos = mul(IN.pos, worldViewProjection);
- OUT.uv = IN.uv;
- OUT.normal = mul(float4(IN.normal, 0), world).xyz;
- float3 worldPos = mul(IN.pos, world).xyz;
- OUT.sun = sunPos - worldPos;
- OUT.view = (view[3] - worldPos);
-
- return OUT;
-}
-
-float4 psMain(v2f IN): COLOR {
- float3 norm = normalize(IN.normal);
- float3 sun = normalize(IN.sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1 - sqrt(light);
- dayNight = dayNight * dayNight;
- dayNight = (1 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0, 1);
- float3 view = normalize(IN.view);
- float3 r = normalize(reflect(norm, sun));
- float4 litR = lit(light, dot(r, view), 0.0).y;
- float3 earth = tex2D(daySampler, IN.uv).xyz;
- float4 mask = tex2D(maskSampler, IN.uv);
- float3 day = lerp(tex2D(daySampler, IN.uv).xyz,
- mask.xyz, mix);
- float3 night = tex2D(nightSampler, IN.uv).xyz;
- day = day * litR.y + float3(1,1,1) * litR.z * (1 - mask.w * mix);
-
- float3 color = lerp(night, day, dayNight);
- return float4(color,1);
-}
-
-// #o3d VertexShaderEntryPoint vsMain
-// #o3d PixelShaderEntryPoint psMain
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<textarea id="atmosphere" name="fx" cols="80" rows="20">
-float4x4 worldViewProjection : WorldViewProjection;
-float4x4 worldView : WorldView;
-float3 sunPos;
-float3 eyePos;
-
-struct a2v {
- float4 pos : POSITION;
- float3 norm : NORMAL;
-};
-
-struct v2f {
- float4 pos : POSITION;
- float3 normal : TEXCOORD0;
-};
-
-v2f vsMain(a2v IN) {
- v2f OUT;
-
- OUT.pos = mul(IN.pos, worldViewProjection);
- OUT.normal = normalize(mul(float4(IN.norm,0), worldView).xyz);
- return OUT;
-}
-
-float4 psMain(v2f IN): COLOR {
- float n = 1 - log(2 * normalize(IN.normal).z);
- return float4(0.3, 0.3, 1, n * n * n * n);
-}
-
-// #o3d VertexShaderEntryPoint vsMain
-// #o3d PixelShaderEntryPoint psMain
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
-</html>
-
-
diff --git a/o3d/samples/trends/trends.html b/o3d/samples/trends/trends.html
deleted file mode 100644
index 7b49537..0000000
--- a/o3d/samples/trends/trends.html
+++ /dev/null
@@ -1,866 +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.
--->
-
-<!--
-TODO:
- O Set Sun to correct location for time.
- O Put in moon
- O Put in Google satellite
- O Put in Star Shader that uses star data from a texture
- O Add Halo
- O Add Sun Model
- O with glowing rays.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<title>
-Google Trends Visualizer
-</title>
-<style>
- html, body {
- border: 0;
- margin: 0;
- height: 100%;
- height: 100%;
- text-align: center;
- }
-</style>
-</head>
-<body onload="init();" onunload="uninit();">
-<script type="text/javascript" src="../o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.arcball');
-o3djs.require('o3djs.io');
-
-var g = {
- EARTH_RADIUS: 25,
- ENERGY_WIDTH: 0.5,
- ENERGY_HEIGHT: 10
-};
-
-g.camera = {
- eye: [0, 0, 75],
- target: [0, 0, 0]
-};
-
-var g_finished = false; // for selenium.
-var dragging = false;
-
-function startDragging(e) {
- g.lastRot = g.thisRot;
- g.aball.click([e.x, e.y]);
- dragging = true;
-}
-
-function drag(e) {
- if (dragging) {
- var rotationQuat = g.aball.drag([e.x, e.y]);
- var rot_mat = g.quaternions.quaternionToRotation(rotationQuat);
- g.thisRot = g.math.matrix4.mul(g.lastRot, rot_mat);
-
- var m = g.root.localMatrix;
- g.math.matrix4.setUpper3x3(m, g.thisRot);
- g.root.localMatrix = m;
- }
-}
-
-function stopDragging(e) {
- dragging = false;
-}
-
-function updateViewFromCamera() {
- var target = g.camera.target;
- var eye = g.camera.eye;
- var up = [0, 1, 0];
- g.viewInfo.drawContext.view = g.math.matrix4.lookAt(eye, target, up);
- g.eyePosParam.value = eye;
-}
-
-function scrollMe(e) {
- if (e.deltaY > 0) {
- g.camera.eye[0] *= 11 / 12;
- g.camera.eye[1] *= 11 / 12;
- g.camera.eye[2] *= 11 / 12;
-
- } else {
- g.camera.eye[0] *= (1 + 1 / 12);
- g.camera.eye[1] *= (1 + 1 / 12);
- g.camera.eye[2] *= (1 + 1 / 12);
- }
- updateViewFromCamera();
-}
-
-function getURL(path) {
- var base = window.location.href;
- var index = base.lastIndexOf('/');
- base = base.substring(0, index + 1);
- return base + path;
-}
-
-function setClientSize() {
- var newWidth = g.client.width;
- var newHeight = g.client.height;
-
- if (newWidth != g.o3dWidth || newHeight != g.o3dHeight) {
- g.o3dWidth = newWidth;
- g.o3dHeight = newHeight;
-
- // Create a perspective projection matrix
- g.viewInfo.drawContext.projection = g.math.matrix4.perspective(
- g.math.degToRad(45), g.o3dWidth / g.o3dHeight, 0.1, 5000);
-
- // Sets a new area size for arcball.
- g.aball.setAreaSize(g.o3dWidth, g.o3dHeight);
- }
-}
-
-function onRender() {
- setClientSize();
-}
-
-function createEnergyShape(pack, material, width, height) {
- var vertexInfo = o3djs.primitives.createVertexInfo();
- var positionStream = vertexInfo.addStream(
- 3, g.o3d.Stream.POSITION);
- var normalStream = vertexInfo.addStream(
- 3, g.o3d.Stream.NORMAL);
- var colorStream = vertexInfo.addStream(
- 4, g.o3d.Stream.COLOR);
- var texCoordStream = vertexInfo.addStream(
- 2, g.o3d.Stream.TEXCOORD, 0);
-
- var vScale = 1;
- positionStream.addElement(width * -0.5, height, 0);
- normalStream.addElement(0, 0, 1);
- colorStream.addElement(1, 1, 1, 0);
- texCoordStream.addElement(0, 0);
- positionStream.addElement(width * 0.5, height, 0);
- normalStream.addElement(0, 0, 1);
- colorStream.addElement(1, 1, 1, 0);
- texCoordStream.addElement(1, 0);
- positionStream.addElement(width * -0.5, 0, 0);
- normalStream.addElement(0, 0, 1);
- colorStream.addElement(1, 1, 1, 1);
- texCoordStream.addElement(0, vScale);
- positionStream.addElement(width * 0.5, 0, 0);
- normalStream.addElement(0, 0, 1);
- colorStream.addElement(1, 1, 1, 1);
- texCoordStream.addElement(1, vScale);
- positionStream.addElement(0, height, width * -0.5);
- normalStream.addElement(1, 0, 0);
- colorStream.addElement(1, 1, 1, 0);
- texCoordStream.addElement(0, 0);
- positionStream.addElement(0, height, width * 0.5);
- normalStream.addElement(1, 0, 0);
- colorStream.addElement(1, 1, 1, 0);
- texCoordStream.addElement(1, 0);
- positionStream.addElement(0, 0, width * -0.5);
- normalStream.addElement(1, 0, 0);
- colorStream.addElement(1, 1, 1, 1);
- texCoordStream.addElement(0, vScale);
- positionStream.addElement(0, 0, width * 0.5);
- normalStream.addElement(1, 0, 0);
- colorStream.addElement(1, 1, 1, 1);
- texCoordStream.addElement(1, vScale);
-
- vertexInfo.addTriangle(0, 1, 2);
- vertexInfo.addTriangle(1, 2, 3);
- vertexInfo.addTriangle(4, 5, 6);
- vertexInfo.addTriangle(5, 6, 7);
-
- return vertexInfo.createShape(pack, material);
-}
-
-// A geo is a float where the integer part is in degrees and the fractional
-// part is in 60ths
-function geoToRad(geo) {
- var sign = geo >= 0 ? 1 : -1;
- geo = Math.abs(geo);
- var integerPart = Math.floor(geo);
- var fractionalPart = (geo % 1) * 100;
- fractionalPart = fractionalPart / 60;
- return g.math.degToRad(integerPart + fractionalPart);
-}
-
-function addEnergyShard(latitude, longitude, energy, height, color) {
- var transform = g.pack.createObject('Transform');
- transform.rotateZ(geoToRad(latitude));
- transform.rotateY(geoToRad(-longitude));
- transform.rotateZ(g.math.degToRad(90));
- transform.translate(0, g.EARTH_RADIUS, 0);
- transform.parent = g.root;
- transform.addShape(g.energyShape);
- transform.createParam('colorMult', 'ParamFloat4').value = color;
- transform.createParam('offset', 'ParamFloat').value = Math.random();
- return transform;
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-/**
- * Initializes o3d
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- var path = window.location.href;
- var index = path.lastIndexOf('/');
-
- g.o3dElement = clientElements[0];
- g.o3d = g.o3dElement.o3d;
- g.math = o3djs.math;
- g.quaternions = o3djs.quaternions;
- g.client = g.o3dElement.client;
-
- g.pack = g.client.createPack();
-
- // Create the render graph for a view.
- g.viewInfo = o3djs.rendergraph.createBasicView(
- g.pack,
- g.client.root,
- g.client.renderGraphRoot);
-
- // Set the background color to black.
- g.viewInfo.clearBuffer.clearColor = [0, 0, 0, 0];
-
- // Set states for shards.
- g.viewInfo.zOrderedState.getStateParam('CullMode').value =
- g.o3d.State.CULL_NONE;
- g.viewInfo.zOrderedState.getStateParam('DestinationBlendFunction').value =
- g.o3d.State.BLENDFUNC_ONE;
- g.viewInfo.zOrderedState.getStateParam('ZWriteEnable').value = false;
-
- g.viewInfo.performanceDrawPass.sortMethod = g.o3d.DrawList.BY_PRIORITY;
-
- g.lastRot = g.math.matrix4.identity();
- g.thisRot = g.math.matrix4.identity();
-
- var root = g.client.root;
-
- // Create a param for the sun and eye positions that we can bind
- // to auto update a bunch of materials.
- g.globalParams = g.pack.createObject('ParamObject');
- g.sunPosParam = g.globalParams.createParam('sunPos', 'ParamFloat3');
- g.sunPosParam.value = [1000, 200, 100];
- g.eyePosParam = g.globalParams.createParam('eyePos', 'ParamFloat3');
-
- updateViewFromCamera();
-
- g.aball = o3djs.arcball.create(100, 100);
- setClientSize();
-
- g.client.setRenderCallback(onRender);
-
-
- // Create Materials.
- var effectNames = [
- "noTexture",
- "dayOnly",
- "nightAndDay",
- "mask",
- "energy",
- "atmosphere"
- ];
- g.materials = [];
- for (var ii = 0; ii < effectNames.length; ++ii) {
- var effectName = effectNames[ii];
- var effect = g.pack.createObject('Effect');
- effect.loadFromFXString(document.getElementById(effectName).value);
-
- // Create a Material for the effect.
- var material = g.pack.createObject('Material');
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shader to use.
- material.effect = effect;
-
- // Set the material's drawList
- material.drawList = g.viewInfo.performanceDrawList;
-
- // This will create the effects's params on the material.
- effect.createUniformParameters(material);
-
- // Bind the sun position to a global value so we can easily change it
- // globally.
- var sunParam = material.getParam('sunPos');
- if (sunParam) {
- sunParam.bind(g.sunPosParam);
- }
-
- // Save off the material.
- g.materials.push(material);
- }
- g.noTextureMaterial = g.materials[0];
- g.dayOnlyMaterial = g.materials[1];
- g.nightAndDayMaterial = g.materials[2];
- g.maskMaterial = g.materials[3];
- g.energyMaterial = g.materials[4];
- g.energyMaterial.drawList = g.viewInfo.zOrderedDrawList;
- g.atmosphereMaterial = g.materials[5];
-
- // create samplers
- g.samplers = [];
- for (var ii = 0; ii < 4; ++ii) {
- var sampler = g.pack.createObject('Sampler');
- g.samplers[ii] = sampler;
- }
-
- g.daySampler = g.samplers[0];
- g.nightSampler = g.samplers[1];
- g.maskSampler = g.samplers[2];
- g.energySampler = g.samplers[3];
-
- // set the material samplers.
- g.dayOnlyMaterial.getParam('daySampler').value = g.daySampler;
- g.nightAndDayMaterial.getParam('daySampler').value = g.daySampler;
- g.nightAndDayMaterial.getParam('nightSampler').value = g.nightSampler;
- g.maskMaterial.getParam('daySampler').value = g.daySampler;
- g.maskMaterial.getParam('maskSampler').value = g.maskSampler;
- g.maskMaterial.getParam('nightSampler').value = g.nightSampler;
- g.energyMaterial.getParam('energySampler').value = g.energySampler;
-
- // Create energy texture(s)
- {
- var dots = [ 0, 1, 0, 1, 0, 0, 1, 0,
- 1, 0, 0, 1, 0, 1, 0, 0,
- 1, 0, 1, 0, 0, 0, 1, 0,
- 0, 1, 0, 1, 0, 0, 1, 0 ];
- var texture = g.pack.createTexture2D(3,
- dots.length,
- g.o3d.Texture.XRGB8,
- 1,
- false);
- var pixels = [];
- for (var yy = 0; yy < dots.length; ++yy) {
- for (var xx = 0; xx < 3; ++xx) {
- var pixelOffset = (yy * 3 + xx) * 3;
- var color = (xx == 1) ? dots[yy] : 0;
- for (var cc = 0; cc < 3; ++cc) {
- pixels[pixelOffset + cc] = color;
- }
- }
- }
- texture.set(0, pixels);
- g.energySampler.texture = texture;
- }
-
- // Setup counters for shard animation.
- g.shardCounter = g.pack.createObject('SecondCounter');
- g.shardCounter.multiplier = 0.1;
- g.energyMaterial.getParam('time').bind(
- g.shardCounter.getParam('count'));
-
- // Setup counters to fade in textures.
- g.flatToDayCounter = g.pack.createObject('SecondCounter');
- g.flatToDayCounter.end = 1;
- g.flatToDayCounter.multiplier = 0.5;
- g.flatToDayCounter.countMode = g.o3d.Counter.ONCE;
- g.flatToDayCounter.running = false;
- g.flatToDayCounter.addCallback(1, loadNightTexture);
- g.dayOnlyMaterial.getParam('mix').bind(
- g.flatToDayCounter.getParam('count'));
-
- g.dayOnlyToNightCounter = g.pack.createObject('SecondCounter');
- g.dayOnlyToNightCounter.end = 1;
- g.dayOnlyToNightCounter.multiplier = 0.5;
- g.dayOnlyToNightCounter.countMode = g.o3d.Counter.ONCE;
- g.dayOnlyToNightCounter.running = false;
- g.dayOnlyToNightCounter.addCallback(1, loadMaskTexture);
- g.nightAndDayMaterial.getParam('mix').bind(
- g.dayOnlyToNightCounter.getParam('count'));
-
- g.noMaskToMaskCounter = g.pack.createObject('SecondCounter');
- g.noMaskToMaskCounter.end = 1;
- g.noMaskToMaskCounter.multiplier = 0.5;
- g.noMaskToMaskCounter.countMode = g.o3d.Counter.ONCE;
- g.noMaskToMaskCounter.running = false;
- g.maskMaterial.getParam('mix').bind(
- g.noMaskToMaskCounter.getParam('count'));
-
- // Create a sphere at the origin for the earth.
- var earth = o3djs.primitives.createSphere(g.pack,
- g.noTextureMaterial,
- 25,
- 50,
- 50);
-
- // Get a the element so we can set its material later.
- g.earthPrimitive = earth.elements[0];
- g.atmosphereState = g.pack.createObject('State');
- g.atmosphereState.getStateParam('AlphaBlendEnable').value = true;
- g.atmosphereState.getStateParam('SourceBlendFunction').value =
- g.o3d.State.BLENDFUNC_SOURCE_ALPHA;
- g.atmosphereState.getStateParam('DestinationBlendFunction').value =
- g.o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA;
- g.atmosphereState.getStateParam('ZWriteEnable').value = false;
- g.atmosphereMaterial.state = g.atmosphereState;
-
- g.root = g.pack.createObject('Transform');
- g.root.parent = g.client.root;
- g.earth = g.pack.createObject('Transform');
- g.earth.addShape(earth);
- g.earth.parent = g.root;
-
- // Create a sphere at the origin for the atmosphere.
- var atmosphere = o3djs.primitives.createSphere(g.pack,
- g.atmosphereMaterial,
- 26,
- 50,
- 50);
- g.atmospherePrimitive = atmosphere.elements[0];
- g.atmospherePrimitive.priority = 1;
- g.atmosphere = g.pack.createObject('Transform');
- g.atmosphere.addShape(atmosphere);
- g.atmosphere.parent = g.root;
-
- g.energyShape = createEnergyShape(g.pack,
- g.energyMaterial,
- g.ENERGY_WIDTH,
- g.ENERGY_HEIGHT);
-
- addEnergyShard(0, 0, 1, 1, [1, 1, 1, 1]);
-
- // Honolulu, Hawaii, 21, 18, 157, 50
- addEnergyShard(21.18, 157.50, 1, 1, [0, 1, 0, 1]);
- // San Francisco, Calif. 37 47 122 26
- addEnergyShard(37.47, 122.26, 1, 1, [1, 0.5, 0.5, 1]);
-
- for (var ii = 0; ii < 24; ++ii) {
- var longitude = Math.random() * 360;
- var latitude = Math.random() * 360 - 180;
- var color = [ Math.random() * 0.5 + 0.2,
- Math.random() * 0.5 + 0.2,
- Math.random() * 0.5 + 0.2,
- 1 ];
- for (var jj = 0; jj < 24; ++jj) {
- addEnergyShard(latitude + (Math.random() - 0.5) * 10,
- longitude + (Math.random() - 0.5) * 10,
- 1,
- 1,
- color);
- }
- }
-
- o3djs.event.addEventListener(g.o3dElement, 'mousedown', startDragging);
- o3djs.event.addEventListener(g.o3dElement, 'mousemove', drag);
- o3djs.event.addEventListener(g.o3dElement, 'mouseup', stopDragging);
- o3djs.event.addEventListener(g.o3dElement, 'wheel', scrollMe);
-
- loadDayTexture();
-}
-
-function loadTexture(path, callback) {
- var url = getURL(path);
- o3djs.io.loadTexture(g.pack, url, function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- callback(texture);
- }
- });
-}
-
-function loadDayTexture() {
- loadTexture('assets/earth.jpg', function(texture) {
- g.daySampler.texture = texture;
- g.earthPrimitive.material = g.dayOnlyMaterial;
- g.flatToDayCounter.running = true;
- });
-}
-
-function loadNightTexture() {
- loadTexture('assets/night.jpg', function(texture) {
- g.nightSampler.texture = texture;
- g.earthPrimitive.material = g.nightAndDayMaterial;
- g.dayOnlyToNightCounter.running = true;
- });
-}
-
-function loadMaskTexture() {
- loadTexture('assets/earth-large-with-ocean-mask.png', function(texture) {
- g.maskSampler.texture = texture;
- g.earthPrimitive.material = g.maskMaterial;
- g.noMaskToMaskCounter.running = true;
- g_finished = true; // for selenium
- });
-}
-
-function uninit() {
- // TODO: We should clean up any counters that have callbacks here.
- if (g.client) {
- g.client.cleanup();
- }
-}
-
-</script>
-<!--<h1>
-Google Trends Visualizer.
-</h1>-->
-<div id="o3d" style="width:100%; height: 100%;"></div>
-<div style="display:none">
-<textarea id="noTexture" name="fx" cols="80" rows="20">
-float4x4 worldViewProjection : WorldViewProjection;
-float4x4 world : World;
-float4x4 view : View;
-
-float3 sunPos;
-
-struct a2v {
- float4 pos : POSITION;
- float3 normal : NORMAL;
-};
-
-struct v2f {
- float4 pos : POSITION;
- float3 normal : TEXCOORD0;
- float3 sun : TEXCOORD1;
- float3 view : TEXCOORD2;
-};
-
-v2f vsMain(a2v IN) {
- v2f OUT;
-
- OUT.pos = mul(IN.pos, worldViewProjection);
- OUT.normal = mul(float4(IN.normal, 0), world).xyz;
- float3 worldPos = mul(IN.pos, world).xyz;
- OUT.sun = sunPos - worldPos;
- OUT.view = (view[3] - worldPos);
-
- return OUT;
-}
-
-float4 psMain(v2f IN): COLOR {
- float3 norm = normalize(IN.normal);
- float3 sun = normalize(IN.sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1 - sqrt(light);
- dayNight = dayNight * dayNight;
- dayNight = (1 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0, 1);
- float3 view = normalize(IN.view);
- float3 r = normalize(reflect(norm, sun));
- float4 litR = lit(light, dot(r, view), 0.0).y;
- float3 day = float3(0.5, 0.5, 1.0) * litR.y + float3(1,1,1) * litR.z;
- float3 night = float3(0.2, 0.2, 0.5);
- return float4(lerp(night, day, dayNight),1);
-}
-
-// #o3d VertexShaderEntryPoint vsMain
-// #o3d PixelShaderEntryPoint psMain
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<textarea id="dayOnly" name="fx" cols="80" rows="20">
-float4x4 worldViewProjection : WorldViewProjection;
-float4x4 world : World;
-float4x4 view : View;
-
-float3 sunPos;
-float mix;
-
-sampler2D daySampler;
-
-struct a2v {
- float4 pos : POSITION;
- float3 normal : NORMAL;
- float2 uv : TEXCOORD0;
-};
-
-struct v2f {
- float4 pos : POSITION;
- float2 uv : TEXCOORD0;
- float3 normal : TEXCOORD1;
- float3 sun : TEXCOORD2;
- float3 view : TEXCOORD3;
-};
-
-v2f vsMain(a2v IN) {
- v2f OUT;
-
- OUT.pos = mul(IN.pos, worldViewProjection);
- OUT.uv = IN.uv;
- OUT.normal = mul(float4(IN.normal, 0), world).xyz;
- float3 worldPos = mul(IN.pos, world).xyz;
- OUT.sun = sunPos - worldPos;
- OUT.view = (view[3] - worldPos);
-
- return OUT;
-}
-
-float4 psMain(v2f IN): COLOR {
- float3 norm = normalize(IN.normal);
- float3 sun = normalize(IN.sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1 - sqrt(light);
- dayNight = dayNight * dayNight;
- dayNight = (1 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0, 1);
- float3 view = normalize(IN.view);
- float3 r = normalize(reflect(norm, sun));
- float4 litR = lit(light, dot(r, view), 0.0).y;
- float3 earth = tex2D(daySampler, IN.uv).xyz;
- float3 day = lerp(float3(0.5, 0.5, 1.0), earth, mix);
- day = day * litR.y + float3(1,1,1) * litR.z;
- float3 night = lerp(float3(0.2, 0.2, 0.5), earth * 0.3, mix);
- return float4(lerp(night, day, dayNight),1);
-}
-
-// #o3d VertexShaderEntryPoint vsMain
-// #o3d PixelShaderEntryPoint psMain
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<textarea id="nightAndDay" name="fx" cols="80" rows="20">
-float4x4 worldViewProjection : WorldViewProjection;
-float4x4 world : World;
-float4x4 view : View;
-
-float3 sunPos;
-float mix;
-
-sampler2D daySampler;
-sampler2D nightSampler;
-
-struct a2v {
- float4 pos : POSITION;
- float3 normal : NORMAL;
- float2 uv : TEXCOORD0;
-};
-
-struct v2f {
- float4 pos : POSITION;
- float2 uv : TEXCOORD0;
- float3 normal : TEXCOORD1;
- float3 sun : TEXCOORD2;
- float3 view : TEXCOORD3;
-};
-
-v2f vsMain(a2v IN) {
- v2f OUT;
-
- OUT.pos = mul(IN.pos, worldViewProjection);
- OUT.uv = IN.uv;
- OUT.normal = mul(float4(IN.normal, 0), world).xyz;
- float3 worldPos = mul(IN.pos, world).xyz;
- OUT.sun = sunPos - worldPos;
- OUT.view = (view[3] - worldPos);
-
- return OUT;
-}
-
-float4 psMain(v2f IN): COLOR {
- float3 norm = normalize(IN.normal);
- float3 sun = normalize(IN.sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1 - sqrt(light);
- dayNight = dayNight * dayNight;
- dayNight = (1 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0, 1);
- float3 view = normalize(IN.view);
- float3 r = normalize(reflect(norm, sun));
- float4 litR = lit(light, dot(r, view), 0.0).y;
- float3 earth = tex2D(daySampler, IN.uv).xyz;
- float3 day = tex2D(daySampler, IN.uv).xyz;
- float3 night = lerp(day * 0.3, tex2D(nightSampler, IN.uv).xyz, mix);
- day = day * litR.y + float3(1,1,1) * litR.z;
- return float4(lerp(night, day, dayNight),1);
-}
-
-// #o3d VertexShaderEntryPoint vsMain
-// #o3d PixelShaderEntryPoint psMain
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<!--
-This shader renders the ocean different then the non-ocean using a mask
-stored in the alpha channel of the maskSampler
--->
-<textarea id="mask" name="fx" cols="80" rows="20">
-float4x4 worldViewProjection : WorldViewProjection;
-float4x4 world : World;
-float4x4 view : View;
-
-float3 sunPos;
-float mix;
-
-sampler2D daySampler;
-sampler2D nightSampler;
-sampler2D maskSampler;
-
-struct a2v {
- float4 pos : POSITION;
- float3 normal : NORMAL;
- float2 uv : TEXCOORD0;
-};
-
-struct v2f {
- float4 pos : POSITION;
- float2 uv : TEXCOORD0;
- float3 normal : TEXCOORD1;
- float3 sun : TEXCOORD2;
- float3 view : TEXCOORD3;
-};
-
-v2f vsMain(a2v IN) {
- v2f OUT;
-
- OUT.pos = mul(IN.pos, worldViewProjection);
- OUT.uv = IN.uv;
- OUT.normal = mul(float4(IN.normal, 0), world).xyz;
- float3 worldPos = mul(IN.pos, world).xyz;
- OUT.sun = sunPos - worldPos;
- OUT.view = (view[3] - worldPos);
-
- return OUT;
-}
-
-float4 psMain(v2f IN): COLOR {
- float3 norm = normalize(IN.normal);
- float3 sun = normalize(IN.sun);
- float light = dot(norm, sun);
- float lightSign = sign(light);
- float dayNight = 1 - sqrt(light);
- dayNight = dayNight * dayNight;
- dayNight = (1 - dayNight) * lightSign;
- dayNight = clamp(dayNight, 0, 1);
- float3 view = normalize(IN.view);
- float3 r = normalize(reflect(norm, sun));
- float4 litR = lit(light, dot(r, view), 0.0).y;
- float3 earth = tex2D(daySampler, IN.uv).xyz;
- float4 mask = tex2D(maskSampler, IN.uv);
- float3 day = lerp(tex2D(daySampler, IN.uv).xyz,
- mask.xyz, mix);
- float3 night = tex2D(nightSampler, IN.uv).xyz;
- day = day * litR.y + float3(1,1,1) * litR.z * (1 - mask.w * mix);
-
- float3 color = lerp(night, day, dayNight);
- return float4(color,1);
-}
-
-// #o3d VertexShaderEntryPoint vsMain
-// #o3d PixelShaderEntryPoint psMain
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<textarea id="energy" name="fx" cols="80" rows="20">
-float4x4 worldViewProjection : WorldViewProjection;
-
-// time is used to scroll the UV coords
-float time;
-
-// offset is used to allow each shard to scroll over a different part of the
-// texture.
-float offset;
-
-// Sets the color of the shard.
-float4 colorMult;
-
-// Provides the dots on the shard.
-sampler2D energySampler;
-
-struct a2v {
- float4 pos : POSITION;
- float3 norm : NORMAL;
- float4 color : COLOR;
- float2 uv : TEXCOORD0;
-};
-
-struct v2f {
- float4 pos : POSITION;
- float2 uv : TEXCOORD0;
- float4 color : TEXCOORD1;
-};
-
-v2f vsMain(a2v IN) {
- v2f OUT;
-
- OUT.pos = mul(IN.pos, worldViewProjection);
- OUT.uv = float2(IN.uv.x, IN.uv.y + time + offset);
- OUT.color = IN.color;
-
- return OUT;
-}
-
-float4 psMain(v2f IN): COLOR {
- return float4(tex2D(energySampler, IN.uv)) * IN.color * colorMult;
-}
-
-// #o3d VertexShaderEntryPoint vsMain
-// #o3d PixelShaderEntryPoint psMain
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<textarea id="atmosphere" name="fx" cols="80" rows="20">
-float4x4 worldViewProjection : WorldViewProjection;
-float4x4 worldView : WorldView;
-float3 sunPos;
-float3 eyePos;
-
-struct a2v {
- float4 pos : POSITION;
- float3 norm : NORMAL;
-};
-
-struct v2f {
- float4 pos : POSITION;
- float3 normal : TEXCOORD0;
-};
-
-v2f vsMain(a2v IN) {
- v2f OUT;
-
- OUT.pos = mul(IN.pos, worldViewProjection);
- OUT.normal = normalize(mul(float4(IN.norm,0), worldView).xyz);
- return OUT;
-}
-
-float4 psMain(v2f IN): COLOR {
- float n = 1 - log(2 * normalize(IN.normal).z);
- return float4(0.3, 0.3, 1, n * n * n * n);
-}
-
-// #o3d VertexShaderEntryPoint vsMain
-// #o3d PixelShaderEntryPoint psMain
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
-</html>
-
-
diff --git a/o3d/samples/tutorial-primitive.html b/o3d/samples/tutorial-primitive.html
deleted file mode 100644
index b6f4c73..0000000
--- a/o3d/samples/tutorial-primitive.html
+++ /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 sample shows how to display something without having to manually setup a
-shader.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Tutorial: Primitive.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.material');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_finished = false; // for selenium testing
-var g_client;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, create a primitive and apply a basic material.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3d = clientElements[0];
- g_client = o3d.client;
-
- // Creates a pack to manage our resources/assets
- var pack = g_client.createPack();
-
- // Create a view.
- var viewInfo = o3djs.rendergraph.createBasicView(
- pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create a material.
- var material = o3djs.material.createBasicMaterial(
- pack,
- viewInfo,
- [1, 0, 0, 1]); // red
-
- // Create a cube.
- var shape = o3djs.primitives.createCube(pack, material, 10);
-
- // Make a transform for the cube, attach the cube and parent it.
- var transform = pack.createObject('Transform');
- transform.parent = g_client.root;
- transform.addShape(shape);
-
- // Make our camera show the scene.
- o3djs.camera.fitContextToScene(g_client.root,
- g_client.width,
- g_client.height,
- viewInfo.drawContext);
-
- g_finished = true; // for selenium
-}
-
-</script>
-</head>
-<body>
-<h1>Tutorial: Primitive.</h1>
-<p>This sample shows how to display something without having to manually setup a
-shader.</p>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-
-</html>
diff --git a/o3d/samples/vertex-shader-animation.html b/o3d/samples/vertex-shader-animation.html
deleted file mode 100644
index 4b1092f..0000000
--- a/o3d/samples/vertex-shader-animation.html
+++ /dev/null
@@ -1,201 +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.
--->
-
-<!--
-O3D Vertex Shader Animation Example.
-
-Demonstrates using a vertex shader for simple animation. The shader moves the
-vertices in a sin wave based on the parameter "time" and the world position
-of the vertices.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Vertex Shader Animation
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- }
-</style>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// global variables
-var g_o3d;
-var g_o3dElement;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_timeParam;
-
-/**
- * Creates the client area.
- */
-function init() {
- // These are here so that they are visible to both the browser (so
- // selenium sees them) and the embedded V8 engine.
- window.g_clock = 0;
- window.g_timeMult = 1;
- window.g_finished = false; // for selenium testing.
-
- // Comment out the line below to run the sample in the browser
- // JavaScript engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and creates the quads.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
-
- // Set window.g_client as well. Otherwise when the sample runs in
- // V8, selenium won't be able to find this variable (it can only see
- // the browser environment).
- window.g_client = g_client = g_o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create a material.
- var material = o3djs.material.createMaterialFromFile(
- g_pack,
- 'shaders/phong-vertex-anim.shader',
- g_viewInfo.performanceDrawList);
-
- // Set the material parameters.
- material.getParam('lightWorldPos').value = [-40, 100, 0];
- material.getParam('lightIntensity').value = [1, 1, 1, 1];
- material.getParam('ambientIntensity').value = [0.1, 0.1, 0.1, 1];
- material.getParam('ambient').value = [1, 1, 1, 1];
- material.getParam('diffuse').value = [1, 1, 1, 1];
- material.getParam('specular').value = [1, 1, 1, 1];
- material.getParam('shininess').value = 50;
-
- g_timeParam = material.getParam('time');
-
- // Create the view matrix which tells the camera which way to point to.
- var eye = [10, 50, 20];
- var target = [2, 0, -2];
- var up = [0, 0, -1];
- var view_matrix = g_math.matrix4.lookAt(eye, target, up);
-
- g_viewInfo.drawContext.view = view_matrix;
-
- var shape = o3djs.primitives.createPlane(g_pack, material,
- 10, 10, 100, 100);
- for (var xx = 0; xx < 5; xx++) {
- for (var yy = 0; yy < 4; yy++) {
- var index = yy * 3 + xx;
-
- // Make a transform for each quad.
- var transform = g_pack.createObject('Transform');
- transform.translate((xx - 2) * 12, 0, (2 - yy) * -12);
- transform.addShape(shape);
- transform.parent = g_client.root;
- transform.createParam('diffuse', 'ParamFloat4').value = [xx * 0.2,
- yy * 0.25,
- 0.5,
- 1];
- }
- }
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- window.g_finished = true; // for selenium testing.
-}
-
-function updateProjectionMatrix() {
- // Create our projection matrix, with a vertical field of view of 45 degrees
- // a near clipping plane of 0.1 and far clipping plane of 100.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 100);
-}
-
-// spin the camera.
-function onrender(render_event) {
- // Get the number of seconds since the last render.
- var elapsedTime = render_event.elapsedTime;
- // Update g_clock in the browser and cache a V8 copy that can be
- // accessed efficiently. g_clock must be in the browser for selenium.
- var clock = window.g_clock + elapsedTime * window.g_timeMult;
- window.g_clock = clock;
-
- updateProjectionMatrix();
-
- g_timeParam.value = clock * 4;
-}
-
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body onload="init()" onunload="unload()">
-<h1>Vertex Shader Animation Example</h1>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 100%; height: 80%"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/vertex-shader.html b/o3d/samples/vertex-shader.html
deleted file mode 100644
index f3f4602..0000000
--- a/o3d/samples/vertex-shader.html
+++ /dev/null
@@ -1,337 +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.
--->
-
-<!--
-O3D Vertex Shader Demo
-
-This sample uses a custom vertex shader to quickly adjust the positions and
-normals of many vertices in a plane to achieve a ripple effect without iterating
-through the vertices in javascript.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Vertex Shader
-</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.effect');
-
-// global variables
-var g_o3dElement;
-var g_client;
-var g_o3d;
-var g_math;
-var g_pack;
-var g_viewInfo;
-var g_clockParam;
-
-/**
- * Creates the client area.
- */
-function init() {
- // These are here so that they are visible to both the browser (so
- // selenium sees them) and the embedded V8 engine.
- window.g_clock = 0;
- window.g_timeMult = 1;
- window.g_finished = false; // for selenium testing.
-
- // Comment out the line below to run the sample in the browser
- // JavaScript engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.util.makeClients(initStep2, 'LargeGeometry');
-}
-
-
-/**
- * Initializes global variables, positions camera, creates the material, and
- * draws the plane.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Init global variables.
- initGlobals(clientElements);
-
- // Set up the view and projection transformations.
- initContext();
-
- // Add the shapes to the transform hierarchy.
- createPlane();
-
- // Setup render callback.
- g_client.setRenderCallback(onRender);
-
- window.g_finished = true; // for selenium testing.
-}
-
-
-/**
- * Initializes global variables and libraries.
- * @param {Array} clientElements An array of o3d object elements assumed
- * to have one entry.
- */
-function initGlobals(clientElements) {
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
-
- // Set window.g_client as well. Otherwise when the sample runs in
- // V8, selenium won't be able to find this variable (it can only see
- // the browser environment).
- window.g_client = g_client = g_o3dElement.client;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-}
-
-
-/**
- * Sets up reasonable view and projection matrices.
- */
-function initContext() {
- // Set up a perspective transformation for the projection.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree frustum.
- g_client.width / g_client.height, // Aspect ratio.
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // cube is located.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [4, 4, 4], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-
-/**
- * Creates an effect using the shaders in the textarea in the document, applies
- * the effect to a new material, binds the uniform parameters of the shader
- * to parameters of the material, and sets certain parameters: the light and
- * camera position.
- * @return {Material} The material.
- */
-function createMaterial() {
- // Create a new, empty Material and Effect object.
- var material = g_pack.createObject('Material');
- var effect = g_pack.createObject('Effect');
-
- // Load shader string from document.
- var shaderString = o3djs.util.getElementContentById('effect');
- effect.loadFromFXString(shaderString);
-
- // Apply the effect to this material.
- material.effect = effect;
-
- // Bind uniform parameters declared in shader to parameters of material.
- effect.createUniformParameters(material);
-
- // Set the material's drawList.
- material.drawList = g_viewInfo.performanceDrawList;
-
- // Set light and camera positions for the pixel shader.
- material.getParam('lightWorldPos').value = [3, 10, 0];
- material.getParam('cameraWorldPos').value = [1, 3, 12];
-
- // Look up clock param.
- g_clockParam = material.getParam('clock');
-
- return material;
-}
-
-
-/**
- * Creates the plane using the primitives utility library, and adds it to the
- * transform graph at the root node.
- */
-function createPlane() {
- // This will create a plane subdivided into 180,000 triangles.
- var plane = o3djs.primitives.createPlane(
- g_pack, createMaterial(), 4, 4, 300, 300);
-
- // Add the shape to the transform hierarchy.
- g_client.root.addShape(plane);
-}
-
-
-/**
- * Updates the clock for the animation.
- * @param {!o3d.RenderEvent} renderEvent Rendering Information.
- */
-function onRender(renderEvent) {
- var elapsedTime = renderEvent.elapsedTime;
-
- // Update g_clock in the browser and cache a V8 copy that can be
- // accessed efficiently. g_clock must be in the browser for selenium.
- var clock = window.g_clock + elapsedTime * window.g_timeMult;
- window.g_clock = clock;
-
- g_clockParam.value = clock;
-}
-
-
-/**
- * Cleanup before exiting.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body onload="init()" onunload="unload()">
-<h1>Vertex Shader</h1>
-This sample uses a custom vertex shader to quickly adjust the positions and
-normals of many vertices in a plane to achieve a ripple effect without iterating
-through the vertices in javascript.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-
-<!-- Text area to hold the shaders -->
-<textarea id="effect" name="effect" cols="80" rows="20"
- style="display: none;">
-uniform float4x4 world : WORLD;
-uniform float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-uniform float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
-uniform float clock;
-uniform float3 lightWorldPos;
-uniform float3 cameraWorldPos;
-
-
-// Input parameters for the vertex shader.
-struct VertexShaderInput {
- float4 position : POSITION;
- float3 normal : NORMAL;
- float4 color : COLOR;
-};
-
-
-// Input parameters for the pixel shader (also the output parameters for the
-// vertex shader.)
-struct PixelShaderInput {
- float4 position : POSITION; // the position in clip space
- float3 objectPosition : TEXCOORD0; // the position in world space
- float3 normal : TEXCOORD1; // the normal in world space
- float4 color : COLOR;
-};
-
-
-/**
- * A function defining the shape of the wave. Takes a single float2 as an
- * argument the entries of which are the x and z components of a point in the
- * plane. Returns the height of that point.
- *
- * @param {float2} v The x and z components of the point in a single float2.
- */
-float wave(float2 v) {
- float d = length(v);
- return 0.15 * sin(15 * d - 5 * clock) / (1 + d * d);
-}
-
-
-/**
- * vertexShaderFunction - The vertex shader perturbs the vertices of the plane
- * to achieve the ripples. Then it applies the worldViewProjection matrix.
- *
- * @param input.position Position vector of vertex in object coordinates.
- * @param input.normal Normal of vertex in object coordinates.
- * @param input.color Color of vertex.
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
-
- float4 p = input.position;
-
- // The height of the point p is adjusted according to the wave function.
- p.y = wave(p.xz);
-
- // Step size used to approximate the partial derivatives of the wave function.
- float h = 0.001;
-
- // We take the derivative numerically so that the wave function can be
- // modified and the normal will still be correct.
- float3 n = normalize(float3(
- wave(float2(p.x - h, p.z)) - wave(float2(p.x + h, p.z)), 2 * h,
- wave(float2(p.x, p.z - h)) - wave(float2(p.x, p.z + h))));
-
- output.position = mul(p, worldViewProjection);
- output.objectPosition = mul(p, world).xyz;
- output.normal = mul(float4(n, 1), worldInverseTranspose).xyz;
- output.color = input.color;
-
- return output;
-}
-
-
-/**
- * This pixel shader is meant to be minimal since the vertex shader is
- * the focus of the sample.
- */
-float4 pixelShaderFunction(PixelShaderInput input) : COLOR {
- float3 p = input.objectPosition; // The point in question.
- float3 l = normalize(lightWorldPos - p); // Unit-length vector toward light.
- float3 n = normalize(input.normal); // Unit-length normal vector.
- float3 v = normalize(cameraWorldPos - p); // Unit-length vector toward camera.
- float3 r = normalize(-reflect(v, n)); // Reflection of v across n.
-
- float3 q = (lightWorldPos - p);
- float ldotr = dot(r, l);
- float specular = clamp(ldotr, 0, 1) /
- (1 + length(q - length(q) * ldotr * r));
-
- return float4(0, 0.6, 0.7, 1) * dot(n, l) + specular;
-}
-
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</body>
-</html>
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.0.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.0.png
deleted file mode 100644
index 64df9b0..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.0.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.1.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.1.png
deleted file mode 100644
index 05fc42a..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.1.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.10.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.10.png
deleted file mode 100644
index 4e907fa..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.10.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.11.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.11.png
deleted file mode 100644
index a799e97..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.11.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.12.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.12.png
deleted file mode 100644
index 15ec38e..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.12.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.13.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.13.png
deleted file mode 100644
index 1bc24f2..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.13.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.14.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.14.png
deleted file mode 100644
index 3e0ce6f..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.14.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.15.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.15.png
deleted file mode 100644
index 39421f2..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.15.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.16.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.16.png
deleted file mode 100644
index 63315b8..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.16.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.17.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.17.png
deleted file mode 100644
index 2786a2a..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.17.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.18.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.18.png
deleted file mode 100644
index bbdf045..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.18.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.19.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.19.png
deleted file mode 100644
index 5568e4a..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.19.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.2.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.2.png
deleted file mode 100644
index 195fc1f..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.2.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.20.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.20.png
deleted file mode 100644
index 3278701..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.20.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.21.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.21.png
deleted file mode 100644
index 6197751..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.21.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.22.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.22.png
deleted file mode 100644
index 22e0812..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.22.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.23.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.23.png
deleted file mode 100644
index 0457d70..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.23.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.24.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.24.png
deleted file mode 100644
index 134aa07..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.24.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.25.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.25.png
deleted file mode 100644
index 59eee69..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.25.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.26.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.26.png
deleted file mode 100644
index e7f1290..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.26.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.27.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.27.png
deleted file mode 100644
index 45fffa9..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.27.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.28.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.28.png
deleted file mode 100644
index 731f324..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.28.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.29.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.29.png
deleted file mode 100644
index ec694c1..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.29.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.3.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.3.png
deleted file mode 100644
index 8cb83a9..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.3.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.4.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.4.png
deleted file mode 100644
index 08b1c5d..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.4.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.5.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.5.png
deleted file mode 100644
index 456e287..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.5.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.6.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.6.png
deleted file mode 100644
index 74be504..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.6.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.7.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.7.png
deleted file mode 100644
index b06faef..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.7.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.8.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.8.png
deleted file mode 100644
index b7bda4c..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.8.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/deepwater/deepwater.9.png b/o3d/samples/waterdemo/assets/deepwater/deepwater.9.png
deleted file mode 100644
index 4540265..0000000
--- a/o3d/samples/waterdemo/assets/deepwater/deepwater.9.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/empty.txt b/o3d/samples/waterdemo/assets/empty.txt
deleted file mode 100644
index e69de29..0000000
--- a/o3d/samples/waterdemo/assets/empty.txt
+++ /dev/null
diff --git a/o3d/samples/waterdemo/assets/horizon_ramp.png b/o3d/samples/waterdemo/assets/horizon_ramp.png
deleted file mode 100644
index 087fac1..0000000
--- a/o3d/samples/waterdemo/assets/horizon_ramp.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/horizon_ramp_1.png b/o3d/samples/waterdemo/assets/horizon_ramp_1.png
deleted file mode 100644
index 087fac1..0000000
--- a/o3d/samples/waterdemo/assets/horizon_ramp_1.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/main_rock_normal.dds b/o3d/samples/waterdemo/assets/main_rock_normal.dds
deleted file mode 100644
index 9410b3a..0000000
--- a/o3d/samples/waterdemo/assets/main_rock_normal.dds
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/noise.png b/o3d/samples/waterdemo/assets/noise.png
deleted file mode 100644
index 863857d..0000000
--- a/o3d/samples/waterdemo/assets/noise.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/reflectivity_map.png b/o3d/samples/waterdemo/assets/reflectivity_map.png
deleted file mode 100644
index c048d63..0000000
--- a/o3d/samples/waterdemo/assets/reflectivity_map.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/rock_reflection_new.png b/o3d/samples/waterdemo/assets/rock_reflection_new.png
deleted file mode 100644
index f1cc39a..0000000
--- a/o3d/samples/waterdemo/assets/rock_reflection_new.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/rock_tile_normal_x.jpg b/o3d/samples/waterdemo/assets/rock_tile_normal_x.jpg
deleted file mode 100644
index 368a805..0000000
--- a/o3d/samples/waterdemo/assets/rock_tile_normal_x.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/rock_tile_rgb.jpg b/o3d/samples/waterdemo/assets/rock_tile_rgb.jpg
deleted file mode 100644
index efec13b..0000000
--- a/o3d/samples/waterdemo/assets/rock_tile_rgb.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/sky_compat.png b/o3d/samples/waterdemo/assets/sky_compat.png
deleted file mode 100644
index 0fe4134..0000000
--- a/o3d/samples/waterdemo/assets/sky_compat.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/sun_compat.png b/o3d/samples/waterdemo/assets/sun_compat.png
deleted file mode 100644
index 969d848..0000000
--- a/o3d/samples/waterdemo/assets/sun_compat.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/sun_ramp.png b/o3d/samples/waterdemo/assets/sun_ramp.png
deleted file mode 100644
index d2dbc53..0000000
--- a/o3d/samples/waterdemo/assets/sun_ramp.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/assets/sun_ramp_1.png b/o3d/samples/waterdemo/assets/sun_ramp_1.png
deleted file mode 100644
index d2dbc53..0000000
--- a/o3d/samples/waterdemo/assets/sun_ramp_1.png
+++ /dev/null
Binary files differ
diff --git a/o3d/samples/waterdemo/cameracontrol.js b/o3d/samples/waterdemo/cameracontrol.js
deleted file mode 100644
index 271c863..0000000
--- a/o3d/samples/waterdemo/cameracontrol.js
+++ /dev/null
@@ -1,123 +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.
- */
-
-
-/**
- * @fileoverview This file contains functions used controlling the camera.
- *
- */
-
- /**
- * Clamps a value between bounds.
- *
- * @param {number} inputValue Value to be clamped.
- * @param {number} lowerBound Lower limit.
- * @param {number} upperBound Upper limit.
- * @return {number} The clamped value.
- */
-function clamp(inputValue, lowerBound, upperBound) {
- var resultValue = inputValue;
- if (inputValue < lowerBound) resultValue = lowerBound;
- if (inputValue > upperBound) resultValue = upperBound;
- return resultValue;
-}
-
-/**
- * Functions for control based on the mouse
- */
-var dragging = false;
-var g_rotX = 2.85;
-var g_rotY = 0;
-var g_thisClick;
-var g_lastClick;
-var g_cameraZoom = 1.0;
-
-function startDragging(e) {
- g_thisClick = e;
-
- dragging = true;
-}
-
-/**
- * Scroll wheel handler. Adjusts g_cameraZoom global according to wheel
- * movement then causes a recalculation of the projection matrix.
- * The goal is to simulate a zoom lens rather than to move the viewpoint.
- * @param {Event} e Wheel event to handle.
- */
-function scrollMe(e) {
- if (e.deltaY) {
- g_cameraZoom = clamp(g_cameraZoom * ((e.deltaY < 0 ? 13 : 11) / 12),
- 0.1,
- 4.0);
- resize();
- }
-}
-
-function drag(e) {
- if (dragging) {
- var scale = -.001 * g_cameraZoom;
-
- g_lastClick = g_thisClick;
- g_thisClick = e;
-
- var xLowerLimit = 2.3;
- var xUpperLimit = 4.2;
- var yLowerLimit = -0.6;
- var yUpperLimit = 0.25;
-
- g_rotX = clamp(g_rotX - scale * (g_thisClick.x - g_lastClick.x),
- xLowerLimit, xUpperLimit);
- g_rotY = clamp(g_rotY + scale * (g_thisClick.y - g_lastClick.y),
- yLowerLimit, yUpperLimit);
-
- setViewFromRotation();
- }
-}
-
-function setViewFromRotation() {
- var rotMatX = g_math.matrix4.rotationY(g_rotX);
- var right = g_math.matrix4.transformDirection(rotMatX, [0, 0, 1]);
- var camera_X = g_math.normalize(g_math.cross([0, 1, 0], right));
- var rotMatY = g_math.matrix4.axisRotation(camera_X, g_rotY);
- var rot_mat = g_math.matrix4.mul(rotMatX, rotMatY);
- g_root.identity();
-
- // TODO: eye position should be a variable
- var eye = [-2.751, 3.529, -8.563];
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- eye,
- g_math.addVector(eye, g_math.mulVectorMatrix([0, 0, 1, 0], rot_mat)),
- g_math.mulVectorMatrix([0, 1, 0, 0], rot_mat));
-}
-
-function stopDragging(e) {
- dragging = false;
-}
diff --git a/o3d/samples/waterdemo/uicomponents.js b/o3d/samples/waterdemo/uicomponents.js
deleted file mode 100644
index 121c646..0000000
--- a/o3d/samples/waterdemo/uicomponents.js
+++ /dev/null
@@ -1,112 +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.
- */
-
-
-/**
- * @fileoverview This file contains functions used for creating UI components
- * on the web page. It also has functions used for altering the parameters
- * that those UI components control.
- *
- */
-
-/*****************************************************************************
- * Helper functions for the html
- *****************************************************************************/
-
-/**
- * Creates the html for the select pop down menu to select the time.
- */
-function buildTimeSelect() {
- document.write('Time: <select id="time" name="time"');
- document.write(' onChange="changeColor()">');
- for (var t = 0; t < 24; t++) {
- document.write('<option value="' + t * 60 + '">');
- if (t % 12 == 0) {
- document.write('12');
- } else {
- document.write(t % 12);
- }
- if (t < 12) {
- document.write(' AM</option>');
- } else {
- document.write(' PM</option>');
- }
- }
- document.write('</select>');
-}
-
-
-/**
- * Creates the html for the select pop down menu to select the speed of the sun.
- */
-function buildTimeSpeedSelect() {
- document.write('Speed: <select id="speed" name="speed" ');
- document.write('onChange="changeSpeed()">');
- document.write('<option value="1">1X(real time)</option>');
- for (var t = 10; t <= 100; t += 10) {
- document.write('<option value="' + t + '">' + t + 'X</option>');
- }
- document.write('</select>');
-}
-
-
-/*****************************************************************************
- * Functions for using the html input.
- *****************************************************************************/
-
-/**
- * Caluclates the current position of the sun based on time.
- * TODO: This is currently not being used--a direction vector is.
- * However, this function shoudl change that direction vector.
- * @param {number} opt_inputMinutes Optional paramter of the time in minutes
- * to return the sun position for.
- * @return {!Array.<number>} A vector indicating the position of the sun.
- */
-function getCurrentSunPosition(opt_inputMinutes) {
- userDate = new Date();
- var totalMinutes = opt_inputMinutes;
- if (!opt_inputMinutes) {
- totalMinutes = userDate.getHours() * 60 + userDate.getMinutes();
- g_currentTime = totalMinutes;
- }
- var minuteRadians = ((totalMinutes / 720 * Math.PI) + 1.5 * Math.PI) %
- (2 * Math.PI);
- return [150 * Math.cos(minuteRadians), 150 * Math.sin(minuteRadians), 0];
-}
-
-
-/**
- * Changes the speed of the sun.
- */
-function changeSpeed() {
- g_sunMultiplier = document.getElementById('speed').value;
- o3djs.dump.dump('-------------speed: ' + g_sunMltiplier + '\n');
-}
diff --git a/o3d/samples/waterdemo/waterdemo.html b/o3d/samples/waterdemo/waterdemo.html
deleted file mode 100644
index 7fcf611..0000000
--- a/o3d/samples/waterdemo/waterdemo.html
+++ /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.
--->
-
-<!--
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
- Water Demo
-</title>
-<style type="text/css">
- html, body {
- height: 100%;
- margin: 0;
- padding: 0;
- border: none;
- }
-</style>
-<script type="text/javascript" src="../o3djs/base.js"></script>
-
-<script type="text/javascript" src="waterdemo.js"></script>
-<script type="text/javascript" src="uicomponents.js"></script>
-<script type="text/javascript" src="cameracontrol.js"></script>
-</head>
-<body>
- <!-- Start of o3d plugin -->
- <div id="o3d" style="width: 100%; height: 100%;"></div>
- <!-- End of o3d plugin -->
-<!-- Don't render the textarea -->
-<div style="display:none">
-
-<!-- *********************************************************************
- Shader for the sky dome
- ********************************************************************* -->
-<textarea id="dome" name="dome" cols="80" rows="20">
- // Constant float4x4 matrices
- float4x4 WVP : WORLDVIEWPROJECTION;
- float4x4 world : WORLD;
-
- // Positions of the light and camera
- float3 lightDirection;
- float3 cameraEye;
-
- // Samplers for textures
- sampler2D DiffuseSampler;
- sampler2D HorizonRamp;
- sampler2D SunRamp;
-
- // Input to our vertex shader
- struct a2v {
- float3 pos : POSITION;
- float4 col : COLOR;
- float3 normal : NORMAL;
- float2 texcoord0 : TEXCOORD0;
- };
-
- // Input to our pixel shader and output of our vertex shader
- struct v2f {
- float4 pos : POSITION;
- float3 worldPos : TEXCOORD0;
- float3 eye : TEXCOORD1;
- };
-
- v2f vsMain(a2v IN) {
- v2f OUT;
- float4 objectPos = float4(IN.pos, 1);
- OUT.pos = mul(objectPos, WVP);
- OUT.worldPos = mul(objectPos,world).xyz;
- OUT.eye = OUT.worldPos - cameraEye;
- return OUT;
- }
-
- float4 psMain(v2f IN): COLOR {
- // TODO: lightDirection is a constant--no need to normalize each vert
- float3 L = normalize(lightDirection);
- float LdotEye=dot(L, normalize(IN.eye));
-
- float4 sun = tex2D(SunRamp, float2((1-LdotEye)*40, (1-LdotEye)*40));
- float4 horizon = tex2D(HorizonRamp, IN.worldPos.yy/80);
- return sun.w*sun*.7+(1-sun.w*.7)*horizon;
- }
-
- // Here we tell our effect file *which* functions are
- // our vertex and pixel shaders.
-
- // #o3d VertexShaderEntryPoint vsMain
- // #o3d PixelShaderEntryPoint psMain
- // #o3d MatrixLoadOrder RowMajor
-</textarea>
-
-<!-- *********************************************************************
- Shader for the water
- Based on Tessendorf's "Simulating Ocean Water" paper
- ********************************************************************* -->
-<textarea id="water" name="water" cols="80" rows="20">
- float4x4 WVP : WorldViewProjection;
- float4x4 worldInverseTranspose : WORLDINVERSETRANSPOSE;
- float4x4 world : WORLD;
-
- // Positions of the light and camera
- float3 lightDirection;
- float3 cameraEye;
-
- // Time from the javascript program
- float inputTime;
-
- float reflectivity;
- float3 swizzle1;
-
- // Textures
- sampler2D HeightSampler;
- sampler2D Reflectivity;
- sampler2D ReflectionSampler;
- sampler2D HorizonRamp;
- sampler2D SunRamp;
- sampler2D RockTexture;
-
- struct a2v{
- float3 Position : POSITION;
- float3 Normal : NORMAL;
- float2 texcoord0 : TEXCOORD0;
- };
-
- struct v2f{
- float4 pos : POSITION;
- float2 texcoord0 : TEXCOORD0;
- float3 lightVec : TEXCOORD1;
- float4 diffuse : TEXCOORD2;
- float3 eyeVec : TEXCOORD3;
- float3 normal : TEXCOORD4;
- float3 worldPos : TEXCOORD5;
- float2 worldTexCoord : TEXCOORD6;
- };
-
-
- float displacement(float2 vec,float time) {
- // These values could be passed in
- float frequency = 15;
- float scaleFactor = .075;
-
- float displacement=0;
- displacement+=scaleFactor*sin((vec.x*-.4+vec.y*-.9)*frequency+time);
- displacement+=scaleFactor*.5*sin((vec.x*.1+vec.y*-.9)*frequency*3+time);
- displacement+=scaleFactor*.25*sin((vec.x*-.2+vec.y*-.8)*frequency*9+time);
- return displacement;
- }
-
- v2f vsMain (a2v IN){
- v2f OUT;
-
- float4 PosWorld = mul(float4(IN.Position, 1.0),world);
-
- float displacementC = displacement(PosWorld.xz/10, inputTime);
- float4 newPosition = float4(IN.Position,1) + displacementC*float4(0,1,0,0);
-
- OUT.normal = mul(float4(IN.Normal,1),worldInverseTranspose).xyz;
- OUT.pos = mul(newPosition, WVP);
- OUT.worldPos = PosWorld.xyz;
- OUT.diffuse = float4(displacementC,displacementC,displacementC,1);
- // TODO: lightDirection is a constant--no need to normalize each vert
- OUT.lightVec = normalize(lightDirection);
- OUT.eyeVec = normalize(PosWorld.xyz - cameraEye);
- OUT.worldTexCoord = PosWorld.xz/40;
- OUT.texcoord0 = IN.texcoord0;
- return OUT;
- }
-
- float4 psMain (v2f IN) : COLOR{
- // Use central differencing to get the normal from the bump maps
- // The swizzle says which channel we're using
- float r = dot(tex2D(HeightSampler, IN.worldTexCoord.xy+float2(.005,0)).xyz,
- swizzle1);
- float l = dot(tex2D(HeightSampler, IN.worldTexCoord.xy+float2(-.005,0)).xyz,
- swizzle1);
- float b = dot(tex2D(HeightSampler, IN.worldTexCoord.xy+float2(0,.005)).xyz,
- swizzle1);
- float f = dot(tex2D(HeightSampler, IN.worldTexCoord.xy+float2(0,-.005)).xyz,
- swizzle1);
- float norm = .01*40;
- float3 bump = float3((r-l)/norm, 1, (b-f)/norm);
- float3 n = normalize(bump + IN.normal);
-
- // Precalculate the calculation of reflectivity basead on costhetai
- // and store as a texture for lookup
- float costhetai = abs(dot(IN.eyeVec, n));
- float reflectivity = tex2D(Reflectivity, float2(costhetai,0)).x;
-
- float3 reflectV = normalize(reflect(IN.eyeVec, n));
-
- float3 dPE = IN.worldPos-IN.eyeVec;
- float dist = length(dPE) * .61;
- dist = exp(-dist);
-
- float3 L = normalize(IN.lightVec);
- float LdotReflectV = dot(L, reflectV);
-
- // Calculate the sun ramp for its reflection on the water
- float4 sun = tex2D(SunRamp, float2((1-LdotReflectV)*40,0));
- sun.xyz = sun.w*sun.xyz;
- float4 horizon = tex2D(HorizonRamp, reflectV.yy*2);
-
- // Add in the refelction of the rock
- float2 vPos = float2((IN.texcoord0.x-.7668)*11.7,
- ((1-IN.texcoord0.y)-.888)*11);
- vPos += bump.xz/7;
- float4 islandReflection = tex2D(ReflectionSampler, vPos);
- reflectivity = reflectivity*(1-islandReflection.w*
- (.75-.75*islandReflection.x));
-
- // Get the reflection of the environment (sun, sky)
- float4 environmentColor = sun*.7+(1-sun.w*.7)*horizon;
-
- // The color of the water when we look straight into it, not at a glancing
- // angle
- float4 internalColor = float4(0, .1, .15, 1);
-
- // First interpolate water color with reflection from environment
- float4 firstlerp = lerp(internalColor, environmentColor, reflectivity);
- // Then interpolate with the air to give atmosphere and some haze
- return lerp(firstlerp, float4(.1, .1, .1, 1), dist) +
- pow(LdotReflectV,200)*float4(.9,.6,.4,0);
- }
-
- // #o3d VertexShaderEntryPoint vsMain
- // #o3d PixelShaderEntryPoint psMain
- // #o3d MatrixLoadOrder RowMajor
-</textarea>
-
-
-<!-- *********************************************************************
- Shader for the rocks
- ********************************************************************* -->
-<textarea id="rocks" name="rocks" cols="80" rows="20">
- // The 4x4 world view projection matrix.
- float4x4 WVP : WORLDVIEWPROJECTION;
-
- // positions of the light and camera
- float3 lightDirection;
- float3 cameraEye;
-
- // Varying time input
- float inputTime;
-
- float4 ambient_color;
- float4 diffuse_Color;
-
- sampler2D DiffuseSampler;
- sampler2D BumpSampler;
-
- // Input to our vertex shader
- struct a2v {
- float3 pos : POSITION;
- float3 normal : NORMAL;
- float2 texcoord0 : TEXCOORD0;
- };
-
- // Input to our pixel shader and output of our vertex shader
- struct v2f {
- float4 pos : POSITION;
- float2 texcoord0 : TEXCOORD0;
- float3 lightVec : TEXCOORD1;
- float3 normal : TEXCOORD2;
- };
-
- v2f vsMain(a2v IN) {
- v2f OUT;
-
- OUT.pos = mul(float4(IN.pos, 1.0), WVP);
- // TODO: lightDirection is a constant--no need to normalize each vert
- float3 l = normalize(lightDirection);
- float3 n = IN.normal;
-
- ambient_color = float4(0.4, 0.4, 0.4, 1);
-
- OUT.texcoord0 = IN.texcoord0;
- OUT.lightVec = l;
- OUT.normal = n;
- return OUT;
- }
-
- float4 psMain(v2f IN): COLOR {
- ambient_color = float4(0.2, 0.2, 0.2, 1);
- float3 n = normalize(IN.normal);
- float4 diffuse = tex2D(DiffuseSampler, IN.texcoord0.xy);
- float4 diffuseCol = diffuse * saturate(dot(n,normalize(IN.lightVec)));
- return diffuseCol + ambient_color*diffuse;
- }
-
- // Here we tell our effect file *which* functions are
- // our vertex and pixel shaders.
-
- // #o3d VertexShaderEntryPoint vsMain
- // #o3d PixelShaderEntryPoint psMain
- // #o3d MatrixLoadOrder RowMajor
-</textarea>
-
-<!-- *********************************************************************
- Shader for the sun
- ********************************************************************* -->
-<textarea id="sun" name="sun" cols="80" rows="20">
- // The 4x4 world view projection matrix.
- float4x4 WVP : WORLDVIEWPROJECTION;
-
- sampler2D DiffuseSampler;
-
- // Input parameters for our vertex shader
- struct a2v {
- float3 pos : POSITION;
- float3 normal : NORMAL;
- float2 texcoord0 : TEXCOORD0;
- };
-
- // Input parameters for our pixel shader
- struct v2f {
- float4 pos : POSITION;
- float2 tex : TEXCOORD0;
- };
-
- v2f vsMain(a2v IN) {
- v2f OUT;
- OUT.pos = mul(float4(IN.pos,1), WVP);
- OUT.tex = IN.texcoord0;
- return OUT;
- }
-
- float4 psMain(v2f IN): COLOR {
- return tex2D(DiffuseSampler, IN.tex);
- }
-
- // Here we tell our effect file *which* functions are
- // our vertex and pixel shaders.
-
- // #o3d VertexShaderEntryPoint vsMain
- // #o3d PixelShaderEntryPoint psMain
- // #o3d MatrixLoadOrder RowMajor
-</textarea>
-
-<!-- *********************************************************************
- Shader for the bridge
- ********************************************************************* -->
-<textarea id="bridge" name="bridge" cols="80" rows="20">
- // The 4x4 world view projection matrix.
- float4x4 WVP : WORLDVIEWPROJECTION;
-
- // Positions of the light and camera
- float3 lightPos;
- float3 cameraEye;
-
- // Changing time variable
- float inputTime;
-
- // Color for the bridge
- float4 lightDiffuse;
-
- sampler2D DiffuseSampler;
-
- float3 bridgeEnd1;
- float3 bridgeEnd2;
-
- // Input parameters for our vertex shader
- struct a2v {
- float3 pos : POSITION;
- float3 col : COLOR;
- float3 normal : NORMAL;
- };
-
- // Input parameters for our pixel shader
- struct v2f {
- float4 pos : POSITION;
- };
-
- v2f vsMain(a2v IN) {
- v2f OUT;
-
- // These two could possible be passed in--different wind values
- float d_frequency = .5;
- float d_scale = .1;
-
- bridgeEnd1 = float3(21,11.3,-50.5);
- bridgeEnd2 = float3(23.3,11,-37);
- float halfBridgeLength = .5*distance(bridgeEnd1,bridgeEnd2);
- float3 displacementVector = float3(0,1,0);
- float displacement = sin(d_frequency*inputTime);
- float percentFromEnd1 = distance(IN.pos,bridgeEnd1)/halfBridgeLength;
- float percentFromEnd2 = distance(IN.pos,bridgeEnd2)/halfBridgeLength;
- float d_weight = percentFromEnd1*percentFromEnd2;
- float3 newPosition = IN.pos +
- d_weight*d_scale*displacement*displacementVector;
- OUT.pos = mul(float4(newPosition,1), WVP);
- return OUT;
- }
-
- float4 psMain(v2f IN): COLOR {
- return lightDiffuse;
- }
-
- // Here we tell our effect file *which* functions are
- // our vertex and pixel shaders.
-
- // #o3d VertexShaderEntryPoint vsMain
- // #o3d PixelShaderEntryPoint psMain
- // #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
-</html>
-
-
diff --git a/o3d/samples/waterdemo/waterdemo.js b/o3d/samples/waterdemo/waterdemo.js
deleted file mode 100644
index 48282f9..0000000
--- a/o3d/samples/waterdemo/waterdemo.js
+++ /dev/null
@@ -1,646 +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.
- */
-
-
-/**
- * @fileoverview This file contains functions used for creating a beach scene.
- *
- */
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.dump');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.loader');
-
-// Events
-
-/**
- * Run the init() function once the page has finished loading.
- */
-window.onload = init;
-
-/**
- * Run the unload() function when the page is unloaded.
- */
-window.onunload = unload;
-
-// O3D variables
-var g_root;
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack = null;
-var g_viewInfo;
-var g_clientWidth;
-var g_clientHeight;
-var g_loader;
-var g_finished = false; // for selenium
-var g_globalParams;
-
-// Model variables
-var g_modelCounter = 0;
-var g_modelPaths = [];
-var g_modelPacks = [];
-var g_modelRoots = [];
-var g_modelIndices = [];
-
-// Pack variables
-var g_rockPack;
-var g_waterPack;
-var g_bridgePack;
-var g_woodPack;
-var g_domePack;
-var g_treePack;
-var g_sunPack;
-
-// Time variables
-var g_frame;
-var g_clock = 0.0;
-var g_clockParam;
-var g_timeMult = 1.0;
-
-// General shader variables
-var g_lightDirectionParam;
-
-// Water variables
-var g_samplerParam;
-var g_swizzle1Param;
-var g_deepWaterTextures = [];
-
-// Cameras
-var g_cameraOriginal = {
- eye: { x: -2.751, y: 3.529, z: -8.563 },
- target: { x: 0, y: 4, z: -10 },
- up: { x: 0, y: 1, z: 0 }
-};
-var g_cameraOverhead = {
- eye: { x: 0, y: 120, z: -20 },
- target: { x: 0, y: 2, z: -20 },
- up: { x: 0, y: 0, z: -1 }
-};
-var g_camera = {
- eye: { x: 0, y: 0, z: 0 },
- target: { x: 0, y: 0, z: 0 },
- up: { x: 0, y: 0, z: 0 }
-};
-
-var g_clientZoom = 1.0;
-
-// Initialize the models we'll be using
-g_modelPaths[0] = 'assets/rocks.9.o3dtgz';
-g_modelPaths[1] = 'assets/lazy_bridge.o3dtgz';
-
-g_modelIndices[0] = 0;
-g_modelIndices[1] = 2;
-
-/**
- * Performs the initial creation of the packs and their roots.
- */
-function initializePacks() {
- var packNames = [
- 'Rock pack', // 0
- 'Tree pack', // 1
- 'Brdige pack', // 2
- 'Wood pack', // 3
- 'Dome pack', // 4
- 'Water pack', // 5
- 'Sun pack']; // 6
-
- for (var mp = 0; mp < packNames.length; mp++) {
- g_modelPacks[mp] = g_client.createPack();
- g_modelRoots[mp] = g_modelPacks[mp].createObject('Transform');
- g_modelRoots[mp].parent = g_root;
- }
-
- // Set some useful variables
- g_rockPack = g_modelPacks[0];
- g_treePack = g_modelPacks[1];
- g_bridgePack = g_modelPacks[2];
- g_woodPack = g_modelPacks[3];
- g_domePack = g_modelPacks[4];
- g_waterPack = g_modelPacks[5];
- g_sunPack = g_modelPacks[6];
-
-}
-
-/**
- * Swaps the properties of two cameras.
- * @param {!Object} oldCamera The old camera.
- * @param {!Object} newCamera The new camera to switch to.
- */
-function switchCamera(oldCamera, newCamera) {
- oldCamera.eye.x = newCamera.eye.x;
- oldCamera.eye.y = newCamera.eye.y;
- oldCamera.eye.z = newCamera.eye.z;
-
- oldCamera.target.x = newCamera.target.x;
- oldCamera.target.y = newCamera.target.y;
- oldCamera.target.z = newCamera.target.z;
-
- oldCamera.up.x = newCamera.up.x;
- oldCamera.up.y = newCamera.up.y;
- oldCamera.up.z = newCamera.up.z;
-}
-
-
-/**
- * Generates the projection matrix based on the size of the o3d plugin and the
- * camera zoom.
- */
-function resize() {
- var newWidth = g_client.width;
- var newHeight = g_client.height;
-
- if (g_clientZoom != g_cameraZoom ||
- newWidth != g_clientWidth ||
- newHeight != g_clientHeight) {
- g_clientZoom = g_cameraZoom;
- g_clientWidth = newWidth;
- g_clientHeight = newHeight;
-
- // Set the projection matrix, with a vertical field of view of 30 degrees
- // a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(g_clientZoom * 30),
- g_clientWidth / g_clientHeight,
- 0.1,
- 10000);
- }
-}
-/**
- * Performs functions (usually related to animation) every time the frame is
- * rendered. Also updates properities such as time.
- * @param {!o3d.RenderEvent} renderEvent Render event.
- */
-function onrender(renderEvent) {
-
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += g_timeMult * elapsedTime;
-
- g_clockParam.value = g_clock;
-
- g_frame = Math.floor(g_clock * 18);
- g_frame = g_frame % 90;
-
- var frame = g_frame - 22.5;
- var twoPiOver90 = 2.0 * Math.PI / 90.0;
- var s1 = Math.sin(frame * twoPiOver90) + 1;
- var s2 = Math.sin((frame - 30) * twoPiOver90) + 1;
- var s3 = Math.sin((frame - 60) * twoPiOver90) + 1;
-
- var denominator = s1 + s2 + s3;
- s1 /= denominator;
- s2 /= denominator;
- s3 /= denominator;
-
- if (g_frame >= 0 && g_frame < 30) {
- g_swizzle1Param.value = new Array(s1, s3, s2);
- } else if (g_frame >= 30 && g_frame < 60) {
- g_swizzle1Param.value = new Array(s2, s1, s3);
- } else {
- g_swizzle1Param.value = new Array(s3, s2, s1);
- }
-
- var i = g_frame % 30;
- var m = Math.floor(g_frame / 3);
- if (g_deepWaterTextures[i]){
- g_samplerParam.value.texture = g_deepWaterTextures[i];
- }
- resize();
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes the scene.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Currently hardcoding the size.
- g_clientWidth = 700;
- g_clientHeight = 500;
-
- g_loader = o3djs.loader.createLoader(function() {
- g_finished = true; // for selenuim
- });
-
- g_pack = g_client.createPack();
- g_root = g_pack.createObject('Transform');
- g_root.parent = g_client.root;
-
- // Initialize the camera
- switchCamera(g_camera, g_cameraOriginal);
-
- // Initialize all the other packs
- initializePacks();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Initialize camera
- resize();
- setViewFromRotation();
-
- // Create global params.
- g_globalParams = g_pack.createObject('ParamObject');
- g_lightDirectionParam = g_globalParams.createParam('lightWorldPos',
- 'ParamFloat3');
- g_clockParam = g_globalParams.createParam('timeParam',
- 'ParamFloat');
- g_swizzle1Param = g_globalParams.createParam('swizzle1Param',
- 'ParamFloat3');
-
- g_lightDirectionParam.value = [0, .15, -1];
-
- // Add our models
- water(g_waterPack, g_modelRoots[5]);
- dome(g_domePack, g_modelRoots[4]);
- sun(g_sunPack, g_modelRoots[6]);
- rocks(g_rockPack, g_modelRoots[0]);
- bridge(g_bridgePack, g_modelRoots[2]);
-
- // Add mouse control
- o3djs.event.addEventListener(g_o3dElement, 'mousedown', startDragging);
- o3djs.event.addEventListener(g_o3dElement, 'mousemove', drag);
- o3djs.event.addEventListener(g_o3dElement, 'mouseup', stopDragging);
- o3djs.event.addEventListener(g_o3dElement, 'wheel', scrollMe);
-
- g_client.setRenderCallback(onrender);
-
- g_loader.finish();
-}
-
-/**
- * Returns the path of where the file is located
- * with the trailing slash
- * @return {string} The current path.
- */
-function getCurrentPath() {
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- return path.substring(0, index + 1);
-}
-
-/**
- * Loads a texture.
- *
- * @param {!o3djs.loader.Loader} loader Loader to use to load texture.
- * @param {!o3d.Pack} pack Pack to load texture in.
- * @param {!o3d.Material} material Material to attach sampler to.
- * @param {string} samplerName Name of sampler.
- * @param {string} textureName filename of texture.
- * @return {!o3d.Sampler} Sampler attached to material.
- */
-function loadTexture(loader, pack, material, samplerName, textureName) {
- var samplerParam = material.getParam(samplerName);
- var sampler = pack.createObject('Sampler');
- samplerParam.value = sampler;
-
- var url = getCurrentPath() + 'assets/' + textureName;
- loader.loadTexture(pack, url, function(texture, exception) {
- if (exception) {
- alert(exception);
- } else {
- sampler.texture = texture;
- }
- });
-
- return sampler;
-}
-
-/**
- * Creates the rocks and its shaders.
- * @param {!o3d.Pack} pack Pack to load the rocks into.
- * @param {o3d.Transform} root Parent transform for the rocks shape.
- */
-function rocks(pack, root) {
- var loader = g_loader.createLoader(function() {
- o3djs.pack.preparePack(pack, g_viewInfo);});
- loader.loadScene(g_client, pack, root, getCurrentPath() + g_modelPaths[0],
- rockCallback);
-
- function rockCallback(pack, root, exception) {
- var rockTextures = ['rock_tile_rgb.jpg', 'main_rock_normal.dds'];
- var bumpSamplers = ['DiffuseSampler', 'BumpSampler'];
-
- var materials = pack.getObjects('lambert2', 'o3d.Material');
- for (var m = 0; m < materials.length; m++) {
- var material = materials[m];
- var fxString = document.getElementById('rocks').value;
- var effect = pack.createObject('Effect');
- effect.loadFromFXString(fxString);
-
- effect.createUniformParameters(material);
- material.effect = effect;
-
- var lightDiffuseParam = material.getParam('diffuse_Color');
- if (lightDiffuseParam) {
- lightDiffuseParam.value = [.5, .5, .5, 1];
- }
- for (var t = 0; t < rockTextures.length; t++) {
- loadTexture(loader, pack, material, bumpSamplers[t], rockTextures[t]);
- }
- }
- connectParams(pack);
- }
- loader.finish();
-}
-
-/**
- * Creates the bridge and its shaders.
- * @param {!o3d.Pack} pack Pack to load the bridge into.
- * @param {!o3d.Transform} root Parent transform for the bridge shape.
- */
-function bridge(pack, root) {
- var loader = g_loader.createLoader(function() {
- o3djs.pack.preparePack(pack, g_viewInfo);});
- loader.loadScene(
- g_client, pack, root, getCurrentPath() + g_modelPaths[1], callback);
-
- function callback(pack, root, exception) {
- var materials = pack.getObjects('bridgeMaterial', 'o3d.Material');
- for (var m = 0; m < materials.length; m++) {
- var material = materials[m];
-
- var fxString = document.getElementById('bridge').value;
- var effect = pack.createObject('Effect');
- effect.loadFromFXString(fxString);
-
- effect.createUniformParameters(material);
- material.effect = effect;
-
- // White ambient light
- var lightAmbientParam = material.getParam('lightAmbient');
- if (lightAmbientParam) {
- lightAmbientParam.value = [0.04, 0.04, 0.04, 1];
- }
- // Reddish diffuse light
- var lightDiffuseParam = material.getParam('lightDiffuse');
- if (lightDiffuseParam) {
- lightDiffuseParam.value = [.45, .27, .07, 1];
- }
- }
- connectParams(pack);
- }
-
- loader.finish();
-}
-
-/**
- * Creates the water shapes, applies correct shaders and connects any special
- * water params.
- * @param {!o3d.Pack} pack Pack to load the water into.
- * @param {!o3d.Transform} root Parent transform for the water shape.
- */
-function water(pack, root) {
- // Create the material
- o3djs.dump.dump('-- start water\n');
-
- var material = pack.createObject('Material');
- o3djs.dump.dump('-- water: created material\n');
- material.drawList = g_viewInfo.performanceDrawList;
- var effect = pack.createObject('Effect');
- var effectString = document.getElementById('water').value;
- effect.loadFromFXString(effectString);
- effect.createUniformParameters(material);
- material.effect = effect;
-
- o3djs.dump.dump('-- water: created material & effect\n');
- var swizzle1Param = material.getParam('swizzle1');
- swizzle1Param.bind(g_swizzle1Param);
- o3djs.dump.dump('-- water: bound swizzle param\n');
-
- var water = o3djs.primitives.createDisc(pack, material,
- 155, 300, 500, 300, 10)
- var loader = g_loader.createLoader(
- function() {
- root.addShape(water);
- });
-
- // The texture that this sampler references changes every 3 frames
- g_samplerParam = material.getParam('HeightSampler');
- if (g_samplerParam) {
- o3djs.dump.dump('bind sampler param\n');
- g_samplerParam.value = pack.createObject('Sampler');
- }
-
- // This is so "index" is unique.
- // @param {number} index Index of texture to register.
- // @return {!function(!o3d.Texture): void} A function that takes a
- // texture.
- function registerDeepWaterTexture(index) {
- return function(texture) {
- g_deepWaterTextures[index] = texture;
- }
- }
-
- o3djs.dump.dump('-- water: start loading deep water textures\n');
- for (var i = 0; i < 30; i++) {
- var textureName = 'deepwater.' + i + '.png';
- var url = getCurrentPath() + 'assets/deepwater/' + textureName;
- loader.loadTexture(pack, url, registerDeepWaterTexture(i));
- }
-
- var sampler = loadTexture(loader, pack, material, 'Reflectivity',
- 'reflectivity_map.png');
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
- sampler.magFilter = g_o3d.Sampler.LINEAR;
- sampler.minFilter = g_o3d.Sampler.LINEAR;
-
- sampler = loadTexture(loader, pack, material, 'ReflectionSampler',
- 'rock_reflection_new.png');
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
-
- sampler = loadTexture(loader, pack, material, 'HorizonRamp',
- 'horizon_ramp_1.png');
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
-
- sampler = loadTexture(loader, pack, material, 'SunRamp', 'sun_ramp_1.png');
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
-
- sampler = loadTexture(loader, pack, material, 'RockTexture',
- 'rock_tile_rgb.jpg');
-
- connectParams(pack);
- o3djs.dump.dump('Done applying Shader\n');
-
- root.localMatrix = g_math.matrix4.translation([-2.751, 0, -8.563]);
- o3djs.dump.dump('-- Finished water\n');
- loader.finish();
-}
-
-
-/**
- * Creates the sun shape, applies correct shaders and connects any special
- * sun params.
- * @param {!o3d.Pack} pack Pack to load the sun into.
- * @param {!o3d.Transform} root Parent transform for the sun shape.
- */
-function sun(pack, root) {
- // Create the material
- o3djs.dump.dump('-- start sun\n');
-
- var material = pack.createObject('Material');
- var effect = pack.createObject('Effect');
- var fxString = document.getElementById('sun').value;
- effect.loadFromFXString(fxString);
- material.drawList = g_viewInfo.zOrderedDrawList;
- material.effect = effect;
- effect.createUniformParameters(material);
- o3djs.dump.dump('-- created sun material\n');
-
- // Probably not a necessary state, but available for the future
- var state = pack.createObject('State');
- state.getStateParam('CullMode').value = g_o3d.State.CULL_NONE;
- material.state = state;
-
- var sun = o3djs.primitives.createPlane(pack, material, 20, 20, 2, 2);
- var loader = g_loader.createLoader(
- function() {
- root.addShape(sun);
- });
-
- var sampler = loadTexture(loader, pack, material, 'DiffuseSampler',
- 'sun_compat.png');
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
-
- connectParams(pack);
- root.localMatrix = g_math.matrix4.mul(
- g_math.matrix4.rotationX(90 * 0.0174),
- g_math.matrix4.translation([0, 15, 140]));
- loader.finish();
- o3djs.dump.dump('-- Finished sun\n');
-}
-
-/**
- * Creates the dume sphere shape, applies correct shaders and connects any
- * special dome params.
- * @param {!o3d.Pack} pack Pack to load the dome into.
- * @param {!o3d.Transform} root Parent transform for the dome sphere shape.
- */
-function dome(pack, root) {
- // Create the material
- o3djs.dump.dump('-- start dome\n');
-
- var material = pack.createObject('Material');
- var effect = pack.createObject('Effect');
- var fxString = document.getElementById('dome').value;
- effect.loadFromFXString(fxString);
- material.effect = effect;
- material.drawList = g_viewInfo.performanceDrawList;
- effect.createUniformParameters(material);
- o3djs.dump.dump('-- created dome material\n');
-
- // Turn off culling since we are inside the sphere
- var state = pack.createObject('State');
- state.getStateParam('CullMode').value = g_o3d.State.CULL_NONE;
- material.state = state;
-
- var dome = o3djs.primitives.createSphere(pack, material, 150, 25, 25);
-
- var loader = g_loader.createLoader(
- function() {
- root.addShape(dome);
- });
-
- var sampler = loadTexture(loader, pack, material, 'DiffuseSampler',
- 'sky_compat.png');
-
- sampler = loadTexture(loader, pack, material, 'HorizonRamp',
- 'horizon_ramp.png');
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
-
- sampler = loadTexture(loader, pack, material, 'SunRamp', 'sun_ramp.png');
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
-
- connectParams(pack);
- loader.finish();
- o3djs.dump.dump('-- Finished dome\n');
-}
-
-/**
- * Binds params to the global params so they update automatically.
- * @param {!o3d.Pack} pack The pack containing the materials with params.
- */
-function connectParams(pack) {
- // Manually connect all the materials' lightWorldPos params to the global
- // params.
- var materials = pack.getObjectsByClassName('o3d.Material');
- for (var m = 0; m < materials.length; ++m) {
- var material = materials[m];
- var param = material.getParam('lightDirection');
- if (param) {
- param.bind(g_lightDirectionParam);
- }
- param = material.getParam('inputTime');
- if (param) {
- param.bind(g_clockParam);
- }
- param = material.getParam('cameraEye');
- if (param) {
- param.value = [-2.751, 3.529, -8.563];
- }
- }
-}
-
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
diff --git a/o3d/samples/yuv2rgb.html b/o3d/samples/yuv2rgb.html
deleted file mode 100644
index 317b731..0000000
--- a/o3d/samples/yuv2rgb.html
+++ /dev/null
@@ -1,196 +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.
--->
-
-<!--
-
-O3D YUV to RGB conversion Tutorial
-
-In this sample we convert from a Y'UV420p encoded video frame to an
-RGB texture using a shader to do the conversion on the video hardware.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>YUV to RGB Conversion in a shader.</title>
-<script type="text/javascript" src="o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.io');
-
-// Events
-// Run the init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_finished = false; // for selenium testing
-
-/**
- * Creates the client area and sets up the secondary init entry point.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D, loads the effect, and draws the quad that
- * will display the texture.
- *
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Setup an orthographic projection
- // Offset by half a pixel to avoid roundoff errors.
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -g_client.width * 0.5 + 0.5,
- g_client.width * 0.5 + 0.5,
- -g_client.height * 0.5 - 0.5,
- g_client.height * 0.5 - 0.5,
- 0.1,
- 1000);
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 500, 0],
- [0, 0, 0],
- [0, 0, -1]);
-
- // Create a material.
- var myMaterial = o3djs.material.createMaterialFromFile(
- g_pack,
- 'shaders/yuv2rgb.shader',
- g_viewInfo.performanceDrawList);
-
- // Creates a quad using the effect that has a 1:1 aspect ratio.
- var myShape = o3djs.primitives.createPlane(g_pack,
- myMaterial,
- 720, // width
- 720, // height
- 1, // quads across
- 1); // quads down
-
- // Get the material's sampler parameter
- var sampler_param = myMaterial.getParam('textureSampler');
- var sampler = g_pack.createObject('Sampler');
- sampler.addressModeU = g_o3d.Sampler.WRAP;
- sampler.addressModeV = g_o3d.Sampler.WRAP;
- sampler.magFilter = g_o3d.Sampler.POINT;
- sampler.minFilter = g_o3d.Sampler.POINT;
-
- // Be sure to turn off MIP-mapping, since that causes problems when
- // jumping around the image the way we are.
- sampler.mipFilter = g_o3d.Sampler.NONE;
- sampler_param.value = sampler;
-
- // Set the source image width
- var width_param = myMaterial.getParam('imageWidth');
- width_param.value = 720.0;
-
- // Set the source image height
- var height_param = myMaterial.getParam('imageHeight');
- height_param.value = 486.0;
-
- // Load our Y'UV420p texture, encoded as a greyscale PNG image. This
- // happens asynchronously.
- var url = o3djs.util.getCurrentURI() + 'assets/shaving_cream.png';
- o3djs.io.loadTexture(g_pack, url, function(texture, exception) {
- if (exception) {
- alert(exception);
- return;
- }
- sampler.texture = texture;
- // adjust the scale of our transform to match the aspect ratio of
- // the texture. Of course we could also have waited until now to build
- // our quad and set its width and height to match instead of scaling
- // here.
- var textureWidth = texture.width;
-
- // Account for additional data on bottom of image.
- var textureHeight = texture.height * 2.0 / 3.0;
- var hScale = 1;
- var vScale = 1;
- if (textureWidth > textureHeight) {
- vScale = textureHeight / textureWidth;
- } else if (textureHeight > textureWidth) {
- hScale = textureWidth / textureHeight;
- }
- // We now attach our quad to the root of the transform graph. We do
- // this after the texture has loaded, otherwise we'd be attempting
- // to display something invalid.
- var root = g_client.root;
- root.addShape(myShape);
- root.scale(hScale, 1, vScale);
-
- g_finished = true; // for selenium testing.
- });
-}
-</script>
-</head>
-<body>
-<h1>YUV to RGB Conversion</h1>
-<p>This how to do image colorspace and format conversion in a shader.</p>
-<p>Here is the YUV encoded image (treated as an 8-bit greyscale image):</p>
-<p><img src="assets/shaving_cream.png" style="width: 720px; height: 729px"
- alt="YUV encoded image"/></p>
-<p>Here is the original image, encoded as a JPEG image:</p>
-<p><img src="assets/shaving_cream.jpg" style="width: 720px; height: 486px"
- alt="Original JPG encoded image"/></p>
-<p>Here is the O3D plugin loading the YUV image, and converting it
-to RGB in the shader on the fly.</p>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 720px; height: 486px"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/samples/zsorting.html b/o3d/samples/zsorting.html
deleted file mode 100644
index 8168aaa..0000000
--- a/o3d/samples/zsorting.html
+++ /dev/null
@@ -1,200 +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.
--->
-
-<!--
-O3D ZSorting.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-ZSorting.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_timeMult = 1.0;
-var g_framesRendered = 0;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_clock = 0;
-var g_finished = false; // for selenium testing
-var g_groupTransforms = [];
-var GROUPS_ACROSS = 2;
-var UNITS_ACROSS_GROUP = 2;
-var TOTAL_ACROSS = GROUPS_ACROSS * UNITS_ACROSS_GROUP;
-var HALF_WIDTH = TOTAL_ACROSS * 0.0;
-var UNIT_SPACING = 100;
-
-/**
- * Make a grid of transforms and put a teapot instance on each one
- * @param {!o3d.Pack} pack Pack to create transforms in.
- * @param {!o3d.Shape} shape Shape to instance.
- */
-function createInstances(pack, shape) {
- for (var g = 0; g < GROUPS_ACROSS; g++) {
- for (var h = 0; h < GROUPS_ACROSS; h++) {
- for (var i = 0; i < GROUPS_ACROSS; i++) {
- var groupTransform = pack.createObject('Transform');
- g_groupTransforms[g_groupTransforms.length] = groupTransform;
- groupTransform.parent = g_client.root;
- groupTransform.translate(
- (g * UNITS_ACROSS_GROUP - HALF_WIDTH) * UNIT_SPACING,
- (h * UNITS_ACROSS_GROUP - HALF_WIDTH) * UNIT_SPACING,
- (i * UNITS_ACROSS_GROUP - HALF_WIDTH) * UNIT_SPACING);
- for (var x = 0; x < UNITS_ACROSS_GROUP; x++) {
- for (var y = 0; y < UNITS_ACROSS_GROUP; y++) {
- for (var z = 0; z < UNITS_ACROSS_GROUP; z++) {
- var transform = pack.createObject('Transform');
- transform.parent = groupTransform;
- transform.addShape(shape);
- transform.translate(
- (x - UNITS_ACROSS_GROUP * 0.5) * UNIT_SPACING,
- (y - UNITS_ACROSS_GROUP * 0.5) * UNIT_SPACING,
- (z - UNITS_ACROSS_GROUP * 0.5) * UNIT_SPACING);
- transform.createParam('diffuse', 'ParamFloat4').value = [
- (g * UNITS_ACROSS_GROUP + x) * (1 / TOTAL_ACROSS),
- (h * UNITS_ACROSS_GROUP + y) * (1 / TOTAL_ACROSS),
- (i * UNITS_ACROSS_GROUP + z) * (1 / TOTAL_ACROSS),
- 0.5];
- }
- }
- }
- }
- }
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
- g_client = o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create our projection matrix, with a vertical field of view of 45
- // degrees a near clipping plane of 0.1 and far clipping plane of 10000.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(45),
- g_client.width / g_client.height,
- 0.1,
- 10000);
-
- // Create a Material.
- var material = o3djs.material.createBasicMaterial(
- g_pack, g_viewInfo, [1, 1, 1, 1], true);
-
- // Create a sphere.
- var shape = o3djs.primitives.createSphere(g_pack, material, 30, 20, 20);
-
- createInstances(g_pack, shape);
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-
- g_finished = true; // for selenium testing.
-}
-
-// spin the camera.
-function onrender(renderEvent) {
- g_framesRendered++;
- // Get the number of seconds since the last render.
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- var x = Math.sin(g_clock * 0.1) * 400;
- var z = Math.cos(g_clock * 0.1) * 400;
- var y = Math.sin(g_clock * 0.2) * 400;
-
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [x, y, z], // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Removes any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>ZSorting</h1>
-Objects get zsorted for transparency.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/serializer/cross/README.txt b/o3d/serializer/cross/README.txt
deleted file mode 100644
index 17c04ef..0000000
--- a/o3d/serializer/cross/README.txt
+++ /dev/null
@@ -1,67 +0,0 @@
-These are the formats for the various O3D objects that can be stored in binary.
-
-NOTE:
-All int16, uint16, int32, uint32 and floats are stored in LITTLE ENDIAN format.
-
------------------------- Buffer ------------------------------------------------
-A Buffer (VertexBuffer, SourceBuffer, IndexBuffer) are all stored as follows.
-
-// Header
-uint8[4] id : A 4 byte ID with the ascii characters "BUFF"
-int32 version : A version number. Must be 1
-int32 numFields : The number of fields in the buffer.
-
-// For each field
- uint8 fieldType : Type of field. 1 = FloatField, 2 = UInt32Field, 3 = UByteNField.
- uint8 numComponents : The number of components for that field.
-// End for
-
-// stored once.
-uint32 numElements : The number of elements in the buffer.
-
-// For each field. Depending on the type of field
- // If FloatField
- float[numElements * numComponents]
-
- // If UInt32Field
- uint32[numElements * numComponents]
-
- // If UByteNField
- uint8[numElements * numComponents]
-// End for
-
-
------------------------- Curve -------------------------------------------------
-A Curve is stored as follows.
-
-// Header
-uint8[4] id : A 4 byte ID with the ascii characters "CURV"
-int32 version : A version number. Must be 1
-
-// For each key in the Curve
- uint8 keyType : The type of key. 1 = StepCurveKey, 2 = LinearCurveKey, 3 = BezierCurveKey
- float input : The input of the key
- float output : The output of the key
- // If it is a BezierCurveKey
- float inTangentX : the x component of the in tangent.
- float inTangentY : the y component of the in tangent.
- float outTangentX : the x component of the out tangent.
- float outTangentY : the y component of the out tangent.
-// End for
-
-
------------------------- Skin --------------------------------------------------
-A Skin is stored as follows.
-
-// Header
-uint8[4] id : A 4 byte ID with the ascii characters "SKIN"
-int32 version : A version number. Must be 1
-
-// For each vertex in the skin
- int32 numInfluences : The number of influences on this vertex.
- // For each influence
- int32 matrixIndex : the Index of a matrix that affects this vertex.
- float weight : The weight for this matrix.
- // End for each influence
-// End for each vertex
-
diff --git a/o3d/serializer/cross/serializer.cc b/o3d/serializer/cross/serializer.cc
deleted file mode 100644
index ccdc7ef..0000000
--- a/o3d/serializer/cross/serializer.cc
+++ /dev/null
@@ -1,948 +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 definitions of class Serializer.
-
-#include <vector>
-
-#include "serializer/cross/serializer.h"
-#include "serializer/cross/serializer_binary.h"
-
-#include "core/cross/buffer.h"
-#include "core/cross/curve.h"
-#include "core/cross/iclass_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/param_array.h"
-#include "core/cross/primitive.h"
-#include "core/cross/shape.h"
-#include "core/cross/skin.h"
-#include "core/cross/texture.h"
-#include "core/cross/transform.h"
-#include "import/cross/destination_buffer.h"
-#include "import/cross/iarchive_generator.h"
-#include "import/cross/json_object.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-#include "serializer/cross/version.h"
-#include "utils/cross/structured_writer.h"
-
-using std::string;
-
-namespace o3d {
-
-const char* Serializer::ROOT_PREFIX = "o3d_rootObject_";
-
-void Serialize(StructuredWriter* writer, ObjectBase* value) {
- if (value == NULL) {
- writer->WriteNull();
- } else {
- writer->BeginCompacting();
- writer->OpenObject();
- writer->WritePropertyName("ref");
- writer->WriteInt(GetObjectId(value));
- writer->CloseObject();
- writer->EndCompacting();
- }
-}
-
-void Serialize(StructuredWriter* writer, float value) {
- writer->WriteFloat(value);
-}
-
-void Serialize(StructuredWriter* writer, const Float2& value) {
- writer->BeginCompacting();
- writer->OpenArray();
- for (int i = 0; i < 2; ++i)
- writer->WriteFloat(value[i]);
- writer->CloseArray();
- writer->EndCompacting();
-}
-
-void Serialize(StructuredWriter* writer, const Float3& value) {
- writer->BeginCompacting();
- writer->OpenArray();
- for (int i = 0; i < 3; ++i)
- writer->WriteFloat(value[i]);
- writer->CloseArray();
- writer->EndCompacting();
-}
-
-void Serialize(StructuredWriter* writer, const Float4& value) {
- writer->BeginCompacting();
- writer->OpenArray();
- for (int i = 0; i < 4; ++i)
- writer->WriteFloat(value[i]);
- writer->CloseArray();
- writer->EndCompacting();
-}
-
-void Serialize(StructuredWriter* writer, int value) {
- writer->WriteInt(value);
-}
-
-void Serialize(StructuredWriter* writer, unsigned int value) {
- writer->WriteUnsignedInt(value);
-}
-
-void Serialize(StructuredWriter* writer, bool value) {
- writer->WriteBool(value);
-}
-
-void Serialize(StructuredWriter* writer, const String& value) {
- writer->WriteString(value);
-}
-
-void Serialize(StructuredWriter* writer, const Matrix4& value) {
- writer->BeginCompacting();
- writer->OpenArray();
- for (int i = 0; i < 4; ++i) {
- writer->OpenArray();
- for (int j = 0; j < 4; ++j)
- writer->WriteFloat(value[i][j]);
- writer->CloseArray();
- }
- writer->CloseArray();
- writer->EndCompacting();
-}
-
-void Serialize(StructuredWriter* writer, const BoundingBox& value) {
- writer->BeginCompacting();
- writer->OpenArray();
-
- if (value.valid()) {
- writer->OpenArray();
- for (int i = 0; i < 3; ++i)
- writer->WriteFloat(value.min_extent()[i]);
- writer->CloseArray();
- writer->OpenArray();
- for (int i = 0; i < 3; ++i)
- writer->WriteFloat(value.max_extent()[i]);
- writer->CloseArray();
- }
-
- writer->CloseArray();
- writer->EndCompacting();
-}
-
-void Serialize(StructuredWriter* writer, const Stream& stream) {
- writer->OpenObject();
-
- writer->WritePropertyName("field");
- Serialize(writer, GetObjectId(&stream.field()));
-
- writer->WritePropertyName("startIndex");
- Serialize(writer, stream.start_index());
-
- writer->WritePropertyName("semantic");
- Serialize(writer, stream.semantic());
-
- writer->WritePropertyName("semanticIndex");
- Serialize(writer, stream.semantic_index());
-
- writer->CloseObject();
-}
-
-void BinaryArchiveManager::WriteObjectBinary(ObjectBase* object,
- const string& file_name,
- const uint8* data,
- size_t numBytes) {
- FileContent& content = file_map_[file_name];
- ObjectBinaryRangeMap::iterator it = object_binary_range_map_.find(object);
- BinaryRange range;
- if (it != object_binary_range_map_.end()) {
- // It is okay to call WriteObjectBinary multiple times for a single
- // object but they must not be interleaved with those for other objects.
- range = it->second;
- DCHECK(range.end_offset_ == content.size());
- } else {
- range.begin_offset_ = content.size();
- }
- content.insert(content.end(), data, data + numBytes);
- range.end_offset_ = content.size();
- object_binary_range_map_[object] = range;
-}
-
-BinaryRange BinaryArchiveManager::GetObjectRange(ObjectBase* object) {
- return object_binary_range_map_[object];
-}
-
-void BinaryArchiveManager::WriteArchive(IArchiveGenerator* archive_generator) {
- for (FileMap::const_iterator it = file_map_.begin();
- it != file_map_.end();
- ++it) {
- const string& file_name = it->first;
- const FileContent& content = it->second;
- archive_generator->AddFile(file_name,
- content.size());
- MemoryReadStream stream(&content[0],
- content.size());
- archive_generator->AddFileBytes(&stream, content.size());
- }
-}
-
-namespace {
-bool ParamIsSerialized(Param* param) {
- return param->output_connections().size() != 0 ||
- (!param->dynamic() && !param->read_only());
-}
-
-class PropertiesVisitor : public VisitorBase<PropertiesVisitor> {
- public:
- // Parameters:
- // writer: The writer to use.
- // binary: True to write parts that can be binary in binary. False for pure
- // JSON.
- PropertiesVisitor(StructuredWriter* writer, bool binary)
- : writer_(writer),
- binary_(binary) {
- Enable<Curve>(&PropertiesVisitor::Visit);
- Enable<Element>(&PropertiesVisitor::Visit);
- Enable<NamedObject>(&PropertiesVisitor::Visit);
- Enable<JSONObject>(&PropertiesVisitor::Visit);
- Enable<Pack>(&PropertiesVisitor::Visit);
- Enable<Primitive>(&PropertiesVisitor::Visit);
- Enable<Shape>(&PropertiesVisitor::Visit);
- Enable<Skin>(&PropertiesVisitor::Visit);
- Enable<Transform>(&PropertiesVisitor::Visit);
- }
-
- private:
- void Visit(Curve* curve) {
- Visit(static_cast<NamedObject*>(curve));
-
- writer_->WritePropertyName("preInfinity");
- Serialize(writer_, curve->pre_infinity());
-
- writer_->WritePropertyName("postInfinity");
- Serialize(writer_, curve->post_infinity());
-
- writer_->WritePropertyName("useCache");
- Serialize(writer_, curve->use_cache());
-
- writer_->WritePropertyName("sampleRate");
- Serialize(writer_, curve->sample_rate());
- }
-
- void Visit(Element* element) {
- Visit(static_cast<NamedObject*>(element));
-
- writer_->WritePropertyName("owner");
- Serialize(writer_, element->owner());
- }
-
- void Visit(JSONObject* object) {
- Visit(static_cast<ParamObject*>(object));
- object->Serialize(writer_);
- }
-
- void Visit(NamedObject* object) {
- Visit(static_cast<ObjectBase*>(object));
-
- if (object->name().length() > 0) {
- writer_->WritePropertyName("name");
- Serialize(writer_, object->name());
- }
- }
-
- void Visit(ObjectBase* object) {
- }
-
- void Visit(Pack* pack) {
- Visit(static_cast<NamedObject*>(pack));
-
- writer_->WritePropertyName("root");
- Serialize(writer_, pack->root());
- }
-
- void Visit(Primitive* primitive) {
- Visit(static_cast<Element*>(primitive));
-
- writer_->WritePropertyName("numberVertices");
- Serialize(writer_, primitive->number_vertices());
-
- writer_->WritePropertyName("numberPrimitives");
- Serialize(writer_, primitive->number_primitives());
-
- writer_->WritePropertyName("primitiveType");
- Serialize(writer_, primitive->primitive_type());
-
- writer_->WritePropertyName("indexBuffer");
- Serialize(writer_, primitive->index_buffer());
-
- writer_->WritePropertyName("startIndex");
- Serialize(writer_, primitive->start_index());
- }
-
- void Visit(Shape* shape) {
- Visit(static_cast<ParamObject*>(shape));
-
- writer_->WritePropertyName("elements");
- writer_->BeginCompacting();
- writer_->OpenArray();
- const ElementRefArray& elements = shape->GetElementRefs();
- for (ElementRefArray::size_type i = 0; i != elements.size(); ++i) {
- Serialize(writer_, elements[i].Get());
- }
- writer_->CloseArray();
- writer_->EndCompacting();
- }
-
- void Visit(Skin* skin) {
- Visit(static_cast<NamedObject*>(skin));
-
- if (!binary_) {
- writer_->WritePropertyName("influences");
- writer_->BeginCompacting();
- writer_->OpenArray();
- const Skin::InfluencesArray& influences_array = skin->influences();
- for (Skin::InfluencesArray::size_type i = 0; i != influences_array.size(); ++i) {
- const Skin::Influences& influences = influences_array[i];
- writer_->OpenArray();
- for (Skin::Influences::size_type j = 0; j != influences.size(); ++j) {
- const Skin::Influence& influence = influences[j];
- Serialize(writer_, influence.matrix_index);
- Serialize(writer_, influence.weight);
- }
- writer_->CloseArray();
- }
- writer_->CloseArray();
- writer_->EndCompacting();
- }
-
- writer_->WritePropertyName("inverseBindPoseMatrices");
- writer_->BeginCompacting();
- writer_->OpenArray();
- const Skin::MatrixArray& inverse_bind_pose_matrices =
- skin->inverse_bind_pose_matrices();
- for (Skin::MatrixArray::size_type i = 0;
- i != inverse_bind_pose_matrices.size(); ++i) {
- const Matrix4& matrix = inverse_bind_pose_matrices[i];
- Serialize(writer_, matrix);
- }
- writer_->CloseArray();
- writer_->EndCompacting();
- }
-
- void Visit(Transform* transform) {
- Visit(static_cast<ParamObject*>(transform));
-
- writer_->WritePropertyName("shapes");
- writer_->BeginCompacting();
- writer_->OpenArray();
- const ShapeRefArray& shape_array = transform->GetShapeRefs();
- for (ShapeRefArray::size_type i = 0; i != shape_array.size(); ++i) {
- Serialize(writer_, shape_array[i]);
- }
- writer_->CloseArray();
- writer_->EndCompacting();
-
- writer_->WritePropertyName("parent");
- Serialize(writer_, transform->parent());
- }
-
- StructuredWriter* writer_;
- bool binary_;
-};
-
-class CustomVisitor : public VisitorBase<CustomVisitor> {
- public:
- // Parameters:
- // writer: The writer to use.
- // binary_archive_manager: The binary archive manager to add binary data
- // too. If this is NULL will write JSON instead where appropriate.
- CustomVisitor(StructuredWriter* writer,
- BinaryArchiveManager* binary_archive_manager)
- : writer_(writer),
- binary_archive_manager_(binary_archive_manager) {
- Enable<DestinationBuffer>(&CustomVisitor::Visit);
- Enable<Buffer>(&CustomVisitor::Visit);
- Enable<Curve>(&CustomVisitor::Visit);
- Enable<Primitive>(&CustomVisitor::Visit);
- Enable<Skin>(&CustomVisitor::Visit);
- Enable<SkinEval>(&CustomVisitor::Visit);
- Enable<StreamBank>(&CustomVisitor::Visit);
- Enable<Texture2D>(&CustomVisitor::Visit);
- Enable<TextureCUBE>(&CustomVisitor::Visit);
- if (!binary_archive_manager) {
- Enable<BezierCurveKey>(&CustomVisitor::Visit);
- Enable<LinearCurveKey>(&CustomVisitor::Visit);
- Enable<StepCurveKey>(&CustomVisitor::Visit);
- }
- }
-
- private:
- void Visit(DestinationBuffer* buffer) {
- // NOTE: We don't call Visit<VertexBuffer*> because we don't want to
- // serialize the contents of the Buffer. We only serialize its structure.
- Visit(static_cast<NamedObject*>(buffer));
- writer_->WritePropertyName("numElements");
- Serialize(writer_, buffer->num_elements());
- writer_->WritePropertyName("fields");
- writer_->OpenArray();
- const FieldRefArray& fields = buffer->fields();
- for (size_t ii = 0; ii < fields.size(); ++ii) {
- Field* field = fields[ii].Get();
- writer_->BeginCompacting();
- writer_->OpenObject();
- writer_->WritePropertyName("id");
- Serialize(writer_, field->id());
- writer_->WritePropertyName("type");
- Serialize(writer_, field->GetClassName());
- writer_->WritePropertyName("numComponents");
- Serialize(writer_, field->num_components());
- writer_->CloseObject();
- writer_->EndCompacting();
- }
- writer_->CloseArray();
- }
-
- void Visit(Buffer* buffer) {
- Visit(static_cast<NamedObject*>(buffer));
-
- if (binary_archive_manager_) {
- writer_->WritePropertyName("fields");
- writer_->OpenArray();
- const FieldRefArray& fields = buffer->fields();
- for (size_t ii = 0; ii < fields.size(); ++ii) {
- Field* field = fields[ii].Get();
- Serialize(writer_, field->id());
- }
- writer_->CloseArray();
-
- WriteObjectBinaryRange(buffer);
- } else {
- writer_->WritePropertyName("fieldData");
- writer_->OpenArray();
- const FieldRefArray& fields = buffer->fields();
- for (size_t ii = 0; ii < fields.size(); ++ii) {
- Field* field = fields[ii].Get();
- writer_->BeginCompacting();
- writer_->OpenObject();
- writer_->WritePropertyName("id");
- Serialize(writer_, field->id());
- writer_->WritePropertyName("type");
- Serialize(writer_, field->GetClassName());
- writer_->WritePropertyName("numComponents");
- Serialize(writer_, field->num_components());
- writer_->WritePropertyName("data");
- writer_->OpenArray();
- Buffer* buffer = field->buffer();
- if (buffer) {
- unsigned num_elements = buffer->num_elements();
- unsigned num_floats = num_elements * field->num_components();
- scoped_array<float> data(
- new float[num_floats]);
- field->GetAsFloats(
- 0, data.get(), field->num_components(), num_elements);
- for (size_t jj = 0; jj < num_floats; ++jj) {
- Serialize(writer_, data[jj]);
- }
- }
- writer_->CloseArray();
- writer_->CloseObject();
- writer_->EndCompacting();
- }
- writer_->CloseArray();
- }
- }
-
- void Visit(BezierCurveKey* key) {
- Serialize(writer_, CurveKey::TYPE_BEZIER);
- Serialize(writer_, key->input());
- Serialize(writer_, key->output());
- Serialize(writer_, key->in_tangent()[0]);
- Serialize(writer_, key->in_tangent()[1]);
- Serialize(writer_, key->out_tangent()[0]);
- Serialize(writer_, key->out_tangent()[1]);
- }
-
- void Visit(LinearCurveKey* key) {
- Serialize(writer_, CurveKey::TYPE_LINEAR);
- Serialize(writer_, key->input());
- Serialize(writer_, key->output());
- }
-
- void Visit(StepCurveKey* key) {
- Serialize(writer_, CurveKey::TYPE_STEP);
- Serialize(writer_, key->input());
- Serialize(writer_, key->output());
- }
-
- void Visit(Curve* curve) {
- Visit(static_cast<NamedObject*>(curve));
-
- if (binary_archive_manager_) {
- WriteObjectBinaryRange(curve);
- } else {
- writer_->WritePropertyName("keys");
- writer_->BeginCompacting();
- writer_->OpenArray();
- const CurveKeyRefArray& keys = curve->keys();
- for (CurveKeyRefArray::const_iterator it = keys.begin();
- it != keys.end(); ++it) {
- CurveKey* key = it->Get();
- writer_->OpenArray();
- Accept(key);
- writer_->CloseArray();
- }
- writer_->CloseArray();
- writer_->EndCompacting();
- }
- }
-
- void Visit(ObjectBase* object) {
- }
-
- void Visit(Primitive* primitive) {
- Visit(static_cast<Element*>(primitive));
-
- if (primitive->index_buffer()) {
- writer_->WritePropertyName("indexBuffer");
- Serialize(writer_, GetObjectId(primitive->index_buffer()));
- }
- }
-
- void Visit(Skin* skin) {
- Visit(static_cast<NamedObject*>(skin));
- if (binary_archive_manager_) {
- WriteObjectBinaryRange(skin);
- }
- }
-
- void Visit(SkinEval* skin_eval) {
- Visit(static_cast<VertexSource*>(skin_eval));
-
- writer_->WritePropertyName("vertexStreams");
- writer_->OpenArray();
- const StreamParamVector& vertex_stream_params =
- skin_eval->vertex_stream_params();
- for (StreamParamVector::size_type i = 0;
- i != vertex_stream_params.size(); ++i) {
- const Stream& stream = vertex_stream_params[i]->stream();
- writer_->OpenObject();
- writer_->WritePropertyName("stream");
- Serialize(writer_, stream);
-
- if (vertex_stream_params[i]->input_connection() != NULL) {
- writer_->WritePropertyName("bind");
- Serialize(writer_,
- GetObjectId(
- vertex_stream_params[i]->input_connection()->owner()));
- }
-
- writer_->CloseObject();
- }
- writer_->CloseArray();
- }
-
- void Visit(StreamBank* stream_bank) {
- Visit(static_cast<NamedObject*>(stream_bank));
-
- writer_->WritePropertyName("vertexStreams");
- writer_->OpenArray();
- const StreamParamVector& vertex_stream_params =
- stream_bank->vertex_stream_params();
- for (StreamParamVector::size_type i = 0;
- i != vertex_stream_params.size(); ++i) {
- const Stream& stream = vertex_stream_params[i]->stream();
- writer_->OpenObject();
- writer_->WritePropertyName("stream");
- Serialize(writer_, stream);
-
- if (vertex_stream_params[i]->input_connection() != NULL) {
- writer_->WritePropertyName("bind");
- Serialize(writer_,
- GetObjectId(
- vertex_stream_params[i]->input_connection()->owner()));
- }
-
- writer_->CloseObject();
- }
- writer_->CloseArray();
- }
-
- void Visit(Texture2D* texture) {
- Visit(static_cast<Texture*>(texture));
-
- writer_->WritePropertyName("width");
- Serialize(writer_, texture->width());
- writer_->WritePropertyName("height");
- Serialize(writer_, texture->height());
- writer_->WritePropertyName("format");
- Serialize(writer_, texture->format());
- writer_->WritePropertyName("levels");
- Serialize(writer_, texture->levels());
- writer_->WritePropertyName("renderSurfacesEnabled");
- Serialize(writer_, texture->render_surfaces_enabled());
- }
-
- void Visit(TextureCUBE* texture) {
- Visit(static_cast<Texture*>(texture));
-
- writer_->WritePropertyName("edgeLength");
- Serialize(writer_, texture->edge_length());
- writer_->WritePropertyName("format");
- Serialize(writer_, texture->format());
- writer_->WritePropertyName("levels");
- Serialize(writer_, texture->levels());
- writer_->WritePropertyName("renderSurfacesEnabled");
- Serialize(writer_, texture->render_surfaces_enabled());
- }
-
- void WriteObjectBinaryRange(ObjectBase* object) {
- writer_->WritePropertyName("binaryRange");
- writer_->BeginCompacting();
- writer_->OpenArray();
- BinaryRange range = binary_archive_manager_->GetObjectRange(object);
- writer_->WriteUnsignedInt(static_cast<unsigned int>(range.begin_offset_));
- writer_->WriteUnsignedInt(static_cast<unsigned int>(range.end_offset_));
- writer_->CloseArray();
- writer_->EndCompacting();
- }
-
- StructuredWriter* writer_;
- BinaryArchiveManager* binary_archive_manager_;
-};
-
-class ParamVisitor : public VisitorBase<ParamVisitor> {
- public:
- explicit ParamVisitor(StructuredWriter* writer)
- : writer_(writer) {
- Enable<ParamObject>(&ParamVisitor::Visit);
- Enable<ParamArray>(&ParamVisitor::Visit);
- Enable<ParamBoolean>(&ParamVisitor::Visit);
- Enable<ParamBoundingBox>(&ParamVisitor::Visit);
- Enable<ParamFloat>(&ParamVisitor::Visit);
- Enable<ParamFloat2>(&ParamVisitor::Visit);
- Enable<ParamFloat3>(&ParamVisitor::Visit);
- Enable<ParamFloat4>(&ParamVisitor::Visit);
- Enable<ParamInteger>(&ParamVisitor::Visit);
- Enable<ParamMatrix4>(&ParamVisitor::Visit);
- Enable<ParamString>(&ParamVisitor::Visit);
- Enable<RefParamBase>(&ParamVisitor::Visit);
- Enable<Material>(&ParamVisitor::Visit);
- }
-
- private:
- void Visit(Material* object) {
- Visit(static_cast<ParamObject*>(object));
- }
-
- void Visit(ParamObject* object) {
- const NamedParamRefMap& params = object->params();
-
- int numWrittenParams = 0;
- for (NamedParamRefMap::const_iterator it = params.begin();
- it != params.end(); ++it) {
- String param_name = it->first;
- Param::Ref param = it->second;
- if (ParamIsSerialized(param.Get())) {
- ++numWrittenParams;
- }
- }
-
- if (numWrittenParams > 0) {
- writer_->WritePropertyName("params");
- writer_->OpenObject();
- for (NamedParamRefMap::const_iterator it = params.begin();
- it != params.end(); ++it) {
- String param_name = it->first;
- Param::Ref param = it->second;
- if (ParamIsSerialized(param.Get())) {
- writer_->WritePropertyName(param_name);
- Accept(param.Get());
- }
- }
- writer_->CloseObject();
- }
- }
-
- void Visit(ParamArray* param_array) {
- writer_->WritePropertyName("params");
- writer_->OpenArray();
- const ParamArray::ParamRefVector& params = param_array->params();
- for (unsigned i = 0; i < params.size(); ++i) {
- Param::Ref param = params[i];
- Accept(param.Get());
- }
- writer_->CloseArray();
- }
-
- template <typename ParamType>
- void Visit(ParamType* param) {
- writer_->BeginCompacting();
- writer_->OpenObject();
-
- if (param->owner() == NULL || param->owner()->IsAddedParam(param)) {
- writer_->WritePropertyName("class");
- writer_->WriteString(param->GetClassName());
- }
-
- if (param->output_connections().size() != 0) {
- writer_->WritePropertyName("id");
- writer_->WriteInt(param->id());
- }
- if (param->input_connection() != NULL) {
- writer_->WritePropertyName("bind");
- writer_->WriteInt(param->input_connection()->id());
- } else if (!param->dynamic()) {
- writer_->WritePropertyName("value");
- Serialize(writer_, param->value());
- }
-
- writer_->CloseObject();
- writer_->EndCompacting();
- }
-
- StructuredWriter* writer_;
-};
-
-class BinaryVisitor : public VisitorBase<BinaryVisitor> {
- public:
- explicit BinaryVisitor(BinaryArchiveManager* binary_archive_manager)
- : binary_archive_manager_(binary_archive_manager) {
- Enable<Curve>(&BinaryVisitor::Visit);
- Enable<IndexBuffer>(&BinaryVisitor::Visit);
- Enable<DestinationBuffer>(&BinaryVisitor::Visit);
- Enable<VertexBufferBase>(&BinaryVisitor::Visit);
- Enable<Skin>(&BinaryVisitor::Visit);
- }
-
- private:
- void Visit(ObjectBase* object) {
- }
-
- void Visit(Curve* curve) {
- Visit(static_cast<NamedObject*>(curve));
-
- MemoryBuffer<uint8> serialized_data;
- SerializeCurve(*curve, &serialized_data);
-
- binary_archive_manager_->WriteObjectBinary(
- curve,
- "curve-keys.bin",
- serialized_data,
- serialized_data.GetLength());
- }
-
- void Visit(DestinationBuffer* buffer) {
- // Destination buffers should NOT have their contents serialized.
- Visit(static_cast<Buffer*>(buffer));
- }
-
- void Visit(IndexBuffer* buffer) {
- Visit(static_cast<Buffer*>(buffer));
-
- MemoryBuffer<uint8> serialized_data;
- SerializeBuffer(*buffer, &serialized_data);
-
- binary_archive_manager_->WriteObjectBinary(
- buffer,
- "index-buffers.bin",
- serialized_data,
- serialized_data.GetLength());
- }
-
- void Visit(VertexBufferBase* buffer) {
- Visit(static_cast<Buffer*>(buffer));
-
- MemoryBuffer<uint8> serialized_data;
- SerializeBuffer(*buffer, &serialized_data);
-
- binary_archive_manager_->WriteObjectBinary(
- buffer,
- "vertex-buffers.bin",
- serialized_data,
- serialized_data.GetLength());
- }
-
- void Visit(Skin* skin) {
- Visit(static_cast<NamedObject*>(skin));
-
- MemoryBuffer<uint8> serialized_data;
- SerializeSkin(*skin, &serialized_data);
-
- binary_archive_manager_->WriteObjectBinary(
- skin,
- "skins.bin",
- serialized_data,
- serialized_data.GetLength());
- }
-
- BinaryArchiveManager* binary_archive_manager_;
-};
-
-// Checks object has a name that starts with prefix.
-// Parameters:
-// object: ObjectBase object to check.
-// prefix: prefix to check for
-// name: optional, pointer to String to store name.
-bool NameStartsWithPrefix(const ObjectBase* object,
- const String& prefix,
- String* name) {
- String object_name;
- if (object->IsA(NamedObject::GetApparentClass())) {
- object_name = down_cast<const NamedObject*>(object)->name();
- } else if (object->IsA(Param::GetApparentClass())) {
- object_name = down_cast<const Param*>(object)->name();
- }
- if (prefix.size() <= object_name.size() &&
- object_name.compare(0, prefix.size(), prefix) == 0) {
- if (name) {
- *name = object_name;
- }
- return true;
- }
- return false;
-}
-
-} // namespace anonymous
-
-Serializer::Serializer(ServiceLocator* service_locator,
- StructuredWriter* writer,
- IArchiveGenerator* archive_generator,
- const Serializer::Options& options)
- : class_manager_(service_locator),
- writer_(writer),
- archive_generator_(archive_generator),
- options_(options) {
- bool binary = options.binary_output == Options::kBinaryOutputOn;
- sections_[PROPERTIES_SECTION].name_ = "properties";
- sections_[PROPERTIES_SECTION].visitor_ =
- new PropertiesVisitor(writer_, binary);
- sections_[CUSTOM_SECTION].name_ = "custom";
- sections_[CUSTOM_SECTION].visitor_ = new CustomVisitor(
- writer_, binary ? &binary_archive_manager_ : NULL);
- param_visitor_ = new ParamVisitor(writer_);
- binary_visitor_ = binary ? new BinaryVisitor(&binary_archive_manager_) : NULL;
-}
-
-Serializer::~Serializer() {
- for (int i = 0; i != NUM_SECTIONS; ++i) {
- delete sections_[i].visitor_;
- }
- delete param_visitor_;
- if (binary_visitor_) {
- delete binary_visitor_;
- }
-}
-
-void Serializer::SerializePack(Pack* pack) {
- SerializePackBinary(pack);
-
- writer_->OpenObject();
- writer_->WritePropertyName("version");
- writer_->WriteInt(kSerializerVersion);
-
- // write out properties for all objects starting with ROOT_PREFIX
- ObjectBaseArray owned_objects = pack->GetByClass<ObjectBase>();
- for (ObjectBaseArray::const_iterator it = owned_objects.begin();
- it != owned_objects.end(); ++it) {
- String name;
- if (NameStartsWithPrefix(*it, ROOT_PREFIX, &name)) {
- writer_->WritePropertyName(name);
- Serialize(writer_, GetObjectId(*it));
- }
- }
-
-
- writer_->WritePropertyName("objects");
- writer_->OpenObject();
-
- std::vector<const ObjectBase::Class*> classes =
- class_manager_->GetAllClasses();
-
- for (std::vector<const ObjectBase::Class*>::size_type i = 0;
- i != classes.size(); ++i) {
- const ObjectBase::Class* current_class = classes[i];
- if (!ObjectBase::ClassIsA(current_class, Param::GetApparentClass())) {
- std::vector<ObjectBase*> objects_of_class;
- for (ObjectBaseArray::const_iterator it = owned_objects.begin();
- it != owned_objects.end(); ++it) {
- if ((*it)->GetClassName() == current_class->name() &&
- !NameStartsWithPrefix(*it, ROOT_PREFIX, NULL)) {
- objects_of_class.push_back(*it);
- }
- }
- if (objects_of_class.size() != 0) {
- writer_->WritePropertyName(current_class->name());
- writer_->OpenArray();
- for (std::vector<ObjectBase*>::size_type j = 0;
- j != objects_of_class.size(); ++j) {
- writer_->OpenObject();
- SerializeObject(objects_of_class[j]);
- writer_->CloseObject();
- }
- writer_->CloseArray();
- }
- }
- }
-
- writer_->CloseObject();
- writer_->CloseObject();
-
- binary_archive_manager_.WriteArchive(archive_generator_);
-}
-
-void Serializer::SerializePackBinary(Pack* pack) {
- if (binary_visitor_) {
- std::vector<ObjectBase*> objects = pack->GetByClass<ObjectBase>();
- for (std::vector<ObjectBase*>::size_type i = 0; i < objects.size(); ++i) {
- binary_visitor_->Accept(objects[i]);
- }
- }
-}
-
-void Serializer::SerializeObject(ObjectBase* object) {
- writer_->WritePropertyName("id");
- writer_->WriteInt(object->id());
- for (int i = 0; i != NUM_SECTIONS; ++i) {
- if (sections_[i].visitor_->IsHandled(object->GetClass())) {
- writer_->WritePropertyName(sections_[i].name_);
- writer_->OpenObject();
- SerializeSection(object, static_cast<Section>(i));
- writer_->CloseObject();
- }
- }
-
- param_visitor_->Accept(object);
-}
-
-void Serializer::SerializeSection(ObjectBase* object, Section section) {
- DCHECK(section >= 0 && section < NUM_SECTIONS);
- sections_[section].visitor_->Accept(object);
-}
-
-void Serializer::SerializeParam(Param* param) {
- param_visitor_->Accept(param);
-}
-} // namespace o3d
diff --git a/o3d/serializer/cross/serializer.h b/o3d/serializer/cross/serializer.h
deleted file mode 100644
index 18aa20c..0000000
--- a/o3d/serializer/cross/serializer.h
+++ /dev/null
@@ -1,216 +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 declaration of class Serializer.
-
-#ifndef O3D_SERIALIZER_CROSS_SERIALIZER_H_
-#define O3D_SERIALIZER_CROSS_SERIALIZER_H_
-
-#include <map>
-#include <string>
-#include <vector>
-
-#include "base/basictypes.h"
-#include "core/cross/bounding_box.h"
-#include "core/cross/float_n.h"
-#include "core/cross/object_base.h"
-#include "core/cross/stream.h"
-#include "core/cross/types.h"
-#include "core/cross/visitor_base.h"
-#include "core/cross/service_dependency.h"
-#include "import/cross/iarchive_generator.h"
-#include "utils/cross/structured_writer.h"
-
-namespace o3d {
-
-class IClassManager;
-class Pack;
-class StructuredWriter;
-class Transform;
-
-// Serialize value to a StructuredWriter.
-void Serialize(StructuredWriter* writer, ObjectBase* value);
-
-// Serialize value to a StructuredWriter.
-void Serialize(StructuredWriter* writer, float value);
-
-// Serialize value to a StructuredWriter.
-void Serialize(StructuredWriter* writer, const Float2& value);
-
-// Serialize value to a StructuredWriter.
-void Serialize(StructuredWriter* writer, const Float3& value);
-
-// Serialize value to a StructuredWriter.
-void Serialize(StructuredWriter* writer, const Float4& value);
-
-// Serialize value to a StructuredWriter.
-void Serialize(StructuredWriter* writer, int value);
-
-// Serialize value to a StructuredWriter.
-void Serialize(StructuredWriter* writer, unsigned int value);
-
-// Serialize value to a StructuredWriter.
-void Serialize(StructuredWriter* writer, bool value);
-
-// Serialize value to a StructuredWriter.
-void Serialize(StructuredWriter* writer, const String& value);
-
-// Serialize value to a StructuredWriter.
-void Serialize(StructuredWriter* writer, const Matrix4& value);
-
-// Serialize value to a StructuredWriter.
-void Serialize(StructuredWriter* writer, const BoundingBox& value);
-
-// Serialize value to a StructuredWriter.
-void Serialize(StructuredWriter* writer, const Stream& value);
-
-// A range of bytes within a binary file.
-struct BinaryRange {
- BinaryRange() : begin_offset_(0), end_offset_(0) {}
- BinaryRange(size_t begin_offset, size_t end_offset)
- : begin_offset_(begin_offset),
- end_offset_(end_offset) {
- }
- size_t begin_offset_;
- size_t end_offset_;
-};
-
-// A class that tracks the contents of binary files in an archive and the ranges
-// corresponding to each object.
-class BinaryArchiveManager {
- typedef std::vector<uint8> FileContent;
- typedef std::map<std::string, FileContent > FileMap;
- typedef std::map<ObjectBase*, BinaryRange> ObjectBinaryRangeMap;
-
- public:
- BinaryArchiveManager() {
- }
-
- // Write the binary content for an object. Multiple consecutive calls
- // can be made for a single object. Calls for different objects may not
- // be interleaved. All binary content for a particular object must be
- // written to a single file. This function does not write to the archive.
- // That is deferred until WriteArchive is called.
- void WriteObjectBinary(ObjectBase* object,
- const std::string& file_name,
- const uint8* begin,
- size_t numBytes);
-
- // Gets the byte range of the file corresponding to a particular
- // object.
- BinaryRange GetObjectRange(ObjectBase* object);
-
- // Writes all the collected binary data to the archive.
- void WriteArchive(IArchiveGenerator* archive_generator);
-
- private:
- FileMap file_map_;
- ObjectBinaryRangeMap object_binary_range_map_;
- DISALLOW_COPY_AND_ASSIGN(BinaryArchiveManager);
-};
-
-// Serializes whole packs, individual objects, individual sections
-// of objects or individual Params to a StructuedWriter.
-class Serializer {
- public:
- // Enumeration of all sections that may optionally be included in
- // an object.
- enum Section {
- PROPERTIES_SECTION,
- CUSTOM_SECTION,
- NUM_SECTIONS
- };
-
- // Serialization Options.
- struct Options {
- enum BinaryOutput {
- kBinaryOutputOn, // output binary
- kBinaryOutputOff, // don't output binary.
- };
-
- explicit Options(BinaryOutput in_binary_output)
- : binary_output(in_binary_output) {
- }
-
- BinaryOutput binary_output;
- };
-
- // Any object that starts with this prefix will not be seralized
- // but a reference to it will be put at the top of the json object.
- static const char* ROOT_PREFIX;
-
- // Construct a new Serializer that writes future output to the
- // given StructuredWriter and IArchiveGenerator.
- explicit Serializer(ServiceLocator* service_locator,
- StructuredWriter* writer,
- IArchiveGenerator* archive_generator,
- const Options& options);
- ~Serializer();
-
- // Serialize a Pack and all the objects contained by the pack
- // to the StructuredWriter.
- void SerializePack(Pack* pack);
-
- // Serialize all the binary files in a pack.
- void SerializePackBinary(Pack* pack);
-
- // Serialize a single object to the StructuredWriter.
- void SerializeObject(ObjectBase* object);
-
- // Serialize one of the sections of an object to the StructuredWriter.
- void SerializeSection(ObjectBase* object, Section section);
-
- // Serialize a single Param of an object to the StructuredWriter.
- void SerializeParam(Param* param);
-
- private:
- ServiceDependency<IClassManager> class_manager_;
- StructuredWriter* writer_;
- IArchiveGenerator* archive_generator_;
- Options options_;
-
- struct SectionConfig {
- const char* name_;
- IVisitor* visitor_;
- };
- SectionConfig sections_[NUM_SECTIONS];
-
- IVisitor* param_visitor_;
- IVisitor* binary_visitor_;
-
- BinaryArchiveManager binary_archive_manager_;
-
- DISALLOW_COPY_AND_ASSIGN(Serializer);
-};
-} // namespace o3d
-
-#endif // O3D_SERIALIZER_CROSS_SERIALIZER_H_
diff --git a/o3d/serializer/cross/serializer_binary.cc b/o3d/serializer/cross/serializer_binary.cc
deleted file mode 100644
index 463b165..0000000
--- a/o3d/serializer/cross/serializer_binary.cc
+++ /dev/null
@@ -1,263 +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 serializer code for binary objects:
-// Buffer, Curve, Skin...
-
-#include <vector>
-
-#include "core/cross/buffer.h"
-#include "core/cross/curve.h"
-#include "core/cross/error.h"
-#include "core/cross/skin.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-
-const size_t kSerializationIDSize = 4;
-const size_t kVersionSize = sizeof(int32);
-
-namespace o3d {
-
-// |output| will be filled with the serialized data
-void SerializeBuffer(const Buffer &buffer, MemoryBuffer<uint8> *output) {
- // Determine the total size for the serialization data
- const unsigned num_elements = buffer.num_elements();
- const size_t num_fields = buffer.fields().size();
- const size_t kNumFieldsSize = sizeof(int32);
- const size_t kSingleFieldInfoSize = 2 * sizeof(uint8); // id / num_components
- const size_t all_field_infos_size = num_fields * kSingleFieldInfoSize;
- const size_t kNumElementsSize = sizeof(int32);
-
- // Add up all the parts comprising the header
- const size_t header_size = kSerializationIDSize +
- kVersionSize +
- kNumFieldsSize +
- all_field_infos_size +
- kNumElementsSize;
-
- const size_t data_size = buffer.GetSizeInBytes();
- const size_t total_size = header_size + data_size;
- output->Resize(total_size);
-
- MemoryWriteStream stream(*output, total_size);
-
- // write out serialization ID for buffer
- stream.Write(Buffer::kSerializationID, 4);
-
- // write out version
- stream.WriteLittleEndianInt32(1);
-
- // write out number of fields
- stream.WriteLittleEndianInt32(static_cast<int32>(num_fields));
-
- // Write out the specification for the fields
- for (size_t i = 0; i < num_fields; ++i) {
- const Field &field = *buffer.fields()[i];
-
- // Determine the FIELDID code we need to write out
- // Start out "unknown" until we determine the class
- uint8 field_id = Field::FIELDID_UNKNOWN;
-
- if (field.IsA(FloatField::GetApparentClass())) {
- field_id = Field::FIELDID_FLOAT32;
- } else if (field.IsA(UInt32Field::GetApparentClass())) {
- field_id = Field::FIELDID_UINT32;
- } else if (field.IsA(UByteNField::GetApparentClass())) {
- field_id = Field::FIELDID_BYTE;
- } else {
- O3D_ERROR(buffer.service_locator()) << "illegal buffer field";
- return;
- }
-
- stream.WriteByte(field_id);
- stream.WriteByte(field.num_components());
- }
-
- // Write out the number of elements
- stream.WriteLittleEndianUInt32(num_elements);
-
- // Write out the data for each field
- // Write out the specification for the fields
- for (size_t i = 0; i < num_fields; ++i) {
- const Field &field = *buffer.fields()[i];
-
- MemoryBuffer<uint8> field_data(field.size() * num_elements);
- uint8 *destination = field_data;
-
- // Figure out what type of field it is, and get the data
- // appropriately
- size_t nitems = num_elements * field.num_components();
-
- if (field.IsA(FloatField::GetApparentClass())) {
- float *float_destination = reinterpret_cast<float*>(destination);
- field.GetAsFloats(0,
- float_destination,
- field.num_components(),
- num_elements);
- // Write out as little endian float32
- for (size_t i = 0; i < nitems; ++i) {
- stream.WriteLittleEndianFloat32(float_destination[i]);
- }
- } else if (field.IsA(UInt32Field::GetApparentClass())) {
- const UInt32Field &int_field = static_cast<const UInt32Field&>(field);
- uint32 *int_destination = reinterpret_cast<uint32*>(destination);
- int_field.GetAsUInt32s(0,
- int_destination,
- field.num_components(),
- num_elements);
- // Write out as little endian int32
- for (size_t i = 0; i < nitems; ++i) {
- stream.WriteLittleEndianInt32(int_destination[i]);
- }
- } else if (field.IsA(UByteNField::GetApparentClass())) {
- const UByteNField &byte_field = static_cast<const UByteNField&>(field);
- uint8 *byte_destination = reinterpret_cast<uint8*>(destination);
- byte_field.GetAsUByteNs(0,
- byte_destination,
- field.num_components(),
- num_elements);
- // Write out the bytes
- stream.Write(byte_destination, nitems);
- }
- }
-
- if (stream.GetStreamPosition() != total_size) {
- O3D_ERROR(buffer.service_locator()) << "error in serializing buffer";
- return;
- }
-}
-
-// |output| will be filled with the serialized data
-void SerializeCurve(const Curve &curve, MemoryBuffer<uint8> *output) {
- const size_t num_keys = const_cast<Curve&>(curve).keys().size();
-
- // Bezier entry size is biggest, so compute kKeyEntryMaxSize based on it
- const size_t kFloat2Size = 2 * sizeof(float);
- const size_t kKeyEntryMaxSize =
- sizeof(uint8) + 2 * sizeof(float) + 2 * kFloat2Size;
-
- const size_t key_data_max_size = num_keys * kKeyEntryMaxSize;
- const size_t max_total_size =
- kSerializationIDSize + kVersionSize + key_data_max_size;
-
- // Allocate a buffer which is large enough to hold the serialized data
- // It may be larger than the actual size required. It will be resized
- // to the exact size at the end
- output->Resize(max_total_size);
-
- MemoryWriteStream stream(*output, max_total_size);
-
- // write out serialization ID for curve
- stream.Write(Curve::kSerializationID, 4);
-
- // write out version
- stream.WriteLittleEndianInt32(1);
-
-
- for (size_t i = 0; i < num_keys; ++i) {
- const CurveKey &key = *curve.GetKey(i);
-
- // determine the KeyType based on the key's class
- if (key.IsA(StepCurveKey::GetApparentClass())) {
- stream.WriteByte(CurveKey::TYPE_STEP);
- stream.WriteLittleEndianFloat32(key.input());
- stream.WriteLittleEndianFloat32(key.output());
- } else if (key.IsA(LinearCurveKey::GetApparentClass())) {
- stream.WriteByte(CurveKey::TYPE_LINEAR);
- stream.WriteLittleEndianFloat32(key.input());
- stream.WriteLittleEndianFloat32(key.output());
- } else if (key.IsA(BezierCurveKey::GetApparentClass())) {
- const BezierCurveKey &bezier_key =
- static_cast<const BezierCurveKey&>(key);
- stream.WriteByte(CurveKey::TYPE_BEZIER);
- stream.WriteLittleEndianFloat32(bezier_key.input());
- stream.WriteLittleEndianFloat32(bezier_key.output());
- stream.WriteLittleEndianFloat32(bezier_key.in_tangent().getX());
- stream.WriteLittleEndianFloat32(bezier_key.in_tangent().getY());
- stream.WriteLittleEndianFloat32(bezier_key.out_tangent().getX());
- stream.WriteLittleEndianFloat32(bezier_key.out_tangent().getY());
- } else {
- O3D_ERROR(curve.service_locator()) << "error in serializing curve";
- return;
- }
- }
-
- // Make note of total amount of data written and set the buffer to this
- // exact size
- size_t total_size = stream.GetStreamPosition();
- output->Resize(total_size);
-}
-
-// |output| will be filled with the serialized data
-void SerializeSkin(const Skin &skin, MemoryBuffer<uint8> *output) {
- const Skin::InfluencesArray &influences_array = skin.influences();
- const size_t influences_array_size = influences_array.size();
-
- // Count up total number of individual influences
- size_t total_influence_count = 0;
- for (size_t i = 0; i < influences_array_size; ++i) {
- total_influence_count += influences_array[i].size();
- }
-
- const size_t kInfluenceSize = sizeof(uint32) + sizeof(float);
- const size_t total_size = kSerializationIDSize +
- kVersionSize +
- influences_array_size * sizeof(uint32) +
- total_influence_count * kInfluenceSize;
-
-
- // Allocate a buffer to hold the serialized data
- output->Resize(total_size);
- MemoryWriteStream stream(*output, total_size);
-
- // write out serialization ID for skin
- stream.Write(Skin::kSerializationID, 4);
-
- // write out version
- stream.WriteLittleEndianInt32(1);
-
- for (size_t i = 0; i < influences_array_size; ++i) {
- const Skin::Influences &influences = influences_array[i];
-
- // Write the influence count for this Influences object
- size_t influence_count = influences.size();
- stream.WriteLittleEndianInt32(static_cast<int32>(influence_count));
-
- for (size_t j = 0; j < influence_count; ++j) {
- const Skin::Influence &influence = influences[j];
- stream.WriteLittleEndianInt32(influence.matrix_index);
- stream.WriteLittleEndianFloat32(influence.weight);
- }
- }
-}
-
-} // namespace o3d
diff --git a/o3d/serializer/cross/serializer_binary.h b/o3d/serializer/cross/serializer_binary.h
deleted file mode 100644
index 9e19392..0000000
--- a/o3d/serializer/cross/serializer_binary.h
+++ /dev/null
@@ -1,56 +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 function declarations for serializing objects
-// with binary representations:
-// Buffer, Curve, Skin...
-
-#ifndef O3D_SERIALIZER_CROSS_SERIALIZER_BINARY_H_
-#define O3D_SERIALIZER_CROSS_SERIALIZER_BINARY_H_
-
-#include "import/cross/memory_buffer.h"
-
-namespace o3d {
-
-class Buffer;
-class Curve;
-class Skin;
-
-// Returns a MemoryBuffer object containing the serialized data
-// returns NULL on error
-void SerializeBuffer(const Buffer &buffer, MemoryBuffer<uint8> *output);
-void SerializeCurve(const Curve &curve, MemoryBuffer<uint8> *output);
-void SerializeSkin(const Skin &skin, MemoryBuffer<uint8> *output);
-
-} // namespace o3d
-
-#endif // O3D_SERIALIZER_CROSS_SERIALIZER_BINARY_H_
diff --git a/o3d/serializer/cross/serializer_test.cc b/o3d/serializer/cross/serializer_test.cc
deleted file mode 100644
index 3d21e41..0000000
--- a/o3d/serializer/cross/serializer_test.cc
+++ /dev/null
@@ -1,1171 +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 tests of class Serializer.
-
-#include <vector>
-
-#include "base/basictypes.h"
-#include "core/cross/buffer.h"
-#include "core/cross/curve.h"
-#include "core/cross/matrix4_translation.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/pack.h"
-#include "core/cross/param_array.h"
-#include "core/cross/primitive.h"
-#include "core/cross/service_dependency.h"
-#include "core/cross/shape.h"
-#include "core/cross/skin.h"
-#include "core/cross/texture.h"
-#include "core/cross/transform.h"
-#include "import/cross/memory_buffer.h"
-#include "import/cross/memory_stream.h"
-#include "serializer/cross/serializer.h"
-#include "serializer/cross/serializer_binary.h"
-#include "serializer/cross/version.h"
-#include "tests/common/win/testing_common.h"
-#include "utils/cross/string_writer.h"
-#include "utils/cross/json_writer.h"
-
-using std::vector;
-
-namespace o3d {
-
-struct AddFileRecord {
- String file_name_;
- size_t file_size_;
- vector<uint8> file_contents_;
-};
-
-class MockArchiveGenerator : public IArchiveGenerator {
- public:
- MockArchiveGenerator() : closed_(false), success_(false) {
- }
-
- virtual bool AddFile(const String& file_name,
- size_t file_size) {
- AddFileRecord record;
- record.file_name_ = file_name;
- record.file_size_ = file_size;
- add_file_records_.push_back(record);
- return true;
- }
-
- virtual int AddFileBytes(MemoryReadStream* stream, size_t numBytes) {
- const uint8* direct_pointer = stream->GetDirectMemoryPointer();
- add_file_records_.back().file_contents_.insert(
- add_file_records_.back().file_contents_.begin(),
- direct_pointer,
- direct_pointer + numBytes);
- return 0;
- }
-
- virtual void Close(bool success) {
- closed_ = true;
- success_ = success;
- }
-
- vector<AddFileRecord> add_file_records_;
- bool closed_;
- bool success_;
-};
-
-class SerializerTest : public testing::Test {
- protected:
- SerializerTest()
- : object_manager_(g_service_locator),
- output_(StringWriter::CR_LF),
- json_writer_(&output_, 2),
- serializer_(
- g_service_locator, &json_writer_, &archive_generator_,
- Serializer::Options(Serializer::Options::kBinaryOutputOn)) {
- json_writer_.BeginCompacting();
- }
-
- virtual void SetUp() {
- pack_ = object_manager_->CreatePack();
- }
-
- virtual void TearDown() {
- object_manager_->DestroyPack(pack_);
- }
-
- ServiceDependency<ObjectManager> object_manager_;
- Pack* pack_;
- StringWriter output_;
- JsonWriter json_writer_;
- MockArchiveGenerator archive_generator_;
- Serializer serializer_;
-};
-
-TEST_F(SerializerTest,
- ShouldSerializeParamWithOnlyValueIfItIsNotBoundOrLateAdded) {
- Transform* transform = pack_->Create<Transform>();
- ParamMatrix4* param = transform->GetParam<ParamMatrix4>("localMatrix");
- param->set_value(Matrix4::identity());
- serializer_.SerializeParam(param);
- EXPECT_EQ("{\"value\":[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]}",
- output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeClassOfLateAddedParams) {
- Transform* transform = pack_->Create<Transform>();
- ParamInteger* param = transform->CreateParam<ParamInteger>("param");
- param->set_value(7);
- serializer_.SerializeParam(param);
- EXPECT_EQ("{\"class\":\"" O3D_NAMESPACE ".ParamInteger\",\"value\":7}",
- output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeIdOfOutputParams) {
- Transform* transform = pack_->Create<Transform>();
- ParamInteger* param = transform->CreateParam<ParamInteger>("param");
- param->set_value(7);
- ParamInteger* other_param = transform->CreateParam<ParamInteger>(
- "other_param");
- other_param->Bind(param);
- serializer_.SerializeParam(param);
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "{\"class\":\"" O3D_NAMESPACE
- ".ParamInteger\",\"id\":%d,\"value\":7}",
- param->id());
-
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeInputIdOfBoundParams) {
- Transform* transform = pack_->Create<Transform>();
- ParamInteger* param = transform->CreateParam<ParamInteger>("param");
- ParamInteger* other_param = transform->CreateParam<ParamInteger>(
- "other_param");
- param->Bind(other_param);
- serializer_.SerializeParam(param);
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "{\"class\":\"" O3D_NAMESPACE ".ParamInteger\",\"bind\":%d}",
- other_param->id());
-
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesPointer) {
- Transform* transform = pack_->Create<Transform>();
- Serialize(&json_writer_, transform);
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted("{\"ref\":%d}", transform->id());
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeNullPointerToNullKeyword) {
- Serialize(&json_writer_, static_cast<ObjectBase*>(NULL));
- EXPECT_EQ("null", output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesFloat) {
- Serialize(&json_writer_, 1.25f);
- EXPECT_EQ("1.25", output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesFloat2) {
- Serialize(&json_writer_, Float2(1.25f, 2.5f));
- EXPECT_EQ("[1.25,2.5]", output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesFloat3) {
- Serialize(&json_writer_, Float3(1.25f, 2.5f, 5.0f));
- EXPECT_EQ("[1.25,2.5,5]", output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesFloat4) {
- Serialize(&json_writer_, Float4(1.25f, 2.5f, 5.0f, 10.0f));
- EXPECT_EQ("[1.25,2.5,5,10]", output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesInteger) {
- Serialize(&json_writer_, 7);
- EXPECT_EQ("7", output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesBoolean) {
- Serialize(&json_writer_, false);
- EXPECT_EQ("false", output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesString) {
- Serialize(&json_writer_, String("hello"));
- EXPECT_EQ("\"hello\"", output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesMatrix4) {
- Serialize(&json_writer_, Matrix4::identity());
- EXPECT_EQ("[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]", output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesValidBoundingBox) {
- BoundingBox bounding_box(Point3(-1.0f, -2.0f, -3.0f),
- Point3(1.0f, 2.0f, 3.0f));
- Serialize(&json_writer_, bounding_box);
- EXPECT_EQ("[[-1,-2,-3],[1,2,3]]", output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesInvalidBoundingBox) {
- BoundingBox bounding_box;
- Serialize(&json_writer_, bounding_box);
- EXPECT_EQ("[]", output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeStreamProperties) {
- VertexBuffer* buffer = pack_->Create<VertexBuffer>();
- StreamBank* streamBank = pack_->Create<StreamBank>();
- Field* field = buffer->CreateField(FloatField::GetApparentClass(), 3);
- streamBank->SetVertexStream(Stream::NORMAL, 9, field, 1);
- const Stream* stream = streamBank->GetVertexStream(Stream::NORMAL, 9);
- Serialize(&json_writer_, *stream);
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "{\"field\":%d,\"startIndex\":1,"
- "\"semantic\":2,\"semanticIndex\":9}",
- field->id());
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeCurveProperties) {
- Curve* curve = pack_->Create<Curve>();
- curve->set_pre_infinity(Curve::CONSTANT);
- curve->set_post_infinity(Curve::LINEAR);
- curve->set_use_cache(true);
- curve->SetSampleRate(0.1f);
-
- serializer_.SerializeSection(curve, Serializer::PROPERTIES_SECTION);
-
- EXPECT_EQ(
- "\"preInfinity\":0,"
- "\"postInfinity\":1,"
- "\"useCache\":true,"
- "\"sampleRate\":0.1",
- output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeCurveCustomSection) {
- // The purpose of this buffer is just to offset the following one in the
- // binary file.
- Curve* firstCurve = pack_->Create<Curve>();
- firstCurve->Create<StepCurveKey>();
-
- Curve* curve = pack_->Create<Curve>();
-
- StepCurveKey* step_key = curve->Create<StepCurveKey>();
- step_key->SetInput(1);
- step_key->SetOutput(2);
-
- LinearCurveKey* linear_key = curve->Create<LinearCurveKey>();
- linear_key->SetInput(3);
- linear_key->SetOutput(4);
-
- BezierCurveKey* bezier_key = curve->Create<BezierCurveKey>();
- bezier_key->SetInput(5);
- bezier_key->SetInTangent(Float2(6, 7));
- bezier_key->SetOutput(8);
- bezier_key->SetOutTangent(Float2(9, 10));
-
- serializer_.SerializePackBinary(pack_);
- serializer_.SerializeSection(curve, Serializer::CUSTOM_SECTION);
-
- // Make sure binaryRange is correct
- MemoryBuffer<uint8> contents1;
- MemoryBuffer<uint8> contents2;
- SerializeCurve(*firstCurve, &contents1);
- SerializeCurve(*curve, &contents2);
- size_t length1 = contents1.GetLength();
- size_t length2 = contents2.GetLength();
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"binaryRange\":[%d,%d]",
- length1,
- length1 + length2);
-
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeCurveCustomSectionNotBinary) {
- Serializer serializer(
- g_service_locator, &json_writer_, &archive_generator_,
- Serializer::Options(Serializer::Options::kBinaryOutputOff));
- Curve* curve = pack_->Create<Curve>();
-
- StepCurveKey* step_key = curve->Create<StepCurveKey>();
- step_key->SetInput(1);
- step_key->SetOutput(2);
-
- LinearCurveKey* linear_key = curve->Create<LinearCurveKey>();
- linear_key->SetInput(3);
- linear_key->SetOutput(4);
-
- BezierCurveKey* bezier_key = curve->Create<BezierCurveKey>();
- bezier_key->SetInput(5);
- bezier_key->SetInTangent(Float2(6, 7));
- bezier_key->SetOutput(8);
- bezier_key->SetOutTangent(Float2(9, 10));
-
- serializer.SerializePackBinary(pack_);
- serializer.SerializeSection(curve, Serializer::CUSTOM_SECTION);
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"keys\":[[1,1,2],[2,3,4],[3,5,8,6,7,9,10]]");
-
- EXPECT_EQ(expected.ToString(), output_.ToString());
- EXPECT_TRUE(archive_generator_.add_file_records_.empty());
-}
-
-TEST_F(SerializerTest, ShouldSerializeCurveKeysToSingleBinaryFile) {
- // The purpose of this buffer is just to offset the following one in the
- // binary file.
- Curve* curve1 = pack_->Create<Curve>();
- StepCurveKey* step_key = curve1->Create<StepCurveKey>();
- step_key->SetInput(1);
- step_key->SetOutput(2);
-
- Curve* curve2 = pack_->Create<Curve>();
- LinearCurveKey* linear_key = curve2->Create<LinearCurveKey>();
- linear_key->SetInput(3);
- linear_key->SetOutput(4);
-
- serializer_.SerializePack(pack_);
- EXPECT_EQ(1U, archive_generator_.add_file_records_.size());
- const AddFileRecord& record = archive_generator_.add_file_records_[0];
- EXPECT_EQ("curve-keys.bin", record.file_name_);
-
- EXPECT_FALSE(archive_generator_.closed_);
-
- // Test that the data matches what we get if we call SerializeCurve directly
- // The file should contain the concatenated contents of both curves
- MemoryBuffer<uint8> contents1;
- MemoryBuffer<uint8> contents2;
- SerializeCurve(*curve1, &contents1);
- SerializeCurve(*curve2, &contents2);
- size_t length1 = contents1.GetLength();
- size_t length2 = contents2.GetLength();
- size_t total_length = length1 + length2;
- ASSERT_EQ(total_length, record.file_size_);
- ASSERT_EQ(total_length, record.file_contents_.size());
-
- uint8 *p1 = contents1;
- uint8 *p2 = contents2;
- const uint8* data = &record.file_contents_[0];
-
- // Validate that first part of file data matches curve1 serialization
- // and that second part matches curve2...
- EXPECT_EQ(0, memcmp(p1, data, length1));
- EXPECT_EQ(0, memcmp(p2, data + length1, length2));
-}
-
-TEST_F(SerializerTest, ShouldSerializeNoCurvesIfCustomSectionIfNoKeys) {
- Curve* curve = pack_->Create<Curve>();
- serializer_.SerializeSection(curve, Serializer::CUSTOM_SECTION);
- EXPECT_EQ("\"binaryRange\":[0,0]", output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesIndexBuffer) {
- // The purpose of this buffer is just to offset the following one in the
- // binary file.
- Buffer* firstBuffer = pack_->Create<IndexBuffer>();
- firstBuffer->AllocateElements(1);
-
- Buffer* buffer = pack_->Create<IndexBuffer>();
- buffer->AllocateElements(2);
- {
- BufferLockHelper locker(buffer);
- uint32* data = locker.GetDataAs<uint32>(Buffer::WRITE_ONLY);
- data[0] = 3;
- data[1] = 7;
- }
-
- serializer_.SerializePackBinary(pack_);
- serializer_.SerializeSection(buffer, Serializer::CUSTOM_SECTION);
-
- // Make sure binaryRange is correct
- MemoryBuffer<uint8> contents1;
- MemoryBuffer<uint8> contents2;
- SerializeBuffer(*firstBuffer, &contents1);
- SerializeBuffer(*buffer, &contents2);
- size_t length1 = contents1.GetLength();
- size_t length2 = contents2.GetLength();
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"fields\":[%d],"
- "\"binaryRange\":[%d,%d]",
- buffer->fields()[0]->id(),
- length1,
- length1 + length2);
-
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesAllIndexBufferBinaryToSingleFileInArchive) {
- Buffer* buffer1 = pack_->Create<IndexBuffer>();
- buffer1->AllocateElements(2);
- {
- BufferLockHelper locker(buffer1);
- uint32* data = locker.GetDataAs<uint32>(Buffer::WRITE_ONLY);
- data[0] = 1;
- data[1] = 2;
- }
-
- Buffer* buffer2 = pack_->Create<IndexBuffer>();
- buffer2->AllocateElements(1);
- {
- BufferLockHelper locker(buffer2);
- uint32* data = locker.GetDataAs<uint32>(Buffer::WRITE_ONLY);
- data[0] = 3;
- }
-
- serializer_.SerializePack(pack_);
- EXPECT_EQ(1U, archive_generator_.add_file_records_.size());
- const AddFileRecord& record = archive_generator_.add_file_records_[0];
- EXPECT_EQ("index-buffers.bin", record.file_name_);
-
- EXPECT_FALSE(archive_generator_.closed_);
-
- // Test that the data matches what we get if we call SerializeBuffer directly
- // The file should contain the concatenated contents of both buffers
- MemoryBuffer<uint8> contents1;
- MemoryBuffer<uint8> contents2;
- SerializeBuffer(*buffer1, &contents1);
- SerializeBuffer(*buffer2, &contents2);
- size_t length1 = contents1.GetLength();
- size_t length2 = contents2.GetLength();
- size_t total_length = length1 + length2;
- ASSERT_EQ(total_length, record.file_size_);
- ASSERT_EQ(total_length, record.file_contents_.size());
-
- uint8 *p1 = contents1;
- uint8 *p2 = contents2;
- const uint8* data = &record.file_contents_[0];
-
- // Validate that first part of file data matches buffer1 serialization
- // and that second part matches buffer2...
- EXPECT_EQ(0, memcmp(p1, data, length1));
- EXPECT_EQ(0, memcmp(p2, data + length1, length2));
-}
-
-namespace {
-class FakeNamedObject : public NamedObject {
- public:
- explicit FakeNamedObject(ServiceLocator* service_locator)
- : NamedObject(service_locator) {}
-};
-}
-
-TEST_F(SerializerTest, ShouldSerializeNamedObjectProperties) {
- FakeNamedObject named_object(g_service_locator);
- named_object.set_name("ObjectName");
- serializer_.SerializeSection(&named_object, Serializer::PROPERTIES_SECTION);
- EXPECT_EQ("\"name\":\"ObjectName\"", output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeNoNameForNamelessNamedObjectProperties) {
- FakeNamedObject named_object(g_service_locator);
- serializer_.SerializeSection(&named_object, Serializer::PROPERTIES_SECTION);
- EXPECT_EQ("", output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeIdPropertiesAndCustomSections) {
- Curve* curve = pack_->Create<Curve>();
- curve->set_pre_infinity(Curve::CONSTANT);
- curve->set_post_infinity(Curve::LINEAR);
- curve->set_use_cache(true);
- curve->SetSampleRate(0.1f);
-
- serializer_.SerializeObject(curve);
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"id\":%d,"
- "\"properties\":{"
- "\"preInfinity\":0,"
- "\"postInfinity\":1,"
- "\"useCache\":true,"
- "\"sampleRate\":0.1"
- "},"
- "\"custom\":{"
- "\"binaryRange\":[0,0]"
- "}",
- curve->id());
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-namespace {
-class FakeObjectBase : public ObjectBase {
- public:
- explicit FakeObjectBase(ServiceLocator* service_locator)
- : ObjectBase(service_locator) {
- }
-};
-}
-
-TEST_F(SerializerTest,
- ShouldNotSerializePropertiesAndCustomSectionsIfTheyAreNotUsed) {
- FakeObjectBase object(g_service_locator);
- serializer_.SerializeObject(&object);
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"id\":%d",
- object.id());
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesEmptyPack) {
- pack_->set_name("MyPack");
-
- Transform* root = pack_->Create<Transform>();
- root->set_name(String(Serializer::ROOT_PREFIX) + String("root"));
-
- serializer_.SerializePack(pack_);
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "{"
- "\"version\":%d,"
- "\"o3d_rootObject_root\":%d,"
- "\"objects\":{}"
- "}",
- kSerializerVersion,
- root->id());
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesObjectsInPackExceptRootGroupedByClass) {
- FunctionEval* object1 = pack_->Create<FunctionEval>();
- object1->set_name("Object1");
-
- FunctionEval* object2 = pack_->Create<FunctionEval>();
- object2->set_name("Object2");
-
- Transform* root = pack_->Create<Transform>();
- root->set_name(String(Serializer::ROOT_PREFIX) + String("root"));
-
- serializer_.SerializePack(pack_);
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "{"
- "\"version\":%d,"
- "\"o3d_rootObject_root\":%d,"
- "\"objects\":{"
- "\"" O3D_NAMESPACE ".FunctionEval\":["
- "{"
- "\"id\":%d,"
- "\"properties\":{"
- "\"name\":\"Object1\""
- "},"
- "\"params\":{"
- "\"o3d.functionObject\":{\"value\":null},"
- "\"o3d.input\":{\"value\":0}"
- "}"
- "},"
- "{"
- "\"id\":%d,"
- "\"properties\":{"
- "\"name\":\"Object2\""
- "},"
- "\"params\":{"
- "\"o3d.functionObject\":{\"value\":null},"
- "\"o3d.input\":{\"value\":0}"
- "}"
- "}"
- "]"
- "}"
- "}",
- kSerializerVersion,
- root->id(),
- object1->id(),
- object2->id());
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesNonDynamicParams) {
- Matrix4Translation* translation = pack_->Create<Matrix4Translation>();
- translation->set_input_matrix(Matrix4::identity());
- translation->set_translation(Float3(1, 2, 3));
-
- serializer_.SerializeObject(translation);
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"id\":%d,"
- "\"properties\":{"
- "},"
- "\"params\":{"
- "\"o3d.inputMatrix\":{"
- "\"value\":[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]},"
- "\"o3d.translation\":{\"value\":[1,2,3]}"
- "}",
- translation->id());
-
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesDynamicParamsIfTheyAreOutputs) {
- Matrix4Translation* translation = pack_->Create<Matrix4Translation>();
- Param* input_matrix = translation->GetUntypedParam(
- Matrix4Translation::kInputMatrixParamName);
- Param* output_matrix = translation->GetUntypedParam(
- Matrix4Translation::kOutputMatrixParamName);
- input_matrix->Bind(output_matrix);
-
- serializer_.SerializeObject(translation);
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"id\":%d,"
- "\"properties\":{"
- "},"
- "\"params\":{"
- "\"o3d.inputMatrix\":{\"bind\":%d},"
- "\"o3d.outputMatrix\":{\"id\":%d},"
- "\"o3d.translation\":{\"value\":[0,0,0]}"
- "}",
- translation->id(),
- output_matrix->id(),
- output_matrix->id());
-
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesParamArray) {
- ParamArray* param_array = pack_->Create<ParamArray>();
- param_array->CreateParam<ParamInteger>(0)->set_value(1);
- param_array->CreateParam<ParamInteger>(1)->set_value(2);
- serializer_.SerializeObject(param_array);
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"id\":%d,"
- "\"properties\":{},"
- "\"params\":[{\"class\":\"" O3D_NAMESPACE
- ".ParamInteger\",\"value\":1},"
- "{\"class\":\"" O3D_NAMESPACE
- ".ParamInteger\",\"value\":2}]",
- param_array->id());
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializePrimitiveProperties) {
- Primitive* primitive = pack_->Create<Primitive>();
-
- Shape* shape = pack_->Create<Shape>();
- primitive->SetOwner(shape);
-
- IndexBuffer* index_buffer = pack_->Create<IndexBuffer>();
- primitive->set_index_buffer(index_buffer);
-
- primitive->set_start_index(4);
- primitive->set_primitive_type(Primitive::LINELIST);
- primitive->set_number_vertices(8);
- primitive->set_number_primitives(9);
-
- serializer_.SerializeSection(primitive, Serializer::PROPERTIES_SECTION);
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"owner\":{\"ref\":%d},"
- "\"numberVertices\":8,"
- "\"numberPrimitives\":9,"
- "\"primitiveType\":2,"
- "\"indexBuffer\":{\"ref\":%d},"
- "\"startIndex\":4",
- shape->id(),
- index_buffer->id());
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeShapeProperties) {
- Shape* shape = pack_->Create<Shape>();
-
- Element* element1 = pack_->Create<Primitive>();
- shape->AddElement(element1);
-
- Element* element2 = pack_->Create<Primitive>();
- shape->AddElement(element2);
-
- serializer_.SerializeSection(shape, Serializer::PROPERTIES_SECTION);
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"elements\":[{\"ref\":%d},{\"ref\":%d}]",
- element1->id(),
- element2->id());
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeSkinProperties) {
- Skin* skin = pack_->Create<Skin>();
- skin->SetInverseBindPoseMatrix(0, Matrix4::identity());
-
- serializer_.SerializeSection(skin, Serializer::PROPERTIES_SECTION);
-
- EXPECT_EQ(
- "\"inverseBindPoseMatrices\":[[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]]",
- output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeSkinPropertiesNotBinary) {
- Serializer serializer(
- g_service_locator, &json_writer_, &archive_generator_,
- Serializer::Options(Serializer::Options::kBinaryOutputOff));
- Skin* skin = pack_->Create<Skin>();
- skin->SetInverseBindPoseMatrix(0, Matrix4::identity());
- Skin::Influences influences(1);
- influences[0] = Skin::Influence(1, 2);
- skin->SetVertexInfluences(0, influences);
-
- serializer.SerializeSection(skin, Serializer::PROPERTIES_SECTION);
-
- EXPECT_EQ(
- "\"influences\":[[1,2]],"
- "\"inverseBindPoseMatrices\":"
- "[[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]]",
- output_.ToString());
- EXPECT_TRUE(archive_generator_.add_file_records_.empty());
-}
-
-TEST_F(SerializerTest, ShouldSerializeSkinCustomSection) {
- Skin* skin1 = pack_->Create<Skin>();
- Skin::Influences influences(1);
- influences[0] = Skin::Influence(1, 2);
- skin1->SetVertexInfluences(0, influences);
-
- Skin* skin2 = pack_->Create<Skin>();
- influences[0] = Skin::Influence(3, 4);
- skin2->SetVertexInfluences(1, influences);
-
- serializer_.SerializePackBinary(pack_);
- serializer_.SerializeSection(skin2, Serializer::CUSTOM_SECTION);
-
- // Make sure binaryRange is correct
- MemoryBuffer<uint8> contents1;
- MemoryBuffer<uint8> contents2;
- SerializeSkin(*skin1, &contents1);
- SerializeSkin(*skin2, &contents2);
- size_t length1 = contents1.GetLength();
- size_t length2 = contents2.GetLength();
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"binaryRange\":[%d,%d]",
- length1,
- length1 + length2);
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeSkinToSingleBinaryFile) {
- Skin* skin1 = pack_->Create<Skin>();
- Skin::Influences influences(1);
- influences[0] = Skin::Influence(1, 2);
- skin1->SetVertexInfluences(0, influences);
- skin1->SetInverseBindPoseMatrix(0, Matrix4::identity());
-
- Skin* skin2 = pack_->Create<Skin>();
- influences[0] = Skin::Influence(3, 4);
- skin2->SetVertexInfluences(1, influences);
- skin2->SetInverseBindPoseMatrix(0, Matrix4::identity());
-
- serializer_.SerializePack(pack_);
- EXPECT_EQ(1U, archive_generator_.add_file_records_.size());
- const AddFileRecord& record = archive_generator_.add_file_records_[0];
- EXPECT_EQ("skins.bin", record.file_name_);
-
- EXPECT_FALSE(archive_generator_.closed_);
-
- // Test that the data matches what we get if we call SerializeSkin directly
- // The file should contain the concatenated contents of both skins
- MemoryBuffer<uint8> contents1;
- MemoryBuffer<uint8> contents2;
- SerializeSkin(*skin1, &contents1);
- SerializeSkin(*skin2, &contents2);
- size_t length1 = contents1.GetLength();
- size_t length2 = contents2.GetLength();
- size_t total_length = length1 + length2;
- ASSERT_EQ(total_length, record.file_size_);
- ASSERT_EQ(total_length, record.file_contents_.size());
-
- uint8 *p1 = contents1;
- uint8 *p2 = contents2;
- const uint8* data = &record.file_contents_[0];
-
- // Validate that first part of file data matches skin1 serialization
- // and that second part matches skin2...
- EXPECT_EQ(0, memcmp(p1, data, length1));
- EXPECT_EQ(0, memcmp(p2, data + length1, length2));
-}
-
-TEST_F(SerializerTest, ShouldSerializeSkinEval) {
- SkinEval* skin_eval = pack_->Create<SkinEval>();
- SourceBuffer* buffer1 = pack_->Create<SourceBuffer>();
- SourceBuffer* buffer2 = pack_->Create<SourceBuffer>();
- Field* field1 = buffer1->CreateField(FloatField::GetApparentClass(), 3);
- Field* field2 = buffer2->CreateField(FloatField::GetApparentClass(), 3);
- skin_eval->SetVertexStream(Stream::POSITION,
- 0,
- field1,
- 0);
- skin_eval->SetVertexStream(Stream::NORMAL,
- 1,
- field2,
- 0);
-
- serializer_.SerializeSection(skin_eval, Serializer::CUSTOM_SECTION);
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"vertexStreams\":["
- "{"
- "\"stream\":{"
- "\"field\":%d,"
- "\"startIndex\":0,"
- "\"semantic\":1,"
- "\"semanticIndex\":0"
- "}"
- "},"
- "{"
- "\"stream\":{"
- "\"field\":%d,"
- "\"startIndex\":0,"
- "\"semantic\":2,"
- "\"semanticIndex\":1"
- "}"
- "}"
- "]",
- field1->id(),
- field2->id());
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeBoundSkinEval) {
- SkinEval* skin_eval1 = pack_->Create<SkinEval>();
- SourceBuffer* buffer1 = pack_->Create<SourceBuffer>();
- Field* field1 = buffer1->CreateField(FloatField::GetApparentClass(), 3);
- skin_eval1->SetVertexStream(Stream::POSITION,
- 0,
- field1,
- 0);
-
- SkinEval* skin_eval2 = pack_->Create<SkinEval>();
- SourceBuffer* buffer2 = pack_->Create<SourceBuffer>();
- Field* field2 = buffer2->CreateField(FloatField::GetApparentClass(), 3);
- skin_eval2->SetVertexStream(Stream::POSITION,
- 0,
- field2,
- 0);
-
- skin_eval1->BindStream(skin_eval2, Stream::POSITION, 0);
- ParamVertexBufferStream* param = skin_eval2->GetVertexStreamParam(
- Stream::POSITION, 0);
- EXPECT_TRUE(param != NULL);
-
- serializer_.SerializeSection(skin_eval1, Serializer::CUSTOM_SECTION);
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"vertexStreams\":["
- "{"
- "\"stream\":{"
- "\"field\":%d,"
- "\"startIndex\":0,"
- "\"semantic\":1,"
- "\"semanticIndex\":0"
- "},"
- "\"bind\":%d"
- "}"
- "]",
- field1->id(),
- skin_eval2->id());
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeStreamBank) {
- StreamBank* stream_bank = pack_->Create<StreamBank>();
- VertexBuffer* vertex_buffer_1 = pack_->Create<VertexBuffer>();
- Field* field_1 = vertex_buffer_1->CreateField(FloatField::GetApparentClass(),
- 3);
- VertexBuffer* vertex_buffer_2 = pack_->Create<VertexBuffer>();
- EXPECT_TRUE(vertex_buffer_2 != NULL);
-
- Field* field_2 = vertex_buffer_1->CreateField(FloatField::GetApparentClass(),
- 3);
- stream_bank->SetVertexStream(Stream::POSITION,
- 0,
- field_1,
- 0);
- stream_bank->SetVertexStream(Stream::NORMAL,
- 1,
- field_2,
- 0);
-
- serializer_.SerializeSection(stream_bank, Serializer::CUSTOM_SECTION);
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"vertexStreams\":["
- "{"
- "\"stream\":{"
- "\"field\":%d,"
- "\"startIndex\":0,"
- "\"semantic\":1,"
- "\"semanticIndex\":0"
- "}"
- "},"
- "{"
- "\"stream\":{"
- "\"field\":%d,"
- "\"startIndex\":0,"
- "\"semantic\":2,"
- "\"semanticIndex\":1"
- "}"
- "}"
- "]",
- field_1->id(),
- field_2->id());
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeBoundStreamBank) {
- SkinEval* skin_eval = pack_->Create<SkinEval>();
- SourceBuffer* source_buffer = pack_->Create<SourceBuffer>();
- Field* source_field = source_buffer->CreateField(
- FloatField::GetApparentClass(), 3);
- skin_eval->SetVertexStream(Stream::POSITION,
- 0,
- source_field,
- 0);
-
- StreamBank* stream_bank = pack_->Create<StreamBank>();
- VertexBuffer* vertex_buffer = pack_->Create<VertexBuffer>();
- Field* vertex_field = vertex_buffer->CreateField(
- FloatField::GetApparentClass(), 3);
- stream_bank->SetVertexStream(Stream::POSITION,
- 0,
- vertex_field,
- 0);
- stream_bank->BindStream(skin_eval, Stream::POSITION, 0);
-
- serializer_.SerializeSection(stream_bank, Serializer::CUSTOM_SECTION);
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"vertexStreams\":["
- "{"
- "\"stream\":{"
- "\"field\":%d,"
- "\"startIndex\":0,"
- "\"semantic\":1,"
- "\"semanticIndex\":0"
- "},"
- "\"bind\":%d"
- "}"
- "]",
- vertex_field->id(),
- skin_eval->id());
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeTexture2DCustomnSection) {
- Texture* texture = pack_->CreateTexture2D(256, 256, Texture::ARGB8,
- 2, false);
-
- serializer_.SerializeSection(texture, Serializer::CUSTOM_SECTION);
-
- EXPECT_EQ(
- "\"width\":256,"
- "\"height\":256,"
- "\"format\":2,"
- "\"levels\":2,"
- "\"renderSurfacesEnabled\":false",
- output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeTextureCUBECustomnSection) {
- Texture* texture = pack_->CreateTextureCUBE(256, Texture::ARGB8,
- 2, false);
-
- serializer_.SerializeSection(texture, Serializer::CUSTOM_SECTION);
-
- EXPECT_EQ(
- "\"edgeLength\":256,"
- "\"format\":2,"
- "\"levels\":2,"
- "\"renderSurfacesEnabled\":false",
- output_.ToString());
-}
-
-TEST_F(SerializerTest, ShouldSerializeTransformProperties) {
- Transform* transform = pack_->Create<Transform>();
- Transform* transform2 = pack_->Create<Transform>();
- ShapeArray shapes;
- Shape* shape1 = pack_->Create<Shape>();
- shapes.push_back(Shape::Ref(shape1));
- Shape* shape2 = pack_->Create<Shape>();
- shapes.push_back(Shape::Ref(shape2));
- transform->SetShapes(shapes);
- transform->SetParent(transform2);
-
- serializer_.SerializeSection(transform, Serializer::PROPERTIES_SECTION);
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"shapes\":[{\"ref\":%d},{\"ref\":%d}],"
- "\"parent\":{\"ref\":%d}",
- shape1->id(),
- shape2->id(),
- transform2->id());
-
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesVertexBuffer) {
- // This buffer exists only to offset the second buffer in the buffer binary
- // file.
- Buffer* firstBuffer = pack_->Create<VertexBuffer>();
- firstBuffer->CreateField(FloatField::GetApparentClass(), 1);
- firstBuffer->AllocateElements(1);
-
- Buffer* buffer = pack_->Create<VertexBuffer>();
- Field* field = buffer->CreateField(FloatField::GetApparentClass(), 1);
- buffer->AllocateElements(2);
- {
- BufferLockHelper locker(buffer);
- float* data = locker.GetDataAs<float>(Buffer::WRITE_ONLY);
- data[0] = 1.25f;
- data[1] = -3.0f;
- }
-
- serializer_.SerializePackBinary(pack_);
- serializer_.SerializeSection(buffer, Serializer::CUSTOM_SECTION);
-
- // Make sure binaryRange is correct
- MemoryBuffer<uint8> contents1;
- MemoryBuffer<uint8> contents2;
- SerializeBuffer(*firstBuffer, &contents1);
- SerializeBuffer(*buffer, &contents2);
- size_t length1 = contents1.GetLength();
- size_t length2 = contents2.GetLength();
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"fields\":[%d],"
- "\"binaryRange\":[%d,%d]",
- field->id(), length1, length1 + length2);
-
- EXPECT_EQ(expected.ToString(), output_.ToString());
-}
-
-TEST_F(SerializerTest, SerializesVertexBufferNotBinary) {
- Serializer serializer(
- g_service_locator, &json_writer_, &archive_generator_,
- Serializer::Options(Serializer::Options::kBinaryOutputOff));
- Buffer* buffer = pack_->Create<VertexBuffer>();
- Field* field = buffer->CreateField(FloatField::GetApparentClass(), 1);
- buffer->AllocateElements(2);
- {
- BufferLockHelper locker(buffer);
- float* data = locker.GetDataAs<float>(Buffer::WRITE_ONLY);
- data[0] = 1.25f;
- data[1] = -3.0f;
- }
-
- serializer.SerializePackBinary(pack_);
- serializer.SerializeSection(buffer, Serializer::CUSTOM_SECTION);
-
- StringWriter expected(StringWriter::CR_LF);
- expected.WriteFormatted(
- "\"fieldData\":[{"
- "\"id\":%d,"
- "\"type\":\"o3d.FloatField\","
- "\"numComponents\":1,\"data\":[1.25,-3]}]",
- field->id(), field->id());
-
- EXPECT_EQ(expected.ToString(), output_.ToString());
- EXPECT_TRUE(archive_generator_.add_file_records_.empty());
-}
-
-TEST_F(SerializerTest,
- SerializesAllVertexBufferBinaryToSingleFileInArchive) {
- Buffer* buffer1 = pack_->Create<VertexBuffer>();
- buffer1->CreateField(FloatField::GetApparentClass(), 1);
- buffer1->AllocateElements(2);
- {
- BufferLockHelper locker(buffer1);
- float* data = locker.GetDataAs<float>(Buffer::WRITE_ONLY);
- data[0] = 1;
- data[1] = 2;
- }
-
- Buffer* buffer2 = pack_->Create<VertexBuffer>();
- buffer2->CreateField(FloatField::GetApparentClass(), 1);
- buffer2->AllocateElements(1);
- {
- BufferLockHelper locker(buffer2);
- float* data = locker.GetDataAs<float>(Buffer::WRITE_ONLY);
- data[0] = 3;
- }
-
- serializer_.SerializePack(pack_);
- EXPECT_EQ(1U, archive_generator_.add_file_records_.size());
- const AddFileRecord& record = archive_generator_.add_file_records_[0];
- EXPECT_EQ("vertex-buffers.bin", record.file_name_);
-
- EXPECT_FALSE(archive_generator_.closed_);
-
- // Test that the data matches what we get if we call SerializeBuffer directly
- // The file should contain the concatenated contents of both buffers
- MemoryBuffer<uint8> contents1;
- MemoryBuffer<uint8> contents2;
- SerializeBuffer(*buffer1, &contents1);
- SerializeBuffer(*buffer2, &contents2);
- size_t length1 = contents1.GetLength();
- size_t length2 = contents2.GetLength();
- size_t total_length = length1 + length2;
- ASSERT_EQ(total_length, record.file_size_);
- ASSERT_EQ(total_length, record.file_contents_.size());
-
- uint8 *p1 = contents1;
- uint8 *p2 = contents2;
- const uint8* data = &record.file_contents_[0];
-
- // Validate that first part of file data matches buffer1 serialization
- // and that second part matches buffer2...
- EXPECT_EQ(0, memcmp(p1, data, length1));
- EXPECT_EQ(0, memcmp(p2, data + length1, length2));
-}
-} // namespace o3d
diff --git a/o3d/serializer/cross/version.h b/o3d/serializer/cross/version.h
deleted file mode 100644
index 619ad3b..0000000
--- a/o3d/serializer/cross/version.h
+++ /dev/null
@@ -1,45 +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 must only contain the serializer version number. Modifying this
-// file causes the assets to be rebuilt. So you must modify this file by
-// incrementing the version number every time you make a change that changes
-// the serializer format.
-
-#ifndef O3D_SERIALIZER_CROSS_VERSION_H_
-#define O3D_SERIALIZER_CROSS_VERSION_H_
-
-namespace o3d {
-const int kSerializerVersion = 6;
-}
-
-#endif // O3D_SERIALIZER_CROSS_VERSION_H_
diff --git a/o3d/serializer/serializer.gyp b/o3d/serializer/serializer.gyp
deleted file mode 100644
index cc2fc02..0000000
--- a/o3d/serializer/serializer.gyp
+++ /dev/null
@@ -1,53 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- },
- 'includes': [
- '../build/common.gypi',
- ],
- 'target_defaults': {
- 'include_dirs': [
- '..',
- '../..',
- '../../<(gtestdir)',
- ],
- },
- 'targets': [
- {
- 'target_name': 'o3dSerializer',
- 'type': 'static_library',
- 'dependencies': [
- '../import/import.gyp:o3dSerializationObjects',
- ],
- 'sources': [
- 'cross/serializer.cc',
- 'cross/serializer.h',
- 'cross/serializer_binary.cc',
- 'cross/serializer_binary.h',
- 'cross/version.h',
- ],
- },
- {
- 'target_name': 'o3dSerializerTest',
- 'type': 'none',
- 'dependencies': [
- 'o3dSerializer',
- ],
- 'direct_dependent_settings': {
- 'sources': [
- 'cross/serializer_test.cc',
- ],
- },
- },
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/standalone/standalone.cc b/o3d/standalone/standalone.cc
deleted file mode 100644
index 2b6fc72..0000000
--- a/o3d/standalone/standalone.cc
+++ /dev/null
@@ -1,5 +0,0 @@
-#include <stdio.h>
-
-int main(int argc, const char** argv) {
- printf("Hello World\n");
-}
diff --git a/o3d/standalone/standalone.gyp b/o3d/standalone/standalone.gyp
deleted file mode 100644
index 2199fa9..0000000
--- a/o3d/standalone/standalone.gyp
+++ /dev/null
@@ -1,144 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- },
- 'includes': [
- '../build/common.gypi',
- ],
- 'target_defaults': {
- 'include_dirs': [
- '..',
- '../..',
- ],
- # TODO(rlp): remove this after fixing signed / unsigned issues in
- # command buffer code and tests.
- 'target_conditions': [
- ['OS == "mac"',
- {
- 'xcode_settings': {
- 'GCC_TREAT_WARNINGS_AS_ERRORS': 'NO'
- },
- },
- ],
- ],
- },
- 'targets': [
- {
- 'target_name': 'standalone',
- 'type': 'executable',
- 'dependencies': [
- '../../<(antlrdir)/antlr.gyp:antlr3c',
- '../../<(fcolladadir)/fcollada.gyp:fcollada',
- '../../<(jpegdir)/libjpeg.gyp:libjpeg',
- '../../<(pngdir)/libpng.gyp:libpng',
- '../../<(zlibdir)/zlib.gyp:zlib',
- '../../base/base.gyp:base',
- '../../skia/skia.gyp:skia',
- '../compiler/technique/technique.gyp:o3dTechnique',
- '../core/core.gyp:o3dCore',
- '../core/core.gyp:o3dCorePlatform',
- '../utils/utils.gyp:o3dUtils',
- ],
- 'sources': [
- 'standalone.cc',
- ],
- 'conditions' : [
- ['renderer == "gl"',
- {
- 'dependencies': [
- '../build/libs.gyp:cg_libs',
- '../build/libs.gyp:gl_libs',
- ],
- },
- ],
- ['renderer == "gles2"',
- {
- 'dependencies': [
- '../build/libs.gyp:gles2_libs',
- ],
- },
- ],
- ['OS == "mac"',
- {
- 'include_dirs': [
- '../../third_party/glew/files/include',
- ],
- 'link_settings': {
- 'libraries': [
- '$(SDKROOT)/System/Library/Frameworks/AGL.framework',
- '$(SDKROOT)/System/Library/Frameworks/Foundation.framework',
- '$(SDKROOT)/System/Library/Frameworks/GLUT.framework',
- '$(SDKROOT)/System/Library/Frameworks/OpenGL.framework',
- '../../third_party/cg/files/mac/Cg.framework',
- '../../third_party/glew/files/lib/libMacStaticGLEW.a',
- ],
- },
- },
- ],
- ['OS == "win"',
- {
- 'msvs_settings': {
- 'VCLinkerTool': {
- 'AdditionalDependencies': [
- 'rpcrt4.lib',
- '../../<(cgdir)/lib/cg.lib',
- '../../<(cgdir)/lib/cgGL.lib',
- ],
- # Set /SUBSYSTEM:WINDOWS for standalone.exe, since
- # it is a console app.
- 'SubSystem': '1',
- },
- },
- # We switch it to console post-build so that we have a
- # windows app that can output to the console and still
- # open windows.
- 'msvs_postbuild':
- 'editbin /SUBSYSTEM:CONSOLE $(OutDir)/$(TargetFileName)',
- },
- ],
- ['OS == "win" and renderer == "d3d9"',
- {
- 'msvs_system_include_dirs': [
- '"$(DXSDK_DIR)/Include"',
- ],
- 'link_settings': {
- 'libraries': [
- '"$(DXSDK_DIR)/Lib/x86/d3dx9.lib"',
- 'd3d9.lib',
- '"$(DXSDK_DIR)/Lib/x86/DxErr.lib"',
- ],
- },
- },
- ],
- ['OS == "win" and renderer == "gl"',
- {
- 'dependencies': [
- '../build/libs.gyp:gl_libs',
- ],
- },
- ],
- ['OS == "win" and renderer == "gles2"',
- {
- 'dependencies': [
- '../build/libs.gyp:gles2_libs',
- ],
- },
- ],
- ['OS == "linux"',
- {
- },
- ],
- ],
- },
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/statsreport/aggregator-mac.h b/o3d/statsreport/aggregator-mac.h
deleted file mode 100644
index 046e10f..0000000
--- a/o3d/statsreport/aggregator-mac.h
+++ /dev/null
@@ -1,77 +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.
- */
-
-
-// Mac aggregator, which aggregates counters to a keyvaluetable. It is the
-// interface to the keyvaluetable for all clients.
-
-#ifndef O3D_STATSREPORT_AGGREGATOR_MAC_H__
-#define O3D_STATSREPORT_AGGREGATOR_MAC_H__
-
-#include <Cocoa/Cocoa.h>
-
-#include <string>
-#include "statsreport/aggregator.h"
-#include "base/scoped_ptr.h"
-
-namespace stats_report {
-
-class Formatter;
-
-class MetricsAggregatorMac: public MetricsAggregator {
- public:
- // @param coll the metrics collection to aggregate, most usually this
- // is g_global_metrics.
- explicit MetricsAggregatorMac(const MetricCollection &coll);
- virtual ~MetricsAggregatorMac();
-
-
- protected:
- virtual bool StartAggregation();
- virtual void EndAggregation();
-
- virtual void Aggregate(CountMetric *metric);
- virtual void Aggregate(TimingMetric *metric);
- virtual void Aggregate(IntegerMetric *metric);
- virtual void Aggregate(BoolMetric *metric);
-
- private:
- NSAutoreleasePool *pool_;
- NSMutableDictionary *dict_;
- NSString *storePath_;
-
- DISALLOW_COPY_AND_ASSIGN(MetricsAggregatorMac);
-};
-
-} // namespace stats_report
-
-#endif // O3D_STATSREPORT_AGGREGATOR_MAC_H__
-
diff --git a/o3d/statsreport/aggregator-mac.mm b/o3d/statsreport/aggregator-mac.mm
deleted file mode 100644
index 8f212b6..0000000
--- a/o3d/statsreport/aggregator-mac.mm
+++ /dev/null
@@ -1,152 +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.
- */
-
-
-// Implementation of a Mac metrics aggregator.
-
-#include "aggregator-mac.h"
-#include "const-mac.h"
-#include "formatter.h"
-
-
-namespace stats_report {
-
-
-MetricsAggregatorMac::MetricsAggregatorMac(const MetricCollection &coll)
- : MetricsAggregator(coll),
- pool_(nil),
- dict_(nil) {
- storePath_ = O3DStatsPath();
-}
-
-MetricsAggregatorMac::~MetricsAggregatorMac() {
-}
-
-
-bool MetricsAggregatorMac::StartAggregation() {
- pool_ = [[NSAutoreleasePool alloc] init];
- dict_ = [NSMutableDictionary dictionaryWithContentsOfFile:storePath_];
- if (dict_ == nil)
- dict_ = [[[NSMutableDictionary alloc] init] autorelease];
-
- return true;
-}
-
-void MetricsAggregatorMac::EndAggregation() {
- [dict_ writeToFile:storePath_ atomically:YES];
- dict_ = nil; // it will get autoreleased when the pool dies
-
- [pool_ release];
- pool_ = nil;
-}
-
-void MetricsAggregatorMac::Aggregate(CountMetric *metric) {
- // do as little as possible if no value
- uint64 value = metric->Reset();
- if (0 == value)
- return;
-
- NSString *keyName = [NSString stringWithFormat:@"C_%s", metric->name()];
- NSNumber *previousValue = [dict_ objectForKey:keyName];
- if (previousValue == nil)
- previousValue = [NSNumber numberWithLongLong:0];
-
- NSNumber *newTotal =
- [NSNumber numberWithLongLong:value + [previousValue longLongValue]];
- [dict_ setObject:newTotal forKey:keyName];
-}
-
-
-static long long LLMin(long long a, long long b) {
- return a < b ? a : b;
-}
-
-static long long LLMax(long long a, long long b) {
- return a > b ? a : b;
-}
-
-void MetricsAggregatorMac::Aggregate(TimingMetric *metric) {
- // do as little as possible if no value
- TimingMetric::TimingData newValue = metric->Reset();
- if (0 == newValue.count)
- return;
-
- NSString *keyName = [NSString stringWithFormat:@"T_%s", metric->name()];
- NSArray *previousValue = [dict_ objectForKey:keyName];
- NSArray *newTotal = nil;
-
- if (previousValue == nil) {
- newTotal = [NSArray arrayWithObjects:
- [NSNumber numberWithInt:newValue.count],
- [NSNumber numberWithLongLong:newValue.sum],
- [NSNumber numberWithLongLong:newValue.minimum],
- [NSNumber numberWithLongLong:newValue.maximum],
- nil];
- } else {
- int previousCount = [[previousValue objectAtIndex:0] intValue];
- long long previousSum = [[previousValue objectAtIndex:1] longLongValue];
- long long previousMin = [[previousValue objectAtIndex:2] longLongValue];
- long long previousMax = [[previousValue objectAtIndex:3] longLongValue];
-
- newTotal =
- [NSArray arrayWithObjects:
- [NSNumber numberWithInt:newValue.count + previousCount],
- [NSNumber numberWithLongLong:newValue.sum + previousSum],
- [NSNumber numberWithLongLong:LLMin(newValue.minimum, previousMin)],
- [NSNumber numberWithLongLong:LLMax(newValue.maximum, previousMax)],
- nil];
- }
-
- [dict_ setObject:newTotal forKey:keyName];
-}
-
-void MetricsAggregatorMac::Aggregate(IntegerMetric *metric) {
- // do as little as possible if no value
- int64 value = metric->value(); // yes, we only have 63 positive bits here :(
- if (0 == value)
- return;
-
- NSString *keyName = [NSString stringWithFormat:@"I_%s", metric->name()];
- [dict_ setObject:[NSNumber numberWithLongLong:value] forKey:keyName];
-}
-
-void MetricsAggregatorMac::Aggregate(BoolMetric *metric) {
- // do as little as possible if no value
- int32 value = metric->Reset();
- if (BoolMetric::kBoolUnset == value)
- return;
-
- NSString *keyName = [NSString stringWithFormat:@"B_%s", metric->name()];
- [dict_ setObject:[NSNumber numberWithBool:(value != 0)] forKey:keyName];
-}
-
-} // namespace stats_report
diff --git a/o3d/statsreport/aggregator-posix-inl.h b/o3d/statsreport/aggregator-posix-inl.h
deleted file mode 100644
index e147bf6..0000000
--- a/o3d/statsreport/aggregator-posix-inl.h
+++ /dev/null
@@ -1,61 +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.
- */
-
-
-// Posix aggregator inlines.
-
-#ifndef O3D_STATSREPORT_AGGREGATOR_POSIX_INL_H__
-#define O3D_STATSREPORT_AGGREGATOR_POSIX_INL_H__
-
-#include <string>
-#include "aggregator-posix.h"
-
-namespace stats_report {
-
-template <typename ValueType>
-bool MetricsAggregatorPosix::GetValue(const string &key, ValueType *value) {
- StartAggregation();
- bool success = transaction_->Get(key, value);
- EndAggregation();
- return success;
-}
-
-template <typename ValueType>
-bool MetricsAggregatorPosix::SetValue(const string &key, ValueType value) {
- StartAggregation();
- bool success = transaction_->Put(key, value);
- EndAggregation();
- return success;
-}
-
-} // namespace stats_report
-
-#endif // O3D_STATSREPORT_AGGREGATOR_POSIX_INL_H__
diff --git a/o3d/statsreport/aggregator-posix.cc b/o3d/statsreport/aggregator-posix.cc
deleted file mode 100644
index 11e99fa..0000000
--- a/o3d/statsreport/aggregator-posix.cc
+++ /dev/null
@@ -1,193 +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.
- */
-
-
-// Implementation of a Posix metrics aggregator.
-
-#include "aggregator-posix.h"
-#include "const-posix.h"
-#include "formatter.h"
-#include "util/endian/endian.h"
-#include "statsreport/common/pathhelpers.h"
-
-namespace stats_report {
-
-MetricsAggregatorPosix::MetricsAggregatorPosix(const MetricCollection &coll) {
- key_value_table_.reset(new KeyValueTable(get_cache_dir() + "stats.sqlite3",
- "stats"));
-}
-
-MetricsAggregatorPosix::~MetricsAggregatorPosix() {
-}
-
-void MetricsAggregatorPosix::ResetMetrics() {
- StartAggregation();
- (void)transaction_->Clear();
- EndAggregation();
-}
-
-namespace {
-
-void AddMetric(const string& key,
- const ScopedStatement &statement,
- void *ref_con) {
- Formatter *formatter =
- static_cast<Formatter *>(ref_con);
-
- string original_key;
- scoped_ptr<MetricBase> metric;
-
- if (key.compare(0, kCountsKeyName.length(), kCountsKeyName) == 0) {
- int64 value;
- GetColumn(statement.get(), 0, &value);
- original_key = key.substr(kCountsKeyName.length());
- metric.reset(new CountMetric(original_key.c_str(), value));
- } else if (key.compare(0, kTimingsKeyName.length(), kTimingsKeyName) == 0) {
- std::vector<BYTE> value_bytes;
- TimingMetric::TimingData value;
- GetColumn(statement.get(), 0, &value_bytes);
- memcpy(&value, &value_bytes[0], value_bytes.size());
- value.count = gntohl(value.count);
- value.sum = gntohll(value.sum);
- value.minimum = gntohll(value.minimum);
- value.maximum = gntohll(value.maximum);
- metric.reset(new TimingMetric(original_key.c_str(), value));
- } else if (key.compare(0, kIntegersKeyName.length(), kIntegersKeyName) == 0) {
- int64 value;
- GetColumn(statement.get(), 0, &value);
- original_key = key.substr(kIntegersKeyName.length());
- metric.reset(new IntegerMetric(original_key.c_str(), value));
- } else if (key.compare(0, kBooleansKeyName.length(), kBooleansKeyName) == 0) {
- int32 value;
- GetColumn(statement.get(), 0, &value);
- original_key = key.substr(kBooleansKeyName.length());
- metric.reset(new BoolMetric(original_key.c_str(), value));
- }
-
- if (!original_key.empty())
- formatter->AddMetric(&*metric);
-}
-
-} // namespace
-
-void MetricsAggregatorPosix::FormatMetrics(Formatter *formatter) {
- StartAggregation();
- transaction_->Iterate(AddMetric, formatter);
- EndAggregation();
-}
-
-bool MetricsAggregatorPosix::StartAggregation() {
- transaction_.reset(new KeyValueTransaction(&*key_value_table_));
-
- return true;
-}
-
-void MetricsAggregatorPosix::EndAggregation() {
- transaction_.reset();
-}
-
-void MetricsAggregatorPosix::Aggregate(CountMetric *metric) {
- // do as little as possible if no value
- uint64 value = metric->Reset();
- if (0 == value)
- return;
-
- string name(metric->name());
- name.insert(0, kCountsKeyName);
- int64 reg_value = 0; // yes, we only have 63 positive bits here :(
- if (!transaction_->Get(name, &reg_value)) {
- // TODO: clean up??
- }
- reg_value += value;
-
- (void)transaction_->Put(name, reg_value);
-}
-
-void MetricsAggregatorPosix::Aggregate(TimingMetric *metric) {
- // do as little as possible if no value
- TimingMetric::TimingData value = metric->Reset();
- if (0 == value.count)
- return;
-
- string name(metric->name());
- name.insert(0, kTimingsKeyName);
- std::vector<BYTE> reg_value_bytes;
- TimingMetric::TimingData reg_value;
- if (!transaction_->Get(name, &reg_value_bytes)) {
- reg_value_bytes.resize(sizeof(reg_value));
- memcpy(&reg_value, &value, sizeof(value));
- } else {
- memcpy(&reg_value, &reg_value_bytes[0], reg_value_bytes.size());
- reg_value.count = gntohl(reg_value.count);
- reg_value.sum = gntohll(reg_value.sum);
- reg_value.minimum = gntohll(reg_value.minimum);
- reg_value.maximum = gntohll(reg_value.maximum);
-
- reg_value.count += value.count;
- reg_value.sum += value.sum;
- reg_value.minimum = std::min(reg_value.minimum, value.minimum);
- reg_value.maximum = std::max(reg_value.maximum, value.maximum);
- }
-
- reg_value.count = ghtonl(reg_value.count);
- reg_value.sum = ghtonll(reg_value.sum);
- reg_value.minimum = ghtonll(reg_value.minimum);
- reg_value.maximum = ghtonll(reg_value.maximum);
-
- memcpy(&reg_value_bytes[0], &reg_value, sizeof(reg_value));
- (void)transaction_->Put(name, reg_value_bytes);
-}
-
-void MetricsAggregatorPosix::Aggregate(IntegerMetric *metric) {
- // do as little as possible if no value
- int64 value = metric->value(); // yes, we only have 63 positive bits here :(
- if (0 == value)
- return;
-
- string name(metric->name());
- name.insert(0, kIntegersKeyName);
-
- (void)transaction_->Put(name, value);
-}
-
-void MetricsAggregatorPosix::Aggregate(BoolMetric *metric) {
- // do as little as possible if no value
- int32 value = metric->Reset();
- if (BoolMetric::kBoolUnset == value)
- return;
-
- string name(metric->name());
- name.insert(0, kBooleansKeyName);
-
- (void)transaction_->Put(name, value);
-}
-
-} // namespace stats_report
diff --git a/o3d/statsreport/aggregator-posix.h b/o3d/statsreport/aggregator-posix.h
deleted file mode 100644
index 10117a4..0000000
--- a/o3d/statsreport/aggregator-posix.h
+++ /dev/null
@@ -1,84 +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.
- */
-
-
-// Posix aggregator, which aggregates counters to a keyvaluetable. It is the
-// interface to the keyvaluetable for all clients.
-
-#ifndef O3D_STATSREPORT_AGGREGATOR_POSIX_H__
-#define O3D_STATSREPORT_AGGREGATOR_POSIX_H__
-
-#include <string>
-#include "aggregator.h"
-#include "base/scoped_ptr.h"
-#include "backend/keyvaluetable.h"
-
-namespace stats_report {
-
-class Formatter;
-
-class MetricsAggregatorPosix: public MetricsAggregator {
- public:
- // @param coll the metrics collection to aggregate, most usually this
- // is g_global_metrics.
- explicit MetricsAggregatorPosix(const MetricCollection &coll);
- ~MetricsAggregatorPosix();
-
- template <typename ValueType>
- bool GetValue(const string &key, ValueType *value);
- template <typename ValueType>
- bool SetValue(const string &key, ValueType value);
-
- void ResetMetrics();
- void FormatMetrics(Formatter *formatter);
-
- protected:
- virtual bool StartAggregation();
- virtual void EndAggregation();
-
- virtual void Aggregate(CountMetric *metric);
- virtual void Aggregate(TimingMetric *metric);
- virtual void Aggregate(IntegerMetric *metric);
- virtual void Aggregate(BoolMetric *metric);
-
- private:
- // The keyvaluetable
- scoped_ptr<KeyValueTable> key_value_table_;
-
- // The current transaction
- scoped_ptr<KeyValueTransaction> transaction_;
-
- DISALLOW_COPY_AND_ASSIGN(MetricsAggregatorPosix);
-};
-
-} // namespace stats_report
-
-#endif // O3D_STATSREPORT_AGGREGATOR_POSIX_H__
diff --git a/o3d/statsreport/aggregator-win32.cc b/o3d/statsreport/aggregator-win32.cc
deleted file mode 100644
index 2f5678b..0000000
--- a/o3d/statsreport/aggregator-win32.cc
+++ /dev/null
@@ -1,172 +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.
- */
-
-
-// Implementation of Win32 metrics aggregator.
-#include "aggregator-win32.h"
-#include "const-win32.h"
-#include "util-win32.h"
-
-namespace stats_report {
-
-MetricsAggregatorWin32::MetricsAggregatorWin32(const MetricCollection &coll,
- const wchar_t *key_name)
- : MetricsAggregator(coll),
- is_machine_(false) {
- DCHECK(NULL != key_name);
-
- key_name_.Format(kStatsKeyFormatString, key_name);
-}
-
-MetricsAggregatorWin32::MetricsAggregatorWin32(const MetricCollection &coll,
- const wchar_t *key_name,
- bool is_machine)
- : MetricsAggregator(coll),
- is_machine_(is_machine) {
- DCHECK(NULL != key_name);
-
- key_name_.Format(kStatsKeyFormatString, key_name);
-}
-
-MetricsAggregatorWin32::~MetricsAggregatorWin32() {
-}
-
-bool MetricsAggregatorWin32::StartAggregation() {
- DCHECK(NULL == key_.m_hKey);
-
- HKEY parent_key = is_machine_ ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
- LONG err = key_.Create(parent_key, key_name_);
- if (err != ERROR_SUCCESS)
- return false;
-
- return true;
-}
-
-void MetricsAggregatorWin32::EndAggregation() {
- count_key_.Close();
- timing_key_.Close();
- integer_key_.Close();
- bool_key_.Close();
-
- key_.Close();
-}
-
-bool MetricsAggregatorWin32::EnsureKey(const wchar_t *name, CRegKey *key) {
- if (NULL != key->m_hKey)
- return true;
-
- LONG err = key->Create(key_, name);
- if (ERROR_SUCCESS != err) {
- DCHECK(NULL == key->m_hKey);
- // TODO: log?
- return false;
- }
-
- return true;
-}
-
-void MetricsAggregatorWin32::Aggregate(CountMetric *metric) {
- DCHECK(NULL != metric);
-
- // do as little as possible if no value
- uint64 value = metric->Reset();
- if (0 == value)
- return;
-
- if (!EnsureKey(kCountsKeyName, &count_key_))
- return;
-
- CString name(metric->name());
- uint64 reg_value = 0;
- if (!GetData(&count_key_, name, &reg_value)) {
- // TODO: clean up??
- }
- reg_value += value;
-
- DWORD err = count_key_.SetBinaryValue(name, &reg_value, sizeof(reg_value));
-}
-
-void MetricsAggregatorWin32::Aggregate(TimingMetric *metric) {
- DCHECK(NULL != metric);
-
- // do as little as possible if no value
- TimingMetric::TimingData value = metric->Reset();
- if (0 == value.count)
- return;
-
- if (!EnsureKey(kTimingsKeyName, &timing_key_))
- return;
-
- CString name(metric->name());
- TimingMetric::TimingData reg_value;
- if (!GetData(&timing_key_, name, &reg_value)) {
- memcpy(&reg_value, &value, sizeof(value));
- } else {
- reg_value.count += value.count;
- reg_value.sum += value.sum;
- reg_value.minimum = std::min(reg_value.minimum, value.minimum);
- reg_value.maximum = std::max(reg_value.maximum, value.maximum);
- }
-
- DWORD err = timing_key_.SetBinaryValue(name, &reg_value, sizeof(reg_value));
-}
-
-void MetricsAggregatorWin32::Aggregate(IntegerMetric *metric) {
- DCHECK(NULL != metric);
-
- // do as little as possible if no value
- uint64 value = metric->value();
- if (0 == value)
- return;
-
- if (!EnsureKey(kIntegersKeyName, &integer_key_))
- return;
-
- DWORD err = integer_key_.SetBinaryValue(CString(metric->name()),
- &value, sizeof(value));
-}
-
-void MetricsAggregatorWin32::Aggregate(BoolMetric *metric) {
- DCHECK(NULL != metric);
-
- // do as little as possible if no value
- int32 value = metric->Reset();
- if (BoolMetric::kBoolUnset == value)
- return;
-
- if (!EnsureKey(kBooleansKeyName, &bool_key_))
- return;
-
- DWORD err = bool_key_.SetBinaryValue(CString(metric->name()),
- &value, sizeof(value));
-}
-
-} // namespace stats_report
diff --git a/o3d/statsreport/aggregator-win32.h b/o3d/statsreport/aggregator-win32.h
deleted file mode 100644
index 566de62..0000000
--- a/o3d/statsreport/aggregator-win32.h
+++ /dev/null
@@ -1,104 +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.
- */
-
-
-// Win32 aggregator, which aggregates counters to registry under a named
-// Mutex lock.
-#ifndef O3D_STATSREPORT_AGGREGATOR_WIN32_H__
-#define O3D_STATSREPORT_AGGREGATOR_WIN32_H__
-
-#include "aggregator.h"
-#include <atlbase.h>
-#include <atlstr.h>
-
-namespace stats_report {
-
-class MetricsAggregatorWin32: public MetricsAggregator {
- public:
- // @param coll the metrics collection to aggregate, most usually this
- // is g_global_metrics.
- // @param app_name name of the subkey under HKCU\Software\Google we
- // aggregate to. Should be or encode the application name for
- // transparency, e.g. "Scour", or "Gears".
- MetricsAggregatorWin32(const MetricCollection &coll,
- const wchar_t *app_name);
-
- // @param is_machine specifies the registry hive where the stats are
- // aggregated to.
- MetricsAggregatorWin32(const MetricCollection &coll,
- const wchar_t *app_name,
- bool is_machine);
- virtual ~MetricsAggregatorWin32();
-
- protected:
- virtual bool StartAggregation();
- virtual void EndAggregation();
-
- virtual void Aggregate(CountMetric *metric);
- virtual void Aggregate(TimingMetric *metric);
- virtual void Aggregate(IntegerMetric *metric);
- virtual void Aggregate(BoolMetric *metric);
- private:
- enum {
- // Max length of time we wait for the mutex on StartAggregation.
- kMaxMutexWaitMs = 1000, // 1 second for now
- };
-
- // Ensures that *key is open, opening it if it's NULL
- // @return true on success, false on failure to open key
- bool EnsureKey(const wchar_t *name, CRegKey *key);
-
- // Mutex name for locking access to key
- CString mutex_name_;
-
- // Subkey name, as per constructor docs
- CString key_name_;
-
- // Handle to our subkey under HKCU\Software\Google
- CRegKey key_;
-
- // Subkeys under the above
- // @{
- CRegKey count_key_;
- CRegKey timing_key_;
- CRegKey integer_key_;
- CRegKey bool_key_;
- // @}
-
- // Specifies HKLM or HKCU, respectively.
- bool is_machine_;
-
- DISALLOW_COPY_AND_ASSIGN(MetricsAggregatorWin32);
-};
-
-} // namespace stats_report
-
-#endif // O3D_STATSREPORT_AGGREGATOR_WIN32_H__
diff --git a/o3d/statsreport/aggregator-win32_unittest.cc b/o3d/statsreport/aggregator-win32_unittest.cc
deleted file mode 100644
index 451927b..0000000
--- a/o3d/statsreport/aggregator-win32_unittest.cc
+++ /dev/null
@@ -1,116 +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.
- */
-
-
-// Implementation of Win32 metrics aggregator.
-#include "aggregator-win32.h"
-#include "aggregator-win32_unittest.h"
-#include "aggregator_unittest.h"
-#include "gtest/gtest.h"
-
-using ::stats_report::MetricsAggregatorWin32;
-using ::stats_report::TimingMetric;
-
-#define APP_NAME_STRING L"aggregator-win32_unittest"
-#define PREFIX_KEY_STRING L"Software\\Google\\"
-#define SUFFIX_KEY_STRING L"\\UsageStats\\Daily"
-#define ROOT_KEY_STRING PREFIX_KEY_STRING APP_NAME_STRING
-#define KEY_STRING ROOT_KEY_STRING SUFFIX_KEY_STRING
-
-const wchar_t MetricsAggregatorWin32Test::kAppName[] = APP_NAME_STRING;
-const wchar_t MetricsAggregatorWin32Test::kRootKeyName[] = ROOT_KEY_STRING;
-const wchar_t MetricsAggregatorWin32Test::kCountsKeyName[] =
- KEY_STRING L"\\Counts";
-const wchar_t MetricsAggregatorWin32Test::kTimingsKeyName[] =
- KEY_STRING L"\\Timings";
-const wchar_t MetricsAggregatorWin32Test::kIntegersKeyName[] =
- KEY_STRING L"\\Integers";
-const wchar_t MetricsAggregatorWin32Test::kBoolsKeyName[] =
- KEY_STRING L"\\Booleans";
-
-
-#define EXPECT_REGVAL_EQ(value, key_name, value_name) do { \
- char buf[sizeof(value)]; \
- ULONG len = sizeof(buf); \
- CRegKey key; \
- ASSERT_EQ(ERROR_SUCCESS, key.Open(HKEY_CURRENT_USER, key_name)); \
- EXPECT_EQ(ERROR_SUCCESS, key.QueryBinaryValue(value_name, buf, &len)); \
- EXPECT_EQ(sizeof(buf), len); \
- EXPECT_EQ(0, memcmp(&value, buf, sizeof(buf))); \
- } while (0)
-
-TEST_F(MetricsAggregatorWin32Test, AggregateWin32) {
- MetricsAggregatorWin32 agg(coll_, kAppName);
-
- EXPECT_TRUE(agg.AggregateMetrics());
- AddStats();
- EXPECT_TRUE(agg.AggregateMetrics());
-
- {
- int64 one = 1, two = 2;
- EXPECT_REGVAL_EQ(one, kCountsKeyName, L"c1");
- EXPECT_REGVAL_EQ(two, kCountsKeyName, L"c2");
-
- TimingMetric::TimingData data1 = { 2, 0, 1500, 500, 1000 };
- TimingMetric::TimingData data2 = { 2, 0, 2030, 30, 2000 };
- EXPECT_REGVAL_EQ(data1, kTimingsKeyName, L"t1");
- EXPECT_REGVAL_EQ(data2, kTimingsKeyName, L"t2");
-
- EXPECT_REGVAL_EQ(one, kIntegersKeyName, L"i1");
- EXPECT_REGVAL_EQ(two, kIntegersKeyName, L"i2");
-
- int32 bool_true = 1, bool_false = 0;
- EXPECT_REGVAL_EQ(bool_true, kBoolsKeyName, L"b1");
- EXPECT_REGVAL_EQ(bool_false, kBoolsKeyName, L"b2");
- }
-
- AddStats();
- EXPECT_TRUE(agg.AggregateMetrics());
-
- {
- int64 two = 2, four = 4;
- EXPECT_REGVAL_EQ(two, kCountsKeyName, L"c1");
- EXPECT_REGVAL_EQ(four, kCountsKeyName, L"c2");
-
- TimingMetric::TimingData data1 = { 4, 0, 3000, 500, 1000 };
- TimingMetric::TimingData data2 = { 4, 0, 4060, 30, 2000 };
- EXPECT_REGVAL_EQ(data1, kTimingsKeyName, L"t1");
- EXPECT_REGVAL_EQ(data2, kTimingsKeyName, L"t2");
-
- int64 one = 1;
- EXPECT_REGVAL_EQ(one, kIntegersKeyName, L"i1");
- EXPECT_REGVAL_EQ(two, kIntegersKeyName, L"i2");
-
- int32 bool_true = 1, bool_false = 0;
- EXPECT_REGVAL_EQ(bool_true, kBoolsKeyName, L"b1");
- EXPECT_REGVAL_EQ(bool_false, kBoolsKeyName, L"b2");
- }
-}
diff --git a/o3d/statsreport/aggregator-win32_unittest.h b/o3d/statsreport/aggregator-win32_unittest.h
deleted file mode 100644
index ceefc90..0000000
--- a/o3d/statsreport/aggregator-win32_unittest.h
+++ /dev/null
@@ -1,78 +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_STATSREPORT_AGGREGATOR_WIN32_UNITTEST_H__
-#define O3D_STATSREPORT_AGGREGATOR_WIN32_UNITTEST_H__
-
-#include "aggregator_unittest.h"
-#include "aggregator-win32.h"
-
-// Shared test fixture for win32 unit tests
-class MetricsAggregatorWin32Test: public MetricsAggregatorTest {
- public:
- virtual void SetUp() {
- // clean the registry
- SHDeleteKey(HKEY_CURRENT_USER, kRootKeyName);
- MetricsAggregatorTest::SetUp();
- }
- virtual void TearDown() {
- MetricsAggregatorTest::TearDown();
- SHDeleteKey(HKEY_CURRENT_USER, kRootKeyName);
- }
-
- void AddStats() {
- ++c1_;
- ++c2_;
- ++c2_;
-
- t1_.AddSample(1000);
- t1_.AddSample(500);
-
- t2_.AddSample(2000);
- t2_.AddSample(30);
-
- i1_ = 1;
- i2_ = 2;
-
- b1_ = true;
- b2_ = false;
- }
-
- static const wchar_t kAppName[];
- static const wchar_t kRootKeyName[];
- static const wchar_t kCountsKeyName[];
- static const wchar_t kTimingsKeyName[];
- static const wchar_t kIntegersKeyName[];
- static const wchar_t kBoolsKeyName[];
-};
-
-#endif // O3D_STATSREPORT_AGGREGATOR_WIN32_UNITTEST_H__
diff --git a/o3d/statsreport/aggregator.cc b/o3d/statsreport/aggregator.cc
deleted file mode 100644
index 41e6fbf..0000000
--- a/o3d/statsreport/aggregator.cc
+++ /dev/null
@@ -1,94 +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.
- */
-
-
-// Implementation of helper classes to aggregate the collected in-memory
-// stats to persistent storage.
-#include "aggregator.h"
-
-namespace stats_report {
-
-bool MetricsAggregator::AggregateMetrics() {
- if (!StartAggregation())
- return false;
-
- MetricIterator it(coll_), end;
- for (; it != end; ++it) {
- MetricBase *metric = *it;
- DCHECK(NULL != metric);
-
- switch (metric->type()) {
- case kCountType:
- Aggregate(metric->AsCount());
- break;
- case kTimingType:
- Aggregate(metric->AsTiming());
- break;
- case kIntegerType:
- Aggregate(metric->AsInteger());
- break;
- case kBoolType:
- Aggregate(metric->AsBool());
- break;
- default:
- DCHECK(false && "Impossible metric type");
- break;
- }
- }
-
- // done, close up
- EndAggregation();
-
- return true;
-}
-
-MetricsAggregator::MetricsAggregator() : coll_(g_global_metrics) {
- DCHECK(coll_.initialized());
-}
-
-MetricsAggregator::MetricsAggregator(const MetricCollection &coll)
- : coll_(coll) {
- DCHECK(coll_.initialized());
-}
-
-MetricsAggregator::~MetricsAggregator() {
-}
-
-bool MetricsAggregator::StartAggregation() {
- // nothing
- return true;
-}
-
-void MetricsAggregator::EndAggregation() {
- // nothing
-}
-
-} // namespace stats_report
diff --git a/o3d/statsreport/aggregator.h b/o3d/statsreport/aggregator.h
deleted file mode 100644
index f5e84e4..0000000
--- a/o3d/statsreport/aggregator.h
+++ /dev/null
@@ -1,77 +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.
- */
-
-
-// Helper class to aggregate the collected in-memory stats to persistent
-// storage.
-#ifndef O3D_STATSREPORT_AGGREGATOR_H__
-#define O3D_STATSREPORT_AGGREGATOR_H__
-
-#include "metrics.h"
-
-namespace stats_report {
-// TODO: Refactor to avoid cross platform code duplication.
-
-// Wrapper class and interface for metrics aggregation. This is a platform
-// independent class and needs to be subclassed for various platforms and/or
-// metrics persistence methods
-class MetricsAggregator {
- public:
- // Aggregate all metrics in the associated collection
- // @returns true iff aggregation started successfully, false otherwise.
- bool AggregateMetrics();
-
- protected:
- MetricsAggregator();
- explicit MetricsAggregator(const MetricCollection &coll);
- virtual ~MetricsAggregator();
-
- // Start aggregation. Override this to grab locks, open files, whatever
- // needs to happen or can expedite the individual aggregate steps.
- // @return true on success, false on failure.
- // @note aggregation will not progress if this function returns false
- virtual bool StartAggregation();
- virtual void EndAggregation();
-
- virtual void Aggregate(CountMetric *metric) = 0;
- virtual void Aggregate(TimingMetric *metric) = 0;
- virtual void Aggregate(IntegerMetric *metric) = 0;
- virtual void Aggregate(BoolMetric *metric) = 0;
-
- private:
- const MetricCollection &coll_;
-
- DISALLOW_COPY_AND_ASSIGN(MetricsAggregator);
-};
-
-} // namespace stats_report
-
-#endif // O3D_STATSREPORT_AGGREGATOR_H__
diff --git a/o3d/statsreport/aggregator_unittest.cc b/o3d/statsreport/aggregator_unittest.cc
deleted file mode 100644
index 44c65cd..0000000
--- a/o3d/statsreport/aggregator_unittest.cc
+++ /dev/null
@@ -1,140 +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.
- */
-
-
-// Implementation of helper classes to aggregate the collected in-memory
-// stats to persistent storage.
-#include "aggregator.h"
-#include "aggregator_unittest.h"
-#include "gtest/gtest.h"
-
-using namespace stats_report;
-
-class TestMetricsAggregator: public MetricsAggregator {
- public:
- explicit TestMetricsAggregator(const MetricCollection &coll)
- : MetricsAggregator(coll), aggregating_(false), counts_(0),
- timings_(0), integers_(0), bools_(0) {
- }
-
- ~TestMetricsAggregator() {
- }
-
- bool aggregating() const { return aggregating_; }
- int counts() const { return counts_; }
- int timings() const { return timings_; }
- int integers() const { return integers_; }
- int bools() const { return bools_; }
-
- protected:
- virtual bool StartAggregation() {
- aggregating_ = true;
- counts_ = 0;
- timings_ = 0;
- integers_ = 0;
- bools_ = 0;
-
- return true;
- }
-
- virtual void EndAggregation() {
- aggregating_ = false;
- }
-
- virtual void Aggregate(CountMetric *metric) {
- ASSERT_TRUE(NULL != metric);
- EXPECT_TRUE(aggregating());
- metric->Reset();
- ++counts_;
- }
-
- virtual void Aggregate(TimingMetric *metric) {
- ASSERT_TRUE(NULL != metric);
- EXPECT_TRUE(aggregating());
- metric->Reset();
- ++timings_;
- }
- virtual void Aggregate(IntegerMetric *metric) {
- ASSERT_TRUE(NULL != metric);
- EXPECT_TRUE(aggregating());
- // Integer metrics don't get reset on aggregation
- ++integers_;
- }
- virtual void Aggregate(BoolMetric *metric) {
- ASSERT_TRUE(NULL != metric);
- EXPECT_TRUE(aggregating());
- metric->Reset();
- ++bools_;
- }
-
- private:
- bool aggregating_;
- int counts_;
- int timings_;
- int integers_;
- int bools_;
-};
-
-TEST_F(MetricsAggregatorTest, Aggregate) {
- TestMetricsAggregator agg(coll_);
-
- EXPECT_FALSE(agg.aggregating());
- EXPECT_EQ(0, agg.counts());
- EXPECT_EQ(0, agg.timings());
- EXPECT_EQ(0, agg.integers());
- EXPECT_EQ(0, agg.bools());
- EXPECT_TRUE(agg.AggregateMetrics());
- EXPECT_FALSE(agg.aggregating());
-
- // check that we saw all counters.
- EXPECT_TRUE(kNumCounts == agg.counts());
- EXPECT_TRUE(kNumTimings == agg.timings());
- EXPECT_TRUE(kNumIntegers == agg.integers());
- EXPECT_TRUE(kNumBools == agg.bools());
-}
-
-class FailureTestMetricsAggregator: public TestMetricsAggregator {
- public:
- explicit FailureTestMetricsAggregator(const MetricCollection &coll) :
- TestMetricsAggregator(coll) {
- }
-
- protected:
- virtual bool StartAggregation() {
- return false;
- }
-};
-
-TEST_F(MetricsAggregatorTest, AggregateFailure) {
- FailureTestMetricsAggregator agg(coll_);
-
- EXPECT_FALSE(agg.AggregateMetrics());
-}
diff --git a/o3d/statsreport/aggregator_unittest.h b/o3d/statsreport/aggregator_unittest.h
deleted file mode 100644
index 286362e..0000000
--- a/o3d/statsreport/aggregator_unittest.h
+++ /dev/null
@@ -1,85 +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_STATSREPORT_AGGREGATOR_UNITTEST_H__
-#define O3D_STATSREPORT_AGGREGATOR_UNITTEST_H__
-
-#include "metrics.h"
-#include "gtest/gtest.h"
-
-// Test fixture shared among aggregator unit tests
-class MetricsAggregatorTest: public testing::Test {
- public:
-#define INIT_METRIC(type, name) name##_(#name, &coll_)
-#define DECL_METRIC(type, name) stats_report::type##Metric name##_
-
- MetricsAggregatorTest()
- : INIT_METRIC(Count, c1),
- INIT_METRIC(Count, c2),
- INIT_METRIC(Timing, t1),
- INIT_METRIC(Timing, t2),
- INIT_METRIC(Integer, i1),
- INIT_METRIC(Integer, i2),
- INIT_METRIC(Bool, b1),
- INIT_METRIC(Bool, b2) {
- }
-
- enum {
- kNumCounts = 2,
- kNumTimings = 2,
- kNumIntegers = 2,
- kNumBools = 2
- };
-
- stats_report::MetricCollection coll_;
- DECL_METRIC(Count, c1);
- DECL_METRIC(Count, c2);
- DECL_METRIC(Timing, t1);
- DECL_METRIC(Timing, t2);
- DECL_METRIC(Integer, i1);
- DECL_METRIC(Integer, i2);
- DECL_METRIC(Bool, b1);
- DECL_METRIC(Bool, b2);
-
-#undef INIT_METRIC
-#undef DECL_METRIC
-
- virtual void SetUp() {
- coll_.Initialize();
- }
-
- virtual void TearDown() {
- coll_.Uninitialize();
- }
-};
-
-#endif // O3D_STATSREPORT_AGGREGATOR_UNITTEST_H__
diff --git a/o3d/statsreport/common/const_product.h b/o3d/statsreport/common/const_product.h
deleted file mode 100644
index 1dc140a..0000000
--- a/o3d/statsreport/common/const_product.h
+++ /dev/null
@@ -1,91 +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.
- */
-
-
-// Product-specific constants.
-//
-
-#ifndef O3D_STATSREPORT_COMMON_CONST_PRODUCT_H_
-#define O3D_STATSREPORT_COMMON_CONST_PRODUCT_H_
-
-#include <build/build_config.h>
-#include "base/basictypes.h"
-
-#define _QUOTEME(x) #x
-#define QUOTEME(x) _QUOTEME(x)
-
-#define _WIDEN(X) L ## X
-#define WIDEN(X) _WIDEN(X)
-
-#define PRODUCT_NAME_STRING "o3d"
-#define PRODUCT_VERSION_STRING QUOTEME(O3D_PLUGIN_VERSION)
-
-#define PRODUCT_NAME_STRING_WIDE WIDEN(PRODUCT_NAME_STRING)
-
-// keep these two in sync
-#define REGISTRY_KEY_NAME_STRING "o3d"
-#define REGISTRY_KEY_STRING "Software\\Google\\O3D"
-
-#ifdef OS_WIN
-const char kMetricsLockName[] = PRODUCT_NAME_STRING "MetricsAggregationlock";
-#endif
-
-const char kProductName[] = PRODUCT_NAME_STRING;
-
-// TODO: Determine if #define below is needed.
-// This is a string value to be found under they key
-// at REGISTRY_KEY_STRING. This is written by our
-// installer
-// #define INSTALL_DIR_VALUE_NAME "InstallDir"
-
-const char kUserAgent[] = "O3D-";
-
-const int kStatsUploadIntervalSec = 24 * 60 * 60; // once per day
-const int kStatsAggregationIntervalMSec = 5 * 60 * 1000; // every 5 minutes
-
-// Taken from Google Update
-// TODO: CRITICAL: Link to actual Google Update docs so that we don't have
-// to keep this up to date. It will mess with our logs.
-const wchar_t* const kRegValueUserId = L"ui";
-const wchar_t* const kRelativeGoopdateRegPath = L"Software\\Google\\Update\\";
-
-const wchar_t* const kClientstateRegistryKey =
- L"Software\\Google\\Update\\ClientState\\"
- L"{70308795-045C-42DA-8F4E-D452381A7459}";
-const wchar_t* const kOptInRegistryKey = L"usagestats";
-
-#define INTERNET_MAX_PATH_LENGTH 2048
-#define INTERNET_MAX_SCHEME_LENGTH 32
-#define INTERNET_MAX_URL_LENGTH (INTERNET_MAX_SCHEME_LENGTH \
- + sizeof("://") \
- + INTERNET_MAX_PATH_LENGTH)
-
-#endif // O3D_STATSREPORT_COMMON_CONST_PRODUCT_H_
diff --git a/o3d/statsreport/common/highres_timer-linux.cc b/o3d/statsreport/common/highres_timer-linux.cc
deleted file mode 100644
index d577fc3..0000000
--- a/o3d/statsreport/common/highres_timer-linux.cc
+++ /dev/null
@@ -1,59 +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 "statsreport/common/highres_timer.h"
-
-const uint64 MICROS_IN_MILLI = 1000L;
-const uint64 MICROS_IN_HALF_MILLI = 500L;
-const uint64 MICROS_IN_HALF_SECOND = 500000L;
-
-uint64 HighresTimer::GetElapsedMs() const {
- uint64 end_time = GetCurrentTicks();
-
- // Scale to ms and round to nearest ms - rounding is important
- // because otherwise the truncation error may accumulate e.g. in sums.
- //
- return (static_cast<uint64>(end_time - start_ticks_) +
- MICROS_IN_HALF_MILLI) /
- MICROS_IN_MILLI;
-}
-
-uint64 HighresTimer::GetElapsedSec() const {
- uint64 end_time = GetCurrentTicks();
-
- // Scale to ms and round to nearest ms - rounding is important
- // because otherwise the truncation error may accumulate e.g. in sums.
- //
- return (static_cast<uint64>(end_time - start_ticks_) +
- MICROS_IN_HALF_SECOND) /
- MICROS_IN_SECOND;
-}
diff --git a/o3d/statsreport/common/highres_timer-linux.h b/o3d/statsreport/common/highres_timer-linux.h
deleted file mode 100644
index 7574a8f..0000000
--- a/o3d/statsreport/common/highres_timer-linux.h
+++ /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.
- */
-
-
-#ifndef O3D_STATSREPORT_COMMON_HIGHRES_TIMER_LINUX_H_
-#define O3D_STATSREPORT_COMMON_HIGHRES_TIMER_LINUX_H_
-
-#include "base/basictypes.h"
-
-#include <sys/time.h>
-
-const uint64 MICROS_IN_SECOND = 1000000L;
-
-// A handy class for reliably measuring wall-clock time with decent resolution.
-//
-// We want to measure time with high resolution on Linux. What to do?
-//
-// RDTSC? Sure, but how do you convert it to wall clock time?
-// clock_gettime? It's not in all Linuxes.
-//
-// Let's just use gettimeofday; it's good to the microsecond.
-class HighresTimer {
- public:
- // Captures the current start time
- HighresTimer();
-
- // Captures the current tick, can be used to reset a timer for reuse.
- void Start();
-
- // Returns the elapsed ticks with full resolution
- uint64 GetElapsedTicks() const;
-
- // Returns the elapsed time in milliseconds, rounded to the nearest
- // millisecond.
- uint64 GetElapsedMs() const;
-
- // Returns the elapsed time in seconds, rounded to the nearest second.
- uint64 GetElapsedSec() const;
-
- uint64 start_ticks() const { return start_ticks_; }
-
- // Returns timer frequency from cache, should be less
- // overhead than ::QueryPerformanceFrequency
- static uint64 GetTimerFrequency();
- // Returns current ticks
- static uint64 GetCurrentTicks();
-
- private:
- // Captured start time
- uint64 start_ticks_;
-};
-
-inline HighresTimer::HighresTimer() {
- Start();
-}
-
-inline void HighresTimer::Start() {
- start_ticks_ = GetCurrentTicks();
-}
-
-inline uint64 HighresTimer::GetTimerFrequency() {
- // fixed; one "tick" is one microsecond
-
- return MICROS_IN_SECOND;
-}
-
-inline uint64 HighresTimer::GetCurrentTicks() {
- timeval tv;
- (void)gettimeofday(&tv, 0);
-
- return tv.tv_sec * MICROS_IN_SECOND + tv.tv_usec;
-}
-
-inline uint64 HighresTimer::GetElapsedTicks() const {
- return start_ticks_ - GetCurrentTicks();
-}
-
-#endif // O3D_STATSREPORT_COMMON_HIGHRES_TIMER_LINUX_H_
diff --git a/o3d/statsreport/common/highres_timer-mac.cc b/o3d/statsreport/common/highres_timer-mac.cc
deleted file mode 100644
index aa14525..0000000
--- a/o3d/statsreport/common/highres_timer-mac.cc
+++ /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.
- */
-
-
-#include "statsreport/common/highres_timer.h"
-
-bool HighresTimer::perf_ratio_collected_ = false;
-mach_timebase_info_data_t HighresTimer::perf_ratio_ = {0};
-
-const uint64 NANOS_IN_MILLI = 1000000L;
-const uint64 NANOS_IN_HALF_MILLI = 500000L;
-const uint64 NANOS_IN_SECOND = 1000000000L;
-const uint64 NANOS_IN_HALF_SECOND = 500000000L;
-
-uint64 HighresTimer::GetElapsedMs() const {
- uint64 end_time = GetCurrentTicks();
-
- // Scale to ms and round to nearest ms - rounding is important
- // because otherwise the truncation error may accumulate e.g. in sums.
- //
- (void)GetTimerFrequency();
- return (static_cast<uint64>(end_time - start_ticks_) * perf_ratio_.numer +
- NANOS_IN_HALF_MILLI * perf_ratio_.denom) /
- (NANOS_IN_MILLI * perf_ratio_.denom);
-}
-
-uint64 HighresTimer::GetElapsedSec() const {
- uint64 end_time = GetCurrentTicks();
-
- // Scale to ms and round to nearest ms - rounding is important
- // because otherwise the truncation error may accumulate e.g. in sums.
- //
- (void)GetTimerFrequency();
- return (static_cast<uint64>(end_time - start_ticks_) * perf_ratio_.numer +
- NANOS_IN_HALF_SECOND * perf_ratio_.denom) /
- (NANOS_IN_SECOND * perf_ratio_.denom);
-}
-
-void HighresTimer::CollectPerfRatio() {
- mach_timebase_info(&perf_ratio_);
- perf_ratio_collected_ = true;
-}
diff --git a/o3d/statsreport/common/highres_timer-mac.h b/o3d/statsreport/common/highres_timer-mac.h
deleted file mode 100644
index af512ac..0000000
--- a/o3d/statsreport/common/highres_timer-mac.h
+++ /dev/null
@@ -1,103 +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_STATSREPORT_COMMON_HIGHRES_TIMER_MAC_H_
-#define O3D_STATSREPORT_COMMON_HIGHRES_TIMER_MAC_H_
-
-#include "base/basictypes.h"
-#include <mach/mach.h>
-#include <mach/mach_time.h>
-
-// A handy class for reliably measuring wall-clock time with decent resolution.
-class HighresTimer {
- public:
- // Captures the current start time
- HighresTimer();
-
- // Captures the current tick, can be used to reset a timer for reuse.
- void Start();
-
- // Returns the elapsed ticks with full resolution
- uint64 GetElapsedTicks() const;
-
- // Returns the elapsed time in milliseconds, rounded to the nearest
- // millisecond.
- uint64 GetElapsedMs() const;
-
- // Returns the elapsed time in seconds, rounded to the nearest second.
- uint64 GetElapsedSec() const;
-
- uint64 start_ticks() const { return start_ticks_; }
-
- // Returns timer frequency from cache, should be less
- // overhead than ::QueryPerformanceFrequency
- static uint64 GetTimerFrequency();
- // Returns current ticks
- static uint64 GetCurrentTicks();
-
- private:
- static void CollectPerfRatio();
-
- // Captured start time
- uint64 start_ticks_;
-
- // Captured performance counter frequency
- static bool perf_ratio_collected_;
- static mach_timebase_info_data_t perf_ratio_;
-};
-
-inline HighresTimer::HighresTimer() {
- Start();
-}
-
-inline void HighresTimer::Start() {
- start_ticks_ = GetCurrentTicks();
-}
-
-inline uint64 HighresTimer::GetTimerFrequency() {
- if (!perf_ratio_collected_)
- CollectPerfRatio();
- // we're losing precision by doing the division here, but this value is only
- // used to estimate tick time by the unit tests, so we're ok
- return static_cast<uint64>(perf_ratio_.denom) * 1000000000ULL
- / perf_ratio_.numer;
-}
-
-inline uint64 HighresTimer::GetCurrentTicks() {
- return mach_absolute_time();
-}
-
-inline uint64 HighresTimer::GetElapsedTicks() const {
- return start_ticks_ - GetCurrentTicks();
-}
-
-#endif // O3D_STATSREPORT_COMMON_HIGHRES_TIMER_MAC_H_
diff --git a/o3d/statsreport/common/highres_timer-win32.cc b/o3d/statsreport/common/highres_timer-win32.cc
deleted file mode 100644
index 878b237..0000000
--- a/o3d/statsreport/common/highres_timer-win32.cc
+++ /dev/null
@@ -1,72 +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 "statsreport/common/highres_timer.h"
-
-bool HighresTimer::perf_freq_collected_ = false;
-ULONGLONG HighresTimer::perf_freq_ = 0;
-
-ULONGLONG HighresTimer::GetElapsedMs() const {
- ULONGLONG end_time = GetCurrentTicks();
-
- // Scale to ms and round to nearerst ms - rounding is important
- // because otherwise the truncation error may accumulate e.g. in sums.
- //
- // Given infinite resolution, this expression could be written as:
- // trunc((end - start (units:freq*sec))/freq (units:sec) *
- // 1000 (unit:ms) + 1/2 (unit:ms))
- ULONGLONG freq = GetTimerFrequency();
- return ((end_time - start_ticks_) * 1000L + freq / 2) / freq;
-}
-
-ULONGLONG HighresTimer::GetElapsedSec() const {
- ULONGLONG end_time = GetCurrentTicks();
-
- // Scale to ms and round to nearerst ms - rounding is important
- // because otherwise the truncation error may accumulate e.g. in sums.
- //
- // Given infinite resolution, this expression could be written as:
- // trunc((end - start (units:freq*sec))/freq (unit:sec) + 1/2 (unit:sec))
- ULONGLONG freq = GetTimerFrequency();
- return ((end_time - start_ticks_) + freq / 2) / freq;
-}
-
-void HighresTimer::CollectPerfFreq() {
- LARGE_INTEGER freq;
-
- // Note that this is racy. It's OK, however, because even
- // concurrent executions of this are idempotent.
- if (::QueryPerformanceFrequency(&freq)) {
- perf_freq_ = freq.QuadPart;
- perf_freq_collected_ = true;
- }
-}
diff --git a/o3d/statsreport/common/highres_timer-win32.h b/o3d/statsreport/common/highres_timer-win32.h
deleted file mode 100644
index 378fdeb..0000000
--- a/o3d/statsreport/common/highres_timer-win32.h
+++ /dev/null
@@ -1,105 +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_STATSREPORT_COMMON_HIGHRES_TIMER_WIN32_H_
-#define O3D_STATSREPORT_COMMON_HIGHRES_TIMER_WIN32_H_
-
-#include <windows.h>
-
-// A handy class for reliably measuring wall-clock time with decent resolution,
-// even on multi-processor machines and on laptops (where RDTSC potentially
-// returns different results on different processors and/or the RDTSC timer
-// clocks at different rates depending on the power state of the CPU,
-// respectively).
-class HighresTimer {
- public:
- // Captures the current start time
- HighresTimer();
- virtual ~HighresTimer() {}
-
- // Captures the current tick, can be used to reset a timer for reuse.
- void Start();
-
- // Returns the elapsed ticks with full resolution
- ULONGLONG GetElapsedTicks() const;
-
- // Returns the elapsed time in milliseconds, rounded to the nearest
- // millisecond.
- virtual ULONGLONG GetElapsedMs() const;
-
- // Returns the elapsed time in seconds, rounded to the nearest second.
- virtual ULONGLONG GetElapsedSec() const;
-
- ULONGLONG start_ticks() const { return start_ticks_; }
-
- // Returns timer frequency from cache, should be less
- // overhead than ::QueryPerformanceFrequency
- static ULONGLONG GetTimerFrequency();
- // Returns current ticks
- static ULONGLONG GetCurrentTicks();
-
- private:
- static void CollectPerfFreq();
-
- // Captured start time
- ULONGLONG start_ticks_;
-
- // Captured performance counter frequency
- static bool perf_freq_collected_;
- static ULONGLONG perf_freq_;
-};
-
-inline HighresTimer::HighresTimer() {
- Start();
-}
-
-inline void HighresTimer::Start() {
- start_ticks_ = GetCurrentTicks();
-}
-
-inline ULONGLONG HighresTimer::GetTimerFrequency() {
- if (!perf_freq_collected_)
- CollectPerfFreq();
- return perf_freq_;
-}
-
-inline ULONGLONG HighresTimer::GetCurrentTicks() {
- LARGE_INTEGER ticks;
- ::QueryPerformanceCounter(&ticks);
- return ticks.QuadPart;
-}
-
-inline ULONGLONG HighresTimer::GetElapsedTicks() const {
- return start_ticks_ - GetCurrentTicks();
-}
-
-#endif // O3D_STATSREPORT_COMMON_HIGHRES_TIMER_WIN32_H_
diff --git a/o3d/statsreport/common/highres_timer.h b/o3d/statsreport/common/highres_timer.h
deleted file mode 100644
index 5842729..0000000
--- a/o3d/statsreport/common/highres_timer.h
+++ /dev/null
@@ -1,40 +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 <build/build_config.h>
-#if defined(OS_WIN)
-#include "statsreport/common/highres_timer-win32.h"
-#elif defined(OS_MACOSX)
-#include "statsreport/common/highres_timer-mac.h"
-#else
-#include "statsreport/common/highres_timer-linux.h"
-#endif
diff --git a/o3d/statsreport/common/highres_timer_unittest.cc b/o3d/statsreport/common/highres_timer_unittest.cc
deleted file mode 100644
index 8a62a91..0000000
--- a/o3d/statsreport/common/highres_timer_unittest.cc
+++ /dev/null
@@ -1,84 +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 "statsreport/common/highres_timer.h"
-#include "gtest/gtest.h"
-#include "base/basictypes.h"
-
-// These unittests have proven to be flaky on the build server. While
-// we don't want them breaking the build, we still build them to guard
-// against bitrot. On dev's machines during local builds we leave them
-// enabled.
-#ifndef BUILD_SERVER_BUILD
-TEST(HighresTimer, MillisecondClock) {
-#else
-TEST(HighresTimer, DISABLED_MillisecondClock) {
-#endif
- HighresTimer timer;
-
- // note: this could fail if we context switch between initializing the timer
- // and here. Very unlikely however.
- EXPECT_EQ(0U, timer.GetElapsedMs());
- timer.Start();
- uint64 half_ms = HighresTimer::GetTimerFrequency() / 2000;
- // busy wait for half a millisecond
- while (timer.start_ticks() + half_ms > HighresTimer::GetCurrentTicks()) {
- // Nothing
- }
- EXPECT_EQ(1U, timer.GetElapsedMs());
-}
-
-#ifndef BUILD_SERVER_BUILD
-TEST(HighresTimer, SecondClock) {
-#else
-TEST(HighresTimer, DISABLED_SecondClock) {
-#endif
- HighresTimer timer;
-
- EXPECT_EQ(0U, timer.GetElapsedSec());
-#ifdef OS_WIN
- ::Sleep(250);
-#else
- struct timespec ts1 = {0, 250000000};
- nanosleep(&ts1, 0);
-#endif
- EXPECT_EQ(0U, timer.GetElapsedSec());
- EXPECT_LE(230U, timer.GetElapsedMs());
- EXPECT_GE(270U, timer.GetElapsedMs());
-#ifdef OS_WIN
- ::Sleep(251);
-#else
- struct timespec ts2 = {0, 251000000};
- nanosleep(&ts2, 0);
-#endif
- EXPECT_EQ(1U, timer.GetElapsedSec());
-}
diff --git a/o3d/statsreport/const-mac.h b/o3d/statsreport/const-mac.h
deleted file mode 100644
index fba3635..0000000
--- a/o3d/statsreport/const-mac.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-// Constants for Mac stats aggregation and uploading
-#ifndef O3D_STATSREPORT_CONST_MAC_H_
-#define O3D_STATSREPORT_CONST_MAC_H_
-
-#include <string>
-#import <Cocoa/Cocoa.h>
-
-namespace stats_report {
-
-extern const char kCountsKeyName[];
-extern const char kTimingsKeyName[];
-extern const char kIntegersKeyName[];
-extern const char kBooleansKeyName[];
-
-#define kLastTransmissionTimeValueName @"LastTransmission"
-NSString* O3DStatsPath(void);
-
-} // namespace stats_report
-
-#endif // O3D_STATSREPORT_CONST_MAC_H_
diff --git a/o3d/statsreport/const-mac.mm b/o3d/statsreport/const-mac.mm
deleted file mode 100644
index 0551d89..0000000
--- a/o3d/statsreport/const-mac.mm
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-// Constants for Posix stats aggregation and uploading
-#include "const-mac.h"
-
-namespace stats_report {
-
-const char kTimingsKeyName[] = "Timings";
-const char kCountsKeyName[] = "Counts";
-const char kIntegersKeyName[] = "Integers";
-const char kBooleansKeyName[] = "Booleans";
-
-static NSString* FindGoogleAppDirectory(void) {
- NSString *applicationSupportFolder =
- [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,
- NSUserDomainMask,
- YES) objectAtIndex:0];
-
- NSString *googleAppSupportPath =
- [applicationSupportFolder stringByAppendingString:@"/Google"];
-
- if (![[NSFileManager defaultManager] fileExistsAtPath:googleAppSupportPath])
- [[NSFileManager defaultManager] createDirectoryAtPath:googleAppSupportPath
- attributes:nil];
-
- return googleAppSupportPath;
-}
-
-NSString* O3DStatsPath(void) {
- static NSString* the_path = NULL;
- if (!the_path) {
- the_path = [FindGoogleAppDirectory() stringByAppendingString:@"/O3D_Stats"];
- [the_path retain];
- }
- return the_path;
-}
-
-} // namespace stats_report
diff --git a/o3d/statsreport/const-posix.cc b/o3d/statsreport/const-posix.cc
deleted file mode 100644
index 9314b04..0000000
--- a/o3d/statsreport/const-posix.cc
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-// Constants for Posix stats aggregation and uploading
-#include "const-posix.h"
-
-namespace stats_report {
-
-const char kTimingsKeyName = "Timings";
-const char kCountsKeyName = "Counts";
-const char kIntegersKeyName = "Integers";
-const char kBooleansKeyName = "Booleans";
-const char kLastTransmissionTimeValueName = "LastTransmission";
-
-} // namespace stats_report
diff --git a/o3d/statsreport/const-posix.h b/o3d/statsreport/const-posix.h
deleted file mode 100644
index e9abe24..0000000
--- a/o3d/statsreport/const-posix.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright 2010, 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.
- */
-
-
-// Constants for Posix stats aggregation and uploading
-#ifndef O3D_STATSREPORT_CONST_POSIX_H_
-#define O3D_STATSREPORT_CONST_POSIX_H_
-
-#include <string>
-
-namespace stats_report {
-
-extern const char kCountsKeyName[];
-extern const char kTimingsKeyName[];
-extern const char kIntegersKeyName[];
-extern const char kBooleansKeyName[];
-extern const char kLastTransmissionTimeValueName[];
-
-} // namespace stats_report
-
-#endif // O3D_STATSREPORT_CONST_POSIX_H_
diff --git a/o3d/statsreport/const-win32.cc b/o3d/statsreport/const-win32.cc
deleted file mode 100644
index a4f3b23..0000000
--- a/o3d/statsreport/const-win32.cc
+++ /dev/null
@@ -1,46 +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.
- */
-
-
-// Constants for Win32 stats aggregation and uploading
-#include "const-win32.h"
-
-namespace stats_report {
-
-const wchar_t kTimingsKeyName[] = L"Timings";
-const wchar_t kCountsKeyName[] = L"Counts";
-const wchar_t kIntegersKeyName[] = L"Integers";
-const wchar_t kBooleansKeyName[] = L"Booleans";
-const wchar_t kStatsKeyFormatString[] = L"Software\\Google\\"
- L"%ws\\UsageStats\\Daily";
-const wchar_t kLastTransmissionTimeValueName[] = L"LastTransmission";
-
-} // namespace stats_report
diff --git a/o3d/statsreport/const-win32.h b/o3d/statsreport/const-win32.h
deleted file mode 100644
index a4897411..0000000
--- a/o3d/statsreport/const-win32.h
+++ /dev/null
@@ -1,48 +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.
- */
-
-
-// Constants for Win32 stats aggregation and uploading
-#ifndef O3D_STATSREPORT_CONST_WIN32_H__
-#define O3D_STATSREPORT_CONST_WIN32_H__
-
-namespace stats_report {
-
-extern const wchar_t kCountsKeyName[];
-extern const wchar_t kTimingsKeyName[];
-extern const wchar_t kIntegersKeyName[];
-extern const wchar_t kBooleansKeyName[];
-extern const wchar_t kStatsKeyFormatString[];
-extern const wchar_t kLastTransmissionTimeValueName[];
-
-} // namespace stats_report
-
-#endif // O3D_STATSREPORT_CONST_WIN32_H__
diff --git a/o3d/statsreport/const_server.h b/o3d/statsreport/const_server.h
deleted file mode 100644
index 1443486..0000000
--- a/o3d/statsreport/const_server.h
+++ /dev/null
@@ -1,54 +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.
- */
-
-
-// Product-specific constants for uploading.
-//
-
-#ifndef O3D_STATSREPORT_INTERNAL_CONST_SERVER_H_
-#define O3D_STATSREPORT_INTERNAL_CONST_SERVER_H_
-
-#include <build/build_config.h>
-#include "base/basictypes.h"
-
-
-// Metrics reporting server constants
-#define METRICS_SERVER_NAME "www.google.com"
-#define METRICS_SERVER_PORT 80
-#define METRICS_SERVER_PATH "tbproxy/usagestats"
-
-#define METRICS_TESTING_SERVER_NAME "0.usagestats.server.toolbar-team.eh.borg.google.com";
-#define METRICS_TESTING_SERVER_PORT 25510
-
-const char kStatsServerParamSourceId[] = "sourceid";
-const char kStatsServerParamVersion[] = "v";
-
-#endif // O3D_STATSREPORT_INTERNAL_CONST_SERVER_H_
diff --git a/o3d/statsreport/formatter.cc b/o3d/statsreport/formatter.cc
deleted file mode 100644
index f295b25..0000000
--- a/o3d/statsreport/formatter.cc
+++ /dev/null
@@ -1,93 +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 "formatter.h"
-
-namespace stats_report {
-
-Formatter::Formatter(const char *name, uint32 measurement_secs) {
- output_ << name << "&" << measurement_secs;
-}
-
-Formatter::~Formatter() {
-}
-
-void Formatter::AddCount(const char *name, uint64 value) {
- output_ << "&" << name << ":c=" << value;
-}
-
-void Formatter::AddTiming(const char *name, uint64 num, uint64 avg,
- uint64 min, uint64 max) {
- output_ << "&" << name << ":t=" << num << ";"
- << avg << ";" << min << ";" << max;
-}
-
-void Formatter::AddInteger(const char *name, uint64 value) {
- output_ << "&" << name << ":i=" << value;
-}
-
-void Formatter::AddBoolean(const char *name, bool value) {
- output_ << "&" << name << ":b=" << (value ? "t" : "f");
-}
-
-void Formatter::AddMetric(MetricBase *metric) {
- switch (metric->type()) {
- case kCountType: {
- CountMetric *count = metric->AsCount();
- AddCount(count->name(), count->value());
- break;
- }
- case kTimingType: {
- TimingMetric *timing = metric->AsTiming();
- AddTiming(timing->name(), timing->count(), timing->average(),
- timing->minimum(), timing->maximum());
- break;
- }
- case kIntegerType: {
- IntegerMetric *integer = metric->AsInteger();
- AddInteger(integer->name(), integer->value());
- break;
- }
- case kBoolType: {
- BoolMetric *boolean = metric->AsBool();
- // TODO: boolean->value() returns a TristateBoolValue. The
- // formatter is going to serialize kBoolUnset to true.
- DCHECK_NE(boolean->value(), BoolMetric::kBoolUnset);
- AddBoolean(boolean->name(), boolean->value() != BoolMetric::kBoolFalse);
- break;
- }
- default:
- DCHECK(false && "Impossible metric type");
- }
-}
-
-} // namespace stats_report
diff --git a/o3d/statsreport/formatter.h b/o3d/statsreport/formatter.h
deleted file mode 100644
index 38316a6..0000000
--- a/o3d/statsreport/formatter.h
+++ /dev/null
@@ -1,79 +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.
- */
-
-
-// Utility class to format metrics to a string suitable for posting to
-// TB stats server.
-#ifndef O3D_STATSREPORT_FORMATTER_H__
-#define O3D_STATSREPORT_FORMATTER_H__
-
-#include <sstream>
-#include "base/basictypes.h"
-#include "metrics.h"
-
-namespace stats_report {
-
-// A utility class that knows how to turn metrics into a string for
-// reporting to the Toolbar stats server.
-class Formatter {
- public:
- // @param name the name of the application to report stats against
- Formatter(const char *name, uint32 measurement_secs);
- ~Formatter();
-
- // Add metric to the output string
- void AddMetric(MetricBase *metric);
-
- // Add typed metrics to the output string
- // @{
- void AddCount(const char *name, uint64 value);
- void AddTiming(const char *name, uint64 num, uint64 avg, uint64 min,
- uint64 max);
- void AddInteger(const char *name, uint64 value);
- void AddBoolean(const char *name, bool value);
- // @}
-
- // Terminates the output string and returns it.
- // It is an error to add metrics after output() is called.
- const std::string output() {
- output_ << std::ends;
- return output_.str();
- }
-
- private:
- mutable std::ostringstream output_;
-
- DISALLOW_COPY_AND_ASSIGN(Formatter);
-};
-
-} // namespace stats_report
-
-#endif // O3D_STATSREPORT_FORMATTER_H__
diff --git a/o3d/statsreport/formatter_unittest.cc b/o3d/statsreport/formatter_unittest.cc
deleted file mode 100644
index f1315ea0..0000000
--- a/o3d/statsreport/formatter_unittest.cc
+++ /dev/null
@@ -1,54 +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 "gtest/gtest.h"
-#include "formatter.h"
-
-using stats_report::Formatter;
-
-TEST(Formatter, Format) {
- Formatter formatter("test_application", 86400);
-
- formatter.AddCount("count1", 10);
- formatter.AddTiming("timing1", 2, 150, 50, 200);
- formatter.AddInteger("integer1", 3000);
- formatter.AddBoolean("boolean1", true);
- formatter.AddBoolean("boolean2", false);
-
- EXPECT_STREQ("test_application&86400"
- "&count1:c=10"
- "&timing1:t=2;150;50;200"
- "&integer1:i=3000"
- "&boolean1:b=t"
- "&boolean2:b=f",
- formatter.output().c_str());
-}
diff --git a/o3d/statsreport/lock.h b/o3d/statsreport/lock.h
deleted file mode 100644
index 23d4a14..0000000
--- a/o3d/statsreport/lock.h
+++ /dev/null
@@ -1,63 +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.
- */
-
-
-// Declaration of LLock, the lock implementation we use.
-#ifndef O3D_STATSREPORT_LOCK_H_
-#define O3D_STATSREPORT_LOCK_H_
-
-#include <windows.h>
-
-namespace stats_report {
-
-class LLock {
- public:
- LLock() {
- InitializeCriticalSection(&lock_);
- }
- ~LLock() {
- DeleteCriticalSection(&lock_);
- };
-
- void Lock() {
- EnterCriticalSection(&lock_);
- }
- void Unlock() {
- LeaveCriticalSection(&lock_);
- }
-
- private:
- CRITICAL_SECTION lock_;
-};
-
-} // namespace stats_report
-
-#endif // O3D_STATSREPORT_LOCK_H_
diff --git a/o3d/statsreport/metrics.cc b/o3d/statsreport/metrics.cc
deleted file mode 100644
index b49202d..0000000
--- a/o3d/statsreport/metrics.cc
+++ /dev/null
@@ -1,276 +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.
- */
-
-
-// Implements metrics and metrics collections
-#include "metrics.h"
-
-#ifndef OS_WIN
-#include <pthread.h>
-#else // OS_WIN
-#include "lock.h"
-#endif // OS_WIN
-
-namespace stats_report {
-// Make sure global stats collection is placed in zeroed storage so as to avoid
-// initialization order snafus.
-MetricCollectionBase g_global_metric_storage = { 0, 0 };
-MetricCollection &g_global_metrics =
- *static_cast<MetricCollection*>(&g_global_metric_storage);
-
-#ifdef OS_WIN
-#pragma warning(push)
-#endif
-// C4640: construction of local static object is not thread-safe.
-// C4073: initializers put in library initialization area.
-#ifdef OS_WIN
-#pragma warning(disable : 4640 4073)
-#endif
-
-// Serialize all metric manipulation and access under this lock.
-#ifdef OS_WIN
-// Initializes g_lock before other global objects of user defined types.
-// It assumes the program is single threaded while executing CRT startup and
-// exit code.
-#pragma init_seg(lib)
-LLock g_lock;
-#pragma warning(pop)
-#else // OS_WIN
-// On non-Windowsen we use a link time initialized pthread mutex.
-pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
-#endif // OS_WIN
-
-class MetricBase::ObjectLock {
- public:
- explicit ObjectLock(const MetricBase *metric) : metric_(metric) {
- metric_->Lock();
- }
-
- ~ObjectLock() {
- metric_->Unlock();
- }
-
- private:
- MetricBase const *const metric_;
- DISALLOW_COPY_AND_ASSIGN(ObjectLock);
-};
-
-void MetricBase::Lock() const {
-#ifdef OS_WIN
- g_lock.Lock();
-#else // OS_WIN
- pthread_mutex_lock(&g_lock);
-#endif // OS_WIN
-}
-
-void MetricBase::Unlock() const {
-#ifdef OS_WIN
- g_lock.Unlock();
-#else // OS_WIN
- pthread_mutex_unlock(&g_lock);
-#endif // OS_WIN
-}
-
-MetricBase::MetricBase(const char *name,
- MetricType type,
- MetricCollectionBase *coll)
- : name_(name), type_(type), next_(coll->first_), coll_(coll) {
- DCHECK_NE(static_cast<MetricCollectionBase*>(NULL), coll_);
- DCHECK_EQ(false, coll_->initialized_);
- coll->first_ = this;
-}
-
-MetricBase::MetricBase(const char *name, MetricType type)
- : name_(name), type_(type), next_(NULL), coll_(NULL) {
-}
-
-MetricBase::~MetricBase() {
- if (coll_) {
- DCHECK_EQ(this, coll_->first_);
- LOG_IF(WARNING, coll_->initialized_)
- << "Warning: Metric destructor called without call to Uninitialize().";
-
- coll_->first_ = next_;
- } else {
- DCHECK(NULL == next_);
- }
-}
-
-void IntegerMetricBase::Set(uint64 value) {
- ObjectLock lock(this);
- value_ = value;
-}
-
-uint64 IntegerMetricBase::value() const {
- ObjectLock lock(this);
- uint64 ret = value_;
- return ret;
-}
-
-void IntegerMetricBase::Increment() {
- ObjectLock lock(this);
- ++value_;
-}
-
-void IntegerMetricBase::Decrement() {
- ObjectLock lock(this);
- --value_;
-}
-
-void IntegerMetricBase::Add(uint64 value) {
- ObjectLock lock(this);
- value_ += value;
-}
-
-void IntegerMetricBase::Subtract(uint64 value) {
- ObjectLock lock(this);
- if (value_ < value)
- value_ = 0;
- else
- value_ -= value;
-}
-
-uint64 CountMetric::Reset() {
- ObjectLock lock(this);
- uint64 ret = value_;
- value_ = 0;
- return ret;
-}
-
-TimingMetric::TimingData TimingMetric::Reset() {
- ObjectLock lock(this);
- TimingData ret = data_;
- Clear();
- return ret;
-}
-
-uint32 TimingMetric::count() const {
- ObjectLock lock(this);
- uint32 ret = data_.count;
- return ret;
-}
-
-uint64 TimingMetric::sum() const {
- ObjectLock lock(this);
- uint64 ret = data_.sum;
- return ret;
-}
-
-uint64 TimingMetric::minimum() const {
- ObjectLock lock(this);
- uint64 ret = data_.minimum;
- return ret;
-}
-
-uint64 TimingMetric::maximum() const {
- ObjectLock lock(this);
- uint64 ret = data_.maximum;
- return ret;
-}
-
-uint64 TimingMetric::average() const {
- ObjectLock lock(this);
-
- uint64 ret = 0;
- if (0 == data_.count) {
- DCHECK_EQ(0U, data_.sum);
- } else {
- ret = data_.sum / data_.count;
- }
- return ret;
-}
-
-void TimingMetric::AddSample(uint64 time_ms) {
- ObjectLock lock(this);
- if (0 == data_.count) {
- data_.minimum = time_ms;
- data_.maximum = time_ms;
- } else {
- if (data_.minimum > time_ms)
- data_.minimum = time_ms;
- if (data_.maximum < time_ms)
- data_.maximum = time_ms;
- }
- data_.count++;
- data_.sum += time_ms;
-}
-
-void TimingMetric::AddSamples(uint64 count, uint64 total_time_ms) {
- if (0 == count)
- return;
-
- uint64 time_ms = total_time_ms / count;
-
- ObjectLock lock(this);
- if (0 == data_.count) {
- data_.minimum = time_ms;
- data_.maximum = time_ms;
- } else {
- if (data_.minimum > time_ms)
- data_.minimum = time_ms;
- if (data_.maximum < time_ms)
- data_.maximum = time_ms;
- }
-
- // TODO: truncation from 64 to 32 may occur here.
- DCHECK_LE(count, kuint32max);
- data_.count += static_cast<uint32>(count);
- data_.sum += total_time_ms;
-}
-
-void TimingMetric::Clear() {
- memset(&data_, 0, sizeof(data_));
-}
-
-void BoolMetric::Set(bool value) {
- ObjectLock lock(this);
- value_ = value ? kBoolTrue : kBoolFalse;
-}
-
-BoolMetric::TristateBoolValue BoolMetric::Reset() {
- ObjectLock lock(this);
- TristateBoolValue ret = value_;
- value_ = kBoolUnset;
- return ret;
-}
-
-void MetricCollection::Initialize() {
- DCHECK(!initialized());
- initialized_ = true;
-}
-
-void MetricCollection::Uninitialize() {
- DCHECK(initialized());
- initialized_ = false;
-}
-
-
-} // namespace stats_report
diff --git a/o3d/statsreport/metrics.h b/o3d/statsreport/metrics.h
deleted file mode 100644
index 876b29c..0000000
--- a/o3d/statsreport/metrics.h
+++ /dev/null
@@ -1,561 +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.
- */
-
-
-// Declares the interface to in-memory metrics capture
-#ifndef O3D_STATSREPORT_METRICS_H__
-#define O3D_STATSREPORT_METRICS_H__
-
-#include <iterator>
-#include "base/basictypes.h"
-#include "base/logging.h"
-#include "statsreport/common/highres_timer.h"
-
-// Macros to declare & define named & typed metrics.
-// Put declarations in headers or in cpp files, where you need access
-// to the metrics. For each declared metric, there must be precisely
-// one definition in a compilation unit someplace.
-
-// A count metric should be used to report anything that monotonically
-// increases.
-// Examples:
-// # event count
-// how often does this condition hit, this function get called
-// # aggregate sums
-// how many bytes are written
-#define DECLARE_METRIC_count(name) DECLARE_METRIC(CountMetric, name)
-#define DEFINE_METRIC_count(name) DEFINE_METRIC(CountMetric, name)
-
-// Use timing metrics to report on the performance of important things.
-// A timing metric will report the count of occurrences, as well as the
-// average, min and max times.
-// Samples are measured in milliseconds if you use the TIME_SCOPE macro
-// or the HighResTimer class to collect samples.
-#define DECLARE_METRIC_timing(name) DECLARE_METRIC(TimingMetric, name)
-#define DEFINE_METRIC_timing(name) DEFINE_METRIC(TimingMetric, name)
-
-// Collects a sample from here to the end of the current scope, and
-// adds the sample to the timing metric supplied
-#define TIME_SCOPE(timing) \
- stats_report::TimingSample __xxsample__(&timing)
-
-// Use integer metrics to report runtime values that fluctuate.
-// Examples:
-// # object count
-// How many objects of some type exist
-// # disk space or memory
-// How much disk space or memory is in use
-#define DECLARE_METRIC_integer(name) DECLARE_METRIC(IntegerMetric, name)
-#define DEFINE_METRIC_integer(name) DEFINE_METRIC(IntegerMetric, name)
-
-
-// Use boolean metrics to report the occurrence of important but rare events
-// or conditions. Note that a boolean metric is tri-state, so you typically
-// want to set it only in one direction, and typically to true.
-// Setting a boolean metric one way or another on a trigger event will report
-// the setting of the boolean immediately prior to reporting, which is
-// typically not what you want.
-#define DECLARE_METRIC_bool(name) DECLARE_METRIC(BoolMetric, name)
-#define DEFINE_METRIC_bool(name) DEFINE_METRIC(BoolMetric, name)
-
-
-// Implementation macros
-#define DECLARE_METRIC(type, name) \
- namespace o3d_statsreport { \
- extern stats_report::type metric_##name; \
- } \
- using o3d_statsreport::metric_##name
-
-#define DEFINE_METRIC(type, name) \
- namespace o3d_statsreport { \
- stats_report::type metric_##name(#name, \
- &stats_report::g_global_metric_storage); \
- } \
- using o3d_statsreport::metric_##name
-
-
-namespace stats_report {
-
-enum MetricType {
- // use zero for invalid, because global storage defaults to zero
- kInvalidType = 0,
- kCountType,
- kTimingType,
- kIntegerType,
- kBoolType
-};
-
-// fwd.
-struct MetricCollectionBase;
-class MetricCollection;
-class MetricBase;
-class IntegerMetricBase;
-class CountMetric;
-class TimingMetric;
-class IntegerMetric;
-class BoolMetric;
-
-// Base class for all stats instances.
-// Stats instances are chained together against a MetricCollection to
-// allow enumerating stats.
-//
-// MetricCollection is factored into a class to make it easier to unittest
-// the implementation.
-class MetricBase {
- public:
- // @name Safe downcasts
- // @{
- CountMetric *AsCount();
- TimingMetric *AsTiming();
- IntegerMetric *AsInteger();
- BoolMetric *AsBool();
-
- const CountMetric *AsCount() const;
- const TimingMetric *AsTiming() const;
- const IntegerMetric *AsInteger() const;
- const BoolMetric *AsBool() const;
- // @}
-
- // @name Accessors
- // @{
- MetricType type() const { return type_; }
- MetricBase *next() const { return next_; }
- const char *name() const { return name_; }
- // @}
-
- // TODO: does this need to be virtual?
- virtual ~MetricBase() = 0;
-
- protected:
- class ObjectLock;
- void Lock() const;
- void Unlock() const;
-
- // Constructs a MetricBase and adds to the provided MetricCollection.
- // @note Metrics can only be constructed up to the point where the
- // MetricCollection is initialized, and there's no locking performed.
- // The assumption is that outside unit tests, Metrics will we declared
- // as static/global variables, and initialized at static initialization
- // time - and static initialization is single-threaded.
- MetricBase(const char *name, MetricType type, MetricCollectionBase *coll);
-
- // Constructs a named typed MetricBase
- MetricBase(const char *name, MetricType type);
-
- // Our name
- char const *const name_;
-
- // type of this metric
- MetricType const type_;
-
- // chains to next stat instance
- MetricBase *const next_;
-
- // The collection we're created against
- MetricCollectionBase *const coll_;
-
- private:
- template <class SubType>
- SubType *SafeCast() {
- return SubType::kType == type() ? static_cast<SubType*>(this) : NULL;
- }
- template <class SubType>
- const SubType *SafeCast() const {
- return SubType::kType == type() ? static_cast<const SubType*>(this) : NULL;
- }
-
- DISALLOW_COPY_AND_ASSIGN(MetricBase);
-};
-
-// Must be a POD
-struct MetricCollectionBase {
- bool initialized_;
- MetricBase *first_;
-};
-
-// Inherit from base, which is a POD and can be initialized at link time.
-//
-// The global MetricCollection is aliased to a link-time initialized
-// instance of MetricCollectionBase, and must not extend the size of its
-// base class.
-class MetricCollection: public MetricCollectionBase {
- public:
- MetricCollection() {
- initialized_ = false;
- first_ = NULL;
- }
- ~MetricCollection() {
- DCHECK(NULL == first_);
- }
-
- // Initialize must be called after all metrics have been added to the
- // collection, but before enumerating it for e.g. aggregation or reporting.
- // The intent is that outside unit tests, there will only be the global
- // metrics collection, which will accrue all metrics defined with the
- // DEFINE_METRIC_* macros.
- // Typically you'd call Initialize very early in your main function, and
- // Uninitialize towards the end of main.
- // It is an error to Initialize() when the collection is initialized().
- void Initialize();
-
- // Uninitialize must be called before removing (deleting or deconstructing)
- // metrics from the collection.
- // It is an error to Uninitialize() when the collection is !initialized().
- void Uninitialize();
-
- MetricBase *first() const { return first_; }
- bool initialized() const { return initialized_; }
-
- private:
- using MetricCollectionBase::initialized_;
- using MetricCollectionBase::first_;
-
- // MetricBase is intimate with us
- friend class MetricBase;
-
- DISALLOW_COPY_AND_ASSIGN(MetricCollection);
-};
-
-// Implements a forward_iterator for MetricCollection.
-class MetricIterator: public std::iterator<std::forward_iterator_tag,
- MetricBase *> {
- public:
- MetricIterator() : curr_(NULL) {
- }
- // We need a non-explicit copy constructor to satisfy the iterator interface.
- MetricIterator(const MetricIterator &other) : curr_(other.curr_) {
- }
- explicit MetricIterator(const MetricCollection &coll) : curr_(coll.first()) {
- DCHECK(coll.initialized());
- }
-
- MetricBase *operator*() const {
- return curr_;
- }
- MetricBase *operator->() const {
- return curr_;
- }
- MetricIterator operator++() { // preincrement
- if (curr_)
- curr_ = curr_->next();
-
- return *this;
- }
- MetricIterator operator++(int dummy) { // postincrement
- MetricIterator ret(*this);
- ++*this;
- return ret;
- }
-
- private:
- MetricBase *curr_;
-};
-
-inline bool operator == (const MetricIterator &a, const MetricIterator &b) {
- return *a == *b;
-}
-inline bool operator != (const MetricIterator &a, const MetricIterator &b) {
- return !operator == (a, b);
-}
-
-// Globally defined counters are registered here
-extern MetricCollectionBase g_global_metric_storage;
-
-// And more conveniently accessed through here
-extern MetricCollection &g_global_metrics;
-
-// Base class for integer metrics
-class IntegerMetricBase: public MetricBase {
- public:
- // Sets the current value
- void Set(uint64 value);
-
- // Retrieves the current value
- uint64 value() const;
-
- void operator ++() { Increment(); }
- void operator ++(int dummy) { Increment(); }
- void operator +=(uint64 addend) { Add(addend); }
-
- protected:
- IntegerMetricBase(const char *name,
- MetricType type,
- MetricCollectionBase *coll)
- : MetricBase(name, type, coll), value_(0) {
- }
- IntegerMetricBase(const char *name, MetricType type, uint64 value)
- : MetricBase(name, type), value_(value) {
- }
-
- void Increment();
- void Decrement();
- void Add(uint64 value);
- void Subtract(uint64 value);
-
- uint64 value_;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(IntegerMetricBase);
-};
-
-// A count metric is a cumulative counter of events.
-class CountMetric: public IntegerMetricBase {
- public:
- // Our type.
- static const int kType = kCountType;
-
- CountMetric(const char *name, MetricCollectionBase *coll)
- : IntegerMetricBase(name, kCountType, coll) {
- }
-
- CountMetric(const char *name, uint64 value)
- : IntegerMetricBase(name, kCountType, value) {
- }
-
- // Nulls the metric and returns the current values.
- uint64 Reset();
-
- private:
- DISALLOW_COPY_AND_ASSIGN(CountMetric);
-};
-
-class TimingMetric: public MetricBase {
- public:
- static const int kType = kTimingType;
-
- struct TimingData {
- uint32 count;
- uint32 align; // allow access to the alignment gap between count and sum,
- // makes it easier to unittest.
- uint64 sum; // ms
- uint64 minimum; // ms
- uint64 maximum; // ms
- };
-
- TimingMetric(const char *name, MetricCollectionBase *coll)
- : MetricBase(name, kTimingType, coll) {
- Clear();
- }
-
- TimingMetric(const char *name, const TimingData &value)
- : MetricBase(name, kTimingType), data_(value) {
- }
-
- uint32 count() const;
- uint64 sum() const;
- uint64 minimum() const;
- uint64 maximum() const;
- uint64 average() const;
-
- // Adds a single sample to the metric
- // @param time_ms time (in milliseconds) for this sample
- void AddSample(uint64 time_ms);
-
- // Adds count samples to the metric
- // @note use this when capturing time over a variable number of items to
- // normalize e.g. download time per byte or KB. This records one sample
- // over count items, which is numerically more stable for the average
- // than dividing the captured time by the item count. As a side benefit
- // the timer will also record the item count.
- // @note if count == 0, no sample will be recorded
- // @param count number of samples to add
- // @param total_time_ms the total time consumed by all the "count" samples
- void AddSamples(uint64 count, uint64 total_time_ms);
-
- // Nulls the metric and returns the current values.
- TimingData Reset();
-
- private:
- void Clear();
-
- TimingData data_;
-
- DISALLOW_COPY_AND_ASSIGN(TimingMetric);
-};
-
-// A convenience class to sample the time from construction to destruction
-// against a given timing metric.
-class TimingSample {
- public:
- // @param timing the metric the sample is to be tallied against
- explicit TimingSample(TimingMetric *timing) : timing_(timing), count_(1) {
- DCHECK(NULL != timing);
- }
-
- // @param timing the metric the sample is to be tallied against
- // @param item_count count of items processed, used to divide the sampled
- // time so as to capture time per item, which is often a better measure
- // than the total time over a varying number of items.
- TimingSample(TimingMetric *timing, uint32 item_count) : timing_(timing),
- count_(item_count) {
- DCHECK(NULL != timing);
- }
-
- ~TimingSample() {
- // We discard samples with a zero count
- if (1 == count_)
- timing_->AddSample(timer_.GetElapsedMs());
- else
- timing_->AddSamples(count_, timer_.GetElapsedMs());
- }
-
- // @name Accessors
- // @{
- uint32 count() const { return count_; }
- void set_count(uint32 count) { count_ = count; }
- // @}
-
- private:
- // Collects the sample for us.
- HighresTimer timer_;
-
- // The metric we tally against.
- TimingMetric *timing_;
-
- // The item count we divide the captured time by
- uint32 count_;
-
- DISALLOW_COPY_AND_ASSIGN(TimingSample);
-};
-
-// An integer metric is used to sample values that vary over time.
-// On aggregation the instantaneous value of the integer metric is captured.
-class IntegerMetric: public IntegerMetricBase {
- public:
- static const int kType = kIntegerType;
-
- IntegerMetric(const char *name, MetricCollectionBase *coll)
- : IntegerMetricBase(name, kIntegerType, coll) {
- }
-
- IntegerMetric(const char *name, uint64 value)
- : IntegerMetricBase(name, kIntegerType, value) {
- }
-
- void operator = (uint64 value) { Set(value); }
-
- void operator --() { Decrement(); }
- void operator --(int dummy) { Decrement(); }
- void operator -=(uint64 sub) { Subtract(sub); }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(IntegerMetric);
-};
-
-// A bool metric is tri-state, and can be:
-// - unset,
-// - true or
-// - false
-// to match other metrics, which are implicitly unset if they've not changed
-// from their initial value.
-class BoolMetric: public MetricBase {
- public:
- static const int kType = kBoolType;
-
- // Values we can take
- enum TristateBoolValue {
- kBoolUnset = -1,
- kBoolFalse,
- kBoolTrue,
- };
-
- BoolMetric(const char *name, MetricCollectionBase *coll)
- : MetricBase(name, kBoolType, coll), value_(kBoolUnset) {
- }
-
- BoolMetric(const char *name, uint32 value)
- : MetricBase(name, kBoolType) {
- switch (value) {
- case kBoolFalse:
- case kBoolTrue:
- value_ = static_cast<TristateBoolValue>(value);
- break;
-
- default:
- DCHECK(false && "Unexpected tristate bool value on construction");
- value_ = kBoolUnset;
- }
- }
-
- // Sets the flag to the provided value.
- void Set(bool value);
-
- void operator = (bool value) {
- Set(value);
- }
-
- // Nulls the metric and returns the current values.
- TristateBoolValue Reset();
-
- // Returns the current value - not threadsafe.
- TristateBoolValue value() const { return value_; }
-
- private:
- TristateBoolValue value_;
-
- DISALLOW_COPY_AND_ASSIGN(BoolMetric);
-};
-
-inline CountMetric *MetricBase::AsCount() {
- return SafeCast<CountMetric>();
-}
-
-inline TimingMetric *MetricBase::AsTiming() {
- return SafeCast<TimingMetric>();
-}
-
-inline IntegerMetric *MetricBase::AsInteger() {
- return SafeCast<IntegerMetric>();
-}
-
-inline BoolMetric *MetricBase::AsBool() {
- return SafeCast<BoolMetric>();
-}
-
-inline const CountMetric *MetricBase::AsCount() const {
- return SafeCast<CountMetric>();
-}
-
-inline const TimingMetric *MetricBase::AsTiming() const {
- return SafeCast<TimingMetric>();
-}
-
-inline const IntegerMetric *MetricBase::AsInteger() const {
- return SafeCast<IntegerMetric>();
-}
-
-inline const BoolMetric *MetricBase::AsBool() const {
- return SafeCast<BoolMetric>();
-}
-
-} // namespace stats_report
-
-#endif // O3D_STATSREPORT_METRICS_H__
diff --git a/o3d/statsreport/metrics_unittest.cc b/o3d/statsreport/metrics_unittest.cc
deleted file mode 100644
index 48b1ef0..0000000
--- a/o3d/statsreport/metrics_unittest.cc
+++ /dev/null
@@ -1,398 +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 "build/build_config.h"
-
-#ifndef OS_WIN
-#include <unistd.h>
-#endif
-
-// Metrics report unit testing
-#include <new>
-#include <algorithm>
-#include "gtest/gtest.h"
-#include "metrics.h"
-
-#ifdef OS_WIN
-#define SLEEP_ONE_SECOND() ::Sleep(1000)
-#else
-#define SLEEP_ONE_SECOND() ::sleep(1)
-#endif
-
-DECLARE_METRIC_count(count);
-DEFINE_METRIC_count(count);
-
-DECLARE_METRIC_timing(timing);
-DEFINE_METRIC_timing(timing);
-
-DECLARE_METRIC_integer(integer);
-DEFINE_METRIC_integer(integer);
-
-DECLARE_METRIC_bool(bool);
-DEFINE_METRIC_bool(bool);
-
-using ::stats_report::BoolMetric;
-using ::stats_report::CountMetric;
-using ::stats_report::IntegerMetric;
-using ::stats_report::MetricBase;
-using ::stats_report::MetricCollection;
-using ::stats_report::MetricCollectionBase;
-using ::stats_report::MetricIterator;
-using ::stats_report::TimingMetric;
-using ::stats_report::TimingSample;
-using ::stats_report::kBoolType;
-using ::stats_report::kCountType;
-using ::stats_report::kIntegerType;
-using ::stats_report::kTimingType;
-
-
-class MetricsTest: public testing::Test {
- protected:
- MetricCollection coll_;
-};
-
-class MetricsEnumTest: public MetricsTest {
- public:
- virtual void SetUp() {
- coll_.Initialize();
- }
-
- virtual void TearDown() {
- coll_.Uninitialize();
- }
-
- protected:
- MetricsEnumTest(): count_("count", &coll_), timing_("timing", &coll_),
- integer_("integer", &coll_), bool_("bool", &coll_) {
- }
-
- CountMetric count_;
- TimingMetric timing_;
- IntegerMetric integer_;
- BoolMetric bool_;
-};
-
-
-// Validates that the above-declared metrics are available
-// in the expected namespace
-TEST_F(MetricsTest, Globals) {
- EXPECT_EQ(0u, ::metric_count.Reset());
- TimingMetric::TimingData data = ::metric_timing.Reset();
- EXPECT_EQ(0u, data.count);
- EXPECT_EQ(0u, data.maximum);
- EXPECT_EQ(0u, data.minimum);
- EXPECT_EQ(0u, data.sum);
-
- EXPECT_EQ(0u, ::metric_integer.value());
- EXPECT_EQ(BoolMetric::kBoolUnset, ::metric_bool.Reset());
-
- // Check for correct initialization
- EXPECT_STREQ("count", metric_count.name());
- EXPECT_STREQ("timing", metric_timing.name());
- EXPECT_STREQ("integer", metric_integer.name());
- EXPECT_STREQ("bool", metric_bool.name());
-}
-
-
-// make GUnit happy
-inline std::ostream &operator << (std::ostream &str, const MetricIterator &it) {
- str << std::hex << reinterpret_cast<void*>(*it);
- return str;
-}
-
-TEST_F(MetricsTest, CollectionInitialization) {
- // The global MetricCollection is aliased to zero memory so as to ensure
- // no initialization order snafus. If an initialized MetricCollection
- // sets any of its storage to non-zero, there's a good chance that e.g. a
- // vtbl has snuck in there, which must not happen
- char buf1[sizeof(MetricCollection)] = { 0 };
- char buf2[sizeof(MetricCollection)] = { 0 };
-
- // Placement new a MetricCollection to one of the buffers
- new (buf1) MetricCollection();
-
- // and check they're still equivalent
- EXPECT_EQ(0, memcmp(buf1, buf2, sizeof(MetricCollection)));
-
- // MetricCollection must not extend MetricCollectionBase in size
- EXPECT_EQ(sizeof(MetricCollection), sizeof(MetricCollectionBase));
-}
-
-TEST_F(MetricsTest, Count) {
- CountMetric foo("foo", &coll_);
-
- EXPECT_EQ(0u, foo.Reset());
- EXPECT_EQ(kCountType, foo.type());
- ASSERT_TRUE(NULL != foo.AsCount());
- ASSERT_TRUE(NULL == foo.AsTiming());
- ASSERT_TRUE(NULL == foo.AsInteger());
- ASSERT_TRUE(NULL == foo.AsBool());
-
- ++foo;
- EXPECT_EQ(1u, foo.value());
- foo++;
- EXPECT_EQ(2u, foo.value());
-
- foo += 100;
- EXPECT_EQ(102u, foo.value());
-}
-
-TEST_F(MetricsTest, Timing) {
- TimingMetric foo("foo", &coll_);
-
- EXPECT_EQ(kTimingType, foo.type());
- ASSERT_TRUE(NULL == foo.AsCount());
- ASSERT_TRUE(NULL != foo.AsTiming());
- ASSERT_TRUE(NULL == foo.AsInteger());
- ASSERT_TRUE(NULL == foo.AsBool());
-
- foo.AddSample(100);
- foo.AddSample(50);
-
- EXPECT_EQ(2u, foo.count());
- EXPECT_EQ(150u, foo.sum());
- EXPECT_EQ(100u, foo.maximum());
- EXPECT_EQ(50u, foo.minimum());
- EXPECT_EQ(75u, foo.average());
-
- TimingMetric::TimingData data = foo.Reset();
- EXPECT_EQ(2u, data.count);
- EXPECT_EQ(150u, data.sum);
- EXPECT_EQ(100u, data.maximum);
- EXPECT_EQ(50u, data.minimum);
-
- EXPECT_EQ(0u, foo.count());
- EXPECT_EQ(0u, foo.sum());
- EXPECT_EQ(0u, foo.maximum());
- EXPECT_EQ(0u, foo.minimum());
- EXPECT_EQ(0u, foo.average());
-
- // Test counted samples
- foo.AddSamples(10u, 1000);
- foo.AddSamples(10u, 500);
- EXPECT_EQ(20u, foo.count());
- EXPECT_EQ(1500u, foo.sum());
- EXPECT_EQ(100u, foo.maximum());
- EXPECT_EQ(50u, foo.minimum());
- EXPECT_EQ(75u, foo.average());
-}
-
-TEST_F(MetricsTest, TimingSample) {
- TimingMetric foo("foo", &coll_);
-
- // add a sample to foo
- {
- TimingSample sample(&foo);
-
- SLEEP_ONE_SECOND();
- }
-
- TimingMetric::TimingData data = foo.Reset();
-
- // Should be precisely one sample in there
- EXPECT_EQ(1u, data.count);
-
- // again, this time with a non-unity count
- {
- TimingSample sample(&foo, 2);
-
- EXPECT_EQ(2u, sample.count());
- SLEEP_ONE_SECOND();
- }
-
- data = foo.Reset();
-
- // Should be precisely two samples in there
- EXPECT_EQ(2u, data.count);
-
- // now with zero count
- {
- TimingSample sample(&foo, 0);
- }
-
- data = foo.Reset();
-
- // Should be no samples in there
- EXPECT_EQ(0u, data.count);
-}
-
-TEST_F(MetricsTest, Integer) {
- IntegerMetric foo("foo", &coll_);
-
- EXPECT_EQ(kIntegerType, foo.type());
- ASSERT_TRUE(NULL == foo.AsCount());
- ASSERT_TRUE(NULL == foo.AsTiming());
- ASSERT_TRUE(NULL != foo.AsInteger());
- ASSERT_TRUE(NULL == foo.AsBool());
-
- EXPECT_EQ(0u, foo.value());
- foo.Set(1005);
- EXPECT_EQ(1005u, foo.value());
- foo = 1009UL;
- EXPECT_EQ(1009u, foo.value());
-
- foo.Set(0);
-
- ++foo;
- EXPECT_EQ(1u, foo.value());
- foo++;
- EXPECT_EQ(2u, foo.value());
-
- foo += 100;
- EXPECT_EQ(102u, foo.value());
-
- foo -= 100;
- EXPECT_EQ(2u, foo.value());
- foo--;
- EXPECT_EQ(1u, foo.value());
- --foo;
- EXPECT_EQ(0u, foo.value());
-}
-
-TEST_F(MetricsTest, Bool) {
- BoolMetric foo("foo", &coll_);
-
- EXPECT_EQ(kBoolType, foo.type());
- ASSERT_TRUE(NULL == foo.AsCount());
- ASSERT_TRUE(NULL == foo.AsTiming());
- ASSERT_TRUE(NULL == foo.AsInteger());
- ASSERT_TRUE(NULL != foo.AsBool());
-
- EXPECT_EQ(BoolMetric::kBoolUnset, foo.Reset());
- foo.Set(true);
- EXPECT_EQ(BoolMetric::kBoolTrue, foo.Reset());
- foo.Set(false);
- EXPECT_EQ(BoolMetric::kBoolFalse, foo.Reset());
- EXPECT_EQ(BoolMetric::kBoolUnset, foo.Reset());
-}
-
-TEST_F(MetricsEnumTest, Enumeration) {
- MetricBase *metrics[] = {
- &count_,
- &timing_,
- &integer_,
- &bool_,
- };
-
- int limit = sizeof(metrics) / sizeof(metrics[0]);
- for (int i = 0; i < limit; ++i) {
- MetricBase *stat = metrics[i];
- MetricBase *curr = coll_.first();
-
- for (; NULL != curr; curr = curr->next()) {
- if (stat == curr)
- break;
- }
-
- // if NULL, we didn't find our counter
- EXPECT_TRUE(NULL != curr);
- }
-}
-
-TEST_F(MetricsEnumTest, Iterator) {
- typedef MetricBase *MetricBasePtr;
- MetricBasePtr metrics[] = { &count_, &timing_, &integer_, &bool_, };
- int num_stats = arraysize(metrics);
-
- MetricIterator it(coll_), end;
- EXPECT_NE(it, end);
-
- // copy construction
- EXPECT_EQ(it, MetricIterator(it));
- EXPECT_EQ(end, MetricIterator(end));
-
- // # of iterations
- int i = 0;
- while (it++ != end)
- ++i;
- ASSERT_EQ(num_stats, i);
- ASSERT_EQ(end, it);
-
- // increment past end is idempotent
- ++it;
- ASSERT_EQ(end, it);
-
- // Check that we return no garbage or nonsense
- for (it = MetricIterator(coll_); it != end; ++it) {
- MetricBasePtr *stats_end = &metrics[num_stats];
- EXPECT_NE(stats_end, std::find(metrics, stats_end, *it));
- }
-
- // and that all metrics can be found
- int limit = sizeof(metrics) / sizeof(metrics[0]);
- for (int i = 0; i < limit; ++i) {
- MetricBase *stat = metrics[i];
-
- EXPECT_EQ(stat, *std::find(MetricIterator(coll_), end, stat));
- }
-}
-
-TEST_F(MetricsTest, SimpleConstruction) {
- const CountMetric c("c", 100);
-
- EXPECT_EQ(100u, c.value());
- EXPECT_EQ(kCountType, c.type());
- EXPECT_STREQ("c", c.name());
- EXPECT_TRUE(NULL == c.next());
-
- TimingMetric::TimingData data = { 10, 0, 1000, 10, 500 };
- const TimingMetric t("t", data);
-
- EXPECT_EQ(10u, t.count());
- EXPECT_EQ(1000u, t.sum());
- EXPECT_EQ(10u, t.minimum());
- EXPECT_EQ(500u, t.maximum());
- EXPECT_EQ(kTimingType, t.type());
- EXPECT_STREQ("t", t.name());
- EXPECT_TRUE(NULL == t.next());
-
- const IntegerMetric i("i", 200);
-
- EXPECT_EQ(200u, i.value());
- EXPECT_EQ(kIntegerType, i.type());
- EXPECT_STREQ("i", i.name());
- EXPECT_TRUE(NULL == i.next());
-
- const BoolMetric bool_true("bool_true", BoolMetric::kBoolTrue);
-
- EXPECT_EQ(BoolMetric::kBoolTrue, bool_true.value());
- EXPECT_EQ(kBoolType, bool_true.type());
- EXPECT_STREQ("bool_true", bool_true.name());
- EXPECT_TRUE(NULL == bool_true.next());
-
- const BoolMetric bool_false("bool_false", BoolMetric::kBoolFalse);
-
- EXPECT_EQ(BoolMetric::kBoolFalse, bool_false.value());
- EXPECT_EQ(kBoolType, bool_false.type());
- EXPECT_STREQ("bool_false", bool_false.name());
- EXPECT_TRUE(NULL == bool_false.next());
-}
diff --git a/o3d/statsreport/persistent_iterator-win32.cc b/o3d/statsreport/persistent_iterator-win32.cc
deleted file mode 100644
index edf687b..0000000
--- a/o3d/statsreport/persistent_iterator-win32.cc
+++ /dev/null
@@ -1,163 +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.
- */
-
-
-// Iterator over persisted metrics
-#include "persistent_iterator-win32.h"
-
-namespace stats_report {
-
-void PersistentMetricsIteratorWin32::Next() {
- current_value_.reset();
-
- // Try to open the top-level key if we didn't already.
- if (NULL == key_.m_hKey) {
- HKEY parent_key = is_machine_ ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
- LONG err = key_.Open(parent_key, key_name_, KEY_READ);
- if (err != ERROR_SUCCESS)
- return;
- }
-
- // Loop until we find a value
- while (state_ != kFinished) {
- if (NULL == sub_key_.m_hKey) {
- const wchar_t *subkey_name = NULL;
- switch (state_) {
- case kUninitialized:
- state_ = kCounts;
- subkey_name = kCountsKeyName;
- break;
- case kCounts:
- state_ = kTimings;
- subkey_name = kTimingsKeyName;
- break;
- case kTimings:
- state_ = kIntegers;
- subkey_name = kIntegersKeyName;
- break;
- case kIntegers:
- state_ = kBooleans;
- subkey_name = kBooleansKeyName;
- break;
- case kBooleans:
- state_ = kFinished;
- break;
- case kFinished:
- break;
- }
-
- if (NULL != subkey_name) {
- LONG err = sub_key_.Open(key_, subkey_name, KEY_READ);
- // go around the loop on error to try the next key type
- if (ERROR_SUCCESS != err)
- continue;
- }
-
- // reset value enumeration
- value_index_ = 0;
- }
-
- if (state_ != kFinished) {
- DCHECK(NULL != sub_key_.m_hKey);
- CString wide_value_name;
- DWORD value_name_len = 255;
- DWORD value_type = 0;
- BYTE buf[sizeof(TimingMetric::TimingData)];
- DWORD value_len = sizeof(buf);
-
- // Get the next key and value
- LONG err = ::RegEnumValue(sub_key_,
- value_index_,
- CStrBuf(wide_value_name, value_name_len),
- &value_name_len,
- 0,
- &value_type,
- buf,
- &value_len);
-
- ++value_index_;
-
- if (ERROR_NO_MORE_ITEMS == err) {
- // done with this subkey, go around again
- sub_key_.Close();
- continue;
- } else if (ERROR_SUCCESS != err) {
- // some other error, broken into a separate case for ease of debugging
- DCHECK(false && "Unexpected error during reg value enumeration");
- } else {
- DCHECK(ERROR_SUCCESS == err);
-
- // convert value to ASCII
- current_value_name_ = wide_value_name;
-
- switch (state_) {
- case kCounts:
- if (value_len != sizeof(uint64))
- continue;
- current_value_.reset(
- new CountMetric(current_value_name_ .GetString(),
- *reinterpret_cast<uint64*>(&buf[0])));
- break;
- case kTimings:
- if (value_len != sizeof(TimingMetric::TimingData))
- continue;
- current_value_.reset(
- new TimingMetric(
- current_value_name_.GetString(),
- *reinterpret_cast<TimingMetric::TimingData*>(&buf[0])));
- break;
- case kIntegers:
- if (value_len != sizeof(uint64))
- continue;
- current_value_.reset(new IntegerMetric(
- current_value_name_.GetString(),
- *reinterpret_cast<uint64*>(&buf[0])));
- break;
- case kBooleans:
- if (value_len != sizeof(uint32))
- continue;
- current_value_.reset(
- new BoolMetric(current_value_name_.GetString(),
- *reinterpret_cast<uint32*>(&buf[0])));
- break;
- default:
- DCHECK(false && "Impossible state during reg value enumeration");
- break;
- }
-
- if (current_value_.get())
- return;
- }
- }
- }
-}
-
-} // namespace stats_report
diff --git a/o3d/statsreport/persistent_iterator-win32.h b/o3d/statsreport/persistent_iterator-win32.h
deleted file mode 100644
index ceaf851..0000000
--- a/o3d/statsreport/persistent_iterator-win32.h
+++ /dev/null
@@ -1,152 +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.
- */
-
-
-// Iterator over persisted metrics
-#ifndef O3D_STATSREPORT_PERSISTENT_ITERATOR_WIN32_H__
-#define O3D_STATSREPORT_PERSISTENT_ITERATOR_WIN32_H__
-
-#include <atlbase.h>
-#include <atlstr.h>
-#include <iterator>
-#include "base/scoped_ptr.h"
-#include "metrics.h"
-#include "const-win32.h"
-
-namespace stats_report {
-
-// Forward iterator for persisted metrics
-class PersistentMetricsIteratorWin32
- : public std::iterator<std::forward_iterator_tag, const MetricBase *> {
- public:
- // @param app_name see MetricsAggregatorWin32
- explicit PersistentMetricsIteratorWin32(const wchar_t *app_name)
- : state_(kUninitialized),
- is_machine_(false) {
- key_name_.Format(kStatsKeyFormatString, app_name);
- Next();
- }
-
- // @param app_name see MetricsAggregatorWin32
- // @param is_machine specifies the registry hive
- PersistentMetricsIteratorWin32(const wchar_t *app_name, bool is_machine)
- : state_(kUninitialized),
- is_machine_(is_machine) {
- key_name_.Format(kStatsKeyFormatString, app_name);
- Next();
- }
-
- // Constructs the at-end iterator
- PersistentMetricsIteratorWin32() : state_(kUninitialized) {
- }
-
- MetricBase *operator* () {
- return Current();
- }
- MetricBase *operator-> () {
- return Current();
- }
-
- // Preincrement, we don't implement postincrement because we don't
- // want to deal with making iterators copyable, comparable etc.
- PersistentMetricsIteratorWin32 &operator++() {
- Next();
-
- return (*this);
- }
-
- // Compare for equality with o.
- bool equals(const PersistentMetricsIteratorWin32 &o) const {
- // compare equal to self, and end iterators compare equal
- if ((this == &o) || (NULL == current_value_.get() &&
- NULL == o.current_value_.get()))
- return true;
-
- return false;
- }
-
- private:
- MetricBase *Current() {
- DCHECK(current_value_.get());
- return current_value_.get();
- }
-
- enum IterationState {
- kUninitialized,
- kCounts,
- kTimings,
- kIntegers,
- kBooleans,
- kFinished,
- };
-
- // Walk to the next key/value under iteration
- void Next();
-
- // Keeps track of which subkey we're iterating over
- IterationState state_;
-
- // The full path from HKCU to the key we iterate over
- CString key_name_;
-
- // The top-level key we're iterating over, valid only
- // after first call to Next().
- CRegKey key_;
-
- // The subkey we're currently enumerating over
- CRegKey sub_key_;
-
- // Current value we're indexing over
- DWORD value_index_;
-
- // Name of the value under the iterator
- CStringA current_value_name_;
-
- // The metric under the iterator
- scoped_ptr<MetricBase> current_value_;
-
- // Specifies HKLM or HKCU, respectively.
- bool is_machine_;
-};
-
-inline bool operator == (const PersistentMetricsIteratorWin32 &a,
- const PersistentMetricsIteratorWin32 &b) {
- return a.equals(b);
-}
-
-inline bool operator != (const PersistentMetricsIteratorWin32 &a,
- const PersistentMetricsIteratorWin32 &b) {
- return !a.equals(b);
-}
-
-} // namespace stats_report
-
-#endif // O3D_STATSREPORT_PERSISTENT_ITERATOR_WIN32_H__
diff --git a/o3d/statsreport/persistent_iterator-win32_unittest.cc b/o3d/statsreport/persistent_iterator-win32_unittest.cc
deleted file mode 100644
index 69e6f55..0000000
--- a/o3d/statsreport/persistent_iterator-win32_unittest.cc
+++ /dev/null
@@ -1,164 +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 <atlbase.h>
-#include <atlcom.h>
-#include <iterator>
-#include <map>
-#include "gtest/gtest.h"
-#include "const-win32.h"
-#include "aggregator-win32_unittest.h"
-#include "persistent_iterator-win32.h"
-
-using ::stats_report::BoolMetric;
-using ::stats_report::CountMetric;
-using ::stats_report::IntegerMetric;
-using ::stats_report::MetricBase;
-using ::stats_report::MetricCollection;
-using ::stats_report::MetricCollectionBase;
-using ::stats_report::MetricIterator;
-using ::stats_report::MetricsAggregatorWin32;
-using ::stats_report::PersistentMetricsIteratorWin32;
-using ::stats_report::TimingMetric;
-using ::stats_report::TimingSample;
-using ::stats_report::kBoolType;
-using ::stats_report::kCountType;
-using ::stats_report::kIntegerType;
-using ::stats_report::kInvalidType;
-using ::stats_report::kTimingType;
-
-namespace {
-
-class PersistentMetricsIteratorWin32Test: public MetricsAggregatorWin32Test {
- public:
- bool WriteStats() {
- // put some persistent metrics into the registry
- MetricsAggregatorWin32 agg(coll_, kAppName);
- AddStats();
- bool ret = agg.AggregateMetrics();
-
- // Reset the stats, we should now have the same stats
- // in our collection as in registry.
- AddStats();
-
- return ret;
- }
-
- typedef std::map<std::string, MetricBase*> MetricsMap;
- void IndexMetrics(MetricsMap *metrics) {
- // build a map over the metrics in our collection
- MetricIterator it(coll_), end;
-
- for (; it != end; ++it) {
- metrics->insert(std::make_pair(std::string(it->name()), *it));
- }
- }
-};
-
-// compare two metrics instances for equality
-bool equals(MetricBase *a, MetricBase *b) {
- if (!a || !b)
- return false;
-
- if (a->type() != b->type() || 0 != strcmp(a->name(), b->name()))
- return false;
-
- switch (a->type()) {
- case kCountType:
- return a->AsCount()->value() == b->AsCount()->value();
- break;
- case kTimingType: {
- TimingMetric *at = a->AsTiming();
- TimingMetric *bt = b->AsTiming();
-
- return at->count() == bt->count() &&
- at->sum() == bt->sum() &&
- at->minimum() == bt->minimum() &&
- at->maximum() == bt->maximum();
- break;
- }
- case kIntegerType:
- return a->AsInteger()->value() == b->AsInteger()->value();
- break;
- case kBoolType:
- return a->AsBool()->value() == b->AsBool()->value();
- break;
- case kInvalidType:
- default:
- LOG(FATAL) << "Impossible metric type";
- }
-
- return false;
-}
-
-} // namespace
-
-TEST_F(PersistentMetricsIteratorWin32Test, Basic) {
- EXPECT_TRUE(WriteStats());
- PersistentMetricsIteratorWin32 a;
- PersistentMetricsIteratorWin32 b;
- PersistentMetricsIteratorWin32 c(kAppName);
-
- EXPECT_TRUE(a == b);
- EXPECT_TRUE(b == a);
-
- EXPECT_FALSE(a == c);
- EXPECT_FALSE(b == c);
- EXPECT_FALSE(c == a);
- EXPECT_FALSE(c == b);
-
- ++a;
- EXPECT_TRUE(a == b);
- EXPECT_TRUE(b == a);
-}
-
-// Test to see whether we can reliably roundtrip metrics through
-// the registry without molestation
-TEST_F(PersistentMetricsIteratorWin32Test, UnmolestedValues) {
- EXPECT_TRUE(WriteStats());
-
- MetricsMap metrics;
- IndexMetrics(&metrics);
-
- PersistentMetricsIteratorWin32 it(kAppName), end;
- int count = 0;
- for (; it != end; ++it) {
- MetricsMap::iterator found = metrics.find(it->name());
-
- // make sure we found it, and that it's unmolested in value
- EXPECT_TRUE(found != metrics.end() && equals(found->second, *it));
- count++;
- }
-
- // Did we visit all metrics?
- EXPECT_EQ(count, metrics.size());
-}
diff --git a/o3d/statsreport/statsreport.gyp b/o3d/statsreport/statsreport.gyp
deleted file mode 100644
index 7e106b4..0000000
--- a/o3d/statsreport/statsreport.gyp
+++ /dev/null
@@ -1,130 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- },
- 'includes': [
- '../build/common.gypi',
- ],
- 'target_defaults': {
- 'include_dirs': [
- '..',
- '../..',
- '../../<(gtestdir)',
- ],
- },
- 'targets': [],
- 'conditions': [
- ['OS!="linux"',
- {
- 'targets': [
- {
- 'target_name': 'o3dStatsReport',
- 'type': 'static_library',
- 'sources': [
- 'aggregator-mac.h',
- 'aggregator-mac.mm',
- 'aggregator-win32.cc',
- 'aggregator-win32.h',
- 'aggregator.cc',
- 'aggregator.h',
- 'common/const_product.h',
- 'common/highres_timer-linux.cc',
- 'common/highres_timer-linux.h',
- 'common/highres_timer-mac.cc',
- 'common/highres_timer-mac.h',
- 'common/highres_timer-win32.cc',
- 'common/highres_timer-win32.h',
- 'common/highres_timer.h',
- 'const-mac.h',
- 'const-mac.mm',
- 'const-win32.cc',
- 'const-win32.h',
- 'const_server.h',
- 'formatter.cc',
- 'formatter.h',
- 'lock.h',
- 'metrics.cc',
- 'metrics.h',
- 'persistent_iterator-win32.cc',
- 'persistent_iterator-win32.h',
- 'uploader-mac.mm',
- 'uploader-win32.cc',
- 'uploader.h',
- 'uploader_aggregation-mac.mm',
- 'uploader_aggregation-win32.cc',
- 'util-win32.h',
- ],
- 'conditions': [
- ['OS != "win"',
- {
- 'sources/': [
- ['exclude', '(-win32)\.(cc|h)$'],
- ],
- },
- ],
- ['OS != "linux"',
- {
- 'sources/': [
- ['exclude', '(-linux)\.(cc|h)$'],
- ],
- },
- ],
- ['OS != "mac"',
- {
- 'sources/': [
- ['exclude', '(-mac)\.(cc|mm|h)$'],
- ],
- },
- ],
- ],
- },
- {
- 'target_name': 'o3dStatsReportTest',
- 'type': 'none',
- 'dependencies': [
- 'o3dStatsReport',
- ],
- 'direct_dependent_settings': {
- 'sources': [
- 'aggregator-win32_unittest.cc',
- 'aggregator-win32_unittest.h',
- 'aggregator_unittest.cc',
- 'aggregator_unittest.h',
- 'common/highres_timer_unittest.cc',
- 'formatter_unittest.cc',
- 'metrics_unittest.cc',
- 'persistent_iterator-win32_unittest.cc',
- ],
- 'conditions': [
- ['OS != "win"',
- {
- 'sources/': [
- ['exclude', '(-win32)_unittest\.(cc|h)$'],
- ],
- },
- ],
- ['OS != "mac"',
- {
- 'sources/': [
- ['exclude', '(-mac)_unittest\.(cc|mm|h)$'],
- ],
- },
- ],
- ],
- },
- },
- ],
- },
- ],
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/statsreport/uploader-mac.mm b/o3d/statsreport/uploader-mac.mm
deleted file mode 100644
index 803b800..0000000
--- a/o3d/statsreport/uploader-mac.mm
+++ /dev/null
@@ -1,97 +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.
- */
-
-
-// Helper class to manage the process of uploading metrics.
-
-#import <Cocoa/Cocoa.h>
-#include "base/logging.h"
-
-#include "statsreport/uploader.h"
-#include "statsreport/aggregator-mac.h"
-#include "statsreport/const-mac.h"
-#include "statsreport/formatter.h"
-#include "statsreport/common/const_product.h"
-#include "statsreport/const_server.h"
-
-const float kTimeOutInterval = 10.0;
-
-namespace stats_report {
- // TODO: Refactor to avoid cross platform code duplication.
-
-bool UploadMetrics(const char* extra_url_data, const char* user_agent,
- const char *content) {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
-
-
- // TODO: refactor to where there's a platform-independent HTTP
- // interface to the ConnectionManager and pass it through into here.
- DLOG(INFO) << "Uploading metrics . . . ";
-
- NSString *url_string =
- [NSString stringWithFormat:@"http://%s:%d/%s?%s=%s&%s=%s&%s",
- METRICS_SERVER_NAME,
- METRICS_SERVER_PORT,
- METRICS_SERVER_PATH,
- kStatsServerParamSourceId,
- PRODUCT_NAME_STRING,
- kStatsServerParamVersion,
- PRODUCT_VERSION_STRING,
- extra_url_data];
- DLOG(INFO) << "Url: " << [url_string UTF8String];
-
- NSURL *url = [NSURL URLWithString:url_string];
-
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
-
- // don't send cookies or user-identifiable info with our request.
- [request setHTTPShouldHandleCookies:NO];
- [request setTimeoutInterval:kTimeOutInterval];
- int content_len = (content == NULL) ? 0 : strlen(content);
- if (content_len) {
- NSData *content_data = [NSData dataWithBytesNoCopy:(void*)content
- length:content_len];
- [request setHTTPMethod:@"POST"];
- [request setHTTPBody:content_data];
- }
- NSURLResponse *response = nil;
- NSError *error = nil;
-
- [NSURLConnection sendSynchronousRequest:request
- returningResponse:&response
- error:&error];
-
- [pool release];
-
- return (error == nil);
-}
-
-} // namespace stats_report
diff --git a/o3d/statsreport/uploader-posix.cc b/o3d/statsreport/uploader-posix.cc
deleted file mode 100644
index 7275b81..0000000
--- a/o3d/statsreport/uploader-posix.cc
+++ /dev/null
@@ -1,76 +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.
- */
-
-
-// Helper class to manage the process of uploading metrics.
-#include "backend/serverconnectionmanager.h"
-#include "statsreport/common/const_product.h"
-#include "statsreport/const_server.h"
-#include "iobuffer/iobuffer-inl.h"
-#include "statsreport/aggregator-posix-inl.h"
-#include "statsreport/const-posix.h"
-#include "statsreport/formatter.h"
-#include "statsreport/uploader.h"
-
-
-DECLARE_int32(metrics_aggregation_interval);
-DECLARE_int32(metrics_upload_interval);
-DECLARE_string(metrics_server_name);
-DECLARE_int32(metrics_server_port);
-
-using stats_report::Formatter;
-using stats_report::MetricsAggregatorPosix;
-
-namespace {
-
-bool UploadMetrics(const char* extra_url_data, const char* user_agent,
- const char *content) {
- o3d_transfer_service::ServerConnectionManager scm(
- METRICS_SERVER_NAME,
- METRICS_SERVER_PORT,
- false,
- PRODUCT_VERSION_STRING,
- PRODUCT_NAME_STRING);
-
- PathString path = PathString("/" METRICS_SERVER_PATH "?") +
- kStatsServerParamSourceId + "=" +
- PRODUCT_NAME_STRING + "&" +
- kStatsServerParamVersion + "=" +
- PRODUCT_VERSION_STRING + "&" +
- extra_url_data;
-
- IOBuffer buffer_out;
- o3d_transfer_service::HttpResponse response;
- return scm.SimplePost(path, const_cast<char *>(content),
- strlen(content), &buffer_out, &response);
-}
-
-} // namespace stats_report
diff --git a/o3d/statsreport/uploader-win32.cc b/o3d/statsreport/uploader-win32.cc
deleted file mode 100644
index ba08e53..0000000
--- a/o3d/statsreport/uploader-win32.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.
- */
-
-
-// Helper class to manage the process of uploading metrics.
-
-#include <atlbase.h>
-#include <atlcom.h>
-#include <atlsafe.h>
-#include <time.h>
-#include "base/logging.h"
-
-#include "statsreport/uploader.h"
-#include "statsreport/aggregator-win32.h"
-#include "statsreport/const-win32.h"
-#include "statsreport/persistent_iterator-win32.h"
-#include "statsreport/formatter.h"
-#include "statsreport/common/const_product.h"
-#include "statsreport/const_server.h"
-
-namespace stats_report {
-// TODO: Refactor to avoid cross platform code duplication.
-
-bool UploadMetrics(const char* extra_url_data, const char* user_agent,
- const char *content) {
- // TODO: refactor to where there's a platform-independent HTTP
- // interface to the ConnectionManager and pass it through into here.
- DLOG(INFO) << "Uploading metrics . . . ";
- CString url;
- url.Format(L"http://%hs:%d/%hs?%hs=%hs&%hs=%hs&%hs",
- METRICS_SERVER_NAME,
- METRICS_SERVER_PORT,
- METRICS_SERVER_PATH,
- kStatsServerParamSourceId,
- PRODUCT_NAME_STRING,
- kStatsServerParamVersion,
- PRODUCT_VERSION_STRING,
- extra_url_data);
- DLOG(INFO) << "Url: " << url;
-
- CComPtr<IXMLHttpRequest> request;
- // create the http request object
- HRESULT hr = request.CoCreateInstance(CLSID_XMLHTTPRequest);
- if (FAILED(hr))
- return false;
-
- DLOG(INFO) << "Created request.";
- // open the request
- // TODO: async?
- CComVariant empty;
- CComVariant var_false(false);
- hr = request->open(CComBSTR("POST"), CComBSTR(url),
- var_false, empty, empty);
- if (FAILED(hr))
- return false;
- DLOG(INFO) << "Opened request.";
-
- hr = request->setRequestHeader(CComBSTR("User-Agent"), CComBSTR(user_agent));
- if (FAILED(hr))
- DLOG(WARNING) << "Failed to set user-agent";
-
- // and send the file
- // TODO: progress?
- CComSafeArray<BYTE> content_array(strlen(content));
- hr = request->send(CComVariant(content));
- if (FAILED(hr))
- return false;
- DLOG(INFO) << "Sent content_array.";
-
-#ifndef NDEBUG
- CComBSTR response;
- hr = request->get_responseText(&response);
-#endif
-
- return true;
-}
-
-} // namespace stats_report
diff --git a/o3d/statsreport/uploader.h b/o3d/statsreport/uploader.h
deleted file mode 100644
index 39b2b7c..0000000
--- a/o3d/statsreport/uploader.h
+++ /dev/null
@@ -1,77 +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.
- */
-
-
-// Helper class to manage the process of uploading metrics.
-#ifndef O3D_STATSREPORT_UPLOADER_H_
-#define O3D_STATSREPORT_UPLOADER_H_
-
-#ifdef OS_WINDOWS
-#include <atlstr.h>
-#endif
-
-#include "statsreport/metrics.h"
-
-namespace stats_report {
-
-class StatsUploader {
- public:
- StatsUploader() {}
- virtual ~StatsUploader() {}
- virtual bool UploadMetrics(const char* extra_url_data,
- const char* user_agent,
- const char *content);
- private:
- DISALLOW_COPY_AND_ASSIGN(StatsUploader);
-};
-
-bool AggregateMetrics();
-bool AggregateAndReportMetrics(const char* extra_url_arguments,
- const char* user_agent,
- bool force_report,
- bool save_old_metrics);
-bool TestableAggregateAndReportMetrics(const char* extra_url_arguments,
- const char* user_agent,
- bool force_report,
- bool save_old_metrics,
- StatsUploader* stats_uploader);
-bool UploadMetrics(const char* extra_url_data, const char* user_agent,
- const char *content);
-
-#ifdef OS_WINDOWS
-void ResetPersistentMetrics(CRegKey *key);
-#else
-void ResetPersistentMetrics(void);
-#endif
-
-} // namespace stats_report
-
-#endif // O3D_STATSREPORT_UPLOADER_H_
diff --git a/o3d/statsreport/uploader_aggregation-mac.mm b/o3d/statsreport/uploader_aggregation-mac.mm
deleted file mode 100644
index ef564a0..0000000
--- a/o3d/statsreport/uploader_aggregation-mac.mm
+++ /dev/null
@@ -1,244 +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.
- */
-
-
-// Helper class to manage the process of uploading metrics.
-#include "statsreport/aggregator-mac.h"
-#include "statsreport/common/const_product.h"
-#include "statsreport/const-mac.h"
-#include "statsreport/formatter.h"
-#include "statsreport/uploader.h"
-
-
-using stats_report::Formatter;
-using stats_report::MetricsAggregatorMac;
-
-namespace stats_report {
-
-bool AggregateMetrics() {
- using stats_report::MetricsAggregatorMac;
- MetricsAggregatorMac aggregator(g_global_metrics);
- if (!aggregator.AggregateMetrics()) {
- DLOG(WARNING) << "Metrics aggregation failed for reasons unknown";
- return false;
- }
-
- return true;
-}
-
-
-static bool ReportMetrics(const char* extra_url_data,
- const char* user_agent,
- uint32 interval,
- StatsUploader* stats_uploader) {
- NSDictionary *dict =
- [NSDictionary dictionaryWithContentsOfFile:O3DStatsPath()];
-
- if (dict == nil)
- return false;
-
- Formatter formatter(PRODUCT_NAME_STRING, interval);
- NSArray *keys = [dict allKeys];
- int count = [keys count];
-
- for(int x = 0; x < count; ++x) {
- NSString *name = [keys objectAtIndex:x];
- NSString *short_name = [name substringFromIndex:2];
-
- if ([short_name length] == 0)
- continue;
-
- const char *short_name_c_str = [short_name UTF8String];
- id item = [dict objectForKey:name];
- MetricBase *current = NULL;
- switch([name characterAtIndex:0]) {
- case 'C':
- current = new CountMetric(short_name_c_str,
- [item longLongValue]);
- break;
- case 'B':
- current = new BoolMetric(short_name_c_str,
- [item boolValue] == YES);
- break;
- case 'T': {
- TimingMetric::TimingData data;
- data.count = [[item objectAtIndex:0] intValue];
- data.sum = [[item objectAtIndex:1] longLongValue];
- data.minimum = [[item objectAtIndex:2] longLongValue];
- data.maximum = [[item objectAtIndex:3] longLongValue];
- data.align = 0; // Pleases the compiler.
- current = new TimingMetric(short_name_c_str, data);
- }
- break;
- case 'I':
- current = new IntegerMetric(short_name_c_str,
- [item longLongValue]);
- break;
- // We don't send this piece of data as it's not a metric.
- case 'L': // "LastTransmission"
- break;
- }
- if (current != NULL)
- formatter.AddMetric(current);
- }
-
- DLOG(INFO) << "formatter.output() = " << formatter.output();
- return stats_uploader->UploadMetrics(extra_url_data,
- user_agent,
- formatter.output().c_str());
-}
-
-void ResetPersistentMetrics() {
- [[NSFileManager defaultManager] removeFileAtPath:O3DStatsPath()
- handler:nil];
-}
-
-
-// Returns:
-// true if metrics were uploaded successfully, false otherwise
-// Note: False does not necessarily mean an error, just that no metrics
-// were uploaded
-bool AggregateAndReportMetrics(const char* extra_url_arguments,
- const char* user_agent,
- bool force_report,
- bool save_old_metrics) {
- StatsUploader stats_uploader;
- return TestableAggregateAndReportMetrics(extra_url_arguments, user_agent,
- force_report, save_old_metrics,
- &stats_uploader);
-}
-
-static int GetLastTransmissionTime() {
- NSDictionary *dict =
- [NSDictionary dictionaryWithContentsOfFile:O3DStatsPath()];
-
- if (dict == nil)
- return 0;
-
- NSNumber *when = [dict objectForKey:kLastTransmissionTimeValueName];
-
- if (when == nil)
- return 0;
-
- return [when intValue];
-}
-
-static void SetLastTransmissionTime(int when) {
- NSMutableDictionary *dict =
- [NSMutableDictionary dictionaryWithContentsOfFile:O3DStatsPath()];
-
- if (dict == nil)
- dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:when]
- forKey:kLastTransmissionTimeValueName];
- else
- [dict setObject:[NSNumber numberWithInt:when]
- forKey:kLastTransmissionTimeValueName];
-
- [dict writeToFile:O3DStatsPath() atomically:YES];
-}
-
-
-// Returns:
-// true if metrics were uploaded successfully, false otherwise
-// Note: False does not necessarily mean an error, just that no metrics
-// were uploaded
-bool TestableAggregateAndReportMetrics(const char* extra_url_arguments,
- const char* user_agent,
- bool force_report,
- bool save_old_metrics,
- StatsUploader* stats_uploader) {
- // Open the store
- MetricsAggregatorMac aggregator(g_global_metrics);
-
- int32 now = static_cast<int32>(time(NULL));
-
- // Retrieve the last transmission time
- int32 last_transmission_time = GetLastTransmissionTime();
-
- // if last transmission time is missing or at all dodgy, then
- // let's wipe all info and start afresh.
- if (last_transmission_time == 0 || last_transmission_time > now) {
- LOG(WARNING) << "dodgy or missing last transmission time, wiping stats";
-
- if (!save_old_metrics) ResetPersistentMetrics();
-
- SetLastTransmissionTime(now);
-
- // Force a report of the stats so we get everything currently in there.
- force_report = true;
- }
-
- if (!AggregateMetrics()) {
- DLOG(INFO) << "AggregateMetrics returned false";
- return false;
- }
-
- DLOG(INFO) << "Last transmission time: " << last_transmission_time;
- DLOG(INFO) << "Now: " << now;
- DLOG(INFO) << "Now - Last transmission time: "
- << now - last_transmission_time;
- DLOG(INFO) << "Compared to: " << kStatsUploadIntervalSec;
-
- // Set last_transmission_time such that it will force
- // an upload of the metrics
- if (force_report) {
- last_transmission_time = now - kStatsUploadIntervalSec;
- }
- if (now - last_transmission_time >= kStatsUploadIntervalSec) {
- bool report_result = ReportMetrics(extra_url_arguments, user_agent,
- now - last_transmission_time,
- stats_uploader);
- if (report_result) {
- DLOG(INFO) << "Stats upload successful, resetting metrics";
-
- ResetPersistentMetrics();
- } else {
- DLOG(WARNING) << "Stats upload failed";
- }
-
- // No matter what, wait another upload interval to try again. It's better
- // to report older stats than hammer on the stats server exactly when it
- // has failed.
- SetLastTransmissionTime(now);
- return report_result;
- }
- return false;
-}
-
-// Used primarily for testing. Default functionality.
-bool StatsUploader::UploadMetrics(const char* extra_url_data,
- const char* user_agent,
- const char *content) {
- return stats_report::UploadMetrics(extra_url_data, user_agent, content);
-}
-
-
-} // namespace stats_report
diff --git a/o3d/statsreport/uploader_aggregation-posix.cc b/o3d/statsreport/uploader_aggregation-posix.cc
deleted file mode 100644
index 4163326..0000000
--- a/o3d/statsreport/uploader_aggregation-posix.cc
+++ /dev/null
@@ -1,154 +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.
- */
-
-
-// Helper class to manage the process of uploading metrics.
-#include "backend/serverconnectionmanager.h"
-#include "statsreport/common/const_product.h"
-#include "iobuffer/iobuffer-inl.h"
-#include "statsreport/aggregator-posix-inl.h"
-#include "statsreport/const-posix.h"
-#include "statsreport/formatter.h"
-#include "statsreport/uploader.h"
-
-
-DECLARE_int32(metrics_aggregation_interval);
-DECLARE_int32(metrics_upload_interval);
-DECLARE_string(metrics_server_name);
-DECLARE_int32(metrics_server_port);
-
-using stats_report::Formatter;
-using stats_report::MetricsAggregatorPosix;
-
-namespace {
-
-bool AggregateMetrics(MetricsAggregatorPosix *aggregator) {
- if (!aggregator->AggregateMetrics()) {
- LOG(WARNING) << "Metrics aggregation failed for reasons unknown";
- return false;
- }
-
- return true;
-}
-
-
-bool ReportMetrics(MetricsAggregatorPosix *aggregator,
- const char* extra_url_data,
- const char* user_agent,
- uint32 interval) {
- Formatter formatter(PRODUCT_NAME_STRING, interval);
- aggregator->FormatMetrics(&formatter);
-
- DLOG(INFO) << "formatter.output() = " << formatter.output();
- return UploadMetrics(extra_url_data, user_agent, formatter.output().c_str());
-}
-
-} // namespace
-
-namespace stats_report {
-
-bool AggregateMetrics() {
- MetricsAggregatorPosix aggregator(g_global_metrics);
- return ::AggregateMetrics(&aggregator);
-}
-
-// Returns:
-// true if metrics were uploaded successfully, false otherwise
-// Note: False does not necessarily mean an error, just that no metrics
-// were uploaded
-bool AggregateAndReportMetrics(const char* extra_url_arguments,
- const char* user_agent,
- bool force_report,
- bool save_old_metrics) {
- StatsUploader stats_uploader;
- return TestableAggregateAndReportMetrics(extra_url_arguments, user_agent,
- force_report, save_old_metrics,
- &stats_uploader);
-}
-// Returns:
-// true if metrics were uploaded successfully, false otherwise
-// Note: False does not necessarily mean an error, just that no metrics
-// were uploaded
-bool TestableAggregateAndReportMetrics(const char* extra_url_arguments,
- const char* user_agent,
- bool force_report,
- bool save_old_metrics,
- StatsUploader* stats_uploader) {
- // Open the store
- MetricsAggregatorPosix aggregator(g_global_metrics);
-
- int32 now = static_cast<int32>(time(NULL));
-
- // Retrieve the last transmission time
- int32 last_transmission_time;
- bool success = aggregator.GetValue(kLastTransmissionTimeValueName,
- &last_transmission_time);
-
- // if last transmission time is missing or at all hinky, then
- // let's wipe all info and start afresh.
- if (!success || last_transmission_time > now) {
- LOG(WARNING) << "Hinky or missing last transmission time, wiping stats";
-
- if (!save_old_metrics) aggregator.ResetMetrics();
-
- success = aggregator.SetValue(kLastTransmissionTimeValueName, now);
- if (!success)
- LOG(ERROR) << "Unable to write last transmission value";
-
- // we just wiped everything, let's not waste any more time
- return false;
- }
-
- if (!::AggregateMetrics(&aggregator))
- return false;
-
- if (now - last_transmission_time >= kStatsUploadInterval) {
- bool report_result = ReportMetrics(&aggregator, extra_url_arguments,
- user_agent,
- now - last_transmission_time);
- if (report_result) {
- LOG(INFO) << "Stats upload successful, resetting metrics";
-
- aggregator.ResetMetrics();
- } else {
- LOG(WARNING) << "Stats upload failed";
- }
-
- // No matter what, wait another upload interval to try again. It's better
- // to report older stats than hammer on the stats server exactly when it's
- // failed.
- (void)aggregator.SetValue(kLastTransmissionTimeValueName, now);
- return report_result;
- }
- return false;
-}
-
-} // namespace stats_report
diff --git a/o3d/statsreport/uploader_aggregation-win32.cc b/o3d/statsreport/uploader_aggregation-win32.cc
deleted file mode 100644
index d128c77..0000000
--- a/o3d/statsreport/uploader_aggregation-win32.cc
+++ /dev/null
@@ -1,193 +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.
- */
-
-
-// Helper class to manage the process of uploading metrics.
-
-#include <atlbase.h>
-#include <atlcom.h>
-#include <atlsafe.h>
-#include <time.h>
-#include "base/logging.h"
-
-#include "statsreport/uploader.h"
-#include "statsreport/aggregator-win32.h"
-#include "statsreport/const-win32.h"
-#include "statsreport/persistent_iterator-win32.h"
-#include "statsreport/formatter.h"
-#include "statsreport/common/const_product.h"
-
-namespace stats_report {
-// TODO: Refactor to avoid cross platform code duplication.
-
-bool AggregateMetrics() {
- using stats_report::MetricsAggregatorWin32;
- MetricsAggregatorWin32 aggregator(g_global_metrics, PRODUCT_NAME_STRING_WIDE);
- if (!aggregator.AggregateMetrics()) {
- DLOG(WARNING) << "Metrics aggregation failed for reasons unknown";
- return false;
- }
-
- return true;
-}
-
-
-static bool ReportMetrics(const char* extra_url_data,
- const char* user_agent,
- DWORD interval,
- StatsUploader* stats_uploader) {
- PersistentMetricsIteratorWin32 it(PRODUCT_NAME_STRING_WIDE), end;
- Formatter formatter(CStringA(PRODUCT_NAME_STRING), interval);
-
- for (; it != end; ++it)
- formatter.AddMetric(*it);
- DLOG(INFO) << "formatter.output() = " << formatter.output();
- return stats_uploader->UploadMetrics(extra_url_data, user_agent,
- formatter.output().c_str());
-}
-
-void ResetPersistentMetrics(CRegKey *key) {
- key->DeleteValue(kLastTransmissionTimeValueName);
- key->DeleteSubKey(kCountsKeyName);
- key->DeleteSubKey(kTimingsKeyName);
- key->DeleteSubKey(kIntegersKeyName);
- key->DeleteSubKey(kBooleansKeyName);
-}
-
-// Returns:
-// true if metrics were uploaded successfully, false otherwise
-// Note: False does not necessarily mean an error, just that no metrics
-// were uploaded
-bool AggregateAndReportMetrics(const char* extra_url_arguments,
- const char* user_agent,
- bool force_report,
- bool save_old_metrics) {
- StatsUploader stats_uploader;
- return TestableAggregateAndReportMetrics(extra_url_arguments, user_agent,
- force_report, save_old_metrics,
- &stats_uploader);
-}
-// Returns:
-// true if metrics were uploaded successfully, false otherwise
-// Note: False does not necessarily mean an error, just that no metrics
-// were uploaded
-bool TestableAggregateAndReportMetrics(const char* extra_url_arguments,
- const char* user_agent,
- bool force_report,
- bool save_old_metrics,
- StatsUploader* stats_uploader) {
- CString key_name;
- key_name.Format(kStatsKeyFormatString, PRODUCT_NAME_STRING_WIDE);
-
- CRegKey key;
- LONG err = key.Create(HKEY_CURRENT_USER, key_name);
- if (ERROR_SUCCESS != err) {
- DLOG(WARNING) << "Unable to open metrics key";
- return false;
- }
-
- DWORD now = static_cast<DWORD>(time(NULL));
-
- // Retrieve the last transmission time
- DWORD last_transmission_time;
- DWORD value_type;
- ULONG value_len = sizeof(last_transmission_time);
- err = key.QueryValue(kLastTransmissionTimeValueName, &value_type,
- &last_transmission_time, &value_len);
-
- // if last transmission time is missing or at all hinky, then
- // let's wipe all info and start afresh.
- if (ERROR_SUCCESS != err || REG_DWORD != value_type ||
- sizeof(last_transmission_time) != value_len ||
- last_transmission_time > now) {
- DLOG(WARNING) << "Hinky or missing last transmission time, wiping stats";
-
- if (!save_old_metrics) ResetPersistentMetrics(&key);
-
- err = key.SetValue(kLastTransmissionTimeValueName, REG_DWORD,
- &now, sizeof(now));
- if (ERROR_SUCCESS != err) {
- DLOG(ERROR) << "Unable to write last transmission value, error "
- << std::hex << err;
- }
- // Force a report of the stats so we get everything currently in there.
- force_report = true;
-
- // we just wiped everything, let's not waste any more time
- // return; <-- skipping this since we still want to aggregate
- }
-
- if (!AggregateMetrics()) {
- DLOG(INFO) << "AggregateMetrics returned false";
- return false;
- }
-
- DLOG(INFO) << "Last transimission time: " << last_transmission_time;
- DLOG(INFO) << "Now: " << now;
- DLOG(INFO) << "Now - Last transmission time: "
- << now - last_transmission_time;
- DLOG(INFO) << "Compared to: " << kStatsUploadIntervalSec;
-
- // Set last_transmission_time such that it will force
- // an upload of the metrics
- if (force_report) {
- last_transmission_time = now - kStatsUploadIntervalSec;
- }
- if (now - last_transmission_time >= kStatsUploadIntervalSec) {
- bool report_result = ReportMetrics(extra_url_arguments, user_agent,
- now - last_transmission_time,
- stats_uploader);
- if (report_result) {
- DLOG(INFO) << "Stats upload successful, resetting metrics";
-
- ResetPersistentMetrics(&key);
- } else {
- DLOG(WARNING) << "Stats upload failed";
- }
-
- // No matter what, wait another upload interval to try again. It's better
- // to report older stats than hammer on the stats server exactly when it's
- // failed.
- err = key.SetValue(kLastTransmissionTimeValueName, REG_DWORD,
- &now, sizeof(now));
- return report_result;
- }
- return false;
-}
-
-// Used primarily for testing. Default functionality.
-bool StatsUploader::UploadMetrics(const char* extra_url_data,
- const char* user_agent,
- const char *content) {
- return stats_report::UploadMetrics(extra_url_data, user_agent, content);
-}
-
-} // namespace stats_report
diff --git a/o3d/statsreport/util-win32.h b/o3d/statsreport/util-win32.h
deleted file mode 100644
index f15dfac..0000000
--- a/o3d/statsreport/util-win32.h
+++ /dev/null
@@ -1,53 +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.
- */
-
-
-// Utility functions for Win32 stats aggregation and uploading
-#ifndef O3D_STATSREPORT_UTIL_WIN32_H__
-#define O3D_STATSREPORT_UTIL_WIN32_H__
-
-namespace stats_report {
-
-template <class ValueType>
-bool GetData(CRegKey *parent, const wchar_t *value_name, ValueType *value) {
- ULONG len = sizeof(ValueType);
- LONG err = parent->QueryBinaryValue(value_name, value, &len);
- if (ERROR_SUCCESS != err || len != sizeof(ValueType)) {
- memset(value, 0, sizeof(ValueType));
- return false;
- }
-
- return true;
-}
-
-} // namespace stats_report
-
-#endif // O3D_STATSREPORT_UTIL_WIN32_H__
diff --git a/o3d/tests/archive_files/BumpReflect.fx b/o3d/tests/archive_files/BumpReflect.fx
deleted file mode 100644
index 684bc6d..0000000
--- a/o3d/tests/archive_files/BumpReflect.fx
+++ /dev/null
@@ -1,99 +0,0 @@
-float4x4 world : World;
-float4x4 worldInverseTranspose : WorldInverseTranspose;
-float4x4 worldViewProj : WorldViewProjection;
-float4x4 viewInverse : ViewInverse;
-
-////////////////
-// tweakables //
-////////////////
-
-float BumpHeight <
- string UIName = "Bump Factor";
- float UIMin = 0.0;
- float UIMax = 2.0;
- float UIStep = 0.1;
-> = 0.2;
-
-texture normalMap : Normal <
- string UIName = "Normal Map";
- string name = "NMP_Ripples2_512.dds";
- string type = "2D";
->;
-
-sampler2D NormalSampler = sampler_state {
- Texture = <normalMap>;
- MinFilter = Linear;
- MagFilter = Linear;
- MipFilter = Linear;
-};
-
-texture envMap : Environment <
- string UIName = "Cube Map";
- string type = "CUBE";
- string name = "sunol_cubemap.dds";
->;
-
-samplerCUBE EnvSampler = sampler_state {
- Texture = <envMap>;
- MinFilter = Linear;
- MipFilter = Linear;
- MagFilter = Linear;
-// WrapS = ClampToEdge;
-// WrapT = ClampToEdge;
-};
-
-////////////////
-// structures //
-////////////////
-
-struct a2v
-{
- float4 Position : POSITION; //in object space
- float3 TexCoord : TEXCOORD0;
- float3 Tangent : TANGENT; // TANGENT; // ATTR14; // in object space
- float3 Binormal : BINORMAL; // BINORMAL; // ATTR15; // in object space
- float3 Normal : NORMAL; //in object space
-};
-
-struct v2f
-{
- float4 Position : POSITION; //in projection space
- float2 TexCoord : TEXCOORD0;
- float3 worldEyeVec : TEXCOORD1;
- float3 WorldNormal : TEXCOORD2;
- float3 WorldTangent : TEXCOORD3;
- float3 WorldBinorm : TEXCOORD4;
-};
-
-/////////////
-// shaders //
-/////////////
-
-v2f BumpReflectVS(a2v IN)
-{
- v2f OUT;
- OUT.Position = mul(IN.Position, worldViewProj);
- OUT.TexCoord.xy = IN.TexCoord.xy;
- OUT.WorldNormal = mul(float4(IN.Normal, 0), worldInverseTranspose).xyz;
- OUT.WorldTangent = mul(float4(IN.Tangent, 0), worldInverseTranspose).xyz;
- OUT.WorldBinorm = mul(float4(IN.Binormal, 0), worldInverseTranspose).xyz;
- float3 worldPos = mul(IN.Position, world).xyz;
- OUT.worldEyeVec = normalize(worldPos - viewInverse[3].xyz);
- return OUT;
-}
-
-float4 BumpReflectPS(v2f IN) : COLOR {
- float2 bump = (tex2D(NormalSampler, IN.TexCoord.xy).xy * 2 - 1) * BumpHeight;
- float3 normal = normalize(IN.WorldNormal);
- float3 tangent = normalize(IN.WorldTangent);
- float3 binormal = normalize(IN.WorldBinorm);
- float3 nb = normal + bump.x * tangent + bump.y * binormal;
- nb = normalize(nb);
- float3 worldEyeVec = normalize(IN.worldEyeVec);
- float3 lookup = reflect(worldEyeVec, nb);
- return texCUBE(EnvSampler, float4(lookup, 1).xyz);
-}
-
-// #o3d VertexShaderEntryPoint BumpReflectVS
-// #o3d PixelShaderEntryPoint BumpReflectPS
-
diff --git a/o3d/tests/archive_files/bogus.tar.gz b/o3d/tests/archive_files/bogus.tar.gz
deleted file mode 100644
index 989c181..0000000
--- a/o3d/tests/archive_files/bogus.tar.gz
+++ /dev/null
@@ -1,4 +0,0 @@
-fjdfijeifjeijfiejfijef
-efifjeijfe
-efislja;djfa
-efkejslfra
diff --git a/o3d/tests/archive_files/keyboard.jpg b/o3d/tests/archive_files/keyboard.jpg
deleted file mode 100644
index 1fdba53..0000000
--- a/o3d/tests/archive_files/keyboard.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/archive_files/keyboard.jpg.gz b/o3d/tests/archive_files/keyboard.jpg.gz
deleted file mode 100644
index 18ee068..0000000
--- a/o3d/tests/archive_files/keyboard.jpg.gz
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/archive_files/perc.aif b/o3d/tests/archive_files/perc.aif
deleted file mode 100644
index fc40178..0000000
--- a/o3d/tests/archive_files/perc.aif
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/archive_files/test1.tar b/o3d/tests/archive_files/test1.tar
deleted file mode 100644
index ae23a28..0000000
--- a/o3d/tests/archive_files/test1.tar
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/archive_files/test1.tar.gz b/o3d/tests/archive_files/test1.tar.gz
deleted file mode 100644
index 9767501..0000000
--- a/o3d/tests/archive_files/test1.tar.gz
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/archive_files/test2.tar.gz b/o3d/tests/archive_files/test2.tar.gz
deleted file mode 100644
index 3bcb1036..0000000
--- a/o3d/tests/archive_files/test2.tar.gz
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/basic_system_test/basic_system_test.cc b/o3d/tests/basic_system_test/basic_system_test.cc
deleted file mode 100644
index 598eb9f8..0000000
--- a/o3d/tests/basic_system_test/basic_system_test.cc
+++ /dev/null
@@ -1,340 +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.
- */
-
-
-// Basic O3D system test for constructing and rendering geometry.
-
-#include <math.h>
-
-#include "core/cross/client.h"
-#include "core/cross/counter.h"
-#include "core/cross/draw_context.h"
-#include "core/cross/draw_pass.h"
-#include "core/cross/draw_list.h"
-#include "core/cross/primitive.h"
-#include "core/cross/stream_bank.h"
-#include "core/cross/tree_traversal.h"
-#include "core/cross/clear_buffer.h"
-#include "core/cross/math_utilities.h"
-#include "import/cross/raw_data.h"
-#include "tests/common/win/testing_common.h"
-#include "tests/common/win/system_test.h"
-
-namespace o3d {
-
-float DegreesToRadians(float degrees) {
- return degrees * kPi / 180.f;
-}
-
-const char kShaderString[] =
-"// World View Projection matrix that will transform the input vertices \n"
-"// to screen space. \n"
-"float4x4 worldViewProjection : WorldViewProjection; \n"
-" \n"
-"// input parameters for our vertex shader \n"
-"struct VertexShaderInput { \n"
-" float4 position : POSITION; \n"
-"}; \n"
-" \n"
-"// input parameters for our pixel shader \n"
-"struct PixelShaderInput { \n"
-" float4 position : POSITION; \n"
-"}; \n"
-"/** \n"
-"* The vertex shader simply transforms the input vertices to screen space. \n"
-"*/ \n"
-"PixelShaderInput vertexShaderFunction(VertexShaderInput input) { \n"
-" PixelShaderInput output; \n"
-" \n"
-" // Multiply the vertex positions by the worldViewProjection matrix to \n"
-" // transform them to screen space. \n"
-" output.position = mul(input.position, worldViewProjection); \n"
-" return output; \n"
-"} \n"
-" \n"
-"/** \n"
-"* This pixel shader just returns the color red. \n"
-"*/ \n"
-"float4 pixelShaderFunction(PixelShaderInput input): COLOR { \n"
-" return float4(1, 0, 0, 1); // Red. \n"
-"} \n"
-" \n"
-"// Here we tell our effect file *which* functions are \n"
-"// our vertex and pixel shaders. \n"
-" \n"
-"// #o3d VertexShaderEntryPoint vertexShaderFunction \n"
-"// #o3d PixelShaderEntryPoint pixelShaderFunction \n"
-"// #o3d MatrixLoadOrder RowMajor \n";
-
-// System-test class for basic o3d geometry construction and render
-// functionality.
-class BasicSystemTest : public testing::Test {
- protected:
- BasicSystemTest()
- : object_manager_(g_service_locator) {}
-
- virtual void SetUp();
- virtual void TearDown();
-
- Client* client() {
- return client_;
- }
-
- Pack* pack() {
- return pack_;
- }
-
- DrawContext* context() {
- return context_;
- }
-
- DrawList* opaque_draw_list() {
- return opaque_draw_list_;
- }
-
- DrawList* transparent_draw_list() {
- return transparent_draw_list_;
- }
-
- // Constructs a cube, and returns the transform node under which
- // the new cube shape resides.
- void CreateCube(Material::Ref material, Transform::Ref* transform);
-
- ServiceDependency<ObjectManager> object_manager_;
-
- private:
- Client *client_;
- Pack* pack_;
- DrawContext* context_;
- DrawList* opaque_draw_list_;
- DrawList* transparent_draw_list_;
-};
-
-void BasicSystemTest::SetUp() {
- client_ = new o3d::Client(g_service_locator);
- client_->Init();
-
- pack_ = object_manager_->CreatePack();
-
- Transform* root = client_->root();
-
- // Creates a clear buffer render node and parents it to the root.
- ClearBuffer* clear_buffer = pack_->Create<ClearBuffer>();
- clear_buffer->set_priority(0);
- clear_buffer->set_clear_color(Float4(0.5f, 0.5f, 0.5f, 1.0f));
- clear_buffer->SetParent(client_->render_graph_root());
-
- // Create DrawLists
- opaque_draw_list_ = pack_->Create<DrawList>();
- transparent_draw_list_ = pack_->Create<DrawList>();
-
- // Create DrawContext.
- context_ = pack_->Create<DrawContext>();
-
- // Creates a TreeTraversal and parents it to the root.
- TreeTraversal* tree_traversal = pack_->Create<TreeTraversal>();
- tree_traversal->set_priority(1);
- tree_traversal->SetParent(client_->render_graph_root());
-
- // Creates a DrawPass for opaque shapes.
- DrawPass* opaque_draw_pass = pack_->Create<DrawPass>();
- opaque_draw_pass->set_priority(2);
- opaque_draw_pass->set_draw_list(opaque_draw_list_);
- opaque_draw_pass->SetParent(client_->render_graph_root());
-
- // Creates a DrawPass for transparent shapes.
- DrawPass* transparent_draw_pass = pack_->Create<DrawPass>();
- transparent_draw_pass->set_priority(3);
- transparent_draw_pass->set_draw_list(transparent_draw_list_);
- transparent_draw_pass->SetParent(client_->render_graph_root());
-
- // Register the passlists and drawcontext with the TreeTraversal
- tree_traversal->RegisterDrawList(opaque_draw_list_, context_, true);
- tree_traversal->RegisterDrawList(transparent_draw_list_, context_, true);
- tree_traversal->set_transform(root);
-
- const Point3 eye(0.0f, 1.0f, 5.0f);
- const Point3 target(0.0f, 0.0f, 0.0f);
- const Vector3 up(0.0f, 1.0f, 0.0f);
-
- const Matrix4 perspective_matrix = Vectormath::Aos::CreatePerspectiveMatrix(
- DegreesToRadians(60.0f),
- 1.0f,
- 1.0f,
- 1000.0f);
- const Matrix4 view_matrix = Matrix4::lookAt(eye, target, up);
-
- context_->set_view(view_matrix);
- context_->set_projection(perspective_matrix);
-}
-
-void BasicSystemTest::TearDown() {
- // Force another render to make the stream capture end.
- client()->RenderClient(true);
-
- pack_->Destroy();
- delete client_;
-}
-
-void BasicSystemTest::CreateCube(Material::Ref material,
- Transform::Ref* transform) {
- Shape::Ref cube_shape(pack()->Create<Shape>());
- ASSERT_FALSE(cube_shape.IsNull());
-
- Transform::Ref cube_xform(pack()->Create<Transform>());
- ASSERT_FALSE(cube_xform.IsNull());
-
- // Create the Primitive that will contain the geometry data for
- // the cube.
- Primitive::Ref cube_primitive(pack()->Create<Primitive>());
- ASSERT_FALSE(cube_primitive.IsNull());
-
- // Create a StreamBank to hold the streams of vertex data.
- StreamBank::Ref stream_bank(pack()->Create<StreamBank>());
- ASSERT_FALSE(stream_bank.IsNull());
-
- // Assign the material that was passed in to the primitive.
- cube_primitive->set_material(material);
-
- // Assign the Primitive to the Shape.
- cube_primitive->SetOwner(cube_shape);
-
- // Assign the StreamBank to the Primitive.
- cube_primitive->set_stream_bank(stream_bank);
-
- cube_primitive->set_primitive_type(Primitive::TRIANGLELIST);
- cube_primitive->set_number_primitives(12); // 12 triangles
- cube_primitive->set_number_vertices(8); // 8 vertices in total
-
- cube_primitive->CreateDrawElement(pack(), NULL);
-
- static const float kPositionArray[][3] = {
- {-0.5, -0.5, 0.5},
- {0.5, -0.5, 0.5},
- {-0.5, 0.5, 0.5},
- {0.5, 0.5, 0.5},
- {-0.5, 0.5, -0.5},
- {0.5, 0.5, -0.5},
- {-0.5, -0.5, -0.5},
- {0.5, -0.5, -0.5}
- };
-
- static const unsigned int kIndicesArray[] = {
- 0, 1, 2, // face 1
- 2, 1, 3,
- 2, 3, 4, // face 2
- 4, 3, 5,
- 4, 5, 6, // face 3
- 6, 5, 7,
- 6, 7, 0, // face 4
- 0, 7, 1,
- 1, 7, 3, // face 5
- 3, 7, 5,
- 6, 0, 4, // face 6
- 4, 0, 2
- };
-
- static const unsigned int kNumComponents = arraysize(kPositionArray[0]);
- static const unsigned int kNumElements = arraysize(kPositionArray);
- static const unsigned int kStride = kNumComponents;
-
- VertexBuffer::Ref positions_buffer(pack()->Create<VertexBuffer>());
-
- FloatField::Ref positions_field(positions_buffer->CreateField(
- FloatField::GetApparentClass(),
- 3));
- ASSERT_FALSE(positions_field.IsNull());
-
- ASSERT_TRUE(positions_buffer->AllocateElements(kNumElements));
- positions_field->SetFromFloats(&kPositionArray[0][0], kStride, 0,
- kNumElements);
-
- IndexBuffer::Ref index_buffer(pack()->Create<IndexBuffer>());
- ASSERT_FALSE(index_buffer.IsNull());
-
- static const unsigned int kNumIndices = arraysize(kIndicesArray);
- ASSERT_TRUE(index_buffer->AllocateElements(kNumIndices));
- index_buffer->index_field()->SetFromUInt32s(&kIndicesArray[0], 1,
- 0, kNumIndices);
-
- // Associate the positions Buffer with the StreamBank.
- stream_bank->SetVertexStream(
- Stream::POSITION, // semantic: This stream stores vertex positions
- 0, // semantic index: First (and only) position stream
- positions_field, // field: the field this stream uses.
- 0); // start_index: How many elements to skip in the
- // field.
-
- // Associate the triangle indices Buffer with the primitive.
- cube_primitive->set_index_buffer(index_buffer);
-
- cube_xform->AddShape(cube_shape);
- *transform = cube_xform;
-}
-
-TEST_F(BasicSystemTest, BasicSystemTestCase) {
- ASSERT_FALSE(client()->root() == NULL);
-
- Transform *spin_transform = pack()->Create<Transform>();
- ASSERT_FALSE(spin_transform == NULL);
-
- Transform* root = client()->root();
- spin_transform->SetParent(root);
-
- Material::Ref cube_material(pack()->Create<Material>());
- ASSERT_FALSE(cube_material.IsNull());
- cube_material->set_draw_list(opaque_draw_list());
-
- Effect::Ref effect(pack()->Create<Effect>());
- effect->LoadFromFXString(kShaderString);
- cube_material->set_effect(effect);
-
- Transform::Ref cube_xform;
- CreateCube(cube_material, &cube_xform);
- ASSERT_FALSE(cube_xform.IsNull());
- cube_xform->SetParent(spin_transform);
-
- ASSERT_FALSE(spin_transform->GetChildren()[0] == NULL);
-
- // Assert that 5 rendered frames generate both the correct command streams,
- // and framebuffer contents.
- BEGIN_ASSERT_STREAM_CAPTURE();
- for (int frame_count = 0; frame_count < 5; ++frame_count) {
- client()->RenderClient(true);
- ASSERT_FRAMEBUFFER();
- Matrix4 mat(Matrix4::rotationY(static_cast<float>(frame_count) * 2 *
- static_cast<float>(M_PI) / 5.0f));
- spin_transform->set_local_matrix(mat);
- }
- END_ASSERT_STREAM_CAPTURE();
-}
-
-} // namespace o3d
diff --git a/o3d/tests/basic_system_test/reference_frames/frame_capture0.png b/o3d/tests/basic_system_test/reference_frames/frame_capture0.png
deleted file mode 100644
index cfe991f..0000000
--- a/o3d/tests/basic_system_test/reference_frames/frame_capture0.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/basic_system_test/reference_frames/frame_capture1.png b/o3d/tests/basic_system_test/reference_frames/frame_capture1.png
deleted file mode 100644
index 3f7baeb..0000000
--- a/o3d/tests/basic_system_test/reference_frames/frame_capture1.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/basic_system_test/reference_frames/frame_capture2.png b/o3d/tests/basic_system_test/reference_frames/frame_capture2.png
deleted file mode 100644
index b498023..0000000
--- a/o3d/tests/basic_system_test/reference_frames/frame_capture2.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/basic_system_test/reference_frames/frame_capture3.png b/o3d/tests/basic_system_test/reference_frames/frame_capture3.png
deleted file mode 100644
index fd5719c..0000000
--- a/o3d/tests/basic_system_test/reference_frames/frame_capture3.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/basic_system_test/reference_frames/frame_capture4.png b/o3d/tests/basic_system_test/reference_frames/frame_capture4.png
deleted file mode 100644
index 2fff834..0000000
--- a/o3d/tests/basic_system_test/reference_frames/frame_capture4.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/basic_system_test/reference_stream.csv b/o3d/tests/basic_system_test/reference_stream.csv
deleted file mode 100644
index eb38ab4..0000000
--- a/o3d/tests/basic_system_test/reference_stream.csv
+++ /dev/null
@@ -1,242 +0,0 @@
-Event Type,EID,Event,StartTime,Frame,Duration,FPS
-Session Start,1,Start Session,0,,0,
-Process Start,2,Start Process,0,,0,
-Frame,3,Frame 2,30598216619,2,2655979068,0.4
-Call,4,D3DPERF_GetStatus(),30598284778,,,
-User Marker,5,User Marker: Frame_Capture: 306 : tests\basic_system_test\import_test.cc,31097816048,,0,
-User Marker,6,User Marker: CaptureScreenContents,31097864253,,0,
-Call,7,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x003EBEC4 --> 0x041F4D40)",31097951090,,,
-Call,8,<0x041F4040> IDirect3DDevice9::GetDepthStencilSurface(0x003EBEC8 --> 0x041C7D68),31097999717,,,
-Call,9,<0x041F4040> IDirect3DDevice9::BeginScene(),31098043720,,,
-Call,10,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0012F3BC --> 0x041F4D40)",31098090625,,,
-Call,11,<0x041F4D40> IDirect3DSurface9::GetDesc(0x0012F394),31098134913,,,
-Call,12,<0x041F4D40> IDirect3DSurface9::Release(),31098179695,,,
-Call,13,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0012F3BC --> 0x041F4D40)",31098233507,,,
-Call,14,<0x041F4D40> IDirect3DSurface9::GetDesc(0x0012F394),31098277332,,,
-Call,15,<0x041F4D40> IDirect3DSurface9::Release(),31098320525,,,
-Call,16,<0x041F4040> IDirect3DDevice9::SetViewport(0x0012F39C),31098365740,,,
-Call,17,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0012F6C8 --> 0x041F4D40)",31098432568,,,
-Call,18,<0x041F4040> IDirect3DDevice9::GetDepthStencilSurface(0x0012F6BC --> 0x041C7D68),31098476648,,,
-Call,19,"<0x041F4040> IDirect3DDevice9::Clear(0x00000000, NULL, 0x00000007, D3DCOLOR_ARGB(0xff,0x7f,0x7f,0x7f), 1.000f, 0x00000000)",31098521071,,,
-Call,20,<0x041C7D68> IDirect3DSurface9::Release(),31098568276,,,
-Call,21,<0x041F4D40> IDirect3DSurface9::Release(),31098611436,,,
-Call,22,<0x041F4040> IDirect3DDevice9::SetIndices(0x041C85B8),31098727017,,,
-Call,23,"<0x041F4040> IDirect3DDevice9::SetStreamSource(0, 0x041C84E8, 0, 12)",31098885293,,,
-Call,24,<0x041F4040> IDirect3DDevice9::SetVertexDeclaration(0x041C8820),31098945447,,,
-Call,25,"<0x041C8298> ID3DXEffect::SetMatrix(0xFAC1DD7B, 0x0012EECC)",31099004241,,,
-Call,26,<0x041C8298> ID3DXEffect::GetTechnique(0),31099061461,,,
-Call,27,<0x041C8298> ID3DXEffect::SetTechnique(0xFAC1D0CB),31099114543,,,
-Call,28,"<0x041C8298> ID3DXEffect::Begin(0x0012EF60, 0x00000000)",31099167480,,,
-Call,29,<0x041CACF0> IDirect3DStateBlock9::Capture(),31099185394,,,
-Call,30,<0x041C9AB8> IDirect3DStateBlock9::Capture(),31099249010,,,
-Call,31,<0x041C94E8> IDirect3DStateBlock9::Capture(),31099306834,,,
-Call,32,<0x041CA088> IDirect3DStateBlock9::Capture(),31099362781,,,
-Call,33,<0x041C8948> IDirect3DStateBlock9::Capture(),31099417686,,,
-Call,34,<0x041C8298> ID3DXEffect::BeginPass(0),31099514400,,,
-Call,35,<0x041F4040> IDirect3DDevice9::SetVertexShader(0x041C81E0),31099533107,,,
-Call,36,"<0x041F4040> IDirect3DDevice9::SetVertexShaderConstantF(0, 0x053E22E0, 4)",31099588736,,,
-Call,37,<0x041F4040> IDirect3DDevice9::SetPixelShader(0x041C8128),31099644021,,,
-Call,38,"<0x041F4040> IDirect3DDevice9::DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8, 0, 12)",31099736770,,,
-Call,39,<0x041C8298> ID3DXEffect::EndPass(),31099825615,,,
-Call,40,<0x041C8298> ID3DXEffect::End(),31099887465,,,
-Call,41,<0x041C8948> IDirect3DStateBlock9::Apply(),31099905619,,,
-Call,42,<0x041CA088> IDirect3DStateBlock9::Apply(),31099959011,,,
-Call,43,<0x041C94E8> IDirect3DStateBlock9::Apply(),31100002488,,,
-Call,44,<0x041C9AB8> IDirect3DStateBlock9::Apply(),31100045426,,,
-Call,45,<0x041CACF0> IDirect3DStateBlock9::Apply(),31100090448,,,
-Call,46,<0x041F4040> IDirect3DDevice9::EndScene(),31100181906,,,
-Call,47,<0x041F4D40> IDirect3DSurface9::Release(),31100226786,,,
-Call,48,<0x041C7D68> IDirect3DSurface9::Release(),31100271023,,,
-Call,49,"<0x041F4040> IDirect3DDevice9::Present(NULL, NULL, NULL, NULL)",31100330032,,,
-Frame,50,Frame 3,33254239772,3,2655502064,0.4
-Call,51,D3DPERF_GetStatus(),33254341389,,,
-User Marker,52,User Marker: Frame_Capture: 306 : tests\basic_system_test\import_test.cc,33754093579,,0,
-User Marker,53,User Marker: CaptureScreenContents,33754168712,,0,
-Call,54,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x003EBEC4 --> 0x041F4D40)",33754242875,,,
-Call,55,<0x041F4040> IDirect3DDevice9::GetDepthStencilSurface(0x003EBEC8 --> 0x041C7D68),33754291635,,,
-Call,56,<0x041F4040> IDirect3DDevice9::BeginScene(),33754335630,,,
-Call,57,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0012F3BC --> 0x041F4D40)",33754382330,,,
-Call,58,<0x041F4D40> IDirect3DSurface9::GetDesc(0x0012F394),33754426625,,,
-Call,59,<0x041F4D40> IDirect3DSurface9::Release(),33754471340,,,
-Call,60,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0012F3BC --> 0x041F4D40)",33754516463,,,
-Call,61,<0x041F4D40> IDirect3DSurface9::GetDesc(0x0012F394),33754560173,,,
-Call,62,<0x041F4D40> IDirect3DSurface9::Release(),33754603635,,,
-Call,63,<0x041F4040> IDirect3DDevice9::SetViewport(0x0012F39C),33754648955,,,
-Call,64,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0012F6C8 --> 0x041F4D40)",33754715152,,,
-Call,65,<0x041F4040> IDirect3DDevice9::GetDepthStencilSurface(0x0012F6BC --> 0x041C7D68),33754758979,,,
-Call,66,"<0x041F4040> IDirect3DDevice9::Clear(0x00000000, NULL, 0x00000007, D3DCOLOR_ARGB(0xff,0x7f,0x7f,0x7f), 1.000f, 0x00000000)",33754803029,,,
-Call,67,<0x041C7D68> IDirect3DSurface9::Release(),33754858946,,,
-Call,68,<0x041F4D40> IDirect3DSurface9::Release(),33754902321,,,
-Call,69,<0x041F4040> IDirect3DDevice9::SetIndices(0x041C85B8),33755087163,,,
-Call,70,"<0x041F4040> IDirect3DDevice9::SetStreamSource(0, 0x041C84E8, 0, 12)",33755142683,,,
-Call,71,<0x041F4040> IDirect3DDevice9::SetVertexDeclaration(0x041C8820),33755189392,,,
-Call,72,"<0x041C8298> ID3DXEffect::SetMatrix(0xFAC1DD7B, 0x0012EECC)",33755236937,,,
-Call,73,<0x041C8298> ID3DXEffect::GetTechnique(0),33755282727,,,
-Call,74,<0x041C8298> ID3DXEffect::SetTechnique(0xFAC1D0CB),33755325955,,,
-Call,75,"<0x041C8298> ID3DXEffect::Begin(0x0012EF60, 0x00000000)",33755369875,,,
-Call,76,<0x041CACF0> IDirect3DStateBlock9::Capture(),33755384392,,,
-Call,77,<0x041C9AB8> IDirect3DStateBlock9::Capture(),33755431049,,,
-Call,78,<0x041C94E8> IDirect3DStateBlock9::Capture(),33755475384,,,
-Call,79,<0x041CA088> IDirect3DStateBlock9::Capture(),33755518354,,,
-Call,80,<0x041C8948> IDirect3DStateBlock9::Capture(),33755561217,,,
-Call,81,<0x041C8298> ID3DXEffect::BeginPass(0),33755635633,,,
-Call,82,<0x041F4040> IDirect3DDevice9::SetVertexShader(0x041C81E0),33755651344,,,
-Call,83,"<0x041F4040> IDirect3DDevice9::SetVertexShaderConstantF(0, 0x053E22E0, 4)",33755697184,,,
-Call,84,<0x041F4040> IDirect3DDevice9::SetPixelShader(0x041C8128),33755742764,,,
-Call,85,"<0x041F4040> IDirect3DDevice9::DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8, 0, 12)",33755818852,,,
-Call,86,<0x041C8298> ID3DXEffect::EndPass(),33755867400,,,
-Call,87,<0x041C8298> ID3DXEffect::End(),33755910380,,,
-Call,88,<0x041C8948> IDirect3DStateBlock9::Apply(),33755923289,,,
-Call,89,<0x041CA088> IDirect3DStateBlock9::Apply(),33755988713,,,
-Call,90,<0x041C94E8> IDirect3DStateBlock9::Apply(),33756051677,,,
-Call,91,<0x041C9AB8> IDirect3DStateBlock9::Apply(),33756095407,,,
-Call,92,<0x041CACF0> IDirect3DStateBlock9::Apply(),33756140752,,,
-Call,93,<0x041F4040> IDirect3DDevice9::EndScene(),33756230874,,,
-Call,94,<0x041F4D40> IDirect3DSurface9::Release(),33756275152,,,
-Call,95,<0x041C7D68> IDirect3DSurface9::Release(),33756318974,,,
-Call,96,"<0x041F4040> IDirect3DDevice9::Present(NULL, NULL, NULL, NULL)",33756374044,,,
-Frame,97,Frame 4,35909807940,4,2701946354,0.4
-Call,98,D3DPERF_GetStatus(),35909909042,,,
-User Marker,99,User Marker: Frame_Capture: 306 : tests\basic_system_test\import_test.cc,36409267444,,0,
-User Marker,100,User Marker: CaptureScreenContents,36409356534,,0,
-Call,101,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x003EBEC4 --> 0x041F4D40)",36409433720,,,
-Call,102,<0x041F4040> IDirect3DDevice9::GetDepthStencilSurface(0x003EBEC8 --> 0x041C7D68),36409482529,,,
-Call,103,<0x041F4040> IDirect3DDevice9::BeginScene(),36409526599,,,
-Call,104,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0012F3BC --> 0x041F4D40)",36409573357,,,
-Call,105,<0x041F4D40> IDirect3DSurface9::GetDesc(0x0012F394),36409617609,,,
-Call,106,<0x041F4D40> IDirect3DSurface9::Release(),36409662462,,,
-Call,107,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0012F3BC --> 0x041F4D40)",36409707537,,,
-Call,108,<0x041F4D40> IDirect3DSurface9::GetDesc(0x0012F394),36409750972,,,
-Call,109,<0x041F4D40> IDirect3DSurface9::Release(),36409794277,,,
-Call,110,<0x041F4040> IDirect3DDevice9::SetViewport(0x0012F39C),36409839547,,,
-Call,111,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0012F6C8 --> 0x041F4D40)",36409906133,,,
-Call,112,<0x041F4040> IDirect3DDevice9::GetDepthStencilSurface(0x0012F6BC --> 0x041C7D68),36409950343,,,
-Call,113,"<0x041F4040> IDirect3DDevice9::Clear(0x00000000, NULL, 0x00000007, D3DCOLOR_ARGB(0xff,0x7f,0x7f,0x7f), 1.000f, 0x00000000)",36409994496,,,
-Call,114,<0x041C7D68> IDirect3DSurface9::Release(),36410040548,,,
-Call,115,<0x041F4D40> IDirect3DSurface9::Release(),36410083603,,,
-Call,116,<0x041F4040> IDirect3DDevice9::SetIndices(0x041C85B8),36410199387,,,
-Call,117,"<0x041F4040> IDirect3DDevice9::SetStreamSource(0, 0x041C84E8, 0, 12)",36410296534,,,
-Call,118,<0x041F4040> IDirect3DDevice9::SetVertexDeclaration(0x041C8820),36410343771,,,
-Call,119,"<0x041C8298> ID3DXEffect::SetMatrix(0xFAC1DD7B, 0x0012EECC)",36410391106,,,
-Call,120,<0x041C8298> ID3DXEffect::GetTechnique(0),36410437171,,,
-Call,121,<0x041C8298> ID3DXEffect::SetTechnique(0xFAC1D0CB),36410573271,,,
-Call,122,"<0x041C8298> ID3DXEffect::Begin(0x0012EF60, 0x00000000)",36410618823,,,
-Call,123,<0x041CACF0> IDirect3DStateBlock9::Capture(),36410633515,,,
-Call,124,<0x041C9AB8> IDirect3DStateBlock9::Capture(),36410680440,,,
-Call,125,<0x041C94E8> IDirect3DStateBlock9::Capture(),36410725060,,,
-Call,126,<0x041CA088> IDirect3DStateBlock9::Capture(),36410768165,,,
-Call,127,<0x041C8948> IDirect3DStateBlock9::Capture(),36410811430,,,
-Call,128,<0x041C8298> ID3DXEffect::BeginPass(0),36410886131,,,
-Call,129,<0x041F4040> IDirect3DDevice9::SetVertexShader(0x041C81E0),36410901798,,,
-Call,130,"<0x041F4040> IDirect3DDevice9::SetVertexShaderConstantF(0, 0x053E22E0, 4)",36410947800,,,
-Call,131,<0x041F4040> IDirect3DDevice9::SetPixelShader(0x041C8128),36410993338,,,
-Call,132,"<0x041F4040> IDirect3DDevice9::DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8, 0, 12)",36411069298,,,
-Call,133,<0x041C8298> ID3DXEffect::EndPass(),36411117723,,,
-Call,134,<0x041C8298> ID3DXEffect::End(),36411160953,,,
-Call,135,<0x041C8948> IDirect3DStateBlock9::Apply(),36411174055,,,
-Call,136,<0x041CA088> IDirect3DStateBlock9::Apply(),36411299753,,,
-Call,137,<0x041C94E8> IDirect3DStateBlock9::Apply(),36411354450,,,
-Call,138,<0x041C9AB8> IDirect3DStateBlock9::Apply(),36411407984,,,
-Call,139,<0x041CACF0> IDirect3DStateBlock9::Apply(),36411463799,,,
-Call,140,<0x041F4040> IDirect3DDevice9::EndScene(),36411573417,,,
-Call,141,<0x041F4D40> IDirect3DSurface9::Release(),36411627859,,,
-Call,142,<0x041C7D68> IDirect3DSurface9::Release(),36411680366,,,
-Call,143,"<0x041F4040> IDirect3DDevice9::Present(NULL, NULL, NULL, NULL)",36411737183,,,
-Frame,144,Frame 5,38611822165,5,2704679664,0.4
-Call,145,D3DPERF_GetStatus(),38611921000,,,
-User Marker,146,User Marker: Frame_Capture: 306 : tests\basic_system_test\import_test.cc,39111379596,,0,
-User Marker,147,User Marker: CaptureScreenContents,39111440170,,0,
-Call,148,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x003EBEC4 --> 0x041F4D40)",39111536980,,,
-Call,149,<0x041F4040> IDirect3DDevice9::GetDepthStencilSurface(0x003EBEC8 --> 0x041C7D68),39111596751,,,
-Call,150,<0x041F4040> IDirect3DDevice9::BeginScene(),39111652673,,,
-Call,151,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0012F3BC --> 0x041F4D40)",39111709028,,,
-Call,152,<0x041F4D40> IDirect3DSurface9::GetDesc(0x0012F394),39111762947,,,
-Call,153,<0x041F4D40> IDirect3DSurface9::Release(),39111820274,,,
-Call,154,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0012F3BC --> 0x041F4D40)",39111884080,,,
-Call,155,<0x041F4D40> IDirect3DSurface9::GetDesc(0x0012F394),39111938522,,,
-Call,156,<0x041F4D40> IDirect3DSurface9::Release(),39111981857,,,
-Call,157,<0x041F4040> IDirect3DDevice9::SetViewport(0x0012F39C),39112027207,,,
-Call,158,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0012F6C8 --> 0x041F4D40)",39112093744,,,
-Call,159,<0x041F4040> IDirect3DDevice9::GetDepthStencilSurface(0x0012F6BC --> 0x041C7D68),39112137584,,,
-Call,160,"<0x041F4040> IDirect3DDevice9::Clear(0x00000000, NULL, 0x00000007, D3DCOLOR_ARGB(0xff,0x7f,0x7f,0x7f), 1.000f, 0x00000000)",39112181704,,,
-Call,161,<0x041C7D68> IDirect3DSurface9::Release(),39112227771,,,
-Call,162,<0x041F4D40> IDirect3DSurface9::Release(),39112270774,,,
-Call,163,<0x041F4040> IDirect3DDevice9::SetIndices(0x041C85B8),39112405776,,,
-Call,164,"<0x041F4040> IDirect3DDevice9::SetStreamSource(0, 0x041C84E8, 0, 12)",39112461208,,,
-Call,165,<0x041F4040> IDirect3DDevice9::SetVertexDeclaration(0x041C8820),39112507971,,,
-Call,166,"<0x041C8298> ID3DXEffect::SetMatrix(0xFAC1DD7B, 0x0012EECC)",39112555123,,,
-Call,167,<0x041C8298> ID3DXEffect::GetTechnique(0),39112601068,,,
-Call,168,<0x041C8298> ID3DXEffect::SetTechnique(0xFAC1D0CB),39112644503,,,
-Call,169,"<0x041C8298> ID3DXEffect::Begin(0x0012EF60, 0x00000000)",39112688565,,,
-Call,170,<0x041CACF0> IDirect3DStateBlock9::Capture(),39112703112,,,
-Call,171,<0x041C9AB8> IDirect3DStateBlock9::Capture(),39112749709,,,
-Call,172,<0x041C94E8> IDirect3DStateBlock9::Capture(),39112794005,,,
-Call,173,<0x041CA088> IDirect3DStateBlock9::Capture(),39112837254,,,
-Call,174,<0x041C8948> IDirect3DStateBlock9::Capture(),39112880402,,,
-Call,175,<0x041C8298> ID3DXEffect::BeginPass(0),39112955206,,,
-Call,176,<0x041F4040> IDirect3DDevice9::SetVertexShader(0x041C81E0),39112970822,,,
-Call,177,"<0x041F4040> IDirect3DDevice9::SetVertexShaderConstantF(0, 0x053E22E0, 4)",39113026769,,,
-Call,178,<0x041F4040> IDirect3DDevice9::SetPixelShader(0x041C8128),39113072436,,,
-Call,179,"<0x041F4040> IDirect3DDevice9::DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8, 0, 12)",39113148480,,,
-Call,180,<0x041C8298> ID3DXEffect::EndPass(),39113196757,,,
-Call,181,<0x041C8298> ID3DXEffect::End(),39113239885,,,
-Call,182,<0x041C8948> IDirect3DStateBlock9::Apply(),39113252804,,,
-Call,183,<0x041CA088> IDirect3DStateBlock9::Apply(),39113297209,,,
-Call,184,<0x041C94E8> IDirect3DStateBlock9::Apply(),39113370402,,,
-Call,185,<0x041C9AB8> IDirect3DStateBlock9::Apply(),39113423302,,,
-Call,186,<0x041CACF0> IDirect3DStateBlock9::Apply(),39113468437,,,
-Call,187,<0x041F4040> IDirect3DDevice9::EndScene(),39113556772,,,
-Call,188,<0x041F4D40> IDirect3DSurface9::Release(),39113600702,,,
-Call,189,<0x041C7D68> IDirect3DSurface9::Release(),39113644717,,,
-Call,190,"<0x041F4040> IDirect3DDevice9::Present(NULL, NULL, NULL, NULL)",39113702049,,,
-Frame,191,Frame 6,41316567158,6,2768584865,0.4
-Call,192,D3DPERF_GetStatus(),41316651078,,,
-User Marker,193,User Marker: Frame_Capture: 306 : tests\basic_system_test\import_test.cc,41816443226,,0,
-User Marker,194,User Marker: CaptureScreenContents,41816519169,,0,
-Call,195,D3DPERF_GetStatus(),41816586445,,,
-User Marker,196,User Marker: EndCommandStreamCapture,41816632693,,0,
-Call,197,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x003EBEC4 --> 0x041F4D40)",41816688500,,,
-Call,198,<0x041F4040> IDirect3DDevice9::GetDepthStencilSurface(0x003EBEC8 --> 0x041C7D68),41816735932,,,
-Call,199,<0x041F4040> IDirect3DDevice9::BeginScene(),41816779852,,,
-Call,200,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0012F558 --> 0x041F4D40)",41816826552,,,
-Call,201,<0x041F4D40> IDirect3DSurface9::GetDesc(0x0012F530),41816870777,,,
-Call,202,<0x041F4D40> IDirect3DSurface9::Release(),41816915274,,,
-Call,203,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0012F558 --> 0x041F4D40)",41816960532,,,
-Call,204,<0x041F4D40> IDirect3DSurface9::GetDesc(0x0012F530),41817004137,,,
-Call,205,<0x041F4D40> IDirect3DSurface9::Release(),41817047360,,,
-Call,206,<0x041F4040> IDirect3DDevice9::SetViewport(0x0012F538),41817092544,,,
-Call,207,"<0x041F4040> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0012F864 --> 0x041F4D40)",41817159118,,,
-Call,208,<0x041F4040> IDirect3DDevice9::GetDepthStencilSurface(0x0012F858 --> 0x041C7D68),41817203298,,,
-Call,209,"<0x041F4040> IDirect3DDevice9::Clear(0x00000000, NULL, 0x00000007, D3DCOLOR_ARGB(0xff,0x7f,0x7f,0x7f), 1.000f, 0x00000000)",41817247511,,,
-Call,210,<0x041C7D68> IDirect3DSurface9::Release(),41817293471,,,
-Call,211,<0x041F4D40> IDirect3DSurface9::Release(),41817336286,,,
-Call,212,<0x041F4040> IDirect3DDevice9::SetIndices(0x041C85B8),41817458434,,,
-Call,213,"<0x041F4040> IDirect3DDevice9::SetStreamSource(0, 0x041C84E8, 0, 12)",41817509654,,,
-Call,214,<0x041F4040> IDirect3DDevice9::SetVertexDeclaration(0x041C8820),41817556511,,,
-Call,215,"<0x041C8298> ID3DXEffect::SetMatrix(0xFAC1DD7B, 0x0012F068)",41817604223,,,
-Call,216,<0x041C8298> ID3DXEffect::GetTechnique(0),41817649908,,,
-Call,217,<0x041C8298> ID3DXEffect::SetTechnique(0xFAC1D0CB),41817693486,,,
-Call,218,"<0x041C8298> ID3DXEffect::Begin(0x0012F0FC, 0x00000000)",41817737806,,,
-Call,219,<0x041CACF0> IDirect3DStateBlock9::Capture(),41817752540,,,
-Call,220,<0x041C9AB8> IDirect3DStateBlock9::Capture(),41817799022,,,
-Call,221,<0x041C94E8> IDirect3DStateBlock9::Capture(),41817843227,,,
-Call,222,<0x041CA088> IDirect3DStateBlock9::Capture(),41817886413,,,
-Call,223,<0x041C8948> IDirect3DStateBlock9::Capture(),41817929598,,,
-Call,224,<0x041C8298> ID3DXEffect::BeginPass(0),41818003948,,,
-Call,225,<0x041F4040> IDirect3DDevice9::SetVertexShader(0x041C81E0),41818019610,,,
-Call,226,"<0x041F4040> IDirect3DDevice9::SetVertexShaderConstantF(0, 0x053E22E0, 4)",41818065208,,,
-Call,227,<0x041F4040> IDirect3DDevice9::SetPixelShader(0x041C8128),41818110687,,,
-Call,228,"<0x041F4040> IDirect3DDevice9::DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8, 0, 12)",41818186683,,,
-Call,229,<0x041C8298> ID3DXEffect::EndPass(),41818234970,,,
-Call,230,<0x041C8298> ID3DXEffect::End(),41818278298,,,
-Call,231,<0x041C8948> IDirect3DStateBlock9::Apply(),41818291347,,,
-Call,232,<0x041CA088> IDirect3DStateBlock9::Apply(),41818378780,,,
-Call,233,<0x041C94E8> IDirect3DStateBlock9::Apply(),41818435942,,,
-Call,234,<0x041C9AB8> IDirect3DStateBlock9::Apply(),41818479202,,,
-Call,235,<0x041CACF0> IDirect3DStateBlock9::Apply(),41818523972,,,
-Call,236,<0x041F4040> IDirect3DDevice9::EndScene(),41818612302,,,
-Call,237,<0x041F4D40> IDirect3DSurface9::Release(),41818656510,,,
-Call,238,<0x041C7D68> IDirect3DSurface9::Release(),41818700222,,,
-Call,239,"<0x041F4040> IDirect3DDevice9::Present(NULL, NULL, NULL, NULL)",41818754391,,,
-Process End,240,End Process,44103702736,,0,
-Session End,241,End Session,44103702736,,0,
diff --git a/o3d/tests/bitmap_test/5kx5k.dds b/o3d/tests/bitmap_test/5kx5k.dds
deleted file mode 100644
index 626845b..0000000
--- a/o3d/tests/bitmap_test/5kx5k.dds
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/5kx5k.jpg b/o3d/tests/bitmap_test/5kx5k.jpg
deleted file mode 100644
index 2395bb3..0000000
--- a/o3d/tests/bitmap_test/5kx5k.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/5kx5k.png b/o3d/tests/bitmap_test/5kx5k.png
deleted file mode 100644
index 458ac24..0000000
--- a/o3d/tests/bitmap_test/5kx5k.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/5kx5k.tga b/o3d/tests/bitmap_test/5kx5k.tga
deleted file mode 100644
index 2db7349..0000000
--- a/o3d/tests/bitmap_test/5kx5k.tga
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/dds-dxt1-256x256-alpha.dds b/o3d/tests/bitmap_test/dds-dxt1-256x256-alpha.dds
deleted file mode 100644
index 79c1c19..0000000
--- a/o3d/tests/bitmap_test/dds-dxt1-256x256-alpha.dds
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/dds-dxt1-256x256-mipmap.dds b/o3d/tests/bitmap_test/dds-dxt1-256x256-mipmap.dds
deleted file mode 100644
index 921cab3..0000000
--- a/o3d/tests/bitmap_test/dds-dxt1-256x256-mipmap.dds
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/dds-dxt1-256x256.dds b/o3d/tests/bitmap_test/dds-dxt1-256x256.dds
deleted file mode 100644
index f5e60e2..0000000
--- a/o3d/tests/bitmap_test/dds-dxt1-256x256.dds
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/dds-dxt3-256x256-alpha.dds b/o3d/tests/bitmap_test/dds-dxt3-256x256-alpha.dds
deleted file mode 100644
index f7086b4..0000000
--- a/o3d/tests/bitmap_test/dds-dxt3-256x256-alpha.dds
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/dds-dxt3-256x256-mipmap.dds b/o3d/tests/bitmap_test/dds-dxt3-256x256-mipmap.dds
deleted file mode 100644
index a72239c..0000000
--- a/o3d/tests/bitmap_test/dds-dxt3-256x256-mipmap.dds
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/dds-dxt5-256x256-alpha.dds b/o3d/tests/bitmap_test/dds-dxt5-256x256-alpha.dds
deleted file mode 100644
index 388d000..0000000
--- a/o3d/tests/bitmap_test/dds-dxt5-256x256-alpha.dds
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/dds-dxt5-256x256-mipmap.dds b/o3d/tests/bitmap_test/dds-dxt5-256x256-mipmap.dds
deleted file mode 100644
index 45b6869..0000000
--- a/o3d/tests/bitmap_test/dds-dxt5-256x256-mipmap.dds
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/gif-256x256-interlaced.gif b/o3d/tests/bitmap_test/gif-256x256-interlaced.gif
deleted file mode 100644
index 7d8498e..0000000
--- a/o3d/tests/bitmap_test/gif-256x256-interlaced.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/gif-256x256.gif b/o3d/tests/bitmap_test/gif-256x256.gif
deleted file mode 100644
index fa81387..0000000
--- a/o3d/tests/bitmap_test/gif-256x256.gif
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/jpeg-256x256.jpg b/o3d/tests/bitmap_test/jpeg-256x256.jpg
deleted file mode 100644
index ae4448c..0000000
--- a/o3d/tests/bitmap_test/jpeg-256x256.jpg
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/png-20x14-4bit-palette.png b/o3d/tests/bitmap_test/png-20x14-4bit-palette.png
deleted file mode 100644
index 3f04186..0000000
--- a/o3d/tests/bitmap_test/png-20x14-4bit-palette.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/png-256x256-24bit-interlaced.png b/o3d/tests/bitmap_test/png-256x256-24bit-interlaced.png
deleted file mode 100644
index 37663d4..0000000
--- a/o3d/tests/bitmap_test/png-256x256-24bit-interlaced.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/png-256x256-24bit.png b/o3d/tests/bitmap_test/png-256x256-24bit.png
deleted file mode 100644
index 126dab8..0000000
--- a/o3d/tests/bitmap_test/png-256x256-24bit.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/png-256x256-32bit.png b/o3d/tests/bitmap_test/png-256x256-32bit.png
deleted file mode 100644
index 3ed12c2..0000000
--- a/o3d/tests/bitmap_test/png-256x256-32bit.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/png-256x256-8bit-palette-alpha.png b/o3d/tests/bitmap_test/png-256x256-8bit-palette-alpha.png
deleted file mode 100644
index 35b61a9..0000000
--- a/o3d/tests/bitmap_test/png-256x256-8bit-palette-alpha.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/png-256x256-8bit-palette.png b/o3d/tests/bitmap_test/png-256x256-8bit-palette.png
deleted file mode 100644
index 7134cf7..0000000
--- a/o3d/tests/bitmap_test/png-256x256-8bit-palette.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/png-2x2-24bit-drawimage-src.png b/o3d/tests/bitmap_test/png-2x2-24bit-drawimage-src.png
deleted file mode 100644
index 0c0adff..0000000
--- a/o3d/tests/bitmap_test/png-2x2-24bit-drawimage-src.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/png-4x4-24bit-drawimage-argb8-src.png b/o3d/tests/bitmap_test/png-4x4-24bit-drawimage-argb8-src.png
deleted file mode 100644
index e386bce..0000000
--- a/o3d/tests/bitmap_test/png-4x4-24bit-drawimage-argb8-src.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/png-4x4-24bit-drawimage-src.png b/o3d/tests/bitmap_test/png-4x4-24bit-drawimage-src.png
deleted file mode 100644
index 7fd68f3..0000000
--- a/o3d/tests/bitmap_test/png-4x4-24bit-drawimage-src.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/png-8x4-24bit-drawimage-argb8-dest.png b/o3d/tests/bitmap_test/png-8x4-24bit-drawimage-argb8-dest.png
deleted file mode 100644
index 1bbc2be..0000000
--- a/o3d/tests/bitmap_test/png-8x4-24bit-drawimage-argb8-dest.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/png-8x4-24bit-drawimage-dest.png b/o3d/tests/bitmap_test/png-8x4-24bit-drawimage-dest.png
deleted file mode 100644
index e162044..0000000
--- a/o3d/tests/bitmap_test/png-8x4-24bit-drawimage-dest.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/png-8x8-24bit-drawimage-src.png b/o3d/tests/bitmap_test/png-8x8-24bit-drawimage-src.png
deleted file mode 100644
index 529b017..0000000
--- a/o3d/tests/bitmap_test/png-8x8-24bit-drawimage-src.png
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/test_source.psd b/o3d/tests/bitmap_test/test_source.psd
deleted file mode 100644
index cd67ce4..0000000
--- a/o3d/tests/bitmap_test/test_source.psd
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/tga-256x256-24bit.tga b/o3d/tests/bitmap_test/tga-256x256-24bit.tga
deleted file mode 100644
index 5619323..0000000
--- a/o3d/tests/bitmap_test/tga-256x256-24bit.tga
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/bitmap_test/tga-256x256-32bit.tga b/o3d/tests/bitmap_test/tga-256x256-32bit.tga
deleted file mode 100644
index 1d20f8c..0000000
--- a/o3d/tests/bitmap_test/tga-256x256-32bit.tga
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/common/cross/main.cc b/o3d/tests/common/cross/main.cc
deleted file mode 100644
index 540107d..0000000
--- a/o3d/tests/common/cross/main.cc
+++ /dev/null
@@ -1,49 +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.
- */
-
-
-// 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
-int test_main(int argc, wchar_t **argv) {
-#else
-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/cross/test_utils.cc b/o3d/tests/common/cross/test_utils.cc
deleted file mode 100644
index 2a2a6af..0000000
--- a/o3d/tests/common/cross/test_utils.cc
+++ /dev/null
@@ -1,68 +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.
- */
-
-
-// useful utility functions for unit/functional testing
-
-#include "tests/common/cross/test_utils.h"
-#include <sys/stat.h>
-#include "core/cross/client.h"
-#include "import/cross/targz_processor.h"
-#include "tests/common/win/testing_common.h"
-
-namespace test_utils {
-
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-uint8 *ReadFile(o3d::String file, size_t *data_size) {
- FILE *fp = fopen(file.c_str(), "rb");
-
- if (fp == NULL) return NULL;
-
- // Figure out the file length
- struct stat file_info;
- stat(file.c_str(), &file_info);
- size_t file_size = file_info.st_size;
-
- // Read it all into memory
- // TODO: this should be new[] instead of malloc.
- uint8 *data = static_cast<uint8*>(malloc(file_size));
- DCHECK(data);
-
- int bytes_read = fread(data, 1, file_size, fp);
- fclose(fp);
- DCHECK_EQ(static_cast<unsigned>(bytes_read), file_size);
-
- // Return file size and data
- if (data_size) *data_size = file_size;
- return data;
-}
-
-} // namespace test_utils
diff --git a/o3d/tests/common/cross/test_utils.h b/o3d/tests/common/cross/test_utils.h
deleted file mode 100644
index 1d3c54f..0000000
--- a/o3d/tests/common/cross/test_utils.h
+++ /dev/null
@@ -1,51 +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.
- */
-
-
-// useful utility functions for unit/functional testing
-
-#ifndef O3D_TESTS_COMMON_CROSS_TEST_UTILS_H_
-#define O3D_TESTS_COMMON_CROSS_TEST_UTILS_H_
-
-#include "core/cross/client.h"
-#include "tests/common/win/testing_common.h"
-
-namespace test_utils {
-
-// Reads the given file into memory and returns a pointer
-// to its contents. The file size is returned in |data_size|
-// The caller is responsible for calling free()
-// NULL is returned if there's an error
-uint8 *ReadFile(o3d::String file, size_t *data_size);
-
-} // namespace test_utils
-
-#endif // O3D_TESTS_COMMON_CROSS_TEST_UTILS_H_
diff --git a/o3d/tests/common/linux/testing_common.cc b/o3d/tests/common/linux/testing_common.cc
deleted file mode 100644
index d563ce6..0000000
--- a/o3d/tests/common/linux/testing_common.cc
+++ /dev/null
@@ -1,171 +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.
- */
-
-
-// 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
-
-#include "core/cross/client_info.h"
-#include "core/cross/class_manager.h"
-#include "core/cross/evaluation_counter.h"
-#include "core/cross/install_check.h"
-#include "core/cross/features.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/profiler.h"
-#include "core/cross/renderer.h"
-#include "core/cross/renderer_platform.h"
-#include "core/cross/service_locator.h"
-#include "core/cross/types.h"
-
-o3d::String *g_program_path = NULL;
-o3d::String *g_program_name = NULL;
-o3d::Renderer* g_renderer = NULL;
-o3d::ServiceLocator* g_service_locator = NULL;
-o3d::DisplayWindow* g_display_window = NULL;
-
-Display *g_display = NULL;
-Window g_window = 0;
-
-static char kOffScreenRenderer[] = "O3D_D3D9_OFF_SCREEN";
-
-extern int test_main(int argc, char **argv);
-
-int main(int argc, char *argv[]) {
- std::string error;
- if (!o3d::RendererInstallCheck(&error)) {
- return false;
- }
-
- std::string program_path(argv[0]);
- std::string program_name;
-
- // Remove all characters starting with last '/'.
- size_t backslash_pos = program_path.rfind('/');
- if (backslash_pos != o3d::String::npos) {
- program_name = program_path.substr(backslash_pos + 1);
- if (backslash_pos == 0) {
- program_path = "/";
- } else {
- program_path.erase(backslash_pos);
- }
- } else {
- program_name = program_path;
- program_path = ".";
- }
-
- g_program_path = &program_path;
- g_program_name = &program_name;
-
- o3d::ServiceLocator service_locator;
- g_service_locator = &service_locator;
-
- o3d::EvaluationCounter evaluation_counter(g_service_locator);
- o3d::ClassManager class_manager(g_service_locator);
- o3d::ClientInfoManager client_info_manager(g_service_locator);
- o3d::ObjectManager object_manager(g_service_locator);
- o3d::Profiler profiler(g_service_locator);
- o3d::Features features(g_service_locator);
-
- // create a renderer device based on the current platform
- g_renderer = o3d::Renderer::CreateDefaultRenderer(g_service_locator);
-
- g_display = ::XOpenDisplay(0);
- int attribs[] = {
- GLX_RGBA,
- GLX_DOUBLEBUFFER,
- GLX_RED_SIZE, 1,
- GLX_GREEN_SIZE, 1,
- GLX_BLUE_SIZE, 1,
- None
- };
- XVisualInfo *visualInfo = ::glXChooseVisual(g_display,
- DefaultScreen(g_display),
- attribs);
- Window root_window = RootWindow(g_display, visualInfo->screen);
- Colormap colorMap = ::XCreateColormap(g_display,
- root_window,
- visualInfo->visual,
- AllocNone);
-
- XSetWindowAttributes windowAttributes;
- windowAttributes.colormap = colorMap;
- windowAttributes.border_pixel = 0;
- windowAttributes.event_mask = StructureNotifyMask;
- g_window = ::XCreateWindow(g_display,
- root_window,
- 0, 0, 800, 600,
- 0,
- visualInfo->depth,
- InputOutput,
- visualInfo->visual,
- CWBorderPixel|CWColormap|CWEventMask,
- &windowAttributes);
- ::XFree(visualInfo);
- ::XMapWindow(g_display, g_window);
- ::XSync(g_display, True);
-
- o3d::DisplayWindowLinux* display_window =
- new o3d::DisplayWindowLinux();
- display_window->set_display(g_display);
- display_window->set_window(g_window);
- g_display_window = display_window;
-
- // Initialize the renderer for off-screen rendering if kOffScreenRenderer
- // is in the environment.
- bool success;
- if (getenv(kOffScreenRenderer)) {
- success =
- g_renderer->Init(*g_display_window, true) == o3d::Renderer::SUCCESS;
- } else {
- success =
- g_renderer->Init(*g_display_window, false) == o3d::Renderer::SUCCESS;
- }
-
- int ret = EXIT_FAILURE;
- if (!success) {
- ::fprintf(stdout, "Failed to initialize renderer\n");
- } else {
- ret = test_main(argc, argv);
- }
-
- g_renderer->Destroy();
- delete g_renderer;
- g_renderer = NULL;
-
- delete display_window;
- g_display_window = NULL;
- g_program_path = NULL;
- g_program_name = NULL;
- ::XCloseDisplay(g_display);
-
- return ret;
-}
diff --git a/o3d/tests/common/mac/testing_common.mm b/o3d/tests/common/mac/testing_common.mm
deleted file mode 100644
index 0d2a2e0..0000000
--- a/o3d/tests/common/mac/testing_common.mm
+++ /dev/null
@@ -1,141 +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.
- */
-
-
-// Contains macintosh-specific code for setting up the Client object
-// used in the unit tests.
-
-#include <GL/glew.h>
-#include <OpenGL/OpenGL.h>
-#include <OpenGL/gl.h>
-#include <OpenGL/glu.h>
-#include <GLUT/glut.h>
-#include <AGL/agl.h>
-
-#include "core/cross/client_info.h"
-#include "core/cross/class_manager.h"
-#include "core/cross/evaluation_counter.h"
-#include "core/cross/install_check.h"
-#include "core/cross/features.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/profiler.h"
-#include "core/cross/renderer.h"
-#include "core/cross/renderer_platform.h"
-#include "core/cross/service_locator.h"
-#include "core/cross/types.h"
-
-o3d::String *g_program_path = NULL;
-o3d::String *g_program_name = NULL;
-o3d::Renderer* g_renderer = NULL;
-o3d::ServiceLocator* g_service_locator = NULL;
-o3d::DisplayWindow* g_display_window = NULL;
-
-const unsigned int kWindowWidth = 800;
-const unsigned int kWindowHeight = 600;
-
-extern int test_main(int argc, char **argv);
-
-int main(int argc, char *argv[]) {
- NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
-
- std::string error;
- if (!o3d::RendererInstallCheck(&error)) {
- return false;
- }
-
- std::string program_path(argv[0]);
- std::string program_name;
-
- // Remove all characters starting with last '/'.
- size_t backslash_pos = program_path.rfind('/');
- if (backslash_pos != o3d::String::npos) {
- program_name = program_path.substr(backslash_pos + 1);
- if (backslash_pos == 0) {
- program_path = "/";
- } else {
- program_path.erase(backslash_pos);
- }
- } else {
- program_name = program_path;
- program_path = ".";
- }
-
- g_program_path = &program_path;
- g_program_name = &program_name;
-
- o3d::ServiceLocator service_locator;
- g_service_locator = &service_locator;
-
- o3d::EvaluationCounter evaluation_counter(g_service_locator);
- o3d::ClassManager class_manager(g_service_locator);
- o3d::ClientInfoManager client_info_manager(g_service_locator);
- o3d::ObjectManager object_manager(g_service_locator);
- o3d::Profiler profiler(g_service_locator);
- o3d::Features features(g_service_locator);
-
- // create a renderer device based on the current platform
- g_renderer = o3d::Renderer::CreateDefaultRenderer(g_service_locator);
-
- glutInit(&argc, argv);
- glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STENCIL);
- glutInitWindowSize(kWindowWidth, kWindowHeight);
- glutInitWindowPosition(100, 100);
- glutCreateWindow(argv[0]);
-
- // Give the renderer the CGL context
- CGLContextObj cgl_context = CGLGetCurrentContext();
- o3d::DisplayWindowMac* display_window = new o3d::DisplayWindowMac();
- g_display_window = display_window;
- display_window->set_agl_context(NULL);
- display_window->set_cgl_context(cgl_context);
- bool success = g_renderer->Init(*g_display_window,
- false) == o3d::Renderer::SUCCESS;
-
- int ret = EXIT_FAILURE;
- if (!success) {
- ::fprintf(stdout, "Failed to initialize renderer\n");
- } else {
- ret = test_main(argc, argv);
- }
-
- g_renderer->Destroy();
- delete g_renderer;
- g_renderer = NULL;
-
- delete display_window;
- g_display_window = NULL;
- g_program_path = NULL;
- g_program_name = NULL;
-
- [pool release];
-
- return ret;
-}
diff --git a/o3d/tests/common/win/dxcapture.cc b/o3d/tests/common/win/dxcapture.cc
deleted file mode 100644
index 0afb91b..0000000
--- a/o3d/tests/common/win/dxcapture.cc
+++ /dev/null
@@ -1,140 +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.
- */
-
-
-// File containing implementation routines for the DirectX testing framework
-// framebuffer and command stream capture routines.
-
-#include "tests/common/win/dxcapture.h"
-
-#include <d3dx9.h>
-
-#include "core/cross/types.h"
-#include "core/win/d3d9/d3d_entry_points.h"
-#include "core/win/d3d9/renderer_d3d9.h"
-#include "core/win/d3d9/utils_d3d9.h"
-#include "tests/common/win/testing_common.h"
-
-namespace directx_capture {
-
-void StartCommandCapture(const wchar_t* stream_name) {
-#if defined(RENDERER_D3D9)
- if (D3DPERF_GetStatus()) {
- D3DPERF_SetMarker(0, stream_name);
- D3DPERF_SetMarker(0, L"BeginCommandStreamCapture");
- }
-#endif
-}
-
-void EndCommandCapture() {
-#if defined(RENDERER_D3D9)
- if (D3DPERF_GetStatus()) {
- D3DPERF_SetMarker(0, L"EndCommandStreamCapture");
- }
-#endif
-}
-
-void CaptureFramebuffer(const wchar_t* buffer_metadata) {
-#if defined(RENDERER_D3D9)
- // Keep track of the invocation count for output file-naming purposes.
- static int g_call_count = 0;
- ++g_call_count;
-
- // If PIX is present, then send a message to PIX requesting a framebuffer
- // capture.
- if (D3DPERF_GetStatus()) {
- ::Sleep(500);
- D3DPERF_SetMarker(0, buffer_metadata);
- D3DPERF_SetMarker(0, L"CaptureScreenContents");
- } else {
- // Otherwise, explicitly read the contents of the buffer into system memory
- // and story a .png file.
- o3d::RendererD3D9* d3d9_renderer =
- down_cast<o3d::RendererD3D9*>(g_renderer);
- LPDIRECT3DDEVICE9 device = d3d9_renderer->d3d_device();
- IDirect3DSurface9* system_surface = NULL;
- IDirect3DSurface9* current_surface = NULL;
-
- HR(device->GetRenderTarget(0, &current_surface));
- D3DSURFACE_DESC surface_description;
- HR(current_surface->GetDesc(&surface_description));
-
- // Construct an intermediate surface with multi-sampling disabled.
- // This surface is required because GetRenderTargetData(...) will fail
- // for multi-sampled targets. One must first down-sample to a
- // non-multi-sample buffer, and then copy from that intermediate buffer
- // to a main memory surface.
- IDirect3DSurface9* intermediate_target;
- HR(device->CreateRenderTarget(surface_description.Width,
- surface_description.Height,
- surface_description.Format,
- D3DMULTISAMPLE_NONE,
- 0,
- FALSE,
- &intermediate_target,
- NULL));
-
- HR(device->StretchRect(current_surface,
- NULL,
- intermediate_target,
- NULL,
- D3DTEXF_NONE));
-
- HR(device->CreateOffscreenPlainSurface(surface_description.Width,
- surface_description.Height,
- surface_description.Format,
- D3DPOOL_SYSTEMMEM,
- &system_surface,
- NULL));
-
- HR(device->GetRenderTargetData(intermediate_target, system_surface));
-
- const o3d::String file_name(*g_program_name +
- o3d::String("_") +
- UintToString(g_call_count) +
- o3d::String(".png"));
-
- std::wstring file_name_utf16 = UTF8ToWide(file_name);
-
- HR(o3d::D3DXSaveSurfaceToFile(file_name_utf16.c_str(),
- D3DXIFF_PNG,
- system_surface,
- NULL,
- NULL));
-
- system_surface->Release();
- intermediate_target->Release();
- current_surface->Release();
- }
-#endif
-}
-
-} // end namespace directx_capture
diff --git a/o3d/tests/common/win/dxcapture.h b/o3d/tests/common/win/dxcapture.h
deleted file mode 100644
index c62ce2c..0000000
--- a/o3d/tests/common/win/dxcapture.h
+++ /dev/null
@@ -1,68 +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.
- */
-
-
-// File exposing a set functions to capture the direct-X command
-// stream and frame-buffer contents. This class is to be used for
-// regression-testing purposes.
-
-#ifndef O3D_TESTS_COMMON_WIN_DXCAPTURE_H__
-#define O3D_TESTS_COMMON_WIN_DXCAPTURE_H__
-
-// Singleton class encapsulating functionality to capture DX command streams
-// and framebuffer contents.
-namespace directx_capture {
-
-// Routine to inform the testing framework that graphics command logs
-// should be captured. The contents of stream_name will be embedded in the
-// logs for ease of human readability.
-// NOTE: Requires that the executable be invoked through PIX. Fn is a no-op
-// when the PIX environment is not present.
-void StartCommandCapture(const wchar_t* stream_name);
-
-// Invoke to disable stream capture. Note that the start/end routines
-// are NOT re-entrant. One cannot nest stream captures.
-// NOTE: Requires that the executable be invoked through PIX. Fn is a no-op
-// when the PIX environment is not present.
-void EndCommandCapture();
-
-// Invoke to capture the current contents of the framebuffer. If stream
-// capture is active, the contents of buffer_metadata will be written to the
-// logs.
-// NOTE: If PIX is present, then the frame-buffer is captured and stored by
-// PIX according to the PIXRun file. Otherwise, the contents of the current
-// render target surface are saved explicitly by the code. The meta-data
-// is ignored when PIX is not present.
-void CaptureFramebuffer(const wchar_t* buffer_metadata);
-
-} // end namespace directx_capture
-
-#endif // O3D_TESTS_COMMON_WIN_DXCAPTURE_H__
diff --git a/o3d/tests/common/win/system_test.h b/o3d/tests/common/win/system_test.h
deleted file mode 100644
index 65e060c..0000000
--- a/o3d/tests/common/win/system_test.h
+++ /dev/null
@@ -1,82 +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.
- */
-
-
-// File containing assert-macros for use in O3D rendering system-tests.
-
-#ifndef O3D_TESTS_COMMON_WIN_SYSTEM_TEST_H__
-#define O3D_TESTS_COMMON_WIN_SYSTEM_TEST_H__
-
-#ifdef OS_WIN
-
-#include "tests/common/win/dxcapture.h"
-
-// A helper-macro to widen strings.
-#define WIDEN_STRING2(x) L##x
-#define WIDEN_STRING(x) WIDEN_STRING2(x)
-
-// Initiates capture of the DX command stream. The start of the captured
-// stream will contain a message indicating the values of the line and
-// file arguments.
-inline void BeginStreamCapture(int line, const wchar_t* file) {
- wchar_t debug_buffer[2048];
- _snwprintf_s(debug_buffer, 2048, L"Stream_Capture: %i : %s", line, file);
- directx_capture::StartCommandCapture(debug_buffer);
-}
-
-// Places a debug marker in the graphics command stream containing
-// the values of line and file, and requests that the current framebuffer
-// contents be captured.
-inline void CaptureFrameBuffer(int line, const wchar_t* file) {
- wchar_t debug_buffer[2048];
- _snwprintf_s(debug_buffer, 2048, L"Frame_Capture: %i : %s", line, file);
- directx_capture::CaptureFramebuffer(debug_buffer);
-}
-
-// Macros placing stream-capture begin-end waypoints in the testing application.
-#define BEGIN_ASSERT_STREAM_CAPTURE() \
- BeginStreamCapture(__LINE__, WIDEN_STRING(__FILE__))
-
-#define END_ASSERT_STREAM_CAPTURE() \
- directx_capture::EndCommandCapture()
-
-#define ASSERT_FRAMEBUFFER() \
- CaptureFrameBuffer(__LINE__, WIDEN_STRING(__FILE__))
-
-#else
-
-#define BEGIN_ASSERT_STREAM_CAPTURE() do {} while (0)
-#define END_ASSERT_STREAM_CAPTURE() do {} while (0)
-#define ASSERT_FRAMEBUFFER() do {} while (0)
-
-#endif
-
-#endif // O3D_TESTS_COMMON_WIN_SYSTEM_TEST_H__
diff --git a/o3d/tests/common/win/testing_common.cc b/o3d/tests/common/win/testing_common.cc
deleted file mode 100644
index 7ab0bb2..0000000
--- a/o3d/tests/common/win/testing_common.cc
+++ /dev/null
@@ -1,212 +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.
- */
-
-// 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
-
-#include <windows.h>
-#include <Shellapi.h>
-
-#include "tests/common/win/testing_common.h"
-#include "core/cross/install_check.h"
-#include "core/cross/service_locator.h"
-#include "core/cross/evaluation_counter.h"
-#include "core/cross/client_info.h"
-#include "core/cross/class_manager.h"
-#include "core/cross/features.h"
-#include "core/cross/object_manager.h"
-#include "core/cross/profiler.h"
-#include "core/cross/renderer.h"
-#include "core/cross/renderer_platform.h"
-#include "core/cross/types.h"
-#include "core/win/display_window_win.h"
-
-using o3d::DisplayWindowWindows;
-
-const int kWindowWidth = 16;
-const int kWindowHeight = 16;
-
-o3d::ServiceLocator* g_service_locator = NULL;
-o3d::DisplayWindow* g_display_window = NULL;
-
-HWND g_window_handle = NULL;
-
-o3d::String *g_program_path = NULL;
-o3d::String *g_program_name = NULL;
-o3d::Renderer* g_renderer = NULL;
-
-static wchar_t kOffScreenRenderer[] = L"O3D_D3D9_OFF_SCREEN";
-
-extern int test_main(int argc, wchar_t **argv);
-
-LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
- return true;
-}
-
-// Handles some errors that would typically cause an OS dialog box to appear.
-LONG WINAPI LocalUnhandledExceptionFilter(EXCEPTION_POINTERS* pep) {
- fprintf(stdout, "ERROR: Unhandled Exception\n");
- exit(EXIT_FAILURE);
-}
-
-// Main entry point for the app. Creates a new window, and calls main()
-int WINAPI WinMain(HINSTANCE instance,
- HINSTANCE prev_instance,
- LPSTR cmd_line,
- int n_cmd_show) {
- // Turn off some of the OS error dialogs.
- ::SetUnhandledExceptionFilter(LocalUnhandledExceptionFilter);
-
- std::string error;
- if (!o3d::RendererInstallCheck(&error)) {
- return false;
- }
- WNDCLASSEX wc = {0};
-
- wc.lpszClassName = L"MY_WINDOWS_CLASS";
- wc.cbSize = sizeof(WNDCLASSEX);
- wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
- wc.lpfnWndProc = ::WindowProc;
- wc.cbClsExtra = 0;
- wc.cbWndExtra = 0;
- wc.hInstance = instance;
- wc.hIcon = ::LoadIcon(instance, IDI_APPLICATION);
- wc.hIconSm = NULL;
- wc.hCursor = ::LoadCursor(instance, IDC_ARROW);
- wc.hbrBackground = static_cast<HBRUSH>(::GetStockObject(BLACK_BRUSH));
- wc.lpszMenuName = NULL;
-
- if (!::RegisterClassEx(&wc))
- return false;
-
- // Leaving this window onscreen leads to a redraw error which makes it
- // a hassle to debug tests in an IDE, so we place the window somewhere that
- // won't happen.
- g_window_handle = ::CreateWindowExW(NULL,
- wc.lpszClassName,
- L"",
- WS_OVERLAPPEDWINDOW,
- 10,
- 10,
- kWindowWidth,
- kWindowHeight,
- 0,
- 0,
- instance,
- 0);
-
- if (g_window_handle == NULL)
- return false;
-
- static wchar_t program_filename[512];
- ::GetModuleFileNameW(NULL, program_filename, sizeof(program_filename));
- program_filename[511] = 0;
-
- std::wstring program_path(program_filename);
- std::wstring program_name;
-
- // Remove all characters starting with last '\'.
- size_t backslash_pos = program_path.rfind('\\');
- if (backslash_pos != o3d::String::npos) {
- program_name = &program_filename[backslash_pos + 1];
- program_path.erase(backslash_pos);
- } else {
- program_name = program_path;
- }
-
- o3d::String program_path_utf8 = WideToUTF8(program_path);
- o3d::String program_name_utf8 = WideToUTF8(program_name);
- g_program_path = &program_path_utf8;
- g_program_name = &program_name_utf8;
-
- o3d::ServiceLocator service_locator;
- g_service_locator = &service_locator;
-
- o3d::EvaluationCounter evaluation_counter(g_service_locator);
- o3d::ClassManager class_manager(g_service_locator);
- o3d::ClientInfoManager client_info_manager(g_service_locator);
- o3d::ObjectManager object_manager(g_service_locator);
- o3d::Profiler profiler(g_service_locator);
- o3d::Features features(g_service_locator);
-
- // 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;
-
- DisplayWindowWindows* display_window = new o3d::DisplayWindowWindows;
- display_window->set_hwnd(g_window_handle);
-
- g_display_window = display_window;
- bool offscreen = (::GetEnvironmentVariableW(kOffScreenRenderer,
- NULL, 0) != 0);
- if (offscreen) {
- success =
- g_renderer->Init(*g_display_window, true) == o3d::Renderer::SUCCESS;
- } else {
- success =
- g_renderer->Init(*g_display_window, false) == o3d::Renderer::SUCCESS;
- if (success) {
- ::SetWindowPos(g_window_handle, HWND_TOPMOST, 0, 0, 0, 0,
- SWP_NOMOVE | SWP_NOSIZE);
- ::ShowWindow(g_window_handle, SW_SHOWNORMAL);
- }
- }
-
- int ret = EXIT_FAILURE;
- if (!success) {
- if (offscreen) {
- ::fprintf(stdout, "Failed to initialize OFFSCREEN renderer\n");
- } else {
- ::fprintf(stdout, "Failed to initialize on screen renderer\n");
- }
- } else {
- // Invoke the main entry point with the command-line arguments
- int arg_count;
- LPWSTR *arg_values = ::CommandLineToArgvW(::GetCommandLine(), &arg_count);
- ret = ::test_main(arg_count, arg_values);
- ::LocalFree(arg_values);
- g_renderer->Destroy();
- }
-
- delete g_renderer;
- g_renderer = NULL;
-
- delete display_window;
- g_display_window = NULL;
- g_program_path = NULL;
- g_program_name = NULL;
-
- return ret;
-}
diff --git a/o3d/tests/common/win/testing_common.h b/o3d/tests/common/win/testing_common.h
deleted file mode 100644
index 1b282f3..0000000
--- a/o3d/tests/common/win/testing_common.h
+++ /dev/null
@@ -1,66 +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.
- */
-
-
-// Set of external declarations for global objects required for O3D
-// testing.
-
-#ifndef O3D_TESTS_COMMON_WIN_TESTING_COMMON_H__
-#define O3D_TESTS_COMMON_WIN_TESTING_COMMON_H__
-
-#include "core/cross/types.h"
-#include "gtest/gtest.h"
-
-namespace o3d {
-class ServiceLocator;
-class Renderer;
-}
-
-extern o3d::ServiceLocator* g_service_locator;
-
-// g_renderer should be declared in a separate .cc file. The
-// code in this file must remain platform agnostic.
-extern o3d::Renderer* g_renderer;
-
-// Path to the executable, used to load files relative to it.
-extern o3d::String *g_program_path;
-
-// the window handle used to create the current window, used to instance a
-// specific Renderer class.
-#if defined(OS_WIN)
-extern HWND g_window_handle;
-#endif
-// Un-qualified name of the executable, stripped of all path information.
-// Note that the executable extension is included in this string.
-extern o3d::String* g_program_name;
-
-
-#endif // O3D_TESTS_COMMON_WIN_TESTING_COMMON_H__
diff --git a/o3d/tests/keyboard_info.html b/o3d/tests/keyboard_info.html
deleted file mode 100644
index 8e737da..0000000
--- a/o3d/tests/keyboard_info.html
+++ /dev/null
@@ -1,126 +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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
- <meta http-equiv="content-type" content="text/html; charset=utf-8">
- <title>Keyboard Events</title>
-
- <style>
- div.debug {
- border:thin dotted gray;
- padding:1em;
- height:150px;
- overflow:scroll;
- }
- </style>
-
-
-<script type="text/javascript" charset="utf-8">
-
-function propsOf(event) {
- var property, propCollection = "";
- for(property in event)
- propCollection += (property + ":" + event[property] + "/");
- return propCollection;
-}
-
-
-function charValue(c) {
- return (c == 0) ? 'none' : String.fromCharCode(c);
-}
-
-function keyPropsOf(event) {
- var props = ['type', 'keyCode', 'charCode', 'keyIdentifier', 'which',
- 'timeStamp', 'isTrusted'];
- var property, propCollection = "";
- for(property in props) {
- var pName = props[property];
- propCollection += (pName + ":" + event[pName] + '<br>');
- }
- propCollection += 'unicode (char, key): ' + charValue(event.charCode) + ', ' +
- charValue(event.keyCode);
- return propCollection;
-}
-
-function setField(the_id, the_value) {
- var field = document.getElementById(the_id);
- field.innerHTML = the_value;
-}
-
-function debugLogEvent(in_event, name) {
- var cb = document.getElementById('checkbox');
- var event = (in_event) ? in_event : window.event;
- setField(name, ((cb.checked) ? propsOf(event) : keyPropsOf(event)));
-}
-
-function keyUp(event) {
- debugLogEvent(event, 'KeyUp_Field');
-}
-
-function keyDown(event) {
- setField('KeyUp_Field', '');
- setField('KeyDown_Field', '');
- setField('KeyPress_Field', '');
- debugLogEvent(event, 'KeyDown_Field');
-}
-
-
-function keyPressed(event) {
- debugLogEvent(event, 'KeyPress_Field');
-}
-
-function init() {
- var field = document.getElementById('KeyDown_Field');
- field.focus();
-}
-
-window.document.onkeypress = keyPressed;
-window.document.onkeyup = keyUp;
-window.document.onkeydown = keyDown;
-window.onload = init;
-
-</script>
-</head>
-<body>
-
-<div id='KeyDown_Field' class='debug'> </div>
-<div id='KeyPress_Field' class='debug'> </div>
-<div id='KeyUp_Field' class='debug'> </div>
-<form>
-<br>
-<input name="Display All Fields" type="checkbox" id='checkbox'>Display All</input>
-</form>
-
-</body>
-</html>
diff --git a/o3d/tests/lab/ChangeResolution/build.bat b/o3d/tests/lab/ChangeResolution/build.bat
deleted file mode 100644
index d0ddcf9..0000000
--- a/o3d/tests/lab/ChangeResolution/build.bat
+++ /dev/null
@@ -1,21 +0,0 @@
-@echo off
-REM Builds the change resolution project.
-
-:vs2005
-reg query HKLM\Software\Microsoft\VisualStudio\8.0 /v InstallDir || goto vs2008
-set vs_reg=HKLM\Software\Microsoft\VisualStudio\8.0
-goto getkey
-
-:vs2008
-reg query HKLM\Software\Microsoft\VisualStudio\9.0 /v InstallDir || goto vsNone
-set vs_reg=HKLM\Software\Microsoft\VisualStudio\9.0
-goto getkey
-
-:vsNone
-echo Visual Studio path cannot be found in registry. Are you using 2005 or 2008?
-exit
-
-:getkey
-for /f "tokens=2,*" %%a in ('reg query %vs_reg% /v InstallDir ^| findstr InstallDir') do set vs_dir=%%b
-
-"%vs_dir%devenv.com" change_resolution.sln /build \ No newline at end of file
diff --git a/o3d/tests/lab/ChangeResolution/change_resolution.cpp b/o3d/tests/lab/ChangeResolution/change_resolution.cpp
deleted file mode 100644
index a5ca125..0000000
--- a/o3d/tests/lab/ChangeResolution/change_resolution.cpp
+++ /dev/null
@@ -1,123 +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.
- */
-
-
-// Tool to change the screen resolution on Windows.
-
-#include <stdio.h>
-#include <wchar.h>
-#include "Windows.h"
-
-
-int wmain(int argc, wchar_t* argv[]) {
- if (argc == 1) {
- // Output current resolution and bits per pixel.
- DEVMODE dmode;
- memset(&dmode, 0, sizeof(DEVMODE));
- if (EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dmode)) {
- printf("Current settings (X resolution, Y resolution, bits per "
- "pixel):\n");
- printf("%lu\n%lu\n%lu\n", dmode.dmPelsWidth, dmode.dmPelsHeight,
- dmode.dmBitsPerPel);
- return 0;
- } else {
- printf("Failed to retrieve current resolution.\n");
- return 1;
- }
- } else if (argc != 4) {
- printf("Pass 3 args: X resolution, Y resolution, and bits per pixel to "
- "change to or no args to view current settings.");
- return 1;
- }
-
- // Read and validate arguments.
- int width = 0;
- if (!swscanf_s((const wchar_t *)argv[1], L"%d", &width)) {
- printf("Invalid value for width. It must be a number.");
- return 1;
- }
- int height = 0;
- if (!swscanf_s((const wchar_t *)argv[2], L"%d", &height)) {
- printf("Invalid value for height. It must be a number.");
- return 1;
- }
- int depth = 0;
- if (!swscanf_s((const wchar_t *)argv[3], L"%d", &depth)) {
- printf("Invalid value for bits per pixel. It must be a number.");
- return 1;
- }
-
- // Find matching mode.
- DEVMODE dmode;
- memset(&dmode, 0, sizeof(DEVMODE));
- dmode.dmSize = sizeof(dmode);
-
- bool foundMode = false;
- for (int i = 0; !foundMode && EnumDisplaySettings(NULL, i, &dmode); ++i) {
- foundMode = (dmode.dmPelsWidth == (DWORD)width) &&
- (dmode.dmPelsHeight == (DWORD)height) &&
- (dmode.dmBitsPerPel == (DWORD)depth);
- }
- if (!foundMode) {
- printf("No screen mode found with given resolution and bits per pixel.\n");
- return 1;
- }
-
- // Change to matched mode.
- dmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
-
- LONG result = ChangeDisplaySettings(&dmode, CDS_UPDATEREGISTRY);
- if (result == DISP_CHANGE_SUCCESSFUL) {
- printf("Resolution changes successfully.\n");
- return 0;
- } else if (result == DISP_CHANGE_BADDUALVIEW) {
- printf("Windows XP: The settings change was unsuccessful because system "
- "is DualView capable.\n");
- } else if (result == DISP_CHANGE_BADFLAGS) {
- printf("An invalid set of flags was passed in.\n");
- } else if (result == DISP_CHANGE_BADMODE) {
- printf("The graphics mode is not supported.\n");
- } else if (result == DISP_CHANGE_BADPARAM) {
- printf("An invalid parameter was passed in. This can include an invalid "
- "flag or combination of flags.\n");
- } else if (result == DISP_CHANGE_FAILED) {
- printf("The display driver failed the specified graphics mode.\n");
- } else if (result == DISP_CHANGE_NOTUPDATED) {
- printf("Windows NT/2000/XP: Unable to write settings to the registry.\n");
- } else if (result == DISP_CHANGE_RESTART) {
- printf("The computer must be restarted in order for the graphics mode to "
- "work.\n");
- } else {
- printf("Unknown error.\n");
- }
-
- return 1;
-}
diff --git a/o3d/tests/lab/ChangeResolution/change_resolution.gyp b/o3d/tests/lab/ChangeResolution/change_resolution.gyp
deleted file mode 100644
index 9701975..0000000
--- a/o3d/tests/lab/ChangeResolution/change_resolution.gyp
+++ /dev/null
@@ -1,25 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'targets': [
- {
- 'target_name': 'ChangeResolution',
- 'conditions': [
- ['OS == "win"',
- {
- 'type': 'executable',
- 'defines': ['_WIN32_WINNT=0x0501'], # for ChangeDisplaySettings
- 'sources': [
- 'change_resolution.cpp',
- ],
- },
- {
- 'type': 'none',
- },
- ],
- ],
- },
- ],
-}
diff --git a/o3d/tests/lab/__init__.py b/o3d/tests/lab/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/o3d/tests/lab/__init__.py
+++ /dev/null
diff --git a/o3d/tests/lab/browsers.py b/o3d/tests/lab/browsers.py
deleted file mode 100644
index f5172d7..0000000
--- a/o3d/tests/lab/browsers.py
+++ /dev/null
@@ -1,216 +0,0 @@
-#!/usr/bin/python
-# Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-# WINDOWS ONLY
-
-"""Installs a specified browser."""
-
-import ConfigParser
-import copy
-import os
-import logging
-import time
-
-import util
-
-
-BROWSERS = [{'name': 'ie6',
- 'version': '6',
- 'family': 'ie',
- 'selenium_name': '*iexplore',
- },
- {'name': 'ie7',
- 'version': '7',
- 'family': 'ie',
- 'selenium_name': '*iexplore',
- },
- {'name': 'ie8',
- 'version': '8',
- 'family': 'ie',
- 'selenium_name': '*iexplore',
- },
- {'name': 'ff3',
- 'version': '3',
- 'family': 'firefox',
- 'selenium_name': '*firefox'
- },
- {'name': 'ff3.5',
- 'version': '3.5',
- 'family': 'firefox',
- 'selenium_name': '*firefox'
- },
- {'name': 'ff2',
- 'version': '2',
- 'family': 'firefox',
- 'selenium_name': '*firefox'
- },
- {'name': 'chrome-dev',
- 'version': '4',
- 'family': 'chrome',
- 'selenium_name': '*googlechrome'
- },
- {'name': 'chrome-beta',
- 'version': '3',
- 'family': 'chrome',
- 'selenium_name': '*googlechrome'
- },
- {'name': 'chrome-stable',
- 'version': '3',
- 'family': 'chrome',
- 'selenium_name': '*googlechrome'
- },
- {'name': 'saf3',
- 'family': 'safari',
- 'selenium_name': '*safari'
- },
- {'name': 'saf4',
- 'family': 'safari',
- 'selenium_name': '*safari'
- }]
-
-if util.IsXP():
- HOME_PATH = 'C:\\Documents and Settings\\testing'
-elif util.IsVista() or util.IsWin7():
- HOME_PATH = 'C:\\Users\\testing'
-
-SERVER = 'http://tsqaserver/mac/o3d/imaging/software/browsers'
-
-SOFTWARE_PATH = 'C:\\imaging\\software'
-
-_FIREFOX_VERSIONS = {'ff3': SERVER + '/ff3.0.13.exe',
- 'ff2': SERVER + '/ff2.0.11.exe',
- 'ff3.5': SERVER + '/ff3.5.2.exe'}
-
-_CHROME_VERSIONS = {'chrome-stable': SERVER + '/chrome_stable.exe',
- 'chrome-dev': SERVER + '/chrome_dev.exe',
- 'chrome-beta': SERVER + '/chrome_beta.exe'}
-
-_IE_7_URLS = {'xp': SERVER + '/IE7-WindowsXP-x86-enu.exe',
- 'xp_64': SERVER + '/IE7-WindowsServer2003-x64-enu.exe'}
-
-_IE_8_URLS = {'xp': SERVER + '/IE8-WindowsXP-x86-ENU.exe',
- 'xp_64': SERVER + '/IE8-WindowsServer2003-x64-ENU.exe',
- 'vista': SERVER + '/IE8-WindowsVista-x86-ENU.exe',
- 'vista_64': SERVER + '/IE8-WindowsVista-x64-ENU.exe'}
-
-
-def GetVersionNumber(family):
- """Get the version number of the installed browser in |family|. Returns
- None if browser is not installed."""
- if family == 'ie':
- path = r'HKLM\SOFTWARE\Microsoft\Internet Explorer'
- version = util.RegQuery(path, 'Version')
- if version is not None:
- return version[0:1]
-
- elif family == 'firefox':
- path = r'HKLM\SOFTWARE\Mozilla\Mozilla Firefox'
- version = util.RegQuery(path, 'CurrentVersion')
- if version is not None:
- if version.startswith('3.0'):
- return '3'
- elif version.startswith('3.5'):
- return '3.5'
- elif version.startswith('2'):
- return '2'
-
- elif family == 'chrome':
- chrome_dir = (HOME_PATH + r'\Local Settings\Application Data\Google' +
- r'\Chrome\Application')
- files = os.listdir(chrome_dir)
-
- for file in files:
- # The Chrome application directory has a folder named with the version #.
- if file.startswith('2.'):
- return '2'
- elif file.startswith('3.'):
- return '3'
- elif file.startswith('4.'):
- return '4'
-
- return None
-
-
-def IsBrowserInstalled(browser):
- """Checks if |browser| is installed."""
-
- return GetVersionNumber(browser['family']).startswith(browser['version'])
-
-def Install(browser):
- """Installs |browser|, if necessary. It is not possible to install
- an older version of the already installed browser currently.
-
- Args:
- browser: specific browst to install.
- Returns:
- whether browser is installed.
- """
-
- # Only dynamic installation of browsers for Windows now.
- if not util.IsWindows():
- return True
-
- logging.info('Wants to install ' + browser['name'])
- version = GetVersionNumber(browser['family'])
- if version is None:
- logging.info('No version of %s is installed' % browser['family'])
- else:
- logging.info('Version %s of %s is installed already'
- % (version, browser['family']))
-
- if not IsBrowserInstalled(browser):
-
- install_cmd = None
-
- # Download browser.
- logging.info('Downloading ' + browser['name'])
- if browser['family'] == 'ie':
-
- if browser['name'] == 'ie7':
- install_cmd = util.Download(_IE_7_URLS[util.GetOSPrefix()],
- SOFTWARE_PATH)
- elif browser['name'] == 'ie8':
- install_cmd = util.Download(_IE_8_URLS[util.GetOSPrefix()],
- SOFTWARE_PATH)
-
- install_cmd += ' /passive /no-default'
-
- elif browser['family'] == 'firefox':
- if util.IsWindows():
- install = util.Download(_FIREFOX_VERSIONS[browser['name']],
- SOFTWARE_PATH)
- install_cmd = install + ' -ms'
- elif browser['family'] == 'chrome':
- if util.IsWindows():
- install_cmd = util.Download(_CHROME_VERSIONS[browser['name']],
- SOFTWARE_PATH)
- else:
- logging.error('Browser %s is not currently supported' % browser['name'])
-
-
- # Run installation.
- if install_cmd is not None:
- logging.info('Installing browser: ' + install_cmd)
- if install_cmd is None or util.RunStr(install_cmd) != 0:
- logging.error('Could not install %s' % browser['name'])
- return False
-
- # Do post installation things.
- if browser['family'] == 'chrome':
- first_run = file(HOME_PATH + '\\Local Settings\\'
- 'Application Data\\Google\\Chrome\\Application\\'
- 'First Run', 'w')
- first_run.close()
-
- # Wait for Chrome to install. Reboot to get rid of that first run UI.
- time.sleep(90)
- util.Reboot()
- logging.error('Could not reboot. Needed for Chrome installation.')
- return False
-
- else:
- logging.info(browser['name'] + ' already installed')
-
- return True
-
diff --git a/o3d/tests/lab/configure_ie.py b/o3d/tests/lab/configure_ie.py
deleted file mode 100644
index 6279308..0000000
--- a/o3d/tests/lab/configure_ie.py
+++ /dev/null
@@ -1,303 +0,0 @@
-#!/usr/bin/python
-# Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Manages configuring Microsoft Internet Explorer."""
-
-import logging
-import os
-import re
-import subprocess
-import urllib
-import urlparse
-import util
-
-
-def _ConfigureSecurityKeyForZone(zone_number, key, value):
- """Set key under the Zone settings in Security.
-
- Args:
- zone_number: Integer identifier of zone to edit.
- key: key under "HKEY_CURRENT_USER\Software\Microsoft\Windows\
- CurrentVersion\Internet Settings\Zones\<Zone>"
- to edit.
- value: new value for key.
-
- Returns:
- True on success.
- """
- if not util.RegAdd(('HKEY_CURRENT_USER\\Software\\Microsoft\\'
- 'Windows\\CurrentVersion\\Internet Settings\\'
- 'Zones\\%s' % zone_number), key, util.REG_DWORD, value):
- return False
- return True
-
-
-def GetInstalledVersion():
- """Reads the version of IE installed by checking the registry.
-
- The complete version is returned. For example: 6.0.2900.55.5512.
-
- Returns:
- String for version or None on failure.
- """
- return util.RegQuery('HKLM\\Software\\Microsoft\\Internet Explorer','Version')
-
-
-def ConfigurePopupBlocker(active):
- """Configure if popup blocker is active for IE 8.
-
- Args:
- active: new active state for popup blocker.
-
- Returns:
- True on success.
- """
- if active:
- value = '1'
- else:
- value = '0'
-
- # IE 8
- if not util.RegAdd(('HKEY_LOCAL_MACHINE\\Software\\Microsoft'
- '\\Internet Explorer\\Main\\FeatureControl\\'
- 'FEATURE_WEBOC_POPUPMANAGEMENT'), 'iexplore.exe',
- util.REG_DWORD, value):
- return False
-
- # IE 6
- if active:
- value = 'yes'
- else:
- value = 'no'
-
- if not util.RegAdd(('HKEY_CURRENT_USER\\Software\\Microsoft\\'
- 'Internet Explorer\\New Windows'),
- 'PopupMgr', util.REG_SZ, value):
- return False
-
- return True
-
-
-def DisableDefaultBrowserCheck(active):
- """Turn off the check to be set as default browser on start up.
-
- Args:
- active: if True then disables browser check, otherwise enables.
-
- Returns:
- True on success.
- """
- if active:
- value = 'no'
- else:
- value = 'yes'
-
- path = 'HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\Main'
-
- if not util.RegAdd(path, 'Check_Associations', util.REG_SZ, value):
- return False
-
- return True
-
-
-def DisableWelcomeWindowForInternetExplorer8():
- """Turn off the window which asks user to configure IE8 on start up.
-
- Returns:
- True on success.
- """
- path = 'HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\Main'
-
- if not util.RegAdd(path, 'IE8RunOnceLastShown', util.REG_DWORD, '1'):
- return False
-
- if not util.RegAdd(path, 'IE8RunOnceLastShown_TIMESTAMP', util.REG_BINARY,
- '79a29ba0bbb7c901'):
- return False
-
- if not util.RegAdd(path, 'IE8RunOnceCompletionTime', util.REG_BINARY,
- 'f98da5b2bbb7c901'):
- return False
-
- if not util.RegAdd(path, 'IE8TourShown', util.REG_DWORD, '1'):
- return False
-
- if not util.RegAdd(path, 'IE8TourShownTime', util.REG_BINARY,
- '1ada825779b6c901'):
- return False
-
- if not util.RegAdd(path, 'DisableFirstRunCustomize', util.REG_DWORD, '1'):
- return False
-
- return True
-
-
-def DisableInformationBarIntro():
- """Turn off the dialog which tells you about information bar.
-
- Returns:
- True on success.
- """
- path = (r'HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer'
- r'\InformationBar')
-
- if not util.RegAdd(path, 'FirstTime', util.REG_DWORD, '0'):
- return False
-
- return True
-
-
-def DisableInternetExplorerPhishingFilter():
- """Turn off the dialog for Phishing filter which blocks tests on IE 7.
-
- Returns:
- True on success.
- """
- path = ('HKEY_CURRENT_USER\\Software\\Microsoft\\'
- 'Internet Explorer\\PhishingFilter')
-
- if not util.RegAdd(path, 'Enabled', util.REG_DWORD, '1'):
- return False
-
- if not util.RegAdd(path, 'ShownVerifyBalloon', util.REG_DWORD, '1'):
- return False
-
- if not util.RegAdd(path, 'EnabledV8', util.REG_DWORD, '1'):
- return False
-
- return True
-
-
-def ConfigureAllowActiveX(activate):
- """Configure internet zone to use Active X.
-
- Args:
- activate: Turn on if True, otherwise turn off.
-
- Returns:
- True on success.
- """
- internet_zone = 3
-
- if activate:
- value = '00000000'
- else:
- value = '00000003'
-
- return _ConfigureSecurityKeyForZone(internet_zone, '1200', value)
-
-
-def ConfigureAllowPreviouslyUnusedActiveXControlsToRun(activate):
- """Configure internet zone to allow new Active X controls to run.
-
- Args:
- activate: Turn on if True, otherwise turn off.
-
- Returns:
- True on success.
- """
- internet_zone = 3
-
- if activate:
- value = '00000000'
- else:
- value = '00000003'
-
- return _ConfigureSecurityKeyForZone(internet_zone, '1208', value)
-
-
-def ConfigureAllowAllDomainsToUseActiveX(activate):
- """Configure internet zone to allow all domains to use Active X.
-
- Args:
- activate: Turn on if True, otherwise turn off.
-
- Returns:
- True on success.
- """
- internet_zone = 3
-
- if activate:
- value = '00000000'
- else:
- value = '00000003'
-
- return _ConfigureSecurityKeyForZone(internet_zone, '120B', value)
-
-
-def ConfigureAllowActiveContentFromMyComputer(activate):
- """Allow Active X to run from local files loaded from My Computer.
-
- This option is shown under Security of the Advanced tab of Internet Options.
-
- Args:
- activate: Turn on if True, otherwise turn off.
-
- Returns:
- True on success.
- """
- if activate:
- value = '0'
- else:
- value = '1'
-
- if not util.RegAdd(('HKEY_CURRENT_USER\\Software\\Microsoft\\'
- 'Internet Explorer\\Main\\FeatureControl\\'
- 'FEATURE_LOCALMACHINE_LOCKDOWN'),
- 'iexplore.exe', util.REG_DWORD, value):
- return False
- if not util.RegAdd(('HKLM\\SOFTWARE\\Microsoft\\Internet Explorer\\Main\\'
- 'FeatureControl\\FEATURE_LOCALMACHINE_LOCKDOWN'),
- 'iexplore.exe', util.REG_DWORD, value):
- return False
-
- return True
-
-
-def ConfigureIE():
- """Calls the other methods to allow testing with Internet Explorer.
-
- Returns:
- True on success.
- """
- on = True
- logging.info('Configuring IE...')
- logging.info('Allowing all active domains to use ActiveX...')
- if not ConfigureAllowAllDomainsToUseActiveX(on):
- return False
-
- logging.info('Allowing ActiveX...')
- if not ConfigureAllowActiveX(on):
- return False
-
- logging.info('Allowing previously unused ActiveX to run...')
- if not ConfigureAllowPreviouslyUnusedActiveXControlsToRun(on):
- return False
-
- logging.info('Disabling default browser check...')
- if not DisableDefaultBrowserCheck(on):
- return False
-
- logging.info('Allowing active content from my computer...')
- if not ConfigureAllowActiveContentFromMyComputer(on):
- return False
-
- logging.info('Disabling popup blocker...')
- if not ConfigurePopupBlocker(False):
- return False
-
- logging.info('Disabling Phishing Filter...')
- if not DisableInternetExplorerPhishingFilter():
- return False
-
- logging.info('Disabling welcome window for IE 8...')
- if not DisableWelcomeWindowForInternetExplorer8():
- return False
-
- logging.info('Disabling info bar intro...')
- if not DisableInformationBarIntro():
- return False
-
- return True
diff --git a/o3d/tests/lab/run_lab_test.py b/o3d/tests/lab/run_lab_test.py
deleted file mode 100644
index 78219dc..0000000
--- a/o3d/tests/lab/run_lab_test.py
+++ /dev/null
@@ -1,320 +0,0 @@
-#!/usr/bin/python2.6.2
-# 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.
-
-
-"""Prepares to run the selenium lab tests and finally invokes the selenium
-runner main.py.
-
-Usage:
- run_lab_test.py [test_config_path]
-
-Args:
- browser_config_path: path to test config file (optional)
-"""
-
-import copy
-import logging
-import optparse
-import os
-import shutil
-import subprocess
-import sys
-import threading
-import time
-
-import configure_ie
-import runner_constants as const
-import runner_util as run_util
-import util
-
-# Resolution to configure video card to before running tests.
-SCREEN_WIDTH = 1280
-SCREEN_HEIGHT = 1024
-SCREEN_BPP = 32
-
-join = os.path.join
-
-if util.IsWindows():
- IMAGE_DIFF_PATH = join(const.BASE_PATH, 'third_party', 'pdiff', 'files',
- 'bin', 'win', 'perceptualdiff.exe')
-elif util.IsMac():
- IMAGE_DIFF_PATH = join(const.BASE_PATH, 'third_party', 'pdiff', 'files',
- 'bin', 'mac', 'perceptualdiff')
-else:
- IMAGE_DIFF_PATH = join(const.BASE_PATH, 'third_party', 'pdiff', 'files',
- 'bin', 'linux', 'perceptualdiff')
-
-SELENIUM_TEST_RUNNER_PATH = join(const.TEST_PATH, 'selenium', 'main.py')
-
-SELENIUM_JAR_PATH = join(const.BASE_PATH, 'third_party', 'selenium_rc', 'files',
- 'selenium-server', 'selenium-server.jar')
-
-O3D_REFERENCE_IMAGES_PATH = join(const.O3D_PATH, 'o3d_assets', 'tests',
- 'screenshots')
-
-SCREENSHOTS_PATH = join(const.RESULTS_PATH,'screenshots')
-
-# Set total test timeout to 90 minutes.
-TEST_TIMEOUT_SECS = 60 * 90.0
-
-SELENIUM_BROWSER_PREFIXES = {
- 'ie': '*iexplore',
- 'ff': '*firefox',
- 'chr': '*googlechrome',
- 'saf': '*safari',
-}
-
-
-class TestRunningThread(threading.Thread):
- """Runs test in separate thread. Allows timeout if test blocks."""
-
- def __init__(self, command):
- threading.Thread.__init__(self)
- # Make the test running thread a daemon thread. It blocks waiting for
- # output from the test. By being a daemon this program can exit even
- # if the runner thread is deadlocked waiting for output from the test.
- self.setDaemon(True)
- self.command = command
- self.return_code = None
- self.has_started_event = threading.Event()
- self.finished_event = threading.Event()
-
- def run(self):
- logging.info('Running tests:')
- logging.info(' '.join(self.command))
- self.test_process = subprocess.Popen(args=self.command,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- universal_newlines=True)
-
- self.has_started_event.set()
- logging.info('Output from running test follows:')
-
- while True:
- line = self.test_process.stdout.readline()
- if line:
- print line.strip('\n')
- else:
- break
-
- self.finished_event.set()
-
-
- def HasFinished(self):
- # The main thread must poll the test thread because it is possible
- # for test_process.readline() to hang. This can happen when a debug
- # window opens from a crashing program. This way, we can know when
- # our process has exited, and then try to kill all the windows.
- if not self.has_started_event.isSet():
- # The tests cannot have finished if they have not even started.
- return False
-
- self.test_process.poll()
-
- code = self.test_process.returncode
-
- if code is not None and util.IsWindows():
- # Wait for the test runner to exit safely, if it is able.
- time.sleep(5)
-
- if not self.finished_event.isSet():
- # Something is preventing proper exiting of test runner.
- # Try to kill all the debug windows.
- logging.info('Trying to clean up after the test. Ignore errors here.')
- os.system('TASKKILL /F /IM dwwin.exe')
- os.system('TASKKILL /F /IM iedw.exe')
-
- # Windows Error Reporting (on Vista)
- os.system('TASKKILL /F /IM WerFault.exe')
-
- # Browsers.
- os.system('TASKKILL /F /IM chrome.exe')
- os.system('TASKKILL /F /IM iexplore.exe')
- os.system('TASKKILL /F /IM firefox.exe')
-
- # Wait and see if the test is allowed to finish now.
- time.sleep(5)
-
- if not self.finished_event.isSet():
- logging.error('Could not kill all the extra processes created by the' +
- 'test run.')
- else:
- logging.info('Test process exited succesfully.')
-
- return code is not None
-
-
- def GetReturnCode(self):
- """Returns the exit code from the test runner, or special code 128 if
- test runner did not exit."""
-
- if not self.has_started_event.isSet():
- code = 128
- else:
- code = self.test_process.returncode
- if code is None:
- code = 128
- return code
-
-
-
-def RunTest(browser):
- """Runs tests on |browser|.
- Args:
- browser: the browser to test.
- Returns:
- True on success.
- """
-
- if util.IsWindows():
- if not run_util.EnsureWindowsScreenResolution(SCREEN_WIDTH, SCREEN_HEIGHT,
- SCREEN_BPP):
- logging.warn('Could not detect/change screen resolution.')
-
- # Clear all screenshots.
- logging.info('** Deleting previous screenshots.')
- if os.path.exists(SCREENSHOTS_PATH):
- shutil.rmtree(SCREENSHOTS_PATH)
-
- os.makedirs(SCREENSHOTS_PATH)
-
- logging.info('** Running selenium tests...')
-
- # -u for unbuffered output.
- # Use Python2.4 for two reasons. First, this is more or less the standard.
- # Second, if we use Python2.6 or later, we must manually shutdown the
- # httpserver, or the next run will overlap ports, which causes
- # some strange problems/exceptions.
- args = [const.PYTHON, '-u', SELENIUM_TEST_RUNNER_PATH]
-
- browser_parts = browser.split(' ', 1)
- args.append('--browser=' + browser_parts[0])
- if len(browser_parts) > 1:
- args.append('--browserpath=' + browser_parts[1])
-
- args.append('--servertimeout=80')
- args.append('--product_dir=' + const.PRODUCT_DIR_PATH)
- args.append('--verbose=0')
- args.append('--screenshots')
- args.append('--screencompare=' + IMAGE_DIFF_PATH)
- args.append('--screenshotsdir=' + SCREENSHOTS_PATH)
- args.append('--referencedir=' + O3D_REFERENCE_IMAGES_PATH)
- args.append('--selenium_server=' + SELENIUM_JAR_PATH)
- args.append('--testprefix=Test')
- args.append('--testsuffixes=small,medium,large')
-
- runner = TestRunningThread(args)
- runner.start()
-
- timeout_time = time.time() + TEST_TIMEOUT_SECS
- while not runner.HasFinished():
- if time.time() > timeout_time:
- break
- time.sleep(5)
-
- return runner.GetReturnCode()
-
-
-def main(argv):
- logfile = os.path.join(os.path.dirname(os.path.abspath(__file__)),
- 'log_run_lab_test.txt')
- util.ConfigureLogging(logfile)
- logging.info('Running on machine: ' + util.IpAddress())
-
- if len(argv) > 2:
- logging.error('Usage: run_lab_test.py [test_config_file]')
- return 1
-
- if len(argv) == 2:
- # Use given config file.
- config_path = argv[1]
- else:
- # Use default config file.
- config_path = os.path.join(const.HOME, 'test_config.txt')
-
- # Uninstall/Install plugin.
- if not run_util.UninstallO3DPlugin():
- logging.error('Could not successfully uninstall O3D. Tests will not be run.')
- return 1
- if not run_util.InstallO3DPlugin():
- logging.error('Unable to install O3D plugin. Tests will not be run.')
- return 1
-
- # Grab test configuration info from config file.
- if not os.path.exists(config_path):
- logging.error('Browser config file "%s" could not be found.' % config_path)
- return 1
- else:
- config_file = open(config_path, 'rU')
- test_browsers = []
- while True:
- browser = config_file.readline().strip()
- if len(browser) == 0:
- # No more lines in the file, go ahead and break.
- break
- test_browsers += [browser]
-
- config_file.close()
-
- if len(test_browsers) == 0:
- logging.warn('No browsers found in config file. No tests will run.')
-
- # Test browsers.
- all_test_passed = True
- for browser in test_browsers:
- # Get the Selenium name of the browser. The config file can contain
- # a particular browser name like "ie6", a selenium name like "*firefox",
- # or a selenium name like "*googlechrome C:/Chrome/chrome.exe".
- sel_name = browser
- for prefix in SELENIUM_BROWSER_PREFIXES.keys():
- if browser.startswith(prefix):
- sel_name = SELENIUM_BROWSER_PREFIXES[prefix]
-
- # Configure IE.
- if sel_name.startswith('*iexplore'):
- if not configure_ie.ConfigureIE():
- logging.error('Failed to configure IE.')
- all_test_passed = False
- continue
-
- # Run selenium tests.
- if RunTest(sel_name) != 0:
- all_test_passed = False
-
- if all_test_passed:
- logging.info('All tests passed.')
- return 0
- else:
- logging.info('Tests failed.')
- return 1
-
-if __name__ == '__main__':
- code = main(sys.argv)
- sys.exit(code)
diff --git a/o3d/tests/lab/runner_constants.py b/o3d/tests/lab/runner_constants.py
deleted file mode 100644
index 33afbe5..0000000
--- a/o3d/tests/lab/runner_constants.py
+++ /dev/null
@@ -1,98 +0,0 @@
-#!/usr/bin/python2.6.2
-# 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.
-
-
-"""Defines common O3D test runner constants. This file determines paths to
-other O3D components relatively, so it must be placed in the right location.
-
-"""
-
-import os
-import sys
-
-import util
-
-join = os.path.join
-
-# Make sure OS is supported.
-if not util.IsWindows() and not util.IsMac() and not util.IsLinux():
- print 'Only Windows, Mac, and Linux are supported.'
- sys.exit(1)
-
-# This path should be root/o3d/tests.
-TEST_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
-# This path should be root/o3d.
-O3D_PATH = os.path.dirname(TEST_PATH)
-# This path should be root, i.e., the checkout location.
-BASE_PATH = os.path.dirname(O3D_PATH)
-
-
-HOME = os.path.expanduser('~')
-if HOME == '~':
- print 'Cannot find user home directory.'
- sys.exit(1)
-
-if util.IsWindows():
- PYTHON = r'C:\Python24\python.exe'
-else:
- PYTHON = 'python'
-
-# Note: this path may or may not exist.
-RESULTS_PATH = join(TEST_PATH, 'results')
-
-# Build directories.
-if util.IsWindows():
- BUILD_PATH = join(O3D_PATH, 'build')
-elif util.IsMac():
- BUILD_PATH = join(BASE_PATH, 'xcodebuild')
-else:
- BUILD_PATH = join(BASE_PATH, 'sconsbuild')
-
-# Product directory.
-if os.path.exists(join(BUILD_PATH, 'Debug')):
- PRODUCT_DIR_PATH = join(BUILD_PATH, 'Debug')
-elif os.path.exists(join(BUILD_PATH, 'Release')):
- PRODUCT_DIR_PATH = join(BUILD_PATH, 'Release')
-else:
- print 'Cannot find Debug or Release folder in ' + BUILD_PATH
- sys.exit(1)
-
-# Plugin locations.
-INSTALL_PATHS = []
-if util.IsWindows():
- INSTALL_PATHS += [join(HOME, 'Application Data', 'Mozilla',
- 'plugins', 'npo3dautoplugin.dll')]
- INSTALL_PATHS += [join(HOME, 'Application Data', 'Google', 'O3D',
- 'o3d_host.dll')]
-elif util.IsMac():
- INSTALL_PATHS += ['/Library/Internet Plug-Ins/O3D.plugin']
-else:
- INSTALL_PATHS += [join(HOME, '.mozilla', 'plugins',
- 'libnpo3dautoplugin.so')]
diff --git a/o3d/tests/lab/runner_util.py b/o3d/tests/lab/runner_util.py
deleted file mode 100644
index 49ae569..0000000
--- a/o3d/tests/lab/runner_util.py
+++ /dev/null
@@ -1,165 +0,0 @@
-#!/usr/bin/python2.6.2
-# 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.
-
-
-"""Utility functions for running the lab tests.
-
-"""
-
-import logging
-import os
-import subprocess
-import shutil
-import sys
-
-import runner_constants as const
-import util
-
-CHANGE_RESOLUTION_PATH = os.path.join(const.TEST_PATH, 'lab',
- 'ChangeResolution','Debug',
- 'changeresolution.exe')
-
-def EnsureWindowsScreenResolution(width, height, bpp):
- """Performs all steps needed to configure system for testing on Windows.
-
- Args:
- width: new screen resolution width
- height: new screen resolution height
- bpp: new screen resolution bytes per pixel
- Returns:
- True on success.
- """
- if not os.path.exists(CHANGE_RESOLUTION_PATH):
- return False
- command = 'call "%s" %d %d %d' % (CHANGE_RESOLUTION_PATH, width, height, bpp)
-
- our_process = subprocess.Popen(command,
- shell=True,
- stdout=None,
- stderr=None,
- universal_newlines=True)
-
- our_process.wait()
-
- return our_process.returncode == 0
-
-
-def AddPythonPath(path):
- """Add path to PYTHONPATH in environment."""
- try:
- os.environ['PYTHONPATH'] = path + os.pathsep + os.environ['PYTHONPATH']
- except KeyError:
- os.environ['PYTHONPATH'] = path
-
- # Need to put at front of sys.path so python will try to import modules from
- # path before locations further down the sys.path.
- sys.path = [path] + sys.path
-
-
-def InstallO3DPlugin():
- """Installs O3D plugin."""
-
- logging.info('Installing plugin...')
- if util.IsWindows():
- installer_path = os.path.join(const.PRODUCT_DIR_PATH, 'o3d.msi')
-
- if not os.path.exists(installer_path):
- logging.error('Installer path not found, %s' % installer_path)
- return False
-
- install_command = 'msiexec.exe /i "%s"' % installer_path
- if util.RunStr(install_command) != 0:
- return False
-
- elif util.IsMac():
- dmg_path = os.path.join(const.PRODUCT_DIR_PATH, 'o3d.dmg')
- mnt = util.MountDiskImage(dmg_path)
- if mnt is None:
- return False
- (device, volumes_path) = mnt
-
- installer_path = os.path.join(volumes_path, 'O3D.mpkg')
-
- if not os.path.exists(installer_path):
- logging.error('Installer path not found, %s' % installer_path)
- util.UnmountDiskImage(device)
- return False
-
- admin_password = 'g00gl3'
- install_command = ('echo %s | sudo -S /usr/sbin/installer -pkg '
- '"%s" -target /' % (admin_password, installer_path))
-
- ret_code = util.RunStr(install_command)
- util.UnmountDiskImage(device)
- if ret_code != 0:
- return False
-
- else:
- plugin_path = os.path.join(const.PRODUCT_DIR_PATH, 'libnpo3dautoplugin.so')
- plugin_dst_dir = os.path.expanduser('~/.mozilla/plugins')
- try:
- os.makedirs(plugin_dst_dir)
- except os.error:
- pass
-
- plugin_dst = os.path.join(plugin_dst_dir, 'libnpo3dautoplugin.so')
- shutil.copyfile(plugin_path, plugin_dst)
- return True
-
- return True
-
-def UninstallO3DPlugin():
- """Uninstalls O3D.
-
- Returns:
- True, if O3D is no longer installed."""
-
- if util.IsWindows():
- installer_path = os.path.join(const.PRODUCT_DIR_PATH, 'o3d.msi')
- os.system('msiexec.exe /x "%s" /q' % installer_path)
-
- # Forcibly remove plugins.
- for path in const.INSTALL_PATHS:
- if os.path.exists(path):
- if util.IsWindows():
- os.remove(path)
- else:
- os.system('echo g00gl3 | sudo -S rm -rf "%s"' % path)
-
- return not DoesAnO3DPluginExist()
-
-def DoesAnO3DPluginExist():
- for path in const.INSTALL_PATHS:
- if os.path.exists(path):
- return True
- return False
-
-
- \ No newline at end of file
diff --git a/o3d/tests/lab/util.py b/o3d/tests/lab/util.py
deleted file mode 100644
index 0a7bc8d..0000000
--- a/o3d/tests/lab/util.py
+++ /dev/null
@@ -1,371 +0,0 @@
-#!/usr/bin/python2.6.2
-# 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.
-
-
-"""Common utilities for O3D's lab test runner.
-
-"""
-
-import logging
-import logging.handlers
-import os
-import platform
-import subprocess
-import sys
-import socket
-import time
-import urllib
-import urlparse
-
-
-# Logging utilities.
-def ConfigureLogging(logging_file_path=None):
- logging_format = '%(levelname)8s -- %(message)s'
-
- root_logger = logging.getLogger('')
- root_logger.setLevel(logging.NOTSET)
-
- # Log to file.
- if logging_file_path is not None:
- file_handler = logging.handlers.RotatingFileHandler(logging_file_path,
- maxBytes=5000000)
- formatter = logging.Formatter(logging_format)
- file_handler.setFormatter(formatter)
- file_handler.setLevel(logging.NOTSET)
- root_logger.addHandler(file_handler)
-
- if not os.path.exists(logging_file_path):
- print 'Failed to create log. Can\'t continue:"%s"' % (logging_file_path)
- sys.exit(1)
-
- logging.info('Appending log output to file:"%s"', logging_file_path)
-
- # Log to stdout.
- stdout_handler = logging.StreamHandler(sys.stdout)
- formatter = logging.Formatter(logging_format)
- stdout_handler.setFormatter(formatter)
- stdout_handler.setLevel(logging.NOTSET)
- root_logger.addHandler(stdout_handler)
-
-
-
-
-# OS Detection utilities.
-def IsMac():
- return platform.system() == 'Darwin'
-
-def IsWindows():
- return platform.system() == 'Windows'
-
-def IsLinux():
- return platform.system() == 'Linux'
-
-def IsWin7():
- return IsWindows() and platform.release() == 'post2008Server'
-
-def IsWin7_64():
- return IsWin7() and os.path.exists(r'C:\Program Files (x86)')
-
-def IsVista():
- return IsWindows() and platform.release() == 'Vista'
-
-def IsVista_64():
- return IsVista() and os.path.exists(r'C:\Program Files (x86)')
-
-def IsXP():
- return (IsWindows() and platform.release() == 'XP') or IsXP_64()
-
-def IsXP_64():
- return (IsWindows() and platform.release() == '2003Server' and
- os.path.exists(r'C:\Program Files (x86)'))
-
-def GetOSName():
- return platform.platform()
-
-def GetOSPrefix():
- if IsWin7_64():
- prefix = 'win7_64'
- elif IsWin7():
- prefix = 'win7'
- elif IsVista_64():
- prefix = 'vista_64'
- elif IsVista():
- prefix = 'vista'
- elif IsXP_64():
- prefix = 'xp_64'
- elif IsXP():
- prefix = 'xp'
- elif IsMac():
- prefix = 'mac'
- elif IsLinux():
- prefix = 'linux'
- else:
- prefix = None
- return prefix
-
-
-NONE = 0
-WARN = 1
-ERROR = 2
-FATAL = 3
-def RunCommand(cmd_string, level=ERROR, info=None):
- # Execute command.
- if info == None:
- info = cmd_string
- if level != NONE:
- logging.info(info + '...')
-
-
- our_process = subprocess.Popen(cmd_string,
- shell=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- universal_newlines=True)
-
- # Read output so that process isn't blocked with a filled buffer.
- (output,err_output) = our_process.communicate()
-
- return_code = our_process.returncode
-
-
- if level != NONE:
- if return_code:
- # Command failed. Take appropriate action.
- if level == WARN:
- logging.warn('Failed: ' + info)
- elif level == ERROR or level == FATAL:
- logging.error('Failed: ' + info)
-
- logging.info(' Details for ' + cmd_string + ':')
- logging.info(' Failed with return code:%d', return_code)
- for line in output.split('\n'):
- logging.info(' ' + line)
-
- if level == FATAL:
- sys.exit(1)
-
- # Command succeeded. Report success.
- else:
- logging.info('Success.')
-
- return (return_code, output)
-
-
-def RunStr(cmd_string, level=ERROR, info=None):
- return RunCommand(cmd_string, level, info)[0]
-
-
-def RunWithOutput(command, level=ERROR, info=None):
- return RunCommand(' '.join(command), level, info)
-
-
-def Run(command, level=ERROR, info=None):
- return RunWithOutput(command, level, info)[0]
-
-
-REG_DWORD = 'REG_DWORD'
-REG_SZ = 'REG_SZ'
-REG_BINARY = 'REG_BINARY'
-def RegAdd(path, key, type, value, level=ERROR, info=None):
-
- cmd = ['REG', 'ADD', '"' + path + '"', '/V', key,
- '/t', type, '/d', '"' + value + '"', '/F']
-
- return Run(cmd, level, info) == 0
-
-
-def RegDoesExist(path, key, level=NONE):
- cmd = ['REG', 'QUERY', '"' + path + '"', '/V', key]
-
- return Run(cmd, level) == 0
-
-
-def RegDel(path, key, level=ERROR):
- cmd = ['REG', 'DELETE', '"' + path + '"', '/V', key, '/F']
-
- return Run(cmd, level) == 0
-
-
-def RegMaybeDel(path, key, level):
- if RegQuery(path, key):
- return RegDel(path, key, level)
-
- return True
-
-
-def RegQuery(path, key):
- """Read value from registry.
-
- Args:
- path: full path into registry for parent of value to read.
- key: key under parent to read.
-
- Returns:
- Value on success and None on failure.
- """
- arguments = ['REG', 'QUERY', path,
- '/V', key]
- reg_process = subprocess.Popen(args=arguments,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- universal_newlines=True)
-
- value = None
-
- lines = reg_process.stdout.readlines()
- for line in lines:
- line = line.strip('\n')
- check_key = line.lstrip()
- if check_key.startswith(key):
- type_and_value = check_key[len(key):].lstrip()
- for i in range(len(type_and_value)):
- if type_and_value[i] == '\t' or type_and_value[i] == ' ':
- value = type_and_value[i:].lstrip()
- break
-
- reg_process.wait()
- if reg_process.returncode:
- return None
- return value
-
-
-# Other utilities.
-def IpAddress():
- """Get IP address of this machine."""
- address_info = socket.gethostbyname_ex(socket.gethostname())
- if len(address_info) == 3:
- ip = address_info[2]
- if ip:
- ip = ip[0]
- return ip
-
- logging.error('Failed to get local machine IP.')
- return None
-
-
-def Reboot():
- """Reboots machine."""
- if IsWindows():
- cmd = 'shutdown -r -t 1 -f'
- elif IsMac():
- cmd = 'shutdown -r now'
-
- logging.info('Rebooting machine...')
- os.system(cmd)
- time.sleep(10)
- logging.error('Failed: Could not reboot')
-
-
-def Download(url, prefix_dir):
- """Downloads single file at |url| to |prefix_dir|.
-
- Returns:
- local_path: the path to the downloaded file, or None if download was
- unsuccessful."""
-
- parsed_url = urlparse.urlparse(url)
- path = parsed_url[2]
- name = path.rsplit('/', 1)[1]
- local_path = os.path.join(prefix_dir, name)
-
- if not os.path.exists(prefix_dir):
- os.mkdir(prefix_dir)
- urllib.urlretrieve(url, local_path)
-
- if not os.path.exists(local_path):
- logging.error('Could not download %s to %s' % (url, local_path))
- return None
-
- return local_path
-
-
-def AddToStartup(name, command):
- if IsWindows():
- path = r'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
- RegAdd(path, name, REG_SZ, command)
-
-
-def RemoveFromStartup(name):
- if IsWindows():
- path = r'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
- RegMaybeDel(path, name, ERROR)
-
-
-def MountDiskImage(dmg_path):
- """Mounts disk image.
-
- Args:
- dmg_path: path to image that will be mounted.
-
- Returns:
- Tuple contaiing device path and mounted path on success,
- or None on failure.
- """
- mount_path = None
- logging.info('Mounting %s...' % dmg_path)
-
- cmd = ['hdiutil', 'attach', '"' + dmg_path + '"']
- (return_code, output) = RunWithOutput(cmd)
-
- if return_code == 0 and output:
- # Attempt to grab the mounted path from the command output.
- # This should be safe regardless of actual output.
- new_device = output.strip().split('\n')[-1].split('\t')
- device = new_device[0].strip()
- mount_path = new_device[-1]
-
- logging.info('Device %s mounted at %s' % (device,mount_path))
-
- # Wait for mounting operation to complete.
- time.sleep(10)
- if os.path.exists(mount_path):
- logging.info('Mount point is accessible.')
- else:
- mount_path = None
-
- if mount_path is None or device is None:
- logging.error('Could not mount properly.')
- return None
-
- return (device, mount_path)
-
-
-def UnmountDiskImage(device):
- """Unmounts disk image.
-
- Args:
- device: path to device to be detached
-
- Returns:
- True on success.
- """
- logging.info('Unmounting device %s...' % device)
-
- return Run(['hdiutil detach', '"' + device + '"', '-force']) == 0
diff --git a/o3d/tests/mac/unit_tests_install_name.sh b/o3d/tests/mac/unit_tests_install_name.sh
deleted file mode 100755
index d6af0b0..0000000
--- a/o3d/tests/mac/unit_tests_install_name.sh
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/bin/sh
-
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-/usr/bin/install_name_tool -change \
- @executable_path/../Library/Frameworks/Cg.framework/Cg \
- @executable_path/Library/Frameworks/Cg.framework/Cg \
- "${BUILT_PRODUCTS_DIR}/${EXECUTABLE_PATH}"
diff --git a/o3d/tests/package_tests.bat b/o3d/tests/package_tests.bat
deleted file mode 100644
index 739f94f..0000000
--- a/o3d/tests/package_tests.bat
+++ /dev/null
@@ -1,37 +0,0 @@
-@ECHO OFF
-REM Copyright 2009, Google Inc.
-REM All rights reserved.
-REM
-REM Redistribution and use in source and binary forms, with or without
-REM modification, are permitted provided that the following conditions are
-REM met:
-REM
-REM * Redistributions of source code must retain the above copyright
-REM notice, this list of conditions and the following disclaimer.
-REM * Redistributions in binary form must reproduce the above
-REM copyright notice, this list of conditions and the following disclaimer
-REM in the documentation and/or other materials provided with the
-REM distribution.
-REM * Neither the name of Google Inc. nor the names of its
-REM contributors may be used to endorse or promote products derived from
-REM this software without specific prior written permission.
-REM
-REM THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-REM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-REM LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-REM A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-REM OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-REM SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-REM LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-REM DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-REM THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-REM (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-REM OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-
-REM Invoke this script to package all of the dependencies required for the
-REM O3D system tests into a single zip file for easy distribution across
-REM testing machines.
-SET TODAY=%date:~10,4%%date:~4,2%%date:~7,2%
-SET ZIPNAME=_test_distribution.zip
-..\..\..\..\third_party\7zip_423\files\7z.exe a -tzip %TODAY%%ZIPNAME% o3d.msi d3d9ref.dll Detoured.dll import_test Microsoft.VC80.DebugCRT perceptualdiff.exe PIXAdmin.exe PIXHelper.dll PIXWin.exe system_tests.exe testing_framework_hardware.PIXExp testing_framework_reference.PIXExp test_driver.py
diff --git a/o3d/tests/presubmit_tests.bat b/o3d/tests/presubmit_tests.bat
deleted file mode 100644
index 137d5a7..0000000
--- a/o3d/tests/presubmit_tests.bat
+++ /dev/null
@@ -1,35 +0,0 @@
-REM Copyright 2009, Google Inc.
-REM All rights reserved.
-REM
-REM Redistribution and use in source and binary forms, with or without
-REM modification, are permitted provided that the following conditions are
-REM met:
-REM
-REM * Redistributions of source code must retain the above copyright
-REM notice, this list of conditions and the following disclaimer.
-REM * Redistributions in binary form must reproduce the above
-REM copyright notice, this list of conditions and the following disclaimer
-REM in the documentation and/or other materials provided with the
-REM distribution.
-REM * Neither the name of Google Inc. nor the names of its
-REM contributors may be used to endorse or promote products derived from
-REM this software without specific prior written permission.
-REM
-REM THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-REM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-REM LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-REM A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-REM OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-REM SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-REM LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-REM DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-REM THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-REM (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-REM OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-REM This test will invoke all of the O3D unit-tests. Please execute
-REM these tests before submitting to P4.
-@echo off
-echo Invoking Tests
-%~dp0\unit_tests.exe
-if exist %~dp0\test_driver.bat call %~dp0\test_driver.bat %*
diff --git a/o3d/tests/selenium/__init__.py b/o3d/tests/selenium/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/o3d/tests/selenium/__init__.py
+++ /dev/null
diff --git a/o3d/tests/selenium/javascript_unit_test_list.txt b/o3d/tests/selenium/javascript_unit_test_list.txt
deleted file mode 100644
index a142c02..0000000
--- a/o3d/tests/selenium/javascript_unit_test_list.txt
+++ /dev/null
@@ -1,103 +0,0 @@
-#
-# Test Requirements:
-#
-# Each sample is expected to have a global variable called g_testResult
-# That starts undefined and is set to true or false when the test is finished.
-#
-# Line Format:
-#
-# TestType test-name options
-#
-# Valid TestTypes are:
-#
-# small
-# medium
-# large
-#
-# options are separated by spaces.
-# screenshot : take a screenshot. You can specify a time with
-# screenshot(seconds) as in screenshot(4), take it at the 4 second mark.
-# You have also specify more than 1 screenshot by specifying more than
-# one screenshot option as in "screenshot(4), screenshot(6.5).
-#
-# To take a screenshot the test must have a global variable "g_client"
-# that is the client plugin object from which to take a screenshot.
-#
-# If the sample is animated, it is expected to have a global variable
-# called g_timeMult that can be set to 0 to stop the animation. All of
-# its animation must be based on a global variable called g_clock, such
-# that setting g_clock to the same value will always produce the same
-# image.
-#
-# Screenshots will not be taking unless g_testResult is true.
-#
-# timeout(milliseconds) : Set the timeout to wait for readiness. Default 5000.
-#
-# client(client_variable_name) : Name of client variable in javascript.
-# Default = "g_client"
-#
-# pdiff_threshold_mac(number_of_pixels_allowed)
-# pdiff_threshold_win(number_of_pixels_allowed)
-# pdiff_threshold_linux(number_of_pixels_allowed)
-# pdiff_threshold(number_of_pixels_allowed) : Number of pixels
-# allowed to be perceptually different before the test fails.
-# "pdiff_threshold" specifies the threshold for all
-# platforms. Platform specific versions override the
-# threshold for that platform. The default threshold is 10 pixels.
-#
-# except(*firefox,*iexplore,*googlechrome) : Name of the browser
-# environment(s) where the test should be skipped. This list should
-# not have spaces delimiting the browser names.
-# Default = ""
-#
-# pdiff_edge_ignore_off : Turn off edge detection function in pdiff.
-# By default, it's on with a default edge detect threshold 5.
-#
-# pdiff_edge_threshold(0 to 7) : Set edge detect threshold in pdiff.
-# This threshold indicates the max number of neighbors the pixel can
-# have to be considered as edge. 0 means only ignore scattered pixels.
-# NOTE! ----------------------------------------------------------------------
-#
-# Read the sample guidelines
-# http://wiki.corp.google.com/twiki/bin/view/Main/ClientThreeDSampleGuidelines
-#
-#
-small version-check-test
-small event-test
-small test-test
-small serialization-test
-small math-test
-small features-test
-small quaternion-test
-small v8-test
-small init-status-test
-small quaternion-test
-small base-test
-small util-test
-small pixel-perfection screenshot pdiff_threshold(200) pdiff_threshold_mac(3000) except(*iexplore)
-# Firefox opens an error dialog on this test stating that O3D failed to
-# start (issue #212). Chrome fails this test occasionally (issue #105).
-medium offscreen-test except(*firefox,*googlechrome)
-medium texture-set-test screenshot
-medium param-array-test screenshot
-small render-target-clear-test screenshot
-small no-rendergraph screenshot
-small non-cachable-params screenshot pdiff_threshold(200)
-small type-test
-small render-test
-# TODO Test disabled, as the behaviour on Chrome does not match other
-# browsers - objects are not deleted properly.
-small ownership-test
-small effect-import-test
-
-# -- tests below this line are tests for which there is a python
-# function to custom run the test. As such, only the 'except' and
-# pdiff_threshold options have any meaning
-
-# These two tests rely on Selenium getting or setting a page's title and that
-# does not currently work with Chrome.
-# Don't run TestStressDrawShapes on ie because selenium/ie is too slow.
-medium TestStressDrawShapes except(*googlechrome,*iexplore)
-medium TestStressMultiWindow except(*googlechrome) run_time(180000)
-
-large TestStressCullingZSort pdiff_threshold(450) screenshots(8)
diff --git a/o3d/tests/selenium/javascript_unit_tests.py b/o3d/tests/selenium/javascript_unit_tests.py
deleted file mode 100644
index b714298..0000000
--- a/o3d/tests/selenium/javascript_unit_tests.py
+++ /dev/null
@@ -1,302 +0,0 @@
-#!/usr/bin/python2.4
-# 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.
-
-
-"""Runs JavaScript unit tests in Selenium.
-
-NOTE: If you manually write a test in python (vs using the generic test)
-The name of the screenshots must match the name of the test not including
-the suffix. In otherwords, if your test is called TestSampleCustomCameraMedium
-then your screenshots need to be named customcamera1, customcamera2 etc.
-
-This is so when it comes time to compare screenshots we can figure out which
-reference images require a corresponding screenshot. In other words if
-TestSampleCustomCameraMedium is run then we know that any reference file
-named customcamera1_reference.png requires that there be a corresponding
-screenshot.
-"""
-
-
-import selenium_utilities
-
-class JavaScriptUnitTests(selenium_utilities.SeleniumTestCase):
- """Runs the JavaScript unit tests for the sample utilities."""
-
- def __init__(self, name, browser, path_to_html, test_type=None,
- sample_path=None, options=None):
- selenium_utilities.SeleniumTestCase.__init__(
- self, name, browser, path_to_html, test_type, sample_path,
- options)
-
- def GenericTest(self):
- """Generically test a sample.
-
- Each sample is expected to have a global variable called g_testResult
- That starts undefined and is set to true or false when the test is finished.
- """
- self.RunGenericTest(
- "/tests/selenium/tests/",
- "typeof(window.g_testResult) != 'undefined'",
- "window.g_testResult")
-
- def TestStressDrawShapes(self):
- """Tries to draw a large number of shapes for stress testing."""
-
- # Alias for the selenium session
- s = self.session
- s.open(self.GetURL("/tests/selenium/tests/drawshapes.html"))
-
- # Allow a limited time for the plugin to initialize.
- s.wait_for_condition("typeof(window.g_client) != 'undefined';", 20000)
-
- # Sanity checks.
- self.assertEqual("Drawshape stress test for O3D", s.get_title())
- self.assertEqual("null", s.get_eval("window.undefined_symbol_xxxyyy"))
-
- # Check assets for base o3d setup:
- # 2 nodes in scene graph
- # Root node and g_parent_transform node
- self.assertEqual(
- "2",
- s.get_eval("window.g_client.root.getTransformsInTree().length"))
-
- # There are 8 nodes in the render graph.
- # 1 root render node
- # 1 viewport
- # 1 clear buffer
- # 1 tree traversal
- # 2 draw passes
- # 2 StateSets
- self.assertEqual(
- "8",
- s.get_eval("window.g_client.renderGraphRoot."
- "getRenderNodesInTree().length"))
-
- # Draw 5 triangles
- s.type("numShapes", "5")
- s.click("btnTri")
-
- # 5 more primitives should get created
- # (1 for the parent transform)
- s.wait_for_condition(
- "window.g_client."
- "getObjectsByClassName('o3d.Shape').length == 5",
- 5000)
- # 5 more primitives nodes should get created
- self.assertEqual(
- "5",
- s.get_eval("window.g_client."
- "getObjectsByClassName('o3d.Primitive').length"))
-
- # Draw more triangles
- s.type("numShapes", "8")
- for i in range(1, 10):
- s.click("btnTri")
- s.wait_for_condition(
- "window.g_client."
- "getObjectsByClassName('o3d.Shape').length == %d" % (5 + i * 8),
- 5000)
- self.assertEqual(
- str(5 + i * 8),
- s.get_eval("window.g_client."
- "getObjectsByClassName('o3d.Primitive').length"))
-
- # Clear triangles, reset pack.
- s.click("btnClear")
-
- # Check assets for base o3d setup again.
- self.assertEqual(
- "2",
- s.get_eval("window.g_client.root.getTransformsInTree().length"))
- self.assertEqual(
- "8",
- s.get_eval("window.g_client.renderGraphRoot."
- "getRenderNodesInTree().length"))
-
- # Now draw lines
- s.type("numShapes", "5")
- s.click("btnLines")
-
- # 5 more shapes should get created
- # (1 for the parent transform)
- s.wait_for_condition(
- "window.g_client."
- "getObjectsByClassName('o3d.Shape').length == 5",
- 5000)
- # 5 more primitives and drawelements should get created
- self.assertEqual(
- "5",
- s.get_eval("window.g_client."
- "getObjectsByClassName('o3d.Primitive').length"))
- self.assertEqual(
- "5",
- s.get_eval("window.g_client."
- "getObjectsByClassName('o3d.DrawElement').length"))
-
- # Draw more lines
- s.type("numShapes", "11")
- for i in range(1, 10):
- s.click("btnLines")
- s.wait_for_condition(
- "window.g_client."
- "getObjectsByClassName('o3d.Shape').length == %d" % (5 + i * 11),
- 5000)
- self.assertEqual(
- str(5 + i * 11),
- s.get_eval("window.g_client."
- "getObjectsByClassName('o3d.Primitive').length"))
-
- # Clear triangles, reset pack.
- s.click("btnClear")
-
- # Check assets for base o3d setup again.
- self.assertEqual(
- "2",
- s.get_eval("window.g_client.root.getTransformsInTree().length"))
- self.assertEqual(
- "8",
- s.get_eval("window.g_client.renderGraphRoot."
- "getRenderNodesInTree().length"))
-
- # Now draw 1000 triangles
- s.type("numShapes", "1000")
- s.click("btnTri")
-
- # 30 seconds to draw 1000 triangle shapes
- s.wait_for_condition(
- "window.g_client."
- "getObjectsByClassName('o3d.Shape').length == 1000",
- 30000)
- # Assert number of primitives
- self.assertEqual(
- "1000",
- s.get_eval("window.g_client."
- "getObjectsByClassName('o3d.Primitive').length"))
-
- # Clear triangles, reset pack.
- s.click("btnClear")
-
- def TestStressMultiWindow(self):
- """Opens 5 windows of simpletexture.html."""
-
- # Alias for the selenium session
- s = self.session
-
- # Save the titles of windows so we can reset the current window.
- # Note: docs of selenium are out of date. We should be able to use ids or
- # names in select_window below but all of those methods failed.
- old = s.get_all_window_titles()
-
- for i in range(1, 5):
- s.open_window(
- self.GetURL("/samples/simpletexture.html"),
- "o3dstress_window%d" % i)
-
- for i in range(1, 5):
- s.select_window("o3dstress_window%d" % i)
- # Allow a limited time for the plugin to initialize.
- s.wait_for_condition("typeof(window.g_client) != 'undefined';", 30000)
-
- # Sanity checks.
- self.assertEqual("Tutorial B3: Textures", s.get_title())
- self.assertEqual("null", s.get_eval("window.undefined_symbol_xxxyyy"))
-
- for i in range(1, 5):
- s.select_window("o3dstress_window%d" % i)
- s.close()
-
- # make the old window the current window so the next test will run.
- s.select_window(old[0])
-
- def TestStressCullingZSort(self):
- """Checks culling and zsorting work."""
-
- # Alias for the selenium session
- s = self.session
- s.open(self.GetURL("/tests/selenium/tests/culling-zsort-test.html"))
-
- # Allow a limited time for the plugin to initialize.
- s.wait_for_condition("typeof(window.g_client) != 'undefined';", 20000)
-
- # Sanity checks.
- self.assertEqual("Culling and ZSorting Test.", s.get_title())
- self.assertEqual("null", s.get_eval("window.undefined_symbol_xxxyyy"))
- s.wait_for_condition("window.g_client != null", 10000)
-
- # Wait for all instances to be created.
- s.wait_for_condition(
- "window.g_totalDrawElementsElement.innerHTML == '2'",
- 40000)
-
- # Stop animation
- s.run_script("g_timeMult = 0")
- s.run_script("g_client.renderMode = g_o3d.Client.RENDERMODE_ON_DEMAND")
- s.run_script("var g_rendered = false")
-
- new_data = []
- culling_reference_data = [[1793, 4472, 3780, 2, 4844, 213, 4631],
- [1793, 6011, 3854, 2, 7734, 337, 7397],
- [1793, 3014, 2416, 2, 3400, 121, 3279],
- [1793, 2501, 2408, 2, 2420, 162, 2258],
- [1793, 2933, 2914, 2, 2746, 182, 2564],
- [1793, 2825, 2848, 2, 2604, 171, 2433],
- [1793, 2933, 2790, 2, 2870, 155, 2715],
- [1793, 4337, 3004, 2, 5360, 237, 5123]]
-
- # Take screenshots
- for clock in range(0, 8):
- s.run_script("window.g_clock = " + str(clock * 3.14159 * 2.5 + 0.5))
- self.assertTrue(
- selenium_utilities.TakeScreenShot(s, self.browser, "window.g_client",
- "cullingzsort" + str(clock + 1)))
- s.run_script("g_framesRendered = 0")
- while int(s.get_eval("window.g_framesRendered")) < 3:
- s.run_script("window.g_client.render()")
- data = [s.get_eval("window.g_totalTransformsElement.innerHTML"),
- s.get_eval("window.g_transformsProcessedElement.innerHTML"),
- s.get_eval("window.g_transformsCulledElement.innerHTML"),
- s.get_eval("window.g_totalDrawElementsElement.innerHTML"),
- s.get_eval("window.g_drawElementsProcessedElement.innerHTML"),
- s.get_eval("window.g_drawElementsCulledElement.innerHTML"),
- s.get_eval("window.g_drawElementsRenderedElement.innerHTML")]
- new_data.append(data)
- print ", ".join(data)
-
- # check the results
- for clock in range(0, 8):
- for ii in range(0, 7):
- # comment out the following line and add a "pass" line if you need new
- # culling reference data.
- self.assertEqual(int(new_data[clock][ii]),
- culling_reference_data[clock][ii])
-
-
-if __name__ == "__main__":
- pass
diff --git a/o3d/tests/selenium/mac_chrome.sh b/o3d/tests/selenium/mac_chrome.sh
deleted file mode 100644
index 68a0c87..0000000
--- a/o3d/tests/selenium/mac_chrome.sh
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" "$@"
diff --git a/o3d/tests/selenium/main.py b/o3d/tests/selenium/main.py
deleted file mode 100644
index 7cb4d1c..0000000
--- a/o3d/tests/selenium/main.py
+++ /dev/null
@@ -1,743 +0,0 @@
-#!/usr/bin/python2.4
-# 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.
-
-
-"""Selenium tests for the O3D plugin.
-
-Sets up a local Selenium Remote Control server and a static file
-server that serves files off the o3d directory.
-
-Launches browsers to test the local build of the o3d plugin
-and reports results back to the user.
-"""
-
-import os
-import sys
-
-script_dir = os.path.normpath(os.path.dirname(os.path.abspath(__file__)))
-o3d_dir = os.path.dirname(os.path.dirname(script_dir))
-src_dir = os.path.dirname(o3d_dir)
-third_party_dir = os.path.join(src_dir, 'third_party')
-o3d_third_party_dir = os.path.join(o3d_dir, 'third_party')
-gflags_dir = os.path.join(o3d_third_party_dir, 'gflags', 'python')
-selenium_dir = os.path.join(third_party_dir, 'selenium_rc', 'files')
-selenium_py_dir = os.path.join(selenium_dir, 'selenium-python-client-driver')
-sys.path.append(gflags_dir)
-sys.path.append(selenium_py_dir)
-
-import re
-import SimpleHTTPServer
-import socket
-import SocketServer
-import subprocess
-import threading
-import time
-import unittest
-import gflags
-import javascript_unit_tests
-import test_runner
-import selenium
-import samples_tests
-import selenium_constants
-import selenium_utilities
-import pdiff_test
-import Queue
-
-if sys.platform == 'win32' or sys.platform == 'cygwin':
- default_java_exe = "java.exe"
-else:
- default_java_exe = "java"
-
-# Command line flags
-FLAGS = gflags.FLAGS
-gflags.DEFINE_boolean("verbose", False, "verbosity")
-gflags.DEFINE_boolean("screenshots", False, "takes screenshots")
-gflags.DEFINE_string(
- "java",
- default_java_exe,
- "specifies the path to the java executable.")
-gflags.DEFINE_string(
- "selenium_server",
- os.path.join(selenium_dir, 'selenium-server', 'selenium-server.jar'),
- "specifies the path to the selenium server jar.")
-gflags.DEFINE_string(
- "product_dir",
- None,
- "specifies the path to the build output directory.")
-gflags.DEFINE_string(
- "screencompare",
- "",
- "specifies the directory in which perceptualdiff resides.\n"
- "compares screenshots with reference images")
-gflags.DEFINE_string(
- "screenshotsdir",
- selenium_constants.DEFAULT_SCREENSHOT_PATH,
- "specifies the directory in which screenshots will be stored.")
-gflags.DEFINE_string(
- "referencedir",
- selenium_constants.DEFAULT_SCREENSHOT_PATH,
- "Specifies the directory where reference images will be read from.")
-gflags.DEFINE_string(
- "testprefix", "Test",
- "specifies the prefix of tests to run")
-gflags.DEFINE_string(
- "testsuffixes",
- "small,medium,large",
- "specifies the suffixes, separated by commas of tests to run")
-gflags.DEFINE_string(
- "servertimeout",
- "30",
- "Specifies the timeout value, in seconds, for the selenium server.")
-
-
-# Browsers to choose from (for browser flag).
-# use --browser $BROWSER_NAME to run
-# tests for that browser
-gflags.DEFINE_list(
- "browser",
- "*firefox",
- "\n".join(["comma-separated list of browsers to test",
- "Options:"] +
- selenium_constants.SELENIUM_BROWSER_SET))
-gflags.DEFINE_string(
- "browserpath",
- "",
- "specifies the path to the browser executable "
- "(for platforms that don't support MOZ_PLUGIN_PATH)")
-gflags.DEFINE_string(
- "samplespath",
- "",
- "specifies the path from the web root to the samples.")
-
-class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
- """Hook to handle HTTP server requests.
-
- Functions as a handler for logging and other utility functions.
- """
-
- def log_message(self, format, *args):
- """Logging hook for HTTP server."""
-
- # For now, just suppress logging.
- pass
- # TODO: might be nice to have a verbose option for debugging.
-
-
-
-
-class LocalFileHTTPServer(threading.Thread):
- """Minimal HTTP server that serves local files.
-
- Members:
- http_alive: event to signal that http server is up and running
- http_port: the TCP port the server is using
- """
-
- START_PORT = 8100
- END_PORT = 8105
-
- def __init__(self, local_root=None):
- """Initializes the server.
-
- Initializes the HTTP server to serve static files from the
- local o3d directory
-
- Args:
- local_root: all files below this path are served. If not specified,
- the current directory is the root.
- """
- threading.Thread.__init__(self)
- self._local_root = local_root
- self.http_alive = threading.Event()
- self.http_port = 0
-
- def run(self):
- """Runs the HTTP server.
-
- Server is started on an available port in the range of
- START_PORT to END_PORT
- """
-
- if self._local_root:
- os.chdir(self._local_root)
-
- for self.http_port in range(self.START_PORT, self.END_PORT):
- # Attempt to start the server
- try:
- httpd = SocketServer.TCPServer(("", self.http_port),
- MyRequestHandler)
- except socket.error:
- # Server didn't manage to start up, try another port.
- pass
- else:
- self.http_alive.set()
- httpd.serve_forever()
-
- if not self.http_alive.isSet():
- print("No available port found for HTTP server in the range %d to %d."
- % (self.START_PORT, self.END_PORT))
- self.http_port = 0
-
- @staticmethod
- def StartServer(local_root=None):
- """Create and start a LocalFileHTTPServer on a separate thread.
-
- Args:
- local_root: serve all static files below this directory. If not
- specified, the current directory is the root.
-
- Returns:
- http_server: LocalFileHTTPServer() object
- """
-
- # Start up the Selenium Remote Control server
- http_server = LocalFileHTTPServer(local_root)
- http_server.setDaemon(True)
- http_server.start()
-
- time_out = 30.0
-
- # Wait till the Selenium RC Server is up
- print 'Waiting %d seconds for local HTTP server to start.' % (int(time_out))
- http_server.http_alive.wait(time_out)
- if not http_server.http_port:
- print 'Timed out.'
- return None
-
- print "LocalFileHTTPServer started on port %d" % http_server.http_port
-
- return http_server
-
-
-class SeleniumRemoteControl(threading.Thread):
- """A thread that launches the Selenium Remote Control server.
-
- The Remote Control server allows us to launch a browser and remotely
- control it from a script.
-
- Members:
- selenium_alive: event to signal that selenium server is up and running
- selenium_port: the TCP port the server is using
- process: the subprocess.Popen instance for the server
- """
-
- START_PORT = 5430
- END_PORT = 5535
-
- def __init__(self, verbose, java_path, selenium_server, server_timeout):
- """Initializes the SeleniumRemoteControl class.
-
- Args:
- verbose: boolean verbose flag
- java_path: path to java used to run selenium.
- selenium_server: path to jar containing selenium server.
- server_timeout: server timeout value, in seconds.
- """
- self.selenium_alive = threading.Event()
- self.selenium_port = 0
- self.verbose = verbose
- self.java_path = java_path
- self.selenium_server = selenium_server
- self.timeout = server_timeout
- threading.Thread.__init__(self)
-
- def run(self):
- """Starts the selenium server.
-
- Server is started on an available port in the range of
- START_PORT to END_PORT
- """
-
- for self.selenium_port in range(self.START_PORT, self.END_PORT):
- # Attempt to start the selenium RC server from java
- self.process = subprocess.Popen(
- [self.java_path, "-jar", self.selenium_server, "-multiWindow",
- "-port", str(self.selenium_port), "-timeout", self.timeout],
- stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
-
- for unused_i in range(1, 20):
- server_msg = self.process.stdout.readline()
- if self.verbose and server_msg is not None:
- # log if verbose flag is on
- print "sel_serv:" + server_msg
-
- # This status message indicates that the server has done
- # a bind to the port self.selenium_port successfully.
- if server_msg.find("INFO - Started SocketListener") != -1:
- self.selenium_alive.set()
- break
-
- # Error starting server on this port, try the next port.
- if not self.selenium_alive.isSet():
- continue
-
- # Loop and read from stdout
- while self.process.poll() is None:
- server_msg = self.process.stdout.readline()
- if self.verbose and server_msg is not None:
- # log if verbose flag is on
- print "sel_serv:" + server_msg
-
- # Finish.
- break
-
- if not self.selenium_alive.isSet():
- print("No available port found for Selenium RC Server "
- "in the range %d to %d."
- % (self.START_PORT, self.END_PORT))
- self.selenium_port = 0
-
- @staticmethod
- def StartServer(verbose, java_path, selenium_server, server_timeout):
- """Create and start the Selenium RC Server on a separate thread.
-
- Args:
- verbose: boolean verbose flag
- java_path: path to java used to run selenium.
- selenium_server: path to jar containing selenium server.
- server_timeout: server timeout value, in seconds
-
- Returns:
- selenium_server: SeleniumRemoteControl() object
- """
-
- # Start up the Selenium Remote Control server
- selenium_server = SeleniumRemoteControl(verbose,
- java_path,
- selenium_server,
- server_timeout)
-
- selenium_server.setDaemon(True)
- selenium_server.start()
-
- time_out = 30.0
-
- # Wait till the Selenium RC Server is up
- print 'Waiting %d seconds for Selenium RC to start.' % (int(time_out))
- selenium_server.selenium_alive.wait(time_out)
- if not selenium_server.selenium_port:
- print 'Timed out.'
- return None
-
- print("Selenium RC server started on port %d"
- % selenium_server.selenium_port)
-
- return selenium_server
-
-
-class SeleniumSessionBuilder:
- def __init__(self, sel_port, sel_timeout, http_port, browserpath):
-
- self.sel_port = sel_port
- self.sel_timeout = sel_timeout
- self.http_port = http_port
- self.browserpath = browserpath
-
- def NewSeleniumSession(self, browser):
- server_url = "http://localhost:"
- server_url += str(self.http_port)
-
- browser_path_with_space = ""
- if self.browserpath:
- browser_path_with_space = " " + self.browserpath
-
-
- new_session = selenium.selenium("localhost",
- self.sel_port,
- browser + browser_path_with_space,
- server_url)
-
- new_session.start()
- new_session.set_timeout(self.sel_timeout)
- if browser == "*iexplore":
- # This improves stability on IE, especially IE 6. It at least fixes the
- # StressWindow test. It adds a 10ms delay between selenium commands.
- new_session.set_speed(10)
-
- return new_session
-
-
-def TestBrowser(session_builder, browser, test_list, verbose):
- """Runs Selenium tests for a specific browser.
-
- Args:
- session_builder: session_builder for creating new selenium sessions.
- browser: selenium browser name (eg. *iexplore, *firefox).
- test_list: list of tests.
-
- Returns:
- summary_result: result of test runners.
- """
- print "Testing %s..." % browser
-
- summary_result = test_runner.TestResult(test_runner.StringBuffer(), browser,
- verbose)
-
- # Fill up the selenium test queue.
- test_queue = Queue.Queue()
- for test in test_list:
- test_queue.put(test)
-
-
- pdiff_queue = None
- if FLAGS.screenshots:
- # Need to do screen comparisons.
- # |pdiff_queue| is the queue of perceptual diff tests that need to be done.
- # This queue is added to by individual slenium test runners.
- # |pdiff_result_queue| is the result of the perceptual diff tests.
- pdiff_queue = Queue.Queue()
- pdiff_result_queue = Queue.Queue()
- pdiff_worker = test_runner.PDiffTestRunner(pdiff_queue,
- pdiff_result_queue,
- browser, verbose)
- pdiff_worker.start()
-
- # Start initial selenium test runner.
- worker = test_runner.SeleniumTestRunner(session_builder, browser,
- test_queue, pdiff_queue,
- verbose)
- worker.start()
-
- # Run through all selenium tests.
- while not worker.IsCompletelyDone():
- if worker.IsTesting() and worker.IsPastDeadline():
- # Test has taken more than allotted. Abort and go to next test.
- worker.AbortTest()
-
- elif worker.DidFinishTest():
- # Do this so that a worker does not grab test off queue till we tell it.
- result = worker.Continue()
- result.printAll(sys.stdout)
- summary_result.merge(result)
-
- # Sleep here for a brief time. This thread is polling the worker thread.
- # We cannot wait for a message from the worker thread because the worker
- # may hang on a bad test. We also do not want to sleep till the test's
- # deadline because the test may finish before then.
- time.sleep(.1)
-
- if FLAGS.screenshots:
- # Finish screenshot comparisons.
- pdiff_worker.EndTesting()
- while not pdiff_worker.IsCompletelyDone():
- time.sleep(1)
-
- # Be careful here, make sure no one else is editing |pdiff_reult_queue|.
- while not pdiff_result_queue.empty():
- result = pdiff_result_queue.get()
- result.printAll(sys.stdout)
- summary_result.merge(result)
-
- return summary_result
-
-
-
-def MatchesSuffix(name, suffixes):
- """Checks if a name ends in one of the suffixes.
-
- Args:
- name: Name to test.
- suffixes: list of suffixes to test for.
- Returns:
- True if name ends in one of the suffixes or if suffixes is empty.
- """
- if suffixes:
- name_lower = name.lower()
- for suffix in suffixes:
- if name_lower.endswith(suffix):
- return True
- return False
- else:
- return True
-
-
-def _GetTestsFromFile(filename, prefix, test_prefix_filter, test_suffixes,
- browser, module, path_to_html):
- """Add tests defined in filename, and associated perceptual diff test, if
- needed.
-
- Assumes module has a method "GenericTest" that uses self.args to run.
-
- Args:
- filename: filename of file with list of tests.
- prefix: prefix to add to the beginning of each test.
- test_prefix_filter: Only adds a test if it starts with this.
- test_suffixes: list of suffixes to filter by. An empty list = pass all.
- browser: browser name.
- module: module which will have method GenericTest() called to run each test.
- path_to_html: Path from server root to html
- """
- # See comments in that file for the expected format.
- # skip lines that are blank or have "#" or ";" as their first non whitespace
- # character.
- test_list_file = open(filename, "r")
- samples = test_list_file.readlines()
- test_list_file.close()
-
- tests = []
-
- for sample in samples:
- sample = sample.strip()
- if not sample or sample[0] == ";" or sample[0] == "#":
- continue
-
- arguments = sample.split()
- test_type = arguments[0].lower()
- test_path = arguments[1]
- options = arguments[2:]
-
- # TODO: Add filter based on test_type
- test_skipped = False
- if test_path.startswith("Test"):
- name = test_path
- else:
- # Need to make a name.
- name = ("Test" + prefix + re.sub("\W", "_", test_path) +
- test_type.capitalize())
- # Only test suffixes for generic tests. That is how it has always worked.
- if test_suffixes and not MatchesSuffix(name, test_suffixes):
- test_skipped = True
-
- if test_prefix_filter and not name.startswith(test_prefix_filter):
- test_skipped = True
-
- # Only execute this test if the current browser is not in the list
- # of skipped browsers.
- screenshot_count = 0
- for option in options:
- if option.startswith("except"):
- skipped_platforms = selenium_utilities.GetArgument(option)
- if not skipped_platforms is None:
- skipped_platforms = skipped_platforms.split(",")
- if browser in skipped_platforms:
- test_skipped = True
- elif option.startswith("screenshots"):
- screenshot_count += int(selenium_utilities.GetArgument(option))
- elif option.startswith("screenshot"):
- screenshot_count += 1
-
- if not test_skipped:
- # Add a test method with this name if it doesn't exist.
- if not (hasattr(module, name) and callable(getattr(module, name))):
- setattr(module, name, module.GenericTest)
-
- new_test = module(name, browser, path_to_html, test_type, test_path,
- options)
-
- if screenshot_count and FLAGS.screenshots:
- pdiff_name = name + 'Screenshots'
- screenshot = selenium_utilities.ScreenshotNameFromTestName(test_path)
- setattr(pdiff_test.PDiffTest, pdiff_name,
- pdiff_test.PDiffTest.PDiffTest)
- new_pdiff = pdiff_test.PDiffTest(pdiff_name,
- screenshot_count,
- screenshot,
- FLAGS.screencompare,
- FLAGS.screenshotsdir,
- FLAGS.referencedir,
- options)
- tests += [(new_test, new_pdiff)]
- else:
- tests += [new_test]
-
-
- return tests
-
-
-def GetTestsForBrowser(browser, test_prefix, test_suffixes):
- """Returns list of tests from test files.
-
- Args:
- browser: browser name
- test_prefix: prefix of tests to run.
- test_suffixes: A comma separated string of suffixes to filter by.
- Returns:
- A list of unittest.TestCase.
- """
- tests = []
- suffixes = test_suffixes.split(",")
-
- # add sample tests.
- filename = os.path.abspath(os.path.join(script_dir, "sample_list.txt"))
- tests += _GetTestsFromFile(filename, "Sample", test_prefix, suffixes, browser,
- samples_tests.SampleTests,
- FLAGS.samplespath.replace("\\","/"))
-
- # add javascript tests.
- filename = os.path.abspath(os.path.join(script_dir,
- "javascript_unit_test_list.txt"))
- tests += _GetTestsFromFile(filename, "UnitTest", test_prefix, suffixes,
- browser, javascript_unit_tests.JavaScriptUnitTests,
- "")
-
- return tests
-
-
-def GetChromePath():
- value = None
- if sys.platform == "win32" or sys.platform == "cygwin":
- import _winreg
- try:
- key = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,
- "Applications\\chrome.exe\\shell\\open\\command")
- (value, type) = _winreg.QueryValueEx(key, None)
- _winreg.CloseKey(key)
- value = os.path.dirname(value)
-
- except WindowsError:
- value = None
- if '*googlechrome' in FLAGS.browser:
- print "Unable to determine location for Chrome -- is it installed?"
-
- return value
-
-
-def main(unused_argv):
- # Boolean to record if all tests passed.
- all_tests_passed = True
-
- selenium_constants.REFERENCE_SCREENSHOT_PATH = os.path.join(
- FLAGS.referencedir,
- "reference",
- "")
- selenium_constants.PLATFORM_SPECIFIC_REFERENCE_SCREENSHOT_PATH = os.path.join(
- FLAGS.referencedir,
- selenium_constants.PLATFORM_SCREENSHOT_DIR,
- "")
-
- # Launch HTTP server.
- http_server = LocalFileHTTPServer.StartServer(FLAGS.product_dir)
-
- if not http_server:
- print "Could not start a local http server with root." % FLAGS.product_dir
- return 1
-
-
- # Start Selenium Remote Control and Selenium Session Builder.
- sel_server_jar = os.path.abspath(FLAGS.selenium_server)
- sel_server = SeleniumRemoteControl.StartServer(
- FLAGS.verbose, FLAGS.java, sel_server_jar,
- FLAGS.servertimeout)
-
- if not sel_server:
- print "Could not start selenium server at %s." % sel_server_jar
- return 1
-
- session_builder = SeleniumSessionBuilder(
- sel_server.selenium_port,
- int(FLAGS.servertimeout) * 1000,
- http_server.http_port,
- FLAGS.browserpath)
-
- all_tests_passed = True
- # Test browsers.
- for browser in FLAGS.browser:
- if browser in set(selenium_constants.SELENIUM_BROWSER_SET):
- test_list = GetTestsForBrowser(browser, FLAGS.testprefix,
- FLAGS.testsuffixes)
-
- result = TestBrowser(session_builder, browser, test_list, FLAGS.verbose)
-
- if not result.wasSuccessful():
- all_tests_passed = False
-
- # Log non-succesful tests, for convenience.
- print ""
- print "Failures for %s:" % browser
- print "[Selenium tests]"
- for entry in test_list:
- if type(entry) == tuple:
- test = entry[0]
- else:
- test = entry
-
- if test in result.results:
- if result.results[test] != 'PASS':
- print test.name
-
- print ""
- print "[Perceptual Diff tests]"
- for entry in test_list:
- if type(entry) == tuple:
- pdiff_test = entry[1]
- if pdiff_test in result.results:
- if result.results[pdiff_test] != 'PASS':
- print pdiff_test.name
-
-
- # Log summary results.
- print ""
- print "Summary for %s:" % browser
- print " %d tests run." % result.testsRun
- print " %d errors." % len(result.errors)
- print " %d failures.\n" % len(result.failures)
-
- else:
- print "ERROR: Browser %s is invalid." % browser
- print "Run with --help to view list of supported browsers.\n"
- all_tests_passed = False
-
- # Shut down remote control
- shutdown_session = selenium.selenium("localhost",
- sel_server.selenium_port, "*firefox",
- "http://%s:%d" % (socket.gethostname(), http_server.http_port))
- shutdown_session.shut_down_selenium_server()
-
- if all_tests_passed:
- # All tests successful.
- return 0
- else:
- # Return error code 1.
- return 1
-
-if __name__ == "__main__":
- remaining_argv = FLAGS(sys.argv)
-
- # Setup the environment for Firefox
- os.environ["MOZ_CRASHREPORTER_DISABLE"] = "1"
- os.environ["MOZ_PLUGIN_PATH"] = os.path.normpath(FLAGS.product_dir)
-
- # Setup the path for chrome.
- chrome_path = GetChromePath()
- if chrome_path:
- if os.environ.get("PATH"):
- os.environ["PATH"] = os.pathsep.join([os.environ["PATH"], chrome_path])
- else:
- os.environ["PATH"] = chrome_path
-
- # Setup the LD_LIBRARY_PATH on Linux.
- if sys.platform[:5] == "linux":
- if os.environ.get("LD_LIBRARY_PATH"):
- os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(
- [os.environ["LD_LIBRARY_PATH"], os.path.normpath(FLAGS.product_dir)])
- else:
- os.environ["LD_LIBRARY_PATH"] = os.path.normpath(FLAGS.product_dir)
-
- sys.exit(main(remaining_argv))
diff --git a/o3d/tests/selenium/pdiff_test.py b/o3d/tests/selenium/pdiff_test.py
deleted file mode 100644
index 0a91f55..0000000
--- a/o3d/tests/selenium/pdiff_test.py
+++ /dev/null
@@ -1,132 +0,0 @@
-import os
-import re
-import subprocess
-import unittest
-import sys
-
-import selenium_utilities
-import selenium_constants
-
-class PDiffTest(unittest.TestCase):
- """A perceptual diff test class, for running perceptual diffs on any
- number of screenshots."""
-
- def __init__(self, name, num_screenshots, screenshot_name, pdiff_path,
- gen_dir, ref_dir, options):
- unittest.TestCase.__init__(self, name)
- self.name = name
- self.num_screenshots = num_screenshots
- self.screenshot_name = screenshot_name
- self.pdiff_path = pdiff_path
- self.gen_dir = gen_dir
- self.ref_dir = ref_dir
- self.options = options
-
- def shortDescription(self):
- """override unittest.TestCase shortDescription for our own descriptions."""
- return "Screenshot comparison for: " + self.name
-
- def PDiffTest(self):
- """Runs a generic Perceptual Diff test."""
- # Get arguments for perceptual diff.
- pixel_threshold = "10"
- alpha_threshold = "1.0"
- use_colorfactor = False
- use_downsample = False
- use_edge = True
- edge_threshold = "5"
-
- for opt in self.options:
- if opt.startswith("pdiff_threshold"):
- pixel_threshold = selenium_utilities.GetArgument(opt)
- elif (opt.startswith("pdiff_threshold_mac") and
- sys.platform == "darwin"):
- pixel_threshold = selenium_utilities.GetArgument(opt)
- elif (opt.startswith("pdiff_threshold_win") and
- sys.platform == 'win32' or sys.platform == "cygwin"):
- pixel_threshold = selenium_utilities.GetArgument(opt)
- elif (opt.startswith("pdiff_threshold_linux") and
- sys.platform[:5] == "linux"):
- pixel_threshold = selenium_utilities.GetArgument(opt)
- elif (opt.startswith("colorfactor")):
- colorfactor = selenium_utilities.GetArgument(opt)
- use_colorfactor = True
- elif (opt.startswith("downsample")):
- downsample_factor = selenium_utilities.GetArgument(opt)
- use_downsample = True
- elif (opt.startswith("pdiff_edge_ignore_off")):
- use_edge = False
- elif (opt.startswith("pdiff_edge_threshold")):
- edge_threshold = selenium_utilities.GetArgument(opt)
-
- results = []
- # Loop over number of screenshots.
- for screenshot_no in range(self.num_screenshots):
- # Find reference image.
- shotname = self.screenshot_name + str(screenshot_no + 1)
- J = os.path.join
- platform_img_path = J(self.ref_dir,
- selenium_constants.PLATFORM_SCREENSHOT_DIR,
- shotname + '_reference.png')
- reg_img_path = J(self.ref_dir,
- selenium_constants.DEFAULT_SCREENSHOT_DIR,
- shotname + '_reference.png')
-
- if os.path.exists(platform_img_path):
- ref_img_path = platform_img_path
- elif os.path.exists(reg_img_path):
- ref_img_path = reg_img_path
- else:
- self.fail('Reference image for ' + shotname + ' not found.')
-
- # Find generated image.
- gen_img_path = J(self.gen_dir, shotname + '.png')
- diff_img_path = J(self.gen_dir, 'cmp_' + shotname + '.png')
-
- self.assertTrue(os.path.exists(gen_img_path),
- 'Generated screenshot for ' + shotname + ' not found.\n')
-
- # Run perceptual diff
- arguments = [self.pdiff_path,
- ref_img_path,
- gen_img_path,
- "-output", diff_img_path,
- "-fov", "45",
- "-alphaThreshold", alpha_threshold,
- # Turn on verbose output for the percetual diff so we
- # can see how far off we are on the threshold.
- "-verbose",
- # Set the threshold to zero so we can get a count
- # of the different pixels. This causes the program
- # to return failure for most images, but we can compare
- # the values ourselves below.
- "-threshold", "0"]
- if use_colorfactor:
- arguments += ["-colorfactor", colorfactor]
- if use_downsample:
- arguments += ["-downsample", downsample_factor]
- if use_edge:
- arguments += ["-ignoreEdges", edge_threshold]
-
- pdiff_pipe = subprocess.Popen(arguments,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE)
- (pdiff_stdout, pdiff_stderr) = pdiff_pipe.communicate()
- result = pdiff_pipe.returncode
- # Find out how many pixels were different by looking at the output.
- pixel_re = re.compile("(\d+) pixels are different", re.DOTALL)
- pixel_match = pixel_re.search(pdiff_stdout)
- different_pixels = "0"
- if pixel_match:
- different_pixels = pixel_match.group(1)
-
- results += [(shotname, int(different_pixels))]
-
- all_tests_passed = True
- msg = "Pixel threshold is %s. Failing screenshots:\n" % pixel_threshold
- for name, pixels in results:
- if pixels >= int(pixel_threshold):
- all_tests_passed = False
- msg += " %s, differing by %s\n" % (name, str(pixels))
-
- self.assertTrue(all_tests_passed, msg)
diff --git a/o3d/tests/selenium/run.bat b/o3d/tests/selenium/run.bat
deleted file mode 100644
index 3305ef8..0000000
--- a/o3d/tests/selenium/run.bat
+++ /dev/null
@@ -1,34 +0,0 @@
-@echo off
-REM Copyright 2009, Google Inc.
-REM All rights reserved.
-REM
-REM Redistribution and use in source and binary forms, with or without
-REM modification, are permitted provided that the following conditions are
-REM met:
-REM
-REM * Redistributions of source code must retain the above copyright
-REM notice, this list of conditions and the following disclaimer.
-REM * Redistributions in binary form must reproduce the above
-REM copyright notice, this list of conditions and the following disclaimer
-REM in the documentation and/or other materials provided with the
-REM distribution.
-REM * Neither the name of Google Inc. nor the names of its
-REM contributors may be used to endorse or promote products derived from
-REM this software without specific prior written permission.
-REM
-REM THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-REM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-REM LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-REM A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-REM OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-REM SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-REM LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-REM DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-REM THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-REM (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-REM OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-echo Setting up python environment..
-call %~dp0..\..\..\third_party\python_24\setup_env.bat
-echo Starting selenium tests..
-%~dp0..\..\..\third_party\python_24\python.exe main.py %*
diff --git a/o3d/tests/selenium/sample_list.txt b/o3d/tests/selenium/sample_list.txt
deleted file mode 100644
index 2fe3e67..0000000
--- a/o3d/tests/selenium/sample_list.txt
+++ /dev/null
@@ -1,148 +0,0 @@
-#
-# Test Requirements:
-#
-# Each sample is expected to have a global variable called g_finished
-# that is set to true when the sample has finish initalizing and is ready
-# for a screenshot.
-#
-# Line Format:
-#
-# TestType test-name options
-#
-# Valid TestTypes are:
-#
-# small
-# medium
-# large
-#
-# options are separated by spaces.
-# screenshot : take a screenshot. You can specify a time with
-# screenshot(seconds) as in screenshot(4), take it at the 4 second mark.
-# You can also specify more than 1 screenshot by specifying more than
-# one screenshot option as in "screenshot(4), screenshot(6.5). If no time
-# is specified 27.5 is used.
-#
-# To take a screenshot the test must have a global variable "g_client"
-# that is the client plugin object from which to take a screenshot.
-#
-# If the sample is animated, it is expected to have a global variable
-# called g_timeMult that can be set to 0 to stop the animation. All of
-# its animation must be based on a global variable called g_clock, such
-# that setting g_clock to the same value will always produce the same
-# image.
-#
-# timeout(milliseconds) : Set the timeout to wait for the initial page load.
-# Default 10000.
-#
-# run_timeout(milliseconds) : Set the timeout for the test, not including
-# the initial page load. Default is 25000 plus time for each screenshot.
-#
-# client(client_variable_name) : Name of client variable in javascript.
-# Default = "g_client"
-#
-# pdiff_threshold_mac(number_of_pixels_allowed)
-# pdiff_threshold_win(number_of_pixels_allowed)
-# pdiff_threshold_linux(number_of_pixels_allowed)
-# pdiff_threshold(number_of_pixels_allowed) : Number of pixels
-# allowed to be perceptually different before the test fails.
-# "pdiff_threshold" specifies the threshold for all
-# platforms. Platform specific versions override the
-# threshold for that platform. The default threshold is 10 pixels.
-#
-# except(*firefox,*iexplore,*googlechrome) : Name of the browser
-# environment(s) where the test should be skipped. This list should
-# not have spaces between the browser names.
-# Default = ""
-#
-# colorfactor(0 to 1) : Determines how important color is for comparison. A
-# value of 1 means they must be exactly the same; a value of 0 means it
-# won't factor in at all.
-#
-# downsample(number_of_times_to_halve_resolution) : The resolution will be
-# cut in half this number of times before comparing. It is useful for
-# eliminating aliasing artifacts since such differences are less
-# noticeable at the lower resolution. Be careful with using this parameter
-# as it may mask other problems.
-#
-# pdiff_edge_ignore_off : Turn off edge detection function in pdiff.
-# By default, it's on with a default edge detect threshold 5.
-#
-# pdiff_edge_threshold(0 to 7) : Set edge detect threshold in pdiff.
-# This threshold indicates the max number of neighbors the pixel can
-# have to be considered as edge. 0 means only ignore scattered pixels.
-# NOTE! ----------------------------------------------------------------------
-#
-# Read the sample guidelines
-# http://wiki.corp.google.com/twiki/bin/view/Main/ClientThreeDSampleGuidelines
-#
-#
-medium 2d screenshot timeout(30000) pdiff_threshold(200) pdiff_threshold_mac(41200) colorfactor(0.8) downsample(1)
-medium animation
-large animated-scene screenshot timeout(55000) pdiff_threshold(200)
-large beachdemo/beachdemo screenshot timeout(120000) pdiff_threshold(200) pdiff_threshold_mac(2100) downsample(1) except(*iexplore,*googlechrome)
-medium billboards screenshot pdiff_threshold(200)
-medium bitmap-draw-image screenshot pdiff_threshold(200)
-medium canvas screenshot pdiff_threshold(200) pdiff_threshold_mac(14600)
-medium canvas-fonts screenshot pdiff_threshold(200) pdiff_threshold_mac(21900)
-medium canvas-texturedraw
-medium checkers screenshot pdiff_threshold(200)
-medium convolution screenshot pdiff_threshold(200)
-medium culling screenshot(9) pdiff_threshold(450) downsample(1)
-medium debugging screenshot pdiff_threshold(200) pdiff_threshold_mac(3000)
-medium displayfps
-small generate-texture screenshot pdiff_threshold(200) except(*iexplore)
-medium hellocube screenshot pdiff_threshold(200)
-medium hellocube-colors screenshot pdiff_threshold(200)
-medium helloworld screenshot pdiff_threshold(200)
-medium hud-2d-overlay screenshot pdiff_threshold(200) pdiff_threshold_win(200)
-medium instance-override screenshot(2) pdiff_threshold(200) run_time(200000)
-medium instancing screenshot pdiff_threshold(200) run_time(200000)
-medium juggler screenshot downsample(1)
-medium julia screenshot
-small multiple-views screenshot pdiff_threshold(200)
-medium old-school-shadows screenshot pdiff_threshold(200)
-medium particles screenshot(2) pdiff_threshold(200)
-medium primitives screenshot pdiff_threshold(200) pdiff_threshold_mac(20000) colorfactor(.7)
-medium procedural-texture screenshot pdiff_threshold(200)
-medium render-targets screenshot pdiff_threshold(200)
-medium scatter-chart screenshot pdiff_threshold(200) pdiff_threshold_mac(10600)
-medium simple screenshot client(g_simple.client)
-medium simpletexture screenshot pdiff_threshold(300)
-medium skinning screenshot pdiff_threshold(200)
-medium sobel screenshot pdiff_threshold(1400)
-medium stencil_example screenshot(0) screenshot(100) screenshot(7777) pdiff_threshold(200) pdiff_threshold_win(200)
-medium shadow-map screenshot pdiff_threshold(200)
-small texturesamplers screenshot pdiff_threshold_win(1200) pdiff_threshold_mac(32200)
-medium tutorial-primitive screenshot pdiff_threshold(200) pdiff_threshold_mac(10400)
-large vertex-shader screenshot timeout(45000) pdiff_threshold(200) except(*iexplore)
-medium vertex-shader-animation screenshot pdiff_threshold(200)
-medium zsorting screenshot(9) pdiff_threshold_win(200) pdiff_threshold_mac(39500)
-# box2d-3d works in browsers but for some reason times out on some configs
-#large box2d-3d/box2d-3d timeout(45000) except(*googlechrome)
-large simpleviewer/simpleviewer screenshot pdiff_threshold(100)
-large trends/trends timeout(30000)
-medium GoogleIO-2009/step09ex screenshot pdiff_threshold(200)
-large GoogleIO-2009/step14ex screenshot pdiff_threshold(200) timeout(45000) downsample(1)
-
-# -- tests below this line are tests for which there is a python
-# function to custom run the test. As such, only the 'except' and
-# pdiff_threshold options have any meaning
-
-small TestSampleErrorTextureSmall pdiff_threshold(200) screenshots(5)
-small TestSampleHelloCube_TexturesSmall pdiff_threshold(450) screenshot
-# IE and chrome hang on this test.
-small TestSampleRefreshPageLoad_Small except(*iexplore,*googlechrome)
-medium TestSampleCustomCamera pdiff_threshold(200) pdiff_threshold_win(200) screenshot run_time(180000)
-medium TestSamplePicking run_time(60000)
-medium TestSampleRenderMode run_time(60000)
-medium TestSampleRotateModel pdiff_threshold(200) screenshots(2) run_time(100000)
-medium TestSampleShader_Test pdiff_threshold(200) pdiff_threshold_win(200) screenshots(13)
-# IE takes several minutes just loading this test.
-large TestSampleMultipleClientsLarge run_time(180000) except(*iexplore)
-large TestSamplePingPongLarge
-# This test currently fails on IE as it considers localhost: to be a trusted
-# domain.
-# Do not run this test until get rid of scons. It assumes a particular
-# directory structure to find an asset. Need to change to reflect new gyp
-# directory structure. Should be changed when scons is gone.
-#small TestLoadTextureFromFileSmall except(*iexplore)
diff --git a/o3d/tests/selenium/samples_tests.py b/o3d/tests/selenium/samples_tests.py
deleted file mode 100644
index 7e993b1..0000000
--- a/o3d/tests/selenium/samples_tests.py
+++ /dev/null
@@ -1,527 +0,0 @@
-#!/usr/bin/python2.4
-# 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.
-
-
-"""Selenium tests on the o3d samples.
-
-Checks for javascript errors and compares screenshots
-taken with reference images.
-
-NOTE: If you manually write a test in python (vs using the generic test)
-The name of the screenshots must match the name of the test not including
-the suffix. In otherwords, if your test is called TestSampleCustomCameraMedium
-then your screenshots need to be named customcamera1, customcamera2 etc.
-
-This is so when it comes time to compare screenshots we can figure out which
-reference images require a corresponding screenshot. In other words if
-TestSampleCustomCameraMedium is run then we know that any reference file
-named customcamera1_reference.png requires that there be a corresponding
-screenshot.
-"""
-
-
-import os
-import time
-import gflags
-import selenium_utilities
-
-
-class SampleTests(selenium_utilities.SeleniumTestCase):
- """Tests a couple of samples in the o3d samples directory."""
-
- # TODO: Change to correct object class when NPAPI class is exposed.
- SELENIUM_OBJ_TYPE = "[object HTMLObjectElement]"
-
- def __init__(self, name, browser, path_to_html, test_type=None,
- sample_path=None, options=None):
- selenium_utilities.SeleniumTestCase.__init__(
- self, name, browser, path_to_html, test_type, sample_path,
- options)
-
- def GenericTest(self):
- """Generically test a sample.
-
- Each sample is expected to have a global variable called g_finished
- which is set to true when it is finished initializing and is in a state
- ready for a screenshot.
- """
- self.RunGenericTest(
- "/samples/",
- "(typeof(window.g_finished) != 'undefined') && "
- "window.g_finished == true;",
- None)
-
- def AssertEqualMatrix4(self, matrix1, matrix2):
- """Compares two 4-by-4 matrices.
-
- It asserts that their entries are each very close.
- Args:
- matrix1: Full DOM path to first matrix in javascript.
- matrix2: Full DOM path to second matrix in javascript.
- """
- # Alias for the selenium session
- s = self.session
- mat1_values = s.get_eval(matrix1 + '.toString()').split(',')
- mat2_values = s.get_eval(matrix2 + '.toString()').split(',')
-
- self.assertTrue(len(mat1_values) == 16)
- self.assertTrue(len(mat2_values) == 16)
- for i in range(len(mat1_values)):
- a = float(mat1_values[i])
- b = float(mat2_values[i])
- self.assertTrue(abs(a - b) < 0.001)
-
- def TestSampleRotateModel(self):
- """Tests rotatemodel.html."""
-
- # Alias for the selenium session
- s = self.session
- s.open(self.GetURL("/samples/rotatemodel.html"))
-
- # wait for sample to be ready.
- s.wait_for_condition("(typeof(window.g_finished) != 'undefined') && "
- "window.g_finished == true;", 50000)
-
- # Capture screenshot
- self.assertTrue(selenium_utilities.TakeScreenShot(s, self.browser,
- "g_client",
- "rotatemodel1"))
-
- # Check that local matrix is the identity
- self.AssertEqualMatrix4("window.g_math.matrix4.identity()",
- "window.g_sceneRoot.localMatrix")
-
- # TODO: s.key_press is not functioning on Chrome, so we revert
- # to button-based testing of the rotation functions on this platform.
- # Remove this test when chrome keyboard input works in selenium.
- browser_is_chrome = self.browser == "*googlechrome"
-
- # Rotate slightly
- if browser_is_chrome:
- s.click("A")
- else:
- s.key_press("document.getElementById('o3d')", "a")
-
- # Check that rotation matrix is correct
- self.AssertEqualMatrix4(
- "window.g_math.matrix4.rotationZYX([0, -0.05, 0])",
- "window.g_sceneRoot.localMatrix")
-
- # Rotate model
- for unused_i in range(1, 10):
- if browser_is_chrome:
- s.click("W")
- else:
- s.key_press("document.getElementById('o3d')", "w")
-
- for unused_i in range(1, 5):
- if browser_is_chrome:
- s.click("S")
- else:
- s.key_press("document.getElementById('o3d')", "s")
-
- for unused_i in range(1, 5):
- if browser_is_chrome:
- s.click("A")
- else:
- s.key_press("document.getElementById('o3d')", "a")
-
- for unused_i in range(1, 10):
- if browser_is_chrome:
- s.click("D")
- else:
- s.key_press("document.getElementById('o3d')", "d")
-
- # Capture screenshot
- self.assertTrue(selenium_utilities.TakeScreenShot(s, self.browser,
- "g_client",
- "rotatemodel2"))
-
- # Reset view
- s.click("//input[@value='Reset view']")
-
- def TestSampleCustomCamera(self):
- """Tests customcamera.html."""
-
- # Alias for the selenium session
- s = self.session
- s.open(self.GetURL("/samples/customcamera.html"))
-
- # Allow a limited time for the plugin to initialize.
- s.wait_for_condition("typeof(window.g_client) != 'undefined';", 10000)
-
- # Sanity checks.
- self.assertEqual("Tutorial B4: Cameras and events", s.get_title())
- self.assertEqual("null", s.get_eval("window.undefined_symbol_xxxyyy"))
-
- # Try different views of the camera.
- # Set delay between each operation at 100ms. This is needed for some
- # versions of IE and Chrome.
- speed = int(s.get_speed())
- s.set_speed(100)
- s.type("eyeX", "5")
- s.type("eyeY", "5")
- s.type("eyeZ", "5")
- s.click("btnSet")
-
- s.type("eyeX", "2")
- s.type("eyeY", "3")
- s.type("eyeZ", "2")
- s.type("upX", "1")
- s.type("upY", "0")
- s.click("btnSet")
- # Reset delay to previous value.
- s.set_speed(speed)
-
- # Capture screenshot
- self.assertTrue(selenium_utilities.TakeScreenShot(s, self.browser,
- "g_client",
- "customcamera1"))
-
- # Reset view
- s.click("btnDefault")
-
- def TestSampleRenderMode(self):
- """Tests render-mode.html."""
-
- # Alias for the selenium session
- s = self.session
- s.open(self.GetURL("/samples/render-mode.html"))
-
- # Allow a limited time for the plugin to initialize.
- s.wait_for_condition("typeof(window.g_client) != 'undefined';", 10000)
-
- # Sanity checks.
- self.assertEqual("Render Mode Example.", s.get_title())
- self.assertEqual("null", s.get_eval("window.undefined_symbol_xxxyyy"))
- s.wait_for_condition("window.g_client != null", 5000)
-
- # Wait for it to render a few frames.
- s.wait_for_condition(
- "window.g_framesRendered > 10",
- 5000)
-
- # stop rendering
- s.click("//input[@value='ondemand']")
-
- # reset frame count to 0
- s.run_script("window.g_framesRendered = 0")
-
- # wait 1 second
- time.sleep(1)
-
- # check that we didn't render much. Note: This is a kind of hacky
- # check because if something else (the window being covered/unconvered)
- # causes the window to be refreshed this number is unpredictable. Also,
- # if the window is covered we don't render so that can effect this test
- # as well. The hope is since we waiting 1 second it should render 30-60
- # frames if render mode is not working.
- self.assertTrue(
- s.get_eval("window.g_framesRendered < 10"))
-
- def TestSamplePicking(self):
- """Tests picking.html."""
-
- # Alias for the selenium session
- s = self.session
- s.open(self.GetURL("/samples/picking.html"))
-
- # wait for sample to be ready.
- s.wait_for_condition("(typeof(window.g_finished) != 'undefined') && "
- "window.g_finished == true;", 50000)
-
- # Sanity checks.
- self.assertEqual("O3D Picking Example.", s.get_title())
-
- pick_info = [{"x": 189, "y": 174, "shape": "pConeShape1"},
- {"x": 191, "y": 388, "shape": "pTorusShape1"},
- {"x": 459, "y": 365, "shape": "pPipeShape1"},
- {"x": 466, "y": 406, "shape": "pCubeShape1"}]
-
- # if it's not working these will timeout.
- for record in pick_info:
- # Selenium can't really click the mouse; it can only tell JavaScript that
- # the mouse has been clicked, which isn't enough to get an OS-level event
- # into the plugin. So we go around the plugin and just call the event
- # handler that it would have called. This means we're testing most of the
- # code in the sample, but not the actual event path.
- s.get_eval("window.pick({x:%d,y:%d});" % (record["x"], record["y"]))
- s.wait_for_condition(
- "window.g_pickInfoElem.innerHTML == '" + record["shape"] + "'",
- 10000)
-
- def TestSampleShader_Test(self):
- """Tests shader-test.html."""
-
- # Alias for the selenium session
- s = self.session
- s.open(self.GetURL("/samples/shader-test.html"))
-
- # Allow a limited time for the plugin to initialize.
- s.wait_for_condition("typeof(window.g_client) != 'undefined';", 20000)
-
- # Sanity checks.
- self.assertEqual("Shader Test", s.get_title())
- self.assertEqual("null", s.get_eval("window.undefined_symbol_xxxyyy"))
-
- # wait for it to initialize.
- s.wait_for_condition("(typeof(window.g_finished) != 'undefined') && "
- "window.g_finished == true;",
- 20000)
-
- # if they are animated we need to stop the animation and set the clock
- # to some time so we get a known state.
- s.run_script("g_timeMult = 0")
- s.run_script("g_clock = 27.5")
-
- # Figure out how many options there are.
- num_shaders = s.get_eval(
- "window.document.getElementById('shaderSelect').length")
-
- # try each shader
- for shader in range(0, int(num_shaders)):
- # select shader
- s.select("//select[@id='shaderSelect']", ("index=%d" % shader))
- # Take screenshot
- self.assertTrue(selenium_utilities.TakeScreenShot(
- s, self.browser, "g_client", "shader-test%d" % (shader + 1)))
-
- def TestSampleErrorTextureSmall(self):
- """Tests error-texture.html."""
-
- # Alias for the selenium session
- s = self.session
- s.open(self.GetURL("/samples/error-texture.html"))
-
- # Allow a limited time for the plugin to initialize.
- s.wait_for_condition("typeof(window.g_client) != 'undefined';", 30000)
-
- # Sanity checks.
- self.assertEqual("Error Texture", s.get_title())
- self.assertEqual("null", s.get_eval("window.undefined_symbol_xxxyyy"))
-
- # Take screenshots
- time.sleep(2) # helps with Vista FF screencapture
- self.assertTrue(selenium_utilities.TakeScreenShot(s, self.browser,
- "g_client",
- "errortexture1"))
- s.click("//input[@value='User Texture']")
- s.wait_for_condition("(window.g_errorMsgElement.innerHTML=='-');",
- 1000)
- time.sleep(2) # helps with Vista FF screencapture
- self.assertTrue(selenium_utilities.TakeScreenShot(s, self.browser,
- "g_client",
- "errortexture2"))
- s.click("//input[@value='No Texture']")
- s.wait_for_condition("(window.g_errorMsgElement.innerHTML=="
- "'Missing texture for sampler s2d');",
- 1000)
- self.assertTrue(selenium_utilities.TakeScreenShot(s, self.browser,
- "g_client",
- "errortexture3"))
- s.click("//input[@value='hide 0']")
- s.wait_for_condition("(window.g_errorMsgElement.innerHTML=="
- "'Missing Sampler for ParamSampler texSampler0');",
- 1000)
- self.assertTrue(selenium_utilities.TakeScreenShot(s, self.browser,
- "g_client",
- "errortexture4"))
- s.click("//input[@value='hide 1']")
- s.wait_for_condition("(window.g_errorMsgElement.innerHTML=="
- "'Missing ParamSampler');",
- 1000)
- self.assertTrue(selenium_utilities.TakeScreenShot(s, self.browser,
- "g_client",
- "errortexture5"))
-
- def TestSampleMultipleClientsLarge(self):
- """Tries to draw a simple example in a large number of clients."""
-
- # Alias for the selenium session
- s = self.session
- s.open(self.GetURL("/samples/multiple-clients.html"))
-
- # Allow a limited time for the plugin to initialize. We spot-check the
- # first and last here to make sure the page has basically loaded. Before we
- # access any plugin data, we'll check each individual client.
- s.wait_for_condition("typeof(window.g_clients[49]) != 'undefined';", 40000)
-
- # Sanity checks.
- self.assertEqual("Multiple Clients", s.get_title())
- self.assertEqual("null", s.get_eval("window.undefined_symbol_xxxyyy"))
-
- # Wait until the entire setup is finished.
- s.wait_for_condition("window.g_setupDone == true;", 5000)
-
- # Spot-check assets for base o3d setup:
- for index in range(0, 50, 12):
- client_string = (
- "window.document.getElementById('o3d%d').client" % index)
-
- # Make sure this client is ready for us.
- s.wait_for_condition(client_string + " != null;", 1000)
- s.wait_for_condition(client_string + ".root != null;", 1000)
-
- # There are 1 draw elements:
- self.assertEqual(
- "1",
- s.get_eval(client_string +
- ".getObjectsByClassName('o3d.DrawElement').length"))
-
- # There are 8 nodes in the render graph.
- # 1 root render node
- # 1 viewport
- # 1 clear buffer
- # 1 tree traversal
- # 2 draw passes
- # 2 StateSets
- self.assertEqual(
- "8",
- s.get_eval(client_string + ".renderGraphRoot."
- "getRenderNodesInTree().length"))
-
- def TestSamplePingPongLarge(self):
- """Validates the start-up logic of the ping-pong sample."""
-
- # Alias for the selenium session
- s = self.session
- s.open(self.GetURL("/samples/pingpong/o3dPingPong.html"))
-
- # Sanity checks.
- self.assertEqual("o3dPingPong", s.get_title())
- self.assertEqual("null", s.get_eval("window.undefined_symbol_xxxyyy"))
-
- # Start the game
- s.click("clientBanner")
-
- # Allow a limited time for the plugin to initialize.
- s.wait_for_condition("(typeof(window.g_finished) != 'undefined') && "
- "window.g_finished == true;", 10000)
-
- def TestSampleHelloCube_TexturesSmall(self):
- """Validates loading of files from an external source."""
-
- # Alias for the selenium session
- s = self.session
- s.open(self.GetURL("/samples/hellocube-textures.html"))
-
- # Sanity checks.
- self.assertEqual(
- "Hello Square Textures: Getting started with O3D, take 3.",
- s.get_title())
- self.assertEqual("null", s.get_eval("window.undefined_symbol_xxxyyy"))
-
- # Allow a limited time for the plugin to initialize.
- s.wait_for_condition("(typeof(window.g_finished) != 'undefined') && "
- "window.g_finished == true;", 10000)
-
- # if they are animated we need to stop the animation and set the clock
- # to some time so we get a known state.
- s.run_script("g_timeMult = 0")
- s.run_script("g_clock = 27.5")
-
- # Take screenshot
- self.assertTrue(selenium_utilities.TakeScreenShot(
- s,
- self.browser,
- "g_client",
- "hellocube-textures1"))
-
- def TestLoadTextureFromFileSmall(self):
- """Checks for improper access to local files."""
-
- # Alias for the selenium session.
- s = self.session
- s.open(self.GetURL("/samples/hellocube-textures.html"))
-
- # Sanity checks.
- self.assertEqual(
- "Hello Square Textures: Getting started with O3D, take 3.",
- s.get_title())
- self.assertEqual("null", s.get_eval("window.undefined_symbol_xxxyyy"))
-
- # Allow a limited time for the plugin to initialize.
- s.wait_for_condition("(typeof(window.g_finished) != 'undefined') && "
- "window.g_finished == true;", 10000)
-
- # Check that loading from a local file fails, when the page is served over
- # http.
- existing_image = os.path.abspath(
- os.path.join(os.path.dirname(__file__),
- "..",
- "..",
- "samples",
- "assets",
- "google-square.png"))
-
- self.assertTrue(os.path.exists(existing_image))
- s.type("url", "file://%s" % existing_image)
- s.click("updateButton")
-
- s.wait_for_condition(
- "(typeof(window.g_textureLoadDenied) != 'undefined') && "
- "window.g_textureLoadDenied == true;", 10000)
-
- def TestSampleRefreshPageLoad_Small(self):
- """Tests the behaviour of the plug-in and browser when the page is
- refreshed before all of the O3D streams have loaded.
- """
-
- # Alias for the selenium session
- s = self.session
- s.open(self.GetURL("/samples/archive-textures.html"))
-
- # Allow a limited time for the plugin to initialize.
- s.wait_for_condition("typeof(window.g_client) != 'undefined';", 10000)
-
- # Instruct the page to continually download content.
- s.run_script("window.g_repeatDownload = true")
- s.click("startLoad")
-
- # Wait for the browser to load the page.
- s.wait_for_condition(
- "(typeof(window.g_streamingStarted) != 'undefined')", 10000)
-
- # Refresh the page, before waiting for all of the textures to be loaded.
- # This tests that the browser won't hang while processing the
- # no-longer-needed streams.
- s.open(self.GetURL("/samples/archive-textures.html"))
-
- # Allow a limited time for the plugin to initialize.
- s.wait_for_condition("typeof(window.g_client) != 'undefined';", 10000)
-
- # Instruct the page to download the tgz file once.
- s.click("startLoad")
-
- s.wait_for_condition("(typeof(window.g_finished) != 'undefined') && "
- "window.g_finished == true;", 20000)
-
-if __name__ == "__main__":
- pass
diff --git a/o3d/tests/selenium/selenium.gyp b/o3d/tests/selenium/selenium.gyp
deleted file mode 100644
index 15576b58..0000000
--- a/o3d/tests/selenium/selenium.gyp
+++ /dev/null
@@ -1,281 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- 'selenium_args': [
- '--referencedir=<(screenshotsdir)',
- '--product_dir=<(PRODUCT_DIR)',
- '--screencompare=<(PRODUCT_DIR)/perceptualdiff<(EXECUTABLE_SUFFIX)',
- # We only want to include selenium_ie and register host
- # if the user is admin.
- ],
- 'is_admin': '<!(python ../../build/is_admin.py)',
- },
- 'includes': [
- '../../build/common.gypi',
- ],
- 'targets': [
- {
- 'target_name': 'install_selenium_tests',
- 'type': 'none',
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)/tests/selenium/tests',
- 'files': [
- 'tests/base-test.html',
- 'tests/culling-zsort-test.html',
- 'tests/drawshapes.html',
- 'tests/effect-import-test.html',
- 'tests/event-test.html',
- 'tests/features-test.html',
- 'tests/init-status-test.html',
- 'tests/math-test.html',
- 'tests/no-rendergraph.html',
- 'tests/non-cachable-params.html',
- 'tests/offscreen-test.html',
- 'tests/ownership-test.html',
- 'tests/param-array-test.html',
- 'tests/pixel-perfection.html',
- 'tests/quaternion-test.html',
- 'tests/render-test.html',
- 'tests/render-target-clear-test.html',
- 'tests/serialization-test.html',
- 'tests/test-test.html',
- 'tests/texture-set-test.html',
- 'tests/type-test.html',
- 'tests/util-test.html',
- 'tests/v8-test.html',
- 'tests/version-check-test.html',
- 'tests/window-overlap-test.html',
- 'tests/window-overlap-top.html',
- ],
- },
- {
- 'destination': '<(PRODUCT_DIR)/tests/selenium/tests/assets',
- 'files': [
- 'tests/assets/archive.o3dtgz',
- ],
- },
- ]
- },
- {
- 'target_name': 'selenium_firefox',
- 'type': 'none',
- 'dependencies': [
- 'install_selenium_tests',
- '../tests.gyp:unit_tests',
- '../../plugin/plugin.gyp:npo3dautoplugin',
- ],
- 'scons_propagate_variables': [
- 'HOME',
- 'DISPLAY',
- 'XAUTHORITY',
- ],
- 'run_as': {
- 'working_directory': '<(DEPTH)',
- 'action': [
- 'python<(EXECUTABLE_SUFFIX)',
- 'o3d/tests/selenium/main.py',
- '<@(selenium_args)',
- '--browserpath=<(browser_path)',
- '--browser=*firefox',
- '--screenshotsdir=<(PRODUCT_DIR)/tests/selenium/screenshots_firefox',
- ],
- },
- 'conditions': [
- ['OS=="win"',
- {
- 'variables': {
- 'browser_path': '',
- },
- }
- ],
- ['OS=="linux"',
- {
- 'variables': {
- 'browser_path': '',
- },
- },
- ],
- ['OS=="mac"',
- {
- 'dependencies': [
- 'unpack_firefox',
- ],
- 'variables': {
- 'browser_path': '<(PRODUCT_DIR)/selenium_firefox/Firefox.app/Contents/MacOS/firefox-bin',
- },
- },
- ],
- ],
- },
- {
- 'target_name': 'selenium_chrome',
- 'type': 'none',
- 'dependencies': [
- 'install_selenium_tests',
- '../tests.gyp:unit_tests',
- '../../plugin/plugin.gyp:npo3dautoplugin',
- ],
- 'scons_propagate_variables': [
- 'HOME',
- 'DISPLAY',
- 'XAUTHORITY',
- ],
- 'run_as': {
- 'action': [
- 'python<(EXECUTABLE_SUFFIX)',
- 'main.py',
- '<@(selenium_args)',
- '--browserpath=<(browser_path)',
- '--browser=*googlechrome',
- '--screenshotsdir=<(PRODUCT_DIR)/tests/selenium/screenshots_chrome',
- ],
- },
- 'conditions': [
- ['OS=="win"',
- {
- 'variables': {
- 'browser_path': '',
- },
- }
- ],
- ['OS=="linux"',
- {
- 'variables': {
- 'browser_path': '/usr/bin/google-chrome',
- },
- },
- ],
- ['OS=="mac"',
- {
- 'variables': {
- 'browser_path': 'mac_chrome.sh',
- },
- },
- ],
- ],
- },
- ],
- 'conditions': [
- ['<(selenium_screenshots) == 1',
- {
- 'variables': {
- 'selenium_args': [
- '--screenshots',
- ],
- },
- },
- ],
- ['OS=="mac"',
- {
- 'targets': [
- {
- 'target_name': 'unpack_firefox',
- 'type': 'none',
- 'dependencies': [
- '../../plugin/plugin.gyp:npo3dautoplugin',
- ],
- 'variables': {
- 'plugin_npapi_filename%': 'O3D',
- },
- 'actions': [
- {
- 'action_name': 'unpack_firefox',
- 'inputs': [
- '<(PRODUCT_DIR)/<(plugin_npapi_filename).plugin',
- ],
- 'outputs': [
- '<(PRODUCT_DIR)/selenium_firefox',
- ],
- 'action': [
- 'python',
- 'unpack_firefox.py',
- '--plugin_path=<(PRODUCT_DIR)/<(plugin_npapi_filename).plugin',
- '--product_path=<(PRODUCT_DIR)',
- ],
- },
- ],
- },
- {
- 'target_name': 'selenium_safari',
- 'type': 'none',
- 'dependencies': [
- 'install_selenium_tests',
- '../tests.gyp:unit_tests',
- '../../plugin/plugin.gyp:npo3dautoplugin',
- ],
- 'run_as': {
- 'action': [
- 'python<(EXECUTABLE_SUFFIX)',
- 'main.py',
- '<@(selenium_args)',
- '--browser=*safari',
- '--screenshotsdir=<(PRODUCT_DIR)/tests/selenium/screenshots_safari',
- ],
- },
- },
- ],
- },
- ],
- ['OS=="win" and "<(is_admin)"=="True"',
- {
- 'targets': [
- {
- 'target_name': 'selenium_ie',
- 'type': 'none',
- 'dependencies': [
- 'install_selenium_tests',
- '../tests.gyp:unit_tests',
- '../../plugin/plugin.gyp:npo3dautoplugin',
- '../../plugin/plugin.gyp:o3d_host',
- #'o3d_host_register',
- ],
- 'run_as': {
- 'action': [
- 'python<(EXECUTABLE_SUFFIX)',
- 'main.py',
- '<@(selenium_args)',
- '--servertimeout=80',
- '--browser=*iexplore',
- '--screenshotsdir=<(PRODUCT_DIR)/tests/selenium/screenshots_ie',
- ],
- },
- },
- {
- 'target_name': 'o3d_host_register',
- 'type': 'none',
- 'dependencies': [
- '../../plugin/plugin.gyp:o3d_host',
- ],
- 'actions': [
- {
- 'action_name': 'register_o3d_host',
- 'inputs': [
- '<(PRODUCT_DIR)/o3d_host.dll',
- ],
- 'outputs': [
- 'file_that_never_exists_so_this_action_always_runs',
- ],
- 'action': [
- 'regsvr32',
- '/s',
- '<(_inputs)',
- ],
- },
- ],
- },
- ],
- },
- ],
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/tests/selenium/selenium_constants.py b/o3d/tests/selenium/selenium_constants.py
deleted file mode 100644
index ad2b166..0000000
--- a/o3d/tests/selenium/selenium_constants.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python2.4
-# 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.
-
-
-"""Constants for the selenium scripts.
-
-Variables that are shared across all the selenium scripts.
-"""
-
-
-import os
-import sys
-
-script_dir = os.path.normpath(os.path.dirname(os.path.abspath(__file__)))
-o3d_dir = os.path.dirname(os.path.dirname(script_dir))
-
-# Default path where screenshots will be stored.
-DEFAULT_SCREENSHOT_PATH = os.path.join(o3d_dir,
- "tests",
- "selenium",
- "screenshots")
-
-# Path where reference screenshots will be stored.
-# Unfortunately we need separate reference images for certain platforms
-# for certain tests.
-DEFAULT_SCREENSHOT_DIR = "reference"
-if sys.platform == "darwin":
- PLATFORM_SCREENSHOT_DIR = "reference-mac"
-elif sys.platform[:5] == "linux":
- PLATFORM_SCREENSHOT_DIR = "reference-linux"
-elif sys.platform == "win32" or sys.platform == "cygwin":
- PLATFORM_SCREENSHOT_DIR = "reference-win"
-else:
- raise Exception, 'Platform %s not supported' % sys.platform
-
-
-
-SELENIUM_BROWSER_SET = ["*iexplore", "*firefox", "*googlechrome", "*safari"]
-
-# Dimensions to resize window to
-# on the Mac, the window has to be big enough to hold the entire o3d div
-# otherwise the OpenGL context will be clipped to the size of the window
-RESIZE_WIDTH = 1400
-RESIZE_HEIGHT = 1200
diff --git a/o3d/tests/selenium/selenium_utilities.py b/o3d/tests/selenium/selenium_utilities.py
deleted file mode 100644
index 7c23ca9..0000000
--- a/o3d/tests/selenium/selenium_utilities.py
+++ /dev/null
@@ -1,354 +0,0 @@
-#!/usr/bin/python2.4
-# 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.
-
-
-"""Utility scripts for selenium.
-
-A collection of utility scripts for selenium test cases to use.
-"""
-
-
-import os
-import re
-import time
-import unittest
-import base64
-import gflags
-import selenium_constants
-
-
-FLAGS = gflags.FLAGS
-SUFFIXES = ["small", "medium", "large"]
-
-
-def IsValidTestType(test_type):
- """Returns True if test_type is a "small", "medium" or "large"."""
- return test_type.lower() in SUFFIXES
-
-
-def IsValidSuffix(name):
- """Returns True if name ends in a valid test type."""
- name = name.lower()
- for suffix in SUFFIXES:
- if name.endswith(suffix):
- return True
- return False
-
-def ScreenshotNameFromTestName(name):
- name = StripTestTypeSuffix(name)
-
- if name.startswith("Test"):
- # Make sure these are in order.
- prefixes = ["TestStress", "TestSample", "Test"]
- for prefix in prefixes:
- if name.startswith(prefix):
- name = name[len(prefix):]
- break
-
- # Lowercase the name only for custom test methods.
- name = name.lower()
-
- name = name.replace("_", "-")
- name = name.replace("/", "_")
-
- return name
-
-
-def StripTestTypeSuffix(name):
- """Removes the suffix from name if it is a valid test type."""
- name_lower = name.lower()
- for suffix in SUFFIXES:
- if name_lower.endswith(suffix):
- return name[:-len(suffix)]
- return name
-
-
-def GetArgument(string):
- """Returns the value inside the first set of parentheses in a string.
-
- Args:
- string: String in the format "identifier(args)"
-
- Returns:
- args from string passed in. None if there were no parentheses.
- """
- match = re.match("\w+\(([^)]+)\)", string)
- if match:
- return match.group(1)
- return None
-
-
-def TakeScreenShot(session, browser, client, filename):
- """Takes a screenshot of the o3d display buffer.
-
- This function is the preferred way to capture an image of the plugin.
-
- Uses gflags:
- If gflags.FLAGS.screenshots is False then screen shots will not be taken.
- gflags.FLAGS.screenshotsdir must be set to the path to save screenshots in.
-
- Args:
- session: Selenium session.
- browser: Name of the browser running the test.
- client: String that in javascript will return the o3d client.
- filename: Name of screenshot.
- Returns:
- success: True on success, False on failure.
- """
- # If screenshots enabled
- if gflags.FLAGS.screenshots:
- full_path = os.path.join(os.getcwd(),
- FLAGS.screenshotsdir,
- filename)
- return TakeScreenShotAtPath(session,
- browser,
- client,
- full_path)
- else:
- # Screenshots not enabled, return true (success).
- return True
-
-
-def TakeScreenShotAtPath(session,
- browser,
- client,
- filename):
- """Takes a screenshot of the o3d display buffer.
-
- This should be used by tests that need to specify exactly where to save the
- image or don't want to use gflags.
-
- Args:
- session: Selenium session.
- browser: Name of the browser running the test.
- client: String that in javascript will return the o3d client.
- filename: Full path to screenshot to be saved.
-
- Returns:
- success: True on success, False on failure.
- """
- session.window_focus()
-
- # Resize window, and client area if needed.
- session.run_script(
- "(function() {\n"
- " var needResize = false;\n"
- " var divs = window.document.getElementsByTagName('div');\n"
- " for (var ii = 0; ii < divs.length; ++ii) {\n"
- " var div = divs[ii];\n"
- " if (div.id && div.id == 'o3d') {\n"
- " var widthSpec = div.style.width;\n"
- " if (widthSpec.indexOf('%') >= 0) {\n"
- " div.style.width = '800px';\n"
- " div.style.height = '600px';\n"
- " needResize = true;\n"
- " break;\n"
- " }\n"
- " }\n"
- " }\n"
- " window.o3d_seleniumNeedResize = needResize;\n"
- "} ());\n")
-
- need_client_resize = (
- session.get_eval("window.o3d_seleniumNeedResize") == "true")
- if need_client_resize:
- session.wait_for_condition(
- "window.%s.width == 800 && window.%s.height == 600" % (client, client),
- 20000)
- else:
- session.run_script("window.resizeTo(%d, %d)" %
- (selenium_constants.RESIZE_WIDTH,
- selenium_constants.RESIZE_HEIGHT))
-
- # Execute screenshot capture code
-
- # Replace all backslashes with forward slashes so it is parsed correctly
- # by Javascript
- full_path = filename.replace("\\", "/")
-
- # Attempt to take a screenshot of the display buffer
- eval_string = ("%s.toDataURL()" % client)
-
-
- # Set Post render call back to take screenshot
- script = ["window.g_selenium_post_render = false;",
- "window.g_selenium_save_screen_result = false;",
- "var frameCount = 0;",
- "%s.setPostRenderCallback(function() {" % client,
- " ++frameCount;",
- " if (frameCount >= 3) {",
- " %s.clearPostRenderCallback();" % client,
- " window.g_selenium_save_screen_result = %s;" % eval_string,
- " window.g_selenium_post_render = true;",
- " } else {",
- " %s.render()" % client,
- " }",
- "})",
- "%s.render()" % client]
- session.run_script("\n".join(script))
- # Wait for screenshot to be taken.
- session.wait_for_condition("window.g_selenium_post_render", 20000)
-
- # Get result
- data_url = session.get_eval("window.g_selenium_save_screen_result")
- expected_header = "data:image/png;base64,"
- if data_url.startswith(expected_header):
- png = base64.b64decode(data_url[len(expected_header):])
- file = open(full_path + ".png", 'wb')
- file.write(png)
- file.close()
- return True
-
- return False
-
-
-class SeleniumTestCase(unittest.TestCase):
- """Wrapper for TestCase for selenium."""
-
- def __init__(self, name, browser, path_to_html, test_type=None,
- sample_path=None, options=None):
- """Constructor for SampleTests.
-
- Args:
- name: Name of unit test.
- session: Selenium session.
- browser: Name of browser.
- path_to_html: path to html from server root
- test_type: Type of test ("small", "medium", "large")
- sample_path: Path to test.
- load_timeout: Time to wait for page to load (ms).
- run_timeout: Time to wait for test to run.
- options: list of option strings.
- """
-
- unittest.TestCase.__init__(self, name)
- self.name = name
- self.session = None
- self.browser = browser
- self.test_type = test_type
- self.sample_path = sample_path
- self.path_to_html = path_to_html
- self.screenshots = []
- self.load_timeout = 10000
- self.run_timeout = None
- self.client = "g_client"
- # parse options
- for option in options:
- if option.startswith("screenshots"):
- for i in range(int(GetArgument(option))):
- self.screenshots.append("27.5")
- elif option.startswith("screenshot"):
- clock = GetArgument(option)
- if clock is None:
- clock = "27.5"
- self.screenshots.append(clock)
- elif option.startswith("timeout"):
- self.load_timeout = int(GetArgument(option))
- elif option.startswith("client"):
- self.client = GetArgument(option)
- elif option.startswith("run_time"):
- self.run_timeout = int(GetArgument(option))
-
- if self.run_timeout is None:
- # Estimate how long this test needs to run.
- time_per_screenshot = 10000
- if browser == "*iexplore":
- time_per_screenshot = 60000
- self.run_timeout = 25000 + len(self.screenshots) * time_per_screenshot
-
- def SetSession(self, session):
- self.session = session
-
- def GetTestTimeout(self):
- return self.load_timeout + self.run_timeout
-
- def GetURL(self, url):
- """Gets a URL for the test."""
- return self.session.browserURL + self.path_to_html + url
-
- def shortDescription(self):
- """override unittest.TestCase shortDescription for our own descriptions."""
- if self.sample_path:
- return "Testing: " + self.sample_path + ".html"
- else:
- return unittest.TestCase.shortDescription(self)
-
- def RunGenericTest(self, base_path, ready_condition, assertion):
- """Runs a generic test.
-
- Args:
- base_path: path for sample.
- ready_condition: condition to check in javascript to know sample is ready.
- assertion: javascript to check equals "true"
-
- Assumes self.sample_path is a path to the html page to load and that
- samples.options is an array of option strings.
-
- If the sample is animated, it is expected to have a global variable
- called g_timeMult that can be set to 0 to stop the animation. All of its
- animation must be based on a global variable called g_clock, such that
- setting g_clock to the same value will always produce the same image.
-
- Finally, each sample is expected to have a global variable called
- g_client which is the o3d client object for that sample. This is
- used to take a screenshot.
- """
- self.assertTrue(not self.load_timeout is None)
- self.assertTrue(not self.client is None)
- self.assertTrue(self.test_type in ["small", "medium", "large"])
-
- url = self.GetURL(base_path + self.sample_path + ".html")
-
- # load the sample.
- self.session.open(url)
-
- # wait for it to initialize.
- self.session.wait_for_condition(ready_condition, self.load_timeout)
-
- self.session.run_script(
- "if (window.o3d_prepForSelenium) { window.o3d_prepForSelenium(); }")
-
- if assertion:
- self.assertEqual("true", self.session.get_eval(assertion))
-
- # take a screenshot.
- screenshot_id = 1
- for clock in self.screenshots:
- # if they are animated we need to stop the animation and set the clock
- # to some time so we get a known state.
- self.session.run_script("g_timeMult = 0")
- self.session.run_script("g_clock = " + clock)
-
- # take a screenshot.
- screenshot = self.sample_path.replace("_", "-").replace("/", "_")
- screenshot += str(screenshot_id)
- self.assertTrue(TakeScreenShot(self.session, self.browser,
- self.client, screenshot))
- screenshot_id += 1
diff --git a/o3d/tests/selenium/test_runner.py b/o3d/tests/selenium/test_runner.py
deleted file mode 100644
index 458b4a5..0000000
--- a/o3d/tests/selenium/test_runner.py
+++ /dev/null
@@ -1,412 +0,0 @@
-#!/usr/bin/python2.4
-# 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.
-
-
-"""Test runners and associated classes.
-
-Each test runner has its own thread, which attempts to perform a given test.
-If a test hangs, the test runner can be aborted or exited.
-
-"""
-
-import os
-import sys
-
-import socket
-import subprocess
-import threading
-import time
-import unittest
-import gflags
-import selenium
-import selenium_constants
-import Queue
-import thread
-import copy
-
-class StringBuffer:
- """Primitive string buffer.
-
- Members:
- data: the contents of the buffer
- """
- def __init__(self):
- self.data = ""
- def write(self, data):
- self.data += str(data)
- def writeln(self, data=None):
- if data is not None:
- self.write(data)
- self.write("\n")
- def get(self):
- get_data = self.data
- self.data = ""
- return get_data
-
-class TestResult(unittest.TestResult):
- """A specialized class that prints formatted text results to a stream.
-
- """
- separator1 = "=" * 30
- separator2 = "-" * 30
-
- def __init__(self, stream, browser, verbose):
- unittest.TestResult.__init__(self)
- self.stream = stream
- # Dictionary of start times
- self.start_times = {}
- # Dictionary of results
- self.results = {}
- self.browser = browser
- self.verbose = verbose
-
- def getDescription(self, test):
- """Gets description of test."""
- return test.shortDescription() or str(test)
-
- def startTest(self, test):
- """Starts test."""
- # Records the start time
- self.start_times[test] = time.time()
- # Default testresult if success not called
- self.results[test] = "FAIL"
- unittest.TestResult.startTest(self, test)
- if self.verbose:
- self.stream.writeln()
- self.stream.writeln(self.separator2)
- self.stream.write(self.getDescription(test))
- self.stream.writeln(" ... ")
-
- def stopTest(self, test):
- """Called when test is ended."""
- time_taken = time.time() - self.start_times[test]
- result = self.results[test]
- self.stream.writeln("SELENIUMRESULT %s <%s> [%.3fs]: %s"
- % (test, self.browser, time_taken, result))
- self.printErrors()
-
- def addSuccess(self, test):
- """Adds success result to TestResult."""
- unittest.TestResult.addSuccess(self, test)
- self.results[test] = "PASS"
-
- def addError(self, test, err):
- """Adds error result to TestResult."""
- unittest.TestResult.addError(self, test, err)
- self.results[test] = "FAIL"
-
- def addFailure(self, test, err):
- """Adds failure result to TestResult."""
- unittest.TestResult.addFailure(self, test, err)
- self.results[test] = "FAIL"
-
- def noResponse(self, test):
- """Configures the result for a test that did not respond."""
- self.results[test] = "FAIL"
- self.testsRun += 1
- self.errors.append("No response from test")
-
- if self.verbose:
- self.stream.writeln()
- self.stream.writeln(self.separator2)
- self.stream.write(self.getDescription(test))
- self.stream.writeln(" ... ")
- self.stream.writeln("SELENIUMRESULT %s <%s> [0s]: FAIL"
- % (test, self.browser))
- self.stream.writeln("Test was aborted due to timeout")
-
- def printErrors(self):
- """Prints all errors and failures."""
- if self.errors:
- self.printErrorList("ERROR", self.errors)
- if self.failures:
- self.printErrorList("FAIL", self.failures)
-
- def printErrorList(self, flavour, errors):
- """Prints a given list of errors."""
- for test, err in errors:
- self.stream.writeln("%s:" % flavour)
- self.stream.writeln("%s" % err)
-
- def printAll(self, stream):
- """Prints the entire stream to the given stream."""
- stream.write(self.stream.data)
-
- def merge(self, result):
- """Merges the given result into this resultl."""
- self.testsRun += result.testsRun
- for key, entry in result.results.iteritems():
- self.results[key] = entry
- for error in result.errors:
- self.errors.append(error)
- for failure in result.failures:
- self.failures.append(failure)
- self.stream.write(result.stream)
-
-
-class TestRunnerThread(threading.Thread):
- """Abstract test runner class. Launches its own thread for running tests.
- Formats test results.
-
- Members:
- completely_done_event: event that occurs just before thread exits.
- test: the currently running test.
- browser: selenium_name of browser that will be tested.
- """
- def __init__(self, verbose):
- threading.Thread.__init__(self)
- # This thread is a daemon so that the program can exit even if the
- # thread has not finished.
- self.setDaemon(True)
- self.completely_done_event = threading.Event()
- self.test = None
- self.browser = "default_browser"
- self.verbose = verbose
-
- def IsCompletelyDone(self):
- """Returns true if this test runner is completely done."""
- return self.completely_done_event.isSet()
-
- def run(self):
- pass
-
- def SetBrowser(self, browser):
- """Sets the browser name."""
- self.browser = browser
-
- def GetNoResponseResult(self):
- """Returns a generic no response result for last test."""
- result = TestResult(StringBuffer(), self.browser, self.verbose)
- result.noResponse(self.test)
- return result
-
- def RunTest(self, test):
- "Run the given test case or test suite."
- self.test = test
-
- stream = StringBuffer()
- result = TestResult(stream, self.browser, self.verbose)
- startTime = time.time()
- test(result)
- stopTime = time.time()
- timeTaken = stopTime - startTime
- if self.verbose:
- result.printErrors()
- run = result.testsRun
- return result
-
-
-class PDiffTestRunner(TestRunnerThread):
- """Test runner for Perceptual Diff tests. Polls a test queue and launches
- given tests. Adds result to given queue.
-
- Members:
- pdiff_queue: list of tests to run, when they arrive.
- result_queue: queue of our tests results.
- browser: selenium name of browser to be tested.
- end_testing_event: event that occurs when we are guaranteed no more tests
- will be added to the queue.
- """
- def __init__(self, pdiff_queue, result_queue, browser, verbose):
- TestRunnerThread.__init__(self, verbose)
- self.pdiff_queue = pdiff_queue
- self.result_queue = result_queue
- self.browser = browser
-
- self.end_testing_event = threading.Event()
-
- def EndTesting(self):
- """Called to notify thread that no more tests will be added to the test
- queue."""
- self.end_testing_event.set()
-
- def run(self):
- while True:
- try:
- test = self.pdiff_queue.get_nowait()
-
- result = self.RunTest(test)
-
- self.result_queue.put(result)
-
- except Queue.Empty:
- if self.end_testing_event.isSet() and self.pdiff_queue.empty():
- break
- else:
- time.sleep(1)
-
- self.completely_done_event.set()
-
-
-class SeleniumTestRunner(TestRunnerThread):
- """Test runner for Selenium tests. Takes a test from a test queue and launches
- it. Tries to handle hung/crashed tests gracefully.
-
- Members:
- testing_event: event that occurs when the runner is testing.
- finished_event: event that occurs when thread has finished testing and
- before it starts its next test.
- can_continue_lock: lock for |can_continue|.
- can_continue: is True when main thread permits the test runner to continue.
- sel_builder: builder that constructs new selenium sessions, as needed.
- browser: selenium name of browser to be tested.
- session: current selenium session being used in tests, can be None.
- test_queue: queue of tests to run.
- pdiff_queue: queue of perceptual diff tests to run. We add a perceptual
- diff test to the queue when the related selenium test passes.
- deadline: absolute time of when the test should be done.
- """
- def __init__(self, sel_builder, browser, test_queue, pdiff_queue, verbose):
- TestRunnerThread.__init__(self, verbose)
-
- # Synchronization.
- self.testing_event = threading.Event()
- self.finished_event = threading.Event()
- self.can_continue_lock = threading.Lock()
- self.can_continue = False
-
- # Selenium variables.
- self.sel_builder = sel_builder
- self.browser = browser
-
- # Test variables.
- self.test_queue = test_queue
- self.pdiff_queue = pdiff_queue
-
- self.deadline = 0
-
- def IsPastDeadline(self):
- if time.time() > self.deadline:
- return True
- return False
-
- def IsTesting(self):
- return self.testing_event.isSet()
-
- def DidFinishTest(self):
- return self.finished_event.isSet()
-
- def Continue(self):
- """Signals to thread to continue testing.
-
- Returns:
- result: the result for the recently finished test.
- """
-
- self.finished_event.clear()
-
- self.can_continue_lock.acquire()
- self.can_continue = True
- result = self.result
- self.can_continue_lock.release()
-
- return result
-
- def AbortTest(self):
- self._StopSession()
- self._StartSession()
-
- def _StartSession(self):
- self.session = self.sel_builder.NewSeleniumSession(self.browser)
- # Copy the session so we can shut down safely on a different thread.
- self.shutdown_session = copy.deepcopy(self.session)
-
- def _StopSession(self):
- if self.session is not None:
- self.session = None
- try:
- # This can cause an exception on some browsers.
- # Silenly disregard the exception.
- self.shutdown_session.stop()
- except:
- pass
-
- def run(self):
- self._StartSession()
-
- while not self.test_queue.empty():
- try:
- # Grab test from queue.
- test_obj = self.test_queue.get_nowait()
- if type(test_obj) == tuple:
- test = test_obj[0]
- pdiff_test = test_obj[1]
- else:
- test = test_obj
- pdiff_test = None
-
- self.can_continue = False
-
- # Check the current selenium session. Particularly, we are
- # interested if the previous test ran to completion, but the
- # browser window is closed.
- try:
- # This will generate an exception if the window is closed.
- self.session.window_focus()
- except Exception:
- self._StopSession()
- self._StartSession()
-
- # Deadline is the time to load page plus test run time.
- self.deadline = time.time() + (test.GetTestTimeout() / 1000.0)
- # Supply test with necessary selenium session.
- test.SetSession(self.session)
-
- # Run test.
- self.testing_event.set()
- self.result = self.RunTest(test)
-
- if time.time() > self.deadline:
- self.result = self.GetNoResponseResult()
-
- self.testing_event.clear()
- self.finished_event.set()
-
- # Wait for instruction from the main thread.
- while True:
- self.can_continue_lock.acquire()
- can_continue = self.can_continue
- self.can_continue_lock.release()
- if can_continue:
- break
- time.sleep(.5)
-
- if self.pdiff_queue is not None and pdiff_test is not None:
- if self.result.wasSuccessful():
- # Add the dependent perceptual diff test.
- self.pdiff_queue.put(pdiff_test)
-
- except Queue.Empty:
- break
-
- self._StopSession()
- self.completely_done_event.set()
-
-
diff --git a/o3d/tests/selenium/tests/assets/archive.o3dtgz b/o3d/tests/selenium/tests/assets/archive.o3dtgz
deleted file mode 100644
index c482299..0000000
--- a/o3d/tests/selenium/tests/assets/archive.o3dtgz
+++ /dev/null
Binary files differ
diff --git a/o3d/tests/selenium/tests/base-test.html b/o3d/tests/selenium/tests/base-test.html
deleted file mode 100644
index c799ec3..0000000
--- a/o3d/tests/selenium/tests/base-test.html
+++ /dev/null
@@ -1,89 +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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Base Test
-</title>
-</head>
-<body>
-<h1>Base Test</h1>
-This tests base.js.
-<br/>
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 32px; height: 32px;"></div>
-<!-- End of O3D plugin -->
-
-<script type="text/javascript"
- src="../../../samples/o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-
-o3djs.require('o3djs.test');
-o3djs.require('o3djs.util');
-
-var isChrome = navigator.userAgent.indexOf('Chrome') != -1;
-var isSafari = !isChrome && navigator.userAgent.indexOf('Safari') != -1;
-var isFirefox2 = navigator.userAgent.indexOf('Firefox/2.') != -1;
-var isFirefox = navigator.userAgent.indexOf('Firefox') != -1;
-var isInternetExplorer = navigator.userAgent.indexOf('Internet Explorer' != -1);
-
-g_suite = {};
-
-g_suite.testIsArrayWorksInBrowserForV8Arrays = function() {
- if (!isSafari) {
- g_test.assertTrue(o3djs.base.isArray(window.g_plugin.eval('[1, 2, 3]')));
- }
-};
-
-g_suite.testIsArrayWorksForBrowser = function() {
- g_test.assertFalse(o3djs.base.isArray(undefined));
- g_test.assertFalse(o3djs.base.isArray(7));
- g_test.assertTrue(o3djs.base.isArray([1, 2, 3]));
-};
-
-function initStep2(clientElements) {
- g_test = o3djs.test;
- g_plugin = clientElements[0];
- g_testResult = g_test.runTests(g_suite);
-};
-
-window.onload = function() {
- o3djs.util.makeClients(initStep2);
-};
-
-</script>
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/culling-zsort-test.html b/o3d/tests/selenium/tests/culling-zsort-test.html
deleted file mode 100644
index 2fe62ed..0000000
--- a/o3d/tests/selenium/tests/culling-zsort-test.html
+++ /dev/null
@@ -1,459 +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.
--->
-
-<!--
-O3D Culling and ZSorting Test.
-
-Make sure things off screen get culled.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Culling and ZSorting Test.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// global variables
-var g_timeMult = 1.0;
-var g_framesRendered = 0;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfos = [];
-var g_pack;
-var g_o3d_width; // width of our client area
-var g_o3d_height; // height of our client area
-var g_clock = 0;
-var g_totalTransformsElement;
-var g_transformsProcessedElement;
-var g_transformsCulledElement;
-var g_totalDrawElementsElement;
-var g_drawElementsProcessedElement;
-var g_drawElementsCulledElement;
-var g_drawElementsRenderedElement;
-var g_primitivesRenderedElement;
-var GROUPS_ACROSS = 4;
-var UNITS_ACROSS_GROUP = 3;
-var TOTAL_ACROSS = GROUPS_ACROSS * UNITS_ACROSS_GROUP;
-var HALF_WIDTH = TOTAL_ACROSS * 0.5;
-var UNIT_SPACING = 100;
-
-/**
- * Returns the path of where the file is located
- * with the trailing slash
- */
-function getCurrentPath() {
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- return path.substring(0, index + 1);
-}
-
-function createInstances(pack, shape) {
- // now make a grid of transforms and put a teapot instance on each one
- for (var g = 0; g < GROUPS_ACROSS; g++) {
- for (var h = 0; h < GROUPS_ACROSS; h++) {
- for (var i = 0; i < GROUPS_ACROSS; i++) {
- var groupTransform = pack.createObject('Transform');
- groupTransform.parent = g_client.root;
- groupTransform.cull = true;
- var boundingBox = g_o3d.BoundingBox([0, 0, 0],
- [0, 0, 0]);
- groupTransform.localMatrix = g_math.matrix4.translation([
- (g * UNITS_ACROSS_GROUP - HALF_WIDTH) * UNIT_SPACING,
- (h * UNITS_ACROSS_GROUP - HALF_WIDTH) * UNIT_SPACING,
- (i * UNITS_ACROSS_GROUP - HALF_WIDTH) * UNIT_SPACING]);
- for (var x = 0; x < UNITS_ACROSS_GROUP; x++) {
- for (var y = 0; y < UNITS_ACROSS_GROUP; y++) {
- for (var z = 0; z < UNITS_ACROSS_GROUP; z++) {
- var transform = pack.createObject('Transform');
- transform.parent = groupTransform;
- transform.cull = true;
- transform.addShape(shape);
- var elements = shape.elements;
- var box = elements[0].boundingBox;
- for (var ee = 1; ee < elements.length; ee++) {
- box = box.add(elements[ee].boundingBox);
- }
- transform.boundingBox = box;
- transform.localMatrix = g_math.matrix4.translation([
- (x - UNITS_ACROSS_GROUP * 0.5) * UNIT_SPACING,
- (y - UNITS_ACROSS_GROUP * 0.5) * UNIT_SPACING,
- (z - UNITS_ACROSS_GROUP * 0.5) * UNIT_SPACING]);
- transform.createParam('colorMult', 'ParamFloat4').value = [
- (g * UNITS_ACROSS_GROUP + x) * (1 / TOTAL_ACROSS),
- (h * UNITS_ACROSS_GROUP + y) * (1 / TOTAL_ACROSS),
- (i * UNITS_ACROSS_GROUP + z) * (1 / TOTAL_ACROSS),
- 1];
- var box = transform.boundingBox.mul(transform.localMatrix);
- boundingBox = boundingBox.add(box);
- }
- }
- }
- groupTransform.boundingBox = boundingBox;
- }
- }
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3d = clientElements[0];
- g_o3d = o3d.o3d;
- g_math = o3djs.math;
- g_client = o3d.client;
-
- g_totalTransformsElement =
- document.getElementById('totalTransforms');
- g_transformsProcessedElement =
- document.getElementById('transformsProcessed');
- g_transformsCulledElement =
- document.getElementById('transformsCulled');
- g_totalDrawElementsElement =
- document.getElementById('totalDrawElements');
- g_drawElementsProcessedElement =
- document.getElementById('drawElementsProcessed');
- g_drawElementsCulledElement =
- document.getElementById('drawElementsCulled');
- g_drawElementsRenderedElement =
- document.getElementById('drawElementsRendered');
- g_primitivesRenderedElement =
- document.getElementById('primitivesRendered');
-
- // Get the width and height of our client area. We will need this to create
- // a projection matrix.
- g_o3d_width = o3d.clientWidth;
- g_o3d_height = o3d.clientHeight;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- for (var yy = 0; yy < 2; yy++) {
- for (var xx = 0; xx < 2; xx++) {
- var viewInfo;
- var ii = yy * 2 + xx;
- if (xx == 0 && yy == 0) {
- viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot,
- [0.5, 0.5, 0.5, 1],
- 0,
- [0, 0, 0.5, 0.5]);
-
- } else {
- viewInfo = o3djs.rendergraph.createExtraView(
- g_viewInfos[0],
- [xx * 0.5, yy * 0.5, 0.5, 0.5], // top-right
- [0.5, 0.2 + xx * 0.5, 0.7 - yy * 0.5, 1.0]);
- }
- g_viewInfos[ii] = viewInfo;
-
- // Create our projection matrix, with a vertical field of view of 45
- // degrees a near clipping plane of 0.1 and far clipping plane of 100.
- viewInfo.drawContext.projection = g_math.matrix4.perspective(
- 45 * 3.14159 / 180,
- g_o3d_width / g_o3d_height,
- 0.1,
- 10000);
- }
- }
-
- /* Load the effect for our sphere from our file.
- Effects, stored in a hidden textarea for simplicity, contain the
- functions that define the vertex and pixel shaders used by our shape.
-
- Here, we calculate phong illumination in our vertex shader and pass the
- resultant color to our pixel shader, which does nothing except output its
- given (input) color.
- */
- var defaultEffect = g_pack.createObject('Effect');
- defaultEffect.loadFromFXString(document.getElementById('shader').value);
-
- // Create a Material for the effect.
- var material = g_pack.createObject('Material');
-
- // Apply our effect to this material.
- material.effect = defaultEffect;
-
- // Set the material's drawList
- material.drawList = g_viewInfos[0].zOrderedDrawList;
-
- // create params the effect needs on the material.
- defaultEffect.createUniformParameters(material);
-
- // Light position
- var light_pos_param = material.getParam('light_pos');
- light_pos_param.value = [1000, 1000, 0];
-
- // Phong components of the light source
- var light_ambient_param = material.getParam('light_ambient');
- var light_diffuse_param = material.getParam('light_diffuse');
- var light_specular_param = material.getParam('light_specular');
-
- // White ambient light
- light_ambient_param.value = [0.1, 0.1, 0.1, 1];
- // Reddish diffuse light
- light_diffuse_param.value = [1, 1, 1, 1];
- // White specular light
- light_specular_param.value = [0.5, 0.5, 0.5, 1];
-
- // Shininess of the material (for specular lighting)
- var shininess_param = material.getParam('shininess');
- shininess_param.value = 5.0;
-
- // Position of the camera.
- // (should be the same as the 'eye' position given below)
- var camera_pos_param = material.getParam('camera_pos');
- // Camera is at (0, 0, 3).
- camera_pos_param.value = [0, 0, 3];
-
- // Create 2 spheres.
- var shape1 = o3djs.primitives.createSphere(
- g_pack,
- material,
- 20,
- 10,
- 12,
- g_math.matrix4.translation([-25, 0, 0]));
-
- var shape2 = o3djs.primitives.createSphere(
- g_pack,
- material,
- 20,
- 10,
- 12,
- g_math.matrix4.translation([25, 0, 0]));
-
- // Create a shape and move the 2 sphere primitives to the same shape.
- var shape = g_pack.createObject('Shape');
- shape1.elements[0].owner = shape;
- shape2.elements[0].owner = shape;
- g_pack.removeObject(shape1);
- g_pack.removeObject(shape2);
- var elements = shape.elements;
- elements[0].cull = true;
- elements[1].cull = true;
-
- createInstances(g_pack, shape);
-
- g_totalDrawElementsElement.innerHTML = g_client.getObjectsByClassName(
- 'o3d.DrawElement').length;
- g_totalTransformsElement.innerHTML = g_client.getObjectsByClassName(
- 'o3d.Transform').length;
-
- // Setup an onrender callback for animation.
- g_client.setRenderCallback(onrender);
-}
-
-// spin the camera.
-function onrender(renderEvent) {
- g_framesRendered++;
- // Get the number of seconds since the last render.
- var elapsedTime = renderEvent.elapsedTime;
- g_clock += elapsedTime * g_timeMult;
-
- for (var vv = 0; vv < 4; vv++) {
- var clock = g_clock * (vv * 0.1 + 1);
- var x = Math.sin(clock * 0.1) * 400;
- var z = Math.cos(clock * 0.1) * 400;
- var y = Math.sin(clock * 0.2) * 400;
-
- g_viewInfos[vv].drawContext.view = g_math.matrix4.lookAt(
- [x, y, z],
- [0, 0, 0],
- [0, 1, 0]);
- }
-
- g_transformsProcessedElement.innerHTML = renderEvent.transformsProcessed;
- g_transformsCulledElement.innerHTML = renderEvent.transformsCulled;
- g_drawElementsProcessedElement.innerHTML = renderEvent.drawElementsProcessed;
- g_drawElementsCulledElement.innerHTML = renderEvent.drawElementsCulled;
- g_drawElementsRenderedElement.innerHTML = renderEvent.drawElementsRendered;
- g_primitivesRenderedElement.innerHTML = renderEvent.primitivesRendered;
-}
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Culling and ZSort Test</h1>
-Objects off screen should get culled and nothing in the front should zbuffer out
-stuff in the back.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<table>
-<tr><td>Total Transforms:</td><td><span id="totalTransforms">-</span></td></tr>
-<tr><td>Transforms Processed:</td><td><span id="transformsProcessed">-</span></td></tr>
-<tr><td>Transforms Culled:</td><td><span id="transformsCulled">-</span></td></tr>
-<tr><td>Total DrawElements:</td><td><span id="totalDrawElements">-</span></td></tr>
-<tr><td>DrawElements Processed:</td><td><span id="drawElementsProcessed">-</span></td></tr>
-<tr><td>DrawElements Culled:</td><td><span id="drawElementsCulled">-</span></td></tr>
-<tr><td>DrawElements Rendered:</td><td><span id="drawElementsRendered">-</span></td></tr>
-<tr><td>Primitives Rendered:</td><td><span id="primitivesRendered">-</span></td></tr>
-</table>
-<!-- Don't render the textarea -->
-<div style="display:none">
-<textarea id="shader" name="fx" cols="80" rows="20">
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WorldViewProjection;
-float4x4 worldInverseTranspose : WorldInverseTranspose;
-float4x4 world : World;
-
-// positions of the light and camera
-float3 light_pos;
-float3 camera_pos;
-
-// lighting components of the light source
-float4 light_ambient;
-float4 light_diffuse;
-float4 light_specular;
-
-// shininess of the material. (for specular lighting)
-float shininess;
-
-float4 colorMult;
-
-// input parameters for our vertex shader
-struct a2v {
- float4 pos : POSITION;
- float3 normal : NORMAL;
- float4 col : COLOR;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct v2f {
- float4 pos : POSITION;
- float4 pos2 : TEXCOORD0;
- float3 norm : TEXCOORD1;
- float3 light : TEXCOORD2;
- float4 col : COLOR;
-};
-
-/**
- * vsMain - our vertex shader
- *
- * @param IN.pos Position vector of vertex
- * @param IN.normal Normal of vertex
- * @param IN.col Color of vertex
- */
-v2f vsMain(a2v IN) {
- /**
- * We use the standard phong illumination equation here.
- * We restrict (clamp) the dot products so that we
- * don't get any negative values.
- * All vectors are normalized for proper calculations.
- *
- * The output color is the summation of the
- * ambient, diffuse, and specular contributions.
- *
- * Note that we have to transform each vertex and normal
- * by the view projection matrix first.
- */
- v2f OUT;
-
- OUT.pos = mul(IN.pos, worldViewProjection);
- OUT.pos2 = OUT.pos;
- OUT.norm = mul(float4(IN.normal, 0), worldInverseTranspose).xyz;
- OUT.light = light_pos - mul(IN.pos, world).xyz;
- OUT.col = IN.col;
- return OUT;
-}
-/**
- * psMain - pixel shader
- *
- * @param IN.pos Position vector of vertex
- * @param IN.col Color of vertex
- */
-float4 psMain(v2f IN): COLOR {
- float3 light = normalize(IN.light);
- float3 normal = normalize(IN.norm);
- float3 litR = normalize(2 * dot(light, normal) * normal - light);
- float3 v = normalize(mul(float4(camera_pos, 1),
- worldViewProjection).xyz - IN.pos2.xyz);
-
- // use lit function to calculate phong shading
- float4 phong_coeff = lit(dot(normal, light), dot(litR, v), shininess);
- float4 ambient = light_ambient * phong_coeff.x * IN.col;
- float4 diffuse = light_diffuse * phong_coeff.y * IN.col;
- float4 specular = light_specular * phong_coeff.z * IN.col;
-
- return float4(((ambient + diffuse) * colorMult + specular).xyz, 0.5);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vsMain
-// #o3d PixelShaderEntryPoint psMain
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-</div>
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/drawshapes.html b/o3d/tests/selenium/tests/drawshapes.html
deleted file mode 100644
index dcd9831..0000000
--- a/o3d/tests/selenium/tests/drawshapes.html
+++ /dev/null
@@ -1,395 +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.
--->
-
-<!--
-O3D Shape Stress Test
-
-This test generates a number of shapes that display on an empty o3d canvas.
-We assign each shape a pixel shader that colors the shape via a parameter.
-The color is set randomly.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Drawshape stress test for O3D
-</title>
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// Run the init() function once the page has finished loading.
-// and unload() when the page is unloaded.
-window.onload = init;
-window.onunload= unload;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_packEffect;
-var g_packShapes;
-var g_material;
-var g_parentTransform;
-
-// Variables for computing FPS
-var FPS_FRAMES_FOR_SAMPLE = 10; // number of frames to average for FPS.
-var g_totalTime = 0.0; // total time spent for last N frames.
-var g_timeTable = []; // elapsed time for last N frames.
-var g_timeTableCursor = 0;
-
-/**
- * Returns a random double between -1 and 1.
- */
-function getRandom() {
- return (Math.random() - 0.5) * 2;
-}
-
-/**
- * Creates a shape with the given effect
- * @param {Material} material material which our shape will use.
- * @param {Shape::PrimitiveType} primitiveType the shape's primitive type
- */
-function createShape(material, primitiveType) {
- // First, create a 'shape' and 'primitive' to store the our geometry.
- var myShape = g_packShapes.createObject('Shape');
- var myPrimitive = g_packShapes.createObject('Primitive');
- var myBank = g_packShapes.createObject('StreamBank');
- myPrimitive.owner = myShape;
- myPrimitive.streamBank = myBank;
-
- // Apply our material to this primitive.
- myPrimitive.material = material;
-
- myPrimitive.primitiveType = primitiveType;
- myPrimitive.numberPrimitives = 1; // 1 primitive.
-
- if (primitiveType == g_o3d.Primitive.TRIANGLELIST) {
- // Triangle list
- myPrimitive.numberVertices = 3; // 3 vertices in total
-
- // Create a javascript array that gives the coordinates of each of the
- // 3 corners (vertices) of the triangle.
-
- var vertsArray = [
- // Triangle
- getRandom(), getRandom(), 0,
- getRandom(), getRandom(), 0,
- getRandom(), getRandom(), 0
- ];
-
- // Check if vertices are oriented clockwise.
- // If not, we re-orient them.
- // This is done by checking the determinant.
- var determinant =
- vertsArray[0] * vertsArray[4] +
- vertsArray[3] * vertsArray[7] +
- vertsArray[6] * vertsArray[1] -
- vertsArray[3] * vertsArray[1] -
- vertsArray[6] * vertsArray[4] -
- vertsArray[0] * vertsArray[7];
-
- // vertices oriented wrongly.
- if (determinant < 0) {
- // swap vertices to reorient.
- var tmpVertX = vertsArray[0];
- var tmpVertY = vertsArray[1];
- vertsArray[0] = vertsArray[3];
- vertsArray[1] = vertsArray[4];
- vertsArray[3] = tmpVertX;
- vertsArray[4] = tmpVertY;
- }
-
- // The index array defines the order of the vertices we want to draw.
- // Here we tell the renderer that
- // Triangle 1 is created from vertices 0, 1 and 2.
- // Triangle 2 is created from vertices 3, 4 and 5.
- var indicesArray = [
- 0, 1, 2
- ];
- } else if (primitiveType == g_o3d.Primitive.LINELIST) {
- // Line list
- myPrimitive.numberVertices = 2; // 2 vertices in total
-
- var vertsArray = [
- // Line
- getRandom(), getRandom(), 0,
- getRandom(), getRandom(), 0
- ];
-
- var indicesArray = [
- 0, 1
- ];
- }
-
- // These next few lines take our javascript arrays and load them into some
- // 'buffers' where the 3D hardware can find them. We have to do this because
- // the 3D hardware can't 'see' javascript data until it is in a buffer.
- var vertexBuffer = g_packShapes.createObject('VertexBuffer');
- var field = vertexBuffer.createField('FloatField', 3);
- vertexBuffer.set(vertsArray);
-
- var indexBuffer = g_packShapes.createObject('IndexBuffer');
- indexBuffer.set(indicesArray);
-
- // Now we associate these 'buffers' of data with our primitive so that it can
- // access the data.
- myBank.setVertexStream(g_o3d.Stream.POSITION,
- 0,
- field,
- 0);
- myPrimitive.indexBuffer = indexBuffer;
-
- // Create a shapeColor parameter directly on the primitive so we don't have
- // to create multiple materials.
- var shapeColorParam = myPrimitive.createParam('shapeColor', 'ParamFloat4');
- shapeColorParam.value = [Math.random(), Math.random(), Math.random(), 1];
-
- // We now attach our shape to the transform.
- g_parentTransform.addShape(myShape);
-
- // Lastly we generate the draw elements.
- g_parentTransform.createDrawElements(g_packShapes, null);
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the effect.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- var o3d = clientElements[0];
- g_o3d = o3d.o3d;
- g_math = o3djs.math;
- g_client = o3d.client;
-
- var pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Create packs to manage our resources/assets
- g_packEffect = g_client.createPack();
- g_packShapes = g_client.createPack();
-
- // Load the effect for the shapes from the textarea and associate it
- // with the pack.
- var effect = g_packEffect.createObject('Effect');
- var fxString = document.getElementById('fx').value;
- effect.loadFromFXString(fxString);
-
- // Create a material.
- g_material = g_packEffect.createObject('Material');
-
- // Set the material's drawList
- g_material.drawList = g_viewInfo.performanceDrawList;
-
- // Apply our effect to this material.
- g_material.effect = effect;
- effect.createUniformParameters(g_material);
-
- // Create a parent transform
- g_parentTransform =
- g_packShapes.createObject('Transform');
- g_parentTransform.parent = g_client.root;
-
- // Initialize the FPS elapsed time history table.
- for (var tt = 0; tt < FPS_FRAMES_FOR_SAMPLE; tt++ ) {
- g_timeTable[tt] = 0.0;
- }
-
- // Set our render callback to display stats.
- g_client.setRenderCallback(onrender);
-}
-
-/**
- * Creates several shapes in the scene and renders them.
- */
-function createShapes(numShapes, primitiveType) {
- // Creates the shapes using the default effect.
- for (var i = 0; i < numShapes; i++)
- createShape(g_material, primitiveType);
-}
-
-/**
- * Destroys all the shapes that we have created.
- */
-function destroyShapes() {
- // Remove references
- g_parentTransform.parent = null;
- g_packShapes.destroy();
-
- // Re-create parent transform and pack
- g_packShapes = g_client.createPack();
- g_parentTransform =
- g_packShapes.createObject('Transform');
- g_parentTransform.parent = g_client.root;
-}
-
-/**
- * Frees unreferenced objects by destroying the packs on page unload.
- */
-function unload() {
- g_packEffect.destroy();
- g_packShapes.destroy();
-}
-
-// Updates statistics.
-// This function executes on each frame.
-function onrender(renderEvent) {
- if (window.g_client) {
- document.getElementById('clientObjectCount').innerHTML =
- g_client.getObjectsByClassName('o3d.ObjectBase').length;
- // Update FPS
- // Get the number of seconds since the last render.
- var elapsedTime = renderEvent.elapsedTime;
-
- // Keep the total time for the last N frames.
- g_totalTime += elapsedTime - g_timeTable[g_timeTableCursor];
-
- // Save off the elapsed time for this frame so we can subtract it later.
- g_timeTable[g_timeTableCursor] = elapsedTime;
-
- // Wrap the place to store the next time sample.
- g_timeTableCursor++;
- if (g_timeTableCursor == FPS_FRAMES_FOR_SAMPLE) {
- g_timeTableCursor = 0;
- }
-
- // Print the average frame rate for the last N frames as well as the
- // instantaneous frame rate.
- document.getElementById('fps').innerHTML = "" +
- Math.floor((1.0 / (g_totalTime / FPS_FRAMES_FOR_SAMPLE)) + 0.5) +
- " : " + Math.floor(1.0 / elapsedTime + 0.5);
-
-
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Draw shapes stress test</h1>
-This is a shape drawing stress test for o3d.
-<br/>
-Enter in the number of shapes to create and click the
-appropriate shape type button to render the shapes.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<br/>
-<form action="#" method="get" name="defaultForm">
- Render <input type="text" name="numShapes" value="3">
- <input type="button" name="btnTri" value="Triangles"
- onClick="createShapes(
- document.defaultForm.numShapes.value,
- g_o3d.Primitive.TRIANGLELIST)">
- <input type="button" name="btnLines" value="Lines"
- onClick="createShapes(
- document.defaultForm.numShapes.value,
- g_o3d.Primitive.LINELIST)">
- <br/>
- <input type="button" name="btnClear" value="Clear"
- onClick="destroyShapes()">
-</form>
-<table border="0" summary="O3D statistics">
- <tr>
- <td style="font-weight:bold">Client Object Count:</td>
- <td id="clientObjectCount">0</td>
- </tr>
- <tr>
- <td style="font-weight:bold; color:red">FPS:</td>
- <td id="fps">0</td>
- </tr>
-</table>
-<!-- Don't render the textarea -->
-<div style="display:none">
-<!-- Start of effect -->
-<textarea id="fx" name="fx" cols="80" rows="20">
- // This is the color of the triangle.
- // We bind this to a javascript variable shapeColorParam
- // to modify its value dynamically
- float4 shapeColor : FLOAT4;
-
- // input parameters for our vertex shader
- struct a2v {
- float4 pos : POSITION;
- };
-
- // input parameters for our pixel shader
- struct v2f {
- float4 pos : POSITION;
- };
-
- /**
- * Our vertex shader does nothing but returns the position of the vertex.
- * (which is unused eventually)
- */
- v2f vsMain(a2v IN) {
- v2f OUT;
- OUT.pos = IN.pos;
- return OUT;
- }
-
- /* Our pixel shader returns the color which is assigned dynamically.
- */
- float4 psMain(v2f IN): COLOR {
- return shapeColor;
- }
-
- // Here we tell our effect file *which* functions are
- // our vertex and pixel shaders.
-
- // #o3d VertexShaderEntryPoint vsMain
- // #o3d PixelShaderEntryPoint psMain
- // #o3d MatrixLoadOrder RowMajor
-</textarea>
-<!-- End of effect -->
-</div>
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/effect-import-test.html b/o3d/tests/selenium/tests/effect-import-test.html
deleted file mode 100644
index 06357e0..0000000
--- a/o3d/tests/selenium/tests/effect-import-test.html
+++ /dev/null
@@ -1,154 +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.
--->
-
-<!--
-Test that when importing a file Effects get shared.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Effect Import Test
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_client;
-var g_viewInfo;
-var g_testResult;
-var g_pack;
-
-/**
- * Loads a model into the transform graph and generates its corresponding entry
- * in the render graph when it is done loading.
- * @param {!o3d.Pack} pack Pack to load model into.
- * @param {string} fileName filename of the model.
- * @param {!o3d.Transform} parent parent node in the transform graph to
- * which to load the model into.
- */
-function loadModel(pack, fileName, parent) {
- // Get our full path to the model
- var modelPath = o3djs.util.getCurrentURI() + fileName;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, modelPath, callback);
-
- /**
- * Our callback is called once the model has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + fileName + '\n' + exception);
- return;
- }
- // Get a cameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- g_client.width,
- g_client.height);
-
- // Copy the camera info from the file the draw context.
- g_viewInfo.drawContext.view = cameraInfo.view;
- g_viewInfo.drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfo);
-
- var effects = g_client.getObjectsByClassName('o3d.Effect');
- g_testResult = effects.length == 1;
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the model into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3d = clientElements[0];
- g_o3d = o3d.o3d;
- g_client = o3d.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Load the model into the transform graph.
- loadModel(g_pack,
- '../../../samples/assets/seven_shapes.o3dtgz',
- g_client.root);
-}
-</script>
-</head>
-<body>
-<h1>Effect Import Test</h1>
-<br/>
-Test that when importing a file Effects get shared.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/event-test.html b/o3d/tests/selenium/tests/event-test.html
deleted file mode 100644
index 4e03d6fd..0000000
--- a/o3d/tests/selenium/tests/event-test.html
+++ /dev/null
@@ -1,284 +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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Event Test
-</title>
-</head>
-<body>
-<h1>Event Test</h1>
-This tests the event-handler functions in the event.js library.
-<br/>
-<script type="text/javascript"
- src="../../../samples/o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-
-o3djs.require('o3djs.event');
-o3djs.require('o3djs.test');
-
-var g_event = {};
-
-function FakeClient() {
-};
-
-FakeClient.prototype.getCallbacks = function() {
- this.callbacks = this.callbacks || [];
- return this.callbacks;
-};
-
-FakeClient.prototype.setEventCallback = function(type, callback) {
- this.getCallbacks()[type] = callback;
-};
-
-FakeClient.prototype.clearEventCallback = function(type) {
- this.getCallbacks()[type] = null;
-};
-
-FakeClient.prototype.handleEvent = function(type, event) {
- var callback = this.getCallbacks()[type];
- if (callback) {
- g_test.assertTrue(typeof(callback) == 'function');
- callback(event);
- }
-};
-
-function FakePlugin() {
- this.client = new FakeClient();
-}
-
-FakePlugin.prototype.handleEvent = function(type, event) {
- this.client.handleEvent(type, event);
-};
-
-var g_a;
-function incA(event) {
- g_test.assertTrue(event != null);
- g_test.assertTrue(event == g_event);
- ++g_a;
-}
-
-var incAAsEventListener = {
- handleEvent: incA
-};
-
-var g_b;
-function incB(event) {
- g_test.assertTrue(event != null);
- g_test.assertTrue(event == g_event);
- ++g_b;
-}
-
-var g_suite = {};
-
-g_suite.testSimpleHandler = function() {
- var fakePlugin = new FakePlugin;
- g_a = 0;
- g_b = 0;
- o3djs.event.addEventListener(fakePlugin, 'click', incA);
- g_test.assertEquals(0, g_a);
- g_test.assertEquals(0, g_b);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(1, g_a);
- g_test.assertEquals(0, g_b);
-}
-
-g_suite.testMultipleHandlers = function() {
- var fakePlugin = new FakePlugin;
- g_a = 0;
- g_b = 0;
- o3djs.event.addEventListener(fakePlugin, 'click', incA);
- o3djs.event.addEventListener(fakePlugin, 'click', incB);
- g_test.assertEquals(0, g_a);
- g_test.assertEquals(0, g_b);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(1, g_a);
- g_test.assertEquals(1, g_b);
-}
-
-g_suite.testAddingHandlerIsIdempotent = function() {
- var fakePlugin = new FakePlugin;
- g_a = 0;
- g_b = 0;
- o3djs.event.addEventListener(fakePlugin, 'click', incA);
- o3djs.event.addEventListener(fakePlugin, 'click', incA);
- g_test.assertEquals(0, g_a);
- g_test.assertEquals(0, g_b);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(1, g_a);
- g_test.assertEquals(0, g_b);
-}
-
-g_suite.testAddingAndRemovingHandlers = function() {
- var fakePlugin = new FakePlugin;
- g_a = 0;
- g_b = 0;
- o3djs.event.addEventListener(fakePlugin, 'click', incA);
- o3djs.event.addEventListener(fakePlugin, 'click', incB);
- g_test.assertEquals(0, g_a);
- g_test.assertEquals(0, g_b);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(1, g_a);
- g_test.assertEquals(1, g_b);
- // Check that it's repeatable.
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(2, g_a);
- g_test.assertEquals(2, g_b);
- o3djs.event.removeEventListener(fakePlugin, 'click', incA);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(2, g_a);
- g_test.assertEquals(3, g_b);
- o3djs.event.removeEventListener(fakePlugin, 'click', incB);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(2, g_a);
- g_test.assertEquals(3, g_b);
- // Check that removing in the opposite order works too.
- var fakePlugin = new FakePlugin;
- g_a = 0;
- g_b = 0;
- o3djs.event.addEventListener(fakePlugin, 'click', incA);
- o3djs.event.addEventListener(fakePlugin, 'click', incB);
- g_test.assertEquals(0, g_a);
- g_test.assertEquals(0, g_b);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(1, g_a);
- g_test.assertEquals(1, g_b);
- // Check that it's repeatable.
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(2, g_a);
- g_test.assertEquals(2, g_b);
- o3djs.event.removeEventListener(fakePlugin, 'click', incB);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(3, g_a);
- g_test.assertEquals(2, g_b);
- o3djs.event.removeEventListener(fakePlugin, 'click', incA);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(3, g_a);
- g_test.assertEquals(2, g_b);
-}
-
-g_suite.testRemovingHandlerIsIdempotent = function() {
- var fakePlugin = new FakePlugin;
- g_a = 0;
- g_b = 0;
- o3djs.event.addEventListener(fakePlugin, 'click', incA);
- o3djs.event.addEventListener(fakePlugin, 'click', incA);
- g_test.assertEquals(0, g_a);
- g_test.assertEquals(0, g_b);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(1, g_a);
- g_test.assertEquals(0, g_b);
- o3djs.event.removeEventListener(fakePlugin, 'click', incA);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(1, g_a);
- g_test.assertEquals(0, g_b);
- o3djs.event.removeEventListener(fakePlugin, 'click', incA);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(1, g_a);
- g_test.assertEquals(0, g_b);
-}
-
-g_suite.testEventListenerIsLikeFunction = function() {
- var fakePlugin = new FakePlugin;
- g_a = 0;
- g_b = 0;
- o3djs.event.addEventListener(fakePlugin, 'click', incA);
- o3djs.event.addEventListener(fakePlugin, 'click', incAAsEventListener);
- g_test.assertEquals(0, g_a);
- g_test.assertEquals(0, g_b);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(2, g_a);
- g_test.assertEquals(0, g_b);
- o3djs.event.removeEventListener(fakePlugin, 'click', incA);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(3, g_a);
- g_test.assertEquals(0, g_b);
- o3djs.event.removeEventListener(fakePlugin, 'click', incA);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(4, g_a);
- g_test.assertEquals(0, g_b);
- o3djs.event.removeEventListener(fakePlugin, 'click',
- incAAsEventListener);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(4, g_a);
- g_test.assertEquals(0, g_b);
-}
-
-g_suite.testMultipleDifferentEvents = function() {
- var fakePlugin = new FakePlugin;
- g_a = 0;
- g_b = 0;
- o3djs.event.addEventListener(fakePlugin, 'click', incA);
- o3djs.event.addEventListener(fakePlugin, 'mousedown', incB);
- g_test.assertEquals(0, g_a);
- g_test.assertEquals(0, g_b);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(1, g_a);
- g_test.assertEquals(0, g_b);
- fakePlugin.handleEvent('mousedown', g_event);
- g_test.assertEquals(1, g_a);
- g_test.assertEquals(1, g_b);
- o3djs.event.removeEventListener(fakePlugin, 'mousedown', incA);
- o3djs.event.removeEventListener(fakePlugin, 'click', incB);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(2, g_a);
- g_test.assertEquals(1, g_b);
- fakePlugin.handleEvent('mousedown', g_event);
- g_test.assertEquals(2, g_a);
- g_test.assertEquals(2, g_b);
- o3djs.event.removeEventListener(fakePlugin, 'click', incA);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(2, g_a);
- g_test.assertEquals(2, g_b);
- fakePlugin.handleEvent('mousedown', g_event);
- g_test.assertEquals(2, g_a);
- g_test.assertEquals(3, g_b);
- o3djs.event.removeEventListener(fakePlugin, 'mousedown', incB);
- fakePlugin.handleEvent('click', g_event);
- g_test.assertEquals(2, g_a);
- g_test.assertEquals(3, g_b);
- fakePlugin.handleEvent('mousedown', g_event);
- g_test.assertEquals(2, g_a);
- g_test.assertEquals(3, g_b);
-}
-
-window.onload = function() {
- window.g_test = o3djs.test;
- window.g_testResult = g_test.runTests(g_suite);
-};
-
-</script>
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/features-test.html b/o3d/tests/selenium/tests/features-test.html
deleted file mode 100644
index ea4ec7d..0000000
--- a/o3d/tests/selenium/tests/features-test.html
+++ /dev/null
@@ -1,157 +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.
--->
-
-<!--
-Features Test
-
-Make sure when features are not requested you can not use them and when
-they are requested you can use them.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Features Test.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_client;
-var g_pack;
-var g_testResult;
-
-/**
- * Checks the client.lastError is empty or not after calling a function.
- * @param {!o3d.Client} client The client to use.
- * @param {boolean} expectError True if we expect an error.
- * @param {!function(): void} func Function to call.
- * @return {boolean} True if error matched expectations.
- */
-function checkForError(client, expectError, func) {
- client.clearLastError();
- func();
- var haveError = client.lastError.length > 0;
- return haveError == expectError;
-}
-
-/**
- * Creates a buffer with the requested number of elements.
- * @param {!o3d.Pack} pack Pack to create buffer in.
- * @param {number} numElements Number of elements to create.
- */
-function createBuffer(pack, numElements) {
- var buffer = pack.createObject('VertexBuffer');
- var field = buffer.createField('FloatField', 1);
- buffer.allocateElements(numElements);
-}
-
-/**
- * Checks that features error or are available based on if they were requested.
- *
- * @param {!Element} o3dElement The o3dElement for the O3D object.
- * @param {boolean} expectError True if we expect errors when using the
- * features.
- * @return {boolean} True if checks succeeded.
- */
-function checkFeatures(o3dElement, expectError) {
- var o3d = o3dElement.o3d;
- var client = o3dElement.client;
- client.clearErrorCallback();
- var pack = client.createPack();
- // A list of functions that each create something that require a feature.
- var functions = [
- function() { pack.createTexture2D(32, 32, o3d.Texture.R32F, 1, false); },
- function() { pack.createTexture2D(32, 32, o3d.Texture.ABGR16F, 1, false); },
- function() { pack.createTexture2D(32, 32, o3d.Texture.ABGR32F, 1, false); },
- function() { createBuffer(pack, 65535); }
- ];
-
- for (var ii = 0; ii < functions.length; ++ii) {
- if (!checkForError(client, expectError, functions[ii])) {
- return false;
- }
- }
-
- return true;
-}
-
-/**
- * Creates the client areas.
- */
-function init() {
- o3djs.util.makeClients(initStep2); // no features requested.
-}
-
-/**
- * Initializes O3D and loads the model into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- g_testResult = checkFeatures(clientElements[0], true) &&
- checkFeatures(clientElements[1], false);
-
- document.getElementById('result').innerHTML = g_testResult ?
- '<font color="green">success</font>' :
- '<font color="red">failure</font>';
-}
-</script>
-</head>
-<body>
-<h1>Features Test</h1>
-Make sure when features are not requested you can not use them and when
-they are requested you can use them.
-<br/>
-<br/>
-<div>Result: <span id="result"></span></div>
-<!-- Start of O3D plugin -->
-<div id="o3d1" style="width: 100px; height: 100px;"></div>
-<br/>
-<div id="o3d2" o3d_features="FloatingPointTextures,LargeGeometry" style="width: 100px; height: 100px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/init-status-test.html b/o3d/tests/selenium/tests/init-status-test.html
deleted file mode 100644
index c46a587..0000000
--- a/o3d/tests/selenium/tests/init-status-test.html
+++ /dev/null
@@ -1,117 +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.
--->
-
-<!--
-Init Status Test
-
-Check we get the expected result if the plugin does not start.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Init Status Test.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_client;
-var g_pack;
-var g_testResult;
-
-/**
- * Creates the client areas.
- */
-function init() {
- setTimeout(failed, 2000);
- o3djs.util.makeClients(initStep2, 'InitStatus=3');
-}
-
-/**
- * Initializes O3D.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- g_testResult = false;
-}
-
-/**
- * Called if makeClients failed.
- */
-function failed () {
- var tag = 'div';
- var id = '^o3d';
- var msg =
- 'We are terribly sorry but it appears your graphics card is not ' +
- 'able to run o3d. We are working on a solution.';
- var elements = document.getElementsByTagName(tag);
- for (var ee = 0; ee < elements.length; ++ee) {
- var element = elements[ee];
- if (element.id && element.id.match(id)) {
- var innerHTML = element.innerHTML;
- g_testResult = (innerHTML.indexOf(msg) >= 0);
- document.getElementById('result').innerHTML = g_testResult ?
- '<font color="green">success</font>' :
- '<font color="red">failure</font>';
- return;
- }
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Init Status Test</h1>
-
-Check we get the expected result if the plugin does not start.
-<br/>
-<br/>
-<div>Result: <span id="result"></span></div>
-<br/>
-Note: You should see "We are terribly sorry..." below.
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<br/>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/math-test.html b/o3d/tests/selenium/tests/math-test.html
deleted file mode 100644
index bba64c0..0000000
--- a/o3d/tests/selenium/tests/math-test.html
+++ /dev/null
@@ -1,886 +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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Math Test
-</title>
-</head>
-<body>
-<h1>Math Test</h1>
-This tests the math utility library.
-<br/>
-<script type="text/javascript"
- src="../../../samples/o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.test');
-
-var isChrome = navigator.userAgent.indexOf('Chrome') != -1;
-var isSafari = !isChrome && navigator.userAgent.indexOf('Safari') != -1;
-var isFirefox = navigator.userAgent.indexOf('Firefox') != -1;
-var isInternetExplorer = navigator.userAgent.indexOf('Internet Explorer' != -1);
-
-var g_suite = {};
-
-g_suite.testPseudoRandom = function() {
- var values = [];
- g_math.resetPseudoRandom();
- for (var ii = 0; ii < 100; ++ii) {
- value = g_math.pseudoRandom();
- g_test.assertTrue(value >= 0);
- g_test.assertTrue(value <= 1);
- for (var jj = 0; jj < ii - 1; ++jj) {
- g_test.assertTrue(value !== values[jj]);
- }
- values.push(value);
- }
- g_math.resetPseudoRandom();
- for (var ii = 0; ii < values.length; ++ii) {
- value = g_math.pseudoRandom();
- g_test.assertEquals(value, values[ii]);
- }
-};
-
-g_suite.testDegToRad = function() {
- g_test.assertEquals(Math.PI, g_math.degToRad(180));
-};
-
-g_suite.testRadToDeg = function() {
- g_test.assertEquals(180, g_math.radToDeg(Math.PI));
-};
-
-g_suite.testScalarLerp = function() {
- g_test.assertEquals(3, g_math.lerpScalar(2, 6, .25));
-};
-
-g_suite.testModClamp = function() {
- g_test.assertEquals(0.5, g_math.modClamp(2.5, 2.0));
- g_test.assertEquals(0.5, g_math.modClamp(6.5, 2.0));
- g_test.assertEquals(3.0, g_math.modClamp(3.0, 2.0, 2.5));
- g_test.assertEquals(1.5, g_math.modClamp(-0.5, 2.0));
- g_test.assertEquals(0.5, g_math.modClamp(-3.5, 2.0));
-}
-
-g_suite.testLerpCircular = function() {
- g_test.assertEquals(30, g_math.lerpCircular(0, 100, 0.3, 300));
- g_test.assertEquals(270, g_math.lerpCircular(0, 200, 0.3, 300));
- g_test.assertEquals(0, g_math.lerpCircular(0, 300, 1, 300));
-}
-
-g_suite.testLerpRadian = function() {
- g_test.assertEquals(0.3, g_math.lerpRadian(0, 1, 0.3));
- g_test.assertEquals(Math.PI * 2 - 0.3,
- g_math.lerpRadian(0, Math.PI * 2 - 1, 0.3));
- g_test.assertEquals(0, g_math.lerpRadian(0, Math.PI * 2, 1));
-}
-
-g_suite.testVectorNegative = function() {
- g_test.assertArrayEquals([0, 6, 7], g_math.negativeVector([0, -6, -7]));
-};
-
-g_suite.testVectorCopy = function() {
- var v = [0, 6, 7];
- var u = g_math.copyVector(v);
- g_test.assertArrayEquals(u, v);
- g_test.assertFalse(u == v);
-};
-
-g_suite.testVectorAdd = function() {
- g_test.assertArrayEquals([0, 6, 7], g_math.addVector([1, 2, 3], [-1, 4, 4]));
- g_test.assertArrayEquals([1, -1, -1], g_math.addVector([0, 0, 0],
- [1, -1, -1]));
-};
-
-g_suite.testVectorSub = function() {
- g_test.assertArrayEquals([2, -2, -1, 4],
- g_math.subVector([1, 2, 3, 4], [-1, 4, 4, 0]));
-};
-
-g_suite.testVectorLerp = function() {
- g_test.assertArrayEquals([0.5, 2.5, 3.25, 3],
- g_math.lerpVector([1, 2, 3, 4], [-1, 4, 4, 0], 0.25));
-}
-
-g_suite.testVectorMul = function() {
- g_test.assertArrayEquals([2, 4, 6], g_math.mulScalarVector(2, [1, 2, 3]));
- g_test.assertArrayEquals([2, 4, 6], g_math.mulVectorScalar([1, 2, 3], 2));
-}
-
-g_suite.testVectorDiv = function() {
- g_test.assertArrayEquals([0.5, 1, 1.5, 2],
- g_math.divVectorScalar([1, 2, 3, 4], 2));
-};
-
-g_suite.testDotProduct = function() {
- g_test.assertEquals(19, g_math.dot([-1, 4, 4], [1, 2, 3]));
-};
-
-g_suite.testLength = function() {
- g_test.assertEquals(13, g_math.length([5, 12]));
-};
-
-g_suite.testLengthSquared = function() {
- g_test.assertEquals(169, g_math.lengthSquared([5, 12]));
-};
-
-g_suite.testDistance = function() {
- g_test.assertEquals(13, g_math.distance([1, 1], [6, 13]));
-};
-
-g_suite.testDistanceSquared = function() {
- g_test.assertEquals(169, g_math.distanceSquared([1, 1], [6, 13]));
-};
-
-g_suite.testNormalize = function() {
- g_test.assertEquals(1, g_math.length(g_math.normalize([1, 2, 3])));
- g_test.assertEquals(0,
- g_math.length(g_math.cross(g_math.normalize([1, 2, 3]), [1, 2, 3])));
-};
-
-g_suite.testCrossProduct = function() {
- var u = [-1, 4, 4];
- var v = [1, 2, 3];
- g_test.assertArrayEquals([4, 7, -6], g_math.cross(u, v));
- g_test.assertEquals(0, g_math.dot(g_math.cross(u, v), u));
- g_test.assertEquals(0, g_math.dot(g_math.cross(u, v), v));
-};
-
-
-var A = [[1, 2, 3], [2, -5, 1], [-1, 5, 3], [1, 4, 2]];
-var B = [[0, 1, -1], [1, -1, 3], [2, 1, 2], [0, -1, 4]];
-
-g_suite.testMatrixNegative = function() {
- g_test.assertArrayEquals(
- [[-1, -2, -3], [-2, 5, -1], [1, -5, -3], [-1, -4, -2]],
- g_math.negativeMatrix(A));
-};
-
-g_suite.testMatrixCopy = function() {
- var M = g_math.copyMatrix(A);
- g_test.assertArrayEquals(A, M);
- g_test.assertFalse(A == M);
-};
-
-g_suite.testMatrixAdd = function() {
- g_test.assertArrayEquals([[1, 3, 2], [3, -6, 4], [1, 6, 5], [1, 3, 6]],
- g_math.addMatrix(A, B));
-};
-
-g_suite.testMatrixSub = function() {
- g_test.assertArrayEquals([[1, 1, 4], [1, -4, -2], [-3, 4, 1], [1, 5, -2]],
- g_math.subMatrix(A, B));
-};
-
-g_suite.testMatrixLerp = function() {
- g_test.assertArrayEquals(
- [[0.75, 1.75, 2],
- [1.75, -4, 1.5],
- [-0.25, 4, 2.75],
- [0.75, 2.75, 2.5]], g_math.lerpMatrix(A, B, .25));
-};
-
-g_suite.testMulScalarMatrix = function() {
- g_test.assertArrayEquals([[2, 4, 6], [4, -10, 2], [-2, 10, 6], [2, 8, 4]],
- g_math.mulMatrixScalar(A, 2));
- g_test.assertArrayEquals([[2, 4, 6], [4, -10, 2], [-2, 10, 6], [2, 8, 4]],
- g_math.mulScalarMatrix(2, A));
-};
-
-g_suite.testMatrixDiv = function() {
- g_test.assertArrayEquals(
- [[0.5, 1, 1.5], [1, -2.5, 0.5], [-0.5, 2.5, 1.5], [0.5, 2, 1]],
- g_math.divMatrixScalar(A, 2));
-};
-
-// The square root of the sum of squares of the entries of a matrix.
-function frobeniusNorm(a) {
- return Math.sqrt(g_math.trace(g_math.mulMatrixMatrix(
- g_math.transpose(a), a)));
-};
-
-// The sum of squares of entries of the difference between two matrices.
-function matrixDiff(a,b) {
- return frobeniusNorm(g_math.subMatrix(a,b));
-};
-
-// Multiplies a matrix by its inverse and checks that it is not
-// too different from the identity. (With floating-point error, exact
-// equality is too much to ask).
-function inverseTest(a) {
- g_test.assertTrue(matrixDiff(g_math.mulMatrixMatrix(a, g_math.inverse(a)),
- g_math.identity(a.length)) < 0.001);
- g_test.assertTrue(matrixDiff(g_math.mulMatrixMatrix(g_math.inverse(a), a),
- g_math.identity(a.length)) < 0.001);
-};
-
-g_suite.testTranspose = function() {
- g_test.assertArrayEquals([[1, 2, -1, 1], [2, -5, 5, 4], [3, 1, 3, 2]],
- g_math.transpose([[1, 2, 3], [2, -5, 1], [-1, 5, 3], [1, 4, 2]]));
-};
-
-g_suite.testTrace = function() {
- g_test.assertEquals(6, g_math.trace([
- [1, 2, 3, 4],
- [1, -2, 1, 1],
- [1, 1, 0, -1],
- [1,2,-1,7]]));
-};
-
-g_suite.testIdentity = function() {
- g_test.assertArrayEquals([[1, 0], [0, 1]], g_math.identity(2));
- g_test.assertArrayEquals([[1, 0, 0], [0, 1, 0], [0, 0, 1]],
- g_math.identity(3));
-};
-
-g_suite.testDeterminant2 = function() {
- g_test.assertEquals(-2, g_math.det([[1, 2], [3, 4]]));
-};
-
-g_suite.testDeterminant3 = function() {
- g_test.assertEquals(10, g_math.det([[1, 2, 3], [1, -2, 1], [1, 1, 0]]));
-};
-
-g_suite.testDeterminant4 = function() {
- g_test.assertEquals(28, g_math.det([
- [1, 2, 3, 4],
- [1, -2, 1, 1],
- [1, 1, 0, -1],
- [1, 2, -1, 0]]));
-};
-
-g_suite.testDeterminant5 = function() {
- g_test.assertEquals(-120.00,
- g_math.det([
- [2, 5,-1, 2, 1],
- [1, 2,-1, 3, 2],
- [1, 3, 4, 7, -3],
- [1, -1, 1, 2, -4],
- [0, 1, 0, 1, 0]]));
-};
-
-g_suite.testMatrixInversion2 = function() {
- inverseTest([[1, 2], [3, 4]]);
-};
-
-g_suite.testMatrixInversion3 = function() {
- inverseTest([[1, 2, 3], [1, -2, 1], [1, 1, 0]]);
-};
-
-g_suite.testMatrixInversion4 = function() {
- inverseTest([[1, 2, 3, 4], [1, -2, 1, 1],
- [1, 1, 0, -1], [1, 2, -1, 0]]);
-};
-
-g_suite.testMatrixInversion5 = function() {
- inverseTest([
- [2, 5, -1, 2, 1],
- [1, 2, -1, 3, 2],
- [1, 3, 4, 7, -3],
- [1, -1, 1, 2, -4],
- [0, 1, 0, 1, 0]]);
-};
-
-var S = [[1, 2, 3, 0], [2, -5, 1, 1]];
-var T = [[1, 2, 3], [2, -5, 1], [-1, 5, 3], [1, 4, 2]];
-var U = [[2, 5, -1, 2], [1, 2, -1, 3], [1, 3, 4, 7]];
-
-g_suite.testRowMajorMulMatrixMatrix = function() {
- g_test.assertArrayEquals(
- [[7, 18, 9, 29], [0, 3, 7, -4], [6, 14, 8, 34], [8, 19, 3, 28]],
- g_math.rowMajor.mulMatrixMatrix(T, U));
- g_test.assertArrayEquals([[2, 7, 14], [-8, 38, 6]],
- g_math.rowMajor.mulMatrixMatrix(S, T));
-};
-
-g_suite.testColumnMajorMulMatrixMatrix = function() {
- g_test.assertArrayEquals([[7, 18, 9, 29],
- [0, 3, 7, -4],
- [6, 14, 8, 34],
- [8, 19, 3, 28]],
- g_math.columnMajor.mulMatrixMatrix(U, T));
- g_test.assertArrayEquals([[2, 7, 14], [-8, 38, 6]],
- g_math.columnMajor.mulMatrixMatrix(T, S));
-};
-
-g_suite.testRowMajorMulMatrixMatrix2 = function() {
- g_test.assertArrayEquals([[5, -2], [9, -2]],
- g_math.rowMajor.mulMatrixMatrix2([[1, 2], [3, 4]], [[-1, 2], [3,-2]]));
-};
-
-g_suite.testColumnMajorMulMatrixMatrix2 = function() {
- g_test.assertArrayEquals([[5, 6], [-3, -2]],
- g_math.columnMajor.mulMatrixMatrix2([[1, 2], [3, 4]], [[-1, 2], [3,-2]]));
-};
-
-g_suite.testRowMajorMulMatrixMatrix3 = function() {
- g_test.assertArrayEquals([[6, 0, 10], [14, 8, 42], [-4, 12, 20]],
- g_math.rowMajor.mulMatrixMatrix3(
- [[1, 2, 1], [3, 4, 5], [-1, -3, 4]],
- [[-1, 2, 4], [3, -2, 0], [1, 2, 6]]));
-};
-
-g_suite.testColumnMajorMulMatrixMatrix3 = function() {
- g_test.assertArrayEquals([[1, -6, 25], [-3, -2, -7], [1, -8, 35]],
- g_math.columnMajor.mulMatrixMatrix3(
- [[1, 2, 1], [3, 4, 5], [-1, -3, 4]],
- [[-1, 2, 4], [3, -2, 0], [1, 2, 6]]));
-};
-
-g_suite.testRowMajorMatrixMatrix4 = function() {
- g_test.assertArrayEquals([
- [8, 5, 9, 7],
- [12, 3, 43, 33],
- [0, 22, 18, 1],
- [14, 10, 14, 9]],
- g_math.rowMajor.mulMatrixMatrix4(
- [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2], [1, 3, 2, 2]],
- [[-1, 2, 4, 4], [3, -2, 0, 1], [1, 2, 6, 3], [2, 5, -1, -2]]));
-};
-
-g_suite.testColumnMajorMatrixMatrix4 = function() {
- g_test.assertArrayEquals([
- [5, 6, 33, 13],
- [-2, 1, -5, 7],
- [4, 1, 41, 17],
- [16, 21, 19, -9]],
- g_math.columnMajor.mulMatrixMatrix4(
- [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2], [1, 3, 2, 2]],
- [[-1, 2, 4, 4], [3, -2, 0, 1], [1, 2, 6, 3], [2, 5, -1, -2]]));
-};
-
-g_suite.testRowMajorMulMatrixVector = function() {
- g_test.assertArrayEquals([5, 9, 0, 1],
- g_math.rowMajor.mulMatrixVector(T, [1, -1, 2]));
-};
-
-g_suite.testColumnMajorMulMatrixVector = function() {
- g_test.assertArrayEquals([-2, 21, 10],
- g_math.columnMajor.mulMatrixVector(T, [1, -1, 2, 1]));
-};
-
-g_suite.testRowMajorMulVectorMatrix = function() {
- g_test.assertArrayEquals([-2, 21, 10],
- g_math.rowMajor.mulVectorMatrix([1, -1, 2, 1], T));
-};
-
-g_suite.testColumnMajorMulVectorMatrix = function() {
- g_test.assertArrayEquals([5, 9, 0, 1],
- g_math.columnMajor.mulVectorMatrix([1, -1, 2], T));
-};
-
-g_suite.testMulVectorVector = function() {
- g_test.assertArrayEquals([-1, 0, 6, -8],
- g_math.mulVectorVector([1, 2, 3, 4],
- [-1, 0, 2, -2]));
-};
-
-g_suite.testDivVectorVector = function() {
- g_test.assertArrayEquals([-0.5, 0, 2, -2],
- g_math.divVectorVector([-1, 0, 8, -10],
- [2, 3, 4, 5]));
-};
-
-g_suite.testOrthonormalize = function() {
- var W = g_math.orthonormalize([[1, 2, -1], [1, -2, 0], [2, 4, 1]]);
- g_test.assertTrue(matrixDiff(g_math.mulMatrixMatrix(W, g_math.transpose(W)),
- g_math.identity(3)) < 0.001);
- g_test.assertTrue(matrixDiff(g_math.mulMatrixMatrix(g_math.transpose(W), W),
- g_math.identity(3)) < 0.001);
- g_test.assertTrue(matrixDiff(
- g_math.orthonormalize([[1.01, -.01, 0], [0, 1.01, .01], [0, -0.1, 1.01]]),
- g_math.identity(3)) < 0.1);
-};
-
-function dehomogenize(v) {
- return [v[0] / v[3], v[1] / v[3], v[2] / v[3]];
-};
-
-function homogenize(v) {
- return [v[0], v[1], v[2], 1];
-};
-
-function push0(v) {
- return [v[0], v[1], v[2], 0];
-};
-
-function pop0(v) {
- return [v[0], v[1], v[2]];
-};
-
-g_suite.testPerspective = function() {
- var angle = 1;
- var aspect = 16 / 9;
- var zNear = 3;
- var zFar = 10;
-
- var P = g_math.matrix4.perspective(angle, aspect, zNear, zFar);
-
- // Points on the near clipping plane should get sent to points on the plane
- // z = 0, and points on the far clipping plane should get sent to points on
- // the plane z = 1.
- sendTest(P, [0, 0, -zNear], [0, 0, 0]);
- sendTest(P, [0, 0, -zFar], [0, 0, 1]);
-
- // The right edge of the near rectangular face of the frustum should get sent
- // to the point [1, 0, 0]
- sendTest(P, [zNear * aspect * Math.tan(angle / 2), 0, -zNear], [1, 0, 0]);
-
- // The top edge of the near rectangular face of the frustum should get sent
- // to the point [0, 1, 0]
- sendTest(P, [0, zNear * Math.tan(angle / 2), -zNear], [0, 1, 0]);
-};
-
-g_suite.testOrthographic = function() {
- var left = 3;
- var right = 5;
- var bottom = 4;
- var top = 6;
- var near = 2;
- var far = 100;
-
- var P = g_math.matrix4.orthographic(left, right, bottom, top, near, far);
-
- // Points on the near face of the viewing box should get sent to the plane
- // z = 0.
- sendTest(P, [left, bottom, -near], [-1, -1, 0]);
- sendTest(P, [right, bottom, -near], [1, -1, 0]);
- sendTest(P, [left, top, -near], [-1, 1, 0]);
-
- // Points on the far face of the viewing box should get sent to the plane
- // z = 1.
- sendTest(P, [left, bottom, -far], [-1, -1, 1]);
-};
-
-g_suite.testLookAt = function() {
- var eye = [1, 2, 4];
- var target = [1, -1, 3];
- var up = [0, 1, 1];
- var v = [];
-
- var M = g_math.matrix4.lookAt(eye, target, up);
-
- var U = g_math.matrix4.getUpper3x3(M);
- g_test.assertTrue(
- Math.abs(g_math.det(g_math.matrix4.getUpper3x3(M)) - 1) < 0.0001);
-
- // M rotation component should be orthogonal.
- g_test.assertTrue(matrixDiff(g_math.mulMatrixMatrix(U, g_math.transpose(U)),
- g_math.identity(3)) < 0.001);
-
- // M should send the eye to the origin.
- sendTest(M, eye, [0, 0, 0]);
-
- // M should send (target-eye) to point in the -z direction.
- v = g_math.mulVectorMatrix(push0(g_math.subVector(target, eye)), M);
- g_test.assertTrue(Math.abs(v[0]) < 0.0001);
- g_test.assertTrue(Math.abs(v[1]) < 0.0001);
- g_test.assertTrue(v[2] < 0);
-
- // M should send up into the zy plane with positive y.
- v = g_math.mulMatrixVector(M, push0(up));
- g_test.assertTrue(Math.abs(v[0]) < 0.0001);
- g_test.assertTrue(v[1] > 0);
-
- // Arguments with four entries should be accepted, so all the following should
- // be equal.
- var lookats = [
- g_math.matrix4.lookAt(homogenize(eye), homogenize(target), push0(up)),
- g_math.matrix4.lookAt(eye, homogenize(target), push0(up)),
- g_math.matrix4.lookAt(homogenize(eye), target, push0(up)),
- g_math.matrix4.lookAt(eye, target, push0(up)),
- g_math.matrix4.lookAt(homogenize(eye), homogenize(target), up),
- g_math.matrix4.lookAt(eye, homogenize(target), up),
- g_math.matrix4.lookAt(homogenize(eye), target, up),
- g_math.matrix4.lookAt(eye, target, up)
- ];
-
- for (var i = 0; i < 7; ++i)
- g_test.assertArrayEquals(lookats[i], lookats[i + 1]);
-};
-
-g_suite.testGetAndSetUpper3x3 = function() {
- var a = [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2], [1, 3, 2, 2]];
- var b = [[10, 11, 12], [13, 14, 15], [16, 17, 18]];
- var r = g_math.matrix4.setUpper3x3(a, b);
-
- g_test.assertTrue(r == a);
- g_test.assertArrayEquals([[10, 11, 12, 1],
- [13, 14, 15, -1],
- [16, 17, 18, 2],
- [1, 3, 2, 2]], a);
-
- g_test.assertArrayEquals(g_math.matrix4.getUpper3x3(a), b);
-};
-
-g_suite.testGetAndSetTranslation = function() {
- var a = [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2], [1, 3, 2, 2]];
- var t = [-4, -5, -6];
- var r = g_math.matrix4.setTranslation(a, t);
-
- g_test.assertTrue(r == a);
- g_test.assertArrayEquals([[1, 2, 1, 1],
- [3, 4, 5, -1],
- [-1, -3, 4, 2],
- [-4, -5, -6, 1]], a);
- g_test.assertArrayEquals(g_math.matrix4.getTranslation(a), t);
-};
-
-g_suite.testTransformPoint = function() {
- var m = [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2], [1, 3, 2, 2]];
- var v3 = [1, 2, 3];
-
- sendTest(m, v3, g_math.matrix4.transformPoint(m, v3));
-};
-
-g_suite.testTransformVector4 = function() {
- var m = [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2], [1, 3, 2, 2]];
- var v4 = [1, 2, 3, 4];
- var v3 = dehomogenize(v4);
-
- sendTest(m, v3, dehomogenize(g_math.matrix4.transformVector4(m, v4)));
-};
-
-g_suite.testTransformDirection = function() {
- // It is important that the last coordinate of the first three vectors of m be
- // 0, so that m is parallel-preserving.
- var m = [[1, 2, 1, 0], [3, 4, 5, 0], [-1, -3, 4, 0], [1, 3, 2, 2]];
- var v3 = [1, 2, 3];
-
- directionSendTest(m, v3, g_math.matrix4.transformDirection(m, v3));
-};
-
-g_suite.testTransformNormal = function() {
- // It is important that the last coordinate of the first three vectors of m be
- // 0, so that m is parallel-preserving.
- var m = [[1, 2, 1, 0], [3, 4, 5, 0], [-1, -3, 4, 0], [1, 3, 2, 2]];
- var v3 = [1, 2, 3];
-
- // Transform the direction by the inverse transpose and make sure we get the
- // same answer.
- var a = g_math.matrix4.transformDirection(
- g_math.inverse(g_math.transpose(m)), v3);
- var b = g_math.matrix4.transformNormal(m, v3);
-
- g_test.assertTrue(g_math.distance(a, b) < 0.001);
-};
-
-g_suite.testMatrix4Identity = function() {
- g_test.assertArrayEquals([[1, 0, 0, 0],
- [0, 1, 0, 0],
- [0, 0, 1, 0],
- [0, 0, 0, 1]], g_math.matrix4.identity());
-};
-
-g_suite.testRowAndColumn = function() {
- var a = [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2]];
-
- g_test.assertArrayEquals([-1, -3, 4, 2], g_math.rowMajor.row(a, 2));
- g_test.assertArrayEquals([2, 4, -3], g_math.rowMajor.column(a, 1));
-
- g_test.assertArrayEquals([2, 4, -3], g_math.columnMajor.row(a, 1));
- g_test.assertArrayEquals([-1, -3, 4, 2], g_math.columnMajor.column(a, 2));
-};
-
-g_suite.testComposition = function() {
- var b = [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2], [1, 3, 2, 2]];
- var a = g_math.matrix4.identity();
- var u = [1, 2, 3];
- var v = g_math.matrix4.transformPoint(a, g_math.matrix4.transformPoint(b, u));
-
- var r = g_math.matrix4.compose(a, b);
-
- g_test.assertTrue(r == a);
- sendTest(a, u, v);
-};
-
-g_suite.testCompose = function() {
- var m = [[5, 2, -4, 1], [1, 0, 0, -2], [5, 6, 3, 2], [-1, -1, 2, 3]];
- var b = [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2], [1, 3, 2, 2]];
- var a = g_math.matrix4.composition(b, m);
- var c = g_math.copyMatrix(b);
- g_math.matrix4.compose(c, m);
-
- g_test.assertTrue(matrixDiff(a, c) < 0.001);
-};
-
-g_suite.testTranslation = function() {
- var v = [1, 2, 3];
- var a = g_math.matrix4.identity();
- var r = g_math.matrix4.translate(a, v);
-
- g_test.assertTrue(r == a);
- g_test.assertArrayEquals(a, g_math.matrix4.translation(v));
- g_test.assertArrayEquals(g_math.identity(3), g_math.matrix4.getUpper3x3(a));
-
- sendTest(a, [0, 0, 0], v);
-};
-
-g_suite.testTranslate = function() {
- var v = [1, 2, 3];
- var b = [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2], [1, 3, 2, 2]];
- var a = g_math.matrix4.translation(v);
- var c = g_math.copyMatrix(b);
- g_math.matrix4.translate(c, v);
-
- composeTest(a, b, c);
-};
-
-g_suite.testScaling = function() {
- var v = [2, 3, 4];
- var a = g_math.matrix4.identity();
- var r = g_math.matrix4.scale(a, v);
-
- g_test.assertTrue(r == a);
- g_test.assertTrue(matrixDiff(a, g_math.matrix4.scaling(v)) < 0.001);
-
- sendTest(a, [1, 0, 0], [v[0], 0, 0]);
- sendTest(a, [0, 1, 0], [0, v[1], 0]);
- sendTest(a, [0, 0, 1], [0, 0, v[2]]);
-};
-
-g_suite.testScale = function() {
- var v = [2, 3, 4];
- var b = [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2], [1, 3, 2, 2]];
- var a = g_math.matrix4.scaling(v);
- var c = g_math.copyMatrix(b);
- g_math.matrix4.scale(c, v);
-
- composeTest(a, b, c);
-};
-
-g_suite.testRotationX = function() {
- var a = g_math.matrix4.identity();
- var r = g_math.matrix4.rotateX(a, Math.PI / 2);
-
- g_test.assertTrue(r == a);
- g_test.assertTrue(
- matrixDiff(a, g_math.matrix4.rotationX(Math.PI / 2)) < 0.001);
-
- sendTest(a, [1, 0, 0], [1, 0, 0]);
- sendTest(a, [0, 1, 0], [0, 0, 1]);
- sendTest(a, [0, 0, 1], [0, -1, 0]);
-};
-
-g_suite.testRotateX = function() {
- var angle = 1;
- var b = [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2], [1, 3, 2, 2]];
- var a = g_math.matrix4.rotationX(angle);
- var c = g_math.copyMatrix(b);
- g_math.matrix4.rotateX(c, angle);
-
- composeTest(a, b, c);
-};
-
-g_suite.testRotationY = function() {
- var a = g_math.matrix4.identity();
- var r = g_math.matrix4.rotateY(a, Math.PI / 2);
-
- g_test.assertTrue(r == a);
- g_test.assertTrue(
- matrixDiff(a, g_math.matrix4.rotationY(Math.PI / 2)) < 0.001);
-
- sendTest(a, [1, 0, 0], [0, 0, -1]);
- sendTest(a, [0, 1, 0], [0, 1, 0]);
- sendTest(a, [0, 0, 1], [1, 0, 0]);
-};
-
-g_suite.testRotateY = function() {
- var angle = 1;
- var b = [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2], [1, 3, 2, 2]];
- var a = g_math.matrix4.rotationY(angle);
- var c = g_math.copyMatrix(b);
- g_math.matrix4.rotateY(c, angle);
-
- composeTest(a, b, c);
-};
-
-g_suite.testRotationZ = function() {
- var a = g_math.matrix4.identity();
- var r = g_math.matrix4.rotateZ(a, Math.PI / 2);
-
- g_test.assertTrue(r == a);
- g_test.assertTrue(
- matrixDiff(a, g_math.matrix4.rotationZ(Math.PI / 2)) < 0.001);
-
- sendTest(a, [1, 0, 0], [0, 1, 0]);
- sendTest(a, [0, 1, 0], [-1, 0, 0]);
- sendTest(a, [0, 0, 1], [0, 0, 1]);
-};
-
-g_suite.testRotateZ = function() {
- var angle = 1;
- var b = [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2], [1, 3, 2, 2]];
- var a = g_math.matrix4.rotationZ(angle);
- var c = g_math.copyMatrix(b);
- g_math.matrix4.rotateZ(c, angle);
-
- composeTest(a, b, c);
-};
-
-g_suite.testRotationZYX = function() {
- var v = [1, 2, 3];
- var a = g_math.matrix4.identity();
- var r = g_math.matrix4.rotateZYX(a, v);
-
- g_test.assertTrue(r == a);
- g_test.assertTrue(matrixDiff(a, g_math.matrix4.rotationZYX(v)) < 0.001);
-
- var b = g_math.matrix4.identity();
- g_math.matrix4.rotateZ(b, v[2]);
- g_math.matrix4.rotateY(b, v[1]);
- g_math.matrix4.rotateX(b, v[0]);
-
- g_test.assertTrue(matrixDiff(a, b) < 0.001);
-};
-
-g_suite.testRotateZYX = function() {
- var v = [1, 2, 3];
- var b = [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2], [1, 3, 2, 2]];
- var a = g_math.matrix4.rotationZYX(v);
- var c = g_math.copyMatrix(b);
- g_math.matrix4.rotateZYX(c, v);
-
- composeTest(a, b, c);
-};
-
-g_suite.testAxisRotation = function() {
- var angle = 1;
-
- g_test.assertTrue(matrixDiff(g_math.matrix4.axisRotation([1, 0, 0], angle),
- g_math.matrix4.rotationX(angle)) < 0.001);
- g_test.assertTrue(matrixDiff(g_math.matrix4.axisRotation([0, 1, 0], angle),
- g_math.matrix4.rotationY(angle)) < 0.001);
- g_test.assertTrue(matrixDiff(g_math.matrix4.axisRotation([0, 0, 1], angle),
- g_math.matrix4.rotationZ(angle)) < 0.001);
-};
-
-g_suite.testAxisRotation111 = function() {
- var v = [1, 1, 1];
- var a = g_math.matrix4.identity();
- var r = g_math.matrix4.axisRotate(a, v, 2 * Math.PI / 3);
-
- g_test.assertTrue(r == a);
- g_test.assertTrue(
- matrixDiff(a, g_math.matrix4.axisRotation(v, 2 * Math.PI / 3)) < 0.001);
-
- sendTest(a, [1, 0, 0], [0, 1, 0]);
- sendTest(a, [0, 1, 0], [0, 0, 1]);
- sendTest(a, [0, 0, 1], [1, 0, 0]);
-};
-
-g_suite.testAxisRotate = function() {
- var v = [1, 2, 3];
- var angle = 1;
- var b = [[1, 2, 1, 1], [3, 4, 5, -1], [-1, -3, 4, 2], [1, 3, 2, 2]];
- var a = g_math.matrix4.axisRotation(v, angle);
- var c = g_math.copyMatrix(b);
- g_math.matrix4.axisRotate(c, v, angle);
-
- composeTest(a, b, c);
-};
-
-// Tests that the 4-by-4 homogenous matrix M sends the 3-vector v to the
-// 3-vector vM.
-function sendTestVM(M, v, vM) {
- g_test.assertTrue(matrixDiff([dehomogenize(
- g_math.mulVectorMatrix(homogenize(v), M))],
- [vM]) < 0.001);
-}
-
-// Tests that the 4-by-4 homogenous matrix M sends the 3-vector v to the
-// 3-vector Mv.
-function sendTestMV(M, v, Mv) {
- g_test.assertTrue(matrixDiff([dehomogenize(
- g_math.mulMatrixVector(M, homogenize(v)))], [Mv]) < 0.001);
-}
-
-// Tests that the 4-by-4 homogenous matrix M sends the 3-vector v to the
-// 3-vector Mv when v is interpreted as a direction.
-function directionSendTestVM(M, v, vM) {
- g_test.assertTrue(matrixDiff([pop0(
- g_math.mulVectorMatrix(push0(v), M))], [vM]) < 0.001);
-}
-
-// Tests that the 4-by-4 homogenous matrix M sends the 3-vector v to the
-// 3-vector Mv when v is interpreted as a direction.
-function directionSendTestMV(M, v, Mv) {
- g_test.assertTrue(matrixDiff([pop0(
- g_math.mulMatrixVector(M, push0(v)))], [Mv]) < 0.001);
-}
-
-// Tests whether if a is pre-composed with b, the result is c; assumes A * B
-// precomposes a with b, as in row major.
-function composeTestAB(a, b, c) {
- g_test.assertTrue(matrixDiff(g_math.mulMatrixMatrix(a, b), c) < 0.001);
-}
-
-// Tests whether if a is pre-composed with b, the result is c; assumes B * A
-// precomposes a with b, as in column major.
-function composeTestBA(a, b, c) {
- g_test.assertTrue(matrixDiff(g_math.mulMatrixMatrix(b, a), c) < 0.001);
-}
-
-window.onload = function() {
- window.g_test = o3djs.test;
- window.g_math = o3djs.math;
-
- // Whether or not a matrix transforms a vector by multiplying on
- // the right or on the left depends on the choice of row major or column
- // major. Tests which ask whether a matrix sends a point (or direction) to a
- // particular other point (or direction) do so by appealing to the function
- // sendTest (or directionSendTest). In row major mode, sendTest gets aliased
- // to sendTestVM, in column major mode, sendTest gets aliased to sendTestMV,
- // so in either mode, all the same tests should pass.
-
- window.sendTest = sendTestMV;
- window.directionSendTest = directionSendTestMV;
- window.composeTest = composeTestBA;
- o3djs.math.installColumnMajorFunctions();
- var columnMajorTestResult = g_test.runTests(g_suite);
-
- window.sendTest = sendTestVM;
- window.directionSendTest = directionSendTestVM;
- window.composeTest = composeTestAB;
- o3djs.math.installRowMajorFunctions();
- var rowMajorTestResult = g_test.runTests(g_suite);
-
- window.g_testResult = columnMajorTestResult && rowMajorTestResult;
-};
-
-</script>
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/no-rendergraph.html b/o3d/tests/selenium/tests/no-rendergraph.html
deleted file mode 100644
index dd20206..0000000
--- a/o3d/tests/selenium/tests/no-rendergraph.html
+++ /dev/null
@@ -1,80 +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.
--->
-
-<!--
-For checking what happens with no rendergraph.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-No Rendergraph.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- window.g_client = clientElements[0].client;
- window.g_testResult = true;
-}
-</script>
-</head>
-<body>
-<h1>No Rendergraph</h1>
-Area below should be a solid color.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/non-cachable-params.html b/o3d/tests/selenium/tests/non-cachable-params.html
deleted file mode 100644
index 14e8fdd..0000000
--- a/o3d/tests/selenium/tests/non-cachable-params.html
+++ /dev/null
@@ -1,250 +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.
--->
-
-<!--
-Example of multiple views into the same scene.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Non Cachable Params
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.pack');
-o3djs.require('o3djs.camera');
-o3djs.require('o3djs.scene');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfos = [];
-var g_pack;
-var g_o3d_width; // width of our client area
-var g_o3d_height; // height of our client area
-
-/**
- * Returns the path of where the file is located
- * with the trailing slash
- */
-function getCurrentPath() {
- var path = window.location.href;
- var index = path.lastIndexOf('/');
- return path.substring(0, index + 1);
-}
-
-/**
- * Loads a model into the transform graph and generates its corresponding entry
- * in the render graph when it is done loading.
- * @param {Pack} packfile_name filename of the collada model.
- * @param {string} file_name filename of the collada model.
- * @param {Transform} parent parent node in the transform graph to which to load
- * the model into
- */
-function loadModel(pack, file_name, parent) {
- // Get our full path to the model
- var model_path = getCurrentPath() + file_name;
-
- // Load the file given the full path, and call the callback function
- // when its done loading.
- o3djs.scene.loadScene(g_client, pack, parent, model_path, callback);
-
- /**
- * Our callback is called once the model has been loaded into memory
- * from the web or locally.
- * @param {!o3d.Pack} pack The pack that was passed in above.
- * @param {!o3d.Transform} parent The parent that was passed in above.
- * @param {*} exception null if loading succeeded.
- */
- function callback(pack, parent, exception) {
- if (exception) {
- alert('Could not load: ' + file_name + '\n' + exception);
- } else {
- // Get a cameraInfo (an object with a view and projection matrix)
- // using our javascript library function
- var cameraInfo = o3djs.camera.getViewAndProjectionFromCameras(
- parent,
- g_o3d_width / 2, // because this context only uses 1/2 the area
- g_o3d_height);
-
- // Copy the view and projection to the draw context of the first view.
- g_viewInfos[0].drawContext.view = cameraInfo.view;
- g_viewInfos[0].drawContext.projection = cameraInfo.projection;
-
- // Generate draw elements and setup material draw lists.
- o3djs.pack.preparePack(pack, g_viewInfos[0]);
-
- // for each effect, get a list of it's params and setup a param chain
- // for the SAS params
- var effects = pack.getObjectsByClassName('o3d.Effect');
- for (var ee = 0; ee < effects.length; ++ee) {
- var effect = effects[ee];
- var paramInfos = effect.getParameterInfo();
- for (var pp = 0; pp < paramInfos.length; ++pp) {
- var paramInfo = paramInfos[pp];
- if (paramInfo.sasClassName != "") {
- var param = effect.createParam(paramInfo.name, 'ParamMatrix4');
- var sas_param = effect.createParam(paramInfo.name + "_sas",
- paramInfo.sasClassName);
- param.bind(sas_param);
- }
- }
- }
- window.g_testResult = true;
- }
- }
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the model into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3d = clientElements[0];
- g_o3d = o3d.o3d;
- g_math = o3djs.math;
- g_client = o3d.client;
-
- // Initialize the sample javascript library.
- o3djs.base.init(o3d);
-
- // Get the width and height of our client area. We will need this to create
- // a projection matrix.
- g_o3d_width = o3d.clientWidth;
- g_o3d_height = o3d.clientHeight;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view for the left half of screen.
- g_viewInfos[0] = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot,
- [0.7, 0.2, 0.2, 1],
- 0,
- [0, 0, 0.5, 1]); // left half of screen.
-
- // Setup 3 areas. Each area needs a viewport, a tree traveral, 2 drawpasses
- // and although we could clear the screen once let's do it per viewport just
- // as an example. The original area is already setup except it needs a
- // viewport setting.
-
- // make the 2 right viewports
- for (var yy = 0; yy < 2; yy++) {
- var viewInfo = o3djs.rendergraph.createExtraView(
- g_viewInfos[0],
- [0.5, yy * 0.5, 0.5, 0.5], // right half top or bottom.
- [0.5, 0.2 + 0.5 * yy, 0.7 - 0.5 * yy, 1.0], // bg color.
- yy + 1); // after the other views.
-
- // save if off for later?
- g_viewInfos[g_viewInfos.length] = viewInfo;
-
- // Get the drawcontext for this area and set the view and
- // projection matrices.
- var drawContext = viewInfo.drawContext;
-
- if (yy == 0) {
- drawContext.projection = g_math.matrix4.perspective(
- 45 * 3.14159 / 180,
- (g_o3d_width * 0.5) / (g_o3d_height * 0.5),
- 0.1,
- 100);
- drawContext.view = g_math.matrix4.lookAt(
- [-10, 3, -15], // eye
- [0, 2, 0], // target
- [0, 1, 0]); // up
- } else {
- // lets make this one orthographic
- var aspect = g_o3d_width / g_o3d_height;
- drawContext.projection = g_math.matrix4.orthographic(
- -10,
- 10,
- -10 / aspect,
- 10 / aspect,
- 0,
- 100);
- // look directly from the front
- drawContext.view = g_math.matrix4.lookAt(
- [0, 5, 30], // eye
- [0, 5, 0], // target
- [0, 1, 0]); // up
- }
- }
-
- // Creates a transform to put our data on.
- var my_data_root = g_pack.createObject('Transform');
-
- // Connects our root to the client so that world matrices will
- // get calculated.
- my_data_root.parent = g_client.root;
-
- // Load the model into the transform graph as a child my_data_root
- loadModel(g_pack, '../../../samples/assets/yard.o3dtgz', my_data_root);
-}
-</script>
-</head>
-<body>
-<h1>Non Cachable Params</h1>
-<br/>
-Checks that non cachable param chains work by replacing all the standard (SAS)
-params with chains to those params. If they are not working the 3 views will
-show roughly the same image just with different aspect ratios.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 800px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/offscreen-test.html b/o3d/tests/selenium/tests/offscreen-test.html
deleted file mode 100644
index e1e3519..0000000
--- a/o3d/tests/selenium/tests/offscreen-test.html
+++ /dev/null
@@ -1,158 +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.
--->
-
-<!--
-Offscreen Test
-
-Make sure client areas that are not visible are not rendered.
-But that tick callbacks are called.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Offscreen Test.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = uninit;
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_clients = [];
-var g_packs = [];
-var g_viewInfos = [];
-var g_renderCounts = [0, 0];
-var g_tickCounts = [0, 0];
-var g_testResult;
-
-function onRender(index) {
- g_viewInfos[index].clearBuffer.clearColor = [Math.random(),
- Math.random(),
- Math.random(),
- 1];
- g_renderCounts[index] += 1;
-
- // After 30 frames check that the offscreen client didn't render.
- if (g_renderCounts[0] > 30) {
- g_testResult = g_renderCounts[1] < 5 &&
- g_tickCounts[1] > 25 &&
- g_tickCounts[0] > 25;
- }
-}
-
-function onTick(index) {
- g_tickCounts[index] += 1;
-}
-
-/**
- * Creates the client areas.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the model into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- for (var ii = 0; ii < clientElements.length; ++ii) {
- var o3dElement = clientElements[ii];
-
- g_clients[ii] = o3dElement.client;
- g_packs[ii] = g_clients[ii].createPack();
-
- g_viewInfos[ii] = o3djs.rendergraph.createBasicView(
- g_packs[ii],
- g_clients[ii].root,
- g_clients[ii].renderGraphRoot);
-
- setRenderCallback(ii);
- setTickCallback(ii);
- }
-}
-
-/**
- * Sets the render callback such that it has access to the client.
- * @param {!o3d.client} client The client to set the render callback on.
- */
-function setRenderCallback(index) {
- g_clients[index].setRenderCallback(function() { onRender(index); });
-}
-
-/**
- * Sets the tick callback such that it has access to the client.
- * @param {!o3d.client} client The client to set the tick callback on.
- */
-function setTickCallback(index) {
- g_clients[index].setTickCallback(function() { onTick(index); });
-}
-
-/**
- * Cleans up.
- */
-function uninit() {
- for (var ii = 0; ii < g_clients.length; ++ii) {
- g_clients[ii].clearRenderCallback();
- g_clients[ii].clearTickCallback();
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Offscreen Test</h1>
-This test verifies that client areas offscreen do not render but that tick
-callbacs get called.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d-on-screen" style="width: 100px; height: 100px;"></div>
-<div style="width: 100px; height: 4000px; border: red 1px solid;"></div>
-<div id="o3d-off-screen" style="width: 100px; height: 100px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/ownership-test.html b/o3d/tests/selenium/tests/ownership-test.html
deleted file mode 100644
index 298ef77..0000000
--- a/o3d/tests/selenium/tests/ownership-test.html
+++ /dev/null
@@ -1,210 +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.
--->
-
-<!--
-A Selenium test to make that streams lasting past the client don't crash.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Ownership Test
-</title>
-<!-- Our javascript code -->
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-
-window.onload = init;
-
-// global variables
-var g_testResult;
-var g_streamArrays = [];
-var g_effectInfo;
-
-/**
- * Creates a o3d object.
- */
-function init() {
- // Create a client.
- var clientSpan = document.getElementById('client');
- var objElem = o3djs.util.createClient(clientSpan);
- objElem.style.width = '60px';
- objElem.style.height = '60px';
- objElem.id = 'o3d';
- objElem.name ='o3d';
-
- // wait for the browsers to settle down.
- var clearId = window.setInterval(function() {
- if (document.o3d.o3d) {
- window.clearInterval(clearId);
- test();
- }
-
- }, 10);
-}
-
-function makeBufferAndFreeClient() {
- // Initialize global variables and libraries.
- var o3d = document.o3d.o3d;
- var client = document.o3d.client;
-
- // Create a g_pack to manage our resources/assets
- var pack = client.createPack();
-
- var effect = pack.createObject('Effect');
- effect.loadFromFXString('' +
- 'float var1;\n' +
- 'float2 var2;\n' +
- 'float3 var3;\n' +
- 'float4 var4;\n' +
- 'struct a2v {\n' +
- ' float4 pos : POSITION;\n' +
- '};\n'+
- 'struct v2f {\n' +
- ' float4 pos : POSITION;\n' +
- '};\n' +
- 'v2f vsMain(a2v IN) {\n' +
- ' v2f OUT;\n' +
- ' OUT.pos = IN.pos;\n' +
- ' return OUT;\n' +
- '}\n' +
- 'float4 psMain(v2f IN): COLOR {\n' +
- ' return float4(var1, var2.y, var3.z, var4.w);\n' +
- '}\n' +
- '// #o3d VertexShaderEntryPoint vsMain\n' +
- '// #o3d PixelShaderEntryPoint psMain\n' +
- '// #o3d MatrixLoadOrder RowMajor\n');
- g_effectInfo = effect.getParameterInfo();
-
-
- // Let's create a lot of buffers just to try to make it crash.
- for (var ii = 0; ii < 100; ii++) {
- var bank = pack.createObject('StreamBank');
- var buffer = pack.createObject('VertexBuffer');
- var field = buffer.createField('FloatField', 3);
-
- var vertsArray = [
- // Triangle 1
- -0.5, 0.5, 0,
- -0.5, -0.5, 0,
- 0.5, -0.5, 0,
-
- // Triangle 2
- 0.5, 0.5, 0,
- -0.5, 0.5, 0,
- 0.5, -0.5, 0
- ];
- buffer.set(vertsArray);
- bank.setVertexStream(o3d.Stream.POSITION,
- 0,
- field,
- 0);
-
- // copy the streams out so they last past the client.
- g_streamArrays[ii] = bank.vertexStreams;
- }
-
- pack.destroy();
-
- var clientSpan = document.getElementById('client');
- var clientNode = clientSpan.childNodes[0];
- clientSpan.removeChild(clientNode);
-}
-
-function isDefined(variable) {
- return (typeof(variable) == "undefined") ? false : true;
-}
-
-function test() {
- makeBufferAndFreeClient();
-
- // check that we can still access the stream objects.
- var caught = false;
- try {
- // Chrome does not always throw exceptions when methods/properties on NPAPI
- // objects fail, so we explicitly throw here.
- var stream = g_streamArrays[1][0];
- if (!isDefined(stream))
- throw 'error';
-
- // The stream object may exist as an empty container, so probe its normally
- // expected properties - they should no longer exist.
- var semantic = stream.semantic;
- var field = stream.field;
-
- // The object was deleted, so both of its properties should not exist.
- if (!isDefined(semantic) && !isDefined(field))
- throw 'error'
- } catch (e) {
- // We should always get here unless there is a bug.
- caught = true;
- }
-
- var caught2 = false;
- try {
- var effectInfo = g_effectInfo[0];
- var name = effect.name;
- if (!isDefined(name)) {
- throw 'error';
- }
- } catch(e) {
- // We should always get here unless there is a bug.
- caught2 = true;
- }
-
- // This should free the Stream objects.
- g_streamArrays = null;
-
- // attempt to allocate lots of stuff to hopefully force the browser
- // to garbage collect. If there is a bug we should crash here.
- var array = {};
- for (var ii = 0; ii < 100000; ii++) {
- array['abced' + ii] = 'this is a waste of memory';
- }
-
- if (caught && caught2)
- document.getElementById('testStatus').innerHTML = "Finished - Passed";
- else
- document.getElementById('testStatus').innerHTML = "Finished - Failed";
- g_testResult = caught;
-}
-
-</script>
-</head>
-<body>
-<h1>Ownership Test</h1>
-<div id="client" style="width: 60px; height 60px;"></div>
-<div>Status: <span id="testStatus">--running--</span></div>
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/param-array-test.html b/o3d/tests/selenium/tests/param-array-test.html
deleted file mode 100644
index a5fd6d8..0000000
--- a/o3d/tests/selenium/tests/param-array-test.html
+++ /dev/null
@@ -1,307 +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.
--->
-
-<!--
-Param Array Test
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Param Array Test.
-</title>
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.effect');
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-
-/**
- * Creates the client area.
- */
-function init() {
- // Comment out the line below to run the sample in the browser
- // JavaScript engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
- o3djs.util.makeClients(initStep2, 'FloatingPointTextures,NotAntiAliased');
-}
-
-/**
- * Initializes O3D, loads an effect, creates some textures
- * and quads to display them.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Set window.g_client as well. Otherwise when the sample runs in
- // V8, selenium won't be able to find this variable (it can only see
- // the browser environment).
- window.g_client = g_client = o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- var clientWidth = g_client.width;
- var clientHeight = g_client.height;
-
- // The + 0.5 makes this pixel aligned.
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -clientWidth * 0.5 + 0.5,
- clientWidth * 0.5 + 0.5,
- -clientHeight * 0.5 + 0.5,
- clientHeight * 0.5 + 0.5,
- 0.001,
- 1000);
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 500, 0], // eye
- [0, 0, 0], // target
- [0, 0, -1]); // up
-
- var textures = [];
- for (var ii = 0; ii < 2; ++ii) {
- var texture = g_pack.createTexture2D(1, 1, g_o3d.Texture.ARGB8, 1, false);
- texture.set(0, [ii, 0.7, 0.9, 1]);
- textures[ii] = texture;
- }
-
- for (var ii = 0; ii < 2; ++ii) {
- var effect = g_pack.createObject('Effect');
- effect.loadFromFXString(o3djs.util.getElementContentById('fx' + (ii + 1)));
-
- // Create a Material for the effect.
- var material = g_pack.createObject('Material');
-
- // Set the material's drawList for transparent objects.
- material.drawList = g_viewInfo.zOrderedDrawList;
-
- // Apply the effect to this material.
- material.effect = effect;
-
- // Create the params that effect requires on the material.
- o3djs.effect.createUniformParameters(g_pack, effect, material);
-
- // Create a quad.
- var shape = o3djs.primitives.createPlane(g_pack,
- material,
- 1,
- 1,
- 1,
- 1);
-
- if (ii == 0) {
- var paramArray = material.getParam('colors1').value;
- paramArray.getParam(0).value = 0.3;
- paramArray.getParam(1).value = 0.7;
- var paramArray = material.getParam('colors2').value;
- paramArray.getParam(0).value = [1, 0.5];
- paramArray.getParam(1).value = [0.5, 1];
- var paramArray = material.getParam('colors3').value;
- paramArray.getParam(0).value = [1, 1, 0];
- paramArray.getParam(1).value = [1, 0, 1];
- var paramArray = material.getParam('colors4').value;
- paramArray.getParam(0).value = [1, 0, 0, 1];
- paramArray.getParam(1).value = [0, 0, 1, 1];
- } else {
- var paramArray = material.getParam('colorsb').value;
- paramArray.getParam(0).value = true;
- paramArray.getParam(1).value = false;
- var paramArray = material.getParam('colorsi').value;
- paramArray.getParam(0).value = 254;
- paramArray.getParam(1).value = 255;
- var paramArray = material.getParam('colors4x4').value;
- paramArray.getParam(0).value = [[0, 0, 0, 0],
- [0, 0, 0, 0],
- [0, 0, 0, 0],
- [0, 1, 1, 1]];
- paramArray.getParam(1).value = [[0, 0, 0, 0],
- [0, 0, 0, 0],
- [0, 0, 0, 0],
- [0.5, 0.3, 0.3, 1]];
- var paramArray = material.getParam('texSamplers').value;
- paramArray.getParam(0).value.texture = textures[0];
- paramArray.getParam(1).value.texture = textures[1];
- }
-
- var transform = g_pack.createObject('Transform');
- transform.translate(-100 + ii * 200, 0, 0);
- transform.scale(180, 1, 360);
- transform.parent = g_client.root;
- transform.addShape(shape);
- }
-
- window.g_testResult = true; // for selenium testing.
-}
-
-</script>
-</head>
-<body onload="init()">
-<h1>Param Array Test</h1>
-<br/>
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 400px; height: 400px;"></div>
-<!-- End of O3D plugin -->
-<script type="test/o3deffect" id="fx1">
-float colors1[2];
-float2 colors2[2];
-float3 colors3[2];
-float4 colors4[2];
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-
-// input parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-// input parameters for our pixel shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-/**
- * The vertex shader
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(input.position, worldViewProjection);
- output.texcoord = input.texcoord;
- return output;
-}
-
-bool segment(float id, float position) {
- return position * 4 >= id && position * 4 < (id + 1);
-}
-
-/**
- * The pixel shader
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- if (segment(0, input.texcoord.y)) {
- return float4(input.texcoord.x > 0.5 ? colors1[1].xxx : colors1[0].xxx, 1);
- }
- if (segment(1, input.texcoord.y)) {
- return float4(input.texcoord.x > 0.5 ? colors2[1] : colors2[0], 0, 1);
- }
- if (segment(2, input.texcoord.y)) {
- return float4(input.texcoord.x > 0.5 ? colors3[1] : colors3[0], 1);
- }
- return input.texcoord.x > 0.5 ? colors4[1] : colors4[0];
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
-</script>
-<script type="test/o3deffect" id="fx2">
-float4x4 colors4x4[2];
-int colorsi[2];
-bool colorsb[2];
-sampler texSamplers[2];
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-
-// input parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-// input parameters for our pixel shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-/**
- * The vertex shader
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(input.position, worldViewProjection);
- output.texcoord = input.texcoord;
- return output;
-}
-
-bool segment(float id, float position) {
- return position * 4 >= id && position * 4 < (id + 1);
-}
-
-/**
- * The pixel shader
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- if (segment(0, input.texcoord.y)) {
- return input.texcoord.x > 0.5 ? colors4x4[1][3] : colors4x4[0][3];
- }
- if (segment(1, input.texcoord.y)) {
- return float4(input.texcoord.x > 0.5 ? colorsb[1] : colorsb[0], 0, 0, 1);
- }
- if (segment(2, input.texcoord.y)) {
- return float4((input.texcoord.x > 0.5 ? colorsi[1] : colorsi[0]) / 255,
- 0, 0, 1);
- }
- float4 t0 = tex2D(texSamplers[0], input.texcoord);
- float4 t1 = tex2D(texSamplers[1], input.texcoord);
- return input.texcoord.x > 0.5 ? t1 : t0;
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
-</script>
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/pixel-perfection.html b/o3d/tests/selenium/tests/pixel-perfection.html
deleted file mode 100644
index a1e84b0..0000000
--- a/o3d/tests/selenium/tests/pixel-perfection.html
+++ /dev/null
@@ -1,337 +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.
--->
-
-<!--
-O3D Pixel Perfection Test
-
-This test generates some shapes that should be able to be rendered
-identically on all the platforms that we support. It tests fill
-coverage, zbuffer coverage, blending and color and brightness fidelity.
-
-It purposly does not test things like anti-aliasing and texture
-sampling, because those vary too much from vendor to vendor, and
-because they are tested adequately in other tests.
-
-TODO: Anti-aliasing should be turned off for this test, when
-we have a way to do that.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Pixel Perfection
-</title>
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.effect');
-o3djs.require('o3djs.material');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.util');
-
-// global variables
-var g_o3dElement;
-var g_client;
-var g_o3d;
-var g_math;
-var g_pack;
-var g_viewInfo;
-
-var g_vertexShaderMaterial;
-var g_lightPosition = [0, 0, 12];
-var g_eyePosition = [0, 0, 12];
-
-/**
- * Creates the client area.
- */
-function initClient() {
- window.g_finished = false; // for selenium testing.
-
- // Runs the sample in V8. Comment out this line to run it in the browser
- // JavaScript engine, for example if you want to debug it.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
-
- o3djs.util.makeClients(main, 'NotAntiAliased');
-}
-
-/**
- * Initializes global variables, positions camera, draws shapes.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function main(clientElements) {
- // Init global variables.
- initGlobals(clientElements);
-
- // Set up the view and projection transformations.
- initContext();
-
- // Add the shapes to the transform hierarchy.
- createShapes();
-
- window.g_testResult = true; // for selenium testing.
-}
-
-/**
- * Initializes global variables and libraries.
- */
-function initGlobals(clientElements) {
- g_o3dElement = clientElements[0];
- window.g_client = g_client = g_o3dElement.client;
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
-
- // Create a pack to manage the objects created.
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- // Set the background color to white for more contrast.
- g_viewInfo.clearBuffer.clearColor = [1, 1, 1, 1];
-
- // Create and load the effect.
- var effect = g_pack.createObject('Effect');
- var vertexShaderString = o3djs.util.getElementContentById('vertexShader');
- effect.loadFromFXString(vertexShaderString);
- // Create a material for it.
- g_vertexShaderMaterial = g_pack.createObject('Material');
-
- // Set the material's drawList
- g_vertexShaderMaterial.drawList = g_viewInfo.performanceDrawList;
-
- // Apply our effect to this material. The effect tells the 3D hardware
- // which shader to use.
- g_vertexShaderMaterial.effect = effect;
-
- // Create the parameters the effect needs on the material.
- effect.createUniformParameters(g_vertexShaderMaterial);
-}
-
-/**
- * Sets up reasonable view and projection matrices.
- */
-function initContext() {
- // Set up a perspective transformation for the projection.
- g_viewInfo.drawContext.projection = g_math.matrix4.perspective(
- g_math.degToRad(30), // 30 degree frustum.
- g_o3dElement.clientWidth / g_o3dElement.clientHeight, // Aspect ratio.
- 1, // Near plane.
- 5000); // Far plane.
-
- // Set up our view transformation to look towards the world origin where the
- // primitives are located.
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- g_eyePosition, // eye
- [0, 0, 0], // target
- [0, 1, 0]); // up
-}
-
-/**
- * Creates a phong material based on the given single color.
- * @param {Array} baseColor An array with 4 entries, the R,G,B, and A components
- * of a color.
- * @return {Material} A phong material whose overall pigment is baseColor.
- */
-function createMaterial(baseColor) {
- // Create a material.
- var material = o3djs.material.createBasicMaterial(
- g_pack,
- g_viewInfo,
- baseColor,
- baseColor[3] != 1.0);
-
- return material;
-}
-
-/**
- * Creates shapes using the primitives utility library, and adds them to the
- * transform graph at the root node.
- */
-function createShapes() {
- var cube = o3djs.primitives.createRainbowCube(
- g_pack,
- g_vertexShaderMaterial,
- Math.sqrt(2));
-
- var sphere = o3djs.primitives.createSphere(
- g_pack,
- createMaterial([1, 0, 0, 1]),
- 1.0, // Radius of the sphere.
- 30, // Number of meridians.
- 20); // Number of parallels.
-
- var plane1 = o3djs.primitives.createPlane(
- g_pack,
- createMaterial([0, 1, 1, 1]),
- 2.5, // Width.
- 2.5, // Depth.
- 3, // Horizontal subdivisions.
- 3); // Vertical subdivisions.
-
- var plane2 = o3djs.primitives.createPlane(
- g_pack,
- createMaterial([0, .5, 0, 1]),
- 2.5, // Width.
- 2.5, // Depth.
- 3, // Horizontal subdivisions.
- 3); // Vertical subdivisions.
-
- var transPlane1 = o3djs.primitives.createPlane(
- g_pack,
- createMaterial([0, 1, 1, .1]),
- 2.5, // Width.
- 2.5, // Depth.
- 3, // Horizontal subdivisions.
- 3); // Vertical subdivisions.
-
- var transPlane2 = o3djs.primitives.createPlane(
- g_pack,
- createMaterial([0, .5, 0, .1]),
- 2.5, // Width.
- 2.5, // Depth.
- 3, // Horizontal subdivisions.
- 3); // Vertical subdivisions.
-
- var disc1 = o3djs.primitives.createDisc(
- g_pack,
- createMaterial([0, 0, 0, 0.25]),
- 1, // Radius.
- 50, // Divisions.
- 2, // Stacks.
- 1, // Start Stack.
- 1); // Stack Power.
-
- var disc2 = o3djs.primitives.createDisc(
- g_pack,
- createMaterial([0, 0, 0, 1]),
- 1, // Radius.
- 50, // Divisions.
- 2, // Stacks.
- 1, // Start Stack.
- 1); // Stack Power.
-
- // Add the shapes to the transforms.
- var transformTable = [
- {shape: cube, translation: [-2, 1, 0],
- rotation: [Math.PI / 4, Math.PI / 4, 0]},
- {shape: sphere, translation: [0, 1, 0], rotation: [0, 0, 0]},
- {shape: plane1, translation: [2, 1, 0],
- rotation: [0.99 * Math.PI / 2, 0, 0]},
- {shape: plane2, translation: [2, 1, 0], rotation: [Math.PI / 2, 0, 0]},
- {shape: transPlane1, translation: [-2, -1, -0.1],
- rotation: [0.99 * Math.PI / 2, 0, 0]},
- {shape: transPlane2, translation: [-2, -1, -0.1],
- rotation: [Math.PI / 2, 0, 0]},
- {shape: disc1, translation: [0, -1, 0], rotation: [Math.PI / 2, 0, 0]},
- {shape: disc2, translation: [2, -1, 0], rotation: [Math.PI / 2, 0, 0]}
- ];
-
- for (var tt = 0; tt < transformTable.length; ++tt) {
- var transform = g_pack.createObject('Transform');
- transform.addShape(transformTable[tt].shape);
- transform.translate(transformTable[tt].translation);
- transform.rotateX(transformTable[tt].rotation[0]);
- transform.rotateY(transformTable[tt].rotation[1]);
- transform.rotateZ(transformTable[tt].rotation[2]);
- transform.parent = g_client.root;
- }
-}
-
-
-</script>
-</head>
-<body onload="initClient()">
-<h1>Pixel Perfection</h1>
-<p>This test generates some shapes that should be able to be rendered
-identically on all the platforms that we support. It tests things
-like fill coverage, zbuffer coverage, blending and color/brightness
-fidelity.</p>
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 600px; height: 600px;"></div>
-<!-- End of O3D plugin -->
-<!-- Start of effect -->
-<textarea id="vertexShader" name="vertexShader" cols="80" rows="20"
- style="display: none;">
-// The 4x4 world view projection matrix.
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-
-// input parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float4 color : COLOR;
-};
-
-// input parameters for our pixel shader
-// also the output parameters for our vertex shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float4 color: COLOR;
-};
-
-/**
- * Vertex Shader - our vertex shader
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- /**
- * Our vertex shader projects the vertices onto the screen.
- * We return its color unchanged.
- */
- PixelShaderInput output;
-
- output.position = mul(input.position, worldViewProjection);
- output.color = input.color;
- return output;
-}
-
-/**
- * pixel shader does nothing but return whatever color it was given.
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return input.color;
-}
-
-// Here we tell our effect file the functions
-// which specify our vertex and pixel shaders.
-
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
-</textarea>
-<!-- End of effect -->
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/quaternion-test.html b/o3d/tests/selenium/tests/quaternion-test.html
deleted file mode 100644
index 2b2223f..0000000
--- a/o3d/tests/selenium/tests/quaternion-test.html
+++ /dev/null
@@ -1,336 +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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Quaternion Test
-</title>
-</head>
-<body>
-<h1>Quaternion Test</h1>
-This tests the quaternion utility library.
-<br/>
-<script type="text/javascript"
- src="../../../samples/o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.quaternions');
-o3djs.require('o3djs.test');
-
-var g_suite = {};
-
-g_suite.testType = function() {
- g_test.assertEquals(g_quat.mathType(1), "Scalar");
- g_test.assertEquals(g_quat.mathType([1, 2, 3, 4]), "Quaternion");
-};
-
-g_suite.testNegative = function() {
- g_test.assertArrayEquals([0, 6, 7, -1], g_quat.negative([0, -6, -7, 1]));
-};
-
-g_suite.testCopy = function() {
- var a = [0, 6, 7, 1];
- var b = g_quat.copy(a);
- g_test.assertArrayEquals(a, b);
- g_test.assertFalse(a == b);
-};
-
-g_suite.testAddQuaternions = function() {
- g_test.assertArrayEquals([0, 6, 7, 1],
- g_quat.add([1, 2, 3, 2], [-1, 4, 4, -1]));
- g_test.assertArrayEquals([1, -1, -1, 2],
- g_quat.add([0, 0, 0, 0], [1, -1, -1, 2]));
-};
-
-g_suite.testAddQuaternionsAndScalars = function() {
- g_test.assertArrayEquals([0, 6, 7, 2], g_quat.add([0, 6, 7, 1], 1));
- g_test.assertArrayEquals([0, 6, 7, 2], g_quat.add(1, [0, 6, 7, 1]));
-};
-
-g_suite.testSubQuaternions = function() {
- g_test.assertArrayEquals([2, -2, -1, 4],
- g_quat.sub([1, 2, 3, 4], [-1, 4, 4, 0]));
-};
-
-g_suite.testSubQuaternionsAndScalars = function() {
- g_test.assertArrayEquals([0, 6, 7, 0], g_quat.sub([0, 6, 7, 1], 1));
- g_test.assertArrayEquals([0, -6, -7, 0], g_quat.sub(1, [0, 6, 7, 1]));
-};
-
-g_suite.testMulQuaternions = function() {
- // 2*3 = 6
- g_test.assertArrayEquals([0, 0, 0, 6],
- g_quat.mul([0, 0, 0, 2], [0, 0, 0, 3]));
-
- // i^2 = -1
- g_test.assertArrayEquals([0, 0, 0, -1],
- g_quat.mul([1, 0, 0, 0], [1, 0, 0, 0]));
-
- // j^2 = -1
- g_test.assertArrayEquals([0, 0, 0, -1],
- g_quat.mul([0, 1, 0, 0], [0, 1, 0, 0]));
-
- // k^2 = -1
- g_test.assertArrayEquals([0, 0, 0, -1],
- g_quat.mul([0, 0, 1, 0], [0, 0, 1, 0]));
-
- // i*j = k
- g_test.assertArrayEquals([0, 0, 1, 0],
- g_quat.mul([1, 0, 0, 0], [0, 1, 0, 0]));
-};
-
-g_suite.testMulQuaternionsAndScalars = function() {
- g_test.assertArrayEquals([2, 4, 6, 8], g_quat.mul([1, 2, 3, 4], 2));
- g_test.assertArrayEquals([2, 4, 6, 8], g_quat.mul(2, [1, 2, 3, 4]));
-};
-
-g_suite.testDivQuaternions = function() {
- var q = [-1, 5, -4, 2];
- var r = [4, 4, 2, -2];
- assertQuaternionsClose(r, g_quat.mul(g_quat.div(r, q), q));
-};
-
-g_suite.testDivQuaternionScalar = function() {
- g_test.assertArrayEquals([0.5, 1, 1.5, 2], g_quat.div([1, 2, 3, 4], 2));
-};
-
-g_suite.testDivScalarQuaternion = function() {
- var q = [4, 2, -1, 7];
- var k = 3;
- assertQuaternionsClose([0, 0, 0, k], g_quat.mul(q, g_quat.div(k, q)));
- assertQuaternionsClose([0, 0, 0, k], g_quat.mul(g_quat.div(k, q), q));
-};
-
-g_suite.testDivDirection = function() {
- var q = [4, 2, -1, 7];
- var r = [4, 4, 2, -2];
- assertQuaternionsClose(g_quat.div(q, r), g_quat.mul(q, g_quat.div(1, r)));
-};
-
-g_suite.testLength = function() {
- g_test.assertEquals(13, g_quat.length([5, 12, 0, 0]));
- g_test.assertEquals(13, g_quat.length([0, 0, 5, 12]));
- g_test.assertClose(Math.sqrt(30), g_quat.length([1, 2, 3, 4]));
-};
-
-g_suite.testLengthSquared = function() {
- g_test.assertEquals(30, g_quat.lengthSquared([1, 2, 3, 4]));
-};
-
-g_suite.testNormalize = function() {
- g_test.assertTrue(compareWithTolerance(1,
- g_quat.length(g_quat.normalize([1, 2, 3, 4])), 1e-4));
-};
-
-g_suite.testConjugate = function() {
- g_test.assertArrayEquals([-1, -2, -3, 4], g_quat.conjugate([1, 2, 3, 4]));
-};
-
-g_suite.testRotationX = function() {
- var q = g_quat.rotationX(Math.PI / 2);
- var v = [0, 1, 0, 0]; // Y rotated around the X axis should be Z.
- assertVectorsClose(g_quat.mul(q, g_quat.div(v, q)), [0, 0, 1, 0]);
-};
-
-g_suite.testRotationY = function() {
- var q = g_quat.rotationY(Math.PI / 2);
- var v = [0, 0, 1, 0]; // Z rotated around the Y axis should be X.
- assertVectorsClose(g_quat.mul(q, g_quat.div(v, q)), [1, 0, 0, 0]);
-};
-
-g_suite.testRotationZ = function() {
- var q = g_quat.rotationZ(Math.PI / 2);
- var v = [1, 0, 0, 0]; // X rotated around the Z axis should be Y.
- assertVectorsClose(g_quat.mul(q, g_quat.div(v, q)), [0, 1, 0, 0]);
-};
-
-g_suite.testRotationVarious = function() {
- var v = g_quat.rotationX(0);
- assertMatricesClose(g_math.matrix4.rotationX(1),
- g_quat.quaternionToRotation(g_quat.rotationX(1)));
- assertMatricesClose(g_math.matrix4.rotationY(1),
- g_quat.quaternionToRotation(g_quat.rotationY(1)));
- assertMatricesClose(g_math.matrix4.rotationZ(1),
- g_quat.quaternionToRotation(g_quat.rotationZ(1)));
- assertMatricesClose(g_math.matrix4.identity(),
- g_quat.quaternionToRotation([0, 0, 0, 1]));
-
- var axis = [1, -4, 2];
- var angle = 3;
- assertMatricesClose(
- g_math.matrix4.axisRotation(axis, angle),
- g_quat.quaternionToRotation(g_quat.axisRotation(axis, angle)));
-};
-
-g_suite.testAxisRotation = function() {
- var q = g_quat.axisRotation([1, 1, 1], 2 * Math.PI / 3);
- assertVectorsClose(g_quat.mul(q, g_quat.div([1, 0, 0, 0], q)), [0, 1, 0, 0]);
- assertVectorsClose(g_quat.mul(q, g_quat.div([0, 1, 0, 0], q)), [0, 0, 1, 0]);
- assertVectorsClose(g_quat.mul(q, g_quat.div([0, 0, 1, 0], q)), [1, 0, 0, 0]);
-};
-
-g_suite.testQuaternionToRotation = function() {
- // The quaternion 1, should give the identity transformation.
- assertMatricesClose(g_math.matrix4.identity(),
- g_quat.quaternionToRotation([0, 0, 0, 1]));
-
- // Each of i, j, and k should rotate 180 degrees around the x, y and z axes
- // (respectively).
- assertMatricesClose(g_math.matrix4.rotationX(Math.PI),
- g_quat.quaternionToRotation([1, 0, 0, 0]));
- assertMatricesClose(g_math.matrix4.rotationY(Math.PI),
- g_quat.quaternionToRotation([0, 1, 0, 0]));
- assertMatricesClose(g_math.matrix4.rotationZ(Math.PI),
- g_quat.quaternionToRotation([0, 0, 1, 0]));
-
- // Pick an arbitrary point v and quaternion q.
- var v = [1, 2, 3, 1];
- var q = [2, -7, 4, -3];
-
- // Convert the vector to a quatnerion, apply q, and convert back.
- var t1 = toPoint(g_quat.div(g_quat.mul(q, toQuat(v)), q));
- // Also apply the matrix obtained from quaternionToRotation.
- var t2 = g_math.mulVectorMatrix(v, g_quat.quaternionToRotation(q));
-
- // Results should be the same.
- assertVectorsClose(t1, t2);
-};
-
-g_suite.testRotationToQuaternion = function() {
- // Start with a bunch of haphazard rotation matrices.
- var matrices = [g_math.matrix4.identity(),
- g_math.matrix4.axisRotation([1, -2, 0], 1),
- g_math.matrix4.axisRotation([2, -4, -1], -.1),
- g_math.matrix4.axisRotation([-1, -4, -1], 1),
- g_math.matrix4.axisRotation([-1, -3, 2], .1),
- g_math.matrix4.axisRotation([2, -7, -1], -5),
- g_math.matrix4.axisRotation([1, -7, 6], .5),
- g_math.matrix4.axisRotation([-2, 7, -6], 3),
- g_math.matrix4.axisRotation([-2, -2, -6], -3),
- g_math.matrix4.axisRotation([-4, -2, 3], .4),
- g_math.matrix4.axisRotation([-1, -2, -3], -1)
- ];
-
- // Test each one.
- for (var i = 0; i < matrices.length; ++i){
- toQuaternionAndBack(matrices[i]);
- }
-};
-
-function toQuaternionAndBack(m1)
-{
- // Convert the matrix to a quaternion.
- var q = g_quat.rotationToQuaternion(m1);
-
- // Then convert back.
- var m2 = g_quat.quaternionToRotation(q);
-
- // Assert that you get the same matrix you started with.
- assertMatricesClose(m1, m2);
-};
-
-g_suite.testInverse = function() {
- var q = [1, 2, 3, 4];
-
- // The inverse quaternion should give you the inverse matrix.
- var m1 = g_quat.quaternionToRotation(g_quat.inverse(q));
- var m2 = g_math.inverse(g_quat.quaternionToRotation(q));
-
- assertMatricesClose(m1, m2);
-};
-
-// Asks if two numbers are within a tolerance of eachother.
-function compareWithTolerance(a, b, tol) {
- return Math.abs(a-b) < tol;
-};
-
-// Compares two quaternions by subtracting them, taking the length of the
-// difference, and comparing that length to a tolerance.
-function compareQuaternionsWithTolerance(a, b, tol) {
- return g_quat.length(g_quat.sub(a,b)) < tol;
-};
-
-function assertQuaternionsClose(a, b) {
- g_test.assertTrue(compareQuaternionsWithTolerance(a, b, 1e-4));
-};
-
-// Compares two vectors by subtracting them, taking the length of the
-// difference and comparing that length to a tolerance.
-function compareVectorsWithTolerance(a, b, tol) {
- return g_math.length(g_math.subVector(a,b)) < tol;
-};
-
-function assertVectorsClose(a, b) {
- g_test.assertTrue(compareVectorsWithTolerance(a, b, 1e-4));
-};
-
-// The square root of the sum of squares of the entries of a matrix.
-function frobeniusNorm(a) {
- return Math.sqrt(g_math.trace(
- g_math.mulMatrixMatrix(g_math.transpose(a), a)));
-};
-
-// The sum of squares of entries of the difference between two matrices.
-function matrixDiff(a, b) {
- return frobeniusNorm(g_math.subMatrix(a, b));
-};
-
-function assertMatricesClose(a, b) {
- g_test.assertTrue(matrixDiff(a, b) < 1e-4);
-};
-
-// Creates a quaternion from a vector; assumes that either the vector has three
-// entries or it is in homogenous coordinates with a w component of 1.
-function toQuat(v) {
- return [v[0], v[1], v[2], 0];
-};
-
-// Reinterprets a quaternion as a point in homogenous coordinates with a w
-// component of 1.
-function toPoint(q) {
- return [q[0], q[1], q[2], 1];
-};
-
-window.onload = function() {
- window.g_quat = o3djs.quaternions;
- window.g_math = o3djs.math;
- window.g_test = o3djs.test;
- window.g_testResult = g_test.runTests(g_suite);
-};
-
-</script>
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/render-target-clear-test.html b/o3d/tests/selenium/tests/render-target-clear-test.html
deleted file mode 100644
index 65ccbb1..0000000
--- a/o3d/tests/selenium/tests/render-target-clear-test.html
+++ /dev/null
@@ -1,156 +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 that Render Targets clear correctly.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Render Target Clear Test.
-</title>
-<link rel="stylesheet" type="text/css" href="assets/style.css" />
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.material');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = unload;
-
-// global variables
-var g_o3dElement;
-var g_o3d;
-var g_math;
-var g_client;
-var g_viewInfo;
-var g_pack;
-var g_root;
-var g_o3dElement;
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and creates one shape.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- g_o3dElement = clientElements[0];
- g_o3d = g_o3dElement.o3d;
- g_math = o3djs.math;
- g_client = g_o3dElement.client;
-
- // Creates a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- g_root = g_pack.createObject('Transform');
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_root,
- g_client.renderGraphRoot,
- [0.2, 0.3, 0.4, 1]);
-
- var clientWidth = g_client.width;
- var clientHeight = g_client.height;
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -clientWidth * 0.5 + 0.5,
- clientWidth * 0.5 + 0.5,
- -clientHeight * 0.5 + 0.5,
- clientHeight * 0.5 + 0.5,
- 0.001,
- 1000);
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 500, 0], // eye
- [0, 0, 0], // target
- [0, 0, -1]); // up
-
- for (var ii = 0; ii < 3; ++ii) {
- var texture = g_pack.createTexture2D(
- 256, 256, g_o3d.Texture.ARGB8, 1, true);
- var surface = texture.getRenderSurface(0);
- var renderSet = g_pack.createObject('RenderSurfaceSet');
- renderSet.renderSurface = surface;
- // Make render before the main display.
- renderSet.priority = -10 + ii;
-
- var material = o3djs.material.createConstantMaterial(
- g_pack, g_viewInfo, texture);
- var shape = o3djs.primitives.createPlane(g_pack, material, 128, 128, 1, 1);
- var transform = g_pack.createObject("Transform");
- transform.translate(-200 + 150 * ii, 0, 0);
- transform.parent = g_root;
- transform.addShape(shape);
- var clearColor = [0, 0, 0, 1];
- clearColor[ii] = 1;
- var viewInfo = o3djs.rendergraph.createBasicView(
- g_pack, null, renderSet, clearColor);
- // Splice it into the render graph AFTER everything is setup.
- renderSet.parent = g_client.renderGraphRoot;
- }
-
- window.g_testResult = true;
-}
-
-/**
- * Remove any callbacks so they don't get called after the page has unloaded.
- */
-function unload() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-</script>
-</head>
-<body>
-<h1>Tests that render targets clear correctly.</h1>
-Should be red, green, blue on dark blue background.
-<div id="o3d" style="width: 600px; height: 600px"></div>
-</body>
-</html>
-
diff --git a/o3d/tests/selenium/tests/render-test.html b/o3d/tests/selenium/tests/render-test.html
deleted file mode 100644
index 0571ede..0000000
--- a/o3d/tests/selenium/tests/render-test.html
+++ /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.
--->
-
-<!--
-Render Test
-
-Make sure that if client.render() is called multiple times it is only rendered
-once. client.render() should only flag that the client needs to be rendered and
-the system (browser + plugin) should render it the next time it's time to
-render. It should NOT render immediately therefore multiple calls to
-client.render() without returning to the browser should only make it render
-once.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Render Test.
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = uninit;
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_client;
-var g_renderCount = 0;
-
-function onRender() {
- ++g_renderCount;
-}
-
-/**
- * Creates the client areas.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- var o3dElement = clientElements[0];
-
- var o3d = o3dElement.o3d;
- g_client = o3dElement.client;
- g_client.renderMode = o3d.Client.RENDERMODE_ON_DEMAND;
-
- g_client.setRenderCallback(onRender);
-
- for (var ii = 0; ii < 60; ++ii) {
- g_client.render();
- }
-
- setTimeout(checkResults, 1000);
-}
-
-function checkResults() {
- // We give it some leeway in case the browser is settling down.
- window.g_testResult = g_renderCount < 5;
-
- document.getElementById('success').innerHTML =
- g_testResult ? 'pass' : '<font color="red">fail</font>';
-}
-
-/**
- * Cleans up.
- */
-function uninit() {
- if (g_client) {
- g_client.cleanup();
- }
-}
-
-</script>
-</head>
-<body>
-<h1>Render Test</h1>
-Make sure that if client.render() is called multiple times it is only rendered
-once. client.render() should only flag that the client needs to be rendered and
-the system (browser + plugin) should render it the next time it's time to
-render. It should NOT render immediately therefore multiple calls to
-client.render() without returning to the browser should only make it render
-once.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 100px; height: 100px;"></div>
-<!-- End of O3D plugin -->
-<div>Test Results: <span id="success"></span></div>
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/serialization-test.html b/o3d/tests/selenium/tests/serialization-test.html
deleted file mode 100644
index 1f822ad..0000000
--- a/o3d/tests/selenium/tests/serialization-test.html
+++ /dev/null
@@ -1,1531 +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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Deserialization Test
-</title>
-</head>
-<body>
-<h1>Deserialization Test</h1>
-This tests deserialization of packs from JSON.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 32px; height: 32px;"></div>
-<!-- End of O3D plugin -->
-
-<script type="text/javascript"
- src="../../../samples/o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-
-o3djs.require('o3djs.io');
-o3djs.require('o3djs.serialization');
-o3djs.require('o3djs.test');
-o3djs.require('o3djs.util');
-
-var g_suite = {};
-
-g_suite.testDeserializesEmptyPack = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
- g_test.assertEquals(0, pack.objects.length);
-};
-
-g_suite.testExceptionIfVersionIsMissing = function() {
- var json = {
- objects: {
- }
- };
-
- var pack = g_client.createPack();
- var exception = null;
- try {
- o3djs.serialization.deserialize(pack, json);
- } catch(e) {
- exception = e;
- }
-
- g_test.assertEquals('Version in JSON file was missing.', exception);
- g_test.assertEquals(0, pack.objects.length);
-};
-
-g_suite.testExceptionIfVersionIsUnsupported = function() {
- var json = {
- version: 0,
- objects: {
- }
- };
-
- var pack = g_client.createPack();
- var exception = null;
- try {
- o3djs.serialization.deserialize(pack, json);
- } catch(e) {
- exception = e;
- }
-
- g_test.assertEquals(
- 'Version in JSON file was 0 but expected at least version ' +
- o3djs.serialization.supportedVersion + '.', exception);
- g_test.assertEquals(0, pack.objects.length);
-};
-
-g_suite.testExceptionIfObjectsArrayIsMissing = function() {
- var json = {
- version: o3djs.serialization.supportedVersion
- };
-
- var pack = g_client.createPack();
- var exception = null;
- try {
- o3djs.serialization.deserialize(pack, json);
- } catch(e) {
- exception = e;
- }
-
- g_test.assertEquals('Objects array in JSON file was missing.', exception);
- g_test.assertEquals(0, pack.objects.length);
-};
-
-g_suite.testDeserializesObject = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Transform': [
- {
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(1, pack.objects.length);
- g_test.assertEquals('o3d.Transform', pack.objects[0].className);
-};
-
-g_suite.testDeserializesIntoExistingObjectIfItIsAlreadyAdded = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Transform': [
- {
- id: 7,
- properties: {
- name: 'Foo'
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var transform = pack.createObject('o3d.Transform');
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.addObject(7, transform);
- deserializer.run();
-
- g_test.assertEquals(1, pack.objects.length);
- g_test.assertEquals('o3d.Transform', pack.objects[0].className);
- g_test.assertEquals(transform.clientId, pack.objects[0].clientId);
- g_test.assertEquals('Foo', pack.objects[0].name);
-};
-
-g_suite.testCreatesSpecialClassByInvokingCallback = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Transform': [
- {
- id: 7
- }
- ],
- 'myname.SpecialClass': [
- {
- parent: 7
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
-
- deserializer.createCallbacks['myname.SpecialClass'] = function(
- deserializer, json) {
- var transform = deserializer.pack.createObject('o3d.Transform');
- transform.parent = deserializer.getObjectById(json.parent);
- return transform;
- };
-
- deserializer.run();
-
- g_test.assertEquals(2, pack.objects.length);
- g_test.assertEquals(pack.objects[0].children[0].clientId,
- pack.objects[1].clientId);
-};
-
-g_suite.testDeserializesBoolProperty = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Transform': [
- {
- properties: {
- cull: true
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(1, pack.objects.length);
- g_test.assertEquals(true, pack.objects[0].cull);
-};
-
-g_suite.testDeserializesMatrixProperty = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Transform': [
- {
- properties: {
- localMatrix: [[1,2,3,4],[5,6,7,8],[8,7,6,5],[4,3,2,1]]
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(1, pack.objects.length);
- g_test.assertEquals(4, pack.objects[0].localMatrix[3][0]);
-};
-
-g_suite.testDeserializesStringProperty = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Transform': [
- {
- properties: {
- name: 'myTransform'
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(1, pack.objects.length);
- g_test.assertEquals('myTransform', pack.objects[0].name);
-};
-
-g_suite.testShouldDeserializeNullKeywordToNullValue = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.FunctionEval': [
- {
- properties: {
- 'functionObject': null
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(1, pack.objects.length);
- g_test.assertNull(pack.objects[0].functionObject);
-};
-
-g_suite.testDeserializesReferenceProperty = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Curve': [
- {
- id: 7
- }
- ],
- 'o3d.FunctionEval': [
- {
- properties: {
- 'functionObject': { ref: 7 }
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(2, pack.objects.length);
- g_test.assertEquals(pack.objects[0].clientId, pack.objects[1].functionObject.clientId);
-};
-
-g_suite.testDeserializesAndFixesUpReferenceProperty = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.FunctionEval': [
- {
- properties: {
- 'functionObject': { ref: 7 }
- }
- }
- ],
- 'o3d.Curve': [
- {
- id: 7
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(2, pack.objects.length);
- g_test.assertEquals(pack.objects[1].clientId, pack.objects[0].functionObject.clientId);
-};
-
-g_suite.testExceptionIfReferenceCannotBeResolved = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.FunctionEval': [
- {
- properties: {
- 'functionObject': { ref: 7 }
- }
- }
- ]
- }
- };
-
- var exception = null;
- var pack = g_client.createPack();
- try {
- o3djs.serialization.deserialize(pack, json);
- } catch (e) {
- exception = e;
- }
-
- g_test.assertEquals('Could not find object with id 7.', exception);
-};
-
-g_suite.testDeserializesArrayOfReferenceProperty = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Primitive': [
- {
- id: 7
- }
- ],
- 'o3d.Shape': [
- {
- properties: {
- 'elements': [{ ref: 7 }]
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(2, pack.objects.length);
- g_test.assertEquals(1, pack.objects[1]['elements'].length);
- g_test.assertEquals(pack.objects[0].clientId, pack.objects[1]['elements'][0].clientId);
-};
-
-g_suite.testIgnoresMissingProperty = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Transform': [
- {
- properties: {
- missing: true
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(1, pack.objects.length);
- g_test.assertFalse('missing' in pack.objects[0]);
-};
-
-g_suite.testShouldCallInitializationCallbackIfPresent = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'myname.SpecialClass': [
- {
- indexBuffer: {ref: 7}
- }
- ],
- 'o3d.IndexBuffer': [
- {
- id: 7
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
-
- deserializer.createCallbacks['myname.SpecialClass'] = function(
- deserializer, json) {
- return deserializer.pack.createObject('o3d.Primitive');
- };
-
- deserializer.initCallbacks['myname.SpecialClass'] = function(
- deserializer, object, json) {
- object.indexBuffer = deserializer.deserializeValue(json.indexBuffer);
- };
-
- deserializer.run();
-
- g_test.assertEquals(2, pack.objects.length);
- g_test.assertEquals(pack.objects[1].clientId, pack.objects[0].indexBuffer.clientId);
-};
-
-g_suite.testShouldIgnoreCallIfMethodIsMissing = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Primitive': [
- {
- calls: [
- ['missingMethod', 1, 2, 3]
- ]
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(1, pack.objects.length);
-};
-
-g_suite.testDeserializesExistingParam = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Transform': [
- {
- params: {
- localMatrix: {value: [[1,2,3,4],[5,6,7,8],[8,7,6,5],[4,3,2,1]]}
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(1, pack.objects.length);
- g_test.assertEquals(4, pack.objects[0].localMatrix[3][0]);
-};
-
-g_suite.testDeserializesAddedParam = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Transform': [
- {
- params: {
- newParam: {'class': 'o3d.ParamFloat', value: 7}
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(1, pack.objects.length);
- g_test.assertEquals(7, pack.objects[0].getParam('newParam').value);
-};
-
-g_suite.testBindsParam = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Matrix4Translation': [
- {
- params: {
- 'o3d.outputMatrix': {id: 2}
- }
- },
- {
- params: {
- 'o3d.inputMatrix': {bind: 2}
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(2, pack.objects.length);
- g_test.assertEquals(pack.objects[0].getParam('o3d.outputMatrix').clientId,
- pack.objects[1].getParam('o3d.inputMatrix').inputConnection.clientId);
-};
-
-g_suite.testIgnoresMissingOutputs = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Matrix4Translation': [
- {
- params: {
- missingParam: {id: 2}
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(1, pack.objects.length);
- g_test.assertNull(pack.objects[0].getParam('misingParam'));
-};
-
-g_suite.testExceptionIfCannotBindParam = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Matrix4Translation': [
- {
- params: {
- 'o3d.inputMatrix': {bind: 2}
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var exception = null;
- try {
- o3djs.serialization.deserialize(pack, json);
- } catch(e) {
- exception = e;
- }
-
- g_test.assertEquals('Could not find output param with id 2.', exception);
-};
-
-g_suite.testCannotBindToMissingOutput = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Matrix4Translation': [
- {
- params: {
- missingOutput: {id: 2}
- }
- },
- {
- params: {
- 'o3d.inputMatrix': {bind: 2}
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var exception = null;
- try {
- o3djs.serialization.deserialize(pack, json);
- } catch(e) {
- exception = e;
- }
-
- g_test.assertEquals('Could not find output param with id 2.', exception);
-};
-
-g_suite.testDeserializesParamArray = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.ParamArray': [
- {
- params: [
- {'class': 'o3d.ParamFloat', value: 7},
- {'class': 'o3d.ParamBoolean', value: true}
- ]
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(1, pack.objects.length);
- var array = pack.objects[0];
- g_test.assertEquals(2, array.length);
- g_test.assertEquals(7, array.getParam(0).value);
- g_test.assertEquals(true, array.getParam(1).value);
-};
-
-g_suite.testDeserializesParamArrayWithBindings = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.ParamArray': [
- {
- params: [
- {'class': 'o3d.ParamFloat', id: 1, value: 7},
- {'class': 'o3d.ParamBoolean', id: 2, value: true},
- {'class': 'o3d.ParamFloat', id: 3, bind: 1}
- ]
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(1, pack.objects.length);
- var array = pack.objects[0];
- g_test.assertEquals(3, array.length);
- g_test.assertEquals(array.getParam(0).clientId,
- array.getParam(2).inputConnection.clientId);
-};
-
-g_suite.testDeserializerObjectShouldDeserializeIncrementallyWhenRunRepeatedly = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- o3d_rootObject_root: {ref: 7},
- objects: {
- 'o3d.Transform': [
- {
- id: 7,
- properties: {
- name: 'transform1'
- }
- },
- {
- properties: {
- name: 'transform2'
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- g_test.assertEquals(0, pack.objects.length);
- var running;
- running = deserializer.run(1);
- g_test.assertEquals(true, running);
- g_test.assertEquals(1, pack.objects.length);
- running = deserializer.run(1);
- g_test.assertEquals(true, running);
- g_test.assertEquals(2, pack.objects.length);
- running = deserializer.run(1);
- g_test.assertEquals(true, running);
- g_test.assertEquals(2, pack.objects.length);
- running = deserializer.run(1);
- g_test.assertEquals(false, running);
- g_test.assertEquals(2, pack.objects.length);
-
- g_test.assertEquals('o3d.Transform', pack.objects[0].className);
- g_test.assertEquals('transform1', pack.objects[0].name);
- g_test.assertEquals('o3d.Transform', pack.objects[1].className);
- g_test.assertEquals('transform2', pack.objects[1].name);
-
- running = deserializer.run(1);
- g_test.assertEquals(false, running);
- g_test.assertEquals(2, pack.objects.length);
-};
-
-g_suite.testDeserializesTexture2DByCallingSpecialCreateFunction = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Texture2D': [
- {
- params: {
- myParam: {'class':'o3d.ParamFloat', value: 7}
- },
- custom: {
- width: 256,
- height: 256,
- format: 1,
- levels: 2,
- renderSurfacesEnabled: true
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(1, pack.objects.length);
- g_test.assertEquals('o3d.Texture2D', pack.objects[0].className);
- g_test.assertEquals(256, pack.objects[0].width);
- g_test.assertEquals(256, pack.objects[0].height);
- g_test.assertEquals(1, pack.objects[0].format);
-
- var myParam = pack.objects[0].getParam("myParam");
- g_test.assertEquals(7, myParam.value);
-};
-
-g_suite.testFindsTextureFromArchive = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Texture2D': [
- {
- params: {
- 'o3d.uri': {
- 'class': 'o3d.ParamString',
- value: 'dir/image1.png'
- }
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- deserializer.run();
-
- g_test.assertEquals(1, pack.objects.length);
- g_test.assertEquals('o3d.Texture2D', pack.objects[0].className);
- g_test.assertEquals(16, pack.objects[0].width);
- g_test.assertEquals(16, pack.objects[0].height);
- g_test.assertEquals(5, pack.objects[0].levels);
-};
-
-g_suite.testExceptionIfCannotFindTexture = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Texture2D': [
- {
- params: {
- 'o3d.uri': {
- 'class': 'o3d.ParamString',
- value: 'dir/missing.png'
- }
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- var error = '';
- try {
- deserializer.run();
- } catch (e) {
- error = e;
- }
-
- g_test.assertEquals('Could not find texture dir/missing.png in the archive',
- error);
-};
-
-g_suite.testDeserializesTextureCUBEByCallingSpecialCreateFunction = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.TextureCUBE': [
- {
- params: {
- myParam: {'class':'o3d.ParamFloat', value: 7}
- },
- custom: {
- edgeLength: 256,
- format: 1,
- levels: 2,
- renderSurfacesEnabled: true
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- o3djs.serialization.deserialize(pack, json);
-
- g_test.assertEquals(1, pack.objects.length);
- g_test.assertEquals('o3d.TextureCUBE', pack.objects[0].className);
- g_test.assertEquals(256, pack.objects[0].edgeLength);
- g_test.assertEquals(1, pack.objects[0].format);
-
- var myParam = pack.objects[0].getParam("myParam");
- g_test.assertEquals(7, myParam.value);
-};
-
-
-g_suite.testFindsCUBETextureFromArchive = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.TextureCUBE': [
- {
- params: {
- 'o3d.uri': {
- 'class': 'o3d.ParamString',
- value: 'dir/image1.png'
- }
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- deserializer.run();
-
- g_test.assertEquals(1, pack.objects.length);
- g_test.assertEquals('o3d.Texture2D', pack.objects[0].className);
- g_test.assertEquals(16, pack.objects[0].width);
- g_test.assertEquals(16, pack.objects[0].height);
- g_test.assertEquals(5, pack.objects[0].levels);
-};
-
-g_suite.testExceptionIfCannotFindCUBETexture = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.TextureCUBE': [
- {
- params: {
- 'o3d.uri': {
- 'class': 'o3d.ParamString',
- value: 'dir/missing.png'
- }
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- var error = '';
- try {
- deserializer.run();
- } catch (e) {
- error = e;
- }
-
- g_test.assertEquals('Could not find texture dir/missing.png in the archive',
- error);
-};
-
-g_suite.testShouldSetVertexBufferData = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.VertexBuffer': [
- {
- custom: {
- fields: [7,8,9],
- binaryRange: [5310,10620]
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- deserializer.run();
-
- g_test.assertEquals(1, pack.objects.length);
- var buffer = pack.objects[0];
- g_test.assertEquals(1, buffer.fields.length);
- var field = buffer.fields[0];
- g_test.assertEquals('o3d.FloatField', field.className);
- g_test.assertEquals(3, field.numComponents);
- g_test.assertEquals(12, field.size);
-};
-
-g_suite.testShouldSetVertexBufferDataNotBinary = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.VertexBuffer': [
- {
- custom: {
- fieldData: [
- {
- id: 55,
- type: "o3d.FloatField",
- numComponents: 1,
- data: [1.25,-3]
- }
- ]
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.run();
-
- g_test.assertEquals(1, pack.objects.length);
- var buffer = pack.objects[0];
- g_test.assertEquals(2, buffer.numElements);
- g_test.assertEquals(1, buffer.fields.length);
- var field = buffer.fields[0];
- g_test.assertEquals('o3d.FloatField', field.className);
- g_test.assertEquals(1, field.numComponents);
- g_test.assertEquals(4, field.size);
- var data = field.getAt(0, 2);
- g_test.assertEquals(1.25, data[0]);
- g_test.assertEquals(-3, data[1]);
-
-};
-
-g_suite.testShouldSetDestinationBufferData = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3djs.DestinationBuffer': [
- {
- 'custom':{
- 'numElements':1398,
- 'fields':[
- {
- 'id':197809,
- 'type':'o3d.FloatField',
- 'numComponents':3},
- {
- 'id':197813,
- 'type':'o3d.FloatField',
- 'numComponents':3}]
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- deserializer.run();
-
- g_test.assertEquals(1, pack.objects.length);
- var buffer = pack.objects[0];
- g_test.assertEquals(1398, buffer.numElements);
- g_test.assertEquals(2, buffer.fields.length);
- var field = buffer.fields[0];
- g_test.assertEquals('o3d.FloatField', field.className);
- g_test.assertEquals(3, field.numComponents);
- g_test.assertEquals(12, field.size);
-};
-
-g_suite.testShouldSetSourceBufferData = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.SourceBuffer': [
- {
- custom: {
- fields: [7,8,9],
- binaryRange: [5310,10620]
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- deserializer.run();
-
- g_test.assertEquals(1, pack.objects.length);
- var buffer = pack.objects[0];
- g_test.assertEquals(1, buffer.fields.length);
- var field = buffer.fields[0];
- g_test.assertEquals('o3d.FloatField', field.className);
- g_test.assertEquals(3, field.numComponents);
- g_test.assertEquals(12, field.size);
-};
-
-g_suite.testShouldSetIndexBufferData = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.IndexBuffer': [
- {
- custom: {
- fields:[7],
- binaryRange:[9618,10092]
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- deserializer.run();
-
- g_test.assertEquals(1, pack.objects.length);
- var buffer = pack.objects[0];
- g_test.assertEquals(1, buffer.fields.length);
- var field = buffer.fields[0];
- g_test.assertEquals('o3d.UInt32Field', field.className);
- g_test.assertEquals(1, field.numComponents);
- g_test.assertEquals(4, field.size);
- g_test.assertArrayEquals([0, 1, 2, 0, 2], field.getAt(0, 5));
-};
-
-g_suite.testShouldSetCurveWithKeys = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Curve': [
- {
- custom: {
- binaryRange: [358,716]
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- deserializer.run();
-
- g_test.assertEquals(1, pack.objects.length);
- var keys = pack.objects[0].keys;
- g_test.assertEquals(14, keys.length);
-};
-
-g_suite.testShouldSetCurveWithKeysNotBinary = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Curve': [
- {
- custom: {
- keys: [
- [1,1,2],
- [2,3,4],
- [3,5,8,6,7,9,10]
- ]
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.run();
- g_test.assertEquals(1, pack.objects.length);
- var curve = pack.objects[0];
- var keys = curve.keys;
- g_test.assertEquals(3, keys.length);
- g_test.assertEquals('o3d.StepCurveKey', keys[0].className);
- g_test.assertEquals('o3d.LinearCurveKey', keys[1].className);
- g_test.assertEquals('o3d.BezierCurveKey', keys[2].className);
- g_test.assertEquals(1, keys[0].input);
- g_test.assertEquals(2, keys[0].output);
- g_test.assertEquals(3, keys[1].input);
- g_test.assertEquals(4, keys[1].output);
- g_test.assertEquals(5, keys[2].input);
- g_test.assertEquals(8, keys[2].output);
- g_test.assertEquals(6, keys[2].inTangent[0]);
- g_test.assertEquals(7, keys[2].inTangent[1]);
- g_test.assertEquals(9, keys[2].outTangent[0]);
- g_test.assertEquals(10, keys[2].outTangent[1]);
-};
-
-g_suite.testShouldSetSkinEvalStreams = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.SkinEval': [
- {
- custom: {
- vertexStreams: [
- {
- stream: {
- field: 8,
- startIndex: 4,
- semantic: 1,
- semanticIndex: 2
- }
- }
- ]
- }
- }
- ],
- 'o3d.SourceBuffer': [
- {
- id: 7,
- custom: {
- fields: [8,9,10],
- binaryRange: [5310,10620]
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- deserializer.run();
-
- g_test.assertEquals(2, pack.objects.length);
- var stream = pack.objects[0].vertexStreams[0];
- var field = pack.objects[1].fields[0];
- g_test.assertEquals(field.clientId, stream.field.clientId);
- g_test.assertEquals(4, stream.startIndex);
- g_test.assertEquals(1, stream.semantic);
- g_test.assertEquals(2, stream.semanticIndex);
-};
-
-g_suite.testShouldSetStreamBankStreams = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.StreamBank': [
- {
- custom: {
- vertexStreams: [
- {
- stream: {
- field: 8,
- startIndex: 4,
- semantic: 1,
- semanticIndex: 2
- }
- }
- ]
- }
- }
- ],
- 'o3d.VertexBuffer': [
- {
- id: 7,
- custom: {
- fields: [8],
- binaryRange: [5310,10620]
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- deserializer.run();
-
- g_test.assertEquals(2, pack.objects.length);
- var stream = pack.objects[0].vertexStreams[0];
- var field = pack.objects[1].fields[0];
- g_test.assertEquals(field.clientId, stream.field.clientId);
- g_test.assertEquals(4, stream.startIndex);
- g_test.assertEquals(1, stream.semantic);
- g_test.assertEquals(2, stream.semanticIndex);
-};
-
-g_suite.testShouldSetAndBindStreamBankStreams = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.SkinEval': [
- {
- id: 7,
- custom: {
- vertexStreams: [
- {
- stream: {
- field: 9,
- startIndex: 4,
- semantic: 1,
- semanticIndex: 2
- }
- }
- ]
- }
- }
- ],
- 'o3d.SourceBuffer': [
- {
- id: 8,
- custom: {
- fields: [9],
- binaryRange: [5310,10620]
- }
- }
- ],
- 'o3d.StreamBank': [
- {
- custom: {
- vertexStreams: [
- {
- stream: {
- field: 11,
- startIndex: 4,
- semantic: 1,
- semanticIndex: 2
- },
- bind: 7
- }
- ]
- }
- }
- ],
- 'o3d.VertexBuffer': [
- {
- id: 10,
- custom: {
- fields: [11],
- binaryRange: [5310,10620]
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- deserializer.run();
-
- g_test.assertEquals(4, pack.objects.length);
- g_test.assertTrue(pack.objects[2].unbindStream(1, 2));
-};
-
-g_suite.testShouldSetAndBindSkinEvalStreams = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.SkinEval': [
- {
- id: 7,
- custom: {
- vertexStreams: [
- {
- stream: {
- field: 9,
- startIndex: 4,
- semantic: 1,
- semanticIndex: 2
- }
- }
- ]
- }
- },
- {
- id: 14,
- custom: {
- vertexStreams: [
- {
- stream: {
- field: 11,
- startIndex: 4,
- semantic: 1,
- semanticIndex: 2
- },
- bind: 7
- }
- ]
- }
- }
- ],
- 'o3d.SourceBuffer': [
- {
- id: 8,
- custom: {
- fields: [9],
- binaryRange: [5310,10620]
- }
- },
- {
- id: 10,
- custom: {
- fields: [11],
- binaryRange: [5310,10620]
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- deserializer.run();
-
- g_test.assertEquals(4, pack.objects.length);
- g_test.assertTrue(pack.objects[1].unbindStream(1, 2));
-};
-
-g_suite.testShouldLoadEffectShaderFromArchive = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Effect': [
- {
- params: {
- 'o3d.uri': {
- 'class': 'o3d.ParamString',
- value: 'dir/solid-color.shader'
- }
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- deserializer.run();
-
- g_test.assertEquals(1, pack.objects.length);
- var effect = pack.objects[0];
- g_test.assertEquals('o3d.Effect', effect.className);
- g_test.assertEquals('//', effect.source.substring(0, 2));
-};
-
-g_suite.testExceptionIfCannotLoadShaderFromArchive = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Effect': [
- {
- params: {
- 'o3d.uri': {
- 'class': 'o3d.ParamString',
- value: 'dir/image1.png'
- }
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- var error = '';
- try {
- deserializer.run();
- } catch (e) {
- error = e;
- }
-
- g_test.assertEquals('Cannot load shader dir/image1.png in archive.', error);
-};
-
-g_suite.testShouldSetSkinData = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Skin': [
- {
- custom: {
- binaryRange: [32724,34584]
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- deserializer.run();
-
- g_test.assertEquals(1, pack.objects.length);
- var skin = pack.objects[0];
- g_test.assertEquals(79, skin.influences.length);
- g_test.assertEquals(2, skin.influences[0].length);
- g_test.assertArrayEquals([2, 1], skin.influences[0]);
-};
-
-g_suite.testShouldSetSkinDataNotBinary = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Skin': [
- {
- properties: {
- influences: [[1, 2],[2, 3, 4, 5]],
- inverseBindPoseMatrices: [
- [[1, 2, 3, 4],
- [5, 6, 7, 8],
- [9, 10, 11, 12],
- [13, 14, 15, 16]],
- [[1, 2, 3, 4],
- [5, 6, 7, 8.5],
- [9, 10, 11, 12],
- [13, 14, 15, 1]]]
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.run();
-
- g_test.assertEquals(1, pack.objects.length);
- var skin = pack.objects[0];
- g_test.assertEquals(2, skin.influences.length);
- g_test.assertEquals(2, skin.influences[0].length);
- g_test.assertEquals(4, skin.influences[1][2]);
- g_test.assertArrayEquals([1, 2], skin.influences[0]);
- g_test.assertArrayEquals([2, 3, 4, 5], skin.influences[1]);
- g_test.assertEquals(2, skin.inverseBindPoseMatrices.length);
- g_test.assertEquals(8.5, skin.inverseBindPoseMatrices[1][1][3]);
-};
-
-g_suite.testExceptionIfEffectShaderCannotBeFound = function() {
- var json = {
- version: o3djs.serialization.supportedVersion,
- objects: {
- 'o3d.Effect': [
- {
- params: {
- 'o3d.uri': {
- 'class': 'o3d.ParamString',
- value: 'dir/missing.shader'
- }
- }
- }
- ]
- }
- };
-
- var pack = g_client.createPack();
- var deserializer = o3djs.serialization.createDeserializer(pack, json);
- deserializer.archiveInfo = g_archiveInfo;
- var error = '';
- try {
- deserializer.run();
- } catch (e) {
- error = e;
- }
-
- g_test.assertEquals(
- 'Cannot find shader dir/missing.shader in archive.',
- error);
-};
-
-function initStep3(archiveInfo, exception) {
- window.g_archiveInfo = archiveInfo;
- window.g_testResult = g_test.runTests(g_suite);
-}
-
-function initStep2(clientElements) {
- window.g_test = o3djs.test;
- window.g_plugin = clientElements[0];
- window.g_client = clientElements[0].client;
- window.g_pack = g_client.createPack();
- window.g_client.clearErrorCallback();
- o3djs.io.loadArchive(g_pack, 'assets/archive.o3dtgz', initStep3);
-};
-
-window.onload = function() {
- o3djs.util.makeClients(initStep2);
-};
-
-</script>
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/test-test.html b/o3d/tests/selenium/tests/test-test.html
deleted file mode 100644
index 0161ff9..0000000
--- a/o3d/tests/selenium/tests/test-test.html
+++ /dev/null
@@ -1,368 +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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Unit Testing library tests
-</title>
-</head>
-<body>
-<h1>Unit Testing library tests</h1>
-This tests the operation of the unit testing library.
-<br/>
-<script type="text/javascript"
- src="../../../samples/o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-
-o3djs.require('o3djs.test');
-
-function MockReporter() {
- this.reportPass = function(testName) {
- this.passName = testName;
- }
- this.reportFail = function(testName, message) {
- this.failName = testName;
- this.failMessage = message;
- }
- this.reportSummary = function(passCount, failCount) {
- this.passCount = passCount;
- this.failCount = failCount;
- }
-};
-
-var g_suite = {};
-
-g_suite.testRunsFunctionsWithTestPrefix = function() {
- var ran = false;
- var tests = {
- testFoo: function() {
- ran = true;
- }
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertTrue(ran);
- g_test.assertEquals('testFoo', reporter.passName);
- g_test.assertEquals('undefined', typeof(reporter.failName));
-};
-
-g_suite.testDoesNotRunFunctionsWithoutTestPrefix = function() {
- var ran = false;
- var tests = {
- notATest: function() {
- ran = true;
- }
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertFalse(ran);
- g_test.assertEquals('undefined', typeof(reporter.passName));
- g_test.assertEquals('undefined', typeof(reporter.failName));
-};
-
-g_suite.testDoesNotRunValuesThatAreNotFunctions = function() {
- var tests = {
- testFoo: 7
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertEquals('undefined', typeof(reporter.passName));
- g_test.assertEquals('undefined', typeof(reporter.failName));
-};
-
-g_suite.testReportsNumberOfPassingTests = function() {
- var tests = {
- testFoo: function() {
- },
- testBar: function() {
- },
- testBaz: function() {
- assertTrue(false);
- }
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertEquals(2, reporter.passCount);
- g_test.assertEquals(1, reporter.failCount);
-};
-
-g_suite.testReturnsTrueIfAllTestsPass = function() {
- var tests = {
- testFoo: function() {
- },
- testBar: function() {
- }
- };
- var reporter = new MockReporter();
- g_test.assertTrue(g_test.runTests(tests, reporter));
-};
-
-g_suite.testReturnsFalseIfAnyTestFails = function() {
- var tests = {
- testFoo: function() {
- },
- testBar: function() {
- g_test.assertTrue(false);
- }
- };
- var reporter = new MockReporter();
- g_test.assertFalse(g_test.runTests(tests, reporter));
-};
-
-g_suite.testAssertTrueDoesNotAssertForTrueValue = function() {
- g_test.assertTrue(true);
-};
-
-g_suite.testAssertTrueAssertsForFalseValue = function() {
- var tests = {
- testFoo: function() {
- g_test.assertTrue(false);
- }
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertEquals('undefined', typeof(reporter.passName));
- g_test.assertEquals('testFoo', reporter.failName);
- g_test.assertEquals(
- 'assertTrue failed for false',
- reporter.failMessage);
-};
-
-g_suite.testAssertFalseDoesNotAssertForFalseValue = function() {
- g_test.assertFalse(false);
-};
-
-g_suite.testAssertFalseAssertsForTrueValue = function() {
- var tests = {
- testFoo: function() {
- g_test.assertFalse(true);
- }
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertEquals('undefined', typeof(reporter.passName));
- g_test.assertEquals('testFoo', reporter.failName);
- g_test.assertEquals(
- 'assertFalse failed for true',
- reporter.failMessage);
-};
-
-g_suite.testAssertNullDoesNotAssertForNullValue = function() {
- g_test.assertNull(null);
-};
-
-g_suite.testAssertNullAssertsForNonNullValue = function() {
- var tests = {
- testFoo: function() {
- g_test.assertNull(undefined);
- }
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertEquals('undefined', typeof(reporter.passName));
- g_test.assertEquals('testFoo', reporter.failName);
- g_test.assertEquals(
- 'assertNull failed for undefined',
- reporter.failMessage);
-};
-
-g_suite.testAssertEqualsDoesNotAssertForEqualValue = function() {
- g_test.assertEquals(7, 7);
-};
-
-g_suite.testAssertEqualsAssertsForUnequalValue = function() {
- var tests = {
- testFoo: function() {
- g_test.assertEquals(6, 7);
- }
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertEquals('undefined', typeof(reporter.passName));
- g_test.assertEquals('testFoo', reporter.failName);
- g_test.assertEquals(
- 'assertEquals failed: expected 6 but got 7',
- reporter.failMessage);
-};
-
-g_suite.testStringValuesAreReportedInQuotes = function() {
- var tests = {
- testFoo: function() {
- g_test.assertEquals('a', 'b');
- }
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertEquals('undefined', typeof(reporter.passName));
- g_test.assertEquals('testFoo', reporter.failName);
- g_test.assertEquals(
- 'assertEquals failed: expected "a" but got "b"',
- reporter.failMessage);
-};
-
-g_suite.testObjectsWithDifferentIdentityAreNotEqual = function() {
- var tests = {
- testFoo: function() {
- g_test.assertEquals({a: 7, b: 8, f: function() {}},
- {a: 7, b: 8, f: function() {}});
- }
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertEquals('undefined', typeof(reporter.passName));
- g_test.assertEquals('testFoo', reporter.failName);
- g_test.assertEquals(
- 'assertEquals failed: expected {a: 7, b: 8} but got {a: 7, b: 8}',
- reporter.failMessage);
-};
-
-g_suite.testAssertCloseDoesNotAssertForEqualValue = function() {
- g_test.assertClose(7, 7);
-};
-
-g_suite.testAssertCloseDoesNotAssertForSlightlySmallerActual = function() {
- g_test.assertClose(7, 6.9991);
-};
-
-g_suite.testAssertCloseDoesNotAssertForSlightlyLargerActual = function() {
- g_test.assertClose(7, 7.0009);
-};
-
-g_suite.testAssertCloseAssertsForValueOutsideThreshold= function() {
- var tests = {
- testFoo: function() {
- g_test.assertClose(7, 7.0015);
- }
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertEquals('undefined', typeof(reporter.passName));
- g_test.assertEquals('testFoo', reporter.failName);
- g_test.assertEquals(
- 'assertClose failed: expected 7 but got 7.0015',
- reporter.failMessage);
-};
-g_suite.testAssertArrayEqualsDoesNotAssertForEqualArrays = function() {
- g_test.assertArrayEquals([1, 2, 3], [1, 2, 3]);
-};
-
-g_suite.testAssertArrayEqualsAssertsForNonArrayExpectedValue = function() {
- var tests = {
- testFoo: function() {
- g_test.assertArrayEquals(7, [1, 2, 3]);
- }
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertEquals('undefined', typeof(reporter.passName));
- g_test.assertEquals('testFoo', reporter.failName);
- g_test.assertEquals(
- 'assertArrayEquals failed: expected value 7 is not an array',
- reporter.failMessage);
-}
-
-g_suite.testAssertArrayEqualsAssertsForNonArrayActualValue = function() {
- var tests = {
- testFoo: function() {
- g_test.assertArrayEquals([1, 2], 7);
- }
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertEquals('undefined', typeof(reporter.passName));
- g_test.assertEquals('testFoo', reporter.failName);
- g_test.assertEquals(
- 'assertArrayEquals failed: actual value 7 is not an array',
- reporter.failMessage);
-};
-
-g_suite.testAssertArrayEqualsAssertsForArraysOfDifferingLength = function() {
- var tests = {
- testFoo: function() {
- g_test.assertArrayEquals([1, 2], [1, 2, 3]);
- }
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertEquals('undefined', typeof(reporter.passName));
- g_test.assertEquals('testFoo', reporter.failName);
- g_test.assertEquals(
- 'assertArrayEquals failed: expected [1, 2] but got [1, 2, 3]',
- reporter.failMessage);
-};
-
-g_suite.testAssertArrayEqualsAssertsForArraysWithDifferingElement = function() {
- var tests = {
- testFoo: function() {
- g_test.assertArrayEquals([3, 2, 1], [1, 2, 3]);
- }
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertEquals('undefined', typeof(reporter.passName));
- g_test.assertEquals('testFoo', reporter.failName);
- g_test.assertEquals(
- 'assertArrayEquals failed: expected [3, 2, 1] but got [1, 2, 3]',
- reporter.failMessage);
-};
-
-g_suite.testAssertArrayEqualsDoesNotAssertForEqual2DArrays = function() {
- g_test.assertArrayEquals([[1, 2, 3]], [[1, 2, 3]]);
-};
-
-g_suite.testAssertArrayEqualsAssertsFor2DArraysWithDifferingElement =
- function() {
- var tests = {
- testFoo: function() {
- g_test.assertArrayEquals([[3, 2, 1]], [[1, 2, 3]]);
- }
- };
- var reporter = new MockReporter();
- g_test.runTests(tests, reporter);
- g_test.assertEquals('undefined', typeof(reporter.passName));
- g_test.assertEquals('testFoo', reporter.failName);
- g_test.assertEquals(
- 'assertArrayEquals failed: expected [[3, 2, 1]] but got [[1, 2, 3]]',
- reporter.failMessage);
-};
-
-window.onload = function() {
- window.g_test = o3djs.test;
- window.g_testResult = g_test.runTests(g_suite);
-};
-
-</script>
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/texture-set-test.html b/o3d/tests/selenium/tests/texture-set-test.html
deleted file mode 100644
index bd2f0d4..0000000
--- a/o3d/tests/selenium/tests/texture-set-test.html
+++ /dev/null
@@ -1,496 +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.
--->
-
-<!--
-Texture set test.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Texture Set Test.
-</title>
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-o3djs.require('o3djs.rendergraph');
-o3djs.require('o3djs.primitives');
-o3djs.require('o3djs.effect');
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_viewInfo;
-
-/**
- * Creates the client area.
- */
-function init() {
- // Comment out the line below to run the sample in the browser
- // JavaScript engine. This may be helpful for debugging.
- o3djs.util.setMainEngine(o3djs.util.Engine.V8);
- o3djs.util.makeClients(initStep2, 'FloatingPointTextures,NotAntiAliased');
-}
-
-/**
- * Initializes O3D, loads an effect, creates some textures
- * and quads to display them.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initializes global variables and libraries.
- var o3dElement = clientElements[0];
- g_o3d = o3dElement.o3d;
- g_math = o3djs.math;
-
- // Set window.g_client as well. Otherwise when the sample runs in
- // V8, selenium won't be able to find this variable (it can only see
- // the browser environment).
- window.g_client = g_client = o3dElement.client;
-
- // Create a pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- // Create the render graph for a view.
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- var clientWidth = g_client.width;
- var clientHeight = g_client.height;
- // The + 0.5 makes this pixel aligned.
- g_viewInfo.drawContext.projection = g_math.matrix4.orthographic(
- -clientWidth * 0.5 + 0.5,
- clientWidth * 0.5 + 0.5,
- -clientHeight * 0.5 + 0.5,
- clientHeight * 0.5 + 0.5,
- 0.001,
- 1000);
- g_viewInfo.drawContext.view = g_math.matrix4.lookAt(
- [0, 500, 0], // eye
- [0, 0, 0], // target
- [0, 0, -1]); // up
-
- // Create and load the effects.
- var effectNames = [
- 'texture-only.shader',
- 'luminance_alpha_texture.shader'];
-
- var effectInfos = {
- texture_only: {name: 'texture_only'},
- one_channel_texture: {name: 'one_channel_texture'}};
- for (var key in effectInfos) {
- var info = effectInfos[key];
- var effect = g_pack.createObject('Effect');
- effect.loadFromFXString(o3djs.util.getElementContentById(info.name));
-
- // Create a Material for the effect.
- var material = g_pack.createObject('Material');
-
- // Set the material's drawList for transparent objects.
- material.drawList = g_viewInfo.zOrderedDrawList;
-
- // Apply the effect to this material.
- material.effect = effect;
-
- // Create the params that effect requires on the material.
- effect.createUniformParameters(material);
-
- // Create a quad.
- var shape = o3djs.primitives.createPlane(g_pack,
- material,
- 1,
- 1,
- 1,
- 1);
- info.shape = shape;
- }
-
- // display our shape 5 times with 5 different textures
- // by overriding the sampler on each instance.
- for (var f = 0; f < 5; ++f) {
- for (var s = 0; s < 5; ++s) {
- // create a transform for an instance
- var transform = g_pack.createObject('Transform');
- var x = s;
- var z = f;
- transform.translate(-180 + 32 + s * 70, 0, -180 + 32 + f * 70);
- transform.scale(64, 1, 64);
- transform.parent = g_client.root;
-
- // Create a ParamSampler on the transform with the same name as in
- // the effect so this param will be used instead of the one on the
- // material.
- var samplerParam = transform.createParam('texSampler0', 'ParamSampler');
-
- var sampler = g_pack.createObject('Sampler');
- samplerParam.value = sampler;
- sampler.magFilter = g_o3d.Sampler.POINT;
- sampler.minFilter = g_o3d.Sampler.POINT;
- sampler.mipFilter = g_o3d.Sampler.NONE;
- sampler.addressModeU = g_o3d.Sampler.CLAMP;
- sampler.addressModeV = g_o3d.Sampler.CLAMP;
-
- // Create a texture.
- {
- var pixels = [];
- var format;
-
- switch (s) {
- case 0: { // XRGB8
- transform.addShape(effectInfos.texture_only.shape);
- format = g_o3d.Texture.XRGB8;
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 3; // rgb
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.cos(u); // red
- pixels[offset + 1] = Math.sin(v); // green
- pixels[offset + 2] = Math.sin(u); // blue
- }
- }
- break;
- }
- case 1: { // ARGB8
- transform.addShape(effectInfos.texture_only.shape);
- format = g_o3d.Texture.ARGB8;
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 4; // rgba
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.floor(y / 4) % 2; // red
- pixels[offset + 1] = Math.sin(v); // green
- pixels[offset + 2] = Math.floor(x / 4) % 2; // blue
- pixels[offset + 3] = Math.abs(Math.sin(v * 4)); // alpha
- }
- }
- break;
- }
- case 2: { // ABGR16F
- transform.addShape(effectInfos.texture_only.shape);
- format = g_o3d.Texture.ABGR16F;
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 4; // rgba
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.cos(v); // red
- pixels[offset + 1] = Math.sin(u); // green
- pixels[offset + 2] = Math.sin(v); // blue
- pixels[offset + 3] = Math.abs(Math.sin(u * 8)); // alpha
- }
- }
- break;
- }
- case 3: { // ABGR32F
- transform.addShape(effectInfos.texture_only.shape);
- format = g_o3d.Texture.ABGR32F;
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x) * 4; // rgba
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.cos(v); // red
- pixels[offset + 1] = Math.sin(u); // green
- pixels[offset + 2] = Math.sin(v); // blue
- pixels[offset + 3] = Math.abs(Math.sin(u * 8)); // alpha
- }
- }
- break;
- }
- case 4: { // R32F
- /**
- * NOTE: GL and D3D do NOT share compatible 1 channel texture
- * formats.
- *
- * In D3D the sampler will return
- *
- * R = channel 0
- * G = const 1
- * B = const 1
- * A = const 1
- *
- * In GL the sampler will return
- *
- * R = channel 0
- * G = channel 0
- * B = channel 0
- * A = channel 0
- *
- * What that means is only R works across platforms. G, B and A are
- * undefined and if you use them you'll get the wrong results.
- */
- transform.addShape(effectInfos.one_channel_texture.shape);
- format = g_o3d.Texture.R32F;
- for (var y = 0; y < 32; ++y) {
- for (var x = 0; x < 32; ++x) {
- var offset = (y * 32 + x); // r
- var u = x / 32 * Math.PI * 0.5;
- var v = y / 32 * Math.PI * 0.5;
- pixels[offset + 0] = Math.cos(v * 16); // red
- }
- }
- break;
- }
- }
- var texture = g_pack.createTexture2D(32, 32, format, 1, false);
- var tx = -16 + (f % 2) * 32;
- var ty = -16 + Math.floor(f / 2) * 32;
- if (f == 4) {
- tx = 0;
- ty = 0;
- }
- texture.setRect(0, tx, ty, 32, pixels);
- sampler.texture = texture;
- if (tx == 0 && ty == 0 && format != 4) {
- var texturePixels = texture.getRect(0, tx, ty, 32, 32);
- if (texturePixels.length != pixels.length) {
- reportResult(false, 'different length');
- return;
- }
- for (var ndx = 0; ndx < pixels.length; ++ndx) {
- // because float<->half conversion is not perfect
- var difference = Math.abs(pixels[ndx] - texturePixels[ndx]);
- if (difference > 0.004) {
- //console.log("fmt: " + format +
- // " ndx: " + ndx +
- // " p1: " + pixels[ndx] +
- // " p2: " + texturePixels[ndx] +
- // " dif: " + difference);
- reportResult(false, 'pixels, format: ' + format +
- ' different by: ' + difference);
- return;
- }
- }
- }
- }
- }
- }
- reportResult(true, '');
-}
-
-function reportResult(result, msg) {
- o3djs.BROWSER_ONLY;
- o3djs.util.getElementById('result').innerHTML = result ?
- '<font color="green">success</font>' :
- '<font color="red">failure: ' + msg + '</font>';
- window.g_testResult = result; // for selenium testing.
-}
-
-</script>
-</head>
-<body onload="init()">
-<h1>Texture Set Test</h1>
-<br/>
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 400px; height: 400px;"></div>
-<!-- End of O3D plugin -->
-<div>Result: <span id="result"></span></div>
-<script type="test/o3deffect" id="texture_only">
-/*
- * 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.
- */
-
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-
-// The texture sampler is used to access the texture bitmap in the fragment
-// shader.
-sampler texSampler0;
-
-// input parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-// input parameters for our pixel shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-/**
- * Our vertex shader
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(input.position, worldViewProjection);
- output.texcoord = input.texcoord;
- return output;
-}
-
-/* Given the texture coordinates, our pixel shader grabs the corresponding
- * color from the texture.
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- return tex2D(texSampler0, input.texcoord);
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
-</script>
-<script type="test/o3deffect" id="one_channel_texture">
-/*
- * 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.
- */
-
-float4x4 worldViewProjection : WORLDVIEWPROJECTION;
-
-// The texture sampler is used to access the texture bitmap in the fragment
-// shader.
-sampler texSampler0;
-
-// input parameters for our vertex shader
-struct PixelShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-// input parameters for our pixel shader
-struct VertexShaderInput {
- float4 position : POSITION;
- float2 texcoord : TEXCOORD0; // Texture coordinates
-};
-
-/**
- * Our vertex shader
- */
-PixelShaderInput vertexShaderFunction(VertexShaderInput input) {
- PixelShaderInput output;
- output.position = mul(input.position, worldViewProjection);
- output.texcoord = input.texcoord;
- return output;
-}
-
-/**
- * Given the texture coordinates, our pixel shader grabs the corresponding
- * color from the texture.
- *
- * NOTE: GL and D3D do NOT share compatible 1 channel texture formats.
- *
- * In D3D the sampler will return
- *
- * R = channel 0
- * G = const 1
- * B = const 1
- * A = const 1
- *
- * In GL the sampler will return
- *
- * R = channel 0
- * G = channel 0
- * B = channel 0
- * A = channel 0
- *
- * What that means is only R works across platforms. G, B and A are undefined
- * and if you use them you'll get the wrong results.
- */
-float4 pixelShaderFunction(PixelShaderInput input): COLOR {
- // ** Use only valid channels. ** ---------+
- // |
- // V
- return tex2D(texSampler0, input.texcoord).rrrr;
-}
-
-// Here we tell our effect file *which* functions are
-// our vertex and pixel shaders.
-// #o3d VertexShaderEntryPoint vertexShaderFunction
-// #o3d PixelShaderEntryPoint pixelShaderFunction
-// #o3d MatrixLoadOrder RowMajor
-</script>
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/type-test.html b/o3d/tests/selenium/tests/type-test.html
deleted file mode 100644
index 84eee91..0000000
--- a/o3d/tests/selenium/tests/type-test.html
+++ /dev/null
@@ -1,166 +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.
--->
-
-<!--
-A Selenium test to make sure various math types convert.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Type Test
-</title>
-<!-- Our javascript code -->
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-
-window.onload = init;
-
-// global variables
-var g_o3d;
-var g_math;
-var g_client;
-var g_pack;
-var g_testResult;
-
-function compare3(object, x, y, z) {
- return object[0] == x &&
- object[1] == y &&
- object[2] == z;
-}
-
-function compare4(object, x, y, z, w) {
- return object[0] == x &&
- object[1] == y &&
- object[2] == z &&
- object[3] == w;
-}
-
-function compareArrays(array1, array2) {
- if (array1.length != array2.length) {
- return false;
- }
- for (var ii = 0; ii < array1.length; ++ii) {
- if (array1[ii] !== array2[ii]) {
- return false;
- }
- }
- return true;
-}
-
-/**
- * Creates the client area.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes g_o3d, loads the effect, and draws the sphere.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- // Initialize global variables and libraries.
- var o3d = clientElements[0];
- g_o3d = o3d.o3d;
- g_math = o3djs.math;
- g_client = o3d.client;
-
- // Create a g_pack to manage our resources/assets
- g_pack = g_client.createPack();
-
- var good = true;
- // we shouldn't get an error while we're testing any of these.
- g_client.setErrorCallback(function(msg) { good = false; });
-
- var transform = g_pack.createObject('Transform');
- var paramFloat3 = transform.createParam('f3', 'ParamFloat3');
- var paramFloat4 = transform.createParam('f4', 'ParamFloat4');
- var float3;
- var float4;
- var test = 0;
-
- // --- float3 ---
-
- // Check that we can set a ParamFloat3 to an array
- if (good) {
- test++;
- paramFloat3.value = [1, 2, 3];
- good = good && compare3(paramFloat3.value, 1, 2, 3);
- }
-
- // Check that we can get an array from a ParamFloat3
- if (good) {
- test++;
- float3 = paramFloat3.value;
- good = good && compare3(float3, 1, 2, 3);
- }
-
- // --- float4 ---
-
- // Check that we can set a ParamFloat4 to an array
- if (good) {
- test++;
- paramFloat4.value = [1, 2, 3, 4];
- good = good && compare4(paramFloat4.value, 1, 2, 3, 4);
- }
-
- // Check that we can get an array from a ParamFloat4
- if (good) {
- test++;
- float4 = paramFloat4.value;
- good = good && compare4(float4, 1, 2, 3, 4);
- }
-
- document.getElementById('testStatus').innerHTML = "Finished";
- document.getElementById('testResults').innerHTML =
- good ? "Passed" : ("Failed: at test# " + test);
- g_testResult = good;
-}
-
-</script>
-</head>
-<body>
-<h1>Type Test</h1>
-<table>
-<tr><td>Tests:</td><td><span id="testStatus">Running</span></td></td>
-<tr><td>Results:</td><td><span id="testResults">---</span></td></td>
-</table>
-<!-- Start of g_o3d plugin -->
-<div id="o3d" style="width: 100px; height: 100px;"></div>
-<!-- End of g_o3d plugin -->
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/util-test.html b/o3d/tests/selenium/tests/util-test.html
deleted file mode 100644
index 0101840..0000000
--- a/o3d/tests/selenium/tests/util-test.html
+++ /dev/null
@@ -1,111 +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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Util Test
-</title>
-</head>
-<body>
-<h1>Util Test</h1>
-This tests util.js.
-<br/>
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 32px; height: 32px;"></div>
-<!-- End of O3D plugin -->
-
-<script type="text/javascript"
- src="../../../samples/o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-
-o3djs.require('o3djs.test');
-o3djs.require('o3djs.util');
-
-g_suite = {};
-
-function add(a, b) {
- return a + b;
-}
-
-g_suite.testCanCurryAFunctionFixingNoArguments = function() {
- var newAdd = o3djs.util.curry(add);
- g_test.assertEquals(3, newAdd(1, 2));
-}
-
-g_suite.testCanCurryAFunctionFixingSomeArguments = function() {
- var increment = o3djs.util.curry(add, 1);
- g_test.assertEquals(3, increment(2));
-}
-
-g_suite.testCanCurryAFunctionFixingAllArguments = function() {
- var three = o3djs.util.curry(add, 1, 2);
- g_test.assertEquals(3, three());
-}
-
-g_suite.testLeavesAbsoluteURIUnchanged = function() {
- g_test.assertEquals(
- 'http://www.domain.org/foo/bar.html',
- o3djs.util.toAbsoluteUri('http://www.domain.org/foo/bar.html'));
-};
-
-g_suite.testAddsBaseURIToRelativeURI = function() {
- g_test.assertEquals(
- g_baseUri + '/foo/bar.html',
- o3djs.util.toAbsoluteUri('foo/bar.html'));
-};
-
-g_suite.testStripsDotDotFromAbsoluteURI = function() {
- g_test.assertEquals(
- g_baseUri + '/bing/foo/baz.html',
- o3djs.util.toAbsoluteUri('bing/foo/bar/../../foo/baz.html'));
-};
-
-function initStep2(clientElements) {
- g_test = o3djs.test;
- g_plugin = clientElements[0];
- g_baseUri = document.location.toString();
- var lastSlash = g_baseUri.lastIndexOf('/');
- g_baseUri = g_baseUri.substring(0, lastSlash);
- g_testResult = g_test.runTests(g_suite);
-};
-
-window.onload = function() {
- o3djs.util.makeClients(initStep2);
-};
-
-</script>
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/v8-test.html b/o3d/tests/selenium/tests/v8-test.html
deleted file mode 100644
index 41a0ca2..0000000
--- a/o3d/tests/selenium/tests/v8-test.html
+++ /dev/null
@@ -1,784 +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.
--->
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-V8 Test
-</title>
-</head>
-<body>
-<h1>V8 / ActiveX Bridge Tests</h1>
-This tests V8/NPAPI interoperation and the ActiveX bridge.
-<br/>
-
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 32px; height: 32px;"></div>
-<!-- End of O3D plugin -->
-
-<script type="text/javascript"
- src="../../../samples/o3djs/base.js"></script>
-<script type="text/javascript" id="o3dscript">
-
-o3djs.require('o3djs.test');
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.math');
-
-var isChrome = navigator.userAgent.indexOf('Chrome') != -1;
-var isSafari = !isChrome && navigator.userAgent.indexOf('Safari') != -1;
-var isFirefox2 = navigator.userAgent.indexOf('Firefox/2.') != -1;
-var isFirefox = navigator.userAgent.indexOf('Firefox') != -1;
-var isInternetExplorer = navigator.userAgent.indexOf('Internet Explorer' != -1);
-
-var g_suite = {};
-
-g_suite.testEvaluatesUndefinedExpression = function() {
- g_test.assertEquals(undefined, window.g_plugin.eval('undefined'));
-};
-
-g_suite.testEvaluatesNullExpression = function() {
- g_test.assertEquals(null, window.g_plugin.eval('null'));
-};
-
-g_suite.testEvaluatesDoubleExpression = function() {
- g_test.assertEquals(4.5, window.g_plugin.eval('2.25+2.25'));
-};
-
-g_suite.testEvaluatesInt32Expression = function() {
- g_test.assertEquals(4, window.g_plugin.eval('2+2'));
-};
-
-g_suite.testEvaluatesBooleanExpression = function() {
- g_test.assertTrue(window.g_plugin.eval('true || true'));
-};
-
-g_suite.testEvaluatesStringExpression = function() {
- g_test.assertEquals('ab', window.g_plugin.eval('"a" + "b"'));
-};
-
-g_suite.testWrapsAndUnwrapsV8ObjectsAndPreservesIdentity = function() {
- var a = window.g_plugin.eval('var a = {}; a');
- var v8f = window.g_plugin.eval('function(x) { return a === x; }');
- g_test.assertTrue(v8f(a));
-};
-
-g_suite.testBrowserConsidersTheSamePluginToBeTheSame = function() {
- g_test.assertEquals(g_plugin, g_plugin);
-};
-
-g_suite.testBrowserConsidersTheSameNPObjectReturnedMultipleTimesToBeTheSame =
- function() {
- // http://code.google.com/p/chromium/issues/detail?id=5751
- if (!isChrome && !isSafari) {
- g_test.assertEquals(g_plugin.client, g_plugin.client);
- }
-};
-
-g_suite.testBrowserConsidersTheSameV8ObjectReturnedMultipleTimesToBeTheSame =
- function() {
- // http://code.google.com/p/chromium/issues/detail?id=5751
- if (!isChrome && !isSafari) {
- window.g_plugin.eval('var a = {};');
- var obj1 = window.g_plugin.eval('a');
- var obj2 = window.g_plugin.eval('a');
- g_test.assertEquals(obj1, obj2);
- }
-};
-
-g_suite.testTypeofV8ObjectInBrowserIsObject = function() {
- var a = window.g_plugin.eval('({})');
- if (!isSafari) {
- g_test.assertEquals('object', typeof(a));
- } else {
- // Safari thinks its a function!
- g_test.assertEquals('function', typeof(a));
- }
-};
-
-g_suite.testTypeofV8FunctionInBrowserIsFunction = function() {
- var v8f = window.g_plugin.eval('function() {}');
- g_test.assertEquals('function', typeof(v8f));
-};
-
-g_suite.testV8FunctionIsInstanceOfFunctionInBrowser = function() {
- var v8f = window.g_plugin.eval('function(x) { return typeof(x); }');
- g_test.assertTrue(v8f instanceof Function);
-};
-
-g_suite.testV8FunctionKeepsIdentityWhenPassedBackIntoV8 = function() {
- var v8f = window.g_plugin.eval(
- 'g_originalFunction = function(x) { return typeof(x); }');
- var comparer = window.g_plugin.eval(
- 'function(func) { return func === g_originalFunction; }');
- g_test.assertTrue(comparer(v8f));
-};
-
-g_suite.testBrowserCanInvokeV8Functions = function() {
- var v8f = window.g_plugin.eval('function(x) { return x; }');
- g_test.assertEquals(2, v8f(2));
-};
-
-g_suite.testBrowserCanInvokeV8Constructors = function() {
- // http://code.google.com/p/chromium/issues/detail?id=3285
- if (!isChrome && !isSafari && !isFirefox2) {
- var v8f = window.g_plugin.eval('function(x) { this.p = x; }');
- var obj = new v8f(2);
- g_test.assertEquals(2, obj.p);
- }
-};
-
-g_suite.testBrowserCalledV8ConstructorsReturnDistinctObjects = function() {
- // http://code.google.com/p/chromium/issues/detail?id=3285
- if (!isChrome && !isSafari && !isFirefox2) {
- var v8f = window.g_plugin.eval('function(x) { this.p = x; }');
- var obj1 = new v8f(2);
- var obj2 = new v8f(3);
- g_test.assertFalse(obj1 === obj2);
- }
-};
-
-g_suite.testBrowserCanGetV8Properties = function() {
- var a = window.g_plugin.eval('({ p : 123 })');
- g_test.assertEquals(123, a.p);
-};
-
-g_suite.testBrowserCanSetV8Properties = function() {
- var a = window.g_plugin.eval('({ p : 123 })');
- a.p = 321;
- g_test.assertEquals(321, a.p);
-};
-
-g_suite.testBrowserCanGetV8ArrayElements = function() {
- var a = window.g_plugin.eval('([1, 2, 3])');
- g_test.assertEquals(2, a[1]);
-};
-
-g_suite.testBrowserCanGetV8ArrayLength = function() {
- var a = window.g_plugin.eval('([1, 2, 3])');
- g_test.assertEquals(3, a.length);
-};
-
-g_suite.testBrowserCanSetV8ArrayElements = function() {
- var a = window.g_plugin.eval('([1, 2, 3])');
- a[1] = 7;
- g_test.assertEquals(7, a[1]);
-};
-
-g_suite.testBrowserCanSetV8ArrayLength = function() {
- var a = window.g_plugin.eval('([1, 2, 3])');
- a.length = 10;
- g_test.assertEquals(10, a.length);
-};
-
-g_suite.testBrowserCanIterateOverV8Array = function() {
- // Chrome bug: http://code.google.com/p/chromium/issues/detail?id=5743
- if (!isChrome && !isFirefox2) {
- var a = window.g_plugin.eval('([1, 2, 3])');
- var total = 0;
- for (var i in a) {
- total += a[i];
- }
- g_test.assertEquals(6, total);
- }
-};
-
-g_suite.testBrowserCanQueryV8Properties = function() {
- var a = window.g_plugin.eval('({ p : 123 })');
- g_test.assertTrue('p' in a);
- g_test.assertFalse('q' in a);
- g_test.assertTrue(a.hasOwnProperty('p'));
- g_test.assertFalse(a.hasOwnProperty('q'));
-};
-
-g_suite.testBrowserCanQueryV8PropertiesThatAreUndefined = function() {
- var a = window.g_plugin.eval('({ p : undefined })');
- g_test.assertTrue('p' in a);
-};
-
-g_suite.testBrowserCanRemoveV8Properties = function() {
- // Firefox does not forward property deletions from the browser
- // through the NPAPI. Bug:
- // https://bugzilla.mozilla.org/show_bug.cgi?id=470291
- // Neither does Chrome:
- // http://code.google.com/p/chromium/issues/detail?id=5746
- if (!isChrome && !isSafari && !isFirefox) {
- var a = window.g_plugin.eval('({ p : 123 })');
- g_test.assertTrue(delete a.p);
- g_test.assertFalse('p' in a);
- }
-};
-
-g_suite.testBrowserCanInvokeV8Methods = function() {
- var obj = window.g_plugin.eval(
- 'function C() { this.f = 7; this.m = function() { return this.f; } } new C()');
- g_test.assertEquals(7, obj.m());
-};
-
-g_suite.testBrowserCanEnumerateV8Properties = function() {
- // Chrome bug: http://code.google.com/p/chromium/issues/detail?id=5743
- if (!isChrome && !isFirefox2) {
- var a = window.g_plugin.eval('var a = { p : 123 }; a[1] = 321; a');
- all = "";
- for (m in a) {
- all += m;
- }
-
- // The EcmaScript spec says the order property names are returned is
- // implementation dependent.
- g_test.assertTrue('1p' === all || 'p1' === all);
- }
-};
-
-g_suite.testStringValueOfV8ObjectInBrowserIsDefault = function() {
- var a = window.g_plugin.eval('({})');
- g_test.assertEquals('[object Object]', a.toString());
-};
-
-g_suite.testStringValueOfV8ObjectInBrowserCanBeOverriden = function() {
- var a = window.g_plugin.eval('({ toString: function() { return "foo"; } })');
- g_test.assertEquals('foo', a.toString());
-};
-
-g_suite.testV8SeesSameBrowserObjectAsEqualToItself = function() {
- if (!isSafari && !isChrome) {
- var v8f = window.g_plugin.eval('function(a, b) { return a === b; }');
- var obj = {};
- g_test.assertTrue(v8f(obj, obj));
- }
-};
-
-g_suite.testTypeofBrowserObjectInV8IsObject = function() {
- var v8f = window.g_plugin.eval('function(x) { return typeof(x); }');
- g_test.assertEquals('object', v8f({}));
-};
-
-// I put in this test because the V8 bridge code uses the absence of
-// a call property as an early out test when determining whether a
-// browser object is a function or not.
-g_suite.testTypeofBrowserObjectInV8IsObjectEvenIfItHasACallProperty =
- function() {
- var v8f = window.g_plugin.eval('function(x) { return typeof(x); }');
- g_test.assertEquals('object', v8f({ call: {} }));
-};
-
-g_suite.testTypeofBrowserFunctionInV8IsFunction = function() {
- var v8f = window.g_plugin.eval('function(x) { return typeof(x); }');
- g_test.assertEquals('function', v8f(function() {}));
-};
-
-g_suite.testV8CanInvokeBrowserFunctions = function() {
- var v8f = window.g_plugin.eval('function(f) { return f(); }');
- var f = function() { return 12; };
- g_test.assertEquals(12, v8f(f));
-};
-
-g_suite.testV8ReceivesExceptionOnInvokingUndefinedFunction = function() {
- var v8f = window.g_plugin.eval(
- 'function(f) { try { f(); } catch(e) { return e; } }');
- g_test.assertEquals("TypeError: undefined is not a function",
- v8f(undefined).toString());
-};
-
-g_suite.testV8CanInvokeBrowserConstructor = function() {
- window.Constructor = function(x) { this.p = x; };
- var obj = window.g_plugin.eval('new Constructor(7)');
- g_test.assertEquals(7, obj.p);
-};
-
-g_suite.testV8ReceivesExceptionOnInvokingUndefinedConstructor = function() {
- var v8f = window.g_plugin.eval(
- 'function(f) { try { new f(); } catch(e) { return e; } }');
- g_test.assertEquals("TypeError: undefined is not a function",
- v8f(undefined).toString());
-};
-
-g_suite.testV8CanGetConstructorFromBrowserObject = function() {
- window.Constructor = function(x) { this.p = x; };
- var obj = window.g_plugin.eval('new Constructor(7)');
- g_test.assertTrue(obj.constructor === window.Constructor);
-};
-
-g_suite.testV8CanGetBrowserProperties = function() {
- var a = { p: 123 };
- var v8f = window.g_plugin.eval('function(x) { return x.p; }');
- g_test.assertEquals(123, v8f(a));
-};
-
-g_suite.testV8ReceivesExceptionOnGettingPropertyFromUndefined = function() {
- var v8f = window.g_plugin.eval(
- 'function(x) { try { return x.p; } catch(e) { return e; } }');
- g_test.assertEquals("TypeError: Cannot read property 'p' of undefined",
- v8f(undefined).toString());
-};
-
-g_suite.testV8CodeReceivesUndefinedIfGettingBrowserPropertyFails = function() {
- var a = window.g_plugin.eval('plugin.nonExistentProperty');
- g_test.assertEquals(undefined, a);
-};
-
-g_suite.testV8CanSetBrowserProperties = function() {
- var a = { p: 123 };
- var v8f = window.g_plugin.eval('function(x) { x.p = 321; }');
- v8f(a);
- g_test.assertEquals(321, a.p);
-};
-
-g_suite.testV8CanGetBrowserArrayElements = function() {
- var a = [1, 2, 3];
- var v8f = window.g_plugin.eval('function(x) { return x[1]; }');
- g_test.assertEquals(2, v8f(a));
-};
-
-g_suite.testV8CodeReceivesUndefinedIfGettingBrowserNonExistentArrayElement =
- function() {
- var a = window.g_plugin.eval('plugin[17]');
- g_test.assertEquals(undefined, a);
-};
-
-g_suite.testV8CanGetBrowserArrayLength = function() {
- var a = [1, 2, 3];
- var v8f = window.g_plugin.eval('function(x) { return x.length; }');
- g_test.assertEquals(3, v8f(a));
-};
-
-g_suite.testV8CanSetBrowserArrayElements = function() {
- var a = [1, 2, 3];
- var v8f = window.g_plugin.eval('function(x) { x[1] = 7; }');
- v8f(a);
- g_test.assertEquals(7, a[1]);
-};
-
-g_suite.testV8CanSetBrowserArrayLength = function() {
- var a = [1, 2, 3];
- var v8f = window.g_plugin.eval('function(x) { x.length = 10; }');
- v8f(a);
- g_test.assertEquals(10, a.length);
-};
-
-g_suite.testV8CanIterateOverBrowserArray = function() {
- var a = [1, 2, 3];
- var v8f = window.g_plugin.eval(
- 'function(x) { var total = 0; for (var i in x) { total += x[i]; } return total; }');
- g_test.assertEquals(6, v8f(a));
-};
-
-g_suite.testIsArrayWorksInV8ForBrowserArrays = function() {
- var v8f = g_plugin.eval('function(x) { return o3djs.base.isArray(x); }');
- g_test.assertTrue(v8f([1, 2, 3]));
-};
-
-g_suite.testIsArrayWorksInV8ForV8Arrays = function() {
- g_test.assertFalse(g_plugin.eval('o3djs.base.isArray(undefined)'));
- g_test.assertFalse(g_plugin.eval('o3djs.base.isArray(7)'));
- g_test.assertTrue(g_plugin.eval('o3djs.base.isArray([1, 2, 3])'));
-};
-
-g_suite.testV8CanQueryBrowserProperties = function() {
- var a = { p : 123 }; a[1] = 321;
- var v8f = window.g_plugin.eval(
- 'function(x) { var all = ""; for (m in x) { all += m; } return all; }');
-
- // The EcmaScript spec says the order property names are returned is
- // implementation dependent.
- g_test.assertTrue('1p' === v8f(a) || 'p1' === v8f(a));
-};
-
-g_suite.testV8CanRemoveBrowserProperties = function() {
- if (!isSafari) {
- var a = { p : 123 };
- var v8f = window.g_plugin.eval('function(x) { return delete x.p; }');
- g_test.assertTrue(v8f(a));
- // check property does not exist
- g_test.assertEquals('undefined', typeof(a.p));
- // delete should still succeed if the property does not exist
- g_test.assertTrue(v8f(a));
- }
-};
-
-g_suite.testV8DeleteOperatorReturnsFalseIfPropertyCannotBeRemoved = function() {
- g_test.assertFalse(window.g_plugin.eval('delete plugin.client'));
-};
-
-g_suite.testV8CanInvokeBrowserMethods = function() {
- function C() { this.f = 7; this.m = function() { return this.f; } }
- c = new C();
- var v8f = window.g_plugin.eval('function(x) { return x.m(); }');
- g_test.assertEquals(7, v8f(c));
-};
-
-g_suite.testV8CodeReceivesAnExceptionIfBrowserMethodCallFails = function() {
- var v8f = window.g_plugin.eval(
- 'function() { try { plugin.nonExistentFunction(); } catch(e) { return e; } }');
- g_test.assertEquals(
- "TypeError: Object [object Object] has no method 'nonExistentFunction'",
- v8f().toString());
-};
-
-// This won't work until will can support intercepting on V8 objects built
-// from FunctionTemplates.
-//g_suite.testV8CanInvokeBrowserFunctionsWithExplicitThisThroughCallAndApply =
-// function() {
-// var this_copy, arg_copy;
-// function f(arg) { this_copy = this; arg_copy = arg; return arg; }
-// var v8f = window.g_plugin.eval('function(x) { return x(7); }');
-// var obj = {};
-// g_test.assertEquals(7, v8f.call(obj, 7));
-// g_test.assertEquals(obj, this_copy);
-// g_test.assertEquals(7, arg_copy);
-// obj = {};
-// g_test.assertEquals(8, v8f.apply(obj, [7]));
-// g_test.assertEquals(obj, this_copy);
-// g_test.assertEquals(8, arg_copy);
-//}
-
-g_suite.testStringValueOfBrowserObjectInV8IsDefault = function() {
- var v8f = window.g_plugin.eval('function(x) { return x.toString(); }');
- g_test.assertEquals('[object Object]', v8f({}));
-};
-
-g_suite.testStringValueOfBrowserObjectInV8CanBeOverriden = function() {
- var v8f = window.g_plugin.eval('function(x) { return x.toString(); }');
- g_test.assertEquals('foo', v8f({ toString: function() { return 'foo' } }));
-};
-
-g_suite.testV8CanInvokeNativeMethod = function() {
- g_test.assertEquals('My pack', window.g_plugin.eval(
- 'var pack = plugin.client.createPack(); pack.name = \"My pack\"; pack.name'));
-};
-
-g_suite.testV8CanInvokeNativeObject = function() {
- g_test.assertArrayEquals([-1, -1, -2], window.g_plugin.eval(
- 'var b = plugin.o3d.BoundingBox(' +
- '[-1, -1, -2], [1, 2, 4]); b.minExtent'));
-};
-
-g_suite.testV8ExceptionsInPluginEvalResultInErrorCallback = function() {
- var error = 'no error';
- var exceptionThrown = false;
- window.g_plugin.client.setErrorCallback(function(e) {
- error = e; });
- try {
- window.g_plugin.eval('throw "error";');
- } catch(e) {
- exceptionThrown = true;
- }
- // Chrome bug: http://code.google.com/p/chromium/issues/detail?id=5748
- if (!isChrome && !isSafari) {
- g_test.assertTrue(exceptionThrown);
- }
- g_test.assertEquals('Uncaught error in throw "error";', error);
-};
-
-g_suite.testV8ExceptionsInFunctionCallResultInErrorCallback = function() {
- var v8f = window.g_plugin.eval('function() { throw "error"; }');
- var error = 'no error';
- var exceptionThrown = false;
- window.g_plugin.client.setErrorCallback(function(e) {
- error = e; });
- try {
- v8f();
- } catch(e) {
- exceptionThrown = true;
- }
- // Chrome bug: http://code.google.com/p/chromium/issues/detail?id=5748
- if (!isChrome && !isSafari) {
- g_test.assertTrue(exceptionThrown);
- }
- g_test.assertEquals('Uncaught error in (function() { throw "error"; })',
- error);
-};
-
-g_suite.testV8ExceptionsInMethodCallResultInErrorCallback = function() {
- var obj = window.g_plugin.eval('({ f: function() { throw "error"; } })');
- var error = 'no error';
- var exceptionThrown = false;
- window.g_plugin.client.setErrorCallback(function(e) {
- error = e; });
- try {
- obj.f();
- } catch(e) {
- exceptionThrown = true;
- }
- // Chrome bug: http://code.google.com/p/chromium/issues/detail?id=5748
- if (!isChrome && !isSafari) {
- g_test.assertTrue(exceptionThrown);
- }
- g_test.assertEquals(
- 'Uncaught error in ({ f: function() { throw "error"; } })',
- error);
-};
-
-g_suite.testV8ExceptionsInConstructorCallResultInErrorCallback = function() {
- // Chrome bug: http://code.google.com/p/chromium/issues/detail?id=3285
- if (!isChrome && !isSafari && !isFirefox2) {
- var obj = window.g_plugin.eval('function() { throw "error"; }');
- var error = 'no error';
- var exceptionThrown = false;
- window.g_plugin.client.setErrorCallback(function(e) {
- error = e; });
- try {
- new obj();
- } catch(e) {
- exceptionThrown = true;
- }
- // Chrome bug: http://code.google.com/p/chromium/issues/detail?id=5748
- if (!isChrome && !isSafari) {
- g_test.assertTrue(exceptionThrown);
- }
- if (isChrome) {
- // Chrome does not expect parenthesis around the error.
- g_test.assertEquals(
- 'Uncaught error in function() { throw "error"; }', error);
- } else {
- g_test.assertEquals(
- 'Uncaught error in (function() { throw "error"; })', error);
- }
- }
-};
-
-g_suite.testV8CanAccessBrowserGlobals = function() {
- window.g_global = 7;
- g_test.assertEquals(7, window.g_plugin.eval('g_global'));
-};
-
-g_suite.testV8ModificationsToBrowserGlobalsAreOnlyLocallyVisible = function() {
- window.g_global = 7;
- g_test.assertEquals(8, window.g_plugin.eval('g_global = 8; g_global'));
- g_test.assertEquals(7, window.g_global);
-};
-
-g_suite.testV8CanAccessPluginThroughPluginGlobal = function() {
- // http://code.google.com/p/chromium/issues/detail?id=5751
- if (!isChrome && !isSafari) {
- g_test.assertEquals(g_plugin.client, window.g_plugin.eval('plugin.client'));
- }
-};
-
-g_suite.testEvalFailsWithBadArguments = function() {
- // Chrome bug: http://code.google.com/p/chromium/issues/detail?id=5748
- if (!isChrome && !isSafari) {
- var numExceptions = 0;
- try {
- window.g_plugin.eval();
- } catch (e) {
- ++numExceptions;
- }
- try {
- window.g_plugin.eval('a', 'b');
- } catch (e) {
- ++numExceptions;
- }
- try {
- window.g_plugin.eval(7);
- } catch (e) {
- ++numExceptions;
- }
- g_test.assertEquals(3, numExceptions);
- }
-};
-
-g_suite.testExceptionThrownIfV8CodeIsInvalid = function() {
- var error = 'no error';
- var exceptionThrown = false;
- window.g_plugin.client.setErrorCallback(function(e) {
- error = e; });
- try {
- window.g_plugin.eval('+1)');
- } catch (e) {
- exceptionThrown = true;
- }
- g_test.assertEquals('Uncaught SyntaxError: Unexpected token ) in (+1))',
- error);
- if (!isSafari && !isChrome) {
- g_test.assertTrue(exceptionThrown);
- }
-};
-
-g_suite.testV8CanAccessDOM = function() {
- if (!isInternetExplorer) {
- g_test.assertEquals('P', window.g_plugin.eval(
- "document.createElement('P').tagName"));
- }
-};
-
-g_suite.testV8CanRunUtilityCodeNatively = function() {
- var result = g_plugin.eval("o3djs.math.addVector([1, 2, 3], [3, 2, 1])");
- if (!isSafari) {
- g_test.assertArrayEquals([4, 4, 4], result);
- }
-};
-
-o3djs.provide('myNamespace');
-
-myNamespace.anUndefinedConstant = undefined;
-
-myNamespace.aNumberConstant = 7;
-
-myNamespace.aBooleanConstant = true;
-
-myNamespace.anEscapedStringConstant = 'foo\r\n\tbar';
-
-myNamespace.anUnescapedStringConstant = 'foo bar';
-
-myNamespace.aNullConstant = null;
-
-myNamespace.anObjectConstant = {a: 'foo'};
-
-myNamespace.anArrayConstant = [1, 2, 3];
-
-myNamespace.doSomething = function() {
- return 7;
-};
-
-myNamespace.AConstructor = function(a) {
- this.a = a;
-};
-
-myNamespace.AConstructor.prototype.getA = function() {
- return this.a;
-};
-
-myNamespace.getPlugin = function() {
- return plugin;
-};
-
-myNamespace.doSomethingInBrowser = function() {
- o3djs.BROWSER_ONLY;
- myNamespace.didSomethingInBrowser = true;
- return 7;
-};
-
-myNamespace.aRegExp = /Foo\n\r/gim;
-
-g_suite.testProvidedCodeRunsInV8 = function() {
- g_test.assertTrue('client' in g_plugin.eval('myNamespace.getPlugin()'));
-};
-
-g_suite.testV8CanAccessUndefinedInAProvidedNamespace = function() {
- myNamespace.anUndefinedConstant = 7;
- g_test.assertEquals(undefined, g_plugin.eval(
- 'myNamespace.anUndefinedConstant'));
-};
-
-g_suite.testV8CanAccessNumbersInAProvidedNamespace = function() {
- myNamespace.aNumberConstant = undefined;
- g_test.assertEquals(7, g_plugin.eval('myNamespace.aNumberConstant'));
-};
-
-g_suite.testV8CanAccessBooleansInAProvidedNamespace = function() {
- myNamespace.aBooleanConstant = undefined;
- g_test.assertTrue(g_plugin.eval('myNamespace.aBooleanConstant'));
-};
-
-g_suite.testV8CanAccessEscapedStringsInAProvidedNamespace = function() {
- myNamespace.anEscapedStringConstant = undefined;
- g_test.assertEquals('foo\r\n\tbar', g_plugin.eval(
- 'myNamespace.anEscapedStringConstant'));
-};
-
-g_suite.testV8CanAccessUneapedStringsInAProvidedNamespace = function() {
- myNamespace.anUnescapedStringConstant = undefined;
- g_test.assertEquals('foo bar', g_plugin.eval(
- 'myNamespace.anUnescapedStringConstant'));
-};
-
-g_suite.testV8CanAccessNullInAProvidedNamespace = function() {
- myNamespace.aNullConstant = undefined;
- g_test.assertEquals(null, g_plugin.eval('myNamespace.aNullConstant'));
-};
-
-g_suite.testV8CanAccessObjectsInAProvidedNamespace = function() {
- myNamespace.anObjectConstant = undefined;
- g_test.assertEquals('foo', g_plugin.eval('myNamespace.anObjectConstant.a'));
-};
-
-g_suite.testV8CanAccessArraysInAProvidedNamespace = function() {
- myNamespace.anArrayConstant = undefined;
- if (!isSafari) {
- g_test.assertArrayEquals([1, 2, 3], g_plugin.eval(
- 'myNamespace.anArrayConstant'));
- }
-};
-
-g_suite.testV8CanInvokeFunctionsInAProvidedNamespace = function() {
- myNamespace.doSomething = undefined;
- g_test.assertEquals(7, g_plugin.eval('myNamespace.doSomething()'));
-};
-
-g_suite.testV8CanInvokeConstructorsAndPrototypeMethodsInAProvidedNamespace =
- function() {
- myNamespace.AConstructor = undefined;
- g_test.assertEquals(7, g_plugin.eval(
- 'new myNamespace.AConstructor(7).getA()'));
-};
-
-g_suite.testV8CanInvokeFunctionsAnnotatedAsRunningInTheBrowser = function() {
- g_test.assertEquals(7, g_plugin.eval('myNamespace.doSomethingInBrowser()'));
- g_test.assertTrue(myNamespace.didSomethingInBrowser);
-};
-
-g_suite.textV8CanAccessRegExpInAProvidedNamespace = function() {
- myNamespace.aRegExp = undefined;
- g_test.assertEquals('Foo\n\r', g_plugin.eval('myNamespace.aRegExp.source'));
- g_test.assertTrue(g_plugin.eval('myNamespace.aRegExp.global'));
- g_test.assertTrue(g_plugin.eval('myNamespace.aRegExp.multiline'));
- g_test.assertTrue(g_plugin.eval('myNamespace.aRegExp.ignoreCase'));
-}
-
-g_suite.testV8CanAccessBrowserO3djs = function() {
- g_test.assertEquals(o3djs, g_plugin.eval('o3djs.browser'));
-};
-
-g_suite.testV8CanAccessGlobalsThroughO3djs = function() {
- g_test.assertEquals(navigator.userAgent,
- g_plugin.eval('o3djs.global.navigator.userAgent'));
-};
-
-g_suite.testV8CanAccessO3dNamespaceThroughO3djs = function() {
- g_test.assertTrue(g_plugin.eval('g_plugin.o3d === o3djs.base.o3d'));
-};
-
-function initStep2(clientElements) {
- g_test = o3djs.test;
- g_plugin = clientElements[0];
- g_testResult = g_test.runTests(g_suite);
-};
-
-window.onload = function() {
- o3djs.util.makeClients(initStep2);
-};
-
-</script>
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/version-check-test.html b/o3d/tests/selenium/tests/version-check-test.html
deleted file mode 100644
index fcc3acb..0000000
--- a/o3d/tests/selenium/tests/version-check-test.html
+++ /dev/null
@@ -1,90 +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.
--->
-
-<!--
-Test we can check for the version.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Version Check
-</title>
-<!-- Include sample javascript library functions-->
-<script
- type="text/javascript"
- src="../../../samples/o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-
-// global variables
-var g_testResult;
-
-/**
- * Request version 999999 which should always fail.
- */
-function init() {
- o3djs.util.makeClients(haveVersion, '', '999999', dontHaveVersion);
-}
-
-function dontHaveVersion() {
- document.getElementById('result').innerHTML =
- 'success: version 999999 not available';
- g_testResult = true;
-}
-
-/**
- *
- */
-function haveVersion() {
- document.getElementById('result').innerHTML =
- 'failure: version 999999 is supposedly available!';
- g_testResult = false;
-}
-</script>
-</head>
-<body>
-<h1>Version Check</h1>
-Check that asking for a non-existent version fails<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 200px; height: 200px;"></div>
-<!-- End of O3D plugin -->
-<div>Result: <span id="result"></span><div>
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/window-overlap-test.html b/o3d/tests/selenium/tests/window-overlap-test.html
deleted file mode 100644
index 8a7910e..0000000
--- a/o3d/tests/selenium/tests/window-overlap-test.html
+++ /dev/null
@@ -1,119 +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.
--->
-
-<!--
-Window Overlap Test
-
-Make sure client areas that are not visible because of overlapping windows do
-not render.
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Window Overlap Test
-</title>
-<!-- Include sample javascript library functions-->
-<script type="text/javascript" src="../../../samples/o3djs/base.js"></script>
-
-<!-- Our javascript code -->
-<script type="text/javascript" id="o3dscript">
-o3djs.require('o3djs.util');
-o3djs.require('o3djs.rendergraph');
-
-// Events
-// init() once the page has finished loading.
-// unload() when the page is unloaded.
-window.onload = init;
-window.onunload = uninit;
-
-// global variables
-var g_client;
-var g_pack;
-var g_viewInfo;
-var g_renderCount = 0;
-var g_finished = false;
-
-function onRender() {
- g_viewInfo.clearBuffer.clearColor = [Math.random(),
- Math.random(),
- Math.random(),
- 1];
- g_renderCount += 1;
-}
-
-/**
- * Creates the client areas.
- */
-function init() {
- o3djs.util.makeClients(initStep2);
-}
-
-/**
- * Initializes O3D and loads the model into the transform graph.
- * @param {Array} clientElements Array of o3d object elements.
- */
-function initStep2(clientElements) {
- var o3dElement = clientElements[0];
-
- g_client = o3dElement.client;
- g_pack = g_client.createPack();
-
- g_viewInfo = o3djs.rendergraph.createBasicView(
- g_pack,
- g_client.root,
- g_client.renderGraphRoot);
-
- g_client.setRenderCallback(onRender);
-
- g_finished = true;
-}
-
-/**
- * Cleans up.
- */
-function uninit() {
- g_client.clearRenderCallback();
-}
-</script>
-</head>
-<body>
-<h1>Window Overlap Test</h1>
-This test verifies that client areas that are not visible because of overlapping
-windows do not render.
-<br/>
-<!-- Start of O3D plugin -->
-<div id="o3d" style="width: 100px; height: 100px;"></div>
-<!-- End of O3D plugin -->
-</body>
-</html>
diff --git a/o3d/tests/selenium/tests/window-overlap-top.html b/o3d/tests/selenium/tests/window-overlap-top.html
deleted file mode 100644
index 8243465..0000000
--- a/o3d/tests/selenium/tests/window-overlap-top.html
+++ /dev/null
@@ -1,63 +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.
--->
-
-<!--
-Window Overlap Test Top
-
-See window-overlap-test.html
--->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-<title>
-Window Overlap Test Top Window
-</title>
-<script type="text/javascript" id="o3dscript">
-// Events
-// init() once the page has finished loading.
-window.onload = init;
-
-var g_finished = false;
-
-function init() {
- g_finished = true;
-}
-</script>
-</head>
-<body>
-<h1>Window Overlap Test Top Window</h1>
-This test verifies that client areas that are not visible because of overlapping
-windows do not render.
-<br/>
-</body>
-</html>
diff --git a/o3d/tests/selenium/unpack_firefox.py b/o3d/tests/selenium/unpack_firefox.py
deleted file mode 100644
index a969c44..0000000
--- a/o3d/tests/selenium/unpack_firefox.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/env python
-
-import sys
-import os
-import shutil
-import subprocess
-
-script_dir = os.path.normpath(os.path.dirname(os.path.abspath(__file__)))
-o3d_dir = os.path.dirname(os.path.dirname(script_dir))
-src_dir = os.path.dirname(o3d_dir)
-third_party_dir = os.path.join(o3d_dir, 'third_party')
-internal_dir = os.path.join(src_dir, 'o3d-internal')
-gflags_dir = os.path.join(third_party_dir, 'gflags', 'python')
-sys.path.append(gflags_dir)
-
-import gflags
-
-# Command line flags
-FLAGS = gflags.FLAGS
-gflags.DEFINE_boolean("cleanup", False,
- "If this is set, then the script cleans up "
- "instead of unpacking.")
-gflags.DEFINE_string("plugin_path", "", "This is the path to the plugin.")
-gflags.DEFINE_string("product_path", "",
- "This is the path to the built products.")
-
-if sys.platform != "darwin":
- print "This script is only for use on Mac OS X"
- sys.exit(-1)
-
-def Cleanup(dir):
- shutil.rmtree(dir, ignore_errors=True)
-
-def InstallInternal(internal_firefox_dir, firefox_dir):
- firefox_app = os.path.join(firefox_dir, 'Firefox.app')
- firefox_tgz = os.path.join(internal_firefox_dir, 'firefox.tgz')
- print "Unpacking Firefox in '%s' to staging area." % firefox_tgz
- os.mkdir(firefox_dir)
- subprocess.call(['tar', '-C', firefox_dir, 'xfz', firefox_tgz])
- dest_plugin_path = os.path.join(firefox_app, 'Contents', 'MacOS',
- 'plugins',
- os.path.basename(FLAGS.plugin_path))
- os.symlink(FLAGS.plugin_path, dest_plugin_path)
- return 0
-
-def Install(firefox_dir):
- # No hermetic version, look for Firefox.app in /Applications
- source_app = '/Applications/Firefox.app'
- print "Copying Firefox in '%s' to staging area." % source_app
-
- if not os.path.exists(source_app):
- print "Unable to find Firefox in %s, is it installed?" % source_app
- sys.exit(-1)
-
- firefox_app = os.path.join(firefox_dir, 'Firefox.app')
- dest_plugin_path = os.path.join(firefox_app, 'Contents', 'MacOS',
- 'plugins',
- os.path.basename(FLAGS.plugin_path))
- os.mkdir(firefox_dir)
- subprocess.call(['ditto', source_app, firefox_app])
- os.symlink(FLAGS.plugin_path, dest_plugin_path)
- return 0
-
-def main(args):
- internal_firefox_dir = os.path.join(internal_dir, 'firefox')
- if not os.path.exists(FLAGS.plugin_path):
- print "Plugin '%s' is missing." % FLAGS.plugin_path
- sys.exit(-1)
-
- if not os.path.exists(FLAGS.product_path):
- print "Product path '%s' is missing." % FLAGS.product_path
- sys.exit(-1)
-
- # Cleanup any residual stuff.
- firefox_dir = os.path.join(FLAGS.product_path, 'selenium_firefox')
- Cleanup(firefox_dir)
-
- if not FLAGS.cleanup:
- # if we have a hermetic version of Firefox, then use it.
- if os.path.exists(internal_firefox_dir):
- sys.exit(InstallInternal(internal_firefox_dir, firefox_dir))
- # Otherwise, we just copy what the user has installed.
- else:
- if not FLAGS.cleanup:
- sys.exit(Install(firefox_dir))
- sys.exit(0)
-
-if __name__ == "__main__":
- bare_args = FLAGS(sys.argv)
- main(bare_args)
diff --git a/o3d/tests/test_driver.bat b/o3d/tests/test_driver.bat
deleted file mode 100644
index c9e0e4a..0000000
--- a/o3d/tests/test_driver.bat
+++ /dev/null
@@ -1,33 +0,0 @@
-@echo off
-REM Copyright 2009, Google Inc.
-REM All rights reserved.
-REM
-REM Redistribution and use in source and binary forms, with or without
-REM modification, are permitted provided that the following conditions are
-REM met:
-REM
-REM * Redistributions of source code must retain the above copyright
-REM notice, this list of conditions and the following disclaimer.
-REM * Redistributions in binary form must reproduce the above
-REM copyright notice, this list of conditions and the following disclaimer
-REM in the documentation and/or other materials provided with the
-REM distribution.
-REM * Neither the name of Google Inc. nor the names of its
-REM contributors may be used to endorse or promote products derived from
-REM this software without specific prior written permission.
-REM
-REM THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-REM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-REM LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-REM A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-REM OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-REM SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-REM LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-REM DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-REM THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-REM (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-REM OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-set PYTHONDIR=%~dp0..\..\..\..\third_party\python_24
-call %PYTHONDIR%\setup_env.bat
-%PYTHONDIR%\python.exe %~dp0\test_driver.py %*
diff --git a/o3d/tests/test_driver.py b/o3d/tests/test_driver.py
deleted file mode 100644
index 891ecec..0000000
--- a/o3d/tests/test_driver.py
+++ /dev/null
@@ -1,433 +0,0 @@
-#!/usr/bin/python2.4
-# 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.
-
-
-"""Test harness script that invokes O3D system-tests.
-
-This script constructs the necessary testing environment required for the
-DirectX-based O3D system-tests. It invokes each test within the PIX
-debugging tool to capture the graphics command stream and framebuffer
-contents.
-
-See (http://wiki.corp.google.com/twiki/bin/view/Main/ClientThreeDTestingPlan)
-for the o3d testing plan.
-
-Usage:
- test_driver.py [-capture_only] [-hardware]
-
-The script will scan all of the directories, and invoke system-tests for all
-<name>_test directories present. Each of the system-tests in system_tests.exe
-will be invoked one at a time through PIXWin.exe. PIX has been configured
-to interact with the testing framework to capture graphics command streams
-and framebuffer contents.
-
-After the test has executed, the script will parse the persisted log files
-and compare the generated results.
-
-The framework assumes that each test-case is named with a camel-caps
-translation of the directory name. So in the case of the directory
-tests\import_test, the system invokes the gUnit test ImportTest.
-
-Command Arguments:
- -capture_only: The script will only capture results. All verification with
- reference-data will be bypassed. This flag should be used when updating the
- reference-data.
-
- - hardware: The the system tests will execute using the graphics hardware, as
- opposed to the software reference rasterizer. Use this mode to look for
- problems related to a specific hardware platform.
-"""
-
-
-import os
-import re
-from stat import ST_MODE
-from stat import S_ISDIR
-import sys
-
-_PIX_EXECUTABLE = '.\PIXWin.exe'
-
-# Template for the command line required to invoke a system-test within PIX.
-_PIX_EXPERIMENT_INVOKE = ('%s %s -start -runfile %s -targetstartfolder %s '
- '-targetargs %s')
-
-# Template for the command line required to invoke PIX when constructing a
-# .csv file from a .PIXRun file.
-_PIX_RUNFILE_INVOKE = '%s %s -exporttocsv %s'
-
-# Template command line argument for the gunit system that selectively
-# executes individual groups of tests.
-_GUNIT_INVOKE = '--gunit_filter=%s.*'
-_SYSTEM_TEST = '.\system_test.exe'
-_EXPERIMENT_FILE_REFERENCE = 'testing_framework_reference.PIXExp'
-_EXPERIMENT_FILE_HARDWARE = 'testing_framework_hardware.PIXExp'
-
-# Command line required to invoke the perceptual diff utility.
-_PDIFF = ('perceptualdiff.exe %s %s -verbose -fov 45 -threshold 40000')
-
-# Regular expression used to search for hexadecimal pointer values in
-# generated log files
-_HEX_EXPRESSION = re.compile('0x[0-9ABCDEF]+')
-
-# Constant command argument string to enable capture-only mode.
-_CAPTURE_FLAG = '-capture_only'
-
-# Command flags to specify usage of the hardware rasterizer for the tests.
-_HARDWARE_RASTERIZER = '-hardware'
-
-# Boolen set to True if test results should be captured and not validated.
-_GENERATE_ONLY = False
-
-# Boolean set to True if hardware rasterizer is to be used instead of the DX
-# reference rasterizer.
-_HARDWARE_DEVICE = False
-
-
-def ConstructTestName(filesystem_name):
- """Returns a camel-caps translation of the input string.
-
- Args:
- filesystem_name: The name of the test, as found on the file-system.
- Typically this name is_of_this_form.
-
- Returns:
- A camel-caps version of the input string. _ delimiters are removed, and
- the first letters of words are capitalized.
- """
- names = filesystem_name.split('_')
- test_name = ''
- for word in names:
- test_name += word.upper()[0] + word[1:]
- return test_name
-
-
-def AssertCapturedFrames(test_name):
- """Performs the image validation for test-case frame captures.
-
- Args:
- test_name: The name of the test, as found on the file-system.
-
- Returns:
- True if all images match within tolerance, false otherwise.
- """
- print 'Status: Validating captured frames against reference data.'
-
- reference_files = os.listdir('./' + test_name + '/reference_frames')
- generated_files = os.listdir('./' + test_name)
- generated_files = [(file_name) for file_name in generated_files
- if '.png' in file_name]
-
- if set(reference_files) != set(generated_files):
- print 'Error: Reference file set does not match generated file set.'
- print 'Reference files: ' + ', '.join(reference_files)
- print 'Generated files: ' + ', '.join(generated_files)
- return False
-
- # Assuming both the result and reference image sets are the same size,
- # verify that corresponding images are similar within tolerance.
- for file in reference_files:
- reference_file = test_name + '/reference_frames/' + file
- generated_file = test_name + '/' + file
- if os.system(_PDIFF % (reference_file, generated_file)):
- error = ('Error: Reference framebuffer (%s) does not match generated '
- 'file (%s).')
- print error % (reference_file, generated_file)
- return False
-
- return True
-
-
-def GenerateCSVStream(test_name):
- """Invokes PIX to convert a PIXRun file to a .csv file.
-
- Args:
- test_name: The name of the test for which the .csv file is
- to be generated.
- """
-
- runfile_invoke = _PIX_RUNFILE_INVOKE % (
- _PIX_EXECUTABLE,
- test_name + '/' + test_name + '.PIXRun',
- test_name + '/' + test_name + '.csv')
-
- os.system(runfile_invoke)
-
-
-def RemovePointerReferences(call_log):
- """Returns the input argument with all pointer values removed.
-
- Args:
- call_log: String containing an dx call-log entry.
-
- Returns:
- The input string with all substrings matching '0x[0-9A-F]+', which is the
- pointer syntax used for the log files, removed.
- """
-
- return _HEX_EXPRESSION.sub('', call_log)
-
-
-def PartitionCSVLine(line):
- """Returns a list of all column values in a comma-separated-value line.
-
- Args:
- line: The input line from a comma-separated-value source.
-
- Returns:
- CSV files may include quoted text segments containing commas. This
- routine will return an array of all of the columns present in the line,
- respecting quoted regions.
- """
-
- # This routine is more complicated than expected due to the presence of
- # quoted lists within colums. The algorithm proceeds by first splitting
- # the line by quoted sub-strings. Sub-strings not matching a quoted
- # expression are then split on ','.
- quoted_column = re.compile('(\"[^\"]*\")')
- block_partitions = quoted_column.split(line)
-
- output_columns = []
-
- for chunk in block_partitions:
- # If this chunk is a quoted string, append it to the output verbatim.
- if quoted_column.match(chunk):
- output_columns += [chunk]
- else:
- output_columns += chunk.split(',')
-
- # Return the output set of columns with all empty entries removed.
- # Empty columns will be present due to the interaction of the split by
- # quoted string, and split by ','.
- # For example: here, is, "a (tuple, example)", to, try
- # After the first split: ['here, is, ', 'a (tuple, example)', 'to, try']
- # After the second split:
- # ['here', 'is', '', 'a (tuple, example)', 'to', 'try']
- # Since these empty columns are not present in the original list, we remove
- # them here.
- return [(column) for column in output_columns if column != ""]
-
-
-def AssertCapturedStreams(test_name):
- """Performes graphics command stream verification for test with name
- test_name.
-
- Args:
- test_name: The name of the test, as found on the file-system.
-
- Returns:
- Returns true if the generated testing streams match the reference streams.
- """
-
- print 'Status: Validating generated command streams.'
-
- generated_stream = open(test_name + '/' + test_name + '.csv')
- reference_stream = open(test_name + '/reference_stream.csv')
-
- reference_lines = reference_stream.readlines()
- generated_lines = generated_stream.readlines()
-
- if len(reference_lines) != len(generated_lines):
- print 'Error: Reference and generated logs differ in length.'
- return False
-
- # Compare each of the log lines from both files.
- for index in range(0, len(reference_lines)):
- generated_line = generated_lines[index]
- reference_line = reference_lines[index]
-
- # Partition each csv line correctly wrt quoted blocks
- reference_columns = PartitionCSVLine(reference_line)
- generated_columns = PartitionCSVLine(generated_line)
-
- # Only perform deep-validation on 'Call' commands.
- if reference_columns[0] != 'Call':
- continue
-
- generated_log = RemovePointerReferences(generated_columns[2])
- reference_log = RemovePointerReferences(reference_columns[2])
-
- if (generated_log != reference_log or
- reference_columns[0] != generated_columns[0] or
- reference_columns[1] != generated_columns[1]):
- print 'Error: Log file mis-match. Line: %i' % index
- print 'Reference = %s' % reference_line
- print 'Generated = %s' % generated_line
- return False
-
- return True
-
-
-def InvokeTest(test_name):
- """Invoke the system-test with name test_name.
-
- Args:
- test_name: The name of the test, as found on the file-system.
-
- Returns:
- True if the test succeeds, false otherwise.
- """
-
- global _GENERATE_ONLY
-
- if _HARDWARE_DEVICE:
- pix_experiment_file = _EXPERIMENT_FILE_HARDWARE
- else:
- pix_experiment_file = _EXPERIMENT_FILE_REFERENCE
-
- print 'Status: Executing test : %s\n' % test_name
- gunit_invoke = _GUNIT_INVOKE % ConstructTestName(test_name)
- pix_invoke = _PIX_EXPERIMENT_INVOKE % (_PIX_EXECUTABLE,
- pix_experiment_file,
- test_name + '.PIXRun',
- test_name,
- gunit_invoke)
- os.system(pix_invoke)
-
- # Invoke PIX to translate the just created .PIXRun file to a .csv suitable
- # for parsing.
- GenerateCSVStream(test_name)
-
- # If invoked for capture-only, then exit here before validation.
- if _GENERATE_ONLY:
- return True
-
- if not(AssertCapturedFrames(test_name)):
- return False
-
- if not(AssertCapturedStreams(test_name)):
- return False
-
- return True
-
-
-def BuildTestList():
- """Returns a list of all available system tests.
-
- Returns:
- A list of test_names, constructed from the set of directory names
- in the current directory. All directories containing the substring
- 'test' are included in the returned set.
- """
-
- testing_directory = os.listdir('.')
- test_list = []
-
- for test in testing_directory:
- mode = os.stat(test)[ST_MODE]
- if ('test' in test and test != 'unittest_data' and
- test != 'bitmap_test' and
- test != 'conditioner_test_data' and S_ISDIR(mode)):
- test_list += [test]
- return test_list
-
-
-def ValidateArgs(argv):
- """Validates the script arguments, and displays a help message,
- if necessary.
-
- Args:
- argv: Array of script arguments, in argv format.
-
- Returns:
- True if the arguments are valid. See the usage description for
- valid arguments.
- """
-
- global _GENERATE_ONLY
- global _HARDWARE_DEVICE
-
- # TODO : Make use of the gflags library to ease parsing of command line
- # arguments.
- argument_set = [_CAPTURE_FLAG, _HARDWARE_RASTERIZER]
-
- for arg in argv[1:]:
- if arg not in argument_set:
- print 'O3D System-Test Harness - Usage:'
- print ('test_driver.py [' + _CAPTURE_FLAG + '] [' +
- _HARDWARE_RASTERIZER + ']')
- print 'Arguments:'
- print _CAPTURE_FLAG + ' : Force generation of reference data.'
- print (_HARDWARE_RASTERIZER +
- ' : Force usage of hardware for test data generation')
- return False
-
- if _CAPTURE_FLAG in argv[1:]:
- _GENERATE_ONLY = True
-
- if _HARDWARE_RASTERIZER in argv[1:]:
- print 'Rendering with local graphics hardware.'
- _HARDWARE_DEVICE = True
- else:
- print 'Rendering with DX9 reference rasterizer.'
-
- return True
-
-
-def main(argv):
- """Main entry point of the script.
-
- Args:
- argv: The c-like arguments to the script.
-
- Returns:
- True if all tests pass, false othwerwise.
- """
-
- print 'Running O3D system tests.'
-
- if not ValidateArgs(argv):
- return False
-
- os.chdir(os.path.dirname(argv[0]))
-
- test_set = BuildTestList()
-
- # Invoke each test, tracking failures.
- test_failures = []
- for test in test_set:
- if not InvokeTest(test):
- test_failures += [test]
-
- if len(test_failures) == 0:
- print 'Success: All tests passed.'
- return True
- else:
- print 'Error Summary: The following tests failed:'
- print test_failures
- return False
-
-
-if __name__ == '__main__':
- if main(sys.argv):
- # Return with a 0 for success (per unix convention).
- sys.exit(0)
- else:
- # Return with a 1 for failure (per unix convention).
- sys.exit(1)
diff --git a/o3d/tests/testing_framework_hardware.PIXExp b/o3d/tests/testing_framework_hardware.PIXExp
deleted file mode 100644
index 0495ae03..0000000
--- a/o3d/tests/testing_framework_hardware.PIXExp
+++ /dev/null
@@ -1,2 +0,0 @@
-<?xml version="1.0"?>
-<PIXExperiment><Version><ExpFileVersion>202</ExpFileVersion></Version><TargetApp><TargetPath>system_tests.exe</TargetPath><StartFolder></StartFolder><Args></Args><SkipProcesses>0</SkipProcesses><RecordDiagnosticLog>0</RecordDiagnosticLog><IncludeDebugSpew>0</IncludeDebugSpew><DisableD3DXAnalysis>0</DisableD3DXAnalysis></TargetApp><Columns><Column><Name>EDID</Name><ColumnID>1</ColumnID><Flags>0</Flags><Type>3</Type><Format>%d</Format></Column><Column><Name>Event Type</Name><ColumnID>2</ColumnID><Flags>0</Flags><Type>3</Type><Format>%d</Format></Column><Column><Name>EID</Name><ColumnID>3</ColumnID><Flags>0</Flags><Type>3</Type><Format>%d</Format></Column><Column><Name>Parent EID</Name><ColumnID>4</ColumnID><Flags>0</Flags><Type>3</Type><Format>%d</Format></Column><Column><Name>Children</Name><ColumnID>11</ColumnID><Flags>0</Flags><Type>6</Type><Format>%d</Format></Column><Column><Name>Parent</Name><ColumnID>10</ColumnID><Flags>0</Flags><Type>2</Type><Format>%d</Format></Column><Column><Name>Flags</Name><ColumnID>5</ColumnID><Flags>0</Flags><Type>2</Type><Format>0x%08X</Format></Column><Column><Name>Event</Name><ColumnID>6</ColumnID><Flags>0</Flags><Type>4</Type><Format>%s</Format></Column><Column><Name>StartTime</Name><ColumnID>7</ColumnID><Flags>0</Flags><Type>5</Type><Format>%I64i</Format></Column><Column><Name>Path</Name><ColumnID>13</ColumnID><Flags>0</Flags><Type>1</Type><Format>%s</Format></Column><Column><Name>Path2</Name><ColumnID>14</ColumnID><Flags>0</Flags><Type>1</Type><Format>%s</Format></Column><Column><Name>Version</Name><ColumnID>15</ColumnID><Flags>0</Flags><Type>1</Type><Format>%s</Format></Column><Column><Name>TimeLastModified</Name><ColumnID>16</ColumnID><Flags>0</Flags><Type>1</Type><Format>%s</Format></Column><Column><Name>ProcessID</Name><ColumnID>23</ColumnID><Flags>0</Flags><Type>3</Type><Format>%d</Format></Column><Column><Name>SessionStartTimeStamp</Name><ColumnID>24</ColumnID><Flags>0</Flags><Type>5</Type><Format>%I64i</Format></Column><Column><Name>Frame</Name><ColumnID>9</ColumnID><Flags>0</Flags><Type>3</Type><Format>%d</Format></Column><Column><Name>Duration</Name><ColumnID>8</ColumnID><Flags>0</Flags><Type>5</Type><Format>%I64i</Format></Column><Column><Name>FPS</Name><ColumnID>12</ColumnID><Flags>0</Flags><Type>0</Type><Format>%0.01f</Format></Column><Column><Name>ThisEventPos</Name><ColumnID>21</ColumnID><Flags>0</Flags><Type>5</Type><Format>%I64i</Format></Column><Column><Name>NextSiblingPos</Name><ColumnID>22</ColumnID><Flags>0</Flags><Type>5</Type><Format>%I64i</Format></Column><Column><Name>User Event Name</Name><ColumnID>17</ColumnID><Flags>0</Flags><Type>1</Type><Format>%s</Format></Column><Column><Name>PackedCallPackage</Name><ColumnID>19</ColumnID><Flags>0</Flags><Type>7</Type><Format></Format></Column><Column><Name>Object Pointer</Name><ColumnID>20</ColumnID><Flags>0</Flags><Type>2</Type><Format>0x%08X</Format></Column></Columns><EventDescs><EventDesc><Name>Session Start</Name><EventType>1</EventType><EDID>1</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,1</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>CalcOnLoad,Const,-1</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>8</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,0,Start Session</String></EventDescColumn><EventDescColumn><ColumnID>13</ColumnID><String>(expfilepath)</String></EventDescColumn><EventDescColumn><ColumnID>14</ColumnID><String>(runfilepath)</String></EventDescColumn><EventDescColumn><ColumnID>24</ColumnID><String>(sessionstarttimestamp)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>Session End</Name><EventType>2</EventType><EDID>2</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,2</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>CalcOnLoad,Const,-1</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>8</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,0,End Session</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>Process Start</Name><EventType>3</EventType><EDID>3</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,3</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>CalcOnLoad,Const,-1</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>8</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,0,Start Process</String></EventDescColumn><EventDescColumn><ColumnID>13</ColumnID><String>(processpath)</String></EventDescColumn><EventDescColumn><ColumnID>15</ColumnID><String>(processversion)</String></EventDescColumn><EventDescColumn><ColumnID>16</ColumnID><String>(processtimelastmodified)</String></EventDescColumn><EventDescColumn><ColumnID>23</ColumnID><String>(processid)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>Process End</Name><EventType>4</EventType><EDID>4</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,4</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>CalcOnLoad,Const,-1</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>8</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,0,End Process</String></EventDescColumn><EventDescColumn><ColumnID>13</ColumnID><String>(processpath)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>Frame Begin</Name><EventType>5</EventType><EDID>5</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,5</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>(parenteid)</String></EventDescColumn><EventDescColumn><ColumnID>11</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>(rowflags)</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>9</ColumnID><String>(frame)</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,1,Frame %d,3,MemberOf,ThisRow,Frame</String></EventDescColumn><EventDescColumn><ColumnID>8</ColumnID><String>Async,(duration)</String></EventDescColumn><EventDescColumn><ColumnID>12</ColumnID><String>CalcOnLoad,Divide,Const,1000000000.0,MemberOf,ThisRow,Duration</String></EventDescColumn><EventDescColumn><ColumnID>21</ColumnID><String>(frameeventfilepos)</String></EventDescColumn><EventDescColumn><ColumnID>22</ColumnID><String>(lastframeeventfilepos)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>User Event Begin</Name><EventType>7</EventType><EDID>6</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,7</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>(parenteid)</String></EventDescColumn><EventDescColumn><ColumnID>10</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>11</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>17</ColumnID><String>(usereventname)</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,1,User Event: %s,1,MemberOf,ThisRow,User Event Name</String></EventDescColumn><EventDescColumn><ColumnID>8</ColumnID><String>Async,(duration)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>User Marker</Name><EventType>9</EventType><EDID>7</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,9</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>(parenteid)</String></EventDescColumn><EventDescColumn><ColumnID>10</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>11</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>17</ColumnID><String>(usereventname)</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,1,User Marker: %s,1,MemberOf,ThisRow,User Event Name</String></EventDescColumn><EventDescColumn><ColumnID>8</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>D3D Call</Name><EventType>10</EventType><EDID>8</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,10</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>(parenteid)</String></EventDescColumn><EventDescColumn><ColumnID>11</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>10</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,CallPlusParams,MemberOf,ThisRow,PackedCallPackage</String></EventDescColumn><EventDescColumn><ColumnID>19</ColumnID><String>Async,(packedcallpkg)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>Object Creation</Name><EventType>11</EventType><EDID>9</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,11</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>(parenteid)</String></EventDescColumn><EventDescColumn><ColumnID>11</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>10</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,0,Object Creation</String></EventDescColumn><EventDescColumn><ColumnID>20</ColumnID><String>(objpointer)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>Object Population</Name><EventType>12</EventType><EDID>10</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,12</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>(parenteid)</String></EventDescColumn><EventDescColumn><ColumnID>11</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>10</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,0,Object Population</String></EventDescColumn><EventDescColumn><ColumnID>20</ColumnID><String>(objpointer)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>D3D Call (Sync)</Name><EventType>13</EventType><EDID>11</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,13</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>(parenteid)</String></EventDescColumn><EventDescColumn><ColumnID>11</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>10</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,CallPlusParams,MemberOf,ThisRow,PackedCallPackage</String></EventDescColumn><EventDescColumn><ColumnID>19</ColumnID><String>(packedcallpkg)</String></EventDescColumn></EventDescColumns></EventDesc></EventDescs><Counters/><Triggers><Trigger><Type>1</Type><Recurrence>0</Recurrence><Actions><Action><Type>1</Type><Int1>1</Int1><Str1>import_test</Str1></Action></Actions></Trigger><Trigger><Type>4</Type><Str1>BeginCommandStreamCapture</Str1><Recurrence>1</Recurrence><Actions><Action><Type>3</Type><Int1>1</Int1><Int2>1</Int2></Action></Actions></Trigger><Trigger><Type>4</Type><Str1>EndCommandStreamCapture</Str1><Recurrence>1</Recurrence><Actions><Action><Type>3</Type><Int1>0</Int1><Int2>0</Int2></Action></Actions></Trigger><Trigger><Type>4</Type><Str1>CaptureScreenContents</Str1><Recurrence>1</Recurrence><Actions><Action><Type>4</Type><Int1>19</Int1><Str1>frame_capture</Str1><Str2>.png</Str2></Action></Actions></Trigger></Triggers></PIXExperiment>
diff --git a/o3d/tests/testing_framework_reference.PIXExp b/o3d/tests/testing_framework_reference.PIXExp
deleted file mode 100644
index 5a86d5d..0000000
--- a/o3d/tests/testing_framework_reference.PIXExp
+++ /dev/null
@@ -1,2 +0,0 @@
-<?xml version="1.0"?>
-<PIXExperiment><Version><ExpFileVersion>202</ExpFileVersion></Version><TargetApp><TargetPath>system_tests.exe</TargetPath><StartFolder></StartFolder><Args></Args><SkipProcesses>0</SkipProcesses><RecordDiagnosticLog>0</RecordDiagnosticLog><IncludeDebugSpew>0</IncludeDebugSpew><DisableD3DXAnalysis>0</DisableD3DXAnalysis></TargetApp><Columns><Column><Name>EDID</Name><ColumnID>1</ColumnID><Flags>0</Flags><Type>3</Type><Format>%d</Format></Column><Column><Name>Event Type</Name><ColumnID>2</ColumnID><Flags>0</Flags><Type>3</Type><Format>%d</Format></Column><Column><Name>EID</Name><ColumnID>3</ColumnID><Flags>0</Flags><Type>3</Type><Format>%d</Format></Column><Column><Name>Parent EID</Name><ColumnID>4</ColumnID><Flags>0</Flags><Type>3</Type><Format>%d</Format></Column><Column><Name>Children</Name><ColumnID>11</ColumnID><Flags>0</Flags><Type>6</Type><Format>%d</Format></Column><Column><Name>Parent</Name><ColumnID>10</ColumnID><Flags>0</Flags><Type>2</Type><Format>%d</Format></Column><Column><Name>Flags</Name><ColumnID>5</ColumnID><Flags>0</Flags><Type>2</Type><Format>0x%08X</Format></Column><Column><Name>Event</Name><ColumnID>6</ColumnID><Flags>0</Flags><Type>4</Type><Format>%s</Format></Column><Column><Name>StartTime</Name><ColumnID>7</ColumnID><Flags>0</Flags><Type>5</Type><Format>%I64i</Format></Column><Column><Name>Path</Name><ColumnID>13</ColumnID><Flags>0</Flags><Type>1</Type><Format>%s</Format></Column><Column><Name>Path2</Name><ColumnID>14</ColumnID><Flags>0</Flags><Type>1</Type><Format>%s</Format></Column><Column><Name>Version</Name><ColumnID>15</ColumnID><Flags>0</Flags><Type>1</Type><Format>%s</Format></Column><Column><Name>TimeLastModified</Name><ColumnID>16</ColumnID><Flags>0</Flags><Type>1</Type><Format>%s</Format></Column><Column><Name>ProcessID</Name><ColumnID>23</ColumnID><Flags>0</Flags><Type>3</Type><Format>%d</Format></Column><Column><Name>SessionStartTimeStamp</Name><ColumnID>24</ColumnID><Flags>0</Flags><Type>5</Type><Format>%I64i</Format></Column><Column><Name>Frame</Name><ColumnID>9</ColumnID><Flags>0</Flags><Type>3</Type><Format>%d</Format></Column><Column><Name>Duration</Name><ColumnID>8</ColumnID><Flags>0</Flags><Type>5</Type><Format>%I64i</Format></Column><Column><Name>FPS</Name><ColumnID>12</ColumnID><Flags>0</Flags><Type>0</Type><Format>%0.01f</Format></Column><Column><Name>ThisEventPos</Name><ColumnID>21</ColumnID><Flags>0</Flags><Type>5</Type><Format>%I64i</Format></Column><Column><Name>NextSiblingPos</Name><ColumnID>22</ColumnID><Flags>0</Flags><Type>5</Type><Format>%I64i</Format></Column><Column><Name>User Event Name</Name><ColumnID>17</ColumnID><Flags>0</Flags><Type>1</Type><Format>%s</Format></Column><Column><Name>PackedCallPackage</Name><ColumnID>19</ColumnID><Flags>0</Flags><Type>7</Type><Format></Format></Column><Column><Name>Object Pointer</Name><ColumnID>20</ColumnID><Flags>0</Flags><Type>2</Type><Format>0x%08X</Format></Column></Columns><EventDescs><EventDesc><Name>Session Start</Name><EventType>1</EventType><EDID>1</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,1</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>CalcOnLoad,Const,-1</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>8</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,0,Start Session</String></EventDescColumn><EventDescColumn><ColumnID>13</ColumnID><String>(expfilepath)</String></EventDescColumn><EventDescColumn><ColumnID>14</ColumnID><String>(runfilepath)</String></EventDescColumn><EventDescColumn><ColumnID>24</ColumnID><String>(sessionstarttimestamp)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>Session End</Name><EventType>2</EventType><EDID>2</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,2</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>CalcOnLoad,Const,-1</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>8</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,0,End Session</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>Process Start</Name><EventType>3</EventType><EDID>3</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,3</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>CalcOnLoad,Const,-1</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>8</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,0,Start Process</String></EventDescColumn><EventDescColumn><ColumnID>13</ColumnID><String>(processpath)</String></EventDescColumn><EventDescColumn><ColumnID>15</ColumnID><String>(processversion)</String></EventDescColumn><EventDescColumn><ColumnID>16</ColumnID><String>(processtimelastmodified)</String></EventDescColumn><EventDescColumn><ColumnID>23</ColumnID><String>(processid)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>Process End</Name><EventType>4</EventType><EDID>4</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,4</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>CalcOnLoad,Const,-1</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>8</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,0,End Process</String></EventDescColumn><EventDescColumn><ColumnID>13</ColumnID><String>(processpath)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>Frame Begin</Name><EventType>5</EventType><EDID>5</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,5</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>(parenteid)</String></EventDescColumn><EventDescColumn><ColumnID>11</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>(rowflags)</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>9</ColumnID><String>(frame)</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,1,Frame %d,3,MemberOf,ThisRow,Frame</String></EventDescColumn><EventDescColumn><ColumnID>8</ColumnID><String>Async,(duration)</String></EventDescColumn><EventDescColumn><ColumnID>12</ColumnID><String>CalcOnLoad,Divide,Const,1000000000.0,MemberOf,ThisRow,Duration</String></EventDescColumn><EventDescColumn><ColumnID>21</ColumnID><String>(frameeventfilepos)</String></EventDescColumn><EventDescColumn><ColumnID>22</ColumnID><String>(lastframeeventfilepos)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>User Event Begin</Name><EventType>7</EventType><EDID>6</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,7</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>(parenteid)</String></EventDescColumn><EventDescColumn><ColumnID>10</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>11</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>17</ColumnID><String>(usereventname)</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,1,User Event: %s,1,MemberOf,ThisRow,User Event Name</String></EventDescColumn><EventDescColumn><ColumnID>8</ColumnID><String>Async,(duration)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>User Marker</Name><EventType>9</EventType><EDID>7</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,9</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>(parenteid)</String></EventDescColumn><EventDescColumn><ColumnID>10</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>11</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>17</ColumnID><String>(usereventname)</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,1,User Marker: %s,1,MemberOf,ThisRow,User Event Name</String></EventDescColumn><EventDescColumn><ColumnID>8</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>D3D Call</Name><EventType>10</EventType><EDID>8</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,10</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>(parenteid)</String></EventDescColumn><EventDescColumn><ColumnID>11</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>10</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,CallPlusParams,MemberOf,ThisRow,PackedCallPackage</String></EventDescColumn><EventDescColumn><ColumnID>19</ColumnID><String>Async,(packedcallpkg)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>Object Creation</Name><EventType>11</EventType><EDID>9</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,11</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>(parenteid)</String></EventDescColumn><EventDescColumn><ColumnID>11</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>10</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,0,Object Creation</String></EventDescColumn><EventDescColumn><ColumnID>20</ColumnID><String>(objpointer)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>Object Population</Name><EventType>12</EventType><EDID>10</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,12</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>(parenteid)</String></EventDescColumn><EventDescColumn><ColumnID>11</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>10</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,FormatText,0,Object Population</String></EventDescColumn><EventDescColumn><ColumnID>20</ColumnID><String>(objpointer)</String></EventDescColumn></EventDescColumns></EventDesc><EventDesc><Name>D3D Call (Sync)</Name><EventType>13</EventType><EDID>11</EDID><EventDescColumns><EventDescColumn><ColumnID>1</ColumnID><String>(edid)</String></EventDescColumn><EventDescColumn><ColumnID>2</ColumnID><String>CalcOnLoad,Const,13</String></EventDescColumn><EventDescColumn><ColumnID>3</ColumnID><String>(eid)</String></EventDescColumn><EventDescColumn><ColumnID>4</ColumnID><String>(parenteid)</String></EventDescColumn><EventDescColumn><ColumnID>11</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>10</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>5</ColumnID><String>CalcOnLoad,Const,0</String></EventDescColumn><EventDescColumn><ColumnID>7</ColumnID><String>(time)</String></EventDescColumn><EventDescColumn><ColumnID>6</ColumnID><String>CalcOnLoad,CallPlusParams,MemberOf,ThisRow,PackedCallPackage</String></EventDescColumn><EventDescColumn><ColumnID>19</ColumnID><String>(packedcallpkg)</String></EventDescColumn></EventDescColumns></EventDesc></EventDescs><Counters/><Triggers><Trigger><Type>1</Type><Recurrence>0</Recurrence><Actions><Action><Type>1</Type><Int1>1</Int1><Str1>import_test</Str1></Action><Action><Type>5</Type><Int1>1</Int1></Action></Actions></Trigger><Trigger><Type>4</Type><Str1>BeginCommandStreamCapture</Str1><Recurrence>1</Recurrence><Actions><Action><Type>3</Type><Int1>1</Int1><Int2>1</Int2></Action></Actions></Trigger><Trigger><Type>4</Type><Str1>EndCommandStreamCapture</Str1><Recurrence>1</Recurrence><Actions><Action><Type>3</Type><Int1>0</Int1><Int2>0</Int2></Action></Actions></Trigger><Trigger><Type>4</Type><Str1>CaptureScreenContents</Str1><Recurrence>1</Recurrence><Actions><Action><Type>4</Type><Int1>19</Int1><Str1>frame_capture</Str1><Str2>.png</Str2></Action></Actions></Trigger></Triggers></PIXExperiment>
diff --git a/o3d/tests/tests.gyp b/o3d/tests/tests.gyp
deleted file mode 100644
index 48f4b46..0000000
--- a/o3d/tests/tests.gyp
+++ /dev/null
@@ -1,251 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- },
- 'includes': [
- '../build/common.gypi',
- ],
- 'target_defaults': {
- 'include_dirs': [
- '..',
- '../..',
- ],
- # TODO(rlp): remove this after fixing signed / unsigned issues in
- # command buffer code and tests.
- 'target_conditions': [
- ['OS == "mac"',
- {
- 'xcode_settings': {
- 'GCC_TREAT_WARNINGS_AS_ERRORS': 'NO'
- },
- },
- ],
- ],
- },
- 'targets': [
- {
- 'target_name': 'unit_tests',
- 'type': 'executable',
- 'dependencies': [
- '../../<(antlrdir)/antlr.gyp:antlr3c',
- '../../<(fcolladadir)/fcollada.gyp:fcollada',
- '../../<(jpegdir)/libjpeg.gyp:libjpeg',
- '../../<(pngdir)/libpng.gyp:libpng',
- '../../<(zlibdir)/zlib.gyp:zlib',
- '../../base/base.gyp:base',
- '../../skia/skia.gyp:skia',
- '../../testing/gtest.gyp:gtest',
- '../../testing/gmock.gyp:gmock',
- '../../native_client/src/shared/imc/imc.gyp:google_nacl_imc',
- '../compiler/technique/technique.gyp:o3dTechnique',
- '../compiler/technique/technique.gyp:o3dTechniqueTest',
- '../core/core.gyp:o3dCore',
- '../core/core.gyp:o3dCorePlatform',
- '../core/core.gyp:o3dCoreTest',
- '../import/import.gyp:o3dImport',
- '../import/archive.gyp:o3dArchiveTest',
- '../import/import.gyp:o3dImportTest',
- '../serializer/serializer.gyp:o3dSerializerTest',
- '../utils/utils.gyp:o3dUtils',
- '../utils/utils.gyp:o3dUtilsTest',
- ],
- 'sources': [
- 'common/cross/test_utils.cc',
- 'common/cross/main.cc',
- ],
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)/bitmap_test',
- 'files': [
- "bitmap_test/5kx5k.dds",
- "bitmap_test/5kx5k.jpg",
- "bitmap_test/5kx5k.png",
- "bitmap_test/5kx5k.tga",
- "bitmap_test/dds-dxt1-256x256-alpha.dds",
- "bitmap_test/dds-dxt1-256x256-mipmap.dds",
- "bitmap_test/dds-dxt1-256x256.dds",
- "bitmap_test/dds-dxt3-256x256-alpha.dds",
- "bitmap_test/dds-dxt3-256x256-mipmap.dds",
- "bitmap_test/dds-dxt5-256x256-alpha.dds",
- "bitmap_test/dds-dxt5-256x256-mipmap.dds",
- "bitmap_test/gif-256x256-interlaced.gif",
- "bitmap_test/gif-256x256.gif",
- "bitmap_test/jpeg-256x256.jpg",
- "bitmap_test/png-20x14-4bit-palette.png",
- "bitmap_test/png-256x256-24bit-interlaced.png",
- "bitmap_test/png-256x256-24bit.png",
- "bitmap_test/png-256x256-32bit.png",
- "bitmap_test/png-256x256-8bit-palette-alpha.png",
- "bitmap_test/png-256x256-8bit-palette.png",
- "bitmap_test/png-2x2-24bit-drawimage-src.png",
- "bitmap_test/png-4x4-24bit-drawimage-argb8-src.png",
- "bitmap_test/png-4x4-24bit-drawimage-src.png",
- "bitmap_test/png-8x4-24bit-drawimage-argb8-dest.png",
- "bitmap_test/png-8x4-24bit-drawimage-dest.png",
- "bitmap_test/png-8x8-24bit-drawimage-src.png",
- "bitmap_test/test_source.psd",
- "bitmap_test/tga-256x256-24bit.tga",
- "bitmap_test/tga-256x256-32bit.tga",
- ],
- },
- ],
- 'conditions' : [
- ['renderer == "gl"',
- {
- 'dependencies': [
- '../build/libs.gyp:cg_libs',
- '../build/libs.gyp:gl_libs',
- ],
- },
- ],
- ['renderer == "gles2"',
- {
- 'dependencies': [
- '../build/libs.gyp:gles2_libs',
- ],
- },
- ],
- ['OS == "mac"',
- {
- 'dependencies': [
- '../statsreport/statsreport.gyp:o3dStatsReportTest',
- ],
- 'sources': [
- 'common/mac/testing_common.mm',
- ],
- 'postbuilds': [
- {
- 'variables': {
- # Define install_name in a variable ending in _path
- # so that gyp understands it's a path and performs proper
- # relativization during dict merging.
- 'install_name_path': 'mac/unit_tests_install_name.sh',
- },
- 'postbuild_name': 'Fix Framework Paths',
- 'action': ['<(install_name_path)'],
- },
- ],
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)',
- 'files': [
- '../../<(pdiffdir)/bin/mac/perceptualdiff',
- ],
- },
- ],
- 'include_dirs': [
- '../../third_party/glew/files/include',
- ],
- 'link_settings': {
- 'libraries': [
- '$(SDKROOT)/System/Library/Frameworks/AGL.framework',
- '$(SDKROOT)/System/Library/Frameworks/Foundation.framework',
- '$(SDKROOT)/System/Library/Frameworks/GLUT.framework',
- '$(SDKROOT)/System/Library/Frameworks/OpenGL.framework',
- '../../third_party/cg/files/mac/Cg.framework',
- '../../third_party/glew/files/lib/libMacStaticGLEW.a',
- ],
- },
- },
- ],
- ['OS == "win"',
- {
- 'dependencies': [
- '../statsreport/statsreport.gyp:o3dStatsReportTest',
- ],
- 'sources': [
- 'common/win/testing_common.cc',
- 'common/win/testing_common.h',
- ],
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)',
- 'files': [
- '../../<(pdiffdir)/bin/win/perceptualdiff.exe',
- '../../<(pdiffdir)/bin/win/FreeImage.dll',
- ],
- },
- ],
- 'msvs_settings': {
- 'VCLinkerTool': {
- 'AdditionalDependencies': [
- 'rpcrt4.lib',
- '../../<(cgdir)/lib/cg.lib',
- '../../<(cgdir)/lib/cgGL.lib',
- ],
- # Set /SUBSYSTEM:WINDOWS for unit_tests.exe, since
- # it is a windows app.
- 'SubSystem': '2',
- # Don't optimize away unreferenced symbols when
- # linking. If we didn't do this, then none of the
- # tests would auto-register.
- 'OptimizeReferences': '1',
- },
- },
- # We switch it to console post-build so that we have a
- # windows app that can output to the console and still
- # open windows.
- 'msvs_postbuild':
- 'editbin /SUBSYSTEM:CONSOLE $(OutDir)/$(TargetFileName)',
- },
- ],
- ['OS == "win" and renderer == "d3d9"',
- {
- 'sources': [
- 'common/win/dxcapture.cc',
- ],
- 'msvs_system_include_dirs': [
- '"$(DXSDK_DIR)/Include"',
- ],
- 'link_settings': {
- 'libraries': [
- '"$(DXSDK_DIR)/Lib/x86/d3dx9.lib"',
- 'd3d9.lib',
- '"$(DXSDK_DIR)/Lib/x86/DxErr.lib"',
- ],
- },
- },
- ],
- ['OS == "win" and renderer == "gl"',
- {
- 'dependencies': [
- '../build/libs.gyp:gl_libs',
- ],
- },
- ],
- ['OS == "win" and renderer == "gles2"',
- {
- 'dependencies': [
- '../build/libs.gyp:gles2_libs',
- ],
- },
- ],
- ['OS == "linux"',
- {
- 'sources': [
- 'common/linux/testing_common.cc',
- ],
- 'copies': [
- {
- 'destination': '<(PRODUCT_DIR)',
- 'files': [
- '../../<(pdiffdir)/bin/linux/perceptualdiff',
- ],
- },
- ],
- },
- ],
- ],
- },
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2:
diff --git a/o3d/utils/cross/base64.cc b/o3d/utils/cross/base64.cc
deleted file mode 100644
index 0d36e1e..0000000
--- a/o3d/utils/cross/base64.cc
+++ /dev/null
@@ -1,218 +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 declaration of functions for dealing with base64
-// encoding and decoding
-
-#include "utils/cross/base64.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-namespace base64 {
-
-size_t GetEncodeLength(size_t length) {
- return (length + 2) / 3 * 4;
-}
-
-void Encode(const void* src_ptr, size_t length, void* dst_ptr) {
- const int kEncodePad = 64;
-
- static const char kEncode[] =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- "abcdefghijklmnopqrstuvwxyz"
- "0123456789+/=";
-
- const uint8* src = reinterpret_cast<const uint8*>(src_ptr);
- uint8* dst = reinterpret_cast<uint8*>(dst_ptr);
- if (dst) {
- size_t remainder = length % 3;
- const uint8* end = &src[length - remainder];
- while (src < end) {
- unsigned a = *src++;
- unsigned b = *src++;
- unsigned c = *src++;
- unsigned d = c & 0x3F;
- c = (c >> 6 | b << 2) & 0x3F;
- b = (b >> 4 | a << 4) & 0x3F;
- a = a >> 2;
- *dst++ = kEncode[a];
- *dst++ = kEncode[b];
- *dst++ = kEncode[c];
- *dst++ = kEncode[d];
- }
- if (remainder > 0) {
- unsigned k1 = 0;
- unsigned k2 = kEncodePad;
- unsigned a = *src++;
- if (remainder == 2) {
- int b = *src++;
- k1 = b >> 4;
- k2 = (b << 2) & 0x3F;
- }
- *dst++ = kEncode[a >> 2];
- *dst++ = kEncode[(k1 | a << 4) & 0x3F];
- *dst++ = kEncode[k2];
- *dst++ = kEncode[kEncodePad];
- }
- }
-}
-
-// This function actually does the decoding.
-// Parameters:
-// src_ptr: pointer to the source data
-// input_length: The length in bytes of the source data.
-// dst_ptr: pointer to where the output data should be stored.
-// dst_buffer_length: the size in bytes of the dst_ptr buffer. This
-// is used to check for overflow. Not used if write_destination is
-// false.
-// output_length: The output length (in bytes) will be stored here if
-// it is not null.
-// write_destination: If true, actually write to the output. Otherwise,
-// the length of the output will be determined only.
-DecodeStatus PerformDecode(const void* src_ptr,
- size_t input_length,
- void* dst_ptr,
- size_t dst_buffer_length,
- size_t* output_length,
- bool write_destination) {
- const int kDecodePad = -2;
-
- static const int8 kDecodeData[] = {
- 62, -1, -1, -1, 63,
- 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, kDecodePad, -1, -1,
- -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
- 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
- -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
- 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
- };
-
- uint8* dst = reinterpret_cast<uint8*>(dst_ptr);
- const uint8* dst_start = reinterpret_cast<const uint8*>(dst_ptr);
- const uint8* dst_end = dst_start + dst_buffer_length;
- const uint8* src = reinterpret_cast<const uint8*>(src_ptr);
- bool pad_two = false;
- bool pad_three = false;
- const uint8* end = src + input_length;
- while (src < end) {
- uint8 bytes[4];
- int byte = 0;
- do {
- uint8 src_byte = *src++;
- if (src_byte == 0)
- goto goHome;
- if (src_byte <= ' ')
- continue; // treat as white space
- if (src_byte < '+' || src_byte > 'z')
- return kBadCharError;
- int8 decoded = kDecodeData[src_byte - '+'];
- bytes[byte] = decoded;
- if (decoded < 0) {
- if (decoded == kDecodePad)
- goto handlePad;
- return kBadCharError;
- } else {
- byte++;
- }
- if (*src)
- continue;
- if (byte == 0)
- goto goHome;
- if (byte == 4)
- break;
- handlePad:
- if (byte < 2)
- return kPadError;
- pad_three = true;
- if (byte == 2)
- pad_two = true;
- break;
- } while (byte < 4);
- int two = 0, three = 0;
- if (write_destination) {
- int one = (bytes[0] << 2) & 0xFF;
- two = bytes[1];
- one |= two >> 4;
- two = (two << 4) & 0xFF;
- three = bytes[2];
- two |= three >> 2;
- three = (three << 6) & 0xFF;
- three |= bytes[3];
- O3D_ASSERT(one < 256 && two < 256 && three < 256);
- if (dst >= dst_end) {
- return kOutputOverflowError;
- }
- *dst = one;
- }
- dst++;
- if (pad_two)
- break;
- if (write_destination) {
- if (dst >= dst_end) {
- return kOutputOverflowError;
- }
- *dst = two;
- }
- dst++;
- if (pad_three)
- break;
- if (write_destination) {
- if (dst >= dst_end) {
- return kOutputOverflowError;
- }
- *dst = three;
- }
- dst++;
- }
- goHome:
- if (output_length) {
- *output_length = dst - dst_start;
- }
- return kSuccess;
-}
-
-// Returns the number of bytes of output data after decoding from base64.
-DecodeStatus GetDecodeLength(const void* src,
- size_t input_length,
- size_t* decode_length) {
- return PerformDecode(src, input_length, NULL, 0, decode_length, false);
-}
-
-// Decodes the src data from base64 and stores the result in dst.
-DecodeStatus Decode(const void* src,
- size_t input_length,
- void* dst,
- size_t dst_buffer_length) {
- return PerformDecode(src, input_length, dst, dst_buffer_length, NULL, true);
-}
-
-} // namespace base64
-} // namespace o3d
-
diff --git a/o3d/utils/cross/base64.h b/o3d/utils/cross/base64.h
deleted file mode 100644
index eae0817..0000000
--- a/o3d/utils/cross/base64.h
+++ /dev/null
@@ -1,92 +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 declaration of functions for dealing with base64
-// encoding and decoding
-
-#ifndef O3D_UTILS_CROSS_BASE64_H_
-#define O3D_UTILS_CROSS_BASE64_H_
-
-#include <stddef.h>
-
-namespace o3d {
-namespace base64 {
-
-// The possible error codes that can occur during a decoding.
-enum DecodeStatus {
- kSuccess,
- kPadError,
- kBadCharError,
- kOutputOverflowError
-};
-
-// Returns the number of bytes needed to encode length bytes in base64.
-size_t GetEncodeLength(size_t length);
-
-// Encodes the src into base64 into the dst. The dst must have enough
-// space to hold the result.
-// Parameters:
-// src: pointer to source data.
-// length: the length of the source data
-// dst: pointer to place to store result.
-void Encode(const void* src, size_t length, void* dst);
-
-// Used to obtain the number of bytes needed to decode the src data
-// from base64.
-// Parameters:
-// src: pointer to the source data.
-// input_length: the length of the source data
-// decode_length: the length in bytes of the decoded data will be
-// placed here.
-DecodeStatus GetDecodeLength(const void* src,
- size_t input_length,
- size_t* decode_length);
-
-// Decodes the src, which should be encoded in base64, into the dst.
-// dst must have enough space to hold the result. The number of bytes
-// necessary can be obtained by calling GetDecodeLength()
-// Parameters:
-// src: pointer to the source data
-// input_length: the length of the source data
-// dst: pointer to where the result should be stored.
-// dst_buffer_length: the size in bytes of the dst buffer. This is
-// used to check for buffer overflow.
-// Returns an error code (of type DecodeStatus)
-DecodeStatus Decode(const void* src,
- size_t input_length,
- void* dst,
- size_t dst_buffer_length);
-
-} // namespace base64
-} // namespace o3d
-
-#endif // O3D_UTILS_CROSS_BASE64_H_
-
diff --git a/o3d/utils/cross/base64_test.cc b/o3d/utils/cross/base64_test.cc
deleted file mode 100644
index d291f14..0000000
--- a/o3d/utils/cross/base64_test.cc
+++ /dev/null
@@ -1,170 +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 tests of base64 functions
-
-#include "tests/common/win/testing_common.h"
-#include "utils/cross/base64.h"
-
-namespace o3d {
-
-class Base64Test : public testing::Test {
-};
-
-TEST_F(Base64Test, GetEncodeLength) {
- EXPECT_EQ(0u, base64::GetEncodeLength(0));
- EXPECT_EQ(4u, base64::GetEncodeLength(1));
- EXPECT_EQ(4u, base64::GetEncodeLength(2));
- EXPECT_EQ(4u, base64::GetEncodeLength(3));
- EXPECT_EQ(8u, base64::GetEncodeLength(4));
-}
-
-TEST_F(Base64Test, Encode) {
- unsigned char buffer[100];
- memset(buffer, 0xFF, sizeof(buffer));
- base64::Encode("abc", 3, buffer);
- EXPECT_EQ(0, memcmp(buffer, "YWJj", 4));
- EXPECT_EQ(0xFF, buffer[4]);
- memset(buffer, 0xFF, sizeof(buffer));
- base64::Encode("ab\0c", 4, buffer);
- EXPECT_EQ(0, memcmp(buffer, "YWIAYw==", 8));
- EXPECT_EQ(0xFF, buffer[8]);
-}
-
-TEST_F(Base64Test, GetDecodeLength) {
- size_t length = 256u;
- base64::GetDecodeLength("", 0, &length);
- EXPECT_EQ(0u, length);
-
- length = 256u;
- base64::GetDecodeLength("YQ==", 4, &length);
- EXPECT_EQ(1u, length);
-
- length = 256u;
- base64::GetDecodeLength("YWI=", 4, &length);
- EXPECT_EQ(2u, length);
-
- length = 256u;
- base64::GetDecodeLength("YWJj", 4, &length);
- EXPECT_EQ(3u, length);
-
- length = 256u;
- base64::GetDecodeLength("YWJjZA==", 8, &length);
- EXPECT_EQ(4u, length);
-
- length = 256u;
- base64::GetDecodeLength("YWJjZGU=", 8, &length);
- EXPECT_EQ(5u, length);
-}
-
-TEST_F(Base64Test, GetDecodeLengthInputError) {
- base64::DecodeStatus status = base64::kSuccess;
- size_t length = 256u;
- status = base64::GetDecodeLength("Y@==", 4, &length);
- EXPECT_EQ(base64::kBadCharError, status);
-
- status = base64::GetDecodeLength("Y Q==", 4, &length);
- EXPECT_EQ(base64::kSuccess, status);
-
- status = base64::GetDecodeLength("Y", 1, &length);
- EXPECT_EQ(base64::kPadError, status);
-}
-
-TEST_F(Base64Test, Decode) {
- unsigned char buffer[10];
- memset(buffer, 0xFF, sizeof(buffer));
- unsigned char result_buffer[10];
- memset(result_buffer, 0xFF, sizeof(result_buffer));
- base64::DecodeStatus status = base64::kSuccess;
-
- status = base64::Decode("", 0, buffer, 10);
- EXPECT_EQ(base64::kSuccess, status);
- EXPECT_EQ(0, memcmp(buffer, result_buffer, 10));
-
- result_buffer[0] = 'a';
- status = base64::Decode("YQ==", 4, buffer, 10);
- EXPECT_EQ(base64::kSuccess, status);
- EXPECT_EQ(0, memcmp(buffer, result_buffer, 10));
-
- result_buffer[1] = 'b';
- status = base64::Decode("YWI=", 4, buffer, 10);
- EXPECT_EQ(base64::kSuccess, status);
- EXPECT_EQ(0, memcmp(buffer, result_buffer, 10));
-
- result_buffer[2] = 'c';
- status = base64::Decode("YWJj", 4, buffer, 10);
- EXPECT_EQ(base64::kSuccess, status);
- EXPECT_EQ(0, memcmp(buffer, result_buffer, 10));
-
- result_buffer[3] = 'd';
- status = base64::Decode("YWJjZA==", 8, buffer, 10);
- EXPECT_EQ(base64::kSuccess, status);
- EXPECT_EQ(0, memcmp(buffer, result_buffer, 10));
-
- result_buffer[4] = 'e';
- status = base64::Decode("YWJjZGU=", 8, buffer, 10);
- EXPECT_EQ(base64::kSuccess, status);
- EXPECT_EQ(0, memcmp(buffer, result_buffer, 10));
-}
-
-TEST_F(Base64Test, DecodeInputError) {
- unsigned char buffer[10];
- base64::DecodeStatus status = base64::kSuccess;
- status = base64::Decode("Y@==", 4, buffer, 10);
- EXPECT_EQ(base64::kBadCharError, status);
-
- status = base64::Decode("Y Q==", 4, buffer, 10);
- EXPECT_EQ(base64::kSuccess, status);
-
- status = base64::Decode("Y", 1, buffer, 10);
- EXPECT_EQ(base64::kPadError, status);
-}
-
-TEST_F(Base64Test, DecodeOverflowError) {
- unsigned char buffer[10];
- base64::DecodeStatus status = base64::kSuccess;
- status = base64::Decode("YWJjZA==", 8, buffer, 3);
- EXPECT_EQ(base64::kOutputOverflowError, status);
-
- status = base64::Decode("YWJjZA==", 8, buffer, 4);
- EXPECT_EQ(base64::kSuccess, status);
-
- status = base64::Decode("YQ==", 8, buffer, 0);
- EXPECT_EQ(base64::kOutputOverflowError, status);
-
- status = base64::Decode("YQ==", 8, buffer, 1);
- EXPECT_EQ(base64::kSuccess, status);
-}
-
-} // namespace o3d
-
-
diff --git a/o3d/utils/cross/dataurl.cc b/o3d/utils/cross/dataurl.cc
deleted file mode 100644
index 328d174..0000000
--- a/o3d/utils/cross/dataurl.cc
+++ /dev/null
@@ -1,113 +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 definition of functions for dealing with data urls.
-
-#include "utils/cross/dataurl.h"
-#include "core/cross/types.h"
-#include "utils/cross/base64.h"
-
-namespace o3d {
-namespace dataurl {
-
-const char* const kEmptyDataURL = "data:,";
-
-String ToDataURL(const String& mime_type, const void* data, size_t length) {
- String header(String("data:") + mime_type + ";base64,");
- String result(header.size() + base64::GetEncodeLength(length), ' ');
- result.replace(0, header.size(), header);
- base64::Encode(data, length, &result[header.size()]);
- return result;
-}
-
-// Decodes the data URL and stores a pointer to the data in dst_buffer
-bool FromDataURL(const String& data_url,
- scoped_array<uint8>* dst_buffer,
- size_t* output_length,
- String* error_string) {
- // First parse the data_url
- const String kDataHeader("data:");
- const String kBase64Header(";base64,");
- // The string has to be long enough.
- if (data_url.size() <= kDataHeader.size() + kBase64Header.size()) {
- *error_string = "Invalid formatting: The data URL is not long enough.";
- return false;
- }
- // it must start with "data:"
- if (data_url.compare(0, kDataHeader.size(), kDataHeader) != 0) {
- *error_string
- = "Invalid formatting: The data URL must start with 'data:'";
- return false;
- }
- // we only support base64 data URL's
- String::size_type data_index = data_url.find(kBase64Header);
- if (data_index == String::npos) {
- *error_string
- = "Invalid formatting: The data URL have ';base64,' in the header.";
- return false;
- }
- // The start of the data.
- data_index += kBase64Header.size();
- if (data_index >= data_url.size()) {
- *error_string
- = "Invalid formatting: There must be data in the body of the data URL.";
- return false;
- }
-
- // Get the length of the decoded data
- size_t input_length = data_url.size() - data_index;
- base64::DecodeStatus return_code = base64::GetDecodeLength(
- &data_url[data_index],
- input_length,
- output_length);
- if (return_code != base64::kSuccess) {
- if (return_code == base64::kPadError) {
- *error_string
- = "Invalid formatting: Padding error in the data URL data.";
- } else {
- *error_string
- = "Invalid formatting: Bad character error in the data URL data.";
- }
- return false;
- }
-
- dst_buffer->reset(new uint8[*output_length]);
- base64::Decode(&data_url[data_index],
- input_length,
- dst_buffer->get(),
- (*output_length));
-
- return true;
-}
-
-} // namespace dataurl
-} // namespace o3d
-
diff --git a/o3d/utils/cross/dataurl.h b/o3d/utils/cross/dataurl.h
deleted file mode 100644
index c403388..0000000
--- a/o3d/utils/cross/dataurl.h
+++ /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.
- */
-
-// This file contains the declaration of functions for dealing with data urls.
-
-#ifndef O3D_UTILS_CROSS_DATAURL_H_
-#define O3D_UTILS_CROSS_DATAURL_H_
-
-#include "core/cross/types.h"
-#include "base/scoped_ptr.h"
-
-namespace o3d {
-namespace dataurl {
-
-// An empty data URL. ("data:,")
-extern const char* const kEmptyDataURL;
-
-// Creates a data URL for the given data.
-String ToDataURL(const String& mime_type, const void* data, size_t length);
-
-// Decodes the data from a data URL and stores a pointer to the data in
-// dst_buffer. If an error occurs in decoding, it returns false and
-// error_string will contain an error message. Otherwise, returns true.
-// Parameters:
-// data_url: The data URL from which to extract the data.
-// dst_buffer: A pointer to the output data will be stored in this
-// scoped_array.
-// output_length: The length of the output data will be stored at this
-// address.
-// error_string: This will contain the error message, if an error occurs.
-// Returns:
-// False if an error occurs in decoding, true otherwise.
-bool FromDataURL(const String& data_url,
- scoped_array<uint8>* dst_buffer,
- size_t* output_length,
- String* error_string);
-
-} // namespace dataurl
-} // namespace o3d
-
-#endif // O3D_UTILS_CROSS_DATAURL_H_
-
diff --git a/o3d/utils/cross/dataurl_test.cc b/o3d/utils/cross/dataurl_test.cc
deleted file mode 100644
index f189011..0000000
--- a/o3d/utils/cross/dataurl_test.cc
+++ /dev/null
@@ -1,125 +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 tests of dataurl functions
-
-#include "tests/common/win/testing_common.h"
-#include "utils/cross/dataurl.h"
-
-namespace o3d {
-
-class DataURLTest : public testing::Test {
-};
-
-TEST_F(DataURLTest, kEmptyDataURL) {
- EXPECT_STREQ("data:,", dataurl::kEmptyDataURL);
-}
-
-TEST_F(DataURLTest, ToDataURL) {
- EXPECT_STREQ("data:a/b;base64,YWJj",
- dataurl::ToDataURL("a/b", "abc", 3).c_str());
- EXPECT_STREQ("data:de/ej;base64,YWIAYw==",
- dataurl::ToDataURL("de/ej", "ab\0c", 4).c_str());
-}
-
-TEST_F(DataURLTest, FromDataURL) {
- String data_url("data:a/b;base64,YWJj");
- scoped_array<uint8> output;
- size_t output_length;
- String error_string;
-
- EXPECT_TRUE(dataurl::FromDataURL(data_url,
- &output,
- &output_length,
- &error_string));
- EXPECT_EQ(3u, output_length);
- EXPECT_EQ(0, memcmp("abc", output.get(), 3));
-}
-
-TEST_F(DataURLTest, FromDataURLFormatErrors) {
- scoped_array<uint8> output;
- size_t output_length;
- String error_string("");
- // Not long enough
- EXPECT_FALSE(dataurl::FromDataURL("",
- &output,
- &output_length,
- &error_string));
- EXPECT_LT(0u, error_string.size());
- // Does not start with "data:"
- error_string = "";
- EXPECT_FALSE(dataurl::FromDataURL("aaaaaaaaaaaaaaaa",
- &output,
- &output_length,
- &error_string));
- EXPECT_LT(0u, error_string.size());
- // Must contain base64
- error_string = "";
- EXPECT_FALSE(dataurl::FromDataURL("data:aaaaaaaaaaa",
- &output,
- &output_length,
- &error_string));
- EXPECT_LT(0u, error_string.size());
- // Must contain data.
- error_string = "";
- EXPECT_FALSE(dataurl::FromDataURL("data:aa;base64,",
- &output,
- &output_length,
- &error_string));
- EXPECT_LT(0u, error_string.size());
-
- // Bad character in data.
- error_string = "";
- EXPECT_FALSE(dataurl::FromDataURL("data:;base64,@",
- &output,
- &output_length,
- &error_string));
- EXPECT_LT(0u, error_string.size());
- // Padding error in data.
- error_string = "";
- EXPECT_FALSE(dataurl::FromDataURL("data:;base64,Y",
- &output,
- &output_length,
- &error_string));
- EXPECT_LT(0u, error_string.size());
- // Correct.
- error_string = "";
- EXPECT_TRUE(dataurl::FromDataURL("data:;base64,YWJj",
- &output,
- &output_length,
- &error_string));
- EXPECT_EQ(0u, error_string.size());
-}
-
-} // namespace o3d
-
-
diff --git a/o3d/utils/cross/file_path_utils.cc b/o3d/utils/cross/file_path_utils.cc
deleted file mode 100644
index 06b7015..0000000
--- a/o3d/utils/cross/file_path_utils.cc
+++ /dev/null
@@ -1,222 +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 definitions for some convenience functions
-// used to make FilePaths more useful.
-
-#include "utils/cross/file_path_utils.h"
-#include "base/file_util.h"
-#include "base/file_path.h"
-#include "base/utf_string_conversions.h"
-
-namespace o3d {
-std::wstring FilePathToWide(const FilePath& input) {
-#if defined(OS_WIN)
- return input.value();
-#else
- return UTF8ToWide(input.value());
-#endif
-}
-
-FilePath WideToFilePath(const std::wstring& input) {
-#if defined(OS_WIN)
- return FilePath(input);
-#else
- return FilePath(WideToUTF8(input));
-#endif
-}
-
-String FilePathToUTF8(const FilePath& input) {
-#if defined(OS_WIN)
- return WideToUTF8(input.value());
-#else
- return input.value();
-#endif
-}
-
-FilePath UTF8ToFilePath(const String& input) {
-#if defined(OS_WIN)
- return FilePath(UTF8ToWide(input));
-#else
- return FilePath(input);
-#endif
-}
-
-FilePath::StringType UTF8ToFilePathStringType(const String& input) {
-#if defined(OS_WIN)
- return UTF8ToWide(input);
-#else
- return input;
-#endif
-}
-
-bool AbsolutePath(FilePath* absolute_path) {
-#if defined(OS_WIN)
- return file_util::AbsolutePath(absolute_path);
-#else
- // On the Posix implementation of file_util::AbsolutePath,
- // realpath() is used, which only works if the path actually exists.
- // So, we try using AbsolutePath, and if it doesn't work, we fake it
- // by just prepending the current working direcory if it's not
- // already absolute.
- if (absolute_path->IsAbsolute()) {
- return true;
- } else {
- FilePath new_absolute_path = FilePath(*absolute_path);
- if (file_util::AbsolutePath(&new_absolute_path)) {
- *absolute_path = new_absolute_path;
- return true;
- } else {
- // OK, so we failed to make an absolute path above, and we know
- // it's not an absolute path to begin with, so we just prepend
- // the current working directory.
- FilePath cwd_path;
- if (!file_util::GetCurrentDirectory(&cwd_path)) {
- return false;
- }
- *absolute_path = cwd_path.Append(*absolute_path);
- return true;
- }
- }
-#endif
-}
-
-bool GetRelativePathIfPossible(const FilePath& base_dir,
- const FilePath& candidate,
- FilePath *result) {
- FilePath parent = FilePath(base_dir.StripTrailingSeparators());
- FilePath child = FilePath(candidate.StripTrailingSeparators());
-
- // If we can't convert the child to an absolute path for some
- // reason, then we just do nothing and return the candidate.
- if (!child.IsAbsolute() && !AbsolutePath(&child)) {
- *result = candidate;
- return false;
- }
-
- // If we can't convert the parent to an absolute path for some
- // reason, then we just do nothing and return the absolute path to
- // the child.
- if (!parent.IsAbsolute() && !AbsolutePath(&parent)) {
- *result = child;
- return false;
- }
-
- FilePath::StringType child_str = child.value();
- FilePath::StringType parent_str = parent.value();
-
- // If the child is too short, it can't be a child of parent, and if
- // it doesn't have a separator in the right place, then it also
- // can't be a child, so we return the absolute path to the child.
- // file_util::AbsolutePath() normalizes '/' to '\' on Windows, so we
- // only need to check kSeparators[0].
- if (child_str.length() <= parent_str.length() ||
- child_str[parent_str.length()] != FilePath::kSeparators[0]) {
- *result = child;
- return false;
- }
-
- if (
-#if defined(OS_WIN)
- // file_util::AbsolutePath() does not flatten case on Windows,
- // so we must do a case-insensitive compare.
- StartsWith(child_str, parent_str, false)
-#else
- StartsWithASCII(child_str, parent_str, true)
-#endif
- ) {
- // Add one to skip over the dir separator.
- child_str = child_str.substr(parent_str.size() + 1);
-
- // Now we know we can return the relative path.
- *result = FilePath(child_str);
- return true;
- } else {
- *result = FilePath(child_str);
- return false;
- }
-}
-
-namespace { // anonymous namespace.
-
-// Tries to find a file path_to_find in path_to_search. Will start with
-// base name and progressively try each higher path. Example:
-//
-// FindFile('this/that', 'foo/bar/baf.txt');
-//
-// Looks for:
-// this/that/foo/bar/baf.txt
-// this/that/bar/baf.txt
-// this/that/baf.txt
-bool FindFileHelper(const FilePath& path_to_search,
- const FilePath& path_to_find,
- FilePath* found_path) {
- std::vector<FilePath::StringType> parts;
- path_to_find.GetComponents(&parts);
-
- for (size_t ii = 0; ii < parts.size(); ++ii) {
- // build a path from parts.
- FilePath path(path_to_search);
- for (size_t jj = ii; jj < parts.size(); ++jj) {
- path = path.Append(parts[jj]);
- }
- if (file_util::PathExists(path)) {
- *found_path = path;
- return true;
- }
- }
-
- return false;
-}
-
-} // anonymous namespace
-
-bool FindFile(const std::vector<FilePath>& paths_to_search,
- const FilePath& path_to_find,
- FilePath* found_path) {
- if (file_util::PathExists(path_to_find)) {
- *found_path = path_to_find;
- return true;
- }
-
- for (size_t ii = 0; ii < paths_to_search.size(); ++ii) {
- FilePath absolute_path(paths_to_search[ii]);
- o3d::AbsolutePath(&absolute_path);
-
- if (FindFileHelper(absolute_path, path_to_find, found_path)) {
- return true;
- }
- }
- return false;
-}
-
-} // end namespace o3d
diff --git a/o3d/utils/cross/file_path_utils.h b/o3d/utils/cross/file_path_utils.h
deleted file mode 100644
index 463b47de..0000000
--- a/o3d/utils/cross/file_path_utils.h
+++ /dev/null
@@ -1,90 +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 declaration for some convenience functions
-// used to make FilePaths more useful.
-
-#ifndef O3D_UTILS_CROSS_FILE_PATH_UTILS_H_
-#define O3D_UTILS_CROSS_FILE_PATH_UTILS_H_
-
-#include <string>
-#include <vector>
-#include "base/file_path.h"
-#include "core/cross/types.h"
-
-namespace o3d {
-// TODO: Go through the process to add these to FilePath
-// itself in the Chromium depot.
-
-std::wstring FilePathToWide(const FilePath& input);
-FilePath WideToFilePath(const std::wstring& input);
-String FilePathToUTF8(const FilePath& input);
-FilePath UTF8ToFilePath(const String& input);
-FilePath::StringType UTF8ToFilePathStringType(const String& input);
-
-// On Windows, this is just the same as file_util::AbsolutePath.
-// On the Posix implementation of file_util::AbsolutePath,
-// realpath() is used, which only works if the path actually exists.
-// So, we try using AbsolutePath, and if it doesn't work, we fake it
-// by just prepending the cwd if it's not already an absolute path.
-bool AbsolutePath(FilePath* abs_path);
-
-// If the candidate is a child (a file or directory in a subdir of the
-// base directory or the base directory itself), then we figure out
-// the relative path to it. If not, then we just return the absolute
-// path to the candidate. Does not return any paths that would
-// require use of ".." to form a relative path. Returns true if the
-// path returned in "result" is a relative path.
-bool GetRelativePathIfPossible(const FilePath& base_dir,
- const FilePath& candidate,
- FilePath *result);
-
-// Tries to find a file path_to_find in paths_to_search. Will start with
-// base name and progressively try each higher path. Example:
-//
-// FindFile(['this/that', 'there'], 'foo/bar/baf.txt');
-//
-// Looks for:
-// foo/bar/baf.txt
-// this/that/foo/bar/baf.txt
-// this/that/bar/baf.txt
-// this/that/baf.txt
-// there/foo/bar/baf.txt
-// there/bar/baf.txt
-// there/baf.txt
-bool FindFile(const std::vector<FilePath>& paths_to_search,
- const FilePath& path_to_find,
- FilePath* found_path);
-
-} // namespace o3d
-
-#endif // O3D_UTILS_CROSS_FILE_PATH_UTILS_H_
diff --git a/o3d/utils/cross/file_path_utils_test.cc b/o3d/utils/cross/file_path_utils_test.cc
deleted file mode 100644
index ac4d777..0000000
--- a/o3d/utils/cross/file_path_utils_test.cc
+++ /dev/null
@@ -1,237 +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 tests of the file path utils.
-#include <stdio.h>
-
-#include "base/file_path.h"
-#include "base/file_util.h"
-#include "tests/common/win/testing_common.h"
-#include "utils/cross/file_path_utils.h"
-
-namespace o3d {
-
-namespace { // anonymous namespace
-
-bool FilePathsEqual(const FilePath& path_1, const FilePath path_2) {
- const FilePath::StringType& p1(path_1.value());
- const FilePath::StringType& p2(path_2.value());
- if (p1.size() == p2.size()) {
- for (size_t ii = 0; ii < p1.size(); ++ii) {
- if (p1[ii] != p2[ii]) {
- if (!FilePath::IsSeparator(p1[ii]) || !FilePath::IsSeparator(p2[ii])) {
- return false;
- }
- }
- }
- return true;
- }
- return false;
-}
-
-} // anonymous namespace
-
-class FilePathUtilsTest : public testing::Test {
-};
-
-TEST_F(FilePathUtilsTest, ConvertFilePathToUTF8) {
- std::string test_path("/this/is/a/path");
- FilePath source_path(FILE_PATH_LITERAL("/this/is/a/path"));
- EXPECT_EQ(test_path, FilePathToUTF8(source_path));
-}
-
-TEST_F(FilePathUtilsTest, ConvertFilePathToWide) {
- std::wstring test_path(L"/this/is/a/path");
- FilePath source_path(FILE_PATH_LITERAL("/this/is/a/path"));
- EXPECT_EQ(test_path, FilePathToWide(source_path));
-}
-
-TEST_F(FilePathUtilsTest, ConvertWideToFilePath) {
- std::wstring test_path(L"/this/is/a/path");
- FilePath dest_path = WideToFilePath(test_path);
- EXPECT_STREQ(FILE_PATH_LITERAL("/this/is/a/path"), dest_path.value().c_str());
-}
-
-TEST_F(FilePathUtilsTest, ConvertUTF8ToFilePath) {
- std::string test_path("/this/is/a/path");
- FilePath dest_path = UTF8ToFilePath(test_path);
- EXPECT_STREQ(FILE_PATH_LITERAL("/this/is/a/path"), dest_path.value().c_str());
-}
-
-TEST_F(FilePathUtilsTest, AbsolutePathBasic) {
- FilePath cwd;
- file_util::GetCurrentDirectory(&cwd);
-#if defined(OS_WIN)
- FilePath test_path(FILE_PATH_LITERAL("this\\is\\a\\path"));
-#else
- FilePath test_path(FILE_PATH_LITERAL("this/is/a/path"));
-#endif
- FilePath abs_path = test_path;
- AbsolutePath(&abs_path);
- FilePath expected_result = cwd;
- expected_result = expected_result.Append(test_path);
- EXPECT_STREQ(expected_result.value().c_str(), abs_path.value().c_str());
-}
-
-TEST_F(FilePathUtilsTest, AbsolutePathAlreadyAbsolute) {
-#if defined(OS_WIN)
- FilePath test_path(FILE_PATH_LITERAL("c:\\this\\is\\a\\path"));
-#else
- FilePath test_path(FILE_PATH_LITERAL("/this/is/a/path"));
-#endif
- FilePath abs_path = test_path;
- AbsolutePath(&abs_path);
- EXPECT_STREQ(test_path.value().c_str(), abs_path.value().c_str());
-}
-
-#if defined(OS_WIN)
-TEST_F(FilePathUtilsTest, AbsolutePathAlreadyAbsoluteWindowsUnc) {
- FilePath test_path(FILE_PATH_LITERAL("\\\\this\\is\\a\\path"));
- FilePath abs_path = test_path;
- bool result = AbsolutePath(&abs_path);
- EXPECT_STREQ(test_path.value().c_str(), abs_path.value().c_str());
-}
-#endif
-
-TEST_F(FilePathUtilsTest, RelativePathsBasic) {
-#if defined(OS_WIN)
- FilePath expected_result(FILE_PATH_LITERAL("under\\parent"));
-#else
- FilePath expected_result(FILE_PATH_LITERAL("under/parent"));
-#endif
- FilePath base_path(FILE_PATH_LITERAL("/this/is/a/path"));
- FilePath child_path(FILE_PATH_LITERAL("/this/is/a/path/under/parent"));
- FilePath result;
- bool is_relative = GetRelativePathIfPossible(base_path, child_path, &result);
- EXPECT_STREQ(expected_result.value().c_str(), result.value().c_str());
- EXPECT_TRUE(is_relative);
-}
-
-#if defined(OS_WIN)
-TEST_F(FilePathUtilsTest, RelativePathsWindowsAbsolute) {
- FilePath expected_result(FILE_PATH_LITERAL("under\\parent"));
- FilePath base_path(FILE_PATH_LITERAL("c:\\this\\is\\a\\path"));
- FilePath child_path(
- FILE_PATH_LITERAL("c:\\this\\is\\a\\path\\under\\parent"));
- FilePath result;
- bool is_relative = GetRelativePathIfPossible(base_path, child_path, &result);
- EXPECT_STREQ(expected_result.value().c_str(), result.value().c_str());
- EXPECT_TRUE(is_relative);
-}
-
-TEST_F(FilePathUtilsTest, RelativePathsWindowsDifferentDrives) {
- FilePath base_path(FILE_PATH_LITERAL("c:\\this\\is\\a\\path"));
- FilePath child_path(
- FILE_PATH_LITERAL("d:\\this\\is\\a\\path\\not\\under\\parent"));
- FilePath result;
- bool is_relative = GetRelativePathIfPossible(base_path, child_path, &result);
- EXPECT_STREQ(child_path.value().c_str(), result.value().c_str());
- EXPECT_FALSE(is_relative);
-}
-#endif
-
-TEST_F(FilePathUtilsTest, RelativePathsCaseDifferent) {
- FilePath base_path(FILE_PATH_LITERAL("/This/Is/A/Path"));
- FilePath child_path(FILE_PATH_LITERAL("/this/is/a/path/under/parent"));
- FilePath result;
- bool is_relative = GetRelativePathIfPossible(base_path, child_path, &result);
-#if defined(OS_WIN)
- EXPECT_STREQ(FILE_PATH_LITERAL("under\\parent"), result.value().c_str());
- EXPECT_TRUE(is_relative);
-#else
- EXPECT_STREQ(child_path.value().c_str(), result.value().c_str());
- EXPECT_FALSE(is_relative);
-#endif
-}
-
-TEST_F(FilePathUtilsTest, RelativePathsTrailingSlash) {
-#if defined(OS_WIN)
- FilePath expected_result(FILE_PATH_LITERAL("under\\parent"));
-#else
- FilePath expected_result(FILE_PATH_LITERAL("under/parent"));
-#endif
- FilePath base_path(FILE_PATH_LITERAL("/this/is/a/path/"));
- FilePath child_path(FILE_PATH_LITERAL("/this/is/a/path/under/parent"));
- FilePath result;
- bool is_relative = GetRelativePathIfPossible(base_path, child_path, &result);
- EXPECT_STREQ(expected_result.value().c_str(), result.value().c_str());
- EXPECT_TRUE(is_relative);
-}
-
-TEST_F(FilePathUtilsTest, RelativePathsRelativeInputs) {
-#if defined(OS_WIN)
- FilePath expected_result(FILE_PATH_LITERAL("under\\parent"));
-#else
- FilePath expected_result(FILE_PATH_LITERAL("under/parent"));
-#endif
- FilePath base_path(FILE_PATH_LITERAL("this/is/a/path"));
- FilePath child_path(FILE_PATH_LITERAL("this/is/a/path/under/parent"));
- FilePath result;
- bool is_relative = GetRelativePathIfPossible(base_path, child_path, &result);
- EXPECT_STREQ(expected_result.value().c_str(), result.value().c_str());
- EXPECT_TRUE(is_relative);
-}
-
-TEST_F(FilePathUtilsTest, FindFile) {
- String folder_name_1(*g_program_path + "/unittest_data");
- String folder_name_2(*g_program_path + "/bitmap_test");
- FilePath folder_path_1 = UTF8ToFilePath(folder_name_1);
- FilePath folder_path_2 = UTF8ToFilePath(folder_name_2);
- String file_name_1("fur.fx");
- String file_name_2("someplace/somewhere/tga-256x256-32bit.tga");
- FilePath file_path_1 = UTF8ToFilePath(file_name_1);
- FilePath file_path_2 = UTF8ToFilePath(file_name_2);
- FilePath out_path;
-
- FilePath expected_path_1(folder_path_1);
- expected_path_1 = expected_path_1.Append(file_path_1);
- o3d::AbsolutePath(&expected_path_1);
- FilePath expected_path_2(folder_path_2);
- expected_path_2 =
- expected_path_2.Append(UTF8ToFilePath("tga-256x256-32bit.tga"));
- o3d::AbsolutePath(&expected_path_2);
-
- std::vector<FilePath> paths;
- EXPECT_FALSE(FindFile(paths, file_path_1, &out_path));
- EXPECT_FALSE(FindFile(paths, file_path_2, &out_path));
- paths.push_back(folder_path_1);
- EXPECT_TRUE(FindFile(paths, file_path_1, &out_path));
- EXPECT_FALSE(FindFile(paths, file_path_2, &out_path));
- EXPECT_TRUE(FilePathsEqual(out_path, expected_path_1));
- paths.push_back(folder_path_2);
- EXPECT_TRUE(FindFile(paths, file_path_1, &out_path));
- EXPECT_TRUE(FilePathsEqual(out_path, expected_path_1));
- EXPECT_TRUE(FindFile(paths, file_path_2, &out_path));
- EXPECT_TRUE(FilePathsEqual(out_path, expected_path_2));
-}
-
-} // namespace o3d
diff --git a/o3d/utils/cross/file_text_reader.cc b/o3d/utils/cross/file_text_reader.cc
deleted file mode 100644
index 314be5e..0000000
--- a/o3d/utils/cross/file_text_reader.cc
+++ /dev/null
@@ -1,190 +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 definition of class FileTextReader. The
-// tests are in string_reader_test.cc.
-
-#include "utils/cross/file_text_reader.h"
-
-#include <stdio.h>
-#include <sys/stat.h>
-#include "base/logging.h"
-#include "base/scoped_ptr.h"
-
-namespace o3d {
-
-FileTextReader::FileTextReader(FILE* input)
- : TextReader(), input_(input) {
- if (input_ == NULL) {
- LOG(FATAL) << "Invalid NULL file pointer";
- }
- if (::ferror(input_) != 0) {
- DLOG(FATAL) << "Invalid file pointer.";
- }
-}
-
-FileTextReader::~FileTextReader() {
-}
-
-size_t FileTextReader::position() const {
- if (input_) {
- return ::ftell(input_);
- } else {
- return 0;
- }
-}
-
-bool FileTextReader::IsAtEnd() const {
- size_t position = ::ftell(input_);
- if (::feof(input_) != 0) {
- return true;
- }
- return GetFileSize() == position;
-}
-
-std::string FileTextReader::PeekString(std::string::size_type count) const {
- if (IsAtEnd()) {
- return std::string("");
- }
-
- // Find out where we are in the stream.
- size_t original_pos = ::ftell(input_);
-
- // We're just re-using code here -- the stream will not be affected
- // because we will seek back to where we started.
- std::string result = const_cast<FileTextReader*>(this)->ReadString(count);
-
- // Go back to where we started in the stream.
- ::fseek(input_, original_pos, SEEK_SET);
- return result;
-}
-
-char FileTextReader::ReadChar() {
- if (!IsAtEnd()) {
- return ::fgetc(input_);
- } else {
- return 0;
- }
-}
-
-std::string FileTextReader::ReadString(std::string::size_type count) {
- if (count <= 0 || IsAtEnd()) {
- return std::string("");
- }
-
- // Allocate a string to hold the data.
- scoped_array<char> buffer(new char[count + 1]);
-
- // Read it.
- size_t count_read = ::fread(reinterpret_cast<void*>(buffer.get()),
- sizeof(char),
- count,
- input_);
-
- // Make sure it's null terminated.
- (buffer.get())[count_read] = 0;
- return std::string(buffer.get());
-}
-
-std::string FileTextReader::ReadLine() {
- // Find out where we are in the stream.
- int original_pos = ::ftell(input_);
-
- // Find the occurance of the next eol character, regardless of what
- // kind of terminator it is.
- static const char linefeed = '\n';
- static const char carriage_return = '\r';
- int eol_pos = -1;
- int eol_len = 1;
- while (!IsAtEnd()) {
- char eol = ::fgetc(input_);
- if (eol == linefeed) {
- eol_pos = ::ftell(input_);
- break;
- }
- if (eol == carriage_return) {
- eol_pos = ::ftell(input_);
- if (IsAtEnd()) {
- break;
- }
- eol = ::fgetc(input_);
- if (eol == linefeed) {
- eol_len = 2;
- }
- break;
- }
- }
-
- // Go back to where we started in the stream.
- ::fseek(input_, original_pos, SEEK_SET);
-
- if (eol_pos > 0) {
- int count = eol_pos - original_pos - 1;
- std::string result = ReadString(count);
- // Strip off one EOL marker (of the appropriate length).
- ReadString(eol_len);
- return result;
- } else {
- // If there are no end of line markers in this file, just send
- // back the whole file.
- return ReadToEnd();
- }
-}
-
-std::string FileTextReader::ReadToEnd() {
- size_t remaining_size = GetRemainingSize();
- if (remaining_size > 0) {
- return ReadString(remaining_size);
- } else {
- return std::string("");
- }
-}
-
-size_t FileTextReader::GetFileSize() const {
- struct stat file_info;
-#if defined(OS_WIN)
- int file_number = ::_fileno(input_);
-#else
- int file_number = ::fileno(input_);
-#endif
- ::fstat(file_number, &file_info);
-
- return file_info.st_size;
-}
-
-size_t FileTextReader::GetRemainingSize() const {
- // Find out where we are in the stream.
- int original_pos = ::ftell(input_);
-
- return GetFileSize() - original_pos;
-}
-} // end namespace o3d
diff --git a/o3d/utils/cross/file_text_reader.h b/o3d/utils/cross/file_text_reader.h
deleted file mode 100644
index 307679d..0000000
--- a/o3d/utils/cross/file_text_reader.h
+++ /dev/null
@@ -1,73 +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 declaration of class FileTextReader.
-
-#ifndef O3D_UTILS_CROSS_FILE_TEXT_READER_H_
-#define O3D_UTILS_CROSS_FILE_TEXT_READER_H_
-
-#include <string>
-#include "utils/cross/text_reader.h"
-
-namespace o3d {
-
-// A FileTextReader reads a sequence of characters from an
-// in-memory string.
-class FileTextReader : public TextReader {
- public:
- // Prepare to read from the given input string.
- explicit FileTextReader(FILE* input);
- virtual ~FileTextReader();
-
- virtual bool IsAtEnd() const;
- virtual std::string PeekString(std::string::size_type count) const;
- virtual char ReadChar();
- virtual std::string ReadString(std::string::size_type count);
- virtual std::string ReadLine();
- virtual std::string ReadToEnd();
-
- // Access to the original input file pointer, and the current
- // position in that buffer.
- const FILE* input() const { return input_; }
- size_t position() const;
-
- protected:
- size_t GetFileSize() const;
- size_t GetRemainingSize() const;
-
- private:
- FILE* input_;
- DISALLOW_COPY_AND_ASSIGN(FileTextReader);
-};
-} // namespace o3d
-
-#endif // O3D_UTILS_CROSS_FILE_TEXT_READER_H_
diff --git a/o3d/utils/cross/file_text_reader_test.cc b/o3d/utils/cross/file_text_reader_test.cc
deleted file mode 100644
index 951e3429..0000000
--- a/o3d/utils/cross/file_text_reader_test.cc
+++ /dev/null
@@ -1,266 +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 tests of class FileTextReader.
-#include <stdio.h>
-
-#include "base/basictypes.h"
-#include "tests/common/win/testing_common.h"
-#include "utils/cross/file_text_reader.h"
-
-namespace o3d {
-
-namespace {
-struct FileInfo {
- const char* file_name_;
- const char* file_contents_;
-};
-
-static const FileInfo kFileInfo[] = {
- { "/test_file_string_one", "testing 1..2..3" },
- { "/test_file_string_two", "4..5..6" },
- { "/test_file_string_lf", "testing 1..2..3\n4..5..6\n" },
- { "/test_file_string_cr", "testing 1..2..3\r4..5..6\r" },
- { "/test_file_string_crlf", "testing 1..2..3\r\n4..5..6\r\n" },
- { "/test_file_string_lfcr", "testing 1..2..3\n\r4..5..6\n\r" },
- { "/test_file_string_lflf", "testing 1..2..3\n\n4..5..6\n\n" },
- { "/test_file_string_short", "T" },
- { "/test_file_string_empty", "" }
-};
-
-static const int kNumFiles = arraysize(kFileInfo);
-} // end anonymous namespace
-
-class FileTextReaderTest : public testing::Test {
- public:
- FileTextReaderTest() {
- test_string_one_ = kFileInfo[0].file_contents_;
- test_string_two_ = kFileInfo[1].file_contents_;
- test_string_lf_ = kFileInfo[2].file_contents_;
- test_string_cr_ = kFileInfo[3].file_contents_;
- test_string_crlf_ = kFileInfo[4].file_contents_;
- test_string_lfcr_ = kFileInfo[5].file_contents_;
- test_string_lflf_ = kFileInfo[6].file_contents_;
- test_string_short_ = kFileInfo[7].file_contents_;
- test_string_empty_ = kFileInfo[8].file_contents_;
- }
- virtual void SetUp() {
- // This clears out the existing Temporary files and rewrites them.
- std::string tmp_base(g_program_path->data());
- for (int i = 0; i < kNumFiles; i++) {
- std::string filename = tmp_base + kFileInfo[i].file_name_;
- FILE* file_pointer = fopen(filename.c_str(), "wb+");
- int contents_size = ::strlen(kFileInfo[i].file_contents_);
- if (contents_size > 0) {
- ::fwrite(kFileInfo[i].file_contents_, sizeof(char), contents_size,
- file_pointer);
- ::fseek(file_pointer, 0, SEEK_SET);
- }
- file_pointers_[i] = file_pointer;
- }
- }
- virtual void TearDown() {
- std::string tmp_base(g_program_path->data());
- // Clear out the tmp files.
- for (int i = 0; i < kNumFiles; i++) {
- if (file_pointers_[i]) {
- ::fclose(file_pointers_[i]);
- }
- std::string path = tmp_base + kFileInfo[i].file_name_;
-#if defined(OS_WIN)
- ::_unlink(path.c_str());
-#else
- ::unlink(path.c_str());
-#endif
- file_pointers_[i] = NULL;
- }
- }
-
- FILE* file_pointers_[kNumFiles];
- std::string test_string_one_;
- std::string test_string_two_;
- std::string test_string_lf_;
- std::string test_string_cr_;
- std::string test_string_crlf_;
- std::string test_string_lfcr_;
- std::string test_string_lflf_;
- std::string test_string_short_;
- std::string test_string_empty_;
-};
-
-TEST_F(FileTextReaderTest, StartAtBeginning) {
- FileTextReader reader(file_pointers_[0]);
- EXPECT_EQ(0U, reader.position());
- EXPECT_EQ(file_pointers_[0], reader.input());
- EXPECT_FALSE(reader.IsAtEnd());
-}
-
-TEST_F(FileTextReaderTest, TestPeekString) {
- FileTextReader reader(file_pointers_[0]);
- EXPECT_EQ(test_string_one_.substr(0, 6), reader.PeekString(6));
- EXPECT_EQ(0U, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
-}
-
-TEST_F(FileTextReaderTest, ReadsSingleCharacter) {
- FileTextReader reader(file_pointers_[0]);
- EXPECT_EQ(test_string_one_.substr(0, 1)[0], reader.ReadChar());
- EXPECT_EQ(1U, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_one_.substr(1, 2), reader.PeekString(2));
- EXPECT_EQ(1U, reader.position());
-}
-
-TEST_F(FileTextReaderTest, ReadsMultipleCharacters) {
- FileTextReader reader(file_pointers_[0]);
- EXPECT_EQ(test_string_one_.substr(0, 1)[0], reader.ReadChar());
- EXPECT_EQ(test_string_one_.substr(1, 1)[0], reader.ReadChar());
- EXPECT_EQ(2U, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_one_.substr(2, 2), reader.PeekString(2));
- EXPECT_EQ(2U, reader.position());
-}
-
-TEST_F(FileTextReaderTest, ReadsFile) {
- FileTextReader reader(file_pointers_[0]);
- EXPECT_EQ(test_string_one_.substr(0, 7), reader.ReadString(7));
- EXPECT_EQ(7U, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_one_.substr(7, 2), reader.PeekString(2));
- EXPECT_EQ(7U, reader.position());
-}
-
-TEST_F(FileTextReaderTest, EmptyFile) {
- FileTextReader reader(file_pointers_[8]);
- EXPECT_EQ("", reader.PeekString(1));
- EXPECT_EQ(0U, reader.position());
- EXPECT_TRUE(reader.IsAtEnd());
- EXPECT_EQ(0, reader.ReadChar());
- EXPECT_TRUE(reader.IsAtEnd());
-}
-
-TEST_F(FileTextReaderTest, TinyFile) {
- FileTextReader reader(file_pointers_[7]);
- EXPECT_EQ(test_string_short_.substr(0, 1), reader.PeekString(1));
- EXPECT_EQ(0U, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_short_[0], reader.ReadChar());
- EXPECT_TRUE(reader.IsAtEnd());
-}
-
-TEST_F(FileTextReaderTest, ReadsToEnd) {
- FileTextReader reader(file_pointers_[2]);
- EXPECT_EQ(test_string_lf_, reader.ReadToEnd());
- EXPECT_EQ(test_string_lf_.size(), reader.position());
- EXPECT_TRUE(reader.IsAtEnd());
- EXPECT_EQ("", reader.ReadString(1));
- EXPECT_TRUE(reader.IsAtEnd());
- EXPECT_EQ(test_string_lf_.size(), reader.position());
-}
-
-
-TEST_F(FileTextReaderTest, ReadsLinefeedFile) {
- FileTextReader reader(file_pointers_[2]);
- std::string line = reader.ReadLine();
- EXPECT_EQ(test_string_one_, line);
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_lf_.substr(test_string_one_.size() + 1, 2),
- reader.PeekString(2));
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_EQ(test_string_two_, reader.ReadLine());
- EXPECT_TRUE(reader.IsAtEnd());
- EXPECT_EQ(test_string_lf_.size(), reader.position());
-}
-
-TEST_F(FileTextReaderTest, ReadsCarriageReturnFile) {
- FileTextReader reader(file_pointers_[3]);
- EXPECT_EQ(test_string_one_, reader.ReadLine());
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_cr_.substr(test_string_one_.size() + 1, 2),
- reader.PeekString(2));
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_EQ(test_string_two_, reader.ReadLine());
- EXPECT_TRUE(reader.IsAtEnd());
- EXPECT_EQ(test_string_cr_.size(), reader.position());
-}
-
-
-TEST_F(FileTextReaderTest, ReadsCarriageReturnLinefeedFile) {
- FileTextReader reader(file_pointers_[4]);
- EXPECT_EQ(test_string_one_, reader.ReadLine());
- EXPECT_EQ(test_string_one_.size() + 2, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_crlf_.substr(test_string_one_.size() + 2, 2),
- reader.PeekString(2));
- EXPECT_EQ(test_string_one_.size() + 2, reader.position());
- EXPECT_EQ(test_string_two_, reader.ReadLine());
- EXPECT_TRUE(reader.IsAtEnd());
- EXPECT_EQ(test_string_crlf_.size(), reader.position());
-}
-
-TEST_F(FileTextReaderTest, ReadsLinefeedCarriageReturnFile) {
- FileTextReader reader(file_pointers_[5]);
- EXPECT_EQ(test_string_one_, reader.ReadLine());
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_lfcr_.substr(test_string_one_.size() + 1, 2),
- reader.PeekString(2));
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_EQ("", reader.ReadLine());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_two_, reader.ReadLine());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ("", reader.ReadLine());
- EXPECT_TRUE(reader.IsAtEnd());
- EXPECT_EQ(test_string_lfcr_.size(), reader.position());
-}
-
-TEST_F(FileTextReaderTest, ReadsLinefeedLinefeedFile) {
- FileTextReader reader(file_pointers_[6]);
- EXPECT_EQ(test_string_one_, reader.ReadLine());
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_lflf_.substr(test_string_one_.size() + 1, 2),
- reader.PeekString(2));
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_EQ("", reader.ReadLine());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_two_, reader.ReadLine());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ("", reader.ReadLine());
- EXPECT_TRUE(reader.IsAtEnd());
- EXPECT_EQ(test_string_lflf_.size(), reader.position());
-}
-
-} // namespace o3d
diff --git a/o3d/utils/cross/file_text_writer.cc b/o3d/utils/cross/file_text_writer.cc
deleted file mode 100644
index ed83133..0000000
--- a/o3d/utils/cross/file_text_writer.cc
+++ /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.
- */
-
-
-// This file contains the definition of class FileTextWriter.
-
-#include "utils/cross/file_text_writer.h"
-#include "base/logging.h"
-
-namespace o3d {
-FileTextWriter::FileTextWriter(FILE* file,
- Encoding encoding,
- NewLine new_line)
- : TextWriter(new_line),
- file_(file),
- encoding_(encoding) {
- DCHECK(file_);
-}
-
-FileTextWriter::~FileTextWriter() {
- Close();
-}
-
-void FileTextWriter::WriteChar(char c) {
- DCHECK(file_);
- fputc(c, file_);
-}
-
-void FileTextWriter::WriteString(const std::string& s) {
- DCHECK(file_);
- if (s.length() != fwrite(s.c_str(), 1, s.length(), file_)) {
- return;
- }
-}
-
-void FileTextWriter::Close() {
- if (file_ != NULL) {
- fclose(file_);
- file_ = NULL;
- }
-}
-} // namespace o3d
diff --git a/o3d/utils/cross/file_text_writer.h b/o3d/utils/cross/file_text_writer.h
deleted file mode 100644
index 7776e47..0000000
--- a/o3d/utils/cross/file_text_writer.h
+++ /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.
- */
-
-
-// This file contains the declaration of class FileTextWriter.
-
-#ifndef O3D_UTILS_CROSS_FILE_TEXT_WRITER_H_
-#define O3D_UTILS_CROSS_FILE_TEXT_WRITER_H_
-
-#include <stdio.h>
-
-#include <string>
-
-#include "utils/cross/text_writer.h"
-
-namespace o3d {
-
-// A FileTextWriter writes a sequence of characters to a file.
-class FileTextWriter : public TextWriter {
- public:
- // TODO: decide how we're going to use Unicode: wstrings of wide
- // chars or strings encoded as UTF8? Only support ASCII for now (although it
- // doesn't check that all chars are in the ASCII range).
- enum Encoding {
- ASCII,
- };
-
- // Take ownership of the given file. Prepare to write characters to
- // it using the specified character encoding and new line sequence.
- FileTextWriter(FILE* file, Encoding encoding, NewLine new_line);
- virtual ~FileTextWriter();
- virtual void WriteChar(char c);
- virtual void WriteString(const std::string& s);
- virtual void Close();
- private:
- FILE* file_;
- Encoding encoding_;
- DISALLOW_COPY_AND_ASSIGN(FileTextWriter);
-};
-} // namespace o3d
-
-#endif // O3D_UTILS_CROSS_FILE_TEXT_WRITER_H_
diff --git a/o3d/utils/cross/json_writer.cc b/o3d/utils/cross/json_writer.cc
deleted file mode 100644
index a49700e..0000000
--- a/o3d/utils/cross/json_writer.cc
+++ /dev/null
@@ -1,246 +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 definition of class JsonWriter.
-
-#include "utils/cross/json_writer.h"
-#include "base/logging.h"
-#include "base/string_util.h"
-
-using std::string;
-
-namespace o3d {
-JsonWriter::JsonWriter(TextWriter* writer, int indent_spaces)
- : writer_(writer),
- indent_spaces_(indent_spaces),
- compacting_level_(0),
- current_indentation_(0),
- new_line_pending_(false),
- comma_pending_(false) {
- DCHECK(writer_);
-}
-
-JsonWriter::~JsonWriter() {
- Close();
-}
-
-void JsonWriter::OpenObject() {
- DCHECK(writer_);
- WritePending();
- writer_->WriteChar('{');
- IncreaseIndentation();
- ScheduleNewLine();
-}
-
-void JsonWriter::CloseObject() {
- DCHECK(writer_);
- CancelComma();
- DecreaseIndentation();
- WritePending();
- writer_->WriteChar('}');
- ScheduleComma();
- ScheduleNewLine();
-}
-
-void JsonWriter::OpenArray() {
- DCHECK(writer_);
- WritePending();
- writer_->WriteChar('[');
- IncreaseIndentation();
- ScheduleNewLine();
-}
-
-void JsonWriter::CloseArray() {
- DCHECK(writer_);
- CancelComma();
- DecreaseIndentation();
- WritePending();
- writer_->WriteChar(']');
- ScheduleComma();
- ScheduleNewLine();
-}
-
-void JsonWriter::BeginCompacting() {
- WritePending();
- ++compacting_level_;
-}
-
-void JsonWriter::EndCompacting() {
- DCHECK_GT(compacting_level_, 0);
- --compacting_level_;
-}
-
-void JsonWriter::WritePropertyName(const string& name) {
- DCHECK(writer_);
- WritePending();
- writer_->WriteChar('\"');
- WriteEscapedString(name);
- writer_->WriteChar('\"');
- if (compacting_level_ > 0) {
- writer_->WriteChar(':');
- } else {
- writer_->WriteString(string(": "));
- }
-}
-
-void JsonWriter::WriteBool(bool value) {
- DCHECK(writer_);
- WritePending();
- writer_->WriteBool(value);
- ScheduleComma();
- ScheduleNewLine();
-}
-
-void JsonWriter::WriteInt(int value) {
- DCHECK(writer_);
- WritePending();
- writer_->WriteInt(value);
- ScheduleComma();
- ScheduleNewLine();
-}
-
-void JsonWriter::WriteUnsignedInt(unsigned int value) {
- DCHECK(writer_);
- WritePending();
- writer_->WriteUnsignedInt(value);
- ScheduleComma();
- ScheduleNewLine();
-}
-
-void JsonWriter::WriteFloat(float value) {
- DCHECK(writer_);
- WritePending();
- writer_->WriteFloat(value);
- ScheduleComma();
- ScheduleNewLine();
-}
-
-void JsonWriter::WriteString(const string& value) {
- DCHECK(writer_);
- WritePending();
- writer_->WriteChar('\"');
- WriteEscapedString(value);
- writer_->WriteChar('\"');
- ScheduleComma();
- ScheduleNewLine();
-}
-
-void JsonWriter::WriteNull() {
- DCHECK(writer_);
- WritePending();
- writer_->WriteString(string("null"));
- ScheduleComma();
- ScheduleNewLine();
-}
-
-void JsonWriter::Close() {
- if (writer_) {
- CancelComma();
- WritePending();
- writer_->Close();
- writer_ = NULL;
- }
-}
-
-void JsonWriter::IncreaseIndentation() {
- ++current_indentation_;
-}
-
-void JsonWriter::DecreaseIndentation() {
- DCHECK_GT(current_indentation_, 0);
- --current_indentation_;
-}
-
-void JsonWriter::ScheduleNewLine() {
- new_line_pending_ = true;
-}
-
-void JsonWriter::ScheduleComma() {
- comma_pending_ = true;
-}
-
-void JsonWriter::CancelComma() {
- comma_pending_ = false;
-}
-
-void JsonWriter::WritePending() {
- if (comma_pending_) {
- writer_->WriteChar(',');
- comma_pending_ = false;
- }
-
- if (new_line_pending_) {
- if (compacting_level_ == 0) {
- writer_->WriteNewLine();
- for (int i = 0; i < current_indentation_ * indent_spaces_; ++i) {
- writer_->WriteChar(' ');
- }
- }
- new_line_pending_ = false;
- }
-}
-
-void JsonWriter::WriteEscapedString(const string& unescaped) {
- for (string::size_type i = 0; i < unescaped.length(); ++i) {
- char c = unescaped[i];
- switch (c) {
- case '\"':
- writer_->WriteString("\\\"");
- break;
- case '\\':
- writer_->WriteString("\\\\");
- break;
- case '\b':
- writer_->WriteString("\\b");
- break;
- case '\f':
- writer_->WriteString("\\f");
- break;
- case '\n':
- writer_->WriteString("\\n");
- break;
- case '\r':
- writer_->WriteString("\\r");
- break;
- case '\t':
- writer_->WriteString("\\t");
- break;
- default:
- if (c < ' ') {
- writer_->WriteString(StringPrintf("\\u%04x", static_cast<int>(c)));
- } else {
- writer_->WriteChar(c);
- }
- }
- }
-}
-} // namespace o3d
diff --git a/o3d/utils/cross/json_writer.h b/o3d/utils/cross/json_writer.h
deleted file mode 100644
index b9a623d..0000000
--- a/o3d/utils/cross/json_writer.h
+++ /dev/null
@@ -1,121 +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 declaration of class JsonWriter.
-
-#ifndef O3D_UTILS_CROSS_JSON_WRITER_H_
-#define O3D_UTILS_CROSS_JSON_WRITER_H_
-
-#include <string>
-
-#include "base/basictypes.h"
-#include "utils/cross/text_writer.h"
-#include "utils/cross/structured_writer.h"
-
-namespace o3d {
-
-// A JsonWriter is used to write data to a TextWriter using
-// the JSON format. See http://json.org.
-class JsonWriter : public StructuredWriter {
- public:
- // Construct a JsonWriter that writes to the specified TextWriter.
- // Specify the number of spaces for each indentation level.
- JsonWriter(TextWriter* writer, int indent_spaces);
-
- // Flushes the remaining output and closes the underlying TextWriter.
- virtual ~JsonWriter();
-
- // Writes the opening brace of an JSON object literal.
- virtual void OpenObject();
-
- // Writes the closing brace of an JSON object literal.
- virtual void CloseObject();
-
- // Writes the opening bracket of a JSON array literal.
- virtual void OpenArray();
-
- // Writes the closing bracket of a JSON array literal.
- virtual void CloseArray();
-
- // Disables redundant white space until compacting is closed.
- // Can be nested.
- virtual void BeginCompacting();
-
- // Disables previously opened compacting.
- virtual void EndCompacting();
-
- // Writes the name of a property surrounded by quotes. Follow
- // with a call to one of the functions that writes a value.
- virtual void WritePropertyName(const std::string& name);
-
- // Writes a boolean literal.
- virtual void WriteBool(bool value);
-
- // Writes a number literal.
- virtual void WriteInt(int value);
-
- // Writes a number literal.
- virtual void WriteUnsignedInt(unsigned int value);
-
- // Writes a number literal.
- virtual void WriteFloat(float value);
-
- // Writes a string literal with JSON escape sequences for
- // special characters.
- virtual void WriteString(const std::string& value);
-
- // Writes a null literal.
- virtual void WriteNull();
-
- // Flushes the remaining output and closes the underlying TextWriter.
- virtual void Close();
-
- private:
- void IncreaseIndentation();
- void DecreaseIndentation();
- void ScheduleNewLine();
- void ScheduleComma();
- void CancelComma();
- void WritePending();
- void WriteEscapedString(const std::string& unescaped);
-
- TextWriter* writer_;
- int indent_spaces_;
- int compacting_level_;
- int current_indentation_;
- bool new_line_pending_;
- bool comma_pending_;
- DISALLOW_COPY_AND_ASSIGN(JsonWriter);
-};
-} // namespace o3d
-
-#endif // O3D_UTILS_CROSS_JSON_WRITER_H_
diff --git a/o3d/utils/cross/json_writer_test.cc b/o3d/utils/cross/json_writer_test.cc
deleted file mode 100644
index ad00d8b..0000000
--- a/o3d/utils/cross/json_writer_test.cc
+++ /dev/null
@@ -1,212 +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 tests of class JsonWriter.
-
-#include "tests/common/win/testing_common.h"
-#include "utils/cross/json_writer.h"
-#include "utils/cross/string_writer.h"
-
-namespace o3d {
-
-class JsonWriterTest : public testing::Test {
- public:
- JsonWriterTest()
- : output_(StringWriter::CR_LF),
- json_writer_(&output_, 2) {
- }
- protected:
- StringWriter output_;
- JsonWriter json_writer_;
-};
-
-TEST_F(JsonWriterTest, WritesEmptyObject) {
- json_writer_.OpenObject();
- json_writer_.CloseObject();
- json_writer_.Close();
- ASSERT_EQ(String("{\r\n}\r\n"), output_.ToString());
-}
-
-TEST_F(JsonWriterTest, WritesNestedObjects) {
- json_writer_.OpenObject();
- json_writer_.OpenObject();
- json_writer_.CloseObject();
- json_writer_.OpenObject();
- json_writer_.CloseObject();
- json_writer_.CloseObject();
- json_writer_.Close();
- ASSERT_EQ(String("{\r\n {\r\n },\r\n {\r\n }\r\n}\r\n"),
- output_.ToString());
-}
-
-TEST_F(JsonWriterTest, WritesObjectProperty) {
- json_writer_.OpenObject();
- json_writer_.WritePropertyName(String("myProperty"));
- json_writer_.WriteFloat(1.25f);
- json_writer_.CloseObject();
- json_writer_.Close();
- ASSERT_EQ(String("{\r\n \"myProperty\": 1.25\r\n}\r\n"),
- output_.ToString());
-}
-
-TEST_F(JsonWriterTest, EscapesSpecialCharsInObjectPropertyName) {
- json_writer_.OpenObject();
- json_writer_.WritePropertyName(String("\"\\\b\f\n\r\t\x01"));
- json_writer_.WriteFloat(1.25f);
- json_writer_.CloseObject();
- json_writer_.Close();
- ASSERT_EQ(
- String("{\r\n \"\\\"\\\\\\b\\f\\n\\r\\t\\u0001\": 1.25\r\n}\r\n"),
- output_.ToString());
-}
-TEST_F(JsonWriterTest, WritesCommaSeparatedObjectProperties) {
- json_writer_.OpenObject();
- json_writer_.WritePropertyName(String("myProperty1"));
- json_writer_.WriteFloat(1.25f);
- json_writer_.WritePropertyName(String("myProperty2"));
- json_writer_.WriteFloat(2.5f);
- json_writer_.CloseObject();
- json_writer_.Close();
- ASSERT_EQ(
- String(
- "{\r\n \"myProperty1\": 1.25,\r\n \"myProperty2\": 2.5\r\n}\r\n"),
- output_.ToString());
-}
-
-TEST_F(JsonWriterTest, WritesEmptyArray) {
- json_writer_.OpenArray();
- json_writer_.CloseArray();
- json_writer_.Close();
- ASSERT_EQ(String("[\r\n]\r\n"), output_.ToString());
-}
-
-TEST_F(JsonWriterTest, WritesNestedArrays) {
- json_writer_.OpenArray();
- json_writer_.OpenArray();
- json_writer_.CloseArray();
- json_writer_.OpenArray();
- json_writer_.CloseArray();
- json_writer_.CloseArray();
- json_writer_.Close();
- ASSERT_EQ(String("[\r\n [\r\n ],\r\n [\r\n ]\r\n]\r\n"),
- output_.ToString());
-}
-
-TEST_F(JsonWriterTest, WritesArrayOfBools) {
- json_writer_.OpenArray();
- json_writer_.WriteBool(false);
- json_writer_.WriteBool(true);
- json_writer_.CloseArray();
- json_writer_.Close();
- ASSERT_EQ(String("[\r\n false,\r\n true\r\n]\r\n"),
- output_.ToString());
-}
-
-TEST_F(JsonWriterTest, WritesArrayOfInts) {
- json_writer_.OpenArray();
- json_writer_.WriteInt(1);
- json_writer_.WriteInt(2);
- json_writer_.CloseArray();
- json_writer_.Close();
- ASSERT_EQ(String("[\r\n 1,\r\n 2\r\n]\r\n"), output_.ToString());
-}
-
-TEST_F(JsonWriterTest, WritesArrayOfUnsignedInts) {
- json_writer_.OpenArray();
- json_writer_.WriteUnsignedInt(1u);
- json_writer_.WriteUnsignedInt(2u);
- json_writer_.CloseArray();
- json_writer_.Close();
- ASSERT_EQ(String("[\r\n 1,\r\n 2\r\n]\r\n"), output_.ToString());
-}
-
-TEST_F(JsonWriterTest, WritesArrayOfFloats) {
- json_writer_.OpenArray();
- json_writer_.WriteFloat(1);
- json_writer_.WriteFloat(2);
- json_writer_.CloseArray();
- json_writer_.Close();
- ASSERT_EQ(String("[\r\n 1,\r\n 2\r\n]\r\n"), output_.ToString());
-}
-
-TEST_F(JsonWriterTest, WritesArrayOfStrings) {
- json_writer_.OpenArray();
- json_writer_.WriteString(String("abc"));
- json_writer_.WriteString(String("def"));
- json_writer_.CloseArray();
- json_writer_.Close();
- ASSERT_EQ(String("[\r\n \"abc\",\r\n \"def\"\r\n]\r\n"),
- output_.ToString());
-}
-
-TEST_F(JsonWriterTest, EscapesSpecialCharsInString) {
- json_writer_.WriteString(String("\"\\\b\f\n\r\t\x01"));
- json_writer_.Close();
- ASSERT_EQ(String("\"\\\"\\\\\\b\\f\\n\\r\\t\\u0001\"\r\n"),
- output_.ToString());
-}
-
-TEST_F(JsonWriterTest, WritesArrayOfNulls) {
- json_writer_.OpenArray();
- json_writer_.WriteNull();
- json_writer_.WriteNull();
- json_writer_.CloseArray();
- json_writer_.Close();
- ASSERT_EQ(String("[\r\n null,\r\n null\r\n]\r\n"), output_.ToString());
-}
-
-TEST_F(JsonWriterTest, WritesWithoutWhiteSpaceIfCompacted) {
- json_writer_.BeginCompacting();
- json_writer_.OpenObject();
- json_writer_.WritePropertyName(String("foo"));
- json_writer_.WriteNull();
- json_writer_.WritePropertyName(String("bar"));
- json_writer_.WriteNull();
- json_writer_.CloseObject();
- json_writer_.EndCompacting();
- json_writer_.Close();
- ASSERT_EQ(String("{\"foo\":null,\"bar\":null}\r\n"), output_.ToString());
-}
-
-TEST_F(JsonWriterTest, ShouldWritePendingWhiteSpaceBeforeCompactedElements) {
- json_writer_.OpenArray();
- json_writer_.BeginCompacting();
- json_writer_.OpenObject();
- json_writer_.WritePropertyName(String("foo"));
- json_writer_.WriteNull();
- json_writer_.CloseObject();
- json_writer_.EndCompacting();
- json_writer_.CloseArray();
- json_writer_.Close();
- ASSERT_EQ(String("[\r\n {\"foo\":null}\r\n]\r\n"), output_.ToString());
-}
-} // namespace o3d
diff --git a/o3d/utils/cross/math_gtest.cc b/o3d/utils/cross/math_gtest.cc
deleted file mode 100644
index 1296817..0000000
--- a/o3d/utils/cross/math_gtest.cc
+++ /dev/null
@@ -1,119 +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 some helper for gtest for the math library used by O3D.
-
-#include "utils/cross/math_gtest.h"
-#include "core/cross/types.h"
-
-
-namespace Vectormath {
-namespace Aos {
-
-bool operator==(const Vector4& left, const Vector4& right) {
- return left[0] == right[0] && left[1] == right[1] && left[2] == right[2] &&
- left[3] == right[3];
-}
-
-bool operator!=(const Vector4& left, const Vector4& right) {
- return !(left == right);
-}
-
-bool operator==(const Matrix4& left, const Matrix4& right) {
- return left[0] == right[0] && left[1] == right[1] && left[2] == right[2] &&
- left[3] == right[3];
-}
-
-bool operator!=(const Matrix4& left, const Matrix4& right) {
- return !(left == right);
-}
-
-std::ostream& operator<<(std::ostream& stream, const Vector4& value) {
- stream << "{" << value[0] << ", " << value[1] << ", " << value[2] << ", "
- << value[3] << "}";
- return stream;
-}
-
-std::ostream& operator<<(std::ostream& stream, const Matrix4& value) {
- stream << "{" << value[0] << ", " << value[1] << ", " << value[2] << ", "
- << value[3] << "}";
- return stream;
-}
-
-} // namespace Aos
-} // namespace Vectormath
-
-namespace o3d {
-
-bool operator==(const Float2& left, const Float2& right) {
- return left[0] == right[0] && left[1] == right[1];
-}
-
-bool operator!=(const Float2& left, const Float2& right) {
- return !(left == right);
-}
-
-bool operator==(const Float3& left, const Float3& right) {
- return left[0] == right[0] && left[1] == right[1] && left[2] == right[2];
-}
-
-bool operator!=(const Float3& left, const Float3& right) {
- return !(left == right);
-}
-
-bool operator==(const Float4& left, const Float4& right) {
- return left[0] == right[0] && left[1] == right[1] && left[2] == right[2] &&
- left[3] == right[3];
-}
-
-bool operator!=(const Float4& left, const Float4& right) {
- return !(left == right);
-}
-
-std::ostream& operator<<(std::ostream& stream, const Float2& value) {
- stream << "{" << value[0] << ", " << value[1] << "}";
- return stream;
-}
-
-std::ostream& operator<<(std::ostream& stream, const Float3& value) {
- stream << "{" << value[0] << ", " << value[1] << ", " << value[2] << "}";
- return stream;
-}
-
-std::ostream& operator<<(std::ostream& stream, const Float4& value) {
- stream << "{" << value[0] << ", " << value[1] << ", " << value[2] << ", "
- << value[3] << "}";
- return stream;
-}
-
-} // namespace o3d
-
-
diff --git a/o3d/utils/cross/math_gtest.h b/o3d/utils/cross/math_gtest.h
deleted file mode 100644
index e411eac..0000000
--- a/o3d/utils/cross/math_gtest.h
+++ /dev/null
@@ -1,71 +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 some helper for gtest for the math library used by
-// O3D.
-
-#ifndef O3D_UTILS_CROSS_MATH_GTEST_H_
-#define O3D_UTILS_CROSS_MATH_GTEST_H_
-
-#include <ostream> // NOLINT
-
-namespace Vectormath {
-namespace Aos {
-class Vector4;
-class Matrix4;
-
-bool operator==(const Vector4& left, const Vector4& right);
-bool operator!=(const Vector4& left, const Vector4& right);
-bool operator==(const Matrix4& left, const Matrix4& right);
-bool operator!=(const Matrix4& left, const Matrix4& right);
-std::ostream& operator<<(std::ostream& stream, const Vector4& value);
-std::ostream& operator<<(std::ostream& stream, const Matrix4& value);
-}
-}
-
-namespace o3d {
-class Float2;
-class Float3;
-class Float4;
-
-bool operator==(const Float2& left, const Float2& right);
-bool operator!=(const Float2& left, const Float2& right);
-bool operator==(const Float3& left, const Float3& right);
-bool operator!=(const Float3& left, const Float3& right);
-bool operator==(const Float4& left, const Float4& right);
-bool operator!=(const Float4& left, const Float4& right);
-std::ostream& operator<<(std::ostream& stream, const Float2& value);
-std::ostream& operator<<(std::ostream& stream, const Float3& value);
-std::ostream& operator<<(std::ostream& stream, const Float4& value);
-}
-
-#endif // O3D_UTILS_CROSS_MATH_GTEST_H_
-
diff --git a/o3d/utils/cross/math_gtest_test.cc b/o3d/utils/cross/math_gtest_test.cc
deleted file mode 100644
index ae6bc62..0000000
--- a/o3d/utils/cross/math_gtest_test.cc
+++ /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.
- */
-
-#include "tests/common/win/testing_common.h"
-#include "utils/cross/math_gtest.h"
-
-namespace o3d {
-
-class MathGTestTest : public testing::Test {
-};
-
-// Test the math gtest helper functions.
-TEST_F(MathGTestTest, TestMathGTest) {
- EXPECT_EQ(Float2(1.2f, 2.3f), Float2(1.2f, 2.3f));
- EXPECT_NE(Float2(1.2f, 2.3f), Float2(1.3f, 2.3f));
- EXPECT_NE(Float2(1.2f, 2.3f), Float2(1.2f, 2.4f));
- EXPECT_EQ(Float3(1.2f, 2.3f, 4.5f), Float3(1.2f, 2.3f, 4.5f));
- EXPECT_NE(Float3(1.2f, 2.3f, 4.5f), Float3(1.3f, 2.3f, 4.5f));
- EXPECT_NE(Float3(1.2f, 2.3f, 4.5f), Float3(1.2f, 2.4f, 4.5f));
- EXPECT_NE(Float3(1.2f, 2.3f, 4.5f), Float3(1.2f, 2.3f, 4.6f));
- EXPECT_EQ(Float4(1.2f, 2.3f, 4.5f, 6.7f), Float4(1.2f, 2.3f, 4.5f, 6.7f));
- EXPECT_NE(Float4(1.2f, 2.3f, 4.5f, 6.7f), Float4(1.3f, 2.3f, 4.5f, 6.7f));
- EXPECT_NE(Float4(1.2f, 2.3f, 4.5f, 6.7f), Float4(1.2f, 2.4f, 4.5f, 6.7f));
- EXPECT_NE(Float4(1.2f, 2.3f, 4.5f, 6.7f), Float4(1.2f, 2.3f, 4.6f, 6.7f));
- EXPECT_NE(Float4(1.2f, 2.3f, 4.5f, 6.7f), Float4(1.2f, 2.3f, 4.5f, 6.8f));
- Matrix4 a(Vector4(1.1f, 2.2f, 3.3f, 4.4f),
- Vector4(1.2f, 2.3f, 3.4f, 4.5f),
- Vector4(1.3f, 2.4f, 3.5f, 4.6f),
- Vector4(1.4f, 2.5f, 3.6f, 4.7f));
- Matrix4 b(a);
- EXPECT_EQ(a, b);
- for (int ii = 0; ii < 4; ++ii) {
- for (int jj = 0; jj < 4; ++jj) {
- b = a;
- b.setElem(ii, jj, b.getElem(ii, jj) * 2);
- EXPECT_NE(a, b);
- }
- }
-}
-
-} // namespace o3d
-
diff --git a/o3d/utils/cross/string_reader.cc b/o3d/utils/cross/string_reader.cc
deleted file mode 100644
index c62669d..0000000
--- a/o3d/utils/cross/string_reader.cc
+++ /dev/null
@@ -1,110 +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 definition of class StringReader. The
-// tests are in string_reader_test.cc.
-
-#include <stdio.h>
-#include "utils/cross/string_reader.h"
-
-namespace o3d {
-
-StringReader::StringReader(const std::string& input)
- : TextReader(), input_(input), position_(0) {
-}
-
-StringReader::~StringReader() {
-}
-
-bool StringReader::IsAtEnd() const {
- return position_ == input_.size();
-}
-
-std::string StringReader::PeekString(
- std::string::size_type count) const {
- count = std::min(input_.size() - position_, count);
- if (count > 0) {
- return input_.substr(position_, count);
- } else {
- return "";
- }
-}
-
-char StringReader::ReadChar() {
- if (position_ <= input_.size() && input_.size() > 0) {
- position_++;
- return input_[position_ - 1];
- } else {
- return 0;
- }
-}
-
-std::string StringReader::ReadString(std::string::size_type count) {
- count = std::min(input_.size() - position_, count);
- std::string result;
- if (count > 0) {
- result = input_.substr(position_, count);
- position_ += count;
- }
- return result;
-}
-
-std::string StringReader::ReadLine() {
- std::string::size_type possible_eol = input_.find_first_of("\r\n", position_);
- if (possible_eol == std::string::npos) {
- // There wasn't an end of line marker anywhere, so just return the
- // whole string.
- return ReadToEnd();
- } else {
- if ((input_.size() - position_) > 1) {
- // See which end of line marker we have and strip it.
- int eol_len = TestForEndOfLine(input_.substr(possible_eol, 2));
- std::string result = input_.substr(position_, possible_eol - position_);
- position_ = possible_eol + eol_len;
- return result;
- } else {
- // If it's only one long, and it found a carriage return or a
- // linefeed, then we just eat that character and return an
- // empty string.
- position_++;
- return std::string("");
- }
- }
- return std::string("");
-}
-
-std::string StringReader::ReadToEnd() {
- std::string result = input_.substr(position_);
- position_ = input_.size();
- return result;
-}
-} // end namespace o3d
diff --git a/o3d/utils/cross/string_reader.h b/o3d/utils/cross/string_reader.h
deleted file mode 100644
index aea6ea6..0000000
--- a/o3d/utils/cross/string_reader.h
+++ /dev/null
@@ -1,71 +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 declaration of class StringReader.
-
-#ifndef O3D_UTILS_CROSS_STRING_READER_H_
-#define O3D_UTILS_CROSS_STRING_READER_H_
-
-#include <string>
-
-#include "utils/cross/text_reader.h"
-
-namespace o3d {
-
-// A StringReader reads a sequence of characters from an
-// in-memory string.
-class StringReader : public TextReader {
- public:
- // Prepare to read from the given input string.
- explicit StringReader(const std::string& input);
- virtual ~StringReader();
-
- virtual bool IsAtEnd() const;
- virtual std::string PeekString(std::string::size_type count) const;
- virtual char ReadChar();
- virtual std::string ReadString(std::string::size_type count);
- virtual std::string ReadLine();
- virtual std::string ReadToEnd();
-
- // Access to the original input buffer, and the current position in
- // that buffer.
- const std::string& input() const { return input_; }
- std::string::size_type position() const { return position_; }
-
- private:
- std::string input_;
- std::string::size_type position_;
- DISALLOW_COPY_AND_ASSIGN(StringReader);
-};
-} // namespace o3d
-
-#endif // O3D_UTILS_CROSS_STRING_READER_H_
diff --git a/o3d/utils/cross/string_reader_test.cc b/o3d/utils/cross/string_reader_test.cc
deleted file mode 100644
index 1afab5e..0000000
--- a/o3d/utils/cross/string_reader_test.cc
+++ /dev/null
@@ -1,200 +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 tests of class StringReader.
-#include <stdio.h>
-
-#include "tests/common/win/testing_common.h"
-#include "utils/cross/string_reader.h"
-
-namespace o3d {
-
-namespace {
-static const char* kTestStrings[] = {
- "testing 1..2..3",
- "4..5..6",
- "testing 1..2..3\n4..5..6\n",
- "testing 1..2..3\r4..5..6\r",
- "testing 1..2..3\r\n4..5..6\r\n",
- "testing 1..2..3\n\r4..5..6\n\r",
- "testing 1..2..3\n\n4..5..6\n\n",
-};
-} // end anonymous namespace
-
-class StringReaderTest : public testing::Test {
- public:
- StringReaderTest() {
- test_string_one_ = kTestStrings[0];
- test_string_two_ = kTestStrings[1];
- test_string_lf_ = kTestStrings[2];
- test_string_cr_ = kTestStrings[3];
- test_string_crlf_ = kTestStrings[4];
- test_string_lfcr_ = kTestStrings[5];
- test_string_lflf_ = kTestStrings[6];
- }
-
- std::string test_string_one_;
- std::string test_string_two_;
- std::string test_string_lf_;
- std::string test_string_cr_;
- std::string test_string_crlf_;
- std::string test_string_lfcr_;
- std::string test_string_lflf_;
-};
-
-TEST_F(StringReaderTest, StartAtBeginning) {
- StringReader reader(test_string_one_);
- EXPECT_EQ(0U, reader.position());
- EXPECT_EQ(test_string_one_, reader.input());
-}
-
-TEST_F(StringReaderTest, TestPeekString) {
- StringReader reader(test_string_one_);
- EXPECT_EQ(test_string_one_.substr(0, 6), reader.PeekString(6));
- EXPECT_EQ(0U, reader.position());
- EXPECT_EQ(test_string_one_, reader.input());
-}
-
-TEST_F(StringReaderTest, ReadsSingleCharacter) {
- StringReader reader(test_string_one_);
- EXPECT_EQ(test_string_one_.substr(0, 1)[0], reader.ReadChar());
- EXPECT_EQ(1U, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_one_.substr(1, 2), reader.PeekString(2));
- EXPECT_EQ(1U, reader.position());
-}
-
-TEST_F(StringReaderTest, ReadsMultipleCharacters) {
- StringReader reader(test_string_one_);
- EXPECT_EQ(test_string_one_.substr(0, 1)[0], reader.ReadChar());
- EXPECT_EQ(test_string_one_.substr(1, 1)[0], reader.ReadChar());
- EXPECT_EQ(2U, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_one_.substr(2, 2), reader.PeekString(2));
- EXPECT_EQ(2U, reader.position());
-}
-
-TEST_F(StringReaderTest, ReadsString) {
- StringReader reader(test_string_one_);
- EXPECT_EQ(test_string_one_.substr(0, 7), reader.ReadString(7));
- EXPECT_EQ(7U, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_one_.substr(7, 2), reader.PeekString(2));
- EXPECT_EQ(7U, reader.position());
-}
-
-TEST_F(StringReaderTest, ReadsToEnd) {
- StringReader reader(test_string_lf_);
- EXPECT_EQ(test_string_lf_, reader.ReadToEnd());
- EXPECT_EQ(test_string_lf_.size(), reader.position());
- EXPECT_TRUE(reader.IsAtEnd());
- EXPECT_EQ("", reader.ReadString(1));
- EXPECT_TRUE(reader.IsAtEnd());
- EXPECT_EQ(test_string_lf_.size(), reader.position());
-}
-
-
-TEST_F(StringReaderTest, ReadsLinefeedString) {
- StringReader reader(test_string_lf_);
- std::string line = reader.ReadLine();
- EXPECT_EQ(test_string_one_, line);
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_lf_.substr(test_string_one_.size() + 1, 2),
- reader.PeekString(2));
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_EQ(test_string_two_, reader.ReadLine());
- EXPECT_TRUE(reader.IsAtEnd());
- EXPECT_EQ(test_string_lf_.size(), reader.position());
-}
-
-TEST_F(StringReaderTest, ReadsCarriageReturnString) {
- StringReader reader(test_string_cr_);
- EXPECT_EQ(test_string_one_, reader.ReadLine());
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_cr_.substr(test_string_one_.size() + 1, 2),
- reader.PeekString(2));
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_EQ(test_string_two_, reader.ReadLine());
- EXPECT_TRUE(reader.IsAtEnd());
- EXPECT_EQ(test_string_cr_.size(), reader.position());
-}
-
-
-TEST_F(StringReaderTest, ReadsCarriageReturnLinefeedString) {
- StringReader reader(test_string_crlf_);
- EXPECT_EQ(test_string_one_, reader.ReadLine());
- EXPECT_EQ(test_string_one_.size() + 2, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_crlf_.substr(test_string_one_.size() + 2, 2),
- reader.PeekString(2));
- EXPECT_EQ(test_string_one_.size() + 2, reader.position());
- EXPECT_EQ(test_string_two_, reader.ReadLine());
- EXPECT_TRUE(reader.IsAtEnd());
- EXPECT_EQ(test_string_crlf_.size(), reader.position());
-}
-
-TEST_F(StringReaderTest, ReadsLinefeedCarriageReturnString) {
- StringReader reader(test_string_lfcr_);
- EXPECT_EQ(test_string_one_, reader.ReadLine());
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_lfcr_.substr(test_string_one_.size() + 1, 2),
- reader.PeekString(2));
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_EQ("", reader.ReadLine());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_two_, reader.ReadLine());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ("", reader.ReadLine());
- EXPECT_TRUE(reader.IsAtEnd());
- EXPECT_EQ(test_string_lfcr_.size(), reader.position());
-}
-
-TEST_F(StringReaderTest, ReadsLinefeedLinefeedString) {
- StringReader reader(test_string_lflf_);
- EXPECT_EQ(test_string_one_, reader.ReadLine());
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_lflf_.substr(test_string_one_.size() + 1, 2),
- reader.PeekString(2));
- EXPECT_EQ(test_string_one_.size() + 1, reader.position());
- EXPECT_EQ("", reader.ReadLine());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ(test_string_two_, reader.ReadLine());
- EXPECT_FALSE(reader.IsAtEnd());
- EXPECT_EQ("", reader.ReadLine());
- EXPECT_TRUE(reader.IsAtEnd());
- EXPECT_EQ(test_string_lflf_.size(), reader.position());
-}
-} // namespace o3d
diff --git a/o3d/utils/cross/string_writer.cc b/o3d/utils/cross/string_writer.cc
deleted file mode 100644
index ccedeeb..0000000
--- a/o3d/utils/cross/string_writer.cc
+++ /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.
- */
-
-
-// This file contains the definition of class StringWriter.
-
-#include "utils/cross/string_writer.h"
-
-namespace o3d {
-
-StringWriter::StringWriter(NewLine new_line)
- : TextWriter(new_line) {
-}
-
-void StringWriter::WriteChar(char c) {
- string_ += c;
-}
-
-void StringWriter::WriteString(const std::string& s) {
- string_ += s;
-}
-
-std::string StringWriter::ToString() const {
- return string_;
-}
-
-} // namespace o3d
diff --git a/o3d/utils/cross/string_writer.h b/o3d/utils/cross/string_writer.h
deleted file mode 100644
index 823f15f..0000000
--- a/o3d/utils/cross/string_writer.h
+++ /dev/null
@@ -1,62 +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 declaration of class StringWriter.
-
-#ifndef O3D_UTILS_CROSS_STRING_WRITER_H_
-#define O3D_UTILS_CROSS_STRING_WRITER_H_
-
-#include <string>
-
-#include "utils/cross/text_writer.h"
-
-namespace o3d {
-
-// A StringWriter writes a sequence of characters to an
-// in-memory string.
-class StringWriter : public TextWriter {
- public:
- // Prepare to produce a string using the given new line
- // sequence.
- explicit StringWriter(NewLine new_line);
- virtual void WriteChar(char c);
- virtual void WriteString(const std::string& s);
-
- // Retrieve the string that has been produced so far.
- std::string ToString() const;
- private:
- std::string string_;
- DISALLOW_COPY_AND_ASSIGN(StringWriter);
-};
-} // namespace o3d
-
-#endif // O3D_UTILS_CROSS_STRING_WRITER_H_
diff --git a/o3d/utils/cross/string_writer_test.cc b/o3d/utils/cross/string_writer_test.cc
deleted file mode 100644
index 488bad0..0000000
--- a/o3d/utils/cross/string_writer_test.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 tests of class StringWriter.
-
-#include "tests/common/win/testing_common.h"
-#include "utils/cross/string_writer.h"
-
-namespace o3d {
-
-class StringWriterTest : public testing::Test {
-};
-
-TEST_F(StringWriterTest, EmptyByDefault) {
- StringWriter writer(StringWriter::CR);
- EXPECT_EQ(String(), writer.ToString());
-}
-
-TEST_F(StringWriterTest, WritesSingleCharacter) {
- StringWriter writer(StringWriter::CR);
- writer.WriteChar('y');
- EXPECT_EQ(String("y"), writer.ToString());
-}
-
-TEST_F(StringWriterTest, WritesMultipleCharacters) {
- StringWriter writer(StringWriter::CR);
- writer.WriteChar('y');
- writer.WriteChar('z');
- EXPECT_EQ(String("yz"), writer.ToString());
-}
-
-TEST_F(StringWriterTest, WritesString) {
- StringWriter writer(StringWriter::CR);
- writer.WriteString(String("hello"));
- EXPECT_EQ(String("hello"), writer.ToString());
-}
-
-TEST_F(StringWriterTest, WritesCarriageReturnNewLine) {
- StringWriter writer(StringWriter::CR);
- writer.WriteNewLine();
- EXPECT_EQ(String("\r"), writer.ToString());
-}
-
-TEST_F(StringWriterTest, WritesCarriageReturnLineFeedNewLine) {
- StringWriter writer(StringWriter::CR_LF);
- writer.WriteNewLine();
- EXPECT_EQ(String("\r\n"), writer.ToString());
-}
-
-TEST_F(StringWriterTest, WritesLineFeedNewLine) {
- StringWriter writer(StringWriter::LF);
- writer.WriteNewLine();
- EXPECT_EQ(String("\n"), writer.ToString());
-}
-
-TEST_F(StringWriterTest, WritesFalse) {
- StringWriter writer(StringWriter::LF);
- writer.WriteBool(false);
- EXPECT_EQ(String("false"), writer.ToString());
-}
-
-TEST_F(StringWriterTest, WritesTrue) {
- StringWriter writer(StringWriter::LF);
- writer.WriteBool(true);
- EXPECT_EQ(String("true"), writer.ToString());
-}
-
-TEST_F(StringWriterTest, WritesInt) {
- StringWriter writer(StringWriter::LF);
- writer.WriteInt(-123);
- EXPECT_EQ(String("-123"), writer.ToString());
-}
-
-TEST_F(StringWriterTest, WritesUnsignedInt) {
- StringWriter writer(StringWriter::LF);
- writer.WriteInt(123u);
- ASSERT_EQ(String("123"), writer.ToString());
-}
-
-TEST_F(StringWriterTest, WritesFloat) {
- StringWriter writer(StringWriter::LF);
- writer.WriteFloat(1.25f);
- EXPECT_EQ(String("1.25"), writer.ToString());
-}
-
-TEST_F(StringWriterTest, WritesPrintfFormatted) {
- StringWriter writer(StringWriter::LF);
- writer.WriteFormatted("%s: %d", "age", 31);
- EXPECT_EQ(String("age: 31"), writer.ToString());
-}
-} // namespace o3d
diff --git a/o3d/utils/cross/structured_writer.h b/o3d/utils/cross/structured_writer.h
deleted file mode 100644
index e25f615..0000000
--- a/o3d/utils/cross/structured_writer.h
+++ /dev/null
@@ -1,103 +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 declaration of class StructuredWriter.
-
-#ifndef O3D_UTILS_CROSS_STRUCTURED_WRITER_H_
-#define O3D_UTILS_CROSS_STRUCTURED_WRITER_H_
-
-#include <string>
-
-#include "base/basictypes.h"
-
-namespace o3d {
-
-// Interface of classes that can write structured data consisting of
-// a hierarchy of objects (with named properties) and arrays of typed
-// values.
-class StructuredWriter {
- public:
- StructuredWriter() {}
- virtual ~StructuredWriter() {}
-
- // Opens an object block. An object block contains property / value
- // pairs.
- virtual void OpenObject() = 0;
-
- // Closes an object block.
- virtual void CloseObject() = 0;
-
- // Opens an array block. An array block contains zero or more values.
- virtual void OpenArray() = 0;
-
- // Closes an array block.
- virtual void CloseArray() = 0;
-
- // Hints to the writer that it should not add additional formatting
- // to make the output more readable. These can be nested.
- virtual void BeginCompacting() = 0;
-
- // Ends the hint that additional formatting is not necessary.
- virtual void EndCompacting() = 0;
-
- // Writes the name of a property. This should be immediately by a
- // value.
- virtual void WritePropertyName(const std::string& name) = 0;
-
- // Writes a boolean value.
- virtual void WriteBool(bool value) = 0;
-
- // Writes an integer value.
- virtual void WriteInt(int value) = 0;
-
- // Writes an unsigned integer value.
- virtual void WriteUnsignedInt(unsigned int value) = 0;
-
- // Writes a float value.
- virtual void WriteFloat(float value) = 0;
-
- // Writes a string value.
- virtual void WriteString(const std::string& value) = 0;
-
- // Writes a null value.
- virtual void WriteNull() = 0;
-
- // Flushes any unwritten content and closes the writer. No further
- // writes are allowed.
- virtual void Close() {}
-
- private:
- DISALLOW_COPY_AND_ASSIGN(StructuredWriter);
-};
-} // namespace o3d
-
-#endif // O3D_UTILS_CROSS_STRUCTURED_WRITER_H_
diff --git a/o3d/utils/cross/temporary_file.cc b/o3d/utils/cross/temporary_file.cc
deleted file mode 100644
index fb9e8de..0000000
--- a/o3d/utils/cross/temporary_file.cc
+++ /dev/null
@@ -1,89 +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 definition of class TemporaryFile.
-
-#include "utils/cross/temporary_file.h"
-
-#include "base/file_path.h"
-#include "base/file_util.h"
-
-namespace o3d {
-
-// TODO(gspencer): Remove this. This is a hack to prevent needing to
-// merge all of chrome's base code into the google code O3D tree.
-#ifndef GYP_BUILD
-#define CreateTemporaryFile CreateTemporaryFileName
-#endif
-
-namespace {
-void DeletePath(const FilePath& path) {
- if (!path.empty()) {
- file_util::Delete(path, false);
- }
-}
-} // end anonymous namespace
-
-TemporaryFile::TemporaryFile() {
- // file_path_ is initialized to be empty.
-}
-
-TemporaryFile::TemporaryFile(const FilePath& file_to_manage)
- : file_path_(file_to_manage) {
-}
-
-bool TemporaryFile::Create(TemporaryFile* temporary_file) {
- FilePath temporary_path;
- if (file_util::CreateTemporaryFile(&temporary_path)) {
- temporary_file->Reset(temporary_path);
- } else {
- return false;
- }
- return true;
-}
-
-TemporaryFile::~TemporaryFile() {
- DeletePath(file_path_);
-}
-
-FilePath TemporaryFile::Release() {
- FilePath old_path = file_path_;
- file_path_ = FilePath();
- return old_path;
-}
-
-void TemporaryFile::Reset(const FilePath& file_path) {
- DeletePath(file_path_);
- file_path_ = file_path;
-}
-
-} // end namespace o3d
diff --git a/o3d/utils/cross/temporary_file.h b/o3d/utils/cross/temporary_file.h
deleted file mode 100644
index f3cf383..0000000
--- a/o3d/utils/cross/temporary_file.h
+++ /dev/null
@@ -1,86 +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 a simple manager class that manages a temporary
-// file.
-
-#ifndef O3D_UTILS_CROSS_TEMPORARY_FILE_H_
-#define O3D_UTILS_CROSS_TEMPORARY_FILE_H_
-
-#include "base/file_path.h"
-
-namespace o3d {
-
-// TemporaryFile is a simple manager class that manages a temporary
-// file. It accepts the path to the temporary file when it is
-// created, and deletes the temporary file when it goes out of scope.
-// It is up to the creator to verify that the program has the rights
-// to delete the file given to it.
-class TemporaryFile {
- public:
- // Creates an empty TemporaryFile object. Must call "reset" to have
- // it manage a file.
- TemporaryFile();
-
- // Manages the given file path as a temporary file.
- explicit TemporaryFile(const FilePath& file_to_manage);
- ~TemporaryFile();
-
- // Returns the currently managed path.
- const FilePath& path() const {
- return file_path_;
- }
-
- // Releases the managed path so that it will NOT be deleted when
- // this object goes out of scope. The path that was being managed
- // is returned.
- FilePath Release();
-
- // Resets the path being managed to the supplied path. If this
- // object was managing a file before, then that file will be
- // immediately deleted.
- void Reset(const FilePath& file_path);
-
- // Creates an empty temporary file in the system's default temporary
- // directory and resets the given TemporaryFile object to manage
- // that file. Returns true if it was successful in creating the
- // file.
- static bool Create(TemporaryFile* temp_file);
-
- private:
- FilePath file_path_;
-
- DISALLOW_COPY_AND_ASSIGN(TemporaryFile);
-};
-
-} // end namespace o3d
-#endif // O3D_UTILS_CROSS_TEMPORARY_FILE_H_
diff --git a/o3d/utils/cross/temporary_file_test.cc b/o3d/utils/cross/temporary_file_test.cc
deleted file mode 100644
index d9ae361..0000000
--- a/o3d/utils/cross/temporary_file_test.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 tests of class TemporaryFile.
-
-#include <stdio.h>
-
-#include "base/file_util.h"
-#include "tests/common/win/testing_common.h"
-#include "utils/cross/temporary_file.h"
-
-namespace o3d {
-
-// TODO(gspencer): Remove this once scons build is dead. This is a
-// hack to prevent needing to merge all of chrome's base code into the
-// google code O3D tree.
-#ifndef GYP_BUILD
-#define CreateTemporaryFile CreateTemporaryFileName
-#endif
-
-class TemporaryFileTest : public testing::Test {
-};
-
-TEST_F(TemporaryFileTest, BasicConstruction) {
- TemporaryFile temporary_file;
- EXPECT_TRUE(temporary_file.path().empty());
-}
-
-TEST_F(TemporaryFileTest, BasicFunction) {
- FilePath path;
- file_util::CreateTemporaryFile(&path);
- EXPECT_TRUE(file_util::PathExists(path));
- {
- TemporaryFile temporary_file(path);
- EXPECT_TRUE(file_util::PathExists(path));
- EXPECT_EQ(path.value(), temporary_file.path().value());
- EXPECT_TRUE(file_util::PathExists(temporary_file.path()));
- }
- EXPECT_FALSE(file_util::PathExists(path));
-}
-
-TEST_F(TemporaryFileTest, Reset) {
- FilePath path;
- FilePath path1;
- file_util::CreateTemporaryFile(&path);
- file_util::CreateTemporaryFile(&path1);
- EXPECT_TRUE(file_util::PathExists(path));
- EXPECT_TRUE(file_util::PathExists(path1));
- {
- TemporaryFile temporary_file(path1);
- EXPECT_EQ(path1.value(), temporary_file.path().value());
- EXPECT_TRUE(file_util::PathExists(path1));
- EXPECT_TRUE(file_util::PathExists(temporary_file.path()));
- temporary_file.Reset(path);
- EXPECT_TRUE(file_util::PathExists(path));
- EXPECT_EQ(path.value(), temporary_file.path().value());
- EXPECT_FALSE(file_util::PathExists(path1));
- EXPECT_TRUE(file_util::PathExists(path));
- EXPECT_TRUE(file_util::PathExists(temporary_file.path()));
- }
- EXPECT_FALSE(file_util::PathExists(path));
- EXPECT_FALSE(file_util::PathExists(path1));
-}
-
-TEST_F(TemporaryFileTest, Release) {
- FilePath path;
- file_util::CreateTemporaryFile(&path);
- EXPECT_TRUE(file_util::PathExists(path));
- {
- TemporaryFile temporary_file(path);
- EXPECT_TRUE(file_util::PathExists(path));
- EXPECT_TRUE(file_util::PathExists(temporary_file.path()));
- temporary_file.Release();
- }
- EXPECT_TRUE(file_util::PathExists(path));
-}
-
-TEST_F(TemporaryFileTest, Create) {
- FilePath test_path;
- {
- TemporaryFile temporary_file;
- TemporaryFile::Create(&temporary_file);
- EXPECT_FALSE(temporary_file.path().empty());
- EXPECT_TRUE(file_util::PathExists(temporary_file.path()));
- EXPECT_TRUE(file_util::PathIsWritable(temporary_file.path()));
- test_path = temporary_file.path();
- }
- EXPECT_FALSE(file_util::PathExists(test_path));
-}
-
-} // namespace o3d
diff --git a/o3d/utils/cross/text_reader.cc b/o3d/utils/cross/text_reader.cc
deleted file mode 100644
index c6f1e56..0000000
--- a/o3d/utils/cross/text_reader.cc
+++ /dev/null
@@ -1,66 +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 definition of class TextReader. The
-// tests are in string_reader_test.cc.
-
-#include "utils/cross/text_reader.h"
-
-namespace o3d {
-namespace {
-static const char kLinefeed = '\n';
-static const char kCarriageReturn = '\r';
-}
-
-TextReader::TextReader() {
-}
-
-TextReader::~TextReader() {
-}
-
-int TextReader::TestForEndOfLine(const std::string& eol) {
- if (eol.empty()) {
- return 0;
- }
- if (eol[0] == kLinefeed) {
- return 1;
- }
- if (eol[0] == kCarriageReturn) {
- if (eol.size() > 1 && eol[1] == kLinefeed) {
- return 2;
- } else {
- return 1;
- }
- }
- return 0;
-}
-} // end namespace o3d
diff --git a/o3d/utils/cross/text_reader.h b/o3d/utils/cross/text_reader.h
deleted file mode 100644
index 470b666..0000000
--- a/o3d/utils/cross/text_reader.h
+++ /dev/null
@@ -1,91 +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 declaration of class TextReader.
-
-#ifndef O3D_UTILS_CROSS_TEXT_READER_H_
-#define O3D_UTILS_CROSS_TEXT_READER_H_
-
-#include <string>
-#include "base/basictypes.h"
-
-namespace o3d {
-
-// TextReader is the abstract base class of classes
-// that read a sequence of characters to an underlying
-// medium.
-class TextReader {
- public:
- // Construct a new TextReader.
- TextReader();
- virtual ~TextReader();
-
- // Returns true if at the end of the input.
- virtual bool IsAtEnd() const = 0;
-
- // Read ahead up to count characters and return them as a string,
- // but don't modify the input's current position. Returns the empty
- // string if at the end of the input.
- virtual std::string PeekString(std::string::size_type count) const = 0;
-
- // Read a single character.
- virtual char ReadChar() = 0;
-
- // Read a number of characters as a string. If the input isn't that
- // long, the string may be shorter than the given number of
- // characters. Returns an empty string if it is already at the end
- // of the input or if there is an error.
- virtual std::string ReadString(std::string::size_type count) = 0;
-
- // Read a line of text, terminated by any kind of line terminator
- // (LF/CRLF/CR). Returns the empty string if at end of input, or if
- // there is an error.
- virtual std::string ReadLine() = 0;
-
- // Read the remaining file into a string, linefeeds and all.
- // Returns the empty string if already at the end of the file or
- // there is an error.
- virtual std::string ReadToEnd() = 0;
-
- protected:
- // Returns length of EOL marker (one or two characters) if the given
- // character string starts with an end of line marker. Returns zero
- // if there is no EOL marker at the BEGINNING of the string.
- static int TestForEndOfLine(const std::string& eol);
-
- private:
-
- DISALLOW_COPY_AND_ASSIGN(TextReader);
-};
-} // namespace o3d
-
-#endif // O3D_UTILS_CROSS_TEXT_READER_H_
diff --git a/o3d/utils/cross/text_writer.cc b/o3d/utils/cross/text_writer.cc
deleted file mode 100644
index 01dca8d..0000000
--- a/o3d/utils/cross/text_writer.cc
+++ /dev/null
@@ -1,104 +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 definition of class TextWriter. The
-// tests are in string_writer_test.cc.
-
-#include <stdarg.h>
-
-#include "utils/cross/text_writer.h"
-#include "base/string_util.h"
-
-using std::string;
-
-namespace o3d {
-TextWriter::TextWriter(NewLine new_line)
- : new_line_(new_line) {
-}
-
-TextWriter::~TextWriter() {
-}
-
-void TextWriter::WriteString(const string& s) {
- for (size_t i = 0; i != s.length(); ++i) {
- WriteChar(s[i]);
- }
-}
-
-void TextWriter::WriteBool(bool value) {
- if (value) {
- WriteString(string("true"));
- } else {
- WriteString(string("false"));
- }
-}
-
-void TextWriter::WriteInt(int value) {
- WriteString(StringPrintf("%d", value));
-}
-
-void TextWriter::WriteUnsignedInt(unsigned int value) {
- WriteString(StringPrintf("%u", value));
-}
-
-void TextWriter::WriteFloat(float value) {
- WriteString(StringPrintf("%g", value));
-}
-
-void TextWriter::WriteFormatted(const char* format, ...) {
- va_list args;
- va_start(args, format);
- string formatted;
- StringAppendV(&formatted, format, args);
- va_end(args);
-
- WriteString(formatted);
-}
-
-void TextWriter::WriteNewLine() {
- switch (new_line_) {
- case CR:
- WriteChar('\r');
- break;
- case CR_LF:
- WriteChar('\r');
- WriteChar('\n');
- break;
- case LF:
- WriteChar('\n');
- break;
- }
-}
-
-void TextWriter::Close() {
-}
-} // namespace o3d
diff --git a/o3d/utils/cross/text_writer.h b/o3d/utils/cross/text_writer.h
deleted file mode 100644
index 59fab88..0000000
--- a/o3d/utils/cross/text_writer.h
+++ /dev/null
@@ -1,95 +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 declaration of class TextWriter.
-
-#ifndef O3D_UTILS_CROSS_TEXT_WRITER_H_
-#define O3D_UTILS_CROSS_TEXT_WRITER_H_
-
-#include <string>
-
-#include "base/basictypes.h"
-
-namespace o3d {
-
-// TextWriter is the abstract base class of classes
-// that write a sequence of characters to an underlying
-// medium.
-class TextWriter {
- public:
- enum NewLine {
- LF,
- CR_LF,
- CR,
- };
-
- // Construct a new TextWriter using the given newline
- // sequence.
- explicit TextWriter(NewLine new_line);
- virtual ~TextWriter();
-
- // Write a single character.
- virtual void WriteChar(char c) = 0;
-
- // Write a string of characters.
- virtual void WriteString(const std::string& s);
-
- // Write "true" or "false".
- void WriteBool(bool value);
-
- // Write a signed integer.
- void WriteInt(int value);
-
- // Write an unsigned integer.
- void WriteUnsignedInt(unsigned int value);
-
- // Write a floating point number.
- void WriteFloat(float value);
-
- // Write a printf formatted string.
- void WriteFormatted(const char* format, ...);
-
- // Write a newline.
- void WriteNewLine();
-
- // Close the writer.
- virtual void Close();
-
- NewLine new_line() const { return new_line_; }
-
- private:
- NewLine new_line_;
- DISALLOW_COPY_AND_ASSIGN(TextWriter);
-};
-} // namespace o3d
-
-#endif // O3D_UTILS_CROSS_TEXT_WRITER_H_
diff --git a/o3d/utils/utils.gyp b/o3d/utils/utils.gyp
deleted file mode 100644
index b1f197a..0000000
--- a/o3d/utils/utils.gyp
+++ /dev/null
@@ -1,75 +0,0 @@
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'variables': {
- 'chromium_code': 1,
- },
- 'includes': [
- '../build/common.gypi',
- ],
- 'target_defaults': {
- 'include_dirs': [
- '..',
- '../..',
- '../../<(gtestdir)',
- ],
- },
- 'targets': [
- {
- 'target_name': 'o3dUtils',
- 'type': 'static_library',
- 'sources': [
- "cross/base64.cc",
- "cross/base64.h",
- "cross/dataurl.cc",
- "cross/dataurl.h",
- "cross/file_path_utils.cc",
- "cross/file_path_utils.h",
- "cross/file_text_reader.cc",
- "cross/file_text_reader.h",
- "cross/file_text_writer.cc",
- "cross/file_text_writer.h",
- "cross/json_writer.cc",
- "cross/json_writer.h",
- "cross/string_reader.cc",
- "cross/string_reader.h",
- "cross/string_writer.cc",
- "cross/string_writer.h",
- "cross/structured_writer.h",
- "cross/temporary_file.cc",
- "cross/temporary_file.h",
- "cross/text_reader.cc",
- "cross/text_reader.h",
- "cross/text_writer.cc",
- "cross/text_writer.h",
- ],
- },
- {
- 'target_name': 'o3dUtilsTest',
- 'type': 'none',
- 'dependencies': [
- 'o3dUtils',
- ],
- 'direct_dependent_settings': {
- 'sources': [
- "cross/base64_test.cc",
- "cross/dataurl_test.cc",
- "cross/file_path_utils_test.cc",
- "cross/file_text_reader_test.cc",
- "cross/json_writer_test.cc",
- "cross/string_reader_test.cc",
- "cross/string_writer_test.cc",
- "cross/temporary_file_test.cc",
- ],
- },
- },
- ],
-}
-
-# Local Variables:
-# tab-width:2
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=2 shiftwidth=2: